Chapter 13: The Modern Decoder Block
Between 2017 and a Llama-family model, almost every part of the transformer block changed. The previous two chapters gave you the 2017 architecture and the objectives built on it; none of that code can load a single checkpoint published today. This chapter rebuilds the block piece by piece until it loads Hugging Face configs and weights and matches SmolLM2-135M’s logits.
Concepts from other sections (30)
This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.
- logits: unnormalized log-scores that softmax turns into probabilities; here the table stores . Read more: 6.1 Byte bigram: counts, logits, safetensors v0
- LayerNorm: per-row normalization by the population mean and variance with inside the square root, then an affine map. Read more: 6.5 Module system and basic layers
- RMSNorm: divides a vector by its root mean square plus eps (inside the root) and multiplies by a learned gain; no mean subtraction, no bias. Read more: 13.1 Pre-LN and RMSNorm
- Position interpolation: dividing every frequency by the factor so long positions reuse trained angles. Read more: 13.4 Context Extension: PI, NTK, YaRN, Llama 3 Scaling, and ALiBi
- YaRN: a per-pair ramp between keeping and dividing frequencies, by turns over the trained context, plus a temperature . Read more: 13.4 Context Extension: PI, NTK, YaRN, Llama 3 Scaling, and ALiBi
- Llama 3 scaling: wavelength bands with a smooth blend between keep and divide, no temperature. Read more: 13.4 Context Extension: PI, NTK, YaRN, Llama 3 Scaling, and ALiBi
- ALiBi: a per-head bias that falls linearly with query-key distance, used instead of rotations. Read more: 13.4 Context Extension: PI, NTK, YaRN, Llama 3 Scaling, and ALiBi
- Grouped-query attention (GQA): query heads share key/value heads, each serving a contiguous group of query heads. Read more: 13.5 Grouped-Query Attention with a Cache Hook, Windows, and Sinks
- Multi-head latent attention (MLA): attention whose keys and values are rebuilt per head from a cached low-rank latent of each token. Read more: 13.6 Multi-Head Latent Attention and Weight Absorption
- Sliding window: a limit so query reads only keys . Read more: 13.5 Grouped-Query Attention with a Cache Hook, Windows, and Sinks
- Attention sink: an early token that a trained model parks unwanted attention on; StreamingLLM keeps the first tokens visible forever. Read more: 13.7 Sliding Windows and Attention Sinks
- Mixture of experts (MoE): a layer of many expert MLPs of which a router picks per token. Read more: 13.8 Mixture of Experts
- Pre-LN: the residual step , which normalizes only the branch input. Read more: 13.1 Pre-LN and RMSNorm
- SwiGLU: the gated MLP with silu on the gate (Llama, SmolLM2). Read more: 13.2 Gated MLPs: SwiGLU and GeGLU
- GeGLU: the gated MLP with the tanh-approximated GELU on the gate (Gemma). Read more: 13.2 Gated MLPs: SwiGLU and GeGLU
- RoPE: rotating pair of a query or key at position by , so scores depend only on relative position. Read more: 13.3 Rotary Position Embeddings
- Cache hook: the
update(layer, k, v)protocol through which a KV cache receives rotated, unrepeated keys and values. Read more: 13.5 Grouped-Query Attention with a Cache Hook, Windows, and Sinks - Bytes per token: total UTF-8 bytes over total tokens; the compression ratio. Read more: 7.6 Tokenizer metrics
- Sorted dispatch: grouping assignments by expert with a stable sort so each expert runs once on a contiguous slice. Read more: 13.8 Mixture of Experts
- op library (
F): the module of differentiable functions, each a NumPy forward plus one closed-form VJP joined byfrom_op. Read more: 6.3 The op library and gradcheck_all - frequency ladder: the geometric sequence of angular speeds, from 1 down to about . Read more: 11.4 Positional encodings: sinusoidal, learned
- Identity path: the term in the Pre-LN Jacobian that carries the gradient straight from the loss to the embedding. Read more: 13.1 Pre-LN and RMSNorm
- Interleaved layout: pair is ; used by RoFormer and Meta’s original code. Read more: 13.3 Rotary Position Embeddings
- Partial rotary: rotating only the first entries of each head. Read more: 13.3 Rotary Position Embeddings
- KV cache: per-layer storage of past keys and values, so each decode step processes only the new token. Read more: 21.2 The KV cache, incremental decoding, and generate
- Learned sink: a per-head extra logit in every softmax row, dropped afterwards, letting a head attend to nothing. Read more: 13.5 Grouped-Query Attention with a Cache Hook, Windows, and Sinks
- Decoupled rope key: a small rotated key shared by all heads, kept separate so the latent part stays position-free. Read more: 13.6 Multi-Head Latent Attention and Weight Absorption
- Inverse permutation: (
inv_perm): the map from each assignment to its sorted slot, used to put outputs back. Read more: 13.8 Mixture of Experts - Load-balancing loss: Switch Transformer’s , equal to at perfect balance. Read more: 13.8 Mixture of Experts
- Aux-free bias: DeepSeek-V3’s per-expert correction added to choice scores only, moved by a sign rule. Read more: 13.8 Mixture of Experts
The arc follows the block from the inside out. You start with the two changes that make deep stacks train without warmup: moving the norm in front of each sublayer and replacing LayerNorm with RMSNorm. Next comes the gated MLP that now holds most of a block’s parameters, then rotary position embeddings, which put position inside every attention layer by rotating queries and keys so a score depends only on the offset between them, and the context-extension rules (position interpolation, NTK, YaRN, Llama 3 scaling, and the optional ALiBi) that stretch a model past its training length.
Attention itself is next, and its theme is that KV bytes, not FLOPs, are the serving cost. Grouped-query attention shares key and value heads across query heads; multi-head latent attention compresses them into a latent and absorbs the up-projection into the query; sliding windows and attention sinks bound the cache for streams of any length. Mixture of experts then routes each token to of experts, so parameters grow without growing per-token compute, and shows that balancing the load is the hard part. The last section assembles everything into one model, loads real checkpoints by name, and downloads them with a resumable, verified downloader.
Learning objectives
- Implement RMSNorm and the Pre-LN residual step, and explain why Pre-LN trains without warmup.
- Build SwiGLU and GeGLU MLPs whose shapes and widths match published checkpoints.
- Implement RoPE in both layouts and every common context-extension rule, matching Hugging Face to long positions.
- Build grouped-query and multi-head latent attention with a cache hook, sliding windows, and sinks, and reason about KV bytes per token.
- Route tokens through a mixture of experts with sorted dispatch and both load-balancing schemes.
- Assemble a Llama-family model that loads Hugging Face configs and weights and matches SmolLM2-135M’s logits.
Before you begin
Section titled “Before you begin”You should have The Transformer (2017) and Objectives and Adaptation behind you, along with the Tensor, op library, and module system of the foundations chapter. From Mathematics, Counting: parameters, FLOPs, KV bytes, and memory plans supplies the parameter and KV-byte counts used throughout, and the rotations and frequency ladders of Precalculus are the mathematics behind RoPE.
In this chapter
Section titled “In this chapter”- Pre-LN and RMSNorm. Normalizing by the root mean square with eps inside the root, Gemma’s stored-gain offset, and the Pre-LN residual step that gives the gradient an identity path.
- Gated MLPs: SwiGLU and GeGLU. Two projections, one gating the other, the activation on the gate, and why three matrices at width explain Llama’s odd hidden sizes.
- Rotary Position Embeddings. Rotating query and key pairs by position-proportional angles so scores depend on relative position, in the half and interleaved layouts, with partial rotary and float32 angles.
- Context Extension: PI, NTK, YaRN, Llama 3 Scaling, and ALiBi. Why slow RoPE pairs break past the trained context and how each scaling rule fixes the frequencies; ALiBi is an optional final part.
- Grouped-Query Attention with a Cache Hook, Windows, and Sinks. Sharing kv heads across query heads, the visibility rule for cached calls, the hook through which every KV cache plugs in, and learned sinks.
- Multi-Head Latent Attention and Weight Absorption. DeepSeek’s low-rank latent cache, the decoupled rope key, and the absorbed decode form that never rebuilds per-head keys.
- Sliding Windows and Attention Sinks. One visibility rule for windows and sink tokens, a cache that holds at most keys, and a float64 reference attention with learned sinks.
- Mixture of Experts. Three routers, sorted dispatch with an inverse permutation, the Switch load-balancing loss, and DeepSeek-V3’s aux-free bias.
- The Llama-Family Model: Config, Weight Loading, and Download. Assembling the block, reading every
config.jsondialect, loading strictly by name, counting SmolLM2’s 134,515,008 parameters, and a resumable, verified downloader.
Further reading
Section titled “Further reading”- Su et al., RoFormer; Peng et al., YaRN; Ainslie et al., GQA; DeepSeek-AI, DeepSeek-V2 (MLA).
- Shazeer, GLU Variants Improve Transformer; Fedus et al., Switch Transformers; Xiao et al., StreamingLLM.