首先放原文地址:https://arxiv.org/pdf/1706.03762
前言
首先我没有系统学习过和深度学习有关的内容,本文仅代表我个人的理解。
本文将和原文的章节一一对应,同时给出原文和译文以及我自己增加的额外的解释。
下面从摘要开始:
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 分。
在 WMT-2014 英语到法语的翻译任务上,我们的模型在经过 8 个 GPU 训练3.5天后,取得了41.8的 BLEU 分数,创造了新的在单模型中最好的 BLEU 成绩,这是现有文献中最好的模型的训练成本的一小部分。
我们通过成功地将Transformer应用于英语成分解析,证明该模型能够很好地推广到其他任务,并且在大规模和有限训练数据的情况下都能取得优异的表现。
Introduction
介绍
Recurrent neural networks, long short-term memory [13] and gated recurrent [7] neural networks in particular, have been firmly established as state of the art approaches in sequence modeling and transduction problems such as language modeling and machine translation [35, 2, 5]. Numerous efforts have since continued to push the boundaries of recurrent language models and encoder-decoder architectures [38, 24, 15].
循环神经网络,特别是 长短期记忆(LSTM)[13] 和 门控循环 [7] 神经网络(RNN),已被确立为序列建模和转导问题(如语言建模和机器翻译 [35,2,5])的最新方法。
此后,还有许多正在努力推动着循环语言模型和编码器-解码器架构的边界 [38,24,15]。
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 [21] and conditional computation [32], while also improving model performance in case of the latter. The fundamental constraint of sequential computation, however, remains.
递归模型通常沿着输入和输出序列的符号位置进行计算。它们将位置与计算步骤对齐,生成一个隐藏状态序列 $h_t$,该序列是前一个隐藏状态 $h_{t−1}$ 和当前位置 $t$ 输入的函数。
这种固定的顺序性使得在训练时无法在模型内部进行并行化,由于内存限制,无法同时处理多个批次,而这又在处理长序列时尤为重要。
最近的研究通过一些 因式分解技巧 [21] 和 条件计算 [32] 显著提高了计算效率,同时在条件计算的情况下也提升了模型性能。然而,顺序计算的基本限制依然存在。
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, 19]. In all but a few cases [27], however, such attention mechanisms are used in conjunction with a recurrent network.
注意力机制已经成为许多序列建模和转换模型中不可或缺的一部分,能够在各种任务中建模依赖关系,而不考虑它们在输入或输出序列中的距离 [2, 19]。
然而,在除少数几种情况 [27] 之外,注意力机制通常是与递归网络结合使用的。
In this work we propose the Transformer, a model architecture eschewing recurrence and instead relying entirely on an attention mechanism to draw global dependencies between input and output. The Transformer allows for significantly more parallelization and can reach a new state of the art in translation quality after being trained for as little as twelve hours on eight P100 GPUs.
在这项研究中,我们提出了一种摒弃递归机制、完全依赖注意力机制来建模输入和输出之间全局依赖关系的模型架构——Transformer。
Transformer 允许更大程度的并行化,并且经过仅仅十二小时在八块P100 GPU上训练后,能够在翻译质量上达到新的最先进水平。
Background
背景
The goal of reducing sequential computation also forms the foundation of the Extended Neural GPU [16], ByteNet [18] and ConvS2S [9], all of which use convolutional neural networks as basic building block, computing hidden representations in parallel for all input and output positions. In these models, the number of operations required to relate signals from two arbitrary input or output positions grows in the distance between positions, linearly for ConvS2S and logarithmically for ByteNet. This makes it more difficult to learn dependencies between distant positions [12]. In the Transformer this is reduced to a constant number of operations, albeit at the cost of reduced effective resolution due to averaging attention-weighted positions, an effect we counteract with Multi-Head Attention as described in section 3.2.
减少顺序计算的目标也是扩展神经GPU [16]、ByteNet [18] 和 ConvS2S [9] 的基础,这些模型都使用卷积神经网络作为基本构建模块,在所有输入和输出位置并行计算隐藏表示。
在这些模型中,将信号从两个任意输入或输出位置关联起来所需的操作数量随着位置之间的距离增长:对于 ConvS2S 是线性增长的,对于 ByteNet 则是对数增长的。这使得学习远距离位置之间的依赖关系变得更加困难 [12]。
在 Transformer 中,这个问题被减少为常数数量的操作。尽管由于对注意力加权位置的平均处理,导致有效分辨率降低,这一效应我们通过在 3.2 节中描述的多头注意力(Multi-Head Attention)来进行补偿。
Self-attention, sometimes called intra-attention is an attention mechanism relating different positions of a single sequence in order to compute a representation of the sequence. Self-attention has been used successfully in a variety of tasks including reading comprehension, abstractive summarization, textual entailment and learning task-independent sentence representations [4, 27, 28, 22].
自注意力(Self-attention),有时也称为内部注意力(Intra-attention),是一种将单个序列的不同位置进行关联的注意力机制,目的是计算该序列的表示。自注意力已成功应用于各种任务,包括阅读理解、抽象摘要、文本蕴含以及学习与任务无关的句子表示 [4, 27, 28, 22]。
End-to-end memory networks are based on a recurrent attention mechanism instead of sequence aligned recurrence and have been shown to perform well on simple-language question answering and language modeling tasks [34].
端到端记忆网络基于递归注意力机制,而不是按顺序对齐的递归,并且已被证明在简单语言的问答和语言建模任务中表现良好 [34]。
To the best of our knowledge, however, the Transformer is the first transduction model relying entirely on self-attention to compute representations of its input and output without using sequence aligned RNNs or convolution. In the following sections, we will describe the Transformer, motivate self-attention and discuss its advantages over models such as [17, 18] and [9].
然而据我们所知,Transformer 是首个完全依赖自注意力机制来计算输入和输出表示的转换模型,且无需使用按序列顺序对齐的 RNN 或卷积。
在接下来的章节中,我们将描述 Transformer 并阐述自注意力机制的原理,并讨论其相对于如 [17, 18] 和 [9] 等模型的优势。
Model Architecture
模型架构
Most competitive neural sequence transduction models have an encoder-decoder structure [5, 2, 35]. Here, the encoder maps an input sequence of symbol representations $(x_1, \cdots, x_n)$ to a sequence of continuous representations $z = (z_1, \cdots, z_n)$. Given $z$, the decoder then generates an output sequence $(y_1, \cdots, y_m)$ of symbols one element at a time. At each step the model is auto-regressive [10], consuming the previously generated symbols as additional input when generating the next.
大多数竞争力强的神经序列转换模型都采用编码器-解码器结构 [5, 2, 35]。
在这种结构中,编码器将输入序列的符号表示 $(x_1, \cdots, x_n)$ 映射到一组连续表示 $z = (z_1, \cdots, z_n)$。
给定 $z$ 后,解码器逐个生成输出序列 $(y_1, \cdots, y_m)$ 中的符号。
在每一步,模型是自回归的 [10],在生成下一个符号时,会将之前生成的符号作为额外输入。
The Transformer follows this overall architecture using stacked self-attention and point-wise, fully connected layers for both the encoder and decoder, shown in the left and right halves of Figure 1, respectively.
Transformer 采用了这种总体架构,在编码器和解码器中分别使用堆叠的自注意力机制和逐点全连接层,如图 1 的左半部分和右半部分所示。
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 [11] 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$.
编码器由 $N = 6$ 个相同的层堆叠而成。每一层包含两个子层。
第一个子层是一个多头自注意力机制(Multi-Head Attention),第二个子层是一个简单的逐位置全连接前馈网络(Feed Forward Network)。
我们在每个子层周围使用残差连接[11],并随后进行层归一化[1]。即每个子层的输出为 $LayerNorm(x + Sublayer(x))$,其中 $Sublayer(x)$ 是子层本身实现的函数。
为了方便这些残差连接,模型中的所有子层以及嵌入层的输出维度均为 $d_{model} = 512$。
Decoder
解码器
The decoder is also composed of a stack of $N = 6$ identical layers. In addition to the two sub-layers in each encoder layer, the decoder inserts a third sub-layer, which performs multi-head attention over the output of the encoder stack. Similar to the encoder, we employ residual connections around each of the sub-layers, followed by layer normalization. We also modify the self-attention sub-layer in the decoder stack to prevent positions from attending to subsequent positions. This masking, combined with fact that the output embeddings are offset by one position, ensures that the predictions for position $i$ can depend only on the known outputs at positions less than $i$.
解码器同样由 $N = 6$ 个相同的层堆叠而成。
除了每个编码器层中的两个子层外,解码器还插入了第三个子层,这个子层执行多头注意力机制,作用于编码器堆叠的输出。
与编码器类似,我们在每个子层周围使用残差连接,随后进行层归一化。
我们还修改了解码器堆叠中的自注意力子层,防止当前位置关注后续位置。这个遮蔽机制,再加上输出嵌入被偏移一个位置的事实,确保了位置 $i$ 的预测只能依赖于位置小于 $i$ 的已知输出。
Add & Norm(补充)
Add & Norm 是残差连接(Residual Connection)和层归一化(Layer Normalization)的组合。
层归一化是 Transformer 中用来标准化激活的技术。与批量归一化(Batch Normalization)不同,层归一化是在每个样本的每一层中进行归一化,而不是在整个批次的维度上做归一化。
图中的 [Add & Norm] 模块有两个输入一个输出,其中输入分别为 $x$ 和 $sub-layer(x)$,输出与输入的 $x$ 形状相同。
首先进行残差连接,$ t = x + sub-layer(x) $,直接做一个向量加法即可。
计算 $t$ 的平均值 $\mu$ 和标准差 $\sigma$,最后得到输出:
$$ AddNorm(x, t) = \frac {t – \mu}{\sigma} \cdot \gamma + \beta$$
其中 $\gamma$ 是缩放因子,$\beta$ 是偏置。
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 query with all keys, divide each by $\sqrt{d_k}$, and apply a softmax function to obtain the weights on the values.
我们称我们特别的注意力为:”缩放点积注意力” (图 2)。输入由以下部分组成:维度为 $d_k$ 的查询 $Q$ (query) 和键 $K$ (key) 以及维度为 $d_v$ 的值 $V$ (value). 用每一个 查询 $Q$ 点积所有的 键 $K$,得到的每一个值再除以 $\sqrt{d_k}$,然后使用 softmax 函数来得到这些值的权重。
In practice, we compute the attention function on a set of queries simultaneously, packed together into a matrix $Q$. The keys and values are also packed together into matrices $K$ and $V$ . We compute the matrix of outputs as:
在实践中,我们同时计算一组查询的注意力函数,将这一组注意力整合在一个矩阵 Q 中。键 $K$ 和值 $V$ 也要整合在一个矩阵 $K$ 和 $V$ 中。
计算输出矩阵的公式:
$$Attention(Q, K, V) = softmax(\frac {Q \cdot K^T}{\sqrt {d_k}}) \cdot V$$
The two most commonly used attention functions are additive attention [2], and dot-product (multiplicative) attention. Dot-product attention is identical to our algorithm, except for the scaling factor of ${1 \over \sqrt{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.
最常见的两种注意力函数是加型注意力 [2 ]和点积注意力。除了缩放因子 ${1 \over \sqrt{d_k}}$ 外点积注意力和我们的算法相同。
附加注意力使用具有单个隐藏层的前馈网络来计算兼容性函数。虽然两者在理论复杂性上相似,但点积注意力在实践中要快得多,空间效率也更高,因为它可以使用高度优化的矩阵乘法代码来实现。
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 gradients 4. To counteract this effect, we scale the dot products by ${1 \over \sqrt{d_k}}$.
虽然对于较小的$d_k$值,这两种机制的表现相似,但加型注意力的表现优于没有对 $d_k$ 进行大值缩放的点积注意力 [3]。
们怀疑,对于较大的值 $d_k$,点积增长幅度很大,将 softmax 函数推向了它所具有的极小的梯度 4 的区域。为了抵消这种影响,我们将点积按 ${1\over\sqrt{d_k}}$ 进行缩放。
缩放点积注意力(补充)
这里详细解释一下缩放点积注意力的整个计算过程,首先假设词向量维度是 $d_{model} = 512$,输入序列长度(上下文长度)$d_v = 8192$,以及 查询 Q/ 键 K 向量维度 $d_k = 128$。
现在假设有一句:The cat sat on the mat,一共 6 个词。
将每一个词编码成 $(1 \times 512)$ 的词向量 $E_i$,然后组合在一个 $(8192 \times 512)$ 的 Embedding 矩阵 $E = [E_1, E_2, \cdots, E_i]$ 中。
由于实际文本长度只有6,下面简化 8192 的长度为 6。
$$E = \begin{pmatrix} {\begin{pmatrix} 1.01 \\ -0.16 \\ \cdots \\ 0.96 \end{pmatrix}}, & {\begin{pmatrix} 2.14 \\ -1.42 \\ \cdots \\ 0.42 \end{pmatrix}}, & E_2, & E_3, & E_4, & E_5, & \cdots, & E_i \\ \end{pmatrix}$$
很容易得出矩阵 $W_Q$ 是一个形状为 $(d_{model} \times d_k)$ 的矩阵:
$$W_Q = \begin{pmatrix} 0.15 & \cdots & 1.17 \\ \vdots & \ddots & \vdots \\ -1.21 & \cdots & 0.56 \end{pmatrix}$$
将矩阵 $E$ 左乘矩阵 $W_Q$,得到查询矩阵 Q:
$$Q = W_Q \cdot E$$
得到的查询矩阵 Q,每一行都是一个查询 $Q_i$。
下面同理也可以得到,键矩阵 K:
$$K = W_K \cdot E$$
因此可以得到 $Q \cdot K_T$ 的结果:
因为是每一个查询 $Q_i$ 都要对所有的 K 进行一次查询,因此紧接着对每一行计算 softmax:
最后计算矩阵 V,这个矩阵是 $(d_v \times d_{model})$ 大小的,这里就是 $(8192 \times 512)$。而 $W_V$ 的形状一般是 $(d_v \times d_v)$,这里就是 $(8192 \times 8192)$。
同样地,将 $W_V$ 左乘 $E$,得到 V 矩阵,每一行则是 $V_i$。
下面计算加权和 $\delta E_i$:
$$\delta E_i = \sum_{j = 0}^{d_v} (V_j \cdot softmax(Q_i \cdot K^T)_j) = \sum_{j = 0}^{d_v} (V_j \cdot p_{ij})$$
这里的 $W_V$ 矩阵是 $(8192 \times 8192)$ 的,参数量达到了 67, 108, 864 个,我们可以采用 LoRA(Low-Rank Adaptation) 的思想,将这个大矩阵拆分成两个更小的矩阵。
这里可以将其拆分为两个形状为 $(d_k \times d_v)$ 的 $W_{V1}$ 和 $W_{V2}$ 矩阵,这样参数量就减少到了 2, 097, 152 个,数量仅是原来的 3.125%。
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. \cdots, head_h)W^O$$
$$where \cdot head_i = Attention(QW_i^Q, KW_i^K, VW_i^V)$$
Where the projections are parameter matrices $W_i^Q \in R^{d_{model} \times d_k}, W_i^K \in R^{d_{model} \times d_k}, W_i^V \in R^{d_{model} \times d_v}$ and $W^O \in R^{hd_v \times d_{model}}$.
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.
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 [38, 2, 9].
• The encoder contains self-attention layers. In a self-attention layer all of the keys, values and queries come from the same place, in this case, the output of the previous layer in the encoder. Each position in the encoder can attend to all positions in the previous layer of the encoder.
• Similarly, self-attention layers in the decoder allow each position in the decoder to attend to all positions in the decoder up to and including that position. We need to prevent leftward information flow in the decoder to preserve the auto-regressive property. We implement this inside of scaled dot-product attention by masking out (setting to −∞) all values in the input of the softmax which correspond to illegal connections. See Figure 2.
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$$
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_{ff} = 2048$.
Table 1: Maximum path lengths, per-layer complexity and minimum number of sequential operations for different layer types. n is the sequence length, d is the representation dimension, k is the kernel size of convolutions and r the size of the neighborhood in restricted self-attention.
Layer Type | Complexity per Layer | Sequential Operations | Maximum Path Length |
Self-Attention | $O(n_2 \cdot d)$ | $O(1)$ | $O(1)$ |
Recurrent | $O(n \cdot d^2)$ | $O(n)$ | $O(n)$ |
Convolutional | $O(k \cdot n \cdot d^2)$ | $O(1)$ | $O(log_k(n))$ |
Self-Attention (restricted) | $O(r \cdot n \cdot d)$ | $O(1)$ | $O(n / r)$ |
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 [30]. In the embedding layers, we multiply those weights by $\sqrt{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 bottoms of the encoder and decoder stacks. The positional encodings have the same dimension dmodel as the embeddings, so that the two can be summed. There are many choices of positional encodings, learned and fixed [9].
In this work, we use sine and cosine functions of different frequencies:
$$PE_{(pos, 2i)} = \sin(pos / 10000^{2i / d_{model}})$$
$$PE_{(pos, 2i+1)} = \cos(pos / 10000^{2i / d_{model}})$$
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\pi$ to $10000 \cdot 2\pi$. 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, PE_{pos+k}$ can be represented as a linear function of $PE_{pos}$.
We also experimented with using learned positional embeddings [9] instead, and found that the two versions produced nearly identical results (see Table 3 row (E)). We chose the sinusoidal version because it may allow the model to extrapolate to sequence lengths longer than the ones encountered during training.
WhySelf-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, \cdots, x_n)$ to another sequence of equal length $(z_1, \cdots, z_n)$, with $x_i, z_i \in 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 [12]. 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 [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.
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 [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 \cdot n \cdot d + n \cdot 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.
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 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.
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).
Optimizer
We used the Adam optimizer [20] with $\beta_1 = 0.9, \beta_2 = 0.98$ and $\epsilon = 10^{−9}$. We varied the learning rate over the course of training, according to the formula:
$$lrate = d_{model}^{-0.5} \cdot min({step\_num}^{-0.5}, {step\_num} \cdot {warmup\_steps}^{-1.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$.
Regularization
We employ three types of regularization during training:
Table2: The Transformer achieves better BLEU scores than previous state-of-the-art models on the English-to-German and English-to-French newstest2014 tests at a fraction of the training cost.
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 embedding sand 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 $\epsilon_{ls} = 0.1$ [36]. This hurts perplexity, as the model learns to be more unsure, but improves accuracy and BLEU score.
Results
Machine Translation
On the WMT2014 English-to-German translation task, the big transformer model(Transformer(big)
inTable2) 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 P100GPUs. 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 WMT2014 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 $\alpha = 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].(5.We used values of 2.8, 3.7, 6.0 and 9.5 TFLOPS for K80, K40, M40 and P100, respectively.)
Model Variations
Table3: Variations on the Transformer architecture. Unlisted values are identical to those of the base model. All metrics are on the English-to-German translation development set, newstest 2013. Listed perplexities are per-word piece, according to our byte-pair encoding, and should not be compared to per-word perplexities.
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, newstest 2013. 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 [9], and observe nearly identical results to the base model.
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 [37].
We trained a 4-layer transformer with $d_{model} = 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 $\alpha = 0.3$ for both WSJ only and the semi-supervised setting.
Table 4: The Transformer generalizes well to English constituency parsing (Results are on Section 23 of WSJ)
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 [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.
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 https://github.com/tensorflow/tensor2tensor.
Acknowledgements We are grateful to Nal Kalchbrenner and Stephan Gouws for their fruitful
comments, corrections and inspiration.
References
- [1] Jimmy Lei Ba, Jamie Ryan Kiros, and Geoffrey E Hinton. Layer normalization. arXiv preprint arXiv:1607.06450, 2016.
- [2] Dzmitry Bahdanau, Kyunghyun Cho, and Yoshua Bengio. Neural machine translation by jointly learning to align and translate. CoRR, abs/1409.0473, 2014.
- [3] Denny Britz, Anna Goldie, Minh-Thang Luong, and Quoc V. Le. Massive exploration of neural machine translation architectures. CoRR, abs/1703.03906, 2017.
- [4] Jianpeng Cheng, Li Dong, and Mirella Lapata. Long short-term memory-networks for machine reading. arXiv preprint arXiv:1601.06733, 2016.
- [5] Kyunghyun Cho, Bart van Merrienboer, Caglar Gulcehre, Fethi Bougares, Holger Schwenk, and Yoshua Bengio. Learning phrase representations using rnn encoder-decoder for statistical machine translation. CoRR, abs/1406.1078, 2014.
- [6] Francois Chollet. Xception: Deep learning with depthwise separable convolutions. arXiv preprint arXiv:1610.02357, 2016.
- [7] Junyoung Chung, Çaglar Gülçehre, Kyunghyun Cho, and Yoshua Bengio. Empirical evaluation of gated recurrent neural networks on sequence modeling. CoRR, abs/1412.3555, 2014.
- [8] Chris Dyer, Adhiguna Kuncoro, Miguel Ballesteros, and Noah A. Smith. Recurrent neural network grammars. In Proc. of NAACL, 2016.
- [9] Jonas Gehring, Michael Auli, David Grangier, Denis Yarats, and Yann N. Dauphin. Convolutional sequence to sequence learning. arXiv preprint arXiv:1705.03122v2, 2017.
- [10] Alex Graves. Generating sequences with recurrent neural networks. arXiv preprint arXiv:1308.0850, 2013.
- [11] Kaiming He, Xiangyu Zhang, Shaoqing Ren, and Jian Sun. Deep residual learning for image recognition. In Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition, pages 770–778, 2016.
- [12] Sepp Hochreiter, Yoshua Bengio, Paolo Frasconi, and Jürgen Schmidhuber. Gradient flow in recurrent nets: the difficulty of learning long-term dependencies, 2001.
- [13] Sepp Hochreiter and Jürgen Schmidhuber. Long short-term memory. Neural computation, 9(8):1735–1780, 1997.
- [14] Zhongqiang Huang and Mary Harper. Self-training PCFG grammars with latent annotations across languages. In Proceedings of the 2009 Conference on Empirical Methods in Natural Language Processing, pages 832–841. ACL, August 2009.
- [15] Rafal Jozefowicz, Oriol Vinyals, Mike Schuster, Noam Shazeer, and Yonghui Wu. Exploring the limits of language modeling. arXiv preprint arXiv:1602.02410, 2016.
- [16] Łukasz Kaiser and Samy Bengio. Can active memory replace attention? In Advances in Neural Information Processing Systems, (NIPS), 2016.
- [17] Łukasz Kaiser and Ilya Sutskever. Neural GPUs learn algorithms. In International Conference on Learning Representations (ICLR), 2016.
- [18] Nal Kalchbrenner, Lasse Espeholt, Karen Simonyan, Aaron van den Oord, Alex Graves, and Ko ray Kavukcuoglu. Neural machine translation in linear time. arXiv preprint arXiv:1610.10099v2, 2017.
- [19] Yoon Kim, Carl Denton, Luong Hoang, and Alexander M. Rush. Structured attention networks. In International Conference on Learning Representations, 2017.
- [20] Diederik Kingma and Jimmy Ba. Adam: A method for stochastic optimization. In ICLR, 2015.
- [21] Oleksii Kuchaiev and Boris Ginsburg. Factorization tricks for LSTM networks. arXiv preprint arXiv:1703.10722, 2017.
- [22] Zhouhan Lin, Minwei Feng, Cicero Nogueira dos Santos, Mo Yu, Bing Xiang, Bowen Zhou, and Yoshua Bengio. A structured self-attentive sentence embedding. arXiv preprint arXiv:1703.03130, 2017.
- [23] Minh-Thang Luong, Quoc V. Le, Ilya Sutskever, Oriol Vinyals, and Lukasz Kaiser. Multi-task sequence to sequence learning. arXiv preprint arXiv:1511.06114, 2015.
- [24] Minh-Thang Luong, Hieu Pham, and Christopher D Manning. Effective approaches to attention based neural machine translation. arXiv preprint arXiv:1508.04025, 2015.
- [25] Mitchell P Marcus, Mary AnnMarcinkiewicz, and Beatrice Santorini. Building a large annotated corpus of english: The penn treebank. Computational linguistics, 19(2):313–330, 1993.
- [26] David McClosky, Eugene Charniak, and Mark Johnson. Effective self-training for parsing. In Proceedings of the Human Language Technology Conference of the NAACL, Main Conference, pages 152–159. ACL, June 2006.
- [27] Ankur Parikh, Oscar Täckström, Dipanjan Das, and Jakob Uszkoreit. A decomposable attention model. In Empirical Methods in Natural Language Processing, 2016.
- [28] Romain Paulus, Caiming Xiong, and Richard Socher. A deep reinforced model for abstractive summarization. arXiv preprint arXiv:1705.04304, 2017.
- [29] Slav Petrov, Leon Barrett, Romain Thibaux, and Dan Klein. Learning accurate, compact, and interpretable tree annotation. In Proceedings of the 21st International Conference on Computational Linguistics and 44th Annual Meeting of the ACL, pages 433–440. ACL, July 2006.
- [30] Ofir Press and Lior Wolf. Using the output embedding to improve language models. arXiv preprint arXiv:1608.05859, 2016.
- [31] Rico Sennrich, Barry Haddow, and Alexandra Birch. Neural machine translation of rare words with subword units. arXiv preprint arXiv:1508.07909, 2015.
- [32] Noam Shazeer, Azalia Mirhoseini, Krzysztof Maziarz, Andy Davis, Quoc Le, Geoffrey Hinton, and Jeff Dean. Outrageously large neural networks: The sparsely-gated mixture-of-experts layer. arXiv preprint arXiv:1701.06538, 2017.
- [33] Nitish Srivastava, Geoffrey E Hinton, Alex Krizhevsky, Ilya Sutskever, and Ruslan Salakhutdi nov. Dropout: a simple way to prevent neural networks from overfitting. Journal of Machine Learning Research, 15(1):1929–1958, 2014.
- [34] Sainbayar Sukhbaatar, Arthur Szlam, Jason Weston, and Rob Fergus. End-to-end memory networks. In C. Cortes, N. D. Lawrence, D. D. Lee, M. Sugiyama, and R. Garnett, editors, Advances in Neural Information Processing Systems 28, pages 2440–2448. Curran Associates, Inc., 2015.
- [35] Ilya Sutskever, Oriol Vinyals, and Quoc VV Le. Sequence to sequence learning with neural networks. In Advances in Neural Information Processing Systems, pages 3104–3112, 2014.
- [36] Christian Szegedy, Vincent Vanhoucke, Sergey Ioffe, Jonathon Shlens, and Zbigniew Wojna. Rethinking the inception architecture for computer vision. CoRR, abs/1512.00567, 2015.
- [37] Vinyals & Kaiser, Koo, Petrov, Sutskever, and Hinton. Grammar as a foreign language. In Advances in Neural Information Processing Systems, 2015.
- [38] Yonghui Wu, Mike Schuster, Zhifeng Chen, Quoc V Le, Mohammad Norouzi, Wolfgang Macherey, Maxim Krikun, Yuan Cao, Qin Gao, Klaus Macherey, et al. Google’s neural machine translation system: Bridging the gap between human and machine translation. arXiv preprint arXiv:1609.08144, 2016.
- [39] Jie Zhou, Ying Cao, Xuguang Wang, Peng Li, and Wei Xu. Deep recurrent models with fast-forward connections for neural machine translation. CoRR, abs/1606.04199, 2016.
- [40] Muhua Zhu, Yue Zhang, Wenliang Chen, Min Zhang, and Jingbo Zhu. Fast and accurate shift-reduce constituent parsing. In Proceedings of the 51st Annual Meeting of the ACL (Volume 1: Long Papers), pages 434–443. ACL, August 2013.