论文信息
Subjects: Computation and Language (cs.CL); Machine Learning (cs.LG)
(1)题目:Attention Is All You Need (你需要的就是关注)
(2)文章下载地址:https://doi.org/10.48550/arXiv.1706.03762
Cite as: arXiv:1706.03762 [cs.CL] (or arXiv:1706.03762v5 [cs.CL] for this version)
(3)相关代码:https://github.com/tensorflow/tensor2tensor
(4)作者信息:Ashish Vaswani
Google Brain [email protected]
————————————————
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 ncoder and decoder through an attention mechanism. We propose a new simple network architecture, the Transformer, based solely on attention mechanisms, dispensing with recurrence and convolutions entirely. Experiments on two machine translation tasks show these models to be superior in quality while being more parallelizable and requiring significantly less time to train. Our model achieves 28.4 BLEU on the WMT 2014 English-to-German translation task, improving over the existing best results, including ensembles, by over 2 BLEU. On the WMT 2014 English-to-French translation task, our odel stablishes 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 eneralizes 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英语到法语翻译任务中,我们的模型在八个GPU上训练了3.5天后,建立了一个新的单模型最先进的BLEU分数41.8,这是文献中最佳模型训练成本的一小部分。我们证明,Transformer通过成功地将其应用于具有大量和有限训练数据的英语选区分析,可以很好地推广到其他任务。
the Transformer, a model architecture eschewing recurrence and instead relying entirely on an attention mechanism to draw global dependencies between input and output.
(Transformer,一种避免重复的模型架构,而是完全依赖于注意力机制来绘制输入和输出之间的全局依赖关系。)
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].
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 ht, as a function of the previous hidden state ht−1 and the input for position t. This inherently sequential nature precludes parallelization within training examples, which becomes critical at longer sequence lengths, as memory constraints limit batching across examples. Recent work has achieved significant improvements in computational efficiency through factorization tricks [21] and conditional computation [32], while also improving model performance in case of the latter. The fundamental constraint of sequential computation, however, remains.
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.
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.
递归神经网络,特别是长短期记忆[13]和门控递归[7]神经网络,已被牢固地确立为序列建模和预测中的最新方法语言建模和机器翻译等转导问题[35,2,5]。此后,许多努力继续推动递归语言模型和编码器-解码器架构的边界[38,24,15]。
递归模型通常沿着输入和输出序列的符号位置进行因子计算。将位置与计算时间中的步骤对齐,它们生成一系列隐藏状态ht,作为先前隐藏状态ht的函数−1和位置t的输入。这种固有的顺序性排除了训练示例内的并行化,这在较长的序列长度下变得至关重要,因为内存约束限制了示例之间的批处理。最近的工作通过因子分解技巧[21]和条件计算[32] 显著提高了计算效率,同时也提高了后者的模型性能。然而,顺序计算的基本约束仍然存在。
注意力机制已成为各种任务中引人注目的序列建模和转导模型的组成部分,允许对依赖性进行建模,而不考虑它们在输入或输出序列中的距离[2,19]。然而,在除少数情况外的所有情况下[27],这种注意机制与循环网络一起使用。
在这项工作中,我们提出了Transformer,这是一种避免重复的模型架构,而是完全依赖于注意力机制来绘制输入和输出之间的全局依赖关系。
Transformer允许显著提高并行化,并且在8个P100 GPU上训练了12小时后,可以在翻译质量方面达到最新水平。
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.
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].
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].
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].
减少顺序计算的目标也构成了扩展神经GPU[16]、ByteNet[18]和ConvS2S[9]的基础,所有这些都使用卷积神经网络 作为基本构建块,并行计算所有输入和输出位置的隐藏表示。在这些模型中,关联来自两个任意输入或输出位置的信号所需的操作数量随着位置之间的距离而增加,ConvS2S为线性,ByteNet为对数。这使得学习远距离位置之间的相关性变得更加困难[12]。在Transformer中,这被减少到恒定数量的操作,尽管代价是由于平均注意力加权位置而降低了有效分辨率,如第3.2节所述,我们通过多头注意力抵消了这种影响。
自我注意,有时称为内部注意,是一种将单个序列的不同位置联系起来以计算序列表示的注意机制。自我注意已成功地应用于各种任务,包括阅读理解、摘要摘要、文本蕴涵和学习任务无关的句子表达[4,27,28,22]。
端到端记忆网络基于循环注意力机制 ,而不是序列设计的循环,已证明在简单的语言问答和语言建模任务中表现良好[34]。
然而,据我们所知,Transformer是第一个完全依靠自我关注来计算其输入和输出表示的转导模型,而不使用序列设计的RNN或卷积。 在接下来的章节中,我们将描述Transformer,激发自我关注,并讨论其相对于[17,18]和[9]等模型的优势。
注:Multi-Head Attention,Scaled Dot-Product Attention,Positional Encoding介绍如下:
Multi-Head Attention: 对于同一个文本,一个Attention获得一个表示空间,如果多个Attention,则可以获得多个不同的表示空间。基于这种想法,就有了Multi-Head Attention。换句话说,Multi-Head Attention为Attention提供了多个“representation subspaces”。因为在每个Attention中,采用不同的Query / Key / Value权重矩阵,每个矩阵都是随机初始化生成的。然后通过训练,将词嵌入投影到不同的“representation subspaces(表示子空间)”中。
Multi-Head Attention与经典的Attention一样,并不是一个独立的结构,自身无法进行训练。Multi-Head Attention也可以堆叠,形成深度结构。应用场景:可以作为文本分类、文本聚类、关系抽取等模型的特征表示部分。
Scaled Dot-Product Attention(点积型注意力机制):在实际应用中,经常会用到 Attention 机制,其中最常用的是 Scaled Dot-Product Attention,它是通过计算query和key之间的点积 来作为 之间的相似度。
Scaled 指的是 Q和K计算得到的相似度 再经过了一定的量化,具体就是 除以 根号下K_dim;
Dot-Product 指的是 Q和K之间 通过计算点积作为相似度;
Mask 可选择性 目的是将 padding的部分 填充负无穷,这样算softmax的时候这里就attention为0,从而避免padding带来的影响
在数学上,Scaled Dot-Product Attention表示为:
Q,K和V是经过卷积后得到的特征,其形状为(batch_size,seq_length,num_features)。
将查询(Q)和键(K)相乘会得到(batch_size,seq_length,seq_length)特征,这大致告诉我们序列中每个元素的重要性,确定我们“注意”哪些元素。 注意数组使用softmax标准化,因此所有权重之和为1。 最后,注意力将通过矩阵乘法应用于值(V)数组。scaled dot-product attention 的代码 非常简单-只需几个矩阵乘法,再加上softmax函数。
Positional Encoding:在构建完整的transformer之前,我们还需要一个组件:Positional Encoding。 请注意,Multi Head Attention 没有在序列维度上运行, 一切都在特征维上进行,因此它与序列长度无关。 我们必须向模型提供位置信息,以便它知道输入序列中数据点的相对位置。
transformer 论文里使用三角函数对位置信息进行编码:
为什么使用正弦编码呢? 因为正弦/余弦函数是周期性的,并且它们覆盖[0,1]的范围。所以,尽管事实证明学习的嵌入表现出同样良好的效果,但作者仍然选择使用正弦编码。
transformer使用编码器-解码器体系结构。 编码器(左)处理输入序列并返回特征向量(或存储向量)。 解码器处理目标序列,并合并来自编码器存储器的信息。 解码器的输出是我们模型的预测!
Transformer是第一个完全依靠自我关注来计算其输入和输出表示的转导模型,而不使用序列设计的RNN或卷积。
Self-attention: 有时称为内部注意,是一种将单个序列的不同位置联系起来以计算序列表示的注意机制。自我注意已成功地应用于各种任务,包括阅读理解、摘要摘要、文本蕴涵和学习任务无关的句子表达。
End-to-end memory networks(端到端记忆网络)基于循环注意力机制,而不是顺序设计的循环,已被证明在简单的语言问答和语言建模任务中表现良好。
我们可以彼此独立地对编码器/解码器模块进行编码,然后最后将它们组合。 首先,我们先构建encoder。如下:
def feed_forward(dim_input: int = 512, dim_feedforward: int = 2048) -> nn.Module:
return nn.Sequential(
nn.Linear(dim_input, dim_feedforward),
nn.ReLU(),
nn.Linear(dim_feedforward, dim_input),
)
class Residual(nn.Module):
def __init__(self, sublayer: nn.Module, dimension: int, dropout: float = 0.1):
super().__init__()
self.sublayer = sublayer
self.norm = nn.LayerNorm(dimension)
self.dropout = nn.Dropout(dropout)
def forward(self, *tensors: Tensor) -> Tensor:
# Assume that the "value" tensor is given last, so we can compute the
# residual. This matches the signature of 'MultiHeadAttention'.
return self.norm(tensors[-1] + self.dropout(self.sublayer(*tensors)))
class TransformerEncoderLayer(nn.Module):
def __init__(
self,
dim_model: int = 512,
num_heads: int = 6,
dim_feedforward: int = 2048,
dropout: float = 0.1,
):
super().__init__()
dim_k = dim_v = dim_model // num_heads
self.attention = Residual(
MultiHeadAttention(num_heads, dim_model, dim_k, dim_v),
dimension=dim_model,
dropout=dropout,
)
self.feed_forward = Residual(
feed_forward(dim_model, dim_feedforward),
dimension=dim_model,
dropout=dropout,
)
def forward(self, src: Tensor) -> Tensor:
src = self.attention(src, src, src)
return self.feed_forward(src)
class TransformerEncoder(nn.Module):
def __init__(
self,
num_layers: int = 6,
dim_model: int = 512,
num_heads: int = 8,
dim_feedforward: int = 2048,
dropout: float = 0.1,
):
super().__init__()
self.layers = nn.ModuleList([
TransformerEncoderLayer(dim_model, num_heads, dim_feedforward, dropout)
for _ in range(num_layers)
])
def forward(self, src: Tensor) -> Tensor:
seq_len, dimension = src.size(1), src.size(2)
src += position_encoding(seq_len, dimension)
for layer in self.layers:
src = layer(src)
return src
解码器模块非常相似。只是一些小的区别:
解码器接受两个参数(target和memory),而不是一个;
每层有两个多头部注意力模块,而不是一个;
第二个多头注意力接受两个输入的记忆;
解码器中包含了self-attention和cross-attention。
class TransformerDecoderLayer(nn.Module):
def __init__(
self,
dim_model: int = 512,
num_heads: int = 6,
dim_feedforward: int = 2048,
dropout: float = 0.1,
):
super().__init__()
dim_k = dim_v = dim_model // num_heads
self.attention_1 = Residual(
MultiHeadAttention(num_heads, dim_model, dim_k, dim_v),
dimension=dim_model,
dropout=dropout,
)
self.attention_2 = Residual(
MultiHeadAttention(num_heads, dim_model, dim_k, dim_v),
dimension=dim_model,
dropout=dropout,
)
self.feed_forward = Residual(
feed_forward(dim_model, dim_feedforward),
dimension=dim_model,
dropout=dropout,
)
def forward(self, tgt: Tensor, memory: Tensor) -> Tensor:
tgt = self.attention_1(tgt, tgt, tgt)
tgt = self.attention_2(memory, memory, tgt)#⬅这句有可能是tgt = self.attention_2(tgt,memory,memory)
return self.feed_forward(tgt)
class TransformerDecoder(nn.Module):
def __init__(
self,
num_layers: int = 6,
dim_model: int = 512,
num_heads: int = 8,
dim_feedforward: int = 2048,
dropout: float = 0.1,
):
super().__init__()
self.layers = nn.ModuleList([
TransformerDecoderLayer(dim_model, num_heads, dim_feedforward, dropout)
for _ in range(num_layers)
])
self.linear = nn.Linear(dim_model, dim_model)
def forward(self, tgt: Tensor, memory: Tensor) -> Tensor:
seq_len, dimension = tgt.size(1), tgt.size(2)
tgt += position_encoding(seq_len, dimension)
for layer in self.layers:
tgt = layer(tgt, memory)
return torch.softmax(self.linear(tgt), dim=-1)
最后,我们需要将所有内容打包成一个Transformer类,只要把一个编码器和解码器放在一起,然后以正确的顺序通过它们传递数据。
class Transformer(nn.Module):
def __init__(
self,
num_encoder_layers: int = 6,
num_decoder_layers: int = 6,
dim_model: int = 512,
num_heads: int = 6,
dim_feedforward: int = 2048,
dropout: float = 0.1,
activation: nn.Module = nn.ReLU(),
):
super().__init__()
self.encoder = TransformerEncoder(
num_layers=num_encoder_layers,
dim_model=dim_model,
num_heads=num_heads,
dim_feedforward=dim_feedforward,
dropout=dropout,
)
self.decoder = TransformerDecoder(
num_layers=num_decoder_layers,
dim_model=dim_model,
num_heads=num_heads,
dim_feedforward=dim_feedforward,
dropout=dropout,
)
def forward(self, src: Tensor, tgt: Tensor) -> Tensor:
return self.decoder(tgt, self.encoder(src))
让我们创建一个简单的测试,作为实现的健全性检查。我们可以构造src和tgt的随机张量,检查我们的模型执行没有错误,并确认输出张量具有正确的形状。
src = torch.rand(64, 16, 512)
tgt = torch.rand(64, 16, 512)
out = Transformer()(src, tgt)
print(out.shape)
# torch.Size([64, 16, 512])
大部分内容在background中介绍过,前面提及过的在这里不再赘述。
1.大多数竞争性神经序列转导模型具有编码器-解码器结构[5,2,35]。
这里,编码器将符号表示的输入序列(x1,…,xn)映射到连续表示的序列z=(z1,…,zn)。给定z,解码器然后一次生成一个元素的符号输出序列(y1,…,ym)。在每个步骤中,模型都是自回归的[10],在生成下一个符号时,使用先前生成的符号作为附加输入。
Transformer遵循这种整体架构,为编码器和解码器使用堆叠的自关注和逐点、完全连接的层,分别如图1的左半部分和右半部分所示。
2.Applications of Attention in our Model
The Transformer uses multi-head attention in three different ways:
Transformer以三种不同的方式使用multi-head 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 (x1, …, xn) to another sequence of equal length (z1, …, zn), with 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.
在本节中,我们将Self-Attention的各个方面与递归层和卷积层进行了比较,递归层和褶积层通常用于将一个可变长度的符号表示序列(x1,…,xn)映射到另一个等长序列(z1,…,zn),xi,zi∈ Rd,例如典型的序列转导编码器或解码器中的隐藏层。为了激励我们使用Self-Attention,我们考虑了三个需求:
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.
一个是每层的总计算复杂性。另一个是可以并行化的计算量,以所需的最小顺序操作数来衡量。第三个是网络中长距离依赖关系之间的路径长度。
This section describes the training regime for our models.
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.
我们在标准WMT 2014英语-德语数据集上进行了训练,该数据集包含约450万个句子对。句子使用字节对编码[3]进行编码,该编码具有约37000个令牌的共享源目标词汇。
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秒。我们对基础模型进行了总共10万步或12小时的训练。对于我们的大模型(见表3的底部),步长为1.0秒。大模型训练了30万步(3.5天)。
We employ three types of regularization during training:
如前一节所述,我们使用了波束搜索,但没有检查点平均。我们在表3中列出了这些结果。
为了评估Transformer是否可以推广到其他任务,我们对英语选区分析进行了实验。这项任务提出了具体的挑战:产出受到强烈的结构性影响并且明显长于输入。此外,RNN序列到序列模型还无法在小数据状态下获得最先进的结果[37]。
我们在《华尔街日报》(WSJ)的Penn Treebank[25]部分训练了一个dmodel=1024的4层转换器,大约有40K个训练句子。我们还在半监督环境中对其进行了训练,使用了更大的高信度和BerkleyParser语料库,其中包含大约1700万个句子[37]。对于仅WSJ设置,我们使用了16K令牌的词汇表,对于半监督设置,使用了32K令牌的单词表。
我们只进行了少量实验,以选择第22节开发集上的辍学、注意力和剩余(第5.4节)、学习率和光束大小,所有其他参数与英语到德语基础翻译模型保持不变。在推断过程中,我们将最大输出长度增加到输入长度+300。对于仅WSJ和半监督设置,我们使用了21和α=0.3的波束大小。
我们在表4中的结果表明,尽管缺乏特定于任务的调整,但我们的模型表现出奇地好,产生的结果优于除递归神经网络语法外的所有先前报告的模型[8]。
与RNN序列到序列模型[37]相比,即使仅在40K句的WSJ训练集上进行训练,Transformer也优于BerkeleyParser[29]。