Search

Search papers and lessons

Attention Is All You Need

Ashish Vaswani, Noam Shazeer, Niki Parmar et al. · 2017

The Transformer translates text using only attention, with no recurrence or convolution, which lets training run in parallel and reached a new best BLEU score on English to German.

On this page

  • Colour = topic mix
  • Calculus
  • Probability
  • Architectures
  • Neural network basics
  • Linear algebra
  • Discrete math
  • Sign in to see your progress

TL;DR

Sequence models such as translators used recurrent networks, which read a sentence one token at a time and so cannot be trained in parallel across the sentence. The Transformer drops recurrence and convolution entirely. It builds every representation from attention over the whole sequence, plus small feed-forward layers, and adds position information by hand. It trained faster and reached 28.4 BLEU on English to German translation, beating the best previously reported results, including ensembles.

Where you'll see it: the architecture under nearly every modern language model, from translators to chat assistants, and under vision and speech models that reuse its blocks.

The problem

Before 2017, the strongest machine translation systems were encoder-decoder networks built from recurrent neural networks, often with an attention layer connecting the two halves. The encoder read the source sentence step by step, and the decoder wrote the target one token at a time. Attention, introduced for translation by Bahdanau and colleagues, let the decoder look back at the encoder's states instead of relying on one fixed summary vector.

The recurrence was the bottleneck. Step tt depends on step t−1t - 1, so a long sentence needs a long chain of sequential operations, and a GPU cannot compute them at once. Training was slow, and information from early words had to survive many steps to reach later ones. The authors wanted an architecture whose sequential cost did not grow with sentence length.

Key idea

Keep the encoder-decoder layout and the attention, and remove the recurrence. If attention can connect any two positions directly, then one layer can relate the first word to the last word with a fixed number of steps, no matter how long the sentence is. Every position can be computed at the same time, which is what GPUs are good at.

Think of a meeting where everyone can hear everyone at once, instead of a relay where each person must wait for the one before. Each word asks, in parallel, which other words matter for understanding it, and gathers their information in proportion to how relevant they are.

The price is that attention on its own does not know word order. So the paper adds a position signal to each input embedding, a sinusoidal positional encoding, and keeps it simple.

flowchart TB
    A[Source tokens] --> B[Embedding plus positional encoding]
    B --> C[Encoder stack, 6 layers of self-attention and feed-forward]
    C --> D[Decoder stack, 6 layers of masked self-attention, cross-attention and feed-forward]
    E[Shifted target tokens] --> F[Embedding plus positional encoding]
    F --> D
    D --> G[Linear layer and softmax over the vocabulary]

The method

Encoder and decoder stacks

The encoder is a stack of N=6N = 6 identical layers. Each layer has two sub-layers: multi-head self-attention, then a position-wise feed-forward network. Each sub-layer is wrapped in a residual connection followed by layer normalization, so the output of each sub-layer is LayerNorm(x+Sublayer(x))\mathrm{LayerNorm}(x + \mathrm{Sublayer}(x)). All sub-layers and the embeddings produce vectors of size dmodel=512d_{\text{model}} = 512, which is what makes the residual sums possible.

The decoder is also six identical layers, with a third sub-layer that attends over the encoder output. This is cross-attention, and it is how the decoder reads the source sentence. The decoder's self-attention is masked so that position ii can use only outputs at positions less than ii. This is what makes the model autoregressive: during training, all positions are computed in parallel, but the mask stops each one from seeing the answer to its own prediction.

Scaled dot-product attention

Each token is projected into a query, a key and a value. The output for a query is a weighted sum of the values, where each weight comes from how well that query matches a key. For matrices of queries QQ, keys KK and values VV, the paper computes

Attention(Q,K,V)=softmax(QKTdk)V\mathrm{Attention}(Q, K, V) = \mathrm{softmax}\left( \frac{Q K^{T}}{\sqrt{d_k}} \right) V

The dot products QKTQK^T score every query against every key in one matrix multiply, which dot-product attention makes fast. The Softmax turns each row of scores into weights that sum to one.

The division by dk\sqrt{d_k} is there for a reason the paper explains. If the components of a query and a key are independent with mean 0 and variance 1, their dot product over dkd_k components has variance dkd_k. For large dkd_k the scores grow large, the softmax saturates, and its gradients become tiny. Dividing by dk\sqrt{d_k} brings the variance back to 1.

Worked numbers. Take dk=64d_k = 64. An unscaled dot product of two random unit-variance vectors has standard deviation 64=8\sqrt{64} = 8. After dividing by 64=8\sqrt{64} = 8, its standard deviation is 1. A softmax over raw scores with spread around 8 would put almost all its weight on one key, while spread around 1 keeps the weights informative.

Multi-head attention

Instead of one attention function on dmodeld_{\text{model}}-dimensional vectors, the model runs h=8h = 8 attention heads in parallel. Each head first projects the queries, keys and values to dimension dk=dv=dmodel/h=64d_k = d_v = d_{\text{model}} / h = 64 with its own learned matrices. The head outputs are concatenated and projected once more:

MultiHead(Q,K,V)=Concat(head1,…,headh) WO\mathrm{MultiHead}(Q, K, V) = \mathrm{Concat}(\mathrm{head}_1, \ldots, \mathrm{head}_h) \, W^{O}

where headi=Attention(QWiQ,KWiK,VWiV)\mathrm{head}_i = \mathrm{Attention}(Q W_i^{Q}, K W_i^{K}, V W_i^{V}). Because each head works in 64 dimensions, the total cost is about the same as one attention with the full 512 dimensions. The point of several heads is that each can attend to a different kind of relation in a different subspace, which a single averaged attention cannot do.

The three attention uses are: self-attention in the encoder, where every position attends to every earlier and later position; masked self-attention in the decoder, which sees only earlier positions; and cross-attention, where decoder queries attend to encoder keys and values.

Position-wise feed-forward network

Each layer also applies a two-layer network to each position separately, with the same weights at every position:

FFN(x)=max⁡(0,xW1+b1)W2+b2\mathrm{FFN}(x) = \max(0, x W_1 + b_1) W_2 + b_2

The input and output have dimension 512, and the inner layer has dimension 2048. Attention mixes information across positions; this network transforms each position on its own.

Embeddings, softmax, and positional encoding

Input and output tokens are turned into vectors by learned embeddings. The two embedding layers and the final pre-softmax linear layer share one weight matrix, and the embedding weights are multiplied by dmodel\sqrt{d_{\text{model}}}.

Because there is no recurrence, order must be injected. The paper adds a fixed signal to each embedding, with each dimension a sinusoid of a different wavelength:

PE(pos,2i)=sin⁡(pos/100002i/dmodel),PE(pos,2i+1)=cos⁡(pos/100002i/dmodel)PE_{(pos, 2i)} = \sin\left( pos / 10000^{2i / d_{\text{model}}} \right), \qquad PE_{(pos, 2i+1)} = \cos\left( pos / 10000^{2i / d_{\text{model}}} \right)

The wavelengths form a geometric progression from 2π2\pi to 10000⋅2π10000 \cdot 2\pi. The authors chose this because, for any fixed offset kk, PEpos+kPE_{pos+k} is a linear function of PEposPE_{pos}, which should make relative positions easy to learn. Learned position embeddings gave nearly the same results, and the sinusoidal form may generalize to sentences longer than those seen in training. See Positional Encoding for the general idea.

Training setup

The authors trained on the WMT 2014 English to German data, about 4.5 million sentence pairs, encoded with byte-pair encoding into a shared vocabulary of about 37,000 tokens. English to French used a larger 36 million sentence dataset and a 32,000 word-piece vocabulary. Batches held about 25,000 source tokens and 25,000 target tokens.

The optimizer was Adam with β1=0.9\beta_1 = 0.9, β2=0.98\beta_2 = 0.98 and ϵ=10−9\epsilon = 10^{-9}. The learning rate rose linearly for 4,000 warmup steps and then fell with the inverse square root of the step number. Regularization used dropout with rate 0.1 for the base model and 0.3 for the big English to German model, plus label smoothing with value 0.1, which makes the model less certain and so raises perplexity but improved accuracy and BLEU. Label smoothing is not covered in the lessons linked here.

Training the base model took 100,000 steps, about 12 hours on 8 NVIDIA P100 GPUs. The big model took 300,000 steps, about 3.5 days.

Results

Why self-attention. The paper's Table 1 compares layer types on three measures. A self-attention layer costs O(n2⋅d)O(n^2 \cdot d) per layer, has O(1)O(1) sequential operations, and has O(1)O(1) maximum path length between any two positions. A recurrent layer costs O(n⋅d2)O(n \cdot d^2), needs O(n)O(n) sequential operations, and has O(n)O(n) path length. Self-attention is cheaper than recurrence when the sequence length nn is smaller than the representation size dd, which covers most sentences in translation data, and it is far more parallel.

Translation. On WMT 2014 English to German, the big Transformer reaches 28.4 BLEU, more than 2.0 BLEU above the best previous results, including ensembles. The base model, at 27.3 BLEU, already beats all previously published models and ensembles at a fraction of the training cost. The best earlier result in Table 2 is the ConvS2S ensemble at 26.36 BLEU. The big model's training cost is about 2.3⋅10192.3 \cdot 10^{19} floating point operations, against 7.7⋅10197.7 \cdot 10^{19} for that ensemble, and the base model's is 3.3⋅10183.3 \cdot 10^{18}.

English to French: text and table disagree. Section 6.1 says the big model scores 41.0 BLEU, while Table 2 and the abstract say 41.8. The table value is the one that appears in the abstract, so it is the likelier intended number, but the paper does not say which is right. The choice matters for the claim. At 41.0 the model beats every single model (the best is MoE at 40.56) but not the ConvS2S ensemble (41.29 in Table 2). At 41.8 it beats that ensemble too. The abstract's claim is only "single-model state of the art", which holds either way. The base model scores 38.1 on English to French, below several earlier systems. The paper says the big model needed less than a quarter of the previous state-of-the-art's training cost: 2.3⋅10192.3 \cdot 10^{19} against 1.41.4 to 1.5⋅10201.5 \cdot 10^{20} for the best single models.

Inference used beam search with beam size 4 and a length penalty of 0.6, and the authors averaged the last 5 checkpoints for base models and the last 20 for big models.

Ablations and parsing. Table 3 varies the number of heads, the key size, model size and dropout on the English to German development set. With computation held constant, one head scores 24.9 BLEU on the development set against 25.8 for eight (0.9 worse), and 32 heads drop back to 25.4. Shrinking the key size dkd_k also hurts (25.1 to 25.4 against 25.8), while swapping sinusoids for learned positions gives 25.7, nearly the same. The same architecture, a 4-layer model, was also trained on English constituency parsing, with little task tuning. It scored 91.3 F1 on WSJ section 23 when trained on the WSJ alone and 92.7 in a semi-supervised setting. The paper says this beats all earlier reported models except the Recurrent Neural Network Grammar. Table 4 is less flattering: Dyer et al.'s discriminative parser trained on WSJ only scores 91.7, above the Transformer's 91.3, and the multi-task model of Luong et al. (93.0) is above its 92.7 as well as the generative RNN Grammar (93.3). So the text overstates the table, and "competitive" is the accurate word.

Why it mattered

The paper showed that attention alone was enough for state-of-the-art sequence transduction, and that removing recurrence made training far faster. The block it introduced, with self-attention, feed-forward layers, residual connections, and layer normalization, became the default backbone for language models, and later for vision and audio models. Most of the models in the rest of this graph inherit its design, which is why the lessons on attention and the Transformer concept are the places to read the mechanics in more detail.

The paper also set the pattern that followed: a parallel-friendly architecture scaled up with more data and compute, rather than a cleverer recurrent cell. Its positional encodings, its scaled attention and its layer norm placement have been revised by later work, but the overall shape held.

Reading guide

Read the paper in this order.

Check yourself

QuestionWhat does the Transformer remove compared with the earlier encoder-decoder translation models, and what does it add to replace the ordering that recurrence used to provide?Show answer
It removes recurrence and convolution, so every position is computed from attention over the whole sequence in parallel. It adds positional encodings to the input embeddings, because attention alone does not know the order of tokens.
QuestionTake d_k = 64. An unscaled dot product of two random vectors whose components are independent with mean 0 and variance 1 has what standard deviation, and what is it after the paper's scaling?Show answer
The dot product has variance d_k, so its standard deviation is the square root of 64, which is 8. Dividing by the square root of d_k, which is 8, brings the standard deviation back to 1.
QuestionThe model has d_model = 512 and h = 8 heads. What is the dimension of each head's queries, keys and values, and why is the total cost similar to a single head with the full dimension?Show answer
Each head uses d_k = d_v = 512 / 8 = 64. Each of the 8 heads works in 64 dimensions, so the total work across heads is about the same as one attention over 512 dimensions.
QuestionWhy does a self-attention layer have a smaller maximum path length than a recurrent layer, and when does the paper say self-attention is faster per layer?Show answer
In self-attention every position connects to every other in one step, so the maximum path length is O(1). In a recurrent layer information must pass through up to n steps, so it is O(n). Self-attention is faster per layer when the sequence length n is smaller than the representation size d, which is common for sentences.

Sources

Read the full paper

Ashish Vaswani, Noam Shazeer, Niki Parmar et al., 2017. arXiv:1706.03762