10 Attention
The recurrent models of Chapter 8 read a sequence one token at a time and compress everything they have seen into a hidden state of fixed size. If a prediction near the end of a long document depends on a detail from the first paragraph, the recurrent network must have written that detail into its hidden state long before knowing it would be needed. Rather than compressing history into a single vector, can a network retain a representation at every position and retrieve only what the current prediction requires?
Attention does exactly this. At each lookup, a query vector representing what the current position seeks is scored against a key vector at every candidate position. A softmax converts those scores into nonnegative weights that sum to one, and the layer returns the weighted average of the value vectors stored at those positions. Because a weighted average is smooth, gradient descent can train the projections that produce queries, keys, and values end to end. Running several such lookups in parallel gives multi-head attention. Introduced for neural machine translation so a decoder could consult every source word directly (Bahdanau et al. 2015), attention became the sole position-mixing operation in the Transformer (Vaswani et al. 2017).
Replacing recurrence with all-pairs lookup introduces three new challenges:
- Order blindness: A weighted sum is invariant to permutations of its inputs, so positional information must be injected explicitly.
- Quadratic scaling: Scoring all pairs of \(n\) tokens requires \(O(n^2)\) operations and memory, motivating both IO-aware exact kernels and sub-quadratic approximations.
- Mechanistic interpretation: Attention weights show where a head reads, not what function it computes across layers.
The first three sections construct the layer: differentiable key–value lookup (Section 10.1), scaled dot-product scoring and boolean masking (Section 10.2), and multi-head self-attention (Section 10.3). Section 10.4 addresses sequence order through absolute, rotary (RoPE), and relative (ALiBi) positional encodings. The next two sections address computational scale: Section 10.5 derives tiled online-softmax kernels (FlashAttention) that avoid materializing the \(n \times n\) score matrix, and Section 10.6 examines sliding-window and linear attention variants. Finally, Section 10.7 analyzes trained attention circuits through the residual stream, QK/OV decompositions, and two-layer induction heads, and Section 10.8 surveys extensions and primary literature.
Readers heading directly to Chapter 11 need only the first four sections and the residual-stream formulation at the start of Section 10.7; the sections on computational cost can be read alongside Section 11.3 and Chapter 12.