feat: regime-switch runner for claims A1 and A2 (spec §8)

This commit is contained in:
chrnx committed 2026-09-02 07:44:52 -05:00
1 parent 8a59473025
commit ba1b036635
2 files changed
+148

No files matched your search

+130
View File
@@ -0,0 +1,130 @@
"""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 run(name: str, seed: int, steps: int, window: int = 20, bptt: int = 20,
lr: float = 1e-3, hidden: int = 32, kappa: float = 4.0) -> dict:
spec = dict(CONDITIONS[name])
if spec["kappa"] == KAPPA_FLAG:
spec["kappa"] = kappa
torch.manual_seed(seed)
wcfg = ParticleConfig(seed=seed, oracle=spec["oracle"])
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, 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)
# metrics on the second half only: the first half is training warm-up
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(
condition=name, seed=seed, steps=steps,
recovery=recovery, steady=steady, 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 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("--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)
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()
+18
View File
@@ -0,0 +1,18 @@
import pytest
from regime import CONDITIONS, run
@pytest.mark.parametrize("name", sorted(CONDITIONS))
def test_every_condition_runs(name):
res = run(name, seed=0, steps=300, window=5, bptt=10)
assert len(res["recovery"]) == 5
assert res["steady"] >= 0.0
assert res["n_switches"] >= 1
def test_rp_only_has_no_memory_and_zero_kappa():
assert CONDITIONS["rp_only"]["memory"] is False
assert CONDITIONS["grp_k0"]["kappa"] == 0.0
assert CONDITIONS["grp_flag"]["kappa"] == 0.0 and CONDITIONS["grp_flag"]["oracle"] == "change"
assert CONDITIONS["grp_regime"]["kappa"] == 0.0 and CONDITIONS["grp_regime"]["oracle"] == "regime"