Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01KAWnnPg2qvmLNySamE2k85
142 lines
6.2 KiB
Python
142 lines
6.2 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) -> 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, 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("--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()
|