The Mathematics of Attention
Scaled dot products, softmax and multi-head attention.
A transformer layer is a few lines of linear algebra, yet those lines hide real mathematics: a softmax that is a maximum-entropy choice, a Jacobian that vanishes when attention becomes confident, a rank ceiling on what one head can express, and a dilution effect that limits what soft attention can compute as inputs grow.
What you’ll learn
- Characterize softmax as the maximizer of an entropy-regularized linear objective, and attention as a kernel smoother.
- Prove that the softmax Jacobian is positive semidefinite with norm at most , and connect saturation to the scaling.
- Prove the low-rank bottleneck of a single head, and decompose multi-head attention into QK and OV circuits.
- State the dilution lemma for bounded scores and explain Hahn's limitation, rank collapse and their escape routes.
Softmax as a variational choice
The objective is strictly concave, because is, so the maximizer is unique; since as , it lies in the interior. Add a multiplier for and set the gradient to zero:
Normalizing gives the softmax. Substitute with : the linear term cancels and only the log-partition function survives, a smooth maximum of the scores.
So attention chooses a distribution over positions that trades expected score against entropy, and acts as the temperature of the raw dot products. Other regularizers give other attentions: a squared norm instead of the entropy gives sparsemax, the Euclidean projection onto the simplex, which assigns exact zeros (Martins & Astudillo, 2016).
Saturation: the Jacobian of softmax
Differentiating gives . Its quadratic form is the variance of a random variable that takes the value with probability :
A variable confined to has variance at most (Popoviciu's inequality). For a unit vector with largest and smallest coordinates and , :
A variance is the smallest mean squared deviation from any constant. Take the constant at the largest weight: only the other coordinates contribute, and they carry total weight :
The bound is nearly tight: for two keys with score gap , has eigenvalue . The gradient that reaches the scores, , therefore shrinks exponentially in the gap.
Unscaled score gaps grow with the head size, like for random vectors and like for aligned ones, and the theorem turns growing gaps into exponentially small gradients. The makes initial gaps, and so trainability, independent of head size. It does not stop logits from growing during training: at scale, runaway query–key logits and collapsing attention entropy cause loss spikes, countered by normalizing queries and keys (Dehghani et al., 2023) or reparametrizing the weights (Zhai et al., 2023).
Two keys' scaled scores differ by . What is the Jacobian's nonzero eigenvalue , in percent?
Show the answer
39.3 %
, so , close to the maximum . Without the scaling, at , the same alignment gives a gap of and an eigenvalue of about : four orders of magnitude less gradient.
Heads, rank and circuits
The score matrix has rank at most . A row-wise softmax subtracts each row's log-normalizer :
For (b), , so it suffices to make . Full row rank gives for the pseudoinverse . Choose
The chosen matrix has rank at most , so it factors with factors. Full row rank needs , so (b) covers only short sequences. At realistic lengths, thousands of tokens against of to , every head is confined to low-rank log-patterns.
Circuits. Writing multi-head attention as a sum over heads isolates two low-rank matrices per head (Elhage et al., 2021): the QK circuit , a bilinear form that decides where the head looks, and the OV circuit , which decides what it writes to the residual stream. Head contributes with : a linear map of the stream, gated by a pattern computed from the stream. Heads in different layers compose through the stream, since a later head can read an earlier head's output in its queries, keys or values. That is how induction heads form (In-Context Learning & Emergence).
A single head has and sees tokens. Which pattern can it not produce, whatever its weights and input?
- The uniform pattern, with every weight
- A previous-token pattern whose scores are a sum of a few sinusoids in the offset
- A pattern in which every query puts most of its weight on the first token
- A generic positive row-stochastic matrix whose entrywise logarithm has rank
Show the answer
D. A generic positive row-stochastic matrix whose entrywise logarithm has rank
Its scores have rank at most , so has rank at most . The uniform pattern needs ; a first-token sink needs , rank one; and has rank two per frequency. A full-rank log-pattern is out of reach.
What soft attention cannot do
Hahn's limitation. In a transformer with fixed weights, bounded embeddings and layer normalization keep every score in a fixed interval, independent of . By the lemma each position then contributes to every attention output, and with Lipschitz layers, changing one input symbol moves the output by at constant depth. PARITY flips with every bit, so such a model cannot keep a fixed margin: its cross-entropy tends to chance as (Hahn, 2020). The limit is on confidence, not on correctness. Chiang and Cholak (2022) built a transformer that recognizes PARITY exactly, used layer normalization to restore confidence, and found that scaling scores by , the growth the lemma demands, improves length generalization.
Rank collapse. Stack attention layers without residual connections or MLPs and all token representations converge to one shared vector doubly exponentially fast: the distance from rank one shrinks roughly like its -th power after layers (Dong, Cordonnier & Loukas, 2021). Skip connections and MLPs keep deep transformers from averaging everything away. On the positive side, with positional encodings transformers are universal approximators of continuous sequence-to-sequence functions on compact sets (Yun et al., 2020), and with hard attention and unbounded precision they are Turing complete (Pérez, Barceló & Marinković, 2021). With logarithmic precision and no chain of thought they lie in (Reasoning in Language Models).
Key takeaways
- Softmax is the entropy-regularized argmax, maximizing over the simplex; attention is a kernel smoother with .
- The softmax Jacobian is a covariance: positive semidefinite, norm at most and at most , so saturated heads pass almost no gradient; the keeps initial gaps independent of head size.
- One head's log-attention has rank at most . Multi-head attention is a sum of low-rank QK circuits (where to look) and OV circuits (what to write) that compose across layers.
- With bounded scores each weight is , which limits confident computation on long inputs such as PARITY (Hahn, 2020); pure attention stacks collapse to rank one, and residual connections prevent it.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
Which objective does maximize over the probability simplex?
- alone
- alone
Show the answer
B.
Stationarity gives , and the optimal value is the smooth maximum .
A query's attention has saturated, with . What can you say about the gradient that reaches its scores?
- It is unchanged, since the softmax is 1-Lipschitz
- It is exactly zero
- Its norm is at most times that of the gradient with respect to the weights
- It grows, since a confident head has a larger Jacobian
Show the answer
C. Its norm is at most times that of the gradient with respect to the weights
, so . Saturated heads learn slowly, which the guards against at initialization.
Why can one attention head with not express a generic attention pattern?
- Its scores have rank at most , so has rank at most
- The softmax cannot produce probabilities above
- Each query can attend to at most keys
- The value vectors have only dimensions
Show the answer
A. Its scores have rank at most , so has rank at most
A row-wise softmax subtracts one constant per row from the scores, which raises the rank by at most one.
In a fixed transformer whose scores stay in a bounded interval, what happens to the largest weight a single key can receive as the input length grows?
- It stays constant, since weights depend only on scores
- It can grow without bound
- It approaches the largest score
- It falls like , by the dilution lemma
Show the answer
D. It falls like , by the dilution lemma
With scores in every weight is at most . Keeping a key's weight fixed needs gaps that grow like , the motivation for scaling scores by .
Further reading
- S. Bhojanapalli, C. Yun, A. S. Rawat, S. J. Reddi & S. Kumar, "Low-rank bottleneck in multi-head attention models," ICML (2020).
- M. Hahn, "Theoretical limitations of self-attention in neural sequence models," TACL 8 (2020).
- Y. Dong, J.-B. Cordonnier & A. Loukas, "Attention is not all you need: Pure attention loses rank doubly exponentially with depth," ICML (2021).
- N. Elhage et al., "A mathematical framework for transformer circuits," Transformer Circuits Thread (2021).
- L. Strobl, W. Merrill, G. Weiss, D. Chiang & D. Angluin, "What formal languages can transformers express? A survey," TACL 12 (2024).