All papersFoundations Classic
The Transformer: AI that reads with attention Paper: Attention Is All You Need
Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, Illia Polosukhin · NIPS 2017 (31st Conference on Neural Information Processing Systems) · Posted 12 Jun 2017 · 14 min read · arXiv 1706.03762
1 The problem Show in original Older models read a sentence one word at a time. That is slow, because each step waits for the step before. Far apart words are hard to link. 28.4 BLEU on English to German, more than 2 BLEU above the old best.
2 What they tested Show in original The authors built the Transformer , a model with only attention. They tested it on two translation tasks. They also tested it on English parsing . They changed parts of the model to see what matters. 3 What they found Show in original It set a new best score on both translation tasks. English to French: 41.8 BLEU after 3.5 days on 8 GPUs. It cost a small part of the training cost of older models. It also worked well on parsing. In a chart The Transformer beats every older model on English to German From Table 2 0 10 20 30 BLEU score on English to German newstest2014 ByteNet 23.75 BLEU GNMT + RL 24.60 BLEU ConvS2S 25.16 BLEU MoE 26.03 BLEU ConvS2S Ensemble 26.36 BLEU Transformer (base) 27.30 BLEU Transformer (big) 28.40 BLEU
Hover, tap or focus a bar to read its exact value.
Show as table Model BLEU ByteNet 23.75 GNMT + RL 24.60 ConvS2S 25.16 MoE 26.03 ConvS2S Ensemble 26.36 Transformer (base) 27.30 Transformer (big) 28.40
5 Watch out Show in original The paper is from 2017 . It tests translation and parsing only. Attention cost grows with the square of the text length. The authors note the model needs a way to know word order. Section 6.1 says 41.0 BLEU for English to French. Table 2 says 41.8. Jump to A The abstract1 Introduction2 Background3 Model architecture3.1 Encoder and decoder stacks3.2 Attention3.3 Position-wise feed-forward networks3.4 Embeddings and softmax3.5 Positional encoding4 Why self-attention5 Training6.1 Results: machine translation6.2 Results: model variations6.3 Results: English constituency parsing7 ConclusionA Appendix: attention visualizations (summary)W Words to knowEvery detail from the paper Cards follow the paper's own order. Dotted words link to Words to know. Numbers match the paper.
A The abstract Show in original The idea The authors propose the Transformer . It is based only on attention . It drops recurrence and convolutions entirely. The results Two translation tasks show better quality and faster training. 28.4 BLEU on WMT 2014 English to German.That is over 2 BLEU above the best results, including ensembles. 41.8 BLEU on English to French. This is a new single-model best.Training took 3.5 days on eight GPUs. That is a small fraction of the cost of the best models in the literature. Beyond translation The Transformer also works on English constituency parsing. It works with large and with limited training data. 1 Introduction Show in original The old approach Recurrent neural networks were the best for sequence tasks. This includes long short-term memory and gated recurrent networks. The tasks are language modeling and machine translation. The slow part A recurrent model works along the positions of the input and output. It makes a hidden state at step t. That state depends on the previous state and the input at t. So the work is sequential . You cannot run the steps of one example in parallel. This matters more for long sequences, because memory limits batching. What was tried Factorization tricks and conditional computation made models faster. Conditional computation also made them better. The basic limit of sequential computation stayed. Attention before Attention lets a model link words no matter how far apart . But in almost all cases it ran together with a recurrent network. This paper The Transformer uses only attention to link input and output. It allows far more parallel work. It reached a new best translation quality. That took as little as twelve hours on eight P100 GPUs. 2 Background Show in original Other fast models The Extended Neural GPU, ByteNet and ConvS2S also cut sequential work. They all use convolutional networks as the building block. They compute hidden states for all positions in parallel. The distance problem In these models, the work to link two far positions grows with distance. It grows linearly for ConvS2S and logarithmically for ByteNet. So far apart links are harder to learn. In the Transformer it is a constant number of operations. The cost of that Averaging attention-weighted positions lowers effective resolution. The authors fix this with multi-head attention . Self-attention Self-attention relates positions of one sequence to each other.It builds a representation of that sequence. It already worked in reading comprehension, summaries, entailment and sentence representations. Memory networks End-to-end memory networks use recurrent attention. They work on simple question answering and language modeling. The claim The Transformer is the first transduction model using only self-attention . It uses no sequence-aligned RNNs and no convolution. 3 Model architecture Show in original Encoder and decoder Most strong sequence transduction models have an encoder and a decoder . The encoder maps input symbols (x1 to xn) to continuous vectors z. The decoder uses z to make output symbols (y1 to ym), one at a time. At each step the model is auto-regressive . It reads its own earlier outputs as extra input. How the Transformer is built From Figure 1 Words become embeddings Add position signals 6 encoder layers 6 decoder layers Linear layer, then softmax Next word probabilities Both halves use stacked self-attention and point-wise, fully connected layers. The encoder is the left half of Figure 1 and the decoder is the right half.
3.1 Encoder and decoder stacks Show in original The encoder The encoder is a stack of N = 6 identical layers. Each layer has two sub-layers. First: a multi-head self-attention mechanism. Second: a simple, position-wise, fully connected feed-forward network . Residual links Each sub-layer has a residual connection around it. Then comes layer normalization . The output of each sub-layer is LayerNorm(x + Sublayer(x)). All sub-layers and embedding layers give outputs of size dmodel = 512 . This makes the residual connections work. The decoder The decoder is also a stack of N = 6 identical layers. It has the two encoder sub-layers plus a third one. The third sub-layer does multi-head attention over the encoder output. It also has residual connections and layer normalization. Masking The decoder self-attention is changed so a position cannot see later positions. This is called masking . Output embeddings are also offset by one position. So the prediction for position i depends only on known outputs before i. 3.2 Attention Show in original What attention does An attention function maps a query and a set of key-value pairs to an output. The query, keys, values and output are all vectors. The output is a weighted sum of the values . The weight of each value comes from how well the query fits its key. How attention works, step by step From Section 3.2.1 and Figure 2 Each word makes query, key, value Query meets every key (dot product) Divide scores by root of dk Softmax turns scores into weights Weights mix the values The formula is Attention(Q, K, V) = softmax(QK^T / root dk) V. Many queries run at once, packed in matrices.
3.2.1 Scaled dot-product attention The inputs Queries and keys have size dk . Values have size dv . Take the dot product of the query with all keys. Divide each by the square root of dk. Apply softmax to get the weights on the values. In practice The model runs attention on many queries at the same time. It packs queries into matrix Q, keys into K and values into V. Output = softmax(Q K^T / root dk) V. This is equation (1). Two common kinds Additive attention uses a feed-forward network with one hidden layer.Dot-product attention is the same as the authors' method, without the scale factor.Both have similar theoretical cost. Dot-product is much faster and uses less space in practice. It uses highly tuned matrix multiplication code. Why scale For small dk, the two work about the same. For large dk, additive beats dot-product without scaling. The authors suspect large dk makes dot products large. That pushes softmax into regions with extremely small gradients . So they scale by 1 over the square root of dk. Why dot products grow Assume the parts of q and k are independent, with mean 0 and variance 1. Then the dot product has mean 0 and variance dk. 3.2.2 Multi-head attention The method Do not run one attention function with dmodel-size keys, values and queries. Instead, project queries, keys and values h times with different learned projections. The sizes become dk, dk and dv. Run attention in parallel on each projected version. Join the outputs and project once more.That gives the final values. Why it helps Multi-head attention looks at different information at different positions together. With one head, averaging blocks this. The settings The authors use h = 8 parallel heads. For each, dk = dv = dmodel / h = 64 . Each head is smaller, so total cost is like one head at full size. How multi-head attention works From Section 3.2.2 and Figure 2 Project Q, K, V 8 times Run attention in each head Join the 8 head outputs Project once more The projections are learned parameter matrices.
3.2.3 Three ways the model uses attention Encoder-decoder attention Queries come from the previous decoder layer. Keys and values come from the encoder output. Every decoder position can look at all input positions . This copies the usual attention in sequence-to-sequence models. Encoder self-attention Keys, values and queries all come from the previous encoder layer. Each encoder position can look at all positions in that layer. Decoder self-attention Each decoder position looks at all positions up to and including itself. The model must stop information flowing to the left. This keeps the auto-regressive property. It sets illegal softmax inputs to minus infinity. 3.3 Position-wise feed-forward networks Show in original What it is Each layer also has a fully connected feed-forward network. It works on each position separately and identically . It is two linear transformations with a ReLU between them. FFN(x) = max(0, xW1 + b1)W2 + b2. This is equation (2). Details The linear parts are the same across positions. They use different parameters from layer to layer. You can also see it as two convolutions with kernel size 1. Input and output size is dmodel = 512 . The inner layer size is dff = 2048 . 3.4 Embeddings and softmax Show in original Embeddings The model uses learned embeddings to turn tokens into vectors of size dmodel. It uses the usual learned linear step and softmax. These turn decoder output into next-token probabilities. Shared weights The two embedding layers and the pre-softmax linear step share one weight matrix. In the embedding layers the weights are multiplied by the square root of dmodel. Layer type Complexity per layer Sequential operations Maximum path length Self-Attention O(n^2 · d) O(1) O(1) Recurrent O(n · d^2) O(n) O(n) Convolutional O(k · n · d^2) O(1) O(log_k(n)) Self-Attention (restricted) O(r · n · d) O(1) O(n/r)
Table 1: layer types compared
n is sequence length, d is representation size, k is kernel size, r is neighborhood size.
3.5 Positional encoding Show in original The problem The model has no recurrence and no convolution. So it needs another way to know the order of tokens. The authors add positional encodings to the input embeddings. They sit at the bottom of the encoder and decoder stacks. They have size dmodel, so they can be added. The choice The authors use sine and cosine waves of different frequencies. PE(pos, 2i) = sin(pos / 10000^(2i/dmodel)). PE(pos, 2i+1) = cos(pos / 10000^(2i/dmodel)). pos is the position and i is the dimension. Wavelengths go from 2π to 10000 · 2π. Why sine waves The authors guessed it helps the model attend by relative position . For any fixed offset k, PE(pos+k) is a linear function of PE(pos). Learned instead They also tried learned positional embeddings. The results were nearly the same (Table 3 row E). They kept sine waves, which may handle longer sequences than seen in training. 4 Why self-attention Show in original Three goals The authors compare self-attention to recurrent and convolutional layers. Goal one: total computation per layer. Goal two: how much work runs in parallel, as the fewest sequential steps. Goal three: the path length between far apart positions. Shorter paths make long-range links easier to learn. Self-attention vs recurrent Self-attention links all positions in a constant number of sequential steps. A recurrent layer needs O(n) sequential steps. Self-attention is faster than recurrent when n is smaller than d. This is usual for word-piece and byte-pair sentence representations. Very long sequences Self-attention could look only at a neighborhood of size r. This raises the maximum path length to O(n/r). The authors plan to study this later. Convolutions One convolutional layer with kernel width k less than n does not link all pairs. You need O(n/k) layers for contiguous kernels. You need O(log_k(n)) layers for dilated convolutions. Convolutions cost more than recurrent layers by a factor of k. Separable convolutions cut cost to O(k · n · d + n · d^2). Even with k = n, that equals self-attention plus a feed-forward layer. That is the authors' approach. A side benefit Self-attention may give models that are easier to interpret . The authors show attention examples in the appendix. Individual heads learn different tasks. Many seem tied to sentence structure and meaning. 5 Training Show in original 5.1 Data and batching English to German: the WMT 2014 set of about 4.5 million sentence pairs. They used byte-pair encoding , with a shared vocabulary of about 37000 tokens. English to French: the much larger WMT 2014 set of 36M sentences. They used a 32000 word-piece vocabulary. Pairs were batched by approximate length. Each batch had about 25000 source tokens and 25000 target tokens. 5.2 Hardware and schedule One machine with 8 NVIDIA P100 GPUs . Base models: about 0.4 seconds per step. They trained for 100,000 steps, or 12 hours . Big models: 1.0 seconds per step. They trained for 300,000 steps, or 3.5 days . 5.3 Optimizer They used the Adam optimizer. Settings: β1 = 0.9, β2 = 0.98 and ε = 10^-9. The learning rate changed over training, by equation (3). It rises linearly for the first warmup_steps steps. Then it falls in proportion to the inverse square root of the step number. They used warmup_steps = 4000 . 5.4 Regularization Three kinds Residual dropout : applied to each sub-layer output before adding and normalizing.Dropout is also applied to the sums of embeddings and positional encodings. The base model uses Pdrop = 0.1. Label smoothing They used label smoothing of ε = 0.1. This hurts perplexity , because the model learns to be less sure. It improves accuracy and BLEU. 6.1 Results: machine translation Show in original English to German The big model beats the best earlier models, including ensembles, by more than 2.0 BLEU . It sets a new best of 28.4 . It trained for 3.5 days on 8 P100 GPUs. Even the base model beats all earlier published models and ensembles. Its training cost is a fraction of theirs. English to French The big model reaches 41.0 BLEU in the text of this section. Table 2 and the abstract say 41.8 . It beats all earlier single models. Its training cost is less than 1/4 of the previous best. It used dropout Pdrop = 0.1, not 0.3. The big Transformer leads English to German From Table 2 English to German English to French
0 10 20 30 BLEU, English to German ByteNet 23.75 BLEU GNMT + RL 24.60 BLEU ConvS2S 25.16 BLEU MoE 26.03 BLEU ConvS2S Ensemble 26.36 BLEU Transformer (base) 27.30 BLEU Transformer (big) 28.40 BLEU
Hover, tap or focus a bar to read its exact value.
Show as table Model English to German (BLEU) English to French (BLEU) ByteNet 23.75 GNMT + RL 24.60 39.92 ConvS2S 25.16 40.46 MoE 26.03 40.56 ConvS2S Ensemble 26.36 41.29 Transformer (base) 27.30 38.10 Transformer (big) 28.40 41.80
Model EN-DE BLEU EN-FR BLEU ByteNet 23.75 - Deep-Att + PosUnk - 39.2 GNMT + RL 24.6 39.92 ConvS2S 25.16 40.46 MoE 26.03 40.56 Deep-Att + PosUnk Ensemble - 40.4 GNMT + RL Ensemble 26.30 41.16 ConvS2S Ensemble 26.36 41.29 Transformer (base model) 27.3 38.1 Transformer (big) 28.4 41.8
Table 2: BLEU scores
Higher is better.
Model EN-DE FLOPs EN-FR FLOPs Deep-Att + PosUnk - 1.0 · 10^20 GNMT + RL 2.3 · 10^19 1.4 · 10^20 ConvS2S 9.6 · 10^18 1.5 · 10^20 MoE 2.0 · 10^19 1.2 · 10^20 Deep-Att + PosUnk Ensemble - 8.0 · 10^20 GNMT + RL Ensemble 1.8 · 10^20 1.1 · 10^21 ConvS2S Ensemble 7.7 · 10^19 1.2 · 10^21 Transformer (base model) 3.3 · 10^18 - Transformer (big) 2.3 · 10^19 -
Table 2: training cost in FLOPs
FLOPs means floating point operations. Lower is cheaper. The paper lists no Transformer FLOPs for English to French here.
How they ran the test Base models: one model made by averaging the last 5 checkpoints. Checkpoints were saved at 10-minute intervals. Big models: they averaged the last 20 checkpoints. They used beam search with beam size 4 and length penalty α = 0.6. They chose these settings on the development set. Maximum output length was input length + 50, with early stop when possible. How cost is estimated Cost = training time × number of GPUs × sustained single-precision speed per GPU. They used 2.8, 3.7, 6.0 and 9.5 TFLOPS for K80, K40, M40 and P100. 6.2 Results: model variations Show in original The test The authors changed the base model in different ways. They measured English to German on the development set newstest2013. They used beam search but no checkpoint averaging. One head is 0.9 BLEU worse, and too many heads also hurt From Table 3 row (A) 0 10 20 30 BLEU on newstest2013 (dev) 1 head 24.9 BLEU 4 heads 25.5 BLEU 8 heads (base) 25.8 BLEU 16 heads 25.8 BLEU 32 heads 25.4 BLEU
Hover, tap or focus a bar to read its exact value.
Show as table Number of heads BLEU (dev) 1 head 24.9 4 heads 25.5 8 heads (base) 25.8 16 heads 25.8 32 heads 25.4
What they found Rows (A): one head is 0.9 BLEU worse than the best setting. Too many heads also lower quality. Rows (B): a smaller key size dk hurts quality. So finding compatibility is not easy. A better function than the dot product may help. Rows (C) and (D): bigger models are better, as expected. Dropout helps a lot against over-fitting. Row (E): learned positions give nearly the same results as sine waves. Row and change PPL (dev) BLEU (dev) Params (x10^6) base: N=6, dmodel=512, dff=2048, h=8, dk=dv=64, Pdrop=0.1, ε=0.1, 100K steps 4.92 25.8 65 (A) h=1, dk=dv=512 5.29 24.9 - (A) h=4, dk=dv=128 5.00 25.5 - (A) h=16, dk=dv=32 4.91 25.8 - (A) h=32, dk=dv=16 5.01 25.4 - (B) dk=16 5.16 25.1 58 (B) dk=32 5.01 25.4 60
Table 3: variations (part 1)
A dash means the paper lists no value for that row. Other settings are the same as the base model.
Row and change PPL (dev) BLEU (dev) Params (x10^6) (C) N=2 6.11 23.7 36 (C) N=4 5.19 25.3 50 (C) N=8 4.88 25.5 80 (C) dmodel=256, dk=dv=32 5.75 24.5 28 (C) dmodel=1024, dk=dv=128 4.66 26.0 168 (C) dff=1024 5.12 25.4 53 (C) dff=4096 4.75 26.2 90 (D) Pdrop=0.0 5.77 24.6 - (D) Pdrop=0.2 4.95 25.5 - (D) ε=0.0 4.67 25.3 - (D) ε=0.2 5.47 25.7 - (E) positional embedding instead of sinusoids 4.92 25.7 - big: N=6, dmodel=1024, dff=4096, h=16, Pdrop=0.3, 300K steps 4.33 26.4 213
Table 3: variations (part 2)
PPL is per word-piece and cannot be compared with per-word perplexity.
6.3 Results: English constituency parsing Show in original Why this test Parsing has strong structure rules, and the output is much longer than the input. RNN sequence-to-sequence models had not reached the best results with little data. The setup A 4-layer Transformer with dmodel = 1024. Trained on the Wall Street Journal part of the Penn Treebank, about 40K sentences. Also trained semi-supervised on about 17M sentences. Vocabulary: 16K tokens for WSJ only, 32K for semi-supervised. They ran only a few tests to pick dropout, learning rates and beam size. All else stayed as in the English to German base model. At inference, max output length was input length + 300. They used beam size 21 and α = 0.3. Parser Training F1 Vinyals & Kaiser et al. (2014) WSJ only, discriminative 88.3 Petrov et al. (2006) WSJ only, discriminative 90.4 Zhu et al. (2013) WSJ only, discriminative 90.4 Dyer et al. (2016) WSJ only, discriminative 91.7 Transformer (4 layers) WSJ only, discriminative 91.3 Zhu et al. (2013) semi-supervised 91.3 Huang & Harper (2009) semi-supervised 91.3 McClosky et al. (2006) semi-supervised 92.1 Vinyals & Kaiser et al. (2014) semi-supervised 92.1 Transformer (4 layers) semi-supervised 92.7 Luong et al. (2015) multi-task 93.0 Dyer et al. (2016) generative 93.3
Table 4: WSJ section 23 F1
Higher is better.
What they found With no task-specific tuning, the model does surprisingly well. It beats all earlier reports except the Recurrent Neural Network Grammar. It beats the Berkeley Parser even with only the 40K WSJ sentences. RNN sequence-to-sequence models could not do this. 7 Conclusion Show in original What they did They presented the Transformer , the first sequence model based entirely on attention. It replaces the recurrent layers with multi-headed self-attention. What they found It trains much faster than recurrent or convolutional models for translation. It set a new best on both WMT 2014 tasks. On English to German it beats all earlier ensembles. What comes next The authors plan to use attention models on other tasks. They plan to cover images, audio and video, not only text. They plan to study local, restricted attention for large inputs and outputs. They also want generation to be less sequential. Code The training and test code is at github.com/tensorflow/tensor2tensor. A Appendix: attention visualizations (summary) Show in original What the figures show Figure 3: heads in encoder self-attention, layer 5 of 6, follow a far link. Many heads link the verb 'making' to 'more difficult'. Figure 4: two heads in layer 5 appear to handle anaphora resolution. The attention from the word 'its' is very sharp. Figure 5: many heads act in ways tied to sentence structure. Two heads in layer 5 of 6 clearly learned different tasks. Note This card sums up the appendix. The figures are pictures in the original paper. Words to know Adam: A common method for updating a model during training.Additive attention: Attention that scores with a small feed-forward network.Attention: A way to weigh which parts of the input matter most.Auto-regressive: The model reads its own earlier outputs to make the next one.Beam search: Keeping several best partial answers while writing the output.BLEU: A score that compares a translation with a human one. Higher is better.Byte-pair encoding: A way to split text into common word pieces.Concatenate: Join several vectors end to end into one.Convolutional network: A network that looks at small windows of nearby positions.Dot-product attention: Attention that scores by multiplying vectors and summing.Dropout: Randomly switching off parts of a model during training.Embedding: A list of numbers that stands for a word.Encoder and decoder: The encoder reads the input. The decoder writes the output.Feed-forward network: A small network that handles each position on its own.Gradient: The signal that tells a model how to change while it learns.Label smoothing: Training so the model is a little less sure of its answers.Layer normalization: A step that keeps the numbers in a layer on a steady scale.Masking: Hiding some positions so the model cannot see them.Multi-head attention: Several attention functions that run in parallel.Perplexity: A score for how surprised a model is. Lower is better.Positional encoding: Numbers added to a word vector to show its position.Query, key, value: A query asks. Keys are labels. Values carry the content.Recurrent network (RNN): A network that reads a sequence one step at a time.ReLU: A function that keeps positive numbers and turns negative ones to 0.Residual connection: A shortcut that adds a layer's input to its output.Self-attention: Attention where a sequence looks at its own positions.Sequence transduction: Turning one sequence into another, such as a translation.Softmax: A function that turns scores into weights that add up to 1.Word-piece: A small piece of a word used as a token.Ask AI about this paper Stuck on a word or an idea? Ask in plain words. The answer comes from the write-up on this page.
Ask AI about this paper Explain it like I am new to AI How would a finance team use this? What are the limits?
Jump to