Multi-head attention

One attention head can only follow one pattern at a time. A transformer layer runs several heads side by side, each on its own slice of the vector, so different heads can track different relations at once. Their outputs are glued back together and mixed by one more matrix.

Key idea
Split d_model into h heads of size d_model ÷ h, run attention in each, concatenate, multiply by W_O
Real world
A newspaper story read by an editorial team at the same time: one checks names, one checks dates, one checks quotes. Each marks up the same text for their own purpose, and the editor combines their notes.
In an LLM
GPT-2 small has 12 heads of 64 numbers in every layer. In layer 4 of GPT-2 reading “The cat sat on the mat because it was tired”, one head reads the previous word, one links “it” to “cat”, and most of the others park their attention on the first token.

One head, one pattern

A single attention head produces one weight matrix: for every token, one set of weights over the earlier tokens. But a word usually needs several kinds of information at once. For “it” in our sentence, the model would like to know what “it” refers to (“cat”), what the previous word was (“because”), and perhaps where the sentence started. A single softmax has to share its weight among all of those, and blurs them.

The fix is simple: run several heads in parallel, each with its own WQW_Q, WKW_K and WVW_V, and let each one learn its own pattern. That is . Each is a full attention computation; a layer just has several.

Split, attend, concatenate, mix

The heads don’t each use the full vector. If the model has width dmodeld_{\text{model}} and hh heads, each head works with dmodel/hd_{\text{model}} / h numbers. In GPT-2 small that is 768/12=64768 / 12 = 64.

  1. Project. Compute QQ, KK and VV for all heads at once, with full-width matrices: each is T×dmodelT \times d_{\text{model}}.
  2. Split. Cut the columns into hh groups. Head 1 gets the first dmodel/hd_{\text{model}}/h columns, head 2 the next, and so on. No arithmetic: it is a reshape from (T,dmodel)(T, d_{\text{model}}) to (T,h,dhead)(T, h, d_{\text{head}}), then a transpose to (h,T,dhead)(h, T, d_{\text{head}}) so each head is its own slice.
  3. Attend. Every head runs ordinary scaled, masked attention on its slice. All heads are computed together as one batched matrix multiplication.
  4. Concatenate. Put the head outputs back side by side: (T,dmodel)(T, d_{\text{model}}) again.
  5. Mix. Multiply by an output matrix WOW_O (dmodel×dmodeld_{\text{model}} \times d_{\text{model}}), so each output number can combine what every head found.

Here it is on our toy sentence with dmodel=4d_{\text{model}} = 4 and two heads of size 2:

X
tensor shape: (5, 4)
X5 × 4
thingactsmallfirstThe0.10.01.01.0cat1.00.10.00.0sat0.21.00.00.0on0.00.30.80.0the0.10.01.00.0
Five tokens, each a row of d_model = 4 numbers. This layer has h = 2 heads, so each head works with d_model ÷ h = 2 numbers.
A two-head attention layer on the toy sentence, every number shown. Press play or step through: project, split, attend, concatenate, mix.

The two heads see the same tokens but have different weights, so they produce different patterns. Head 1 sends the last “the” mostly to “cat”; head 2 sends every word back to “The”. The output of the layer contains both kinds of information.

example · an editorial team

A reporter files a story. Instead of one editor reading it for everything, four read it at once: one checks every name against the earlier mentions, one checks dates, one checks quotes, one checks grammar. Each writes short notes in their own column. The chief editor reads all four columns together and writes the final mark-up. The checkers are heads, their columns are concatenated, and the chief editor is WOW_O.

Real heads in GPT-2

The toy heads were designed by hand. In a trained model each head’s pattern is learned. Here are all 12 heads of a GPT-2 layer, reading the same sentence. (Layers and heads are numbered from 0, so “layer 4” is the fifth of the 12.)

Loading GPT-2 data…

In layer 4, head 11 is a previous-token head: every token gives over 99% of its attention to the token just before it. Head 3 sends “it” to “cat”. Head 7 gives its largest share, about half, to the current token itself. Most of the rest put the bulk of their weight on the first token, a habit called an attention sink, explained on the next page. Move the layer slider and the mix of patterns changes from layer to layer.

example · 12 heads of 64

GPT-2 small has dmodel=768d_{\text{model}} = 768 and 12 heads, so each head’s query, key and value are 64 numbers. Its 12 layers hold 144 heads in total. Bigger models keep the head size around 64 to 128 and add more heads: GPT-2 XL has 25 heads of 64; Llama 2 7B has 32 heads of 128.

How many parameters

Splitting into heads doesn’t add weights. Each head’s WQW_Q, WKW_K and WVW_V are dmodel×dheadd_{\text{model}} \times d_{\text{head}}; with hh heads that adds up to three dmodel×dmodeld_{\text{model}} \times d_{\text{model}} matrices, the same as one big head. Add WOW_O and an attention layer has

4 dmodel2 weights4\, d_{\text{model}}^2 \text{ weights}

whatever hh is. For GPT-2 small: 4×7682=2,359,2964 \times 768^2 = 2{,}359{,}296, plus 3,0723{,}072 biases, about 2.36 million per layer and 28.3 million across its 12 layers, just under a quarter of its 124 million parameters.

d_model = 768, split into 12 heads of 64
per head: W_Q, W_K, W_V3 × 768 × 64 = 147,456
all heads + W_O12 × 147,456 + 589,824 = 2,359,296
per layer (with biases)2,362,368
all 12 layers28.3M
GPT-2 small uses 12 heads of 64. The attention weights of one layer are 4 × 768² = 2,359,296 numbers, plus 3,072 biases. Move the slider: the head count changes how the work is divided, not how many weights there are.
Pick a model, then change the number of heads. Each head gets a slice of d_model; the matrices get narrower as the heads multiply, so the total stays the same.

So the number of heads is a trade-off, not a cost. More heads give more separate patterns, but each compares queries and keys using fewer numbers. Most models settle on heads of 64 or 128.

Why it works

Different relations need different query–key matches. “Which noun does this pronoun mean?” compares meaning; “what was the previous token?” compares positions; “where did this word appear before?” compares token identity. One head’s single dot product can’t be good at all of them at once, because its weights would have to be a compromise. Separate heads can each specialise, and WOW_O lets the next part of the network use all their findings together.

Not every head is essential. Researchers have pruned many heads from trained models with little loss, which suggests heads are partly redundant. A few, like the induction heads on the next page, turn out to be crucial.

going deeper

Formula

MultiHead⁡(X)=Concat⁡(head1,…,headh) WO,headi=Attention⁡(XWQ(i),XWK(i),XWV(i))\operatorname{MultiHead}(X) = \operatorname{Concat}(\text{head}_1, \dots, \text{head}_h)\, W_O, \qquad \text{head}_i = \operatorname{Attention}(X W_Q^{(i)}, X W_K^{(i)}, X W_V^{(i)})

with WQ(i),WK(i),WV(i)∈Rdmodel×dheadW_Q^{(i)}, W_K^{(i)}, W_V^{(i)} \in \mathbb{R}^{d_{\text{model}} \times d_{\text{head}}} and WO∈Rh dhead×dmodelW_O \in \mathbb{R}^{h\,d_{\text{head}} \times d_{\text{model}}}.

An equivalent view: WOW_O can be split into hh row blocks WO(i)W_O^{(i)}, and the layer output is ∑iheadi WO(i)\sum_i \text{head}_i\, W_O^{(i)}. Each head writes its own contribution into the residual stream, and the contributions are added. This is the view interpretability work uses.

In code

B, T, D = x.shape
q, k, v = (x @ W_qkv).split(D, dim=-1)                 # each (B, T, D)
q = q.view(B, T, h, D // h).transpose(1, 2)            # (B, h, T, d_head)
k = k.view(B, T, h, D // h).transpose(1, 2)
v = v.view(B, T, h, D // h).transpose(1, 2)
o = F.scaled_dot_product_attention(q, k, v, is_causal=True)   # (B, h, T, d_head)
o = o.transpose(1, 2).reshape(B, T, D)                 # concatenate heads
y = o @ W_o

GPT-2 stores WQW_Q, WKW_K and WVW_V as one 768×2304768 \times 2304 matrix (c_attn) and WOW_O as c_proj.

Variants

Many recent models share keys and values between groups of query heads to shrink the KV cache: multi-query attention (one K/V head for all) and grouped-query attention (one per group). See efficient attention.

In papers

Related

  • qkv - Attention is three matrix multiplications to make queries, keys and values, one more to compare every query with every key, a softmax to turn scores into weights, and a last multiplication to mix the values. Here is every number.
  • attention-patterns - Open up GPT-2 and look at its 144 attention heads on real sentences. Some read the previous token, some resolve pronouns, some copy repeated text, and many dump their attention on the first token. Here is an explorer, and the stories of the heads researchers understand best.
  • causal-mask - A language model must predict each token without seeing it. The causal mask is a triangle of −∞ added to the attention scores so that every token can only look at itself and earlier tokens. It also lets training check a prediction at every position of a text in one pass.
  • the-block - Put the pieces together: LayerNorm, attention, add; LayerNorm, MLP, add. That is one transformer block, and a model is a stack of identical blocks between an embedding table and an output layer. Here is one block computed number by number, and an exact parameter count for real models.