π Attention Is All You Need
Attention Is All You Need (Vaswani et al., 2017)
Before 2017, the best translation systems read a sentence one word at a time, with recurrent networks. This paper removed the recurrence entirely and built the model from attention alone. The result trained faster, translated better, and became the base of nearly every large model since.
This page follows the paper's own argument rather than repeating the full forward pass. That pass, with every matrix printed, is in Autoregressive Transformer: Encoder + Decoder.
- The problem: recurrence is sequential, and long paths forget
- Scaled dot-product attention, by hand
- Why divide by $\sqrt{d_k}$, measured
- Multi-head attention, and what it costs
- Masking: training a decoder on every position at once
- The paper's numbers: complexity, model size, learning rate, results
helpers ready
1. The problem with recurrence
A recurrent network computes $h_t = f(h_{t-1}, x_t)$. Two things follow from that one line:
- Nothing runs in parallel along the sequence. Step $t$ needs step $t-1$, so a 50-word sentence takes 50 dependent steps, however many GPU cores you have.
- Distant words are far apart. Information from word 1 reaches word 50 only by passing through 49 intermediate states, and each one can overwrite it.
Self-attention connects every position to every other in one step. The paper's Table 1 states this as maximum path length: $O(n)$ for recurrence, $O(1)$ for self-attention.
2. Scaled dot-product attention, by hand
The paper's central formula:
$$\text{Attention}(Q, K, V) = \text{softmax}\!\left(\frac{QK^\top}{\sqrt{d_k}}\right)V$$
Read it as a soft dictionary lookup. Each query is compared with every key by a dot product. The softmax turns those scores into weights that sum to 1. The output is the weighted average of the values. A hard dictionary would return exactly one value; attention returns a blend, which is what makes it differentiable.
Below: four tokens, $d_k = 4$, and the output for token 0 written out in full.
==============================================================================
ONE QUERY, FOUR KEYS
==============================================================================
Scores: q0 . k_j, then divide by sqrt(d_k) = 2
------------------------------------------------------------------------------
q0.k0 = (+1.79)(-0.55) + (+0.44)(-1.55) + (+0.10)(+0.98) + (-1.86)(-1.10) = +0.4775 -> /2 = +0.2388
q0.k1 = (+1.79)(-1.19) + (+0.44)(-0.21) + (+0.10)(+1.49) + (-1.86)(+0.24) = -2.5199 -> /2 = -1.2600
q0.k2 = (+1.79)(-1.02) + (+0.44)(-0.71) + (+0.10)(+0.63) + (-1.86)(-0.16) = -1.7776 -> /2 = -0.8888
q0.k3 = (+1.79)(-0.77) + (+0.44)(-0.23) + (+0.10)(+0.75) + (-1.86)(+1.98) = -5.0873 -> /2 = -2.5437
Softmax
------------------------------------------------------------------------------
w0 = exp(+0.2388 - max) / sum = 1.0000 / 1.6091 = 0.6215
w1 = exp(-1.2600 - max) / sum = 0.2234 / 1.6091 = 0.1388
w2 = exp(-0.8888 - max) / sum = 0.3238 / 1.6091 = 0.2012
w3 = exp(-2.5437 - max) / sum = 0.0619 / 1.6091 = 0.0385
weights sum to 1.000000
Output: weighted average of the value rows
------------------------------------------------------------------------------
out0 = 0.621*v0 + 0.139*v1 + 0.201*v2 + 0.038*v3
= [-1.2474 -0.425 -0.4476 -1.871 ]
[MATCH] by-hand output for token 0 == row 0 of softmax(QK^T/sqrt(d_k)) V
The same lookup in motion: scores are computed, the softmax squashes them into weights, and the value rows are blended in proportion to those weights.
3. Why divide by $\sqrt{d_k}$
The paper's reason, in one sentence: if the components of $q$ and $k$ are independent with mean 0 and variance 1, then $q \cdot k$ has variance $d_k$. With $d_k = 64$ the scores have a standard deviation of 8, the softmax pushes almost all its weight onto one key, and its gradient becomes tiny. Dividing by $\sqrt{d_k}$ brings the variance back to 1.
Both halves of that claim can be measured.
============================================================================== VARIANCE OF q.k GROWS WITH d_k ============================================================================== Empirical variance of q.k over 200,000 random pairs ------------------------------------------------------------------------------ d_k = 4: var(q.k) = 4.00 (theory 4) var(q.k / sqrt(d_k)) = 0.999 d_k = 16: var(q.k) = 15.90 (theory 16) var(q.k / sqrt(d_k)) = 0.994 d_k = 64: var(q.k) = 63.95 (theory 64) var(q.k / sqrt(d_k)) = 0.999 d_k = 256: var(q.k) = 255.30 (theory 256) var(q.k / sqrt(d_k)) = 0.997 d_k = 512: var(q.k) = 511.69 (theory 512) var(q.k / sqrt(d_k)) = 0.999 What the softmax does with 10 keys, d_k = 64 (averaged over 2,000 queries) ------------------------------------------------------------------------------ unscaled mean largest weight = 0.865 mean |d softmax / d scores| = 0.1608 scaled by 1/sqrt(d_k) mean largest weight = 0.320 mean |d softmax / d scores| = 0.3467 Scaling makes the softmax gradient 2.2x larger on average.
4. Multi-head attention
One attention function averages. If a word needs to look at its subject and at the previous word, one set of weights has to compromise. The paper runs $h = 8$ attention functions in parallel, each in its own $d_k = d_{model}/h = 64$ dimensional subspace, and concatenates the results:
$$\text{MultiHead}(Q,K,V) = \text{Concat}(\text{head}_1, \dots, \text{head}_h)\,W^O, \qquad \text{head}_i = \text{Attention}(QW_i^Q, KW_i^K, VW_i^V)$$
Because each head is $h$ times narrower, eight heads cost the same as one head of full width. The next cell checks that and counts the parameters.
============================================================================== MULTI-HEAD = SAME COST AS ONE WIDE HEAD ============================================================================== d_model = 512, h = 8, d_k = d_v = 512/8 = 64 projection weights, one 512-wide head: 3*512*512 + 512*512 = 1,048,576 projection weights, 8 heads of 64: 8*(3*512*64) + 512*512 = 1,048,576 [MATCH] same number of parameters And the same output, computed head by head vs with one reshaped matmul ------------------------------------------------------------------------------ [MATCH] 8 separate heads == one batched reshape
5. Masking: train on every position at once
The decoder generates left to right, so position $i$ must not see positions after it. The paper enforces this inside the softmax by setting those scores to $-\infty$. Their weight becomes exactly zero.
This is what makes training fast. One forward pass over a 50-token target gives 50 next-token predictions at once, each seeing only its own past. A recurrent decoder has to produce them one after another.
============================================================================== CAUSAL MASK ============================================================================== attention weights (row = query position, column = key position): [[1. 0. 0. 0. 0. ] [0.2201 0.7799 0. 0. 0. ] [0.0784 0.6775 0.2441 0. 0. ] [0.4004 0.4761 0.0768 0.0467 0. ] [0.2683 0.2794 0.2248 0.1382 0.0892]] [MATCH] every row sums to 1 [MATCH] every weight above the diagonal is exactly 0 Changing a FUTURE token does not change an earlier output ------------------------------------------------------------------------------ [MATCH] outputs 0..3 unchanged after editing token 4 output 4 changed by 27.511, as it should
6. The paper's numbers
Cost per layer (the paper's Table 1, with $n$ the sequence length and $d$ the width):
| Layer | Work per layer | Sequential steps | Longest path |
|---|---|---|---|
| Self-attention | $O(n^2 d)$ | $O(1)$ | $O(1)$ |
| Recurrent | $O(n d^2)$ | $O(n)$ | $O(n)$ |
| Convolution (kernel $k$) | $O(k n d^2)$ | $O(1)$ | $O(\log_k n)$ |
Self-attention is cheaper than recurrence whenever $n < d$. That held for sentence-level translation, with $n$ in the tens and $d = 512$. The quadratic term is also why long-context models later needed so much engineering.
============================================================================== WHEN IS SELF-ATTENTION CHEAPER? (d = 512) ============================================================================== n = 25: n^2 d = 320,000 n d^2 = 6,553,600 attention cheaper n = 50: n^2 d = 1,280,000 n d^2 = 13,107,200 attention cheaper n = 100: n^2 d = 5,120,000 n d^2 = 26,214,400 attention cheaper n = 512: n^2 d = 134,217,728 n d^2 = 134,217,728 equal n = 2048: n^2 d = 2,147,483,648 n d^2 = 536,870,912 recurrence cheaper n = 32768: n^2 d = 549,755,813,888 n d^2 = 8,589,934,592 recurrence cheaper
Model size. The base model has $N = 6$ encoder and 6 decoder layers, $d_{model} = 512$, $d_{ff} = 2048$ and $h = 8$. The big model uses 1024, 4096 and 16. The paper reports 65M and 213M parameters. Counting layer by layer, with a shared ~37,000-token BPE vocabulary, gets close to both.
============================================================================== COUNTING THE PARAMETERS ============================================================================== base encoder 18.9M + decoder 25.2M + embeddings 18.9M = 63.1M (paper: 65M, off by -3.0%) big encoder 75.6M + decoder 100.8M + embeddings 37.9M = 214.2M (paper: 213M, off by +0.6%) The gap is the vocabulary size, which the paper gives only as about 37,000.
Learning rate. The paper increases the learning rate linearly for 4,000 warm-up steps, then decays it with the inverse square root of the step number:
$$lr = d_{model}^{-0.5}\cdot\min\left(step^{-0.5},\ step\cdot warmup^{-1.5}\right)$$
Warm-up has since become standard for transformers, because large updates in the first steps, made while the Adam statistics are still noisy, can destabilise training.
============================================================================== THE WARM-UP SCHEDULE ============================================================================== peak at step 4,000: lr = 0.000699 check: 512^-0.5 * 4000^-0.5 = 0.000699 at step 100,000 (end of base training): lr = 0.000140
Results. On WMT 2014 English to German, the big model reached 28.4 BLEU, more than 2 BLEU above the best earlier results, ensembles included. On English to French it reached 41.8 BLEU. The base model trained for 100,000 steps, about 12 hours on 8 P100 GPUs. The big model trained for 300,000 steps, about 3.5 days. That was a fraction of the training cost of the systems it beat.
Summary
- Recurrence forces sequential computation and long paths between distant words. Self-attention has neither.
- Attention is a soft dictionary lookup: dot-product scores, a softmax, and a weighted average of values.
- The $\sqrt{d_k}$ scaling keeps score variance at 1. Without it the softmax saturates and its gradient shrinks; measured here, about 2Γ smaller at $d_k = 64$.
- Multi-head attention costs the same as one wide head and lets different heads attend to different things.
- Masking lets a decoder train on every position in parallel.
- What came next: GPT kept only the decoder, BERT kept only the encoder, and ViT applied the encoder to image patches. Each has its own page in this section.