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 noise symbols, then report the bit. At initialization the gradient that reaches the bit from the final loss is for an Elman network, because it passes through 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 . Trained by the same protocol at lag , the attention layer reports the bit correctly on every fresh sequence, at lag and at lag .
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.
- Attention is a kernel smoother. Softmax attention is the Nadaraya–Watson estimator of nonparametric regression, with the kernel . That kernel is a Gaussian in the distance between query and key, tilted toward long keys.
- 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.
- The scale keeps random dot products from saturating the softmax, whose Jacobian vanishes as it saturates.
- 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 and the gradient reaching the bit falls from to for attention, and from to 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 to bits per character, mostly by copying words the training text never contained, though lzma, at , still codes them shorter.
A weighted lookup
Rows are tokens, as in the neural-language-models topic. The inputs are mapped to queries , keys in , and values in . Position may read the positions : all of them in bidirectional attention, and in causal attention, the kind a language model uses. Write .
Before attention, there was regression. Given design points and responses , 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 , responses , and a positive kernel , the kernel smoother at is
With , a scaled density of bandwidth , it is the Nadaraya–Watson estimator. With positive design weights , the kernel is .
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 , with temperature unless stated, and the attention weights are over . The output is . In matrix form,
row by row, where the mask is on and 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 is Definition 1’s smoother at , with the kernel , design points , and responses .
(ii) For all and ,
So is the Gaussian Nadaraya–Watson estimator with bandwidth , which is at the default scale, and design weights .
(iii) If all keys have the same norm, is the unweighted Gaussian estimator. If queries and keys lie on a sphere of radius , the kernel is , the von Mises–Fisher kernel with concentration .
(iv) lies in the convex hull of the values it reads, so .
Proof.
Part (i) is the definition of the softmax: . Part (ii) is the polarization identity , divided by and exponentiated. The factor is the same for every key, so it cancels between the numerator and the denominator of Definition 1, and what remains is times a Gaussian kernel of variance . Part (iii) follows because equal norms make every equal, and on the sphere . For (iv), the weights are positive and sum to .
∎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 . The keys’ lengths act as a design density: of two keys equally far from the query, the longer one gets exactly 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 take the value with probability , let , and let . Then
Equivalently, is the conditional mean of under the joint law , a kernel density estimate in with point masses in , where is the density.
Proof.
By Bayes’ rule, , and by Proposition 1 (ii) this is proportional to , with a constant that does not depend on . Normalizing gives . Then .
∎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 has atoms in , so it is not a density. Its marginal in 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 draws from the mixture, the residual is uncorrelated with , , and , 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, depends on only through their multiset. Two prefixes that rearrange the same tokens, followed by the same , 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 commute with relabeling; position-wise maps commute with it trivially. For (ii), the sum is a symmetric function of the pairs with , given , , and . For (iii), the second layer at position reads the first layer’s outputs at , and each of those depends on its own prefix , 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 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 , 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 the weight piles onto the best-scoring key; at it spreads evenly. Both limits come with rates.
Proposition 4 (The two temperature limits).
Fix raw scores over a set of positions, undivided by , and let and . Let be the set of maximizers, the gap between the maximum and the largest score off , and the range of the scores. Write for the mean of the values over . Then
Proof.
For the first bound, every weight on is the same, and each weight off is at most times it, so the mass off is . The weights on are then each, so , whose norm is at most . For the second, lies in , so , and .
∎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 , variance of order , and an optimal bandwidth of order in one dimension. For attention there is a setting where the answer is exact at every . Place 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 for , give every token the features for its query and key, and let the scores be with . Let the values be , with the independent of mean and variance . Let be the bidirectional attention matrix, and the discrete Fourier coefficients of .
(i) is circulant. The Fourier vectors are its eigenvectors, with eigenvalues
where is the modified Bessel function of the first kind. For , for every ; at , .
(ii) The exact risk at the design points is
Proof.
The score depends only on modulo , so with and : is circulant. Applied to , it gives . The generating function (DLMF 10.35.1), summed over the angles , keeps exactly the terms with :
since . The normalizer is the case , which gives the formula in (i). For every is positive, so . Because is symmetric, , with equality only if for every , that is, . At , for .
For (ii), split the error into bias and noise. The mean output is , and in the Fourier basis . The vectors are orthogonal with squared norm , so by the discrete form of Parseval’s identity . The noise contributes , since every row of is a rotation of . Finally , which is the generating-function sum at with .
∎With one frequency of position, attention is a low-pass filter. The Fourier mode keeps the fraction of its amplitude, and once is large enough that the aliased terms vanish, ; at and the first six gains are , , , , , and . The first gain 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 , 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 , 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 and , to , and (ii) against simulated noise.
Corollary 1 (The bandwidth rate).
For a fixed nonconstant trigonometric polynomial , write for its power at frequency , and . The risk-minimizing satisfies
as . So the angular bandwidth is of order , and the optimal risk is of order , the rate of kernel regression in one dimension.
Proof.
The large-argument expansion (DLMF 10.40.1) gives and . The aliased terms with are smaller than by about . That is not always tiny: at and it is about . But it vanishes while . So do the errors it causes: in the leading aliased terms nearly cancel, leaving a relative error of order , and the sum at has a relative error of order . So, uniformly as with ,
This expansion applies at the optimum. For bounded the bias term is bounded away from , while , so . And of order keeps the variance term bounded away from . Fix and take . Numbering the positions so that , the bound on gives
so the variance term is at least . So .
Write for the two leading terms. Setting its derivative to zero gives its minimizer , with , and , which falls on and rises on . Since uniformly on the range that holds both and , the inequality forces .
∎The asymptote is approached quickly. Two spectra are used below: a smooth one, with random Fourier coefficients of variance at frequency and at frequency , and a rough one, with variance at each of the frequencies through , both with noise . Computed from Theorem 1’s exact formula, the ratio , where , is:
| spectrum | |||||||
|---|---|---|---|---|---|---|---|
| smooth | |||||||
| rough |
Between and the log–log slope of is for the smooth spectrum and 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 ; its queries and keys see the position only, so its scores are with , and its values are the . Adam trains it on fresh random functions from one spectrum, at random rotations , to minimize the squared error against the clean . The task distribution is invariant under rotations and reflections, which points to a population optimum of , with 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 matrices , from one isotropic and five random starts, for each row below, and every search ends within of , at Theorem 1’s risk to . That is numerical evidence, not a proof that the minimum is global.
| spectrum, | learned | Theorem 1’s | ||
|---|---|---|---|---|
| smooth, | ||||
| smooth, | ||||
| rough, |
Here is the average over the second half of training, and the learned is half its trace. The trained layer lands within of the theorem’s optimum at worst, from a start near uniform attention. That worst case is nearly all the miss in itself, of . Anisotropy is a separate and smaller effect: is at most . 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
The temperature of Definition 2 is not a tuned constant but . 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 and are independent with i.i.d. coordinates of mean and variance , then and .
(ii) The softmax Jacobian satisfies
(iii) Let , and let be i.i.d. , independent of , with fixed. For the unscaled scores , in probability as . For the scaled scores , converges in distribution to , with i.i.d. standard normal.
Proof.
For (i), is a sum of independent terms of mean and variance . For (ii), is the covariance of the one-hot vector of a draw from (the neural-language-models topic’s Proposition 2), so it is positive semidefinite, and its largest eigenvalue is at most its trace, . And .
For (iii), condition on . The scores are then i.i.d. , which is the law of with i.i.d. standard normal and independent of . If is the gap between the two largest , every non-maximal weight is at most times the largest, so . Fix and let . Then forces , so for every ,
By the law of large numbers in probability, so the first term tends to for each . The gap has the same law at every , and almost surely, so the second term is as small as we like for large . Scaled, the scores have the law of . The factor tends to in probability, so by Slutsky’s theorem and the continuity of the softmax, converges in distribution to .
∎Part (iii) stops at convergence in probability for a reason. The keys change with , and the theorem states no coupling across dimensions. With , with . If the draws are nested, one coordinate added at each , then is a recurrent random walk. If they are independent across , then is of order , whose sum diverges, so the Borel–Cantelli lemma applies. Either way infinitely often, almost surely, and then : almost sure convergence fails.
Without the scale, the kernel’s bandwidth shrinks like 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 keys, mean and mean over random draws at each dimension are:
| , unscaled | |||||
| , scaled | |||||
| , unscaled | |||||
| , scaled |
A lookup instead of a state
The neural-language-models topic’s Theorem 5 bounds the gradient that reaches state from the loss at step by a product of step Jacobians. Attention has no such product.
Proposition 5 (One hop).
In one causal layer, for ,
acting on row perturbations of , where is the outer product . Hence
When all scores are equal, for positions numbered from .
Proof.
For , enters in two places: through , and through the score , since depends on alone. The first contributes . For the second, the softmax gives , so , and . The bound follows from the triangle inequality and .
∎The lookup’s path from back to has length one. Its only loss is the factor , 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 , then noise symbols drawn from , and the target is . Take one causal layer read at the last position, with one-hot inputs, equal scores, values for the symbol , for the symbol , and for noise, and logits with . Then
the prediction is correct for every , and the cross-entropy is , which tends to as . Keys that score the bit symbols above the noise raise the margin to .
Proof.
With equal scores every one of the positions gets weight , and only position has a nonzero value, . The logits are , whose sign picks , and the cross-entropy of the correct class is . With the bit’s score raised by , its weight is .
∎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 initializations on batches of . The recurrent rows at lag are that topic’s own census, re-run.
| lag | ||||||
|---|---|---|---|---|---|---|
| attention | ||||||
| Elman | ||||||
| LSTM, forget bias | ||||||
| LSTM, forget bias |
Attention’s gradient times stays between and across the whole range: dilution, roughly , 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 orders of magnitude. The LSTM with forget bias is ahead of attention at lag , because its cell path damps the bit far less, keeping of it over that lag (that topic’s Proposition 4). But its gradient still falls, unevenly from lag to lag, and by lag attention has overtaken it. A forget gate postpones the decay; a lookup has none.
Trained by the same protocol, Adam steps at lag , the attention layer answers all fresh test sequences correctly, at a test loss of . That topic reported for the Elman network, for the LSTM with forget bias , and with forget bias . The attention layer also answers every sequence correctly at lag , 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 , run across its sentences in the n-gram topic’s order: each word, then each sentence’s end marker. Position has the target and the preceding token , which is the sentence-start marker at the start of a sentence. Its key is the unit vector of in the distributional-semantics topic’s truncated SVD (positive PMI shifted by , a two-word window, ), with one extra coordinate for the sentence-start marker and one for each distinct out-of-vocabulary string. The kernel cache with inverse bandwidth is
over the document’s earlier positions, and the model is , 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, , with 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 , Definition 3 is the unigram document cache, , since positions are numbered from . As , if some earlier position has the key , 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 .
Proof.
At every weight is . As , Proposition 4 (i) sends the weight to the maximizers of , whose maximum value is attained exactly at the positions with , 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: pairs of training words, among of the , have identical vectors, because they were seen in identical contexts, so the limit pools them. Of the , 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 and mixture weight are chosen on the development documents, never on held-out text. For each , the table gives the dev-chosen , the development loss, and the held-out loss, in nats per token over the closed vocabulary.
| dev | ||||||||
| dev | ||||||||
| held out |
The bandwidth trade-off appears on text. Development data chooses , 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 nats per token () and the mixture (). The paired gain, , is more than ten standard errors.
The gain is where a cache should help. On the of positions whose target already occurred in the document, the loss falls from to nats; on first mentions it rises from to , the price of the weight the cache takes. By distance back to the previous mention:
| previous mention | share of repeats | in an earlier sentence | Kneser–Ney | mixture |
|---|---|---|---|---|
| – tokens back | ||||
| – | ||||
| more than |
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 times the net gain. The net gain is still small, to 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,
where is the preceding token’s SVD vector together with indicators of the sentence start and of an out-of-vocabulary word. Train and on the training documents to minimize the pointer loss, 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 , twelve epochs of Adam lower the training pointer loss at every epoch, from to , and development data chooses the eleventh epoch with . On held-out text the learned kernel’s own pointer loss falls from to , and the mixture improves to nats per token, a further , 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 and watch the smoothed curve, the Fourier gains, and the exact risk; and the trained layer’s 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.
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.
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.
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.
Kernels that factor
A head’s scores form a matrix of rank at most . 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 positions, , where is the log-sum-exp of row , so . A positive row-stochastic pattern is realizable by one head with key dimension if and only if some row shift has rank at most . The least Frobenius distance from to the set is the norm of the singular values of beyond the -th, where .
Proof.
The first claim is subadditivity of rank. The softmax is unchanged by adding a constant to a row, so is realizable exactly when for some of rank at most , and any such factors as . For the distance, fix : the best shift is the row means of , which leaves . As ranges over matrices of rank at most , ranges over those whose rows are orthogonal to , and has rows orthogonal to too, so Eckart–Young applies to .
∎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 , 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 into an inner product.
Proposition 8 (Positive random features).
For , the feature satisfies
For the kernel on unit vectors, independent features have relative variance . Positive features never give a nonpositive attention denominator; trigonometric features can.
Proof.
For , . At , . At the second moment is , and subtracting the squared mean gives the variance. Apply it to and , and use . 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 for positive features , the causal smoother is
with and . Its state has numbers, whatever is.
Proof.
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 positive random features and measure, on the held-out documents, the mean total-variation distance between the approximate attention weights and the exact ones:
| (dev) | ||||
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 of the probability: , , , and nats per token for , , , and , against 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 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 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 ; the trained denoiser against Theorem 1’s optimum; a search over general 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
- paper On Estimating Regression — E. A. Nadaraya (1964) Theory of Probability and Its Applications 9 (1): 141–42. The kernel regression estimator, Definition 1
- paper Smooth Regression Analysis — Geoffrey S. Watson (1964) Sankhyā, Series A 26 (4): 359–72. The same estimator, independently, Definition 1
- paper Neural Machine Translation by Jointly Learning to Align and Translate — Dzmitry Bahdanau, Kyunghyun Cho, and Yoshua Bengio (2015) ICLR 2015. Attention as a soft lookup over every source position, Definition 2
- paper Attention Is All You Need — Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, and Illia Polosukhin (2017) NeurIPS 30. Scaled dot-product attention, Definition 2, and the 1/√d scale of Theorem 2
- paper Transformer Dissection: An Unified Understanding for Transformer's Attention via the Lens of Kernel — Yao-Hung Hubert Tsai, Shaojie Bai, Makoto Yamada, Louis-Philippe Morency, and Ruslan Salakhutdinov (2019) Proceedings of EMNLP-IJCNLP 2019, 4344–53. Attention read as a kernel smoother, Proposition 1
- paper Probabilistic Attention for Interactive Segmentation — Prasad Gabbur, Manjot Bilkhu, and Javier Movellan (2021) NeurIPS 34. Dot-product attention as inference in a Gaussian mixture, Proposition 2
- paper Transformer Language Models without Positional Encodings Still Learn Positional Information — Adi Haviv, Ori Ram, Ofir Press, Peter Izsak, and Omer Levy (2022) Findings of EMNLP 2022, 1382–90. The causal mask leaks order, Proposition 3 (iii)
- paper Hopfield Networks is All You Need — Hubert Ramsauer, Bernhard Schäfl, Johannes Lehner, Philipp Seidl, Michael Widrich, Thomas Adler, Lukas Gruber, et al. (2021) ICLR 2021. One-step retrieval with exponentially small error, Proposition 4 (i)
- paper In-Context Learning with Transformers: Softmax Attention Adapts to Function Lipschitzness — Liam Collins, Advait Parulekar, Aryan Mokhtari, Sujay Sanghavi, and Sanjay Shakkottai (2024) NeurIPS 37. A trained attention unit's window adapts to the tasks' smoothness and noise, the trained denoiser
- documentation NIST Digital Library of Mathematical Functions, §10.35 and §10.40 — F. W. J. Olver et al., eds. The generating function of the modified Bessel functions (10.35.1), Theorem 1, and their large-argument expansions (10.40.1), Corollary 1
- paper Low-Rank Bottleneck in Multi-head Attention Models — Srinadh Bhojanapalli, Chulhee Yun, Ankit Singh Rawat, Sashank J. Reddi, and Sanjiv Kumar (2020) ICML 2020, PMLR 119. One head's rank limit, Proposition 7
- paper Random Features for Large-Scale Kernel Machines — Ali Rahimi and Benjamin Recht (2007) NeurIPS 20. Trigonometric random features, Proposition 8
- paper Rethinking Attention with Performers — Krzysztof Choromanski, Valerii Likhosherstov, David Dohan, Xingyou Song, Andreea Gane, Tamas Sarlos, Peter Hawkins, et al. (2021) ICLR 2021. Positive random features for the softmax kernel, Proposition 8
- paper Transformers are RNNs: Fast Autoregressive Transformers with Linear Attention — Angelos Katharopoulos, Apoorv Vyas, Nikolaos Pappas, and François Fleuret (2020) ICML 2020, PMLR 119. Causal linear attention as a recurrence, Proposition 9
- paper A Cache-Based Natural Language Model for Speech Recognition — Roland Kuhn and Renato De Mori (1990) IEEE Transactions on Pattern Analysis and Machine Intelligence 12 (6): 570–83. The unigram cache, Definition 3 at β = 0
- paper Improving Neural Language Models with a Continuous Cache — Edouard Grave, Armand Joulin, and Nicolas Usunier (2017) ICLR 2017. A cache read through a kernel on hidden states, Definition 3
- paper Pointer Sentinel Mixture Models — Stephen Merity, Caiming Xiong, James Bradbury, and Richard Socher (2017) ICLR 2017. Training a pointer over the recent context, Definition 4
- paper Breaking the Softmax Bottleneck: A High-Rank RNN Language Model — Zhilin Yang, Zihang Dai, Ruslan Salakhutdinov, and William W. Cohen (2018) ICLR 2018. The rank argument Proposition 7 repeats for keys
- paper Poisson Mixtures — Kenneth W. Church and William A. Gale (1995) Natural Language Engineering 1 (2): 163–90. Words recur within a document more than a constant rate predicts