Files
artcraft/models/tts/NeMo/tutorials/01_NeMo_Models.ipynb
T

102 KiB

In [ ]:
"""
You can run either this notebook locally (if you have all the dependencies and a GPU) or on Google Colab.

Instructions for setting up Colab are as follows:
1. Open a new Python 3 notebook.
2. Import this notebook from GitHub (File -> Upload Notebook -> "GITHUB" tab -> copy/paste GitHub URL)
3. Connect to an instance with a GPU (Runtime -> Change runtime type -> select "GPU" for hardware accelerator)
4. Run this cell to set up dependencies.
"""
# If you're using Google Colab and not running locally, run this cell.

## Install dependencies
!pip install wget
!apt-get install sox libsndfile1 ffmpeg
!pip install unidecode

# ## Install NeMo
BRANCH = 'v1.0.2'
!python -m pip install git+https://github.com/NVIDIA/NeMo.git@$BRANCH#egg=nemo_toolkit[all]

## Install TorchAudio
!pip install torchaudio>=0.6.0 -f https://download.pytorch.org/whl/torch_stable.html

## Grab the config we'll use in this example
!mkdir configs

minGPT License

This notebook port's the minGPT codebase into equivalent NeMo code. The license for minGPT has therefore been attached here.

The MIT License (MIT) Copyright (c) 2020 Andrej Karpathy

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

torch-rnn License

This notebook utilizes the tiny-shakespeare dataset from the torch-rnn codebase. The license for torch-rnn has therefore been attached here.

The MIT License (MIT)

Copyright (c) 2016 Justin Johnson

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Note: This notebook will intentionally introduce some errors to show the power of Neural Types or model development concepts, inside the cells marked with [ERROR CELL]. The explanation of and resolution of such errors can be found in the subsequent cells.


The NeMo Model

NeMo comes with several state-of-the-art pre-trained Conversational AI models for users to quickly be able to start training and fine-tuning on their own datasets.

In the previous NeMo Primer notebook, we learned how to download pretrained checkpoints with NeMo and we also discussed the fundamental concepts of the NeMo Model. The previous tutorial showed us how to use, modify, save, and restore NeMo Models.

In this tutorial we will learn how to develop a non-trivial NeMo model from scratch. This helps us to understand the underlying components and how they interact with the overall PyTorch ecosystem.


At the heart of NeMo lies the concept of the "Model". For NeMo developers, a "Model" is the neural network(s) as well as all the infrastructure supporting those network(s), wrapped into a singular, cohesive unit. As such, most NeMo models are constructed to contain the following out of the box (note: some NeMo models support additional functionality specific to the domain/use case!) -

  • Neural Network architecture - all of the modules that are required for the model.

  • Dataset + Data Loaders - all of the components that prepare the data for consumption during training or evaluation.

  • Preprocessing + Postprocessing - any of the components that process the datasets so the modules can easily consume them.

  • Optimizer + Schedulers - basic defaults that work out of the box and allow further experimentation with ease.

  • Any other supporting infrastructure - tokenizers, language model configuration, data augmentation, etc.

Constructing a NeMo Model

NeMo "Models" are comprised of a few key components, so let's tackle them one by one. We will attempt to go in the order that's stated above.

To make this slightly challenging, let's port a model from the NLP domain this time. Transformers are all the rage, with BERT and his friends from Sesame Street forming the core infrastructure for many NLP tasks.

An excellent (yet simple) implementation of one such model - GPT - can be found in the minGPT repository - https://github.com/karpathy/minGPT. While the script is short, it explains and succinctly explores all of the core components we expect in a NeMo model, so it's a prime candidate for NeMo! Sidenote: NeMo supports GPT in its NLP collection, and as such, this notebook aims to be an in-depth development walkthrough for such models.

In the following notebook, we will attempt to port minGPT to NeMo, and along the way, discuss some core concepts of NeMo itself.

Constructing the Neural Network Architecture

First, on the list - the neural network that forms the backbone of the NeMo Model.

So how do we create such a model? Using PyTorch! As you'll see below, NeMo components are compatible with all of PyTorch, so you can augment your workflow without ever losing the flexibility of PyTorch itself!

Let's start with a couple of imports -

In [ ]:
import torch
import nemo
from nemo.core import NeuralModule
from nemo.core import typecheck

Neural Module

Wait, what's NeuralModule? Where is the wonderful torch.nn.Module?

NeuralModule is a subclass of torch.nn.Module, and it brings with it a few additional functionalities.

In addition to being a torch.nn.Module, thereby being entirely compatible with the PyTorch ecosystem, it has the following capabilities -

  1. Typing - It adds support for Neural Type Checking to the model. Typing is optional but quite useful, as we will discuss below!

  2. Serialization - Remember the OmegaConf config dict and YAML config files? Well, all NeuralModules inherently supports serialization/deserialization from such config dictionaries!

  3. FileIO - This is another entirely optional file serialization system. Does your NeuralModule require some way to preserve data that can't be saved into a PyTorch checkpoint? Write your serialization and deserialization logic in two handy methods! Note: When you create the final NeMo Model, this will be implemented for you! Automatic serialization and deserialization support of NeMo models!

In [ ]:
class MyEmptyModule(NeuralModule):

  def forward(self):
    print("Neural Module ~ hello world!")
In [ ]:
x = MyEmptyModule()
x()

Neural Types

Neural Types? You might be wondering what that term refers to.

Almost all NeMo components inherit the class Typing. Typing is a simple class that adds two properties to the class that inherits it - input_types and output_types. A NeuralType, by its shortest definition, is simply a semantic tensor. It contains information regarding the semantic shape the tensor should hold, as well as the semantic information of what that tensor represents. That's it.

So what semantic information does such a typed tensor contain? Let's take an example below.


Across the Deep Learning domain, we often encounter cases where tensor shapes may match, but the semantics don't match at all. For example take a look at the following rank 3 tensors -

In [ ]:
# Case 1:
embedding = torch.nn.Embedding(num_embeddings=10, embedding_dim=30)
x = torch.randint(high=10, size=(1, 5))
print("x :", x)
print("embedding(x) :", embedding(x).shape)
In [ ]:
# Case 2
lstm = torch.nn.LSTM(1, 30, batch_first=True)
x = torch.randn(1, 5, 1)
print("x :", x)
print("lstm(x) :", lstm(x)[0].shape)  # Let's take all timestep outputs of the LSTM

As you can see, the output of Case 1 is an embedding of shape [1, 5, 30], and the output of Case 2 is an LSTM output (state h over all time steps), also of the same shape [1, 5, 30].

Do they have the same shape? Yes.
If we do a Case 1 .shape == Case 2 .shape, will we get True as an output? Yes.
Do they represent the same concept? No.

The ability to recognize that the two tensors do not represent the same semantic information is precisely why we utilize Neural Types. It contains the information of both the shape and the semantic concept of what that tensor represents. If we performed a neural type check between the two outputs of those tensors, it would raise an error saying semantically they were different things (more technically, it would say that they are INCOMPATIBLE with each other)!


You may have read of concepts such as Named Tensors. While conceptually similar, Neural Types attached by NeMo are not as tightly bound to the PyTorch ecosystem - practically any object of a class can be attached with a neural type!

Neural Types - Usage

Neural Types sound interesting, so how do we go about adding them? Let's take a few cases below.

Neural Types are one of the core foundations of NeMo - you will find them in a vast majority of Neural Modules, and every NeMo Model will have its Neural Types defined. While they are entirely optional and not intrusive, NeMo takes great care to support it so that there is no semantic incompatibility between components being used by users.

Let's start with a basic example of a type checked module.

In [ ]:
from nemo.core.neural_types import NeuralType
from nemo.core.neural_types import *
In [ ]:
class EmbeddingModule(NeuralModule):
  def __init__(self):
    super().__init__()
    self.embedding = torch.nn.Embedding(num_embeddings=10, embedding_dim=30)

  @typecheck()
  def forward(self, x):
    return self.embedding(x)

  @property
  def input_types(self):
    return {
        'x': NeuralType(axes=('B', 'T'), elements_type=Index())
    }

  @property
  def output_types(self):
    return {
        'y': NeuralType(axes=('B', 'T', 'C'), elements_type=EmbeddedTextType())
    }

To show the benefit of Neural Types, we are going to replicate the above cases inside NeuralModules.

Let's discuss how we added type checking support to the above class.

  1. forward has a decorator @typecheck() on it.

  2. input_types and output_types properties are defined.

That's it!


Let's expand on each of the above steps.

  • @typecheck() is a simple decorator that takes any class that inherits Typing (NeuralModule does this for us) and adds the two default properties of input_types and output_types, which by default returns None.

The @typecheck() decorator's explicit use ensures that, by default, neural type checking is disabled. NeMo does not wish to intrude on the development process of models. So users can "opt-in" to type checking by overriding the two properties. Therefore, the decorator ensures that users are not burdened with type checking before they wish to have it.

So what is @typecheck()? Simply put, you can wrap any function of a class that inherits Typing with this decorator, and it will look up the definition of the types of that class and enforce them. Typically, torch.nn.Module subclasses only implement forward() so it is most common to wrap that method, but @typecheck() is a very flexible decorator. Inside NeMo, we will show some advanced use cases (which are quite crucial to particular domains such as TTS).


As we see above, @typecheck() enforces the types. How then, do we provide this type of information to NeMo?

By overriding input_types and output_types properties of the class, we can return a dictionary mapping a string name to a NeuralType.

In the above case, we define a NeuralType as two components -

  • axes: This is the semantic information of the carried by the axes themselves. The most common axes information is from single character notation.

B = Batch
C / D - Channel / Dimension (treated the same)
T - Time
H / W - Height / Width

  • elements_type: This is the semantic information of "what the tensor represents". All such types are derived from the basic ElementType, and merely subclassing ElementType allows us to build a hierarchy of custom semantic types that can be used by NeMo!

Here, we declare that the input is an element_type of Index (index of the character in the vocabulary) and that the output is an element_type of EmbeddedTextType (the text embedding)

In [ ]:
embedding_module = EmbeddingModule()

Now let's construct the equivalent of the Case 2 above, but as a NeuralModule.

In [ ]:
class LSTMModule(NeuralModule):
  def __init__(self):
    super().__init__()
    self.lstm = torch.nn.LSTM(1, 30, batch_first=True)

  @typecheck()
  def forward(self, x):
    return self.lstm(x)

  @property
  def input_types(self):
    return {
        'x': NeuralType(axes=('B', 'T', 'C'), elements_type=SpectrogramType())
    }

  @property
  def output_types(self):
    return {
        'y': NeuralType(axes=('B', 'T', 'C'), elements_type=EncodedRepresentation())
    }

Here, we define the LSTM module from the Case 2 above.

We changed the input to be a rank three tensor, now representing a "SpectrogramType". We intentionally keep it generic - it can be a MelSpectrogramType or a MFCCSpectrogramType as its input!

The output of an LSTM is now an EncodedRepresentation. Practically, this can be the output of a CNN layer, a Transformer block, or in this case, an LSTM layer. We can, of course, specialize by subclassing EncodedRepresentation and then using that!

In [ ]:
lstm_module = LSTMModule()

Now for the test !

In [ ]:
# Case 1 [ERROR CELL]
x1 = torch.randint(high=10, size=(1, 5))
print("x :", x1)
print("embedding(x) :", embedding_module(x1).shape)

You might be wondering why we get a TypeError right off the bat. This TypeError is raised by design.

Positional arguments can cause significant issues during model development, mostly when the model/module design is not finalized. To reduce the potential for mistakes caused by wrong positional arguments and enforce the name of arguments provided to the function, Typing requires you to call all of your type-checked functions by kwargs only.

In [ ]:
# Case 1
print("x :", x1)
print("embedding(x) :", embedding_module(x=x1).shape)

Now let's try the same for the LSTMModule in Case 2

In [ ]:
# Case 2 [ERROR CELL]
x2 = torch.randn(1, 5, 1)  # Input = [B=1, T=5, C=1]
print("x :", x2)
print("lstm(x) :", lstm_module(x=x2)[0].shape)  # Let's take all timestep outputs of the LSTM

Now we get a type error stating that the number of output arguments provided does not match what is expected.

What exactly is going on here? Well, inside our LSTMModule class, we declare the output types to be a single NeuralType - an EncodedRepresentation of shape [B, T, C].

But the output of an LSTM layer is a tuple of

  1. the encoded representation of shape [B, T, C]
  2. another tuple containing two state values - the hidden state h and the cell state c, each of shape [num_layers * num_directions, B, C]!

So the neural type system raises an error saying that the number of output arguments does not match what is expected.

NOTE: The axis kind information of the two states will be represented by D to represent a general "Dimension" - since num_layers and num_directions are collapsed under a single axis. For NeMo, Axis types of C and D are equivalent and can be interchanged, so we will use C here to represent the hidden dimension of the LSTM and D to represent the merged axis num_layers * num_directions.

Let's fix the above.

In [ ]:
class CorrectLSTMModule(LSTMModule):  # Let's inherit the wrong class to make it easy to override
  @property
  def output_types(self):
    return {
        'y': NeuralType(axes=('B', 'T', 'C'), elements_type=EncodedRepresentation()),
        'h_c': [NeuralType(axes=('D', 'B', 'C'), elements_type=EncodedRepresentation())],
    }

You should note that for the h_c neural type, we wrap it in a list - []. NeMo, by default, assumes that each NeuralType corresponds to a single returned value. However, in the case of LSTMs, they produce a tuple of two state tensors.

So we inform NeMo that this particular NeuralType is a single-dimensional list of items - and that each element of this list shares the same NeuralType and has the same shape.

NeMo then ensures that the h_c is always a list of tensors. It will not check how many items are in the list, but will ensure that the returned value must be a list containing zero or more items - and that each of these items share the same NeuralType.

In [ ]:
lstm_module = CorrectLSTMModule()
In [ ]:
# Case 2
x2 = torch.randn(1, 5, 1)
y2, (h, c) = lstm_module(x=x2)
print("x :", x2)
print("lstm(x) :", y2.shape)  # The output of the LSTM RNN
print("hidden state (h) :", h.shape)  # The first hidden state of the LSTM RNN
print("hidden state (c) :", c.shape)  # The second hidden state of the LSTM RNN

Great! So now, the type checking system is happy.

If you looked closely, the outputs were ordinary Torch Tensors (this is good news; we don't want to be incompatible with torch Tensors after all!). So, where exactly is the type of information stored?

When the output_types is overridden, and valid torch tensors are returned as a result, these tensors are attached with the attribute neural_type. Let's inspect this -

In [ ]:
emb_out = embedding_module(x=x1)
lstm_out = lstm_module(x=x2)[0]

assert hasattr(emb_out, 'neural_type')
assert hasattr(lstm_out, 'neural_type')
In [ ]:
print("Embedding tensor :", emb_out.neural_type)
print("LSTM tensor :", lstm_out.neural_type)

So we see that these tensors now have this attribute called neural_type and are the same shape.

This exercise's entire goal was to assert that the two outputs are semantically not the same object, even if they are the same shape.

Let's test this!

In [ ]:
emb_out.neural_type.compare(lstm_out.neural_type)
In [ ]:
emb_out.neural_type == lstm_out.neural_type

Neural Types - Limitations

You might have noticed one interesting fact - our inputs were just torch.Tensor to both typed function calls, and they had no neural_type assigned to them.

So why did the type check system not raise any error?

This is to maintain compatibility - type checking is meant to work on a chain of function calls - and each of these functions should themselves be wrapped with the @typecheck() decorator. This is also done because we don't want to overtax the forward call with dozens of checks, and therefore we only type modules that perform some higher-order logical computation.


As an example, it is mostly unnecessary (but still possible) to type the input and output of every residual block of a ResNet model. However, it is practically important to type the encoder (no matter how many layers is inside it) and the decoder (the classification head) separately so that when one does fine-tuning, there is no semantic mismatch of the tensors input to the encoder and bound to the decoder.


For this case, since it would be impractical to extend a class to attach a type to the input tensor, we can take a shortcut and directly attach the neural type to the input!

In [ ]:
embedding_module = EmbeddingModule()
x1 = torch.randint(high=10, size=(1, 5))

# Attach correct neural type
x1.neural_type = NeuralType(('B', 'T'), Index())

print("embedding(x) :", embedding_module(x=x1).shape)
In [ ]:
# Attach wrong neural type [ERROR CELL]
x1.neural_type = NeuralType(('B', 'T'), LabelsType())

print("embedding(x) :", embedding_module(x=x1).shape)

Let's create the minGPT components

Now that we have a somewhat firm grasp of neural type checking, let's begin porting the minGPT example code. Once again, most of the code will be a direct port from the minGPT repository.

Here, you will notice one thing. By just changing class imports, one @typecheck() on forward, and adding input_types and output_types (which are also entirely optional!), we are almost entirely done with the PyTorch Lightning port!

In [ ]:
import math
from typing import List, Set, Dict, Tuple, Optional

import torch
import torch.nn as nn
from torch.nn import functional as F

Creating Element Types

Till now, we have used the Neural Types provided by the NeMo core. But we need not be restricted to the pre-defined element types !

Users have total flexibility in defining any hierarchy of element types as they please!

In [ ]:
class AttentionType(EncodedRepresentation):
  """Basic Attention Element Type"""

class SelfAttentionType(AttentionType):
  """Self Attention Element Type"""

class CausalSelfAttentionType(SelfAttentionType):
  """Causal Self Attention Element Type"""

Creating the modules

Neural Modules are generally top-level modules but can be used at any level of the module hierarchy.

For demonstration, we will treat an encoder comprising a block of Causal Self Attention modules as a typed Neural Module. Of course, we can also treat each Causal Self Attention layer itself as a neural module if we require it, but top-level modules are generally preferred.

In [ ]:
class CausalSelfAttention(nn.Module):
    """
    A vanilla multi-head masked self-attention layer with a projection at the end.
    It is possible to use torch.nn.MultiheadAttention here but I am including an
    explicit implementation here to show that there is nothing too scary here.
    """

    def __init__(self, n_embd, block_size, n_head, attn_pdrop, resid_pdrop):
        super().__init__()
        assert n_embd % n_head == 0
        self.n_head = n_head
        # key, query, value projections for all heads
        self.key = nn.Linear(n_embd, n_embd)
        self.query = nn.Linear(n_embd, n_embd)
        self.value = nn.Linear(n_embd, n_embd)
        # regularization
        self.attn_drop = nn.Dropout(attn_pdrop)
        self.resid_drop = nn.Dropout(resid_pdrop)
        # output projection
        self.proj = nn.Linear(n_embd, n_embd)
        # causal mask to ensure that attention is only applied to the left in the input sequence
        self.register_buffer("mask", torch.tril(torch.ones(block_size, block_size))
                                     .view(1, 1, block_size, block_size))
    def forward(self, x, layer_past=None):
        B, T, C = x.size()

        # calculate query, key, values for all heads in batch and move head forward to be the batch dim
        k = self.key(x).view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
        q = self.query(x).view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
        v = self.value(x).view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)

        # causal self-attention; Self-attend: (B, nh, T, hs) x (B, nh, hs, T) -> (B, nh, T, T)
        att = (q @ k.transpose(-2, -1)) * (1.0 / math.sqrt(k.size(-1)))
        att = att.masked_fill(self.mask[:,:,:T,:T] == 0, float('-inf'))
        att = F.softmax(att, dim=-1)
        att = self.attn_drop(att)
        y = att @ v # (B, nh, T, T) x (B, nh, T, hs) -> (B, nh, T, hs)
        y = y.transpose(1, 2).contiguous().view(B, T, C) # re-assemble all head outputs side by side

        # output projection
        y = self.resid_drop(self.proj(y))
        return y
    

class Block(nn.Module):
    """ an unassuming Transformer block """

    def __init__(self, n_embd, block_size, n_head, attn_pdrop, resid_pdrop):
        super().__init__()
        self.ln1 = nn.LayerNorm(n_embd)
        self.ln2 = nn.LayerNorm(n_embd)
        self.attn = CausalSelfAttention(n_embd, block_size, n_head, attn_pdrop, resid_pdrop)
        self.mlp = nn.Sequential(
            nn.Linear(n_embd, 4 * n_embd),
            nn.GELU(),
            nn.Linear(4 * n_embd, n_embd),
            nn.Dropout(resid_pdrop),
        )

    def forward(self, x):
        x = x + self.attn(self.ln1(x))
        x = x + self.mlp(self.ln2(x))
        return x

Building the NeMo Model

Since a NeMo Model is comprised of various parts, we are going to iterate on the model step by step inside this notebook. As such, we will have multiple intermediate NeMo "Models", which will be partial implementations, and they will inherit each other iteratively.

In a complete implementation of a NeMo Model (as found in the NeMo collections), all of these components will generally be found in a single class.

Let's start by inheriting ModelPT - the core class of a PyTorch NeMo Model, which inherits the PyTorch Lightning Module.


Remember:

  • The NeMo equivalent of torch.nn.Module is the `NeuralModule.
  • The NeMo equivalent of the LightningModule is ModelPT.
In [ ]:
import pytorch_lightning as ptl
from nemo.core import ModelPT
from omegaconf import OmegaConf

Next, let's construct the bare minimum implementation of the NeMo Model - just the constructor, the initializer of weights, and the forward method.

Initially, we will follow the steps followed by the minGPT implementation, and progressively refactor for NeMo

In [ ]:
class PTLGPT(ptl.LightningModule):
  def __init__(self,
                 # model definition args
                 vocab_size: int, # size of the vocabulary (number of possible tokens)
                 block_size: int, # length of the model's context window in time
                 n_layer: int, # depth of the model; number of Transformer blocks in sequence
                 n_embd: int, # the "width" of the model, number of channels in each Transformer
                 n_head: int, # number of heads in each multi-head attention inside each Transformer block
                 # model optimization args
                 learning_rate: float = 3e-4, # the base learning rate of the model
                 weight_decay: float = 0.1, # amount of regularizing L2 weight decay on MatMul ops
                 betas: Tuple[float, float] = (0.9, 0.95), # momentum terms (betas) for the Adam optimizer
                 embd_pdrop: float = 0.1, # \in [0,1]: amount of dropout on input embeddings
                 resid_pdrop: float = 0.1, # \in [0,1]: amount of dropout in each residual connection
                 attn_pdrop: float = 0.1, # \in [0,1]: amount of dropout on the attention matrix
                 ):
        super().__init__()

        # save these for optimizer init later
        self.learning_rate = learning_rate
        self.weight_decay = weight_decay
        self.betas = betas

        # input embedding stem: drop(content + position)
        self.tok_emb = nn.Embedding(vocab_size, n_embd)
        self.pos_emb = nn.Parameter(torch.zeros(1, block_size, n_embd))
        self.drop = nn.Dropout(embd_pdrop)
        # deep transformer: just a sequence of transformer blocks
        self.blocks = nn.Sequential(*[Block(n_embd, block_size, n_head, attn_pdrop, resid_pdrop) for _ in range(n_layer)])
        # decoder: at the end one more layernorm and decode the answers
        self.ln_f = nn.LayerNorm(n_embd)
        self.head = nn.Linear(n_embd, vocab_size, bias=False) # no need for extra bias due to one in ln_f

        self.block_size = block_size
        self.apply(self._init_weights)

        print("number of parameters: %e" % sum(p.numel() for p in self.parameters()))

  def forward(self, idx):
      b, t = idx.size()
      assert t <= self.block_size, "Cannot forward, model block size is exhausted."

      # forward the GPT model
      token_embeddings = self.tok_emb(idx) # each index maps to a (learnable) vector
      position_embeddings = self.pos_emb[:, :t, :] # each position maps to a (learnable) vector
      x = self.drop(token_embeddings + position_embeddings)
      x = self.blocks(x)
      x = self.ln_f(x)
      logits = self.head(x)

      return logits

  def get_block_size(self):
      return self.block_size

  def _init_weights(self, module):
      """
      Vanilla model initialization:
      - all MatMul weights \in N(0, 0.02) and biases to zero
      - all LayerNorm post-normalization scaling set to identity, so weight=1, bias=0
      """
      if isinstance(module, (nn.Linear, nn.Embedding)):
          module.weight.data.normal_(mean=0.0, std=0.02)
          if isinstance(module, nn.Linear) and module.bias is not None:
              module.bias.data.zero_()
      elif isinstance(module, nn.LayerNorm):
          module.bias.data.zero_()
          module.weight.data.fill_(1.0)

Let's create a PyTorch Lightning Model above, just to make sure it works !

In [ ]:
m = PTLGPT(vocab_size=100, block_size=32, n_layer=1, n_embd=32, n_head=4)

Now, let's convert the above easily into a NeMo Model.

A NeMo Model constructor generally accepts only two things -

  1. cfg: An OmegaConf DictConfig object that defines precisely the components required by the model to define its neural network architecture, data loader setup, optimizer setup, and any additional components needed for the model itself.

  2. trainer: An optional Trainer from PyTorch Lightning if the NeMo model will be used for training. It can be set after construction (if required) using the set_trainer method. For this notebook, we will not be constructing the config for the Trainer object.

Refactoring Neural Modules

As we discussed above, Neural Modules are generally higher-level components of the Model and can potentially be replaced by equivalent Neural Modules.

As we see above, the embedding modules, deep transformer decoder network, and final decoder layer have all been combined inside the PyTorch Lightning implementation constructor.


However, the final decoder module could have been an RNN instead of a simple Linear layer, or it could have been a 1D-CNN instead.

Likewise, the deep transformer decoder could potentially have a different implementation of Self Attention modules.

These changes cannot be easily implemented any more inside the above implementation. However, if we refactor these components into their respective NeuralModules, then we can easily replace them with equivalent modules we construct in the future!

Refactoring the Embedding module

Let's first refactor out the embedding module from the above implementation

In [ ]:
class GPTEmbedding(NeuralModule):
  def __init__(self, vocab_size: int, n_embd: int, block_size: int, embd_pdrop: float = 0.0):
    super().__init__()

    # input embedding stem: drop(content + position)
    self.tok_emb = nn.Embedding(vocab_size, n_embd)
    self.pos_emb = nn.Parameter(torch.zeros(1, block_size, n_embd))
    self.drop = nn.Dropout(embd_pdrop)

  @typecheck()
  def forward(self, idx):
    b, t = idx.size()
    
    # forward the GPT model
    token_embeddings = self.tok_emb(idx) # each index maps to a (learnable) vector
    position_embeddings = self.pos_emb[:, :t, :] # each position maps to a (learnable) vector
    x = self.drop(token_embeddings + position_embeddings)
    return x

  @property
  def input_types(self):
    return {
        'idx': NeuralType(('B', 'T'), Index())
    }

  @property
  def output_types(self):
    return {
        'embeddings': NeuralType(('B', 'T', 'C'), EmbeddedTextType())
    }

Refactoring the Encoder

Next, let's refactor the GPT Encoder - which is implemented as a multi layer Transformer (Decoder) network.


It can be noted that we refer to the GPT "Encoder" module - but it is constructed by using Transformer "Decoder" blocks.

When we discuss Neural Modules - we are discussing an abstract module with a certain input neural type and a certain output neural type.

For us, the GPT "Encoder" neural module will accept any implementation, whose

  • input neural type is NeuralType(('B', 'T', 'C'), EmbeddedTextType())

  • output type is NeuralType(('B', 'T', 'C'), EncodedRepresentation())


One concrete implementation of such a GPT "Encoder" neural module is a Deep Transformer "Decoder" network.

In [ ]:
class GPTTransformerEncoder(NeuralModule):
  def __init__(self, n_embd: int, block_size: int, n_head: int, n_layer: int, attn_pdrop: float = 0.0, resid_pdrop: float = 0.0):
    super().__init__()

    self.blocks = nn.Sequential(*[Block(n_embd, block_size, n_head, attn_pdrop, resid_pdrop) 
                                  for _ in range(n_layer)])
    
  @typecheck()
  def forward(self, embed):
    return self.blocks(embed)

  @property
  def input_types(self):
    return {
        'embed': NeuralType(('B', 'T', 'C'), EmbeddedTextType())
    }

  @property
  def output_types(self):
    return {
        'encoding': NeuralType(('B', 'T', 'C'), CausalSelfAttentionType())
    }

Refactoring the Decoder

Finally, let's refactor the Decoder - the small one-layer feed-forward network to decode the answer.


Note an interesting detail - The input_types of the Decoder accepts the generic EncoderRepresentation(), where as the neural_type of the GPTTransformerEncoder has the output_type of CausalSelfAttentionType.

This is semantically not a mismatch! As you can see above in the inheritance chart, we declare EncodedRepresentation -> AttentionType -> SelfAttentionType -> CausalSelfAttentionType.

Such an inheritance hierarchy for the element_type allows future encoders (which also have a neural output type of at least EncodedRepresentation) to be swapped in place of the current GPT Causal Self Attention Encoder while keeping the rest of the NeMo model working just fine!

In [ ]:
class GPTDecoder(NeuralModule):
  def __init__(self, n_embd: int, vocab_size: int):
    super().__init__()
    self.ln_f = nn.LayerNorm(n_embd)
    self.head = nn.Linear(n_embd, vocab_size, bias=False) # no need for extra bias due to one in ln_f

  @typecheck()
  def forward(self, encoding):
    x = self.ln_f(encoding)
    logits = self.head(x)
    return logits

  @property
  def input_types(self):
    return {
        'encoding': NeuralType(('B', 'T', 'C'), EncodedRepresentation())
    }
  
  @property
  def output_types(self):
    return {
        'logits': NeuralType(('B', 'T', 'C'), LogitsType())
    }

Refactoring the NeMo GPT Model

Now that we have 3 NeuralModules for the embedding, the encoder, and the decoder, let's refactor the NeMo model to take advantage of this refactor!

This time, we inherit from ModelPT instead of the general LightningModule.

In [ ]:
class AbstractNeMoGPT(ModelPT):
  def __init__(self, cfg: OmegaConf, trainer: ptl.Trainer = None):
      super().__init__(cfg=cfg, trainer=trainer)

      # input embedding stem: drop(content + position)
      self.embedding = self.from_config_dict(self.cfg.embedding)
      # deep transformer: just a sequence of transformer blocks
      self.encoder = self.from_config_dict(self.cfg.encoder)
      # decoder: at the end one more layernorm and decode the answers
      self.decoder = self.from_config_dict(self.cfg.decoder)

      self.block_size = self.cfg.embedding.block_size
      self.apply(self._init_weights)

      print("number of parameters: %e" % self.num_weights)

  @typecheck()
  def forward(self, idx):
      b, t = idx.size()
      assert t <= self.block_size, "Cannot forward, model block size is exhausted."

      # forward the GPT model
      # Remember: Only kwargs are allowed !
      e = self.embedding(idx=idx)
      x = self.encoder(embed=e)
      logits = self.decoder(encoding=x)

      return logits

  def get_block_size(self):
      return self.block_size

  def _init_weights(self, module):
      """
      Vanilla model initialization:
      - all MatMul weights \in N(0, 0.02) and biases to zero
      - all LayerNorm post-normalization scaling set to identity, so weight=1, bias=0
      """
      if isinstance(module, (nn.Linear, nn.Embedding)):
          module.weight.data.normal_(mean=0.0, std=0.02)
          if isinstance(module, nn.Linear) and module.bias is not None:
              module.bias.data.zero_()
      elif isinstance(module, nn.LayerNorm):
          module.bias.data.zero_()
          module.weight.data.fill_(1.0)

  @property
  def input_types(self):
    return {
        'idx': NeuralType(('B', 'T'), Index())
    }

  @property
  def output_types(self):
    return {
        'logits': NeuralType(('B', 'T', 'C'), LogitsType())
    }

Creating a config for a Model

At first glance, not much changed compared to the PyTorch Lightning implementation above. Other than the constructor, which now accepts a config, nothing changed at all!

NeMo operates on the concept of a NeMo Model being accompanied by a corresponding config dict (instantiated as an OmegaConf object). This enables us to prototype the model by utilizing Hydra rapidly. This includes various other benefits - such as hyperparameter optimization and serialization/deserialization of NeMo models.

Let's look at how actually to construct such config objects!

In [ ]:
# model definition args (required)
# ================================
# vocab_size: int # size of the vocabulary (number of possible tokens)
# block_size: int # length of the model's context window in time
# n_layer: int # depth of the model; number of Transformer blocks in sequence
# n_embd: int # the "width" of the model, number of channels in each Transformer
# n_head: int # number of heads in each multi-head attention inside each Transformer block  

# model definition args (optional)
# ================================
# embd_pdrop: float = 0.1, # \in [0,1]: amount of dropout on input embeddings
# resid_pdrop: float = 0.1, # \in [0,1]: amount of dropout in each residual connection
# attn_pdrop: float = 0.1, # \in [0,1]: amount of dropout on the attention matrix

As we look at the required parameters above, we need a way to tell OmegaConf that these values are currently not set, but the user should set them before we use them.

OmegaConf supports such behavior using the MISSING value. A similar effect can be achieved in YAML configs by using ??? as a placeholder.

In [ ]:
from omegaconf import MISSING
In [ ]:
# Let's create a utility for building the class path
def get_class_path(cls):
  return f'{cls.__module__}.{cls.__name__}'

Structure of a Model config

Let's first create a config for the common components of the model level config -

In [ ]:
common_config = OmegaConf.create({
    'vocab_size': MISSING,
    'block_size': MISSING,
    'n_layer': MISSING,
    'n_embd': MISSING,
    'n_head': MISSING,
})

The model config right now is still being built - it needs to contain a lot more details!

A complete Model Config should have the sub-configs of all of its top-level modules as well. This means the configs of the embedding, encoder, and the decoder.

Structure of sub-module config

For top-level models, we generally don't change the actual module very often, and instead, primarily change the hyperparameters of that model.

So we will make use of Hydra's Class instantiation method - which can easily be accessed via the class method ModelPT.from_config_dict().

Let's take a few examples below -

In [ ]:
embedding_config = OmegaConf.create({
    '_target_': get_class_path(GPTEmbedding),
    'vocab_size': '${model.vocab_size}',
    'n_embd': '${model.n_embd}',
    'block_size': '${model.block_size}',
    'embd_pdrop': 0.1
})

encoder_config = OmegaConf.create({
    '_target_': get_class_path(GPTTransformerEncoder),
    'n_embd': '${model.n_embd}',
    'block_size': '${model.block_size}',
    'n_head': '${model.n_head}',
    'n_layer': '${model.n_layer}',
    'attn_pdrop': 0.1,
    'resid_pdrop': 0.1
})

decoder_config = OmegaConf.create({
    '_target_': get_class_path(GPTDecoder),
    # n_embd: int, vocab_size: int
    'n_embd': '${model.n_embd}',
    'vocab_size': '${model.vocab_size}'
})
What is _target_?

In the above config, we see a _target_ in the config. _target_ is usually a full classpath to the actual class in the python package/user local directory. It is required for Hydra to locate and instantiate the model from its path correctly.

So why do we want to set a classpath?

In general, when developing models, we don't often change the encoder or the decoder, but we do change the hyperparameters of the encoder and decoder.

This notation helps us keep the Model level declaration of the forward step neat and precise. It also logically helps us demark which parts of the model can be easily replaced - in the future, we can easily replace the encoder with some other type of self-attention block or the decoder with an RNN or 1D-CNN neural module (as long as they have the same Neural Type definition as the current blocks).

What is the ${} syntax?

OmegaConf, and by extension, Hydra, supports Variable Interpolation. As you can see in the __init__ of embedding, encoder, and decoder neural modules, they often share many parameters between each other.

It would become tedious and error-prone to set each of these constructors' values separately in each of the embedding, encoder, and decoder configs.

So instead, we define standard keys inside of the model level config and then interpolate these values inside of the respective configs!

Attaching the model and module-level configs

So now, we have a Model level and per-module level configs for the core components. Sub-module configs generally fall under the "model" namespace, but you have the flexibility to define the structure as you require.

Let's attach them!

In [ ]:
model_config = OmegaConf.create({
    'model': common_config
})

# Then let's attach the sub-module configs
model_config.model.embedding = embedding_config
model_config.model.encoder = encoder_config
model_config.model.decoder = decoder_config

Let's print this config!

In [ ]:
print(OmegaConf.to_yaml(model_config))

Wait, why did OmegaConf not fill in the value of the variable interpolation for the configs yet?

This is because OmegaConf takes a deferred approach to variable interpolation. To force it ahead of time, we can use the following snippet -

In [ ]:
temp_config = OmegaConf.create(OmegaConf.to_container(model_config, resolve=True))
print(OmegaConf.to_yaml(temp_config))

Now that we have a config, let's try to create an object of the NeMo Model !

In [ ]:
import copy
In [ ]:
# Let's work on a copy of the model config and update it before we send it into the Model.
cfg = copy.deepcopy(model_config)
In [ ]:
# Let's set the values of the config (for some plausible small model)
cfg.model.vocab_size = 100
cfg.model.block_size = 128
cfg.model.n_layer = 1
cfg.model.n_embd = 32
cfg.model.n_head = 4
In [ ]:
print(OmegaConf.to_yaml(cfg))
In [ ]:
# Try to create a model with this config [ERROR CELL]
m = AbstractNeMoGPT(cfg.model)

You will note that we added the Abstract tag for a reason to this NeMo Model and that when we try to instantiate it - it raises an error that we need to implement specific methods.

  1. setup_training_data & setup_validation_data - All NeMo models should implement two data loaders - the training data loader and the validation data loader. Optionally, they can go one step further and also implement the setup_test_data method to add support for evaluating the Model on its own.

Why do we enforce this? NeMo Models are meant to be a unified, cohesive object containing the details about the neural network underlying that Model and the data loaders to train, validate, and optionally test those models.

In doing so, once the Model is created/deserialized, it would take just a few more steps to train the Model from scratch / fine-tune/evaluate the Model on any data that the user provides, as long as this user-provided dataset is in a format supported by the Dataset / DataLoader that is used by this Model!

  1. list_available_models - This is a utility method to provide a list of pre-trained NeMo models to the user from the cloud.

Typically, NeMo models can be easily packaged into a tar file (which we call a .nemo file in the earlier primer notebook). These tar files contain the model config + the pre-trained checkpoint weights of the Model, and can easily be downloaded from some cloud service.

For this notebook, we will not be implementing this method.


Finally, let's create a concrete implementation of the above NeMo Model!

In [ ]:
from nemo.core.classes.common import PretrainedModelInfo
Warning:
Output truncated. This notebook contains too many cells to display efficiently.