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.
主流的序列转换模型基于复杂的循环神经网络或卷积神经网络,一般包括一个编码器和一个解码器。且性能好的模型往往需要用注意力层来连接编码器和解码器。
在Transformer之前,主流的序列模型一般要用到RNN或CNN技术,多采用encoder-decoder结构,尤其是引入注意力的encoder-decoder结构。
- 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.
- 我们提出了一个新的神经网络架构——Transformer,它完全基于注意力机制,不再依赖循环层和卷积层。在两个机器翻译任务上的实验表明,Transformer在结果上质量更优,同时具有更强的并行计算能力,需要的训练时间也显著减少。我们的模型在2014年WMT英德翻译任务中达到了28.4 BLEU,比现有的最佳结果(包括集成部分)提高了2个BLEU以上。在WMT 2014年英语到法语的翻译任务中,我们的模型在8个GPU上训练3.5天后,创造了单模型的最佳结果——BLEU 41.8分,这只是既往文献中最佳模型训练成本的一小部分而以。
Transformer只使用注意力机制,但它的表现更好。
- 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能很好的适应于其它任务。
Transformer有很广泛的应用前景。
- Recurrent neural networks, long short-term memory and gated recurrent 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 . Numerous efforts have since continued to push the boundaries of recurrent language models and encoder-decoder architectures.
- RNN,尤其是LSTM和GRU,已成为序列建模和转换问题(如语言建模和机器翻译)的牢固方法。自此,大量的工作继续扩大了循环语言模型和编码器-解码器体系结构的界限。
肯定了RNN相关技术在序列模型上的贡献。
- 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.
- 循环模型通常是沿着输入和输出序列的符号位置进行因子计算。在计算时将位置与步骤对齐,它们生成一个隐藏状态序列ht, ht根据它前面的隐状态ht-1和当前时刻t的输入生成。这种内部的固有顺阻碍了训练样本的并行化,在序列较长时,这个问题变得更加严重,因为内存空间是有限的,这将限制了样本之间的批处理。
介绍RNN相关技术的简要原理,指出RNN技术的缺点 ———— 并行计算能力差。
要额外指出的是,RNN也难以构建长距离的依赖关系,具体而言,RNN几乎不能学到距离某点很远的位置的信息,即存在长程依赖问题。
综上所述,RNN两大短板:并行计算能力差、长程依赖问题
- Recent work has achieved significant improvements in computational efficiency through factorization tricks and conditional computation, while also improving model performance in case of the latter. 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 . 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. 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小时,就可以在翻译质量上达到一个新的最佳效果。
注意力机制拥有更好的并行计算的能力,它可以克服RNN的两大缺点,因此可以用注意力机制代替RNN,这就是Transformer。
- The goal of reducing sequential computation also forms the foundation of the Extended Neural GPU, ByteNet and ConvS2S, 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.
- 减少序列计算的目标也成就了 Extended Neural GPU ,ByteNet和ConvS2S,它们都使用了卷积神经网络作为基础模块,并行计算所有输入和输出位置的隐藏表示。在这些模型中,将来自两个任意输入或输出位置的信号关联起来所需的操作数,随位置间的距离而增长,ConvS2S为线性增长,ByteNet为对数增长。这使得学习远距离位置之间的依赖性变得更加困难。
CNN技术也可以用到序列模型中,但受计算量的限制,某种意义上也存在长程依赖问题。
- 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节所述,我们用多头注意力抵消这种影响。
注意力机制可以克服CNN的短板,但带来了“分辨率降低”的问题,但这可以通过多头注意力解决。
*存在疑问:分辨率降低是什么?*
- 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 .
- 自注意力,有时也叫做内部注意力,是一种注意力机制,它将一个序列的不同位置联系起来,以计算序列的表示。自注意力已经成功的运用到了很多任务上,包括阅读理解、抽象摘要、语篇蕴涵和学习任务无关的句子表征等。
简要介绍自注意力机制的相关概念。
- 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 .
- 使用循环注意力机制替代序列对齐的端到端的记忆网络, 已经被证明,在简单的语言问答和语言建模任务中表现良好。
再次说用注意力机制可以代替RNN
*存在疑问:循环注意力机制?是否可以理解为,每次的输出都要作为下一次decoder的输入,因此叫循环。*
- 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-attetion来计算其输入和输出表示,而不使用序列对齐的RNN或卷积的转换模型,在下面的章节中,我们将描述Transformer与self-attention,并讨论它相对于[17,18]和[9]等模型的优势。
Transformer是第一个“真 * 纯 * 自注意力机制”的模型。
- Most competitive neural sequence transduction models have an encoder-decoder structure.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 , consuming the previously generated symbols as additional input when generating the next.
- 大多数有竞争力的序列转换模型都有encoder-decoder结构。这里,encoder将符号表示的输入序列(x1 , …, xn ) 映射成一个连续表示的序列z = (z1 , …, zn )。给定z,解码器以一次生成一个字符的方式生成输出序列(y1, …, ym ) 。在每一步,模型都是自回归的,即在生成下一个字符时,要将先前生成的符号作为附加的输入。
encoder-decoder架构简介,并指出Transformer是以encoder-decoder模型为基础架构的,特别的,它会把decoder的上一个输出当作本次输入的一部分重新输入模型。
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遵循这个总体架构,使用堆叠的self-attention层、point-wise和全连接层,分别用于encoder和decoder,如图1的左半部分和右半部分所示。
Transformerd的总体架构,encoder、decoder都采用了模块堆叠的思想。
- 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 around each of the two sub-layers, followed by layer normalization. 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.
- Encoder:encoder由N(N=6)个完全相同的layer堆叠而成。每层有两个子层。第一层是多头自注意力机制,第二层是一个简单的、位置全连接的前馈神经网络(全连阶层)。我们在两个子层的每一层后采用残差连接,接着进行layer normalization(层归一化)。也就是说,每个子层的输出是LayerNorm(x + Sublayer(x)),其中Sublayer(x)是由子层本身实现的函数。为了方便这些残差连接,模型中的所有子层以及embedding层产生的输出维度都为dmodel=512。
encoder由若干结构完全相同的layer组成,每个layer有两个子层,一个是多头注意力子层,一个是前馈的全连阶层,在两个自层的最后都引入了残差结构,然后再做layer normalization,即每个子层的输出都是:LayerNorm(x + Sublayer(x)),特别的,为方便残差连接,所有子层的输出、embedding层的输出维度都要保证一致,文中给的是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 asking, 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.
- Decoder: 解码器也由N(N=6)个完全相同的layer堆叠而成。除了编码器块中的两个子层之外,解码器还插入了第三个子层,该子层对编码器块的输出执行多头注意操作,与编码器相似,我们在每个子层的后面使用了残差连接,之后采用了layer normalization。我们也修改了解码器块中的自注意子层(即引入掩码mask),以防止当前位置信息中被添加进后续的位置信息。这种掩码与偏移一个位置的输出embedding(即接受上一次的输出)相结合, 确保对第 i 个位置的预测只能依赖小于i 的已知输出。
decoder也是若干个一样的layer堆叠成的,但它有三个子层,多出的是第二个子层,即对encoder输出做多头注意力的那个,一般被称为交叉自注意力(cross-attention),每个子层后面也用到了残差结构、layer normalization,此外decoder的自注意力机制是加过掩码的,为了防止后续位置的信息被添加到当前位置中,这样就能保障对第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,keys,values和输出均是向量。输出是values的加权求和,其中每个value的权重通过query与相应key的兼容函数来计算。
Attention的k、q、v的都是向量(组矩阵),输出的结果本质上是v的加权求和,而v的权重是由q、k计算所得。
- 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 . We compute the dot products of the query with all keys, divide each by d k \sqrt{ d_k} dk , 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:- 我们称我们的特殊的注意力机制为Scaled Dot-Product Attention(Figure 2)。输入由query、 dk的key和dv的value组成。我们计算query和所有key的点积,再除以 d k \sqrt{ d_k} dk,然后再通过softmax函数来获取values的权重。在实际应用中,我们把一组query拼接成一个矩阵Q,同时应用attention函数。key和valuue也同样被拼接成矩阵K和矩阵V。我们按照如下方式计算输出矩阵:
采用了引入缩放因子的点积,且在实际计算中q、k、v,都是拼接成矩阵的Q、K、V以方便并行运算。展示计算公式。
- The two most commonly used attention functions are additive attention , and dot-product (multi-plicative) attention. Dot-product attention is identical to our algorithm, except for the scaling factor of 1 d k {1 \over \sqrt{ d_k}} dk1 . 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.
- additive attention和dot-product(multi-plicative) attention是最常用的两个attention 函数。dot-product attention除了没有使用缩放因子 1 d k {1 \over \sqrt{ d_k}} dk1外,与我们的算法相同。Additive attention使用一个具有单隐层的前馈神经网络来计算兼容性函数。尽管在理论上两者的复杂度相似,但是在实践中dot-product attention要快得多,而且空间效率更高,这是因为它可以使用高度优化的矩阵乘法代码来实现。
介绍两种常见的计算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. 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 d k {1 \over \sqrt{ d_k}} dk1 .
- 当dk的值较小时,这两种方法性能表现的相近,当dk比较大时,addtitive attention表现优于 dot-product attention。我们认为对于大的dk,点积在数量级上增长的幅度大,将softmax函数推向具有极小梯度的区域。为了抵消这种影响,我们对点积结果扩大 1 d k {1 \over \sqrt{ d_k}} dk1倍。
引入缩放因子意义的假设。
- 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.Where the projections are parameter matrices WiQ ∈ R d m o d e l × d k R^{d_{model}×{d_k}} Rdmodel×dk , WiK ∈ R d m o d e l × d k R^{d_{model}×{d_k}} Rdmodel×dk , WiV ∈ R d m o d e l × d v R^{d_{model}×{d_v}} Rdmodel×dv and WO ∈ R h d v × d m o d e l R^{hd_{v}×{d_{model}}} Rhdv×dmodel .
- 相比于使dmodel维度的queries,keys,values执行一个attention函数,我们发现多次使用不同的学习到的线性映射把queries, keys 和 values线性映射到dk,dk和dv维度h次是有益的。在queries,keys和values的每个映射版本上,我们并行的执行attention函数,生成dv维输出值。它们被拼接起来再次映射,生成一个最终值,如 Figure 2 中所示。Multi-head attention可以让模型把不同位置子序列的表示都整合到一个信息中。如果只有一个attention-head,它的平均值会削弱这个信息。其中,映射为参数矩阵 WiQ ∈ R d m o d e l × d k R^{d_{model}×{d_k}} Rdmodel×dk , WiK ∈ R d m o d e l × d k R^{d_{model}×{d_k}} Rdmodel×dk , WiV ∈ R d m o d e l × d v R^{d_{model}×{d_v}} Rdmodel×dv and WO ∈ R h d v × d m o d e l R^{hd_{v}×{d_{model}}} Rhdv×dmodel 。
使用全维度的Q、K、V计算多头注意力机制,计算量会大幅增加,因此不妨在计算前利用线性层(不激活的全连阶层)对它们进行线性降维,对降维后的数据进行多头注意力计算,然后将结果拼接,作为最终的结果。
- 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个并行attention层或head(即采用8个头)。 对每个head,我们使用 dk = dv = dmodel / h = 64。 由于每个head尺寸上的减小,总的计算成本与使用全部维度的单个head attention相似。
为保障拼接后的结果维度不变(为残差连接提供便利),降维后的维度与头数的选择是要慎重的,具体而言应满足,
dk = dv = dmodel/ h,其中h是头数。
理论上讲,以
dmodel = 256, h = 8为例,对Q、K、V的降维需要矩阵
Wqi 、Wki、Wvi,各8套,每个矩阵的形状为256 * 32。
但在实际的应用中,多采用以
Wq 、Wk、Wv(形状为256 * 256)进行线性变换,然后将结果分别拆成8份即可。
应该明确,要想由输入数据 I 获得 Q、K、V,必须经由矩阵
Wq、Wk、Wv做线性变换才行,然后Q、K、V的降维运算需要经由另一套矩阵
Wq 、Wk、Wv做线性变换,因此实际上是涉及到了两次线性变换。
但实际上任何连续两次线性变换的都可以由另一个线性变换所代替(矩阵乘法的特点),因此可以直接用一套做尺寸不变的矩阵做线性变化,然后拆分即可。
具体的线性变换过程可以用不加激活函数的全连接实现。
- The Transformer uses multi-head attention in three different ways:
- multi-head attention在Transformer中有三种不同的使用方式:
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 [38, 2, 9].
- 在encoder-decoder attention层中,queries来自前面的decoder层(上次的输出),而keys和values来自encoder的输出。这使得decoder中的每个位置都能关注到输入序列中的所有位置。 这是模仿序列到序列模型中典型的编码器—解码器的attention机制,例如[38, 2, 9]。(decoder的块中的交叉注意部分)
交叉注意,decoder块中的第二部分,q来自于decoder的前次输出,k、v来自于encoder的输出,这样可以让模型更好的考察前面的输出与encoder输出中的信息。
- 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.
- encoder包含self-attention层。 在self-attention层中,所有的key、value和query来自同一个地方,在这里是encoder中前一层的输出。 encoder中的每个位置都可以关注到encoder上一层的所有位置。(encoder的attention)。
encoder中的注意力机制,这是最简单的内容,q、k、v都来自于上层的输出,每个位置都关注上层的所有位置。
- 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.
- 类似地,decoder中的self-attention层允许decoder中的每个位置都关注decoder层中当前位置之前的所有位置(包括当前位置)。 为了保持解码器的自回归特性,需要防止解码器中的信息向左流动。我们在scaled dot-product attention的内部 ,通过屏蔽softmax输入中所有的非法连接值(设置为 −∞)实现了这一点。(mask-attention)
mask-attention,decoder中的注意力,它关注的是当前位置,以及之前位置的信息,是带掩码的,通过屏蔽softmax输入中的所有非法连接(设定为-∞)来实现mask。
- 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 dmodel = 512, and the inner-layer has dimensionality dff = 2048.
- 除了注意力子层之外,我们的每个encder和decoder中的每个层还包含一个全连接的前馈网络,该网络分别单独应用于每一个位置。这包括两个线性转换,中间有一个ReLU激活。尽管线性变换在不同位置上是相同的,但它们在层与层之间使用不同的参数。 它的另一种描述方式是两组卷积核大小为1的卷积。 输入和输出的维度为dmodel = 512,内部层的维度为dff = 2048。
全链接层,而且所有这一部分都是一样的结构,input->全连接->relu->全连接->output,公式为
relu(xW1+b1)W2+b2,要注意的是,结构相同,参数不同。
同样的功能另一种表示方法,两组卷积核大小为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 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 d m o d e l {\sqrt{ d_{model}}} dmodel .
- 与其他序列转换模型类似,我们使用学习到的嵌入词向量将输入字符和输出字符转换为维度为dmodel的向量。我们还使用普通的线性变换和softmax函数将decoder输出转换为预测的下一个词符的概率。在我们的模型中,两个嵌入层之间和pre-softmax线性变换共享相同的权重矩阵,类似于[30]。 在嵌入层中,我们将这些权重乘以 d m o d e l {\sqrt{ d_{model}}} dmodel。
使用嵌入词向量技术,将输入的字符转换成维度为
dmodel的向量,线性层+softmax的组合可以把decoder的输出转换成预测下一个词符的概率。参数共享,input(encoder的输入)、output(decoder的部分输入,输出)embedding,pre-softmax linear transformation是decoder输出前的linear层。以上三个地方的参数维度是一样的可以共享,不过在嵌入层中权重要乘以
d m o d e l {\sqrt{ d_{model}}} dmodel。
- 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 dmodel as the embeddings, so that the two can be summed. There are many choices of positional encodings, learned and fixed.- 由于我们的模型不包含循环或卷积,为了让模型利用序列的顺序(位置)信息,我们必须加入序列中关于字符相对或者绝对位置的一些信息。 为此,我们在encoder和decoder堆栈底部的输入嵌入编码中添加“位置编码”。 位置编码和嵌入的维度dmodel相同,所以它们两个可以相加。有多种位置编码可以选择,例如通过学习得到的位置编码和固定的位置编码。
位置编码,用于记录序列中向量的位置信息,其维度与embedding的维度相同,即
dmodel,因此两者可以向加,位置编码有多种选择,可以是通过学习得到的,也可以是固定编码。
- In this work, we use sine and cosine functions of different frequencies:
PE( pos,2i ) = sin(pos/10000 2 i / d m o d e l ^{2i/d_{model}} 2i/dmodel )
PE(pos,2i+1) = cos(pos/10000 2 i / d m o d e l ^{2i/d_{model}} 2i/dmodel )
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 .
We also experimented with using learned positional embeddings 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.- 在这项工作(位置编码)中,我们使用不同频率的正弦和余弦函数(来表示位置信息):
PE( pos,2i ) = sin(pos/10000 2 i / d m o d e l ^{2i/d_{model}} 2i/dmodel )
PE(pos,2i+1) = cos(pos/10000 2 i / d m o d e l ^{2i/d_{model}} 2i/dmodel )
其中pos是(向量在序列中的)位置,2i 、2i+1 是(向量中的)维度编号。也就是说,位置编码的每个维度对应于一个正弦曲线。形成了波长从2π到10000·2π的几何数列。我们之所以选择这个函数,是因为我们假设它可以让模型很容易地通过相对位置来学习,因为对任意确定的偏移k, PEpos+k 可以表示为 PEpos 的线性函数。
我们还尝试使用预先学习的位置编码[9]来代替正弦波,但发现这两个版本产生了几乎相同的结果 (see Table 3 row (E))。我们之所以选择正弦曲线,是因为它允许模型扩展到比训练中遇到的序列长度更长的序列。- P E ( p o s , 2 i ) = s i n ( p o s 1000 0 2 i d m o d e l ) PE(pos,2i) = sin(\frac{pos}{10000^{\frac{2i}{d_{model}} }} ) PE(pos,2i)=sin(10000dmodel2ipos)
P E ( p o s , 2 i + 1 ) = c o s ( p o s 1000 0 2 i d m o d e l ) PE(pos,2i+1) = cos(\frac{pos}{10000^{\frac{2i}{d_{model}} }} ) PE(pos,2i+1)=cos(10000dmodel2ipos)
pos代表向量在序列中的位置,2i、2i+1是编码向量的维度,i的取值范围
0~dmodel/2当编码维度是偶数(2i)时用第一个公式,是奇数(2i+1)时用第二个公式。
为什么有用?回顾以下公式
sin(a+b) = sina * cosb + cosa * sinb
cos(a+b) = cosa * cosb - sina * sinb
不难推导出
PE(pos+k , 2i) = PE(pos , 2i) * PE(k , 2i+1) + PE(pos , 2i+1) * PE(k , 2i)
PE(pos+k , 2i+i) = PE(pos , 2i+1) * PE(k , 2i+1) - PE(pos , 2i) * PE(k , 2i)
可以看出,对于pos+k位置的信息可以由pos位置与k位置的向量信息的线性组合来表示(之所以说是线性组合是因为k位置的向量可以被视为常数向量)。这样的线性组合意味着向量中不只有绝对位置信息,还蕴含了相对位置信息。
- 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.
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 layers与常用的recurrent layers和convolutional layers进行各方面的比较,比较的方式是将一个可变长度的符号表示序列 (x1 , …, xn )映射到另一个等长序列(z1 , …, zn ),用 xi , zi ∈ Rd,例如编在一个典型的序列转换模型的编码器或解码器中的隐藏层。我们考察了三个方面,最后促使我们使用self-attention。
一是每层的总计算复杂度(complexity per layer)。另一个是可以并行化的计算量(sequential operations),它以所需的最小序列操作数为衡量。第三个是网络中长距离依赖关系之间的路径长度(maximum path length),在许多序列转换任务中,学习长距离依赖性是一个关键的挑战。影响学习这种依赖关系能力的一个关键因素是网络中向前和向后信号必须经过的路径的长度。输入和输出序列中任意位置组合之间的这些路径越短,越容易学习长距离依赖。因此,我们还比较了在由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. 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 layer用常数次 O(1)的操作连接所有位置,而recurrent layer需要O(n)顺序操作(长程依赖问题)。在计算复杂度方面,当序列长度n小于表示维度d时,self-attention layers比recurrent layers更快,这是使用最先进的机器翻译模型表示句子时的常见情况,例如word-piece [38] 和byte-pair [31] 表示。为了提高包含很长序列的任务的计算性能,可以仅在以输出位置为中心,半径为r的的领域内使用self-attention。这将使最大路径长度增长到O(n/r)。我们计划在今后的工作中进一步研究这种方法。
在长程依赖与并行计算上self-attention相较RNN有明显优势,但只有序列长度小于向量维度时self-attention才会比RNN快,因此只用self-attention时对长序列的计算复杂度更高,即性能更差,但是可以对其进行改进,不对全局做运算,只对局部做处理,采用窗口的思想(有点类似CNN),可以降低降低计算复杂度,但也会导致长程依赖能力降低(最大路径长度增加到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.
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
k(n) 层[18],它们增加了网络中任意两个位置之间的最长路径的长度。 卷积层通常比循环层代价更昂贵,这与因子k有关。然而,可分卷积[6]大幅减少复杂度到O(k⋅n⋅d+n⋅d2)。然而,即使k=n,可分离卷积的复杂度等于self-attention layer和point-wise feed-forward layer的组合,这是我们在模型中采用的方法。
一个随之而来的好处是,self-attention可以产生更多可解释的模型。我们从我们的模型中研究attention的分布,并在附录中展示和讨论示例。每个attention head不仅清楚地学习到执行不同的任务,还表现出了许多和句子的句法和语义结构相关的行为。核宽k
综合来说self-attention不仅在长程依赖与并行计算问题上有很好的能力,而且连带着在可解释性上也有不俗的表现。
- 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万个句子对。 这些句子使用byte-pair编码[3]进行编码,源语句和目标语句共享大约37000个词符的词汇表。 对于英语-法语翻译,我们使用大得多的WMT 2014英法数据集,它包含3600万个句子,并将词符分成32000个word-piece词汇表[38]。 序列长度相近的句子一起进行批处理。 每个训练批次的句子对包含大约25000个源词符和25000个目标词符。
序列长度相近的句子一起进行批处理。
- 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的机器上训练我们的模型。对于paper中描述的使用超参数的基础模型,每个训练步骤大约需要0.4秒。我们对基础模型进行了总共100000步或12小时的训练。对于我们的大型模型(见表3的底线),步进时间为1.0秒。大模型 使用了30万步(3.5天)的训练。
8个 NVIDIA P100 gpu上训练3.5天。
- We used the Adam optimizer [20] with β1 = 0.9, β2 = 0.98 and ϵ = 10−9 . 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],其中β1 = 0.9, β2 = 0.98及ϵ= 10-9。 我们根据以下公式在训练过程中改变学习率:
该公式对应于在第一次warmup_steps 步骤中线性地增加学习速率,并且随后将其与步骤数的平方根成比例地减小。 我们使用 warmup_steps = 4000。学习率可变的Adam优化器作为训练用的优化器。
- 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.
- Residual Dropout 我们在对每个子层的输出上执行dropout操作,这个操作在additive操作(子层的输出加上子层的输入)和 normalized操作之前。 此外,在编码器和解码器块中,我们将丢弃应用到嵌入和位置编码的和。 对于基础模型,我们使用 Pdrop = 0.1的丢弃率。
- ``
- Label Smoothing During training, we employed label smoothing of value εls = 0.1 [36]. This hurts perplexity, as the model learns to be more unsure, but improves accuracy and BLEU score.
- Label Smoothing 在训练过程中,我们采用了值 εls=0.1[36]的标签平滑。虽然使模型有更大的不确定性,但也提高了准确性和BLEU分数。
- 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.
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.
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 .- 在WMT 2014英语-德语翻译任务中,大型Transformer模型(表2中的Transformer (big))比以前报道的最佳模型(包括整合模型)高出2个以上的BLEU评分,以28.4分建立了一个全新的SOTA BLEU分数。 该模型的配置列在表3的底部。 在8 个P100 GPU上花费3.5 天进行训练。 即使我们的基础模型也超过了以前发布的所有模型和整合模型,且训练成本只是这些模型的一小部分。
我们的模型在 WMT2014 英语-德语的翻译任务上取得了28.4的BLEU评分。在现有的表现最好模型的基础上,包括整合模型,提高了2个BLEU评分。
在WMT 2014英语-法语翻译任务中,我们的大型模型的BLEU得分为41.0,超过了之前发布的所有单一模型,训练成本低于先前最先进模型的1 ∕ 4 。 英语-法语的Transformer (big) 模型使用 Pdrop=0.1,而不是0.3。
对于基础模型,我们使用的单个模型来自最后5个checkpoints的平均值,这些checkpoints每10分钟保存一次。 对于大型模型,我们对最后20个checkpoints进行了平均。 我们使用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 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 © 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)中,我们观察到减小key的大小dk会有损模型质量。 这表明确定兼容性并不容易,并且比点积更复杂的兼容性函数可能更有用。 我们在行(C)和(D)中进一步观察到,如预期的那样,更大的模型更好,并且dropout对避免过度拟合非常有帮助。 在行(E)中,我们用学习到的positional encoding[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 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.
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 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.- 为了评估Transformer是否可以扩展到其他任务,我们进行了英语选区解析的实验。这项任务提出特别的挑战:输出受到很强的结构性约束,并且比输入要长很多。 此外,RNN序列到序列模型还没有能够在小数据[37]中获得最好的结果。
我们用 dmodel= 1024 在Penn Treebank[25]的Wall Street Journal(WSJ)部分训练了一个4层的transformer,约40K个训练句子。 我们还使用更大的高置信度和BerkleyParser语料库,在半监督环境中对其进行了训练,大约17M个句子[37]。 我们使用了一个16K词符的词汇表作为WSJ唯一设置,和一个32K词符的词汇表用于半监督设置。
我们只在开发集的Section 22 上进行了少量的实验来选择dropout、attention 和residual(第5.4节)、learning rates和beam size,所有其他参数从英语到德语的基础翻译模型保持不变。在推断过程中,我们将最大输出长度增加到输入长度+300。 对于WSJ和半监督设置,我们都使用beam size = 21 和α = 0.3 。
表4中我们的结果表明,尽管缺少特定任务的调优,我们的模型表现得非常好,得到的结果比之前报告的Recurrent Neural Network Grammar [8]之外的所有模型都好。
与RNN序列到序列模型[37]相比,即使仅在WSJ训练40K句子组训练时,Transformer也胜过BerkeleyParser [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.
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.- 在这项工作中,我们提出了Transformer,第一个完全基于attention的序列转换模型,用multi-headed self-attention取代了encoder-decoder架构中最常用的recurrent layers。
对于翻译任务,Transformer比基于循环或卷积层的体系结构训练更快。 在WMT 2014英语-德语和WMT 2014英语-法语翻译任务中,我们取得了最好的结果。 在前面的任务中,我们最好的模型甚至胜过以前报道过的所有整合模型。
我们对基于attention的模型的未来感到兴奋,并计划将它们应用于其他任务。 我们计划将Transformer扩展到除文本之外的涉及输入和输出模式的问题,并研究局部的、受限的attention机制,以有效地处理图像、音频和视频等大型输入和输出。 让生成具有更少的顺序性是我们的另一个研究目标。
我们用于训练和评估模型的代码可以在https://github.com/tensorflow/tensor2tensor找到。
我们十分感谢Nal Kalchbrenner和Stephan Gouws卓有成效的评论、修正和灵感。
- 首先,给Decoder输入开始标志(S),Decoder会预测出第一个单词(I);
- 然后,将“S I”输入Decoder去预测第二个单词(love);
- 进而,拿着 “S I love” 去预测 第三个单词(you);
- 最后,拿着 “S I love you” 去预测结束标志(E)。