Compare commits

...
6 Commits
Author SHA1 Message Date
chrnx 5ecf5d1146 results: apply Task 11's two corrections
The gate's weights moved 26.8% of their initial norm — more than any other block — so
"untrained" was wrong and pointed at a hypothesis Task 11 falsified. What did not move is
the function: the displacement stayed inside the sigmoid's linear band. frozen.md's three
affected passages now say so and a new section 6 carries the measurement, including why the
887x gradient-magnitude gap should not be led with (Adam is scale-invariant; the
per-coordinate SNR is comparable across blocks).

Section 7 and a note in when_memory_works.md mark the probe figures as linear-probe numbers.
An MLP probe reads +0.159 from M and +0.234 from h. The relative claim is unchanged; the
absolute fraction needed the qualifier.
2026-09-02 17:05:26 -05:00
chrnx 247d4d5280 exp: chess history probe, not yet run
Does a piece own past predict its next square beyond the current board? The same question
  identify.py asked of particles, asked of chess, and answered without building the organism.
  Split by game rather than by position, and a shuffled-history control for the gain to beat.
  
  Written against the local Lichess PGN. Not executed yet.
2026-09-02 17:00:26 -05:00
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
chrnx 0d682db353 docs: two rules earned by Task 10
Eight seeds reported the wrong sign here and flipped only at sixteen. And a null needs a
positive control, or it cannot be told apart from an instrument that sees nothing.
2026-09-02 14:41:58 -05:00
chrnx 63f8050bb7 exp: pooling the 16 states buys nothing memory-specific -- (b) is dead
The regime decodes from a single M at 0.332 and the question was whether it is
distributed across the 16 per-entity states rather than absent from them. Mean-pooling
lifts M's gap above the measured shift null by +0.045 -- and lifts the memoryless h it
is built from by +0.048, on more seeds. Difference -0.003, paired se 0.015, M ahead on
8/16. Concatenating all 16 adds nothing over the mean once it has samples to fit.

The instrument is not blind: a synthetic representation whose regime code is genuinely
split across entities gains +0.589 through the same probe, thirteen times the effect
measured here, and test_the_power_check_can_fail breaks the pooling on purpose and
confirms that control fails.

Eight seeds would have reported +0.010 in M's favour on 5/8. Sixteen report -0.003 on
8/16, which is the spread this project keeps being warned about.

No training loop and no architecture added: _build, _train, _frozen and probe come from
frozen.py unchanged, and seeds 0-7 reproduce results/frozen.json bit-identically.
2026-09-02 14:38:56 -05:00
chrnx 9710d4e84c docs: the gain is knowledge, not performance
Optimising the GRP is a grave error, not a goal. Adds the operational test before running
anything: is the negative result as informative as the positive one?
2026-09-02 14:28:28 -05:00
19 changed files with 35120 additions and 14 deletions

No files matched your search

+14 -3
View File
@@ -19,6 +19,12 @@ directory.
## The rules that matter
- **The gain is knowledge, not performance.** These experiments exist to establish what is
missing, not to make a mechanism work. Optimising the GRP is a grave error, not a goal.
Before running anything, apply the test: **is the negative result as informative as the
positive one?** If the experiment only makes sense when it comes out positive, it is a
performance experiment wearing a diagnostic costume — redesign it. Write verdicts so both
branches carry equal weight, and describe no outcome as good or bad news.
- **Report a null plainly.** Every substantive result in this repo so far is a null, and each
one turned out more informative than the positive it replaced. Do not soften a negative, do
not hunt for a configuration that rescues it, and do not defer it by proposing a new domain.
@@ -40,9 +46,14 @@ directory.
trajectory, regime schedule, switch times and noise draws stay byte-identical to the
non-oracle run at the same seed, or a measured difference could come from a different world
rather than from the extra information.
- **Seeds.** Across-seed spread here is comparable to the effects being claimed. Eight seeds
supports a direction; it does not support a ratio. Report per-seed values and the count of
seeds won, not only the ratio of means.
- **Seeds.** Across-seed spread here is comparable to the effects being claimed, and worse:
in Task 10 eight seeds reported the **wrong sign**, flipping only at sixteen. Report
per-seed values, the count of seeds won, and a paired standard error. If the effect sits
inside one se of zero, say it is ambiguous rather than reading its sign.
- **A null needs a positive control.** Task 10's null means something only because the same
probe, on a synthetic where the signal genuinely was distributed, recovered it at thirteen
times the measured effect. Without that, "we found nothing" is indistinguishable from "our
instrument cannot see anything".
- **Anything a results file quotes must be re-runnable from this repo.** An uncommitted
throwaway driver is not reproducible. `ceilings.py` exists because of this rule; there is a
standing debt where `frozen.md` §1d's width-matched rows still are not.
+171
View File
@@ -0,0 +1,171 @@
"""Does a piece's own past predict its next move, beyond the current board?
The same question `identify.py` asked of the particles domain, asked of chess. Nothing here
builds or trains the organism — this measures a property of the domain.
In particles the answer was that the past held the hidden variable almost perfectly (one
observed displacement identified the regime at 0.958) while the present held much less. The
per-entity version of that question is different and is the one chess is supposed to answer
differently: does *this piece's own history* say something about where it goes next that the
current board does not?
Two predictors of the same target, given the same conditioning:
A (present) board occupancy, the moving piece's type and colour, its current square
B (+history) the same, plus the squares that piece occupied on its previous moves
The gap B - A is the per-entity history's contribution. If it is ~0, chess is like particles
for this purpose and a per-entity memory has nothing to carry.
"""
from __future__ import annotations
import argparse
import random
from collections import defaultdict
import chess
import chess.pgn
import numpy as np
PGN = "/Users/chrnx/workspace/ailed/model/data/slice.pgn"
def piece_histories(game: chess.pgn.Game, hist: int):
"""Yield (piece_key, from_sq, to_sq, prev_squares, board) per move, tracking identity.
Identity is the point: `id_at[square]` follows a piece across its moves so that "this
knight" means the same knight ten moves later. Castling moves the rook too; en passant
removes a pawn from a square the mover never touches; promotion keeps the identity and
changes the type.
"""
board = game.board()
id_at: dict[int, int] = {sq: sq for sq in chess.SQUARES if board.piece_at(sq)}
past: dict[int, list[int]] = defaultdict(list)
nxt = 64
for move in game.mainline_moves():
piece = board.piece_at(move.from_square)
if piece is None:
return
key = id_at.get(move.from_square)
if key is None:
key = nxt; nxt += 1
prev = past[key][-hist:]
yield key, move.from_square, move.to_square, prev, board.copy(stack=False), piece
# advance identity bookkeeping alongside the board
if board.is_en_passant(move):
cap = move.to_square + (-8 if piece.color == chess.WHITE else 8)
id_at.pop(cap, None)
id_at.pop(move.to_square, None) # a normal capture
id_at[move.to_square] = id_at.pop(move.from_square, key)
if board.is_castling(move):
back = 0 if piece.color == chess.WHITE else 56
r_from, r_to = ((back + 7, back + 5) if chess.square_file(move.to_square) == 6
else (back, back + 3))
if r_from in id_at:
id_at[r_to] = id_at.pop(r_from)
past[key].append(move.from_square)
board.push(move)
def features(from_sq, prev, board, piece, hist: int, with_history: bool):
"""Present-only features, then optionally the piece's own past squares."""
f = np.zeros(64 + 6 + 1 + 64 + (64 * hist if with_history else 0), dtype=np.float32)
f[from_sq] = 1.0 # where it is now
f[64 + piece.piece_type - 1] = 1.0 # what it is
f[70] = 1.0 if piece.color == chess.WHITE else 0.0
occ = board.occupied
for sq in chess.SQUARES: # what the board looks like
if occ >> sq & 1:
f[71 + sq] = 1.0
if with_history:
base = 135
for i in range(hist): # where it has been
if i < len(prev):
f[base + i * 64 + prev[-1 - i]] = 1.0
return f
def collect(n_games: int, hist: int, min_moves: int, seed: int):
rng = random.Random(seed)
A, B, y, gid = [], [], [], []
with open(PGN, encoding="utf-8", errors="replace") as fh:
for g in range(n_games):
game = chess.pgn.read_game(fh)
if game is None:
break
for key, frm, to, prev, board, piece in piece_histories(game, hist):
if len(prev) < min_moves: # only pieces with a history to speak of
continue
A.append(features(frm, prev, board, piece, hist, False))
B.append(features(frm, prev, board, piece, hist, True))
y.append(to)
gid.append(g)
return np.array(A), np.array(B), np.array(y), np.array(gid)
def fit_eval(Xtr, ytr, Xte, yte, l2: float = 1.0):
"""Ridge onto one-hot targets, argmax at test. One estimator for both arms, so the
difference between them is about the features and not about the fit."""
K = 64
Y = np.zeros((len(ytr), K), dtype=np.float32)
Y[np.arange(len(ytr)), ytr] = 1.0
d = Xtr.shape[1]
W = np.linalg.solve(Xtr.T @ Xtr + l2 * np.eye(d, dtype=np.float32), Xtr.T @ Y)
return float((np.argmax(Xte @ W, axis=1) == yte).mean())
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--games", type=int, default=3000)
ap.add_argument("--hist", type=int, default=3, help="how many past squares B may see")
ap.add_argument("--min-moves", type=int, default=2, help="skip a piece's first moves")
ap.add_argument("--seeds", default="0,1,2,3,4,5,6,7,8,9,10,11")
a = ap.parse_args()
A, B, y, gid = collect(a.games, a.hist, a.min_moves, 0)
print(f"{len(y)} moves from {gid.max() + 1} games, {A.shape[1]} present features, "
f"{B.shape[1]} with history\n")
gains = []
print(f"{'seed':>5}{'present':>10}{'+history':>10}{'gain':>9}{'shuffled':>10}")
print("-" * 44)
for s in (int(x) for x in a.seeds.split(",")):
# split by GAME, never by position: two positions from one game share almost
# everything, and splitting inside a game leaks the answer across the split.
games = np.unique(gid)
rng = np.random.default_rng(s)
rng.shuffle(games)
te = np.isin(gid, games[: max(1, len(games) // 4)])
tr = ~te
acc_a = fit_eval(A[tr], y[tr], A[te], y[te])
acc_b = fit_eval(B[tr], y[tr], B[te], y[te])
# chance for the history arm: same features, history block shuffled across rows,
# so its marginal is intact and only its alignment with the target is broken
Bs = B.copy()
idx = rng.permutation(len(Bs))
Bs[:, 135:] = Bs[idx, 135:]
acc_s = fit_eval(Bs[tr], y[tr], Bs[te], y[te])
gains.append((acc_a, acc_b, acc_b - acc_a, acc_s))
print(f"{s:>5}{acc_a:>10.4f}{acc_b:>10.4f}{acc_b - acc_a:>+9.4f}{acc_s:>10.4f}")
g = np.array(gains)
se = g[:, 2].std(ddof=1) / np.sqrt(len(g))
print("-" * 44)
print(f"{'mean':>5}{g[:, 0].mean():>10.4f}{g[:, 1].mean():>10.4f}"
f"{g[:, 2].mean():>+9.4f}{g[:, 3].mean():>10.4f}")
print(f"\nhistory gain {g[:, 2].mean():+.4f} +/- {se:.4f} (paired se), "
f"{(g[:, 2] > 0).sum()}/{len(g)} seeds positive")
print(f"shuffled-history control gains {g[:, 3].mean() - g[:, 0].mean():+.4f} over present, "
f"which is what the real gain must beat to mean anything")
if abs(g[:, 2].mean()) < se:
print("\nVERDICT: inside one se of zero — ambiguous, not a direction.")
elif g[:, 2].mean() > 0:
print("\nVERDICT: a piece's own past predicts its next square beyond the board.")
else:
print("\nVERDICT: the piece's own past adds nothing over the board.")
if __name__ == "__main__":
main()
+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,
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).
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
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
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.
`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
`AffectConfig()`, the value this loop always used, so the copy stays verbatim for
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
affect = Affect()
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)
pred, memory = org(obs.attrs, r, obs.ids, axes, held, context=ctx)
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)
losses.append(loss.item()); switched.append(obs.switched); arousals.append(affect.arousal)
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)
def _scores(reps: np.ndarray, W: np.ndarray, mu: np.ndarray, sd: np.ndarray) -> np.ndarray:
return (_design(reps, mu, sd) @ W).reshape(reps.shape[0], reps.shape[1], -1)
def _scores(reps: np.ndarray, W, mu: np.ndarray, sd: np.ndarray) -> np.ndarray:
"""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]:
+257
View File
@@ -0,0 +1,257 @@
"""Task 10: is the regime information distributed across the 16 per-entity states?
`results/frozen.md` Part B decoded the world's regime id from a *single* entity's `M`
at 0.332, from the memoryless RP's `h` at 0.342, and from the `h` inside the same GRP
at 0.338 -- all against a measured chance near 0.273. Two explanations were left open:
(b) shape mismatch -- the regime is one global 3x3 matrix `K`, the state is per-entity,
so the information could be *distributed across* the 16 states while being absent
from any one of them;
(a) credit assignment -- nothing in the loss rewards carrying the regime forward, so
the state never learns to hold it at all.
This file decodes from three views of the same frozen representation: one entity, the
mean over the 16, and all 16 concatenated. Pooling is applied to `M` *and* to `h`.
**The `h` control is the whole measurement.** Pooling 16 samples of anything averages
away per-entity noise, and that alone lifts a probe. `h` is the feedforward layer `M`
is built from and carries no memory, so whatever pooling buys on `h` is the value of
pooling as such. (b) is live only if pooled `M` gains what pooled `h` does not.
Nothing here is an architecture change: `_build`, `_train`, `_frozen` and `probe` are
imported from `frozen.py` unmodified, so the organism, the world and the estimator are
the ones that produced the 0.332 baseline. `power_check` is the positive control -- a
synthetic representation whose regime code is genuinely distributed, confirming this
pipeline detects (b) when (b) is true.
"""
from __future__ import annotations
import argparse
import json
import statistics
from pathlib import Path
import numpy as np
from frozen import FROZEN_STEPS, SPLIT, TRAIN_STEPS, _build, _frozen, _train, probe
VIEWS = ("single", "mean", "concat")
REPS = ("M", "h")
def views(rep: np.ndarray) -> dict[str, np.ndarray]:
"""(T, N, D) -> the three pooling views, each shaped (T, samples_per_step, features).
`single` is the published baseline: one sample per entity per step, D features.
`mean` is one sample per step of the entity-averaged state, D features.
`concat` is one sample per step of every entity's state, N*D features -- the
strongest form of pooling, and the one whose feature count inflates a fitted
probe's chance level, which is why the shift null is not optional.
Entity order is stable: `ParticleWorld.ids` is `list(range(n))` on every step, so
column block `i` of `concat` is always particle `i`.
"""
T, N, D = rep.shape
return {"single": rep,
"mean": rep.mean(axis=1, keepdims=True),
"concat": rep.reshape(T, 1, N * D)}
# -- one seed --------------------------------------------------------------------
def run_one(seed: int, train_steps: int = TRAIN_STEPS, frozen_steps: int = FROZEN_STEPS,
bptt: int = 20, lr: float = 1e-3, hidden: int = 32, omega: float = 10.0,
split: float = SPLIT, n_null: int = 20, estimators: tuple[str, ...] = ("lsq",)) -> dict:
"""Train `grp_k0` as `regime.run` does, freeze, then probe every view.
The training and frozen phases are `frozen.py`'s, called unchanged, so this seed's
`M_single` row is the same number `results/frozen.md` Part B reports.
"""
spec, wcfg, world, org = _build("grp_k0", seed, hidden, omega, kappa=4.0)
affect, memory, _ = _train(spec, wcfg, world, org, train_steps, bptt, lr)
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"])
got: dict[str, dict] = {}
for tag in REPS:
for view, r in views(fr[tag]).items():
for est in estimators:
p = probe(r, labels, fr["switched"], wcfg.n_regimes, split=split,
n_null=n_null if est == "lsq" else 5, seed=seed, estimator=est)
p["n_features"] = int(r.shape[-1])
p["n_train_samples"] = int(int(r.shape[0] * split) * r.shape[1])
got[f"{tag}_{view}_{est}"] = p
return dict(condition="grp_k0", seed=seed, train_steps=train_steps,
frozen_steps=frozen_steps, split=split, n_regimes=wcfg.n_regimes,
n_entities=wcfg.n, hidden=hidden, probes=got)
# -- the positive control --------------------------------------------------------
def power_check(labels: np.ndarray, switched: list[bool], n_regimes: int = 4,
n: int = 16, d: int = 32, seed: int = 0, split: float = SPLIT) -> dict:
"""Can this pipeline see a distributed code at all? Two synthetic representations.
`distributed`: the regime is 2 bits. Entities 0-7 write bit 0 into channel 0 and
entities 8-15 write bit 1 into channel 1; every other channel is noise. **No single
entity carries more than one bit**, so a per-entity probe caps near 0.5 however good
it is, while the mean and the concatenation carry both and can reach 1.0. This is
hypothesis (b) made true by construction -- if the measurement cannot find it here,
a null on the real data would mean nothing.
`redundant`: every entity carries the *whole* regime code plus independent noise.
Nothing is distributed; pooling only averages the noise away. This is the confound
the `h` control exists to catch, reproduced deliberately so its signature -- a lift
on any representation, memory or not -- can be compared with the real rows.
"""
rng = np.random.default_rng(seed)
T = len(labels)
bit0 = (labels % 2).astype(float) * 2 - 1
bit1 = (labels // 2).astype(float) * 2 - 1
dist = rng.normal(size=(T, n, d))
half = n // 2
dist[:, :half, 0] += 4.0 * bit0[:, None]
dist[:, half:, 1] += 4.0 * bit1[:, None]
code = rng.normal(size=(n_regimes, d))
red = code[labels][:, None, :] + 4.0 * rng.normal(size=(T, n, d))
out = {}
for tag, rep in (("distributed", dist), ("redundant", red)):
for view, r in views(rep).items():
out[f"{tag}_{view}"] = probe(r, labels, switched, n_regimes, split=split,
n_null=10, seed=seed)
return out
# -- reporting -------------------------------------------------------------------
def _col(results: list[dict], key: str, field: str) -> list[float]:
return [r["probes"][key][field] for r in results]
def table(results: list[dict], est: str = "lsq") -> str:
"""acc, both measured chance levels, and the gap, per view."""
lines = [f"{'representation':<16}{'feat':>6}{'n_tr':>8}{'acc':>8}{'shuffle':>9}"
f"{'shift':>8}{'gap':>8}{'sd(gap)':>9}{'>chance':>9}",
"-" * 81]
for tag in REPS:
for view in VIEWS:
k = f"{tag}_{view}_{est}"
acc = _col(results, k, "acc_entity")
sh = _col(results, k, "chance_shuffle")
sf = _col(results, k, "chance_shift")
gap = [a - c for a, c in zip(acc, sf)]
p0 = results[0]["probes"][k]
lines.append(
f"{tag + ', ' + view:<16}{p0['n_features']:>6}{p0['n_train_samples']:>8}"
f"{statistics.fmean(acc):>8.3f}{statistics.fmean(sh):>9.3f}"
f"{statistics.fmean(sf):>8.3f}{statistics.fmean(gap):>+8.3f}"
f"{statistics.stdev(gap) if len(gap) > 1 else 0.0:>9.3f}"
f"{sum(g > 0 for g in gap):>6}/{len(gap):<3}")
return "\n".join(lines)
def gains(results: list[dict], est: str = "lsq") -> str:
"""The measurement: pooling's gain on `M` beside pooling's gain on `h`.
Gain is measured on the gap above the *shift* null, per seed, because the three
views do not share a chance level -- concatenation multiplies the feature count by
16 and lifts what a fitted probe scores on shuffled labels.
"""
def gap(k: str) -> list[float]:
return [a - c for a, c in zip(_col(results, k, "acc_entity"),
_col(results, k, "chance_shift"))]
lines = [f"{'pooling':<10}{'M gain':>9}{'h gain':>9}{'M-h':>9}{'M wins':>9}"
f"{'h wins':>9}{'M>h':>7}", "-" * 62]
for view in ("mean", "concat"):
gm = [p - s for p, s in zip(gap(f"M_{view}_{est}"), gap(f"M_single_{est}"))]
gh = [p - s for p, s in zip(gap(f"h_{view}_{est}"), gap(f"h_single_{est}"))]
d = [a - b for a, b in zip(gm, gh)]
n = len(gm)
lines.append(f"{view:<10}{statistics.fmean(gm):>+9.3f}{statistics.fmean(gh):>+9.3f}"
f"{statistics.fmean(d):>+9.3f}{sum(g > 0 for g in gm):>6}/{n:<3}"
f"{sum(g > 0 for g in gh):>6}/{n:<3}{sum(x > 0 for x in d):>4}/{n}")
return "\n".join(lines)
def per_seed(results: list[dict], est: str = "lsq") -> str:
seeds = [r["seed"] for r in results]
lines = [f"{'representation':<16}" + "".join(f"{'s' + str(s):>8}" for s in seeds),
"-" * (16 + 8 * len(seeds))]
for tag in REPS:
for view in VIEWS:
k = f"{tag}_{view}_{est}"
row = [a - c for a, c in zip(_col(results, k, "acc_entity"),
_col(results, k, "chance_shift"))]
lines.append(f"{tag + ', ' + view:<16}" + "".join(f"{v:>+8.3f}" for v in row))
return "\n".join(lines)
def vote_table(results: list[dict], est: str = "lsq") -> str:
"""The single-entity probe's per-step vote: 16 decisions aggregated, not 16 states.
Separates pooling the *representation* from aggregating 16 independent decoders,
which is the other way a per-step number can rise without any state holding more.
"""
lines = [f"{'representation':<16}{'per-entity':>12}{'16-vote':>10}{'mean-pooled':>13}", "-" * 51]
for tag in REPS:
e = statistics.fmean(_col(results, f"{tag}_single_{est}", "acc_entity"))
v = statistics.fmean(_col(results, f"{tag}_single_{est}", "acc_step"))
m = statistics.fmean(_col(results, f"{tag}_mean_{est}", "acc_entity"))
lines.append(f"{tag:<16}{e:>12.3f}{v:>10.3f}{m:>13.3f}")
return "\n".join(lines)
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--seeds", default="0,1,2,3,4,5,6,7")
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("--estimators", default="lsq")
ap.add_argument("--power-check", action="store_true",
help="also run the synthetic distributed/redundant controls")
ap.add_argument("--out", default="results/pooled.json")
a = ap.parse_args()
ests = tuple(a.estimators.split(","))
results = []
for seed in (int(s) for s in a.seeds.split(",")):
r = run_one(seed, a.train_steps, a.frozen_steps, lr=a.lr, estimators=ests)
p = r["probes"]
print(f"seed={seed} " + " ".join(
f"{t}_{v}={p[f'{t}_{v}_lsq']['acc_entity']:.3f}"
f"/{p[f'{t}_{v}_lsq']['chance_shift']:.3f}"
for t in REPS for v in VIEWS), flush=True)
results.append(r)
payload: dict = dict(results=results)
if a.power_check:
spec, wcfg, world, org = _build("grp_k0", 0, 32, 10.0, kappa=4.0)
affect, memory, _ = _train(spec, wcfg, world, org, 200, 20, a.lr)
fr = _frozen(spec, wcfg, world, org, affect, memory, a.frozen_steps)
pc = power_check(np.asarray(fr["regimes"]), fr["switched"], wcfg.n_regimes)
payload["power_check"] = pc
print("\npositive control (synthetic):")
for k, v in pc.items():
print(f" {k:<24} acc={v['acc_entity']:.3f} shift={v['chance_shift']:.3f}")
Path(a.out).parent.mkdir(parents=True, exist_ok=True)
Path(a.out).write_text(json.dumps(payload, indent=1, default=float))
for est in ests:
print(f"\n=== {est} ===")
print(table(results, est))
print("\npooling gain on the gap above the shift null:")
print(gains(results, est))
print("\nper-seed gap above the shift null:")
print(per_seed(results, est))
print("\nrepresentation pooling vs decision voting:")
print(vote_table(results, est))
if __name__ == "__main__":
main()
+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
]
}
}
}
]
+55 -5
View File
@@ -23,8 +23,9 @@ builds an internal regime variable.**
less — and the same +0.05 appears in a state-free network, so it is a read-off of
the current configuration, not a memory.
3. The mechanism is visible: the gate sits at `g = 0.500 ± 0.029`, never above 0.9,
never below 0.1, on any seed. It is at its initialisation. The GRP as trained here
is not gating anything.
never below 0.1, on any seed. Its *function* is at its initialisation — the weights
themselves moved more than any other block's, see the correction in §6 — and the GRP
as trained here is not gating anything.
Environment: `experiments/`, `ailed/` unmodified, no default in `particles.py` or
`regime.py` changed. 8 seeds (0-7), 8000 training steps then 4000 frozen steps,
@@ -329,8 +330,10 @@ grp_k0_nostate 0.509 0.025 0.000 0.000
```
`g = σ(W_g[h‖M] − κa)` with `κ = 0`. A mean of 0.500 with sd 0.029 and no saturation
in either direction, on every seed, means the gate's pre-activation is sitting at zero:
it is at its initialisation and 8000 training steps have not moved it. The update
in either direction, on every seed, means the gate's pre-activation is sitting at zero.
**The weights that produce it did move** — Task 11 measured a displacement of 26.8% of
their initial norm, larger than any other block's; what stayed put is the function, because
the displacement remained inside the band where the sigmoid is linear. See §6. The update
`M ← (1−g)M̃ + gM` degenerates to a fixed 50/50 blend — a two-step exponential moving
average of `tanh(W_c[h‖M])`, with no input dependence. **Nothing is being decided about
what to keep.**
@@ -371,7 +374,8 @@ What the frozen probe does establish, and it is worth having:
- **The margin is not memory.** It is 4160 extra feedforward parameters. Ablating the
state while keeping them preserves the entire effect (1.06x, 4/8 seeds) and leaves
the recovery curve unchanged at every lag.
- **The GRP's gate is untrained.** It sits at 0.5 with no input dependence, which is a
- **The GRP's gate does not gate.** It is *not* untrained — that reading is corrected in
§6. It sits at 0.5 with no input dependence, which is a
sufficient mechanistic explanation for both nulls and is a fact about this setup, not
about the architecture.
@@ -399,3 +403,49 @@ is the same conclusion §6(c) of `headroom.md` reached from the other direction.
- **`recovery[k]` is not an adaptation measurement in this domain.** It tracks the
world's post-switch transient, and a stateless frozen model reproduces its shape. Any
A1 claim phrased on recovery curves needs a different observable.
---
## 6. Correction (Task 11): the gate's weights moved; its function did not
This file originally read `g = 0.500 ± 0.029` as meaning the gate was *untrained*.
`results/credit.md` measured the weights directly and that reading is wrong.
- `grp.gate.weight` moved **26.8% of its initial norm** over training — **more than any
other block** (`cand` 19.0%, `out` 15.3%, `feat` 4.4%). The gate is among the
most-updated parameters in the model, not the least.
- What did not move is the **function**. On identical inputs the trained weights give
`g = 0.5008 ± 0.0270` and the weights at initialisation give `g = 0.5009 ± 0.0203`. The
displacement stayed inside the ±0.1 pre-activation band where the sigmoid is linear, so a
large change in the weights produces no change in behaviour.
- The gradient is **coherent, not cancelling**: 0.202 against its own measured sign-flip
null of 0.163, above null on 14/16 seeds. And **0.587 of it arrives through the
truncated-BPTT window**, making the temporal path 1.187x the per-step one.
Two things follow for anyone quoting this file.
**Do not lead with the gradient magnitude.** The gate's mean gradient norm is 887x smaller
than `cand`'s on identically shaped tensors, and that number is not the story: Adam is
scale-invariant, and the per-coordinate signal-to-noise ratio it actually consumes is
comparable across blocks (gate 0.066, `cand` 0.070, `out` 0.079).
**"Untrained" was the wrong word and it pointed at the wrong hypothesis.** It suggested the
training signal never reached the gate, which Task 11 falsified. What is true is narrower:
the gate receives a coherent signal, mostly through time, moves a long way in weight space,
and lands somewhere functionally indistinguishable from where it started.
`credit.md` Part B says why that is not merely a tuning accident: `M` cannot hold the regime
even when an auxiliary loss 5.8e4 times the main one demands it, while the same head
installs the entity *type* at 0.738 against chance 0.333. The state update can represent
per-entity properties and cannot represent this one.
## 7. Correction (Task 11): the probe figures here are linear-probe figures
Part B's decodes, and the "roughly a fifth of the available signal" reading they support in
`when_memory_works.md` §4, come from a linear probe. An MLP probe on the same runs reads the
regime from `M` at a gap of **+0.159** where the linear probe reads +0.064, and from the
memoryless `h` at **+0.234**.
The relative claim is unchanged and is what this file argues from: `M` holds no more about
the regime than the `h` it is built from, and on the MLP probe it holds visibly less. The
*absolute* fraction needs the qualifier wherever it is quoted.
+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
+270
View File
@@ -0,0 +1,270 @@
# Pooled probe: is the regime distributed across the 16 per-entity states?
Task 10. `results/frozen.md` Part B decoded the world's regime id from a *single*
entity's `M` at 0.332 against a measured chance of 0.273, and from the `h` inside the
same GRP at 0.338 against 0.274. An exact decoder reaches 0.958 from one observed
displacement (`results/when_memory_works.md` §2), so the information is there and the
organism holds about a fifth of it. Two explanations were left open:
- **(b) shape mismatch** — the regime is one global 3×3 matrix `K` and the state is
per-entity, so the information could be *distributed across* the 16 states while
being absent from any one of them.
- **(a) credit assignment** — nothing in the loss rewards carrying the regime forward,
so the state never learns to hold it at all.
**Verdict: (b) is dead. Pooling the 16 states does lift the decode — by +0.045 — but
it lifts the memoryless `h` by +0.048 at the same time. Pooled `M` gains nothing that
pooled `h` does not. The gain is noise-averaging over 16 samples, not a global variable
assembled out of per-entity fragments. (a) is the remaining suspect.**
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. 24 training runs total.
```
uv run python pooled.py --seeds 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15 \
--estimators lsq,logit --power-check --out results/pooled.json
uv run python pooled.py --seeds 0,1,2,3,4,5,6,7 --frozen-steps 16000 \
--out results/pooled_long.json
```
`pooled.py` adds no training loop and no architecture. `_build`, `_train`, `_frozen`
and `probe` are imported from `frozen.py` unchanged; the only new code is the three
views of the representation, the reporting, and the synthetic positive control.
## 0. The pin
The `single` rows are not a re-implementation of the baseline, they *are* the baseline.
Every seed 0-7 `M_single` and `h_single` accuracy and chance level in this file is
**bit-identical to the corresponding entry in `results/frozen.json`** (asserted by
comparing the two files, and by `test_single_view_reproduces_the_frozen_probe_exactly`,
which pins `pooled.run_one` against `frozen.run_one` at a small budget). Restricted to
seeds 0-7 the table below reproduces `frozen.md` Part B exactly: `M` 0.332 against
0.273, `h` 0.338 against 0.274.
## 1. The table
16 seeds, least squares, means over seeds. `shuffle` permutes the step labels keeping a
step's 16 entities together; `shift` circularly shifts the label sequence, preserving
each regime's 40-80 step block structure, and is the stricter of the two. `gap` is
`acc − shift`, per seed, then averaged. `feat` is the probe's feature count and `n_tr`
its training samples — pooling trades 16× the samples for one pooled sample per step,
and concatenation multiplies the feature count by 16, which is exactly what inflates a
fitted probe's chance level and why `shift` is not optional.
```
representation feat n_tr acc shuffle shift gap sd(gap) >chance
---------------------------------------------------------------------------------
M, single 32 44800 0.312 0.270 0.268 +0.044 0.053 13/16
M, mean 32 2800 0.349 0.265 0.260 +0.089 0.066 15/16
M, concat 512 2800 0.292 0.251 0.258 +0.034 0.055 10/16
h, single 32 44800 0.313 0.272 0.268 +0.045 0.058 13/16
h, mean 32 2800 0.354 0.267 0.261 +0.093 0.065 16/16
h, concat 512 2800 0.291 0.251 0.256 +0.036 0.061 12/16
```
The concatenated chance levels do sit lower than the single-entity ones (0.256-0.258
against 0.268) — the control caught the direction, though not the magnitude some
inflation argument would predict.
## 2. The measurement
Pooling's gain is `gap(pooled) − gap(single)`, computed per seed and then averaged.
**The `h` row is the whole measurement.** `h` is the feedforward layer `M` is built
from and carries no memory across steps, so whatever pooling buys on `h` is the value
of pooling as such. (b) is live only if `M` gains what `h` does not.
```
M gain h gain M − h M>h seeds
------------------------------------------------------------------------
mean-pooled +0.045 (sd 0.043) +0.048 (sd 0.060) -0.003 8/16
concatenated -0.010 (sd 0.053) -0.009 (sd 0.063) -0.001 8/16
```
**Mean-pooled `M` gains +0.045. Mean-pooled `h` gains +0.048. The difference is
−0.003, with a paired across-seed standard error of 0.015, and `M` beats `h` on
exactly 8 seeds out of 16 — a coin flip.** The gain itself is real: it is positive on
14/16 seeds for `M` and 13/16 for `h`. It is simply not a memory effect. Concatenation
gains nothing at all at this budget, on either representation (see §4).
Per-seed pooling gains, mean-pooled, seeds 0-15:
```
M gain +0.041 +0.126 +0.025 +0.057 +0.049 +0.088 -0.033 +0.041 +0.081 +0.001 -0.017 +0.106 +0.063 +0.003 +0.056 +0.038
h gain +0.076 +0.060 +0.055 +0.054 +0.115 +0.086 -0.069 -0.062 +0.066 +0.038 +0.089 +0.116 -0.038 +0.000 +0.062 +0.120
M − h -0.036 +0.066 -0.030 +0.003 -0.066 +0.003 +0.036 +0.103 +0.015 -0.036 -0.106 -0.010 +0.101 +0.003 -0.006 -0.082
```
Per-seed gap above the shift null, all six representations:
```
representation s0 s1 s2 s3 s4 s5 s6 s7 s8 s9 s10 s11 s12 s13 s14 s15
------------------------------------------------------------------------------------------------------------------------------------------------
M, single +0.064 +0.017 +0.042 +0.117 +0.047 -0.047 +0.101 +0.127 +0.014 +0.042 -0.058 +0.087 +0.053 +0.048 -0.019 +0.069
M, mean +0.105 +0.143 +0.067 +0.174 +0.096 +0.041 +0.068 +0.168 +0.095 +0.043 -0.075 +0.193 +0.116 +0.051 +0.037 +0.106
M, concat -0.014 -0.050 +0.146 +0.090 +0.093 -0.007 +0.009 +0.091 +0.026 +0.002 -0.010 +0.076 -0.001 +0.061 -0.027 +0.052
h, single +0.060 +0.019 +0.040 +0.124 +0.082 -0.055 +0.110 +0.137 +0.027 +0.028 -0.072 +0.087 +0.050 +0.039 -0.009 +0.054
h, mean +0.136 +0.079 +0.094 +0.179 +0.197 +0.031 +0.041 +0.076 +0.093 +0.066 +0.017 +0.203 +0.013 +0.039 +0.053 +0.174
h, concat +0.034 -0.030 +0.109 +0.127 +0.077 -0.045 +0.047 +0.046 +0.004 -0.063 +0.038 +0.139 +0.006 +0.052 +0.069 -0.035
```
**Eight seeds are worth reporting on their own, because eight is what would have been
run.** Restricted to seeds 0-7 the mean-pooling gains are `M` +0.049 and `h` +0.039, a
difference of +0.010 with `M` ahead on 5/8 — which reads, faintly, like support for
(b). Adding seeds 8-15 flips the sign to −0.003 at 8/16. The apparent effect at 8 seeds
is smaller than the across-seed spread that produces it, which is the failure mode
`AGENTS.md` warns about, caught here by running twice the seeds.
## 3. Controls
### 3a. Pooling representations vs. aggregating decisions
A per-step number can also rise by letting 16 independent per-entity decoders vote,
which involves no pooled representation at all. `frozen.probe` already computes that
vote. 16 seeds, least squares, accuracies:
```
representation per-entity 16-vote mean-pooled
---------------------------------------------------
M 0.312 0.327 0.349
h 0.313 0.327 0.354
```
Voting recovers roughly half of what mean-pooling recovers, and it recovers exactly the
same amount for `M` and for `h`. Both routes to a per-step answer are indifferent to
whether the representation carries memory.
### 3b. Second estimator
Multinomial logistic (LBFGS, strong Wolfe), same 16 seeds, same splits:
```
M gain h gain M − h M>h seeds
--------------------------------------------------------------
mean-pooled +0.054 +0.048 +0.005 7/16
concatenated -0.001 +0.002 -0.003 6/16
```
The sign of `M − h` flips between the two estimators (−0.003 least squares, +0.005
logistic) while both stay inside one standard error of zero. Not a least-squares
artefact; not an effect either.
### 3c. The concatenated view was sample-starved — and it does not change the answer
`M, concat` fits 513 parameters to 2800 pooled samples and comes out *below* the
single-entity probe, with a per-seed spread (sd 0.055) as large as the effect. That is
a fit problem, not an information one, and it had to be separated from the null.
Re-running 8 seeds with a 16000-step frozen phase — 11200 pooled training samples, 22
per feature, the only change — turns concatenation into a working probe:
```
representation gap (4000 frozen) gap (16000 frozen)
-------------------------------------------------------------
M, single +0.058* +0.097
M, mean +0.108* +0.160
M, concat +0.045* +0.105
h, single +0.065* +0.090
h, mean +0.104* +0.150
h, concat +0.046* +0.102
```
`*` seeds 0-7 at 4000 frozen steps, so the two columns are the same eight seeds.
Every representation decodes better with a longer probe budget, and concatenation
recovers to parity with the single-entity probe rather than beating it. The gains:
```
M gain h gain M − h M>h seeds (8 seeds, 16000 frozen)
------------------------------------------------------------------------------------------
mean-pooled +0.063 +0.060 +0.003 5/8
concatenated +0.008 +0.012 -0.003 4/8
```
Same null, measured more precisely: every seed's pooling gain is positive for `M`
(8/8) and for `h` (7/8), and the difference between them is +0.003 on a coin flip.
**The strongest form of pooling, given enough samples to fit it, adds nothing over the
mean and still splits evenly between the state and the state-free layer.**
### 3d. The positive control: this measurement can detect (b)
A null is worth nothing without evidence the instrument has the power to see the
positive. `pooled.power_check` builds two synthetic representations over a real
4000-step regime label sequence from the same world (seed 0), so the block structure
is the world's, and runs them through the same three views and the same probe:
- **`distributed`** — hypothesis (b) made true by construction. The regime is two bits;
entities 0-7 write bit 0 into channel 0 and entities 8-15 write bit 1 into channel 1,
every other channel noise. No single entity holds more than one bit, so a per-entity
probe caps near 0.5 while the pool holds both.
- **`redundant`** — every entity carries the whole regime code plus independent noise.
Nothing is distributed; pooling only averages noise away. This is the confound the
`h` control exists to catch, reproduced deliberately.
```
view acc shuffle shift gap pooling gain
--------------------------------------------------------------------
distributed single 0.421 0.281 0.328 +0.093 --
distributed mean 1.000 0.266 0.318 +0.682 +0.589
distributed concat 0.963 0.252 0.267 +0.696 +0.603
redundant single 0.691 0.294 0.310 +0.381 --
redundant mean 1.000 0.283 0.336 +0.664 +0.283
redundant concat 0.999 0.261 0.280 +0.719 +0.338
```
**A genuinely distributed code produces a pooling gain of +0.589. The measured gain on
`M` is +0.045, and `h` produces +0.048 of it.** The instrument's demonstrated
sensitivity is thirteen times the effect it was asked to find, and the effect it did
find has the redundant signature — present on the memoryless layer too — not the
distributed one.
### 3e. The controls can fail
`AGENTS.md`: a test that cannot fail is worse than no test, so the property was broken
on purpose. `test_the_power_check_can_fail` replaces `views` with one whose `mean` and
`concat` read entity 0 alone — every downstream shape unchanged, only the aggregation
removed — and asserts the `distributed` control then **fails** to clear its threshold.
It does. `test_views_preserve_the_representation` separately pins that `concat` block
`i` is always particle `i` and that `mean` is the entity average. Full suite: 70 passed
(66 existing, 4 new); the existing `frozen.py` and `regime.py` tests are untouched and
still pass.
## 4. Verdict
**Is the regime information distributed across the per-entity states, or absent from
them?** Absent from them. Pooling the 16 states does raise the decode — mean-pooled
`M` reaches 0.349 against a measured chance of 0.260, where a single state reached
0.312 against 0.268 — but the memoryless `h` inside the very same organism rises by
the same amount at the same time, from +0.045 to +0.093 above its own chance, and does
so on more seeds than `M` does. Across three settings (16 seeds at 4000 frozen steps, 8
seeds at 4000, 8 seeds at 16000) and two estimators, the difference between `M`'s
pooling gain and `h`'s ranges from −0.003 to +0.010, with a paired standard error of
about 0.015 and a seed-win count that never leaves the 4/8-to-5/8 band. Against that,
a synthetic representation whose regime code is genuinely distributed across entities
gains +0.589 from the same pooling through the same probe. The lift that pooling
delivers here is what averaging 16 noisy samples of one instantaneous quantity
delivers, and the instantaneous quantity is the particle configuration the current
coupling matrix is imposing — visible in `r` right now, in a state-free layer,
exactly as `frozen.md` §2 concluded from the state-ablated GRP. Even pooled, the decode sits 0.089
above chance where an exact decoder given one observed displacement sits about 0.73
above its own measured chance. **Hypothesis (b), that the regime is present but distributed across the
per-entity states, is not supported: the shape of the memory is not what is stopping
it. (a), that nothing in the loss ever rewarded carrying the regime forward, is the
remaining suspect.**
## 5. Consequences
- **Do not spend the next month on the shape of the memory.** A global read-out head,
a cross-entity aggregation, or a shared regime slot alongside the per-entity states
would all be motivated by (b), and (b) is measured dead here. Whatever such a change
bought would have to come from somewhere other than recovering information the 16
states already hold, because they do not hold it.
- **The remaining suspect is testable, and it is testable the way this project already
knows how.** (a) says the loss never asked. `frozen.md` §3 supplies the mechanism —
the gate sits at 0.500 ± 0.029, untrained, on every seed — and §1b supplies the
reason it had no job: the post-switch error is dominated by the world's own
configuration transient, which no state can shorten. Measure the ceiling first: an
oracle condition given the regime, in a setting where holding it is worth something,
before any mechanism is built to hold it.
- **Eight seeds would have reported the wrong sign.** At seeds 0-7 this measurement
reads +0.010 in `M`'s favour on 5/8; at 16 seeds it reads −0.003 on 8/16. Nothing
in this file's design changed between those two numbers except the seed count.
+4
View File
@@ -462,6 +462,10 @@ history, using a decoder with no privileged knowledge. `M` holds roughly a fifth
signal that a fair observer extracts from one step of the past, and no more than the
memoryless RP's own `h` holds.
(Both figures are **linear-probe** numbers. An MLP probe reads +0.159 from `M` and +0.234
from `h` on the same runs — see `frozen.md` §7. The relative claim is unchanged; the
absolute fraction needs the qualifier.)
**So the failure is ours, not the domain's.** That is the uncomfortable branch, and it was
named in advance precisely so it could not be avoided afterwards: `T_id << T_z` was
pre-registered as meaning "the domain can reward memory and the failure is ours". It came
+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
+81
View File
@@ -0,0 +1,81 @@
import numpy as np
import pytest
import frozen
import pooled
from pooled import power_check, run_one, views
def _labels(t: int = 4000, seed: int = 0):
"""A regime label sequence with the world's own 40-80 step block structure."""
rng = np.random.default_rng(seed)
lab, sw, g = [], [], 0
while len(lab) < t:
g = int(rng.choice([i for i in range(4) if i != g]))
n = int(rng.integers(40, 81))
sw += [True] + [False] * (n - 1)
lab += [g] * n
return np.array(lab[:t]), sw[:t]
def test_views_preserve_the_representation():
"""Pooling must aggregate the entities it claims to, in a stable order."""
rep = np.random.default_rng(0).normal(size=(50, 16, 32))
v = views(rep)
assert v["single"] is rep
assert v["mean"].shape == (50, 1, 32)
assert v["concat"].shape == (50, 1, 16 * 32)
assert np.allclose(v["mean"][:, 0], rep.mean(1))
for i in range(16): # concat block i is always particle i
assert np.array_equal(v["concat"][:, 0, i * 32:(i + 1) * 32], rep[:, i])
def test_single_view_reproduces_the_frozen_probe_exactly():
"""The `single` row must be the published baseline, not a re-implementation of it.
Same organism, same world, same estimator: bit-identical or the comparison this
file draws against `results/frozen.md` is not against anything.
"""
kw = dict(train_steps=300, frozen_steps=300)
mine = run_one(seed=0, **kw)["probes"]
theirs = frozen.run_one("grp_k0", seed=0, **kw)["probes"]
for tag in ("M", "h"):
assert mine[f"{tag}_single_lsq"]["acc_entity"] == theirs[f"{tag}_lsq"]["acc_entity"]
assert mine[f"{tag}_single_lsq"]["chance_shift"] == theirs[f"{tag}_lsq"]["chance_shift"]
def test_power_check_finds_a_code_that_is_only_in_the_pool():
"""The positive control: hypothesis (b) made true by construction.
In `distributed` no entity holds more than one of the regime's two bits, so a
per-entity probe caps near 0.5 while the pool holds both. If this pipeline could
not find that, a null on the real data would carry no information.
"""
lab, sw = _labels()
pc = power_check(lab, sw, seed=0)
gap = lambda k: pc[k]["acc_entity"] - pc[k]["chance_shift"]
assert gap("distributed_single") < 0.30
assert gap("distributed_mean") > 0.60
assert gap("distributed_concat") > 0.60
# and pooling lifts a merely redundant code too -- the confound the `h` row controls
assert gap("redundant_mean") - gap("redundant_single") > 0.20
def test_the_power_check_can_fail(monkeypatch):
"""Break the pooling on purpose; the positive control must notice.
`views` is replaced by one whose `mean` and `concat` read entity 0 alone -- the
shape of every downstream call is unchanged, only the aggregation is gone. A test
that still passed here would be defending nothing.
"""
def broken(rep):
t, n, d = rep.shape
one = rep[:, :1]
return {"single": rep, "mean": one, "concat": np.tile(one, (1, 1, n)).reshape(t, 1, n * d)}
monkeypatch.setattr(pooled, "views", broken)
lab, sw = _labels()
pc = power_check(lab, sw, seed=0)
gap = lambda k: pc[k]["acc_entity"] - pc[k]["chance_shift"]
with pytest.raises(AssertionError):
assert gap("distributed_mean") > 0.60