[论文翻译]注意力就是你所需要的 (Attention Is All You Need)


原文地址:https://u254848-88c6-e493554b.yza1.seetacloud.com:8443/miner/v2/analysis/pdf_md?filename=full.md&as_attachment=False&pdf=bdfaa68d8984f0dc02beaca527b76f207d99b666d31d1da728ee0728182df6971735798439_2405.21060v1.pdf


Attention Is All You Need

注意力就是你所需要的 (Attention Is All You Need)


Illia Polosukhin∗‡ illia.polosukhin@gmail.com

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 parallel iz able 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.

目前主流的序列转换模型基于复杂的递归神经网络 (Recurrent Neural Networks) 或卷积神经网络 (Convolutional Neural Networks),这些模型包含编码器和解码器。表现最好的模型还通过注意力机制 (attention mechanism) 将编码器和解码器连接起来。我们提出了一种新的简单网络架构,即 Transformer,该架构完全基于注意力机制,摒弃了递归和卷积。我们在两个机器翻译任务上的实验表明,这些模型在质量上更优,同时具有更高的并行性,并且训练时间显著减少。我们的模型在 WMT 2014 英德翻译任务中达到了 28.4 BLEU 分,比现有最佳结果(包括集成模型)提高了超过 2 BLEU 分。在 WMT 2014 英法翻译任务中,我们的模型在八个 GPU 上训练 3.5 天后,达到了 41.8 的单模型最新 BLEU 分数,这仅占文献中最佳模型训练成本的一小部分。我们通过将 Transformer 成功应用于英语句法分析任务(无论是大规模数据还是有限数据),证明了其在其他任务上的良好泛化能力。

1 Introduction

1 引言

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

递归神经网络,特别是长短期记忆 [13] 和门控递归 [7] 神经网络,已经在序列建模和转导问题(如语言模型和机器翻译 [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 parallel iz ation 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.

注意力机制 (Attention mechanisms) 已成为在各种任务中构建强大的序列建模和转导模型的重要组成部分,允许建模依赖关系而不考虑这些依赖关系在输入或输出序列中的距离 [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 parallel iz ation 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 训练仅 12 小时后,就能在翻译质量上达到新的最佳水平。

2 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 logarithmic ally 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.

减少顺序计算的目标也构成了 Extended Neural GPU [16]、ByteNet [18] 和 ConvS2S [9] 的基础,这些模型都使用卷积神经网络作为基本构建块,对所有输入和输出位置的隐藏表示进行并行计算。在这些模型中,关联两个任意输入或输出位置信号所需的运算次数会随着位置之间的距离增加而增加,对于 ConvS2S 是线性增长,对于 ByteNet 是对数增长。这使得学习远距离位置之间的依赖关系变得更加困难 [12]。在 Transformer 中,这一运算次数被减少为常数,尽管这是以降低有效分辨率(由于平均了注意力加权的位置)为代价的,我们通过多头注意力机制(Multi-Head Attention)来抵消这一影响,具体见第 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, abstract ive sum mari z ation, 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 sequencealigned 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 sequencealigned 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] 等模型的优势。

3 Model Architecture

3 模型架构 (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},...,x_{n})$ to a sequence of continuous representations $\mathbf{z};=;(z_{1},...,z_{n})$ . Given $\mathbf{z}$ , the decoder then generates an output sequence $\left(y_{1},...,y_{m}\right)$ 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},...,x_{n})$ 映射为连续表示序列 $\mathbf{z};=;(z_{1},...,z_{n})$。给定 $\mathbf{z}$,解码器随后逐个生成输出符号序列 $\left(y_{1},...,y_{m}\right)$。在每一步中,模型是自回归的 [10],即在生成下一个符号时,会将之前生成的符号作为附加输入。


Figure 1: The Transformer - model architecture.


图 1: Transformer - 模型架构。

请注意,图片链接可能无法直接显示,建议您通过复制链接在浏览器中查看。

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 的左半部分和右半部分所示。

图 1:

3.1 Encoder and Decoder Stacks

Encoder: The encoder is composed of a stack of $N,=,6$ identical layers. Each layer has two sub-layers. The first is a multi-head self-attention mechanism, and the second is a simple, positionwise 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+\mathrm{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_{\mathrm{model}}=512$ .

编码器 (Encoder): 编码器由 $N,=,6$ 个相同的层堆叠而成。每一层包含两个子层。第一个子层是多头自注意力机制 (multi-head self-attention),第二个子层是一个简单的、按位置全连接的前馈网络 (positionwise fully connected feed-forward network)。我们在每个子层周围使用残差连接 [11],并随后进行层归一化 [1]。也就是说,每个子层的输出为 LayerNorm $(x + \mathrm{Sublayer}(x))$,其中 Sublayer $(x)$ 是子层自身实现的功能。为了便于这些残差连接,模型中的所有子层以及嵌入层都产生维度为 $d_{\mathrm{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$ .

解码器 (Decoder):解码器也由 $N=6$ 个相同的层堆叠而成。除了每个编码器层中的两个子层外,解码器插入了一个第三子层,该子层对编码器堆栈的输出执行多头注意力 (multi-head attention)。与编码器类似,我们在每个子层周围使用残差连接 (residual connections),并随后进行层归一化 (layer normalization)。我们还修改了解码器堆栈中的自注意力 (self-attention) 子层,以防止某个位置关注后续位置。这种掩码机制,结合输出嵌入向右偏移一个位置的事实,确保了位置 $i$ 的预测只能依赖于位置小于 $i$ 的已知输出。

在解码器中,通过这种方式,模型能够确保在生成序列时,每个位置的输出只受之前位置的影响,从而保持了因果关系。

3.2 Attention

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

一个注意力函数可以被描述为将查询和一组键值对映射到输出,其中查询、键、值和输出都是向量。输出是通过加权和计算得到的。

Figure 2: (left) Scaled Dot-Product Attention. (right) Multi-Head Attention consists of several attention layers running in parallel.

图 2: (左) 缩放点积注意力机制 (Scaled Dot-Product Attention)。 (右) 多头注意力机制 (Multi-Head Attention) 由多个并行运行的注意力层组成。

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

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

我们特别关注的机制称为“Scaled Dot-Product Attention”(图 2)。输入包括维度为 $d_{k}$ 的查询和键,以及维度为 $d_{v}$ 的值。我们计算查询与所有键的点积,将每个点积除以 $\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$ 。我们按照以下方式计算输出矩阵:

$$
\text{输出} = \text{Attention}(Q, K, V)
$$

其中,$\text{Attention}(Q, K, V)$ 的具体计算公式为:

$$
\text{Attention}(Q, K, V) = \text{softmax}\left(\frac{QK^T}{\sqrt{d_k}}\right)V
$$

这里,$d_k$ 是键的维度。

$$
\mathrm{Attention}(Q,K,V)=\mathrm{softmax}(\frac{Q K^{T}}{\sqrt{d_{k}}})V
$$

该公式表示注意力机制 (Attention) 的计算过程,其中 ( Q ) 为查询矩阵,( K ) 为键矩阵,( V ) 为值矩阵,( d_k ) 为键的维度。注意力机制通过计算查询和键之间的相似度,加权求和值矩阵来生成输出。

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 $\textstyle{\frac{1}{\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] 和点积(乘法)注意力。点积注意力与我们的算法相同,只是有一个缩放因子 $\textstyle{\frac{1}{\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 $\textstyle{\frac{1}{\sqrt{d_{k}}}}$ .

当 $d_{k}$ 的值较小时,两种机制的表现相似;但对于较大的 $d_{k}$ 值,加性注意力机制优于未缩放的点积注意力机制 [3]。我们怀疑,对于较大的 $d_{k}$ 值,点积的绝对值会变得很大,使得 softmax 函数进入梯度极小的区域。为了抵消这种效应,我们将点积乘以 $\textstyle{\frac{1}{\sqrt{d_{k}}}}$。

3.2.2 Multi-Head Attention

3.2.2 多头注意力机制 (Multi-Head Attention)

Instead of performing a single attention function with $d_{\mathrm{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.

我们发现,与其使用单个注意力函数来处理 $d_{\mathrm{model}}$ 维的键、值和查询,不如将查询、键和值分别通过 $h$ 次不同的、可学习的线性投影映射到 $d_{k}$ 、 $d_{k}$ 和 $d_{v}$ 维。对于每次投影后的查询、键和值,我们并行地执行注意力函数,生成 $d_{v}$ 维的输出值。这些输出值被拼接在一起,并再次进行投影,得到最终的结果,如图 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.

多头注意力机制 (Multi-head attention) 允许模型在不同位置同时关注来自不同表示子空间的信息。如果只使用单个注意力头 (attention head),平均化会抑制这种能力。

$$
\begin{array}{r l}&{\mathrm{MultiHead}(Q,K,V)=\mathrm{Concat}(\mathrm{head}{1},...,\mathrm{head}{\mathrm{h}})W^{O}}\ &{\qquad\qquad\mathrm{where~head}_{\mathrm{i}}=\mathrm{Attention}(Q W_{i}^{Q},K W_{i}^{K},V W_{i}^{V})}\end{array}
$$

$$
\begin{array}{r l}
& \text{MultiHead}(Q, K, V) = \text{Concat}(\text{head}_1, ..., \text{head}_h) W^O \
& \qquad \qquad \text{其中 head}_i = \text{Attention}(Q W_i^Q, K W_i^K, V W_i^V)
\end{array}
$$

这段公式描述了多头注意力机制 (MultiHead Attention) 的计算过程。其中,QKV 分别表示查询 (Query)、键 (Key) 和值 (Value),W^O 是输出线性变换的权重矩阵,W_i^QW_i^KW_i^V 是第 i 个注意力头的线性变换权重矩阵。每个 head_i 都是通过注意力机制 (Attention) 计算得到的。

Where the projections are parameter matrices $W_{i}^{Q}\in\mathbb{R}^{d_{\mathrm{model}}\times d_{k}}$ , W iK∈Rdmodel×dk, W iV ∈Rdmodel×dv and $W^{O}\in\mathbb{R}^{h d_{v}\times d_{\mathrm{model}}}$ .

其中投影是由参数矩阵 $W_{i}^{Q} \in \mathbb{R}^{d_{\mathrm{model}} \times d_{k}}$ 、$W_{i}^{K} \in \mathbb{R}^{d_{\mathrm{model}} \times d_{k}}$ 和 $W_{i}^{V} \in \mathbb{R}^{d_{\mathrm{model}} \times d_{v}}$ 以及 $W^{O} \in \mathbb{R}^{h d_{v} \times d_{\mathrm{model}}}$ 来实现的。

这些矩阵分别用于计算查询 (Query)、键 (Key) 和值 (Value) 的线性变换,最后通过输出矩阵 $W^O$ 将多头注意力的结果映射回模型维度 $d_{\mathrm{model}}$。

In this work we employ $h\ =\ 8$ parallel attention layers, or heads. For each of these we use $d_{k}=d_{v}=d_{\mathrm{model}}/h\stackrel{\cdot}{=}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$ 个并行的注意力层,也称为头。对于每个头,我们使用 $d_{k}=d_{v}=d_{\mathrm{model}}/h\stackrel{\cdot}{=}64$ 。由于每个头的维度较低,因此总的计算成本与单头全维度注意力机制相似。

3.2.3 Applications of Attention in our Model

3.2.3 注意力机制在我们模型中的应用 (Applications of Attention in our Model)

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

Transformer 通过三种不同的方式使用多头注意力 (multi-head attention):

  1. 编码器-编码器注意力 (Encoder-Encoder Attention):在编码器层中,每个位置的 Token 可以关注输入序列中的所有其他 Token。这种方式使得模型能够捕捉输入序列中的长距离依赖关系。
  2. 解码器-解码器注意力 (Decoder-Decoder Attention):在解码器层中,每个位置的 Token 只能关注之前生成的 Token(包括当前位置),这被称为因果注意力 (causal attention),确保了解码过程的顺序性。
  3. 编码器-解码器注意力 (Encoder-Decoder Attention):在解码器层中,每个位置的 Token 可以关注整个编码器输出的表示。这种方式使得解码器能够在生成输出时参考完整的输入信息。

通过这三种注意力机制,Transformer 能够有效地处理序列数据,并在各种自然语言处理任务中取得优异的表现。

3.3 Position-wise Feed-Forward Networks

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.

除了注意力子层之外,我们编码器和解码器中的每一层还包含一个全连接的前馈网络 (fully connected feed-forward network),该网络分别且相同地应用于每个位置。这个网络由两个线性变换组成,在两者之间有一个 ReLU 激活函数。

$$
\mathrm{FFN}(x)=\operatorname*{max}(0,x W_{1}+b_{1})W_{2}+b_{2}
$$

前馈神经网络 (Feed-Forward Network, FFN) 的公式表示为:输入 ( x ) 通过线性变换 ( x W_{1} + b_{1} ) 后,应用ReLU激活函数(即取最大值操作),再经过第二次线性变换 ( 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_{\mathrm{model}},=,512$ , and the inner-layer has dimensionality $d_{f f}=2048$ .

虽然线性变换在不同的位置上是相同的,但每一层使用的参数不同。另一种描述方式是将其视为两个卷积,卷积核大小为 1。输入和输出的维度为 $d_{\mathrm{model}},=,512$ ,而中间层的维度为 $d_{f f}=2048$ 。

3.4 Embeddings and Softmax

Similarly to other sequence transduction models, we use learned embeddings to convert the input tokens and output tokens to vectors of dimension $d_{\mathrm{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_{\mathrm{model}}}$ .

与其它序列转换模型类似,我们使用学习到的嵌入 (embeddings) 将输入和输出的 Token 转换为维度为 $d_{\mathrm{model}}$ 的向量。我们还使用常见的学习线性变换和 softmax 函数将解码器的输出转换为预测的下一个 Token 的概率。在我们的模型中,我们在两个嵌入层和预 softmax 线性变换之间共享相同的权重矩阵,这与 [30] 类似。在嵌入层中,我们将这些权重乘以 $\sqrt{d_{\mathrm{model}}}$。

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.

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

层类型 每层复杂度 顺序操作次数 最大路径长度
自注意力 (Self-Attention) O(n²·d) O(1) O(1)
循环 (Recurrent) O(n·d²) O(n) O(n)
卷积 (Convolutional) O(k·n·d²) O(1) O(n)
受限自注意力 (Self-Attention (restricted)) O(r·n·d) O(1) O(n/r)

注意:表格中的公式和符号保持原样,未进行翻译。

3.5 Positional Encoding

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_{\mathrm{model}}$ as the embeddings, so that the two can be summed. There are many choices of positional encodings, learned and fixed [9].

由于我们的模型不包含递归和卷积,为了使模型能够利用序列的顺序信息,我们必须向模型注入关于序列中 Token 的相对或绝对位置的信息。为此,我们在编码器和解码器堆栈的底部将“位置编码”添加到输入嵌入中。位置编码的维度与嵌入的维度相同,均为 $d_{\mathrm{model}}$,因此两者可以相加。位置编码有多种选择,既可以是学习得到的,也可以是固定的 [9]。

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

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

$$
\begin{array}{r}{P E_{(pos,2i)}=sin(pos/10000^{2i/d_{\text{model}}})} \ {P E_{(pos,2i+1)}=cos(pos/10000^{2i/d_{\text{model}}})}\end{array}
$$

位置编码 (Positional Encoding) 的计算公式如下:

  • 对于偶数位置:$P E_{(pos,2i)} = sin(pos/10000^{2i/d_{\text{model}}})$
  • 对于奇数位置:$P E_{(pos,2i+1)} = cos(pos/10000^{2i/d_{\text{model}}})$

其中,$pos$ 表示位置,$d_{\text{model}}$ 表示模型的维度。位置编码用于为输入序列中的每个位置添加位置信息,以便模型能够区分不同位置的 Token。

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\cdot2\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$ , $P E_{p o s+k}$ can be represented as a linear function of PEpos.

其中 pos 是位置,$i$ 是维度。也就是说,每个位置编码的维度对应一个正弦波。波长从 $2\pi$ 到 $10000 \cdot 2\pi$ 形成几何级数。我们选择这个函数是因为我们假设它可以让模型更容易学习通过相对位置进行注意力机制,因为对于任何固定的偏移量 $k$,$PE_{pos+k}$ 可以表示为 $PE_{pos}$ 的线性函数。

在位置编码中,每个维度都由一个正弦函数(sinusoid)表示,波长按照几何级数递增。这种设计使得模型能够更好地捕捉序列中元素之间的相对位置关系,从而提高其对位置信息的理解能力。

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.

我们还尝试使用学习到的位置嵌入 (learned positional embeddings) [9],并发现这两种版本产生了几乎相同的结果(见表 3 第 (E) 行)。我们选择了正弦版本,因为它可能允许模型外推到比训练时遇到的序列长度更长的情况。

表 3:

模型版本 结果
(E) 正弦位置编码 ...
(E) 学习到的位置嵌入 ...

注:表中具体内容未给出,仅展示格式。

4 Why Self-Attention

4 为什么选择自注意力机制 (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},\in,\mathbf{\bar{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.

在本节中,我们将自注意力层 (self-attention layers) 的各个方面与常用的递归层 (recurrent layers) 和卷积层 (convolutional layers) 进行比较,这些层通常用于将一个可变长度的符号表示序列 $(x_{1},...,x_{n})$ 映射到另一个等长的序列 $(z_{1},...,z_{n})$,其中 $x_{i},z_{i},\in,\mathbf{\bar{R}}^{d}$,例如典型序列转换编码器或解码器中的隐藏层。为了说明我们使用自注意力层的原因,我们考虑了三个理想特性 (desiderata)。

  1. 并行化能力:自注意力层可以并行处理输入序列中的所有位置,而递归层需要按顺序处理每个位置,这限制了其并行化能力。
  2. 长距离依赖建模:自注意力层能够有效地捕捉序列中任意位置之间的依赖关系,而递归层和卷积层在这方面的表现较弱,尤其是在处理长距离依赖时。
  3. 计算效率:自注意力层的计算复杂度与序列长度成线性关系,而卷积层的计算复杂度与卷积核大小和序列长度有关,递归层则需要逐个处理序列元素,导致计算效率较低。

通过对比这些特性,我们可以更好地理解自注意力层的优势及其在序列建模任务中的应用。

One is the total computational complexity per layer. Another is the amount of computation that can be parallel i zed, 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.

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

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(l o g_{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.

单个卷积层在核宽度为 $k < n$ 时,无法连接所有输入和输出位置的对。要实现这一点,在连续核的情况下需要堆叠 $O(n/k)$ 个卷积层,或在空洞卷积的情况下需要 $O(\log_{k}(n))$ 个卷积层 [18],这会增加网络中任意两个位置之间最长路径的长度。卷积层通常比循环层昂贵 $k$ 倍。然而,可分离卷积 [6] 大大降低了复杂度,降至 $O(k \cdot n \cdot d + n \cdot d^{2})$。即使当 $k = n$ 时,可分离卷积的复杂度仍然等同于自注意力层和逐点前馈层的组合,这是我们模型采用的方法。

As side benefit, self-attention could yield more interpret able 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 structu