Attention Is All You Need论文精读(逐段解析)
Attention Is All You Need论文精读(逐段解析)
论文地址:https://proceedings.neurips.cc/paper_files/paper/2017/file/3f5ee243547dee91fbd053c1c4a845aa-Paper.pdf
NIPS 2017
Google机器翻译团队发布
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,完全基于注意力机制,完全摒弃了循环和卷积。在两个机器翻译任务上的实验表明,这些模型在质量上更优越,同时具有更好的并行性,训练时间显著减少。我们的模型在WMT 2014英德翻译任务上达到了28.4 BLEU分数,比现有最佳结果(包括集成模型)提高了超过2个BLEU分数。在WMT 2014英法翻译任务上,我们的模型在8个GPU上训练3.5天后建立了新的单模型最先进BLEU分数41.8,这只是文献中最佳模型训练成本的一小部分。我们通过将Transformer成功应用于英语成分句法分析(在大量和有限训练数据下)证明了Transformer在其他任务上的良好泛化能力。
【解析】作者在这里明确提出了他们的研究贡献。传统的序列到序列模型主要依赖两种架构:循环神经网络(RNN)和卷积神经网络(CNN)。这些模型通常采用编码器-解码器框架,编码器负责理解输入序列,解码器负责生成输出序列。为了让编码器和解码器更好地协作,研究者们引入了注意力机制作为桥梁。然而,作者们在这里提出了一个大胆的想法:既然注意力机制如此有效,为什么不完全基于注意力机制构建模型呢?这就是Transformer的核心思想——抛弃传统的循环和卷积结构,纯粹依靠注意力机制来处理序列数据。这种设计带来了两个重要优势:首先是并行化能力的大幅提升,因为不再需要按时间步骤顺序处理,可以同时处理序列中的所有位置;其次是训练效率的显著改善,大大减少了训练时间。论文通过具体的实验数据证明了这一点:在标准的机器翻译基准测试中,Transformer不仅在翻译质量上超越了之前的最佳模型,而且训练成本大幅降低。更重要的是,作者们还证明了Transformer的通用性,它不仅在机器翻译任务上表现出色,在其他自然语言处理任务如句法分析上也展现了强大的能力,这表明Transformer可能成为一个通用的序列建模架构。
1 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].
【翻译】循环神经网络,特别是长短期记忆网络[13]和门控循环神经网络[7],已经被确立为序列建模和转换问题(如语言建模和机器翻译)的最先进方法[35, 2, 5]。此后,众多努力持续推动循环语言模型和编码器-解码器架构的边界[38, 24, 15]。
【解析】这段话首先介绍了当时(2017年)深度学习领域的现状。在Transformer出现之前,处理序列数据的主流方法是循环神经网络(RNN)及其变种。RNN的基本思想是按时间步骤逐个处理序列中的元素,每个时间步的输出不仅依赖于当前输入,还依赖于之前所有时间步的信息。但是普通的RNN存在梯度消失问题,难以学习长距离依赖关系。为了解决这个问题,研究者们开发了LSTM(长短期记忆网络)和GRU(门控循环单元)等改进版本。LSTM通过引入门控机制(输入门、遗忘门、输出门)来控制信息的流动,能够更好地保持长期记忆。GRU则是LSTM的简化版本,用更少的参数实现类似的效果。这些模型在语言建模(预测下一个词)和机器翻译(将一种语言翻译成另一种语言)等任务上取得了当时最好的效果。编码器-解码器架构是处理序列到序列任务的标准框架,编码器将输入序列编码成固定长度的向量表示,解码器根据这个表示生成输出序列。
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 [ 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} ht,作为前一个隐藏状态 h t − 1 h_{t-1} ht−1和位置 t t t处输入的函数。这种固有的顺序性质阻碍了训练样本内的并行化,这在较长序列长度时变得至关重要,因为内存约束限制了样本间的批处理。最近的工作通过分解技巧[21]和条件计算[32]在计算效率方面取得了显著改进,在后者的情况下还提高了模型性能。然而,顺序计算的基本约束仍然存在。
【解析】这段话深入分析了循环神经网络的核心问题。RNN的计算过程是严格按照时间顺序进行的,当前时刻的隐藏状态 h t h_t ht必须依赖于前一时刻的隐藏状态 h t − 1 h_{t-1} ht−1和当前时刻的输入。这种依赖关系意味着我们无法并行计算所有时间步的隐藏状态,必须等待前一步计算完成后才能进行下一步。这种顺序性在处理短序列时问题不大,但当序列变长时就成了严重的瓶颈。现代GPU擅长并行计算,但RNN的顺序特性无法充分利用这种并行能力。更糟糕的是,当序列很长时,由于内存限制,我们甚至无法同时处理多个训练样本(即批处理大小必须减小),这进一步降低了训练效率。虽然研究者们尝试了各种优化技巧,比如将大矩阵分解成小矩阵的乘积来节省内存,或者使用条件计算只激活网络的一部分来提高效率,但这些都是治标不治本的方法,RNN固有的顺序计算限制依然存在。
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]外,这些注意力机制都是与循环网络结合使用的。
【解析】这段话介绍了注意力机制的重要性和当时的使用现状。传统的RNN在处理长序列时存在一个严重问题:随着序列长度增加,早期的信息会逐渐被遗忘,这使得模型难以捕捉长距离的依赖关系。注意力机制的出现很好地解决了这个问题。注意力机制的核心思想是让模型在生成每个输出时,都能够"回头看"整个输入序列,并根据相关性给不同位置的输入分配不同的权重。这样,无论两个相关元素在序列中相距多远,模型都能够直接建立它们之间的联系,而不需要通过中间的许多步骤来传递信息。这种机制在机器翻译、文本摘要等任务中表现出色,因为这些任务经常需要处理长距离的语义依赖。但是在2017年之前,注意力机制几乎总是作为RNN的辅助组件出现,用来增强RNN的能力,而不是独立使用。
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上仅训练十二小时后就能在翻译质量上达到新的最先进水平。
【解析】Transformer标志着深度学习历史上的一个重要转折点。作者们提出了一个革命性的想法:既然注意力机制如此有效,为什么还要依赖RNN呢?Transformer完全抛弃了循环结构,纯粹基于注意力机制构建。这种设计带来了巨大的优势:首先是并行化能力的飞跃。由于不再需要按时间步骤顺序计算,Transformer可以同时处理序列中的所有位置,充分利用现代GPU的并行计算能力。其次是训练效率的显著提升,论文中提到仅用8个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 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.
【翻译】减少顺序计算的目标也构成了Extended Neural GPU [16]、ByteNet [18]和ConvS2S [9]的基础,这些模型都使用卷积神经网络作为基本构建块,为所有输入和输出位置并行计算隐藏表示。在这些模型中,连接两个任意输入或输出位置信号所需的操作数量随位置间距离增长,ConvS2S为线性增长,ByteNet为对数增长。这使得学习远距离位置之间的依赖关系变得更加困难[12]。在Transformer中,这被减少到恒定数量的操作,尽管由于对注意力加权位置进行平均而导致有效分辨率降低,我们通过第3.2节描述的多头注意力来抵消这种影响。
【解析】这段话讲述了在Transformer之前,研究者们为了解决RNN顺序计算问题所做的努力。Extended Neural GPU、ByteNet和ConvS2S都是基于卷积神经网络的模型,它们的共同目标是实现并行计算。卷积操作天然具有并行性,可以同时处理序列中的多个位置,这比RNN的逐步处理要高效得多。但是这些基于卷积的模型存在一个关键问题:当需要建立两个相距较远位置之间的联系时,信息需要通过多层卷积逐步传播。ConvS2S需要的层数与距离成正比(线性增长),而ByteNet通过特殊的扩张卷积设计,需要的层数与距离的对数成正比(对数增长)。虽然对数增长比线性增长好,但随着序列长度增加,仍然需要很多层才能连接远距离的位置,这增加了模型的复杂性和训练难度。Transformer的革命性在于,无论两个位置相距多远,都只需要恒定数量的操作(实际上是一次矩阵乘法)就能建立直接联系。这种设计确实会带来一个副作用:由于注意力机制会对所有位置进行加权平均,可能会稀释重要信息的表示。但作者们通过多头注意力机制巧妙地解决了这个问题,让模型能够同时关注不同类型的信息。
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].
【翻译】自注意力,有时称为内部注意力,是一种将单个序列的不同位置相关联以计算序列表示的注意力机制。自注意力已经在各种任务中成功使用,包括阅读理解、抽象摘要、文本蕴含和学习任务无关的句子表示[4, 27, 28, 22]。
【解析】自注意力是Transformer的核心机制,这里需要理解它与传统注意力的区别。传统的注意力机制通常用在编码器-解码器架构中,解码器在生成每个输出时会"注意"编码器的不同位置,这是跨序列的注意力。而自注意力是序列内部的注意力机制,它让序列中的每个位置都能够与同一序列中的所有其他位置建立直接联系。比如在处理句子"The cat sat on the mat"时,自注意力让"cat"这个词不仅能看到自己,还能直接看到"The"、“sat”、“on”、“the”、"mat"等所有其他词,并根据语义相关性给它们分配不同的权重。这种机制特别适合处理需要理解长距离依赖关系的任务。在阅读理解中,模型需要将问题中的关键词与文章中相关的部分联系起来;在文本摘要中,需要识别文章中最重要的信息;在文本蕴含任务中,需要判断两个句子之间的逻辑关系。自注意力的强大之处在于它能够让模型自动学会关注最相关的信息,而不需要人工设计特征。
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]。
【解析】端到端记忆网络代表了另一种尝试突破传统RNN限制的方法。传统RNN的问题在于它严格按照序列顺序处理信息,而记忆网络引入了一种不同的循环方式。它不是在时间维度上循环,而是在注意力维度上循环。具体来说,模型会反复地在记忆中搜索相关信息,每次搜索都会更新查询向量,然后用更新后的查询向量进行下一轮搜索。这种设计让模型能够进行多步推理,特别适合需要复杂推理的问答任务。比如回答"John去了厨房,然后去了花园,Mary在哪里?"这样的问题时,模型需要多步推理才能得出答案。虽然记忆网络在某些任务上表现不错,但它仍然保留了循环结构,只是将循环从时间维度转移到了推理维度,并没有完全解决并行化的问题。
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]等模型的优势。
【解析】在深度学习的发展历程中,研究者们一直在寻找更好的序列建模方法。从最初的RNN到LSTM、GRU,再到加入注意力机制的RNN,每一步都是在原有架构基础上的改进。即使是前面提到的卷积模型和记忆网络,也都保留了某种形式的循环或卷积结构。Transformer的革命性在于它彻底抛弃了这些传统结构,纯粹基于自注意力机制构建。这种设计哲学的转变具有深远意义:它证明了注意力机制本身就足够强大,不需要依赖其他复杂的结构。BERT、GPT等后续的重要模型都是基于Transformer架构发展而来的,可以说Transformer开启了现代自然语言处理的新时代。
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 ) (x_{1},...,x_{n}) (x1,...,xn) to a sequence of continuous representations z = ( z 1 , . . . , z n ) \mathbf{z}~=~(z_{1},...,z_{n}) z = (z1,...,zn) . Given z \mathbf{z} z , the decoder then generates an output sequence ( y 1 , . . . , y m ) \left(y_{1},...,y_{m}\right) (y1,...,ym) 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 ) (x_{1},...,x_{n}) (x1,...,xn)映射到连续表示的序列 z = ( z 1 , . . . , z n ) \mathbf{z}~=~(z_{1},...,z_{n}) z = (z1,...,zn)。给定 z \mathbf{z} z,解码器然后一次生成一个元素的输出序列 ( y 1 , . . . , y m ) \left(y_{1},...,y_{m}\right) (y1,...,ym)。在每一步中,模型都是自回归的[10],在生成下一个符号时将先前生成的符号作为额外输入。
【解析】编码器-解码器架构是处理序列到序列任务的经典框架,这种设计思想来源于人类处理信息的方式。想象你在做翻译工作,首先你需要完整理解原文的含义(编码过程),然后用目标语言表达出来(解码过程)。编码器的作用就是将输入序列中的离散符号(比如单词、字符)转换成计算机能够处理的连续数值向量。这个过程不是简单的查表,而是要捕捉每个符号在特定上下文中的语义信息。比如"bank"这个词在"river bank"和"money bank"中的含义完全不同,编码器需要根据上下文生成不同的向量表示。解码器则是一个生成过程,它根据编码器提供的语义表示,逐步生成目标序列。自回归特性是解码器的核心特征,意味着生成每个新符号时都会参考之前已经生成的所有符号。这种设计确保了输出序列的连贯性和一致性,但也带来了无法并行生成的限制,因为每一步都依赖于前面步骤的结果。
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的左半部分和右半部分。
【解析】传统的编码器-解码器模型通常使用RNN或CNN作为基础组件,而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 [ 11 ] around each of the two sub-layers, followed by layer normalization [ 1 ]. That is, the output of each sub-layer is LayerNorm ( x + S u b l a y e r ( x ) ) (x+{\mathrm{Sublayer}}(x)) (x+Sublayer(x)) , where Sublayer ( x ) (x) (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_{\mathrm{model}}=512 dmodel=512 .
【翻译】编码器:编码器由 N = 6 N=6 N=6个相同层的堆叠组成。每层有两个子层。第一个是多头自注意力机制,第二个是简单的逐位置全连接前馈网络。我们在两个子层周围都采用残差连接[11],然后进行层归一化[1]。也就是说,每个子层的输出是LayerNorm ( x + S u b l a y e r ( x ) ) (x+{\mathrm{Sublayer}}(x)) (x+Sublayer(x)),其中Sublayer ( x ) (x) (x)是子层本身实现的函数。为了便于这些残差连接,模型中的所有子层以及嵌入层都产生维度为 d m o d e l = 512 d_{\mathrm{model}}=512 dmodel=512的输出。
【解析】编码器的设计。首先是模块化设计,6个相同的层堆叠在一起,每层内部又分为两个功能明确的子层。多头自注意力子层负责捕捉序列内部的依赖关系,而前馈网络子层则对每个位置的表示进行非线性变换,增强模型的表达能力。残差连接允许梯度直接流向较浅的层,解决了深度网络训练中的梯度消失问题。在Transformer中,残差连接的形式是 x + Sublayer ( x ) x + \text{Sublayer}(x) x+Sublayer(x),即子层的输出会与输入相加。这种设计让网络更容易学习恒等映射,如果某个子层对当前任务没有帮助,它可以学会输出接近零的值,从而不影响信息的传递。层归一化则是另一个重要的技术,它对每个样本的特征维度进行归一化,稳定训练过程并加速收敛。所有子层输出维度统一为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的已知输出。
【解析】解码器的设计比编码器更加复杂,因为它需要处理生成任务的特殊要求。解码器有三个子层:第一个是带掩码的自注意力层,第二个是编码器-解码器注意力层,第三个是前馈网络层。带掩码的自注意力是解码器的关键创新,它通过掩码机制确保模型在生成第 i i i个位置的输出时,只能看到前面 i − 1 i-1 i−1个位置的信息,而不能"偷看"后面的内容。这种设计保持了自回归生成的特性,模拟了人类逐词生成文本的过程。编码器-解码器注意力层则建立了解码器与编码器之间的桥梁,让解码器能够根据输入序列的信息来生成输出。在这个子层中,查询来自解码器的前一层,而键和值来自编码器的输出,这样解码器的每个位置都能关注到输入序列的所有位置。输出嵌入偏移一个位置是训练时的技巧,在训练阶段,解码器的输入是目标序列向右偏移一位的版本,这样模型学会根据前面的真实输出来预测下一个位置的输出。这种设计确保了模型的因果性,即未来的信息不会影响当前的预测,这对于生成任务的正确性至关重要。
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.
【翻译】注意力函数可以描述为将一个查询和一组键值对映射到输出的过程,其中查询、键、值和输出都是向量。输出被计算为值的加权和,其中分配给每个值的权重是通过查询与相应键的兼容性函数计算得出的。
【解析】注意力机制的本质是一个信息检索和聚合的过程,这个过程可以类比为我们在图书馆查找资料的方式。当你带着一个特定的问题(查询query)走进图书馆时,你会浏览书架上的各种书籍标题(键keys),然后根据标题与你问题的相关程度来决定是否翻阅这本书的内容(值values)。最终,你会将从不同书籍中获得的信息按照它们与你问题的相关程度进行加权组合,形成最终的答案(输出output)。在数学层面,这个过程涉及三个核心组件:查询向量代表了我们想要寻找的信息特征,键向量代表了每个候选信息的索引特征,值向量则包含了实际的信息内容。兼容性函数负责计算查询与每个键之间的匹配程度,这个匹配程度决定了对应值在最终输出中的重要性。通过这种机制,模型能够动态地从大量候选信息中选择最相关的部分,并将它们有机地组合起来。这种设计的优雅之处在于它完全是可微分的,可以通过反向传播进行端到端的训练,让模型自动学会如何进行有效的信息检索和聚合。
Figure 2: (left) Scaled Dot-Product Attention. (right) Multi-Head Attention consists of several attention layers running in parallel.
【翻译】图2:(左)缩放点积注意力。(右)多头注意力由几个并行运行的注意力层组成。
【解析】这个图展示了Transformer中两个核心的注意力机制。左侧的缩放点积注意力是最基础的注意力计算单元,它通过矩阵运算高效地计算查询与所有键的相似度,然后用这些相似度对值进行加权求和。右侧的多头注意力则是对基础注意力机制的扩展,它并行运行多个注意力头,每个头都关注不同的表示子空间。这种设计让模型能够同时捕捉多种不同类型的依赖关系,比如语法关系、语义关系、位置关系等。多头机制的核心思想是"分工合作":不同的注意力头专门负责不同类型的信息处理,最后将所有头的输出拼接起来,通过一个线性变换得到最终结果。这种并行处理不仅提高了模型的表达能力,还保持了计算效率,因为每个头处理的维度相对较小,总的计算量与单头全维度注意力相当。
3.2.1 缩放点积注意力
We call our particular attention “Scaled Dot-Product Attention” (Figure 2). The input consists of queries and keys of dimension query with all keys, divide each by d k d_{k} dk , and values of dimension d k \sqrt{d_{k}} dk , and apply a softmax function to obtain the weights on the d v d_{v} dv . We compute the dot products of the values.
【翻译】我们将我们的特定注意力称为"缩放点积注意力"(图2)。输入包括维度为 d k d_k dk的查询和键,以及维度为 d v d_v dv的值。我们计算查询与所有键的点积,将每个点积除以 d k \sqrt{d_k} dk,然后应用softmax函数来获得值的权重。
【解析】缩放点积注意力是Transformer的核心计算单元,这里的"点积"指的是向量之间的内积运算,用来衡量两个向量的相似程度。当查询向量与某个键向量越相似时,它们的点积值就越大,这意味着对应的值向量在最终输出中的权重也越大。缩放因子 d k \sqrt{d_k} dk的引入是为了数值稳定性考虑。当向量维度 d k d_k dk较大时,点积的结果往往也会变得很大,这会导致softmax函数的输出过于集中在某几个位置上,使得梯度变得极小,影响训练效果。通过除以 d k \sqrt{d_k} dk,我们可以将点积的方差控制在合理范围内,让softmax的输出更加平滑,从而保证训练的稳定性。。
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 ) = softmax ( Q K T d k ) V {\mathrm{Attention}}(Q,K,V)=\operatorname{softmax}({\frac{Q K^{T}}{\sqrt{d_{k}}}})V Attention(Q,K,V)=softmax(dkQKT)V
【解析】矩阵 Q Q Q的每一行代表一个查询向量, K K K的每一行代表一个键向量, V V V的每一行代表一个值向量。 Q K T QK^T QKT的计算实际上是在计算所有查询与所有键之间的相似度矩阵,其中第 ( i , j ) (i,j) (i,j)个元素表示第 i i i个查询与第 j j j个键的相似度。除以 d k \sqrt{d_k} dk进行缩放后,对每一行应用softmax函数,得到的是每个查询对所有键的注意力权重分布。最后乘以值矩阵 V V V,实现了加权求和的过程。这种矩阵化的实现方式不仅在数学上优雅,更重要的是它充分利用了现代GPU的并行计算能力。所有的查询可以同时处理,所有的键值对也可以同时参与计算,这使得注意力机制能够高效地处理长序列,这是RNN等序列模型无法比拟的优势。
The two most commonly used attention functions are additive attention [ 2 ], and dot-product (multiplicative) attention. Dot-product attention is identical to our algorithm, except for the scaling factor of 1 d k \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.
【翻译】两种最常用的注意力函数是加性注意力[2]和点积(乘性)注意力。点积注意力与我们的算法相同,除了缩放因子 1 d k \frac{1}{\sqrt{d_{k}}} dk1。加性注意力使用具有单个隐藏层的前馈网络来计算兼容性函数。虽然两者在理论复杂度上相似,但点积注意力在实践中要快得多且更节省空间,因为它可以使用高度优化的矩阵乘法代码来实现。
【解析】这里对比了两种主要的注意力计算方式,揭示了Transformer选择点积注意力的深层原因。加性注意力的计算过程更加复杂,它需要将查询和键先通过一个前馈网络进行变换,然后再计算兼容性分数。虽然这种方法在表达能力上可能更强,但它的计算成本也更高。相比之下,点积注意力只需要简单的向量内积运算,这种运算在现代计算硬件上有着高度优化的实现。特别是在GPU和专用AI芯片上,矩阵乘法运算可以充分利用硬件的并行计算能力,实现极高的计算效率。。
While for small values of d k d_{k} dk the two mechanisms perform similarly, additive attention outperforms dot product attention without scaling for larger values of d k d_{k} dk [ 3 ]. 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 4 . 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值,加性注意力优于未缩放的点积注意力[3]。我们怀疑对于较大的 d k d_{k} dk值,点积的幅度变得很大,将softmax函数推入梯度极小的区域。为了抵消这种影响,我们将点积缩放 1 d k \frac{1}{\sqrt{d_{k}}} dk1。
【解析】当向量维度增大时,随机向量之间点积的方差会随着维度线性增长,这是高维空间的一个基本性质。具体来说,如果两个独立的随机向量的每个分量都是均值为0、方差为1的分布,那么它们点积的方差就等于向量的维度 d k d_k dk。当 d k d_k dk很大时,点积的绝对值往往也会很大,这会导致softmax函数的输入分布变得极端。softmax函数在输入值很大或很小时,其梯度会趋近于零,这种现象被称为"梯度饱和"。在这种情况下,模型很难通过梯度下降进行有效的学习。通过除以 d k \sqrt{d_k} dk,我们实际上是在对点积进行标准化,使其方差保持在1左右,这样softmax函数就能工作在梯度较大的区域,保证训练的有效性。。
3.2.2 Multi-Head Attention
Instead of performing a single attention function with d m o d e l d_{\mathrm{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_{\mathrm{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 ) \begin{array}{r l}&{\mathrm{MultiHead}(Q,K,V)=\mathrm{Concat}(\mathrm{head}_{1},...,\mathrm{head}_{\mathrm{h}})W^{O}}\ &{\quad\quad\quad\quad\mathrm{where~head}_{\mathrm{i}}=\mathrm{Attention}(Q W_{i}^{Q},K W_{i}^{K},V W_{i}^{V})}\end{array} MultiHead(Q,K,V)=Concat(head1,...,headh)WO where headi=Attention(QWiQ,KWiK,VWiV)
【解析】这个公式完整地描述了多头注意力的计算流程。首先,每个头 h e a d i \mathrm{head}_i headi都通过三个不同的投影矩阵 W i Q W_{i}^{Q} WiQ、 W i K W_{i}^{K} WiK、 W i V W_{i}^{V} WiV将输入的查询、键、值矩阵投影到各自的子空间中。这些投影矩阵是可学习的参数,在训练过程中会自动调整以捕捉不同类型的特征。每个头在其投影后的子空间中独立计算注意力,得到一个 d v d_v dv维的输出。然后,所有头的输出通过 C o n c a t \mathrm{Concat} Concat操作拼接成一个大的矩阵,这个矩阵的维度是 h × d v h \times d_v h×dv。最后,通过输出投影矩阵 W O W^O WO将拼接后的结果转换回模型的标准维度 d m o d e l d_{\mathrm{model}} dmodel。保持了计算的并行性:所有头可以同时计算,而且每个头处理的维度相对较小,使得总体计算复杂度与单头全维度注意力相当。同时,通过学习不同的投影矩阵,每个头能够自动专门化处理不同类型的信息,这种自动的任务分工是多头注意力强大表达能力的根源。
Where the projections are parameter matrices W i Q ∈ R d m o d e l × d k W_{i}^{Q}\in\mathbb{R}^{d_{\mathrm{model}}\times d_{k}} WiQ∈Rdmodel×dk ∈ , W K ∈ R d model × d k , W V ∈ R d model × d v i i and W O ∈ R h d v × d m o d c l W^{O}\in\mathbb{R}^{h d_{v}\times d_{\mathrm{modcl}}} WO∈Rhdv×dmodcl .
【翻译】其中投影是参数矩阵 W i Q ∈ R d m o d e l × d k W_{i}^{Q}\in\mathbb{R}^{d_{\mathrm{model}}\times d_{k}} WiQ∈Rdmodel×dk, W i K ∈ R d m o d e l × d k W_{i}^{K}\in\mathbb{R}^{d_{\mathrm{model}}\times d_{k}} WiK∈Rdmodel×dk, W i V ∈ R d m o d e l × d v W_{i}^{V}\in\mathbb{R}^{d_{\mathrm{model}}\times d_{v}} WiV∈Rdmodel×dv和 W O ∈ R h d v × d m o d e l W^{O}\in\mathbb{R}^{h d_{v}\times d_{\mathrm{model}}} WO∈Rhdv×dmodel。
【解析】每个头的查询和键投影矩阵 W i Q W_{i}^{Q} WiQ和 W i K W_{i}^{K} WiK都是从 d m o d e l d_{\mathrm{model}} dmodel维映射到 d k d_{k} dk维,这确保了查询和键在同一个子空间中进行匹配计算。值投影矩阵 W i V W_{i}^{V} WiV将 d m o d e l d_{\mathrm{model}} dmodel维映射到 d v d_{v} dv维,决定了每个头输出的维度。输出投影矩阵 W O W^{O} WO的维度是 h d v × d m o d e l h d_{v} \times d_{\mathrm{model}} hdv×dmodel,它负责将所有头拼接后的输出(总维度为 h d v h d_{v} hdv)重新映射回模型的标准维度 d m o d e l d_{\mathrm{model}} 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 = . 6 ˙ 4 d_{k}=d_{v}=d_{\mathrm{model}}/h\stackrel{.}{=}\dot{6}4 dk=dv=dmodel/h=.6˙4 . 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_{\mathrm{model}}/h=64 dk=dv=dmodel/h=64。由于每个头的维度减少了,总计算成本与全维度的单头注意力相似。
【解析】在增加模型表达能力的同时保持计算效率。选择8个头是经过实验验证的一个有效配置,它提供了足够的多样性来捕捉不同类型的依赖关系,同时又不会让模型变得过于复杂。每个头的维度设置为 d m o d e l / h = 512 / 8 = 64 d_{\mathrm{model}}/h=512/8=64 dmodel/h=512/8=64,这种均匀分割确保了所有头都有相同的表达能力,避免了某些头过于强势而其他头被边缘化的问题。更重要的是,这种设计实现了一个巧妙的计算平衡:虽然我们有8个头在并行工作,但每个头处理的维度只有原来的1/8,所以总的计算量(主要是矩阵乘法的复杂度)与单头全维度注意力基本相当。
3.2.3 注意力在我们模型中的应用
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 values in the input of the softmax which correspond to illegal connections. See Figure 2.
【翻译】Transformer以三种不同的方式使用多头注意力:
• 在"编码器-解码器注意力"层中,查询来自前一个解码器层,而记忆键和值来自编码器的输出。这允许解码器中的每个位置关注输入序列中的所有位置。这模仿了序列到序列模型中典型的编码器-解码器注意力机制,如[38, 2, 9]。
• 编码器包含自注意力层。在自注意力层中,所有的键、值和查询都来自同一个地方,在这种情况下,来自编码器中前一层的输出。编码器中的每个位置都可以关注编码器前一层中的所有位置。
• 类似地,解码器中的自注意力层允许解码器中的每个位置关注解码器中直到并包括该位置的所有位置。我们需要防止解码器中的向左信息流动以保持自回归特性。我们通过在缩放点积注意力内部屏蔽(设置为 − ∞ -\infty −∞)softmax输入中对应于非法连接的所有值来实现这一点。见图2。
【解析】这三种注意力应用方式,每种都有其特定的作用和实现方式。编码器-解码器注意力是连接编码器和解码器的桥梁,它让解码器在生成每个输出时都能"看到"整个输入序列。这种机制的关键在于查询来自解码器当前的状态,而键和值来自编码器的完整表示,这样解码器就能根据当前的生成进度动态地关注输入中最相关的部分。编码器的自注意力则让输入序列内部的每个位置都能与其他所有位置建立直接联系,这种全连接的方式使得模型能够捕捉到长距离的依赖关系,而不像RNN那样需要通过多步传递信息。解码器的自注意力最为复杂,因为它需要在保持自回归特性的同时实现内部信息交互。自回归特性要求在生成第i个词时,模型只能看到前i-1个词,不能"偷看"后面的词。通过将注意力矩阵中对应未来位置的值设为负无穷,softmax函数会将这些位置的权重变为0,从而实现了信息流的单向控制。这种掩码机制既保证了训练时的并行性,又维持了推理时的因果性约束。
3.3 逐位置前馈网络
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激活函数。
【解析】前馈网络是Transformer架构中的另一个核心组件,它与注意力机制形成了互补的作用。虽然注意力机制负责捕捉序列中不同位置之间的依赖关系,但前馈网络则专注于对每个位置的表示进行非线性变换和特征提取。这个网络是一个两层的全连接网络,第一层将输入从 d m o d e l d_{\mathrm{model}} dmodel维扩展到更高的 d f f d_{ff} dff维,然后通过ReLU激活函数引入非线性,最后第二层再将维度压缩回 d m o d e l d_{\mathrm{model}} dmodel维。这种"先扩展再压缩"的设计让模型在更高维的空间中进行复杂的特征变换,然后将结果映射回标准维度。关键的是,这个网络对每个位置都执行完全相同的操作,这意味着它是位置无关的,这种设计既保证了计算的一致性,又使得模型能够并行处理序列中的所有位置。
F F N ( x ) = max ( 0 , x W 1 + b 1 ) W 2 + b 2 \mathrm{FFN}(x)=\operatorname*{max}(0,x W_{1}+b_{1})W_{2}+b_{2} FFN(x)=max(0,xW1+b1)W2+b2
【解析】这个公式展示了前馈网络的计算流程。输入 x x x首先通过第一个线性变换 x W 1 + b 1 xW_1 + b_1 xW1+b1,其中 W 1 W_1 W1是权重矩阵, b 1 b_1 b1是偏置向量。这个线性变换的作用是将输入映射到一个更高维的特征空间中,为后续的非线性处理做准备。接下来, max ( 0 , ⋅ ) \max(0, \cdot) max(0,⋅)函数就是ReLU激活函数,它将所有负值置为零,只保留正值。ReLU的引入至关重要,因为它为模型提供了非线性表达能力,使得网络能够学习复杂的函数映射关系。如果没有这个非线性激活,整个前馈网络就退化为一个简单的线性变换,大大限制了模型的表达能力。经过ReLU激活后,结果再通过第二个线性变换 W 2 + b 2 W_2 + b_2 W2+b2,将高维特征重新映射回原始的模型维度。这种两步线性变换加一个非线性激活的结构,虽然简单,但能够有效地对输入进行复杂的特征变换。
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 m o d e l = 512 d_{\mathrm{model}}=512 dmodel=512, and the inner-layer has dimensionality d f f = 2048 d_{ff}=2048 dff=2048.
【翻译】虽然线性变换在不同位置上是相同的,但它们在不同层之间使用不同的参数。另一种描述方式是将其视为两个核大小为1的卷积。输入和输出的维度是 d m o d e l = 512 d_{\mathrm{model}}=512 dmodel=512,内层的维度是 d f f = 2048 d_{ff}=2048 dff=2048。
【解析】这段话揭示了前馈网络设计的几个重要特点。首先,"在不同位置上相同"说明了对于同一层内的所有位置,前馈网络使用完全相同的权重参数,这确保了模型对序列中每个位置的处理是一致的,不会因为位置不同而产生偏见。但是,“在不同层之间使用不同参数"则保证了每一层都能学习到不同层次的特征表示,从低层的局部特征到高层的抽象概念。将前馈网络描述为"核大小为1的卷积”,因为1×1卷积本质上就是对每个位置独立进行的全连接操作,这种等价性说明了前馈网络可以看作是在序列的每个位置上独立应用的特征变换器。维度设计:输入输出维度保持在512,这是模型的标准维度,确保了与其他组件的兼容性;而内层维度扩展到2048,这个4倍的扩展为模型提供了足够的表达空间来进行复杂的特征变换。这种"瓶颈"结构(先扩展后压缩)被广泛使用,它既增强了模型的表达能力,又通过最终的维度压缩控制了参数数量和计算复杂度。
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 m o d e l d_{\mathrm{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 [ 30 ]. In the embedding layers, we multiply those weights by d m o d e l \sqrt{d_{\mathrm{{model}}}} dmodel .
【翻译】与其他序列转换模型类似,我们使用学习的嵌入来将输入标记和输出标记转换为维度为 d m o d e l d_{\mathrm{model}} dmodel的向量。我们还使用通常的学习线性变换和softmax函数将解码器输出转换为预测的下一个标记概率。在我们的模型中,我们在两个嵌入层和pre-softmax线性变换之间共享相同的权重矩阵,类似于[30]。在嵌入层中,我们将这些权重乘以 d m o d e l \sqrt{d_{\mathrm{model}}} dmodel。
【解析】这段话描述了Transformer模型中词嵌入和输出层的设计细节。首先,模型需要将离散的词汇标记转换为连续的向量表示,这就是词嵌入的作用。无论是输入端的源语言词汇还是输出端的目标语言词汇,都通过各自的嵌入矩阵映射到 d m o d e l d_{\mathrm{model}} dmodel维的向量空间中,这个统一的维度确保了模型内部各个组件之间的兼容性。在输出端,解码器最后一层的隐藏状态需要转换为词汇表上的概率分布,这通过一个线性变换层和softmax函数来实现。线性变换将 d m o d e l d_{\mathrm{model}} dmodel维的隐藏状态映射到词汇表大小的向量,然后softmax函数将这些数值转换为概率分布,每个位置对应词汇表中一个词的生成概率。
Table 1: Maximum path lengths, per-layer complexity and minimum number of sequential operations for different layer types. n n n is the sequence length, d d d is the representation dimension, k k k is the kernel size of convolutions and r r r the size of the neighborhood in restricted self-attention.
【翻译】表1:不同层类型的最大路径长度、每层复杂度和最小顺序操作数。 n n n是序列长度, d d d是表示维度, k k k是卷积的核大小, r r r是受限自注意力中邻域的大小。
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_{\mathrm{model}} dmodel as the embeddings, so that the two can be summed. There are many choices of positional encodings, learned and fixed [9].
【翻译】由于我们的模型不包含循环和卷积,为了让模型能够利用序列的顺序,我们必须注入一些关于序列中标记的相对或绝对位置的信息。为此,我们在编码器和解码器堆栈的底部将"位置编码"添加到输入嵌入中。位置编码具有与嵌入相同的维度 d m o d e l d_{\mathrm{model}} dmodel,因此两者可以相加。位置编码有很多选择,包括学习的和固定的[9]。
【解析】这里揭示了Transformer架构面临的一个挑战:如何让模型理解序列中词汇的位置信息。传统的RNN模型天然具备位置感知能力,因为它们按顺序处理输入,每个时间步的隐藏状态都隐含地编码了位置信息。CNN虽然不是顺序处理,但通过卷积核的滑动窗口机制也能捕捉到局部的位置关系。然而,Transformer的注意力机制本质上是一个集合操作,它同时处理序列中的所有位置,这种并行性虽然带来了计算效率的提升,但也丢失了位置信息。如果没有位置编码,注意力机制就无法区分"我爱你"和"你爱我"这样的句子,因为它只能看到词汇本身,而看不到它们的排列顺序。位置编码的设计需要满足几个关键要求:首先,它必须与词嵌入具有相同的维度,这样才能通过简单的加法操作将位置信息融入到词汇表示中;其次,它需要为每个位置提供唯一的编码,确保模型能够区分不同的位置;最后,这种编码应该具有某种规律性,使得模型能够学习到位置之间的相对关系。
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 ) \begin{array}{r}{P E_{(p o s,2i)}=s i n(p o s/10000^{2i/d_{\mathrm{model}}})}\ {P E_{(p o s,2i+1)}=c o s(p o s/10000^{2i/d_{\mathrm{model}}})}\end{array} PE(pos,2i)=sin(pos/100002i/dmodel) PE(pos,2i+1)=cos(pos/100002i/dmodel)
【解析】这个位置编码公式是Transformer的一个巧妙设计,它使用三角函数来生成位置编码。公式中, p o s pos pos表示词汇在序列中的位置(从0开始), i i i表示编码向量的维度索引(从0到 d m o d e l / 2 − 1 d_{\mathrm{model}}/2-1 dmodel/2−1)。对于每个位置,生成一个 d m o d e l d_{\mathrm{model}} dmodel维的位置编码向量,其中偶数维度使用正弦函数,奇数维度使用余弦函数。这种设计思想是为不同的维度分配不同的频率,频率由 1000 0 2 i / d m o d e l 10000^{2i/d_{\mathrm{model}}} 100002i/dmodel决定。当 i = 0 i=0 i=0时,频率最高,对应最快的振荡;随着 i i i增大,频率逐渐降低,对应越来越慢的振荡。这样,低维度的编码能够捕捉细粒度的位置变化,而高维度的编码则捕捉粗粒度的位置模式。三角函数的周期性特性使得相近位置的编码向量在数值上也比较相近,而远距离位置的编码则差异较大,这为模型学习位置关系提供了良好的基础。更重要的是,正弦和余弦函数的组合使得任意位置的编码都可以通过其他位置的编码进行线性组合来表示,这种线性可组合性为模型学习相对位置关系提供了数学基础。
where 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\pi 2π to 10000 ⋅ 2 π 10000\cdot2\pi 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_{p o s+k} PEpos+k can be represented as a linear function of P E p o s P E_{p o s} PEpos .
【翻译】其中pos是位置, i i i是维度。也就是说,位置编码的每个维度都对应一个正弦曲线。波长形成从 2 π 2\pi 2π到 10000 ⋅ 2 π 10000\cdot2\pi 10000⋅2π的几何级数。我们选择这个函数是因为我们假设它能让模型容易学会按相对位置进行注意,因为对于任何固定偏移 k k k, P E p o s + k PE_{pos+k} PEpos+k可以表示为 P E p o s PE_{pos} PEpos的线性函数。
【解析】这段话进一步解释了位置编码设计的数学原理。每个维度对应一个正弦曲线,这说明位置编码本质上是多个不同频率的正弦波的叠加。波长的几何级数分布是一个关键设计:最短波长为 2 π 2\pi 2π,最长波长为 10000 ⋅ 2 π 10000\cdot2\pi 10000⋅2π,中间的波长按几何级数递增。这种分布确保了编码能够同时捕捉短距离和长距离的位置关系。短波长的正弦波能够区分相邻的位置,而长波长的正弦波则能够编码更大范围内的位置模式。最重要的是线性可表示性质:对于任意固定的偏移 k k k,位置 p o s + k pos+k pos+k的编码可以通过位置 p o s pos pos的编码进行线性变换得到。这个性质基于三角函数的加法公式: sin ( x + k ) = sin ( x ) cos ( k ) + cos ( x ) sin ( k ) \sin(x+k) = \sin(x)\cos(k) + \cos(x)\sin(k) sin(x+k)=sin(x)cos(k)+cos(x)sin(k)和 cos ( x + k ) = cos ( x ) cos ( k ) − sin ( x ) sin ( k ) \cos(x+k) = \cos(x)\cos(k) - \sin(x)\sin(k) cos(x+k)=cos(x)cos(k)−sin(x)sin(k)。这种线性关系使得模型能够更容易地学习相对位置的概念,比如"前一个词"、"后两个词"等相对位置关系,而不需要记住每个绝对位置的具体编码。这种设计大大简化了模型学习位置关系的难度,提高了训练效率和泛化能力。
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.
【翻译】我们还实验了使用学习的位置嵌入[9],发现两个版本产生了几乎相同的结果(见表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 ) \left(x_{1},...,x_{n}\right) (x1,...,xn) to another sequence of equal length ( z 1 , … , z n ) \left(z_{1},\ldots,z_{n}\right) (z1,…,zn) , with x i , z i ∈ R d x_{i},z_{i}\in{\bf{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 ) \left(x_{1},...,x_{n}\right) (x1,...,xn)映射到另一个等长序列 ( z 1 , … , z n ) \left(z_{1},\ldots,z_{n}\right) (z1,…,zn),其中 x i , z i ∈ R d x_{i},z_{i}\in{\bf{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 [ 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]。因此,我们还比较了由不同层类型组成的网络中任意两个输入和输出位置之间的最大路径长度。
【解析】长距离依赖是指序列中相距较远的元素之间的关系,比如在句子"The cat that was sitting on the mat was black"中,"cat"和"was black"之间存在长距离的主谓关系。传统的神经网络在处理这种长距离依赖时面临梯度消失或梯度爆炸的问题。路径长度指的是信息从一个位置传播到另一个位置需要经过的网络层数或计算步骤数。在RNN中,要建立位置i和位置j之间的联系,信息需要逐步传播|i-j|个时间步;在CNN中,需要堆叠多层才能让感受野覆盖到足够远的位置;而在自注意力机制中,任意两个位置之间都可以直接建立联系,路径长度为常数。更短的路径长度不仅有利于梯度的传播,也使得模型能够更直接地学习到远距离位置之间的依赖关系。这种直接的连接方式是Transformer能够在各种NLP任务上取得突破性成果的重要原因之一。
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 [ 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 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时,自注意力层比循环层更快,这在机器翻译中最先进模型使用的句子表示中最常见,如word-piece[38]和byte-pair[31]表示。为了提高涉及很长序列的任务的计算性能,自注意力可以限制为只考虑以相应输出位置为中心的输入序列中大小为 r r r的邻域。这将使最大路径长度增加到 O ( n / r ) O(n/r) O(n/r)。我们计划在未来的工作中进一步研究这种方法。
【解析】这段话详细分析了自注意力机制相对于RNN的优势。首先,在并行化方面,自注意力的巨大优势在于它可以同时计算序列中所有位置对之间的注意力权重,只需要常数个顺序操作步骤,而RNN必须按顺序处理每个时间步,需要n个顺序操作。这种差异在长序列处理时尤为明显。在计算复杂度方面,情况稍微复杂一些。自注意力的复杂度是 O ( n 2 ⋅ d ) O(n^2 \cdot d) O(n2⋅d),因为需要计算n×n的注意力矩阵,每个元素的计算涉及d维向量的操作;而RNN的复杂度是 O ( n ⋅ d 2 ) O(n \cdot d^2) O(n⋅d2),因为每个时间步都需要进行d×d的矩阵乘法。当n<d时, n 2 ⋅ d < n ⋅ d 2 n^2 \cdot d < n \cdot d^2 n2⋅d<n⋅d2,所以自注意力更快。在现代NLP模型中,这个条件通常成立:句子长度(n)通常在几十到几百之间,而模型维度(d)通常在几百到几千之间。Word-piece和byte-pair编码是现代分词技术,它们将词汇分解为更小的子词单元,这样既能处理未见过的词汇,又能保持相对较短的序列长度。对于极长序列,作者提出了局部注意力的解决方案:不让每个位置关注整个序列,而是只关注周围r个位置的邻域。这样可以将计算复杂度从 O ( n 2 ) O(n^2) O(n2)降低到 O ( n ⋅ r ) O(n \cdot r) O(n⋅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(l o g_{k}(n)) O(logk(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 k k . Separable convolutions [ 6 ], however, decrease the complexity considerably, to O ( k ⋅ n ⋅ d + n ⋅ d 2 ) ˙ {\dot{O(k\cdot n\cdot d+n\cdot 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)个卷积层的堆叠,或在扩张卷积[18]的情况下需要 O ( l o g k ( n ) ) O(log_k(n)) O(logk(n))个,这增加了网络中任意两个位置之间最长路径的长度。卷积层通常比循环层更昂贵,昂贵 k k k倍。然而,可分离卷积[6]大大降低了复杂度,降至 O ( k ⋅ n ⋅ d + n ⋅ d 2 ) O(k\cdot n\cdot d+n\cdot d^{2}) O(k⋅n⋅d+n⋅d2)。然而,即使 k = n k=n k=n,可分离卷积的复杂度也等于自注意力层和逐点前馈层的组合,这正是我们在模型中采用的方法。
【解析】这段话分析了卷积神经网络在序列建模中的特点和局限性。CNN的核心特征是局部连接:一个卷积核只能看到固定大小的局部窗口,无法直接建立远距离位置之间的联系。要让CNN具备全局建模能力,需要堆叠多层卷积,让感受野逐渐扩大。对于核大小为k的普通卷积,需要大约n/k层才能让感受野覆盖整个序列;而扩张卷积通过在卷积核中插入空洞来快速扩大感受野,只需要 l o g k ( n ) log_k(n) logk(n)层就能覆盖全序列,这是一个显著的改进。但是,层数的增加直接导致了路径长度的增加,这对长距离依赖的学习是不利的。在计算复杂度方面,标准卷积的复杂度大约是 O ( k ⋅ n ⋅ d 2 ) O(k \cdot n \cdot d^2) O(k⋅n⋅d2),比RNN高出k倍,这是因为卷积需要在每个位置都进行k×d×d的计算。可分离卷积将标准卷积分解为深度卷积和逐点卷积两步,大大减少了参数量和计算量。即使在最极端的情况下(k=n,即卷积核覆盖整个序列),可分离卷积的复杂度也只是相当于自注意力加前馈网络的组合。这个比较很有意思,因为它说明Transformer的设计在某种意义上可以看作是一种特殊的卷积网络,但具有更好的理论性质和实际性能。
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 [ 3 ], which has a shared sourcetarget vocabulary of about 37000 tokens. For English-French, we used the significantly larger WMT 2014 English-French dataset consisting of 36M sentences and split tokens into a 32000 word-piece vocabulary [ 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.
【翻译】我们在标准的WMT 2014英德数据集上进行训练,该数据集包含约450万个句子对。句子使用字节对编码[3]进行编码,该编码具有约37000个标记的共享源-目标词汇表。对于英法翻译,我们使用了更大的WMT 2014英法数据集,包含3600万个句子,并将标记分割为32000个词片词汇表[38]。句子对按近似序列长度进行批处理。每个训练批次包含一组句子对,包含大约25000个源标记和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 GPU的机器上训练我们的模型。对于使用本文中描述的超参数的基础模型,每个训练步骤大约需要0.4秒。我们总共训练基础模型100,000步或12小时。对于我们的大模型(在表3的底行中描述),每步时间为1.0秒。大模型训练了300,000步(3.5天)。
5.3 Optimizer
We used the Adam optimizer [ 20 ] with β 1 = 0.9 \beta_{1}=0.9 β1=0.9 , β 2 = 0.98 \beta_{2}=0.98 β2=0.98 and ϵ = 1 0 − 9 \epsilon=10^{-9} ϵ=10−9 . We varied the learning rate over the course of training, according to the formula:
l r a t e = d m o d e l − 0.5 ⋅ min ( 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 ) l r a t e=d_{\mathrm{model}}^{-0.5}\cdot\operatorname*{min}(s t e p_{-}n u m^{-0.5},s t e p_{-}n u m\cdot w a r m u p_{-}s t e p s^{-1.5}) lrate=dmodel−0.5⋅min(step−num−0.5,step−num⋅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 w a r m u p _ s t e p s = 4000 w a r m u p\_s t e p s=4000 warmup_steps=4000 .
【翻译】我们使用Adam优化器[20],参数设置为 β 1 = 0.9 \beta_{1}=0.9 β1=0.9, β 2 = 0.98 \beta_{2}=0.98 β2=0.98和 ϵ = 1 0 − 9 \epsilon=10^{-9} ϵ=10−9。我们在训练过程中根据以下公式调整学习率。这对应于在前warmup_steps个训练步骤中线性增加学习率,然后按步数的平方根倒数成比例地减少学习率。我们使用 w a r m u p _ s t e p s = 4000 w a r m u p\_s t e p s=4000 warmup_steps=4000。
【解析】公式可以分解为两个阶段:1)预热阶段(warmup phase):在前4000步中,学习率从0线性增长到峰值,这有助于模型在训练初期稳定收敛;2)衰减阶段:之后学习率按照步数的平方根倒数进行衰减,即 s t e p _ n u m − 0.5 step\_num^{-0.5} step_num−0.5,这比常见的指数衰减更温和。整个公式还乘以了 d m o d e l − 0.5 d_{model}^{-0.5} dmodel−0.5,这意味着模型维度越大,学习率越小,这是为了适应更大模型的训练特点。这种学习率调度策略后来成为了Transformer类模型的标准配置,被广泛采用。
5.4 Regularization
We employ three types of regularization during training: 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 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_{d r o p}=0.1 Pdrop=0.1 .
Label Smoothing During training, we employed label smoothing of value ϵ l s = 0.1 \epsilon_{l s}=0.1 ϵls=0.1 [ 36 ]. This hurts perplexity, as the model learns to be more unsure, but improves accuracy and BLEU score.
【翻译】我们在训练过程中采用三种类型的正则化:残差Dropout 我们对每个子层的输出应用dropout[33],在将其添加到子层输入并进行归一化之前。此外,我们对编码器和解码器堆栈中嵌入和位置编码的和应用dropout。对于基础模型,我们使用 P d r o p = 0.1 P_{d r o p}=0.1 Pdrop=0.1的比率。标签平滑 在训练过程中,我们采用值为 ϵ l s = 0.1 \epsilon_{l s}=0.1 ϵls=0.1的标签平滑[36]。这会损害困惑度,因为模型学会了更加不确定,但提高了准确率和BLEU分数。
【解析】这里介绍了三种正则化技术。残差Dropout是在每个子层(如注意力层、前馈网络)的输出上应用dropout,然后再与输入相加并进行层归一化。这种做法不同于传统的在层内部应用dropout,而是在残差连接之前应用,这样可以防止信息过度依赖某些特定的神经元。同时,在输入端也对词嵌入和位置编码的和应用dropout,这有助于防止模型过度拟合特定的位置模式。标签平滑是也一种正则化技术:不是让模型对正确答案给出100%的概率,而是将一小部分概率分配给其他可能的答案。虽然这会让模型在训练数据上的困惑度变差(因为模型变得"不那么自信"),但实际上提高了模型的泛化能力,在测试集上获得更好的BLEU分数。
Table 2: 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.
【翻译】表2:Transformer在英德和英法newstest2014测试中取得了比以前最先进模型更好的BLEU分数,而训练成本只是其中的一小部分。
6 Results
6.1 机器翻译
On the WMT 2014 English-to-German translation task, the big transformer model (Transformer (big) in Table 2) outperforms the best previously reported models (including ensembles) by more than 2 . 0 BLEU, establishing a new state-of-the-art BLEU score of 28 . 4 . The configuration of this model is listed in the bottom line of Table 3. Training took 3 . 5 days on 8 P100 GPUs. Even our base model surpasses all previously published models and ensembles, at a fraction of the training cost of any of the competitive models.
On the WMT 2014 English-to-French translation task, our big model achieves a BLEU score of 41 . 0 , outperforming all of the previously published single models, at less than 1 / 4 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_{d r o p}=0.1 Pdrop=0.1 , instead of 0 . 3 .
For the base models, we used a single model obtained by averaging the last 5 checkpoints, which were written at 10-minute intervals. For the big models, we averaged the last 20 checkpoints. We used beam search with a beam size of 4 and length penalty α = 0.6 \alpha=0.6 α=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 +~50 + 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 .
【翻译】在WMT 2014英德翻译任务上,大型transformer模型(表2中的Transformer (big))比之前报告的最佳模型(包括集成模型)的表现超出2.0 BLEU以上,建立了28.4的新的最先进BLEU分数。该模型的配置列在表3的底行。训练在8个P100 GPU上花费了3.5天。即使是我们的基础模型也超越了所有先前发布的模型和集成模型,而训练成本只是任何竞争模型的一小部分。
在WMT 2014英法翻译任务上,我们的大模型达到了41.0的BLEU分数,超越了所有先前发布的单一模型,训练成本不到先前最先进模型的 1 / 4 1/4 1/4。用于英法翻译训练的Transformer (big)模型使用了dropout率 P d r o p = 0.1 P_{d r o p}=0.1 Pdrop=0.1,而不是0.3。
对于基础模型,我们使用通过平均最后5个检查点获得的单一模型,这些检查点以10分钟间隔写入。对于大模型,我们平均了最后20个检查点。我们使用束搜索,束大小为4,长度惩罚 α = 0.6 \alpha=0.6 α=0.6[38]。这些超参数是在开发集上实验后选择的。我们在推理过程中将最大输出长度设置为输入长度 + 50 +~50 + 50,但在可能的情况下提前终止[38]。
表2总结了我们的结果,并将我们的翻译质量和训练成本与文献中的其他模型架构进行了比较。我们通过将训练时间、使用的GPU数量和每个GPU的持续单精度浮点运算能力的估计值相乘来估计训练模型所使用的浮点运算次数。
6.2 模型变体
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中展示这些结果。
Table 3: 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, newstest2013. Listed perplexities are per-wordpiece, according to our byte-pair encoding, and should not be compared to per-word perplexities.
【翻译】表3:Transformer架构的变体。未列出的值与基础模型相同。所有指标都基于英德翻译开发集newstest2013。列出的困惑度是按词片计算的,根据我们的字节对编码,不应与按词计算的困惑度进行比较。
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 [ 9 ], and observe nearly identical results to the base model.
【翻译】在表3的行(B)中,我们观察到减少注意力键大小 d k d_{k} dk会损害模型质量。这表明确定兼容性并不容易,比点积更复杂的兼容性函数可能是有益的。我们在行©和(D)中进一步观察到,正如预期的那样,更大的模型更好,dropout在避免过拟合方面非常有帮助。在行(E)中,我们用学习的位置嵌入[9]替换正弦位置编码,观察到与基础模型几乎相同的结果。
【解析】这个消融实验系统地验证了Transformer各个组件的重要性。关于注意力头数量的实验(A)揭示了一个重要发现:并非头数越多越好,存在一个最优点。单头注意力性能较差说明多头机制确实有效,但头数过多时性能下降可能是因为参数分散导致每个头学到的表示不够丰富。实验(B)证明了键维度 d k d_k dk的重要性,较小的键维度限制了模型表达复杂兼容性关系的能力,这也暗示未来可能需要探索比简单点积更复杂的注意力计算方式。实验©和(D)验证了深度学习的经典规律:更大的模型通常性能更好,而dropout作为正则化技术对防止过拟合至关重要。实验(E)对比了固定的正弦位置编码和可学习位置嵌入,结果相近说明正弦位置编码的设计是合理的,能够有效编码位置信息。
6.3 英语成分句法分析
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].
【翻译】为了评估Transformer是否能够泛化到其他任务,我们在英语成分句法分析上进行了实验。这个任务提出了特定的挑战:输出受到强结构约束,并且比输入显著更长。此外,RNN序列到序列模型在小数据环境下无法达到最先进的结果[37]。
We trained a 4-layer transformer with d m o d e l = 1024 d_{m o d e l}=1024 dmodel=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.
【翻译】我们在Penn Treebank的华尔街日报(WSJ)部分训练了一个4层的transformer, d m o d e l = 1024 d_{m o d e l}=1024 dmodel=1024,约40K个训练句子。我们还在半监督设置下训练它,使用更大的高置信度和BerkleyParser语料库,约17M个句子[37]。对于仅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 and α = 0.3 \alpha=0.3 α=0.3 for both WSJ only and the semi-supervised setting.
【翻译】我们只进行了少量实验来在Section 22开发集上选择dropout(注意力和残差,见5.4节)、学习率和束搜索大小,所有其他参数与英德基础翻译模型保持不变。在推理过程中,我们将最大输出长度增加到输入长度 + 300 +300 +300。对于仅WSJ和半监督设置,我们都使用束大小为21和 α = 0.3 \alpha=0.3 α=0.3。
Table 4: The Transformer generalizes well to English constituency parsing (Results are on Section 23 of WSJ)
【翻译】表4:Transformer在英语成分句法分析上泛化良好(结果基于WSJ的Section 23)
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].
【翻译】表4中的结果显示,尽管缺乏任务特定的调优,我们的模型表现出人意料地好,产生了比所有先前报告的模型更好的结果,除了循环神经网络语法[8]。
In contrast to RNN sequence-to-sequence models [ 37 ], the Transformer outperforms the BerkeleyParser [29] even when training only on the WSJ training set of 40K sentences.
【翻译】与RNN序列到序列模型[37]相比,即使仅在40K句子的WSJ训练集上训练,Transformer也优于BerkeleyParser[29]。
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. 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.
【翻译】在这项工作中,我们提出了Transformer,这是第一个完全基于注意力机制的序列转换模型,用多头自注意力替代了编码器-解码器架构中最常用的循环层。对于翻译任务,Transformer的训练速度比基于循环层或卷积层的架构要快得多。在WMT 2014英德翻译和WMT 2014英法翻译任务上,我们都达到了新的最先进水平。在前一个任务中,我们的最佳模型甚至超越了所有先前报告的集成模型。我们对基于注意力机制的模型的未来感到兴奋,并计划将它们应用到其他任务中。我们计划将Transformer扩展到涉及文本以外的输入和输出模态的问题,并研究局部的、受限的注意力机制,以有效处理大型输入和输出,如图像、音频和视频。使生成过程更少序列化是我们的另一个研究目标。
注意力可视化
Figure 3: An example of the attention mechanism following long-distance dependencies in the encoder self-attention in layer 5 of 6. Many of the attention heads attend to a distant dependency of the verb ‘making’, completing the phrase ‘making…more difficult’. Attentions here shown only for the word ‘making’. Different colors represent different heads. Best viewed in color.
图3:注意力机制在第5层(共6层)编码器自注意力中跟踪长距离依赖关系的示例。许多注意力头关注动词"making"的远距离依赖关系,完成短语"making…more difficult"。这里仅显示单词"making"的注意力。不同颜色代表不同的注意力头。彩色查看效果最佳。
Figure 4: Two attention heads, also in layer 5 of 6, apparently involved in anaphora resolution. Top: Full attentions for head 5. Bottom: Isolated attentions from just the word ‘its’ for attention heads 5 and 6. Note that the attentions are very sharp for this word.
图4:两个注意力头,同样在第5层(共6层),显然参与了指代消解。上图:注意力头5的完整注意力。下图:仅从单词"its"出发的注意力头5和6的孤立注意力。注意这个单词的注意力非常尖锐。
Figure 5: Many of the attention heads exhibit behaviour that seems related to the structure of the sentence. We give two such examples above, from two different heads from the encoder self-attention at layer 5 of 6. The heads clearly learned to perform different tasks.
图5:许多注意力头表现出似乎与句子结构相关的行为。我们在上面给出了两个这样的例子,来自第5层(共6层)编码器自注意力的两个不同注意力头。这些注意力头显然学会了执行不同的任务。