AlgoViz

Attention Is All You Need

medium 40 min

The 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

  1. 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).

  2. 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).

  3. 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).

  4. 2018

    On 11 October, BERT (1810.04805) is posted: a stack of Transformer encoders pretrained on unlabelled text, then fine-tuned.

  5. 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.

  6. 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).

  7. 2022

    On 27 May, FlashAttention (2205.14135) is posted: exact attention computed in tiles to cut reads and writes to GPU memory.

  8. 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.

Step 1 of 4

Tokens plus position. Embeddings plus a sine and cosine pattern

Understand it

Start here

The paper at a glance

CitationVaswani, Shazeer, Parmar, Uszkoreit, Jones, Gomez, Kaiser, Polosukhin. Attention Is All You Need
Venue and yearNIPS 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
LevelMust-know: its ideas come up in almost every AI engineering interview
TimeAbout 40 minutes here, then 10 minutes for pass 1 of the paper itself
Before thisTokens and embeddings and the prediction engine
Last checked27 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.

From a whisper line to a ring of badges
parcelfitslotitbigA whisper line

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

Attention already existed. What the Transformer removed was the recurrence on both sides.

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)

Attention(Q,K,V)=softmax ⁣(QK⊤dk)V\text{Attention}(Q, K, V) = \text{softmax}\!\left(\frac{QK^{\top}}{\sqrt{d_k}}\right) V
QKᵀ holds one score for every pair of tokens. Dividing by √d_k keeps the scores in a range where softmax still learns. Each row of weights then mixes the rows of V.

The row for "it", with our numbers

Key ofq · k÷ √2Weight after softmax
parcel42.830.62
fit000.04
slot000.04
it21.410.15
big21.410.15
Our made-up vectors with d_k = 2: the query of "it" is [2, 0]; the keys are [2, 0], [0, 1], [0, 2], [1, 1] and [1, 0]. The weights add up to 1. The code below prints the same numbers.

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

    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

    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

    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

    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

    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

    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

    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

    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)

PE(pos, 2i)=sin⁡ ⁣(pos100002i/dmodel)PE(pos, 2i+1)=cos⁡ ⁣(pos100002i/dmodel)PE_{(pos,\,2i)} = \sin\!\left(\frac{pos}{10000^{2i/d_{model}}}\right) \qquad PE_{(pos,\,2i+1)} = \cos\!\left(\frac{pos}{10000^{2i/d_{model}}}\right)
Each pair of dimensions is a wave. The wavelengths grow from 2π to 10000 · 2π, so early dimensions change fast and later ones slowly, like the hands of a clock.

The pattern for d_model = 4, our small example

Positionsin, fastcos, fastsin, slowcos, slow
00.001.000.001.00
10.840.540.011.00
20.91-0.420.021.00
30.14-0.990.031.00
Printed by the code below. With d_model = 512 the slowest waves take tens of thousands of positions to repeat.
  • 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)

q⋅k=∑i=1dkqiki,Var⁡(q⋅k)=dk⇒Var⁡ ⁣(q⋅kdk)=1q \cdot k = \sum_{i=1}^{d_k} q_i k_i, \qquad \operatorname{Var}(q \cdot k) = d_k \quad\Rightarrow\quad \operatorname{Var}\!\left(\frac{q \cdot k}{\sqrt{d_k}}\right) = 1
If every part of q and k is random with mean 0 and variance 1, the dot product has variance d_k. With d_k = 64, scores spread about 8 times wider, softmax puts nearly all weight on one key, and the gradient almost vanishes.
Python
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])])
Ten lines. The second print shows why scaling matters: the same scores 8 times larger give a near one-hot softmax.
Edit and run it in your browser

Two ways to score, from §3.2.1

Additive attention (Bahdanau)Dot-product attention (this paper, scaled)
ScoreA small feed-forward network on q and kq · k / √d_k
Theory costSimilarSimilar
In practiceSlowerMuch faster and smaller in memory: it is one matrix product
Large d_k without scalingBetter than unscaled dot productNeeds 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 endsWeight on parcelWeight on slot"it" means
"because it was too big"0.620.04the parcel
"because it was too narrow"0.030.56the slot
Our made-up vectors, printed by the Code tab. In a trained model the weights come from learned matrices, not from us.

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)

MultiHead(Q,K,V)=Concat(head1,…,headh) WO,headi=Attention(QWiQ,KWiK,VWiV)\text{MultiHead}(Q,K,V) = \text{Concat}(\text{head}_1, \dots, \text{head}_h)\,W^{O}, \quad \text{head}_i = \text{Attention}(QW_i^{Q}, KW_i^{K}, VW_i^{V})
Base model: h = 8 and d_k = d_v = 512 / 8 = 64. Each head is 8 times smaller, so the total cost is close to one head of full width.

How many heads? Table 3, rows A (same computation each time)

Heads hd_k = d_vBLEU (dev)Perplexity (dev)
151224.95.29
412825.55.00
8 (base)6425.84.92
163225.84.91
321625.45.01
On the English to German development set, newstest2013. One head is 0.9 BLEU worse than the best; too many heads also hurt (§6.2). Rows B show that making d_k smaller alone hurts too.

Inside one multi-head layer

The heads never talk to each other until the concatenation. That is why they can run in parallel.

Where attention is used

Three kinds of attention in one model

Kind (§3.2.3)Queries fromKeys and values fromMask
Encoder self-attentionThe previous encoder layerThe previous encoder layerNone: every word sees every word
Decoder self-attentionThe previous decoder layerThe previous decoder layerLater positions set to minus infinity
Encoder-decoder attentionThe previous decoder layerThe output of the encoderNone: every output word sees every input word
The third kind is the old Bahdanau idea kept inside the new model. It is also called cross-attention.

Translating one sentence

The encoder runs once. The decoder runs once per output word at inference, but all positions at once in training thanks to the mask.

Steps 6 and 7

The layer, the mask and the stack

One encoder layer, as §3.1 describes it

LayerNorm(x + Sublayer(x)) around both parts. This order, normalising after the addition, is called post-norm. A decoder layer adds a third part: cross-attention over the encoder output.

The feed-forward part (equation 2, §3.3)

FFN(x)=max⁡(0,  xW1+b1) W2+b2,512→2048→512\text{FFN}(x) = \max(0,\; xW_1 + b_1)\,W_2 + b_2, \qquad 512 \to 2048 \to 512
The same two matrices for every position in a layer, different ones in each layer. Attention moves information between tokens; this part works on each token alone.

Generating with the mask

At inference the paper used beam search with 4 beams and stopped at input length + 50 words, or earlier (§6.1). In training the same mask lets all positions learn at once.

Training

How they trained it

The training run of the base model, from §5 and §6.1

Sentence pairs from WMT 2014 English to German go through a byte-pair tokenizer with a shared vocabulary of about 37,000 tokens. A batcher groups pairs of similar length into batches of about 25,000 source and 25,000 target tokens. Inside one machine with 8 P100 GPUs the batches train the encoder and decoder. Checkpoints are written every 10 minutes to storage, and the last 5 are averaged into the final base model.
Everything in this picture is from the paper. The paper does not say how the work was split across the 8 GPUs, so the picture does not either.

The recipe

ItemValueSection
English to German dataAbout 4.5 million sentence pairs, byte-pair encoding, shared vocabulary of about 37,000 tokens§5.1
English to French data36 million sentences, 32,000 word pieces§5.1
BatchAbout 25,000 source and 25,000 target tokens, grouped by length§5.1
HardwareOne machine, 8 NVIDIA P100 GPUs§5.2
Base model0.4 s a step, 100,000 steps, 12 hours§5.2
Big model1.0 s a step, 300,000 steps, 3.5 days§5.2
OptimizerAdam, β1 = 0.9, β2 = 0.98, ε = 10⁻⁹§5.3
RegularisationDropout 0.1 (base), label smoothing 0.1§5.4

Warm up, then slow down (equation 3, §5.3)

lrate=dmodel−0.5⋅min⁡ ⁣(step−0.5,  step⋅warmup−1.5),warmup=4000lrate = d_{model}^{-0.5} \cdot \min\!\left(step^{-0.5},\; step \cdot warmup^{-1.5}\right), \quad warmup = 4000
The rate rises in a straight line for 4,000 steps, then falls with one over the square root of the step. At step 4,000 it peaks at 512^(-0.5) × 4000^(-0.5) ≈ 0.0007, by our arithmetic.

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

ModelBLEU En-DeBLEU En-FrTraining FLOPs En-De
GNMT + RL24.639.922.3 · 10¹⁹
ConvS2S25.1640.469.6 · 10¹⁸
ConvS2S ensemble26.3641.297.7 · 10¹⁹
Transformer (base)27.338.13.3 · 10¹⁸
Transformer (big)28.441.82.3 · 10¹⁹
newstest2014. The base model beat every earlier model and ensemble on English to German at a fraction of the compute.

Check their FLOPs yourself

12 h×3600×8 GPUs×9.5×1012 FLOPs≈3.3×10183.5 days→2.3×101912\ \text{h} \times 3600 \times 8\ \text{GPUs} \times 9.5 \times 10^{12}\ \tfrac{\text{FLOP}}{\text{s}} \approx 3.3 \times 10^{18} \qquad 3.5\ \text{days} \to 2.3 \times 10^{19}
§6.1 says they multiplied training time, GPU count and an estimate of sustained single-precision speed, 9.5 TFLOPS for a P100 (footnote 5). Both rows of Table 2 come out right.

Where 65 million parameters come from (our count)

6×3.15M⏟encoder+6×4.20M⏟decoder+37,000×512⏟shared embedding≈18.9+25.2+18.9=63M\underbrace{6 \times 3.15\text{M}}_{\text{encoder}} + \underbrace{6 \times 4.20\text{M}}_{\text{decoder}} + \underbrace{37{,}000 \times 512}_{\text{shared embedding}} \approx 18.9 + 25.2 + 18.9 = 63\text{M}
Attention has four 512 × 512 matrices (1.05M), the feed-forward part two 512 × 2048 matrices (2.1M); the decoder has two attention parts. Our 63M is close to the paper's 65M; the vocabulary size is approximate and we left out small pieces.

§4

Why self-attention: the interview table

Table 1 of the paper

LayerCost per layerSequential stepsLongest path
Self-attentionO(n² · d)O(1)O(1)
RecurrentO(n · d²)O(n)O(n)
ConvolutionalO(k · n · d²)O(1)O(log_k n)
Self-attention, restricted to r neighboursO(r · n · d)O(1)O(n / r)
n is the sequence length, d the vector size, k the kernel width, r the neighbourhood. Know the first two rows cold.

When is attention cheaper?

n2d<nd2  ⟺  n<dn=50, d=512:  1.28M<13.1Mn=8,192:  34.4B>2.1Bn^2 d < n d^2 \iff n < d \qquad n = 50,\ d = 512:\ \ 1.28\text{M} < 13.1\text{M} \qquad n = 8{,}192:\ \ 34.4\text{B} > 2.1\text{B}
§4 notes that sentences in translation are usually shorter than d, so attention was cheaper there. The 50 and 8,192 are our examples. At long contexts the comparison flips, which is the story of everything since.

Since 2017

What changed, and what did not

In the paperWhat most models do nowRead next
Encoder plus decoder for translationDecoder-only for generation (GPT line); encoder-only for embeddings (BERT line)BERT, GPT-3
Sine and cosine positions, added onceRotary position embedding (RoPE) applied inside attentionSu and others, 2021, arXiv 2104.09864
Post-norm: LayerNorm(x + Sublayer(x))Pre-norm, which Xiong and others found trains without the warm-up stagearXiv 2002.04745
ReLU feed-forwardGated variants such as GLU formsShazeer, 2020, arXiv 2002.05202
8 heads, each with its own K and VShared K and V across heads: multi-query, then grouped-queryMulti-query attention, GQA arXiv 2305.13245
Plain attention, full n × n matrixExact attention computed in tiles, never storing the matrixFlashAttention
Short sentences, n smaller than dContexts far longer than d, where n² dominatesContext windows
The core equation, softmax(QKᵀ/√d_k)V, is still at the centre of these models.

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

Dates are the arXiv posting years. Each later paper has its own page in Papers.

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

Users send prompts to an API gateway, which forwards them to one GPU server. Inside the server's GPU memory sit the model weights and the KV cache. Prefill runs the whole prompt at once and writes its keys and values into the cache. Decode then makes one token at a time: it reads the weights and the whole cache, appends one new key and value, and streams the token back to the user.
Our own picture, not from the paper. Prefill fills the cache in one pass; every decode step reads all of it and adds one row.

Prefill, then decode

Prefill is limited by arithmetic: n² scores at once. Decode is often limited by memory reads: the whole cache and the weights for each token.

How big is the cache?

KV bytes=2×layers×kv heads×head dim×bytes×tokens2⋅32⋅8⋅128⋅2⋅8,192≈1.07 GB\text{KV bytes} = 2 \times \text{layers} \times \text{kv heads} \times \text{head dim} \times \text{bytes} \times \text{tokens} \qquad 2 \cdot 32 \cdot 8 \cdot 128 \cdot 2 \cdot 8{,}192 \approx 1.07\ \text{GB}
The 2 is one key plus one value. Our example model: 32 layers, 8 key-value heads of 128, 16-bit numbers, 8,192 tokens, one request. The paper's own base decoder would need 2 × 6 × 512 × 2 = 12,288 bytes per token at 16 bits.

Why FlashAttention never stores the matrix

131,0722×2 bytes≈34.4 GB per head, per layer131{,}072^2 \times 2\ \text{bytes} \approx 34.4\ \text{GB per head, per layer}
Our arithmetic for one full score matrix at 128k tokens in 16 bits. Computing it in tiles that fit in fast on-chip memory gives the same exact answer without ever holding all of it.

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 confuseThis paperThe other one
Bahdanau attention (2014)Self-attention replaces the recurrent network entirelyA recurrent decoder attends to recurrent encoder states; scores from a small network
FlashAttentionDefines the maths of attentionSame maths, different order of memory reads and writes
PagedAttentionImplies the KV cacheManages KV cache memory in blocks; the maths is unchanged
BERT and GPTEncoder and decoder togetherBERT 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. 1

    The problem

    Recurrent translators worked one word at a time, so training was hard to parallelise and distant words were far apart.

  2. 2

    The idea

    Drop recurrence. Each token makes a query, a key and a value.

  3. 3

    The equation

    softmax(QKᵀ/√d_k) gives weights; each output is a weighted mix of values.

  4. 4

    The parts

    Eight heads find different relations, sine patterns add position, and the decoder masks the future.

  5. 5

    The win

    Everything runs in parallel in training. 28.4 BLEU on English to German, 3.5 days on 8 GPUs.

  6. 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

PassReadSkipYou can now
1, about 10 minutesAbstract, §1, Figure 1, the headings of §3, Table 1, §7Everything elseSay 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 §5Explain every block of Figure 1 and quote its numbers
3, optionalWrite attention and a causal mask in about 15 lines, then check them on our 5-word exampleLabel smoothing and checkpoint averaging detailsRebuild the model from memory and name its assumptions: short inputs, a fixed vocabulary, translation pairs
Pass 1 answers five questions: what kind of paper (a new model with results), what context (recurrent seq2seq with attention, ConvS2S, ByteNet), is it convincing (two translation tasks and parsing), what is new (attention only, multi-head, sine positions, parallel training), and is it clear (dense but short).

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