Multi-Head Attention
After this lesson, you will be able to:
- Understand why one attention head is not enough, and how multiple heads fix this
- See how each head focuses on a different type of pattern (grammar, meaning, position, etc.)
- Grasp the dimension budget: the total size stays the same, you just slice it into more pieces
- Follow how head outputs get combined back into a single representation
- Compare MHA, MQA, and GQA — the efficiency tricks that make real LLMs affordable
- Reason about the tradeoff: more heads vs. larger heads
Before you start
#Eight Pairs of Eyes
A single attention head computes one set of attention weights. It can capture one type of pattern, maybe positional proximity or maybe subject-verb agreement. But language (and data in general) has many simultaneous relationships happening at once. The word "it" in "The animal didn't cross the street because it was too tired" needs to track coreference (it = animal), syntax (it = subject), and semantics (tired = animate) all at the same time. One head is not enough.
#How It Works
The idea is elegant and computationally efficient:
#Step 1: Split the Dimensions
#Step 2: Independent QKV Projections
Each head has its own W_Q, W_K, W_V weight matrices. Head 1 projects input into its own 64-dimensional subspace. Head 2 projects into a different 64-dimensional subspace. The projections are learned independently during training, so each head can specialize.
#Step 3: Parallel Attention
Run scaled dot-product attention independently on each head, in parallel. Head 1 computes its own attention pattern. Head 2 computes a different pattern. All 8 heads execute simultaneously on the GPU, which is embarrassingly parallel.
#Step 4: Concatenate
Take the output from all heads (each of shape [seq_len x 64]) and concatenate them along the last dimension. Result: [seq_len x 512]. We are back to the full model dimension, but now each token carries information from 8 different attention perspectives.
#Step 5: Output Projection
Multiply by a final weight matrix W_O of shape [512 x 512]. This is the critical step that mixes information across heads. Without it, each head's contribution would remain isolated in its own 64-dimensional subspace. W_O lets the model combine insights from all heads into a unified representation.
#The Equations
Where each head is:
bhqd, bhkd -> bhqk into the dot-product scores you saw above.Before the heads multiply, here is a single head worked end to end on five tokens.
- Do: Press Next through the five stages: embeddings, Q K V, scores, softmax and weighted sum. At the softmax stage, check that each row adds up to 1.
- Notice: Scores are divided by √3 because d_k is 3. After the softmax every row sums to 1, and each output row is a weighted average of the V rows.
- Why: The arithmetic is real, but W_Q, W_K and W_V are hand-picked values, not learned ones, and a real head uses a d_k such as 64. Drawn stand-in, not a trained model: this is one head on one tiny example.
#The Dimension Budget
Here is the key constraint that keeps multi-head attention efficient:
The total parameter count stays roughly the same regardless of how many heads you use (ignoring the output projection). With 8 heads of dimension 64 or 16 heads of dimension 32, you are projecting the same 512-dimensional input. You are just slicing it differently.
More heads means each head works in a lower-dimensional subspace. Fewer heads means each head has more dimensions to work with. The tradeoff: more heads give you more diverse attention patterns, but each head has less capacity to model complex relationships within its subspace.
If we doubled the number of heads from 8 to 16 but halved each head's dimension from 64 to 32, what happens to the total computation?
#How Many Patterns Can One Head Express?
Shrinking d_k has a hard geometric cost. A head scores every pair of tokens with Q K^T, and that score table cannot be more complicated than the width of the head. The derivation shows the limit, which is the precise sense in which more heads means smaller heads.
#What Do Heads Learn?
Research has shown that different heads naturally specialize during training, without being explicitly told to. In BERT-like models, researchers have found:
- Positional heads attend primarily to adjacent tokens (previous or next word). These capture local context, like bigram patterns.
- Syntactic heads track subject-verb dependencies, even across long distances. In "The keys to the cabinet are", the head attends to "keys" for agreement even though "cabinet" is closer.
- Separator heads focus on special tokens like [SEP] or punctuation. They act as "reset" signals that mark boundaries between segments.
- Rare token heads activate strongly for infrequent vocabulary items, possibly routing them through specialized processing.
- Coreference heads link pronouns to their antecedents ("she" to "Marie").
This specialization emerges purely from training. No one programs the heads to do this. The model discovers that having diverse attention strategies produces better representations.
#Interactive: Visualize Attention Heads
Try different sentences and switch between attention heads using the dropdown. Notice how each head produces a different attention pattern. This is multi-head attention in action. Head 1 might focus on adjacent words while Head 3 might capture longer-range dependencies.
Experiments to try:
- Type "The cat that the dog chased ran away" — nested clauses stress-test heads
- Try "She gave him the book and he read it" — watch for coreference patterns
- Switch between heads on the same sentence — see the diversity of attention patterns
#The Output Projection: Why It Matters
After concatenation, the output passes through one more linear projection W^O. This step is often overlooked but serves a critical purpose: it lets the model mix information across heads.
Without W^O, each head's contribution to the final output would be completely independent, limited to its own d_k-dimensional subspace. With W^O, every head writes into the same d_model-dimensional space. Cut W^O into one block of d_k rows per head and you will see that the output is exactly a sum of per-head writes. That sum is the view mechanistic interpretability uses.
Two things follow. Each head's write can be studied on its own, and the writes are added, not multiplied, so heads do not interact inside this layer. Their combined vector is read by the next layers.
Counting parameters gives a clean result: one multi-head attention layer holds 4 x d_model^2 weights, whatever the number of heads. For d_model = 512 that is 1,048,576 (about 1M), and for d_model = 4096 (GPT-3 scale) it is 67,108,864 (about 67M). The derivation below counts them.
#Modern Efficiency Improvements
#Try It: Multi-Head Attention in Code
Attention Is All You Need
Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Lukasz Kaiser, Illia Polosukhin (2017)
Section 3.2.2 introduces multi-head attention. The paper's key insight is that projecting to multiple lower-dimensional subspaces is more effective than a single full-dimensional attention function.
GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints
Joshua Ainslie, James Lee-Thorp, Michiel de Jong, Yinfei Yang, Sumit Sanghai, Santiago Ontanon (2023)
Introduces Grouped-Query Attention, the compromise between MHA and MQA that is now standard in modern LLMs like LLaMA 2/3 and Mistral.
#Key Takeaways
- Multiple heads let the model attend to different relationship types simultaneously. One head might capture syntactic dependencies (subject-verb), another semantic similarity, and another positional proximity
- Heads operate in parallel on different subspaces. The model dimension is split evenly across heads (d_model = num_heads x d_k), so multi-head attention costs the same as single-head attention with full dimensionality
- Concatenation and output projection combine all heads. After each head computes its attention independently, results are concatenated and projected through a learned matrix to produce the final output
- GQA and MQA reduce memory during inference. By sharing Key/Value projections across groups of heads, Grouped-Query Attention and Multi-Query Attention dramatically reduce the KV cache size for serving large language models
#Quick Check
Why does multi-head attention use multiple heads instead of one large attention computation?