Attention Is All You Need
A translation model with the recurrence taken out, which turned out to matter far more than the translation.
Read the original ↗This is a paper about machine translation. It contains no language model, no scaling law, no chatbot and no claim about what happens if you make it a thousand times bigger. It is worth reading precisely because of how little it claims.
The problem it was solving
To translate a sentence, a machine has to work out which words relate to which. In 2017 the standard way to do that was to read the sentence one word at a time, keeping a running summary in memory, the way you would read aloud. This paper proposes reading the whole sentence at once instead, and letting every word directly compare itself to every other word to decide what it should pay attention to, which is what the word attention means here, a set of weights saying how much each position should draw from each other position. The reason that change mattered is almost entirely practical: reading one word at a time forces the work into a queue, and the hardware these models train on is built to do thousands of things simultaneously. The architecture that came out of this decision is called the transformer, and it is underneath essentially every language model in use now, which is why a translation paper from a single conference is worth an hour of anyone's time.
In 2017 the best sequence models were recurrent: read a sentence one position at a time, carrying a hidden state forward. That design has a property nothing about the maths requires, but the hardware cares about enormously, position t cannot be computed until position t-1 is done. Training is a long chain of steps that must happen in order, on machines built to do thousands of things at once.
Attention already existed, and was already being used, as an addition to those recurrent models: a way for the decoder to look back at any position of the input rather than relying on a single compressed state. The paper's question is what happens if attention stops being the addition and becomes the whole thing.
The motive is stated as parallelisation and path length, and the paper argues it with a comparison table rather than a slogan: for a self-attention layer, a recurrent layer and a convolutional layer, how much computation each does, how much of that computation must run in sequence, and how many steps a signal must travel to connect two distant positions. Self-attention costs more arithmetic per layer and grows quadratically with sequence length, the paper says so, but its sequential depth and its path between any two positions are both constant.
Read that table's first column carefully, because it contains a condition that most later readers have quietly stopped satisfying. A self-attention layer costs on the order of the sequence length squared times the width of the representation. A recurrent layer costs the sequence length times the width squared. Set those side by side and attention is the cheaper of the two exactly when the sequence is shorter than the representation is wide, which the paper points out is the usual case for the sentences it is translating. With a width of 512 and sentences of a few dozen tokens, the quadratic term is not merely tolerable, it is a saving. The whole cost argument in this paper is made inside that regime, and every long-context system since has been operating outside it.
flowchart TB
subgraph REC["Recurrent, the 2017 default"]
r1["word 1"] --> r2["word 2"] --> r3["word 3"] --> r4["word 4"]
end
subgraph ATT["Self-attention"]
a0["one step: every position<br/>reads every other position"] --> a1["word 1"]
a0 --> a2["word 2"]
a0 --> a3["word 3"]
a0 --> a4["word 4"]
endCount the steps between word 1 and word 4 in each half. Above, information passes through three intermediate states and cannot be computed until the ones before it are done. Below, the distance is one and every position is computed at the same time. That difference is what the hardware was waiting for.
What it actually claims
The claim is an architecture and two translation results. The architecture is an encoder-decoder built from stacked identical layers, with attention and position-wise feed-forward sublayers, residual connections and layer normalisation throughout, and no recurrence or convolution anywhere.
The specifics are modest enough to be worth stating, because the reputation of this paper is not. The base model is six encoder layers and six decoder layers, a representation width of 512, eight attention heads each working in 64 dimensions, and an inner feed-forward width of 2048, which comes to about 65 million parameters. The larger model widens that to 1024 with sixteen heads and an inner width of 4096, about 213 million parameters. Both are described in the paper's table of model variations, and both are smaller than a great many models trained by individuals today.
flowchart LR X["The token vectors<br/>coming into the layer"] --> Q["Queries: what each<br/>position is looking for"] X --> K["Keys: what each<br/>position advertises"] X --> V["Values: what each position<br/>would contribute if attended to"] Q --> S["Score every pair:<br/>query dotted with key"] K --> S S --> D["Divide by 8, the square root<br/>of the key width of 64"] D --> W["Softmax, so each position's<br/>weights sum to one"] W --> O["Output: the weighted<br/>sum of the values"] V --> O
Three views of the same input, one comparison, one normalisation, one weighted sum. The only place the positions meet is the scoring box, which is both why the layer parallelises perfectly and why its cost grows with the square of the number of positions.
- Scaled dot-product attention
- Every position produces a query, a key and a value. Attention scores are dot products of queries against keys, scaled down by the square root of the key dimension before the softmax, the scaling is there because large dot products push the softmax into a region where gradients nearly vanish. The output is the weighted sum of values.
- Multiple heads
- Rather than one attention over the full width, the model projects down into several lower-dimensional subspaces and attends in each in parallel, then concatenates. The paper's argument is that this lets different heads attend to different kinds of relationship at once, at roughly the cost of a single full-width attention.
- Position has to be put back in
- With recurrence gone, nothing in the model knows what order the tokens came in, attention is a set operation. The paper adds fixed sinusoidal position signals of varying frequency to the input embeddings. It also reports trying learned position embeddings and finding results essentially the same, choosing the sinusoids on the hypothesis that they might extrapolate to sequences longer than any seen in training.
- The results are translation results
- The evaluation is the WMT 2014 English-to-German and English-to-French translation tasks, where the larger model set a new state of the art, at a fraction of the training cost of the best previous systems. There is also one generalisation experiment, on English constituency parsing, to show the architecture is not translation-specific. That is the extent of the empirical claim.
- Where the parameters actually sit, counted from the paper's own dimensions
- Take one encoder layer of the base model and add it up. The attention sublayer needs four square projections at the model width: queries, keys, values and the output, which is four times 512 times 512, a little over one million parameters. The feed-forward sublayer is two matrices between widths 512 and 2048, which is two times 512 times 2048, a little over two million. So roughly two thirds of every layer's weights are in the part that has nothing to do with attention, and that ratio is set by the choice to make the inner width four times the model width, which every descendant architecture kept. It is worth doing this arithmetic once, because it makes the paper's title a claim about which component was novel rather than a claim about where the capacity is.
- The recipe is part of the claim, and so is the size of the win
- The training procedure is specified in detail and the details are load-bearing rather than incidental: Adam with a learning rate that rises linearly for the first four thousand steps and then decays with the inverse square root of the step, dropout applied to every sublayer output as well as the embedding sums, and label smoothing that deliberately worsens the model's confidence and improves its translation score. The base model trains for one hundred thousand steps in about twelve hours on eight GPUs. The larger one for three hundred thousand steps in about three and a half days. The results are 28.4 BLEU on English to German and 41.8 on English to French, which the paper presents as beating the previous best systems, ensembles included, at a small fraction of their training cost. The ablation table alongside is the more instructive read, because it shows the architecture is not indifferent to its own settings, single-head attention is measurably worse than the eight-head configuration, and adding heads past a point gets worse again.
- It is small, and trained on one machine
- The models here are trained on a single machine with eight GPUs, hours for the base model, a few days for the larger one. Worth holding in mind when reading anything that treats this paper as the origin of frontier-scale training.
The one idea worth stealing
The contribution is a removal. Attention was not new here. Taking the recurrence out was, and the reason it mattered is not that attention is a better way to relate positions: it is that the recurrence was the part of the design forcing the work to happen in order.
That is a design move worth carrying into work that has nothing to do with models. Look at the thing you are building and find the dependency that makes step t wait for step t-1. Then ask whether it is load-bearing or merely inherited. The parallel ceiling is set by the fraction that must stay sequential, and no amount of extra hardware moves it - so the highest-leverage change available is usually deleting a sequential dependency rather than speeding one up.
The second thing to steal is the way the argument is made, which is a table rather than a benchmark. Three candidate designs, three columns: total work per layer, how much of that work has to happen in sequence, and how far a signal has to travel to connect two distant parts of the input. Any argument about a redesign can be laid out that way, and doing so tends to end the argument, because it separates the quantity everyone is worrying about from the quantity that is actually binding. Here the total work went up and the paper won anyway, since the column that mattered was the sequential one. Most performance debates would be shorter if someone drew the three columns first.
It also cuts the other way, and the paper is a case study in that too: the architecture pays more total arithmetic per layer for its parallelism, and accepts a cost that grows with the square of the sequence length. That was a good trade in 2017 because the arithmetic was the abundant resource. Every design of this shape is a bet about which resource stays cheap.
What aged badly
Very little of the paper is wrong. What is wrong is nearly everything it gets credited with, so this section is mostly a list of things that are somebody else's later work.
- It is not about language models
- There is no pretraining here, no next-token objective on a large corpus, no fine-tuning, no in-context learning and no scaling law. Those arrived over the following years in other papers, and they are the ideas that actually produced the systems people now have in mind when they cite this one. Read as the origin of the modern language model, it will disappoint. Read as the architecture those later papers happened to pick up, it is exactly right.
- The shape it proposes is not the shape that won
- The paper specifies an encoder-decoder for translation. Most of what followed at scale is decoder-only, which the paper does not propose or anticipate.
- The parts have been replaced piece by piece
- Sinusoidal position encodings gave way to learned ones, and later to rotary and other relative schemes, in subsequent work. The placement of layer normalisation and the learning-rate warm-up the paper describes turned out to matter for stability at larger scales, and were revisited. What survived is the attention block and the residual stack. A fair amount of the specific recipe did not.
- The quadratic cost became the central engineering problem
- The paper flags it and moves on, suggesting restricted attention as future work for very long inputs. That single line describes most of a decade of subsequent effort. Note also what the paper never had to think about: serving. It measures training cost. The cache of keys and values that dominates the economics of generating tokens one at a time is nowhere in it.
- Attention is not, in fact, all you need
- In the architecture the paper specifies, the position-wise feed-forward sublayers hold the bulk of the parameters, the title names the part that was novel, not the part that does most of the work. Relatedly, the paper includes visualisations of attention weights and observes that heads appear to pick up syntactic and semantic structure. Later work has argued at length that attention weights should not be read as explanations of a model's behaviour. That argument is not in this paper, and neither is the strong version of the claim it responds to.
- Its cost argument holds in a regime the field left almost immediately
- The paper's own comparison says attention is cheaper than recurrence when the sequence is shorter than the model is wide, and it is translating sentences with a width of 512. Almost everything built afterwards inverted that ratio: contexts of thousands and then hundreds of thousands of tokens, against widths that grew far more slowly. Once the sequence is much longer than the width, the quadratic term is the whole bill, and the line the paper spends on restricted attention as future work turns into an entire research area plus a great deal of systems engineering. Nothing here is wrong. The trade was simply evaluated in the only setting that existed at the time, and the setting changed within about two years.
- What to take from it today
- Read it for the removal and the table, not for the origin story. The removal is the transferable lesson: the recurrence was not doing anything the maths demanded, it was a habit that forced work into a queue, and taking it out unlocked hardware that had been sitting idle. That question, which of my dependencies is load-bearing and which is inherited, is worth asking about any pipeline, not any model. The table is the second lesson: state total work, sequential work and distance separately, and you will usually find that the number people are optimising is not the number that binds. And when someone cites this paper for scaling laws, pretraining, chat behaviour or emergent capability, they are citing the wrong document. Those belong to later work, and knowing which paper says what is the difference between understanding the field and repeating it.
Related on chalk
The same idea as a board, lab, video or lesson.
- BoardAttention and the Transformerthe architecture, drawn block by block
- BoardTokens and Embeddingswhat the model is given before any attention happens
- BoardConcurrency and the Hardwarethe ceiling the sequential part imposes, which is the paper's real motive
- LabTokens and embeddingsthe input side, run on your own sentence
- LabThe batch size dialthe serving cost the paper never had to pay
- LabThe parallel ceilingwhy removing a sequential dependency is worth this much trouble
- VideoAttention from scratch: the mechanism that ate the fieldthe mechanism itself
- VideoAttention in production: KV cache, MQA, GQA and MLAwhat the industry did with it afterwards
- VideoRNNs and LSTMs: the memory that almost workedthe recurrent models the paper is replacing
- LessonAttention & the TransformerUses the board Attention and the Transformer
- LessonRNNs and LSTMsUses the board Attention and the Transformer
- LessonAttention by HandUses the board Attention and the Transformer
- LessonAttention, grown up: RoPE, GQA, FlashAttention and MambaUses the board Attention and the Transformer
- LessonTokens & EmbeddingsUses the board Tokens and Embeddings
- LessonLooking Inside the ModelUses the board Tokens and Embeddings
- LessonThe MLP Language ModelUses the board Tokens and Embeddings
- LessonGroups nobody labelled: k-means and PCAUses the board Tokens and Embeddings
- LessonBuild the tokenizer: BPE by handUses the board Tokens and Embeddings
- LessonPeople who bought this: recommenders and time seriesUses the board Tokens and Embeddings
- LessonConcurrency & the HardwareUses the board Concurrency and the Hardware
- LessonWaiting without spinningUses the board Concurrency and the Hardware
- LessonFour ways to get stuck: deadlockUses the board Concurrency and the Hardware
- LessonOne key, many handsUses the board Concurrency and the Hardware
- LessonWho sees your write first: memory orderingUses the board Concurrency and the Hardware
Further reading
Read the original for the full argument and its evidence.