Unit 2 · Architecture
Lesson 06 · Available to read
Self-Attention and Multi-Head Attention in Depth
The mathematics of attention step by step: queries, keys, values, scaled dot-products, causal masks and multiple heads.
Lesson 5 gave the intuition: every token looks at the others and pulls in what's relevant. Now we open the box. By the end of this lesson you'll be able to compute attention by hand for a tiny example — and you'll understand every symbol in the most famous formula in modern AI:
Attention(Q, K, V) = softmax(QKᵀ / √d) · V
Queries, keys and values
Attention borrows an idea from databases and search. Each token produces three different vectors from its current residual-stream vector x, using three learned weight matrices:
- Query
q = x · W_Q— what am I looking for? - Key
k = x · W_K— what do I contain? (my label) - Value
v = x · W_V— what will I hand over if someone attends to me?
A useful analogy is a library: your query is the question you bring, each book's key is its catalogue entry, and the value is the book's actual content. You compare your question to every catalogue entry, then read mostly from the best matches.
Keys and values are separate on purpose: what makes a token relevant (key) isn't necessarily the information it should contribute (value).
The four steps
For one token attending over the sequence:
- Score — dot product of its query with every key:
scoreⱼ = q · kⱼ. A large dot product means "this key matches what I'm looking for". - Scale — divide by √d, where d is the key dimension. Without this, dot products of long vectors get very large, softmax becomes nearly one-hot, and gradients vanish.
- Normalize — softmax over the scores, giving attention weights that are positive and sum to 1.
- Blend — output = Σⱼ weightⱼ × vⱼ, a weighted average of the values.
Doing this for all tokens at once is just matrix multiplication: stack the queries into Q, keys into K and values into V, and the formula above computes every token's output in one go — which is exactly what GPUs are good at.
A worked example
Three tokens, key dimension d = 2. We compute the output for token 3, whose query is q = (1, 0).
- keys: k₁ = (1, 0), k₂ = (0, 1), k₃ = (1, 1)
- values: v₁ = (1, 0), v₂ = (0, 1), v₃ = (1, 1)
Step 1 — scores: q·k₁ = 1, q·k₂ = 0, q·k₃ = 1. Step 2 — scale by √2 ≈ 1.414: (0.707, 0, 0.707). Step 3 — softmax: e^0.707 ≈ 2.028, e⁰ = 1, so the sum ≈ 5.056 and the weights ≈ (0.401, 0.198, 0.401). Step 4 — blend: 0.401·(1, 0) + 0.198·(0, 1) + 0.401·(1, 1) ≈ (0.80, 0.60).
Token 3 drew mostly on tokens 1 and 3, whose keys matched its query, and a little on token 2.
The causal mask
A language model must predict the next token without peeking at it. During training, the whole sequence is processed in parallel, so we need to stop each position from attending to positions after it.
The trick: before the softmax, set every score where key position > query position to −∞. Since e^(−∞) = 0, those positions get exactly zero weight. The resulting attention matrix is lower-triangular.
This causal mask is what makes a decoder-only transformer a next-token predictor — and it's why, in Lesson 5's example, "it" couldn't see "tired".
Multi-head attention
One attention operation produces one weighting pattern per token. But a token may need several kinds of information at once: its grammatical subject, the previous word, the entity a pronoun refers to.
Multi-head attention runs h attention operations in parallel, each with its own smaller W_Q, W_K, W_V (dimension d/h). Their outputs are concatenated and mixed by an output matrix W_O.
With d = 4,096 and 32 heads, each head works in 128 dimensions — the total cost is about the same as one big head, but the model gets 32 different ways to look. Researchers have found heads that track the previous token, copy repeated patterns ("induction heads"), or link pronouns to their referents. No one designs these roles; they are learned.
Cost: the quadratic catch
For a sequence of n tokens, the score matrix QKᵀ is n × n. Doubling the context length quadruples the attention compute and memory. This is the main reason long context windows are hard and expensive — the subject of Lesson 7.
Self-attention vs. cross-attention
Everything above is self-attention: queries, keys and values all come from the same sequence. In encoder–decoder models, cross-attention takes queries from one sequence (the translation being written) and keys/values from another (the source sentence). Multimodal models use the same idea to let text attend to image features.
The takeaway
Attention lets each token ask a question (query), compare it with every earlier token's label (key), and collect a weighted blend of their content (value): softmax(QKᵀ/√d)·V — with a causal mask to hide the future and many heads running in parallel.
Practice
0 of 8 attempted
- 1Recall
State in one phrase each what the query, key and value of a token represent.
Saved in this browser
- 2Calculate
Using the lesson's keys and values (k₁=(1,0), k₂=(0,1), k₃=(1,1); v₁=(1,0), v₂=(0,1), v₃=(1,1)) and d = 2, compute the attention output for a token whose query is q = (0, 2).
Saved in this browser
- 3Explain in your own words
Why do we divide the scores by √d before the softmax? What would go wrong without it?
Saved in this browser
- 4Multiple choice
In a causal attention matrix for a 5-token sequence, how many query–key pairs are allowed (not masked)?
- 5Explain in your own words
Explain how the causal mask is implemented and why setting scores to −∞ (rather than, say, 0) is the right choice.
Saved in this browser
- 6Calculate
A model has d = 5,120 and 40 attention heads. What is the dimension of each head? If the context length goes from 8,000 to 32,000 tokens, by what factor does the size of each attention score matrix grow?
Saved in this browser
- 7Apply
Write a short paragraph, as if teaching a friend, explaining multi-head attention using an analogy of your own (not the library one).
Saved in this browser
- 8Recall
Write the attention formula from memory and label each part.
Saved in this browser