On the path Attention paperEight attention heads side by side, each reading the sequence in its own way.
One reading is not enough
One attention gives each position one set of weights: one way of deciding what matters. But a word has many relations at once: “sat” needs its subject, its place and its tense. Multi-head attention runs several attentions, the heads, side by side, each with its own query, key and value matrices, so each can learn to look for something different.
Head i has its own matrices WiQ, WiK and WiV, each of shape (d, d/h), and gives one vector of length d/h per position. The h heads’ vectors are joined end to end (concat) into one of length d, and one matrix WO of shape (d, d) mixes them.
The same cost as one wide head
Each head works on vectors h times narrower, so h heads cost about as much as one attention of full width. In code the h query matrices are usually stored side by side as one (d, d) matrix and the result cut into h pieces; that is the same thing as separate matrices, computed in one product. After training, different heads are often found to do recognisably different jobs, such as following the previous word or linking a pronoun to its noun, but nothing forces them to.
On the path Attention paper
In the paper. The base model has h = 8 heads with dk = dv = 512 / 8 = 64 (the big model 16 heads of 64). Multi-head attention is used in three places: the encoder’s self-attention, the decoder’s masked self-attention, and the decoder’s attention to the encoder (cross-attention). The paper tried other numbers of heads, keeping the total width (table 3, rows A, English–German development set):
| Heads | dk = dv | BLEU |
|---|---|---|
| 1 | 512 | 24.9 |
| 4 | 128 | 25.5 |
| 8 (base) | 64 | 25.8 |
| 16 | 32 | 25.8 |
| 32 | 16 | 25.4 |
One head was 0.9 BLEU worse than the best; too many heads, each too narrow, lost quality again.
Test yourself
Do the heads share their query, key and value matrices?
No: each head has its own. Code often stores them side by side in one matrix and computes them in one product, but each head uses its own slice.
What does WO do, and how many are there in one layer?
One per layer: it mixes the heads’ outputs, joined end to end, back into one vector of the model’s width.
Why do eight heads cost about as much as one?
Each works on vectors eight times narrower (64 instead of 512), so the eight together do about the same amount of arithmetic as one head of full width.
Where it leads
Kept in this browser only, never sent.
Paths through it
- Attention paperstep 7 of 17Follow this path