Files
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.0 KiB
Raw Permalink Blame History

Task 6 report: experiments/regime.py

Fix round 1 (2026-09-02)

Two findings from review, both fixed:

Window/switch-spacing guard. run() now constructs wcfg = ParticleConfig(seed=seed, oracle=spec["oracle"]) before doing any other work and raises ValueError immediately if window >= wcfg.t_min ("a recovery window that reaches the next switch blends two events into one curve"). ParticleConfig construction is a pure, RNG-free dataclass instantiation, so moving it ahead of torch.manual_seed(seed) does not change anything about the run's randomness — verified below. Added test_window_too_large_raises.

_metrics() extracted and tested directly. Pulled the recovery/steady/n_switches/arousal block out of run() verbatim into _metrics(losses, switched, arousals, window) -> dict; run() now just calls _metrics(losses, switched, arousals, window) and merges it with condition/seed/steps. No metric definition changed. Added four direct tests against hand-built sequences:

  • test_metrics_recovery_is_mean_loss_k_steps_after_switch — losses[i] = i, one switch at index 12 (steps=20, half=10, window=3) → asserts recovery == [12.0, 13.0, 14.0] exactly.
  • test_metrics_ignores_switches_in_the_first_half — same base case, then perturbs index 3 (switched + a wildly different loss/arousal value) and asserts the result is byte-identical to the unperturbed baseline.
  • test_metrics_steady_excludes_window_steps_after_a_switch — a switch at index 15 with huge losses at 15-18; asserts steady == 1.0, i.e. those four post-switch steps are excluded rather than pulling the mean up.
  • test_metrics_no_switch_in_range_gives_nan_recovery — no switches at all: recovery is all nan, n_switches == 0, steady is still a normal finite mean.

Also added a one-line comment at the n_switches field in _metrics()'s return noting it counts switches in the measured second half only, per the request — key name unchanged.

Behavioural equivalence check, before and after the refactor:

$ uv run python -c "
from regime import run
r = run('grp_k0', seed=0, steps=2000, window=20, bptt=20)
print('steady=%.5f n_switches=%d' % (r['steady'], r['n_switches']))
"
steady=0.00025 n_switches=15

Ran this once against the pre-refactor code (matched the value given in the review) and again after both changes landed — identical output both times. Confirmed match.

Test output after the fixes:

$ uv run pytest -q
.........................                                                [100%]
25 passed in 1.65s

Commit: 7ac0081b2f516d4f2a139275a47417ee48d89010

fix: validate window<t_min and test _metrics directly (spec §8)

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BoDVQE6PnU9Mt9uikRy7pD

No concerns carried forward from this round — both findings were addressed as scoped, no changes to the training loop, conditions, defaults, or any metric's definition.

What I wrote

  • experiments/regime.py — the online regime-switch runner, exactly as specified in the brief:
    • CONDITIONS dict with the 8 named conditions (rp_only, grp_k0, grp_k, grp_flag, grp_regime, rp_flag, grp_k_noctx, grp_k_regimectx), KAPPA_FLAG sentinel resolved inside run().
    • _context(kind, affect, regime, n_regimes) building None (affect default), zeros(2), or a regime one-hot of width n_regimes.
    • run(name, seed, steps, window=20, bptt=20, lr=1e-3, hidden=32, kappa=4.0) -> dict — one continuous stream per (condition, seed): world.step() → build context → Organism.forward → MSE loss → accumulate in pending → affect = update(affect, loss.item(), acfg) (plain float, never the loss tensor) → every bptt steps, one backward()/opt.step(), then memory = detach_memory(memory) (detaches, doesn't clear). Metrics (recovery, steady, n_switches, arousal_at_switch, arousal_steady) are computed only over the second half of the run.
    • table() and main() (argparse CLI: --conditions --seeds --steps --window --kappa --out), writing JSON results under results/.
  • experiments/tests/test_regime.py — the two tests from the brief, verbatim: the 8-condition parametrized smoke test and the condition-table assertions.

One real bug I found and fixed

The brief's table() hard-codes recovery[5] and recovery[10] columns. That's fine for the default window=20, but main() also exposes --window on the CLI, and any run with window < 11 (e.g. a quick manual smoke run with --window 5, which is what I used to exercise the CLI end-to-end) raises IndexError: list index out of range inside table() — after the results JSON has already been written successfully, so the crash only kills the human-readable summary line, not the run itself. I fixed table() to derive its recovery columns from len(results[0]["recovery"]) (idxs = [i for i in (0, 2, 5, 10) if i < win]) so it degrades gracefully instead of crashing; with the default window=20 the output is byte-identical to what the brief's version would have produced. Verified both paths manually:

$ uv run python regime.py --conditions rp_only,grp_k --seeds 0 --steps 200 --window 5 --out results/smoke.json
rp_only            seed=0 steady=0.00439 rec@0=0.00427
grp_k              seed=0 steady=0.00644 rec@0=0.00570

condition             steady     rec@0     rec@2  a@switch  a@steady
--------------------------------------------------------------------
rp_only              0.00439   0.00427   0.00429     0.000     0.000
grp_k                0.00644   0.00570   0.00576     0.000     0.000

$ uv run python regime.py --conditions rp_only --seeds 0 --steps 200 --out results/smoke2.json
rp_only            seed=0 steady=0.00422 rec@0=0.00427

condition             steady     rec@0     rec@2     rec@5    rec@10  a@switch  a@steady
----------------------------------------------------------------------------------------
rp_only              0.00422   0.00427   0.00429   0.00434   0.00443     0.000     0.000

Both smoke JSON files were deleted after inspection (results/*.json is gitignored anyway, and git status was clean of them before the commit).

Something ambiguous in the brief

test_particles.py (already committed by task 5) has 10 tests, not 9 — the brief's "Expected: all pass (1 + 9 + 9)" undercounts it by one. Not a blocker, just noting the arithmetic is off; the actual full-suite count is 20 (1 smoke + 10 particles + 9 regime), all passing.

Everything else in the brief — the exact run() signature, the metric definitions (recovery measured only on the second half, steady defined as "no switch in the last window steps including this one"), the context_dim wiring per condition, the truncated-BPTT/detach-not-clear memory contract, and \psi being built from loss.item() — matched the installed ailed and particles signatures exactly and needed no other changes.

Test output

$ uv run pytest -q
....................                                                     [100%]
20 passed in 1.65s

Just the new file's tests:

$ uv run pytest tests/test_regime.py -q
.........                                                                [100%]
9 passed in 1.57s

The regime-only smoke suite (8 parametrized conditions at steps=300 each, plus the one static assertion test) took about 1.6s; the full 20-test suite takes about 1.7–3.3s depending on machine load — well within interactive range, no long-running training was needed to validate correctness.

Commit

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

Trailer used is this session's own attribution (per the controller's instruction to use whatever trailer the session provides, not the brief's session trailer verbatim):

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BoDVQE6PnU9Mt9uikRy7pD

Working tree is clean after the commit; results/ remains empty and untracked.