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 tokens and any recurrent network: reading it takes steps, one after another, and buying a machine with processors changes nothing, because step needs a number that step has not finished computing. That is the first bill. The second took the whole of Block 3 to pay: whatever position has to tell position travels through 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.
The chain of waits no computer can shorten
The recurrence from the previous block fits on one line, and that line says it all:
with and . Of the two terms, the second waits for nobody. looks only at the token in its own position, so all products can be computed at once as soon as the text is tokenised. The first term does wait. 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 .
Set that against the attention call as the previous block left it. The score of the pair is
and no from any other pair appears in it. The wait the previous block ended on, each row of 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 to produce query . That is why the call was made once per step, row by row. Take that decoder away and suppose, for now, that , and 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 scores comes from two vectors that are already there, so all can be computed at once. That is what it means for them to fit in a single matrix product, . 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 still needed the one at . 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 contributes to position has to travel. In the recurrence it travels inside the state, and the state is rewritten at every step, so that contribution passes through products by before it arrives. This is exactly the count from the lesson on the vanishing gradient: multiplying times by the same matrix switches the signal off if its spectral radius is below 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:
What position contributes is its own term, and in front of it stands a single factor, . One, not . And since the backward pass is the forward pass travelled in reverse, the gradient that reaches position from the loss at step 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 by one vector and 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:
Now the grid. multiplies a matrix by a one. Each of the entries of the result is a dot product of terms, which makes multiplications. The mixture has entries and each one sums terms, which adds another . In total:
Seen pair by pair: scoring entry of the grid costs multiplications, and adding its share to the mixture, , costs more. The grid has entries.
The two counts compare most easily when all four widths are equal. Suppose they are, and call the common width . That leaves against , and the ratio between them is . 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 , and not before. In the paper these counts are written against , 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 squared, on long texts), but in exchange that work can be shared out, whereas the recurrence's steps cannot be shared out at all. A large computation that fits in a single matrix product finishes before a small one broken into waits.
The price that isn't paid in multiplications
Look at the score again, and this time look closely at the indices. In the subscripts only point at which two vectors go in; neither nor 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 and , 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 (the width of the paper's model) and a sentence of tokens.
The recurrence costs multiplications, spread over steps that come one after another. The grid costs , and not in waits but in two matrix products. That is ten times less work, and the depth of the chain has gone from to a number that does not even mention .
Now go up to , a long text. The grid needs multiplications and the recurrence . The grid now costs almost double, so this time the newcomer is the expensive one. The ratio is , exactly as predicted. Try yourself and check that you get . Notice also that the depth of the chain still has not moved, while the recurrence's has gone to .
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 tokens that is already fully tokenised. What still takes steps that cannot overlap?
With , at what length do the attention grid and the recurrence cost the same number of multiplications?
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 to position , 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.
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 §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.