Files
chrnx 17c13af1db exp: headroom check for the regime setup
Requirement 2 holds (grp_k0 beats rp_only 2.9x on steady, all seeds).
Requirements 1 and 3 fail, both for setup reasons rather than A1 reasons.

Measured the domain's information ceilings by least squares rather than tuning
against them. The regime oracle's own ceiling is 1.18e-05, which sits on
requirement 1's tolerance boundary before any training loss; the trained models
land 3-4x above even that. Ruled out omega (5/10/20), noise (16x lower floor
moves nothing), sigma, training length (40k), and the missing type-pair edge
channel. Every condition converges to ~1.5e-05 regardless of the information it
is given: the error is optimiser tracking lag against a target that switches
every 40-80 steps, not missing information. An oracle cannot help a model that
is not yet using what it has.

rp_flag's 4x rec@0 spike is an untrained input spike, not a leak: the change
flag column gets gradient on ~1.5% of steps and so perturbs every message at
the exact step rec@0 measures. Zero-initialising the oracle columns of W_feat
removes it, makes rp_flag a valid null, and makes grp_regime exactly equal to
grp_k0. Recommended in the report, not adopted here - it moves every oracle
condition off what Task 6 was reviewed under.

Only source change: omega is now a run() parameter, default 10.0 unchanged, so
prior runs reproduce exactly. No default in particles.py or regime.py changed;
../ailed untouched.
2026-09-02 08:12:32 -05:00

143 lines
6.3 KiB
Python

"""Claims A1 and A2 on relational particles. Spec §8.
One continuous online stream per (condition, seed). Truncated BPTT every `bptt`
steps. Affect is updated from loss.item() so it never carries gradient.
"""
from __future__ import annotations
import argparse
import json
import statistics
from pathlib import Path
import torch
from ailed import Affect, AffectConfig, Organism, detach_memory, update
from particles import ParticleConfig, ParticleWorld, wrapped_diff
KAPPA_FLAG = "kappa" # resolved from run(kappa=...) when the value is this sentinel
CONDITIONS: dict[str, dict] = {
# A1
"rp_only": dict(memory=False, kappa=0.0, oracle="none", ctx="affect"),
"grp_k0": dict(memory=True, kappa=0.0, oracle="none", ctx="affect"),
"grp_k": dict(memory=True, kappa=KAPPA_FLAG, oracle="none", ctx="affect"),
"grp_flag": dict(memory=True, kappa=0.0, oracle="change", ctx="affect"),
"grp_regime": dict(memory=True, kappa=0.0, oracle="regime", ctx="affect"),
# control that cannot show an effect
"rp_flag": dict(memory=False, kappa=0.0, oracle="change", ctx="affect"),
# A2 (on the affect-gated model)
"grp_k_noctx": dict(memory=True, kappa=KAPPA_FLAG, oracle="none", ctx="zeros"),
"grp_k_regimectx": dict(memory=True, kappa=KAPPA_FLAG, oracle="none", ctx="regime"),
}
def _context(kind: str, affect: Affect, regime: int, n_regimes: int) -> torch.Tensor | None:
if kind == "affect":
return None # Organism defaults to (valence, arousal)
if kind == "zeros":
return torch.zeros(2)
if kind == "regime":
c = torch.zeros(n_regimes); c[regime] = 1.0
return c
raise ValueError(kind)
def _metrics(losses: list[float], switched: list[bool], arousals: list[float], window: int) -> dict:
# metrics on the second half only: the first half is training warm-up
steps = len(losses)
half = steps // 2
switch_idx = [i for i in range(half, steps - window) if switched[i]]
recovery = [statistics.fmean(losses[i + k] for i in switch_idx) for k in range(window)] if switch_idx else [float("nan")] * window
steady_idx = [i for i in range(half, steps) if not any(switched[max(0, i - window):i + 1])]
steady = statistics.fmean(losses[i] for i in steady_idx) if steady_idx else float("nan")
return dict(
recovery=recovery, steady=steady,
# counts switches in the measured second half only, not the whole run
n_switches=len(switch_idx),
arousal_at_switch=statistics.fmean(arousals[i] for i in switch_idx) if switch_idx else float("nan"),
arousal_steady=statistics.fmean(arousals[i] for i in steady_idx) if steady_idx else float("nan"),
)
def run(name: str, seed: int, steps: int, window: int = 20, bptt: int = 20,
lr: float = 1e-3, hidden: int = 32, kappa: float = 4.0, omega: float = 10.0) -> dict:
spec = dict(CONDITIONS[name])
if spec["kappa"] == KAPPA_FLAG:
spec["kappa"] = kappa
wcfg = ParticleConfig(seed=seed, oracle=spec["oracle"])
if window >= wcfg.t_min:
raise ValueError(
f"window={window} must be < t_min={wcfg.t_min}: a recovery window that reaches "
"the next switch blends two events into one curve"
)
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"])
opt = torch.optim.Adam(org.parameters(), lr=lr)
acfg = AffectConfig()
affect = Affect()
memory: dict[int, torch.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, 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)
return dict(condition=name, seed=seed, steps=steps, **_metrics(losses, switched, arousals, window))
def table(results: list[dict]) -> str:
by = {}
for r in results:
by.setdefault(r["condition"], []).append(r)
win = len(results[0]["recovery"]) if results else 0
idxs = [i for i in (0, 2, 5, 10) if i < win] # skip columns the window is too short to have
header = "".join(f"{'rec@' + str(i):>10}" for i in idxs)
lines = [f"{'condition':<18}{'steady':>10}{header}{'a@switch':>10}{'a@steady':>10}",
"-" * (18 + 10 + 10 * len(idxs) + 20)]
for name, rs in by.items():
m = lambda key, idx=None: statistics.fmean((r[key][idx] if idx is not None else r[key]) for r in rs)
row = "".join(f"{m('recovery', i):>10.5f}" for i in idxs)
lines.append(f"{name:<18}{m('steady'):>10.5f}{row}{m('arousal_at_switch'):>10.3f}{m('arousal_steady'):>10.3f}")
return "\n".join(lines)
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--conditions", default=",".join(CONDITIONS))
ap.add_argument("--seeds", default="0,1,2")
ap.add_argument("--steps", type=int, default=20000)
ap.add_argument("--window", type=int, default=20)
ap.add_argument("--kappa", type=float, default=4.0)
ap.add_argument("--omega", type=float, default=10.0)
ap.add_argument("--out", default="results/run.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(name, seed, a.steps, window=a.window, kappa=a.kappa, omega=a.omega)
print(f"{name:<18} seed={seed} steady={r['steady']:.5f} rec@0={r['recovery'][0]:.5f}", 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))
print(); print(table(results))
if __name__ == "__main__":
main()