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.
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..
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 . 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 dimensions and there are heads.
- 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.
- 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.
- 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.
- Concatenate. Put the twelve 64-long outputs side by side: back to 768 numbers per token.
- 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. , 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, . That is why adding heads does not add parameters: the same 768 × 768 projection matrices are simply interpreted as twelve 768 × 64 blocks.
Each token looks one step back. Useful for building bigrams like "the mat".
Almost everything goes to the first token. A "no-op" parking spot when the head has nothing to do.
"it" (and words after it) look back to the noun it refers to: "cat", not "mat".
Verbs find their subjects (sat→cat, was→it); prepositions find what they attach to.
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.
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).
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:
- 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.
- 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.
- 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.
- 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 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 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 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 ( tokens, ) and heads of width , head uses its own projection blocks :
where is the causal mask ( above the diagonal). Then
Parameter count. Stacking the head blocks side by side gives full matrices , plus :
For GPT-2 small, : weights, plus biases, for per attention layer.
Worked example. Two tokens A and B, , heads of width . We compute the output for the query at B. Suppose the projections give:
| head 1 | head 2 | |
|---|---|---|
| query of B | ||
| key of A / key of B | / | / |
| value of A / value of B | / | / |
Head 1 scores: and . Softmax gives : head 1 mostly looks at A, output .
Head 2 scores: and , softmax : head 2 mostly looks at B itself, output .
Concatenate: , then multiply by the matrix . 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
- “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 regardless of . 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 -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
Q1.A model has d_model = 1024 and 16 attention heads. What is the dimension of each head's query vectors?
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?
Q3.What is the main advantage of 12 heads of width 64 over 1 head of width 768?
Q4.Many heads put most of their weight on the first token. The most likely reason is…
Q5.What does the output projection W_O do?
Further reading
- paperAttention Is All You Need (Vaswani et al., 2017) — The original Transformer paper; Section 3.2.2 introduces multi-head attention.
- blogThe Illustrated Transformer — Jay Alammar's visual walkthrough, including multi-head attention.
- paperWhat Does BERT Look At? An Analysis of BERT's Attention — Clark et al. find heads that track syntax and coreference.
- paperAre Sixteen Heads Really Better than One? — Michel et al. show many heads can be pruned at test time.
- paperEfficient Streaming Language Models with Attention Sinks — Xiao et al. describe attention sinks and why the first tokens matter.
- blogIn-context Learning and Induction Heads — Anthropic's study of a two-head copying circuit.