intermediate attention-transformers 40 min read

Attention as Kernel Smoothing

Softmax attention is the Nadaraya–Watson estimator with an exponential kernel: the temperature is a bandwidth whose trade-off is exact on the circle, the 1/√d scale keeps the kernel from collapsing into a lookup, and a weighted lookup over every earlier position reaches in one step what a recurrent state forgets

Overview & Motivation

The neural-language-models topic gave a recurrent network a long-lag task: read a bit, read 6060 noise symbols, then report the bit. At initialization the gradient that reaches the bit from the final loss is 2.45×10−102.45 \times 10^{-10} for an Elman network, because it passes through 6060 step Jacobians and its Theorem 5 says how fast their product shrinks. Give the same task to one layer of attention, which reads every earlier position directly, and the same census gives 3.76×10−53.76 \times 10^{-5}. Trained by the same protocol at lag 6060, the attention layer reports the bit correctly on every fresh sequence, at lag 6060 and at lag 600600.

That topic ended with a promise: attention replaces the recurrent state’s compression with a weighted lookup over every earlier position, and this topic reads that lookup as kernel smoothing. The reading is exact, and it explains the experiment above and several others.

  1. Attention is a kernel smoother. Softmax attention is the Nadaraya–Watson estimator of nonparametric regression, with the kernel e⟨q,k⟩/τe^{\langle q, k \rangle / \tau}. That kernel is a Gaussian in the distance between query and key, tilted toward long keys.
  2. The temperature is a bandwidth. At low temperature attention is a lookup, at high temperature an average. On keys spaced around a circle the smoother is a Fourier low-pass filter whose gains are ratios of Bessel functions, so its bias–variance trade-off is a closed form, and a trained attention layer finds its optimum.
  3. The 1/d1/\sqrt d scale keeps random dot products from saturating the softmax, whose Jacobian vanishes as it saturates.
  4. A lookup’s gradient takes one step. It is diluted by the number of positions competing for weight, not decayed through a product of Jacobians. Between lags 1010 and 480480 the gradient reaching the bit falls from 2.22×10−42.22 \times 10^{-4} to 4.88×10−64.88 \times 10^{-6} for attention, and from 1.88×10−41.88 \times 10^{-4} to 9.41×10−469.41 \times 10^{-46} for the Elman network.

Then the lookup goes to work on text. A kernel over a document’s own earlier words, mixed with the n-gram topic’s Kneser–Ney, reads across sentence boundaries that no earlier model on this site could see. On three real 10-K excerpts it cuts Kneser–Ney’s code from 5.6605.660 to 4.4984.498 bits per character, mostly by copying words the training text never contained, though lzma, at 2.9082.908, still codes them shorter.


A weighted lookup

Rows are tokens, as in the neural-language-models topic. The inputs x1,…,xn∈Rpx_1, \dots, x_n \in \mathbb{R}^p are mapped to queries qt=xtWQq_t = x_t W_Q, keys kj=xjWKk_j = x_j W_K in Rdk\mathbb{R}^{d_k}, and values vj=xjWVv_j = x_j W_V in Rdv\mathbb{R}^{d_v}. Position tt may read the positions Jt\mathcal{J}_t: all of them in bidirectional attention, and j≤tj \le t in causal attention, the kind a language model uses. Write Vmax⁡=max⁡j∥vj∥V_{\max} = \max_j \lVert v_j \rVert.

Before attention, there was regression. Given design points kjk_j and responses vjv_j, a kernel smoother predicts at a new point by averaging the responses, each weighted by how close its design point is.

Definition 1 (Kernel smoother).

For design points k1,…,knk_1, \dots, k_n, responses v1,…,vnv_1, \dots, v_n, and a positive kernel κ\kappa, the kernel smoother at qq is

m^(q)=∑jκ(q,kj) vj∑jκ(q,kj).\hat m(q) = \frac{\sum_j \kappa(q, k_j)\, v_j}{\sum_j \kappa(q, k_j)}.

With κ(q,k)=Kh(q−k)\kappa(q, k) = K_h(q - k), a scaled density of bandwidth hh, it is the Nadaraya–Watson estimator. With positive design weights ωj\omega_j, the kernel is ωjKh(q−kj)\omega_j K_h(q - k_j).

This is Nadaraya’s (1964) and Watson’s (1964) estimator, whose bias, variance, and optimal bandwidth formalML develops (Kernel Regression, its Definition 2 and Theorems 1–2).

Definition 2 (Scaled dot-product attention).

The scores are stj=⟨qt,kj⟩/τs_{tj} = \langle q_t, k_j \rangle / \tau, with temperature τ=dk\tau = \sqrt{d_k} unless stated, and the attention weights are αt=softmax⁡(st)\alpha_t = \operatorname{softmax}(s_t) over Jt\mathcal{J}_t. The output is ot=∑j∈Jtαtjvjo_t = \sum_{j \in \mathcal{J}_t} \alpha_{tj} v_j. In matrix form,

Attn⁡(Q,K,V)=softmax⁡ ⁣(QK⊤τ+B)V,\operatorname{Attn}(Q, K, V) = \operatorname{softmax}\!\Bigl(\frac{Q K^\top}{\tau} + B\Bigr) V,

row by row, where the mask BB is 00 on Jt\mathcal{J}_t and −∞-\infty off it.

Bahdanau, Cho, and Bengio (2015) introduced attention as a soft lookup over every source position. Vaswani and colleagues (2017) gave the scaled dot-product form. Put the two definitions side by side and the first proposition is nearly immediate. Its content is in what the kernel turns out to be.

Proposition 1 (Attention is a Nadaraya–Watson smoother).

(i) The output oto_t is Definition 1’s smoother at qtq_t, with the kernel κτ(q,k)=e⟨q,k⟩/τ\kappa_\tau(q, k) = e^{\langle q, k \rangle / \tau}, design points kjk_j, and responses vjv_j.

(ii) For all qq and kk,

e⟨q,k⟩/τ=e∥q∥2/2τ⋅e∥k∥2/2τ⋅e−∥q−k∥2/2τ.e^{\langle q, k \rangle / \tau} = e^{\lVert q \rVert^2 / 2\tau} \cdot e^{\lVert k \rVert^2 / 2\tau} \cdot e^{-\lVert q - k \rVert^2 / 2\tau}.

So oto_t is the Gaussian Nadaraya–Watson estimator with bandwidth h=τh = \sqrt\tau, which is dk1/4d_k^{1/4} at the default scale, and design weights ωj=e∥kj∥2/2τ\omega_j = e^{\lVert k_j \rVert^2 / 2\tau}.

(iii) If all keys have the same norm, oto_t is the unweighted Gaussian estimator. If queries and keys lie on a sphere of radius rr, the kernel is e(r2/τ)cos⁡∠(q,k)e^{(r^2/\tau)\cos\angle(q, k)}, the von Mises–Fisher kernel with concentration r2/τr^2/\tau.

(iv) oto_t lies in the convex hull of the values it reads, so ∥ot∥≤Vmax⁡\lVert o_t \rVert \le V_{\max}.

Proof.

Part (i) is the definition of the softmax: αtj=estj/∑iesti\alpha_{tj} = e^{s_{tj}} / \sum_i e^{s_{ti}}. Part (ii) is the polarization identity ∥q−k∥2=∥q∥2+∥k∥2−2⟨q,k⟩\lVert q - k \rVert^2 = \lVert q \rVert^2 + \lVert k \rVert^2 - 2\langle q, k \rangle, divided by −2τ-2\tau and exponentiated. The factor e∥q∥2/2τe^{\lVert q \rVert^2/2\tau} is the same for every key, so it cancels between the numerator and the denominator of Definition 1, and what remains is ωj\omega_j times a Gaussian kernel of variance τ\tau. Part (iii) follows because equal norms make every ωj\omega_j equal, and on the sphere ⟨q,k⟩=r2cos⁡∠(q,k)\langle q, k \rangle = r^2 \cos\angle(q, k). For (iv), the weights are positive and sum to 11.

∎

Tsai and colleagues (2019) read attention as a kernel smoother. The factorization in (ii) says which kernel smoother it is. The temperature sets a squared bandwidth, so the default bandwidth grows like dk1/4d_k^{1/4}. The keys’ lengths act as a design density: of two keys equally far from the query, the longer one gets exactly e(∥kj∥2−∥ki∥2)/2τe^{(\lVert k_j \rVert^2 - \lVert k_i \rVert^2)/2\tau} times the weight. On the sphere the kernel is the von Mises–Fisher one that formalRAG develops (Hypersphere and von Mises–Fisher Geometry, its Definition 1).

A kernel smoother is also a conditional mean. Put a Gaussian bump on every key and a point mass on every value, and attention computes the posterior.

Proposition 2 (The mixture posterior).

Let JJ take the value jj with probability πj∝ωj\pi_j \propto \omega_j, let Q∣J∼N(kJ,τI)Q \mid J \sim N(k_J, \tau I), and let V=vJV = v_J. Then

P(J=j∣Q=q)=αj(q)andE[V∣Q=q]=o(q).P(J = j \mid Q = q) = \alpha_j(q) \qquad \text{and} \qquad E[V \mid Q = q] = o(q).

Equivalently, oo is the conditional mean of VV under the joint law p^(q,v)=∑jπjφτ(q−kj) δvj(v)\hat p(q, v) = \sum_j \pi_j \varphi_\tau(q - k_j)\, \delta_{v_j}(v), a kernel density estimate in qq with point masses in vv, where φτ\varphi_\tau is the N(0,τI)N(0, \tau I) density.

Proof.

By Bayes’ rule, P(J=j∣Q=q)∝πjφτ(q−kj)∝ωje−∥q−kj∥2/2τP(J = j \mid Q = q) \propto \pi_j \varphi_\tau(q - k_j) \propto \omega_j e^{-\lVert q - k_j \rVert^2 / 2\tau}, and by Proposition 1 (ii) this is proportional to e⟨q,kj⟩/τe^{\langle q, k_j \rangle / \tau}, with a constant that does not depend on jj. Normalizing gives αj(q)\alpha_j(q). Then E[V∣Q=q]=∑jP(J=j∣Q=q) vj=o(q)E[V \mid Q = q] = \sum_j P(J = j \mid Q = q)\, v_j = o(q).

∎

The attention weights are the responsibilities of an isotropic Gaussian mixture whose means are the keys: one soft assignment of the query to a key, then the mean of the assigned values. Gabbur, Bilkhu, and Movellan (2021) give a probabilistic reading of dot-product attention along these lines. The joint p^\hat p has atoms in vv, so it is not a density. Its marginal in qq is a weighted kernel density estimate, a valid density by the argument formalStatistics gives for kernel density estimates (Kernel Density Estimation, its Theorem 1). The notebook checks the conditional mean the way it is defined: on 10510^5 draws from the mixture, the residual V−o(Q)V - o(Q) is uncorrelated with 11, Q1Q_1, and Q2Q_2, while the smoother that drops the design weights fails the same test.

A smoother averages over a set, and a set has no order. The next proposition is why the positional-encodings topic exists.

Proposition 3 (Order blindness).

(i) Bidirectional attention is permutation-equivariant: permuting the inputs permutes the outputs in the same way. So is any stack of bidirectional layers with position-wise maps between them.

(ii) In one causal layer, oto_t depends on x1,…,xt−1x_1, \dots, x_{t-1} only through their multiset. Two prefixes that rearrange the same tokens, followed by the same xtx_t, give the same output.

(iii) Two causal layers do not have property (ii).

Proof.

For (i), relabeling the positions relabels the scores, and the softmax and the sum over jj commute with relabeling; position-wise maps commute with it trivially. For (ii), the sum ∑j≤tαtjvj\sum_{j \le t} \alpha_{tj} v_j is a symmetric function of the pairs (kj,vj)(k_j, v_j) with j<tj \lt t, given qtq_t, ktk_t, and vtv_t. For (iii), the second layer at position tt reads the first layer’s outputs at j<tj \lt t, and each of those depends on its own prefix x1,…,xjx_1, \dots, x_j, which a rearrangement changes. The notebook exhibits a counterexample.

∎

At the last word, one causal layer without positions reads the dog bit the man today exactly as it reads the man bit the dog today. The last word has to match, because that is the xtx_t of (ii). The notebook reverses a corpus sentence’s prefix, good morning and welcome to the brightwater analytics, keeping its last word, and one random causal layer’s output at the last position is unchanged to rounding. Two layers differ by more than 10−310^{-3}, asserted. The causal mask itself leaks order, which is why causal language models trained without positional encodings still learn some (Haviv et al. 2022).


Temperature is bandwidth

Take one query and a fixed set of scores, and turn the temperature. At τ→0\tau \to 0 the weight piles onto the best-scoring key; at τ→∞\tau \to \infty it spreads evenly. Both limits come with rates.

Proposition 4 (The two temperature limits).

Fix raw scores sjs_j over a set J\mathcal{J} of nn positions, undivided by τ\tau, and let αj∝esj/τ\alpha_j \propto e^{s_j/\tau} and oτ=∑jαjvjo_\tau = \sum_j \alpha_j v_j. Let S∗S^* be the set of maximizers, Δ\Delta the gap between the maximum and the largest score off S∗S^*, and RR the range of the scores. Write vˉA\bar v_A for the mean of the values over AA. Then

∥oτ−vˉS∗∥≤2Vmax⁡(n−∣S∗∣)∣S∗∣e−Δ/τand∥oτ−vˉJ∥≤Vmax⁡(eR/τ−1).\lVert o_\tau - \bar v_{S^*} \rVert \le \frac{2 V_{\max} (n - \lvert S^* \rvert)}{\lvert S^* \rvert} e^{-\Delta/\tau} \qquad \text{and} \qquad \lVert o_\tau - \bar v_{\mathcal{J}} \rVert \le V_{\max}\bigl(e^{R/\tau} - 1\bigr).
Proof.

For the first bound, every weight on S∗S^* is the same, and each weight off S∗S^* is at most e−Δ/τe^{-\Delta/\tau} times it, so the mass off S∗S^* is ε≤(n−∣S∗∣)e−Δ/τ/∣S∗∣\varepsilon \le (n - \lvert S^* \rvert) e^{-\Delta/\tau} / \lvert S^* \rvert. The weights on S∗S^* are then (1−ε)/∣S∗∣(1 - \varepsilon)/\lvert S^* \rvert each, so oτ−vˉS∗=∑j∉S∗αj(vj−vˉS∗)o_\tau - \bar v_{S^*} = \sum_{j \notin S^*} \alpha_j (v_j - \bar v_{S^*}), whose norm is at most 2Vmax⁡ε2 V_{\max} \varepsilon. For the second, nαj=esj/τ/(1n∑iesi/τ)n \alpha_j = e^{s_j/\tau} / \bigl(\tfrac1n \sum_i e^{s_i/\tau}\bigr) lies in [e−R/τ,eR/τ][e^{-R/\tau}, e^{R/\tau}], so ∣αj−1/n∣≤(eR/τ−1)/n\lvert \alpha_j - 1/n \rvert \le (e^{R/\tau} - 1)/n, and ∥oτ−vˉJ∥=∥∑j(αj−1/n)vj∥≤Vmax⁡(eR/τ−1)\lVert o_\tau - \bar v_{\mathcal{J}} \rVert = \lVert \sum_j (\alpha_j - 1/n) v_j \rVert \le V_{\max}(e^{R/\tau} - 1).

∎

The first limit is retrieval: when the best key is separated from the rest, attention returns its value with an error exponentially small in the gap. That is the one-step retrieval of Ramsauer and colleagues’ (2021) modern Hopfield networks, and its zero-temperature end is the MaxSim lookup of late-interaction retrieval in formalRAG. The second limit is a bag-of-values average. Between them lies the bandwidth.

How should the bandwidth be set? formalML answers for the Nadaraya–Watson estimator asymptotically: bias of order h2h^2, variance of order 1/(nh)1/(nh), and an optimal bandwidth of order n−1/5n^{-1/5} in one dimension. For attention there is a setting where the answer is exact at every nn. Place nn keys at equally spaced angles around a circle, which is what a sinusoidal positional encoding of a single frequency does.

Theorem 1 (Attention on the circle is a Fourier multiplier).

Let θj=θ0+2πj/n\theta_j = \theta_0 + 2\pi j/n for j=0,…,n−1j = 0, \dots, n - 1, give every token the features u(θ)=(cos⁡θ,sin⁡θ)u(\theta) = (\cos\theta, \sin\theta) for its query and key, and let the scores be sij=ccos⁡(θi−θj)s_{ij} = c \cos(\theta_i - \theta_j) with c≥0c \ge 0. Let the values be yj=f(θj)+εjy_j = f(\theta_j) + \varepsilon_j, with the εj\varepsilon_j independent of mean 00 and variance σ2\sigma^2. Let AA be the bidirectional attention matrix, and Fk=1n∑jf(θj)e−ikθjF_k = \frac1n \sum_j f(\theta_j) e^{-ik\theta_j} the discrete Fourier coefficients of ff.

(i) AA is circulant. The Fourier vectors (eikθj)j(e^{ik\theta_j})_j are its eigenvectors, with eigenvalues

ρk(c)=∑m≡k (mod n)Im(c)∑m≡0 (mod n)Im(c),\rho_k(c) = \frac{\sum_{m \equiv k \ (\mathrm{mod}\ n)} I_m(c)}{\sum_{m \equiv 0 \ (\mathrm{mod}\ n)} I_m(c)},

where ImI_m is the modified Bessel function of the first kind. For c>0c \gt 0, 0<ρk<1=ρ00 \lt \rho_k \lt 1 = \rho_0 for every k≢0k \not\equiv 0; at c=0c = 0, ρk=0\rho_k = 0.

(ii) The exact risk at the design points is

R(c)=1n∑iE(oi−f(θi))2=∑k=0n−1(1−ρk(c))2∣Fk∣2+σ2 ∑m≡0Im(2c)n(∑m≡0Im(c))2.R(c) = \frac1n \sum_i E\bigl(o_i - f(\theta_i)\bigr)^2 = \sum_{k=0}^{n-1} \bigl(1 - \rho_k(c)\bigr)^2 \lvert F_k \rvert^2 + \sigma^2\, \frac{\sum_{m \equiv 0} I_m(2c)}{n \bigl(\sum_{m \equiv 0} I_m(c)\bigr)^2}.
Proof.

The score ccos⁡(θi−θj)c\cos(\theta_i - \theta_j) depends only on j−ij - i modulo nn, so Aij=a(j−i) mod nA_{ij} = a_{(j - i) \bmod n} with am=eccos⁡(2πm/n)/Za_m = e^{c\cos(2\pi m/n)}/Z and Z=∑meccos⁡(2πm/n)Z = \sum_m e^{c\cos(2\pi m/n)}: AA is circulant. Applied to e(k)=(eikθj)je^{(k)} = (e^{ik\theta_j})_j, it gives (Ae(k))i=eikθi∑mame2πikm/n(A e^{(k)})_i = e^{ik\theta_i} \sum_m a_m e^{2\pi i k m/n}. The generating function eccos⁡φ=∑l∈ZIl(c)eilφe^{c\cos\varphi} = \sum_{l \in \mathbb{Z}} I_l(c) e^{il\varphi} (DLMF 10.35.1), summed over the nn angles φ=2πm/n\varphi = 2\pi m/n, keeps exactly the terms with l+k≡0(modn)l + k \equiv 0 \pmod n:

∑m=0n−1eccos⁡(2πm/n)e2πikm/n=n∑l≡−kIl(c)=n∑l≡kIl(c),\sum_{m=0}^{n-1} e^{c\cos(2\pi m/n)} e^{2\pi i k m/n} = n \sum_{l \equiv -k} I_l(c) = n \sum_{l \equiv k} I_l(c),

since I−l=IlI_{-l} = I_l. The normalizer ZZ is the case k=0k = 0, which gives the formula in (i). For c>0c \gt 0 every Il(c)I_l(c) is positive, so ρk>0\rho_k \gt 0. Because aa is symmetric, ρk=∑mamcos⁡(2πkm/n)≤∑mam=1\rho_k = \sum_m a_m \cos(2\pi k m/n) \le \sum_m a_m = 1, with equality only if cos⁡(2πkm/n)=1\cos(2\pi k m/n) = 1 for every mm, that is, k≡0k \equiv 0. At c=0c = 0, Il(0)=0I_l(0) = 0 for l≠0l \ne 0.

For (ii), split the error into bias and noise. The mean output is AfAf, and in the Fourier basis Af−f=∑k(ρk−1)Fke(k)Af - f = \sum_k (\rho_k - 1) F_k e^{(k)}. The vectors e(k)e^{(k)} are orthogonal with squared norm nn, so by the discrete form of Parseval’s identity 1n∥Af−f∥2=∑k(1−ρk)2∣Fk∣2\frac1n \lVert Af - f \rVert^2 = \sum_k (1 - \rho_k)^2 \lvert F_k \rvert^2. The noise contributes 1nE∥Aε∥2=σ2ntr⁡(A⊤A)=σ2∑mam2\frac1n E\lVert A\varepsilon \rVert^2 = \frac{\sigma^2}{n} \operatorname{tr}(A^\top A) = \sigma^2 \sum_m a_m^2, since every row of AA is a rotation of aa. Finally ∑mam2=Z−2∑me2ccos⁡(2πm/n)\sum_m a_m^2 = Z^{-2} \sum_m e^{2c\cos(2\pi m/n)}, which is the generating-function sum at 2c2c with k=0k = 0.

∎

With one frequency of position, attention is a low-pass filter. The Fourier mode kk keeps the fraction ρk\rho_k of its amplitude, and once nn is large enough that the aliased terms vanish, ρk=Ik(c)/I0(c)\rho_k = I_k(c)/I_0(c); at n=64n = 64 and c=7.3c = 7.3 the first six gains are 0.9290.929, 0.7460.746, 0.5200.520, 0.3180.318, 0.1720.172, and 0.0830.083. The first gain I1(c)/I0(c)I_1(c)/I_0(c) is formalRAG’s mean resultant length of the von Mises–Fisher distribution on the circle (its Proposition 2), and the Bessel normalizer is its Theorem 2. Raising cc, which lowers the temperature, opens the filter: less bias, more noise. This is the trade-off formalML derives asymptotically for kernel regression, here as a closed form at every nn, and it rests on the orthogonality and Parseval’s identity of formalCalculus (Fourier Series & Orthogonal Expansions). The notebook checks (i) against numpy’s FFT on a grid of nn and cc, to 10−1210^{-12}, and (ii) against simulated noise.

Corollary 1 (The bandwidth rate).

For a fixed nonconstant trigonometric polynomial ff, write Pk=∣Fk∣2+∣F−k∣2P_k = \lvert F_k \rvert^2 + \lvert F_{-k} \rvert^2 for its power at frequency k≥1k \ge 1, and B=14∑kk4PkB = \tfrac14 \sum_k k^4 P_k. The risk-minimizing c∗(n)c^*(n) satisfies

c∗(n)∼(4Bnσ2π)2/5c^*(n) \sim \Bigl(\frac{4 B n}{\sigma^2 \sqrt\pi}\Bigr)^{2/5}

as n→∞n \to \infty. So the angular bandwidth 1/c∗1/\sqrt{c^*} is of order n−1/5n^{-1/5}, and the optimal risk is of order n−4/5n^{-4/5}, the rate of kernel regression in one dimension.

Proof.

The large-argument expansion Iν(c)=ec2πc(1−4ν2−18c+O(c−2))I_\nu(c) = \frac{e^c}{\sqrt{2\pi c}}\bigl(1 - \frac{4\nu^2 - 1}{8c} + O(c^{-2})\bigr) (DLMF 10.40.1) gives Ik(c)/I0(c)=1−k2/(2c)+O(c−2)I_k(c)/I_0(c) = 1 - k^2/(2c) + O(c^{-2}) and I0(2c)/I0(c)2=πc (1+O(c−1))I_0(2c)/I_0(c)^2 = \sqrt{\pi c}\,\bigl(1 + O(c^{-1})\bigr). The aliased terms Ik+mn(c)I_{k + mn}(c) with m≠0m \ne 0 are smaller than Ik(c)I_k(c) by about e−n2/2ce^{-n^2/2c}. That is not always tiny: at n=1,000n = 1{,}000 and c=n2/log⁡nc = n^2/\log n it is about 0.030.03. But it vanishes while c=o(n2)c = o(n^2). So do the errors it causes: in 1−ρk1 - \rho_k the leading aliased terms nearly cancel, leaving a relative error of order (n2/c)e−n2/2c(n^2/c) e^{-n^2/2c}, and the sum at 2c2c has a relative error of order e−n2/4ce^{-n^2/4c}. So, uniformly as c→∞c \to \infty with c=o(n2)c = o(n^2),

R(c)=Bc2+σ2πcn+o(1c2+cn).R(c) = \frac{B}{c^2} + \frac{\sigma^2 \sqrt{\pi c}}{n} + o\Bigl(\frac{1}{c^2} + \frac{\sqrt c}{n}\Bigr).

This expansion applies at the optimum. For bounded cc the bias term is bounded away from 00, while R(n2/5)→0R(n^{2/5}) \to 0, so c∗(n)→∞c^*(n) \to \infty. And cc of order n2n^2 keeps the variance term bounded away from 00. Fix ε>0\varepsilon \gt 0 and take c≥εn2c \ge \varepsilon n^2. Numbering the positions so that ∣m∣≤n/2\lvert m \rvert \le n/2, the bound 1−cos⁡x≥2x2/π21 - \cos x \ge 2x^2/\pi^2 on [−π,π][-\pi, \pi] gives

1a0=∑me−c(1−cos⁡(2πm/n))≤∑m∈Ze−8εm2=Aε<∞,\frac{1}{a_0} = \sum_m e^{-c(1 - \cos(2\pi m/n))} \le \sum_{m \in \mathbb{Z}} e^{-8\varepsilon m^2} = A_\varepsilon \lt \infty,

so the variance term σ2∑mam2\sigma^2 \sum_m a_m^2 is at least σ2/Aε2\sigma^2 / A_\varepsilon^2. So c∗=o(n2)c^* = o(n^2).

Write L(c)L(c) for the two leading terms. Setting its derivative to zero gives its minimizer c0c_0, with c05/2=4Bn/(σ2π)c_0^{5/2} = 4Bn/(\sigma^2\sqrt\pi), and L(tc0)=L(c0)(t−2+4t)/5L(t c_0) = L(c_0)(t^{-2} + 4\sqrt t)/5, which falls on (0,1)(0, 1) and rises on (1,∞)(1, \infty). Since R=L⋅(1+o(1))R = L \cdot (1 + o(1)) uniformly on the range that holds both c∗c^* and c0c_0, the inequality R(c∗)≤R(c0)R(c^*) \le R(c_0) forces c∗/c0→1c^*/c_0 \to 1.

∎

The asymptote is approached quickly. Two spectra are used below: a smooth one, with random Fourier coefficients of variance 11 at frequency 11 and 14\tfrac14 at frequency 22, and a rough one, with variance 14\tfrac14 at each of the frequencies 11 through 66, both with noise σ=12\sigma = \tfrac12. Computed from Theorem 1’s exact formula, the ratio c∗(n)/(Cn2/5)c^*(n)/(Cn^{2/5}), where C=(4B/σ2π)2/5C = (4B/\sigma^2\sqrt\pi)^{2/5}, is:

spectrumCCn=32n = 3264641281281,0241{,}02410610^610810^8
smooth2.6362.6360.9490.9490.9620.9620.9720.9720.9880.9880.99930.99930.99990.9999
rough17.51317.5130.8160.8160.9060.9060.9290.9290.9700.9700.99810.99810.99970.9997

Between n=106n = 10^6 and 10810^8 the log–log slope of c∗c^* is 0.40010.4001 for the smooth spectrum and 0.40030.4003 for the rough one.

Does a trained attention layer find this optimum? Collins and colleagues (2024) prove that a softmax attention unit trained on regression tasks learns a window that narrows as the tasks’ functions grow less smooth and widens with label noise. Here the optimum is known exactly. One attention layer reads the tokens (cos⁡θj,sin⁡θj,yj)(\cos\theta_j, \sin\theta_j, y_j); its queries and keys see the position only, so its scores are u(θi)Mu(θj)⊤u(\theta_i) M u(\theta_j)^\top with M=WQWK⊤/2M = W_Q W_K^\top/\sqrt2, and its values are the yjy_j. Adam trains it on fresh random functions from one spectrum, at random rotations θ0\theta_0, to minimize the squared error against the clean ff. The task distribution is invariant under rotations and reflections, which points to a population optimum of M=c∗IM = c^* I, with c∗c^* from Theorem 1. Invariance alone doesn’t prove that, since a symmetric objective can have asymmetric minimizers. So the harness searches: it minimizes the exact population risk over all 2×22 \times 2 matrices MM, from one isotropic and five random starts, for each row below, and every search ends within 0.1%0.1\% of c∗Ic^* I, at Theorem 1’s risk to 10−610^{-6}. That is numerical evidence, not a proof that the minimum is global.

spectrum, nnlearned ccTheorem 1’s c∗c^*∥M−c∗I∥/∥c∗I∥\lVert M - c^* I \rVert / \lVert c^* I \rVertR(c∗)R(c^*)
smooth, 323210.00610.00610.01110.0110.12%0.12\%0.05460.0546
smooth, 646413.32013.32013.39113.3910.53%0.53\%0.03160.0316
rough, 323257.20157.20157.13057.1300.13%0.13\%0.14050.1405

Here MM is the average over the second half of training, and the learned cc is half its trace. The trained layer lands within 0.53%0.53\% of the theorem’s optimum at worst, from a start near uniform attention. That worst case is nearly all the miss in cc itself, 0.525%0.525\% of c∗c^*. Anisotropy is a separate and smaller effect: ∥M−cI∥/∥M∥\lVert M - cI \rVert / \lVert M \rVert is at most 0.11%0.11\%. The layer learns a kernel more than five times sharper for the rough functions than for the smooth ones, and a sharper one for the longer context.


Why 1/d1/\sqrt d

The temperature of Definition 2 is not a tuned constant but dk\sqrt{d_k}. Vaswani and colleagues gave the reason in a footnote: dot products of random vectors grow with the dimension, and large scores push the softmax into a region with tiny gradients. Both halves can be made exact.

Theorem 2 (Why 1/√d).

(i) If qq and kk are independent with i.i.d. coordinates of mean 00 and variance 11, then E⟨q,k⟩=0E\langle q, k \rangle = 0 and Var⁡⟨q,k⟩=d\operatorname{Var}\langle q, k \rangle = d.

(ii) The softmax Jacobian J=diag⁡(α)−αα⊤J = \operatorname{diag}(\alpha) - \alpha\alpha^\top satisfies

∥J∥2≤tr⁡J=1−∥α∥2≤2(1−αmax⁡).\lVert J \rVert_2 \le \operatorname{tr} J = 1 - \lVert \alpha \rVert^2 \le 2(1 - \alpha_{\max}).

(iii) Let q∼N(0,Id)q \sim N(0, I_d), and let k1,…,knk_1, \dots, k_n be i.i.d. N(0,Id)N(0, I_d), independent of qq, with n≥2n \ge 2 fixed. For the unscaled scores ⟨q,kj⟩\langle q, k_j \rangle, 1−αmax⁡→01 - \alpha_{\max} \to 0 in probability as d→∞d \to \infty. For the scaled scores ⟨q,kj⟩/d\langle q, k_j \rangle/\sqrt d, α\alpha converges in distribution to softmax⁡(g)\operatorname{softmax}(g), with g1,…,gng_1, \dots, g_n i.i.d. standard normal.

Proof.

For (i), ⟨q,k⟩=∑iqiki\langle q, k \rangle = \sum_i q_i k_i is a sum of dd independent terms of mean 00 and variance Eqi2 Eki2=1E q_i^2\, E k_i^2 = 1. For (ii), JJ is the covariance of the one-hot vector of a draw from α\alpha (the neural-language-models topic’s Proposition 2), so it is positive semidefinite, and its largest eigenvalue is at most its trace, ∑jαj(1−αj)=1−∥α∥2\sum_j \alpha_j(1 - \alpha_j) = 1 - \lVert \alpha \rVert^2. And 1−∥α∥2≤1−αmax⁡2=(1−αmax⁡)(1+αmax⁡)1 - \lVert \alpha \rVert^2 \le 1 - \alpha_{\max}^2 = (1 - \alpha_{\max})(1 + \alpha_{\max}).

For (iii), condition on qq. The scores ⟨q,kj⟩\langle q, k_j \rangle are then i.i.d. N(0,∥q∥2)N(0, \lVert q \rVert^2), which is the law of ∥q∥gj\lVert q \rVert g_j with gg i.i.d. standard normal and independent of qq. If G>0G \gt 0 is the gap between the two largest gjg_j, every non-maximal weight is at most e−∥q∥Ge^{-\lVert q \rVert G} times the largest, so 1−αmax⁡≤(n−1)e−∥q∥G1 - \alpha_{\max} \le (n - 1) e^{-\lVert q \rVert G}. Fix ε∈(0,1)\varepsilon \in (0, 1) and let a=log⁡(n/ε)a = \log(n/\varepsilon). Then 1−αmax⁡>ε1 - \alpha_{\max} \gt \varepsilon forces ∥q∥G<a\lVert q \rVert G \lt a, so for every M>0M \gt 0,

P(1−αmax⁡>ε)≤P(∥q∥<M)+P(G<a/M).P(1 - \alpha_{\max} \gt \varepsilon) \le P(\lVert q \rVert \lt M) + P(G \lt a/M).

By the law of large numbers ∥q∥2/d→1\lVert q \rVert^2 / d \to 1 in probability, so the first term tends to 00 for each MM. The gap GG has the same law at every dd, and G>0G \gt 0 almost surely, so the second term is as small as we like for large MM. Scaled, the scores have the law of (∥q∥/d) g(\lVert q \rVert/\sqrt d)\, g. The factor tends to 11 in probability, so by Slutsky’s theorem and the continuity of the softmax, α\alpha converges in distribution to softmax⁡(g)\operatorname{softmax}(g).

∎

Part (iii) stops at convergence in probability for a reason. The keys change with dd, and the theorem states no coupling across dimensions. With n=2n = 2, 1−αmax⁡=1/(1+e∣Sd∣)1 - \alpha_{\max} = 1/(1 + e^{\lvert S_d \rvert}) with Sd=⟨q,k1−k2⟩S_d = \langle q, k_1 - k_2 \rangle. If the draws are nested, one coordinate added at each dd, then SdS_d is a recurrent random walk. If they are independent across dd, then P(∣Sd∣<1)P(\lvert S_d \rvert \lt 1) is of order 1/d1/\sqrt d, whose sum diverges, so the Borel–Cantelli lemma applies. Either way ∣Sd∣<1\lvert S_d \rvert \lt 1 infinitely often, almost surely, and then 1−αmax⁡>1/(1+e)1 - \alpha_{\max} \gt 1/(1 + e): almost sure convergence fails.

Without the scale, the kernel’s bandwidth shrinks like d−1/2d^{-1/2} in units of the scores, attention collapses into a lookup at initialization, and by (ii) the gradient through the scores vanishes with it. The neural-language-models topic’s covariance identity, there a fact about the output layer, is here a cost. With 1616 keys, mean 1−αmax⁡1 - \alpha_{\max} and mean ∥J∥2\lVert J \rVert_2 over 600600 random draws at each dimension are:

dd44161664642562561,0241{,}024
1−αmax⁡1 - \alpha_{\max}, unscaled0.5710.5710.3090.3090.1390.1390.0730.0730.0410.041
1−αmax⁡1 - \alpha_{\max}, scaled0.7660.7660.7550.7550.7480.7480.7510.7510.7590.759
∥J∥2\lVert J \rVert_2, unscaled0.2570.2570.2500.2500.1570.1570.0930.0930.0560.056
∥J∥2\lVert J \rVert_2, scaled0.1920.1920.2030.2030.2080.2080.2070.2070.2030.203

A lookup instead of a state

The neural-language-models topic’s Theorem 5 bounds the gradient that reaches state kk from the loss at step tt by a product of t−kt - k step Jacobians. Attention has no such product.

Proposition 5 (One hop).

In one causal layer, for k<tk \lt t,

∂ot∂xk=αtk[WV+τ−1(WKqt)⊗(vk−ot)],\frac{\partial o_t}{\partial x_k} = \alpha_{tk} \Bigl[ W_V + \tau^{-1} (W_K q_t) \otimes (v_k - o_t) \Bigr],

acting on row perturbations of xkx_k, where (a⊗b)(a \otimes b) is the outer product ab⊤a b^\top. Hence

∥∂ot∂xk∥≤αtk(∥WV∥+τ−1∥WK∥∥qt∥∥vk−ot∥).\Bigl\lVert \frac{\partial o_t}{\partial x_k} \Bigr\rVert \le \alpha_{tk} \Bigl( \lVert W_V \rVert + \tau^{-1} \lVert W_K \rVert \lVert q_t \rVert \lVert v_k - o_t \rVert \Bigr).

When all scores are equal, αtk=1/(t+1)\alpha_{tk} = 1/(t + 1) for positions numbered from 00.

Proof.

For k<tk \lt t, xkx_k enters ot=∑jαtjvjo_t = \sum_j \alpha_{tj} v_j in two places: through vk=xkWVv_k = x_k W_V, and through the score stk=⟨qt,xkWK⟩/τs_{tk} = \langle q_t, x_k W_K \rangle / \tau, since qtq_t depends on xtx_t alone. The first contributes αtkWV\alpha_{tk} W_V. For the second, the softmax gives ∂αtj/∂stk=αtj(δjk−αtk)\partial \alpha_{tj} / \partial s_{tk} = \alpha_{tj}(\delta_{jk} - \alpha_{tk}), so ∂ot/∂stk=αtk(vk−ot)\partial o_t / \partial s_{tk} = \alpha_{tk}(v_k - o_t), and ∂stk/∂xk=WKqt/τ\partial s_{tk} / \partial x_k = W_K q_t / \tau. The bound follows from the triangle inequality and ∥ab⊤∥=∥a∥∥b∥\lVert a b^\top \rVert = \lVert a \rVert \lVert b \rVert.

∎

The lookup’s path from tt back to kk has length one. Its only loss is the factor αtk\alpha_{tk}, a dilution by the positions competing for weight, and the scores can undo it by concentrating the weight. That is what “replaces the compression with a weighted lookup” means as a derivative. The long-lag task shows it.

Proposition 6 (Content addressing solves the lag task).

In the neural-language-models topic’s task, the input is x0∈{0,1}x_0 \in \{0, 1\}, then LL noise symbols drawn from {2,3}\{2, 3\}, and the target is x0x_0. Take one causal layer read at the last position, with one-hot inputs, equal scores, values +1+1 for the symbol 00, −1-1 for the symbol 11, and 00 for noise, and logits (w o,−w o)(w\, o, -w\, o) with w>0w \gt 0. Then

o=1−2x0L+1,o = \frac{1 - 2x_0}{L + 1},

the prediction is correct for every LL, and the cross-entropy is log⁡(1+e−2w/(L+1))\log\bigl(1 + e^{-2w/(L + 1)}\bigr), which tends to 00 as w→∞w \to \infty. Keys that score the bit symbols β\beta above the noise raise the margin to eβ/(eβ+L)e^\beta / (e^\beta + L).

Proof.

With equal scores every one of the L+1L + 1 positions gets weight 1/(L+1)1/(L + 1), and only position 00 has a nonzero value, 1−2x01 - 2x_0. The logits are ±w(1−2x0)/(L+1)\pm w(1 - 2x_0)/(L + 1), whose sign picks x0x_0, and the cross-entropy of the correct class is log⁡(1+e−2w/(L+1))\log(1 + e^{-2w/(L+1)}). With the bit’s score raised by β\beta, its weight is eβ/(eβ+L)e^\beta/(e^\beta + L).

∎

The bit symbols differ from the noise symbols, so the layer can find the bit by content alone, with no notion of position; the honest caveats return to this. The census below repeats the neural-language-models topic’s protocol: the norm of the gradient of the batch-mean loss reaching the bit’s own representation, at initialization, the median over 1212 initializations on batches of 256256. The recurrent rows at lag 6060 are that topic’s own census, re-run.

lag LL101030306060120120240240480480
attention2.22×10−42.22 \times 10^{-4}5.71×10−55.71 \times 10^{-5}3.76×10−53.76 \times 10^{-5}2.77×10−52.77 \times 10^{-5}9.81×10−69.81 \times 10^{-6}4.88×10−64.88 \times 10^{-6}
Elman1.88×10−41.88 \times 10^{-4}2.78×10−72.78 \times 10^{-7}2.45×10−102.45 \times 10^{-10}1.37×10−151.37 \times 10^{-15}1.87×10−331.87 \times 10^{-33}9.41×10−469.41 \times 10^{-46}
LSTM, forget bias 111.98×10−41.98 \times 10^{-4}3.28×10−53.28 \times 10^{-5}2.42×10−72.42 \times 10^{-7}3.35×10−113.35 \times 10^{-11}1.73×10−161.73 \times 10^{-16}1.83×10−311.83 \times 10^{-31}
LSTM, forget bias 331.12×10−31.12 \times 10^{-3}8.73×10−48.73 \times 10^{-4}1.42×10−31.42 \times 10^{-3}2.36×10−42.36 \times 10^{-4}1.51×10−41.51 \times 10^{-4}1.29×10−71.29 \times 10^{-7}

Attention’s gradient times L+1L + 1 stays between 1.77×10−31.77 \times 10^{-3} and 3.35×10−33.35 \times 10^{-3} across the whole range: dilution, roughly 1/(L+1)1/(L + 1), the equal-score case of Proposition 5. The scores at initialization are not exactly equal, so the match is only rough. The Elman network’s falls by 4141 orders of magnitude. The LSTM with forget bias 33 is ahead of attention at lag 6060, because its cell path damps the bit far less, keeping σ(3)60=0.054\sigma(3)^{60} = 0.054 of it over that lag (that topic’s Proposition 4). But its gradient still falls, unevenly from lag to lag, and by lag 480480 attention has overtaken it. A forget gate postpones the decay; a lookup has none.

Trained by the same protocol, 600600 Adam steps at lag 6060, the attention layer answers all 2,0002{,}000 fresh test sequences correctly, at a test loss of 3.0×10−63.0 \times 10^{-6}. That topic reported 0.4860.486 for the Elman network, 0.5310.531 for the LSTM with forget bias 11, and 1.0001.000 with forget bias 33. The attention layer also answers every sequence correctly at lag 600600, ten times the lag it was trained on: a lookup never counted the steps.


Attention over a document

The recurrent network of the neural-language-models topic reset its state at every sentence, and Kneser–Ney never looks past two words. Neither can use the fact that a company named in one sentence is likely to be named again three sentences later. A lookup over the whole document can. To see what such a lookup buys on text, before any training, take its keys from fixed word vectors.

Definition 3 (Kernel cache).

A document’s predicted positions, numbered from 00, run across its sentences in the n-gram topic’s order: each word, then each sentence’s end marker. Position tt has the target wtw_t and the preceding token utu_t, which is the sentence-start marker at the start of a sentence. Its key e^(ut)\hat e(u_t) is the unit vector of utu_t in the distributional-semantics topic’s truncated SVD (positive PMI shifted by log⁡5\log 5, a two-word window, d=100d = 100), with one extra coordinate for the sentence-start marker and one for each distinct out-of-vocabulary string. The kernel cache with inverse bandwidth β≥0\beta \ge 0 is

pβ(w∣t)=∑i<tαti 1[wi=w],αti∝exp⁡(β⟨e^(ut),e^(ui)⟩),p_\beta(w \mid t) = \sum_{i \lt t} \alpha_{ti}\, \mathbb{1}[w_i = w], \qquad \alpha_{ti} \propto \exp\bigl(\beta \langle \hat e(u_t), \hat e(u_i) \rangle\bigr),

over the document’s earlier positions, and the model is λ pKN+(1−λ) pβ\lambda\, p_{\mathrm{KN}} + (1 - \lambda)\, p_\beta, with Kneser–Ney alone at a document’s first position. Over the open vocabulary, an out-of-vocabulary word costs Kneser–Ney the probability of <unk> times its spelling, pKN(unk) S(w)p_{\mathrm{KN}}(\mathrm{unk})\, S(w), with SS the perplexity topic’s speller, while the cache’s values are the raw strings.

This is attention with fixed queries and keys, a value per position, and Nadaraya–Watson’s estimator applied to classification: the cache predicts a word in proportion to the kernel weight of the earlier positions where it occurred. Grave, Joulin, and Usunier (2017) built such a cache over a recurrent network’s hidden states; here the keys are word vectors, so there is nothing to train. The two ends of the bandwidth are older models.

Corollary 2 (The cache's two limits).

At β=0\beta = 0, Definition 3 is the unigram document cache, p0(w∣t)=#{i<t:wi=w}/tp_0(w \mid t) = \#\{i \lt t : w_i = w\}/t, since positions are numbered from 00. As β→∞\beta \to \infty, if some earlier position has the key e^(ut)\hat e(u_t), the cache puts all its weight on those positions: it is the document’s bigram cache over the key’s occurrences. Otherwise it puts its weight on the earlier positions whose keys are nearest to e^(ut)\hat e(u_t).

Proof.

At β=0\beta = 0 every weight is 1/t1/t. As β→∞\beta \to \infty, Proposition 4 (i) sends the weight to the maximizers of ⟨e^(ut),e^(ui)⟩\langle \hat e(u_t), \hat e(u_i) \rangle, whose maximum value 11 is attained exactly at the positions with e^(ui)=e^(ut)\hat e(u_i) = \hat e(u_t), when there are any, since the keys are unit vectors.

∎

The unigram cache is Kuhn and De Mori’s (1990). The exact-context limit is a bigram cache, with one caveat that the corpus forces: 1,2251{,}225 pairs of training words, among 358358 of the 3,4253{,}425, have identical vectors, because they were seen in identical contexts, so the limit pools them. Of the 358358, 348348 were seen only once, many of them pseudo-words such as bondbook. The other ten are names such as aisha and rahman and ordinary words such as field and offshore. Between the limits, a context never seen before in the document borrows from the earlier contexts nearest to it, the neural-language-models topic’s smoothing by geometry, now over a document.

Inverse bandwidth β\beta and mixture weight λ\lambda are chosen on the development documents, never on held-out text. For each β\beta, the table gives the dev-chosen λ\lambda, the development loss, and the held-out loss, in nats per token over the closed vocabulary.

β\beta0012\tfrac12112244881616∞\infty
dev λ\lambda0.990.990.990.990.980.980.980.980.980.980.990.990.990.990.990.99
dev2.78982.78982.78942.78942.78872.78872.78702.78702.78712.78712.79182.79182.79252.79252.79372.7937
held out2.83612.83612.83532.83532.83062.83062.82822.82822.82842.82842.83862.83862.84082.84082.84242.8424

The bandwidth trade-off appears on text. Development data chooses β=2\beta = 2, between the unigram cache and the exact-context cache, and on held-out text that choice beats both. With standard errors clustered by document, because a cache makes a document’s sentences dependent, Kneser–Ney scores 2.8552.855 nats per token (±0.026\pm 0.026) and the mixture 2.8282.828 (±0.025\pm 0.025). The paired gain, 0.0269±0.00250.0269 \pm 0.0025, is more than ten standard errors.

The gain is where a cache should help. On the 41.9%41.9\% of positions whose target already occurred in the document, the loss falls from 1.7981.798 to 1.7061.706 nats; on first mentions it rises from 3.6173.617 to 3.6373.637, the price of the weight the cache takes. By distance back to the previous mention:

previous mentionshare of repeatsin an earlier sentenceKneser–Neymixture
11–1212 tokens back36.3%36.3\%89.1%89.1\%1.4271.4271.3801.380
1313–505045.5%45.5\%99.2%99.2\%1.7641.7641.6821.682
more than 505018.2%18.2\%100%100\%2.6212.6212.4142.414

The farther back the previous mention, the more the cache gains, and nearly every repeat’s previous mention is in an earlier sentence, where the per-sentence recurrent network had nothing. The gain on those repeats alone is 1.311.31 times the net gain. The net gain is still small, 0.6370.637 to 0.6320.632 bits per character over the open vocabulary, because the synthetic generator draws its words from corpus-wide restaurants: a document repeats itself only a little more than the corpus does. Real text repeats itself more (Church and Gale 1995), and the finance case study below is where that shows.

The keys so far were fixed. Learning them is the step from a cache to attention.

Definition 4 (Learned kernel).

Add a trained bilinear term to Definition 3’s scores,

β⟨e^(ut),e^(ui)⟩+⟨FtA,FiB⟩,A,B∈R102×16,\beta \langle \hat e(u_t), \hat e(u_i) \rangle + \langle F_t A, F_i B \rangle, \qquad A, B \in \mathbb{R}^{102 \times 16},

where FtF_t is the preceding token’s SVD vector together with indicators of the sentence start and of an out-of-vocabulary word. Train AA and BB on the training documents to minimize the pointer loss, −log⁡∑i<t: wi=wtαti-\log \sum_{i \lt t :\, w_i = w_t} \alpha_{ti} averaged over the positions whose target occurred earlier in the document.

The pointer loss asks the kernel to put its weight where the target is, as in Merity and colleagues’ (2017) pointer sentinel, and it needs no Kneser–Ney, whose probabilities on its own training text are overfit. Starting from Definition 3 at β=2\beta = 2, twelve epochs of Adam lower the training pointer loss at every epoch, from 3.0013.001 to 2.0732.073, and development data chooses the eleventh epoch with λ=0.97\lambda = 0.97. On held-out text the learned kernel’s own pointer loss falls from 3.2563.256 to 2.3832.383, and the mixture improves to 2.8212.821 nats per token, a further 0.0071±0.00110.0071 \pm 0.0011, more than six standard errors.


Bandwidth, reach, and memory

The laboratory puts the last three sections side by side. Panel A is the circle: drag the concentration cc and watch the smoothed curve, the Fourier gains, and the exact risk; c∗c^* and the trained layer’s cc are marked. Panel B is the lookup: one held-out document and the three filings of the case study below, token by token, with the bits each variant of the cache spends on every token and, for selected tokens, where the kernel looks; and the gradient census of the long-lag task.

A · Temperature is bandwidth — attention over n keys on a circle, scores c·cos(θᵢ − θⱼ)
c = 11.0
click a keyweights for query 0angle θ, from 0 to 2π
true fattention output

Dots: the noisy values y. The output is Definition 2 computed from these values; the readouts below are the exact risk over all functions of this spectrum.

ρ₁ρ₂ρ₃ρ₄ρ₅ρ₆ρ₇ρ₈10the fraction of each Fourier mode the smoother keeps
risk R(c)
0.0548
bias²
0.0097
variance
0.0451
gain ρ₁
0.953
c* (Theorem 1)
10.011
R(c*)
0.0546
trained layer's c
10.006

Raising c narrows the kernel: the gains rise toward 1, so less of f is smoothed away (bias falls) and more of the noise passes through (variance rises). They balance at c*, and the attention layer trained on random functions of this kind lands there. At c = 0 every key gets the same weight and the output is the mean.


B · A lookup instead of a state — a cache over the document’s own words, and the gradient that reaches back
thankyouforjoiningthedunmoreaerospacequarterlyresultscallresultsreflectedmultibrokercrosspremiumshelfbaseandtranspricecopricestheplanreallocatesresourcesfrommidsuppliersandmultibrokerpartnershipstowardoverindexanddepositbaserebatebooksmanagementhighlightedchannellineinterfleetroutersandoutreceivableasareasoffocusdunmoreaerospacereportedrevenueofmillionforfiscalprioritiesfortheyearincludecouponlinesshelfagestocksideoverindexsanddepositingcomponentscostofrevenuewasmilliondunmorehasitsrootsingermanyactivityintransindexpipingandfleetworkheadcounttrackedthebroaderseatworkscrosspremiumcycledunmoreaerospacecompeteswithmarrowfreightforoutrebatesbusinessdunmoreaerospaceguidedtopercentgrowthinthefirstquarterthomasaveryhasspokenpubliclyaboutdunmoreaerospacetheplanreallocatesresourcesfromnetworkingsandfundingtowardbrokerbaseandoutreceivableoperatingmarginheldsteadyacrossoutreceivableandpostmerchantoperatingcostsinpartnershipsandmarketspartnershipstrailedexpectationsliquidityfellpercentinordersandundercyclerouterswhichmanagementdescribedasweakeroperatingmarginwasbroadlyunchangedincorebatecostsinpricageoutperformedexpectationsdemandforthewrenactuatorshapedtheroutersandnonroyaltysoutlook

Shading: bits the chosen model saves on each token against Kneser–Ney (green) or spends (red). Italic: not in the training vocabulary. ¶: a sentence end. Click any token; for the tokens marked •, the eight earlier positions the β = 2 kernel weights most are underlined, darker for more weight, and the word’s own earlier occurrences, the positions it is copied from, are outlined with dashes.

document, Kneser–Ney (bits per character)
0.742
document, β = 2: the dev choice
0.713
token
multibroker
its bits, Kneser–Ney
15.40
its bits, β = 2: the dev choice
10.71
cache probability of this word, β = 2
0.029
earlier occurrences it is copied from
1
β = 2 kernel, heaviest earlier positions: transprice (0.219) · midsuppliers (0.036) · from (0.035) · results (0.032) · the (0.032) · dunmore (0.032) · plan (0.032) · reallocates (0.031)
2.8002.8202.840β = 0β = ½β = 1β = 2β = 4β = 8β = 16β = ∞nats per token, Kneser–Ney ⊕ cache · dev chooses β = 2
held outdevelopment
held out at β = 2 (dev λ = 0.98)
2.8282
held out at β = 0
2.8361
held out at β = ∞
2.8424

Kernels that factor

A head’s scores QK⊤/τQK^\top/\tau form a matrix of rank at most dkd_k. That limits what one head can express, and a stronger factorization makes attention cheap.

Proposition 7 (One head's rank bound).

For one bidirectional head over nn positions, log⁡A=QK⊤/τ−λ1⊤\log A = QK^\top/\tau - \lambda \mathbf{1}^\top, where λi\lambda_i is the log-sum-exp of row ii, so rank⁡log⁡A≤dk+1\operatorname{rank} \log A \le d_k + 1. A positive row-stochastic pattern PP is realizable by one head with key dimension dkd_k if and only if some row shift log⁡P−c1⊤\log P - c \mathbf{1}^\top has rank at most dkd_k. The least Frobenius distance from log⁡P\log P to the set {S+c1⊤:rank⁡S≤dk}\{S + c \mathbf{1}^\top : \operatorname{rank} S \le d_k\} is the norm of the singular values of log⁡P Jn\log P\, J_n beyond the dkd_k-th, where Jn=I−11⊤/nJ_n = I - \mathbf{1}\mathbf{1}^\top/n.

Proof.

The first claim is subadditivity of rank. The softmax is unchanged by adding a constant to a row, so PP is realizable exactly when log⁡P=S+c1⊤\log P = S + c\mathbf{1}^\top for some SS of rank at most dkd_k, and any such SS factors as QK⊤/τQK^\top/\tau. For the distance, fix SS: the best shift is the row means of log⁡P−S\log P - S, which leaves (log⁡P−S)Jn(\log P - S) J_n. As SS ranges over matrices of rank at most dkd_k, SJnS J_n ranges over those whose rows are orthogonal to 1\mathbf{1}, and log⁡P Jn\log P\, J_n has rows orthogonal to 1\mathbf{1} too, so Eckart–Young applies to log⁡P Jn\log P\, J_n.

∎

This is the neural-language-models topic’s softmax bottleneck (its Theorem 6; Yang et al. 2018), with keys in the place of the vocabulary, and it is Bhojanapalli and colleagues’ (2020) case for wider heads. Hard patterns escape it in the zero-temperature limit of Proposition 4: with dk=2d_k = 2, keys on a circle and queries pointed at the right angles realize any permutation. Several heads give several kernels, which is where the transformer-block topic begins.

The softmax kernel can also be factored approximately, with features that turn e⟨x,y⟩e^{\langle x, y \rangle} into an inner product.

Proposition 8 (Positive random features).

For w∼N(0,I)w \sim N(0, I), the feature φw(x)=e⟨w,x⟩−∥x∥2/2\varphi_w(x) = e^{\langle w, x \rangle - \lVert x \rVert^2/2} satisfies

E[φw(x)φw(y)]=e⟨x,y⟩,Var⁡[φw(x)φw(y)]=e2⟨x,y⟩(e∥x+y∥2−1).E\bigl[\varphi_w(x)\varphi_w(y)\bigr] = e^{\langle x, y \rangle}, \qquad \operatorname{Var}\bigl[\varphi_w(x)\varphi_w(y)\bigr] = e^{2\langle x, y \rangle}\bigl(e^{\lVert x + y \rVert^2} - 1\bigr).

For the kernel eβ⟨x^,y^⟩e^{\beta\langle \hat x, \hat y \rangle} on unit vectors, mm independent features have relative variance (eβ∥x^+y^∥2−1)/m≤(e4β−1)/m(e^{\beta \lVert \hat x + \hat y \rVert^2} - 1)/m \le (e^{4\beta} - 1)/m. Positive features never give a nonpositive attention denominator; trigonometric features can.

Proof.

For w∼N(0,I)w \sim N(0, I), Ee⟨w,a⟩=e∥a∥2/2E e^{\langle w, a \rangle} = e^{\lVert a \rVert^2/2}. At a=x+ya = x + y, E[φw(x)φw(y)]=e∥x+y∥2/2−∥x∥2/2−∥y∥2/2=e⟨x,y⟩E[\varphi_w(x)\varphi_w(y)] = e^{\lVert x + y \rVert^2/2 - \lVert x \rVert^2/2 - \lVert y \rVert^2/2} = e^{\langle x, y \rangle}. At a=2(x+y)a = 2(x + y) the second moment is e2∥x+y∥2−∥x∥2−∥y∥2e^{2\lVert x + y \rVert^2 - \lVert x \rVert^2 - \lVert y \rVert^2}, and subtracting the squared mean gives the variance. Apply it to x=β x^x = \sqrt\beta\, \hat x and y=β y^y = \sqrt\beta\, \hat y, and use ∥x^+y^∥2≤4\lVert \hat x + \hat y \rVert^2 \le 4. Positivity is immediate; the module’s test exhibits trigonometric features, those of Rahimi and Recht (2007), with a negative denominator.

∎

These are Choromanski and colleagues’ (2021) features. Their variance is largest exactly where the kernel is largest: the sharp kernel that makes a lookup useful is the one that does not compress. The point of factoring is the next proposition.

Proposition 9 (Causal linear attention is a recurrence).

With a kernel φ(q)⊤φ(k)\varphi(q)^\top \varphi(k) for positive features φ:Rdk→Rm\varphi: \mathbb{R}^{d_k} \to \mathbb{R}^m, the causal smoother is

o^t=φ(qt)⊤Stφ(qt)⊤zt,St=St−1+φ(kt) vt⊤,zt=zt−1+φ(kt),\hat o_t = \frac{\varphi(q_t)^\top S_t}{\varphi(q_t)^\top z_t}, \qquad S_t = S_{t-1} + \varphi(k_t)\, v_t^\top, \quad z_t = z_{t-1} + \varphi(k_t),

with S0=0S_0 = 0 and z0=0z_0 = 0. Its state (St,zt)(S_t, z_t) has m(dv+1)m(d_v + 1) numbers, whatever tt is.

Proof.

∑j≤t(φ(qt)⊤φ(kj))vj=φ(qt)⊤∑j≤tφ(kj)vj⊤=φ(qt)⊤St\sum_{j \le t} \bigl(\varphi(q_t)^\top \varphi(k_j)\bigr) v_j = \varphi(q_t)^\top \sum_{j \le t} \varphi(k_j) v_j^\top = \varphi(q_t)^\top S_t by associativity, and likewise for the denominator.

∎

Katharopoulos and colleagues (2020) named the result: transformers with factored kernels are recurrent networks. The lookup has been compressed back into a fixed-size state, the neural-language-models topic’s design, and Proposition 8 gives the price. formalRAG’s Retrieval versus Long Context counts what the unfactored lookup costs; here is what factoring it loses. Replace the kernel cache’s exponential by mm positive random features and measure, on the held-out documents, the mean total-variation distance between the approximate attention weights and the exact ones:

β\betam=16m = 1664642562561,0241{,}024
12\tfrac120.0820.0820.0470.0470.0230.0230.0130.013
110.1690.1690.0960.0960.0490.0490.0290.029
22 (dev)0.2640.2640.2210.2210.1170.1170.0960.096
440.4220.4220.3940.3940.3190.3190.2660.266
880.7340.7340.5890.5890.4950.4950.4340.434

The error falls with the number of features and grows with the kernel’s sharpness, at every entry. At the dev-chosen setting the mixture’s loss hardly registers it, because the cache carries only 2%2\% of the probability: 2.83272.8327, 2.82822.8282, 2.82972.8297, and 2.83042.8304 nats per token for m=16m = 16, 6464, 256256, and 1,0241{,}024, against 2.82822.8282 for the exact cache.


Finance case study: the filing as memory


Where this goes next

  • Positions. Proposition 3 says that at the last word, one layer of attention cannot tell the dog bit the man today from the man bit the dog today. The positional-encodings topic adds position, and Theorem 1’s features (cos⁡θ,sin⁡θ)(\cos\theta, \sin\theta) are already a sinusoidal encoding of one frequency: several frequencies, and rotations of the queries and keys, are its subject.
  • The transformer block. A block runs several heads, each a smoother with its own kernel (Proposition 7), and adds their outputs to a residual stream; the transformer-block topic assembles it.
  • Contextual embeddings. Stacking blocks gives each occurrence of a word its own vector, the subject of the contextual-embeddings topic.
  • Aspect-based sentiment. Attention to the words that carry an aspect’s sentiment is a kernel lookup whose query is the aspect; the aspect-based sentiment topic asks how far its weights explain its predictions.
  • Retrieval. formalRAG’s late interaction scores a document by each query token’s best match, the zero-temperature lookup of Proposition 4, and its long-context topic prices the full lookup.

Honest caveats


Implementation

The companion notebook (notebookPath) imports attention_as_kernel_smoothing.py, which owns every number on this page. It imports the neural-language-models topic’s module for its gradient checkers, its long-lag task and census, its Kneser–Ney scores, and its spelling cache; the distributional-semantics topic’s module for the word vectors; and the perplexity topic’s speller and ratio estimator. It trains the circle denoiser, the lag-task attention layer, and the learned kernel from scratch in NumPy, and runs a harness of 2121 assertion-based tests in under a minute on a laptop CPU. The tests cover:

  • Propositions 1–3 on random instances and a corpus sentence’s prefix; Proposition 2’s conditional mean by Monte Carlo.
  • Proposition 4’s bounds; Theorem 1 against numpy’s FFT and simulated noise; Corollary 1 on the exact formula to n=108n = 10^8; the trained denoiser against Theorem 1’s optimum; a search over general MM on the exact population risk.
  • Theorem 2 by Monte Carlo; Proposition 5 against complex-step derivatives; Proposition 6, the census, the lag sweep, and training.
  • Definition 3’s limits, the development grid, and the held-out benchmark with document-clustered standard errors; Definition 4’s gradient and training.
  • Propositions 7–9 on random instances; the random-feature cache; the finance case study.

Every hand-written gradient is checked against complex-step derivatives and central differences. The laboratory reads its data from a JSON file that one of those tests requires to equal the module’s viz_payload() exactly, so the figure cannot drift from the code.

References & Further Reading