12.7 The Delta Rule

The additive matrix memories of Section 12.6 store each new pair by adding vtkt⊤\mathbf{v}_t \mathbf{k}_t^\top to whatever is already in St−1\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 kt\mathbf{k}_t (v^t=St−1kt\hat{\mathbf{v}}_t = \mathbf{S}_{t-1}\mathbf{k}_t) and write only the prediction error βt(vt−v^t)kt⊤\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 12∥Skt−vt∥2\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 k\mathbf{k} is written RR times with values v(1),…,v(R)\mathbf{v}^{(1)}, \ldots, \mathbf{v}^{(R)}, an additive memory returns their unweighted sum:

Sk=v(1)+v(2)+⋯+v(R),(12.7.1)\mathbf{S}\mathbf{k} = \mathbf{v}^{(1)} + \mathbf{v}^{(2)} + \cdots + \mathbf{v}^{(R)}, \tag{12.7.1}

plus cross-key interference ∑i(ki⊤k)vi\sum_i (\mathbf{k}_i^\top \mathbf{k})\mathbf{v}_i. A scalar decay at∈(0,1)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 R64\mathbb{R}^{64}, writing each key R∈{1,2,4,8}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 Sk\mathbf{S}\mathbf{k} matches the latest value v(R)\mathbf{v}^{(R)}.

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 R64\mathbb{R}^{64}, additive recall drops from 1.001.00 at R=1R = 1 to 0.510.51 at R=2R = 2 (a coin toss between the two summed values) and 0.210.21 at R=8R = 8 (Exercise 1).

12.7.2 Writes as Gradient Steps#

12.7.2.1 The Delta Rule#

To replace the value bound to kt\mathbf{k}_t while disturbing other directions as little as possible, we measure the memory's squared prediction error on the incoming pair (kt,vt)(\mathbf{k}_t, \mathbf{v}_t):

ℓt(S)=12 ∥Skt−vt∥2,(12.7.2)\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 St=St−1−βt∇Sℓt(St−1)\mathbf{S}_t = \mathbf{S}_{t-1} - \beta_t \nabla_{\mathbf{S}} \ell_t(\mathbf{S}_{t-1}) with step size (write strength) βt\beta_t:

St=St−1−βt(St−1kt−vt)kt⊤.(12.7.3)\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 v^t=St−1kt\hat{\mathbf{v}}_t = \mathbf{S}_{t-1}\mathbf{k}_t, and add the rank-one correction βt(vt−v^t)kt⊤\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 ∥kt∥=1\|\mathbf{k}_t\| = 1, querying kt\mathbf{k}_t immediately after (12.7.3) returns Stkt=(1−βt)v^t+βtvt\mathbf{S}_t \mathbf{k}_t = (1 - \beta_t)\hat{\mathbf{v}}_t + \beta_t \mathbf{v}_t—an exact replacement when βt=1\beta_t = 1 and a convex blend when βt∈(0,1)\beta_t \in (0, 1). (By contrast, the additive write vtkt⊤\mathbf{v}_t \mathbf{k}_t^\top is a gradient ascent step on the linear alignment vt⊤Skt\mathbf{v}_t^\top \mathbf{S}\mathbf{k}_t, which has no saturation point.)

12.7.2.2 The Transition#

Factoring St−1\mathbf{S}_{t-1} out of (12.7.3) exposes the matrix transition applied to the existing memory:

St=St−1(I−βtktkt⊤)+βtvtkt⊤.(12.7.4)\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 kt\mathbf{k}_t, the symmetric matrix I−βtktkt⊤\mathbf{I} - \beta_t \mathbf{k}_t \mathbf{k}_t^\top fixes every subspace orthogonal to kt\mathbf{k}_t (eigenvalue 11) and scales the direction kt\mathbf{k}_t by eigenvalue 1−βt1 - \beta_t (Figure 12.7.1):

  • βt=0\beta_t = 0: identity (no write);
  • βt∈(0,1)\beta_t \in (0, 1): partial contraction along kt\mathbf{k}_t;
  • βt=1\beta_t = 1: orthogonal projection I−ktkt⊤\mathbf{I} - \mathbf{k}_t \mathbf{k}_t^\top, completely erasing the kt\mathbf{k}_t component before writing vtkt⊤\mathbf{v}_t \mathbf{k}_t^\top;
  • βt=2\beta_t = 2: Householder reflection I−2ktkt⊤\mathbf{I} - 2\mathbf{k}_t \mathbf{k}_t^\top (eigenvalue −1-1), reversing the sign along kt\mathbf{k}_t.
Figure 12.7.1:

The transition I−βkk⊤\mathbf{I} - \beta\mathbf{k}\mathbf{k}^\top acting on a vector s\mathbf{s} in the plane spanned by a unit key k\mathbf{k} and an orthogonal direction. The component along k\mathbf{k} is multiplied by 1−β1 - \beta: kept at β=0\beta = 0, halved at β=0.5\beta = 0.5, removed at β=1\beta = 1, and reversed at β=2\beta = 2. The orthogonal component is unchanged.

Two consequences follow from the eigenvalue 1−βt∥kt∥21 - \beta_t\|\mathbf{k}_t\|^2:

  1. Unit-norm keys prevent instability: With ∥kt∥=1\|\mathbf{k}_t\| = 1 and βt∈[0,2]\beta_t \in [0, 2], all eigenvalues of the transition lie in [−1,1][-1, 1], so homogeneous memory states never blow up geometrically.
  2. Negative eigenvalues enable modulo-2 counting (parity): When βt∈[0,1]\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 βt\beta_t to 22 allows reflections (eigenvalue −1-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, βt=1\beta_t = 1 erases stale values on rebound keys without touching any other key. What happens when n>dkn > d_k or keys are random unit vectors so that distinct keys ki\mathbf{k}_i and kt\mathbf{k}_t have non-zero overlap kt⊤ki\mathbf{k}_t^\top \mathbf{k}_i? Each subsequent delta step along kt\mathbf{k}_t projects out the kt\mathbf{k}_t-component of viki⊤\mathbf{v}_i \mathbf{k}_i^\top, shrinking key ii's stored signal by 1−(kt⊤ki)2≈1−1/dk1 - (\mathbf{k}_t^\top \mathbf{k}_i)^2 \approx 1 - 1/d_k per step—so after mm later writes, only (1−1/dk)m≈e−m/dk(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=64d = 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()})

We compare four memory rules (additive, delta, β = 1, delta, β = 0.5, and offline least squares, where np.linalg.lstsq minimizes ∑s∥Sks−vs∥2\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∈{32,64,128,256}n \in \{32, 64, 128, 256\} independent random unit keys written once, and (3) 64 correlated keys (ρ=0.5\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

The table highlights the trade-off of online projection:

  • Rebinding (8 orthonormal keys, 4 writes): delta achieves 1.001.00 recall at both β=1\beta = 1 and β=0.5\beta = 0.5 (squared error 0.000.00 and 0.330.33), whereas additive and unweighted least squares average all 4 values bound to each key and score just 0.280.28.
  • Correlated keys (64 keys, ρ = 0.5): Because every key shares a common direction, additive piles every value onto that shared component (squared error 5.825.82, recall 0.540.54), whereas delta subtracts the prediction along the shared direction before writing (recall 0.770.77 at β=1\beta = 1 and 0.890.89 at β=0.5\beta = 0.5).
  • Crowded independent keys (128 keys, 256 keys): Here delta, β = 1 has lower squared error than additive (1.061.06 vs. 1.991.99 at n=128n = 128), yet lower nearest-neighbor recall (0.530.53 vs. 0.960.96). Why? Because shrinking old reads toward 0\mathbf{0} lowers their squared error toward ∥0−vj∥2=1\|\mathbf{0} - \mathbf{v}_j\|^2 = 1 while eroding the signal of early pairs relative to later ones. Using a gentler step β=0.5\beta = 0.5 recovers both lower squared error (0.670.67) and much higher recall (0.820.82), motivating making βt\beta_t an input-dependent gate so the network can use βt≈1\beta_t \approx 1 to overwrite a rebound key and smaller βt\beta_t when accumulating facts.

12.7.3 Gated DeltaNet#

12.7.3.1 Decay and Correction#

Because the delta rule modifies St−1\mathbf{S}_{t-1} only along the current key kt\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 at∈(0,1)a_t \in (0, 1) (for global forgetting) with the delta rule's rank-one directional update (for targeted key overwriting):

St=at St−1(I−βtktkt⊤)+βtvtkt⊤.(12.7.5)\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 ata_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 at≈1a_t \approx 1 and βt=1\beta_t = 1 it replaces the value under the current key and leaves orthogonal keys untouched, as in the rebinding test above. With at≈1a_t \approx 1 and a small βt\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.

Figure 12.7.2:

One step of Gated DeltaNet on a 2×22 \times 2 memory under three settings of its gates. The arrows are the reads along the current key kt\mathbf{k}_t (blue) and along an orthogonal key (purple), before the step (dashed) and after it (solid). A decay ata_t near zero flushes the memory, and only the new pair remains. With at≈1a_t \approx 1, a write strength βt=1\beta_t = 1 replaces the value under kt\mathbf{k}_t by vt\mathbf{v}_t and leaves the other key alone, while a small βt\beta_t moves the read only part of the way toward vt\mathbf{v}_t.

12.7.3.2 Chunked Computation#

Because the transition at(I−βtktkt⊤)a_t(\mathbf{I} - \beta_t \mathbf{k}_t \mathbf{k}_t^\top) is a dk×dkd_k \times d_k matrix rather than a scalar, a naive token-level scan would multiply dk×dkd_k \times d_k matrices at O(Tdk3)O(T d_k^3) cost. Yang et al. (2024) showed how to evaluate (12.7.5) in chunks of size mm using the WY representation. Rewrite (12.7.5) as an additive decayed update St=atSt−1+utkt⊤\mathbf{S}_t = a_t \mathbf{S}_{t-1} + \mathbf{u}_t \mathbf{k}_t^\top with effective corrected value ut=βt(vt−atSt−1kt)\mathbf{u}_t = \beta_t(\mathbf{v}_t - a_t \mathbf{S}_{t-1}\mathbf{k}_t). Inside a chunk of length mm starting from initial state S0\mathbf{S}_0, unrolling atSt−1kt=γtS0kt+∑s<tLts(ks⊤kt)usa_t \mathbf{S}_{t-1}\mathbf{k}_t = \gamma_t \mathbf{S}_0 \mathbf{k}_t + \sum_{s \lt t} L_{ts}(\mathbf{k}_s^\top \mathbf{k}_t)\mathbf{u}_s (where Lts=∏r=s+1tarL_{ts} = \prod_{r=s+1}^t a_r and γt=∏r=1tar\gamma_t = \prod_{r=1}^t a_r) yields a strictly lower-triangular m×mm \times m linear system for the chunk's corrected values u1,…,um\mathbf{u}_1, \ldots, \mathbf{u}_m:

ut+βt∑s<tLts (ks⊤kt) us=βt(vt−γtS0kt).\mathbf{u}_t + \beta_t \sum_{s \lt 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 S0\mathbf{S}_0, delta_rule_writes solves the unit-lower-triangular m×mm \times m system M=I+diag(β) tril−1(L⊙KK⊤)\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, W=M−1(β⊙V)\mathbf{W} = \mathbf{M}^{-1}(\boldsymbol{\beta} \odot \mathbf{V}) and Z=M−1((β⊙γ)⊙K)\mathbf{Z} = \mathbf{M}^{-1}((\boldsymbol{\beta} \odot \boldsymbol{\gamma}) \odot \mathbf{K}), so that U=W−ZS0⊤\mathbf{U} = \mathbf{W} - \mathbf{Z}\mathbf{S}_0^\top once S0\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, Z

Substituting U=W−ZS0⊤\mathbf{U} = \mathbf{W} - \mathbf{Z}\mathbf{S}_0^\top into the chunk-end state Sm=γmS0+U⊤DK\mathbf{S}_m = \gamma_m \mathbf{S}_0 + \mathbf{U}^\top \mathbf{D}\mathbf{K} (where D\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/mT / m chunks:

Sm=S0A+W⊤DK,A=γmI−Z⊤DK.\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 (A,W⊤DK)(\mathbf{A}, \mathbf{W}^\top \mathbf{D}\mathbf{K}) across the T/mT / m chunks costs only (T/m)dk3(T/m) d_k^3 operations (matching the intra-chunk O(Tdk2)O(T d_k^2) matrix products when m≈dkm \approx d_k), after which U=W−ZS0⊤\mathbf{U} = \mathbf{W} - \mathbf{Z}\mathbf{S}_0^\top and all outputs Y\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)

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)

We now compare chunked_delta_rule at chunk sizes m∈{16,64}m \in \{16, 64\} against delta_rule_recurrent on a random sequence of length T=256T = 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

The chunked algorithm matches the token-level recurrence to ∼10−7\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 (βt,h=σ(wβ,h⊤xt+bβ,h)∈(0,1)\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, ℓ2\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)

12.7.3.4 Rebinding#

Can a trained GatedDeltaNet layer overwrite rebound keys where GatedLinearAttention struggles? We test a single-block SeqLM (d=64d = 64, 4 heads of dimension 16, initial decay timescales [256,2048][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))])

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

Adding the 260-parameter W_beta head raises recall on rebound keys from about 0.90.9 (gated linear attention) to 0.960.96 or more (Gated DeltaNet), bringing rebound keys within about 22 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 ht−1\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 zt∈(0,1)\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 (12.7.4) then has an eigenvalue 1−βt∈(0,1)1 - \beta_t \in (0, 1) along the key. With βt∈(0,2)\beta_t \in (0, 2) the eigenvalue can reach −1-1. A layer that writes a value v\mathbf{v} with βt=2\beta_t = 2 under one fixed key k\mathbf{k} on every 1, and writes nothing on a 0, changes its read by Stk=2v−St−1k\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 2v2\mathbf{v} and 0\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 βt∈(0,2)\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.50.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 blocks

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

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.50.5 and Gated DeltaNet at about 0.750.75 to 0.80.8, but neither has learned the rule: beyond position 64 both answer at 0.500.50, a coin toss. Doubling the write strength changes this. GatedDeltaNetReflect reaches 1.001.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.90.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 βt=2\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 Kt∈Rt×dk\mathbf{K}_t \in \mathbb{R}^{t \times d_k} to values Vt∈Rt×dv\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 ∑s≤t∥Sks−vs∥2\sum_{s \le t} \|\mathbf{S}\mathbf{k}_s - \mathbf{v}_s\|^2 is:

St⋆=Vt⊤Kt (Kt⊤Kt)−1,(12.7.6)\mathbf{S}_t^\star = \mathbf{V}_t^\top \mathbf{K}_t\, (\mathbf{K}_t^\top \mathbf{K}_t)^{-1}, \tag{12.7.6}

where (Kt⊤Kt)−1(\mathbf{K}_t^\top \mathbf{K}_t)^{-1} is replaced by the pseudoinverse when t<dkt \lt d_k. Look at the two factors of (12.7.6) (Table 12.7.1):

  • Linear attention keeps only the first factor, the unnormalized cross-moment Vt⊤Kt=∑s≤tvsks⊤\mathbf{V}_t^\top \mathbf{K}_t = \sum_{s \le t} \mathbf{v}_s \mathbf{k}_s^\top, omitting the Gram inverse (Kt⊤Kt)−1(\mathbf{K}_t^\top \mathbf{K}_t)^{-1} that decorrelates overlapping keys.
  • The delta rule takes one online stochastic gradient step per token toward (12.7.6), while Gated DeltaNet adds weight decay (at<1a_t \lt 1) before each step. Replacing the explicit gradient step by the proximal implicit step arg⁡min⁡S12∥S−St−1∥2+βt2∥Skt−vt∥2\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 βt/(1+βt∥kt∥2)\beta_t / (1 + \beta_t\|\mathbf{k}_t\|^2) of Longhorn (Liu et al., 2024) (Exercise 3), while carrying (Kt⊤Kt+λI)−1(\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)O(t) KV cache.

The exact fit can also be kept up to date one pair at a time. Each pair changes Kt⊤Kt\mathbf{K}_t^\top \mathbf{K}_t by the rank-one term ktkt⊤\mathbf{k}_t\mathbf{k}_t^\top, so the Sherman–Morrison formula (Section 21.2.3.5) updates the inverse without a new matrix inversion. This is recursive least squares. It carries a second state of size dk×dkd_k \times d_k next to the memory (Exercise 4).

Table 12.7.1. Memories as regressions on the pairs read so far.
MemoryWhat it fitsHowState
Softmax attentionkernel-weighted average of all valuesat query timeall pairs
Linear attentionV⊤K\mathbf{V}^\top\mathbf{K}, least squares without the key correctionone addition per pairdv×dkd_v \times d_k
Gated linear attentionthe same, weighted toward recent pairsone addition per pairdv×dkd_v \times d_k
Delta ruleleast squares, approximatelyone gradient step per pairdv×dkd_v \times d_k
Gated DeltaNetleast squares with weight decay, approximatelyone gradient step per pairdv×dkd_v \times d_k

In all these architectures, learning operates at two timescales: the fast weights of the state St\mathbf{S}_t fit the key–value associations of the current context during the forward pass, while the slow weights of the network (Wqkv,Wa,Wβ,…\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 dv×dkd_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 St−1kt\mathbf{S}_{t-1}\mathbf{k}_t before writing and adds only the error correction βt(vt−St−1kt)kt⊤\beta_t(\mathbf{v}_t - \mathbf{S}_{t-1}\mathbf{k}_t)\mathbf{k}_t^\top—one online gradient descent step on 12∥Skt−vt∥2\frac{1}{2}\|\mathbf{S}\mathbf{k}_t - \mathbf{v}_t\|^2 whose transition I−βtktkt⊤\mathbf{I} - \beta_t \mathbf{k}_t \mathbf{k}_t^\top selectively contracts the memory along kt\mathbf{k}_t. While targeted erasure outperforms additive writes whenever keys are rebound or correlated, aggressive erasure (βt=1\beta_t = 1) can erode earlier signals when many random keys overlap. GatedDeltaNet pairs an input-dependent write strength βt\beta_t with a scalar head decay ata_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#

  1. 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 RR values written under one key from an additive memory alone, and compute the recall that the best rule achieves when the RR values are distinct. How does the measured recall after eight writes change when the codebook grows from 32 to 1,024 values, and why?

  2. [code] Decay instead of correction. Give the additive write of overwrite_recall a constant decay, S←aS+vk⊤\mathbf{S} \leftarrow a\mathbf{S} + \mathbf{v}\mathbf{k}^\top.

    1. For R=2,4,8R = 2, 4, 8, find the largest decay aa 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?
    2. Now replace the orthonormal keys by 16 random unit keys in width 64. Rewrite 8 of them RR 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?
  3. The implicit step. Show that the minimizer of 12∥S−St−1∥2+β2∥Sk−v∥2\tfrac{1}{2}\|\mathbf{S} - \mathbf{S}_{t-1}\|^2 + \tfrac{\beta}{2}\|\mathbf{S}\mathbf{k} - \mathbf{v}\|^2 is St−1−β1+β∥k∥2(St−1k−v)k⊤\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 k\mathbf{k} to find Sk\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.

  4. [code] Recursive least squares. A regularized least-squares fit, which approaches (12.7.6) as λ→0\lambda \to 0, can be updated one pair at a time if the memory also keeps Pt=(Kt⊤Kt+λI)−1\mathbf{P}_t = (\mathbf{K}_t^\top \mathbf{K}_t + \lambda\mathbf{I})^{-1}.

    1. Use the Sherman–Morrison formula of Section 21.2.3.5 to derive the updates of Pt\mathbf{P}_t and St\mathbf{S}_t after one new pair, and show that the update of St\mathbf{S}_t is a delta rule that writes along Ptkt\mathbf{P}_t\mathbf{k}_t instead of kt\mathbf{k}_t. How many numbers does the state now hold, against dvdkd_v d_k for the delta rule?
    2. 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?
  5. [code] Parity. ● The write strength of GatedDeltaNet is a sigmoid, so the eigenvalue 1−βt1 - \beta_t of its transition along the key lies in (0,1)(0, 1). With 2σ(⋅)2\sigma(\cdot) in place of σ(⋅)\sigma(\cdot) it lies in (−1,1)(-1, 1).

    1. Even then, a trained layer can only approach βt=2\beta_t = 2. In the parity construction of Section 12.7.3.5, write β=2−ϵ\beta = 2 - \epsilon on every counted token, and show that after nn counted tokens the read is (1−(ϵ−1)n)v\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 ϵ=0.01\epsilon = 0.01, after how many counted tokens is it below 1% of ∥v∥\|\mathbf{v}\|, and what does that mean for a readout with finite precision?
    2. 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?
  6. [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.

    1. Switch off the decay of gated linear attention by overriding its method decays (it returns log⁡at\log a_t) to return zeros of the same shape, so that every at=1a_t = 1, and train again. How does its recall change on rewritten keys and on keys written once?
    2. Restore the decay and let each rewrite come at any later position (gap=None in task). Does the gap between the two layers shrink? Explain with the ages of the two values.
    3. Train both layers with two blocks instead of one. How can two additive layers together correct a value?

Discussions