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