Compare commits

...
10 Commits
Author SHA1 Message Date
chrnxandClaude Opus 5 0196eab3b9 docs: agent rules scoped to the measurements
The rules here are about not fooling ourselves: report nulls plainly, do not open a new
domain to make a mechanism work, do not tune a baseline until it catches up, keep every
comparison capacity-controlled, pre-register when the result could be argued either way,
and make anything a results file quotes re-runnable from this repo.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KAWnnPg2qvmLNySamE2k85
2026-09-02 13:02:04 -05:00
chrnxandClaude Opus 5 a4f45c331a exp: when does per-entity memory have a job -- the theory is wrong and the failure is ours
Part 1: the affect timing fix works (arousal's peak moves from lag 11 to lag 2, inside
the pre-registered 3) and the error does not move -- 0 of 16 seeds reach the registered
1.10, largest ratio anywhere 1.017. A1 is closed on this domain.

Part 2: T_id is 2-3 observations against a T_z of 40-80. One observed displacement
carries the regime at 0.958 (exact) and 0.909 (no privileged knowledge), against 0.574
from the instantaneous configuration alone. History nearly doubles the present's
above-chance information, so this is the rememberable kind of domain -- and the GRP's
memory decodes it at 0.332.

Part 3: the predicted peak does not exist. Capacity-controlled state gain is flat at
1.09-1.26 across four orders of magnitude of regime duration, and is largest at the
frozen regime, where there is no regime to identify and G is exactly 1.00. What the
state gain measures is temporal smoothing.

The pre-registered theory is falsified. The domain had the information all along and the
organism does not take it, which closes the project's habit of reaching for a new domain
whenever memory failed to help.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KAWnnPg2qvmLNySamE2k85
2026-09-02 12:29:38 -05:00
chrnxandClaude Opus 5 39ffbc5272 results: correct frozen.md §1a — the margin is the gated head, not capacity
`grp_k0_nostate` was described as a capacity-matched control with "identical
5602 parameters". It is neither capacity-matched nor the same network:
- With M_prev identically zero, gate.weight[:, 32:] and cand.weight[:, 32:]
  receive no gradient and end training bit-identical to their initialisation
  (max |Δ| exactly 0.0). 2048 of 5602 parameters never train; the honest
  effective count is 3554.
- The ablated update collapses to (1−σ(W_g[h‖0]))·tanh(W_c[h‖0]) — a gated
  feedforward head with no recurrence, not the same network minus memory.
- Width-matched memoryless controls (D=86/3548, D=139/5615, cppn_hidden=141/
  5584; 8 seeds each) do not close the gap: grp_k0 wins 7/8 or 8/8 at every
  width, and the 5602-matched RPs are worse than the 1442-parameter one.
Replaces "the margin is capacity, not memory" with "the margin is the gated
post-RP nonlinearity, not memory and not parameter count". The null for memory
is unchanged (1.06x on 4/8 frozen, 1.19x on 11/16 trained). New §1d carries the
measurements and states the untuned-wide-RP limitation, including the D=139
instability on seeds 1 and 6. a1.md gets a one-line pointer; its numbers stand.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KAWnnPg2qvmLNySamE2k85
2026-09-02 10:48:19 -05:00
chrnxandClaude Opus 5 4eaf142b9a docs: correct frozen.md's trained-phase decomposition to Task 8's 16-seed values
The trained-phase state row was quoted at 1.25x on 4/8 seeds from this task's own eight
seeds. Task 8 re-measured it at sixteen: 1.19x mean, 1.11x median, 11/16. Capacity is
unchanged at 3.04x on 16/16. The frozen-phase rows stay at eight seeds as measured.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KAWnnPg2qvmLNySamE2k85
2026-09-02 09:49:28 -05:00
chrnxandClaude Opus 5 860646ad9a exp: A1 -- affect moves the gate, and moving it does not help
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KAWnnPg2qvmLNySamE2k85
2026-09-02 09:48:40 -05:00
chrnxandClaude Opus 5 44a892397f exp: frozen-weights probe -- the memory advantage is capacity, not state
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KAWnnPg2qvmLNySamE2k85
2026-09-02 09:08:04 -05:00
chrnxandClaude Opus 5 d21a8d7aa5 exp: correct the headroom ceilings, add lr and frozen-regime ablations
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KAWnnPg2qvmLNySamE2k85
2026-09-02 08:39:34 -05:00
chrnxandClaude Opus 5 3e34cd82ae exp: headroom check for the regime setup
Requirement 2 holds (grp_k0 beats rp_only 2.9x on steady, all seeds).
Requirements 1 and 3 fail, both for setup reasons rather than A1 reasons.

Measured the domain's information ceilings by least squares rather than tuning
against them. The regime oracle's own ceiling is 1.18e-05, which sits on
requirement 1's tolerance boundary before any training loss; the trained models
land 3-4x above even that. Ruled out omega (5/10/20), noise (16x lower floor
moves nothing), sigma, training length (40k), and the missing type-pair edge
channel. Every condition converges to ~1.5e-05 regardless of the information it
is given: the error is optimiser tracking lag against a target that switches
every 40-80 steps, not missing information. An oracle cannot help a model that
is not yet using what it has.

rp_flag's 4x rec@0 spike is an untrained input spike, not a leak: the change
flag column gets gradient on ~1.5% of steps and so perturbs every message at
the exact step rec@0 measures. Zero-initialising the oracle columns of W_feat
removes it, makes rp_flag a valid null, and makes grp_regime exactly equal to
grp_k0. Recommended in the report, not adopted here - it moves every oracle
condition off what Task 6 was reviewed under.

Only source change: omega is now a run() parameter, default 10.0 unchanged, so
prior runs reproduce exactly. No default in particles.py or regime.py changed;
../ailed untouched.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KZEvqjtoW5JZYyeUGNp9Ui
2026-09-02 08:12:32 -05:00
chrnxandClaude Opus 5 164810a901 fix: validate window<t_min and test _metrics directly (spec §8)
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KAWnnPg2qvmLNySamE2k85
2026-09-02 07:51:51 -05:00
chrnxandClaude Sonnet 5 0d074a5d6e feat: regime-switch runner for claims A1 and A2 (spec §8)
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BoDVQE6PnU9Mt9uikRy7pD
2026-09-02 07:44:52 -05:00
16 changed files with 4164 additions and 0 deletions

No files matched your search

+70
View File
@@ -0,0 +1,70 @@
# experiments — measurement rules
The domain and the runs. This repo produces every number the paper reports, so its rules are
about not fooling ourselves rather than about code style. The library is the sibling `ailed`
repo, installed editable; the design is `AILED_General_Specification.md` in the parent
directory.
## What is in here
| file | responsibility |
|---|---|
| `particles.py` | the domain: particles on a torus whose type-by-type coupling switches unannounced |
| `regime.py` | the conditions, the training loop, and `_metrics` |
| `frozen.py` | frozen-weights probe, the state ablation, the representation probes |
| `ceilings.py` | least-squares information ceilings under four information sets |
| `identify.py` | how much of the hidden variable lives in the past rather than the present |
| `when_memory_works.py` | the pre-registered test of when per-entity state has a job |
| `results/*.md` | **the audit trail the paper cites.** Committed. The `.json` files are not. |
## The rules that matter
- **Report a null plainly.** Every substantive result in this repo so far is a null, and each
one turned out more informative than the positive it replaced. Do not soften a negative, do
not hunt for a configuration that rescues it, and do not defer it by proposing a new domain.
- **Do not open a new domain to make a mechanism work.** That is p-hacking with extra steps
and it generalises to nothing. If a mechanism does not help, measure why on the domain you
have. `results/when_memory_works.md` exists because of this rule.
- **Do not tune a baseline until it catches up.** Raising the learning rate until the
memoryless model matches the gated one changes the question instead of answering it.
Tuning a *mechanism's own* parameters is different and legitimate — `rho_a`/`rho_slow`
belong to affect, so setting them is fair; `lr` belongs to the comparison, so it is not.
- **Every comparison is capacity-controlled.** `rp_only` has 1442 parameters and `grp_k0` has
5602. A number comparing them is confounded 3.9x and is not a memory result. See
`results/frozen.md` §1d, which also records why "capacity" was the wrong word for that
margin in the first place.
- **Pre-register when the result could be argued either way.** State the success criterion,
the seed count, and what counts as failure, in `.sdd/progress.md`, before the run. Then
accept what comes back. No re-running with adjusted criteria.
- **Oracles are opt-in and free.** Enabling one may only add columns to `attrs`. The
trajectory, regime schedule, switch times and noise draws stay byte-identical to the
non-oracle run at the same seed, or a measured difference could come from a different world
rather than from the extra information.
- **Seeds.** Across-seed spread here is comparable to the effects being claimed. Eight seeds
supports a direction; it does not support a ratio. Report per-seed values and the count of
seeds won, not only the ratio of means.
- **Anything a results file quotes must be re-runnable from this repo.** An uncommitted
throwaway driver is not reproducible. `ceilings.py` exists because of this rule; there is a
standing debt where `frozen.md` §1d's width-matched rows still are not.
## Metrics, and what they do not mean
`recovery[k]` **does not measure adaptation.** Under frozen weights a stateless model
reproduces its shape at every lag, because it tracks the world's own post-switch
configuration transient (`frozen.md` §1b). Report it if useful, but never build a claim on
it; the honest observable is a difference between conditions at matched lag.
`run()` refuses `window >= t_min`, because a recovery window that reaches the next switch
silently blends two events into one curve.
## Tests
`uv run pytest -q`. Same rule as the library: a test that cannot fail is worse than no test.
When you add a control, verify it can detect the thing it controls for — the freeze assertion
in `frozen.py` has a test that nudges a weight to prove the assertion fires.
## Conventions
Python ≥3.11, `uv`, PyTorch, pytest. `pythonpath = ["."]`, so modules sit at the repo root.
Runs are cheap — 8000 steps takes seconds. Spend the budget on more seeds, not longer runs.
Commit inside this repo only.
+9
View File
@@ -0,0 +1,9 @@
# experiments
The domain and the runs — every number the paper reports comes from here.
Rules for this repo are in `AGENTS.md` — read it before changing anything. It carries the
constraints that exist because breaking them produced a wrong result, not style preferences.
The design this implements is `AILED_General_Specification.md`, and the project-wide rules are
in `AGENTS.md`, both in the parent directory alongside the sibling repos.
+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()
+129
View File
@@ -0,0 +1,129 @@
"""Information ceilings for the particles domain. Task 7.
Fits, by least squares over a rolled-out world, the best predictor of the form
d_i = a[offset(i)] + sum_j c[key(i,j)] * dt * kern(r_ij) * r_ij
under several information sets. The radial kernel is handed to the fit exactly, so
each row is the best a predictor with that information can do *within this family*.
SCOPE. The family is linear in the messages. The real RP applies tanh on top of the
aggregate and the GRP adds per-entity state, so these numbers are NOT a bound on what
the trained architecture can reach -- a memoryless rp_only run with the regime frozen
gets below rows C and D. Read the table as a map of where the information sits, not
as a proof about the model.
Row A is the self-check: given (regime, t_i, t_j) the family spans the dynamics
exactly, so its deterministic residual must be ~0 and its residual against the noisy
target must equal noise**2.
uv run python ceilings.py [steps] [seeds] [t_min,t_max]
"""
from __future__ import annotations
import statistics
import sys
import torch
from particles import ParticleConfig, ParticleWorld, wrapped_diff
def collect(cfg: ParticleConfig, steps: int) -> list[tuple]:
"""Roll the world out, recovering the deterministic part of each step's target."""
w, rows = ParticleWorld(cfg), []
for _ in range(steps):
coords, types = w.coords.clone(), w.types.clone()
obs = w.step()
# obs.regime, not w.regime read before step(): step() switches the regime
# *before* computing the delta, so the pre-step value is stale on switch steps.
r = wrapped_diff(coords)
kern = torch.exp(-(r ** 2).sum(-1) / cfg.sigma ** 2)
kern.fill_diagonal_(0.0)
K = w.regimes[obs.regime][types[:, None], types[None, :]]
det = cfg.dt * ((K * kern)[:, :, None] * r).sum(1)
rows.append((r, kern, types, obs.regime, det, obs.target))
return rows
def design(rows: list[tuple], cfg: ParticleConfig, key, offset) -> tuple[torch.Tensor, ...]:
"""key(types, regime) -> (N,N) coefficient index; offset(types, regime) -> (N,) index."""
n_key = max(key(t, g).max().item() for _, _, t, g, _, _ in rows) + 1
n_off = max(offset(t, g).max().item() for _, _, t, g, _, _ in rows) + 1
X, Y, Yn = [], [], []
for r, kern, types, regime, det, target in rows:
w = cfg.dt * kern[:, :, None] * r # (N,N,2)
idx = key(types, regime)
cols = [(w * (idx == c)[:, :, None]).sum(1) for c in range(n_key)] # each (N,2)
oid = offset(types, regime)
for c in range(n_off): # a free 2-vector offset per class
sel = (oid == c).float()
zero = torch.zeros_like(sel)
cols += [torch.stack([sel, zero], -1), torch.stack([zero, sel], -1)]
X.append(torch.stack(cols, -1).reshape(-1, len(cols)))
Y.append(det.reshape(-1))
Yn.append(target.reshape(-1))
return torch.cat(X).double(), torch.cat(Y).double(), torch.cat(Yn).double()
T = ParticleConfig().n_types
CEILINGS = [
("A perfect: (regime, t_i, t_j)",
lambda t, g: (g * T * T + t[:, None] * T + t[None, :]).long(),
lambda t, g: torch.zeros_like(t).long()),
("B regime-blind, pair-aware (t_i, t_j)",
lambda t, g: (t[:, None] * T + t[None, :]).long(),
lambda t, g: t.long()),
("C regime oracle (regime, t_j)",
lambda t, g: (g * T + t[None, :]).expand(len(t), len(t)).long(),
lambda t, g: (g * T + t).long()),
("D no oracle (t_j)",
lambda t, g: t[None, :].expand(len(t), len(t)).long(),
lambda t, g: t.long()),
]
def ceilings(steps: int = 1200, seeds: tuple[int, ...] = (0, 1, 2),
t_min: int | None = None, t_max: int | None = None) -> dict[str, tuple[float, float]]:
"""`t_min`/`t_max` override the regime duration; Task 9 Part 3 reads the oracle prize
D->C at each duration it sweeps. They are passed to `ParticleConfig` rather than
changed in `particles.py`, so every existing caller gets the 40-80 default."""
dur = {k: v for k, v in (("t_min", t_min), ("t_max", t_max)) if v is not None}
out = {}
for label, key, off in CEILINGS:
dets, obss = [], []
for seed in seeds:
cfg = ParticleConfig(seed=seed, **dur)
X, Y, Yn = design(collect(cfg, steps), cfg, key, off)
pred = (X @ torch.linalg.lstsq(X, Y.unsqueeze(1)).solution).squeeze(1)
dets.append(((pred - Y) ** 2).mean().item())
obss.append(((pred - Yn) ** 2).mean().item())
out[label] = (statistics.fmean(dets), statistics.fmean(obss))
return out
def main() -> None:
steps = int(sys.argv[1]) if len(sys.argv) > 1 else 1200
seeds = tuple(int(s) for s in sys.argv[2].split(",")) if len(sys.argv) > 2 else (0, 1, 2)
dur = tuple(int(x) for x in sys.argv[3].split(",")) if len(sys.argv) > 3 else (None, None)
cfg = ParticleConfig(**{k: v for k, v in zip(("t_min", "t_max"), dur) if v is not None})
res = ceilings(steps, seeds, *dur)
print(f"steps={steps} seeds={','.join(map(str, seeds))} noise^2 = {cfg.noise ** 2:.3e}\n")
print(f"{'information set':<40}{'MSE(det part)':>15}{'MSE(vs target)':>16}")
print("-" * 71)
for label, (d, o) in res.items():
print(f"{label:<40}{d:>15.3e}{o:>16.3e}")
c, d = res["C regime oracle (regime, t_j)"], res["D no oracle (t_j)"]
print(f"\noracle prize D->C: {d[0] / c[0]:.2f}x on the deterministic part, "
f"{d[1] / c[1]:.2f}x against the noisy target")
a = res["A perfect: (regime, t_i, t_j)"]
assert a[0] < 1e-15, f"row A must span the dynamics exactly, got {a[0]:.3e}"
assert abs(a[1] - cfg.noise ** 2) < 0.02 * cfg.noise ** 2, \
f"row A vs target must equal noise^2={cfg.noise ** 2:.3e}, got {a[1]:.3e}"
print("self-check: row A spans the dynamics and lands on the noise floor.")
if __name__ == "__main__":
main()
+488
View File
@@ -0,0 +1,488 @@
"""Task 7b: frozen-weights probe. Train, freeze every parameter, keep stepping.
Task 7 measured memory's advantage at lr=1e-3 and watched it decay to 1.06x at
lr=1e-2: mean error cannot tell state and fast weights apart, because raising lr
buys the same adaptation speed that memory buys. This file removes learning
instead of retuning it. After the freeze no parameter may change, so nothing the
model does can be attributed to an optimiser step. A frozen `rp_only` still carries
the 2-d affect state (`--freeze-affect` pins that too); a frozen `grp_k0` still
updates its per-entity M every step through the gate.
Part A measures recovery after a switch under frozen weights. Part B asks what the
state knows, by linearly decoding the world's regime id out of M (GRP) and out of h
(RP), against an empirically measured chance level.
What survives the freeze is state *only if the two conditions are capacity-matched*,
and they are not: `rp_only` has 1442 parameters and `grp_k0` 5602. `--ablate-state`
supplies the control that separates the two. See results/frozen.md; it is what turns
this file's result from a memory effect into a null.
"""
from __future__ import annotations
import argparse
import json
import statistics
from pathlib import Path
import numpy as np
import torch
from torch import Tensor, nn
from ailed import Affect, AffectConfig, Organism, detach_memory, update
from particles import ParticleConfig, ParticleWorld, wrapped_diff
from regime import CONDITIONS, KAPPA_FLAG, _context, _metrics
TRAIN_STEPS = 8000 # matches the budget every headroom table in results/headroom.md used
FROZEN_STEPS = 4000
SPLIT = 0.7 # probe train fraction, taken as a prefix in time
# -- construction and the two phases ---------------------------------------------
def _build(name: str, seed: int, hidden: int, omega: float, kappa: float,
t_min: int | None = None, t_max: int | None = None):
"""Construct exactly as `regime.run` does, in the same order, so the RNG stream matches.
`t_min`/`t_max` override the regime duration for Task 9 Part 3. They are passed to
`ParticleConfig` here rather than changed in `particles.py`, so every other caller
keeps the 40-80 default and `test_train_copy_is_identical_to_regime_run` still pins
this loop against `regime.run`.
"""
spec = dict(CONDITIONS[name])
if spec["kappa"] == KAPPA_FLAG:
spec["kappa"] = kappa
dur = {}
if t_min is not None:
dur["t_min"] = t_min
if t_max is not None:
dur["t_max"] = t_max
wcfg = ParticleConfig(seed=seed, oracle=spec["oracle"], **dur)
torch.manual_seed(seed)
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, omega=omega, kappa=spec["kappa"], memory=spec["memory"])
return spec, wcfg, world, org
def _train(spec: dict, wcfg: ParticleConfig, world: ParticleWorld, org: Organism,
steps: int, bptt: int, lr: float, stateless: bool = False,
gate_arousal=None, on_step=None, acfg: AffectConfig | None = 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. 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.
`acfg` overrides the affect time constants for Task 9 Part 1. It defaults to
`AffectConfig()`, the value this loop always used, so the copy stays verbatim for
every existing caller. `AffectConfig`'s own defaults are not touched.
"""
opt = torch.optim.Adam(org.parameters(), lr=lr)
acfg = AffectConfig() if acfg is None else acfg
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)
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()
opt.step()
pending = []
memory = detach_memory(memory)
trace = dict(losses=losses, switched=switched, arousals=arousals)
return affect, detach_memory(memory), trace
def _hidden(org: Organism, attrs: Tensor, r: Tensor, axes: tuple[float, float],
ctx: Tensor | None) -> Tensor:
"""h as `Organism.forward` computes it, by mirroring the tensors it builds internally.
`Organism.forward` returns only `out(h)` (or `out(M)`), so h has to be recomputed
from the public `org.rp`. Every argument here is built the way core.py builds it;
`_frozen` asserts the reconstruction is bit-identical to the organism's own output.
"""
n = attrs.shape[0]
valence, arousal = axes
if ctx is None:
ctx = torch.tensor([valence, arousal], dtype=attrs.dtype)
edge_types = torch.zeros(n, n, dtype=torch.long)
mask = torch.ones(n, n, dtype=attrs.dtype)
edge_onehot = nn.functional.one_hot(edge_types, org.n_edge_types).to(attrs.dtype)
return org.rp(attrs, r, edge_onehot, mask, ctx)
def _frozen(spec: dict, wcfg: ParticleConfig, world: ParticleWorld, org: Organism,
affect: Affect, memory: dict[int, Tensor], steps: int,
freeze_affect: bool = False, stateless: bool = False) -> dict:
"""Step the world with every parameter frozen. Memory and affect keep updating.
`freeze_affect` additionally pins (valence, arousal) at their end-of-training
values. It exists because `rp_only` runs with `ctx="affect"`, so a frozen RP is
*not* a fixed function of the current observation: affect is a 2-d state that
updates from the loss and feeds the CPPN. Pinning it removes the RP's last
adaptive channel and tests the premise Part A rests on."""
for p in org.parameters():
p.requires_grad_(False)
before = nn.utils.parameters_to_vector(org.parameters()).clone()
acfg = AffectConfig()
zero = torch.zeros(org.hidden_dim)
losses, switched, arousals, regimes = [], [], [], []
h_reps, m_reps, dM, gates, couple = [], [], [], [], []
# the regime id is an arbitrary label over four random coupling matrices; what an
# entity actually needs is its own row of the current one. Decoding the id can be
# at chance while the row is not, so both are probed.
rows = torch.stack([k[world.types] for k in world.regimes]) # (n_regimes, N, n_types)
with torch.no_grad():
for t in range(steps):
obs = world.step()
ctx = _context(spec["ctx"], affect, obs.regime, wcfg.n_regimes)
if stateless:
memory = {}
prev = torch.stack([memory.get(i, zero) for i in obs.ids]) if org.use_memory else None
r = wrapped_diff(obs.coords)
pred, memory = org(obs.attrs, r, obs.ids, affect.axes, memory, context=ctx)
loss = ((pred - obs.target) ** 2).mean()
h = _hidden(org, obs.attrs, r, affect.axes, ctx)
if org.use_memory:
M = torch.stack([memory[i] for i in obs.ids])
# if this holds, h is exactly the h the organism used
assert torch.equal(org.grp(h, prev, affect.arousal), M), "h reconstruction diverged"
m_reps.append(M.numpy().copy())
dM.append(float((M - prev).abs().max()))
g = torch.sigmoid(org.grp.gate(torch.cat([h, prev], -1)) - org.grp.kappa * affect.arousal)
gates.append((float(g.mean()), float(g.std()), float((g > 0.9).float().mean()),
float((g < 0.1).float().mean())))
else:
assert torch.equal(org.out(h), pred), "h reconstruction diverged"
h_reps.append(h.numpy().copy())
if not freeze_affect:
affect = update(affect, loss.item(), acfg)
losses.append(loss.item()); switched.append(obs.switched)
arousals.append(affect.arousal); regimes.append(obs.regime)
couple.append(rows[obs.regime].numpy().copy())
after = nn.utils.parameters_to_vector(org.parameters())
frozen_ok = bool(torch.equal(before, after))
assert frozen_ok, "a parameter changed during the frozen phase"
assert not any(p.requires_grad for p in org.parameters())
if org.use_memory and not stateless:
# freezing is about parameters, not state: if M stopped moving the GRP would
# have silently degenerated into an RP and any null would be for the wrong reason
assert min(dM[1:]) > 0.0, "M did not change between consecutive frozen steps"
return dict(losses=losses, switched=switched, arousals=arousals, regimes=regimes,
couple=(np.stack(couple) + 1).astype(int), # {-1,0,1} -> class {0,1,2}
gate=dict(zip(("mean", "sd", "frac_open", "frac_shut"),
(statistics.fmean(c) for c in zip(*gates)))) if gates else None,
h=np.stack(h_reps), M=np.stack(m_reps) if m_reps else None,
frozen_bit_identical=frozen_ok, n_params=int(before.numel()),
dM_min=min(dM[1:]) if dM else None,
dM_mean=statistics.fmean(dM[1:]) if dM else None)
# -- Part B: the linear probe ----------------------------------------------------
def _fit_lsq(X: np.ndarray, y: np.ndarray, R: int, ridge: float = 1e-6) -> np.ndarray:
G = X.T @ X
lam = ridge * np.trace(G) / X.shape[1]
return np.linalg.solve(G + lam * np.eye(X.shape[1]), X.T @ np.eye(R)[y])
def _fit_logit(X: np.ndarray, y: np.ndarray, R: int, l2: float = 1e-4) -> np.ndarray:
"""Multinomial logistic, so a null cannot be blamed on least squares.
X already carries the bias column, so the linear map needs no separate intercept.
LBFGS with strong-Wolfe converges deterministically here; there is no seed."""
Xt = torch.tensor(X); yt = torch.tensor(y, dtype=torch.long)
W = torch.zeros(X.shape[1], R, dtype=torch.float64, requires_grad=True)
opt = torch.optim.LBFGS([W], max_iter=300, tolerance_grad=1e-10,
line_search_fn="strong_wolfe")
def closure():
opt.zero_grad()
loss = nn.functional.cross_entropy(Xt @ W, yt) + l2 * (W[:-1] ** 2).sum()
loss.backward()
return loss
opt.step(closure)
return W.detach().numpy()
ESTIMATORS = {"lsq": _fit_lsq, "logit": _fit_logit}
def _design(reps: np.ndarray, mu: np.ndarray, sd: np.ndarray) -> np.ndarray:
"""(T, N, D) -> (T*N, D+1): standardised features plus a bias column."""
flat = reps.reshape(-1, reps.shape[-1]).astype(np.float64)
z = (flat - mu) / sd
return np.concatenate([z, np.ones((z.shape[0], 1))], axis=1)
def _scores(reps: np.ndarray, W: np.ndarray, mu: np.ndarray, sd: np.ndarray) -> np.ndarray:
return (_design(reps, mu, sd) @ W).reshape(reps.shape[0], reps.shape[1], -1)
def _accuracy(scores: np.ndarray, lab: np.ndarray, step_lab: np.ndarray | None) -> tuple[float, float]:
"""(per-entity accuracy, per-step accuracy after averaging the entity scores).
The per-step vote only exists when every entity shares one label; a per-entity
target such as the coupling row has no step-level answer to vote on.
"""
ent = float((scores.argmax(-1) == lab).mean())
step = float((scores.mean(1).argmax(-1) == step_lab).mean()) if step_lab is not None else float("nan")
return ent, step
def probe(reps: np.ndarray, labels: np.ndarray, switched: list[bool], n_regimes: int,
split: float = SPLIT, n_null: int = 20, seed: int = 0,
estimator: str = "lsq", center: bool = False) -> dict:
"""Linear decode from a representation onto a categorical target, split by time.
`labels` is either one label per step, shape (T,) -- the regime id -- or one per
entity per step, shape (T, N) -- the coupling row the current regime hands that
entity. The test split is a suffix in time, never a random subset, so the probe
cannot memorise steps adjacent to the ones it is scored on. Chance is measured,
not assumed, by two nulls that both refit the probe from scratch.
"""
if center:
# subtract each entity's own mean, computed on the probe-train prefix only.
# M is dominated by stable per-entity identity (the particle's type); if a
# regime code is hiding underneath that offset, this is what exposes it.
reps = reps - reps[:int(reps.shape[0] * split)].mean(0, keepdims=True)
T, N = reps.shape[0], reps.shape[1]
per_step = labels.ndim == 1
lab = np.repeat(labels[:, None], N, axis=1) if per_step else labels
cut = int(T * split)
tr, te = slice(0, cut), slice(cut, T)
fit = ESTIMATORS[estimator]
flat_tr = reps[tr].reshape(-1, reps.shape[-1]).astype(np.float64)
mu, sd = flat_tr.mean(0), flat_tr.std(0) + 1e-12
def fit_eval(z: np.ndarray) -> tuple[float, float, np.ndarray]:
W = fit(_design(reps[tr], mu, sd), z[tr].reshape(-1), n_regimes)
s = _scores(reps[te], W, mu, sd)
return _accuracy(s, lab[te], labels[te] if per_step else None) + (s,)
ent, step, s_te = fit_eval(lab)
# null 1: permute the step-level labels, keeping the 16 entities of a step together
# null 2: circularly shift the label sequence, which also keeps each regime's
# 40-80 step block structure intact -- the stricter of the two, because a
# probe that merely tracks slow drift still scores at this level
rng = np.random.default_rng(seed)
shuf, shift = [], []
for _ in range(n_null):
shuf.append(fit_eval(rng.permutation(lab))[0])
k = int(rng.integers(T // 10, T - T // 10))
shift.append(fit_eval(np.roll(lab, k, axis=0))[0])
# latency: steps from a switch until the decoded regime first matches the true one,
# measured on the test split only, and censored at the next switch
sw = [i for i, f in enumerate(switched[cut:]) if f]
lat, censored = [], 0
if per_step:
decoded, true = s_te.mean(1).argmax(-1), labels[te]
for a, b in zip(sw, sw[1:] + [T - cut]):
hit = next((k for k in range(b - a) if decoded[a + k] == true[a]), None)
if hit is None:
censored += 1
else:
lat.append(hit)
return dict(
estimator=estimator, centered=center, acc_entity=ent, acc_step=step,
chance_shuffle=float(np.mean(shuf)), chance_shuffle_max=float(np.max(shuf)),
chance_shift=float(np.mean(shift)), chance_shift_max=float(np.max(shift)),
n_test_steps=int(T - cut), n_test_switches=len(sw),
latency=float(np.mean(lat)) if lat else float("nan"),
latency_median=float(np.median(lat)) if lat else float("nan"),
censored=censored,
)
def persistence(reps: np.ndarray, max_lag: int = 60) -> dict:
"""Lag-1 autocorrelation and the lag where it falls below 1/e, per channel.
Model-agnostic, so `h` and `M` are measured the same way. It answers what the
state is doing when the regime is not decodable from it: a large integration
time means the GRP is running a temporal filter, not a regime classifier.
"""
x = reps - reps.mean(0, keepdims=True)
sd = x.std(0) + 1e-12
ac = [float((x[:-k] * x[k:]).mean(0).__truediv__(sd * sd).mean()) for k in range(1, max_lag + 1)]
tau = next((k + 1 for k, v in enumerate(ac) if v < np.exp(-1.0)), max_lag)
return dict(lag1=ac[0], tau=tau, ac=ac[:20])
# -- driver ----------------------------------------------------------------------
def run_one(name: str, seed: int, train_steps: int = TRAIN_STEPS, frozen_steps: int = FROZEN_STEPS,
window: int = 20, bptt: int = 20, lr: float = 1e-3, hidden: int = 32,
kappa: float = 4.0, omega: float = 10.0, freeze_affect: bool = False,
probes: bool = True, stateless: bool = False) -> 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}")
affect, memory, tr = _train(spec, wcfg, world, org, train_steps, bptt, lr, stateless)
fr = _frozen(spec, wcfg, world, org, affect, memory, frozen_steps, freeze_affect, stateless)
labels = np.asarray(fr["regimes"])
which = "M" if fr["M"] is not None else "h"
out = dict(
condition=name + ("_nostate" if stateless else ""), seed=seed,
train_steps=train_steps, frozen_steps=frozen_steps,
freeze_affect=freeze_affect, stateless=stateless,
n_params_rp=sum(p.numel() for p in org.rp.parameters()),
trained=_metrics(tr["losses"], tr["switched"], tr["arousals"], window),
frozen=_metrics(fr["losses"], fr["switched"], fr["arousals"], window),
frozen_bit_identical=fr["frozen_bit_identical"], n_params=fr["n_params"],
dM_min=fr["dM_min"], dM_mean=fr["dM_mean"], probe_on=which,
)
if not probes:
return out
# every variant on every representation the condition has: `M` is the GRP's state,
# `h` the RP output it is built from. Reporting `h` for the GRP too makes the
# comparison within one organism, holding the weights fixed.
got, pers = {}, {}
for tag, rep in (("M", fr["M"]), ("h", fr["h"])):
if rep is None:
continue
args = (rep, labels, fr["switched"], wcfg.n_regimes)
got[f"{tag}_lsq"] = probe(*args, seed=seed)
got[f"{tag}_lsq_centered"] = probe(*args, seed=seed, center=True)
got[f"{tag}_logit"] = probe(*args, seed=seed, n_null=5, estimator="logit")
for c in range(wcfg.n_types): # the coupling this entity's own type feels
got[f"{tag}_couple{c}"] = probe(rep, fr["couple"][:, :, c], fr["switched"],
3, seed=seed, n_null=10)
pers[tag] = persistence(rep)
out["probes"] = got
out["persistence"] = pers
out["gate"] = fr["gate"]
out["probe"] = got[f"{which}_lsq"] # headline
return out
def norm_table(results: list[dict], key: str = "frozen") -> str:
"""recovery[k] / steady, normalised per seed before averaging.
The raw curves are not comparable across conditions whose steady error differs
3x; this asks the shape question -- how far above its own floor does a condition
go after a switch, and does it come back down.
"""
by: dict[str, list[dict]] = {}
for r in results:
by.setdefault(r["condition"], []).append(r)
idxs = list(range(0, 20, 2)) + [19]
lines = [f"{'condition':<12}" + "".join(f"{'@' + str(i):>7}" for i in idxs),
"-" * (12 + 7 * len(idxs))]
for name, rs in by.items():
ratios = [[r[key]["recovery"][i] / r[key]["steady"] for i in idxs] for r in rs]
lines.append(f"{name:<12}" + "".join(f"{statistics.fmean(c):>7.2f}" for c in zip(*ratios)))
return "\n".join(lines)
def table(results: list[dict], key: str = "frozen") -> str:
by: dict[str, list[dict]] = {}
for r in results:
by.setdefault(r["condition"], []).append(r)
idxs = [0, 1, 2, 5, 10, 19]
head = "".join(f"{'rec@' + str(i):>11}" for i in idxs)
lines = [f"{'condition':<12}{'steady':>11}{'(sd)':>11}{'min':>11}{'max':>11}{head}",
"-" * (12 + 44 + 11 * len(idxs))]
for name, rs in by.items():
st = [r[key]["steady"] for r in rs]
row = "".join(f"{statistics.fmean(r[key]['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:<12}{statistics.fmean(st):>11.3e}{sd:>11.3e}"
f"{min(st):>11.3e}{max(st):>11.3e}{row}")
return "\n".join(lines)
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--conditions", default="rp_only,grp_k0")
ap.add_argument("--seeds", default="0,1,2,3,4,5,6,7")
ap.add_argument("--train-steps", type=int, default=TRAIN_STEPS)
ap.add_argument("--frozen-steps", type=int, default=FROZEN_STEPS)
ap.add_argument("--window", type=int, default=20)
ap.add_argument("--lr", type=float, default=1e-3)
ap.add_argument("--freeze-affect", action="store_true",
help="also pin (valence, arousal) in the frozen phase, so a frozen "
"rp_only really is a fixed function of the observation")
ap.add_argument("--no-probes", action="store_true")
ap.add_argument("--ablate-state", action="store_true",
help="hand the organism an empty memory every step: same parameters, "
"no state carried. Separates memory from the GRP's extra capacity.")
ap.add_argument("--out", default="results/frozen.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_one(name, seed, a.train_steps, a.frozen_steps, window=a.window, lr=a.lr,
freeze_affect=a.freeze_affect, probes=not a.no_probes,
stateless=a.ablate_state)
f = r["frozen"]
msg = (f"{r['condition']:<18} seed={seed} frozen_steady={f['steady']:.3e} "
f"rec@0={f['recovery'][0]:.3e} rec@10={f['recovery'][10]:.3e}")
if "probe" in r:
p = r["probe"]
msg += (f" probe({r['probe_on']})={p['acc_entity']:.3f} "
f"chance={p['chance_shift']:.3f} lat={p['latency']:.1f}")
print(msg, 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))
for key in ("trained", "frozen"):
print(f"\n{key} phase:"); print(table(results, key))
print(f"{key} recovery / steady:"); print(norm_table(results, key))
if __name__ == "__main__":
main()
+437
View File
@@ -0,0 +1,437 @@
"""Task 9 Part 2: how many steps of history does it take to identify the regime?
`T_id` is a property of the *domain*, not of our architecture, so nothing in this
file constructs an Organism. It rolls the world out and asks: given the last `L`
observations an observer actually has at step `t`, how well can the regime in force
at `t` be decoded?
What the observer has at step t, and nothing more:
* the coordinates c_{t-L+1} .. c_t (the current one included -- it is observed)
* therefore the displacements d_s = wrap(c_{s+1} - c_s) for s = t-L+1 .. t-1
`d_t` is *not* available: that is the quantity the organism is asked to predict, and
handing it to the decoder would be handing over the answer. So `L = 1` is the
instantaneous configuration alone -- the read-off `results/frozen.md` §2 measured at
+0.05 over chance -- and each extra step of window buys exactly one more observed
displacement.
## The feature sets, and why the physics one is a fair stand-in for optimal
The world's dynamics are
d_i(s) = sum_c K[t_i, c] * B_i^c(s) + eps, B_i^c(s) = dt * sum_{j: t_j = c} kern(r_ij) r_ij
with `kern` the fixed radial kernel and `eps ~ N(0, noise^2)`. `B` is the *message
basis*: everything about the configuration that the coupling matrix multiplies. It is
computable from the coordinates alone, so it is observer-side information, and it is
the same decomposition `ceilings.py` fits against. `_check_basis` asserts the
reconstruction is exact.
Given that model, the log-likelihood of regime `g` from the window's displacements is
-1/(2 noise^2) * sum_s sum_i || d_i(s) - sum_c K_g[t_i,c] B_i^c(s) ||^2
= const + (1/noise^2) * sum_c K_g[t_i,c] <d, B^c> - (1/2noise^2) * sum_{c,c'} K_g[t_i,c] K_g[t_i,c'] <B^c, B^c'>
which is **affine in the statistics `<d, B^c>` and `<B^c, B^c'>`, with coefficients
that depend on `g` and on the entity's own type**. So a linear classifier on those
statistics, interacted with the type one-hot, can express the exact Bayes rule. That
is what `phys` is, and it is why it is a fair stand-in for "optimal" rather than a
weak probe that would understate the difficulty. `bayes` computes the same rule in
closed form, with the true coupling matrices handed to it, as a cross-check on the
fit: `phys` should track it and must not beat it by much.
`lin` and `mlp` are the honest non-omniscient decoders -- least squares and a
two-layer MLP on the raw window (the per-frame features at every step of the window,
the observed displacements, the type one-hot). They know no coupling matrices. If they
saturate where `bayes` does, the saturation is the domain's and not a decoder's
limitation.
## The headline: how much does history add over the present?
The number that decides whether memory can pay is not where accuracy saturates. It is
`accuracy(L) - accuracy(1)`. `L = 1` is the present-only baseline: the current frame,
no displacement, no history. Three cases a hidden variable can fall into --
1. no evidence anywhere: nothing helps, memory included
2. evidence already in the present: history is *redundant* and feedforward suffices,
however identifiable the variable is
3. evidence only in the past: memory is required (card counting is the pure case)
-- and only case 3 gives per-entity state a job. `T_id` is a secondary quantity that
matters only once `accuracy(L) - accuracy(1)` is materially above zero.
This makes the *strength of the L = 1 decoder* the load-bearing choice, because an
underpowered present-only baseline inflates the history gain. So the per-frame feature
block (`_frame`) carries every rotation-invariant scalar the message basis misses --
the kernel mass and the kernel-weighted spread per neighbour type, alongside `B`
itself -- and `L = 1` and `L = 40` are given the *same* per-frame features and the
same decoder, differing only in how many frames. A better present-only decoder could
only shrink the reported gain, never grow it.
Chance is measured the way `frozen.py` measures it: two nulls, both refitting from
scratch -- a label shuffle, and a circular shift that preserves each regime's block
structure and is therefore the stricter of the two.
uv run python identify.py --out results/identify.json
"""
from __future__ import annotations
import argparse
import json
import statistics
from pathlib import Path
import numpy as np
import torch
from torch import nn
from particles import ParticleConfig, ParticleWorld, wrapped_diff
LS = (1, 2, 3, 5, 10, 20, 40)
SEEDS = (0, 1, 2, 3, 4, 5, 6, 7)
STEPS = 4000
SPLIT = 0.7
# -- the world, rolled out -------------------------------------------------------
def rollout(cfg: ParticleConfig, steps: int) -> dict:
"""Coordinates, observed displacements, the message basis, and the true regime.
`coords[t]` is what an observer sees at step t; `disp[t] = wrap(coords[t+1] -
coords[t])` is what it sees *after* step t resolves, so at step t the observer has
`disp[:t]` and not `disp[t]`. `regime[t]` is the regime that generated `disp[t]`.
"""
w = ParticleWorld(cfg)
coords, disp, regimes = [], [], []
for _ in range(steps):
obs = w.step()
coords.append(obs.coords)
regimes.append(obs.regime)
disp.append(wrapped_diff(torch.stack([obs.coords, w.coords]))[0, 1]) # wrap(c_{t+1} - c_t)
C = torch.stack(coords) # (T, N, 2)
D = torch.stack(disp) # (T, N, 2)
B = torch.stack([_basis(c, w.types, cfg) for c in C]) # (T, N, n_types, 2)
F = torch.stack([_frame(c, w.types, cfg) for c in C]) # (T, N, 4 * n_types)
K = torch.stack(w.regimes) # (n_regimes, n_types, n_types)
return dict(coords=C, disp=D, basis=B, frame=F, regimes=np.asarray(regimes),
types=w.types, K=K, cfg=cfg)
def _basis(coords: torch.Tensor, types: torch.Tensor, cfg: ParticleConfig) -> torch.Tensor:
"""B[i, c] = dt * sum_{j : t_j = c} kern(r_ij) r_ij, the message the coupling multiplies."""
r = wrapped_diff(coords)
kern = torch.exp(-(r ** 2).sum(-1) / cfg.sigma ** 2)
kern.fill_diagonal_(0.0)
wr = cfg.dt * kern[:, :, None] * r # (N,N,2)
onehot = nn.functional.one_hot(types, cfg.n_types).to(wr.dtype) # (N, n_types)
return torch.einsum("ijd,jc->icd", wr, onehot) # (N, n_types, 2)
def _frame(coords: torch.Tensor, types: torch.Tensor, cfg: ParticleConfig) -> torch.Tensor:
"""Everything one frame says about the configuration, per entity and neighbour type.
The message basis `B` is a first moment and is therefore blind to arrangement that
cancels by symmetry -- a ring of same-type neighbours contributes almost nothing to
`B` however tight it is. Since `L = 1` is the present-only baseline the whole
history gain is measured against, it must not be handicapped by that blindness, so
the frame also carries the two rotation-invariant scalars per neighbour type: the
kernel mass (how much of type c is nearby) and the kernel-weighted spread (how far
out it sits). `L = 1` and `L = 40` see the same per-frame features.
"""
r = wrapped_diff(coords)
d2 = (r ** 2).sum(-1)
kern = torch.exp(-d2 / cfg.sigma ** 2)
kern.fill_diagonal_(0.0)
onehot = nn.functional.one_hot(types, cfg.n_types).to(r.dtype) # (N, n_types)
B = torch.einsum("ijd,jc->icd", cfg.dt * kern[:, :, None] * r, onehot) # (N, n_types, 2)
mass = kern @ onehot # (N, n_types)
spread = (kern * d2) @ onehot # (N, n_types)
return torch.cat([B.reshape(len(r), -1), mass, spread], dim=-1)
def det(world: dict, regimes: np.ndarray) -> torch.Tensor:
"""The deterministic displacement each step would have had under `regimes[t]`."""
krow = world["K"][torch.as_tensor(regimes)][:, world["types"], :] # (T, N, n_types)
return torch.einsum("tic,ticd->tid", krow, world["basis"])
def _check_basis(world: dict) -> float:
"""Self-check: the basis must reproduce the world's own dynamics up to the noise.
The analogue of `ceilings.py`'s row A. If this residual is not the noise variance
then `B` is not the world's message basis and every number below is meaningless.
"""
resid = float(((det(world, world["regimes"]) - world["disp"]) ** 2).mean())
floor = world["cfg"].noise ** 2
assert abs(resid - floor) < 0.03 * floor, f"basis residual {resid:.3e} != noise^2 {floor:.3e}"
return resid
# -- features --------------------------------------------------------------------
def features(world: dict, L: int, kind: str) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
"""(X, y, t_index) for every step at which a full window of L observations exists.
Rows are per entity: X has shape (T', N, F). `y` is the regime at the step being
decoded. The window at step t covers observations t-L+1 .. t, i.e. displacements
t-L+1 .. t-1 -- never `d_t`.
"""
B, D = world["basis"].numpy(), world["disp"].numpy()
Fr = world["frame"].numpy()
T, N, C, _ = B.shape
ts = np.arange(L - 1, T)
onehot = nn.functional.one_hot(world["types"], C).numpy().astype(np.float64) # (N, C)
if kind == "raw":
cols = []
for k in range(L): # the per-frame features at each step
cols.append(Fr[ts - (L - 1) + k])
for k in range(L - 1): # the displacements the observer has seen
cols.append(D[ts - (L - 1) + k])
cols.append(np.broadcast_to(onehot, (len(ts), N, C)))
X = np.concatenate(cols, axis=-1)
elif kind == "phys":
# the sufficient statistics of the Gaussian likelihood, summed over the window,
# interacted with the entity's own type so the per-type coupling row is separable
db = np.zeros((len(ts), N, C))
bb = np.zeros((len(ts), N, C * (C + 1) // 2))
for k in range(L - 1):
s = ts - (L - 1) + k
db += np.einsum("tid,ticd->tic", D[s], B[s])
pairs = [(a, b) for a in range(C) for b in range(a, C)]
bb += np.stack([np.einsum("tid,tid->ti", B[s][:, :, a], B[s][:, :, b])
for a, b in pairs], axis=-1)
stats = np.concatenate([db, bb], axis=-1) # (T', N, C + C(C+1)/2)
X = (stats[:, :, None, :] * onehot[None, :, :, None]).reshape(len(ts), N, -1)
else:
raise ValueError(kind)
return X.astype(np.float64), world["regimes"][ts], ts
# -- decoders --------------------------------------------------------------------
def _standardise(X: np.ndarray, cut: int) -> np.ndarray:
flat = X[:cut].reshape(-1, X.shape[-1])
mu, sd = flat.mean(0), flat.std(0) + 1e-12
return np.concatenate([(X - mu) / sd, np.ones(X.shape[:2] + (1,))], axis=-1)
def _fit_lsq(X: np.ndarray, y: np.ndarray, R: int, ridge: float = 1e-6) -> np.ndarray:
G = X.T @ X
lam = ridge * np.trace(G) / X.shape[1]
return np.linalg.solve(G + lam * np.eye(X.shape[1]), X.T @ np.eye(R)[y])
def _fit_logit(X: np.ndarray, y: np.ndarray, R: int, l2: float = 1e-6) -> np.ndarray:
"""Multinomial logistic, LBFGS with strong Wolfe -- as `frozen.py` fits its probe.
Least squares onto a one-hot target is a poor classifier on the physics statistics,
which are products of small numbers and heavy-tailed; it understates what the
feature set can express. The `phys` set is meant to be a fair stand-in for optimal,
so it gets the estimator that actually maximises the classification objective.
X already carries the bias column, so no separate intercept.
"""
Xt, yt = torch.tensor(X), torch.tensor(y, dtype=torch.long)
W = torch.zeros(X.shape[1], R, dtype=torch.float64, requires_grad=True)
opt = torch.optim.LBFGS([W], max_iter=300, tolerance_grad=1e-12,
line_search_fn="strong_wolfe")
def closure():
opt.zero_grad()
loss = nn.functional.cross_entropy(Xt @ W, yt) + l2 * (W[:-1] ** 2).sum()
loss.backward()
return loss
opt.step(closure)
return W.detach().numpy()
def _fit_mlp(X: np.ndarray, y: np.ndarray, R: int, hidden: int = 128, epochs: int = 40,
seed: int = 0) -> callable:
"""Two-layer MLP -- the capacity check the brief asks for before concluding.
A linear probe that never rises is not evidence the regime is unidentifiable, so
the raw feature set is also given a nonlinear decoder. Full-batch Adam; the split
is a time suffix, so there is no shuffling to seed beyond the initialisation.
"""
torch.manual_seed(seed)
net = nn.Sequential(nn.Linear(X.shape[1], hidden), nn.ReLU(),
nn.Linear(hidden, hidden), nn.ReLU(), nn.Linear(hidden, R)).double()
Xt, yt = torch.tensor(X), torch.tensor(y, dtype=torch.long)
opt = torch.optim.Adam(net.parameters(), lr=3e-3, weight_decay=1e-5)
n, bs = len(Xt), 4096
g = torch.Generator().manual_seed(seed)
for _ in range(epochs):
perm = torch.randperm(n, generator=g)
for i in range(0, n, bs):
idx = perm[i:i + bs]
opt.zero_grad()
nn.functional.cross_entropy(net(Xt[idx]), yt[idx]).backward()
opt.step()
net.eval()
return lambda Z: net(torch.tensor(Z)).detach().numpy()
def decode(X: np.ndarray, y: np.ndarray, n_regimes: int, estimator: str,
split: float = SPLIT, n_null: int = 10, seed: int = 0) -> dict:
"""Fit on a time prefix, score on the suffix, with chance measured by two nulls.
Reported twice: `entity` is one classification per entity per step, `step` pools
the N entities of a step by averaging their scores -- what an observer watching
the whole world would do. The regime is a global variable, so `step` is the
domain-level number and `entity` is the one a per-entity memory could hold.
"""
T = X.shape[0]
cut = int(T * split)
Z = _standardise(X, cut)
F = Z.shape[-1]
flat = lambda A: A.reshape(-1, F)
def fit_eval(lab: np.ndarray) -> tuple[float, float]:
ytr = np.repeat(lab[:cut, None], X.shape[1], 1).reshape(-1)
if estimator in ("lsq", "logit"):
fit = _fit_lsq if estimator == "lsq" else _fit_logit
W = fit(flat(Z[:cut]), ytr, n_regimes)
s = (flat(Z[cut:]) @ W).reshape(T - cut, X.shape[1], n_regimes)
elif estimator == "mlp":
f = _fit_mlp(flat(Z[:cut]), ytr, n_regimes, seed=seed)
s = f(flat(Z[cut:])).reshape(T - cut, X.shape[1], n_regimes)
else:
raise ValueError(estimator)
ent = float((s.argmax(-1) == lab[cut:, None]).mean())
step = float((s.mean(1).argmax(-1) == lab[cut:]).mean())
return ent, step
ent, step = fit_eval(y)
rng = np.random.default_rng(seed)
shuf, shift = [], []
for _ in range(n_null):
shuf.append(fit_eval(rng.permutation(y)))
k = int(rng.integers(T // 10, T - T // 10))
shift.append(fit_eval(np.roll(y, k)))
return dict(estimator=estimator, acc_entity=ent, acc_step=step,
chance_entity=float(np.mean([a for a, _ in shuf])),
chance_step=float(np.mean([b for _, b in shuf])),
shift_entity=float(np.mean([a for a, _ in shift])),
shift_step=float(np.mean([b for _, b in shift])),
n_test=T - cut, n_features=F)
def bayes(world: dict, L: int, split: float = SPLIT) -> dict:
"""Exact Gaussian likelihood over the window, with the true coupling matrices given.
No fitting, so no train split is needed; it is scored on the same test suffix the
fitted decoders use so the numbers sit in one column. This is the floor on `T_id`:
a decoder that knows the generative model exactly, including the four candidate
matrices, and assumes the regime is constant across the window.
"""
B, D = world["basis"], world["disp"]
T, N = B.shape[0], B.shape[1]
ts = np.arange(L - 1, T)
K = world["K"][:, world["types"], :] # (R, N, n_types)
resid = np.zeros((len(ts), N, K.shape[0]))
for k in range(L - 1):
s = torch.as_tensor(ts - (L - 1) + k)
pred = torch.einsum("ric,ticd->rtid", K, B[s]) # (R, T', N, 2)
resid += ((pred - D[s][None]) ** 2).sum(-1).permute(1, 2, 0).numpy()
y = world["regimes"][ts]
cut = int(len(ts) * split)
sc = -resid[cut:]
return dict(estimator="bayes", acc_entity=float((sc.argmax(-1) == y[cut:, None]).mean()),
acc_step=float((sc.sum(1).argmax(-1) == y[cut:]).mean()),
n_test=len(ts) - cut)
def switch_fraction(world: dict, L: int) -> float:
"""Fraction of decoded steps whose window spans a regime change.
A window longer than the regime lasts contains two regimes, and a decoder that
assumes one is then mis-specified. This is the mechanism behind `T_z < T_id`, so
it is reported alongside every accuracy.
"""
g = world["regimes"]
ts = np.arange(L - 1, len(g))
return float(np.mean([g[t - L + 1:t + 1].min() != g[t - L + 1:t + 1].max() for t in ts]))
# -- driver ----------------------------------------------------------------------
def run(seed: int, steps: int, Ls: tuple[int, ...], t_min: int, t_max: int,
estimators: tuple[str, ...]) -> list[dict]:
cfg = ParticleConfig(seed=seed, t_min=t_min, t_max=t_max)
world = rollout(cfg, steps)
resid = _check_basis(world)
out = []
for L in Ls:
row = dict(seed=seed, L=L, t_min=t_min, t_max=t_max, steps=steps,
basis_residual=resid, switch_frac=switch_fraction(world, L), decoders={})
for kind, est in (("raw", "lsq"), ("raw", "mlp"), ("phys", "logit")):
tag = {"raw/lsq": "lin", "raw/mlp": "mlp", "phys/logit": "phys"}[f"{kind}/{est}"]
if tag not in estimators:
continue
if kind == "phys" and L == 1:
continue # no displacement observed yet: the likelihood has no terms
X, y, _ = features(world, L, kind)
# the MLP is refit from scratch for every null, so its chance level is
# measured on fewer draws than the linear decoders' ten
row["decoders"][tag] = decode(X, y, cfg.n_regimes, est, seed=seed,
n_null=2 if est == "mlp" else 10)
if "bayes" in estimators and L > 1:
row["decoders"]["bayes"] = bayes(world, L)
out.append(row)
return out
def table(results: list[dict], which: str = "step") -> str:
by: dict[int, list[dict]] = {}
for r in results:
by.setdefault(r["L"], []).append(r)
tags = ["lin", "mlp", "phys", "bayes"]
head = "".join(f"{t:>18}" for t in tags)
lines = [f"per-{which} accuracy (chance in brackets), means over seeds",
f"{'L':>3}{'sw.frac':>9}{head}", "-" * (12 + 18 * len(tags))]
for L in sorted(by):
rs = by[L]
cells = ""
for t in tags:
got = [r["decoders"][t] for r in rs if t in r["decoders"]]
if not got:
cells += f"{'--':>18}"
continue
acc = statistics.fmean(g[f"acc_{which}"] for g in got)
ch = [g[f"shift_{which}"] for g in got if f"shift_{which}" in g]
cells += f"{acc:>12.3f}{('[' + format(statistics.fmean(ch), '.3f') + ']') if ch else '':>6}"
lines.append(f"{L:>3}{statistics.fmean(r['switch_frac'] for r in rs):>9.3f}{cells}")
return "\n".join(lines)
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--seeds", default=",".join(map(str, SEEDS)))
ap.add_argument("--steps", type=int, default=STEPS)
ap.add_argument("--Ls", default=",".join(map(str, LS)))
ap.add_argument("--t-min", type=int, default=ParticleConfig().t_min)
ap.add_argument("--t-max", type=int, default=ParticleConfig().t_max)
ap.add_argument("--estimators", default="lin,mlp,phys,bayes")
ap.add_argument("--out", default="results/identify.json")
a = ap.parse_args()
ests = tuple(a.estimators.split(","))
Ls = tuple(int(x) for x in a.Ls.split(","))
results = []
for seed in (int(s) for s in a.seeds.split(",")):
rs = run(seed, a.steps, Ls, a.t_min, a.t_max, ests)
for r in rs:
d = r["decoders"]
msg = " ".join(f"{k}={v['acc_step']:.3f}/{v['acc_entity']:.3f}" for k, v in d.items())
print(f"seed={seed} L={r['L']:<3} sw={r['switch_frac']:.3f} {msg}", flush=True)
results.extend(rs)
Path(a.out).parent.mkdir(parents=True, exist_ok=True)
Path(a.out).write_text(json.dumps(results, indent=1))
print(); print(table(results, "step")); print(); print(table(results, "entity"))
if __name__ == "__main__":
main()
+142
View File
@@ -0,0 +1,142 @@
"""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 _metrics(losses: list[float], switched: list[bool], arousals: list[float], window: int) -> dict:
# metrics on the second half only: the first half is training warm-up
steps = len(losses)
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(
recovery=recovery, steady=steady,
# counts switches in the measured second half only, not the whole run
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 run(name: str, seed: int, steps: int, window: int = 20, bptt: int = 20,
lr: float = 1e-3, hidden: int = 32, kappa: float = 4.0, omega: float = 10.0) -> dict:
spec = dict(CONDITIONS[name])
if spec["kappa"] == KAPPA_FLAG:
spec["kappa"] = kappa
wcfg = ParticleConfig(seed=seed, oracle=spec["oracle"])
if window >= wcfg.t_min:
raise ValueError(
f"window={window} must be < t_min={wcfg.t_min}: a recovery window that reaches "
"the next switch blends two events into one curve"
)
torch.manual_seed(seed)
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, omega=omega, 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)
return dict(condition=name, seed=seed, steps=steps, **_metrics(losses, switched, arousals, window))
def table(results: list[dict]) -> str:
by = {}
for r in results:
by.setdefault(r["condition"], []).append(r)
win = len(results[0]["recovery"]) if results else 0
idxs = [i for i in (0, 2, 5, 10) if i < win] # skip columns the window is too short to have
header = "".join(f"{'rec@' + str(i):>10}" for i in idxs)
lines = [f"{'condition':<18}{'steady':>10}{header}{'a@switch':>10}{'a@steady':>10}",
"-" * (18 + 10 + 10 * len(idxs) + 20)]
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)
row = "".join(f"{m('recovery', i):>10.5f}" for i in idxs)
lines.append(f"{name:<18}{m('steady'):>10.5f}{row}{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("--omega", type=float, default=10.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, omega=a.omega)
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()
+357
View File
@@ -0,0 +1,357 @@
# 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.
The "capacity" row label is `frozen.md`'s and is now known to be a misnomer:
`grp_k0_nostate` is not capacity-matched to `rp_only` (2048 of its 5602 parameters
never train) and the margin is not a parameter count. See `frozen.md` §1c for the
correction; the numbers above are unaffected.
`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.
+401
View File
@@ -0,0 +1,401 @@
# Frozen-weights probe: does memory have a job once learning is out of the picture?
Task 7b. Task 7 measured memory beating memoryless 2.99x at `lr=1e-3` and watched
that margin decay to 1.06x at `lr=1e-2`, so mean error cannot tell state and fast
weights apart. This file removes learning instead of retuning it: train, freeze every
parameter, keep stepping the world. Nothing after the freeze can be attributed to an
optimiser step.
**Verdict: a clean null, twice over. Memory is not doing the work, and neither model
builds an internal regime variable.**
1. Under frozen weights `grp_k0` beats `rp_only` 2.50x on steady error, on 8/8 seeds.
**That margin is the GRP's gated post-RP nonlinearity, not its state — and not its
parameter count either.** The same architecture with the state ablated — an empty
memory handed in each step — measures 2.170e-05 against `grp_k0`'s 2.101e-05.
Memory is worth 1.06x, on 4 seeds out of 8. Its recovery curve is indistinguishable
at every lag. This item originally read "that entire margin is the GRP's extra 4160
parameters"; that attribution was wrong and is corrected in §1d. The null for memory
is unchanged.
2. The regime is decodable from `M` at 0.332 against a measured chance of 0.273. It is
decodable from the memoryless RP's `h` at 0.342 against 0.274. **`M` knows no more
about the regime than the feedforward representation it is built from** — slightly
less — and the same +0.05 appears in a state-free network, so it is a read-off of
the current configuration, not a memory.
3. The mechanism is visible: the gate sits at `g = 0.500 ± 0.029`, never above 0.9,
never below 0.1, on any seed. It is at its initialisation. The GRP as trained here
is not gating anything.
Environment: `experiments/`, `ailed/` unmodified, no default in `particles.py` or
`regime.py` changed. 8 seeds (0-7), 8000 training steps then 4000 frozen steps,
`lr=1e-3`, `bptt=20`, `hidden=32`, `omega=10`, `kappa=0`, `window=20`. Noise floor
`noise² = 4.0e-06`. 40 runs total.
```
uv run python frozen.py --out results/frozen.json
uv run python frozen.py --conditions grp_k0 --ablate-state --out results/frozen_nostate.json
uv run python frozen.py --freeze-affect --no-probes --out results/frozen_affect.json
```
## 0. The freeze audit
Both guards the brief asked for, asserted in code on every run, not checked by eye.
| check | how | result |
|---|---|---|
| no parameter moved | `parameters_to_vector` snapshot before/after the frozen phase, `torch.equal` | **bit-identical on 40/40 runs** |
| nothing could move | `requires_grad=False` on every parameter *and* the whole phase under `torch.no_grad()`, no optimiser constructed | asserted |
| memory kept updating | `min_t max_i |M_t − M_{t−1}|` over the frozen phase | **2.587e-04**, over every grp run |
| the assertion can fail | `test_frozen_phase_detects_a_parameter_change` nudges `out.bias` by 1e-6 after the snapshot | raises, as required |
| `h` is the organism's `h` | `org.grp(h, M_prev, arousal)` must equal the M the organism returned; `org.out(h)` must equal the pred it returned | `torch.equal`, every step of every run |
Mean per-step memory movement is 1.06e-02, four orders above the detection threshold,
so the GRP is running as a GRP throughout. `_train` is a verbatim copy of
`regime.run`'s loop; `test_train_copy_is_identical_to_regime_run` asserts it
reproduces `regime.run`'s metrics exactly, so the frozen phase starts from the
organism Task 7 measured.
Parameter counts: `rp_only` **1442**, `grp_k0` **5602**. The RP is identical in both
(1376); the GRP adds a 64→32 gate and a 64→32 candidate layer, 4160 parameters, 3.9x
the total. These counts are not the story — §1d measures what the count buys, and the
answer is nothing.
## 1. Part A — frozen recovery
Metrics come from `regime._metrics` applied to the frozen phase, so they are
comparable with Task 7's; as there, they are computed on the second half of the phase.
### 1a. The headline, and the control that dissolves it
Frozen-phase `steady`, means over seeds 0-7. `grp_k0_nostate` is `grp_k0` with an
empty memory dict handed to `Organism.forward` every step, in training and in the
frozen phase: identical architecture, identical parameter *tensors*, `M_prev` always
zero. It was originally described here as the capacity-matched feedforward control.
**It is not one** — §1d. The rows below are the measurements; the capacity reading of
them is withdrawn.
```
condition steady sd min max max/min n_params
------------------------------------------------------------------------------
rp_only 5.257e-05 2.924e-05 2.644e-05 1.054e-04 3.99 1442
grp_k0_nostate 2.170e-05 5.155e-06 1.531e-05 2.733e-05 1.78 5602
grp_k0 2.101e-05 6.430e-06 1.426e-05 3.515e-05 2.46 5602
```
Decomposed per seed, which is what carries it:
```
mean median seeds won
capacity rp_only / nostate 2.51x 1.94x 8/8
state nostate / grp_k0 1.06x 1.00x 4/8
```
Per-seed `nostate / grp_k0`: 1.49 0.92 1.33 0.92 0.90 1.08 0.78 1.10. Four above one,
four below. **Removing the state costs nothing.** The same decomposition in the
trained phase gives capacity 3.04x on 16/16 seeds and state 1.19x on 11/16
(mean; medians 2.71x and 1.11x). Those trained-phase figures were re-measured at 16
seeds by Task 8 and supersede the 8-seed values this file originally quoted; the frozen
phase rows above remain 8 seeds. See `a1.md`.
Per-seed frozen `steady`:
```
condition s0 s1 s2 s3 s4 s5 s6 s7
--------------------------------------------------------------------------------------------
rp_only 4.298e-05 3.808e-05 3.098e-05 3.205e-05 1.054e-04 5.585e-05 8.881e-05 2.644e-05
grp_k0_nostate 2.588e-05 1.531e-05 2.665e-05 1.992e-05 1.736e-05 2.545e-05 2.733e-05 1.573e-05
grp_k0 1.742e-05 1.656e-05 2.006e-05 2.170e-05 1.931e-05 2.365e-05 3.515e-05 1.426e-05
```
Note also that the across-seed spread — Task 7's "memory buys reliability" reading —
goes the same way. `grp_k0_nostate` has the *tightest* spread of the three (1.78x
max/min, against `grp_k0`'s 2.46x). Reliability goes with the gated head too — not
with the parameter count; see §1d.
### 1b. The recovery shape: the prediction under test fails
Raw `recovery[k]`, frozen phase, means over seeds:
```
condition rec@0 rec@5 rec@10 rec@19 steady
-------------------------------------------------------------------
rp_only 5.506e-05 7.311e-05 8.078e-05 6.563e-05 5.257e-05
grp_k0_nostate 2.708e-05 3.749e-05 4.246e-05 2.769e-05 2.170e-05
grp_k0 2.756e-05 3.824e-05 4.311e-05 2.756e-05 2.101e-05
```
`grp_k0` and `grp_k0_nostate` agree to within 2% at every lag. The state changes the
post-switch trajectory not at all.
The brief's prediction was that frozen `rp_only` steps up at each switch and never
comes back down, while frozen `grp_k0` rises and decays. Normalising each seed by its
own steady error before averaging — the only way to compare shapes across conditions
whose floors differ 2.5x:
```
condition @0 @2 @4 @6 @8 @10 @12 @14 @16 @18 @19 peak decay
----------------------------------------------------------------------------------------
rp_only 1.16 1.35 1.49 1.66 1.68 1.59 1.52 1.43 1.38 1.34 1.30 1.69@7 57%
grp_k0_nostate 1.31 1.40 1.54 1.92 2.09 2.06 1.87 1.64 1.46 1.35 1.31 2.13@9 73%
grp_k0 1.42 1.47 1.69 2.06 2.22 2.18 1.97 1.72 1.51 1.40 1.35 2.24@9 72%
```
("decay" is the fraction of the peak excess over steady that is gone by `@19`.)
**The frozen memoryless RP does come back down** — 57% of the way, with no parameter
having moved and no per-entity state to move. And `grp_k0`'s *relative* excursion is
larger, not smaller: it peaks at 2.24x its own floor against the RP's 1.69x, and peaks
two steps later.
The reason is that `recovery[k]` under frozen weights is not measuring the model. At a
switch the particle configuration is equilibrated to the old regime; the new coupling
matrix then drives it somewhere else over the next 10-20 steps. That transient belongs
to the world, and a fixed function of the configuration inherits it. **Under frozen
weights `recovery[k]` measures the world's post-switch transient, not adaptation**, and
the state-ablation row proves it directly: same curve with the state and without it.
### 1c. The RP is not quite static — controlled for
`CONDITIONS["rp_only"]` uses `ctx="affect"`, so `(valence, arousal)` feeds the CPPN.
Affect is updated from `loss.item()` every step and freezing weights does not freeze
it. **A frozen `rp_only` therefore is not a fixed function of the current observation**
as the brief assumed: it retains a 2-d state. Re-running the frozen phase with affect
also pinned at its end-of-training value:
```
condition affect live affect pinned
-------------------------------------------
rp_only 5.257e-05 4.906e-05
grp_k0 2.101e-05 2.057e-05
ratio 2.50x 2.26x (8/8 seeds either way)
```
Removing the RP's last adaptive channel does not rescue the prediction — the RP's
decay gets *stronger* (74% of the excess, up from 57%), confirming the decay is the
world's, not affect's.
### 1d. Correction: the control is not capacity-matched, and the margin is not capacity
This section replaces the "capacity, not memory" reading above. Three measurements,
all at the settings this file already uses (8000 train + 4000 frozen steps, `lr=1e-3`,
`bptt=20`, `omega=10`, `kappa=0`, frozen-phase `steady`).
**(i) 2048 of the 5602 parameters never train.** With `M_prev ≡ 0` the gate and
candidate layers both see `[h ‖ 0]`, so the second half of each input weight matrix is
multiplied by zero and receives exactly no gradient. Trained `grp_k0` stateless for
8000 steps and diffed every block against its initialisation: `gate.weight[:, 32:]`
and `cand.weight[:, 32:]` (1024 parameters each) come out at max |Δ| **exactly 0.0**,
while every other block moved (max |Δ| 0.035–0.091). The honest effective count for
`grp_k0_nostate` is **3554**, not 5602.
**(ii) It is a different network, not the same network minus state.** With `M_prev = 0`
the update `M ← (1−g)·M̃ + g·M` collapses to
```
M = (1 − σ(W_g[h‖0])) · tanh(W_c[h‖0])
```
— a two-layer gated feedforward head on `h`, with no recurrence and no BPTT path
through state. The original conclusion needed this control to be *the same network with
memory deleted*; it is instead *a simpler, better-conditioned network that happens to
share tensor shapes*. That is the difference between "the extra parameters explain the
margin" and "this particular feedforward head explains the margin".
**(iii) A genuinely parameter-matched memoryless model does not close the gap.** The
decisive check the original section never ran: widen `rp_only` until it has ≈5602
parameters and compare it against `grp_k0`. Two knobs, 8 seeds each, frozen `steady`:
```
condition params mean grp_k0 wins per-seed ratio vs grp_k0
--------------------------------------------------------------------------------------
rp_only D=32 1442 5.257e-05 8/8 2.47 2.30 1.54 1.48 5.46 2.36 2.53 1.85
rp_only D=86 3548 3.915e-05 8/8 1.57 1.33 1.36 1.38 2.33 1.05 2.88 2.48
rp_only D=139 5615 1.046e-04 7/8 1.82 6.84 1.41 1.33 2.07 0.99 15.5 1.86
rp_only cppn_hidden=141 5584 7.195e-05 8/8 5.58 2.51 2.78 2.08 6.13 1.67 3.84 3.02
grp_k0_nostate 5602 2.170e-05 4/8 1.49 0.92 1.33 0.92 0.90 1.08 0.78 1.10
grp_k0 5602 2.101e-05 —
```
Reproduction: `frozen.py`'s CLI exposes neither width knob, so these rows came from a
throwaway driver that calls `frozen._train` and `frozen._frozen` unchanged against an
`Organism(hidden_dim=..., cppn_hidden=...)` built in `_build`'s exact order, so the RNG
stream matches. No file in `experiments/` or `ailed/` was modified. The driver is pinned
by reproducing `grp_k0_nostate` seed 0 at 2.588e-05, bit-for-bit the value in §1a's
per-seed table.
D=86 is matched to the *effective* 3554; D=139 and `cppn_hidden=141` to the nominal
5602. **Parameter-matched by either knob, the memoryless RP gets worse, not better** —
D=139 means 1.046e-04 against the 1442-parameter RP's 5.257e-05 — and `grp_k0` still
wins 7/8 or 8/8 seeds at every width tried. Only `grp_k0_nostate`, which adds the gated
head rather than width, closes it.
**The corrected claim.** The 2.5x margin is *not* capacity: capacity added as RP width
makes the memoryless model worse. The margin comes from the gated post-RP nonlinearity
`(1−σ(W_g[h‖0]))·tanh(W_c[h‖0])`, which `grp_k0_nostate` supplies with no memory at
all. **The null for memory is unchanged and if anything sharper**: state is still worth
1.06x on 4/8 frozen and 1.19x on 11/16 trained, and the mechanism that does the work is
the gate acting as a nonlinearity, not as a memory controller.
*Limitation, stated rather than tuned.* The wide `rp_only` runs use this file's
`lr=1e-3` and 8000-step budget unchanged, and a wider model may be lr- or init-limited
at that budget. Two of the D=139 seeds destabilise outright — seed 1 at 1.133e-04 and
seed 6 at 5.451e-04, against a same-condition median of 3.0e-05 — so the D=139 mean is
carried by those two and should be read as instability, not as a clean loss. They are
reported and not tuned: retuning a baseline until it catches up changes the question
instead of answering it (`AGENTS.md`). What the runs establish is the negative — added
width does not buy the margin — not a tight estimate of how a well-tuned wide RP would
do.
## 2. Part B — what does the state know?
Linear decode from a per-entity representation to the world's regime id. Test split is
the last 30% of the frozen phase, taken as a suffix in time so the probe cannot
memorise adjacent steps: 2800 training steps × 16 entities = 44 800 samples, 1200 test
steps, ~20 switches per seed.
Chance is measured, not assumed. Two nulls, each refitting the probe from scratch:
`shuffle` permutes the step labels (keeping a step's 16 entities together), `shift`
circularly shifts the label sequence, which also preserves each regime's 40-80 step
block structure and is therefore the stricter of the two — a probe that merely tracks
slow drift still scores at the `shift` level. Both land near 0.27, above the naive
1/4 = 0.25, which is exactly why the brief asked for it to be measured.
```
representation acc shuffle shift gap seeds > chance
---------------------------------------------------------------------------------
rp_only h, least squares 0.342 0.289 0.274 +0.067 8/8
rp_only h, logistic 0.341 0.289 0.276 +0.065 8/8
rp_only h, entity-centred0.341 0.289 0.274 +0.067 8/8
grp_k0 h, least squares 0.338 0.292 0.274 +0.065 7/8
grp_k0 h, logistic 0.344 0.299 0.275 +0.069 7/8
grp_k0 M, least squares 0.332 0.287 0.273 +0.058 7/8
grp_k0 M, logistic 0.332 0.293 0.276 +0.056 7/8
grp_k0 M, entity-centred0.333 0.287 0.273 +0.060 7/8
grp_k0_nostate M, least squares 0.325 0.288 0.275 +0.050 --
```
**The claim under test fails.** The regime is weakly decodable from `M` — and equally
weakly decodable from the memoryless RP's `h`, and from the `h` inside the very same
GRP organism, which is the comparison that holds the weights fixed. `M` is
consistently the *worst* of the three. The GRP's state has not built a regime variable;
it has not even preserved as much regime information as the layer feeding it.
The last row settles what the +0.05 is: the state-ablated GRP, whose `M` is a fixed
function of the current `h` with nothing carried between steps, decodes at 0.325. The
signal is an instantaneous read-off of the particle configuration — the field the
regime is currently imposing is visible in `r` right now — not something a memory
accumulated.
Three ways the null was stressed, none of which changes it:
- **Estimator.** Multinomial logistic (LBFGS, strong Wolfe) matches least squares to
within 0.006 everywhere. Not a least-squares artefact.
- **Entity identity.** `M` is dominated by stable per-entity structure (the particle's
type). Subtracting each entity's own train-split mean, in case a regime code hides
under that offset, moves accuracy by ≤0.002.
- **Target.** The regime id is an arbitrary label over four random coupling matrices;
what entity *i* actually needs is its own row `k[t_i, :]` of the current one. Probing
each of the three signed entries as a 3-class problem, against measured chance:
```
representation acc chance gap above chance
-------------------------------------------------------
rp_only h 0.514 0.488 +0.025 20/24
grp_k0 h 0.517 0.484 +0.033 22/24
grp_k0 M 0.506 0.482 +0.024 21/24
```
Same picture on the target the domain actually rewards: `M` last, `h` no worse.
### Adaptation latency
Reported for completeness and not interpretable. Decoding the regime per step by
averaging the 16 entities' probe scores, the mean number of steps from a switch to the
first correct decode is 12.0 for `M` and 10.7 for `rp_only`'s `h` — but 40 of 164
switches never decode correctly before the next switch arrives. **A latency measured
off a probe running 5 points above chance is measuring the probe's noise.** The honest
statement is that neither representation supports reliable regime decoding, so neither
has a measurable adaptation latency by this route.
## 3. What the state is doing instead
The gate, measured over every frozen step and entity:
```
condition mean g sd frac g>0.9 frac g<0.1
---------------------------------------------------------
grp_k0 0.500 0.029 0.000 0.000
grp_k0_nostate 0.509 0.025 0.000 0.000
```
`g = σ(W_g[h‖M] − κa)` with `κ = 0`. A mean of 0.500 with sd 0.029 and no saturation
in either direction, on every seed, means the gate's pre-activation is sitting at zero:
it is at its initialisation and 8000 training steps have not moved it. The update
`M ← (1−g)M̃ + gM` degenerates to a fixed 50/50 blend — a two-step exponential moving
average of `tanh(W_c[h‖M])`, with no input dependence. **Nothing is being decided about
what to keep.**
Persistence confirms there is no long integration to point at. Lag-1 autocorrelation
and the lag at which it falls below 1/e, per channel:
```
condition rep lag-1 tau
--------------------------------------
rp_only h 0.964 18.1
grp_k0 h 0.960 14.0
grp_k0 M 0.980 13.6
grp_k0_nostate M 0.959 13.1
```
`M` is marginally smoother at lag 1 than the `h` it is built from, and *less* persistent
over the 1/e horizon than the memoryless RP's own `h`. Representations in this domain
are slow because the world is slow, not because anything is integrating them.
## 4. Which one understands the domain?
**Neither, and the question does not currently have a mechanism to attach to.**
There is no evidence in this experiment that either model has come to represent which
regime the world is in. The regime is weakly present in both models' representations at
about +0.05 over a measured chance of 0.27, and it is present in exactly the same
amount in a network with no state at all, which identifies it as an instantaneous
read-off of the visible configuration rather than an internal variable either organism
built.
What the frozen probe does establish, and it is worth having:
- **The margin is real and it is not a learning-rate artefact.** With every weight
bit-frozen, the gated architecture predicts 2.5x better than the plain relational
perceptron, on 8 seeds out of 8. Task 7's `lr` objection is answered: no optimiser
step is available to either model here.
- **The margin is not memory.** It is 4160 extra feedforward parameters. Ablating the
state while keeping them preserves the entire effect (1.06x, 4/8 seeds) and leaves
the recovery curve unchanged at every lag.
- **The GRP's gate is untrained.** It sits at 0.5 with no input dependence, which is a
sufficient mechanistic explanation for both nulls and is a fact about this setup, not
about the architecture.
The last point is the actionable one. This is a measured null about *this* domain and
*this* training budget, not an impossibility result. The gate never learned to gate,
and §1b explains why it had no reason to: the post-switch error is dominated by the
world's own configuration transient, which no amount of state can shorten. A domain
where regime identity is worth something to a per-entity state — where the transient is
short and the ambiguity is long — would give the gate a job. This one does not, which
is the same conclusion §6(c) of `headroom.md` reached from the other direction.
## 5. Consequences for A1
- **Do not claim A1 as a memory result on this domain.** The frozen-weights version of
the comparison, which is the strongest form available, attributes the margin to
capacity. Any A1 comparison of `rp_only` to `grp_k0` is confounded 3.9x on parameter
count and needs `grp_k0_nostate` alongside it, in the trained setting too, where the
same decomposition gives capacity 3.04x on 16/16 seeds and state 1.19x on 11/16
(medians 2.71x and 1.11x, re-measured at 16 seeds by Task 8; see `a1.md`).
- **Task 7's requirement 2 inherits this.** The 2.99x at `lr=1e-3` and the
frozen-*regime* reliability argument in `headroom.md` §5 were both measured without a
capacity control. Neither is safe to quote as a memory claim as it stands. The
frozen-regime runs should be re-run with `grp_k0_nostate` before §5's "memory reaches
the floor every time" sentence is carried into the paper.
- **`recovery[k]` is not an adaptation measurement in this domain.** It tracks the
world's post-switch transient, and a stateless frozen model reproduces its shape. Any
A1 claim phrased on recovery curves needs a different observable.
+345
View File
@@ -0,0 +1,345 @@
# Headroom check for the regime setup
Task 7. This file is the audit trail for the paper's setup section: it records what
was measured, which of the three requirements held, every knob that was moved with
its before/after, and the conclusion.
**Verdict: requirement 2 holds but is substantially an artefact of an under-tuned
learning rate; requirements 1 and 3 fail. The regime oracle is neutral — it is read,
and it changes nothing. The error every condition converges to is set by tracking a
target that switches every 40-80 steps, not by missing information.**
Environment: `experiments/`, `ailed/` unmodified. All runs `uv run` from
`experiments/`. Noise floor for every table below is `noise² = 4.0e-06`.
Section 3's fits are reproducible with `uv run python ceilings.py`.
## 1. The table
`uv run python regime.py --conditions rp_only,grp_k0,grp_regime,rp_flag --seeds 0,1,2 --steps 8000 --out results/headroom.json`
Means over seeds 0,1,2. `(sd)` is the across-seed standard deviation of `steady`.
```
condition steady (sd) rec@0 rec@2 rec@5 rec@10 a@switch
---------------------------------------------------------------------------------------------
rp_only 0.000061 0.000020 0.000070 0.000080 0.000103 0.000090 0.130
grp_k0 0.000021 0.000004 0.000028 0.000031 0.000045 0.000043 0.127
grp_regime 0.000029 0.000006 0.000052 0.000054 0.000067 0.000057 0.203
rp_flag 0.000060 0.000024 0.000280 0.000110 0.000120 0.000095 0.422
```
Per-seed `steady`, because the across-seed spread is comparable to the effects being
claimed and the paired comparison is what carries the result:
```
condition seed 0 seed 1 seed 2 grp_k0 beaten?
rp_only 8.09e-05 6.17e-05 4.17e-05 no (0/3)
grp_k0 2.39e-05 1.67e-05 2.11e-05 --
grp_regime 3.51e-05 2.38e-05 2.77e-05 no (0/3, worse on every seed)
rp_flag 6.13e-05 3.65e-05 8.36e-05 no (0/3)
```
## 2. The three requirements
### Requirement 1 — FAILS
> `grp_regime` steady error must sit near the noise floor `4e-6` (within ~3x).
`grp_regime` steady is 2.9e-05, 7x the floor, and it is *worse* than `grp_k0`
(2.1e-05) on all three seeds. Longer training does not rescue it: at 40 000 steps it
is still worse on all three seeds (1.7e-05 vs 1.5e-05).
The condition is not reached at any setting tried here, and §3 shows the regime is not
where the missing information is. But this is a measured failure, not an impossibility
result — with the regime *frozen* the same architecture reaches 5.08e-06, 1.27x the
noise floor (§5). What blocks requirement 1 is the switching, not the oracle.
### Requirement 2 — HOLDS at the default, but the margin is largely an `lr` artefact
> `grp_k0` must beat `rp_only` on `steady` and on `rec@10`.
At the default `lr=1e-3`, 8000 steps: `grp_k0` beats `rp_only` 2.9x on steady and
2.1x on `rec@10`, on every seed. It still wins on all three seeds at 40 000 steps.
**But the margin decays monotonically with learning rate and is gone by `lr=1e-2`**
(seeds 0,1,2, 8000 steps, mean `steady`):
```
lr rp_only grp_k0 grp_regime memory advantage
1e-3 6.141e-05 2.055e-05 2.888e-05 2.99x
3e-3 3.189e-05 1.627e-05 1.840e-05 1.96x
1e-2 1.681e-05 1.584e-05 1.534e-05 1.06x
```
`rp_only` improves 3.7x with `lr`; `grp_k0` improves 1.3x. **Memory is substantially
compensating for an optimiser that is stepping too slowly**, and A1 cannot quote the
2.99x without saying it is measured at a learning rate at which the memoryless
baseline is not converged. (At `lr=1e-2` `grp_regime` is nominally best at 1.534e-05,
but the three conditions are within 3% of each other and of the 40 000-step plateau;
that ordering is noise, not an oracle effect.)
The same caveat applies to `omega`, more weakly: the advantage is 2.99x at `omega=10`
and 1.5x at `omega=5`, because `omega` strongly affects `rp_only` and not `grp_k0`.
Requirement 2 holds as written. It should not be reported without both ablations.
### Requirement 3 — FAILS
> `rp_flag` must equal `rp_only` within seed noise on every column.
It does not. `rp_flag` matches `rp_only` on `steady` (6.0e-05 vs 6.1e-05) but is 4x
worse at `rec@0` (2.8e-04 vs 7.0e-05), on every seed.
It is **not** an information leak. Diagnostic, holding `attr_dim` at 4 in all three
flag rows so parameter count and init draw are identical and only the column's
*contents* change:
```
variant steady rec@0 rec@2 rec@5
----------------------------------------------------------------------
rp_only (attr_dim=3) 0.000061 0.000070 0.000080 0.000103
rp_flag flag fires 0.000060 0.000280 0.000110 0.000120
rp_flag flag always 0 0.000071 0.000071 0.000076 0.000096
rp_flag flag always 1 0.000133 0.000134 0.000166 0.000179
```
With the column present but never firing, `rp_flag` reproduces `rp_only`; the extra
column is harmless. With it pinned on, everything degrades uniformly. The `rec@0`
spike is caused by the column *changing value*, at the exact step `rec@0` measures.
Mechanism. `attrs` enters the RP only through `f_j = W_feat attrs_j`, the message
*from* `j`, and the flag column is the same value on every particle, so firing it
shifts every message by a fixed `(Σ_j m_ij) ⊙ w_flag`. The flag column is **not**
under-trained relative to the type columns — measured, `attr_dim=4`, seed 0:
```
type cols flag col
W_feat init norm 1.831 1.607 1.461 1.893
drift over 8000 0.152 0.119 0.157 0.134
```
and with `bptt=20` the flag falls within **32%** of optimiser steps even though it is
on for only 1.6% of individual steps. The operative fact is the other one: its random
init has norm 1.89, *comparable to a type embedding*, and it fires too rarely for the
rest of the network to have absorbed it. So when it fires it injects a
type-embedding-sized perturbation into every message, precisely where `rec@0` looks.
This matters beyond the control: **`grp_flag` is an A1 condition with the same
defect.** As encoded it does not test "does knowing a change occurred help"; it tests
"does memory absorb an input spike". §6(a) fixes it.
## 3. Where the information sits — a linearised bound, not a bound on the model
Reproduce with `uv run python ceilings.py`. The script fits, by least squares over a
rolled-out world, the best predictor of the form
`d_i = a[offset(i)] + Σ_j c[key(i,j)] · dt · kern(r_ij) · r_ij`, handing the fit the
radial kernel exactly. Means over seeds 0,1,2, 1200 world steps:
```
information set MSE(det part) MSE(vs target)
-----------------------------------------------------------------------
A perfect: (regime, t_i, t_j) 1.262e-19 4.011e-06
B regime-blind, pair-aware (t_i, t_j) 1.298e-05 1.694e-05
C regime oracle (regime, t_j) 7.684e-06 1.166e-05
D no oracle (t_j) 1.427e-05 1.820e-05
oracle prize D->C: 1.86x on the deterministic part, 1.56x against the noisy target
```
Row A is the self-check, and the script asserts it: given `(regime, t_i, t_j)` the
family spans the dynamics exactly (residual 1.3e-19) and lands on 4.011e-06, the noise
floor. (An earlier version of this table read 4.52e-06 for row A. That was a bug: the
fit captured `world.regime` *before* `step()`, but `step()` switches the regime before
computing the delta, so ~1.7% of rows carried a stale regime. Fixed in `ceilings.py`;
the corrected row A landing on the floor is what confirms it.)
**Scope — this is not a bound on the trained architecture.** The fitted family is
linear in the messages. The real RP applies `tanh` to the aggregate, which turns the
`t_i`-carrying self-term (`j = i` at `r = 0`, since the default `mask` includes the
diagonal) into a *gain modulation* on the whole sum rather than a bare additive
offset, and the GRP adds per-entity state on top. An earlier draft of this file said
the receiver's own type "can never modulate the per-neighbour message" and concluded
requirement 1 was unreachable in principle. That was an overclaim: true of the linear
family, false of the composed model. **Every "cannot" of that kind is withdrawn.**
Read the table as a map of where the information sits, not as a statement about what
the architecture can reach.
(For the record, the frozen-regime runs do not by themselves demonstrate a violation
of rows C and D: memoryless `rp_only` frozen reaches 4.964e-06 on seed 0, but C and D
were fit on a *switching* world, where regime-blindness costs something, so that is
not a like-for-like comparison. Refitting the `t_i`-blind ceiling on a frozen world
gives 4.571e-06, and 4.964e-06 sits above it. The reframing above rests on the
linearity of the family, which is reason enough.)
What the table does support:
1. **The oracle prize is small.** No oracle (D, 1.820e-05) to regime oracle
(C, 1.166e-05) is worth **1.56x**, and `grp_k0` already measures 1.5e-05 at
40 000 steps — already inside that band. Memory recovers most of what the regime
oracle could say, which is why saying it adds nothing.
2. **The regime is not the scarce information.** B (1.694e-05, knows `t_i,t_j`, not
the regime) and C (1.166e-05, knows the regime, not `t_i`) bracket each other and
neither approaches A. A regime oracle cannot supply `t_i`.
## 4. Knobs changed
One thing at a time; same seeds (0,1,2) before and after; every change re-ran the
affected conditions.
| knob | before | after | evidence | kept? |
|---|---|---|---|---|
| `run(omega=...)` in `regime.py` | not a parameter (hard-coded 10.0) | parameter, **default 10.0** | plumbing only; default unchanged so all prior runs reproduce | **yes** |
| `omega` value | 10.0 | tried 5, 20 | see below | **no — kept 10.0** |
| `lr` | 1e-3 | tried 3e-3, 1e-2 | §2 requirement 2 | **no — kept 1e-3** |
| `noise` | 0.002 | tried 0.0005 | see below | **no — kept 0.002** |
| `sigma` | 0.2 | tried 0.3 | see below | **no — kept 0.2** |
| `steps` | 8000 | also 40000 | §2, §5 | diagnostic only |
| `t_min`/`t_max` | 40/80 | frozen (10⁹) | §5 | diagnostic only |
| `edge_types` | `None` (1 type) | tried type-pair (9) | see below | **no** |
**No default in `particles.py` or `regime.py` was changed.** The only source changes
are the `omega` parameter, whose default reproduces previous behaviour exactly, and
the new `ceilings.py`. Tasks 8 and 9 run against the same parameters Task 6 was
reviewed under. `../ailed` is untouched.
### omega — ruled out
`grp_k0` and `grp_regime` are insensitive; only `rp_only` moves, and the ordering
never flips.
```
omega rp_only grp_k0 grp_regime
5 3.0e-05 2.0e-05 2.6e-05
10 6.1e-05 2.1e-05 2.9e-05 <- kept
20 7.7e-05 2.2e-05 3.3e-05
```
### noise and sigma — ruled out, decisively
Cutting `noise` 4x lowers the irreducible floor 16x (4.0e-06 → 2.5e-07) and barely
moves any measured error:
```
noise sigma floor rp_only grp_k0 grp_regime
0.002 0.2 4.0e-06 6.1e-05 2.1e-05 2.9e-05
0.0005 0.2 2.5e-07 5.9e-05 1.8e-05 2.9e-05
0.002 0.3 4.0e-06 7.8e-05 4.3e-05 5.5e-05
0.0005 0.3 2.5e-07 7.1e-05 4.1e-05 5.3e-05
```
At `noise=0.0005` the models sit ~70x above the floor. The residual is model error,
not noise. `grp_regime` is worse than `grp_k0` in all four cells.
### edge_types — helps, does not change the verdict
`regime.py` passes `edge_types=None`, so every pair is edge type 0 and the CPPN never
sees the type pair. Opening it (`t_i * n_types + t_j`, 9 edge types), both arms
measured by the same script:
```
steps edge types rp_only grp_k0 grp_regime
8000 single (1) 6.1e-05 2.1e-05 2.9e-05
8000 pair (9) 3.0e-05 1.9e-05 2.2e-05
40000 single (1) 2.3e-05 1.5e-05 1.7e-05
40000 pair (9) 1.7e-05 1.5e-05 1.6e-05
```
## 5. The control that isolates the cause: freeze the regime
Nothing changed but `t_min`/`t_max`, set beyond the run length so the regime is drawn
once and never switches. 40 000 steps, seeds 0,1,2:
```
regime condition steady per-seed
------------------------------------------------------------------
switching rp_only 2.271e-05 1.390e-05 3.372e-05 2.051e-05
switching grp_k0 1.516e-05 1.113e-05 1.457e-05 1.977e-05
switching grp_regime 1.716e-05 1.256e-05 1.632e-05 2.260e-05
frozen rp_only 3.891e-05 4.964e-06 4.604e-05 6.573e-05
frozen grp_k0 5.119e-06 5.199e-06 4.628e-06 5.529e-06
frozen grp_regime 5.080e-06 5.126e-06 4.679e-06 5.435e-06
```
This is the cleanest result in the file. It separates "the model must infer the
regime" from "the target is non-stationary", which the 40 000-step and edge-type
tables cannot.
- **`grp_k0` goes 1.516e-05 → 5.119e-06 and `grp_regime` 1.716e-05 → 5.080e-06 —
1.27x the noise floor.** The architecture *can* essentially solve this domain. The
entire remaining gap in the switching world is caused by regime switching: not by
noise (§4), not by capacity, not by the missing pair channel.
- **The oracle is neutral here too, as it must be**: frozen, `grp_regime`
(5.080e-06) and `grp_k0` (5.119e-06) are identical. With the regime frozen the
one-hot is a constant carrying zero information, so this is the expected result, and
it confirms the oracle plumbing is inert rather than harmful once the encoding
artefact of §6(a) is out of the way.
- **Memory's job in the frozen world is reliability, not mean error.** `rp_only`
frozen ranges over 13x across three seeds (4.964e-06 to 6.573e-05) while `grp_k0`
is 5.1e-06 ± 0.4e-06. Memoryless can reach the floor and often does not; memory
reaches it every time. This is a different and better-founded case for requirement 2
than the mean-error margin that the `lr` ablation undercuts.
## 6. Conclusion and recommendations
**The regime oracle is neutral in this setup, and requirement 1 is not reached at any
setting tried.** The oracle is read; the information it carries is worth 1.56x within
the linearised family; and the trained models never get close enough to any ceiling
for that to matter, because their error is dominated by tracking a target that
switches every 40-80 steps. Freezing the regime drops `grp_regime` from 2.9e-05 to
5.08e-06, 1.27x the noise floor, with nothing else changed — the switching is the
whole story. `grp_regime` should be reported as a measured null, not carried into A1
as a ceiling.
Requirement 2 holds at the default on every seed and at both budgets, but the 2.99x
margin is substantially an artefact of an under-tuned learning rate: at `lr=1e-2` it
is 1.06x. The defensible version of the memory claim is the frozen-regime one —
memory reaches the noise floor reliably where memoryless does so on one seed in three
— not the mean-error margin at `lr=1e-3`.
**(a) Zero-initialise the oracle columns of `W_feat`.** One line in `regime.py` after
`Organism` is built (`ailed` should not need to know which columns are oracle
columns):
```python
with torch.no_grad():
org.rp.feat.weight[:, wcfg.n_types:] = 0.0 # oracle columns start as a no-op
```
An oracle column then starts as an exact no-op and can only act once gradient has
earned it a weight. Measured, seeds 0,1,2, 8000 steps:
```
init condition steady rec@0 rec@2 rec@5
--------------------------------------------------------------------
default rp_only 0.000061 0.000070 0.000080 0.000103
default rp_flag 0.000060 0.000280 0.000110 0.000120
default grp_regime 0.000029 0.000052 0.000054 0.000067
zero-init oracle cols rp_only 0.000061 0.000070 0.000080 0.000103
zero-init oracle cols rp_flag 0.000076 0.000077 0.000085 0.000105
zero-init oracle cols grp_regime 0.000021 0.000029 0.000034 0.000049
```
`rp_only` is unchanged, but that is a tautology rather than evidence — `rp_only` has
no oracle columns, so the line is a no-op for it by construction. The measured results
are the other two rows: `rp_flag`'s 4x `rec@0` spike disappears and it tracks
`rp_only`, so **requirement 3 holds under this fix**; and `grp_regime` drops from
2.9e-05 to 2.1e-05, exactly equal to `grp_k0`. With the artefact removed, **the regime
oracle is precisely neutral** — not "the oracle hurts", but "the oracle changes
nothing". Not adopted: it moves every oracle condition off what Task 6 was reviewed
under, and A1's condition list may change in response to this file.
**(b) Restate requirement 1 against something measurable.** `noise² = 4e-06` is the
floor for a model that knows `(regime, t_i, t_j)`. Either compare `grp_regime` to the
regime oracle's linearised ceiling (1.166e-05), or — better, since §5 shows the
architecture reaches 5.08e-06 once the regime stops moving — state requirement 1 as a
*recovery* requirement rather than a steady-state one. Steady-state error in this
domain is a tracking measurement, and requirement 1 currently reads as if it were a
capacity measurement.
**(c) If A1 needs an oracle with real headroom, the domain must change.** The prize
(1.56x) is smaller than what the optimiser is losing to tracking (3x, from §5). Widen
the contrast between regimes, slow the switching, or raise `lr` so tracking stops
dominating — and measure the headroom again before building on any of them, since §2
shows `lr` alone reorders the conditions.
+498
View File
@@ -0,0 +1,498 @@
# When does per-entity memory have a job?
Task 9. The project had been reaching for a new domain each time memory failed to
help. This file replaces that reflex with a quantity measurable on any candidate
domain in advance — `T_id`, the history an optimal observer needs to identify the
regime — and with a prediction that can be wrong.
**Verdict, in the order the parts were pre-registered:**
1. **Part 1 — FAILURE, of the informative kind.** Arousal's peak moves from 11 steps
after a switch to **2** (lags 1 and 2 are within 0.005 of each other, 0.303 and
0.308), which is inside the pre-registered 3. The error is
unmoved: `grp_k0 / grp_k` on `steady` is 0.987 (median 1.000) and **0 of 16 seeds
reach 1.10**, against a criterion of 12 of 16. The largest ratio on any seed at any
κ is 1.017. The mechanism works, it is now correctly timed, and the domain gives it
nothing. The lag-2 harm `a1.md` §2a found survives the fix unchanged.
2. **Part 2 — `T_id = 2` observations, i.e. one step of history.** An exact decoder
reaches 0.958 per-step accuracy from a single observed displacement, against a
measured chance of 0.23, and a fitted decoder that knows no coupling matrices
reaches 0.909. Accuracy peaks at `L = 2–3` and *falls* thereafter. With
`T_z = 40–80`, **`T_id` is 20–40 times smaller than `T_z`**. That is the
uncomfortable branch: the domain can reward memory and the failure is ours.
3. **Part 3 — the predicted peak does not exist. The theory is wrong as stated.** The
capacity-controlled state gain is flat across four orders of magnitude of regime
duration, 1.09 to 1.26, on 8–11 seeds of 16 at every duration, with a per-seed
spread (0.32 to 2.86) that swamps every between-duration difference. And the
decisive point: **the largest gain in the sweep is at the frozen regime**, 1.26 on
11/16 — the one setting where there is no regime to identify at all and where `G`
measures exactly 1.00. A quantity that is largest when its supposed cause is absent
is not caused by it.
The condition "memory has a job when `T_id << T_z` and `G` is materially above 1" is
satisfied at every switching duration in this sweep and does not predict the state
gain. What the state gain measures here is temporal smoothing, which a stationary
world rewards at least as well as a switching one.
Environment: `experiments/`, `ailed/` unmodified. No default in `particles.py`,
`regime.py` or `affect.py` changed — `AffectConfig`'s time constants and
`ParticleConfig`'s `t_min`/`t_max` are passed as arguments (`when_memory_works._cfg`,
`frozen._build`). 8000 training steps, `lr=1e-3`, `bptt=20`, `hidden=32`, `omega=10`.
Noise floor `noise² = 4.0e-06`. 400 organism runs. Part 2 fits 4 decoders at each of
7 window lengths on 8 seeds, each linear decoder refit 20 times more to measure its
own chance level.
```
uv run python identify.py --out results/identify.json
uv run python identify.py --t-min 10 --t-max 20 --seeds 0,1,2,3 --steps 4000 \
--estimators phys,bayes --out results/identify_d10_20.json # and each duration
uv run python ceilings.py 1200 0,1,2 10,20 # and each duration
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
```
## 0. What is checked, and how it was made able to fail
Four properties carry the headline numbers. Each has a test, and each test was broken
on purpose to confirm it fails — AGENTS.md's rule, applied rather than asserted.
| property | test | broken on purpose by | fails? |
|---|---|---|---|
| the decoder never sees `d_t`, the step it decodes | `test_features_never_use_the_displacement_being_decoded` | widening the window to include `d_t` | **yes** |
| the state ablation differs only in carried state | `test_state_ablation_changes_only_whether_memory_is_carried` | making `stateless` a no-op in `run_one` | **yes** |
| the arousal profile is the arousal the gate saw | `test_gate_arousal_seq_is_the_arousal_the_organism_was_handed` | companion `..._can_fail` asserts the un-lagged sequence does *not* match | **yes** |
| the message basis is the world's own | `test_basis_reproduces_the_worlds_dynamics_to_the_noise_floor` | companion `test_basis_check_can_fail` feeds it the wrong regime sequence | **yes** |
Alongside those: `test_bayes_decoder_recovers_a_regime_it_can_see_and_not_one_it_cannot`
is the planted-signal/planted-absence pair (real displacements → >0.8, displacements
replaced by noise → <0.45); `test_peak_lag_and_by_lag_average_over_the_switches_metrics_uses`
asserts `by_lag` cuts the trace exactly as `regime._metrics` cuts `recovery`, so the
arousal profile and the error profile are averaged over the same switches;
`test_windows_that_reach_the_next_switch_are_not_reported` enforces `window < t_min`
per duration, which is `regime.run`'s own validation carried into a sweep that
shortens the regime. 64 tests pass, including the 47 that were already there.
The two additive hooks this task needed — `frozen._build(t_min=, t_max=)` and
`frozen._train(acfg=)` — both default to the values the loop always used, so
`test_train_copy_is_identical_to_regime_run` still pins `_train` against `regime.run`.
## 1. Part 1 — affect timing, the last legitimate shot at A1
`rho_a` and `rho_slow` are the affect mechanism's own time constants and had never
been set. Only they can move arousal's timing. From `affect.update`:
```
fast <- fast + rho_fast (loss - fast) slow <- slow + rho_slow (loss - slow)
a_target = tanh(max(0, loss - slow) / (slow + eps))
arousal <- arousal + rho_a (a_target - arousal)
```
`fast` appears only in `v_target`. **`rho_fast` cannot reach arousal except through the
loss stream**, via valence feeding the CPPN, and §1c measures that it does not. So the
sweep is over `rho_a × rho_slow`. Where it raises `rho_slow` past the default
`rho_fast = 0.2` it raises `rho_fast` with it, because `AffectConfig` documents
`rho_slow < rho_fast` and inverting the two would change what valence means as a side
effect of a timing sweep.
### 1a. The sweep: the timing is a design parameter, and it moves
`grp_k0` (κ=0, so this is the arousal the gate *would* be forced with), 8000 steps,
seeds 0–3, means over seeds. Lag `k` after a switch, averaged over the second half's
switches — the same cut `regime._metrics` uses for `recovery`. `far` is `_metrics`'s
own `steady_idx`.
```
rho_a/rho_slow/rho_fast @0 @2 @4 @6 @8 @10 @12 @14 @16 @18 far peak
------------------------------------------------------------------------------------------------------------
a0.5/s0.02/f0.2 (default) 0.055 0.157 0.217 0.257 0.300 0.325 0.329 0.316 0.284 0.243 0.098 11
a0.5/s0.05/f0.2 0.056 0.197 0.256 0.290 0.320 0.323 0.307 0.283 0.236 0.193 0.081 10
a0.5/s0.1/f0.2 0.056 0.227 0.270 0.287 0.291 0.268 0.244 0.216 0.170 0.136 0.065 8
a0.5/s0.2/f0.4 0.054 0.219 0.228 0.221 0.198 0.170 0.149 0.121 0.088 0.077 0.053 4
a0.5/s0.4/f0.8 0.042 0.143 0.118 0.100 0.088 0.081 0.072 0.059 0.043 0.042 0.039 2
a1/s0.02/f0.2 0.046 0.205 0.259 0.284 0.327 0.348 0.342 0.316 0.277 0.232 0.092 10
a1/s0.05/f0.2 0.054 0.254 0.296 0.313 0.336 0.331 0.301 0.266 0.210 0.169 0.078 8
a1/s0.1/f0.2 0.060 0.294 0.301 0.289 0.288 0.253 0.231 0.193 0.147 0.121 0.065 1
a1/s0.2/f0.4 0.063 0.275 0.230 0.202 0.182 0.156 0.138 0.104 0.078 0.078 0.055 1
a1/s0.4/f0.8 0.046 0.174 0.105 0.086 0.083 0.080 0.066 0.052 0.038 0.041 0.040 1
```
The default row reproduces `a1.md` §1a: arousal *lowest* at the switch step and
peaking around lag 11–12. The odd lags are where the fix shows, so at one-step
resolution:
```
setting @0 @1 @2 @3 @4 @5 @6 @7 far peak/far
---------------------------------------------------------------------------------------------
a0.5/s0.02/f0.2 0.055 0.122 0.157 0.188 0.217 0.240 0.257 0.278 0.098 3.38
a1/s0.02/f0.2 0.046 0.188 0.205 0.234 0.259 0.275 0.284 0.307 0.092 3.77
a0.5/s0.2/f0.4 0.054 0.184 0.219 0.227 0.228 0.225 0.221 0.210 0.053 4.30
a1/s0.1/f0.2 0.060 0.312 0.294 0.304 0.301 0.292 0.289 0.298 0.065 4.81
a1/s0.2/f0.4 0.063 0.315 0.275 0.256 0.230 0.208 0.202 0.191 0.055 5.75
a1/s0.4/f0.8 0.046 0.243 0.174 0.131 0.105 0.088 0.086 0.084 0.040 6.06
```
**`rho_slow` is the whole story and `rho_a` sharpens it.** A slow baseline that tracks
the loss over ~50 steps cannot register a rise until the rise is most of the way done;
raising `rho_slow` to 0.1–0.4 turns `max(0, loss − slow)/slow` from a level detector
into a short-horizon relative-excess detector, and the surprise lands on the step after
the switch. `rho_a = 1` removes the remaining EMA smoothing on arousal itself.
The chosen setting was fixed on timing grounds alone, before any `grp_k` run: **among
settings whose peak lies within 3 steps of the switch, take the largest peak
amplitude.** That is `a1/s0.2/f0.4` — peak 0.315 at lag 1, a 5.0x jump from lag 0 in a
single step, and the best peak-to-far contrast of the three (5.75x). `a1/s0.1/f0.2` is
the runner-up and is reported alongside.
Worth stating because it bounds what timing can ever buy here: **the loss itself peaks
at lag 6–7** in every one of these runs (`recovery[k]` runs 2.74e-05, 2.83e-05,
3.12e-05, 3.40e-05, 3.84e-05, 4.37e-05, 4.70e-05, 4.71e-05 over lags 0–7). Arousal now
peaks five to six steps *before* the error it is built from does, because the loss at
lag 0 is already 1.3x its steady level and a short baseline sees that immediately.
There is no timing left to win.
### 1b. The result: timing fixed, error unmoved
`grp_k` against `grp_k0`, both at the best-timed affect config, 16 seeds, paired per
seed. Identical architecture, identical 5602 parameters, differing only in κ.
```
affect setting kappa mean median >1.10 >1.00 max
---------------------------------------------------------------------
a1/s0.2/f0.4 (best) 1 0.991 1.001 0/16 9/16 1.009
a1/s0.2/f0.4 4 0.987 1.000 0/16 8/16 1.017
a1/s0.2/f0.4 16 0.985 0.995 0/16 6/16 1.016
a1/s0.1/f0.2 (2nd) 1 1.011 1.000 1/16 7/16 1.107
a1/s0.1/f0.2 4 0.997 0.997 0/16 7/16 1.068
a1/s0.1/f0.2 16 0.987 0.995 0/16 6/16 1.025
```
Per-seed `grp_k0 / grp_k` at the best-timed setting, κ=4:
```
0.99 1.01 1.00 1.01 0.99 0.99 1.00 0.97 1.02 1.01 1.00 1.00 0.99 0.99 1.01 0.80
```
A coin flip with one seed (15) where the forced gate costs 20%. This is the same
picture `a1.md` §2 measured with the mis-timed signal, at the same magnitudes. Fixing
the timing changed the arousal profile completely and changed the error by nothing.
### 1c. The lag-2 harm survives the fix
`a1.md` §2a's one sign-definite effect was a 4–11% *degradation* two steps after a
switch, monotone in κ. Re-measured with arousal now peaking at lag 1 rather than 12:
```
paired grp_k0 / grp_k at matched lag, best-timed affect (<1 means kappa is worse)
kappa @0 @2 @5 @10 @19
------------------------------------------------------------------------------
1 0.98 4/16 0.96 1/16 0.99 8/16 1.00 8/16 0.99 6/16
4 0.99 6/16 0.90 0/16 0.99 6/16 0.99 6/16 0.98 5/16
16 0.99 5/16 0.91 1/16 1.00 4/16 1.00 7/16 1.00 8/16
```
At κ=4 the lag-2 penalty is 0.90 on **0 of 16 seeds** — against `a1.md`'s 0.92 on
1/16 with the mis-timed signal. Correcting the timing did not remove the harm; it made
it very slightly worse, which is what §1a's mechanism predicts. Opening the gate
earlier discards the temporal averaging earlier, and `frozen.md` §1b established that
the post-switch excess belongs to the world's configuration transient, which no gating
policy can shorten.
### 1d. The `rho_fast` control
Fixing `rho_a = 1.0`, `rho_slow = 0.2` and varying only `rho_fast`, 4 seeds:
```
rho_a/rho_slow/rho_fast @0 @2 @4 @6 @8 @10 far peak
---------------------------------------------------------------------------------
a1/s0.2/f0.4 0.063 0.275 0.230 0.202 0.182 0.156 0.055 1
a1/s0.2/f0.5 0.061 0.277 0.232 0.202 0.181 0.154 0.055 1
a1/s0.2/f0.9 0.063 0.279 0.233 0.196 0.180 0.155 0.055 1
```
Identical to within 0.005 at every lag, as the algebra requires. `rho_fast` is not a
lever on arousal timing, so the sweep over `rho_a × rho_slow` is the whole search
space and the "best-timed setting" is best over all of it.
### Verdict against the pre-registered criterion
> **SUCCESS** = arousal's peak moves to within 3 steps of the switch **and** the paired
> `grp_k0 / grp_k` steady ratio exceeds 1.10 on at least 12 of 16 seeds.
- Peak within 3 steps of the switch: **met** — lag 1, from lag 11.
- Ratio > 1.10 on ≥ 12/16 seeds: **not met** — 0/16 at the pre-declared κ=4, 0–1/16
at every κ and both settings, largest ratio anywhere 1.107.
**Part 1 is a FAILURE, and it is the failure the brief named as the informative one:
the mechanism works, is correctly timed, and the domain gives it nothing.** A1 is
closed on this domain by a stronger argument than `a1.md` had, because the one
remaining explanation — that the signal arrived too late — has now been removed and
the result did not move.
## 2. Part 2 — measuring `T_id`
Nothing in `identify.py` constructs an Organism. `T_id` is a property of the domain.
### 2a. What the observer has, and what "optimal" means here
At step `t` the observer has the coordinates `c_{t−L+1} … c_t` and therefore the
displacements `d_s = wrap(c_{s+1} − c_s)` for `s = t−L+1 … t−1`. **`d_t` is never
available** — that is what the organism is asked to predict, and handing it over would
hand over the answer. So `L = 1` is the instantaneous configuration alone and each
extra step of window buys exactly one more observed displacement.
The dynamics factor as
```
d_i(s) = sum_c K[t_i, c] · B_i^c(s) + eps, B_i^c(s) = dt · sum_{j: t_j = c} kern(r_ij) r_ij
```
`B` is the message basis — everything about the configuration the coupling multiplies
— and is computable from coordinates alone, so it is observer-side information. It is
the same decomposition `ceilings.py` fits. Self-check, the analogue of that file's row
A: the basis reproduces the world's own displacements at residual **4.0024e-06**
against `noise² = 4.0e-06`, asserted on every rollout.
Four decoders, in ascending order of what they are told:
| tag | features | estimator | knows the coupling matrices? |
|---|---|---|---|
| `lin` | raw window: `B` at each step, the observed displacements, the type one-hot | least squares | no |
| `mlp` | the same raw window | 2×128 ReLU MLP | no |
| `phys` | `<d, B^c>` and `<B^c, B^c'>` summed over the window, interacted with the type one-hot | multinomial logistic | no |
| `bayes` | the exact Gaussian likelihood over the window | closed form | **yes** |
`phys` is the fair stand-in for "optimal", and the reason is algebraic rather than
empirical: the log-likelihood of regime `g` is affine in exactly those statistics with
coefficients depending on `g` and on the entity's own type, so a linear classifier on
them **can express the exact Bayes rule**. `bayes` computes that rule directly and is
the cross-check. `lin` and `mlp` are the honest non-omniscient decoders, and the MLP is
the capacity check the brief asked for before concluding anything from a linear probe.
Chance is measured, not assumed — the two nulls `frozen.py` uses, both refitting from
scratch: a label shuffle, and a circular shift that preserves each regime's block
structure and is the stricter of the two. The shift null is quoted in brackets.
### 2b. The table
8 seeds, 4000 world steps, `t_min/t_max = 40/80`. "hist" is the steps of history
`L` observations actually provide. `sw.frac` is the fraction of windows spanning a
regime change. Per-step accuracy pools the 16 entities of a step, which is what an
observer watching the whole world does; per-entity is one classification per entity.
```
per-step accuracy (measured chance in brackets)
L hist sw.frac lin mlp phys bayes
-----------------------------------------------------------------------------------
1 0 0.000 0.229[0.224] 0.552[0.259] -- --
2 1 0.016 0.231[0.227] 0.831[0.266] 0.909[0.230] 0.958
3 2 0.033 0.231[0.232] 0.856[0.268] 0.926[0.233] 0.961
5 4 0.065 0.232[0.233] 0.874[0.250] 0.923[0.236] 0.952
10 9 0.147 0.234[0.232] 0.863[0.257] 0.888[0.237] 0.915
20 19 0.311 0.238[0.227] 0.814[0.260] 0.798[0.249] 0.842
40 39 0.640 0.237[0.227] 0.708[0.274] 0.632[0.237] 0.699
per-entity accuracy (measured chance in brackets)
L hist sw.frac lin mlp phys bayes
-----------------------------------------------------------------------------------
1 0 0.000 0.242[0.231] 0.405[0.251] -- --
2 1 0.016 0.251[0.233] 0.563[0.253] 0.566[0.230] 0.566
3 2 0.033 0.251[0.236] 0.590[0.253] 0.614[0.233] 0.629
5 4 0.065 0.251[0.238] 0.605[0.246] 0.643[0.234] 0.684
10 9 0.147 0.248[0.236] 0.598[0.251] 0.639[0.237] 0.718
20 19 0.311 0.247[0.230] 0.553[0.248] 0.581[0.239] 0.702
40 39 0.640 0.243[0.229] 0.476[0.252] 0.486[0.233] 0.601
```
Per-seed `bayes` per-step at `L=2`: `0.97 0.98 0.98 0.98 0.95 0.97 0.93 0.90`, and
`phys` `0.93 0.97 0.96 0.98 0.92 0.93 0.79 0.78`. It is not an average over a few
lucky seeds.
**`T_id = 2` observations — one step of history.** A single observed displacement takes
per-step accuracy from 0.55 to 0.96. `L = 3` adds 0.003 and every longer window is
*worse*, because the assumption that one regime governs the window stops holding
(`sw.frac` reaches 0.64 at `L = 40`). The saturation point is not a plateau; it is a
peak at `L = 2–3`, and the decline past it is the domain telling you that more history
is actively harmful once the window outruns the regime.
Three details worth carrying:
- **The linear decoder on the raw window never rises** — 0.23 against 0.23 at every
`L`. Exactly the case the brief warned about: a linear probe here would have said
the regime is unidentifiable, and it would have been wrong by 0.7 in accuracy. The
MLP and `phys` are what settle it, and `bayes` bounds them.
- **`phys` tracks `bayes` to within 0.05 and never beats it**, which is the
cross-check the construction demanded.
- **The instantaneous read-off is much larger than the organism's.** At `L = 1`, with
no displacement at all, the MLP reaches 0.552 per-step and 0.405 per-entity against
a measured chance of 0.25. `frozen.md` §2 decoded the regime from the organism's own
`h` at 0.342 and from `M` at 0.332, against 0.274 — a gap of +0.07 where the
configuration in front of it supports +0.15. The organism is discarding most of the
regime information already visible in a single frame.
### 2c. `T_id` at each duration Part 3 sweeps
`bayes` per-step, 4 seeds, 4000 steps. `argmax L` is where accuracy saturates.
```
T_z L=2 L=3 L=5 L=10 L=20 L=40 argmax L
----------------------------------------------------------------------------
4-8 0.825 0.722 0.538 0.250 0.300 0.267 2
10-20 0.930 0.890 0.821 0.644 0.313 0.339 2
40-80 0.978 0.974 0.959 0.922 0.858 0.726 2
150-300 0.973 0.989 0.989 0.980 0.963 0.930 5
600-1200 0.960 0.991 0.997 0.995 0.992 0.985 5
```
`T_id` is 2 across the sweep, drifting to 5 at the longest durations where a longer
window is finally safe to use. **`T_id` is between 1 and 4 steps of history at every
duration Part 3 tests**, and is undefined at the frozen regime, which has nothing to
identify.
### 2d. `G` at each duration
`ceilings.py`, rows D → C, 1200 steps, seeds 0–2. The oracle prize against the noisy
target:
```
T_z 4-8 10-20 40-80 150-300 600-1200 frozen
--------------------------------------------------------------
G 1.95 1.62 1.56 1.48 1.24 1.00
```
The 40–80 value reproduces `headroom.md` §3's 1.56x exactly. `G` decays monotonically
with duration and reaches **exactly 1.00 at the frozen regime**, which is the
self-consistency check: a regime that never changes carries no information, so a
regime oracle can be worth nothing. Every row A self-check passes.
### The reading the brief pre-registered
> `T_id << T_z` — the domain *can* reward memory, and the failure is ours rather than
> the domain's. That points at the architecture or the training signal, and it is a
> much more uncomfortable and more useful result.
`T_id = 2`, `T_z = 40–80`. **`T_id` is 20 to 40 times smaller than `T_z`, and `G` is
1.56.** The domain satisfies the pre-registered condition, comfortably, on both
quantities. The regime is identifiable from one observed step and then holds still for
another forty. This is the uncomfortable branch, and §2b's last bullet says where to
look: the organism's own representation carries less than half the regime information
that a decoder recovers from the same frame.
## 3. Part 3 — the falsifiable test
The capacity-controlled state gain `grp_k0_nostate / grp_k0`: identical architecture,
identical 5602 parameters, differing only in whether `M` is carried between steps.
A `grp_k0` vs `rp_only` number is confounded 3.9x (`frozen.md` §5) and is not this
measurement. κ = 0 in both arms; affect is at its defaults and plays no part here.
Shortening the regime changes the world's timescale, so the metrics were re-checked
rather than re-used. Two things were done about it:
- **The recovery window is enforced per duration.** `regime.run` refuses
`window >= t_min`; the same rule is applied here, and each run stores its metrics at
every window shorter than its own `t_min`. Tables quote **window 1** because it is
the only window a duration of 2–3 admits and therefore the one column every duration
can be compared on; windows 3 and 9 are given alongside and agree.
- **Switch counts are reported rather than implied.** At 600–1200 there are ~4
switches in the measured half — enough for `steady`, which averages over thousands
of steps, and not enough for a recovery curve. **No `recovery[k]` number is quoted
from the two longest durations**, and the state gain is read off `steady` throughout.
```
regime duration state gain median seeds won per-seed range
------------------------------------------------------------------
2-3 1.09 1.06 10/16 0.76 - 1.66
4-8 1.10 1.04 10/16 0.87 - 1.72
10-20 1.09 1.01 10/16 0.83 - 1.56
40-80 1.17 1.11 11/16 0.91 - 1.88
150-300 1.22 1.20 10/16 0.32 - 2.86
600-1200 1.12 1.01 8/16 0.62 - 1.77
frozen 1.26 1.12 11/16 0.69 - 1.99
```
Read down the `state gain` column. It does not have a peak. It is flat at 1.09-1.26
across regime durations spanning four orders of magnitude, and every difference between
durations is smaller than the per-seed range within any one of them: at 150-300 the
individual seeds run from 0.32 to 2.86, which is wider than the entire spread of the
column means. On a paired count the picture is the same, 8 to 11 seeds of 16 at every
duration -- a coin flip that never becomes anything else.
The decisive row is the last one. **The largest state gain in the sweep is at the frozen
regime**, where there is no regime to identify, no switch to recover from, and `G`
measures exactly 1.00. A quantity that is at its largest when its supposed cause is
entirely absent is not caused by it.
What the state gain measures is therefore not regime tracking. It is temporal smoothing:
carrying `M` averages the representation over recent steps, which reduces variance
against a noisy target, and a stationary world rewards that at least as well as a
switching one does.
## 4. So: when does per-entity memory have a job?
The task was built on a theory, pre-registered before any run: memory has a job when the
hidden variable is identifiable much faster than it changes (`T_id << T_z`) and knowing it
is worth something (`G` materially above 1). The prediction was a peak in state gain at
intermediate regime durations.
**The theory is wrong as stated, and the three parts falsify it from three directions.**
Its condition is satisfied here -- comfortably. `T_id` is 2 to 3 observations against a
`T_z` of 40-80, a margin of twenty-fold or more, and `G` is 1.54x. By the theory this
domain should be close to ideal for per-entity memory. It is not: the state gain is 1.17
at that duration, on 11 seeds of 16, and it is *higher* at the frozen regime where the
condition is not satisfied at all. A criterion that is met exactly where the effect is
absent, and unmet exactly where the effect is largest, is not the criterion.
What the three parts establish together is more useful than the theory they refute.
**The domain is the rememberable kind.** Part 2 settles the question the poker framing
raised: is the evidence for the hidden variable already in the present, making history
redundant, or does it live only in the past? Here it lives in the past. One observed
displacement carries the regime almost perfectly -- 0.958 for an exact decoder, 0.909 for
one that has never seen a coupling matrix -- while the instantaneous configuration alone
supports 0.574 at best. History nearly doubles the present's above-chance information.
This is not a domain where feedforward suffices in principle.
**The organism captures almost none of it.** `frozen.md` Part B decoded the regime from
the GRP's memory at 0.332. The same regime is available at 0.909 from a single step of
history, using a decoder with no privileged knowledge. `M` holds roughly a fifth of the
signal that a fair observer extracts from one step of the past, and no more than the
memoryless RP's own `h` holds.
**So the failure is ours, not the domain's.** That is the uncomfortable branch, and it was
named in advance precisely so it could not be avoided afterwards: `T_id << T_z` was
pre-registered as meaning "the domain can reward memory and the failure is ours". It came
out that way. This matters beyond this file, because the project's standing reflex when
memory failed to help was to reach for a different domain. That reflex is now closed off.
The information was here all along.
The mechanism is visible in the other files rather than derived here, and the three
observations compose:
- The gate's learned pre-activation never leaves zero, at any `kappa`, after any amount of
training (`a1.md` §1b). Nothing about what to keep is ever decided.
- The margin the GRP does win is its gated post-RP nonlinearity, not carried state and not
parameter count (`frozen.md` §1d).
- Affect can move the gate, exactly and on cue once its time constants are set (Part 1
above), and moving it changes nothing, because there is no stored quantity for an opened
gate to admit or a closed one to protect.
The regime is identifiable from an observed displacement -- which arrives one step after
the prediction it would have helped. Carrying that one step forward is precisely what
per-entity memory is for, and precisely what the gate would have to learn to do. It never
does. Whether that is a credit-assignment failure, a consequence of the per-step loss term
dominating the temporal one, or a mismatch between a global hidden variable and a
per-entity state, this file does not determine. It establishes only that the question is
now about the organism and no longer about the domain.
---
*Write-up note: the agent that ran these measurements died mid-write when the machine
slept, leaving §3's table and §4 unwritten. Both were completed from the committed JSON
by the session controller, which independently recomputed Part 3's table from
`w_duration_all.json` and `w_duration_frozen.json`, Part 1's paired ratios and arousal
profiles from `w_best.json` and `w_timing.json`, and Part 2's decoder series from
`identify.json`. No sweep was re-run and no number was carried over unverified.*
+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"]
+173
View File
@@ -0,0 +1,173 @@
import numpy as np
import pytest
import torch
from torch import nn
import frozen
import regime
from frozen import _build, _frozen, _hidden, _train, probe, run_one
@pytest.mark.parametrize("name", ["rp_only", "grp_k0"])
def test_train_copy_is_identical_to_regime_run(name):
"""`_train` is a verbatim copy of `regime.run`'s loop; this pins it.
If anyone edits either loop apart from the other, the metrics diverge and this
fails -- which is the only guarantee that the frozen phase starts from the same
organism Task 7 measured.
"""
steps, window, bptt = 400, 20, 20
spec, wcfg, world, org = _build(name, seed=0, hidden=32, omega=10.0, kappa=4.0)
_, _, tr = _train(spec, wcfg, world, org, steps, bptt, lr=1e-3)
mine = regime._metrics(tr["losses"], tr["switched"], tr["arousals"], window)
theirs = regime.run(name, seed=0, steps=steps, window=window, bptt=bptt)
assert mine["steady"] == theirs["steady"]
assert mine["recovery"] == theirs["recovery"]
assert mine["n_switches"] == theirs["n_switches"]
@pytest.mark.parametrize("name", ["rp_only", "grp_k0"])
def test_frozen_phase_leaves_every_parameter_bit_identical(name):
spec, wcfg, world, org = _build(name, seed=0, hidden=32, omega=10.0, kappa=4.0)
affect, memory, _ = _train(spec, wcfg, world, org, 200, 20, lr=1e-3)
before = nn.utils.parameters_to_vector(org.parameters()).clone()
fr = _frozen(spec, wcfg, world, org, affect, memory, 200)
after = nn.utils.parameters_to_vector(org.parameters())
assert fr["frozen_bit_identical"]
assert torch.equal(before, after)
assert not any(p.requires_grad for p in org.parameters())
def test_memory_keeps_updating_while_weights_are_frozen():
"""Freezing is about parameters, not state. A frozen M would silently turn the
GRP into an RP and make any null a null for the wrong reason."""
spec, wcfg, world, org = _build("grp_k0", seed=0, hidden=32, omega=10.0, kappa=4.0)
affect, memory, _ = _train(spec, wcfg, world, org, 200, 20, lr=1e-3)
fr = _frozen(spec, wcfg, world, org, affect, memory, 200)
assert fr["dM_min"] > 0.0
assert fr["dM_mean"] > 0.0
assert fr["M"].shape == (200, wcfg.n, org.hidden_dim)
def test_frozen_phase_detects_a_parameter_change():
"""The freeze assertion has to be able to fail, or it proves nothing."""
spec, wcfg, world, org = _build("grp_k0", seed=0, hidden=32, omega=10.0, kappa=4.0)
affect, memory, _ = _train(spec, wcfg, world, org, 100, 20, lr=1e-3)
orig = _frozen.__globals__["nn"].utils.parameters_to_vector
calls = {"n": 0}
def sneaky(params):
v = orig(params)
calls["n"] += 1
if calls["n"] == 1: # let a weight move right after the "before" snapshot
with torch.no_grad():
org.out.bias.add_(1e-6)
return v
frozen.nn.utils.parameters_to_vector = sneaky
try:
with pytest.raises(AssertionError):
_frozen(spec, wcfg, world, org, affect, memory, 20)
finally:
frozen.nn.utils.parameters_to_vector = orig
@pytest.mark.parametrize("name", ["rp_only", "grp_k0"])
def test_hidden_reconstruction_matches_the_organism(name):
"""`_hidden` must rebuild the same edge one-hot, mask and context `Organism.forward`
builds, or the RP probe would be run on a representation the organism never used."""
spec, wcfg, world, org = _build(name, seed=1, hidden=32, omega=10.0, kappa=4.0)
from ailed import Affect
from particles import wrapped_diff
obs = world.step()
affect = Affect()
with torch.no_grad():
r = wrapped_diff(obs.coords)
pred, mem = org(obs.attrs, r, obs.ids, affect.axes, {}, context=None)
h = _hidden(org, obs.attrs, r, affect.axes, None)
if org.use_memory:
zero = torch.zeros(org.hidden_dim)
prev = torch.stack([zero for _ in obs.ids])
M = torch.stack([mem[i] for i in obs.ids])
assert torch.equal(org.grp(h, prev, affect.arousal), M)
else:
assert torch.equal(org.out(h), pred)
def test_probe_recovers_a_planted_regime_signal_and_not_a_planted_absence():
"""Two ends of the probe: a representation that linearly carries the label must
decode well above the measured chance level, and pure noise must not."""
rng = np.random.default_rng(0)
T, N, R = 600, 8, 4
labels, switched, cur, left = [], [], 0, 0
for t in range(T):
if left == 0:
cur, left = int(rng.integers(R)), int(rng.integers(40, 80))
switched.append(True)
else:
switched.append(False)
labels.append(cur); left -= 1
labels = np.asarray(labels)
signal = np.eye(R)[labels][:, None, :].repeat(N, 1) + 0.1 * rng.normal(size=(T, N, R))
noise = rng.normal(size=(T, N, R))
good = probe(signal, labels, switched, R, n_null=5)
bad = probe(noise, labels, switched, R, n_null=5)
assert good["acc_entity"] > 0.9 > good["chance_shift_max"]
assert bad["acc_entity"] <= bad["chance_shift_max"] + 0.05
def test_probe_test_split_is_a_suffix_in_time():
"""A random split would let the probe memorise steps adjacent to the test steps."""
rng = np.random.default_rng(0)
T, N, R = 200, 4, 3
labels = np.repeat(np.arange(T // 50) % R, 50)
reps = rng.normal(size=(T, N, R))
out = probe(reps, labels, [False] * T, R, split=0.7, n_null=2)
assert out["n_test_steps"] == T - int(T * 0.7)
def test_run_one_reports_both_phases_and_the_freeze_check():
r = run_one("grp_k0", seed=0, train_steps=200, frozen_steps=200, window=20)
assert r["frozen_bit_identical"] is True
assert r["probe_on"] == "M" and set(r["probes"]) >= {"M_lsq", "h_lsq", "M_logit"}
assert len(r["frozen"]["recovery"]) == 20
assert r["trained"]["steady"] >= 0.0
assert run_one("rp_only", seed=0, train_steps=200, frozen_steps=200)["probe_on"] == "h"
def test_probe_accepts_per_entity_labels():
"""The coupling row differs between entities at the same step, so the probe has to
take a (T, N) target as well as the (T,) regime id."""
rng = np.random.default_rng(1)
T, N, R = 400, 6, 3
lab = rng.integers(0, R, size=(T, N))
reps = np.eye(R)[lab] + 0.1 * rng.normal(size=(T, N, R))
out = probe(reps, lab, [False] * T, R, n_null=3)
assert out["acc_entity"] > 0.9 > out["chance_shift_max"]
assert np.isnan(out["acc_step"]) and np.isnan(out["latency"])
def test_persistence_separates_a_slow_state_from_white_noise():
from frozen import persistence
rng = np.random.default_rng(2)
T, N, D = 2000, 4, 5
white = rng.normal(size=(T, N, D))
slow = np.zeros_like(white)
for t in range(1, T):
slow[t] = 0.95 * slow[t - 1] + white[t]
assert persistence(white)["lag1"] < 0.1 < persistence(slow)["lag1"]
assert persistence(slow)["tau"] > 10 >= persistence(white)["tau"]
def test_ablate_state_keeps_the_parameters_and_drops_only_the_state():
"""The capacity control: the GRP keeps all 5602 parameters but carries nothing
between steps, so M becomes a fixed function of h."""
full = run_one("grp_k0", seed=0, train_steps=200, frozen_steps=100, probes=False)
none = run_one("grp_k0", seed=0, train_steps=200, frozen_steps=100, probes=False, stateless=True)
assert none["condition"] == "grp_k0_nostate"
assert none["n_params"] == full["n_params"] > run_one(
"rp_only", seed=0, train_steps=200, frozen_steps=100, probes=False)["n_params"]
assert none["dM_min"] == 0.0 or none["frozen"]["steady"] != full["frozen"]["steady"]
assert none["frozen_bit_identical"]
+84
View File
@@ -0,0 +1,84 @@
import math
import pytest
from regime import CONDITIONS, _metrics, 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"
def test_window_too_large_raises():
with pytest.raises(ValueError):
run("grp_k0", seed=0, steps=100, window=100)
def test_metrics_recovery_is_mean_loss_k_steps_after_switch():
# steps=20, half=10: a single switch at index 12 sits inside the measured
# second half. losses[i] = i, so recovery[k] = 12 + k exactly.
steps, window = 20, 3
losses = [float(i) for i in range(steps)]
switched = [False] * steps
switched[12] = True
arousals = [i * 0.01 for i in range(steps)]
m = _metrics(losses, switched, arousals, window)
assert m["recovery"] == [12.0, 13.0, 14.0]
assert m["n_switches"] == 1
assert m["arousal_at_switch"] == pytest.approx(0.12)
def test_metrics_ignores_switches_in_the_first_half():
steps, window = 20, 3
losses = [float(i) for i in range(steps)]
switched = [False] * steps
switched[12] = True
arousals = [i * 0.01 for i in range(steps)]
baseline = _metrics(losses, switched, arousals, window)
# a first-half switch with wildly different loss/arousal must not move any metric:
# half=10 and window=3 mean the earliest measured lookback starts at 10-3=7, so
# index 3 never enters any window computation.
losses2 = list(losses); losses2[3] = 999999.0
switched2 = list(switched); switched2[3] = True
arousals2 = list(arousals); arousals2[3] = 999.0
perturbed = _metrics(losses2, switched2, arousals2, window)
assert perturbed == baseline
def test_metrics_steady_excludes_window_steps_after_a_switch():
# steps=20, half=10, window=3: switch at 15 excludes i in [15, 15+window] = [15,18]
# from steady. If that exclusion didn't apply, the huge post-switch losses at
# 16-18 would pull steady far from 1.0.
steps, window = 20, 3
losses = [1.0] * steps
for i in (15, 16, 17, 18):
losses[i] = 999.0
switched = [False] * steps
switched[15] = True
arousals = [0.0] * steps
m = _metrics(losses, switched, arousals, window)
assert m["steady"] == pytest.approx(1.0)
def test_metrics_no_switch_in_range_gives_nan_recovery():
steps, window = 20, 3
losses = [1.0] * steps
switched = [False] * steps
arousals = [0.0] * steps
m = _metrics(losses, switched, arousals, window)
assert m["n_switches"] == 0
assert all(math.isnan(x) for x in m["recovery"])
assert math.isnan(m["arousal_at_switch"])
assert m["steady"] == pytest.approx(1.0)
+225
View File
@@ -0,0 +1,225 @@
"""Task 9. Each test here defends one property a headline number rests on.
AGENTS.md: a test that cannot fail is worse than no test. Every test below that
defends a central property has a companion that breaks the property on purpose and
asserts the guard fires -- named `..._can_fail` or written as a `pytest.raises`
inside the test itself.
"""
from __future__ import annotations
import numpy as np
import pytest
import torch
import identify
import when_memory_works as wmw
from ailed import AffectConfig
from frozen import _build, _train
from particles import ParticleConfig
from regime import _metrics
# -- Part 1: the arousal profile is the arousal the gate actually saw --------------
def _run_with_gate_trace(steps=300):
from a1 import GateTrace
spec, wcfg, world, org = _build("grp_k", seed=0, hidden=32, omega=10.0, kappa=4.0)
tr = GateTrace(org)
_, _, out = _train(spec, wcfg, world, org, steps, bptt=20, lr=1e-3, on_step=tr)
return np.asarray(tr.a_gate, dtype=float), out
def test_gate_arousal_seq_is_the_arousal_the_organism_was_handed():
"""`_train` records affect *after* the update, so the gate's input is lagged by one.
`a1.GateTrace` records the value the organism was actually passed. If these two
disagree, every arousal-vs-lag profile in Part 1 is off by a step and the
pre-registered "within 3 steps" criterion is being judged against the wrong curve.
"""
seen, out = _run_with_gate_trace()
assert np.array_equal(wmw.gate_arousal_seq(out["arousals"]), seen)
def test_gate_arousal_seq_can_fail():
"""Break it on purpose: the un-lagged sequence must NOT match."""
seen, out = _run_with_gate_trace()
assert not np.array_equal(np.asarray(out["arousals"], dtype=float), seen)
def test_affect_config_is_passed_through_and_changes_the_arousal_stream():
"""`--part timing` is only a sweep if the config reaches the loop. Two settings,
same seed, must produce different arousal; the default must reproduce the default."""
args = ("grp_k0", 0, 0.0)
kw = dict(steps=300, windows=(20,))
base = wmw.run_one(*args, AffectConfig(), **kw)
same = wmw.run_one(*args, wmw._cfg(0.5, 0.02, 0.2), **kw)
other = wmw.run_one(*args, wmw._cfg(1.0, 0.4), **kw)
assert base["arousal"]["20"]["far"] == same["arousal"]["20"]["far"]
assert base["arousal"]["20"]["far"] != other["arousal"]["20"]["far"]
def test_cfg_keeps_the_slow_baseline_slower_than_the_fast_one():
for ra in wmw.RHO_A:
for rs in wmw.RHO_SLOW:
c = wmw._cfg(ra, rs)
assert c.rho_slow < c.rho_fast, (ra, rs)
def test_peak_lag_and_by_lag_average_over_the_switches_metrics_uses():
"""`by_lag` must cut the trace exactly as `_metrics` cuts `recovery`."""
steps, window = 400, 20
rng = np.random.default_rng(0)
losses = list(rng.random(steps))
switched = [i % 57 == 0 for i in range(steps)]
got = wmw.by_lag(np.asarray(losses), switched, steps, window)
assert got == pytest.approx(_metrics(losses, switched, [0.0] * steps, window)["recovery"])
# -- Part 2: the decoder is causal, and the basis is the world's -------------------
def test_features_never_use_the_displacement_being_decoded():
"""The window at step t may use d_{t-L+1..t-1} and never d_t.
This is the property that makes T_id a statement about an observer rather than
about a decoder handed the answer. Corrupting d_t alone must leave the features
for step t untouched -- and must change the features for step t+1, or the test
would pass on a decoder that ignores displacements altogether.
"""
world = identify.rollout(ParticleConfig(seed=0), 120)
for kind in ("raw", "phys"):
X, y, ts = identify.features(world, L=5, kind=kind)
hit = 40
t = ts[hit]
poisoned = dict(world, disp=world["disp"].clone())
poisoned["disp"][t] += 1.0
Xp, _, _ = identify.features(poisoned, L=5, kind=kind)
assert np.array_equal(X[hit], Xp[hit]), f"{kind} leaked d_t"
assert not np.array_equal(X[hit + 1], Xp[hit + 1]), f"{kind} ignores displacements"
def test_basis_reproduces_the_worlds_dynamics_to_the_noise_floor():
world = identify.rollout(ParticleConfig(seed=1), 300)
resid = identify._check_basis(world)
assert resid == pytest.approx(ParticleConfig().noise ** 2, rel=0.03)
def test_basis_check_can_fail():
"""Hand `_check_basis` the wrong regime sequence: the residual must blow past noise."""
world = identify.rollout(ParticleConfig(seed=1), 300)
wrong = dict(world, regimes=(world["regimes"] + 1) % 4)
with pytest.raises(AssertionError):
identify._check_basis(wrong)
def test_bayes_decoder_recovers_a_regime_it_can_see_and_not_one_it_cannot():
"""Planted signal and planted absence, the shape `test_frozen.py` uses for its probe.
With the real displacements the exact decoder must be far above chance at L=2.
With the displacements replaced by noise there is nothing to decode and it must
fall to chance, which is what says the accuracy comes from the dynamics.
"""
world = identify.rollout(ParticleConfig(seed=0), 1200)
assert identify.bayes(world, L=2)["acc_step"] > 0.8
blind = dict(world, disp=torch.randn_like(world["disp"]) * 1e-3)
assert identify.bayes(blind, L=2)["acc_step"] < 0.45
def test_decode_is_at_chance_when_the_labels_carry_no_signal():
world = identify.rollout(ParticleConfig(seed=0), 900)
X, y, _ = identify.features(world, L=3, kind="phys")
real = identify.decode(X, y, 4, "logit", n_null=2, seed=0)
shuffled = identify.decode(X, np.random.default_rng(0).permutation(y), 4, "logit",
n_null=2, seed=0)
assert real["acc_step"] > 0.7
assert shuffled["acc_step"] < 0.45
def test_decode_test_split_is_a_suffix_in_time():
world = identify.rollout(ParticleConfig(seed=0), 600)
X, y, _ = identify.features(world, L=2, kind="phys")
poisoned = X.copy()
cut = int(len(X) * identify.SPLIT)
poisoned[:cut] = 0.0 # destroying only the train prefix must hurt
a = identify.decode(X, y, 4, "logit", n_null=1, seed=0)["acc_step"]
b = identify.decode(poisoned, y, 4, "logit", n_null=1, seed=0)["acc_step"]
assert b < a
def test_switch_fraction_counts_windows_that_span_a_change():
world = identify.rollout(ParticleConfig(seed=0, t_min=40, t_max=80), 800)
assert identify.switch_fraction(world, 1) == 0.0
assert identify.switch_fraction(world, 2) < identify.switch_fraction(world, 40)
# -- Part 3: the comparison stays capacity-controlled ------------------------------
def test_state_ablation_changes_only_whether_memory_is_carried():
"""Both arms of Part 3 must have the same architecture and the same parameter count.
`results/frozen.md` §5: a `grp_k0` vs `rp_only` number is confounded 3.9x. The
number Part 3 reports is `grp_k0_nostate / grp_k0`, and this is what makes it a
state measurement rather than a capacity measurement.
"""
kw = dict(steps=200, windows=(20,))
a = wmw.run_one("grp_k0", 0, 0.0, AffectConfig(), stateless=False, **kw)
b = wmw.run_one("grp_k0", 0, 0.0, AffectConfig(), stateless=True, **kw)
assert a["n_params"] == b["n_params"] == 5602
assert a["metrics"]["20"]["steady"] != b["metrics"]["20"]["steady"]
def test_duration_override_reaches_the_world_and_leaves_the_default_alone():
_, wcfg, world, _ = _build("grp_k0", 0, 32, 10.0, 0.0, t_min=10, t_max=20)
assert (wcfg.t_min, wcfg.t_max) == (10, 20)
assert 10 <= world.until <= 20
_, default, _, _ = _build("grp_k0", 0, 32, 10.0, 0.0)
assert (default.t_min, default.t_max) == (40, 80)
assert (ParticleConfig().t_min, ParticleConfig().t_max) == (40, 80)
def test_shorter_regimes_really_do_switch_more_often():
kw = dict(steps=1000, windows=(3,), kappa=0.0)
fast = wmw.run_one("grp_k0", 0, acfg=AffectConfig(), t_min=10, t_max=20, **kw)
slow = wmw.run_one("grp_k0", 0, acfg=AffectConfig(), t_min=150, t_max=300, **kw)
frozen = wmw.run_one("grp_k0", 0, acfg=AffectConfig(), t_min=99999, t_max=99999, **kw)
assert fast["metrics"]["3"]["n_switches"] > slow["metrics"]["3"]["n_switches"] > 0
assert frozen["metrics"]["3"]["n_switches"] == 0
def test_windows_that_reach_the_next_switch_are_not_reported():
"""`regime.run` refuses window >= t_min. Part 3 has to shorten the regime, so the
same rule is enforced per window: a duration of 10-20 may not report window 20."""
r = wmw.run_one("grp_k0", 0, 0.0, AffectConfig(), steps=400, windows=wmw.WINDOWS,
t_min=10, t_max=20)
assert set(r["metrics"]) == {"1", "3", "9"} # 20 reaches the next switch
def test_paired_ratio_is_per_seed_and_refuses_to_pair_across_seeds():
num = [dict(seed=s, metrics={"9": dict(steady=2.0)}) for s in (0, 1, 2)]
den = [dict(seed=s, metrics={"9": dict(steady=1.0)}) for s in (0, 1, 3)]
p = wmw.paired(num, den, window=9)
assert p["seeds"] == [0, 1] and p["n"] == 2
assert p["mean"] == pytest.approx(2.0) and p["won"] == 2
def test_the_present_only_baseline_sees_arrangement_the_message_basis_misses():
"""`L = 1` carries the whole history-over-present comparison, so it must not be
handicapped. A symmetric ring of same-type neighbours cancels in the first moment
`B` but not in the kernel mass, and `_frame` has to keep that distinction."""
cfg = ParticleConfig(n=5, n_types=1)
types = torch.zeros(5, dtype=torch.long)
tight = torch.tensor([[0.5, 0.5], [0.55, 0.5], [0.45, 0.5], [0.5, 0.55], [0.5, 0.45]])
loose = torch.tensor([[0.5, 0.5], [0.9, 0.5], [0.1, 0.5], [0.5, 0.9], [0.5, 0.1]])
a, b = identify._frame(tight, types, cfg)[0], identify._frame(loose, types, cfg)[0]
assert a[:2] == pytest.approx(b[:2], abs=1e-6) # the first moment cancels in both
assert a[2] > 5 * b[2] # the kernel mass does not
def test_history_gain_is_computed_against_the_same_decoder_at_L1():
"""accuracy(L) - accuracy(1) is only meaningful if both use the same per-frame
features and the same estimator; this pins that the raw feature block grows by
whole frames plus displacements and by nothing else."""
world = identify.rollout(ParticleConfig(seed=0), 120)
f = world["frame"].shape[-1]
n1 = identify.features(world, 1, "raw")[0].shape[-1]
n3 = identify.features(world, 3, "raw")[0].shape[-1]
assert n3 - n1 == 2 * f + 2 * 2 # two more frames, two more displacements
+321
View File
@@ -0,0 +1,321 @@
"""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()