# The Annotated Transformer

注释版 Transformer

**———————-**

**There is now a new version of this blog post updated for modern PyTorch.现在有一个为现代 PyTorch 更新的新版本这篇博客文章。**

**———————-**

The Transformer from “Attention is All You
Need” has been on a lot of people’s minds
over the last year. Besides producing major improvements in translation quality,
it provides a new architecture for many other NLP tasks. The paper itself is
very clearly written, but the conventional wisdom has been that it is quite
difficult to implement correctly.

Transformer 来自“注意力就是一切”在过去一年中一直占据着很多人的思维。除了在翻译质量方面取得重大改进外，它还为许多其他自然语言处理任务提供了新的架构。这篇论文本身写得非常清晰，但传统观点是实现正确相当困难。

In this post I present an “annotated” version of the paper in the form of a
line-by-line implementation. I have reordered and deleted some sections from the
original paper and added comments throughout. This document itself is a working
notebook, and should be a completely usable implementation. In total there are
400 lines of library code which can process 27,000 tokens per second on 4 GPUs.

在这篇文章中，我以逐行实现的形式呈现了论文的“注释”版本。我重新排列并删除了原始论文中的一些部分，并在整个过程中添加了评论。这个文档本身是一个工作笔记本，应该是一个完全可用的实现。总共有 400 行库代码，可以在 4 个 GPU 上每秒处理 27,000 个标记。

To follow along you will first need to install
PyTorch. The complete notebook is also
available on
github or on
Google
Colab with free GPUs.

要跟着进行，您首先需要安装PyTorch。完整的笔记本也可以在github或 Google Colab上免费使用 GPU。

Note this is merely a starting point for researchers and interested developers.
The code here is based heavily on our OpenNMT packages.
(If helpful feel free to cite.) For other full-sevice
implementations of the model check-out
Tensor2Tensor (tensorflow) and
Sockeye (mxnet).

请注意，这仅仅是研究人员和感兴趣的开发者的起点。这里的代码主要基于我们的OpenNMT软件包。（如果有帮助，请随意引用。）对于模型的其他完整服务实现，请查看Tensor2Tensor（tensorflow）和Sockeye（mxnet）。

- Alexander Rush (@harvardnlp or
srush@seas.harvard.edu), with help from Vincent Nguyen and Guillaume Klein

Alexander Rush (@harvardnlp 或 srush@seas.harvard.edu)，在 Vincent Nguyen 和 Guillaume Klein 的帮助下

# Prelims 初步选拔

Table of Contents 目录

- Prelims 初步选拔
- Background 背景
- Model Architecture 模型架构
- Training 培训
- A First Example 第一个例子
- A Real World Example 一个真实世界的例子
- Additional Components: BPE, Search, Averaging

额外组件：BPE、搜索、平均 - Results 结果
- Conclusion 结论

My comments are blockquoted. The main text is all from the paper itself.

我的评论被引用为块引用。主要文本全部来自论文本身。

# Background 背景

The goal of reducing sequential computation also forms the foundation of the
Extended Neural GPU, ByteNet and ConvS2S, 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. 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.

减少顺序计算的目标也构成了 Extended Neural GPU、ByteNet 和 ConvS2S 的基础，所有这些模型都使用卷积神经网络作为基本构建模块，在所有输入和输出位置并行计算隐藏表示。在这些模型中，需要执行的操作数量与两个任意输入或输出位置之间的距离成正比增长，对于 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. 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.

自注意力，有时称为内部注意力，是一种注意机制，涉及计算序列的不同位置以计算序列的表示。自注意力已成功应用于各种任务，包括阅读理解、抽象总结、文本蕴涵和学习任务独立的句子表示。端到端记忆网络基于循环注意机制，而不是序列对齐循环，并已被证明在简单语言问答和语言建模任务上表现良好。

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 sequence aligned RNNs or convolution.

# Model Architecture

Most competitive neural sequence transduction models have an encoder-decoder structure (cite). Here, the encoder maps an input sequence of symbol representations $({x}_{1},\dots ,{x}_{n})$ to a sequence of continuous representations $\mathbf{z}=({z}_{1},\dots ,{z}_{n})$. Given $\mathbf{z}$, the decoder then generates an output sequence $({y}_{1},\dots ,{y}_{m})$ of symbols one element at a time. At each step the model is auto-regressive (cite), consuming the previously generated symbols as additional input when generating the next.

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.

## Encoder and Decoder Stacks

### Encoder

The encoder is composed of a stack of $N=6$ identical layers.

We employ a residual connection (cite) around each of the two sub-layers, followed by layer normalization (cite).

That is, the output of each sub-layer is $\mathrm{L}\mathrm{a}\mathrm{y}\mathrm{e}\mathrm{r}\mathrm{N}\mathrm{o}\mathrm{r}\mathrm{m}(x+\mathrm{S}\mathrm{u}\mathrm{b}\mathrm{l}\mathrm{a}\mathrm{y}\mathrm{e}\mathrm{r}(x))$, where $\mathrm{S}\mathrm{u}\mathrm{b}\mathrm{l}\mathrm{a}\mathrm{y}\mathrm{e}\mathrm{r}(x)$ is the function implemented by the sub-layer itself. We apply dropout (cite) to the output of each sub-layer, before it is added to the sub-layer input and normalized.

To facilitate these residual connections, all sub-layers in the model, as well as the embedding layers, produce outputs of dimension ${d}_{\text{model}}=512$.

Each layer has two sub-layers. The first is a multi-head self-attention mechanism, and the second is a simple, position-wise fully connected feed- forward network.

### Decoder

The decoder is also composed of a stack of $N=6$ identical layers.

In addition to the two sub-layers in each encoder layer, the decoder inserts a third sub-layer, which performs multi-head attention over the output of the encoder stack. Similar to the encoder, we employ residual connections around each of the sub-layers, followed by layer normalization.

We also modify the self-attention sub-layer in the decoder stack to prevent positions from attending to subsequent positions. This masking, combined with fact that the output embeddings are offset by one position, ensures that the predictions for position $i$ can depend only on the known outputs at positions less than $i$.

Below the attention mask shows the position each tgt word (row) is allowed to look at (column). Words are blocked for attending to future words during training.

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

We call our particular attention “Scaled Dot-Product Attention”. The input consists of queries and keys of dimension ${d}_{k}$, and values of dimension ${d}_{v}$. We compute the dot products of the query with all keys, divide each by $\sqrt{{d}_{k}}$, and apply a softmax function to obtain the weights on the values.

In practice, we compute the attention function on a set of queries simultaneously, packed together into a matrix $Q$. The keys and values are also packed together into matrices $K$ and $V$. We compute the matrix of outputs as:

$$\mathrm{A}\mathrm{t}\mathrm{t}\mathrm{e}\mathrm{n}\mathrm{t}\mathrm{i}\mathrm{o}\mathrm{n}(Q,K,V)=\mathrm{s}\mathrm{o}\mathrm{f}\mathrm{t}\mathrm{m}\mathrm{a}\mathrm{x}(\frac{Q{K}^{T}}{\sqrt{{d}_{k}}})V$$The two most commonly used attention functions are additive attention (cite), and dot-product (multiplicative) attention. Dot-product attention is identical to our algorithm, except for the scaling factor of $\frac{1}{\sqrt{{d}_{k}}}$. Additive attention computes the compatibility function using a feed-forward network with a single hidden layer. While the two are similar in theoretical complexity, dot-product attention is much faster and more space-efficient in practice, since it can be implemented using highly optimized matrix multiplication code.

While for small values of ${d}_{k}$ the two mechanisms perform similarly, additive attention outperforms dot product attention without scaling for larger values of ${d}_{k}$ (cite). We suspect that for large values of ${d}_{k}$, the dot products grow large in magnitude, pushing the softmax function into regions where it has extremely small gradients (To illustrate why the dot products get large, assume that the components of $q$ and $k$ are independent random variables with mean $0$ and variance $1$. Then their dot product, $q\cdot k=\sum _{i=1}^{{d}_{k}}{q}_{i}{k}_{i}$, has mean $0$ and variance ${d}_{k}$.). To counteract this effect, we scale the dot products by $\frac{1}{\sqrt{{d}_{k}}}$.

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. $\mathrm{M}\mathrm{u}\mathrm{l}\mathrm{t}\mathrm{i}\mathrm{H}\mathrm{e}\mathrm{a}\mathrm{d}(Q,K,V)=\mathrm{C}\mathrm{o}\mathrm{n}\mathrm{c}\mathrm{a}\mathrm{t}(\mathrm{h}\mathrm{e}\mathrm{a}{\mathrm{d}}_{1},...,\mathrm{h}\mathrm{e}\mathrm{a}{\mathrm{d}}_{\mathrm{h}}){W}^{O}\phantom{\rule{0ex}{0ex}}\text{where}\text{}\mathrm{h}\mathrm{e}\mathrm{a}{\mathrm{d}}_{\mathrm{i}}=\mathrm{A}\mathrm{t}\mathrm{t}\mathrm{e}\mathrm{n}\mathrm{t}\mathrm{i}\mathrm{o}\mathrm{n}(Q{W}_{i}^{Q},K{W}_{i}^{K},V{W}_{i}^{V})$

Where the projections are parameter matrices ${W}_{i}^{Q}\in {\mathbb{R}}^{{d}_{\text{model}}\times {d}_{k}}$, ${W}_{i}^{K}\in {\mathbb{R}}^{{d}_{\text{model}}\times {d}_{k}}$, ${W}_{i}^{V}\in {\mathbb{R}}^{{d}_{\text{model}}\times {d}_{v}}$ and ${W}^{O}\in {\mathbb{R}}^{h{d}_{v}\times {d}_{\text{model}}}$. In this work we employ $h=8$ parallel attention layers, or heads. For each of these we use ${d}_{k}={d}_{v}={d}_{\text{model}}/h=64$. Due to the reduced dimension of each head, the total computational cost is similar to that of single-head attention with full dimensionality.

### Applications of Attention in our Model

The Transformer uses multi-head attention in three different ways: 1) 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 (cite).

2) 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.

3) 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 $-\mathrm{\infty}$) all values in the input of the softmax which correspond to illegal connections.

## Position-wise Feed-Forward Networks

In addition to attention sub-layers, each of the layers in our encoder and decoder contains a fully connected feed-forward network, which is applied to each position separately and identically. This consists of two linear transformations with a ReLU activation in between.

$$\mathrm{F}\mathrm{F}\mathrm{N}(x)=max(0,x{W}_{1}+{b}_{1}){W}_{2}+{b}_{2}$$While the linear transformations are the same across different positions, they use different parameters from layer to layer. Another way of describing this is as two convolutions with kernel size 1. The dimensionality of input and output is ${d}_{\text{model}}=512$, and the inner-layer has dimensionality ${d}_{ff}=2048$.

## 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}_{\text{model}}$. We also use the usual learned linear transformation and softmax function to convert the decoder output to predicted next-token probabilities. In our model, we share the same weight matrix between the two embedding layers and the pre-softmax linear transformation, similar to (cite). In the embedding layers, we multiply those weights by $\sqrt{{d}_{\text{model}}}$.

## 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}_{\text{model}}$ as the embeddings, so that the two can be summed. There are many choices of positional encodings, learned and fixed (cite).

In this work, we use sine and cosine functions of different frequencies: $P{E}_{(pos,2i)}=sin(pos/{10000}^{2i/{d}_{\text{model}}})$

$P{E}_{(pos,2i+1)}=cos(pos/{10000}^{2i/{d}_{\text{model}}})$ where $pos$ is the position and $i$ is the dimension. That is, each dimension of the positional encoding corresponds to a sinusoid. The wavelengths form a geometric progression from $2\pi $ to $10000\cdot 2\pi $. We chose this function because we hypothesized it would allow the model to easily learn to attend by relative positions, since for any fixed offset $k$, $P{E}_{pos+k}$ can be represented as a linear function of $P{E}_{pos}$.

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}_{drop}=0.1$.

Below the positional encoding will add in a sine wave based on position. The frequency and offset of the wave is different for each dimension.

We also experimented with using learned positional embeddings (cite) instead, and found that the two versions produced nearly identical results. We chose the sinusoidal version because it may allow the model to extrapolate to sequence lengths longer than the ones encountered during training.

## Full Model

Here we define a function that takes in hyperparameters and produces a full model.

# Training

This section describes the training regime for our models.

We stop for a quick interlude to introduce some of the tools needed to train a standard encoder decoder model. First we define a batch object that holds the src and target sentences for training, as well as constructing the masks.

## Batches and Masking

Next we create a generic training and scoring function to keep track of loss. We pass in a generic loss compute function that also handles parameter updates.

## Training Loop

## 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, which has a shared source-target 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.

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.

We will use torch text for batching. This is discussed in more detail below. Here we create batches in a torchtext function that ensures our batch size padded to the maximum batchsize does not surpass a threshold (25000 if we have 8 gpus).

## 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, step time was 1.0 seconds. The big models were trained for 300,000 steps (3.5 days).

## Optimizer

We used the Adam optimizer (cite) with ${\beta}_{1}=0.9$, ${\beta}_{2}=0.98$ and $\u03f5={10}^{-9}$. We varied the learning rate over the course of training, according to the formula: $lrate={d}_{\text{model}}^{-0.5}\cdot min({step\mathrm{\_}num}^{-0.5},step\mathrm{\_}num\cdot {warmup\mathrm{\_}steps}^{-1.5})$ This corresponds to increasing the learning rate linearly for the first $warmu{p}_{s}teps$ training steps, and decreasing it thereafter proportionally to the inverse square root of the step number. We used $warmu{p}_{s}teps=4000$.

Note: This part is very important. Need to train with this setup of the model.

Example of the curves of this model for different model sizes and for optimization hyperparameters.

## Regularization

### Label Smoothing

During training, we employed label smoothing of value ${\u03f5}_{ls}=0.1$ (cite). This hurts perplexity, as the model learns to be more unsure, but improves accuracy and BLEU score.

We implement label smoothing using the KL div loss. Instead of using a one-hot target distribution, we create a distribution that has

`confidence`

of the correct word and the rest of the`smoothing`

mass distributed throughout the vocabulary.

Here we can see an example of how the mass is distributed to the words based on confidence.

Label smoothing actually starts to penalize the model if it gets very confident about a given choice.

# A First Example

We can begin by trying out a simple copy-task. Given a random set of input symbols from a small vocabulary, the goal is to generate back those same symbols.

## Synthetic Data

## Loss Computation

## Greedy Decoding

```
Epoch Step: 1 Loss: 3.023465 Tokens per Sec: 403.074173
Epoch Step: 1 Loss: 1.920030 Tokens per Sec: 641.689380
1.9274832487106324
Epoch Step: 1 Loss: 1.940011 Tokens per Sec: 432.003378
Epoch Step: 1 Loss: 1.699767 Tokens per Sec: 641.979665
1.657595729827881
Epoch Step: 1 Loss: 1.860276 Tokens per Sec: 433.320240
Epoch Step: 1 Loss: 1.546011 Tokens per Sec: 640.537198
1.4888023376464843
Epoch Step: 1 Loss: 1.682198 Tokens per Sec: 432.092305
Epoch Step: 1 Loss: 1.313169 Tokens per Sec: 639.441857
1.3485562801361084
Epoch Step: 1 Loss: 1.278768 Tokens per Sec: 433.568756
Epoch Step: 1 Loss: 1.062384 Tokens per Sec: 642.542067
0.9853351473808288
Epoch Step: 1 Loss: 1.269471 Tokens per Sec: 433.388727
Epoch Step: 1 Loss: 0.590709 Tokens per Sec: 642.862135
0.5686767101287842
Epoch Step: 1 Loss: 0.997076 Tokens per Sec: 433.009746
Epoch Step: 1 Loss: 0.343118 Tokens per Sec: 642.288427
0.34273059368133546
Epoch Step: 1 Loss: 0.459483 Tokens per Sec: 434.594030
Epoch Step: 1 Loss: 0.290385 Tokens per Sec: 642.519464
0.2612409472465515
Epoch Step: 1 Loss: 1.031042 Tokens per Sec: 434.557008
Epoch Step: 1 Loss: 0.437069 Tokens per Sec: 643.630322
0.4323212027549744
Epoch Step: 1 Loss: 0.617165 Tokens per Sec: 436.652626
Epoch Step: 1 Loss: 0.258793 Tokens per Sec: 644.372296
0.27331129014492034
```

This code predicts a translation using greedy decoding for simplicity.

```
1 2 3 4 5 6 7 8 9 10
[torch.LongTensor of size 1x10]
```

# A Real World Example

Now we consider a real-world example using the IWSLT German-English Translation task. This task is much smaller than the WMT task considered in the paper, but it illustrates the whole system. We also show how to use multi-gpu processing to make it really fast.

## Data Loading

We will load the dataset using torchtext and spacy for tokenization.

Batching matters a ton for speed. We want to have very evenly divided batches, with absolutely minimal padding. To do this we have to hack a bit around the default torchtext batching. This code patches their default batching to make sure we search over enough sentences to find tight batches.

## Iterators

## Multi-GPU Training

Finally to really target fast training, we will use multi-gpu. This code implements multi-gpu word generation. It is not specific to transformer so I won’t go into too much detail. The idea is to split up word generation at training time into chunks to be processed in parallel across many different gpus. We do this using pytorch parallel primitives:

- replicate - split modules onto different gpus.
- scatter - split batches onto different gpus
- parallel_apply - apply module to batches on different gpus
- gather - pull scattered data back onto one gpu.
- nn.DataParallel - a special module wrapper that calls these all before evaluating.

Now we create our model, criterion, optimizer, data iterators, and paralelization

Now we train the model. I will play with the warmup steps a bit, but everything else uses the default parameters. On an AWS p3.8xlarge with 4 Tesla V100s, this runs at ~27,000 tokens per second with a batch size of 12,000

## Training the System

Once trained we can decode the model to produce a set of translations. Here we simply translate the first sentence in the validation set. This dataset is pretty small so the translations with greedy search are reasonably accurate.

```
Translation: <unk> <unk> . In my language , that means , thank you very much .
Gold: <unk> <unk> . It means in my language , thank you very much .
```

# Additional Components: BPE, Search, Averaging

So this mostly covers the transformer model itself. There are four aspects that we didn’t cover explicitly. We also have all these additional features implemented in OpenNMT-py.

1) BPE/ Word-piece: We can use a library to first preprocess the data into subword units. See Rico Sennrich’s subword- nmt implementation. These models will transform the training data to look like this:

▁Die ▁Protokoll datei ▁kann ▁ heimlich ▁per ▁E - Mail ▁oder ▁FTP ▁an ▁einen ▁bestimmte n ▁Empfänger ▁gesendet ▁werden .

2) Shared Embeddings: When using BPE with shared vocabulary we can share the same weight vectors between the source / target / generator. See the (cite) for details. To add this to the model simply do this:

3) Beam Search: This is a bit too complicated to cover here. See the OpenNMT- py for a pytorch implementation.

4) Model Averaging: The paper averages the last k checkpoints to create an ensembling effect. We can do this after the fact if we have a bunch of models:

# Results

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 the training cost of the previous state-of-the-art model. The Transformer (big) model trained for English-to-French used dropout rate Pdrop = 0.1, instead of 0.3.

The code we have written here is a version of the base model. There are fully trained version of this system available here (Example Models).

With the addtional extensions in the last section, the OpenNMT-py replication gets to 26.9 on EN-DE WMT. Here I have loaded in those parameters to our reimplemenation.

```
Translation: <s> ▁Die ▁Protokoll datei ▁kann ▁ heimlich ▁per ▁E - Mail ▁oder ▁FTP ▁an ▁einen ▁bestimmte n ▁Empfänger ▁gesendet ▁werden .
```

## Attention Visualization

Even with a greedy decoder the translation looks pretty good. We can further visualize it to see what is happening at each layer of the attention

```
Encoder Layer 2
```

```
Encoder Layer 4
```

```
Encoder Layer 6
```

```
Decoder Self Layer 2
```

```
Decoder Src Layer 2
```

```
Decoder Self Layer 4
```

```
Decoder Src Layer 4
```

```
Decoder Self Layer 6
```

```
Decoder Src Layer 6
```

# Conclusion

Hopefully this code is useful for future research. Please reach out if you have any issues. If you find this code helpful, also check out our other OpenNMT tools.

```
@inproceedings{opennmt,
author = {Guillaume Klein and
Yoon Kim and
Yuntian Deng and
Jean Senellart and
Alexander M. Rush},
title = {OpenNMT: Open-Source Toolkit for Neural Machine Translation},
booktitle = {Proc. ACL},
year = {2017},
url = {https://doi.org/10.18653/v1/P17-4012},
doi = {10.18653/v1/P17-4012}
}
```

Cheers, srush