Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01KAWnnPg2qvmLNySamE2k85
111 lines
5.0 KiB
Python
111 lines
5.0 KiB
Python
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"]
|