Writing is not reading: the decoder and its mask

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 TT 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 TT 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.

The same sentence with the mask on: half the grid goes, and no row stops summing to 1. Position 1 keeps 1.00 on itself, because there is nothing behind it.

Blanking out the future inside the softmax

The mask is a matrix the size of the grid, and its cells take only two values:

Mij={0if j≤i,−∞if j>i.M_{ij} = \begin{cases} 0 & \text{if } j \leq i, \\ -\infty & \text{if } j > i \end{cases}.

With it, the attention call changes by one term and nothing else:

Attention(Q,K,V)=softmax ⁣(QK⊤dk+M)V,\text{Attention}(\mathbf{Q}, \mathbf{K}, \mathbf{V}) = \text{softmax}\!\left(\frac{\mathbf{Q}\mathbf{K}^{\top}}{\sqrt{d_k}} + \mathbf{M}\right)\mathbf{V},

with M∈RT×T\mathbf{M} \in \mathbb{R}^{T \times T} 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 M\mathbf{M}).

Why −∞-\infty and not something else shows when you write out the whole weight:

αij=exp⁡(eij+Mij)∑m=1Texp⁡(eim+Mim),\alpha_{ij} = \frac{\exp\left(e_{ij} + M_{ij}\right)}{\sum_{m=1}^{T}\exp\left(e_{im} + M_{im}\right)},

where eije_{ij} is the score already divided by dk\sqrt{d_k}. Since exp⁡(−∞)=0\exp(-\infty) = 0, 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 00 in the score blanks out nothing: exp⁡(0)=1\exp(0) = 1 is a perfectly ordinary weight, and in the cell further down, row 00 ends up giving the future 0.5250.525 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 (0.0850.085, 0.2910.291, 0.8710.871), 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 j≤ij \leq i the term MijM_{ij} is 00, so the numerator is the usual one and the only thing that changes is the denominator, which keeps the terms up to ii. Divide top and bottom by the full sum ∑m=1Texp⁡(eim)\sum_{m=1}^{T}\exp(e_{im}) and the unmasked weights appear:

αijcausal=exp⁡(eij)∑m≤iexp⁡(eim)=αij∑m≤iαim,j≤i.\alpha^{\text{causal}}_{ij} = \frac{\exp\left(e_{ij}\right)}{\sum_{m \leq i}\exp\left(e_{im}\right)} = \frac{\alpha_{ij}}{\sum_{m \leq i}\alpha_{im}}, \qquad j \leq i.

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 11 is left with a single candidate and therefore with α11=1\alpha_{11} = 1, 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 ii gets the token yi−1y_{i-1}, the one the model should have written at the previous step, and row 11 gets <GO>, the symbol the decoder starts from, because before the first there is none. So row ii has y<iy_{<i} in front of it and has to produce yiy_i, which is precisely the distribution the previous block wrote,

P(yi∣y<i,x1:Tx),P\left(y_i \mid y_{<i}, x_{1:T_x}\right),

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 TyT_y rows came out of TyT_y 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 ii would also be conditioning on yiy_{i}, yi+1y_{i+1} 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 ii needs the token the previous pass produced, and that is TyT_y passes, one per token. The other is that the triangle saves not a single multiplication: the T2T^{2} 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:

Q=XdecWQ,K=XencWK,V=XencWV,\mathbf{Q} = \mathbf{X}^{\text{dec}}\mathbf{W}^Q, \qquad \mathbf{K} = \mathbf{X}^{\text{enc}}\mathbf{W}^K, \qquad \mathbf{V} = \mathbf{X}^{\text{enc}}\mathbf{W}^V,

where Xdec∈RTy×dmodel\mathbf{X}^{\text{dec}} \in \mathbb{R}^{T_y \times d_{\text{model}}} is what has been written so far and Xenc∈RTx×dmodel\mathbf{X}^{\text{enc}} \in \mathbb{R}^{T_x \times d_{\text{model}}} is what the encoder left read. The superscripts on X\mathbf{X} say which column the matrix comes from; those on W\mathbf{W} 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:

A∈RTy×Tx,\mathbf{A} \in \mathbb{R}^{T_y \times T_x},

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 11. 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 hh 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 TxT_x of the source is available from the first token of the output, as position 11 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:

CallQueriesKeys and valuesShape of A\mathbf{A}Mask?
encoder self-attentionXenc\mathbf{X}^{\text{enc}}Xenc\mathbf{X}^{\text{enc}}Tx×TxT_x \times T_xno
masked self-attentionXdec\mathbf{X}^{\text{dec}}Xdec\mathbf{X}^{\text{dec}}Ty×TyT_y \times T_yyes, causal
encoder-decoder attentionXdec\mathbf{X}^{\text{dec}}Xenc\mathbf{X}^{\text{enc}}Ty×TxT_y \times T_xno

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 00, the column of sums, and what happens with the two ways of getting it wrong.

import numpy as np

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))
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 first three lines are the whole argument. With −∞-\infty row 00 comes out [1. 0. 0. 0.] and all four sums are 11. With a 00 in the score the sums are 11 as well, and that is the trap: the row shares out correctly, but it shares out among positions that shouldn't be there (the 0.5250.525 that goes to three columns of the future). With the weights blanked out afterwards, the sums drop to 0.0850.085, 0.2910.291, 0.8710.871 and 11: 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.

import numpy as np

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))
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 maps have the table's shapes (5×55 \times 5 the masked one, 5×75 \times 7 the encoder-decoder one) and all ten rows sum to 11. Of the first one's 2525 cells, 1515 are left live, which is the count T(T+1)/2T(T+1)/2. And the last two lines are the property all of this exists for: rewriting positions 44 and 55 of the decoder moves what comes out at the first three by exactly 0.00.0, while the fourth (which is one of the ones I rewrote) does move. Change causal=True to causal=False and run it again: that 0.00.0 stops being one, and that is a model that has read what it hasn't written yet.

Test your intuition

Four questions: why −∞-\infty 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, −∞-\infty is added to the score before the softmax. What is wrong with leaving the softmax as it was and setting the leftover weights αij\alpha_{ij} to zero afterwards?

A decoder works on an output of T=6T = 6 tokens. How many cells of its map A\mathbf{A} end up different from zero?

cells

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 TyT_y 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 (nq,dk)(n_q, d_k), K shape (nk,dk)(n_k, d_k) and V shape (nk,dv)(n_k, d_v), and nqn_q and nkn_k need not be equal: in encoder-decoder attention there are TyT_y queries and TxT_x keys.

Return the pair (output, A), in that order: the output, of shape (nq,dv)(n_q, d_v), and the map of weights, of shape (nq,nk)(n_q, n_k), normalised by rows. The score is the dot product of each query with each key divided by dk\sqrt{d_k}, with dkd_k read off the shape of Q.

With causal=True, cell (i,j)(i, j) with j>ij > i is −∞-\infty 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.

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.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.