The dominant sequence transduction models are based on complex recurrent or convolutional neural networks that include an encoder and a decoder. 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. 主导式序列转换模型基于复杂的循环或卷积神经网络,包括编码器和解码器。表现最佳的模型还通过注意力机制连接编码器和解码器。我们提出了一种新的简单网络架构"变换器"(Transformer),完全基于注意力机制,完全摆脱了循环和卷积。在两项机器翻译任务的实验中,这些模型在质量上优于现有最佳结果,且更易并行化,训练时间也大幅缩短。我们的模型在 2014 年 WMT 英德翻译任务上取得了 28.4 的 BLEU 分数,比现有最佳结果(包括集成模型)提高了 2 分以上。在 2014 年 WMT 英法翻译任务上,我们的模型在 3.5 天内使用 8 个 GPU 进行训练,创下 41.8 的新单一模型最高 BLEU 分数,大幅降低了文献中最佳模型的训练成本。我们还证明,变换器可很好地推广到其他任务,在英语成分分析任务上,无论训练数据量大小,都取得了成功应用。
1 Introduction 1 简介
Recurrent neural networks, long short-term memory [13] and gated recurrent [7] neural networks in particular, have been firmly established as state of the art approaches in sequence modeling and transduction problems such as language modeling and machine translation [35, 2, 5]. Numerous efforts have since continued to push the boundaries of recurrent language models and encoder-decoder architectures [38, 24, 15]. 循环神经网络,特别是长短期记忆[13]和门控循环[7]神经网络,已被牢固地确立为序列建模和传导问题的最先进方法,如语言建模和机器翻译[35,2,5]。此后,许多努力一直在推动循环语言模型和编码-解码体系结构的边界[38,24,15]。
Recurrent models typically factor computation along the symbol positions of the input and output sequences. Aligning the positions to steps in computation time, they generate a sequence of hidden states h_(t)h_{t}, as a function of the previous hidden state h_(t-1)h_{t-1} and the input for position tt. This inherently sequential nature precludes parallelization within training examples, which becomes critical at longer sequence lengths, as memory constraints limit batching across examples. 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. 循环模型通常沿着输入和输出序列的符号位置计算。通过将位置与计算时间步骤对齐,它们生成一个隐藏状态序列作为前一个隐藏状态和当前位置输入的函数。这种固有的顺序性阻碍了训练示例内部的并行化,这在序列长度较长时变得很关键,因为内存限制限制了跨示例的批处理。最近的工作通过因子化技巧[21]和条件计算[32]实现了显著的计算效率提升,同时也提高了后者情况下的模型性能。然而,顺序计算的基本约束仍然存在。
Attention mechanisms have become an integral part of compelling sequence modeling and transduction 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. 注意力机制已成为各种任务中引人入胜的序列建模和转导模型不可或缺的一部分,它们可以对输入或输出序列中的依赖关系进行建模,而不受距离的影响[2,19]。但在少数情况下[27],这种注意力机制与循环网络一起使用。
In 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. 我们提出了 Transformer 模型,这是一种摆脱循环的架构,完全依赖于注意力机制来勾画输入和输出之间的全局依赖关系。Transformer 允许显著更多的并行计算,在 8 块 P100 GPU 上训练 12 小时后就可以达到翻译质量的新纪录。
2 Background 2 背景
The 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 降低顺序计算的目标也构成了扩展神经 GPU [16]、ByteNet [18] 和 ConvS2S [9] 的基础,这些模型都使用卷积神经网络作为基本构件,并行计算所有输入和输出位置的隐藏表示。在这些模型中,所需的运算数量在输入或输出位置之间的距离上线性增长(对于 ConvS2S)或对数增长(对于 ByteNet)。这使得学习远距离位置之间的依赖关系更加困难[12]。在 Transformer 中,这被减少到一个恒定的操作数量,尽管代价是由于注意力加权位置的平均化导致的有效分辨率降低,我们在第 3.2 节描述的多头注意力机制可以抵消这一影响。
Self-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]. 自注意力, 有时被称为内部注意力, 是一种注意力机制, 它将单个序列的不同位置联系起来, 以计算该序列的表征。自注意力已成功应用于多种任务, 包括阅读理解、抽象摘要、文本蕴涵和学习独立于任务的句子表征 [4, 27, 28, 22]。
End-to-end memory networks are based on a recurrent attention mechanism instead of sequencealigned recurrence and have been shown to perform well on simple-language question answering and language modeling tasks [34]. 端到端记忆网络基于递归注意机制而不是串联性递归,已被证明在简单语言问题回答和语言建模任务上有良好表现。
To 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 sequencealigned 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]. 根据我们所知,然而,Transformer 是第一个完全依赖自注意力来计算其输入和输出表示的转导模型,而不使用序列对齐的 RNNs 或卷积。在接下来的章节中,我们将描述 Transformer,阐述自注意力,并讨论其相比于[17, 18]和[9]等模型的优势。
3 Model Architecture 3 个模型架构
Most competitive neural sequence transduction models have an encoder-decoder structure [5, 2, 35]. Here, the encoder maps an input sequence of symbol representations (x_(1),dots,x_(n))\left(x_{1}, \ldots, x_{n}\right) to a sequence of continuous representations z=(z_(1),dots,z_(n))\mathbf{z}=\left(z_{1}, \ldots, z_{n}\right). Given z\mathbf{z}, the decoder then generates an output sequence (y_(1),dots,y_(m))\left(y_{1}, \ldots, y_{m}\right) 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. 大多数竞争性神经序列转换模型都有编码器-解码器结构[5、2、35]。在这里,编码器将符号表示 (x_(1),dots,x_(n))\left(x_{1}, \ldots, x_{n}\right) 的输入序列映射到一序列连续表示 z=(z_(1),dots,z_(n))\mathbf{z}=\left(z_{1}, \ldots, z_{n}\right) 。给定 z\mathbf{z} ,解码器然后一次生成一个元素的输出序列 (y_(1),dots,y_(m))\left(y_{1}, \ldots, y_{m}\right) 。在每一步,模型都是自回归的[10],在生成下一个符号时消耗之前生成的符号作为额外输入。
Figure 1: The Transformer - model architecture. 图 1:Transformer-模型架构。
The 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. 变换器遵循这种整体架构,使用堆叠的自注意力和点方式、全连接层,用于编码器和解码器,如图 1 所示的左侧和右侧。
3.1 Encoder and Decoder Stacks 编码器和解码器堆栈
Encoder: The encoder is composed of a stack of N=6N=6 identical layers. Each layer has two sub-layers. The first is a multi-head self-attention mechanism, and the second is a simple, positionwise fully connected feed-forward network. 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))(x+\operatorname{Sublayer}(x)), where Sublayer(x)\operatorname{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 d_("model ")=512d_{\text {model }}=512. 编码器由一堆 N=6N=6 相同层组成。每一层有两个子层。第一个是多头自注意机制,第二个是简单的位置全连接前馈网络。我们在两个子层周围都使用残差连接[11],然后进行层标准化[1]。也就是说,每个子层的输出是 LayerNorm (x+Sublayer(x))(x+\operatorname{Sublayer}(x)) ,其中 Sublayer(x)\operatorname{Sublayer}(x) 是子层自身实现的函数。为了促进这些残差连接,模型中的所有子层以及嵌入层都产生 d_("model ")=512d_{\text {model }}=512 维度的输出。
Decoder: The decoder is also composed of a stack of N=6N=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 ii can depend only on the known outputs at positions less than ii. 译文:
解码器由一堆 N=6N=6 相同的层组成。除了编码器层中的两个子层外,解码器还插入了第三个子层,该子层对编码器堆栈的输出执行多头注意力。与编码器类似,我们在每个子层周围使用残差连接,然后进行层归一化。我们还修改了解码器堆栈中的自注意力子层,以防止位置注意到后续位置。这种遮蔽,再加上输出嵌入被偏移一个位置的事实,确保位置 ii 的预测只能依赖于小于位置 ii 的已知输出。
3.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 注意力函数可以被描述为将查询和一组键值对映射到输出,其中查询、键、值和输出都是向量。输出被计算为加权和。
Figure 2: (left) Scaled Dot-Product Attention. (right) Multi-Head Attention consists of several attention layers running in parallel. 图 2:(左)缩放点乘注意力。(右)多头注意力由多个并行运行的注意力层组成。
of the values, where the weight assigned to each value is computed by a compatibility function of the query with the corresponding key. 每个值的权重由查询与相应键的兼容性函数计算得出。
3.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 d_(k)d_{k}, and values of dimension d_(v)d_{v}. We compute the dot products of the query with all keys, divide each by sqrt(d_(k))\sqrt{d_{k}}, and apply a softmax function to obtain the weights on the values. 我们将特别注意力称为"缩放点积注意力"(图 2)。输入由维度为 d_(k)d_{k} 的查询和密钥以及维度为 d_(v)d_{v} 的值组成。我们计算查询与所有密钥的点积,每个点积除以 sqrt(d_(k))\sqrt{d_{k}} ,然后应用 softmax 函数获得值的权重。
In practice, we compute the attention function on a set of queries simultaneously, packed together into a matrix QQ. The keys and values are also packed together into matrices KK and VV. We compute the matrix of outputs as: 在实践中,我们同时对一组查询计算注意力函数,打包在矩阵 QQ
Attention(Q,K,V)=softmax((QK^(T))/(sqrt(d_(k))))V\operatorname{Attention}(Q, K, V)=\operatorname{softmax}\left(\frac{Q K^{T}}{\sqrt{d_{k}}}\right) V
The two most commonly used attention functions are additive attention [2], and dot-product (multiplicative) attention. Dot-product attention is identical to our algorithm, except for the scaling factor of (1)/(sqrt(d_(k)))\frac{1}{\sqrt{d_{k}}}. Additive attention computes the compatibility function using a feed-forward network with 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. 两种最常用的注意力机制是加性注意力[2]和点积(乘积)注意力。除了缩放因子 (1)/(sqrt(d_(k)))\frac{1}{\sqrt{d_{k}}} 之外,点积注意力与我们的算法完全一致。加性注意力使用单隐层的前馈网络计算兼容性函数。理论复杂度相似,但点积注意力在实践中更快且更节省空间,因为可以使用高度优化的矩阵乘法代码实现。
While for small values of d_(k)d_{k} the two mechanisms perform similarly, additive attention outperforms dot product attention without scaling for larger values of d_(k)d_{k} [3]. We suspect that for large values of d_(k)d_{k}, the dot products grow large in magnitude, pushing the softmax function into regions where it has extremely small gradients ^(4){ }^{4} To counteract this effect, we scale the dot products by (1)/(sqrt(d_(k)))\frac{1}{\sqrt{d_{k}}}. 对于 d_(k)d_{k} 值较小时,两种机制的表现相似,但对于 d_(k)d_{k} 值较大时,加性注意力优于点乘注意力,无需缩放[3]。我们怀疑对于 d_(k)d_{k} 值较大时,点乘结果值很大,导致 softmax 函数进入梯度极小的区域 ^(4){ }^{4} 。为了抵消这一效果,我们将点乘结果缩放 (1)/(sqrt(d_(k)))\frac{1}{\sqrt{d_{k}}} 。
3.2.2 Multi-Head Attention 多头注意力
Instead of performing a single attention function with d_("model ")d_{\text {model }}-dimensional keys, values and queries, we found it beneficial to linearly project the queries, keys and values hh times with different, learned linear projections to d_(k),d_(k)d_{k}, d_{k} and d_(v)d_{v} dimensions, respectively. On each of these projected versions of queries, keys and values we then perform the attention function in parallel, yielding d_(v)d_{v}-dimensional 与其执行单个 d_("model ")d_{\text {model }}
output values. These are concatenated and once again projected, resulting in the final values, as depicted in Figure 2 输出值。这些被连接并再次投射,形成最终值,如图 2 所示。
Multi-head attention allows the model to jointly attend to information from different representation subspaces at different positions. With a single attention head, averaging inhibits this. 多头注意力允许模型同时关注来自不同表示子空间的信息,位于不同位置上。使用单个注意力头,平均值会抑制这一点。
[
{:[MultiHead(Q","K","V)=Concat(" head "_(1),dots," head "_(h))W^(O)],[" where head "],[i=Attention(QW_(i)^(Q),KW_(i)^(K),VW_(i)^(V))]:}\begin{aligned}
& \operatorname{MultiHead}(Q, K, V)=\operatorname{Concat}\left(\text { head }_{1}, \ldots, \text { head }_{\mathrm{h}}\right) W^{O} \\
& \text { where head } \\
& \mathrm{i}=\operatorname{Attention}\left(Q W_{i}^{Q}, K W_{i}^{K}, V W_{i}^{V}\right)
\end{aligned}
]
Where the projections are parameter matrices W_(i)^(Q)inR^(d_("model ")xxd_(k)),W_(i)^(K)inR^(d_("model ")xxd_(k)),W_(i)^(V)inR^(d_("model ")xxd_(v))W_{i}^{Q} \in \mathbb{R}^{d_{\text {model }} \times d_{k}}, W_{i}^{K} \in \mathbb{R}^{d_{\text {model }} \times d_{k}}, W_{i}^{V} \in \mathbb{R}^{d_{\text {model }} \times d_{v}} and W^(O)inR^(hd_(v)xxd_("model "))W^{O} \in \mathbb{R}^{h d_{v} \times d_{\text {model }}}. 投影是参数矩阵 W_(i)^(Q)inR^(d_("model ")xxd_(k)),W_(i)^(K)inR^(d_("model ")xxd_(k)),W_(i)^(V)inR^(d_("model ")xxd_(v))W_{i}^{Q} \in \mathbb{R}^{d_{\text {model }} \times d_{k}}, W_{i}^{K} \in \mathbb{R}^{d_{\text {model }} \times d_{k}}, W_{i}^{V} \in \mathbb{R}^{d_{\text {model }} \times d_{v}} 和 W^(O)inR^(hd_(v)xxd_("model "))W^{O} \in \mathbb{R}^{h d_{v} \times d_{\text {model }}} 。
In this work we employ h=8h=8 parallel attention layers, or heads. For each of these we use d_(k)=d_(v)=d_("model ")//h=64d_{k}=d_{v}=d_{\text {model }} / h=64. Due to the reduced dimension of each head, the total computational cost is similar to that of single-head attention with full dimensionality. 在这项工作中,我们采用了 h=8h=8 个并行注意力层或注意力头。对于每个注意力头,我们使用了 d_(k)=d_(v)=d_("model ")//h=64d_{k}=d_{v}=d_{\text {model }} / h=64 。由于每个注意力头的维度降低,总的计算成本与使用单注意力头且完整维度的注意力计算相似。
3.2.3 Applications of Attention in our Model 我们模型中注意力的应用
The Transformer uses multi-head attention in three different ways: 变形金刚在三种不同的方式中使用了多头注意力机制
In “encoder-decoder attention” layers, the queries come from the previous decoder layer, and the memory keys and values come from the output of the encoder. This allows every position in the decoder to attend over all positions in the input sequence. This mimics the typical encoder-decoder attention mechanisms in sequence-to-sequence models such as [38, 2, 9]. 在"编码解码器注意力"层中,查询来自前一个解码器层,而内存键和值来自编码器的输出。这使得解码器中的每个位置都可以关注输入序列中的所有位置。这模仿了序列到序列模型(如[38, 2, 9])中典型的编码器-解码器注意力机制。
The encoder contains self-attention layers. In a self-attention layer all of the keys, values and queries come from the same place, in this case, the output of the previous layer in the encoder. Each position in the encoder can attend to all positions in the previous layer of the encoder. 编码器包含自注意力层。在自注意力层中,所有的键、值和查询都来自同一个地方,在本例中,来自编码器中前一层的输出。编码器中的每个位置都可以关注前一层编码器中的所有位置。
Similarly, self-attention layers in the decoder allow each position in the decoder to attend to all positions in the decoder up to and including that position. We need to prevent leftward information flow in the decoder to preserve the auto-regressive property. We implement this inside of scaled dot-product attention by masking out (setting to -oo-\infty ) all values in the input of the softmax which correspond to illegal connections. See Figure 2. 在解码器中,自注意力层允许解码器中的每个位置都注意到该位置前的所有位置。我们需要防止解码器中的左向信息流来保持自回归性质。我们通过在 softmax 的输入中屏蔽掉对应于非法连接的所有值(设置为 -oo-\infty )来实现这一点。请参见图 2。
3.3 Position-wise Feed-Forward Networks 位置式前馈网络
In addition to attention sub-layers, each of the layers in our encoder and decoder contains a fully connected feed-forward network, which is applied to each position separately and identically. This consists of two linear transformations with a ReLU activation in between. 除了注意力子层外,我们的编码器和解码器中的每个层都包含一个完全连接的前馈网络,它被单独和相同地应用于每个位置。这由两个线性变换组成,中间有一个 ReLU 激活。
FFN(x)=max(0,xW_(1)+b_(1))W_(2)+b_(2)\operatorname{FFN}(x)=\max \left(0, x W_{1}+b_{1}\right) W_{2}+b_{2}
While the linear transformations are the same across different positions, they use different parameters from layer to layer. Another way of describing this is as two convolutions with kernel size 1. The dimensionality of input and output is d_("model ")=512d_{\text {model }}=512, and the inner-layer has dimensionality d_(ff)=2048d_{f f}=2048. 虽然线性变换在不同位置是相同的,但它们从层到层使用不同的参数。另一种描述方式是两个卷积核大小为 1。输入和输出的维度为 d_("model ")=512d_{\text {model }}=512 ,内部层的维度为 d_(ff)=2048d_{f f}=2048 。
3.4 Embeddings and Softmax 3.4 嵌入和 Softmax
Similarly to other sequence transduction models, we use learned embeddings to convert the input tokens and output tokens to vectors of dimension d_("model ")d_{\text {model }}. We also use the usual learned linear transformation and softmax function to convert the decoder output to predicted next-token probabilities. In our model, we share the same weight matrix between the two embedding layers and the pre-softmax linear transformation, similar to [30]. In the embedding layers, we multiply those weights by sqrt(d_("model "))\sqrt{d_{\text {model }}}. 与其他顺序转换模型类似,我们使用学习嵌入将输入令牌和输出令牌转换为 d_("model ")d_{\text {model }}
Table 1: Maximum path lengths, per-layer complexity and minimum number of sequential operations for different layer types. nn is the sequence length, dd is the representation dimension, kk is the kernel size of convolutions and rr the size of the neighborhood in restricted self-attention. 表 1:不同层类型的最大路径长度、每层复杂度和最小顺序操作数。 nn 是序列长度, dd 是表示维度, kk 是卷积的内核大小, rr 是受限自注意力中的邻域大小。
Since our model contains no recurrence and no convolution, in order for the model to make use of the order of the sequence, we must inject some information about the relative or absolute position of the tokens in the sequence. To this end, we add “positional encodings” to the input embeddings at the bottoms of the encoder and decoder stacks. The positional encodings have the same dimension d_("model ")d_{\text {model }} as the embeddings, so that the two can be summed. There are many choices of positional encodings, learned and fixed [9]. 由于我们的模型不包含循环和卷积,为了让模型利用序列的顺序信息,我们必须注入一些关于令牌在序列中相对或绝对位置的信息。为此,我们在编码器和解码器栈的底部将"位置编码"添加到输入嵌入中。位置编码的维度与嵌入相同,因此两者可以相加。有许多可学习和固定的位置编码选择[9]。
In this work, we use sine and cosine functions of different frequencies: 在这项工作中,我们使用不同频率的正弦和余弦函数:
{:[PE_((pos,2i))=sin(pos//10000^(2i//d_("model ")))],[PE_((pos,2i+1))=cos(pos//10000^(2i//d_("model ")))]:}\begin{aligned}
P E_{(p o s, 2 i)} & =\sin \left(p o s / 10000^{2 i / d_{\text {model }}}\right) \\
P E_{(p o s, 2 i+1)} & =\cos \left(p o s / 10000^{2 i / d_{\text {model }}}\right)
\end{aligned}
where pos is the position and ii is the dimension. That is, each dimension of the positional encoding corresponds to a sinusoid. The wavelengths form a geometric progression from 2pi2 \pi to 10000*2pi10000 \cdot 2 \pi. We chose this function because we hypothesized it would allow the model to easily learn to attend by relative positions, since for any fixed offset k,PE_(pos+k)k, P E_{p o s+k}