论文阅读:Attention is all you need

发布于:2025-03-22 ⋅ 阅读:(48) ⋅ 点赞:(0)

省流:

(2017)

本文提出 Transformer,是一个用来平替 CNN & RNN 的,完全基于注意力机制的架构。Transformer 能力强、容易并行、训练时间短。

  • 作者的出发点可能是并行化。

Authors

作者来自 Google Brain 和 Google Research.

Equal contribution. Listing order is random.

  • Jakob proposed replacing RNNs with self-attention and started the effort to evaluate this idea.
  • Ashish, with Illia, designed and implemented the first Transformer models and has been crucially involved in every aspect of this work.
  • Noam proposed scaled dot-product attention, multi-head attention and the parameter-free position representation and became the other person involved in nearly every detail.
  • Niki designed, implemented, tuned and evaluated countless model variants in our original codebase and tensor2tensor.
  • Llion also experimented with novel model variants, was responsible for our initial codebase, and efficient inference and visualizations.
  • Lukasz and Aidan spent countless long days designing various parts of and implementing tensor2tensor, replacing our earlier codebase, greatly improving results and massively accelerating our research.

八卦:

  • 发起人 Ashish 和其他人
  • 花了几个月,包括一些实习生来写代码。
  • Noam 来了之后把架构重写了一遍
  • 本来是用于机器翻译的,用于 google docs 替代机器学习方法

abstract

当前用来解决 seq2seq 问题的模型通常包含 CNN 和 RNN,并且整体架构通常形如 encoder-decoder。并且,时下(2017) 的 SOTA 结果通常会在 encoder 和 decoder 之间用 attention 联系起来。

本文提出一个新的结构,transformer,仅依靠注意力机制,可以有效对长距离进行建模,是 CNN, RNN 的有力平替,实验表明效果好,并行度高,收敛快。

1. Introduction

传统的处理序列的方法具有如下特征:

  1. 架构上通常有一部分作为 encoder, 一部分作为 decoder.
  2. 通常会沿序列方向计算隐向量 h t h_t ht
  3. encoder 和 decoder 之间有一层注意力
  4. 研究范式基于 CNN, RNN,在此基础上对效率 [21] 和性能做了很多改进。

注意力机制允许模型建模输入和输出之间,任意远距离间的的关联关系。然而,在绝大多数场景下,注意力机制长期被结合在 RNN 里。本文提出的 Transformer 不需要循环神经元,是我们所了解到的第一个完全由自注意力机制搭起来的模型。

2. Background

有很多相关工作(如 ByteNet, ConvS2S) 旨在减小串行的计算量,这些工作希望并行地给每个位置计算隐向量,然而,他们关联任意两个输入输出的位置时,所需的的开销随距离成线性或 log 增长,导致难以捕捉远距离特征。

在 Transformer 中,关联任意远距离的开销是常数的(position encoding),但是由于是计算了注意力加权的 position,这个关联的分辨率有所降低。

自注意力是在序列中两两计算 attention 的机制,这样可以对一个 seq 计算一种表示。

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.

在 [34] 中,端到端的记忆网络是基于循环注意力机制的,而不是沿 seq 方向的循环神经网络(我理解意思是竖着的而不是横着的)。该方法效果不错

本文提出的 Transformer 不需要循环神经元,是我们所了解到的第一个完全由自注意力机制搭起来的模型。

3. Model Architecture

3.1 Encoder and Decoder Stacks

绝大多数 SOTA 的机器翻译模型采用 encoder-decoder 架构。encoder 把输入的符号序列 ( x 1 , … , x n ) (x_1, \ldots, x_n) (x1,,xn) 映射到一个连续向量空间的序列 z = ( z 1 , … , z n ) \bm z = (z_1,\ldots, z_n) z=(z1,,zn)。给定 z z z, decoder 一个一个地生成输出序列 ( y 1 , … , y m ) (y_1, \ldots, y_m) (y1,,ym)。每步生成都是 auto-regressive 的,接受前一个输出。

在这里插入图片描述

Encoder

Encoder 由 N = 6 N=6 N=6 个相同 layer 组成。每个 layer 有两个 sub-layer.
第一个是多头自注意力机制,第二个是一个 position-wise 的 FC 前馈网络。每个 sub-layer 中还使用归一化和残差网络连接,输出是 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)),其中 sublayer 是每个子层的实现。

考虑到残差的实现,所有 sub-layer 以及 embedding 层的输出维度都是 d m o d e l = 512 d_{model} = 512 dmodel=512.

Decoder

Decoder 同样由 N = 6 N=6 N=6 个相同 layer 堆叠组成。在编码器每层两个 sub-layer 的基础上,解码器额外引入第三个 sub-layer,用于对编码器输出的表示进行多头注意力交互。与编码器一致,每个子层均通过残差连接与层归一化处理。此外,解码器中的自注意力子层被特别设计为掩码版本,以禁止当前位置关注后续位置的输入。这种掩码机制与输出嵌入向右偏移一位的特性协同作用,确保位置 i i i 的预测仅依赖于小于 i i i 的已知位置输出。

3.2 Attention

注意力可以看作是对向量 v v v 的加权输出,其中权重是 q q q 和每个位置的 k k k 在某种度量下的相似度。

在这里插入图片描述

3.2.1 Scaled dot-product Attention.

我们实现的 attention 机制被叫做 “scaled dot-product attention”.

  • 输入的 queries 和 keys 维度都是 d k d_k dk,values 的维度是 d v d_v dv.
  • 用点积计算相似度,然后除以 d k \sqrt{d_k} dk ,并接入 softmax

在实际计算中,一句话分成 n 个 token 的 embeddings,n 个 q,k,v 并行计算,构成矩阵 Q , K ∈ R n × d k , V ∈ R n × d v Q, K \in \Reals^{n\times d_k}, V\in \Reals^{n\times d_v} Q,KRn×dk,VRn×dv.

A t t e n t i o n ( Q , K , V ) = softmax ⁡ ( Q K T d k ) V Attention(Q, K, V) = \operatorname{softmax}(\frac{QK^T}{\sqrt{d_k}})V Attention(Q,K,V)=softmax(dk QKT)V

最常用的 attention 是 additive attention[2] 和 dot-product attention,前者需要用神经网络,后者直接是矩阵计算。本文选用后者,因为可以直接利用矩阵乘法的优化,性能更快。 其中本文对 dot-product attention 做出的改进是分母除掉了 d k 1 / 2 d_k^{1/2} dk1/2

作者做实验发现,在 d k d_k dk 比较小的时候两种 attention 效果相近。但对于更大的 d k d_k dk[3],点乘的不如加性的。作者怀疑这是因为点积导致模长快速上涨,导致自变量进入 softmax 梯度极端变小的区间。为了控制这个问题,

3.2.2 Multi-Head Attention

作者发现,用多个头的效果比用一个头要好,也就是说,上文提到的每个层的输出维度是 d m o d e l = 512 d_{model} = 512 dmodel=512,作者并不是直接让 qkv 都是 d m o d e l d_{model} dmodel 维,而是选择将 qkv 用线性模型投影 h h h 次拆分成 d k , d k , d v d_k, d_k, d_v dk,dk,dv 维,用 h h h 头分别学习,每个头最终得到 d v d_v dv-维的输出。然后将 h h h 个头的输出 concat 到一起并最后再映射一次得到最终结果。

如上图 (图 2) 所示,多头注意力允许模型综合多个表示的子空间的信息,避免单独的一个头取平均抑制了这点。

据说因为不是一个分布,理论上 addition 和 concat 其实都可以,做实验做出来的。

MultiHead ⁡ ( Q , K , V ) = Concat ⁡ ( h e a d 1 , … , h e a d h ) W O where  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 ) \begin{align*} \operatorname{MultiHead}(Q, K, V) &= \operatorname{Concat}(head_1, \ldots, head_h)W^O\\ \text{where } head_i &= Attention(QW_i^Q, KW_i^K, VW_i^V) \end{align*} MultiHead(Q,K,V)where headi=Concat(head1,,headh)WO=Attention(QWiQ,KWiK,VWiV)

其中,线性映射即参数矩阵 W i Q ∈ R d m o d e l × d k W_i^Q \in \Reals^{d_{model}\times d_k} WiQRdmodel×dk, W i K ∈ R d m o d e l × d k W_i^K\in \Reals^{d_{model}\times d_k} WiKRdmodel×dk, W i V ∈ R d m o d e l × d v W_i^V \in \Reals^{d_{model}\times d_v} WiVRdmodel×dv, W O ∈ R h d v × d m o d e l W^O \in \Reals^{hd_v \times d_{model}} WORhdv×dmodel

作者采用 h = 8 h = 8 h=8 个头(并行 attention layers), 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

详细解释用到 attention 的地方

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 − ∞ −\infty ) all v

3.3 Position-wise Feed-Forward Networks

前馈网络采用点对点的线性变换加 ReLU.

F F N ( x ) = m a x ( 0 , x W 1 + b 1 ) W 2 + b 2 FFN(x) = max(0, xW_1 + b_1)W_2 + b_2 FFN(x)=max(0,xW1+b1)W2+b2
其中,乘法其实是 1x1 卷积,不同位置的系数相同(层与层之间不同)。 输入输出的维度是 d m o d e l = 512 d_{model} = 512 dmodel=512, inner-layer has dimensionality d f f = 2048 d_{ff} = 2048 dff=2048.

3.4 Embeddings and Softmax

输入输出经过 embedding 转换成 d m o d e l d_{model} dmodel 维的向量。然后经过线性和 softmax 转换成 prob。

本文的两个 embedding 层和 pre-softmax 的线性变换共享同样的权重矩阵,特别地,在 embedding 层会把权重乘上 d m o d e l \sqrt{d_{model}} dmodel

3.5 Positional Encoding

Attention 本身不考虑位置先后顺序。于是作者参考了时序 CNN 的方法,从众多已有 positional encodings 里选择了 sin ⁡ , cos ⁡ \sin, \cos sin,cos 两个函数。

P E ( p o s , 2 i ) = sin ⁡ ( p o s / 1000 0 2 i / d m o d e l ) P E ( p o s , 2 i + 1 ) = cos ⁡ ( p o s / 1000 0 2 i / d m o d e l ) \begin{align*} PE_{(pos, 2i)} &= \operatorname{sin}(pos/10000^{2i/d_{model}})\\ PE_{(pos, 2i + 1)} &= \operatorname{cos}(pos/10000^{2i/d_{model}})\\ \end{align*} PE(pos,2i)PE(pos,2i+1)=sin(pos/100002i/dmodel)=cos(pos/100002i/dmodel)

其中 p o s pos pos 指位置, i i i 指维度。在某个固定的维度,PE 关于 pos 构成三角波,波长从 2 π 2\pi 2π 10000 ⋅ 2 π 10000\cdot 2\pi 100002π.

选用三角波是因为,固定维度 k k k P E p o s + k PE_{pos+k} PEpos+k P E p o s PE_{pos} PEpos 的线性表示。因此作者假设模型容易学。

作者也尝试了基于学习的 positional encoding,实验结果显示性能几乎相同。但由于三角波能在训练时容纳更长的上下文,文章最后使用三角波

4. Why Self-Attention

5. Training

6. Results

相关教程

https://www.youtube.com/watch?v=l4is4uHvKlU
在这里插入图片描述