Writing is not reading: the decoder and its mask
28 min read
The sum and the layer norm of the previous lesson, on residual connections, wrap whatever is put inside them without asking what it is, so putting one layer on top of another is no longer the problem. The one left isn't about depth. Everything this block has built takes for granted that the sentence is whole and in front of it, and that the positions are computed at once, and for half the architecture that is false: a model that translates has no translation in front of it until it has written one. And if you train it by computing everything in one go (which is what dropping the recurrence won), the answer ends up sitting right next to the position that has to guess it.
See it in the cat drinks milk, which is what the model would have to learn to write. If the four positions are computed at once and each one looks at all of them (which is exactly what the layer from the lesson on self-attention does), the position that has to produce drinks is looking at milk while it produces it. Guessing with the answer in front of you goes very well: the loss falls to zero during training. When it really generates there is nothing to the right, because it hasn't been written yet, and the model hasn't learned to do anything else. This lesson forbids that look without giving up computing the positions at once, and along the way it builds the sublayer that joins the paper's two columns.
Go back to the self-attention grid and turn on the causal mask. It is the same sentence, with the same projections and the same calculation; the only thing that changes is that everything to the right of the diagonal disappears and the cells that are left share out among themselves the unit there was to share. Start with the first row, which is the extreme case: it has no one to look at but itself.
Blanking out the future inside the softmax
The mask is a matrix the size of the grid, and its cells take only two values:
With it, the attention call changes by one term and nothing else:
with and the softmax by rows, as always. Nothing inside is touched: the three projections are the same, the divisor from the lesson on the scaled dot-product is the same, and the heads from the lesson on multi-head attention are the same (each one receives the same ).
Why and not something else shows when you write out the whole weight:
where is the score already divided by . Since , a blanked-out cell disappears from the numerator and from its place in the denominator, both at once. That is what leaves nothing over: the unit the softmax shares out is shared out entirely among the cells that remain.
The two alternatives that occur to anyone fail right there. Putting a in the score blanks out nothing: is a perfectly ordinary weight, and in the cell further down, row ends up giving the future of its weight. And computing the softmax as usual and setting the weights to zero afterwards leaves the denominator as it was, so the row sums to whatever its start summed to (, , ), and what comes out is no longer a mixture but a shrunken mixture, with a different factor in each row.
Masking is renormalising the start of the row
There is a way of reading the mask that puts it in its place, and it comes out of the formula above in two steps. For the term is , so the numerator is the usual one and the only thing that changes is the denominator, which keeps the terms up to . Divide top and bottom by the full sum and the unmasked weights appear:
In other words: take the row that self-attention computed, throw away the part on the right and divide what is left by what it summed to. Three things follow from that, and none of them needs another calculation. The order within what survives doesn't change, because all those cells are divided by the same number: the mask doesn't alter preferences, it withdraws candidates. Row is left with a single candidate and therefore with , whether the model knows it or not. And the mask is not a second operation beside the softmax; it is the same softmax over fewer cells.
One pass instead of T
We still have to say what goes into the decoder, because so far we've talked about what it can't look at and not about what it has in front of it. What goes in is the correct output shifted one position: row gets the token , the one the model should have written at the previous step, and row gets <GO>, the symbol the decoder starts from, because before the first there is none. So row has in front of it and has to produce , which is precisely the distribution the previous block wrote,
one per row. That is the teacher forcing of the lesson on sequence-to-sequence models, with no change to the idea: the model is given the true token instead of the one it wrote. What changes is the price. There, the rows came out of steps of a recurrence; here they come out of one matrix product, and the mask is what makes that vertical bar tell the truth: without it, row would also be conditioning on , and everything else.
And now the two concessions, which go together. The mask makes training parallel, not generation: when it really writes there is no correct output to shift by one position, row needs the token the previous pass produced, and that is passes, one per token. The other is that the triangle saves not a single multiplication: the scores are computed in full and then more than half of them are blanked out. The mask is a prohibition, not an optimisation.
The sublayer that looks at the other column
The decoder has three sublayers where the encoder has two, and the middle one is the only box in the whole paper that joins the two columns. It is the previous block's attention, whole, with the queries read from one place and the keys and values from another:
where is what has been written so far and is what the encoder left read. The superscripts on say which column the matrix comes from; those on still say which role each one projects, as they have since the lesson on self-attention. Neither of the two counts layers.
The shape of the map falls out on its own, and it is what gives away where this sublayer comes from:
rectangular, one row per position of the output and one column per position of the input. It is the grid of the previous block, the one from the lesson on multiplicative attention, with the same two axes and the same row summing to . What has changed since then is three things, and none of them is the operation: the score is the scaled dot-product instead of the alignment model, there are heads in parallel instead of one, and the query is no longer the state of a recurrent network but a row of a matrix that exists in full.
There is no mask here, and it's worth saying why, because it sounds odd after the previous section. What is forbidden is reading what hasn't been written yet, and the input is not being written: it was read in full before starting. Position of the source is available from the first token of the output, as position is. (Real implementations do put another mask here, the padding mask, so that the filler positions of a batch don't count; it is the same mechanism applied to another problem, and it is outside this lesson.)
With that, the paper's three calls to attention can be put in one table, and they are the three boxes that lit up in the diagram from the lesson that said goodbye to recurrence:
| Call | Queries | Keys and values | Shape of | Mask? |
|---|---|---|---|---|
| encoder self-attention | no | |||
| masked self-attention | yes, causal | |||
| encoder-decoder attention | no |
One function, three sets of arguments. And the decoder's three sublayers are wrapped in the line from the previous lesson, without a single exception: what went in is added and the result is normalised, three times.
The two attentions in NumPy
The first cell is the mask on its own, over a grid of scores whose numbers I set by hand so that the sums can be followed by eye. Look at three things: row , the column of sums, and what happens with the two ways of getting it wrong.
E = np.array([[1.0, 2.0, 0.5, 3.0], # scores already divided by the root of d_k
[0.5, 1.5, 2.5, 1.0],
[2.0, 0.0, 1.0, 0.5],
[1.0, 1.0, 2.0, 1.5]])
T = len(E)
future = np.triu(np.ones((T, T), dtype=bool), k=1) # True where j > i
def softmax_rows(S):
Z = np.exp(S - S.max(axis=1, keepdims=True))
return Z / Z.sum(axis=1, keepdims=True)
M = np.where(future, -np.inf, 0.0)
with_mask = softmax_rows(E + M) # the paper's
with_a_zero = softmax_rows(np.where(future, 0.0, E)) # blanking out with a 0 in the SCORE
weights_to_zero = np.where(future, 0.0, softmax_rows(E)) # blanking out the WEIGHTS, already shared out
for name, A in (("with -inf ", with_mask),
("with a 0 ", with_a_zero),
("weights to 0", weights_to_zero)):
print(name, "row 0:", np.round(A[0], 3), " sums:", np.round(A.sum(axis=1), 3))
# Masking is keeping the start of the row and normalising it again.
free = softmax_rows(E)
starts = np.where(future, 0.0, free)
starts = starts / starts.sum(axis=1, keepdims=True)
print("\nthe mask is the renormalised start:", bool(np.allclose(with_mask, starts)))
print("without the mask, row 0 gives the future:", round(float(free[0, 1:].sum()), 3))
The first run downloads the Python interpreter (~15 MB). After that it stays in the browser cache and is reused across every lesson.
The first three lines are the whole argument. With row comes out [1. 0. 0. 0.] and
all four sums are . With a in the score the sums are as well, and that is the trap: the row
shares out correctly, but it shares out among positions that shouldn't be there (the that
goes to three columns of the future). With the weights blanked out afterwards, the sums drop to
, , and : four rows scaled four different ways, which is the worst of the
three results even though it looks the most harmless.
The second cell builds the decoder's two attentions and checks the only thing the mask promises.
rng = np.random.default_rng(8)
T_x, T_y, d_model, d_k, d_v = 7, 5, 16, 8, 8
X_enc = rng.normal(size=(T_x, d_model)) # what the encoder left read
X_dec = rng.normal(size=(T_y, d_model)) # what has been written so far
Wq = rng.normal(size=(d_model, d_k)) * 0.5
Wk = rng.normal(size=(d_model, d_k)) * 0.5
Wv = rng.normal(size=(d_model, d_v)) * 0.5
def attention(asking, answering, causal=False):
Q, K, V = asking @ Wq, answering @ Wk, answering @ Wv
E = Q @ K.T / np.sqrt(d_k)
if causal:
E = np.where(np.triu(np.ones(E.shape, dtype=bool), k=1), -np.inf, E)
Z = np.exp(E - E.max(axis=1, keepdims=True))
A = Z / Z.sum(axis=1, keepdims=True)
return A @ V, A
own, A_own = attention(X_dec, X_dec, causal=True) # masked self-attention
enc_dec, A_enc_dec = attention(X_dec, X_enc) # encoder-decoder attention
print("masked : A", A_own.shape, " sums", np.round(A_own.sum(axis=1), 3))
print("enc-dec : A", A_enc_dec.shape, " sums", np.round(A_enc_dec.sum(axis=1), 3))
print("live cells in the masked one:", int((A_own > 0).sum()), "of", A_own.size)
# Rewrite the end of what has been written and see what moves of what came before.
other = X_dec.copy()
other[3:] = rng.normal(size=(T_y - 3, d_model))
out_other, _ = attention(other, other, causal=True)
print("\nchange positions 4 and 5; do the first three move?",
round(float(np.abs(out_other[:3] - own[:3]).max()), 12))
print("and the fourth?", round(float(np.abs(out_other[3] - own[3]).max()), 3))
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 maps have the table's shapes ( the masked one, the encoder-decoder
one) and all ten rows sum to . Of the first one's cells, are left live, which is the
count . And the last two lines are the property all of this exists for: rewriting positions
and of the decoder moves what comes out at the first three by exactly , while the fourth
(which is one of the ones I rewrote) does move. Change causal=True to causal=False and run it
again: that stops being one, and that is a model that has read what it hasn't written yet.
Test your intuition
Four questions: why and not a zero, how many cells survive, what carries a mask and what doesn't, and what really runs in parallel.
To blank out the future, is added to the score before the softmax. What is wrong with leaving the softmax as it was and setting the leftover weights to zero afterwards?
A decoder works on an output of tokens. How many cells of its map end up different from zero?
A margin of ±0 is accepted.
A full Transformer calls attention three times. Tick what is true of those three calls.
Select every correct option. This is graded all-or-nothing: there is no partial credit.
With the mask in place, writing a translation of tokens takes a single pass through the decoder.
Write attention(Q, K, V, causal=False), the call that serves for the paper's three
attentions. Q has shape , K shape and V shape
, and and need not be equal: in encoder-decoder attention
there are queries and keys.
Return the pair (output, A), in that order: the output, of shape , and the
map of weights, of shape , normalised by rows. The score is the dot product
of each query with each key divided by , with read off the shape of
Q.
With causal=True, cell with is before the softmax. 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.
There is no box left in the drawing without a lesson behind it, except the one at the very top, which turns each row into a probability per vocabulary entry. What has never appeared in these seven lessons is the numbers: how many blocks are stacked, how wide they are, how many heads there are, which tables are shared and how many parameters it all adds up to. Each piece has been built with the widths the argument needed, and the paper chose particular ones.
That is the next lesson, on the paper's full architecture: Figure 1 box by box, with its sizes, set beside what we have built. It is the lesson that turns Attention Is All You Need into a text you can open and read from beginning to end, which was the promise the block started with.
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.3 is your table of three calls, with the masking written as −∞ in the input of the softmax; its §3.1, the decoder with the output shifted one position. Why −∞ and not a zero afterwards, and the teacher forcing, are the lesson's.