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).
The core idea
An RNN has to finish before it can compute , 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.
- Tokens become 512-dimensional embeddings, plus a positional encoding.
- Encoder: 6 layers, each with multi-head self-attention and a position-wise feed-forward network.
- Decoder: 6 layers, with masked self-attention and an extra attention block over the encoder output.
- A linear layer and softmax give the probability of the next word.
Every sub-layer is wrapped in a residual connection followed by LayerNorm:
Every sub-layer outputs 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.
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:
The matrix shapes make it much clearer. 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 ? If the components of and are independent with mean 0 and variance 1, then has variance . With 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 brings the variance back to 1.
The mask in the decoder
When predicting word , 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 is added before the softmax to set every score after position to (in code, usually a very large negative number). Since , those weights all become 0:
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 learned linear layers to project , and into lower dimensions, runs attention once per head, then concatenates the results and projects them back:
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 , so the total cost is about the same as one 512-dimensional head.
Attention is used in three ways:
| Q from | K and V from | Mask | |
|---|---|---|---|
| Encoder self-attention | previous encoder layer | previous encoder layer | none |
| Decoder self-attention | previous decoder layer | previous decoder layer | hides later positions |
| Encoder-decoder attention | previous decoder layer | encoder output | none |
Feed-forward network
Each position goes through the same two-layer MLP on its own, with the weights shared across positions:
The widths are 512 → 2048 → 512. The split of work is clean: attention moves information between positions, and the MLP transforms each position separately.
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 is the position and is the dimension:
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 , is a linear function of . 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 . 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. is the sequence length, the vector dimension and the kernel size:
| Layer | Compute per layer | Sequential ops | Max path length |
|---|---|---|---|
| Self-attention | |||
| Recurrent | |||
| Convolutional |
- The in self-attention comes from every query scoring every key, and is the length of each dot product.
- An RNN takes steps, and each step multiplies the hidden state by a matrix, so it costs . Those steps also have to run one after another.
Sentences are usually shorter than . With and , the attention scores cost about and the RNN about , roughly 10× more. That only counts the term in the table, though. The Q, K, V and output projections add another , 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 . 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:
It rises linearly for the first 4,000 steps to about , then decays as .
- 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 , the big English-German model 0.3.
- Label smoothing: . 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 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 scales down the scores inside attention. Multiplying by 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.







