Simple Algorithm
Artificial Intelligence · Deep Layer · 30 min

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 diag⁡(a)−aa⊤\diag(\mathbf a)-\mathbf a\mathbf a^\top is positive semidefinite with norm at most min⁡{12, 2(1−amax⁡)}\min\{\tfrac12,\,2(1-a_{\max})\}, and connect saturation to the dk\sqrt{d_k} 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

DerivationProof
  1. sj−T(log⁡pj+1)−λ=0⟹pj∝esj/Ts_j-T(\log p_j+1)-\lambda=0\quad\Longrightarrow\quad p_j\propto e^{s_j/T}

    The objective is strictly concave, because HH is, so the maximizer is unique; since ∂H/∂pj→+∞\partial H/\partial p_j\to+\infty as pj→0p_j\to0, it lies in the interior. Add a multiplier λ\lambda for ∑jpj=1\sum_jp_j=1 and set the gradient to zero:

  2. max⁡p∈Δn{⟨p,s⟩+T H(p)}=Tlog⁡∑jesj/T → T→0  max⁡jsj\max_{\mathbf p\in\Delta_n}\big\{\langle\mathbf p,\mathbf s\rangle+T\,H(\mathbf p)\big\}=T\log\sum_je^{s_j/T}\ \xrightarrow{\ T\to0\ }\ \max_js_j

    Normalizing gives the softmax. Substitute Tlog⁡pj=sj−Tlog⁡ZT\log p_j=s_j-T\log Z with Z=∑jesj/TZ=\sum_je^{s_j/T}: the linear term cancels and only the log-partition function survives, a smooth maximum of the scores.

  3. sparsemax⁡(s)=arg max⁡p∈Δn{⟨p,s⟩−12∥p∥22}=arg min⁡p∈Δn∥p−s∥22\operatorname{sparsemax}(\mathbf s)=\argmax_{\mathbf p\in\Delta_n}\big\{\langle\mathbf p,\mathbf s\rangle-\tfrac12\norm{\mathbf p}_2^2\big\}=\argmin_{\mathbf p\in\Delta_n}\norm{\mathbf p-\mathbf s}_2^2

    So attention chooses a distribution over positions that trades expected score against entropy, and dk\sqrt{d_k} 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

DerivationProof
  1. x⊤Jx=∑iaixi2−(∑iaixi)2=Var⁡a(x) ≥ 0\mathbf x^\top J\mathbf x=\sum_ia_ix_i^2-\Big(\sum_ia_ix_i\Big)^2=\Var_{\mathbf a}(\mathbf x)\ \ge\ 0

    Differentiating ai=esi/∑lesla_i=e^{s_i}/\sum_le^{s_l} gives Jij=ai(δij−aj)J_{ij}=a_i(\delta_{ij}-a_j). Its quadratic form is the variance of a random variable that takes the value xix_i with probability aia_i:

  2. λmax⁡(J)=max⁡∥x∥2=1Var⁡a(x)≤(M−m)24≤12\lambda_{\max}(J)=\max_{\norm{\mathbf x}_2=1}\Var_{\mathbf a}(\mathbf x)\le\frac{(M-m)^2}{4}\le\frac12

    A variable confined to [m,M][m,M] has variance at most (M−m)2/4(M-m)^2/4 (Popoviciu's inequality). For a unit vector x\mathbf x with largest and smallest coordinates MM and mm, (M−m)2≤2(M2+m2)≤2(M-m)^2\le2(M^2+m^2)\le2:

  3. Var⁡a(x)≤∑i≠i∗ai (xi−xi∗)2≤(1−amax⁡)⋅2∥x∥22\Var_{\mathbf a}(\mathbf x)\le\sum_{i\ne i^*}a_i\,(x_i-x_{i^*})^2\le(1-a_{\max})\cdot2\norm{\mathbf x}_2^2

    A variance is the smallest mean squared deviation from any constant. Take the constant xi∗x_{i^*} at the largest weight: only the other coordinates contribute, and they carry total weight 1−amax⁡1-a_{\max}:

  4. ∥∂ℓ∂s∥2≤2(1−amax⁡) ∥∂ℓ∂a∥2\Big\lVert\frac{\partial\ell}{\partial\mathbf s}\Big\rVert_2\le2(1-a_{\max})\,\Big\lVert\frac{\partial\ell}{\partial\mathbf a}\Big\rVert_2

    The bound is nearly tight: for two keys with score gap gg, JJ has eigenvalue 2σ(g)σ(−g)≈2e−g2\sigma(g)\sigma(-g)\approx2e^{-g}. The gradient that reaches the scores, ∂ℓ/∂s=J ∂ℓ/∂a\partial\ell/\partial\mathbf s=J\,\partial\ell/\partial\mathbf a, therefore shrinks exponentially in the gap.

Unscaled score gaps grow with the head size, like dk\sqrt{d_k} for random vectors and like dkd_k for aligned ones, and the theorem turns growing gaps into exponentially small gradients. The 1/dk1/\sqrt{d_k} 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).

Predict before you look

Two keys' scaled scores differ by g=1g=1. What is the Jacobian's nonzero eigenvalue 2σ(g)σ(−g)2\sigma(g)\sigma(-g), in percent?

Show the answer

39.3 %

σ(1)≈0.731\sigma(1)\approx0.731, so 2×0.731×0.269≈0.3932\times0.731\times0.269\approx0.393, close to the maximum 12\tfrac12. Without the scaling, at dk=128d_k=128, the same alignment gives a gap of 128≈11.3\sqrt{128}\approx11.3 and an eigenvalue of about 2.5×10−52.5\times10^{-5}: four orders of magnitude less gradient.

Heads, rank and circuits

DerivationProof
  1. log⁡A=S−c 1⊤⟹rank⁡(log⁡A)≤rank⁡S+1≤dk+1\log A=S-\mathbf c\,\mathbf 1^\top\quad\Longrightarrow\quad\rank(\log A)\le\rank S+1\le d_k+1

    The score matrix S=XWQWK⊤X⊤/dkS=XW_QW_K^\top X^\top/\sqrt{d_k} has rank at most dkd_k. A row-wise softmax subtracts each row's log-normalizer ci=log⁡∑jeSijc_i=\log\sum_je^{S_{ij}}:

  2. WQWK⊤=dk X+(log⁡P)(X+)⊤⟹S=XX+(log⁡P)(XX+)⊤=log⁡PW_QW_K^\top=\sqrt{d_k}\,X^+(\log P)(X^+)^\top\quad\Longrightarrow\quad S=XX^+(\log P)(XX^+)^\top=\log P

    For (b), softmax⁡rows(log⁡P)=P\softmax_{\text{rows}}(\log P)=P, so it suffices to make S=log⁡PS=\log P. Full row rank gives XX+=InXX^+=I_n for the pseudoinverse X+X^+. Choose

  3. dk=64≪n⟹rank⁡(log⁡A)≤65d_k=64\ll n\quad\Longrightarrow\quad\rank(\log A)\le65

    The chosen matrix has rank at most n≤dkn\le d_k, so it factors with d×dkd\times d_k factors. Full row rank needs d≥nd\ge n, so (b) covers only short sequences. At realistic lengths, thousands of tokens against dkd_k of 6464 to 128128, every head is confined to low-rank log-patterns.

Circuits. Writing multi-head attention as a sum over heads isolates two low-rank d×dd\times d matrices per head (Elhage et al., 2021): the QK circuit WQKr=WQr(WKr)⊤W_{QK}^r=W_Q^r(W_K^r)^\top, a bilinear form that decides where the head looks, and the OV circuit WOVr=WVrWOrW_{OV}^r=W_V^rW_O^r, which decides what it writes to the residual stream. Head rr contributes ArXWOVrA^rXW_{OV}^r with Ar=softmax⁡(XWQKrX⊤/dk)A^r=\softmax(XW_{QK}^rX^\top/\sqrt{d_k}): 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).

Check your understanding

A single head has dk=64d_k=64 and sees n=2048n=2048 tokens. Which pattern can it not produce, whatever its weights and input?

  1. The uniform pattern, with every weight 1/20481/2048
  2. A previous-token pattern whose scores are a sum of a few sinusoids in the offset j−ij-i
  3. A pattern in which every query puts most of its weight on the first token
  4. A generic positive row-stochastic matrix whose entrywise logarithm has rank 20482048
Show the answer

D. A generic positive row-stochastic matrix whose entrywise logarithm has rank 20482048

Its scores have rank at most 6464, so log⁡A\log A has rank at most 6565. The uniform pattern needs S=0S=0; a first-token sink needs S=c 1e1⊤S=c\,\mathbf 1\mathbf e_1^\top, rank one; and cos⁡ω(j−i)=cos⁡ωicos⁡ωj+sin⁡ωisin⁡ωj\cos\omega(j-i)=\cos\omega i\cos\omega j+\sin\omega i\sin\omega j 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 nn. By the lemma each position then contributes O(1/n)\order{1/n} to every attention output, and with Lipschitz layers, changing one input symbol moves the output by O(1/n)\order{1/n} at constant depth. PARITY flips with every bit, so such a model cannot keep a fixed margin: its cross-entropy tends to chance as n→∞n\to\infty (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 log⁡n\log n, 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 3L3^L-th power after LL 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 TC0\mathsf{TC}^0 (Reasoning in Language Models).

Key takeaways

  • Softmax is the entropy-regularized argmax, maximizing ⟨p,s⟩+TH(p)\langle\mathbf p,\mathbf s\rangle+TH(\mathbf p) over the simplex; attention is a kernel smoother with κ(q,k)=eq⊤k/dk\kappa(\mathbf q,\mathbf k)=e^{\mathbf q^\top\mathbf k/\sqrt{d_k}}.
  • The softmax Jacobian diag⁡(a)−aa⊤\diag(\mathbf a)-\mathbf a\mathbf a^\top is a covariance: positive semidefinite, norm at most 12\tfrac12 and at most 2(1−amax⁡)2(1-a_{\max}), so saturated heads pass almost no gradient; the 1/dk1/\sqrt{d_k} keeps initial gaps independent of head size.
  • One head's log-attention has rank at most dk+1d_k+1. 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 Θ(1/n)\Theta(1/n), 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.

Question 1

Which objective does softmax⁡(s/T)\softmax(\mathbf s/T) maximize over the probability simplex?

  1. ⟨p,s⟩−T∥p∥22\langle\mathbf p,\mathbf s\rangle-T\norm{\mathbf p}_2^2
  2. ⟨p,s⟩+T H(p)\langle\mathbf p,\mathbf s\rangle+T\,H(\mathbf p)
  3. H(p)H(\mathbf p) alone
  4. ⟨p,s⟩\langle\mathbf p,\mathbf s\rangle alone
Show the answer

B. ⟨p,s⟩+T H(p)\langle\mathbf p,\mathbf s\rangle+T\,H(\mathbf p)

Stationarity gives pj∝esj/Tp_j\propto e^{s_j/T}, and the optimal value is the smooth maximum Tlog⁡∑jesj/TT\log\sum_je^{s_j/T}.

Question 2

A query's attention has saturated, with amax⁡=0.999a_{\max}=0.999. What can you say about the gradient that reaches its scores?

  1. It is unchanged, since the softmax is 1-Lipschitz
  2. It is exactly zero
  3. Its norm is at most 0.0020.002 times that of the gradient with respect to the weights a\mathbf a
  4. It grows, since a confident head has a larger Jacobian
Show the answer

C. Its norm is at most 0.0020.002 times that of the gradient with respect to the weights a\mathbf a

∥J∥2≤2(1−amax⁡)=0.002\norm J_2\le2(1-a_{\max})=0.002, so ∥∂ℓ/∂s∥2≤0.002 ∥∂ℓ/∂a∥2\norm{\partial\ell/\partial\mathbf s}_2\le0.002\,\norm{\partial\ell/\partial\mathbf a}_2. Saturated heads learn slowly, which the 1/dk1/\sqrt{d_k} guards against at initialization.

Question 3

Why can one attention head with dk≪nd_k\ll n not express a generic attention pattern?

  1. Its scores XWQWK⊤X⊤/dkXW_QW_K^\top X^\top/\sqrt{d_k} have rank at most dkd_k, so log⁡A\log A has rank at most dk+1d_k+1
  2. The softmax cannot produce probabilities above 1/dk1/d_k
  3. Each query can attend to at most dkd_k keys
  4. The value vectors have only dkd_k dimensions
Show the answer

A. Its scores XWQWK⊤X⊤/dkXW_QW_K^\top X^\top/\sqrt{d_k} have rank at most dkd_k, so log⁡A\log A has rank at most dk+1d_k+1

A row-wise softmax subtracts one constant per row from the scores, which raises the rank by at most one.

Question 4

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 nn grows?

  1. It stays constant, since weights depend only on scores
  2. It can grow without bound
  3. It approaches the largest score
  4. It falls like 1/n1/n, by the dilution lemma
Show the answer

D. It falls like 1/n1/n, by the dilution lemma

With scores in [m,M][m,M] every weight is at most eM−m/ne^{M-m}/n. Keeping a key's weight fixed needs gaps that grow like log⁡n\log n, the motivation for scaling scores by log⁡n\log n.

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