Skip to content
mentoor

Topic 3 of 6 · 5 min read

Stacking blocks into a GPT model

Goal: Count the parameters of a small GPT configuration and explain what each component contributes to the model.

A GPT is an embedding layer, a stack of identical residual blocks that each mix information across positions (attention) and then transform each position (MLP), and a final linear layer that turns every position into scores over the vocabulary.

Check yourself · 1 of 3

Why does a GPT add position embeddings to token embeddings?

Choose one answer

Why it matters

When you can name each part and count its parameters, you can read any model card, predict memory use, and spot a config that wastes capacity. Real models differ in size and details, but the layout is the same one you build here.

How to do it

Take a small configuration: vocab_size = 65, block_size = 256, n_embd = 128, n_layer = 4, n_head = 4.

  1. Token embedding: a table (vocab_size, n_embd). Each id becomes a vector. 65 * 128 = 8,320 parameters.
  2. Position embedding: a table (block_size, n_embd). Attention itself has no sense of order, so position vectors are added to token vectors. 256 * 128 = 32,768.
  3. Blocks, repeated n_layer times. Each block does x = x + attn(ln1(x)) then x = x + mlp(ln2(x)).
    • The residual additions (x + ...) give gradients a direct path through the stack and let each block make small edits.
    • Layer norm rescales each position's vector so activations stay in a stable range.
    • The MLP is two linear layers with a nonlinearity such as GELU, widening to 4 * n_embd and back. Its weights are 8 * n_embd^2.
    • Attention holds four n_embd x n_embd matrices (q, k, v and the output projection): 4 * n_embd^2.
  4. Final layer norm, then a linear language-model head (n_embd, vocab_size) giving logits of shape (B, T, vocab_size). Many GPTs tie this matrix to the token embedding, sharing its weights.

Per block that is 12 * n_embd^2 = 196,608. Four blocks give 786,432. Add both embeddings and the total is about 0.83 million parameters. Biases and layer norms add under 1%.

Before and after

A weak mental model says "more layers means a smarter model" and picks n_layer = 24 for a 1 MB text file. A better one counts: 24 blocks at n_embd = 128 is about 4.7 million parameters for roughly a million characters of data. The model has more room than the data can fill, so it memorizes the text. For this corpus, a few layers is enough, and extra capacity shows up as a growing gap between train and validation loss.

What goes wrong

  • Forgetting position embeddings. The model sees a bag of tokens, and word order cannot be learned.
  • Using a sequence longer than block_size. The position table has no row for it and indexing fails. Crop the context.
  • n_embd not divisible by n_head. The head size n_embd // n_head truncates and shapes no longer match.
  • Counting the head twice. With tied weights, the output matrix is not new parameters.

Examples

Block and model skeleton

class Block(nn.Module):
    def __init__(self, n_embd, n_head, block_size):
        super().__init__()
        self.ln1 = nn.LayerNorm(n_embd)
        self.attn = MultiHeadAttention(n_embd, n_head, block_size)
        self.ln2 = nn.LayerNorm(n_embd)
        self.mlp = nn.Sequential(
            nn.Linear(n_embd, 4 * n_embd), nn.GELU(), nn.Linear(4 * n_embd, n_embd))

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

In the model, x = tok_emb(idx) + pos_emb(torch.arange(T)), then the blocks, then ln_f and lm_head. Shapes: (B, T) ids in, (B, T, 65) logits out.

Key points

  • A GPT is token plus position embeddings, n_layer residual blocks, a final layer norm and a linear head to vocabulary logits.
  • Each block applies attention then an MLP, each wrapped in layer norm and added back through a residual connection.
  • Per block, attention has about 4 times n_embd squared weights and the MLP about 8 times, so a block is roughly 12 times n_embd squared.
  • Position embeddings are required because attention alone does not know the order of tokens.
  • Tying the output head to the token embedding removes a vocab-by-embedding matrix from the parameter count.

Common mistakes

  • Leaving out position embeddings and then wondering why word order does not matter to the model.
  • Choosing depth and width without counting parameters against the amount of training text.
  • Setting n_embd to a value that n_head does not divide.
  • Putting layer norm after the residual add in a deep stack and getting unstable early training.

Check yourself · 2 of 3

What does the residual connection x = x + attn(ln1(x)) give a deep stack?

Choose one answer

Check yourself · 3 of 3

Roughly how many weights are in one block with n_embd = 128, counting attention (4 matrices) and a 4x-wide MLP and ignoring biases?

Choose one answer

Practice items, not counted towards your mastery.

Start here