The transformer block and the full GPT

Residual streams, layer norm, the MLP, and stacking blocks into a decoder-only language model.

Intermediate about 4 h

The picture

  1. 01

    Embed + position

    x₀

  2. 02

    Norm → Attention

    + residual

  3. 03

    Norm → MLP

    + residual

  4. 04

    × N blocks

    the stack

  5. 05

    Final norm

    then unembed

  6. 06

    Logits

    next-token scores

The residual stream

Think of each token as carrying a vector (its residual stream). Every sub-layer reads from it and adds a correction. Attention moves information between positions; the MLP processes each position independently, storing and recalling facts.

x = x + Attention(Norm(x))     # communicate between tokens
x = x + MLP(Norm(x))           # compute within a token

Pre-norm (normalise the input of each sub-layer) keeps a clean identity path for gradients and is what most modern models use.

A complete block

class MLP(nn.Module):
    def __init__(self, d, mult=4):
        super().__init__()
        self.up, self.down = nn.Linear(d, mult * d), nn.Linear(mult * d, d)
    def forward(self, x):
        return self.down(F.gelu(self.up(x)))

class Block(nn.Module):
    def __init__(self, d, n_heads, block_size):
        super().__init__()
        self.n1, self.n2 = nn.LayerNorm(d), nn.LayerNorm(d)
        self.attn = CausalSelfAttention(d, n_heads, block_size)
        self.mlp = MLP(d)
    def forward(self, x):
        x = x + self.attn(self.n1(x))
        return x + self.mlp(self.n2(x))

class GPT(nn.Module):
    def __init__(self, vocab, d=256, n_layers=6, n_heads=8, block_size=256):
        super().__init__()
        self.tok = nn.Embedding(vocab, d)
        self.pos = nn.Embedding(block_size, d)
        self.blocks = nn.ModuleList(Block(d, n_heads, block_size) for _ in range(n_layers))
        self.norm = nn.LayerNorm(d)
        self.head = nn.Linear(d, vocab, bias=False)
        self.head.weight = self.tok.weight        # weight tying
        self.block_size = block_size

    def forward(self, idx, targets=None):
        B, T = idx.shape
        x = self.tok(idx) + self.pos(torch.arange(T, device=idx.device))
        for b in self.blocks:
            x = b(x)
        logits = self.head(self.norm(x))
        loss = None if targets is None else F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1))
        return logits, loss

Counting parameters

For width dd, LL layers and vocabulary VV (ignoring biases and norms): each block has about 4d24d^2 in attention and 8d28d^2 in the MLP, so

N≈12 L d2+V dN \approx 12\,L\,d^2 + V\,d

GPT-2 small (L=12L=12, d=768d=768, V≈50kV\approx 50\text{k}) gives about 124M parameters. Verify with sum(p.numel() for p in model.parameters()).

Weight tying

The input embedding and the output projection solve mirror-image problems (token → vector, vector → token). Sharing them saves V⋅dV\cdot d parameters and usually helps small models.

Common mistakes

  • Forgetting the final norm before the output head.
  • Not scaling the initialisation of residual projections as depth grows (GPT-2 scales them by 1/2L1/\sqrt{2L}).
  • Treating the MLP as a minor detail: it holds most of the parameters.

Exercises

  1. Compute the parameter count for L=24L=24, d=1024d=1024, V=50304V=50304 by hand and in code.
  2. Remove the residual connections and watch training collapse.

You are done when you can…

  • Draw the residual stream and say what each sub-layer reads and writes
  • Count a model's parameters from its configuration
  • Explain weight tying and why pre-norm trains more stably than post-norm