In [1]:
GPT_CONFIG_124M = {
    "vocab_size": 50257,     # Vocabulary size
    "context_length": 1024,  # Context length
    "emb_dim": 768,          # Embedding dimension
    "n_heads": 12,           # Number of attention heads
    "n_layers": 12,          # Number of layers
    "drop_rate": 0.1,        # Dropout rate
    "qkv_bias": False        # Query-Key-Value bias
}

DEBUG = True

def dbg(*args, **kwargs):
    if DEBUG: print(*args, **kwargs)
In [2]:
import torch
import torch.nn as nn
In [3]:
class DummyTransformerBlock(nn.Module):
    def __init__(self, cfg):
        super().__init__()

    def forward(self, X):
        return X
In [4]:
class DummyLayerNorm(nn.Module):
    def __init__(self, normalized_shape, eps=1e-5):
        super().__init__()

    def forward(self, X):
        return X
In [5]:
class DummyGPT(nn.Module):
    def __init__(self, cfg):
        super().__init__()
        self.tok_emb = nn.Embedding(cfg["vocab_size"], cfg["emb_dim"])
        self.pos_emb = nn.Embedding(cfg["context_length"], cfg["emb_dim"])
        self.dropout = nn.Dropout(cfg["drop_rate"])
        self.xform_blocks = nn.Sequential(
            *[DummyTransformerBlock(cfg) for _ in range(cfg["n_layers"])]
        )
        self.final_norm = DummyLayerNorm(cfg["emb_dim"])
        self.out_head = nn.Linear(cfg["emb_dim"], cfg["vocab_size"], bias = False)

    def forward(self, input_tokens):
        dbg("Input shape:", input_tokens.shape)
        
        batch_size, num_tokens = input_tokens.shape
        token_embeds = self.tok_emb(input_tokens)
        dbg("Token embeds:\n", token_embeds)
        
        pos_embeds = self.pos_emb(torch.arange(num_tokens, device=input_tokens.device))
        dbg("Position embeds:\n", pos_embeds)
        
        X = token_embeds + pos_embeds
        dbg("Combined embeds:\n", X)

        X = self.dropout(X)
        X = self.xform_blocks(X)
        X = self.final_norm(X)
        logits = self.out_head(X)
        
        return logits
In [6]:
gpt = DummyGPT(GPT_CONFIG_124M)
input = torch.stack([torch.arange(4) for _ in range(2)])
gpt.forward(input)
Input shape: torch.Size([2, 4])
Token embeds:
 tensor([[[ 0.4023,  0.8857,  0.8581,  ..., -0.3757,  0.3657,  0.1599],
         [ 1.0300,  0.1366, -0.2415,  ...,  0.2170, -0.2039,  1.3761],
         [-0.6201,  0.6362, -0.7190,  ...,  0.8805, -1.0276,  0.6588],
         [-0.8750,  0.5982,  0.8219,  ..., -0.0701,  1.5045, -0.7513]],

        [[ 0.4023,  0.8857,  0.8581,  ..., -0.3757,  0.3657,  0.1599],
         [ 1.0300,  0.1366, -0.2415,  ...,  0.2170, -0.2039,  1.3761],
         [-0.6201,  0.6362, -0.7190,  ...,  0.8805, -1.0276,  0.6588],
         [-0.8750,  0.5982,  0.8219,  ..., -0.0701,  1.5045, -0.7513]]],
       grad_fn=<EmbeddingBackward0>)
Position embeds:
 tensor([[ 1.2036,  0.4807, -0.1925,  ...,  0.4570, -1.0665, -0.7661],
        [ 0.0789,  0.1446,  0.6366,  ...,  1.2646,  1.9790,  0.5499],
        [-1.3648, -0.0904, -1.5379,  ...,  0.6167,  0.9703, -0.4264],
        [ 0.5624,  0.6849, -1.0254,  ...,  0.8100, -0.2039, -0.2021]],
       grad_fn=<EmbeddingBackward0>)
Combined embeds:
 tensor([[[ 1.6060,  1.3664,  0.6656,  ...,  0.0813, -0.7008, -0.6062],
         [ 1.1089,  0.2811,  0.3951,  ...,  1.4815,  1.7751,  1.9259],
         [-1.9849,  0.5458, -2.2570,  ...,  1.4973, -0.0572,  0.2324],
         [-0.3126,  1.2832, -0.2035,  ...,  0.7400,  1.3006, -0.9534]],

        [[ 1.6060,  1.3664,  0.6656,  ...,  0.0813, -0.7008, -0.6062],
         [ 1.1089,  0.2811,  0.3951,  ...,  1.4815,  1.7751,  1.9259],
         [-1.9849,  0.5458, -2.2570,  ...,  1.4973, -0.0572,  0.2324],
         [-0.3126,  1.2832, -0.2035,  ...,  0.7400,  1.3006, -0.9534]]],
       grad_fn=<AddBackward0>)
Out[6]:
tensor([[[ 1.3636,  0.3033, -0.1053,  ...,  0.6030,  1.0600, -0.2486],
         [ 1.2595,  0.6509,  0.7934,  ..., -0.1170,  0.4513, -1.1860],
         [-0.5215, -1.5249, -1.7802,  ...,  0.0226,  0.0309, -0.5734],
         [ 0.0696, -0.1423,  0.8635,  ...,  1.3263, -1.1367, -0.2015]],

        [[ 1.7359,  1.0144, -0.0770,  ...,  0.6755,  1.3236, -0.1445],
         [ 0.8064,  0.5008,  0.3296,  ...,  0.3537,  0.5848, -1.5076],
         [-0.3987, -1.9612, -1.9645,  ...,  0.2650,  0.1417, -1.0769],
         [-0.3253, -0.1121,  1.4003,  ...,  0.6107, -0.7941, -0.0220]]],
       grad_fn=<UnsafeViewBackward0>)
In [7]:
import tiktoken
In [8]:
tokenizer = tiktoken.get_encoding("gpt2")
batch = []
txt1 = "Every effort moves you"
txt2 = "Every day holds a"

batch.append(torch.tensor(tokenizer.encode(txt1)))
batch.append(torch.tensor(tokenizer.encode(txt2)))
batch = torch.stack(batch)
batch
Out[8]:
tensor([[6109, 3626, 6100,  345],
        [6109, 1110, 6622,  257]])
In [9]:
DEBUG = False

torch.manual_seed(123)
model = DummyGPT(GPT_CONFIG_124M)
logits = model.forward(batch)
print("Shape:", logits.shape)
print(logits)
Shape: torch.Size([2, 4, 50257])
tensor([[[-1.2034,  0.3201, -0.7130,  ..., -1.5548, -0.2390, -0.4667],
         [-0.1192,  0.4539, -0.4432,  ...,  0.2392,  1.3469,  1.2430],
         [ 0.5307,  1.6720, -0.4695,  ...,  1.1966,  0.0111,  0.5835],
         [ 0.0139,  1.6754, -0.3388,  ...,  1.1586, -0.0435, -1.0400]],

        [[-1.0908,  0.1798, -0.9484,  ..., -1.6047,  0.2439, -0.4530],
         [-0.7860,  0.5581, -0.0610,  ...,  0.4835, -0.0077,  1.6621],
         [ 0.3567,  1.2698, -0.6398,  ..., -0.0162, -0.1296,  0.3717],
         [-0.2407, -0.7349, -0.5102,  ...,  2.0057, -0.3694,  0.1814]]],
       grad_fn=<UnsafeViewBackward0>)
In [10]:
# Show an example of a neural network layer producing un-normalized output.
torch.manual_seed(123)
batch = torch.randn(2, 5)
layer = nn.Sequential(nn.Linear(5, 6), nn.ReLU())
logits = layer(batch)
logits
Out[10]:
tensor([[0.2260, 0.3470, 0.0000, 0.2216, 0.0000, 0.0000],
        [0.2133, 0.2394, 0.0000, 0.5198, 0.3297, 0.0000]],
       grad_fn=<ReluBackward0>)
In [11]:
logits.mean(dim=-1, keepdim=True)
Out[11]:
tensor([[0.1324],
        [0.2170]], grad_fn=<MeanBackward1>)
In [12]:
logits.var(dim=-1, keepdim=True)
Out[12]:
tensor([[0.0231],
        [0.0398]], grad_fn=<VarBackward0>)
In [13]:
# To normalize we subtract the mean and divide by the square root of the variance.
normed_logits = (logits - logits.mean(dim=-1, keepdim=True)) / logits.var(dim=-1, keepdim=True)**0.5
normed_logits
Out[13]:
tensor([[ 0.6159,  1.4126, -0.8719,  0.5872, -0.8719, -0.8719],
        [-0.0189,  0.1121, -1.0876,  1.5173,  0.5647, -1.0876]],
       grad_fn=<DivBackward0>)
In [14]:
torch.set_printoptions(sci_mode=False) # print near zero as just zero, no scientific notation
normed_logits.mean(dim=-1, keepdim=True)
Out[14]:
tensor([[0.0000],
        [0.0000]], grad_fn=<MeanBackward1>)
In [15]:
normed_logits.var(dim=-1, keepdim=True)
Out[15]:
tensor([[1.0000],
        [1.0000]], grad_fn=<VarBackward0>)
In [16]:
# Create a basic normalization layer.
class LayerNorm(nn.Module):
    def __init__(self, embed_dim):
        super().__init__()
        self.epsilon = 1e-5 # Prevents divide-by-zero errors.

        # These trainable parameters allow the model to scale and
        # shift this layer's output beyond strict normalization if
        # that improves model performance.
        self.scale = nn.Parameter(torch.ones(embed_dim))
        self.shift = nn.Parameter(torch.zeros(embed_dim))

    def forward(self, X):
        mean = X.mean(dim=-1, keepdim=True)

        # We use a biased variance because in practice embedding
        # dimensions are so large that the difference is negligible,
        # plus this ensures compatibility with historical open-weight
        # GPT models.
        var = X.var(dim=-1, keepdim=True, unbiased=False)

        normed_X = (X - mean) / (var**0.5)
        normed_X = normed_X * self.scale + self.shift
        return normed_X
In [17]:
layer_norm = LayerNorm(logits.shape[1])
normed_logits = layer_norm.forward(logits)
normed_logits
Out[17]:
tensor([[ 0.6746,  1.5474, -0.9551,  0.6433, -0.9551, -0.9551],
        [-0.0207,  0.1228, -1.1915,  1.6621,  0.6186, -1.1915]],
       grad_fn=<AddBackward0>)
In [18]:
normed_logits.mean(dim=-1, keepdim=True)
Out[18]:
tensor([[-0.0000],
        [ 0.0000]], grad_fn=<MeanBackward1>)
In [19]:
# Our normalization layer uses a biased variance. If we print
# an *unbiased* variance for our result, we get something weird.
In [20]:
normed_logits.var(dim=-1, keepdim=True) 
Out[20]:
tensor([[1.2000],
        [1.2000]], grad_fn=<VarBackward0>)
In [21]:
# The solution is to print a *biased* variance.
normed_logits.var(dim=-1, unbiased=False, keepdim=True)
Out[21]:
tensor([[1.0000],
        [1.0000]], grad_fn=<VarBackward0>)

Now to implement GELU, which has empirically better properties for LLMs. In practice this is typically implemented with the following approximation:

image.png

In [22]:
class GELU(nn.Module):
    def __init__(self):
        super().__init__()

    def forward(self, X):
        sqrt_2_over_pi = torch.sqrt(torch.tensor(2 / torch.pi))
        result = 0.5 * X * (1 + torch.tanh(sqrt_2_over_pi * (X + 0.044715 * torch.pow(X,3))))
        return result
In [23]:
# Here's GELU in action vs. ReLU.
import matplotlib.pyplot as plt
gelu, relu = GELU(), nn.ReLU()

x = torch.linspace(-3, 3, 100)
y_gelu, y_relu = gelu(x), relu(x)
plt.figure(figsize=(8, 3))
for i, (y, label) in enumerate(zip([y_gelu, y_relu], ["GELU", "ReLU"]), 1):
    plt.subplot(1, 2, i)
    plt.plot(x, y)
    plt.title(f"{label} activation function")
    plt.xlabel("x")
    plt.ylabel(f"{label}(x)")
    plt.grid(True)
plt.tight_layout()
plt.show()
No description has been provided for this image
In [24]:
# Now implement a simple feed forward neural network module. It will use two
# layers separated by GELU, the first layer expanding the embedding dimension by
# a factor of four, and the second layer reducing back down to the original
# embedding dimension.

class FeedForward(nn.Module):
    def __init__(self, cfg):
        super().__init__()
        embed_dim = cfg["emb_dim"]
        embed_dim_x4 = embed_dim * 4
        self.layers = nn.Sequential(
            nn.Linear(embed_dim, embed_dim_x4),
            GELU(),
            nn.Linear(embed_dim_x4, embed_dim)
        )

    def forward(self, X):
        result = self.layers(X)
        return result
In [25]:
ffn = FeedForward(GPT_CONFIG_124M)
batch = torch.randn(2, 3, GPT_CONFIG_124M["emb_dim"])
out = ffn.forward(batch)
out.shape
Out[25]:
torch.Size([2, 3, 768])
In [26]:
# Create an example deep neural network with five layers and GELU activiation,
# plus optional shortcutting: if the dimensions align and shortcutting is enabled,
# the input to the current layer will be added to that layers output before being
# sent to the next layer.
class ExampleDeepNeuralNetwork(nn.Module):
    def __init__(self, layer_dims, use_shortcuts=True):
        super().__init__()
        assert len(layer_dims) == 6, "Must provide 6 layer dimensions."

        self.use_shortcuts = use_shortcuts
        self.layers = nn.ModuleList([
            nn.Sequential(nn.Linear(layer_dims[0], layer_dims[1]), GELU()),
            nn.Sequential(nn.Linear(layer_dims[1], layer_dims[2]), GELU()),
            nn.Sequential(nn.Linear(layer_dims[2], layer_dims[3]), GELU()),
            nn.Sequential(nn.Linear(layer_dims[3], layer_dims[4]), GELU()),
            nn.Sequential(nn.Linear(layer_dims[4], layer_dims[5]), GELU())
        ])

    # Expects a simple vector of inputs and returns a vector of outputs.
    def forward(self, x):
        for layer in self.layers:
            layer_output = layer(x)
            if self.use_shortcuts and x.shape == layer_output.shape:
                x = layer_output + x
            else:
                x = layer_output
        return x
In [27]:
# Initialize a neural network without shortcuts.
layer_dims = [3, 3, 3, 3, 3, 1]
nn_input = torch.tensor([[1., 0., -1.]])
torch.manual_seed(123)
dnn_no_shortcuts = ExampleDeepNeuralNetwork(layer_dims, False)
In [28]:
# Run a neural network, get its loss, print out its gradient.
def print_gradient(model, x):
    output = model(x)
    target = torch.tensor([[0.]])

    loss = nn.MSELoss()
    loss = loss(output, target)
    loss.backward()

    for name, param in model.named_parameters():
        if "weight" in name:
            print(f"{name} has gradient mean:", param.grad.abs().mean().item())
In [29]:
print_gradient(dnn_no_shortcuts, nn_input)
layers.0.0.weight has gradient mean: 0.00020173590746708214
layers.1.0.weight has gradient mean: 0.0001201116101583466
layers.2.0.weight has gradient mean: 0.0007152042235247791
layers.3.0.weight has gradient mean: 0.0013988739810883999
layers.4.0.weight has gradient mean: 0.00504964729771018
In [30]:
# Now compare with shortcuts enabled.
torch.manual_seed(123)
dnn_shortcuts = ExampleDeepNeuralNetwork(layer_dims, True)
print_gradient(dnn_shortcuts, nn_input)
layers.0.0.weight has gradient mean: 0.22169791162014008
layers.1.0.weight has gradient mean: 0.20694102346897125
layers.2.0.weight has gradient mean: 0.32896995544433594
layers.3.0.weight has gradient mean: 0.2665732204914093
layers.4.0.weight has gradient mean: 1.3258541822433472
In [31]:
# This is the multi-head attention module we coded in chapter 3.
class MultiHeadAttention(nn.Module):
    def __init__(self, input_dim, output_dim, context_length, dropout_pct, num_heads, use_bias=False):
        super().__init__()

        assert output_dim % num_heads == 0, "output_dim must be a multiple of num_heads"
        self.num_heads = num_heads
        self.head_dim = output_dim // num_heads
        self.output_dim = output_dim
        
        self.W_q = nn.Linear(input_dim, output_dim, bias=use_bias)
        self.W_k = nn.Linear(input_dim, output_dim, bias=use_bias)
        self.W_v = nn.Linear(input_dim, output_dim, bias=use_bias)
        self.output_proj = nn.Linear(output_dim, output_dim)
        
        self.dropout = torch.nn.Dropout(dropout_pct, inplace=True)
        ones = torch.ones(context_length, context_length)
        self.register_buffer("mask", torch.triu(ones, diagonal=1).bool())

    def forward(self, batch):
        num_samples, num_tokens, token_dim = batch.shape
        queries = self.W_q(batch)
        keys = self.W_k(batch)
        values = self.W_v(batch)

        queries = queries.view(num_samples, num_tokens, self.num_heads, self.head_dim).transpose(1, 2)
        keys = keys.view(num_samples, num_tokens, self.num_heads, self.head_dim).transpose(1, 2)
        values = values.view(num_samples, num_tokens, self.num_heads, self.head_dim).transpose(1, 2)
        
        attn_scores = queries @ keys.transpose(2, 3)
        attn_scores.masked_fill_(self.mask[:num_tokens, :num_tokens], -torch.inf)
        
        attn_weights = torch.softmax(attn_scores / keys.shape[-1]**0.5, dim=-1)
        self.dropout(attn_weights) # Dropout in-place
        
        context_vectors = attn_weights @ values
        context_vectors = context_vectors.transpose(1, 2)
        context_vectors = context_vectors.contiguous().view(num_samples, num_tokens, self.output_dim)
        
        output = self.output_proj(context_vectors)
        return output

Now we will implement a transformer block using the components we've previously authored. It looks something like this:

image.png

In [32]:
class TransformerBlock(nn.Module):
    def __init__(self, config):
        super().__init__()
        self.attention = MultiHeadAttention(
            input_dim      = config["emb_dim"],
            output_dim     = config["emb_dim"],
            context_length = config["context_length"],
            num_heads      = config["n_heads"],
            dropout_pct    = config["drop_rate"],
            use_bias       = config["qkv_bias"]
        )
        self.feed_forward = FeedForward(config)
        self.norm1 = LayerNorm(config["emb_dim"])
        self.norm2 = LayerNorm(config["emb_dim"])
        self.dropout = nn.Dropout(config["drop_rate"])

    def forward(self, batch):
        shortcut = batch
        output = self.norm1(batch)
        output = self.attention(output)
        output = self.dropout(output)
        output = output + shortcut

        shortcut = output
        output = self.norm2(output)
        output = self.feed_forward(output)
        output = self.dropout(output)
        output = output + shortcut

        return output
In [33]:
# Now create and run a transformer block on a random batch of two samples
# with four tokens each and an embedding dimension of 768, then print the input
# and output shapes.
torch.manual_seed(123)
batch = torch.rand([2, 4, 768])
block = TransformerBlock(GPT_CONFIG_124M)
output = block(batch)

print("Input shape:", batch.shape)
print("Output shape:", batch.shape)
Input shape: torch.Size([2, 4, 768])
Output shape: torch.Size([2, 4, 768])
In [34]:
# We can now plug our transformer and layer norm modules into our original
# dummy GPT module to produce a working LLM module in the style of ChatGPT2.

class GPTModel(nn.Module):
    def __init__(self, cfg):
        super().__init__()
        self.tok_emb = nn.Embedding(cfg["vocab_size"], cfg["emb_dim"])
        self.pos_emb = nn.Embedding(cfg["context_length"], cfg["emb_dim"])
        self.dropout = nn.Dropout(cfg["drop_rate"])
        self.xform_blocks = nn.Sequential(
            *[TransformerBlock(cfg) for _ in range(cfg["n_layers"])]
        )
        self.final_norm = LayerNorm(cfg["emb_dim"])
        self.out_head = nn.Linear(cfg["emb_dim"], cfg["vocab_size"], bias = False)

    def forward(self, input_tokens):
        batch_size, num_tokens = input_tokens.shape

        token_embeds = self.tok_emb(input_tokens)
        pos_embeds = self.pos_emb(torch.arange(num_tokens, device=input_tokens.device))
        X = token_embeds + pos_embeds
        X = self.dropout(X)
        X = self.xform_blocks(X)
        X = self.final_norm(X)

        logits = self.out_head(X)
        return logits
In [35]:
# Recreate our example batch.
batch = []
txt1 = "Every effort moves you"
txt2 = "Every day holds a"

batch.append(torch.tensor(tokenizer.encode(txt1)))
batch.append(torch.tensor(tokenizer.encode(txt2)))
batch = torch.stack(batch)
batch
Out[35]:
tensor([[6109, 3626, 6100,  345],
        [6109, 1110, 6622,  257]])
In [36]:
# Now run our GPT model.
torch.manual_seed(123)
model = GPTModel(GPT_CONFIG_124M)
output = model(batch)
print("Batch shape:", batch.shape)
print("Batch:\n", batch)
print("\nOutput shape:", output.shape)
print("Output:\n", output)
Batch shape: torch.Size([2, 4])
Batch:
 tensor([[6109, 3626, 6100,  345],
        [6109, 1110, 6622,  257]])

Output shape: torch.Size([2, 4, 50257])
Output:
 tensor([[[ 0.3613,  0.4222, -0.0711,  ...,  0.3483,  0.4661, -0.2838],
         [-0.1792, -0.5660, -0.9485,  ...,  0.0477,  0.5181, -0.3168],
         [ 0.7120,  0.0332,  0.1085,  ...,  0.1018, -0.4327, -0.2553],
         [-1.0076,  0.3418, -0.1190,  ...,  0.7195,  0.4023,  0.0532]],

        [[-0.2564,  0.0900,  0.0335,  ...,  0.2659,  0.4454, -0.6806],
         [ 0.1230,  0.3653, -0.2074,  ...,  0.7705,  0.2710,  0.2246],
         [ 1.0558,  1.0318, -0.2800,  ...,  0.6936,  0.3205, -0.3178],
         [-0.1565,  0.3926,  0.3288,  ...,  1.2630, -0.1858,  0.0388]]],
       grad_fn=<UnsafeViewBackward0>)
In [37]:
# How many parameters do we have in this model?
total_params = sum(param.numel() for param in model.parameters())
print(f"Total parameters: {total_params:,}")
Total parameters: 163,009,536
In [38]:
print("Token embedding layer:", model.tok_emb.weight.shape)
print("Output layer:", model.out_head.weight.shape)
Token embedding layer: torch.Size([50257, 768])
Output layer: torch.Size([50257, 768])
In [39]:
# Adjust for weight tying: reusing input layer weights in output layer.
total_params_gpt2 = total_params - sum(param.numel() for param in model.out_head.parameters())
print(f"Total parameters with weight tying: {total_params_gpt2:,}")
Total parameters with weight tying: 124,412,160

Exercise 4.1 Number of parameters in feed forward and attention modules¶

Calculate and compare the number of parameters that are contained in the feed forward module and those that are contained in the multi-head attention module.

In [40]:
total_ff_params = 0
total_ff_params_per_block = 0
total_mha_params = 0
total_mha_params_per_block = 0
for block in model.xform_blocks:
    total_ff_params += sum(param.numel() for param in block.feed_forward.parameters())
    if total_ff_params_per_block == 0: total_ff_params_per_block = total_ff_params
    total_mha_params += sum(param.numel() for param in block.attention.parameters())
    if total_mha_params_per_block == 0: total_mha_params_per_block = total_mha_params
print(f"Feed-forward params total / per block: {total_ff_params:,} / {total_ff_params_per_block:,}")
print(f"Multi-head attention params / per block: {total_mha_params:,} / {total_mha_params_per_block:,}")
Feed-forward params total / per block: 56,669,184 / 4,722,432
Multi-head attention params / per block: 28,320,768 / 2,360,064
In [41]:
total_size_bytes = total_params * 4
total_size_mb = total_size_bytes / (1024 * 1024)
print(f"Total size of the model: {total_size_mb:.2f} MB")
Total size of the model: 621.83 MB

Exercise 4.2 Initializing larger GPT models¶

We initialized a 124-million-parameter GPT model, which is known as “GPT-2 small.” Without making any code modifications besides updating the configuration file, use the GPTModel class to implement GPT-2 medium (using 1,024-dimensional embeddings, 24 transformer blocks, 16 multi-head attention heads), GPT-2 large (1,280-dimensional embeddings, 36 transformer blocks, 20 multi-head attention heads), and GPT-2 XL (1,600-dimensional embeddings, 48 transformer blocks, 25 multi-head attention heads). As a bonus, calculate the total number of parameters in each GPT model.

In [42]:
def model_stats(model):
    total_params = sum(param.numel() for param in model.parameters())
    print(f"Total parameters: {total_params:,}")
    total_size_bytes = total_params * 4
    total_size_mb = total_size_bytes / (1024 * 1024)
    print(f"Total size of the model: {total_size_mb:.2f} MB")

GPT_CONFIG_MED = {
    "vocab_size": 50257,     # Vocabulary size
    "context_length": 1024,  # Context length
    "emb_dim": 1024,          # Embedding dimension
    "n_heads": 16,           # Number of attention heads
    "n_layers": 24,          # Number of layers
    "drop_rate": 0.1,        # Dropout rate
    "qkv_bias": False        # Query-Key-Value bias
}
model_med = GPTModel(GPT_CONFIG_MED)
print("MEDIUM")
model_stats(model_med)

GPT_CONFIG_LRG = {
    "vocab_size": 50257,     # Vocabulary size
    "context_length": 1024,  # Context length
    "emb_dim": 1280,          # Embedding dimension
    "n_heads": 20,           # Number of attention heads
    "n_layers": 36,          # Number of layers
    "drop_rate": 0.1,        # Dropout rate
    "qkv_bias": False        # Query-Key-Value bias
}
model_lrg = GPTModel(GPT_CONFIG_LRG)
print("LARGE")
model_stats(model_lrg)

GPT_CONFIG_XL = {
    "vocab_size": 50257,     # Vocabulary size
    "context_length": 1024,  # Context length
    "emb_dim": 1600,          # Embedding dimension
    "n_heads": 25,           # Number of attention heads
    "n_layers": 48,          # Number of layers
    "drop_rate": 0.1,        # Dropout rate
    "qkv_bias": False        # Query-Key-Value bias
}
model_xl = GPTModel(GPT_CONFIG_XL)
print("XL")
model_stats(model_xl)
MEDIUM
Total parameters: 406,212,608
Total size of the model: 1549.58 MB
LARGE
Total parameters: 838,220,800
Total size of the model: 3197.56 MB
XL
Total parameters: 1,637,792,000
Total size of the model: 6247.68 MB
In [43]:
# Now to generate tokens from some input. We take a model, a set of tokens
# in (batch, tokens) shape, the maximum number of new tokens to generate, and the
# maximum context size. We then repeatedly call the model with a batch which grows until
# we've generated our maximum number of new tokens. After each call, we take the last
# token output of each batch, take the softmax, find the index of the maximum value,
# and then grab whatever token that index corresponds to in our tokenizer scheme; we
# append this token to our batch and repeat.

def simple_generator(model, tokens, max_output_tokens, max_context_length):
    for _ in range(max_output_tokens):
        logits = model(tokens)

        # Go from [batch_size, num_tokens, embed_dim] to [batch_size, embed_dim],
        # only retaining the last token from each batch.
        logits = logits[:, -1, :]

        # Determine the next token and append it.
        probas = torch.softmax(logits, dim=-1)
        next_tokens = torch.argmax(probas, dim=-1, keepdim=True)
        tokens = torch.cat([tokens, next_tokens], dim=-1)

        # Crop tokens to maximum context length.
        tokens = tokens[:, -max_context_length:]

    return tokens
In [44]:
start_context = "Hello, I am"
encoded = tokenizer.encode(start_context)
print("encoded:", encoded)
encoded_tensor = torch.tensor(encoded).unsqueeze(0) # unsqueeze adds an initial dimension for batch
print("encoded_tensor.shape:", encoded_tensor.shape)
encoded: [15496, 11, 314, 716]
encoded_tensor.shape: torch.Size([1, 4])
In [45]:
model.eval() # Disable training things like dropout
out = simple_generator(
    model=model,
    tokens=encoded_tensor, 
    max_output_tokens=6, 
    max_context_length=GPT_CONFIG_124M["context_length"]
)
print("Output:", out)
print("Output length:", len(out[0]))
Output: tensor([[15496,    11,   314,   716, 27018, 24086, 47843, 30961, 42348,  7267]])
Output length: 10
In [46]:
# Let's see what we got!
decoded_text = tokenizer.decode(out.squeeze(0).tolist()) # squeeze removes the first "batch" dimension
print(decoded_text)
Hello, I am Featureiman Byeswickattribute argue

Exercise 4.3 Using separate dropout parameters¶

At the beginning of this chapter, we defined a global drop_rate setting in the GPT_ CONFIG_124M dictionary to set the dropout rate in various places throughout the GPTModel architecture. Change the code to specify a separate dropout value for the various dropout layers throughout the model architecture. (Hint: there are three distinct places where we used dropout layers: the embedding layer, shortcut layer, and multi-head attention module.)

In [47]:
GPT_CONFIG_124M = {
    "vocab_size": 50257,     # Vocabulary size
    "context_length": 1024,  # Context length
    "emb_dim": 768,          # Embedding dimension
    "n_heads": 12,           # Number of attention heads
    "n_layers": 12,          # Number of layers
    "drop_rate_embed": 0.1,  # Dropout rate for embedding layer
    "drop_rate_short": 0.2,  # Dropout rate for shortcut layer
    "drop_rate_mha": 0.3,    # Dropout rate for multi-head attention module
    "qkv_bias": False        # Query-Key-Value bias
}

class TransformerBlock(nn.Module):
    def __init__(self, config):
        super().__init__()
        self.attention = MultiHeadAttention(
            input_dim      = config["emb_dim"],
            output_dim     = config["emb_dim"],
            context_length = config["context_length"],
            num_heads      = config["n_heads"],
            dropout_pct    = config["drop_rate_mha"],
            use_bias       = config["qkv_bias"]
        )
        self.feed_forward = FeedForward(config)
        self.norm1 = LayerNorm(config["emb_dim"])
        self.norm2 = LayerNorm(config["emb_dim"])
        self.dropout = nn.Dropout(config["drop_rate_short"])

    def forward(self, batch):
        shortcut = batch
        output = self.norm1(batch)
        output = self.attention(output)
        output = self.dropout(output)
        output = output + shortcut

        shortcut = output
        output = self.norm2(output)
        output = self.feed_forward(output)
        output = self.dropout(output)
        output = output + shortcut

        return output

class GPTModel(nn.Module):
    def __init__(self, cfg):
        super().__init__()
        self.tok_emb = nn.Embedding(cfg["vocab_size"], cfg["emb_dim"])
        self.pos_emb = nn.Embedding(cfg["context_length"], cfg["emb_dim"])
        self.dropout = nn.Dropout(cfg["drop_rate_embed"])
        self.xform_blocks = nn.Sequential(
            *[TransformerBlock(cfg) for _ in range(cfg["n_layers"])]
        )
        self.final_norm = LayerNorm(cfg["emb_dim"])
        self.out_head = nn.Linear(cfg["emb_dim"], cfg["vocab_size"], bias = False)

    def forward(self, input_tokens):
        batch_size, num_tokens = input_tokens.shape

        token_embeds = self.tok_emb(input_tokens)
        pos_embeds = self.pos_emb(torch.arange(num_tokens, device=input_tokens.device))
        X = token_embeds + pos_embeds
        X = self.dropout(X)
        X = self.xform_blocks(X)
        X = self.final_norm(X)

        logits = self.out_head(X)
        return logits