During autoregressive generation, a causal Transformer can retain the keys and values of earlier tokens in a key–value (KV) cache, described in the architectural trade-offs section of Chapter 16, so that each new query attends to all prior tokens without recomputing them. This interlude compares three ways to construct that memory computation: a query-local fit over stored pairs, running statistics for a factorized kernel, and an online linear predictor updated by the delta rule.
Read this way, attention is an online regression estimator at test time. The constructions share a regression perspective, but they need not solve the same optimization problem. Softmax attention, linear attention, state-space models and DeltaNet differ in the kernel, the predictor class, the regularization and the update rule, and these choices determine both the answer and the information that must be retained.
17.1 Three memory constructions through regression
The recurrent networks of Chapter 12 compressed the history into a fixed-size state. The Transformer resolved that bottleneck by keeping the visible key–value rows available. Reading those rows becomes more expensive as the prefix grows, and across a complete sequence dense routing has quadratic cost. There is another resolution: return to the regression perspective of Chapter 14 and change the kernel, the predictor class, or the update rule. Some of these choices permit a state of fixed size.
Recent sequence models make that move under names such as test-time regression, test-time training, fast weights, linear attention, DeltaNet, Titans, MesaNet, and state-space sequence models. Each solver is characterized by what information it retains and what computational trade-offs it accepts.
Choices within the regression framework
At time \(t\), let learned projections turn each token representation \(\vect{x}_\tau\) into two views,
Following Wang, Shi, and Fox (2025), we describe memory construction as a weighted regression problem. A memory layer builds an online predictor \(M_t:\mathbb{R}^{d_k}\rightarrow\mathbb{R}^{d_v}\):
The display specifies a reference fitting problem. An online update need not attain its minimizer. Query-local attention also makes the observation weights depend on the query, as the next construction shows.
Here the keys and values are computed from the input sequence. The memory state changes during the forward computation, while the projection parameters are held fixed during that evaluation. The frame exposes four design choices.
The views.\(\matr{W}_Q,\matr{W}_K,\matr{W}_V\) are the learned projections of Chapter 16: queries and keys are compared, and values are what the comparison passes on. The token is not assigned one permanent meaning. The three projections give it a query, a key that provides the features used for comparison, and a value.
The history weights.\(w_{t,\tau}\) determine how much an older residual matters to the fitting problem. The forget gates of Chapter 12 already made retention depend on time and content. A geometric schedule can privilege recent errors; an input-dependent schedule can keep some tokens longer than others.
The model and regularizer. The class \(\mathcal{M}\) determines whether the predictor is a local constant, a linear map, or something richer. \(\Omega\) brings back ridge penalties from Chapter 1 and weight decay from Chapter 4. Regularization controls the fitted map. It is not, by itself, the same operation as forgetting old observations.
The solver. A closed-form local fit, a running sufficient statistic, and one gradient step do different work and preserve different information. A layer may compute a closed-form solution or execute an iterative or approximate update, whose rule may itself be learned.
This objective is an umbrella, not an equivalence theorem. Its methods can restrict different function classes, use different weights, and stop at different approximations.
Solver 1: keep the data and fit at the query
Softmax attention instantiates the framework as a query-local constant estimator. For a query \(\vect{q}\), the predictor class \(\mathcal{M}\) is restricted to constant vectors \(\vect{c}\in\mathbb{R}^{d_v}\), and observation weights are the query-dependent affinities, yielding the local-constant problem
Choose \(\kappa(\vect{q},\vect{k})=\exp(\vect{q}^{\top}\vect{k}/\sqrt{d_k})\) and the normalized coefficients form a row of scaled dot-product softmax. The kernel supplies the weights, and the constant fit supplies the average. An unrestricted \(M\) with unit observation weights and no regularizer would instead interpolate compatible training pairs and be undetermined away from them.
We can check numerically that the gradient vanishes at the weighted average. Subtracting the largest score rescales every \(\kappa_\tau\) by the same positive constant and leaves the minimizer unchanged.
Draw 12 seeded key-value pairs and a query, then form the weighted average, softmax output, and gradient.
This solver retains the key–value rows because a future query may weight every row differently. That is why dense causal attention carries a growing dataset forward.
Solver 2: collapse a factorized kernel into sufficient state
Suppose the kernel factors through a finite feature map \(\phi:\mathbb{R}^{d_k}\rightarrow\mathbb{R}^{r}\):
Assume the resulting kernel is nonnegative on the pairs being used and that the normalization denominator is positive. The positive feature map used below satisfies these conditions. Substitute that factorization into the weighted average and regroup terms:
The sufficient state is the pair \((\matr{S}_t,\vect{z}_t)\), not \(\matr{S}_t\) alone: the numerator needs accumulated value-weighted features and the denominator needs its normalizer. Each new pair updates that fixed-size state once. For this factorized kernel, any later query gets the same answer from the state as from a full traversal of all pairs.
Define the reusable ms_phi helper.
Initialize the sufficient-state pair, ms_S and ms_z, as zero arrays.
Compare a factorized-kernel traversal with its running state.
Check the claimed identities, shapes, or invariants.
Print whether ms_streaming matches ms_traversal and their largest absolute difference.
streaming equals traversal: True
max |difference|: 3.469e-17
The identity is exact in real arithmetic. In floating point the two results can differ slightly, because the sums are accumulated in a different order. The traversal of the full dataset has collapsed into two running sums. With \(r\) and \(d_v\) fixed, storage no longer grows with the prefix. Causal linear attention can therefore run as a recurrence: its state stores the sufficient statistics of this regression.
This construction has a limitation. Ordinary softmax’s exponential dot-product kernel does not have a finite exact feature map like the one used above. With the scale \(1/\sqrt{d_k}\) absorbed into \(\vect{q}\), the kernel has the Taylor series \(\exp(\vect{q}^{\top}\vect{k})=\sum_{m\ge0}(\vect{q}^{\top}\vect{k})^{m}/m!\). Each power \((\vect{q}^{\top}\vect{k})^{m}\) is a dot product of features built from all products of \(m\) coordinates, as in \((\vect{q}^{\top}\vect{k})^{2}=\sum_{a,a'}(q_a q_{a'})(k_a k_{a'})\), so the series gives an exact feature map with such features for every \(m\), infinitely many in all. Changing to a finite factorization changes the kernel, or approximates it.1 The state preserves the chosen kernel’s readout for every query, but not the individual stored pairs: a discarded row cannot be revisited. The traversal equality is exact for the chosen factorized kernel, not a proof that finite-state linear attention reproduces exact softmax for arbitrary prefixes.
Solver 3: take one gradient step and get the delta rule
Now restrict the predictor to a scalar linear map \(M(\vect{q})=\vect{h}^{\top}\vect{q}\) and let the solver take one SGD step on only the newest pair. Its instantaneous loss and gradient are
Each outer product writes the residual left by the current key. The update changes a query’s readout in proportion to its inner product with that key, \(\matr{H}_t\vect{q}-\matr{H}_{t-1}\vect{q}=\eta_t(\vect{v}_t-\matr{H}_{t-1}\vect{k}_t)(\vect{k}_t^{\top}\vect{q})\), so a query orthogonal to the key reads the same value before and after the update. DeltaNet turns that classical online least-squares step into a sequence layer. Expanding the update gives \(\matr{H}_t=\matr{H}_{t-1}(\matr{I}-\eta_t\vect{k}_t\vect{k}_t^{\top})+\eta_t\vect{v}_t\vect{k}_t^{\top}\), where the transition matrix acts on the state from the right. In transposed form, \(\matr{H}_t^{\top}=(\matr{I}-\eta_t\vect{k}_t\vect{k}_t^{\top})\matr{H}_{t-1}^{\top}+\eta_t\vect{k}_t\vect{v}_t^{\top}\), exposing a state-space form where \(\matr{A}_t=\matr{I}-\eta_t\vect{k}_t\vect{k}_t^{\top}\) acts on the key space from the left and the input write is the outer product \(\eta_t\vect{k}_t\vect{v}_t^{\top}\). The state transition is therefore determined by the current token’s learned key.
Exponential history weights \(w_{t,\tau}=\gamma^{t-\tau}\) introduce forgetting into the least-squares objective, but its exact minimizer generally requires a recursive least-squares covariance state. Writing \(\gamma\matr{H}_{t-1}\) into a one-step delta recurrence is a fading-memory solver choice, not an algebraic consequence of those weights. Gates can make that retention and the step size depend on the current token.
Such gates link this recurrence to the wider state-space model (SSM) family (connected to the parallel-recurrence bridge of Exercise 8 of Chapter 12). Mamba makes parts of its state transition, input injection, and readout depend on the token; in the regression frame, those mechanisms play roles analogous to a learnable schedule for what to keep and what to write. Gated DeltaNet adds learned gating around delta-style updates. That reading is an analogy, not a claim that Mamba is literally obtained by differentiating the shared regression objective. Structured SSMs also use different state parameterizations and can cost less, in retained state and per-token work, than the dense outer-product recurrence here.
Retained state and per-token work
Figure 17.1: The solver map compares retained state and per-token work. Its positions are qualitative; the formulas and direct labels give the asymptotic costs for the stated dense setup.
The asymptotic labels in Figure 17.1 describe this dense setup, not every implementation. Feature width \(r\), head dimensions, low-rank structure, convolutions, and hardware schedules change the constants and sometimes the order of growth.
WarningTrap: attention’s memory is a dataset, not a hidden box
Attention does not have a separate memory in the recurrent sense. The attention operation is the estimator. During causal decoding, the KV cache is the observed key–value dataset it must retain. A nonparametric query rule keeps a growing dataset so it can form a new local fit. A parametric state instead compresses those data into a fixed-size object. FlashAttention changes how the uncompressed fit is scheduled, but it does not compress the history into a fixed-size state. “Retains every row” does not mean “recalls every association without error.” Softmax still returns a convex mixture whose quality depends on keys, temperature, and interference.
Mechanism test: recall under a fixed capacity
The storage comparison motivates a recall experiment to evaluate how the one-pass delta update behaves as more associations are written into a state of fixed dimension. We store \(N\) random unit key–value pairs, query every stored key, and decode each retrieved vector to the nearest stored value. Exact softmax attention keeps all pairs. A dense delta state has \(d^2\) numbers regardless of \(N\). A selective delta arm receives one extra priority bit and writes ordinary pairs at only one-tenth strength, so the bit marks the pairs that the arm favors.
We developed the study on two groups of seeds. On those groups we fixed \(\eta=0.20\), the 25% priority rate, the 0.10 ordinary write gate, dimensions \((8,16,32)\), and loads \(N/d\in(0.5,1,2,4,8)\). After fixing these settings, we evaluated a third, disjoint group, the held-out group, with 30 repetitions for each dimension and load. All methods in a trial receive the same keys, values, order, queries, and decoder. The code below is the frozen protocol; it runs on CPU in under a second on the reference machine.
Fix the seed, step size, ordinary write gate, three dimensions, five loads, and 30 repetitions.
Define the reusable helpers: ms_unit and ms_decode.
Define the reusable helpers: ms_trial and ms_panel.
Run the sealed synthetic recall-under-capacity study.
Figure 17.2: A sealed synthetic mechanism test. The uncompressed table keeps perfect top-1 identification in this sharp-softmax construction, while the fixed delta state loses associations as \(N/d\) grows. The selective arm receives a priority bit that the other arms lack and trades ordinary recall for priority recall. Keys, values, order, queries, decoder, and feature dimension \(d\) are matched; stored data, side information, and inference arithmetic are not.
At \(N/d=8\), the gate raises priority recall over the plain delta state by 0.387 on average and lowers ordinary recall by 0.124; over the trials at that load, the sample standard deviations of these paired differences are 0.156 and 0.065. The gate favors the retention of priority pairs at the expense of ordinary pairs, and total recall barely moves. Overall gated recall is 0.138 while plain delta recall is 0.134 at that load. At lighter loads the same gate lowers total recall: at \(N/d=0.5\) the gated arm recalls 0.471 of all pairs against 0.988 for the plain state. Given an extra signal, a fixed state can allocate its capacity differently.
These results show interference under the specified delta update as the number of stored pairs grows. They do not establish a universal recall limit for fixed-size recurrent states. Now we can compare the three solvers. Keeping the dataset provides uncompressed access at growing cost. Sufficient statistics give exact streaming evaluation for the chosen factorized kernel. Delta updates instead maintain a fixed-size predictor whose stored associations can interfere. The RNN state has returned as one of these statistical choices.
NoteCheck yourself
Close the book for one minute and list what each solver keeps.
Which solver retains the original key–value rows?
Why does a factorized kernel need both \(\matr{S}_t\) and \(\vect{z}_t\)?
What information can a fixed delta state overwrite as its load grows?
17.2 Okay, so: the solver is part of the architecture
The objective alone does not specify the memory system. Views, history weights, function class, regularizer, and solver jointly define the result.
Softmax attention keeps the dataset for query-dependent reads. It preserves every key–value row, and its read cost grows with the prefix.
A finite kernel feature map admits sufficient state. The pair \((\matr{S}_t,\vect{z}_t)\) reproduces the chosen factorized-kernel traversal without retaining raw rows.
One SGD step yields a delta update. Its fixed matrix writes residuals online, which makes capacity and interference explicit.
Selective retention reallocates a fixed capacity. The sealed recall study shows a gate trading ordinary recall for priority recall, without establishing a universal architecture ranking.
(Pencil.) Starting from the local-constant objective, derive its stationarity equation and normalized solution. Identify where the local-constant restriction enters. Why would an unrestricted function with no regularizer not imply the same average?
(Code.) Reproduce the factorized-kernel sufficient-state identity with a positive feature map of your choice. Assert that the full traversal and the running pair \((\matr{S}_t,\vect{z}_t)\) agree for every prefix. Which assertion fails if you omit \(\vect{z}_t\)?
(Pencil.) Derive the delta recurrence from one SGD step. Then multiply the old state by \(\gamma\). Explain why this is a fading-memory solver choice rather than the exact minimizer of exponentially weighted least squares.
(Code.) Sweep the capacity study over at least five state widths \(d\). Preserve the sealed-seed protocol, plot recall against both \(N\) and \(N/d\), and report where the curves align. Do not call top-1 identification exact value recall.
(Audit.) For each solver in Figure 17.1, record state size, update cost, query cost, and information that cannot be reconstructed. Identify what is compute-matched and storage-matched, then design one matched test for a claim you would be willing to make.
We can cut the series off after an even power, which keeps the kernel positive, or use \(r\) positive features built from random projections, chosen so that \(\phi(\vect{q})^{\top}\phi(\vect{k})\) equals the kernel on average over the random draw (Choromanski et al.). In both cases the relative error can rise quickly as \(\norm{\vect{q}}\) and \(\norm{\vect{k}}\) grow.↩︎