Skip to content
LearnAI

2.6Multi-head attention

Why a Transformer runs a dozen small attention operations side by side instead of one big one, and what the individual heads end up doing.

⏱ 14 minIntermediate

One attention pattern is not enough

In self-attention step by step you saw how a single attention operation works. Every token makes a query, every token offers a key and a value, and each token ends up with a weighted average of the values, weighted by how well its query matches each key. The result is one attention patternSelf-attentionAttention in which the queries, keys and values all come from the same sequence.: a grid saying, for every token, how much it looks at every earlier token.

Now look at a real sentence and ask what a token should look at:

The cat sat on the mat because it was tired.

To process “it”, the model needs to know what “it” refers to (the cat, not the mat). To process “sat”, it helps to know the subject (cat). To get the local phrase right, every word benefits from knowing its immediate neighbor. And some words just want a rough summary of the whole sentence so far. These are different questions, and they often want different answers for the same token.

A single attention pattern has one row per token, and each row is a single softmaxSoftmaxA function that turns a vector of scores into probabilities by exponentiating each score and dividing by the total. distribution that sums to 1. If “was” wants to look at “it” (its subject) and at “cat” (what “it” means) and at the previous word, one distribution has to split its attention between all three, and the value vectors it gets back are blended into one average. Information about which source said what gets smeared together.

The fix, introduced in the original Transformer paper, is almost embarrassingly simple: run several attention operations in parallel, each with its own queries, keys and values, and let each one specialize. That is multi-head attentionMulti-head attention (MHA)Running several attention operations (heads) in parallel, each with its own projections, then combining their outputs..

ANALOGY· A panel of specialist readers

Imagine a committee reviewing a contract. One lawyer only checks that every “the Party” points to a defined name. Another only tracks dates. A third reads for the overall tone. Each reads the same document but highlights different passages, and each writes a short note. The notes are stapled together and handed to a manager who writes the final summary.

Each lawyer is an attention head: same input, different question, different highlights (its attention pattern). Each note is a head’s output. Stapling the notes together is the concatenation, and the manager who combines them is the output projection WOW_O. The committee costs the same as one generalist with the same total reading time, because each specialist only reads with a narrow lens.

Split, attend, concatenate, project

Here is the recipe for one multi-head attention layer, with numbers from GPT-2 small, where each token’s vector has dmodel=768d_\text{model} = 768 dimensions and there are h=12h = 12 heads.

  1. Project. Multiply each token vector by three learned matrices to get its query, key and value (see Q, K and VQuery, key, value (Q/K/V)Three learned projections of each token. A query is compared with keys to get attention weights, which then mix the values.). Each is still 768 numbers long.
  2. Split. Chop each 768-long query, key and value into 12 consecutive chunks of 64. Chunk 1 belongs to head 1, chunk 2 to head 2, and so on. Each head now has its own 64-dimensional queries, keys and values for every token.
  3. Attend (per head). Each head runs ordinary scaled dot-product attention on its own 64-dimensional pieces, with the causal maskCausal maskA mask that stops each token from attending to later tokens, so the model can't peek at the future during training. so no token sees the future. Twelve heads give twelve different attention patterns and twelve 64-dimensional outputs per token.
  4. Concatenate. Put the twelve 64-long outputs side by side: back to 768 numbers per token.
  5. Project again. Multiply by the output projectionOutput projection (W_O)The d_model × d_model matrix applied after the attention heads' outputs are concatenated. It mixes information from all heads back into the residual stream. WOW_O, a 768 × 768 matrix, which lets information from different heads mix. The result is added to the token’s running vector (the residual stream, covered in LayerNorm and residuals).

The key trick is in step 2: the heads do not each get a full-size copy of the vector. The width is divided among them, dhead=dmodel/hd_\text{head} = d_\text{model} / h. That is why adding heads does not add parameters: the same 768 × 768 projection matrices are simply interpreted as twelve 768 × 64 blocks.

INTERACTIVEMulti-head pattern viewer
Heads:
Query token (row):
H1 · Previous token

Each token looks one step back. Useful for building bigrams like "the mat".

ThecatsatonthematbecauseitwastiredThecatsatonthematbecauseitwastired
it → because: 87.7%
H2 · Attention sink

Almost everything goes to the first token. A "no-op" parking spot when the head has nothing to do.

ThecatsatonthematbecauseitwastiredThecatsatonthematbecauseitwastired
it → The: 81.2%
H3 · Coreference

"it" (and words after it) look back to the noun it refers to: "cat", not "mat".

ThecatsatonthematbecauseitwastiredThecatsatonthematbecauseitwastired
it → cat: 83.8%
H4 · Syntax: verb → subject

Verbs find their subjects (sat→cat, was→it); prepositions find what they attach to.

ThecatsatonthematbecauseitwastiredThecatsatonthematbecauseitwastired
it → The: 60.7%
What each head reads for the query “it” (one row of each heatmap)
H1 → because 88%
The
cat
sat
on
the
mat
because
it
was
tired
H2 → The 81%
The
cat
sat
on
the
mat
because
it
was
tired
H3 → cat 84%
The
cat
sat
on
the
mat
because
it
was
tired
H4 → The 61%
The
cat
sat
on
the
mat
because
it
was
tired

Each head produces its own weighted mix of value vectors. The outputs are concatenated and mixed by W_O, so the next layer receives all of these readings at once.

Number of heads h
input xsplit: 12 × 64attend (per head)concatW_O768Q, K, Vprojectionssoftmax(QKᵀ/√64)Vsoftmax(QKᵀ/√64)Vsoftmax(QKᵀ/√64)Vsoftmax(QKᵀ/√64)Vsoftmax(QKᵀ/√64)Vsoftmax(QKᵀ/√64)Vsoftmax(QKᵀ/√64)Vsoftmax(QKᵀ/√64)Vsoftmax(QKᵀ/√64)Vsoftmax(QKᵀ/√64)Vsoftmax(QKᵀ/√64)Vsoftmax(QKᵀ/√64)V12 × 64 = 768768×768mixes heads
d_head = d_model / h
768 / 12 = 64
W_Q, W_K, W_V (3·d²)
1,769,472
W_O (d²)
589,824
total weights (4·d²)
2,359,296

Change h: the per-head width shrinks, but the parameter count never moves. More heads means more, narrower “readers” for the same budget (biases ignored; d_model = 768 as in GPT-2 small).

Five hand-designed heads on the same sentence. Toggle heads to compare their heatmaps side by side; click a query token (or a heatmap row) to see what each head reads for it. Below, change the number of heads and watch the per-head width shrink while the parameter count stays put.

The patterns in the demo are hand-built, but each one is modeled on head behavior that researchers have actually found in trained models. Things to try:

  1. Query “it”. The coreference head puts most of its weight on “cat” and a little on “mat” (a plausible distractor). The previous-token head looks at “because”. The syntax head has nothing grammatical to do for a pronoun, so it parks its attention on the first token.
  2. Query “was”. Now the syntax head lights up on “it” (the subject of “was”), while the coreference head still reaches back to “cat”. Two heads, two different relationships, both delivered to the same token in the same layer.
  3. The attention sink head. Almost every row dumps its weight on “The”. This looks useless, and that’s partly the point; see the next section.
  4. Change the number of heads in the diagram. With 1 head, each head is 768 wide; with 16 heads, each is 48 wide. The total stays at 4×7682=2,359,2964 \times 768^2 = 2{,}359{,}296 weights.

What do real heads learn?

Nobody tells a head what to specialize in. Specialization emerges from training because it reduces the loss, and studies that open up trained models keep finding recognizable roles:

  • Positional heads that attend to the previous token (or the next-but-one, and so on). These are among the most common and easiest to spot.
  • Syntactic heads. A 2019 study of BERT (“What Does BERT Look At?”) found individual heads that track specific grammatical relations, such as verbs attending to their direct objects or determiners attending to their nouns, with surprisingly high accuracy.
  • Coreference heads that link pronouns and repeated mentions back to the entity they refer to.
  • Induction heads, a two-head circuit that finds an earlier occurrence of the current token and copies whatever came after it (“Harry … Potter … Harry → Potter”). Anthropic’s interpretability work argues these are a major mechanism behind in-context learning.
  • Broad heads that spread attention nearly evenly, giving the token a cheap “bag of words” summary of its context.

Two honest caveats. First, real heads are messier than the clean cartoons in the demo: most do several jobs at once, and their behavior depends on the input. Second, heads are less individually important than they look. Pruning studies in 2019 found that a large fraction of heads in trained translation and BERT models could be removed at test time with only a small drop in quality, while a few heads were crucial. The heads are a useful lens, not a list of guaranteed job titles; see interpretability for the deeper story.

Why many narrow heads beat one wide head

If the parameter count is identical, why is multi-head better? Three reasons.

Several distributions per token. Each head has its own softmax, so a token can attend sharply to its subject in one head and to its antecedent in another, without the two competing for the same probability mass. One head can only produce one weighted average per token; twelve heads produce twelve, which the output projection can keep apart.

Several notions of similarity. A head’s queries and keys live in their own 64-dimensional subspace, learned for its own purpose. “Similar” for a syntax head (verb looks for noun) is a completely different question from “similar” for a coreference head (pronoun looks for matching entity). Separate projections let each head define its own question.

Cheap and parallel. Heads don’t depend on each other, so a GPU computes them all at once as one batched matrix multiply. The compute is roughly the same as one big head of the same total width: the extra cost is only that you compute hh smaller softmaxes instead of one.

How many heads, then? There is no law. The original Transformer used 8 heads of 64; GPT-2 small uses 12 heads of 64; much larger models use dozens of heads, often still 128 dimensions or so each. If heads get too narrow, each one’s dot products become crude, so in practice designers keep dheadd_\text{head} around 64 to 128 and scale the head count with model width.

MATH CORNER · optionalMulti-head attention in equations, with a tiny worked example

For input X∈Rn×dX \in \mathbb{R}^{n \times d} (nn tokens, d=dmodeld = d_\text{model}) and hh heads of width dk=d/hd_k = d/h, head ii uses its own projection blocks WQ(i),WK(i),WV(i)∈Rd×dkW_Q^{(i)}, W_K^{(i)}, W_V^{(i)} \in \mathbb{R}^{d \times d_k}:

Qi=XWQ(i),Ki=XWK(i),Vi=XWV(i)Q_i = X W_Q^{(i)}, \quad K_i = X W_K^{(i)}, \quad V_i = X W_V^{(i)}headi=softmax ⁣(QiKi⊤dk+M)Vi  ∈Rn×dk\text{head}_i = \text{softmax}\!\left(\frac{Q_i K_i^\top}{\sqrt{d_k}} + M\right) V_i \;\in \mathbb{R}^{n \times d_k}

where MM is the causal mask (−∞-\infty above the diagonal). Then

MultiHead(X)=[head1 ∥ head2 ∥ ⋯ ∥ headh] WO,WO∈Rd×d.\text{MultiHead}(X) = \big[\text{head}_1 \,\|\, \text{head}_2 \,\|\, \cdots \,\|\, \text{head}_h\big]\, W_O, \qquad W_O \in \mathbb{R}^{d \times d}.

Parameter count. Stacking the head blocks side by side gives full d×dd \times d matrices WQ,WK,WVW_Q, W_K, W_V, plus WOW_O:

params=4d2  (+ 4d biases),independent of h.\text{params} = 4d^2 \;(+\,4d \text{ biases}), \quad \text{independent of } h.

For GPT-2 small, d=768d = 768: 4×7682=2,359,2964 \times 768^2 = 2{,}359{,}296 weights, plus 4×768=3,0724 \times 768 = 3{,}072 biases, for 2,362,3682{,}362{,}368 per attention layer.

Worked example. Two tokens A and B, d=4d = 4, h=2h = 2 heads of width dk=2d_k = 2. We compute the output for the query at B. Suppose the projections give:

head 1head 2
query of B(1,0)(1, 0)(0,1)(0, 1)
key of A / key of B(2,0)(2, 0) / (0,2)(0, 2)(2,0)(2, 0) / (0,2)(0, 2)
value of A / value of B(1,0)(1, 0) / (0,1)(0, 1)(0,2)(0, 2) / (1,1)(1, 1)

Head 1 scores: q⋅kA/2=2/1.414=1.41q \cdot k_A / \sqrt{2} = 2/1.414 = 1.41 and q⋅kB/2=0q \cdot k_B/\sqrt 2 = 0. Softmax gives (0.80,0.20)(0.80, 0.20): head 1 mostly looks at A, output 0.8(1,0)+0.2(0,1)=(0.80,0.20)0.8(1,0) + 0.2(0,1) = (0.80, 0.20).

Head 2 scores: 00 and 1.411.41, softmax (0.20,0.80)(0.20, 0.80): head 2 mostly looks at B itself, output 0.2(0,2)+0.8(1,1)=(0.80,1.20)0.2(0,2) + 0.8(1,1) = (0.80, 1.20).

Concatenate: (0.80,0.20,0.80,1.20)(0.80, 0.20, 0.80, 1.20), then multiply by the 4×44 \times 4 matrix WOW_O. One token, two heads, two opposite attention patterns, and both results survive into the output. A single head would have had to choose one weighting.

In code

A compact multi-head causal self-attention layer in PyTorch. Note that “splitting into heads” is just a reshape; no data is copied into separate networks.

import torch, torch.nn as nn, torch.nn.functional as F

class MultiHeadSelfAttention(nn.Module):
    def __init__(self, d_model=768, n_heads=12):
        super().__init__()
        assert d_model % n_heads == 0
        self.h, self.dk = n_heads, d_model // n_heads
        self.qkv = nn.Linear(d_model, 3 * d_model)   # W_Q, W_K, W_V in one matrix
        self.out = nn.Linear(d_model, d_model)       # W_O

    def forward(self, x):                            # x: [batch, seq, d_model]
        B, T, D = x.shape
        q, k, v = self.qkv(x).split(D, dim=-1)       # each [B, T, D]
        # split: [B, T, D] -> [B, h, T, dk]
        q, k, v = (t.view(B, T, self.h, self.dk).transpose(1, 2) for t in (q, k, v))
        y = F.scaled_dot_product_attention(q, k, v, is_causal=True)  # per-head attention
        y = y.transpose(1, 2).reshape(B, T, D)       # concat heads: [B, T, D]
        return self.out(y)                           # mix heads with W_O

mha = MultiHeadSelfAttention()
print(sum(p.numel() for p in mha.parameters()))      # 2,362,368
COMMON MISCONCEPTIONS
  • “Each head looks at a different part of the sentence.” Heads differ in what relationship they look for, not in which region they cover. Every head can see every earlier token; they differ only in how they weight them.
  • “More heads means more parameters.” The projections are 4d24d^2 regardless of hh. Adding heads just cuts the same width into narrower slices.
  • “Each head gets its own copy of the whole token vector.” Each head works in a d/hd/h-dimensional subspace produced by its own slice of the projection matrices. Its queries, keys and values are 64 numbers in GPT-2 small, not 768.
  • “Heads have clean, human-readable jobs.” Some do, roughly, and they make great illustrations. Many heads are polysemantic or redundant, and plenty can be pruned with little loss.

Check your understanding

0/5 answered
  1. Q1.A model has d_model = 1024 and 16 attention heads. What is the dimension of each head's query vectors?

  2. Q2.You change a layer from 8 heads to 16 heads, keeping d_model fixed. What happens to the number of weights in its Q, K, V and output projections?

  3. Q3.What is the main advantage of 12 heads of width 64 over 1 head of width 768?

  4. Q4.Many heads put most of their weight on the first token. The most likely reason is…

  5. Q5.What does the output projection W_O do?

Further reading

Progress is saved in this browser only.
Type to search across all lessons and glossary terms.