← All notes
Course chapters
On this page

Lesson 20 · Large language models

Multi-head attention

Why use several attention heads? Compute separate learned projections, combine their outputs, and explore the trade-off between head count, width and cost.

1. One token, several relationships

Consider the sentence “He likes the painting she made.”

Understanding “likes” involves its subject, “he”, and its object, “the painting”. Understanding “painting” may also involve the person who made it. Different relationships can matter at the same time.

In the previous lesson, one attention head calculated a set of weights and used them to combine value vectors:

h=∑jαjvj.\mathbf h=\sum_j\alpha_j\mathbf v_j.

A single head can assign weight to several positions. It can also carry multiple kinds of information in different coordinates. However, it produces one weighted mixture for each query, using the same weight for every coordinate of each value vector.

A simple average of two value vectors

12[1,0]+12[0,1]=[0.5,0.5]\tfrac12[1,0]+\tfrac12[0,1]=[0.5,0.5]
Figure 20-1. One mixture combines its inputs. Multiple input pairs can produce the same average, but a single head can still attend to several positions and encode more than one relationship.

An average is not a record of its separate inputs. For example, averaging [1,0][1,0] and [0,1][0,1] gives the same result as averaging [0.5,0.5][0.5,0.5] with itself. Once we keep only the average, we cannot generally recover which pair produced it.

This motivates a useful extension: calculate several mixtures in different learned spaces and keep their outputs separate until we combine them.

Pause and think

If we want to select information about both a subject and an object, must we manually tell one head to find each?

I've thought about it — show the answerHide answer

No. We can provide separate learned projections and let the training objective determine which distinctions are useful.

“Subject head” and “object head” are convenient teaching labels, not required roles. One head can serve several functions, and different heads can learn similar patterns.

2. Several heads in parallel

Multi-head attention repeats the attention calculation with separate query, key and value projections. Each head receives the input sequence XX:

Qi=XWQ(i),Ki=XWK(i),Vi=XWV(i).Q_i=XW_Q^{(i)},\qquad K_i=XW_K^{(i)},\qquad V_i=XW_V^{(i)}.

Head ii then calculates:

Hi=softmax⁡ ⁣(QiKiTdk)Vi.H_i=\operatorname{softmax}\!\left( \frac{Q_iK_i^{\mathsf T}}{\sqrt{d_k}} \right)V_i.

Softmax operates across the available keys for each query row. Because the projections differ, the same input position can produce different attention distributions in different heads.

Head A · query “likes”

he66.97%
likes16.63%
painting16.40%

Head B · query “likes”

he16.32%
likes16.55%
painting67.13%
Figure 20-2. The same query position produces two different weight rows using our hand-picked projections. These are calculated values, not measured heads from a trained model.

Our small example uses the tokens “he”, “likes” and “painting”. With “likes” as the query, one set of hand-picked projections favours “he”; the other favours “painting”. The numbers are calculated from the matrices shown later, rather than inferred from a trained language model.

We concatenate the head outputs along their feature dimension and apply a learned output projection:

O=Concat⁡(H1,…,Hm)WO.O=\operatorname{Concat}(H_1,\ldots,H_m)W_O.

Concatenation keeps the separate head outputs available to WOW_O. It does not average them together. The output projection can mix their coordinates to produce the representation passed to the rest of the network.

Each head has its own parameters in standard multi-head attention, but all heads are trained jointly with the network. They are not independently trained models with fixed, human-assigned responsibilities.

3. Full inputs, smaller working spaces

Do eight heads make attention eight times as expensive? The answer depends on the width assigned to each head.

A common arrangement keeps the total output width fixed. If the model width is dd and the number of heads is mm, choose:

dk=dv=dm.d_k=d_v=\frac{d}{m}.

The original Transformer used d=512d=512 and m=8m=8, giving 6464 coordinates per head. This is an example of a design choice, not a universal rule for all models.

With nn input positions, the shapes are:

X∈Rn×d,WQ(i),WK(i),WV(i)∈Rd×(d/m),Hi∈Rn×(d/m),Concat⁡(H1,…,Hm)∈Rn×d,WO∈Rd×d.\begin{aligned} X&\in\mathbb R^{n\times d},\\ W_Q^{(i)},W_K^{(i)},W_V^{(i)}&\in\mathbb R^{d\times(d/m)},\\ H_i&\in\mathbb R^{n\times(d/m)},\\ \operatorname{Concat}(H_1,\ldots,H_m)&\in\mathbb R^{n\times d},\\ W_O&\in\mathbb R^{d\times d}. \end{aligned}

Every projection receives the complete input row

Head 1

Q1=XWQ(1)Q_1=XW_Q^{(1)}

Full model width → a smaller learned subspace

Head 2

Q2=XWQ(2)Q_2=XW_Q^{(2)}

Full model width → a smaller learned subspace

Concat⁡(H1,…,Hm) WO(concatenate along the feature axis)\operatorname{Concat}(H_1,\ldots,H_m)\,W_O\quad\text{(concatenate along the feature axis)}
Figure 20-3. Heads project the whole input into separate working spaces, then their outputs are concatenated. Equal total width is not a guarantee of lossless compression.

Every head projects the full input. We do not give the first head only the first group of input coordinates and the second head only the next group. A projection can combine information from any input coordinate.

A smaller projected space can discard information. Returning to the original width after concatenation does not prove that the operation preserves all information or is invertible.

What stays fixed, and what grows?

Under this equal-width arrangement, ignoring biases, the query, key and value projections together contain 3d23d^2 parameters. The output projection adds d2d^2:

projection parameters=4d2.\text{projection parameters}=4d^2.

The leading work for all score products is proportional to:

m n2dm=n2d.m\,n^2\frac{d}{m}=n^2d.

The value-mixing products have a similar leading cost. Narrower heads therefore avoid multiplying these matrix-product costs by the full head count.

But more heads are not free. A separate attention table for each head contains mn2mn^2 entries, and Softmax, masking and execution overhead can grow. Optimised implementations may avoid storing every table; actual memory use and speed depend on the implementation.

Query/key/value width per head: 64

Concatenated width: 512

Q/K/V/output projection weights, excluding biases: 1,048,576

Attention weight entries across heads for a 16-token sequence: 2,048

This uses equal head widths and full multi-head Q/K/V projections. Projection parameter count stays fixed; the number of weight-table entries grows with head count. Actual memory and runtime depend on the implementation.

Experiment 20-B. Compare head width, projection parameter count and attention-table size while keeping model width fixed.

Increasing the head count at fixed width also makes each head narrower. More heads do not automatically produce a better model: capacity, training and the task all matter.

A complete numerical example

For Experiment 20-A, use three four-coordinate input rows:

X=[101001110001].X=\begin{bmatrix} 1&0&1&0\\ 0&1&1&1\\ 0&0&0&1 \end{bmatrix}.

The rows stand for “he”, “likes” and “painting”. These are teaching vectors, not learned word embeddings. Each head maps four input coordinates into two query, key and value coordinates.

The complete projection matrices used by Experiment 20-A

WQ(1)=[0.202000.100],qquadWK(1)=[1000.20000.1],qquadWV(1)=[10010.50.500.5]W_Q^{(1)}=\begin{bmatrix}0.2&0\\2&0\\0&0.1\\0&0\end{bmatrix},qquad W_K^{(1)}=\begin{bmatrix}1&0\\0&0.2\\0&0\\0&0.1\end{bmatrix},qquad W_V^{(1)}=\begin{bmatrix}1&0\\0&1\\0.5&0.5\\0&0.5\end{bmatrix}
WQ(2)=[0.202000.100],qquadWK(2)=[00−10.20010],qquadWV(2)=[0.5000.500.510]W_Q^{(2)}=\begin{bmatrix}0.2&0\\2&0\\0&0.1\\0&0\end{bmatrix},qquad W_K^{(2)}=\begin{bmatrix}0&0\\-1&0.2\\0&0\\1&0\end{bmatrix},qquad W_V^{(2)}=\begin{bmatrix}0.5&0\\0&0.5\\0&0.5\\1&0\end{bmatrix}
WO=[100001000.501000.501]W_O=\begin{bmatrix}1&0&0&0\\0&1&0&0\\0.5&0&1&0\\0&0.5&0&1\end{bmatrix}
Teaching matrices. Both heads use four input coordinates and two projected coordinates. All numbers are fixed by hand.

Change the query below to see how its dot products, weights and weighted values change. The two two-coordinate head outputs concatenate into four coordinates, then the displayed WOW_O mixes them.

Hi=softmax⁡ ⁣(QiKiTdk+M)Vi,O=Concat⁡(H1,H2)WOH_i=\operatorname{softmax}\!\left(\frac{Q_iK_i^{\mathsf T}}{\sqrt{d_k}}+M\right)V_i,\qquad O=\operatorname{Concat}(H_1,H_2)W_O

Head A · Query [2.00, 0.10]

he: score 1.414 · weight 66.97%

likes: score 0.021 · weight 16.63%

painting: score 0.007 · weight 16.40%

Head output: [1.0877, 0.7495]

Head B · Query [2.00, 0.10]

he: score 0.000 · weight 16.32%

likes: score 0.014 · weight 16.55%

painting: score 1.414 · weight 67.13%

Head output: [0.9184, 0.2471]

Concatenated: [1.0877, 0.7495, 0.9184, 0.2471]

After output projection: [1.5469, 0.8730, 0.9184, 0.2471]

Actual matrix arithmetic with fixed teaching inputs and projections. These heads were designed to show different patterns; they did not learn grammar from a corpus.

Experiment 20-A. Compute two projected attention heads, concatenate their outputs, and apply the displayed output matrix. Causal masking uses the sequence order “he, likes, painting”.

With causal masking, a query may use its own position and earlier positions, but cannot read later positions. We add a mask MM to the scaled scores before Softmax, with allowed entries 00 and forbidden entries −∞-\infty. For example, “likes” cannot attend to “painting” when the mask is enabled.

Within this attention operation, each head computes its mixture separately; the output projection combines them. Shared inputs, joint training and subsequent layers also connect their contributions across the network.

Some architectures use multi-query attention or grouped-query attention, where query heads share key and value projections. These variants can reduce key-value cache costs during generation. Sharing keys and values is not a mechanism that assigns grammatical roles or makes heads explicitly discuss their choices.

4. What do heads attend to?

A heatmap is a useful way to inspect attention. Each row is a query position, each column is a key position, and darker cells indicate larger weights.

Previous position

Same position

Earlier matching item

Special position

Figure 20-4. Schematic patterns to help read heatmaps: rows are queries and columns are keys. These grids are illustrations, not normalised measurements or evidence about a specific model.

Patterns worth looking for include attention to an adjacent position, the same position, an earlier related token or a special token. A trained model can also show patterns associated with syntax or references. Such observations depend on the model, layer, input and training.

These diagrams are deliberately schematic. They do not establish that a particular model contains exactly these four types of heads.

A related idea is an induction pattern: after seeing a sequence such as [A][B]…[A][A][B]\ldots[A], a model may use the earlier occurrence to help predict [B][B]. Some studied attention circuits support this kind of copying from context. That does not mean one head alone explains every form of in-context learning.

Pause and think

If a heatmap shows strong attention to a pronoun's likely referent, have we proved that this head is responsible for understanding the pronoun?

I've thought about it — show the answerHide answer

No. The weights show where the head looks, but its effect also depends on the value vectors, output projection and the rest of the network.

A stronger investigation would examine outputs and test interventions, such as removing a head and measuring the effect on the task. A visible pattern is a starting point for investigation, not a complete causal explanation.

Heads can be redundant or serve several purposes. A head that often attends to a separator is not necessarily confused; that position may carry useful information, or the pattern may have little effect on the final result.

5. What you have discovered

  • A head produces a weighted mixture for each query. Several heads allow separate mixtures in separate learned spaces.
  • Standard multi-head attention gives each head its own query, key and value projections of the full input.
  • Head outputs are concatenated and passed through an output projection.
  • Dividing a fixed width among heads keeps leading matrix-product work comparable, while head-specific overhead and attention-table size can grow.
  • Head roles emerge through joint training. Neither specialisation, lossless compression nor improved performance is guaranteed by adding heads.

Attention is only one part of a Transformer. Next, we will put it together with positional information, feed-forward networks, residual connections and normalisation to understand the complete architecture.

Check your understanding

1. What does multi-head attention add to one attention head?
2. How are standard multi-head outputs combined?