Goodbye to recurrence

Goodbye to recurrence

22 min read

The previous block stripped attention down to its bones: three roles (query, key and value), a function that compares, and a weighted sum, with not a single recurrence inside. What it left untouched was the machine attention sits in, and that machine is still recurrent from top to bottom: the keys and values are states of a recurrent encoder, and the queries come from a recurrent decoder. Inside, attention waits for nothing. Outside, every call still has to wait for the decoder to finish its previous step and hand over the next query.

This lesson builds no new piece, and it helps to say up front what it removes and what it keeps. It removes the recurrence, not the encoder or the decoder. The encoder still reads the source sentence and the decoder still writes the target one, but neither keeps a state that is passed from one position to the next. Each layer handles every position at once, and the only thing that puts a token in contact with all the others is attention. Building that version takes the rest of the block; this lesson first counts what you gain and what you lose. That is not a matter of taste, because recurrence charges a price you can count. Take a news story of 800800 tokens and any recurrent network: reading it takes 800800 steps, one after another, and buying a machine with 800800 processors changes nothing, because step 401401 needs a number that step 400400 has not finished computing. That is the first bill. The second took the whole of Block 3 to pay: whatever position 11 has to tell position 800800 travels through 799799 multiplications by the same matrix, and by the time it arrives there is almost nothing left of it. Both bills have the same source, and removing it clears both.

The diagram below is where all of this ends up: the complete architecture the block builds, which is Figure 1 of the paper Attention Is All You Need, box by box. At this point half the names mean nothing to you, and that is fine, because each box says which lesson builds it. What you can read today is the one claim this lesson makes. Turn on the marker and, of the fifteen boxes, three light up. The other twelve work on one row at a time and have no way of knowing what is in the next one.

Fifteen boxes, and not one arrow running from one position to the next. Only the three attention boxes mix positions; the rest treat each position on its own.

The chain of waits no computer can shorten

The recurrence from the previous block fits on one line, and that line says it all:

ht=tanh⁡(Whhht−1+Wxhxt+bh),\mathbf{h}_t = \tanh\left(\mathbf{W}_{hh}\mathbf{h}_{t-1} + \mathbf{W}_{xh}\mathbf{x}_t + \mathbf{b}_h\right),

with ht∈Rdh\mathbf{h}_t \in \mathbb{R}^{d_h} and h0=0\mathbf{h}_0 = \mathbf{0}. Of the two terms, the second waits for nobody. Wxhxt\mathbf{W}_{xh}\mathbf{x}_t looks only at the token in its own position, so all TT products can be computed at once as soon as the text is tokenised. The first term does wait. ht−1\mathbf{h}_{t-1} is the result of the previous step, and there is no way to bring it forward without computing it. One half can be shared out among processors and the other cannot, and the half that cannot is the one that matters: the depth of the chain, meaning how many operations have to happen one after another, is TT.

Set that against the attention call as the previous block left it. The score of the pair (i,j)(i,j) is

eij=a(qi,kj),e_{ij} = a\left(\mathbf{q}_i, \mathbf{k}_j\right),

and no ee from any other pair appears in it. The wait the previous block ended on, each row of Q\mathbf{Q} waiting for the one before, is not in this formula. It lives in the decoder that makes the queries, which needs the context from call ii to produce query i+1i+1. That is why the call was made once per step, row by row. Take that decoder away and suppose, for now, that Q\mathbf{Q}, K\mathbf{K} and V\mathbf{V} arrive whole, one row per position of the sentence. Who makes them without a recurrence is the question this lesson ends on. With all three in hand, each of the T2T^{2} scores comes from two vectors that are already there, so all T2T^{2} can be computed at once. That is what it means for them to fit in a single matrix product, QK⊤\mathbf{Q}\mathbf{K}^{\top}. The softmax normalises each row using only its own entries, and no row looks at another; the mixture is a second product. That makes three operations in a row, and the three does not change when the text gets longer.

One caveat, so that you do not read more into this than it says. When generating text, the decoder still writes one token per step, because it cannot look at a token it has not written yet. What disappears is the wait when processing a sentence that is already complete: the source sentence always, and the target sentence during training, when the correct translation is already known. The recurrence could not take advantage of that even in training: with the translation right there, the state at step tt still needed the one at t−1t-1. How the decoder is trained in a single pass without being allowed to see the answer is the subject of the lesson on masks.

The other distance, the one Block 3 couldn't shorten

The depth of the chain decides how long the computation takes. There is a second distance, and it decides something worse.

Ask yourself which route whatever position 11 contributes to position TT has to travel. In the recurrence it travels inside the state, and the state is rewritten at every step, so that contribution passes through T−1T-1 products by Whh\mathbf{W}_{hh} before it arrives. This is exactly the count from the lesson on the vanishing gradient: multiplying T−1T-1 times by the same matrix switches the signal off if its spectral radius is below 11 and blows it up if it is above. The LSTM and the GRU did not shorten that path; they opened an additive path beside it so that the trip could be survived.

In attention, the path between those two positions is a single weight:

cT=αT1 v1+αT2 v2+⋯+αTT vT.\mathbf{c}_T = \alpha_{T1}\,\mathbf{v}_1 + \alpha_{T2}\,\mathbf{v}_2 + \dots + \alpha_{TT}\,\mathbf{v}_T.

What position 11 contributes is its own term, and in front of it stands a single factor, αT1\alpha_{T1}. One, not T−1T-1. And since the backward pass is the forward pass travelled in reverse, the gradient that reaches position 11 from the loss at step TT does not go through anything in between either. The distance between two positions stops depending on how many lie between them, which is more than Block 3 managed: the gate made the trip survivable, not short.

What it costs to swap the steps for a grid

None of this is free, and the price is counted in multiplications. Start with the recurrence. A step multiplies Whh∈Rdh×dh\mathbf{W}_{hh} \in \mathbb{R}^{d_h \times d_h} by one vector and Wxh∈Rdh×dmodel\mathbf{W}_{xh} \in \mathbb{R}^{d_h \times d_{\text{model}}} by another. Multiplying a matrix by a vector costs one multiplication per entry, so a step costs one product for each entry of its matrices. That is the count from the lesson on the vanilla RNN, read as a cost rather than as memory. Over the whole sentence:

T⋅(dh⋅dh+dh⋅dmodel)multiplications.T \cdot \left(d_h \cdot d_h + d_h \cdot d_{\text{model}}\right) \quad \text{multiplications}.

Now the grid. QK⊤\mathbf{Q}\mathbf{K}^{\top} multiplies a T×dkT \times d_k matrix by a dk×Td_k \times T one. Each of the T2T^{2} entries of the result is a dot product of dkd_k terms, which makes T2⋅dkT^{2} \cdot d_k multiplications. The mixture AV\mathbf{A}\mathbf{V} has T⋅dvT \cdot d_v entries and each one sums TT terms, which adds another T2⋅dvT^{2} \cdot d_v. In total:

T2⋅(dk+dv)multiplications.T^{2} \cdot \left(d_k + d_v\right) \quad \text{multiplications}.

Seen pair by pair: scoring entry (i,j)(i,j) of the grid costs dkd_k multiplications, and adding its share to the mixture, αijvj\alpha_{ij}\mathbf{v}_j, costs dvd_v more. The grid has T2T^{2} entries.

The two counts compare most easily when all four widths are equal. Suppose they are, and call the common width dd. That leaves 2Td22Td^{2} against 2T2d2T^{2}d, and the ratio between them is T/dT/d. The grid costs less than the recurrence as long as the sentence is shorter than the model is wide, and more once it is longer; the two cross at T=dT = d, and not before. In the paper these counts are written O(T2d)O(T^{2}d) against O(Td2)O(Td^{2}), which is the same comparison with the constants dropped, and that is how you will find it in its Table 1.

What this buys is worth spelling out, because the gain is not only speed. It is a change of axis. The total work grows (with TT squared, on long texts), but in exchange that work can be shared out, whereas the recurrence's TT steps cannot be shared out at all. A large computation that fits in a single matrix product finishes before a small one broken into TT waits.

The price that isn't paid in multiplications

Look at the score again, and this time look closely at the indices. In eij=a(qi,kj)e_{ij} = a(\mathbf{q}_i, \mathbf{k}_j) the subscripts only point at which two vectors go in; neither ii nor jj appears inside the computation. The same goes for the mixture, which is a sum, and a sum does not care about the order of its terms. The consequence is awkward: if you shuffle the rows of K\mathbf{K} and V\mathbf{V}, the outputs are shuffled the same way, and not one number changes.

So the dog bites the postman and the postman bites the dog reach the layer as the same set of vectors. The recurrence did not have this problem, though not through any merit of its own: it was solved from birth, because it read in order and the reading order was the sentence's order. Nor did the concatenated MLP from the lesson on why the MLP fails on sequences, for the opposite reason: each position multiplied its own block of columns, which is why it could tell positions apart and could not generalise across them. Attention has neither of those protections.

The concession is a big one, and this lesson does not fix it: removing the recurrence takes away the only thing that knew the order. The fix is to add to each row something that depends on where it sits, and that is the subject of a later lesson on positional encoding. Until then, everything that follows treats the input as a bag of vectors.

Check it by hand on a sentence of 50 tokens

Do both counts with numbers to see that the change is not only theoretical. Take d=512d = 512 (the width of the paper's model) and a sentence of T=50T = 50 tokens.

The recurrence costs 2⋅50⋅5122=26 214 4002 \cdot 50 \cdot 512^{2} = 26\,214\,400 multiplications, spread over 5050 steps that come one after another. The grid costs 2⋅502⋅512=2 560 0002 \cdot 50^{2} \cdot 512 = 2\,560\,000, and not in 5050 waits but in two matrix products. That is ten times less work, and the depth of the chain has gone from 5050 to a number that does not even mention 5050.

Now go up to T=1 000T = 1\,000, a long text. The grid needs 2⋅1 0002⋅512=1 024 000 0002 \cdot 1\,000^{2} \cdot 512 = 1\,024\,000\,000 multiplications and the recurrence 2⋅1 000⋅5122=524 288 0002 \cdot 1\,000 \cdot 512^{2} = 524\,288\,000. The grid now costs almost double, so this time the newcomer is the expensive one. The ratio is 1 000/512≈1.951\,000/512 \approx 1.95, exactly as T/dT/d predicted. Try T=2 000T = 2\,000 yourself and check that you get 3.93.9. Notice also that the depth of the chain still has not moved, while the recurrence's has gone to 2 0002\,000.

That is the deal, with both columns in view: you pay in work, which can be shared out between processors, and you buy back waiting, which cannot be shared out at all.

Test your intuition

Four questions: what cannot overlap, where the two counts cross, what happens if you shuffle the rows, and what becomes of the path between two distant positions.

Suppose you have as many processors as you like and a sentence of TT tokens that is already fully tokenised. What still takes TT steps that cannot overlap?

With dh=dmodel=dk=dv=512d_h = d_{\text{model}} = d_k = d_v = 512, at what length TT do the attention grid and the recurrence cost the same number of multiplications?

tokens

A margin of ±0 is accepted.

You pass the same rows to the attention call in a different order (the same tokens, shuffled). What comes out?

About the path linking position 11 to position TT, mark what is true.

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


That leaves a gap in the most visible place. The attention call needs queries, keys and values, and throughout the previous block they were made by two recurrent networks: the queries were the decoder's states, one per step, and the keys and values were the encoder's. Those states have gone with the recurrence, and without them the operation this lesson has put at the centre of the architecture has nothing to start from.

The answer is the one that gives the next lesson, on self-attention, its name: let the sequence ask itself. If the queries, the keys and the values are three readings of the same vectors, one per position, no second network is needed to produce anything, and every position gets to look at all the others, itself included. It is the same attention as in the previous block, with all three roles in the hands of a single sequence, and it is what turns the diagram above into something that can be computed.

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 §4 and Table 1 set out this lesson's three counts: sequential operations, path length between two positions and cost per layer, O(T²d) against O(Td²). The table drops the constants, so the crossing at T = d is yours to work out.