"""Task 9 Parts 1 and 3: when does per-entity memory have a job? Part 2 lives in `identify.py` -- it measures `T_id` and touches no organism. **Part 1 (`--part timing`)** is the last legitimate shot at A1. `results/a1.md` §1a measured arousal peaking about 12 steps *after* a switch and sitting *lower* at the switch step (0.061) than far from one (0.106). `rho_a` and `rho_slow` are the affect mechanism's own time constants and have never been set, so tuning them is tuning the mechanism rather than tuning a baseline to lose. This sweeps them, reports the arousal-vs-lag profile for each, and runs `grp_k` against `grp_k0` at the best-timed setting. Only `rho_slow` and `rho_a` can move arousal's timing. Read `affect.update`: a_target = tanh(max(0, loss - slow) / (slow + eps)); a <- a + rho_a (a_target - a) `fast` appears only in `v_target`, so `rho_fast` reaches arousal solely through the loss stream, via valence feeding the CPPN. `--part rho-fast` measures that it does not matter, rather than assuming it. Where the sweep raises `rho_slow` past the default `rho_fast`, `rho_fast` is raised with it (`_cfg`), because `AffectConfig` documents `rho_slow < rho_fast` and inverting the two would change what valence means as a side effect of a timing sweep. `AffectConfig`'s defaults are not touched: values are passed. **Part 3 (`--part duration`)** is the falsifiable test. At each regime duration it measures the **capacity-controlled** state gain `grp_k0_nostate / grp_k0`: identical architecture, identical 5602 parameters, differing only in whether memory is carried between steps. A `grp_k0` vs `rp_only` number is confounded 3.9x on parameter count (`results/frozen.md` §5) and is not this measurement. Shortening the regime changes the world's timescale, so the metrics have to be re-checked rather than re-used. `regime._metrics` is a pure function of the traces and the window, so each run stores its metrics at every window shorter than the duration's `t_min`; the tables then quote one window across all durations and `steady` means the same thing in every row. `n_switches` is reported with every number so a duration with too few switches in the measured half to average over is visible rather than implied. uv run python when_memory_works.py --part timing --out results/w_timing.json uv run python when_memory_works.py --part rho-fast --rho-a 1.0 --rho-slow 0.2 \ --out results/w_rhofast.json uv run python when_memory_works.py --part best --rho-a 1.0 --rho-slow 0.2 \ --out results/w_best.json uv run python when_memory_works.py --part duration --out results/w_duration_all.json """ from __future__ import annotations import argparse import json import statistics from pathlib import Path import numpy as np from ailed import AffectConfig from frozen import _build, _train from regime import _metrics STEPS = 8000 BPTT = 20 LR = 1e-3 HIDDEN = 32 OMEGA = 10.0 # Part 1: rho_a x rho_slow. rho_fast is carried up with rho_slow (see _cfg). RHO_A = (0.5, 1.0) RHO_SLOW = (0.02, 0.05, 0.1, 0.2, 0.4) TIMING_SEEDS = (0, 1, 2, 3) BEST_SEEDS = tuple(range(16)) KAPPA_PRIMARY = 4.0 # `regime.run`'s standing default; the criterion is read off this KAPPA_CONTEXT = (1.0, 16.0) # reported as context, never as the verdict # Part 3: the pre-registered grid, plus (4, 8) added before any duration run was made # because T_id turns out to be short and the predicted peak would otherwise sit on the # grid's edge. `frozen` draws one regime and never switches, as headroom.md section 5 did. # (2, 3) probes the theory's left arm, T_z < T_id. Part 2 measures T_id = 2 observations, # so no duration in the pre-registered grid reaches below it -- the shortest, 4-8, is # already twice T_id. It was added after Part 2 and before any duration run was read. DURATIONS = ((2, 3), (4, 8), (10, 20), (40, 80), (150, 300), (600, 1200), (STEPS * 2, STEPS * 2)) DURATION_SEEDS = tuple(range(16)) # window 1 is the only one a duration of 2-3 admits, and it is the column every duration # can therefore be compared on. Reported alongside, never instead of, the wider windows. WINDOWS = (1, 3, 9, 20) def _cfg(rho_a: float, rho_slow: float, rho_fast: float | None = None) -> AffectConfig: """An AffectConfig with the swept time constants, keeping rho_slow < rho_fast. `AffectConfig` says rho_slow "must be < rho_fast". The default pair is (0.02, 0.2), a factor of ten. Settings that raise rho_slow past 0.2 therefore raise rho_fast to keep a separation, so the sweep moves arousal's timing without silently inverting the two baselines valence is built from. """ fast = rho_fast if rho_fast is not None else max(0.2, 2.0 * rho_slow) return AffectConfig(rho_a=rho_a, rho_slow=rho_slow, rho_fast=fast) def label(acfg: AffectConfig) -> str: return f"a{acfg.rho_a:g}/s{acfg.rho_slow:g}/f{acfg.rho_fast:g}" # -- one run --------------------------------------------------------------------- def gate_arousal_seq(arousals: list[float]) -> np.ndarray: """The arousal the gate saw at each step, from the arousal `_train` records. `_train` appends `affect.arousal` *after* `update`, so `arousals[t]` is built from `losses[t]` and the gate at step t saw the previous value. Step 0 sees `Affect()`'s initial 0.0. `tests/test_when_memory_works.py` pins this against `a1.GateTrace`, which records the value the organism actually passed in. """ return np.concatenate([[0.0], np.asarray(arousals[:-1], dtype=float)]) def by_lag(x: np.ndarray, switched: list[bool], steps: int, window: int) -> list[float]: """`x` at lag k after a switch, averaged over the measured (second) half's switches. The same cut `regime._metrics` uses for `recovery`, so an arousal profile and an error profile are averaged over exactly the same switches. """ half = steps // 2 sw = [i for i in range(half, steps - window) if switched[i]] if not sw: return [float("nan")] * window return [float(x[[j + k for j in sw]].mean()) for k in range(window)] def far_level(x: np.ndarray, switched: list[bool], steps: int, window: int) -> float: """`x` on `_metrics`'s own `steady_idx` -- no switch in the preceding `window` steps.""" half = steps // 2 idx = [i for i in range(half, steps) if not any(switched[max(0, i - window):i + 1])] return float(x[idx].mean()) if idx else float("nan") def run_one(name: str, seed: int, kappa: float, acfg: AffectConfig, *, steps: int = STEPS, windows: tuple[int, ...] = (20,), t_min: int | None = None, t_max: int | None = None, stateless: bool = False, bptt: int = BPTT, lr: float = LR, hidden: int = HIDDEN, omega: float = OMEGA) -> dict: spec, wcfg, world, org = _build(name, seed, hidden, omega, kappa, t_min, t_max) _, _, tr = _train(spec, wcfg, world, org, steps, bptt, lr, stateless, acfg=acfg) a_gate = gate_arousal_seq(tr["arousals"]) out = dict(condition=name + ("_nostate" if stateless else ""), seed=seed, kappa=kappa, steps=steps, stateless=stateless, t_min=wcfg.t_min, t_max=wcfg.t_max, rho_a=acfg.rho_a, rho_slow=acfg.rho_slow, rho_fast=acfg.rho_fast, affect=label(acfg), n_params=sum(p.numel() for p in org.parameters()), metrics={}, arousal={}, loss_by_lag={}) losses = np.asarray(tr["losses"], dtype=float) for w in windows: if w >= wcfg.t_min: continue # a recovery window reaching the next switch blends two events out["metrics"][str(w)] = _metrics(tr["losses"], tr["switched"], tr["arousals"], w) out["arousal"][str(w)] = dict( by_lag=by_lag(a_gate, tr["switched"], steps, w), far=far_level(a_gate, tr["switched"], steps, w)) out["loss_by_lag"][str(w)] = by_lag(losses, tr["switched"], steps, w) return out # -- Part 1 ---------------------------------------------------------------------- def peak_lag(profile: list[float]) -> int: """Lag of the maximum, or -1 when there is nothing to peak. A frozen regime never switches, so `by_lag` and `recovery` are all-NaN there and there is no post-switch profile to take an argmax over. That is a real state of the world at the end of Part 3's sweep, not an error. """ a = np.asarray(profile, dtype=float) return -1 if np.all(np.isnan(a)) else int(np.nanargmax(a)) def timing_table(results: list[dict], window: int = 20) -> str: """Arousal at each lag after a switch, per affect setting, means over seeds.""" by: dict[str, list[dict]] = {} for r in results: by.setdefault(r["affect"], []).append(r) lags = list(range(0, min(window, 20), 2)) head = "".join(f"{'@' + str(k):>7}" for k in lags) lines = [f"{'rho_a/rho_slow/rho_fast':<24}{head}{'far':>7}{'peak':>7}{'loss pk':>9}", "-" * (24 + 7 * len(lags) + 23)] for name, rs in sorted(by.items()): prof = [statistics.fmean(r["arousal"][str(window)]["by_lag"][k] for r in rs) for k in range(window)] lprof = [statistics.fmean(r["loss_by_lag"][str(window)][k] for r in rs) for k in range(window)] far = statistics.fmean(r["arousal"][str(window)]["far"] for r in rs) lines.append(f"{name:<24}" + "".join(f"{prof[k]:>7.3f}" for k in lags) + f"{far:>7.3f}{peak_lag(prof):>7d}{peak_lag(lprof):>9d}") return "\n".join(lines) def paired(num: list[dict], den: list[dict], window: int = 20, key: str = "steady") -> dict: """`num/den` on `steady`, per seed. Both lists must cover the same seeds.""" a = {r["seed"]: r["metrics"][str(window)][key] for r in num} b = {r["seed"]: r["metrics"][str(window)][key] for r in den} seeds = sorted(set(a) & set(b)) ratios = [a[s] / b[s] for s in seeds] return dict(n=len(seeds), mean=statistics.fmean(ratios), median=statistics.median(ratios), won=sum(r > 1.0 for r in ratios), per_seed=ratios, seeds=seeds) # -- Part 3 ---------------------------------------------------------------------- def duration_table(results: list[dict], window: int) -> str: """Capacity-controlled state gain against regime duration.""" by: dict[tuple, dict[str, list[dict]]] = {} for r in results: by.setdefault((r["t_min"], r["t_max"]), {}).setdefault(r["condition"], []).append(r) lines = [f"{'duration':>14}{'window':>7}{'n_sw':>6}{'grp_k0':>11}{'nostate':>11}" f"{'gain':>7}{'median':>8}{'won':>7}", "-" * 71] for dur in sorted(by): arms = by[dur] if "grp_k0" not in arms or "grp_k0_nostate" not in arms: continue if any(str(window) not in r["metrics"] for r in arms["grp_k0"]): continue p = paired(arms["grp_k0_nostate"], arms["grp_k0"], window) m = lambda c: statistics.fmean(r["metrics"][str(window)]["steady"] for r in arms[c]) nsw = statistics.fmean(r["metrics"][str(window)]["n_switches"] for r in arms["grp_k0"]) tag = "frozen" if dur[0] >= STEPS else f"{dur[0]}-{dur[1]}" lines.append(f"{tag:>14}{window:>7}{nsw:>6.0f}{m('grp_k0'):>11.3e}" f"{m('grp_k0_nostate'):>11.3e}{p['mean']:>7.2f}{p['median']:>8.2f}" f"{str(p['won']) + '/' + str(p['n']):>7}") return "\n".join(lines) # -- driver ---------------------------------------------------------------------- def _save(results: list[dict], out: str) -> None: Path(out).parent.mkdir(parents=True, exist_ok=True) Path(out).write_text(json.dumps(results, indent=1)) def _say(r: dict, window: int) -> None: m = r["metrics"].get(str(window)) a = r["arousal"].get(str(window)) extra = "" if m is not None: extra = f" steady={m['steady']:.3e} n_sw={m['n_switches']}" if a is not None: extra += f" a_peak@{peak_lag(a['by_lag'])} a_far={a['far']:.3f}" print(f"{r['condition']:<16} k={r['kappa']:<5g} {r['affect']:<18} " f"dur={r['t_min']}-{r['t_max']:<6} seed={r['seed']:<3}{extra}", flush=True) def main() -> None: ap = argparse.ArgumentParser() ap.add_argument("--part", required=True, choices=["timing", "rho-fast", "best", "duration"]) ap.add_argument("--seeds", default=None) ap.add_argument("--steps", type=int, default=STEPS) ap.add_argument("--window", type=int, default=20) ap.add_argument("--rho-a", type=float, default=None, help="best/rho-fast: the setting to run") ap.add_argument("--rho-slow", type=float, default=None) ap.add_argument("--kappa", type=float, default=KAPPA_PRIMARY) ap.add_argument("--durations", default=None, help="duration: comma-separated t_min-t_max pairs, e.g. 10-20,40-80") ap.add_argument("--out", required=True) a = ap.parse_args() seeds = tuple(int(s) for s in a.seeds.split(",")) if a.seeds else None results: list[dict] = [] if a.part == "timing": for ra in RHO_A: for rs in RHO_SLOW: for seed in seeds or TIMING_SEEDS: r = run_one("grp_k0", seed, 0.0, _cfg(ra, rs), steps=a.steps, windows=(a.window,)) _say(r, a.window); results.append(r) _save(results, a.out) print(); print(timing_table(results, a.window)) elif a.part == "rho-fast": ra = a.rho_a if a.rho_a is not None else 0.5 rs = a.rho_slow if a.rho_slow is not None else 0.02 for rf in (0.1, 0.2, 0.5, 0.9): if rf <= rs: continue for seed in seeds or TIMING_SEEDS: r = run_one("grp_k0", seed, 0.0, _cfg(ra, rs, rf), steps=a.steps, windows=(a.window,)) _say(r, a.window); results.append(r) _save(results, a.out) print(); print(timing_table(results, a.window)) elif a.part == "best": acfg = _cfg(a.rho_a, a.rho_slow) for kappa in (a.kappa, *KAPPA_CONTEXT): for seed in seeds or BEST_SEEDS: r = run_one("grp_k", seed, kappa, acfg, steps=a.steps, windows=(a.window,)) _say(r, a.window); results.append(r) for seed in seeds or BEST_SEEDS: # the paired kappa=0 control at the same acfg r = run_one("grp_k0", seed, 0.0, acfg, steps=a.steps, windows=(a.window,)) _say(r, a.window); results.append(r) _save(results, a.out) base = [r for r in results if r["condition"] == "grp_k0"] print() for kappa in (a.kappa, *KAPPA_CONTEXT): arm = [r for r in results if r["condition"] == "grp_k" and r["kappa"] == kappa] p = paired(base, arm, a.window) print(f"kappa={kappa:<5g} grp_k0/grp_k mean={p['mean']:.3f} " f"median={p['median']:.3f} won={p['won']}/{p['n']} " + " ".join(f"{x:.2f}" for x in p["per_seed"])) elif a.part == "duration": acfg = AffectConfig() # Part 3 runs at kappa=0 in both arms; affect is untouched here grid = ([tuple(int(x) for x in d.split("-")) for d in a.durations.split(",")] if a.durations else DURATIONS) for t_min, t_max in grid: for stateless in (False, True): for seed in seeds or DURATION_SEEDS: r = run_one("grp_k0", seed, 0.0, acfg, steps=a.steps, windows=WINDOWS, t_min=t_min, t_max=t_max, stateless=stateless) _say(r, min(w for w in WINDOWS if w < t_min)); results.append(r) _save(results, a.out) for w in WINDOWS: print(f"\nwindow={w}"); print(duration_table(results, w)) if __name__ == "__main__": main()