def overwrite_recall(write, num_writes, d=64, num_keys=8, num_values=32,
trials=200, seed=0):
"""Recall of the latest value after every key is written num_writes
times."""
rng = np.random.default_rng(seed)
codebook = rng.standard_normal((num_values, d))
codebook /= np.linalg.norm(codebook, axis=1, keepdims=True)
recall = 0
for _ in range(trials):
keys = np.linalg.qr(rng.standard_normal((d, num_keys)))[0].T # Rows
S = np.zeros((d, d))
for _ in range(num_writes):
ids = rng.integers(0, num_values, num_keys)
for k, v in zip(keys, codebook[ids]):
S = write(S, k, v)
reads = keys @ S.T # Row j is S k_j
recall += ((reads @ codebook.T).argmax(1) == ids).mean() / trials
return recall
additive = lambda S, k, v: S + np.outer(v, k)
writes = [1, 2, 4, 8]
print('additive:', ' '.join(f'{overwrite_recall(additive, R):.2f}'
for R in writes))12.7 The Delta Rule
The additive matrix memories of Section 12.6 store each new pair by adding \(\mathbf{v}_t \mathbf{k}_t^\top\) to whatever is already in \(\mathbf{S}_{t-1}\). That works as long as every key is bound only once. Real text and code frequently rebind keys: a program assigns rate = 0.05 and later updates rate = 0.07; a story moves a character from Paris to Rome. Under additive writes, querying a key that has been written twice returns the sum of its old and new values, and repeated updates bury the latest value under stale ones. How can a fixed-size matrix memory overwrite the value stored under a key?
The answer is to read before writing: compute what the memory currently predicts for \(\mathbf{k}_t\) (\(\hat{\mathbf{v}}_t = \mathbf{S}_{t-1}\mathbf{k}_t\)) and write only the prediction error \(\beta_t(\mathbf{v}_t - \hat{\mathbf{v}}_t)\mathbf{k}_t^\top\). This delta rule (Widrow and Hoff 1960; Schlag et al. 2021) performs one online step of gradient descent on the squared recall loss \(\frac{1}{2}\|\mathbf{S}\mathbf{k}_t - \mathbf{v}_t\|^2\) during the forward pass. Below we derive the delta rule’s projection geometry, measure both its rebinding benefit and its signal-erosion cost on random vs. correlated keys, combine it with scalar decay in GatedDeltaNet (Yang et al. 2025) evaluated via a chunked triangular solve (Yang et al. 2024), and conclude with a unified view of sequence memories as online regression solvers.
12.7.1 Additive Writes
12.7.1.1 A Key Written Twice
First let us quantify how additive writes fail when a key is rebound. If a unit key \(\mathbf{k}\) is written \(R\) times with values \(\mathbf{v}^{(1)}, \ldots, \mathbf{v}^{(R)}\), an additive memory returns their unweighted sum:
\[ \mathbf{S}\mathbf{k} = \mathbf{v}^{(1)} + \mathbf{v}^{(2)} + \cdots + \mathbf{v}^{(R)}, \tag{12.7.1}\]
plus cross-key interference \(\sum_i (\mathbf{k}_i^\top \mathbf{k})\mathbf{v}_i\). A scalar decay \(a_t \in (0, 1)\) attenuates older values relative to newer ones, but it decays all keys of the same age indiscriminately—fading facts that were written once just as fast as stale values of rebound keys (Exercise 2).
To isolate rebinding from cross-key interference, overwrite_recall tests 8 mutually orthonormal keys in \(\mathbb{R}^{64}\), writing each key \(R \in \{1, 2, 4, 8\}\) times with values drawn from a 32-vector unit codebook and measuring how often the nearest codebook neighbor to \(\mathbf{S}\mathbf{k}\) matches the latest value \(\mathbf{v}^{(R)}\).
additive: 1.00 0.51 0.27 0.21
def overwrite_recall(write, num_writes, d=64, num_keys=8, num_values=32,
trials=200, seed=0):
"""Recall of the latest value after every key is written num_writes
times."""
rng = np.random.default_rng(seed)
codebook = rng.standard_normal((num_values, d))
codebook /= np.linalg.norm(codebook, axis=1, keepdims=True)
recall = 0
for _ in range(trials):
keys = np.linalg.qr(rng.standard_normal((d, num_keys)))[0].T # Rows
S = np.zeros((d, d))
for _ in range(num_writes):
ids = rng.integers(0, num_values, num_keys)
for k, v in zip(keys, codebook[ids]):
S = write(S, k, v)
reads = keys @ S.T # Row j is S k_j
recall += ((reads @ codebook.T).argmax(1) == ids).mean() / trials
return recall
additive = lambda S, k, v: S + np.outer(v, k)
writes = [1, 2, 4, 8]
print('additive:', ' '.join(f'{overwrite_recall(additive, R):.2f}'
for R in writes))additive: 1.00 0.51 0.27 0.21
Even with zero interference between the 8 orthonormal keys in \(\mathbb{R}^{64}\), additive recall drops from \(1.00\) at \(R = 1\) to \(0.51\) at \(R = 2\) (a coin toss between the two summed values) and \(0.21\) at \(R = 8\) (Exercise 1).
12.7.2 Writes as Gradient Steps
12.7.2.1 The Delta Rule
To replace the value bound to \(\mathbf{k}_t\) while disturbing other directions as little as possible, we measure the memory’s squared prediction error on the incoming pair \((\mathbf{k}_t, \mathbf{v}_t)\):
\[ \ell_t(\mathbf{S}) = \tfrac{1}{2}\, \|\mathbf{S}\mathbf{k}_t - \mathbf{v}_t\|^2, \tag{12.7.2}\]
and take one gradient descent step \(\mathbf{S}_t = \mathbf{S}_{t-1} - \beta_t \nabla_{\mathbf{S}} \ell_t(\mathbf{S}_{t-1})\) with step size (write strength) \(\beta_t\):
\[ \mathbf{S}_t = \mathbf{S}_{t-1} - \beta_t (\mathbf{S}_{t-1}\mathbf{k}_t - \mathbf{v}_t)\mathbf{k}_t^\top. \tag{12.7.3}\]
This is the delta rule (Widrow and Hoff 1960; Schlag et al. 2021): read the current prediction \(\hat{\mathbf{v}}_t = \mathbf{S}_{t-1}\mathbf{k}_t\), and add the rank-one correction \(\beta_t(\mathbf{v}_t - \hat{\mathbf{v}}_t)\mathbf{k}_t^\top\). Notice that this gradient step occurs inside the forward pass on every token at both training and inference time. For a unit key \(\|\mathbf{k}_t\| = 1\), querying \(\mathbf{k}_t\) immediately after Equation 12.7.3 returns \(\mathbf{S}_t \mathbf{k}_t = (1 - \beta_t)\hat{\mathbf{v}}_t + \beta_t \mathbf{v}_t\)—an exact replacement when \(\beta_t = 1\) and a convex blend when \(\beta_t \in (0, 1)\). (By contrast, the additive write \(\mathbf{v}_t \mathbf{k}_t^\top\) is a gradient ascent step on the linear alignment \(\mathbf{v}_t^\top \mathbf{S}\mathbf{k}_t\), which has no saturation point.)
12.7.2.2 The Transition
Factoring \(\mathbf{S}_{t-1}\) out of Equation 12.7.3 exposes the matrix transition applied to the existing memory:
\[ \mathbf{S}_t = \mathbf{S}_{t-1}(\mathbf{I} - \beta_t \mathbf{k}_t \mathbf{k}_t^\top) + \beta_t \mathbf{v}_t \mathbf{k}_t^\top. \tag{12.7.4}\]
For a unit key \(\mathbf{k}_t\), the symmetric matrix \(\mathbf{I} - \beta_t \mathbf{k}_t \mathbf{k}_t^\top\) fixes every subspace orthogonal to \(\mathbf{k}_t\) (eigenvalue \(1\)) and scales the direction \(\mathbf{k}_t\) by eigenvalue \(1 - \beta_t\) (Figure 12.7.1):
- \(\beta_t = 0\): identity (no write);
- \(\beta_t \in (0, 1)\): partial contraction along \(\mathbf{k}_t\);
- \(\beta_t = 1\): orthogonal projection \(\mathbf{I} - \mathbf{k}_t \mathbf{k}_t^\top\), completely erasing the \(\mathbf{k}_t\) component before writing \(\mathbf{v}_t \mathbf{k}_t^\top\);
- \(\beta_t = 2\): Householder reflection \(\mathbf{I} - 2\mathbf{k}_t \mathbf{k}_t^\top\) (eigenvalue \(-1\)), reversing the sign along \(\mathbf{k}_t\).
Two consequences follow from the eigenvalue \(1 - \beta_t\|\mathbf{k}_t\|^2\):
- Unit-norm keys prevent instability: With \(\|\mathbf{k}_t\| = 1\) and \(\beta_t \in [0, 2]\), all eigenvalues of the transition lie in \([-1, 1]\), so homogeneous memory states never blow up geometrically.
- Negative eigenvalues enable modulo-2 counting (parity): When \(\beta_t \in [0, 1]\), all transition eigenvalues are non-negative, which in finite precision cannot track parity over arbitrary sequence lengths (Grazzi et al. 2025). Extending \(\beta_t\) to \(2\) allows reflections (eigenvalue \(-1\)) that toggle a stored state on each counted token, computing exact parity at any length. Section 12.7.3.5 tests whether a trained layer finds this solution.
12.7.2.3 The Cost of Correction
On orthonormal keys, \(\beta_t = 1\) erases stale values on rebound keys without touching any other key. What happens when \(n > d_k\) or keys are random unit vectors so that distinct keys \(\mathbf{k}_i\) and \(\mathbf{k}_t\) have non-zero overlap \(\mathbf{k}_t^\top \mathbf{k}_i\)? Each subsequent delta step along \(\mathbf{k}_t\) projects out the \(\mathbf{k}_t\)-component of \(\mathbf{v}_i \mathbf{k}_i^\top\), shrinking key \(i\)’s stored signal by \(1 - (\mathbf{k}_t^\top \mathbf{k}_i)^2 \approx 1 - 1/d_k\) per step—so after \(m\) later writes, only \((1 - 1/d_k)^m \approx e^{-m/d_k}\) of an old pair’s signal survives.
To see when targeted erasure helps and when it hurts, delta_rule(beta) implements online delta writes and correction_cost measures both squared read error and nearest-neighbor recall at width \(d = 64\) across multiple write rounds and key correlations:
def delta_rule(beta):
"""The memory after writing the pairs in order with the delta rule."""
def fit(K, V):
S = np.zeros((V.shape[1], K.shape[1]))
for k, v in zip(K, V):
S = S + beta * np.outer(v - S @ k, k)
return S
return fit
def correction_cost(memories, num_keys, writes=1, orthonormal=False, rho=0,
d=64, num_values=256, trials=20, seed=0):
"""Squared read error and recall of the latest value when each of
num_keys keys is written `writes` times, for each memory."""
rng = np.random.default_rng(seed)
unit = lambda X: X / np.linalg.norm(X, axis=-1, keepdims=True)
codebook = unit(rng.standard_normal((num_values, d)))
error, recall = dict.fromkeys(memories, 0), dict.fromkeys(memories, 0)
for _ in range(trials):
if orthonormal:
keys = np.linalg.qr(rng.standard_normal((d, num_keys)))[0].T
else: # Random unit keys that share one direction with weight rho
keys = unit(np.sqrt(1 - rho**2) * unit(rng.standard_normal(
(num_keys, d))) + rho * unit(rng.standard_normal(d)))
ids = rng.integers(0, num_values, (writes, num_keys)) # Row = round
K, V = np.tile(keys, (writes, 1)), codebook[ids.ravel()]
for name, fit in memories.items():
reads = keys @ fit(K, V).T # Row j is S k_j
error[name] += ((reads - codebook[ids[-1]]) ** 2).sum(1).mean()
recall[name] += ((reads @ codebook.T).argmax(1) == ids[-1]).mean()
return ({name: e / trials for name, e in error.items()},
{name: r / trials for name, r in recall.items()})def delta_rule(beta):
"""The memory after writing the pairs in order with the delta rule."""
def fit(K, V):
S = np.zeros((V.shape[1], K.shape[1]))
for k, v in zip(K, V):
S = S + beta * np.outer(v - S @ k, k)
return S
return fit
def correction_cost(memories, num_keys, writes=1, orthonormal=False, rho=0,
d=64, num_values=256, trials=20, seed=0):
"""Squared read error and recall of the latest value when each of
num_keys keys is written `writes` times, for each memory."""
rng = np.random.default_rng(seed)
unit = lambda X: X / np.linalg.norm(X, axis=-1, keepdims=True)
codebook = unit(rng.standard_normal((num_values, d)))
error, recall = dict.fromkeys(memories, 0), dict.fromkeys(memories, 0)
for _ in range(trials):
if orthonormal:
keys = np.linalg.qr(rng.standard_normal((d, num_keys)))[0].T
else: # Random unit keys that share one direction with weight rho
keys = unit(np.sqrt(1 - rho**2) * unit(rng.standard_normal(
(num_keys, d))) + rho * unit(rng.standard_normal(d)))
ids = rng.integers(0, num_values, (writes, num_keys)) # Row = round
K, V = np.tile(keys, (writes, 1)), codebook[ids.ravel()]
for name, fit in memories.items():
reads = keys @ fit(K, V).T # Row j is S k_j
error[name] += ((reads - codebook[ids[-1]]) ** 2).sum(1).mean()
recall[name] += ((reads @ codebook.T).argmax(1) == ids[-1]).mean()
return ({name: e / trials for name, e in error.items()},
{name: r / trials for name, r in recall.items()})We compare four memory rules (additive, delta, β = 1, delta, β = 0.5, and offline least squares, where np.linalg.lstsq minimizes \(\sum_{s} \|\mathbf{S}\mathbf{k}_s - \mathbf{v}_s\|^2\) over all pairs simultaneously) across three regimes: (1) 8 orthonormal keys written 4 times each, (2) \(n \in \{32, 64, 128, 256\}\) independent random unit keys written once, and (3) 64 correlated keys (\(\rho = 0.5\)) written once:
memories = {'additive': lambda K, V: V.T @ K, # Sum of the v k^T
'delta, β = 1': delta_rule(1), 'delta, β = 0.5': delta_rule(0.5),
'least squares': lambda K, V: np.linalg.lstsq(K, V)[0].T}
cases = {'8 orthonormal keys, 4 writes': dict(num_keys=8, writes=4,
orthonormal=True),
**{f'{n} keys': dict(num_keys=n) for n in (32, 64, 128, 256)},
'64 keys, ρ = 0.5': dict(num_keys=64, rho=0.5)}
results = {case: correction_cost(memories, **args)
for case, args in cases.items()}
for i, measure in enumerate(['squared read error', 'recall']):
print(f'{measure:28s}', ''.join(f'{name:>15s}' for name in memories))
for case, result in results.items():
print(f'{case:28s}', ''.join(f'{result[i][name]:15.2f}'
for name in memories))squared read error additive delta, β = 1 delta, β = 0.5 least squares
8 orthonormal keys, 4 writes 2.98 0.00 0.33 0.74
32 keys 0.49 0.29 0.37 0.00
64 keys 0.98 0.60 0.49 0.00
128 keys 1.99 1.06 0.67 0.50
256 keys 3.94 1.49 0.89 0.75
64 keys, ρ = 0.5 5.82 0.76 0.61 0.00
recall additive delta, β = 1 delta, β = 0.5 least squares
8 orthonormal keys, 4 writes 0.28 1.00 1.00 0.28
32 keys 1.00 1.00 1.00 1.00
64 keys 1.00 0.89 0.99 1.00
128 keys 0.96 0.53 0.82 1.00
256 keys 0.73 0.26 0.45 0.86
64 keys, ρ = 0.5 0.54 0.77 0.89 1.00
memories = {'additive': lambda K, V: V.T @ K, # Sum of the v k^T
'delta, β = 1': delta_rule(1), 'delta, β = 0.5': delta_rule(0.5),
'least squares': lambda K, V: np.linalg.lstsq(K, V)[0].T}
cases = {'8 orthonormal keys, 4 writes': dict(num_keys=8, writes=4,
orthonormal=True),
**{f'{n} keys': dict(num_keys=n) for n in (32, 64, 128, 256)},
'64 keys, ρ = 0.5': dict(num_keys=64, rho=0.5)}
results = {case: correction_cost(memories, **args)
for case, args in cases.items()}
for i, measure in enumerate(['squared read error', 'recall']):
print(f'{measure:28s}', ''.join(f'{name:>15s}' for name in memories))
for case, result in results.items():
print(f'{case:28s}', ''.join(f'{result[i][name]:15.2f}'
for name in memories))squared read error additive delta, β = 1 delta, β = 0.5 least squares
8 orthonormal keys, 4 writes 2.98 0.00 0.33 0.74
32 keys 0.49 0.29 0.37 0.00
64 keys 0.98 0.60 0.49 0.00
128 keys 1.99 1.06 0.67 0.50
256 keys 3.94 1.49 0.89 0.75
64 keys, ρ = 0.5 5.82 0.76 0.61 0.00
recall additive delta, β = 1 delta, β = 0.5 least squares
8 orthonormal keys, 4 writes 0.28 1.00 1.00 0.28
32 keys 1.00 1.00 1.00 1.00
64 keys 1.00 0.89 0.99 1.00
128 keys 0.96 0.53 0.82 1.00
256 keys 0.73 0.26 0.45 0.86
64 keys, ρ = 0.5 0.54 0.77 0.89 1.00
The table highlights the trade-off of online projection:
- Rebinding (
8 orthonormal keys, 4 writes):deltaachieves \(1.00\) recall at both \(\beta = 1\) and \(\beta = 0.5\) (squared error \(0.00\) and \(0.33\)), whereasadditiveand unweightedleast squaresaverage all 4 values bound to each key and score just \(0.28\). - Correlated keys (
64 keys, ρ = 0.5): Because every key shares a common direction,additivepiles every value onto that shared component (squared error \(5.82\), recall \(0.54\)), whereasdeltasubtracts the prediction along the shared direction before writing (recall \(0.77\) at \(\beta = 1\) and \(0.89\) at \(\beta = 0.5\)). - Crowded independent keys (
128 keys,256 keys): Heredelta, β = 1has lower squared error thanadditive(\(1.06\) vs. \(1.99\) at \(n = 128\)), yet lower nearest-neighbor recall (\(0.53\) vs. \(0.96\)). Why? Because shrinking old reads toward \(\mathbf{0}\) lowers their squared error toward \(\|\mathbf{0} - \mathbf{v}_j\|^2 = 1\) while eroding the signal of early pairs relative to later ones. Using a gentler step \(\beta = 0.5\) recovers both lower squared error (\(0.67\)) and much higher recall (\(0.82\)), motivating making \(\beta_t\) an input-dependent gate so the network can use \(\beta_t \approx 1\) to overwrite a rebound key and smaller \(\beta_t\) when accumulating facts.
12.7.3 Gated DeltaNet
12.7.3.1 Decay and Correction
Because the delta rule modifies \(\mathbf{S}_{t-1}\) only along the current key \(\mathbf{k}_t\), directions orthogonal to recent keys never decay on their own. Gated DeltaNet (Yang et al. 2025) combines an input-dependent scalar decay \(a_t \in (0, 1)\) (for global forgetting) with the delta rule’s rank-one directional update (for targeted key overwriting):
\[ \mathbf{S}_t = a_t\, \mathbf{S}_{t-1}(\mathbf{I} - \beta_t \mathbf{k}_t\mathbf{k}_t^\top) + \beta_t \mathbf{v}_t \mathbf{k}_t^\top. \tag{12.7.5}\]
The two gates do different jobs, and their joint settings give the layer three ways to treat a new pair (Figure 12.7.2). With \(a_t\) near zero the layer flushes everything it has stored and keeps only the new pair, which is the right response to a change of topic. With \(a_t \approx 1\) and \(\beta_t = 1\) it replaces the value under the current key and leaves orthogonal keys untouched, as in the rebinding test above. With \(a_t \approx 1\) and a small \(\beta_t\) it moves the read only part of the way toward the new value, so that several writes under similar keys are averaged rather than the last one winning.
12.7.3.2 Chunked Computation
Because the transition \(a_t(\mathbf{I} - \beta_t \mathbf{k}_t \mathbf{k}_t^\top)\) is a \(d_k \times d_k\) matrix rather than a scalar, a naive token-level scan would multiply \(d_k \times d_k\) matrices at \(O(T d_k^3)\) cost. Yang et al. (2024) showed how to evaluate Equation 12.7.5 in chunks of size \(m\) using the WY representation. Rewrite Equation 12.7.5 as an additive decayed update \(\mathbf{S}_t = a_t \mathbf{S}_{t-1} + \mathbf{u}_t \mathbf{k}_t^\top\) with effective corrected value \(\mathbf{u}_t = \beta_t(\mathbf{v}_t - a_t \mathbf{S}_{t-1}\mathbf{k}_t)\). Inside a chunk of length \(m\) starting from initial state \(\mathbf{S}_0\), unrolling \(a_t \mathbf{S}_{t-1}\mathbf{k}_t = \gamma_t \mathbf{S}_0 \mathbf{k}_t + \sum_{s < t} L_{ts}(\mathbf{k}_s^\top \mathbf{k}_t)\mathbf{u}_s\) (where \(L_{ts} = \prod_{r=s+1}^t a_r\) and \(\gamma_t = \prod_{r=1}^t a_r\)) yields a strictly lower-triangular \(m \times m\) linear system for the chunk’s corrected values \(\mathbf{u}_1, \ldots, \mathbf{u}_m\):
\[ \mathbf{u}_t + \beta_t \sum_{s < t} L_{ts}\, (\mathbf{k}_s^\top \mathbf{k}_t)\, \mathbf{u}_s = \beta_t\big(\mathbf{v}_t - \gamma_t \mathbf{S}_0\mathbf{k}_t\big). \]
Because the right-hand side is affine in \(\mathbf{S}_0\), delta_rule_writes solves the unit-lower-triangular \(m \times m\) system \(\mathbf{M} = \mathbf{I} + \textrm{diag}(\boldsymbol{\beta})\,\textrm{tril}_{-1}(\mathbf{L} \odot \mathbf{K}\mathbf{K}^\top)\) in parallel across all chunks and heads for two right-hand sides, \(\mathbf{W} = \mathbf{M}^{-1}(\boldsymbol{\beta} \odot \mathbf{V})\) and \(\mathbf{Z} = \mathbf{M}^{-1}((\boldsymbol{\beta} \odot \boldsymbol{\gamma}) \odot \mathbf{K})\), so that \(\mathbf{U} = \mathbf{W} - \mathbf{Z}\mathbf{S}_0^\top\) once \(\mathbf{S}_0\) is known.
def delta_rule_writes(K, V, beta, log_a):
"""W and Z with corrected values U = W - Z S_0^T, for every chunk.
K: (..., m, d_k); V: (..., m, d_v); beta, log_a: (..., m)
"""
L = d2l.decay_mask(log_a) # Products of decays within the chunk
gamma = torch.exp(log_a.cumsum(-1)).unsqueeze(-1) # Decay since start
beta = beta.unsqueeze(-1)
M = torch.eye(K.shape[-2], device=K.device) + (
beta * L.tril(-1) * (K @ K.mT)) # Lower triangular
W = torch.linalg.solve_triangular(M, beta * V, upper=False)
Z = torch.linalg.solve_triangular(M, beta * gamma * K, upper=False)
return W, Zdef delta_rule_writes(K, V, beta, log_a):
"""W and Z with corrected values U = W - Z S_0^T, for every chunk.
K: (..., m, d_k); V: (..., m, d_v); beta, log_a: (..., m)
"""
L = d2l.decay_mask(log_a) # Products of decays within the chunk
gamma = jnp.exp(log_a.cumsum(-1))[..., None] # Decay since start
beta = beta[..., None]
M = jnp.eye(K.shape[-2]) + (
beta * jnp.tril(L, -1) * (K @ K.mT)) # Lower triangular
W = jax.scipy.linalg.solve_triangular(M, beta * V, lower=True)
Z = jax.scipy.linalg.solve_triangular(M, beta * gamma * K, lower=True)
return W, ZSubstituting \(\mathbf{U} = \mathbf{W} - \mathbf{Z}\mathbf{S}_0^\top\) into the chunk-end state \(\mathbf{S}_m = \gamma_m \mathbf{S}_0 + \mathbf{U}^\top \mathbf{D}\mathbf{K}\) (where \(\mathbf{D}\) is the diagonal matrix of decays to the end of the chunk) expresses the chunk transition as an affine matrix recurrence across the \(T / m\) chunks:
\[ \mathbf{S}_m = \mathbf{S}_0 \mathbf{A} + \mathbf{W}^\top \mathbf{D} \mathbf{K}, \qquad \mathbf{A} = \gamma_m \mathbf{I} - \mathbf{Z}^\top \mathbf{D} \mathbf{K}. \]
Scanning \((\mathbf{A}, \mathbf{W}^\top \mathbf{D}\mathbf{K})\) across the \(T / m\) chunks costs only \((T/m) d_k^3\) operations (matching the intra-chunk \(O(T d_k^2)\) matrix products when \(m \approx d_k\)), after which \(\mathbf{U} = \mathbf{W} - \mathbf{Z}\mathbf{S}_0^\top\) and all outputs \(\mathbf{Y}\) follow in one batched matrix product.
def chunked_delta_rule(Q, K, V, beta, log_a, chunk_size):
"""Outputs y_t = S_t q_t of the gated delta rule, computed in chunks.
Q, K: (batch_size, T, d_k); V: (batch_size, T, d_v);
beta, log_a: (batch_size, T)
"""
B, T, m = Q.shape[0], Q.shape[1], chunk_size
Q, K, V = (X.reshape(B, T // m, m, -1) for X in (Q, K, V))
beta, log_a = beta.reshape(B, T // m, m), log_a.reshape(B, T // m, m)
W, Z = delta_rule_writes(K, V, beta, log_a)
L, cum = d2l.decay_mask(log_a), log_a.cumsum(-1)
# Each chunk maps the memory S at its start to S A + W^T D K at its end
to_end = torch.exp(cum[..., -1:] - cum).unsqueeze(-1)
I = torch.eye(K.shape[-1], device=K.device)
A = torch.exp(cum[..., -1, None, None]) * I - (Z * to_end).mT @ K
def combine(earlier, later): # A scan over chunks, with matrix products
(A1, W1), (A2, W2) = earlier, later
return A1 @ A2, W1 @ A2 + W2
W_end = d2l.associative_scan(combine, (A, (W * to_end).mT @ K))[1]
S = torch.cat([torch.zeros_like(W_end[:, :1]), W_end[:, :-1]], 1)
U = W - Z @ S.mT # Corrected values, with the memory at each start
Y = torch.exp(cum).unsqueeze(-1) * (Q @ S.mT) + (L * (Q @ K.mT)) @ U
return Y.reshape(B, T, -1)def chunked_delta_rule(Q, K, V, beta, log_a, chunk_size):
"""Outputs y_t = S_t q_t of the gated delta rule, computed in chunks.
Q, K: (batch_size, T, d_k); V: (batch_size, T, d_v);
beta, log_a: (batch_size, T)
"""
B, T, m = Q.shape[0], Q.shape[1], chunk_size
Q, K, V = (X.reshape(B, T // m, m, -1) for X in (Q, K, V))
beta, log_a = beta.reshape(B, T // m, m), log_a.reshape(B, T // m, m)
W, Z = delta_rule_writes(K, V, beta, log_a)
L, cum = d2l.decay_mask(log_a), log_a.cumsum(-1)
# Each chunk maps the memory S at its start to S A + W^T D K at its end
to_end = jnp.exp(cum[..., -1:] - cum)[..., None]
I = jnp.eye(K.shape[-1])
A = jnp.exp(cum[..., -1, None, None]) * I - (Z * to_end).mT @ K
def combine(earlier, later): # A scan over chunks, with matrix products
(A1, W1), (A2, W2) = earlier, later
return A1 @ A2, W1 @ A2 + W2
W_end = jax.lax.associative_scan(combine, (A, (W * to_end).mT @ K),
axis=1)[1]
S = jnp.concatenate([jnp.zeros_like(W_end[:, :1]), W_end[:, :-1]], 1)
U = W - Z @ S.mT # Corrected values, with the memory at each start
Y = jnp.exp(cum)[..., None] * (Q @ S.mT) + (L * (Q @ K.mT)) @ U
return Y.reshape(B, T, -1)To verify chunked_delta_rule, we first implement the sequential token-by-token reference delta_rule_recurrent:
def delta_rule_recurrent(Q, K, V, beta, a):
"""The same outputs, one step at a time."""
S, outputs = Q.new_zeros(V.shape[-1], K.shape[-1]), []
for q, k, v, b, a_t in zip(Q, K, V, beta, a):
S = a_t * S
S = S + b * torch.outer(v - S @ k, k)
outputs.append(S @ q)
return torch.stack(outputs)def delta_rule_recurrent(Q, K, V, beta, a):
"""The same outputs, one step at a time."""
def step(S, inputs):
q, k, v, b, a_t = inputs
S = a_t * S
S = S + b * jnp.outer(v - S @ k, k)
return S, S @ q
S = jnp.zeros((V.shape[-1], K.shape[-1]))
return jax.lax.scan(step, S, (Q, K, V, beta, a))[1]We now compare chunked_delta_rule at chunk sizes \(m \in \{16, 64\}\) against delta_rule_recurrent on a random sequence of length \(T = 256\) with unit-normalized keys:
gen = torch.Generator().manual_seed(0) # Local: later training stays unseeded
T, d_k, d_v = 256, 32, 32
Q, V = torch.randn(T, d_k, generator=gen), torch.randn(T, d_v, generator=gen)
K = F.normalize(torch.randn(T, d_k, generator=gen), dim=-1)
beta = torch.rand(T, generator=gen)
a = 0.8 + 0.19 * torch.rand(T, generator=gen)
Y = delta_rule_recurrent(Q, K, V, beta, a)
for m in [16, 64]:
Y_chunked = chunked_delta_rule(Q[None], K[None], V[None], beta[None],
torch.log(a)[None], m)[0]
print(f'chunk size {m}: relative deviation '
f'{(Y_chunked - Y).abs().max() / Y.abs().max():.1e}')chunk size 16: relative deviation 2.1e-07
chunk size 64: relative deviation 3.1e-07
T, d_k, d_v = 256, 32, 32
keys = jax.random.split(jax.random.key(0), 5)
Q = jax.random.normal(keys[0], (T, d_k))
V = jax.random.normal(keys[1], (T, d_v))
K = jax.random.normal(keys[2], (T, d_k))
K = K / jnp.linalg.norm(K, axis=-1, keepdims=True)
beta = jax.random.uniform(keys[3], (T,))
a = 0.8 + 0.19 * jax.random.uniform(keys[4], (T,))
with jax.default_matmul_precision('highest'): # Full float32, not TF32
Y = delta_rule_recurrent(Q, K, V, beta, a)
for m in [16, 64]:
Y_chunked = chunked_delta_rule(Q[None], K[None], V[None], beta[None],
jnp.log(a)[None], m)[0]
print(f'chunk size {m}: relative deviation '
f'{jnp.abs(Y_chunked - Y).max() / jnp.abs(Y).max():.1e}')chunk size 16: relative deviation 2.6e-07
chunk size 64: relative deviation 3.7e-07
The chunked algorithm matches the token-level recurrence to \(\sim 10^{-7}\) relative error.
12.7.3.3 The Layer
GatedDeltaNet subclasses d2l.GatedLinearAttention (Section 12.6), adding only the write-strength projection W_beta (\(\beta_{t,h} = \sigma(\mathbf{w}_{\beta,h}^\top \mathbf{x}_t + b_{\beta,h}) \in (0, 1)\) per head) and overriding memory to call chunked_delta_rule. Every other component (the width-4 causal convolution, \(\ell_2\)-normalized queries and keys, scalar per-head decay, RMS head normalization, and SiLU output gate) is identical.
class GatedDeltaNet(d2l.GatedLinearAttention):
"""Gated linear attention whose memory is written by the delta rule."""
def __init__(self, num_hiddens, num_heads, chunk_size=32, conv_width=4,
timescales=(4, 256)):
super().__init__(num_hiddens, num_heads, chunk_size, conv_width,
timescales)
self.W_beta = nn.Linear(num_hiddens, num_heads) # Write strength
d2l.init_lecun(self.W_beta)
def memory(self, X, Q, K, V, log_a):
beta = d2l.heads_to_batch(torch.sigmoid(self.W_beta(X)),
self.num_heads).squeeze(-1)
return chunked_delta_rule(Q, K, V, beta, log_a, self.chunk_size)class GatedDeltaNet(d2l.GatedLinearAttention):
"""Gated linear attention whose memory is written by the delta rule."""
def __init__(self, num_hiddens, num_heads, chunk_size=32, conv_width=4,
timescales=(4, 256), *, rngs):
super().__init__(num_hiddens, num_heads, chunk_size, conv_width,
timescales, rngs=rngs)
self.W_beta = nnx.Linear(num_hiddens, num_heads, rngs=rngs)
def memory(self, X, Q, K, V, log_a):
beta = d2l.heads_to_batch(jax.nn.sigmoid(self.W_beta(X)),
self.num_heads)[..., 0]
return chunked_delta_rule(Q, K, V, beta, log_a, self.chunk_size)12.7.3.4 Rebinding
Can a trained GatedDeltaNet layer overwrite rebound keys where GatedLinearAttention struggles? We test a single-block SeqLM (\(d = 64\), 4 heads of dimension 16, initial decay timescales \([256, 2048]\)) on d2l.associative_recall with 16 keys drawn from 128 and values from 16, where 8 of the 16 keys are rebound to a new value just 2 writes after their initial binding (num_rebound=8, gap=2). Keeping the gap short ensures the two bindings have nearly the same age, so global age-based decay cannot easily separate the new value from the stale one without also forgetting keys written only once. (We use a single block because a two-block additive model can approximate one delta step across depth; see Exercise 6.)
def rebinding_model(layer, num_hiddens=64, num_heads=4,
vocab_size=16 + 128 + 1):
"""One block of `layer`; tokens: 16 values, 128 keys, the filler."""
return d2l.SeqLM(vocab_size, num_hiddens, [layer(
num_hiddens, num_heads, chunk_size=16, timescales=(256, 2048))])def rebinding_model(layer, num_hiddens=64, num_heads=4,
vocab_size=16 + 128 + 1):
"""One block of `layer`; tokens: 16 values, 128 keys, the filler."""
rngs = nnx.Rngs(d2l.get_key()) # A new initialization each call
return d2l.SeqLM(vocab_size, num_hiddens, [layer(
num_hiddens, num_heads, chunk_size=16, timescales=(256, 2048),
rngs=rngs)], rngs=rngs)Using recall_by_kind to separate accuracy on rebound keys (rebound) from keys written only once (~rebound), we train two seeds each of GatedLinearAttention and GatedDeltaNet on the 16-pair rebinding task:
def recall_by_kind(model, X, Y, rebound):
"""Recall on the queries for keys written twice and for keys written
once; a label of -1 matches no prediction."""
accuracy = lambda mask: float(d2l.query_accuracy(
model, X, np.where(mask, Y, -1))) / mask.mean()
return accuracy(rebound), accuracy(~rebound)
task = dict(num_keys=128, num_values=16, num_rebound=8, gap=2)
test = d2l.associative_recall(np.random.default_rng(1), 2048, 16,
num_steps=64, **task)
print(f'{"":24s}{"parameters":>12s}{"written twice":>16s}'
f'{"written once":>16s}')
for name, layer in (('gated linear attention', d2l.GatedLinearAttention),
('Gated DeltaNet', d2l.GatedDeltaNet)):
models = [rebinding_model(layer) for _ in range(2)] # Two runs
for model in models:
d2l.train_recall(model, pairs=(16,), **task)
twice, once = zip(*[recall_by_kind(model, *test) for model in models])
print(f'{name:24s}{d2l.num_params(models[0]):12,d}'
f'{twice[0]:11.3f} {twice[1]:.3f}{once[0]:11.3f} {once[1]:.3f}') parameters written twice written once
gated linear attention 73,941 0.929 0.859 0.977 0.968
Gated DeltaNet 74,201 0.965 0.969 0.978 0.986
def recall_by_kind(model, X, Y, rebound):
"""Recall on the queries for keys written twice and for keys written
once; a label of -1 matches no prediction."""
accuracy = lambda mask: float(d2l.query_accuracy(
model, X, np.where(mask, Y, -1))) / mask.mean()
return accuracy(rebound), accuracy(~rebound)
task = dict(num_keys=128, num_values=16, num_rebound=8, gap=2)
test = d2l.associative_recall(np.random.default_rng(1), 2048, 16,
num_steps=64, **task)
print(f'{"":24s}{"parameters":>12s}{"written twice":>16s}'
f'{"written once":>16s}')
for name, layer in (('gated linear attention', d2l.GatedLinearAttention),
('Gated DeltaNet', d2l.GatedDeltaNet)):
models = [rebinding_model(layer) for _ in range(2)] # Two runs
for model in models:
d2l.train_recall(model, pairs=(16,), **task)
twice, once = zip(*[recall_by_kind(model, *test) for model in models])
print(f'{name:24s}{d2l.num_params(models[0]):12,d}'
f'{twice[0]:11.3f} {twice[1]:.3f}{once[0]:11.3f} {once[1]:.3f}') parameters written twice written once
gated linear attention 73,941 0.895 0.910 0.968 0.977
Gated DeltaNet 74,201 0.977 0.990 0.987 0.996
Adding the 260-parameter W_beta head raises recall on rebound keys from about \(0.9\) (gated linear attention) to \(0.96\) or more (Gated DeltaNet), bringing rebound keys within about \(2\) percentage points of keys written only once.
12.7.3.5 State Tracking
Every experiment so far asked a memory to store something and to return it later. A different demand is to track a state that every token may change: which cup hides the ball after a series of swaps, whether a quotation is open, or, in the simplest case, whether the number of ones read so far is odd or even. Parity needs a single bit of state. A 1 flips it and a 0 leaves it alone. Nothing has to be kept for long, but nothing may be skipped either, since one missed bit makes every later answer wrong.
A GRU solves this task the way a program would. Its gates see the previous state \(\mathbf{h}_{t-1}\), so one step can compute “flip if the input is 1”. The linear recurrences of this chapter gave that up for parallel training: their decays and writes depend on the input alone (Section 12.3). To flip a stored bit, such a recurrence has to multiply a coordinate of its state by a negative number, and the decay \(\mathbf{z}_t \in (0, 1)\) of a minGRU can shrink a coordinate but never change its sign. The delta rule is under the same restriction as long as its write strength is a sigmoid, because the transition Equation 12.7.4 then has an eigenvalue \(1 - \beta_t \in (0, 1)\) along the key. With \(\beta_t \in (0, 2)\) the eigenvalue can reach \(-1\). A layer that writes a value \(\mathbf{v}\) with \(\beta_t = 2\) under one fixed key \(\mathbf{k}\) on every 1, and writes nothing on a 0, changes its read by \(\mathbf{S}_t\mathbf{k} = 2\mathbf{v} - \mathbf{S}_{t-1}\mathbf{k}\) on every 1. Starting from an empty memory, the read alternates between \(2\mathbf{v}\) and \(\mathbf{0}\), which is the parity.
The construction exists, then, but does training find it? We train a d2l.SeqLM of two blocks and width 64, the depth Grazzi et al. (2025) use for this task, on random strings of 64 bits to output, at every step, the parity of the bits so far. We then test it on strings of 256 bits, which separates a model that has learned the rule from one that has only fit the lengths it was trained on. Four mixers compete: a GRU, a minGRU, GatedDeltaNet, and GatedDeltaNetReflect, which doubles the sigmoid of the write strength and is otherwise the same layer. If the argument above is right, the GRU and the layer with \(\beta_t \in (0, 2)\) should be correct at every position, including those beyond the training length, while the minGRU and the sigmoid delta rule should fail, and fall to the chance level of \(0.5\) once the strings are longer than those they were trained on.
class GatedDeltaNetReflect(d2l.GatedDeltaNet):
"""Gated DeltaNet with write strengths in (0, 2), so that the transition
can reflect the memory along the key."""
def memory(self, X, Q, K, V, log_a):
beta = 2 * d2l.heads_to_batch(torch.sigmoid(self.W_beta(X)),
self.num_heads).squeeze(-1)
return chunked_delta_rule(Q, K, V, beta, log_a, self.chunk_size)
def running_parity(rng, batch_size, num_steps):
"""Random bits and, at every step, the parity of the bits so far."""
X = rng.integers(0, 2, (batch_size, num_steps))
return X, np.cumsum(X, 1) % 2
def train_parity(model, num_updates=1000):
"""Train on strings of 64 bits; return the accuracy on positions 1-64
and on positions 65-256 of new strings of 256 bits."""
rng = np.random.default_rng()
model.to(d2l.try_gpu())
optimizer = torch.optim.AdamW(model.parameters(), lr=1e-2,
weight_decay=0.01)
scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, lambda t: (
d2l.cosine_warmup(t, num_updates, num_updates // 10)))
d2l.train_queries(model, lambda step: running_parity(rng, 128, 64),
num_updates, optimizer, scheduler)
X, Y = running_parity(np.random.default_rng(1), 1024, 256)
return (float(d2l.query_accuracy(model, X[:, :64], Y[:, :64])),
float(d2l.query_accuracy(model, X, Y[:, 64:])))
d = 64 # Width; the delta rules have 4 heads of size 16
parity_mixers = {
'GRU': lambda: d2l.Recurrent(d2l.init_lecun(
nn.GRU(d, d, batch_first=True))),
'minGRU': lambda: d2l.MinGRU(d, d),
'Gated DeltaNet': lambda: d2l.GatedDeltaNet(
d, 4, chunk_size=32, timescales=(256, 2048)),
'Gated DeltaNet, 2σ': lambda: GatedDeltaNetReflect(
d, 4, chunk_size=32, timescales=(256, 2048))}
def parity_model(mixer): # Tokens and outputs: the bits 0 and 1
return d2l.SeqLM(2, d, [mixer(), mixer()]) # Two blocksclass GatedDeltaNetReflect(d2l.GatedDeltaNet):
"""Gated DeltaNet with write strengths in (0, 2), so that the transition
can reflect the memory along the key."""
def memory(self, X, Q, K, V, log_a):
beta = 2 * d2l.heads_to_batch(jax.nn.sigmoid(self.W_beta(X)),
self.num_heads)[..., 0]
return chunked_delta_rule(Q, K, V, beta, log_a, self.chunk_size)
def running_parity(rng, batch_size, num_steps):
"""Random bits and, at every step, the parity of the bits so far."""
X = rng.integers(0, 2, (batch_size, num_steps))
return X, np.cumsum(X, 1) % 2
def train_parity(model, num_updates=1000):
"""Train on strings of 64 bits; return the accuracy on positions 1-64
and on positions 65-256 of new strings of 256 bits."""
rng = np.random.default_rng()
schedule = lambda t: 1e-2 * d2l.cosine_warmup(t, num_updates,
num_updates // 10)
optimizer = nnx.Optimizer(model, optax.chain(
optax.clip_by_global_norm(1.0),
optax.adamw(schedule, weight_decay=0.01)), wrt=nnx.Param)
X, Y = running_parity(np.random.default_rng(1), 1024, 256)
with jax.default_matmul_precision('highest'): # Full float32, not TF32
d2l.train_queries(model, lambda step: running_parity(rng, 128, 64),
num_updates, optimizer)
return (float(d2l.query_accuracy(model, X[:, :64], Y[:, :64])),
float(d2l.query_accuracy(model, X, Y[:, 64:])))
d = 64 # Width; the delta rules have 4 heads of size 16
lecun = nnx.initializers.lecun_normal() # For the recurrent matrix
parity_mixers = {
'GRU': lambda rngs: nnx.RNN(nnx.GRUCell(
d, d, recurrent_kernel_init=lecun, rngs=rngs), unroll=8),
'minGRU': lambda rngs: d2l.MinGRU(d, d, rngs=rngs),
'Gated DeltaNet': lambda rngs: d2l.GatedDeltaNet(
d, 4, chunk_size=32, timescales=(256, 2048), rngs=rngs),
'Gated DeltaNet, 2σ': lambda rngs: GatedDeltaNetReflect(
d, 4, chunk_size=32, timescales=(256, 2048), rngs=rngs)}
def parity_model(mixer): # Tokens and outputs: the bits 0 and 1
rngs = nnx.Rngs(d2l.get_key()) # A new initialization each call
return d2l.SeqLM(2, d, [mixer(rngs), mixer(rngs)], # Two blocks
rngs=rngs)We train two runs of each mixer and report the accuracy on positions 1–64, the lengths seen in training, and on positions 65–256:
print(f'{"":24s}{"positions 1-64":>16s}{"65-256":>12s}')
for name, mixer in parity_mixers.items():
(a, b), (c, e) = [train_parity(parity_model(mixer)) for _ in range(2)]
print(f'{name:24s}{a:11.2f}/{c:.2f}{b:7.2f}/{e:.2f}') positions 1-64 65-256
GRU 1.00/1.00 1.00/1.00
minGRU 0.52/0.56 0.50/0.50
Gated DeltaNet 0.80/0.81 0.50/0.50
Gated DeltaNet, 2σ 1.00/1.00 1.00/1.00
print(f'{"":24s}{"positions 1-64":>16s}{"65-256":>12s}')
for name, mixer in parity_mixers.items():
(a, b), (c, e) = [train_parity(parity_model(mixer)) for _ in range(2)]
print(f'{name:24s}{a:11.2f}/{c:.2f}{b:7.2f}/{e:.2f}') positions 1-64 65-256
GRU 1.00/1.00 1.00/1.00
minGRU 0.58/0.55 0.50/0.50
Gated DeltaNet 0.74/0.81 0.50/0.50
Gated DeltaNet, 2σ 1.00/1.00 0.99/1.00
The GRU is correct at every position in both runs, at the training lengths and beyond them. The minGRU and the sigmoid delta rule are not. On the first 64 positions they sit above chance, the minGRU a little above \(0.5\) and Gated DeltaNet at about \(0.75\) to \(0.8\), but neither has learned the rule: beyond position 64 both answer at \(0.50\), a coin toss. Doubling the write strength changes this. GatedDeltaNetReflect reaches \(1.00\) on the training lengths and keeps that accuracy out to 256 bits. This is the typical outcome and not a lucky pair of runs: of some fifty further runs, all but one generalized in this way, and the exception still scored about \(0.9\) beyond position 64. Linearity, then, is not the obstacle. What the linear recurrences gave up is an update that depends on the state, and whether a matrix memory can track a state anyway is decided by the range of its transition’s eigenvalues. The minGRU has neither a negative eigenvalue nor a gate that sees its state. A second block does not supply the missing sign, and the model fails.
The reflection is delicate, though. A doubled sigmoid only approaches \(\beta_t = 2\), so every flip also shrinks the stored bit a little, and a run that stops short of 2 loses accuracy on long strings (Exercise 5). Harder state tracking, such as following several cups through their swaps, needs more than one reflection per token.
12.7.4 Memory as Regression
Stepping back, every matrix memory in this chapter, as well as softmax attention, can be understood as fitting a regression predictor from keys \(\mathbf{K}_t \in \mathbb{R}^{t \times d_k}\) to values \(\mathbf{V}_t \in \mathbb{R}^{t \times d_v}\) on the fly as a sequence is read (Wang et al. 2025). The exact linear least-squares minimizer of \(\sum_{s \le t} \|\mathbf{S}\mathbf{k}_s - \mathbf{v}_s\|^2\) is:
\[ \mathbf{S}_t^\star = \mathbf{V}_t^\top \mathbf{K}_t\, (\mathbf{K}_t^\top \mathbf{K}_t)^{-1}, \tag{12.7.6}\]
where \((\mathbf{K}_t^\top \mathbf{K}_t)^{-1}\) is replaced by the pseudoinverse when \(t < d_k\). Look at the two factors of Equation 12.7.6 (Table 12.7.1):
- Linear attention keeps only the first factor, the unnormalized cross-moment \(\mathbf{V}_t^\top \mathbf{K}_t = \sum_{s \le t} \mathbf{v}_s \mathbf{k}_s^\top\), omitting the Gram inverse \((\mathbf{K}_t^\top \mathbf{K}_t)^{-1}\) that decorrelates overlapping keys.
- The delta rule takes one online stochastic gradient step per token toward Equation 12.7.6, while Gated DeltaNet adds weight decay (\(a_t < 1\)) before each step. Replacing the explicit gradient step by the proximal implicit step \(\arg\min_{\mathbf{S}} \frac{1}{2}\|\mathbf{S} - \mathbf{S}_{t-1}\|^2 + \frac{\beta_t}{2}\|\mathbf{S}\mathbf{k}_t - \mathbf{v}_t\|^2\) yields the normalized step size \(\beta_t / (1 + \beta_t\|\mathbf{k}_t\|^2)\) of Longhorn (Liu et al. 2024) (Exercise 3), while carrying \((\mathbf{K}_t^\top \mathbf{K}_t + \lambda\mathbf{I})^{-1}\) explicitly yields recursive least squares (Exercise 4).
- Softmax attention performs nonparametric Nadaraya–Watson kernel regression (Section 10.1.2) at query time over all stored pairs, avoiding parametric compression at the cost of an \(O(t)\) KV cache.
The exact fit can also be kept up to date one pair at a time. Each pair changes \(\mathbf{K}_t^\top \mathbf{K}_t\) by the rank-one term \(\mathbf{k}_t\mathbf{k}_t^\top\), so the Sherman–Morrison formula (Section 33.2.3.5) updates the inverse without a new matrix inversion. This is recursive least squares. It carries a second state of size \(d_k \times d_k\) next to the memory (Exercise 4).
| Memory | What it fits | How | State |
|---|---|---|---|
| Softmax attention | kernel-weighted average of all values | at query time | all pairs |
| Linear attention | \(\mathbf{V}^\top\mathbf{K}\), least squares without the key correction | one addition per pair | \(d_v \times d_k\) |
| Gated linear attention | the same, weighted toward recent pairs | one addition per pair | \(d_v \times d_k\) |
| Delta rule | least squares, approximately | one gradient step per pair | \(d_v \times d_k\) |
| Gated DeltaNet | least squares with weight decay, approximately | one gradient step per pair | \(d_v \times d_k\) |
In all these architectures, learning operates at two timescales: the fast weights of the state \(\mathbf{S}_t\) fit the key–value associations of the current context during the forward pass, while the slow weights of the network (\(\mathbf{W}_{qkv}, \mathbf{W}_a, \mathbf{W}_\beta, \ldots\)) are trained across sequences by backpropagation to produce keys, values, queries, and step sizes that make that online fit effective. Even with an optimal write rule, however, a \(d_v \times d_k\) matrix has finite rank and finite bit capacity; Section 12.8 measures that hard limit and shows how interleaving a small fraction of full attention layers lifts it.
12.7.5 Summary
Because additive matrix memories superpose every write to the same key, querying a rebound key returns the sum of its old and new values. The delta rule reads the current prediction \(\mathbf{S}_{t-1}\mathbf{k}_t\) before writing and adds only the error correction \(\beta_t(\mathbf{v}_t - \mathbf{S}_{t-1}\mathbf{k}_t)\mathbf{k}_t^\top\)—one online gradient descent step on \(\frac{1}{2}\|\mathbf{S}\mathbf{k}_t - \mathbf{v}_t\|^2\) whose transition \(\mathbf{I} - \beta_t \mathbf{k}_t \mathbf{k}_t^\top\) selectively contracts the memory along \(\mathbf{k}_t\). While targeted erasure outperforms additive writes whenever keys are rebound or correlated, aggressive erasure (\(\beta_t = 1\)) can erode earlier signals when many random keys overlap. GatedDeltaNet pairs an input-dependent write strength \(\beta_t\) with a scalar head decay \(a_t\) and evaluates the recurrence in parallel chunks via a lower-triangular solve (delta_rule_writes) and a chunk-level scan (chunked_delta_rule), reliably recovering rebound keys on associative recall.
12.7.6 Exercises
Order does not matter. Show that the additive memory after a sequence of writes does not depend on the order of the writes. Conclude that no read rule, however clever, can recover the latest of \(R\) values written under one key from an additive memory alone, and compute the recall that the best rule achieves when the \(R\) values are distinct. How does the measured recall after eight writes change when the codebook grows from 32 to 1,024 values, and why?
[code] Decay instead of correction. Give the additive write of
overwrite_recalla constant decay, \(\mathbf{S} \leftarrow a\mathbf{S} + \mathbf{v}\mathbf{k}^\top\).- For \(R = 2, 4, 8\), find the largest decay \(a\) at which the latest value is recalled at least 95% of the time. Why does the answer depend on how many writes separate two writes of the same key, and why does a smaller decay never hurt in this test?
- Now replace the orthonormal keys by 16 random unit keys in width 64. Rewrite 8 of them \(R\) times as before, write the other 8 once at the start, and measure the recall of both kinds of key at the end. Which write rule serves both kinds of key?
The implicit step. Show that the minimizer of \(\tfrac{1}{2}\|\mathbf{S} - \mathbf{S}_{t-1}\|^2 + \tfrac{\beta}{2}\|\mathbf{S}\mathbf{k} - \mathbf{v}\|^2\) is \(\mathbf{S}_{t-1} - \frac{\beta}{1 + \beta\|\mathbf{k}\|^2} (\mathbf{S}_{t-1}\mathbf{k} - \mathbf{v})\mathbf{k}^\top\). (Hint: set the gradient to zero and multiply the result by \(\mathbf{k}\) to find \(\mathbf{S}\mathbf{k}\) first.) Give the eigenvalues of its transition, and show that the step recalls the new pair exactly only in the limit \(\beta \to \infty\).
[code] Recursive least squares. A regularized least-squares fit, which approaches Equation 12.7.6 as \(\lambda \to 0\), can be updated one pair at a time if the memory also keeps \(\mathbf{P}_t = (\mathbf{K}_t^\top \mathbf{K}_t + \lambda\mathbf{I})^{-1}\).
- Use the Sherman–Morrison formula of Section 33.2.3.5 to derive the updates of \(\mathbf{P}_t\) and \(\mathbf{S}_t\) after one new pair, and show that the update of \(\mathbf{S}_t\) is a delta rule that writes along \(\mathbf{P}_t\mathbf{k}_t\) instead of \(\mathbf{k}_t\). How many numbers does the state now hold, against \(d_v d_k\) for the delta rule?
- Implement it and compare it with the delta rule on the overwrite test. Why does recursive least squares, the best fit of all pairs, recall the latest value poorly? What would fix it?
[code] Parity. ● The write strength of
GatedDeltaNetis a sigmoid, so the eigenvalue \(1 - \beta_t\) of its transition along the key lies in \((0, 1)\). With \(2\sigma(\cdot)\) in place of \(\sigma(\cdot)\) it lies in \((-1, 1)\).- Even then, a trained layer can only approach \(\beta_t = 2\). In the parity construction of Section 12.7.3.5, write \(\beta = 2 - \epsilon\) on every counted token, and show that after \(n\) counted tokens the read is \(\big(1 - (\epsilon - 1)^n\big)\mathbf{v}\). How fast does the difference between the reads after an odd and after an even count shrink? For \(\epsilon = 0.01\), after how many counted tokens is it below 1% of \(\|\mathbf{v}\|\), and what does that mean for a readout with finite precision?
- Section 12.7.3.5 tested its models at four times the training length. Train
Gated DeltaNet, 2σagain and test it on strings of 1,024 and of 4,096 bits. At what length does the accuracy begin to fall, and is that length consistent with your answer to the first part?
[code] Other routes to rebinding. The rebinding experiment fixed three choices so that only the write rule could correct a value. Relax them one at a time and explain each result.
- Switch off the decay of gated linear attention by overriding its method
decays(it returns \(\log a_t\)) to return zeros of the same shape, so that every \(a_t = 1\), and train again. How does its recall change on rewritten keys and on keys written once? - Restore the decay and let each rewrite come at any later position (
gap=Noneintask). Does the gap between the two layers shrink? Explain with the ages of the two values. - Train both layers with two blocks instead of one. How can two additive layers together correct a value?
- Switch off the decay of gated linear attention by overriding its method