Paper:2017年的Google机器翻译团队《Transformer:Attention Is All You Need》翻译并解读

Paper:2017年的Google机器翻译团队《Transformer:Attention Is All You Need》翻译并解读论文评价2017年,Google机器翻译团队发表的《Attention is all you need》中大量使用了自注意力(self-attention)机制来学习文本表示。参考文章:《attention is all you need》解读1、Motivation:靠attention机制,不使用rnn和cnn,并行度高通过attention,抓长距离依赖关系比rnn强2、创新点:通过self-attention,自己和自己做attention,使得每个词都有全局的语义信息(长依赖由于 Self-Attention 是每个词和所有词都要计算 Attention,所以不管他们中间有多长距离,最大的路径长度也都只是 1。可以捕获长距离依赖关系提出multi-head attention,可以看成attention的ensemble版本,不同head学习不同的子空间语义。论文地址链接:《Attention Is All You Need》PDF:《Attention Is All You Need》AbstractThe 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 BLEUon 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,它完全基于注意机制,完全不需要递归和卷积。在两个机器翻译任务上的实验表明,这些模型具有更好的并行性和更少的训练时间。我们的模型在WMT 2014英语到德语翻译任务中达到28.4的BLEU,改进现有的最佳结果,包括集成,超过2 BLEU。在WMT 2014英法翻译任务中,我们的模型在8个GPU上训练3.5天后,建立了一个新的单模型最新的BLEU分数41.8,这是文献中最好模型的训练成本的一小部分。我们将该Transformer成功地应用于具有大量和有限训练数据的英语选区句法分析中,证明了该变换器对其他任务具有良好的推广效果。注:BLEU是一种文本评估算法,即Bilingual Evaluation Understudy,它是用来评估机器翻译跟专业人工翻译之间的对应关系,核心思想就是机器翻译越接近专业人工翻译,质量就越好,经过BLEU算法得出的分数可以作为机器翻译质量的其中一个指标。1、IntroductionRecurrent 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].∗Equal contribution. Listing order is random. Jakob proposed replacing RNNs with self-attention and started the effort to evaluate this idea. Ashish, with Illia, designed and implemented the first Transformer models and has been crucially involved in every aspect of this work. Noam proposed scaled dot-product attention, multi-head attention and the parameter-free position representation and became the other person involved in nearly every detail. Niki designed, implemented, tuned and evaluated countless model variants in our original codebase and tensor2tensor. Llion also experimented with novel model variants, was responsible for our initial codebase, and efficient inference and visualizations. Lukasz and Aidan spent countless long days designing various parts of and implementing tensor2tensor, replacing our earlier codebase, greatly improving results and massively accelerating our research.  †Work performed while at Google Brain.  ‡Work performed while at Google Research.递归神经网络,特别是LSTM[13]和GRU[7]神经网络,已经作为序列建模和转导问题(如语言建模和机器翻译[35,2,5])的最新方法被牢固地建立起来。此后,无数的努力继续推进递归语言模型和编码器-解码器体系结构的界限[38,24,15]。*同等贡献。列表顺序是随机的。Jakob建议用self-attention取代RNNs,并开始努力评估这个想法。Ashish和Illia一起设计并实现了第一个Transformer 模型,并在这项工作的各个方面都有重要的参与。Noam提出了标度点积注意、多头注意和无参数位置表示,成为几乎涉及每个细节的另一个人。Niki在我们最初的代码库和tensor2tensor中设计、实现、调整和评估了无数的模型变体。Llion还试验了新的模型变体,负责我们的初始代码库,以及有效的推理和可视化。Lukasz和Aidan花了无数天的时间设计和实现Tensor2Sensor的各个部分,取代了我们早期的代码库,极大地改进了结果,极大地加速了我们的研究。在谷歌大脑工作期间完成的工作。‡在谷歌研究所工作期间完成的工作。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. 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.递归模型通常沿输入和输出序列的符号位置进行因子计算。将位置与计算时间中的步骤对齐,它们生成隐藏状态的序列ht,作为先前隐藏状态ht-1和位置t的输入的函数。这种固有的序列性质排除了训练示例中的并行化,而在较长的序列长度下,并行化变得至关重要,因为内存限制限制了跨示例的批处理。最近的工作通过因子分解技巧[21]和条件计算[32]在计算效率方面取得了显著的提高,同时也提高了后者的模型性能。然而,顺序计算的基本约束仍然存在。Attention 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.    注意机制已经成为各种任务中强制序列建模和转换模型的一个组成部分,允许不考虑输入或输出序列中的距离的依赖关系建模[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、BackgroundThe 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〕和VusS2S〔9〕的基础,所有这些都使用卷积神经网络作为基本构建块,并行计算所有输入和输出位置的隐藏表示。在这些模型中,将来自两个任意输入或输出位置的信号关联起来所需的操作数在位置之间的距离中增长,convs2为线性增长,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].Self-attention,有时称为注意内注意,是一种注意机制,它将单个序列的不同位置联系起来,以计算序列的表示。Self-attention在阅读理解、抽象概括、语篇蕴涵和学习任务无关的句子表征等任务中得到了成功的运用[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].端到端的记忆网络是基于一种循环注意机制而不是顺序排列的循环,并且已经被证明在简单的语言问答和语言建模任务中表现良好[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].然而,据我们所知,Transformer 是第一个完全依赖于self-attention来计算其输入和输出表示的传导模型,而不使用序列对齐的RNN或卷积。在下面的章节中,我们将描述Transformer ,激发self-attention,并讨论其相对于[17,18]和[9]等模型的优势。3、Model ArchitectureMost 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.大多数竞争性神经序列转导模型都具有编码器-解码器结构[5,2,35]。这里,编码器将符号表示的输入序列(x1,…,xn)映射到连续表示的序列z=(z1,…,zn)。给定z,解码器然后一次生成一个符号的输出序列(y1,…,ym)。在每一步,模型都是自回归的[10],在生成下一步时,将先前生成的符号作为附加输入。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的左半部分和右半部分所示。

Figure 1: The Transformer - model architecture.3.1、Encoder and Decoder StacksEncoder: The encoder is composed of a stack of N self-attention1]. That is, the output of each sub-layer isLayerNorm(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个相同层组成。每层有两个子层。第一层是多头multi-head self-attention机制,第二层是一个简单的、位置全连接的前馈网络。我们在两子层的每一个子层周围使用一个残差连接[11],然后是层规范化[1]。也就是说,每个子层的输出是LayerNorm(x + Sublayer(x)),其中Sublayer(x) 是子层本身实现的功能。为了方便这些残差连接,模型中的所有子层以及嵌入层都会生成维d model=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 attention。与编码器类似,我们在每个子层周围使用残差连接,然后进行层规范化。我们还修改解码器堆栈中的自关注子层,以防止位置关注后续位置。这种掩蔽加上输出嵌入偏移一个位置的事实,确保位置i的预测只能依赖于小于i的位置处的已知输出。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 of the values, where the weight assigned to each value is computed by a compatibility function of the query with the corresponding key.一个注意函数可以描述为将查询和一组键值对映射到输出,其中query, keys, values和output 都是向量。输出被计算为值的加权和,其中分配给每个值的权重由查询的兼容函数和相应的键计算。

Figure 2: (left) Scaled Dot-Product Attention. (right) Multi-Head Attention consists of several attention layers running in parallel.图2:(左)缩放点积注意力机制          (右图)多头注意力机制由几个平行运行的注意力层组成。3.2.1、Scaled Dot-Product AttentionThe input consists of queries and keys of dimension dk , and values of dimension dv . 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.我们称特别注意为“缩放点积注意”(图2)。输入由维度dk的查询和键以及维度dv的值组成。我们使用所有键计算查询的点积,用√dk除以每个键,然后应用softmax函数获得值的权重。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:

在实际应用中,我们同时计算一组查询的注意函数,将它们组合成一个矩阵Q,并将键和值组合成矩阵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. Additive attention computes the compatibility function using a feed-forward network witha single hidden layer. While the two are similar in theoretical complexity, dot-product attention ismuch faster and more space-efficient in practice, since it can be implemented using highly optimized matrix multiplication code.最常用的两个注意函数是additive attention[2]和dot-product attention(乘法)。dot-product attention与我们的算法相同,除了比例因子。additive attention使用具有单个隐藏层的前馈网络计算兼容性函数。虽然这两种方法在理论复杂度上是相似的,但是由于它可以用高度优化的矩阵乘法码来实现,所以在实际应用中,dot-product attention要快得多,空间也更有效。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 4. To counteract this effect, we scale the dot products by而对于dk的小值,两种机制的表现相似,additive attention优于dot product attention,而对于dk的大值则没有标度[3]。我们怀疑,对于dk的大值,点积在数量级上增长很大,将softmax函数推到梯度非常小的区域4。为了抵消这一影响,我们将 dot products积按

3.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 , dk and dv dimensions, respectively. On each of these projected versions of queries, keys and values we then perform the attention function in parallel, yielding dv -dimensional output values. These are concatenated and once again projected, resulting in the final values, as depicted in Figure 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.我们发现,不同于使用dmodel维度的键、值和查询来执行单一的注意功能,将查询、键和值分别以不同的线性投影h次线性投影到dk、dk和dv维度是有益的。然后,在这些查询、键和值的投影版本中,我们并行地执行注意功能,生成dv维输出值。如图2所示,这些被连接起来并再次投影,从而产生最终值。Multi-head attention允许模型共同关注来自不同位置的不同表示子空间的信息。只有一个注意力集中的头脑,平均化可以抑制这种情况。In this work we employ h = 8 parallel attention layers, or heads. For each of these we use dk = dv = dmodel/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个平行的注意层,或者说头部。对于每一个,我们使用dk=dv=dmodel/h=64。由于每个头部的维数减少,总的计算成本与全维度的单头部注意的计算成本相似。

3.2.3、Applications of Attention in our ModelThe 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].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.Transformer 以三种不同的方式使用multi-head: 在“编码器-解码器-注意”层中,查询来自上一个解码器层,而内存键和值来自编码器的输出。这使得解码器中的每个位置都可以参与输入序列中的所有位置。这模仿了典型的编码器-解码器-注意机制的顺序对序列模型,如[38,2,9]。编码器包含self-attention层。在自关注层中,所有键、值和查询都来自同一个位置,在本例中,是编码器中前一层的输出。编码器中的每个位置都可以处理编码器前一层中的所有位置。类似地,解码器中的 self-attention层允许解码器中的每个位置关注解码器中直到并包括该位置的所有位置。为了保持解码器的自回归特性,需要防止解码器中的信息向左流动。我们通过屏蔽softmax输入中所有与非法连接相对应的值(设置为–∞)来实现这个内标度点积注意。见图2。3.3、Position-wise Feed-Forward NetworksIn 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.FFN(x) = max(0, xW1 + b1)W2 + b2 (2)

除了注意力子层之外,我们的编码器和解码器中的每一层都包含一个完全连接的前馈网络,该网络分别且相同地应用于每个位置。。这包括两个线性变换,中间有一个ReLU激活。FFN(x)=max(0,xW1+b1)W2+b2While 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 df f = 2048.虽然不同位置的线性变换是相同的,但它们在不同的层之间使用不同的参数。另一种描述方法是两个核大小为1的卷积。输入输出的维数为dmodel=512,内层的维数为df f=2048。3.4、Embeddings and SoftmaxSimilarly to other sequence transduction models, we use learned embeddings to convert the input tokens and output tokens to vectors of dimension dmodel. We also use the usual learned linear transfor- mation 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 √dmodel.与其他序列转换模型类似,我们使用学习的嵌入来将输入标记和输出标记转换为维度dmodel的向量。我们还使用通常的学习线性变换和softmax函数将解码器输出转换为预测的下一个令牌概率。在我们的模型中,我们在两个嵌入层和pre-softmax线性变换之间共享相同的权重矩阵,类似于[30]。在嵌入层中,我们将这些权重乘以√dmodel。3.5、Positional EncodingSince 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 dmodel as the embeddings, so that the two can be summed. There are many choices of positional encodings, learned and fixed [9].由于我们的模型不包含递归和卷积,为了使模型能够利用序列的顺序,我们必须注入一些关于序列中标记的相对或绝对位置的信息。为此,我们将“位置编码”添加到编码器和解码器堆栈底部的输入嵌入中。位置编码与嵌入编码具有相同的维度dmodel,因此可以将它们相加。有许多位置编码的选择,学习和固定的[9]。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.

表1:不同层类型的最大路径长度、每层复杂度和最小顺序操作数。n为序列长度,d为表示维数,k为卷积的核大小,r为受限自我注意的邻域大小。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, P Epos+k can be represented as a linear function of P Epos.在这项工作中,我们使用不同频率的正弦和余弦函数:其中pos是位置,i是维度。也就是说,位置编码的每个维度对应于一个正弦。波长形成了从2π到10000·2π的几何级数。我们选择这个函数是因为我们假设它可以让模型很容易地学会通过相对位置来参与,因为对于任何固定偏移量k,P-Epos+k可以表示为P-Epos的线性函数。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.我们还尝试使用学习的位置嵌入[9],发现这两个版本产生了几乎相同的结果(见表3第(E)行)。我们之所以选择正弦曲线,是因为它可能允许模型外推到比训练中遇到的序列长度更长的序列。4、Why Self-AttentionIn this section we compare various aspects of self-attention layers to the recurrent and convolu- tional 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.在本节中,我们将self-attention层的各个方面与通常用于映射一个可变长度的符号表示序列(x1,…,xn)到另一个等长序列(Z1,…,Zn)的递归和卷积层进行比较。例如典型的序列转换编码器或解码器中的隐藏层。激发我们使用self-attention,我们考虑三个目的。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.一个是每层的总计算复杂度。另一个是可以并行化的计算量,用所需的最少顺序操作数来衡量。第三个是网络中长距离依赖关系之间的路径长度。在许多序列转导任务中,学习长程依赖性是一个关键的挑战。影响学习这种依赖关系的能力的一个关键因素是网络中向前和向后信号必须经过的路径的长度。输入和输出序列中任何位置组合之间的这些路径越短,就越容易学习长期依赖性[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时,自关注层比递归层更快,这是最常用的机器翻译中最先进的模型所使用的句子表示的情况,例如Word(38)和字节对(31)表示。为了提高包含很长序列的任务的计算性能,可以将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 O(logk (n)) 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 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<n的单个卷积层不能连接所有输入和输出位置对。这样做需要一堆O(n/k)卷积层(对于相邻的核),或者O(logk(n))卷积层(对于扩展卷积)[18],增加网络中任意两个位置之间最长路径的长度。卷积层通常比递归层更昂贵,由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.作为附带好处,self-attention可以产生更多可解释的模型。我们从我们的模型中检查注意分布,并在附录中给出和讨论示例。不仅个体的注意头清楚地学会了执行不同的任务,许多似乎表现出与句子的句法和语义结构有关的行为。5、TrainingThis section describes the training regime for our models.本节介绍我们的模型的训练制度。5.1、Training Data and BatchingWe 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个标记的共享源-目标词汇表。对于英语-法语,我们使用了更大的WMT 2014英语-法语数据集,该数据集包含3600万个句子,并将标记拆分为32000个词条词汇[38]。句子对由近似的序列长度组合在一起。每个训练批次包含一组句子对,其中包含大约25000个源令牌和25000个目标令牌。5.2、Hardware and Schedule—8台+12小时/3.5天We trained our models on one machine with 8 NVIDIA P100 GPUs. For our base models using the hyperparameters 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天)的训练。5.3、Optimizer—Adam优化器We used the Adam optimizer [20] with β1 = 0.9, β2 = 0.98 and E = 10−9. We varied the learning rate over the course of training, according to the formula:

我们使用Adam优化器[20],beta1=0.9,beta2=0.98,E=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.4、Regularization‌—3种正则化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 Pdrop = 0.1.在训练期间,我们采用3种正则化: 在将Dropout[33]添加到子层输入并规范化之前,我们对每个子层的输出应用Dropout[33]。此外,我们还将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.

Label Smoothing During training, we employed label smoothing of value Els = 0.1 [36]. This hurts perplexity, as the model learns to be more unsure, but improves accuracy and BLEU score.表2:Transformer在英语到德语和英语到法语的newstest2014测试中取得了比以前最先进的模式更好的BLEU分数,只需花费很少的训练成本。在训练中,我们使用Els = 0.1[36]的值进行标签平滑。这伤害了perplexity,因为模型学会了更不确定,但提高了准确性和BLEU分数。6、Results6.1、Machine TranslationOn 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.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英德翻译任务中,big transformer模型(表2中的transformer(big))比之前报告的最佳模型(包括集成)的表现超过2.0 BLEU,新的最新BLEU分数为28.4。此型号的配置列于表3的最后一行。训练时间为3.5天,平均成绩为8 P100。即使是我们的基础模型也超过了所有之前发布的模型和集合,只是任何竞争模型的训练成本的一小部分。在WMT 2014英法翻译任务中,我们的大模型达到了41.0的BLEU分数,超过了所有之前发布的单一模型,在不到1/4的训练成本的前一个最先进的模式。为英语到法语培训的Transformer(big)模型使用的是辍学率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 [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].对于基本模型,我们使用一个通过平均最后5个检查点(以10分钟为间隔写入)获得的模型。对于大型模型,我们平均使用了最后20个检查点。我们使用波束搜索,波束大小为4,长度惩罚α=0.6[38]。这些超参数是在开发集上进行实验后选择的。在输入长度为50时,我们设定最大输出长度,但在可能时终止(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.表2总结了我们的结果,并将我们的翻译质量和训练成本与文献中的其他模型架构进行了比较。我们通过乘以训练时间、使用的GPU数量和每个GPU 5的持续单精度浮点容量,来估计用于训练模型的浮点操作的数量。6.2、Model VariationsTo 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不同部件的重要性,我们以不同的方式改变了我们的基本模型,测量了开发集newstest2013中英德语翻译的性能变化。我们使用前一节中描述的波束搜索,但没有检查点平均。这些结果见表3。

Table 4: The Transformer generalizes well to English constituency parsing (Results are on Section 23 of WSJ)表4:Transformer很好地概括了英语选民解析(结果见《华尔街日报》第23章)

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,但如果头太多,质量也会下降。6.3、English Constituency ParsingTo 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].为了评估转换程序是否可以推广到其他任务,我们进行了英语选区解析的实验。这项任务提出了具体的挑战:产出受到强烈的结构限制,而且明显长于投入。此外,RNN序列到序列模型无法在小数据区获得最新的结果[37]。We trained a 4-layer transformer with dmodel = 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.我们在《华尔街日报》(Wall Street Journal)的Penn Treebank[25]部分训练了一个dmodel=1024的4层transformer ,大约4万个训练句子。我们还训练了它在半监督设置,使用较大的高置信度和BerkleyParser语料库从大约17M句[37 ]。我们只对WSJ设置使用了16K令牌的词汇表,对半监督设置使用了32K令牌的词汇表。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.我们只进行了少量的实验来选择22段开发集上的dropout、attention 和residual (第5.4节)、学习率和beam 大小,所有其他参数从英语到德语的基础翻译模型保持不变。在推理过程中,我们将最大输出长度增加到输入长度+ 300。我们使用21和α=0.3的光束尺寸,仅用于WSJ和半监督设置。Our results in Table 4 show that despite the lack of task-specific tuning our model performs sur- prisingly 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.我们在表4中的结果表明,尽管缺乏特定于任务的调整,我们的模型仍然运行得很好,产生的结果比以前报告的所有模型都要好,除了递归神经网络语法[8]。与RNN的序列到序列模型[37]相比,Transformer甚至在仅接受华尔街日报的40K句子训练集训练时,也比Berkeley- Parser[29]表现更好。7、ConclusionIn 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,它用多头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 。在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.Acknowledgements We are grateful to Nal Kalchbrenner and Stephan Gouws for their fruitful comments, corrections and inspiration.我们用来训练和评估模型的代码可以在https://github.com/tensorflow/tensor2tensor上找到。感谢Nal Kalchbrenner和Stephan Gouws的富有成效的评论、更正和启发。References[1] Jimmy Lei Ba, Jamie Ryan Kiros, and Geoffrey E Hinton. Layer normalization. arXiv preprint arXiv:1607.06450, 2016.[2] Dzmitry Bahdanau, Kyunghyun Cho, and Yoshua Bengio. Neural machine translation by jointly learning to align and translate. CoRR, abs/1409.0473, 2014.[3] Denny Britz, Anna Goldie, Minh-Thang Luong, and Quoc V. Le. Massive exploration of neural machine translation architectures. CoRR, abs/1703.03906, 2017.[4] Jianpeng Cheng, Li Dong, and Mirella Lapata. Long short-term memory-networks for machine reading. arXiv preprint arXiv:1601.06733, 2016.[5] Kyunghyun Cho, Bart van Merrienboer, Caglar Gulcehre, Fethi Bougares, Holger Schwenk, and Yoshua Bengio. Learning phrase representations using rnn encoder-decoder for statistical machine translation. CoRR, abs/1406.1078, 2014.[6] Francois Chollet. Xception: Deep learning with depthwise separable convolutions. arXiv preprint arXiv:1610.02357, 2016.[7] Junyoung Chung, Çaglar Gülçehre, Kyunghyun Cho, and Yoshua Bengio. Empirical evaluation of gated recurrent neural networks on sequence modeling. CoRR, abs/1412.3555, 2014.[8] Chris Dyer, Adhiguna Kuncoro, Miguel Ballesteros, and Noah A. Smith. Recurrent neural network grammars. In Proc. of NAACL, 2016.[9] Jonas Gehring, Michael Auli, David Grangier, Denis Yarats, and Yann N. Dauphin. Convolu- tional sequence to sequence learning. arXiv preprint arXiv:1705.03122v2, 2017.[10] Alex Graves. Generating sequences with recurrent neural networks. arXiv preprint arXiv:1308.0850, 2013.[11] Kaiming He, Xiangyu Zhang, Shaoqing Ren, and Jian Sun. Deep residual learning for im- age recognition. In Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition, pages 770–778, 2016.[12] Sepp Hochreiter, Yoshua Bengio, Paolo Frasconi, and Jürgen Schmidhuber. Gradient flow in recurrent nets: the difficulty of learning long-term dependencies, 2001.[13] Sepp Hochreiter and Jürgen Schmidhuber. Long short-term memory. Neural computation, 9(8):1735–1780, 1997.[14] Zhongqiang Huang and Mary Harper. Self-training PCFG grammars with latent annotations across languages. In Proceedings of the 2009 Conference on Empirical Methods in Natural Language Processing, pages 832–841. ACL, August 2009.[15] Rafal Jozefowicz, Oriol Vinyals, Mike Schuster, Noam Shazeer, and Yonghui Wu. Exploring the limits of language modeling. arXiv preprint arXiv:1602.02410, 2016.[16] Łukasz Kaiser and Samy Bengio. Can active memory replace attention? In Advances in Neural Information Processing Systems, (NIPS), 2016.[17] Łukasz Kaiser and Ilya Sutskever. Neural GPUs learn algorithms. In International Conference on Learning Representations (ICLR), 2016.[18] Nal Kalchbrenner, Lasse Espeholt, Karen Simonyan, Aaron van den Oord, Alex Graves, and Ko- ray Kavukcuoglu. Neural machine translation in linear time. arXiv preprint arXiv:1610.10099v2, 2017.[19] Yoon Kim, Carl Denton, Luong Hoang, and Alexander M. Rush. Structured attention networks.In International Conference on Learning Representations, 2017.[20] Diederik Kingma and Jimmy Ba. Adam: A method for stochastic optimization. In ICLR, 2015. [21] Oleksii Kuchaiev and Boris Ginsburg. Factorization tricks for LSTM networks. arXiv preprint‌ arXiv:1703.10722, 2017.[22] Zhouhan Lin, Minwei Feng, Cicero Nogueira dos Santos, Mo Yu, Bing Xiang, Bowen Zhou, and Yoshua Bengio. A structured self-attentive sentence embedding. arXiv preprint arXiv:1703.03130, 2017.[23] Minh-Thang Luong, Quoc V. Le, Ilya Sutskever, Oriol Vinyals, and Lukasz Kaiser. Multi-task sequence to sequence learning. arXiv preprint arXiv:1511.06114, 2015.[24] Minh-Thang Luong, Hieu Pham, and Christopher D Manning. Effective approaches to attention- based neural machine translation. arXiv preprint arXiv:1508.04025, 2015.[25] Mitchell P Marcus, Mary Ann Marcinkiewicz, and Beatrice Santorini. Building a large annotated corpus of english: The penn treebank. Computational linguistics, 19(2):313–330, 1993.[26] David McClosky, Eugene Charniak, and Mark Johnson. Effective self-training for parsing. In Proceedings of the Human Language Technology Conference of the NAACL, Main Conference, pages 152–159. ACL, June 2006.[27] Ankur Parikh, Oscar Täckström, Dipanjan Das, and Jakob Uszkoreit. A decomposable attention model. In Empirical Methods in Natural Language Processing, 2016.[28] Romain Paulus, Caiming Xiong, and Richard Socher. A deep reinforced model for abstractive summarization. arXiv preprint arXiv:1705.04304, 2017.[29] Slav Petrov, Leon Barrett, Romain Thibaux, and Dan Klein. Learning accurate, compact, and interpretable tree annotation. In Proceedings of the 21st International Conference on Computational Linguistics and 44th Annual Meeting of the ACL, pages 433–440. ACL, July 2006.[30] Ofir Press and Lior Wolf. Using the output embedding to improve language models. arXiv preprint arXiv:1608.05859, 2016.[31] Rico Sennrich, Barry Haddow, and Alexandra Birch. Neural machine translation of rare words with subword units. arXiv preprint arXiv:1508.07909, 2015.[32] Noam Shazeer, Azalia Mirhoseini, Krzysztof Maziarz, Andy Davis, Quoc Le, Geoffrey Hinton, and Jeff Dean. Outrageously large neural networks: The sparsely-gated mixture-of-experts layer. arXiv preprint arXiv:1701.06538, 2017.[33] Nitish Srivastava, Geoffrey E Hinton, Alex Krizhevsky, Ilya Sutskever, and Ruslan Salakhutdi- nov. Dropout: a simple way to prevent neural networks from overfitting. Journal of Machine Learning Research, 15(1):1929–1958, 2014.[34] Sainbayar Sukhbaatar, Arthur Szlam, Jason Weston, and Rob Fergus. End-to-end memory networks. In C. Cortes, N. D. Lawrence, D. D. Lee, M. Sugiyama, and R. Garnett, editors, Advances in Neural Information Processing Systems 28, pages 2440–2448. Curran Associates, Inc., 2015.[35] Ilya Sutskever, Oriol Vinyals, and Quoc VV Le. Sequence to sequence learning with neural networks. In Advances in Neural Information Processing Systems, pages 3104–3112, 2014.[36] Christian Szegedy, Vincent Vanhoucke, Sergey Ioffe, Jonathon Shlens, and Zbigniew Wojna. Rethinking the inception architecture for computer vision. CoRR, abs/1512.00567, 2015.[37] Vinyals & Kaiser, Koo, Petrov, Sutskever, and Hinton. Grammar as a foreign language. In Advances in Neural Information Processing Systems, 2015.[38] Yonghui Wu, Mike Schuster, Zhifeng Chen, Quoc V Le, Mohammad Norouzi, Wolfgang Macherey, Maxim Krikun, Yuan Cao, Qin Gao, Klaus Macherey, et al. Google’s neural machine translation system: Bridging the gap between human and machine translation. arXiv preprint arXiv:1609.08144, 2016.[39] Jie Zhou, Ying Cao, Xuguang Wang, Peng Li, and Wei Xu. Deep recurrent models with fast-forward connections for neural machine translation. CoRR, abs/1606.04199, 2016.[40] Muhua Zhu, Yue Zhang, Wenliang Chen, Min Zhang, and Jingbo Zhu. Fast and accurate shift-reduce constituent parsing. In Proceedings of the 51st Annual Meeting of the ACL (Volume 1: Long Papers), pages 434–443. ACL, August 2013.

(0)

相关推荐