exp: A1 -- affect moves the gate, and moving it does not help

This commit is contained in:
chrnx committed 2026-09-02 09:48:40 -05:00
1 parent f8acee6835
commit aa8ad2abfc
4 files changed
+866 -5

No files matched your search

+375
View File
@@ -0,0 +1,375 @@
"""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()
+29 -5
View File
@@ -54,35 +54,59 @@ def _build(name: str, seed: int, hidden: int, omega: float, kappa: float):
def _train(spec: dict, wcfg: ParticleConfig, world: ParticleWorld, org: Organism,
steps: int, bptt: int, lr: float, stateless: bool = False):
"""A verbatim copy of `regime.run`'s training loop (`stateless` aside).
steps: int, bptt: int, lr: float, stateless: bool = False,
gate_arousal=None, on_step=None):
"""A verbatim copy of `regime.run`'s training loop (the keyword arguments aside).
Copied rather than reused because `regime.run` returns metrics and drops the
organism and the world, and this task has to keep stepping the same world with
the same organism after training ends. `tests/test_frozen.py` pins the copy: it
asserts this loop reproduces `regime.run`'s metrics bit-identically.
asserts this loop reproduces `regime.run`'s metrics bit-identically. Every
keyword below defaults to off, and with all three off the loop body is the same
sequence of calls it always was.
`stateless=True` hands the organism an empty memory dict every step, so M_prev is
always zero. The GRP keeps every parameter it had and loses only the carrying of
state -- the control that separates "memory helps" from "the GRP's extra 4160
parameters help". It is a call into the public API, not a change to the library.
`gate_arousal(t, affect) -> float` replaces the arousal the *gate* sees while the
CPPN keeps the organism's own live affect: the context is then passed explicitly,
built exactly as `Organism.forward` would have built it from the real affect. This
is Task 8's shuffled-affect control -- it has to move `-kappa*a` alone, because
shuffling the affect the CPPN reads would change a second input as well.
`on_step(t, obs, r, ctx, axes, prev, memory)` is a read-only callback fired after
the forward pass, for measuring the gate. `prev` is the M_prev the organism was
handed, captured before `memory` is rebound.
"""
opt = torch.optim.Adam(org.parameters(), lr=lr)
acfg = AffectConfig()
affect = Affect()
memory: dict[int, Tensor] = {}
zero = torch.zeros(org.hidden_dim)
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,
{} if stateless else memory, context=ctx)
r = wrapped_diff(obs.coords)
axes = affect.axes
if gate_arousal is not None:
if ctx is None: # what Organism.forward builds from the real affect
ctx = torch.tensor(affect.axes, dtype=obs.attrs.dtype)
axes = (affect.valence, float(gate_arousal(t, affect)))
held = {} if stateless else memory
prev = (torch.stack([held.get(i, zero) for i in obs.ids])
if on_step is not None and org.use_memory else None)
pred, memory = org(obs.attrs, r, obs.ids, axes, held, 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 on_step is not None:
on_step(t, obs, r, ctx, axes, prev, memory)
if len(pending) == bptt:
opt.zero_grad()
torch.stack(pending).mean().backward()
+352
View File
@@ -0,0 +1,352 @@
# Claim A1: does affect move a gate that gradient descent left inert, and does moving it help?
Task 8. `results/frozen.md` §3 measured the GRP's gate at `g = 0.500 ± 0.029` after
8000 steps, on every seed, never above 0.9, never below 0.1: `M ← (1−g)M̃ + gM` had
degenerated to a fixed 50/50 blend with no input dependence. The gate's
pre-activation is `W_g[h‖M] + b_g − κa`, and the `−κa` term never passes through the
gradient, which makes it the only available lever on that gate. This file measures
what pulling it does.
**Verdict: affect moves the gate, decisively and by a visible mechanism. Moving it
buys nothing, and the one effect that is specific to real surprise timing is a
harm.** Steady error is flat across `κ ∈ {0,1,2,4,8,16}` to within 1.2%, on a coin
flip of seeds. Two steps after a switch, real affect is *worse* than `κ=0` on 14–16
of 16 seeds, monotonically in `κ`, and worse than a shuffled-affect control that
delivers the same gate-value distribution with the wrong timing on 15/16.
Environment: `experiments/`, `ailed/` unmodified, no default in `particles.py` or
`regime.py` changed. 16 seeds (0–15), 8000 training steps, `lr=1e-3`, `bptt=20`,
`hidden=32`, `omega=10`, `window=20`. Noise floor `noise² = 4.0e-06`. All metrics are
`regime._metrics` on the second half of training, so they are directly comparable
with the tables in `headroom.md` and `frozen.md`. 288 runs.
```
uv run python a1.py --stage sweep --out results/a1_sweep.json
uv run python a1.py --stage controls --out results/a1_controls.json
uv run python a1.py --stage shuffle --kappa 4 --out results/a1_shuffle_k4.json
uv run python a1.py --stage shuffle --kappa 16 --out results/a1_shuffle_k16.json
uv run python a1.py --stage report --inputs results/a1_sweep.json,results/a1_controls.json
```
## 0. What is measured, and how it is checked
`Organism.forward` returns only `out(M)`, so `g` has to be reconstructed. `a1.GateTrace`
rebuilds `h` from the public `org.rp` exactly as `core.py` builds it, then asserts
`org.grp(h, M_prev, a)` equals the `M` the organism actually returned — **every step
of every run — 272 gated runs, 2.18M assertions, none of which fired**. That is what makes the reported
`g` the organism's own gate rather than a plausible lookalike;
`test_gate_reconstruction_is_the_organisms_own_gate` shows the assert can fail, by
perturbing the reconstructed `h` by 1e-6.
The A1 comparison is **`grp_k` against `grp_k0`**: identical architecture, identical
5602 parameters, one seed, differing only in `κ`. `rp_only` (1442 parameters) and
`grp_k0_nostate` are context and never the claim — `frozen.md` §5. For the record, at
16 seeds in the *trained* phase the same decomposition reads:
```
mean median seeds won
capacity rp_only / nostate 3.04x 2.71x 16/16
state nostate / grp_k0 1.19x 1.11x 11/16
```
which is `frozen.md`'s trained-phase decomposition (3.06x on 8/8, 1.25x on 4/8) at
twice the seeds. The state row is firmer than it was at 8 seeds and still modest:
five seeds go the other way and the median is 1.11x.
`grp_k` at `κ=0` is `grp_k0` by construction, and `test_run_a1_reports_the_same_metrics_regime_run_does`
asserts the two produce bit-identical metrics, so the sweep's `κ=0` row is the
baseline rather than a re-implementation of it.
## 1. Part A — the gate moves, and the learned part does not
Second half of training, pooled over all entity-steps, means over 16 seeds. `g_post`
is the union of the 20 steps each switch opens — exactly the steps `recovery[0..19]`
averages over — and `g_far` is `_metrics`'s own `steady_idx`, so the gate contrast and
the error contrast are measured on the same steps. `pre` is the learned part of the
pre-activation, `W_g[h‖M] + b_g`, with the forcing left out.
```
kappa g_all sd g_post g_far delta frac>0.9 frac<0.1 pre a_post a_far
--------------------------------------------------------------------------------------
0 0.501 0.025 0.501 0.500 +0.000 0.000 0.000 0.002 0.229 0.109
1 0.465 0.068 0.446 0.474 -0.029 0.000 0.000 0.000 0.227 0.106
2 0.436 0.114 0.402 0.453 -0.052 0.000 0.000 0.000 0.228 0.106
4 0.400 0.164 0.349 0.427 -0.078 0.000 0.124 0.002 0.229 0.106
8 0.368 0.197 0.307 0.400 -0.094 0.000 0.206 0.002 0.231 0.107
16 0.343 0.213 0.277 0.378 -0.100 0.000 0.264 -0.002 0.232 0.108
```
Read down the columns:
- **`κ=1` is enough.** Mean `g` moves from 0.501 to 0.465 and its sd nearly triples,
0.025 → 0.068. The mean shift is the trivial part; the sd is not, and it is what
says the gate has acquired input dependence it did not have.
- **Saturation begins between `κ=2` and `κ=4`.** No entity-step has `g<0.1` at
`κ≤2`; 12.4% do at `κ=4`, 20.6% at `κ=8`, 26.4% at `κ=16`. The gate never
saturates the other way at any `κ`, which it cannot: `a ≥ 0`, so the forcing is
one-sided.
- **The forcing signal is real and switch-locked.** Mean arousal is 0.229 in the
post-switch window against 0.106 far from one, a factor of 2.2, at every `κ`.
- **Gradient neither compensates nor participates.** `pre` is 0.000 ± 0.002 at every
`κ`, the same value `frozen.md` §3 measured at `κ=0`. The learned part of this gate
is inert whether or not it is being forced: `−κa` is not modulating a learned
gating policy, it *is* the entire gate.
Per-seed, the post-vs-far contrast is unanimous rather than an average:
```
kappa mean delta median seeds with post < far
--------------------------------------------------
0 +0.0000 +0.0001 4/16
1 -0.0288 -0.0296 16/16
2 -0.0518 -0.0528 16/16
4 -0.0778 -0.0769 16/16
8 -0.0936 -0.0942 16/16
16 -0.1004 -0.0970 16/16
```
The `κ=0` row is the control on this contrast: with the forcing off, the gate is as
likely to sit higher after a switch as lower (4/16) and the effect size is 0.0000.
### 1a. The excursion, lag by lag
The same quantity `recovery[k]` measures on the loss, measured on the gate: lag `k`
after a switch, averaged over the second half's switches, means over 16 seeds.
```
kappa @0 @2 @4 @6 @8 @10 @12 @14 @16 @18 far
-------------------------------------------------------------------------
0 0.500 0.500 0.500 0.500 0.500 0.501 0.501 0.501 0.501 0.501 0.500
1 0.486 0.457 0.448 0.445 0.440 0.436 0.434 0.435 0.440 0.447 0.474
2 0.473 0.419 0.405 0.400 0.392 0.386 0.383 0.384 0.391 0.404 0.453
4 0.456 0.370 0.355 0.347 0.336 0.328 0.323 0.325 0.334 0.349 0.427
8 0.439 0.330 0.319 0.307 0.293 0.283 0.280 0.278 0.286 0.302 0.400
16 0.421 0.302 0.292 0.278 0.260 0.252 0.251 0.251 0.256 0.269 0.378
arousal (identical at every kappa, so the forcing is an input, not a feedback loop)
0.061 0.184 0.223 0.236 0.253 0.267 0.279 0.272 0.249 0.220 0.106
```
The gate is an exact mirror of the arousal transient, which is what it must be given
that `pre` is flat. Two details worth carrying into the paper:
- **Arousal is lowest at the switch step itself** (0.061, *below* its far-from-switch
level of 0.106) and peaks 12 steps later. `Affect.update` compares the loss to a
slow baseline, so the surprise register lags the event by several steps. The gate
therefore opens after the error has already begun to rise, not at the moment the
world changes.
- **The arousal curve is the same at every `κ`** to within 0.01. Forcing the gate
does not change the error stream enough to change the affect built from it, so
there is no feedback loop to worry about here.
## 2. Part B — moving it buys nothing
`steady` and `recovery[k]` from `regime._metrics`, means over 16 seeds. `rp_only` and
`grp_k0_nostate` are the context rows.
```
condition steady (sd) rec@0 rec@2 rec@5 rec@10 rec@19
---------------------------------------------------------------------------------------------
grp_k0 2.399e-05 1.163e-05 3.177e-05 3.166e-05 3.477e-05 3.952e-05 3.196e-05
grp_k1 2.425e-05 1.223e-05 3.224e-05 3.323e-05 3.629e-05 4.050e-05 3.221e-05
grp_k2 2.409e-05 1.162e-05 3.224e-05 3.382e-05 3.640e-05 4.043e-05 3.186e-05
grp_k4 2.413e-05 1.163e-05 3.209e-05 3.453e-05 3.644e-05 4.065e-05 3.218e-05
grp_k8 2.415e-05 1.160e-05 3.185e-05 3.542e-05 3.619e-05 4.075e-05 3.185e-05
grp_k16 2.428e-05 1.158e-05 3.218e-05 3.605e-05 3.686e-05 4.061e-05 3.179e-05
rp_only 7.708e-05 3.668e-05 8.322e-05 8.702e-05 9.174e-05 9.437e-05 8.391e-05
grp_k0_nostate 2.791e-05 1.213e-05 3.539e-05 3.689e-05 3.947e-05 4.515e-05 3.707e-05
```
The across-seed sd (1.16e-05) is 40 times the largest difference between any two
`κ` rows, so the paired comparison is the only one worth reading.
```
paired grp_k0 / grp_k on steady
kappa mean median won per-seed
---------------------------------------------------------------------------
1 0.99 1.00 6/16 1.03 1.00 1.00 1.00 1.01 1.01 0.99 1.01 0.99 0.99 0.96 1.00 0.99 0.98 0.96 1.02
2 1.00 1.00 9/16 1.03 1.00 1.00 1.00 1.01 1.00 1.00 1.01 0.98 1.01 1.01 0.99 1.00 0.98 0.92 1.02
4 1.00 1.00 8/16 1.05 1.01 0.99 1.00 1.00 1.00 0.93 1.02 0.98 1.02 1.02 0.99 1.00 0.94 0.94 1.05
8 1.00 1.00 7/16 1.04 1.01 0.99 0.99 1.03 0.99 0.94 1.01 0.97 1.02 1.02 0.99 1.00 0.94 0.92 1.08
16 0.99 1.00 9/16 1.09 1.01 0.99 0.98 1.02 1.01 0.92 1.01 0.97 1.01 1.03 0.98 1.00 0.92 0.88 1.01
```
**A coin flip at every `κ`**: median 1.00, between 6 and 9 seeds out of 16, no trend
in `κ`. A gate driven from an inert 0.500 to a switch-locked excursion between 0.42
and 0.25 changes steady error by nothing that 16 seeds can see.
### 2a. The one systematic effect, and it is a harm
`frozen.md` §1b showed `recovery[k]` tracks the world's post-switch configuration
transient — a stateless frozen model reproduces its shape at every lag — so the raw
curve is not an adaptation measurement. That transient is common to every condition
here, which is what makes a *difference between conditions at matched lag*
interpretable where the curve itself is not.
```
paired grp_k0 / grp_k at matched lag (mean ratio, seeds won; <1 means kappa is worse)
kappa @0 @2 @5 @10 @19
---------------------------------------------------------------------------
1 0.99 7/16 0.96 2/16 0.97 2/16 0.98 3/16 1.00 7/16
2 0.99 5/16 0.94 0/16 0.96 3/16 0.98 3/16 1.00 12/16
4 0.99 6/16 0.92 1/16 0.96 4/16 0.97 3/16 0.99 8/16
8 1.00 7/16 0.91 0/16 0.96 5/16 0.97 2/16 1.00 10/16
16 0.99 7/16 0.89 0/16 0.95 4/16 0.97 3/16 1.00 10/16
```
At lag 2 the forced gate is worse on 14–16 seeds out of 16, monotonically in `κ`,
from 4% at `κ=1` to 11% at `κ=16`. The effect is present but smaller at lags 5 and
10, absent at lag 0 (arousal has not risen yet) and gone by lag 19 (it has decayed).
It is the only sign-definite, `κ`-monotone effect anywhere in this file.
The mechanism is visible in §1a. Overwriting `M` with a fresh candidate discards the
temporal averaging the blend was providing, and `frozen.md` §1b already established
that the post-switch excess belongs to the world's configuration transient, which no
amount of state can shorten. There is nothing for a freshly written memory to gain
here, and the smoothing is what it costs.
## 3. Part C — the shuffled-affect control
If a forced gate had helped, the obvious alternative reading is that `−κa` acts as a
generic regulariser or bias shift rather than as an affective signal. Three controls,
all replaying the arousal sequence the gate itself saw, all at the same seed with
everything else unchanged:
| arm | what it delivers |
|---|---|
| `real` | the live signal — replayed from the recorded trace, so this arm must reproduce the unhooked run bit for bit |
| `shuffled` | the same values permuted within each half, so the marginal is matched *exactly* in the measured window, not merely in expectation |
| `shifted` | the whole trace circularly rolled — also preserves arousal's own autocorrelation, and breaks only its alignment with the switches |
| `const` | the run's mean arousal, i.e. `−κa` reduced to a pure bias shift with no timing information at all |
Only the arousal reaching the **gate** is replaced. The CPPN keeps the organism's own
live `(valence, arousal)`, passed explicitly and built exactly as `Organism.forward`
would have built it, so `−κa` is the single thing that moves.
`test_replaying_the_runs_own_arousal_reproduces_it_exactly` pins this, the driver
asserts it again on all 16 seeds at run time, and the `real` arm is separately
verified identical to the sweep's `grp_k4` / `grp_k16` rows on `steady` and on all 20
recovery lags. The replay machinery is checked, not trusted.
### 3a. The controls do what they are supposed to do
`κ=4`, means over 16 seeds:
```
arm g_all sd g_post g_far delta frac<0.1 a_post a_far
------------------------------------------------------------------------
real 0.400 0.164 0.349 0.427 -0.078 0.124 0.229 0.106
shuffled 0.400 0.165 0.399 0.400 -0.001 0.124 0.150 0.147
shifted 0.408 0.158 0.411 0.407 +0.004 0.105 0.130 0.135
const 0.369 0.024 0.369 0.369 +0.000 0.000 0.136 0.136
```
`shuffled` matches `real`'s gate distribution to three decimals — same mean, same sd,
same saturated fraction — while its post-vs-far contrast collapses from −0.078 to
−0.001. The values are preserved and the timing is destroyed, which is exactly what
the control has to do. Lag by lag, `κ=4`:
```
arm @0 @2 @4 @6 @8 @10 @12 @14 @16 @18 far
real 0.456 0.370 0.355 0.347 0.336 0.328 0.323 0.325 0.334 0.349 0.427
shuffled 0.414 0.405 0.400 0.398 0.407 0.402 0.405 0.398 0.394 0.395 0.400
shifted 0.409 0.410 0.413 0.415 0.416 0.413 0.408 0.409 0.409 0.410 0.407
const 0.369 0.369 0.369 0.369 0.369 0.369 0.369 0.369 0.369 0.369 0.369
```
Note `const` at `κ=16`: `g = 0.103 ± 0.010` with 47.9% of entity-steps below 0.1. A
gate pinned near zero is not an open gate, it is a different dead gate, and this is
what a constant-arousal bias shift degenerates into at large `κ`.
### 3b. The result
`κ=4`, `steady`, means over 16 seeds, with the paired comparison against `shuffled`:
```
arm steady rec@0 rec@2 rec@5 rec@10 rec@19
---------------------------------------------------------------------------
real 2.413e-05 3.209e-05 3.453e-05 3.644e-05 4.065e-05 3.218e-05
shuffled 2.378e-05 3.191e-05 3.243e-05 3.591e-05 4.036e-05 3.216e-05
shifted 2.438e-05 3.222e-05 3.280e-05 3.619e-05 4.062e-05 3.261e-05
const 2.391e-05 3.223e-05 3.286e-05 3.585e-05 4.009e-05 3.170e-05
(grp_k0 2.399e-05 3.177e-05 3.166e-05 3.477e-05 3.952e-05 3.196e-05)
paired shuffled / arm, per seed
steady @0 @2 @5 @10 @19
-------------------------------------------------------------------------------------
real 0.99 5/16 1.00 8/16 0.94 1/16 0.99 5/16 0.99 10/16 1.00 8/16
shifted 0.98 6/16 1.00 9/16 0.99 7/16 1.00 8/16 1.00 10/16 0.99 7/16
const 1.00 8/16 1.00 10/16 0.99 8/16 1.00 10/16 1.01 12/16 1.01 11/16
```
`κ=16`:
```
arm steady rec@0 rec@2 rec@5 rec@10 rec@19
---------------------------------------------------------------------------
real 2.428e-05 3.218e-05 3.605e-05 3.686e-05 4.061e-05 3.179e-05
shuffled 2.371e-05 3.171e-05 3.269e-05 3.584e-05 4.033e-05 3.221e-05
shifted 2.426e-05 3.236e-05 3.293e-05 3.575e-05 4.068e-05 3.204e-05
const 2.413e-05 3.239e-05 3.438e-05 3.673e-05 4.095e-05 3.210e-05
paired shuffled / arm, per seed
steady @0 @2 @5 @10 @19
-------------------------------------------------------------------------------------
real 0.98 5/16 0.99 7/16 0.92 1/16 0.98 4/16 0.99 6/16 1.01 11/16
shifted 0.98 8/16 0.98 6/16 0.99 5/16 1.00 7/16 0.99 9/16 1.00 10/16
const 0.99 8/16 0.98 4/16 0.95 1/16 0.98 6/16 0.99 5/16 1.01 9/16
```
**On `steady`, real affect is indistinguishable from shuffled affect** — 5/16 seeds
at both `κ`, mean ratio 0.98–0.99. The values matter as little as the timing does,
because neither matters at all.
**On `recovery[2]`, real affect is worse than shuffled on 15/16 seeds**, by 6% at
`κ=4` and 8% at `κ=16`, while `shifted` (which preserves arousal's autocorrelation
and breaks only its alignment with the switches) sits at parity, 0.99 on 5–7/16. So
the lag-2 degradation of §2a is genuinely about surprise *timing*: it is the one
thing correlating `−κa` with the switches does that a distribution-matched control
does not, and what it does is make the error worse. `const` reproduces about half of
it at `κ=16` (0.95 on 1/16) and none of it at `κ=4`, which is the bias-shift channel
appearing only once the constant is large enough to shut the gate outright.
## 4. Verdict
**Does affect move the gate? Yes.** `κ=1` moves mean `g` off 0.500 and triples its
sd; `κ=4` opens 12% of entity-steps past `g<0.1`; the gate traces the arousal
transient lag for lag, with a post-vs-far contrast of −0.078 at `κ=4` on 16/16 seeds.
The learned part of the pre-activation stays at 0.000 ± 0.002 throughout, so this is
not affect modulating a learned gating policy — it is affect supplying the whole of a
gating policy gradient descent never built. A1's premise holds: the `−κa` term
activates a mechanism that gradient descent left inert.
**Does moving it help? No.** Steady error is flat to 1.2% across a 16-fold range of
`κ` and wins on 6–9 seeds of 16 — a coin flip. The only sign-definite effect is a
4–11% *degradation* of error two steps after a switch, monotone in `κ`, on 14–16 of
16 seeds. The shuffled control confirms that this degradation is specifically about
surprise timing and not a generic bias shift, which makes it the cleanest positive
measurement in the file and it points the wrong way.
**A1 does not hold on this domain**, and the reason is the one `headroom.md` §6(c)
and `frozen.md` §4 both reached from other directions. The post-switch error here is
dominated by the world's own configuration transient, which no gating policy can
shorten; memory's only contribution is temporal smoothing; and a gate that opens on
surprise spends exactly that smoothing at the moment it is worth most. The mechanism
works. The domain gives it nothing to do, and a small amount to lose.
This is a measured null about *this* domain and *this* budget, not an impossibility
result. What would give the mechanism a job is what the two earlier files already
asked for: a domain where regime identity is worth something to a per-entity state —
a short world transient and a long ambiguity — so that discarding a stale memory buys
more than the averaging it costs. Three things this file establishes that carry
forward regardless:
- **The forcing lever works and is measurable.** Any future domain can be checked for
A1 with the same instrument, and `pre ≈ 0` gives the null a mechanism rather than
an absence.
- **Arousal lags the event by ~12 steps.** `Affect.update`'s slow baseline means the
gate opens after the error rises, not when the world changes. In a domain where
timing matters, that lag is a design parameter (`rho_a`, `rho_slow`) and not a
constant.
- **`recovery[2]` is where affect shows up at all.** Whatever replaces this domain
should be checked for an effect at short lag before its steady-state error is
quoted.
+110
View File
@@ -0,0 +1,110 @@
import numpy as np
import pytest
import regime
from a1 import GateTrace, affect_variants, gate_stats, index_sets, run_a1
from frozen import _build, _train
def _run(seed=0, steps=400, **kw):
spec, wcfg, world, org = _build("grp_k", seed, 32, 10.0, 4.0)
affect, mem, tr = _train(spec, wcfg, world, org, steps, 20, 1e-3, **kw)
return org, tr
def test_replaying_the_runs_own_arousal_reproduces_it_exactly():
"""The Part C control replaces the arousal the gate sees and passes the context
explicitly instead of letting `Organism.forward` build it. Replaying the sequence
the gate itself saw must therefore change nothing at all -- if it does, every
shuffled result is measuring the plumbing rather than the timing."""
base = run_a1("grp_k", 0, 4.0, steps=400)
seen = base["a_gate_seq"]
replayed = run_a1("grp_k", 0, 4.0, steps=400, gate_arousal=lambda t, _a, s=seen: s[t])
assert replayed["steady"] == base["steady"]
assert replayed["recovery"] == base["recovery"]
assert replayed["a_gate_seq"] == seen
def test_on_step_does_not_perturb_the_run():
"""The gate instrumentation is read-only: hooking it must not move a single loss."""
_, base = _run()
_, hooked = _run(on_step=lambda *args: None)
assert hooked["losses"] == base["losses"]
def test_gate_reconstruction_is_the_organisms_own_gate(monkeypatch):
"""`GateTrace` asserts `org.grp(h, prev, a)` equals the M the organism returned, so
the reported g is the organism's own gate and not a plausible lookalike. Feeding it
an h the organism never used must trip that assert, or it is guarding nothing."""
spec, wcfg, world, org = _build("grp_k", 0, 32, 10.0, 4.0)
tr = GateTrace(org)
_train(spec, wcfg, world, org, 50, 20, 1e-3, on_step=tr)
assert len(tr.g_mean) == 50 and all(0.0 < g < 1.0 for g in tr.g_mean)
import a1
real_hidden = a1._hidden
monkeypatch.setattr(a1, "_hidden", lambda *args: real_hidden(*args) + 1e-6)
spec, wcfg, world, org = _build("grp_k", 0, 32, 10.0, 4.0)
with pytest.raises(AssertionError, match="gate reconstruction diverged"):
_train(spec, wcfg, world, org, 5, 20, 1e-3, on_step=GateTrace(org))
def test_index_sets_match_the_metrics_the_error_is_measured_on():
"""`far` must be `_metrics`'s own steady_idx and `post` its recovery steps, or the
gate contrast and the error contrast are measured on different steps."""
steps, window = 400, 20
switched = [i % 57 == 0 for i in range(steps)]
idx = index_sets(switched, steps, window)
half = steps // 2
steady_idx = [i for i in range(half, steps) if not any(switched[max(0, i - window):i + 1])]
assert idx["far"] == steady_idx
assert idx["post"] == sorted({j + k for j in idx["switch"] for k in range(window)})
assert not set(idx["far"]) & set(idx["post"])
assert all(i >= half for i in idx["far"] + idx["switch"])
def test_gate_stats_pools_the_sd_over_entity_steps():
"""Per-step means of g and g^2 must pool to the sd over all entity-steps."""
rng = np.random.default_rng(0)
steps, n = 200, 16
g = rng.random((steps, n))
tr = GateTrace.__new__(GateTrace)
tr.g_mean = list(g.mean(1)); tr.g_sq = list((g ** 2).mean(1))
tr.open_ = list((g > 0.9).mean(1)); tr.shut = list((g < 0.1).mean(1))
tr.pre_mean = list(g.mean(1)); tr.pre_sq = list((g ** 2).mean(1))
tr.a_gate = [0.0] * steps
tr.org = None
out = gate_stats(tr, [False] * steps, steps, 20)
half = g[steps // 2:]
assert out["all"]["g"] == pytest.approx(half.mean())
assert out["all"]["g_sd"] == pytest.approx(half.std(), abs=1e-9)
def test_affect_variants_preserve_the_values_and_destroy_the_timing():
steps = 400
a = list(np.random.default_rng(1).random(steps))
v = affect_variants(a, seed=3, steps=steps)
half = steps // 2
assert np.array_equal(v["real"], a)
for tag in ("shuffled", "shifted", "const"):
assert len(v[tag]) == steps
# shuffled matches the marginal exactly in each half, not merely in expectation
for sl in (slice(0, half), slice(half, steps)):
assert sorted(v["shuffled"][sl]) == pytest.approx(sorted(np.asarray(a)[sl]))
assert sorted(v["shifted"]) == pytest.approx(sorted(a)) # a roll keeps every value
assert v["const"].std() == pytest.approx(0) and v["const"][0] == pytest.approx(np.mean(a))
assert not np.array_equal(v["shuffled"], a) and not np.array_equal(v["shifted"], a)
def test_kappa_lowers_the_gate_in_the_direction_the_spec_says():
"""g -> 0 overwrites, g -> 1 keeps, and arousal is non-negative, so forcing can
only push g down. A positive delta here would mean the sign is wired backwards."""
lo = run_a1("grp_k", 0, 0.0, steps=600)["gate"]["all"]["g"]
hi = run_a1("grp_k", 0, 16.0, steps=600)["gate"]["all"]["g"]
assert hi < lo < 0.55
def test_run_a1_reports_the_same_metrics_regime_run_does():
r = run_a1("grp_k", 0, 0.0, steps=400)
theirs = regime.run("grp_k0", seed=0, steps=400)
assert r["steady"] == theirs["steady"] and r["recovery"] == theirs["recovery"]