exp: frozen-weights probe -- the memory advantage is capacity, not state

This commit is contained in:
chrnx committed 2026-09-02 09:08:04 -05:00
1 parent 55a57d8924
commit f8acee6835
3 files changed
+939

No files matched your search

+448
View File
@@ -0,0 +1,448 @@
"""Task 7b: frozen-weights probe. Train, freeze every parameter, keep stepping.
Task 7 measured memory's advantage at lr=1e-3 and watched it decay to 1.06x at
lr=1e-2: mean error cannot tell state and fast weights apart, because raising lr
buys the same adaptation speed that memory buys. This file removes learning
instead of retuning it. After the freeze no parameter may change, so nothing the
model does can be attributed to an optimiser step. A frozen `rp_only` still carries
the 2-d affect state (`--freeze-affect` pins that too); a frozen `grp_k0` still
updates its per-entity M every step through the gate.
Part A measures recovery after a switch under frozen weights. Part B asks what the
state knows, by linearly decoding the world's regime id out of M (GRP) and out of h
(RP), against an empirically measured chance level.
What survives the freeze is state *only if the two conditions are capacity-matched*,
and they are not: `rp_only` has 1442 parameters and `grp_k0` 5602. `--ablate-state`
supplies the control that separates the two. See results/frozen.md; it is what turns
this file's result from a memory effect into a null.
"""
from __future__ import annotations
import argparse
import json
import statistics
from pathlib import Path
import numpy as np
import torch
from torch import Tensor, nn
from ailed import Affect, AffectConfig, Organism, detach_memory, update
from particles import ParticleConfig, ParticleWorld, wrapped_diff
from regime import CONDITIONS, KAPPA_FLAG, _context, _metrics
TRAIN_STEPS = 8000 # matches the budget every headroom table in results/headroom.md used
FROZEN_STEPS = 4000
SPLIT = 0.7 # probe train fraction, taken as a prefix in time
# -- construction and the two phases ---------------------------------------------
def _build(name: str, seed: int, hidden: int, omega: float, kappa: float):
"""Construct exactly as `regime.run` does, in the same order, so the RNG stream matches."""
spec = dict(CONDITIONS[name])
if spec["kappa"] == KAPPA_FLAG:
spec["kappa"] = kappa
wcfg = ParticleConfig(seed=seed, oracle=spec["oracle"])
torch.manual_seed(seed)
world = ParticleWorld(wcfg)
ctx_dim = wcfg.n_regimes if spec["ctx"] == "regime" else 2
org = Organism(attr_dim=world.attr_dim, coord_dim=2, target_dim=2, context_dim=ctx_dim,
hidden_dim=hidden, omega=omega, kappa=spec["kappa"], memory=spec["memory"])
return spec, wcfg, world, org
def _train(spec: dict, wcfg: ParticleConfig, world: ParticleWorld, org: Organism,
steps: int, bptt: int, lr: float, stateless: bool = False):
"""A verbatim copy of `regime.run`'s training loop (`stateless` aside).
Copied rather than reused because `regime.run` returns metrics and drops the
organism and the world, and this task has to keep stepping the same world with
the same organism after training ends. `tests/test_frozen.py` pins the copy: it
asserts this loop reproduces `regime.run`'s metrics bit-identically.
`stateless=True` hands the organism an empty memory dict every step, so M_prev is
always zero. The GRP keeps every parameter it had and loses only the carrying of
state -- the control that separates "memory helps" from "the GRP's extra 4160
parameters help". It is a call into the public API, not a change to the library.
"""
opt = torch.optim.Adam(org.parameters(), lr=lr)
acfg = AffectConfig()
affect = Affect()
memory: dict[int, Tensor] = {}
losses, switched, arousals = [], [], []
pending = []
for t in range(steps):
obs = world.step()
ctx = _context(spec["ctx"], affect, obs.regime, wcfg.n_regimes)
pred, memory = org(obs.attrs, wrapped_diff(obs.coords), obs.ids, affect.axes,
{} if stateless else memory, context=ctx)
loss = ((pred - obs.target) ** 2).mean()
pending.append(loss)
affect = update(affect, loss.item(), acfg)
losses.append(loss.item()); switched.append(obs.switched); arousals.append(affect.arousal)
if len(pending) == bptt:
opt.zero_grad()
torch.stack(pending).mean().backward()
opt.step()
pending = []
memory = detach_memory(memory)
trace = dict(losses=losses, switched=switched, arousals=arousals)
return affect, detach_memory(memory), trace
def _hidden(org: Organism, attrs: Tensor, r: Tensor, axes: tuple[float, float],
ctx: Tensor | None) -> Tensor:
"""h as `Organism.forward` computes it, by mirroring the tensors it builds internally.
`Organism.forward` returns only `out(h)` (or `out(M)`), so h has to be recomputed
from the public `org.rp`. Every argument here is built the way core.py builds it;
`_frozen` asserts the reconstruction is bit-identical to the organism's own output.
"""
n = attrs.shape[0]
valence, arousal = axes
if ctx is None:
ctx = torch.tensor([valence, arousal], dtype=attrs.dtype)
edge_types = torch.zeros(n, n, dtype=torch.long)
mask = torch.ones(n, n, dtype=attrs.dtype)
edge_onehot = nn.functional.one_hot(edge_types, org.n_edge_types).to(attrs.dtype)
return org.rp(attrs, r, edge_onehot, mask, ctx)
def _frozen(spec: dict, wcfg: ParticleConfig, world: ParticleWorld, org: Organism,
affect: Affect, memory: dict[int, Tensor], steps: int,
freeze_affect: bool = False, stateless: bool = False) -> dict:
"""Step the world with every parameter frozen. Memory and affect keep updating.
`freeze_affect` additionally pins (valence, arousal) at their end-of-training
values. It exists because `rp_only` runs with `ctx="affect"`, so a frozen RP is
*not* a fixed function of the current observation: affect is a 2-d state that
updates from the loss and feeds the CPPN. Pinning it removes the RP's last
adaptive channel and tests the premise Part A rests on."""
for p in org.parameters():
p.requires_grad_(False)
before = nn.utils.parameters_to_vector(org.parameters()).clone()
acfg = AffectConfig()
zero = torch.zeros(org.hidden_dim)
losses, switched, arousals, regimes = [], [], [], []
h_reps, m_reps, dM, gates, couple = [], [], [], [], []
# the regime id is an arbitrary label over four random coupling matrices; what an
# entity actually needs is its own row of the current one. Decoding the id can be
# at chance while the row is not, so both are probed.
rows = torch.stack([k[world.types] for k in world.regimes]) # (n_regimes, N, n_types)
with torch.no_grad():
for t in range(steps):
obs = world.step()
ctx = _context(spec["ctx"], affect, obs.regime, wcfg.n_regimes)
if stateless:
memory = {}
prev = torch.stack([memory.get(i, zero) for i in obs.ids]) if org.use_memory else None
r = wrapped_diff(obs.coords)
pred, memory = org(obs.attrs, r, obs.ids, affect.axes, memory, context=ctx)
loss = ((pred - obs.target) ** 2).mean()
h = _hidden(org, obs.attrs, r, affect.axes, ctx)
if org.use_memory:
M = torch.stack([memory[i] for i in obs.ids])
# if this holds, h is exactly the h the organism used
assert torch.equal(org.grp(h, prev, affect.arousal), M), "h reconstruction diverged"
m_reps.append(M.numpy().copy())
dM.append(float((M - prev).abs().max()))
g = torch.sigmoid(org.grp.gate(torch.cat([h, prev], -1)) - org.grp.kappa * affect.arousal)
gates.append((float(g.mean()), float(g.std()), float((g > 0.9).float().mean()),
float((g < 0.1).float().mean())))
else:
assert torch.equal(org.out(h), pred), "h reconstruction diverged"
h_reps.append(h.numpy().copy())
if not freeze_affect:
affect = update(affect, loss.item(), acfg)
losses.append(loss.item()); switched.append(obs.switched)
arousals.append(affect.arousal); regimes.append(obs.regime)
couple.append(rows[obs.regime].numpy().copy())
after = nn.utils.parameters_to_vector(org.parameters())
frozen_ok = bool(torch.equal(before, after))
assert frozen_ok, "a parameter changed during the frozen phase"
assert not any(p.requires_grad for p in org.parameters())
if org.use_memory and not stateless:
# freezing is about parameters, not state: if M stopped moving the GRP would
# have silently degenerated into an RP and any null would be for the wrong reason
assert min(dM[1:]) > 0.0, "M did not change between consecutive frozen steps"
return dict(losses=losses, switched=switched, arousals=arousals, regimes=regimes,
couple=(np.stack(couple) + 1).astype(int), # {-1,0,1} -> class {0,1,2}
gate=dict(zip(("mean", "sd", "frac_open", "frac_shut"),
(statistics.fmean(c) for c in zip(*gates)))) if gates else None,
h=np.stack(h_reps), M=np.stack(m_reps) if m_reps else None,
frozen_bit_identical=frozen_ok, n_params=int(before.numel()),
dM_min=min(dM[1:]) if dM else None,
dM_mean=statistics.fmean(dM[1:]) if dM else None)
# -- Part B: the linear probe ----------------------------------------------------
def _fit_lsq(X: np.ndarray, y: np.ndarray, R: int, ridge: float = 1e-6) -> np.ndarray:
G = X.T @ X
lam = ridge * np.trace(G) / X.shape[1]
return np.linalg.solve(G + lam * np.eye(X.shape[1]), X.T @ np.eye(R)[y])
def _fit_logit(X: np.ndarray, y: np.ndarray, R: int, l2: float = 1e-4) -> np.ndarray:
"""Multinomial logistic, so a null cannot be blamed on least squares.
X already carries the bias column, so the linear map needs no separate intercept.
LBFGS with strong-Wolfe converges deterministically here; there is no seed."""
Xt = torch.tensor(X); yt = torch.tensor(y, dtype=torch.long)
W = torch.zeros(X.shape[1], R, dtype=torch.float64, requires_grad=True)
opt = torch.optim.LBFGS([W], max_iter=300, tolerance_grad=1e-10,
line_search_fn="strong_wolfe")
def closure():
opt.zero_grad()
loss = nn.functional.cross_entropy(Xt @ W, yt) + l2 * (W[:-1] ** 2).sum()
loss.backward()
return loss
opt.step(closure)
return W.detach().numpy()
ESTIMATORS = {"lsq": _fit_lsq, "logit": _fit_logit}
def _design(reps: np.ndarray, mu: np.ndarray, sd: np.ndarray) -> np.ndarray:
"""(T, N, D) -> (T*N, D+1): standardised features plus a bias column."""
flat = reps.reshape(-1, reps.shape[-1]).astype(np.float64)
z = (flat - mu) / sd
return np.concatenate([z, np.ones((z.shape[0], 1))], axis=1)
def _scores(reps: np.ndarray, W: np.ndarray, mu: np.ndarray, sd: np.ndarray) -> np.ndarray:
return (_design(reps, mu, sd) @ W).reshape(reps.shape[0], reps.shape[1], -1)
def _accuracy(scores: np.ndarray, lab: np.ndarray, step_lab: np.ndarray | None) -> tuple[float, float]:
"""(per-entity accuracy, per-step accuracy after averaging the entity scores).
The per-step vote only exists when every entity shares one label; a per-entity
target such as the coupling row has no step-level answer to vote on.
"""
ent = float((scores.argmax(-1) == lab).mean())
step = float((scores.mean(1).argmax(-1) == step_lab).mean()) if step_lab is not None else float("nan")
return ent, step
def probe(reps: np.ndarray, labels: np.ndarray, switched: list[bool], n_regimes: int,
split: float = SPLIT, n_null: int = 20, seed: int = 0,
estimator: str = "lsq", center: bool = False) -> dict:
"""Linear decode from a representation onto a categorical target, split by time.
`labels` is either one label per step, shape (T,) -- the regime id -- or one per
entity per step, shape (T, N) -- the coupling row the current regime hands that
entity. The test split is a suffix in time, never a random subset, so the probe
cannot memorise steps adjacent to the ones it is scored on. Chance is measured,
not assumed, by two nulls that both refit the probe from scratch.
"""
if center:
# subtract each entity's own mean, computed on the probe-train prefix only.
# M is dominated by stable per-entity identity (the particle's type); if a
# regime code is hiding underneath that offset, this is what exposes it.
reps = reps - reps[:int(reps.shape[0] * split)].mean(0, keepdims=True)
T, N = reps.shape[0], reps.shape[1]
per_step = labels.ndim == 1
lab = np.repeat(labels[:, None], N, axis=1) if per_step else labels
cut = int(T * split)
tr, te = slice(0, cut), slice(cut, T)
fit = ESTIMATORS[estimator]
flat_tr = reps[tr].reshape(-1, reps.shape[-1]).astype(np.float64)
mu, sd = flat_tr.mean(0), flat_tr.std(0) + 1e-12
def fit_eval(z: np.ndarray) -> tuple[float, float, np.ndarray]:
W = fit(_design(reps[tr], mu, sd), z[tr].reshape(-1), n_regimes)
s = _scores(reps[te], W, mu, sd)
return _accuracy(s, lab[te], labels[te] if per_step else None) + (s,)
ent, step, s_te = fit_eval(lab)
# null 1: permute the step-level labels, keeping the 16 entities of a step together
# null 2: circularly shift the label sequence, which also keeps each regime's
# 40-80 step block structure intact -- the stricter of the two, because a
# probe that merely tracks slow drift still scores at this level
rng = np.random.default_rng(seed)
shuf, shift = [], []
for _ in range(n_null):
shuf.append(fit_eval(rng.permutation(lab))[0])
k = int(rng.integers(T // 10, T - T // 10))
shift.append(fit_eval(np.roll(lab, k, axis=0))[0])
# latency: steps from a switch until the decoded regime first matches the true one,
# measured on the test split only, and censored at the next switch
sw = [i for i, f in enumerate(switched[cut:]) if f]
lat, censored = [], 0
if per_step:
decoded, true = s_te.mean(1).argmax(-1), labels[te]
for a, b in zip(sw, sw[1:] + [T - cut]):
hit = next((k for k in range(b - a) if decoded[a + k] == true[a]), None)
if hit is None:
censored += 1
else:
lat.append(hit)
return dict(
estimator=estimator, centered=center, acc_entity=ent, acc_step=step,
chance_shuffle=float(np.mean(shuf)), chance_shuffle_max=float(np.max(shuf)),
chance_shift=float(np.mean(shift)), chance_shift_max=float(np.max(shift)),
n_test_steps=int(T - cut), n_test_switches=len(sw),
latency=float(np.mean(lat)) if lat else float("nan"),
latency_median=float(np.median(lat)) if lat else float("nan"),
censored=censored,
)
def persistence(reps: np.ndarray, max_lag: int = 60) -> dict:
"""Lag-1 autocorrelation and the lag where it falls below 1/e, per channel.
Model-agnostic, so `h` and `M` are measured the same way. It answers what the
state is doing when the regime is not decodable from it: a large integration
time means the GRP is running a temporal filter, not a regime classifier.
"""
x = reps - reps.mean(0, keepdims=True)
sd = x.std(0) + 1e-12
ac = [float((x[:-k] * x[k:]).mean(0).__truediv__(sd * sd).mean()) for k in range(1, max_lag + 1)]
tau = next((k + 1 for k, v in enumerate(ac) if v < np.exp(-1.0)), max_lag)
return dict(lag1=ac[0], tau=tau, ac=ac[:20])
# -- driver ----------------------------------------------------------------------
def run_one(name: str, seed: int, train_steps: int = TRAIN_STEPS, frozen_steps: int = FROZEN_STEPS,
window: int = 20, bptt: int = 20, lr: float = 1e-3, hidden: int = 32,
kappa: float = 4.0, omega: float = 10.0, freeze_affect: bool = False,
probes: bool = True, stateless: bool = False) -> dict:
spec, wcfg, world, org = _build(name, seed, hidden, omega, kappa)
if window >= wcfg.t_min:
raise ValueError(f"window={window} must be < t_min={wcfg.t_min}")
affect, memory, tr = _train(spec, wcfg, world, org, train_steps, bptt, lr, stateless)
fr = _frozen(spec, wcfg, world, org, affect, memory, frozen_steps, freeze_affect, stateless)
labels = np.asarray(fr["regimes"])
which = "M" if fr["M"] is not None else "h"
out = dict(
condition=name + ("_nostate" if stateless else ""), seed=seed,
train_steps=train_steps, frozen_steps=frozen_steps,
freeze_affect=freeze_affect, stateless=stateless,
n_params_rp=sum(p.numel() for p in org.rp.parameters()),
trained=_metrics(tr["losses"], tr["switched"], tr["arousals"], window),
frozen=_metrics(fr["losses"], fr["switched"], fr["arousals"], window),
frozen_bit_identical=fr["frozen_bit_identical"], n_params=fr["n_params"],
dM_min=fr["dM_min"], dM_mean=fr["dM_mean"], probe_on=which,
)
if not probes:
return out
# every variant on every representation the condition has: `M` is the GRP's state,
# `h` the RP output it is built from. Reporting `h` for the GRP too makes the
# comparison within one organism, holding the weights fixed.
got, pers = {}, {}
for tag, rep in (("M", fr["M"]), ("h", fr["h"])):
if rep is None:
continue
args = (rep, labels, fr["switched"], wcfg.n_regimes)
got[f"{tag}_lsq"] = probe(*args, seed=seed)
got[f"{tag}_lsq_centered"] = probe(*args, seed=seed, center=True)
got[f"{tag}_logit"] = probe(*args, seed=seed, n_null=5, estimator="logit")
for c in range(wcfg.n_types): # the coupling this entity's own type feels
got[f"{tag}_couple{c}"] = probe(rep, fr["couple"][:, :, c], fr["switched"],
3, seed=seed, n_null=10)
pers[tag] = persistence(rep)
out["probes"] = got
out["persistence"] = pers
out["gate"] = fr["gate"]
out["probe"] = got[f"{which}_lsq"] # headline
return out
def norm_table(results: list[dict], key: str = "frozen") -> str:
"""recovery[k] / steady, normalised per seed before averaging.
The raw curves are not comparable across conditions whose steady error differs
3x; this asks the shape question -- how far above its own floor does a condition
go after a switch, and does it come back down.
"""
by: dict[str, list[dict]] = {}
for r in results:
by.setdefault(r["condition"], []).append(r)
idxs = list(range(0, 20, 2)) + [19]
lines = [f"{'condition':<12}" + "".join(f"{'@' + str(i):>7}" for i in idxs),
"-" * (12 + 7 * len(idxs))]
for name, rs in by.items():
ratios = [[r[key]["recovery"][i] / r[key]["steady"] for i in idxs] for r in rs]
lines.append(f"{name:<12}" + "".join(f"{statistics.fmean(c):>7.2f}" for c in zip(*ratios)))
return "\n".join(lines)
def table(results: list[dict], key: str = "frozen") -> str:
by: dict[str, list[dict]] = {}
for r in results:
by.setdefault(r["condition"], []).append(r)
idxs = [0, 1, 2, 5, 10, 19]
head = "".join(f"{'rec@' + str(i):>11}" for i in idxs)
lines = [f"{'condition':<12}{'steady':>11}{'(sd)':>11}{'min':>11}{'max':>11}{head}",
"-" * (12 + 44 + 11 * len(idxs))]
for name, rs in by.items():
st = [r[key]["steady"] for r in rs]
row = "".join(f"{statistics.fmean(r[key]['recovery'][i] for r in rs):>11.3e}" for i in idxs)
sd = statistics.stdev(st) if len(st) > 1 else 0.0
lines.append(f"{name:<12}{statistics.fmean(st):>11.3e}{sd:>11.3e}"
f"{min(st):>11.3e}{max(st):>11.3e}{row}")
return "\n".join(lines)
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--conditions", default="rp_only,grp_k0")
ap.add_argument("--seeds", default="0,1,2,3,4,5,6,7")
ap.add_argument("--train-steps", type=int, default=TRAIN_STEPS)
ap.add_argument("--frozen-steps", type=int, default=FROZEN_STEPS)
ap.add_argument("--window", type=int, default=20)
ap.add_argument("--lr", type=float, default=1e-3)
ap.add_argument("--freeze-affect", action="store_true",
help="also pin (valence, arousal) in the frozen phase, so a frozen "
"rp_only really is a fixed function of the observation")
ap.add_argument("--no-probes", action="store_true")
ap.add_argument("--ablate-state", action="store_true",
help="hand the organism an empty memory every step: same parameters, "
"no state carried. Separates memory from the GRP's extra capacity.")
ap.add_argument("--out", default="results/frozen.json")
a = ap.parse_args()
results = []
for name in a.conditions.split(","):
for seed in (int(s) for s in a.seeds.split(",")):
r = run_one(name, seed, a.train_steps, a.frozen_steps, window=a.window, lr=a.lr,
freeze_affect=a.freeze_affect, probes=not a.no_probes,
stateless=a.ablate_state)
f = r["frozen"]
msg = (f"{r['condition']:<18} seed={seed} frozen_steady={f['steady']:.3e} "
f"rec@0={f['recovery'][0]:.3e} rec@10={f['recovery'][10]:.3e}")
if "probe" in r:
p = r["probe"]
msg += (f" probe({r['probe_on']})={p['acc_entity']:.3f} "
f"chance={p['chance_shift']:.3f} lat={p['latency']:.1f}")
print(msg, flush=True)
results.append(r)
Path(a.out).parent.mkdir(parents=True, exist_ok=True)
Path(a.out).write_text(json.dumps(results, indent=1))
for key in ("trained", "frozen"):
print(f"\n{key} phase:"); print(table(results, key))
print(f"{key} recovery / steady:"); print(norm_table(results, key))
if __name__ == "__main__":
main()
+318
View File
@@ -0,0 +1,318 @@
# Frozen-weights probe: does memory have a job once learning is out of the picture?
Task 7b. Task 7 measured memory beating memoryless 2.99x at `lr=1e-3` and watched
that margin decay to 1.06x at `lr=1e-2`, so mean error cannot tell state and fast
weights apart. This file removes learning instead of retuning it: train, freeze every
parameter, keep stepping the world. Nothing after the freeze can be attributed to an
optimiser step.
**Verdict: a clean null, twice over. Memory is not doing the work, and neither model
builds an internal regime variable.**
1. Under frozen weights `grp_k0` beats `rp_only` 2.50x on steady error, on 8/8 seeds.
**That entire margin is the GRP's extra 4160 parameters, not its state.** The same
architecture with the state ablated — every parameter kept, an empty memory handed
in each step — measures 2.170e-05 against `grp_k0`'s 2.101e-05. Memory is worth
1.06x, on 4 seeds out of 8. Its recovery curve is indistinguishable at every lag.
2. The regime is decodable from `M` at 0.332 against a measured chance of 0.273. It is
decodable from the memoryless RP's `h` at 0.342 against 0.274. **`M` knows no more
about the regime than the feedforward representation it is built from** — slightly
less — and the same +0.05 appears in a state-free network, so it is a read-off of
the current configuration, not a memory.
3. The mechanism is visible: the gate sits at `g = 0.500 ± 0.029`, never above 0.9,
never below 0.1, on any seed. It is at its initialisation. The GRP as trained here
is not gating anything.
Environment: `experiments/`, `ailed/` unmodified, no default in `particles.py` or
`regime.py` changed. 8 seeds (0-7), 8000 training steps then 4000 frozen steps,
`lr=1e-3`, `bptt=20`, `hidden=32`, `omega=10`, `kappa=0`, `window=20`. Noise floor
`noise² = 4.0e-06`. 40 runs total.
```
uv run python frozen.py --out results/frozen.json
uv run python frozen.py --conditions grp_k0 --ablate-state --out results/frozen_nostate.json
uv run python frozen.py --freeze-affect --no-probes --out results/frozen_affect.json
```
## 0. The freeze audit
Both guards the brief asked for, asserted in code on every run, not checked by eye.
| check | how | result |
|---|---|---|
| no parameter moved | `parameters_to_vector` snapshot before/after the frozen phase, `torch.equal` | **bit-identical on 40/40 runs** |
| nothing could move | `requires_grad=False` on every parameter *and* the whole phase under `torch.no_grad()`, no optimiser constructed | asserted |
| memory kept updating | `min_t max_i |M_t − M_{t−1}|` over the frozen phase | **2.587e-04**, over every grp run |
| the assertion can fail | `test_frozen_phase_detects_a_parameter_change` nudges `out.bias` by 1e-6 after the snapshot | raises, as required |
| `h` is the organism's `h` | `org.grp(h, M_prev, arousal)` must equal the M the organism returned; `org.out(h)` must equal the pred it returned | `torch.equal`, every step of every run |
Mean per-step memory movement is 1.06e-02, four orders above the detection threshold,
so the GRP is running as a GRP throughout. `_train` is a verbatim copy of
`regime.run`'s loop; `test_train_copy_is_identical_to_regime_run` asserts it
reproduces `regime.run`'s metrics exactly, so the frozen phase starts from the
organism Task 7 measured.
Parameter counts, which turn out to be the whole story: `rp_only` **1442**,
`grp_k0` **5602**. The RP is identical in both (1376); the GRP adds a 64→32 gate and
a 64→32 candidate layer, 4160 parameters, 3.9x the total.
## 1. Part A — frozen recovery
Metrics come from `regime._metrics` applied to the frozen phase, so they are
comparable with Task 7's; as there, they are computed on the second half of the phase.
### 1a. The headline, and the control that dissolves it
Frozen-phase `steady`, means over seeds 0-7. `grp_k0_nostate` is `grp_k0` with an
empty memory dict handed to `Organism.forward` every step, in training and in the
frozen phase: identical architecture, identical 5602 parameters, `M_prev` always zero.
It is the capacity-matched feedforward control.
```
condition steady sd min max max/min n_params
------------------------------------------------------------------------------
rp_only 5.257e-05 2.924e-05 2.644e-05 1.054e-04 3.99 1442
grp_k0_nostate 2.170e-05 5.155e-06 1.531e-05 2.733e-05 1.78 5602
grp_k0 2.101e-05 6.430e-06 1.426e-05 3.515e-05 2.46 5602
```
Decomposed per seed, which is what carries it:
```
mean median seeds won
capacity rp_only / nostate 2.51x 1.94x 8/8
state nostate / grp_k0 1.06x 1.00x 4/8
```
Per-seed `nostate / grp_k0`: 1.49 0.92 1.33 0.92 0.90 1.08 0.78 1.10. Four above one,
four below. **Removing the state costs nothing.** The same decomposition in the
trained phase gives capacity 3.06x on 8/8 seeds and state 1.25x on 4/8.
Per-seed frozen `steady`:
```
condition s0 s1 s2 s3 s4 s5 s6 s7
--------------------------------------------------------------------------------------------
rp_only 4.298e-05 3.808e-05 3.098e-05 3.205e-05 1.054e-04 5.585e-05 8.881e-05 2.644e-05
grp_k0_nostate 2.588e-05 1.531e-05 2.665e-05 1.992e-05 1.736e-05 2.545e-05 2.733e-05 1.573e-05
grp_k0 1.742e-05 1.656e-05 2.006e-05 2.170e-05 1.931e-05 2.365e-05 3.515e-05 1.426e-05
```
Note also that the across-seed spread — Task 7's "memory buys reliability" reading —
goes the same way. `grp_k0_nostate` has the *tightest* spread of the three (1.78x
max/min, against `grp_k0`'s 2.46x). Reliability is capacity here too.
### 1b. The recovery shape: the prediction under test fails
Raw `recovery[k]`, frozen phase, means over seeds:
```
condition rec@0 rec@5 rec@10 rec@19 steady
-------------------------------------------------------------------
rp_only 5.506e-05 7.311e-05 8.078e-05 6.563e-05 5.257e-05
grp_k0_nostate 2.708e-05 3.749e-05 4.246e-05 2.769e-05 2.170e-05
grp_k0 2.756e-05 3.824e-05 4.311e-05 2.756e-05 2.101e-05
```
`grp_k0` and `grp_k0_nostate` agree to within 2% at every lag. The state changes the
post-switch trajectory not at all.
The brief's prediction was that frozen `rp_only` steps up at each switch and never
comes back down, while frozen `grp_k0` rises and decays. Normalising each seed by its
own steady error before averaging — the only way to compare shapes across conditions
whose floors differ 2.5x:
```
condition @0 @2 @4 @6 @8 @10 @12 @14 @16 @18 @19 peak decay
----------------------------------------------------------------------------------------
rp_only 1.16 1.35 1.49 1.66 1.68 1.59 1.52 1.43 1.38 1.34 1.30 1.69@7 57%
grp_k0_nostate 1.31 1.40 1.54 1.92 2.09 2.06 1.87 1.64 1.46 1.35 1.31 2.13@9 73%
grp_k0 1.42 1.47 1.69 2.06 2.22 2.18 1.97 1.72 1.51 1.40 1.35 2.24@9 72%
```
("decay" is the fraction of the peak excess over steady that is gone by `@19`.)
**The frozen memoryless RP does come back down** — 57% of the way, with no parameter
having moved and no per-entity state to move. And `grp_k0`'s *relative* excursion is
larger, not smaller: it peaks at 2.24x its own floor against the RP's 1.69x, and peaks
two steps later.
The reason is that `recovery[k]` under frozen weights is not measuring the model. At a
switch the particle configuration is equilibrated to the old regime; the new coupling
matrix then drives it somewhere else over the next 10-20 steps. That transient belongs
to the world, and a fixed function of the configuration inherits it. **Under frozen
weights `recovery[k]` measures the world's post-switch transient, not adaptation**, and
the state-ablation row proves it directly: same curve with the state and without it.
### 1c. The RP is not quite static — controlled for
`CONDITIONS["rp_only"]` uses `ctx="affect"`, so `(valence, arousal)` feeds the CPPN.
Affect is updated from `loss.item()` every step and freezing weights does not freeze
it. **A frozen `rp_only` therefore is not a fixed function of the current observation**
as the brief assumed: it retains a 2-d state. Re-running the frozen phase with affect
also pinned at its end-of-training value:
```
condition affect live affect pinned
-------------------------------------------
rp_only 5.257e-05 4.906e-05
grp_k0 2.101e-05 2.057e-05
ratio 2.50x 2.26x (8/8 seeds either way)
```
Removing the RP's last adaptive channel does not rescue the prediction — the RP's
decay gets *stronger* (74% of the excess, up from 57%), confirming the decay is the
world's, not affect's.
## 2. Part B — what does the state know?
Linear decode from a per-entity representation to the world's regime id. Test split is
the last 30% of the frozen phase, taken as a suffix in time so the probe cannot
memorise adjacent steps: 2800 training steps × 16 entities = 44 800 samples, 1200 test
steps, ~20 switches per seed.
Chance is measured, not assumed. Two nulls, each refitting the probe from scratch:
`shuffle` permutes the step labels (keeping a step's 16 entities together), `shift`
circularly shifts the label sequence, which also preserves each regime's 40-80 step
block structure and is therefore the stricter of the two — a probe that merely tracks
slow drift still scores at the `shift` level. Both land near 0.27, above the naive
1/4 = 0.25, which is exactly why the brief asked for it to be measured.
```
representation acc shuffle shift gap seeds > chance
---------------------------------------------------------------------------------
rp_only h, least squares 0.342 0.289 0.274 +0.067 8/8
rp_only h, logistic 0.341 0.289 0.276 +0.065 8/8
rp_only h, entity-centred0.341 0.289 0.274 +0.067 8/8
grp_k0 h, least squares 0.338 0.292 0.274 +0.065 7/8
grp_k0 h, logistic 0.344 0.299 0.275 +0.069 7/8
grp_k0 M, least squares 0.332 0.287 0.273 +0.058 7/8
grp_k0 M, logistic 0.332 0.293 0.276 +0.056 7/8
grp_k0 M, entity-centred0.333 0.287 0.273 +0.060 7/8
grp_k0_nostate M, least squares 0.325 0.288 0.275 +0.050 --
```
**The claim under test fails.** The regime is weakly decodable from `M` — and equally
weakly decodable from the memoryless RP's `h`, and from the `h` inside the very same
GRP organism, which is the comparison that holds the weights fixed. `M` is
consistently the *worst* of the three. The GRP's state has not built a regime variable;
it has not even preserved as much regime information as the layer feeding it.
The last row settles what the +0.05 is: the state-ablated GRP, whose `M` is a fixed
function of the current `h` with nothing carried between steps, decodes at 0.325. The
signal is an instantaneous read-off of the particle configuration — the field the
regime is currently imposing is visible in `r` right now — not something a memory
accumulated.
Three ways the null was stressed, none of which changes it:
- **Estimator.** Multinomial logistic (LBFGS, strong Wolfe) matches least squares to
within 0.006 everywhere. Not a least-squares artefact.
- **Entity identity.** `M` is dominated by stable per-entity structure (the particle's
type). Subtracting each entity's own train-split mean, in case a regime code hides
under that offset, moves accuracy by ≤0.002.
- **Target.** The regime id is an arbitrary label over four random coupling matrices;
what entity *i* actually needs is its own row `k[t_i, :]` of the current one. Probing
each of the three signed entries as a 3-class problem, against measured chance:
```
representation acc chance gap above chance
-------------------------------------------------------
rp_only h 0.514 0.488 +0.025 20/24
grp_k0 h 0.517 0.484 +0.033 22/24
grp_k0 M 0.506 0.482 +0.024 21/24
```
Same picture on the target the domain actually rewards: `M` last, `h` no worse.
### Adaptation latency
Reported for completeness and not interpretable. Decoding the regime per step by
averaging the 16 entities' probe scores, the mean number of steps from a switch to the
first correct decode is 12.0 for `M` and 10.7 for `rp_only`'s `h` — but 40 of 164
switches never decode correctly before the next switch arrives. **A latency measured
off a probe running 5 points above chance is measuring the probe's noise.** The honest
statement is that neither representation supports reliable regime decoding, so neither
has a measurable adaptation latency by this route.
## 3. What the state is doing instead
The gate, measured over every frozen step and entity:
```
condition mean g sd frac g>0.9 frac g<0.1
---------------------------------------------------------
grp_k0 0.500 0.029 0.000 0.000
grp_k0_nostate 0.509 0.025 0.000 0.000
```
`g = σ(W_g[h‖M] − κa)` with `κ = 0`. A mean of 0.500 with sd 0.029 and no saturation
in either direction, on every seed, means the gate's pre-activation is sitting at zero:
it is at its initialisation and 8000 training steps have not moved it. The update
`M ← (1−g)M̃ + gM` degenerates to a fixed 50/50 blend — a two-step exponential moving
average of `tanh(W_c[h‖M])`, with no input dependence. **Nothing is being decided about
what to keep.**
Persistence confirms there is no long integration to point at. Lag-1 autocorrelation
and the lag at which it falls below 1/e, per channel:
```
condition rep lag-1 tau
--------------------------------------
rp_only h 0.964 18.1
grp_k0 h 0.960 14.0
grp_k0 M 0.980 13.6
grp_k0_nostate M 0.959 13.1
```
`M` is marginally smoother at lag 1 than the `h` it is built from, and *less* persistent
over the 1/e horizon than the memoryless RP's own `h`. Representations in this domain
are slow because the world is slow, not because anything is integrating them.
## 4. Which one understands the domain?
**Neither, and the question does not currently have a mechanism to attach to.**
There is no evidence in this experiment that either model has come to represent which
regime the world is in. The regime is weakly present in both models' representations at
about +0.05 over a measured chance of 0.27, and it is present in exactly the same
amount in a network with no state at all, which identifies it as an instantaneous
read-off of the visible configuration rather than an internal variable either organism
built.
What the frozen probe does establish, and it is worth having:
- **The margin is real and it is not a learning-rate artefact.** With every weight
bit-frozen, the gated architecture predicts 2.5x better than the plain relational
perceptron, on 8 seeds out of 8. Task 7's `lr` objection is answered: no optimiser
step is available to either model here.
- **The margin is not memory.** It is 4160 extra feedforward parameters. Ablating the
state while keeping them preserves the entire effect (1.06x, 4/8 seeds) and leaves
the recovery curve unchanged at every lag.
- **The GRP's gate is untrained.** It sits at 0.5 with no input dependence, which is a
sufficient mechanistic explanation for both nulls and is a fact about this setup, not
about the architecture.
The last point is the actionable one. This is a measured null about *this* domain and
*this* training budget, not an impossibility result. The gate never learned to gate,
and §1b explains why it had no reason to: the post-switch error is dominated by the
world's own configuration transient, which no amount of state can shorten. A domain
where regime identity is worth something to a per-entity state — where the transient is
short and the ambiguity is long — would give the gate a job. This one does not, which
is the same conclusion §6(c) of `headroom.md` reached from the other direction.
## 5. Consequences for A1
- **Do not claim A1 as a memory result on this domain.** The frozen-weights version of
the comparison, which is the strongest form available, attributes the margin to
capacity. Any A1 comparison of `rp_only` to `grp_k0` is confounded 3.9x on parameter
count and needs `grp_k0_nostate` alongside it, in the trained setting too, where the
same decomposition gives capacity 3.06x on 8/8 seeds and state 1.25x on 4/8.
- **Task 7's requirement 2 inherits this.** The 2.99x at `lr=1e-3` and the
frozen-*regime* reliability argument in `headroom.md` §5 were both measured without a
capacity control. Neither is safe to quote as a memory claim as it stands. The
frozen-regime runs should be re-run with `grp_k0_nostate` before §5's "memory reaches
the floor every time" sentence is carried into the paper.
- **`recovery[k]` is not an adaptation measurement in this domain.** It tracks the
world's post-switch transient, and a stateless frozen model reproduces its shape. Any
A1 claim phrased on recovery curves needs a different observable.
+173
View File
@@ -0,0 +1,173 @@
import numpy as np
import pytest
import torch
from torch import nn
import frozen
import regime
from frozen import _build, _frozen, _hidden, _train, probe, run_one
@pytest.mark.parametrize("name", ["rp_only", "grp_k0"])
def test_train_copy_is_identical_to_regime_run(name):
"""`_train` is a verbatim copy of `regime.run`'s loop; this pins it.
If anyone edits either loop apart from the other, the metrics diverge and this
fails -- which is the only guarantee that the frozen phase starts from the same
organism Task 7 measured.
"""
steps, window, bptt = 400, 20, 20
spec, wcfg, world, org = _build(name, seed=0, hidden=32, omega=10.0, kappa=4.0)
_, _, tr = _train(spec, wcfg, world, org, steps, bptt, lr=1e-3)
mine = regime._metrics(tr["losses"], tr["switched"], tr["arousals"], window)
theirs = regime.run(name, seed=0, steps=steps, window=window, bptt=bptt)
assert mine["steady"] == theirs["steady"]
assert mine["recovery"] == theirs["recovery"]
assert mine["n_switches"] == theirs["n_switches"]
@pytest.mark.parametrize("name", ["rp_only", "grp_k0"])
def test_frozen_phase_leaves_every_parameter_bit_identical(name):
spec, wcfg, world, org = _build(name, seed=0, hidden=32, omega=10.0, kappa=4.0)
affect, memory, _ = _train(spec, wcfg, world, org, 200, 20, lr=1e-3)
before = nn.utils.parameters_to_vector(org.parameters()).clone()
fr = _frozen(spec, wcfg, world, org, affect, memory, 200)
after = nn.utils.parameters_to_vector(org.parameters())
assert fr["frozen_bit_identical"]
assert torch.equal(before, after)
assert not any(p.requires_grad for p in org.parameters())
def test_memory_keeps_updating_while_weights_are_frozen():
"""Freezing is about parameters, not state. A frozen M would silently turn the
GRP into an RP and make any null a null for the wrong reason."""
spec, wcfg, world, org = _build("grp_k0", seed=0, hidden=32, omega=10.0, kappa=4.0)
affect, memory, _ = _train(spec, wcfg, world, org, 200, 20, lr=1e-3)
fr = _frozen(spec, wcfg, world, org, affect, memory, 200)
assert fr["dM_min"] > 0.0
assert fr["dM_mean"] > 0.0
assert fr["M"].shape == (200, wcfg.n, org.hidden_dim)
def test_frozen_phase_detects_a_parameter_change():
"""The freeze assertion has to be able to fail, or it proves nothing."""
spec, wcfg, world, org = _build("grp_k0", seed=0, hidden=32, omega=10.0, kappa=4.0)
affect, memory, _ = _train(spec, wcfg, world, org, 100, 20, lr=1e-3)
orig = _frozen.__globals__["nn"].utils.parameters_to_vector
calls = {"n": 0}
def sneaky(params):
v = orig(params)
calls["n"] += 1
if calls["n"] == 1: # let a weight move right after the "before" snapshot
with torch.no_grad():
org.out.bias.add_(1e-6)
return v
frozen.nn.utils.parameters_to_vector = sneaky
try:
with pytest.raises(AssertionError):
_frozen(spec, wcfg, world, org, affect, memory, 20)
finally:
frozen.nn.utils.parameters_to_vector = orig
@pytest.mark.parametrize("name", ["rp_only", "grp_k0"])
def test_hidden_reconstruction_matches_the_organism(name):
"""`_hidden` must rebuild the same edge one-hot, mask and context `Organism.forward`
builds, or the RP probe would be run on a representation the organism never used."""
spec, wcfg, world, org = _build(name, seed=1, hidden=32, omega=10.0, kappa=4.0)
from ailed import Affect
from particles import wrapped_diff
obs = world.step()
affect = Affect()
with torch.no_grad():
r = wrapped_diff(obs.coords)
pred, mem = org(obs.attrs, r, obs.ids, affect.axes, {}, context=None)
h = _hidden(org, obs.attrs, r, affect.axes, None)
if org.use_memory:
zero = torch.zeros(org.hidden_dim)
prev = torch.stack([zero for _ in obs.ids])
M = torch.stack([mem[i] for i in obs.ids])
assert torch.equal(org.grp(h, prev, affect.arousal), M)
else:
assert torch.equal(org.out(h), pred)
def test_probe_recovers_a_planted_regime_signal_and_not_a_planted_absence():
"""Two ends of the probe: a representation that linearly carries the label must
decode well above the measured chance level, and pure noise must not."""
rng = np.random.default_rng(0)
T, N, R = 600, 8, 4
labels, switched, cur, left = [], [], 0, 0
for t in range(T):
if left == 0:
cur, left = int(rng.integers(R)), int(rng.integers(40, 80))
switched.append(True)
else:
switched.append(False)
labels.append(cur); left -= 1
labels = np.asarray(labels)
signal = np.eye(R)[labels][:, None, :].repeat(N, 1) + 0.1 * rng.normal(size=(T, N, R))
noise = rng.normal(size=(T, N, R))
good = probe(signal, labels, switched, R, n_null=5)
bad = probe(noise, labels, switched, R, n_null=5)
assert good["acc_entity"] > 0.9 > good["chance_shift_max"]
assert bad["acc_entity"] <= bad["chance_shift_max"] + 0.05
def test_probe_test_split_is_a_suffix_in_time():
"""A random split would let the probe memorise steps adjacent to the test steps."""
rng = np.random.default_rng(0)
T, N, R = 200, 4, 3
labels = np.repeat(np.arange(T // 50) % R, 50)
reps = rng.normal(size=(T, N, R))
out = probe(reps, labels, [False] * T, R, split=0.7, n_null=2)
assert out["n_test_steps"] == T - int(T * 0.7)
def test_run_one_reports_both_phases_and_the_freeze_check():
r = run_one("grp_k0", seed=0, train_steps=200, frozen_steps=200, window=20)
assert r["frozen_bit_identical"] is True
assert r["probe_on"] == "M" and set(r["probes"]) >= {"M_lsq", "h_lsq", "M_logit"}
assert len(r["frozen"]["recovery"]) == 20
assert r["trained"]["steady"] >= 0.0
assert run_one("rp_only", seed=0, train_steps=200, frozen_steps=200)["probe_on"] == "h"
def test_probe_accepts_per_entity_labels():
"""The coupling row differs between entities at the same step, so the probe has to
take a (T, N) target as well as the (T,) regime id."""
rng = np.random.default_rng(1)
T, N, R = 400, 6, 3
lab = rng.integers(0, R, size=(T, N))
reps = np.eye(R)[lab] + 0.1 * rng.normal(size=(T, N, R))
out = probe(reps, lab, [False] * T, R, n_null=3)
assert out["acc_entity"] > 0.9 > out["chance_shift_max"]
assert np.isnan(out["acc_step"]) and np.isnan(out["latency"])
def test_persistence_separates_a_slow_state_from_white_noise():
from frozen import persistence
rng = np.random.default_rng(2)
T, N, D = 2000, 4, 5
white = rng.normal(size=(T, N, D))
slow = np.zeros_like(white)
for t in range(1, T):
slow[t] = 0.95 * slow[t - 1] + white[t]
assert persistence(white)["lag1"] < 0.1 < persistence(slow)["lag1"]
assert persistence(slow)["tau"] > 10 >= persistence(white)["tau"]
def test_ablate_state_keeps_the_parameters_and_drops_only_the_state():
"""The capacity control: the GRP keeps all 5602 parameters but carries nothing
between steps, so M becomes a fixed function of h."""
full = run_one("grp_k0", seed=0, train_steps=200, frozen_steps=100, probes=False)
none = run_one("grp_k0", seed=0, train_steps=200, frozen_steps=100, probes=False, stateless=True)
assert none["condition"] == "grp_k0_nostate"
assert none["n_params"] == full["n_params"] > run_one(
"rp_only", seed=0, train_steps=200, frozen_steps=100, probes=False)["n_params"]
assert none["dM_min"] == 0.0 or none["frozen"]["steady"] != full["frozen"]["steady"]
assert none["frozen_bit_identical"]