论文信息
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 avaswani@google.com
————————————————
目录
- Abstract
- Abstract小结:
- Introduction
- Introduction小结:
- Background
- Multi-Head Attention
- Scaled Dot-Product Attention(点积型注意力机制)
- Positional Encoding
- 关于transformer总结:
- Self-attention
- End-to-end memory networks
- Transformer编码器-解码器代码实现
- Model Architecture
- Why Self-Attention
- Training
- Training Data and Batching
- Hardware and Schedule
- Optimizer
- Regularization
- Results
- Machine Translation
- Model Variations
- English Constituency Parsing
- Conclusion
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 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通过成功地将其应用于具有大量和有限训练数据的英语选区分析,可以很好地推广到其他任务。
Abstract小结:
- Transformer,它完全基于注意力机制,完全不用重复和卷积,同时更易于并行化,并且需要的训练时间明显更少。
- Transformer,这是一种避免重复的模型架构,而是完全依赖于注意力机制来绘制输入和输出之间的全局依赖关系。
- Transformer通过成功地将其应用于具有大量和有限训练数据的英语选区分析,可以很好地推广到其他任务。
Introduction
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小时后,可以在翻译质量方面达到最新水平。
Introduction小结:
- 递归神经网络,特别是长短期记忆[13]和门控递归[7]神经网络,已被牢固地确立为序列建模和预测中的最新方法。
- 递归模型通常沿着输入和输出序列的符号位置进行因子计算。将位置与计算时间中的步骤对齐,它们生成一系列隐藏状态ht,作为先前隐藏状态ht的函数−1和位置t的输入。最近的工作通过因子分解技巧[21]和条件计算[32]显著提高了计算效率,同时也提高了后者的模型性能。然而,顺序计算的基本约束仍然存在。
-== 注意力机制已成为各种任务中引人注目的序列建模和转导模型==的组成部分,允许对依赖性进行建模,而不考虑它们在输入或输出序列中的距离[2,19]。然而,在除少数情况外的所有情况下[27],这种注意机制与循环网络一起使用。 - 在这项工作中,我们提出了Transformer,这是一种避免重复的模型架构,而是完全依赖于注意力机制来绘制输入和输出之间的全局依赖关系。Transformer允许显著提高并行化,并且在8个P100 GPU上训练了12小时后,可以在翻译质量方面达到最新水平。
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.
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
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(点积型注意力机制)
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
Positional Encoding:在构建完整的transformer之前,我们还需要一个组件:Positional Encoding。 请注意,Multi Head Attention 没有在序列维度上运行, 一切都在特征维上进行,因此它与序列长度无关。 我们必须向模型提供位置信息,以便它知道输入序列中数据点的相对位置。
transformer 论文里使用三角函数对位置信息进行编码:
为什么使用正弦编码呢? 因为正弦/余弦函数是周期性的,并且它们覆盖[0,1]的范围。所以,尽管事实证明学习的嵌入表现出同样良好的效果,但作者仍然选择使用正弦编码。
关于transformer总结:
transformer使用编码器-解码器体系结构。 编码器(左)处理输入序列并返回特征向量(或存储向量)。 解码器处理目标序列,并合并来自编码器存储器的信息。 解码器的输出是我们模型的预测!
Transformer是第一个完全依靠自我关注来计算其输入和输出表示的转导模型,而不使用序列设计的RNN或卷积。
Self-attention
Self-attention: 有时称为内部注意,是一种将单个序列的不同位置联系起来以计算序列表示的注意机制。自我注意已成功地应用于各种任务,包括阅读理解、摘要摘要、文本蕴涵和学习任务无关的句子表达。
End-to-end memory networks
End-to-end memory networks(端到端记忆网络)基于循环注意力机制,而不是顺序设计的循环,已被证明在简单的语言问答和语言建模任务中表现良好。
Transformer编码器-解码器代码实现
我们可以彼此独立地对编码器/解码器模块进行编码,然后最后将它们组合。 首先,我们先构建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])
Model Architecture
大部分内容在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:
- 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 ueries come from the same place, in this case, the output of the previous layer in the encoder. Each position in the encoder can attend to all positions in the previous layer of the encoder.
- Similarly, self-attention layers in the decoder allow each position in the decoder to attend to all positions in the decoder up to and including that position. We need to prevent leftward information flow in the decoder to preserve the auto-regressive property. We implement this inside of scaled dot-product attention by masking out (setting to −∞) all values in the input of the softmax which orrespond to illegal connections. See Figure 2.
Transformer以三种不同的方式使用multi-head attention:
- 在“编码器-解码器注意”层中,查询来自前一个解码器层,内存键和值来自编码器的输出。这允许解码器中的每个位置在输入序列中的所有位置上出现。这模仿了序列到序列模型中的典型编码器-解码器注意机制,如[38,2,9]。
- 编码器包含自我关注层。在自我关注层中,所有的键、值和查询都来自同一个地方,在本例中,来自编码器中前一层的输出。编码器中的每个位置都可以关注编码器前一层中的所有位置。
- 类似地,解码器中的自关注层允许解码器中的每个位置关注解码器中的所有位置,直到并包括该位置。我们需要防止解码器中的向左信息流,以保持自回归特性。我们通过掩蔽(设置为−∞)
softmax输入中对应于非法连接的所有值。见图2。
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 (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.
一个是每层的总计算复杂性。另一个是可以并行化的计算量,以所需的最小顺序操作数来衡量。第三个是网络中长距离依赖关系之间的路径长度。
Training
This section describes the training regime for our models.
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.
我们在标准WMT 2014英语-德语数据集上进行了训练,该数据集包含约450万个句子对。句子使用字节对编码[3]进行编码,该编码具有约37000个令牌的共享源目标词汇。
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秒。我们对基础模型进行了总共10万步或12小时的训练。对于我们的大模型(见表3的底部),步长为1.0秒。大模型训练了30万步(3.5天)。
Optimizer
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 Pdrop = 0.1.
- Label Smoothing During training, we employed label smoothing of value ?ls = 0.1 [36]. This hurts perplexity, as the model learns to be more unsure, but improves accuracy and BLEU score.
翻译: - 我们将dropout[33]应用于每个子层的输出,然后将其添加到子层输入并归一化。此外,我们将丢弃应用于编码器和解码器堆栈中的嵌入和位置编码的总和。对于基础模型,我们使用Pdrop=0.1的比率。
- 在培训期间,我们采用了价值的标签平滑?ls=0.1[36]。这伤害了困惑,因为模型学会了更加不确定,但提高了准确性和BLEU分数。
Results
Machine Translation
- 在WMT 2014英语到德语翻译任务中,大变压器模型(表2中的变压器(大))以超过2.0
BLEU的成绩超过了之前报告的最佳模型(包括集合),建立了新的最先进的BLEU分数28.4。 - 在WMT
2014英语到法语翻译任务中,我们的大模型获得了41.0的BLEU分数,超过了之前发布的所有单一模型,训练成本低于之前最先进模型的1/4。为英语到法语训练的Transformer(大)模型使用的辍学率Pdrop=0.1,而不是0.3。 - 对于基础模型,我们使用了通过平均最后5个检查点获得的单个模型,这些检查点每隔10分钟写入一次。对于大模型,我们平均了最后20个检查点。我们使用波束搜索,波束大小为4,长度惩罚α=0.6[38]。这些超参数是在开发集上进行实验后选择的。我们将推理期间的最大输出长度设置为输入长度+50,但尽可能提前终止[38]。
- 表2总结了我们的结果,并将我们的翻译质量和培训成本与文献中的其他模型架构进行了比较。我们通过将训练时间、使用的GPU数量和每个GPU 5的持续单精度浮点容量的估计值相乘来估计用于训练模型的浮点运算的数量。
Model Variations
如前一节所述,我们使用了波束搜索,但没有检查点平均。我们在表3中列出了这些结果。
- In Table 3 rows (A), we vary the number of attention heads and the attention key and value dimensions, keeping the amount of computation constant, as described in Section 3.2.2. While single-head attention is 0.9 BLEU worse than the best setting, quality also drops off with too many heads.
- In Table 3 rows (B), we observe that reducing the attention key size 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的行(A)中,我们改变了注意力头部的数量以及注意力键和值维度,保持计算量不变,如第3.2.2节所述。虽然单头部注意力比最佳设置差0.9 BLEU,但由于头部过多,质量也会下降。
- 在表3的行(B)中,我们观察到减少关注键大小dk会损害模型质量。这表明,确定兼容性并不容易,而且比点积更复杂的兼容性功能可能是有益的。我们在第(C)行和第(D)行中进一步观察到,正如预期的那样,更大的模型更好,而丢弃非常有助于避免过度拟合。在第(E)行中,我们用学习的位置嵌入来替换正弦位置编码[9],并观察到与基础模型几乎相同的结果。
English Constituency Parsing
为了评估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]。
Conclusion
- 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.
- 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.
翻译: - Transformer,这是第一个完全基于注意力的序列转导模型,用多头自我注意力取代了编码器-解码器架构中最常用的递归层。
- 对于翻译任务,Transformer可以比基于递归或卷积层的架构更快地进行训练。在WMT 2014英语到德语和WMT 2014英文到法语的翻译任务中,我们都达到了最新的水平。
- 我们对基于注意力的模型的未来感到兴奋,并计划将其应用于其他任务。我们计划将Transformer扩展到涉及文本以外的输入和输出模式的问题,并研究本地受限注意力机制,以有效处理图像、音频和视频等大型输入和输出。