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

+788
View File
@@ -0,0 +1,788 @@
"""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()
+23 -6
View File
@@ -67,14 +67,15 @@ def _build(name: str, seed: int, hidden: int, omega: float, kappa: float,
def _train(spec: dict, wcfg: ParticleConfig, world: ParticleWorld, org: Organism, def _train(spec: dict, wcfg: ParticleConfig, world: ParticleWorld, org: Organism,
steps: int, bptt: int, lr: float, stateless: bool = False, steps: int, bptt: int, lr: float, stateless: bool = False,
gate_arousal=None, on_step=None, acfg: AffectConfig | None = None): gate_arousal=None, on_step=None, acfg: AffectConfig | None = None,
aux=None, extra_params=()):
"""A verbatim copy of `regime.run`'s training loop (the keyword arguments aside). """A verbatim copy of `regime.run`'s training loop (the keyword arguments aside).
Copied rather than reused because `regime.run` returns metrics and drops the Copied rather than reused because `regime.run` returns metrics and drops the
organism and the world, and this task has to keep stepping the same world with organism and the world, and this task has to keep stepping the same world with
the same organism after training ends. `tests/test_frozen.py` pins the copy: it the same organism after training ends. `tests/test_frozen.py` pins the copy: it
asserts this loop reproduces `regime.run`'s metrics bit-identically. Every asserts this loop reproduces `regime.run`'s metrics bit-identically. Every
keyword below defaults to off, and with all three off the loop body is the same keyword below defaults to off, and with all of them off the loop body is the same
sequence of calls it always was. sequence of calls it always was.
`stateless=True` hands the organism an empty memory dict every step, so M_prev is `stateless=True` hands the organism an empty memory dict every step, so M_prev is
@@ -95,8 +96,15 @@ def _train(spec: dict, wcfg: ParticleConfig, world: ParticleWorld, org: Organism
`acfg` overrides the affect time constants for Task 9 Part 1. It defaults to `acfg` overrides the affect time constants for Task 9 Part 1. It defaults to
`AffectConfig()`, the value this loop always used, so the copy stays verbatim for `AffectConfig()`, the value this loop always used, so the copy stays verbatim for
every existing caller. `AffectConfig`'s own defaults are not touched. every existing caller. `AffectConfig`'s own defaults are not touched.
`aux(t, obs, memory) -> Tensor | None` returns a scalar added to the loss that is
put in `pending`, and `extra_params` are optimised alongside the organism's. This
is Task 11 Part B's oracle on the state: a supervised head is attached to M to ask
what the state *could* hold if it were told. **Affect and the reported `losses`
stay on the main-task loss alone**, so the metric `_metrics` computes is still the
task's and a run with `aux=None` is bit-identical to every earlier caller's.
""" """
opt = torch.optim.Adam(org.parameters(), lr=lr) opt = torch.optim.Adam(list(org.parameters()) + list(extra_params), lr=lr)
acfg = AffectConfig() if acfg is None else acfg acfg = AffectConfig() if acfg is None else acfg
affect = Affect() affect = Affect()
memory: dict[int, Tensor] = {} memory: dict[int, Tensor] = {}
@@ -118,7 +126,7 @@ def _train(spec: dict, wcfg: ParticleConfig, world: ParticleWorld, org: Organism
if on_step is not None and org.use_memory else None) if on_step is not None and org.use_memory else None)
pred, memory = org(obs.attrs, r, obs.ids, axes, held, context=ctx) pred, memory = org(obs.attrs, r, obs.ids, axes, held, context=ctx)
loss = ((pred - obs.target) ** 2).mean() loss = ((pred - obs.target) ** 2).mean()
pending.append(loss) pending.append(loss if aux is None else loss + aux(t, obs, memory))
affect = update(affect, loss.item(), acfg) affect = update(affect, loss.item(), acfg)
losses.append(loss.item()); switched.append(obs.switched); arousals.append(affect.arousal) losses.append(loss.item()); switched.append(obs.switched); arousals.append(affect.arousal)
if on_step is not None: if on_step is not None:
@@ -264,8 +272,17 @@ def _design(reps: np.ndarray, mu: np.ndarray, sd: np.ndarray) -> np.ndarray:
return np.concatenate([z, np.ones((z.shape[0], 1))], axis=1) return np.concatenate([z, np.ones((z.shape[0], 1))], axis=1)
def _scores(reps: np.ndarray, W: np.ndarray, mu: np.ndarray, sd: np.ndarray) -> np.ndarray: def _scores(reps: np.ndarray, W, mu: np.ndarray, sd: np.ndarray) -> np.ndarray:
return (_design(reps, mu, sd) @ W).reshape(reps.shape[0], reps.shape[1], -1) """An estimator returns either a linear map or a callable that scores a design.
The callable form is what lets a non-linear decoder use this probe unchanged --
`results/when_memory_works.md` §2b is the reason one is wanted: on this target a
linear decoder reads 0.23 where an MLP reads 0.83, so a linear-only probe would
answer a question nobody asked.
"""
X = _design(reps, mu, sd)
S = W(X) if callable(W) else X @ W
return np.asarray(S).reshape(reps.shape[0], reps.shape[1], -1)
def _accuracy(scores: np.ndarray, lab: np.ndarray, step_lab: np.ndarray | None) -> tuple[float, float]: def _accuracy(scores: np.ndarray, lab: np.ndarray, step_lab: np.ndarray | None) -> tuple[float, float]:
+541
View File
@@ -0,0 +1,541 @@
# Credit assignment: is there a signal, and is there a ceiling?
Task 11. `results/pooled.md` measured hypothesis (b) dead — the regime is not distributed
across the sixteen per-entity states, it is absent from them. Hypothesis (a) was what
remained:
> Nothing in the training signal rewards carrying the regime forward, so the state never
> learns to hold it.
This file measures the ceiling on (a) before anything is built, following the standing
methodology: a mechanism ships with an oracle that is *given* what the mechanism is
supposed to infer, and if the oracle does not pay, the mechanism has no job. **Direct
supervision is used here as a measuring instrument, an oracle on the state. It is not a
proposed architecture and nothing below recommends one.**
**Verdict: hypothesis (a) is not supported, and what replaces it is narrower and harder.
Part A finds the gate is neither starved of gradient nor cancelling it: the temporal path
supplies 59% of the gradient the gate receives, and after 8000 steps `gate.weight` has
travelled further from its initialisation than any other block measured — 27% of its own
norm, against `out.weight`'s 15%. Part B gives the brief's third outcome. Supervised
directly, at every weight from 1e-5 to 1.0, `M` does not come to hold the regime: the
auxiliary head never leaves chance, and the frozen-phase decode moves by −0.001 ± 0.019.
The same head, at the same weights, installs the entity's own type into `M` (0.738 against
a chance of 0.333) and — the control that matters — raises the *regime* decode by
+0.073 ± 0.022 while doing it. The instrument can move the number being read. Regime
supervision does not move it.**
The credit does reach the gate and does flow through time. What it cannot do is put this
hidden variable into this state.
Environment: `experiments/`, `ailed/` unmodified, no default in `particles.py` or
`regime.py` changed. `grp_k0`, 16 seeds (0-15), 8000 training steps then 4000 frozen steps,
`lr=1e-3`, `bptt=20`, `hidden=32`, `omega=10`, `kappa=0`. Test split is the last 30% of the
frozen phase, taken as a suffix in time. Part A: 16 runs, 400 optimiser steps each, three
gradients per step. Part B: 296 training runs.
```
uv run python credit.py --part grad --seeds 0,...,15 --out results/credit_grad.json
uv run python credit.py --part aux --target regime --seeds 0,...,15 \
--out results/credit_aux_regime.json
uv run python credit.py --part aux --target type --seeds 0,...,15 \
--out results/credit_aux_type.json # positive control
uv run python credit.py --part aux --target regime --head mlp --mlp-probe \
--lambdas 0.0,0.01,0.1,1.0 --seeds 0,...,15 # non-linear control
uv run python credit.py --part traj --seeds 0,1,2,3 --lambdas 1.0 \
--out results/credit_traj.json
```
`credit.py` adds no training loop. `_build`, `_train`, `_frozen`, `_metrics` and `probe` are
imported from `frozen.py` and `regime.py` and called unchanged. Two keywords were added to
`_train` — `aux`, which adds a scalar to the loss that goes into `pending`, and
`extra_params`, which puts the head in the optimiser — both defaulting to off, so
`test_train_copy_is_identical_to_regime_run` still pins the loop against `regime.run`.
`frozen._scores` was extended by one line to accept a callable estimator, which is what
lets the non-linear control use the published probe rather than a fork of it.
## 0. The pins, and how each was made able to fail
Four properties carry the numbers below. Each is asserted in code on every run, and each
assertion has a test that breaks it on purpose.
| check | how | result |
|---|---|---|
| the replay is the real training step | every window is replayed at the same parameters from the recorded observations, and the replayed `M` is `torch.equal` to the `M` the organism computed | **bit-identical, 400/400 windows on 16/16 seeds** |
| the replayed gradient is the one Adam used | a per-parameter hook reads the real backward and compares it against the replay's | **max relative difference exactly 0.0**, on all 6400 windows |
| detaching changed only the graph | the carried and detached window losses must be `torch.equal` | holds on every window |
| `lambda = 0` is the published baseline | `part_b(seed, 0.0)` against `frozen.run_one("grp_k0", seed)` | `steady`, `recovery`, probe accuracy and chance level all **bit-identical** |
`test_the_replay_pin_can_fail` perturbs the replay's starting `M` by 1e-3 and the pin
raises, as required. `test_the_readout_block_has_no_temporal_path` is the structural
control on the carried/detached split with a known answer: `out.weight` multiplies `M` at
the current step and nothing else, so its temporal term must be exactly zero — it is —
while the gate's, applied at every step of the window, must not be. If both had come out
zero the split would have been measuring nothing.
`test_coherence_is_one_for_a_constant_gradient_and_at_the_null_for_noise` pins the ratio at
both ends. Full suite: 78 passed (70 existing, 8 new); no existing test was modified.
## 1. Part A — is there a gradient signal at all, or is it cancelling?
Two failures look identical from "the weights did not move": the gradient reaching the gate
is ~0 (*absent*), or it is substantial per step and averages to nothing (*cancelling*). The
ratio of `‖mean gradient‖` to `mean ‖gradient‖` is what separates them, and it is the whole
of this part.
`gate` and `cand` are `grp.gate.weight` and `grp.cand.weight`; `feat` and `out` are
`rp.feat.weight` and `out.weight`, the reference blocks. Both gate and cand take `[h ‖ M]`,
so their column halves are reported separately — `[M]` is the only place a temporal path
can enter them. 16 seeds, 400 optimiser steps each.
### 1a. The ratio, against each block's own measured null
The coherence floor is not zero: averaging `n` directions that agree about nothing still
leaves `~1/sqrt(n)`, and how much it leaves depends on how unevenly that block's gradient
magnitude is spread over the run. 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; 40 draws.
`adam snr` is the same ratio taken per coordinate, `|mean_t g|/rms_t(g)`, which is what
Adam's `m/(sqrt(v)+eps)` actually consumes.
```
block coherence null excess paired se >null adam snr null excess se
------------------------------------------------------------------------------------------
gate 0.202 0.163 +0.039 0.009 14/16 0.066 0.042 +0.024 0.003
cand 0.173 0.108 +0.066 0.016 16/16 0.070 0.041 +0.030 0.004
feat 0.193 0.119 +0.075 0.007 16/16 0.082 0.041 +0.040 0.003
out 0.193 0.101 +0.091 0.022 15/16 0.079 0.040 +0.039 0.007
gate[h] 0.220 0.189 +0.031 0.007 15/16 0.063 0.042 +0.021 0.003
gate[M] 0.191 0.141 +0.050 0.012 14/16 0.069 0.042 +0.027 0.004
cand[h] 0.146 0.110 +0.036 0.008 14/16 0.062 0.041 +0.021 0.002
cand[M] 0.189 0.106 +0.083 0.020 15/16 0.078 0.040 +0.038 0.006
```
Per-seed coherence, `gate` then the three others:
```
block s0 s1 s2 s3 s4 s5 s6 s7 s8 s9 s10 s11 s12 s13 s14 s15
-----------------------------------------------------------------------------------------------------------------------------------------
gate 0.259 0.160 0.258 0.196 0.221 0.234 0.176 0.279 0.184 0.150 0.124 0.226 0.190 0.240 0.163 0.173
cand 0.210 0.134 0.206 0.179 0.102 0.295 0.251 0.210 0.154 0.123 0.085 0.133 0.115 0.167 0.095 0.316
feat 0.203 0.228 0.248 0.191 0.146 0.180 0.204 0.279 0.157 0.202 0.157 0.208 0.146 0.194 0.199 0.153
out 0.252 0.107 0.236 0.206 0.088 0.334 0.321 0.216 0.161 0.147 0.063 0.127 0.136 0.178 0.113 0.393
```
**The signal at the gate does not cancel.** Its coherence is 0.202 against its own measured
floor of 0.163, above that floor on 14 seeds of 16, with a paired standard error of 0.009 —
and 0.202 is the *highest* raw coherence of the four blocks. Read as an excess over its own
null it is the smallest, +0.039 against `out`'s +0.091 and `cand`'s +0.066, so the gate's
signal is somewhat less consistent than the rest of the network's; but it is a signal, on
the same order as the blocks that certainly train, not a quantity averaging to nothing.
Every block in this network is mostly-cancelling — coherence 0.15-0.26 against nulls of
0.10-0.19 — which is what 400 minibatch gradients look like, and the gate is not an
exception to it.
### 1b. And "negligible" is a thousandfold — which turns out not to matter
```
block n_par mean ‖g‖ per-par x gate x gate/par |dW|/|W|
----------------------------------------------------------------------
gate 2048 3.412e-06 7.539e-08 1.0 1.0 0.2682
cand 2048 3.026e-03 6.686e-05 886.9 886.9 0.1904
feat 96 3.670e-04 3.746e-05 107.6 496.8 0.0443
out 64 4.353e-03 5.441e-04 1275.8 7217.3 0.1529
gate[h] 1024 2.287e-06 7.148e-08 0.7 0.9 0.2408
gate[M] 1024 2.472e-06 7.724e-08 0.7 1.0 0.2921
cand[h] 1024 1.815e-03 5.672e-05 532.0 752.4 0.1792
cand[M] 1024 2.390e-03 7.468e-05 700.5 990.6 0.1996
```
`gate` and `cand` have identical shapes and read identical inputs, so their ratio is the
like-for-like one: **the gate's gradient is 887 times smaller than the candidate layer's
sitting beside it**, and 1276 times smaller than the readout's. The mechanism is in the
architecture — `∂L/∂(gate pre-activation) = (∂L/∂M) · (M − M̃) · g(1−g)`, and with `g`
pinned near 0.5 the update is a fixed 50/50 blend under which `M` and `M̃` stay close, so
the factor the gate's gradient carries is a difference that the gate's own inaction keeps
small.
**But a magnitude on its own says nothing here, and the last column is why.** Adam's step
is `lr · m/(sqrt(v)+eps)`, which is invariant to a uniform rescaling of the gradient: what
survives is consistency, not size. Measured per coordinate, the gate's signal-to-noise is
0.066 against `cand`'s 0.070 and `out`'s 0.079 — the same order. And the consequence is
visible in the weights: over 8000 steps **`gate.weight` moved 26.8% of its initial norm,
more than any other block measured**, against `cand`'s 19.0%, `out`'s 15.3% and `feat`'s
4.4%.
This retires the premise both of Part A's two failure modes were built to explain. It is
not true that the gate's weights did not move. They moved the furthest.
### 1c. What moved, and what did not
The gradient measurement says how much signal arrived; this says what arriving changed. The
gate's pre-activation `W_g[h‖M] + b_g − κa` is evaluated on the *same* inputs — the ones the
trained organism actually produces, the last 500 training steps — under the trained weights
and under the weights at initialisation. 16 seeds, 256 000 gate evaluations each.
```
quantity trained at init
------------------------------------------
pre-activation mean 0.0030 0.0038
pre-activation sd 0.1083 0.0811
g mean 0.5008 0.5009
g sd 0.0270 0.0203
rms change in pre 0.0787
corr(trained, init) 0.7001
```
The trained row reproduces `frozen.md` §3's `g = 0.500 ± 0.029` on 16 seeds. The point is
the column beside it. **After a 27% displacement of its weight matrix, the gate computes a
function whose output distribution is where it started**: `g` mean 0.5008 against 0.5009,
and an sd of 0.0270 against 0.0203. The pre-activations did change — they correlate at 0.70
across the displacement, with an rms change of 0.079 that is as large as the sd itself — but
they changed *within* a band of ±0.1 around zero, which is where the sigmoid is linear and
the update `M ← (1−g)M̃ + gM` is a fixed blend regardless.
The gate is not stuck because nothing pushed it. It is stuck because the pushing moved it
sideways: 8000 steps of a real, temporally-informed, Adam-rescaled gradient rearranged 2048
weights without once taking the pre-activation out of the neighbourhood of zero where the
gate does not gate.
### 1d. The temporal path
Paired inside a single run. At every optimiser step the same 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, asserted against the `M` the organism computed, and
the two window losses are `torch.equal`. The difference is the credit that flows through
time.
```
block ‖carried‖ ‖per-step‖ ‖temporal‖ temporal/per-step se temporal/carried
---------------------------------------------------------------------------------------
gate 3.412e-06 1.682e-06 2.033e-06 1.187 0.036 0.587
cand 3.026e-03 1.510e-03 1.753e-03 1.142 0.028 0.572
feat 3.670e-04 1.871e-04 2.116e-04 1.136 0.043 0.576
out 4.353e-03 4.353e-03 0.000e+00 0.000 0.000 0.000
gate[h] 2.287e-06 1.126e-06 1.362e-06 1.189 0.037 0.586
gate[M] 2.472e-06 1.221e-06 1.473e-06 1.184 0.036 0.587
cand[h] 1.815e-03 9.081e-04 1.053e-03 1.141 0.028 0.572
cand[M] 2.390e-03 1.191e-03 1.384e-03 1.142 0.028 0.572
```
Per-seed `temporal/per-step` for the gate:
```
s0 s1 s2 s3 s4 s5 s6 s7 s8 s9 s10 s11 s12 s13 s14 s15
1.395 1.204 1.162 1.252 1.009 1.226 1.268 1.521 1.284 1.153 1.122 1.095 1.103 0.994 0.973 1.227
```
**Hypothesis (a) predicted the temporal term would be negligible next to the per-step one.
It is 1.187 times larger, on 14 seeds of 16, with a paired standard error of 0.036.** Just
under three-fifths of the gradient the gate receives — 0.587 of it — arrives through the
carried state rather than from the current step. The `out.weight` row is the structural
control: it multiplies `M` at the current step and nothing else, and its temporal term is
exactly 0.000e+00 on every seed, so the split is not manufacturing a difference where there
is none.
The temporal path is also no less coherent than the per-step one: the gate's temporal
gradient has coherence 0.201 against a null of 0.171, essentially the whole block's 0.202
against 0.163. Credit through time arrives, and it arrives with the same directional
consistency as the rest.
### 1e. Part A's answer
**Neither absent nor cancelling.** The gradient reaching the gate is a thousandfold smaller
than its neighbours' in magnitude, but Adam does not care about magnitude; it is
directionally consistent above its own measured floor on 14/16 seeds, at a per-coordinate
signal-to-noise of 0.066 against `cand`'s 0.070 and `out`'s 0.079 — the lowest of the four
and measurably so, but the same order and not a different regime; a majority of it
comes through the truncated-BPTT window rather than from the current step; and it moved
`gate.weight` further than it moved any other block in the network. The training signal
that hypothesis (a) says is missing is there.
What is missing is any consequence. The displacement leaves the gate's output where it
began.
## 2. Part B — the ceiling: if the state were told, could it hold it?
A linear head from `M_i` to the current regime id, trained jointly with the task at a weight
`lambda`. Seven weights, 16 seeds each. At `lambda = 0` no head is built and the loop is
literally the one that produced Task 7b's baseline, pinned bit-identical.
`aux(train)` is the head's own accuracy over the second half of training, which is the
direct "can it" number: the head is linear on `M`, so its accuracy tracks the linear
separability of the regime in `M` — running rather than exact, since the head is chasing a
representation that is still moving, which is why the independent frozen-phase probe is
reported beside it and why §2a traces the curve rather than only its mean. `probe acc` is the independent least-squares probe on the
frozen phase, the number comparable with `frozen.md` Part B's 0.332 and `pooled.md`'s 0.312.
### 2a. Reading 1 — can it?
```
lambda aux(train) probe acc shuffle shift gap sd >chance M_type (perm)
------------------------------------------------------------------------------------------
0e+00 nan 0.312 0.270 0.268 +0.044 0.053 13/16 0.634 0.479
1e-05 0.251 0.311 0.270 0.268 +0.043 0.053 13/16 0.634 0.479
1e-04 0.251 0.311 0.270 0.268 +0.043 0.053 13/16 0.634 0.479
1e-03 0.252 0.314 0.270 0.269 +0.045 0.053 13/16 0.635 0.480
1e-02 0.250 0.306 0.273 0.266 +0.040 0.071 13/16 0.641 0.482
1e-01 0.253 0.301 0.275 0.268 +0.033 0.029 15/16 0.661 0.486
1e+00 0.259 0.307 0.271 0.264 +0.043 0.047 12/16 0.672 0.485
```
**The auxiliary head never leaves chance.** Against 1/4, it reads 0.250 to 0.259 at every
weight over five orders of magnitude — including `lambda = 1.0`, where the auxiliary term at chance
is 5.8x10^4 times the main loss and demonstrably dominates the run (§2b: the task degrades
5.9x). And the independent frozen-phase decode is flat: +0.044 above the
shift null at `lambda = 0`, +0.043 at `lambda = 1.0`.
The `M_type` column is the same probe on the entity's own type, a signal that is in `attrs`
and therefore certainly in reach. Note that both of `probe`'s time-based 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, and they report
the accuracy back as its own chance level — so the type's chance level is measured by
permuting the assignment across entities instead, which breaks the association and keeps the
marginal. That is the `(perm)` column.
**"Cannot" and "has not yet" are different claims**, so the head's accuracy was traced over
training rather than summarised. Four seeds, `lambda = 1.0`, bucketed by 1000 steps:
```
target chance seed @1k @2k @3k @4k @5k @6k @7k @8k
--------------------------------------------------------------------------------------
regime 0.250 0 0.268 0.284 0.210 0.420 0.270 0.197 0.200 0.224
regime 0.250 1 0.202 0.380 0.239 0.279 0.248 0.291 0.403 0.222
regime 0.250 2 0.337 0.169 0.346 0.300 0.140 0.342 0.220 0.244
regime 0.250 3 0.222 0.167 0.234 0.293 0.173 0.328 0.318 0.372
type 0.333 0 0.438 0.558 0.544 0.655 0.695 0.682 0.733 0.746
type 0.333 1 0.438 0.608 0.651 0.623 0.649 0.689 0.737 0.768
type 0.333 2 0.418 0.463 0.553 0.626 0.588 0.676 0.724 0.762
type 0.333 3 0.419 0.486 0.663 0.685 0.731 0.720 0.754 0.820
```
The regime curve wanders around chance on all four seeds with no trend across 8000 steps.
The type curve climbs monotonically on all four. This is not a budget problem.
### 2b. Reading 2 — does the task improve?
Main-task `steady`, paired per seed against `lambda = 0`. The log-ratio is positive when the
error fell.
```
lambda steady ratio l0/l won log-ratio paired se reading
-------------------------------------------------------------------------
0e+00 2.399e-05 -- -- -- -- --
1e-05 2.397e-05 1.001 9/16 +0.0008 0.0012 ambiguous
1e-04 2.396e-05 1.002 9/16 +0.0018 0.0015 lower err
1e-03 2.408e-05 0.997 4/16 -0.0028 0.0032 ambiguous
1e-02 2.956e-05 0.809 0/16 -0.2118 0.0443 higher err
1e-01 7.760e-05 0.341 0/16 -1.0759 0.1238 higher err
1e+00 1.416e-04 0.171 0/16 -1.7671 0.1040 higher err
```
Per-seed trained `steady`:
```
lambda s0 s1 s2 s3 s4 s5 s6 s7 s8 s9 s10 s11 s12 s13 s14 s15
------------------------------------------------------------------------------------------------------------------------------------------------------------------------
0e+00 2.39e-05 1.67e-05 2.11e-05 2.72e-05 1.68e-05 2.49e-05 3.53e-05 1.68e-05 2.10e-05 2.06e-05 6.20e-05 1.23e-05 2.51e-05 1.60e-05 2.73e-05 1.70e-05
1e-04 2.39e-05 1.67e-05 2.11e-05 2.71e-05 1.68e-05 2.49e-05 3.51e-05 1.68e-05 2.10e-05 2.01e-05 6.20e-05 1.23e-05 2.51e-05 1.60e-05 2.73e-05 1.70e-05
1e-02 2.42e-05 2.27e-05 2.62e-05 5.15e-05 1.99e-05 2.67e-05 3.89e-05 1.95e-05 3.37e-05 2.18e-05 6.28e-05 1.75e-05 2.88e-05 1.79e-05 4.02e-05 2.08e-05
1e-01 2.98e-04 5.67e-05 6.20e-05 6.59e-05 3.96e-05 6.05e-05 9.43e-05 5.19e-05 1.07e-04 4.76e-05 9.74e-05 3.66e-05 4.98e-05 2.58e-05 7.40e-05 7.48e-05
1e+00 1.61e-04 1.09e-04 1.22e-04 1.97e-04 1.05e-04 2.28e-04 3.13e-04 1.64e-04 1.36e-04 5.06e-05 1.36e-04 7.97e-05 1.40e-04 9.01e-05 1.16e-04 1.17e-04
```
Below `lambda = 1e-3` the auxiliary term is too small to change anything and the reading is
ambiguous or a fourth-decimal improvement — the `1e-4` row's `+0.0018 ± 0.0015` is a 0.2%
effect on 9/16 seeds and is not worth a sentence. Above it, the auxiliary term is large
enough to matter and the task gets monotonically worse, on 0 seeds of 16 at every weight
from `1e-2` up. That is what an auxiliary loss competing with the task does when it buys
nothing; the frozen phase agrees at every row.
This column is reported because the brief asked for it, not because it is informative on its
own. Reading 2 only means something conditional on reading 1, and reading 1 says the state
never held the regime at any weight, so there was never anything for the task to benefit
from.
### 2c. Reading 3 — the joint reading, and the control that carries it
Both columns are paired changes against `lambda = 0`, per seed. 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` §4 both identified and neither
attributed to memory. The question is whether being told the regime raises it.
**Regime target — the measurement:**
```
lambda gap d(gap) vs l=0 se won task log-ratio se won
------------------------------------------------------------------------------
0e+00 +0.044 -- -- -- -- -- --
1e-05 +0.043 -0.001 0.001 6/16 +0.0008 0.0012 9/16
1e-04 +0.043 -0.001 0.001 10/16 +0.0018 0.0015 9/16
1e-03 +0.045 +0.001 0.003 8/16 -0.0028 0.0032 4/16
1e-02 +0.040 -0.004 0.014 8/16 -0.2118 0.0443 0/16
1e-01 +0.033 -0.011 0.011 5/16 -1.0759 0.1238 0/16
1e+00 +0.043 -0.001 0.019 9/16 -1.7671 0.1040 0/16
```
**Type target — the positive control, run identically:**
```
lambda gap d(gap) vs l=0 se won task log-ratio se won
------------------------------------------------------------------------------
0e+00 +0.044 -- -- -- -- -- --
1e-05 +0.044 -0.000 0.000 5/16 +0.0001 0.0002 5/16
1e-04 +0.043 -0.001 0.001 4/16 -0.0025 0.0014 3/16
1e-03 +0.054 +0.010 0.008 9/16 -0.0892 0.0374 3/16
1e-02 +0.115 +0.071 0.027 11/16 -1.5275 0.1440 0/16
1e-01 +0.120 +0.076 0.024 12/16 -3.0582 0.1603 0/16
1e+00 +0.117 +0.073 0.022 14/16 -3.6922 0.2028 0/16
```
with the type itself, in `M`, going from 0.634 at `lambda = 0` to 0.789 at `lambda = 1.0`
against an entity-permutation chance of 0.48-0.51, and the head's own accuracy from 0.472 to
0.738 against 0.333.
**This is the pair the verdict rests on.** The same head, the same optimiser, the same
weights, the same 16 seeds, the same probe — the only difference is what the head is told to
put in `M`. Told the entity's type, it installs it, and it raises the *regime* decode as a
side effect by +0.073 ± 0.022 on 14 seeds of 16. Told the regime, it moves the regime
decode by −0.001 ± 0.019 on 9 of 16 — a change this measurement cannot tell apart from
zero. **The control that had no business moving the number is the only one that moved it.**
A null that survives that is not a broken instrument.
(Why type supervision lifts the regime decode is not established here and no claim is made
about it. The obvious guess is the one `frozen.md` §2's entity-centred variant was probing —
`M` is dominated by stable per-entity structure, and sharpening it changes the geometry the
regime probe fits in. It is a side effect of the control, not a result.)
### 2d. The linear head is not the binding constraint — MEASUREMENT INCOMPLETE
`when_memory_works.md` §2b is explicit that a linear decoder is the wrong instrument for
this target: on the raw observation window a linear decoder reads 0.23 at every history
length while an MLP on the same features reads 0.83, so a linear probe there "would have
said the regime is unidentifiable, and it would have been wrong by 0.7 in accuracy". A null
from a linear head on `M` inherits exactly that objection.
**This control was run and did not finish. No numbers from it are reported here.** Part B
was re-run with the auxiliary head replaced by a 2×128 ReLU network and the frozen-phase
decode taken by a second one, at `lambda ∈ {0, 0.01, 0.1, 1.0}` and the same 16 seeds; the
sweep reached 10 of 16 runs per shard before it was stopped. `.sdd/task-11-report.md`
records exactly what completed and the one command that finishes it.
What was observed in the incomplete run, recorded so it is not lost and **not relied on
below**: the MLP head's own training accuracy sat at 0.21-0.31 against a chance of 0.25 at
`lambda = 0.01` and `lambda = 0.1`, the same flat reading the linear head gave. Separately,
a single full-budget seed at `lambda = 0` decoded the regime from `M` at a gap of +0.159
above the shift null with the MLP probe where the linear probe read +0.064 on the same run,
and from the memoryless `h` at +0.234. **§3's verdict is stated on the linear head alone
and carries that limitation explicitly.**
## 3. Verdict
**Part A: the signal exists, reaches the gate, and flows through time.** Hypothesis (a) as
stated — that nothing in the training signal rewards carrying the regime forward — is not
supported. The gate's gradient is coherent above its own measured null on 14/16 seeds
(0.202 against 0.163, paired se 0.009), 59% of it arrives through the truncated-BPTT window
rather than from the current step, its per-coordinate signal-to-noise is 0.066 where the
blocks that certainly train read 0.070 to 0.082, and it moved `gate.weight` 27% of its norm — further than any
other block in the network. It is 887x smaller in magnitude than the identically-shaped
candidate layer's, which is worth knowing and is not the explanation, because Adam is scale
invariant. What the displacement did not do is change the gate's output: on the same inputs,
trained weights give `g = 0.5008 ± 0.0270` where the initial weights give `0.5009 ± 0.0203`.
**Part B gives the brief's third outcome: `M` cannot hold the regime even under direct
supervision.** The head never leaves chance at any weight over five orders of magnitude,
with no trend across 8000 steps; the frozen-phase decode moves by −0.001 ± 0.019; and the
same head at the same weights installs the entity's type into `M` and raises the regime
decode by +0.073 ± 0.022 in passing. The brief's reading of that outcome — "the state update
is not expressive enough; a different problem from credit assignment" — is what the numbers
give, and Part A independently rules out the credit-assignment alternative from the other
direction.
**The limitation this verdict carries.** It is stated on a linear head and a least-squares
probe. §2d's non-linear control was run and did not finish, so the possibility that `M`
holds the regime non-linearly and a linear head could not install it is *not* closed here.
Two things bear against it and neither settles it: the head's failure is not a readout
failure but a training-signal one — the same linear head installs the entity's type and
moves the regime decode while doing so — and the incomplete MLP-head run showed the same
flat chance reading at the two weights it reached. **A reader acting on this file should
treat outcome 3 as established for a linear readout of `M` and open for a non-linear one,
and should finish §2d before spending anything on the consequence.**
Neither part is good or bad news, and the second is the more useful of the two. A
credit-assignment failure would have been repairable by an auxiliary signal, a longer BPTT
window, or a different optimiser, and the natural next month would have been spent trying
them. The measurement says that month would have bought nothing: the state was told, at
weights that destroyed the task to make room, and it still did not hold the regime.
**One paragraph of argument, flagged as argument.** The following is not measured here;
it is offered because §4's second bullet turns on it and it should be visible enough to
be attacked. What the state update would have to do to hold this variable is legible in
`identify.py`. The regime is identifiable from one observed displacement,
but only through the statistics `⟨d, B^c⟩` and `⟨B^c, B^c'⟩` — inner products of the current
message basis with the *previous* step's, which are quadratic in a pair of consecutive
frames. `M ← (1−g)·tanh(W_c[h‖M]) + g·M` has one `tanh` between `h_t` and `M_{t−1}` and no
product of the two. With the gate pinned at 0.5 it is an exponential moving average of
`tanh` of a linear map, and an EMA of a nonlinearity is not where a cross-frame inner product
lives. If that is right it is a statement about this update rule and not about memory, and
the way to find out is to measure the ceiling on a rule that does carry such a product —
which §4 says how to do and does not do here.
## 4. What each outcome would have meant for keeping per-entity memory
This file is the last measurement on the memory line, so the consequence of each of the
brief's three outcomes is written out rather than left to be inferred. **The decision to
keep or drop the GRP is not made here.**
| outcome | what it would say about keeping per-entity memory |
|---|---|
| `M` holds the regime **and** the task improves | credit assignment is the blocker and the prize is measured. Keep the GRP; the work is to get the signal to it, and the size of the win is known in advance. |
| `M` holds the regime **and** the task does not improve | the regime is not useful to this architecture's prediction. That is an argument the GRP has no job on this domain *regardless of how credit reaches it*, and no amount of pushing from the unbuilt modules changes it. |
| **`M` cannot hold it even under direct supervision** — what the numbers give | the update rule cannot represent the variable. This says nothing about whether per-entity memory is worth keeping in general, and everything about `(1−g)·tanh(W_c[h‖M]) + g·M`. Giving the GRP more push from metabolism, reflexes or the policy readout would be pushing on a state that has been shown not to hold the thing they would be pushing it to hold. Replacing the update rule is a different move from dropping memory, and this file distinguishes them without choosing between them. |
## 5. What this does and does not bear on
**Measured, across four files.** `frozen.md`, `when_memory_works.md`, `pooled.md` and this
one measure claim A1 — that per-entity gated memory helps on a domain with an unannounced
hidden regime — and every mechanism they attach to it: the state's contribution over the
gated head (`frozen.md` §1a, §1d), affect on the gate (`a1.md`, `when_memory_works.md`
Part 1), the shape of the memory (`pooled.md`), the domain's suitability
(`when_memory_works.md` Parts 2-3), and now the training signal and the ceiling on the
state itself.
**Not measured, and untouched by any of it.** Claim A2 — the CPPN kernel taking `ψ` as
input — does not route through memory. Nothing in this file, `pooled.md`, `frozen.md` or
`when_memory_works.md` bears on it in either direction; the `grp_k_noctx` and
`grp_k_regimectx` conditions exist in `regime.py` and have not been run against it. A
decision to drop the GRP would not cost A2, and this file should not be read as evidence
for or against it. Spec §6's other organism modules — metabolism, reflexes S1/S2, the
instinct/EQ policy readout — are likewise unbuilt and unmeasured; §4's third row is a
statement about what pushing them into *this state update* could achieve, not an
evaluation of the modules.
## 6. Consequences
- **Do not build a mechanism to fix credit assignment on this domain.** An auxiliary
regime loss, a longer BPTT window, a gate-specific learning rate, or a gradient-boosting
reparameterisation of the gate are all motivated by (a), and (a) is measured dead here in
both directions: the credit arrives (§1) and being handed the answer changes nothing (§2).
The oracle did not pay, so the mechanism has no job — the same test `headroom.md` and
`when_memory_works.md` applied, reaching the same kind of answer.
- **The remaining question is about the update rule, and it is a design question rather
than a training one.** Nothing here says a per-entity state cannot hold this regime;
it says `(1−g)·tanh(W_c[h‖M]) + g·M` does not, and §3 gives the algebraic reason to
expect that. A state update carrying an explicit product of the current frame with the
previous one is the shape the domain asks for. **That is a hypothesis, and it comes with
the same obligation as every other in this repo: measure the ceiling before building it.**
The ceiling measurement is the one in §2 — supervise a candidate state to hold the regime
and decode it back out — and `credit.py --part aux` runs it against any update rule that
`ailed` exposes, with the type target already in place as its positive control.
- **`frozen.md` §3's "the gate is untrained" needs one word changed.** The gate's
pre-activation is at its initialisation, which is what that section measured and it is
correct. Its *weights* are not: they travel further than any other block's. "Untrained"
should read "trained without effect", and the distinction matters, because the first
invites a fix to the training and the second does not.
- **A magnitude is not a diagnosis under an adaptive optimiser.** The gate's 887-fold
gradient deficit is the kind of number that would have carried a claim, and it would have
been the wrong claim: the block with the smallest gradient in this network is the one that
moved the furthest. Any future gradient argument in this project needs the displacement
beside it.
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+138
View File
@@ -0,0 +1,138 @@
[
{
"seed": 0,
"lam": 1.0,
"bucket": 1000,
"head_kind": "linear",
"targets": {
"regime": {
"chance": 0.25,
"curve": [
0.268,
0.2836875,
0.210375,
0.4199375,
0.270375,
0.1966875,
0.199875,
0.224125
]
},
"type": {
"chance": 0.3333333333333333,
"curve": [
0.4378125,
0.5581875,
0.544375,
0.6551875,
0.6945625,
0.6823125,
0.7328125,
0.746
]
}
}
},
{
"seed": 1,
"lam": 1.0,
"bucket": 1000,
"head_kind": "linear",
"targets": {
"regime": {
"chance": 0.25,
"curve": [
0.2015,
0.379875,
0.239,
0.2786875,
0.2479375,
0.2911875,
0.403,
0.2215625
]
},
"type": {
"chance": 0.3333333333333333,
"curve": [
0.4375,
0.6081875,
0.6514375,
0.6228125,
0.6495,
0.68875,
0.73675,
0.7685
]
}
}
},
{
"seed": 2,
"lam": 1.0,
"bucket": 1000,
"head_kind": "linear",
"targets": {
"regime": {
"chance": 0.25,
"curve": [
0.336875,
0.1686875,
0.34575,
0.3,
0.139875,
0.3416875,
0.220125,
0.244125
]
},
"type": {
"chance": 0.3333333333333333,
"curve": [
0.417875,
0.4633125,
0.5529375,
0.6264375,
0.5883125,
0.675625,
0.7235,
0.7624375
]
}
}
},
{
"seed": 3,
"lam": 1.0,
"bucket": 1000,
"head_kind": "linear",
"targets": {
"regime": {
"chance": 0.25,
"curve": [
0.22225,
0.1665,
0.234375,
0.2925625,
0.1735,
0.3280625,
0.3179375,
0.37225
]
},
"type": {
"chance": 0.3333333333333333,
"curve": [
0.4186875,
0.4863125,
0.6628125,
0.6854375,
0.7305,
0.7199375,
0.7541875,
0.819875
]
}
}
}
]
+10
View File
@@ -0,0 +1,10 @@
lam=0 seed=0 steady=2.388e-05 aux=nan M_regime=0.351/0.286 M_type=0.631 g=0.494
lam=0 seed=1 steady=1.666e-05 aux=nan M_regime=0.256/0.239 M_type=0.487 g=0.504
lam=0 seed=2 steady=2.110e-05 aux=nan M_regime=0.289/0.247 M_type=0.547 g=0.496
lam=0 seed=3 steady=2.716e-05 aux=nan M_regime=0.426/0.309 M_type=0.536 g=0.498
lam=0.01 seed=0 steady=2.385e-05 aux=0.270 M_regime=0.344/0.276 M_type=0.625 g=0.495
lam=0.01 seed=1 steady=1.681e-05 aux=0.292 M_regime=0.254/0.240 M_type=0.497 g=0.503
lam=0.01 seed=2 steady=2.132e-05 aux=0.213 M_regime=0.285/0.247 M_type=0.546 g=0.497
lam=0.01 seed=3 steady=2.729e-05 aux=0.266 M_regime=0.419/0.307 M_type=0.540 g=0.495
lam=0.1 seed=0 steady=6.219e-05 aux=0.210 M_regime=0.342/0.284 M_type=0.627 g=0.498
lam=0.1 seed=1 steady=2.465e-05 aux=0.308 M_regime=0.258/0.240 M_type=0.536 g=0.498
+10
View File
@@ -0,0 +1,10 @@
lam=0 seed=12 steady=2.512e-05 aux=nan M_regime=0.325/0.272 M_type=0.703 g=0.496
lam=0 seed=13 steady=1.600e-05 aux=nan M_regime=0.298/0.250 M_type=0.466 g=0.503
lam=0 seed=14 steady=2.726e-05 aux=nan M_regime=0.229/0.249 M_type=0.604 g=0.493
lam=0 seed=15 steady=1.704e-05 aux=nan M_regime=0.325/0.257 M_type=0.713 g=0.505
lam=0.01 seed=12 steady=2.504e-05 aux=0.233 M_regime=0.330/0.272 M_type=0.706 g=0.496
lam=0.01 seed=13 steady=1.586e-05 aux=0.259 M_regime=0.295/0.250 M_type=0.468 g=0.501
lam=0.01 seed=14 steady=2.853e-05 aux=0.257 M_regime=0.229/0.250 M_type=0.608 g=0.493
lam=0.01 seed=15 steady=1.863e-05 aux=0.233 M_regime=0.336/0.258 M_type=0.710 g=0.505
lam=0.1 seed=12 steady=3.474e-05 aux=0.232 M_regime=0.334/0.272 M_type=0.698 g=0.500
lam=0.1 seed=13 steady=1.907e-05 aux=0.254 M_regime=0.316/0.258 M_type=0.484 g=0.506
+10
View File
@@ -0,0 +1,10 @@
lam=0 seed=4 steady=1.683e-05 aux=nan M_regime=0.333/0.286 M_type=0.723 g=0.505
lam=0 seed=5 steady=2.491e-05 aux=nan M_regime=0.262/0.309 M_type=0.688 g=0.492
lam=0 seed=6 steady=3.528e-05 aux=nan M_regime=0.370/0.270 M_type=0.666 g=0.506
lam=0 seed=7 steady=1.680e-05 aux=nan M_regime=0.369/0.241 M_type=0.594 g=0.506
lam=0.01 seed=4 steady=1.745e-05 aux=0.274 M_regime=0.341/0.283 M_type=0.722 g=0.504
lam=0.01 seed=5 steady=2.534e-05 aux=0.195 M_regime=0.275/0.309 M_type=0.690 g=0.491
lam=0.01 seed=6 steady=3.762e-05 aux=0.237 M_regime=0.327/0.266 M_type=0.699 g=0.503
lam=0.01 seed=7 steady=1.678e-05 aux=0.289 M_regime=0.370/0.245 M_type=0.586 g=0.506
lam=0.1 seed=4 steady=2.809e-05 aux=0.245 M_regime=0.321/0.292 M_type=0.723 g=0.490
lam=0.1 seed=5 steady=3.386e-05 aux=0.202 M_regime=0.257/0.303 M_type=0.692 g=0.482
+10
View File
@@ -0,0 +1,10 @@
lam=0 seed=8 steady=2.099e-05 aux=nan M_regime=0.250/0.236 M_type=0.652 g=0.503
lam=0 seed=9 steady=2.061e-05 aux=nan M_regime=0.325/0.283 M_type=0.650 g=0.503
lam=0 seed=10 steady=6.197e-05 aux=nan M_regime=0.244/0.302 M_type=0.705 g=0.506
lam=0 seed=11 steady=1.230e-05 aux=nan M_regime=0.345/0.257 M_type=0.781 g=0.503
lam=0.01 seed=8 steady=2.142e-05 aux=0.252 M_regime=0.256/0.239 M_type=0.644 g=0.503
lam=0.01 seed=9 steady=2.121e-05 aux=0.298 M_regime=0.303/0.277 M_type=0.650 g=0.502
lam=0.01 seed=10 steady=6.103e-05 aux=0.254 M_regime=0.243/0.303 M_type=0.717 g=0.506
lam=0.01 seed=11 steady=1.241e-05 aux=0.212 M_regime=0.345/0.258 M_type=0.785 g=0.503
lam=0.1 seed=8 steady=3.096e-05 aux=0.184 M_regime=0.258/0.254 M_type=0.665 g=0.503
lam=0.1 seed=9 steady=2.303e-05 aux=0.298 M_regime=0.287/0.274 M_type=0.662 g=0.499
+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