AI / ML Theory
Chapter 6 · 20 min

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 hh copies of the scaled dot-product attention of 6.2 in parallel, each on its own subspace of size d/hd/h, then concatenate and project. Each head produces its own attention pattern, so the layer outputs hh 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 dd and the number of heads hh, with dh:=d/hd_h := d / h the per-head dimension. Each head ℓ∈{1,…,h}\ell \in \{1, \dots, h\} has its own three projection matrices:

WQ(ℓ)∈Rd×dh,WK(ℓ)∈Rd×dh,WV(ℓ)∈Rd×dh.W_Q^{(\ell)} \in \mathbb{R}^{d \times d_h}, \qquad W_K^{(\ell)} \in \mathbb{R}^{d \times d_h}, \qquad W_V^{(\ell)} \in \mathbb{R}^{d \times d_h}.

Given input X∈RT×dX \in \mathbb{R}^{T \times d}, each head computes:

headℓ=Attn ⁣(XWQ(ℓ), XWK(ℓ), XWV(ℓ))∈RT×dh.\text{head}_\ell = \text{Attn}\!\left( X W_Q^{(\ell)},\ X W_K^{(\ell)},\ X W_V^{(\ell)} \right) \in \mathbb{R}^{T \times d_h}.

The hh head outputs are then concatenated along the feature axis and projected back to dimension dd by a final output matrix WO∈Rd×dW_O \in \mathbb{R}^{d \times d}:

 MHA(X)=Concat ⁣(head1,…,headh)WO∈RT×d. \boxed{\ \text{MHA}(X) = \text{Concat}\!\left( \text{head}_1, \dots, \text{head}_h \right) W_O \in \mathbb{R}^{T \times d}. \ }

The concatenation produces a matrix of shape T×(h⋅dh)=T×dT \times (h \cdot d_h) = T \times d; the output projection mixes information across heads back into the model's main dimension.

2.1 Implementation: one big GEMM, not hh small ones

In code, MHA is not implemented as hh separate GEMMs. The standard implementation packs the per-head projections into single matrices:

WQ∈Rd×d,WK∈Rd×d,WV∈Rd×d,W_Q \in \mathbb{R}^{d \times d}, \quad W_K \in \mathbb{R}^{d \times d}, \quad W_V \in \mathbb{R}^{d \times d},

each formed by horizontally concatenating the hh per-head matrices. Then one big multiply Q=XWQQ = X W_Q gives a T×dT \times d matrix, which is reshaped to T×h×dhT \times h \times d_h and treated as hh 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 dd.

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: WQ,WK,WVW_Q, W_K, W_V each in Rd×d\mathbb{R}^{d \times d}, and WO∈Rd×dW_O \in \mathbb{R}^{d \times d}. Total:

 #θMHA=4d2. \boxed{\ \#\theta_\text{MHA} = 4 d^2. \ }

(Ignoring biases, which are typically omitted in modern Transformers.) Independent of hh. Splitting into more heads does not add parameters. Each head has 3d⋅dh3 d \cdot d_h parameters, times hh heads, gives 3d⋅(h dh)=3d23 d \cdot (h\, d_h) = 3 d^2 — back to where we started. Plus d2d^2 for WOW_O gives 4d24 d^2. The parameter budget per attention sub-layer is fixed.

3.1 What you do trade off

If hh is independent of parameter count, what does increasing hh cost?

  • Per-head expressiveness. Each head's WQ(ℓ),WK(ℓ),WV(ℓ)W_Q^{(\ell)}, W_K^{(\ell)}, W_V^{(\ell)} has only 3d⋅dh3 d \cdot d_h params; large hh means small dhd_h and a less expressive single head. Tiny dhd_h (say 8 or 16) saturates softmax less but represents narrower subspaces.
  • Compute is unchanged. Total FLOPs are Θ(T2d)\Theta(T^2 d) regardless of hh (the score matrix is still T×TT \times T per head, total T×T×hT \times T \times h, with dhd_h matrix dimension; the product gives the same T2dT^2 d).
  • Memory is roughly unchanged. The attention matrix is T×TT \times T per head, h⋅T2h \cdot T^2 total. This is the same as a single-head attention of dimension dd which would have an h⋅T2h \cdot T^2 "implicit" pattern smoothed out by the larger projection.

The standard choice is dh=64d_h = 64 — independent of dd. So as models grow, the number of heads hh grows with dd (LLaMA-7B: d=4096,h=32,dh=128d = 4096, h = 32, d_h = 128; LLaMA-70B: d=8192,h=64,dh=128d = 8192, h = 64, d_h = 128). The dh=64d_h = 64 default was popularised by AIAYN and has remained sticky for two reasons:

  1. It is small enough that the dh≈8\sqrt{d_h} \approx 8 scaling (6.2 §4) is not too extreme.
  2. 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-dd softmax could not express several of these patterns simultaneously, while hh parallel dimension-dhd_h softmaxes can.

4.1 Why a single big head fails

Suppose we used one head of size dd instead of hh heads of size d/hd/h. The parameter budgets match (WQ,WK,WV∈Rd×dW_Q, W_K, W_V \in \mathbb{R}^{d \times d} in both cases). What changes?

The single-head attention computes a single matrix A∈RT×TA \in \mathbb{R}^{T \times T} of weights: row ii is one probability distribution over the TT keys for query ii. The output of the layer at position ii is rank-1 in the value space — it is one weighted combination of value rows.

The multi-head attention computes hh matrices A(ℓ)∈RT×TA^{(\ell)} \in \mathbb{R}^{T \times T}, each a separate distribution per query, and concatenates the outputs. The output at position ii is rank-up-to-hh in the value space — it is the concatenation of hh different weighted combinations, projected by WOW_O.

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 | dd | hh | dhd_h | | --- | --- | --- | --- | | 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: dh∈{64,128}d_h \in \{64, 128\}, hh scales with dd. Other configurations exist (LLaMA-3 uses dh=128d_h = 128; Mamba-style models have no hh in this sense; small GPT-2 sticks with dh=64d_h = 64), but the centre of mass is here.

For efficient inference, modern LLMs increasingly use grouped-query attention (GQA) or multi-query attention (MQA), where QQ has the full hh heads but KK and VV 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:

  1. Multi-head attention is hh parallel copies of scaled dot-product attention on disjoint d/hd/h-dim subspaces, concatenated and projected.
  2. Total parameters of the sub-layer are 4d24 d^2, independent of hh.
  3. 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).

Self-test

(a) Confirm that for hh heads with dh=d/hd_h = d/h and projections WQ(ℓ),WK(ℓ),WV(ℓ)∈Rd×dhW_Q^{(\ell)}, W_K^{(\ell)}, W_V^{(\ell)} \in \mathbb{R}^{d \times d_h}, the total parameter count of all three matrix families is 3d23 d^2, independent of hh. Then add WOW_O to recover 4d24 d^2.

(b) A Transformer has d=4096d = 4096 and you experiment with h=8,h=32,h=128h = 8, h = 32, h = 128. For each, give dhd_h and the per-head softmax temperature induced by the dh\sqrt{d_h} scaling. Which configuration's softmax saturates fastest at initialisation?

(c) Show that single-head attention with hidden size dd produces, at each query position, a single convex combination of the TT rows of VV. Then show that MHA with hh heads produces a vector that is the projection of hh such combinations. Why does the latter have higher rank in the value space?

(d) A Transformer block can be written as a sum: output(x)=x+MHA(x)+FFN(x+MHA(x))\text{output}(x) = x + \text{MHA}(x) + \text{FFN}(x + \text{MHA}(x)) (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 (d=8192,h=64,dh=128d = 8192, h = 64, d_h = 128), 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 dff=4dd_\text{ff} = 4 d (we'll formalise this in 6.8).

[1]

References

  1. [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. [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. [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. [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. [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. [6]

    Alammar, J. (2018). "The illustrated Transformer". jalammar.github.io — Canonical visual walkthrough (6.4, 6.8).

    ↩