exp: when does per-entity memory have a job -- the theory is wrong and the failure is ours

Part 1: the affect timing fix works (arousal's peak moves from lag 11 to lag 2, inside
the pre-registered 3) and the error does not move -- 0 of 16 seeds reach the registered
1.10, largest ratio anywhere 1.017. A1 is closed on this domain.

Part 2: T_id is 2-3 observations against a T_z of 40-80. One observed displacement
carries the regime at 0.958 (exact) and 0.909 (no privileged knowledge), against 0.574
from the instantaneous configuration alone. History nearly doubles the present's
above-chance information, so this is the rememberable kind of domain -- and the GRP's
memory decodes it at 0.332.

Part 3: the predicted peak does not exist. Capacity-controlled state gain is flat at
1.09-1.26 across four orders of magnitude of regime duration, and is largest at the
frozen regime, where there is no regime to identify and G is exactly 1.00. What the
state gain measures is temporal smoothing.

The pre-registered theory is falsified. The domain had the information all along and the
organism does not take it, which closes the project's habit of reaching for a new domain
whenever memory failed to help.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KAWnnPg2qvmLNySamE2k85
This commit is contained in:
chrnxandClaude Opus 5 committed 2026-09-02 12:29:38 -05:00
1 parent 39ffbc5272
commit a4f45c331a
6 files changed
+1513 -10

No files matched your search

+11 -5
View File
@@ -17,7 +17,7 @@ Row A is the self-check: given (regime, t_i, t_j) the family spans the dynamics
exactly, so its deterministic residual must be ~0 and its residual against the noisy exactly, so its deterministic residual must be ~0 and its residual against the noisy
target must equal noise**2. target must equal noise**2.
uv run python ceilings.py [steps] [seeds] uv run python ceilings.py [steps] [seeds] [t_min,t_max]
""" """
from __future__ import annotations from __future__ import annotations
@@ -84,12 +84,17 @@ CEILINGS = [
] ]
def ceilings(steps: int = 1200, seeds: tuple[int, ...] = (0, 1, 2)) -> dict[str, tuple[float, float]]: def ceilings(steps: int = 1200, seeds: tuple[int, ...] = (0, 1, 2),
t_min: int | None = None, t_max: int | None = None) -> dict[str, tuple[float, float]]:
"""`t_min`/`t_max` override the regime duration; Task 9 Part 3 reads the oracle prize
D->C at each duration it sweeps. They are passed to `ParticleConfig` rather than
changed in `particles.py`, so every existing caller gets the 40-80 default."""
dur = {k: v for k, v in (("t_min", t_min), ("t_max", t_max)) if v is not None}
out = {} out = {}
for label, key, off in CEILINGS: for label, key, off in CEILINGS:
dets, obss = [], [] dets, obss = [], []
for seed in seeds: for seed in seeds:
cfg = ParticleConfig(seed=seed) cfg = ParticleConfig(seed=seed, **dur)
X, Y, Yn = design(collect(cfg, steps), cfg, key, off) X, Y, Yn = design(collect(cfg, steps), cfg, key, off)
pred = (X @ torch.linalg.lstsq(X, Y.unsqueeze(1)).solution).squeeze(1) pred = (X @ torch.linalg.lstsq(X, Y.unsqueeze(1)).solution).squeeze(1)
dets.append(((pred - Y) ** 2).mean().item()) dets.append(((pred - Y) ** 2).mean().item())
@@ -101,8 +106,9 @@ def ceilings(steps: int = 1200, seeds: tuple[int, ...] = (0, 1, 2)) -> dict[str,
def main() -> None: def main() -> None:
steps = int(sys.argv[1]) if len(sys.argv) > 1 else 1200 steps = int(sys.argv[1]) if len(sys.argv) > 1 else 1200
seeds = tuple(int(s) for s in sys.argv[2].split(",")) if len(sys.argv) > 2 else (0, 1, 2) seeds = tuple(int(s) for s in sys.argv[2].split(",")) if len(sys.argv) > 2 else (0, 1, 2)
cfg = ParticleConfig() dur = tuple(int(x) for x in sys.argv[3].split(",")) if len(sys.argv) > 3 else (None, None)
res = ceilings(steps, seeds) cfg = ParticleConfig(**{k: v for k, v in zip(("t_min", "t_max"), dur) if v is not None})
res = ceilings(steps, seeds, *dur)
print(f"steps={steps} seeds={','.join(map(str, seeds))} noise^2 = {cfg.noise ** 2:.3e}\n") print(f"steps={steps} seeds={','.join(map(str, seeds))} noise^2 = {cfg.noise ** 2:.3e}\n")
print(f"{'information set':<40}{'MSE(det part)':>15}{'MSE(vs target)':>16}") print(f"{'information set':<40}{'MSE(det part)':>15}{'MSE(vs target)':>16}")
print("-" * 71) print("-" * 71)
+21 -5
View File
@@ -39,12 +39,24 @@ SPLIT = 0.7 # probe train fraction, taken as a prefix in time
# -- construction and the two phases --------------------------------------------- # -- construction and the two phases ---------------------------------------------
def _build(name: str, seed: int, hidden: int, omega: float, kappa: float): 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.""" t_min: int | None = None, t_max: int | None = None):
"""Construct exactly as `regime.run` does, in the same order, so the RNG stream matches.
`t_min`/`t_max` override the regime duration for Task 9 Part 3. They are passed to
`ParticleConfig` here rather than changed in `particles.py`, so every other caller
keeps the 40-80 default and `test_train_copy_is_identical_to_regime_run` still pins
this loop against `regime.run`.
"""
spec = dict(CONDITIONS[name]) spec = dict(CONDITIONS[name])
if spec["kappa"] == KAPPA_FLAG: if spec["kappa"] == KAPPA_FLAG:
spec["kappa"] = kappa spec["kappa"] = kappa
wcfg = ParticleConfig(seed=seed, oracle=spec["oracle"]) dur = {}
if t_min is not None:
dur["t_min"] = t_min
if t_max is not None:
dur["t_max"] = t_max
wcfg = ParticleConfig(seed=seed, oracle=spec["oracle"], **dur)
torch.manual_seed(seed) torch.manual_seed(seed)
world = ParticleWorld(wcfg) world = ParticleWorld(wcfg)
ctx_dim = wcfg.n_regimes if spec["ctx"] == "regime" else 2 ctx_dim = wcfg.n_regimes if spec["ctx"] == "regime" else 2
@@ -55,7 +67,7 @@ def _build(name: str, seed: int, hidden: int, omega: float, kappa: float):
def _train(spec: dict, wcfg: ParticleConfig, world: ParticleWorld, org: Organism, def _train(spec: dict, wcfg: ParticleConfig, world: ParticleWorld, org: Organism,
steps: int, bptt: int, lr: float, stateless: bool = False, steps: int, bptt: int, lr: float, stateless: bool = False,
gate_arousal=None, on_step=None): gate_arousal=None, on_step=None, acfg: AffectConfig | None = None):
"""A verbatim copy of `regime.run`'s training loop (the keyword arguments aside). """A verbatim copy of `regime.run`'s training loop (the keyword arguments aside).
Copied rather than reused because `regime.run` returns metrics and drops the Copied rather than reused because `regime.run` returns metrics and drops the
@@ -79,9 +91,13 @@ def _train(spec: dict, wcfg: ParticleConfig, world: ParticleWorld, org: Organism
`on_step(t, obs, r, ctx, axes, prev, memory)` is a read-only callback fired after `on_step(t, obs, r, ctx, axes, prev, memory)` is a read-only callback fired after
the forward pass, for measuring the gate. `prev` is the M_prev the organism was the forward pass, for measuring the gate. `prev` is the M_prev the organism was
handed, captured before `memory` is rebound. handed, captured before `memory` is rebound.
`acfg` overrides the affect time constants for Task 9 Part 1. It defaults to
`AffectConfig()`, the value this loop always used, so the copy stays verbatim for
every existing caller. `AffectConfig`'s own defaults are not touched.
""" """
opt = torch.optim.Adam(org.parameters(), lr=lr) opt = torch.optim.Adam(org.parameters(), lr=lr)
acfg = AffectConfig() acfg = AffectConfig() if acfg is None else acfg
affect = Affect() affect = Affect()
memory: dict[int, Tensor] = {} memory: dict[int, Tensor] = {}
+437
View File
@@ -0,0 +1,437 @@
"""Task 9 Part 2: how many steps of history does it take to identify the regime?
`T_id` is a property of the *domain*, not of our architecture, so nothing in this
file constructs an Organism. It rolls the world out and asks: given the last `L`
observations an observer actually has at step `t`, how well can the regime in force
at `t` be decoded?
What the observer has at step t, and nothing more:
* the coordinates c_{t-L+1} .. c_t (the current one included -- it is observed)
* therefore the displacements d_s = wrap(c_{s+1} - c_s) for s = t-L+1 .. t-1
`d_t` is *not* available: that is the quantity the organism is asked to predict, and
handing it to the decoder would be handing over the answer. So `L = 1` is the
instantaneous configuration alone -- the read-off `results/frozen.md` §2 measured at
+0.05 over chance -- and each extra step of window buys exactly one more observed
displacement.
## The feature sets, and why the physics one is a fair stand-in for optimal
The world's dynamics are
d_i(s) = sum_c K[t_i, c] * B_i^c(s) + eps, B_i^c(s) = dt * sum_{j: t_j = c} kern(r_ij) r_ij
with `kern` the fixed radial kernel and `eps ~ N(0, noise^2)`. `B` is the *message
basis*: everything about the configuration that the coupling matrix multiplies. It is
computable from the coordinates alone, so it is observer-side information, and it is
the same decomposition `ceilings.py` fits against. `_check_basis` asserts the
reconstruction is exact.
Given that model, the log-likelihood of regime `g` from the window's displacements is
-1/(2 noise^2) * sum_s sum_i || d_i(s) - sum_c K_g[t_i,c] B_i^c(s) ||^2
= const + (1/noise^2) * sum_c K_g[t_i,c] <d, B^c> - (1/2noise^2) * sum_{c,c'} K_g[t_i,c] K_g[t_i,c'] <B^c, B^c'>
which is **affine in the statistics `<d, B^c>` and `<B^c, B^c'>`, with coefficients
that depend on `g` and on the entity's own type**. So a linear classifier on those
statistics, interacted with the type one-hot, can express the exact Bayes rule. That
is what `phys` is, and it is why it is a fair stand-in for "optimal" rather than a
weak probe that would understate the difficulty. `bayes` computes the same rule in
closed form, with the true coupling matrices handed to it, as a cross-check on the
fit: `phys` should track it and must not beat it by much.
`lin` and `mlp` are the honest non-omniscient decoders -- least squares and a
two-layer MLP on the raw window (the per-frame features at every step of the window,
the observed displacements, the type one-hot). They know no coupling matrices. If they
saturate where `bayes` does, the saturation is the domain's and not a decoder's
limitation.
## The headline: how much does history add over the present?
The number that decides whether memory can pay is not where accuracy saturates. It is
`accuracy(L) - accuracy(1)`. `L = 1` is the present-only baseline: the current frame,
no displacement, no history. Three cases a hidden variable can fall into --
1. no evidence anywhere: nothing helps, memory included
2. evidence already in the present: history is *redundant* and feedforward suffices,
however identifiable the variable is
3. evidence only in the past: memory is required (card counting is the pure case)
-- and only case 3 gives per-entity state a job. `T_id` is a secondary quantity that
matters only once `accuracy(L) - accuracy(1)` is materially above zero.
This makes the *strength of the L = 1 decoder* the load-bearing choice, because an
underpowered present-only baseline inflates the history gain. So the per-frame feature
block (`_frame`) carries every rotation-invariant scalar the message basis misses --
the kernel mass and the kernel-weighted spread per neighbour type, alongside `B`
itself -- and `L = 1` and `L = 40` are given the *same* per-frame features and the
same decoder, differing only in how many frames. A better present-only decoder could
only shrink the reported gain, never grow it.
Chance is measured the way `frozen.py` measures it: two nulls, both refitting from
scratch -- a label shuffle, and a circular shift that preserves each regime's block
structure and is therefore the stricter of the two.
uv run python identify.py --out results/identify.json
"""
from __future__ import annotations
import argparse
import json
import statistics
from pathlib import Path
import numpy as np
import torch
from torch import nn
from particles import ParticleConfig, ParticleWorld, wrapped_diff
LS = (1, 2, 3, 5, 10, 20, 40)
SEEDS = (0, 1, 2, 3, 4, 5, 6, 7)
STEPS = 4000
SPLIT = 0.7
# -- the world, rolled out -------------------------------------------------------
def rollout(cfg: ParticleConfig, steps: int) -> dict:
"""Coordinates, observed displacements, the message basis, and the true regime.
`coords[t]` is what an observer sees at step t; `disp[t] = wrap(coords[t+1] -
coords[t])` is what it sees *after* step t resolves, so at step t the observer has
`disp[:t]` and not `disp[t]`. `regime[t]` is the regime that generated `disp[t]`.
"""
w = ParticleWorld(cfg)
coords, disp, regimes = [], [], []
for _ in range(steps):
obs = w.step()
coords.append(obs.coords)
regimes.append(obs.regime)
disp.append(wrapped_diff(torch.stack([obs.coords, w.coords]))[0, 1]) # wrap(c_{t+1} - c_t)
C = torch.stack(coords) # (T, N, 2)
D = torch.stack(disp) # (T, N, 2)
B = torch.stack([_basis(c, w.types, cfg) for c in C]) # (T, N, n_types, 2)
F = torch.stack([_frame(c, w.types, cfg) for c in C]) # (T, N, 4 * n_types)
K = torch.stack(w.regimes) # (n_regimes, n_types, n_types)
return dict(coords=C, disp=D, basis=B, frame=F, regimes=np.asarray(regimes),
types=w.types, K=K, cfg=cfg)
def _basis(coords: torch.Tensor, types: torch.Tensor, cfg: ParticleConfig) -> torch.Tensor:
"""B[i, c] = dt * sum_{j : t_j = c} kern(r_ij) r_ij, the message the coupling multiplies."""
r = wrapped_diff(coords)
kern = torch.exp(-(r ** 2).sum(-1) / cfg.sigma ** 2)
kern.fill_diagonal_(0.0)
wr = cfg.dt * kern[:, :, None] * r # (N,N,2)
onehot = nn.functional.one_hot(types, cfg.n_types).to(wr.dtype) # (N, n_types)
return torch.einsum("ijd,jc->icd", wr, onehot) # (N, n_types, 2)
def _frame(coords: torch.Tensor, types: torch.Tensor, cfg: ParticleConfig) -> torch.Tensor:
"""Everything one frame says about the configuration, per entity and neighbour type.
The message basis `B` is a first moment and is therefore blind to arrangement that
cancels by symmetry -- a ring of same-type neighbours contributes almost nothing to
`B` however tight it is. Since `L = 1` is the present-only baseline the whole
history gain is measured against, it must not be handicapped by that blindness, so
the frame also carries the two rotation-invariant scalars per neighbour type: the
kernel mass (how much of type c is nearby) and the kernel-weighted spread (how far
out it sits). `L = 1` and `L = 40` see the same per-frame features.
"""
r = wrapped_diff(coords)
d2 = (r ** 2).sum(-1)
kern = torch.exp(-d2 / cfg.sigma ** 2)
kern.fill_diagonal_(0.0)
onehot = nn.functional.one_hot(types, cfg.n_types).to(r.dtype) # (N, n_types)
B = torch.einsum("ijd,jc->icd", cfg.dt * kern[:, :, None] * r, onehot) # (N, n_types, 2)
mass = kern @ onehot # (N, n_types)
spread = (kern * d2) @ onehot # (N, n_types)
return torch.cat([B.reshape(len(r), -1), mass, spread], dim=-1)
def det(world: dict, regimes: np.ndarray) -> torch.Tensor:
"""The deterministic displacement each step would have had under `regimes[t]`."""
krow = world["K"][torch.as_tensor(regimes)][:, world["types"], :] # (T, N, n_types)
return torch.einsum("tic,ticd->tid", krow, world["basis"])
def _check_basis(world: dict) -> float:
"""Self-check: the basis must reproduce the world's own dynamics up to the noise.
The analogue of `ceilings.py`'s row A. If this residual is not the noise variance
then `B` is not the world's message basis and every number below is meaningless.
"""
resid = float(((det(world, world["regimes"]) - world["disp"]) ** 2).mean())
floor = world["cfg"].noise ** 2
assert abs(resid - floor) < 0.03 * floor, f"basis residual {resid:.3e} != noise^2 {floor:.3e}"
return resid
# -- features --------------------------------------------------------------------
def features(world: dict, L: int, kind: str) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
"""(X, y, t_index) for every step at which a full window of L observations exists.
Rows are per entity: X has shape (T', N, F). `y` is the regime at the step being
decoded. The window at step t covers observations t-L+1 .. t, i.e. displacements
t-L+1 .. t-1 -- never `d_t`.
"""
B, D = world["basis"].numpy(), world["disp"].numpy()
Fr = world["frame"].numpy()
T, N, C, _ = B.shape
ts = np.arange(L - 1, T)
onehot = nn.functional.one_hot(world["types"], C).numpy().astype(np.float64) # (N, C)
if kind == "raw":
cols = []
for k in range(L): # the per-frame features at each step
cols.append(Fr[ts - (L - 1) + k])
for k in range(L - 1): # the displacements the observer has seen
cols.append(D[ts - (L - 1) + k])
cols.append(np.broadcast_to(onehot, (len(ts), N, C)))
X = np.concatenate(cols, axis=-1)
elif kind == "phys":
# the sufficient statistics of the Gaussian likelihood, summed over the window,
# interacted with the entity's own type so the per-type coupling row is separable
db = np.zeros((len(ts), N, C))
bb = np.zeros((len(ts), N, C * (C + 1) // 2))
for k in range(L - 1):
s = ts - (L - 1) + k
db += np.einsum("tid,ticd->tic", D[s], B[s])
pairs = [(a, b) for a in range(C) for b in range(a, C)]
bb += np.stack([np.einsum("tid,tid->ti", B[s][:, :, a], B[s][:, :, b])
for a, b in pairs], axis=-1)
stats = np.concatenate([db, bb], axis=-1) # (T', N, C + C(C+1)/2)
X = (stats[:, :, None, :] * onehot[None, :, :, None]).reshape(len(ts), N, -1)
else:
raise ValueError(kind)
return X.astype(np.float64), world["regimes"][ts], ts
# -- decoders --------------------------------------------------------------------
def _standardise(X: np.ndarray, cut: int) -> np.ndarray:
flat = X[:cut].reshape(-1, X.shape[-1])
mu, sd = flat.mean(0), flat.std(0) + 1e-12
return np.concatenate([(X - mu) / sd, np.ones(X.shape[:2] + (1,))], axis=-1)
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-6) -> np.ndarray:
"""Multinomial logistic, LBFGS with strong Wolfe -- as `frozen.py` fits its probe.
Least squares onto a one-hot target is a poor classifier on the physics statistics,
which are products of small numbers and heavy-tailed; it understates what the
feature set can express. The `phys` set is meant to be a fair stand-in for optimal,
so it gets the estimator that actually maximises the classification objective.
X already carries the bias column, so no separate intercept.
"""
Xt, yt = torch.tensor(X), 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-12,
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()
def _fit_mlp(X: np.ndarray, y: np.ndarray, R: int, hidden: int = 128, epochs: int = 40,
seed: int = 0) -> callable:
"""Two-layer MLP -- the capacity check the brief asks for before concluding.
A linear probe that never rises is not evidence the regime is unidentifiable, so
the raw feature set is also given a nonlinear decoder. Full-batch Adam; the split
is a time suffix, so there is no shuffling to seed beyond the initialisation.
"""
torch.manual_seed(seed)
net = nn.Sequential(nn.Linear(X.shape[1], hidden), nn.ReLU(),
nn.Linear(hidden, hidden), nn.ReLU(), nn.Linear(hidden, R)).double()
Xt, yt = torch.tensor(X), torch.tensor(y, dtype=torch.long)
opt = torch.optim.Adam(net.parameters(), lr=3e-3, weight_decay=1e-5)
n, bs = len(Xt), 4096
g = torch.Generator().manual_seed(seed)
for _ in range(epochs):
perm = torch.randperm(n, generator=g)
for i in range(0, n, bs):
idx = perm[i:i + bs]
opt.zero_grad()
nn.functional.cross_entropy(net(Xt[idx]), yt[idx]).backward()
opt.step()
net.eval()
return lambda Z: net(torch.tensor(Z)).detach().numpy()
def decode(X: np.ndarray, y: np.ndarray, n_regimes: int, estimator: str,
split: float = SPLIT, n_null: int = 10, seed: int = 0) -> dict:
"""Fit on a time prefix, score on the suffix, with chance measured by two nulls.
Reported twice: `entity` is one classification per entity per step, `step` pools
the N entities of a step by averaging their scores -- what an observer watching
the whole world would do. The regime is a global variable, so `step` is the
domain-level number and `entity` is the one a per-entity memory could hold.
"""
T = X.shape[0]
cut = int(T * split)
Z = _standardise(X, cut)
F = Z.shape[-1]
flat = lambda A: A.reshape(-1, F)
def fit_eval(lab: np.ndarray) -> tuple[float, float]:
ytr = np.repeat(lab[:cut, None], X.shape[1], 1).reshape(-1)
if estimator in ("lsq", "logit"):
fit = _fit_lsq if estimator == "lsq" else _fit_logit
W = fit(flat(Z[:cut]), ytr, n_regimes)
s = (flat(Z[cut:]) @ W).reshape(T - cut, X.shape[1], n_regimes)
elif estimator == "mlp":
f = _fit_mlp(flat(Z[:cut]), ytr, n_regimes, seed=seed)
s = f(flat(Z[cut:])).reshape(T - cut, X.shape[1], n_regimes)
else:
raise ValueError(estimator)
ent = float((s.argmax(-1) == lab[cut:, None]).mean())
step = float((s.mean(1).argmax(-1) == lab[cut:]).mean())
return ent, step
ent, step = fit_eval(y)
rng = np.random.default_rng(seed)
shuf, shift = [], []
for _ in range(n_null):
shuf.append(fit_eval(rng.permutation(y)))
k = int(rng.integers(T // 10, T - T // 10))
shift.append(fit_eval(np.roll(y, k)))
return dict(estimator=estimator, acc_entity=ent, acc_step=step,
chance_entity=float(np.mean([a for a, _ in shuf])),
chance_step=float(np.mean([b for _, b in shuf])),
shift_entity=float(np.mean([a for a, _ in shift])),
shift_step=float(np.mean([b for _, b in shift])),
n_test=T - cut, n_features=F)
def bayes(world: dict, L: int, split: float = SPLIT) -> dict:
"""Exact Gaussian likelihood over the window, with the true coupling matrices given.
No fitting, so no train split is needed; it is scored on the same test suffix the
fitted decoders use so the numbers sit in one column. This is the floor on `T_id`:
a decoder that knows the generative model exactly, including the four candidate
matrices, and assumes the regime is constant across the window.
"""
B, D = world["basis"], world["disp"]
T, N = B.shape[0], B.shape[1]
ts = np.arange(L - 1, T)
K = world["K"][:, world["types"], :] # (R, N, n_types)
resid = np.zeros((len(ts), N, K.shape[0]))
for k in range(L - 1):
s = torch.as_tensor(ts - (L - 1) + k)
pred = torch.einsum("ric,ticd->rtid", K, B[s]) # (R, T', N, 2)
resid += ((pred - D[s][None]) ** 2).sum(-1).permute(1, 2, 0).numpy()
y = world["regimes"][ts]
cut = int(len(ts) * split)
sc = -resid[cut:]
return dict(estimator="bayes", acc_entity=float((sc.argmax(-1) == y[cut:, None]).mean()),
acc_step=float((sc.sum(1).argmax(-1) == y[cut:]).mean()),
n_test=len(ts) - cut)
def switch_fraction(world: dict, L: int) -> float:
"""Fraction of decoded steps whose window spans a regime change.
A window longer than the regime lasts contains two regimes, and a decoder that
assumes one is then mis-specified. This is the mechanism behind `T_z < T_id`, so
it is reported alongside every accuracy.
"""
g = world["regimes"]
ts = np.arange(L - 1, len(g))
return float(np.mean([g[t - L + 1:t + 1].min() != g[t - L + 1:t + 1].max() for t in ts]))
# -- driver ----------------------------------------------------------------------
def run(seed: int, steps: int, Ls: tuple[int, ...], t_min: int, t_max: int,
estimators: tuple[str, ...]) -> list[dict]:
cfg = ParticleConfig(seed=seed, t_min=t_min, t_max=t_max)
world = rollout(cfg, steps)
resid = _check_basis(world)
out = []
for L in Ls:
row = dict(seed=seed, L=L, t_min=t_min, t_max=t_max, steps=steps,
basis_residual=resid, switch_frac=switch_fraction(world, L), decoders={})
for kind, est in (("raw", "lsq"), ("raw", "mlp"), ("phys", "logit")):
tag = {"raw/lsq": "lin", "raw/mlp": "mlp", "phys/logit": "phys"}[f"{kind}/{est}"]
if tag not in estimators:
continue
if kind == "phys" and L == 1:
continue # no displacement observed yet: the likelihood has no terms
X, y, _ = features(world, L, kind)
# the MLP is refit from scratch for every null, so its chance level is
# measured on fewer draws than the linear decoders' ten
row["decoders"][tag] = decode(X, y, cfg.n_regimes, est, seed=seed,
n_null=2 if est == "mlp" else 10)
if "bayes" in estimators and L > 1:
row["decoders"]["bayes"] = bayes(world, L)
out.append(row)
return out
def table(results: list[dict], which: str = "step") -> str:
by: dict[int, list[dict]] = {}
for r in results:
by.setdefault(r["L"], []).append(r)
tags = ["lin", "mlp", "phys", "bayes"]
head = "".join(f"{t:>18}" for t in tags)
lines = [f"per-{which} accuracy (chance in brackets), means over seeds",
f"{'L':>3}{'sw.frac':>9}{head}", "-" * (12 + 18 * len(tags))]
for L in sorted(by):
rs = by[L]
cells = ""
for t in tags:
got = [r["decoders"][t] for r in rs if t in r["decoders"]]
if not got:
cells += f"{'--':>18}"
continue
acc = statistics.fmean(g[f"acc_{which}"] for g in got)
ch = [g[f"shift_{which}"] for g in got if f"shift_{which}" in g]
cells += f"{acc:>12.3f}{('[' + format(statistics.fmean(ch), '.3f') + ']') if ch else '':>6}"
lines.append(f"{L:>3}{statistics.fmean(r['switch_frac'] for r in rs):>9.3f}{cells}")
return "\n".join(lines)
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--seeds", default=",".join(map(str, SEEDS)))
ap.add_argument("--steps", type=int, default=STEPS)
ap.add_argument("--Ls", default=",".join(map(str, LS)))
ap.add_argument("--t-min", type=int, default=ParticleConfig().t_min)
ap.add_argument("--t-max", type=int, default=ParticleConfig().t_max)
ap.add_argument("--estimators", default="lin,mlp,phys,bayes")
ap.add_argument("--out", default="results/identify.json")
a = ap.parse_args()
ests = tuple(a.estimators.split(","))
Ls = tuple(int(x) for x in a.Ls.split(","))
results = []
for seed in (int(s) for s in a.seeds.split(",")):
rs = run(seed, a.steps, Ls, a.t_min, a.t_max, ests)
for r in rs:
d = r["decoders"]
msg = " ".join(f"{k}={v['acc_step']:.3f}/{v['acc_entity']:.3f}" for k, v in d.items())
print(f"seed={seed} L={r['L']:<3} sw={r['switch_frac']:.3f} {msg}", flush=True)
results.extend(rs)
Path(a.out).parent.mkdir(parents=True, exist_ok=True)
Path(a.out).write_text(json.dumps(results, indent=1))
print(); print(table(results, "step")); print(); print(table(results, "entity"))
if __name__ == "__main__":
main()
+498
View File
@@ -0,0 +1,498 @@
# When does per-entity memory have a job?
Task 9. The project had been reaching for a new domain each time memory failed to
help. This file replaces that reflex with a quantity measurable on any candidate
domain in advance — `T_id`, the history an optimal observer needs to identify the
regime — and with a prediction that can be wrong.
**Verdict, in the order the parts were pre-registered:**
1. **Part 1 — FAILURE, of the informative kind.** Arousal's peak moves from 11 steps
after a switch to **2** (lags 1 and 2 are within 0.005 of each other, 0.303 and
0.308), which is inside the pre-registered 3. The error is
unmoved: `grp_k0 / grp_k` on `steady` is 0.987 (median 1.000) and **0 of 16 seeds
reach 1.10**, against a criterion of 12 of 16. The largest ratio on any seed at any
κ is 1.017. The mechanism works, it is now correctly timed, and the domain gives it
nothing. The lag-2 harm `a1.md` §2a found survives the fix unchanged.
2. **Part 2 — `T_id = 2` observations, i.e. one step of history.** An exact decoder
reaches 0.958 per-step accuracy from a single observed displacement, against a
measured chance of 0.23, and a fitted decoder that knows no coupling matrices
reaches 0.909. Accuracy peaks at `L = 2–3` and *falls* thereafter. With
`T_z = 40–80`, **`T_id` is 20–40 times smaller than `T_z`**. That is the
uncomfortable branch: the domain can reward memory and the failure is ours.
3. **Part 3 — the predicted peak does not exist. The theory is wrong as stated.** The
capacity-controlled state gain is flat across four orders of magnitude of regime
duration, 1.09 to 1.26, on 8–11 seeds of 16 at every duration, with a per-seed
spread (0.32 to 2.86) that swamps every between-duration difference. And the
decisive point: **the largest gain in the sweep is at the frozen regime**, 1.26 on
11/16 — the one setting where there is no regime to identify at all and where `G`
measures exactly 1.00. A quantity that is largest when its supposed cause is absent
is not caused by it.
The condition "memory has a job when `T_id << T_z` and `G` is materially above 1" is
satisfied at every switching duration in this sweep and does not predict the state
gain. What the state gain measures here is temporal smoothing, which a stationary
world rewards at least as well as a switching one.
Environment: `experiments/`, `ailed/` unmodified. No default in `particles.py`,
`regime.py` or `affect.py` changed — `AffectConfig`'s time constants and
`ParticleConfig`'s `t_min`/`t_max` are passed as arguments (`when_memory_works._cfg`,
`frozen._build`). 8000 training steps, `lr=1e-3`, `bptt=20`, `hidden=32`, `omega=10`.
Noise floor `noise² = 4.0e-06`. 400 organism runs. Part 2 fits 4 decoders at each of
7 window lengths on 8 seeds, each linear decoder refit 20 times more to measure its
own chance level.
```
uv run python identify.py --out results/identify.json
uv run python identify.py --t-min 10 --t-max 20 --seeds 0,1,2,3 --steps 4000 \
--estimators phys,bayes --out results/identify_d10_20.json # and each duration
uv run python ceilings.py 1200 0,1,2 10,20 # and each duration
uv run python when_memory_works.py --part timing --out results/w_timing.json
uv run python when_memory_works.py --part rho-fast --rho-a 1.0 --rho-slow 0.2 \
--out results/w_rhofast.json
uv run python when_memory_works.py --part best --rho-a 1.0 --rho-slow 0.2 \
--out results/w_best.json
uv run python when_memory_works.py --part duration --out results/w_duration_all.json
```
## 0. What is checked, and how it was made able to fail
Four properties carry the headline numbers. Each has a test, and each test was broken
on purpose to confirm it fails — AGENTS.md's rule, applied rather than asserted.
| property | test | broken on purpose by | fails? |
|---|---|---|---|
| the decoder never sees `d_t`, the step it decodes | `test_features_never_use_the_displacement_being_decoded` | widening the window to include `d_t` | **yes** |
| the state ablation differs only in carried state | `test_state_ablation_changes_only_whether_memory_is_carried` | making `stateless` a no-op in `run_one` | **yes** |
| the arousal profile is the arousal the gate saw | `test_gate_arousal_seq_is_the_arousal_the_organism_was_handed` | companion `..._can_fail` asserts the un-lagged sequence does *not* match | **yes** |
| the message basis is the world's own | `test_basis_reproduces_the_worlds_dynamics_to_the_noise_floor` | companion `test_basis_check_can_fail` feeds it the wrong regime sequence | **yes** |
Alongside those: `test_bayes_decoder_recovers_a_regime_it_can_see_and_not_one_it_cannot`
is the planted-signal/planted-absence pair (real displacements → >0.8, displacements
replaced by noise → <0.45); `test_peak_lag_and_by_lag_average_over_the_switches_metrics_uses`
asserts `by_lag` cuts the trace exactly as `regime._metrics` cuts `recovery`, so the
arousal profile and the error profile are averaged over the same switches;
`test_windows_that_reach_the_next_switch_are_not_reported` enforces `window < t_min`
per duration, which is `regime.run`'s own validation carried into a sweep that
shortens the regime. 64 tests pass, including the 47 that were already there.
The two additive hooks this task needed — `frozen._build(t_min=, t_max=)` and
`frozen._train(acfg=)` — both default to the values the loop always used, so
`test_train_copy_is_identical_to_regime_run` still pins `_train` against `regime.run`.
## 1. Part 1 — affect timing, the last legitimate shot at A1
`rho_a` and `rho_slow` are the affect mechanism's own time constants and had never
been set. Only they can move arousal's timing. From `affect.update`:
```
fast <- fast + rho_fast (loss - fast) slow <- slow + rho_slow (loss - slow)
a_target = tanh(max(0, loss - slow) / (slow + eps))
arousal <- arousal + rho_a (a_target - arousal)
```
`fast` appears only in `v_target`. **`rho_fast` cannot reach arousal except through the
loss stream**, via valence feeding the CPPN, and §1c measures that it does not. So the
sweep is over `rho_a × rho_slow`. Where it raises `rho_slow` past the default
`rho_fast = 0.2` it raises `rho_fast` with it, because `AffectConfig` documents
`rho_slow < rho_fast` and inverting the two would change what valence means as a side
effect of a timing sweep.
### 1a. The sweep: the timing is a design parameter, and it moves
`grp_k0` (κ=0, so this is the arousal the gate *would* be forced with), 8000 steps,
seeds 0–3, means over seeds. Lag `k` after a switch, averaged over the second half's
switches — the same cut `regime._metrics` uses for `recovery`. `far` is `_metrics`'s
own `steady_idx`.
```
rho_a/rho_slow/rho_fast @0 @2 @4 @6 @8 @10 @12 @14 @16 @18 far peak
------------------------------------------------------------------------------------------------------------
a0.5/s0.02/f0.2 (default) 0.055 0.157 0.217 0.257 0.300 0.325 0.329 0.316 0.284 0.243 0.098 11
a0.5/s0.05/f0.2 0.056 0.197 0.256 0.290 0.320 0.323 0.307 0.283 0.236 0.193 0.081 10
a0.5/s0.1/f0.2 0.056 0.227 0.270 0.287 0.291 0.268 0.244 0.216 0.170 0.136 0.065 8
a0.5/s0.2/f0.4 0.054 0.219 0.228 0.221 0.198 0.170 0.149 0.121 0.088 0.077 0.053 4
a0.5/s0.4/f0.8 0.042 0.143 0.118 0.100 0.088 0.081 0.072 0.059 0.043 0.042 0.039 2
a1/s0.02/f0.2 0.046 0.205 0.259 0.284 0.327 0.348 0.342 0.316 0.277 0.232 0.092 10
a1/s0.05/f0.2 0.054 0.254 0.296 0.313 0.336 0.331 0.301 0.266 0.210 0.169 0.078 8
a1/s0.1/f0.2 0.060 0.294 0.301 0.289 0.288 0.253 0.231 0.193 0.147 0.121 0.065 1
a1/s0.2/f0.4 0.063 0.275 0.230 0.202 0.182 0.156 0.138 0.104 0.078 0.078 0.055 1
a1/s0.4/f0.8 0.046 0.174 0.105 0.086 0.083 0.080 0.066 0.052 0.038 0.041 0.040 1
```
The default row reproduces `a1.md` §1a: arousal *lowest* at the switch step and
peaking around lag 11–12. The odd lags are where the fix shows, so at one-step
resolution:
```
setting @0 @1 @2 @3 @4 @5 @6 @7 far peak/far
---------------------------------------------------------------------------------------------
a0.5/s0.02/f0.2 0.055 0.122 0.157 0.188 0.217 0.240 0.257 0.278 0.098 3.38
a1/s0.02/f0.2 0.046 0.188 0.205 0.234 0.259 0.275 0.284 0.307 0.092 3.77
a0.5/s0.2/f0.4 0.054 0.184 0.219 0.227 0.228 0.225 0.221 0.210 0.053 4.30
a1/s0.1/f0.2 0.060 0.312 0.294 0.304 0.301 0.292 0.289 0.298 0.065 4.81
a1/s0.2/f0.4 0.063 0.315 0.275 0.256 0.230 0.208 0.202 0.191 0.055 5.75
a1/s0.4/f0.8 0.046 0.243 0.174 0.131 0.105 0.088 0.086 0.084 0.040 6.06
```
**`rho_slow` is the whole story and `rho_a` sharpens it.** A slow baseline that tracks
the loss over ~50 steps cannot register a rise until the rise is most of the way done;
raising `rho_slow` to 0.1–0.4 turns `max(0, loss − slow)/slow` from a level detector
into a short-horizon relative-excess detector, and the surprise lands on the step after
the switch. `rho_a = 1` removes the remaining EMA smoothing on arousal itself.
The chosen setting was fixed on timing grounds alone, before any `grp_k` run: **among
settings whose peak lies within 3 steps of the switch, take the largest peak
amplitude.** That is `a1/s0.2/f0.4` — peak 0.315 at lag 1, a 5.0x jump from lag 0 in a
single step, and the best peak-to-far contrast of the three (5.75x). `a1/s0.1/f0.2` is
the runner-up and is reported alongside.
Worth stating because it bounds what timing can ever buy here: **the loss itself peaks
at lag 6–7** in every one of these runs (`recovery[k]` runs 2.74e-05, 2.83e-05,
3.12e-05, 3.40e-05, 3.84e-05, 4.37e-05, 4.70e-05, 4.71e-05 over lags 0–7). Arousal now
peaks five to six steps *before* the error it is built from does, because the loss at
lag 0 is already 1.3x its steady level and a short baseline sees that immediately.
There is no timing left to win.
### 1b. The result: timing fixed, error unmoved
`grp_k` against `grp_k0`, both at the best-timed affect config, 16 seeds, paired per
seed. Identical architecture, identical 5602 parameters, differing only in κ.
```
affect setting kappa mean median >1.10 >1.00 max
---------------------------------------------------------------------
a1/s0.2/f0.4 (best) 1 0.991 1.001 0/16 9/16 1.009
a1/s0.2/f0.4 4 0.987 1.000 0/16 8/16 1.017
a1/s0.2/f0.4 16 0.985 0.995 0/16 6/16 1.016
a1/s0.1/f0.2 (2nd) 1 1.011 1.000 1/16 7/16 1.107
a1/s0.1/f0.2 4 0.997 0.997 0/16 7/16 1.068
a1/s0.1/f0.2 16 0.987 0.995 0/16 6/16 1.025
```
Per-seed `grp_k0 / grp_k` at the best-timed setting, κ=4:
```
0.99 1.01 1.00 1.01 0.99 0.99 1.00 0.97 1.02 1.01 1.00 1.00 0.99 0.99 1.01 0.80
```
A coin flip with one seed (15) where the forced gate costs 20%. This is the same
picture `a1.md` §2 measured with the mis-timed signal, at the same magnitudes. Fixing
the timing changed the arousal profile completely and changed the error by nothing.
### 1c. The lag-2 harm survives the fix
`a1.md` §2a's one sign-definite effect was a 4–11% *degradation* two steps after a
switch, monotone in κ. Re-measured with arousal now peaking at lag 1 rather than 12:
```
paired grp_k0 / grp_k at matched lag, best-timed affect (<1 means kappa is worse)
kappa @0 @2 @5 @10 @19
------------------------------------------------------------------------------
1 0.98 4/16 0.96 1/16 0.99 8/16 1.00 8/16 0.99 6/16
4 0.99 6/16 0.90 0/16 0.99 6/16 0.99 6/16 0.98 5/16
16 0.99 5/16 0.91 1/16 1.00 4/16 1.00 7/16 1.00 8/16
```
At κ=4 the lag-2 penalty is 0.90 on **0 of 16 seeds** — against `a1.md`'s 0.92 on
1/16 with the mis-timed signal. Correcting the timing did not remove the harm; it made
it very slightly worse, which is what §1a's mechanism predicts. Opening the gate
earlier discards the temporal averaging earlier, and `frozen.md` §1b established that
the post-switch excess belongs to the world's configuration transient, which no gating
policy can shorten.
### 1d. The `rho_fast` control
Fixing `rho_a = 1.0`, `rho_slow = 0.2` and varying only `rho_fast`, 4 seeds:
```
rho_a/rho_slow/rho_fast @0 @2 @4 @6 @8 @10 far peak
---------------------------------------------------------------------------------
a1/s0.2/f0.4 0.063 0.275 0.230 0.202 0.182 0.156 0.055 1
a1/s0.2/f0.5 0.061 0.277 0.232 0.202 0.181 0.154 0.055 1
a1/s0.2/f0.9 0.063 0.279 0.233 0.196 0.180 0.155 0.055 1
```
Identical to within 0.005 at every lag, as the algebra requires. `rho_fast` is not a
lever on arousal timing, so the sweep over `rho_a × rho_slow` is the whole search
space and the "best-timed setting" is best over all of it.
### Verdict against the pre-registered criterion
> **SUCCESS** = arousal's peak moves to within 3 steps of the switch **and** the paired
> `grp_k0 / grp_k` steady ratio exceeds 1.10 on at least 12 of 16 seeds.
- Peak within 3 steps of the switch: **met** — lag 1, from lag 11.
- Ratio > 1.10 on ≥ 12/16 seeds: **not met** — 0/16 at the pre-declared κ=4, 0–1/16
at every κ and both settings, largest ratio anywhere 1.107.
**Part 1 is a FAILURE, and it is the failure the brief named as the informative one:
the mechanism works, is correctly timed, and the domain gives it nothing.** A1 is
closed on this domain by a stronger argument than `a1.md` had, because the one
remaining explanation — that the signal arrived too late — has now been removed and
the result did not move.
## 2. Part 2 — measuring `T_id`
Nothing in `identify.py` constructs an Organism. `T_id` is a property of the domain.
### 2a. What the observer has, and what "optimal" means here
At step `t` the observer has the coordinates `c_{t−L+1} … c_t` and therefore the
displacements `d_s = wrap(c_{s+1} − c_s)` for `s = t−L+1 … t−1`. **`d_t` is never
available** — that is what the organism is asked to predict, and handing it over would
hand over the answer. So `L = 1` is the instantaneous configuration alone and each
extra step of window buys exactly one more observed displacement.
The dynamics factor as
```
d_i(s) = sum_c K[t_i, c] · B_i^c(s) + eps, B_i^c(s) = dt · sum_{j: t_j = c} kern(r_ij) r_ij
```
`B` is the message basis — everything about the configuration the coupling multiplies
— and is computable from coordinates alone, so it is observer-side information. It is
the same decomposition `ceilings.py` fits. Self-check, the analogue of that file's row
A: the basis reproduces the world's own displacements at residual **4.0024e-06**
against `noise² = 4.0e-06`, asserted on every rollout.
Four decoders, in ascending order of what they are told:
| tag | features | estimator | knows the coupling matrices? |
|---|---|---|---|
| `lin` | raw window: `B` at each step, the observed displacements, the type one-hot | least squares | no |
| `mlp` | the same raw window | 2×128 ReLU MLP | no |
| `phys` | `<d, B^c>` and `<B^c, B^c'>` summed over the window, interacted with the type one-hot | multinomial logistic | no |
| `bayes` | the exact Gaussian likelihood over the window | closed form | **yes** |
`phys` is the fair stand-in for "optimal", and the reason is algebraic rather than
empirical: the log-likelihood of regime `g` is affine in exactly those statistics with
coefficients depending on `g` and on the entity's own type, so a linear classifier on
them **can express the exact Bayes rule**. `bayes` computes that rule directly and is
the cross-check. `lin` and `mlp` are the honest non-omniscient decoders, and the MLP is
the capacity check the brief asked for before concluding anything from a linear probe.
Chance is measured, not assumed — the two nulls `frozen.py` uses, both refitting from
scratch: a label shuffle, and a circular shift that preserves each regime's block
structure and is the stricter of the two. The shift null is quoted in brackets.
### 2b. The table
8 seeds, 4000 world steps, `t_min/t_max = 40/80`. "hist" is the steps of history
`L` observations actually provide. `sw.frac` is the fraction of windows spanning a
regime change. Per-step accuracy pools the 16 entities of a step, which is what an
observer watching the whole world does; per-entity is one classification per entity.
```
per-step accuracy (measured chance in brackets)
L hist sw.frac lin mlp phys bayes
-----------------------------------------------------------------------------------
1 0 0.000 0.229[0.224] 0.552[0.259] -- --
2 1 0.016 0.231[0.227] 0.831[0.266] 0.909[0.230] 0.958
3 2 0.033 0.231[0.232] 0.856[0.268] 0.926[0.233] 0.961
5 4 0.065 0.232[0.233] 0.874[0.250] 0.923[0.236] 0.952
10 9 0.147 0.234[0.232] 0.863[0.257] 0.888[0.237] 0.915
20 19 0.311 0.238[0.227] 0.814[0.260] 0.798[0.249] 0.842
40 39 0.640 0.237[0.227] 0.708[0.274] 0.632[0.237] 0.699
per-entity accuracy (measured chance in brackets)
L hist sw.frac lin mlp phys bayes
-----------------------------------------------------------------------------------
1 0 0.000 0.242[0.231] 0.405[0.251] -- --
2 1 0.016 0.251[0.233] 0.563[0.253] 0.566[0.230] 0.566
3 2 0.033 0.251[0.236] 0.590[0.253] 0.614[0.233] 0.629
5 4 0.065 0.251[0.238] 0.605[0.246] 0.643[0.234] 0.684
10 9 0.147 0.248[0.236] 0.598[0.251] 0.639[0.237] 0.718
20 19 0.311 0.247[0.230] 0.553[0.248] 0.581[0.239] 0.702
40 39 0.640 0.243[0.229] 0.476[0.252] 0.486[0.233] 0.601
```
Per-seed `bayes` per-step at `L=2`: `0.97 0.98 0.98 0.98 0.95 0.97 0.93 0.90`, and
`phys` `0.93 0.97 0.96 0.98 0.92 0.93 0.79 0.78`. It is not an average over a few
lucky seeds.
**`T_id = 2` observations — one step of history.** A single observed displacement takes
per-step accuracy from 0.55 to 0.96. `L = 3` adds 0.003 and every longer window is
*worse*, because the assumption that one regime governs the window stops holding
(`sw.frac` reaches 0.64 at `L = 40`). The saturation point is not a plateau; it is a
peak at `L = 2–3`, and the decline past it is the domain telling you that more history
is actively harmful once the window outruns the regime.
Three details worth carrying:
- **The linear decoder on the raw window never rises** — 0.23 against 0.23 at every
`L`. Exactly the case the brief warned about: a linear probe here would have said
the regime is unidentifiable, and it would have been wrong by 0.7 in accuracy. The
MLP and `phys` are what settle it, and `bayes` bounds them.
- **`phys` tracks `bayes` to within 0.05 and never beats it**, which is the
cross-check the construction demanded.
- **The instantaneous read-off is much larger than the organism's.** At `L = 1`, with
no displacement at all, the MLP reaches 0.552 per-step and 0.405 per-entity against
a measured chance of 0.25. `frozen.md` §2 decoded the regime from the organism's own
`h` at 0.342 and from `M` at 0.332, against 0.274 — a gap of +0.07 where the
configuration in front of it supports +0.15. The organism is discarding most of the
regime information already visible in a single frame.
### 2c. `T_id` at each duration Part 3 sweeps
`bayes` per-step, 4 seeds, 4000 steps. `argmax L` is where accuracy saturates.
```
T_z L=2 L=3 L=5 L=10 L=20 L=40 argmax L
----------------------------------------------------------------------------
4-8 0.825 0.722 0.538 0.250 0.300 0.267 2
10-20 0.930 0.890 0.821 0.644 0.313 0.339 2
40-80 0.978 0.974 0.959 0.922 0.858 0.726 2
150-300 0.973 0.989 0.989 0.980 0.963 0.930 5
600-1200 0.960 0.991 0.997 0.995 0.992 0.985 5
```
`T_id` is 2 across the sweep, drifting to 5 at the longest durations where a longer
window is finally safe to use. **`T_id` is between 1 and 4 steps of history at every
duration Part 3 tests**, and is undefined at the frozen regime, which has nothing to
identify.
### 2d. `G` at each duration
`ceilings.py`, rows D → C, 1200 steps, seeds 0–2. The oracle prize against the noisy
target:
```
T_z 4-8 10-20 40-80 150-300 600-1200 frozen
--------------------------------------------------------------
G 1.95 1.62 1.56 1.48 1.24 1.00
```
The 40–80 value reproduces `headroom.md` §3's 1.56x exactly. `G` decays monotonically
with duration and reaches **exactly 1.00 at the frozen regime**, which is the
self-consistency check: a regime that never changes carries no information, so a
regime oracle can be worth nothing. Every row A self-check passes.
### The reading the brief pre-registered
> `T_id << T_z` — the domain *can* reward memory, and the failure is ours rather than
> the domain's. That points at the architecture or the training signal, and it is a
> much more uncomfortable and more useful result.
`T_id = 2`, `T_z = 40–80`. **`T_id` is 20 to 40 times smaller than `T_z`, and `G` is
1.56.** The domain satisfies the pre-registered condition, comfortably, on both
quantities. The regime is identifiable from one observed step and then holds still for
another forty. This is the uncomfortable branch, and §2b's last bullet says where to
look: the organism's own representation carries less than half the regime information
that a decoder recovers from the same frame.
## 3. Part 3 — the falsifiable test
The capacity-controlled state gain `grp_k0_nostate / grp_k0`: identical architecture,
identical 5602 parameters, differing only in whether `M` is carried between steps.
A `grp_k0` vs `rp_only` number is confounded 3.9x (`frozen.md` §5) and is not this
measurement. κ = 0 in both arms; affect is at its defaults and plays no part here.
Shortening the regime changes the world's timescale, so the metrics were re-checked
rather than re-used. Two things were done about it:
- **The recovery window is enforced per duration.** `regime.run` refuses
`window >= t_min`; the same rule is applied here, and each run stores its metrics at
every window shorter than its own `t_min`. Tables quote **window 1** because it is
the only window a duration of 2–3 admits and therefore the one column every duration
can be compared on; windows 3 and 9 are given alongside and agree.
- **Switch counts are reported rather than implied.** At 600–1200 there are ~4
switches in the measured half — enough for `steady`, which averages over thousands
of steps, and not enough for a recovery curve. **No `recovery[k]` number is quoted
from the two longest durations**, and the state gain is read off `steady` throughout.
```
regime duration state gain median seeds won per-seed range
------------------------------------------------------------------
2-3 1.09 1.06 10/16 0.76 - 1.66
4-8 1.10 1.04 10/16 0.87 - 1.72
10-20 1.09 1.01 10/16 0.83 - 1.56
40-80 1.17 1.11 11/16 0.91 - 1.88
150-300 1.22 1.20 10/16 0.32 - 2.86
600-1200 1.12 1.01 8/16 0.62 - 1.77
frozen 1.26 1.12 11/16 0.69 - 1.99
```
Read down the `state gain` column. It does not have a peak. It is flat at 1.09-1.26
across regime durations spanning four orders of magnitude, and every difference between
durations is smaller than the per-seed range within any one of them: at 150-300 the
individual seeds run from 0.32 to 2.86, which is wider than the entire spread of the
column means. On a paired count the picture is the same, 8 to 11 seeds of 16 at every
duration -- a coin flip that never becomes anything else.
The decisive row is the last one. **The largest state gain in the sweep is at the frozen
regime**, where there is no regime to identify, no switch to recover from, and `G`
measures exactly 1.00. A quantity that is at its largest when its supposed cause is
entirely absent is not caused by it.
What the state gain measures is therefore not regime tracking. It is temporal smoothing:
carrying `M` averages the representation over recent steps, which reduces variance
against a noisy target, and a stationary world rewards that at least as well as a
switching one does.
## 4. So: when does per-entity memory have a job?
The task was built on a theory, pre-registered before any run: memory has a job when the
hidden variable is identifiable much faster than it changes (`T_id << T_z`) and knowing it
is worth something (`G` materially above 1). The prediction was a peak in state gain at
intermediate regime durations.
**The theory is wrong as stated, and the three parts falsify it from three directions.**
Its condition is satisfied here -- comfortably. `T_id` is 2 to 3 observations against a
`T_z` of 40-80, a margin of twenty-fold or more, and `G` is 1.54x. By the theory this
domain should be close to ideal for per-entity memory. It is not: the state gain is 1.17
at that duration, on 11 seeds of 16, and it is *higher* at the frozen regime where the
condition is not satisfied at all. A criterion that is met exactly where the effect is
absent, and unmet exactly where the effect is largest, is not the criterion.
What the three parts establish together is more useful than the theory they refute.
**The domain is the rememberable kind.** Part 2 settles the question the poker framing
raised: is the evidence for the hidden variable already in the present, making history
redundant, or does it live only in the past? Here it lives in the past. One observed
displacement carries the regime almost perfectly -- 0.958 for an exact decoder, 0.909 for
one that has never seen a coupling matrix -- while the instantaneous configuration alone
supports 0.574 at best. History nearly doubles the present's above-chance information.
This is not a domain where feedforward suffices in principle.
**The organism captures almost none of it.** `frozen.md` Part B decoded the regime from
the GRP's memory at 0.332. The same regime is available at 0.909 from a single step of
history, using a decoder with no privileged knowledge. `M` holds roughly a fifth of the
signal that a fair observer extracts from one step of the past, and no more than the
memoryless RP's own `h` holds.
**So the failure is ours, not the domain's.** That is the uncomfortable branch, and it was
named in advance precisely so it could not be avoided afterwards: `T_id << T_z` was
pre-registered as meaning "the domain can reward memory and the failure is ours". It came
out that way. This matters beyond this file, because the project's standing reflex when
memory failed to help was to reach for a different domain. That reflex is now closed off.
The information was here all along.
The mechanism is visible in the other files rather than derived here, and the three
observations compose:
- The gate's learned pre-activation never leaves zero, at any `kappa`, after any amount of
training (`a1.md` §1b). Nothing about what to keep is ever decided.
- The margin the GRP does win is its gated post-RP nonlinearity, not carried state and not
parameter count (`frozen.md` §1d).
- Affect can move the gate, exactly and on cue once its time constants are set (Part 1
above), and moving it changes nothing, because there is no stored quantity for an opened
gate to admit or a closed one to protect.
The regime is identifiable from an observed displacement -- which arrives one step after
the prediction it would have helped. Carrying that one step forward is precisely what
per-entity memory is for, and precisely what the gate would have to learn to do. It never
does. Whether that is a credit-assignment failure, a consequence of the per-step loss term
dominating the temporal one, or a mismatch between a global hidden variable and a
per-entity state, this file does not determine. It establishes only that the question is
now about the organism and no longer about the domain.
---
*Write-up note: the agent that ran these measurements died mid-write when the machine
slept, leaving §3's table and §4 unwritten. Both were completed from the committed JSON
by the session controller, which independently recomputed Part 3's table from
`w_duration_all.json` and `w_duration_frozen.json`, Part 1's paired ratios and arousal
profiles from `w_best.json` and `w_timing.json`, and Part 2's decoder series from
`identify.json`. No sweep was re-run and no number was carried over unverified.*
+225
View File
@@ -0,0 +1,225 @@
"""Task 9. Each test here defends one property a headline number rests on.
AGENTS.md: a test that cannot fail is worse than no test. Every test below that
defends a central property has a companion that breaks the property on purpose and
asserts the guard fires -- named `..._can_fail` or written as a `pytest.raises`
inside the test itself.
"""
from __future__ import annotations
import numpy as np
import pytest
import torch
import identify
import when_memory_works as wmw
from ailed import AffectConfig
from frozen import _build, _train
from particles import ParticleConfig
from regime import _metrics
# -- Part 1: the arousal profile is the arousal the gate actually saw --------------
def _run_with_gate_trace(steps=300):
from a1 import GateTrace
spec, wcfg, world, org = _build("grp_k", seed=0, hidden=32, omega=10.0, kappa=4.0)
tr = GateTrace(org)
_, _, out = _train(spec, wcfg, world, org, steps, bptt=20, lr=1e-3, on_step=tr)
return np.asarray(tr.a_gate, dtype=float), out
def test_gate_arousal_seq_is_the_arousal_the_organism_was_handed():
"""`_train` records affect *after* the update, so the gate's input is lagged by one.
`a1.GateTrace` records the value the organism was actually passed. If these two
disagree, every arousal-vs-lag profile in Part 1 is off by a step and the
pre-registered "within 3 steps" criterion is being judged against the wrong curve.
"""
seen, out = _run_with_gate_trace()
assert np.array_equal(wmw.gate_arousal_seq(out["arousals"]), seen)
def test_gate_arousal_seq_can_fail():
"""Break it on purpose: the un-lagged sequence must NOT match."""
seen, out = _run_with_gate_trace()
assert not np.array_equal(np.asarray(out["arousals"], dtype=float), seen)
def test_affect_config_is_passed_through_and_changes_the_arousal_stream():
"""`--part timing` is only a sweep if the config reaches the loop. Two settings,
same seed, must produce different arousal; the default must reproduce the default."""
args = ("grp_k0", 0, 0.0)
kw = dict(steps=300, windows=(20,))
base = wmw.run_one(*args, AffectConfig(), **kw)
same = wmw.run_one(*args, wmw._cfg(0.5, 0.02, 0.2), **kw)
other = wmw.run_one(*args, wmw._cfg(1.0, 0.4), **kw)
assert base["arousal"]["20"]["far"] == same["arousal"]["20"]["far"]
assert base["arousal"]["20"]["far"] != other["arousal"]["20"]["far"]
def test_cfg_keeps_the_slow_baseline_slower_than_the_fast_one():
for ra in wmw.RHO_A:
for rs in wmw.RHO_SLOW:
c = wmw._cfg(ra, rs)
assert c.rho_slow < c.rho_fast, (ra, rs)
def test_peak_lag_and_by_lag_average_over_the_switches_metrics_uses():
"""`by_lag` must cut the trace exactly as `_metrics` cuts `recovery`."""
steps, window = 400, 20
rng = np.random.default_rng(0)
losses = list(rng.random(steps))
switched = [i % 57 == 0 for i in range(steps)]
got = wmw.by_lag(np.asarray(losses), switched, steps, window)
assert got == pytest.approx(_metrics(losses, switched, [0.0] * steps, window)["recovery"])
# -- Part 2: the decoder is causal, and the basis is the world's -------------------
def test_features_never_use_the_displacement_being_decoded():
"""The window at step t may use d_{t-L+1..t-1} and never d_t.
This is the property that makes T_id a statement about an observer rather than
about a decoder handed the answer. Corrupting d_t alone must leave the features
for step t untouched -- and must change the features for step t+1, or the test
would pass on a decoder that ignores displacements altogether.
"""
world = identify.rollout(ParticleConfig(seed=0), 120)
for kind in ("raw", "phys"):
X, y, ts = identify.features(world, L=5, kind=kind)
hit = 40
t = ts[hit]
poisoned = dict(world, disp=world["disp"].clone())
poisoned["disp"][t] += 1.0
Xp, _, _ = identify.features(poisoned, L=5, kind=kind)
assert np.array_equal(X[hit], Xp[hit]), f"{kind} leaked d_t"
assert not np.array_equal(X[hit + 1], Xp[hit + 1]), f"{kind} ignores displacements"
def test_basis_reproduces_the_worlds_dynamics_to_the_noise_floor():
world = identify.rollout(ParticleConfig(seed=1), 300)
resid = identify._check_basis(world)
assert resid == pytest.approx(ParticleConfig().noise ** 2, rel=0.03)
def test_basis_check_can_fail():
"""Hand `_check_basis` the wrong regime sequence: the residual must blow past noise."""
world = identify.rollout(ParticleConfig(seed=1), 300)
wrong = dict(world, regimes=(world["regimes"] + 1) % 4)
with pytest.raises(AssertionError):
identify._check_basis(wrong)
def test_bayes_decoder_recovers_a_regime_it_can_see_and_not_one_it_cannot():
"""Planted signal and planted absence, the shape `test_frozen.py` uses for its probe.
With the real displacements the exact decoder must be far above chance at L=2.
With the displacements replaced by noise there is nothing to decode and it must
fall to chance, which is what says the accuracy comes from the dynamics.
"""
world = identify.rollout(ParticleConfig(seed=0), 1200)
assert identify.bayes(world, L=2)["acc_step"] > 0.8
blind = dict(world, disp=torch.randn_like(world["disp"]) * 1e-3)
assert identify.bayes(blind, L=2)["acc_step"] < 0.45
def test_decode_is_at_chance_when_the_labels_carry_no_signal():
world = identify.rollout(ParticleConfig(seed=0), 900)
X, y, _ = identify.features(world, L=3, kind="phys")
real = identify.decode(X, y, 4, "logit", n_null=2, seed=0)
shuffled = identify.decode(X, np.random.default_rng(0).permutation(y), 4, "logit",
n_null=2, seed=0)
assert real["acc_step"] > 0.7
assert shuffled["acc_step"] < 0.45
def test_decode_test_split_is_a_suffix_in_time():
world = identify.rollout(ParticleConfig(seed=0), 600)
X, y, _ = identify.features(world, L=2, kind="phys")
poisoned = X.copy()
cut = int(len(X) * identify.SPLIT)
poisoned[:cut] = 0.0 # destroying only the train prefix must hurt
a = identify.decode(X, y, 4, "logit", n_null=1, seed=0)["acc_step"]
b = identify.decode(poisoned, y, 4, "logit", n_null=1, seed=0)["acc_step"]
assert b < a
def test_switch_fraction_counts_windows_that_span_a_change():
world = identify.rollout(ParticleConfig(seed=0, t_min=40, t_max=80), 800)
assert identify.switch_fraction(world, 1) == 0.0
assert identify.switch_fraction(world, 2) < identify.switch_fraction(world, 40)
# -- Part 3: the comparison stays capacity-controlled ------------------------------
def test_state_ablation_changes_only_whether_memory_is_carried():
"""Both arms of Part 3 must have the same architecture and the same parameter count.
`results/frozen.md` §5: a `grp_k0` vs `rp_only` number is confounded 3.9x. The
number Part 3 reports is `grp_k0_nostate / grp_k0`, and this is what makes it a
state measurement rather than a capacity measurement.
"""
kw = dict(steps=200, windows=(20,))
a = wmw.run_one("grp_k0", 0, 0.0, AffectConfig(), stateless=False, **kw)
b = wmw.run_one("grp_k0", 0, 0.0, AffectConfig(), stateless=True, **kw)
assert a["n_params"] == b["n_params"] == 5602
assert a["metrics"]["20"]["steady"] != b["metrics"]["20"]["steady"]
def test_duration_override_reaches_the_world_and_leaves_the_default_alone():
_, wcfg, world, _ = _build("grp_k0", 0, 32, 10.0, 0.0, t_min=10, t_max=20)
assert (wcfg.t_min, wcfg.t_max) == (10, 20)
assert 10 <= world.until <= 20
_, default, _, _ = _build("grp_k0", 0, 32, 10.0, 0.0)
assert (default.t_min, default.t_max) == (40, 80)
assert (ParticleConfig().t_min, ParticleConfig().t_max) == (40, 80)
def test_shorter_regimes_really_do_switch_more_often():
kw = dict(steps=1000, windows=(3,), kappa=0.0)
fast = wmw.run_one("grp_k0", 0, acfg=AffectConfig(), t_min=10, t_max=20, **kw)
slow = wmw.run_one("grp_k0", 0, acfg=AffectConfig(), t_min=150, t_max=300, **kw)
frozen = wmw.run_one("grp_k0", 0, acfg=AffectConfig(), t_min=99999, t_max=99999, **kw)
assert fast["metrics"]["3"]["n_switches"] > slow["metrics"]["3"]["n_switches"] > 0
assert frozen["metrics"]["3"]["n_switches"] == 0
def test_windows_that_reach_the_next_switch_are_not_reported():
"""`regime.run` refuses window >= t_min. Part 3 has to shorten the regime, so the
same rule is enforced per window: a duration of 10-20 may not report window 20."""
r = wmw.run_one("grp_k0", 0, 0.0, AffectConfig(), steps=400, windows=wmw.WINDOWS,
t_min=10, t_max=20)
assert set(r["metrics"]) == {"1", "3", "9"} # 20 reaches the next switch
def test_paired_ratio_is_per_seed_and_refuses_to_pair_across_seeds():
num = [dict(seed=s, metrics={"9": dict(steady=2.0)}) for s in (0, 1, 2)]
den = [dict(seed=s, metrics={"9": dict(steady=1.0)}) for s in (0, 1, 3)]
p = wmw.paired(num, den, window=9)
assert p["seeds"] == [0, 1] and p["n"] == 2
assert p["mean"] == pytest.approx(2.0) and p["won"] == 2
def test_the_present_only_baseline_sees_arrangement_the_message_basis_misses():
"""`L = 1` carries the whole history-over-present comparison, so it must not be
handicapped. A symmetric ring of same-type neighbours cancels in the first moment
`B` but not in the kernel mass, and `_frame` has to keep that distinction."""
cfg = ParticleConfig(n=5, n_types=1)
types = torch.zeros(5, dtype=torch.long)
tight = torch.tensor([[0.5, 0.5], [0.55, 0.5], [0.45, 0.5], [0.5, 0.55], [0.5, 0.45]])
loose = torch.tensor([[0.5, 0.5], [0.9, 0.5], [0.1, 0.5], [0.5, 0.9], [0.5, 0.1]])
a, b = identify._frame(tight, types, cfg)[0], identify._frame(loose, types, cfg)[0]
assert a[:2] == pytest.approx(b[:2], abs=1e-6) # the first moment cancels in both
assert a[2] > 5 * b[2] # the kernel mass does not
def test_history_gain_is_computed_against_the_same_decoder_at_L1():
"""accuracy(L) - accuracy(1) is only meaningful if both use the same per-frame
features and the same estimator; this pins that the raw feature block grows by
whole frames plus displacements and by nothing else."""
world = identify.rollout(ParticleConfig(seed=0), 120)
f = world["frame"].shape[-1]
n1 = identify.features(world, 1, "raw")[0].shape[-1]
n3 = identify.features(world, 3, "raw")[0].shape[-1]
assert n3 - n1 == 2 * f + 2 * 2 # two more frames, two more displacements
+321
View File
@@ -0,0 +1,321 @@
"""Task 9 Parts 1 and 3: when does per-entity memory have a job?
Part 2 lives in `identify.py` -- it measures `T_id` and touches no organism.
**Part 1 (`--part timing`)** is the last legitimate shot at A1. `results/a1.md` §1a
measured arousal peaking about 12 steps *after* a switch and sitting *lower* at the
switch step (0.061) than far from one (0.106). `rho_a` and `rho_slow` are the affect
mechanism's own time constants and have never been set, so tuning them is tuning the
mechanism rather than tuning a baseline to lose. This sweeps them, reports the
arousal-vs-lag profile for each, and runs `grp_k` against `grp_k0` at the best-timed
setting.
Only `rho_slow` and `rho_a` can move arousal's timing. Read `affect.update`:
a_target = tanh(max(0, loss - slow) / (slow + eps)); a <- a + rho_a (a_target - a)
`fast` appears only in `v_target`, so `rho_fast` reaches arousal solely through the
loss stream, via valence feeding the CPPN. `--part rho-fast` measures that it does not
matter, rather than assuming it. Where the sweep raises `rho_slow` past the default
`rho_fast`, `rho_fast` is raised with it (`_cfg`), because `AffectConfig` documents
`rho_slow < rho_fast` and inverting the two would change what valence means as a side
effect of a timing sweep. `AffectConfig`'s defaults are not touched: values are passed.
**Part 3 (`--part duration`)** is the falsifiable test. At each regime duration it
measures the **capacity-controlled** state gain `grp_k0_nostate / grp_k0`: identical
architecture, identical 5602 parameters, differing only in whether memory is carried
between steps. A `grp_k0` vs `rp_only` number is confounded 3.9x on parameter count
(`results/frozen.md` §5) and is not this measurement.
Shortening the regime changes the world's timescale, so the metrics have to be
re-checked rather than re-used. `regime._metrics` is a pure function of the traces and
the window, so each run stores its metrics at every window shorter than the duration's
`t_min`; the tables then quote one window across all durations and `steady` means the
same thing in every row. `n_switches` is reported with every number so a duration with
too few switches in the measured half to average over is visible rather than implied.
uv run python when_memory_works.py --part timing --out results/w_timing.json
uv run python when_memory_works.py --part rho-fast --rho-a 1.0 --rho-slow 0.2 \
--out results/w_rhofast.json
uv run python when_memory_works.py --part best --rho-a 1.0 --rho-slow 0.2 \
--out results/w_best.json
uv run python when_memory_works.py --part duration --out results/w_duration_all.json
"""
from __future__ import annotations
import argparse
import json
import statistics
from pathlib import Path
import numpy as np
from ailed import AffectConfig
from frozen import _build, _train
from regime import _metrics
STEPS = 8000
BPTT = 20
LR = 1e-3
HIDDEN = 32
OMEGA = 10.0
# Part 1: rho_a x rho_slow. rho_fast is carried up with rho_slow (see _cfg).
RHO_A = (0.5, 1.0)
RHO_SLOW = (0.02, 0.05, 0.1, 0.2, 0.4)
TIMING_SEEDS = (0, 1, 2, 3)
BEST_SEEDS = tuple(range(16))
KAPPA_PRIMARY = 4.0 # `regime.run`'s standing default; the criterion is read off this
KAPPA_CONTEXT = (1.0, 16.0) # reported as context, never as the verdict
# Part 3: the pre-registered grid, plus (4, 8) added before any duration run was made
# because T_id turns out to be short and the predicted peak would otherwise sit on the
# grid's edge. `frozen` draws one regime and never switches, as headroom.md section 5 did.
# (2, 3) probes the theory's left arm, T_z < T_id. Part 2 measures T_id = 2 observations,
# so no duration in the pre-registered grid reaches below it -- the shortest, 4-8, is
# already twice T_id. It was added after Part 2 and before any duration run was read.
DURATIONS = ((2, 3), (4, 8), (10, 20), (40, 80), (150, 300), (600, 1200), (STEPS * 2, STEPS * 2))
DURATION_SEEDS = tuple(range(16))
# window 1 is the only one a duration of 2-3 admits, and it is the column every duration
# can therefore be compared on. Reported alongside, never instead of, the wider windows.
WINDOWS = (1, 3, 9, 20)
def _cfg(rho_a: float, rho_slow: float, rho_fast: float | None = None) -> AffectConfig:
"""An AffectConfig with the swept time constants, keeping rho_slow < rho_fast.
`AffectConfig` says rho_slow "must be < rho_fast". The default pair is (0.02, 0.2),
a factor of ten. Settings that raise rho_slow past 0.2 therefore raise rho_fast to
keep a separation, so the sweep moves arousal's timing without silently inverting
the two baselines valence is built from.
"""
fast = rho_fast if rho_fast is not None else max(0.2, 2.0 * rho_slow)
return AffectConfig(rho_a=rho_a, rho_slow=rho_slow, rho_fast=fast)
def label(acfg: AffectConfig) -> str:
return f"a{acfg.rho_a:g}/s{acfg.rho_slow:g}/f{acfg.rho_fast:g}"
# -- one run ---------------------------------------------------------------------
def gate_arousal_seq(arousals: list[float]) -> np.ndarray:
"""The arousal the gate saw at each step, from the arousal `_train` records.
`_train` appends `affect.arousal` *after* `update`, so `arousals[t]` is built from
`losses[t]` and the gate at step t saw the previous value. Step 0 sees `Affect()`'s
initial 0.0. `tests/test_when_memory_works.py` pins this against `a1.GateTrace`,
which records the value the organism actually passed in.
"""
return np.concatenate([[0.0], np.asarray(arousals[:-1], dtype=float)])
def by_lag(x: np.ndarray, switched: list[bool], steps: int, window: int) -> list[float]:
"""`x` at lag k after a switch, averaged over the measured (second) half's switches.
The same cut `regime._metrics` uses for `recovery`, so an arousal profile and an
error profile are averaged over exactly the same switches.
"""
half = steps // 2
sw = [i for i in range(half, steps - window) if switched[i]]
if not sw:
return [float("nan")] * window
return [float(x[[j + k for j in sw]].mean()) for k in range(window)]
def far_level(x: np.ndarray, switched: list[bool], steps: int, window: int) -> float:
"""`x` on `_metrics`'s own `steady_idx` -- no switch in the preceding `window` steps."""
half = steps // 2
idx = [i for i in range(half, steps) if not any(switched[max(0, i - window):i + 1])]
return float(x[idx].mean()) if idx else float("nan")
def run_one(name: str, seed: int, kappa: float, acfg: AffectConfig, *,
steps: int = STEPS, windows: tuple[int, ...] = (20,), t_min: int | None = None,
t_max: int | None = None, stateless: bool = False, bptt: int = BPTT,
lr: float = LR, hidden: int = HIDDEN, omega: float = OMEGA) -> dict:
spec, wcfg, world, org = _build(name, seed, hidden, omega, kappa, t_min, t_max)
_, _, tr = _train(spec, wcfg, world, org, steps, bptt, lr, stateless, acfg=acfg)
a_gate = gate_arousal_seq(tr["arousals"])
out = dict(condition=name + ("_nostate" if stateless else ""), seed=seed, kappa=kappa,
steps=steps, stateless=stateless, t_min=wcfg.t_min, t_max=wcfg.t_max,
rho_a=acfg.rho_a, rho_slow=acfg.rho_slow, rho_fast=acfg.rho_fast,
affect=label(acfg), n_params=sum(p.numel() for p in org.parameters()),
metrics={}, arousal={}, loss_by_lag={})
losses = np.asarray(tr["losses"], dtype=float)
for w in windows:
if w >= wcfg.t_min:
continue # a recovery window reaching the next switch blends two events
out["metrics"][str(w)] = _metrics(tr["losses"], tr["switched"], tr["arousals"], w)
out["arousal"][str(w)] = dict(
by_lag=by_lag(a_gate, tr["switched"], steps, w),
far=far_level(a_gate, tr["switched"], steps, w))
out["loss_by_lag"][str(w)] = by_lag(losses, tr["switched"], steps, w)
return out
# -- Part 1 ----------------------------------------------------------------------
def peak_lag(profile: list[float]) -> int:
"""Lag of the maximum, or -1 when there is nothing to peak.
A frozen regime never switches, so `by_lag` and `recovery` are all-NaN there and
there is no post-switch profile to take an argmax over. That is a real state of the
world at the end of Part 3's sweep, not an error.
"""
a = np.asarray(profile, dtype=float)
return -1 if np.all(np.isnan(a)) else int(np.nanargmax(a))
def timing_table(results: list[dict], window: int = 20) -> str:
"""Arousal at each lag after a switch, per affect setting, means over seeds."""
by: dict[str, list[dict]] = {}
for r in results:
by.setdefault(r["affect"], []).append(r)
lags = list(range(0, min(window, 20), 2))
head = "".join(f"{'@' + str(k):>7}" for k in lags)
lines = [f"{'rho_a/rho_slow/rho_fast':<24}{head}{'far':>7}{'peak':>7}{'loss pk':>9}",
"-" * (24 + 7 * len(lags) + 23)]
for name, rs in sorted(by.items()):
prof = [statistics.fmean(r["arousal"][str(window)]["by_lag"][k] for r in rs)
for k in range(window)]
lprof = [statistics.fmean(r["loss_by_lag"][str(window)][k] for r in rs)
for k in range(window)]
far = statistics.fmean(r["arousal"][str(window)]["far"] for r in rs)
lines.append(f"{name:<24}" + "".join(f"{prof[k]:>7.3f}" for k in lags)
+ f"{far:>7.3f}{peak_lag(prof):>7d}{peak_lag(lprof):>9d}")
return "\n".join(lines)
def paired(num: list[dict], den: list[dict], window: int = 20, key: str = "steady") -> dict:
"""`num/den` on `steady`, per seed. Both lists must cover the same seeds."""
a = {r["seed"]: r["metrics"][str(window)][key] for r in num}
b = {r["seed"]: r["metrics"][str(window)][key] for r in den}
seeds = sorted(set(a) & set(b))
ratios = [a[s] / b[s] for s in seeds]
return dict(n=len(seeds), mean=statistics.fmean(ratios),
median=statistics.median(ratios), won=sum(r > 1.0 for r in ratios),
per_seed=ratios, seeds=seeds)
# -- Part 3 ----------------------------------------------------------------------
def duration_table(results: list[dict], window: int) -> str:
"""Capacity-controlled state gain against regime duration."""
by: dict[tuple, dict[str, list[dict]]] = {}
for r in results:
by.setdefault((r["t_min"], r["t_max"]), {}).setdefault(r["condition"], []).append(r)
lines = [f"{'duration':>14}{'window':>7}{'n_sw':>6}{'grp_k0':>11}{'nostate':>11}"
f"{'gain':>7}{'median':>8}{'won':>7}",
"-" * 71]
for dur in sorted(by):
arms = by[dur]
if "grp_k0" not in arms or "grp_k0_nostate" not in arms:
continue
if any(str(window) not in r["metrics"] for r in arms["grp_k0"]):
continue
p = paired(arms["grp_k0_nostate"], arms["grp_k0"], window)
m = lambda c: statistics.fmean(r["metrics"][str(window)]["steady"] for r in arms[c])
nsw = statistics.fmean(r["metrics"][str(window)]["n_switches"] for r in arms["grp_k0"])
tag = "frozen" if dur[0] >= STEPS else f"{dur[0]}-{dur[1]}"
lines.append(f"{tag:>14}{window:>7}{nsw:>6.0f}{m('grp_k0'):>11.3e}"
f"{m('grp_k0_nostate'):>11.3e}{p['mean']:>7.2f}{p['median']:>8.2f}"
f"{str(p['won']) + '/' + str(p['n']):>7}")
return "\n".join(lines)
# -- driver ----------------------------------------------------------------------
def _save(results: list[dict], out: str) -> None:
Path(out).parent.mkdir(parents=True, exist_ok=True)
Path(out).write_text(json.dumps(results, indent=1))
def _say(r: dict, window: int) -> None:
m = r["metrics"].get(str(window))
a = r["arousal"].get(str(window))
extra = ""
if m is not None:
extra = f" steady={m['steady']:.3e} n_sw={m['n_switches']}"
if a is not None:
extra += f" a_peak@{peak_lag(a['by_lag'])} a_far={a['far']:.3f}"
print(f"{r['condition']:<16} k={r['kappa']:<5g} {r['affect']:<18} "
f"dur={r['t_min']}-{r['t_max']:<6} seed={r['seed']:<3}{extra}", flush=True)
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--part", required=True,
choices=["timing", "rho-fast", "best", "duration"])
ap.add_argument("--seeds", default=None)
ap.add_argument("--steps", type=int, default=STEPS)
ap.add_argument("--window", type=int, default=20)
ap.add_argument("--rho-a", type=float, default=None, help="best/rho-fast: the setting to run")
ap.add_argument("--rho-slow", type=float, default=None)
ap.add_argument("--kappa", type=float, default=KAPPA_PRIMARY)
ap.add_argument("--durations", default=None,
help="duration: comma-separated t_min-t_max pairs, e.g. 10-20,40-80")
ap.add_argument("--out", required=True)
a = ap.parse_args()
seeds = tuple(int(s) for s in a.seeds.split(",")) if a.seeds else None
results: list[dict] = []
if a.part == "timing":
for ra in RHO_A:
for rs in RHO_SLOW:
for seed in seeds or TIMING_SEEDS:
r = run_one("grp_k0", seed, 0.0, _cfg(ra, rs),
steps=a.steps, windows=(a.window,))
_say(r, a.window); results.append(r)
_save(results, a.out)
print(); print(timing_table(results, a.window))
elif a.part == "rho-fast":
ra = a.rho_a if a.rho_a is not None else 0.5
rs = a.rho_slow if a.rho_slow is not None else 0.02
for rf in (0.1, 0.2, 0.5, 0.9):
if rf <= rs:
continue
for seed in seeds or TIMING_SEEDS:
r = run_one("grp_k0", seed, 0.0, _cfg(ra, rs, rf),
steps=a.steps, windows=(a.window,))
_say(r, a.window); results.append(r)
_save(results, a.out)
print(); print(timing_table(results, a.window))
elif a.part == "best":
acfg = _cfg(a.rho_a, a.rho_slow)
for kappa in (a.kappa, *KAPPA_CONTEXT):
for seed in seeds or BEST_SEEDS:
r = run_one("grp_k", seed, kappa, acfg, steps=a.steps, windows=(a.window,))
_say(r, a.window); results.append(r)
for seed in seeds or BEST_SEEDS: # the paired kappa=0 control at the same acfg
r = run_one("grp_k0", seed, 0.0, acfg, steps=a.steps, windows=(a.window,))
_say(r, a.window); results.append(r)
_save(results, a.out)
base = [r for r in results if r["condition"] == "grp_k0"]
print()
for kappa in (a.kappa, *KAPPA_CONTEXT):
arm = [r for r in results if r["condition"] == "grp_k" and r["kappa"] == kappa]
p = paired(base, arm, a.window)
print(f"kappa={kappa:<5g} grp_k0/grp_k mean={p['mean']:.3f} "
f"median={p['median']:.3f} won={p['won']}/{p['n']} "
+ " ".join(f"{x:.2f}" for x in p["per_seed"]))
elif a.part == "duration":
acfg = AffectConfig() # Part 3 runs at kappa=0 in both arms; affect is untouched here
grid = ([tuple(int(x) for x in d.split("-")) for d in a.durations.split(",")]
if a.durations else DURATIONS)
for t_min, t_max in grid:
for stateless in (False, True):
for seed in seeds or DURATION_SEEDS:
r = run_one("grp_k0", seed, 0.0, acfg, steps=a.steps, windows=WINDOWS,
t_min=t_min, t_max=t_max, stateless=stateless)
_say(r, min(w for w in WINDOWS if w < t_min)); results.append(r)
_save(results, a.out)
for w in WINDOWS:
print(f"\nwindow={w}"); print(duration_table(results, w))
if __name__ == "__main__":
main()