{"paper":{"abstract":"The dominant sequence transduction models are based on complex recurrent or convolutional neural networks in an encoder-decoder configuration. The best performing models also connect the encoder and decoder through an attention mechanism. We propose a new simple network architecture, the Transformer, based solely on attention mechanisms, dispensing with recurrence and convolutions entirely. Experiments on two machine translation tasks show these models to be superior in quality while being more parallelizable and requiring significantly less time to train. Our model achieves 28.4 BLEU on the WMT 2014 English-to-German translation task, improving over the existing best results, including ensembles by over 2 BLEU. On the WMT 2014 English-to-French translation task, our model establishes a new single-model state-of-the-art BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small fraction of the training costs of the best models from the literature. We show that the Transformer generalizes well to other tasks by applying it successfully to English constituency parsing both with large and limited training data.","authors":"Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Lukasz Kaiser, Illia Polosukhin","categories":["cs.CL","cs.LG"],"createdDate":"Mon, 12 Jun 2017 17:57:34 GMT","ids":{"arxiv":["1706.03762"]},"paperId":"8319239866974784291","title":"Attention Is All You Need","updateDate":"2023-08-03"},"paperId":"8319239866974784291","passages":[{"score":0.032522473,"text":"\\[32\\] Noam Shazeer, Azalia Mirhoseini, Krzysztof Maziarz, Andy Davis, Quoc Le, Geoffrey Hinton,\nand Jeff Dean. Outrageously large neural networks: The sparsely-gated mixture-of-experts\nlayer. arXiv preprint arXiv:1701.06538, 2017.\n\\[33\\] Nitish Srivastava, Geoffrey E Hinton, Alex Krizhevsky, Ilya Sutskever, and Ruslan Salakhutdinov. Dropout: a simple way to prevent neural networks from overfitting. Journal of Machine\nLearning Research, 15(1):1929–1958, 2014.\n\\[34\\] Sainbayar Sukhbaatar, Arthur Szlam, Jason Weston, and Rob Fergus. End-to-end memory\nnetworks. In C. Cortes, N. D. Lawrence, D. D. Lee, M. Sugiyama, and R. Garnett, editors,\nAdvances in Neural Information Processing Systems 28, pages 2440–2448. Curran Associates,\nInc., 2015.\n\\[35\\] Ilya Sutskever, Oriol Vinyals, and Quoc VV Le. Sequence to sequence learning with neural\nnetworks. In Advances in Neural Information Processing Systems, pages 3104–3112, 2014.\n\\[36\\] Christian Szegedy, Vincent Vanhoucke, Sergey Ioffe, Jonathon Shlens, and Zbigniew Wojna.\nRethinking the inception architecture for computer vision. CoRR, abs/1512.00567, 2015.\n\\[37\\] Vinyals & Kaiser, Koo, Petrov, Sutskever, and Hinton. Grammar as a foreign language. In\nAdvances in Neural Information Processing Systems, 2015.\n\\[38\\] Yonghui Wu, Mike Schuster, Zhifeng Chen, Quoc V Le, Mohammad Norouzi, Wolfgang\nMacherey, Maxim Krikun, Yuan Cao, Qin Gao, Klaus Macherey, et al. Google’s neural machine\ntranslation system: Bridging the gap between human and machine translation. arXiv preprint\narXiv:1609.08144, 2016.\n\\[39\\] Jie Zhou, Ying Cao, Xuguang Wang, Peng Li, and Wei Xu. Deep recurrent models with\nfast-forward connections for neural machine translation. CoRR, abs/1606.04199, 2016.\n\\[40\\] Muhua Zhu, Yue Zhang, Wenliang Chen, Min Zhang, and Jingbo Zhu. Fast and accurate\nshift-reduce constituent parsing. In Proceedings of the 51st Annual Meeting of the ACL (Volume\n1: Long Papers), pages 434–443. ACL, August 2013.\n* * *\n\nInput-Input Layer5\nAttention Visualizations\n\nFigure 3: An example of the attention mechanism following long-distance dependencies in the\nencoder self-attention in layer 5 of 6. Many of the attention heads attend to a distant dependency of\nthe verb ‘making’, completing the phrase ‘making...more difficult’. Attentions here shown only for\nthe word ‘making’. Different colors represent different heads. Best viewed in color.\n* * *\n\n# Input-Input Layer5\n\nThe Lawwillneverbe perfect, butitsapplicationshouldbe just-thisis whatwe aremissing, in my opinion.\n,\\- is , in . will be but its be just this we are my\n\n# Input-Input Layer5\n\nThe Law never what perfect should missing opinion\n\napplication\n\nThe Lawwillneverbe perfect, butitsapplicationshouldbe just-thisis whatwe aremissing, in my opinion.\n,\\- is , in . will be but its be just this we are my The Law what never should  perfect missing opinion application\n\nFigure 4: Two attention heads, also in layer 5 of 6, apparently involved in anaphora resolution. Top:\n\nFull attentions for head 5. Bottom: Isolated attentions from just the word ‘its’ for attention heads 5 and 6. Note that the attentions are very sharp for this word.\n* * *\n\n# Input-Input Layer5\n\nThe Lawwillneverbe perfect, butitsapplicationshouldbe just-thisis whatwe aremissing, in my opinion.\n,\\- is , in . will be but its be just this we are my The Law what\n\n# Input-Input Layer5never\n\nperfect should missing opinion\n\napplication\n\nThe Lawwillneverbe perfect, butitsapplicationshouldbe just-thisis whatwe aremissing, in my opinion.\n,\\- is , in . will be but its be just this we are my The Law what never should  perfect missing opinion application\n\nFigure 5: Many of the attention heads exhibit behaviour that seems related to the structure of the\n\nsentence. We give two such examples above, from two different heads from the encoder self-attention at layer 5 of 6. The heads clearly learned to perform different tasks."},{"score":0.03201844,"text":"We employ a residual connection \\[11\\] around each of the two sub-layers, followed by layer normalization \\[1\\]. That is, the output of each sub-layer is LayerNorm(x + Sublayer(x)), where Sublayer(x) is the function implemented by the sub-layer itself. To facilitate these residual connections, all sub-layers in the model, as well as the embedding layers, produce outputs of dimension dmodel= 512. Decoder: The decoder is also composed of a stack of N = 6 identical layers. In addition to the two sub-layers in each encoder layer, the decoder inserts a third sub-layer, which performs multi-head attention over the output of the encoder stack. Similar to the encoder, we employ residual connections around each of the sub-layers, followed by layer normalization. We also modify the self-attention sub-layer in the decoder stack to prevent positions from attending to subsequent positions. This masking, combined with fact that the output embeddings are offset by one position, ensures that the predictions for position i can depend only on the known outputs at positions less than i.\n3.2 Attention An attention function can be described as mapping a query and a set of key-value pairs to an output, where the query, keys, values, and output are all vectors. The output is computed as a weighted sum\n\n* * *\n\n## Scaled Dot-Product Attention Multi-Head Attention\n\nFigure 2: (left) Scaled Dot-Product Attention. (right) Multi-Head Attention consists of several\n\nattention layers running in parallel.\nof the values, where the weight assigned to each value is computed by a compatibility function of the query with the corresponding key.\n3.2.1 Scaled Dot-Product Attention We call our particular attention \"Scaled Dot-Product Attention\" (Figure 2). The input consists of queries and keys of dimension dk, and values of dimension\n√ dv. We compute the dot products of the query with all keys, divide each by dk, and apply a softmax function to obtain the weights on the values.\nIn practice, we compute the attention function on a set of queries simultaneously, packed together into a matrix Q. The keys and values are also packed together into matrices K and V. We compute the matrix of outputs as:\n\nQK T Attention(Q,K,V) = softmax( √)V (1) dk\n\nThe two most commonly used attention functions are additive attention \\[2\\], and dot-product (multi- plicative) attention. Dot-product attention is identical to our algorithm, except for the scaling factor of√1d. Additive attention computes the compatibility function using a feed-forward network with k a single hidden layer. While the two are similar in theoretical complexity, dot-product attention is much faster and more space-efficient in practice, since it can be implemented using highly optimized matrix multiplication code.\nWhile for small values of dkthe two mechanisms perform similarly, additive attention outperforms dot product attention without scaling for larger values of dk\\[3\\]. We suspect that for large values of dk, the dot products grow large in magnitude, pushing the softmax function into regions where it has extremely small gradients 4 . To counteract this effect, we scale the dot products by√1d. k\n\n3.2.2 Multi-Head Attention Instead of performing a single attention function with dmodel-dimensional keys, values and queries, we found it beneficial to linearly project the queries, keys and values h times with different, learned linear projections to dk, dkand dvdimensions, respectively. On each of these projected versions of queries, keys and values we then perform the attention function in parallel, yielding dv-dimensional To illustrate why the dot products get large, assume that the components of q and k are independent random\nPd k variables with mean 0 and variance 1. Then their dot product, q · k =i=1qiki, has mean 0 and variance dk.\n* * *\n\noutput values. These are concatenated and once again projected, resulting in the final values, as\ndepicted in Figure 2."},{"score":0.03175403,"text":"Recent work has achieved significant improvements in computational efficiency through factorization tricks \\[21\\] and conditional computation \\[32\\], while also improving model performance in case of the latter. The fundamental constraint of sequential computation, however, remains.\nAttention mechanisms have become an integral part of compelling sequence modeling and transduc- tion models in various tasks, allowing modeling of dependencies without regard to their distance in the input or output sequences \\[2, 19\\]. In all but a few cases \\[27\\], however, such attention mechanisms are used in conjunction with a recurrent network.\nIn this work we propose the Transformer, a model architecture eschewing recurrence and instead relying entirely on an attention mechanism to draw global dependencies between input and output. The Transformer allows for significantly more parallelization and can reach a new state of the art in translation quality after being trained for as little as twelve hours on eight P100 GPUs.\n# 2 Background\n\nThe goal of reducing sequential computation also forms the foundation of the Extended Neural GPU \\[16\\], ByteNet \\[18\\] and ConvS2S \\[9\\], all of which use convolutional neural networks as basic building block, computing hidden representations in parallel for all input and output positions. In these models, the number of operations required to relate signals from two arbitrary input or output positions grows in the distance between positions, linearly for ConvS2S and logarithmically for ByteNet. This makes it more difficult to learn dependencies between distant positions \\[12\\]. In the Transformer this is reduced to a constant number of operations, albeit at the cost of reduced effective resolution due to averaging attention-weighted positions, an effect we counteract with Multi-Head Attention as described in section 3.2.\nSelf-attention, sometimes called intra-attention is an attention mechanism relating different positions of a single sequence in order to compute a representation of the sequence. Self-attention has been used successfully in a variety of tasks including reading comprehension, abstractive summarization, textual entailment and learning task-independent sentence representations \\[4, 27, 28, 22\\].\nEnd-to-end memory networks are based on a recurrent attention mechanism instead of sequence- aligned recurrence and have been shown to perform well on simple-language question answering and language modeling tasks \\[34\\].\nTo the best of our knowledge, however, the Transformer is the first transduction model relying entirely on self-attention to compute representations of its input and output without using sequence- aligned RNNs or convolution. In the following sections, we will describe the Transformer, motivate self-attention and discuss its advantages over models such as \\[17, 18\\] and \\[9\\].\n# 3 Model Architecture\n\nMost competitive neural sequence transduction models have an encoder-decoder structure \\[5, 2, 35\\]. Here, the encoder maps an input sequence of symbol representations (x1,...,xn) to a sequence of continuous representations z = (z1,...,zn). Given z, the decoder then generates an output sequence (y1,...,ym) of symbols one element at a time. At each step the model is auto-regressive \\[10\\], consuming the previously generated symbols as additional input when generating the next.\n* * *\n\nFigure 1: The Transformer-model architecture.\nThe Transformer follows this overall architecture using stacked self-attention and point-wise, fully connected layers for both the encoder and decoder, shown in the left and right halves of Figure 1, respectively.\n3.1 Encoder and Decoder Stacks Encoder: The encoder is composed of a stack of N = 6 identical layers. Each layer has two sub-layers. The first is a multi-head self-attention mechanism, and the second is a simple, position- wise fully connected feed-forward network."},{"score":0.015873017,"text":"Multi-head attention allows the model to jointly attend to information from different representation\nsubspaces at different positions. With a single attention head, averaging inhibits this.\n\\\\mathbf{M u l t i H e a d}(Q,K,V)=\\\\mathbf{C o n c a t}(\\\\mathbf{h e a d} _{1},\\\\ldots,\\\\mathbf{h e a d}_{})W^{O}\n\n\\\\small\\ \\\n\ndmodel×dkdmodel×dkdmodel×dv\nWhere the projections are parameter matrices WiQ∈ R, WiK∈ R, WiV∈ R\nO hdv×dmodel\nand W ∈ R.\n,\\ \\\\cdot W\\_ _i{i}^{,C},\\\\in,\\\\mathbb{R}^{d_{\\\\mathsf{m o d e l}}\\\\times,d\\_{k}},,W\\_ _i{i}^{,K},\\\\in,\\\\mathbb{R}^{d_{\\\\mathsf{m o d e l}}\\\\times,d\\_{k}},,W\\_{i}^{,V},\\\\in,\\\\mathbb{R}^{d\\_{\\\\mathsf{m o d e l}}\\\\times,d\\_{v}}\n\nW^{O}\\\\overset{\\\\center}{\\\\in}\\\\mathbb{R}^{h d\\_{v}\\\\times d\\_{\\\\operatorname{m o d c}}}\n\nIn this work we employ h = 8 parallel attention layers, or heads. For each of these we use\ndk= dv= dmodel/h = 64. Due to the reduced dimension of each head, the total computational cost\nis similar to that of single-head attention with full dimensionality.\nh,=,8\n\nd\\_{k}=d\\_{v}=d\\_{\\\\mathrm{m o d e l}}/\\\\dot{h==64}\n\n3.2.3 Applications of Attention in our Model\n\nThe Transformer uses multi-head attention in three different ways:\n\n• In \"encoder-decoder attention\" layers, the queries come from the previous decoder layer,\nand the memory keys and values come from the output of the encoder. This allows every\nposition in the decoder to attend over all positions in the input sequence. This mimics the\ntypical encoder-decoder attention mechanisms in sequence-to-sequence models such as\n\\[38, 2, 9\\].\n• The encoder contains self-attention layers. In a self-attention layer all of the keys, values\nand queries come from the same place, in this case, the output of the previous layer in the\nencoder. Each position in the encoder can attend to all positions in the previous layer of the\nencoder.\n• Similarly, self-attention layers in the decoder allow each position in the decoder to attend to\nall positions in the decoder up to and including that position. We need to prevent leftward\ninformation flow in the decoder to preserve the auto-regressive property. We implement this\ninside of scaled dot-product attention by masking out (setting to −∞) all values in the input\nof the softmax which correspond to illegal connections. See Figure 2.\nIn addition to attention sub-layers, each of the layers in our encoder and decoder contains a fully\nconnected feed-forward network, which is applied to each position separately and identically. This\nconsists of two linear transformations with a ReLU activation in between.\n3.3 Position-wise Feed-Forward Networks\n\nSimilarly to other sequence transduction models, we use learned embeddings to convert the input\ntokens and output tokens to vectors of dimension dmodel. We also use the usual learned linear transformation and softmax function to convert the decoder output to predicted next-token probabilities. In\nour model, we share the same weight matrix between the two embedding layers and the pre-softmax\n√\nlinear transformation, similar to \\[30\\]. In the embedding layers, we multiply those weights by dmodel.\nd\\_{\\\\mathrm{m o d e l}}\n\n(2)\n\nd\\_{f f}=2048\n\n\\\\operatorname{F F N}(x)=\\\\operatorname\\*{m a x}(0,x W\\_{1}+b\\_{1})W\\_{2}+b\\_{2}\n\n* * *\n\nTable 1: Maximum path lengths, per-layer complexity and minimum number of sequential operations\n\nfor different layer types. n is the sequence length, d is the representation dimension, k is the kernel size of convolutions and r the size of the neighborhood in restricted self-attention.\nLayer Type Complexity per Layer Sequential Maximum Path Length Operations Self-Attention O(n2 · d) O(1) O(1) Recurrent O(n · d2) O(n) O(n) Convolutional O(k · n · d2) O(1) O(logk(n)) Self-Attention (restricted) O(r · n · d) O(1) O(n/r)"}],"query":"what is the attention mechanism","success":true}