Let every word look at every other word — and delete everything else.
In 2017, every strong translation system read a sentence the way a ticker tape is read: one word at a time, left to right, carrying a running summary in its hidden state. Attention already existed — but only as a patch bolted onto that recurrent machinery, helping the decoder glance back at the input. This paper's bet was blunt: keep the patch, throw away the machine under it. No recurrence, no convolutions — attention as the only way information moves between positions.
The prize wasn't just translation quality, though it got that too. A model that reads word-by-word must compute word-by-word, and you cannot parallelize a loop whose every turn waits for the previous one. Pure attention has no such loop — every position is processed at once, as one big matrix multiplication, which is exactly what a GPU is good at. That property, more than any BLEU score, is why this architecture ended up underneath nearly every large model that followed.
“…the Transformer, based solely on attention mechanisms, dispensing with recurrence and convolutions entirely.” — the abstract
The task, the bottleneck, and the bet
What translation looked like in 2017 — and why this paper threw half of it away
Step 1 · The black box
English in, German out — and a sentence we'll keep for the whole lesson.
Start from the outside. The Transformer, as tested in this paper, is a translation box: an English sentence goes in, a German one comes out. The benchmark is WMT 2014 — about 4.5 million English–German sentence pairs to learn from.
We need a sentence to feed it, and the paper hands us one: in its appendix, the authors probe a trained model with test sentences and plot what the mechanism does to them. This is one of those sentences, and it stays with us to the end of the page:
One word in it will become the star: “its”. To translate “its application” correctly, the model has to work out that “its” points back to “Law” — a small act of reading comprehension that sits seven words away. Hold that thought; it's the example every mechanism on this page gets tested against.
Headline, up front: the big model scored 28.4 BLEU on WMT 2014 English→German — more than 2 points above every previous system, ensembles included — after 3.5 days of training on 8 GPUs. How it earns that is Parts B and C.
Step 2 · The bottleneck
Word-by-word reading kills parallelism — and stretches “its” → “Law” into a 7-hop relay.
The box translates our sentence without recurrence. To see why anyone would want that, look at what recurrence was costing.
A recurrent network reads position by position: the hidden state ht is computed from ht−1 and the current word. That little subscript is the whole problem. Each step needs the one before it, so nothing can run in parallel within a sentence — no matter how many processors you own, a 50-word sentence is 50 sequential steps. Memory limits make it worse: you can't just batch your way out at longer lengths.
There's a second cost, quieter but just as real. Watch “its” try to reach “Law” in our sentence:
The paper turns this picture into a table (its Table 1), scoring each layer type on two things we now care about: how many steps must run in sequence, and how long the worst-case path is between two positions. Convolutional stacks (ByteNet, ConvS2S) had already fixed the parallelism — but their path between distant words still grows with distance, linearly or logarithmically. Self-attention is the row where both columns hit bottom:
| layer type | sequential ops | max path length |
|---|---|---|
| self-attention | O(1) | O(1) |
| recurrent | O(n) | O(n) |
| convolutional | O(1) | O(logk n) |
The fine print on cost: per layer, self-attention is O(n²·d) — it compares every pair of positions — versus O(n·d²) for recurrence. That n² looks scary, but for typical sentence lengths n is far smaller than d = 512, so self-attention is actually cheaper. The paper is open about the caveat for very long sequences and sketches a windowed variant (path O(n/r)) as future work.
Step 3 · The machine, first pass
Two towers, six identical layers each — built from just two kinds of parts.
So the bet is: attention only, everything reachable in one step, everything computable in parallel. Here's the machine that bet produced — outline first, details owed.
The Transformer keeps the classic two-part shape of translation models. An encoder reads all 21 tokens of our sentence at once and turns them into 21 context-loaded vectors. A decoder then writes the German, one word at a time, consulting those vectors as it goes. Each side is a stack of N = 6 identical layers, and every layer contains only two kinds of machinery: an attention sublayer (words exchanging information) and a small feed-forward network (each word thinking by itself). Every vector everywhere has the same width, dmodel = 512, so the parts snap together.
Two IOUs before we dive. That “attention sublayer” is really multi-head attention — a phrase that will only make sense once you've computed attention yourself, so Steps 4–7 pay it off. And the decoder's “one word at a time” hides a masking trick, paid off in Step 10. Everything else in the drawing you've already met.
Inside either tower there is no path along the sentence. The only way “its” ever learns about “Law” is the attention sublayer. Whatever attention turns out to be, it is carrying 100% of the between-word traffic.
The heart of the machine
Q, K, V · one attention step by hand · the √dk scale · eight heads · the full layer · order · the decoder
Step 4 · Attention, felt first
Every word asks the whole sentence a question. “its” asks: whose am I?
All between-word traffic rides on attention — so let's watch it carry some. No numbers yet; first, what it feels like.
When the authors opened up their trained encoder, they found a head in layer 5 doing something you can read off the plot: at the word “its”, the attention lands sharply on “Law” and “application” — the two words that resolve what the pronoun refers to. That's the paper's Figure 4, and here it is redrawn:
The mechanism behind those arcs runs on three vectors per word. Take the embedding of “its” and multiply it by three learned matrices — WQ, WK, WV — to get a query (the question this word is asking), a key (the label it shows when other words ask), and a value (the content it hands over if selected). Attention is then a soft lookup: the query of “its” is compared against every word's key, and the answer comes back as a weighted blend of every word's value. Not one winner — a blend, weighted by how well each key matches.
If the three-way split feels arbitrary, you're in good company — this is the point where most readers stall, and the paper itself introduces q, k, v in a single sentence and moves on. It helps to notice the roles are genuinely different: when “its” looks for its noun, the question it asks (“I'm a possessive pronoun seeking an owner”) is not the label it shows others (“I'm a determiner-ish little word”), and neither is the content it would contribute. One vector can't play all three parts at once.
Where do the matrices' numbers come from? Training — backpropagation pushes them toward whatever makes translation work, and we won't open that box on this page (the recipe lives in §5 of the paper). What we can do is run the mechanism itself, by hand, right now.
Step 5 · One attention step, by hand
Four dot products, a division, a softmax, a weighted sum — that's the entire mechanism.
“its” has a query; every word has a key and a value. Time to run the lookup — with numbers small enough to check on paper.
We shrink the world to four words of our sentence — Law, perfect, its, application — and make the vectors 4-dimensional (the real model uses 64 per head; nothing about the procedure changes). The word asking is “its”, with query q = [2, 0, 2, 0]. The keys are: k(Law) = [2, 0, 2, 0], k(perfect) = [0, 2, 0, 0], k(its) = [1, 0, 1, 0], k(application) = [2, 0, 1, 0]. Notice we've rigged Law's key to point the same way as the query — that's the geometric meaning of “this key matches”.
Dot each key with the query
Multiply matching components, add them up. A big result means “this key points where the query points”.
Divide by √dk = √4 = 2
The scale that gives the paper's attention its name. Why it's there is Step 6's whole job — for now, just do it.
Softmax the scores into weights
Exponentiate each score, divide by the sum: e⁴ = 54.6, e⁰ = 1.0, e² = 7.4, e³ = 20.1, total 83.1. Weights sum to 1 — and the exponential stretches gaps.
Blend the values with those weights
Toy values, 2-d: v(Law) = [1, 0] · v(perfect) = [0, 1] · v(its) = [0.5, 0.5] · v(application) = [1, 1]. The output is the weighted sum.
Read the result. The new vector for “its” is about two-thirds Law-stuff and a quarter application-stuff — the pronoun has pulled in the words it refers to. Those are the two heavy arcs of Step 4, now with arithmetic under them. 0.66 and 0.24 aren't decoration; you just computed where they come from.
Drag the raw scores — watch softmax hand out the weights
Two things to notice. Weights always sum to 1 no matter what you do. And a gap of 2 between raw scores (÷2, then e¹) is already a factor of e ≈ 2.7 in weight — softmax is an amplifier. Push perfect's score to 10 and watch it steal almost everything.
equation (1) of the paper · you have just computed one row of it
This one line is steps a–d in matrix clothes. Stack every word's query into a matrix Q, every key into K, every value into V: then QKT computes all the dot products at once, the softmax runs per row, and the final multiplication by V does every word's blend simultaneously. No loop over positions anywhere — the Step 2 promise of parallelism is cashed in right here, as a pair of matrix multiplications.
Honesty note: our toy q, k, v values are invented for teaching — in the real model they're learned, 64-dimensional, and no one hand-picks them. What is faithful: the procedure (dot, scale, softmax, blend) is exactly equation (1), and the sharp-attention-to-Law behaviour is what the trained model actually does in Figure 4.
Step 6 · Why divide by √dk
Long vectors make big dot products — and big scores drive softmax into a dead zone.
In step b you divided by 2 on faith. The reason is a one-line statistics argument, and it's the paper's own (footnote 4).
Suppose each component of q and k is a random number with mean 0 and variance 1. Their dot product adds up dk such products, so its variance is dk — typical size √dk. At our toy dk = 4 that's a tame 2. At 512 it's about 23, and softmax of scores around ±23 is winner-take-all: one weight lands at ≈ 1.0, the rest at ≈ 0.0000000001. That's fatal for learning — in that regime the gradients through softmax are vanishingly small, so training stalls. Dividing by √dk puts the variance back to 1, whatever the dimension.
Slide dk — same three scores, with and without the scale
typical raw score √dk ≈ 8.0
Without the scale · scores ±√dk
With ÷√dk · scores ±1, always
Left panel: the blend collapses as dk grows. By 256 the “weighted average” is really just a copy of one value — and the near-zero weights mean near-zero gradients, so those connections stop learning. Right panel: scaled scores don't care what dk is.
Context from §3.2.1: the two standard attention flavours were additive (a small feed-forward net scores each query–key pair) and dot-product. Dot-product wins on speed — it's just matrix multiplication — but unscaled it loses quality at large dk, for the reason above. The √dk scale is the two-character fix that keeps the fast one accurate.
Step 7 · Eight heads, not one
One head can only average. Eight small heads can each specialize.
You computed one blend for “its”: mostly Law, some application. Good — but a sentence holds more than one kind of relationship, and one blend can only encode one.
“its” doesn't just need its antecedent. Some layer needs to know it sits next to “application”; another that it's inside the clause after “but”. A single attention head must cram all of that into one set of weights — one weighted average — and the paper is blunt about the cost: averaging inhibits it (§2). The fix is to run several small attentions side by side. Project the words into h = 8 different 64-dimensional subspaces — each head gets its own WiQ, WiK, WiV — run equation (1) independently in each, then concatenate the eight outputs and mix them with one last matrix WO.
Does the freedom get used? The paper's Figure 5 answers with our own sentence. Two heads, same layer, same input — completely different habits:
headi = Attention(QWiQ, KWiK, VWiV) · each head works in 64 dims
The budget trick: 8 heads × 64 dims = 512, so multi-head attention costs about the same as one full-width head — the capacity is re-arranged, not added. Does it matter? A single 512-dim head loses 0.9 BLEU; 32 heads also drops quality. The full table shows up in Step 12.
Step 8 · The rest of a layer
Attention mixes between words; the feed-forward net thinks per word; residuals keep six of these trainable.
Multi-head attention was the hard half. One more part and you can read the paper's architecture diagram without a legend.
After attention has mixed information between positions, each position gets private processing: a two-layer feed-forward network, applied to every word separately and identically — FFN(x) = max(0, xW₁ + b₁)W₂ + b₂ — expanding from 512 up to dff = 2048 and back. Same weights at every position, different weights in every layer.
Around both sublayers runs the plumbing that makes a 6-deep stack trainable: a residual connection adds each sublayer's input to its output, and layer normalization re-scales the result — LayerNorm(x + Sublayer(x)). We'll treat LayerNorm as a black box that keeps the numbers well-behaved (it has its own paper, cited as [1]); the residual idea is borrowed from ResNet, and it's why dmodel must stay 512 everywhere — you can only add vectors of the same width.
Track “its” through this drawing once. It arrives as a vector, leaves the attention block carrying its 0.66-Law blend, gets added to its old self (residual), normalized, then privately transformed by the FFN, added and normalized again — and hands the result to the next layer, where the whole game repeats with sharper inputs. After six rounds, “its” is no longer a pronoun; it's a pronoun that knows its noun.
Step 9 · Order, injected as waves
Attention is order-blind, so each position's number is written in as a fingerprint of sines.
One thing in the tower should bother you: nothing so far ever used word order. Shuffle our sentence and every dot product in Step 5 comes out identical.
Recurrence got order for free — it read in order. With recurrence gone, order has to be smuggled into the data itself. The paper adds a positional encoding vector to each word's embedding before the first layer: position pos, dimension i gets sin(pos / 100002i/dmodel) in the even slots and the matching cosine in the odd ones. Each dimension is a wave; the wavelengths grow geometrically from 2π to 10000·2π. Fast waves distinguish neighbors, slow waves distinguish regions — together, every position gets a unique fingerprint:
Why sines instead of just learning a vector per position? The authors give two reasons, one proved and one hoped. The proved one: for any fixed offset k, PEpos+k is a linear function of PEpos, which should make “attend three words back” an easy pattern to learn. The hoped one: waves extend to any position, so the model might handle sentences longer than any it saw in training. Honest footnote — they tried learned position embeddings too, and the scores came out nearly identical (Table 3, row E). The sinusoids won on the extrapolation hope, not on the scoreboard.
Step 10 · The decoder: writing without peeking
Generate left to right, mask the future, and let German queries read English keys.
The encoder is done: 21 English vectors, each soaked in context. Now the other tower has to write German — and writing is where attention needs a leash.
Fair warning: this is the twistiest part of the architecture, because the decoder's input is its own earlier output. During training, the model learns to predict every position of the real German sentence at once — position i should be predictable from positions before i only. But self-attention, as built in Step 5, looks everywhere — including at the very future words the model is supposed to predict. Unleashed, it would learn to copy the answer sheet.
The fix costs one matrix: before the softmax, set every query-to-future-key score to −∞. Softmax turns −∞ into weight 0 — the future is still on the page, but it gets exactly none of the blend. Combined with shifting the output sequence one slot right (so position i's input is word i−1), the prediction for position i can only draw on what comes before it.
Pick a writing position — see what its attention may touch
writing position 3 · visible positions: 3 of 5
Whichever row you pick, the upper-right triangle stays crossed out. Those × cells are the −∞ scores: after softmax they weigh exactly 0. Rows = the word being written; columns = the positions it wants to look at.
The full decoder layer stacks three attentions, and you've now met every one of them. The paper's §3.2.3 lists the trio: encoder self-attention (Steps 4–7, unrestricted), decoder masked self-attention (the grid above), and between them encoder–decoder attention — queries come from the German side, keys and values from the encoder's 21 English vectors. That third one is where translation actually crosses the language line: when the decoder writes “wird”, its query reaches into the English sentence and lands on the key of “will”. Same equation (1) every time; only the sources of Q, K, V change.
One more honesty note: our five-word “Das Gesetz wird nie perfekt” is a hand-made illustration of the first half of the sentence — the paper doesn't print its German outputs. Decoding details it does give: generation stops early or at input length + 50, and the reported scores use beam search with beam 4 and length penalty α = 0.6.
Did the bet pay off?
Results · what the ablations taught · test yourself
Step 11 · The report card
State of the art on both benchmarks — for a fraction of everyone else's compute.
The machine is complete: encoder, decoder, masks, waves. The claim in the title still needs numbers behind it.
Translation quality is scored in BLEU — an overlap score between the system's output and human reference translations, where higher is better and a couple of points is a big deal. On WMT 2014 English→German, the big Transformer scores 28.4: more than 2 BLEU above every previous system, including ensembles of models. Even the base model beats every prior single model and ensemble — and that's the cheap one:
Report card · WMT 2014 english→german BLEU (longer = better)
Transformer (big) · 3.5 days, 8 GPUs
Transformer (base) · 12 hours, 8 GPUs
ConvS2S ensemble
GNMT + RL ensemble
ByteNet
0BLEU →30
The parsing line deserves a pause. The authors pointed the same architecture at a different, structurally strict task — producing parse trees — changed almost nothing, and still landed near the state of the art (91.3 F1 training on just 40K sentences, 92.7 semi-supervised). For a paper claiming attention is all you need, generalizing beyond translation was the claim's first real test outside its home turf.
Training recipe, for the record: WMT 2014 data (4.5M sentence pairs EN–DE with 37K shared BPE vocabulary; 36M pairs EN–FR), Adam with a 4000-step warmup then inverse-square-root decay, dropout 0.1 on every sublayer output and on the embedding + positional-encoding sums, and label smoothing 0.1 — which hurts perplexity but helps BLEU.
Step 12 · What the knobs taught + self-test
The ablation table is a design manual: heads matter, key size matters, dropout matters.
Results say the whole machine works. Ablations say which parts were load-bearing: the authors re-trained the base model dozens of ways and watched what each change cost.
The scores below are on the development set (newstest2013), so they're a notch lower than Step 11's test numbers — what matters is the gaps:
Ablations · BLEU on newstest2013 dev · axis starts at 23 to magnify gaps
big · dmodel 1024, 16 heads, dropout 0.3
base · the reference point
learned position embeddings (row E)
key size dk cut to 16 (row B)
single attention head (row A)
no dropout (row D)
23BLEU (dev) →27
Reading the rows: one head loses 0.9 BLEU against the best setting — Step 7's specialization argument, measured — but 32 heads drops quality too, so more isn't monotonically better. Shrinking the keys to dk = 16 hurts, which the authors read as a hint that judging query–key compatibility is genuinely hard — a dot product may not even be the final word. Dropping dropout costs 1.2 BLEU, the single worst change. And learned position embeddings tie the sinusoids almost exactly, which is the honest footnote under Step 9.
Now close the loop. Five questions, answers folded away — each one traces back to a step you did with your own hands:
Walk “its” through one attention step.
Its query is dotted with every word's key (8, 0, 4, 6 in our toy), the scores are divided by √dk, softmax turns them into weights (0.66, 0.01, 0.09, 0.24), and those weights blend the value vectors into a new vector for “its” — mostly Law, some application.
Why divide by √dk?
A dot product of dk unit-variance components has variance dk, so raw scores grow like √dk. Softmax on big scores saturates to winner-take-all and its gradients vanish; the ÷√dk puts variance back at 1 for any dimension.
Why eight heads instead of one big one?
One head produces one weighted average — one relationship per word. Eight heads in separate 64-dim subspaces can specialize (Figure 5: one tracks content words, one watches neighbors) at the same total cost. A single head measurably loses 0.9 BLEU.
How does the decoder avoid reading the answer sheet?
Scores from any position to later positions are set to −∞ before softmax, so future words get weight 0; the target is also shifted right one slot. Prediction for position i can only use positions before i.
If attention ignores order, how does the model know it?
A positional encoding is added to each embedding before layer 1 — sinusoids whose wavelengths grow geometrically, giving every position a unique fingerprint. Learned embeddings scored the same; sinusoids were chosen hoping to extrapolate to longer sentences.
Homework — open the actual PDF and flip to the appendix. Figure 3 is the same plot style you now know from Steps 4 and 7, showing heads bridging “making … more difficult” across 13 words. You can read those plots now; that's the test that you own the mechanism.
“…we presented the Transformer, the first sequence transduction model based entirely on attention, replacing the recurrent layers most commonly used in encoder-decoder architectures with multi-headed self-attention.” — the conclusion, Vaswani et al., 2017
Both towers went on to run the field — half each.
The conclusion announced plans to extend the Transformer to images, audio and video. That is roughly what happened — within three years the architecture had outgrown translation, and its two towers became two dynasties.
BERT
Stacks of the encoder tower — Steps 4–8, attention unmasked in both directions — pretrained on raw text, became the default reading machine for search and understanding tasks.
GPT and its heirs
The masked tower of Step 10, scaled up and left to write: autoregressive decoder-only Transformers are the blueprint of essentially every modern large language model.
ViT · audio · code
Treat image patches, audio frames or source code as token sequences and the same machinery applies — the paper's own closing prediction, delivered.
d_model, heads, layers — the configuration vocabulary this paper coined is still the first line of nearly every model card.