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 , produced by a single pair of matrices, and ; and 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 : 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.
In the row of sleeps, head 1 ties mouse with cats, at each; head 2 prefers two singular words that are not the subject, this and the verb itself, at 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 , 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 , and leaves mouse . Head 1, by contrast, still gives it , 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.
with , and with and . Notice that the heads read the same : 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 , square and with rows summing to like the one in the lesson on self-attention.
That leaves outputs of , and the layer has to return one. Lay them side by side and project the result:
where joins the matrices by columns (one row per position, with the pieces one after another inside it, so the result is ), and 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.
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:
where is coordinate of the query of position . 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 and one of , so coordinate of the query times coordinate of the key is the score of rule . The single-head layer carries all four columns, so it compares in coordinates (and divides their sum by ); each of the four heads keeps a single column, , 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 and are what two rules give word , the exponential turns their sum into a product:
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 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 groups and giving each group its own softmax is sharing out before combining, instead of combining before sharing out. Out come share-outs instead of one, each with its own denominator, and they reach the output without touching each other; what combines them is , 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 , the other open question, and it is chosen by counting. Each head costs what the whole layer from the lesson on self-attention cost:
there are of them, and on top of them sits with more, so the complete layer asks for
Now assign and the value (splitting the model's width among the heads, instead of giving each one the whole width) and watch what happens:
The 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 , and of them give , which is exactly what a single one of width cost.
So is chosen for what it does and not for what it costs, and stops being a loose number: it is what is left of once it is split. With the paper's figures, and , that gives (the number the previous lesson did its sums with), and the whole layer weighs parameters.
What it costs is worth saying, because it isn't nothing. Each head compares in coordinates where a single one would have compared in : 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, , and return , 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 that stacks copies of :
Concatenating with a 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 heads to write into the same coordinates, so two heads that have found two different things can cancel each other out before anything reads them. Concatenated, each has its coordinates to itself, and 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 , 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 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 .
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}")
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 on position , its own, and the second on position , to which the first
gave . 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 , and while falls
from to .
The second cell measures the concession. If the heads start out with the same parameters, there are not heads.
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))
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 : the four maps are the same, and receives four copies of one vector per position. Moving a single block separates that head from the other three ( 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 all start out different. With everything symmetric, the gradient would have no way of breaking it.
Test your intuition
Five questions: what separates heads from one, how much the layer weighs, where comes from, what the layer computes with equal heads, and whether averaging was an option.
One layer has a single head with . Another has four heads with , and their columns are exactly the four of the first. What is the difference between them?
A multi-head layer with and splits the width the way the paper does (). How many parameters does it have in total, counting ?
A margin of ±0 is accepted.
Why , and not some other width?
You initialise the heads with exactly the same , and . 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 heads is something that the concatenation followed by cannot do.
Write multi_head(X, Wq, Wk, Wv, Wo, h). It takes the sentence already turned into vectors,
X of shape ; the three projections whole, Wq, Wk and Wv,
all three of shape ; the output projection Wo, of
the same shape; and the number of heads h, which divides .
Head takes the -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 .
Return the pair (output, A), in that order: the output, of shape
, with the heads concatenated by columns and projected by Wo;
and the maps stacked, A of shape , with every row of every map summing
to .
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 heads, a position has answers where it had one, and decides what to do with them. But look at where the come from: the same , the same formula, and neither nor appears anywhere in . Multiplying the heads multiplies what is compared, and adds not a single coordinate of where. None of the 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 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.
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
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.