Attention Is All You Need: the Transformer, with self-attention instead of recurrence and convolution
The original Transformer paper: an encoder-decoder built only from multi-head self-attention and feed-forward layers, 28.4 BLEU on WMT 2014 English-German. We recompute its parameter counts, costs and BLEU claims, then train a tiny Transformer to copy digits.
On this page
- Why this paper is worth reading
- Background: two bottlenecks of recurrent networks
- Method: how the Transformer is put together
- Encoder, decoder and residuals
- Scaled dot-product attention and multiple heads
- Feed-forward, embeddings and positions
- Training details
- What the paper reports
- Machine translation (Table 2)
- Ablations (Table 3)
- Constituency parsing (Table 4)
- Hands-on check: recompute the paper’s numbers
- Hands-on reproduction: a tiny Transformer learns to copy digit strings
- Limits and what came next
- What to take away
- Further reading
- FAQ
“Attention Is All You Need” (Vaswani, Shazeer, Parmar, Uszkoreit, Jones, Gomez, Kaiser and Polosukhin; Google Brain, Google Research and the University of Toronto; arXiv 1706.03762, NeurIPS 2017; called the Transformer paper below) introduced the Transformer: an encoder-decoder built entirely from multi-head self-attention and position-wise feed-forward layers, with no recurrence and no convolution. All positions of a sequence are computed in parallel and any two positions are one step apart. On WMT 2014 English-German the big model reached 28.4 BLEU, more than 2 BLEU above the best earlier result including ensembles; on English-French, Table 2 and the abstract report a single-model 41.8 BLEU after 3.5 days on eight P100 GPUs, at under a quarter of the training cost of the best earlier single model. The same architecture also came close to the best parsing results of the time on English constituency parsing. The paper defines two sizes: base (6 layers, , 65M parameters as printed) and big (6 layers, , 213M as printed).
This page does two things. Checking: we recompute the paper’s parameter counts, training costs, BLEU claims and learning-rate formula. The training costs reproduce exactly (3.3e18 and 2.3e19 FLOPs), but the parameter column cannot be reproduced with one vocabulary (base computes to 63.1M against 65M printed, big to 214.2M against 213M); the English-French score is 41.8 BLEU in Table 2 and the abstract but 41.0 in section 6.1; and 7 of the 18 variants in Table 3 are within 0.3 BLEU of the base model although each was trained only once. Small-scale reproduction: a 235K-parameter Transformer learns to copy digit strings (training lengths 5 to 8, three seeds per configuration), which tests what heads, depth, scaling and position encoding each do. Differences in heads, depth and scaling are lost in the spread between seeds beyond the training lengths; position information is decisive: a model without it copies only 0.5% of the strings exactly, learned position embeddings fall to 16.4% at length 9, and sinusoidal encodings degrade slowly (77.2% at length 9).
Why this paper is worth reading
- It is the common ancestor of almost every large model. The GPT series keeps its decoder, BERT keeps the encoder, T5 keeps the full encoder-decoder, and ViT moves it to images; every model discussed on this site is built from the layer introduced here.
- Its argument does not rest on one BLEU number. Section 4 first names three criteria (computation per layer, how much of it can run in parallel, and the path length between distant positions) and Table 1 compares self-attention, recurrent and convolutional layers on each. Explaining why before showing results is worth copying.
- Its details are specific enough to check. Three tables (complexity, translation scores with costs, ablations) plus the training hyperparameters are enough to recompute; the check below does exactly that.
- It also shows how to read a paper. The parameter column, the two BLEU figures and the “within 0.3” ablation rows are a reminder that even a hugely influential paper has loose ends; ask where each number comes from and whether it was repeated.
- Who did what is in a footnote. Jakob Uszkoreit proposed replacing RNNs with self-attention; Noam Shazeer proposed scaled dot-product attention, multi-head attention and the parameter-free position representation; Ashish Vaswani and Illia Polosukhin designed and implemented the first Transformer models; Niki Parmar tuned countless variants; Llion Jones built the initial codebase, efficient inference and visualizations; Łukasz Kaiser and Aidan Gomez wrote tensor2tensor, which replaced the earlier code and greatly improved the results.
- Related pages on this site. The intuition is in Attention basics, the bottleneck of RNNs in From RNNs to attention, one layer in The Transformer block, the evolution of positions in Positional encoding and the RoFormer walkthrough, and today’s architectures in Modern LLM architecture.
Background: two bottlenecks of recurrent networks
The introduction points out that recurrent models factor computation along the symbol positions: the hidden state at position is a function of the previous hidden state and the input at . This inherently sequential nature rules out parallelism inside a training example, which hurts most for long sequences because memory limits batching across examples. Attention was already part of translation models, since it models dependencies regardless of distance, but “in all but a few cases” it was used together with a recurrent network.
Convolutional models (Extended Neural GPU, ByteNet, ConvS2S) compute representations for all positions in parallel, but the number of operations needed to relate two positions grows with their distance: linearly for ConvS2S and logarithmically for ByteNet. The Transformer makes it constant, at the price of averaging attention-weighted positions, which lowers the effective resolution; the paper counters this with multi-head attention.
Table 1 of the paper puts the three criteria side by side ( is the sequence length, the representation dimension, the convolution kernel width and the neighborhood of restricted self-attention):
| Layer type | Complexity per layer | Sequential ops | Max path length |
|---|---|---|---|
| Self-attention | |||
| Recurrent | |||
| Convolutional | |||
| Self-attention (restricted) |
Two things to notice. First, self-attention costs per layer and a recurrent layer , so “self-attention is faster” holds only when , as the paper says: for the word-piece and byte-pair representations used in translation, is usually smaller than . Once sequences reach tens of thousands of tokens the quadratic term dominates, which is the starting point of FlashAttention and the various efficient attention methods. Second, path length and parallelism matter more than raw complexity: self-attention connects any two positions in one step, while a recurrent network must carry the gradient back over steps (see the experiments in From RNNs to attention).
Method: how the Transformer is put together
The model is still an encoder-decoder: the encoder maps an input symbol sequence to continuous representations , and the decoder generates one symbol at a time from and the symbols already generated (auto-regressive). The figure is a simplified version of the paper’s Figure 1:
The paper gives two configurations that share most hyperparameters:
| base | big | |
|---|---|---|
| Layers N (each of encoder, decoder) | 6 | 6 |
| 512 | 1024 | |
| Feed-forward inner | 2048 | 4096 |
| Heads | 8 | 16 |
| 64 | 64 | |
| Dropout | 0.1 | 0.3 (0.1 for English-French) |
| Training steps | 100K (12 hours) | 300K (3.5 days) |
| Parameters (as printed) | 65M | 213M |
Encoder, decoder and residuals
The encoder is a stack of identical layers with two sub-layers each: multi-head self-attention and a position-wise feed-forward network. Each sub-layer is wrapped in a residual connection followed by layer normalization, so its output is ; all sub-layers and embeddings produce -dimensional outputs. The decoder also has 6 layers and inserts a third sub-layer that attends over the encoder output between those two; its own self-attention is masked so that a position cannot attend to later positions, and together with the output embeddings being offset by one position this guarantees that the prediction at position depends only on known outputs at positions before .
Scaled dot-product attention and multiple heads
Attention compares a query with all keys by dot product, divides by , applies a softmax to get weights and takes the weighted sum of the values:
Footnote 4 of the paper explains the scaling: if the components of and are independent with mean 0 and variance 1, then has mean 0 and variance . Large dot products push the softmax into regions with tiny gradients. Instead of one attention over dimensions, multi-head attention projects queries, keys and values times, runs attention on each projection in parallel and concatenates the results:
The paper uses and , so the total cost is similar to single-head attention with full dimensionality. Attention is used in three ways: encoder-decoder attention (queries from the decoder, keys and values from the encoder output), encoder self-attention, and masked decoder self-attention, where illegal connections are set to inside the softmax.
Feed-forward, embeddings and positions
Each layer’s feed-forward network applies the same two linear maps with a ReLU between them to every position separately: with inner dimension . The two embedding layers and the pre-softmax linear layer share one weight matrix, and the embedding output is multiplied by .
With no recurrence and no convolution, position information has to be injected explicitly. The paper adds fixed sine and cosine functions to the input embeddings:
Each dimension is a sinusoid, with wavelengths forming a geometric progression from to . The authors chose it because they hypothesized it would make it easy for the model to attend by relative position: for any fixed offset , is a linear function of . They also tried learned positional embeddings and found nearly identical results (row (E) of Table 3), and kept the sinusoids because they “may allow the model to extrapolate to sequence lengths longer than the ones encountered during training”. Both claims can be measured, below.
Training details
- Data: WMT 2014 English-German, about 4.5 million sentence pairs, byte-pair encoding with a shared vocabulary of about 37,000 tokens; English-French, 36 million sentences with a 32,000 word-piece vocabulary. Batches are grouped by approximate length, with about 25,000 source and 25,000 target tokens each.
- Hardware and schedule: one machine with 8 NVIDIA P100 GPUs. The base model takes about 0.4 s per step and trains for 100,000 steps, about 12 hours; the big model takes 1.0 s per step and trains for 300,000 steps, about 3.5 days.
- Optimizer: Adam with , , ; the learning rate rises linearly and then decays with the inverse square root of the step:
- Regularization: residual dropout (on each sub-layer output and on the sum of embeddings and positional encodings); label smoothing , which the paper says hurts perplexity but improves accuracy and BLEU.
- Inference: the base model averages the last 5 checkpoints (written 10 minutes apart) and the big model the last 20; beam search with beam size 4 and length penalty ; maximum output length is the input length plus 50.
What the paper reports
Machine translation (Table 2)
The table below is the paper’s Table 2 (BLEU on newstest2014; training cost is an estimate of floating-point operations, and the two Transformer rows span both columns with one number):
| Model | EN-DE BLEU | EN-FR BLEU | EN-DE cost | EN-FR cost |
|---|---|---|---|---|
| ByteNet | 23.75 | |||
| Deep-Att + PosUnk | 39.2 | 1.0×10²⁰ | ||
| GNMT + RL | 24.6 | 39.92 | 2.3×10¹⁹ | 1.4×10²⁰ |
| ConvS2S | 25.16 | 40.46 | 9.6×10¹⁸ | 1.5×10²⁰ |
| MoE | 26.03 | 40.56 | 2.0×10¹⁹ | 1.2×10²⁰ |
| Deep-Att + PosUnk ensemble | 40.4 | 8.0×10²⁰ | ||
| GNMT + RL ensemble | 26.30 | 41.16 | 1.8×10²⁰ | 1.1×10²¹ |
| ConvS2S ensemble | 26.36 | 41.29 | 7.7×10¹⁹ | 1.2×10²¹ |
| Transformer (base) | 27.3 | 38.1 | 3.3×10¹⁸ | 3.3×10¹⁸ |
| Transformer (big) | 28.4 | 41.8 | 2.3×10¹⁹ | 2.3×10¹⁹ |
The paper’s conclusions: on English-German the big model reaches 28.4, more than 2.0 BLEU above the best earlier results including ensembles, and even the base model beats every published model and ensemble at a fraction of the cost; on English-French the big model is a new single-model state of the art at less than a quarter of the training cost of the previous best model. Cost is estimated as training time × number of GPUs × sustained single-precision capacity, taken as 2.8, 3.7, 6.0 and 9.5 TFLOPS for K80, K40, M40 and P100.
Ablations (Table 3)
The authors vary the base model one factor at a time and report perplexity (per word piece, not comparable with per-word perplexity) and BLEU on the English-German development set newstest2013, without checkpoint averaging. The table lists the main rows (unlisted hyperparameters equal the base model; each row was trained once):
| Variant | PPL | BLEU | Params (M, printed) |
|---|---|---|---|
| base | 4.92 | 25.8 | 65 |
| (A) heads h=1 () | 5.29 | 24.9 | |
| (A) h=4 (128) | 5.00 | 25.5 | |
| (A) h=16 (32) | 4.91 | 25.8 | |
| (A) h=32 (16) | 5.01 | 25.4 | |
| (B) | 5.16 | 25.1 | 58 |
| (B) | 5.01 | 25.4 | 60 |
| (C) layers N=2 | 6.11 | 23.7 | 36 |
| (C) N=4 | 5.19 | 25.3 | 50 |
| (C) N=8 | 4.88 | 25.5 | 80 |
| (C) | 5.75 | 24.5 | 28 |
| (C) | 4.66 | 26.0 | 168 |
| (C) | 5.12 | 25.4 | 53 |
| (C) | 4.75 | 26.2 | 90 |
| (D) | 5.77 | 24.6 | |
| (D) | 4.95 | 25.5 | |
| (D) | 4.67 | 25.3 | |
| (D) | 5.47 | 25.7 | |
| (E) learned position embedding | 4.92 | 25.7 | |
| big | 4.33 | 26.4 | 213 |
The paper’s reading: single-head attention is 0.9 BLEU worse than the best setting and quality also drops with too many heads; reducing hurts, which suggests that judging compatibility is not easy and a more sophisticated function than the dot product may help; bigger models are better and dropout helps against over-fitting; learned position embeddings are nearly identical to sinusoids. The two label-smoothing rows support the paper’s remark: has the lowest perplexity (4.67) and yet a lower BLEU than the 0.2 row (25.3 against 25.7).
Constituency parsing (Table 4)
To see whether the Transformer generalizes, the authors trained a 4-layer model with on English constituency parsing: about 40K WSJ sentences give an F1 of 91.3 on WSJ section 23, and the semi-supervised setting with about 17M high-confidence sentences gives 92.7. Apart from a few task-specific choices (dropout, learning rates, beam size), everything is carried over from the English-German base model. The paper says the results beat all previously reported models except the Recurrent Neural Network Grammar.
Hands-on check: recompute the paper’s numbers
The script trains nothing: it types the paper’s tables into code, recomputes them from the paper’s formulas and cross-checks the parameter count against PyTorch’s nn.Transformer. There are six parts, in the order of the output: the parameter counts of Table 3, the training costs of Table 2, the BLEU claims, the learning-rate formula, the scaling (Monte Carlo) and the linearity of the sinusoidal encoding. Environment: Python 3.14.3, NumPy, PyTorch 2.10.0, CPU.
Full code (about 163 lines)
"""Recheck the Transformer paper: parameters, training cost, BLEU,
learning rate and two mathematical properties"""
import math
import numpy as np
import torch
V = 37000 # paper: shared vocabulary of about 37000 tokens
def pad(s, width):
"""pad to a display width (CJK counts two)"""
return s + " " * (width - sum(2 if ord(c) > 0x2e80 else 1 for c in s))
def mha(dm, h, dk, dv):
"""parameters of one multi-head attention"""
return 2 * dm * h * dk + 2 * dm * h * dv + 2 * h * dk + h * dv + dm
def layers(dm, dff, h, dk, dv, n):
"""n encoder and n decoder layers"""
ffn = 2 * dm * dff + dff + dm
enc = mha(dm, h, dk, dv) + ffn + 2 * 2 * dm
dec = 2 * mha(dm, h, dk, dv) + ffn + 3 * 2 * dm
return n * (enc + dec)
# Table 3 rows: name -> (N, d_model, d_ff, h, d_k, d_v, printed M)
ROWS = {
"base": (6, 512, 2048, 8, 64, 64, 65),
"(A) h=1": (6, 512, 2048, 1, 512, 512, None),
"(A) h=32": (6, 512, 2048, 32, 16, 16, None),
"(B) d_k=16": (6, 512, 2048, 8, 16, 64, 58),
"(B) d_k=32": (6, 512, 2048, 8, 32, 64, 60),
"(C) N=2": (2, 512, 2048, 8, 64, 64, 36),
"(C) N=4": (4, 512, 2048, 8, 64, 64, 50),
"(C) N=8": (8, 512, 2048, 8, 64, 64, 80),
"(C) d_model=256": (6, 256, 2048, 8, 32, 32, 28),
"(C) d_model=1024": (6, 1024, 2048, 8, 128, 128, 168),
"(C) d_ff=1024": (6, 512, 1024, 8, 64, 64, 53),
"(C) d_ff=4096": (6, 512, 4096, 8, 64, 64, 90),
"big": (6, 1024, 4096, 16, 64, 64, 213),
}
print("1. Parameters in Table 3 (vocabulary 37000, tied embeddings)")
print(" " + pad("row", 18) + pad("formula", 10) + pad("paper", 8)
+ pad("gap", 7) + "implied vocabulary")
implied = {}
for name, (n, dm, dff, h, dk, dv, printed) in ROWS.items():
body = layers(dm, dff, h, dk, dv, n)
total = (body + V * dm) / 1e6
if printed is None:
print(" " + pad(name, 18) + f"{total:.1f}M")
continue
implied[name] = (printed * 1e6 - body) / dm
print(" " + pad(name, 18) + pad(f"{total:.1f}M", 10)
+ pad(f"{printed}M", 8) + pad(f"{total - printed:+.1f}", 7)
+ f"{implied[name]:,.0f}")
rest = [v for k, v in implied.items() if k != "big"]
print(f" implied vocabulary without big: "
f"{min(rest):,.0f} - {max(rest):,.0f}")
# cross-check the formula with nn.Transformer
# (it adds a final LayerNorm to the encoder and decoder)
for name in ("base", "big"):
n, dm, dff, h, dk, dv, _ = ROWS[name]
net = torch.nn.Transformer(dm, h, n, n, dff, dropout=0.0,
batch_first=True)
got = sum(p.numel() for p in net.parameters())
print(f" nn.Transformer minus formula ({name}): "
f"{got - layers(dm, dff, h, dk, dv, n)}")
print("\n2. Training cost (FLOPs = time x GPUs x sustained FLOPS per GPU)")
P100 = 9.5e12 # paper footnote: P100 = 9.5 TFLOPS
for name, steps, sec, hours, printed in (("base", 100_000, 0.4, 12, 3.3e18),
("big", 300_000, 1.0, 84, 2.3e19)):
run = steps * sec / 3600
print(f" {name}: {steps:,} steps x {sec} s = {run:.1f} h; "
f"paper says {hours} h -> "
f"{hours * 3600 * 8 * P100:.2e} (paper {printed:.1e})")
RIVAL = {"Deep-Att": 1.0e20, "GNMT+RL": 1.4e20, "ConvS2S": 1.5e20,
"MoE": 1.2e20}
print(" EN-FR: cost of big over each single-model rival: "
+ ", ".join(f"{k} {2.3e19 / v:.3f}" for k, v in RIVAL.items()))
print(" EN-DE: cost of base over the cheapest rival, ConvS2S: "
f"{3.3e18 / 9.6e18:.2f}")
print("\n3. The BLEU claims")
print(" EN-DE: big beats the best earlier ensemble by"
f" {28.4 - 26.36:.2f} BLEU")
FR = {"Deep-Att": 39.2, "GNMT+RL": 39.92, "ConvS2S": 40.46, "MoE": 40.56}
best = max(FR, key=FR.get)
print(" EN-FR: big is 41.8 in Table 2, 41.0 in the text; "
f"best earlier single model: {best} ({FR[best]})")
print(f" margin over it: {41.8 - FR[best]:.2f} / "
f"{41.0 - FR[best]:.2f}")
print(" EN-FR: base's 38.1 is below the lowest rival in the column (39.2): "
f"{38.1 < 39.2}")
DEV = {"h=1": 24.9, "h=4": 25.5, "h=16": 25.8, "h=32": 25.4,
"d_k=16": 25.1, "d_k=32": 25.4, "N=2": 23.7, "N=4": 25.3, "N=8": 25.5,
"d_model=256": 24.5, "d_model=1024": 26.0, "d_ff=1024": 25.4,
"d_ff=4096": 26.2, "P_drop=0.0": 24.6, "P_drop=0.2": 25.5,
"eps_ls=0.0": 25.3, "eps_ls=0.2": 25.7, "learned PE": 25.7}
close = [k for k, v in DEV.items() if round(abs(v - 25.8), 1) <= 0.3]
print(f" Table 3 rows within 0.3 dev BLEU of base (25.8): "
f"{len(close)} of {len(DEV)}")
print(" " + ", ".join(close))
print(" single head minus base: "
f"{DEV['h=1'] - 25.8:+.1f}; learned PE minus base: "
f"{DEV['learned PE'] - 25.8:+.1f}")
# Table 4: constituency parsing, WSJ section 23 F1
T4 = (("Vinyals 2014", "WSJ only", 88.3), ("Petrov 2006", "WSJ only", 90.4),
("Zhu 2013", "WSJ only", 90.4), ("Dyer 2016", "WSJ only", 91.7),
("Zhu 2013", "semi", 91.3), ("Huang 2009", "semi", 91.3),
("McClosky 2006", "semi", 92.1), ("Vinyals 2014", "semi", 92.1),
("Luong 2015", "multi-task", 93.0), ("Dyer 2016", "generative", 93.3))
above = [f"{n} ({s}) {v}" for n, s, v in T4 if v > 92.7]
print(" Table 4 rows above the semi-supervised Transformer (92.7): "
+ "; ".join(above))
same = [f"{n} {v}" for n, s, v in T4 if s == "WSJ only" and v > 91.3]
print(" WSJ-only rows above 91.3: "
+ "; ".join(same))
print("\n4. Learning rate d_model^-0.5 * min(step^-0.5, step*4000^-1.5)")
for name, dm, steps in (("base", 512, 100_000), ("big", 1024, 300_000)):
print(f" {name}: peak (step 4000) "
f"{dm ** -0.5 * 4000 ** -0.5:.2e}, step {steps:,} "
f" {dm ** -0.5 * steps ** -0.5:.2e}")
print("\n5. Why divide by sqrt(d_k): q, k i.i.d., mean 0, variance 1")
rng = np.random.default_rng(0)
print(" " + pad("d_k", 6) + pad("std(q·k)", 10) + pad("sqrt(d_k)", 11)
+ pad("max weight: raw", 20)
+ "max weight: scaled")
for dk in (1, 4, 16, 64, 256, 1024):
q = rng.standard_normal((500, dk))
k = rng.standard_normal((500, 64, dk))
s = np.einsum("bd,bnd->bn", q, k)
def top(x):
e = np.exp(x - x.max(1, keepdims=True))
return (e / e.sum(1, keepdims=True)).max(1).mean()
print(" " + pad(str(dk), 6) + pad(f"{s.std():.2f}", 10)
+ pad(f"{math.sqrt(dk):.2f}", 11)
+ pad(f"{top(s):.3f}", 20) + f"{top(s / math.sqrt(dk)):.3f}")
print("\n6. Sinusoidal positional encoding (d_model=512)")
w = 1 / 10000 ** (2 * np.arange(256) / 512)
worst = 0.0
for pos in range(0, 2000, 7):
for off in (1, 5, 50, 300):
a, b = pos * w, (pos + off) * w
c, s = np.cos(off * w), np.sin(off * w)
worst = max(worst,
np.abs(np.sin(a) * c + np.cos(a) * s - np.sin(b)).max(),
np.abs(np.cos(a) * c - np.sin(a) * s - np.cos(b)).max())
print(" PE(pos+k) is linear in PE(pos) (a rotation per pair), max error: "
f"{worst:.1e}")
print(f" wavelengths run from {2 * math.pi:.2f} to "
f"{2 * math.pi / w[-1]:,.0f}; the paper's limit "
f"{2 * math.pi * 10000:,.0f}")
Output:
1. Parameters in Table 3 (vocabulary 37000, tied embeddings)
row formula paper gap implied vocabulary
base 63.1M 65M -1.9 40,745
(A) h=1 63.1M
(A) h=32 63.1M
(B) d_k=16 56.0M 58M -2.0 40,924
(B) d_k=32 58.4M 60M -1.6 40,214
(C) N=2 33.7M 36M -2.3 41,576
(C) N=4 48.4M 50M -1.6 40,184
(C) N=8 77.8M 80M -2.2 41,306
(C) d_model=256 26.8M 28M -1.2 41,551
(C) d_model=1024 163.9M 168M -4.1 41,014
(C) d_ff=1024 50.5M 53M -2.5 41,908
(C) d_ff=4096 88.3M 90M -1.7 40,373
big 214.2M 213M +1.2 35,784
implied vocabulary without big: 40,184 - 41,908
nn.Transformer minus formula (base): 2048
nn.Transformer minus formula (big): 4096
2. Training cost (FLOPs = time x GPUs x sustained FLOPS per GPU)
base: 100,000 steps x 0.4 s = 11.1 h; paper says 12 h -> 3.28e+18 (paper 3.3e+18)
big: 300,000 steps x 1.0 s = 83.3 h; paper says 84 h -> 2.30e+19 (paper 2.3e+19)
EN-FR: cost of big over each single-model rival: Deep-Att 0.230, GNMT+RL 0.164, ConvS2S 0.153, MoE 0.192
EN-DE: cost of base over the cheapest rival, ConvS2S: 0.34
3. The BLEU claims
EN-DE: big beats the best earlier ensemble by 2.04 BLEU
EN-FR: big is 41.8 in Table 2, 41.0 in the text; best earlier single model: MoE (40.56)
margin over it: 1.24 / 0.44
EN-FR: base's 38.1 is below the lowest rival in the column (39.2): True
Table 3 rows within 0.3 dev BLEU of base (25.8): 7 of 18
h=4, h=16, N=8, d_model=1024, P_drop=0.2, eps_ls=0.2, learned PE
single head minus base: -0.9; learned PE minus base: -0.1
Table 4 rows above the semi-supervised Transformer (92.7): Luong 2015 (multi-task) 93.0; Dyer 2016 (generative) 93.3
WSJ-only rows above 91.3: Dyer 2016 91.7
4. Learning rate d_model^-0.5 * min(step^-0.5, step*4000^-1.5)
base: peak (step 4000) 6.99e-04, step 100,000 1.40e-04
big: peak (step 4000) 4.94e-04, step 300,000 5.71e-05
5. Why divide by sqrt(d_k): q, k i.i.d., mean 0, variance 1
d_k std(q·k) sqrt(d_k) max weight: raw max weight: scaled
1 1.01 1.00 0.101 0.101
4 2.03 2.00 0.280 0.109
16 4.01 4.00 0.562 0.103
64 7.98 8.00 0.798 0.108
256 16.09 16.00 0.902 0.112
1024 32.06 32.00 0.942 0.107
6. Sinusoidal positional encoding (d_model=512)
PE(pos+k) is linear in PE(pos) (a rotation per pair), max error: 2.6e-13
wavelengths run from 6.28 to 60,611; the paper's limit 62,832
Reading the numbers.
- The parameter column does not match one vocabulary. With the paper’s configuration (embeddings shared with the output layer, vocabulary 37,000, biases and LayerNorms included) base computes to 63.1M against 65M printed; every (B) and (C) row is 1.2M to 4.1M below the printed value (the largest, N=2, is 2.3M or about 6% off); only big goes the other way, 214.2M against 213M. Taking the printed counts as given and solving for each row’s implied vocabulary gives 40,184 to 41,908 for every row except big, which implies only 35,784. So the column was not produced with a single vocabulary; I did not find the reason, possibly different vocabularies or counting conventions per row. The gap is at most about 7% of the model size and changes no conclusion, but the column is approximate. The formula itself is fine: it differs from
nn.Transformeronly by the extra LayerNorm that module puts at the end of the encoder and of the decoder (2048 parameters for base, 4096 for big). - The training costs reproduce exactly, with one rounding. 12 hours × 8 P100 × 9.5 TFLOPS is 3.28e18 (printed 3.3e18) and 84 hours gives 2.30e19 (printed 2.3e19). But 100,000 steps × 0.4 s is only 11.1 hours and 300,000 steps × 1.0 s is 83.3 hours: the table uses the rounded 12 and 84 hours of the text, which overstates the base cost by about 8% and the big cost by about 1%. “Less than a quarter of the cost on English-French” holds: big’s cost is 0.192 of MoE (the best earlier single model), 0.230 of Deep-Att, 0.164 of GNMT+RL and 0.153 of ConvS2S; on English-German the base model costs 0.34 of the cheapest rival, ConvS2S.
- 41.8 or 41.0 on English-French. Table 2 and the abstract say 41.8; the text of section 6.1 says 41.0. The best earlier single model is MoE (40.56), so the big model’s margin is 1.24 or 0.44 depending on where you look (this post reads arXiv v7, August 2023). English-German has no such problem: 28.4 beats the best earlier ensemble (26.36) by 2.04, so “more than 2 BLEU” just holds.
- The base model is below every rival on English-French. Its 38.1 is lower than the lowest rival in that column (39.2). The sentence “even our base model surpasses all previously published models and ensembles” holds for English-German only.
- Table 3 cannot resolve small differences. 7 of the 18 variants are within 0.3 BLEU of the base model (25.8): h=4, h=16, N=8, , , and learned positions; and the paper gives one number per variant, with no variance from repeated runs, so differences within 0.3 cannot be interpreted. Single-head being 0.9 below base is one of the few differences above that size, and learned positions being 0.1 below base is indeed “nearly identical”.
- “Except the RNN grammar” in Table 4 is loose. Two more rows in the table are above the Transformer’s semi-supervised 92.7: Luong et al.’s multi-task model (93.0) and Dyer et al.’s generative model (93.3); in the WSJ-only setting only the discriminative RNN grammar of Dyer et al. (91.7) is above 91.3. The rows use different training settings and are not strictly comparable.
- The learning-rate formula. The peak is at step 4000: 6.99e-4 for base and 4.94e-4 for big (); at the end of training base has decayed to 1.40e-4.
- The effect of scaling can be seen directly. The standard deviation of is almost exactly (7.98 measured against 8 at ). The largest attention weight over 64 keys rises from 0.101 at to 0.942 at without scaling (nearly one-hot, tiny gradients) and stays between 0.101 and 0.112 with it.
- The linearity of the sinusoidal encoding holds. is a linear function of (each sin-cos pair is a rotation), with a maximum error of 2.6e-13; wavelengths run from 6.28 to 60,611, and the paper’s upper bound is a limit that the last pair for does not reach.
Hands-on reproduction: a tiny Transformer learns to copy digit strings
Table 3 of the paper ablates heads, key size, position embeddings and more, but trains each variant once, and a WMT run takes days. Here the task shrinks to something a laptop finishes in a dozen minutes: copying digit strings. The input is a random string of digits 0 to 9 and the target is the same string. The model keeps the paper’s structure (encoder-decoder, post-norm, ReLU feed-forward, scaled dot-product attention, multiple heads), only much smaller. It asks three small questions: how much does the result change with the number of heads or layers? What happens without the scaling? What if the sinusoidal encoding is replaced by learned embeddings, or removed altogether? Training sees only lengths 5 to 8; testing uses lengths 6 and 8 (inside the training range) and 9, 10 and 12 (beyond it), so the run doubles as a length-extrapolation experiment.
| Paper | Here | |
|---|---|---|
| Task | WMT 2014 English-German translation | Copy random strings of digits 0 to 9 |
| Model | base: 6 layers, , , 65M parameters | 2 encoder and 2 decoder layers, , , , 235K parameters |
| Training | 100,000 steps, about 25,000 source tokens per batch | 2000 steps, 64 strings per batch, lengths 5 to 8 |
| Optimizer | Adam, 4000 warmup steps, label smoothing 0.1 | The same, 400 warmup steps, learning-rate factor 0.5 (see below) |
| Repeats | One run per variant | Three seeds per configuration; mean and min to max |
| Metric | BLEU | 1000 fixed test strings; a string counts only if copied exactly (greedy decoding) |
The learning rate was tuned once. Applying the paper’s formula unchanged to such a small model is unstable. In preliminary runs (seed 0, 2500 steps, the same 1000 test strings, with a script that is not part of this page) I tried factors 0.5, 1.0 and 2.0: at 2.0 the model with learned position embeddings diverged (0% at every length) and the baseline had not even learned the training lengths properly (89.4% at length 8); at 1.0 the baseline scored 60.7% at length 9, against 85.1% at 0.5. I used 0.5 for every configuration. The choice used the test strings, so the baseline’s absolute numbers are somewhat optimistic; the ordering (learned embeddings collapse at length 9, sinusoidal ones degrade slowly) was the same at factors 0.5 and 1.0, but the absolute numbers moved by tens of points, so read the table below as qualitative.
Environment: Apple M2 Max, CPU with three threads, Python 3.14.3, PyTorch 2.10.0, NumPy 2.4.2. The seeds (0, 1, 2) and the test strings are fixed; another machine or PyTorch version may change individual numbers slightly.
Full code (about 180 lines)
"""Tiny Transformer ablations on copying digit strings:
heads, depth, positional encoding and scaling"""
import math
import sys
import time
import numpy as np
import torch
import torch.nn.functional as F
from torch import nn
torch.set_num_threads(3)
SEEDS = int(sys.argv[1]) if len(sys.argv) > 1 else 3
STEPS = int(sys.argv[2]) if len(sys.argv) > 2 else 2000
DM, DFF, BATCH, WARM, LR_SCALE = 64, 256, 64, 400, 0.5
BOS, TRAIN_LEN = 10, (4, 8) # digits 0-9, BOS is 10
TEST_LEN = (6, 8, 9, 10, 12) # last three: longer than any training string
class MHA(nn.Module):
def __init__(self, heads, scale):
super().__init__()
self.h, self.scale = heads, scale
self.qkv = nn.ModuleList(nn.Linear(DM, DM) for _ in range(3))
self.out = nn.Linear(DM, DM)
def forward(self, x, mem, causal=False):
b, n, _ = x.shape
q, k, v = (f(t).view(b, -1, self.h, DM // self.h).transpose(1, 2)
for f, t in zip(self.qkv, (x, mem, mem)))
s = (1 / math.sqrt(DM // self.h)) if self.scale else 1.0
y = F.scaled_dot_product_attention(q, k, v, is_causal=causal, scale=s)
return self.out(y.transpose(1, 2).reshape(b, n, DM))
class Layer(nn.Module):
"""post-norm encoder or decoder layer, as in the paper"""
def __init__(self, heads, scale, decoder):
super().__init__()
self.self_attn, self.dec = MHA(heads, scale), decoder
self.cross = MHA(heads, scale) if decoder else None
self.ffn = nn.Sequential(nn.Linear(DM, DFF), nn.ReLU(),
nn.Linear(DFF, DM))
self.norms = nn.ModuleList(nn.LayerNorm(DM) for _ in range(3))
self.drop = nn.Dropout(0.1)
def forward(self, x, mem=None):
x = self.norms[0](x + self.drop(self.self_attn(x, x, self.dec)))
if self.dec:
x = self.norms[1](x + self.drop(self.cross(x, mem)))
return self.norms[2](x + self.drop(self.ffn(x)))
class Model(nn.Module):
def __init__(self, layers=2, heads=4, pos="sin", scale=True):
super().__init__()
self.pos = pos
self.emb = nn.Embedding(11, DM)
nn.init.normal_(self.emb.weight, std=DM ** -0.5)
self.enc = nn.ModuleList(Layer(heads, scale, False)
for _ in range(layers))
self.dec = nn.ModuleList(Layer(heads, scale, True)
for _ in range(layers))
self.out = nn.Linear(DM, 10)
i = torch.arange(0, DM, 2)
ang = torch.arange(64)[:, None] / 10000 ** (i / DM)
table = torch.zeros(64, DM)
table[:, 0::2], table[:, 1::2] = ang.sin(), ang.cos()
if pos == "learned":
self.table = nn.Parameter(torch.randn(64, DM))
else:
self.register_buffer("table", table)
self.drop = nn.Dropout(0.1)
def embed(self, ids):
x = self.emb(ids) * math.sqrt(DM)
if self.pos != "none":
x = x + self.table[:ids.shape[1]]
return self.drop(x)
def forward(self, src, tgt_in):
mem = self.embed(src)
for layer in self.enc:
mem = layer(mem)
y = self.embed(tgt_in)
for layer in self.dec:
y = layer(y, mem)
return self.out(y)
@torch.no_grad()
def generate(self, src):
ys = torch.full((src.shape[0], 1), BOS)
for _ in range(src.shape[1]):
nxt = self(src, ys)[:, -1].argmax(-1, keepdim=True)
ys = torch.cat([ys, nxt], 1)
return ys[:, 1:]
def batch(rng, n):
src = torch.from_numpy(rng.integers(0, 10, (BATCH, n)))
return src, torch.cat([torch.full((BATCH, 1), BOS), src[:, :-1]], 1), src
def run(seed, **cfg):
torch.manual_seed(seed)
rng = np.random.default_rng(1000 + seed)
model = Model(**cfg)
opt = torch.optim.Adam(model.parameters(), lr=1.0, betas=(0.9, 0.98),
eps=1e-9)
sched = torch.optim.lr_scheduler.LambdaLR(
opt, lambda s: LR_SCALE * DM ** -0.5 * min(
(s + 1) ** -0.5, (s + 1) * WARM ** -1.5))
model.train()
for _ in range(STEPS):
src, tgt_in, tgt = batch(rng, int(rng.integers(*TRAIN_LEN)) + 1)
loss = F.cross_entropy(model(src, tgt_in).reshape(-1, 10),
tgt.reshape(-1), label_smoothing=0.1)
opt.zero_grad()
loss.backward()
opt.step()
sched.step()
model.eval()
acc, pre, bag = {}, {}, {}
for n in TEST_LEN:
g = np.random.default_rng(777 + n) # fixed test set shared by all runs
src = torch.from_numpy(g.integers(0, 10, (1000, n)))
out = model.generate(src)
acc[n] = 100 * (out == src).all(1).float().mean()
pre[n] = 100 * (out[:, :8] == src[:, :8]).all(1).float().mean()
same = out.sort(1).values == src.sort(1).values
bag[n] = 100 * same.all(1).float().mean()
return acc, pre, bag
CONFIGS = (("base (N=2, h=4)", {}),
("h=1", dict(heads=1)), ("h=2", dict(heads=2)),
("h=8", dict(heads=8)), ("h=16", dict(heads=16)),
("N=1", dict(layers=1)),
("no 1/sqrt(d_k)", dict(scale=False)),
("learned position embedding", dict(pos="learned")),
("no position information", dict(pos="none")))
def pad(s, width):
"""pad to a display width (CJK counts two)"""
return s + " " * (width - sum(2 if ord(c) > 0x2e80 else 1 for c in s))
lo, hi = TRAIN_LEN[0] + 1, TRAIN_LEN[1]
print(f"Task: copy digit strings; training lengths {lo} to {hi}, "
f"{STEPS} steps, batch {BATCH}")
print(f"d_model={DM}, d_ff={DFF}, {SEEDS} seeds")
print(f"lr = {LR_SCALE} x the paper's formula (warmup {WARM} steps), peak "
f"{LR_SCALE * DM ** -0.5 * WARM ** -0.5:.4f}")
print("Accuracy = share of strings copied exactly (%, 1000 strings)")
print("In brackets: min to max over seeds")
print("\n" + pad("configuration", 30) + pad("params", 9)
+ "".join(pad(f"length {n}", 16) for n in TEST_LEN))
start = time.time()
done = {}
for name, cfg in CONFIGS:
runs = done[name] = [run(s, **cfg) for s in range(SEEDS)]
params = sum(p.numel() for p in Model(**cfg).parameters())
cells = []
for n in TEST_LEN:
v = [float(r[0][n]) for r in runs]
cells.append(pad(f"{np.mean(v):5.1f} ({min(v):.0f}-{max(v):.0f})", 16))
print(pad(name, 30) + pad(f"{params / 1e3:.1f}K", 9) + "".join(cells),
flush=True)
names = [c[0] for c in CONFIGS]
print("\nDiagnostic 1: share with the first 8 digits right (%, mean)")
for name in (names[0], names[7]):
vals = [np.mean([float(r[1][n]) for r in done[name]]) for n in (9, 10, 12)]
print(f"{name}: length 9 = {vals[0]:.1f}, 10 = {vals[1]:.1f}, "
f"12 = {vals[2]:.1f}")
print("Diagnostic 2: no position info; same digits, any order (%)")
got = [np.mean([float(r[2][n]) for r in done[names[8]]]) for n in (6, 8)]
print(f"lengths 6 and 8: {got[0]:.1f}, {got[1]:.1f}")
print(f"\ntotal time {(time.time() - start) / 60:.0f} minutes")
Output (about 12 minutes):
Task: copy digit strings; training lengths 5 to 8, 2000 steps, batch 64
d_model=64, d_ff=256, 3 seeds
lr = 0.5 x the paper's formula (warmup 400 steps), peak 0.0031
Accuracy = share of strings copied exactly (%, 1000 strings)
In brackets: min to max over seeds
configuration params length 6 length 8 length 9 length 10 length 12
base (N=2, h=4) 235.1K 100.0 (100-100) 100.0 (100-100) 77.2 (64-96) 44.2 (21-75) 1.0 (0-2)
h=1 235.1K 100.0 (100-100) 100.0 (100-100) 72.5 (33-97) 37.5 (7-54) 0.5 (0-1)
h=2 235.1K 100.0 (100-100) 100.0 (100-100) 71.0 (62-84) 27.8 (18-39) 0.5 (0-1)
h=8 235.1K 100.0 (100-100) 100.0 (100-100) 78.9 (76-84) 36.7 (33-41) 0.3 (0-0)
h=16 235.1K 100.0 (100-100) 100.0 (100-100) 72.8 (70-74) 21.8 (20-25) 0.2 (0-0)
N=1 118.2K 100.0 (100-100) 100.0 (100-100) 63.2 (53-83) 24.3 (16-40) 0.4 (0-1)
no 1/sqrt(d_k) 235.1K 100.0 (100-100) 100.0 (100-100) 73.6 (51-94) 33.5 (17-43) 0.9 (0-2)
learned position embedding 239.2K 100.0 (100-100) 100.0 (100-100) 16.4 (16-17) 3.3 (3-5) 0.2 (0-0)
no position information 235.1K 0.5 (0-0) 0.0 (0-0) 0.0 (0-0) 0.0 (0-0) 0.0 (0-0)
Diagnostic 1: share with the first 8 digits right (%, mean)
base (N=2, h=4): length 9 = 77.2, 10 = 71.4, 12 = 68.1
learned position embedding: length 9 = 99.2, 10 = 99.4, 12 = 98.7
Diagnostic 2: no position info; same digits, any order (%)
lengths 6 and 8: 99.6, 99.9
total time 12 minutes
Reading the numbers.
- Position information is decisive. Without it, the share of exactly copied strings is only 0.5% at length 6, inside the training range, while the other eight configurations score 100% at lengths 6 and 8. The model’s digits are almost always right (at lengths 6 and 8, 99.6% and 99.9% of the outputs contain the same digits as the source, ignoring order) but their order is scrambled: with no position information, the decoder’s cross-attention has no way to “look at the i-th position”. That is the literal meaning of the paper’s statement that position information must be injected.
- Heads, depth and scaling cannot be told apart here. Inside the training lengths every variant scores 100%; at lengths 9 and 10 the min-to-max range of each of the six variants overlaps the baseline’s range (length 9: baseline 64 to 96, N=1 53 to 83, no scaling 51 to 94; length 10: baseline 21 to 75, N=1 16 to 40, no scaling 17 to 43). Three seeds cannot show that the baseline is better. Here the default is (64 with a single head, the same as the paper’s base model) and there are at most 12 keys; at this scale dropping the scaling does no visible harm, which does not show that it is harmless at the paper’s scale (in the Monte Carlo above, at the largest weight over 64 keys is 0.798 without scaling and 0.108 with it). In the paper’s Table 3 a single head is 0.9 BLEU below the base model; nothing like that shows up here, but the task and the scale are entirely different, so neither result confirms or refutes the other.
- Learned position embeddings fail cleanly: exactly at the positions that were never trained. At length 9 only 16.4% of the strings are copied exactly (16 to 17 over the three seeds), yet 99.2% have the first 8 digits right (99.4% and 98.7% at lengths 10 and 12). The 8 trained positions work perfectly; the embedding of the 9th position still holds its random initial value and the model knows nothing about it. One reason the paper gives for choosing sinusoids is that they “may allow the model to extrapolate to sequence lengths longer than the ones encountered during training” (section 3.5).
- Sinusoidal encodings do extrapolate a little, but not reliably. They reach 77.2% at length 9 (64 to 96 over seeds), 44.2% at length 10 and only 1.0% at length 12. Their failures are not confined to the new positions either: at length 9 the share with the first 8 digits right is also 77.2%, the same as the exact-copy share, so a failing string is wrong even at the trained positions and the whole model becomes unstable. The paper’s guess was half right: some extrapolation, nothing reliable. Relative position encodings (see Positional encoding and the RoFormer walkthrough) and context-extension methods (see the YaRN walkthrough) are what later treated this as a problem in its own right.
- The sample is small. Three seeds and 1000 test strings (one string is 0.1 percentage points), with large spread between seeds (the baseline at length 9 ranges from 64 to 96), so do not interpret differences under ten percentage points; at length 12 every configuration is near 0 and carries no information.
Limits and what came next
- Quadratic attention cost. The in Table 1 becomes the bottleneck for long sequences, and the paper’s own conclusion plans to study local, restricted attention; later came exact algorithms such as FlashAttention and the sparse and linear attention families (see Efficient attention), plus extrapolation methods for long contexts such as YaRN and the warning of Lost in the Middle that a longer context does not mean the model uses it.
- Positional encoding. Sinusoidal encodings extrapolate only a little beyond the training length (see the experiment above); the mainstream today is RoPE, explained in Positional encoding.
- Post-norm. The paper uses , which needs learning-rate warmup to train deep stacks; GPT-2 moved normalization to the sub-layer input (pre-norm) and LLaMA uses a pre-norm RMSNorm (see the LLaMA walkthrough).
- The cache cost of many heads. At inference every head’s keys and values must be cached; GQA lets several query heads share a key-value head to shrink the KV cache (see KV cache).
- Narrow validation, no variance. The paper validates on translation and parsing only, reports each number from one training run and gives no variance; the scale is also far below today’s. The scaling laws papers later answered how scale affects results systematically.
- Encoder-decoder is no longer the default. Generative LLMs are mostly decoder-only; understanding tasks use encoders (see BERT); T5 keeps the full structure.
What to take away
- One step apart, computed in parallel. Self-attention connects any two positions in one step and computes all positions of a layer at once, at the price of an cost; it is cheaper than recurrence when .
- Attention + feed-forward + residuals and normalization, stacked into a regular structure. , and in the paper are the starting point of all later variants.
- Scaling, multiple heads and positional encoding each have a clear reason: dividing by keeps the softmax from saturating, multiple heads counter the resolution lost by averaging, and positions supply the order that attention does not carry.
- The paper’s numbers are mostly reliable but should be read with question marks: the parameter column, 41.8 versus 41.0, “the base model beats everything” holding for one language pair only, and small differences in Table 3 falling inside the noise.
- Measuring it yourself is the best way to read: a 235K-parameter Transformer trained for a dozen minutes on a laptop is enough to see that position information is indispensable, that learned embeddings do not leave the training lengths, and that differences in heads and depth vanish in the spread between three seeds; the paper’s Tables 1 and 2 can be recomputed in a few lines, which makes the loose ends easy to spot.
Further reading
- Paper: Attention Is All You Need; original code: tensor2tensor.
- Predecessors: Neural Machine Translation by Jointly Learning to Align and Translate (attention); Convolutional Sequence to Sequence Learning (ConvS2S); Layer Normalization; Adam.
- Follow-ups on this site: BERT, T5, ViT, RoFormer, GQA, FlashAttention, AdamW.
- Wiki: Attention basics, From RNNs to attention, The Transformer block, Positional encoding, Modern LLM architecture.
FAQ
- What problem does "Attention Is All You Need" solve?
- Recurrent networks (RNNs, LSTMs) compute one position after another, so the positions of a sequence cannot be processed in parallel, and two distant positions need many steps to exchange information. The paper (arXiv 1706.03762, NeurIPS 2017) proposes the Transformer: only self-attention and position-wise feed-forward layers, so any two positions are one step apart and a whole sequence is computed in parallel. On WMT 2014 English-German it reached 28.4 BLEU after 3.5 days on eight P100 GPUs, more than 2 BLEU above the best earlier result, ensembles included.
- Why does scaled dot-product attention divide by the square root of d_k?
- Because dot products grow with dimension. If the components of q and k are independent with mean 0 and variance 1, then q·k has variance d_k and standard deviation √d_k; without scaling the softmax inputs get large, the weights approach one-hot and the gradients vanish. We measured it on 500 random queries: at d_k=1024 the largest attention weight averages 0.942 without scaling and 0.107 with it, almost the same as the 0.101 at d_k=1.
- Why does the Transformer need positional encodings, and can they be learned?
- Self-attention by itself does not distinguish positions: shuffle the input and the outputs are shuffled in the same way, so position information has to be added. The paper uses fixed sine and cosine encodings and also tried learned position embeddings; the two were nearly identical on translation (Table 3, row (E): 25.7 BLEU against 25.8 for the base model). In the small copy experiment on this page (training lengths 5 to 8) they differ sharply: without any position information 99.6% of the outputs contain the right digits but in the wrong order, so only 0.5% are copied exactly; learned embeddings are perfect on the trained lengths but reach only 16.4% at length 9, because the embedding of the 9th position was never trained; sinusoidal encodings degrade much more slowly (77.2% at length 9). Most modern LLMs use relative schemes such as RoPE.
- Do the numbers in the paper check out?
- Most do, a few do not. The training costs (3.3e18 and 2.3e19 FLOPs) are reproduced exactly from the paper's own times, GPU counts and 9.5 TFLOPS; the parameter column of Table 3 cannot be reproduced with one 37,000-token vocabulary (base computes to 63.1M against 65M printed, big to 214.2M against 213M); the English-French score of the big model is 41.8 BLEU in Table 2 and the abstract but 41.0 in the text of section 6.1. Table 3 trains each variant once, and 7 variants are within 0.3 BLEU of the base model, so small differences should be read with care.
- How do today's LLMs differ from the original Transformer?
- The skeleton is the same (attention plus feed-forward, residual connections, stacking) and nearly every detail has changed: encoder-decoder became decoder-only; post-norm (LayerNorm after the residual) became pre-norm, with RMSNorm in LLaMA; sinusoidal positions became RoPE; multi-head attention became MQA or GQA to shrink the KV cache; the ReLU feed-forward became SwiGLU; attention is implemented with FlashAttention; and the scale grew from 65 million parameters by several orders of magnitude.