Skip to main content

DM-4 — State-dependent gating & memory forensics

Open In Colab

The question: how do you let the forget gate see the memory state without destroying chunkwise parallelism — and how do you inspect what actually survived inside \(\mathbf{S}_t\)?

Prerequisites: M3, M4, M7 · Runtime: ~3 seconds on CPU.

In DM-1, every single gate — GDN’s \(\alpha_t\), KDA’s \(\mathbf{D}_t\), GDN-2’s \(\mathbf{b}_t, \mathbf{w}_t\), even Stable GDN-2’s symmetric erase — was state-blind: computed purely from the incoming token \(\mathbf{x}_t\) without ever looking at what is currently stored in \(\mathbf{S}_{t-1}\). The reason is hardware: if \(\alpha_t\) depends on \(\mathbf{S}_{t-1}\) at every token, you can no longer unroll a chunk of 64 tokens into parallel matrix multiplies.

This closing module of the Delta Memory track covers two late-2026 breakthroughs that open the black box of \(\mathbf{S}_t\): 1. SDG — State-Dependent Gating at Chunk Boundaries (Deng et al., Oct/Nov 2026): keep intra-chunk updates 100% state-blind and parallel, then compute an element-wise gate \(\boldsymbol\Lambda_{[n]}\) from the chunk memory change \(\Delta\mathbf{S}_{[n]}\) and apply it at the chunk boundary — proving it acts as an element-wise ridge proximal step. 2. How Linear Attention Remembers (Lee et al., Sep 2026): decompose any linear-attention state into the exact sum of every past token’s surviving contribution \(\mathbf{S}_t = \sum_{i=1}^t \mathbf{C}_i^{(t)}\), turning \(\mathbf{S}_t\) from an opaque matrix into an inspectable timeline.

Grounding: SDG: State-Dependent Gating at Chunk Boundaries for Linear Attention (Deng, Liu, He, Wang & Yuan, Oct/Nov 2026) Eqs. 2–5; How Linear Attention Remembers (Lee, Park, Kim & Ko, Sep 2026) Eqs. 1–5; Comba (Hu et al., Jun 2025) for closed-loop bilinear feedback.

Objective

After this module you should be able to:

  • Explain why token-level state-dependent gates break chunkwise parallel training, and why chunk-boundary gating preserves it completely.
  • Write SDG’s chunk-boundary update \(\mathbf{S}_{[n+1]}^+ = \boldsymbol\Lambda_{[n]} \odot \mathbf{S}_{[n+1]}^-\) where \(\boldsymbol\Lambda_{[n]}\) is computed from \(\Delta\mathbf{S}_{[n]} = \mathbf{S}_{[n+1]}^- - \mathbf{S}_{[n]}^+\), and explain its ridge-proximal interpretation.
  • Implement the exact per-token contribution decomposition \(\mathbf{S}_t = \sum_{i=1}^t \mathbf{C}_i^{(t)}\) from How Linear Attention Remembers and verify it to machine precision.
  • Identify the one blind spot SDG still leaves open: reacting to write changes \(\Delta\mathbf{S}_{[n]}\) is not the same as knowing which stored memories are read by queries.

Why it exists (the limitation it fixes)

With an input-only forget gate, the exact same token \(\mathbf{x}_t\) produces the exact same decay \(\alpha(\mathbf{x}_t)\) whether the memory is empty, half-full of critical facts, or overflowing with noise. Gated DeltaNet explicitly noted that it dropped \(\mathbf{S}_{t-1}\) dependence from \(\alpha_t\) solely to keep chunkwise parallel training fast.

SDG (Deng et al., Oct/Nov 2026) spots a clean middle ground. Chunkwise linear attention already splits a sequence into chunks of size \(C\) (typically 64 tokens) and passes the state sequentially across chunk boundaries:

  1. Inside chunk \(n\) (parallel): run your favorite layer (GDN, KDA, GDN-2, or Mamba-3) unchanged to get the pre-gate state \(\mathbf{S}_{[n+1]}^-\).
  2. At the chunk boundary (state-aware): measure how much the chunk changed the state, \(\Delta\mathbf{S}_{[n]} = \mathbf{S}_{[n+1]}^- - \mathbf{S}_{[n]}^+\), pass it through a tiny gating map to produce an element-wise gate \(\boldsymbol\Lambda_{[n]} \in (0, 1)^{d_v \times d_k}\), and shrink:

\[\mathbf{S}_{[n+1]}^+ = \boldsymbol\Lambda_{[n]} \odot \mathbf{S}_{[n+1]}^-.\]

When \(\boldsymbol\Lambda_{[n]}\) is held fixed, this element-wise shrinkage is the exact closed-form solution to an element-wise ridge proximal step:

\[\mathbf{S}_{[n+1]}^+ = \arg\min_{\mathbf{M}} \left\{ \frac{1}{2}\|\mathbf{M} - \mathbf{S}_{[n+1]}^-\|_F^2 + \frac{1}{2}\sum_{i,j} \lambda_{ij} M_{ij}^2 \right\}, \qquad \Lambda_{ij} = \frac{1}{1 + \lambda_{ij}}.\]

Because this runs once every \(C\) tokens instead of every token, intra-chunk parallelism is completely untouched.

Reading

  • SDG (Deng et al., Oct/Nov 2026): Eqs. 3–5, fused kernels for GDN/KDA/GDN-2/Mamba-3, and 1.3B / 100B-token improvements on LM, NIAH, RULER, and LongBench.
  • How Linear Attention Remembers (Lee et al., Sep 2026): Eqs. 1–5, exact linear-operator decomposition of GLA and GDN states.

1. Chunk-boundary state-dependent gating (SDG) in action

Let’s compare a state-blind scalar gate against a simple chunk-boundary SDG gate on a stream with bursty noise chunks: some chunks carry clean, low-drift signal; other chunks flood specific entries of \(\mathbf{S}\) with large noisy spikes (\(|\Delta S_{ij}|\) large). A state-blind gate has to shrink every entry equally; an element-wise boundary gate \(\Lambda_{ij} = 1 / (1 + \kappa |\Delta S_{ij}|)\) selectively damps the spiked entries while leaving quiet entries untouched!

import torch
import torch.nn.functional as F
import matplotlib.pyplot as plt

torch.manual_seed(0)
d = 16
chunk_size = 8
n_chunks = 12

# Clean fact stored in chunk 0 (lives mostly in rows 0..7)
k_fact = F.normalize(torch.randn(d), dim=0)
v_fact = torch.zeros(d); v_fact[:8] = F.normalize(torch.randn(8), dim=0)

S_blind = torch.zeros(d, d)
S_sdg   = torch.zeros(d, d)

# Write clean fact at t=0 in both
S_blind = S_blind + 0.9 * torch.outer(v_fact, k_fact)
S_sdg   = S_sdg   + 0.9 * torch.outer(v_fact, k_fact)

err_blind, err_sdg, norm_blind, norm_sdg = [], [], [], []

for c in range(n_chunks):
    S_b_prev = S_blind.clone()
    S_s_prev = S_sdg.clone()

    # Inside chunk c: standard parallelizable GDN steps (noise burst on orthogonal keys in rows 8..15)
    for _ in range(chunk_size):
        k = torch.randn(d)
        k = F.normalize(k - (k @ k_fact) * k_fact, dim=0)
        v = torch.zeros(d)
        amp = 2.5 if (c % 3 == 1) else 0.2
        v[8:] = torch.randn(8) * amp
        S_blind = 0.998 * (S_blind + 0.5 * torch.outer(v - S_blind @ k, k))
        S_sdg   = 0.998 * (S_sdg   + 0.5 * torch.outer(v - S_sdg   @ k, k))

    # Chunk-boundary step:
    # State-blind uniform scalar decay vs. SDG element-wise ridge proximal gate from |Delta S|
    S_blind = 0.85 * S_blind
    delta_S = S_sdg - S_s_prev
    Lambda = 1.0 / (1.0 + 1.5 * delta_S.abs())   # element-wise ridge proximal gate in (0, 1]
    S_sdg = Lambda * S_sdg

    err_blind.append((S_blind[:8] @ k_fact - v_fact[:8]).norm().item())
    err_sdg.append((S_sdg[:8] @ k_fact - v_fact[:8]).norm().item())
    norm_blind.append(S_blind[8:].norm().item())
    norm_sdg.append(S_sdg[8:].norm().item())

print(f"After {n_chunks} chunks ({n_chunks*chunk_size} tokens):")
print(f"  State-blind scalar gate | fact error = {err_blind[-1]:.3f} | noisy-rows norm = {norm_blind[-1]:.2f}")
print(f"  Chunk-boundary SDG      | fact error = {err_sdg[-1]:.3f} | noisy-rows norm = {norm_sdg[-1]:.2f}")

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(8.5, 3.0))
ax1.plot(err_blind, "o-", label="State-blind scalar decay", color="#c85a53")
ax1.plot(err_sdg,   "s-", label="Chunk-boundary SDG", color="#1f6f66", lw=2.2)
ax1.set_title("Clean fact recall error"); ax1.set_xlabel("chunk n"); ax1.legend(fontsize=8)

ax2.plot(norm_blind, "o-", label="State-blind scalar decay", color="#c85a53")
ax2.plot(norm_sdg,   "s-", label="Chunk-boundary SDG", color="#1f6f66", lw=2.2)
ax2.set_title("Noisy-rows norm"); ax2.set_xlabel("chunk n"); ax2.legend(fontsize=8)
plt.tight_layout(); plt.show()
After 12 chunks (96 tokens):
  State-blind scalar gate | fact error = 0.894 | noisy-rows norm = 5.27
  Chunk-boundary SDG      | fact error = 0.286 | noisy-rows norm = 2.69

Look at both panels: the state-blind scalar gate shrinks the quiet fact rows every chunk right alongside the noisy rows, eroding the stored fact (error → 0.90+). SDG sees that ΔS is near zero on the quiet rows (Λ ≈ 1.0) and huge on the noisy rows (Λ ≪ 1.0), so it damps the burst without touching the stored fact — all at the chunk boundary, with zero loss of intra-chunk parallelism.

2. Memory forensics: How Linear Attention Remembers

When a recurrent memory fails, how do you know which past token was erased, and which later token erased it?

How Linear Attention Remembers (Lee et al., Sep 2026) makes a deceptively simple observation. Any linear-attention recurrence has the affine form

\[\mathbf{S}_t = \mathcal{T}_t(\mathbf{S}_{t-1}) + \mathbf{W}_t,\]

where \(\mathcal{T}_t\) is a linear transition operator (for Gated DeltaNet, \(\mathcal{T}_t(\mathbf{S}) = \alpha_t \mathbf{S}(\mathbf{I} - \beta_t \mathbf{k}_t \mathbf{k}_t^\top)\)) and \(\mathbf{W}_t = \beta_t \mathbf{v}_t \mathbf{k}_t^\top\) is the fresh write at step \(t\). Because \(\mathcal{T}_t\) is linear, superposition holds exactly:

\[\mathbf{S}_t = \sum_{i=1}^t \mathbf{C}_i^{(t)}, \qquad \mathbf{C}_i^{(t)} = (\mathcal{T}_t \circ \mathcal{T}_{t-1} \circ \cdots \circ \mathcal{T}_{i+1})(\mathbf{W}_i).\]

Every single past token \(i\)’s write \(\mathbf{W}_i\) has an exact, trackable footprint \(\mathbf{C}_i^{(t)}\) inside the current state \(\mathbf{S}_t\), and its readout contribution to query \(\mathbf{q}_t\) is simply \(\mathbf{C}_i^{(t)}\mathbf{q}_t\)!

Let’s implement this exact decomposition, assert that \(\sum_i \mathbf{C}_i^{(t)} = \mathbf{S}_t\) to machine precision, and plot the survival curves of individual writes under Gated DeltaNet — watching a revisited key get surgically erased while an orthogonal key survives.

torch.manual_seed(1)
d = 12
T = 25

# Build an orthogonal pair of special keys: kA written at t=2 and OVERWRITTEN at t=14;
# kB written at t=4 and never overwritten.
Q_orth, _ = torch.linalg.qr(torch.randn(d, d))
kA, kB = Q_orth[:, 0], Q_orth[:, 1]
vA1, vA2, vB = F.normalize(torch.randn(d), dim=0), F.normalize(torch.randn(d), dim=0), F.normalize(torch.randn(d), dim=0)

S = torch.zeros(d, d)
contribs = []  # contribs[i] holds C_i^{(t)}
surv_A1, surv_B = [], []

for t in range(T):
    if t == 2:
        k, v, alpha, beta = kA, vA1, 0.96, 1.0
    elif t == 4:
        k, v, alpha, beta = kB, vB, 0.96, 1.0
    elif t == 14:
        k, v, alpha, beta = kA, vA2, 0.96, 1.0   # overwrite kA!
    else:
        # Distractors orthogonal to kA and kB
        coeff = torch.randn(d - 2)
        k = F.normalize(Q_orth[:, 2:] @ coeff, dim=0)
        v = F.normalize(torch.randn(d), dim=0) * 0.5
        alpha, beta = 0.96, 0.6

    # Transition operator T_t(X) = alpha * X @ (I - beta k k^T), write W_t = beta v k^T
    P = alpha * (torch.eye(d) - beta * torch.outer(k, k))
    W = beta * torch.outer(v, k)

    S = S @ P + W
    contribs = [C @ P for C in contribs]
    contribs.append(W)

    surv_A1.append(contribs[2].norm().item() if t >= 2 else 0.0)
    surv_B.append(contribs[4].norm().item()  if t >= 4 else 0.0)

# Exact identity check: sum of surviving token contributions == S_T
recon_err = (sum(contribs) - S).norm().item()
print(f"Exact decomposition check ||sum(C_i) - S_T||_F = {recon_err:.2e}")
assert recon_err < 1e-5
print(f"At t=13 (before overwrite): ||C_A1|| = {surv_A1[13]:.3f}, ||C_B|| = {surv_B[13]:.3f}")
print(f"At t=14 (after overwrite) : ||C_A1|| = {surv_A1[14]:.3f}, ||C_B|| = {surv_B[14]:.3f}")

plt.figure(figsize=(6.8, 3.0))
plt.plot(surv_A1, "o-", label="C_2 (kA=vA1, overwritten at t=14)", color="#c85a53", lw=2)
plt.plot(surv_B,  "s-", label="C_4 (kB=vB, untouched)", color="#1f6f66", lw=2)
plt.axvline(14, ls="--", color="gray", alpha=0.7, label="overwrite kA at t=14")
plt.xlabel("step t"); plt.ylabel("||C_i^(t)||_F (surviving write norm)")
plt.title("How Linear Attention Remembers: exact per-token write survival")
plt.legend(fontsize=8); plt.tight_layout(); plt.show()
Exact decomposition check ||sum(C_i) - S_T||_F = 2.77e-07
At t=13 (before overwrite): ||C_A1|| = 0.638, ||C_B|| = 0.693
At t=14 (after overwrite) : ||C_A1|| = 0.000, ||C_B|| = 0.665

The identity check passes to 1e-6, and the plot makes the memory’s internal life transparent: C_2 and C_4 decay gently at alpha=0.96 until step 14, when the delta write at kA drops ||C_2|| straight to 0.000 while leaving ||C_4|| completely untouched.

The open door this track ends on. Notice what SDG and How Linear Attention Remembers still do not solve: - SDG’s gate sees write activity (\(\Delta\mathbf{S}_{[n]}\)), not read utility (which stored directions queries actually use). - Every paper in this track (GDN, KDA, GDN-2, Stable GDN-2, KLA, OSDN, MesaNet, EDA, GSA2, Triadic, HOLA, SDG) evaluates single-sequence retrieval and zero of them measure proactive loss of plasticity — whether the memory still absorbs new writes cleanly after hundreds of episodes.

That is the exact question the sibling track Plasticity & Capacity takes up from scratch.

Honest scope. Our SDG demo uses a hand-written magnitude formula \(\Lambda = 1/(1+1.5|\Delta S|)\) rather than Deng et al.’s learned low-rank projection over \(\Delta\mathbf{S}_{[n]}\), and our forensic demo tracks orthogonal keys so the surgical drop is crisp. What this notebook settles is the exact mechanics of both ideas: chunk-boundary gating restores state awareness without losing intra-chunk parallelism, and affine superposition lets you trace every token’s exact survival inside \(\mathbf{S}_t\).

Exit check

  1. Why does a token-level gate \(\alpha(\mathbf{S}_{t-1})\) break chunkwise parallel training, while SDG’s chunk-boundary gate \(\boldsymbol\Lambda(\Delta\mathbf{S}_{[n]})\) keeps it?
  2. What optimization problem is element-wise multiplication \(\boldsymbol\Lambda \odot \mathbf{S}^-\) solving when \(\boldsymbol\Lambda\) is fixed?
  3. Why does the exact decomposition \(\mathbf{S}_t = \sum_i \mathbf{C}_i^{(t)}\) hold for GDN and GLA — and would it still hold for a nonlinear MLP memory like Titans?
  4. What information does SDG’s \(\Delta\mathbf{S}_{[n]}\) not observe that a lifelong memory needs in order to protect old, frequently used facts?

Track complete. Return to the track index or the course front page.