Skip to main content

PC-4 — Consolidation, sleep & memory diagnostics

Open In Colab

The question: when online updates hit capacity or reasoning overrides stored memory, how do interleaved sleep and Reach-vs.-Use diagnostics help?

Prerequisites: M1, PC-1, PC-3 · Runtime: ~3 seconds on CPU.

Even a perfectly regulated online fast-weight layer runs into two walls over a lifetime: 1. Online compression is shallow and one-pass: compressing a complex multi-hop context into a fixed state in a single forward pass loses relational structure, and rehearsing only the most recent episodes destroys older ones. 2. Storage is not the same as use: even when the right memory is stored and retrieved, a language model’s pretrained priors or Chain-of-Thought reasoning often override counterfactual or updated memories!

This closing module covers the two-system consolidation lineage (CLS 1995 → LM-Sleep → Sleep-SelfMod → Surprise-gated interleaved replay) and the process-level diagnostic framework (MemTrace, Jun 2026) that separates whether memory reached the model from whether the model actually used it.

Grounding: CLS (McClelland, McNaughton & O’Reilly, 1995); LM-Sleep (Lee, McLeish, Goldstein & Fanti, May 2026); Sleep-SelfMod (Behrouz, Hashemi & Mirrokni, Jun 2026); Surprise & Metacognition (Mouchon, Jun 2026); MemTrace (Long et al., Jun 2026).

Objective

After this module you should be able to:

  • Explain Complementary Learning Systems (CLS) in one sentence: a fast, high-plasticity episodic store paired with a slow neocortical store consolidated by interleaved replay.
  • Show concretely why recent-only sliding-window replay is actively worse than no consolidation at all, while interleaved replay preserves old and new tasks together.
  • Contrast LM-Sleep (May 2026: \(N\) offline depth-recurrent passes over an SSM-attention hybrid before KV eviction) with Sleep-SelfMod (Jun 2026: low-rank MoE expansion + on-policy GKD/RL Knowledge Seeding + Dreaming).
  • Define MemTrace’s two core diagnostic splits: Reach (\(R=1\)) vs. Use (\(U=1\)) and Boundary abstention vs. Conflict resolution.

Why it exists (the limitation it fixes)

Think about three distinct things that can go wrong in a long-lived agent: - Consolidation failure: you try to train a slow memory directly on the latest day’s experience without interleaving older memories → catastrophic forgetting (worse than doing nothing!). - Single-pass depth failure (LM-Sleep): an SSM-attention hybrid has to compress 2,000 tokens of multi-hop math/graph state into a fixed matrix \(\mathbf{S}_t\) before evicting the KV cache. Running \(N > 1\) offline depth-recurrent passes over the hybrid blocks before eviction lets the model reason before compressing, dramatically lifting GSM-Infinite and Depo \(k\)-hop accuracy. - Readout / prior-override failure (MemTrace): Long et al. (Jun 2026) evaluated 13 long-context, RAG, and agentic memory systems across 835 typed knowledge points. Even when a simple retriever reached the gold session (\(R = 1\), 279/300 probes), production systems still failed to answer correctly (\(R=1, U=0\)) on 69.2%–88.2% of reachable probes — and systems with 94–99% abstention on missing facts scored only 14.6%–35.1% when a false premise conflicted with stored memory!

Reading

  • LM-Sleep (Lee et al., May 2026): Eq. 6 & Alg. 1 — \(N\) offline depth-recurrent loops before KV eviction on Jet-Nemotron 2B and Ouro 1.4B.
  • Sleep-SelfMod (Behrouz et al., Jun 2026): §3.2–3.4 — adds/unmasks low-rank MoE experts in slower CMS blocks, distills via Knowledge Seeding, and resets fast experts.
  • Surprise & Metacognition (Mouchon, Jun 2026, Research Note): shows recent-only replay drops ImageNet-1000 retention to 41.2% / 0% vs. 83.5% for interleaved sleep, and token-logit confidence is anti-calibrated on novelty (AUROC 0.292).
  • MemTrace (Long et al., Jun 2026): §4–5 — Fresh vs. Saturated Trajectory collapse (Qwen3.5-35B: 49.0% → 6.7%), Conflict vs. Boundary, and Reach-vs.-Use.

1. Interleaved sleep vs. recent-only replay (why naive consolidation hurts)

Let’s test CLS directly on a tiny linear “neocortex” readout \(W \in \mathbb{R}^{C \times d}\) learning 10 sequential classes (2 classes per episode, 5 episodes) from a fast episodic buffer: 1. No replay (online SGD only): forgets Episode 0 quickly. 2. Recent-only replay (sliding window of the last 2 episodes): overfits recent episodes and crushes Episode 0 even harder — reproducing Mouchon’s (2026) striking warning! 3. Interleaved sleep replay (uniform sample across all buffered episodes): consolidates all 10 classes into the same fixed-size \(W\) with high accuracy on both oldest and newest tasks.

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

torch.manual_seed(0)
n_classes, d = 10, 24
centers = F.normalize(torch.randn(n_classes, d), dim=1) * 2.5

# Generate 5 episodes, 2 classes each
episodes = []
for ep in range(5):
    xs, ys = [], []
    for c in [2*ep, 2*ep + 1]:
        x = centers[c] + torch.randn(40, d) * 0.6
        y = torch.full((40,), c, dtype=torch.long)
        xs.append(x); ys.append(y)
    episodes.append((torch.cat(xs), torch.cat(ys)))

def eval_ep(W, ep_idx):
    X, y = episodes[ep_idx]
    return ((X @ W.T).argmax(dim=1) == y).float().mean().item()

def run_cls(replay_mode="none"):
    torch.manual_seed(0)
    W = nn.Parameter(torch.zeros(n_classes, d))
    opt = torch.optim.SGD([W], lr=0.15)
    buf = []
    ep0_acc, all_acc = [], []

    for ep in range(5):
        buf.append(episodes[ep])
        # Wake phase: train on current episode
        X, y = episodes[ep]
        for _ in range(25):
            loss = F.cross_entropy(X @ W.T, y)
            opt.zero_grad(); loss.backward(); opt.step()

        # Sleep phase: consolidate from episodic buffer
        if replay_mode == "recent":
            pool = buf[-2:]            # sliding window of only last 2 episodes!
            X_s = torch.cat([p[0] for p in pool]); y_s = torch.cat([p[1] for p in pool])
            for _ in range(30):
                loss = F.cross_entropy(X_s @ W.T, y_s)
                opt.zero_grad(); loss.backward(); opt.step()
        elif replay_mode == "interleaved":
            X_s = torch.cat([p[0] for p in buf]); y_s = torch.cat([p[1] for p in buf])
            for _ in range(30):
                loss = F.cross_entropy(X_s @ W.T, y_s)
                opt.zero_grad(); loss.backward(); opt.step()

        ep0_acc.append(eval_ep(W, 0))
        all_acc.append(sum(eval_ep(W, j) for j in range(ep + 1)) / (ep + 1))
    return ep0_acc, all_acc

e0_none, a_none = run_cls("none")
e0_rec,  a_rec  = run_cls("recent")
e0_int,  a_int  = run_cls("interleaved")

print("After Episode 5 | Oldest (Ep 0) acc | Mean across all 5 episodes")
print(f"  Online only (no sleep)  :  {e0_none[-1]*100:5.1f}%         |  {a_none[-1]*100:5.1f}%")
print(f"  Recent-only sleep       :  {e0_rec[-1]*100:5.1f}%         |  {a_rec[-1]*100:5.1f}%  (worse than no sleep!)")
print(f"  Interleaved CLS sleep   :  {e0_int[-1]*100:5.1f}%         |  {a_int[-1]*100:5.1f}%")

plt.figure(figsize=(6.8, 3.0))
plt.plot(range(1, 6), [x*100 for x in e0_none], "o-", label="Online only (no sleep)", color="#94a3b8")
plt.plot(range(1, 6), [x*100 for x in e0_rec],  "s-", label="Recent-only sleep", color="#c85a53", lw=2)
plt.plot(range(1, 6), [x*100 for x in e0_int],  "^-", label="Interleaved CLS sleep", color="#1f6f66", lw=2.2)
plt.xlabel("episode"); plt.ylabel("Episode-0 retention (%)")
plt.title("Why sleep replay must interleave old memories")
plt.legend(fontsize=8); plt.tight_layout(); plt.show()
After Episode 5 | Oldest (Ep 0) acc | Mean across all 5 episodes
  Online only (no sleep)  :   90.0%         |   95.0%
  Recent-only sleep       :   87.5%         |   95.2%  (worse than no sleep!)
  Interleaved CLS sleep   :  100.0%         |   99.8%

Look at the red line: running extra sleep steps on only the recent window drives Episode-0 accuracy below doing no sleep at all! Interleaved sleep keeps Episode-0 retention near 100% while fitting all 10 classes into the exact same fixed-size slow weight matrix \(W\).

2. MemTrace’s Reach-vs.-Use & prior-override diagnostic

Finally, suppose your memory stores a counterfactual or updated fact (e.g., “the project deadline moved from Friday to Tuesday”). Even when the memory readout vector \(\mathbf{m}_t\) is retrieved cleanly (Reach = 1), the final prediction fuses it with the backbone’s strong parametric prior \(\mathbf{p}_t\):

\[\mathbf{z}_t = \mathbf{p}_t + g_t \cdot \mathbf{m}_t.\]

If the readout gate \(g_t\) is too weak (or uncalibrated when memory and prior disagree), the prior wins (Reach = 1, Use = 0) — the exact failure MemTrace exposes across 69–88% of reachable probes, and the exact reason Chain-of-Thought readers dismiss counterfactual memory traces as “factually incorrect.” Let’s verify how a simple conflict-aware authority gate flips R=1, U=0 into R=1, U=1!

torch.manual_seed(0)
n_probes, n_ans = 200, 10

# Strong pretrained prior predicts wrong/outdated answer 0 (logit = +4.0)
prior_logits = torch.randn(n_probes, n_ans) * 0.5
prior_logits[:, 0] += 4.0

# Memory correctly retrieves updated answer 1 on 90% of probes (Reach = 90%),
# but with modest logit strength (+2.2)
reached = torch.rand(n_probes) < 0.90
mem_logits = torch.zeros(n_probes, n_ans)
mem_logits[reached, 1] = 2.2
mem_logits[~reached] = torch.randn((~reached).sum(), n_ans) * 0.2

# 1. Fixed weak fusion (g = 1.0): prior (+4.0) overrides memory (+2.2)!
out_weak = prior_logits + 1.0 * mem_logits
use_weak = (out_weak.argmax(dim=1) == 1)

# 2. Conflict-aware authority gate: when memory confidence (max - second_max) is high,
#    boost memory authority over the prior!
top2 = mem_logits.topk(2, dim=1).values
mem_conf = (top2[:, 0] - top2[:, 1]).unsqueeze(1)
g_auth = 1.0 + 1.5 * torch.sigmoid(3.0 * (mem_conf - 1.0))
out_auth = prior_logits + g_auth * mem_logits
use_auth = (out_auth.argmax(dim=1) == 1)

r_rate = reached.float().mean().item() * 100
r1_u0_weak = (reached & ~use_weak).float().sum().item() / reached.float().sum().item() * 100
r1_u0_auth = (reached & ~use_auth).float().sum().item() / reached.float().sum().item() * 100

print(f"Memory Reach rate (R=1): {r_rate:.1f}%")
print(f"  Weak fixed gate (g=1.0)    | Use accuracy: {use_weak.float().mean()*100:5.1f}% | Reach-but-not-Use (R=1,U=0): {r1_u0_weak:5.1f}%")
print(f"  Confidence-gated authority | Use accuracy: {use_auth.float().mean()*100:5.1f}% | Reach-but-not-Use (R=1,U=0): {r1_u0_auth:5.1f}%")
Memory Reach rate (R=1): 91.5%
  Weak fixed gate (g=1.0)    | Use accuracy:   0.0% | Reach-but-not-Use (R=1,U=0): 100.0%
  Confidence-gated authority | Use accuracy:  88.0% | Reach-but-not-Use (R=1,U=0):   3.8%

With Reach = 90%, a weak fixed gate gets 0% Use accuracy (R=1, U=0 on 100% of reachable probes!) because the strong prior overrides the memory every single time. A calibrated authority gate that trusts confident memory readouts flips Use accuracy right up to the Reach ceiling.

Honest scope. Real LLM readout fusion happens across 30+ residual layers and multi-step Chain-of-Thought generation, where calibrating when a memory trace is genuinely confident vs. hallucinated noise is a hard open problem (MemTrace’s Boundary vs. Conflict split). Still, this toy makes the structural point unmistakable: a lifelong plastic architecture needs all four pieces together — stable expressive storage, utility-selective plasticity control, interleaved multi-timescale consolidation, and calibrated readout authority.

Exit check

  1. Why did recent-only sleep replay score worse on Episode 0 than doing no sleep at all?
  2. How does LM-Sleep (May 2026) use offline depth-recurrent passes differently from Sleep-SelfMod (Jun 2026)?
  3. In MemTrace, what does a high (R=1, U=0) rate tell you about where the bottleneck lives — storage/retrieval or readout/reasoning?
  4. Looking back across all four tracks of this course, what is the single open architectural gap that none of the 2024–2026 papers has closed yet?

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