注意力机制论文Attention Is All You Need

148 阅读34分钟

Attention Is All You Need

# Abstract:

The dominant sequence transduction models are based on complex recurrent or convolutional neural networks that include an encoder and a decoder. The best performing models also connect the encoder and decoder through an attention mechanism. We propose a new simple network architecture, the Transformer, based solely on attention mechanisms, dispensing with recurrence and convolutions entirely. Experiments on two machine translation tasks show these models to be superior in quality while being more parallelizable and requiring significantly less time to train. Our model achieves 28.4 BLEU on the WMT 2014 Englishto-German translation task, improving over the existing best results, including ensembles, by over 2 BLEU. On the WMT 2014 English-to-French translation task, our model establishes a new single-model state-of-the-art BLEU score of 41.0 after training for 3.5 days on eight GPUs, a small fraction of the training costs of the best models from the literature. * 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.

# Meta Translation

题目: Aufmerksamkeit ist alles, was Sie brauchen

**摘要:*主流的序列转换模型基于复杂的循环或卷积神经网络,包括一个编码器和一个解码器。表现最好的模型还通过注意力机制连接编码器和解码器。我们提出了一种新的简单网络架构—— Transformer,它完全基于注意力机制,完全放弃了递归和卷积。在两个机器翻译任务上的实验表明,这些模型在质量上更优秀,同时更易于并行化,并且训练所需的时间明显更少。在 WMT 2014 年英语到德语的翻译任务上,我们的模型获得了 28.4 的 BLEU 分数,比现有最好的结果(包括集合)提高了 2 个 BLEU 分数以上。在 WMT 2014 的英语到法语翻译任务上,在八个 GPU 上训练 3.5 天后,我们的模型达到了 41.0 的 BLEU 分数,创下了新的单模型最先进记录,仅为文献中最佳模型训练成本的一小部分。 等量贡献。列出顺序是随机的。雅各布提议使用自注意力替换 RNN,并开始评估这一想法。阿什什与伊利亚一起设计和实现了第一个 Transformer 模型,并且一直参与到该工作的各个环节中。诺姆提议了缩放点积注意力、多头注意力和无参数位置表示,并成为几乎所有环节中的另一位参与者。尼基在我们最初的代码库和 tensor2tensor 中设计、实现、调整和评估了无数的模型变体。利昂也尝试了新颖的模型变体,并负责我们的初始代码库、高效推理和可视化。卢卡斯和艾登花了无数个漫长的日子设计和实现了 tensor2tensor 的各个部分,取代了我们之前的代码库,极大地改善了结果,并大大加快了我们的研究进程。

# Introduction

Recurrent neural networks, long short-term memory [12] and gated recurrent [7] neural networks in particular, have been firmly established as state of the art approaches in sequence modeling and transduction problems such as language modeling and machine translation [29,2,5]. Numerous efforts have since continued to push the boundaries of recurrent language models and encoder-decoder architectures [31,21,13]. Recurrent models typically factor computation along the symbol positions of the input and output sequences. Aligning the positions to steps in computation time, they generate a sequence of hidden states h t , as a function of the previous hidden state h t-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 [18] and conditional computation [26], 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 [2,16]. In all but a few cases [22], 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.

循环神经网络,尤其是长期短期记忆 [12] 和门控循环 [7] 神经网络,已被牢固地确立为序列建模和转换问题的最先进方法,例如语言建模和机器翻译 [29,2,5]。从那以后,许多努力继续突破循环语言模型和编码器-解码器架构的界限 [31,21,13]。 递归模型通常沿着输入和输出序列的符号位置进行计算。将位置与计算时间中的步骤对齐,它们生成一个隐藏状态序列 h t,作为前一个隐藏状态 h t-1 和位置 t 的输入的函数。这种固有的顺序特性在训练示例中不允许并行化,这在较长的序列长度下变得至关重要,因为内存限制限制了示例之间的批处理。最近的工作通过分解技巧 [18] 和条件计算 [26] 在计算效率方面取得了显着改进,同时还改进了后者的模型性能。然而,时序计算的基本约束仍然存在。 注意机制已经成为各种任务中引人注目的序列建模和转换模型不可或缺的一部分,它允许对依赖项进行建模,而不考虑它们在输入或输出序列中的距离 [2,16]。然而,除少数情况 [22] 外,此类注意力机制与循环网络一起使用。 在这项工作中,我们提出了 Transformer,这是一种完全避开循环的模型架构,而是完全依赖注意机制在输入和输出之间建立全局依赖关系。只需在八个 P100 GPU 上训练十二小时,Transformer 就可以实现更高的并行化,并在翻译质量方面达到新的最先进水平。

# Background

The goal of reducing sequential computation also forms the foundation of the Extended Neural GPU [20], ByteNet [15] and ConvS2S [8], all of which use convolutional neural networks as basic building block, computing hidden representations in parallel for all input and output positions. 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 [11]. In the Transformer this is reduced to a constant number of operations, albeit at the cost of reduced effective resolution due to averaging attention-weighted positions, an effect we counteract with Multi-Head Attention as described in section 3.2. 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,22,23,19]. End-to-end memory networks are based on a recurrent attention mechanism instead of sequencealigned recurrence and have been shown to perform well on simple-language question answering and language modeling tasks [28]. To the best of our knowledge, however, the Transformer is the first transduction model relying entirely on self-attention to compute representations of its input and output without using sequencealigned RNNs or convolution. In the following sections, we will describe the Transformer, motivate self-attention and discuss its advantages over models such as [14,15] and [8].

减少顺序计算的目标也是 Extended Neural GPU [20]、ByteNet [15] 和 ConvS2S [8] 的基础,所有这些都使用卷积神经网络作为基本构建模块,并为所有输入和输出位置并行计算隐藏表示。在这些模型中,关联来自两个任意输入或输出位置的信号所需的运算数量随着位置之间的距离而增长,对于 ConvS2S 线性增长,对于 ByteNet 以对数方式增长。这使得学习远距离位置之间的依赖关系变得更加困难 [11]。在 Transformer 中,这减少到恒定的操作数,尽管代价是由于对注意力加权位置的平均而降低了有效分辨率,我们用第 3.2 节中描述的多头注意力抵消了这种影响。

自注意力,有时称为内部注意力,是一种注意机制,它涉及单个序列的不同位置以计算序列的表示。自注意力已成功用于各种任务中,包括阅读理解、抽象总结、文本蕴涵和学习独立于任务的句子表示 [4,22,23,19]。

端到端内存网络基于递归注意力机制而不是序列对齐递归,并且已显示出在简单的语言问答和语言建模任务上表现良好 [28]。

尽我们所知,Transformer 是第一个完全依赖自注意力来计算其输入和输出表示的转导模型,而没有使用序列对齐的 RNN 或卷积。在以下部分中,我们将描述 Transformer,激发自注意力,并讨论它相对于 [14,15] 和 [8] 等模型的优势。

# Model Architecture

Most competitive neural sequence transduction models have an encoder-decoder structure [5,2,29]. Here, the encoder maps an input sequence of symbol representations (x 1 , ..., x n ) to a sequence of continuous representations z = (z 1 , ..., z n ). Given z, the decoder then generates an output sequence (y 1 , ..., y m ) of symbols one element at a time. At each step the model is auto-regressive [9], consuming the previously generated symbols as additional input when generating the next. The Transformer follows this overall architecture using stacked self-attention and point-wise, fully connected layers for both the encoder and decoder, shown in the left and right halves of Figure 1, respectively.

大多数有竞争力的神经序列转换模型采用编码器-解码器结构[5,2,29]。此处,编码器将输入符号表示序列(x1,...,xn)映射为连续表示序列z =(z1,...,zn)。获得z后,解码器将一次产生一个元素的符号输出序列(y1,...,ym)。在每个步骤中,模型都是自回归的[9],当生成下一个元素时消耗先前生成的符号作为附加输入。

transformer采用此整体架构,使用堆叠自注意力、逐点全连层作为编码器和解码器,分别如下图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 [10] around each of the two sub-layers, followed by layer normalization [1]. That is, the output of each sub-layer is LayerNorm(x + Sublayer(x)), where Sublayer(x) is the function implemented by the sub-layer itself. To facilitate these residual connections, all sub-layers in the model, as well as the embedding layers, produce outputs of dimension 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 个相同的层堆叠而成。每层有两个子层。第一层是一个多头自注意力机制,第二层是一个简单的位置前馈全连接网络。我们在两个子层周围采用一个残差连接 [10],然后进行层归一化 [1]。即,每个子层的输出为 LayerNorm(x + Sublayer(x)),其中 Sublayer(x) 是子层自己实现的函数。为了促进这些残差连接,模型中的所有子层以及嵌入层都生成维度为 d model = 512 的输出。

**解码器:**解码器也由 N = 6 个相同的层堆叠而成。除了每个编码器层中的两个子层外,解码器还插入第三个子层,该子层对编码器堆栈的输出执行多头注意力。与编码器类似,我们在每个子层周围采用残差连接,然后进行层归一化。我们还修改解码器堆栈中的自注意力子层,以防止位置关注后续位置。此屏蔽与输出嵌入偏移一个位置的事实相结合,确保位置 i 的预测仅取决于小于 i 的已知输出。

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

注意力函数可以描述为将查询和一组键值对映射到一个输出,其中查询、键、值和输出都是向量。输出计算为值的加权和,其中分配给每个值的权重是查询与相应键的兼容性函数计算的。

# Scaled Dot-Product Attention

We call our particular attention "Scaled Dot-Product Attention" (Figure 2). The input consists of queries and keys of dimension d k , and values of dimension d v . We compute the dot products of the Scaled Dot-Product Attention Multi-Head Attention 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: Attention(Q, K, V ) = softmax( QK T √ d k )V(1) The two most commonly used attention functions are additive attention [2], and dot-product (multiplicative) attention. Dot-product attention is identical to our algorithm, except for the scaling factor of 1 √ d k . 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 d k the two mechanisms perform similarly, additive attention outperforms dot product attention without scaling for larger values of d k [3]. We suspect that for large values of d k , the dot products grow large in magnitude, pushing the softmax function into regions where it has extremely small gradients4 . To counteract this effect, we scale the dot products by 1 √ d k .

Scaled Dot-Product Attention

我们将我们特别的注意力机制称为“Scaled Dot-Product Attention”(缩放点积注意力机制)(见图 2)。输入由维度为 d k 的查询和键以及维度为 d v 的值组成。我们计算 Scaled Dot-Product Attention 的点积。

多头注意力

实际上,我们在成组查询上计算注意力函数并将其打包到矩阵 Q 中。键和值也打包到矩阵 K 和 V 中。我们计算输出矩阵为:

Attention(Q, K, V ) = softmax( QK T √ d k )V(1)

点积注意力

在实践中,最常用的两个注意力函数是加性注意力 [2] 和点积(乘性)注意力。点积注意力与我们的算法相同,但缩放因子为 1/√d k。加性注意力使用具有单个隐藏层的馈送前向神经网络计算兼容性函数。虽然二者在理论复杂度上类似,但点积注意力实际上更快且更省空间,因为它可以使用经过高度优化的矩阵乘法代码来实现。

虽然对于 d k 的较小值,这两种机制执行起来类似,但加性注意力在 d k 的较大值的情况下优于未缩放的点积注意力 [3]。我们怀疑对于大的 d k,点积的幅度会变大,将 softmax 函数推入其梯度极小的区域4。为了抵消这种影响,我们将点积缩放到 1/√d k。

# Multi-Head Attention

Instead of performing a single attention function with d model -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 d k , d k and d v dimensions, respectively. On each of these projected versions of queries, keys and values we then perform the attention function in parallel, yielding d v -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. MultiHead(Q, K, V ) = Concat(head 1 , ..., head h )W O where head i = Attention(QW Q i , KW K i , V W V i ) Where the projections are parameter matrices W Q i ∈ R dmodel×d k , W K i ∈ R dmodel×d k , W V i ∈ R dmodel×dv and W O ∈ R hdv×dmodel . In this work we employ h = 8 parallel attention layers, or heads. For each of these we use d k = d v = d model /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.

与执行具有 d 模型维度的键、值和查询的单个注意力函数不同,我们发现将查询、键和值使用线性投影 h 次有利,这些投影具有不同的已学习线性投影,分别以 d k、d k 和 d v 维执行。然后,针对这些查询、键和值的投影版本中的每个版本,我们并行执行注意力函数,生成 d v 维输出值。这些输出值连接后再次投影,生成最终值,如图 2 所示。 多头注意力使模型能够根据不同位置联合注意不同表示子空间的信息。对于单个注意头,平均值抑制了这一点。 MultiHead(Q, K, V) = Concat(head 1 , ..., head h)W o 其中 head i = Attention(QW Q i , KW K i , V W V i) 其中投影为参数矩阵 W Q i ∈ R d model×d k、W K i ∈ R d model×d k、W V i ∈ R d model×d v 和 W o ∈ R hd v×d model。 在本项工作中,我们采用 h = 8 个并行的注意力层,或头部。对于每一个,我们使用 d k = d v = d model/h = 64。 鉴于每个头的维数减小,总的计算成本与具有全维度的单头注意力的计算成本相似。

# 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 such as [31,2,8]. • The encoder contains self-attention layers. In a self-attention layer all of the keys, values and queries come from the same place, in this case, the output of the previous layer in the encoder. Each position in the encoder can attend to all positions in the previous layer of the encoder. • Similarly, self-attention layers in the decoder allow each position in the decoder to attend to all positions in the decoder up to and including that position. We need to prevent leftward information flow in the decoder to preserve the auto-regressive property. We implement this inside of scaled dot-product attention by masking out (setting to -∞) all values in the input of the softmax which correspond to illegal connections. See Figure 2.

Transformer 以三种不同的方式使用多头注意力: • 在“编码器-解码器注意力”层中,查询来自前一个解码器层,而记忆键和值来自编码器的输出。这允许解码器中的每个位置都关注输入序列中的所有位置。这模拟了诸如 [31,2,8] 等序列到序列模型中的典型编码器-解码器注意力机制。 • 编码器包含自注意力层。在自注意力层中,所有键、值和查询都来自同一位置,在本例中,即编码器中前一层的输出。编码器中的每个位置都可以关注编码器前一层中的所有位置。 • 同样,解码器中的自注意力层允许解码器中的每个位置关注解码器中所有位置(至多到该位置)。我们需要防止信息在解码器中向左流动,以保持自回归特性。我们在缩放点积注意力内通过掩蔽(设置为 -∞)softmax 输入中与非法连接相对应的所有值来实现这一点。请参见图 2。

# 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. FFN(x) = max(0, xW 1 + b 1 )W 2 + b 2(2) 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 d model = 512, and the inner-layer has dimensionality d f f = 2048.

除了注意子层,我们的编码器和解码器中的每一层都包含一个全连接的前馈网络,它被单独且相同地应用于每个位置。这包括两个线性变换,中间有一个 ReLU 激活。 FFN(x) = max(0, xW₁ + b₁)W₂ + b₂ (2) 虽然线性变换在不同位置都是相同的,但它们从层到层使用不同的参数。描述它的另一种方法是使用内核大小为 1 的两个卷积。 输入和输出的维数为 d model = 512,并且内部层的维数为 dff = 2048。

# 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 d model . We also use the usual learned linear transformation and softmax function to convert the decoder output to predicted next-token probabilities. In our model, we share the same weight matrix between the two embedding layers and the pre-softmax linear transformation, similar to [24]. In the embedding layers, we multiply those weights by √ d model .

嵌入和 Softmax

与其他序列转换模型类似,我们使用学习的嵌入将输入标记和输出标记转换为维度为 d_model 的向量。我们还使用通常学习的线性变换和 softmax 函数将解码器输出转换为预测的下一个标记概率。在我们的模型中,我们共享同一权重矩阵,用于两个嵌入层和预 softmax 线性变换,类似于 [24]。在嵌入层中,我们将这些权重乘以 √d_model。

# 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 (n 2 • d) O(1) O(1) Recurrent O(n • d 2 ) O(n) O(n) Convolutional O(k • n • d 2 ) O(1) O(log k (n)) Self-Attention (restricted) O(r • n • d) O(1) O(n/r) bottoms of the encoder and decoder stacks. The positional encodings have the same dimension d model as the embeddings, so that the two can be summed. There are many choices of positional encodings, learned and fixed [8]. In this work, we use sine and cosine functions of different frequencies: P E (pos,2i) = sin(pos/10000 2i/dmodel ) P E (pos,2i+1) = cos(pos/10000 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, P E pos+k can be represented as a linear function of P E pos . We also experimented with using learned positional embeddings [8] instead, and found that the two versions produced nearly identical results (see Table 3 row (E)). We chose the sinusoidal version because it may allow the model to extrapolate to sequence lengths longer than the ones encountered during training.

由于我们的模型不包含循环也不包含卷积,因此为了让模型利用序列的顺序,我们必须注入一些关于序列中标记的相对或绝对位置的信息。为此,我们在编码器和解码器堆栈底部的输入嵌入中添加了“位置编码”。位置编码与嵌入的维度 dmodel 相同,因此两者可以相加。有很多位置编码可供选择,学习和固定 [8]。

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

P E (pos,2i) = sin(pos/10000 2i/dmodel )

P E (pos,2i+1) = cos(pos/10000 2i/dmodel )

其中 pos 是位置,i 是维度。也就是说,位置编码的每个维度都对应一个正弦波。波长形成从 2π 到 10000 • 2π 的几何级数。我们选择这个函数是因为我们假设它可以让模型很容易地学会通过相对位置来注意,因为对于任何固定的偏移 k,P E pos+k 可以表示为 P E pos 的线性函数。

我们还尝试使用学习的位置嵌入 [8],发现这两个版本产生了几乎相同的结果(参见表 3 行 (E))。我们选择正弦版本是因为它可能允许模型外推到比训练期间遇到的序列更长的序列。

# 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 (x 1 , ..., x n ) to another sequence of equal length (z 1 , ..., z n ), with x i , z i ∈ R d , 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 [11]. Hence we also compare the maximum path length between any two input and output positions in networks composed of the different layer types. As noted in Table 1, a self-attention layer connects all positions with a constant number of sequentially executed operations, whereas a recurrent layer requires O(n) sequential operations. In terms of computational complexity, self-attention layers are faster than recurrent layers when the sequence length n is smaller than the representation dimensionality d, which is most often the case with sentence representations used by state-of-the-art models in machine translations, such as word-piece [31] and byte-pair [25] representations. 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/k) convolutional layers in the case of contiguous kernels, or O(log k (n)) in the case of dilated convolutions [15], 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 • d 2 ) . 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.

自注意力机制

在本节中,我们将自注意力层和通常用于将一个可变长度的符号表示序列(x1、…、xn)映射到另一个相同长度的序列(z1、…、zn)的递归和卷积层,与 xi,zi ∈ Rd 进行了比较,例如典型序列转导编码器或解码器中的隐藏层。为了说明我们使用自注意力机制的动机,我们考虑了三个方面。 其一是每层总的计算复杂度。另一个是可以并行化的计算量,以所需的最小顺序操作数来衡量。 第三个是在网络中长距离依赖关系之间的路径长度。学习长距离依赖关系是在许多序列转导任务中的一项关键挑战。影响学习此类依赖关系能力的一个关键因素是网络中前向信号和后向信号必须遍历的路径长度。输入和输出序列中任意位置组合之间的路径越短,学习长距离依赖关系就越容易 [11]。因此,我们还比较了由不同层类型组成的网络中任意两个输入和输出位置之间的最长路径长度。 如表 1 所示,一个自注意力层以恒定数量的顺序执行操作将所有位置连接起来,而递归层需要 O(n) 个顺序操作。在计算复杂度方面,当序列长度 n 小于表示维度 d 时,自注意力层比递归层更快,这在机器翻译领域的最先进模型使用的句子表示形式中是最常见的,例如 word-piece [31] 和 byte-pair [25] 表示形式。为了提高涉及非常长序列的任务的计算性能,可以将自注意力限制为仅考虑输入序列围绕相应输出位置大小为 r 的邻域。这样会将最长路径长度增加到 O(n/r)。我们计划在未来的工作中进一步研究这种方法。 具有内核宽度 k < n 的一个卷积层不会将所有输入和输出位置都连接起来。如果使用连续的内核,则需要一个包含 O(n/k) 层的卷积层堆栈;如果使用膨胀卷积 [15],则需要一个包含 O(log k (n)) 层的卷积层堆栈,增加网络中任意两个位置之间最长路径的长度。卷积层通常比递归层昂贵,昂贵程度为 k。然而,可分离卷积 [6] 将复杂性大大降低到 O(k•n•d + n•d2)。然而,即使 k = n,可分离卷积的复杂度也等于自注意力层和逐点前馈层的组合,这是我们在模型中采用的方法。 作为一项附带优点,自注意力机制可以产生更易于解释的模型。我们检查了模型的注意力分布,并在附录中给出了示例并进行了讨论。各个注意力头不仅可以清楚地学会执行不同的任务,而且很多还表现出与句子的句法和语义结构相关的行为。

# Training

This section describes the training regime for our models.

本部分描述了我们模型的训练制度。

# 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 [3], which has a shared sourcetarget 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 [31]. 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 个单词块词汇表 [31]。通过近似的序列长度对句子对进行批处理。每个训练批处理包含一组句子对,其中包含大约 25000 个源标记和 25000 个目标标记。

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

硬件和时间表

我们在装有 8 个 NVIDIA P100 GPU 的一台机器上训练了我们的模型。对于我们在论文中描述过的超参数所用的基础模型,每个训练步骤大约需要 0.4 秒。我们总共对基础模型进行了 100,000 步或 12 小时的训练。对于我们的大型模型(在表 3 的底行描述),步骤时间是 1.0 秒。我们对大型模型进行了 300,000 步(3.5 天)的训练。

# Optimizer

We used the Adam optimizer [17] with β 1 = 0.9, β 2 = 0.98 and = 10 -9 . We varied the learning rate over the course of training, according to the formula: lrate = d -0.5 model • min(step_num -0.5 , step_num • warmup_steps -1.5 )(3) 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优化器 [17],其中 β1 = 0.9、 β 2 = 0.98 和 = 10 -9。我们根据以下公式在训练过程中改变学习率: lrate = d -0.5 模型 • 最小(步数 -0.5,步数 • 热身步数 -1.5 )(3) 这相当于在前 warmup_steps 训练步骤中线性增加学习率,此后与步数的平方根成反比将其减少。我们使用 warmup_steps = 4000。

# Regularization

We employ three types of regularization during training: Residual Dropout We apply dropout [27] to the output of each sub-layer, before it is added to the sub-layer input and normalized. In addition, we apply dropout to the sums of the embeddings and the positional encodings in both the encoder and decoder stacks. For the base model, we use a rate of P drop = 0.1. Label Smoothing During training, we employed label smoothing of value ls = 0.1 [30]. This hurts perplexity, as the model learns to be more unsure, but improves accuracy and BLEU score. 6 Results

正则化

我们在训练过程中使用了三种类型的正则化:

残差 Dropout 在将每个子层的输出添加到子层输入并归一化之前,我们将 Dropout [27] 应用于每个子层的输出。此外,我们在编码器和解码器堆栈中将 Dropout 应用于嵌入和位置编码的和。对于基础模型,我们使用删除率 Pdrop = 0.1。标签平滑 在训练期间,我们使用了标签平滑,值为 ls = 0.1 [30]。这会损害困惑度,因为模型学会变得更加不确定,但会提高准确率和 BLEU 分数。结果

# 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 P drop = 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 [31]. These hyperparameters were chosen after experimentation on the development set. We set the maximum output length during inference to input length + 50, but terminate early when possible [31]. 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 GPU5 .

机器翻译

在 WMT 2014 英语到德语翻译任务中,大型 Transformer 模型(表 2 中的 Transformer(大))比之前报告的最佳模型(包括集合)高出 2.0 以上的 BLEU 分数,建立了新的 28.4 的 BLEU 分数最先进水平。此模型的配置在表 3 的底部列出。训练在 8 个 P100 GPU 上进行了 3.5 天。即使是我们的基础模型也超过了所有之前发布的模型和集合,而其训练成本只是任何竞争模型的一小部分。

在 WMT 2014 英语到法语翻译任务中,我们的大型模型实现了 41.0 的 BLEU 分数,其性能优于所有之前发布的单一模型,并且其训练成本不到之前最先进模型的 1/4。用于英语到法语的 Transformer(大)模型使用前述概率 P 为 0.1 的辍学率,而不是 0.3 的前述概率。

对于基础模型,我们使用了一个通过平均最后 5 个检查点(以 10 分钟的间隔编写)而获得的单一模型。对于大型模型,我们平均了最后 20 个检查点。我们使用波束搜索,波束大小为 4,长度惩罚系数 α = 0.6 [31]。这些超参数是在对开发集合进行试验后选择的。我们将推理期间的最大输出长度设置为输入长度 + 50,但如果可能,会尽早终止 [31]。

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

# 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 d k hurts model quality. This suggests that determining compatibility is not easy and that a more sophisticated compatibility function than dot product may be beneficial. We further observe in rows (C) and (D) that, as expected, bigger models are better, and dropout is very helpful in avoiding over-fitting. In row (E) we replace our sinusoidal positional encoding with learned positional embeddings [8], and observe nearly identical results to the base model.

模型变化

为了评估 Transformer 各个组成部分的重要性,我们以不同的方式改变了基础模型,在英德翻译中的开发集中测量性能变化,newstest2013。我们使用了前一节中描述的 beam search,但没有检查点的平均值。我们在表 3 中展示了这些结果。 在表 3 行(A)中,我们改变了注意力头的数量和注意力键和值的维度,保持计算量不变,如第 3.2.2 节中所述。虽然单头注意力比最佳设置差 0.9 BLEU,但质量也会随着头部数量过多而下降。 在表 3 行(B)中,我们观察到减少注意力键大小 d k 会损害模型质量。这表明确定兼容性并不容易,并且比点积更复杂的兼容性函数可能是有益的。我们在行 (C) 和 (D) 中进一步观察到,正如预期的那样,较大的模型更好,dropout 在避免过度拟合方面非常有用。在行 (E) 中,我们将正弦位置编码替换为学习的位置嵌入[8],并观察到与基础模型几乎相同的结果。

# 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. The code we used to train and evaluate our models is available at github.com/ tensorflow/tensor2tensor.

在本项工作中,我们提出了Transformer,这是第一个完全基于注意力的序列转换模型,使用多头自注意力取代了在编码器-解码器架构中最常用的循环层。 对于翻译任务,与基于循环层或卷积层的架构相比,Transformer 的训练速度可以显著提升。在 WMT 2014 英译德和 WMT 2014 英译法翻译任务上,我们都取得了新的突破。在前一项任务中,我们的最佳模型甚至优于以前报道的所有集成模型。 我们对基于注意力的模型的未来感到兴奋,并计划将它们应用于其他任务。我们计划将 Transformer 扩展到涉及除文本之外的输入和输出模态的问题,并研究局部、受限注意力机制以有效处理图像、音频和视频等大型输入和输出。让生成过程减少顺序性是我们研究的另一个目标。 我们用来训练和评估模型的代码可从 github.com/ tensorflow/tensor2tensor 获得。