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.
主流序列转换模型基于复杂的循环神经网络或卷积神经网络,这些神经网络包括编码器和解码器。性能最好的模型还通过attention机制将编码器和解码器连接起来。我们提出了一种新的简单的网络结构,Transformer,仅基于attention机制,完全不需要循环和卷积。对两个机器翻译任务的实验表明,这些模型在质量上更优、并行性更好、训练时间更短。我们的模型在WMT 2014英语-德语翻译任务上达到28.4 BLEU,比现有的最佳结果(包括集成模型)提高了2 BLEU以上。在WMT 2014英法翻译任务中,我们的模型在8个GPU上训练3.5天后,建立了一个新的单模型最新的BLEU分数41.8,这个时间只是目前文献中记载的最好的模型训练成本的一小部分。我们将该变换器成功地应用于具有大量和有限训练数据的英语句法分析中,证明了Transformer可以很好地推广到其他任务。
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].
在序列建模和转换问题中,如语言建模和机器翻译[35,2,5],循环神经网络,特别是长时短记忆[13]和门控循环[7]神经网络,已经被确立为最先进的方法。自那以来,人们花了许多努力来推动循环语言模型和编码器-解码器体系结构的界限[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 , as a function of the previous hidden state
and the input for position t. 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.
循环模型通常是对输入和输出序列的符号位置进行因子计算。 通过在计算期间将位置与步骤对齐,循环模型根据前一步的隐藏状态和输入,产生位置t的隐藏状态序列
。这种固有的顺序特性阻碍了样本训练的并行化,这在更长的序列长度上变得至关重要,因为有限的内存会限制样本的批次大小。 最近的工作通过巧妙的因子分解[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.
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.
在各种任务中,attention机制已经成为序列建模和转换模型不可或缺的一部分,它可以建模依赖关系而不考虑其在输入或输出序列中的距离[2, 19]。 除少数情况外[27],这种attention机制都与循环网络一起使用。
在这项工作中,我们提出了Transformer,这种模型架构不使用循环网络结构,而是完全依赖于attention机制来表示输入和输出之间的全局依赖关系。Transformer允许进行更多的并行化,并且可以在八个P100 GPU上进行十二小时的训练后达到翻译质量的新的最佳结果。
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.
减少序列计算的目标也构成了Extended Neural GPU [16],ByteNet [18]和ConvS2S [9]的基础,它们都使用卷积神经网络作为基本构建模块,并行计算所有输入和输出位置的隐藏表示。在这些模型中,关联任意两个输入或输出位置的信号所需的操作次数会随着位置之间的距离而增加,ConvS2S是线性增加,而ByteNet是对数增加。这使得学习远距离之间的依赖关系变得更加困难[12]。在Transformer中,关联两个输入或输出位置的信号所需的操作次数可以减少到固定的次数,尽管由于用attention权重化的位置取平均降低了效果,但是我们使用Multi-Head Attention抵消了效果降低,具体描述见 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].
End-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].
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 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].
Self-attention,有时称为intra-attention,是一种attention机制,它关联单个序列的不同位置以计算序列的表示。 Self-attention已成功用于各种任务,包括阅读理解、摘要概括、文本蕴涵和学习与任务无关的句子表征[4,27,28,22]。
端到端的内存网络基于循环attention机制,而不是序列对齐的循环,并且已被证明在简单语言的问题回答和语言建模任务中表现良好[34]。
就我们所知,Transformer是第一个完全依靠self-attention来计算输入和输出表示而不使用序列对齐RNN或卷积的转换模型。 在后续章节中,我们将描述Transformer,引出self-attention并讨论它相对 [17, 18]和[9]几个模型的优势。
Most competitive neural sequence transduction models have an encoder-decoder structure [5, 2, 35]. Here, the encoder maps an input sequence of symbol representations () to a sequence of continuous representations z = (
). Given z, the decoder then generates an output sequence (
) 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.
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.
大部分神经序列转换模型都有一个编码器-解码器结构[5, 2, 35]。编码器把一个输入序列()映射到一个连续的表示 z = (
)。解码器对z中的每个元素,生成输出序列(
)。在每一步中,模型都是自回归的[10],在生成下一个时,会将先前生成的符号作为附加输入。
Transformer的编码器和解码器都使用self-attention堆叠和point-wise、完全连接的层,如Figure 1的左、右两边所示。
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. 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 = 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.
编码器: 编码器由N = 6 个完全相同的层组成。 每一层都有两个子层。 第一层是一个multi-head self-attention机制,第二层是一个简单的、位置全连通的前馈网络。 我们对每个子层再采用一个残差连接[11] ,接着进行层标准化[1]。 也就是说,每个子层的输出是LayerNorm(x + Sublayer(x)),其中Sublayer(x) 是由子层本身实现的函数。 为了便于进行残差连接,模型中的所有子层以及embedding层产生的输出的维度都为 = 512。
解码器: 解码器也是由N = 6 个完全相同的层组成。 除了每个编码器层中的两个子层之外,解码器还有第三个子层,该层对编码器的输出执行multi-head attention。 与编码器类似,我们在每个子层再采用残差连接,然后进行层标准化。 我们还修改解码器中的self-attention子层,以防止当前位置关注后续位置。 这种掩码结合将输出embedding偏移一个位置,确保对位置 i 的预测只依赖位置小于i 的已知输出。
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 of the values, where the weight assigned to each value is computed by a compatibility function of the query with the corresponding key.
Attention功能可以描述为将query和一组key-value对映射到输出,其中query、key、value和输出都是向量。 输出为value的加权和,其中每个value的权重通过query与相应key的兼容函数来计算。
We call our particular attention "Scaled Dot-Product Attention" (Figure 2). The input consists of queries and keys of dimension , and values of dimension
. We compute the dot products of the query with all keys, divide each by
, and apply a softmax function to obtain the weights on the values.
In 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: (1)
Figure 2左侧为"缩放的点积Attention"。其输入为query、维度为的key、维度为
的value。我们计算query和所有key的点积,然后对每个除以
,最后用softmax函数获得value的权重。
在实践中,我们同时计算一组query的attention函数,并将它们组合成一个矩阵Q。 key和value也一起组成矩阵 K 和 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 . 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.
While for small values of the 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
, the dot products grow large in magnitude, pushing the softmax function into regions where it has extremely small gradients. To counteract this effect, we scale the dot products by
.
两个最常用的attention函数是加法attention[2]和点积(乘法)attention。除了缩放因子,点积Attention跟我们的算法一样。加法attention使用具有单个隐层的前馈网络计算兼容函数。虽然理论上点积attention和加法attention复杂度相似,但在实践中,点积attention可以使用高度优化的矩阵乘法来实现,因此点积attention计算更快、更节省空间。
当的值比较小的时候,这两个机制的性能相近。当
比较大时,加法attention比不带缩放的点积attention性能好[3]。 我们怀疑,对于很大的
值,点积大幅度增长,将softmax函数推向具有极小梯度的区域。 为了抵消这种影响,我们将点积缩小
倍。
Instead of performing a single attention function with -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
,
and
dimensions, respectively. On each of these projected versions of queries, keys and values we then perform the attention function in parallel, yielding
-dimensional output values. These are concatenated and once again projected, resulting in the final values, as depicted in Figure 2
我们发现将query、key和value分别进行h次不同的、学到的到、
和
维的线性映射效果更好,而不是用
维的query、key和value执行单个attention函数。 基于query、key和value的每个映射,我们并行执行attention函数,产生
维输出值。 将它们连接并再次映射,产生最终值,如图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.
Multi-head attention允许模型联合关注不同位置的不同表示子空间的信息。如果只有一个attention head,它的平均值会削弱这个信息。
Where the projections are parameter matrices and
.
In this work we employ h = 8 parallel attention layers, or heads. For each of these we use =
=
/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 = 8 个并行attention层或head。对每个head, =
=
/h = 64。 由于每个head的大小减小,总的计算成本与具有全部维度的单个head attention相似。
The Transformer uses multi-head attention in three different ways:
Transformer以3种方式使用multi-head attention:
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.
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 = 512, and the inner-layer has dimensionality
=2048.
除了attention子层,编码器和解码器的每层还包含一个全连接前馈网络,该网络分别单独作用于每个位置。该网络包含两个线性转换,中间有一个ReLU激活。
虽然线性变换在不同位置上是相同的,但每层的参数不同。它的另一种描述方式是两个内核大小为1的卷积。 输入和输出的维度为 = 512,内层的维度为
= 2048。
Similarly to other sequence transduction models, we use learned embeddings to convert the input tokens and output tokens to vectors of dimension . 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
.
与其他序列转换模型类似,我们使用学习到的embedding将输入token和输出token转换为维的向量。我们还使用学到的线性变换和softmax函数将解码器的输出转换为预测的下一个token的概率。在我们的模型中,我们在两个embedding层之间和pre-softmax线性变换共享相同的权重矩阵,类似于[30]。在embedding层中,我们将这些权重乘以
。
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 as the embeddings, so that the two can be summed. There are many choices of positional encodings, learned and fixed [9].
由于我们的模型不包含循环和卷积,为了让模型利用序列的顺序,我们必须加入一些序列中token的相对或者绝对位置的信息。为此,我们将“位置编码”添加到编码器和解码器底部的输入embeddinng中。位置编码和embedding的维度相同,也是,所以这两个向量可以相加。 有多种位置编码可以选择,例如通过学习得到的位置编码和固定的位置编码[9]。
In this work, we use sine and cosine functions of different frequencies:
where pos is the position and i is the dimension. That is, each dimension of the positional encoding corresponds to a sinusoid. The wavelengths form a geometric progression from 2π to 10000 · 2π. 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, can be represented as a linear function of
.
We also experimented with using learned positional embeddings [9] instead, and found that the two versions produced nearly identical results (see Table 3 row (E)). We chose the sinusoidal version because it may allow the model to extrapolate to sequence lengths longer than the ones encountered during training.
在这项工作中,我们使用不同频率的正弦和余弦函数:
其中pos是位置,i 是维度。 也就是说,位置编码的每个维度对应于一个正弦曲线。 这些波长形成一个从2π 到10000 ⋅ 2π的几何级数。 我们选择这个函数是因为我们假设它会让模型很容易学习对相对位置的关注,因为对任意确定的偏移k, 都可以表示为
的线性函数。
我们还用学习到的位置embedding[9]进行了试验,发现这两个版本的结果几乎是相同的(参见表 3 行(E))。我们之所以选择正弦曲线,是因为它可以让模型推断比训练期间遇到的更长的序列。
In this section we compare various aspects of self-attention layers to the recurrent and convolutional layers commonly used for mapping one variable-length sequence of symbol representations (x1, ..., xn) to another sequence of equal length (z1, ..., zn), with , such as a hidden layer in a typical sequence transduction encoder or decoder. Motivating our use of self-attention we consider three desiderata.
One is the total computational complexity per layer. Another is the amount of computation that can be parallelized, as measured by the minimum number of sequential operations required.
The third is the path length between long-range dependencies in the network. Learning long-range dependencies is a key challenge in many sequence transduction tasks. One key factor affecting the ability to learn such dependencies is the length of the paths forward and backward signals have to traverse in the network. The shorter these paths between any combination of positions in the input and output sequences, the easier it is to learn long-range dependencies [12]. Hence we also compare the maximum path length between any two input and output positions in networks composed of the different layer types.
在这一节中,我们将self-attention与循环和卷积层进行比较,后者通常用于将变长的符号序列表示()映射到另一个等长的序列(
),
,例如一个典型的序列转换编码器或解码器中的隐层。使用self-attention主要是为了解决以下三个问题。
一个是每层的总计算复杂度。另一个是可以并行的计算量,以所需的最少顺序操作数来衡量。
第三个是网络中长距离依赖之间的路径长度。在许多序列转换任务中,学习长距离依赖性是一个主要的挑战。 影响学习这种依赖性能力的一个关键因素是前向和后向信号在网络中传播的路径长度。输入和输出序列中任意位置组合之间的这些路径越短,学习远距离依赖性就越容易[12]。因此,我们还比较了由不同类型网络层组成的网络中任意两个输入和输出位置之间的最大路径长度。
As noted in Table 1, a self-attention layer connects all positions with a constant number of sequentially executed operations, whereas a recurrent layer requires O(n) sequential operations. In terms of computational complexity, self-attention layers are faster than recurrent layers when the sequence length n is smaller than the representation dimensionality d, which is most often the case with sentence representations used by state-of-the-art models in machine translations, such as word-piece [38] and byte-pair [31] representations. To improve computational performance for tasks involving very long sequences, self-attention could be restricted to considering only a neighborhood of size r in the input sequence centered around the respective output position. This would increase the maximum path length to O(n/r). We plan to investigate this approach further in future work.
如表1所示,self-attention层只需要常量顺序执行的操作就可以将所有位置连接起来,而循环层需要O(n) 顺序操作。 在计算复杂度方面,机器翻译中最先进的模型经常遇到序列长度n小于表示的维度d的情况,例如单词[38]表示法和字节对[31]表示法,此时,self-attention层比循环层要快很多。为了提高包含很长序列的任务的计算性能,可以将self-attention限制在以各自输出位置为中心的输入序列中 r 大小的邻域内。这会将最大路径长度增加到O(n/r)。我们计划在今后的工作中进一步研究这种方法。
A single convolutional layer with kernel width k < n does not connect all pairs of input and output positions. Doing so requires a stack of O(n/k) convolutional layers in the case of contiguous kernels, or in the case of dilated convolutions [18], increasing the length of the longest paths between any two positions in the network. Convolutional layers are generally more expensive than recurrent layers, by a factor of k. Separable convolutions [6], however, decrease the complexity considerably, to
. Even with k = n, however, the complexity of a separable convolution is equal to the combination of a self-attention layer and a point-wise feed-forward layer, the approach we take in our model.
As side benefit, self-attention could yield more interpretable models. We inspect attention distributions from our models and present and discuss examples in the appendix. Not only do individual attention heads clearly learn to perform different tasks, many appear to exhibit behavior related to the syntactic and semantic structure of the sentences.
核宽度为 k < n 的单层卷积不能连接每一对输入和输出的位置对。要这么做,卷积核为邻近核的情况下需要O(n/k)个卷积层,在扩展卷积的情况下需要个层[18],这增加了网络中任意两个位置之间的最长路径的长度。卷积层通常比循环层更耗费资源,大约为k倍。然而,可分卷积[6]可以把复杂度大幅减少到
。 然而,即使k = n,一个可分卷积的复杂度等同于self-attention层和point-wise前馈层的组合,即我们的模型采用的方法。
间接的好处是,self-attention可以产生更可解释的模型。我们从我们的模型中研究attention的分布,并在附录中进行展示和讨论。每个attention head不仅清楚地学习了执行不同的任务,许多attention head似乎还能学到与句子的句法和语义结构相关的行为。
This section describes the training regime for our models.
本节介绍我们的模型训练方法
We trained on the standard WMT 2014 English-German dataset consisting of about 4.5 million sentence pairs. Sentences were encoded using byte-pair encoding [3], which has a shared source-target vocabulary of about 37000 tokens. For English-French, we used the significantly larger WMT 2014 English-French dataset consisting of 36M sentences and split tokens into a 32000 word-piece vocabulary [38]. Sentence pairs were batched together by approximate sequence length. Each training batch contained a set of sentence pairs containing approximately 25000 source tokens and 25000 target tokens.
我们在标准的WMT 2014英语-德语数据集上进行了训练,该数据集包含约450万个句子对。 这些句子使用字节对编码[3]进行编码,源语句和目标语句共享大约37000个token的词汇表。对于英语-法语翻译,我们使用了更大的WMT 2014英语-法语数据集,该数据集包含3600万个句子,并将tokens分成32000个word-piece词汇表[38]。句子对按大致的序列长度分批处理。 每个训练批次的句子对包含大约25000个源token和25000个目标token。
We trained our models on one machine with 8 NVIDIA P100 GPUs. For our base models using the hyper parameters described throughout the paper, each training step took about 0.4 seconds. We trained the base models for a total of 100,000 steps or 12 hours. For our big models,(described on the bottom line of table 3), step time was 1.0 seconds. The big models were trained for 300,000 steps (3.5 days).
我们在一台有8个NVIDIA P100 GPU的机器上训练我们的模型。使用本文描述的超参数的基础模型,每个训练步骤耗时约0.4秒。我们对基础模型进行了总共100000步或12小时的训练。对于我们的大型模型(见表3的底部),步进时间为1.0秒,模型训练了30万步(3.5天)。
We used the Adam optimizer [20] with and
. We varied the learning rate over the course of training, according to the formula:
This corresponds to increasing the learning rate linearly for the first warmup_steps training steps, and decreasing it thereafter proportionally to the inverse square root of the step number. We used warmup_steps = 4000.
我们使用Adam优化[20],其中及
。我们根据以下公式在训练过程中改变学习率:
这对应于在刚开始的warmup_steps步中线性地增加学习速率,然后随后将其与步数的平方根成比例地减小。 其中,warmup_steps = 4000。
We employ three types of regularization during training:
Residual Dropout We apply dropout [33] to the output of each sub-layer, before it is added to the sub-layer input and normalized. In addition, we apply dropout to the sums of the embeddings and the positional encodings in both the encoder and decoder stacks. For the base model, we use a rate of = 0.1.
Label Smoothing During training, we employed label smoothing of value = 0.1 [36]. This hurts perplexity, as the model learns to be more unsure, but improves accuracy and BLEU score.
训练时我们采用三种正则化:
残差丢弃 在将每个子层的输出与子层的输入进行相加并规范化之前,我们对其进行dropout[33]。此外,在编码器和解码器中,我们对embedding和位置编码的和进行dropout。对于基础模型,我们使用的丢弃率 = 0.1。
Label 平滑 在训练过程中,我们使用的label 平滑的值为 = 0.1[36]。 这让模型不易理解,因为模型学得更加不确定,但提高了准确性和BLEU得分。
两种dropout,加上Label平滑,所以是三种正则化..
On the WMT 2014 English-to-German translation task, the big transformer model (Transformer (big) in Table 2) outperforms the best previously reported models (including ensembles) by more than 2.0 BLEU, establishing a new state-of-the-art BLEU score of 28.4. The configuration of this model is listed in the bottom line of Table 3. Training took 3.5 days on 8 P100 GPUs. Even our base model surpasses all previously published models and ensembles, at a fraction of the training cost of any of the competitive models.
在WMT 2014英语-德语翻译任务中,big transformer模型(表2中的Transformer (big))比之前报道的最佳模型(包括集成模型)的高出2.0 BLEU以上,新的最高BLEU分数为28.4。该模型的配置列于表3的底部。模型在8个P100 GPU上训练3.5天。即使是我们的基础模型,其表现也超过了之前的模型和集成模型,且模型训练时间比之前模型要小的多。
On the WMT 2014 English-to-French translation task, our big model achieves a BLEU score of 41.0, outperforming all of the previously published single models, at less than 1/4 the training cost of the previous state-of-the-art model. The Transformer (big) model trained for English-to-French used dropout rate Pdrop = 0.1, instead of 0.3.
在WMT 2014英语-法语翻译任务中,我们的大型模型的BLEU得分达到41.0分,优于之前发布的所有单一模型,训练成本不到之前最先进模型的1/4。英语-法语翻译任务训练的Transformer (big)模型使用的丢弃率为=0.1,而不是0.3。
For the base models, we used a single model obtained by averaging the last 5 checkpoints, which were written at 10-minute intervals. For the big models, we averaged the last 20 checkpoints. We used beam search with a beam size of 4 and length penalty α = 0.6 [38]. These hyperparameters were chosen after experimentation on the development set. We set the maximum output length during inference to input length + 50, but terminate early when possible [38].
Table 2 summarizes our results and compares our translation quality and training costs to other model architectures from the literature. We estimate the number of floating point operations used to train a model by multiplying the training time, the number of GPUs used, and an estimate of the sustained single-precision floating-point capacity of each GPU 5.
对于基础模型,我们使用最后5个检查点的平均值得到,这些检查点每10分钟写一次。对于大型模型,我们对最后20个检查点进行平均得到。我们使用了beam search,beam大小为4 ,长度惩罚α = 0.6 [38]。这些超参数是在开发集上进行实验后选定的。在推断时,我们设置最大输出长度为输入长度+50,但会提前中止[38]。
表2总结了我们的结果,并将我们的翻译质量和训练成本与文献中的其他模型框架进行了比较。 我们通过将训练时间、所使用的GPU的数量以及每个GPU的持续单精度浮点能力的估计相乘来估计训练模型所需的浮点运算的数量。
To evaluate the importance of different components of the Transformer, we varied our base model in different ways, measuring the change in performance on English-to-German translation on the development set, newstest2013. We used beam search as described in the previous section, but no checkpoint averaging. We present these results in Table 3.
In Table 3 rows (A), we vary the number of attention heads and the attention key and value dimensions, keeping the amount of computation constant, as described in Section 3.2.2. While single-head attention is 0.9 BLEU worse than the best setting, quality also drops off with too many heads.
In Table 3 rows (B), we observe that reducing the attention key size hurts model quality. This suggests that determining compatibility is not easy and that a more sophisticated compatibility function than dot product may be beneficial. We further observe in rows (C) and (D) that, as expected, bigger models are better, and dropout is very helpful in avoiding over-fitting. In row (E) we replace our sinusoidal positional encoding with learned positional embeddings [9], and observe nearly identical results to the base model.
为了评估Transformer不同组件的重要性,我们以不同的方式改变我们的基础模型,用测量集newstest2013上英文-德文翻译的性能来评估这些改动。如前所述,我们使用了beam search,但没使用checkpoint平均。我们在表3中列出了这些模型变体的结果。
在表3的(A)行中,我们改变attention head的数量、attention key和value的维度,保持计算量不变,如第3.2.2节所述。虽然只有一个head attention比最佳性能差0.9 BLEU,但质量也会因head太多而下降。
在表3(B)行中,我们观察到减小attention key的大小会有损模型质量。这表明,确定兼容性并不容易,并且比点积更复杂的兼容性函数可能更有用。我们在(C)行和(D)行中进一步观察到,正如预期的那样,模型越大越好,并且dropout对避免过拟合非常有效。在(E)行中,我们用学到的位置embedding代替正弦位置编码[9],并观察到与基础模型几乎相同的结果。
To evaluate if the Transformer can generalize to other tasks we performed experiments on English constituency parsing. This task presents specific challenges: the output is subject to strong structural constraints and is significantly longer than the input. Furthermore, RNN sequence-to-sequence models have not been able to attain state-of-the-art results in small-data regimes [37].
We trained a 4-layer transformer with = 1024 on the Wall Street Journal (WSJ) portion of the Penn Treebank [25], about 40K training sentences. We also trained it in a semi-supervised setting, using the larger high-confidence and BerkleyParser corpora from with approximately 17M sentences [37]. We used a vocabulary of 16K tokens for the WSJ only setting and a vocabulary of 32K tokens for the semi-supervised setting.
为了评估Transformer是否可以推广到其他任务,我们进行了English constituency parsing的实验。这项任务有如下挑战:输出受到很强的结构约束,且输出长度大大高于输入。此外,RNN sequence-to-sequence模型无法在小数据场景获得较好的结果[37]。
我们基于Penn Treebank [25]的《华尔街日报》(Wall Street Journal)训练了一个=1024的4层transformer,大约4万个训练句子。我们还进行了半监督训练,使用更大的高置信度和BerkleyParser语料库,其中包含约1700万个句子[37]。我们对只有WSJ的数据使用包含16K tokens的词汇表,对半监督训练使用包含32K tokens的词汇表。
We performed only a small number of experiments to select the dropout, both attention and residual (section 5.4), learning rates and beam size on the Section 22 development set, all other parameters remained unchanged from the English-to-German base translation model. During inference, we increased the maximum output length to input length + 300. We used a beam size of 21 and α = 0.3 for both WSJ only and the semi-supervised setting.
Our results in Table 4 show that despite the lack of task-specific tuning our model performs surprisingly well, yielding better results than all previously reported models with the exception of the Recurrent Neural Network Grammar [8].
In contrast to RNN sequence-to-sequence models [37], the Transformer outperforms the Berkeley-Parser [29] even when training only on the WSJ training set of 40K sentences.
基于Section 22测试集,我们进行了少量的实验来选择Attention和残差网络的dropout、学习率、beam size,其他参数跟英语-德语基础模型保持一致。推断时,我们把最大的输出长度设置为输入长度+300。对只有WSJ和半监督场景,beam size为21,α = 0.3。
表4中的结果表明,尽管没进行特定任务的调整,我们的模型仍然表现的很好,比先前报告的所有模型效果更好,除了Recurrent Neural Network Grammar [8]。
与RNN sequence-to-sequence模型[37]相比,即使只在由40K个句子组成的WSJ训练集上进行训练,Transformer的性能也优于Berkeley-Parser [29]。
In this work, we presented the Transformer, the first sequence transduction model based entirely on attention, replacing the recurrent layers most commonly used in encoder-decoder architectures with multi-headed self-attention.
For translation tasks, the Transformer can be trained significantly faster than architectures based on recurrent or convolutional layers. On both WMT 2014 English-to-German and WMT 2014 English-to-French translation tasks, we achieve a new state of the art. In the former task our best model outperforms even all previously reported ensembles.
在这项工作中,我们提出了Transformer,第一个完全基于attention的序列转换模型,用multi-headed self-attention取代了编码器-解码器架构中最常用的循环层。
对于翻译任务,Transformer比基于循环或卷积层的体系结构训练的更快。在WMT 2014英语-德语和WMT 2014英语-法语翻译任务中,我们取得了最好的结果。在WMT 2014英语-德语任务中,我们最好的模型甚至胜过以前报道过的所有集成模型。
We are excited about the future of attention-based models and plan to apply them to other tasks. We plan to extend the Transformer to problems involving input and output modalities other than text and to investigate local, restricted attention mechanisms to efficiently handle large inputs and outputs such as images, audio and video. Making generation less sequential is another research goals of ours.
The code we used to train and evaluate our models is available at https://github.com/tensorflow/tensor2tensor.
我们对基于attention的模型的未来感到兴奋,并计划将它们应用到其他任务中。 我们计划将Transformer扩展到除文本之外的涉及输入和输出模式的问题,并研究局部的、受限attention机制,以有效地处理图像、音频和视频等大型输入和输出。让生成具有更少的顺序性是我们的另一个研究目标。
我们用于训练和评估模型的代码可以在 https://github.com/tensorflow/tensor2tensor 找到。