Attention Is All You Need

TLDR#

The Transformer is an encoder-decoder built only from attention and feed-forward layers, with no recurrence or convolution. Any two positions in a layer are one step apart and all positions are computed in parallel, where an RNN needs O(n)O(n) sequential steps. It reached 28.4 BLEU on WMT 2014 English-German, more than 2 BLEU above the best earlier result including ensembles, and 41.8 on English-French, after 3.5 days of training on eight P100 GPUs.1

Method#

The Transformer: an encoder stack on the left feeding a decoder stack on the right

Figure 1 of Vaswani et al. (2017), reproduced with attribution as the paper permits; white background added.

Stacks#

The encoder and the decoder each have N=6N = 6 identical layers with dmodel=512d_{\text{model}} = 512 (§3.1). Every sub-layer is wrapped in a residual connection followed by layer normalization:

LayerNorm(x+Sublayer(x))\mathrm{LayerNorm}(x + \mathrm{Sublayer}(x))
  • Encoder layer: self-attention, then a feed-forward network.
  • Decoder layer: masked self-attention, attention over the encoder output, then a feed-forward network. The mask sets illegal connections to −∞-\infty before the softmax. Together with output embeddings shifted by one position, it lets position ii depend only on outputs before ii.

Attention#

The basic operation is scaled dot-product attention:

Attention(Q,K,V)=softmax ⁣(QK⊤dk)V\mathrm{Attention}(Q, K, V) = \mathrm{softmax}\!\left(\frac{QK^\top}{\sqrt{d_k}}\right) V

If the components of a query and a key are independent with mean 0 and variance 1, their dot product has variance dkd_k. The authors suspect that for large dkd_k this pushes the softmax into regions with tiny gradients, hence the scaling by dk\sqrt{d_k} (§3.2.1).

Multi-head attention runs h=8h = 8 of these in parallel with dk=dv=dmodel/h=64d_k = d_v = d_{\text{model}} / h = 64, so the total cost stays close to one full-width head (§3.2.2). It appears in three places (§3.2.3):

Where Queries from Keys and values from
Encoder self-attention previous encoder layer previous encoder layer
Decoder self-attention (masked) previous decoder layer previous decoder layer
Encoder-decoder attention previous decoder layer encoder output

Feed-forward, embeddings and positions#

The feed-forward network is applied to each position separately, with inner width dff=2048d_{ff} = 2048 (§3.3):

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

Both embedding layers and the pre-softmax projection share one weight matrix, multiplied by dmodel\sqrt{d_{\text{model}}} in the embedding layers (§3.4).

With no recurrence or convolution, the model has no other source of token order, so sinusoidal positional encodings are added to the embeddings (§3.5):

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

For a fixed offset kk, PEpos+kPE_{pos+k} is a linear function of PEposPE_{pos}, which the authors hypothesized would make attending by relative position easy to learn.

Why self-attention#

The argument in §4 compares layer types by cost, parallelism and how far a signal travels between two positions (Table 1). Here nn is the sequence length, dd the representation dimension, kk the kernel size and rr the neighborhood size.

Layer Complexity per layer Sequential operations Maximum path length
Self-attention O(n2⋅d)O(n^2 \cdot d) O(1)O(1) O(1)O(1)
Recurrent O(n⋅d2)O(n \cdot d^2) O(n)O(n) O(n)O(n)
Convolutional O(k⋅n⋅d2)O(k \cdot n \cdot d^2) O(1)O(1) O(log⁡kn)O(\log_k n)
Restricted self-attention O(r⋅n⋅d)O(r \cdot n \cdot d) O(1)O(1) O(n/r)O(n/r)

Per layer, self-attention is cheaper than recurrence only while n<dn < d.

Experiment#

Setup#

  • Data: WMT 2014 English-German, about 4.5M sentence pairs; English-French, 36M sentences (§5.1).
  • Batches: about 25,000 source and 25,000 target tokens (§5.1).
  • Models: base as described above, 65M parameters; big with dmodel=1024d_{\text{model}} = 1024, dff=4096d_{ff} = 4096 and h=16h = 16, 213M parameters (Table 3).
  • Compute: one machine with 8 P100 GPUs. Base trains for 100K steps (12 hours), big for 300K steps (3.5 days) (§5.2).
  • Optimizer: Adam with β1=0.9\beta_1 = 0.9, β2=0.98\beta_2 = 0.98, ϵ=10−9\epsilon = 10^{-9}. The learning rate rises linearly for 4,000 warm-up steps, then falls with the inverse square root of the step (§5.3).
  • Regularization: dropout 0.1 for base, 0.3 for big (0.1 on English-French); label smoothing 0.1 (§5.4, §6.1, Table 3).

Results#

Test results on newstest2014 (Table 2). Training cost is the authors' estimate: training time × GPUs × sustained FLOPS of each GPU.

Model BLEU EN-DE BLEU EN-FR FLOPs EN-DE FLOPs EN-FR
GNMT + RL 24.6 39.92 2.3⋅10192.3 \cdot 10^{19} 1.4⋅10201.4 \cdot 10^{20}
ConvS2S 25.16 40.46 9.6⋅10189.6 \cdot 10^{18} 1.5⋅10201.5 \cdot 10^{20}
MoE 26.03 40.56 2.0⋅10192.0 \cdot 10^{19} 1.2⋅10201.2 \cdot 10^{20}
ConvS2S ensemble 26.36 41.29 7.7⋅10197.7 \cdot 10^{19} 1.2⋅10211.2 \cdot 10^{21}
Transformer (base) 27.3 38.1 3.3⋅10183.3 \cdot 10^{18} 3.3⋅10183.3 \cdot 10^{18}
Transformer (big) 28.4 41.8 2.3⋅10192.3 \cdot 10^{19} 2.3⋅10192.3 \cdot 10^{19}

The English-French score is inconsistent inside the paper: the abstract and Table 2 of arXiv v7 give 41.8, while §6.1 gives 41.0.

Takeaway#

  • The gain is parallelism plus short paths. Self-attention trades a quadratic cost in nn for constant sequential depth and constant path length. That suits sentences, where n<dn < d; for long inputs the first row of Table 1 becomes the bottleneck. The authors already name local, restricted attention for images, audio and video as future work (§7).
  • "A fraction of the cost" depends on the comparison. On English-German, big costs as much as a single GNMT + RL (2.3⋅10192.3 \cdot 10^{19}) and more than ConvS2S. The large savings are for base on English-German, for big on English-French, and against ensembles. Base itself trails the earlier single models on English-French (38.1).
  • Order is an add-on. Attention itself ignores position, and learned and sinusoidal encodings score nearly the same (Table 3, row E). Sinusoids were kept because they might extrapolate to longer sequences, which the paper does not test.
  • Perplexity and BLEU can disagree. Label smoothing makes perplexity worse and BLEU better (§5.4), so the choice depends on which metric matters.
  • Parallel training, sequential generation. The decoder still emits one token at a time; making generation less sequential is listed as a research goal (§7).

Footnotes#

  1. Vaswani et al., "Attention Is All You Need", NIPS 2017, arXiv:1706.03762v7. Every section, table and figure number on this page refers to this version. ↩