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.
226 lines
10 KiB
Python
226 lines
10 KiB
Python
"""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
|