Skip to content

Reading "Attention Is All You Need": how the Transformer differs from earlier translation models, and why it matters

A reading of the 2017 paper "Attention Is All You Need" by Vaswani et al., from its abstract and full text (version 7): how the Transformer and its attention work, the translation and parsing results the paper reported, and how to read those numbers.

The Transformer is a sequence transduction model built on attention alone, with no recurrence and no convolution. In the 2017 paper "Attention Is All You Need," Vaswani et al. reported that it beat earlier models on two machine translation tasks. They also reported that it parallelized more readily and took far less time to train, and that it worked for English constituency parsing. The paper's central result is that removing recurrence and convolution still delivered better translation quality together with faster training. The numbers and claims in this article come from the abstract on the paper's arXiv page (https://arxiv.org/abs/1706.03762) and the full text of the PDF (https://arxiv.org/pdf/1706.03762, version 7).

The dominant models of the time were encoder-decoders built on RNNs or CNNs

According to the paper, the dominant sequence transduction models at the time were complex RNNs or CNNs arranged as an encoder and a decoder.

Words joined to other words by weighted lines, an image of attention
An image of how attention works

Sequence transduction means taking in a sequence, such as a string of words, and producing another sequence. Machine translation from an English sentence to a German one is the standard example. An encoder-decoder splits the job in two: the encoder turns the input sentence into a numerical representation, and the decoder produces the output sentence from that representation. A recurrent neural network (RNN) reads words in order from the start, handing the result of each step on to the next. That hand-off is called recurrence. A convolutional neural network (CNN) extracts features by sliding the same small filter repeatedly across neighbouring parts of the input. Applying the filter is called convolution.

The best-performing models of the time connected the encoder and decoder with attention. Attention computes weights for how much each part of the input should count when producing an output, then gathers the input's information using those weights. The paper's introduction explains that attention lets a model handle dependencies regardless of their distance in the sequence. It adds that, with only a few exceptions, attention had been used together with RNNs.

The Transformer is built from attention alone, dropping recurrence and convolution

The Transformer the authors proposed is a network based solely on attention, with no recurrence or convolution at all. Attention also takes over the core work of reading in the sentence, which RNNs and CNNs used to do. The paper's title, "Attention Is All You Need," can be read as a description of that design. The authors call the Transformer a "new simple" architecture and describe earlier models as "complex." "Simple" is the authors' own assessment.

The encoder and the decoder each stack six identical layers

The Transformer's encoder and decoder are each a stack of N=6 identical layers (section 3.1 of the paper).

Each encoder layer has two sub-layers. The first is multi-head self-attention, explained in a later section. The second is a position-wise fully connected feed-forward network, which applies the same computation separately to the vector at each position in the sentence: two linear transformations with a ReLU activation in between (section 3.3). Its input and output have dimension d_model=512, and its inner layer has dimension d_ff=2048. d_model is the length of the vector the model uses to represent one word. The embedding layers and every sub-layer produce outputs of this length.

Each sub-layer has a residual connection and layer normalization around it. A residual connection adds a sub-layer's input straight back onto its output. Layer normalization (LayerNorm) evens out the spread of values in a vector. The paper writes each sub-layer's output as LayerNorm(x + Sublayer(x)): take the input x, add the sub-layer's result, and normalize the sum.

On top of those two sub-layers, each decoder layer has a third that applies attention over the encoder's output. The decoder is auto-regressive: it produces the output one word at a time, feeding the words it has already produced back in as input. Its self-attention is therefore masked so that no position can see the positions after it. Together with shifting the output embeddings by one position, this makes the prediction at position i depend only on outputs before i.

Input and output words are turned into d_model-dimensional vectors by learned embeddings. The decoder's output is turned into probabilities for the next word by a linear transformation and a softmax (section 3.4). Softmax is a function that turns a list of numbers into a list of probabilities that sum to 1.

The Transformer's encoder and decoder: a residual connection and LayerNorm around each sub-layer, N=6 layers each
The Transformer's encoder and decoder (based on section 3.1 of the paper)

Attention weighs values by the dot product of queries and keys

The Transformer's attention is called scaled dot-product attention. It sets weights from the dot products of queries and keys, then sums the values using those weights (section 3.2.1).

Queries, keys and values are all vectors. Each position being attended to holds one key and one value, and the better a query matches a key, the more that position's value contributes to the output. The formula is softmax(QK^T/√d_k)V. Q, K and V are matrices that stack many queries, keys and values, and d_k is the dimension of the queries and keys. The computation runs in this order. First, QK^T gives the dot product of every query with every key. Next, the result is divided by √d_k, and the softmax makes each query's weights sum to 1. Finally, the rows of V are summed using those weights to give the output.

The division by √d_k is there because dot products grow too large when d_k is large. Footnote 4 explains that if each component of q and k is an independent random variable with mean 0 and variance 1, their dot product has mean 0 and variance d_k. The authors suspect that large dot products push the softmax into regions where its gradients are extremely small. A gradient is the quantity that tells training which way, and how far, to adjust the parameters.

The other common approach is additive attention, which scores how well a query matches a key with a feed-forward network that has a single hidden layer. According to the paper, the two have similar theoretical complexity. Dot-product attention, though, can be implemented with highly optimized matrix multiplication code, so in practice it is much faster and uses less memory. The paper says the two perform similarly for small d_k, while for large d_k additive attention did better than dot-product attention without scaling.

Self-attention is attention in which the queries, keys and values all come from the same place. The Transformer uses attention in three ways (section 3.2.3). The first is encoder-decoder attention, where the queries come from the previous decoder layer and the keys and values come from the encoder's output. The second is self-attention in the encoder, where all three come from the output of the previous encoder layer and each position can attend to every position in that layer. The third is self-attention in the decoder, where each position can attend to positions up to and including itself. Connections that must not be seen are masked by setting their values to −∞ before the softmax.

The computation of scaled dot-product attention: softmax(QK^T/√d_k)V
The steps of scaled dot-product attention (based on section 3.2.1 of the paper)

Multi-head attention runs eight attentions in parallel and joins them

Multi-head attention projects the queries, keys and values h different ways with separate learned linear transformations, and runs attention on each projection in parallel (section 3.2.2). The h results are concatenated and projected once more. Each of these attentions is called a head.

The paper uses h=8, with each head's dimension set to d_k=d_v=d_model/h=64. Because each head is smaller, the authors write, the total computational cost is about the same as a single head at full dimension. The aim is to let the model attend at once to information from different representation subspaces at different positions. The paper explains that with a single head, averaging works against this.

Row (A) of Table 3 varies the number of heads and their dimension while holding the amount of computation constant. On the English-to-German development set (newstest2013), a single head scored 0.9 BLEU below the best setting, and quality also dropped with too many heads.

Positional encodings add information about word order

Since the Transformer has neither recurrence nor convolution, it needs position information added separately in order to use word order (section 3.5). The paper adds "positional encodings" to the input embeddings at the bottom of the encoder and decoder stacks. A positional encoding has the same dimension d_model as the embeddings, so the two can simply be summed.

The paper builds its positional encodings from sine and cosine functions of different frequencies. With pos for the position and i for the dimension index, even dimensions are sin(pos/10000^(2i/d_model)) and odd dimensions are cos(pos/10000^(2i/d_model)). Each dimension corresponds to one sinusoid, and the wavelengths form a geometric progression from 2π to 10000·2π.

The authors give a hypothesis for choosing this function. For any fixed offset k, the encoding of position pos+k can be written as a linear function of the encoding of position pos, so the model should find it easy to learn to attend by relative position. They also tried learned positional embeddings instead, and row (E) of Table 3 shows nearly identical results. The authors chose the sinusoidal version because it may let the model handle sequences longer than those seen in training.

Without recurrence, the computation within a sentence can run all at once

The Transformer parallelizes well because it computes every position at the same time, without waiting for the previous position. Parallelization means running several computations simultaneously.

According to the paper's introduction, an RNN computes the hidden state h_t at position t from the previous hidden state h_{t−1} and the input at position t. This is inherently sequential, so computation cannot be parallelized within a single training example. The paper notes that this constraint becomes critical at longer sequence lengths, because memory limits make it harder to batch many examples together.

In section 4, Table 1 compares layer types on three measures: computational complexity per layer, the number of sequential operations, and maximum path length. Here n is the sequence length, d the representation dimension, and k the kernel width of a convolution. Self-attention has a per-layer complexity of O(n²·d), O(1) sequential operations, and a maximum path length of O(1). An RNN has O(n·d²), O(n) and O(n). A CNN has O(k·n·d²), O(1) and O(log_k(n)).

O(1) means constant regardless of sequence length, and O(n) means growing in proportion to it. Maximum path length is the length of the path a signal travels through the network between any two positions. The paper argues that shorter paths make it easier to learn dependencies between distant words. On complexity, the authors write that self-attention is faster than recurrence when the sequence length n is smaller than the dimension d, which is most often the case for sentence representations in state-of-the-art translation models.

Training used eight P100 GPUs: 12 hours for the base model and 3.5 days for the big model

The authors trained their models on one machine with eight NVIDIA P100 GPUs (section 5.2). The standard base model took about 0.4 seconds per step for 100,000 steps, 12 hours in all. The larger big model took 1.0 second per step for 300,000 steps, 3.5 days.

The training data was WMT 2014: about 4.5 million sentence pairs for English-German and 36 million sentences for English-French. The optimizer was Adam. The learning rate rose linearly over the first 4,000 steps (the warmup) and then fell in proportion to the inverse square root of the step number. For regularization, the base model used dropout at a rate of 0.1 and label smoothing with a value of 0.1. The paper notes that label smoothing hurts perplexity (a measure of how uncertain the predictions are), since the model learns to be less sure, but improves accuracy and BLEU.

On English-to-German, the big model scored 28.4 BLEU, more than 2 BLEU above the previous best

In their 2017 paper, Vaswani et al. reported that the Transformer (big) scored 28.4 BLEU on the WMT 2014 English-to-German translation task. That is more than 2.0 BLEU above the best previously reported results, ensembles included.

BLEU is a metric that scores machine translation against human reference translations; a higher score means closer to the references. An ensemble combines the outputs of several models into one result. The earlier English-German scores in the paper's Table 2 are ByteNet 23.75, GNMT + RL 24.6, ConvS2S 25.16, MoE 26.03, the GNMT + RL ensemble 26.30, and the ConvS2S ensemble 26.36. The paper states that even the base model, at 27.3, surpassed all previously published models and ensembles.

Table 2 also gives training cost as the number of floating point operations (FLOPs). For English-German, the Transformer's figures are 3.3×10^18 for the base model and 2.3×10^19 for the big model. Across both English-German and English-French, the earlier models in Table 2 range from 9.6×10^18 to 1.2×10^21. Footnote 5 explains that these counts are estimates: training time, multiplied by the number of GPUs, multiplied by an estimate of each GPU's sustained single-precision throughput. For the P100 the paper uses 9.5 TFLOPS.

BLEU on WMT 2014 English-to-German (newstest2014): earlier models compared with the Transformer
BLEU on WMT 2014 English-to-German (based on Table 2 of the paper)

The English-to-French BLEU appears in the paper as both 41.8 and 41.0

For the WMT 2014 English-to-French translation task, the 2017 paper by Vaswani et al. gives the Transformer (big) a BLEU of 41.8 in the abstract and in Table 2. Section 6.1 of the text, however, says 41.0. Since the paper disagrees with itself, this article does not pick one and shows both.

This result compares single models. The abstract calls it "a new single-model state-of-the-art," and section 6.1 says it outperforms all previously published single models. Among the earlier English-French scores in Table 2, the best single model is MoE at 40.56, and including ensembles the best is the ConvS2S ensemble at 41.29. The English-German result is compared against ensembles too, so the two tasks are compared on different terms.

On training cost, section 6.1 says it was less than a quarter of the previous state-of-the-art model's. The training time in the abstract, 3.5 days on eight GPUs, matches the big model's setup in section 5.2.

On constituency parsing, it scored F1 91.3 trained on WSJ alone and 92.7 semi-supervised

In their 2017 paper, Vaswani et al. reported F1 scores for English constituency parsing on Section 23 of the WSJ. Trained on WSJ data alone, the model scored 91.3; in the semi-supervised setting, 92.7 (Table 4). The authors say this beat every previously reported model except the Recurrent Neural Network Grammar.

Constituency parsing splits a sentence into groups such as noun phrases and verb phrases and represents its structure as a tree of nested groups. The paper calls it a hard task because the output is subject to strong structural constraints and is much longer than the input. F1 is a score for how closely the parse trees a model produces match the correct ones.

The experiment used a 4-layer Transformer with d_model=1024. The training data was about 40,000 sentences from the Wall Street Journal (WSJ) portion of the Penn Treebank, and the semi-supervised setting also used a larger corpus of about 17 million sentences. Apart from dropout, learning rates and beam size, chosen with a small number of experiments, the settings matched the English-German base model. Table 4 also lists results from other training approaches: 93.0 for the multi-task model of Luong et al. (2015) and 93.3 for the generative model of Dyer et al. (2016).

Read the numbers as what the authors reported in their 2017 paper

The 28.4 BLEU, and the 41.8 or 41.0 BLEU, are numbers the paper's authors reported from their own experiments. "New state-of-the-art" refers to the work the 2017 paper compared against, and does not include results published since. These numbers therefore do not describe where machine translation stands today. When citing them elsewhere, saying who reported them, when, and on what (for example, "the value Vaswani et al. reported in 2017 on the WMT 2014 English-to-French task") avoids misunderstanding. For the English-French score, it is safest to also mention that the paper gives two values, 41.8 and 41.0.

The paper is on arXiv as arXiv:1706.03762. It was first submitted on June 12, 2017, and the version used here is version 7 (v7), revised on August 2, 2023. The eight authors are Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin. The PDF identifies it as a NIPS 2017 paper, and the arXiv page lists 15 pages and 5 figures.

An explanation of "Attention Is All You Need" (arXiv:1706.03762) by Vaswani et al., based on the abstract on the paper's arXiv page and the full text of the PDF (version 7). It is not a translation of the paper and does not speak for its authors. The numbers are those the authors reported.

Read next

All insights