Paper review on “Attention is all you need”

Rohan Chhetry
9 min readJan 3, 2023

--

Problem Statement

Attention approach to mitigate the complexity of state of the art convolution or recurrent neural network architectures

Recurrent neural networks, i.e long short-term memory (LSTM), and gated recurrent neural networks (GRU) were used as State of the art approaches for sequence and language modelling. This paper establishes a new model architecture of Transformers, which uses attention mechanism instead of recurrence to reach higher state of the art translation quality.

RNN based architectures are hard to parallelize and inefficient in learning long term dependencies within the input and output sequences.

  • Transformers use multiple attention distributions and multiple outputs for a single input in order to improve the problem.
  • It also uses layer normalization and residual connections to make optimizations easier.

Current Approach

Figure: Transformer Architecture

The left side shows the encoder that encodes the input sequence (x1,…,xn)(x1​,…,xn​) to a sequence of continuous representations z=(z1,…,zn)z=(z1​,…,zn​), the right side shows the decoder that decodes the output of the encoder combined with the output (embeddings) to an output sequence (y1,…,ym)(y1​,…,ym​). The decoder works auto-regressive: for each output the model consumes all previously generated symbols as additional input. As can be seen from the image, the transformer architecture consists of encoder (decoder) blocks that can be stacked (–> Nx) upon each other to create a more and more complex model.

The Transformer follows this overall architecture using stacked self-attention and point-wise, fully connected layers for both the encoder and decoder.

Encoder

The vanilla transformer architecture uses N=6N=6 encoder blocks where each block consists of 2 sub-layers, a multi-head self-attention mechanism and a position-wise fully connected feed-forward network. Around each sub-layer a residual connection is employed. Afterwards follows a layer normalization.

Final output of each sub-layer: LayerNorm(x+Sublayer(x))LayerNorm(x+Sublayer(x)). All embedding layers as well as all sub-layers in the model produce outputs of the dimension dmodel=512dmodel​=512.

Decoder

The decoder is structured similarly to the encoder. The difference is that the decoder applies an additional multi-head attention layer that works on the output of an encoder block. Again, residual connections are employed around each sub-layer followed by layer normalization. For all positions, the multi-head attention that works on output embeddings masks all subsequent positions so that a prediction for step ii depends only on previously seen positions. Additionally, the output embeddings are shifted right by one position so that the first prediction is the first symbol (without shifting the first symbol would be known during the first prediction…not what we want). The vanilla transformer applies also N=6N=6 decoder blocks.

Experimentation Setup

Attention

Figure : Multi-head attention

Scaled Dot-Product Attention

Figure: Scaled Dot-Product Attention

The input consists of queries and keys of dimension dk, and values of dimension dv.

The dot product of the query with all keys are computed , each divided by √(dk) , and a softmax function is applied to obtain the weights on the values.

In practice , the attention function can be computed 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. The matrix of outputs are:

Reasons of Using Dot Product Attention over Additive Attention:

  1. The two most commonly used attention functions are additive attention, and dot-product (multiplicative) attention.
  2. 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 dk, the two mechanisms perform similarly. For large values of dk, the dot products grow large in magnitude, pushing the softmax function into regions where it has extremely small gradients. To counteract this effect, we scale the dot products by 1/√(dk).

Multi-head attention

Instead of performing a single attention function with model-dimensional keys, values and queries, it is found to be beneficial to linear project the queries, keys and values h times with different , learned linear projections to dk , dk and dv dimensions respectively.

On each of these projected versions of queries, keys and values, the attention function is performed in parallel, yielding dv-dimensional output values. These are concatenated and once again projected:

Here the projections are parameter matrices WQi, WKi, WVi. In this model, h=8 parallel attention layers, or heads. For each of these, dk=dv=dmodel/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.

The overall framework, the Transformer uses multi-head attention in three different ways (The 3 orange blocks):

  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.
  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. To prevent leftward information flow in the decoder to preserve the auto-regressive property, the scaled dot-product attention is modified by masking out (setting to -∞) all values in the input of the softmax which correspond to illegal connections.

Position-wise Feed-Forward Networks

Figure: Position Wise feed forward network

In addition to attention sub-layers, each of the layers in the encoder and decoder contains a fully connected feed-forward network, which consists of two linear transformations with a ReLU activation:

Another way of describing this is as two convolutions with kernel size 1.The dimensionality of input and output is dmodel = 512, and the inner-layer has dimensionality dff = 2048, which is a bottleneck structure.

Embedding and softmax

Learned embeddings are used to convert the input tokens and output tokens to vectors of dimension dmodel. The usual learned linear transformation and softmax function are used to convert the decoder output to predicted next-token probabilities.In Transformer, the same weight matrix is shared between the two embedding layers and the pre-softmax linear transformation.

In the embedding layers, those weights are multiplied by √(dmodel).

Positional Encoding

Figure: Positional encoding at encoder (left) and decoder (right)

Since Transformer contains no recurrence and no convolution, some information about the relative or absolute position of the tokens in the sequence are needed to inject.

“Positional encodings” are added to the input embeddings at the bottoms of the encoder and decoder stacks. The positional encodings have the same dimension dmodel as the embeddings, so that the two can be summed.

Sine and cosine functions of different frequencies are used:

where pos is the position and i is the dimension. Each dimension of the positional encoding corresponds to a sinusoid, it is hypothesis that it would allow the model to easily learn to attend by relative positions.

Figure: maximum path lengths, per-layer complexity and minimum number of sequential operations for different layer types

Factors that influence the use of self-attention:

  1. The total computational complexity per layer.
  2. The amount of computation that can be parallelized.
  3. The path length between long-range dependencies in the network.

A self-attention layer connects all positions with a constant number of sequentially executed operations, whereas a recurrent layer requires O(n) sequential operations.

In terms of computational complexity, self-attention layers are faster than recurrent layers when the sequence length n is smaller than the representation dimensionality d. A single convolutional layer with kernel width k<n does not connect all pairs of input and output positions. Doing so requires a stack of O(n=k) convolutional layers in the case of contiguous kernels, or O(logk(n)) in the case of dilated convolutions.

Training Data and Batching

Trained data on the standard WMT 2014 English-German dataset

  • 4.5 million sentence pairs
  • Sentences encoded using byte-pair encoding
  • shared source target vocabulary of about 37000 tokens.

WMT 2014 English-French dataset

  • 36M sentences
  • split tokens into a 32000 word-piece vocabulary
  • Sentence pairs batched together by approximate sequence length.

Hardware and Schedule

  • Trained models on one machine with 8 NVIDIA P100 GPUs.

Optimizer

  • Adam optimizer
  • Varied the learning rate over the course of training,

Regularization

Residual Dropout

Applied to the output of each sub-layer, before it is added to the sub-layer input and normalized.

Label Smoothing

During training, label smoothing was employed. The model learns to be more unsure, but improves accuracy and BLEU score.

Result

Machine Translation

WMT 2014 English-to-German translation task

  • New state of art BLEU score of 28.4
  • Training took 3.5 days on 8 P100 GPUs
  • Base model surpasses all previously published models and ensembles

WMT 2014 English-to-French translation task

  • Model achieves a BLEU score of 41.0
  • Outperformed all of the previously published single models, at less than 1/4 the training cost of the previous state-of-the-art model.
  • Used dropout rate Pdrop = 0.1, instead of 0.3.

For the base models

  • A single model obtained by averaging the last 5 checkpoints was used, which were written at 10-minute intervals.

For the big models,

  • Average of the last 20 checkpoints are used.
  • Used beam search with a beam size of 4 and length penalty of 0.6.

Model Variations

Variation in base model:

  • Measured the change in performance on English-to-German translation on the development set, newstest2013.
  • Used beam search with no checkpoint averaging.
  • Varying the number of attention heads and the attention key and value dimensions, keeping the amount of computation constant.
  • While single-head attention is 0.9 BLEU worse than the best setting, quality also drops off with too many heads.

English Constituency Parsing

A 4-layer transformer with dmodel = 1024 on the Wall Street Journal (WSJ) portion of the Penn Treebank was trained with:

  • About 40K training sentences
  • Trained in a semi-supervised setting,
  • 17M sentences
  • Vocabulary of 16K tokens for the WSJ only setting and a vocabulary of 32K tokens for the semi-supervised setting.
  • Dropout used

During inference,

  • Increased the maximum output length to input length + 300.
  • Used a beam size of 21 and alpha = 0.3 for both WSJ only and the semi-supervised setting.

Results shows that

  • Despite the lack of task-specific tuning the model performed better, with better results than all previously reported models with the exception of the Recurrent Neural Network Grammar.
  • In contrast to RNN sequence-to-sequence models, the Transformer outperforms the Berkeley-Parser even when training only on the WSJ training set of 40K sentences.

Conclusion

Key Takeaways

  • This work introduces Transformer, a novel sequence transduction model based entirely on attention mechanism.
  • It replaces the recurrent layers most commonly used in encoder-decoder architectures with multi-headed self-attention.
  • Transformer can be trained significantly faster than architectures based on recurrent or convolutional layers for translation tasks.
  • Attention mechanism allows the decoder to look at the entire sentence and selectively extract the information needed during decoding

Questions related to paper

  • To what extent is the sentence generated after transformation syntatically correct?
  • Unlike in encoder, why in decoder attention is applied on tokens up to current position and not future tokens?
  • Why is decoder input shifted to the right by one position despite for the first token, there exist no previous token?

Limitation

  • The paper presents may be less experiments for obtaining the desired results.

The paper can be found at the link: https://arxiv.org/pdf/1706.03762

--

--

Rohan Chhetry
Rohan Chhetry

Written by Rohan Chhetry

Currently a student transitioning into the work environment and exploring data science , publishing my findings

No responses yet