Skip to content
King Jin

20 July 2026

Attention Is All You Need

In July I read Attention Is All You Need, the 2017 paper that introduced the Transformer. It was built for machine translation, and now almost every large model is based on it. The core idea fits in one sentence: replace the step-by-step computation of an RNN with self-attention, so every position can see every other position within one layer and training runs fully in parallel. The cost is that compute grows with the square of the sentence length, and the model has no built-in sense of word order, so position has to be added separately.

The images in this post are the notes I wrote on the PDF while reading it. The pages are from Vaswani et al. (2017).

Page 1 of the paper: title and authors, with handwritten notes in Chinese at the top and on the right.

The core idea

An RNN has to finish ht−1h_{t-1} before it can compute hth_t, so a sentence is processed one word at a time. That cannot be parallelised, it gets slower as sentences get longer, and a signal between two distant words has to pass through many steps.

Convolutional models (ConvS2S, ByteNet) can run in parallel, but a convolution only looks at a small window, so connecting two distant positions takes many stacked layers. The Transformer uses only attention: every word scores its relevance to every other word directly, so any two positions are one step apart. The catch is that attention is a weighted average, which can blur details. The paper uses multi-head attention to make up for that.

The architecture

It is still an encoder-decoder. The encoder turns the input sentence into a sequence of vectors. The decoder uses those vectors to generate the output one word at a time, feeding each generated word back in as input for the next step. This makes the decoder auto-regressive.

  1. Tokens become 512-dimensional embeddings, plus a positional encoding.
  2. Encoder: 6 layers, each with multi-head self-attention and a position-wise feed-forward network.
  3. Decoder: 6 layers, with masked self-attention and an extra attention block over the encoder output.
  4. A linear layer and softmax give the probability of the next word.

Figure 1 of the paper: the Transformer architecture, with the encoder on the left and the decoder on the right, each labelled by hand.

Every sub-layer is wrapped in a residual connection followed by LayerNorm:

LayerNorm⁡(x+Sublayer⁡(x))\operatorname{LayerNorm}(x+\operatorname{Sublayer}(x))

Every sub-layer outputs dmodel=512d_{model}=512 dimensions, so the residuals can be added directly. Unlike BatchNorm, LayerNorm computes the mean and variance over each token's own 512 numbers and ignores the other samples in the batch.

Page 3 of the paper, section 3.1: the description of the encoder and decoder stacks, with yellow and blue highlights and handwritten notes in Chinese in both margins.

Scaled dot-product attention

The output is a weighted sum of the values, where each weight depends on how well the query matches the corresponding key. The paper calls it scaled dot-product attention:

Attention⁡(Q,K,V)=softmax⁡(QK⊤dk)V\operatorname{Attention}(Q,K,V)=\operatorname{softmax}\left(\frac{QK^\top}{\sqrt{d_k}}\right)V

The matrix shapes make it much clearer. dkd_k is the dimension of a key:

Q (n × d_k) · Kᵀ (d_k × m) → n × m     a score for every query and key
(n × m) · V (m × d_v)      → n × d_v   one output per query

Why divide by dk\sqrt{d_k}? If the components of qq and kk are independent with mean 0 and variance 1, then q⋅kq\cdot k has variance dkd_k. With dk=64d_k=64 the standard deviation is 8, so the softmax pushes the largest score close to 1 and the rest close to 0. The gradients become tiny and training gets harder. Dividing by 64=8\sqrt{64}=8 brings the variance back to 1.

Page 4 of the paper, section 3.2.1: a small sketch of the matrix shapes next to the attention formula, blue highlights on the paragraph about dividing by the square root of d_k, and handwritten notes in Chinese in both margins.

The mask in the decoder

When predicting word tt, the decoder must not see the words after it. But during training the whole target sentence (shifted right by one) goes in at once, so a matrix MM is added before the softmax to set every score after position tt to −∞-\infty (in code, usually a very large negative number). Since e−∞=0e^{-\infty}=0, those weights all become 0:

softmax⁡(QK⊤dk+M)V\operatorname{softmax}\left(\frac{QK^\top}{\sqrt{d_k}}+M\right)V M=(0−∞−∞00−∞000)M=\begin{pmatrix}0&-\infty&-\infty\\0&0&-\infty\\0&0&0\end{pmatrix}

With three words, row 1 can only see word 1, and row 3 can see all three.

Multi-head attention

With a single attention, every relationship has to share the same set of weights. Multi-head attention uses hh learned linear layers to project QQ, KK and VV into lower dimensions, runs attention once per head, then concatenates the results and projects them back:

head⁡i=Attention⁡(QWiQ,KWiK,VWiV)\operatorname{head}_i=\operatorname{Attention}(QW_i^Q,KW_i^K,VW_i^V) MultiHead⁡(Q,K,V)=Concat⁡(head⁡1,…,head⁡h)WO\operatorname{MultiHead}(Q,K,V)=\operatorname{Concat}(\operatorname{head}_1,\ldots,\operatorname{head}_h)W^O

Figure 2 of the paper: scaled dot-product attention on the left and multi-head attention on the right, with handwritten notes in Chinese next to the mask, the h stacked attention layers and the three Linear blocks.

It is a lot like the output channels of a convolution: each channel picks up one kind of pattern, and each head gets its own chance to learn a different kind of relationship. The paper uses 8 heads, each with dk=dv=512/8=64d_k=d_v=512/8=64, so the total cost is about the same as one 512-dimensional head.

Attention is used in three ways:

Q fromK and V fromMask
Encoder self-attentionprevious encoder layerprevious encoder layernone
Decoder self-attentionprevious decoder layerprevious decoder layerhides later positions
Encoder-decoder attentionprevious decoder layerencoder outputnone

Feed-forward network

Each position goes through the same two-layer MLP on its own, with the weights shared across positions:

FFN⁡(x)=max⁡(0,xW1+b1)W2+b2\operatorname{FFN}(x)=\max(0,xW_1+b_1)W_2+b_2

The widths are 512 → 2048 → 512. The split of work is clean: attention moves information between positions, and the MLP transforms each position separately.

Page 5 of the paper: the sections on the three uses of attention and the feed-forward network, with blue and yellow highlights, a blue and red sketch of attention and the MLP in the left margin, and handwritten notes in Chinese.

Positional encoding

Attention does not care about order. Shuffle the input words and each word's output just moves with it. So position has to be added in. The paper uses sines and cosines of different frequencies, where pospos is the position and ii is the dimension:

PE(pos,2i)=sin⁡(pos/100002i/dmodel)PE_{(pos,2i)}=\sin\left(pos/10000^{2i/d_{model}}\right) PE(pos,2i+1)=cos⁡(pos/100002i/dmodel)PE_{(pos,2i+1)}=\cos\left(pos/10000^{2i/d_{model}}\right)

Learned position embeddings give almost the same result (25.7 vs 25.8 BLEU on the dev set). The paper gives two reasons for sin/cos. It guessed the model could more easily learn to attend by relative position, since for any fixed offset kk, PEpos+kPE_{pos+k} is a linear function of PEposPE_{pos}. It also hoped the model could handle sentences longer than the ones it was trained on.

I don't love that position is simply added onto the word embedding, though. Position and meaning end up mixed in the same vector, which muddies the input. When I moved JustOneGPT to a LLaMA-style model, I used RoPE instead: it rotates the query and key by position inside attention, so position never gets mixed into the embedding.

Two smaller details. The two embedding layers and the linear layer before the softmax share one weight matrix, which works because the English-German model uses one BPE vocabulary shared by both languages. The embeddings are also multiplied by dmodel\sqrt{d_{model}}. The paper doesn't say why; the usual explanation is that it puts the embeddings on a similar scale to the positional encoding.

Why self-attention

Section 4 of the paper compares layer types in three ways: compute per layer, how many steps must run in sequence, and how far a signal has to travel between two positions. nn is the sequence length, dd the vector dimension and kk the kernel size:

LayerCompute per layerSequential opsMax path length
Self-attentionO(n2⋅d)O(n^2\cdot d)O(1)O(1)O(1)O(1)
RecurrentO(n⋅d2)O(n\cdot d^2)O(n)O(n)O(n)O(n)
ConvolutionalO(k⋅n⋅d2)O(k\cdot n\cdot d^2)O(1)O(1)O(log⁡kn)O(\log_k n)
  • The n2n^2 in self-attention comes from every query scoring every key, and dd is the length of each dot product.
  • An RNN takes nn steps, and each step multiplies the hidden state by a d×dd\times d matrix, so it costs n⋅d2n\cdot d^2. Those nn steps also have to run one after another.

Page 6 of the paper: Table 1 and section 3.5 on positional encoding, with blue highlights on the complexities, arrows and a red star drawn on the table, and handwritten notes in Chinese in the margins.

Sentences are usually shorter than dd. With n=50n=50 and d=512d=512, the attention scores cost about 502×512≈1.3×10650^2\times512\approx1.3\times10^6 and the RNN about 50×5122≈1.3×10750\times512^2\approx1.3\times10^7, roughly 10× more. That only counts the term in the table, though. The Q, K, V and output projections add another 4⋅n⋅d2≈5.2×1074\cdot n\cdot d^2\approx5.2\times10^7, which on its own is bigger than the RNN number above. But a real RNN also has an input projection, and an LSTM with its 4 gates comes to about 8⋅n⋅d28\cdot n\cdot d^2. Per layer the two end up in roughly the same ballpark. The bigger wins are that it runs in parallel and that any two words are one step apart, which makes long-range dependencies easier to learn.

Training

The data was WMT 2014 English-German, about 4.5 million sentence pairs, split with BPE (byte-pair encoding): start from single characters and keep merging the pair of pieces that most often appear together, so common roots and affixes become subwords. Both languages share a vocabulary of about 37,000 tokens. On 8 P100 GPUs, the base model trained for 100k steps, about 12 hours, and the big model for 300k steps, about 3.5 days.

The optimiser is Adam, with a learning rate that rises and then falls:

lrate=dmodel−0.5⋅min⁡(step−0.5, step⋅warmup−1.5)lrate=d_{model}^{-0.5}\cdot\min\left(step^{-0.5},\ step\cdot warmup^{-1.5}\right)

It rises linearly for the first 4,000 steps to about 7×10−47\times10^{-4}, then decays as 1/step1/\sqrt{step}.

  • Dropout: applied to each sub-layer's output before the residual is added, and to the sum of the embeddings and positional encodings. The base model uses Pdrop=0.1P_{drop}=0.1, the big English-German model 0.3.
  • Label smoothing: ϵls=0.1\epsilon_{ls}=0.1. Perplexity gets worse, but accuracy and BLEU go up.

Results

  • English to German: the big model gets 28.4 BLEU, more than 2 BLEU above the previous best results, ensembles included. Even the base model (27.3) beats them, at a fraction of the training cost.
  • English to French: the big model gets 41.8 BLEU, the best single model at the time.
  • Model variants (Table 3, dev set): one head is 0.9 BLEU worse than the best setting, quality also drops with too many heads, and a smaller dkd_k hurts too.
  • English constituency parsing: a 4-layer Transformer trained only on the roughly 40k sentences of WSJ reaches an F1 of 91.3, so it is not just a translation model.

Things I got confused about

  • The 0.1 in label smoothing is probability taken away from the right answer: the target for the correct word drops from 1 to 0.9, and the remaining 0.1 is spread over the rest of the vocabulary, so the model is less sure of itself.
  • At inference the decoder generates one word at a time, but in training the mask lets every position be computed at once, in parallel.
  • 8 heads do not cost 8× as much, because each head only has 64 dimensions.
  • Dividing by dk\sqrt{d_k} scales down the scores inside attention. Multiplying by dmodel\sqrt{d_{model}} scales up the embeddings at the input. They are unrelated.

My take

My main takeaway is that the Transformer has very few built-in assumptions. It doesn't know word order and has no preference for nearby words, so it has to learn all of that from data. That makes it lean much more on data and model size, which is probably part of why Transformers kept getting bigger. The Vision Transformer shows the same thing: the fewer assumptions in the architecture, the more data it needs.

Page 10 of the paper: the conclusion, with yellow highlights and handwritten notes in Chinese under the code link and next to the References heading.

References

OlderFrom RNN to Seq2Seq →