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.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,它完全基于注意力机制,彻底摒弃了循环和卷积结构。在两个机器翻译任务上的实验表明,该模型在保持更高质量的同时具备更强的并行化能力,且训练时间显著缩短。我们的模型在WMT2014英德翻译任务中取得了28.4的BLEU值,比现有最佳结果(包括集成模型)高出2个BLEU以上。在WMT2014英法翻译任务中,经过8块GPU上3.5天的训练(仅为文献中最佳模型训练成本的一小部分),我们的模型创下了41.8的单模型最高BLEU分记录。通过将该模型成功应用于英语成分句法分析(无论训练数据量大小),我们证明了Transformer具有优异的泛化能力。
1 Introduction 介绍
Recurrent neural networks, long short-term memory 1 and gated recurrent 2 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 3 , 4 , 5. Numerous efforts have since continued to push the boundaries of recurrent language models and encoder-decoder architectures 6, 7, 8.
循环神经网络,尤其是长短期记忆网络1和门控循环单元网络2,已在序列建模和转换任务(如语言建模和机器翻译3, 4, 5)中被公认为最先进的解决方案。此后大量研究持续推动着循环语言模型与编码器-解码器架构的发展边界6, 7, 8。
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
h_t
ht, as a function of the previous hidden state
h
t
−
1
h_{t−1}
ht−1 and the input for position
t
t
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 9 and conditional computation 10, while also improving model performance in case of the latter. The fundamental constraint of sequential computation, however, remains.
循环模型通常沿着输入和输出序列的符号位置分解计算过程。它们将位置与计算时间步对齐,通过前一个隐藏状态
h
t
−
1
h_{t-1}
ht−1和位置
t
t
t的输入,生成一系列隐藏状态
h
t
h_t
ht。这种固有的顺序特性阻碍了训练样本内部的并行化处理,当序列较长时这个问题尤为突出,因为内存限制会影响跨样本的批处理。近期研究通过因子分解技巧9和条件计算10显著提升了计算效率,后者还同时改善了模型性能。然而顺序计算的根本限制依然存在。
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 4, 11. In all but a few cases 12, however, such attention mechanisms are used in conjunction with a recurrent network.
注意力机制已成为各种任务中引人注目的序列建模和转换模型的重要组成部分,它能够对依赖关系进行建模,而无需考虑其在输入或输出序列中的距离4, 11。然而,除少数情况外12,此类注意力机制通常与循环网络结合使用。
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模型架构,它摒弃了循环结构,完全依赖注意力机制来捕捉输入与输出之间的全局依赖关系。该架构实现了更高程度的并行化,仅需在8块P100 GPU上训练12小时,就能达到翻译质量的新最优水平。
2 Background 背景
The goal of reducing sequential computation also forms the foundation of the Extended Neural GPU 13, ByteNet 14 and ConvS2S 15, 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 16. 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.
减少序列计算的目标也是扩展神经GPU13、ByteNet14和ConvS2S15的基础,它们都使用卷积神经网络作为基本构建块,并行计算所有输入和输出位置的隐藏表示。在这些模型中,关联两个任意输入或输出位置信号所需的操作次数随着位置间距离的增加而增长——ConvS2S呈线性增长,ByteNet呈对数增长。这使得学习远距离位置之间的依赖关系变得更加困难16。在Transformer中,这一操作次数被减少为常数量级,尽管代价是由于对注意力加权位置进行平均而导致有效分辨率降低,我们通过第3.2节描述的多头注意力机制来抵消这种影响。
Self-attention, sometimes called intra-attention is an attention mechanism relating different positions of a single sequence in order to compute a representation of the sequence. Self-attention has been used successfully in a variety of tasks including reading comprehension, abstractive summarization, textual entailment and learning task-independent sentence representations 17, 12, 18, 19.
自注意力(有时称为内部注意力)是一种注意力机制,它关联单个序列的不同位置以计算该序列的表征。自注意力已在多种任务中成功应用,包括阅读理解、抽象摘要、文本蕴含以及学习任务无关的句子表征17, 12, 18, 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 20.
端到端记忆网络基于循环注意力机制,而非序列对齐的循环结构,已被证明在简单语言问答和语言建模任务中表现良好20。
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 21, 14 and 15.
然而,据我们所知,Transformer是第一个完全依赖自注意力机制来计算输入和输出表征的转换模型,无需使用序列对齐的循环神经网络(RNN)或卷积结构。在接下来的章节中,我们将描述Transformer架构,阐释自注意力的原理,并讨论其相对于21、14和15等模型的优势。
3 Model Architecture 模型架构
Most competitive neural sequence transduction models have an encoder-decoder structure 5, 4 , 3. Here, the encoder maps an input sequence of symbol representations
(
x
1
,
.
.
.
,
x
n
)
(x_1, ..., x_n)
(x1,...,xn) to a sequence of continuous representations
z
=
(
z
1
,
.
.
.
,
z
n
)
z = (z_1, ..., z_n)
z=(z1,...,zn). Given
z
z
z, the decoder then generates an output sequence
(
y
1
,
.
.
.
,
y
m
)
(y_1, ..., y_m)
(y1,...,ym) of symbols one element at a time. At each step the model is auto-regressive 22, 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, 4, 3。编码器将符号表征的输入序列
(
x
1
,
.
.
.
,
x
n
)
(x_1,...,x_n)
(x1,...,xn)映射为连续表征序列
z
=
(
z
1
,
.
.
.
,
z
n
)
z=(z_1,...,z_n)
z=(z1,...,zn)。解码器根据
z
z
z逐步生成符号输出序列
(
y
1
,
.
.
.
,
y
m
)
(y_1,...,y_m)
(y1,...,ym),每个步骤采用自回归机制22,生成下一个符号时将先前已生成的符号作为附加输入。如模型整体架构所示(图1左右两部分分别对应编码器和解码器),Transformer遵循这一设计范式,其编码器和解码器均由堆叠的自注意力层及逐点全连接层构成。
图1:Transformer模型架构
3.1 Encoder and Decoder Stacks 编码器和解码器堆栈
Encoder: The encoder is composed of a stack of
N
=
6
N = 6
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, positionwise fully connected feed-forward network. We employ a residual connection 23 around each of the two sub-layers, followed by layer normalization 24. That is, the output of each sub-layer is
L
a
y
e
r
N
o
r
m
(
x
+
S
u
b
l
a
y
e
r
(
x
)
)
LayerNorm(x + Sublayer(x))
LayerNorm(x+Sublayer(x)), where
S
u
b
l
a
y
e
r
(
x
)
Sublayer(x)
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
m
o
d
e
l
=
512
d_{model} = 512
dmodel=512.
编码器:编码器由
N
=
6
N = 6
N=6个完全相同的层堆叠而成。每层包含两个子层。第一子层是多头自注意力机制,第二子层是简单的位置全连接前馈网络。我们在每个子层周围采用残差连接23,随后进行层归一化24。即每个子层的输出为
L
a
y
e
r
N
o
r
m
(
x
+
S
u
b
l
a
y
e
r
(
x
)
)
LayerNorm(x + Sublayer(x))
LayerNorm(x+Sublayer(x)),其中
S
u
b
l
a
y
e
r
(
x
)
Sublayer(x)
Sublayer(x)是该子层实现的函数。为便于残差连接,模型中所有子层及嵌入层的输出维度均为
d
m
o
d
e
l
=
512
d_{model} = 512
dmodel=512。
Decoder: The decoder is also composed of a stack of
N
=
6
N = 6
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
i
i can depend only on the known outputs at positions less than
i
i
i.
解码器:解码器同样由
N
=
6
N=6
N=6个相同层堆叠而成。除编码器层中的两个子层外,解码器还插入了第三个子层,该子层对编码器堆栈的输出执行多头注意力机制。与编码器类似,我们在每个子层周围采用残差连接,并紧跟层归一化操作。同时修改了解码器堆栈中的自注意力子层,以防止当前位置关注到后续位置。这种掩码机制结合输出嵌入向右偏移一位的特性,确保位置
i
i
i的预测仅能依赖于小于
i
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.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
d
k
d_k
dk, and values of dimension
d
v
d_v
dv . We compute the dot products of the query with all keys, divide each by
d
k
\sqrt[]{d_k}
dk, and apply a softmax function to obtain the weights on the values.
我们将特别的注意力机制称为“缩放点积注意力”(图2)。输入由维度为
d
k
d_k
dk的查询和键,以及维度为
d
v
d_v
dv的值组成。我们计算查询与所有键的点积,将每个点积除以
d
k
\sqrt[]{d_k}
dk,然后应用softmax函数以获得值的权重。
图2:(左)缩放点积注意力机制。(右)多头注意力由多个并行运行的注意力层组成。
In practice, we compute the attention function on a set of queries simultaneously, packed together into a matrix
Q
Q
Q. The keys and values are also packed together into matrices
K
K
K and
V
V
V . We compute the matrix of outputs as:
在实践中,我们会同时计算一组查询的注意力函数,将它们打包成矩阵
Q
Q
Q。键和值也分别打包成矩阵
K
K
K和
V
V
V。我们按如下公式计算输出矩阵:
A
t
t
e
n
t
i
o
n
(
Q
,
K
,
V
)
=
s
o
f
t
m
a
x
(
Q
K
T
d
k
)
V
(1)
Attention(Q, K, V ) = softmax( \frac {QK^T} {\sqrt[]{d_k}})V \tag1
Attention(Q,K,V)=softmax(dkQKT)V(1)
The two most commonly used attention functions are additive attention 4, and dot-product (multiplicative) attention. Dot-product attention is identical to our algorithm, except for the scaling factor of
1
d
k
\frac {1} {\sqrt[]{d_k}}
dk1. Additive attention computes the compatibility function using a feed-forward network with a single hidden layer. While the two are similar in theoretical complexity, dot-product attention is much faster and more space-efficient in practice, since it can be implemented using highly optimized matrix multiplication code.
最常用的两种注意力函数是加性注意力4和点积(乘法)注意力。点积注意力与我们的算法相同,除了
1
d
k
\frac{1}{\sqrt{d_k}}
dk1的缩放因子外。加性注意力使用具有单个隐藏层的前馈网络计算兼容性函数。虽然两者在理论复杂度上相似,但在实践中点积注意力速度更快且空间效率更高,因为它可以使用高度优化的矩阵乘法代码实现。
While for small values of dk the two mechanisms perform similarly, additive attention outperforms dot product attention without scaling for larger values of
d
k
d_k
dk 25. We suspect that for large values of
d
k
d_k
dk, the dot products grow large in magnitude, pushing the softmax function into regions where it has extremely small gradients (To illustrate why the dot products get large, assume that the components of
q
q
q and
k
k
k are independent random variables with mean
0
0
0 and variance
1
1
1. Then their dot product,
q
⋅
k
=
∑
i
=
1
d
k
q
i
k
i
q · k = ∑^{d_k}_{i=1} q_ik_i
q⋅k=∑i=1dkqiki, has mean
0
0
0 and variance
d
k
dk
dk .). To counteract this effect, we scale the dot products by
1
d
k
\frac{1}{\sqrt{d_k}}
dk1.
当
d
k
d_k
dk值较小时,两种机制表现相近;但对于较大的
d
k
d_k
dk值,加性注意力机制的表现在未经缩放的情况下优于点积注意力机制25。我们认为当
d
k
d_k
dk值较大时,点积结果的绝对值会显著增大,从而将softmax函数推入梯度极小的区域(为了说明点积变大的原因,假设
q
q
q 和
k
k
k 的分量是均值为
0
0
0、方差为
1
1
1 的独立随机变量。那么它们的点积
q
⋅
k
=
∑
i
=
1
d
k
q
i
k
i
q · k = \sum ^{d_k}_{i=1} q_ik_i
q⋅k=∑i=1dkqiki 的均值为 0,方差为
d
k
d_k
dk)。为了抵消这种效应,我们将点积结果缩放
1
d
k
\frac{1}{\sqrt{d_k}}
dk1倍。
3.2.2 Multi-Head Attention 多头注意力机制
Instead of performing a single attention function with
d
m
o
d
e
l
d_{model}
dmodel-dimensional keys, values and queries, we found it beneficial to linearly project the queries, keys and values
h
h
h times with different, learned linear projections to
d
k
d_k
dk,
d
k
d_k
dk and
d
v
d_v
dv dimensions, respectively. On each of these projected versions of queries, keys and values we then perform the attention function in parallel, yielding
d
v
d_v
dv-dimensional output values. These are concatenated and once again projected, resulting in the final values, as depicted in Figure 2.
我们没有使用单一的
d
m
o
d
e
l
d_{model}
dmodel维键、值和查询进行注意力计算,而是发现将查询、键和值分别进行
h
h
h次不同且可学习的线性投影到
d
k
d_k
dk、
d
k
d_k
dk和
d
v
d_v
dv维度更为有效。在每个投影版本的查询、键和值上并行执行注意力计算后,会得到
d
v
d_v
dv维的输出值。这些输出值被拼接后再进行一次投影,最终生成如图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.
多头注意力机制使模型能够同时关注来自不同位置的不同表征子空间的信息。而单一注意力头则因平均化抑制了这一特性。
M
u
l
t
i
H
e
a
d
(
Q
,
K
,
V
)
=
C
o
n
c
a
t
(
h
e
a
d
1
,
.
.
.
,
h
e
a
d
h
)
W
O
w
h
e
r
e
h
e
a
d
i
=
A
t
t
e
n
t
i
o
n
(
Q
W
i
Q
,
K
W
i
K
,
V
W
i
V
)
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 )
MultiHead(Q,K,V)=Concat(head1,...,headh)WOwhereheadi=Attention(QWiQ,KWiK,VWiV)
Where the projections are parameter matrices
W
i
Q
∈
R
d
m
o
d
e
l
×
d
k
,
W
i
K
∈
R
d
m
o
d
e
l
×
d
k
,
W
i
V
∈
R
d
m
o
d
e
l
×
d
v
W ^Q _i ∈ \mathbb{R}^{d_{model}×d_k}, {\,} {\,} W^K_i ∈ \mathbb{R}^{d_{model}×d_k} ,{\,} {\,} W^V_i ∈ \mathbb{R}^{d_{model}×d_v}
WiQ∈Rdmodel×dk,WiK∈Rdmodel×dk,WiV∈Rdmodel×dv and
W
O
∈
R
h
d
v
×
d
m
o
d
e
l
W^O ∈ \mathbb{R}^{hd_v ×d_{model}}
WO∈Rhdv×dmodel .
其中投影参数矩阵为
W
i
Q
∈
R
d
m
o
d
e
l
×
d
k
,
W
i
K
∈
R
d
m
o
d
e
l
×
d
k
,
W
i
V
∈
R
d
m
o
d
e
l
×
d
v
W ^Q_ i ∈ \mathbb{R}^{d_{model}×d_k}, {\,} {\,} W^K_i ∈ \mathbb{R}^{d_{model}×d_k} ,{\,} {\,} W^V_i ∈ \mathbb{R}^{d_{model}×d_v}
WiQ∈Rdmodel×dk,WiK∈Rdmodel×dk,WiV∈Rdmodel×dv 以及
W
O
∈
R
h
d
v
×
d
m
o
d
e
l
W^O ∈ \mathbb{R}^{hd_v ×d_{model}}
WO∈Rhdv×dmodel 。
In this work we employ
h
=
8
h = 8
h=8 parallel attention layers, or heads. For each of these we use
d
k
=
d
v
=
d
m
o
d
e
l
/
h
=
64
d_k = d_v = d_{model}/h = 64
dk=dv=dmodel/h=64. Due to the reduced dimension of each head, the total computational cost is similar to that of single-head attention with full dimensionality.
在这项工作中,我们使用了
h
=
8
h=8
h=8个平行的注意力层(或称头)。每个头的维度设置为
d
k
=
d
v
=
d
m
o
d
e
l
/
h
=
64
d_k=d_v=d_{model}/h=64
dk=dv=dmodel/h=64。由于每个头的维度降低,其总体计算成本与全维度的单头注意力机制相当。
3.2.3 Applications of Attention in our Model 注意力机制在我们模型中的应用
The Transformer uses multi-head attention in three different ways:
Transformer在三个方面使用了多头注意力机制:
-
In “encoder-decoder attention” layers, the queries come from the previous decoder layer, and the memory keys and values come from the output of the encoder. This allows every position in the decoder to attend over all positions in the input sequence. This mimics the typical encoder-decoder attention mechanisms in sequence-to-sequence models such as 6, 4, 15.
在“编码器-解码器注意力”层中,查询来自前一个解码器层,而记忆键和值则来自编码器的输出。这使得解码器中的每个位置都能关注输入序列的所有位置。这种现象模仿了序列到序列模型中典型的编码器-解码器注意力机制,例如6, 4, 15。 -
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.
同样,解码器中的自注意力层允许解码器的每个位置关注解码器中所有位置,直至并包括该位置。为避免破坏自回归特性,我们需要阻止解码器中的信息向左流动。为此,在缩放点积注意力机制中,我们对 softmax 输入中所有对应非法连接的值进行掩码处理(将其设置为 − ∞ −∞ −∞)。见图2。
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.
除了注意力子层外,我们的编码器和解码器中的每一层都包含一个全连接前馈网络,该网络分别且相同地应用于每个位置。它由两个线性变换组成,中间通过一个ReLU激活函数相连。
F F N ( x ) = m a x ( 0 , x W 1 + b 1 ) W 2 + b 2 (2) FFN(x) = max(0, {\,} {\,} xW_1 + b_1)W_2 + b_2 \tag2 FFN(x)=max(0,xW1+b1)W2+b2(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
1
1. The dimensionality of input and output is
d
m
o
d
e
l
=
512
d_{model} = 512
dmodel=512, and the inner-layer has dimensionality
d
f
f
=
2048
d_{f f} = 2048
dff=2048.
虽然线性变换在不同位置上是相同的,但它们在不同层之间使用不同的参数。另一种描述方式是将其视为两个卷积核大小为
1
1
1的卷积操作。输入和输出的维度为
d
m
o
d
e
l
=
512
d_{model} = 512
dmodel=512,而内部层的维度为
d
f
f
=
2048
d_{ff} = 2048
dff=2048。
3.4 Embeddings and Softmax 嵌入和Softmax
Similarly to other sequence transduction models, we use learned embeddings to convert the input tokens and output tokens to vectors of dimension
d
m
o
d
e
l
d_{model}
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, similar to 26. In the embedding layers, we multiply those weights by
d
m
o
d
e
l
\sqrt{d_{model}}
dmodel.
与其他序列转导模型类似,我们使用学习到的嵌入向量将输入标记和输出标记转换为维度为
d
m
o
d
e
l
d_{model}
dmodel的向量。我们还采用常规的学习线性变换和softmax函数,将解码器输出转换为预测的下一个标记概率。在我们的模型中,两个嵌入层与softmax前的线性变换共享相同的权重矩阵,类似于26的做法。在嵌入层中,我们将这些权重乘以
d
m
o
d
e
l
\sqrt{d_{model}}
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
d
m
o
d
e
l
d_{model}
dmodel as the embeddings, so that the two can be summed. There are many choices of positional encodings, learned and fixed 15.
由于我们的模型不包含循环和卷积结构,为了使其能够利用序列的顺序信息,必须注入关于词元在序列中相对或绝对位置的信息。为此,我们在编码器和解码器堆栈底部的输入嵌入中添加了"位置编码"。位置编码的维度
d
m
o
d
e
l
d_{model}
dmodel与嵌入维度相同,因此二者可以相加。位置编码有多种选择方案,既可以是可学习的也可以是固定的15。
In this work, we use sine and cosine functions of different frequencies:
在这项工作中,我们使用不同频率的正弦和余弦函数:
P
E
(
p
o
s
,
2
i
)
=
s
i
n
(
p
o
s
/
1000
0
2
i
/
d
m
o
d
e
l
)
P
E
(
p
o
s
,
2
i
+
1
)
=
c
o
s
(
p
o
s
/
1000
0
2
i
/
d
m
o
d
e
l
)
P {\,} E(pos, {\,} 2i) = sin(pos/10000^{2i/d_{model}} ) \\ P {\,} E(pos, {\,} 2i+1) = cos(pos/10000^{2i/d_{model}} )
PE(pos,2i)=sin(pos/100002i/dmodel)PE(pos,2i+1)=cos(pos/100002i/dmodel)
where
p
o
s
pos
pos is the position and
i
i
i is the dimension. That is, each dimension of the positional encoding corresponds to a sinusoid. The wavelengths form a geometric progression from
2
π
2π
2π to
10000
⋅
2
π
10000 · 2π
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
k
k,
P
E
p
o
s
+
k
P {\,} E_{pos+k}
PEpos+k can be represented as a linear function of
P
E
p
o
s
P {\,} E_{pos}
PEpos.
其中
p
o
s
pos
pos表示位置,
i
i
i表示维度。也就是说,位置编码的每个维度都对应一个正弦曲线。波长从
2
π
2π
2π到
10000
⋅
2
π
10000·2π
10000⋅2π呈几何级数排列。我们选择这个函数是因为我们假设它能帮助模型轻松学习通过相对位置进行注意力计算,因为对于任何固定偏移量
k
k
k,
P
E
p
o
s
+
k
P{\,}E_{pos+k}
PEpos+k都可以表示为
P
E
p
o
s
P{\,}E_{pos}
PEpos的线性函数。
We also experimented with using learned positional embeddings 15 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.
我们还尝试使用学习得到的位置嵌入15替代方案,发现两种版本产生的结果几乎相同(见表3行(E))。我们最终选择正弦曲线版本,因为这种方案可能让模型外推到比训练时更长的序列长度。
4 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
)
(x_1, ..., x_n)
(x1,...,xn) to another sequence of equal length
(
z
1
,
.
.
.
,
z
n
)
(z_1, ..., z_n)
(z1,...,zn), with
x
i
,
z
i
∈
R
d
x_i, z_i ∈ \mathbb{R}^d
xi,zi∈Rd, such as a hidden layer in a typical sequence transduction encoder or decoder. Motivating our use of self-attention we consider three desiderata.
本节我们将自注意力层与常用于将一个变长符号表示序列
(
x
1
,
.
.
.
,
x
n
)
(x_1,...,x_n)
(x1,...,xn)映射到另一个等长序列
(
z
1
,
.
.
.
,
z
n
)
(z_1,...,z_n)
(z1,...,zn)(其中
x
i
,
z
i
∈
R
d
x_i,z_i∈\mathbb{R}^d
xi,zi∈Rd)的循环层和卷积层进行多维度比较,例如典型序列转导模型编码器或解码器中的隐藏层。为阐明采用自注意力的动机,我们主要考量三个关键因素。
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 16. Hence we also compare the maximum path length between any two input and output positions in networks composed of the different layer types.
第三点是网络中远距离依赖之间的路径长度。学习远距离依赖是许多序列转导任务中的关键挑战。影响学习此类依赖能力的一个关键因素是网络中前向和后向信号必须穿越的路径长度。输入和输出序列中任意位置组合之间的路径越短,学习远距离依赖就越容易16。因此,我们还比较了由不同层类型组成的网络中任意两个输入和输出位置之间的最大路径长度。
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
)
O(n)
O(n) sequential operations. In terms of computational complexity, self-attention layers are faster than recurrent layers when the sequence length
n
n
n is smaller than the representation dimensionality
d
d
d, which is most often the case with sentence representations used by state-of-the-art models in machine translations, such as word-piece 6 and byte-pair 27 representations. To improve computational performance for tasks involving very long sequences, self-attention could be restricted to considering only a neighborhood of size
r
r
r in the input sequence centered around the respective output position. This would increase the maximum path length to
O
(
n
/
r
)
O(n/r)
O(n/r). We plan to investigate this approach further in future work.
如表1所示,自注意力层以恒定次数的顺序执行操作连接所有位置,而循环层需要
O
(
n
)
O(n)
O(n)次顺序操作。在计算复杂度方面,当序列长度
n
n
n小于表征维度
d
d
d时(这正是机器翻译领域前沿模型常用的词片6和字节对27表征的典型情况),自注意力层比循环层速度更快。对于涉及超长序列的任务,可通过限制自注意力机制仅考虑输入序列中以各输出位置为中心、大小为
r
r
r的邻域来提升计算性能,这将使最大路径长度增至
O
(
n
/
r
)
O(n/r)
O(n/r)。我们计划在未来工作中进一步探索该方法。
A single convolutional layer with kernel width
k
<
n
k < n
k<n does not connect all pairs of input and output positions. Doing so requires a stack of
O
(
n
/
k
)
O(n/k)
O(n/k) convolutional layers in the case of contiguous kernels, or
O
(
l
o
g
k
(
n
)
)
O(log_k(n))
O(logk(n)) in the case of dilated convolutions 14, 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
k
k. Separable convolutions 28, however, decrease the complexity considerably, to
O
(
k
⋅
n
⋅
d
+
n
⋅
d
2
)
O(k · n · d + n · d^2)
O(k⋅n⋅d+n⋅d2). Even with
k
=
n
k = n
k=n, however, the complexity of a separable convolution is equal to the combination of a self-attention layer and a point-wise feed-forward layer, the approach we take in our model.
一个核宽度为
k
<
n
k < n
k<n的单一卷积层并不能连接所有输入和输出位置的对应关系。在连续核的情况下需要堆叠
O
(
n
/
k
)
O(n/k)
O(n/k)个卷积层,而在空洞卷积14情况下则需要
O
(
l
o
g
k
(
n
)
)
O(log_k(n))
O(logk(n))层,这会增加网络中任意两个位置之间最长路径的长度。卷积层的计算成本通常比循环层高出
k
k
k倍。然而可分离卷积28显著降低了复杂度至
O
(
k
⋅
n
⋅
d
+
n
⋅
d
2
)
O(k · n · d + n · d^2)
O(k⋅n⋅d+n⋅d2)。即使当
k
=
n
k = n
k=n时,可分离卷积的复杂度也仅相当于自注意力层与点向前馈层的组合——这正是我们模型所采用的方法。
As side benefit, self-attention could yield more interpretable models. We inspect attention distributions from our models and present and discuss examples in the appendix. Not only do individual attention heads clearly learn to perform different tasks, many appear to exhibit behavior related to the syntactic and semantic structure of the sentences.
附带的好处是,自注意力机制可以产生更具可解释性的模型。我们检查了模型中注意力分布的情况,并在附录中展示并讨论了一些示例。不仅单个注意力头明显学会了执行不同的任务,许多注意力头还表现出与句子的句法和语义结构相关的行为。
5 Training 训练
This section describes the training regime for our models. 本节介绍我们模型的训练方案。
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 25, 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 6. 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万句对。句子采用字节对编码25进行处理,共享的源-目标词汇表约含37000个词元。对于英法翻译,我们采用了规模更大的WMT 2014英法数据集,包含3600万句对,并将词元划分为32000个词片段的词汇表6。句对按近似序列长度分组批处理,每个训练批次包含一组句对,其中源语言和目标语言词元数量各约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).
我们在配备8块NVIDIA P100显卡的单一机器上训练模型。对于采用本文所述超参数的基准模型,每个训练步骤耗时约0.4秒。基准模型共训练了10万步,合计12小时。而大型模型(对应表3最后一行所述配置)每个训练步骤耗时1秒,该模型共训练了30万步(耗时3.5天)。
5.3 Optimizer 优化器
We used the Adam optimizer 29 with
β
1
=
0.9
β_1 = 0.9
β1=0.9,
β
2
=
0.98
β_2 = 0.98
β2=0.98 and
ε
=
1
0
−
9
ε = 10^{−9}
ε=10−9. We varied the learning rate over the course of training, according to the formula:
我们使用了Adam优化器29,参数设置为
β
1
=
0.9
β_1 = 0.9
β1=0.9、
β
2
=
0.98
β_2 = 0.98
β2=0.98和
ε
=
1
0
−
9
ε = 10^{−9}
ε=10−9。在训练过程中,我们根据以下公式动态调整学习率:
l
r
a
t
e
=
d
m
o
d
e
l
−
0.5
⋅
m
i
n
(
s
t
e
p
_
n
u
m
−
0.5
,
s
t
e
p
_
n
u
m
⋅
w
a
r
m
u
p
_
s
t
e
p
s
−
1.5
)
(3)
lrate = d^{−0.5}_{model} · min(step\_num^{−0.5}, {\,} step\_num · warmup\_steps^{−1.5}) \tag3
lrate=dmodel−0.5⋅min(step_num−0.5,step_num⋅warmup_steps−1.5)(3)
This corresponds to increasing the learning rate linearly for the first
w
a
r
m
u
p
_
s
t
e
p
s
warmup\_steps
warmup_steps training steps, and decreasing it thereafter proportionally to the inverse square root of the step number. We used
w
a
r
m
u
p
_
s
t
e
p
s
=
4000
warmup\_steps = 4000
warmup_steps=4000.
这对应于在前
w
a
r
m
u
p
_
s
t
e
p
s
warmup\_steps
warmup_steps训练步数中线性增加学习率,之后按步数的平方根倒数比例递减学习率。我们设定
w
a
r
m
u
p
_
s
t
e
p
s
=
4000
warmup\_steps = 4000
warmup_steps=4000。
5.4 Regularization 正则化
We employ three types of regularization during training:
我们在训练过程中采用了三种正则化方法:
Residual Dropout We apply dropout 30 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
d
r
o
p
=
0.1
P_{drop} = 0.1
Pdrop=0.1.
残差丢弃 我们在每个子层的输出上应用丢弃30,然后将其添加到子层输入并进行归一化。此外,我们还对编码器和解码器堆栈中的嵌入向量与位置编码之和应用丢弃。对于基础模型,我们使用丢弃率
P
d
r
o
p
=
0.1
P_{drop} = 0.1
Pdrop=0.1。
Label Smoothing During training, we employed label smoothing of value
ε
l
s
=
0.1
ε_{ls} = 0.1
εls=0.1 31. This hurts perplexity, as the model learns to be more unsure, but improves accuracy and BLEU score.
标签平滑 在训练过程中,我们采用了值为
ε
l
s
=
0.1
ε_{ls} = 0.1
εls=0.1 的标签平滑技术31。虽然这会降低模型的困惑度(因为模型学会了更不确定的预测),但提高了准确率和BLEU得分。
表2:Transformer模型在英德和英法newstest2014测试中,以更低的训练成本获得了比之前最先进模型更高的BLEU分数。
6 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.0BLEU, establishing a new state-of-the-art BLEU score of
28.4
28.4
28.4. The configuration of this model is listed in the bottom line of Table 3. Training took
3.5
3.5
3.5 days on
8
8
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.
在2014年WMT英德翻译任务中,大型Transformer模型(表2中的Transformer(big))以超过2.0BLEU的优势击败了之前所有最佳报告模型(包括集成模型),创造了28.4分的最新BLEU纪录。该模型配置详见表3末行,使用8块P100显卡训练耗时3.5天。即便我们的基础模型也超越了所有已发表模型和集成系统,而训练成本仅为任何竞争模型的一小部分。
On the WMT 2014 English-to-French translation task, our big model achieves a BLEU score of
41.0
41.0
41.0, outperforming all of the previously published single models, at less than
1
/
4
1/4
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
d
r
o
p
=
0.1
P_{drop} = 0.1
Pdrop=0.1, instead of
0.3
0.3
0.3.
在WMT 2014英法翻译任务中,我们的大模型以低于之前最先进模型
1
/
4
1/4
1/4的训练成本,取得了
41.0
41.0
41.0的BLEU分数,超越了所有先前发布的单一模型性能。针对英法翻译任务训练的Transformer(大)模型采用了丢弃率
P
d
r
o
p
=
0.1
P_{drop} = 0.1
Pdrop=0.1,而非
0.3
0.3
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
4
4 and length penalty
α
=
0.6
α = 0.6
α=0.6 6. These hyperparameters were chosen after experimentation on the development set. We set the maximum output length during inference to input length
+
50
+ 50
+50, but terminate early when possible 6.
对于基础模型,我们采用最后5个检查点的平均值(这些检查点每10分钟保存一次)。对于大型模型,我们平均了最后20个检查点。我们使用束搜索算法,束宽度设为
4
4
4,长度惩罚系数
α
=
0.6
α=0.6
α=0.66。这些超参数是通过在开发集上实验确定的。在推理过程中,我们将最大输出长度设置为输入长度
+
50
+50
+50,但会尽可能提前终止生成6。
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. (We used values of 2.8, 3.7, 6.0 and 9.5 TFLOPS for K80, K40, M40 and P100, respectively.)
表2总结了我们的结果,并将我们的翻译质量和训练成本与文献中的其他模型架构进行了比较。我们通过将训练时间、使用的GPU数量以及每块GPU持续单精度浮点运算能力的估算值相乘,来估计训练模型所需的浮点运算次数。(我们分别采用2.8、3.7、6.0和9.5 TFLOPS作为K80、K40、M40和P100的估算值。)
表3:Transformer架构的变体。未列出的值与基础模型相同。所有指标均基于英语到德语翻译开发集newstest2013。列出的困惑度是每个词片段的(根据我们的字节对编码计算),不应与每个单词的困惑度进行比较。
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.
为了评估Transformer中不同组件的重要性,我们以多种方式调整基础模型,测量在开发集newstest2013上英德翻译任务的性能变化。我们采用前文所述的束搜索方法,但未使用检查点平均技术。实验结果如表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.
在表3的(A)行中,我们按照第3.2.2节所述,保持计算量不变,调整注意力头数量以及注意力键和值的维度。当使用单头注意力机制时,其效果比最优设置低0.9个BLEU值;而注意力头数量过多时,翻译质量也会下降。
In Table 3 rows (B), we observe that reducing the attention key size
d
k
d_k
dk hurts model quality. This suggests that determining compatibility is not easy and that a more sophisticated compatibility function than dot product may be beneficial. We further observe in rows © and (D) that, as expected, bigger models are better, and dropout is very helpful in avoiding over-fitting. In row (E) we replace our sinusoidal positional encoding with learned positional embeddings 15, and observe nearly identical results to the base model.
在表3的(B)行中,我们观察到减小注意力键尺寸
d
k
d_k
dk会损害模型质量。这表明确定兼容性并不容易,使用比点积更复杂的兼容性函数可能更有益处。我们在( C)和(D)行进一步观察到,正如预期的那样,更大的模型表现更好,而dropout对于避免过拟合非常有帮助。在(E)行中,我们将正弦位置编码替换为可学习的位置嵌入15,结果与基础模型几乎相同。
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 32.
为了评估Transformer模型是否能推广到其他任务,我们在英语成分句法分析上进行了实验。该任务面临特定挑战:输出受到严格结构约束且明显长于输入。此外,在数据量较小的情况下,RNN序列到序列模型尚未取得最先进的成果32。
We trained a 4-layer transformer with
d
m
o
d
e
l
=
1024
d_{model} = 1024
dmodel=1024 on the Wall Street Journal (WSJ) portion of the Penn Treebank 33, 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 32. We used a vocabulary of 16K tokens for the WSJ only setting and a vocabulary of 32K tokens for the semi-supervised setting.
我们在宾州树库33的华尔街日报(WSJ)语料部分(约4万条训练句子)上训练了一个4层Transformer模型(
d
m
o
d
e
l
=
1024
d_{model} = 1024
dmodel=1024)。同时采用半监督学习方式,使用了约1700万条句子的高置信度伯克利Parser语料库32进行训练。纯WSJ训练场景使用16K词表,半监督场景则使用32K词表。
We performed only a small number of experiments to select the dropout, both attention and residual (section 5.4), learning rates and beam size on the Section 22 development set, all other parameters remained unchanged from the English-to-German base translation model. During inference, we increased the maximum output length to input length
+
300
+ 300
+300. We used a beam size of
21
21
21 and
α
=
0.3
α = 0.3
α=0.3 for both WSJ only and the semi-supervised setting.
我们仅进行了少量实验来选择dropout(包括注意力机制和残差连接部分,见第5.4节)、学习率以及集束搜索大小,这些实验都是在第22节开发集上完成的,其余参数均保持与英德基础翻译模型一致。在推理阶段,我们将最大输出长度调整为输入长度
+
300
+300
+300。无论是纯WSJ数据还是半监督学习场景,均采用集束宽度
21
21
21和长度惩罚系数
α
=
0.3
α=0.3
α=0.3的配置。
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 34.
表4中的结果显示,尽管缺乏针对特定任务的调优,我们的模型表现却出人意料地出色——除递归神经网络语法模型34外,其效果优于所有先前报道的模型。
In contrast to RNN sequence-to-sequence models 32, the Transformer outperforms the BerkeleyParser 35 even when training only on the WSJ training set of 40K sentences.
与RNN序列到序列模型32相比,Transformer即使在仅使用4万句WSJ训练集进行训练的情况下,其表现也优于BerkeleyParser36。
表4:Transformer模型在英语成分句法分析中表现出良好的泛化能力(结果基于WSJ语料库第23节)
7 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.
在这项工作中,我们提出了Transformer模型——首个完全基于注意力机制的序列转换模型,它用多头自注意力机制取代了编码器-解码器架构中最常用的循环层。
For translation tasks, the Transformer can be trained significantly faster than architectures based on recurrent or convolutional layers. On both WMT 2014 English-to-German and WMT 2014 English-to-French translation tasks, we achieve a new state of the art. In the former task our best model outperforms even all previously reported ensembles.
在翻译任务中,Transformer模型的训练速度显著快于基于循环或卷积层的架构。在WMT 2014英德翻译和WMT 2014英法翻译任务中,我们都取得了最先进的结果。在前一项任务中,我们表现最佳的模型甚至超越了之前所有已报告的集成模型。
We are excited about the future of attention-based models and plan to apply them to other tasks. We plan to extend the Transformer to problems involving input and output modalities other than text and to investigate local, restricted attention mechanisms to efficiently handle large inputs and outputs such as images, audio and video. Making generation less sequential is another research goals of ours. The code we used to train and evaluate our models is available at https://github.com/ tensorflow/tensor2tensor.
我们对基于注意力机制模型的未来充满期待,并计划将其应用于其他任务。我们打算将Transformer架构扩展到涉及非文本输入输出模态的问题中,同时研究局部受限注意力机制,以高效处理图像、音频和视频等大型输入输出数据。另一个研究目标是减少生成过程的序列化依赖。用于模型训练和评估的代码已开源在https://github.com/tensorflow/tensor2tensor。
Acknowledgements We are grateful to Nal Kalchbrenner and Stephan Gouws for their fruitful comments, corrections and inspiration.
致谢 我们感谢Nal Kalchbrenner和Stephan Gouws富有成效的评论、修改和启发。
Attention Visualizations 注意力可视化
图3:编码器自注意力机制在第5层(共6层)中遵循长距离依赖关系的示例。多个注意力头聚焦于动词"making"的远距离依赖,完成了短语"making…more difficult"。图中仅展示了单词"making"的注意力分布。不同颜色代表不同的注意力头。建议彩色查看效果最佳。
图4:同样位于6层网络中的第5层的两个注意力头,显然参与了指代消解任务。上图:第5号注意力头的完整注意力分布。下图:仅针对单词"its"在第5和第6号注意力头上的独立注意力分布。值得注意的是,该单词的注意力分布非常集中。
图5:许多注意力头展现出与句子结构相关的行为模式。上图展示了两个典型案例,均来自第5层(共6层)编码器自注意力机制中的不同注意力头。这些注意力头显然已习得执行不同任务的能力。
References 参考
Sepp Hochreiter and Jürgen Schmidhuber. Long short-term memory. Neural computation, 9(8):1735–1780, 1997. ↩︎ ↩︎
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. ↩︎ ↩︎
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. ↩︎ ↩︎ ↩︎ ↩︎
Dzmitry Bahdanau, Kyunghyun Cho, and Yoshua Bengio. Neural machine translation by jointly learning to align and translate. CoRR, abs/1409.0473, 2014. ↩︎ ↩︎ ↩︎ ↩︎ ↩︎ ↩︎ ↩︎ ↩︎ ↩︎ ↩︎
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. ↩︎ ↩︎ ↩︎ ↩︎
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. ↩︎ ↩︎ ↩︎ ↩︎ ↩︎ ↩︎ ↩︎ ↩︎ ↩︎ ↩︎ ↩︎ ↩︎
Minh-Thang Luong, Hieu Pham, and Christopher D Manning. Effective approaches to attentionbased neural machine translation. arXiv preprint arXiv:1508.04025, 2015. ↩︎ ↩︎
Rafal Jozefowicz, Oriol Vinyals, Mike Schuster, Noam Shazeer, and Yonghui Wu. Exploring the limits of language modeling. arXiv preprint arXiv:1602.02410, 2016. ↩︎ ↩︎
Oleksii Kuchaiev and Boris Ginsburg. Factorization tricks for LSTM networks. arXiv preprint arXiv:1703.10722, 2017. ↩︎ ↩︎
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. ↩︎ ↩︎
Yoon Kim, Carl Denton, Luong Hoang, and Alexander M. Rush. Structured attention networks. In International Conference on Learning Representations, 2017. ↩︎ ↩︎
Ankur Parikh, Oscar Täckström, Dipanjan Das, and Jakob Uszkoreit. A decomposable attention model. In Empirical Methods in Natural Language Processing, 2016. ↩︎ ↩︎ ↩︎ ↩︎
Łukasz Kaiser and Samy Bengio. Can active memory replace attention? In Advances in Neural Information Processing Systems, (NIPS), 2016. ↩︎ ↩︎
Nal Kalchbrenner, Lasse Espeholt, Karen Simonyan, Aaron van den Oord, Alex Graves, and Koray Kavukcuoglu. Neural machine translation in linear time. arXiv preprint arXiv:1610.10099v2, 2017. ↩︎ ↩︎ ↩︎ ↩︎ ↩︎ ↩︎
Jonas Gehring, Michael Auli, David Grangier, Denis Yarats, and Yann N. Dauphin. Convolutional sequence to sequence learning. arXiv preprint arXiv:1705.03122v2, 2017. ↩︎ ↩︎ ↩︎ ↩︎ ↩︎ ↩︎ ↩︎ ↩︎ ↩︎ ↩︎ ↩︎ ↩︎
Sepp Hochreiter, Yoshua Bengio, Paolo Frasconi, and Jürgen Schmidhuber. Gradient flow in recurrent nets: the difficulty of learning long-term dependencies, 2001. ↩︎ ↩︎ ↩︎ ↩︎
Jianpeng Cheng, Li Dong, and Mirella Lapata. Long short-term memory-networks for machine reading. arXiv preprint arXiv:1601.06733, 2016. ↩︎ ↩︎
Romain Paulus, Caiming Xiong, and Richard Socher. A deep reinforced model for abstractive summarization. arXiv preprint arXiv:1705.04304, 2017. ↩︎ ↩︎
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. ↩︎ ↩︎
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. ↩︎ ↩︎
Łukasz Kaiser and Ilya Sutskever. Neural GPUs learn algorithms. In International Conference on Learning Representations (ICLR), 2016. ↩︎ ↩︎
Alex Graves. Generating sequences with recurrent neural networks. arXiv preprint arXiv:1308.0850, 2013. ↩︎ ↩︎
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. ↩︎ ↩︎
Jimmy Lei Ba, Jamie Ryan Kiros, and Geoffrey E Hinton. Layer normalization. arXiv preprint arXiv:1607.06450, 2016. ↩︎ ↩︎
Denny Britz, Anna Goldie, Minh-Thang Luong, and Quoc V. Le. Massive exploration of neural machine translation architectures. CoRR, abs/1703.03906, 2017. ↩︎ ↩︎ ↩︎ ↩︎
Ofir Press and Lior Wolf. Using the output embedding to improve language models. arXiv preprint arXiv:1608.05859, 2016. ↩︎ ↩︎
Rico Sennrich, Barry Haddow, and Alexandra Birch. Neural machine translation of rare words with subword units. arXiv preprint arXiv:1508.07909, 2015. ↩︎ ↩︎
Francois Chollet. Xception: Deep learning with depthwise separable convolutions. arXiv preprint arXiv:1610.02357, 2016. ↩︎ ↩︎
Diederik Kingma and Jimmy Ba. Adam: A method for stochastic optimization. In ICLR, 2015. ↩︎ ↩︎
Nitish Srivastava, Geoffrey E Hinton, Alex Krizhevsky, Ilya Sutskever, and Ruslan Salakhutdinov. Dropout: a simple way to prevent neural networks from overfitting. Journal of Machine Learning Research, 15(1):1929–1958, 2014. ↩︎ ↩︎
Christian Szegedy, Vincent Vanhoucke, Sergey Ioffe, Jonathon Shlens, and Zbigniew Wojna. Rethinking the inception architecture for computer vision. CoRR, abs/1512.00567, 2015. ↩︎ ↩︎
Vinyals & Kaiser, Koo, Petrov, Sutskever, and Hinton. Grammar as a foreign language. InAdvances in Neural Information Processing Systems, 2015. ↩︎ ↩︎ ↩︎ ↩︎ ↩︎ ↩︎
Mitchell P Marcus, Mary Ann Marcinkiewicz, and Beatrice Santorini. Building a large annotated corpus of english: The penn treebank. Computational linguistics, 19(2):313–330, 1993. ↩︎ ↩︎
Chris Dyer, Adhiguna Kuncoro, Miguel Ballesteros, and Noah A. Smith. Recurrent neural network grammars. In Proc. of NAACL, 2016. ↩︎ ↩︎
29 ↩︎
29 ↩︎