"""Task 8, claim A1: does affect move a gate that gradient descent left inert? `results/frozen.md` measured the gate at `g = 0.500 +- 0.029` after 8000 steps, on every seed, with no saturation in either direction: `M <- (1-g) M~ + g M` is a fixed 50/50 blend and nothing is being decided about what to keep. The gate's pre-activation is `W_g[h||M] + b_g - kappa*a`, and the `-kappa*a` term is external forcing that never passes through the gradient. It is therefore the only available lever on this gate, which is what makes A1 worth running now: Part A does an affective signal move a mechanism gradient descent left inert? Part B does moving it do any measurable good? Part C is the good it does about *surprise*, or would any signal with the same marginal distribution and the wrong timing do as well? The A1 comparison is `grp_k` against `grp_k0`: identical architecture, identical 5602 parameters, differing only in kappa. `rp_only` (1442 params) and `grp_k0_nostate` are context, never the claim -- see results/frozen.md section 5. Part A's headline is *not* mean `g`. Arousal is non-negative, so `-kappa*a` lowers the mean by construction and a lower mean proves nothing. The contrast that carries the claim is post-switch against far-from-switch within one run, and alongside it the learned pre-activation `W_g[h||M] + b_g` measured on its own, which says whether gradient pushes back against the forcing or leaves it alone. """ from __future__ import annotations import argparse import json import math import statistics from pathlib import Path import numpy as np import torch from frozen import _build, _hidden, _train from regime import _metrics STEPS = 8000 SEEDS = tuple(range(16)) KAPPAS = (0.0, 1.0, 2.0, 4.0, 8.0, 16.0) WINDOW = 20 BPTT = 20 LR = 1e-3 # -- Part A: watching the gate --------------------------------------------------- class GateTrace: """`_train` callback recording the gate at every step, per entity, pooled per step. `g` is reconstructed rather than read out, because `Organism.forward` returns only `out(M)`. `org.grp(h, prev, a)` is asserted equal to the M the organism actually returned on every step of every run, which is what makes the reconstructed `h` -- and therefore the reconstructed `g` -- the organism's own and not a plausible lookalike. The reconstruction runs under `no_grad`; it is bit-identical anyway. `pre` is the learned part of the pre-activation, `W_g[h||M] + b_g`, with the `-kappa*a` forcing left out. Comparing it across kappa asks whether gradient compensates for the forcing or ignores it. """ def __init__(self, org): self.org = org self.g_mean, self.g_sq, self.open_, self.shut = [], [], [], [] self.pre_mean, self.pre_sq, self.a_gate = [], [], [] def __call__(self, t, obs, r, ctx, axes, prev, memory): org = self.org arousal = axes[1] with torch.no_grad(): h = _hidden(org, obs.attrs, r, axes, ctx) M = torch.stack([memory[i] for i in obs.ids]) assert torch.equal(org.grp(h, prev, arousal), M), "gate reconstruction diverged" pre = org.grp.gate(torch.cat([h, prev], -1)) g = torch.sigmoid(pre - org.grp.kappa * arousal) self.g_mean.append(float(g.mean())); self.g_sq.append(float((g ** 2).mean())) self.open_.append(float((g > 0.9).float().mean())) self.shut.append(float((g < 0.1).float().mean())) self.pre_mean.append(float(pre.mean())); self.pre_sq.append(float((pre ** 2).mean())) self.a_gate.append(arousal) def arrays(self) -> dict[str, np.ndarray]: return {k: np.asarray(v) for k, v in vars(self).items() if isinstance(v, list)} def index_sets(switched: list[bool], steps: int, window: int) -> dict[str, list[int]]: """The second half's post-switch and far-from-switch steps, as `regime._metrics` cuts them. `far` is `_metrics`'s own `steady_idx` -- no switch in the preceding `window` steps -- so the gate contrast and the error contrast are measured on the same steps. `post` is the union of the `window` steps each switch opens, i.e. exactly the steps `recovery[0..window-1]` averages over. """ half = steps // 2 sw = [i for i in range(half, steps - window) if switched[i]] post = sorted({j + k for j in sw for k in range(window)}) far = [i for i in range(half, steps) if not any(switched[max(0, i - window):i + 1])] return dict(switch=sw, post=post, far=far) def _pool(idx: list[int], mean: np.ndarray, sq: np.ndarray) -> tuple[float, float]: """Pooled mean and sd over entity-steps, from per-step means of x and x^2.""" if not idx: return float("nan"), float("nan") m = float(mean[idx].mean()) return m, math.sqrt(max(0.0, float(sq[idx].mean()) - m * m)) def gate_stats(tr: GateTrace, switched: list[bool], steps: int, window: int) -> dict: a = tr.arrays() idx = index_sets(switched, steps, window) allidx = list(range(steps // 2, steps)) out = {} mean = lambda k, ix: float(a[k][ix].mean()) if ix else float("nan") for tag, ix in (("all", allidx), ("post", idx["post"]), ("far", idx["far"])): g, gsd = _pool(ix, a["g_mean"], a["g_sq"]) pre, presd = _pool(ix, a["pre_mean"], a["pre_sq"]) out[tag] = dict(g=g, g_sd=gsd, frac_open=mean("open_", ix), frac_shut=mean("shut", ix), pre=pre, pre_sd=presd, a_gate=mean("a_gate", ix), n_steps=len(ix)) # the same excursion `recovery[k]` measures on the loss, measured on the gate: # lag k after a switch, averaged over the second half's switches sw = idx["switch"] for tag, key in (("g_by_lag", "g_mean"), ("pre_by_lag", "pre_mean"), ("a_by_lag", "a_gate"), ("shut_by_lag", "shut"), ("open_by_lag", "open_")): out[tag] = [float(a[key][[j + k for j in sw]].mean()) if sw else float("nan") for k in range(window)] out["delta_post_far"] = out["post"]["g"] - out["far"]["g"] out["a_delta_post_far"] = out["post"]["a_gate"] - out["far"]["a_gate"] out["a_gate_at_switch"] = float(a["a_gate"][idx["switch"]].mean()) if idx["switch"] else float("nan") return out # -- driver ---------------------------------------------------------------------- def run_a1(name: str, seed: int, kappa: float, steps: int = STEPS, window: int = WINDOW, bptt: int = BPTT, lr: float = LR, hidden: int = 32, omega: float = 10.0, stateless: bool = False, gate_arousal=None, label: str | None = None) -> dict: spec, wcfg, world, org = _build(name, seed, hidden, omega, kappa) if window >= wcfg.t_min: raise ValueError(f"window={window} must be < t_min={wcfg.t_min}") tr = GateTrace(org) if org.use_memory else None _, _, out = _train(spec, wcfg, world, org, steps, bptt, lr, stateless, gate_arousal=gate_arousal, on_step=tr) r = dict(condition=label or (name + ("_nostate" if stateless else "")), seed=seed, kappa=kappa, steps=steps, stateless=stateless, n_params=sum(p.numel() for p in org.parameters()), **_metrics(out["losses"], out["switched"], out["arousals"], window)) if tr is not None: r["gate"] = gate_stats(tr, out["switched"], steps, window) # the sequence the gate actually saw, not `arousals`: `_train` records affect # *after* the update, so arousals[t] is one step later than the gate's input. # Part C replays this, which is what lets the `real` arm reproduce the run. r["a_gate_seq"] = list(tr.a_gate) return r # -- Part C: the shuffled-affect control ----------------------------------------- def affect_variants(a_gate: list[float], seed: int, steps: int) -> dict: """The same arousal values the gate saw, delivered with the wrong timing. `shuffled` permutes within each half separately, so the marginal distribution the gate sees is matched exactly in the measured second half and not merely in expectation; within a half the permutation is uniform, so it carries no relation to switch timing. `shifted` rolls the whole trace, which additionally preserves arousal's own autocorrelation and only breaks its alignment with the switches -- the stricter control of the two. `const` pins the run's mean arousal, which is `-kappa*a` reduced to a pure bias shift with no timing information at all: if that alone reproduces the effect, the effect was never about affect. `real` replays the recorded trace unchanged. Because the run is deterministic given the seed and the replayed values are exactly the ones it produced, it must reproduce the unhooked run bit for bit -- which is how the replay machinery is checked rather than trusted. """ a = np.asarray(a_gate, dtype=float) rng = np.random.default_rng(10_000 + seed) half = steps // 2 shuf = a.copy() shuf[:half] = rng.permutation(shuf[:half]) shuf[half:] = rng.permutation(shuf[half:]) k = int(rng.integers(steps // 10, steps - steps // 10)) return dict(real=a, shuffled=shuf, shifted=np.roll(a, k), const=np.full(steps, a.mean())) # -- reporting ------------------------------------------------------------------- def by_condition(results: list[dict]) -> dict[str, list[dict]]: by: dict[str, list[dict]] = {} for r in results: by.setdefault(r["condition"], []).append(r) return {k: sorted(v, key=lambda r: r["seed"]) for k, v in by.items()} def gate_table(results: list[dict]) -> str: lines = [f"{'condition':<16}{'kappa':>7}{'g_all':>8}{'sd':>7}{'g_post':>8}{'g_far':>8}" f"{'delta':>8}{'open':>7}{'shut':>7}{'pre':>8}{'a_post':>8}{'a_far':>8}", "-" * 100] for name, rs in by_condition(results).items(): if "gate" not in rs[0]: continue m = lambda *k: statistics.fmean(_dig(r["gate"], k) for r in rs) lines.append( f"{name:<16}{rs[0]['kappa']:>7.0f}{m('all', 'g'):>8.3f}{m('all', 'g_sd'):>7.3f}" f"{m('post', 'g'):>8.3f}{m('far', 'g'):>8.3f}{m('delta_post_far'):>8.3f}" f"{m('all', 'frac_open'):>7.3f}{m('all', 'frac_shut'):>7.3f}{m('all', 'pre'):>8.3f}" f"{m('post', 'a_gate'):>8.3f}{m('far', 'a_gate'):>8.3f}") return "\n".join(lines) def _dig(d, keys): for k in keys: d = d[k] return d def error_table(results: list[dict]) -> str: idxs = [0, 2, 5, 10, 19] head = "".join(f"{'rec@' + str(i):>11}" for i in idxs) lines = [f"{'condition':<16}{'steady':>11}{'(sd)':>11}{head}", "-" * (16 + 22 + 11 * len(idxs))] for name, rs in by_condition(results).items(): st = [r["steady"] for r in rs] row = "".join(f"{statistics.fmean(r['recovery'][i] for r in rs):>11.3e}" for i in idxs) sd = statistics.stdev(st) if len(st) > 1 else 0.0 lines.append(f"{name:<16}{statistics.fmean(st):>11.3e}{sd:>11.3e}{row}") return "\n".join(lines) def paired(results: list[dict], ref: str) -> str: """Per-seed ratio ref/condition on `steady`. Eight seeds supports a direction, not a ratio.""" by = by_condition(results) if ref not in by: return f"(no {ref} in these results)" base = {r["seed"]: r["steady"] for r in by[ref]} lines = [f"paired {ref} / condition on steady, per seed", f"{'condition':<16}{'mean':>8}{'median':>8}{'won':>7} per-seed", "-" * 70] for name, rs in by.items(): if name == ref: continue ratios = [base[r["seed"]] / r["steady"] for r in rs if r["seed"] in base] per = " ".join(f"{x:.2f}" for x in ratios) lines.append(f"{name:<16}{statistics.fmean(ratios):>8.2f}{statistics.median(ratios):>8.2f}" f"{sum(x > 1 for x in ratios):>4}/{len(ratios):<2} {per}") return "\n".join(lines) def per_seed(results: list[dict], key: str = "steady") -> str: by = by_condition(results) seeds = sorted({r["seed"] for rs in by.values() for r in rs}) lines = [f"{'condition':<16}" + "".join(f"{'s' + str(s):>10}" for s in seeds), "-" * (16 + 10 * len(seeds))] for name, rs in by.items(): got = {r["seed"]: r[key] for r in rs} lines.append(f"{name:<16}" + "".join( f"{got[s]:>10.3e}" if s in got else f"{'--':>10}" for s in seeds)) return "\n".join(lines) def paired_recovery(results: list[dict], ref: str, lags=(0, 2, 5, 10, 19)) -> str: """Per-seed ratio ref/condition at matched lag. `recovery[k]` is contaminated: results/frozen.md section 1b showed it tracks the world's post-switch configuration transient, which a stateless frozen model reproduces at every lag. That transient is common to every condition, so a *difference between conditions at the same lag* is the part of it that is about the model. This is still a weaker observable than `steady`; it is reported, not built on. """ by = by_condition(results) if ref not in by: return f"(no {ref} in these results)" base = {r["seed"]: r["recovery"] for r in by[ref]} lines = [f"paired {ref} / condition at matched lag (mean ratio, seeds won)", f"{'condition':<16}" + "".join(f"{'@' + str(k):>14}" for k in lags), "-" * (16 + 14 * len(lags))] for name, rs in by.items(): if name == ref: continue cells = [] for k in lags: rat = [base[r["seed"]][k] / r["recovery"][k] for r in rs if r["seed"] in base] cells.append(f"{statistics.fmean(rat):>8.2f}{sum(x > 1 for x in rat):>4}/{len(rat)}") lines.append(f"{name:<16}" + "".join(f"{c:>14}" for c in cells)) return "\n".join(lines) def gate_consistency(results: list[dict]) -> str: """How many seeds show the post-switch gate below the far-from-switch gate. The mean is not the claim -- arousal is non-negative, so `-kappa*a` lowers mean g by construction. This asks whether the gate moves *when surprised*, on each seed. """ lines = [f"{'condition':<16}{'mean delta':>12}{'median':>10}{'seeds down':>12} per-seed", "-" * 76] for name, rs in by_condition(results).items(): if "gate" not in rs[0]: continue d = [r["gate"]["delta_post_far"] for r in rs] lines.append(f"{name:<16}{statistics.fmean(d):>12.4f}{statistics.median(d):>10.4f}" f"{sum(x < 0 for x in d):>8}/{len(d):<3} " + " ".join(f"{x:+.3f}" for x in d)) return "\n".join(lines) def _save(results, out): Path(out).parent.mkdir(parents=True, exist_ok=True) Path(out).write_text(json.dumps(results, indent=1)) def _line(r): g = r.get("gate") msg = f"{r['condition']:<16} seed={r['seed']:<2} steady={r['steady']:.3e} rec@0={r['recovery'][0]:.3e}" if g: msg += (f" g={g['all']['g']:.3f} post={g['post']['g']:.3f} far={g['far']['g']:.3f}" f" open={g['all']['frac_open']:.3f} shut={g['all']['frac_shut']:.3f}") return msg def main() -> None: ap = argparse.ArgumentParser() ap.add_argument("--stage", default="sweep", choices=["sweep", "controls", "shuffle", "report"]) ap.add_argument("--inputs", default="results/a1_sweep.json,results/a1_controls.json", help="report stage: json files to tabulate together") ap.add_argument("--ref", default="grp_k0", help="report stage: the paired baseline") ap.add_argument("--seeds", default=",".join(str(s) for s in SEEDS)) ap.add_argument("--kappas", default=",".join(str(k) for k in KAPPAS)) ap.add_argument("--kappa", type=float, default=4.0, help="Part C operating point") ap.add_argument("--steps", type=int, default=STEPS) ap.add_argument("--window", type=int, default=WINDOW) ap.add_argument("--out", default="results/a1_sweep.json") a = ap.parse_args() seeds = [int(s) for s in a.seeds.split(",")] results = [] if a.stage == "report": for f in a.inputs.split(","): results += json.loads(Path(f).read_text()) for title, fn in (("gate", gate_table), ("gate post-vs-far, per seed", gate_consistency), ("error", error_table), ("per-seed steady", per_seed), ("paired steady", lambda r: paired(r, a.ref)), ("paired recovery", lambda r: paired_recovery(r, a.ref))): print(f"\n## {title}\n"); print(fn(results)) return if a.stage == "sweep": for k in (float(x) for x in a.kappas.split(",")): for seed in seeds: r = run_a1("grp_k", seed, k, a.steps, a.window, label=f"grp_k{k:g}") print(_line(r), flush=True); results.append(r) elif a.stage == "controls": for seed in seeds: for name, sl in (("rp_only", False), ("grp_k0", True)): r = run_a1(name, seed, 0.0, a.steps, a.window, stateless=sl) print(_line(r), flush=True); results.append(r) else: # shuffle for seed in seeds: base = run_a1("grp_k", seed, a.kappa, a.steps, a.window, label="unhooked") for tag, seq in affect_variants(base["a_gate_seq"], seed, a.steps).items(): r = run_a1("grp_k", seed, a.kappa, a.steps, a.window, gate_arousal=lambda t, _a, s=seq: s[t], label=tag) if tag == "real": # the replay must reproduce the unhooked run exactly assert r["steady"] == base["steady"], "arousal replay is not self-consistent" assert r["recovery"] == base["recovery"], "arousal replay is not self-consistent" print(_line(r), flush=True); results.append(r) for r in results: r.pop("a_gate_seq", None) _save(results, a.out) print(); print(gate_table(results)); print(); print(error_table(results)) print(); print(paired(results, "grp_k0" if a.stage == "sweep" else "const")) if __name__ == "__main__": main()