The problem attention solves
Before transformers, translation used encoder-decoder RNNs. Their flaw: the RNN must squeeze the entire input into a single final hidden state (a "memory cell") before the decoder can use it, and it can't reach back to earlier states — so context is lost on long or complex sentences.
Key concept · From Bahdanau attention to self-attention
The first fix was Bahdanau attention (2014): let the decoder selectively access different parts of the input at each step, weighting the important tokens. Three years later, researchers found RNNs weren't needed at all and introduced the transformer's self-attention. The "self" means it relates different positions within a single sequence to each other (word-to-word in one sentence), rather than between two separate sequences. Self-attention lets each position attend to all positions in the same sequence when building its representation.
Key concept · Context vectors — the goal
The output of self-attention is a context vector z for each input token: an enriched embedding that blends in information from all the other tokens in the sequence, weighted by relevance. Where a plain token embedding knows only about itself, a context vector for "journey" also carries information about "Your", "starts", and every other word — exactly the relational understanding an LLM needs to predict the next token.
The mechanism, without trainable weights
To build intuition, the book first codes self-attention with no learnable parameters. It's three steps: attention scores → attention weights → context vector.
Key concept · Scores, weights, and the weighted sum
(1) Attention scores: for a chosen query token, compute the dot product of its embedding with every input token's embedding. The dot product is a similarity measure — higher means the two vectors are more aligned, so the tokens attend to each other more. (2) Attention weights: normalize the scores with softmax so they're positive and sum to 1 (softmax handles extreme values better than naive division and gives good gradients). (3) Context vector: take the weighted sum of all input embeddings using those weights. Repeat for every token — efficiently, this is just matrix multiplication: scores = inputs @ inputs.T, then softmax per row, then weights @ inputs.
Scaled dot-product attention
The version used in real LLMs (and the original transformer) adds trainable weight matrices, so the model can learn to build good context vectors. This is scaled dot-product attention.
Key concept · Query, key, and value
Three learnable matrices — Wq, Wk, Wv — project each input embedding into three roles. The query (q) is the current token "asking" for relevant information; the key (k) is what each token "offers" to be matched against; the value (v) is the actual content that gets aggregated. Attention scores are now the dot products of the query with every key; the resulting weights are applied to the values to produce the context vector. (Note: "weight" in Wq/Wk/Wv means trainable network parameters — distinct from the dynamic, context-specific attention weights.)
Key concept · The scaling, and the compact class
Before softmax, the query·key scores are divided by the square root of the key dimension (√dk) — hence "scaled." Without scaling, large dot products push softmax into regions with tiny gradients, slowing learning; scaling keeps the distribution well-behaved. In code this becomes a tidy SelfAttention class, implemented with nn.Linear layers (which give better weight initialization than raw nn.Parameter) — a reusable module that computes context vectors for a whole batch at once.
Hiding the future
For a text-generating model, a token must not "see" tokens that come after it — otherwise predicting the next word would be cheating. Causal attention (a.k.a. masked attention) enforces this.
Key concept · The causal mask and dropout
Causal attention restricts each position to attend only to itself and earlier positions. Implementation: after computing the attention scores, mask out the future — set the upper-triangular entries (positions after the current one) to −∞ before softmax, so they receive zero weight; the remaining weights are renormalized to sum to 1. On top of the mask, the book applies dropout to the attention weights — randomly zeroing some of them during training — to reduce overfitting and avoid the model over-relying on any single attention connection.
Many attention patterns at once
The final variant, and the one the GPT model uses, is multi-head attention — running several causal-attention mechanisms in parallel.
Key concept · Heads, subspaces, and concatenation
A single attention "head" captures one kind of relationship. Multi-head attention stacks several heads, each with its own Wq/Wk/Wv, so the model can attend to information from different representation subspaces at once — one head might track syntax, another long-range references. Each head produces its own set of context vectors; these are concatenated to form the output. Conceptually you could stack separate attention modules, but the efficient implementation uses a single set of larger matrices and splits them into heads by reshaping — one matrix multiply instead of many. This multi-head causal-attention module is exactly what gets plugged into the GPT architecture in Chapter 4.
Chapter 3 quiz
Fifteen questions on self-attention, Q/K/V, causal masking, and multi-head attention. Answer first, then expand Show answer.
Part A · Multiple choice
The key limitation of encoder-decoder RNNs that motivated attention was:
- A Compressing the whole input into one hidden state, with no access to earlier states
- B They were too fast
- C They used too little memory
- D They couldn't be trained
Show answer
A. Context is lost on long sequences.
The "self" in self-attention means it relates:
- A Different positions within the same sequence
- B Two separate sequences
- C A model to itself
- D Input to output only
Show answer
A. Word-to-word within one sentence, versus cross-sequence attention.
A context vector is:
- A An enriched embedding blending information from all other tokens
- B A token ID
- C The loss value
- D A positional embedding
Show answer
A. The output of self-attention for each token.
In simplified self-attention, attention scores are computed as:
- A Dot products between token embeddings (a similarity measure)
- B Random values
- C Token IDs
- D The softmax of the inputs
Show answer
A. Higher dot product = more aligned = more attention.
Attention scores are turned into attention weights using:
- A Softmax (so they're positive and sum to 1)
- B ReLU
- C Rounding
- D The mean
Show answer
A. Softmax handles extreme values and gives good gradients.
The context vector is computed as:
- A A weighted sum of the (value) vectors using the attention weights
- B The largest input
- C The query alone
- D A random pick
Show answer
A.
The three trainable matrices in scaled dot-product attention project inputs into:
- A Query, key, and value vectors
- B Token, position, segment
- C Input, hidden, output
- D Score, weight, context
Show answer
A. W_q, W_k, W_v.
Why divide the scores by √d_k before softmax?
- A Large dot products otherwise push softmax into tiny-gradient regions, slowing learning
- B To make them bigger
- C It's required by PyTorch
- D No reason
Show answer
A. Scaling keeps the distribution well-behaved — hence "scaled" dot-product attention.
Causal (masked) attention ensures each token attends only to:
- A Itself and earlier tokens
- B All tokens including future ones
- C Only the last token
- D Only future tokens
Show answer
A. So next-word prediction can't peek ahead.
Part B · True or false
The causal mask sets future-position scores to −∞ before softmax so they get zero weight.
Show answer
True. The remaining weights are then renormalized to sum to 1.
Dropout on attention weights helps reduce overfitting during training.
Show answer
True. It randomly zeroes some attention connections.
"Weight parameters" (W_q/W_k/W_v) and "attention weights" are the same thing.
Show answer
False. Weight parameters are learned network coefficients; attention weights are dynamic, context-specific values.
Multiple attention heads let the model attend to different representation subspaces at once.
Show answer
True. Each head has its own W_q/W_k/W_v; their outputs are concatenated.
Part C · Short answer
State the roles of query, key, and value.
Show answer
Query = the current token seeking information; key = what each token offers to be matched against (query·key gives the scores); value = the content aggregated into the context vector.
List the four attention variants the chapter builds, in order.
Show answer
Simplified self-attention → self-attention with trainable weights (scaled dot-product) → causal (masked) attention → multi-head attention.