Files
ailed-docs-rp/.sdd/task-6-brief.md
T
chrnx 5da4b8efa5 docs: design, plan, and the execution record
The thinking behind the organism, versioned alongside the three code repos rather than
living only on one machine.

- AILED_General_Specification.md, the authoritative design, and the implementation plan
  the code was built from
- AGENTS.md, the project-wide rules, including the two that were learned the hard way:
  this is not a performance benchmark, and a null recorded early beats a claim propped up
  later
- the nine superseded module specs, each carrying a banner naming what replaced it
- .sdd/, the execution ledger and every task brief and report: each ruling taken, what it
  would cost if wrong, every correction, and every number verified independently

The three code repos are siblings, each its own repository, and are git-ignored here so
nothing is nested.
2026-09-02 13:17:39 -05:00

8.6 KiB

Task 6: Regime experiment runner (spec §8)

Global constraints

  • Root ia-stuff/ is not a git repo; ailed/, experiments/, paper/ each are. Commit inside the repo you touched.
  • No hand-written backward passes. Autograd only (spec §1, §11).
  • \psi never carries gradient: it is built from loss.item() (spec §5).
  • Every oracle is opt-in and must leave the non-oracle trajectory byte-identical (spec §7).
  • \kappa = 0 must be a single flag that disables affect on the gate (spec §4).
  • Affect axes are read by name (valence, arousal), never by position, outside Organism.forward (spec §5).
  • Commit messages end with the attribution trailer of the session driving this plan:
    Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
    Claude-Session: https://claude.ai/code/session_01KAWnnPg2qvmLNySamE2k85
    
    Implementers use these two lines verbatim, not the attribution of their own subagent session — the commits belong to one plan run.

Files:

  • Create: experiments/regime.py
  • Test: experiments/tests/test_regime.py

Interfaces:

  • Consumes: Organism, detach_memory, Affect, AffectConfig, update from ailed; ParticleConfig, ParticleWorld, wrapped_diff from particles.

  • Produces:

    • CONDITIONS: dict[str, dict] with keys rp_only, grp_k0, grp_k, grp_flag, grp_regime, rp_flag, grp_k_noctx, grp_k_regimectx
    • 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 with keys recovery (list of window floats), steady (float), n_switches (int), arousal_at_switch (float), arousal_steady (float)
    • main() CLI: --conditions a,b,c --seeds 0,1,2 --steps 20000 --out results/a1.json
  • Step 1: Write the failing smoke test

experiments/tests/test_regime.py:

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"
  • Step 2: Run to verify failure

Run: cd experiments && uv run pytest tests/test_regime.py -q Expected: ModuleNotFoundError: regime.

  • Step 3: Implement

experiments/regime.py:

"""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)
    lines = [f"{'condition':<18}{'steady':>10}{'rec@0':>10}{'rec@2':>10}{'rec@5':>10}{'rec@10':>10}{'a@switch':>10}{'a@steady':>10}",
             "-" * 88]
    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)
        lines.append(f"{name:<18}{m('steady'):>10.5f}{m('recovery', 0):>10.5f}{m('recovery', 2):>10.5f}"
                     f"{m('recovery', 5):>10.5f}{m('recovery', 10):>10.5f}{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()
  • Step 4: Run to verify pass

Run: cd experiments && uv run pytest -q Expected: all pass (1 + 9 + 9).

  • Step 5: Commit
cd experiments && git add -A && git commit -q -m "feat: regime-switch runner for claims A1 and A2 (spec §8)

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KAWnnPg2qvmLNySamE2k85"