exp: the gate gets the credit and the state cannot hold the regime -- (a) is dead too

Task 11. Both parts of the brief, 16 seeds each, plus a positive control. One
control is incomplete and is marked as such in results/credit.md and in
.sdd/task-11-report.md.

Part A falsifies hypothesis (a). The gradient reaching grp.gate.weight is
coherent above its own measured sign-flip null on 14/16 seeds (0.202 against
0.163, paired se 0.009), and 0.587 of it arrives through the truncated-BPTT
window rather than from the current step -- the temporal term is 1.187x the
per-step one, where (a) predicted it negligible. Every window is replayed twice
at the same parameters from the same recorded observations, carried and
detached, and pinned bit-identical against the gradient Adam actually used
(max relative difference exactly 0.0, 6400 windows).

The gate's gradient is 887x smaller than the identically-shaped candidate
layer's, and that is not the explanation: Adam is scale invariant, the
per-coordinate SNR is 0.066 against cand's 0.070, and gate.weight travelled
26.8% of its initial norm over training -- further than any other block
measured. "The weights did not move", which frozen.md §3 and a1.md both lean
on, is false. What did not move is the function: on the same inputs, trained
weights give g = 0.5008 +- 0.0270 where the initial weights give 0.5009 +-
0.0203. The displacement stayed inside the sigmoid's linear band.

Part B gives the brief's third outcome: M cannot hold the regime even under
direct supervision. The auxiliary head never leaves chance at any lambda from
1e-5 to 1.0, with no trend over 8000 steps; the frozen-phase decode moves by
-0.001 +- 0.019. The positive control -- the same head, optimiser, seeds and
probe, supervising the entity's own type instead -- installs it and raises the
regime decode by +0.073 +- 0.022 on 14/16 seeds in passing. The control that
had no business moving that number is the only one that moved it.

Incomplete: the non-linear control (2x128 head and probe) reached 10 of 16
seeds per shard and was stopped. Its section reports no numbers and the verdict
states the limitation it carries.

frozen.py gains two _train keywords (aux, extra_params), both defaulting to off
so test_train_copy_is_identical_to_regime_run still pins the loop, and one line
in _scores so an estimator may be a callable. results/*.json and the partial
sweep logs are committed past .gitignore as checkpoint data.
This commit is contained in:
chrnx committed 2026-09-02 16:56:01 -05:00
1 parent 0d682db353
commit 0beba606cb
12 files changed
+34268 -6

No files matched your search

+156
View File
@@ -0,0 +1,156 @@
import math
import numpy as np
import pytest
import torch
import credit
import frozen
from credit import AuxHead, GradTrace, part_b
from frozen import _build, _train
SMALL = dict(train_steps=300, frozen_steps=300)
# -- Part A ----------------------------------------------------------------------
def test_replayed_gradient_is_the_one_the_optimiser_used():
"""The pin. Part A's whole comparison is between two replays, so if the replay
does not reproduce the real backward, the carried/detached difference is a
statement about the replay rather than about time.
`GradTrace._check` asserts this on every window during training; this test makes
the check itself visible and confirms it actually ran.
"""
spec, wcfg, world, org = _build("grp_k0", seed=0, hidden=32, omega=10.0, kappa=4.0)
tr = GradTrace(org, bptt=20)
_train(spec, wcfg, world, org, 200, 20, lr=1e-3, on_step=tr.on_step)
assert tr.n_checked == 10 # every window, not a subset
assert tr.max_rel == 0.0 # bit-identical, not merely close
assert tr.loss_equal # detaching changed the graph and no value
def test_the_replay_pin_can_fail():
"""A check that cannot fail defends nothing (AGENTS.md).
The replay is broken on purpose -- the window is replayed from a perturbed
starting M -- and the pin against the real backward must notice.
"""
spec, wcfg, world, org = _build("grp_k0", seed=0, hidden=32, omega=10.0, kappa=4.0)
tr = GradTrace(org, bptt=20)
real_replay = tr._replay
def sneaky(carry):
if tr.prev0 is not None:
tr.prev0 = tr.prev0 + 1e-3
return real_replay(carry)
tr._replay = sneaky
with pytest.raises(AssertionError):
_train(spec, wcfg, world, org, 200, 20, lr=1e-3, on_step=tr.on_step)
def test_the_readout_block_has_no_temporal_path():
"""A structural control on the carried/detached split, with a known answer.
`out.weight` multiplies `M` at the current step and nothing else, so detaching `M`
between steps cannot change the gradient it receives. Its temporal term must be
exactly zero -- and the gate's, which is applied at every step of the window, must
not be. If both came out zero the split would be measuring nothing.
"""
spec, wcfg, world, org = _build("grp_k0", seed=0, hidden=32, omega=10.0, kappa=4.0)
tr = GradTrace(org, bptt=20)
_train(spec, wcfg, world, org, 200, 20, lr=1e-3, on_step=tr.on_step)
s = tr.summary()["blocks"]
assert s["out"]["temporal"]["mean_norm"] == 0.0
assert s["gate"]["temporal"]["mean_norm"] > 0.0
assert s["cand"]["temporal"]["mean_norm"] > 0.0
def test_coherence_is_one_for_a_constant_gradient_and_at_the_null_for_noise():
"""The ratio has to read 1 when every step agrees and ~1/sqrt(n) when none do."""
spec, wcfg, world, org = _build("grp_k0", seed=0, hidden=32, omega=10.0, kappa=4.0)
tr = GradTrace(org, bptt=20)
n, shapes = 200, [p.shape for p in tr.params]
g = torch.Generator().manual_seed(0)
fixed = [torch.randn(s, generator=g) for s in shapes]
tr.carried = [[f.clone() for f in fixed] for _ in range(n)]
tr.detached = [[torch.zeros(s) for s in shapes] for _ in range(n)]
assert tr.summary()["blocks"]["gate"]["carried"]["coherence"] == pytest.approx(1.0, abs=1e-5)
tr.carried = [[torch.randn(s, generator=g) for s in shapes] for _ in range(n)]
got = tr.summary()["blocks"]["gate"]["carried"]
assert got["coherence"] == pytest.approx(1 / math.sqrt(n), rel=0.35)
assert got["coherence"] == pytest.approx(got["null"], rel=0.35)
# -- Part B ----------------------------------------------------------------------
def test_lambda_zero_reproduces_the_frozen_baseline():
"""`lam=0` must *be* Task 7b's grp_k0 run, not a re-implementation of it.
The whole of Part B is read against this row, so if the auxiliary machinery moved
the world, the organism or the estimator by so much as a bit, every comparison
below is against the wrong baseline.
"""
mine = part_b(seed=0, lam=0.0, **SMALL)
theirs = frozen.run_one("grp_k0", seed=0, **SMALL)
assert mine["trained"]["steady"] == theirs["trained"]["steady"]
assert mine["frozen"]["steady"] == theirs["frozen"]["steady"]
assert mine["probes"]["M_regime"]["acc_entity"] == theirs["probes"]["M_lsq"]["acc_entity"]
assert mine["probes"]["M_regime"]["chance_shift"] == theirs["probes"]["M_lsq"]["chance_shift"]
def test_the_auxiliary_head_does_not_move_the_world():
"""An oracle is opt-in and free (AGENTS.md): enabling one may not change the run
it is measuring, other than through the gradient it is there to supply.
The head is built inside `fork_rng`, so the world's trajectory, its regime
schedule and the organism's initialisation are the same draws at every lambda.
Checked by giving the head a weight of zero: the loss is then numerically the
baseline's and every reported number must match it exactly.
"""
from regime import _metrics
a = part_b(seed=0, lam=0.0, **SMALL)
spec, wcfg, world, org = _build("grp_k0", 0, 32, 10.0, kappa=4.0)
head = AuxHead(org, world, wcfg.n_regimes, lam=0.0, target="regime", seed=0)
_, _, tr = _train(spec, wcfg, world, org, SMALL["train_steps"], 20, 1e-3,
aux=head, extra_params=head.head.parameters())
m = _metrics(tr["losses"], tr["switched"], tr["arousals"], 20)
assert m["steady"] == a["trained"]["steady"]
assert m["recovery"] == a["trained"]["recovery"]
def test_the_auxiliary_loss_reaches_the_state():
"""The instrument has to be able to do the thing it is measuring the ceiling of.
A head supervising `M` toward the entity's own type -- a signal that is in `attrs`
and therefore certainly reachable -- must train, while the same head at the same
budget on shuffled labels must not. Without this, "M cannot hold the regime" is
indistinguishable from "the head is not connected".
"""
real = part_b(seed=0, lam=1.0, target="type", train_steps=2000, frozen_steps=300)
spec, wcfg, world, org = _build("grp_k0", 0, 32, 10.0, kappa=4.0)
head = AuxHead(org, world, wcfg.n_types, lam=1.0, target="type", seed=0)
rng = np.random.default_rng(0)
head.labels = lambda obs: torch.tensor(rng.integers(0, 3, size=16), dtype=torch.long)
_train(spec, wcfg, world, org, 2000, 20, 1e-3, aux=head,
extra_params=head.head.parameters())
# the same head, the same budget, the same optimiser: the only difference is
# whether the labels mean anything. Chance is 1/3.
assert real["aux_train_acc"] > 0.50 # a reachable signal is reached
assert head.accuracy() < 0.40 # an unreachable one is not
assert real["aux_train_acc"] - head.accuracy() > 0.15
def test_the_head_is_linear_in_M_alone():
"""The ceiling is a claim about `M`, so the head may read nothing else."""
spec, wcfg, world, org = _build("grp_k0", 0, 32, 10.0, kappa=4.0)
head = AuxHead(org, world, wcfg.n_regimes, lam=1.0, target="regime", seed=0)
assert isinstance(head.head, torch.nn.Linear)
assert head.head.in_features == org.hidden_dim
assert head.head.out_features == wcfg.n_regimes