Transformer (machine learning model)
A transformer is a deep learning model that adopts the mechanism of self-attention, differentially weighting the significance of each part of the input data. It is used primarily in the fields of natural language processing (NLP) and computer vision (CV). Like recurrent neural networks (RNNs), transformers are designed to handle sequential input data, such as natural language, for tasks such as translation and text summarization. However, unlike RNNs, transformers do not necessarily process the data in order. Rather, the attention mechanism provides context for any position in the input sequence. For example, if the input  data is a natural language sentence, the transformer does not need to process the beginning of the sentence before the end. Rather it identifies the context that confers meaning to each word in the sentence. This feature allows for more parallelization than RNNs and therefore reduces training times. Transformers were introduced in 2017 by a team at Google Brain and are increasingly the model of choice for NLP problems, replacing RNN models such as long short-term memory (LSTM). The additional training parallelization allows training on larger datasets than was once possible. This led to the development of pretrained systems  such as BERT (Bidirectional Encoder Representations from Transformers) and GPT (Generative Pre-trained Transformer), which were trained with large language datasets, such as the Wikipedia Corpus and Common Crawl, and can be fine-tuned for specific tasks. Background. Before transformers, most state-of-the-art NLP systems relied on gated RNNs, such as LSTM and gated recurrent units (GRUs), with added attention mechanisms. Transformers are built on these attention technologies without using an RNN structure, highlighting the fact that attention mechanisms alone can match the performance of RNNs with attention. Sequential processing. Gated RNNs process tokens sequentially, maintaining a state  vector that contains a representation of the data seen after every token. To process the formula_1th token, the model combines the state representing the sentence up to token formula_2 with the information of the new token to create a new state, representing the sentence up to token formula_1. Theoretically, the information from one token can propagate arbitrarily far down the sequence, if at every point the state continues to encode contextual information about the token. In practice this mechanism is flawed: the vanishing gradient problem leaves the model's state at the end of a long sentence without precise, extractable  information about preceding tokens. The dependency of token computations on results of previous token computations also makes it hard to parallelize computation on modern deep learning hardware. This can make the training of RNNs inefficient. Attention. These problems were addressed by attention mechanisms. Attention mechanisms let a model draw from the state at any preceding point along the sequence. The attention layer can access all previous states and weigh them according to a learned measure of relevancy, providing relevant information about far-away tokens. A clear example of the value of attention is in language translation, where context is essential  to assign the meaning of a word in a sentence. In an English-to-French translation system, the first word of the French output most probably depends heavily on the first few words of the English input. However, in a classic LSTM model, in order to produce the first word of the French output, the model is given only the state vector of the "last" English word. Theoretically, this vector can encode information about the whole English sentence, giving the model all necessary knowledge. In practice, this information is often poorly preserved by the LSTM. An attention mechanism can be  added to address this problem: the decoder is given access to the state vectors of every English input word, not just the last, and can learn attention weights that dictate how much to attend to each English input state vector. When added to RNNs, attention mechanisms increase performance. The development of the Transformer architecture revealed that attention mechanisms were powerful in themselves and that sequential recurrent processing of data was not necessary to achieve the quality gains of RNNs with attention. Transformers use an attention mechanism without an RNN, processing all tokens at the same time and calculating attention weights  between them in successive layers. Since the attention mechanism only uses information about other tokens from lower layers, it can be computed for all tokens in parallel, which leads to improved training speed. Architecture. Encoder-decoder architecture. Like earlier seq2seq models, the original Transformer model used an encoder-decoder architecture. The encoder consists of encoding layers that process the input iteratively one layer after another, while the decoder consists of decoding layers that do the same thing to the encoder's output. The function of each encoder layer is to generate encodings that contain information about which parts of the  inputs are relevant to each other. It passes its encodings to the next encoder layer as inputs. Each decoder layer does the opposite, taking all the encodings and using their incorporated contextual information to generate an output sequence. To achieve this, each encoder and decoder layer makes use of an attention mechanism. For each input, attention weighs the relevance of every other input and draws from them to produce the output. Each decoder layer has an additional attention mechanism that draws information from the outputs of previous decoders, before the decoder layer draws information from the encodings. Both the encoder  and decoder layers have a feed-forward neural network for additional processing of the outputs and contain residual connections and layer normalization steps. Scaled dot-product attention. The transformer building blocks are scaled dot-product attention units. When a sentence is passed into a transformer model, attention weights are calculated between every token simultaneously. The attention unit produces embeddings for every token in context that contain information about the token itself along with a weighted combination of other relevant tokens each weighted by its attention weight. For each attention unit the transformer model learns three weight matrices; the query weights  formula_4, the key weights formula_5, and the value weights formula_6. For each token formula_7, the input word embedding formula_8 is multiplied with each of the three weight matrices to produce a query vector formula_9, a key vector formula_10, and a value vector formula_11. Attention weights are calculated using the query and key vectors: the attention weight formula_12 from token formula_7 to token formula_14 is the dot product between formula_15 and formula_16. The attention weights are divided by the square root of the dimension of the key vectors, formula_17, which stabilizes gradients during training, and passed through a softmax which normalizes  the weights. The fact that formula_4 and formula_5 are different matrices allows attention to be non-symmetric: if token formula_7 attends to token formula_14 (i.e. formula_22 is large), this does not necessarily mean that token formula_14 will attend to token formula_7 (i.e. formula_25 could be small). The output of the attention unit for token formula_7 is the weighted sum of the value vectors of all tokens, weighted by formula_12, the attention from token formula_7 to each token. The attention calculation for all tokens can be expressed as one large matrix calculation using the softmax function, which is useful for training  due to computational matrix operation optimizations that quickly compute matrix operations. The matrices formula_29, formula_30 and formula_31 are defined as the matrices where the formula_7th rows are vectors formula_15, formula_34, and formula_35 respectively. formula_36 Multi-head attention. One set of formula_37 matrices is called an "attention head", and each layer in a transformer model has multiple attention heads. While each attention head attends to the tokens that are relevant to each token, with multiple attention heads the model can do this for different definitions of "relevance". In addition the influence field representing relevance can become progressively dilated in successive layers . Many transformer attention heads encode relevance relations that are meaningful to humans. For example, attention heads can attend mostly to the next word, while others mainly attend from verbs to their direct objects. The computations for each attention head can be performed in parallel, which allows for fast processing. The outputs for the attention layer are concatenated to pass into the feed-forward neural network layers. Encoder. Each encoder consists of two major components: a self-attention mechanism and a feed-forward neural network. The self-attention mechanism accepts input encodings from the previous encoder and weighs their relevance to  each other to generate output encodings. The feed-forward neural network further processes each output encoding individually. These output encodings are then passed to the next encoder as its input, as well as to the decoders. The first encoder takes positional information and embeddings of the input sequence as its input, rather than encodings. The positional information is necessary for the transformer to make use of the order of the sequence, because no other part of the transformer makes use of this. Decoder. Each decoder consists of three major components: a self-attention mechanism, an attention mechanism over the encodings , and a feed-forward neural network. The decoder functions in a similar fashion to the encoder, but an additional attention mechanism is inserted which instead draws relevant information from the encodings generated by the encoders. Like the first encoder, the first decoder takes positional information and embeddings of the output sequence as its input, rather than encodings. The transformer must not use the current or future output to predict an output, so the output sequence must be partially masked to prevent this reverse information flow. The last decoder is followed by a final linear transformation and softmax layer, to produce  the output probabilities over the vocabulary. Alternatives. Training transformer-based architectures can be expensive, especially for long inputs. Alternative architectures include the Reformer (which reduces the computational load from formula_38 to formula_39), or models like ETC/BigBird (which can reduce it to formula_40) where formula_41 is the length of the sequence. This is done using locality-sensitive hashing and reversible layers. A benchmark for comparing transformer architectures was introduced in late 2020. Training. Transformers typically undergo semi-supervised learning involving unsupervised pretraining followed by supervised fine-tuning. Pretraining is typically done on a larger dataset than fine-tuning, due to  the limited availability of labeled training data. Tasks for pretraining and fine-tuning commonly include: Applications. The transformer has had great success in natural language processing (NLP), for example the tasks of machine translation and time series prediction. Many pretrained models such as GPT-2, GPT-3, BERT, XLNet, and RoBERTa demonstrate the ability of transformers to perform a wide variety of such NLP-related tasks, and have the potential to find real-world applications. These may include: In 2020, it was shown that the transformer architecture, more specifically GPT-2, could be tuned to play chess. Transformers have been applied to image  processing with results competitive with convolutional neural networks. Implementations. The transformer model has been implemented in standard deep learning frameworks such as TensorFlow and PyTorch. "Transformers" is a library produced by Hugging Face that supplies transformer-based architectures and pretrained models.