The Mathematics of Transformers
Attention derived from scratch, why the scaling is 1/sqrt(d_k), multi-head as a low-rank sum, positional encodings, residual and normalisation placement, and the exact complexity.
Attention
Let hold token representations as rows.
with the softmax applied row-wise. is row-stochastic: and , so row of the output is a convex combination of the value vectors.
Suppose the entries of and are independent with mean and variance , as at standard initialisation. Then
so has standard deviation , growing with . Dividing by makes the standard deviation , independent of the head dimension.
Let for logits . Then
and for any , . Hence if concentrates on one index, the Jacobian is approximately zero.
Key idea
Combine the two propositions. Without the factor, logits would have standard deviation growing like ; with and that is a spread of across positions, which after softmax is near-one-hot. The Jacobian is then a variance of a near-degenerate distribution, i.e. near zero, and no gradient flows through the attention weights. The scaling is not cosmetic: it is what keeps the softmax in its informative regime at initialisation.
Let be an permutation matrix. Then
Consequently a transformer without positional information computes a function of the input multiset, not the sequence.
This is why positional encodings are required, not an enhancement. The MLP and normalisation sublayers act position-wise and are therefore also permutation equivariant, so nothing else in the architecture breaks the symmetry.
Multi-head attention
with so that the total parameter count matches a single head of full width.
Partition into blocks . Then
where . Each head contributes an attention pattern composed with a rank- value transformation, and each logit matrix is determined by the rank- matrix .
Key idea
The interesting quantity is not and separately but their product , of rank at most — and likewise . A head is fully specified by these two low-rank matrices, which is the observation underlying the circuit-level analyses in the interpretability literature, and also the observation that makes LoRA natural: if the operative objects are already low rank, a low-rank update is an appropriate parameterisation.
Multiple heads are therefore a rank allocation choice: heads of rank each rather than one map of rank . The total parameter count is the same; what changes is that each head is forced to attend according to a single low-dimensional similarity structure, and different heads can specialise.
Positional information
added to the token embedding at position . Because
a shift by acts as a fixed linear map on each frequency pair — so relative position is linearly available to the model.
Let be the block-diagonal rotation acting on coordinate pairs by angle , and define , . Then
so the attention logit depends on and only through .
This is why rotary embeddings (RoPE) are now standard: relative position is built into the inner product exactly, rather than being linearly recoverable as with additive sinusoids, and the construction extends to unseen positions.
Residual stream, normalisation and the MLP block
A pre-norm transformer layer is
with , , .
The additive form means is a residual stream that every sublayer reads from and writes to, with Jacobian — the same identity-path mechanism as the LSTM cell state, with the gate fixed at one.
Empirical observation — a regularity seen in experiments. No theorem on this page establishes it in general.
The original transformer used post-norm, , and required a learning-rate warmup to train at all beyond a modest depth. Pre-norm trains stably without warmup and is now universal for large models.
What this does not say
Xiong et al. give a partial account: in post-norm the expected gradient norm at initialisation grows with depth, so the first steps are too large and destroy the initialisation; warmup masks this by starting small. In pre-norm the gradient norm is roughly depth-independent. Their analysis is at initialisation and under simplifying assumptions, so it explains the need for warmup rather than everything about the two variants' behaviour throughout training. The practical choice is settled; the theory is suggestive rather than complete.
Heuristic — a reasoning shortcut that predicts the right answer in the regimes discussed here. It is not a proof and can fail outside them.
Write the attention output for query as
This is exactly a Nadaraya–Watson kernel-weighted average with kernel .
What this does not say
The analogy is genuinely useful: it explains why attention is a smoother, why temperature (the ) controls bandwidth, and it motivates the linear-attention family, which replaces by a factorisable and thereby reduces the cost from to .
But is not symmetric in the sense a kernel smoother assumes — queries and keys come from different projections of the same input, so is a similarity between two different representations of tokens, not a distance-based kernel on a single space. It is positive definite as a function of pairs via the exponential of a linear kernel, but the Nadaraya–Watson theory that gives rates for kernel smoothers assumes a fixed kernel and i.i.d. data, neither of which holds. Treat the analogy as a source of architectural ideas, not as a route to guarantees.
Complexity
For sequence length , model width , and MLP expansion factor :
| Component | FLOPs | Memory (activations) |
|---|---|---|
| projections | ||
| Logits | (per head, total) | |
| Output projection | ||
| MLP | ||
| Total |
Attention dominates the MLP when .
Key idea
The crossover at is worth internalising. For a model with and context , the MLP dominates and attention is not the bottleneck. At attention dominates by a factor of . This is why long-context work is about attention specifically, and why the memory for the attention matrix is often the harder constraint than the FLOPs — FlashAttention's contribution is to compute exact attention without ever materialising the matrix, by tiling and recomputation, reducing memory to at no accuracy cost.
Problems
Why attention divides by the square root of d_kProof · Intermediate · 30 min The softmax Jacobian as a variance, and saturationProof · Intermediate · 30 min Attention is permutation equivariantProof · Intermediate · 30 min Multi-head attention is a sum of low-rank mapsProof · Advanced · 30 min Rotary embeddings encode relative position exactlyProof · Advanced · 30 min When does attention dominate the MLP?Numerical · Beginner · 30 min Implement multi-head attention from scratchCoding · Intermediate · 3 hoursReferences
- PaperAshish Vaswani and collaborators (2017). Attention Is All You Need
- PaperJianlin Su, Yu Lu, Shengfeng Pan, Ahmed Murtadha, Bo Wen and Yunfeng Liu (2021). RoFormer: Enhanced Transformer with Rotary Position Embedding
- PaperRuibin Xiong and collaborators (2020). On Layer Normalization in the Transformer Architecture
- PaperTri Dao, Daniel Y. Fu, Stefano Ermon, Atri Rudra and Christopher Ré (2022). FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness
- SurveyNelson Elhage and collaborators (2021). A Mathematical Framework for Transformer Circuits
These works are cited as sources to read, not reproduced. All exposition, examples and problems on this site are written independently; where an argument is standard, the citation points to a canonical treatment.
Results stated on this page
- DefinitionScaled dot-product attentionA row-stochastic mixing of value vectors with weights given by a softmax over scaled query-key inner products.
- PropositionWhy the scaling is 1 over the square root of d_kproof includedAt random initialisation the logits have variance d_k, so dividing by its square root makes their scale independent of the head dimension.
- PropositionSoftmax saturation kills the gradientproof includedThe attention Jacobian is a variance under the attention distribution, which vanishes when the distribution is concentrated.
- PropositionAttention is permutation equivariantproof includedWithout positional information a transformer cannot distinguish orderings of its input, which is why positional encodings are required rather than optional.
- PropositionMulti-head attention is a sum of low-rank attention mapsproof includedEach head has rank at most d_k, so h heads give an attention operator that is a sum of h low-rank pieces rather than one full-rank piece.
- PropositionRotary embeddings make the logit depend only on relative positionproof includedRotating queries and keys by position-dependent angles makes their inner product a function of the position difference.
- PropositionComplexity of a transformer layerproof includedAttention costs n^2 d and the MLP costs n d^2, so the crossover is at sequence length comparable to the model width.
- HeuristicAttention as a kernel smootherSoftmax attention has the form of a Nadaraya-Watson estimator with an exponential kernel, a useful but incomplete analogy.
- Empirical observationPre-norm versus post-normPlacing layer normalisation before the sublayer makes deep transformers trainable without warmup; the reasons are partly understood.
Problems (7)
All problems- Why attention divides by the square root of d_kProofIntermediate⏱ 30 min
- When does attention dominate the MLP?NumericalBeginner⏱ 30 min
- Implement multi-head attention from scratchCodingIntermediate⏱ 3 hours
- Multi-head attention is a sum of low-rank mapsProofAdvanced⏱ 30 min
- Attention is permutation equivariantProofIntermediate⏱ 30 min
- Rotary embeddings encode relative position exactlyProofAdvanced⏱ 30 min
- The softmax Jacobian as a variance, and saturationProofIntermediate⏱ 30 min
Papers that use this mathematics
Attention Is All You Need
Vaswani, Shazeer, Parmar, Uszkoreit, Jones, Gomez, Kaiser, Polosukhin · 2017
LoRA: Low-Rank Adaptation of Large Language Models
Edward J. Hu, Yelong Shen, Phillip Wallis, Zeyuan Allen-Zhu, Yuanzhi Li, Shean Wang, Lu Wang, Weizhu Chen · 2021
Language Models are Few-Shot Learners
Tom B. Brown, Benjamin Mann, Nick Ryder, Melanie Subbiah, Jared Kaplan, Prafulla Dhariwal, Arvind Neelakantan, Pranav Shyam, Girish Sastry, Amanda Askell and others · 2020
BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding
Jacob Devlin, Ming-Wei Chang, Kenton Lee, Kristina Toutanova · 2019
Outrageously Large Neural Networks: The Sparsely-Gated Mixture-of-Experts Layer
Noam Shazeer, Azalia Mirhoseini, Krzysztof Maziarz, Andy Davis, Quoc Le, Geoffrey Hinton, Jeff Dean · 2017