MONA explainer 9 min read

Multi-Head Attention Explained: Why a Transformer Uses Several Heads

Mona spreads the five fingers of one hand beside eight parallel lanes joined into one bar: "why several heads?"

What is multi-head attention, and why does a transformer use several heads?

Multi-head attention is the step in a transformer layer where several attention computations, called heads, run side by side and get joined; in each, every token (a word or word piece) takes a mix of the tokens’ information, more from some than others.

The original authors’ reason: several heads let a layer attend to information from different subspaces at different positions at the same time. In “The keys to the cabinet are on the table.”, one head could link “are” to “keys”, another “on” to “table” (an illustration, not a measurement). Measured: one head per layer translated 0.9 BLEU worse than eight.

Multi-head attention sits inside the transformer architecture, the design behind large language models. A tokenizer cuts text into tokens; each becomes an embedding (a vector, or list of numbers, the model learns) plus a position signal, and passes through a stack of layers (repeated stages).

Each layer runs attention, then a feed-forward network, a small network that works on each token alone. Multi-head attention builds the attention step: one vector per token goes in (512 numbers in the original base transformer), and one of the same size comes out.

What one head does

In one head, each token’s vector is multiplied by three tables of learned numbers (weights), giving a query, a key and a value. A token’s query scored against another’s key decides how much of that token’s value flows in. More: the attention topic and our transformer explainer.

Why several heads

The paper that introduced the transformer gives the reason: multi-head attention lets the model “jointly attend to information from different representation subspaces at different positions. With a single attention head, averaging inhibits this.”

Our paraphrase: one head gives each token one weighted average; several heads give several averages, each from its own shorter version of every token (its “subspace”).

How the heads are projected and joined

In the original base model, a layer has 8 heads:

  1. Project. Each head multiplies the token’s vector by its own learned tables (a projection), getting its own query, key and value of 64 numbers each.

  2. Attend. Each head runs attention on its own vectors.

  3. Join. The 8 outputs of 64 numbers are joined end to end: 512 again.

  4. Mix. One more learned table mixes them, so each output draws on all heads.

With heads that narrow, the total cost “is similar to that of single-head attention with full dimensionality”, the authors write.

Eight heads of 64 numbers; the arrows show possible links, not measured weights.

How many heads, and do they specialise?

The authors varied the head count for English-to-German translation at fixed total computation, scored by BLEU (how closely output matches human translations). One head was “0.9 BLEU worse than the best setting”; quality “also drops off with too many heads”.

Our reading, not the authors’: nothing in these steps forces heads to differ. Studies of trained translation models and of BERT, a text-reading model, show:

  • Voita and colleagues removed most heads on a translation model’s input side (its encoder) after training, with little loss; heads with readable roles, such as a neighbouring token, a grammatical link or the rarest word, were the last to go.

  • Michel and colleagues found that after training some layers still work with one head, but not all: in an English-to-French translation model, keeping one head in the last layer where the output side reads the input side (encoder-decoder attention) cost at least 13.5 BLEU (newstest2013).

  • Clark and colleagues found BERT heads for single grammatical links, yet “there is no single attention head that does well at syntax ‘overall’”.

So “each head learns its own relation” is wrong: some heads do readable work, many are redundant once trained. None of these studies tested today’s chat models.

If you only wanted the basics, you can stop here.

The head-count measurement in detail

The “0.9 BLEU” comes from Vaswani et al. (2017), Table 3, rows (A): base model, English to German, development set newstest2013. The paper gives no reason for 8.

HeadsNumbers per headBLEU
151224.9
412825.5
86425.8
163225.8
321625.4

The paper prints one value per row and no variance or number of runs; differences of up to 0.4 BLEU cannot be ranked from it (our caution, not the authors’).

What the head studies measured

Voita et al. (ACL 2019): Transformer base, English to Russian, 48 encoder heads (6 layers × 8), 2.5 million WMT sentence pairs. Pruning 38 of the 48 cost 0.15 BLEU. The best verb-to-subject head was right 45 % of the time (fixed-position baseline 35 %).

Limit: pruned by fine-tuning after training; the same few heads trained from scratch scored lower.

Michel et al. (NeurIPS 2019): an English-to-French Transformer (6 layers × 16 heads). Removing single encoder heads changed BLEU significantly (newstest2013, p < 0.01) for only 8 of 96 heads. Limits: “rather small” test sets, and heads were masked after training.

Clark et al. (BlackboxNLP 2019): all 144 heads of BERT-base. Head 9-6 (layer 9, head 6) points from a preposition to its object 76.3 % of the time on Penn Treebank text (fixed-offset baseline 34.6 %).

The cabinet sentence is printed in Linzen, Dupoux and Goldberg (2016), a test of whether a model keeps the subject’s number past a noun of the other number.

In small self-attention models (2 to 4 layers, 2 or 4 heads) trained on Linzen’s agreement data, Tran, Bisazza and Monz (2018) found some heads that “frequently point to the subject”, yet LSTMs, a type of recurrent network, “consistently outperform” them at predicting the verb’s number; recurrent networks versus transformers has both directions.

In Google’s Gemma 2B, Ferrando and Costa-jussà (2024) found head L13H7 (layer 13, head 7) writing a “subject number” signal while it “attends broadly to the context”; head L17H4 “focuses on the subject’s noun”. They warn it may not generalise to other model families.

The construction in symbols

d_model is the token vector’s width (512), h the head count (8), d_k and d_v the widths of a head’s query/key and value (64 = d_model / h). W^O is the mixing table of step 4.

head_i = Attention(Q · W_i^Q, K · W_i^K, V · W_i^V)
MultiHead(Q, K, V) = Concat(head_1, …, head_h) · W^O

W_i^Q, W_i^K : d_model × d_k      W_i^V : d_model × d_v      W^O : (h · d_v) × d_model

When queries, keys and values come from the same sequence, this is multi-head self-attention. In the original decoder, one attention step takes keys and values from the encoder’s output; see the encoder-decoder architecture topic.

Our derivation, not a quote: the three input projections hold h · d_model · (d_model / h) = d_model² weights each (all heads together), as does W^O, so the weight count does not depend on h.

By the same derivation, what grows with h is the number of n × n tables of query-key scores for n tokens. Why n² hurts long inputs: attention variants and their limits. Mamba, a state-space model, scales linearly with sequence length.

Multi-query attention lets all query heads share one key head and one value head, to cut memory traffic when generating token by token; grouped-query attention shares one pair per group; the query heads stay separate.

Multi-head attention in PyTorch

nn.MultiheadAttention (PyTorch 2.15 documentation) is a reference implementation that “contains only limited features relative to newer architectures”. embed_dim is d_model; each of num_heads heads gets embed_dim // num_heads numbers.

import torch
from torch import nn

mha = nn.MultiheadAttention(embed_dim=512, num_heads=8, batch_first=True)
x = torch.randn(1, 9, 512)                      # 1 sequence, 9 tokens, 512 numbers each
out, w = mha(x, x, x, average_attn_weights=False)
# out: (1, 9, 512)    one vector per token
# w:   (1, 8, 9, 9)   one 9 x 9 weight table per head

Shapes as documented, not run by us. Three defaults matter:

  • batch_first=False: inputs are (sequence, batch, features) unless you set it.
  • average_attn_weights=True: the weights come back averaged over heads; pass False to see each head.
  • need_weights=True: pass False if you do not need weights, so PyTorch can use scaled_dot_product_attention.

Boolean masks mean the opposite of scaled_dot_product_attention: here True means “not allowed to attend”, there it means “take part in attention”. Our from-scratch guide measures what happens when the two are mixed up.

Position information, in brief

The original design “contains no recurrence and no convolution”, so it adds position information.

The original positional encoding adds a vector of sines and cosines of the position, PE(pos, 2i) = sin(pos / 10000^(2i/d_model)) (pos = position, i = dimension pair), to each embedding.

The lowest dimensions change fastest: the first pair repeats every 2π ≈ 6.28 positions, and wavelengths grow towards 10000 · 2π. The authors “hypothesized” that this makes relative offsets easy to learn. In the same Table 3 setting (English to German, newstest2013, base model, one value each), learned position vectors scored 25.7 BLEU against 25.8 for sines.

Sines can be computed for any length, yet Press and colleagues found “very weak extrapolation abilities” past the training length (WikiText-103). Rotary position embedding (RoPE), used in LLaMA, rotates queries and keys by a position-dependent angle; RoPE did better there but “still does not achieve satisfying results”.

Haviv and colleagues found models that see only earlier tokens “still competitive” with no position signal; they conjecture the models count the earlier tokens.

When it breaks: nn.MultiheadAttention(500, 8) raises AssertionError: embed_dim must be divisible by num_heads (a v2.15.0 source-code check, absent from the docs); default averaged weights hide the heads; and a boolean mask copied from scaled_dot_product_attention unflipped blocks exactly what it should allow.

Cheat sheet

The article on one page: open it full size, save it or share it.

Cheat sheet: one attention head, 8 heads of 64 joined to 512, head-count BLEU table, head studies, PyTorch traps, position
PNG

AI-assisted content, human-reviewed. Images AI-generated. Editorial Standards · Our Editors