Search

Search papers and lessons

Multi-Head Attention

Level 3 · 9 min read

Multi-head attention runs several attention operations side by side, each on its own learned projection of the input, then mixes their outputs, so the model can track several kinds of relation at once.

On this page

  • Colour = topic mix
  • Linear algebra
  • Architectures
  • Neural network basics
  • Discrete math
  • Probability
  • Sign in to see your progress

TL;DR

Multi-head attention is attention run several times in parallel, with each run (a head) working on its own learned projection of the input. The head outputs are concatenated and passed through one more matrix that mixes them back to the model's width. Each head gets its own attention weights, so different heads can pick out different relations between positions. The total parameter count is about the same as one attention operation at full width.

Where you'll see it: every layer of the Transformer, in both its encoder and decoder, and in most large language models and vision transformers built on it.

Intuition

Imagine reading a sentence with several people at once, each with a different question. One is tracking who the subject is, another is looking for the verb that agrees with it, and a third is finding the matching bracket or the word that the pronoun refers to. Each reader writes down what they found, and the notes are then combined into one summary.

A single attention operation gives each query one set of weights over the other positions. That is one distribution, so one query has to commit to one pattern of focus. It can be a mixture of patterns, but the mixture is shared by all its uses. Several heads let the same query hold several separate focus patterns at once, each shaped by its own learned projections.

Splitting the work is also cheap. If the model width is dd and there are hh heads, each head works in a smaller space of size d/hd/h. Each head is cheaper than one full-width head, and the total cost stays close to a single full-width attention. The model gets diversity without paying for it in size.

flowchart LR
  X[Input x, width d] --> H1[Head 1: own Q, K, V]
  X --> H2[Head 2: own Q, K, V]
  X --> HN[Head h: own Q, K, V]
  H1 --> C[Concatenate, width d]
  H2 --> C
  HN --> C
  C --> O[Output projection W O]

The math

Let the input be a matrix X∈Rn×dX \in \mathbb{R}^{n \times d} with one row per position, where nn is the sequence length and dd is the model width. There are hh heads. Each head ii has three learned projection matrices, WiQW_i^Q, WiK∈Rd×dkW_i^K \in \mathbb{R}^{d \times d_k} and WiV∈Rd×dvW_i^V \in \mathbb{R}^{d \times d_v}, with dk=dv=d/hd_k = d_v = d / h by convention. The symbol dkd_k is the width of each query and key, and dvd_v is the width of each value.

Definition: Multi-head attention

Each head is an ordinary scaled dot-product attention on projected inputs:

headi=Attention(XWiQ, XWiK, XWiV)=softmax ⁣((XWiQ)(XWiK)⊤dk)XWiV.\mathrm{head}_i = \mathrm{Attention}\big(X W_i^Q,\ X W_i^K,\ X W_i^V\big) = \mathrm{softmax}\!\left(\frac{(X W_i^Q)(X W_i^K)^\top}{\sqrt{d_k}}\right) X W_i^V.

The heads are concatenated along the width and mixed by an output matrix WO∈Rhdv×dW^O \in \mathbb{R}^{h d_v \times d}:

MultiHead(X)=Concat(head1,…,headh) WO.\mathrm{MultiHead}(X) = \mathrm{Concat}(\mathrm{head}_1, \dots, \mathrm{head}_h)\, W^O.

The result has shape n×dn \times d, the same as the input, so the layer can be stacked.

The softmax is applied row by row, so each position has its own distribution over the other positions, separately in each head. The dk\sqrt{d_k} scaling is the one from single-head attention and has the same purpose there: it keeps the scores from growing with dkd_k and saturating the softmax.

Shapes and cost

Each head's score matrix has size n×nn \times n, so the total score memory is hn2h n^2 values per layer. The projections cost O(nd2)O(n d^2) and the score products cost O(n2d)O(n^2 d), the same order as single-head attention with full width. The price of extra heads is in the number of score matrices held in memory, not in the projection arithmetic.

Parameter count

With the base-model values from the original paper, d=512d = 512 and h=8h = 8, each head has dk=64d_k = 64. Each head has three projections of size 512×64512 \times 64, and the output matrix has size 512×512512 \times 512. Splitting into heads gives the same total as one head of full width, because the eight narrow projections together have the same number of weights as one wide one. That is why the heads are essentially free.

Worked examples

Example
Shapes and parameters for the base model

Use d=512d = 512, h=8h = 8 and dk=dv=64d_k = d_v = 64.

  1. Each head's query projection WiQW_i^Q has size 512×64=32,768512 \times 64 = 32{,}768 weights. Keys and values add two more of the same size, so one head has 3×32,768=98,3043 \times 32{,}768 = 98{,}304 projection weights.
  2. Eight heads give 8×98,304=786,4328 \times 98{,}304 = 786{,}432 projection weights.
  3. The output matrix WOW^O has size 512×512=262,144512 \times 512 = 262{,}144 weights.
  4. Total per layer, ignoring biases: 786,432+262,144=1,048,576786{,}432 + 262{,}144 = 1{,}048{,}576.
  5. A single head of full width d=512d = 512 would use three projections of size 512×512512 \times 512, which is 786,432786{,}432 weights, plus an output matrix of 262,144262{,}144 if one is used. The total is the same as the eight-head version.

Interpretation: the heads add separate patterns of focus without adding parameters. The extra cost is the eight separate n×nn \times n score matrices, which grows with sequence length.

Example
Two heads on a two-token sequence

Let d=2d = 2, h=2h = 2, so dk=dv=1d_k = d_v = 1. The query token is xa=(1,0)x_a = (1, 0) and the other token is xb=(0,1)x_b = (0, 1). The scaling factor is dk=1\sqrt{d_k} = 1. The output projection is the identity, so the concatenated heads are the output.

Head 1 uses W1Q=(1,0)⊤W_1^Q = (1, 0)^\top, W1K=(1,0)⊤W_1^K = (1, 0)^\top and W1V=(2,4)⊤W_1^V = (2, 4)^\top.

  1. Query: q=xa⋅(1,0)=1q = x_a \cdot (1, 0) = 1.
  2. Keys: ka=1k_a = 1 and kb=0k_b = 0. Scores: s=(1,0)s = (1, 0).
  3. Softmax: α=(ee+1,1e+1)≈(0.7311,0.2689)\alpha = \left(\frac{e}{e + 1}, \frac{1}{e + 1}\right) \approx (0.7311, 0.2689).
  4. Values: va=2v_a = 2 and vb=4v_b = 4.
  5. Head 1 output: 0.7311×2+0.2689×4≈2.53790.7311 \times 2 + 0.2689 \times 4 \approx 2.5379.

Head 2 uses W2Q=(0,1)⊤W_2^Q = (0, 1)^\top, W2K=(0,1)⊤W_2^K = (0, 1)^\top and W2V=(1,0)⊤W_2^V = (1, 0)^\top.

  1. Query: q=xa⋅(0,1)=0q = x_a \cdot (0, 1) = 0.
  2. Keys: ka=0k_a = 0 and kb=1k_b = 1. Scores: s=(0,1)s = (0, 1).
  3. Softmax: α=(0.2689,0.7311)\alpha = (0.2689, 0.7311).
  4. Values: va=1v_a = 1 and vb=0v_b = 0.
  5. Head 2 output: 0.2689×1+0.7311×0≈0.26890.2689 \times 1 + 0.7311 \times 0 \approx 0.2689.

Concatenated output for the query token: (2.5379,0.2689)(2.5379, 0.2689).

Interpretation: head 1 is mostly looking at xax_a and returns a value near 2, but it also gives xbx_b a weight, which pulls the result toward 4. Head 2 looks mainly at xbx_b, whose value is 0, so it returns only a small amount. The two heads disagree about where to look, and both views reach the output.

Tradeoffs and failure modes

More heads are not always better. With a fixed width, each head is narrower, so each head's query and key have fewer dimensions to match on. Very many narrow heads can each learn a weak, noisy pattern. In practice the head count is a tuning choice, and it is often set by what the hardware handles efficiently.

The main cost in deployment is memory for keys and values during generation. Each head keeps its own keys and values for every past position, so the cache grows with the number of heads.

SituationProblemBetter choice
Serving long contexts with many headsThe key-value cache grows with heads times length[[multi-query-attention
Long sequences in training or inferenceScore matrices grow with the square of the lengthMemory-efficient exact kernels such as [[flashattention-paper
Small model or short sequencesHeads are narrow and each learns a weak patternFewer, wider heads
A task with one clear relationExtra heads add little beyond one good headA single head is enough

Analysis of trained models has found heads that track the previous token, heads that follow syntactic links, and heads that look for repeated content. These patterns are observed after training. The architecture does not assign them in advance, and not every head has a clear role.

History

Attention in neural networks came first in sequence-to-sequence translation. Bahdanau, Cho and Bengio introduced additive attention in 2014 so that a decoder could look back at the encoder's states. Luong and colleagues in 2015 studied simpler scoring functions. Vaswani and colleagues introduced multi-head attention in 2017 in Attention Is All You Need, using it with self-attention and removing recurrence entirely. Their base model used eight heads. The design became the core of the transformer and of most large language models that followed.

Check yourself

QuestionIn multi-head attention, what does the output matrix WOW^O do after the heads are concatenated?Show answer

It mixes the concatenated head outputs, which together have width h⋅dvh \cdot d_v, back into the model width dd. This lets information from different heads combine in any proportion. It also makes the output the same shape as the input, so the layer can be stacked.

QuestionA model has width d=768d = 768 and h=12h = 12 heads, with dk=dv=64d_k = d_v = 64. How many projection weights does one head's query projection have, and what is the total for all heads of the query projection?Show answer

Each head's query projection maps width 768768 to width 6464, so it has 768×64=49,152768 \times 64 = 49{,}152 weights. Across 12 heads the total is 12×49,152=589,82412 \times 49{,}152 = 589{,}824, which equals 768×768768 \times 768. The total is the same as one full-width query projection, so splitting into heads does not change the count.

QuestionWhy can one attention head with one softmax find it hard to capture two different relations for the same query?Show answer

Each head gives a query a single set of weights that sum to 1. If the query should attend strongly to two unrelated positions, the weight has to be split between them, and each relation gets less than it would alone. Separate heads each produce their own set of weights, so each can sharpen on one pattern without giving up the other.

QuestionApplied: you are serving a model with 32 heads and very long prompts, and the GPU runs out of memory during generation. Which part of the attention layer is the likely cause, and what design change targets it?Show answer

The likely cause is the key-value cache, which stores keys and values for every head and every past position. With 32 heads, that is 32 sets of keys and values per position. Multi-query attention targets this by sharing a single key and value across all query heads, which cuts the cache by roughly the number of heads. A memory-efficient kernel such as FlashAttention targets the score matrix instead, which is a different cost.

Sources