Transformer (deep learning) - Wikipedia
Transformer (deep learning) - Wikipedia
Jump to content [-]
Main menu
Main menu
move to sidebar hide
Navigation
Main page
Contents
Current events
Random article
About Wikipedia
Contact us
Contribute
Help
Learn to edit
Community portal
Recent changes
Upload file
Special pages
WikipediaThe Free Encyclopedia
Search
Search [-]
Appearance
Donate
Create account
Log in [-]
Personal tools
Donate
Create account
Log in
Contents
move to sidebar hide
(Top)
1 History Toggle History subsection
1.1 Predecessors
1.2 Attention with seq2seq
1.3 Parallelizing attention
1.4 AI boom era
1.1 Predecessors
1.2 Attention with seq2seq
1.3 Parallelizing attention
1.4 AI boom era
2 Training Toggle Training subsection
2.1 Methods for stabilizing training
2.2 Pretrain-finetune
2.3 Tasks
2.1 Methods for stabilizing training
2.2 Pretrain-finetune
2.3 Tasks
3 Architecture Toggle Architecture subsection
3.1 Tokenization
3.2 Embedding
3.3 Un-embedding
3.4 Positional encoding
3.5 Encoder–decoder (overview)
3.6 Feedforward network
3.7 Scaled dot-product attention
3.7.1 Attention head
3.7.2 Multihead attention
3.7.3 Masked attention
3.8 Encoder
3.9 Decoder
3.1 Tokenization
3.2 Embedding
3.3 Un-embedding
3.4 Positional encoding
3.5 Encoder–decoder (overview)
3.6 Feedforward network
3.7 Scaled dot-product attention
3.7.1 Attention head
3.7.2 Multihead attention
3.7.3 Masked attention
3.7.1 Attention head
3.7.2 Multihead attention
3.7.3 Masked attention
3.8 Encoder
3.9 Decoder
4 Full transformer architecture Toggle Full transformer architecture subsection
4.1 Sublayers
4.2 Pseudocode
4.3 Terminology
4.1 Sublayers
4.2 Pseudocode
4.3 Terminology
5 Subsequent work Toggle Subsequent work subsection
5.1 Alternative activation functions
5.2 Alternative normalizations
5.3 Alternative positional encodings
5.3.1 RoPE
5.3.2 ALiBi
5.3.3 Relative Position Encodings
5.4 Efficient implementation
5.4.1 KV caching
5.4.2 FlashAttention
5.4.3 Multi-Query Attention
5.4.4 Speculative decoding
5.5 Sub-quadratic transformers
5.5.1 Alternative attention graphs
5.5.2 Random Feature Attention
5.6 Multimodality
5.1 Alternative activation functions
5.2 Alternative normalizations
5.3 Alternative positional encodings
5.3.1 RoPE
5.3.2 ALiBi
5.3.3 Relative Position Encodings
5.3.1 RoPE
5.3.2 ALiBi
5.3.3 Relative Position Encodings
5.4 Efficient implementation
5.4.1 KV caching
5.4.2 FlashAttention
5.4.3 Multi-Query Attention
5.4.4 Speculative decoding
5.4.1 KV caching
5.4.2 FlashAttention
5.4.3 Multi-Query Attention
5.4.4 Speculative decoding
5.5 Sub-quadratic transformers
5.5.1 Alternative attention graphs
5.5.2 Random Feature Attention
5.5.1 Alternative attention graphs
5.5.2 Random Feature Attention
5.6 Multimodality
6 Applications
7 See also
8 Notes
9 References
10 Further reading [-]
Toggle the table of contents
Transformer (deep learning)
[-]
35 languages
Afrikaans
العربية
বাংলা
Bosanski
Català
کوردی
Čeština
Deutsch
Español
Eesti
Euskara
فارسی
Français
Gaeilge
Galego
עברית
Հայերեն
Bahasa Indonesia
Italiano
日本語
Qaraqalpaqsha
한국어
Norsk nynorsk
Polski
Português
Русский
Simple English
Српски / srpski
Svenska
ไทย
Türkçe
Українська
Tiếng Việt
粵語
中文
Edit links
Article
Talk [-]
English
Read
Edit
View history [-]
Tools
Tools
move to sidebar hide
Actions
Read
Edit
View history
General
What links here
Related changes
Upload file
Permanent link
Page information
Cite this page
Get shortened URL
Switch to legacy parser
Expand all
Edit interlanguage links
Print/export
Download as PDF
Printable version
In other projects
Abstract Wikipedia
Wikidata item
Appearance
move to sidebar hide
Text
[-] 0 Small [x] 1 Standard [-] 2 Large
This page always uses small font size
Width
[x] 1 Standard [-] 0 Wide
The content is as wide as possible for your browser window.
Color
[-] os Automatic [x] day Light [-] night Dark
This page is always in light mode.
From Wikipedia, the free encyclopedia
Algorithm for modelling sequential data
hide This article has multiple issues. Please help improve it or discuss these issues on the talk page. ( Learn how and when to remove these messages)
This article needs more citations. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.
Find sources: "Transformer" deep learning – news
· newspapers
· books
· scholar
· JSTOR ( June 2026) ( Learn how and when to remove this message)
Some of this article's listed sources may not be reliable. Please help improve this article by looking for better, more reliable sources. Unreliable citations may be challenged and removed. ( June 2026) ( Learn how and when to remove this message)
( Learn how and when to remove this message)
A standard transformer architecture, showing on the left an encoder, and on the right a decoder. Note: this uses the pre-LN convention, which is different from the post-LN convention used in the original 2017 transformer.
Part of a series on
Machine learning
and
data mining
show
Paradigms
Supervised learning
Unsupervised learning
Semi-supervised learning
Self-supervised learning
Reinforcement learning
Transfer learning
Meta-learning
Few-shot learning
Zero-shot learning
Online learning
Batch learning
Curriculum learning
Rule-based learning
Neuro-symbolic AI
Neuromorphic engineering
Quantum machine learning
show
Problems
Classification
Generative modeling
Regression
Clustering
Dimensionality reduction
Density estimation
Anomaly detection
Data cleaning
AutoML
Association rules
Semantic analysis
Structured prediction
Feature engineering
Feature learning
Learning to rank
Grammar induction
Ontology learning
Multimodal learning
show
Supervised learning
( classification
• regression)
Apprenticeship learning
Decision trees
Ensembles
Bagging
Boosting
Random forest
Bagging
Boosting
Random forest
k-NN
Linear regression
Naive Bayes
Artificial neural networks
Logistic regression
Perceptron
Relevance vector machine (RVM)
Support vector machine (SVM)
show
Clustering
BIRCH
CURE
Hierarchical
k-means
Fuzzy
Expectation–maximization (EM)
DBSCAN
OPTICS
Mean shift
show
Dimensionality reduction
Factor analysis
Exploratory
Exploratory
CCA
ICA
LDA
NMF
PCA
PGD
t-SNE
SDL
show
Structured prediction
Graphical models
Bayes net
Conditional random field
Hidden Markov
Bayes net
Conditional random field
Hidden Markov
show
Anomaly detection
RANSAC
k-NN
Local outlier factor
Isolation forest
hide
Neural networks
Autoencoder
Deep learning
Feedforward neural network
Recurrent neural network
LSTM
GRU
ESN
reservoir computing
LSTM
GRU
ESN
reservoir computing
Boltzmann machine
Restricted
Restricted
GAN
Diffusion model
SOM
Convolutional neural network
U-Net
LeNet
AlexNet
DeepDream
U-Net
LeNet
AlexNet
DeepDream
Neural field
Neural radiance field
Physics-informed neural networks
Neural radiance field
Physics-informed neural networks
Transformer
Vision
Vision
Mamba
Spiking neural network
Memtransistor
Electrochemical RAM (ECRAM)
show
Reinforcement learning
Q-learning
Policy gradient
SARSA
Temporal difference (TD)
Multi-agent
Self-play
Self-play
show
Learning with humans
Active learning
Crowdsourcing
Human-in-the-loop
Mechanistic interpretability
RLHF
show
Model diagnostics
Coefficient of determination
Confusion matrix
Learning curve
ROC curve
show
Mathematical foundations
Kernel machines
Bias–variance tradeoff
Computational learning theory
Empirical risk minimization
Occam learning
PAC learning
Statistical learning
VC theory
Topological deep learning
show
Journals and conferences
AAAI
CVPR
ECCV
ECML PKDD
EMNLP
ICCV
NeurIPS
ICML
ICLR
IJCAI
ML
JMLR
show
Related articles
Glossary of artificial intelligence
List of datasets for machine-learning research
List of datasets in computer vision and image processing
List of datasets in computer vision and image processing
Outline of machine learning
v
t
e
In deep learning, the transformer is a family of artificial neural network architectures based on the multi-head attention mechanism, in which input data such as text, images, or audio, is converted to a sequence of 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. Because self-attention alone is permutation-invariant, transformers inject positional information, typically through positional encodings or learned positional embeddings, so token order can affect the output. [1]
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 (LLMs) on large (language) datasets. [3] Modern transformer designs are commonly grouped into encoder-only, decoder-only, and encoder-decoder variants, depending on whether they are optimized for representation learning, autoregressive generation, or conditional sequence-to-sequence tasks. [4]
The original version of the transformer architecture was proposed in the 2017 paper " Attention Is All You Need" by researchers at Google. [1] The predecessors of transformers were developed as an improvement over previous architectures for machine translation, [5] [6] but have found many applications since. They are used in large-scale natural language processing, computer vision ( vision transformers), reinforcement learning, [7] [8] audio, [9] multimodal learning, robotics, [10] and playing chess. [11] It has also led to the development of pre-trained systems, such as generative pre-trained transformers (GPTs) [12] and BERT [13] (bidirectional encoder representations from transformers).
History
[ edit]
This section's style of writing may not reflect the encyclopedic tone used on Wikipedia. See Wikipedia's guide to writing better articles for suggestions. ( February 2026) ( Learn how and when to remove this message)
See also: Timeline of machine learning
Predecessors
[ edit]
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 (originally described in a 1995 technical report and formally published in 1997), [2] [note1] an RNN that introduced gating mechanisms to mitigate the vanishing gradient problem, allowing efficient learning of long-sequence modelling. One key architectural element was the use of multiplicative gating units, in which the outputs of some neurons modulate the outputs of others. These multiplicative units are conceptually distinct from the additive attention mechanism later introduced for sequence-to-sequence models. [14] Neural networks using multiplicative units were later called sigma-pi networks [15] or higher-order networks. [16] 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. [note2] 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. [17] One of its two networks has "fast weights" or "dynamic links" (1981). [18] [19] [20] 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. [17] This was later shown to be equivalent to the unnormalized linear transformer. [21] [22]
Attention with seq2seq
[ edit]
Main article: Seq2seq § History
The idea of encoder–decoder sequence transduction had been developed in the early 2010s; commonly cited as the originators that produced seq2seq are two concurrently published papers from 2014. [23] [24] [originalresearch?]
A 380M-parameter model for machine translation uses two long short-term memories (LSTM). [24] 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. [23] Later research showed that GRUs are neither better nor worse than LSTMs for seq2seq. [25] [26]
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. [27]
The RNN search 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". [5]
The relative performances were compared between global (that of RNN search) 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. [28]
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. [29] It took nine months to develop, and it outperformed the statistical approach, which took ten years to develop. [30]
Parallelizing attention
[ edit]
Main article: Attention (machine learning) § History
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. [31] One of its authors, Jakob Uszkoreit, suspected that attention without recurrence would be sufficient for language translation, thus the title "attention is all you need". [32] That hypothesis was against conventional wisdom at the time, and even his father Hans Uszkoreit, a well-known computational linguist, was skeptical. [32] In the same year, self-attention (called intra-attention or intra-sentence attention) was proposed for LSTMs. [33]
On 2017-06-12, the original (100M-parameter) encoder–decoder transformer model was published 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. [34]
AI boom era
[ edit]
As early as 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. [35] Transformer architecture is now used alongside many generative models that contribute to the ongoing AI boom.
The "reference implementation" of the original Transformer was written in a TensorFlow library. [36] [37] 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. [38] In October 2019, Google started using BERT to process search queries. [39] In 2020, Google Translate replaced the previous RNN-encoder–RNN-decoder model by a transformer-encoder–RNN-decoder model. [40]
Starting in 2018, the OpenAI GPT series of decoder-only transformers became state of the art in natural language generation. At the end of 2022, ChatGPT, a chatbot based on a fine-tuned variant of GPT-3.5, became unexpectedly [41] [42] popular, triggering a boom around large language models. [43] [44]
Transformers have been applied in modalities beyond text. Four days after the publication of "Attention is All You Need", a multimodal transformer architecture, MultiModel, was published by most authors of that paper. [45] Other examples include the vision transformer, [46] speech recognition, [47] robotics, [7] and multimodal. [48] The vision transformer, in turn, stimulated new developments in convolutional neural networks. [49] Image and video generators like DALL-E (2021), Stable Diffusion 3 (2024), [50] 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
[ edit]
Methods for stabilizing training
[ edit]
The plain transformer architecture had difficulty in 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) multihead attention and feedforward layers stabilizes training, not requiring learning rate warmup. [51] This is the "pre-LN Transformer" and is more commonly used, compared to the original "post-LN Transformer".
Pretrain-finetune
[ edit]
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:
language modeling [13]
next-sentence prediction [13]
question answering [3]
reading comprehension
sentiment analysis [1]
paraphrasing [1]
The T5 transformer report [52] documents a large number of natural language pretraining tasks. Some examples are:
restoring or repairing incomplete or corrupted text. For example, the input, "Thank you ~~ me to your party ~~ week", 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", [53] because even though it is syntactically well-formed, it is improbable in ordinary human usage: The course is jumping well.
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
[ edit]
See also: Large language model § Evaluation
In general, there are three classes of language modelling tasks: "masked", [54] "autoregressive", [55] and "prefixLM". [56] 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, [54] 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 = − ∑ t ∈ masked tokens ln ( probability of t conditional on its context ) {\displaystyle {\text{Loss}}=-\sum _{t\in {\text{masked tokens}}}\ln({\text{probability of }}t{\text{ 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. ("Masked" as in "masked language modelling" is not "masked" as in " masked attention".)
In an autoregressive task, [55] 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, [56] 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. ("PrefixLM" as in "prefix language modeling" is not "prefixLM" as in " prefix language model".)
Architecture
[ edit]
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. For example, pushing a vector through a linear layer means multiplying it by a weight matrix on the right, as x W {\displaystyle xW}
.
Tokenization
[ edit]
As the transformer architecture natively consists of operations over numbers (matrix multiplications, dot products, activation functions) rather than over text, there must first be a mapping from any input text to some numerical representation. This happens in three steps.
First, the input text is treated by a preprocessor, which performs both textual transformations and splits the text into coarse-grained segments called pretokens. The latter is referred to as pretokenization. Second, each pretoken is segmented further into tokens by a tokenizer that expects to only see pretokens output by its preprocessor. Each token it produces is a string of one or more characters belonging to a finite set of strings called the vocabulary V {\displaystyle V}
. Third, because the vocabulary is finite and known beforehand, each token can be assigned an integer identifier, and this mapping is applied to the sequence of tokens to represent any input text as a numerical sequence. Since this mapping is bijective, the output side can produce a sequence of integer identifiers which can then be turned back into tokens. After undoing some of the preprocessing, the result is again legible text.
Training a tokenizer (sometimes referred to as vocabularization) means finding a suitable vocabulary V {\displaystyle V}
, but also learning how to use it, since any given string s {\displaystyle s}
of length | s | {\displaystyle |s|}
has 2 | s | − 1 {\displaystyle 2^{|s|-1}}
hypothetical segmentations, some of which containing segments that are not in the vocabulary. The most important hyperparameter during vocabularization is the vocabulary size | V | {\displaystyle |V|}
: when it is small, the learned vocabulary generally consists of characters and smaller strings, and words will be segmented into many tokens. At larger sizes, it becomes affordable to dedicate tokens to full words, although depending on the preprocessor and tokenizer, it is not necessarily the case that large vocabularies will always use the largest token(s) available to segment a word.
Because tokens are not always full words, they may also be referred to as subwords and tokenization algorithms may be referred to as subword tokenizers. This is also to differentiate these systems from traditional terminology used in older information retrieval and natural language processing systems, where "tokenization" was used to denote what is today called "pretokenization" (very crudely: splitting into words). In tokenizers that produce tokens that are not part of the vocabulary, a special token that does belong to the vocabulary is used as a generic stand-in, written as "[UNK]" for "unknown". In principle, any string could be hidden by such an [UNK]. Indeed, in information retrieval, pretokenizers were themselves used as tokenizers (and also called "tokenizers") with a word-level vocabulary that contained an [UNK].
Commonly used subword tokenization algorithms are byte pair encoding (BPE) and the unigram language model (ULM), which each include a vocabularization algorithm and a dedicated segmentation algorithm. There also exist several segmentation algorithms that require no learning and can be applied given a vocabulary (produced by BPE or ULM, for example), like greedily recognising tokens in a pretoken by moving through it left-to-right. Well-known software implementations of subword tokenizers are Hugging Face's tokenizers Python package implemented in Rust, and the sentencepiece Python package implemented in C++. The latter package is named as such because one of its configuration options allows disabling the built-in pretokenizer, hence effectively making entire sentences a pretoken and thus having the tokenizer see entire sentences, rather than individual words.
Embedding
[ edit]
Further information: Word embedding
Each integer token identifier is converted into an embedding vector via a lookup table. Equivalently stated, it multiplies a one-hot representation of the token identifier by an embedding matrix M {\displaystyle M}
. For example, if the input token's identifier is 3 {\displaystyle 3}
, then the one-hot representation is [ 0 , 0 , 0 , 1 , 0 , 0 , … ] {\displaystyle [0,0,0,1,0,0,\dots ]}
, and its embedding vector is E m b e d ( 3 ) = [ 0 , 0 , 0 , 1 , 0 , 0 , … ] M {\displaystyle \mathrm {Embed} (3)=[0,0,0,1,0,0,\dots ]M}
The token embedding vectors are added to their respective positional encoding vectors (see below), producing the sequence of input vectors.
The dimension of an embedding vector is called hidden size or embedding size and written as d emb {\displaystyle d_{\text{emb}}}
. [38] This size is written as d model {\displaystyle d_{\text{model}}}
in the original transformer paper. [1]
Un-embedding
[ edit]
An un-embedding layer is almost the reverse of an embedding layer. Whereas an embedding layer converts a token identifier into a vector, an un-embedding layer converts a vector into a probability distribution over tokens.
An illustration of the top 16 token probabilities at temperature 1, for each output token in the chain-of-thought response, with colour representing how that output differs from the same prompt but at temperature 0.
The un-embedding layer is a linear- softmax layer: U n E m b e d ( x ) = s o f t m a x ( x W + b ) {\displaystyle \mathrm {UnEmbed} (x)=\mathrm {softmax} (xW+b)}
The matrix has shape ( d emb , | V | ) {\displaystyle (d_{\text{emb}},|V|)}
. Some architectures use the transpose of the embedding matrix M {\displaystyle M}
as the un-embedding matrix W {\displaystyle W}
in order to avoid needing double the amount of embedding-related parameters and to avoid divergence during training. This practice is called weight tying. [57]
Positional encoding
[ edit]
Illustration of (absolute) positional encoding with parameters N = 10000 , d = 100 {\displaystyle 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 induces 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 : R → R d {\displaystyle f:\mathbb {R} \to \mathbb {R} ^{d}}
, where d {\displaystyle d}
is a positive even integer. The full positional encoding defined in the original paper [1] is: ( f ( t ) 2 k , f ( t ) 2 k + 1 ) = ( sin ( θ ) , cos ( θ ) ) ∀ k ∈ { 0 , 1 , … , d / 2 − 1 } {\displaystyle (f(t){2k},f(t){2k+1})=(\sin(\theta ),\cos(\theta ))\quad \forall k\in {0,1,\ldots ,d/2-1}}
where θ = t r k , r = N 2 / d {\displaystyle \theta ={\frac {t}{r^{k}}},r=N^{2/d}}
.
Here, N {\displaystyle N}
is a free parameter that should be significantly larger than the biggest k {\displaystyle k}
that would be input into the positional encoding function. The original paper uses N = 10000 {\displaystyle N=10000}
.
The function is in a simpler form when written as a complex function of type f : R → C d / 2 {\displaystyle f:\mathbb {R} \to \mathbb {C} ^{d/2}}
f ( t ) = ( e i t / r k ) k = 0 , 1 , … , d 2 − 1 {\displaystyle f(t)=\left(e^{it/r^{k}}\right)_{k=0,1,\ldots ,{\frac {d}{2}}-1}}
where r = N 2 / d {\displaystyle r=N^{2/d}}
.
The main reason for using this positional encoding function is that using it, shifts are linear transformations: f ( t + Δ t ) = d i a g ( f ( Δ t ) ) f ( t ) {\displaystyle f(t+\Delta t)=\mathrm {diag} (f(\Delta t))f(t)}
where Δ t ∈ R {\displaystyle \Delta t\in \mathbb {R} }
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: ∑ j c j f ( t + Δ t j ) = ( ∑ j c j d i a g ( f ( Δ t j ) ) ) f ( t ) {\displaystyle \sum {j}c{j}f(t+\Delta t_{j})=\left(\sum {j}c{j},\mathrm {diag} (f(\Delta t_{j}))\right)f(t)}
for any constants c j {\displaystyle c_{j}}
. 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)
[ edit]
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). [58] [59]
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. [59] These feed-forward layers contain most of the parameters in a transformer model.
Feedforward network
[ edit]
The feedforward network module. It is a two-layered network that maps d emb {\displaystyle d_{\text{emb}}}
-dimensional vectors into d emb {\displaystyle d_{\text{emb}}}
-dimensional vectors.
The feedforward network (FFN) modules in a transformer are 2-layered multilayer perceptrons: F F N ( x ) = ϕ ( x W ( 1 ) + b ( 1 ) ) W ( 2 ) + b ( 2 ) {\displaystyle \mathrm {FFN} (x)=\phi (xW^{(1)}+b^{(1)})W^{(2)}+b^{(2)}}
where W ( 1 ) {\displaystyle W^{(1)}}
and W ( 2 ) {\displaystyle W^{(2)}}
are weight matrices and b ( 1 ) {\displaystyle b^{(1)}}
and b ( 2 ) {\displaystyle b^{(2)}}
are bias vectors, and ϕ {\displaystyle \phi }
is its activation function. The original transformer used ReLU activation.
The number of neurons in the middle layer is called intermediate size (GPT), [60] filter size (BERT), [38] or feedforward size (BERT). [38] 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: d ffn = 4 d emb {\displaystyle d_{\text{ffn}}=4d_{\text{emb}}}
.
Scaled dot-product attention
[ edit]
Main article: Dot-product attention
Attention head
[ edit]
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 W Q {\displaystyle W^{Q}}
, the key weights W K {\displaystyle W^{K}}
, and the value weights W V {\displaystyle W^{V}}
.
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 {\displaystyle \ell _{\text{seq, query}}}
, and each entry is a vector of dimension d emb, query {\displaystyle d_{\text{emb, query}}}
. Similarly for the key and value sequences.
For each vector x i , query {\displaystyle x_{i,{\text{query}}}}
in the query sequence, it is multiplied by a matrix W Q {\displaystyle W^{Q}}
to produce a query vector q i = x i , query W Q {\displaystyle q_{i}=x_{i,{\text{query}}}W^{Q}}
. The matrix of all query vectors is the query matrix: Q = X query W Q {\displaystyle Q=X_{\text{query}}W^{Q}}
Similarly, we construct the key matrix K = X key W K {\displaystyle K=X_{\text{key}}W^{K}}
and the value matrix V = X value W V {\displaystyle V=X_{\text{value}}W^{V}}
.
It is usually the case that all W Q , W K , W V {\displaystyle W^{Q},W^{K},W^{V}}
are square matrices, meaning d emb, query = d query {\displaystyle d_{\text{emb, query}}=d_{\text{query}}}
, etc.
Attention weights are calculated using the query and key vectors: the attention weight a i j {\displaystyle a_{ij}}
from token i {\displaystyle i}
to token j {\displaystyle j}
is the dot product between q i {\displaystyle q_{i}}
and k j {\displaystyle k_{j}}
. The attention weights are divided by the square root of the dimension of the key vectors, d k {\displaystyle {\sqrt {d_{k}}}}
, which stabilizes gradients during training, and passed through a softmax which normalizes the weights. The fact that W Q {\displaystyle W^{Q}}
and W K {\displaystyle W^{K}}
are different matrices allows attention to be non-symmetric: if token i {\displaystyle i}
attends to token j {\displaystyle j}
(i.e. q i ⋅ k j {\displaystyle q_{i}\cdot k_{j}}
is large), this does not necessarily mean that token j {\displaystyle j}
will attend to token i {\displaystyle i}
(i.e. q j ⋅ k i {\displaystyle q_{j}\cdot k_{i}}
could be small). The output of the attention unit for token i {\displaystyle i}
is the weighted sum of the value vectors of all tokens, weighted by a i j {\displaystyle a_{ij}}
, the attention from token i {\displaystyle 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 {\displaystyle Q}
, K {\displaystyle K}
and V {\displaystyle V}
are defined as the matrices where the i {\displaystyle i}
th rows are vectors q i {\displaystyle q_{i}}
, k i {\displaystyle k_{i}}
, and v i {\displaystyle v_{i}}
respectively. Then we can represent the attention as Attention ( Q , K , V ) = softmax ( Q K T d k ) V {\displaystyle {\begin{aligned}{\text{Attention}}(Q,K,V)={\text{softmax}}\left({\frac {QK^{\mathrm {T} }}{\sqrt {d_{k}}}}\right)V\end{aligned}}}
where the softmax is applied over each of the rows of the matrix.
The number of dimensions in a query vector is query size d query {\displaystyle d_{\text{query}}}
and similarly for the key size d key {\displaystyle d_{\text{key}}}
and value size d value {\displaystyle d_{\text{value}}}
. The output dimension of an attention head is its head dimension d head {\displaystyle d_{\text{head}}}
. The attention mechanism requires the following three equalities to hold: ℓ seq, key = ℓ seq, value , d query = d key , d value = d head {\displaystyle \ell {\text{seq, key}}=\ell {\text{seq, value}},;d{\text{query}}=d{\text{key}},;d_{\text{value}}=d_{\text{head}}}
but is otherwise unconstrained.
If the attention head is used in a self-attention fashion, then X query = X key = X value {\displaystyle X_{\text{query}}=X_{\text{key}}=X_{\text{value}}}
. If the attention head is used in a cross-attention fashion, then usually X query ≠ X key = X value {\displaystyle X_{\text{query}}\neq X_{\text{key}}=X_{\text{value}}}
. It is theoretically possible for all three to be different, but that is rarely the case in practice.
Multihead attention
[ edit]
Multihead attention, block diagram Exact dimension counts within a multihead attention module
One set of ( W Q , W K , W V ) {\displaystyle \left(W^{Q},W^{K},W^{V}\right)}
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, W Q {\displaystyle W^{Q}}
and W K {\displaystyle W^{K}}
, which are involved in the attention score computation, defines the "relevance". Meanwhile, the value projection matrix W V {\displaystyle W^{V}}
, in combination with the part of the output projection matrix W O {\displaystyle W^{O}}
, 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. [61] 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 feedforward neural network layers.
Concretely, let the multiple attention heads be indexed by i {\displaystyle i}
, then we have MultiheadAttention ( Q , K , V ) = Concat i ∈ [ n heads ] ( Attention ( X W i Q , X W i K , X W i V ) ) W O {\displaystyle {\text{MultiheadAttention}}(Q,K,V)={\text{Concat}}{i\in [n{\text{heads}}]}({\text{Attention}}(XW_{i}^{Q},XW_{i}^{K},XW_{i}^{V}))W^{O}}
where the matrix X {\displaystyle X}
is the concatenation of word embeddings, and the matrices W i Q , W i K , W i V {\displaystyle W_{i}^{Q},W_{i}^{K},W_{i}^{V}}
are "projection matrices" owned by individual attention head i {\displaystyle i}
, and W O {\displaystyle W^{O}}
is a final projection matrix owned by the whole multihead attention head.
It is theoretically possible for each attention head to have a different head dimension d head {\displaystyle d_{\text{head}}}
, 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: d emb = 768 , n head = 12 , d head = 64 {\displaystyle d_{\text{emb}}=768,n_{\text{head}}=12,d_{\text{head}}=64}
Since 12 × 64 = 768 {\displaystyle 12\times 64=768}
, its output projection matrix W O ∈ R ( 12 × 64 ) × 768 {\displaystyle W^{O}\in \mathbb {R} ^{(12\times 64)\times 768}}
is a square matrix.
Masked attention
[ edit]
The transformer architecture is constructed to calculate output tokens iteratively. Assuming t = 0 {\displaystyle t=0}
refers to the calculation of the first output token i = 0 {\displaystyle i=0}
, for step t > 0 {\displaystyle t>0}
, the output token i = 0 {\displaystyle i=0}
shall remain constant. This ensures properties of the model similar to autoregressive models. [1] Therefore, at every time step t {\displaystyle t}
, the calculation for all outputs i {\displaystyle i}
should not have access to tokens at position j {\displaystyle j}
for j >= i {\displaystyle j>=i}
(as it naturally is the case for time step t = i {\displaystyle t=i}
, when tokens j > t {\displaystyle j>t}
are not yet calculated). This behavior may be accomplished before the softmax stage by adding a mask matrix M {\displaystyle M}
that is − ∞ {\displaystyle -\infty }
at entries where the attention link must be cut, and 0 {\displaystyle 0}
at other places: MaskedAttention ( Q , K , V ) = softmax ( M + Q K T d k ) V {\displaystyle {\begin{aligned}{\text{MaskedAttention}}(Q,K,V)={\text{softmax}}\left(M+{\frac {QK^{\mathrm {T} }}{\sqrt {d_{k}}}}\right)V\end{aligned}}}
The following matrix is commonly used in decoder self-attention modules, called "causal masking": M causal = [ 0 − ∞ − ∞ … − ∞ 0 0 − ∞ … − ∞ 0 0 0 … − ∞ ⋮ ⋮ ⋮ ⋱ ⋮ 0 0 0 … 0 ] {\displaystyle M_{\text{causal}}={\begin{bmatrix}0&-\infty &-\infty &\dots &-\infty \0&0&-\infty &\dots &-\infty \0&0&0&\dots &-\infty \\vdots &\vdots &\vdots &\ddots &\vdots \0&0&0&\dots &0\end{bmatrix}}}
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 P M causal P − 1 {\displaystyle PM_{\text{causal}}P^{-1}}
, where P {\displaystyle P}
is a random permutation matrix. [62]
Encoder
[ edit]
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 h 0 , h 1 , … combine them into a matrix H = [ h 0 h 1 ⋮ ] EncoderLayer ( H ) = [ FFN ( MultiheadAttention ( H , H , H ) 0 ) FFN ( MultiheadAttention ( H , H , H ) 1 ) ⋮ ] {\displaystyle {\begin{aligned}{\text{given input vectors }}&h_{0},h_{1},\dots \{\text{combine them into a matrix }}H&={\begin{bmatrix}h_{0}\h_{1}\\vdots \end{bmatrix}}\{\text{EncoderLayer}}(H)&={\begin{bmatrix}{\text{FFN}}({\text{MultiheadAttention}}(H,H,H){0})\{\text{FFN}}({\text{MultiheadAttention}}(H,H,H){1})\\vdots \end{bmatrix}}\\end{aligned}}}
where FFN {\displaystyle {\text{FFN}}}
stands for "feed-forward network". We can more succinctly write it as EncoderLayer ( H ) = FFN ( MultiheadAttention ( H , H , H ) ) {\displaystyle {\text{EncoderLayer}}(H)={\text{FFN}}({\text{MultiheadAttention}}(H,H,H))}
with the implicit convention that the FFN {\displaystyle {\text{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
[ edit]
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] [59]
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 ′ = MaskedMultiheadAttention ( H , H , H ) DecoderLayer ( H ) = FFN ( MultiheadAttention ( H ′ , H E , H E ) ) {\displaystyle {\begin{aligned}H'&={\text{MaskedMultiheadAttention}}(H,H,H)\{\text{DecoderLayer}}(H)&={\text{FFN}}({\text{MultiheadAttention}}(H',H^{E},H^{E}))\end{aligned}}}
where H E {\displaystyle H^{E}}
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.
Full transformer architecture
[ edit]
Sublayers
[ edit]
(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, (denoted as "LayerNorm", or "LN" in the following), which while conceptually unnecessary, are necessary for numerical stability and convergence.
The residual connections are introduced to avoid vanishing gradient issues and stabilize the training process. They can be expressed by x ↦ F ( x ) + x {\displaystyle x\mapsto F(x)+x}
, where F {\displaystyle F}
is a given component of the transformer. Adding the input x {\displaystyle x}
can preserve the input information and avoid issues when the gradient of F ( x ) {\displaystyle F(x)}
is close to zero.
Similarly to how the feedforward network modules are applied individually to each vector, the LayerNorm is also applied individually to each vector.
There 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 L a y e r N o r m ( x + S u b l a y e r ( x ) ) {\displaystyle \mathrm {LayerNorm} (x+\mathrm {Sublayer} (x))}
where S u b l a y e r ( x ) {\displaystyle \mathrm {Sublayer} (x)}
is the function implemented by the sublayer itself.
In the pre-LN convention, the output of each sublayer is x + S u b l a y e r ( L a y e r N o r m ( x ) ) {\displaystyle x+\mathrm {Sublayer} (\mathrm {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, [63] was found to be easier to train, requiring no warm-up, leading to faster convergence. [51]
Pseudocode
[ edit]
The following is the pseudocode for a standard pre-LN encoder–decoder transformer, adapted from Formal Algorithms for Transformers [64]
Terminology
[ edit]
The transformer architecture, being modular, allows variations. Several common variations are described here. [52]
An "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. [56] They are also referred to as "all-to-all" or "BERT-like".
A "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. They are also referred to as "autoregressive" or "causal".
An "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. [52]
A "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 [52] :Figure3 M prefixLM = [ 0 − ∞ 0 M causal ] {\displaystyle M_{\text{prefixLM}}={\begin{bmatrix}\mathbf {0} &-\infty \\mathbf {0} &M_{\text{causal}}\end{bmatrix}}}
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. [56]
There are also mixed seq2seq models. For example, in 2020, Google Translate replaced the previous RNN-encoder–RNN-decoder model with a transformer-encoder–RNN-decoder model, as transformer-based decoders did not appear to significantly increase quality unlike the encoder, while the RNN decoder was much faster. [40]
Subsequent work
[ edit]
Alternative activation functions
[ edit]
The original transformer uses ReLU activation function. Other activation functions were developed. The Llama series and PaLM used SwiGLU; [65] both GPT-1 and BERT [38] used GELU. [66]
Alternative activation functions are often used in combination with Gated Linear Units in the feedforward module. [65]
Alternative normalizations
[ edit]
The normalization used in the transformer can be different from LayerNorm. One example is RMSNorm [67] which is used in the Llama series. Other examples include ScaleNorm [68] and FixNorm. [68]
Alternative positional encodings
[ edit]
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
[ edit]
RoPE (rotary positional embedding), [72] is best explained by considering a list of 2-dimensional vectors [ ( x 1 ( 1 ) , x 1 ( 2 ) ) , ( x 2 ( 1 ) , x 2 ( 2 ) ) , ( x 3 ( 1 ) , x 3 ( 2 ) ) , ... ] {\displaystyle [(x_{1}^{(1)},x_{1}^{(2)}),(x_{2}^{(1)},x_{2}^{(2)}),(x_{3}^{(1)},x_{3}^{(2)}),...]}
. Now pick some angle θ {\displaystyle \theta }
. Then RoPE encoding is RoPE ( x m ( 1 ) , x m ( 2 ) , m ) = ( cos m θ − sin m θ sin m θ cos m θ ) ( x m ( 1 ) x m ( 2 ) ) = ( x m ( 1 ) cos m θ − x m ( 2 ) sin m θ x m ( 2 ) cos m θ + x m ( 1 ) sin m θ ) {\displaystyle {\text{RoPE}}{\big (}x_{m}^{(1)},x_{m}^{(2)},m{\big )}={\begin{pmatrix}\cos m\theta &-\sin m\theta \\sin m\theta &\cos m\theta \end{pmatrix}}{\begin{pmatrix}x_{m}^{(1)}\x_{m}^{(2)}\\end{pmatrix}}={\begin{pmatrix}x_{m}^{(1)}\cos m\theta -x_{m}^{(2)}\sin m\theta \x_{m}^{(2)}\cos m\theta +x_{m}^{(1)}\sin m\theta \\end{pmatrix}}}
Equivalently, if we write the 2-dimensional vectors as complex numbers z m := x m ( 1 ) + i x m ( 2 ) {\displaystyle z_{m}:=x_{m}^{(1)}+ix_{m}^{(2)}}
, then RoPE encoding is just multiplication by an angle: RoPE ( z m , m ) = e i m θ z m {\displaystyle {\text{RoPE}}{\big (}z_{m},m{\big )}=e^{im\theta }z_{m}}
For a list of 2 n {\displaystyle 2n}
-dimensional vectors, a RoPE encoder is defined by a sequence of angles θ ( 1 ) , ... , θ ( n ) {\displaystyle \theta ^{(1)},...,\theta ^{(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 ) T RoPE ( y , n ) = RoPE ( x , m + k ) T RoPE ( y , n + k ) {\displaystyle {\text{RoPE}}{\big (}x,m{\big )}^{T}{\text{RoPE}}{\big (}y,n{\big )}={\text{RoPE}}{\big (}x,m+k{\big )}^{T}{\text{RoPE}}{\big (}y,n+k{\big )}}
for any integer k {\displaystyle k}
.
ALiBi
[ edit]
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 is Attention ( Q , K , V ) = softmax ( Q K T d k + s B ) V {\displaystyle {\begin{aligned}{\text{Attention}}(Q,K,V)={\text{softmax}}\left({\frac {QK^{\mathrm {T} }}{\sqrt {d_{k}}}}+sB\right)V\end{aligned}}}
Here, s {\displaystyle s}
is a real number ("scalar"), and B {\displaystyle B}
is the linear bias matrix defined by B = ( 0 1 2 3 ⋯ − 1 0 1 2 ⋯ − 2 − 1 0 1 ⋯ − 3 − 2 − 1 0 ⋯ ⋮ ⋮ ⋮ ⋮ ⋱ ) {\displaystyle B={\begin{pmatrix}0&1&2&3&\cdots \-1&0&1&2&\cdots \-2&-1&0&1&\cdots \-3&-2&-1&0&\cdots \\vdots &\vdots &\vdots &\vdots &\ddots \\end{pmatrix}}}
in other words, B i , j = j − i {\displaystyle B_{i,j}=j-i}
. The idea being that the linear bias matrix is a softened mask. Just as 0 {\displaystyle 0}
represent full attention paid, and − ∞ {\displaystyle -\infty }
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
[ edit]
Relative Position Encodings [74] is similar to ALiBi, but more generic: Attention ( Q , K , V ) = softmax ( Q K T d k + B ) V {\displaystyle {\begin{aligned}{\text{Attention}}(Q,K,V)={\text{softmax}}\left({\frac {QK^{\mathrm {T} }}{\sqrt {d_{k}}}}+B\right)V\end{aligned}}}
where B {\displaystyle B}
is a Toeplitz matrix, that is, B i , j = B i ′ , j ′ {\displaystyle B_{i,j}=B_{i',j'}}
whenever i − j = i ′ − j ′ {\displaystyle i-j=i'-j'}
. This is contrasted with the original sinusoidal positional encoding, which is an "absolute positional encoding". [75]
Efficient implementation
[ edit]
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. [12]
KV caching
[ edit]
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 real-time interactions, such as in online chatbots.
In general, when a user uses an autoregressive transformer to generate a continuation to a sequence of tokens, the model would first perform a forward-pass on this sequence, whereby the KV caches over this sequence are computed. This is called prefilling. Hyperscalers serving large Transformer models may use disaggregated inference, wherein prefilling and decoding are performed on separately specialized hardware. [79]
FlashAttention
[ edit]
FlashAttention [80] 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).
The FlashAttention method is a communication-avoiding algorithm that fuses these operations into a single loop, increasing the arithmetic intensity. It is an online algorithm that computes the following quantities: [81] [82] z i = q T k i m i = max ( z 1 , … , z i ) = max ( m i − 1 , z i ) ℓ i = e z 1 − m i + ⋯ + e z i − m i = e m i − 1 − m i ℓ i − 1 + e z i − m i o i = e z 1 − m i v 1 + ⋯ + e z i − m i v i = e m i − 1 − m i o i − 1 + e z i − m i v i {\displaystyle {\begin{aligned}z_{i}&=q^{T}k_{i}&\m_{i}&=\max(z_{1},\dots ,z_{i})&={}&\max(m_{i-1},z_{i})\\ell {i}&=e^{z{1}-m_{i}}+\dots +e^{z_{i}-m_{i}}&={}&e^{m_{i-1}-m_{i}}\ell {i-1}+e^{z{i}-m_{i}}\o_{i}&=e^{z_{1}-m_{i}}v_{1}+\dots +e^{z_{i}-m_{i}}v_{i}&={}&e^{m_{i-1}-m_{i}}o_{i-1}+e^{z_{i}-m_{i}}v_{i}\end{aligned}}}
and returns o N / ℓ N {\displaystyle o_{N}/\ell _{N}}
. In practice, FlashAttention operates over multiple queries and keys per loop iteration, in a similar way as blocked matrix multiplication. If backpropagation is needed, then the output vectors and the intermediate arrays [ m 1 , … , m N ] , [ ℓ 1 , … , ℓ N ] {\displaystyle [m_{1},\dots ,m_{N}],[\ell _{1},\dots ,\ell _{N}]}
are cached, and during the backward pass, attention matrices are rematerialized from these, making it a form of gradient checkpointing.
An improved version, FlashAttention-2, [83] [84] [85] 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). [86]
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.
FlashAttention-4 focuses on pipelining to increase instruction throughput, and was developed to perform particularly well on Blackwell GPUs. [87]
Multi-Query Attention
[ edit]
Comparison between several different forms of attention mechanism and the amount of KV caching necessary for each
Multi-Query Attention changes the Multihead Attention mechanism. [88] Whereas normally,
MultiheadAttention ( Q , K , V ) = Concat i ∈ [ n heads ] ( Attention ( X W i Q , X W i K , X W i V ) ) W O {\displaystyle {\text{MultiheadAttention}}(Q,K,V)={\text{Concat}}{i\in [n{\text{heads}}]}\left({\text{Attention}}(XW_{i}^{Q},XW_{i}^{K},XW_{i}^{V})\right)W^{O}}
with Multi-Query Attention, there is just one W K , W V {\displaystyle W^{K},W^{V}}
, thus:
MultiQueryAttention ( Q , K , V ) = Concat i ∈ [ n heads ] ( Attention ( X W i Q , X W K , X W V ) ) W O {\displaystyle {\text{MultiQueryAttention}}(Q,K,V)={\text{Concat}}{i\in [n{\text{heads}}]}\left({\text{Attention}}(XW_{i}^{Q},XW^{K},XW^{V})\right)W^{O}}
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 Multihead Attention is GQA with the maximal number of groups. [89]
The architecture of V2, showing both MLA and a variant of mixture of experts [90] :Figure2
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. [90]
Speculative decoding
[ edit]
Main article: Speculative decoding
Speculative decoding [91] [92] 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 x 1 , x 2 , ... , x 512 {\displaystyle x_{1},x_{2},...,x_{512}}
, taking time 512 T GPT-3 {\displaystyle 512T_{\text{GPT-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 x t {\displaystyle x_{t}}
is indeed the token with the largest log-likelihood in the t {\displaystyle 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 {\displaystyle {\tilde {x}}{1},{\tilde {x}}{2},{\tilde {x}}{3},{\tilde {x}}{4}}
. This only takes 4 T GPT-3-small {\displaystyle 4T_{\text{GPT-3-small}}}
. These tokens are then run through the larger GPT-3 in one go. Suppose that x ~ 1 {\displaystyle {\tilde {x}}_{1}}
and x ~ 2 {\displaystyle {\tilde {x}}_{2}}
are verified by GPT-3 as what it would have picked, then those are kept, but x ~ 3 {\displaystyle {\tilde {x}}_{3}}
is not, so x ~ 3 , x ~ 4 {\displaystyle {\tilde {x}}{3},{\tilde {x}}{4}}
are discarded, and GPT-3 is run on those. This would take 4 T GPT-3-small + 3 T GPT-3 {\displaystyle 4T_{\text{GPT-3-small}}+3T_{\text{GPT-3}}}
, which might be shorter than 4 T GPT-3 {\displaystyle 4T_{\text{GPT-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. [91] [93]
Multi-token prediction
In 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. [94] [95]
Sub-quadratic transformers
[ edit]
Training transformer-based architectures can be expensive, especially for long inputs. [96] 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. [97] In the audio domain, SepTr decouples the attention in time and frequency domains. [98] Long Range Arena (2020) [99] is a standard benchmark for comparing the behavior of transformer architectures over long inputs.
Alternative attention graphs
[ edit]
The standard attention graph is either all-to-all or causal, both of which scales as O ( N 2 ) {\displaystyle O(N^{2})}
where N {\displaystyle N}
is the number of tokens in a sequence.
Reformer (2020) [96] [100] reduces the computational load from O ( N 2 ) {\displaystyle O(N^{2})}
to O ( N ln N ) {\displaystyle O(N\ln N)}
by using locality-sensitive hashing and reversible layers. [101]
Sparse attention [102] uses attention graphs that grows slower than O ( N 2 ) {\displaystyle O(N^{2})}
. For example, BigBird (2020) [103] uses random small-world networks which grows as O ( N ) {\displaystyle O(N)}
.
Ordinary transformers require a memory size that is quadratic in the size of the context window. Attention-free transformers [104] reduce this to a linear dependence while still retaining the advantages of a transformer by linking the key to the value.
Random Feature Attention
[ edit]
Random Feature Attention (2021) [105] uses Fourier random features: φ ( x ) = 1 D [ cos ⟨ w 1 , x ⟩ , sin ⟨ w 1 , x ⟩ , ⋯ cos ⟨ w D , x ⟩ , sin ⟨ w D , x ⟩ ] T {\displaystyle \varphi (x)={\frac {1}{\sqrt {D}}}[\cos \langle w_{1},x\rangle ,\sin \langle w_{1},x\rangle ,\cdots \cos \langle w_{D},x\rangle ,\sin \langle w_{D},x\rangle ]^{T}}
where w 1 , ... , w D {\displaystyle w_{1},...,w_{D}}
are independent samples from the normal distribution N ( 0 , σ 2 I ) {\displaystyle N(0,\sigma ^{2}I)}
. This choice of parameters satisfy E [ ⟨ φ ( x ) , φ ( y ) ⟩ ] = e − ‖ x − y ‖ 2 2 σ 2 {\displaystyle \mathbb {E} [\langle \varphi (x),\varphi (y)\rangle ]=e^{-{\frac {|x-y|^{2}}{2\sigma ^{2}}}}}
, or e ⟨ x , y ⟩ / σ 2 = E [ ⟨ e ‖ x ‖ 2 / 2 σ 2 φ ( x ) , e ‖ y ‖ 2 / 2 σ 2 φ ( y ) ⟩ ] ≈ ⟨ e ‖ x ‖ 2 / 2 σ 2 φ ( x ) , e ‖ y ‖ 2 / 2 σ 2 φ ( y ) ⟩ {\displaystyle e^{\langle x,y\rangle /\sigma ^{2}}=\mathbb {E} [\langle e^{|x|^{2}/2\sigma ^{2}}\varphi (x),e^{|y|^{2}/2\sigma ^{2}}\varphi (y)\rangle ]\approx \langle e^{|x|^{2}/2\sigma ^{2}}\varphi (x),e^{|y|^{2}/2\sigma ^{2}}\varphi (y)\rangle }
Consequently, the one-headed attention, with one query, can be written as Attention ( q , K , V ) = softmax ( q K T d k ) V ≈ φ ( q ) T ∑ i e ‖ k i ‖ 2 / 2 σ 2 φ ( k i ) v i T φ ( q ) T ∑ i e ‖ k i ‖ 2 / 2 σ 2 φ ( k i ) {\displaystyle {\text{Attention}}(q,K,V)={\text{softmax}}\left({\frac {qK^{\mathrm {T} }}{\sqrt {d_{k}}}}\right)V\approx {\frac {\varphi (q)^{T}\sum {i}e^{|k{i}|^{2}/2\sigma ^{2}}\varphi (k_{i})v_{i}^{T}}{\varphi (q)^{T}\sum {i}e^{|k{i}|^{2}/2\sigma ^{2}}\varphi (k_{i})}}}
where σ = d K 1 / 4 {\displaystyle \sigma =d_{K}^{1/4}}
. Similarly for multiple queries, and for multihead attention.
This approximation can be computed in linear time, as we can compute the matrix φ ( k i ) v i T {\displaystyle \varphi (k_{i})v_{i}^{T}}
first, then multiply it with the query. In essence, we have managed to obtain a more precise version of Attention ( Q , K , V ) = softmax ( Q K T d k ) V ≈ Q ( K T V / d k ) {\displaystyle {\text{Attention}}(Q,K,V)={\text{softmax}}\left({\frac {QK^{\mathrm {T} }}{\sqrt {d_{k}}}}\right)V\approx Q(K^{T}V/{\sqrt {d_{k}}})}
Performer (2022) [106] uses the same Random Feature Attention, but w 1 , ... , w D {\displaystyle w_{1},...,w_{D}}
are first independently sampled from the normal distribution N ( 0 , σ 2 I ) {\displaystyle N(0,\sigma ^{2}I)}
, then they are Gram–Schmidt processed.
Multimodality
[ edit]
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. [107] The LLaVA was a vision-language model composed of a language model (Vicuna-13B) [108] and a vision model ( ViT-L/14), connected by a linear layer. Only the linear layer is finetuned. [109]
Vision transformers [46] adapt the transformer to computer vision by breaking down input images as a series of patches, turning them into vectors, and treating them like embedding vector of tokens in a standard transformer.
Conformer [47] and later Whisper [110] 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 embedding vector of tokens in a standard transformer.
Perceivers [111] [112] are a variant of transformers designed for multimodality.
For image generation, notable architectures are DALL-E 1 (2021), Parti (2022), [113] Phenaki (2023), [114] and Muse (2023). [115] 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. [116] Parti is an encoder–decoder transformer, where the encoder processes a text prompt, and the decoder generates a token representation of an image. [117] 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. [115] 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. [114]
Applications
[ edit]
The transformer has had great success in natural language processing (NLP). Many large language models such as GPT-2, GPT-3, GPT-4, Gemini, AlbertAGPT, Claude, BERT, Grok, 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:
machine translation
time series prediction
document summarization
document generation
named entity recognition (NER) [118]
writing computer code based on requirements expressed in natural language.
speech-to-text
Beyond traditional NLP, the transformer architecture has had success in other applications, such as:
biological sequence analysis
video understanding
protein folding (such as AlphaFold)
evaluating chess board positions. Using static evaluation alone (that is, with no Minimax search) transformer achieved an Elo of 2895, putting it at grandmaster level. [11]
See also
[ edit]
seq2seq – Family of machine learning approaches
Circuit (neural network) – Interpretable computational sub-graphs within artificial neural networks
Perceiver – Variant of Transformer designed for multimodal data
Vision transformer – Machine learning model for vision processing
Large language model – Type of machine learning model
BERT (language model) – Series of language models developed by Google AI
Generative pre-trained transformer – Type of large language model
T5 (language model) – Series of large language models developed by Google AI
Notes
[ edit]
↑ Gated recurrent units (2014) further reduced its complexity.
↑ Some architectures, such as RWKV (Receptance Weighted Key Value) or state space models, avoid the issue.
References
[ edit]
Jump up to: 1 2 3 4 5 6 7 8 9 10 11 12 13 Vaswani, Ashish; Shazeer, Noam; Parmar, Niki; Uszkoreit, Jakob; Jones, Llion; Gomez, Aidan N; Kaiser, Łukasz; Polosukhin, Illia (2017). "Attention is All You Need" (PDF). 31st Conference on Neural Information Processing Systems (NIPS 2017), 4-9 December 2017, Long Beach, CA, USA. Vol. 30. Curran Associates, Inc. arXiv: 1706.03762. ISBN 978-1-5108-6096-4 . Archived from the original (PDF) on 2024-02-21. Retrieved 2023-10-31.
Jump up to: 1 2 Hochreiter, Sepp; Schmidhuber, Jürgen (November 1997). "Long Short-Term Memory". Neural Computation. 9 (8): 1735– 1780. doi: 10.1162/neco.1997.9.8.1735. PMID 9377276.
Jump up to: 1 2 "Better Language Models and Their Implications". OpenAI. 2019-02-14. Archived from the original on 2020-12-19. Retrieved 2019-08-25.
↑ Raffel, Colin; Shazeer, Noam; Roberts, Adam; Lee, Katherine; Narang, Sharan; Matena, Michael; Zhou, Yanqi; Li, Wei; Liu, Peter J. (2019-10-23). "Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer". arXiv: 1910.10683 [ cs.LG].
Jump up to: 1 2 Bahdanau; Cho, Kyunghyun; Bengio, Yoshua (September 1, 2014). "Neural Machine Translation by Jointly Learning to Align and Translate". arXiv: 1409.0473 [ cs.CL].
↑ Luong, Minh-Thang; Pham, Hieu; Manning, Christopher D. (August 17, 2015). "Effective Approaches to Attention-based Neural Machine Translation". arXiv: 1508.04025 [ cs.CL].
Jump up to: 1 2 Chen, Lili; Lu, Kevin; Rajeswaran, Aravind; Lee, Kimin; Grover, Aditya; Laskin, Michael; Abbeel, Pieter; Srinivas, Aravind; Mordatch, Igor (2021-06-24). "Decision Transformer: Reinforcement Learning via Sequence Modeling". arXiv: 2106.01345 [ cs.LG].
↑ Parisotto, Emilio; Song, Francis; Rae, Jack; Pascanu, Razvan; Gulcehre, Caglar; Jayakumar, Siddhant; Jaderberg, Max; Kaufman, Raphaël Lopez; Clark, Aidan; Noury, Seb; Botvinick, Matthew; Heess, Nicolas; Hadsell, Raia (2020-11-21). "Stabilizing Transformers for Reinforcement Learning". Proceedings of the 37th International Conference on Machine Learning. PMLR: 7487– 7498. Archived from the original on 2024-08-09. Retrieved 2024-08-09.
↑ Radford, Alec; Jong Wook Kim; Xu, Tao; Brockman, Greg; McLeavey, Christine; Sutskever, Ilya (2022). "Robust Speech Recognition via Large-Scale Weak Supervision". arXiv: 2212.04356 [ eess.AS].
↑ Monastirsky, Maxim; Azulay, Osher; Sintov, Avishai (February 2023). "Learning to Throw With a Handful of Samples Using Decision Transformers". IEEE Robotics and Automation Letters. 8 (2): 576– 583. Bibcode: 2023IRAL....8..576M. doi: 10.1109/LRA.2022.3229266.
Jump up to: 1 2 Ruoss, Anian; Delétang, Grégoire; Medapati, Sourabh; Grau-Moya, Jordi; Wenliang, Li; Catt, Elliot; Reid, John; Genewein, Tim (2024-02-07). "Grandmaster-Level Chess Without Search". arXiv: 2402.04494v1 [ cs.LG].
Jump up to: 1 2 Wolf, Thomas; Debut, Lysandre; Sanh, Victor; Chaumond, Julien; Delangue, Clement; Moi, Anthony; Cistac, Pierric; Rault, Tim; Louf, Remi; Funtowicz, Morgan; Davison, Joe; Shleifer, Sam; von Platen, Patrick; Ma, Clara; Jernite, Yacine; Plu, Julien; Xu, Canwen; Le Scao, Teven; Gugger, Sylvain; Drame, Mariama; Lhoest, Quentin; Rush, Alexander (2020). "Transformers: State-of-the-Art Natural Language Processing". Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing: System Demonstrations. pp. 38– 45. doi: 10.18653/v1/2020.emnlp-demos.6.
Jump up to: 1 2 3 "Open Sourcing BERT: State-of-the-Art Pre-training for Natural Language Processing". Google AI Blog. 2 November 2018. Archived from the original on 2021-01-13. Retrieved 2019-08-25.
↑ Feldman, J; Ballard, D (September 1982). "Connectionist models and their properties". Cognitive Science. 6 (3): 205– 254. doi: 10.1016/S0364-0213(82)80001-3.
↑ Rumelhart, David E.; McClelland, James L.; Hinton, Geoffrey E. (1986). Parallel Distributed Processing, Volume 1: Explorations in the Microstructure of Cognition: Foundations, Chapter 2 (PDF). Cambridge, Massachusetts: Bradford Books. ISBN 978-0-262-68053-0 . OCLC 12837549. OL 21219798M. Archived (PDF) from the original on April 16, 2026.
↑ Giles, C. Lee; Maxwell, Tom (December 1987). "Learning, invariance, and generalization in high-order neural networks". Applied Optics. 26 (23): 4972– 4978. doi: 10.1364/AO.26.004972. PMID 20523475.
Jump up to: 1 2 Schmidhuber, Jürgen (January 1992). "Learning to Control Fast-Weight Memories: An Alternative to Dynamic Recurrent Networks". Neural Computation. 4 (1): 131– 139. doi: 10.1162/neco.1992.4.1.131.
↑ 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 Archived 2022-01-26 at the Wayback Machine See Reprint in Models of Neural Networks II, chapter 2, pages 95–119. Springer, Berlin, 1994.
↑ Feldman, Jerome A. (December 1982). "Dynamic connections in neural networks". Biological Cybernetics. 46 (1): 27– 39. doi: 10.1007/BF00335349. PMID 6307398.
↑ Hinton, Geoffrey E.; Plaut, David C. (1987). "Using Fast Weights to Deblur Old Memories". Proceedings of the Annual Meeting of the Cognitive Science Society. 9. Archived from the original on 2024-07-23. Retrieved 2024-07-23.
↑ Katharopoulos, Angelos; Vyas, Apoorv; Pappas, Nikolaos; Fleuret, François (2020). "Transformers are RNNs: Fast autoregressive Transformers with linear attention". ICML 2020. PMLR. pp. 5156– 5165.
↑ Schlag, Imanol; Irie, Kazuki; Schmidhuber, Jürgen (2021). "Linear Transformers Are Secretly Fast Weight Programmers". ICML 2021. Springer. pp. 9355– 9366. Archived from the original on 2026-05-20. Retrieved 2026-05-20.
Jump up to: 1 2 Cho, Kyunghyun; van Merriënboer, Bart; Gulcehre, Caglar; Bahdanau, Dzmitry; Bougares, Fethi; Schwenk, Holger; Bengio, Yoshua (October 2014). "Learning Phrase Representations using RNN Encoder–Decoder for Statistical Machine Translation". In Moschitti, Alessandro; Pang, Bo; Daelemans, Walter (eds.). Proceedings of the 2014 Conference on Empirical Methods in Natural Language Processing (EMNLP). Doha, Qatar: Association for Computational Linguistics. pp. 1724– 1734. arXiv: 1406.1078. doi: 10.3115/v1/D14-1179. Archived from the original on 2024-09-06. Retrieved 2024-08-09.
Jump up to: 1 2 Sutskever, Ilya; Vinyals, Oriol; Le, Quoc Viet (14 Dec 2014). "Sequence to sequence learning with neural networks". arXiv: 1409.3215 [ cs.CL]. [first version posted to arXiv on 10 Sep 2014]
↑ Chung, Junyoung; Gulcehre, Caglar; Cho, KyungHyun; Bengio, Yoshua (2014). "Empirical Evaluation of Gated Recurrent Neural Networks on Sequence Modeling". arXiv: 1412.3555 [ cs.NE].
↑ Gruber, Nicole; Jockisch, Alfred (30 June 2020). "Are GRU Cells More Specific and LSTM Cells More Sensitive in Motive Classification of Text?". Frontiers in Artificial Intelligence. 3 40. doi: 10.3389/frai.2020.00040. PMC 7861254. PMID 33733157.
↑ Sutskever, Ilya; Vinyals, Oriol; Le, Quoc V (2014). "Sequence to Sequence Learning with Neural Networks". Advances in Neural Information Processing Systems. 27. Curran Associates, Inc. arXiv: 1409.3215. Archived from the original on 2025-01-27. Retrieved 2024-07-23.
↑ Luong, Minh-Thang; Pham, Hieu; Manning, Christopher D. (2015). "Effective Approaches to Attention-based Neural Machine Translation". arXiv: 1508.04025 [ cs.CL].
↑ Wu, Yonghui; et al. (2016-09-01). "Google's Neural Machine Translation System: Bridging the Gap between Human and Machine Translation". arXiv: 1609.08144 [ cs.CL].
↑ Lewis-Kraus, Gideon (2016-12-14). "The Great A.I. Awakening". The New York Times. Archived from the original on 24 May 2023. Retrieved 2023-06-22.
↑ Parikh, Ankur P.; Täckström, Oscar; Das, Dipanjan; Uszkoreit, Jakob (2016-09-25). "A Decomposable Attention Model for Natural Language Inference". arXiv: 1606.01933 [ cs.CL].
Jump up to: 1 2 Levy, Steven. "8 Google Employees Invented Modern AI. Here's the Inside Story". Wired. Archived from the original on 20 Mar 2024. Retrieved 2024-08-06.
↑ Cheng, Jianpeng; Dong, Li; Lapata, Mirella (November 2016). "Long Short-Term Memory-Networks for Machine Reading". In Su, Jian; Duh, Kevin; Carreras, Xavier (eds.). Proceedings of the 2016 Conference on Empirical Methods in Natural Language Processing. Austin, Texas: Association for Computational Linguistics. pp. 551– 561. doi: 10.18653/v1/D16-1053. Archived from the original on 2024-08-27. Retrieved 2024-08-27.
↑ Peng, Bo; Alcaide, Eric; Anthony, Quentin; Albalak, Alon; Arcadinho, Samuel; Biderman, Stella; Cao, Huanqi; Cheng, Xin; Chung, Michael (2023-12-10). "RWKV: Reinventing RNNs for the transformer Era". arXiv: 2305.13048 [ cs.CL].
↑ Marche, Stephen (2024-08-23). "Was Linguistic A.I. Created by Accident?". The New Yorker. Retrieved 2024-08-27.
↑ Vaswani, Ashish; Bengio, Samy; Brevdo, Eugene; Chollet, Francois; Gomez, Aidan; Gouws, Stephan; Jones, Llion; Kaiser, Łukasz; Kalchbrenner, Nal; Parmar, Niki; Sepassi, Ryan; Shazeer, Noam; Uszkoreit, Jakob (March 2018). Cherry, Colin; Neubig, Graham (eds.). "Tensor2Tensor for Neural Machine Translation". Proceedings of the 13th Conference of the Association for Machine Translation in the Americas (Volume 1: Research Track). Boston, MA: Association for Machine Translation in the Americas: 193– 199. Archived from the original on 2026-04-29. Retrieved 2026-03-31.
↑ Kaiser, Łukasz (2017-06-19). "Accelerating Deep Learning Research with the Tensor2Tensor Library". Google Research Blog. Archived from the original on 2026-04-15. Retrieved 2026-03-31.
Jump up to: 1 2 3 4 5 Devlin, Jacob; Chang, Ming-Wei; Lee, Kenton; Toutanova, Kristina (11 October 2018). "BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding". arXiv: 1810.04805v2 [ cs.CL].
↑ "Google: BERT now used on almost every English query". Search Engine Land. 2020-10-15. Archived from the original on 2022-05-06. Retrieved 2020-11-24.
Jump up to: 1 2 Caswell, Isaac; Liang, Bowen (June 8, 2020). "Recent Advances in Google Translate". Google Research. Archived from the original on 4 Jul 2024. Retrieved 2024-08-07.
↑ "The inside story of how ChatGPT was built from the people who made it". MIT Technology Review. Archived from the original on 2023-03-03. Retrieved 2024-08-06.
↑ "Introducing ChatGPT". OpenAI. 2022-11-30. Archived from the original on 2026-04-05. Retrieved 2026-05-16.
↑ "Improving language understanding with unsupervised learning". openai.com. June 11, 2018. Archived from the original on 2023-03-18. Retrieved 2023-03-18.
↑ "finetune-transformer-lm". OpenAI. June 11, 2018. Archived from the original on 2023-05-19. Retrieved 2023-05-01.
↑ Kaiser, Lukasz; Gomez, Aidan N.; Shazeer, Noam; Vaswani, Ashish; Parmar, Niki; Jones, Llion; Uszkoreit, Jakob (2017-06-16). "One Model To Learn Them All". arXiv: 1706.05137v1 [ cs.LG].
Jump up to: 1 2 Dosovitskiy, Alexey; Beyer, Lucas; Kolesnikov, Alexander; Weissenborn, Dirk; Zhai, Xiaohua; Unterthiner, Thomas; Dehghani, Mostafa; Minderer, Matthias; Heigold, Georg; Gelly, Sylvain; Uszkoreit, Jakob (2021-06-03). "An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale". arXiv: 2010.11929 [ cs.CV].
Jump up to: 1 2 Gulati, Anmol; Qin, James; Chiu, Chung-Cheng; Parmar, Niki; Zhang, Yu; Yu, Jiahui; Han, Wei; Wang, Shibo; Zhang, Zhengdong; Wu, Yonghui; Pang, Ruoming (2020). "Conformer: Convolution-augmented Transformer for Speech Recognition". arXiv: 2005.08100 [ eess.AS].
↑ Choromanski, Krzysztof; Likhosherstov, Valerii; Dohan, David; Song, Xingyou; Gane, Andreea; Sarlos, Tamas; Hawkins, Peter; Davis, Jared; Mohiuddin, Afroz (2022-11-19). "Rethinking Attention with Performers". arXiv: 2009.14794 [ cs.LG].
↑ Liu, Zhuang; Mao, Hanzi; Wu, Chao-Yuan; Feichtenhofer, Christoph; Darrell, Trevor; Xie, Saining (2022). A ConvNet for the 2020s. Conference on Computer Vision and Pattern Recognition ( CVPR). pp. 11976– 11986.
↑ Esser, Patrick; Kulal, Sumith; Blattmann, Andreas; Entezari, Rahim; Müller, Jonas; Saini, Harry; Levi, Yam; Lorenz, Dominik; Sauer, Axel (2024-03-05). "Scaling Rectified Flow Transformers for High-Resolution Image Synthesis". arXiv: 2403.03206 [ cs.CV].
Jump up to: 1 2 Xiong, Ruibin; Yang, Yunchang; He, Di; Zheng, Kai; Zheng, Shuxin; Xing, Chen; Zhang, Huishuai; Lan, Yanyan; Wang, Liwei; Liu, Tie-Yan (2020-06-29). "On Layer Normalization in the Transformer Architecture". arXiv: 2002.04745 [ cs.LG].
Jump up to: 1 2 3 4 Raffel, Colin; Shazeer, Noam; Roberts, Adam; Lee, Katherine; Narang, Sharan; Matena, Michael; Zhou, Yanqi; Li, Wei; Liu, Peter J. (2020). "Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer". Journal of Machine Learning Research. 21 (140): 1– 67. Archived from the original on 2026-04-10. Retrieved 2026-04-18.
↑ Raffel, Colin; Shazeer, Noam; Roberts, Adam; Lee, Katherine; Narang, Sharan; Matena, Michael; Zhou, Yanqi; Li, Wei; Liu, Peter J. (2019). "Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer". arXiv: 1910.10683 [ cs.LG].
Jump up to: 1 2 "Masked language modeling". huggingface.co. Archived from the original on 2023-10-10. Retrieved 2023-10-05.
Jump up to: 1 2 "Causal language modeling". huggingface.co. Archived from the original on 2023-10-10. Retrieved 2023-10-05.
Jump up to: 1 2 3 4 Tay, Yi; Dehghani, Mostafa; Tran, Vinh Q.; Garcia, Xavier; Wei, Jason; Wang, Xuezhi; Chung, Hyung Won; Shakeri, Siamak; Bahri, Dara (2023-02-28). "UL2: Unifying Language Learning Paradigms". arXiv: 2205.05131 [ cs.CL].
↑ Press, Ofir; Wolf, Lior (2017-02-21). "Using the Output Embedding to Improve Language Models". arXiv: 1608.05859 [ cs.CL].
↑ Lintz, Nathan (2016-04-18). "Sequence Modeling with Neural Networks (Part 2): Attention Models". Indico. Archived from the original on 2020-10-21. Retrieved 2019-10-15.
Jump up to: 1 2 3 Alammar, Jay. "The Illustrated transformer". jalammar.github.io. Archived from the original on 2020-10-18. Retrieved 2019-10-15.
↑ Team, Keras. "Keras documentation: GPT2Backbone model". keras.io. Archived from the original on 2024-08-08. Retrieved 2024-08-08.
↑ Clark, Kevin; Khandelwal, Urvashi; Levy, Omer; Manning, Christopher D. (August 2019). "What Does BERT Look at? An Analysis of BERT's Attention". Proceedings of the 2019 ACL Workshop BlackboxNLP: Analyzing and Interpreting Neural Networks for NLP. Florence, Italy: Association for Computational Linguistics: 276– 286. arXiv: 1906.04341. doi: 10.18653/v1/W19-4828. Archived from the original on 2020-10-21. Retrieved 2020-05-20.
↑ Yang, Zhilin; Dai, Zihang; Yang, Yiming; Carbonell, Jaime; Salakhutdinov, Russ R; Le, Quoc V (2019). "XLNet: Generalized Autoregressive Pretraining for Language Understanding". Advances in Neural Information Processing Systems. 32. Curran Associates, Inc. arXiv: 1906.08237. Archived from the original on 2024-08-09. Retrieved 2024-08-09.
↑ Wang, Qiang; Li, Bei; Xiao, Tong; Zhu, Jingbo; Li, Changliang; Wong, Derek F.; Chao, Lidia S. (2019-06-04). "Learning Deep Transformer Models for Machine Translation". arXiv: 1906.01787 [ cs.CL].
↑ Phuong, Mary; Hutter, Marcus (2022-07-19). "Formal Algorithms for Transformers". arXiv: 2207.09238 [ cs.LG].
Jump up to: 1 2 Shazeer, Noam (2020-02-01). "GLU Variants Improve Transformer". arXiv: 2002.05202 [ cs.LG].
↑ Hendrycks, Dan; Gimpel, Kevin (2016-06-27). "Gaussian Error Linear Units (GELUs)". arXiv: 1606.08415v5 [ cs.LG].
↑ Zhang, Biao; Sennrich, Rico (2019). "Root Mean Square Layer Normalization". Advances in Neural Information Processing Systems. 32. Curran Associates, Inc. arXiv: 1910.07467. Archived from the original on 2024-09-17. Retrieved 2024-08-09.
Jump up to: 1 2 Nguyen, Toan Q.; Salazar, Julian (2019-11-02). Niehues, Jan; Cattoni, Rolando; Stüker, Sebastian; Negri, Matteo; Turchi, Marco; Ha, Thanh-Le; Salesky, Elizabeth; Sanabria, Ramon; Barrault, Loic (eds.). "Transformers without Tears: Improving the Normalization of Self-Attention". Proceedings of the 16th International Conference on Spoken Language Translation. Hong Kong: Association for Computational Linguistics. arXiv: 1910.05895. doi: 10.5281/zenodo.3525484. Archived from the original on 2024-08-09. Retrieved 2024-08-09.
↑ Dufter, Philipp; Schmitt, Martin; Schütze, Hinrich (September 2022). "Position Information in Transformers: An Overview". Computational Linguistics. 48 (3): 733– 763. arXiv: 2102.11090. doi: 10.1162/coli_a_00445.
↑ Gehring, Jonas; Auli, Michael; Grangier, David; Yarats, Denis; Dauphin, Yann N. (2017-07-17). "Convolutional Sequence to Sequence Learning". Proceedings of the 34th International Conference on Machine Learning. PMLR: 1243– 1252. Archived from the original on 2024-08-09. Retrieved 2024-08-09.
↑ Haviv, Adi; Ram, Ori; Press, Ofir; Izsak, Peter; Levy, Omer (2022-12-05). "Transformer Language Models without Positional Encodings Still Learn Positional Information". arXiv: 2203.16634 [ cs.CL].
↑ Su, Jianlin; Lu, Yu; Pan, Shengfeng; Murtadha, Ahmed; Wen, Bo; Liu, Yunfeng (2021-04-01). "RoFormer: Enhanced Transformer with Rotary Position Embedding". arXiv: 2104.09864 [ cs.CL].
↑ Press, Ofir; Smith, Noah A.; Lewis, Mike (2021-08-01). "Train Short, Test Long: Attention with Linear Biases Enables Input Length Extrapolation". arXiv: 2108.12409 [ cs.CL].
↑ Shaw, Peter; Uszkoreit, Jakob; Vaswani, Ashish (2018). "Self-Attention with Relative Position Representations". arXiv: 1803.02155 [ cs.CL].
↑ Ke, Guolin; He, Di; Liu, Tie-Yan (2021-03-15). "Rethinking Positional Encoding in Language Pre-training". arXiv: 2006.15595 [ cs.CL].
↑ Kwon, Woosuk; Li, Zhuohan; Zhuang, Siyuan; Sheng, Ying; Zheng, Lianmin; Yu, Cody Hao; Gonzalez, Joseph; Zhang, Hao; Stoica, Ion (2023-10-23). "Efficient Memory Management for Large Language Model Serving with PagedAttention". Proceedings of the 29th Symposium on Operating Systems Principles. SOSP '23. New York, NY, USA: Association for Computing Machinery. pp. 611– 626. arXiv: 2309.06180. doi: 10.1145/3600006.3613165. ISBN 979-8-4007-0229-7 .
↑ "vllm-project/vllm". vLLM. 2024-06-20. Archived from the original on 2024-06-18. Retrieved 2024-06-20.
↑ Zhuohan Li, Woosuk Kwon; Zhuang, Siyuan; Sheng, Ying; Zheng, Lianmin; Yu, Cody; Gonzalez, Joey; Zhang, Hao; Stoica, Ion (2023-06-20). "vLLM: Easy, Fast, and Cheap LLM Serving with PagedAttention". vLLM Blog. Archived from the original on 2024-06-20. Retrieved 2024-06-20.
↑ Hu, Cunchen; Huang, Heyang; Xu, Liangliang; Chen, Xusheng; Xu, Jiang; Chen, Shuang; Feng, Hao; Wang, Chenxi; Wang, Sa (2024-01-20). "Inference without Interference: Disaggregate LLM Inference for Mixed Downstream Workloads". arXiv: 2401.11181 [ cs.DC].
↑ Dao, Tri; Ermon, Stefano; Fu, Dan; Ré, Christopher; Rudra, Atri (2022). "FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness". Advances in Neural Information Processing Systems 35. pp. 16344– 16359. doi: 10.52202/068431-1189. ISBN 978-1-7138-7108-8 .
↑ Milakov, Maxim; Gimelshein, Natalia (2018). "Online normalizer calculation for softmax". arXiv: 1805.02867 [ cs.PF].
↑ Dao, Tri; Fu, Dan; Ermon, Stefano; Rudra, Atri; Ré, Christopher (2022-12-06). "FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness". Advances in Neural Information Processing Systems. 35: 16344– 16359.
↑ "Stanford CRFM". crfm.stanford.edu. Archived from the original on 2023-07-18. Retrieved 2023-07-18.
↑ "FlashAttention-2: Faster Attention with Better Parallelism and Work Partitioning". Princeton NLP. 2023-06-17. Archived from the original on 2023-07-18. Retrieved 2023-07-18.
↑ "Introducing Together AI Chief Scientist Tri Dao, as he releases FlashAttention-2 to speed up model training and inference". TOGETHER. Archived from the original on 2023-07-17. Retrieved 2023-07-18.
↑ Ainslie, Joshua; Lee-Thorp, James; de Jong, Michiel; Zemlyanskiy, Yury; Lebrón, Federico; Sanghai, Sumit (2023-12-23). "GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints". arXiv: 2305.13245 [ cs.CL].
↑ "We reverse-engineered Flash Attention 4". Modal. Archived from the original on 2025-09-27. Retrieved 2025-09-26.
↑ Chowdhery, Aakanksha; Narang, Sharan; Devlin, Jacob; Bosma, Maarten; Mishra, Gaurav; Roberts, Adam; Barham, Paul; Chung, Hyung Won; Sutton, Charles; Gehrmann, Sebastian; Schuh, Parker; Shi, Kensen; Tsvyashchenko, Sasha; Maynez, Joshua; Rao, Abhishek (2022-04-01). "PaLM: Scaling Language Modeling with Pathways". arXiv: 2204.02311 [ cs.CL].
↑ Ainslie, Joshua; Lee-Thorp, James; de Jong, Michiel; Zemlyanskiy, Yury; Lebrón, Federico; Sanghai, Sumit (2023-12-23). "GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints". arXiv: 2305.13245 [ cs.CL].
Jump up to: 1 2 DeepSeek-AI; Liu, Aixin; Feng, Bei; Wang, Bin; Wang, Bingxuan; Liu, Bo; Zhao, Chenggang; Dengr, Chengqi; Ruan, Chong (19 June 2024). "DeepSeek-V2: A Strong, Economical, and Efficient Mixture-of-Experts Language Model". arXiv: 2405.04434 [ cs.CL]..
Jump up to: 1 2 Leviathan, Yaniv; Kalman, Matan; Matias, Yossi (2023-05-18). "Fast Inference from Transformers via Speculative Decoding". arXiv: 2211.17192 [ cs.LG].
↑ Fu, Yao (2023-12-11). "Towards 100x Speedup: Full Stack Transformer Inference Optimization". yaofu.notion.site.
↑ Chen, Charlie; Borgeaud, Sebastian; Irving, Geoffrey; Lespiau, Jean-Baptiste; Sifre, Laurent; Jumper, John (2023-02-02). "Accelerating Large Language Model Decoding with Speculative Sampling". arXiv: 2302.01318 [ cs.CL].
↑ Gloeckle, Fabian; Badr Youbi Idrissi; Rozière, Baptiste; Lopez-Paz, David; Synnaeve, Gabriel (2024). "Better & Faster Large Language Models via Multi-token Prediction". arXiv: 2404.19737 [ cs.CL].
↑ DeepSeek-AI; et al. (2024). "DeepSeek-V3 Technical Report". arXiv: 2412.19437 [ cs.CL].
Jump up to: 1 2 Kitaev, Nikita; Kaiser, Łukasz; Levskaya, Anselm (2020). "Reformer: The Efficient Transformer". arXiv: 2001.04451 [ cs.LG].
↑ Liu, Ze; Lin, Yutong; Cao, Yue; Hu, Han; Wei, Yixuan; Zhang, Zheng; Lin, Stephen; Guo, Baining (2021). "Swin Transformer: Hierarchical Vision Transformer using Shifted Windows". 2021 IEEE/CVF International Conference on Computer Vision (ICCV). IEEE. pp. 9992– 10002. arXiv: 2103.14030. doi: 10.1109/ICCV48922.2021.00986. ISBN 978-1-6654-2812-5 .
↑ Ristea, Nicolaea Catalin; Ionescu, Radu Tudor; Khan, Fahad Shahbaz (2022-09-18). "SepTr: Separable Transformer for Audio Spectrogram Processing". Interspeech. ISCA: 4103– 4107. arXiv: 2203.09581. doi: 10.21437/Interspeech.2022-249.
↑ Tay, Yi; Dehghani, Mostafa; Abnar, Samira; Shen, Yikang; Bahri, Dara; Pham, Philip; Rao, Jinfeng; Yang, Liu; Ruder, Sebastian; Metzler, Donald (2020-11-08). "Long Range Arena: A Benchmark for Efficient Transformers". arXiv: 2011.04006 [ cs.LG].
↑ "Reformer: The Efficient Transformer". Google AI Blog. 16 January 2020. Archived from the original on 2020-10-22. Retrieved 2020-10-22.
↑ Gomez, Aidan N; Ren, Mengye; Urtasun, Raquel; Grosse, Roger B (2017). "The Reversible Residual Network: Backpropagation Without Storing Activations". Advances in Neural Information Processing Systems. 30. Curran Associates, Inc. arXiv: 1707.04585. Archived from the original on 2024-08-11. Retrieved 2024-08-11.
↑ Child, Rewon; Gray, Scott; Radford, Alec; Sutskever, Ilya (2019-04-23). "Generating Long Sequences with Sparse Transformers". arXiv: 1904.10509 [ cs.LG].
↑ "Constructing Transformers For Longer Sequences with Sparse Attention Methods". Google AI Blog. 25 March 2021. Archived from the original on 2021-09-18. Retrieved 2021-05-28.
↑ Zhai, Shuangfei; Talbott, Walter; Srivastava, Nitish; Huang, Chen; Goh, Hanlin; Zhang, Ruixiang; Susskind, Josh (2021-09-21). "An Attention Free Transformer". arXiv: 2105.14103 [ cs.LG].
↑ Peng, Hao; Pappas, Nikolaos; Yogatama, Dani; Schwartz, Roy; Smith, Noah A.; Kong, Lingpeng (2021-03-19). "Random Feature Attention". arXiv: 2103.02143 [ cs.CL].
↑ Choromanski, Krzysztof; Likhosherstov, Valerii; Dohan, David; Song, Xingyou; Gane, Andreea; Sarlos, Tamas; Hawkins, Peter; Davis, Jared; Belanger, David; Colwell, Lucy; Weller, Adrian (2020-09-30). "Masked Language Modeling for Proteins via Linearly Scalable Long-Context Transformers". arXiv: 2006.03555 [ cs.LG].
↑ Lu, Kevin; Grover, Aditya; Abbeel, Pieter; Mordatch, Igor (2022-06-28). "Frozen Pretrained Transformers as Universal Computation Engines". Proceedings of the AAAI Conference on Artificial Intelligence. 36 (7): 7628– 7636. doi: 10.1609/aaai.v36i7.20729. ISSN 2374-3468. Archived from the original on 2024-12-02. Retrieved 2024-08-11.
↑ "Vicuna: An Open-Source Chatbot Impressing GPT-4 with 90%* ChatGPT Quality | LMSYS Org". lmsys.org. 30 March 2023. Archived from the original on 2024-08-12. Retrieved 2024-08-11.
↑ Liu, Haotian; Li, Chunyuan; Wu, Qingyang; Lee, Yong Jae (2023-12-15). "Visual Instruction Tuning". Advances in Neural Information Processing Systems. Vol. 36. pp. 34892– 34916. doi: 10.52202/075280-1516. ISBN 978-1-7138-9911-2 . Archived from the original on 2024-09-26. Retrieved 2024-08-11.
↑ Radford, Alec; Kim, Jong Wook; Xu, Tao; Brockman, Greg; McLeavey, Christine; Sutskever, Ilya (2022). "Robust Speech Recognition via Large-Scale Weak Supervision". arXiv: 2212.04356 [ eess.AS].
↑ Jaegle, Andrew; Gimeno, Felix; Brock, Andrew; Zisserman, Andrew; Vinyals, Oriol; Carreira, Joao (2021-06-22). "Perceiver: General Perception with Iterative Attention". arXiv: 2103.03206 [ cs.CV].
↑ Jaegle, Andrew; Borgeaud, Sebastian; Alayrac, Jean-Baptiste; Doersch, Carl; Ionescu, Catalin; Ding, David; Koppula, Skanda; Zoran, Daniel; Brock, Andrew; Shelhamer, Evan; Hénaff, Olivier (2021-08-02). "Perceiver IO: A General Architecture for Structured Inputs & Outputs". arXiv: 2107.14795 [ cs.LG].
↑ "Parti: Pathways Autoregressive Text-to-Image Model". sites.research.google. Archived from the original on 2024-08-10. Retrieved 2024-08-09.
Jump up to: 1 2 Villegas, Ruben; Babaeizadeh, Mohammad; Kindermans, Pieter-Jan; Moraldo, Hernan; Zhang, Han; Saffar, Mohammad Taghi; Castro, Santiago; Kunze, Julius; Erhan, Dumitru (2022-09-29). "Phenaki: Variable Length Video Generation from Open Domain Textual Descriptions". arXiv: 2210.02399 [ cs.CV].
Jump up to: 1 2 Chang, Huiwen; Zhang, Han; Barber, Jarred; Maschinot, A. J.; Lezama, Jose; Jiang, Lu; Yang, Ming-Hsuan; Murphy, Kevin; Freeman, William T. (2023-01-02). "Muse: Text-To-Image Generation via Masked Generative Transformers". arXiv: 2301.00704 [ cs.CV].
↑ Ramesh, Aditya; Pavlov, Mikhail; Goh, Gabriel; Gray, Scott; Voss, Chelsea; Radford, Alec; Chen, Mark; Sutskever, Ilya (2021-02-26). "Zero-Shot Text-to-Image Generation". arXiv: 2102.12092 [ cs.CV].
↑ Yu, Jiahui; Xu, Yuanzhong; Koh, Jing Yu; Luong, Thang; Baid, Gunjan; Wang, Zirui; Vasudevan, Vijay; Ku, Alexander; Yang, Yinfei (2022-06-21). "Scaling Autoregressive Models for Content-Rich Text-to-Image Generation". arXiv: 2206.10789 [ cs.CV].
↑ Kariampuzha, William; Alyea, Gioconda; Qu, Sue; Sanjak, Jaleal; Mathé, Ewy; Sid, Eric; Chatelaine, Haley; Yadaw, Arjun; Xu, Yanji; Zhu, Qian (2023). "Precision information extraction for rare disease epidemiology at scale". Journal of Translational Medicine. 21 (1): 157. doi: 10.1186/s12967-023-04011-y. PMC 9972634. PMID 36855134.
Further reading
[ edit]
Alexander Rush, The Annotated transformer Archived 2021-09-22 at the Wayback Machine , Harvard NLP group, 3 April 2018
Phuong, Mary; Hutter, Marcus (2022). "Formal Algorithms for Transformers". arXiv: 2207.09238 [ cs.LG].
Ferrando, Javier; Sarti, Gabriele; Bisazza, Arianna; Costa-jussà, Marta R. (2024-05-01). "A Primer on the Inner Workings of Transformer-based Language Models". arXiv: 2405.00208 [ cs.CL].
Leech, Gavin (2024-11-06). "Transformer++". argmin gravitas. Archived from the original on 2025-02-26. Retrieved 2025-05-08.
US patent 10452978, Noam M. Shazeer; Aidan Nicholas Gomez; Lukasz Mieczyslaw Kaiser; Jakob D. Uszkoreit; Llion Owen Jones; Niki J. Parmar; Illia Polosukhin; Ashish Teku Vaswani, "Attention-based sequence transduction neural networks", issued 2019-10-22, assigned to Google LLC
Raschka, Sebastian (2026-03-11). "The Big LLM Architecture Comparison: From DeepSeek V3 to GLM-5: A Look At Modern LLM Architecture Design". Sebastian Raschka's AI Magazine. Archived from the original on 2026-03-21. Retrieved 2026-03-25.
show
v
t
e
Google AI
Google
Google Brain
Google DeepMind
Computer
programs
AlphaGo
Versions
- AlphaGo (2015) - Master (2016) - AlphaGo Zero (2017) - AlphaZero (2017) - MuZero (2019)
Competitions
- Fan Hui (2015) - Lee Sedol (2016) - Ke Jie (2017)
In popular culture
- AlphaGo (2017)
Other - AlphaFold (2018) - AlphaStar (2019) - AlphaTensor (2022) - AlphaDev (2023) - AlphaGeometry (2024) - AlphaGenome (2025)
Machine
learning
Neural networks
- Inception (2014) - WaveNet (2016) - MobileNet (2017) - Transformer (2017) - EfficientNet (2019) - Gato (2022)
Other
- Quantum Artificial Intelligence Lab - TensorFlow - Tensor Processing Unit
Generative
AI
Chatbots
- Assistant (2016) - Sparrow (2022) - Gemini (2023) - Nano Banana (2025)
Models
- BERT (2018) - XLNet (2019) - T5 (2019) - LaMDA (2021) - Chinchilla (2022) - PaLM (2022) - Imagen (2023) - Gemini (2023) - VideoPoet (2024) - Gemma (2024) - Genie (2024) - Veo (2024)
Other
- DreamBooth (2022) - NotebookLM (2023) - Vids (2024) - Gemini Robotics (2025) - Antigravity (2025)
See also
" Attention Is All You Need"
Future of Go Summit
Generative pre-trained transformer
Google Labs
Google Workspace
Category
Commons
show
v
t
e
Artificial intelligence (AI)
History
timeline
timeline
Glossary
Companies
Projects
List of open-source AI software
Concepts
Automated reasoning
Automated planning
Constraint satisfaction
Knowledge representation
Parameter
Hyperparameter
Hyperparameter
Loss functions
Regression
Bias–variance tradeoff
Double descent
Overfitting
Bias–variance tradeoff
Double descent
Overfitting
Clustering
Gradient descent
SGD
Quasi-Newton method
Conjugate gradient method
SGD
Quasi-Newton method
Conjugate gradient method
Backpropagation
Attention
Convolution
Normalization
Batchnorm
Batchnorm
Activation
Softmax
Sigmoid
Rectifier
Softmax
Sigmoid
Rectifier
Gating
Weight initialization
Regularization
Datasets
Augmentation
Augmentation
Prompt engineering
Reinforcement learning
Q-learning
SARSA
Imitation
Policy gradient
Q-learning
SARSA
Imitation
Policy gradient
Diffusion
Latent diffusion model
Autoregression
Adversary
RAG
Uncanny valley
LLM post-training
RLHF
Self-supervised learning
Reflection
Recursive self-improvement
Hallucination
Word embedding
Vibe coding
Symbolic AI
Neuro-symbolic AI
Applications
Automated theorem proving
General game playing
Machine learning
In-context learning
In-context learning
Artificial neural network
Deep learning
Deep learning
Language model
Large
NMT
Reasoning
Large
NMT
Reasoning
Model Context Protocol
Intelligent agent
AI agent
AI agent
Artificial human companion
Humanity's Last Exam
Lethal autonomous weapons (LAWs)
Generative AI
Weak AI
Hypothetical
Artificial general intelligence (AGI)
Artificial superintelligence (ASI)
Artificial general intelligence (AGI)
Artificial superintelligence (ASI)
Agent2Agent protocol
Physical AI
Implementations
Audio–visual
AlexNet
WaveNet
Human image synthesis
HWR
OCR
Computer vision
Speech synthesis
15.ai
ElevenLabs
15.ai
ElevenLabs
Speech recognition
Whisper
Whisper
Facial recognition
AlphaFold
Text-to-image models
Aurora
DALL-E
Firefly
Flux
GPT Image
Ideogram
Imagen
Midjourney
Recraft
Stable Diffusion
Aurora
DALL-E
Firefly
Flux
GPT Image
Ideogram
Imagen
Midjourney
Recraft
Stable Diffusion
Text-to-video models
Dream Machine
Runway Gen
Hailuo AI
Kling
Sora
Seedance
Veo
Dream Machine
Runway Gen
Hailuo AI
Kling
Sora
Seedance
Veo
Music generation
Riffusion
Suno
Udio
Riffusion
Suno
Udio
World models
Genie
Oasis
Genie
Oasis
Text
List of large language models
Project Debater
IBM Watson
IBM Watsonx
IBM Watsonx
Decisional
AlphaGo
AlphaZero
OpenAI Five
Self-driving car
MuZero
Action selection
AutoGPT
AutoGPT
Robot control
Reasoning systems
Deductive classifiers
Expert systems
Inference engines
Knowledge-based systems
Logic programs
Procedural reasoning systems
Semantic reasoners
Rule-based systems
Cognitive architectures
ACT-R
Soar
CLARION
LIDA
OpenCog
Knowledge bases
ConceptNet
Wikidata
DBpedia
YAGO
People
Alan Turing
Warren Sturgis McCulloch
Walter Pitts
John von Neumann
Christopher D. Manning
Claude Shannon
Shun'ichi Amari
Kunihiko Fukushima
Takeo Kanade
Marvin Minsky
John McCarthy
Nathaniel Rochester
Allen Newell
Cliff Shaw
Herbert A. Simon
Oliver Selfridge
Frank Rosenblatt
Bernard Widrow
Joseph Weizenbaum
Seymour Papert
Seppo Linnainmaa
Paul Werbos
Geoffrey Hinton
John Hopfield
Jürgen Schmidhuber
Yann LeCun
Yoshua Bengio
Lotfi A. Zadeh
Stephen Grossberg
Alex Graves
James Goodnight
Andrew Ng
Fei-Fei Li
Alex Krizhevsky
Ilya Sutskever
Oriol Vinyals
Quoc V. Le
Ian Goodfellow
Demis Hassabis
David Silver
Andrej Karpathy
Ashish Vaswani
Noam Shazeer
Aidan Gomez
John Schulman
Mustafa Suleyman
Jan Leike
Daniel Kokotajlo
François Chollet
Neural network architectures
Neural Turing machine
Differentiable neural computer
Transformer
Vision transformer (ViT)
Vision transformer (ViT)
Recurrent neural network (RNN)
Long short-term memory (LSTM)
Gated recurrent unit (GRU)
Echo state network
Multilayer perceptron (MLP)
Convolutional neural network (CNN)
Residual neural network (RNN)
Highway network
Mamba
Autoencoder
Variational autoencoder (VAE)
Generative adversarial network (GAN)
Graph neural network (GNN)
Political
AI Cold War
AI in government
AI safety ( Alignment)
AI takeover
Elections
Ethics of AI
EU AI Act
Nationalism
Precautionary principle
Regulation of AI
US
US
Virtual politician
Propaganda
Social and economic
AI boom
AI bubble
AI data center
AI effect
AI infrastructure
AI literacy
AI slop
AI winter
Anthropomorphism
Arms race
Competition
Environmental impact
Explainable AI
Generative engine optimization
In architecture
In education
In fiction
In healthcare
Chatbot psychosis
Chatbot psychosis
In marketing
In video games
In visual art
Military applications
AI warfare
AI warfare
Workplace impact
Category
show
v
t
e
Large language models (LLMs)
List of LLMs
AI Companies
Benchmarks
List of chatbots
Foundation model
Generative AI
Concepts
Language model
NLP
NLG
Computational linguistics
Foundation model
Small language model
Reasoning model
Generative pre-trained transformer
Transformer
Attention
KV cache
Attention
KV cache
Context window
Tokenization
Word embedding
Parameter
Hyperparameter
Autoregression
Mixture of experts (MoE)
Inference
Model compression
Knowledge distillation
Knowledge distillation
Speculative decoding
PagedAttention
Neural scaling law
Multimodality
Open weights
Training, prompting,
and alignment
Self-supervised learning
Supervised learning
Fine-tuning
Instruction tuning
Instruction tuning
RLHF
Constitutional AI
AI alignment
AI safety
Mechanistic interpretability
Prompt engineering
In-context learning
Chain-of-thought prompting
In-context learning
Chain-of-thought prompting
RAG
Prompt injection
Adversarial machine learning
Hallucination
Stochastic parrot
Glitch token
Generative engine optimization
Models
Apertus
BERT
BLOOM
Chinchilla
Claude
DBRX
Gemini
Gemma
Gemma
GloVe
GLM
GPT
GPT-J
PanGu
Granite
Jais
LaMDA
Llama
MiMo
Minerva
Mistral and Mixtral
Nemotron
PaLM
Phi
Qwen
Seq2seq
T5
Vicuna
Word2vec
XLNet
Chatbots and assistants
Amazon Q
ChatGPT
Character.ai
Claude
DeepSeek
Doubao
Ernie Bot
GLM
Google Gemini
Grok
Kimi
Microsoft Copilot
Meta AI
Perplexity AI
Sparrow
You.com
Agents, coding,
and applications
AI agent
Intelligent agent
AutoGPT
CrewAI
LangChain
Manus
Model Context Protocol
Agent2Agent
OpenAI Codex
Vibe coding
Code generation
Question answering
Machine translation
Text summarization
Chatbot
Virtual assistant
LLMs in higher education
Software
PyTorch
TensorFlow
Hugging Face
Inference engine
llama.cpp
Ollama
SGLang
TensorRT-LLM
vLLM
ONNX
OpenVINO
Vector database
ChromaDB
Deep learning software
Open-source AI software
Hardware and infrastructure
AI data center
AI accelerator
GPU
CUDA
TPU
High-bandwidth memory
Benchmarks, evaluation,
and detection
Language model benchmark
MMLU
Humanity's Last Exam
LMArena
LLM-as-a-Judge
Perplexity metric
GPTZero
Artificial intelligence content detection
Undetectable.ai
Datasets and data
Data set
Text corpus
Common Crawl
The Pile
Web scraping
Synthetic data
Training, validation, and test data sets
Organizations
AI21 Labs
Alibaba
Anthropic
Baidu
Cohere
DeepSeek
EleutherAI
Google DeepMind
Hugging Face
Meta AI
Microsoft AI
Mistral AI
MiniMax
Moonshot AI
Nvidia
OpenAI
Sarvam AI
StepFun
Technology Innovation Institute
Thinking Machines Lab
xAI
People
Sam Altman
Dario Amodei
Yoshua Bengio
Aidan Gomez
Demis Hassabis
Geoffrey Hinton
Andrej Karpathy
Yann LeCun
Percy Liang
Liang Wenfeng
Christopher D. Manning
Arthur Mensch
Mira Murati
Alec Radford
Noam Shazeer
Ilya Sutskever
Ashish Vaswani
Andrew Ng
Social, economic,
and governance
AI boom
AI bubble
AI slop
AI anthropomorphism
AI arms race
Chatbot psychosis
Competition
Copyright
Deaths linked to chatbots
Dependency (GAID)
Environmental impact
Regulation
Ethics
Existential risk
In education
In healthcare
Workplace impact
Category:Large language models
Retrieved from " https://en.wikipedia.org/w/index.php?title=Transformer_(deep_learning)&oldid=1368654600"
Categories:
Google software
Neural network architectures
2017 in artificial intelligence
Hidden categories:
Articles with short description
Short description is different from Wikidata
Articles needing additional references from June 2026
All articles needing additional references
Articles lacking reliable references from June 2026
All articles lacking reliable references
Articles with multiple maintenance issues
Wikipedia articles with style issues from February 2026
All articles with style issues
Webarchive template wayback links
All articles that may contain original research
Articles that may contain original research from February 2026
This page was last edited on 10 August 2026, at 09:08 (UTC).
Page was rendered with Parsoid.
Text is available under the Creative Commons Attribution-ShareAlike 4.0 License; additional terms may apply. By using this site, you agree to the Terms of Use and Privacy Policy. Wikipedia® is a registered trademark of the Wikimedia Foundation, Inc., a non-profit organization.
Privacy policy
About Wikipedia
Disclaimers
Contact Wikipedia
Legal & safety contacts
Code of Conduct
Developers
Statistics
Cookie statement
Mobile view
Search
Search [-]
Toggle the table of contents
Transformer (deep learning)
35 languages Add topic