Chapter 11: The Transformer
The previous chapter ended with attention bolted onto a recurrent network: the decoder still walks the sequence one step at a time, and attention is a side channel into the encoder’s states. This chapter removes the recurrence entirely and builds “Attention Is All You Need” from its parts. Every model in the rest of the book, from GPT and BERT to the modern Llama block and the inference engine’s kernels, is a rearrangement of the pieces you build here.
Concepts from other sections (14)
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.
- inference engine: software that loads weights, schedules requests, manages the KV cache, and generates tokens (vLLM, SGLang, TensorRT-LLM, llama.cpp). Read more: 20.5 LLM Serving Platforms: How They Work and When to Use Them
- scaled dot-product attention: , a weighted average of values with weights from query-key similarity. Read more: 11.1 Scaled dot-product attention (forward and backward)
- Noam schedule: , linear warmup then inverse-square-root decay. Read more: 11.5 Encoder-decoder Transformer: post-LN and pre-LN, Noam, label smoothing
- label smoothing: training against instead of a one-hot target. Read more: 11.5 Encoder-decoder Transformer: post-LN and pre-LN, Noam, label smoothing
- 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
- positional encoding: a vector depending only on position, added to the token embedding so attention can see order. Read more: 11.4 Positional encodings: sinusoidal, learned
- beam search: keeping the best prefixes by summed log-probability, ranking all extensions together at each step. Read more: 10.4 Beam search, generic over a step function
- 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 - VJP (vector-Jacobian product): , the gradient of ; what reverse mode computes. Read more: 10.2 Jacobians, the multivariable chain rule, and numeric JVP/VJP in Mathematics
- frequency ladder: the geometric sequence of angular speeds, from 1 down to about . Read more: 11.4 Positional encodings: sinusoidal, learned
- Variance: the expected squared distance from the mean; its square root is the standard deviation. Read more: 13.1 Random variables, expectation, variance, and normal draws by Box-Muller in Mathematics
- attention dropout: an inverted-dropout multiplier applied to after the softmax, reused unchanged in the backward. Read more: 11.1 Scaled dot-product attention (forward and backward)
- cross-attention: attention with queries from one sequence and keys and values from another. Read more: 11.3 Multi-head attention
- RoPE: rotary position embedding, which rotates queries and keys by position to encode relative position. Read more: 5.3 Model landscape and lifecycle
The arc is bottom-up. You start with the one function everything else calls, scaled dot-product attention, , and write its backward pass by hand. You then build the masks that keep a decoder from reading the future or a batch from reading padding, split attention into heads so one position can read several places at once, and give the model a sense of order with sinusoidal and learned positions. The last section assembles everything into the full encoder-decoder transformer, trains it on three-digit addition with the paper’s recipe (Noam schedule, label smoothing), and shows the first decision modern models made differently: placing the LayerNorm before each sublayer instead of after, which removes the need for warmup.
Learning objectives
- Derive and implement scaled dot-product attention and its backward pass as one autograd node, and explain the scale.
- Build causal, padding, and sliding-window masks from one convention, and explain why the additive form uses .
- Implement multi-head attention with correct head splitting, per-head scaling, and masks for every head.
- Construct sinusoidal and learned positional encodings and prove that a sinusoidal shift is a fixed rotation.
- Assemble and train an encoder-decoder transformer in both LayerNorm placements, and decode it step by step with beam search.
Before you begin
Section titled “Before you begin”You should have the attention mechanisms of Attention Origins in hand, especially Luong attention and beam search, and the Tensor, op library, and layers of the foundations chapter. From Mathematics, the sections that matter most are the logic in the discrete math 1 problem set, the VJP derivations in the matrix calculus problem set, and the rotations and frequency ladders of Precalculus.
In this chapter
Section titled “In this chapter”- Scaled dot-product attention (forward and backward). The soft lookup at the heart of every transformer, the variance argument for its scale, and a hand-derived backward pass registered as a single autograd node, with attention dropout.
- Masks: causal, padding, sliding window, additive. One convention (True = may attend) for every rule, a
q_offsetthat makes decode chunks exact rows of the training mask, and why the additive form must be . - Multi-head attention. Splitting the model width into heads that attend independently, the reshape-and-transpose layout, and one module that serves both self- and cross-attention.
- Positional encodings: sinusoidal, learned. The geometric frequency ladder, the shift-is-a-rotation property that later becomes RoPE, and GPT-2’s learned table.
- Encoder-decoder Transformer: post-LN and pre-LN, Noam, label smoothing. The full 2017 architecture, its training recipe worked by hand, step-by-step decoding with beam search, and the LayerNorm placement that decides whether it trains without warmup.
Further reading
Section titled “Further reading”- Vaswani et al., Attention Is All You Need; Rush et al., The Annotated Transformer.
- Xiong et al., On Layer Normalization in the Transformer Architecture.