Skip to content

Attention Is All You Need

Vaswani A , Shazeer N , Parmar N ,et al.Attention Is All You Need[J].arXiv, 2017.DOI:10.48550/arXiv.1706.03762.

Attention Is All You Need


注意力就是你所需要的

Abstract

The dominant sequence transduction models are based on complex recurrent or convolutional neural networks in an encoder-decoder configuration. The best performing models also connect the encoder and decoder through an attention mechanism. We propose a new simple network architecture, the Transformer, based solely on attention mechanisms, dispensing with recurrence and convolutions entirely. Experiments on two machine translation tasks show these models to be superior in quality while being more parallelizable and requiring significantly less time to train.


Our model achieves 28.4 BLEU on the WMT 2014 English-to-German translation task, improving over the existing best results, including ensembles by over 2 BLEU. On the WMT 2014 English-to-French translation task, our model establishes a new single-model state-of-the-art BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small fraction of the training costs of the best models from the literature. We show that the Transformer generalizes well to other tasks by applying it successfully to English constituency parsing both with large and limited training data.

主流的序列转换模型普遍基于复杂的循环神经网络或卷积神经网络,并采用编码器-解码器架构。性能最优异的模型通常还通过注意力机制连接编码器与解码器。我们提出了一种全新的简单网络架构——Transformer,该架构完全基于注意力机制,彻底摒弃了循环与卷积结构。在两个机器翻译任务上的实验表明,该模型在翻译质量上表现更优,同时具有更强的并行化能力,并且所需训练时间显著减少。


我们的模型在 WMT 2014 英德翻译任务中取得了 28.4 的 BLEU 分数,相比现有最佳结果(包括集成模型)提升了超过 2 个 BLEU 分数。在 WMT 2014 英法翻译任务中,我们的模型在 8 块 GPU 上训练 3.5 天后,建立了一个新的单模型最优 BLEU 分数——41.8,其训练成本仅为文献中最佳模型所需成本的一小部分。我们还通过将该模型成功应用于英语成分句法分析任务(包括大量训练数据和有限训练数据两种场景),证明了 Transformer 能够很好地泛化至其他任务。

Introduction

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.


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 ht1 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 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.

循环神经网络(RNN),尤其是长短期记忆网络(LSTM)和门控循环神经网络,已被牢固确立为序列建模与转换任务(如语言建模和机器翻译)中的主流SOTA方法。此后,众多研究不断推动循环语言模型及编码器-解码器架构的发展边界。


循环模型通常沿输入与输出序列的符号位置进行逐步计算。通过将位置与计算时间步骤对齐,它们以前一隐藏状态 ht1 和当前位置 t的输入为函数,生成一系列隐藏状态 ht。这种固有的顺序性质阻碍了在单个训练样本内部进行并行计算,这在处理较长序列时变得尤为关键,因为内存限制会影响跨样本的批处理。近期研究通过分解技巧和条件计算显著提升了计算效率,后者还同时提升了模型性能。然而,顺序计算的根本限制依然存在。


注意力机制已成为各类任务中构建强大序列建模与转换模型的关键组成部分,它允许对依赖关系进行建模而无需考虑其在输入或输出序列中的距离。然而,除极少数情况外,此类注意力机制均与循环网络结合使用。


本工作中,我们提出了 Transformer——一种摒弃循环结构、完全依赖注意力机制来捕捉输入与输出之间全局依赖关系的模型架构。Transformer 能够实现远高于以往的并行化程度,在仅使用 8 个 P100 GPU 训练十二小时后,便能在翻译质量上达到新的先进水平。

Background

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. 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.


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.


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.

降低顺序计算的需求同样构成了扩展神经GPUByteNet 与 ConvS2S 等模型的基础,这些模型均以卷积神经网络为基本构建模块,能够并行计算所有输入及输出位置的隐藏表示。在这些模型中,关联两个任意输入或输出位置的信号所需操作数,会随位置间距离的增加而增长:ConvS2S为线性增长,ByteNet为对数增长。这使得学习远距离位置间的依赖关系变得更加困难。而在Transformer中,这一操作数被降低至常数级别,尽管这是以对注意力加权位置进行平均而降低有效分辨率为代价的——我们通过第3.2节中描述的多头注意力机制来抵消这一影响。


自注意力(有时称为内部注意力)是一种注意力机制,它通过关联单个序列中不同位置的信息来计算该序列的表示。自注意力已成功应用于多种任务,包括阅读理解、抽象摘要、文本蕴含以及学习与任务无关的句子表示。


端到端记忆网络基于循环注意力机制而非按序列顺序的循环,并已被证明在简单语言问答和语言建模任务中表现良好。


然而,据我们所知,Transformer是首个完全依赖自注意力来计算其输入与输出表示,而不使用序列对齐的RNN或卷积的转换模型。在接下来的章节中,我们将描述Transformer的架构,阐述自注意力的原理,并讨论其相较于其他模型的优势。

Model Architecture

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.


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.

大多数具有竞争力的神经序列转换模型都采用编码器-解码器结构。在此结构中,编码器将输入符号表示序列 (x1,,xn) 映射为连续表示序列 z=(z1,,zn). Given z。给定 z,解码器随后逐元素地生成输出符号序列 (y1,,ym)。模型在每一步都是自回归的,即在生成下一个符号时,会将先前已生成的符号作为附加输入。


Transformer 遵循这一整体架构,在编码器和解码器中均使用堆叠的自注意力层和逐点全连接层。

3.1 Encoder and Decoder Stacks

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.


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.

3.1 编码器与解码器堆栈

编码器: 编码器由 N=6 个完全相同的层堆叠而成。每一层包含两个子层。第一个子层是一个多头自注意力机制,第二个子层是一个简单的、按位置全连接的前馈网络。我们在每个子层周围应用残差连接,然后进行层归一化。也就是说,每个子层的输出为 LayerNorm(x+Sublayer(x)),其中 Sublayer(x) 是该子层自身实现的函数。为了方便进行这些残差连接,模型中所有子层以及嵌入层产生的输出维度均为 dmodel=512


解码器: 解码器同样由 N=6 个完全相同的层堆叠而成。除了包含编码器每层中的两个子层之外,解码器还插入了第三个子层,该子层对编码器堆栈的输出执行多头注意力操作。与编码器类似,我们在每个子层周围应用残差连接,然后进行层归一化。此外,我们对解码器堆栈中的自注意力子层进行了修改,以防止某个位置关注到其后续的位置。这种掩码操作,结合输出嵌入向右偏移一个位置的事实,确保了对位置 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.

3.2 注意力机制

注意力函数可描述为将一个查询(query)和一组键值对(key-value pairs)映射为一个输出的过程,其中查询、键、值及输出均为向量。输出通过对值进行加权求和计算得到,而分配给每个值的权重则由查询与对应键的兼容性函数计算得出。

3.2.1 Scaled Dot-Product Attention

We call our particular attention "Scaled Dot-Product Attention" (Figure 2). The input consists of queries and keys of dimension dk, and values of dimension 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.


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:

3.2.1 缩放点积注意力

我们将我们特定的注意力机制称为“缩放点积注意力”。输入由维度为 dk 的查询和键,以及维度为 dv 的值组成。我们计算查询与所有键的点积,将每个点积除以 dk,然后应用softmax函数来获得对值的权重。


在实践中,我们同时计算一组查询的注意力函数,将它们打包成一个矩阵 Q。键和值也被分别打包成矩阵 KV。我们按如下公式计算输出矩阵:

(1)Attention(Q,K,V)=softmax(QKTdk)V

The two most commonly used attention functions are additive attention , and dot-product (multiplicative) attention. Dot-product attention is identical to our algorithm, except for the scaling factor of 1dk. 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. 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 1dk.

最常用的两种注意力函数是加性注意力和点积(乘法)注意力。点积注意力与我们的算法相同,除了没有 1dk 这个缩放因子。加性注意力使用一个具有单隐藏层的前馈网络来计算兼容性函数。尽管两者在理论复杂度上相似,但点积注意力在实践中速度更快且空间效率更高,因为它可以通过高度优化的矩阵乘法代码来实现。


dk 值较小时,两种机制性能相近;但在 dk 值较大时,未缩放的加性注意力要优于点积注意力。我们推测,当 dk 值较大时,点积的结果在量级上会变得很大,从而将softmax函数推入梯度极小的区域。为了抵消这种影响,我们将点积缩放 1dk

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.

3.2.2 多头注意力

与使用 dmodel 维度的键、值和查询执行单一的注意力函数不同,我们发现,将查询、键和值分别用 h 个不同的、可学习的线性投影线性映射到 dkdkdv 维度是有益的。随后,我们在这些投影后的查询、键和值的每一个版本上并行执行注意力函数,得到 dv 维的输出值。这些输出被拼接起来并再次投影,从而产生最终值。


多头注意力使得模型能够同时关注来自不同位置的不同表示子空间的信息。如果仅使用单一的注意力头,其平均操作会抑制这种能力。

MultiHead(Q,K,V)=Concat(head1,,headh)WO where headi=Attention(QWiQ,KWiK,VWiV)

Where the projections are parameter matrices WiQRdmodel ×dk, WiKRdmodel ×dk, WiVRdmodel ×dv, and WORhdv×dmodel .


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.

其中,投影为参数矩阵 WiQRdmodel ×dkWiKRdmodel ×dkWiVRdmodel ×dv 以及 WORhdv×dmodel 


在本工作中,我们采用 h=8 个并行的注意力层。对每一个头,我们使用 dk=dv=dmodel /h=64。由于每个头的维度减小,总计算成本与使用全维度的单头注意力相近。

3.2.3 Applications of Attention in our Model

The Transformer uses multi-head attention in three different ways:

  • In "encoder-decoder attention" layers, the queries come from the previous decoder layer, and the memory keys and values come from the output of the encoder. This allows every position in the decoder to attend over all positions in the input sequence. This mimics the typical encoder-decoder attention mechanisms in sequence-to-sequence models.
  • 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.
3.2.3 注意力机制在我们模型中的应用

Transformer 在三个不同方面使用了多头注意力机制:

  • “编码器-解码器注意力” 层 中,查询来自前一个解码器层,而记忆键和值则来自编码器的输出。这使得解码器中的每个位置都能够关注输入序列中的所有位置。这模仿了序列到序列模型中典型的编码器-解码器注意力机制。
  • 编码器包含自注意力层。在自注意力层中,所有的键、值和查询都来自同一个地方,即编码器中前一层的输出。编码器中的每个位置都可以关注编码器前一层中的所有位置。
  • 类似地,解码器中的自注意力层 允许解码器中的每个位置关注解码器内包括该位置在内的所有先前位置。为了保持自回归特性,我们需要阻止解码器中的信息向左流动(即关注未来的位置)。我们在缩放点积注意力内部通过掩码来实现这一点:将所有在 softmax 输入中对应非法连接的值掩盖掉(设置为 )。

3.3 Position-wise Feed-Forward Networks

In addition to attention sub-layers, each of the layers in our encoder and decoder contains a fully connected feed-forward network, which is applied to each position separately and identically. This consists of two linear transformations with a ReLU activation in between.

3.3 逐位置前馈网络

除了注意力子层之外,我们的编码器和解码器中的每一层还包含一个全连接前馈网络。该网络分别并相同地应用于每个位置。它由两个线性变换组成,中间通过一个 ReLU 激活函数连接。

(2)FFN(x)=max(0,xW1+b1)W2+b2

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.4 Embeddings and Softmax

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 transformation and softmax function to convert the decoder output to predicted next-token probabilities. In our model, we share the same weight matrix between the two embedding layers and the pre-softmax linear transformation. In the embedding layers, we multiply those weights by dmodel.

3.4 嵌入和Softmax

与其他序列转换模型类似,我们使用学习到的嵌入将输入词元和输出词元转换为维度为 dmodel 的向量。我们还采用常规的学习得到的线性变换与 softmax 函数,将解码器输出转换为下一个词元的预测概率。在我们的模型中,我们在两个嵌入层与 softmax 前的线性变换之间共享相同的权重矩阵。在嵌入层中,我们将这些权重乘以 dmodel

3.5 Positional 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. 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.


In this work, we use sine and cosine functions of different frequencies:

3.5 位置编码

由于我们的模型不含循环结构,也没有卷积操作,为了让模型能够利用序列的顺序信息,我们必须注入关于序列中词元相对位置或绝对位置的一些信息。为此,我们在编码器栈和解码器栈底部的输入嵌入中添加“位置编码”。位置编码与嵌入具有相同的维度 dmodel,以便两者可以直接相加。位置编码有多种选择,可以是可学习的,也可以是固定的。

在本工作中,我们使用不同频率的正弦和余弦函数:

PE(pos,2i)=sin(pos/100002i/dmodel )PE(pos,2i+1)=cos(pos/100002i/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 100002π. 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. We chose the sinusoidal version because it may allow the model to extrapolate to sequence lengths longer than the ones encountered during training.

其中 pos 是位置,i 是维度。也就是说,位置编码的每个维度都对应一个正弦波。波长构成从 2π100002π 的几何级数。我们选择这个函数是因为我们假设它能使模型轻易地学习关注相对位置,因为对于任意固定偏移量 kPEpos+k 都可以表示为 PEpos 的线性函数。


我们还尝试使用可学习的位置嵌入,并发现两种版本产生的结果几乎相同。我们选择正弦波版本,是因为它可能允许模型外推到比训练时遇到的序列长度更长的序列。

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,ziRd, 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. Hence we also compare the maximum path length between any two input and output positions in networks composed of the different layer types.

在本节中,我们将自注意力层与常用于将变长符号表示序列 (x1,,xn) 映射为另一个等长序列 (z1,,zn)(其中 xi,ziRd)的循环层和卷积层进行多方面比较,例如典型序列转换编码器或解码器中的隐藏层。我们使用自注意力主要基于三个考量。


首先是每层的总计算复杂度。其次是可以并行化的计算量,以所需的最小顺序操作数来衡量。


第三是网络中长距离依赖之间的路径长度。学习长距离依赖是许多序列转换任务中的关键挑战。影响此类依赖学习能力的一个关键因素是前向和后向信号在网络中必须 travers 的路径长度。输入和输出序列中任意位置组合之间的路径越短,学习长距离依赖就越容易。因此,我们还比较了由不同层类型组成的网络中任意两个输入和输出位置之间的最大路径长度。

表1:不同层类型的最大路径长度、每层复杂度及最小顺序操作数。其中 n 为序列长度,d 为表示维度,k 为卷积核大小,r 为受限自注意力中的邻域大小。

层类型            每层复杂度        顺序操作数        最大路径长度    
自注意力O(n2d)O(1)O(1)
递归O(nd2)O(n)O(n)
卷积O(knd2)O(1)O(logk(n))
自注意力(受限)O(rnd)O(1)O(n/r)

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 and byte-pair 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.


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/r) convolutional layers in the case of contiguous kernels, or O(logk(n)) in the case of dilated convolutions, 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, however, decrease the complexity considerably, to O(knt+nd2). 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.

如表 1 所示,自注意力层通过常数次顺序执行的操作即可连接所有位置,而循环层则需要 O(n) 次顺序操作。就计算复杂度而言,当序列长度 n 小于表示维度 d时,自注意力层比循环层更快——这在机器翻译的当前最优模型中十分常见,例如使用词片段(word-piece)和字节对(byte-pair)表示时的句子表示。为了提升涉及超长序列任务的计算性能,可将自注意力限制为仅考虑以每个输出位置为中心的、大小为 r 的输入邻域。这将使最大路径长度增加至 O(n/r)。我们计划在未来工作中进一步研究这一方向。


卷积层若卷积核宽度 k<n ,则无法连接所有输入输出位置对。要做到这一点,对于连续卷积核需要堆叠 O(n/r) 层,对于空洞卷积则需要 O(logk(n)) 层,这会增加网络中任意两个位置间的最长路径长度。卷积层通常比循环层计算成本更高,成本约为循环层的 k倍。然而,可分离卷积能将复杂度显著降低至 O(knt+nd2)。即便如此,即使 k=n,可分离卷积的复杂度也等于自注意力层与逐点前馈层之和——这正是我们模型所采用的方式。


作为附加好处,自注意力还能产生更具可解释性的模型。我们检查了模型中的注意力分布,并在附录中展示并讨论了一些示例。不仅各个注意力头明显学会了执行不同的任务,其中许多还表现出与句子句法结构和语义结构相关的行为。

Training

5.1 Training Data and Batching

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, 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. 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.

5.1 训练数据与批处理

我们在标准的 WMT 2014 英德数据集上进行训练,该数据集包含约 450 万个句子对。句子采用字节对编码,共享的源-目标词汇表包含约 37000 个词元。对于英法任务,我们使用了规模更大的 WMT 2014 英法数据集,包含 3600 万个句子,并将词元切分为 32000 个词片段(word-piece)词汇表。句子对按近似序列长度进行批处理。每个训练批次包含一组句子对,其中源语言和目标语言各约有 25000 个词元。

5.2 Hardware and Schedule

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).

5.2 硬件与训练计划

我们在一台配备 8 块 NVIDIA P100 GPU 的机器上训练模型。对于采用本文所述超参数的基础模型,每步训练时间约为 0.4 秒。我们对基础模型总共进行了 100000 步(即 12 小时)的训练。对于大模型(见表 3 底行),每步训练时间为 1.0 秒。大模型训练了 300000 步(3.5 天)。

5.3 Optimizer

We used the Adam optimizer with β1=0.9, β2=0.98 and ϵ=109. We varied the learning rate over the course of training, according to the formula:

5.3 优化器

我们使用 Adam 优化器,其中 β1=0.9β2=0.98ϵ=109。我们在训练过程中根据以下公式动态调整学习率:

(3)lrate=dmodel 0.5min(step_num0.5,step_numwarmup_steps1.5)

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

We employ three types of regularization during training:


Residual Dropout We apply dropout 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.


Label Smoothing During training, we employed label smoothing of value ϵls=0.1. This hurts perplexity, as the model learns to be more unsure, but improves accuracy and BLEU score.

5.4 正则化

我们在训练过程中采用了三种正则化方法:


残差 Dropout 我们在每个子层的输出上应用 Dropout,然后再将其添加到子层输入并进行层归一化。此外,我们还对编码器和解码器堆栈中的嵌入与位置编码的求和结果应用 Dropout。对于基础模型,我们使用的丢弃率为 Pdrop=0.1


标签平滑 在训练过程中,我们采用了值为 ϵls=0.1 的标签平滑。这会导致困惑度上升,因为模型学会了更加不确定,但却提高了准确率和 BLEU 分数。

Results

6.1 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. 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. 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.


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.

6.1 机器翻译

在 WMT 2014 英德翻译任务上,大号 Transformer 模型(表 2 中的 Transformer (big))以超过 2.0 BLEU 的优势击败了此前报告的最佳模型(包括集成模型),取得了 28.4 BLEU 分数,树立了新的 SOTA。该模型的配置列于表 3 底行。训练在 8 块 P100 GPU 上耗时 3.5 天。即便是我们的基础模型,也以远低于任何竞争模型的训练成本,超越了所有先前发表的模型与集成模型。


在 WMT 2014 英法翻译任务上,我们的大号模型取得了 41.0 BLEU 分数,优于此前发表的所有单模型,而训练成本不到此前最先进模型的 1/4。用于英法任务的 Transformer (big) 模型使用的丢弃率为 Pdrop=0.1,而非 0.3。


对于基础模型,我们采用对最后 5 个检查点(每 10 分钟写入一次)进行平均所得到的单一模型。对于大号模型,我们对最后 20 个检查点进行平均。我们使用集束搜索,束大小为 4,长度惩罚 α=0.6。这些超参数是在开发集上实验后选定的。推理时我们将最大输出长度设为输入长度 + 50,并在可能时提前终止。


表 2 总结了我们的结果,并将我们的翻译质量与训练成本同文献中的其他模型架构进行了比较。我们通过将训练时间、使用的 GPU 数量以及对每个 GPU 持续单精度浮点运算能力的估算相乘,来估计训练一个模型所需的浮点运算次数。

表2:在 newstest2014 英德和英法翻译测试中,Transformer 以远低于先前最优模型的训练成本,取得了更高的 BLEU 分数。

Model                                    BLEUTraining Cost (FLOPs)
EN-DEEN-FREN-DEEN-FR
Deep-Att + PosUnk39.21.0·1020
GNMT + RL24.639.922.3·10191.4·1020
ConvS2S25.1640.469.6·10181.5·1020
MoE26.0340.562.0·10191.2·1020
Deep-Att + PosUnk Ensemble40.48.0·1020
GNMT + RL Ensemble26.3041.161.8·10201.1·1021
ConvS2S Ensemble26.3641.297.7·10191.2·1021
Transformer (base model)27.338.13.3·1018
Transformer (big)28.441.82.3·1019

6.2 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.


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 (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, and observe nearly identical results to the base model.

6.2 模型变体

为了评估 Transformer 不同组件的重要性,我们以多种方式改变基础模型,并在开发集 newstest2013 上测量英德翻译性能的变化。我们使用前一节所述的集束搜索,但未采用检查点平均。我们在表 3 中展示了这些结果。


在表 3 的 (A) 行中,我们改变注意力头数量以及注意力键和值的维度,同时保持计算量不变,如第 3.2.2 节所述。虽然单头注意力的 BLEU 值比最佳设置低 0.9,但头数过多时质量同样会下降。


在表 3 的 (B) 行中,我们观察到减小注意力键的尺寸 dk 会损害模型质量。这表明确定兼容性并非易事,并且比点积更复杂的兼容性函数可能会更有益。我们进一步在 (C) 和 (D) 行中观察到,正如预期,更大的模型效果更好,并且 Dropout 对于避免过拟合非常有帮助。在 (E) 行中,我们用可学习的位置嵌入替换了我们的正弦位置编码,并观察到与基础模型几乎相同的结果。

表3:Transformer 架构的变体。 未列出的数值与基础模型相同。所有指标均基于英德翻译开发集 newstest2013。所列困惑度为根据我们的字节对编码计算的每词片段困惑度,不应与每词困惑度进行比较。

N

dmodel

dff

h

dk

dv

Pdrop

ϵls

train stepsPPL (dev)BLEU (dev)params ×106
base65122048864640.10.1100K4.9225.865
(A)15125125.2924.9
41281285.0025.5
1632324.9125.8
3216165.0125.4
(B)165.1625.158
325.0125.460
(C)26.1123.736
45.1925.350
84.8825.580
25632325.7524.528
10241281284.6626.0168
10245.1225.453
40964.7526.290
(D)0.05.7724.6
0.24.9525.5
0.04.6725.3
0.25.4725.7
(E)positional embedding instead of sinusoids4.9225.7
big610244096160.3300K4.3326.4213

6.3 English Constituency Parsing

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.


We trained a 4-layer transformer with dmodel=1024 on the Wall Street Journal (WSJ) portion of the Penn Treebank, 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. 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 surprisingly well, yielding better results than all previously reported models with the exception of the Recurrent Neural Network Grammar.


In contrast to RNN sequence-to-sequence models, the Transformer outperforms the BerkeleyParser even when training only on the WSJ training set of 40K sentences.

6.3 英语成分句法分析

为了评估 Transformer 能否泛化到其他任务,我们在英语成分句法分析上进行了实验。该任务具有特殊的挑战:输出受限于严格的结构约束,且长度明显长于输入。此外,RNN 序列到序列模型在小数据场景下一直未能取得最先进的结果。


我们在宾州树库的华尔街日报(WSJ)部分(约 40K 训练句子)上训练了一个 4 层 Transformer,其中 dmodel=1024。我们还以半监督方式进行训练,使用了来自高置信度语料库和 BerkeleyParser 语料库的更大规模数据,包含约 1700 万句子。对于仅 WSJ 的设置,我们使用 16K 词元的词汇表;对于半监督设置,则使用 32K 词元的词汇表。


我们仅在 Section 22 开发集上进行了少量实验,以选择丢弃率(包括注意力和残差,见第 5.4 节)、学习率和束大小,所有其他参数均与英德翻译基础模型保持一致。推理时,我们将最大输出长度增加到输入长度 + 300。对于仅 WSJ 和半监督两种设置,我们都使用束大小为 21,长度惩罚 α=0.3


表 4 中的结果表明,尽管缺乏针对任务的调优,我们的模型仍表现出色,除了循环神经网络文法之外,其结果优于此前所有已报告的模型。


与 RNN 序列到序列模型相比,Transformer 即便仅在 40K 句子的 WSJ 训练集上训练,也优于 BerkeleyParser。

表4:Transformer 能够很好地泛化到英语成分句法分析任务(结果基于 WSJ 第23节)

Parser                                Training                WSJ 23 F1        
Vinyals & Kaiser el al. (2014)WSJ only, discriminative88.3
Petrov et al. (2006)WSJ only, discriminative90.4
Zhu et al. (2013)WSJ only, discriminative90.4
Dyer et al. (2016)WSJ only, discriminative91.7
Transformer (4 layers)WSJ only, discriminative91.3
Zhu et al. (2013)semi-supervised91.3
Huang & Harper (2009)semi-supervised91.3
McClosky et al. (2006)semi-supervised92.1
Vinyals & Kaiser el al. (2014)semi-supervised92.1
Transformer (4 layers)semi-supervised92.7
Luong et al. (2015)multi-task93.0
Dyer et al. (2016)generative93.3

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.


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.

在本工作中,我们提出了 Transformer——首个完全基于注意力机制的序列转换模型,它用多头自注意力层取代了编码器-解码器架构中最常使用的循环层。


在翻译任务上,Transformer 的训练速度显著快于基于循环层或卷积层的架构。在 WMT 2014 英德翻译和英法翻译两项任务上,我们都取得了新的最先进成果。在前一项任务中,我们最好的模型甚至超越了此前报告的所有集成模型。


我们对基于注意力的模型的未来充满期待,并计划将其应用于其他任务。我们计划将 Transformer 扩展到涉及文本以外的输入输出模态的问题,并研究局部的、受限的注意力机制,以高效处理图像、音频和视频等大规模输入与输出。减少生成的顺序性也是我们的后续研究目标之一。