This is a reading note (almost a copy without references🤦) of the paper: Attention Is All You Need. The key section in this paper is 3.2 Attention, where I also refer to this post for better understanding.
Abstract
This paper proposed a new simple network architecture, the Transformer, based solely on attention mechanisms, dispensing with recurrence and convolutions entirely. Their 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. They show that the Transformer generalizes well to other tasks by applying it successfully to English constituency parsing both with large and limited training data.
1 Introduction
Recurrent neural networks, LSTM and GRU neural networks in particular, have been firmly established as state-of-the-art approaches for sequence modeling and transformation problems such as language modeling and machine translation. And a lot of efforts have been pushing the boundaries of recurrent language models and encode-decoder architectures.
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$, as a function of the precious hidden state $h_{t - 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.
Transformer is a model architecture without 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.
2 Background
One of the goals is reducing sequential computation.
Self-attention is an attention mechanism relating different positions of a single sequence in order to compute a representation of the sequence
End-to-end memory networks are based on a recurrent attention mechanism instead of sequence-aligned recurrence and have been shown to perform well on simple-language question answering and language modeling tasks.
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.
3 Model Architecture
Most competitive neural sequence transduction models have an encoder-decoder structure, where the encoder maps an input sequence of symbol representations $(x_1, \ldots, x_n)$ to a sequence of continuous representations $\mathbf{z} = (z_1, \ldots, z_n)$. Given $\mathbf{z}$, the decoder then generates an output sequence $(y_1, \ldots, y_m)$ of symbols one element at a time. At each step the model is auto-regressive, 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.
3.1 Encoder and Decoder Stacks
Encoder:
The encoder is composed of a stack of $N = 6$ identical layers. Each layer has two sub-layers:
- a multi-head self-attention mechanism [Section 3.2]
- a simple, position-wise fully connected feed-forward network [Section 3.3]
A residual connection is employed around each of the two sub-layers, followed by layer normalization. That is, the output of each sub-layer is $\text{LayerNorm}(x + \text{Sublayer}(x))$, where $\text{Sublayer}(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_{\text{model}} = 512$ .
Decoder:
The decoder is also composed of a stack of $N = 6$ identical layers. Each layer has three sub-layers:
- a layer that performs multi-head attention over the output of the encoder stack. [Section 3.2]
- a multi-head self-attention mechanism [Section 3.2]
- a simple, position-wise fully connected feed-forward network [Section 3.3]
Similar to the encoder, residual connection followed by layer normalization is employed. The self-attention sub-layer is also modified 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$.
3.2 Attention
An attention function maps a query and a set of key-value pairs to an output. 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.
3.2.1 Scaled Dot-Product Attention
Input: queries $Q$ and keys $K$ of dimension $d_k$, and values $V$ of dimension $d_v$ $$ \text{Attention}(Q,K,V) = \text{softmax}\left(\frac{QK^T}{\sqrt{d_k}}\right)V $$ Two most commonly used attention functions:
- additive attention (computes the compatibility function using a feed-forward network with a single hidden layer).
- dot-product (multiplicative) attention (identical to the algorithm in the paper, except for the scaling factor of $\frac{1}{\sqrt{d_k}}$).
They 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$. They 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 counteract this effect, they scale the dot products by $\frac{1}{\sqrt{d_k}}$.
3.2.2 Multi-Head Attention
Linearly project the queries, keys and values $h$ times with different, learned linear projections to $d_k$, $d_k$ and $d_v$ dimensions. On each of these projected versions of queries, keys and values, perform the attention function in parallel, yielding $d_v$-dimensional output values. These are concatenated and once again projected, resulting in the final values, as depicted in Figure 2. $$ \text{MultiHead}(Q,K,V) = \text{Concat}(\text{head}_1, \ldots, \text{head}_h)W^O $$ $$ \text{where } \text{head}_i = \text{Attention}(QW_i^Q, KW_i^K, VW_i^V) $$
An illustration of attention mechanism from this post:
3.2.3 Applications of Attention in the 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.
- 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.
3.3 Position-wise Feed-Forward Networks
Two linear transformations with a ReLU activation in between: $$ \text{FFN}(x) = \max(0, xW_1 + b_1)W_2 + b_2 $$
The dimensionality of input and output is $d_{\text{model}} = 512$, and the inner-layer has dimensionality $d_{f f} = 2048$.
3.4 Embeddings and Softmax
- learned embeddings to convert the input tokens and output tokens to vectors of dimension $d_{\text{model}}$
- learned linear transformation and softmax function to convert the decoder output to predicted next-token probabilities.
Two embedding layers and the pre-softmax linear transformation share the same weight matrix. In the embedding layers, those weights are multiplied by $\sqrt{d_{\text{model}}}$.