Transformer (deep learning architecture)

From testwiki
Revision as of 03:18, 24 February 2025 by imported>MathXplore (Reverted edits by 2806:263:482:2EB:88B7:87D7:C316:E924 (talk) to last version by 2A02:C7C:BDCC:3D00:B428:A3E7:5054:999)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Template:Short description Template:Machine learning

A standard Transformer architecture, showing on the left an encoder, and on the right a decoder. Note: it uses the pre-LN convention, which is different from the post-LN convention used in the original 2017 Transformer.

The transformer is a deep learning architecture that was developed by researchers at Google and is based on the multi-head attention mechanism, which was proposed in the 2017 paper "Attention Is All You Need".[1] Text is converted to numerical representations called tokens, and each token is converted into a vector via lookup from a word embedding table.[1] At each layer, each token is then contextualized within the scope of the context window with other (unmasked) tokens via a parallel multi-head attention mechanism, allowing the signal for key tokens to be amplified and less important tokens to be diminished.

Transformers have the advantage of having no recurrent units, therefore requiring less training time than earlier recurrent neural architectures (RNNs) such as long short-term memory (LSTM).[2] Later variations have been widely adopted for training large language models (LLM) on large (language) datasets.[3]

Transformers were first developed as an improvement over previous architectures for machine translation,[4][5] but have found many applications since. They are used in large-scale natural language processing, computer vision (vision transformers), reinforcement learning,[6][7] audio,[8] multimodal learning, robotics,[9] and even playing chess.[10] It has also led to the development of pre-trained systems, such as generative pre-trained transformers (GPTs)[11] and BERT[12] (bidirectional encoder representations from transformers).Template:TOC limit

History

Template:See also

Predecessors

For many years, sequence modelling and generation was done by using plain recurrent neural networks (RNNs). A well-cited early example was the Elman network (1990). In theory, the information from one token can propagate arbitrarily far down the sequence, but in practice the vanishing-gradient problem leaves the model's state at the end of a long sentence without precise, extractable information about preceding tokens.

A key breakthrough was LSTM (1995),Template:NoteTag a RNN which used various innovations to overcome the vanishing gradient problem, allowing efficient learning of long-sequence modelling. One key innovation was the use of an attention mechanism which used neurons that multiply the outputs of other neurons, so-called multiplicative units.[13] Neural networks using multiplicative units were later called sigma-pi networks[14] or higher-order networks.[15] LSTM became the standard architecture for long sequence modelling until the 2017 publication of Transformers. However, LSTM still used sequential processing, like most other RNNs.Template:NoteTag Specifically, RNNs operate one token at a time from first to last; they cannot operate in parallel over all tokens in a sequence.

Modern Transformers overcome this problem, but unlike RNNs, they require computation time that is quadratic in the size of the context window. The linearly scaling fast weight controller (1992) learns to compute a weight matrix for further processing depending on the input.[16] One of its two networks has "fast weights" or "dynamic links" (1981).[17][18][19] A slow neural network learns by gradient descent to generate keys and values for computing the weight changes of the fast neural network which computes answers to queries.[16] This was later shown to be equivalent to the unnormalized linear Transformer.[20][21]

Attention with seq2seq

Template:Main The idea of encoder-decoder sequence transduction had been developed in the early 2010s (see previous papers[22][23]). The papers most commonly cited as the originators that produced seq2seq are two concurrently published papers from 2014.[22][23]

A 380M-parameter model for machine translation uses two long short-term memories (LSTM).[23] Its architecture consists of two parts. The encoder is an LSTM that takes in a sequence of tokens and turns it into a vector. The decoder is another LSTM that converts the vector into a sequence of tokens. Similarly, another 130M-parameter model used gated recurrent units (GRU) instead of LSTM.[22] Later research showed that GRUs are neither better nor worse than LSTMs for seq2seq.[24][25]

These early seq2seq models had no attention mechanism, and the state vector is accessible only after the last word of the source text was processed. Although in theory such a vector retains the information about the whole original sentence, in practice the information is poorly preserved. This is because the input is processed sequentially by one recurrent network into a fixed-size output vector, which is then processed by another recurrent network into an output. If the input is long, then the output vector would not be able to contain all relevant information, degrading the output. As evidence, reversing the input sentence improved seq2seq translation.[26]

The RNNsearch model introduced an attention mechanism to seq2seq for machine translation to solve the bottleneck problem (of the fixed-size output vector), allowing the model to process long-distance dependencies more easily. The name is because it "emulates searching through a source sentence during decoding a translation".[4]

The relative performances were compared between global (that of RNNsearch) and local (sliding window) attention model architectures for machine translation, finding that mixed attention had higher quality than global attention, while local attention reduced translation time.[27]

In 2016, Google Translate was revamped to Google Neural Machine Translation, which replaced the previous model based on statistical machine translation. The new model was a seq2seq model where the encoder and the decoder were both 8 layers of bidirectional LSTM.[28] It took nine months to develop, and it outperformed the statistical approach, which took ten years to develop.[29]

Parallelizing attention

Template:Main Seq2seq models with attention (including self-attention) still suffered from the same issue with recurrent networks, which is that they are hard to parallelize, which prevented them from being accelerated on GPUs. In 2016, decomposable attention applied a self-attention mechanism to feedforward networks, which are easy to parallelize, and achieved SOTA result in textual entailment with an order of magnitude fewer parameters than LSTMs.[30] One of its authors, Jakob Uszkoreit, suspected that attention without recurrence is sufficient for language translation, thus the title "attention is all you need".[31] That hypothesis was against conventional wisdom at the time, and even his father Hans Uszkoreit, a well-known computational linguist, was skeptical.[31] In the same year, self-attention (called intra-attention or intra-sentence attention) was proposed for LSTMs.[32]

In 2017, the original (100M-sized) encoder-decoder transformer model was proposed in the "Attention is all you need" paper. At the time, the focus of the research was on improving seq2seq for machine translation, by removing its recurrence to process all tokens in parallel, but preserving its dot-product attention mechanism to keep its text processing performance.[1] This led to the introduction of a multi-head attention model that was easier to parallelize due to the use of independent heads and the lack of recurrence. Its parallelizability was an important factor to its widespread use in large neural networks.[33] Template:Anchor

AI boom era

Already in spring 2017, even before the "Attention is all you need" preprint was published, one of the co-authors applied the "decoder-only" variation of the architecture to generate fictitious Wikipedia articles.[34] Transformer architecture is now used alongside many generative models that contribute to the ongoing AI boom.

In language modelling, ELMo (2018) was a bi-directional LSTM that produces contextualized word embeddings, improving upon the line of research from bag of words and word2vec. It was followed by BERT (2018), an encoder-only Transformer model.[35] In 2019 October, Google started using BERT to process search queries.[36] In 2020, Google Translate replaced the previous RNN-encoder–RNN-decoder model by a Transformer-encoder–RNN-decoder model.[37]

Starting in 2018, the OpenAI GPT series of decoder-only Transformers became state of the art in natural language generation. In 2022, a chatbot based on GPT-3, ChatGPT, became unexpectedly popular,[38] triggering a boom around large language models.[39][40]

Since 2020, Transformers have been applied in modalities beyond text, including the vision transformer,[41] speech recognition,[42] robotics,[6] and multimodal.[43] The vision transformer, in turn, stimulated new developments in convolutional neural networks.[44] Image and video generators like DALL-E (2021), Stable Diffusion 3 (2024),[45] and Sora (2024), use Transformers to analyse input data (like text prompts) by breaking it down into "tokens" and then calculating the relevance between each token using self-attention, which helps the model understand the context and relationships within the data.

Training

Methods for stabilizing training

The plain transformer architecture had difficulty converging. In the original paper[1] the authors recommended using learning rate warmup. That is, the learning rate should linearly scale up from 0 to maximal value for the first part of the training (usually recommended to be 2% of the total number of training steps), before decaying again.

A 2020 paper found that using layer normalization before (instead of after) multiheaded attention and feedforward layers stabilizes training, not requiring learning rate warmup.[46]

Pretrain-finetune

Transformers typically are first pretrained by self-supervised learning on a large generic dataset, followed by supervised fine-tuning on a small task-specific dataset. The pretrain dataset is typically an unlabeled large corpus, such as The Pile. Tasks for pretraining and fine-tuning commonly include:

The T5 transformer report[47] documents a large number of natural language pretraining tasks. Some examples are:

  • restoring or repairing incomplete or corrupted text. For example, the input, "Thank youTemplate:Nnbspme to your partyTemplate:Nnbspweek", might generate the output, "Thank you for inviting me to your party last week".
  • translation between natural languages (machine translation)
  • judging the pragmatic acceptability of natural language. For example, the following sentence might be judged "not acceptable",[48] because even though it is syntactically well-formed, it is improbable in ordinary human usage: The course is jumping well.

Note that while each of these tasks is trivial or obvious for human native speakers of the language (or languages), they have typically proved challenging for previous generations of machine learning architecture.

Tasks

Template:See also In general, there are 3 classes of language modelling tasks: "masked",[49] "autoregressive",[50] and "prefixLM".[51] These classes are independent of a specific modeling architecture such as Transformer, but they are often discussed in the context of Transformer.

In a masked task,[49] one or more of the tokens is masked out, and the model would produce a probability distribution predicting what the masked-out tokens are based on the context. The loss function for the task is typically sum of log-perplexities for the masked-out tokens: Loss=tmasked tokensln(probability of t conditional on its context)and the model is trained to minimize this loss function. The BERT series of models are trained for masked token prediction and another task.

In an autoregressive task,[50] the entire sequence is masked at first, and the model produces a probability distribution for the first token. Then the first token is revealed and the model predicts the second token, and so on. The loss function for the task is still typically the same. The GPT series of models are trained by autoregressive tasks.

In a prefixLM task,[51] the sequence is divided into two parts. The first part is presented as context, and the model predicts the first token of the second part. Then that would be revealed, and the model predicts the second token, and so on. The loss function for the task is still typically the same. The T5 series of models are trained by prefixLM tasks.

Note that "masked" as in "masked language modelling" is not "masked" as in "masked attention", and "prefixLM" (prefix language modeling) is not "prefixLM" (prefix language model).

Architecture

All transformers have the same primary components:

  • Tokenizers, which convert text into tokens.
  • Embedding layer, which converts tokens and positions of the tokens into vector representations.
  • Transformer layers, which carry out repeated transformations on the vector representations, extracting more and more linguistic information. These consist of alternating attention and feedforward layers. There are two major types of transformer layers: encoder layers and decoder layers, with further variants.
  • Un-embedding layer, which converts the final vector representations back to a probability distribution over the tokens.

The following description follows exactly the Transformer as described in the original paper. There are variants, described in the following section.

By convention, we write all vectors as row vectors. This, for example, means that pushing a vector through a linear layer means multiplying it by a weight matrix on the right, as xW.

Tokenization

Template:Main

As the Transformer architecture natively processes numerical data, not text, there must be a translation between text and tokens. A token is an integer that represents a character, or a short segment of characters. On the input side, the input text is parsed into a token sequence. Similarly, on the output side, the output tokens are parsed back to text. The module doing the conversion between texts and token sequences is a tokenizer.

The set of all tokens is the vocabulary of the tokenizer, and its size is the vocabulary size nvocabulary. When faced with tokens outside the vocabulary, typically a special token is used, written as "[UNK]" for "unknown".

Some commonly used tokenizers are byte pair encoding, WordPiece, and SentencePiece.

Embedding

Template:See Each token is converted into an embedding vector via a lookup table. Equivalently stated, it multiplies a one-hot representation of the token by an embedding matrix M. For example, if the input token is 3, then the one-hot representation is [0,0,0,1,0,0,], and its embedding vector isEmbed(3)=[0,0,0,1,0,0,]MThe token embedding vectors are added to their respective positional encoding vectors (see below), producing the sequence of input vectors.

The number of dimensions in an embedding vector is called hidden size or embedding size and written as demb.[35] This size is written as dmodel in the original Transformer paper.[1]

Un-embedding

An un-embedding layer is almost the reverse of an embedding layer. Whereas an embedding layer converts a token into a vector, an un-embedding layer converts a vector into a probability distribution over tokens.

The un-embedding layer is a linear-softmax layer:UnEmbed(x)=softmax(xW+b)The matrix has shape (demb,nvocabulary). The embedding matrix M and the un-embedding matrix W are sometimes required to be transposes of each other, a practice called weight tying.[52]

Positional encoding

A diagram of a sinusoidal positional encoding with parameters N=10000,d=100

A positional encoding is a fixed-size vector representation of the relative positions of tokens within a sequence: it provides the transformer model with information about where the words are in the input sequence. This shall induce a bias towards the order of the input sequence, so that, for example, the input sequence "man bites dog" is processed differently from "dog bites man".

The positional encoding is defined as a function of type f:d;d,d>0, where d is a positive even integer. The full positional encoding defined in the original paper[1] is:(f(t)2k,f(t)2k+1)=(sin(θ),cos(θ))k{0,1,,d/21}where θ=trk,r=N2/d.

Here, N is a free parameter that should be significantly larger than the biggest k that would be input into the positional encoding function. The original paper uses N=10000.

The function is in a simpler form when written as a complex function of type f:d/2f(t)=(eit/rk)k=0,1,,d21where r=N2/d.

The main reason for using this positional encoding function is that using it, shifts are linear transformations:f(t+Δt)=diag(f(Δt))f(t)where Δt is the distance one wishes to shift. This allows the transformer to take any encoded position, and find the encoding of the position n-steps-ahead or n-steps-behind, by a matrix multiplication.

By taking a linear sum, any convolution can also be implemented as linear transformations:jcjf(t+Δtj)=(jcjdiag(f(Δtj)))f(t)for any constants cj. This allows the transformer to take any encoded position and find a linear sum of the encoded locations of its neighbors. This sum of encoded positions, when fed into the attention mechanism, would create attention weights on its neighbors, much like what happens in a convolutional neural network language model. In the author's words, "we hypothesized it would allow the model to easily learn to attend by relative position."

In typical implementations, all operations are done over the real numbers, not the complex numbers, but since complex multiplication can be implemented as real 2-by-2 matrix multiplication, this is a mere notational difference.

Encoder-decoder (overview)

One encoder-decoder block
A Transformer is composed of stacked encoder layers and decoder layers.

Like earlier seq2seq models, the original transformer model used an encoder-decoder architecture. The encoder consists of encoding layers that process all the input tokens together one layer after another, while the decoder consists of decoding layers that iteratively process the encoder's output and the decoder's output tokens so far.

The purpose of each encoder layer is to create contextualized representations of the tokens, where each representation corresponds to a token that "mixes" information from other input tokens via self-attention mechanism. Each decoder layer contains two attention sublayers: (1) cross-attention for incorporating the output of encoder (contextualized input token representations), and (2) self-attention for "mixing" information among the input tokens to the decoder (i.e. the tokens generated so far during inference time).[53][54]

Both the encoder and decoder layers have a feed-forward neural network for additional processing of their outputs and contain residual connections and layer normalization steps.[54] These feed-forward layers contain most of the parameters in a Transformer model.

Feedforward network

Template:Anchor

The feedforward network module. It is a two-layered network that maps demb-dimensional vectors into demb-dimensional vectors.

The feedforward network (FFN) modules in a Transformer are 2-layered multilayer perceptrons:FFN(x)=ϕ(xW(1)+b(1))W(2)+b(2)where ϕ is its activation function. The original Transformer used ReLU activation.

The number of neurons in the middle layer is called intermediate size (GPT),[55] filter size (BERT),[35] or feedforward size (BERT).[35] It is typically larger than the embedding size. For example, in both GPT-2 series and BERT series, the intermediate size of a model is 4 times its embedding size: dffn=4demb.

Scaled dot-product attention

Template:Main

Attention head

Scaled dot-product attention, block diagram
Exact dimension counts within an attention head module

The attention mechanism used in the Transformer architecture are scaled dot-product attention units. For each unit, the transformer model learns three weight matrices: the query weights WQ, the key weights WK, and the value weights WV.

The module takes three sequences, a query sequence, a key sequence, and a value sequence. The query sequence is a sequence of length seq, query, and each entry is a vector of dimension demb, query. Similarly for the key and value sequences.

For each vector xi,query in the query sequence, it is multiplied by a matrix WQ to produce a query vector qi=xi,queryWQ. The matrix of all query vectors is the query matrix:Q=XqueryWQSimilarly, we construct the key matrix K=XkeyWK and the value matrix V=XvalueWV.

It is usually the case that all WQ,WK,WV are square matrices, meaning demb, query=dquery, etc.

Attention weights are calculated using the query and key vectors: the attention weight aij from token i to token j is the dot product between qi and kj. The attention weights are divided by the square root of the dimension of the key vectors, dk, which stabilizes gradients during training, and passed through a softmax which normalizes the weights. The fact that WQ and WK are different matrices allows attention to be non-symmetric: if token i attends to token j (i.e. qikj is large), this does not necessarily mean that token j will attend to token i (i.e. qjki could be small). The output of the attention unit for token i is the weighted sum of the value vectors of all tokens, weighted by aij, the attention from token i 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 Q, K and V are defined as the matrices where the ith rows are vectors qi, ki, and vi respectively. Then we can represent the attention asAttention(Q,K,V)=softmax(QKTdk)V

where the softmax is applied over each of the rows of the matrix.

The number of dimensions in a query vector is query size dquery and similarly for the key size dkey and value size dvalue. The output dimension of an attention head is its head dimension dhead. The attention mechanism requires the following three equalities to hold:seq, key=seq, value,dquery=dkey,dvalue=dheadbut is otherwise unconstrained.

If the attention head is used in a self-attention fashion, then Xquery=Xkey=Xvalue. If the attention head is used in a cross-attention fashion, then usually XqueryXkey=Xvalue. It is theoretically possible for all three to be different, but that is rarely the case in practice.

Multiheaded attention

Multiheaded attention, block diagram
Exact dimension counts within a multiheaded attention module

One set of (WQ,WK,WV) 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, multiple attention heads allow the model to do this for different definitions of "relevance". Specifically, the query and key projection matrices, WQ and WK , which are involved in the attention score computation, defines the "relevance". Meanwhile, the value projection matrix WV, in combination with the part of the output projection matrix WO, determines how the attended tokens influence what information is passed to subsequent layers and ultimately the output logits. In addition, the scope of attention, or the range of token relationships captured by each attention head, can expand as tokens pass through successive layers. This allows the model to capture more complex and long-range dependencies in deeper layers. Many transformer attention heads encode relevance relations that are meaningful to humans. For example, some attention heads can attend mostly to the next word, while others mainly attend from verbs to their direct objects.[56] 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.

Concretely, let the multiple attention heads be indexed by i, then we haveMultiheadedAttention(Q,K,V)=Concati[nheads](Attention(QWiQ,KWiK,VWiV))WO where the matrix X is the concatenation of word embeddings, and the matrices WiQ,WiK,WiV are "projection matrices" owned by individual attention head i, and WO is a final projection matrix owned by the whole multi-headed attention head.

It is theoretically possible for each attention head to have a different head dimension dhead, but that is rarely the case in practice.

As an example, in the smallest GPT-2 model, there are only self-attention mechanisms. It has the following dimensions:demb=768,nhead=12,dhead=64Since 12×64=768, its output projection matrix WO(12×64)×768 is a square matrix.

Masked attention

The Transformer architecture is constructed to calculate output tokens iteratively. Assuming t=0 refers to the calculation of the first output token i=0, for step t>0, the output token i=0 shall remain constant. This ensures properties of the model similar to autoregressive models.[1] Therefore, at every time step t, the calculation for all outputs i should not have access to tokens at position j for j>=i (as it naturally is the case for time step t=i, when tokens j>t are not yet calculated). This behavior may be accomplished before the softmax stage by adding a mask matrix M that is at entries where the attention link must be cut, and 0 at other places:MaskedAttention(Q,K,V)=softmax(M+QKTdk)V The following matrix is commonly used in decoder self-attention modules, called "causal masking":Mcausal=[0000000000]

In words, it means that each token can pay attention to itself, and every token before it, but not any after it. A non-masked attention module can be thought of as a masked attention module where the mask has all entries zero. As an example of an uncommon use of mask matrix, the XLNet considers all masks of the form PMcausalP1, where P is a random permutation matrix.[57]

Encoder

One encoder layer

An encoder consists of an embedding layer, followed by multiple encoder layers.

Each encoder layer consists of two major components: a self-attention mechanism and a feed-forward layer. It takes an input as a sequence of input vectors, applies the self-attention mechanism, to produce an intermediate sequence of vectors, then applies the feed-forward layer for each vector individually. Schematically, we have:given input vectors h0,h1,combine them into a matrix H=[h0h1]EncoderLayer(H)=[FFN(MultiheadedAttention(H,H,H)0)FFN(MultiheadedAttention(H,H,H)1)]

where FFN stands for "feed-forward network". We can more succinctly write it asEncoderLayer(H)=FFN(MultiheadedAttention(H,H,H))with the implicit convention that the FFN is applied to each row of the matrix individually.

The encoder layers are stacked. The first encoder layer takes the sequence of input vectors from the embedding layer, producing a sequence of vectors. This sequence of vectors is processed by the second encoder, and so on. The output from the final encoder layer is then used by the decoder.

As the encoder processes the entire input all at once, every token can attend to every other token (all-to-all attention), so there is no need for causal masking.

Decoder

One decoder layer

A decoder consists of an embedding layer, followed by multiple decoder layers, followed by an un-embedding layer.

Each decoder consists of three major components: a causally masked self-attention mechanism, a cross-attention mechanism, 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. This mechanism can also be called the encoder-decoder attention.[1][54]

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.[1] This allows for autoregressive text generation. For decoding, all-to-all attention is inappropriate, because a token cannot attend to tokens not yet generated. Thus, the self-attention module in the decoder is causally masked.

In contrast, the cross-attention mechanism attends to the output vectors of the encoder, which is computed before the decoder starts decoding. Consequently, there is no need for masking in the cross-attention mechanism.

Schematically, we have:H=MaskedMultiheadedAttention(H,H,H)DecoderLayer(H)=FFN(MultiheadedAttention(H,HE,HE))where HE is the matrix with rows being the output vectors from the encoder.

The last decoder is followed by a final un-embedding layer. to produce the output probabilities over the vocabulary. Then, one of the tokens is sampled according to the probability, and the decoder can be run again to produce the next token, etc, autoregressively generating output text.

Adapted architectures

Many large language models, since they do not need to predict a whole new sequence from an input sequence, only use the encoder or decoder of the original transformer architecture. Early GPT models are decoder-only models trained to predict the next token in a sequence.[58] BERT, another language model, only makes use of an encoder, and is trained to predict a randomly masked token in a sequence.[35]

Full transformer architecture

Sublayers

(a) One encoder layer and one decoder layer. (b) Two encoder layers and two decoder layers. The sublayers are labelled as well.

Each encoder layer contains 2 sublayers: the self-attention and the feedforward network. Each decoder layer contains 3 sublayers: the causally masked self-attention, the cross-attention, and the feedforward network.

Transformer encoder with norm-first and norm-last
Transformer decoder with norm-first and norm-last
Block diagram for the full Transformer architecture
Schematic object hierarchy for the full Transformer architecture, in object-oriented programming style

The final points of detail are the residual connections and layer normalization (LayerNorm, or LN), which while conceptually unnecessary, are necessary for numerical stability and convergence. Similarly to how the feedforward network modules are applied individually to each vector, the LayerNorm is also applied individually to each vector.

Template:AnchorThere are two common conventions in use: the post-LN and the pre-LN convention. In the post-LN convention, the output of each sublayer is LayerNorm(x+Sublayer(x))where Sublayer(x) is the function implemented by the sublayer itself.

In the pre-LN convention, the output of each sublayer isx+Sublayer(LayerNorm(x))The original 2017 Transformer used the post-LN convention. It was difficult to train and required careful hyperparameter tuning and a "warm-up" in learning rate, where it starts small and gradually increases. The pre-LN convention, proposed several times in 2018,[59] was found to be easier to train, requiring no warm-up, leading to faster convergence.[46]

Pseudocode

The following is the pseudocode for a standard pre-LN encoder-decoder Transformer, adapted from[60]

input: Encoder input t_e
       Decoder input t_d
output: Array of probability distributions, with shape (decoder vocabulary size x length(decoder output sequence))

/* encoder */
z_e ← encoder.tokenizer(t_e)

for each t in 1:length(z_e) do
    z_e[t] ← encoder.embedding(z_e[t]) + encoder.positional_embedding(t)

for each l in 1:length(encoder.layers) do
    layer ← encoder.layers[l]

    /* first sublayer */
    z_e_copy ← copy(z_e)
    for each t in 1:length(z_e) do
        z_e[t] ← layer.layer_norm(z_e[t])
    z_e ← layer.multiheaded_attention(z_e, z_e, z_e)
    for each t in 1:length(z_e) do
        z_e[t] ← z_e[t] + z_e_copy[t]

    /* second sublayer */
    z_e_copy ← copy(z_e)
    for each t in 1:length(z_e) do
        z_e[t] ← layer.layer_norm(z_e[t])
    z_e ← layer.feedforward(z_e)
    for each t in 1:length(z_e) do
        z_e[t] ← z_e[t] + z_e_copy[t]

for each t in 1:length(z_e) do
    z_e[t] ← encoder.final_layer_norm(z_e[t])

/* decoder */
z_d ← decoder.tokenizer(t_d)

for each t in 1:length(z_d) do
    z_d[t] ← decoder.embedding(z_d[t]) + decoder.positional_embedding(t)

for each l in 1:length(decoder.layers) do
        layer ← decoder.layers[l]

        /* first sublayer */
        z_d_copy ← copy(z_d)
        for each t in 1:length(z_d) do
            z_d[t] ← layer.layer_norm(z_d[t])
        z_d ← layer.masked_multiheaded_attention(z_d, z_d, z_d)
        for each t in 1:length(z_d) do
            z_d[t] ← z_d[t] + z_d_copy[t]

        /* second sublayer */
        z_d_copy ← copy(z_d)
        for each t in 1:length(z_d) do
            z_d[t] ← layer.layer_norm(z_d[t])
        z_d ← layer.multiheaded_attention(z_d, z_e, z_e) 
        for each i in 1:length(z_d) do
            z_d[t] ← z_d[t] + z_d_copy[t]

        /* third sublayer */
        z_d_copy ← copy(z_d)
        for each t in 1:length(z_d) do
            z_d[t] ← layer.layer_norm(z_d[t])
        z_d ← layer.feedforward(z_d)
        for each t in 1:length(z_d) do
            z_d[t] ← z_d[t] + z_d_copy[t]

z_d ← decoder.final_layer_norm(z_d)

output_distributions ← []
for each t in 1:length(z_d) do
    output_distributions.append(decoder.unembed(z_d[t]))

return output_distributions

Terminology

The Transformer architecture, being modular, allows variations. Several common variations are described here.[61]

Template:AnchorAn "encoder-only" Transformer applies the encoder to map an input text into a sequence of vectors that represent the input text. This is usually used for text embedding and representation learning for downstream applications. BERT is encoder-only. They are less often used currently, as they were found to be not significantly better than training an encoder-decoder Transformer, then taking just the encoder.[51]

Template:AnchorA "decoder-only" Transformer is not literally decoder-only, since without an encoder, the cross-attention mechanism has nothing to attend to. Thus, the decoder layers in a decoder-only Transformer is composed of just two sublayers: the causally masked self-attention, and the feedforward network. This is usually used for text generation and instruction following. The models in the GPT series and Chinchilla series are decoder-only.

Template:AnchorAn "encoder-decoder" Transformer is generally the same as the original Transformer, with 2 sublayers per encoder layer and 3 sublayers per decoder layer, etc. They might have minor architectural improvements, such as alternative activation functions, changing the location of normalization, etc. This is also usually used for text generation and instruction following. The models in the T5 series are encoder-decoder.[61]

Template:AnchorA "prefixLM" (prefix language model) is a decoder-only architecture, but with prefix masking, which is different from causal masking. Specifically, it has mask of the form[61]Template:PgMprefixLM=[𝟎𝟎Mcausal]where the first columns correspond to the "prefix", and the subsequent columns correspond to the autoregressively generated text based on the prefix. They resemble encoder-decoder models, but has less "sparsity". Such models are rarely used, though they are cited as theoretical possibilities and benchmarked comparisons.[51]

There are also mixed seq2seq models. For example, in 2020, Google Translate replaced the previous RNN-encoder–RNN-decoder model by a Transformer-encoder–RNN-decoder model, on the argument that an RNN-decoder runs much faster than Transformer-decoder when run autoregressively.[62]

Subsequent work

Alternative activation functions

The original transformer uses ReLU activation function. Other activation functions were developed. The Llama series and PaLM used SwiGLU;[63] both GPT-1 and BERT[35] used GELU.[64]

Alternative activation functions are often used in combination with Gated Linear Units in the feedforward module.[65]

Alternative normalizations

The normalization used in the Transformer can be different from LayerNorm. One example is RMSNorm[66] which is used in the Llama series. Other examples include CapsuleNorm[67] ScaleNorm,[68] or FixNorm.[68]

Alternative positional encodings

Transformers may use other positional encoding methods than sinusoidal.[69]

The original Transformer paper reported using a learned positional encoding,[70] but finding it not superior to the sinusoidal one.[1] Later, [71] found that causal masking itself provides enough signal to a Transformer decoder that it can learn to implicitly perform absolute positional encoding without the positional encoding module.

RoPE

Template:AnchorRoPE (rotary positional embedding),[72] is best explained by considering a list of 2-dimensional vectors [(x1(1),x1(2)),(x2(1),x2(2)),(x3(1),x3(2)),...]. Now pick some angle θ. Then RoPE encoding isRoPE(xm(1),xm(2),m)=(cosmθsinmθsinmθcosmθ)(xm(1)xm(2))=(xm(1)cosmθxm(2)sinmθxm(2)cosmθ+xm(1)sinmθ)Equivalently, if we write the 2-dimensional vectors as complex numbers zm:=xm(1)+ixm(2), then RoPE encoding is just multiplication by an angle:RoPE(zm,m)=eimθzmFor a list of 2n-dimensional vectors, a RoPE encoder is defined by a sequence of angles θ(1),...,θ(n). Then the RoPE encoding is applied to each pair of coordinates.

The benefit of RoPE is that the dot-product between two vectors depends on their relative location only:RoPE(x,m)TRoPE(y,n)=RoPE(x,m+k)TRoPE(y,n+k) for any integer k.

ALiBi

ALiBi (Attention with Linear Biases)[73] is not a replacement for the positional encoder on the original transformer. Instead, it is an additional positional encoder that is directly plugged into the attention mechanism. Specifically, the ALiBi attention mechanism isAttention(Q,K,V)=softmax(QKTdk+sB)VHere, s is a real number ("scalar"), and B is the linear bias matrix defined byB=(0123101221013210)in other words, Bi,j=ji. The idea being that the linear bias matrix is a softened mask. Just as 0 represent full attention paid, and represents no attention paid, the linear bias matrix increases attention paid in one direction and decreases attention paid in the other direction.

ALiBi allows pretraining on short context windows, then fine-tuning on longer context windows. Since it is directly plugged into the attention mechanism, it can be combined with any positional encoder that is plugged into the "bottom" of the entire network (which is where the sinusoidal encoder on the original transformer, as well as RoPE and many others, are located).

Relative Position Encodings

Relative Position Encodings[74] is similar to ALiBi, but more generic:Attention(Q,K,V)=softmax(QKTdk+B)Vwhere B is a Toeplitz matrix, that is, Bi,j=Bi,j whenever ij=ij. This is contrasted with the original sinusoidal positional encoding, which is an "absolute positional encoding".[75]

Efficient implementation

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.[11]

KV caching

When an autoregressive transformer is used for inference, such as generating text, the query vector is different at each step, but the already-computed key and value vectors are always the same. The KV caching method saves the computed key and value vectors at each attention block, so that they are not recomputed at each new token. PagedAttention applies memory paging to KV caching.[76][77][78]

If a transformer is used with a baked-in prompt, such as ["You are a customer support agent..."], then the key and value vectors can be computed for the prompt, and saved on disk. The saving in compute is significant when the model is used for many short interactions, such as in online chatbots.

FlashAttention

FlashAttention[79] is an algorithm that implements the transformer attention mechanism efficiently on a GPU. It is a communication-avoiding algorithm that performs matrix multiplications in blocks, such that each block fits within the cache of a GPU, and by careful management of the blocks it minimizes data copying between GPU caches (as data movement is slow). See the page on softmax for details.

An improved version, FlashAttention-2,[80][81][82] was developed to cater to the rising demand for language models capable of handling longer context lengths. It offers enhancements in work partitioning and parallelism, enabling it to achieve up to 230 TFLOPs/s on A100 GPUs (FP16/BF16), a 2x speed increase over the original FlashAttention.

Key advancements in FlashAttention-2 include the reduction of non-matmul FLOPs, improved parallelism over the sequence length dimension, better work partitioning between GPU warps, and added support for head dimensions up to 256 and multi-query attention (MQA) and grouped-query attention (GQA).[83]

Benchmarks revealed FlashAttention-2 to be up to 2x faster than FlashAttention and up to 9x faster than a standard attention implementation in PyTorch. Future developments include optimization for new hardware like H100 GPUs and new data types like FP8.

Multi-Query Attention

Template:Anchor

Comparison between several different forms of attention mechanism and the amount of KV caching necessary for each.

Multi-Query Attention changes the multiheaded attention mechanism.[84] Whereas normally,

MultiheadedAttention(Q,K,V)=Concati[nheads](Attention(XWiQ,XWiK,XWiV))WOwith Multi-Query Attention, there is just one WK,WV, thus:

MultiQueryAttention(Q,K,V)=Concati[nheads](Attention(XWiQ,XWK,XWV))WO

This has a neutral effect on model quality and training speed, but increases inference speed.

More generally, grouped-query attention (GQA) partitions attention heads into groups, each of which shares the key-value pair. MQA is GQA with one group, while standard multiheaded attention is GQA with the maximal number of groups.[85]

The architecture of V2, showing both MLA and a variant of mixture of experts.[86]Template:Pg

Template:Anchor Multihead Latent Attention (MLA) is a low-rank approximation to standard MHA. Specifically, each hidden vector, before entering the attention mechanism, is first projected to two low-dimensional spaces ("latent space"), one for query and one for key-value (KV vector). This design minimizes the KV cache, as only the low-dimensional KV vector needs to be cached.[86]

Speculative decoding

Speculative decoding[87][88] is a method to accelerate token decoding. Similarly to speculative execution in CPUs, future tokens are computed quickly, then verified. If the quickly computed tokens are incorrect, they are discarded and computed slowly.

The key factor in speculative decoding is that a Transformer decoder can verify faster than it can decode, in the following sense.

Suppose we have two transformer models like GPT-3 and GPT-3-small, both with a context window size of 512. To generate an entire context window autoregressively with greedy decoding with GPT-3, it must be run for 512 times, each time generating a token x1,x2,...,x512, taking time 512TGPT-3. However, if we had some educated guess for the values of these tokens, we could verify all of them in parallel, in one run of the model, by checking that each xt is indeed the token with the largest log-likelihood in the t-th output.

In speculative decoding, a smaller model or some other simple heuristic is used to generate a few speculative tokens that are subsequently verified by the larger model. For example, suppose we use GPT-3-small to generate four speculative tokens: x~1,x~2,x~3,x~4. This only takes 4TGPT-3-small. These tokens are then run through the larger GPT-3 in one go. Suppose that x~1 and x~2 are verified by GPT-3 as what it would have picked, then those are kept, but x~3 is not, so x~3,x~4 are discarded, and GPT-3 is run on those. This would take 4TGPT-3-small+3TGPT-3, which might be shorter than 4TGPT-3.

For non-greedy decoding, similar ideas apply, except the speculative tokens are accepted or rejected stochastically, in a way that guarantees the final output distribution is the same as if speculative decoding was not used.[87][89]

Multi-Token Prediction.

Template:AnchorIn Multi-Token Prediction, a single forward pass creates a final embedding vector, which then is un-embedded into a token probability. However, that vector can then be further processed by another Transformer block to predict the next token, and so on for arbitrarily many steps into the future. This trades off accuracy for speed, since each new token costs just one more Transformer block, rather than the entire stack.[90][91]

Sub-quadratic transformers

Training transformer-based architectures can be expensive, especially for long inputs.[92] Many methods have been developed to attempt to address the issue. In the image domain, Swin Transformer is an efficient architecture that performs attention inside shifting windows.[93] In the audio domain, SepTr decouples the attention in time and frequency domains.[94] Long Range Arena (2020)[95] is a standard benchmark for comparing the behavior of transformer architectures over long inputs.

Alternative attention graphs

The standard attention graph is either all-to-all or causal, both of which scales as O(N2) where N is the number of tokens in a sequence.

Reformer (2020)[92][96] reduces the computational load from O(N2) to O(NlnN) by using locality-sensitive hashing and reversible layers.[97]

Sparse attention[98] uses attention graphs that grows slower than O(N2). For example, BigBird (2020)[99] uses random small-world networks which grows as O(N).

Ordinary transformers require a memory size that is quadratic in the size of the context window. Attention-free transformers[100] reduce this to a linear dependence while still retaining the advantages of a transformer by linking the key to the value.

Random Feature Attention

Random Feature Attention (2021)[101] uses Fourier random features:φ(x)=1D[cosw1,x,sinw1,x,coswD,x,sinwD,x]Twhere w1,...,wD are independent samples from the normal distribution N(0,σ2I). This choice of parameters satisfy 𝔼[φ(x),φ(y)]=exy22σ2, or ex,y/σ2=𝔼[ex2/2σ2φ(x),ey2/2σ2φ(y)]ex2/2σ2φ(x),ey2/2σ2φ(y)Consequently, the one-headed attention, with one query, can be written as Attention(q,K,V)=softmax(qKTdk)Vφ(q)Tieki2/2σ2φ(ki)viTφ(q)Tieki2/2σ2φ(ki)where σ=dK1/4. Similarly for multiple queries, and for multiheaded attention.

This approximation can be computed in linear time, as we can compute the matrix φ(ki)viT first, then multiply it with the query. In essence, we have managed to obtain a more precise version of Attention(Q,K,V)=softmax(QKTdk)VQ(KTV/dk)Performer (2022)[102] uses the same Random Feature Attention, but w1,...,wD are first independently sampled from the normal distribution N(0,σ2I), then they are Gram-Schmidt processed.

Multimodality

Transformers can also be used/adapted for modalities (input or output) beyond just text, usually by finding a way to "tokenize" the modality.

Multimodal models can either be trained from scratch, or by finetuning. A 2022 study found that Transformers pretrained only on natural language can be finetuned on only 0.03% of parameters and become competitive with LSTMs on a variety of logical and visual tasks, demonstrating transfer learning.[103] The LLaVA was a vision-language model composed of a language model (Vicuna-13B)[104] and a vision model (ViT-L/14), connected by a linear layer. Only the linear layer is finetuned.[105]

Vision transformers[41] adapt the transformer to computer vision by breaking down input images as a series of patches, turning them into vectors, and treating them like tokens in a standard transformer.

Conformer[42] and later Whisper[106] follow the same pattern for speech recognition, first turning the speech signal into a spectrogram, which is then treated like an image, i.e. broken down into a series of patches, turned into vectors and treated like tokens in a standard transformer.

Perceivers[107][108] are a variant of Transformers designed for multimodality.

For image generation, notable architectures are DALL-E 1 (2021), Parti (2022),[109] Phenaki (2023),[110] and Muse (2023).[111] Unlike later models, DALL-E is not a diffusion model. Instead, it uses a decoder-only Transformer that autoregressively generates a text, followed by the token representation of an image, which is then converted by a variational autoencoder to an image.[112] Parti is an encoder-decoder Transformer, where the encoder processes a text prompt, and the decoder generates a token representation of an image.[113] Muse is an encoder-only Transformer that is trained to predict masked image tokens from unmasked image tokens. During generation, all input tokens are masked, and the highest-confidence predictions are included for the next iteration, until all tokens are predicted.[111] Phenaki is a text-to-video model. It is a bidirectional masked transformer conditioned on pre-computed text tokens. The generated tokens are then decoded to a video.[110]

Applications

The transformer has had great success in natural language processing (NLP). Many large language models such as GPT-2, GPT-3, GPT-4, AlbertAGPT, Claude, BERT, XLNet, RoBERTa and ChatGPT demonstrate the ability of transformers to perform a wide variety of NLP-related subtasks and their related real-world applications, including:

Beyond traditional NLP, the transformer architecture has had success in other applications, such as:

See also

Notes

Template:Reflist

References

Template:Reflist

Further reading

Template:Refbegin

Template:Refend

Template:Google AI Template:Artificial intelligence navbox

  1. 1.00 1.01 1.02 1.03 1.04 1.05 1.06 1.07 1.08 1.09 1.10 1.11 Template:Cite journal
  2. Template:Cite journal
  3. 3.0 3.1 Template:Cite web
  4. 4.0 4.1 Template:Cite arXiv
  5. Template:Cite arXiv
  6. 6.0 6.1 Template:Citation
  7. Template:Cite journal
  8. Template:Cite arXiv
  9. Template:Cite journal
  10. 10.0 10.1 Template:Cite arXiv
  11. 11.0 11.1 Template:Cite book
  12. 12.0 12.1 12.2 Template:Cite web
  13. Template:Cite journal
  14. Template:Cite book
  15. Template:Cite journal
  16. 16.0 16.1 Template:Cite journal
  17. Christoph von der Malsburg: The correlation theory of brain function. Internal Report 81-2, MPI Biophysical Chemistry, 1981. http://cogprints.org/1380/1/vdM_correlation.pdf See Reprint in Models of Neural Networks II, chapter 2, pages 95-119. Springer, Berlin, 1994.
  18. Jerome A. Feldman, "Dynamic connections in neural networks," Biological Cybernetics, vol. 46, no. 1, pp. 27-39, Dec. 1982.
  19. Template:Cite journal
  20. Template:Cite conference
  21. Template:Cite conference
  22. 22.0 22.1 22.2 Template:Cite book
  23. 23.0 23.1 23.2 Template:Cite arXiv [first version posted to arXiv on 10 Sep 2014]
  24. Template:Cite arXiv
  25. Template:Citation
  26. Template:Cite journal
  27. Template:Cite arXiv
  28. Template:Cite arXiv
  29. Template:Cite news
  30. Template:Cite arXiv
  31. 31.0 31.1 Template:Cite magazine
  32. Template:Cite book
  33. Template:Citation
  34. Template:Cite magazine
  35. 35.0 35.1 35.2 35.3 35.4 35.5 Template:Cite arXiv
  36. Template:Cite web
  37. Template:Cite web
  38. Template:Cite web
  39. Template:Cite web
  40. Template:Citation
  41. 41.0 41.1 Template:Cite arXiv
  42. 42.0 42.1 Template:Cite arXiv
  43. Template:Citation
  44. Template:Cite conference
  45. Template:Citation
  46. 46.0 46.1 Template:Cite arXiv
  47. Template:Cite journal
  48. Template:Cite arXiv
  49. 49.0 49.1 Template:Cite web
  50. 50.0 50.1 Template:Cite web
  51. 51.0 51.1 51.2 51.3 Template:Citation
  52. Template:Citation
  53. Template:Cite web
  54. 54.0 54.1 54.2 Template:Cite web
  55. Template:Cite web
  56. Template:Cite journal
  57. Template:Cite journal
  58. Template:Cite web
  59. Template:Citation
  60. Template:Citation
  61. 61.0 61.1 61.2 Template:Cite journal
  62. Template:Cite web
  63. Template:Cite arXiv
  64. Template:Cite arXiv
  65. Template:Cite arXiv
  66. Template:Cite journal
  67. Tembine, Hamidou, Manzoor Ahmed Khan, and Issa Bamia. 2024. "Mean-Field-Type Transformers" Mathematics 12, no. 22: 3506. https://doi.org/10.3390/math12223506
  68. 68.0 68.1 Template:Cite journal
  69. Template:Cite journal
  70. Template:Cite journal
  71. Template:Citation
  72. Template:Cite arXiv
  73. Template:Cite arXiv
  74. Template:Cite arXiv
  75. Template:Citation
  76. Template:Cite book
  77. Template:Citation
  78. Template:Cite web
  79. Template:Cite journal
  80. Template:Cite web
  81. Template:Cite web
  82. Template:Cite web
  83. Template:Cite arXiv
  84. Template:Cite arXiv
  85. Template:Citation
  86. 86.0 86.1 Template:Citation.
  87. 87.0 87.1 Template:Citation
  88. Template:Cite web
  89. Template:Citation
  90. Template:Citation
  91. Template:Citation
  92. 92.0 92.1 Template:Cite arXiv
  93. Template:Cite book
  94. Template:Cite journal
  95. Template:Cite arXiv
  96. Template:Cite web
  97. Template:Cite journal
  98. Template:Citation
  99. Template:Cite web
  100. Template:Cite arXiv
  101. Template:Cite arXiv
  102. Template:Cite arXiv
  103. Template:Cite journal
  104. Template:Cite web
  105. Template:Cite journal
  106. Template:Cite arXiv
  107. Template:Cite arXiv
  108. Template:Cite arXiv
  109. Template:Cite web
  110. 110.0 110.1 Template:Cite journal
  111. 111.0 111.1 Template:Cite arXiv
  112. Template:Citation
  113. Template:Citation
  114. Template:Cite journal