Skip to content
DAH
Wiki/ArchitecturesAlgorithmActive

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
Why other work relies on it

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.

  1. 1Words need context from far away
  2. 2Attention scores every pair of words
  3. 3Blend information using those scores
  4. 4Runs in parallel, so training scales
  5. 5Pair scores make cost grow with n²

Architecture. A transformer maps a sequence of nn token vectors (each of size dmodeld_{\text{model}}) 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 QQ, keys KK and values VV for every token. The output is

Att(Q,K,V)=softmax ⁣(QK⊤d)V.\mathrm{Att}(Q,K,V)=\mathrm{softmax}\!\Big(\tfrac{QK^{\top}}{\sqrt d}\Big)V.

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 QK⊤QK^{\top} takes time proportional to n2dn^2d and the attention matrix has n2n^2 entries, so naive attention is quadratic in context length. The feed-forward layers cost about n dmodel2n\,d_{\text{model}}^2, 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 n dn\,d 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 n×nn\times n 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 TC0\mathsf{TC}^0 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 nn token vectors X∈Rn×dmodelX\in\mathbb R^{n\times d_{\mathrm{model}}} 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 Q,K,V∈Rn×dQ,K,V\in\mathbb R^{n\times d}, and the output is Att(Q,K,V)=softmax ⁣(QK⊤d)V,\mathrm{Att}(Q,K,V)=\mathrm{softmax}\!\Big(\tfrac{QK^{\top}}{\sqrt d}\Big)V, 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 QK⊤QK^{\top} takes O(n2d)O(n^2 d) time and the attention matrix has n2n^2 entries, so naive attention is quadratic in context length. The feed-forward layers cost O(n dmodel2)O(n\,d_{\mathrm{model}}^2), which dominates at short context. During autoregressive generation the keys and values of all previous tokens are cached, so each new token costs O(nd)O(nd) 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 n×nn\times n matrix is never written to slow memory, cutting memory traffic and making memory use linear in nn. 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 nn, 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 1/poly(n)1/\mathrm{poly}(n) additive error: when entries of Q,K,VQ,K,V are bounded by o(log⁡n)o(\sqrt{\log n}) there is an n1+o(1)n^{1+o(1)} algorithm, and when they reach Θ(log⁡n)\Theta(\sqrt{\log n}) no truly subquadratic algorithm exists unless the Strong Exponential Time Hypothesis fails (for head dimension d=Θ(log⁡n)d=\Theta(\log n)). 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 TC0\mathsf{TC}^0, 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)
Words on this page
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)
New to this? Read first

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.

  1. Start with
  2. Step 2
  3. Step 3
  4. Then

Open problems & questions

Progress timeline

  1. Apr 20, 2026
    Depth–cache trade-offs (preprint)
    Related to: Unconditional Ω(log k) depth lower bound for k-hop induction heads in narrow transformers

    X. Wang proved unconditional max-type depth bounds for KV-compressed transformers on pointer chasing and conjectured the product form. Not refereed.

    source
  2. Apr 28, 2025
    Rigorous feature-learning scaling laws on isotropic data
    Related to: Proving the t−2β/(1+β) feature-learning loss exponent for hard tasks under power-law kernel spectra

    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).

    source
  3. Dec 4, 2024
    First unconditional multi-layer transformer lower bound
    Related to: Unconditional Ω(log k) depth lower bound for k-hop induction heads in narrow transformers

    Chen, Peng and Wu proved that constant-depth decoder-only transformers need polynomial width for sequential function composition.

    source
  4. Sep 26, 2024
    DMFT prediction of the hard-task exponent
    Related to: Proving the t−2β/(1+β) feature-learning loss exponent for hard tasks under power-law kernel spectra

    Bordelon, Atanasov and Pehlevan predict that feature learning improves the time exponent from β to 2β/(1+β) for hard tasks (non-rigorous; ICLR 2025).

    source
  5. Jun 12, 2024
    Scaling laws proved for SGD linear regression
    Related to: Proving the t−2β/(1+β) feature-learning loss exponent for hard tasks under power-law kernel spectra

    Lin et al. give matching upper and lower bounds in data, parameters and compute for power-law spectra (lazy/linear setting).

    source
  6. Feb 14, 2024
    Log-depth transformers for k-hop induction heads
    Related to: Unconditional Ω(log k) depth lower bound for k-hop induction heads in narrow transformers

    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.

    source
  7. Dec 1, 2023
    Mamba

    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.

    source
  8. Feb 26, 2023
    Fine-grained hardness of attention

    Alman and Song proved a SETH-conditional threshold, at entry magnitude about the square root of log n, between near-linear and quadratic attention.

    source
  9. May 27, 2022
    FlashAttention

    An IO-aware exact attention kernel reduced memory traffic and became standard in training and inference stacks.

    source
  10. Jan 23, 2020
    Kaplan et al. power-law scaling
    Related to: Proving the t−2β/(1+β) feature-learning loss exponent for hard tasks under power-law kernel spectra

    Loss follows power laws in parameters, data and compute over several orders of magnitude.

    source
  11. Nov 22, 2018
    Barrier for MPC round lower bounds
    Related to: Unconditional Ω(log k) depth lower bound for k-hop induction heads in narrow transformers

    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).

    source
  12. Jun 12, 2017
    The transformer is introduced

    Vaswani et al. proposed an architecture based solely on attention and reported state-of-the-art machine translation at lower training cost.

    source