Module 2 · Lesson 2.2 of 2.5
Multi-Head Attention
Lesson 2.1 built one attention operation: one set of queries, keys and values, one softmax per query, one output. Real transformer layers run several of these in parallel on smaller slices of the model width and then recombine them. This lesson traces exactly how that works, tensor by tensor.
Learning goal. By the end you should be able to write the multi-head attention equations with every dimension, trace the shapes from [T, dmodel] through the head split and back, compute dhead, score-tensor sizes and projection parameter counts for any configuration, and explain what changing the head count does and does not change.
Builds on. The single-head equation from 2.1.8: Attention(Q, K, V) = softmax(QKT / √dk + M)V, with the row-vector convention (each row is one token position), the causal mask from 2.1.6 and learned projections from 2.1.2. Those steps are not repeated here.
Simplifications. One layer, one sequence (no batch dimension), biases omitted, contiguous logical tensors, every head the same size. Toy numbers are labelled as such.
Explore this inside the 3D Transformer → Follow the full input through Q/K/V and head sharing; later architecture topics are optional.
2.2.1 Why multiple heads?
The limitation of one head
In single-head attention each query position produces one row of weights: a single probability distribution over the positions it may attend to. Its output is one weighted average of value vectors, all living in the same dv-dimensional space. Suppose a position would benefit from two different pieces of context, found at different positions, that matter for different reasons. One distribution must split its weight between them, and the two contributions are blended into a single averaged vector. The scores that decide the split are also computed from one comparison q·k: one notion of "relevant" per layer. Use the diagram: choose Next to follow one operation at a time, Previous to revisit it, or Reset diagram to return to the shared input. Read the caption after each step; Play advances automatically. This is a two-head schematic, not measured attention weights.
What multiple heads change
Multi-head attention gives the layer H independent attention operations. Each head has its own learned projections into a smaller space of width dhead, its own scores, its own softmax and its own weighted sum. A position can therefore put most of one head's weight on one position and most of another head's weight on a different position, and the two results are kept apart until the output projection combines them. Vaswani et al. describe this as letting the model attend jointly to information from different representation subspaces at different positions, and note that a single head's averaging works against this (Attention Is All You Need, 2017, §3.2.2).
The benefit is representational flexibility: the layer can learn several different ways of comparing and mixing positions. Nothing in the equations forces it to, and nothing assigns a role to a head.
What heads do not guarantee. Heads are not designed modules. A trained head is not "the grammar head" or "the coreference head" by construction; any such description is an after-the-fact interpretation of one trained model, and attention weights alone do not explain a model's reasoning. Heads can also be redundant: for example, Michel et al. (2019) report that many heads in trained models can be removed at test time with little loss on the tasks they measured. Treat "different subspaces" as a capacity the architecture offers, not a description of what each head does.
2.2.2 Splitting dmodel into heads
Every head receives a projection of the whole input vector. The split groups projected columns, not pieces of the original embedding. Use the diagram: this view starts at the head split. Choose Previous to inspect the projection that created those columns, or Next to follow the head results.
Two widths: dmodel and dhead
- dmodel
- The model width: the length of the vector each token carries between layers. That per-token vector, which every layer reads and then adds its result back into, is called the residual stream (the block overview in 2.2.4 shows where the adding happens). The input to attention is X ∈ ℝT×dmodel, and the layer must return the same shape so it can be added back and the next layer can consume it.
- dhead
- The width of one head's query, key and value vectors. In Lesson 2.1's notation each head has dk = dv = dhead. Every head here uses the same dhead for Q, K and V. Lessons 2.3–2.5 call this same number D (head dimension): D = dhead = dk = dv.
- H
- The number of heads. In multi-head attention every head has its own query, key and value, so this is also the number of query heads: from Lesson 2.3 on it is written Hq (H = Hq) to tell it apart from the number of key/value heads, HKV.
- T
- The number of token positions in the sequence.
The common choice, and the one in the original Transformer, is an equal partition of the model width:
With the base Transformer's dmodel = 512 and H = 8, each head works in dhead = 512 / 8 = 64 dimensions. The heads together use all 512 columns: 8 × 64 = 512. Section 2.2.6 covers architectures that choose dhead independently.
One big projection, then a reshape
Conceptually each head i has its own matrices WiQ, WiK, WiV ∈ ℝdmodel×dhead. Placing the H query matrices side by side gives one matrix:
Because matrix multiplication works column by column, Q = XWQ computes all heads' queries at once: columns 0–63 of Q are exactly XW1Q, columns 64–127 are XW2Q, and so on. The same holds for K and V. Implementations therefore run three large matrix multiplications (or one fused one) rather than 3H small ones, then split the result:
- Q = XWQ: [T, 512]
- reshape: [T, 8, 64]
- transpose: [8, T, 64]
Advanced: what reshape and transpose cost in memory
In a row-major [T, 512] tensor, the 512 numbers of a row are adjacent, so viewing them as [T, 8, 64] only changes the indexing arithmetic. The transpose to [8, T, 64] is usually also a view with different strides: element (h, t, c) is still at offset t·512 + h·64 + c. Whether a kernel copies it into a head-major contiguous layout, or reads the strided view directly, is an implementation choice. Frameworks and attention kernels differ here; the logical shapes in this lesson are the same either way.
2.2.3 Attention inside each head
Each head runs exactly the scaled dot-product attention of Lesson 2.1 on its own projected slices. Use the numerical example: choose query position 3: is, then 1: The. Compare the two heads’ highlighted weight rows and outputs. At the first position the causal mask allows only that position; later positions allow different mixtures.
- Qi, Ki, Vi
- Head i's queries, keys and values, each [T, dhead]: the i-th column slice of Q, K, V.
- QiKiT
- Head i's raw scores, [T, T]. Across all heads the score tensor is [H, T, T].
- √dhead
- The scale uses the head width, because each dot product sums dhead terms (the variance argument of 2.1.4). For dhead = 64 the scale is 1/8.
- M
- The same [T, T] causal mask for every head in a decoder.
- headi
- Head i's output, [T, dhead]. All heads together: [H, T, dhead].
The heads do not exchange information: head 3's softmax never sees head 5's scores. That independence is why the head axis is moved to the front. A [H, T, dhead] tensor is a batch of H separate matrix problems, which GPUs run as one batched matrix multiplication.
The compute does not grow with H
Computing one head's scores costs T · T · dhead multiply-adds (T2 dot products of length dhead). All heads: H · T2 · dhead = T2 · dmodel under equal partition, the same as one head of width dmodel. The same holds for AiVi. This is the paper's point that the total cost is similar to single-head attention at full width. What does grow with H is the number of score elements, H · T2, and so the softmax work and the memory needed if the score tensor is stored in full. The explorer in 2.2.5 shows both numbers.
Two heads, one input: a toy example
- What this shows
- Causal two-head attention computed from the same X, with dmodel = 4, H = 2, dhead = 2. Head 1 uses columns h1·0–h1·1 of Q, K, V; head 2 uses h2·0–h2·1.
- Try
- Choose query position t2, then t1 and t0, and compare the two heads' weight rows.
- What to notice
- For t2 the heads spread their weight differently, because each computes scores from different columns. For t0 the causal mask leaves one choice, so both heads give weight 1 to t0.
Step 1: one projection each for Q, K and V, then split by columns
Step 2: each head runs its own scaled, causally masked softmax (scale 1/√2; entries above the diagonal are masked, so their weight is exactly 0)
Step 3: concatenate the head outputs, then multiply by WO
Assumptions: hand-picked toy numbers, not learned weights. X = [[1, 0, 0, 1], [0, 1, 1, 0], [1, 0, 1, 0]]; WK and WV are identity matrices and WQ = 2·I, so head 1 only reads input features f0–f1 and head 2 only f2–f3. WO = [[0.5, 0, 0.5, 0], [0, 0.5, 0, 0.5], [0.5, 0, −0.5, 0], [0, 0.5, 0, −0.5]]. Learned projections mix every feature into every head. Weights and outputs are rounded to 3 decimals.
2.2.4 Concatenation and the output projection WO
After attention, the H head outputs are put back side by side and multiplied by one more learned matrix. Use the diagram: this view starts at concatenation. Next shows the output projection and residual addition; Previous returns to the separate head results. Concatenation joins components without adding them; the residual addition happens afterward.
- Concat(…)
- [T, H·dhead]: row t is head1's row t, then head2's, and so on. In tensor terms: transpose [H, T, dhead] back to [T, H, dhead] and merge the last two axes.
- WO
- The output projection, ∈ ℝ(H·dhead)×dmodel. Under equal partition it is [dmodel, dmodel], e.g. [512, 512].
- MHA(X)
- [T, dmodel], the same shape as X, so it can be added to the residual stream.
Why WO is needed
Without WO, output columns 0–63 would come only from head 1, columns 64–127 only from head 2, and so on: each head would own a fixed block of the residual stream. WO lets every output dimension draw on every head. It also maps back to dmodel when H·dhead ≠ dmodel.
Where attention sits in a layer: block overview
Multi-head attention is one of two sub-blocks in a layer. A common layer (a “pre-normalised” decoder block) applies the steps below to every token’s vector. This is a fixed sketch, not an interactive calculation; the architecture explorer opens it up for a chosen model.
- Incoming x: [T, dmodel], the residual stream.
- Normalise: rescale each token’s vector to a steady size so the next sub-block sees well-behaved numbers.
- Multi-head attention (2.2.1–2.2.4): mixes information across positions; returns [T, dmodel].
- Add (residual addition): u = x + attention result, component by component. The same shape on both sides is what makes the sum possible, and it keeps a direct path for the original x.
- Normalise again.
- Feed-forward network (FFN, also called MLP): a small learned network applied to each position on its own. It does not mix positions; attention is the only sub-block that does.
- Add again: x′ = u + FFN(norm(u)). x′ is the next layer’s input.
One decoder layer for one token position, in order. Exact arrangements vary by model (for example where normalisation sits); this lesson’s equations cover only the attention step. Lesson 2.4 uses this loop to explain what the KV cache stores.
Advanced: concatenate-then-project equals a sum over heads
Split WO by rows into H blocks WO(i) ∈ ℝdhead×dmodel (block i is the rows that multiply head i's columns). Block matrix multiplication gives
So each head writes its own [T, dmodel] contribution and the layer adds them. Implementations still use the single concatenated matmul because one large multiplication is more efficient than H small ones plus a sum.
Parameter count
Without biases, the four projection matrices hold
For dmodel = 512: 4 × 5122 = 4 × 262,144 = 1,048,576 parameters per attention layer. H does not appear: splitting the same 512 columns into 1, 8 or 64 heads only regroups them. Choosing heads under equal partition is therefore not a parameter-count decision.
2.2.5 Tensor shapes end to end
The explorer below lists every stage of one multi-head attention layer with its symbolic and concrete shape. It starts at the Transformer base configuration: dmodel = 512, H = 8, dhead = 64. The list is the diagram; each row reads as text. Use the explorer: change Heads first: equal partition sets each head width to 512 / H automatically. Compare head width, score elements and multiply-adds. Change Sequence length separately. The optional advanced experiment lets the total projected width differ from 512.
Head-count shape explorer
- What this shows
- How each tensor's shape, the head width, the score-tensor size, the score compute and the projection parameter count follow from dmodel, H, T and dhead.
- Try
- Move H from 1 to 64 with dmodel fixed at 512. Then double T. Keep equal partition for this first comparison.
- What to notice
- More heads means narrower heads and more T×T score matrices, while the projection parameters and QKT multiply-adds stay fixed. Doubling T quadruples the score tensor.
Equal partition: the projected width stays 512 while each head gets narrower as the head count rises.
Advanced: choose an independent head width
Changed invariant: projected width H · dhead may differ from dmodel = 512. Input and output width stay 512; the output projection maps the chosen internal width back to 512. This changes parameter count and projection work. Equal partition restores the first experiment.
Stages of one layer (dmodel = 512)
- dhead
- Projected width H·dhead
- One head's Q, K or V
- Score tensor [H, T, T]
- Score tensor size if stored in FP16/BF16
- QKT multiply-adds, all heads
- Projection parameters (no biases)
- WO shape
Assumptions: one layer, one sequence (no batch dimension), biases omitted, equal-sized heads, the same dhead for Q, K and V. "Size if stored" assumes the full score tensor is materialized at 2 bytes per element; fused kernels such as FlashAttention (Dao et al., 2022) avoid storing it, so this is not a measured memory footprint. Multiply-adds count only QiKiT; AiVi costs the same again.
From tensor shapes to NumPy operations
For one sequence, first project the full input: Q = X @ W_Q, with the same operation for K and V. Here T counts tokens, H counts heads, and d_head is each head’s width. The projected shape is [T, H * d_head].
- Split projected columns:
Q.reshape(T, H, d_head).transpose(1, 0, 2)gives[H, T, d_head]. Apply the same reshape and transpose to K and V. Reshape groups columns; transpose changes the order of axes. - Reuse single-head attention: select one head’s
[T, d_head]Q, K and V matrices. Run the same scaled scores, causal mask, row-wise softmax and weighted-value sum as Lesson 2.1. Each head returns[T, d_head]; stacking the results gives[H, T, d_head]. Heads do not share a softmax. - Join, then project: if
headsholds those results,heads.transpose(1, 0, 2).reshape(T, H * d_head)restores token-first order and joins head components. Multiplying that matrix byW_Oreturns[T, d_model]. Reshaping directly without the transpose would mix token and head ordering.
This is an axis-order reference, not a complete implementation. It assumes equal query/key/value head widths and aligned self-attention positions; it does not introduce GQA or a KV cache.
With the defaults (T = 1024, H = 8), the score tensor holds 8 × 1024 × 1024 = 8,388,608 elements. At H = 64 it holds 67,108,864, eight times more, while the QKT multiply-adds stay at 10242 × 512 = 536,870,912. The head count trades fewer, wider comparisons for more, narrower ones; it does not change the matmul budget.
2.2.6 Head count, head dimension and what heads do not tell us
More heads is not automatically better
With a fixed model width and equally sized heads, more heads means fewer components per head. Each head has less space for its comparisons, while the layer calculates more separate attention patterns. More heads therefore does not automatically improve quality.
- Lower-dimensional comparisons. Head i's score matrix QiKiT is a product of a [T, dhead] and a [dhead, T] matrix, so its rank is at most dhead. At H = 64 with dmodel = 512, each head compares positions using only 8 numbers per vector.
- More score matrices. H·T2 score elements and H softmaxes per query position. Very small heads also tend to use GPU matrix units less efficiently; attention kernels are commonly tuned for head widths such as 64 or 128.
Fewer, wider heads have the opposite trade-off: fewer independent attention patterns per layer. The original paper's ablation (Table 3, English–German translation development set) varied the head count while keeping compute constant: single-head attention was clearly worse than the best setting, and quality also dropped with too many heads. Head count is a tuned hyperparameter, and results from one model and task do not transfer as a rule. More heads does not mean better quality.
dhead does not have to equal dmodel / H
Equal partition is a convention, not a requirement. Some architectures set dhead directly, so H·dhead can be larger or smaller than dmodel (model configuration files often expose a separate head-dimension field for this). The equations are unchanged; only the widths move:
- WQ, WK, WV ∈ ℝdmodel×(H·dhead) and the concatenation is [T, H·dhead].
- WO ∈ ℝ(H·dhead)×dmodel maps back to the model width, so the output is still [T, dmodel].
- Parameters become 4 · dmodel · H · dhead and the score multiply-adds T2 · H · dhead; now they do depend on the choice.
Switch the explorer to Independent to see WO change shape. For example, dmodel = 512, H = 8, dhead = 128 gives WQ = [512, 1024], a [T, 1024] concatenation and WO = [1024, 512], with 4 × 512 × 1024 = 2,097,152 projection parameters.
Engineering implication: heads shape the KV cache
During decoding the model stores each processed position's keys and values for every head. In the multi-head attention described here, every head has its own K and V, so each token adds 2 · H · dhead numbers per layer, which is 2 · dmodel under equal partition. Lesson 2.3 shows how multi-query and grouped-query attention keep all the query heads while sharing fewer K/V heads, and Lessons 2.4–2.5 turn this into bytes.
Knowledge check
These use a different configuration from the lesson, dmodel = 4096, H = 32 and T = 10, so you have to apply the rules rather than recall 512/8/64. Work each one on paper first; the feedback shows the full set of shapes.
References
- Vaswani, A. et al. (2017). Attention Is All You Need. arXiv:1706.03762. Multi-head attention (§3.2.2), base configuration dmodel = 512, h = 8, dk = dv = 64, head-count ablation (Table 3).
- Michel, P., Levy, O. and Neubig, G. (2019). Are Sixteen Heads Really Better than One? arXiv:1905.10650. Head pruning in trained models.
- Dao, T. et al. (2022). FlashAttention. arXiv:2205.14135. Mentioned only for not materializing the score tensor.