Several heads, several share-outs

Several heads, several share-outs

35 min read

The lesson on the square root in the scores left two things unsettled. A self-attention layer gives each position one row of A\mathbf{A}, produced by a single pair of matrices, WQ\mathbf{W}^Q and WK\mathbf{W}^K; and dkd_k sits in the formula with nothing to say how large it ought to be.

Take the sentence this small mouse which the cats chase sleeps. sleeps has to find its subject, mouse, and one criterion isn't enough for that: asking whether a word is a noun doesn't tell mouse from cats, and asking whether it agrees in number doesn't tell a subject from a determiner. I'll call each criterion of that kind a rule. The row of sleeps needs both at once, and it combines them by adding: each rule gives each word a score, the dot product adds them up and the softmax shares out the row according to the total. The word that meets both rules wins.

Adding works when what you're after is one word that meets every rule, but a position may need two different words. chase needs whoever does the chasing, cats, and whoever is chased, mouse, and its row is a single share-out that sums to 11: either it keeps one and loses the other, or it mixes the two. What's more, once the rules have been added they can't be pulled apart again: the row doesn't say how much each one put in.

The alternative is not to add before sharing out: split the rules into groups, each with its own attention and its own softmax, and join what each one reads afterwards. Each of those attentions is a head, and the layer that runs several of them is multi-head attention, the subject of this lesson.

The explorable below puts one rule in each head: head 1 is the noun rule, head 2 is agreement, and heads 3 and 4 relate nouns to their determiners and modifiers. The fifth button doesn't join the heads: it is the layer from the lesson on self-attention, with the four rules added before a single softmax. The row is the position asking and the column the position answering, and the panel underneath sums up, for the row you pick, which word each map pulls towards.

Four rules, one per head, and a fifth button with all four added in a single row. No head finds the subject of "sleeps" on its own, and the sum, which does find it, all but erases "mouse" in the row of "chase".

In the row of sleeps, head 1 ties mouse with cats, at 0.300.30 each; head 2 prefers two singular words that are not the subject, this and the verb itself, at 0.320.32 each; and heads 3 and 4 have nothing to say. No head finds the subject, because the two rules it needed have gone to different heads. The sum does find it, mouse with 0.330.33, but at the cost of erasing what each rule said.

In the row of chase, which needed both cats and mouse, the sum keeps cats, with 0.400.40, and leaves mouse 0.070.07. Head 1, by contrast, still gives it 0.300.30, so with several heads what is read from mouse gets through to the output. That head doesn't know mouse is the one being chased, because none of these rules looks for objects and it reads both nouns alike; what the separation prevents is the sum erasing it. That is why a real head carries several rules: the ones that have to hold at the same time are added inside it, and the ones that look for different things can end up in different heads.

The same matrix read by several attentions at once

Each head is the layer from the lesson on self-attention, whole: its three projections over the same matrix and its own map. All that has to be added is the subscript there was no need to write there, because there was only one.

headi=Attention(XWiQ,  XWiK,  XWiV)∈RT×dv,\text{head}_i = \text{Attention}\left(\mathbf{X}\mathbf{W}^Q_i,\; \mathbf{X}\mathbf{W}^K_i,\; \mathbf{X}\mathbf{W}^V_i\right) \in \mathbb{R}^{T \times d_v},

with i=1,…,hi = 1, \dots, h, and with WiQ,WiK∈Rdmodel×dk\mathbf{W}^Q_i, \mathbf{W}^K_i \in \mathbb{R}^{d_{\text{model}} \times d_k} and WiV∈Rdmodel×dv\mathbf{W}^V_i \in \mathbb{R}^{d_{\text{model}} \times d_v}. Notice that the hh heads read the same X\mathbf{X}: they don't divide the sentence among themselves, and they don't divide the input coordinates either. Each one draws its own queries, keys and values from it, and with them its own map Ai∈RT×T\mathbf{A}_i \in \mathbb{R}^{T \times T}, square and with rows summing to 11 like the one in the lesson on self-attention.

That leaves hh outputs of T×dvT \times d_v, and the layer has to return one. Lay them side by side and project the result:

MultiHead(X)=Concat(head1,…,headh)WO∈RT×dmodel,\text{MultiHead}(\mathbf{X}) = \text{Concat}\left(\text{head}_1, \dots, \text{head}_h\right)\mathbf{W}^O \in \mathbb{R}^{T \times d_{\text{model}}},

where Concat\text{Concat} joins the hh matrices by columns (one row per position, with the hh pieces one after another inside it, so the result is T×(h⋅dv)T \times \left(h \cdot d_v\right)), and WO∈R(h⋅dv)×dmodel\mathbf{W}^O \in \mathbb{R}^{\left(h \cdot d_v\right) \times d_{\text{model}}} is the only matrix in the layer that belongs to no head. Its superscript is a label for its role, like those of the other three.

Three rows. At the top, X, T by 512, multiplied by W Q, a 512 by 512 square split into 8 blocks of 64 columns with the third one highlighted, gives Q, T by 512, split into the same 8 blocks: the 8 queries side by side. The same with W K and W V. In the middle, head 3 takes block 3 of Q, of K and of V, each T by 64: Q 3 and K 3 give, through the softmax of Q 3 times K 3 transposed over the root of 64, the map A 3, a T by T square; A 3 times V 3 gives head 3, T by 64. At the bottom, the 8 outputs side by side, with head 3 in block 3, form a T by 512 matrix which, multiplied by W O, 512 by 512 and split into 8 blocks of rows, gives the output, T by 512.
The h query matrices of the equation are not stored separately: they are the blocks of columns of a single 512 × 512 matrix, and the same goes for the key and value ones. Each head does the usual attention with its block, and its output takes that same place in the concatenation, which is what the output projection receives.

Adding before or after the softmax

A head's score was already a sum, and the previous lesson wrote it that way precisely so that it could count it:

eij=1dk∑m=1dkqimkjm,e_{ij} = \frac{1}{\sqrt{d_k}}\sum_{m=1}^{d_k} q_{im}k_{jm},

where qimq_{im} is coordinate mm of the query of position ii. Each coordinate of the comparison contributes its term, and the softmax doesn't see the terms: it sees the total.

The rules from the start of the lesson are those terms. The explorable above is built that way on purpose: each rule is one column of WQ\mathbf{W}^Q and one of WK\mathbf{W}^K, so coordinate mm of the query times coordinate mm of the key is the score of rule mm. The single-head layer carries all four columns, so it compares in dk=4d_k = 4 coordinates (and divides their sum by 4=2\sqrt{4} = 2); each of the four heads keeps a single column, dk=1d_k = 1, and its score is one rule and nothing more. In a trained layer nobody writes the rules, and a coordinate need not mean anything on its own, but the count is the same: terms that reach the softmax already added up.

Adding inside the softmax has a consequence that fits in one line. If aja_j and bjb_j are what two rules give word jj, the exponential turns their sum into a product:

softmaxj(aj+bj)=eaj ebj∑leal ebl.\text{softmax}_j\left(a_j + b_j\right) = \frac{e^{a_j}\,e^{b_j}}{\sum_{l} e^{a_l}\,e^{b_l}}.

Sharing out the total means multiplying, word by word, what each rule would give on its own, and rescaling so that the row sums to 11 again. A product behaves like a logical AND: if one rule scores a word low, that word is left with no weight, whatever the other rule says. That is what happens to mouse in the row of chase: agreement sinks it, because the number doesn't match, and the noun rule, which scored it the same as cats, can't pull it back up. And since what comes out is a single share-out, there's no longer any telling how much each rule put in.

That is the whole operation. Splitting the coordinates into hh groups and giving each group its own softmax is sharing out before combining, instead of combining before sharing out. Out come hh share-outs instead of one, each with its own denominator, and they reach the output without touching each other; what combines them is WO\mathbf{W}^O, a matrix that is learnt and that receives them already shared out. The sum the single-head layer did inside the softmax could not be undone; done outside, how much each part weighs can still be decided.

Splitting the width among the heads

That leaves choosing dkd_k, the other open question, and it is chosen by counting. Each head costs what the whole layer from the lesson on self-attention cost:

dmodel(2dk+dv)parameters,d_{\text{model}}\left(2d_k + d_v\right) \quad \text{parameters},

there are hh of them, and on top of them sits WO\mathbf{W}^O with h⋅dv⋅dmodelh \cdot d_v \cdot d_{\text{model}} more, so the complete layer asks for

h⋅dmodel(2dk+dv)+h⋅dv⋅dmodel.h \cdot d_{\text{model}}\left(2d_k + d_v\right) + h \cdot d_v \cdot d_{\text{model}}.

Now assign dkd_k and dvd_v the value dmodel/hd_{\text{model}}/h (splitting the model's width among the heads, instead of giving each one the whole width) and watch what happens:

h⋅dmodel⋅3dmodelh+h⋅dmodelh⋅dmodel=3dmodel2+dmodel2=4dmodel2.h \cdot d_{\text{model}} \cdot \frac{3d_{\text{model}}}{h} + h \cdot \frac{d_{\text{model}}}{h} \cdot d_{\text{model}} = 3d_{\text{model}}^{2} + d_{\text{model}}^{2} = 4d_{\text{model}}^{2}.

The hh has gone. Eight heads cost the same as one, and sixteen the same as eight. The multiplications behave the same way: the lesson that said goodbye to recurrence measured one attention at T2(dk+dv)T^{2}\left(d_k + d_v\right), and hh of them give h⋅T2(dk+dv)=2T2dmodelh \cdot T^{2}\left(d_k + d_v\right) = 2T^{2}d_{\text{model}}, which is exactly what a single one of width dmodeld_{\text{model}} cost.

So hh is chosen for what it does and not for what it costs, and dkd_k stops being a loose number: it is what is left of dmodeld_{\text{model}} once it is split. With the paper's figures, dmodel=512d_{\text{model}} = 512 and h=8h = 8, that gives dk=64d_k = 64 (the number the previous lesson did its sums with), and the whole layer weighs 4⋅5122=1 048 5764 \cdot 512^{2} = 1\,048\,576 parameters.

What it costs is worth saying, because it isn't nothing. Each head compares in 6464 coordinates where a single one would have compared in 512512: these are not eight comparisons as fine as the one there was, they are eight comparisons eight times narrower. That is the deal, and it is a bet about language (that several coarse relations are worth more than one very fine one), not a theorem.

Concatenate and project, don't average

The obvious alternative to concatenating is averaging: give each head the whole width, dv=dmodeld_v = d_{\text{model}}, and return 1h∑iheadi\frac{1}{h}\sum_i \text{head}_i, which already has the right shape without any further matrix. It is worth seeing it for what it is, a special case of what the layer already does. Take the WO\mathbf{W}^O that stacks hh copies of 1hI\frac{1}{h}\mathbf{I}:

WO=1h[I⋮I]⟹Concat(head1,…,headh)WO=1h∑i=1hheadi.\mathbf{W}^O = \frac{1}{h}\begin{bmatrix}\mathbf{I} \\ \vdots \\ \mathbf{I}\end{bmatrix} \quad\Longrightarrow\quad \text{Concat}\left(\text{head}_1, \dots, \text{head}_h\right)\mathbf{W}^O = \frac{1}{h}\sum_{i=1}^{h}\text{head}_i.

Concatenating with a WO\mathbf{W}^O that is learnt can therefore give the average and anything else; averaging is fixing one point of all that in advance. And fixing it has a very specific cost: it forces the hh heads to write into the same dmodeld_{\text{model}} coordinates, so two heads that have found two different things can cancel each other out before anything reads them. Concatenated, each has its dvd_v coordinates to itself, and WO\mathbf{W}^O decides afterwards, one output coordinate at a time, which of them to listen to.

That matrix does a second thing as well, which is only pointed out here: it brings the output back to dmodeld_{\text{model}}, the width it came in with. That is what lets these layers be stacked one on top of another, and what really needs it is a lesson further on, on the full block with residual connections and layer norm.

It remains to say what this construction does not do, because the drawings in papers invite you to believe the opposite. Nothing in the loss assigns a role to a head: there is no term saying that head 2 takes care of agreement. Heads do different things because they start out different, and for no other reason. The names in the explorable above are mine, from writing the four rules by hand; in a trained layer nobody names them, and you have to go looking for them afterwards, when they are there at all. Not even the order means anything: swap two heads together with their two blocks of rows of WO\mathbf{W}^O and not one number of the output changes, so head 3 does not name the same thing in two trainings of the same model.

The heads in NumPy

The first cell builds the layer with the projections whole and one block of columns per head, which is how it is really implemented, and then runs the parameter count through five values of hh.

import numpy as np

T, d_model, h = 6, 8, 4
d_k = d_v = d_model // h
rng = np.random.default_rng(5)
X = rng.normal(size=(T, d_model))
Wq = rng.normal(size=(d_model, d_model)) * 0.6 # the h heads, side by side
Wk = rng.normal(size=(d_model, d_model)) * 0.6
Wv = rng.normal(size=(d_model, d_model)) * 0.6
Wo = rng.normal(size=(h * d_v, d_model)) * 0.6


def softmax_rows(E):
Z = np.exp(E - E.max(axis=1, keepdims=True))
return Z / Z.sum(axis=1, keepdims=True)


outputs, maps = [], []
for i in range(h):
cols = slice(i * d_k, (i + 1) * d_k) # head i's block of columns
Q, K, V = X @ Wq[:, cols], X @ Wk[:, cols], X @ Wv[:, cols]
A = softmax_rows(Q @ K.T / np.sqrt(d_k))
outputs.append(A @ V)
maps.append(A)

concat = np.concatenate(outputs, axis=1) # (T, h*d_v): the h pieces in a row
Y = concat @ Wo

print("one head", outputs[0].shape, " concatenated", concat.shape, " output", Y.shape)
print("maps:", len(maps), "of", maps[0].shape,
" every row sums to 1:", bool(np.allclose([A.sum(axis=1) for A in maps], 1.0)))
print("row 0 of head 1:", np.round(maps[0][0], 3))
print("row 0 of head 2:", np.round(maps[1][0], 3))

d = 512 # the paper's width
print("\n h d_k projections W^O total")
for hh in (1, 2, 4, 8, 16):
dk = d // hh
proj, out = hh * d * 3 * dk, hh * dk * d
print(f"{hh:3d} {dk:4d} {proj:12d} {out:8d} {proj + out:9d}")
numpy

The first run downloads the Python interpreter (~15 MB). After that it stays in the browser cache and is reused across every lesson.

The two rows printed are the same position seen by two heads, and they look nothing alike: the first puts 0.5910.591 on position 00, its own, and the second 0.5310.531 on position 44, to which the first gave 0.0050.005. Here the heads have come apart only because rng gave them different matrices, which is also all that separates them in a trained model. And the table is the cancellation above, checked: the three columns on the right don't budge from 786 432786\,432, 262 144262\,144 and 1 048 5761\,048\,576 while dkd_k falls from 512512 to 3232.

The second cell measures the concession. If the hh heads start out with the same parameters, there are not hh heads.

import numpy as np

T, d_model, h = 6, 8, 4
d_k = d_model // h
rng = np.random.default_rng(5)
X = rng.normal(size=(T, d_model))


def softmax_rows(E):
Z = np.exp(E - E.max(axis=1, keepdims=True))
return Z / Z.sum(axis=1, keepdims=True)


def head_maps(Wq, Wk):
out = []
for i in range(h):
cols = slice(i * d_k, (i + 1) * d_k)
Q, K = X @ Wq[:, cols], X @ Wk[:, cols]
out.append(softmax_rows(Q @ K.T / np.sqrt(d_k)))
return np.stack(out) # (h, T, T)


block = rng.normal(size=(d_model, d_k)) * 0.6
equal = np.tile(block, (1, h)) # the h heads, with the same matrices
A = head_maps(equal, equal)
print("h identical maps:", bool(np.allclose(A, A[0])))
print("largest difference from head 1:", np.abs(A - A[0]).max(axis=(1, 2)))

different = equal.copy()
different[:, :d_k] += 0.4 * rng.normal(size=(d_model, d_k)) # head 1 only
B = head_maps(different, different)
print("after moving head 1 only:")
print(" how far each one is from head 1:", np.round(np.abs(B - B[0]).max(axis=(1, 2)), 3))
print(" and how far each one is from head 2:", np.round(np.abs(B - B[1]).max(axis=(1, 2)), 3))
print("row 0, head 1:", np.round(B[0][0], 3))
print("row 0, head 2:", np.round(B[1][0], 3))
numpy

The first run downloads the Python interpreter (~15 MB). After that it stays in the browser cache and is reused across every lesson.

With the four blocks of columns equal, the four distances come out exactly 00: the four maps are the same, and WO\mathbf{W}^O receives four copies of one vector per position. Moving a single block separates that head from the other three (0.4580.458 in the last three cells of the first line) and leaves those three identical to one another, which is what the three zeros of the second line say. The asymmetry doesn't appear by itself: it comes in through the initialisation, and in training it lasts because the heads and the blocks of rows of WO\mathbf{W}^O all start out different. With everything symmetric, the gradient would have no way of breaking it.

Test your intuition

Five questions: what separates hh heads from one, how much the layer weighs, where dkd_k comes from, what the layer computes with equal heads, and whether averaging was an option.

One layer has a single head with dk=4d_k = 4. Another has four heads with dk=1d_k = 1, and their columns are exactly the four of the first. What is the difference between them?

A multi-head layer with dmodel=512d_{\text{model}} = 512 and h=8h = 8 splits the width the way the paper does (dk=dv=dmodel/hd_k = d_v = d_{\text{model}}/h). How many parameters does it have in total, counting WO\mathbf{W}^O?

parameters

A margin of ±0 is accepted.

Why dk=dmodel/hd_k = d_{\text{model}}/h, and not some other width?

You initialise the hh heads with exactly the same WiQ\mathbf{W}^Q_i, WiK\mathbf{W}^K_i and WiV\mathbf{W}^V_i. Mark what is true of the layer at that moment.

Select every correct option. This is graded all-or-nothing: there is no partial credit.

Averaging the hh heads is something that the concatenation followed by WO\mathbf{W}^O cannot do.

Write multi_head(X, Wq, Wk, Wv, Wo, h). It takes the sentence already turned into vectors, X of shape (T,dmodel)(T, d_{\text{model}}); the three projections whole, Wq, Wk and Wv, all three of shape (dmodel,dmodel)(d_{\text{model}}, d_{\text{model}}); the output projection Wo, of the same shape; and the number of heads h, which divides dmodeld_{\text{model}}.

Head ii takes the ii-th block of columns of each projection (from i * d_k to (i + 1) * d_k, with d_k = d_v = d_model // h) and does the usual attention with it, dividing by dk\sqrt{d_k}.

Return the pair (output, A), in that order: the output, of shape (T,dmodel)(T, d_{\text{model}}), with the hh heads concatenated by columns and projected by Wo; and the hh maps stacked, A of shape (h,T,T)(h, T, T), with every row of every map summing to 11.

Don't write into the arrays you receive.

The first run downloads the Python interpreter (~15 MB); after that it stays in the browser cache. This challenge is much easier to solve on a physical keyboard: on a phone, read it and come back later.


With hh heads, a position has hh answers where it had one, and WO\mathbf{W}^O decides what to do with them. But look at where the hh come from: the same X\mathbf{X}, the same formula, and neither ii nor jj appears anywhere in eije_{ij}. Multiplying the heads multiplies what is compared, and adds not a single coordinate of where. None of the hh can learn to look for the noun on its left, however many of them you put in, because in what the layer reads there is no left.

The missing piece isn't in the layer: it is in the input, and it amounts to two different positions reaching X\mathbf{X} as two different rows even when the token is the same. That is the next lesson, on positional encoding, and what makes it interesting is not that it is needed (that has been known since the first lesson of this block) but the particular form the paper chooses: sines and cosines with which the distance between two positions can be written as a linear operation on what has been added. That property is shown, not asserted, and it takes up the whole lesson.

Was this helpful?
Further reading1 source · 1 paper

Where this lesson comes from, and where to go next. None of it is needed to carry on with the course.

  • Attention Is All You Need
    paperVaswani, Shazeer, Parmar and others, 2017arXiv:1706.03762EN

    Its §3.2.2 gives the concatenation with W^O and the split d_k = d_model/h, and says in one line that h heads cost as much as one. You work that cancellation out; reading heads as adding before or after the softmax is not in the paper.