In one line: Replaced recurrence entirely with multi-head scaled dot-product self-attention, making sequence training parallel and becoming the backbone of nearly every modern LLM.
Drop recurrence and let every position attend to every other position in one parallel step: the path between any two words falls from n steps to 1, training parallelises across the sequence, and an encoder-decoder built only from attention, a per-position feed-forward layer and Add & Norm beat every earlier translation model at a fraction of the training cost.
How far to trust it: the idea held up completely; the BLEU margins are single runs with no error bars, and two printed numbers disagree with each other or with a recount (Results).
The whole model is attention, a feed-forward layer and Add & Norm: no recurrence, no convolution. The figure is the base model of Figure 1 in 3D: N = 6 of each layer, dmodel = 512, h = 8, dff = 2048. Step through it in the order data flows; drag it to turn it.
The sentence is an illustration; the layout and sizes are the paper's (§3.1). Notice the three kinds of attention: the encoder's self-attention, the decoder's masked self-attention, and cross-attention carrying the encoder's keys and values into every decoder layer.
New terms. Sequence transduction: mapping one sequence to another (translation, parsing). Post-LN: the norm applied after the residual sum, LayerNorm(x + Sublayer(x)). Background the page assumes: RNN encoder-decoders with Bahdanau attention (Sequence models before the transformer).
In 2017 sequence transduction, translation above all, was dominated by recurrent encoder-decoders (LSTMs and GRUs), usually with an attention mechanism between encoder and decoder, and by convolutional alternatives such as ByteNet and ConvS2S (§1, §2). A recurrent network computes its hidden state ht from ht−1 and the input at position t, so training cannot be parallelised along the sequence: that caps how much of a GPU a batch can use, and memory limits batching across examples as sentences get longer. Convolutional models do compute all positions in parallel, but connecting two distant positions takes a stack of layers, O(n/k) for contiguous kernels (ConvS2S) or O(logk n) for dilated ones (ByteNet), so long-range dependency paths stay long (§4).
The question: can attention alone, with no recurrence and no convolution, carry an entire sequence model?
Let every position look at every other position directly, in one step. Section 4 compares layer types on three counts: total computation per layer, how much of it can run in parallel (the minimum number of sequential operations), and the longest path a signal has to travel between two positions, since shorter paths make long-range dependencies easier to learn (§4, Table 1).
| Layer | Computation per layer | Sequential operations | Longest path |
|---|---|---|---|
| Self-attention | O(n²·d) | O(1) | O(1) |
| Recurrent | O(n·d²) | O(n) | O(n) |
| Convolutional | O(k·n·d²) | O(1) | O(logk(n)) |
| Self-attention, restricted to r neighbours | O(r·n·d) | O(1) | O(n/r) |
n is the sequence length, d the representation size, k the kernel width, r the neighbourhood size (Table 1).
When n < d, as with sentence-level word-piece and byte-pair tokens, self-attention is also cheaper per layer than recurrence: n²d < nd² exactly when n < d, so with the base model's d = 512 the crossover is at 512 tokens; for longer sequences the paper suggests the restricted row (§4). The figure runs one sentence through both layer types, step by step below; the Table 1 calculator moves n and d.
Counts follow Table 1: n sequential steps of d² multiply-adds against all n² dot products of length d at once (the 4nd² projections are left out, as in the table).
The Transformer is an encoder-decoder built only from attention, position-wise feed-forward layers, residual connections and layer normalisation (§3). Attention maps a query and a set of key-value pairs to a weighted sum of the values, the weights coming from how well the query matches each key. With queries and keys of size dk and values of size dv, packed as matrices:
The figure runs Equation 1 with real numbers: the first encoder layer of this page's trained toy Transformer (Run a Transformer; dmodel = 24, h = 4, so dk = 6), head 4, on one sentence. The paper's base model does the same with dk = 64.
Query word
The 1/√dk is the load-bearing detail. If the components of q and k are independent with mean 0 and variance 1, then q·k = Σqiki has mean 0 and variance dk (the paper's footnote 1). Unscaled, the logits spread out as dk grows and push the softmax into regions with tiny gradients; the paper notes that additive attention beats unscaled dot-product attention at large dk (§3.2.1).
Try: these are real random vectors, drawn fresh with each press of Redraw. Drag dk up and watch the unscaled softmax (left) collapse onto one key while its gradient vanishes; the scaled one (right) keeps the same spread at every size.
Ten keys and one query with components drawn from a standard normal (Box-Muller, seeded). Variance of q·k is measured over 4,000 fresh pairs. "Largest gradient" is the largest entry of the softmax Jacobian, max pi(1 − pi): how much the strongest logit can still move the output. Illustrative inputs; the formula is the paper's.
Instead of one attention over dmodel = 512 dimensions, the queries, keys and values are projected h = 8 times with learned matrices WiQ, WiK (dmodel × dk) and WiV (dmodel × dv), with dk = dv = dmodel/h = 64. Each head runs attention in parallel; the h outputs are concatenated and projected back by WO (hdv × dmodel) (§3.2.2).
Because each head is h times narrower, the total cost is about that of one full-width head. What it buys: heads can attend to different subspaces and positions at once, where a single head has to average them. In the ablation one head costs 0.9 BLEU against the best setting (24.9 against 25.8), and too many heads hurt as well: 32 heads of 16 score 25.4 (Table 3 rows (A)). The Run a Transformer tab shows every head of a trained toy model, and a one-head version of it.
The encoder is a stack of N = 6 identical layers with two sub-layers each: multi-head self-attention, then a position-wise feed-forward network. Every sub-layer is wrapped as LayerNorm(x + Sublayer(x)), normalisation after the residual sum ("post-LN"), with dropout on the sub-layer output before it is added. Every sub-layer and the embeddings produce outputs of size dmodel = 512 so the residuals line up (§3.1, §5.4).
The decoder is also N = 6 layers, with three sub-layers: masked self-attention, where every illegal connection is set to −∞ before the softmax so position i sees only positions up to i (combined with the outputs being shifted right by one, a prediction depends only on earlier words); cross-attention, whose queries come from the decoder and whose keys and values come from the encoder's output, so every output position can look at every input position; and the same feed-forward network (§3.1, §3.2.3).
v2 (19 June 2017) and v3 (20 June) end with an appendix, "Two Feed-Forward Layers = Attention over Parameters": Equation 2 is a kind of attention, with ReLU in place of the softmax and each of the 2,048 hidden units a stored pair, its column of W1 the key and its row of W2 the value, so the FFN is a key-value memory four years before Geva et al. (2021) measured trained FFNs behaving as one. Its Table 5 replaces every FFN with attention over learned key-value pairs at matched parameters (65M), on newstest2013 (development): base perplexity 4.92 and BLEU 25.8; AOP1 4.92 and 25.5; AOP2 4.86 and 25.9, both trained 16 hours against the base's 12. One slip: the text gives the second model 8 heads where Table 5 says 16. From v4 (30 June 2017) on, the appendix is gone; this page reads v7. Checked against v1 to v5 on the transformers-from-memory article page, which derives why a sharper curve than ReLU (up to softmax) lets such a memory hold more rows.
Embeddings. One weight matrix is shared by the input embedding, the output embedding and the pre-softmax projection, and in the embedding layers it is multiplied by √dmodel (§3.4); with the shared English-German vocabulary of about 37,000 tokens, that one matrix is 18.9 million of the base model's parameters (37,000 × 512, counted in the tables tab).
With no recurrence and no convolution nothing in the model knows word order, so it has to be injected. The paper adds fixed sinusoids to the embeddings at the bottom of both stacks:
Why sinusoids: for any fixed offset k, PEpos+k is a linear function of PEpos (each sine and cosine pair is rotated by an angle that depends only on k), which the authors hoped would make attending by relative position easy to learn. Learned absolute embeddings gave nearly identical results (25.7 BLEU against 25.8, Table 3 row (E)); the sinusoids were kept because they might extrapolate to sequences longer than any seen in training (§3.5). What later models use instead (relative biases, ALiBi, RoPE and its scaling) is taught on Positional encodings.
Left: the encoding of positions 0 (top) to 63 (bottom) across all 512 dimensions at dmodel = 512 (blue negative, orange positive): fast sinusoids on the left, wavelengths up to 10000 · 2π on the right. Right: PEp · PEp+k against the offset k for three starting positions p: the curves coincide, because the dot product depends only on the offset. Computed from the formula above.
Exactly the same, and not by luck. Without positions the encoder is permutation-equivariant (shuffle the input words and its outputs shuffle the same way) and cross-attention sums over the encoder's outputs, which ignores their order; so any reordering of the source gives the same translation. The trained no-position model shows it word for word: . Try it with the real weights in the Run a Transformer tab, where this model gets of held-out sentences right against for the full model.
Batches held about 25,000 source and 25,000 target tokens, sentences grouped by length (§5.1). Dropout is applied to every sub-layer output and to the sums of embeddings and positional encodings (§5.4). Decoding stops at input length + 50; the final model averages the last 5 checkpoints, written every 10 minutes, for base models and the last 20 for big ones (§6.1).
§5.4 announces "three types of regularization" and lists two (residual dropout and label smoothing). §5.2 gives the base model as 65M parameters; recounting from the stated configuration gives 63.1M (the recount in the tables tab).
FLOPs (Table 2, footnote 2): training time × number of GPUs × an estimate of each GPU's sustained single-precision rate (2.8, 3.7, 6.0 and 9.5 TFLOPS for K80, K40, M40 and P100). Defaults reproduce Table 2 independently: 12 h × 3,600 s × 8 × 9.5 × 1012 = 3.28 × 1018 (3.3 × 1018), and 3.5 days gives 2.30 × 1019 (2.3 × 1019); see recompute.py. These are estimates of what the hardware could do, not measured operations.
41.0 against 41.8. The two primary figures disagree: the v7 text of §6.1 still says 41.0, the figure the v1 and v2 abstracts reported, while Table 2 and the abstract from v5 on say 41.8.
Vocabulary 16K (WSJ only) or 32K (semi-supervised); beam 21, α = 0.3, maximum output length input + 300; little task-specific tuning (§6.3).
From Table 3. Depth matters most at this scale: 2 layers lose 2.1 BLEU; no dropout loses 1.2, a quarter-size dmodel 1.3, one head 0.9, learned positions 0.1. Every row, with perplexity and parameters, is in The paper's tables, rebuilt.
Table 2 rebuilt: BLEU on newstest2014 against training FLOPs (log scale). Filled: single models; rings: ensembles; Transformers in blue. The paper prints one cost per Transformer model for both pairs; ByteNet (EN-DE 23.75) and Deep-Att + PosUnk have no cost and are listed under the chart. The Transformer costs reproduce independently (details below).
Removing recurrence made training embarrassingly parallel across sequence length, which let compute be spent on model and data size instead of waiting on wall-clock sequential steps. Every frontier LLM (GPT, Claude, Llama, Gemini, DeepSeek), BERT-style encoders, ViT, CLIP, Whisper and most of diffusion's backbone work descend from this design.
What survived untouched: scaled dot-product attention itself, multi-head projections, and the residual-plus-norm wrapping. What changed were the choices that turned out not to be load-bearing, each taught on the page that owns it: decoder-only won for generation, with cross-attention surviving in multimodal adapters and encoder-decoders holding on in T5 and Whisper (Families and objectives); pre-LN and RMSNorm replaced post-LN LayerNorm (Normalisation, residuals and stability); RoPE replaced the added sinusoids, with interpolation and YaRN to extend the context (Positional encodings); SwiGLU (or GeGLU) replaced the ReLU FFN and biases were dropped; MQA, GQA and MLA shrink the KV cache (Attention variants); FlashAttention makes exact attention IO-aware (Writing kernels), since the O(n²) cost the paper acknowledged is now the central serving bottleneck, also attacked by PagedAttention, sliding windows, and sparse and linear hybrids such as Mamba; and the recipe changed: label smoothing and heavy dropout largely dropped at pretraining scale (PaLM trained without dropout), with Adam's β2 moved to 0.95 and the warmup then decay schedule surviving in cosine form. The Then and now tab morphs the 2017 block into a 2026 one, one sourced change per step.
Connections. BERT kept the encoder; GPT-3 and Scaling Laws scaled the decoder; T5 kept the encoder-decoder; ViT fed it image patches; RoFormer replaced its positional encoding; FlashAttention and PagedAttention attack the memory and IO costs it created; Mamba tries to remove its O(n²) core. Topics: ml-fundamentals (sequence-model history, attention), llm-training-and-post-training (positional encodings, learning-rate schedules), llms (the ancestor of every family covered). Each is described in Further reading.
This is not an illustration. A tiny encoder-decoder Transformer built exactly as §3 describes (post-LN residual blocks, sinusoidal positional encoding, multi-head scaled dot-product attention, a ReLU feed-forward network with a 4× expansion, masked decoder self-attention, cross-attention, and one embedding matrix shared by both inputs and the output projection, scaled by √dmodel) was trained offline with PyTorch, and its weights are inside this page. Your browser runs its forward pass in plain JavaScript, so every translation and every attention map below is computed live from the real weights. Inspired by Polo Club's Transformer Explainer, which runs GPT-2 in the browser; this page loads nothing from the network, so the model has to be small enough to ship inside it.
Lindu is invented for this page so the task is exactly known and every answer can be checked by rule (grammar.py and 21_js_lang.js). It is verb-final, like Japanese or the German subordinate clause: subject, then any place phrase, then the object marked with su, then the verb. Adjectives follow the noun in mirrored order, the article comes last, and prepositions become postpositions. So the alignment between the languages crosses itself, as English-German translation does, and a model that ignores word order cannot translate it.
Vocabulary: 2 articles, 5 adjectives, 8 nouns, 4 places, 5 verbs, 3 prepositions, and their 27 Lindu words plus su; 58 entries in one shared vocabulary with the start, end and padding symbols, as the paper shares one BPE vocabulary between English and German (§5.1). The grammar generates 540.8 million distinct sentences; training drew 2,048,000 sentences, 1,231,511 of them distinct, and the 2,000 test sentences behind the accuracies on this page were drawn the same way but never occur in that stream (overlap.py, train.py).
Click words to build an English sentence; only words that can come next are offered (subject, verb, object, then an optional place phrase). Pick which of the three trained models translates it. The translation, and everything below, updates as you go.
Greedy decoding: at each step the decoder sees the source (through cross-attention) and only the words it has already written (through masked self-attention), and picks the most probable next word. The paper uses beam search with beam 4; on this task greedy is enough. The bars under the source are the cross-attention of the step's query in the chosen layer: where the model is looking to choose that word.
The decoder writes the Lindu sentence phrase by phrase, and each phrase reads a different part of the English. The animation plays one stretch per phrase of the sentence above (it changes when you compose a new one); the caption under it gives each word's probability and where cross-attention looks.
Pick the kind of attention, the layer and the head. Rows are queries, columns are the keys they attend to; each row sums to 1. Cross-attention rows are labelled by the Lindu word being chosen; the dots mark the English word that the rules say it translates. Encoder self-attention is what the paper's appendix visualises for its own model (Figures 3 to 5).
The same architecture trained three times on the same data with the same seed: the full model, the model with the positional encoding removed, and the model with one head of 24 instead of four heads of 6 (same parameter count). Accuracy is exact-match sentences on 2,000 held-out test sentences, measured in PyTorch on the weights this page ships (check_forward.py confirms the browser gives the same translations).
Without positions the encoder cannot tell "the dog chased the cat" from "the cat chased the dog": attention is a weighted sum over a set, so reordering the source words reorders the encoder's outputs and leaves cross-attention's sums unchanged. The decoder still gets the shape of a Lindu sentence right (it gets of words right) because its own causal mask leaks position: a word can count how many earlier words it sees, as Haviv et al. 2022 found in language models trained without positional encodings. But it has to guess which noun is the subject and which adjective belongs to which noun, so only of sentences come out right. One head is enough on this task (it scores the same as four), unlike the paper's 0.9 BLEU loss on real translation (Table 3 (A)); its attention maps are blunter, as the maps above show.
Translate fresh random sentences with all three models in your browser and score them against the rules. Sentences are drawn uniformly over all 540.8 million distinct sentences (fixed seed), so they run longer than the training mix, and only 0.2% of such sentences occur in the training stream. For comparison, PyTorch on 2,000 such sentences that are not in training: full model 100%, no positions 0.7%, one head 100% (overlap.py).
35,184 parameters (dmodel 24, 4 heads, 2 + 2 layers), trained like the paper (Adam, Equation 3, dropout and label smoothing 0.1); the browser forward pass matches PyTorch exactly on 200 held-out sentences.
Training loss (label-smoothed cross-entropy) every 1,000 steps, from train.py's log. The dashed line is the smallest loss label smoothing 0.1 allows over 58 words, : the full and one-head models reach it; without positions the model stalls far above.
Every number below is transcribed from the arXiv HTML (v7) of the paper, and every derived number is recomputed in recompute.py. Each section links the table it rebuilds.
Try: slide the sequence length past the representation size and watch self-attention's n²d overtake recurrence's nd². Table 1 gives orders of growth; the curves drop the constants, as the table does.
At the paper's d = 512 the crossover is n = d = 512 tokens (recompute.py). The default n = 30 is an illustrative sentence length, not a figure from the paper. Restricted self-attention is the paper's own suggestion for long sequences (§4).
Table 2 (translation quality against training cost) is drawn in the Reading tab beside the result it proves: Table 2 chart.
Dev-set (newstest2013) results; base model 25.8 BLEU and perplexity 4.92 per word-piece; unlisted values equal the base model's. Rows (A) keep computation constant as heads change (§6.2).
Parameters: the paper's column where it has one, and this page's count from each configuration (with a 37,000-token shared vocabulary, biases and LayerNorm; see the recount below). The big row trains 300K steps with dropout 0.3.
Embedding: one shared 37,000 × 512 matrix, 18,944,000. Each attention sub-layer: four 512 × 512 matrices plus biases, 1,050,624. Each FFN: 512 × 2048 and 2048 × 512 plus biases, 2,099,712. Each LayerNorm: 1,024. Encoder layer 3,152,384; decoder layer (two attentions, three norms) 4,204,032; six of each: 44,138,496. Total 63,082,496, against the paper's 65M.
Does not reproduce exactly: with the stated vocabulary of "about 37000 tokens" (§5.1) the count is 63.1M, 1.9M (3%) below 65M; a vocabulary of 40,745 would give 65.0M exactly. The other rows show the same shortfall of about 1.2M to 4.1M (proportional to dmodel, as an embedding term would be), except the big model, which comes out 1.3M above 213M; the paper does not say how it counted (what "about 37000" was exactly, or which biases and norms it included), so the gap is left open rather than fitted.
Each step makes one change that later work introduced, names the paper, and recounts the block. The widths stay at the paper's base model (dmodel 512, 8 heads of 64) so every count is comparable; only the design changes. Counts are per decoder layer and computed from the formulas in the caption, not from any one model. The stage draws one decoder layer as its stack of sub-layers, bottom to top in the order data flows.
Parameters per decoder layer at d = 512: attention 4d² (with GQA, 2d² + 2d · g · 64 for g KV heads), FFN 2d · dff (SwiGLU: 3d · dff), plus biases and norm gains while they exist. KV cache: numbers stored per token per layer, 2 × (KV heads) × 64.
| Change | 2017 | Now | Introduced or adopted by |
|---|---|---|---|
| Decoder-only | encoder-decoder with cross-attention | one causal stack over prompt and answer | Liu et al. 2018 (drops the encoder, "almost reducing model parameters by half"); GPT; GPT-3. Encoder-decoders hold on in T5 and Whisper. |
| Pre-LN | LayerNorm(x + Sublayer(x)) | x + Sublayer(Norm(x)), plus a final norm | GPT-2 §2.3; Xiong et al. 2020 show post-LN's large gradients near the output at initialisation are why it needs warmup, and train pre-LN without it. |
| RMSNorm | LayerNorm (subtract mean, divide by deviation, gain and bias) | divide by root mean square, gain only | Zhang and Sennrich 2019 |
| RoPE | sinusoids added once to the input | q and k rotated by position inside every attention | RoFormer (Su et al. 2021); context extension by interpolation and YaRN (LLM Architecture Gallery) |
| SwiGLU | max(0, xW1)W2, 4× inner size | (Swish(xW) ⊗ xV)W2, three matrices, inner size scaled by 2/3 to hold the parameter count | Shazeer 2020; PaLM, Llama |
| GQA (and MQA, MLA) | 8 query heads, 8 key-value heads | query heads share fewer key-value heads, shrinking the KV cache | Shazeer 2019 (MQA), Ainslie et al. 2023 (GQA); MLA in DeepSeek (Architecture Gallery) |
| No biases | biases in every projection and norm | none | PaLM §2: "No biases were used in any of the dense kernels or layer norms", for training stability |
| Long context and serving | O(n²) attention accepted | IO-aware kernels, paged KV, sliding windows, linear or state-space hybrids | FlashAttention, PagedAttention, Mamba |
| Training recipe | dropout 0.1, label smoothing 0.1, Adam β2 0.98, warmup then 1/√step | no dropout in pretraining, β2 0.95, warmup then cosine decay | GPT-3 Appendix B (β2 0.95, cosine decay to 10% over 260B tokens after a 375M-token warmup); PaLM §5 (trained without dropout) |
Every link opens in a new tab. Reading time of the resources below: 6h 25m.
NeurIPS 2017, the paper itself; the HTML version has the anchors this page links to. abstract page, PDF.
(45 min)
the authors' code (repo, about 20 minutes for the README and entry path); now deprecated in favour of Trax.
(20 min)
Jay Alammar: still the canonical visual walkthrough of Q/K/V, multi-head attention and the encoder-decoder data flow.
(30 min)
Harvard NLP, 2022 revision: the paper reimplemented line by line in PyTorch; the fastest route from equations to working code.
(1h 30m)
3Blue1Brown: the best geometric intuition for what attention heads actually compute.
(30 min)
Andrej Karpathy: builds a decoder-only Transformer from an empty file; makes the causal masking and multi-head mechanics concrete.
(2h)
Polo Club, Georgia Tech: a live GPT-2 small running in your browser: type a prompt and inspect every attention head and the sampling step. Its paper is arXiv 2408.04619. The idea this page's Run a Transformer tab borrows, at toy scale and encoder-decoder.
(20 min)
Brendan Bycroft: a 3D walk through every matrix multiply of a small GPT (nano-gpt) at true shape, step by step.
(30 min)
2018: the encoder stack alone, pretrained bidirectionally.
2020: the decoder stack scaled; the parallelism this paper unlocked is what made those curves reachable.
2020: loss as a power law in parameters, data and compute, measured on Transformers.
2021: rotary embeddings replace the sinusoidal positional encoding.
2022: exact attention made IO-aware; attacks the memory traffic this architecture created.
2023: pages the KV cache like virtual memory to serve many sequences.
2020: the same encoder applied to image patches.
2023: the main post-Transformer attempt to remove the O(n²) attention core.
2019: the encoder-decoder kept and scaled, every task as text to text.
sequence-model history, attention.
positional encodings, learning-rate schedules.
the ancestor of every model family covered there.
what a 2026 block looks like across 90-odd open models: norms, attention variants, KV cache.
This page is one row of the Papers database; its properties (Paper, Takeaway, Topics, Year) live there.