Transformers: Attention Is All You Need
Each word gathers information from every other word directly, in one parallel step.
A translation architecture with no recurrence and no convolution: tokens turn into vectors, compare themselves with every other token via matrix multiplication, and pass through six stacked layers.
Explaining the paperAttention Is All You NeedIn 2017, eight NVIDIA P100 GPUs trained this network for 3.5 days to set translation records on the WMT 2014 news benchmark (28.4 BLEU English-to-German and 41.8 English-to-French, a 0-to-100 translation-overlap score where higher is better) at under a quarter of the prior best model's compute.
Vaswani et al. built the Transformer for machine translation: an English sentence enters, and a German or French translation comes out. Before 2017, top translation systems relied on recurrent neural networks (RNNs), which read a sentence one token at a time, updating a running hidden state at every word. Even when researchers added an attention layer so the translator could refer back to the source sentence, the recurrent backbone stayed in place and forced every training example to execute sequentially from left to right.
The Transformer removes recurrence and convolution. Every layer computes a fresh vector for each word by taking a learned weighted average of every other word's vector, and it computes all word positions simultaneously in a handful of dense matrix multiplications. On WMT 2014 (Workshop on Machine Translation 2014, a standard public benchmark of news sentences), quality is scored in BLEU (Bilingual Evaluation Understudy, a 0 to 100 measure of n-gram overlap against human reference translations, where higher is better). Even the small base Transformer, trained in 12 hours, beat every previously published single model and ensemble on English-to-German.
Why recurrent networks are slow
To understand what the Transformer replaces, start with how a recurrent encoder-decoder translates a sentence. An RNN maintains a fixed-size vector called the hidden state . At word 1, it combines word 1 with an initial state to produce . At word 2, it combines word 2 with to produce , and so on until the end of the sentence. Early neural translators such as Seq2Seq (which uses long short-term memory units, or LSTMs, with no attention layer) and Cho et al.'s GRU encoder-decoder compressed the entire source sentence into that final hidden state, then ran a second recurrent network to emit the translation one word at a time.
That chain of dependencies imposes two bottlenecks. The first is GPU parallelism. Because depends on , step 20 cannot begin until step 19 finishes, so a 50-word sentence requires 50 sequential steps regardless of how many parallel cores a GPU (graphics processing unit) has. The paper notes that this sequential structure precludes parallelization within training examples: you can still batch multiple sentences together, yet longer sentences consume more memory per example and shrink the batch size that fits on one GPU.
The second bottleneck is path length between distant words. Suppose word 1 is “animal” and word 50 is a pronoun referring back to it. In a recurrent layer, any signal from word 1 has to pass through 49 consecutive state updates before reaching word 50, and during backpropagation the training gradient has to travel backward through those same 49 updates. Citing Hochreiter et al.'s analysis of long-range dependencies, the paper argues that the shorter the forward and backward paths between two positions, the easier it is for gradient descent to learn their relationship.
Convolutional sequence models such as ByteNet and ConvS2S removed the sequential bottleneck by sliding fixed-width filters over all positions in parallel. Even so, a convolution with kernel width only connects neighbors within words per layer, so linking distant tokens still requires stacking ordinary layers or dilated layers. Self-attention connects every position directly to every other position in a single layer: one hop between any two tokens, and sequential operations across the sentence. Toggle between recurrent and self-attention modes in Figure 1 and drag the sequence length slider to see how path length and sequential steps separate as grows.
Direct all-to-all wiring does have a price: comparing every pair of tokens requires comparisons per layer, each taking a dot product across numbers, for operations. A recurrent layer runs steps, each multiplying a weight matrix by a -element state vector, for operations. Whenever a sentence is shorter than the model's vector width (), self-attention actually performs fewer total arithmetic operations than a recurrent layer, a crossover explored quantitatively in the final section.
How tokens become vectors
Neural networks operate on arrays of floating-point numbers, so the first step converts raw text into integer IDs and then into continuous vectors. Splitting on whitespace alone creates a huge vocabulary full of rare inflections (“walk”, “walked”, “unwalkable”) and fails on unseen words. Instead, for English-German the authors use byte-pair encoding (BPE), a subword tokenizer that keeps frequent words whole and breaks rare words into common fragments (for example, splitting an unfamiliar compound word into recognizable roots and suffixes). Both languages share a single vocabulary of about 37,000 tokens. For English-French, the paper uses a 32,000-token word-piece vocabulary, a closely related subword scheme.
Next comes a learned lookup table of shape , where is the vocabulary size and in the base model. Embedding a token ID fetches its 512-number row from this table. At initialization those rows hold small random values; backpropagation gradually moves semantically or syntactically related tokens to nearby directions in 512-dimensional space.
A sentence of tokens therefore enters the network as an matrix, one row per token. Every sublayer in the Transformer accepts an matrix and returns an matrix. Row 7 always belongs to token 7; what changes from layer to layer is the contextual information packed into that row. At the input, row 7 for the pronoun “it” in “the animal crossed the road because it got tired” is identical to “it” in any other sentence. After several layers of self-attention, row 7 incorporates features pulled from “animal” and “tired”.
Two implementation choices sit inside this embedding layer. First, the paper multiplies every looked-up embedding vector by (about 22.6 for width 512) before adding the positional encoding covered below. The paper states this factor without explaining why; a common reading is that embedding tables are typically initialized with small entries (variance around , roughly 0.04 in magnitude), so scaling by brings token embeddings to order 1, keeping them from being drowned out by positional encodings whose entries lie in . Second, following Press and Wolf (2017), the model reuses that same matrix in three places: source embeddings, target embeddings, and (transposed) as the final linear projection that turns the decoder's 512-number output vectors into 37,000 next-token scores. Sharing that table saves nearly 38 million parameters compared to keeping three separate tables.
How scaled dot-product attention works
A hash table or dictionary takes a lookup key, checks for an exact match among stored keys, and returns the single matching value. Attention softens that exact lookup into a differentiable weighted average. Given a query vector, it scores that query against every stored key, converts those scores into non-negative weights summing to 1, and returns the weighted sum of all value vectors: when one key matches far better than the rest, its weight approaches 1 and the output nearly copies its value, whereas two equally strong matches produce a fifty-fifty blend of their values.
Why not compare raw token embeddings directly with ? Direct dot products have two flaws. First, a vector's largest dot product is usually with itself (), so every token would mostly copy itself. Second, is symmetric, whereas language relationships are asymmetric: “it” needs to gather features from “animal”, while “animal” has no reason to copy “it”. To break symmetry and separate matching from content, every token vector is multiplied by three separate learned matrices to produce three distinct vectors:
- Query (): the search pattern this token issues to find relevant context.
- Key (): the label this token advertises for other tokens' queries to match.
- Value (): the content payload this token contributes when another token attends to it.
To measure compatibility between a query and a key , the Transformer computes their dot product: multiply matching coordinates and add them up (). When and point in similar directions, the dot product is large and positive; when they are perpendicular, it is zero; when they point opposite ways, it is negative. After dividing each raw score by , where is the query and key vector dimension (justified in the next section), a softmax converts the row of scores into weights: each score becomes . Because the exponential is always positive and dividing by the sum normalizes the total to 1, the weights form a probability distribution over all keys in the sentence. Pick different query tokens in Figure 2 to inspect how one token distributes its attention weights across the sentence.
In the base Transformer, queries and keys live in 64 dimensions (), which cannot be drawn directly. Dropping to lets every step sit on a flat 2D plane. Suppose the pronoun “it” projects to the query vector , and four words in the sentence have the keys and values listed below (a full head also scores “it” against itself and the remaining words):
| token | key k | q·k | ÷ √2 | weight | value v |
|---|---|---|---|---|---|
| animal | (1.5, 0.5) | 2.70 | 1.91 | 0.80 | (2.0, 1.5) |
| road | (0.5, −1.5) | −0.10 | −0.07 | 0.11 | (1.5, −1.5) |
| crossed | (−1.2, 0.8) | −1.44 | −1.02 | 0.04 | (−1.5, 0.5) |
| tired | (−0.6, −0.9) | −1.50 | −1.06 | 0.04 | (−1.0, −1.5) |
The raw compatibility between “it” and “animal” is the dot product of their two-number vectors:
Dividing all four dot products by (about 1.414) produces scaled scores of 1.91, −0.07, −1.02, and −1.06. Exponentiating gives 6.75, 0.93, 0.36, and 0.35 (sum 8.39); dividing by 8.39 yields attention weights of 0.80, 0.11, 0.04, and 0.04. Multiplying each value vector by its weight and summing gives the new representation at the position of “it”:
Geometrically, every weighted average with non-negative weights summing to 1 is trapped inside the shaded polygon spanning the value points (their convex hull). Drag the query vector on the left plane of Figure 3 to watch the bars and the white output ring respond in real time, then click the “same direction, short” and “same direction, long” presets. Notice that keeping the same angle while shortening flattens the weights to 0.39, 0.24, 0.19, 0.19, whereas lengthening sharpens the peak on “animal” to 0.96, because scaling a query multiplies every dot product by the same factor and exponentially amplifies gaps inside softmax.
Rather than looping over tokens one by one, stack all query vectors as rows of a matrix , all keys as rows of , and all values as rows of . One matrix multiply computes all pairwise dot products simultaneously, a row-wise softmax turns every row into weights, and multiplying by forms all output vectors at once. This is equation (1) of the paper, called scaled dot-product attention:
Reading equation (1) from inside out: has shape (entry is query scored against key ); dividing by keeps the scores in a well-behaved numerical range; softmax normalizes each row across the keys without changing the shape; multiplying by the value matrix yields an output matrix. Every step is a standard GPU matrix operation:
# Scaled dot-product attention, one head, equation (1)
# Q: [n, d_k], K: [m, d_k], V: [m, d_v] (base model: d_k = d_v = 64)
scores = (Q @ K.T) / sqrt(d_k) # [n, m]: query-key dot products
if mask is not None:
scores = scores + mask # [n, m]: -inf on forbidden cells
weights = softmax(scores, axis=-1) # [n, m]: positive rows summing to 1
out = weights @ V # [n, d_v]: weighted sum of valuesWhen , , and all come from projections of the same sentence, equation (1) performs self-attention (). When comes from the target sentence being generated and come from the encoded source sentence, the same equation performs cross-attention (encoder-decoder attention), letting every target position read the entire source.
Why attention divides by √d_k
Remove the factor from equation (1) and you get ordinary dot-product (“multiplicative”) attention, already used in machine translation by Luong, Pham, and Manning (2015). The paper notes that its formula is identical to plain dot-product attention except for that scaling factor. The other established option was additive attention from Bahdanau, Cho, and Bengio (2015), which scores a query-key pair by passing both through a small feed-forward network with one hidden layer. Although both have similar theoretical complexity, dot-product attention runs on highly optimized matrix-multiply kernels and is faster and more memory-efficient in practice.
Prior empirical comparisons (Britz et al., 2017) had found an awkward wrinkle: when the key dimension is small, dot-product and additive attention perform similarly, yet at larger additive attention outperforms unscaled dot-product attention. Vaswani et al. offer a statistical diagnosis, carefully phrased as a suspicion (“We suspect”) rather than a proven theorem: as grows, raw dot products grow in magnitude and shove softmax into flat regions with near-zero gradients.
A random-walk picture makes the scaling law immediate. Imagine a query and a key whose entries are independent random numbers with mean 0 and variance 1 (each coordinate roughly ). Each coordinate product is a step of size roughly , and their dot product sums such steps. Just as a 64-step random walk wanders an average distance of from zero rather than staying near 1, independent variances add linearly:
The typical spread (standard deviation) of raw scores is therefore . At the base model's , that spread is 8, so the highest and second-highest raw scores in a row routinely sit 10 or 15 points apart. Inside softmax, exponentials magnify a gap of 10 into a factor of , collapsing nearly 100% of the weight onto one key. The derivative of a softmax weight with respect to its own score is , which peaks at 0.25 when and vanishes as or . Once softmax saturates, gradients back to and shrink by orders of magnitude, stalling learning. Dividing every score by restores the variance to 1 at any width. Drag the slider in Figure 4 from 1 to 256 to watch the unscaled distribution collapse and its largest gradient vanish while the scaled distribution holds steady.
At , both panels agree because . At the base model's , the unscaled peak weight hits 0.997 and the maximum gradient drops to 0.0035, roughly 70 times smaller than the scaled panel's 0.245. By , the unscaled gradient falls to . Dividing by the variance instead of the standard deviation would overcorrect in the opposite direction: at , dividing by 64 would compress the score spread to , flattening softmax into a nearly uniform average across every token.
How multi-head attention works
A single application of equation (1) assigns each query token one probability distribution over the sentence and returns one weighted average. In real text, a single word participates in several distinct relationships at the same time: in “the animal crossed the road because it got tired”, the pronoun “it” links to its referent (“animal”), its verb (“got”), and its predicate (“tired”). With only one attention distribution, those links must share a single weight vector, blurring their value vectors into one blended average. The paper calls this “reduced effective resolution due to averaging attention-weighted positions.”
Multi-head attention runs attention computations in parallel ( in the base model), each operating in its own smaller 64-dimensional subspace. Head owns three learned projection matrices, , , and , each of shape . Every head projects the entire 512-dimensional token vector down to 64 numbers; it does not merely slice coordinates for head 1 and for head 2. Slicing raw coordinates would wall each head off from seven-eighths of the token's features, whereas learned projections let each head extract whichever linear combination of all 512 features best captures its pattern. Click different query tokens in Figure 5 to compare four specialized heads against the blurred average of a single head.
After all heads compute their output matrices in parallel, the layer concatenates them side by side back into an matrix and multiplies by a final learned output matrix so information gathered by different heads can interact:
The learned projection matrices have shapes:
These formulas are unnumbered in the paper. Because each head shrinks the inner width to (which is 64), eight heads cost roughly the same compute and parameters as a single 512-dimensional head. Across all eight heads, the , , and projections hold 3 × 8 × 512 × 64 = 786,432 weights, plus 512² = 262,144 for , giving (1,048,576) parameters per attention sublayer. In matrix-multiply terms, eight heads compute eight score grids of 64-element dot products instead of one grid of 512-element dot products, keeping total multiply-adds identical (8 × 64 = 512).
# Multi-head attention with h heads (base: d_model = 512, h = 8, d_k = 64)
def multi_head(Xq, Xkv, h=8): # Xq: [n, 512], Xkv: [m, 512]
heads = []
for i in range(h): # separate learned projections per head
Q = Xq @ Wq[i] # [n, 64] Wq[i]: [512, 64]
K = Xkv @ Wk[i] # [m, 64] Wk[i]: [512, 64]
V = Xkv @ Wv[i] # [m, 64] Wv[i]: [512, 64]
heads.append(attention(Q, K, V)) # [n, 64] calls equation (1)
joined = concat(heads, axis=-1) # [n, 512] h * d_v = 8 * 64
return joined @ Wo # [n, 512] Wo: [512, 512]Table 3 rows (A) test how head count affects quality at constant compute on the English-to-German development set (newstest2013): one head of width 512 scores 24.9 BLEU; four heads of 128 score 25.5; eight heads of 64 score 25.8; sixteen heads of 32 also score 25.8; thirty-two heads of 16 drop back to 25.4. One head loses 0.9 BLEU relative to eight heads because of the averaging bottleneck, while splitting into 32 heads starves each head's key dimension down to 16 numbers. Table 3 rows (B) confirm that second effect directly: holding fixed and shrinking only from 64 to 32 or 16 drops BLEU from 25.8 to 25.4 and 25.1, which the authors interpret as evidence that determining query-key compatibility requires enough dimensions.
In the paper's appendix, visualizations of trained attention heads show patterns aligned with syntax and coreference, including two heads in encoder layer 5 whose weights resolve what the pronoun “its” refers to. Treat clean functional roles as a loose tendency rather than a rigid division of labor: Michel, Levy, and Neubig (2019) later demonstrated that a large fraction of attention heads in trained Transformers can be pruned at test time with minimal drop in translation quality.
How positional encoding adds word order
Everything in equation (1) treats the input tokens as an unordered set. Permute the rows of , , and , and every token computes the same dot products with the same keys, obtains the same weights, and emits the same output vector in the shuffled row. Without extra information, “dog bites man” and “man bites dog” produce identical contextual vectors for every word. A recurrent network gets word order automatically from its step-by-step loop; a Transformer has to inject position directly into the input embeddings.
Why not try the two most obvious fixes? First, appending or adding the raw integer index creates unbounded values that grow without limit on long sentences and swamp the learned word embedding. Second, normalizing position into by dividing by sentence length makes step sizes inconsistent across sentences: adjacent words sit 0.20 apart in a 5-word sentence and 0.02 apart in a 50-word sentence, preventing a layer from matching a fixed relative step such as “one word back”. Binary counting avoids both failures by giving every integer a unique bounded code whose lowest bit flips every step, the next bit every two steps, and the next every four; sinusoidal waves provide a smooth, differentiable version of that multi-frequency counter.
For each token position , Vaswani et al. construct a 512-dimensional positional encoding vector and add it elementwise to the scaled token embedding at the bottom of both the encoder and decoder stacks. Even coordinates get sines and odd coordinates get cosines whose wavelengths span a geometric progression across the 256 dimension pairs:
The variable (0, 1, 2, ...) is the token index and (0 to 255) indexes the 256 sine-cosine pairs, each oscillating at angular frequency . Pair has and completes a full cycle every positions, like a fast second hand. Each successive pair slows down by a constant factor, forming a geometric progression of wavelengths from toward (about 62,832); the slowest pair, , completes one cycle every 60,611 positions. All entries stay bounded in , and reading all 512 coordinates together gives every position a unique fingerprint. Drag the position slider in Figure 6 to inspect how fast oscillations on the left and slow waves on the right combine into a single row vector.
The authors give two reasons for choosing sinusoids, and hedge both. First, they hypothesize that sinusoids make it easy for attention to learn relative-position offsets, because for any fixed step , is a linear transformation of . Each sine-cosine pair sits on a unit circle at angle , and stepping forward by positions advances that angle by regardless of where began, which the angle-addition identities express as a rotation matrix independent of :
Because the rotation matrix contains only and not , the dot product between any two positional encodings depends solely on their distance . Each pair contributes , which equals (here ), and summing across all 256 pairs cancels out:
At , every cosine equals 1 and the dot product is 256; as the offset grows, the sum decays smoothly. Set any pair index and offset in Figure 7, then drag the start position : the teal arc glides around the circle while both the turn angle and the 512-dimensional dot product on the right stay fixed.
The authors' second rationale is likewise a “may”: a closed-form formula defined for every integer might let a model extrapolate to sentences longer than any seen during training. The paper does not test extrapolation directly, and when it swaps sinusoids for learned position embeddings (one trained 512-number vector per position), Table 3 row (E) records nearly identical results: 25.7 dev BLEU against 25.8 for sinusoids. Later research found that additive sinusoidal encodings extrapolate poorly in practice and developed relative position schemes such as Transformer-XL, RoPE (which rotates queries and keys directly so their dot product depends only on relative offset), and ALiBi (which adds linear distance penalties directly to attention scores).
Feed-forward layers, residuals, and normalization
Multi-head attention mixes information across token positions, yet for fixed attention weights each output vector is a linear weighted average of value vectors. Stacking only attention layers would leave each position without nonlinear feature transformations. Every encoder and decoder layer therefore places a second sublayer after attention: a position-wise feed-forward network (FFN), applying the same two-layer neural network independently to every token row, with zero communication between positions:
In equation (2), is one token's vector, expands it fourfold into a 2048-dimensional hidden layer, the ReLU activation (, which keeps positive values and zeroes negative ones) introduces nonlinearity, and projects it back to 512 dimensions. Each layer learns its own , which the paper also describes as two convolutions of kernel size 1. Counting the weights in equation (2) gives:
Each feed-forward sublayer holds 2.10 million parameters, twice the 1.05 million parameters of the multi-head attention sublayer sitting right below it. Table 3 row (C) shows that this capacity matters: doubling from 2048 to 4096 on the base model lifts dev BLEU from 25.8 to 26.2, whereas halving it to 1024 drops BLEU to 25.4.
Deep stacks of nonlinear layers fail to train cleanly unless signal magnitudes and gradients stay bounded from top to bottom. The Transformer wraps every sublayer (attention and FFN alike) in two stabilizing mechanisms. A residual connection, adopted from He et al.'s ResNet (2016), adds the sublayer's input directly to its output, so each sublayer computes an incremental update to the vector stream and gradients flow backward along an unobstructed additive highway across all six layers. Immediately after that addition, layer normalization (Ba, Kiros, and Hinton, 2016) standardizes each token's 512 coordinates to mean 0 and variance 1, then applies a learned per-channel scale and shift. Unlike batch normalization, which averages across examples in a mini-batch and struggles with variable-length sequences, layer normalization operates within each individual token vector. During training, dropout randomly zeroes 10% of each sublayer's output entries () before the residual addition.
# Position-wise FFN, equation (2) (base: d_model = 512, d_ff = 2048)
def ffn(x): # x: [n, 512]
h = maximum(0, x @ W1 + b1) # [n, 2048] W1: [512, 2048]
return h @ W2 + b2 # [n, 512] W2: [2048, 512]
# One encoder layer as written in the 2017 paper (post-LN)
a = LayerNorm(x + dropout(multi_head(x, x, 8))) # [n, 512] sublayer 1
z = LayerNorm(a + dropout(ffn(a))) # [n, 512] sublayer 2
# Pre-LN (later practice, e.g. GPT-2) moves the norm inside each branch:
# a = x + dropout(multi_head(LayerNorm(x), LayerNorm(x), 8))Placing normalization outside the residual sum, LayerNorm(x + Sublayer(x)), is known as post-LN. Many later Transformers, including GPT-2 (Radford et al., 2019, section 2.3), adopted pre-LN instead, normalizing each sublayer's input so the residual stream stays untouched: x + Sublayer(LayerNorm(x)). Xiong et al. (2020) later analyzed both arrangements and showed why the order matters: in post-LN, the expected gradients on parameters near the output are large at initialization, making early training unstable without the learning-rate warmup described in the training section, whereas the already-proposed pre-LN variant trains to comparable accuracy without warmup. None of that stability analysis appears in the 2017 paper, which uses post-LN with a 4,000-step warmup.
The encoder, the decoder, and the causal mask
With embeddings, attention, positional encodings, feed-forward networks, residuals, and layer normalization in hand, the complete translation model snaps together into two stacks of layers. The encoder reads the full source sentence once and transforms its tokens into contextual 512-dimensional vectors; each encoder layer contains two sublayers (self-attention and FFN). The decoder generates the target translation and inserts a third sublayer into every layer so it can consult the encoder's representation. Multi-head attention therefore plays three distinct roles in the assembled network:
- Encoder self-attention: , , and all come from the previous encoder layer, so every source word attends to every other source word in both directions.
- Masked decoder self-attention: , , and come from the previous decoder layer, with a mask restricting each target position to itself and earlier target positions.
- Encoder-decoder attention (cross-attention): queries come from the decoder sublayer below, while keys and values come from the final output of the 6-layer encoder stack. Every target word can read every source word, fulfilling the alignment role of Bahdanau-style attention.
Figure 8 maps every block of the base model for a concrete 9-token source sentence and 10-token target sentence. Click any block (or step through with the prev and next buttons) to trace its input sources, tensor shapes, and parameter count. It starts focused on cross-attention, where 10 target queries attend over 9 source keys to form a score matrix.
Summing the base model's parameter counts checks out against the paper: each encoder layer holds 3,150,336 weights (1.05M attention + 2.10M FFN + two 1,024-parameter layer norms), each decoder layer holds 4,199,936 weights (adding one more attention sublayer and norm), and the shared embedding table holds 18,944,000 weights. Six encoder layers, six decoder layers, and the shared table total 63.0 million parameters, close to the 65 million rounded figure in Table 3 (the paper only reports the vocabulary size as “about 37000”).
Training the decoder in parallel requires one safeguard. At inference time, translation is auto-regressive: the decoder produces word before word exists, so predicting position can only depend on words already emitted before . During training, however, the entire reference target sentence is known upfront, and feeding all target tokens at once lets the GPU compute all predictions in a single parallel pass. If decoder self-attention could attend to rightward positions during that pass, position would copy the true answer from position and fail at inference.
The paper blocks leftward information leakage with two coordinated pieces. First, the decoder's input target sequence is shifted one position to the right (prefixed with a start-of-sequence symbol), so at slot the decoder receives ground-truth word and is trained to predict word . Second, inside scaled dot-product attention, the causal mask adds to every score above the main diagonal () before softmax runs. Since , future keys receive exactly zero weight and the surviving weights on positions automatically renormalize to sum to 1. Toggle the mask button and sweep the query position in Figure 9 to compare the encoder's full bidirectional grid with the decoder's lower-triangular mask.
At the top of the decoder, each 512-dimensional output row is multiplied by the transposed embedding table to produce one raw score (logit) per vocabulary token, and a softmax turns those logits into next-token probabilities. While training processes all target tokens simultaneously, inference must still generate one token per forward pass. Rather than greedily picking the single highest-probability word at each step, the authors use beam search with beam size 4 (maintaining the 4 highest-scoring partial translations at every step) and a length penalty (preventing the search from favoring overly short sentences merely because multiplying fewer probabilities under 1 gives a higher product), stopping early on an end-of-sequence token or at input length plus 50.
How the Transformer is trained
For English-to-German, the authors trained on WMT 2014's roughly 4.5 million sentence pairs; for English-to-French, they used 36 million sentence pairs. Because sentences vary wildly in length, naive random batching wastes GPU work on padding tokens. Instead, sentence pairs of similar length were grouped together so each batch packed roughly 25,000 source tokens and 25,000 target tokens. Every model trained on a single machine holding 8 NVIDIA P100 GPUs: the base model ran for 100,000 steps at roughly 0.4 seconds per step (12 hours total), and the big model ran for 300,000 steps at 1.0 second per step (3.5 days total).
Optimization uses Adam with , (shorter second-moment memory than Adam's standard 0.999), and , paired with a custom learning-rate schedule given by equation (3):
Unpacking the minimum shows two clean regimes that meet at , where both arguments equal . Before that point, the second term is smaller, ramping the learning rate linearly from zero up to its peak so early post-LN updates do not blow up the weights. After that point, the first term is smaller, decaying the learning rate gently as . The leading automatically scales step sizes down for wider models. With the paper's , the base model () peaks at:
By step 100,000, the base learning rate has decayed fivefold to . For the wider big model (), the peak sits lower at . Switch between base and big and drag the warmup slider in Figure 10 to see how shortening warmup creates a sharp early spike while lengthening warmup lowers and delays the peak.
Two regularizers keep the model from overfitting its training pairs. First, residual dropout ( for base; 0.3 for the big English-German model, 0.1 for big English-French) zeroes random activations on every sublayer output before the residual add and on the summed embeddings plus positional encodings. Setting dropout to zero (, Table 3 row D) drops development BLEU from 25.8 down to 24.6.
Second, label smoothing () softens the training targets: instead of demanding probability 1.0 on the true next token and 0.0 everywhere else, the cross-entropy loss targets 0.9 on the correct token and distributes the remaining 0.1 across the vocabulary. This produces a counterintuitive trade-off documented in Table 3 row (D). Measuring perplexity (PPL, equal to , the effective number of equally plausible tokens the model chooses among per step, where lower is better), turning label smoothing off improves validation perplexity from 4.92 down to 4.67, yet hurts translation quality from 25.8 down to 25.3 BLEU. Without smoothing, the network keeps pushing logits toward to squeeze out tiny cross-entropy gains, which makes beam search overconfident and brittle; label smoothing keeps probabilities calibrated enough to choose better full translations. Finally, before evaluating, the authors averaged the weights of the last 5 checkpoints saved every 10 minutes for the base model, and the last 20 checkpoints for the big model.
Complexity, translation results, and limits
Section 4 of the paper summarizes the architectural trade-off in Table 1, comparing four sequence layers on total arithmetic per layer, minimum sequential operations, and longest signal path between two arbitrary positions. In Table 1, is sequence length, is vector width, is convolutional kernel width, and is the local window size of a restricted self-attention layer that only attends to nearby tokens:
| Layer type | Complexity / layer | Sequential ops | Max path length |
|---|---|---|---|
| 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(logₖ n) |
| Self-attention (restricted) | O(r·n·d) | O(1) | O(n/r) |
Comparing the first two rows exposes the exact crossover point between self-attention and recurrence. Dividing by leaves , so self-attention does fewer multiply-adds whenever . For a typical 30-token translation sentence at the base width , self-attention uses roughly 17 times fewer operations per layer than a recurrent step:
Slide past in Figure 11, however, and the advantage reverses sharply. At and , self-attention takes 8 times more multiply-adds than recurrence, and each head must compute a score grid containing 16.8 million entries per layer. Toggle between 256, 512, and 1024 to watch the crossover point shift directly with model width.
Table 2 compares the Transformer against prior recurrent, convolutional, and mixture-of-experts (MoE) translators on WMT 2014 test sets (newstest2014):
| Model (Table 2) | EN-DE BLEU | EN-FR BLEU | Training FLOPs (EN-DE / EN-FR) |
|---|---|---|---|
| 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²⁰ |
| ConvS2S ensemble | 26.36 | 41.29 | 7.7·10¹⁹ / 1.2·10²¹ |
| Transformer (base) | 27.3 | 38.1 | 3.3·10¹⁸ |
| Transformer (big) | 28.4 | 41.8 | 2.3·10¹⁹ |
On English-to-German, the big Transformer (, , , 213 million parameters, 26.4 dev BLEU vs. base's 25.8) reached 28.4 BLEU, beating every previously published model and ensemble (top prior: ConvS2S ensemble at 26.36) by more than 2.0 BLEU. Even the 65-million-parameter base model scored 27.3, beating every earlier ensemble on its own. On English-to-French, the big model hit 41.8 BLEU, setting a single-model record over MoE's 40.56 (base scored 38.1).
The training-cost column reports estimated FLOPs (total floating-point operations), computed by multiplying training duration, GPU count, and an assumed sustained single-precision throughput of 9.5 TFLOPS (trillion floating-point operations per second) per NVIDIA P100. For the base model, 12 hours × 8 GPUs × 9.5 TFLOPS comes to FLOPs, nearly three times less than ConvS2S's . For the big model, 3.5 days yields FLOPs, roughly 19% of the EN-FR MoE model's FLOPs (the paper's “less than 1/4 the training cost of the previous state-of-the-art model”).
To verify that the design was not specific to translation, the authors trained a 4-layer Transformer () on English constituency parsing: predicting the grammatical phrase tree of a sentence on Section 23 of the Wall Street Journal (WSJ) Penn Treebank, scored by F1 (the harmonic mean of precision and recall over predicted phrase brackets, 0 to 100, higher is better). With minimal task-specific tuning, it scored 91.3 F1 when trained only on the 40,000 WSJ sentences (beating the BerkeleyParser baseline of 90.4, whereas earlier RNN seq2seq parsers struggled in small-data regimes) and 92.7 F1 in the semi-supervised setting using about 17 million extra sentences.
Four genuine limitations remained open in 2017 and drove much of the next decade of architecture and systems research:
- Quadratic scaling with length: both compute and score-grid memory grow as . Fine for 30-token translation sentences, this quickly saturates GPU memory on long documents, audio, or high-resolution images, motivating local/restricted attention in Table 1 as well as FlashAttention (which eliminates the memory footprint without changing the exact math), Reformer, and linear-time state-space models such as Mamba.
- Sequential decoding at inference: although training runs all target tokens in parallel, auto-regressive generation still emits one token per forward pass, rereading all past keys and values on every step. The paper's conclusion explicitly flags “making generation less sequential” as open work; later systems attacked this bottleneck through Multi-Query Attention, PagedAttention, and speculative decoding.
- Training sensitivity under post-LN: normalizing outside the residual branch requires careful warmup tuning to prevent early gradient blowups, leading many later models to switch to pre-LN.
- Untested length extrapolation: the sinusoidal encoding's hoped-for extrapolation beyond training lengths went untested in the paper and proved fragile in follow-up work.
The paper describes the Transformer as “the first sequence transduction model based entirely on attention”, evaluated as a full encoder-decoder on translation and parsing. Its later adoption across machine learning came from subsequent papers splitting the architecture apart: BERT (2018) kept only the bidirectional encoder for masked language modeling; the GPT line, through GPT-3, kept only the causally masked decoder and dropped cross-attention; T5 (2019) kept the full encoder-decoder and cast every text task as text-to-text; and the Vision Transformer (ViT) (2020) fed 16×16 image patches into an encoder using learned 1D position embeddings rather than sinusoids. Even on the 2017 paper's own terms, the title overstates what was removed: attention replaces recurrence and convolution, while embeddings, positional encodings, two-thirds of the layer weights inside the feed-forward networks, residuals, and layer normalization remain.
Questions you might still have
Why do tokens need separate query, key, and value projections instead of comparing embeddings directly?
Direct dot products between raw token embeddings are symmetric (so "it" attends to "animal" with the same raw score as "animal" attends to "it") and peak on self-matches because a vector aligns most closely with itself. Separate learned Q and K matrices let a token ask for one role while advertising another, and a separate V matrix lets it pass along different content than the label it was matched on.
If attention has no sense of order, why not add the position as a single number?
A lone scalar index would grow without bound on long sentences, drowning out the word embedding, while dividing by sentence length would make a one-word step change size from sentence to sentence. Sinusoids spread bounded values in [-1, 1] across all 512 coordinates at geometric wavelengths, and because stepping forward by k rotates every sine-cosine pair by a fixed angle, relative offsets correspond to a linear map.
Why divide by the square root of d_k and not by d_k?
When query and key entries have mean 0 and variance 1, their dot product sums d_k independent terms and has variance d_k, so its typical size (standard deviation) is sqrt(d_k), which equals 8 at d_k = 64. Dividing by sqrt(d_k) restores unit standard deviation. Dividing by d_k would shrink the spread to 1/8 and flatten softmax toward uniform weights.
Which parts of the Transformer are learned, and which are fixed?
Learned: the shared embedding table, the Q, K, V, and output projections of every head in every layer, the two weight matrices and biases of every feed-forward sublayer, and the scale and bias of every layer norm (about 65 million weights in the base model). Fixed: the sinusoidal positional encodings, the sqrt(d_model) and 1/sqrt(d_k) scaling factors, and the decoder causal mask.
Does the Transformer eliminate sequential computation at inference time too?
Only inside the encoder. During training, causal masking lets the decoder predict all target tokens in one parallel pass because the reference target is known. At inference time, the decoder still generates translations one token at a time auto-regressively, because step i depends on the word chosen at step i-1.
Is the original 2017 Transformer the same architecture as GPT or BERT?
No. The 2017 model is a full encoder-decoder built for translation. BERT kept only the bidirectional encoder stack, while GPT models kept only the causally masked decoder stack and removed cross-attention. Both have dedicated explainers on this site.
How expensive is self-attention on long documents?
Each head in each layer builds an n by n score grid, so both arithmetic and naive attention memory grow with the square of sequence length n. Below n = d (512 in the base model), self-attention uses fewer operations than a recurrent layer; at thousands of tokens, the n^2 term dominates. The FlashAttention explainer on this site covers how to eliminate the quadratic memory cost without approximating the output.
Footnotes & further reading
- The paper: Vaswani, Shazeer, Parmar, Uszkoreit, Jones, Gomez, Kaiser, Polosukhin, Attention Is All You Need (NIPS 2017, now NeurIPS). Reference implementation in Tensor2Tensor and Harvard NLP's line-by-line The Annotated Transformer.
- Prior attention and sequence-to-sequence translators: Sutskever, Vinyals, Le, Sequence to Sequence Learning with Neural Networks (explained here); Bahdanau, Cho, Bengio, Neural Machine Translation by Jointly Learning to Align and Translate (additive attention; explained here); Luong, Pham, Manning, Effective Approaches to Attention-based NMT (multiplicative attention); Britz et al., Massive Exploration of Neural Machine Translation Architectures.
- Building blocks: He, Zhang, Ren, Sun, Deep Residual Learning for Image Recognition (explained here); Ba, Kiros, Hinton, Layer Normalization (explained here); Hinton et al. (2012), Improving neural networks by preventing co-adaptation of feature detectors (dropout; explained here).
- Post-LN versus pre-LN: Xiong et al., On Layer Normalization in the Transformer Architecture; Radford et al., Language Models are Unsupervised Multitask Learners (GPT-2, section 2.3).
- Weight tying between embeddings and output projection: Press & Wolf, Using the Output Embedding to Improve Language Models.
- Attention head specialization and pruning: Michel, Levy, Neubig, Are Sixteen Heads Really Better than One?, and Voita et al., Analyzing Multi-Head Self-Attention.
- What the architecture spawned: Devlin et al., BERT (explainer); Brown et al., GPT-3 (explainer); Raffel et al., T5 (explainer); Dosovitskiy et al., Vision Transformer (explainer); Su et al., RoFormer (explainer).
How could this explainer be improved? Found an error, or something unclear? I read every message.