AI & Machine Learning · Paper 03 / 05

Attention Is All You Need

Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, Illia Polosukhin

2017 · NeurIPS · ~11 min read

Read the original paper

Replaces recurrent networks with attention, so every token reads every other token in parallel. Read it to understand the block inside every large language model, and the n² cost that context windows still pay.

In 2016 the strongest translation systems were stacks of recurrent networks. An LSTM encoder read the source sentence one word at a time, updating a hidden state after each word, and an LSTM decoder produced the translation one word at a time. Google’s production system stacked these layers eight deep and trained for days on about a hundred GPUs. The hardware was mostly idle in an important sense: step 10 of a sentence cannot start until step 9 has finished, so a GPU that could do thousands of things at once was doing one sentence position at a time.

In 2017 eight researchers at Google published a model with no recurrence at all. Their Transformer processed every position of a sentence at once, trained in twelve hours on eight GPUs for its base version, and beat the best published translation results. Every large language model since is built from its parts.

This explainer computes attention for a four-token sentence by hand, shows what changes when we drop the scaling factor or mask the future, and then follows the cost the design accepted, quadratic in sentence length, into the engineering of today’s long-context models.

Why recurrence was the bottleneck

A recurrent network has two problems that come from the same source. The first is speed. Training cannot be parallelised along the sentence, because each hidden state depends on the previous one. The second is distance. If the verb at position 30 needs information from the subject at position 2, that information has to survive 28 updates of the hidden state. Each update mixes in new words, and long-range information tends to fade.

Bahdanau, Cho and Bengio added attention to translation in 2014 as a patch for the second problem. When producing each output word, the decoder computed a weighted average over all the encoder’s hidden states, so it could look directly at the relevant source word instead of relying on a single compressed summary. It helped a great deal. But the encoder and decoder were still recurrent, so the first problem remained. The Transformer paper asked whether attention alone, used everywhere, could replace the recurrence.

The paper’s Section 4 makes the comparison with three quantities per layer, for a sentence of n tokens with vectors of size d. The table restates it.

layer typework per layersequential stepslongest path between two tokens
recurrentn · d²nn
convolutional, kernel kk · n · d²1logk n (dilated) or n/k
self-attentionn² · d11

Self-attention wins on the last two columns outright. On the first it wins only when n is smaller than d. For the base model d = 512, and translation sentences are usually a few dozen tokens, so in 2017 the n² term looked harmless. The authors noted that very long sequences would need restricted attention. That remark became an industry, as we will see.

Attention over four tokens, by hand

Each token starts as a vector (its embedding plus a position signal). Self-attention multiplies that vector by three learned matrices to get three smaller vectors: a query, a key and a value. The query describes what this token is looking for, the key describes what it offers to others, and the value is what it hands over if chosen. The output for a token is a weighted average of all the values, with weights from how well its query matches each key.

Take the sentence “the cat chased mice” and compute the new vector for “chased”. To keep the arithmetic small we use dk = 2 and write down the projected vectors directly; in the model they come from multiplying each token’s embedding by WQ, WK and WV.

query of "chased"  q = (2, 1)

token     key k     q·k     ÷ √2     softmax    value v
the       (0, 1)     1      0.707     0.046     (0.1, 0.0)
cat       (2, 0)     4      2.828     0.383     (1.0, 0.0)
chased    (1, 1)     3      2.121     0.189     (0.0, 0.2)
mice      (1, 2)     4      2.828     0.383     (0.0, 1.0)

output = 0.046·(0.1,0) + 0.383·(1,0) + 0.189·(0,0.2) + 0.383·(0,1)
       = (0.388, 0.421)

The softmax step is exp of each scaled score divided by their sum: e0.707 = 2.03, e2.828 = 16.91, e2.121 = 8.34, and the total is 44.19. The verb’s query matched the two nouns equally and the article hardly at all. Its new vector is roughly an even mix of the value for “cat” (first coordinate) and the value for “mice” (second coordinate). After one layer, the representation of “chased” carries information about who chased and what was chased. A recurrent network would have had to carry “cat” forward through the hidden state to get the same effect.

Every token does this at the same time with its own query. Stack the queries into a matrix Q, the keys into K and the values into V, and the whole layer is softmax(QKT / √dk) V: two matrix multiplications and a softmax. That form is why the model trains fast. GPUs are built to multiply large matrices.

token vectorsquery = xWqkey = xWkvalue = xWvscores = QKᵀ / √dsoftmax → weightsweights × Vnew token vectors× 8 heads in parallel,each with its own W
Scaled dot-product attention as a data flow. Queries are compared with keys, the scores are scaled and turned into weights, and the weights mix the values. The paper runs eight of these heads side by side, each with its own projection matrices.
Predict first

Suppose d_k is 64, as in the paper, and the query and key components are roughly independent with mean 0 and variance 1. Without dividing by √d_k, what do typical attention scores look like, and what happens to the softmax?

Show the worked answer

A dot product of two such 64-dimensional vectors is a sum of 64 terms, each with variance 1, so it has variance 64 and a standard deviation of 8. Scores of 8, 0 and −8 within one row are ordinary.

Softmax over (8, 0, −8) gives about (0.9997, 0.0003, 0.0000). The weights are almost one-hot, and the gradient through a softmax output near 0 or 1 is tiny (it is roughly p(1 − p)), so the query and key matrices barely learn. Divide by √64 = 8 and the scores become (1, 0, −1); softmax gives (0.665, 0.245, 0.090), which is soft enough to learn from. The scaling keeps the score variance near 1 whatever the head size.

Two variables to change: the scale and the mask

In our four-token example the effect of the scaling is mild, because dk = 2. Without it the scores are 1, 4, 3, 4 and the weights become 0.021, 0.414, 0.152, 0.414: slightly sharper, nothing dramatic. The Predict above shows why it matters at the paper’s size. The authors give the variance argument in a footnote, and note that additive attention (the 2014 kind) did not have the problem but was slower than a matrix multiply.

The second variable is what each token is allowed to see. The encoder lets every token attend to every other. The decoder generates text left to right, so during training it must not see the words it is about to predict. The fix is a mask: before the softmax, set the score for every future position to minus infinity, so its weight becomes exactly zero. Apply that to “chased” and the score for “mice” disappears. The remaining weights are 2.03, 16.91 and 8.34 out of 27.28: 0.074 for “the”, 0.620 for “cat”, 0.306 for “chased” itself. The output becomes (0.627, 0.061). Now “chased” is mostly about the cat, because it cannot know yet what was chased.

The mask is what separates the decoder’s self-attention from the encoder’s (the decoder also attends to the encoder’s output), and it decided what later models became. GPT kept only the masked decoder stack and trained it to predict the next token. BERT kept only the unmasked encoder and trained it to fill in blanks. The AttentionHeatmap below lets you pick any token as the query and watch its weights change when the last word of the sentence changes. Its example sentence comes from Google’s blog post announcing the paper rather than the paper itself; the paper’s appendix shows similar pronoun-resolution patterns on its own sentences.

Try itWhat does “it” look at?

Click a token in the sentence to make it the query. The bars are its attention weights over every token, including itself. Swap the last word and watch the same mechanism resolve “it” differently.

queryit4%The25%animal4%didn't6%cross4%the7%street4%because22%it4%was5%too15%tired
the whole head · rows are queries, columns are keys

For “it”, the strongest keys are “animal” (25%), “it” (22%), “tired” (15%). The output of this head for “it” is a blend of their value vectors in those proportions, so the word carries the meaning of what it refers to. Google's 2017 post announcing the Transformer used this same sentence to show attention resolving a pronoun.

Many heads, positions, and the rest of the block

One attention head computes one set of weights per token, and one set of weights can express one kind of relation. The paper splits the 512-dimensional model into eight heads of 64 dimensions each, runs them in parallel with separate projection matrices, and concatenates their outputs. Because each head works in 64 dimensions, eight heads cost about the same as one 512-dimensional head. In the ablations (Table 3), a single head was 0.9 BLEU worse than the best setting, and going to 32 tiny heads also hurt. Different heads do learn different patterns: some track the previous word, some link pronouns to nouns, some follow syntax.

Attention on its own has no idea of order. Shuffle the input tokens and each token gets the same output, shuffled. The authors fixed this by adding a positional encoding to each embedding: sines and cosines of the position at different frequencies, so every position gets a distinct pattern and relative offsets correspond to simple linear transformations. They also tried learned position embeddings and got nearly identical results; they chose the sinusoids hoping they would extend to sequences longer than any seen in training.

Each block wraps attention with a small feed-forward network applied to each token separately (512 → 2,048 → 512, with a ReLU), and each of those two sub-layers has a residual connection and layer normalisation. Attention moves information between tokens; the feed-forward layer processes it within each token. The base model stacks six such blocks in the encoder and six in the decoder, about 65 million parameters in all. The big model doubles the width and has about 213 million.

The training recipe carried two details that later turned out to matter. The learning rate rose linearly for the first 4,000 steps and then decayed with the inverse square root of the step number, scaled by 1/√dmodel. For the base model that is a peak of about 0.0442 × 4,000−0.5 ≈ 7 × 10−4 at step 4,000, halving by step 16,000. Without the warm-up, the original arrangement of normalisation layers tended to diverge early in training, a problem later work traced and fixed. The second detail was label smoothing: the training targets put 90 per cent of their probability on the correct token and spread the rest over the vocabulary. The paper reports that this made the model’s perplexity worse, since it learns to be less certain, while improving BLEU. That is a reminder that the loss being minimised and the score being reported are not the same thing.

encoder · ×6input embedding + positionmulti-head self-attentionadd & normfeed-forward (per token)add & normdecoder · ×6output so far + positionmasked self-attentionattention over encoder outputfeed-forwardnext-token probabilitiesGPT keeps only the decoder stack; BERT keeps only the encoder
The full model in the paper: six encoder blocks and six decoder blocks, each made of attention and a per-token feed-forward layer with residual connections. GPT-style models keep only the decoder stack; BERT keeps only the encoder.

The results that made people pay attention were on WMT 2014 translation. The big model scored 28.4 BLEU on English–German, more than 2 points above the previous best including ensembles, and 41.8 on English–French, after 3.5 days on eight P100 GPUs. The paper’s Table 2 compares training cost in floating-point operations, and the Transformer reached those scores for a fraction of the compute of the recurrent and convolutional systems it beat.

The cost they accepted: n²

Follow the quadratic term forward to a modern use. A token attends to every other token, so one head in one layer computes n × n scores. For a 40-token sentence that is 1,600 numbers, nothing. For a 100,000-token document it is 1010 scores. Stored as 16-bit numbers, that is 20 GB for one head in one layer, before the softmax and its gradient. A model with 32 heads and 32 layers cannot hold that, and the arithmetic grows by a hundred times each time the context grows by ten.

Three lines of later work responded. FlashAttention (2022) computes exact attention in tiles that fit in the GPU’s fast on-chip memory and never stores the full n × n matrix, so memory grows linearly with n even though the arithmetic is still quadratic. Sparse and sliding-window attention restrict which pairs are scored, giving up some direct paths for much less work. And at generation time, models keep the keys and values of earlier tokens in a KV cache so each new token only computes its own query against the stored keys. That cache, at roughly 2 × layers × heads × head size numbers per token, is now often the limit on how many users one GPU can serve, which is why later models share keys and values across heads (multi-query and grouped-query attention).

What later work changed

The block in today’s models is recognisably the 2017 block with a handful of revisions. Layer normalisation moved from after each sub-layer to before it (“pre-norm”), because the original placement made very deep stacks unstable without careful learning-rate warm-up; the paper’s warm-up schedule was partly compensating for this. Sinusoidal positions were largely replaced, first by learned embeddings in GPT and BERT and then by rotary position embeddings (2021), which encode relative position directly in the query–key dot product and extend better to long contexts. Most large models dropped the encoder entirely and use a decoder-only stack. The feed-forward layer acquired gated variants, and in some models was split into many experts with only a few active per token.

The architecture also left language. Vision Transformers (2020) cut an image into 16×16 patches and treat each as a token. Speech, protein structure and robotics models followed. The title’s claim was provocative in 2017. In practice, attention needed the feed-forward layers, residual connections, normalisation and positions as well, but it did replace recurrence almost everywhere.

When attention is the wrong tool

If the sequence is very long and the relevant information is mostly local, as in raw audio or some genomics and time-series data, paying n² to compare every pair is wasteful. Convolutions or the newer state-space models (such as Mamba) process sequences in linear time and are competitive there. For small datasets, attention’s lack of built-in assumptions about locality is a cost: a convolutional network knows nearby pixels matter before it sees any data, while a Vision Transformer has to learn it, and needs more data to do so. And when latency per token at generation time is the constraint, the KV cache and quadratic prefill are the first things to measure.

How to read the original

Read Section 3.2 first, with Figure 2: scaled dot-product attention and multi-head attention, including the footnote on why the scores are divided by √dk. Then Section 3.5 on positional encoding, and Section 4, “Why Self-Attention”, with Table 1; this is the paper’s own argument and the clearest statement of the trade it made. Figure 1, the full architecture diagram, is easier to follow after those.

Section 5 (training) is worth a skim for the details that turned out to matter: the learning-rate warm-up over the first 4,000 steps, label smoothing, dropout on the residual connections. Table 2 holds the translation results and training costs. Table 3, the ablations, is the most informative table: rows A to E vary the number of heads, key size, model size, dropout and position encoding one at a time. The attention visualisations at the end of the arXiv version show heads tracking long-distance dependencies and resolving “its” to its noun. If you want to read the paper with code beside it, the Harvard “Annotated Transformer” in the reading list reproduces it line by line.

The Transformer made it practical to train much larger language models, because every token in a batch could be processed in parallel. The next paper, GPT-3, takes the decoder half, scales it to 175 billion parameters, and finds that a model that large can pick up a new task from a few examples written into its input.