【论文翻译】Attention is all you need

Abstract

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.
我们提出了一个新的简单的网络架构,Transformer,完全基于注意力机制,完全免除了递归和卷积。
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 Englishto-German translation task, improving over the existing best results, including ensembles, by over 2 BLEU.
我们的模型在WMT 2014英语到德语翻译任务中达到了28.4 BLEU,比现有的最佳结果(包括集成)提高了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.0 after training for 3.5 days on eight GPUs, a small fraction of the training costs of the best models from the literature.
在WMT 2014英语到法语的翻译任务中,我们的模型在8个GPU上训练了3.5天后,建立了一个新的单模型最先进的BLEU得分为41.0,这是文献中最佳模型训练成本的一小部分。

7.Conclusion

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.
在这项工作中,我们提出了Transformer,这是第一个完全基于注意力的序列转换模型,用多头自注意力取代了编码器-解码器架构中最常用的递归层。
For translation tasks, the Transformer can be trained significantly faster than architectures based on recurrent or convolutional layers.
对于翻译任务,Transformer的训练速度明显快于基于递归或卷积层的架构。
On both WMT 2014 English-to-German and WMT 2014 English-to-French translation tasks, we achieve a new state of the art.
在WMT 2014英语到德语和WMT 2014英语到法语的翻译任务中,我们都达到了最先进的水平。
In the former task our best model outperforms even all previously reported ensembles.
在前一个任务中,我们最好的模型甚至优于所有以前报道的合奏。
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.
我们计划将Transformer扩展到涉及文本以外的输入和输出方式的问题,并研究本地的有限注意力机制,以有效地处理大型输入和输出,如图像,音频和视频。减少世代的连续性是我们的另一个研究目标。
The code we used to train and evaluate our models is available at https://github.com/ tensorflow/tensor2tensor.
我们用来训练和评估模型的代码可以在https://github.com/ tensorflow/tensor 2 tensor上找到。
Acknowledgements
致谢
We are grateful to Nal Kalchbrenner and Stephan Gouws for their fruitful comments, corrections and inspiration.
我们感谢Nal Kalchbrenner和Stephan Gouws富有成效的评论、更正和启发。

1.Introduction

导言
Recurrent neural networks, long short-term memory [12] 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 [29, 2, 5].
递归神经网络,特别是长短期记忆[12]和门控递归神经网络[7],已经被牢固地确立为序列建模和转导问题(如语言建模和机器翻译)中的最先进方法[29,2,5]。
Numerous efforts have since continued to push the boundaries of recurrent language models and encoder-decoder architectures [31, 21, 13].
此后,许多努力继续推动递归语言模型和编码器-解码器架构的边界[31,21,13]。
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 ht, as a function of the previous hidden state ht−1 and the input for position t.
将位置与计算时间中的步骤对齐,它们生成隐藏状态ht的序列,作为前一个隐藏状态ht-1和位置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 [18] and conditional computation [26], while also improving model performance in case of the latter.
最近的工作通过因式分解技巧[18]和条件计算[26]实现了计算效率的显着提高,同时还提高了后者的模型性能。
The fundamental constraint of sequential computation, however, remains.
然而,顺序计算的基本约束仍然存在。
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, 16]. In all but a few cases [22], however, such attention mechanisms are used in conjunction with a recurrent network.
注意力机制已经成为各种任务中引人注目的序列建模和转导模型的组成部分,允许在不考虑它们在输入或输出序列中的距离的情况下对依赖关系进行建模[2,16]。然而,除了少数情况外,在所有情况下[22],这种注意力机制都与循环网络结合使用。
In all but a few cases, 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.
在这项工作中,我们提出了Transformer,一个模型架构避免复发,而是完全依赖于注意力机制,以绘制输入和输出之间的全局依赖关系。
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支持更高的并行化,在8个P100 GPU上训练12小时后,翻译质量就能达到最新水平。

2.Background

The goal of reducing sequential computation also forms the foundation of the Extended Neural GPU [20], ByteNet [15] and ConvS2S [8], all of which use convolutional neural networks as basic building block, computing hidden representations in parallel for all input and output positions.
减少顺序计算的目标也构成了扩展神经GPU [20],ByteNet [15]和ConvS2S [8]的基础,所有这些都使用卷积神经网络作为基本构建块,并行计算所有输入和输出位置的隐藏表示。
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.
在这些模型中,将来自两个任意输入或输出位置的信号关联起来所需的操作数量随着位置之间的距离而增长,对于ConvS2S是线性的,而对于ByteNet是线性的。
This makes it more difficult to learn dependencies between distant positions [11].
这使得学习远距离位置之间的依赖关系变得更加困难[11]。
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.
在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),有时也被称为内部注意力(intra-attention),是一种将单个序列的不同位置联系起来以计算序列的表示的注意力机制。
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, 22, 23, 19].
自我注意已成功用于各种任务,包括阅读理解,抽象概括,文本蕴涵和学习任务独立的句子表征[4,22,23,19]。
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 [28].
端到端记忆网络基于循环注意机制而不是序列对齐的循环,并且已被证明在简单语言问题回答和语言建模任务中表现良好[28]。
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.
然而,据我们所知,Transformer是第一个完全依靠自我注意力来计算其输入和输出的表示而不使用序列对齐的RNN或卷积的转换模型。
In the following sections, we will describe the Transformer, motivate self-attention and discuss its advantages over models such as [14, 15] and [8].
在下面的章节中,我们将描述Transformer,激发自我注意力,并讨论它相对于[14,15]和[8]等模型的优势。

3.Model Architecture

模型架构
Most competitive neural sequence transduction models have an encoder-decoder structure [5, 2, 29].
大多数竞争性神经序列转导模型具有编码器-解码器结构[5,2,29]。
Here, the encoder maps an input sequence of symbol representations (x1, …, xn) to a sequence of continuous representations z = (z1, …, zn).
这里,编码器将符号表示(x1,.,xn)转换为连续表示序列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 [9], consuming the previously generated symbols as additional input when generating the next.
给定z,解码器然后生成输出序列(y1,...,ym)的符号一次一个元素。在每一步,模型都是自回归的[9],在生成下一个符号时,消耗先前生成的符号作为额外的输入。
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.
Transformer遵循这种整体架构,编码器和解码器均使用堆叠的自注意和逐点全连接层,分别如图1的左半部分和右半部分所示。

3.1Encoder and Decoder Stacks

编码器和解码器堆栈
Figure 1: The Transformer - model architecture.
图1:Transformer模型架构。
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 [10] 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.
编码器:编码器由N = 6个相同层的堆栈组成。每层有两个子层。第一种是多头自注意机制,第二种是简单的位置全连接前馈网络。我们在两个子层中的每一个周围使用残差连接[10],然后进行层归一化[1]。也就是说,每个子层的输出是LayerNorm(x + Sublayer(x)),其中Sublayer(x)是子层本身实现的函数。为了促进这些残余连接,模型中的所有子层以及嵌入层产生维度dmodel = 512的输出。
Decoder: The decoder is also composed of a stack ofN = 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相同的层。除了每个编码器层中的两个子层之外,解码器还插入第三子层,该第三子层对编码器堆栈的输出执行多头注意。与编码器类似,我们在每个子层周围使用残差连接,然后进行层归一化。我们还修改了解码器堆栈中的自关注子层,以防止位置关注后续位置。这种掩蔽,结合输出嵌入偏移一个位置的事实,确保了位置i的预测只能依赖于小于i的位置处的已知输出。

3.2Attention

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.
输出被计算为值的加权和,其中分配给每个值的权重由查询与对应键的兼容性函数计算。

Scaled Dot-Product Attention

标度点积注意力
Figure 2: (left) Scaled Dot-Product Attention. (right) Multi-Head Attention consists of several attention layers running in parallel.
图2:(左)标度点积注意力。(右)多头注意力由几个平行运行的注意力层组成。
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 dv.
我们将这种特殊的注意力称为“标度点积注意力”(图2)。输入由维度dk的查询和键以及维度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.
我们计算查询与所有键的点积,将每个键除以√dk,并应用softmax函数来获得值的权重。
In practice, we compute the attention function on a set of queries simultaneously, packed together into a matrix Q.
在实践中,我们同时计算一组查询的注意力函数,这些查询被打包到一个矩阵Q中。
The keys and values are also packed together into matrices K and V. We compute the matrix of outputs as:
键和值也被打包到矩阵K和V中。我们计算输出矩阵为:

The two most commonly used attention functions are additive attention [2], and dot-product (multiplicative) attention.
两种最常用的注意力函数是加法注意力[2]和点积(乘法)注意力。
Dot-product attention is identical to our algorithm, except for the scaling factor of 1/√ dk .
点积注意力与我们的算法相同,除了比例因子为1/√ dk。
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 dk 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 dk, 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 1/√ dk .
虽然对于较小的dk值,这两种机制的表现相似,但在dk值较大的情况下,加法注意力优于点积注意力[3]。我们怀疑,对于较大的dk值,点积的大小会变大,从而将softmax函数推入梯度极小的区域。为了抵消这种影响,我们将点积缩放1/√ dk。

3.2.2Multi-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, dk and dv dimensions, respectively.
我们发现,与使用dmodel维的键、值和查询来执行单个注意力函数不同的是,使用不同的学习线性投影将查询、键和值分别线性投影h次到dk、dk和dv维是有益的。
On each of these projected versions of queries, keys and values we then perform the attention function in parallel, yielding dv-dimensional output values.
在这些查询、键和值的每个投影版本上,我们并行执行注意力函数,产生dv-dimensional输出值。
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.
多头注意力允许模型共同关注来自不同位置的不同表示子空间的信息。对于一个单一的注意力头,平均化抑制了这一点。


其中投影是参数矩阵WQi ∈ Rdmodel×dk,WKi ∈ Rdmodel×dk,WVi ∈ Rdmodel×dv和WO ∈ Rdv ×dmodel。在这项工作中,我们采用h = 8个平行的注意层,或头部。对于每一个,我们使用dk = dv = dmodel/h = 64。由于每个头的维数降低,总的计算成本是类似的单头注意与全维。

3.2.3Applications of Attention in our Model

注意力在模型中的应用
The Transformer uses multi-head attention in three different ways:
Transformer以三种不同的方式使用多头注意力:

  • 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 [31, 2, 8].
  • 在“编码器-解码器注意”层中,查询来自先前的解码器层,并且存储器键和值来自编码器的输出。这使得解码器中的每个位置都可以覆盖输入序列中的所有位置。这模仿了序列到序列模型中典型的编码器-解码器注意力机制,如[31,2,8]。
  • 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 −∞) all values in the input of the softmax which correspond to illegal connections. See Figure 2.
  • 类似地,解码器中的自关注层允许解码器中的每个位置关注解码器中的直到并且包括该位置的所有位置。我们需要防止解码器中的冗余信息流,以保持自回归特性。我们通过屏蔽(设置为−∞)softmax输入中对应于非法连接的所有值来实现这一点。参见图2。

3.3Position-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激活。

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 dmodel = 512, and the inner-layer has dimensionality dff = 2048.
虽然不同位置的线性变换是相同的,但它们在层与层之间使用不同的参数。另一种描述这种情况的方式是两个卷积,内核大小为1。输入和输出的维度为dmodel = 512,内层的维度为dff = 2048。

3.4Embeddings and Softmax

嵌入式和Softmax
Similarly to other sequence transduction models, we use learned embeddings to convert the input tokens and output tokens to vectors of dimension dmodel.
与其他序列转换模型类似,我们使用学习的嵌入将输入令牌和输出令牌转换为维度dmodel的向量。
We also use the usual learned linear transformation and softmax function to convert the decoder output to predicted next-token probabilities.
我们还使用常用的学习线性变换和softmax函数将解码器输出转换为预测的下一个令牌概率。
In our model, we share the same weight matrix between the two embedding layers and the pre-softmax linear transformation, similar to [24].
在我们的模型中,我们在两个嵌入层和pre-softmax线性变换之间共享相同的权重矩阵,类似于[24]。
In the embedding layers, we multiply those weights by √ dmodel.
在嵌入层中,我们将这些权重乘以√ dmodel.

3.5Positional Encoding

位置编码
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.
由于我们的模型不包含递归和卷积,为了让模型利用序列的顺序,我们必须注入一些关于序列中令牌的相对或绝对位置的信息。

Table 1: Maximum path lengths, per-layer complexity and minimum number of sequential operations for 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.
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 dmodel as the embeddings, so that the two can be summed. There are many choices of positional encodings, learned and fixed [8].
为此,我们在编码器和解码器堆栈的底部向输入嵌入添加“位置编码”。位置编码与嵌入具有相同的维度dmodel,因此两者可以相加。有许多位置编码的选择,学习和固定[8]。
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, PEpos+k can be represented as a linear function of PEpos.
其中pos是位置,i是尺寸。即,位置编码的每个维度对应于正弦曲线。波长形成从2π到10000 · 2π的几何级数。我们之所以选择这个函数,是因为我们假设它可以让模型很容易地学会通过相对位置来参与,因为对于任何固定的偏移量k,PEpos+k都可以表示为PEpos的线性函数。
We also experimented with using learned positional embeddings [8] 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.
我们还尝试使用学习的位置嵌入[8],发现两个版本产生了几乎相同的结果(见表3行(E))。我们选择正弦版本,因为它可以允许模型外推到比训练期间遇到的更长的序列长度。

4.Why Self-Attention

为什么自我关注
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 xi, zi ∈ Rd, such as a hidden layer in a typical sequence transduction encoder or decoder. Motivating our use of self-attention we consider three desiderata.
在本节中,我们将自注意层的各个方面与通常用于映射一个可变长度的符号表示序列(x1,...,xn)到另一个相等长度的序列(z1,...,zn),其中xi,zi ∈ Rd,诸如典型序列转换编码器或解码器中的隐藏层。为了激发我们对自我注意力的使用,我们认为有三个必要条件。
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 [11].
输入和输出序列中任意位置组合之间的路径越短,就越容易学习长程依赖性[11]。
Hence we also compare the maximum path length between any two input and output positions in networks composed of the different layer types.
因此,我们还比较了由不同层类型组成的网络中任意两个输入和输出位置之间的最大路径长度。
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.
如表1所示,自注意层用恒定数量的顺序执行操作连接所有位置,而递归层需要O(n)顺序操作。
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 [31] and byte-pair [25] representations.
就计算复杂度而言,当序列长度n小于表示维度d时,自注意层比递归层更快,这是最常见的情况,最先进的机器翻译模型使用的句子表示,例如词段[31]和字节对[25]表示。
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.
为了提高涉及非常长的序列的任务的计算性能,自我注意力可以被限制为仅考虑以相应的输出位置为中心的输入序列中的大小为r的邻域。
This would increase the maximum path length to O(n/r). We plan to investigate this approach further in future work.
这将使最大路径长度增加到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 O(logk(n)) in the case of dilated convolutions [15], increasing the length of the longest paths between any two positions in the network.
具有内核宽度k < n的单个卷积层不连接所有输入和输出位置对。这样做需要一个O(n/k)卷积层的堆栈(在连续内核的情况下),或者O(logk(n))(在扩张卷积的情况下)[15],增加了网络中任何两个位置之间的最长路径的长度。
Convolutional layers are generally more expensive than recurrent layers, by a factor of k. Separable convolutions [6], however, decrease the complexity considerably, to O(k · n · d + n · d2). 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.
卷积层通常比递归层昂贵k倍。然而,可分离卷积[6]大大降低了复杂度,为O(k · n · d + n · d2)。然而,即使k = n,可分离卷积的复杂性也等于自注意层和逐点前馈层的组合,这是我们在模型中采用的方法。
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.
作为附带的好处,自我注意力可以产生更多可解释的模型。我们从我们的模型中检查注意力分布,并在附录中展示和讨论示例。不仅个别注意头清楚地学会执行不同的任务,许多人似乎表现出与句子的句法和语义结构相关的行为。

5.Training

This section describes the training regime for our models.
本节描述了我们模型的训练机制。

5.1Training Data and Batching

训练数据和批处理
We trained on the standard WMT 2014 English-German dataset consisting of about 4.5 million sentence pairs.
我们在标准的WMT 2014英语-德语数据集上进行了训练,该数据集由大约450万个句子对组成。
Sentences were encoded using byte-pair encoding [3], which has a shared sourcetarget vocabulary of about 37000 tokens.
句子使用字节对编码[3]进行编码,它具有大约37000个标记的共享源目标词汇表。
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 [31].
对于英语-法语,我们使用了更大的WMT 2014英语-法语数据集,其中包含3600万个句子,并将标记拆分为32000个单词。
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.
每个训练批次包含一组句子对,其中包含大约25000个源标记和25000个目标标记。

5.2Hardware and Schedule

硬件和时间表
We trained our models on one machine with 8 NVIDIA P100 GPUs. 7
我们在一台配备8个NVIDIA P100 GPU的机器上训练我们的模型。
For our base models using the hyperparameters described throughout the paper, each training step took about 0.4 seconds.
对于我们使用本文中描述的超参数的基础模型,每个训练步骤大约需要0.4秒。
We trained the base models for a total of 100,000 steps or 12 hours.
我们对基础模型进行了总共10万步或12小时的训练。
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).
对于我们的大模型(在表3的底部行描述),步进时间为1.0秒。大模型被训练了30万步(3.5天)。

5.3Optimizer

优化程序
We used the Adam optimizer [17] with β1 = 0.9, β2 = 0.98 and = 10−9. We varied the learning rate over the course of training, according to the formula:
我们使用Adam优化器[17],其中β1 = 0.9,β2 = 0.98,β 2 = 10−9。我们根据以下公式在训练过程中改变学习率:

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.
这对应于对于第一warmup_steps训练步骤线性地增加学习速率,并且此后与步骤数的平方根倒数成比例地减小学习速率。我们使用warmup_steps = 4000。

5.4Regularization

正则化
We employ three types of regularization during training:
我们在训练过程中使用三种类型的正则化:
Residual Dropout
We apply dropout [27] 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 Pdrop = 0.1.
残留脱落
我们将dropout [27]应用于每个子层的输出,然后将其添加到子层输入并归一化。此外,我们将dropout应用于编码器和解码器堆栈中的嵌入和位置编码的总和。对于基础模型,我们使用Pdrop = 0.1的速率。

Table 2: The Transformer achieves better BLEU scores than previous state-of-the-art models on the English-to-German and English-to-French newstest2014 tests at a fraction of the training cost.
Table 2: The Transformer achieves better BLEU scores than previous state-of-the-art models on the English-to-German and English-to-French newstest2014 tests at a fraction of the training cost.

Label Smoothing
During training, we employed label smoothing of value ls = 0.1 [30]. This hurts perplexity, as the model learns to be more unsure, but improves accuracy and BLEU score.
标签平滑
在训练过程中,我们使用了值为0.1的标签平滑[30]。这会伤害困惑,因为模型会变得更加不确定,但会提高准确性和BLEU分数。

6.Results

Machine Translation

机器翻译
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.
在WMT 2014英语到德语的翻译任务中,大Transformer模型(表2中的Transformer(大))比之前报道的最佳模型(包括集成)的BLEU高出2.0以上,建立了28.4的新的最先进的BLEU分数。
The configuration of this model is listed in the bottom line of Table 3.
该型号的配置列于表3的底部行。
Training took 3.5 days on 8 P100 GPUs.
在8个P100 GPU上进行了3.5天的训练。
Even our base model surpasses all previously published models and ensembles, at a fraction of the training cost of any of the competitive models.
甚至我们的基础模型也超过了所有以前发布的模型和集合,而训练成本只是任何竞争模型的一小部分。
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.
在WMT 2014英语到法语的翻译任务中,我们的大模型达到了41.0的BLEU分数,超过了之前发布的所有单个模型,而训练成本不到之前最先进模型的1/4。
The Transformer (big) model trained for English-to-French used dropout rate Pdrop = 0.1, instead of 0.3.
针对英语到法语训练的Transformer(大)模型使用了丢弃率Pdrop = 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 [31]. 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 [31].
对于基本模型,我们使用通过平均最后5个检查点获得的单个模型,这些检查点以10分钟的间隔写入。对于大型模型,我们平均了最后20个检查点。我们使用波束搜索,波束大小为4,长度惩罚α = 0.6 [31]。这些超参数是在开发集上进行实验后选择的。我们将推理过程中的最大输出长度设置为输入长度+ 50,但尽可能提前终止[31]。
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.
表2总结了我们的结果,并将我们的翻译质量和培训成本与文献中的其他模型架构进行了比较。我们通过乘以训练时间、使用的GPU数量以及每个GPU的持续单精度浮点容量估计值来估计用于训练模型的浮点运算数量。

Model Variations

型号变化
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.
为了评估Transformer不同组件的重要性,我们以不同的方式改变了我们的基础模型,在开发集newst2013上测量了英语到德语翻译的性能变化。我们使用了前一节中描述的波束搜索,但没有检查点平均。我们在表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.
在表3的行(A)中,我们改变了注意力头部的数量以及注意力键和值维度,保持计算量不变,如3.2.2节所述。虽然单头注意力比最佳设置差0.9 BLEU,但质量也会随着过多的头而下降。

Table 3: Variations on the Transformer architecture. Unlisted values are identical to those of the base model. All metrics are on the English-to-German translation development set, newstest2013. Listed perplexities are per-wordpiece, according to our byte-pair encoding, and should not be compared to per-word perplexities.
表3:Transformer架构的变化。未列出的值与基本模型的值相同。所有指标都是在英语到德语翻译开发集,newstest2013。根据我们的字节对编码,列出的困惑是每个单词的,不应该与每个单词的困惑进行比较。

In Table 3 rows (B), we observe that reducing the attention key size dk 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 [8], and observe nearly identical results to the base model.
在表3行(B)中,我们观察到减小注意力键大小dk会损害模型质量。这表明确定兼容性并不容易,并且比点积更复杂的兼容性函数可能是有益的。我们在行(C)和(D)中进一步观察到,正如预期的那样,更大的模型更好,并且dropout非常有助于避免过度拟合。在行(E)中,我们用学习的位置嵌入[8]替换了正弦位置编码,并观察到与基本模型几乎相同的结果。