The Modern Decoder Block, Assembled
The upgrades leave the decoder’s basic structure intact. Each changes a different mechanism or execution cost. Assemble them, read real configuration choices, and verify the finished function against a reference.
#Section 33The Full Diff
Every design choice that changed between GPT-2 (2019) and Llama 3 (2024), with the part of this chapter that covers it.
| Choice | GPT-2 / Finch-19 | Llama 3 / Finch-24 | Part |
|---|---|---|---|
| Positions | learned table added at the bottom | RoPE on q and k in every layer | I |
| Context | 1,024 | 8,192 (Llama 3), 4,096 (Finch-24) | I |
| Normalization | LayerNorm, pre-norm | RMSNorm, pre-norm | II |
| MLP | GELU, two matrices, | SwiGLU, three matrices, about | III |
| Key/value heads | one per query head | shared by groups of 4 (GQA) | IV |
| Attention kernel | written by hand | SDPA / FlashAttention | V, VI |
| Biases | on every linear layer and norm | none | VII |
| Vocabulary | 50,257 (GPT-2), 32,000 (Finch) | 128,256 (Llama 3), 32,000 (Finch) |
Look at what did not change: the skeleton. Residual stream, norm, attention, add, norm, MLP, add, stacked, then a final norm and an output head. Every upgrade is a swap of one part, not a redesign. That is good news for learning and for interviews: if you can draw the 2019 block, you can draw the 2024 block by relabelling six boxes.
#Section 34Applying the Upgrades One at a Time
Start from one Finch-19 block and apply each upgrade in turn, counting the parameters per layer and the KV cache per token per layer as we go.
RoPE removes the learned position table. RMSNorm removes centering and bias. SwiGLU changes feature transformation, GQA narrows KV projections, and fused kernels avoid large intermediates. Dropping projection biases completes this teaching recipe.
These substitutions change different resources. Some remove weights, some add capacity, and some change execution without adding parameters. Judge each mechanism separately before comparing the bundle.
The lesson of the table is that most upgrades are not about size. RMSNorm and SwiGLU make the model learn better per parameter; RoPE makes positions relative and extendable; SDPA and FlashAttention make it faster; GQA makes generation cheaper and faster. Only GQA moves the numbers much.
#Section 35Inside the Finished Block: Llama 3 8B
Now the finished block at full size, with Llama 3 8B's real numbers: width 4,096, 32 query heads and 8 key/value heads of 128, an MLP width of 14,336, RoPE base 500,000, RMSNorm with , no biases.
Follow tokens down the block. is . RMSNorm keeps the shape. The query projection gives after splitting heads; the key and value projections give each, a quarter of the size, because of GQA. RoPE rotates queries and keys. The new keys and values are appended to the cache, 8 heads wide. SDPA runs attention with each key/value head shared by 4 query heads, producing , which is merged back to and projected by the output matrix. That is added to the residual stream. Then the second half: RMSNorm, gate and up projections both widen to , SiLU and multiply, and the down projection brings it back to , added to the stream again. The shape going out equals the shape coming in, so the same design stacks 32 times.
Where one block's parameters live
So in a modern block the MLP holds 80.8% of the parameters and attention only 19.2%, smaller than most people expect. Thirty-two blocks give 6,979,584,000 parameters; add the untied input embedding and output head, , and the final norm, 4,096, and you get 8,030,261,248, the "8B" in the name.
#Section 36Four Real Configs and the Code
Four configs side by side
Here are four real models as their config files describe them. GPT-2 small is the 2019 reference; the other three are 2024-era models of about the same size, all built from the recipe in this chapter.
| Config field | GPT-2 small | Llama 3 8B | Mistral 7B v0.1 | Qwen 2.5 7B |
|---|---|---|---|---|
hidden_size () |
768 | 4,096 | 4,096 | 3,584 |
num_hidden_layers |
12 | 32 | 32 | 28 |
num_attention_heads |
12 | 32 | 32 | 28 |
num_key_value_heads |
12 | 8 | 8 | 4 |
intermediate_size |
3,072 (GELU) | 14,336 | 14,336 | 18,944 |
vocab_size |
50,257 | 128,256 | 32,000 | 152,064 |
Positions / rope_theta |
learned | 500,000 | 10,000 | 1,000,000 |
| Norm | LayerNorm | RMSNorm | RMSNorm | RMSNorm |
| QKV biases | yes | no | no | yes |
| Tied embeddings | yes | no | no | no |
| Context | 1,024 | 8,192 | 32,768 (4,096 sliding window) | 32,768 |
The structure is identical across the three modern models; what you read from each config is the sizes, how many key/value heads they share, the MLP width, the vocabulary, and a few small details such as Qwen keeping biases on the query, key and value projections and Mistral's sliding window.
The whole block in code
class Block(nn.Module):
def __init__(self, d=4096, H=32, H_kv=8, hd=128, ff=14336, eps=1e-5):
super().__init__()
self.n1, self.n2 = RMSNorm(d, eps), RMSNorm(d, eps)
self.q = nn.Linear(d, H * hd, bias=False)
self.k = nn.Linear(d, H_kv * hd, bias=False)
self.v = nn.Linear(d, H_kv * hd, bias=False)
self.o = nn.Linear(H * hd, d, bias=False)
self.gate = nn.Linear(d, ff, bias=False)
self.up = nn.Linear(d, ff, bias=False)
self.down = nn.Linear(ff, d, bias=False)
self.H, self.H_kv, self.hd = H, H_kv, hd
def forward(self, x, cos, sin, cache=None): # x: (B, T, d)
B, T, _ = x.shape
h = self.n1(x)
q = self.q(h).view(B, T, self.H, self.hd).transpose(1, 2)
k = self.k(h).view(B, T, self.H_kv, self.hd).transpose(1, 2)
v = self.v(h).view(B, T, self.H_kv, self.hd).transpose(1, 2)
q, k = apply_rope(q, k, cos, sin) # Part I
if cache is not None:
k, v = cache.update(k, v) # store H_kv heads, not H
a = F.scaled_dot_product_attention(q, k, v, is_causal=T > 1,
enable_gqa=True) # Parts IV to VI
x = x + self.o(a.transpose(1, 2).reshape(B, T, -1))
h = self.n2(x)
return x + self.down(F.silu(self.gate(h)) * self.up(h)) # Part IIIEvery part of this chapter appears in those lines. Two RMSNorms. Bias-free projections with fewer key/value heads. RoPE on queries and keys only, after the head reshape. A cache that stores the small key/value tensors. SDPA with grouped heads and is_causal only when more than one token is being processed, because a single decode query must see every cached key (Part V); processing a chunk of new tokens on top of an existing cache would need the lower-right mask instead. The SwiGLU MLP. Two residual additions. The full model wraps 32 of these between an embedding lookup and a final RMSNorm plus output head, and precomputes cos and sin once.
Where compute goes, per generated token
Linear projections run for each new token; attention also reads the growing history. Longer contexts therefore change which part of a block dominates.
Long-context work therefore focuses on attention (FlashAttention, GQA, sparse and sliding-window patterns), while short-context work focuses on the MLP and the matrix multiplies (quantization, batching, better kernels).
#Section 37The Porting Checklist
Before you load someone else's modern model into your own code, check these ten settings. Each one can be wrong without causing any error: the model loads, runs and gives worse answers.
The first three are about positions and norms: rope_theta and any rope_scaling entry; the pairing convention for RoPE; and the norm's and whether is applied as or . The next two are about the MLP: intermediate_size, never assumed from ; and which half of a fused gate/up matrix is the gate. Then attention: the head counts and their grouping, with repeat_interleave semantics; and causal alignment during decode. Then the run: the dtype, bf16 for the fast kernels. And finally two config flags people forget: biases, which Qwen keeps on q, k and v; and tie_word_embeddings. The practical test is to run one prompt through both the reference implementation and yours and compare the logits at every position; differences beyond the last few digits mean one of these is wrong.
#Section 38Real Models That Bend the Recipe
Qwen keeps QKV biases. Qwen models keep bias vectors on the query, key and value projections, unlike Llama. Code written for Llama drops them and gives wrong outputs. Do not assume bias=False everywhere.
Mistral's sliding window. Mistral 7B v0.1 lets each token see only the previous 4,096 tokens. Both the attention mask and the cache size must respect it, which also means the cache can be a fixed-size rolling buffer.
Gemma's extras. Gemma multiplies embeddings by , stores its RMSNorm gain as , and Gemma 2 caps very large attention and output logits with a smooth "soft cap" and uses sandwich norms. None of that is obvious from a typical config. Read the model's reference code, not just the config.
Tied embeddings in small models. Llama 3.2's 1B and 3B models reuse the input embedding as the output head; the 8B model does not. A checkpoint with no output weight usually means the embeddings are tied.
Initialization for training from scratch. Training from scratch needs careful starting values: random weights with a small standard deviation (about 0.02 is common), and the projections that write into the residual stream (the attention output and the MLP down projection) often scaled down further by about so the stream does not grow with depth, as Chapter 1, Section 68, described for GPT-2.