18 min read
Attention Is All You Need — how deleting recurrence still won
The Transformer's self-attention layer costs per layer versus for a recurrent layer, asymptotically worse once sequences get long. Yet it trained in twelve hours on eight P100 GPUs and beat every previous ensemble by over 2 BLEU on WMT14 English-to-German, reaching 28.4 BLEU. A costlier-looking layer topped the leaderboard and trained faster.
By the end you should be able to trace a token's query-key-value routing, compute how scaling prevents softmax saturation, and diagnose why self-attention's cost still trains faster than recurrence's serial path.
Contents
The recurrence bottleneck
What does recurrent memory provide that seems impossible to remove, and why does it bottleneck training?
Read "The animal didn't cross the street because it was too tired" and translate it word by word into German. By the time you reach it, animal is seven tokens back, and the decoder still has to know which noun the pronoun points to before it can choose the right German word. Nothing about the sentence changes this: the model has to carry that link forward across every intervening token.
A recurrent encoder does this by keeping one running summary. At each step it computes a hidden state from the current token and the previous state , so information about animal survives only by being folded into at every subsequent step until it is reached [1]. This is what recurrence provides: a single evolving memory, threaded token by token, that can in principle hold a dependency of any length.
The same rule that makes this memory possible also makes it slow to train. Computing requires to already exist, which requires , back to the start of the sentence. That dependency chain cannot be broken by adding more compute: a second GPU cannot compute step 6 before step 5 has finished, because step 6's input does not exist yet. Training is forced into sequential updates per example, however many positions the sentence has, and this sequential requirement is exactly what limits parallelization within a training example [1].
Suppose the recurrent chain is deleted outright and every position is exposed to the network simultaneously. The serialization problem disappears: all hidden states can now be computed in one parallel pass. But it still needs to know that animal, not street, is the word it refers to, and simultaneous visibility of every token says nothing yet about which one to use.
Query-key-value routing
How can one token retrieve another token's information without a step-by-step hidden state?
By the time self-attention runs, "animal" and "street" are both already sitting in view of the position representing "it" — recurrence's step-by-step handoff is gone, so nothing has to wait its turn. But visible is not the same as read. Suppose "it" just averaged every position's vector with equal weight: the result blends "animal" and "street" into one smeared vector, which is exactly the ambiguity the pronoun needed resolved, not an answer to it. Something has to decide, position by position, how much of "animal" versus how much of "street" belongs in the vector eventually assigned to "it" — and that something can no longer be a hidden state passed down a chain.
The fix is to give each position three learned projections of its embedding: a query describing what that position is searching for, a key describing what it offers to be matched against, and a value holding the content actually retrieved. The output at a position becomes a weighted sum of every position's value, where the weight comes from a compatibility score between that position's query and each other position's key [2]. For "it", the query encodes something like "what was tired"; the key for "animal" is built to score high against that question, and the key for "street" is not.
Turning those raw scores into an actual read requires normalizing them: softmax converts the row of scores belonging to "it" into a distribution over positions, and that distribution weights the corresponding values [2]. The result is scaled dot-product attention, : if the score between "it" and "animal" dominates its row, "it" reads back mostly "animal"'s value and "street" contributes almost nothing to the sum. No step here depends on a previous step's output — the row for "it" is computed independently of, and in parallel with, every other row.
Nothing so far bounds how large one raw dot product can get. As the query and key dimensions grow, a handful of coordinates lining up between and can push a single score far above its neighbors, and softmax's response to a runaway score is not sharper selection — it is a saturated, nearly one-hot distribution with almost no gradient left for training to use [2].
Why large dot products break softmax
Why divide the dot products by before the softmax?
Suppose the raw dot product between the query for and the key for comes out largest simply because is large, not because is semantically the better antecedent: summing across many independent coordinates makes an extreme value more likely by chance alone as grows [3]. Feed that raw score straight into , which weights each value by a compatibility score between query and key [2], and the exponential turns a modest gap over the smaller score for into a near one-hot weight: gets almost all the mass, everything else almost none.
That near one-hot outcome looks correct here only by luck, and the same mechanism will misfire whenever the true antecedent is not the accidental maximum. The cause is structural: if each of the components of and is an independent random variable with mean and variance , the dot product has mean and variance [3]. Larger spreads scores wider, pushing more of them into the region where softmax has extremely small gradients [4]. The fix divides every score by before the softmax, producing the scaled score, which rescales variance back to roughly regardless of and keeps scores in the region where softmax's gradient still carries signal.
How key dimension changes softmax saturation
At , a raw score gap of pushes the softmax weight to about , near and deep in the flat, low-gradient zone, while dividing by brings the same gap to about , still on the informative slope.
Reduces the full row-wise softmax over keys to a two-key comparison, the top score against a fixed competing score of , holding every other score and dimension fixed; only varies via the slider.
Scaling fixes the gradient problem, not the underlying constraint: scaled or not, the weights out of still sum to one, so one softmax distribution can only spend its whole probability mass on a single blended view of every other token. The vector for still gets exactly one weighted mixture of , , and everything else at once, never several independent judgments.
Multi-head attention
Why run several smaller attention operations instead of one large one?
Go back to the sentence about the tired animal. The vector for "it" has two jobs to do at once: find its antecedent () and pick up the modifier that describes it (). A single scaled dot-product attention pass [2] produces exactly one softmax distribution over every position. Whatever routing pattern that one distribution learns has to carry both relations at once, so the weight mass meant for coreference and the weight mass meant for the modifier get folded into the same blended value vector. There is no slot inside one softmax to keep those two relations separate.
The fix is not a bigger or smarter single attention function. It is several smaller ones run side by side. , , and are each linearly projected times into their own subspaces, -dimensional for queries and keys and value dimension-dimensional for values, using separate learned matrices per head. Each head then runs its own scaled dot-product attention independently and in parallel: one head can learn to track "it" back to "animal" while a different head learns to track "it" forward to "tired", instead of one softmax averaging both into a single view, and because each head works in its smaller /-dimensional subspace rather than the full dimension, running heads in parallel costs about the same as one full-dimensional head would [5].
Eight heads now resolve coreference and modifier attachment as separate, parallel routing patterns instead of one blended average. But every one of those heads still computes its weights from a set of keys and values with no sense of order attached to them: swap and in the input and a head that routes purely by content produces the identical attention pattern on the swapped sentence. Multi-head attention fixes the averaging problem and leaves the ordering problem exactly where it was.
Positional encoding
How does word order enter a mechanism that treats every position symmetrically?
Run the sentence through everything built so far, then swap two words: "The street didn't cross the animal because it was too tired." Every content-based score comes out identical, because query-key-value routing compares only what each token contains, never where it sits [2]. "It" attends to "animal" or "street" with the same weights in both sentences. The two sentences mean different things and produce identical attention. Nothing built so far can see word order at all.
The fix does not touch attention. Before the first layer, a fixed vector is added directly to each token's embedding at position index , the token's index in the sequence, so an early position and a late position start from different vectors before any query or key is ever computed [6].
Low gives short wavelengths near ; high stretches toward , so the dimensions sweep a whole range of frequencies. That range is what makes offsets recoverable: for any fixed fixed offset , trigonometric addition turns into a linear function of , with coefficients depending only on , not on [7]. A single linear map can convert "eight tokens back" into an operation a query can act on, without the model learning a separate vector per absolute position.
Adding leaves the embedding's dimension at unchanged: the encoding has the same dimension as the embedding so the two can be summed rather than concatenated [6], and every later sublayer still receives the same -wide input it expected before position was added.
The encoder can now tell "animal" from "street" and knows "it" sits eight positions past "animal." But positional encoding only says where each token is; it says nothing about direction. Left unmasked, the decoder's self-attention still lets "it" attend to every position, including words the translation has not produced yet.
Masked decoder self-attention
How does the decoder generate one token at a time without recurrence enforcing that order?
Picture the decoder midway through producing the German sentence, having just emitted the word for tired. Its self-attention sub-layer is built exactly like the encoder's: every query forms a compatibility score against every key at every position in the sequence [2]. During training the entire target sentence already sits in memory at once, so nothing stops the query at this step from reading a key several words ahead, at a token the model has not actually generated yet. A model that can see its own future output does not learn to translate; it learns to copy.
The fix is arithmetic, not new architecture. Before the softmax inside decoder self-attention, every score for a connection from position to a later position is overwritten with [8]. Softmax turns that entry into weight , so no value from an unseen future token ever reaches the output; the causal mask records exactly this pattern of legal and illegal connections. Combined with shifting the target sequence right by one position before it enters the decoder, so the input consumed at step is the ground-truth token from step , this guarantees the prediction for position depends only on positions earlier than [9].
Apply this to the German sentence: at the step producing the word for tired, the mask zeroes out every score pointing to positions still to come, leaving only words already emitted, plus — through the separate encoder-decoder attention sub-layer — the whole source sentence, animal included [10]. Training and inference now match: at both, position only ever sees what came before it. Correctness is settled. What is not yet settled is cost: this masked self-attention still scores every pair of positions at every layer [2], the same all-pairs computation recurrence was built to avoid — is that trade actually cheaper?
Self-attention vs recurrence cost
Does the quadratic per-layer cost of self-attention actually beat recurrence in practice?
Line up the two costs and self-attention looks like it lost the trade. A self-attention layer costs per layer; a recurrent layer costs [11]. Read that literally: for long enough sequences, deleting recurrence should have made training slower, not faster. Here is the sequence length, the number of tokens the layer processes.
"Long enough" is carrying the whole argument, and it never arrives for this running example. Translating the tired-animal sentence as a single sentence produces a token count far below in this model, and that gap between and is the ordinary case for sentence-level machine translation with word-piece or byte-pair vocabularies [11]. When , the squared factor in is attached to the smaller quantity, so self-attention's per-layer cost is actually lower than recurrence's , not higher. The naive read of the table, extrapolated to sentence-length inputs, gives the wrong answer.
Per-layer FLOPs are only one column of the table. Self-attention connects every position to every other position in a single matrix multiply, so it needs only sequential operations regardless of ; recurrence needs steps, one hidden state at a time, before position can see position . The same gap shows up in path length: the maximum distance a signal travels between any two positions is for self-attention against for recurrence, so resolving "it" back to "animal" costs one hop instead of one hop per intervening word [11]. Three separate numbers in the table (cost, parallelism, path length) all favor self-attention once , which is exactly why a per-layer exponent that looks worse in isolation does not settle the question.
None of this is a measured result. Fewer sequential steps and shorter paths are architectural properties read off a complexity table, not observed training time or translation quality. Whether they convert into faster wall-clock training and higher BLEU on an actual model is a separate claim the table cannot make on its own.
Empirical validation
Did removing recurrence actually pay off in training cost and translation quality?
Every property established so far — sequential steps, path length between "it" and "animal", cheaper per-layer cost when sequence length stays below — describes what the connection graph allows, not what training actually produced. The hook that opened this page was exactly this kind of promise: a per-layer cost of that looks worse than recurrence's , redeemed only if shorter paths and full parallelism translate into faster training and better translations. A favorable complexity table does not guarantee a better translation: architectures with appealing asymptotic bounds have failed to beat a well-tuned recurrent baseline once real optimization, vocabulary, and decoding costs enter the picture. The claim needs a number, not a table.
The number arrived. Training the big Transformer for days on P100 GPUs produced BLEU on WMT14 English-to-German, more than BLEU above the strongest previously published ensemble, and BLEU on WMT14 English-to-French, a new single-model state of the art [12] [13]. The base model — smaller and far cheaper to train — still surpassed every earlier single model and ensemble at a fraction of their training cost [14].
That result settles translation. It does not settle whether path length is doing something general or just something German-and-French-shaped. The same architecture, four layers, with only dropout, learning rate, and beam size tuned on a held-out set, was then pointed at English constituency parsing — a task whose output is a tree, not a sentence, and whose length dwarfs its input. It reached F1 in the semi-supervised setting, beaten only by a purpose-built recurrent grammar model [15]. A mechanism built to shorten the path between "it" and "animal" turned out to shorten paths generally: that is the sense in which deleting recurrence, not just approximating it more cheaply, is what won.
Transfer set
Put the pieces together
These questions combine mechanisms from more than one section. Work from the causal chain before opening the answer.
- 01
Suppose positional encoding were deleted but multi-head attention were kept exactly as in the multi-head section, with one head still specializing in coreference and another in modifier attachment. Would those two heads still tell apart "The animal didn't cross the street because it was too tired" from the word-swapped "The street didn't cross the animal because it was too tired"?
Show answer
No. Multi-head attention only fixes the problem of a single softmax having to blend two relations into one averaged value; each head still computes its routing purely from content-based scores , which depend only on what a token contains, never on where it sits. Positional encoding is the only mechanism that breaks that symmetry, since it adds a position-dependent vector to each embedding before , , are computed, letting a fixed offset become a linear function of position. Without it, swapping "animal" and "street" leaves every head's scores identical between the two sentences, because word identity alone does not encode which noun is the subject. Multi-head attention separates relations into parallel routing patterns; only positional encoding supplies the order those patterns need to route correctly.
- 02
Take the causal mask from the masked-decoder section and apply it to the 2000-token document from the complexity-tradeoff section's predict question, where . Does adding the causal mask change which layer type has the lower per-layer cost?
Show answer
No. The causal mask only overwrites illegal future scores with before softmax, so those weights become ; it does not reduce how many position pairs get scored in the first place; every position still computes a raw score against every other position, so the operation is still per layer. Since masking does not shrink that count, the sequence-length comparison from the complexity-tradeoff section is unchanged: with exceeding , the squared factor in is attached to the larger quantity, so self-attention's per-layer cost still exceeds recurrence's , exactly as it did without the mask.
- 03
The empirical-validation section reports 28.4 BLEU on English-to-German and 41.8 BLEU on English-to-French after 3.5 days on 8 P100 GPUs. Those numbers came from sentence-level translation where stayed below . If the same architecture were instead trained on inputs where , as in the complexity-tradeoff section's changed case, would those same numbers still demonstrate that deleting recurrence pays off?
Show answer
Not on the same grounds. The 28.4 and 41.8 BLEU results validate the path-length argument specifically in the regime the translation sentences fall into, , where self-attention's per-layer cost is lower than recurrence's, its sequential steps are instead of , and its path length between any two positions is instead of . At , the per-layer cost comparison reverses, so self-attention's per-layer cost now exceeds recurrence's, and the trained-faster, better-BLEU result cannot be assumed to carry over without new evidence at that sequence length. This is exactly the causal chain the hook depends on: self-attention's cost looks asymptotically worse than recurrence's , but WMT14 sentences keep below , which is what let the costlier-looking layer actually train in 3.5 days on 8 GPUs and reach 28.4 and 41.8 BLEU above every prior ensemble — the win is tied to that regime, not a universal property of deleting recurrence.
References
- [1]“they generate a sequence of hidden states , as a function of the previous hidden state and the input for position . This inherently sequential nature precludes parallelization within training examples”
- [2]AttentionS3.2“The output is computed as a weighted sum of the values, where the weight assigned to each value is computed by a compatibility function of the query with the corresponding key.”
- [3]AttentionS3.2“has mean and variance ”
- [4]AttentionS3.2“pushing the softmax function into regions where it has extremely small gradients”
- [5]AttentionS3.2“Multi-head attention allows the model to jointly attend to information from different representation subspaces at different positions.”
- [6]“we add "positional encodings" to the input embeddings at the bottoms of the encoder and decoder stacks”
- [7]“since for any fixed offset , can be represented as a linear function of ”
- [8]AttentionS3.2“We implement this inside of scaled dot-product attention by masking out (setting to ) all values in the input of the softmax which correspond to illegal connections.”
- [9]“This masking, combined with fact that the output embeddings are offset by one position, ensures that the predictions for position can depend only on the known outputs at positions less than .”
- [10]AttentionS3.2“In "encoder-decoder attention" layers, the queries come from the previous decoder layer, and the memory keys and values come from the output of the encoder.”
- [11]“Self-Attention & & & \ Recurrent & & & \”
- [12]“outperforms the best previously reported models (including ensembles) by more than BLEU, establishing a new state-of-the-art BLEU score of ”
- [13]Abstractabstract“our model establishes a new single-model state-of-the-art BLEU score of 41.8 after training for 3.5 days on eight GPUs”
- [14]“Even our base model surpasses all previously published models and ensembles, at a fraction of the training cost of any of the competitive models.”
- [15]“despite the lack of task-specific tuning our model performs surprisingly well, yielding better results than all previously reported models with the exception of the Recurrent Neural Network Grammar”