6.4 — Multi-head attention (MHA)
Goal: Derive multi-head attention as h parallel copies of scaled dot-product attention operating on disjoint subspaces of dimension d/h. Understand why we split the heads rather than running a single d-dimensional attention, and count the parameters of the full sub-layer.
1. Why this session exists
A single attention head produces one attention pattern per query: each query distributes its weight across keys in one way. Empirically this turns out to be too constraining — a token often needs to attend to several different things simultaneously. A subject needs to attend to its verb (for tense agreement) and its modifying adjectives (for noun-phrase identity) and its discourse antecedent (for coreference). A single softmax-normalised distribution cannot do all three at once: probability mass spent on one pattern is mass not spent on another.
Multi-head attention (MHA) is the architectural fix: run copies of the scaled dot-product attention of 6.2 in parallel, each on its own subspace of size , then concatenate and project. Each head produces its own attention pattern, so the layer outputs independent mixtures of values per token.
The derivation in §2 is mechanical; the interpretation in §4 is what makes the design memorable. The whole construction is one of the cleanest "trivial-looking trick that matters" moves in deep learning history.[2, 3, 4, 6]
2. The MHA operation
Fix the hidden size and the number of heads , with the per-head dimension. Each head has its own three projection matrices:
Given input , each head computes:
The head outputs are then concatenated along the feature axis and projected back to dimension by a final output matrix :
The concatenation produces a matrix of shape ; the output projection mixes information across heads back into the model's main dimension.
2.1 Implementation: one big GEMM, not small ones
In code, MHA is not implemented as separate GEMMs. The standard implementation packs the per-head projections into single matrices:
each formed by horizontally concatenating the per-head matrices. Then one big multiply gives a matrix, which is reshaped to and treated as heads. The reshape and a per-head softmax are essentially free on the GPU; the expensive parts are the same matrix multiplies as for a single head with hidden size .
So MHA at the level of compute is "scaled dot-product attention applied along an extra batch axis." That batch axis is what makes the multi-head trick free in compute relative to single-head — it does no more work than a single-head attention with the same total dimension.
3. Parameter count
Four matrices: each in , and . Total:
(Ignoring biases, which are typically omitted in modern Transformers.) Independent of . Splitting into more heads does not add parameters. Each head has parameters, times heads, gives — back to where we started. Plus for gives . The parameter budget per attention sub-layer is fixed.
3.1 What you do trade off
If is independent of parameter count, what does increasing cost?
- Per-head expressiveness. Each head's has only params; large means small and a less expressive single head. Tiny (say 8 or 16) saturates softmax less but represents narrower subspaces.
- Compute is unchanged. Total FLOPs are regardless of (the score matrix is still per head, total , with matrix dimension; the product gives the same ).
- Memory is roughly unchanged. The attention matrix is per head, total. This is the same as a single-head attention of dimension which would have an "implicit" pattern smoothed out by the larger projection.
The standard choice is — independent of . So as models grow, the number of heads grows with (LLaMA-7B: ; LLaMA-70B: ). The default was popularised by AIAYN and has remained sticky for two reasons:
- It is small enough that the scaling (6.2 §4) is not too extreme.
- It is large enough that each head expresses meaningful subspaces.
4. Why we don't fuse the heads: heads attend to different things
The architectural payoff of MHA is that different heads learn different attention patterns, and a forward pass produces all of them in parallel. A single-head attention of the same total dimension would learn only one pattern per layer.
Empirical work since the original paper has shown that, in trained Transformers, individual heads specialise:
- Some heads attend to the immediately previous token (a "shift" pattern, useful for n-gram-like statistics).
- Some attend to syntactic dependencies — e.g. the head of a noun phrase.
- Some implement induction heads (Olsson et al., 2022)[5], which copy a previous occurrence of the current token's "successor" — the building block of in-context learning.
- Some attend uniformly (a "do nothing" head).
- Some attend to a
[BOS]token as a no-op sink.
The interpretability literature (Cap 11) has by now catalogued many recurring head roles. None of them require multi-head a priori; the point is that a single dimension- softmax could not express several of these patterns simultaneously, while parallel dimension- softmaxes can.
4.1 Why a single big head fails
Suppose we used one head of size instead of heads of size . The parameter budgets match ( in both cases). What changes?
The single-head attention computes a single matrix of weights: row is one probability distribution over the keys for query . The output of the layer at position is rank-1 in the value space — it is one weighted combination of value rows.
The multi-head attention computes matrices , each a separate distribution per query, and concatenates the outputs. The output at position is rank-up-to- in the value space — it is the concatenation of different weighted combinations, projected by .
So MHA does not just split a budget — it produces qualitatively more output capacity per attention sub-layer at the same parameter count. That is the structural reason every Transformer uses it.
5. Number of heads in practice
| Model | | | | | --- | --- | --- | --- | | GPT-2 small | 768 | 12 | 64 | | GPT-2 medium | 1024 | 16 | 64 | | GPT-3 175B | 12288 | 96 | 128 | | LLaMA 7B | 4096 | 32 | 128 | | LLaMA 70B | 8192 | 64 | 128 | | Mistral 7B | 4096 | 32 | 128 |
The pattern: , scales with . Other configurations exist (LLaMA-3 uses ; Mamba-style models have no in this sense; small GPT-2 sticks with ), but the centre of mass is here.
For efficient inference, modern LLMs increasingly use grouped-query attention (GQA) or multi-query attention (MQA), where has the full heads but and are shared across heads or across groups of heads. This is a memory-bandwidth optimisation for the KV cache at inference — covered in 6.14 in Part 2. The training-time mathematics are unchanged from MHA above.
6. What we keep going forward
Three sentences capture MHA for everything that follows:
- Multi-head attention is parallel copies of scaled dot-product attention on disjoint -dim subspaces, concatenated and projected.
- Total parameters of the sub-layer are , independent of .
- Different heads learn different attention patterns — the qualitative payoff of the design.
We have specified what attention computes; the remaining sessions in Part 1 specify how the inputs and outputs are constrained: causal masking (6.5), positional encoding (6.6–6.7), and the per-position FFN that completes the block (6.8).
(a) Confirm that for heads with and projections , the total parameter count of all three matrix families is , independent of . Then add to recover .
(b) A Transformer has and you experiment with . For each, give and the per-head softmax temperature induced by the scaling. Which configuration's softmax saturates fastest at initialisation?
(c) Show that single-head attention with hidden size produces, at each query position, a single convex combination of the rows of . Then show that MHA with heads produces a vector that is the projection of such combinations. Why does the latter have higher rank in the value space?
(d) A Transformer block can be written as a sum: (this is the pre-norm shape we will see in 6.10). Identify which residual stream each multi-head output is written into, and explain why this is consistent with "different heads do different things."
(e) For LLaMA 70B (), compute the parameter count of one MHA sub-layer (4 weight matrices, no biases). Compare with one FFN sub-layer of the same model assuming (we'll formalise this in 6.8).
References
- [1]
Goodfellow, I., Bengio, Y., & Courville, A. (2016). Deep Learning. MIT Press. — General reference for Chapter 2; specifically §6 (deep feed-forward networks), §8 (optimization), §6.4 (UAT). deeplearningbook.org
↩ - [2]
Prince, S. J. D. (2023). Understanding Deep Learning, §12 (Sequence-to-Sequence Models) and §13 (Transformers). MIT Press. — Attention as soft lookup (6.1), scaled dot-product attention (6.2), multi-head attention (6.4).
↩ - [3]
Raschka, S. (2024). Build a Large Language Model (From Scratch), Chapters 3–4. Manning. — Self-attention implementation (6.3, 6.4), causal masking (6.5), pre-norm block (6.10–6.11).
↩ - [4]
Vaswani, A., Shazeer, N., Parmar, N., et al. (2017). "Attention is all you need". NeurIPS. arXiv:1706.03762 — The Transformer paper. Scaled dot-product attention (6.2), multi-head attention (6.4), encoder–decoder cross-attention (6.3), sinusoidal positional encoding (Appendix 6.A), the FFN sub-layer (6.8), post-LN block diagram (6.10), full architecture read (6.11).
↩ - [5]
Olsson, C., Elhage, N., Nanda, N., et al. (2022). "In-context learning and induction heads". Anthropic. transformer-circuits.pub — Induction heads as the mechanism behind in-context learning (6.4 §4); residual-stream view (6.11 §4).
↩ - [6]
Alammar, J. (2018). "The illustrated Transformer". jalammar.github.io — Canonical visual walkthrough (6.4, 6.8).
↩