Files
ailed-experiments-rp/credit.py
T
chrnx 0beba606cb 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.
2026-09-02 16:56:01 -05:00

789 lines
40 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Task 11: the ceiling on hypothesis (a), credit assignment.
`results/pooled.md` measured hypothesis (b) dead: the regime is not distributed across
the sixteen per-entity states, it is absent from them. (a) is what remains --
nothing in the training signal rewards carrying the regime forward, so the state
never learns to hold it.
**Part A** asks whether a gradient signal reaches the gate at all. Two failures look
identical from "the weights did not move": the gradient is ~0 (*absent*), or it is
substantial per step and averages to nothing (*cancelling*). Only the ratio of the norm
of the mean gradient to the mean of the per-step norms separates them, so that ratio is
the measurement and the magnitudes are reported beside it so "negligible" has a size.
The temporal split is paired inside a single run and isolates time alone. At every
optimiser step the same truncated-BPTT window is replayed twice at the same parameters
from the same recorded observations: once with `M` carried across the window, once with
`M` detached at every step. **Detaching changes the graph and nothing else** -- every
forward value is bit-identical, which `_replay` asserts against the `M` the organism
actually computed, exactly as `frozen._frozen` asserts its reconstruction of `h`. The
difference between the two gradients is the credit that flows through time.
**Part B** is the ceiling, and it is an oracle on the state rather than a proposed
architecture: a linear head from `M_i` to the current regime id, trained jointly at a
weight `lambda`, asking what the state *could* hold if it were told -- exactly as an
oracle condition asks what a model could do if it were handed the answer. Nothing here
recommends adopting it and no `lambda` is better than another.
Part B ships with two controls, because a null from a supervised head has two ways of
being an artefact rather than a result. `--target type` supervises `M` toward the
entity's own type instead, a signal that is in `attrs` and therefore certainly
reachable: if the head cannot install *that*, it is not connected. `--head mlp` and
`--mlp-probe` replace the linear head and the linear probe with 2x128 ReLU networks,
because `results/when_memory_works.md` §2b measured a linear decoder reading 0.23 on
this exact target where an MLP reads 0.83 -- a linear-only null would inherit that
objection.
`_build`, `_train`, `_frozen`, `_metrics` and `probe` are `frozen.py`'s, called
unchanged; `_train`'s `aux`/`extra_params` keywords are the only addition, and they
default to off so every earlier caller's run stays bit-identical (pinned by
`tests/test_frozen.py::test_train_copy_is_identical_to_regime_run`). The non-linear
probe is registered into `frozen.ESTIMATORS` rather than forked from `probe`; the one
line that made that possible is `frozen._scores` accepting a callable.
"""
from __future__ import annotations
import argparse
import json
import math
import statistics
from functools import partial
from pathlib import Path
import numpy as np
import torch
from torch import Tensor, nn
import frozen as frozen_mod
from frozen import FROZEN_STEPS, SPLIT, TRAIN_STEPS, _build, _frozen, _hidden, _train, probe
from regime import _metrics
# the two blocks hypothesis (a) is about, and two reference blocks that are certainly
# trained: `out.weight` is one linear map from the prediction, `rp.feat.weight` sits
# under everything. Both gate and cand take [h ‖ M], so their column halves are split
# out too -- the M half is the only place a temporal path can enter them.
BLOCKS = ("gate", "cand", "feat", "out", "gate[h]", "gate[M]", "cand[h]", "cand[M]")
LAMBDAS = (0.0, 1e-5, 1e-4, 1e-3, 1e-2, 1e-1, 1.0)
TARGETS = ("regime", "type")
def _params(org) -> list[Tensor]:
return [org.grp.gate.weight, org.grp.cand.weight, org.rp.feat.weight, org.out.weight]
def _split_blocks(gs: list[Tensor], d: int) -> dict[str, Tensor]:
"""The four whole blocks plus the column halves of gate and cand."""
gate, cand, feat, out = gs
return {"gate": gate, "cand": cand, "feat": feat, "out": out,
"gate[h]": gate[:, :d], "gate[M]": gate[:, d:],
"cand[h]": cand[:, :d], "cand[M]": cand[:, d:]}
# -- Part A: where the gradient goes ---------------------------------------------
class GradTrace:
"""Records, per optimiser step, the gradient each block receives.
Three gradients are held for every window, all at the same parameters and from the
same data:
- `carried` -- the real training gradient, `M` carried across the window
- `detached` -- the same window with `M` detached every step: the per-step term
- `temporal` -- their difference, which is the credit that flows through time
`carried` is *also* checked against the gradient the optimiser actually used, read
off the real backward through a parameter hook, so a replay bug cannot masquerade
as a temporal effect.
"""
def __init__(self, org, bptt: int, tol: float = 1e-9):
self.org, self.bptt, self.tol = org, bptt, tol
self.d = org.hidden_dim
self.params = _params(org)
self.carried: list[list[Tensor]] = []
self.detached: list[list[Tensor]] = []
self.win: list[tuple] = []
self.win_M: list[Tensor] = []
self.prev0: Tensor | None = None
self.pending: list[Tensor] | None = None
self.replaying = False # the replay's own backward must not trip the pin
self.max_rel = 0.0 # worst disagreement replay vs. the real backward
self.n_checked = 0
self.loss_equal = True # detaching left every forward value untouched
self._seen: dict[int, Tensor] = {}
for k, p in enumerate(self.params):
p.register_hook(partial(self._check, k))
# -- the pin: what the optimiser actually used --------------------------------
def _check(self, k: int, g: Tensor) -> Tensor:
"""Fires on the real backward, with the gradient Adam is about to consume.
One closure per parameter: `gate.weight` and `cand.weight` have the same shape,
so the hooks cannot be told apart after the fact and the index is bound here.
"""
if self.replaying or self.pending is None:
return g
self._seen[k] = g.detach().clone()
if len(self._seen) == len(self.params):
for i, want in enumerate(self.pending):
rel = float((want - self._seen[i]).norm()) / (float(want.norm()) + 1e-30)
self.max_rel = max(self.max_rel, rel)
assert rel < self.tol, f"replay disagrees with the real backward: {rel:.2e}"
self.n_checked += 1
self._seen, self.pending = {}, None
return g
# -- the replay ---------------------------------------------------------------
def _replay(self, carry: bool) -> Tensor:
"""Re-run the window at the current parameters. Only the graph changes.
Every forward value is asserted bit-identical to the `M` the organism computed
during training, which is what makes the carried/detached difference a
statement about time and not about anything else.
"""
org, prev = self.org, self.prev0
losses = []
for k, (obs, r, ctx, axes) in enumerate(self.win):
held = {i: prev[j] for j, i in enumerate(obs.ids)}
pred, mem = org(obs.attrs, r, obs.ids, axes, held, context=ctx)
M = torch.stack([mem[i] for i in obs.ids])
assert torch.equal(M.detach(), self.win_M[k]), "replayed M diverged from the organism's"
losses.append(((pred - obs.target) ** 2).mean())
prev = M if carry else M.detach()
return torch.stack(losses).mean()
def _measure(self) -> None:
self.replaying = True
try:
Lc = self._replay(carry=True)
gc = [g.detach().clone() for g in torch.autograd.grad(Lc, self.params)]
Ld = self._replay(carry=False)
gd = [g.detach().clone() for g in torch.autograd.grad(Ld, self.params)]
finally:
self.replaying = False
self.loss_equal &= bool(torch.equal(Lc.detach(), Ld.detach()))
self.carried.append(gc)
self.detached.append(gd)
self.pending = gc # the real backward, next, must reproduce these
def on_step(self, t, obs, r, ctx, axes, prev, memory) -> None:
if not self.win:
self.prev0 = prev.detach().clone()
self.win.append((obs, r, ctx, axes))
self.win_M.append(torch.stack([memory[i] for i in obs.ids]).detach().clone())
if len(self.win) == self.bptt:
self._measure()
self.win, self.win_M = [], []
# -- the measurement ----------------------------------------------------------
def _paths(self, i: int) -> dict[str, dict[str, Tensor]]:
c = _split_blocks(self.carried[i], self.d)
d = _split_blocks(self.detached[i], self.d)
return {"carried": c, "detached": d,
"temporal": {b: c[b] - d[b] for b in BLOCKS}}
def summary(self, n_null: int = 40, seed: int = 0) -> dict:
"""‖mean gradient‖ against mean ‖gradient‖, per block and per path.
The ratio is the whole of Part A: near 1 the signal is coherent, near 0 it
cancels. Its floor is not 0 -- averaging `n` directions that agree about
nothing still leaves `~1/sqrt(n)` behind -- so the floor is measured the way
every other chance level in this repo is, by destroying the effect and keeping
everything else: each optimiser step's gradient vector is multiplied by a
random sign, which removes any consistent direction and leaves every magnitude
exactly as it was.
`tail_` repeats the ratio over the second half of the optimiser steps, the
segment `regime._metrics` reports the error on, where a signal that only
arrives late in training would show.
"""
n = len(self.carried)
rng = np.random.default_rng(seed)
S = torch.tensor(rng.choice([-1.0, 1.0], size=(n_null, n)), dtype=torch.float32)
by_step = [self._paths(i) for i in range(n)]
t0 = n // 2
out: dict[str, dict] = {}
for b in BLOCKS:
per_path: dict = {}
for tag in ("carried", "detached", "temporal"):
V = torch.stack([s[tag][b].reshape(-1) for s in by_step]) # (n, d)
norms = V.norm(dim=1)
mean_norm = float(norms.mean())
mv = float(V.mean(0).norm())
null = float(((S @ V).norm(dim=1) / n).mean())
# what Adam actually consumes. Its step is lr * m / (sqrt(v) + eps),
# which is invariant to a uniform rescaling of the gradient, so a
# magnitude on its own says nothing about whether a block can move.
# This is the same ratio as `coherence`, taken per coordinate, and it
# is the factor by which a coordinate's step is shrunk from the full
# lr: 1 means every step agreed, 0 means they cancelled.
rms = V.pow(2).mean(0).sqrt() + 1e-30
snr = float((V.mean(0).abs() / rms).mean())
snr_null = float(statistics.fmean(
float(((S[k][:, None] * V).mean(0).abs() / rms).mean())
for k in range(n_null)))
tmean = float(norms[t0:].mean())
tmv = float(V[t0:].mean(0).norm())
per_path[tag] = dict(
mean_norm=mean_norm, norm_of_mean=mv, adam_snr=snr, adam_snr_null=snr_null,
coherence=mv / mean_norm if mean_norm > 0 else float("nan"),
null=null / mean_norm if mean_norm > 0 else float("nan"),
tail_mean_norm=tmean, tail_norm_of_mean=tmv,
tail_coherence=tmv / tmean if tmean > 0 else float("nan"),
)
per_step = per_path["detached"]["mean_norm"]
per_path["temporal_share"] = (per_path["temporal"]["mean_norm"] / per_step
if per_step > 0 else float("nan"))
out[b] = per_path
return dict(n_steps=n, blocks=out, n_checked=self.n_checked,
max_rel_vs_real_backward=self.max_rel, loss_equal=self.loss_equal)
def _gate_function(org, w0: Tensor, b0: Tensor, inputs: list[tuple]) -> dict:
"""What the gate's displacement did to the gate.
The gradient measurement says how much signal arrived; this says what arriving
changed. The pre-activation `W_g[h‖M] + b_g − κa` is evaluated on the *same*
inputs -- the ones the trained organism actually produces -- under the trained
weights and under the weights at initialisation. If the two agree, the block moved
and the function it computes did not.
"""
H = torch.cat([torch.cat([h, m], -1) for h, m, _ in inputs])
a = torch.tensor([ar for _, _, ar in inputs]).repeat_interleave(inputs[0][0].shape[0])
with torch.no_grad():
pre_t = (org.grp.gate(H).T - org.grp.kappa * a).T
pre_0 = (torch.nn.functional.linear(H, w0, b0).T - org.grp.kappa * a).T
g_t, g_0 = torch.sigmoid(pre_t), torch.sigmoid(pre_0)
c = torch.corrcoef(torch.stack([pre_t.reshape(-1), pre_0.reshape(-1)]))[0, 1]
return dict(
pre_trained_mean=float(pre_t.mean()), pre_trained_sd=float(pre_t.std()),
pre_init_mean=float(pre_0.mean()), pre_init_sd=float(pre_0.std()),
g_trained_mean=float(g_t.mean()), g_trained_sd=float(g_t.std()),
g_init_mean=float(g_0.mean()), g_init_sd=float(g_0.std()),
pre_rms_change=float((pre_t - pre_0).pow(2).mean().sqrt()),
pre_corr=float(c), n_samples=int(pre_t.numel()),
)
def part_a(seed: int, train_steps: int = TRAIN_STEPS, bptt: int = 20, lr: float = 1e-3,
hidden: int = 32, omega: float = 10.0, gate_window: int = 500) -> dict:
spec, wcfg, world, org = _build("grp_k0", seed, hidden, omega, kappa=4.0)
tr = GradTrace(org, bptt)
before = {b: v.detach().clone() for b, v in _split_blocks(_params(org), org.hidden_dim).items()}
w0, b0 = org.grp.gate.weight.detach().clone(), org.grp.gate.bias.detach().clone()
tail: list[tuple] = []
def on_step(t, obs, r, ctx, axes, prev, memory):
tr.on_step(t, obs, r, ctx, axes, prev, memory)
if t >= train_steps - gate_window: # the inputs the trained organism produces
with torch.no_grad():
tail.append((_hidden(org, obs.attrs, r, axes, ctx), prev.detach().clone(), axes[1]))
_, _, trace = _train(spec, wcfg, world, org, train_steps, bptt, lr, on_step=on_step)
after = _split_blocks(_params(org), org.hidden_dim)
s = tr.summary()
# how far each block actually travelled, relative to where it started. Adam's step
# is lr * m / (sqrt(v) + eps) and so is invariant to a uniform rescaling of the
# gradient: a block with a tiny gradient can still move a long way. This is what
# turns the gradient measurement into a statement about weights.
for b in BLOCKS:
s["blocks"][b]["displacement"] = float((after[b].detach() - before[b]).norm())
s["blocks"][b]["displacement_rel"] = (s["blocks"][b]["displacement"]
/ float(before[b].norm()))
s["gate_function"] = _gate_function(org, w0, b0, tail)
s.update(seed=seed, train_steps=train_steps, bptt=bptt,
trained=_metrics(trace["losses"], trace["switched"], trace["arousals"], 20))
return s
# -- Part B: the ceiling ----------------------------------------------------------
def _mlp(d_in: int, n_cls: int, width: int, seed: int) -> nn.Module:
with torch.random.fork_rng(): # the organism and the world keep their stream
torch.manual_seed(seed)
return nn.Sequential(nn.Linear(d_in, width), nn.ReLU(),
nn.Linear(width, width), nn.ReLU(), nn.Linear(width, n_cls))
def _fit_mlp(X: np.ndarray, y: np.ndarray, R: int, width: int = 128, steps: int = 400,
lr: float = 3e-3, seed: int = 0):
"""A 2x128 ReLU decoder, registered into `frozen.ESTIMATORS` rather than copied.
`results/when_memory_works.md` §2b is why this exists: on this exact target a
linear decoder on the raw window reads 0.23 at every history length while an MLP
on the same features reads 0.83. A linear-only probe would report "not there" for
a signal that is there non-linearly, so the null in this file needs both.
"""
net = _mlp(X.shape[1], R, width, seed)
Xt = torch.tensor(X, dtype=torch.float32)
yt = torch.tensor(y, dtype=torch.long)
opt = torch.optim.Adam(net.parameters(), lr=lr)
for _ in range(steps):
opt.zero_grad()
nn.functional.cross_entropy(net(Xt), yt).backward()
opt.step()
def score(design: np.ndarray) -> np.ndarray:
with torch.no_grad():
return net(torch.tensor(design, dtype=torch.float32)).numpy()
return score
# `probe` resolves its estimator through this table, so adding an entry extends the
# published probe rather than forking it. `_scores` already accepts a callable.
frozen_mod.ESTIMATORS["mlp"] = _fit_mlp
class AuxHead:
"""A linear head from `M_i` to a categorical target, trained jointly with the task.
The measuring instrument, not an architecture. `target="regime"` supervises the
state to hold the world's current regime id -- the thing hypothesis (a) says the
loss never asked for. `target="type"` supervises it to hold the entity's own type,
a signal that is in `attrs` and therefore certainly reachable: the positive control
that tells a null apart from a broken head.
"""
def __init__(self, org, world, n_cls: int, lam: float, target: str, seed: int,
kind: str = "linear", width: int = 128):
if kind == "linear":
with torch.random.fork_rng(): # the organism and the world keep their stream
torch.manual_seed(9000 + seed)
self.head = nn.Linear(org.hidden_dim, n_cls)
else:
self.head = _mlp(org.hidden_dim, n_cls, width, 9000 + seed)
self.world, self.lam, self.target, self.kind = world, lam, target, kind
self.hits: list[float] = []
def labels(self, obs) -> Tensor:
if self.target == "regime":
return torch.full((obs.attrs.shape[0],), obs.regime, dtype=torch.long)
return self.world.types.long()
def __call__(self, t, obs, memory) -> Tensor:
M = torch.stack([memory[i] for i in obs.ids])
y = self.labels(obs)
logits = self.head(M)
self.hits.append(float((logits.detach().argmax(-1) == y).float().mean()))
return self.lam * nn.functional.cross_entropy(logits, y)
def accuracy(self, half: bool = True) -> float:
h = self.hits[len(self.hits) // 2:] if half else self.hits
return statistics.fmean(h) if h else float("nan")
def part_b(seed: int, lam: float, target: str = "regime", train_steps: int = TRAIN_STEPS,
frozen_steps: int = FROZEN_STEPS, bptt: int = 20, lr: float = 1e-3,
hidden: int = 32, omega: float = 10.0, window: int = 20,
split: float = SPLIT, n_null: int = 20, head_kind: str = "linear",
mlp_probe: bool = False) -> dict:
"""Train `grp_k0` with the auxiliary head at `lam`, freeze, then probe as Task 7b did.
At `lam == 0` no head is built and `aux` is None, so the loop is literally the one
that produced the 0.332 baseline and this row is that baseline (pinned by
`tests/test_credit.py::test_lambda_zero_reproduces_the_frozen_baseline`).
"""
spec, wcfg, world, org = _build("grp_k0", seed, hidden, omega, kappa=4.0)
n_cls = wcfg.n_regimes if target == "regime" else wcfg.n_types
head = AuxHead(org, world, n_cls, lam, target, seed, head_kind) if lam > 0 else None
affect, memory, trace = _train(
spec, wcfg, world, org, train_steps, bptt, lr,
aux=head, extra_params=() if head is None else head.head.parameters())
fr = _frozen(spec, wcfg, world, org, affect, memory, frozen_steps)
assert fr["frozen_bit_identical"] and fr["dM_min"] > 0.0
labels = np.asarray(fr["regimes"])
types = world.types.numpy()
args = dict(split=split, n_null=n_null, seed=seed)
probes = {
# the regime decode, the number comparable with frozen.md Part B's 0.332
"M_regime": probe(fr["M"], labels, fr["switched"], wcfg.n_regimes, **args),
"h_regime": probe(fr["h"], labels, fr["switched"], wcfg.n_regimes, **args),
# the entity's own type: a signal known to be in M, so a floor on the probe
"M_type": probe(fr["M"], np.tile(types, (len(labels), 1)), fr["switched"],
wcfg.n_types, **args),
}
# both of `probe`'s nulls are degenerate for a target that is constant in time --
# permuting or circularly shifting the step axis of a label array whose rows are all
# identical returns that same array, so they report the accuracy back as its own
# chance level. The type's chance level therefore comes from permuting the
# assignment across entities, which breaks the association and keeps the marginal.
rp = np.random.default_rng(seed)
probes["M_type"]["degenerate_time_null"] = (
probes["M_type"]["chance_shift"] == probes["M_type"]["acc_entity"])
probes["M_type"]["chance_entity_perm"] = float(np.mean([
probe(fr["M"], np.tile(types[rp.permutation(len(types))], (len(labels), 1)),
fr["switched"], wcfg.n_types, split=split, n_null=1, seed=seed)["acc_entity"]
for _ in range(5)]))
if mlp_probe:
# the same split, the same two nulls, a decoder that is not linear
probes["M_regime_mlp"] = probe(fr["M"], labels, fr["switched"], wcfg.n_regimes,
split=split, n_null=5, seed=seed, estimator="mlp")
probes["h_regime_mlp"] = probe(fr["h"], labels, fr["switched"], wcfg.n_regimes,
split=split, n_null=5, seed=seed, estimator="mlp")
return dict(condition="grp_k0", seed=seed, lam=lam, target=target, head_kind=head_kind,
train_steps=train_steps, frozen_steps=frozen_steps,
trained=_metrics(trace["losses"], trace["switched"], trace["arousals"], window),
frozen=_metrics(fr["losses"], fr["switched"], fr["arousals"], window),
aux_train_acc=head.accuracy() if head else float("nan"),
gate=fr["gate"], probes=probes)
def trajectory(seed: int, lam: float = 1.0, bucket: int = 1000,
train_steps: int = TRAIN_STEPS, bptt: int = 20, lr: float = 1e-3,
hidden: int = 32, omega: float = 10.0, head_kind: str = "linear") -> dict:
"""The auxiliary head's accuracy over training, bucketed.
Separates "cannot" from "has not yet": a head that is going to get there climbs,
and one that is not wanders. Reported for both targets at the same lambda, so the
two curves are the same measurement on a reachable and an unreachable signal.
"""
out = {}
for target in TARGETS:
spec, wcfg, world, org = _build("grp_k0", seed, hidden, omega, kappa=4.0)
n_cls = wcfg.n_regimes if target == "regime" else wcfg.n_types
head = AuxHead(org, world, n_cls, lam, target, seed, head_kind)
_train(spec, wcfg, world, org, train_steps, bptt, lr,
aux=head, extra_params=head.head.parameters())
out[target] = dict(
chance=1.0 / n_cls,
curve=[statistics.fmean(head.hits[i:i + bucket])
for i in range(0, len(head.hits), bucket)])
return dict(seed=seed, lam=lam, bucket=bucket, head_kind=head_kind, targets=out)
def trajectory_table(runs: list[dict]) -> str:
lines = [f"{'target':<8}{'chance':>8}{'seed':>6}" +
"".join(f"{'@' + str((i + 1)) + 'k':>8}" for i in range(len(runs[0]["targets"]["regime"]["curve"]))),
"-" * 80]
for target in TARGETS:
for r in runs:
c = r["targets"][target]
lines.append(f"{target:<8}{c['chance']:>8.3f}{r['seed']:>6}" +
"".join(f"{v:>8.3f}" for v in c["curve"]))
return "\n".join(lines)
# -- reporting --------------------------------------------------------------------
def _se(xs: list[float]) -> float:
return statistics.stdev(xs) / math.sqrt(len(xs)) if len(xs) > 1 else 0.0
def grad_table(runs: list[dict]) -> str:
"""Magnitudes first, then the ratio they make."""
lines = [f"{'block':<9}{'‖mean g‖':>11}{'mean ‖g‖':>11}{'coher':>8}{'null':>7}"
f"{'snr':>7}{'snr null':>9}{'|dW|/|W|':>10}"
f"{'‖temporal‖':>12}{'‖per-step‖':>12}{'temp/step':>11}", "-" * 105]
for b in BLOCKS:
get = lambda path, f: statistics.fmean(r["blocks"][b][path][f] for r in runs)
at = lambda f: statistics.fmean(r["blocks"][b][f] for r in runs)
lines.append(
f"{b:<9}{get('carried', 'norm_of_mean'):>11.3e}{get('carried', 'mean_norm'):>11.3e}"
f"{get('carried', 'coherence'):>8.3f}{get('carried', 'null'):>7.3f}"
f"{get('carried', 'adam_snr'):>7.3f}{get('carried', 'adam_snr_null'):>9.3f}"
f"{at('displacement_rel'):>10.3f}"
f"{get('temporal', 'mean_norm'):>12.3e}{get('detached', 'mean_norm'):>12.3e}"
f"{at('temporal_share'):>11.3f}")
return "\n".join(lines)
def coherence_table(runs: list[dict]) -> str:
"""The measurement: is the signal coherent, or does it cancel?
Every block is read against *its own* measured null, because the floor depends on
how unevenly that block's gradient magnitude is spread over the run and is not the
same number for all of them.
"""
lines = [f"{'block':<9}{'coherence':>11}{'null':>8}{'excess':>9}{'paired se':>11}"
f"{'>null':>8}{'adam snr':>10}{'null':>7}{'excess':>9}{'se':>8}", "-" * 90]
for b in BLOCKS:
c = [r["blocks"][b]["carried"]["coherence"] for r in runs]
z = [r["blocks"][b]["carried"]["null"] for r in runs]
sn = [r["blocks"][b]["carried"]["adam_snr"] for r in runs]
zn = [r["blocks"][b]["carried"]["adam_snr_null"] for r in runs]
d = [x - y for x, y in zip(c, z)]
e = [x - y for x, y in zip(sn, zn)]
lines.append(
f"{b:<9}{statistics.fmean(c):>11.3f}{statistics.fmean(z):>8.3f}"
f"{statistics.fmean(d):>+9.3f}{_se(d):>11.3f}{sum(x > 0 for x in d):>5}/{len(d):<2}"
f"{statistics.fmean(sn):>10.3f}{statistics.fmean(zn):>7.3f}"
f"{statistics.fmean(e):>+9.3f}{_se(e):>8.3f}")
return "\n".join(lines)
def magnitude_table(runs: list[dict]) -> str:
"""How big "negligible" is, against the blocks that certainly train.
`gate` and `cand` have identical shapes and read identical inputs, so their ratio
is the like-for-like one; `per-par` divides by sqrt(#params) so the others are
comparable too.
"""
npar = {"gate": 2048, "cand": 2048, "feat": 96, "out": 64,
"gate[h]": 1024, "gate[M]": 1024, "cand[h]": 1024, "cand[M]": 1024}
g0 = statistics.fmean(r["blocks"]["gate"]["carried"]["mean_norm"] for r in runs)
lines = [f"{'block':<9}{'n_par':>7}{'mean ‖g‖':>11}{'per-par':>11}{'x gate':>9}"
f"{'x gate/par':>12}{'|dW|/|W|':>11}", "-" * 70]
for b in BLOCKS:
m = statistics.fmean(r["blocks"][b]["carried"]["mean_norm"] for r in runs)
pp = m / math.sqrt(npar[b])
lines.append(f"{b:<9}{npar[b]:>7}{m:>11.3e}{pp:>11.3e}{m / g0:>9.1f}"
f"{pp / (g0 / math.sqrt(npar['gate'])):>12.1f}"
f"{statistics.fmean(r['blocks'][b]['displacement_rel'] for r in runs):>11.4f}")
return "\n".join(lines)
def grad_per_seed(runs: list[dict], field: str = "coherence", path: str = "carried") -> str:
"""`field="temporal_share"` reads the block level; anything else reads a path."""
def cell(r, b):
v = r["blocks"][b]
return v[field] if field in v else v[path][field]
lines = [f"{'block':<9}" + "".join(f"{'s' + str(r['seed']):>8}" for r in runs),
"-" * (9 + 8 * len(runs))]
for b in BLOCKS:
lines.append(f"{b:<9}" + "".join(f"{cell(r, b):>8.3f}" for r in runs))
return "\n".join(lines)
def gate_table(runs: list[dict]) -> str:
"""The gate's pre-activation under the trained weights and under its initialisation."""
f = lambda k: statistics.fmean(r["gate_function"][k] for r in runs)
rows = [("pre-activation mean", "pre_trained_mean", "pre_init_mean"),
("pre-activation sd", "pre_trained_sd", "pre_init_sd"),
("g mean", "g_trained_mean", "g_init_mean"),
("g sd", "g_trained_sd", "g_init_sd")]
lines = [f"{'quantity':<22}{'trained':>10}{'at init':>10}", "-" * 42]
lines += [f"{n:<22}{f(a):>10.4f}{f(b):>10.4f}" for n, a, b in rows]
lines.append(f"{'rms change in pre':<22}{f('pre_rms_change'):>10.4f}")
lines.append(f"{'corr(trained, init)':<22}{f('pre_corr'):>10.4f}")
return "\n".join(lines)
def _by_lam(runs: list[dict]) -> dict[float, list[dict]]:
by: dict[float, list[dict]] = {}
for r in runs:
by.setdefault(r["lam"], []).append(r)
return {k: sorted(v, key=lambda r: r["seed"]) for k, v in sorted(by.items())}
def aux_table(runs: list[dict], key: str = "M_regime") -> str:
"""Reading 1: can the state hold it, measured against both nulls."""
lines = [f"{'lambda':>8}{'aux(train)':>12}{'probe acc':>11}{'shuffle':>9}{'shift':>8}"
f"{'gap':>8}{'sd':>7}{'>chance':>9}{'M_type':>9}{'(perm)':>9}", "-" * 90]
for lam, rs in _by_lam(runs).items():
acc = [r["probes"][key]["acc_entity"] for r in rs]
shuf = [r["probes"][key]["chance_shuffle"] for r in rs]
shift = [r["probes"][key]["chance_shift"] for r in rs]
gap = [a - c for a, c in zip(acc, shift)]
ty = [r["probes"]["M_type"]["acc_entity"] for r in rs]
tyc = [r["probes"]["M_type"]["chance_entity_perm"] for r in rs]
aux = statistics.fmean(r["aux_train_acc"] for r in rs) if lam > 0 else float("nan")
lines.append(
f"{lam:>8.0e}{aux:>12.3f}{statistics.fmean(acc):>11.3f}{statistics.fmean(shuf):>9.3f}"
f"{statistics.fmean(shift):>8.3f}{statistics.fmean(gap):>+8.3f}"
f"{statistics.stdev(gap) if len(gap) > 1 else 0:>7.3f}"
f"{sum(g > 0 for g in gap):>6}/{len(gap):<3}{statistics.fmean(ty):>9.3f}"
f"{statistics.fmean(tyc):>9.3f}")
return "\n".join(lines)
def task_table(runs: list[dict], phase: str = "trained") -> str:
"""Reading 2: does the main task move, paired per seed against lambda = 0."""
by = _by_lam(runs)
base = {r["seed"]: r[phase]["steady"] for r in by.get(0.0, [])}
lines = [f"{'lambda':>8}{'steady':>11}{'ratio l0/l':>12}{'won':>8}{'log-ratio':>11}"
f"{'paired se':>11}{'reading':>12}", "-" * 73]
for lam, rs in by.items():
st = [r[phase]["steady"] for r in rs]
mean = statistics.fmean(st)
if lam == 0.0 or not base:
lines.append(f"{lam:>8.0e}{mean:>11.3e}{'--':>12}{'--':>8}{'--':>11}{'--':>11}{'--':>12}")
continue
pairs = [(base[r["seed"]], r[phase]["steady"]) for r in rs if r["seed"] in base]
lr_ = [math.log(b / x) for b, x in pairs] # > 0 means lambda helped
se, m = _se(lr_), statistics.fmean(lr_)
reading = "ambiguous" if abs(m) < se else ("lower err" if m > 0 else "higher err")
lines.append(f"{lam:>8.0e}{mean:>11.3e}{math.exp(m):>12.3f}"
f"{sum(x > 0 for x in lr_):>5}/{len(lr_):<2}{m:>+11.4f}{se:>11.4f}{reading:>12}")
return "\n".join(lines)
def per_seed_task(runs: list[dict], phase: str = "trained") -> str:
by = _by_lam(runs)
seeds = [r["seed"] for r in next(iter(by.values()))]
lines = [f"{'lambda':>8}" + "".join(f"{'s' + str(s):>10}" for s in seeds),
"-" * (8 + 10 * len(seeds))]
for lam, rs in by.items():
lines.append(f"{lam:>8.0e}" + "".join(f"{r[phase]['steady']:>10.2e}" for r in rs))
return "\n".join(lines)
def per_seed_gap(runs: list[dict], key: str = "M_regime") -> str:
by = _by_lam(runs)
seeds = [r["seed"] for r in next(iter(by.values()))]
lines = [f"{'lambda':>8}" + "".join(f"{'s' + str(s):>8}" for s in seeds),
"-" * (8 + 8 * len(seeds))]
for lam, rs in by.items():
lines.append(f"{lam:>8.0e}" + "".join(
f"{r['probes'][key]['acc_entity'] - r['probes'][key]['chance_shift']:>+8.3f}"
for r in rs))
return "\n".join(lines)
def joint(runs: list[dict], phase: str = "trained", key: str = "M_regime") -> str:
"""Reading 3: cross reading 1 with reading 2, which is what the verdict is read off.
Both columns are *paired changes against lambda = 0*, per seed, with a paired
standard error. The absolute gap is not the question -- the lambda = 0 row already
sits +0.044 above its null, which is the instantaneous read-off `frozen.md` §2 and
`pooled.md` both identified and neither attributed to memory. The question is
whether being told the regime raises it.
"""
by = _by_lam(runs)
base_s = {r["seed"]: r[phase]["steady"] for r in by.get(0.0, [])}
base_g = {r["seed"]: r["probes"][key]["acc_entity"] - r["probes"][key]["chance_shift"]
for r in by.get(0.0, [])}
lines = [f"{'lambda':>8}{'gap':>8}{'d(gap) vs l=0':>15}{'se':>8}{'won':>7}"
f"{'task log-ratio':>16}{'se':>8}{'won':>7}{'quadrant':>28}", "-" * 97]
for lam, rs in by.items():
gap = [r["probes"][key]["acc_entity"] - r["probes"][key]["chance_shift"] for r in rs]
if lam == 0.0:
lines.append(f"{lam:>8.0e}{statistics.fmean(gap):>+8.3f}{'--':>15}{'--':>8}"
f"{'--':>7}{'--':>16}{'--':>8}{'--':>7}{'(baseline)':>28}")
continue
dg = [g - base_g[r["seed"]] for g, r in zip(gap, rs) if r["seed"] in base_g]
lr_ = [math.log(base_s[r["seed"]] / r[phase]["steady"]) for r in rs if r["seed"] in base_s]
m, mse = statistics.fmean(dg), _se(dg)
t, tse = statistics.fmean(lr_), _se(lr_)
held = "no change in M" if abs(m) < mse else ("M holds more" if m > 0 else "M holds less")
moved = "task ambiguous" if abs(t) < tse else ("task improves" if t > 0 else "task worsens")
lines.append(f"{lam:>8.0e}{statistics.fmean(gap):>+8.3f}{m:>+15.3f}{mse:>8.3f}"
f"{sum(x > 0 for x in dg):>4}/{len(dg):<2}{t:>+16.4f}{tse:>8.4f}"
f"{sum(x > 0 for x in lr_):>4}/{len(lr_):<2}{held + ', ' + moved:>28}")
return "\n".join(lines)
# -- driver -----------------------------------------------------------------------
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--part", choices=("grad", "aux", "traj"), default="grad")
ap.add_argument("--seeds", default="0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15")
ap.add_argument("--lambdas", default=",".join(str(l) for l in LAMBDAS))
ap.add_argument("--target", choices=TARGETS, default="regime")
ap.add_argument("--head", choices=("linear", "mlp"), default="linear",
help="the auxiliary head's form. `mlp` is the control on whether a "
"linear head was the binding constraint rather than M")
ap.add_argument("--mlp-probe", action="store_true",
help="also decode the frozen M with a 2x128 MLP, same splits and nulls")
ap.add_argument("--train-steps", type=int, default=TRAIN_STEPS)
ap.add_argument("--frozen-steps", type=int, default=FROZEN_STEPS)
ap.add_argument("--lr", type=float, default=1e-3)
ap.add_argument("--out", default=None)
ap.add_argument("--report", default=None,
help="comma-separated result files to report on instead of running. "
"Seeds are independent, so a sweep may be sharded across "
"processes and merged here; the tables are the same either way.")
a = ap.parse_args()
seeds = [int(s) for s in a.seeds.split(",")]
if a.report:
runs = [r for f in a.report.split(",") for r in json.loads(Path(f).read_text())]
runs.sort(key=lambda r: (r["lam"], r["seed"]))
_report_aux(runs, mlp="M_regime_mlp" in runs[0]["probes"],
target=runs[0]["target"])
return
if a.part == "grad":
runs = []
for seed in seeds:
r = part_a(seed, a.train_steps, lr=a.lr)
g = r["blocks"]
print(f"seed={seed} coherence gate={g['gate']['carried']['coherence']:.3f} "
f"cand={g['cand']['carried']['coherence']:.3f} "
f"feat={g['feat']['carried']['coherence']:.3f} "
f"out={g['out']['carried']['coherence']:.3f} | "
f"temporal/per-step gate={g['gate']['temporal_share']:.4f} "
f"cand={g['cand']['temporal_share']:.4f} "
f"(replay pinned on {r['n_checked']} windows, max rel "
f"{r['max_rel_vs_real_backward']:.1e})", flush=True)
runs.append(r)
out = a.out or "results/credit_grad.json"
Path(out).parent.mkdir(parents=True, exist_ok=True)
Path(out).write_text(json.dumps(runs, indent=1, default=float))
print("\n=== Part A ===")
print(grad_table(runs))
print("\ncoherence against each block's own measured null:")
print(coherence_table(runs))
print("\nmagnitudes:")
print(magnitude_table(runs))
print("\nwhat the displacement did to the gate (same inputs, trained vs initial weights):")
print(gate_table(runs))
print("\nper-seed coherence (carried):")
print(grad_per_seed(runs))
print("\nper-seed temporal/per-step:")
print(grad_per_seed(runs, "temporal_share"))
return
if a.part == "traj":
runs = [trajectory(seed, lam=max(float(x) for x in a.lambdas.split(",")),
train_steps=a.train_steps, lr=a.lr, head_kind=a.head)
for seed in seeds]
out = a.out or "results/credit_traj.json"
Path(out).parent.mkdir(parents=True, exist_ok=True)
Path(out).write_text(json.dumps(runs, indent=1, default=float))
print("\n=== the auxiliary head's accuracy over training ===")
print(trajectory_table(runs))
return
lams = [float(x) for x in a.lambdas.split(",")]
runs = []
for lam in lams:
for seed in seeds:
r = part_b(seed, lam, a.target, a.train_steps, a.frozen_steps, lr=a.lr,
head_kind=a.head, mlp_probe=a.mlp_probe)
p = r["probes"]["M_regime"]
print(f"lam={lam:<7g} seed={seed:<2} steady={r['trained']['steady']:.3e} "
f"aux={r['aux_train_acc']:.3f} M_regime={p['acc_entity']:.3f}"
f"/{p['chance_shift']:.3f} M_type={r['probes']['M_type']['acc_entity']:.3f} "
f"g={r['gate']['mean']:.3f}", flush=True)
runs.append(r)
out = a.out or f"results/credit_aux_{a.target}_{a.head}.json"
Path(out).parent.mkdir(parents=True, exist_ok=True)
Path(out).write_text(json.dumps(runs, indent=1, default=float))
_report_aux(runs, mlp=a.mlp_probe, target=a.target)
def _report_aux(runs: list[dict], mlp: bool, target: str) -> None:
print(f"\n=== Part B, target={target}, head={runs[0].get('head_kind', 'linear')} ===")
print("1. can the state hold it (M -> regime, frozen-phase probe):")
print(aux_table(runs))
if mlp:
print("\n the same M decoded by a 2x128 MLP instead:")
print(aux_table(runs, "M_regime_mlp"))
print("\n and the memoryless h, same MLP decoder:")
print(aux_table(runs, "h_regime_mlp"))
print("\n2. does the main task move (trained phase):")
print(task_table(runs, "trained"))
print("\n frozen phase:")
print(task_table(runs, "frozen"))
print("\nper-seed trained steady:")
print(per_seed_task(runs, "trained"))
print("\nper-seed regime gap above the shift null:")
print(per_seed_gap(runs))
print("\n3. the joint reading:")
print(joint(runs))
if mlp:
print("\n the joint reading on the MLP decode:")
print(joint(runs, key="M_regime_mlp"))
if __name__ == "__main__":
main()