The transformer architecture
The attention-based neural network design behind modern language models, and the quadratic cost of attention that drives work on exact, approximate and recurrent alternatives.
On this page14 sections
Nearly all large language models and many vision and protein models are transformers, so its compute and memory costs set the economics of training and inference.
The neural network design behind chatbots, which lets every word look at every other word, at a rising cost.
- 1Words need context from far away
- 2Attention scores every pair of words
- 3Blend information using those scores
- 4Runs in parallel, so training scales
- 5Pair scores make cost grow with n²
Architecture. A transformer maps a sequence of token vectors (each of size ) to a sequence of the same shape through a stack of identical blocks. Each block has a self-attention layer and a position-wise feed-forward network, each wrapped in a residual connection and normalisation. Vaswani et al. (2017) introduced it for machine translation, replacing recurrent networks.
In one attention head, learned linear maps produce queries , keys and values for every token. The output is
In words: each token's query is compared with every token's key to get scores; softmax turns each row of scores into weights that add up to 1; the output for each token is the weighted average of the values. Several heads run in parallel and are concatenated. In a decoder-only language model a causal mask stops each position from seeing later ones, and the model predicts the next token.
Cost. Forming takes time proportional to and the attention matrix has entries, so naive attention is quadratic in context length. The feed-forward layers cost about , which dominates at short contexts. During generation, the keys and values of earlier tokens are stored in a KV cache, so each new token costs time proportional to but must read the whole cache from memory, which makes decoding limited by memory bandwidth on current accelerators. Training uses reverse-mode automatic differentiation and is parallel across positions, a main reason transformers displaced recurrent networks.
Making attention cheaper. Three families of responses:
- Exact but IO-aware. FlashAttention (Dao et al., 2022) computes exactly the same output but tiles the computation so the matrix is never written to slow memory, cutting memory traffic.
- Approximate. Sparse patterns, low-rank sketches or hashing reduce the cost by accepting a small error.
- Recurrent or state-space alternatives. Replace attention with a fixed-size running state to get linear cost, at some loss of recall of exact earlier details.
Theory questions. What can a transformer of given depth, width and precision compute? How many layers does a task like following a chain of references need? What do scaling laws, the smooth improvement of loss with more data and compute, look like theoretically? Some answers are known. With limited numerical precision, constant-depth transformers can only compute functions in the circuit class in one forward pass (Merrill and Sabharwal). And computing attention to good accuracy in truly subquadratic time is impossible for large entries unless SETH fails, while it can be done almost linearly for small entries (Alman and Song, 2023). Most other questions, including why scaling laws hold, are open.
Go deeper
The full technical text.
Architecture
A transformer maps a sequence of token vectors to a sequence of the same shape through a stack of identical blocks. Each block has a self-attention layer and a position-wise feed-forward network, each wrapped in a residual connection and normalisation. In one attention head, learned projections give queries, keys and values , and the output is where softmax acts on each row. Several heads run in parallel and their outputs are concatenated. In a decoder-only language model a causal mask forbids attending to later positions and the model predicts the next token. Vaswani et al. (2017) introduced the design for machine translation, replacing the recurrent networks that had dominated sequence modelling.
Cost
Forming takes time and the attention matrix has entries, so naive attention is quadratic in context length. The feed-forward layers cost , which dominates at short context. During autoregressive generation the keys and values of all previous tokens are cached, so each new token costs time but requires reading the whole cache from memory, which makes decoding memory-bound on current accelerators. Training uses reverse-mode automatic differentiation and is parallel across positions, which is a main reason transformers displaced recurrent networks.
Making attention cheaper
There are three families of responses.
Exact but IO-aware. FlashAttention (Dao et al., 2022) computes exactly the same output but tiles the computation so the matrix is never written to slow memory, cutting memory traffic and making memory use linear in . The arithmetic stays quadratic.
Approximate or sparse. Sparse, low-rank, kernel and hashing-based methods approximate the attention matrix. Linear attention (Katharopoulos et al., 2020) replaces the softmax by a kernel feature map so that attention can be computed as a recurrence with a fixed-size state.
Recurrent and state-space layers. Models such as Mamba (Gu and Dao, 2023) use selective state-space recurrences with cost linear in , and hybrids interleave them with a few full-attention layers. Their hidden state has fixed size, which limits how much of a long context they can retrieve exactly; how much this matters in practice has been studied mainly by experiment, not theory.
What theory says
Alman and Song (2023) proved a sharp threshold for computing attention to within additive error: when entries of are bounded by there is an algorithm, and when they reach no truly subquadratic algorithm exists unless the Strong Exponential Time Hypothesis fails (for head dimension ). Standard transformers also face expressivity limits: with saturated attention (Merrill, Sabharwal and Smith, TACL 2022) or with logarithmic numerical precision (Merrill and Sabharwal, TACL 2023), constant-depth transformers compute only functions in the circuit class , which limits what they can do in a single forward pass, without long chains of generated reasoning tokens.
Open questions
Whether a subquadratic layer can match full attention on the tasks that matter, and why transformer loss improves predictably with scale, are treated in the two open problems attached to this entry.
Words on this page (12)
- transformer
- A neural network design built around attention, used in most modern language models.
- attention
- A mechanism that lets each word weigh how relevant every other word is when forming its representation.
- softmax
- A function that turns a list of scores into positive weights that add up to one.
- large language model
- A neural network trained on huge amounts of text to predict and generate language.
- token
- A small chunk of text, such as a word or part of a word, that the model reads as one unit.
- quadratic cost
- Cost that grows with the square of the size: double the input, four times the work.
- reverse-mode autodiff
- The method that computes all of a network's gradients in one backward pass, used to train transformers.
- GPU
- A chip with thousands of small cores that does many calculations in parallel.
- matrix multiplication
- The core arithmetic of neural networks: combining grids of numbers row by column.
- query, key, value
- Three vectors computed for each token: a query is compared with every key to get scores, which then weight the values that are averaged.
- KV cache
- Stored keys and values of earlier tokens, so generating each new token does not recompute them; reading it is often the bottleneck.
- recurrent neural network
- A network that reads a sequence one step at a time, carrying a fixed-size memory forward; transformers replaced it for most language tasks.
New to this? Read first (3)
- Transformer (deep learning architecture) (Wikipedia)A full overview of the design and its history.
- Attention (machine learning) (Wikipedia)Focuses on the attention idea itself.
- Attention Is All You Need (Vaswani et al., 2017)The original paper, whose first sections are readable.
Understanding map
map of the whole wiki →What to read before The transformer architecture (left), and what builds on it: entries that depend on it and its open problems (right). Every box links to its page.
- Start with
- Step 2
- Fast matrix multiplicationAlgorithm
- Step 3
- The transformer architectureYou are here
- Then
- Biomolecular structure prediction (AlphaFold-style)Algorithm
- Protein language models and generative protein designFrontier
- Medical image segmentationAlgorithm
- Tensor, data and pipeline parallelism with compute-communication overlapAlgorithm
- FlashAttention: IO-aware exact attentionAlgorithm
- Paged attention and KV-cache kernelsAlgorithm
- Sparse autoencoders for interpretabilityAlgorithm
- Mechanistic circuits and causal interventionsTheory
- Unconditional Ω(log k) depth lower bound for k-hop induction heads in narrow transformersOpen problem · D66
- Proving the t−2β/(1+β) feature-learning loss exponent for hard tasks under power-law kernel spectraOpen problem · D47
Open problems & questions
Progress timeline
- Apr 20, 2026Depth–cache trade-offs (preprint)Related to: Unconditional Ω(log k) depth lower bound for k-hop induction heads in narrow transformerssource
X. Wang proved unconditional max-type depth bounds for KV-compressed transformers on pointer chasing and conjectured the product form. Not refereed.
- Apr 28, 2025Rigorous feature-learning scaling laws on isotropic dataRelated to: Proving the t−2β/(1+β) feature-learning loss exponent for hard tasks under power-law kernel spectrasource
Ren, Nichani, Wu and Lee prove scaling exponents for online SGD on two-layer networks learning power-law additive targets with isotropic Gaussian inputs (NeurIPS 2025).
- Dec 4, 2024First unconditional multi-layer transformer lower boundRelated to: Unconditional Ω(log k) depth lower bound for k-hop induction heads in narrow transformerssource
Chen, Peng and Wu proved that constant-depth decoder-only transformers need polynomial width for sequential function composition.
- Sep 26, 2024DMFT prediction of the hard-task exponentRelated to: Proving the t−2β/(1+β) feature-learning loss exponent for hard tasks under power-law kernel spectrasource
Bordelon, Atanasov and Pehlevan predict that feature learning improves the time exponent from β to 2β/(1+β) for hard tasks (non-rigorous; ICLR 2025).
- Jun 12, 2024Scaling laws proved for SGD linear regressionRelated to: Proving the t−2β/(1+β) feature-learning loss exponent for hard tasks under power-law kernel spectrasource
Lin et al. give matching upper and lower bounds in data, parameters and compute for power-law spectra (lazy/linear setting).
- Feb 14, 2024Log-depth transformers for k-hop induction headsRelated to: Unconditional Ω(log k) depth lower bound for k-hop induction heads in narrow transformerssource
Sanford, Hsu and Telgarsky gave a ⌊log₂ k⌋+2-layer construction and an Ω(log k) lower bound conditional on the one-versus-two-cycles conjecture.
- Dec 1, 2023Mambasource
Gu and Dao proposed selective state-space models with linear-time sequence modelling; in their experiments a 3-billion-parameter Mamba outperformed transformers of the same size and matched transformers twice its size on language modelling.
- Feb 26, 2023Fine-grained hardness of attentionsource
Alman and Song proved a SETH-conditional threshold, at entry magnitude about the square root of log n, between near-linear and quadratic attention.
- May 27, 2022FlashAttentionsource
An IO-aware exact attention kernel reduced memory traffic and became standard in training and inference stacks.
- Jan 23, 2020Kaplan et al. power-law scalingRelated to: Proving the t−2β/(1+β) feature-learning loss exponent for hard tasks under power-law kernel spectrasource
Loss follows power laws in parameters, data and compute over several orders of magnitude.
- Nov 22, 2018Barrier for MPC round lower boundsRelated to: Unconditional Ω(log k) depth lower bound for k-hop induction heads in narrow transformerssource
Roughgarden, Vassilvitskii and Wang showed that super-constant round lower bounds for problems in P in the MPC model would imply new circuit lower bounds (J. ACM 2018; SPAA 2016).
- Jun 12, 2017The transformer is introducedsource
Vaswani et al. proposed an architecture based solely on attention and reported state-of-the-art machine translation at lower training cost.