Highlights

Contents

Part VII
07

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.

YOU ARE HEREMODERN DECODER BLOCKATTENTION HALFRMSNormq, k, v projRoPE (q, k)GQA: 8 q, 2 kvSDPAFlash kernelo proj+MLP HALFRMSNormgate, up projSiLU(g) ⊙ udown proj+residual stream: x + Attn(Norm(x)), then h + MLP(Norm(h))what changed since GPT-2: positions, norm, MLP, K/V sharing, the attention kernel, and no biases

#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, 4d4d SwiGLU, three matrices, about 3.5d3.5d 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.

GPT-2 STYLE (FINCH-19) VERSUS LLAMA 3 STYLE (FINCH-24): SAME SKELETON, SWAPPED PARTSFinch-19 (2019 recipe)tokens + learned positionsLayerNormMHA, 8 K/V heads, by hand+ residualLayerNormGELU MLP, 2,048+ residualFinch-24 (2024 recipe)tokens only (RoPE in attention)IRMSNormIIGQA 8 q / 2 kv + RoPE, SDPAIV,V,VI+ residualRMSNormIISwiGLU MLP, 1,536III+ residualbiases removed everywhere on the right
Figure 2.49The two blocks side by side. The skeleton is identical; the highlighted parts on the right are the swaps, each tagged with the part of this chapter that covers it.

#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.

APPLYING THE UPGRADES TO ONE FINCH BLOCK, ONE AT A TIMEstepattentionMLPnormsKV bytes/tokenFinch-19 block1,050,6242,099,7122,0482,048+ RoPE1,050,6242,099,7122,0482,048+ RMSNorm1,050,6242,099,7121,0242,048+ SwiGLU (1,536)1,050,6242,362,8801,0242,048+ GQA (2 K/V heads)656,6402,362,8801,024512+ SDPA / Flash656,6402,362,8801,024512− biases = Finch-24655,3602,359,2961,024512per layer; orange marks a number that changed at that step. Positions also drop a 524,288-parameter table at "+ RoPE".
Figure 2.50One Finch block as each upgrade is applied. Most upgrades barely move the parameter count; GQA cuts both the attention parameters and the cache sharply.

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 ε=10−5\varepsilon = 10^{-5}, no biases.

Follow TT tokens down the block. xx is (T,4096)(T, 4096). RMSNorm keeps the shape. The query projection gives (T,32,128)(T, 32, 128) after splitting heads; the key and value projections give (T,8,128)(T, 8, 128) 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 (T,32,128)(T, 32, 128), which is merged back to (T,4096)(T, 4096) 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 (T,14336)(T, 14336), SiLU and multiply, and the down projection brings it back to (T,4096)(T, 4096), added to the stream again. The shape going out equals the shape coming in, so the same design stacks 32 times.

ONE LLAMA 3 8B BLOCK, TOP TO BOTTOM, WITH SHAPES (T TOKENS)x(T, 4096)RMSNorm(T, 4096)q_proj(T, 32, 128)k_proj(T, 8, 128)v_proj(T, 8, 128)RoPE on q and kappend k, v to KV cache (8 heads)SDPA, GQA groups of 4(T, 32, 128)o_proj(T, 4096)+ residual, then RMSNorm(T, 4096)gate_proj(T, 14336)up_proj(T, 14336)SiLU(gate) ⊙ up → down_proj → + residual(T, 4096)
Figure 2.51Shapes through one Llama 3 8B block. Queries are 32 heads of 128; keys and values are 8 heads; the MLP widens to 14,336; everything returns to (T, 4096).

Where one block's parameters live

WHERE ONE LLAMA 3 8B BLOCK’S 218,112,000 PARAMETERS LIVEq_proj 4096 × 409616,777,216 (7.7%)k_proj 4096 × 10244,194,304 (1.9%)v_proj 4096 × 10244,194,304 (1.9%)o_proj 4096 × 409616,777,216 (7.7%)gate_proj 4096 × 1433658,720,256 (26.9%)up_proj 4096 × 1433658,720,256 (26.9%)down_proj 14336 × 409658,720,256 (26.9%)2 RMSNorms8,192 (0.0%)the MLP is 80.8% of the block
Figure 2.52One Llama 3 8B block's parameters. Attention is about a fifth; the three MLP matrices are four fifths; the norms round to nothing.

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, 2×128,256×4,096=1,050,673,1522 \times 128{,}256 \times 4{,}096 = 1{,}050{,}673{,}152, 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 (dd) 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

python
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 III

Every 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.

FORWARD FLOPS PER GENERATED TOKEN, ONE LLAMA 3 8B BLOCK: LINEAR LAYERS VERSUS ATTENTION1,024 ctxattention 3.7%8,192 ctxattention 23.5%131,072 ctxattention 83.1%slate: projections + MLP, 2 × 218M ≈ 436M FLOPs. orange: scores and value mixing, 4 · T · 4096
Figure 2.53Forward FLOPs per generated token for one Llama 3 8B block. Attention is a thin slice at short contexts and the majority at 128k.

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.

PORTING CHECKLIST: SETTINGS THAT CAN BE WRONG WITHOUT ANY ERRORrope_theta and rope_scalingbase and long-context method (Part I)01pairing conventioninterleaved or half-split (Part I)02norm ε and γ formγ or 1 + γ, ε value (Part II)03intermediate_sizenever assume 4d (Part III)04gate / up orderwhich half is the gate (Part III)05H, H_kv and groupingrepeat_interleave, not repeat (Part IV)06causal alignmentdecode with a cache (Part V)07dtypebf16 for the fast kernels (Part VI)08biasesQwen keeps q, k, v biases09tied embeddingstie_word_embeddings in the config10
Figure 2.54Ten settings to verify when porting a modern decoder. Each is a silent failure if wrong, and each traces back to a part of this chapter.

The first three are about positions and norms: rope_theta and any rope_scaling entry; the pairing convention for RoPE; and the norm's ε\varepsilon and whether γ\gamma is applied as γ\gamma or 1+γ1 + \gamma. The next two are about the MLP: intermediate_size, never assumed from dd; 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 d\sqrt{d}, stores its RMSNorm gain as γ−1\gamma - 1, and Gemma 2 caps very large attention and output logits with a smooth tanh⁡\tanh "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 1/2N1/\sqrt{2N} so the stream does not grow with depth, as Chapter 1, Section 68, described for GPT-2.