Skip to content

Attention Is All You Need

Skip →BPE (subword units)
main track #1corefundamentalpaperrubric 12/122017 · ~60 min

Ashish Vaswani, Noam Shazeer, Niki Parmar, … Illia Polosukhin

Status

TL;DR. The Transformer drops recurrence and convolution. Every layer is attention plus a position-wise feed-forward network, wrapped in residual connections and layer normalisation. The core operation is scaled dot-product attention, softmax⁡(QK⊤/dk)V\operatorname{softmax}(QK^\top/\sqrt{d_k})V, run in 8 parallel heads. It set a new state of the art on WMT14 translation at a fraction of earlier training costs.

Why it matters now. Every model on this site is a variant of this block. That includes ColBERT and cross-encoder rerankers, LLM judges, and RL-trained search agents. Many modern changes are edits to one equation on this page: RoPE changes how position enters q⋅kq\cdot k, GQA and MLA change how many K,VK, V are stored, and FlashAttention changes how the softmax is computed. Reading those papers is much easier once this one is clear.

Scaled dot-product attention (Eq. 1). Pack queries, keys and values into matrices Q,K∈Rn×dkQ, K \in \mathbb{R}^{n\times d_k} and V∈Rn×dvV\in\mathbb{R}^{n\times d_v}:

Attention⁡(Q,K,V)=softmax⁡ ⁣(QK⊤dk)V.\operatorname{Attention}(Q,K,V)=\operatorname{softmax}\!\Big(\frac{QK^\top}{\sqrt{d_k}}\Big)V .

Row ii of the softmax is a probability distribution over positions. The output for position ii is the weighted average of the value rows under that distribution.

Why dk\sqrt{d_k}. Assume the components of qq and kk are independent with mean 0 and variance 1. Then

q⋅k=∑i=1dkqiki,E[q⋅k]=0,Var⁡(q⋅k)=dk.q\cdot k=\sum_{i=1}^{d_k} q_i k_i,\qquad \mathbb{E}[q\cdot k]=0,\qquad \operatorname{Var}(q\cdot k)=d_k .

With dk=64d_k=64 a typical logit has standard deviation 8. Gaps of that size make the softmax almost one-hot, and its Jacobian pi(δij−pj)p_i(\delta_{ij}-p_j) is then nearly zero. Dividing by dk\sqrt{d_k} brings the variance back to 1. The paper notes that unscaled dot products lose to additive attention for large dkd_k, and it gives this variance argument as the likely reason (§3.2.1, footnote).

Multi-head attention (§3.2.2).

MultiHead⁡(Q,K,V)=Concat⁡(head1,…,headh) WO,headi=Attention⁡(QWiQ, KWiK, VWiV).\operatorname{MultiHead}(Q,K,V)=\operatorname{Concat}(\text{head}_1,\dots,\text{head}_h)\,W^O,\quad \text{head}_i=\operatorname{Attention}(QW_i^Q,\,KW_i^K,\,VW_i^V).

The base model uses dmodel=512d_\text{model}=512, h=8h=8 and dk=dv=dmodel/h=64d_k=d_v=d_\text{model}/h=64. Splitting the width keeps the total cost close to one full-width head. Each head still gets its own attention pattern, so one position can gather information from several places for several reasons.

Three uses. Encoder self-attention (every token sees every token). Decoder self-attention with a causal mask: the logits of future positions are set to −∞-\infty before the softmax. Encoder–decoder attention: queries come from the decoder, while keys and values come from the encoder output.

Position. Attention by itself ignores order. The paper adds sinusoids to the embeddings, PE(pos,2i)=sin⁡(pos/100002i/dmodel)PE_{(pos,2i)}=\sin(pos/10000^{2i/d_\text{model}}) and PE(pos,2i+1)=cos⁡(pos/100002i/dmodel)PE_{(pos,2i+1)}=\cos(pos/10000^{2i/d_\text{model}}). The wavelengths form a geometric progression from 2π2\pi to 10000⋅2π10000\cdot 2\pi. For a fixed offset kk, PEpos+kPE_{pos+k} is a linear function of PEposPE_{pos} (§3.5). RoPE later turns this idea into a rotation applied to qq and kk.

Scaled dot-product attention, why it divides by the square root of d_k, and how multi-head attention splits d_model Left: one attention head as a pipeline. Queries and keys give an n by n score matrix QK transpose, which is divided by the square root of d_k, optionally masked with minus infinity for future positions, passed through a row-wise softmax, and multiplied by V. A small inset shows that with d_k equal to 64 the raw score has standard deviation 8, and after dividing by 8 it has standard deviation 1, which keeps the softmax away from saturation. Right: multi-head attention with d_model 512 splits into 8 heads of width 64, each with its own projections; the head outputs are concatenated back to 512 and mixed by an output matrix W O. One head: softmax(QKᵀ / √dₖ) · V Q K V QKᵀ (n × n) ÷ √dₖ maskfuture → −∞ row softmax weights · V each output row = weighted mix of value rows Why divide by √dₖ? q, k entries: mean 0, var 1 q·k = Σ of dₖ products → variance dₖ, std √dₖ dₖ = 64: std 8 → 1 scores (16, 8, 0): raw → (0.9997, 0.0003, 0) ÷8 → (0.67, 0.24, 0.09) Many heads, same width X (n × 512) head 1dₖ=64 head 2dₖ=64 … head 7dₖ=64 head 8dₖ=64 concat: 8 × 64 = 512 · W_O (512 × 512) each head: its own W_Q, W_K, W_V cost ≈ one head of width 512, but 8 separate attention patterns
Original sketch. Left: one head, with the √d_k rescaling worked through for d_k = 64. Right: d_model = 512 split into 8 heads of width 64 and mixed again by W_O.
  • Cost per layer (Table 1). Self-attention needs O(n2d)O(n^2 d) operations, O(1)O(1) sequential steps and O(1)O(1) maximum path length. Recurrent layers need O(nd2)O(n d^2), O(n)O(n) and O(n)O(n). Self-attention is cheaper when nn is smaller than dd, which was the usual case for sentence-level translation.
  • Translation (Table 2). On WMT14 EN–DE the base model scores 27.3 BLEU and the big model 28.4, more than 2 BLEU above earlier results, ensembles included. On EN–FR the big model reaches 41.8. Training took 12 hours (base, 100k steps) or 3.5 days (big, 300k steps) on 8 P100 GPUs.
  • Ablations (Table 3, newstest2013 dev). One head loses 0.9 BLEU against the best setting. Smaller dkd_k hurts. Bigger models help (dmodel=1024d_\text{model}=1024 gives 26.0). Removing dropout drops BLEU to 24.6. Label smoothing hurts perplexity but helps BLEU. Learned positional embeddings give nearly identical results (25.7 vs 25.8).
  • Quadratic cost. The n2n^2 term dominates for long inputs such as long-context RAG and agent traces. This motivated FlashAttention (exact, IO-aware), sparse and linear attention, and state-space models.
  • Position is an add-on. Sinusoids were justified by a hoped-for extrapolation, which the paper did not test. Length generalisation is still an open problem (see RoPE, YaRN and the long-context pages).
  • The dk\sqrt{d_k} argument is an initialisation argument. Once WQW_Q and WKW_K are trained, logit scale drifts. Later models add QK-norm or other logit controls.
  • Evaluation scope. The main results are on two translation pairs and one parsing task. That decoder-only versions of the block would scale to general LLMs was shown only later.

Questions to think through

These questions have no single right answer. Write or say your answer before you open the hints. Mark a question once you could defend your answer in a reading group.

  1. Derive / compute

    Take d_k = 64 and one query whose dot products with three keys are 16, 8 and 0. Compute the softmax weights without scaling and with the 1/√d_k scaling. Then compute ∂p₁/∂(q·k₁) in both cases, remembering that the scaled version also carries a factor 1/√d_k from the chain rule. How much larger is the scaled gradient?

    What a strong answer covers
    • Unscaled: softmax(16, 8, 0) ≈ (0.99966, 3.4e−4, 1e−7). The distribution is almost one-hot.
    • Scaled by 1/8: softmax(2, 1, 0) = (7.39, 2.72, 1)/11.11 ≈ (0.665, 0.245, 0.090).
    • Softmax Jacobian: ∂p₁/∂s₁ = p₁(1 − p₁). Unscaled ≈ 3.4e−4. Scaled ≈ 0.665 · 0.335 ≈ 0.223, times 1/8 from the chain rule ≈ 0.028.
    • The scaled gradient is about 80× larger. This is the "extremely small gradients" problem the paper's footnote points to: large dot products saturate the softmax.
  2. Mechanism

    The paper argues that the variance of q·k grows with d_k. Derive this from its assumption about q and k, and explain why it makes unscaled dot-product attention worse than additive attention only when d_k is large.

    What a strong answer covers
    • If the components of q and k are independent with mean 0 and variance 1, each product q_i k_i has mean 0 and variance 1, so the sum of d_k terms has mean 0 and variance d_k (standard deviation √d_k).
    • Logit gaps between keys therefore grow like √d_k. The softmax becomes nearly one-hot and its Jacobian p(δ − p) goes to zero, so little gradient reaches Q and K.
    • Additive attention passes scores through a tanh-based small network, which does not have this growth. For small d_k the two behave similarly, which matches the paper's description.
    • Dividing by √d_k restores unit variance, so the softmax temperature no longer depends on the head width.
  3. What if…

    Table 3 (rows A and B) varies the number of heads h while keeping compute constant, and separately shrinks d_k. Explain the pattern: h = 1 is worse than h = 8, h = 32 is also worse, and smaller d_k hurts. What does this say about what a head needs?

    What a strong answer covers
    • Row A: h = 1 (d_k = 512) gives BLEU 24.9 against 25.8 for the base h = 8. h = 16 matches the base, and h = 32 (d_k = 16) drops to 25.4.
    • One head computes a single weighted average per position, so it cannot attend to several positions for different reasons at once (the paper: averaging inhibits this).
    • Many heads shrink each head to d_k = d_model/h. With d_k = 16, the low-rank bilinear form q·k is too weak to express a sharp, useful compatibility function.
    • Row B confirms it: lowering d_k alone (16 or 32) hurts perplexity and BLEU. The paper suggests that a more sophisticated compatibility function than the dot product might help.
    • Row E: learned positional embeddings give 25.7 against 25.8, so the sinusoid choice barely matters.
  4. Design

    You are building a listwise reranker that reads a 64-token query plus 20 passages of 256 tokens each in one sequence. Compare full self-attention with restricted (block-local) self-attention of width r = 256, using Table 1 of the paper. Quantify the cost and say what you lose for cross-passage comparison.

    What a strong answer covers
    • n = 64 + 20 · 256 = 5,184 tokens. Full attention costs O(n² · d) per layer, about 2.7e7 · d score operations.
    • Restricted attention costs O(r · n · d), about 1.3e6 · d, so roughly n/r ≈ 20× cheaper.
    • The maximum path length grows from O(1) to O(n/r) ≈ 20 layers. Two passages that are far apart can only interact through many layers, which hurts listwise comparison.
    • Middle grounds: keep the query tokens global (visible to all blocks), or add a few summary tokens per passage. Validate with nDCG on a set where the best passage needs comparison with distant ones.
  5. Critique

    The √d_k argument assumes that query and key components are independent with unit variance. Which parts of a trained Transformer break this assumption, and what experiment would show whether a fixed 1/√d_k is the right temperature?

    What a strong answer covers
    • The projections W_Q and W_K are learned, so the scale of q and k drifts during training. Their components are correlated, and the means are not zero.
    • The model can also learn to undo the scaling by growing the norms of W_Q and W_K. So the fixed factor is mainly an initialisation-time fix.
    • Experiment: log the standard deviation of the logits and the attention entropy per layer during training, and compare a fixed 1/√d_k with a learned per-head temperature or with normalising q and k.
    • The claim fails if a learned temperature converges far from 1/√d_k or if training stability differs strongly between the variants.
  6. Connect

    ColBERT scores a document as Σ over query tokens of max over document tokens of q_i · d_j. Write this as a limit of a softmax attention computation and explain what the late-interaction model gives up compared with a full cross-attention reranker.

    What a strong answer covers
    • For one query token, Σ_j softmax_j(q · d_j / τ) · (q · d_j) tends to max_j q · d_j as the temperature τ goes to 0. So MaxSim is hard attention whose "values" are the scores themselves.
    • ColBERT then sums over query tokens. There is no W_V or W_O mixing and no further layers after the interaction.
    • A cross-encoder lets query and document tokens attend to each other in every layer, so the document encoding depends on the query. ColBERT encodes them separately, which is what makes offline indexing possible.
    • The trade-off is precomputation and index size against expressiveness. The softmax version stays differentiable for all keys, while hard max sends gradient only to the argmax token.

Done with this page?

Status