Attention Is All You Need
medium 40 minThe 2017 paper that introduced the Transformer.
Attention in 90 seconds
1:30Reel coming soon
Theory
Read or listen first. About 5 min.
What it is
Attention Is All You Need is a paper by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser and Illia Polosukhin. It was posted to arXiv as 1706.03762 on 12 June 2017 and appeared at NIPS 2017, the 31st Conference on Neural Information Processing Systems, in Long Beach. The paper's footnote says the listing order is random and all eight contributed equally.
It introduced the Transformer: a model for turning one sequence into another, such as an English sentence into German, built only from attention and small feed-forward layers. There is no recurrence and no convolution (abstract, §3). Each word asks a question (a query), offers a label for matching (a key) and carries content to hand over (a value). A word's new meaning is a weighted mix of the values of the words whose keys match its query best.
This page follows one sentence of ours all the way: "The parcel did not fit the slot because it was too big." The word it must find out that it means the parcel. Change the end to "too narrow" and it must mean the slot. Hold that puzzle in mind; the answer comes after the mechanism.
Why it exists
In 2017 the best translators were recurrent networks. They read a sentence one word at a time and carry one hidden state from word to word. §1 of the paper names the problem: this sequential nature rules out parallel work inside one training example, and memory limits how many examples can be batched. More GPUs do not help much when every step waits for the step before.
Recurrence also makes distant words far apart. A signal from word 1 must pass through every step to reach word 40. §4 compares the longest path between two positions: it grows with length for a recurrent layer and is constant for self-attention. Shorter paths make long-range relations easier to learn (§4, citing Hochreiter and others).
The Transformer fixed both at once, beat every earlier result on two translation benchmarks (Table 2), and trained the base model in about 12 hours on one machine with 8 GPUs (§5.2). Its decoder half became GPT, its encoder half became BERT, and its attention matrix became the main cost that inference engineers fight today.
A short history
1997
Hochreiter and Schmidhuber publish Long Short-Term Memory in Neural Computation 9(8), the recurrent cell the 2017 paper names as the state of the art it replaces (reference 13 of the paper).
2014
Bahdanau, Cho and Bengio post "Neural Machine Translation by Jointly Learning to Align and Translate" to arXiv on 1 September (1409.0473): a recurrent decoder learns to attend to encoder states. This is the attention the Transformer builds on (reference 2).
2017
On 12 June, version 1 of 1706.03762 is posted to arXiv. The paper is presented at NIPS 2017 in Long Beach. The code is released in tensor2tensor (§7).
2018
On 11 October, BERT (1810.04805) is posted: a stack of Transformer encoders pretrained on unlabelled text, then fine-tuned.
2019
On 6 November, Noam Shazeer posts multi-query attention (1911.02150): all heads share one key and one value, because decoding is slowed by loading the large key and value tensors.
2020
On 28 May, GPT-3 (2005.14165) is posted: an autoregressive model with 175 billion parameters. The same year, Xiong and others show that moving layer normalization changes how training behaves (2002.04745).
2022
On 27 May, FlashAttention (2205.14135) is posted: exact attention computed in tiles to cut reads and writes to GPU memory.
2023
GQA (2305.13245, 22 May) groups heads to share keys and values, and PagedAttention (2309.06180, 12 September) manages the KV cache in blocks like virtual memory. On 2 August, version 7 of the Transformer paper, the one cited on this page, is posted.
Words to know
- Token
- One piece of text the model reads, often a word or part of a word. The paper used byte-pair or word-piece pieces (§5.1).
- Embedding
- A list of numbers that stands for a token. In the base model each list has d_model = 512 numbers (§3.1, §3.4).
- Query, key, value (Q, K, V)
- Three lists made from each token's embedding by learned matrices. The query is what this token looks for, the key is what it offers for matching, the value is what it hands over when chosen.
- Self-attention
- Attention where the queries, keys and values all come from the same sequence, so every position can look at every position (§2, §3.2.3).
- Softmax
- Turns a row of scores into weights that are all positive and add up to 1. Large scores take most of the weight.
- Head
- One attention computation with its own projections. The paper runs h = 8 heads side by side, each with 64 numbers per query, key and value (§3.2.2).
- Mask
- Scores set to minus infinity before the softmax, so their weight becomes exactly 0. The decoder masks later positions (§3.2.3).
- Positional encoding
- A pattern of sines and cosines added to each embedding so the model knows where each token sits (§3.5).
- Encoder and decoder
- The encoder reads the whole input at once. The decoder writes the output one token at a time, looking at its own earlier tokens and at the encoder's output (§3, §3.1).
- KV cache
- During generation, the keys and values of earlier tokens never change, so they are stored and reused. Each new token adds one key and one value per layer and head. Not a term the paper uses; it follows from §3.2.3.
How it works
Step through the idea, or press Play.
Tokens plus position. Embeddings plus a sine and cosine pattern
Understand it
Start here
The paper at a glance
| Citation | Vaswani, Shazeer, Parmar, Uszkoreit, Jones, Gomez, Kaiser, Polosukhin. Attention Is All You Need |
|---|---|
| Venue and year | NIPS 2017 (now NeurIPS), Long Beach. arXiv 1706.03762, first posted 12 June 2017 |
| Read it | [arxiv.org/abs/1706.03762](https://arxiv.org/abs/1706.03762), 15 pages. This page cites version 7 |
| Level | Must-know: its ideas come up in almost every AI engineering interview |
| Time | About 40 minutes here, then 10 minutes for pass 1 of the paper itself |
| Before this | Tokens and embeddings and the prediction engine |
| Last checked | 27 November 2026, against the arXiv listing and the NeurIPS proceedings page |
Before the paper
A whisper line and a ring
Five friends hold one word each of our sentence. First they pass the meaning down a whisper line, the way a recurrent network does. Then they try something else: a ring where everyone can ask everyone at once.
The line is slow and forgets. The ring is fast and remembers, but everyone talks to everyone.
2014 to 2017
How translation worked before
A recurrent encoder read the source sentence one word at a time and produced a hidden state for each word. A recurrent decoder then wrote the translation one word at a time. Since 2014 the decoder could also attend to the encoder's states (Bahdanau and others, reference 2 of the paper), so it no longer had to squeeze the whole sentence into one vector. But both halves were still recurrent.
A recurrent translator with attention
Three things that hurt
No parallel work inside a sentence
State h_t needs h_(t-1). §1 says this rules out parallel work within a training example, which matters more as sentences get longer.
Long paths
A relation between word 1 and word 40 travels through 39 steps. Table 1 puts the longest path of a recurrent layer at O(n).
Convolutions did not fully fix it
ConvS2S and ByteNet computed all positions in parallel, but the operations needed to relate two positions grew with their distance: linearly for ConvS2S, logarithmically for ByteNet (§2).
The key idea
One equation does the work
The whole paper rests on one line. Pack the queries of all tokens into a matrix Q, the keys into K and the values into V. Then:
Scaled dot-product attention (equation 1, §3.2.1)
The row for "it", with our numbers
| Key of | q · k | ÷ √2 | Weight after softmax |
|---|---|---|---|
| parcel | 4 | 2.83 | 0.62 |
| fit | 0 | 0 | 0.04 |
| slot | 0 | 0 | 0.04 |
| it | 2 | 1.41 | 0.15 |
| big | 2 | 1.41 | 0.15 |
How it works
Eight steps, each with a reason
Read each step, then cover the reason and say why the step exists before you read it. Explaining a step to yourself is what makes it stick. The Visualize tab plays the same eight steps with numbers.
- 1
1. Tokens become vectors, plus position
Each token gets a learned embedding of 512 numbers, multiplied by √512, and a positional encoding is added (§3.4, §3.5). Why: attention compares every token with every token and has no idea of order. Without position, "parcel fits slot" and "slot fits parcel" look the same.
- 2
2. Project to Q, K and V
Three learned matrices turn each vector into a query, a key and a value. Why: one token needs three roles. What it looks for, how it is found, and what it hands over are different things.
- 3
3. Score every pair
Take the dot product of each query with every key. Why: a dot product is large when two vectors point the same way, and a matrix product computes all pairs at once on a GPU (§3.2.1).
- 4
4. Scale, softmax, mix
Divide by √d_k, apply softmax per row, and take the weighted sum of values. Why: unscaled scores grow with d_k and push softmax into a region with tiny gradients (§3.2.1, footnote 4). Softmax makes the lookup soft and differentiable, so it can be trained.
- 5
5. Many heads
Do steps 2 to 4 eight times with smaller projections of 64, concatenate, and project back to 512 (§3.2.2). Why: one head averages everything into one blend. Eight heads can track meaning, neighbours and grammar separately, for about the same cost as one big head.
- 6
6. Mask the future in the decoder
Set scores for later positions to minus infinity before softmax (§3.2.3). Why: during training the decoder sees the whole target sentence at once. Without the mask it could copy the word it is meant to predict.
- 7
7. Add, normalise, feed forward, stack
Each sub-layer's output is LayerNorm(x + Sublayer(x)), then a two-layer network with 2048 inner units runs on each position. Six such layers make the encoder, six the decoder (§3.1, §3.3). Why: the residual path lets signals and gradients pass through deep stacks, and the feed-forward part does per-token computation that attention does not.
- 8
8. Pay for it: n² and the cache
Every layer and head computes n × n scores. When generating, keys and values of earlier tokens are kept. Why it matters: this is why long contexts are expensive and why serving systems manage KV memory so carefully.
Step 1
Where am I? Positional encoding
A ring of people has no first seat. Attention is the same: shuffle the tokens and every score is the same, only reordered. §3.5 adds a pattern to each embedding so that each position looks different.
Sines and cosines (§3.5)
The pattern for d_model = 4, our small example
| Position | sin, fast | cos, fast | sin, slow | cos, slow |
|---|---|---|---|---|
| 0 | 0.00 | 1.00 | 0.00 | 1.00 |
| 1 | 0.84 | 0.54 | 0.01 | 1.00 |
| 2 | 0.91 | -0.42 | 0.02 | 1.00 |
| 3 | 0.14 | -0.99 | 0.03 | 1.00 |
Why waves
The authors hoped the model could attend by relative position, because PE at pos + k is a linear function of PE at pos for any fixed k (§3.5).
Learned positions worked as well
Table 3, row E: learned positional embeddings gave nearly identical results, 25.7 BLEU against 25.8. They kept the waves because they might extend to longer sentences than seen in training (§3.5).
Steps 2 to 4
Scaled dot-product attention
A matching game helps. Every token wears a badge (key), holds a question (query) and carries a bag (value). The question is held against every badge; good matches pour more from their bag. That is the whole operation, done for every token at once.
Why divide by √d_k (§3.2.1, footnote 4)
import mathdef softmax(row): m = max(row) e = [math.exp(x - m) for x in row] return [x / sum(e) for x in e]def attend(q, keys, values): d_k = len(q) scores = [sum(a * b for a, b in zip(q, k)) / math.sqrt(d_k) for k in keys] w = softmax(scores) return w, [sum(wi * v[j] for wi, v in zip(w, values)) for j in range(len(values[0]))]keys = [[2, 0], [0, 1], [0, 2], [1, 1], [1, 0]] # parcel, fit, slot, it, bigvalues = [[1, 0], [0, 0], [0, 1], [0, 0], [0, 0]] # [is the parcel, is the slot]w, out = attend([2, 0], keys, values) # the query of "it"print([round(x, 2) for x in w], [round(x, 2) for x in out])print("too wide a spread:", [round(x, 2) for x in softmax([8, 4, 0])], "vs", [round(x, 2) for x in softmax([1, 0.5, 0])])Two ways to score, from §3.2.1
| Additive attention (Bahdanau) | Dot-product attention (this paper, scaled) | |
|---|---|---|
| Score | A small feed-forward network on q and k | q · k / √d_k |
| Theory cost | Similar | Similar |
| In practice | Slower | Much faster and smaller in memory: it is one matrix product |
| Large d_k without scaling | Better than unscaled dot product | Needs the √d_k scale to keep up |
Reveal
The answer to the puzzle
With the sentence ending "too big", the query of it matches the key of parcel best, and 62% of its value comes from the parcel. End it "too narrow" and earlier layers give it a different query, which matches slot: 56% of the weight moves to the slot. Same mechanism, different context, different answer. Nothing about "it" was hard-coded.
Real models show this. The paper's appendix (Figure 4) shows two heads in layer 5 of 6 where the word "its" attends sharply to "Law" in "The Law will never be perfect, but its application should be just". The authors describe these heads as apparently involved in anaphora resolution: working out what a pronoun refers to.
| Sentence ends | Weight on parcel | Weight on slot | "it" means |
|---|---|---|---|
| "because it was too big" | 0.62 | 0.04 | the parcel |
| "because it was too narrow" | 0.03 | 0.56 | the slot |
Step 5
Eight heads instead of one
One head gives one blend per token, and §3.2.2 says averaging inside one head inhibits looking at different things. So the model runs h heads in parallel, each with its own projections into a smaller space, and joins the results.
Multi-head attention (§3.2.2)
How many heads? Table 3, rows A (same computation each time)
| Heads h | d_k = d_v | BLEU (dev) | Perplexity (dev) |
|---|---|---|---|
| 1 | 512 | 24.9 | 5.29 |
| 4 | 128 | 25.5 | 5.00 |
| 8 (base) | 64 | 25.8 | 4.92 |
| 16 | 32 | 25.8 | 4.91 |
| 32 | 16 | 25.4 | 5.01 |
Inside one multi-head layer
Where attention is used
Three kinds of attention in one model
| Kind (§3.2.3) | Queries from | Keys and values from | Mask |
|---|---|---|---|
| Encoder self-attention | The previous encoder layer | The previous encoder layer | None: every word sees every word |
| Decoder self-attention | The previous decoder layer | The previous decoder layer | Later positions set to minus infinity |
| Encoder-decoder attention | The previous decoder layer | The output of the encoder | None: every output word sees every input word |
Translating one sentence
Steps 6 and 7
The layer, the mask and the stack
One encoder layer, as §3.1 describes it
The feed-forward part (equation 2, §3.3)
Generating with the mask
Training
How they trained it
The training run of the base model, from §5 and §6.1
The recipe
| Item | Value | Section |
|---|---|---|
| English to German data | About 4.5 million sentence pairs, byte-pair encoding, shared vocabulary of about 37,000 tokens | §5.1 |
| English to French data | 36 million sentences, 32,000 word pieces | §5.1 |
| Batch | About 25,000 source and 25,000 target tokens, grouped by length | §5.1 |
| Hardware | One machine, 8 NVIDIA P100 GPUs | §5.2 |
| Base model | 0.4 s a step, 100,000 steps, 12 hours | §5.2 |
| Big model | 1.0 s a step, 300,000 steps, 3.5 days | §5.2 |
| Optimizer | Adam, β1 = 0.9, β2 = 0.98, ε = 10⁻⁹ | §5.3 |
| Regularisation | Dropout 0.1 (base), label smoothing 0.1 | §5.4 |
Warm up, then slow down (equation 3, §5.3)
Numbers
The numbers that matter
Shape of the base model
6 encoder and 6 decoder layers, d_model 512, 8 heads of 64, feed-forward 2048. About 65 million parameters (§3, Table 3).
Big model
d_model 1024, 16 heads, feed-forward 4096, dropout 0.3, about 213 million parameters (Table 3, last row).
English to German
28.4 BLEU for the big model, more than 2 BLEU above the best earlier results, ensembles included (Table 2, §6.1). The base model reached 27.3.
English to French
41.8 BLEU in the abstract and Table 2, a new single-model best. The text of §6.1 says 41.0; quote 41.8 with "Table 2" if asked.
Training time
Base: 12 hours on 8 P100 GPUs. Big: 3.5 days (§5.2). The point is parallel training, not size.
Cost per layer
Self-attention O(n² · d), recurrent O(n · d²). Sequential steps O(1) against O(n) (Table 1).
Quality and training cost, a few rows of Table 2
| Model | BLEU En-De | BLEU En-Fr | Training FLOPs En-De |
|---|---|---|---|
| GNMT + RL | 24.6 | 39.92 | 2.3 · 10¹⁹ |
| ConvS2S | 25.16 | 40.46 | 9.6 · 10¹⁸ |
| ConvS2S ensemble | 26.36 | 41.29 | 7.7 · 10¹⁹ |
| Transformer (base) | 27.3 | 38.1 | 3.3 · 10¹⁸ |
| Transformer (big) | 28.4 | 41.8 | 2.3 · 10¹⁹ |
Check their FLOPs yourself
Where 65 million parameters come from (our count)
§4
Why self-attention: the interview table
Table 1 of the paper
| Layer | Cost per layer | Sequential steps | Longest path |
|---|---|---|---|
| Self-attention | O(n² · d) | O(1) | O(1) |
| Recurrent | O(n · d²) | O(n) | O(n) |
| Convolutional | O(k · n · d²) | O(1) | O(log_k n) |
| Self-attention, restricted to r neighbours | O(r · n · d) | O(1) | O(n / r) |
When is attention cheaper?
Since 2017
What changed, and what did not
| In the paper | What most models do now | Read next |
|---|---|---|
| Encoder plus decoder for translation | Decoder-only for generation (GPT line); encoder-only for embeddings (BERT line) | BERT, GPT-3 |
| Sine and cosine positions, added once | Rotary position embedding (RoPE) applied inside attention | Su and others, 2021, arXiv 2104.09864 |
| Post-norm: LayerNorm(x + Sublayer(x)) | Pre-norm, which Xiong and others found trains without the warm-up stage | arXiv 2002.04745 |
| ReLU feed-forward | Gated variants such as GLU forms | Shazeer, 2020, arXiv 2002.05202 |
| 8 heads, each with its own K and V | Shared K and V across heads: multi-query, then grouped-query | Multi-query attention, GQA arXiv 2305.13245 |
| Plain attention, full n × n matrix | Exact attention computed in tiles, never storing the matrix | FlashAttention |
| Short sentences, n smaller than d | Contexts far longer than d, where n² dominates | Context windows |
Still exactly right
- Scaled dot-product attention, equation 1
- Multi-head projections
- Residual connections around every sub-layer
- The causal mask for generation
- Parallel training as the reason to choose it
Did not age well
- "n is usually smaller than d": true for sentences, false for long documents and chats
- Post-norm with a long warm-up
- Separate K and V per head: too much memory to read during decoding
- Encoder-decoder as the default shape
The family tree
Serving
From the paper to the KV cache
A chat model writes one token at a time, like the paper's decoder. At step t it needs the keys and values of all earlier tokens in every layer. They never change, so a server stores them: that store is the KV cache. Reading the prompt is called prefill: all prompt tokens go through at once, in parallel, like training. Writing is called decode: one token per step, and each step reads the whole cache. The full story is in KV cache and prefix caching.
Our example: where the cache lives on a serving machine
Prefill, then decode
How big is the cache?
Why FlashAttention never stores the matrix
A 128k-token feature is too slow. Where do you look first?
BreaksBuy more GPUs and hope
- How
- Add servers without measuring which phase is slow.
- Limit
- Decode is often memory-bound per request; more machines do not make one long answer faster.
- Choose when
- Never as a first step.
WorksShorten the context
- How
- Trim history or retrieve fewer chunks.
- Limit
- Helps every phase but may drop facts the answer needs.
- Choose when
- When much of the context is not used.
StrongSplit prefill from decode and fix each
- How
- Measure time to first token (prefill, n²) and time per token (decode, cache reads). Use FlashAttention kernels for prefill, GQA models and cache quantisation for decode, and prefix caching for repeated system prompts.
- Limit
- More moving parts, and some fixes depend on the model's design.
- Choose when
- Any long-context product.
Connections
Where this paper sits
| Easy to confuse | This paper | The other one |
|---|---|---|
| Bahdanau attention (2014) | Self-attention replaces the recurrent network entirely | A recurrent decoder attends to recurrent encoder states; scores from a small network |
| FlashAttention | Defines the maths of attention | Same maths, different order of memory reads and writes |
| PagedAttention | Implies the KV cache | Manages KV cache memory in blocks; the maths is unchanged |
| BERT and GPT | Encoder and decoder together | BERT keeps the encoder; GPT keeps the decoder |
Related topics: model architectures for what came after, efficient attention for beating n², context windows for what long inputs cost, tokens and embeddings for step 1, and the prediction engine for how one next token is chosen.
Recall
The 60-second recap, and explain it back
Read this out loud in one minute
- 1
The problem
Recurrent translators worked one word at a time, so training was hard to parallelise and distant words were far apart.
- 2
The idea
Drop recurrence. Each token makes a query, a key and a value.
- 3
The equation
softmax(QKᵀ/√d_k) gives weights; each output is a weighted mix of values.
- 4
The parts
Eight heads find different relations, sine patterns add position, and the decoder masks the future.
- 5
The win
Everything runs in parallel in training. 28.4 BLEU on English to German, 3.5 days on 8 GPUs.
- 6
The price
n² scores per layer and a KV cache that grows per token, which is what inference engineering now works around.
The original
Read the paper in three passes
| Pass | Read | Skip | You can now |
|---|---|---|---|
| 1, about 10 minutes | Abstract, §1, Figure 1, the headings of §3, Table 1, §7 | Everything else | Say what it is: a new architecture, tested on translation and parsing, built only from attention |
| 2, about 45 minutes | §3.1 to §3.5 with the Visualize tab open, Figure 2, Table 1, Table 3 | §6.3 parsing; skim §5 | Explain every block of Figure 1 and quote its numbers |
| 3, optional | Write attention and a causal mask in about 15 lines, then check them on our 5-word example | Label smoothing and checkpoint averaging details | Rebuild the model from memory and name its assumptions: short inputs, a fixed vocabulary, translation pairs |
Summary
The whole topic in one minute.
Before 2017, translators read one word at a time, so training could not use many GPUs well inside a sentence, and far-apart words were many steps apart. The Transformer replaced recurrence with attention: every token makes a query, a key and a value; softmax(QKᵀ/√d_k) gives each token weights over all tokens; its output is the weighted sum of values. All positions are computed at once.
Eight heads look for different relations, sine and cosine patterns add word order, a mask stops the decoder from seeing the future, and residual connections with layer normalization keep a stack of 6 layers trainable. The big model reached 28.4 BLEU on English to German after 3.5 days on 8 P100 GPUs.
The cost is n² scores per head per layer, and a KV cache that grows with every generated token. Since then, decoder-only models, RoPE, pre-norm, GQA, FlashAttention and PagedAttention changed the details. The core equation did not change.
- Vaswani and seven co-authors, NIPS 2017, arXiv 1706.03762: the Transformer.
- Attention(Q, K, V) = softmax(QKᵀ/√d_k)V. Queries ask, keys answer, values come back.
- Divide by √d_k because q·k has variance d_k (footnote 4); otherwise softmax saturates.
- Multi-head: 8 heads of 64 instead of one of 512, about the same cost, different relations.
- Position is added with sines and cosines; learned positions worked as well (Table 3, row E).
- The decoder masks later positions with minus infinity; the encoder sees everything.
- Base: 6 + 6 layers, d_model 512, d_ff 2048, 65M parameters, 12 hours on 8 P100 GPUs.
- Table 1: self-attention O(n²·d), O(1) sequential steps, O(1) path. Recurrent O(n·d²), O(n), O(n).
- Serving: prefill is n² at once, decode reads a KV cache of 2 × layers × kv heads × head dim × bytes per token.
Sources
- Vaswani et al., Attention Is All You Need, arXiv 1706.03762
- Attention Is All You Need, NeurIPS 2017 proceedings
- tensor2tensor, the code released with the paper
- Bahdanau, Cho, Bengio: Neural Machine Translation by Jointly Learning to Align and Translate (2014)
- Devlin et al.: BERT (2018)
- Brown et al.: Language Models are Few-Shot Learners (2020)
- Shazeer: Fast Transformer Decoding: One Write-Head is All You Need (2019)
- Ainslie et al.: GQA (2023)
- Su et al.: RoFormer, rotary position embedding (2021)
- Xiong et al.: On Layer Normalization in the Transformer Architecture (2020)
- Shazeer: GLU Variants Improve Transformer (2020)
- Dao et al.: FlashAttention (2022)
- Kwon et al.: PagedAttention and vLLM (2023)
- Gu and Dao: Mamba (2023)
- Dosovitskiy et al.: An Image is Worth 16x16 Words (2020)