Chapter 7: Multi-Head Attention¶
Figure 7.1: We run multiple attention heads at the same time to gather richer context.
In Chapter 6, we built one attention head, which acts as a single "reader" scanning the text. But one reader is rarely enough to catch everything. In this chapter you will:
- Run multiple attention heads in parallel.
- Understand how different heads learn to track different patterns.
- Concatenate their outputs into a single rich representation.
Words to Know
- Multi-Head Attention: Running several attention heads at the same time, so the same text is read in several different ways.
- Concatenation: Joining several lists of numbers end to end to make one longer list.
- Projection: A final step that blends the heads' joined outputs into one list of numbers for each token.
Theory¶
One Reader Isn't Enough¶
Figure 7.2: Each head reads the same input through its own filters, and their outputs are concatenated and projected.
When you read a sentence, you track multiple things at once:
- Who is the subject?
- What action is happening?
- What is the tone, serious or sarcastic?
A single attention head can only "look" for one kind of pattern at a time. Multi-head attention fixes this by running several heads in parallel (Figure 7.2). Think of it as a team of readers, each highlighting different details, who then combine all their notes.
How It Works¶
Multi-head attention repeats the mechanism from Chapter 6:
- Run 4 independent attention heads (each one a
SingleHeadAttentionfrom Chapter 6) on the same input. - Each head produces an output of 32 numbers (
head_size). - Glue (concatenate) all 4 outputs together:
4 heads × 32 numbers = 128 numbers. - Apply a final projection, one more step that blends them.
Because each head starts with different random weights (its own Q, K, and V filters), no two heads ever see the text the same way, and training pushes them further apart.
Why Four Heads and Not One Big One¶
Four readers sound expensive, and people are often surprised by what they cost.
A head's filters are sized by its head_size, not by the full 128 channels. Split 128 channels across four heads and each head gets filters that are a quarter as wide. Multiply it out and the totals match exactly:
| src/examples/ch07_head_budget.py | |
|---|---|
$ python src/examples/ch07_head_budget.py
4 heads of 32: 49,152 numbers
1 head of 128 : 49,152 numbers
Same budget: True
Four points of view cost the same as one, so every model in this family uses many heads.
Do the Heads Really Differ?¶
We can check whether they differ on the model you will train in Chapter 13.
The script below loads the trained weights, feeds in a real line of Shakespeare, and prints how much attention the last character pays to each earlier character, one row per head.
| src/examples/ch07_heads_differ.py (excerpt) | |
|---|---|
$ python src/examples/ch07_heads_differ.py
Prompt: "JULIET: O Romeo"
Attention paid by the last character, one row per head:
J U L I E T : _ O _ R o m e o
head 0: 0.02 0.04 0.01 0.06 0.03 0.04 0.04 0.02 0.06 0.04 0.05 0.04 0.11 0.38 0.07
head 1: 0.02 0.02 0.03 0.03 0.04 0.08 0.12 0.06 0.05 0.07 0.02 0.10 0.16 0.14 0.06
head 2: 0.04 0.07 0.04 0.06 0.05 0.11 0.04 0.06 0.09 0.07 0.07 0.06 0.09 0.09 0.06
head 3: 0.03 0.02 0.01 0.05 0.05 0.03 0.03 0.05 0.04 0.04 0.05 0.08 0.12 0.25 0.14
Sharpest focus per head: 0->'e' (0.38) 1->'m' (0.16) 2->'T' (0.11) 3->'e' (0.25)
Head 0 is paying 0.38 of its attention to the character just before the end. The rest it hardly cares about. Head 3 kind of does this as well but not as pronounced. It's splitting its attention between e and the final o. Head 1 shares its attention across the colon, the m and the e. Head 2 pays very little attention to any single character with the largest weight being 0.11 and the smallest being 0.04 which is almost uniform.
So we see that our heads are acting differently but not as nicely as you may have heard. One is sharp, one is more smooth. One is spread out and one is not doing much of anything. In a trained model, some heads do very little. No one made them act this way and we can't promise that head 1 is the "grammar head". These are just 4 different attention heads with their initial values generated by a seed.
Watch Out
You may be tempted to tell yourself a story about what each head is doing: one head is tracking nouns, another is tracking periods. Sometimes, a head really is nicely interpretable like that and researchers have found some in big models. Often it isn't, though, as head 2 makes clear. See the numbers before you weave your tale.
The Output Projection¶
Once the 4 heads are concatenated, we feed the 128 numbers through one last linear layer. This is called the proj layer.
Why do we have this extra layer? Each head may find duplicate information. The projection layer learns that if head 1 and head 3 both found the same pattern, it should give it more weight. And if head 2 is unsure, the projection layer learns to ignore it. This will mix the 4 separate perspectives into a single context vector of 128 numbers. Now that we have the projection in place, the "Attention" stage of our map is complete (Figure 7.1).
Another option would have been to simply take an average of the 4 heads instead of gluing them together. If we did this we would have 32 numbers instead of 128. The problem with doing this is head 0 has a sharp focus on one character while head 2 has a flat spread. If we average these they'll both have some kind of average attention to some characters. By gluing the heads together we allow each head to provide its answer and the projection will learn how much to weight each head's answer.
In Business
Figure 7.3: Multi-head attention gathers different perspectives.
Imagine training an assistant to write emails in your company's house style. You don't just look for one pattern. You monitor tone, formatting, and word choice (Figure 7.3). Multi-head attention does the same thing, but asks 4 different "departments" to analyze the text, before producing a cohesive executive summary.
Code¶
Figure 7.4: The heads run in parallel, get concatenated, and projected.
We use src/ch06_multihead_attention.py to build the MultiHeadAttention class (Figure 7.4).
| src/ch06_multihead_attention.py (excerpt) | |
|---|---|
Running the script compares one head with four:
$ python src/ch06_multihead_attention.py
--- Comparing one head vs multi-head ---
Single head output shape: torch.Size([2, 10, 32]) (head_size=32)
Multi-head output shape: torch.Size([2, 10, 128]) (C=128)
Multi-head output has 4x more channels - it sees 4 perspectives at once.
Multi-head attention done! Ready for Chapter 8.
What just happened:
- Line 2 ran 4 independent attention heads at the same time.
- Line 2's result is that each head produced an output with 32 channels.
- Line 5 concatenated them into 128 channels (the original embedding dimension).
- Line 8 applied the projection, which blends the 128 channels and keeps the shape of the input. The same line also applied dropout, which Chapter 14 explains.
Shape Check: Table 7.1 lists the shapes as the data passes through the heads.
Table 7.1: Tensor shapes during the multi-head attention step.
| Variable | Shape | Meaning |
|---|---|---|
head_outputs |
4 × [B, T, 32] |
A list of outputs from the 4 heads. |
out (after cat) |
[B, T, 128] |
The 4 outputs joined end-to-end. |
out (final) |
[B, T, 128] |
The blended representation, ready for the next step. |
Try It¶
Try It
Edit src/utils/config.py to use 8 heads instead of 4. Set n_heads = 8. Run the script again. Pay attention to how head_size is now automatically set to 16 to keep the final concatenated size at 128 (8 × 16 = 128). We can have more viewpoints, but with less granularity within each one.
Watch Out
Your embedding dimension (n_embd) has to be divisible by your number of heads (n_heads) for multi-head attention to operate cleanly. Setting n_embd = 128 and n_heads = 5 will crash the program, as it won't be able to cleanly divide the channels.
Key Takeaways¶
- Multi-head attention runs several single-head attention modules in parallel.
- Splitting the channels across heads costs nothing: four heads of 32 hold the same 49,152 numbers as one head of 128.
- The heads do end up different, but not in a tidy way. In our trained model one head is sharp, one is soft and one is close to flat.
- The outputs are concatenated, not averaged, so that no head's answer is diluted by the others before the projection can weigh it.
- A final linear projection blends the separate perspectives.
- The output shape
[B, T, C]is exactly the same as the input shape, so layers stack easily.
Check Your Understanding¶
- Why is one attention head not enough to understand complex text?
- If
n_embd = 256andn_heads = 8, what is thehead_size? - Four heads of 32 hold the same number of weights as one head of 128. Why does splitting cost nothing?
- Why do we concatenate the heads rather than average them?
- In the run above, head 2's attention was almost flat. What does that tell you about the claim that each head learns its own linguistic role?
- What is the purpose of the final projection layer?
Assignment¶
Assignment 7: Same heads, new word
About 15 minutes. You change one word and write no new code. Work in this chapter's Colab notebook or on your own laptop.
- Run it. Run
src/examples/ch07_heads_differ.pyas it is. Copy the last line it prints, the one that startsSharpest focus per head. - Change one word. Near the top of the file, find
PROMPT = "JULIET: O Romeo". The prompt is the line of text the model reads. ChangeRomeotolove, keep the quotation marks, and run the script again. - Compare. Which character does each head focus on most now? Which heads pick the character just before the last one in both runs? Which two heads have the smallest numbers in both runs?
- Explain it. In two or three sentences a manager could follow, say how the four heads differ, and why it is worth testing a second prompt before you say what job a head does.
Hand in: both Sharpest focus per head lines, your answers to step 3, and your sentences.
Further Reading¶
The architecture this book builds. Reading a sequence one step at a time is slow, because step 500 cannot start until step 499 has finished, and distant words stay hard to connect. This paper removed the step-by-step reading and kept only attention, plus a note of each token's position. Every token can then be processed at once, and that made training on very large amounts of text practical. The model you build in Chapters 6 to 10 is this design, made small.
Vaswani, A., Shazeer, N., Parmar, N., Uszkoreit, J., Jones, L., Gomez, A. N., Kaiser, L., & Polosukhin, I. (2017). Attention is all you need (arXiv:1706.03762). arXiv. https://doi.org/10.48550/arXiv.1706.03762
Next up: Chapter 8: Feed-Forward and Norms