In June 2017, eight researchers at Google published a paper titled "Attention Is All You Need." The title was a provocation - a claim that the dominant paradigm for processing sequential data was unnecessary.

Recurrent neural networks, long short-term memory networks, convolutional sequence models: the field had spent years refining these architectures for processing text, audio, and other sequential data.

The Google researchers proposed replacing all of it with a single mechanism called self-attention.

The paper introduced the transformer architecture. Within three years, virtually every major advance in artificial intelligence would be built on it. GPT, BERT, T5, PaLM, LLaMA, Claude, Gemini - all are transformers.

Almost all of the image models, the audio models, the protein folding models and the code generation models are transformers or transformer-derived. The architecture changed the field more profoundly than any single development since backpropagation.

Understanding the transformer (what it does, why it works, and what it replaced) is understanding the foundation of every modern AI system.

"The Transformer is the first transduction model relying entirely on self-attention to compute representations of its input and output without using sequence-aligned RNNs or convolution."

Vaswani et al., Attention Is All You Need (2017)

The original paper by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N.[1] Gomez, Lukasz Kaiser, and Illia Polosukhin has become one of the most cited papers in the history of computer science.

It had collected over 100,000 citations by 2024. That number does not come from academic tribute alone. Instead, virtually every major AI system built in the past seven years depends on its ideas.


Key Definitions

Transformer - A neural network architecture that processes sequential data using self-attention rather than recurrence or convolution. Introduced by Vaswani et al. (2017) at Google. The basis of virtually all large-scale AI language models, and increasingly applied to image, audio, video, and protein structure data.

Self-attention - The core mechanism of the transformer. For each position in an input sequence, self-attention computes a weighted representation that reflects the relationships between that position and every other position in the sequence.

The weights (attention scores) determine how much each other position contributes to the representation at the current position.

Attention mechanism This is a general technique that computes context-dependent representations by selectively focusing on the parts of the input that are relevant. Self-attention is a specific form of attention where a sequence attends to itself. The attention mechanism came before transformers but was used earlier as a supplement to recurrent networks.

Recurrent neural network (RNN) - A neural network architecture that processes sequences one element at a time, maintaining a hidden state that accumulates information from previous elements. RNNs were the dominant architecture for sequence processing before transformers.

Information from early in a long sequence degrades as it goes through many processing steps before it gets to influence later outputs. That is their main limitation.

Long short-term memory (LSTM). This is a variant of RNNs that has gating mechanisms designed to learn longer-range dependencies. Large improvements over vanilla RNNs came from LSTMs on long sequences, yet they still processed inputs sequentially and that stopped parallelization during training.

Token. This is the basic unit of input for a transformer. When text gets tokenized (split into words, subwords or characters as the tokenizer calls for), every token is turned into a numerical vector (an embedding) before the model processes it. Most language models today work with byte-pair encoding (BPE) or a similar system for subword tokenization.

Embedding - A numerical vector representation of a token. Embeddings encode semantic relationships: tokens with similar meanings have embeddings that are geometrically close. The transformer converts input tokens to embeddings, processes them, and converts output embeddings back to tokens.

Positional encoding - Information added to token embeddings to convey the position of each token in the sequence. Because transformers process all positions simultaneously, they have no inherent sense of order. Positional encodings inject this information.

Fixed sinusoidal functions were what the original paper used. Modern architectures most often use learned or rotary position encodings instead.

Multi-head attention. Several self-attention computations run at once in parallel, each one capable of capturing a different type of relationship. The outputs get concatenated and then transformed by a linear layer and having multiple heads lets the model represent different aspects of input relationships all at once.

Feed-forward layer. Every transformer layer has a position-wise feed-forward network following the attention sublayer. It is a two-layer fully connected network that acts independently on each position. Non-linearity gets introduced by this component and model capacity gets increased.

Layer normalization - A normalization technique applied at each sublayer to stabilize training by normalizing the values flowing through the network. Helps prevent the gradient problems that plagued deep networks before normalization techniques were developed.

Encoder - The transformer component that processes the full input sequence bidirectionally, producing a rich representation of the input. Encoder models (BERT and its variants) are well-suited for understanding tasks.

Decoder - The transformer component that generates output sequences autoregressively - one token at a time, with each new token attending only to previously generated tokens and the encoder output. Decoder models (GPT and its variants) are well-suited for generation tasks.

Autoregressive generation - The process by which decoder transformers generate output: producing one token at a time, with each token generated by sampling from a probability distribution conditioned on all previous tokens. The model generates the most probable continuation given everything that came before.


The Problem Transformers Solved

Sequential Processing Was a Bottleneck

Recurrent neural networks were the standard architecture for sequence processing through the mid-2010s. An RNN processes a sequence element by element: at each step, it takes the current input and the previous hidden state, produces a new hidden state, and optionally an output.

This hidden state is supposed to carry information about everything the model has seen so far.

The problem is that the hidden state is a fixed-size vector. For long sequences, compressing all relevant information into a single vector at each step is increasingly difficult. Information from early in the sequence must survive many transformations before it can influence outputs near the end of the sequence.

The further apart two elements are in the sequence, the harder it is for the network to learn the relationship between them.

By adding gating mechanisms that let the network pick what it retains and what it forgets, LSTMs and GRUs built on vanilla RNNs and got better.[6] The basic limit though was still there. It was sequential processing, one element at a time.

"Long Short-Term Memory can learn to bridge minimal time lags in excess of 1000 discrete-time steps by enforcing constant error flow through 'constant error carousels' within special units."

Sepp Hochreiter and Jurgen Schmidhuber, Neural Computation (1997)

LSTMs were a real advance yet they did not get rid of the sequential bottleneck. Sequential processing meant sequential training as well. You could not begin step 50 until step 49 was finished and that put a severe limit on how efficiently training could be done on modern parallel hardware.

Machine Translation: The Domain That Exposed RNN Limits

The clearest evidence of RNN limitations emerged in machine translation. For short sentences, RNN-based sequence-to-sequence models performed well. For longer sentences, quality degraded - not because the vocabulary was harder but because the model was losing track of relationships between sentence elements separated by many words.

Take a sentence like "The economic policies that the government brought in last year, despite big opposition from industry groups as well as several parliamentary debates, seem to have had the intended effect." An RNN has to pass information about "policies" through dozens of tokens before linking it to "appear" and "effect." At each intermediate step, part of what should be kept gets overwritten.

In its 2015 attention paper (Neural Machine Translation by Jointly Learning to Align and Translate)[7], Bahdanau, Cho and Bengio solved this by letting the decoder draw directly from all encoder hidden states instead of using just the final one.

Significant improvement in translation quality for long sentences came out of their experiments as the first clear empirical evidence that direct attention mechanisms could get past the distance limit.

What Vaswani et al. recognized was that attention was not a supplement - it was sufficient. If you could compute relationships between any two positions in a sequence directly, without needing recurrence to propagate information, you did not need recurrence at all.


How Self-Attention Works

Each input token goes through the transformer, which computes a weighted mix of all tokens. Those weights reflect how relevant each token is to the current one. The mechanism draws on three learned projections of each token's embedding.

Query (Q): What this token is looking for.Key (K): What this token offers to others.Value (V): What information this token contributes when attended to.

For each position, the attention weight with every other position is computed as the dot product of the query at the current position with the key at the other position, scaled and passed through a softmax function to produce a probability distribution over all positions.

The output is a weighted sum of the values, weighted by these attention probabilities.

The mathematical formulation is:

Attention(Q, K, V) = softmax(QK^T / sqrt(d_k)) * V

The dimension of the key vectors is d_k. Scaling by sqrt(d_k) stops the dot products from getting too large in magnitude. That would drive the softmax into regions where gradients are very small.

The result: each token's output representation is a mixture of all tokens' value vectors, with higher weight given to tokens that are more relevant to the current query. A token can effectively look at the entire context and incorporate information from wherever it is most relevant.

An Intuition: Subject-Verb Agreement

Take the sentence "The books that the student borrowed are overdue." As the word "are" is processed, the transformer must figure out that it should agree with "books" (the subject of the main clause) and not with "student" (the grammatically closer noun).

Because RNNs had trouble with it, self-attention lets "are" compute a relationship directly with "books" no matter how far apart they are and that is what RNNs struggled with.

Attention analyses of trained transformers have confirmed that attention heads do learn to capture exactly these kinds of grammatical long-range dependencies.

Multi-Head Attention

Multi-head attention runs the attention computation multiple times in parallel with different learned projections. Each "head" may capture a different type of relationship: grammatical dependencies, semantic similarity, positional patterns, coreference. The outputs of all heads are concatenated and linearly transformed.

Research by Clark et al. (2019), "What Does BERT Look At? An Analysis of BERT's Attention," found that different attention heads in trained transformers learned qualitatively different functions - some heads focused on attending to the next or previous token (positional patterns), while other heads learned to attend across long-range syntactic dependencies such as verb-object pairs.[12]

This division of function across heads emerged from training, not from explicit design.


Encoder vs. Decoder Architectures

When the original transformer paper came out, it described a full encoder-decoder architecture for sequence-to-sequence jobs such as translation. Later work showed that the encoder and decoder parts could be used on their own for different purposes.

ArchitectureAttention DirectionPrimary UseExamples
Encoder-onlyBidirectional (each position attends to all positions)Understanding tasks: classification, named entity recognition, question answeringBERT, RoBERTa, ELECTRA
Decoder-onlyCausal (each position attends only to previous positions)Generation tasks: text completion, dialogue, code generationGPT-2, GPT-3, GPT-4, LLaMA, Claude
Encoder-decoderEncoder: bidirectional; Decoder: causal + cross-attention to encoderSeq-to-seq tasks: translation, summarization, question answeringT5, BART, original Transformer

BERT: Bidirectional Understanding

Jacob Devlin, Ming-Wei Chang, Kenton Lee, and Kristina Toutanova at Google introduced BERT (Bidirectional Encoder Representations from Transformers) in 2018.[2] The key insight: for understanding tasks, you want to use context from both before and after a token.

BERT used a pretraining task called masked language modeling - randomly masking tokens and training the model to predict the masked token from its surrounding context in both directions.

BERT's impact on the field was immediate and dramatic. Within six months of its release, BERT-based models set new state-of-the-art results on 11 NLP benchmarks.

Through the early 2020s, the approach of pretraining on large text corpora and then fine-tuning on specific tasks became the dominant paradigm for natural language processing.

GPT: The Path to Generative Power

OpenAI's GPT (Generative Pretrained Transformer) series took a different approach: a decoder-only architecture trained purely on the task of predicting the next token. Radford et al. (2019) showed in "Language Models are Unsupervised Multitask Learners" that sufficiently large GPT-style models could perform diverse tasks - translation, summarization, question answering - as a consequence of their generative training, without task-specific fine-tuning.[3]

GPT-3 (Brown et al., 2020), with 175 billion parameters, demonstrated that scale alone could produce remarkable emergent capabilities: few-shot learning, arithmetic, code generation, and complex reasoning that no one had explicitly trained it for.[5]

This established the "scale hypothesis" - that continued scaling of transformer language models would continue producing qualitative capability improvements.


Why Transformers Scaled So Well

Parallelization During Training

Because self-attention processes all positions simultaneously, transformers can leverage modern GPU and TPU hardware far more efficiently than RNNs, which process positions sequentially. Training an RNN on a 512-token sequence requires 512 sequential steps.

Training a transformer on the same sequence requires a fixed number of matrix operations that can be parallelized completely.

Far more data can be trained on in a given amount of compute than before thanks to this parallelization advantage and that gives transformers better models. More data plus more compute make for better models. As the field turned to larger datasets and larger models, the scaling advantage became decisive.

The Scaling Laws

Jared Kaplan et al. at OpenAI published empirical scaling laws for transformer language models in 2020.[4]

By language modeling loss as the measure of model performance, they discovered smooth power-law relationships between model size (number of parameters), training data size (number of tokens) and compute. That these relationships held across many orders of magnitude.

"We find that language modeling performance depends strongly on scale (the number of model parameters, the size of the dataset, and the amount of compute used for training) and only weakly on the model architecture within a class."

Kaplan et al., Scaling Laws for Neural Language Models (2020)

Making transformers better mostly meant making them bigger and training them on more data so this was a profound result. Architecture was not what held things back. What did hold things back was scale and transformers were much better positioned to scale than any architecture before them.

A subsequent refinement came from Hoffmann et al.[8] (2022) at DeepMind in the "Chinchilla" paper, which found that the Kaplan et al. laws underestimated the importance of training data relative to model size.

Substantially outperforming GPT-3 (175B parameters and trained on just 300 billion tokens), Chinchilla (70B parameters and trained on 1.4 trillion tokens) shows that within a given compute budget, in general a smaller model trained on more data beats a larger model trained on less data.


Modern Developments

Sparse Attention and Efficient Transformers

Self-attention has quadratic complexity by standard measure and that means computing all pairwise attention scores for a sequence of length N takes N squared operations. Long sequences make that prohibitively costly and many efficient attention variants have been developed to deal with this.

  • Sparse attention (Child et al., 2019). Attention is computed only between subsets of positions instead of all pairs and this brings complexity down from O(N^2) to O(NN).
  • Linear attention (Katharopoulos et al., 2020): Approximating attention with linear complexity using kernel methods
  • Sliding window attention (Beltagy et al., 2020, Longformer): Each position attends only to a local window of neighbors plus a few global tokens
  • FlashAttention (Dao et al., 2022): Not reducing the theoretical complexity but dramatically improving the practical speed and memory efficiency of exact attention through careful GPU memory access patterns[11]

By 2023 FlashAttention had become almost universally adopted in production transformer training and deserved special mention for that reason. It gave 2 to 4 times speed improvements and let training on longer sequences without using any algorithmic approximations.

Rotary Position Encoding

The original paper used fixed sinusoidal positional encodings added to token embeddings. More recent architectures use Rotary Position Encoding (RoPE), introduced by Su et al. (2022) and adopted in LLaMA, PaLM 2, and GPT-NeoX.

RoPE incorporates position information directly into the attention computation by rotating the query and key vectors.

More naturally integrated with the attention mechanism and able to generalize better to sequence lengths longer than what was seen during training, RoPE has a critical property needed to extend context windows.

Mixture of Experts

Mixture-of-Experts (MoE) architectures that Shazeer et al. (2017) popularized for transformers and more recently in Google's Switch Transformer (Fedus et al., 2021) replace the standard feed-forward layer with several expert networks. Each token gets a subset of experts selected rather than all of them being used.

This allows models to have more total parameters without a proportional increase in compute, since only a fraction of parameters are active for any given input.

Needing less compute at inference time, Mixtral 8x7B (Jiang et al., 2024) showed that a MoE model with 46.7B total parameters but only 12.9B active parameters per forward pass could match or top the performance of dense 70B models.

Vision Transformers

The transformer's reach has extended far beyond text. Vision Transformers (ViT), introduced by Dosovitskiy et al.[9] (2020) at Google, applied transformers directly to images by splitting images into patches and treating each patch as a token.

When trained on large datasets, ViT models matched or surpassed convolutional neural networks on image classification benchmarks and this showed that the transformer architecture was not fundamentally about language.

Transformers have gone on to be used for audio (Whisper, AudioLM), video (VideoGPT), predicting protein structure (AlphaFold 2, ESMFold), weather forecasting (GraphCast) and even drug design. This points to the transformer being a genuinely general-purpose architecture for learning from structured data.

AlphaFold 2: A Landmark Application

Perhaps the most dramatic single demonstration of the transformer's power outside of language came with AlphaFold 2 (Jumper et al., 2021), which solved the protein folding problem that had been considered one of biology's grand challenges for fifty years.[10]

With an attention-based architecture called the Evoformer, AlphaFold 2 processed multiple sequence alignments as well as structural features and hit accuracy that matched what experimental methods could do.

Its results won the Critical Assessment of Protein Structure Prediction (CASP14) competition by a margin so large that many researchers described it as having "solved" the problem.


The Transformer's Limitations

Quadratic Attention Cost

The O(N^2) complexity of full self-attention limits practical sequence lengths. While techniques like FlashAttention and sparse attention alleviate this, processing extremely long contexts (millions of tokens) remains computationally expensive.

Active research is going on in this field and models such as Mamba (Gu and Dao, 2023) propose state-space model alternatives that get linear complexity.

Lack of Built-In Memory

There is no persistent memory across interactions and each input gets processed independently by transformers. The model has to have everything it can use within the context window. That differs from human cognition in which relevant past experiences can be retrieved over much longer timescales.

Partial solutions are retrieval-augmented generation (RAG) and external memory architectures but the basic design does not natively support long-term memory.

Data Hunger

To work at scale, transformers need huge training datasets. GPT-4, LLaMA and models like them were trained on trillions of tokens. Data hunger creates worries about data quality, intellectual property, privacy and the environmental cost of training.

The Chinchilla scaling laws partly addressed compute efficiency, but the fundamental data requirement remains.


Sources & Further Reading

  1. Vaswani, A., Shazeer, N., Parmar, N., Uszkoreit, J., Jones, L., Gomez, A. N., Kaiser, L., & Polosukhin, I. (2017). Attention Is All You Need. Advances in Neural Information Processing Systems, 30. View source
  2. Devlin, J., Chang, M.-W., Lee, K., & Toutanova, K. (2018). BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding. arXiv preprint arXiv:1810.04805. View source
  3. Radford, A., Wu, J., Child, R., Luan, D., Amodei, D., & Sutskever, I. (2019). Language Models are Unsupervised Multitask Learners. OpenAI Blog.
  4. Kaplan, J., McCandlish, S., Henighan, T., Brown, T. B., Chess, B., Child, R., Gray, S., Radford, A., Wu, J., & Amodei, D. (2020). Scaling Laws for Neural Language Models. arXiv preprint arXiv:2001.08361. View source
  5. Brown, T. B., et al. (2020). Language Models are Few-Shot Learners. Advances in Neural Information Processing Systems, 33. View source
  6. Hochreiter, S., & Schmidhuber, J. (1997). Long Short-Term Memory. Neural Computation, 9(8), 1735-1780. View source
  7. Bahdanau, D., Cho, K., & Bengio, Y. (2015). Neural Machine Translation by Jointly Learning to Align and Translate. arXiv preprint arXiv:1409.0473. View source
  8. Hoffmann, J., Borgeaud, S., Mensch, A., Buchatskaya, E., Cai, T., Rutherford, E., de las Casas, D., Hendricks, L. A., Welbl, J., Clark, A., et al. (2022). Training Compute-Optimal Large Language Models. arXiv preprint arXiv:2203.15556. View source
  9. Dosovitskiy, A., Beyer, L., Kolesnikov, A., Weissenborn, D., Zhai, X., Unterthiner, T., Dehghani, M., Minderer, M., Heigold, G., Gelly, S., Uszkoreit, J., & Houlsby, N. (2020). An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale. arXiv preprint arXiv:2010.11929. View source
  10. Jumper, J., Evans, R., Pritzel, A., Green, T., Figurnov, M., Ronneberger, O., Tunyasuvunakool, K., Bates, R., Zidek, A., Potapenko, A., et al. (2021). Highly Accurate Protein Structure Prediction with AlphaFold. Nature, 596, 583-589. View source
  11. Dao, T., Fu, D. Y., Ermon, S., Rudra, A., & Re, C. (2022). FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness. NeurIPS 2022. View source
  12. Clark, K., Khandelwal, U., Levy, O., & Manning, C. D. (2019). What Does BERT Look At? An Analysis of BERT's Attention. ACL Workshop on BlackboxNLP. View source