Intermediate about 4 h
The picture
01
Embed + position
x₀
02
Norm → Attention
+ residual
03
Norm → MLP
+ residual
04
× N blocks
the stack
05
Final norm
then unembed
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 , layers and vocabulary (ignoring biases and norms): each block has about in attention and in the MLP, so
GPT-2 small (, , ) 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 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 ).
- Treating the MLP as a minor detail: it holds most of the parameters.
Exercises
- Compute the parameter count for , , by hand and in code.
- 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