Papers · 2017 · Reading: 20 min, plus 2 in closed details · +6h 25m of resources.
Paper · NeurIPS 2017 · arXiv 1706.03762

Attention Is All You Need (Transformer)

Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, Illia Polosukhin
Google Brain, Google Research, University of Toronto · June 2017 (arXiv v1 12 June 2017; v7 August 2023)

In one line: Replaced recurrence entirely with multi-head scaled dot-product self-attention, making sequence training parallel and becoming the backbone of nearly every modern LLM.

28.4 BLEU
WMT 2014 English to German, big model
over 2 BLEU above every earlier model, ensembles included · Table 2
41.8 BLEU
WMT 2014 English to French, big model
new single-model state of the art at under 1/4 the training cost · Table 2
12 h on 8 P100s
to train the base model (65M parameters)
3.3 × 1018 FLOPs, already past every earlier EN-DE result · §5.2
The idea in one sentence

Drop recurrence and let every position attend to every other position in one parallel step: the path between any two words falls from n steps to 1, training parallelises across the sequence, and an encoder-decoder built only from attention, a per-position feed-forward layer and Add & Norm beat every earlier translation model at a fraction of the training cost.

How far to trust it: the idea held up completely; the BLEU margins are single runs with no error bars, and two printed numbers disagree with each other or with a recount (Results).

The model at a glance

§3, Figure 1

The whole model is attention, a feed-forward layer and Add & Norm: no recurrence, no convolution. The figure is the base model of Figure 1 in 3D: N = 6 of each layer, dmodel = 512, h = 8, dff = 2048. Step through it in the order data flows; drag it to turn it.

  1. Two stacks. The encoder (left) reads the source sentence; the decoder (right) writes the translation one word at a time. Each is N = 6 identical layers, and every layer outputs dmodel = 512 numbers per word so the residual sums line up.
  2. Words in. Each source word becomes a 512-number embedding (multiplied by √dmodel) plus a fixed sinusoidal positional encoding, at the bottom of the encoder.
  3. Up through the encoder. Every layer runs multi-head self-attention (h = 8 heads), each word looking at every other word, then a position-wise feed-forward network, 512 → 2048 → 512, the same at every position.
  4. Into every decoder layer. The encoder's last output becomes the keys and values of cross-attention in all six decoder layers, so every output position can look at every input position.
  5. The decoder's own words. The translation so far, shifted right by one, enters the decoder. Its first sub-layer is masked self-attention: position i sees only positions up to i.
  6. Add & Norm around every sub-layer. Each is wrapped as LayerNorm(x + Dropout(Sublayer(x))): the residual path (the lines up the sides) lets the signal skip each block, and the norm comes after the sum ("post-LN").
  7. The next word. A linear layer (the embedding matrix, shared) and a softmax turn the decoder's top output into a probability for every token of the vocabulary; the chosen word is appended and the decoder runs again.

The sentence is an illustration; the layout and sizes are the paper's (§3.1). Notice the three kinds of attention: the encoder's self-attention, the decoder's masked self-attention, and cross-attention carrying the encoder's keys and values into every decoder layer.

New terms. Sequence transduction: mapping one sequence to another (translation, parsing). Post-LN: the norm applied after the residual sum, LayerNorm(x + Sublayer(x)). Background the page assumes: RNN encoder-decoders with Bahdanau attention (Sequence models before the transformer).

Problem

§1 Introduction, §2 Background

In 2017 sequence transduction, translation above all, was dominated by recurrent encoder-decoders (LSTMs and GRUs), usually with an attention mechanism between encoder and decoder, and by convolutional alternatives such as ByteNet and ConvS2S (§1, §2). A recurrent network computes its hidden state ht from ht−1 and the input at position t, so training cannot be parallelised along the sequence: that caps how much of a GPU a batch can use, and memory limits batching across examples as sentences get longer. Convolutional models do compute all positions in parallel, but connecting two distant positions takes a stack of layers, O(n/k) for contiguous kernels (ConvS2S) or O(logk n) for dilated ones (ByteNet), so long-range dependency paths stay long (§4).

The question: can attention alone, with no recurrence and no convolution, carry an entire sequence model?

Idea

§4 Why Self-Attention, Table 1

Let every position look at every other position directly, in one step. Section 4 compares layer types on three counts: total computation per layer, how much of it can run in parallel (the minimum number of sequential operations), and the longest path a signal has to travel between two positions, since shorter paths make long-range dependencies easier to learn (§4, Table 1).

LayerComputation per layerSequential operationsLongest path
Self-attentionO(n²·d)O(1)O(1)
RecurrentO(n·d²)O(n)O(n)
ConvolutionalO(k·n·d²)O(1)O(logk(n))
Self-attention, restricted to r neighboursO(r·n·d)O(1)O(n/r)

n is the sequence length, d the representation size, k the kernel width, r the neighbourhood size (Table 1).

When n < d, as with sentence-level word-piece and byte-pair tokens, self-attention is also cheaper per layer than recurrence: n²d < nd² exactly when n < d, so with the base model's d = 512 the crossover is at 512 tokens; for longer sequences the paper suggests the restricted row (§4). The figure runs one sentence through both layer types, step by step below; the Table 1 calculator moves n and d.

Same 11-word sentence; costs at the paper's d = 512.

    Counts follow Table 1: n sequential steps of d² multiply-adds against all n² dot products of length d at once (the 4nd² projections are left out, as in the table).

    Method: scaled dot-product attention

    §3.2.1, Eq. 1

    The Transformer is an encoder-decoder built only from attention, position-wise feed-forward layers, residual connections and layer normalisation (§3). Attention maps a query and a set of key-value pairs to a weighted sum of the values, the weights coming from how well the query matches each key. With queries and keys of size dk and values of size dv, packed as matrices:

    Attention(Q, K, V) = softmax(QK⊤ / √dk) V
    Equation 1 (§3.2.1). Dot-product rather than additive (Bahdanau) attention, because it is a single matrix multiply: similar in theory, much faster and more memory-efficient in practice.

    The figure runs Equation 1 with real numbers: the first encoder layer of this page's trained toy Transformer (Run a Transformer; dmodel = 24, h = 4, so dk = 6), head 4, on one sentence. The paper's base model does the same with dk = 64.

    1. Each word is a vector. The word's embedding plus its position: 24 numbers here (the bars), 512 in the paper.
    2. Three learned matrices make three vectors. WQ, WK and WV turn every word into a query (what it is looking for), a key (what it offers) and a value (what it hands over), 6 numbers each for this head.
    3. The query meets every key. The chosen word's query is dotted with all seven keys: a large score means a good match.
    4. Divide by √dk. Every score shrinks by √6 ≈ 2.45 (by √64 = 8 in the paper), the scaling the paragraph below explains.
    5. Softmax turns scores into weights. Exponentiate and normalise: the weights are positive and sum to 1.
    6. The output is the weighted sum of the values. z = Σj aj vj: each value flows in with its weight. Every word does this at once, which is the matrix form softmax(QK⊤/√dk)V.

    Query word

    The 1/√dk is the load-bearing detail. If the components of q and k are independent with mean 0 and variance 1, then q·k = Σqiki has mean 0 and variance dk (the paper's footnote 1). Unscaled, the logits spread out as dk grows and push the softmax into regions with tiny gradients; the paper notes that additive attention beats unscaled dot-product attention at large dk (§3.2.1).

    without the 1/√dk, what happens to the largest attention weight over 10 keys as dk grows from 4 to 512?

    Method: multi-head attention

    §3.2.2

    Instead of one attention over dmodel = 512 dimensions, the queries, keys and values are projected h = 8 times with learned matrices WiQ, WiK (dmodel × dk) and WiV (dmodel × dv), with dk = dv = dmodel/h = 64. Each head runs attention in parallel; the h outputs are concatenated and projected back by WO (hdv × dmodel) (§3.2.2).

    MultiHead(Q, K, V) = Concat(head1, …, headh) WO,   headi = Attention(QWiQ, KWiK, VWiV)
    1. One word's vector: 512 numbers. Drawn to scale, one unit of width per 64 dimensions.
    2. Eight projections of 64. Each head has its own WiQ, WiK, WiV (512 × 64), giving it a 64-number query, key and value: 8 × 64 = 512, so the eight heads together cost what one full-width head costs.
    3. Each head attends on its own. Eight independent n × n weight patterns, computed in parallel, each in its own 64-dimensional subspace.
    4. Concatenate, then project. The eight 64-wide outputs side by side make 512 again; WO (512 × 512) mixes them. The projections hold 4 × 512 × 512 weights either way.
    5. What heads learn: real patterns. The toy model's four heads in its second encoder layer on one sentence (rows: queries, columns: keys, height: weight). Each head has learned a different pattern, which a single head would have to average.

    Because each head is h times narrower, the total cost is about that of one full-width head. What it buys: heads can attend to different subspaces and positions at once, where a single head has to average them. In the ablation one head costs 0.9 BLEU against the best setting (24.9 against 25.8), and too many heads hurt as well: 32 heads of 16 score 25.4 (Table 3 rows (A)). The Run a Transformer tab shows every head of a trained toy model, and a one-head version of it.

    Method: the block (post-LN)

    §3.1, §3.2.3, §3.3, §3.4

    The encoder is a stack of N = 6 identical layers with two sub-layers each: multi-head self-attention, then a position-wise feed-forward network. Every sub-layer is wrapped as LayerNorm(x + Sublayer(x)), normalisation after the residual sum ("post-LN"), with dropout on the sub-layer output before it is added. Every sub-layer and the embeddings produce outputs of size dmodel = 512 so the residuals line up (§3.1, §5.4).

    The decoder is also N = 6 layers, with three sub-layers: masked self-attention, where every illegal connection is set to −∞ before the softmax so position i sees only positions up to i (combined with the outputs being shifted right by one, a prediction depends only on earlier words); cross-attention, whose queries come from the decoder and whose keys and values come from the encoder's output, so every output position can look at every input position; and the same feed-forward network (§3.1, §3.2.3).

    1. One encoder layer, five positions. From the bottom: the input vectors, multi-head self-attention, Add & Norm, the feed-forward network, Add & Norm. The model at the top stacks six of these.
    2. Only attention mixes positions. Self-attention is the one sub-layer where a position reads from the others; everything above it works on each position alone.
    3. Residual, then norm. The input skips the sub-layer and is added to its output; LayerNorm comes after the sum: LayerNorm(x + Sublayer(x)), post-LN.
    4. The FFN, position by position. 512 → 2048 (ReLU) → 512, the 4× expansion drawn in depth; the same weights at every position, never mixing them (Equation 2 below).
    5. The decoder's mask. Masked self-attention of the toy model's decoder (second layer, first head) as it translates: query i (rows) uses keys up to i; later positions are set to −∞ before the softmax, so their weight is exactly 0 and training can predict every position of a sentence in one pass.
    FFN(x) = max(0, xW1 + b1) W2 + b2
    Equation 2 (§3.3): the same two linear maps with a ReLU between them at every position (two convolutions of kernel size 1), different from layer to layer; inner size dff = 2048, a 4× expansion.
    The FFN as attention over parameters: an appendix only v2 and v3 carried

    v2 (19 June 2017) and v3 (20 June) end with an appendix, "Two Feed-Forward Layers = Attention over Parameters": Equation 2 is a kind of attention, with ReLU in place of the softmax and each of the 2,048 hidden units a stored pair, its column of W1 the key and its row of W2 the value, so the FFN is a key-value memory four years before Geva et al. (2021) measured trained FFNs behaving as one. Its Table 5 replaces every FFN with attention over learned key-value pairs at matched parameters (65M), on newstest2013 (development): base perplexity 4.92 and BLEU 25.8; AOP1 4.92 and 25.5; AOP2 4.86 and 25.9, both trained 16 hours against the base's 12. One slip: the text gives the second model 8 heads where Table 5 says 16. From v4 (30 June 2017) on, the appendix is gone; this page reads v7. Checked against v1 to v5 on the transformers-from-memory article page, which derives why a sharper curve than ReLU (up to softmax) lets such a memory hold more rows.

    Embeddings. One weight matrix is shared by the input embedding, the output embedding and the pre-softmax projection, and in the embedding layers it is multiplied by √dmodel (§3.4); with the shared English-German vocabulary of about 37,000 tokens, that one matrix is 18.9 million of the base model's parameters (37,000 × 512, counted in the tables tab).

    Method: positional encoding

    §3.5

    With no recurrence and no convolution nothing in the model knows word order, so it has to be injected. The paper adds fixed sinusoids to the embeddings at the bottom of both stacks:

    PE(pos, 2i) = sin(pos / 100002i/dmodel),   PE(pos, 2i+1) = cos(pos / 100002i/dmodel)
    Each dimension is a sinusoid; the wavelengths form a geometric progression from 2π to 10000 · 2π (§3.5).
    1. Each pair of dimensions is a clock. Dimensions 2i and 2i+1 hold sin and cos of the same angle, so together they are a hand on a dial (sin across, cos up). Eight of the 256 pairs are drawn; at position 0 every hand points up.
    2. Positions 0 to 6. At position pos hand i has turned by pos / 100002i/512: the first clock a full radian per word (wavelength 2π ≈ 6.3), later clocks ever more slowly.
    3. Positions 6 to 50. Fast hands spin round many times and repeat; slow hands have barely moved. Read together, the hands give every position a different reading, from wavelength 2π up to 10000 · 2π.
    4. An offset is a fixed turn. Moving from position 10 to 15 (k = 5) turns each hand by k / 100002i/512, an angle that depends only on k.
    5. The same turn from anywhere. From 40 to 45 every hand turns by exactly the same angles as from 10 to 15. A turn is a rotation, a linear map, which is why PEpos+k is a linear function of PEpos.

    Why sinusoids: for any fixed offset k, PEpos+k is a linear function of PEpos (each sine and cosine pair is rotated by an angle that depends only on k), which the authors hoped would make attending by relative position easy to learn. Learned absolute embeddings gave nearly identical results (25.7 BLEU against 25.8, Table 3 row (E)); the sinusoids were kept because they might extrapolate to sequences longer than any seen in training (§3.5). What later models use instead (relative biases, ALiBi, RoPE and its scaling) is taught on Positional encodings.

    Left: the encoding of positions 0 (top) to 63 (bottom) across all 512 dimensions at dmodel = 512 (blue negative, orange positive): fast sinusoids on the left, wavelengths up to 10000 · 2π on the right. Right: PEp · PEp+k against the offset k for three starting positions p: the curves coincide, because the dot product depends only on the offset. Computed from the formula above.

    train the same toy model without positional encoding. What does it output for "the dog chased the cat" and for "the cat chased the dog"?

    Method: training and decoding

    §5 Training, §6.1
    • Data (§5.1): WMT 2014 English-German, about 4.5 million sentence pairs, byte-pair encoded with a shared source-target vocabulary of about 37,000 tokens; English-French, 36 million sentences, a 32,000 word-piece vocabulary.
    • Hardware and time (§5.2): one machine with 8 NVIDIA P100s. Base model (65M parameters): 100,000 steps at about 0.4 s each, 12 hours. Big model (213M): 300,000 steps at 1.0 s, 3.5 days.
    • Optimiser (§5.3): Adam with β1 = 0.9, β2 = 0.98, ε = 10−9, and a learning rate that rises linearly for 4,000 warmup steps, then falls with the inverse square root of the step (Equation 3, below).
    • Regularisation (§5.4): residual dropout 0.1 (0.3 for the big English-German model); label smoothing εls = 0.1, which "hurts perplexity, as the model learns to be more unsure, but improves accuracy and BLEU".
    • Decoding (§6.1): beam search with beam 4 and length penalty α = 0.6, on an average of the last checkpoints.
    The rest of the recipe, and two small gaps in it

    Batches held about 25,000 source and 25,000 target tokens, sentences grouped by length (§5.1). Dropout is applied to every sub-layer output and to the sums of embeddings and positional encodings (§5.4). Decoding stops at input length + 50; the final model averages the last 5 checkpoints, written every 10 minutes, for base models and the last 20 for big ones (§6.1).

    §5.4 announces "three types of regularization" and lists two (residual dropout and label smoothing). §5.2 gives the base model as 65M parameters; recounting from the stated configuration gives 63.1M (the recount in the tables tab).

    lrate = dmodel−0.5 · min(step−0.5, step · warmup−1.5)
    Equation 3 (§5.3). The two branches meet at step = warmup, so the peak is (dmodel · warmup)−0.5.
    Warmup, then an inverse-square-root decay: the peak is (dmodel · warmup)−0.5

    Results

    §6 Results, Tables 2 to 4
    • English to German (WMT 2014 newstest2014): the big model scores 28.4 BLEU, more than 2.0 above the best earlier result including ensembles (ConvS2S Ensemble, 26.36; the gap is 2.04). Even the base model, 27.3, beats every earlier model and ensemble at a fraction of their training cost: 3.3 × 1018 FLOPs against 9.6 × 1018 to 1.8 × 1020 for the others (§6.1, Table 2).
    • English to French: 41.8 BLEU for the big model in Table 2 and the abstract, a new single-model state of the art, at 2.3 × 1019 FLOPs, under a quarter of the earlier single models' 1.2 to 1.5 × 1020 (0.15 to 0.19 of them). This model used dropout 0.1 instead of 0.3 (§6.1). Two printed figures: the v7 text of §6.1 still says 41.0; this page uses 41.8, the later and tabulated figure (details below).
    How the FLOPs were counted, and the two English-French scores

    FLOPs (Table 2, footnote 2): training time × number of GPUs × an estimate of each GPU's sustained single-precision rate (2.8, 3.7, 6.0 and 9.5 TFLOPS for K80, K40, M40 and P100). Defaults reproduce Table 2 independently: 12 h × 3,600 s × 8 × 9.5 × 1012 = 3.28 × 1018 (3.3 × 1018), and 3.5 days gives 2.30 × 1019 (2.3 × 1019); see recompute.py. These are estimates of what the hardware could do, not measured operations.

    41.0 against 41.8. The two primary figures disagree: the v7 text of §6.1 still says 41.0, the figure the v1 and v2 abstracts reported, while Table 2 and the abstract from v5 on say 41.8.

    • English constituency parsing (§6.3, Table 4): a 4-layer Transformer with dmodel = 1024, trained on the 40,000 Wall Street Journal sentences alone, scores 91.3 F1 on WSJ section 23, beating the BerkeleyParser (90.4), which RNN sequence-to-sequence models had not managed in this small-data setting; only the Recurrent Neural Network Grammar (91.7) is higher. Semi-supervised, with about 17 million sentences, it scores 92.7: evidence the architecture generalises beyond translation. Table 4 rebuilt.
    • Ablations (§6.2, Table 3, measured on newstest2013 without checkpoint averaging): too many heads hurts as well as too few, bigger models are better, dropout is essential at this data scale, and shrinking dk hurts (the authors suggest a better compatibility function than the dot product might help). Guess the costliest change:
    Parsing setup

    Vocabulary 16K (WSJ only) or 32K (semi-supervised); beam 21, α = 0.3, maximum output length input + 300; little task-specific tuning (§6.3).

    which single change to the base model cost the most dev BLEU (base: 25.8)?
    Better and cheaper at once: the Transformers sit above every earlier model, at a fraction of their training cost

    Table 2 rebuilt: BLEU on newstest2014 against training FLOPs (log scale). Filled: single models; rings: ensembles; Transformers in blue. The paper prints one cost per Transformer model for both pairs; ByteNet (EN-DE 23.75) and Deep-Att + PosUnk have no cost and are listed under the chart. The Transformer costs reproduce independently (details below).

    Why it matters

    beyond the paper: later work, each claim linked

    Removing recurrence made training embarrassingly parallel across sequence length, which let compute be spent on model and data size instead of waiting on wall-clock sequential steps. Every frontier LLM (GPT, Claude, Llama, Gemini, DeepSeek), BERT-style encoders, ViT, CLIP, Whisper and most of diffusion's backbone work descend from this design.

    What survived untouched: scaled dot-product attention itself, multi-head projections, and the residual-plus-norm wrapping. What changed were the choices that turned out not to be load-bearing, each taught on the page that owns it: decoder-only won for generation, with cross-attention surviving in multimodal adapters and encoder-decoders holding on in T5 and Whisper (Families and objectives); pre-LN and RMSNorm replaced post-LN LayerNorm (Normalisation, residuals and stability); RoPE replaced the added sinusoids, with interpolation and YaRN to extend the context (Positional encodings); SwiGLU (or GeGLU) replaced the ReLU FFN and biases were dropped; MQA, GQA and MLA shrink the KV cache (Attention variants); FlashAttention makes exact attention IO-aware (Writing kernels), since the O(n²) cost the paper acknowledged is now the central serving bottleneck, also attacked by PagedAttention, sliding windows, and sparse and linear hybrids such as Mamba; and the recipe changed: label smoothing and heavy dropout largely dropped at pretraining scale (PaLM trained without dropout), with Adam's β2 moved to 0.95 and the warmup then decay schedule surviving in cosine form. The Then and now tab morphs the 2017 block into a 2026 one, one sourced change per step.

    Connections. BERT kept the encoder; GPT-3 and Scaling Laws scaled the decoder; T5 kept the encoder-decoder; ViT fed it image patches; RoFormer replaced its positional encoding; FlashAttention and PagedAttention attack the memory and IO costs it created; Mamba tries to remove its O(n²) core. Topics: ml-fundamentals (sequence-model history, attention), llm-training-and-post-training (positional encodings, learning-rate schedules), llms (the ancestor of every family covered). Each is described in Further reading.