Compare commits
3
Commits
main
..
8dc20c8446
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8dc20c8446 | ||
|
|
ce04abefa1 | ||
|
|
5ea76d275e |
No files matched your search
@@ -1,104 +0,0 @@
|
|||||||
# experiments — measurement rules
|
|
||||||
|
|
||||||
The domain and the runs. This repo produces every number the paper reports, so its rules are
|
|
||||||
about not fooling ourselves rather than about code style. The library is the sibling `ailed`
|
|
||||||
repo, installed editable; the design is `AILED_General_Specification.md` in the parent
|
|
||||||
directory.
|
|
||||||
|
|
||||||
## What is in here
|
|
||||||
|
|
||||||
| file | responsibility |
|
|
||||||
|---|---|
|
|
||||||
| `particles.py` | the domain: particles on a torus whose type-by-type coupling switches unannounced |
|
|
||||||
| `regime.py` | the conditions, the training loop, and `_metrics` |
|
|
||||||
| `frozen.py` | frozen-weights probe, the state ablation, the representation probes |
|
|
||||||
| `ceilings.py` | least-squares information ceilings under four information sets |
|
|
||||||
| `identify.py` | how much of the hidden variable lives in the past rather than the present |
|
|
||||||
| `when_memory_works.py` | the pre-registered test of when per-entity state has a job |
|
|
||||||
| `results/*.md` | **the audit trail the paper cites.** Committed. The `.json` files are not. |
|
|
||||||
|
|
||||||
## 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.
|
|
||||||
- **Do not open a new domain to make a mechanism work.** That is p-hacking with extra steps
|
|
||||||
and it generalises to nothing. If a mechanism does not help, measure why on the domain you
|
|
||||||
have. `results/when_memory_works.md` exists because of this rule.
|
|
||||||
- **Do not tune a baseline until it catches up.** Raising the learning rate until the
|
|
||||||
memoryless model matches the gated one changes the question instead of answering it.
|
|
||||||
Tuning a *mechanism's own* parameters is different and legitimate — `rho_a`/`rho_slow`
|
|
||||||
belong to affect, so setting them is fair; `lr` belongs to the comparison, so it is not.
|
|
||||||
- **Every comparison is capacity-controlled.** `rp_only` has 1442 parameters and `grp_k0` has
|
|
||||||
5602. A number comparing them is confounded 3.9x and is not a memory result. See
|
|
||||||
`results/frozen.md` §1d, which also records why "capacity" was the wrong word for that
|
|
||||||
margin in the first place.
|
|
||||||
- **Verify the model can represent the domain before asking what memory adds.** Every chess
|
|
||||||
null before `results/chess_reach.md` was measured on a kernel that could not tell a knight
|
|
||||||
from a bishop — the type was in `attrs`, so it could only *scale* one shared geometry, and
|
|
||||||
the knight's L scored exactly zero on 8/8 seeds. Those nulls are facts about that setup and
|
|
||||||
not about memory. Before a mechanism comparison, measure whether the model has learned the
|
|
||||||
domain's own structure; a null on a model that has not is uninterpretable. This is the
|
|
||||||
sibling of the oracle rule: the oracle asks whether the information pays, this asks whether
|
|
||||||
the architecture can hold it.
|
|
||||||
- **Teach the basics before measuring anything on top of them.** Training from scratch means
|
|
||||||
the domain's laws have to be *reachable* from what the organism is given, and on chess five
|
|
||||||
separate things were not, each found by measurement rather than argument:
|
|
||||||
the piece type never entered the kernel (knight's L at exactly 0.000, `chess_reach.md`);
|
|
||||||
the target was `attacks`, which for a pawn on e2 returns d3/f3 while its moves are e3/e4 —
|
|
||||||
no overlap — and omits castling and en passant entirely;
|
|
||||||
games never show an open board (a rook is blocked in 98-100% of real positions), so the rule
|
|
||||||
cannot be induced from play;
|
|
||||||
absolute position was erased by a translation-invariant input, while the answer depends on it
|
|
||||||
(a knight has 2.96 destinations on the rim and 6.85 in the middle, and 43% sit on the rim);
|
|
||||||
and rank was not oriented to the piece's own side, which splits one pawn law into two
|
|
||||||
mirrored ones.
|
|
||||||
Every memory null measured before these were fixed stands as a fact about that setup and
|
|
||||||
about nothing else. Before asking what a mechanism adds, check that the domain's own laws
|
|
||||||
are expressible in the inputs, the target, and the training distribution.
|
|
||||||
- **Pre-register when the result could be argued either way.** State the success criterion,
|
|
||||||
the seed count, and what counts as failure, in `.sdd/progress.md`, before the run. Then
|
|
||||||
accept what comes back. No re-running with adjusted criteria.
|
|
||||||
- **Oracles are opt-in and free.** Enabling one may only add columns to `attrs`. The
|
|
||||||
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, 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.
|
|
||||||
|
|
||||||
## Metrics, and what they do not mean
|
|
||||||
|
|
||||||
`recovery[k]` **does not measure adaptation.** Under frozen weights a stateless model
|
|
||||||
reproduces its shape at every lag, because it tracks the world's own post-switch
|
|
||||||
configuration transient (`frozen.md` §1b). Report it if useful, but never build a claim on
|
|
||||||
it; the honest observable is a difference between conditions at matched lag.
|
|
||||||
|
|
||||||
`run()` refuses `window >= t_min`, because a recovery window that reaches the next switch
|
|
||||||
silently blends two events into one curve.
|
|
||||||
|
|
||||||
## Tests
|
|
||||||
|
|
||||||
`uv run pytest -q`. Same rule as the library: a test that cannot fail is worse than no test.
|
|
||||||
When you add a control, verify it can detect the thing it controls for — the freeze assertion
|
|
||||||
in `frozen.py` has a test that nudges a weight to prove the assertion fires.
|
|
||||||
|
|
||||||
## Conventions
|
|
||||||
|
|
||||||
Python ≥3.11, `uv`, PyTorch, pytest. `pythonpath = ["."]`, so modules sit at the repo root.
|
|
||||||
Runs are cheap — 8000 steps takes seconds. Spend the budget on more seeds, not longer runs.
|
|
||||||
Commit inside this repo only.
|
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
# experiments
|
|
||||||
|
|
||||||
The domain and the runs — every number the paper reports comes from here.
|
|
||||||
|
|
||||||
Rules for this repo are in `AGENTS.md` — read it before changing anything. It carries the
|
|
||||||
constraints that exist because breaking them produced a wrong result, not style preferences.
|
|
||||||
|
|
||||||
The design this implements is `AILED_General_Specification.md`, and the project-wide rules are
|
|
||||||
in `AGENTS.md`, both in the parent directory alongside the sibling repos.
|
|
||||||
@@ -1,375 +0,0 @@
|
|||||||
"""Task 8, claim A1: does affect move a gate that gradient descent left inert?
|
|
||||||
|
|
||||||
`results/frozen.md` measured the gate at `g = 0.500 +- 0.029` after 8000 steps, on
|
|
||||||
every seed, with no saturation in either direction: `M <- (1-g) M~ + g M` is a fixed
|
|
||||||
50/50 blend and nothing is being decided about what to keep. The gate's
|
|
||||||
pre-activation is `W_g[h||M] + b_g - kappa*a`, and the `-kappa*a` term is external
|
|
||||||
forcing that never passes through the gradient. It is therefore the only available
|
|
||||||
lever on this gate, which is what makes A1 worth running now:
|
|
||||||
|
|
||||||
Part A does an affective signal move a mechanism gradient descent left inert?
|
|
||||||
Part B does moving it do any measurable good?
|
|
||||||
Part C is the good it does about *surprise*, or would any signal with the same
|
|
||||||
marginal distribution and the wrong timing do as well?
|
|
||||||
|
|
||||||
The A1 comparison is `grp_k` against `grp_k0`: identical architecture, identical
|
|
||||||
5602 parameters, differing only in kappa. `rp_only` (1442 params) and
|
|
||||||
`grp_k0_nostate` are context, never the claim -- see results/frozen.md section 5.
|
|
||||||
|
|
||||||
Part A's headline is *not* mean `g`. Arousal is non-negative, so `-kappa*a` lowers
|
|
||||||
the mean by construction and a lower mean proves nothing. The contrast that carries
|
|
||||||
the claim is post-switch against far-from-switch within one run, and alongside it
|
|
||||||
the learned pre-activation `W_g[h||M] + b_g` measured on its own, which says whether
|
|
||||||
gradient pushes back against the forcing or leaves it alone.
|
|
||||||
"""
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import argparse
|
|
||||||
import json
|
|
||||||
import math
|
|
||||||
import statistics
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
import numpy as np
|
|
||||||
import torch
|
|
||||||
|
|
||||||
from frozen import _build, _hidden, _train
|
|
||||||
from regime import _metrics
|
|
||||||
|
|
||||||
STEPS = 8000
|
|
||||||
SEEDS = tuple(range(16))
|
|
||||||
KAPPAS = (0.0, 1.0, 2.0, 4.0, 8.0, 16.0)
|
|
||||||
WINDOW = 20
|
|
||||||
BPTT = 20
|
|
||||||
LR = 1e-3
|
|
||||||
|
|
||||||
|
|
||||||
# -- Part A: watching the gate ---------------------------------------------------
|
|
||||||
|
|
||||||
class GateTrace:
|
|
||||||
"""`_train` callback recording the gate at every step, per entity, pooled per step.
|
|
||||||
|
|
||||||
`g` is reconstructed rather than read out, because `Organism.forward` returns only
|
|
||||||
`out(M)`. `org.grp(h, prev, a)` is asserted equal to the M the organism actually
|
|
||||||
returned on every step of every run, which is what makes the reconstructed `h` --
|
|
||||||
and therefore the reconstructed `g` -- the organism's own and not a plausible
|
|
||||||
lookalike. The reconstruction runs under `no_grad`; it is bit-identical anyway.
|
|
||||||
|
|
||||||
`pre` is the learned part of the pre-activation, `W_g[h||M] + b_g`, with the
|
|
||||||
`-kappa*a` forcing left out. Comparing it across kappa asks whether gradient
|
|
||||||
compensates for the forcing or ignores it.
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __init__(self, org):
|
|
||||||
self.org = org
|
|
||||||
self.g_mean, self.g_sq, self.open_, self.shut = [], [], [], []
|
|
||||||
self.pre_mean, self.pre_sq, self.a_gate = [], [], []
|
|
||||||
|
|
||||||
def __call__(self, t, obs, r, ctx, axes, prev, memory):
|
|
||||||
org = self.org
|
|
||||||
arousal = axes[1]
|
|
||||||
with torch.no_grad():
|
|
||||||
h = _hidden(org, obs.attrs, r, axes, ctx)
|
|
||||||
M = torch.stack([memory[i] for i in obs.ids])
|
|
||||||
assert torch.equal(org.grp(h, prev, arousal), M), "gate reconstruction diverged"
|
|
||||||
pre = org.grp.gate(torch.cat([h, prev], -1))
|
|
||||||
g = torch.sigmoid(pre - org.grp.kappa * arousal)
|
|
||||||
self.g_mean.append(float(g.mean())); self.g_sq.append(float((g ** 2).mean()))
|
|
||||||
self.open_.append(float((g > 0.9).float().mean()))
|
|
||||||
self.shut.append(float((g < 0.1).float().mean()))
|
|
||||||
self.pre_mean.append(float(pre.mean())); self.pre_sq.append(float((pre ** 2).mean()))
|
|
||||||
self.a_gate.append(arousal)
|
|
||||||
|
|
||||||
def arrays(self) -> dict[str, np.ndarray]:
|
|
||||||
return {k: np.asarray(v) for k, v in vars(self).items() if isinstance(v, list)}
|
|
||||||
|
|
||||||
|
|
||||||
def index_sets(switched: list[bool], steps: int, window: int) -> dict[str, list[int]]:
|
|
||||||
"""The second half's post-switch and far-from-switch steps, as `regime._metrics` cuts them.
|
|
||||||
|
|
||||||
`far` is `_metrics`'s own `steady_idx` -- no switch in the preceding `window`
|
|
||||||
steps -- so the gate contrast and the error contrast are measured on the same
|
|
||||||
steps. `post` is the union of the `window` steps each switch opens, i.e. exactly
|
|
||||||
the steps `recovery[0..window-1]` averages over.
|
|
||||||
"""
|
|
||||||
half = steps // 2
|
|
||||||
sw = [i for i in range(half, steps - window) if switched[i]]
|
|
||||||
post = sorted({j + k for j in sw for k in range(window)})
|
|
||||||
far = [i for i in range(half, steps) if not any(switched[max(0, i - window):i + 1])]
|
|
||||||
return dict(switch=sw, post=post, far=far)
|
|
||||||
|
|
||||||
|
|
||||||
def _pool(idx: list[int], mean: np.ndarray, sq: np.ndarray) -> tuple[float, float]:
|
|
||||||
"""Pooled mean and sd over entity-steps, from per-step means of x and x^2."""
|
|
||||||
if not idx:
|
|
||||||
return float("nan"), float("nan")
|
|
||||||
m = float(mean[idx].mean())
|
|
||||||
return m, math.sqrt(max(0.0, float(sq[idx].mean()) - m * m))
|
|
||||||
|
|
||||||
|
|
||||||
def gate_stats(tr: GateTrace, switched: list[bool], steps: int, window: int) -> dict:
|
|
||||||
a = tr.arrays()
|
|
||||||
idx = index_sets(switched, steps, window)
|
|
||||||
allidx = list(range(steps // 2, steps))
|
|
||||||
out = {}
|
|
||||||
mean = lambda k, ix: float(a[k][ix].mean()) if ix else float("nan")
|
|
||||||
for tag, ix in (("all", allidx), ("post", idx["post"]), ("far", idx["far"])):
|
|
||||||
g, gsd = _pool(ix, a["g_mean"], a["g_sq"])
|
|
||||||
pre, presd = _pool(ix, a["pre_mean"], a["pre_sq"])
|
|
||||||
out[tag] = dict(g=g, g_sd=gsd, frac_open=mean("open_", ix),
|
|
||||||
frac_shut=mean("shut", ix), pre=pre, pre_sd=presd,
|
|
||||||
a_gate=mean("a_gate", ix), n_steps=len(ix))
|
|
||||||
# the same excursion `recovery[k]` measures on the loss, measured on the gate:
|
|
||||||
# lag k after a switch, averaged over the second half's switches
|
|
||||||
sw = idx["switch"]
|
|
||||||
for tag, key in (("g_by_lag", "g_mean"), ("pre_by_lag", "pre_mean"),
|
|
||||||
("a_by_lag", "a_gate"), ("shut_by_lag", "shut"), ("open_by_lag", "open_")):
|
|
||||||
out[tag] = [float(a[key][[j + k for j in sw]].mean()) if sw else float("nan")
|
|
||||||
for k in range(window)]
|
|
||||||
out["delta_post_far"] = out["post"]["g"] - out["far"]["g"]
|
|
||||||
out["a_delta_post_far"] = out["post"]["a_gate"] - out["far"]["a_gate"]
|
|
||||||
out["a_gate_at_switch"] = float(a["a_gate"][idx["switch"]].mean()) if idx["switch"] else float("nan")
|
|
||||||
return out
|
|
||||||
|
|
||||||
|
|
||||||
# -- driver ----------------------------------------------------------------------
|
|
||||||
|
|
||||||
def run_a1(name: str, seed: int, kappa: float, steps: int = STEPS, window: int = WINDOW,
|
|
||||||
bptt: int = BPTT, lr: float = LR, hidden: int = 32, omega: float = 10.0,
|
|
||||||
stateless: bool = False, gate_arousal=None, label: str | None = None) -> dict:
|
|
||||||
spec, wcfg, world, org = _build(name, seed, hidden, omega, kappa)
|
|
||||||
if window >= wcfg.t_min:
|
|
||||||
raise ValueError(f"window={window} must be < t_min={wcfg.t_min}")
|
|
||||||
tr = GateTrace(org) if org.use_memory else None
|
|
||||||
_, _, out = _train(spec, wcfg, world, org, steps, bptt, lr, stateless,
|
|
||||||
gate_arousal=gate_arousal, on_step=tr)
|
|
||||||
r = dict(condition=label or (name + ("_nostate" if stateless else "")), seed=seed,
|
|
||||||
kappa=kappa, steps=steps, stateless=stateless,
|
|
||||||
n_params=sum(p.numel() for p in org.parameters()),
|
|
||||||
**_metrics(out["losses"], out["switched"], out["arousals"], window))
|
|
||||||
if tr is not None:
|
|
||||||
r["gate"] = gate_stats(tr, out["switched"], steps, window)
|
|
||||||
# the sequence the gate actually saw, not `arousals`: `_train` records affect
|
|
||||||
# *after* the update, so arousals[t] is one step later than the gate's input.
|
|
||||||
# Part C replays this, which is what lets the `real` arm reproduce the run.
|
|
||||||
r["a_gate_seq"] = list(tr.a_gate)
|
|
||||||
return r
|
|
||||||
|
|
||||||
|
|
||||||
# -- Part C: the shuffled-affect control -----------------------------------------
|
|
||||||
|
|
||||||
def affect_variants(a_gate: list[float], seed: int, steps: int) -> dict:
|
|
||||||
"""The same arousal values the gate saw, delivered with the wrong timing.
|
|
||||||
|
|
||||||
`shuffled` permutes within each half separately, so the marginal distribution the
|
|
||||||
gate sees is matched exactly in the measured second half and not merely in
|
|
||||||
expectation; within a half the permutation is uniform, so it carries no relation
|
|
||||||
to switch timing. `shifted` rolls the whole trace, which additionally preserves
|
|
||||||
arousal's own autocorrelation and only breaks its alignment with the switches --
|
|
||||||
the stricter control of the two. `const` pins the run's mean arousal, which is
|
|
||||||
`-kappa*a` reduced to a pure bias shift with no timing information at all: if
|
|
||||||
that alone reproduces the effect, the effect was never about affect.
|
|
||||||
|
|
||||||
`real` replays the recorded trace unchanged. Because the run is deterministic
|
|
||||||
given the seed and the replayed values are exactly the ones it produced, it must
|
|
||||||
reproduce the unhooked run bit for bit -- which is how the replay machinery is
|
|
||||||
checked rather than trusted.
|
|
||||||
"""
|
|
||||||
a = np.asarray(a_gate, dtype=float)
|
|
||||||
rng = np.random.default_rng(10_000 + seed)
|
|
||||||
half = steps // 2
|
|
||||||
shuf = a.copy()
|
|
||||||
shuf[:half] = rng.permutation(shuf[:half])
|
|
||||||
shuf[half:] = rng.permutation(shuf[half:])
|
|
||||||
k = int(rng.integers(steps // 10, steps - steps // 10))
|
|
||||||
return dict(real=a, shuffled=shuf, shifted=np.roll(a, k), const=np.full(steps, a.mean()))
|
|
||||||
|
|
||||||
|
|
||||||
# -- reporting -------------------------------------------------------------------
|
|
||||||
|
|
||||||
def by_condition(results: list[dict]) -> dict[str, list[dict]]:
|
|
||||||
by: dict[str, list[dict]] = {}
|
|
||||||
for r in results:
|
|
||||||
by.setdefault(r["condition"], []).append(r)
|
|
||||||
return {k: sorted(v, key=lambda r: r["seed"]) for k, v in by.items()}
|
|
||||||
|
|
||||||
|
|
||||||
def gate_table(results: list[dict]) -> str:
|
|
||||||
lines = [f"{'condition':<16}{'kappa':>7}{'g_all':>8}{'sd':>7}{'g_post':>8}{'g_far':>8}"
|
|
||||||
f"{'delta':>8}{'open':>7}{'shut':>7}{'pre':>8}{'a_post':>8}{'a_far':>8}",
|
|
||||||
"-" * 100]
|
|
||||||
for name, rs in by_condition(results).items():
|
|
||||||
if "gate" not in rs[0]:
|
|
||||||
continue
|
|
||||||
m = lambda *k: statistics.fmean(_dig(r["gate"], k) for r in rs)
|
|
||||||
lines.append(
|
|
||||||
f"{name:<16}{rs[0]['kappa']:>7.0f}{m('all', 'g'):>8.3f}{m('all', 'g_sd'):>7.3f}"
|
|
||||||
f"{m('post', 'g'):>8.3f}{m('far', 'g'):>8.3f}{m('delta_post_far'):>8.3f}"
|
|
||||||
f"{m('all', 'frac_open'):>7.3f}{m('all', 'frac_shut'):>7.3f}{m('all', 'pre'):>8.3f}"
|
|
||||||
f"{m('post', 'a_gate'):>8.3f}{m('far', 'a_gate'):>8.3f}")
|
|
||||||
return "\n".join(lines)
|
|
||||||
|
|
||||||
|
|
||||||
def _dig(d, keys):
|
|
||||||
for k in keys:
|
|
||||||
d = d[k]
|
|
||||||
return d
|
|
||||||
|
|
||||||
|
|
||||||
def error_table(results: list[dict]) -> str:
|
|
||||||
idxs = [0, 2, 5, 10, 19]
|
|
||||||
head = "".join(f"{'rec@' + str(i):>11}" for i in idxs)
|
|
||||||
lines = [f"{'condition':<16}{'steady':>11}{'(sd)':>11}{head}", "-" * (16 + 22 + 11 * len(idxs))]
|
|
||||||
for name, rs in by_condition(results).items():
|
|
||||||
st = [r["steady"] for r in rs]
|
|
||||||
row = "".join(f"{statistics.fmean(r['recovery'][i] for r in rs):>11.3e}" for i in idxs)
|
|
||||||
sd = statistics.stdev(st) if len(st) > 1 else 0.0
|
|
||||||
lines.append(f"{name:<16}{statistics.fmean(st):>11.3e}{sd:>11.3e}{row}")
|
|
||||||
return "\n".join(lines)
|
|
||||||
|
|
||||||
|
|
||||||
def paired(results: list[dict], ref: str) -> str:
|
|
||||||
"""Per-seed ratio ref/condition on `steady`. Eight seeds supports a direction, not a ratio."""
|
|
||||||
by = by_condition(results)
|
|
||||||
if ref not in by:
|
|
||||||
return f"(no {ref} in these results)"
|
|
||||||
base = {r["seed"]: r["steady"] for r in by[ref]}
|
|
||||||
lines = [f"paired {ref} / condition on steady, per seed",
|
|
||||||
f"{'condition':<16}{'mean':>8}{'median':>8}{'won':>7} per-seed", "-" * 70]
|
|
||||||
for name, rs in by.items():
|
|
||||||
if name == ref:
|
|
||||||
continue
|
|
||||||
ratios = [base[r["seed"]] / r["steady"] for r in rs if r["seed"] in base]
|
|
||||||
per = " ".join(f"{x:.2f}" for x in ratios)
|
|
||||||
lines.append(f"{name:<16}{statistics.fmean(ratios):>8.2f}{statistics.median(ratios):>8.2f}"
|
|
||||||
f"{sum(x > 1 for x in ratios):>4}/{len(ratios):<2} {per}")
|
|
||||||
return "\n".join(lines)
|
|
||||||
|
|
||||||
|
|
||||||
def per_seed(results: list[dict], key: str = "steady") -> str:
|
|
||||||
by = by_condition(results)
|
|
||||||
seeds = sorted({r["seed"] for rs in by.values() for r in rs})
|
|
||||||
lines = [f"{'condition':<16}" + "".join(f"{'s' + str(s):>10}" for s in seeds),
|
|
||||||
"-" * (16 + 10 * len(seeds))]
|
|
||||||
for name, rs in by.items():
|
|
||||||
got = {r["seed"]: r[key] for r in rs}
|
|
||||||
lines.append(f"{name:<16}" + "".join(
|
|
||||||
f"{got[s]:>10.3e}" if s in got else f"{'--':>10}" for s in seeds))
|
|
||||||
return "\n".join(lines)
|
|
||||||
|
|
||||||
|
|
||||||
def paired_recovery(results: list[dict], ref: str, lags=(0, 2, 5, 10, 19)) -> str:
|
|
||||||
"""Per-seed ratio ref/condition at matched lag.
|
|
||||||
|
|
||||||
`recovery[k]` is contaminated: results/frozen.md section 1b showed it tracks the
|
|
||||||
world's post-switch configuration transient, which a stateless frozen model
|
|
||||||
reproduces at every lag. That transient is common to every condition, so a
|
|
||||||
*difference between conditions at the same lag* is the part of it that is about
|
|
||||||
the model. This is still a weaker observable than `steady`; it is reported, not
|
|
||||||
built on.
|
|
||||||
"""
|
|
||||||
by = by_condition(results)
|
|
||||||
if ref not in by:
|
|
||||||
return f"(no {ref} in these results)"
|
|
||||||
base = {r["seed"]: r["recovery"] for r in by[ref]}
|
|
||||||
lines = [f"paired {ref} / condition at matched lag (mean ratio, seeds won)",
|
|
||||||
f"{'condition':<16}" + "".join(f"{'@' + str(k):>14}" for k in lags), "-" * (16 + 14 * len(lags))]
|
|
||||||
for name, rs in by.items():
|
|
||||||
if name == ref:
|
|
||||||
continue
|
|
||||||
cells = []
|
|
||||||
for k in lags:
|
|
||||||
rat = [base[r["seed"]][k] / r["recovery"][k] for r in rs if r["seed"] in base]
|
|
||||||
cells.append(f"{statistics.fmean(rat):>8.2f}{sum(x > 1 for x in rat):>4}/{len(rat)}")
|
|
||||||
lines.append(f"{name:<16}" + "".join(f"{c:>14}" for c in cells))
|
|
||||||
return "\n".join(lines)
|
|
||||||
|
|
||||||
|
|
||||||
def gate_consistency(results: list[dict]) -> str:
|
|
||||||
"""How many seeds show the post-switch gate below the far-from-switch gate.
|
|
||||||
|
|
||||||
The mean is not the claim -- arousal is non-negative, so `-kappa*a` lowers mean g
|
|
||||||
by construction. This asks whether the gate moves *when surprised*, on each seed.
|
|
||||||
"""
|
|
||||||
lines = [f"{'condition':<16}{'mean delta':>12}{'median':>10}{'seeds down':>12} per-seed", "-" * 76]
|
|
||||||
for name, rs in by_condition(results).items():
|
|
||||||
if "gate" not in rs[0]:
|
|
||||||
continue
|
|
||||||
d = [r["gate"]["delta_post_far"] for r in rs]
|
|
||||||
lines.append(f"{name:<16}{statistics.fmean(d):>12.4f}{statistics.median(d):>10.4f}"
|
|
||||||
f"{sum(x < 0 for x in d):>8}/{len(d):<3} " + " ".join(f"{x:+.3f}" for x in d))
|
|
||||||
return "\n".join(lines)
|
|
||||||
|
|
||||||
|
|
||||||
def _save(results, out):
|
|
||||||
Path(out).parent.mkdir(parents=True, exist_ok=True)
|
|
||||||
Path(out).write_text(json.dumps(results, indent=1))
|
|
||||||
|
|
||||||
|
|
||||||
def _line(r):
|
|
||||||
g = r.get("gate")
|
|
||||||
msg = f"{r['condition']:<16} seed={r['seed']:<2} steady={r['steady']:.3e} rec@0={r['recovery'][0]:.3e}"
|
|
||||||
if g:
|
|
||||||
msg += (f" g={g['all']['g']:.3f} post={g['post']['g']:.3f} far={g['far']['g']:.3f}"
|
|
||||||
f" open={g['all']['frac_open']:.3f} shut={g['all']['frac_shut']:.3f}")
|
|
||||||
return msg
|
|
||||||
|
|
||||||
|
|
||||||
def main() -> None:
|
|
||||||
ap = argparse.ArgumentParser()
|
|
||||||
ap.add_argument("--stage", default="sweep", choices=["sweep", "controls", "shuffle", "report"])
|
|
||||||
ap.add_argument("--inputs", default="results/a1_sweep.json,results/a1_controls.json",
|
|
||||||
help="report stage: json files to tabulate together")
|
|
||||||
ap.add_argument("--ref", default="grp_k0", help="report stage: the paired baseline")
|
|
||||||
ap.add_argument("--seeds", default=",".join(str(s) for s in SEEDS))
|
|
||||||
ap.add_argument("--kappas", default=",".join(str(k) for k in KAPPAS))
|
|
||||||
ap.add_argument("--kappa", type=float, default=4.0, help="Part C operating point")
|
|
||||||
ap.add_argument("--steps", type=int, default=STEPS)
|
|
||||||
ap.add_argument("--window", type=int, default=WINDOW)
|
|
||||||
ap.add_argument("--out", default="results/a1_sweep.json")
|
|
||||||
a = ap.parse_args()
|
|
||||||
seeds = [int(s) for s in a.seeds.split(",")]
|
|
||||||
results = []
|
|
||||||
|
|
||||||
if a.stage == "report":
|
|
||||||
for f in a.inputs.split(","):
|
|
||||||
results += json.loads(Path(f).read_text())
|
|
||||||
for title, fn in (("gate", gate_table), ("gate post-vs-far, per seed", gate_consistency),
|
|
||||||
("error", error_table), ("per-seed steady", per_seed),
|
|
||||||
("paired steady", lambda r: paired(r, a.ref)),
|
|
||||||
("paired recovery", lambda r: paired_recovery(r, a.ref))):
|
|
||||||
print(f"\n## {title}\n"); print(fn(results))
|
|
||||||
return
|
|
||||||
|
|
||||||
if a.stage == "sweep":
|
|
||||||
for k in (float(x) for x in a.kappas.split(",")):
|
|
||||||
for seed in seeds:
|
|
||||||
r = run_a1("grp_k", seed, k, a.steps, a.window, label=f"grp_k{k:g}")
|
|
||||||
print(_line(r), flush=True); results.append(r)
|
|
||||||
|
|
||||||
elif a.stage == "controls":
|
|
||||||
for seed in seeds:
|
|
||||||
for name, sl in (("rp_only", False), ("grp_k0", True)):
|
|
||||||
r = run_a1(name, seed, 0.0, a.steps, a.window, stateless=sl)
|
|
||||||
print(_line(r), flush=True); results.append(r)
|
|
||||||
|
|
||||||
else: # shuffle
|
|
||||||
for seed in seeds:
|
|
||||||
base = run_a1("grp_k", seed, a.kappa, a.steps, a.window, label="unhooked")
|
|
||||||
for tag, seq in affect_variants(base["a_gate_seq"], seed, a.steps).items():
|
|
||||||
r = run_a1("grp_k", seed, a.kappa, a.steps, a.window,
|
|
||||||
gate_arousal=lambda t, _a, s=seq: s[t], label=tag)
|
|
||||||
if tag == "real": # the replay must reproduce the unhooked run exactly
|
|
||||||
assert r["steady"] == base["steady"], "arousal replay is not self-consistent"
|
|
||||||
assert r["recovery"] == base["recovery"], "arousal replay is not self-consistent"
|
|
||||||
print(_line(r), flush=True); results.append(r)
|
|
||||||
|
|
||||||
for r in results:
|
|
||||||
r.pop("a_gate_seq", None)
|
|
||||||
_save(results, a.out)
|
|
||||||
print(); print(gate_table(results)); print(); print(error_table(results))
|
|
||||||
print(); print(paired(results, "grp_k0" if a.stage == "sweep" else "const"))
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
main()
|
|
||||||
@@ -1,46 +0,0 @@
|
|||||||
"""Does one parameter set still WORK at an entity count it never trained on?
|
|
||||||
|
|
||||||
Read against the ORACLE, never down the N axis. `y_i` is a mean over neighbours, so the target's
|
|
||||||
variance falls as N rises and any error-over-floor ratio climbs with N for a model that is doing
|
|
||||||
nothing wrong. The oracle -- trained over the full range [2,32] -- absorbs all of that: at each
|
|
||||||
N, `forward / oracle` is the cost of never having seen that entity count, and nothing else.
|
|
||||||
|
|
||||||
Both directions are reported. A cost in BOTH is the degree distribution shifting under the mean
|
|
||||||
pooling; a cost in ONE is the extrapolation that was actually asked for.
|
|
||||||
"""
|
|
||||||
import json, statistics as st
|
|
||||||
|
|
||||||
|
|
||||||
def load(tag, arm):
|
|
||||||
rs = json.load(open(f"results/scale_{tag}.json"))["rows"]
|
|
||||||
return [r for r in rs if r["arm"] == arm]
|
|
||||||
|
|
||||||
|
|
||||||
def per_n(rows, n):
|
|
||||||
return st.mean([r["per_n"][str(n)]["mse"] for r in rows])
|
|
||||||
|
|
||||||
|
|
||||||
def paired(a, b, n):
|
|
||||||
d = [x["per_n"][str(n)]["mse"] - y["per_n"][str(n)]["mse"] for x, y in zip(a, b)]
|
|
||||||
return st.mean(d), st.stdev(d) / len(d) ** 0.5, sum(1 for v in d if v > 0), len(d)
|
|
||||||
|
|
||||||
|
|
||||||
NS = [2, 4, 8, 12, 16, 20, 24, 28, 32]
|
|
||||||
|
|
||||||
for arm in ("rp", "table"):
|
|
||||||
fwd, rev, orc = (load(t, arm) for t in ("forward", "reverse", "oracle"))
|
|
||||||
print(f"\n{'=' * 78}\n{arm.upper()} raw MSE, and cost against the oracle trained on [2,32]\n{'=' * 78}")
|
|
||||||
print(f"{'N':>4} {'fwd[2,16]':>10} {'rev[17,32]':>11} {'oracle':>10} "
|
|
||||||
f"{'fwd/orc':>8} {'rev/orc':>8} trained on N?")
|
|
||||||
for n in NS:
|
|
||||||
f, r, o = per_n(fwd, n), per_n(rev, n), per_n(orc, n)
|
|
||||||
tag = "fwd" if n <= 16 else "rev"
|
|
||||||
print(f"{n:>4} {f:10.5f} {r:11.5f} {o:10.5f} {f / o:8.2f} {r / o:8.2f} {tag} only")
|
|
||||||
print()
|
|
||||||
for label, arms_, ns in (("forward, unseen N (17-32)", fwd, [20, 24, 28, 32]),
|
|
||||||
("reverse, unseen N (2-16)", rev, [2, 4, 8, 12])):
|
|
||||||
ms = [paired(orc, arms_, n) for n in ns]
|
|
||||||
tot = st.mean([m for m, _, _, _ in ms])
|
|
||||||
won = sum(w for _, _, w, _ in ms)
|
|
||||||
print(f" {label}: mean cost over oracle {tot:+.5f} "
|
|
||||||
f"{won}/{sum(k for _, _, _, k in ms)} seed-points worse than oracle")
|
|
||||||
@@ -1,39 +0,0 @@
|
|||||||
"""The omega curve. Prints all of it, which is the point.
|
|
||||||
|
|
||||||
omega sets the CPPN's bandwidth. `unseen.md` found a 17x swing between two hand-picked values
|
|
||||||
and every chess number sits at one of them, unexamined. This decides which of two things that
|
|
||||||
is: a knob that was set wrong (broad plateau -> document it, choose per domain, leave
|
|
||||||
AffectiveCPPN alone) or an architectural defect (narrow, domain-dependent optimum -> a learned
|
|
||||||
or multi-scale frequency is a mechanism question worth asking).
|
|
||||||
|
|
||||||
THE TRAP, stated so it cannot be walked into: this reports the whole curve. Picking the omega
|
|
||||||
that beats table+interp and quoting that number would be tuning a mechanism until it wins,
|
|
||||||
which is the move AGENTS.md exists to forbid.
|
|
||||||
"""
|
|
||||||
import glob, json, re, statistics as st
|
|
||||||
|
|
||||||
REF = {"random": 0.00016, "band": 0.00006} # table+interp, from unseen.md
|
|
||||||
|
|
||||||
|
|
||||||
def load(path):
|
|
||||||
return [r for r in json.load(open(path))["rows"] if r["arm"] == "rp"]
|
|
||||||
|
|
||||||
|
|
||||||
for kind in ("random", "band"):
|
|
||||||
files = sorted(glob.glob(f"results/sweep_{kind}_w*.json"),
|
|
||||||
key=lambda f: float(re.search(r"_w([\d.]+)\.json", f).group(1)))
|
|
||||||
if not files:
|
|
||||||
print(f"{kind}: nothing yet")
|
|
||||||
continue
|
|
||||||
print(f"\n{'=' * 78}\n{kind.upper()} hold-out — omega curve, 8 seeds"
|
|
||||||
f" (table+interp reference: {REF[kind]:.5f})\n{'=' * 78}")
|
|
||||||
print(f"{'omega':>6} {'seen':>10} {'unseen':>10} {'u/s':>6} {'vs ref':>8} "
|
|
||||||
f"{'seeds<ref':>10} per-seed unseen")
|
|
||||||
for f in files:
|
|
||||||
w = float(re.search(r"_w([\d.]+)\.json", f).group(1))
|
|
||||||
rs = load(f)
|
|
||||||
seen, uns = st.mean([r["seen"] for r in rs]), st.mean([r["unseen"] for r in rs])
|
|
||||||
beat = sum(1 for r in rs if r["unseen"] < REF[kind])
|
|
||||||
per = " ".join(f"{r['unseen']:.5f}" for r in sorted(rs, key=lambda r: r["seed"]))
|
|
||||||
print(f"{w:>6g} {seen:10.5f} {uns:10.5f} {uns / seen:6.2f} "
|
|
||||||
f"{uns / REF[kind]:8.2f}x {beat:>7}/8 {per}")
|
|
||||||
@@ -1,49 +0,0 @@
|
|||||||
"""Paired comparison across the arms of unseen.py. Per-seed values, seeds won, paired se."""
|
|
||||||
import json, statistics as st
|
|
||||||
|
|
||||||
|
|
||||||
def rows(path, arm=None):
|
|
||||||
rs = json.load(open(path))["rows"]
|
|
||||||
return {r["seed"]: r for r in rs if arm is None or r["arm"] == arm}
|
|
||||||
|
|
||||||
|
|
||||||
def paired(a, b, key="unseen"):
|
|
||||||
d = [b[s][key] - a[s][key] for s in sorted(a)]
|
|
||||||
return st.mean(d), st.stdev(d) / len(d) ** 0.5, sum(1 for x in d if x > 0), len(d)
|
|
||||||
|
|
||||||
|
|
||||||
def col(d, key="unseen"):
|
|
||||||
return st.mean([r[key] for r in d.values()])
|
|
||||||
|
|
||||||
|
|
||||||
for kind in ("random", "band"):
|
|
||||||
rp = rows(f"results/unseen_{kind}.json", "rp")
|
|
||||||
tb = rows(f"results/unseen_{kind}.json", "table")
|
|
||||||
it = rows(f"results/unseen_{kind}_interp.json", "table_interp")
|
|
||||||
try:
|
|
||||||
w10 = rows(f"results/unseen_{kind}_w10.json", "rp")
|
|
||||||
except FileNotFoundError:
|
|
||||||
w10 = None
|
|
||||||
|
|
||||||
print(f"\n{'=' * 72}\n{kind.upper()} hold-out, {rp[0]['n_held']}/225 cells "
|
|
||||||
f"(MSE on held-out relations, lower is better)\n{'=' * 72}")
|
|
||||||
print(f"{'seed':>4} {'rp':>10} {'table':>10} {'tbl+interp':>12} {'rp w=10':>10} {'floor':>10}")
|
|
||||||
for s in sorted(rp):
|
|
||||||
w = f"{w10[s]['unseen']:10.5f}" if w10 else f"{'-':>10}"
|
|
||||||
print(f"{s:>4} {rp[s]['unseen']:10.5f} {tb[s]['unseen']:10.5f} "
|
|
||||||
f"{it[s]['unseen']:12.5f} {w} {rp[s]['floor_unseen']:10.5f}")
|
|
||||||
wm = f"{col(w10):10.5f}" if w10 else f"{'-':>10}"
|
|
||||||
print(f"{'mean':>4} {col(rp):10.5f} {col(tb):10.5f} {col(it):12.5f} {wm} "
|
|
||||||
f"{col(rp, 'floor_unseen'):10.5f}")
|
|
||||||
|
|
||||||
for name, other in (("table", tb), ("table+interp", it)):
|
|
||||||
m, se, won, n = paired(rp, other)
|
|
||||||
verdict = ("inside one se of zero" if abs(m) < se
|
|
||||||
else ("rp better" if m > 0 else "*** rp WORSE ***"))
|
|
||||||
print(f"\n {name:12s} - rp: {m:+.5f} +/- {se:.5f} {won}/{n} seeds {verdict}")
|
|
||||||
if w10:
|
|
||||||
m, se, won, n = paired(rp, w10)
|
|
||||||
print(f" omega=10 - rp: {m:+.5f} +/- {se:.5f} {won}/{n} seeds")
|
|
||||||
|
|
||||||
r = [rp[s]["unseen"] / rp[s]["seen"] for s in sorted(rp)]
|
|
||||||
print(f"\n rp unseen/seen mean {st.mean(r):.2f} per seed {' '.join(f'{x:.2f}' for x in r)}")
|
|
||||||
-129
@@ -1,129 +0,0 @@
|
|||||||
"""Information ceilings for the particles domain. Task 7.
|
|
||||||
|
|
||||||
Fits, by least squares over a rolled-out world, the best predictor of the form
|
|
||||||
|
|
||||||
d_i = a[offset(i)] + sum_j c[key(i,j)] * dt * kern(r_ij) * r_ij
|
|
||||||
|
|
||||||
under several information sets. The radial kernel is handed to the fit exactly, so
|
|
||||||
each row is the best a predictor with that information can do *within this family*.
|
|
||||||
|
|
||||||
SCOPE. The family is linear in the messages. The real RP applies tanh on top of the
|
|
||||||
aggregate and the GRP adds per-entity state, so these numbers are NOT a bound on what
|
|
||||||
the trained architecture can reach -- a memoryless rp_only run with the regime frozen
|
|
||||||
gets below rows C and D. Read the table as a map of where the information sits, not
|
|
||||||
as a proof about the model.
|
|
||||||
|
|
||||||
Row A is the self-check: given (regime, t_i, t_j) the family spans the dynamics
|
|
||||||
exactly, so its deterministic residual must be ~0 and its residual against the noisy
|
|
||||||
target must equal noise**2.
|
|
||||||
|
|
||||||
uv run python ceilings.py [steps] [seeds] [t_min,t_max]
|
|
||||||
"""
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import statistics
|
|
||||||
import sys
|
|
||||||
|
|
||||||
import torch
|
|
||||||
|
|
||||||
from particles import ParticleConfig, ParticleWorld, wrapped_diff
|
|
||||||
|
|
||||||
|
|
||||||
def collect(cfg: ParticleConfig, steps: int) -> list[tuple]:
|
|
||||||
"""Roll the world out, recovering the deterministic part of each step's target."""
|
|
||||||
w, rows = ParticleWorld(cfg), []
|
|
||||||
for _ in range(steps):
|
|
||||||
coords, types = w.coords.clone(), w.types.clone()
|
|
||||||
obs = w.step()
|
|
||||||
# obs.regime, not w.regime read before step(): step() switches the regime
|
|
||||||
# *before* computing the delta, so the pre-step value is stale on switch steps.
|
|
||||||
r = wrapped_diff(coords)
|
|
||||||
kern = torch.exp(-(r ** 2).sum(-1) / cfg.sigma ** 2)
|
|
||||||
kern.fill_diagonal_(0.0)
|
|
||||||
K = w.regimes[obs.regime][types[:, None], types[None, :]]
|
|
||||||
det = cfg.dt * ((K * kern)[:, :, None] * r).sum(1)
|
|
||||||
rows.append((r, kern, types, obs.regime, det, obs.target))
|
|
||||||
return rows
|
|
||||||
|
|
||||||
|
|
||||||
def design(rows: list[tuple], cfg: ParticleConfig, key, offset) -> tuple[torch.Tensor, ...]:
|
|
||||||
"""key(types, regime) -> (N,N) coefficient index; offset(types, regime) -> (N,) index."""
|
|
||||||
n_key = max(key(t, g).max().item() for _, _, t, g, _, _ in rows) + 1
|
|
||||||
n_off = max(offset(t, g).max().item() for _, _, t, g, _, _ in rows) + 1
|
|
||||||
X, Y, Yn = [], [], []
|
|
||||||
for r, kern, types, regime, det, target in rows:
|
|
||||||
w = cfg.dt * kern[:, :, None] * r # (N,N,2)
|
|
||||||
idx = key(types, regime)
|
|
||||||
cols = [(w * (idx == c)[:, :, None]).sum(1) for c in range(n_key)] # each (N,2)
|
|
||||||
oid = offset(types, regime)
|
|
||||||
for c in range(n_off): # a free 2-vector offset per class
|
|
||||||
sel = (oid == c).float()
|
|
||||||
zero = torch.zeros_like(sel)
|
|
||||||
cols += [torch.stack([sel, zero], -1), torch.stack([zero, sel], -1)]
|
|
||||||
X.append(torch.stack(cols, -1).reshape(-1, len(cols)))
|
|
||||||
Y.append(det.reshape(-1))
|
|
||||||
Yn.append(target.reshape(-1))
|
|
||||||
return torch.cat(X).double(), torch.cat(Y).double(), torch.cat(Yn).double()
|
|
||||||
|
|
||||||
|
|
||||||
T = ParticleConfig().n_types
|
|
||||||
|
|
||||||
CEILINGS = [
|
|
||||||
("A perfect: (regime, t_i, t_j)",
|
|
||||||
lambda t, g: (g * T * T + t[:, None] * T + t[None, :]).long(),
|
|
||||||
lambda t, g: torch.zeros_like(t).long()),
|
|
||||||
("B regime-blind, pair-aware (t_i, t_j)",
|
|
||||||
lambda t, g: (t[:, None] * T + t[None, :]).long(),
|
|
||||||
lambda t, g: t.long()),
|
|
||||||
("C regime oracle (regime, t_j)",
|
|
||||||
lambda t, g: (g * T + t[None, :]).expand(len(t), len(t)).long(),
|
|
||||||
lambda t, g: (g * T + t).long()),
|
|
||||||
("D no oracle (t_j)",
|
|
||||||
lambda t, g: t[None, :].expand(len(t), len(t)).long(),
|
|
||||||
lambda t, g: t.long()),
|
|
||||||
]
|
|
||||||
|
|
||||||
|
|
||||||
def ceilings(steps: int = 1200, seeds: tuple[int, ...] = (0, 1, 2),
|
|
||||||
t_min: int | None = None, t_max: int | None = None) -> dict[str, tuple[float, float]]:
|
|
||||||
"""`t_min`/`t_max` override the regime duration; Task 9 Part 3 reads the oracle prize
|
|
||||||
D->C at each duration it sweeps. They are passed to `ParticleConfig` rather than
|
|
||||||
changed in `particles.py`, so every existing caller gets the 40-80 default."""
|
|
||||||
dur = {k: v for k, v in (("t_min", t_min), ("t_max", t_max)) if v is not None}
|
|
||||||
out = {}
|
|
||||||
for label, key, off in CEILINGS:
|
|
||||||
dets, obss = [], []
|
|
||||||
for seed in seeds:
|
|
||||||
cfg = ParticleConfig(seed=seed, **dur)
|
|
||||||
X, Y, Yn = design(collect(cfg, steps), cfg, key, off)
|
|
||||||
pred = (X @ torch.linalg.lstsq(X, Y.unsqueeze(1)).solution).squeeze(1)
|
|
||||||
dets.append(((pred - Y) ** 2).mean().item())
|
|
||||||
obss.append(((pred - Yn) ** 2).mean().item())
|
|
||||||
out[label] = (statistics.fmean(dets), statistics.fmean(obss))
|
|
||||||
return out
|
|
||||||
|
|
||||||
|
|
||||||
def main() -> None:
|
|
||||||
steps = int(sys.argv[1]) if len(sys.argv) > 1 else 1200
|
|
||||||
seeds = tuple(int(s) for s in sys.argv[2].split(",")) if len(sys.argv) > 2 else (0, 1, 2)
|
|
||||||
dur = tuple(int(x) for x in sys.argv[3].split(",")) if len(sys.argv) > 3 else (None, None)
|
|
||||||
cfg = ParticleConfig(**{k: v for k, v in zip(("t_min", "t_max"), dur) if v is not None})
|
|
||||||
res = ceilings(steps, seeds, *dur)
|
|
||||||
print(f"steps={steps} seeds={','.join(map(str, seeds))} noise^2 = {cfg.noise ** 2:.3e}\n")
|
|
||||||
print(f"{'information set':<40}{'MSE(det part)':>15}{'MSE(vs target)':>16}")
|
|
||||||
print("-" * 71)
|
|
||||||
for label, (d, o) in res.items():
|
|
||||||
print(f"{label:<40}{d:>15.3e}{o:>16.3e}")
|
|
||||||
c, d = res["C regime oracle (regime, t_j)"], res["D no oracle (t_j)"]
|
|
||||||
print(f"\noracle prize D->C: {d[0] / c[0]:.2f}x on the deterministic part, "
|
|
||||||
f"{d[1] / c[1]:.2f}x against the noisy target")
|
|
||||||
|
|
||||||
a = res["A perfect: (regime, t_i, t_j)"]
|
|
||||||
assert a[0] < 1e-15, f"row A must span the dynamics exactly, got {a[0]:.3e}"
|
|
||||||
assert abs(a[1] - cfg.noise ** 2) < 0.02 * cfg.noise ** 2, \
|
|
||||||
f"row A vs target must equal noise^2={cfg.noise ** 2:.3e}, got {a[1]:.3e}"
|
|
||||||
print("self-check: row A spans the dynamics and lands on the noise floor.")
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
main()
|
|
||||||
-195
@@ -1,195 +0,0 @@
|
|||||||
"""Move prediction as a distribution over legal destinations, not a regression to their mean.
|
|
||||||
|
|
||||||
`results/chess_move.md` measured the mismatch this file exists to remove. MSE on a displacement
|
|
||||||
vector fits the CONDITIONAL MEAN of the destinations: a knight with five legal squares has a
|
|
||||||
mean pointing at none of them. History shifts the distribution over destinations -- that is what
|
|
||||||
`chess_history.md` measured, +0.034 with a non-linear decoder -- and barely moves the mean, so
|
|
||||||
an MSE readout discards the shape of information history carries. The evidence is direct:
|
|
||||||
putting the piece type into the kernel improved MSE 0.03888 -> 0.03547 and made accuracy
|
|
||||||
*worse*, 0.4144 -> 0.3998. Objective and question pointed in opposite directions.
|
|
||||||
|
|
||||||
So: change the metric, not the baseline. Same target, same chance level (0.3618, uniform among
|
|
||||||
legal), same conditioning. Only the readout changes -- logits over the 15x15 grid of relative
|
|
||||||
offsets, cross-entropy restricted to the legal ones. Still contract A: supervised, no opponent,
|
|
||||||
no reward.
|
|
||||||
|
|
||||||
Offsets rather than absolute squares for the reason `chess_reach.md` gives: the CPPN sees only
|
|
||||||
r_ij, so an entity's representation is translation-invariant and an absolute target is
|
|
||||||
unanswerable by construction.
|
|
||||||
|
|
||||||
`rp_oracle` is the gate, as in every configuration before this one. If handing the model each
|
|
||||||
piece's own past does not pay here either, per-entity history has no job under contract A and
|
|
||||||
the line closes with a number.
|
|
||||||
"""
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import argparse
|
|
||||||
import json
|
|
||||||
import statistics
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
import numpy as np
|
|
||||||
import torch
|
|
||||||
|
|
||||||
from ailed import Affect, Organism, detach_memory
|
|
||||||
from chess_domain import ATTR_DIM, flat_diff, load
|
|
||||||
from chess_reach import GRID
|
|
||||||
|
|
||||||
|
|
||||||
def n_params(memory: bool, hidden: int, cppn_hidden: int, n_edge: int) -> int:
|
|
||||||
org = Organism(ATTR_DIM, 2, GRID, n_edge_types=n_edge, hidden_dim=hidden,
|
|
||||||
cppn_hidden=cppn_hidden, memory=memory)
|
|
||||||
return sum(q.numel() for q in org.parameters())
|
|
||||||
|
|
||||||
|
|
||||||
def match_width(hidden: int, cppn_hidden: int, n_edge: int) -> int:
|
|
||||||
"""The memoryless width matching the gated model's parameter count, AT THIS TARGET DIM.
|
|
||||||
|
|
||||||
With 225 outputs the readout dominates, so a width matched at target_dim=2 is wrong by
|
|
||||||
several times over. `frozen.md` §1d is why the match happens at all.
|
|
||||||
"""
|
|
||||||
target = n_params(True, hidden, cppn_hidden, n_edge)
|
|
||||||
return min(range(hidden, 8 * hidden),
|
|
||||||
key=lambda h: abs(n_params(False, h, cppn_hidden, n_edge) - target))
|
|
||||||
|
|
||||||
|
|
||||||
def offsets(dests: np.ndarray) -> np.ndarray:
|
|
||||||
"""(L,2) scaled displacements -> (L,) cells of the 15x15 offset grid."""
|
|
||||||
d = np.rint(dests * 7).astype(int)
|
|
||||||
return (d[:, 1] + 7) * 15 + (d[:, 0] + 7)
|
|
||||||
|
|
||||||
|
|
||||||
def _stream(org, game, opt, bptt: int, oracle: bool, edges: bool, nostate: bool = False):
|
|
||||||
memory: dict[int, torch.Tensor] = {}
|
|
||||||
pending, losses, hits, chance = [], [], [], []
|
|
||||||
zero = Affect().axes
|
|
||||||
with torch.set_grad_enabled(opt is not None):
|
|
||||||
for ply in game:
|
|
||||||
n = len(ply.ids)
|
|
||||||
attrs = np.concatenate([ply.attrs, ply.past], 1) if oracle else ply.attrs
|
|
||||||
et = None
|
|
||||||
if edges:
|
|
||||||
t = torch.from_numpy(ply.attrs[:, :6]).argmax(1)
|
|
||||||
et = t[:, None].expand(n, n).contiguous()
|
|
||||||
pred, memory = org(torch.from_numpy(attrs), flat_diff(torch.from_numpy(ply.coords)),
|
|
||||||
ply.ids, zero, {} if nostate else memory, edge_types=et)
|
|
||||||
legal = torch.from_numpy(offsets(ply.dests))
|
|
||||||
logits = pred[ply.mover][legal] # only the legal destinations
|
|
||||||
loss = torch.nn.functional.cross_entropy(logits[None, :],
|
|
||||||
torch.tensor([ply.true_dest]))
|
|
||||||
losses.append(loss.item())
|
|
||||||
hits.append(float(int(logits.detach().argmax()) == ply.true_dest))
|
|
||||||
chance.append(1.0 / len(legal))
|
|
||||||
if opt is None:
|
|
||||||
continue
|
|
||||||
pending.append(loss)
|
|
||||||
if len(pending) == bptt:
|
|
||||||
opt.zero_grad(); torch.stack(pending).mean().backward(); opt.step()
|
|
||||||
pending = []; memory = detach_memory(memory)
|
|
||||||
if opt is not None and pending:
|
|
||||||
opt.zero_grad(); torch.stack(pending).mean().backward(); opt.step()
|
|
||||||
return losses, hits, chance
|
|
||||||
|
|
||||||
|
|
||||||
def run(games, memory: bool, hidden: int, cppn_hidden: int, seed: int, lr: float, bptt: int,
|
|
||||||
oracle: bool, edges: bool, nostate: bool = False) -> dict:
|
|
||||||
torch.manual_seed(seed)
|
|
||||||
attr_dim = ATTR_DIM + (games[0][0].past.shape[1] if oracle else 0)
|
|
||||||
org = Organism(attr_dim, 2, GRID, n_edge_types=6 if edges else 1, hidden_dim=hidden,
|
|
||||||
cppn_hidden=cppn_hidden, kappa=0.0, memory=memory)
|
|
||||||
opt = torch.optim.Adam(org.parameters(), lr=lr)
|
|
||||||
order = np.random.default_rng(seed).permutation(len(games))
|
|
||||||
cut = max(1, len(games) // 4)
|
|
||||||
for gi in order[cut:]:
|
|
||||||
_stream(org, games[gi], opt, bptt, oracle, edges, nostate)
|
|
||||||
loss, hits, chance = [], [], []
|
|
||||||
for gi in order[:cut]:
|
|
||||||
l, h, c = _stream(org, games[gi], None, bptt, oracle, edges, nostate)
|
|
||||||
loss += l; hits += h; chance += c
|
|
||||||
return dict(seed=seed, memory=memory, oracle=oracle, nostate=nostate, hidden=hidden,
|
|
||||||
params=sum(p.numel() for p in org.parameters()),
|
|
||||||
loss=statistics.fmean(loss), acc=statistics.fmean(hits),
|
|
||||||
chance=statistics.fmean(chance))
|
|
||||||
|
|
||||||
|
|
||||||
def run_constant(games, seed: int) -> dict:
|
|
||||||
"""The floor: rank offsets by how often a move uses them. Blind to piece and position."""
|
|
||||||
order = np.random.default_rng(seed).permutation(len(games))
|
|
||||||
cut = max(1, len(games) // 4)
|
|
||||||
marg = np.zeros(GRID)
|
|
||||||
for gi in order[cut:]:
|
|
||||||
for ply in games[gi]:
|
|
||||||
marg[offsets(ply.dests[ply.true_dest][None, :])[0]] += 1.0
|
|
||||||
hits, chance = [], []
|
|
||||||
for gi in order[:cut]:
|
|
||||||
for ply in games[gi]:
|
|
||||||
hits.append(float(int(marg[offsets(ply.dests)].argmax()) == ply.true_dest))
|
|
||||||
chance.append(1.0 / len(ply.dests))
|
|
||||||
return dict(seed=seed, memory=False, oracle=False, hidden=0, params=GRID,
|
|
||||||
loss=float("nan"), acc=statistics.fmean(hits),
|
|
||||||
chance=statistics.fmean(chance))
|
|
||||||
|
|
||||||
|
|
||||||
def main() -> None:
|
|
||||||
ap = argparse.ArgumentParser()
|
|
||||||
ap.add_argument("--games", type=int, default=400)
|
|
||||||
ap.add_argument("--hist", type=int, default=3)
|
|
||||||
ap.add_argument("--seeds", default="0,1,2,3,4,5,6,7")
|
|
||||||
ap.add_argument("--hidden", type=int, default=32)
|
|
||||||
ap.add_argument("--cppn-hidden", type=int, default=32)
|
|
||||||
ap.add_argument("--lr", type=float, default=1e-3)
|
|
||||||
ap.add_argument("--bptt", type=int, default=20)
|
|
||||||
ap.add_argument("--edges", default="type", choices=("none", "type"))
|
|
||||||
ap.add_argument("--arms", default="constant,rp,grp,rp_wide,rp_oracle")
|
|
||||||
ap.add_argument("--out", default="results/chess_dist.json")
|
|
||||||
a = ap.parse_args()
|
|
||||||
|
|
||||||
games = load(a.games, a.hist)
|
|
||||||
edges = a.edges == "type"
|
|
||||||
wide = match_width(a.hidden, a.cppn_hidden, 6 if edges else 1)
|
|
||||||
all_arms = {"constant": None, "rp": (False, a.hidden, False), "grp": (True, a.hidden, False),
|
|
||||||
"rp_wide": (False, wide, False),
|
|
||||||
# the oracle sits at the SAME width as `rp`: same architecture, one of them
|
|
||||||
# handed the past. Anything else confounds the ceiling with capacity.
|
|
||||||
"rp_oracle": (False, a.hidden, True),
|
|
||||||
# the control that separates the state from the gate: the SAME architecture and
|
|
||||||
# the SAME parameters, handed an empty memory every ply. In the particles work
|
|
||||||
# this is what turned "memory helps" into "the gated nonlinearity helps"
|
|
||||||
# (results/frozen.md). A GRP gain is not a memory result until this arm is run.
|
|
||||||
"grp_nostate": (True, a.hidden, False)}
|
|
||||||
arms = {k: all_arms[k] for k in a.arms.split(",")}
|
|
||||||
print(f"{len(games)} games, {sum(len(g) for g in games)} plies, edges={a.edges}, "
|
|
||||||
f"width-matched memoryless arm at hidden={wide}\n")
|
|
||||||
|
|
||||||
results = []
|
|
||||||
for name, spec in arms.items():
|
|
||||||
for seed in (int(s) for s in a.seeds.split(",")):
|
|
||||||
r = (run_constant(games, seed) if spec is None else
|
|
||||||
run(games, spec[0], spec[1], a.cppn_hidden, seed, a.lr, a.bptt, spec[2],
|
|
||||||
edges, name == "grp_nostate")) | {"arm": name}
|
|
||||||
print(f"{name:<10} seed={seed} params={r['params']:<6} "
|
|
||||||
f"loss={r['loss']:.4f} acc={r['acc']:.4f}", flush=True)
|
|
||||||
results.append(r)
|
|
||||||
Path(a.out).parent.mkdir(parents=True, exist_ok=True)
|
|
||||||
Path(a.out).write_text(json.dumps(results, indent=1))
|
|
||||||
|
|
||||||
by = {n: [r for r in results if r["arm"] == n] for n in arms}
|
|
||||||
print(f"\n{'arm':<10}{'params':>8}{'loss':>9}{'acc':>9}{'chance':>9}")
|
|
||||||
print("-" * 45)
|
|
||||||
for n, rs in by.items():
|
|
||||||
print(f"{n:<10}{rs[0]['params']:>8}{statistics.fmean(r['loss'] for r in rs):>9.4f}"
|
|
||||||
f"{statistics.fmean(r['acc'] for r in rs):>9.4f}"
|
|
||||||
f"{statistics.fmean(r['chance'] for r in rs):>9.4f}")
|
|
||||||
for top, base in (("rp_oracle", "rp"), ("grp", "rp_wide"), ("grp", "rp"),
|
|
||||||
("grp", "grp_nostate"), ("grp_nostate", "rp_wide")):
|
|
||||||
if top not in by or base not in by:
|
|
||||||
continue
|
|
||||||
d = [x["acc"] - y["acc"] for x, y in zip(by[top], by[base])]
|
|
||||||
se = statistics.stdev(d) / len(d) ** 0.5 if len(d) > 1 else float("nan")
|
|
||||||
print(f"\n{top} - {base}: {statistics.fmean(d):+.4f} +/- {se:.4f} (paired se), "
|
|
||||||
f"{sum(x > 0 for x in d)}/{len(d)} seeds -- "
|
|
||||||
f"{'ambiguous' if abs(statistics.fmean(d)) < se else 'a direction'}")
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
main()
|
|
||||||
-327
@@ -1,327 +0,0 @@
|
|||||||
"""Chess under contract A: which piece moves is given, where it goes is predicted.
|
|
||||||
|
|
||||||
Spec §2, contract A, on the chess instance. What justified coming here is
|
|
||||||
`results/chess_history.md`: a piece's own past predicts its next square beyond the board,
|
|
||||||
+0.034 with a non-linear decoder. That measured headroom is what this file spends.
|
|
||||||
|
|
||||||
Two design decisions, both load-bearing.
|
|
||||||
|
|
||||||
**The target is the mover's displacement, and the loss is masked to the mover.** Exactly one
|
|
||||||
piece moves per ply, so the spec's literal default -- every entity's displacement -- is 31/32
|
|
||||||
zeros and the constant predictor "nobody moves" wins. That leaves a mechanism no job, which is
|
|
||||||
the shape of four nulls in the predecessor project. The cost of the fix is that the model is
|
|
||||||
told *which* piece moves. It is not told where it goes, and this is the same conditioning the
|
|
||||||
probe measured under, so the probe's number is the ceiling on this task and not on some other.
|
|
||||||
|
|
||||||
**Affect is held neutral.** psi = (0, 0), kappa = 0, so the only thing separating the arms is
|
|
||||||
per-entity memory. `--affect stream` runs the real EMA chain instead; it exists so the neutral
|
|
||||||
default is a choice rather than an absence.
|
|
||||||
|
|
||||||
There is no regime switch in chess. A1 -- arousal opens the gate after an unannounced change --
|
|
||||||
has no analogue here and is not tested by this file.
|
|
||||||
"""
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import argparse
|
|
||||||
import json
|
|
||||||
import statistics
|
|
||||||
from dataclasses import dataclass
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
import chess
|
|
||||||
import chess.pgn
|
|
||||||
import numpy as np
|
|
||||||
import torch
|
|
||||||
|
|
||||||
from ailed import Affect, AffectConfig, Organism, detach_memory, update
|
|
||||||
|
|
||||||
PGN = "/Users/chrnx/workspace/ailed/model/data/slice.pgn"
|
|
||||||
ATTR_DIM = 8 # piece type (6), colour (1), "this is the one that moves" (1)
|
|
||||||
ORACLES = ("none", "history") # `history` hands each entity its own past, the thing memory
|
|
||||||
# would have to learn to carry. Opt-in, and it only adds columns.
|
|
||||||
SCALE = 7.0 # file/rank -> [0,1], so a relation lands in [-1,1] like the torus does
|
|
||||||
|
|
||||||
|
|
||||||
def flat_diff(coords: torch.Tensor) -> torch.Tensor:
|
|
||||||
"""r_ij = c_j - c_i. Chess is flat: no wrap, unlike `particles.wrapped_diff`."""
|
|
||||||
return coords[None, :, :] - coords[:, None, :]
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
|
||||||
class Ply:
|
|
||||||
ids: list[int] # stable piece ids, the row order of everything below
|
|
||||||
attrs: np.ndarray # (N, ATTR_DIM)
|
|
||||||
coords: np.ndarray # (N, 2) file, rank, scaled
|
|
||||||
mover: int # row index of the piece that moves
|
|
||||||
target: np.ndarray # (2,) that piece's displacement
|
|
||||||
dests: np.ndarray # (L, 2) displacement of every legal move from its square
|
|
||||||
true_dest: int # index into dests
|
|
||||||
past: np.ndarray # (N, 2*hist) each entity's previous squares, as displacements
|
|
||||||
mask: np.ndarray # (N, N) the attack/defend graph, symmetric, self-loops on
|
|
||||||
reach: np.ndarray # (N,) each entity's attack set as a bitboard, for chess_reach.py
|
|
||||||
|
|
||||||
|
|
||||||
def advance_ids(board: chess.Board, move: chess.Move, piece: chess.Piece,
|
|
||||||
id_at: dict[int, int]) -> None:
|
|
||||||
"""Follow piece identity across a move, so "this knight" means the same knight later.
|
|
||||||
|
|
||||||
Castling moves the rook too; en passant removes a pawn from a square the mover never
|
|
||||||
touches; promotion keeps the identity and changes only the type.
|
|
||||||
|
|
||||||
ponytail: this repeats the bookkeeping inside `chess_history.py` rather than importing it.
|
|
||||||
That file is a committed measurement and is left untouched; the two must agree, and
|
|
||||||
`plies()` asserts the result stays in sync with the board either way.
|
|
||||||
"""
|
|
||||||
if board.is_en_passant(move):
|
|
||||||
id_at.pop(move.to_square + (-8 if piece.color == chess.WHITE else 8), None)
|
|
||||||
id_at.pop(move.to_square, None) # a normal capture
|
|
||||||
id_at[move.to_square] = id_at.pop(move.from_square, move.from_square)
|
|
||||||
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)
|
|
||||||
|
|
||||||
|
|
||||||
def plies(game: chess.pgn.Game, hist: int = 3) -> list[Ply]:
|
|
||||||
board = game.board()
|
|
||||||
id_at = {sq: sq for sq in chess.SQUARES if board.piece_at(sq)}
|
|
||||||
seen: dict[int, list[int]] = {}
|
|
||||||
out: list[Ply] = []
|
|
||||||
for move in game.mainline_moves():
|
|
||||||
piece = board.piece_at(move.from_square)
|
|
||||||
if piece is None:
|
|
||||||
break
|
|
||||||
# the identity map must name exactly the occupied squares, or a memory slot is
|
|
||||||
# following the wrong piece and every number downstream is meaningless
|
|
||||||
assert id_at.keys() == board.piece_map().keys(), "identity map drifted from the board"
|
|
||||||
squares = sorted(id_at)
|
|
||||||
attrs = np.zeros((len(squares), ATTR_DIM), dtype=np.float32)
|
|
||||||
coords = np.zeros((len(squares), 2), dtype=np.float32)
|
|
||||||
for k, sq in enumerate(squares):
|
|
||||||
p = board.piece_at(sq)
|
|
||||||
attrs[k, p.piece_type - 1] = 1.0
|
|
||||||
attrs[k, 6] = float(p.color == chess.WHITE)
|
|
||||||
coords[k] = (chess.square_file(sq) / SCALE, chess.square_rank(sq) / SCALE)
|
|
||||||
mover = squares.index(move.from_square)
|
|
||||||
attrs[mover, 7] = 1.0
|
|
||||||
|
|
||||||
# the spec's optional adjacency input (§2), which chess actually has: i sees j when
|
|
||||||
# either attacks the other's square. With the all-ones default an entity's own
|
|
||||||
# attributes reach it only through the diagonal term and are divided by deg ~= 30.
|
|
||||||
sq = np.array(squares, dtype=np.uint64)
|
|
||||||
bb = np.array([int(board.attacks(int(t))) for t in squares], dtype=np.uint64)
|
|
||||||
att = ((bb[:, None] >> sq[None, :]) & np.uint64(1)).astype(np.float32)
|
|
||||||
mask = np.maximum(att, att.T)
|
|
||||||
np.fill_diagonal(mask, 1.0)
|
|
||||||
|
|
||||||
# each entity's own past, relative to where it stands now. Absent history is zero,
|
|
||||||
# which is also "I am where I was" -- the ambiguity costs the oracle, never the model.
|
|
||||||
past = np.zeros((len(squares), 2 * hist), dtype=np.float32)
|
|
||||||
for k, sq in enumerate(squares):
|
|
||||||
for j, old in enumerate(reversed(seen.get(id_at[sq], [])[-hist:])):
|
|
||||||
past[k, 2 * j] = (chess.square_file(old) - chess.square_file(sq)) / SCALE
|
|
||||||
past[k, 2 * j + 1] = (chess.square_rank(old) - chess.square_rank(sq)) / SCALE
|
|
||||||
|
|
||||||
# every legal destination for that piece, as a displacement; promotions collapse
|
|
||||||
legal = list(dict.fromkeys(m.to_square for m in board.legal_moves
|
|
||||||
if m.from_square == move.from_square))
|
|
||||||
dests = np.array([[(chess.square_file(t) - chess.square_file(move.from_square)) / SCALE,
|
|
||||||
(chess.square_rank(t) - chess.square_rank(move.from_square)) / SCALE]
|
|
||||||
for t in legal], dtype=np.float32)
|
|
||||||
j = legal.index(move.to_square)
|
|
||||||
out.append(Ply([id_at[s] for s in squares], attrs, coords, mover, dests[j], dests, j,
|
|
||||||
past, mask, bb.copy()))
|
|
||||||
|
|
||||||
seen.setdefault(id_at[move.from_square], []).append(move.from_square)
|
|
||||||
advance_ids(board, move, piece, id_at)
|
|
||||||
board.push(move)
|
|
||||||
return out
|
|
||||||
|
|
||||||
|
|
||||||
def load(n_games: int, hist: int = 3, min_plies: int = 20) -> list[list[Ply]]:
|
|
||||||
games: list[list[Ply]] = []
|
|
||||||
with open(PGN, encoding="utf-8", errors="replace") as fh:
|
|
||||||
while len(games) < n_games:
|
|
||||||
g = chess.pgn.read_game(fh)
|
|
||||||
if g is None:
|
|
||||||
break
|
|
||||||
p = plies(g, hist)
|
|
||||||
if len(p) >= min_plies:
|
|
||||||
games.append(p)
|
|
||||||
return games
|
|
||||||
|
|
||||||
|
|
||||||
def n_params(memory: bool, hidden: int, cppn_hidden: int, attr_dim: int = ATTR_DIM,
|
|
||||||
n_edge: int = 1) -> int:
|
|
||||||
org = Organism(attr_dim, 2, 2, n_edge_types=n_edge, hidden_dim=hidden,
|
|
||||||
cppn_hidden=cppn_hidden, memory=memory)
|
|
||||||
return sum(p.numel() for p in org.parameters())
|
|
||||||
|
|
||||||
|
|
||||||
def match_width(hidden: int, cppn_hidden: int, n_edge: int = 1) -> int:
|
|
||||||
"""The memoryless width whose parameter count lands nearest the gated model's.
|
|
||||||
|
|
||||||
`rp_only` at 1442 against `grp_k0` at 5602 is confounded 3.9x and is not a memory
|
|
||||||
result (`results/frozen.md` §1d). This is how that confound is removed here.
|
|
||||||
"""
|
|
||||||
target = n_params(True, hidden, cppn_hidden, n_edge=n_edge)
|
|
||||||
return min(range(hidden, 8 * hidden),
|
|
||||||
key=lambda h: abs(n_params(False, h, cppn_hidden, n_edge=n_edge) - target))
|
|
||||||
|
|
||||||
|
|
||||||
def _stream(org: Organism, game: list[Ply], affect: Affect, acfg: AffectConfig,
|
|
||||||
opt: torch.optim.Optimizer | None, bptt: int, use_affect: bool,
|
|
||||||
oracle: bool, adjacency: bool, edges: bool):
|
|
||||||
"""One game as one continuous stream. Memory starts empty: new game, new pieces."""
|
|
||||||
memory: dict[int, torch.Tensor] = {}
|
|
||||||
pending: list[torch.Tensor] = []
|
|
||||||
losses, hits, chance = [], [], []
|
|
||||||
with torch.set_grad_enabled(opt is not None):
|
|
||||||
for ply in game:
|
|
||||||
coords = torch.from_numpy(ply.coords)
|
|
||||||
attrs = np.concatenate([ply.attrs, ply.past], 1) if oracle else ply.attrs
|
|
||||||
# the receiving piece's type, into the CPPN's own channel. Without this the kernel
|
|
||||||
# is one geometry function shared by all six types -- see results/chess_reach.md,
|
|
||||||
# where that costs the knight's L entirely.
|
|
||||||
et = None
|
|
||||||
if edges:
|
|
||||||
t = torch.from_numpy(ply.attrs[:, :6]).argmax(1)
|
|
||||||
et = t[:, None].expand(len(ply.ids), len(ply.ids)).contiguous()
|
|
||||||
pred, memory = org(torch.from_numpy(attrs), flat_diff(coords), ply.ids,
|
|
||||||
affect.axes, memory, edge_types=et,
|
|
||||||
mask=torch.from_numpy(ply.mask) if adjacency else None)
|
|
||||||
p = pred[ply.mover]
|
|
||||||
loss = ((p - torch.from_numpy(ply.target)) ** 2).mean() # masked to the mover
|
|
||||||
if use_affect:
|
|
||||||
affect = update(affect, loss.item(), acfg)
|
|
||||||
losses.append(loss.item())
|
|
||||||
# snap to the nearest legal destination, so the number is comparable to the
|
|
||||||
# accuracies in results/chess_history.md rather than to a raw MSE
|
|
||||||
k = int(((torch.from_numpy(ply.dests) - p.detach()) ** 2).sum(1).argmin())
|
|
||||||
hits.append(float(k == ply.true_dest))
|
|
||||||
chance.append(1.0 / len(ply.dests))
|
|
||||||
if opt is None:
|
|
||||||
continue
|
|
||||||
pending.append(loss)
|
|
||||||
if len(pending) == bptt:
|
|
||||||
opt.zero_grad(); torch.stack(pending).mean().backward(); opt.step()
|
|
||||||
pending = []; memory = detach_memory(memory)
|
|
||||||
if opt is not None and pending:
|
|
||||||
opt.zero_grad(); torch.stack(pending).mean().backward(); opt.step()
|
|
||||||
return affect, losses, hits, chance
|
|
||||||
|
|
||||||
|
|
||||||
def run_constant(games: list[list[Ply]], seed: int) -> dict:
|
|
||||||
"""The floor: predict the mean displacement, ignore everything else.
|
|
||||||
|
|
||||||
Chance levels are measured here, never assumed. If a trained arm sits on this line it
|
|
||||||
learned nothing about the position and the arms cannot be told apart -- which is a fact
|
|
||||||
about the task, not about any mechanism in it.
|
|
||||||
"""
|
|
||||||
order = np.random.default_rng(seed).permutation(len(games))
|
|
||||||
cut = max(1, len(games) // 4)
|
|
||||||
mean = np.mean([p.target for gi in order[cut:] for p in games[gi]], 0)
|
|
||||||
mse, hits, chance = [], [], []
|
|
||||||
for gi in order[:cut]:
|
|
||||||
for ply in games[gi]:
|
|
||||||
mse.append(float(((mean - ply.target) ** 2).mean()))
|
|
||||||
hits.append(float(int(((ply.dests - mean) ** 2).sum(1).argmin()) == ply.true_dest))
|
|
||||||
chance.append(1.0 / len(ply.dests))
|
|
||||||
return dict(seed=seed, hidden=0, memory=False, oracle=False, params=2, plies=len(mse),
|
|
||||||
mse=statistics.fmean(mse), acc=statistics.fmean(hits),
|
|
||||||
chance=statistics.fmean(chance))
|
|
||||||
|
|
||||||
|
|
||||||
def run(games: list[list[Ply]], memory: bool, hidden: int, cppn_hidden: int, seed: int,
|
|
||||||
lr: float, bptt: int, kappa: float, use_affect: bool, oracle: bool = False,
|
|
||||||
adjacency: bool = False, edges: bool = False) -> dict:
|
|
||||||
torch.manual_seed(seed)
|
|
||||||
attr_dim = ATTR_DIM + (games[0][0].past.shape[1] if oracle else 0)
|
|
||||||
org = Organism(attr_dim, 2, 2, n_edge_types=6 if edges else 1, hidden_dim=hidden,
|
|
||||||
cppn_hidden=cppn_hidden, kappa=kappa, memory=memory)
|
|
||||||
opt = torch.optim.Adam(org.parameters(), lr=lr)
|
|
||||||
acfg, affect = AffectConfig(), Affect()
|
|
||||||
|
|
||||||
# split by GAME, never inside one: two positions from one game share almost everything
|
|
||||||
order = np.random.default_rng(seed).permutation(len(games))
|
|
||||||
cut = max(1, len(games) // 4)
|
|
||||||
for gi in order[cut:]:
|
|
||||||
affect, *_ = _stream(org, games[gi], affect, acfg, opt, bptt, use_affect, oracle, adjacency, edges)
|
|
||||||
mse, hits, chance = [], [], []
|
|
||||||
for gi in order[:cut]:
|
|
||||||
affect, l, h, c = _stream(org, games[gi], affect, acfg, None, bptt, use_affect, oracle, adjacency, edges)
|
|
||||||
mse += l; hits += h; chance += c
|
|
||||||
return dict(seed=seed, hidden=hidden, memory=memory, oracle=oracle, mask=adjacency, edges=edges,
|
|
||||||
params=sum(p.numel() for p in org.parameters()), plies=len(mse),
|
|
||||||
mse=statistics.fmean(mse), acc=statistics.fmean(hits),
|
|
||||||
chance=statistics.fmean(chance))
|
|
||||||
|
|
||||||
|
|
||||||
def main() -> None:
|
|
||||||
ap = argparse.ArgumentParser()
|
|
||||||
ap.add_argument("--games", type=int, default=400)
|
|
||||||
ap.add_argument("--hist", type=int, default=3, help="past squares the oracle hands over")
|
|
||||||
ap.add_argument("--seeds", default="0,1,2,3,4,5,6,7")
|
|
||||||
ap.add_argument("--hidden", type=int, default=32)
|
|
||||||
ap.add_argument("--cppn-hidden", type=int, default=32)
|
|
||||||
ap.add_argument("--lr", type=float, default=1e-3)
|
|
||||||
ap.add_argument("--bptt", type=int, default=20)
|
|
||||||
ap.add_argument("--kappa", type=float, default=0.0)
|
|
||||||
ap.add_argument("--affect", default="neutral", choices=("neutral", "stream"),
|
|
||||||
help="neutral holds psi at (0,0); stream runs the real EMA chain")
|
|
||||||
ap.add_argument("--arms", default="rp,grp,rp_wide,rp_oracle")
|
|
||||||
ap.add_argument("--edges", default="none", choices=("none", "type"),
|
|
||||||
help="type puts the receiving piece's type into e_ij, the CPPN's channel")
|
|
||||||
ap.add_argument("--mask", default="all", choices=("all", "attack"),
|
|
||||||
help="all is the spec default; attack is the domain's own adjacency")
|
|
||||||
ap.add_argument("--out", default="results/chess.json")
|
|
||||||
a = ap.parse_args()
|
|
||||||
|
|
||||||
games = load(a.games, a.hist)
|
|
||||||
wide = match_width(a.hidden, a.cppn_hidden, 6 if a.edges == 'type' else 1)
|
|
||||||
# rp_oracle is the ceiling, not a competitor: the memoryless model is HANDED each piece's
|
|
||||||
# own past, which is exactly what memory would have to learn to carry. If it does not pay,
|
|
||||||
# a memory null here is about the setup and not about memory.
|
|
||||||
all_arms = {"rp": (False, a.hidden, False), "grp": (True, a.hidden, False),
|
|
||||||
"rp_wide": (False, wide, False), "rp_oracle": (False, wide, True),
|
|
||||||
"constant": (False, 0, False)}
|
|
||||||
arms = {k: all_arms[k] for k in a.arms.split(",")}
|
|
||||||
deg = statistics.fmean(float(p.mask.sum(1).mean()) for g in games for p in g)
|
|
||||||
print(f"{len(games)} games, {sum(len(g) for g in games)} plies; "
|
|
||||||
f"width-matched memoryless arm at hidden={wide}; mask={a.mask}, "
|
|
||||||
f"mean degree {deg if a.mask == 'attack' else statistics.fmean(len(p.ids) for g in games for p in g):.1f}\n")
|
|
||||||
|
|
||||||
results = []
|
|
||||||
for name, (mem, h, orc) in arms.items():
|
|
||||||
for seed in (int(s) for s in a.seeds.split(",")):
|
|
||||||
r = (run_constant(games, seed) if name == "constant" else
|
|
||||||
run(games, mem, h, a.cppn_hidden, seed, a.lr, a.bptt, a.kappa,
|
|
||||||
a.affect == "stream", orc, a.mask == "attack",
|
|
||||||
a.edges == "type")) | {"arm": name}
|
|
||||||
print(f"{name:<8} seed={seed} params={r['params']:<6} "
|
|
||||||
f"mse={r['mse']:.5f} acc={r['acc']:.4f}", flush=True)
|
|
||||||
results.append(r)
|
|
||||||
Path(a.out).parent.mkdir(parents=True, exist_ok=True)
|
|
||||||
Path(a.out).write_text(json.dumps(results, indent=1))
|
|
||||||
|
|
||||||
by = {n: [r for r in results if r["arm"] == n] for n in arms}
|
|
||||||
print(f"\n{'arm':<8}{'params':>8}{'mse':>10}{'acc':>9}{'chance':>9}")
|
|
||||||
print("-" * 44)
|
|
||||||
for n, rs in by.items():
|
|
||||||
print(f"{n:<8}{rs[0]['params']:>8}{statistics.fmean(r['mse'] for r in rs):>10.5f}"
|
|
||||||
f"{statistics.fmean(r['acc'] for r in rs):>9.4f}"
|
|
||||||
f"{statistics.fmean(r['chance'] for r in rs):>9.4f}")
|
|
||||||
for top, base in (("grp", "rp"), ("grp", "rp_wide"), ("rp_oracle", "rp_wide")):
|
|
||||||
if top not in by or base not in by:
|
|
||||||
continue
|
|
||||||
d = [x["acc"] - y["acc"] for x, y in zip(by[top], by[base])]
|
|
||||||
se = statistics.stdev(d) / len(d) ** 0.5 if len(d) > 1 else float("nan")
|
|
||||||
verdict = "ambiguous" if abs(statistics.fmean(d)) < se else "a direction"
|
|
||||||
print(f"\n{top} - {base}: {statistics.fmean(d):+.4f} +/- {se:.4f} (paired se), "
|
|
||||||
f"{sum(x > 0 for x in d)}/{len(d)} seeds -- {verdict}")
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
main()
|
|
||||||
@@ -1,203 +0,0 @@
|
|||||||
"""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_ridge(Xtr, ytr, Xte, yte, l2: float = 1.0):
|
|
||||||
"""Ridge onto one-hot targets, argmax at test."""
|
|
||||||
Y = np.zeros((len(ytr), 64), 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 fit_mlp(Xtr, ytr, Xte, yte, hidden: int = 128, epochs: int = 12, bs: int = 512):
|
|
||||||
"""A 2xN ReLU net on the same features.
|
|
||||||
|
|
||||||
Task 11 is why this arm exists: on the particles domain a linear decoder read 0.23
|
|
||||||
where an MLP read 0.83 on identical features, so a linear null there would have been
|
|
||||||
wrong by 0.6 in accuracy. A linear-only null here would inherit that objection.
|
|
||||||
"""
|
|
||||||
import torch
|
|
||||||
g = torch.Generator().manual_seed(0)
|
|
||||||
Xtr_t = torch.from_numpy(Xtr); ytr_t = torch.from_numpy(ytr).long()
|
|
||||||
net = torch.nn.Sequential(
|
|
||||||
torch.nn.Linear(Xtr.shape[1], hidden), torch.nn.ReLU(),
|
|
||||||
torch.nn.Linear(hidden, hidden), torch.nn.ReLU(),
|
|
||||||
torch.nn.Linear(hidden, 64))
|
|
||||||
opt = torch.optim.Adam(net.parameters(), lr=1e-3)
|
|
||||||
n = len(ytr_t)
|
|
||||||
for _ in range(epochs):
|
|
||||||
perm = torch.randperm(n, generator=g)
|
|
||||||
for i in range(0, n, bs):
|
|
||||||
idx = perm[i:i + bs]
|
|
||||||
opt.zero_grad()
|
|
||||||
torch.nn.functional.cross_entropy(net(Xtr_t[idx]), ytr_t[idx]).backward()
|
|
||||||
opt.step()
|
|
||||||
with torch.no_grad():
|
|
||||||
pred = net(torch.from_numpy(Xte)).argmax(1).numpy()
|
|
||||||
return float((pred == yte).mean())
|
|
||||||
|
|
||||||
|
|
||||||
FITS = {"ridge": fit_ridge, "mlp": fit_mlp}
|
|
||||||
|
|
||||||
|
|
||||||
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("--estimator", default="ridge", choices=sorted(FITS))
|
|
||||||
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")
|
|
||||||
|
|
||||||
fit = FITS[a.estimator]
|
|
||||||
gains = []
|
|
||||||
print(f"estimator: {a.estimator}\n")
|
|
||||||
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(A[tr], y[tr], A[te], y[te])
|
|
||||||
acc_b = fit(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(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()
|
|
||||||
-307
@@ -1,307 +0,0 @@
|
|||||||
"""Does the organism learn how a piece moves? Spec §3: the kernel is a function of geometry.
|
|
||||||
|
|
||||||
The move-prediction task in `chess_domain.py` never asks this. It hands legality to the model
|
|
||||||
for free at readout time -- the prediction is snapped to the nearest legal destination -- so
|
|
||||||
the model is never scored on knowing that a knight goes in an L. Its target also mixes what is
|
|
||||||
legal with what a human chose, and move quality is not controlled. This file asks the first
|
|
||||||
question instead: given the board, which squares can each piece reach?
|
|
||||||
|
|
||||||
Target: `board.attacks(square)` for every live piece, expressed as a 15x15 grid of RELATIVE
|
|
||||||
offsets rather than 64 absolute squares. That is not a convenience -- the CPPN sees only
|
|
||||||
`r_ij`, so an entity's representation is translation-invariant and cannot know which absolute
|
|
||||||
square it stands on. An absolute target is unanswerable by construction. In offset space the
|
|
||||||
question is the one worth asking: a knight's L is eight cells, a bishop's is four rays.
|
|
||||||
|
|
||||||
Deterministic, present-determined, same definition for all six types. The pawn caveat is real
|
|
||||||
and stated rather than hidden: `attacks` is the two diagonals, not the forward push, so for
|
|
||||||
pawns this measures the capture geometry only.
|
|
||||||
|
|
||||||
Two things this design is built to separate:
|
|
||||||
|
|
||||||
**Does the piece's type reach the kernel?** The CPPN sees `[r_ij ‖ onehot(e_ij) ‖ context]`.
|
|
||||||
The piece type is NOT in there -- it lives in `attrs`, which enters through `feat` and only
|
|
||||||
meets the kernel as an elementwise product. So the geometry function is shared across all six
|
|
||||||
types. `--edges type` puts the receiving piece's type into `e_ij`, which is the spec's own
|
|
||||||
sanctioned channel, and makes the kernel genuinely type-conditional: a knight-kernel and a
|
|
||||||
bishop-kernel rather than one kernel scaled by a type vector.
|
|
||||||
|
|
||||||
**Memory is the control here, not the hypothesis.** Reachability is fully determined by the
|
|
||||||
present -- type, square, blockers. This is the redundant case, so memory SHOULD buy nothing.
|
|
||||||
An arm that shows no memory gain here is the instrument working, not a null about memory.
|
|
||||||
"""
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import argparse
|
|
||||||
import json
|
|
||||||
import statistics
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
import chess
|
|
||||||
import numpy as np
|
|
||||||
import torch
|
|
||||||
|
|
||||||
from ailed import Affect, Organism, detach_memory
|
|
||||||
from chess_domain import ATTR_DIM, flat_diff, load
|
|
||||||
|
|
||||||
SQ = np.arange(64, dtype=np.uint64)
|
|
||||||
# how many squares each sliding piece would attack from each square on an EMPTY board. A piece
|
|
||||||
# attacking fewer than this is blocked, and a blocked ray is the part of chess geometry that
|
|
||||||
# cannot be memorised as a shape: the knight's L never changes, a rook's does.
|
|
||||||
_EMPTY_BB, _EMPTY = {}, {}
|
|
||||||
for _pt in range(1, 7):
|
|
||||||
for _col in (chess.WHITE, chess.BLACK):
|
|
||||||
for _sq in chess.SQUARES:
|
|
||||||
_b = chess.Board(None)
|
|
||||||
_b.set_piece_at(_sq, chess.Piece(_pt, _col))
|
|
||||||
bb = int(_b.attacks(_sq))
|
|
||||||
_EMPTY_BB[(_pt, _col, _sq)] = bb
|
|
||||||
_EMPTY[(_pt, _sq)] = bin(bb).count("1") # colour-free: only sliding uses this
|
|
||||||
SLIDING = (chess.BISHOP, chess.ROOK, chess.QUEEN)
|
|
||||||
|
|
||||||
|
|
||||||
def blocked_flags(ply) -> np.ndarray:
|
|
||||||
"""(N,) True where a sliding piece attacks fewer squares than it would on an empty board."""
|
|
||||||
t = ply.attrs[:, :6].argmax(1) + 1
|
|
||||||
sq = (np.rint(ply.coords[:, 0] * 7) + 8 * np.rint(ply.coords[:, 1] * 7)).astype(int)
|
|
||||||
have = np.array([bin(int(r)).count("1") for r in ply.reach])
|
|
||||||
full = np.array([_EMPTY.get((int(a), int(b)), -1) for a, b in zip(t, sq)])
|
|
||||||
return (full > 0) & (have < full)
|
|
||||||
GRID = 15 * 15
|
|
||||||
# OFFSET[a, b] is where b sits relative to a, as a cell of the 15x15 displacement grid
|
|
||||||
_f, _r = np.arange(64) % 8, np.arange(64) // 8
|
|
||||||
OFFSET = ((_r[None, :] - _r[:, None] + 7) * 15 + (_f[None, :] - _f[:, None] + 7))
|
|
||||||
|
|
||||||
|
|
||||||
def unpack(ply) -> np.ndarray:
|
|
||||||
"""Each entity's attack set as a (N, 225) multi-hot over relative offsets."""
|
|
||||||
bits = ((ply.reach[:, None] >> SQ[None, :]) & np.uint64(1)).astype(np.float32) # (N,64)
|
|
||||||
sq = (np.rint(ply.coords[:, 0] * 7) + 8 * np.rint(ply.coords[:, 1] * 7)).astype(int)
|
|
||||||
out = np.zeros((len(sq), GRID), dtype=np.float32)
|
|
||||||
np.add.at(out, (np.arange(len(sq))[:, None], OFFSET[sq]), bits)
|
|
||||||
return out
|
|
||||||
|
|
||||||
|
|
||||||
def run_shape(games, seed: int) -> dict:
|
|
||||||
"""The control the blocking question needs: knows the piece's type and its movement RULE,
|
|
||||||
reads nothing from the board.
|
|
||||||
|
|
||||||
Each entity is scored by its EMPTY-BOARD attack set from its own square, ties broken by
|
|
||||||
the marginal frequency of the offset. For a knight or a king this is the exact answer, so
|
|
||||||
the arm is also a ceiling: whatever it scores there is what perfect knowledge of the rule
|
|
||||||
is worth. For a sliding piece it is the un-blocked ray, so beating it means reading
|
|
||||||
occupancy -- knowing how far the ray is actually cut.
|
|
||||||
"""
|
|
||||||
order = np.random.default_rng(seed).permutation(len(games))
|
|
||||||
cut = max(1, len(games) // 4)
|
|
||||||
marg = np.zeros(GRID)
|
|
||||||
for gi in order[cut:]:
|
|
||||||
for ply in games[gi]:
|
|
||||||
marg += unpack(ply).sum(0)
|
|
||||||
marg = marg / max(marg.max(), 1.0)
|
|
||||||
|
|
||||||
prec, chance, tsum, bsum = [], [], np.zeros((6, 2)), np.zeros((6, 2, 2))
|
|
||||||
for gi in order[:cut]:
|
|
||||||
for ply in games[gi]:
|
|
||||||
y = torch.from_numpy(unpack(ply))
|
|
||||||
t = ply.attrs[:, :6].argmax(1) + 1
|
|
||||||
col = ply.attrs[:, 6].astype(bool)
|
|
||||||
sq = (np.rint(ply.coords[:, 0] * 7) + 8 * np.rint(ply.coords[:, 1] * 7)).astype(int)
|
|
||||||
score = np.tile(marg, (len(sq), 1)) * 0.5
|
|
||||||
for k_, (tt, cc, ss) in enumerate(zip(t, col, sq)):
|
|
||||||
bb = _EMPTY_BB[(int(tt), bool(cc), int(ss))]
|
|
||||||
hit_sq = [j for j in range(64) if bb >> j & 1]
|
|
||||||
score[k_, OFFSET[int(ss)][hit_sq]] += 1.0
|
|
||||||
rank = torch.from_numpy((-score).argsort(1).argsort(1))
|
|
||||||
k = y.sum(1); keep = k > 0
|
|
||||||
if keep.any():
|
|
||||||
hit = ((rank < k[:, None]) & (y > 0)).sum(1) / k.clamp(min=1)
|
|
||||||
prec.append(float(hit[keep].mean())); chance.append(float((k[keep] / GRID).mean()))
|
|
||||||
kn = keep.numpy(); tt = ply.attrs[:, :6].argmax(1)[kn]
|
|
||||||
np.add.at(tsum, (tt, 0), hit[keep].numpy()); np.add.at(tsum, (tt, 1), 1.0)
|
|
||||||
bl = blocked_flags(ply)[kn].astype(int)
|
|
||||||
np.add.at(bsum, (tt, bl, 0), hit[keep].numpy())
|
|
||||||
np.add.at(bsum, (tt, bl, 1), 1.0)
|
|
||||||
return dict(seed=seed, memory=False, edges=False, hidden=0, params=0,
|
|
||||||
loss=float("nan"), prec=statistics.fmean(prec), chance=statistics.fmean(chance),
|
|
||||||
by_type=list(tsum[:, 0] / np.maximum(tsum[:, 1], 1)),
|
|
||||||
by_block=(bsum[:, :, 0] / np.maximum(bsum[:, :, 1], 1)).tolist(),
|
|
||||||
n_block=bsum[:, :, 1].tolist())
|
|
||||||
|
|
||||||
|
|
||||||
def _stream(org, game, opt, bptt: int, edges: bool, adjacency: bool):
|
|
||||||
memory: dict[int, torch.Tensor] = {}
|
|
||||||
pending, losses, prec, chance = [], [], [], []
|
|
||||||
# per-type precision is the answer to "does it tell a pawn from a bishop"; the aggregate
|
|
||||||
# can be carried by pawns alone, which are half the pieces on the board
|
|
||||||
by_type = np.zeros((6, 2))
|
|
||||||
by_block = np.zeros((6, 2, 2))
|
|
||||||
zero = Affect().axes
|
|
||||||
with torch.set_grad_enabled(opt is not None):
|
|
||||||
for ply in game:
|
|
||||||
n = len(ply.ids)
|
|
||||||
y = torch.from_numpy(unpack(ply)) # (N,225)
|
|
||||||
et = None
|
|
||||||
if edges: # receiver's type
|
|
||||||
t = torch.from_numpy(ply.attrs[:, :6]).argmax(1)
|
|
||||||
et = t[:, None].expand(n, n).contiguous()
|
|
||||||
pred, memory = org(torch.from_numpy(ply.attrs), flat_diff(torch.from_numpy(ply.coords)),
|
|
||||||
ply.ids, zero, memory, edge_types=et,
|
|
||||||
mask=torch.from_numpy(ply.mask) if adjacency else None)
|
|
||||||
loss = torch.nn.functional.binary_cross_entropy_with_logits(pred, y)
|
|
||||||
losses.append(loss.item())
|
|
||||||
with torch.no_grad():
|
|
||||||
k = y.sum(1)
|
|
||||||
keep = k > 0
|
|
||||||
if keep.any():
|
|
||||||
# precision@k: of the k squares it ranks highest, how many are reachable
|
|
||||||
rank = pred.argsort(1, descending=True).argsort(1)
|
|
||||||
hit = ((rank < k[:, None]) & (y > 0)).sum(1) / k.clamp(min=1)
|
|
||||||
prec.append(float(hit[keep].mean()))
|
|
||||||
chance.append(float((k[keep] / GRID).mean())) # random ranking
|
|
||||||
kn = keep.numpy()
|
|
||||||
tt = ply.attrs[:, :6].argmax(1)[kn]
|
|
||||||
np.add.at(by_type, (tt, 0), hit[keep].numpy())
|
|
||||||
np.add.at(by_type, (tt, 1), 1.0)
|
|
||||||
bl = blocked_flags(ply)[kn].astype(int)
|
|
||||||
np.add.at(by_block, (tt, bl, 0), hit[keep].numpy())
|
|
||||||
np.add.at(by_block, (tt, bl, 1), 1.0)
|
|
||||||
if opt is None:
|
|
||||||
continue
|
|
||||||
pending.append(loss)
|
|
||||||
if len(pending) == bptt:
|
|
||||||
opt.zero_grad(); torch.stack(pending).mean().backward(); opt.step()
|
|
||||||
pending = []; memory = detach_memory(memory)
|
|
||||||
if opt is not None and pending:
|
|
||||||
opt.zero_grad(); torch.stack(pending).mean().backward(); opt.step()
|
|
||||||
return losses, prec, chance, by_type, by_block
|
|
||||||
|
|
||||||
|
|
||||||
def run(games, memory: bool, hidden: int, cppn_hidden: int, seed: int, lr: float, bptt: int,
|
|
||||||
edges: bool, adjacency: bool) -> dict:
|
|
||||||
torch.manual_seed(seed)
|
|
||||||
org = Organism(ATTR_DIM, 2, GRID, n_edge_types=6 if edges else 1, hidden_dim=hidden,
|
|
||||||
cppn_hidden=cppn_hidden, kappa=0.0, memory=memory)
|
|
||||||
opt = torch.optim.Adam(org.parameters(), lr=lr)
|
|
||||||
order = np.random.default_rng(seed).permutation(len(games))
|
|
||||||
cut = max(1, len(games) // 4)
|
|
||||||
for gi in order[cut:]:
|
|
||||||
_stream(org, games[gi], opt, bptt, edges, adjacency)
|
|
||||||
loss, prec, chance, tsum, bsum = [], [], [], np.zeros((6, 2)), np.zeros((6, 2, 2))
|
|
||||||
for gi in order[:cut]:
|
|
||||||
l, p, c, t, b = _stream(org, games[gi], None, bptt, edges, adjacency)
|
|
||||||
loss += l; prec += p; chance += c; tsum += t; bsum += b
|
|
||||||
return dict(seed=seed, memory=memory, edges=edges, hidden=hidden,
|
|
||||||
params=sum(p.numel() for p in org.parameters()),
|
|
||||||
loss=statistics.fmean(loss), prec=statistics.fmean(prec),
|
|
||||||
chance=statistics.fmean(chance),
|
|
||||||
by_type=list(tsum[:, 0] / np.maximum(tsum[:, 1], 1)),
|
|
||||||
by_block=(bsum[:, :, 0] / np.maximum(bsum[:, :, 1], 1)).tolist(),
|
|
||||||
n_block=bsum[:, :, 1].tolist())
|
|
||||||
|
|
||||||
|
|
||||||
def run_constant(games, seed: int) -> dict:
|
|
||||||
"""The floor: every piece moves like the average piece. Type-blind and position-blind.
|
|
||||||
|
|
||||||
This is the control the question needs. Beating it means the model distinguishes a pawn
|
|
||||||
from a bishop; sitting on it means it learned one average movement shape for everything.
|
|
||||||
"""
|
|
||||||
order = np.random.default_rng(seed).permutation(len(games))
|
|
||||||
cut = max(1, len(games) // 4)
|
|
||||||
marg = np.zeros(GRID)
|
|
||||||
for gi in order[cut:]:
|
|
||||||
for ply in games[gi]:
|
|
||||||
marg += unpack(ply).sum(0)
|
|
||||||
rank = torch.from_numpy((-marg).argsort().argsort())
|
|
||||||
prec, chance, tsum, bsum = [], [], np.zeros((6, 2)), np.zeros((6, 2, 2))
|
|
||||||
for gi in order[:cut]:
|
|
||||||
for ply in games[gi]:
|
|
||||||
y = torch.from_numpy(unpack(ply))
|
|
||||||
k = y.sum(1); keep = k > 0
|
|
||||||
if keep.any():
|
|
||||||
hit = ((rank[None, :] < k[:, None]) & (y > 0)).sum(1) / k.clamp(min=1)
|
|
||||||
prec.append(float(hit[keep].mean())); chance.append(float((k[keep] / GRID).mean()))
|
|
||||||
kn = keep.numpy()
|
|
||||||
tt = ply.attrs[:, :6].argmax(1)[kn]
|
|
||||||
np.add.at(tsum, (tt, 0), hit[keep].numpy()); np.add.at(tsum, (tt, 1), 1.0)
|
|
||||||
bl = blocked_flags(ply)[kn].astype(int)
|
|
||||||
np.add.at(bsum, (tt, bl, 0), hit[keep].numpy())
|
|
||||||
np.add.at(bsum, (tt, bl, 1), 1.0)
|
|
||||||
return dict(seed=seed, memory=False, edges=False, hidden=0, params=GRID,
|
|
||||||
loss=float("nan"), prec=statistics.fmean(prec), chance=statistics.fmean(chance),
|
|
||||||
by_type=list(tsum[:, 0] / np.maximum(tsum[:, 1], 1)),
|
|
||||||
by_block=(bsum[:, :, 0] / np.maximum(bsum[:, :, 1], 1)).tolist(),
|
|
||||||
n_block=bsum[:, :, 1].tolist())
|
|
||||||
|
|
||||||
|
|
||||||
def main() -> None:
|
|
||||||
ap = argparse.ArgumentParser()
|
|
||||||
ap.add_argument("--games", type=int, default=400)
|
|
||||||
ap.add_argument("--seeds", default="0,1,2,3,4,5,6,7")
|
|
||||||
ap.add_argument("--hidden", type=int, default=32)
|
|
||||||
ap.add_argument("--cppn-hidden", type=int, default=32)
|
|
||||||
ap.add_argument("--lr", type=float, default=1e-3)
|
|
||||||
ap.add_argument("--bptt", type=int, default=20)
|
|
||||||
ap.add_argument("--mask", default="all", choices=("all", "attack"))
|
|
||||||
ap.add_argument("--arms", default="constant,shape,rp,rp_type")
|
|
||||||
ap.add_argument("--out", default="results/chess_reach.json")
|
|
||||||
a = ap.parse_args()
|
|
||||||
|
|
||||||
games = load(a.games)
|
|
||||||
# (memory, edge types)
|
|
||||||
all_arms = {"constant": None, "shape": "shape", "rp": (False, False), "rp_type": (False, True),
|
|
||||||
"grp": (True, False), "grp_type": (True, True)}
|
|
||||||
arms = {k: all_arms[k] for k in a.arms.split(",")}
|
|
||||||
print(f"{len(games)} games, {sum(len(g) for g in games)} plies, mask={a.mask}\n")
|
|
||||||
|
|
||||||
results = []
|
|
||||||
for name, spec in arms.items():
|
|
||||||
for seed in (int(s) for s in a.seeds.split(",")):
|
|
||||||
r = (run_constant(games, seed) if spec is None else
|
|
||||||
run_shape(games, seed) if spec == "shape" else
|
|
||||||
run(games, spec[0], a.hidden, a.cppn_hidden, seed, a.lr, a.bptt, spec[1],
|
|
||||||
a.mask == "attack")) | {"arm": name}
|
|
||||||
print(f"{name:<10} seed={seed} params={r['params']:<6} "
|
|
||||||
f"loss={r['loss']:.4f} prec@k={r['prec']:.4f}", flush=True)
|
|
||||||
results.append(r)
|
|
||||||
Path(a.out).parent.mkdir(parents=True, exist_ok=True)
|
|
||||||
Path(a.out).write_text(json.dumps(results, indent=1))
|
|
||||||
|
|
||||||
by = {n: [r for r in results if r["arm"] == n] for n in arms}
|
|
||||||
names = ["pawn", "knight", "bishop", "rook", "queen", "king"]
|
|
||||||
print(f"\n{'arm':<10}{'loss':>9}{'prec@k':>9}" + "".join(f"{t:>9}" for t in names))
|
|
||||||
print("-" * (28 + 9 * 6))
|
|
||||||
for n, rs in by.items():
|
|
||||||
bt = [statistics.fmean(r["by_type"][i] for r in rs) for i in range(6)]
|
|
||||||
print(f"{n:<10}{statistics.fmean(r['loss'] for r in rs):>9.4f}"
|
|
||||||
f"{statistics.fmean(r['prec'] for r in rs):>9.4f}"
|
|
||||||
+ "".join(f"{v:>9.4f}" for v in bt))
|
|
||||||
print(f"\nrandom ranking would score {statistics.fmean(r['chance'] for r in results):.4f}")
|
|
||||||
|
|
||||||
# the blocker split: a knight's L never changes, a sliding piece's ray is cut by occupancy.
|
|
||||||
# Reported against the floor inside each bucket, because a blocked piece has a smaller
|
|
||||||
# attack set and therefore a different chance level -- the buckets are not comparable raw.
|
|
||||||
print(f"\n{'':<10}" + "".join(f"{t:>20}" for t in ("bishop", "rook", "queen")))
|
|
||||||
print(f"{'arm':<10}" + "".join(f"{'open':>10}{'blocked':>10}" for _ in range(3)))
|
|
||||||
print("-" * 70)
|
|
||||||
for n, rs in by.items():
|
|
||||||
row = ""
|
|
||||||
for i in (2, 3, 4):
|
|
||||||
for b in (0, 1):
|
|
||||||
row += f"{statistics.fmean(r['by_block'][i][b] for r in rs):>10.4f}"
|
|
||||||
print(f"{n:<10}{row}")
|
|
||||||
counts = by[list(by)[0]][0]["n_block"]
|
|
||||||
print("share blocked: " + " ".join(
|
|
||||||
f"{t}={counts[i][1] / max(counts[i][0] + counts[i][1], 1):.2f}"
|
|
||||||
for i, t in ((2, "bishop"), (3, "rook"), (4, "queen"))))
|
|
||||||
for top, base in (("rp_type", "rp"), ("grp_type", "rp_type"), ("grp", "rp")):
|
|
||||||
if top not in by or base not in by:
|
|
||||||
continue
|
|
||||||
d = [x["prec"] - y["prec"] for x, y in zip(by[top], by[base])]
|
|
||||||
se = statistics.stdev(d) / len(d) ** 0.5 if len(d) > 1 else float("nan")
|
|
||||||
print(f"\n{top} - {base}: {statistics.fmean(d):+.4f} +/- {se:.4f} (paired se), "
|
|
||||||
f"{sum(x > 0 for x in d)}/{len(d)} seeds -- "
|
|
||||||
f"{'ambiguous' if abs(statistics.fmean(d)) < se else 'a direction'}")
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
main()
|
|
||||||
-310
@@ -1,310 +0,0 @@
|
|||||||
"""How the pieces move, taught directly instead of inferred from games.
|
|
||||||
|
|
||||||
Two things games got wrong as a curriculum, both measured rather than assumed:
|
|
||||||
|
|
||||||
**Coverage.** In real play a rook or queen is blocked in 98-100% of positions
|
|
||||||
(`chess_shape.json`), so the model learns the geometry it sees rather than the rule that
|
|
||||||
generates it -- it scored *worse* in open positions than blocked ones. Here the number of
|
|
||||||
pieces is sampled uniformly from 2 to 32, so an empty board is as common as a crowded one.
|
|
||||||
|
|
||||||
**The target left out three rules entirely.** `board.attacks` is what the reachability task
|
|
||||||
asked for, and for a pawn on e2 it returns d3 and f3 while the pawn's actual moves are e3 and
|
|
||||||
e4 -- *no overlap at all*. Castling never appeared (the king's attack set is five adjacent
|
|
||||||
squares; c1 and g1 are not in it). Nor did en passant. The model did not fail to learn these;
|
|
||||||
it was never asked. The target here is `generate_pseudo_legal_moves`, which carries pushes,
|
|
||||||
castling and en passant.
|
|
||||||
|
|
||||||
Castling rights and the en-passant square are **state, not position**: a rook must remember
|
|
||||||
whether it has moved, and en passant depends on the opponent's last move. They are handed over
|
|
||||||
as per-entity attributes here so the rule is learnable at all -- without them the same board
|
|
||||||
has two different correct answers. Taking them away is the cleanest memory experiment this
|
|
||||||
project has available, and it belongs to the GRP line, which is parked (`AGENTS.md`).
|
|
||||||
|
|
||||||
No memory in this file. One position, one answer, no stream: this is the RP question alone.
|
|
||||||
"""
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import argparse
|
|
||||||
import json
|
|
||||||
import statistics
|
|
||||||
from dataclasses import dataclass
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
import chess
|
|
||||||
import numpy as np
|
|
||||||
import torch
|
|
||||||
|
|
||||||
from ailed import Affect, Organism
|
|
||||||
from chess_domain import flat_diff
|
|
||||||
from chess_reach import GRID, OFFSET
|
|
||||||
|
|
||||||
# type (6), colour (1), castling right (1), ep flag (1), file, rank, rank-from-my-own-side (3)
|
|
||||||
ATTR_DIM = 12
|
|
||||||
# The last three exist because the CPPN sees only r_ij, which makes the representation
|
|
||||||
# translation-invariant -- and a chess board has EDGES. A knight on the rim has 2.96
|
|
||||||
# destinations on average and one in the middle has 6.85, and 43% of knights sit on the rim
|
|
||||||
# (measured). Relative geometry to other pieces cannot recover that on a near-empty board.
|
|
||||||
# `own_rank` is rank from the piece's own back rank: a pawn's push, its double-push rank, its
|
|
||||||
# promotion rank and castling are all one law in that frame and two mirrored laws without it.
|
|
||||||
HOME = ((chess.WHITE, chess.E1, chess.H1, chess.A1), (chess.BLACK, chess.E8, chess.H8, chess.A8))
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
|
||||||
class Position:
|
|
||||||
attrs: np.ndarray # (N, 9)
|
|
||||||
coords: np.ndarray # (N, 2)
|
|
||||||
types: np.ndarray # (N,) 0-5, for the per-type breakdown
|
|
||||||
y: np.ndarray # (N, 225) multi-hot over relative offsets
|
|
||||||
shape: np.ndarray # (N, 225) what knowing the rule alone would answer
|
|
||||||
|
|
||||||
|
|
||||||
def _rights(b: chess.Board, rng) -> None:
|
|
||||||
fen = ""
|
|
||||||
for col, k_sq, r_k, r_q in HOME:
|
|
||||||
if b.piece_at(k_sq) == chess.Piece(chess.KING, col):
|
|
||||||
for r_sq, ch in ((r_k, "k"), (r_q, "q")):
|
|
||||||
if b.piece_at(r_sq) == chess.Piece(chess.ROOK, col) and rng.random() < 0.7:
|
|
||||||
fen += ch.upper() if col else ch
|
|
||||||
b.set_castling_fen(fen or "-")
|
|
||||||
|
|
||||||
|
|
||||||
def random_board(rng) -> chess.Board | None:
|
|
||||||
"""A position sampled for coverage, not for plausibility. Density is uniform by design."""
|
|
||||||
for _ in range(60):
|
|
||||||
b = chess.Board(None)
|
|
||||||
sqs = rng.permutation(64)
|
|
||||||
b.set_piece_at(int(sqs[0]), chess.Piece(chess.KING, chess.WHITE))
|
|
||||||
b.set_piece_at(int(sqs[1]), chess.Piece(chess.KING, chess.BLACK))
|
|
||||||
for sq in sqs[2:int(rng.integers(2, 33))]:
|
|
||||||
pt = int(rng.choice([1, 2, 3, 4, 5], p=[0.42, 0.16, 0.16, 0.16, 0.10]))
|
|
||||||
if pt == chess.PAWN and chess.square_rank(int(sq)) in (0, 7):
|
|
||||||
continue
|
|
||||||
b.set_piece_at(int(sq), chess.Piece(pt, bool(rng.integers(2))))
|
|
||||||
b.turn = bool(rng.integers(2))
|
|
||||||
_rights(b, rng)
|
|
||||||
if not b.is_valid():
|
|
||||||
continue
|
|
||||||
# an en-passant square, where a pawn sits as if it had just double-pushed
|
|
||||||
rank = 4 if b.turn == chess.WHITE else 3
|
|
||||||
cands = [s for s in chess.SQUARES if b.piece_at(s) == chess.Piece(chess.PAWN, not b.turn)
|
|
||||||
and chess.square_rank(s) == rank]
|
|
||||||
if cands and rng.random() < 0.35:
|
|
||||||
keep = b.ep_square
|
|
||||||
b.ep_square = int(rng.choice(cands)) + (8 if b.turn == chess.WHITE else -8)
|
|
||||||
if not b.is_valid():
|
|
||||||
b.ep_square = keep
|
|
||||||
return b
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
def _dests(b: chess.Board) -> dict[int, set[int]]:
|
|
||||||
"""Every piece's pseudo-legal destinations, for both colours. Pushes, castling, ep."""
|
|
||||||
out: dict[int, set[int]] = {}
|
|
||||||
turn = b.turn
|
|
||||||
for col in (chess.WHITE, chess.BLACK):
|
|
||||||
b.turn = col
|
|
||||||
for m in b.generate_pseudo_legal_moves():
|
|
||||||
out.setdefault(m.from_square, set()).add(m.to_square)
|
|
||||||
b.turn = turn
|
|
||||||
return out
|
|
||||||
|
|
||||||
|
|
||||||
_RULE_CACHE: dict[tuple, frozenset] = {}
|
|
||||||
|
|
||||||
|
|
||||||
def _rule_only(piece: chess.Piece, sq: int, right: bool, ep: int | None) -> set[int]:
|
|
||||||
"""The control: this piece's moves on an EMPTY board, plus its own flags. Reads nothing.
|
|
||||||
|
|
||||||
Memoised: it is deterministic in its arguments and was rebuilding a Board per piece per
|
|
||||||
position, which dominated generation.
|
|
||||||
"""
|
|
||||||
key = (piece.piece_type, piece.color, sq, right, ep)
|
|
||||||
if key in _RULE_CACHE:
|
|
||||||
return _RULE_CACHE[key]
|
|
||||||
b = chess.Board(None)
|
|
||||||
b.set_piece_at(sq, piece)
|
|
||||||
b.turn = piece.color
|
|
||||||
b.set_castling_fen("-")
|
|
||||||
out = {m.to_square for m in b.generate_pseudo_legal_moves()}
|
|
||||||
if right and piece.piece_type == chess.KING:
|
|
||||||
out |= {sq - 2, sq + 2} # both castling destinations
|
|
||||||
if ep is not None and piece.piece_type == chess.PAWN:
|
|
||||||
out.add(ep)
|
|
||||||
_RULE_CACHE[key] = frozenset(out)
|
|
||||||
return _RULE_CACHE[key]
|
|
||||||
|
|
||||||
|
|
||||||
def build(b: chess.Board) -> Position:
|
|
||||||
dests = _dests(b)
|
|
||||||
squares = sorted(b.piece_map())
|
|
||||||
n = len(squares)
|
|
||||||
attrs = np.zeros((n, ATTR_DIM), dtype=np.float32)
|
|
||||||
coords = np.zeros((n, 2), dtype=np.float32)
|
|
||||||
types = np.zeros(n, dtype=np.int64)
|
|
||||||
y = np.zeros((n, GRID), dtype=np.float32)
|
|
||||||
shape = np.zeros((n, GRID), dtype=np.float32)
|
|
||||||
for k, sq in enumerate(squares):
|
|
||||||
p = b.piece_at(sq)
|
|
||||||
types[k] = p.piece_type - 1
|
|
||||||
attrs[k, p.piece_type - 1] = 1.0
|
|
||||||
attrs[k, 6] = float(p.color == chess.WHITE)
|
|
||||||
right = ((p.piece_type == chess.KING and bool(b.castling_rights & (
|
|
||||||
chess.BB_RANK_1 if p.color else chess.BB_RANK_8)))
|
|
||||||
or (p.piece_type == chess.ROOK and bool(b.castling_rights & chess.BB_SQUARES[sq])))
|
|
||||||
attrs[k, 7] = float(right)
|
|
||||||
ep = b.ep_square if (b.ep_square is not None and p.piece_type == chess.PAWN
|
|
||||||
and b.ep_square in _rule_only(p, sq, False, None)) else None
|
|
||||||
attrs[k, 8] = float(ep is not None)
|
|
||||||
f, r = chess.square_file(sq), chess.square_rank(sq)
|
|
||||||
coords[k] = (f / 7.0, r / 7.0)
|
|
||||||
attrs[k, 9] = f / 7.0
|
|
||||||
attrs[k, 10] = r / 7.0
|
|
||||||
attrs[k, 11] = (r if p.color == chess.WHITE else 7 - r) / 7.0
|
|
||||||
for t in dests.get(sq, ()):
|
|
||||||
y[k, OFFSET[sq][t]] = 1.0
|
|
||||||
for t in _rule_only(p, sq, right, ep):
|
|
||||||
if 0 <= t < 64:
|
|
||||||
shape[k, OFFSET[sq][t]] = 1.0
|
|
||||||
return Position(attrs, coords, types, y, shape)
|
|
||||||
|
|
||||||
|
|
||||||
def stream(n: int, seed: int):
|
|
||||||
"""Positions are generated, never stored: training is a single pass and 200k dense targets
|
|
||||||
would be 6 GB. The test set is materialised because every arm must see the same one."""
|
|
||||||
rng = np.random.default_rng(seed)
|
|
||||||
made = 0
|
|
||||||
while made < n:
|
|
||||||
b = random_board(rng)
|
|
||||||
if b is not None:
|
|
||||||
made += 1
|
|
||||||
yield build(b)
|
|
||||||
|
|
||||||
|
|
||||||
def _precision(score: np.ndarray, y: np.ndarray):
|
|
||||||
"""precision@k per entity, k = the true number of destinations."""
|
|
||||||
s = torch.as_tensor(score); yy = torch.as_tensor(y)
|
|
||||||
k = yy.sum(1)
|
|
||||||
keep = k > 0
|
|
||||||
rank = s.argsort(1, descending=True).argsort(1)
|
|
||||||
hit = ((rank < k[:, None]) & (yy > 0)).sum(1) / k.clamp(min=1)
|
|
||||||
return hit, keep, k
|
|
||||||
|
|
||||||
|
|
||||||
def evaluate(scores, batch, tsum):
|
|
||||||
hit, keep, k = _precision(scores, batch.y)
|
|
||||||
if not keep.any():
|
|
||||||
return [], []
|
|
||||||
np.add.at(tsum, (batch.types[keep.numpy()], 0), hit[keep].numpy())
|
|
||||||
np.add.at(tsum, (batch.types[keep.numpy()], 1), 1.0)
|
|
||||||
return list(hit[keep].numpy()), list((k[keep] / GRID).numpy())
|
|
||||||
|
|
||||||
|
|
||||||
EDGES = {"none": 1, "type": 6, "typecol": 12}
|
|
||||||
|
|
||||||
|
|
||||||
def _edge_types(pos: Position, kind: str, n: int):
|
|
||||||
"""What the CPPN is told about the pieces it relates, beyond their geometry.
|
|
||||||
|
|
||||||
`type` shares one kernel between a white pawn and a black pawn, whose moves are mirrored --
|
|
||||||
which is why the type-conditional arm lost 0.14 on pawns and nothing elsewhere. `typecol`
|
|
||||||
gives each colour its own.
|
|
||||||
"""
|
|
||||||
if kind == "none":
|
|
||||||
return None
|
|
||||||
t = torch.from_numpy(pos.types if kind == "type"
|
|
||||||
else pos.types * 2 + (1 - pos.attrs[:, 6].astype(np.int64)))
|
|
||||||
return t[:, None].expand(n, n).contiguous()
|
|
||||||
|
|
||||||
|
|
||||||
def run(n_train: int, seed_train: int, test, hidden: int, cppn_hidden: int, seed: int,
|
|
||||||
lr: float, batch: int, edges: str) -> dict:
|
|
||||||
torch.manual_seed(seed)
|
|
||||||
org = Organism(ATTR_DIM, 2, GRID, n_edge_types=EDGES[edges], hidden_dim=hidden,
|
|
||||||
cppn_hidden=cppn_hidden, memory=False)
|
|
||||||
opt = torch.optim.Adam(org.parameters(), lr=lr)
|
|
||||||
zero = Affect().axes
|
|
||||||
pending = []
|
|
||||||
for pos in stream(n_train, seed_train):
|
|
||||||
n = len(pos.types)
|
|
||||||
pred, _ = org(torch.from_numpy(pos.attrs), flat_diff(torch.from_numpy(pos.coords)),
|
|
||||||
list(range(n)), zero, {}, edge_types=_edge_types(pos, edges, n))
|
|
||||||
pending.append(torch.nn.functional.binary_cross_entropy_with_logits(
|
|
||||||
pred, torch.from_numpy(pos.y)))
|
|
||||||
if len(pending) == batch:
|
|
||||||
opt.zero_grad(); torch.stack(pending).mean().backward(); opt.step(); pending = []
|
|
||||||
|
|
||||||
prec, chance, tsum = [], [], np.zeros((6, 2))
|
|
||||||
with torch.no_grad():
|
|
||||||
for pos in test:
|
|
||||||
n = len(pos.types)
|
|
||||||
pred, _ = org(torch.from_numpy(pos.attrs), flat_diff(torch.from_numpy(pos.coords)),
|
|
||||||
list(range(n)), zero, {}, edge_types=_edge_types(pos, edges, n))
|
|
||||||
p, c = evaluate(pred.numpy(), pos, tsum)
|
|
||||||
prec += p; chance += c
|
|
||||||
return dict(seed=seed, params=sum(q.numel() for q in org.parameters()),
|
|
||||||
prec=statistics.fmean(prec), chance=statistics.fmean(chance),
|
|
||||||
by_type=list(tsum[:, 0] / np.maximum(tsum[:, 1], 1)))
|
|
||||||
|
|
||||||
|
|
||||||
def run_baseline(n_marg: int, seed_train: int, test, seed: int, kind: str) -> dict:
|
|
||||||
"""`shape` knows each piece's rule and reads no other piece. `constant` knows neither."""
|
|
||||||
marg = np.zeros(GRID)
|
|
||||||
for pos in stream(n_marg, seed_train):
|
|
||||||
marg += pos.y.sum(0)
|
|
||||||
marg /= max(marg.max(), 1.0)
|
|
||||||
prec, chance, tsum = [], [], np.zeros((6, 2))
|
|
||||||
for pos in test:
|
|
||||||
score = np.tile(marg, (len(pos.types), 1)) * 0.5
|
|
||||||
if kind == "shape":
|
|
||||||
score = score + pos.shape
|
|
||||||
p, c = evaluate(score, pos, tsum)
|
|
||||||
prec += p; chance += c
|
|
||||||
return dict(seed=seed, params=0, prec=statistics.fmean(prec),
|
|
||||||
chance=statistics.fmean(chance),
|
|
||||||
by_type=list(tsum[:, 0] / np.maximum(tsum[:, 1], 1)))
|
|
||||||
|
|
||||||
|
|
||||||
def main() -> None:
|
|
||||||
ap = argparse.ArgumentParser()
|
|
||||||
ap.add_argument("--positions", type=int, default=200000)
|
|
||||||
ap.add_argument("--test", type=int, default=4000)
|
|
||||||
ap.add_argument("--seeds", default="0,1,2,3")
|
|
||||||
ap.add_argument("--hidden", type=int, default=32)
|
|
||||||
ap.add_argument("--cppn-hidden", type=int, default=32)
|
|
||||||
ap.add_argument("--lr", type=float, default=1e-3)
|
|
||||||
ap.add_argument("--batch", type=int, default=16)
|
|
||||||
ap.add_argument("--arms", default="constant,shape,rp,rp_type,rp_typecol")
|
|
||||||
ap.add_argument("--out", default="results/chess_rules.json")
|
|
||||||
a = ap.parse_args()
|
|
||||||
|
|
||||||
test = list(stream(a.test, 10_000)) # a different seed: never a training position
|
|
||||||
print(f"{a.positions} training positions streamed, {a.test} held out "
|
|
||||||
f"({sum(int(p.y.sum()) for p in test)} moves to predict), "
|
|
||||||
f"{a.positions // a.batch} optimiser steps\n")
|
|
||||||
|
|
||||||
results = []
|
|
||||||
for name in a.arms.split(","):
|
|
||||||
for seed in (int(s) for s in a.seeds.split(",")):
|
|
||||||
r = (run_baseline(min(a.positions, 5000), seed, test, seed, name)
|
|
||||||
if name in ("constant", "shape") else
|
|
||||||
run(a.positions, seed, test, a.hidden, a.cppn_hidden, seed, a.lr, a.batch,
|
|
||||||
{"rp": "none", "rp_type": "type",
|
|
||||||
"rp_typecol": "typecol"}[name])) | {"arm": name}
|
|
||||||
print(f"{name:<10} seed={seed} params={r['params']:<6} prec@k={r['prec']:.4f}",
|
|
||||||
flush=True)
|
|
||||||
results.append(r)
|
|
||||||
Path(a.out).parent.mkdir(parents=True, exist_ok=True)
|
|
||||||
Path(a.out).write_text(json.dumps(results, indent=1))
|
|
||||||
|
|
||||||
names = ["pawn", "knight", "bishop", "rook", "queen", "king"]
|
|
||||||
by = {n: [r for r in results if r["arm"] == n] for n in a.arms.split(",")}
|
|
||||||
print(f"\n{'arm':<10}{'prec@k':>9}" + "".join(f"{t:>9}" for t in names))
|
|
||||||
print("-" * (19 + 9 * 6))
|
|
||||||
for n, rs in by.items():
|
|
||||||
print(f"{n:<10}{statistics.fmean(r['prec'] for r in rs):>9.4f}"
|
|
||||||
+ "".join(f"{statistics.fmean(r['by_type'][i] for r in rs):>9.4f}" for i in range(6)))
|
|
||||||
print(f"\nrandom ranking would score {statistics.fmean(r['chance'] for r in results):.4f}")
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
main()
|
|
||||||
@@ -1,788 +0,0 @@
|
|||||||
"""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()
|
|
||||||
@@ -1,505 +0,0 @@
|
|||||||
"""Task 7b: frozen-weights probe. Train, freeze every parameter, keep stepping.
|
|
||||||
|
|
||||||
Task 7 measured memory's advantage at lr=1e-3 and watched it decay to 1.06x at
|
|
||||||
lr=1e-2: mean error cannot tell state and fast weights apart, because raising lr
|
|
||||||
buys the same adaptation speed that memory buys. This file removes learning
|
|
||||||
instead of retuning it. After the freeze no parameter may change, so nothing the
|
|
||||||
model does can be attributed to an optimiser step. A frozen `rp_only` still carries
|
|
||||||
the 2-d affect state (`--freeze-affect` pins that too); a frozen `grp_k0` still
|
|
||||||
updates its per-entity M every step through the gate.
|
|
||||||
|
|
||||||
Part A measures recovery after a switch under frozen weights. Part B asks what the
|
|
||||||
state knows, by linearly decoding the world's regime id out of M (GRP) and out of h
|
|
||||||
(RP), against an empirically measured chance level.
|
|
||||||
|
|
||||||
What survives the freeze is state *only if the two conditions are capacity-matched*,
|
|
||||||
and they are not: `rp_only` has 1442 parameters and `grp_k0` 5602. `--ablate-state`
|
|
||||||
supplies the control that separates the two. See results/frozen.md; it is what turns
|
|
||||||
this file's result from a memory effect into a null.
|
|
||||||
"""
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import argparse
|
|
||||||
import json
|
|
||||||
import statistics
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
import numpy as np
|
|
||||||
import torch
|
|
||||||
from torch import Tensor, nn
|
|
||||||
|
|
||||||
from ailed import Affect, AffectConfig, Organism, detach_memory, update
|
|
||||||
from particles import ParticleConfig, ParticleWorld, wrapped_diff
|
|
||||||
from regime import CONDITIONS, KAPPA_FLAG, _context, _metrics
|
|
||||||
|
|
||||||
TRAIN_STEPS = 8000 # matches the budget every headroom table in results/headroom.md used
|
|
||||||
FROZEN_STEPS = 4000
|
|
||||||
SPLIT = 0.7 # probe train fraction, taken as a prefix in time
|
|
||||||
|
|
||||||
|
|
||||||
# -- construction and the two phases ---------------------------------------------
|
|
||||||
|
|
||||||
def _build(name: str, seed: int, hidden: int, omega: float, kappa: float,
|
|
||||||
t_min: int | None = None, t_max: int | None = None):
|
|
||||||
"""Construct exactly as `regime.run` does, in the same order, so the RNG stream matches.
|
|
||||||
|
|
||||||
`t_min`/`t_max` override the regime duration for Task 9 Part 3. They are passed to
|
|
||||||
`ParticleConfig` here rather than changed in `particles.py`, so every other caller
|
|
||||||
keeps the 40-80 default and `test_train_copy_is_identical_to_regime_run` still pins
|
|
||||||
this loop against `regime.run`.
|
|
||||||
"""
|
|
||||||
spec = dict(CONDITIONS[name])
|
|
||||||
if spec["kappa"] == KAPPA_FLAG:
|
|
||||||
spec["kappa"] = kappa
|
|
||||||
dur = {}
|
|
||||||
if t_min is not None:
|
|
||||||
dur["t_min"] = t_min
|
|
||||||
if t_max is not None:
|
|
||||||
dur["t_max"] = t_max
|
|
||||||
wcfg = ParticleConfig(seed=seed, oracle=spec["oracle"], **dur)
|
|
||||||
torch.manual_seed(seed)
|
|
||||||
world = ParticleWorld(wcfg)
|
|
||||||
ctx_dim = wcfg.n_regimes if spec["ctx"] == "regime" else 2
|
|
||||||
org = Organism(attr_dim=world.attr_dim, coord_dim=2, target_dim=2, context_dim=ctx_dim,
|
|
||||||
hidden_dim=hidden, omega=omega, kappa=spec["kappa"], memory=spec["memory"])
|
|
||||||
return spec, wcfg, world, org
|
|
||||||
|
|
||||||
|
|
||||||
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,
|
|
||||||
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 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
|
|
||||||
always zero. The GRP keeps every parameter it had and loses only the carrying of
|
|
||||||
state -- the control that separates "memory helps" from "the GRP's extra 4160
|
|
||||||
parameters help". It is a call into the public API, not a change to the library.
|
|
||||||
|
|
||||||
`gate_arousal(t, affect) -> float` replaces the arousal the *gate* sees while the
|
|
||||||
CPPN keeps the organism's own live affect: the context is then passed explicitly,
|
|
||||||
built exactly as `Organism.forward` would have built it from the real affect. This
|
|
||||||
is Task 8's shuffled-affect control -- it has to move `-kappa*a` alone, because
|
|
||||||
shuffling the affect the CPPN reads would change a second input as well.
|
|
||||||
|
|
||||||
`on_step(t, obs, r, ctx, axes, prev, memory)` is a read-only callback fired after
|
|
||||||
the forward pass, for measuring the gate. `prev` is the M_prev the organism was
|
|
||||||
handed, captured before `memory` is rebound.
|
|
||||||
|
|
||||||
`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(list(org.parameters()) + list(extra_params), lr=lr)
|
|
||||||
acfg = AffectConfig() if acfg is None else acfg
|
|
||||||
affect = Affect()
|
|
||||||
memory: dict[int, Tensor] = {}
|
|
||||||
|
|
||||||
zero = torch.zeros(org.hidden_dim)
|
|
||||||
losses, switched, arousals = [], [], []
|
|
||||||
pending = []
|
|
||||||
for t in range(steps):
|
|
||||||
obs = world.step()
|
|
||||||
ctx = _context(spec["ctx"], affect, obs.regime, wcfg.n_regimes)
|
|
||||||
r = wrapped_diff(obs.coords)
|
|
||||||
axes = affect.axes
|
|
||||||
if gate_arousal is not None:
|
|
||||||
if ctx is None: # what Organism.forward builds from the real affect
|
|
||||||
ctx = torch.tensor(affect.axes, dtype=obs.attrs.dtype)
|
|
||||||
axes = (affect.valence, float(gate_arousal(t, affect)))
|
|
||||||
held = {} if stateless else memory
|
|
||||||
prev = (torch.stack([held.get(i, zero) for i in obs.ids])
|
|
||||||
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 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:
|
|
||||||
on_step(t, obs, r, ctx, axes, prev, memory)
|
|
||||||
if len(pending) == bptt:
|
|
||||||
opt.zero_grad()
|
|
||||||
torch.stack(pending).mean().backward()
|
|
||||||
opt.step()
|
|
||||||
pending = []
|
|
||||||
memory = detach_memory(memory)
|
|
||||||
|
|
||||||
trace = dict(losses=losses, switched=switched, arousals=arousals)
|
|
||||||
return affect, detach_memory(memory), trace
|
|
||||||
|
|
||||||
|
|
||||||
def _hidden(org: Organism, attrs: Tensor, r: Tensor, axes: tuple[float, float],
|
|
||||||
ctx: Tensor | None) -> Tensor:
|
|
||||||
"""h as `Organism.forward` computes it, by mirroring the tensors it builds internally.
|
|
||||||
|
|
||||||
`Organism.forward` returns only `out(h)` (or `out(M)`), so h has to be recomputed
|
|
||||||
from the public `org.rp`. Every argument here is built the way core.py builds it;
|
|
||||||
`_frozen` asserts the reconstruction is bit-identical to the organism's own output.
|
|
||||||
"""
|
|
||||||
n = attrs.shape[0]
|
|
||||||
valence, arousal = axes
|
|
||||||
if ctx is None:
|
|
||||||
ctx = torch.tensor([valence, arousal], dtype=attrs.dtype)
|
|
||||||
edge_types = torch.zeros(n, n, dtype=torch.long)
|
|
||||||
mask = torch.ones(n, n, dtype=attrs.dtype)
|
|
||||||
edge_onehot = nn.functional.one_hot(edge_types, org.n_edge_types).to(attrs.dtype)
|
|
||||||
return org.rp(attrs, r, edge_onehot, mask, ctx)
|
|
||||||
|
|
||||||
|
|
||||||
def _frozen(spec: dict, wcfg: ParticleConfig, world: ParticleWorld, org: Organism,
|
|
||||||
affect: Affect, memory: dict[int, Tensor], steps: int,
|
|
||||||
freeze_affect: bool = False, stateless: bool = False) -> dict:
|
|
||||||
"""Step the world with every parameter frozen. Memory and affect keep updating.
|
|
||||||
|
|
||||||
`freeze_affect` additionally pins (valence, arousal) at their end-of-training
|
|
||||||
values. It exists because `rp_only` runs with `ctx="affect"`, so a frozen RP is
|
|
||||||
*not* a fixed function of the current observation: affect is a 2-d state that
|
|
||||||
updates from the loss and feeds the CPPN. Pinning it removes the RP's last
|
|
||||||
adaptive channel and tests the premise Part A rests on."""
|
|
||||||
for p in org.parameters():
|
|
||||||
p.requires_grad_(False)
|
|
||||||
before = nn.utils.parameters_to_vector(org.parameters()).clone()
|
|
||||||
|
|
||||||
acfg = AffectConfig()
|
|
||||||
zero = torch.zeros(org.hidden_dim)
|
|
||||||
losses, switched, arousals, regimes = [], [], [], []
|
|
||||||
h_reps, m_reps, dM, gates, couple = [], [], [], [], []
|
|
||||||
# the regime id is an arbitrary label over four random coupling matrices; what an
|
|
||||||
# entity actually needs is its own row of the current one. Decoding the id can be
|
|
||||||
# at chance while the row is not, so both are probed.
|
|
||||||
rows = torch.stack([k[world.types] for k in world.regimes]) # (n_regimes, N, n_types)
|
|
||||||
|
|
||||||
with torch.no_grad():
|
|
||||||
for t in range(steps):
|
|
||||||
obs = world.step()
|
|
||||||
ctx = _context(spec["ctx"], affect, obs.regime, wcfg.n_regimes)
|
|
||||||
if stateless:
|
|
||||||
memory = {}
|
|
||||||
prev = torch.stack([memory.get(i, zero) for i in obs.ids]) if org.use_memory else None
|
|
||||||
r = wrapped_diff(obs.coords)
|
|
||||||
pred, memory = org(obs.attrs, r, obs.ids, affect.axes, memory, context=ctx)
|
|
||||||
loss = ((pred - obs.target) ** 2).mean()
|
|
||||||
|
|
||||||
h = _hidden(org, obs.attrs, r, affect.axes, ctx)
|
|
||||||
if org.use_memory:
|
|
||||||
M = torch.stack([memory[i] for i in obs.ids])
|
|
||||||
# if this holds, h is exactly the h the organism used
|
|
||||||
assert torch.equal(org.grp(h, prev, affect.arousal), M), "h reconstruction diverged"
|
|
||||||
m_reps.append(M.numpy().copy())
|
|
||||||
dM.append(float((M - prev).abs().max()))
|
|
||||||
g = torch.sigmoid(org.grp.gate(torch.cat([h, prev], -1)) - org.grp.kappa * affect.arousal)
|
|
||||||
gates.append((float(g.mean()), float(g.std()), float((g > 0.9).float().mean()),
|
|
||||||
float((g < 0.1).float().mean())))
|
|
||||||
else:
|
|
||||||
assert torch.equal(org.out(h), pred), "h reconstruction diverged"
|
|
||||||
h_reps.append(h.numpy().copy())
|
|
||||||
|
|
||||||
if not freeze_affect:
|
|
||||||
affect = update(affect, loss.item(), acfg)
|
|
||||||
losses.append(loss.item()); switched.append(obs.switched)
|
|
||||||
arousals.append(affect.arousal); regimes.append(obs.regime)
|
|
||||||
couple.append(rows[obs.regime].numpy().copy())
|
|
||||||
|
|
||||||
after = nn.utils.parameters_to_vector(org.parameters())
|
|
||||||
frozen_ok = bool(torch.equal(before, after))
|
|
||||||
assert frozen_ok, "a parameter changed during the frozen phase"
|
|
||||||
assert not any(p.requires_grad for p in org.parameters())
|
|
||||||
|
|
||||||
if org.use_memory and not stateless:
|
|
||||||
# freezing is about parameters, not state: if M stopped moving the GRP would
|
|
||||||
# have silently degenerated into an RP and any null would be for the wrong reason
|
|
||||||
assert min(dM[1:]) > 0.0, "M did not change between consecutive frozen steps"
|
|
||||||
|
|
||||||
return dict(losses=losses, switched=switched, arousals=arousals, regimes=regimes,
|
|
||||||
couple=(np.stack(couple) + 1).astype(int), # {-1,0,1} -> class {0,1,2}
|
|
||||||
gate=dict(zip(("mean", "sd", "frac_open", "frac_shut"),
|
|
||||||
(statistics.fmean(c) for c in zip(*gates)))) if gates else None,
|
|
||||||
h=np.stack(h_reps), M=np.stack(m_reps) if m_reps else None,
|
|
||||||
frozen_bit_identical=frozen_ok, n_params=int(before.numel()),
|
|
||||||
dM_min=min(dM[1:]) if dM else None,
|
|
||||||
dM_mean=statistics.fmean(dM[1:]) if dM else None)
|
|
||||||
|
|
||||||
|
|
||||||
# -- Part B: the linear probe ----------------------------------------------------
|
|
||||||
|
|
||||||
def _fit_lsq(X: np.ndarray, y: np.ndarray, R: int, ridge: float = 1e-6) -> np.ndarray:
|
|
||||||
G = X.T @ X
|
|
||||||
lam = ridge * np.trace(G) / X.shape[1]
|
|
||||||
return np.linalg.solve(G + lam * np.eye(X.shape[1]), X.T @ np.eye(R)[y])
|
|
||||||
|
|
||||||
|
|
||||||
def _fit_logit(X: np.ndarray, y: np.ndarray, R: int, l2: float = 1e-4) -> np.ndarray:
|
|
||||||
"""Multinomial logistic, so a null cannot be blamed on least squares.
|
|
||||||
|
|
||||||
X already carries the bias column, so the linear map needs no separate intercept.
|
|
||||||
LBFGS with strong-Wolfe converges deterministically here; there is no seed."""
|
|
||||||
Xt = torch.tensor(X); yt = torch.tensor(y, dtype=torch.long)
|
|
||||||
W = torch.zeros(X.shape[1], R, dtype=torch.float64, requires_grad=True)
|
|
||||||
opt = torch.optim.LBFGS([W], max_iter=300, tolerance_grad=1e-10,
|
|
||||||
line_search_fn="strong_wolfe")
|
|
||||||
|
|
||||||
def closure():
|
|
||||||
opt.zero_grad()
|
|
||||||
loss = nn.functional.cross_entropy(Xt @ W, yt) + l2 * (W[:-1] ** 2).sum()
|
|
||||||
loss.backward()
|
|
||||||
return loss
|
|
||||||
|
|
||||||
opt.step(closure)
|
|
||||||
return W.detach().numpy()
|
|
||||||
|
|
||||||
|
|
||||||
ESTIMATORS = {"lsq": _fit_lsq, "logit": _fit_logit}
|
|
||||||
|
|
||||||
|
|
||||||
def _design(reps: np.ndarray, mu: np.ndarray, sd: np.ndarray) -> np.ndarray:
|
|
||||||
"""(T, N, D) -> (T*N, D+1): standardised features plus a bias column."""
|
|
||||||
flat = reps.reshape(-1, reps.shape[-1]).astype(np.float64)
|
|
||||||
z = (flat - mu) / sd
|
|
||||||
return np.concatenate([z, np.ones((z.shape[0], 1))], axis=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]:
|
|
||||||
"""(per-entity accuracy, per-step accuracy after averaging the entity scores).
|
|
||||||
|
|
||||||
The per-step vote only exists when every entity shares one label; a per-entity
|
|
||||||
target such as the coupling row has no step-level answer to vote on.
|
|
||||||
"""
|
|
||||||
ent = float((scores.argmax(-1) == lab).mean())
|
|
||||||
step = float((scores.mean(1).argmax(-1) == step_lab).mean()) if step_lab is not None else float("nan")
|
|
||||||
return ent, step
|
|
||||||
|
|
||||||
|
|
||||||
def probe(reps: np.ndarray, labels: np.ndarray, switched: list[bool], n_regimes: int,
|
|
||||||
split: float = SPLIT, n_null: int = 20, seed: int = 0,
|
|
||||||
estimator: str = "lsq", center: bool = False) -> dict:
|
|
||||||
"""Linear decode from a representation onto a categorical target, split by time.
|
|
||||||
|
|
||||||
`labels` is either one label per step, shape (T,) -- the regime id -- or one per
|
|
||||||
entity per step, shape (T, N) -- the coupling row the current regime hands that
|
|
||||||
entity. The test split is a suffix in time, never a random subset, so the probe
|
|
||||||
cannot memorise steps adjacent to the ones it is scored on. Chance is measured,
|
|
||||||
not assumed, by two nulls that both refit the probe from scratch.
|
|
||||||
"""
|
|
||||||
if center:
|
|
||||||
# subtract each entity's own mean, computed on the probe-train prefix only.
|
|
||||||
# M is dominated by stable per-entity identity (the particle's type); if a
|
|
||||||
# regime code is hiding underneath that offset, this is what exposes it.
|
|
||||||
reps = reps - reps[:int(reps.shape[0] * split)].mean(0, keepdims=True)
|
|
||||||
T, N = reps.shape[0], reps.shape[1]
|
|
||||||
per_step = labels.ndim == 1
|
|
||||||
lab = np.repeat(labels[:, None], N, axis=1) if per_step else labels
|
|
||||||
cut = int(T * split)
|
|
||||||
tr, te = slice(0, cut), slice(cut, T)
|
|
||||||
fit = ESTIMATORS[estimator]
|
|
||||||
|
|
||||||
flat_tr = reps[tr].reshape(-1, reps.shape[-1]).astype(np.float64)
|
|
||||||
mu, sd = flat_tr.mean(0), flat_tr.std(0) + 1e-12
|
|
||||||
|
|
||||||
def fit_eval(z: np.ndarray) -> tuple[float, float, np.ndarray]:
|
|
||||||
W = fit(_design(reps[tr], mu, sd), z[tr].reshape(-1), n_regimes)
|
|
||||||
s = _scores(reps[te], W, mu, sd)
|
|
||||||
return _accuracy(s, lab[te], labels[te] if per_step else None) + (s,)
|
|
||||||
|
|
||||||
ent, step, s_te = fit_eval(lab)
|
|
||||||
|
|
||||||
# null 1: permute the step-level labels, keeping the 16 entities of a step together
|
|
||||||
# null 2: circularly shift the label sequence, which also keeps each regime's
|
|
||||||
# 40-80 step block structure intact -- the stricter of the two, because a
|
|
||||||
# probe that merely tracks slow drift still scores at this level
|
|
||||||
rng = np.random.default_rng(seed)
|
|
||||||
shuf, shift = [], []
|
|
||||||
for _ in range(n_null):
|
|
||||||
shuf.append(fit_eval(rng.permutation(lab))[0])
|
|
||||||
k = int(rng.integers(T // 10, T - T // 10))
|
|
||||||
shift.append(fit_eval(np.roll(lab, k, axis=0))[0])
|
|
||||||
|
|
||||||
# latency: steps from a switch until the decoded regime first matches the true one,
|
|
||||||
# measured on the test split only, and censored at the next switch
|
|
||||||
sw = [i for i, f in enumerate(switched[cut:]) if f]
|
|
||||||
lat, censored = [], 0
|
|
||||||
if per_step:
|
|
||||||
decoded, true = s_te.mean(1).argmax(-1), labels[te]
|
|
||||||
for a, b in zip(sw, sw[1:] + [T - cut]):
|
|
||||||
hit = next((k for k in range(b - a) if decoded[a + k] == true[a]), None)
|
|
||||||
if hit is None:
|
|
||||||
censored += 1
|
|
||||||
else:
|
|
||||||
lat.append(hit)
|
|
||||||
return dict(
|
|
||||||
estimator=estimator, centered=center, acc_entity=ent, acc_step=step,
|
|
||||||
chance_shuffle=float(np.mean(shuf)), chance_shuffle_max=float(np.max(shuf)),
|
|
||||||
chance_shift=float(np.mean(shift)), chance_shift_max=float(np.max(shift)),
|
|
||||||
n_test_steps=int(T - cut), n_test_switches=len(sw),
|
|
||||||
latency=float(np.mean(lat)) if lat else float("nan"),
|
|
||||||
latency_median=float(np.median(lat)) if lat else float("nan"),
|
|
||||||
censored=censored,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def persistence(reps: np.ndarray, max_lag: int = 60) -> dict:
|
|
||||||
"""Lag-1 autocorrelation and the lag where it falls below 1/e, per channel.
|
|
||||||
|
|
||||||
Model-agnostic, so `h` and `M` are measured the same way. It answers what the
|
|
||||||
state is doing when the regime is not decodable from it: a large integration
|
|
||||||
time means the GRP is running a temporal filter, not a regime classifier.
|
|
||||||
"""
|
|
||||||
x = reps - reps.mean(0, keepdims=True)
|
|
||||||
sd = x.std(0) + 1e-12
|
|
||||||
ac = [float((x[:-k] * x[k:]).mean(0).__truediv__(sd * sd).mean()) for k in range(1, max_lag + 1)]
|
|
||||||
tau = next((k + 1 for k, v in enumerate(ac) if v < np.exp(-1.0)), max_lag)
|
|
||||||
return dict(lag1=ac[0], tau=tau, ac=ac[:20])
|
|
||||||
|
|
||||||
|
|
||||||
# -- driver ----------------------------------------------------------------------
|
|
||||||
|
|
||||||
def run_one(name: str, seed: int, train_steps: int = TRAIN_STEPS, frozen_steps: int = FROZEN_STEPS,
|
|
||||||
window: int = 20, bptt: int = 20, lr: float = 1e-3, hidden: int = 32,
|
|
||||||
kappa: float = 4.0, omega: float = 10.0, freeze_affect: bool = False,
|
|
||||||
probes: bool = True, stateless: bool = False) -> dict:
|
|
||||||
spec, wcfg, world, org = _build(name, seed, hidden, omega, kappa)
|
|
||||||
if window >= wcfg.t_min:
|
|
||||||
raise ValueError(f"window={window} must be < t_min={wcfg.t_min}")
|
|
||||||
affect, memory, tr = _train(spec, wcfg, world, org, train_steps, bptt, lr, stateless)
|
|
||||||
fr = _frozen(spec, wcfg, world, org, affect, memory, frozen_steps, freeze_affect, stateless)
|
|
||||||
|
|
||||||
labels = np.asarray(fr["regimes"])
|
|
||||||
which = "M" if fr["M"] is not None else "h"
|
|
||||||
out = dict(
|
|
||||||
condition=name + ("_nostate" if stateless else ""), seed=seed,
|
|
||||||
train_steps=train_steps, frozen_steps=frozen_steps,
|
|
||||||
freeze_affect=freeze_affect, stateless=stateless,
|
|
||||||
n_params_rp=sum(p.numel() for p in org.rp.parameters()),
|
|
||||||
trained=_metrics(tr["losses"], tr["switched"], tr["arousals"], window),
|
|
||||||
frozen=_metrics(fr["losses"], fr["switched"], fr["arousals"], window),
|
|
||||||
frozen_bit_identical=fr["frozen_bit_identical"], n_params=fr["n_params"],
|
|
||||||
dM_min=fr["dM_min"], dM_mean=fr["dM_mean"], probe_on=which,
|
|
||||||
)
|
|
||||||
if not probes:
|
|
||||||
return out
|
|
||||||
# every variant on every representation the condition has: `M` is the GRP's state,
|
|
||||||
# `h` the RP output it is built from. Reporting `h` for the GRP too makes the
|
|
||||||
# comparison within one organism, holding the weights fixed.
|
|
||||||
got, pers = {}, {}
|
|
||||||
for tag, rep in (("M", fr["M"]), ("h", fr["h"])):
|
|
||||||
if rep is None:
|
|
||||||
continue
|
|
||||||
args = (rep, labels, fr["switched"], wcfg.n_regimes)
|
|
||||||
got[f"{tag}_lsq"] = probe(*args, seed=seed)
|
|
||||||
got[f"{tag}_lsq_centered"] = probe(*args, seed=seed, center=True)
|
|
||||||
got[f"{tag}_logit"] = probe(*args, seed=seed, n_null=5, estimator="logit")
|
|
||||||
for c in range(wcfg.n_types): # the coupling this entity's own type feels
|
|
||||||
got[f"{tag}_couple{c}"] = probe(rep, fr["couple"][:, :, c], fr["switched"],
|
|
||||||
3, seed=seed, n_null=10)
|
|
||||||
pers[tag] = persistence(rep)
|
|
||||||
out["probes"] = got
|
|
||||||
out["persistence"] = pers
|
|
||||||
out["gate"] = fr["gate"]
|
|
||||||
out["probe"] = got[f"{which}_lsq"] # headline
|
|
||||||
return out
|
|
||||||
|
|
||||||
|
|
||||||
def norm_table(results: list[dict], key: str = "frozen") -> str:
|
|
||||||
"""recovery[k] / steady, normalised per seed before averaging.
|
|
||||||
|
|
||||||
The raw curves are not comparable across conditions whose steady error differs
|
|
||||||
3x; this asks the shape question -- how far above its own floor does a condition
|
|
||||||
go after a switch, and does it come back down.
|
|
||||||
"""
|
|
||||||
by: dict[str, list[dict]] = {}
|
|
||||||
for r in results:
|
|
||||||
by.setdefault(r["condition"], []).append(r)
|
|
||||||
idxs = list(range(0, 20, 2)) + [19]
|
|
||||||
lines = [f"{'condition':<12}" + "".join(f"{'@' + str(i):>7}" for i in idxs),
|
|
||||||
"-" * (12 + 7 * len(idxs))]
|
|
||||||
for name, rs in by.items():
|
|
||||||
ratios = [[r[key]["recovery"][i] / r[key]["steady"] for i in idxs] for r in rs]
|
|
||||||
lines.append(f"{name:<12}" + "".join(f"{statistics.fmean(c):>7.2f}" for c in zip(*ratios)))
|
|
||||||
return "\n".join(lines)
|
|
||||||
|
|
||||||
|
|
||||||
def table(results: list[dict], key: str = "frozen") -> str:
|
|
||||||
by: dict[str, list[dict]] = {}
|
|
||||||
for r in results:
|
|
||||||
by.setdefault(r["condition"], []).append(r)
|
|
||||||
idxs = [0, 1, 2, 5, 10, 19]
|
|
||||||
head = "".join(f"{'rec@' + str(i):>11}" for i in idxs)
|
|
||||||
lines = [f"{'condition':<12}{'steady':>11}{'(sd)':>11}{'min':>11}{'max':>11}{head}",
|
|
||||||
"-" * (12 + 44 + 11 * len(idxs))]
|
|
||||||
for name, rs in by.items():
|
|
||||||
st = [r[key]["steady"] for r in rs]
|
|
||||||
row = "".join(f"{statistics.fmean(r[key]['recovery'][i] for r in rs):>11.3e}" for i in idxs)
|
|
||||||
sd = statistics.stdev(st) if len(st) > 1 else 0.0
|
|
||||||
lines.append(f"{name:<12}{statistics.fmean(st):>11.3e}{sd:>11.3e}"
|
|
||||||
f"{min(st):>11.3e}{max(st):>11.3e}{row}")
|
|
||||||
return "\n".join(lines)
|
|
||||||
|
|
||||||
|
|
||||||
def main() -> None:
|
|
||||||
ap = argparse.ArgumentParser()
|
|
||||||
ap.add_argument("--conditions", default="rp_only,grp_k0")
|
|
||||||
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("--window", type=int, default=20)
|
|
||||||
ap.add_argument("--lr", type=float, default=1e-3)
|
|
||||||
ap.add_argument("--freeze-affect", action="store_true",
|
|
||||||
help="also pin (valence, arousal) in the frozen phase, so a frozen "
|
|
||||||
"rp_only really is a fixed function of the observation")
|
|
||||||
ap.add_argument("--no-probes", action="store_true")
|
|
||||||
ap.add_argument("--ablate-state", action="store_true",
|
|
||||||
help="hand the organism an empty memory every step: same parameters, "
|
|
||||||
"no state carried. Separates memory from the GRP's extra capacity.")
|
|
||||||
ap.add_argument("--out", default="results/frozen.json")
|
|
||||||
a = ap.parse_args()
|
|
||||||
|
|
||||||
results = []
|
|
||||||
for name in a.conditions.split(","):
|
|
||||||
for seed in (int(s) for s in a.seeds.split(",")):
|
|
||||||
r = run_one(name, seed, a.train_steps, a.frozen_steps, window=a.window, lr=a.lr,
|
|
||||||
freeze_affect=a.freeze_affect, probes=not a.no_probes,
|
|
||||||
stateless=a.ablate_state)
|
|
||||||
f = r["frozen"]
|
|
||||||
msg = (f"{r['condition']:<18} seed={seed} frozen_steady={f['steady']:.3e} "
|
|
||||||
f"rec@0={f['recovery'][0]:.3e} rec@10={f['recovery'][10]:.3e}")
|
|
||||||
if "probe" in r:
|
|
||||||
p = r["probe"]
|
|
||||||
msg += (f" probe({r['probe_on']})={p['acc_entity']:.3f} "
|
|
||||||
f"chance={p['chance_shift']:.3f} lat={p['latency']:.1f}")
|
|
||||||
print(msg, flush=True)
|
|
||||||
results.append(r)
|
|
||||||
Path(a.out).parent.mkdir(parents=True, exist_ok=True)
|
|
||||||
Path(a.out).write_text(json.dumps(results, indent=1))
|
|
||||||
for key in ("trained", "frozen"):
|
|
||||||
print(f"\n{key} phase:"); print(table(results, key))
|
|
||||||
print(f"{key} recovery / steady:"); print(norm_table(results, key))
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
main()
|
|
||||||
-437
@@ -1,437 +0,0 @@
|
|||||||
"""Task 9 Part 2: how many steps of history does it take to identify the regime?
|
|
||||||
|
|
||||||
`T_id` is a property of the *domain*, not of our architecture, so nothing in this
|
|
||||||
file constructs an Organism. It rolls the world out and asks: given the last `L`
|
|
||||||
observations an observer actually has at step `t`, how well can the regime in force
|
|
||||||
at `t` be decoded?
|
|
||||||
|
|
||||||
What the observer has at step t, and nothing more:
|
|
||||||
|
|
||||||
* the coordinates c_{t-L+1} .. c_t (the current one included -- it is observed)
|
|
||||||
* therefore the displacements d_s = wrap(c_{s+1} - c_s) for s = t-L+1 .. t-1
|
|
||||||
|
|
||||||
`d_t` is *not* available: that is the quantity the organism is asked to predict, and
|
|
||||||
handing it to the decoder would be handing over the answer. So `L = 1` is the
|
|
||||||
instantaneous configuration alone -- the read-off `results/frozen.md` §2 measured at
|
|
||||||
+0.05 over chance -- and each extra step of window buys exactly one more observed
|
|
||||||
displacement.
|
|
||||||
|
|
||||||
## The feature sets, and why the physics one is a fair stand-in for optimal
|
|
||||||
|
|
||||||
The world's dynamics are
|
|
||||||
|
|
||||||
d_i(s) = sum_c K[t_i, c] * B_i^c(s) + eps, B_i^c(s) = dt * sum_{j: t_j = c} kern(r_ij) r_ij
|
|
||||||
|
|
||||||
with `kern` the fixed radial kernel and `eps ~ N(0, noise^2)`. `B` is the *message
|
|
||||||
basis*: everything about the configuration that the coupling matrix multiplies. It is
|
|
||||||
computable from the coordinates alone, so it is observer-side information, and it is
|
|
||||||
the same decomposition `ceilings.py` fits against. `_check_basis` asserts the
|
|
||||||
reconstruction is exact.
|
|
||||||
|
|
||||||
Given that model, the log-likelihood of regime `g` from the window's displacements is
|
|
||||||
|
|
||||||
-1/(2 noise^2) * sum_s sum_i || d_i(s) - sum_c K_g[t_i,c] B_i^c(s) ||^2
|
|
||||||
= const + (1/noise^2) * sum_c K_g[t_i,c] <d, B^c> - (1/2noise^2) * sum_{c,c'} K_g[t_i,c] K_g[t_i,c'] <B^c, B^c'>
|
|
||||||
|
|
||||||
which is **affine in the statistics `<d, B^c>` and `<B^c, B^c'>`, with coefficients
|
|
||||||
that depend on `g` and on the entity's own type**. So a linear classifier on those
|
|
||||||
statistics, interacted with the type one-hot, can express the exact Bayes rule. That
|
|
||||||
is what `phys` is, and it is why it is a fair stand-in for "optimal" rather than a
|
|
||||||
weak probe that would understate the difficulty. `bayes` computes the same rule in
|
|
||||||
closed form, with the true coupling matrices handed to it, as a cross-check on the
|
|
||||||
fit: `phys` should track it and must not beat it by much.
|
|
||||||
|
|
||||||
`lin` and `mlp` are the honest non-omniscient decoders -- least squares and a
|
|
||||||
two-layer MLP on the raw window (the per-frame features at every step of the window,
|
|
||||||
the observed displacements, the type one-hot). They know no coupling matrices. If they
|
|
||||||
saturate where `bayes` does, the saturation is the domain's and not a decoder's
|
|
||||||
limitation.
|
|
||||||
|
|
||||||
## The headline: how much does history add over the present?
|
|
||||||
|
|
||||||
The number that decides whether memory can pay is not where accuracy saturates. It is
|
|
||||||
`accuracy(L) - accuracy(1)`. `L = 1` is the present-only baseline: the current frame,
|
|
||||||
no displacement, no history. Three cases a hidden variable can fall into --
|
|
||||||
|
|
||||||
1. no evidence anywhere: nothing helps, memory included
|
|
||||||
2. evidence already in the present: history is *redundant* and feedforward suffices,
|
|
||||||
however identifiable the variable is
|
|
||||||
3. evidence only in the past: memory is required (card counting is the pure case)
|
|
||||||
|
|
||||||
-- and only case 3 gives per-entity state a job. `T_id` is a secondary quantity that
|
|
||||||
matters only once `accuracy(L) - accuracy(1)` is materially above zero.
|
|
||||||
|
|
||||||
This makes the *strength of the L = 1 decoder* the load-bearing choice, because an
|
|
||||||
underpowered present-only baseline inflates the history gain. So the per-frame feature
|
|
||||||
block (`_frame`) carries every rotation-invariant scalar the message basis misses --
|
|
||||||
the kernel mass and the kernel-weighted spread per neighbour type, alongside `B`
|
|
||||||
itself -- and `L = 1` and `L = 40` are given the *same* per-frame features and the
|
|
||||||
same decoder, differing only in how many frames. A better present-only decoder could
|
|
||||||
only shrink the reported gain, never grow it.
|
|
||||||
|
|
||||||
Chance is measured the way `frozen.py` measures it: two nulls, both refitting from
|
|
||||||
scratch -- a label shuffle, and a circular shift that preserves each regime's block
|
|
||||||
structure and is therefore the stricter of the two.
|
|
||||||
|
|
||||||
uv run python identify.py --out results/identify.json
|
|
||||||
"""
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import argparse
|
|
||||||
import json
|
|
||||||
import statistics
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
import numpy as np
|
|
||||||
import torch
|
|
||||||
from torch import nn
|
|
||||||
|
|
||||||
from particles import ParticleConfig, ParticleWorld, wrapped_diff
|
|
||||||
|
|
||||||
LS = (1, 2, 3, 5, 10, 20, 40)
|
|
||||||
SEEDS = (0, 1, 2, 3, 4, 5, 6, 7)
|
|
||||||
STEPS = 4000
|
|
||||||
SPLIT = 0.7
|
|
||||||
|
|
||||||
|
|
||||||
# -- the world, rolled out -------------------------------------------------------
|
|
||||||
|
|
||||||
def rollout(cfg: ParticleConfig, steps: int) -> dict:
|
|
||||||
"""Coordinates, observed displacements, the message basis, and the true regime.
|
|
||||||
|
|
||||||
`coords[t]` is what an observer sees at step t; `disp[t] = wrap(coords[t+1] -
|
|
||||||
coords[t])` is what it sees *after* step t resolves, so at step t the observer has
|
|
||||||
`disp[:t]` and not `disp[t]`. `regime[t]` is the regime that generated `disp[t]`.
|
|
||||||
"""
|
|
||||||
w = ParticleWorld(cfg)
|
|
||||||
coords, disp, regimes = [], [], []
|
|
||||||
for _ in range(steps):
|
|
||||||
obs = w.step()
|
|
||||||
coords.append(obs.coords)
|
|
||||||
regimes.append(obs.regime)
|
|
||||||
disp.append(wrapped_diff(torch.stack([obs.coords, w.coords]))[0, 1]) # wrap(c_{t+1} - c_t)
|
|
||||||
C = torch.stack(coords) # (T, N, 2)
|
|
||||||
D = torch.stack(disp) # (T, N, 2)
|
|
||||||
B = torch.stack([_basis(c, w.types, cfg) for c in C]) # (T, N, n_types, 2)
|
|
||||||
F = torch.stack([_frame(c, w.types, cfg) for c in C]) # (T, N, 4 * n_types)
|
|
||||||
K = torch.stack(w.regimes) # (n_regimes, n_types, n_types)
|
|
||||||
return dict(coords=C, disp=D, basis=B, frame=F, regimes=np.asarray(regimes),
|
|
||||||
types=w.types, K=K, cfg=cfg)
|
|
||||||
|
|
||||||
|
|
||||||
def _basis(coords: torch.Tensor, types: torch.Tensor, cfg: ParticleConfig) -> torch.Tensor:
|
|
||||||
"""B[i, c] = dt * sum_{j : t_j = c} kern(r_ij) r_ij, the message the coupling multiplies."""
|
|
||||||
r = wrapped_diff(coords)
|
|
||||||
kern = torch.exp(-(r ** 2).sum(-1) / cfg.sigma ** 2)
|
|
||||||
kern.fill_diagonal_(0.0)
|
|
||||||
wr = cfg.dt * kern[:, :, None] * r # (N,N,2)
|
|
||||||
onehot = nn.functional.one_hot(types, cfg.n_types).to(wr.dtype) # (N, n_types)
|
|
||||||
return torch.einsum("ijd,jc->icd", wr, onehot) # (N, n_types, 2)
|
|
||||||
|
|
||||||
|
|
||||||
def _frame(coords: torch.Tensor, types: torch.Tensor, cfg: ParticleConfig) -> torch.Tensor:
|
|
||||||
"""Everything one frame says about the configuration, per entity and neighbour type.
|
|
||||||
|
|
||||||
The message basis `B` is a first moment and is therefore blind to arrangement that
|
|
||||||
cancels by symmetry -- a ring of same-type neighbours contributes almost nothing to
|
|
||||||
`B` however tight it is. Since `L = 1` is the present-only baseline the whole
|
|
||||||
history gain is measured against, it must not be handicapped by that blindness, so
|
|
||||||
the frame also carries the two rotation-invariant scalars per neighbour type: the
|
|
||||||
kernel mass (how much of type c is nearby) and the kernel-weighted spread (how far
|
|
||||||
out it sits). `L = 1` and `L = 40` see the same per-frame features.
|
|
||||||
"""
|
|
||||||
r = wrapped_diff(coords)
|
|
||||||
d2 = (r ** 2).sum(-1)
|
|
||||||
kern = torch.exp(-d2 / cfg.sigma ** 2)
|
|
||||||
kern.fill_diagonal_(0.0)
|
|
||||||
onehot = nn.functional.one_hot(types, cfg.n_types).to(r.dtype) # (N, n_types)
|
|
||||||
B = torch.einsum("ijd,jc->icd", cfg.dt * kern[:, :, None] * r, onehot) # (N, n_types, 2)
|
|
||||||
mass = kern @ onehot # (N, n_types)
|
|
||||||
spread = (kern * d2) @ onehot # (N, n_types)
|
|
||||||
return torch.cat([B.reshape(len(r), -1), mass, spread], dim=-1)
|
|
||||||
|
|
||||||
|
|
||||||
def det(world: dict, regimes: np.ndarray) -> torch.Tensor:
|
|
||||||
"""The deterministic displacement each step would have had under `regimes[t]`."""
|
|
||||||
krow = world["K"][torch.as_tensor(regimes)][:, world["types"], :] # (T, N, n_types)
|
|
||||||
return torch.einsum("tic,ticd->tid", krow, world["basis"])
|
|
||||||
|
|
||||||
|
|
||||||
def _check_basis(world: dict) -> float:
|
|
||||||
"""Self-check: the basis must reproduce the world's own dynamics up to the noise.
|
|
||||||
|
|
||||||
The analogue of `ceilings.py`'s row A. If this residual is not the noise variance
|
|
||||||
then `B` is not the world's message basis and every number below is meaningless.
|
|
||||||
"""
|
|
||||||
resid = float(((det(world, world["regimes"]) - world["disp"]) ** 2).mean())
|
|
||||||
floor = world["cfg"].noise ** 2
|
|
||||||
assert abs(resid - floor) < 0.03 * floor, f"basis residual {resid:.3e} != noise^2 {floor:.3e}"
|
|
||||||
return resid
|
|
||||||
|
|
||||||
|
|
||||||
# -- features --------------------------------------------------------------------
|
|
||||||
|
|
||||||
def features(world: dict, L: int, kind: str) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
|
|
||||||
"""(X, y, t_index) for every step at which a full window of L observations exists.
|
|
||||||
|
|
||||||
Rows are per entity: X has shape (T', N, F). `y` is the regime at the step being
|
|
||||||
decoded. The window at step t covers observations t-L+1 .. t, i.e. displacements
|
|
||||||
t-L+1 .. t-1 -- never `d_t`.
|
|
||||||
"""
|
|
||||||
B, D = world["basis"].numpy(), world["disp"].numpy()
|
|
||||||
Fr = world["frame"].numpy()
|
|
||||||
T, N, C, _ = B.shape
|
|
||||||
ts = np.arange(L - 1, T)
|
|
||||||
onehot = nn.functional.one_hot(world["types"], C).numpy().astype(np.float64) # (N, C)
|
|
||||||
|
|
||||||
if kind == "raw":
|
|
||||||
cols = []
|
|
||||||
for k in range(L): # the per-frame features at each step
|
|
||||||
cols.append(Fr[ts - (L - 1) + k])
|
|
||||||
for k in range(L - 1): # the displacements the observer has seen
|
|
||||||
cols.append(D[ts - (L - 1) + k])
|
|
||||||
cols.append(np.broadcast_to(onehot, (len(ts), N, C)))
|
|
||||||
X = np.concatenate(cols, axis=-1)
|
|
||||||
elif kind == "phys":
|
|
||||||
# the sufficient statistics of the Gaussian likelihood, summed over the window,
|
|
||||||
# interacted with the entity's own type so the per-type coupling row is separable
|
|
||||||
db = np.zeros((len(ts), N, C))
|
|
||||||
bb = np.zeros((len(ts), N, C * (C + 1) // 2))
|
|
||||||
for k in range(L - 1):
|
|
||||||
s = ts - (L - 1) + k
|
|
||||||
db += np.einsum("tid,ticd->tic", D[s], B[s])
|
|
||||||
pairs = [(a, b) for a in range(C) for b in range(a, C)]
|
|
||||||
bb += np.stack([np.einsum("tid,tid->ti", B[s][:, :, a], B[s][:, :, b])
|
|
||||||
for a, b in pairs], axis=-1)
|
|
||||||
stats = np.concatenate([db, bb], axis=-1) # (T', N, C + C(C+1)/2)
|
|
||||||
X = (stats[:, :, None, :] * onehot[None, :, :, None]).reshape(len(ts), N, -1)
|
|
||||||
else:
|
|
||||||
raise ValueError(kind)
|
|
||||||
return X.astype(np.float64), world["regimes"][ts], ts
|
|
||||||
|
|
||||||
|
|
||||||
# -- decoders --------------------------------------------------------------------
|
|
||||||
|
|
||||||
def _standardise(X: np.ndarray, cut: int) -> np.ndarray:
|
|
||||||
flat = X[:cut].reshape(-1, X.shape[-1])
|
|
||||||
mu, sd = flat.mean(0), flat.std(0) + 1e-12
|
|
||||||
return np.concatenate([(X - mu) / sd, np.ones(X.shape[:2] + (1,))], axis=-1)
|
|
||||||
|
|
||||||
|
|
||||||
def _fit_lsq(X: np.ndarray, y: np.ndarray, R: int, ridge: float = 1e-6) -> np.ndarray:
|
|
||||||
G = X.T @ X
|
|
||||||
lam = ridge * np.trace(G) / X.shape[1]
|
|
||||||
return np.linalg.solve(G + lam * np.eye(X.shape[1]), X.T @ np.eye(R)[y])
|
|
||||||
|
|
||||||
|
|
||||||
def _fit_logit(X: np.ndarray, y: np.ndarray, R: int, l2: float = 1e-6) -> np.ndarray:
|
|
||||||
"""Multinomial logistic, LBFGS with strong Wolfe -- as `frozen.py` fits its probe.
|
|
||||||
|
|
||||||
Least squares onto a one-hot target is a poor classifier on the physics statistics,
|
|
||||||
which are products of small numbers and heavy-tailed; it understates what the
|
|
||||||
feature set can express. The `phys` set is meant to be a fair stand-in for optimal,
|
|
||||||
so it gets the estimator that actually maximises the classification objective.
|
|
||||||
X already carries the bias column, so no separate intercept.
|
|
||||||
"""
|
|
||||||
Xt, yt = torch.tensor(X), torch.tensor(y, dtype=torch.long)
|
|
||||||
W = torch.zeros(X.shape[1], R, dtype=torch.float64, requires_grad=True)
|
|
||||||
opt = torch.optim.LBFGS([W], max_iter=300, tolerance_grad=1e-12,
|
|
||||||
line_search_fn="strong_wolfe")
|
|
||||||
|
|
||||||
def closure():
|
|
||||||
opt.zero_grad()
|
|
||||||
loss = nn.functional.cross_entropy(Xt @ W, yt) + l2 * (W[:-1] ** 2).sum()
|
|
||||||
loss.backward()
|
|
||||||
return loss
|
|
||||||
|
|
||||||
opt.step(closure)
|
|
||||||
return W.detach().numpy()
|
|
||||||
|
|
||||||
|
|
||||||
def _fit_mlp(X: np.ndarray, y: np.ndarray, R: int, hidden: int = 128, epochs: int = 40,
|
|
||||||
seed: int = 0) -> callable:
|
|
||||||
"""Two-layer MLP -- the capacity check the brief asks for before concluding.
|
|
||||||
|
|
||||||
A linear probe that never rises is not evidence the regime is unidentifiable, so
|
|
||||||
the raw feature set is also given a nonlinear decoder. Full-batch Adam; the split
|
|
||||||
is a time suffix, so there is no shuffling to seed beyond the initialisation.
|
|
||||||
"""
|
|
||||||
torch.manual_seed(seed)
|
|
||||||
net = nn.Sequential(nn.Linear(X.shape[1], hidden), nn.ReLU(),
|
|
||||||
nn.Linear(hidden, hidden), nn.ReLU(), nn.Linear(hidden, R)).double()
|
|
||||||
Xt, yt = torch.tensor(X), torch.tensor(y, dtype=torch.long)
|
|
||||||
opt = torch.optim.Adam(net.parameters(), lr=3e-3, weight_decay=1e-5)
|
|
||||||
n, bs = len(Xt), 4096
|
|
||||||
g = torch.Generator().manual_seed(seed)
|
|
||||||
for _ in range(epochs):
|
|
||||||
perm = torch.randperm(n, generator=g)
|
|
||||||
for i in range(0, n, bs):
|
|
||||||
idx = perm[i:i + bs]
|
|
||||||
opt.zero_grad()
|
|
||||||
nn.functional.cross_entropy(net(Xt[idx]), yt[idx]).backward()
|
|
||||||
opt.step()
|
|
||||||
net.eval()
|
|
||||||
return lambda Z: net(torch.tensor(Z)).detach().numpy()
|
|
||||||
|
|
||||||
|
|
||||||
def decode(X: np.ndarray, y: np.ndarray, n_regimes: int, estimator: str,
|
|
||||||
split: float = SPLIT, n_null: int = 10, seed: int = 0) -> dict:
|
|
||||||
"""Fit on a time prefix, score on the suffix, with chance measured by two nulls.
|
|
||||||
|
|
||||||
Reported twice: `entity` is one classification per entity per step, `step` pools
|
|
||||||
the N entities of a step by averaging their scores -- what an observer watching
|
|
||||||
the whole world would do. The regime is a global variable, so `step` is the
|
|
||||||
domain-level number and `entity` is the one a per-entity memory could hold.
|
|
||||||
"""
|
|
||||||
T = X.shape[0]
|
|
||||||
cut = int(T * split)
|
|
||||||
Z = _standardise(X, cut)
|
|
||||||
F = Z.shape[-1]
|
|
||||||
flat = lambda A: A.reshape(-1, F)
|
|
||||||
|
|
||||||
def fit_eval(lab: np.ndarray) -> tuple[float, float]:
|
|
||||||
ytr = np.repeat(lab[:cut, None], X.shape[1], 1).reshape(-1)
|
|
||||||
if estimator in ("lsq", "logit"):
|
|
||||||
fit = _fit_lsq if estimator == "lsq" else _fit_logit
|
|
||||||
W = fit(flat(Z[:cut]), ytr, n_regimes)
|
|
||||||
s = (flat(Z[cut:]) @ W).reshape(T - cut, X.shape[1], n_regimes)
|
|
||||||
elif estimator == "mlp":
|
|
||||||
f = _fit_mlp(flat(Z[:cut]), ytr, n_regimes, seed=seed)
|
|
||||||
s = f(flat(Z[cut:])).reshape(T - cut, X.shape[1], n_regimes)
|
|
||||||
else:
|
|
||||||
raise ValueError(estimator)
|
|
||||||
ent = float((s.argmax(-1) == lab[cut:, None]).mean())
|
|
||||||
step = float((s.mean(1).argmax(-1) == lab[cut:]).mean())
|
|
||||||
return ent, step
|
|
||||||
|
|
||||||
ent, step = fit_eval(y)
|
|
||||||
rng = np.random.default_rng(seed)
|
|
||||||
shuf, shift = [], []
|
|
||||||
for _ in range(n_null):
|
|
||||||
shuf.append(fit_eval(rng.permutation(y)))
|
|
||||||
k = int(rng.integers(T // 10, T - T // 10))
|
|
||||||
shift.append(fit_eval(np.roll(y, k)))
|
|
||||||
return dict(estimator=estimator, acc_entity=ent, acc_step=step,
|
|
||||||
chance_entity=float(np.mean([a for a, _ in shuf])),
|
|
||||||
chance_step=float(np.mean([b for _, b in shuf])),
|
|
||||||
shift_entity=float(np.mean([a for a, _ in shift])),
|
|
||||||
shift_step=float(np.mean([b for _, b in shift])),
|
|
||||||
n_test=T - cut, n_features=F)
|
|
||||||
|
|
||||||
|
|
||||||
def bayes(world: dict, L: int, split: float = SPLIT) -> dict:
|
|
||||||
"""Exact Gaussian likelihood over the window, with the true coupling matrices given.
|
|
||||||
|
|
||||||
No fitting, so no train split is needed; it is scored on the same test suffix the
|
|
||||||
fitted decoders use so the numbers sit in one column. This is the floor on `T_id`:
|
|
||||||
a decoder that knows the generative model exactly, including the four candidate
|
|
||||||
matrices, and assumes the regime is constant across the window.
|
|
||||||
"""
|
|
||||||
B, D = world["basis"], world["disp"]
|
|
||||||
T, N = B.shape[0], B.shape[1]
|
|
||||||
ts = np.arange(L - 1, T)
|
|
||||||
K = world["K"][:, world["types"], :] # (R, N, n_types)
|
|
||||||
resid = np.zeros((len(ts), N, K.shape[0]))
|
|
||||||
for k in range(L - 1):
|
|
||||||
s = torch.as_tensor(ts - (L - 1) + k)
|
|
||||||
pred = torch.einsum("ric,ticd->rtid", K, B[s]) # (R, T', N, 2)
|
|
||||||
resid += ((pred - D[s][None]) ** 2).sum(-1).permute(1, 2, 0).numpy()
|
|
||||||
y = world["regimes"][ts]
|
|
||||||
cut = int(len(ts) * split)
|
|
||||||
sc = -resid[cut:]
|
|
||||||
return dict(estimator="bayes", acc_entity=float((sc.argmax(-1) == y[cut:, None]).mean()),
|
|
||||||
acc_step=float((sc.sum(1).argmax(-1) == y[cut:]).mean()),
|
|
||||||
n_test=len(ts) - cut)
|
|
||||||
|
|
||||||
|
|
||||||
def switch_fraction(world: dict, L: int) -> float:
|
|
||||||
"""Fraction of decoded steps whose window spans a regime change.
|
|
||||||
|
|
||||||
A window longer than the regime lasts contains two regimes, and a decoder that
|
|
||||||
assumes one is then mis-specified. This is the mechanism behind `T_z < T_id`, so
|
|
||||||
it is reported alongside every accuracy.
|
|
||||||
"""
|
|
||||||
g = world["regimes"]
|
|
||||||
ts = np.arange(L - 1, len(g))
|
|
||||||
return float(np.mean([g[t - L + 1:t + 1].min() != g[t - L + 1:t + 1].max() for t in ts]))
|
|
||||||
|
|
||||||
|
|
||||||
# -- driver ----------------------------------------------------------------------
|
|
||||||
|
|
||||||
def run(seed: int, steps: int, Ls: tuple[int, ...], t_min: int, t_max: int,
|
|
||||||
estimators: tuple[str, ...]) -> list[dict]:
|
|
||||||
cfg = ParticleConfig(seed=seed, t_min=t_min, t_max=t_max)
|
|
||||||
world = rollout(cfg, steps)
|
|
||||||
resid = _check_basis(world)
|
|
||||||
out = []
|
|
||||||
for L in Ls:
|
|
||||||
row = dict(seed=seed, L=L, t_min=t_min, t_max=t_max, steps=steps,
|
|
||||||
basis_residual=resid, switch_frac=switch_fraction(world, L), decoders={})
|
|
||||||
for kind, est in (("raw", "lsq"), ("raw", "mlp"), ("phys", "logit")):
|
|
||||||
tag = {"raw/lsq": "lin", "raw/mlp": "mlp", "phys/logit": "phys"}[f"{kind}/{est}"]
|
|
||||||
if tag not in estimators:
|
|
||||||
continue
|
|
||||||
if kind == "phys" and L == 1:
|
|
||||||
continue # no displacement observed yet: the likelihood has no terms
|
|
||||||
X, y, _ = features(world, L, kind)
|
|
||||||
# the MLP is refit from scratch for every null, so its chance level is
|
|
||||||
# measured on fewer draws than the linear decoders' ten
|
|
||||||
row["decoders"][tag] = decode(X, y, cfg.n_regimes, est, seed=seed,
|
|
||||||
n_null=2 if est == "mlp" else 10)
|
|
||||||
if "bayes" in estimators and L > 1:
|
|
||||||
row["decoders"]["bayes"] = bayes(world, L)
|
|
||||||
out.append(row)
|
|
||||||
return out
|
|
||||||
|
|
||||||
|
|
||||||
def table(results: list[dict], which: str = "step") -> str:
|
|
||||||
by: dict[int, list[dict]] = {}
|
|
||||||
for r in results:
|
|
||||||
by.setdefault(r["L"], []).append(r)
|
|
||||||
tags = ["lin", "mlp", "phys", "bayes"]
|
|
||||||
head = "".join(f"{t:>18}" for t in tags)
|
|
||||||
lines = [f"per-{which} accuracy (chance in brackets), means over seeds",
|
|
||||||
f"{'L':>3}{'sw.frac':>9}{head}", "-" * (12 + 18 * len(tags))]
|
|
||||||
for L in sorted(by):
|
|
||||||
rs = by[L]
|
|
||||||
cells = ""
|
|
||||||
for t in tags:
|
|
||||||
got = [r["decoders"][t] for r in rs if t in r["decoders"]]
|
|
||||||
if not got:
|
|
||||||
cells += f"{'--':>18}"
|
|
||||||
continue
|
|
||||||
acc = statistics.fmean(g[f"acc_{which}"] for g in got)
|
|
||||||
ch = [g[f"shift_{which}"] for g in got if f"shift_{which}" in g]
|
|
||||||
cells += f"{acc:>12.3f}{('[' + format(statistics.fmean(ch), '.3f') + ']') if ch else '':>6}"
|
|
||||||
lines.append(f"{L:>3}{statistics.fmean(r['switch_frac'] for r in rs):>9.3f}{cells}")
|
|
||||||
return "\n".join(lines)
|
|
||||||
|
|
||||||
|
|
||||||
def main() -> None:
|
|
||||||
ap = argparse.ArgumentParser()
|
|
||||||
ap.add_argument("--seeds", default=",".join(map(str, SEEDS)))
|
|
||||||
ap.add_argument("--steps", type=int, default=STEPS)
|
|
||||||
ap.add_argument("--Ls", default=",".join(map(str, LS)))
|
|
||||||
ap.add_argument("--t-min", type=int, default=ParticleConfig().t_min)
|
|
||||||
ap.add_argument("--t-max", type=int, default=ParticleConfig().t_max)
|
|
||||||
ap.add_argument("--estimators", default="lin,mlp,phys,bayes")
|
|
||||||
ap.add_argument("--out", default="results/identify.json")
|
|
||||||
a = ap.parse_args()
|
|
||||||
|
|
||||||
ests = tuple(a.estimators.split(","))
|
|
||||||
Ls = tuple(int(x) for x in a.Ls.split(","))
|
|
||||||
results = []
|
|
||||||
for seed in (int(s) for s in a.seeds.split(",")):
|
|
||||||
rs = run(seed, a.steps, Ls, a.t_min, a.t_max, ests)
|
|
||||||
for r in rs:
|
|
||||||
d = r["decoders"]
|
|
||||||
msg = " ".join(f"{k}={v['acc_step']:.3f}/{v['acc_entity']:.3f}" for k, v in d.items())
|
|
||||||
print(f"seed={seed} L={r['L']:<3} sw={r['switch_frac']:.3f} {msg}", flush=True)
|
|
||||||
results.extend(rs)
|
|
||||||
Path(a.out).parent.mkdir(parents=True, exist_ok=True)
|
|
||||||
Path(a.out).write_text(json.dumps(results, indent=1))
|
|
||||||
print(); print(table(results, "step")); print(); print(table(results, "entity"))
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
main()
|
|
||||||
@@ -1,257 +0,0 @@
|
|||||||
"""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()
|
|
||||||
@@ -1,269 +0,0 @@
|
|||||||
"""psi as a continuous kernel axis: the one place a lookup cannot be built.
|
|
||||||
|
|
||||||
Where the argument stands after `scale.md` and `unseen.md`: variable N and permutation
|
|
||||||
equivariance are shared with any GNN, identity-in-the-kernel is the same statement as indexing a
|
|
||||||
lookup by type as well as offset, and generating weights from geometry is real but bounded to
|
|
||||||
relation spaces that cannot be enumerated. What is left is parameter compression where the
|
|
||||||
relation space is NOT enumerable -- and psi is the only genuinely continuous axis this
|
|
||||||
architecture has. A table over (offset x valence x arousal) has to bin the last two.
|
|
||||||
|
|
||||||
This is claim A2 of the paper arriving from the front rather than as a later chapter.
|
|
||||||
|
|
||||||
TWO MEASUREMENTS, because accuracy alone did not separate the arms in `unseen.md` and there is
|
|
||||||
no reason to expect it to here:
|
|
||||||
|
|
||||||
1. ACCURACY on a region of psi space held out of training. A binned table can interpolate
|
|
||||||
across psi bins exactly as it interpolated across offset cells, so this is expected to be
|
|
||||||
close and is not the headline.
|
|
||||||
2. COST to get there -- parameters, and samples. The CPPN shares statistical strength across
|
|
||||||
the psi axis by construction; a binned table cannot, and pays for every bin separately.
|
|
||||||
Kernel parameters: CPPN ~720 regardless of resolution; table 3600 * B^2.
|
|
||||||
|
|
||||||
THE NEGATIVE BRANCH, worth as much: if a COARSE table (B=2) plus interpolation matches the CPPN
|
|
||||||
at a fraction of the parameters, then psi-continuity buys nothing either, and the RP has no
|
|
||||||
distinguishing claim left against a GNN. That outcome ends a line of argument, which is why it
|
|
||||||
is written down before the run rather than after.
|
|
||||||
|
|
||||||
The teacher changes the kernel's SHAPE with psi, not its gain: valence rotates the spatial
|
|
||||||
frequency and arousal widens the envelope. A gain would be reproducible by scaling one shared
|
|
||||||
kernel, which is the failure mode `chess_reach.md` measured for piece type.
|
|
||||||
"""
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import argparse
|
|
||||||
import json
|
|
||||||
import math
|
|
||||||
import statistics
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
import torch
|
|
||||||
from torch import nn
|
|
||||||
|
|
||||||
from unseen import ATTR, CELLS, D, G, R, cell_of
|
|
||||||
|
|
||||||
# The interior box of psi space withheld from training, both axes. Aligned to the bin grid:
|
|
||||||
# psi in [-1,1] split into B bins puts edges at multiples of 2/B, so [0, 0.5] is exactly one bin
|
|
||||||
# at B=4 and exactly two at B=8.
|
|
||||||
#
|
|
||||||
# A TABLE CANNOT WITHHOLD ANYTHING FINER THAN ITS OWN BIN, and this favours the coarse arms
|
|
||||||
# rather than the CPPN. At B=1 the box is not held out at all -- that arm ignores psi entirely
|
|
||||||
# and its "unseen" column is just its ordinary error. At B=2 the box is half of a bin whose
|
|
||||||
# other half is trained, so the entry it reads has seen data. Only B>=4 withholds it honestly.
|
|
||||||
# Stated here rather than corrected for: correcting it would mean a different box per arm, and
|
|
||||||
# then the arms would no longer be answering the same question.
|
|
||||||
HELD = (0.0, 0.5) # overridden by --held; see main()
|
|
||||||
|
|
||||||
|
|
||||||
def psi_offsets() -> torch.Tensor:
|
|
||||||
ys, xs = torch.meshgrid(torch.arange(-R, R + 1), torch.arange(-R, R + 1), indexing="ij")
|
|
||||||
return torch.stack([xs, ys], -1).reshape(CELLS, 2).float()
|
|
||||||
|
|
||||||
|
|
||||||
class PsiTeacher(nn.Module):
|
|
||||||
"""W*(r, psi): valence rotates the frequency, arousal widens the envelope.
|
|
||||||
|
|
||||||
Both are shape changes. A psi that only scaled the kernel would be satisfiable by any model
|
|
||||||
with a gain on its output and would make the experiment vacuous.
|
|
||||||
"""
|
|
||||||
def __init__(self, seed: int = 0, kfreq: float = 0.35):
|
|
||||||
super().__init__()
|
|
||||||
g = torch.Generator().manual_seed(seed)
|
|
||||||
self.register_buffer("r", psi_offsets())
|
|
||||||
self.register_buffer("k", torch.randn(D, 2, generator=g) * kfreq)
|
|
||||||
self.register_buffer("phi", torch.rand(D, generator=g) * 2 * math.pi)
|
|
||||||
|
|
||||||
def kernel(self, psi: torch.Tensor) -> torch.Tensor:
|
|
||||||
val, aro = psi[0], psi[1]
|
|
||||||
th = val * (math.pi / 2)
|
|
||||||
rot = torch.stack([torch.stack([torch.cos(th), -torch.sin(th)]),
|
|
||||||
torch.stack([torch.sin(th), torch.cos(th)])])
|
|
||||||
k = self.k @ rot.T # (D,2) frequency rotated by valence
|
|
||||||
sigma = 3.0 * (1.0 + 0.4 * aro) # envelope widened by arousal
|
|
||||||
env = torch.exp(-(self.r * self.r).sum(-1) / (2 * sigma * sigma))[:, None]
|
|
||||||
return env * torch.cos(self.r @ k.T + self.phi) # (CELLS, D)
|
|
||||||
|
|
||||||
def forward(self, r, edge_onehot, context):
|
|
||||||
return self.kernel(context)[cell_of(r)]
|
|
||||||
|
|
||||||
|
|
||||||
class BinnedTable(nn.Module):
|
|
||||||
"""A lookup over (psi bin, offset cell): what a GNN has to do with a continuous axis.
|
|
||||||
|
|
||||||
B=1 is a table that ignores psi entirely -- the floor for this experiment, and the shape a
|
|
||||||
plain edge-type lookup actually has.
|
|
||||||
"""
|
|
||||||
def __init__(self, bins: int):
|
|
||||||
super().__init__()
|
|
||||||
self.bins = bins
|
|
||||||
self.w = nn.Parameter(torch.randn(bins * bins, CELLS, D) * 0.1)
|
|
||||||
|
|
||||||
def bin_of(self, psi: torch.Tensor) -> int:
|
|
||||||
i, j = (((psi.clamp(-1, 1) + 1) / 2 * self.bins).long().clamp(0, self.bins - 1)).tolist()
|
|
||||||
return i * self.bins + j
|
|
||||||
|
|
||||||
def forward(self, r, edge_onehot, context):
|
|
||||||
return self.w[self.bin_of(context)][cell_of(r)]
|
|
||||||
|
|
||||||
|
|
||||||
def make(arm: str, seed: int, omega: float = 2.0) -> nn.Module:
|
|
||||||
from ailed.core import RelationalPerceptron
|
|
||||||
torch.manual_seed(seed)
|
|
||||||
rp = RelationalPerceptron(ATTR, 2, 1, 2, hidden_dim=D, cppn_hidden=32, omega=omega)
|
|
||||||
if arm.startswith("table"):
|
|
||||||
rp.cppn = BinnedTable(int(arm.split("_")[1])) # "table_4" and "table_4_interp" alike
|
|
||||||
return nn.ModuleDict({"rp": rp, "out": nn.Linear(D, D)})
|
|
||||||
|
|
||||||
|
|
||||||
def untrained_bins(bins: int) -> torch.Tensor:
|
|
||||||
"""(bins*bins,) bool: bins lying wholly inside the withheld box, so never gradient-updated.
|
|
||||||
|
|
||||||
A bin only partly inside the box still sees training psi from its other part, which is why
|
|
||||||
B=1 and B=2 have nothing to fill and their `unseen` column is not really held out.
|
|
||||||
"""
|
|
||||||
t = BinnedTable(bins)
|
|
||||||
out = torch.zeros(bins * bins, dtype=torch.bool)
|
|
||||||
lo, hi = HELD
|
|
||||||
eps = 1e-4
|
|
||||||
for i in range(bins):
|
|
||||||
for j in range(bins):
|
|
||||||
x0, x1 = -1 + 2 * i / bins + eps, -1 + 2 * (i + 1) / bins - eps
|
|
||||||
y0, y1 = -1 + 2 * j / bins + eps, -1 + 2 * (j + 1) / bins - eps
|
|
||||||
corners = [torch.tensor([x, y]) for x in (x0, x1) for y in (y0, y1)]
|
|
||||||
if all(in_held(c) for c in corners):
|
|
||||||
out[t.bin_of(corners[0])] = True
|
|
||||||
return out
|
|
||||||
|
|
||||||
|
|
||||||
@torch.no_grad()
|
|
||||||
def fill_bins_by_diffusion(table: BinnedTable, held: torch.Tensor) -> None:
|
|
||||||
"""THE CONTROL THAT DECIDES WHAT THIS MEASURES, and the same one `unseen.md` needed.
|
|
||||||
|
|
||||||
A bin that never received gradient sits at its initialisation, so a table failing on the
|
|
||||||
withheld psi region is arithmetic rather than evidence. Filling those bins from their
|
|
||||||
trained neighbours in psi space asks the question that matters: does generating the kernel
|
|
||||||
from a continuous psi beat a lookup plus the obvious smoothing along the same axis?
|
|
||||||
"""
|
|
||||||
B = table.bins
|
|
||||||
grid = table.w.data.view(B, B, -1).clone()
|
|
||||||
know = (~held).view(B, B).clone()
|
|
||||||
while not know.all():
|
|
||||||
acc = torch.zeros_like(grid)
|
|
||||||
cnt = torch.zeros(B, B)
|
|
||||||
for dy, dx in ((-1, 0), (1, 0), (0, -1), (0, 1)):
|
|
||||||
src_v = torch.roll(grid * know[..., None], shifts=(dy, dx), dims=(0, 1))
|
|
||||||
src_k = torch.roll(know.float(), shifts=(dy, dx), dims=(0, 1))
|
|
||||||
if dy: # do not wrap around the psi range
|
|
||||||
(src_v[0] if dy > 0 else src_v[-1]).zero_()
|
|
||||||
(src_k[0] if dy > 0 else src_k[-1]).zero_()
|
|
||||||
if dx:
|
|
||||||
(src_v[:, 0] if dx > 0 else src_v[:, -1]).zero_()
|
|
||||||
(src_k[:, 0] if dx > 0 else src_k[:, -1]).zero_()
|
|
||||||
acc += src_v
|
|
||||||
cnt += src_k
|
|
||||||
newly = (~know) & (cnt > 0)
|
|
||||||
if not newly.any():
|
|
||||||
break
|
|
||||||
grid[newly] = acc[newly] / cnt[newly][:, None]
|
|
||||||
know |= newly
|
|
||||||
table.w.data.copy_(grid.view(B * B, CELLS, D))
|
|
||||||
|
|
||||||
|
|
||||||
def teacher(seed: int) -> nn.Module:
|
|
||||||
m = make("rp", seed + 1000)
|
|
||||||
m["rp"].cppn = PsiTeacher(seed)
|
|
||||||
for p in m.parameters():
|
|
||||||
p.requires_grad_(False)
|
|
||||||
return m
|
|
||||||
|
|
||||||
|
|
||||||
def in_held(psi: torch.Tensor) -> bool:
|
|
||||||
lo, hi = HELD
|
|
||||||
return bool(((psi >= lo) & (psi <= hi)).all())
|
|
||||||
|
|
||||||
|
|
||||||
def sample_psi(want_held: bool, gen: torch.Generator) -> torch.Tensor:
|
|
||||||
while True:
|
|
||||||
psi = torch.rand(2, generator=gen) * 2 - 1
|
|
||||||
if in_held(psi) == want_held:
|
|
||||||
return psi
|
|
||||||
|
|
||||||
|
|
||||||
def batch(want_held: bool, gen: torch.Generator, size=24, n_lo=2, n_hi=5):
|
|
||||||
out = []
|
|
||||||
for _ in range(size):
|
|
||||||
n = int(torch.randint(n_lo, n_hi + 1, (1,), generator=gen))
|
|
||||||
c = torch.randint(0, 8, (n, 2), generator=gen).float()
|
|
||||||
out.append((torch.randn(n, ATTR, generator=gen), c[None, :, :] - c[:, None, :],
|
|
||||||
torch.ones(n, n), sample_psi(want_held, gen)))
|
|
||||||
return out
|
|
||||||
|
|
||||||
|
|
||||||
def run(model, a, r, mask, psi):
|
|
||||||
edge = torch.ones(a.shape[0], a.shape[0], 1)
|
|
||||||
return model["out"](model["rp"](a, r, edge, mask, psi))
|
|
||||||
|
|
||||||
|
|
||||||
def evaluate(model, tea, data):
|
|
||||||
with torch.no_grad():
|
|
||||||
err = sum(((run(model, *d) - run(tea, *d)) ** 2).sum().item() for d in data)
|
|
||||||
ys = torch.cat([run(tea, *d) for d in data])
|
|
||||||
n = sum(d[0].shape[0] * D for d in data)
|
|
||||||
return err / n, ((ys - ys.mean(0)) ** 2).mean().item()
|
|
||||||
|
|
||||||
|
|
||||||
def one_seed(arm, steps, seed, omega):
|
|
||||||
tea, gen = teacher(seed), torch.Generator().manual_seed(seed)
|
|
||||||
model = make(arm, seed, omega)
|
|
||||||
opt = torch.optim.Adam(model.parameters(), lr=3e-3)
|
|
||||||
for _ in range(steps):
|
|
||||||
data = batch(False, gen)
|
|
||||||
loss = sum(((run(model, *d) - run(tea, *d)) ** 2).mean() for d in data) / len(data)
|
|
||||||
opt.zero_grad(); loss.backward(); opt.step()
|
|
||||||
|
|
||||||
if arm.endswith("_interp"):
|
|
||||||
fill_bins_by_diffusion(model["rp"].cppn, untrained_bins(model["rp"].cppn.bins))
|
|
||||||
|
|
||||||
ev = torch.Generator().manual_seed(seed + 5000)
|
|
||||||
seen, floor_s = evaluate(model, tea, batch(False, ev, size=64))
|
|
||||||
unseen, floor_u = evaluate(model, tea, batch(True, ev, size=64))
|
|
||||||
return {"seed": seed, "arm": arm, "seen": seen, "unseen": unseen, "floor": floor_u,
|
|
||||||
"kernel_params": sum(p.numel() for p in model["rp"].cppn.parameters())}
|
|
||||||
|
|
||||||
|
|
||||||
def main():
|
|
||||||
ap = argparse.ArgumentParser()
|
|
||||||
ap.add_argument("--arms", default="rp,table_1,table_2,table_4")
|
|
||||||
ap.add_argument("--omega", type=float, default=2.0)
|
|
||||||
ap.add_argument("--steps", type=int, default=2500)
|
|
||||||
ap.add_argument("--seeds", default="0,1,2,3,4,5")
|
|
||||||
ap.add_argument("--held", default="0.0,0.5",
|
|
||||||
help="the withheld psi box. The interior default is the easy case: every "
|
|
||||||
"bin around it is trained. A corner box (0.5,1.0) leaves neighbours "
|
|
||||||
"on two sides only, which is what sharp.md showed the offset axis was "
|
|
||||||
"sensitive to -- the earlier conclusion there flipped with the "
|
|
||||||
"hold-out structure, so this axis gets the same check.")
|
|
||||||
ap.add_argument("--out", default="results/psi.json")
|
|
||||||
args = ap.parse_args()
|
|
||||||
global HELD
|
|
||||||
HELD = tuple(float(x) for x in args.held.split(","))
|
|
||||||
|
|
||||||
rows = []
|
|
||||||
for arm in args.arms.split(","):
|
|
||||||
for s in (int(x) for x in args.seeds.split(",")):
|
|
||||||
rows.append(one_seed(arm, args.steps, s, args.omega))
|
|
||||||
r = rows[-1]
|
|
||||||
print(f"{arm:9s} seed {s} seen {r['seen']:.5f} unseen {r['unseen']:.5f}"
|
|
||||||
f" params {r['kernel_params']}", flush=True)
|
|
||||||
|
|
||||||
print(f"\npsi held out: box [{HELD[0]},{HELD[1]}]^2, omega={args.omega}")
|
|
||||||
print(f"{'arm':9s} {'seen':>9s} {'unseen':>9s} {'floor':>9s} {'kernel params':>14s}")
|
|
||||||
for arm in args.arms.split(","):
|
|
||||||
a = [r for r in rows if r["arm"] == arm]
|
|
||||||
print(f"{arm:9s} {statistics.mean([r['seen'] for r in a]):9.5f} "
|
|
||||||
f"{statistics.mean([r['unseen'] for r in a]):9.5f} "
|
|
||||||
f"{statistics.mean([r['floor'] for r in a]):9.5f} {a[0]['kernel_params']:14d}")
|
|
||||||
Path(args.out).write_text(json.dumps({"args": vars(args), "rows": rows}, indent=1))
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
main()
|
|
||||||
@@ -1,142 +0,0 @@
|
|||||||
"""Claims A1 and A2 on relational particles. Spec §8.
|
|
||||||
|
|
||||||
One continuous online stream per (condition, seed). Truncated BPTT every `bptt`
|
|
||||||
steps. Affect is updated from loss.item() so it never carries gradient.
|
|
||||||
"""
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import argparse
|
|
||||||
import json
|
|
||||||
import statistics
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
import torch
|
|
||||||
|
|
||||||
from ailed import Affect, AffectConfig, Organism, detach_memory, update
|
|
||||||
from particles import ParticleConfig, ParticleWorld, wrapped_diff
|
|
||||||
|
|
||||||
KAPPA_FLAG = "kappa" # resolved from run(kappa=...) when the value is this sentinel
|
|
||||||
|
|
||||||
CONDITIONS: dict[str, dict] = {
|
|
||||||
# A1
|
|
||||||
"rp_only": dict(memory=False, kappa=0.0, oracle="none", ctx="affect"),
|
|
||||||
"grp_k0": dict(memory=True, kappa=0.0, oracle="none", ctx="affect"),
|
|
||||||
"grp_k": dict(memory=True, kappa=KAPPA_FLAG, oracle="none", ctx="affect"),
|
|
||||||
"grp_flag": dict(memory=True, kappa=0.0, oracle="change", ctx="affect"),
|
|
||||||
"grp_regime": dict(memory=True, kappa=0.0, oracle="regime", ctx="affect"),
|
|
||||||
# control that cannot show an effect
|
|
||||||
"rp_flag": dict(memory=False, kappa=0.0, oracle="change", ctx="affect"),
|
|
||||||
# A2 (on the affect-gated model)
|
|
||||||
"grp_k_noctx": dict(memory=True, kappa=KAPPA_FLAG, oracle="none", ctx="zeros"),
|
|
||||||
"grp_k_regimectx": dict(memory=True, kappa=KAPPA_FLAG, oracle="none", ctx="regime"),
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def _context(kind: str, affect: Affect, regime: int, n_regimes: int) -> torch.Tensor | None:
|
|
||||||
if kind == "affect":
|
|
||||||
return None # Organism defaults to (valence, arousal)
|
|
||||||
if kind == "zeros":
|
|
||||||
return torch.zeros(2)
|
|
||||||
if kind == "regime":
|
|
||||||
c = torch.zeros(n_regimes); c[regime] = 1.0
|
|
||||||
return c
|
|
||||||
raise ValueError(kind)
|
|
||||||
|
|
||||||
|
|
||||||
def _metrics(losses: list[float], switched: list[bool], arousals: list[float], window: int) -> dict:
|
|
||||||
# metrics on the second half only: the first half is training warm-up
|
|
||||||
steps = len(losses)
|
|
||||||
half = steps // 2
|
|
||||||
switch_idx = [i for i in range(half, steps - window) if switched[i]]
|
|
||||||
recovery = [statistics.fmean(losses[i + k] for i in switch_idx) for k in range(window)] if switch_idx else [float("nan")] * window
|
|
||||||
steady_idx = [i for i in range(half, steps) if not any(switched[max(0, i - window):i + 1])]
|
|
||||||
steady = statistics.fmean(losses[i] for i in steady_idx) if steady_idx else float("nan")
|
|
||||||
return dict(
|
|
||||||
recovery=recovery, steady=steady,
|
|
||||||
# counts switches in the measured second half only, not the whole run
|
|
||||||
n_switches=len(switch_idx),
|
|
||||||
arousal_at_switch=statistics.fmean(arousals[i] for i in switch_idx) if switch_idx else float("nan"),
|
|
||||||
arousal_steady=statistics.fmean(arousals[i] for i in steady_idx) if steady_idx else float("nan"),
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def run(name: str, seed: int, steps: int, window: int = 20, bptt: int = 20,
|
|
||||||
lr: float = 1e-3, hidden: int = 32, kappa: float = 4.0, omega: float = 10.0) -> dict:
|
|
||||||
spec = dict(CONDITIONS[name])
|
|
||||||
if spec["kappa"] == KAPPA_FLAG:
|
|
||||||
spec["kappa"] = kappa
|
|
||||||
wcfg = ParticleConfig(seed=seed, oracle=spec["oracle"])
|
|
||||||
if window >= wcfg.t_min:
|
|
||||||
raise ValueError(
|
|
||||||
f"window={window} must be < t_min={wcfg.t_min}: a recovery window that reaches "
|
|
||||||
"the next switch blends two events into one curve"
|
|
||||||
)
|
|
||||||
torch.manual_seed(seed)
|
|
||||||
world = ParticleWorld(wcfg)
|
|
||||||
ctx_dim = wcfg.n_regimes if spec["ctx"] == "regime" else 2
|
|
||||||
org = Organism(attr_dim=world.attr_dim, coord_dim=2, target_dim=2, context_dim=ctx_dim,
|
|
||||||
hidden_dim=hidden, omega=omega, kappa=spec["kappa"], memory=spec["memory"])
|
|
||||||
opt = torch.optim.Adam(org.parameters(), lr=lr)
|
|
||||||
acfg = AffectConfig()
|
|
||||||
affect = Affect()
|
|
||||||
memory: dict[int, torch.Tensor] = {}
|
|
||||||
|
|
||||||
losses, switched, arousals = [], [], []
|
|
||||||
pending = []
|
|
||||||
for t in range(steps):
|
|
||||||
obs = world.step()
|
|
||||||
ctx = _context(spec["ctx"], affect, obs.regime, wcfg.n_regimes)
|
|
||||||
pred, memory = org(obs.attrs, wrapped_diff(obs.coords), obs.ids, affect.axes, memory, context=ctx)
|
|
||||||
loss = ((pred - obs.target) ** 2).mean()
|
|
||||||
pending.append(loss)
|
|
||||||
affect = update(affect, loss.item(), acfg)
|
|
||||||
losses.append(loss.item()); switched.append(obs.switched); arousals.append(affect.arousal)
|
|
||||||
if len(pending) == bptt:
|
|
||||||
opt.zero_grad()
|
|
||||||
torch.stack(pending).mean().backward()
|
|
||||||
opt.step()
|
|
||||||
pending = []
|
|
||||||
memory = detach_memory(memory)
|
|
||||||
|
|
||||||
return dict(condition=name, seed=seed, steps=steps, **_metrics(losses, switched, arousals, window))
|
|
||||||
|
|
||||||
|
|
||||||
def table(results: list[dict]) -> str:
|
|
||||||
by = {}
|
|
||||||
for r in results:
|
|
||||||
by.setdefault(r["condition"], []).append(r)
|
|
||||||
win = len(results[0]["recovery"]) if results else 0
|
|
||||||
idxs = [i for i in (0, 2, 5, 10) if i < win] # skip columns the window is too short to have
|
|
||||||
header = "".join(f"{'rec@' + str(i):>10}" for i in idxs)
|
|
||||||
lines = [f"{'condition':<18}{'steady':>10}{header}{'a@switch':>10}{'a@steady':>10}",
|
|
||||||
"-" * (18 + 10 + 10 * len(idxs) + 20)]
|
|
||||||
for name, rs in by.items():
|
|
||||||
m = lambda key, idx=None: statistics.fmean((r[key][idx] if idx is not None else r[key]) for r in rs)
|
|
||||||
row = "".join(f"{m('recovery', i):>10.5f}" for i in idxs)
|
|
||||||
lines.append(f"{name:<18}{m('steady'):>10.5f}{row}{m('arousal_at_switch'):>10.3f}{m('arousal_steady'):>10.3f}")
|
|
||||||
return "\n".join(lines)
|
|
||||||
|
|
||||||
|
|
||||||
def main() -> None:
|
|
||||||
ap = argparse.ArgumentParser()
|
|
||||||
ap.add_argument("--conditions", default=",".join(CONDITIONS))
|
|
||||||
ap.add_argument("--seeds", default="0,1,2")
|
|
||||||
ap.add_argument("--steps", type=int, default=20000)
|
|
||||||
ap.add_argument("--window", type=int, default=20)
|
|
||||||
ap.add_argument("--kappa", type=float, default=4.0)
|
|
||||||
ap.add_argument("--omega", type=float, default=10.0)
|
|
||||||
ap.add_argument("--out", default="results/run.json")
|
|
||||||
a = ap.parse_args()
|
|
||||||
results = []
|
|
||||||
for name in a.conditions.split(","):
|
|
||||||
for seed in (int(s) for s in a.seeds.split(",")):
|
|
||||||
r = run(name, seed, a.steps, window=a.window, kappa=a.kappa, omega=a.omega)
|
|
||||||
print(f"{name:<18} seed={seed} steady={r['steady']:.5f} rec@0={r['recovery'][0]:.5f}", flush=True)
|
|
||||||
results.append(r)
|
|
||||||
Path(a.out).parent.mkdir(parents=True, exist_ok=True)
|
|
||||||
Path(a.out).write_text(json.dumps(results, indent=1))
|
|
||||||
print(); print(table(results))
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
main()
|
|
||||||
-357
@@ -1,357 +0,0 @@
|
|||||||
# Claim A1: does affect move a gate that gradient descent left inert, and does moving it help?
|
|
||||||
|
|
||||||
Task 8. `results/frozen.md` §3 measured the GRP's gate at `g = 0.500 ± 0.029` after
|
|
||||||
8000 steps, on every seed, never above 0.9, never below 0.1: `M ← (1−g)M̃ + gM` had
|
|
||||||
degenerated to a fixed 50/50 blend with no input dependence. The gate's
|
|
||||||
pre-activation is `W_g[h‖M] + b_g − κa`, and the `−κa` term never passes through the
|
|
||||||
gradient, which makes it the only available lever on that gate. This file measures
|
|
||||||
what pulling it does.
|
|
||||||
|
|
||||||
**Verdict: affect moves the gate, decisively and by a visible mechanism. Moving it
|
|
||||||
buys nothing, and the one effect that is specific to real surprise timing is a
|
|
||||||
harm.** Steady error is flat across `κ ∈ {0,1,2,4,8,16}` to within 1.2%, on a coin
|
|
||||||
flip of seeds. Two steps after a switch, real affect is *worse* than `κ=0` on 14–16
|
|
||||||
of 16 seeds, monotonically in `κ`, and worse than a shuffled-affect control that
|
|
||||||
delivers the same gate-value distribution with the wrong timing on 15/16.
|
|
||||||
|
|
||||||
Environment: `experiments/`, `ailed/` unmodified, no default in `particles.py` or
|
|
||||||
`regime.py` changed. 16 seeds (0–15), 8000 training steps, `lr=1e-3`, `bptt=20`,
|
|
||||||
`hidden=32`, `omega=10`, `window=20`. Noise floor `noise² = 4.0e-06`. All metrics are
|
|
||||||
`regime._metrics` on the second half of training, so they are directly comparable
|
|
||||||
with the tables in `headroom.md` and `frozen.md`. 288 runs.
|
|
||||||
|
|
||||||
```
|
|
||||||
uv run python a1.py --stage sweep --out results/a1_sweep.json
|
|
||||||
uv run python a1.py --stage controls --out results/a1_controls.json
|
|
||||||
uv run python a1.py --stage shuffle --kappa 4 --out results/a1_shuffle_k4.json
|
|
||||||
uv run python a1.py --stage shuffle --kappa 16 --out results/a1_shuffle_k16.json
|
|
||||||
uv run python a1.py --stage report --inputs results/a1_sweep.json,results/a1_controls.json
|
|
||||||
```
|
|
||||||
|
|
||||||
## 0. What is measured, and how it is checked
|
|
||||||
|
|
||||||
`Organism.forward` returns only `out(M)`, so `g` has to be reconstructed. `a1.GateTrace`
|
|
||||||
rebuilds `h` from the public `org.rp` exactly as `core.py` builds it, then asserts
|
|
||||||
`org.grp(h, M_prev, a)` equals the `M` the organism actually returned — **every step
|
|
||||||
of every run — 272 gated runs, 2.18M assertions, none of which fired**. That is what makes the reported
|
|
||||||
`g` the organism's own gate rather than a plausible lookalike;
|
|
||||||
`test_gate_reconstruction_is_the_organisms_own_gate` shows the assert can fail, by
|
|
||||||
perturbing the reconstructed `h` by 1e-6.
|
|
||||||
|
|
||||||
The A1 comparison is **`grp_k` against `grp_k0`**: identical architecture, identical
|
|
||||||
5602 parameters, one seed, differing only in `κ`. `rp_only` (1442 parameters) and
|
|
||||||
`grp_k0_nostate` are context and never the claim — `frozen.md` §5. For the record, at
|
|
||||||
16 seeds in the *trained* phase the same decomposition reads:
|
|
||||||
|
|
||||||
```
|
|
||||||
mean median seeds won
|
|
||||||
capacity rp_only / nostate 3.04x 2.71x 16/16
|
|
||||||
state nostate / grp_k0 1.19x 1.11x 11/16
|
|
||||||
```
|
|
||||||
|
|
||||||
which is `frozen.md`'s trained-phase decomposition (3.06x on 8/8, 1.25x on 4/8) at
|
|
||||||
twice the seeds. The state row is firmer than it was at 8 seeds and still modest:
|
|
||||||
five seeds go the other way and the median is 1.11x.
|
|
||||||
|
|
||||||
The "capacity" row label is `frozen.md`'s and is now known to be a misnomer:
|
|
||||||
`grp_k0_nostate` is not capacity-matched to `rp_only` (2048 of its 5602 parameters
|
|
||||||
never train) and the margin is not a parameter count. See `frozen.md` §1c for the
|
|
||||||
correction; the numbers above are unaffected.
|
|
||||||
|
|
||||||
`grp_k` at `κ=0` is `grp_k0` by construction, and `test_run_a1_reports_the_same_metrics_regime_run_does`
|
|
||||||
asserts the two produce bit-identical metrics, so the sweep's `κ=0` row is the
|
|
||||||
baseline rather than a re-implementation of it.
|
|
||||||
|
|
||||||
## 1. Part A — the gate moves, and the learned part does not
|
|
||||||
|
|
||||||
Second half of training, pooled over all entity-steps, means over 16 seeds. `g_post`
|
|
||||||
is the union of the 20 steps each switch opens — exactly the steps `recovery[0..19]`
|
|
||||||
averages over — and `g_far` is `_metrics`'s own `steady_idx`, so the gate contrast and
|
|
||||||
the error contrast are measured on the same steps. `pre` is the learned part of the
|
|
||||||
pre-activation, `W_g[h‖M] + b_g`, with the forcing left out.
|
|
||||||
|
|
||||||
```
|
|
||||||
kappa g_all sd g_post g_far delta frac>0.9 frac<0.1 pre a_post a_far
|
|
||||||
--------------------------------------------------------------------------------------
|
|
||||||
0 0.501 0.025 0.501 0.500 +0.000 0.000 0.000 0.002 0.229 0.109
|
|
||||||
1 0.465 0.068 0.446 0.474 -0.029 0.000 0.000 0.000 0.227 0.106
|
|
||||||
2 0.436 0.114 0.402 0.453 -0.052 0.000 0.000 0.000 0.228 0.106
|
|
||||||
4 0.400 0.164 0.349 0.427 -0.078 0.000 0.124 0.002 0.229 0.106
|
|
||||||
8 0.368 0.197 0.307 0.400 -0.094 0.000 0.206 0.002 0.231 0.107
|
|
||||||
16 0.343 0.213 0.277 0.378 -0.100 0.000 0.264 -0.002 0.232 0.108
|
|
||||||
```
|
|
||||||
|
|
||||||
Read down the columns:
|
|
||||||
|
|
||||||
- **`κ=1` is enough.** Mean `g` moves from 0.501 to 0.465 and its sd nearly triples,
|
|
||||||
0.025 → 0.068. The mean shift is the trivial part; the sd is not, and it is what
|
|
||||||
says the gate has acquired input dependence it did not have.
|
|
||||||
- **Saturation begins between `κ=2` and `κ=4`.** No entity-step has `g<0.1` at
|
|
||||||
`κ≤2`; 12.4% do at `κ=4`, 20.6% at `κ=8`, 26.4% at `κ=16`. The gate never
|
|
||||||
saturates the other way at any `κ`, which it cannot: `a ≥ 0`, so the forcing is
|
|
||||||
one-sided.
|
|
||||||
- **The forcing signal is real and switch-locked.** Mean arousal is 0.229 in the
|
|
||||||
post-switch window against 0.106 far from one, a factor of 2.2, at every `κ`.
|
|
||||||
- **Gradient neither compensates nor participates.** `pre` is 0.000 ± 0.002 at every
|
|
||||||
`κ`, the same value `frozen.md` §3 measured at `κ=0`. The learned part of this gate
|
|
||||||
is inert whether or not it is being forced: `−κa` is not modulating a learned
|
|
||||||
gating policy, it *is* the entire gate.
|
|
||||||
|
|
||||||
Per-seed, the post-vs-far contrast is unanimous rather than an average:
|
|
||||||
|
|
||||||
```
|
|
||||||
kappa mean delta median seeds with post < far
|
|
||||||
--------------------------------------------------
|
|
||||||
0 +0.0000 +0.0001 4/16
|
|
||||||
1 -0.0288 -0.0296 16/16
|
|
||||||
2 -0.0518 -0.0528 16/16
|
|
||||||
4 -0.0778 -0.0769 16/16
|
|
||||||
8 -0.0936 -0.0942 16/16
|
|
||||||
16 -0.1004 -0.0970 16/16
|
|
||||||
```
|
|
||||||
|
|
||||||
The `κ=0` row is the control on this contrast: with the forcing off, the gate is as
|
|
||||||
likely to sit higher after a switch as lower (4/16) and the effect size is 0.0000.
|
|
||||||
|
|
||||||
### 1a. The excursion, lag by lag
|
|
||||||
|
|
||||||
The same quantity `recovery[k]` measures on the loss, measured on the gate: lag `k`
|
|
||||||
after a switch, averaged over the second half's switches, means over 16 seeds.
|
|
||||||
|
|
||||||
```
|
|
||||||
kappa @0 @2 @4 @6 @8 @10 @12 @14 @16 @18 far
|
|
||||||
-------------------------------------------------------------------------
|
|
||||||
0 0.500 0.500 0.500 0.500 0.500 0.501 0.501 0.501 0.501 0.501 0.500
|
|
||||||
1 0.486 0.457 0.448 0.445 0.440 0.436 0.434 0.435 0.440 0.447 0.474
|
|
||||||
2 0.473 0.419 0.405 0.400 0.392 0.386 0.383 0.384 0.391 0.404 0.453
|
|
||||||
4 0.456 0.370 0.355 0.347 0.336 0.328 0.323 0.325 0.334 0.349 0.427
|
|
||||||
8 0.439 0.330 0.319 0.307 0.293 0.283 0.280 0.278 0.286 0.302 0.400
|
|
||||||
16 0.421 0.302 0.292 0.278 0.260 0.252 0.251 0.251 0.256 0.269 0.378
|
|
||||||
|
|
||||||
arousal (identical at every kappa, so the forcing is an input, not a feedback loop)
|
|
||||||
0.061 0.184 0.223 0.236 0.253 0.267 0.279 0.272 0.249 0.220 0.106
|
|
||||||
```
|
|
||||||
|
|
||||||
The gate is an exact mirror of the arousal transient, which is what it must be given
|
|
||||||
that `pre` is flat. Two details worth carrying into the paper:
|
|
||||||
|
|
||||||
- **Arousal is lowest at the switch step itself** (0.061, *below* its far-from-switch
|
|
||||||
level of 0.106) and peaks 12 steps later. `Affect.update` compares the loss to a
|
|
||||||
slow baseline, so the surprise register lags the event by several steps. The gate
|
|
||||||
therefore opens after the error has already begun to rise, not at the moment the
|
|
||||||
world changes.
|
|
||||||
- **The arousal curve is the same at every `κ`** to within 0.01. Forcing the gate
|
|
||||||
does not change the error stream enough to change the affect built from it, so
|
|
||||||
there is no feedback loop to worry about here.
|
|
||||||
|
|
||||||
## 2. Part B — moving it buys nothing
|
|
||||||
|
|
||||||
`steady` and `recovery[k]` from `regime._metrics`, means over 16 seeds. `rp_only` and
|
|
||||||
`grp_k0_nostate` are the context rows.
|
|
||||||
|
|
||||||
```
|
|
||||||
condition steady (sd) rec@0 rec@2 rec@5 rec@10 rec@19
|
|
||||||
---------------------------------------------------------------------------------------------
|
|
||||||
grp_k0 2.399e-05 1.163e-05 3.177e-05 3.166e-05 3.477e-05 3.952e-05 3.196e-05
|
|
||||||
grp_k1 2.425e-05 1.223e-05 3.224e-05 3.323e-05 3.629e-05 4.050e-05 3.221e-05
|
|
||||||
grp_k2 2.409e-05 1.162e-05 3.224e-05 3.382e-05 3.640e-05 4.043e-05 3.186e-05
|
|
||||||
grp_k4 2.413e-05 1.163e-05 3.209e-05 3.453e-05 3.644e-05 4.065e-05 3.218e-05
|
|
||||||
grp_k8 2.415e-05 1.160e-05 3.185e-05 3.542e-05 3.619e-05 4.075e-05 3.185e-05
|
|
||||||
grp_k16 2.428e-05 1.158e-05 3.218e-05 3.605e-05 3.686e-05 4.061e-05 3.179e-05
|
|
||||||
rp_only 7.708e-05 3.668e-05 8.322e-05 8.702e-05 9.174e-05 9.437e-05 8.391e-05
|
|
||||||
grp_k0_nostate 2.791e-05 1.213e-05 3.539e-05 3.689e-05 3.947e-05 4.515e-05 3.707e-05
|
|
||||||
```
|
|
||||||
|
|
||||||
The across-seed sd (1.16e-05) is 40 times the largest difference between any two
|
|
||||||
`κ` rows, so the paired comparison is the only one worth reading.
|
|
||||||
|
|
||||||
```
|
|
||||||
paired grp_k0 / grp_k on steady
|
|
||||||
kappa mean median won per-seed
|
|
||||||
---------------------------------------------------------------------------
|
|
||||||
1 0.99 1.00 6/16 1.03 1.00 1.00 1.00 1.01 1.01 0.99 1.01 0.99 0.99 0.96 1.00 0.99 0.98 0.96 1.02
|
|
||||||
2 1.00 1.00 9/16 1.03 1.00 1.00 1.00 1.01 1.00 1.00 1.01 0.98 1.01 1.01 0.99 1.00 0.98 0.92 1.02
|
|
||||||
4 1.00 1.00 8/16 1.05 1.01 0.99 1.00 1.00 1.00 0.93 1.02 0.98 1.02 1.02 0.99 1.00 0.94 0.94 1.05
|
|
||||||
8 1.00 1.00 7/16 1.04 1.01 0.99 0.99 1.03 0.99 0.94 1.01 0.97 1.02 1.02 0.99 1.00 0.94 0.92 1.08
|
|
||||||
16 0.99 1.00 9/16 1.09 1.01 0.99 0.98 1.02 1.01 0.92 1.01 0.97 1.01 1.03 0.98 1.00 0.92 0.88 1.01
|
|
||||||
```
|
|
||||||
|
|
||||||
**A coin flip at every `κ`**: median 1.00, between 6 and 9 seeds out of 16, no trend
|
|
||||||
in `κ`. A gate driven from an inert 0.500 to a switch-locked excursion between 0.42
|
|
||||||
and 0.25 changes steady error by nothing that 16 seeds can see.
|
|
||||||
|
|
||||||
### 2a. The one systematic effect, and it is a harm
|
|
||||||
|
|
||||||
`frozen.md` §1b showed `recovery[k]` tracks the world's post-switch configuration
|
|
||||||
transient — a stateless frozen model reproduces its shape at every lag — so the raw
|
|
||||||
curve is not an adaptation measurement. That transient is common to every condition
|
|
||||||
here, which is what makes a *difference between conditions at matched lag*
|
|
||||||
interpretable where the curve itself is not.
|
|
||||||
|
|
||||||
```
|
|
||||||
paired grp_k0 / grp_k at matched lag (mean ratio, seeds won; <1 means kappa is worse)
|
|
||||||
kappa @0 @2 @5 @10 @19
|
|
||||||
---------------------------------------------------------------------------
|
|
||||||
1 0.99 7/16 0.96 2/16 0.97 2/16 0.98 3/16 1.00 7/16
|
|
||||||
2 0.99 5/16 0.94 0/16 0.96 3/16 0.98 3/16 1.00 12/16
|
|
||||||
4 0.99 6/16 0.92 1/16 0.96 4/16 0.97 3/16 0.99 8/16
|
|
||||||
8 1.00 7/16 0.91 0/16 0.96 5/16 0.97 2/16 1.00 10/16
|
|
||||||
16 0.99 7/16 0.89 0/16 0.95 4/16 0.97 3/16 1.00 10/16
|
|
||||||
```
|
|
||||||
|
|
||||||
At lag 2 the forced gate is worse on 14–16 seeds out of 16, monotonically in `κ`,
|
|
||||||
from 4% at `κ=1` to 11% at `κ=16`. The effect is present but smaller at lags 5 and
|
|
||||||
10, absent at lag 0 (arousal has not risen yet) and gone by lag 19 (it has decayed).
|
|
||||||
It is the only sign-definite, `κ`-monotone effect anywhere in this file.
|
|
||||||
|
|
||||||
The mechanism is visible in §1a. Overwriting `M` with a fresh candidate discards the
|
|
||||||
temporal averaging the blend was providing, and `frozen.md` §1b already established
|
|
||||||
that the post-switch excess belongs to the world's configuration transient, which no
|
|
||||||
amount of state can shorten. There is nothing for a freshly written memory to gain
|
|
||||||
here, and the smoothing is what it costs.
|
|
||||||
|
|
||||||
## 3. Part C — the shuffled-affect control
|
|
||||||
|
|
||||||
If a forced gate had helped, the obvious alternative reading is that `−κa` acts as a
|
|
||||||
generic regulariser or bias shift rather than as an affective signal. Three controls,
|
|
||||||
all replaying the arousal sequence the gate itself saw, all at the same seed with
|
|
||||||
everything else unchanged:
|
|
||||||
|
|
||||||
| arm | what it delivers |
|
|
||||||
|---|---|
|
|
||||||
| `real` | the live signal — replayed from the recorded trace, so this arm must reproduce the unhooked run bit for bit |
|
|
||||||
| `shuffled` | the same values permuted within each half, so the marginal is matched *exactly* in the measured window, not merely in expectation |
|
|
||||||
| `shifted` | the whole trace circularly rolled — also preserves arousal's own autocorrelation, and breaks only its alignment with the switches |
|
|
||||||
| `const` | the run's mean arousal, i.e. `−κa` reduced to a pure bias shift with no timing information at all |
|
|
||||||
|
|
||||||
Only the arousal reaching the **gate** is replaced. The CPPN keeps the organism's own
|
|
||||||
live `(valence, arousal)`, passed explicitly and built exactly as `Organism.forward`
|
|
||||||
would have built it, so `−κa` is the single thing that moves.
|
|
||||||
`test_replaying_the_runs_own_arousal_reproduces_it_exactly` pins this, the driver
|
|
||||||
asserts it again on all 16 seeds at run time, and the `real` arm is separately
|
|
||||||
verified identical to the sweep's `grp_k4` / `grp_k16` rows on `steady` and on all 20
|
|
||||||
recovery lags. The replay machinery is checked, not trusted.
|
|
||||||
|
|
||||||
### 3a. The controls do what they are supposed to do
|
|
||||||
|
|
||||||
`κ=4`, means over 16 seeds:
|
|
||||||
|
|
||||||
```
|
|
||||||
arm g_all sd g_post g_far delta frac<0.1 a_post a_far
|
|
||||||
------------------------------------------------------------------------
|
|
||||||
real 0.400 0.164 0.349 0.427 -0.078 0.124 0.229 0.106
|
|
||||||
shuffled 0.400 0.165 0.399 0.400 -0.001 0.124 0.150 0.147
|
|
||||||
shifted 0.408 0.158 0.411 0.407 +0.004 0.105 0.130 0.135
|
|
||||||
const 0.369 0.024 0.369 0.369 +0.000 0.000 0.136 0.136
|
|
||||||
```
|
|
||||||
|
|
||||||
`shuffled` matches `real`'s gate distribution to three decimals — same mean, same sd,
|
|
||||||
same saturated fraction — while its post-vs-far contrast collapses from −0.078 to
|
|
||||||
−0.001. The values are preserved and the timing is destroyed, which is exactly what
|
|
||||||
the control has to do. Lag by lag, `κ=4`:
|
|
||||||
|
|
||||||
```
|
|
||||||
arm @0 @2 @4 @6 @8 @10 @12 @14 @16 @18 far
|
|
||||||
real 0.456 0.370 0.355 0.347 0.336 0.328 0.323 0.325 0.334 0.349 0.427
|
|
||||||
shuffled 0.414 0.405 0.400 0.398 0.407 0.402 0.405 0.398 0.394 0.395 0.400
|
|
||||||
shifted 0.409 0.410 0.413 0.415 0.416 0.413 0.408 0.409 0.409 0.410 0.407
|
|
||||||
const 0.369 0.369 0.369 0.369 0.369 0.369 0.369 0.369 0.369 0.369 0.369
|
|
||||||
```
|
|
||||||
|
|
||||||
Note `const` at `κ=16`: `g = 0.103 ± 0.010` with 47.9% of entity-steps below 0.1. A
|
|
||||||
gate pinned near zero is not an open gate, it is a different dead gate, and this is
|
|
||||||
what a constant-arousal bias shift degenerates into at large `κ`.
|
|
||||||
|
|
||||||
### 3b. The result
|
|
||||||
|
|
||||||
`κ=4`, `steady`, means over 16 seeds, with the paired comparison against `shuffled`:
|
|
||||||
|
|
||||||
```
|
|
||||||
arm steady rec@0 rec@2 rec@5 rec@10 rec@19
|
|
||||||
---------------------------------------------------------------------------
|
|
||||||
real 2.413e-05 3.209e-05 3.453e-05 3.644e-05 4.065e-05 3.218e-05
|
|
||||||
shuffled 2.378e-05 3.191e-05 3.243e-05 3.591e-05 4.036e-05 3.216e-05
|
|
||||||
shifted 2.438e-05 3.222e-05 3.280e-05 3.619e-05 4.062e-05 3.261e-05
|
|
||||||
const 2.391e-05 3.223e-05 3.286e-05 3.585e-05 4.009e-05 3.170e-05
|
|
||||||
(grp_k0 2.399e-05 3.177e-05 3.166e-05 3.477e-05 3.952e-05 3.196e-05)
|
|
||||||
|
|
||||||
paired shuffled / arm, per seed
|
|
||||||
steady @0 @2 @5 @10 @19
|
|
||||||
-------------------------------------------------------------------------------------
|
|
||||||
real 0.99 5/16 1.00 8/16 0.94 1/16 0.99 5/16 0.99 10/16 1.00 8/16
|
|
||||||
shifted 0.98 6/16 1.00 9/16 0.99 7/16 1.00 8/16 1.00 10/16 0.99 7/16
|
|
||||||
const 1.00 8/16 1.00 10/16 0.99 8/16 1.00 10/16 1.01 12/16 1.01 11/16
|
|
||||||
```
|
|
||||||
|
|
||||||
`κ=16`:
|
|
||||||
|
|
||||||
```
|
|
||||||
arm steady rec@0 rec@2 rec@5 rec@10 rec@19
|
|
||||||
---------------------------------------------------------------------------
|
|
||||||
real 2.428e-05 3.218e-05 3.605e-05 3.686e-05 4.061e-05 3.179e-05
|
|
||||||
shuffled 2.371e-05 3.171e-05 3.269e-05 3.584e-05 4.033e-05 3.221e-05
|
|
||||||
shifted 2.426e-05 3.236e-05 3.293e-05 3.575e-05 4.068e-05 3.204e-05
|
|
||||||
const 2.413e-05 3.239e-05 3.438e-05 3.673e-05 4.095e-05 3.210e-05
|
|
||||||
|
|
||||||
paired shuffled / arm, per seed
|
|
||||||
steady @0 @2 @5 @10 @19
|
|
||||||
-------------------------------------------------------------------------------------
|
|
||||||
real 0.98 5/16 0.99 7/16 0.92 1/16 0.98 4/16 0.99 6/16 1.01 11/16
|
|
||||||
shifted 0.98 8/16 0.98 6/16 0.99 5/16 1.00 7/16 0.99 9/16 1.00 10/16
|
|
||||||
const 0.99 8/16 0.98 4/16 0.95 1/16 0.98 6/16 0.99 5/16 1.01 9/16
|
|
||||||
```
|
|
||||||
|
|
||||||
**On `steady`, real affect is indistinguishable from shuffled affect** — 5/16 seeds
|
|
||||||
at both `κ`, mean ratio 0.98–0.99. The values matter as little as the timing does,
|
|
||||||
because neither matters at all.
|
|
||||||
|
|
||||||
**On `recovery[2]`, real affect is worse than shuffled on 15/16 seeds**, by 6% at
|
|
||||||
`κ=4` and 8% at `κ=16`, while `shifted` (which preserves arousal's autocorrelation
|
|
||||||
and breaks only its alignment with the switches) sits at parity, 0.99 on 5–7/16. So
|
|
||||||
the lag-2 degradation of §2a is genuinely about surprise *timing*: it is the one
|
|
||||||
thing correlating `−κa` with the switches does that a distribution-matched control
|
|
||||||
does not, and what it does is make the error worse. `const` reproduces about half of
|
|
||||||
it at `κ=16` (0.95 on 1/16) and none of it at `κ=4`, which is the bias-shift channel
|
|
||||||
appearing only once the constant is large enough to shut the gate outright.
|
|
||||||
|
|
||||||
## 4. Verdict
|
|
||||||
|
|
||||||
**Does affect move the gate? Yes.** `κ=1` moves mean `g` off 0.500 and triples its
|
|
||||||
sd; `κ=4` opens 12% of entity-steps past `g<0.1`; the gate traces the arousal
|
|
||||||
transient lag for lag, with a post-vs-far contrast of −0.078 at `κ=4` on 16/16 seeds.
|
|
||||||
The learned part of the pre-activation stays at 0.000 ± 0.002 throughout, so this is
|
|
||||||
not affect modulating a learned gating policy — it is affect supplying the whole of a
|
|
||||||
gating policy gradient descent never built. A1's premise holds: the `−κa` term
|
|
||||||
activates a mechanism that gradient descent left inert.
|
|
||||||
|
|
||||||
**Does moving it help? No.** Steady error is flat to 1.2% across a 16-fold range of
|
|
||||||
`κ` and wins on 6–9 seeds of 16 — a coin flip. The only sign-definite effect is a
|
|
||||||
4–11% *degradation* of error two steps after a switch, monotone in `κ`, on 14–16 of
|
|
||||||
16 seeds. The shuffled control confirms that this degradation is specifically about
|
|
||||||
surprise timing and not a generic bias shift, which makes it the cleanest positive
|
|
||||||
measurement in the file and it points the wrong way.
|
|
||||||
|
|
||||||
**A1 does not hold on this domain**, and the reason is the one `headroom.md` §6(c)
|
|
||||||
and `frozen.md` §4 both reached from other directions. The post-switch error here is
|
|
||||||
dominated by the world's own configuration transient, which no gating policy can
|
|
||||||
shorten; memory's only contribution is temporal smoothing; and a gate that opens on
|
|
||||||
surprise spends exactly that smoothing at the moment it is worth most. The mechanism
|
|
||||||
works. The domain gives it nothing to do, and a small amount to lose.
|
|
||||||
|
|
||||||
This is a measured null about *this* domain and *this* budget, not an impossibility
|
|
||||||
result. What would give the mechanism a job is what the two earlier files already
|
|
||||||
asked for: a domain where regime identity is worth something to a per-entity state —
|
|
||||||
a short world transient and a long ambiguity — so that discarding a stale memory buys
|
|
||||||
more than the averaging it costs. Three things this file establishes that carry
|
|
||||||
forward regardless:
|
|
||||||
|
|
||||||
- **The forcing lever works and is measurable.** Any future domain can be checked for
|
|
||||||
A1 with the same instrument, and `pre ≈ 0` gives the null a mechanism rather than
|
|
||||||
an absence.
|
|
||||||
- **Arousal lags the event by ~12 steps.** `Affect.update`'s slow baseline means the
|
|
||||||
gate opens after the error rises, not when the world changes. In a domain where
|
|
||||||
timing matters, that lag is a design parameter (`rho_a`, `rho_slow`) and not a
|
|
||||||
constant.
|
|
||||||
- **`recovery[2]` is where affect shows up at all.** Whatever replaces this domain
|
|
||||||
should be checked for an effect at short lag before its steady-state error is
|
|
||||||
quoted.
|
|
||||||
@@ -1,93 +0,0 @@
|
|||||||
# Per-entity memory pays, and the state is what pays
|
|
||||||
|
|
||||||
The first positive result on the memory line, with the control that killed the equivalent
|
|
||||||
claim in the particles domain.
|
|
||||||
|
|
||||||
**The readout was the bottleneck.** Swapping MSE-on-the-mean for cross-entropy over the legal
|
|
||||||
destinations — same target, same chance level, same conditioning — lifts accuracy from 0.40 to
|
|
||||||
0.47, and flips every memory comparison from negative to positive.
|
|
||||||
|
|
||||||
## Results
|
|
||||||
|
|
||||||
400 games, 28 067 plies, 8 seeds, split by game. Type in `e_ij`. Affect neutral, kappa 0.
|
|
||||||
|
|
||||||
```
|
|
||||||
arm params loss acc chance
|
|
||||||
constant 225 --- 0.3454 0.3618
|
|
||||||
rp 9121 1.2453 0.4685 0.3618
|
|
||||||
rp_oracle 9313 1.2449 0.4705 0.3618
|
|
||||||
rp_wide 13393 1.2422 0.4722 0.3618
|
|
||||||
grp_nostate 13281 1.2497 0.4616 0.3618
|
|
||||||
grp 13281 1.2362 0.4780 0.3618
|
|
||||||
|
|
||||||
grp - rp_wide: +0.0058 +/- 0.0019 7/8 seeds
|
|
||||||
grp - grp_nostate: +0.0164 +/- 0.0025 8/8 seeds
|
|
||||||
grp_nostate - rp_wide: -0.0106 +/- 0.0017 0/8 seeds
|
|
||||||
rp_oracle - rp: +0.0020 +/- 0.0015 5/8 seeds ambiguous
|
|
||||||
```
|
|
||||||
|
|
||||||
`grp - grp_nostate`, per seed — the whole result in one column:
|
|
||||||
|
|
||||||
```
|
|
||||||
seed 0 1 2 3 4 5 6 7
|
|
||||||
+0.0155 +0.0206 +0.0197 +0.0125 +0.0216 +0.0271 +0.0052 +0.0091
|
|
||||||
```
|
|
||||||
|
|
||||||
## Why the control is the result
|
|
||||||
|
|
||||||
`grp_nostate` is the same architecture with the same 13 281 parameters and the same gate,
|
|
||||||
handed an **empty memory every ply**. The only difference from `grp` is whether the state is
|
|
||||||
carried. It gains +0.0164 on 8/8 seeds, 6.6 paired standard errors.
|
|
||||||
|
|
||||||
This is the control that inverted the equivalent claim in particles, where the RP/GRP margin
|
|
||||||
turned out to be the gated post-RP nonlinearity rather than the state (`frozen.md` §1d). Here
|
|
||||||
it goes the other way, and further than that: **the gated architecture with an empty memory is
|
|
||||||
worse than the plain memoryless one** (-0.0106, 0/8 seeds). The gate is a cost that the state
|
|
||||||
more than repays. The +0.0058 over `rp_wide` is a net of those two.
|
|
||||||
|
|
||||||
## The oracle under-measured its own ceiling
|
|
||||||
|
|
||||||
`rp_oracle` hands the memoryless model each piece's previous three squares as relative
|
|
||||||
displacements — six input dimensions. It reads +0.0020 on 5/8 seeds, ambiguous, while the
|
|
||||||
learned state gains three times that on 8/8.
|
|
||||||
|
|
||||||
The state finds more than the encoding we handed over. Three squares as displacements is a
|
|
||||||
narrow guess at what a piece's past contains; the state is 32 dimensions accumulated across a
|
|
||||||
whole game. **The oracle read ambiguous in four configurations of this task, and this is the
|
|
||||||
first evidence that the ambiguity was the oracle's encoding rather than the domain's
|
|
||||||
information.** That is a caution about the oracle-first method as practised here, not a
|
|
||||||
refutation of it: an oracle bounds what its own encoding can supply, and nothing more.
|
|
||||||
|
|
||||||
## Where it sits in the arc
|
|
||||||
|
|
||||||
- `chess_history.md` — the domain has per-entity past that predicts the future. Property of the
|
|
||||||
domain, no organism involved.
|
|
||||||
- `credit.md` — the state update can hold per-entity properties (entity type at 0.738 against
|
|
||||||
chance 0.333) and cannot hold a global one.
|
|
||||||
- `chess_reach.md` — the kernel must see the piece type or it learns one average movement
|
|
||||||
shape; the knight's L is exactly zero without it.
|
|
||||||
- `chess_move.md` — with an MSE readout the objective and the question move in opposite
|
|
||||||
directions, and no memory number there is readable.
|
|
||||||
- **this file** — with a readout that matches the target's shape, the carried state pays.
|
|
||||||
|
|
||||||
## Limits, stated rather than discovered later
|
|
||||||
|
|
||||||
- **What the state holds is not identified.** This measures that carrying it helps, not what is
|
|
||||||
in it. The decode probe that `credit.md` ran on particles has not been run here.
|
|
||||||
- 400 games and 8 seeds. The effect is 6.6 se on its own control and 3.1 se on the
|
|
||||||
width-matched arm; the second of those would not survive much less data.
|
|
||||||
- Affect is neutral throughout, so **A1 and A2 are untested here**. Chess has no regime switch
|
|
||||||
and A1 has no analogue; A2 would need the CPPN's context to vary, which it does not.
|
|
||||||
- Legality is handed to the model at readout: the candidate set is the legal destinations. The
|
|
||||||
loss never sees a rule.
|
|
||||||
- Move quality is uncontrolled — blitz games across a wide rating range.
|
|
||||||
- `grp_nostate` is the state control, not a capacity control; `rp_wide` is the capacity control.
|
|
||||||
Both are reported because neither answers the other's question.
|
|
||||||
|
|
||||||
Reproduce with:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
uv run --with chess python chess_dist.py --games 400 --seeds 0,1,2,3,4,5,6,7
|
|
||||||
uv run --with chess python chess_dist.py --games 400 --seeds 0,1,2,3,4,5,6,7 \
|
|
||||||
--arms grp,grp_nostate,rp_wide
|
|
||||||
```
|
|
||||||
@@ -1,93 +0,0 @@
|
|||||||
# Does a piece's own past predict its next move, beyond the current board?
|
|
||||||
|
|
||||||
The 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, before committing to it.
|
|
||||||
|
|
||||||
**Answer: yes, and it survives a stronger estimator.** A piece's own history of squares
|
|
||||||
predicts its next square beyond what the board says. The gain is +0.034 accuracy with a
|
|
||||||
non-linear decoder — eleven paired standard errors from zero — against a shuffled-history
|
|
||||||
control that is *negative*.
|
|
||||||
|
|
||||||
This is the property particles lacked. There, the per-entity state held no more about the
|
|
||||||
hidden variable than the memoryless representation it was built from (`frozen.md` Part B,
|
|
||||||
`pooled.md`), because the hidden variable was **global** — one coupling matrix shared by all
|
|
||||||
sixteen particles, belonging to no entity. Here what there is to remember belongs to the
|
|
||||||
piece.
|
|
||||||
|
|
||||||
## Setup
|
|
||||||
|
|
||||||
1500 games from the local Lichess PGN, 38 719 moves from pieces with at least two prior moves.
|
|
||||||
Two predictors of the same target — the destination square of the piece that moves — given the
|
|
||||||
same conditioning:
|
|
||||||
|
|
||||||
| arm | features |
|
|
||||||
|---|---|
|
|
||||||
| present | board occupancy (64), the moving piece's type (6) and colour (1), its current square (64) |
|
|
||||||
| + history | the same 135, plus the squares that piece occupied on its previous 3 moves (192) |
|
|
||||||
|
|
||||||
Both arms are told which piece moves and from where. The only difference is the piece's own
|
|
||||||
past, so the gap between them is that past's contribution and nothing else.
|
|
||||||
|
|
||||||
Two things guard the number:
|
|
||||||
|
|
||||||
- **The split is by game, never by position.** Two positions from one game share almost
|
|
||||||
everything; splitting inside a game leaks the answer across the split.
|
|
||||||
- **A shuffled-history control.** The same 327 features, with the history block permuted across
|
|
||||||
rows so its marginal distribution is intact and only its alignment with the target is broken.
|
|
||||||
This is what the real gain has to beat: it controls for the extra features themselves.
|
|
||||||
|
|
||||||
## Results
|
|
||||||
|
|
||||||
```
|
|
||||||
estimator present +history gain shuffled seeds paired se
|
|
||||||
-----------------------------------------------------------------------
|
|
||||||
ridge 0.1227 0.1789 +0.0563 0.1190 6/6 0.0011
|
|
||||||
mlp 2x128 0.1586 0.1926 +0.0341 0.1489 3/3 0.0031
|
|
||||||
```
|
|
||||||
|
|
||||||
Per-seed, every seed positive in both arms. The shuffled control gains **−0.0036** (ridge) and
|
|
||||||
**−0.0096** (mlp) over the present-only arm: adding the history features with their timing
|
|
||||||
destroyed makes the predictor slightly *worse*, so the real gain is about the alignment
|
|
||||||
between a piece's past and its future, not about feature count.
|
|
||||||
|
|
||||||
## What the estimator comparison says, and the caveat it carries
|
|
||||||
|
|
||||||
The MLP reads more from the board alone than ridge does — 0.1586 against 0.1227 — so part of
|
|
||||||
what history supplied to the linear model was recoverable from the present by a non-linear one.
|
|
||||||
The gain shrinks accordingly, from +0.056 to +0.034.
|
|
||||||
|
|
||||||
**That trend is the honest caveat: a stronger estimator shrinks the gain, and this measurement
|
|
||||||
does not establish where it stops.** What it does establish is that the gain is still there,
|
|
||||||
and large relative to its error, for a decoder that is not linear. The particles result it is
|
|
||||||
being compared against went the other way — there the per-entity representation held *less*
|
|
||||||
than the memoryless one, at every estimator tried.
|
|
||||||
|
|
||||||
Other limits worth stating rather than discovering later:
|
|
||||||
|
|
||||||
- 1500 games and three seeds for the MLP arm. This project has already been bitten by eight
|
|
||||||
seeds reporting the wrong sign (`pooled.md`); three is enough for a gain of eleven se, and
|
|
||||||
would not be enough for a smaller one.
|
|
||||||
- The target — a piece's destination square — is a proxy chosen because it is cheap and needs
|
|
||||||
no organism. It is not the contract the organism is trained on.
|
|
||||||
- Move quality is not controlled. These are blitz games across a wide rating range, and a
|
|
||||||
piece's past may predict its future partly because weaker players shuffle pieces.
|
|
||||||
|
|
||||||
## What it means
|
|
||||||
|
|
||||||
Chess has the property the memory line needs and particles did not: **information that belongs
|
|
||||||
to an entity, is absent from the present, and persists.** That is the condition the poker
|
|
||||||
framing named — the evidence lives in the past rather than being redundant with the present —
|
|
||||||
and it is here at a size a decoder can see.
|
|
||||||
|
|
||||||
This does not say the GRP will work on chess. It says the domain is not the reason it would
|
|
||||||
fail, which is exactly what could not be said of particles. `credit.md` established that the
|
|
||||||
state update can hold per-entity properties (the entity's type, at 0.738 against chance 0.333)
|
|
||||||
and cannot hold a global one; this file establishes that chess's rememberable content is the
|
|
||||||
per-entity kind.
|
|
||||||
|
|
||||||
Reproduce with:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
uv run --with chess python chess_history.py --games 1500 --seeds 0,1,2,3,4,5
|
|
||||||
uv run --with chess python chess_history.py --games 1500 --seeds 0,1,2 --estimator mlp
|
|
||||||
```
|
|
||||||
@@ -1,104 +0,0 @@
|
|||||||
# Move prediction under contract A: three configurations, one null, and a measured mismatch
|
|
||||||
|
|
||||||
Predicting where the moving piece goes, given the board and which piece moves. Three
|
|
||||||
configurations of the same task. The per-entity history oracle does not pay in any of them,
|
|
||||||
and the reason is visible in the numbers rather than argued: **the objective and the question
|
|
||||||
move in opposite directions.**
|
|
||||||
|
|
||||||
## Setup
|
|
||||||
|
|
||||||
Target: the mover's displacement, MSE, loss masked to the mover. Chess moves one piece per
|
|
||||||
ply, so the spec's literal per-entity default is 31/32 zeros and the constant predictor wins;
|
|
||||||
masking is what leaves the mechanism a job, at the cost of telling the model which piece moves.
|
|
||||||
Accuracy snaps the prediction to the nearest legal destination, so legality is given for free
|
|
||||||
and chance is 0.3618 (uniform among legal), not 1/64.
|
|
||||||
|
|
||||||
400 games, 28 067 plies, 8 seeds, split by game. Affect neutral, kappa 0.
|
|
||||||
|
|
||||||
`rp_oracle` is the gate: the memoryless model is *handed* each piece's previous three squares,
|
|
||||||
which is exactly what memory would have to learn to carry. If that does not pay, memory has no
|
|
||||||
job in this setup and any GRP number here is not a memory result.
|
|
||||||
|
|
||||||
## Results
|
|
||||||
|
|
||||||
```
|
|
||||||
config arm params mse acc
|
|
||||||
all-ones mask, type-blind constant 2 0.05564 0.3325
|
|
||||||
rp 1602 0.03885 0.4148
|
|
||||||
grp 5762 0.03889 0.4088
|
|
||||||
rp_wide 5782 0.03888 0.4144
|
|
||||||
rp_oracle 6544 0.03881 0.4159
|
|
||||||
|
|
||||||
attack mask, type-blind rp 1602 0.04063 0.3828
|
|
||||||
grp 5762 0.04015 0.3832
|
|
||||||
rp_wide 5782 0.04024 0.3809
|
|
||||||
rp_oracle 6544 0.03980 0.3805
|
|
||||||
|
|
||||||
all-ones mask, type in e_ij rp 1762 0.03547 0.4029
|
|
||||||
grp 5922 0.03547 0.3933
|
|
||||||
rp_wide 5942 0.03548 0.3998
|
|
||||||
rp_oracle 6704 0.03545 0.3992
|
|
||||||
|
|
||||||
chance (uniform among legal destinations) 0.3618
|
|
||||||
```
|
|
||||||
|
|
||||||
The oracle, in all three:
|
|
||||||
|
|
||||||
```
|
|
||||||
all-ones, type-blind rp_oracle - rp_wide +0.0014 +/- 0.0011 4/8 seeds ambiguous
|
|
||||||
attack mask rp_oracle - rp_wide -0.0003 +/- 0.0019 4/8 seeds ambiguous
|
|
||||||
type in e_ij rp_oracle - rp_wide -0.0006 +/- 0.0031 5/8 seeds ambiguous
|
|
||||||
```
|
|
||||||
|
|
||||||
## The mismatch, which is the finding
|
|
||||||
|
|
||||||
Putting the piece's type into the CPPN improves the trained objective substantially — MSE
|
|
||||||
0.03888 -> 0.03547 — and makes the answer to the actual question **worse**: accuracy
|
|
||||||
0.4144 -> 0.3998. The same change that helps the model fit helps it less often name the right
|
|
||||||
square. Compare `chess_reach.md`, where the identical change moved the knight's L from exactly
|
|
||||||
zero to 0.758 on 8/8 seeds; the kernel is not the problem here.
|
|
||||||
|
|
||||||
MSE on a displacement vector fits the **conditional mean** of the destinations. A knight with
|
|
||||||
five legal squares has a mean displacement pointing at none of them, and history shifts the
|
|
||||||
*distribution* over destinations — which is what `chess_history.md` measured, +0.034 with a
|
|
||||||
non-linear decoder over 64 squares — while barely moving the mean. The readout discards the
|
|
||||||
shape of information the history carries. Improving the fit to the mean therefore costs
|
|
||||||
accuracy, which is what the two configurations show.
|
|
||||||
|
|
||||||
The attack-mask configuration is a separate measured null: mean degree falls 30 -> 3.3 and
|
|
||||||
accuracy falls with it, 0.414 -> 0.381 across all arms. The dilution hypothesis — that an
|
|
||||||
entity's own attributes are drowned by 1/deg in the mean-pooled message — predicted the
|
|
||||||
opposite and is not supported.
|
|
||||||
|
|
||||||
## Verdict
|
|
||||||
|
|
||||||
**Per-entity history does not pay under contract A with an MSE readout**, in three
|
|
||||||
configurations, 8 paired seeds each, with a measured floor (0.0556 / 0.3325) confirming the
|
|
||||||
models do learn from the board. This is a fact about this readout and not about chess: the
|
|
||||||
domain measurement in `chess_history.md` stands, and the mismatch above says why the two
|
|
||||||
disagree.
|
|
||||||
|
|
||||||
The GRP numbers here (-0.0057, +0.0023, -0.0065 against the width-matched memoryless arm)
|
|
||||||
should not be read as memory results. The oracle gates them, and the oracle is ambiguous
|
|
||||||
in every configuration.
|
|
||||||
|
|
||||||
## Limits
|
|
||||||
|
|
||||||
- The type-conditional kernel was verified to learn piece movement on the *reachability* task,
|
|
||||||
not on this one. Representability here is inferred, not measured.
|
|
||||||
- Move quality is uncontrolled: blitz games across a wide rating range.
|
|
||||||
- Accuracy hands legality to the model at readout time; the loss never sees it.
|
|
||||||
- No cross-entropy readout was tried here. That change was made in `chess_dist.py` and it
|
|
||||||
reverses the conclusion: accuracy 0.40 -> 0.47 and every memory comparison flips positive.
|
|
||||||
See `chess_dist.md`. The nulls in this file are facts about an MSE readout and nothing more.
|
|
||||||
|
|
||||||
Reproduce with:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
uv run --with chess python chess_domain.py --games 400 --seeds 0,1,2,3,4,5,6,7 \
|
|
||||||
--arms constant,rp,grp,rp_wide,rp_oracle # all-ones, type-blind
|
|
||||||
uv run --with chess python chess_domain.py --games 400 --seeds 0,1,2,3,4,5,6,7 --mask attack \
|
|
||||||
--arms rp,grp,rp_wide,rp_oracle # attack mask
|
|
||||||
uv run --with chess python chess_domain.py --games 400 --seeds 0,1,2,3,4,5,6,7 --edges type \
|
|
||||||
--arms constant,rp,grp,rp_wide,rp_oracle # type in e_ij
|
|
||||||
```
|
|
||||||
@@ -1,115 +0,0 @@
|
|||||||
# Does the organism learn how a piece moves?
|
|
||||||
|
|
||||||
Every memory result in this project so far assumed the model understood its domain. On chess
|
|
||||||
that assumption had never been measured. This file measures it, and the answer changes what
|
|
||||||
the earlier chess nulls mean.
|
|
||||||
|
|
||||||
**Answer: only when the piece's type enters the CPPN.** With the type reaching the kernel
|
|
||||||
through the spec's edge-type channel, the knight's L is recovered at 0.758. Without it, on
|
|
||||||
every seed, the knight scores **exactly zero** — the model learns one average movement shape
|
|
||||||
and applies it to all six types.
|
|
||||||
|
|
||||||
## Setup
|
|
||||||
|
|
||||||
Target: `board.attacks(square)` for every live piece, as a multi-hot over the 15x15 grid of
|
|
||||||
**relative** offsets. Relative, not absolute, and that is not a convenience: the CPPN sees only
|
|
||||||
`r_ij`, so an entity's representation is translation-invariant and cannot know which absolute
|
|
||||||
square it stands on. A 64-square target is unanswerable by construction. In offset space the
|
|
||||||
question is the one worth asking — a knight's L is eight cells, a bishop's is four rays.
|
|
||||||
|
|
||||||
Loss is BCE over all live entities, not just one mover. Metric is precision@k per entity, with
|
|
||||||
k the true number of reachable offsets: of the k offsets it ranks highest, how many are real.
|
|
||||||
|
|
||||||
Three controls, and the first is the one the question needs:
|
|
||||||
|
|
||||||
- **`constant`** — every piece moves like the average piece: offsets ranked by their marginal
|
|
||||||
frequency, blind to type and to position. Beating it is what "tells a pawn from a bishop"
|
|
||||||
means. It is not a weak floor; it scores 0.4065 where random ranking scores 0.0191.
|
|
||||||
- **`rp` vs `rp_type`** — `--edges type` puts the receiving piece's type into `e_ij`, which is
|
|
||||||
the spec's own channel into the CPPN. Without it the kernel is type-blind: type lives in
|
|
||||||
`attrs` and meets the kernel only as an elementwise product, so the *geometry function* is
|
|
||||||
shared across all six types.
|
|
||||||
- **`grp_type`** — memory, on the arm that works. Reachability is fully determined by the
|
|
||||||
present, so this is the redundant case and memory should buy nothing.
|
|
||||||
|
|
||||||
400 games, 28 067 plies, 8 seeds, split by game. Affect neutral, kappa 0.
|
|
||||||
|
|
||||||
## Results
|
|
||||||
|
|
||||||
```
|
|
||||||
arm loss prec@k pawn knight bishop rook queen king params
|
|
||||||
constant --- 0.4065 0.4300 0.0000 0.5017 0.1665 0.5921 0.6617 225
|
|
||||||
rp 0.0527 0.4570 0.5115 0.0000 0.5185 0.1907 0.6320 0.7004 8961
|
|
||||||
rp_type 0.0316 0.5587 0.4363 0.7575 0.6409 0.5763 0.6762 0.7461 9121
|
|
||||||
grp_type 0.0537 0.4122 0.4328 0.0000 0.5012 0.1709 0.6244 0.6613 13281
|
|
||||||
|
|
||||||
random ranking scores 0.0191
|
|
||||||
|
|
||||||
rp_type - rp: +0.1016 +/- 0.0280 (paired se), 7/8 seeds
|
|
||||||
grp_type - rp_type: -0.1465 +/- 0.0010 (paired se), 0/8 seeds
|
|
||||||
```
|
|
||||||
|
|
||||||
Per-seed knight precision, which is the whole result in one row:
|
|
||||||
|
|
||||||
```
|
|
||||||
constant 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000
|
|
||||||
rp 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000
|
|
||||||
rp_type 0.742 0.755 0.749 0.768 0.750 0.768 0.766 0.763
|
|
||||||
grp_type 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000
|
|
||||||
```
|
|
||||||
|
|
||||||
## What it establishes
|
|
||||||
|
|
||||||
**The type must enter the kernel, not the features.** 160 extra parameters — 1.8% — flip the
|
|
||||||
knight from exactly zero to 0.758 on 8/8 seeds. That is not capacity, and the discontinuity
|
|
||||||
says why: the type-blind kernel is one geometry function scaled by a type vector, and the
|
|
||||||
knight's L cannot be reached by scaling the average movement shape. The bishop (0.52 -> 0.64)
|
|
||||||
and the rook (0.19 -> 0.58) move the same way; the rook's gain is the second-largest, and its
|
|
||||||
rays are the second-least average-like pattern.
|
|
||||||
|
|
||||||
**Memory does not merely fail here; it destroys the result.** `grp_type` carries 46% more
|
|
||||||
parameters than `rp_type` and lands back on the floor's profile, knight at zero on 8/8 seeds,
|
|
||||||
at 146 paired standard errors. The mechanism is legible: the readout is `W_out M_i`, and with
|
|
||||||
the gate near 0.5 half of that vector is the previous ply's state. A task determined entirely
|
|
||||||
by the present is damaged by mixing in the past.
|
|
||||||
|
|
||||||
This is the redundant case from the poker framing — the evidence is already in the present —
|
|
||||||
and it is the positive control the instrument needed. It also removes a possible objection to
|
|
||||||
the earlier chess nulls: the GRP path is measurably capable of destroying a signal that is
|
|
||||||
present, so those nulls were not produced by an inert mechanism.
|
|
||||||
|
|
||||||
**Why the per-type breakdown is not decoration.** On seed 4 the aggregate gain is *negative*
|
|
||||||
(-0.082) while the knight sits at 0.750. Pawns are half the pieces on the board, so an
|
|
||||||
aggregate can be carried, or masked, by pawns alone. Reading only `prec@k` would have reported
|
|
||||||
this seed as evidence against the effect.
|
|
||||||
|
|
||||||
## Limits, stated rather than discovered later
|
|
||||||
|
|
||||||
- **Precision@k is a hard ranking threshold.** "Knight = 0.000" means no L cell reaches the
|
|
||||||
top-k, not that the logits carry nothing. A soft metric could show partial structure below
|
|
||||||
that threshold; this measurement does not look.
|
|
||||||
- **`rp_type` makes pawns worse** (0.5115 -> 0.4363). Type-conditioning redistributes capacity,
|
|
||||||
and the pawn — whose two diagonals are close to the average short-range shape — pays for it.
|
|
||||||
Reported because it is a cost, not an artefact to explain away.
|
|
||||||
- **Pawns are measured on captures only.** `board.attacks` is the two diagonals, not the
|
|
||||||
forward push, so for pawns this is capture geometry.
|
|
||||||
- **Pins and check are ignored.** `attacks` is geometry plus blockers. Legality proper is a
|
|
||||||
more global question and is not asked here.
|
|
||||||
- No width-matched arm for the memory comparison. `grp_type` already has 46% more parameters
|
|
||||||
and is worse, so matching would only widen the gap; the direction is safe, the magnitude is
|
|
||||||
not a clean estimate.
|
|
||||||
|
|
||||||
## What it means for the memory line
|
|
||||||
|
|
||||||
The earlier chess results (`chess_domain.py`, move prediction) were measured on a model whose
|
|
||||||
kernel was type-blind — one that, as this file shows, had not learned that a knight moves in an
|
|
||||||
L. Those nulls stand as facts about that setup and should not be read as facts about memory in
|
|
||||||
chess. The domain question `chess_history.md` answered positively is still open at the level of
|
|
||||||
the organism, and it is now askable on a model that understands the pieces.
|
|
||||||
|
|
||||||
Reproduce with:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
uv run --with chess python chess_reach.py --games 400 --seeds 0,1,2,3,4,5,6,7 \
|
|
||||||
--arms constant,rp,rp_type,grp_type
|
|
||||||
```
|
|
||||||
@@ -1,138 +0,0 @@
|
|||||||
# Teaching the movement rules, on generated positions
|
|
||||||
|
|
||||||
The organism was never taught how the pieces move. Every memory result before this file was
|
|
||||||
measured on top of that gap. This is the base.
|
|
||||||
|
|
||||||
**Where it stands: the RP learns the rules from a generated curriculum and, on the pieces where
|
|
||||||
reading the board matters most, exceeds a control that knows the rules and cannot see.**
|
|
||||||
|
|
||||||
## Why not games
|
|
||||||
|
|
||||||
Two failures of games as a curriculum, both measured rather than argued:
|
|
||||||
|
|
||||||
- **Coverage.** A rook or queen is blocked in 98-100% of real positions (`chess_shape.json`), so
|
|
||||||
the model learned the geometry it saw instead of the rule behind it — it scored *worse* in
|
|
||||||
open positions (rook 0.811) than blocked ones (0.891). Here the piece count is sampled
|
|
||||||
uniformly from 2 to 32, so a near-empty board is as common as a crowded one, and every piece
|
|
||||||
type visits all its legal squares: measured at 3000 positions, a knight lands on each of the
|
|
||||||
64 squares between 65 and 107 times.
|
|
||||||
- **The target left out three rules entirely.** The reachability task asked for
|
|
||||||
`board.attacks`, which for a pawn on e2 returns d3 and f3 while its moves are e3 and e4 —
|
|
||||||
**no overlap at all**. Castling never appeared (a king's attack set is its five adjacent
|
|
||||||
squares; c1 and g1 are not in it) and neither did en passant. The model did not fail to learn
|
|
||||||
these. It was never asked. The target here is `generate_pseudo_legal_moves`.
|
|
||||||
|
|
||||||
## Setup
|
|
||||||
|
|
||||||
300 000 generated positions streamed for training (never stored: dense targets would be 6 GB),
|
|
||||||
4 000 held out from a disjoint seed. Target: every piece's pseudo-legal destinations, as a
|
|
||||||
multi-hot over the 15x15 grid of relative offsets. Metric: precision@k per piece, k the true
|
|
||||||
number of destinations. 4 seeds. No memory anywhere in this file — this is the RP question
|
|
||||||
alone, per the sequencing policy in `AGENTS.md`.
|
|
||||||
|
|
||||||
**`shape` is the control**: it knows each piece's type, its movement rule and its own flags, and
|
|
||||||
reads *nothing else on the board*. It proposes the un-blocked ray. Beating it is what "reads the
|
|
||||||
occupancy" means, and it is the bar this file is measured against — not 1.0.
|
|
||||||
|
|
||||||
Castling rights and the en-passant square are handed over as per-entity attributes. They are
|
|
||||||
**state, not position** — a rook must remember whether it has moved — and without them the same
|
|
||||||
board has two different correct answers. Removing them is the cleanest memory experiment this
|
|
||||||
project has available, with exact ground truth instead of a 0.03 correlation, and it belongs to
|
|
||||||
the parked GRP line.
|
|
||||||
|
|
||||||
## Results
|
|
||||||
|
|
||||||
```
|
|
||||||
arm prec@k pawn knight bishop rook queen king
|
|
||||||
constant 0.4075 0.4491 0.0000 0.1730 0.4947 0.5609 0.7781
|
|
||||||
rp_type 0.7793 0.6573 0.8574 0.7856 0.7569 0.7510 0.9124
|
|
||||||
rp 0.8161 0.7835 0.8481 0.7748 0.7837 0.7680 0.9227
|
|
||||||
shape 0.8305 0.8156 0.8624 0.8299 0.7679 0.7618 0.9134
|
|
||||||
|
|
||||||
random ranking scores 0.0233
|
|
||||||
```
|
|
||||||
|
|
||||||
**The RP exceeds the rule-knower on rook (+0.016), queen (+0.006) and king (+0.009)** — the
|
|
||||||
pieces whose moves are cut by occupancy, where ignoring the board costs most. It remains below
|
|
||||||
on pawn (-0.032), bishop (-0.055) and knight (-0.014).
|
|
||||||
|
|
||||||
Absolute position, added as attributes, is worth +0.020 and closes the gap to `shape` from
|
|
||||||
0.034 to 0.014:
|
|
||||||
|
|
||||||
```
|
|
||||||
without position with position
|
|
||||||
rp 0.7962 0.8161
|
|
||||||
rp_type 0.7583 0.7793
|
|
||||||
shape (was always given it) 0.8305 0.8305
|
|
||||||
```
|
|
||||||
|
|
||||||
The CPPN sees only `r_ij`, which makes the representation translation-invariant, and a chess
|
|
||||||
board has edges: a knight has 2.96 destinations on the rim against 6.85 in the middle, and 43%
|
|
||||||
of knights sit on the rim. `shape` was handed the square all along, so the comparison had been
|
|
||||||
biased *against* the organism.
|
|
||||||
|
|
||||||
**A prediction that did not verify.** The improvement was predicted to concentrate on rim
|
|
||||||
pieces. Per type it is roughly flat — pawn +0.008, knight +0.016, bishop +0.028, rook +0.028,
|
|
||||||
queen +0.029, king +0.022 — and the knight, 43% of which sit on the rim, gained *less* than the
|
|
||||||
queen. The per-type cut cannot settle a per-square hypothesis, so this is recorded as
|
|
||||||
unverified rather than as either confirmed or refuted. Position pays; the mechanism proposed
|
|
||||||
for why it pays is not demonstrated.
|
|
||||||
|
|
||||||
## Type in the kernel reverses sign with coverage
|
|
||||||
|
|
||||||
On game data, putting the piece type into `e_ij` was worth +0.10 and took the knight's L from
|
|
||||||
exactly zero to 0.758 (`chess_reach.md`). On the generated curriculum `rp_type` lands *below*
|
|
||||||
`rp`, and the whole deficit is the pawn: 0.6573 against 0.7835, with knight and bishop still
|
|
||||||
slightly ahead. That earlier jump was in part a crutch against scarce data.
|
|
||||||
|
|
||||||
The likely cause is specific and testable: `e_ij` carries the piece **type** and not its
|
|
||||||
**colour**, so a white pawn and a black pawn share one kernel while their moves are mirrored.
|
|
||||||
`own_rank` — rank counted from the piece's own back rank — is present in this run and did not
|
|
||||||
fix it on its own, which points at the colour rather than the orientation.
|
|
||||||
|
|
||||||
**`rp_typecol` confirms it, and splits along a line predicted in advance.** Twelve kernels
|
|
||||||
(type x colour) instead of six, 4 seeds (0.8330, 0.8375, 0.8331, 0.8378):
|
|
||||||
|
|
||||||
```
|
|
||||||
arm prec@k pawn knight bishop rook queen king
|
|
||||||
rp 0.8161 0.7835 0.8481 0.7748 0.7837 0.7680 0.9227
|
|
||||||
rp_typecol 0.8353 0.8689 0.8580 0.7895 0.7615 0.7528 0.9127
|
|
||||||
delta +0.085 +0.010 +0.015 -0.022 -0.015 -0.010
|
|
||||||
shape 0.8305 0.8156 0.8624 0.8299 0.7679 0.7618 0.9134
|
|
||||||
```
|
|
||||||
|
|
||||||
The owner named the split before the run, from chess rather than from the data: colour and
|
|
||||||
starting square matter for the **pawn, bishop and knight**, and not for the **rook, queen and
|
|
||||||
king**. Giving each colour its own kernel gains on exactly the first three and **loses on
|
|
||||||
exactly the second three**. A capacity story predicts a uniform gain and is ruled out by the
|
|
||||||
sign flip.
|
|
||||||
|
|
||||||
The mechanism is a bias-variance trade made per piece type: splitting six kernels into twelve
|
|
||||||
halves the data behind each one. Where colour changes the law — a pawn's direction above all,
|
|
||||||
at +0.085 — that is worth paying. Where the law is colour-symmetric it is pure loss.
|
|
||||||
|
|
||||||
`rp_typecol` is the first arm to exceed the rule-knowing control **in aggregate** (0.8353
|
|
||||||
against 0.8305). Note that it does so by a different route than `rp`, which beat `shape` on
|
|
||||||
rook, queen and king while `rp_typecol` does not. Neither arm dominates; a kernel conditioned
|
|
||||||
on colour only for the pieces whose law depends on it is untested and is the obvious next
|
|
||||||
question.
|
|
||||||
|
|
||||||
## Limits
|
|
||||||
|
|
||||||
- One training pass, no schedule, no ordering. A graded curriculum (piece alone, then one
|
|
||||||
blocker, then a full board) has not been tried; the sampler is i.i.d.
|
|
||||||
- The model is still data-limited: 6k positions gave 0.41, 30k gave 0.61, 300k gives 0.82. It
|
|
||||||
had not plateaued at any budget measured.
|
|
||||||
- Legality of the *position* is not modelled: these are sampled placements, valid but not
|
|
||||||
reachable from the opening.
|
|
||||||
- Pins and check are excluded — the target is pseudo-legal. King safety is a global rule and a
|
|
||||||
separate question.
|
|
||||||
- `shape` is a control, not a ceiling: it scores 0.83 because it cannot see the board, and the
|
|
||||||
true ceiling is 1.0.
|
|
||||||
|
|
||||||
Reproduce with:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
uv run --with chess python chess_rules.py --positions 300000 --seeds 0,1,2,3
|
|
||||||
uv run --with chess python chess_rules.py --positions 300000 --seeds 0,1,2,3 --arms rp_typecol
|
|
||||||
```
|
|
||||||
@@ -1,541 +0,0 @@
|
|||||||
# 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
@@ -1,138 +0,0 @@
|
|||||||
[
|
|
||||||
{
|
|
||||||
"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
|
|
||||||
]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
]
|
|
||||||
@@ -1,109 +0,0 @@
|
|||||||
# Discovering an invariance instead of being handed one — and why the objective forbids it
|
|
||||||
|
|
||||||
`invariance.md` settled that a group **given** to the kernel converts unseen orbit members into
|
|
||||||
seen ones: six of a knight's eight L-squares yields the other two at 0.4% of the floor. Every
|
|
||||||
result in this project is a model applying structure it was handed. This asks the only question
|
|
||||||
whose answer would justify the word "understanding" in the project's own framing: can the model
|
|
||||||
**find** the reparameterisation?
|
|
||||||
|
|
||||||
**No. And more optimisation makes it worse, which is the useful part — it means the objective,
|
|
||||||
not the optimiser, is what forbids it.**
|
|
||||||
|
|
||||||
## Setup
|
|
||||||
|
|
||||||
`rp_learn_K` learns K linear maps on the displacement and averages: `m = (1/K) Σ_k CPPN(T_k r)`.
|
|
||||||
If the learned set is closed under the domain's group the average is invariant to it and the
|
|
||||||
eight knight squares become one input, without anyone having said "D4". The `T_k` start at the
|
|
||||||
identity plus noise, so collapse to K=1 is the null the run has to move away from rather than
|
|
||||||
where it accidentally begins.
|
|
||||||
|
|
||||||
The band is measured on the same harness and seeds, not assumed: `rp` 0.02395 below,
|
|
||||||
`rp_inv` 0.00009 above, floor 0.02182. And at K=8 **the solution exists in the parameter space** —
|
|
||||||
`T_k` equal to the eight D4 matrices makes the average invariant by construction — so a null here
|
|
||||||
cannot be a capacity result.
|
|
||||||
|
|
||||||
`orbit` measures D4-invariance of the kernel's behaviour as a fraction of its own scale, so it
|
|
||||||
answers "did it find the group" without the learned maps having to look like anything. Validated
|
|
||||||
against the one kernel whose answer is known exactly: `rp_inv` reads 0.000, raw `rp` reads 1.12.
|
|
||||||
|
|
||||||
## Results, knight_sym, 6 seeds
|
|
||||||
|
|
||||||
```
|
|
||||||
arm steps seen unseen orbit spread
|
|
||||||
rp 2500 0.00097 0.02395 1.121 -
|
|
||||||
rp_learn_2 2500 0.00093 0.02143 1.019 0.664
|
|
||||||
rp_learn_4 2500 0.00087 0.02031 1.005 1.111
|
|
||||||
rp_learn_4 12000 0.00032 0.04258 1.129 1.236
|
|
||||||
rp_learn_8 2500 0.00065 0.02742 0.969 1.424
|
|
||||||
rp_learn_8 12000 0.00020 0.04341 1.042 1.558
|
|
||||||
rp_inv 2500 0.00002 0.00009 0.000 -
|
|
||||||
floor 0.02182
|
|
||||||
```
|
|
||||||
|
|
||||||
**The 266x band is essentially untravelled.** The learned arms sit at the floor. `orbit` moves
|
|
||||||
from 1.121 to 0.969 at best — a weak drift towards invariance that buys nothing.
|
|
||||||
|
|
||||||
**Both false-positive modes appeared, and both were instrumented before the run.** `seen`
|
|
||||||
improves monotonically with K and with steps (0.00097 → 0.00020, a 5x fit) while `unseen` does
|
|
||||||
not: the K transforms were used as extra capacity. And `spread` rises with K (0.66 → 1.56), so
|
|
||||||
the maps did not collapse to one — they diverged, just not towards the group.
|
|
||||||
|
|
||||||
**Training to convergence makes it worse, not better.** This was run to the same standard applied
|
|
||||||
to the binned table in `psi.md`, because under-training an arm is the mirror of tuning one until
|
|
||||||
it catches up. At 12000 steps `seen` improves 3x and `unseen` **doubles** (0.02031 → 0.04258),
|
|
||||||
while `orbit` moves *away* from invariance (1.005 → 1.129). The null is not a budget artefact; it
|
|
||||||
is the opposite of one.
|
|
||||||
|
|
||||||
## Why, and this is the finding
|
|
||||||
|
|
||||||
**Nothing in the objective rewards invariance.** The loss scores fit on the cells the model was
|
|
||||||
shown. Invariance only pays on the cells it was not shown, and those are by construction absent
|
|
||||||
from the loss. An unconstrained kernel fits the training cells better than one tied to an orbit,
|
|
||||||
so gradient descent walks away from the invariant solution — correctly, by its own lights.
|
|
||||||
|
|
||||||
That reframes the null. It is not that the architecture cannot hold the answer (it can, at K=8),
|
|
||||||
and not that the optimiser is too weak (more of it hurts). It is that **the thing we want was
|
|
||||||
never in what we asked for.** Which is the same shape as the five previous nulls in this project,
|
|
||||||
one level up: those were about what the input could express, this one is about what the objective
|
|
||||||
could reward.
|
|
||||||
|
|
||||||
It also gives the next paper a measured starting line rather than a hunch. Evolutionary search —
|
|
||||||
already recorded as where this project goes next — selects on fitness, and a fitness that
|
|
||||||
includes held-out relations puts invariance *in* the objective, where gradient on a training loss
|
|
||||||
cannot. That is now a stated prediction with a number to beat: 0.02395 floor, 0.00009 ceiling,
|
|
||||||
and gradient reaching 0.02031.
|
|
||||||
|
|
||||||
## One thing the learned frame does buy
|
|
||||||
|
|
||||||
On the `smooth` teacher, which has no D4 symmetry, `rp_learn` costs nothing: 0.00006-0.00007
|
|
||||||
against plain `rp`'s 0.00007. The hardcoded invariance costs **31x** there (0.00216). So a
|
|
||||||
learnable frame is free where the domain lacks the symmetry and a fixed one is not — the
|
|
||||||
advantage of discovering over committing is real. It just does not come with any discovering.
|
|
||||||
|
|
||||||
And the `knight` control behaves: eight squares sharing a support but not a rule, every arm flat
|
|
||||||
at ~0.024 with `orbit` unmoved at ~1.49. Nothing to discover, nothing discovered.
|
|
||||||
|
|
||||||
## What this does not establish
|
|
||||||
|
|
||||||
One route to invariance (averaging over learned frames), one objective (fit the shown cells), one
|
|
||||||
optimiser (Adam 3e-3), one initialisation (identity plus 0.4 noise), K ∈ {2,4,8}, one group.
|
|
||||||
Other parameterisations exist — a learned canonicalisation, a Lie-algebra generator basis — and
|
|
||||||
they are not the same experiment. **This is a null about this route to discovery, not about
|
|
||||||
discovery.** The mechanism it points at, though, is not specific to the route: an objective that
|
|
||||||
scores only what was seen has no term that invariance improves, whatever the parameterisation.
|
|
||||||
|
|
||||||
## Reproduce
|
|
||||||
|
|
||||||
```
|
|
||||||
for t in knight_sym knight smooth; do for a in rp rp_inv rp_learn_2 rp_learn_4 rp_learn_8; do
|
|
||||||
uv run python unseen.py --teacher $t --holdout support --arms $a --omega 2 --steps 2500 \
|
|
||||||
--seeds 0,1,2,3,4,5 --out results/disc_${t}_${a}.json
|
|
||||||
done; done
|
|
||||||
for k in 4 8; do
|
|
||||||
uv run python unseen.py --teacher knight_sym --holdout support --arms rp_learn_$k --omega 2 \
|
|
||||||
--steps 12000 --seeds 0,1,2,3,4,5 --out results/disc_long_k$k.json
|
|
||||||
done
|
|
||||||
```
|
|
||||||
|
|
||||||
Runs go 10-wide with `OMP_NUM_THREADS=1`; torch takes ~2 threads per process by default, so
|
|
||||||
pinning to one and going wide turns a 40-minute sweep into 6 minutes on this machine.
|
|
||||||
@@ -1,451 +0,0 @@
|
|||||||
# Frozen-weights probe: does memory have a job once learning is out of the picture?
|
|
||||||
|
|
||||||
Task 7b. Task 7 measured memory beating memoryless 2.99x at `lr=1e-3` and watched
|
|
||||||
that margin decay to 1.06x at `lr=1e-2`, so mean error cannot tell state and fast
|
|
||||||
weights apart. This file removes learning instead of retuning it: train, freeze every
|
|
||||||
parameter, keep stepping the world. Nothing after the freeze can be attributed to an
|
|
||||||
optimiser step.
|
|
||||||
|
|
||||||
**Verdict: a clean null, twice over. Memory is not doing the work, and neither model
|
|
||||||
builds an internal regime variable.**
|
|
||||||
|
|
||||||
1. Under frozen weights `grp_k0` beats `rp_only` 2.50x on steady error, on 8/8 seeds.
|
|
||||||
**That margin is the GRP's gated post-RP nonlinearity, not its state — and not its
|
|
||||||
parameter count either.** The same architecture with the state ablated — an empty
|
|
||||||
memory handed in each step — measures 2.170e-05 against `grp_k0`'s 2.101e-05.
|
|
||||||
Memory is worth 1.06x, on 4 seeds out of 8. Its recovery curve is indistinguishable
|
|
||||||
at every lag. This item originally read "that entire margin is the GRP's extra 4160
|
|
||||||
parameters"; that attribution was wrong and is corrected in §1d. The null for memory
|
|
||||||
is unchanged.
|
|
||||||
2. The regime is decodable from `M` at 0.332 against a measured chance of 0.273. It is
|
|
||||||
decodable from the memoryless RP's `h` at 0.342 against 0.274. **`M` knows no more
|
|
||||||
about the regime than the feedforward representation it is built from** — slightly
|
|
||||||
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. 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,
|
|
||||||
`lr=1e-3`, `bptt=20`, `hidden=32`, `omega=10`, `kappa=0`, `window=20`. Noise floor
|
|
||||||
`noise² = 4.0e-06`. 40 runs total.
|
|
||||||
|
|
||||||
```
|
|
||||||
uv run python frozen.py --out results/frozen.json
|
|
||||||
uv run python frozen.py --conditions grp_k0 --ablate-state --out results/frozen_nostate.json
|
|
||||||
uv run python frozen.py --freeze-affect --no-probes --out results/frozen_affect.json
|
|
||||||
```
|
|
||||||
|
|
||||||
## 0. The freeze audit
|
|
||||||
|
|
||||||
Both guards the brief asked for, asserted in code on every run, not checked by eye.
|
|
||||||
|
|
||||||
| check | how | result |
|
|
||||||
|---|---|---|
|
|
||||||
| no parameter moved | `parameters_to_vector` snapshot before/after the frozen phase, `torch.equal` | **bit-identical on 40/40 runs** |
|
|
||||||
| nothing could move | `requires_grad=False` on every parameter *and* the whole phase under `torch.no_grad()`, no optimiser constructed | asserted |
|
|
||||||
| memory kept updating | `min_t max_i |M_t − M_{t−1}|` over the frozen phase | **2.587e-04**, over every grp run |
|
|
||||||
| the assertion can fail | `test_frozen_phase_detects_a_parameter_change` nudges `out.bias` by 1e-6 after the snapshot | raises, as required |
|
|
||||||
| `h` is the organism's `h` | `org.grp(h, M_prev, arousal)` must equal the M the organism returned; `org.out(h)` must equal the pred it returned | `torch.equal`, every step of every run |
|
|
||||||
|
|
||||||
Mean per-step memory movement is 1.06e-02, four orders above the detection threshold,
|
|
||||||
so the GRP is running as a GRP throughout. `_train` is a verbatim copy of
|
|
||||||
`regime.run`'s loop; `test_train_copy_is_identical_to_regime_run` asserts it
|
|
||||||
reproduces `regime.run`'s metrics exactly, so the frozen phase starts from the
|
|
||||||
organism Task 7 measured.
|
|
||||||
|
|
||||||
Parameter counts: `rp_only` **1442**, `grp_k0` **5602**. The RP is identical in both
|
|
||||||
(1376); the GRP adds a 64→32 gate and a 64→32 candidate layer, 4160 parameters, 3.9x
|
|
||||||
the total. These counts are not the story — §1d measures what the count buys, and the
|
|
||||||
answer is nothing.
|
|
||||||
|
|
||||||
## 1. Part A — frozen recovery
|
|
||||||
|
|
||||||
Metrics come from `regime._metrics` applied to the frozen phase, so they are
|
|
||||||
comparable with Task 7's; as there, they are computed on the second half of the phase.
|
|
||||||
|
|
||||||
### 1a. The headline, and the control that dissolves it
|
|
||||||
|
|
||||||
Frozen-phase `steady`, means over seeds 0-7. `grp_k0_nostate` is `grp_k0` with an
|
|
||||||
empty memory dict handed to `Organism.forward` every step, in training and in the
|
|
||||||
frozen phase: identical architecture, identical parameter *tensors*, `M_prev` always
|
|
||||||
zero. It was originally described here as the capacity-matched feedforward control.
|
|
||||||
**It is not one** — §1d. The rows below are the measurements; the capacity reading of
|
|
||||||
them is withdrawn.
|
|
||||||
|
|
||||||
```
|
|
||||||
condition steady sd min max max/min n_params
|
|
||||||
------------------------------------------------------------------------------
|
|
||||||
rp_only 5.257e-05 2.924e-05 2.644e-05 1.054e-04 3.99 1442
|
|
||||||
grp_k0_nostate 2.170e-05 5.155e-06 1.531e-05 2.733e-05 1.78 5602
|
|
||||||
grp_k0 2.101e-05 6.430e-06 1.426e-05 3.515e-05 2.46 5602
|
|
||||||
```
|
|
||||||
|
|
||||||
Decomposed per seed, which is what carries it:
|
|
||||||
|
|
||||||
```
|
|
||||||
mean median seeds won
|
|
||||||
capacity rp_only / nostate 2.51x 1.94x 8/8
|
|
||||||
state nostate / grp_k0 1.06x 1.00x 4/8
|
|
||||||
```
|
|
||||||
|
|
||||||
Per-seed `nostate / grp_k0`: 1.49 0.92 1.33 0.92 0.90 1.08 0.78 1.10. Four above one,
|
|
||||||
four below. **Removing the state costs nothing.** The same decomposition in the
|
|
||||||
trained phase gives capacity 3.04x on 16/16 seeds and state 1.19x on 11/16
|
|
||||||
(mean; medians 2.71x and 1.11x). Those trained-phase figures were re-measured at 16
|
|
||||||
seeds by Task 8 and supersede the 8-seed values this file originally quoted; the frozen
|
|
||||||
phase rows above remain 8 seeds. See `a1.md`.
|
|
||||||
|
|
||||||
Per-seed frozen `steady`:
|
|
||||||
|
|
||||||
```
|
|
||||||
condition s0 s1 s2 s3 s4 s5 s6 s7
|
|
||||||
--------------------------------------------------------------------------------------------
|
|
||||||
rp_only 4.298e-05 3.808e-05 3.098e-05 3.205e-05 1.054e-04 5.585e-05 8.881e-05 2.644e-05
|
|
||||||
grp_k0_nostate 2.588e-05 1.531e-05 2.665e-05 1.992e-05 1.736e-05 2.545e-05 2.733e-05 1.573e-05
|
|
||||||
grp_k0 1.742e-05 1.656e-05 2.006e-05 2.170e-05 1.931e-05 2.365e-05 3.515e-05 1.426e-05
|
|
||||||
```
|
|
||||||
|
|
||||||
Note also that the across-seed spread — Task 7's "memory buys reliability" reading —
|
|
||||||
goes the same way. `grp_k0_nostate` has the *tightest* spread of the three (1.78x
|
|
||||||
max/min, against `grp_k0`'s 2.46x). Reliability goes with the gated head too — not
|
|
||||||
with the parameter count; see §1d.
|
|
||||||
|
|
||||||
### 1b. The recovery shape: the prediction under test fails
|
|
||||||
|
|
||||||
Raw `recovery[k]`, frozen phase, means over seeds:
|
|
||||||
|
|
||||||
```
|
|
||||||
condition rec@0 rec@5 rec@10 rec@19 steady
|
|
||||||
-------------------------------------------------------------------
|
|
||||||
rp_only 5.506e-05 7.311e-05 8.078e-05 6.563e-05 5.257e-05
|
|
||||||
grp_k0_nostate 2.708e-05 3.749e-05 4.246e-05 2.769e-05 2.170e-05
|
|
||||||
grp_k0 2.756e-05 3.824e-05 4.311e-05 2.756e-05 2.101e-05
|
|
||||||
```
|
|
||||||
|
|
||||||
`grp_k0` and `grp_k0_nostate` agree to within 2% at every lag. The state changes the
|
|
||||||
post-switch trajectory not at all.
|
|
||||||
|
|
||||||
The brief's prediction was that frozen `rp_only` steps up at each switch and never
|
|
||||||
comes back down, while frozen `grp_k0` rises and decays. Normalising each seed by its
|
|
||||||
own steady error before averaging — the only way to compare shapes across conditions
|
|
||||||
whose floors differ 2.5x:
|
|
||||||
|
|
||||||
```
|
|
||||||
condition @0 @2 @4 @6 @8 @10 @12 @14 @16 @18 @19 peak decay
|
|
||||||
----------------------------------------------------------------------------------------
|
|
||||||
rp_only 1.16 1.35 1.49 1.66 1.68 1.59 1.52 1.43 1.38 1.34 1.30 1.69@7 57%
|
|
||||||
grp_k0_nostate 1.31 1.40 1.54 1.92 2.09 2.06 1.87 1.64 1.46 1.35 1.31 2.13@9 73%
|
|
||||||
grp_k0 1.42 1.47 1.69 2.06 2.22 2.18 1.97 1.72 1.51 1.40 1.35 2.24@9 72%
|
|
||||||
```
|
|
||||||
|
|
||||||
("decay" is the fraction of the peak excess over steady that is gone by `@19`.)
|
|
||||||
|
|
||||||
**The frozen memoryless RP does come back down** — 57% of the way, with no parameter
|
|
||||||
having moved and no per-entity state to move. And `grp_k0`'s *relative* excursion is
|
|
||||||
larger, not smaller: it peaks at 2.24x its own floor against the RP's 1.69x, and peaks
|
|
||||||
two steps later.
|
|
||||||
|
|
||||||
The reason is that `recovery[k]` under frozen weights is not measuring the model. At a
|
|
||||||
switch the particle configuration is equilibrated to the old regime; the new coupling
|
|
||||||
matrix then drives it somewhere else over the next 10-20 steps. That transient belongs
|
|
||||||
to the world, and a fixed function of the configuration inherits it. **Under frozen
|
|
||||||
weights `recovery[k]` measures the world's post-switch transient, not adaptation**, and
|
|
||||||
the state-ablation row proves it directly: same curve with the state and without it.
|
|
||||||
|
|
||||||
### 1c. The RP is not quite static — controlled for
|
|
||||||
|
|
||||||
`CONDITIONS["rp_only"]` uses `ctx="affect"`, so `(valence, arousal)` feeds the CPPN.
|
|
||||||
Affect is updated from `loss.item()` every step and freezing weights does not freeze
|
|
||||||
it. **A frozen `rp_only` therefore is not a fixed function of the current observation**
|
|
||||||
as the brief assumed: it retains a 2-d state. Re-running the frozen phase with affect
|
|
||||||
also pinned at its end-of-training value:
|
|
||||||
|
|
||||||
```
|
|
||||||
condition affect live affect pinned
|
|
||||||
-------------------------------------------
|
|
||||||
rp_only 5.257e-05 4.906e-05
|
|
||||||
grp_k0 2.101e-05 2.057e-05
|
|
||||||
ratio 2.50x 2.26x (8/8 seeds either way)
|
|
||||||
```
|
|
||||||
|
|
||||||
Removing the RP's last adaptive channel does not rescue the prediction — the RP's
|
|
||||||
decay gets *stronger* (74% of the excess, up from 57%), confirming the decay is the
|
|
||||||
world's, not affect's.
|
|
||||||
|
|
||||||
### 1d. Correction: the control is not capacity-matched, and the margin is not capacity
|
|
||||||
|
|
||||||
This section replaces the "capacity, not memory" reading above. Three measurements,
|
|
||||||
all at the settings this file already uses (8000 train + 4000 frozen steps, `lr=1e-3`,
|
|
||||||
`bptt=20`, `omega=10`, `kappa=0`, frozen-phase `steady`).
|
|
||||||
|
|
||||||
**(i) 2048 of the 5602 parameters never train.** With `M_prev ≡ 0` the gate and
|
|
||||||
candidate layers both see `[h ‖ 0]`, so the second half of each input weight matrix is
|
|
||||||
multiplied by zero and receives exactly no gradient. Trained `grp_k0` stateless for
|
|
||||||
8000 steps and diffed every block against its initialisation: `gate.weight[:, 32:]`
|
|
||||||
and `cand.weight[:, 32:]` (1024 parameters each) come out at max |Δ| **exactly 0.0**,
|
|
||||||
while every other block moved (max |Δ| 0.035–0.091). The honest effective count for
|
|
||||||
`grp_k0_nostate` is **3554**, not 5602.
|
|
||||||
|
|
||||||
**(ii) It is a different network, not the same network minus state.** With `M_prev = 0`
|
|
||||||
the update `M ← (1−g)·M̃ + g·M` collapses to
|
|
||||||
|
|
||||||
```
|
|
||||||
M = (1 − σ(W_g[h‖0])) · tanh(W_c[h‖0])
|
|
||||||
```
|
|
||||||
|
|
||||||
— a two-layer gated feedforward head on `h`, with no recurrence and no BPTT path
|
|
||||||
through state. The original conclusion needed this control to be *the same network with
|
|
||||||
memory deleted*; it is instead *a simpler, better-conditioned network that happens to
|
|
||||||
share tensor shapes*. That is the difference between "the extra parameters explain the
|
|
||||||
margin" and "this particular feedforward head explains the margin".
|
|
||||||
|
|
||||||
**(iii) A genuinely parameter-matched memoryless model does not close the gap.** The
|
|
||||||
decisive check the original section never ran: widen `rp_only` until it has ≈5602
|
|
||||||
parameters and compare it against `grp_k0`. Two knobs, 8 seeds each, frozen `steady`:
|
|
||||||
|
|
||||||
```
|
|
||||||
condition params mean grp_k0 wins per-seed ratio vs grp_k0
|
|
||||||
--------------------------------------------------------------------------------------
|
|
||||||
rp_only D=32 1442 5.257e-05 8/8 2.47 2.30 1.54 1.48 5.46 2.36 2.53 1.85
|
|
||||||
rp_only D=86 3548 3.915e-05 8/8 1.57 1.33 1.36 1.38 2.33 1.05 2.88 2.48
|
|
||||||
rp_only D=139 5615 1.046e-04 7/8 1.82 6.84 1.41 1.33 2.07 0.99 15.5 1.86
|
|
||||||
rp_only cppn_hidden=141 5584 7.195e-05 8/8 5.58 2.51 2.78 2.08 6.13 1.67 3.84 3.02
|
|
||||||
grp_k0_nostate 5602 2.170e-05 4/8 1.49 0.92 1.33 0.92 0.90 1.08 0.78 1.10
|
|
||||||
grp_k0 5602 2.101e-05 —
|
|
||||||
```
|
|
||||||
|
|
||||||
Reproduction: `frozen.py`'s CLI exposes neither width knob, so these rows came from a
|
|
||||||
throwaway driver that calls `frozen._train` and `frozen._frozen` unchanged against an
|
|
||||||
`Organism(hidden_dim=..., cppn_hidden=...)` built in `_build`'s exact order, so the RNG
|
|
||||||
stream matches. No file in `experiments/` or `ailed/` was modified. The driver is pinned
|
|
||||||
by reproducing `grp_k0_nostate` seed 0 at 2.588e-05, bit-for-bit the value in §1a's
|
|
||||||
per-seed table.
|
|
||||||
|
|
||||||
D=86 is matched to the *effective* 3554; D=139 and `cppn_hidden=141` to the nominal
|
|
||||||
5602. **Parameter-matched by either knob, the memoryless RP gets worse, not better** —
|
|
||||||
D=139 means 1.046e-04 against the 1442-parameter RP's 5.257e-05 — and `grp_k0` still
|
|
||||||
wins 7/8 or 8/8 seeds at every width tried. Only `grp_k0_nostate`, which adds the gated
|
|
||||||
head rather than width, closes it.
|
|
||||||
|
|
||||||
**The corrected claim.** The 2.5x margin is *not* capacity: capacity added as RP width
|
|
||||||
makes the memoryless model worse. The margin comes from the gated post-RP nonlinearity
|
|
||||||
`(1−σ(W_g[h‖0]))·tanh(W_c[h‖0])`, which `grp_k0_nostate` supplies with no memory at
|
|
||||||
all. **The null for memory is unchanged and if anything sharper**: state is still worth
|
|
||||||
1.06x on 4/8 frozen and 1.19x on 11/16 trained, and the mechanism that does the work is
|
|
||||||
the gate acting as a nonlinearity, not as a memory controller.
|
|
||||||
|
|
||||||
*Limitation, stated rather than tuned.* The wide `rp_only` runs use this file's
|
|
||||||
`lr=1e-3` and 8000-step budget unchanged, and a wider model may be lr- or init-limited
|
|
||||||
at that budget. Two of the D=139 seeds destabilise outright — seed 1 at 1.133e-04 and
|
|
||||||
seed 6 at 5.451e-04, against a same-condition median of 3.0e-05 — so the D=139 mean is
|
|
||||||
carried by those two and should be read as instability, not as a clean loss. They are
|
|
||||||
reported and not tuned: retuning a baseline until it catches up changes the question
|
|
||||||
instead of answering it (`AGENTS.md`). What the runs establish is the negative — added
|
|
||||||
width does not buy the margin — not a tight estimate of how a well-tuned wide RP would
|
|
||||||
do.
|
|
||||||
|
|
||||||
## 2. Part B — what does the state know?
|
|
||||||
|
|
||||||
Linear decode from a per-entity representation to the world's regime id. Test split is
|
|
||||||
the last 30% of the frozen phase, taken as a suffix in time so the probe cannot
|
|
||||||
memorise adjacent steps: 2800 training steps × 16 entities = 44 800 samples, 1200 test
|
|
||||||
steps, ~20 switches per seed.
|
|
||||||
|
|
||||||
Chance is measured, not assumed. Two nulls, each refitting the probe from scratch:
|
|
||||||
`shuffle` permutes the step labels (keeping a step's 16 entities together), `shift`
|
|
||||||
circularly shifts the label sequence, which also preserves each regime's 40-80 step
|
|
||||||
block structure and is therefore the stricter of the two — a probe that merely tracks
|
|
||||||
slow drift still scores at the `shift` level. Both land near 0.27, above the naive
|
|
||||||
1/4 = 0.25, which is exactly why the brief asked for it to be measured.
|
|
||||||
|
|
||||||
```
|
|
||||||
representation acc shuffle shift gap seeds > chance
|
|
||||||
---------------------------------------------------------------------------------
|
|
||||||
rp_only h, least squares 0.342 0.289 0.274 +0.067 8/8
|
|
||||||
rp_only h, logistic 0.341 0.289 0.276 +0.065 8/8
|
|
||||||
rp_only h, entity-centred0.341 0.289 0.274 +0.067 8/8
|
|
||||||
grp_k0 h, least squares 0.338 0.292 0.274 +0.065 7/8
|
|
||||||
grp_k0 h, logistic 0.344 0.299 0.275 +0.069 7/8
|
|
||||||
grp_k0 M, least squares 0.332 0.287 0.273 +0.058 7/8
|
|
||||||
grp_k0 M, logistic 0.332 0.293 0.276 +0.056 7/8
|
|
||||||
grp_k0 M, entity-centred0.333 0.287 0.273 +0.060 7/8
|
|
||||||
grp_k0_nostate M, least squares 0.325 0.288 0.275 +0.050 --
|
|
||||||
```
|
|
||||||
|
|
||||||
**The claim under test fails.** The regime is weakly decodable from `M` — and equally
|
|
||||||
weakly decodable from the memoryless RP's `h`, and from the `h` inside the very same
|
|
||||||
GRP organism, which is the comparison that holds the weights fixed. `M` is
|
|
||||||
consistently the *worst* of the three. The GRP's state has not built a regime variable;
|
|
||||||
it has not even preserved as much regime information as the layer feeding it.
|
|
||||||
|
|
||||||
The last row settles what the +0.05 is: the state-ablated GRP, whose `M` is a fixed
|
|
||||||
function of the current `h` with nothing carried between steps, decodes at 0.325. The
|
|
||||||
signal is an instantaneous read-off of the particle configuration — the field the
|
|
||||||
regime is currently imposing is visible in `r` right now — not something a memory
|
|
||||||
accumulated.
|
|
||||||
|
|
||||||
Three ways the null was stressed, none of which changes it:
|
|
||||||
|
|
||||||
- **Estimator.** Multinomial logistic (LBFGS, strong Wolfe) matches least squares to
|
|
||||||
within 0.006 everywhere. Not a least-squares artefact.
|
|
||||||
- **Entity identity.** `M` is dominated by stable per-entity structure (the particle's
|
|
||||||
type). Subtracting each entity's own train-split mean, in case a regime code hides
|
|
||||||
under that offset, moves accuracy by ≤0.002.
|
|
||||||
- **Target.** The regime id is an arbitrary label over four random coupling matrices;
|
|
||||||
what entity *i* actually needs is its own row `k[t_i, :]` of the current one. Probing
|
|
||||||
each of the three signed entries as a 3-class problem, against measured chance:
|
|
||||||
|
|
||||||
```
|
|
||||||
representation acc chance gap above chance
|
|
||||||
-------------------------------------------------------
|
|
||||||
rp_only h 0.514 0.488 +0.025 20/24
|
|
||||||
grp_k0 h 0.517 0.484 +0.033 22/24
|
|
||||||
grp_k0 M 0.506 0.482 +0.024 21/24
|
|
||||||
```
|
|
||||||
|
|
||||||
Same picture on the target the domain actually rewards: `M` last, `h` no worse.
|
|
||||||
|
|
||||||
### Adaptation latency
|
|
||||||
|
|
||||||
Reported for completeness and not interpretable. Decoding the regime per step by
|
|
||||||
averaging the 16 entities' probe scores, the mean number of steps from a switch to the
|
|
||||||
first correct decode is 12.0 for `M` and 10.7 for `rp_only`'s `h` — but 40 of 164
|
|
||||||
switches never decode correctly before the next switch arrives. **A latency measured
|
|
||||||
off a probe running 5 points above chance is measuring the probe's noise.** The honest
|
|
||||||
statement is that neither representation supports reliable regime decoding, so neither
|
|
||||||
has a measurable adaptation latency by this route.
|
|
||||||
|
|
||||||
## 3. What the state is doing instead
|
|
||||||
|
|
||||||
The gate, measured over every frozen step and entity:
|
|
||||||
|
|
||||||
```
|
|
||||||
condition mean g sd frac g>0.9 frac g<0.1
|
|
||||||
---------------------------------------------------------
|
|
||||||
grp_k0 0.500 0.029 0.000 0.000
|
|
||||||
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.
|
|
||||||
**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.**
|
|
||||||
|
|
||||||
Persistence confirms there is no long integration to point at. Lag-1 autocorrelation
|
|
||||||
and the lag at which it falls below 1/e, per channel:
|
|
||||||
|
|
||||||
```
|
|
||||||
condition rep lag-1 tau
|
|
||||||
--------------------------------------
|
|
||||||
rp_only h 0.964 18.1
|
|
||||||
grp_k0 h 0.960 14.0
|
|
||||||
grp_k0 M 0.980 13.6
|
|
||||||
grp_k0_nostate M 0.959 13.1
|
|
||||||
```
|
|
||||||
|
|
||||||
`M` is marginally smoother at lag 1 than the `h` it is built from, and *less* persistent
|
|
||||||
over the 1/e horizon than the memoryless RP's own `h`. Representations in this domain
|
|
||||||
are slow because the world is slow, not because anything is integrating them.
|
|
||||||
|
|
||||||
## 4. Which one understands the domain?
|
|
||||||
|
|
||||||
**Neither, and the question does not currently have a mechanism to attach to.**
|
|
||||||
|
|
||||||
There is no evidence in this experiment that either model has come to represent which
|
|
||||||
regime the world is in. The regime is weakly present in both models' representations at
|
|
||||||
about +0.05 over a measured chance of 0.27, and it is present in exactly the same
|
|
||||||
amount in a network with no state at all, which identifies it as an instantaneous
|
|
||||||
read-off of the visible configuration rather than an internal variable either organism
|
|
||||||
built.
|
|
||||||
|
|
||||||
What the frozen probe does establish, and it is worth having:
|
|
||||||
|
|
||||||
- **The margin is real and it is not a learning-rate artefact.** With every weight
|
|
||||||
bit-frozen, the gated architecture predicts 2.5x better than the plain relational
|
|
||||||
perceptron, on 8 seeds out of 8. Task 7's `lr` objection is answered: no optimiser
|
|
||||||
step is available to either model here.
|
|
||||||
- **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 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.
|
|
||||||
|
|
||||||
The last point is the actionable one. This is a measured null about *this* domain and
|
|
||||||
*this* training budget, not an impossibility result. The gate never learned to gate,
|
|
||||||
and §1b explains why it had no reason to: the post-switch error is dominated by the
|
|
||||||
world's own configuration transient, which no amount of state can shorten. A domain
|
|
||||||
where regime identity is worth something to a per-entity state — where the transient is
|
|
||||||
short and the ambiguity is long — would give the gate a job. This one does not, which
|
|
||||||
is the same conclusion §6(c) of `headroom.md` reached from the other direction.
|
|
||||||
|
|
||||||
## 5. Consequences for A1
|
|
||||||
|
|
||||||
- **Do not claim A1 as a memory result on this domain.** The frozen-weights version of
|
|
||||||
the comparison, which is the strongest form available, attributes the margin to
|
|
||||||
capacity. Any A1 comparison of `rp_only` to `grp_k0` is confounded 3.9x on parameter
|
|
||||||
count and needs `grp_k0_nostate` alongside it, in the trained setting too, where the
|
|
||||||
same decomposition gives capacity 3.04x on 16/16 seeds and state 1.19x on 11/16
|
|
||||||
(medians 2.71x and 1.11x, re-measured at 16 seeds by Task 8; see `a1.md`).
|
|
||||||
- **Task 7's requirement 2 inherits this.** The 2.99x at `lr=1e-3` and the
|
|
||||||
frozen-*regime* reliability argument in `headroom.md` §5 were both measured without a
|
|
||||||
capacity control. Neither is safe to quote as a memory claim as it stands. The
|
|
||||||
frozen-regime runs should be re-run with `grp_k0_nostate` before §5's "memory reaches
|
|
||||||
the floor every time" sentence is carried into the paper.
|
|
||||||
- **`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.
|
|
||||||
@@ -1,345 +0,0 @@
|
|||||||
# Headroom check for the regime setup
|
|
||||||
|
|
||||||
Task 7. This file is the audit trail for the paper's setup section: it records what
|
|
||||||
was measured, which of the three requirements held, every knob that was moved with
|
|
||||||
its before/after, and the conclusion.
|
|
||||||
|
|
||||||
**Verdict: requirement 2 holds but is substantially an artefact of an under-tuned
|
|
||||||
learning rate; requirements 1 and 3 fail. The regime oracle is neutral — it is read,
|
|
||||||
and it changes nothing. The error every condition converges to is set by tracking a
|
|
||||||
target that switches every 40-80 steps, not by missing information.**
|
|
||||||
|
|
||||||
Environment: `experiments/`, `ailed/` unmodified. All runs `uv run` from
|
|
||||||
`experiments/`. Noise floor for every table below is `noise² = 4.0e-06`.
|
|
||||||
Section 3's fits are reproducible with `uv run python ceilings.py`.
|
|
||||||
|
|
||||||
## 1. The table
|
|
||||||
|
|
||||||
`uv run python regime.py --conditions rp_only,grp_k0,grp_regime,rp_flag --seeds 0,1,2 --steps 8000 --out results/headroom.json`
|
|
||||||
|
|
||||||
Means over seeds 0,1,2. `(sd)` is the across-seed standard deviation of `steady`.
|
|
||||||
|
|
||||||
```
|
|
||||||
condition steady (sd) rec@0 rec@2 rec@5 rec@10 a@switch
|
|
||||||
---------------------------------------------------------------------------------------------
|
|
||||||
rp_only 0.000061 0.000020 0.000070 0.000080 0.000103 0.000090 0.130
|
|
||||||
grp_k0 0.000021 0.000004 0.000028 0.000031 0.000045 0.000043 0.127
|
|
||||||
grp_regime 0.000029 0.000006 0.000052 0.000054 0.000067 0.000057 0.203
|
|
||||||
rp_flag 0.000060 0.000024 0.000280 0.000110 0.000120 0.000095 0.422
|
|
||||||
```
|
|
||||||
|
|
||||||
Per-seed `steady`, because the across-seed spread is comparable to the effects being
|
|
||||||
claimed and the paired comparison is what carries the result:
|
|
||||||
|
|
||||||
```
|
|
||||||
condition seed 0 seed 1 seed 2 grp_k0 beaten?
|
|
||||||
rp_only 8.09e-05 6.17e-05 4.17e-05 no (0/3)
|
|
||||||
grp_k0 2.39e-05 1.67e-05 2.11e-05 --
|
|
||||||
grp_regime 3.51e-05 2.38e-05 2.77e-05 no (0/3, worse on every seed)
|
|
||||||
rp_flag 6.13e-05 3.65e-05 8.36e-05 no (0/3)
|
|
||||||
```
|
|
||||||
|
|
||||||
## 2. The three requirements
|
|
||||||
|
|
||||||
### Requirement 1 — FAILS
|
|
||||||
|
|
||||||
> `grp_regime` steady error must sit near the noise floor `4e-6` (within ~3x).
|
|
||||||
|
|
||||||
`grp_regime` steady is 2.9e-05, 7x the floor, and it is *worse* than `grp_k0`
|
|
||||||
(2.1e-05) on all three seeds. Longer training does not rescue it: at 40 000 steps it
|
|
||||||
is still worse on all three seeds (1.7e-05 vs 1.5e-05).
|
|
||||||
|
|
||||||
The condition is not reached at any setting tried here, and §3 shows the regime is not
|
|
||||||
where the missing information is. But this is a measured failure, not an impossibility
|
|
||||||
result — with the regime *frozen* the same architecture reaches 5.08e-06, 1.27x the
|
|
||||||
noise floor (§5). What blocks requirement 1 is the switching, not the oracle.
|
|
||||||
|
|
||||||
### Requirement 2 — HOLDS at the default, but the margin is largely an `lr` artefact
|
|
||||||
|
|
||||||
> `grp_k0` must beat `rp_only` on `steady` and on `rec@10`.
|
|
||||||
|
|
||||||
At the default `lr=1e-3`, 8000 steps: `grp_k0` beats `rp_only` 2.9x on steady and
|
|
||||||
2.1x on `rec@10`, on every seed. It still wins on all three seeds at 40 000 steps.
|
|
||||||
|
|
||||||
**But the margin decays monotonically with learning rate and is gone by `lr=1e-2`**
|
|
||||||
(seeds 0,1,2, 8000 steps, mean `steady`):
|
|
||||||
|
|
||||||
```
|
|
||||||
lr rp_only grp_k0 grp_regime memory advantage
|
|
||||||
1e-3 6.141e-05 2.055e-05 2.888e-05 2.99x
|
|
||||||
3e-3 3.189e-05 1.627e-05 1.840e-05 1.96x
|
|
||||||
1e-2 1.681e-05 1.584e-05 1.534e-05 1.06x
|
|
||||||
```
|
|
||||||
|
|
||||||
`rp_only` improves 3.7x with `lr`; `grp_k0` improves 1.3x. **Memory is substantially
|
|
||||||
compensating for an optimiser that is stepping too slowly**, and A1 cannot quote the
|
|
||||||
2.99x without saying it is measured at a learning rate at which the memoryless
|
|
||||||
baseline is not converged. (At `lr=1e-2` `grp_regime` is nominally best at 1.534e-05,
|
|
||||||
but the three conditions are within 3% of each other and of the 40 000-step plateau;
|
|
||||||
that ordering is noise, not an oracle effect.)
|
|
||||||
|
|
||||||
The same caveat applies to `omega`, more weakly: the advantage is 2.99x at `omega=10`
|
|
||||||
and 1.5x at `omega=5`, because `omega` strongly affects `rp_only` and not `grp_k0`.
|
|
||||||
|
|
||||||
Requirement 2 holds as written. It should not be reported without both ablations.
|
|
||||||
|
|
||||||
### Requirement 3 — FAILS
|
|
||||||
|
|
||||||
> `rp_flag` must equal `rp_only` within seed noise on every column.
|
|
||||||
|
|
||||||
It does not. `rp_flag` matches `rp_only` on `steady` (6.0e-05 vs 6.1e-05) but is 4x
|
|
||||||
worse at `rec@0` (2.8e-04 vs 7.0e-05), on every seed.
|
|
||||||
|
|
||||||
It is **not** an information leak. Diagnostic, holding `attr_dim` at 4 in all three
|
|
||||||
flag rows so parameter count and init draw are identical and only the column's
|
|
||||||
*contents* change:
|
|
||||||
|
|
||||||
```
|
|
||||||
variant steady rec@0 rec@2 rec@5
|
|
||||||
----------------------------------------------------------------------
|
|
||||||
rp_only (attr_dim=3) 0.000061 0.000070 0.000080 0.000103
|
|
||||||
rp_flag flag fires 0.000060 0.000280 0.000110 0.000120
|
|
||||||
rp_flag flag always 0 0.000071 0.000071 0.000076 0.000096
|
|
||||||
rp_flag flag always 1 0.000133 0.000134 0.000166 0.000179
|
|
||||||
```
|
|
||||||
|
|
||||||
With the column present but never firing, `rp_flag` reproduces `rp_only`; the extra
|
|
||||||
column is harmless. With it pinned on, everything degrades uniformly. The `rec@0`
|
|
||||||
spike is caused by the column *changing value*, at the exact step `rec@0` measures.
|
|
||||||
|
|
||||||
Mechanism. `attrs` enters the RP only through `f_j = W_feat attrs_j`, the message
|
|
||||||
*from* `j`, and the flag column is the same value on every particle, so firing it
|
|
||||||
shifts every message by a fixed `(Σ_j m_ij) ⊙ w_flag`. The flag column is **not**
|
|
||||||
under-trained relative to the type columns — measured, `attr_dim=4`, seed 0:
|
|
||||||
|
|
||||||
```
|
|
||||||
type cols flag col
|
|
||||||
W_feat init norm 1.831 1.607 1.461 1.893
|
|
||||||
drift over 8000 0.152 0.119 0.157 0.134
|
|
||||||
```
|
|
||||||
|
|
||||||
and with `bptt=20` the flag falls within **32%** of optimiser steps even though it is
|
|
||||||
on for only 1.6% of individual steps. The operative fact is the other one: its random
|
|
||||||
init has norm 1.89, *comparable to a type embedding*, and it fires too rarely for the
|
|
||||||
rest of the network to have absorbed it. So when it fires it injects a
|
|
||||||
type-embedding-sized perturbation into every message, precisely where `rec@0` looks.
|
|
||||||
|
|
||||||
This matters beyond the control: **`grp_flag` is an A1 condition with the same
|
|
||||||
defect.** As encoded it does not test "does knowing a change occurred help"; it tests
|
|
||||||
"does memory absorb an input spike". §6(a) fixes it.
|
|
||||||
|
|
||||||
## 3. Where the information sits — a linearised bound, not a bound on the model
|
|
||||||
|
|
||||||
Reproduce with `uv run python ceilings.py`. The script fits, by least squares over a
|
|
||||||
rolled-out world, the best predictor of the form
|
|
||||||
`d_i = a[offset(i)] + Σ_j c[key(i,j)] · dt · kern(r_ij) · r_ij`, handing the fit the
|
|
||||||
radial kernel exactly. Means over seeds 0,1,2, 1200 world steps:
|
|
||||||
|
|
||||||
```
|
|
||||||
information set MSE(det part) MSE(vs target)
|
|
||||||
-----------------------------------------------------------------------
|
|
||||||
A perfect: (regime, t_i, t_j) 1.262e-19 4.011e-06
|
|
||||||
B regime-blind, pair-aware (t_i, t_j) 1.298e-05 1.694e-05
|
|
||||||
C regime oracle (regime, t_j) 7.684e-06 1.166e-05
|
|
||||||
D no oracle (t_j) 1.427e-05 1.820e-05
|
|
||||||
|
|
||||||
oracle prize D->C: 1.86x on the deterministic part, 1.56x against the noisy target
|
|
||||||
```
|
|
||||||
|
|
||||||
Row A is the self-check, and the script asserts it: given `(regime, t_i, t_j)` the
|
|
||||||
family spans the dynamics exactly (residual 1.3e-19) and lands on 4.011e-06, the noise
|
|
||||||
floor. (An earlier version of this table read 4.52e-06 for row A. That was a bug: the
|
|
||||||
fit captured `world.regime` *before* `step()`, but `step()` switches the regime before
|
|
||||||
computing the delta, so ~1.7% of rows carried a stale regime. Fixed in `ceilings.py`;
|
|
||||||
the corrected row A landing on the floor is what confirms it.)
|
|
||||||
|
|
||||||
**Scope — this is not a bound on the trained architecture.** The fitted family is
|
|
||||||
linear in the messages. The real RP applies `tanh` to the aggregate, which turns the
|
|
||||||
`t_i`-carrying self-term (`j = i` at `r = 0`, since the default `mask` includes the
|
|
||||||
diagonal) into a *gain modulation* on the whole sum rather than a bare additive
|
|
||||||
offset, and the GRP adds per-entity state on top. An earlier draft of this file said
|
|
||||||
the receiver's own type "can never modulate the per-neighbour message" and concluded
|
|
||||||
requirement 1 was unreachable in principle. That was an overclaim: true of the linear
|
|
||||||
family, false of the composed model. **Every "cannot" of that kind is withdrawn.**
|
|
||||||
Read the table as a map of where the information sits, not as a statement about what
|
|
||||||
the architecture can reach.
|
|
||||||
|
|
||||||
(For the record, the frozen-regime runs do not by themselves demonstrate a violation
|
|
||||||
of rows C and D: memoryless `rp_only` frozen reaches 4.964e-06 on seed 0, but C and D
|
|
||||||
were fit on a *switching* world, where regime-blindness costs something, so that is
|
|
||||||
not a like-for-like comparison. Refitting the `t_i`-blind ceiling on a frozen world
|
|
||||||
gives 4.571e-06, and 4.964e-06 sits above it. The reframing above rests on the
|
|
||||||
linearity of the family, which is reason enough.)
|
|
||||||
|
|
||||||
What the table does support:
|
|
||||||
|
|
||||||
1. **The oracle prize is small.** No oracle (D, 1.820e-05) to regime oracle
|
|
||||||
(C, 1.166e-05) is worth **1.56x**, and `grp_k0` already measures 1.5e-05 at
|
|
||||||
40 000 steps — already inside that band. Memory recovers most of what the regime
|
|
||||||
oracle could say, which is why saying it adds nothing.
|
|
||||||
2. **The regime is not the scarce information.** B (1.694e-05, knows `t_i,t_j`, not
|
|
||||||
the regime) and C (1.166e-05, knows the regime, not `t_i`) bracket each other and
|
|
||||||
neither approaches A. A regime oracle cannot supply `t_i`.
|
|
||||||
|
|
||||||
## 4. Knobs changed
|
|
||||||
|
|
||||||
One thing at a time; same seeds (0,1,2) before and after; every change re-ran the
|
|
||||||
affected conditions.
|
|
||||||
|
|
||||||
| knob | before | after | evidence | kept? |
|
|
||||||
|---|---|---|---|---|
|
|
||||||
| `run(omega=...)` in `regime.py` | not a parameter (hard-coded 10.0) | parameter, **default 10.0** | plumbing only; default unchanged so all prior runs reproduce | **yes** |
|
|
||||||
| `omega` value | 10.0 | tried 5, 20 | see below | **no — kept 10.0** |
|
|
||||||
| `lr` | 1e-3 | tried 3e-3, 1e-2 | §2 requirement 2 | **no — kept 1e-3** |
|
|
||||||
| `noise` | 0.002 | tried 0.0005 | see below | **no — kept 0.002** |
|
|
||||||
| `sigma` | 0.2 | tried 0.3 | see below | **no — kept 0.2** |
|
|
||||||
| `steps` | 8000 | also 40000 | §2, §5 | diagnostic only |
|
|
||||||
| `t_min`/`t_max` | 40/80 | frozen (10⁹) | §5 | diagnostic only |
|
|
||||||
| `edge_types` | `None` (1 type) | tried type-pair (9) | see below | **no** |
|
|
||||||
|
|
||||||
**No default in `particles.py` or `regime.py` was changed.** The only source changes
|
|
||||||
are the `omega` parameter, whose default reproduces previous behaviour exactly, and
|
|
||||||
the new `ceilings.py`. Tasks 8 and 9 run against the same parameters Task 6 was
|
|
||||||
reviewed under. `../ailed` is untouched.
|
|
||||||
|
|
||||||
### omega — ruled out
|
|
||||||
|
|
||||||
`grp_k0` and `grp_regime` are insensitive; only `rp_only` moves, and the ordering
|
|
||||||
never flips.
|
|
||||||
|
|
||||||
```
|
|
||||||
omega rp_only grp_k0 grp_regime
|
|
||||||
5 3.0e-05 2.0e-05 2.6e-05
|
|
||||||
10 6.1e-05 2.1e-05 2.9e-05 <- kept
|
|
||||||
20 7.7e-05 2.2e-05 3.3e-05
|
|
||||||
```
|
|
||||||
|
|
||||||
### noise and sigma — ruled out, decisively
|
|
||||||
|
|
||||||
Cutting `noise` 4x lowers the irreducible floor 16x (4.0e-06 → 2.5e-07) and barely
|
|
||||||
moves any measured error:
|
|
||||||
|
|
||||||
```
|
|
||||||
noise sigma floor rp_only grp_k0 grp_regime
|
|
||||||
0.002 0.2 4.0e-06 6.1e-05 2.1e-05 2.9e-05
|
|
||||||
0.0005 0.2 2.5e-07 5.9e-05 1.8e-05 2.9e-05
|
|
||||||
0.002 0.3 4.0e-06 7.8e-05 4.3e-05 5.5e-05
|
|
||||||
0.0005 0.3 2.5e-07 7.1e-05 4.1e-05 5.3e-05
|
|
||||||
```
|
|
||||||
|
|
||||||
At `noise=0.0005` the models sit ~70x above the floor. The residual is model error,
|
|
||||||
not noise. `grp_regime` is worse than `grp_k0` in all four cells.
|
|
||||||
|
|
||||||
### edge_types — helps, does not change the verdict
|
|
||||||
|
|
||||||
`regime.py` passes `edge_types=None`, so every pair is edge type 0 and the CPPN never
|
|
||||||
sees the type pair. Opening it (`t_i * n_types + t_j`, 9 edge types), both arms
|
|
||||||
measured by the same script:
|
|
||||||
|
|
||||||
```
|
|
||||||
steps edge types rp_only grp_k0 grp_regime
|
|
||||||
8000 single (1) 6.1e-05 2.1e-05 2.9e-05
|
|
||||||
8000 pair (9) 3.0e-05 1.9e-05 2.2e-05
|
|
||||||
40000 single (1) 2.3e-05 1.5e-05 1.7e-05
|
|
||||||
40000 pair (9) 1.7e-05 1.5e-05 1.6e-05
|
|
||||||
```
|
|
||||||
|
|
||||||
## 5. The control that isolates the cause: freeze the regime
|
|
||||||
|
|
||||||
Nothing changed but `t_min`/`t_max`, set beyond the run length so the regime is drawn
|
|
||||||
once and never switches. 40 000 steps, seeds 0,1,2:
|
|
||||||
|
|
||||||
```
|
|
||||||
regime condition steady per-seed
|
|
||||||
------------------------------------------------------------------
|
|
||||||
switching rp_only 2.271e-05 1.390e-05 3.372e-05 2.051e-05
|
|
||||||
switching grp_k0 1.516e-05 1.113e-05 1.457e-05 1.977e-05
|
|
||||||
switching grp_regime 1.716e-05 1.256e-05 1.632e-05 2.260e-05
|
|
||||||
|
|
||||||
frozen rp_only 3.891e-05 4.964e-06 4.604e-05 6.573e-05
|
|
||||||
frozen grp_k0 5.119e-06 5.199e-06 4.628e-06 5.529e-06
|
|
||||||
frozen grp_regime 5.080e-06 5.126e-06 4.679e-06 5.435e-06
|
|
||||||
```
|
|
||||||
|
|
||||||
This is the cleanest result in the file. It separates "the model must infer the
|
|
||||||
regime" from "the target is non-stationary", which the 40 000-step and edge-type
|
|
||||||
tables cannot.
|
|
||||||
|
|
||||||
- **`grp_k0` goes 1.516e-05 → 5.119e-06 and `grp_regime` 1.716e-05 → 5.080e-06 —
|
|
||||||
1.27x the noise floor.** The architecture *can* essentially solve this domain. The
|
|
||||||
entire remaining gap in the switching world is caused by regime switching: not by
|
|
||||||
noise (§4), not by capacity, not by the missing pair channel.
|
|
||||||
- **The oracle is neutral here too, as it must be**: frozen, `grp_regime`
|
|
||||||
(5.080e-06) and `grp_k0` (5.119e-06) are identical. With the regime frozen the
|
|
||||||
one-hot is a constant carrying zero information, so this is the expected result, and
|
|
||||||
it confirms the oracle plumbing is inert rather than harmful once the encoding
|
|
||||||
artefact of §6(a) is out of the way.
|
|
||||||
- **Memory's job in the frozen world is reliability, not mean error.** `rp_only`
|
|
||||||
frozen ranges over 13x across three seeds (4.964e-06 to 6.573e-05) while `grp_k0`
|
|
||||||
is 5.1e-06 ± 0.4e-06. Memoryless can reach the floor and often does not; memory
|
|
||||||
reaches it every time. This is a different and better-founded case for requirement 2
|
|
||||||
than the mean-error margin that the `lr` ablation undercuts.
|
|
||||||
|
|
||||||
## 6. Conclusion and recommendations
|
|
||||||
|
|
||||||
**The regime oracle is neutral in this setup, and requirement 1 is not reached at any
|
|
||||||
setting tried.** The oracle is read; the information it carries is worth 1.56x within
|
|
||||||
the linearised family; and the trained models never get close enough to any ceiling
|
|
||||||
for that to matter, because their error is dominated by tracking a target that
|
|
||||||
switches every 40-80 steps. Freezing the regime drops `grp_regime` from 2.9e-05 to
|
|
||||||
5.08e-06, 1.27x the noise floor, with nothing else changed — the switching is the
|
|
||||||
whole story. `grp_regime` should be reported as a measured null, not carried into A1
|
|
||||||
as a ceiling.
|
|
||||||
|
|
||||||
Requirement 2 holds at the default on every seed and at both budgets, but the 2.99x
|
|
||||||
margin is substantially an artefact of an under-tuned learning rate: at `lr=1e-2` it
|
|
||||||
is 1.06x. The defensible version of the memory claim is the frozen-regime one —
|
|
||||||
memory reaches the noise floor reliably where memoryless does so on one seed in three
|
|
||||||
— not the mean-error margin at `lr=1e-3`.
|
|
||||||
|
|
||||||
**(a) Zero-initialise the oracle columns of `W_feat`.** One line in `regime.py` after
|
|
||||||
`Organism` is built (`ailed` should not need to know which columns are oracle
|
|
||||||
columns):
|
|
||||||
|
|
||||||
```python
|
|
||||||
with torch.no_grad():
|
|
||||||
org.rp.feat.weight[:, wcfg.n_types:] = 0.0 # oracle columns start as a no-op
|
|
||||||
```
|
|
||||||
|
|
||||||
An oracle column then starts as an exact no-op and can only act once gradient has
|
|
||||||
earned it a weight. Measured, seeds 0,1,2, 8000 steps:
|
|
||||||
|
|
||||||
```
|
|
||||||
init condition steady rec@0 rec@2 rec@5
|
|
||||||
--------------------------------------------------------------------
|
|
||||||
default rp_only 0.000061 0.000070 0.000080 0.000103
|
|
||||||
default rp_flag 0.000060 0.000280 0.000110 0.000120
|
|
||||||
default grp_regime 0.000029 0.000052 0.000054 0.000067
|
|
||||||
|
|
||||||
zero-init oracle cols rp_only 0.000061 0.000070 0.000080 0.000103
|
|
||||||
zero-init oracle cols rp_flag 0.000076 0.000077 0.000085 0.000105
|
|
||||||
zero-init oracle cols grp_regime 0.000021 0.000029 0.000034 0.000049
|
|
||||||
```
|
|
||||||
|
|
||||||
`rp_only` is unchanged, but that is a tautology rather than evidence — `rp_only` has
|
|
||||||
no oracle columns, so the line is a no-op for it by construction. The measured results
|
|
||||||
are the other two rows: `rp_flag`'s 4x `rec@0` spike disappears and it tracks
|
|
||||||
`rp_only`, so **requirement 3 holds under this fix**; and `grp_regime` drops from
|
|
||||||
2.9e-05 to 2.1e-05, exactly equal to `grp_k0`. With the artefact removed, **the regime
|
|
||||||
oracle is precisely neutral** — not "the oracle hurts", but "the oracle changes
|
|
||||||
nothing". Not adopted: it moves every oracle condition off what Task 6 was reviewed
|
|
||||||
under, and A1's condition list may change in response to this file.
|
|
||||||
|
|
||||||
**(b) Restate requirement 1 against something measurable.** `noise² = 4e-06` is the
|
|
||||||
floor for a model that knows `(regime, t_i, t_j)`. Either compare `grp_regime` to the
|
|
||||||
regime oracle's linearised ceiling (1.166e-05), or — better, since §5 shows the
|
|
||||||
architecture reaches 5.08e-06 once the regime stops moving — state requirement 1 as a
|
|
||||||
*recovery* requirement rather than a steady-state one. Steady-state error in this
|
|
||||||
domain is a tracking measurement, and requirement 1 currently reads as if it were a
|
|
||||||
capacity measurement.
|
|
||||||
|
|
||||||
**(c) If A1 needs an oracle with real headroom, the domain must change.** The prize
|
|
||||||
(1.56x) is smaller than what the optimiser is losing to tracking (3x, from §5). Widen
|
|
||||||
the contrast between regimes, slow the switching, or raise `lr` so tracking stops
|
|
||||||
dominating — and measure the headroom again before building on any of them, since §2
|
|
||||||
shows `lr` alone reorders the conditions.
|
|
||||||
@@ -1,90 +0,0 @@
|
|||||||
# The knight null was an input, not an architecture
|
|
||||||
|
|
||||||
`sharp.md` measured that shown six of a knight's eight L-squares, neither the CPPN nor any
|
|
||||||
control finds the other two — everything at or above the floor. That looked like a verdict on
|
|
||||||
relational architectures. It was a verdict on what the kernel was allowed to see.
|
|
||||||
|
|
||||||
The CPPN reads `r_ij` raw. It has no reason to know that (1,2) and (-2,-1) are the same law;
|
|
||||||
they are two different points of the plane. Canonicalise the displacement to
|
|
||||||
`(min|dx|, max|dy|)` — a D4 invariant — and the square's eight symmetries collapse to one orbit.
|
|
||||||
The knight's eight squares become **a single input**.
|
|
||||||
|
|
||||||
```
|
|
||||||
teacher arm seen unseen floor u/floor vs rp
|
|
||||||
knight_sym rp 0.00097 0.02395 0.02182 1.098
|
|
||||||
knight_sym rp_inv 0.00002 0.00009 0.02182 0.004 -0.02386 +/- 0.00154 6/6
|
|
||||||
knight_sym table_interp 0.00001 0.02205 0.02182 1.010 -0.00190 +/- 0.00014 6/6
|
|
||||||
knight rp 0.00117 0.02359 0.02228 1.059
|
|
||||||
knight rp_inv 0.00130 0.02611 0.02228 1.172 +0.00252 +/- 0.00189 2/6
|
|
||||||
smooth rp 0.00006 0.00007 0.01533 0.004
|
|
||||||
smooth rp_inv 0.00138 0.00216 0.01533 0.141 +0.00209 +/- 0.00025 0/6
|
|
||||||
```
|
|
||||||
|
|
||||||
**Six of eight L-squares gives the other two, exactly.** 0.02395 → 0.00009, 0.4% of the floor,
|
|
||||||
6 seeds out of 6, per-seed 0.00012 0.00008 0.00007 0.00012 0.00004 0.00012 — no spread worth
|
|
||||||
reporting. The same architecture, the same parameters, the same training data. Only the
|
|
||||||
parameterisation of the relation changed.
|
|
||||||
|
|
||||||
It is also 48x better on the cells it *did* train on (0.00097 → 0.00002). Eight squares became
|
|
||||||
one thing to learn, so this is sample efficiency and generalisation from the same cause.
|
|
||||||
|
|
||||||
## The two controls are why this means anything
|
|
||||||
|
|
||||||
Handing a model an invariance does not sneak the held-out cells into training — it hands over
|
|
||||||
the **claim** that those cells are equivalent to ones it saw. The controls test that claim in
|
|
||||||
both directions, and both were predicted before the run.
|
|
||||||
|
|
||||||
**When the claim is false, the invariance hurts.** The `knight` teacher puts a different value on
|
|
||||||
each of the eight squares: they share a support but not a rule. `rp_inv` reads 0.02611 against
|
|
||||||
plain `rp`'s 0.02359 — worse than doing nothing, and worse than the floor. It is not that
|
|
||||||
invariants always win.
|
|
||||||
|
|
||||||
**When the claim is the wrong one, it costs 31x.** The smooth Gabor has random frequency
|
|
||||||
directions and no D4 symmetry. Collapsing eight directions into one destroys information the
|
|
||||||
model needed: 0.00007 → 0.00216, 0/6 seeds. **An invariance is a commitment, not a free lunch.**
|
|
||||||
|
|
||||||
## What this says
|
|
||||||
|
|
||||||
A relational architecture infers a rule exactly when the domain's invariance is in its input,
|
|
||||||
and pays for the invariance where the domain does not have it. That is a statement about
|
|
||||||
relational architectures rather than about knights, and it is the same shape as this project's
|
|
||||||
other good result — `chess_reach.md`'s finding that the piece type must enter the kernel rather
|
|
||||||
than scale it. Both are failures of **what was expressible in the input**, not of capacity. That
|
|
||||||
is now five separate times in this project, and it is the pattern worth taking to the paper.
|
|
||||||
|
|
||||||
For the RP verdict, this reverses the conclusion `sharp.md` was heading towards. The RP does not
|
|
||||||
have to be let go. Its knight null was our input design, and when the input carries the group the
|
|
||||||
same mechanism does rule inference cleanly.
|
|
||||||
|
|
||||||
## What it does not say, and this is the real frontier
|
|
||||||
|
|
||||||
**The model is GIVEN the group. It does not find it.** `rp_inv` is handed the exact symmetry the
|
|
||||||
teacher was built with. So the claim earned is: *if you know a domain's invariance, putting it in
|
|
||||||
the kernel's input converts unseen orbit members into seen ones.* Whether a model can **discover**
|
|
||||||
which invariance a domain has is untouched, and it is arguably what the word "understanding" in
|
|
||||||
this project's framing actually means. Everything measured so far — including this — is a model
|
|
||||||
applying structure it was given.
|
|
||||||
|
|
||||||
That is the sharpest open question the project has, and unlike the ones before it, it does not
|
|
||||||
have an obvious cheap oracle. Candidates: a model that learns the canonicalisation, or one
|
|
||||||
scored across a family of domains with different groups so that discovering the right one is the
|
|
||||||
only way to win.
|
|
||||||
|
|
||||||
**Also untested:** one group (D4), one sparse family, one exactly-representable student-teacher
|
|
||||||
setup. And a prediction this now makes, for the parked chess arc: a kernel given D4 invariants
|
|
||||||
should learn piece movement from fewer positions and generalise to offsets it never saw. That is
|
|
||||||
recorded as a prediction, not a result.
|
|
||||||
|
|
||||||
## Reproduce
|
|
||||||
|
|
||||||
```
|
|
||||||
for t in knight_sym knight smooth; do
|
|
||||||
uv run python unseen.py --teacher $t --holdout support --arms rp,rp_inv,table_interp \
|
|
||||||
--omega 2 --steps 2500 --seeds 0,1,2,3,4,5 --out results/inv_${t}.json
|
|
||||||
done
|
|
||||||
```
|
|
||||||
|
|
||||||
Tests: `tests/test_unseen.py`. One of them exists because an edit silently failed to land and
|
|
||||||
`rp_inv` ran as plain `rp`, producing two identical columns that could have been read as
|
|
||||||
"invariants change nothing"; the arm dispatch now raises on an unknown name and the test asserts
|
|
||||||
each arm builds the kernel it claims.
|
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
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
|
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
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
|
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
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
|
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
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
|
|
||||||
@@ -1,88 +0,0 @@
|
|||||||
# omega: a knob that was set wrong, not a defect to design around
|
|
||||||
|
|
||||||
`unseen.md` found a 17x swing in held-out error between two hand-picked values of `omega`, the
|
|
||||||
CPPN's bandwidth, and noted that every chess number in this project sits at one of them without
|
|
||||||
anyone having examined it. This file decides which of two things that is:
|
|
||||||
|
|
||||||
- a **knob** that wants a value per domain — document it, choose it, leave `AffectiveCPPN` alone;
|
|
||||||
- a **defect** — a narrow optimum that moves with the domain, in which case a learned or
|
|
||||||
multi-scale frequency is a mechanism question worth asking rather than a tune.
|
|
||||||
|
|
||||||
The answer is the first one, and the reason the code already gave for it is measured **false**.
|
|
||||||
|
|
||||||
## The curve, one domain, 8 seeds
|
|
||||||
|
|
||||||
MSE on held-out relations, `unseen.py`, teacher bandwidth `kfreq=0.35`.
|
|
||||||
|
|
||||||
```
|
|
||||||
omega 0.25 0.5 1 2 4 8 16
|
|
||||||
random 0.00052 0.00016 0.00008 0.00006 0.00007 0.00112 0.00019
|
|
||||||
band 0.00087 0.00034 0.00014 0.00008 0.00007 0.00064 0.00028
|
|
||||||
(seen) 0.00044 0.00012 0.00007 0.00006 0.00006 0.00024 0.00011
|
|
||||||
```
|
|
||||||
|
|
||||||
A plateau at **omega ∈ [1,4]**, in the same place for both hold-out structures. The project's
|
|
||||||
default of 10 sits outside it, 7-11x worse than the optimum. `omega=1`, which `unseen.md` ran
|
|
||||||
at and which was picked without measuring, is not the optimum either — 2 is. That result was
|
|
||||||
obtained by luck, and it is recorded as luck.
|
|
||||||
|
|
||||||
**omega=8 is unstable, not merely mis-tuned.** Per seed: 0.00028, 0.00425, 0.00016, 0.00127,
|
|
||||||
0.00037, 0.00159, 0.00043, 0.00059. `seen` degrades with it (0.00024), so this is optimisation
|
|
||||||
breaking down rather than a bandwidth mismatch — and 16 recovers to 0.00019. The curve has a
|
|
||||||
cliff in the middle, not a single valley, and a sweep of three points could have missed it.
|
|
||||||
|
|
||||||
## Does the optimum move with the domain? No.
|
|
||||||
|
|
||||||
The deciding axis. `kfreq` is the **domain's** spatial frequency, `omega` the **model's**.
|
|
||||||
6 seeds, random hold-out, MSE on held-out relations.
|
|
||||||
|
|
||||||
```
|
|
||||||
kfreq \ omega 0.5 1 2 4 8 best
|
|
||||||
0.15 0.00006 0.00003 0.00003 0.00003 0.00138 4
|
|
||||||
0.35 0.00017 0.00009 0.00006 0.00006 0.00132 2
|
|
||||||
0.70 0.00118 0.00046 0.00028 0.00020 0.00143 4
|
|
||||||
```
|
|
||||||
|
|
||||||
The optimum sits at 2-4 across a domain bandwidth that varies by 4.7x. It does not track the
|
|
||||||
domain. What *does* change with the domain is the **penalty for being under-banded**: at
|
|
||||||
`kfreq=0.7` an `omega` of 0.5 costs 6x the optimum, at `kfreq=0.15` only 2x. And `omega=8`
|
|
||||||
fails at ~0.0013-0.0014 for every domain tested, which confirms the cliff is a property of the
|
|
||||||
model, not of what it is fitting.
|
|
||||||
|
|
||||||
**This contradicts the comment in `core.py`**, which states that omega "is a calibration knob
|
|
||||||
that wants tuning against the domain's length scale". That was a plausible assumption and it is
|
|
||||||
now measured false over the range tested: a fixed value in [2,4] is near-optimal for every
|
|
||||||
domain bandwidth here. The comment should say what the measurement says.
|
|
||||||
|
|
||||||
## What follows
|
|
||||||
|
|
||||||
**Do not rework `AffectiveCPPN`.** There is a broad plateau, it does not move, and a learned or
|
|
||||||
multi-scale frequency would be solving a problem that was not found. That option stays available
|
|
||||||
if a domain ever turns up whose optimum is outside [1,4]; none has.
|
|
||||||
|
|
||||||
**The default is a footgun and the debt is recorded rather than paid here.** Every chess number
|
|
||||||
in this project was produced at `omega=10`, outside the plateau. Those results are comparisons
|
|
||||||
at a *fixed* omega, so the comparisons remain fair and nothing in `chess_reach.md`,
|
|
||||||
`chess_rules.md` or `chess_dist.md` is invalidated — but their absolute levels come from a
|
|
||||||
badly calibrated kernel, and how much of the gap to the rule-knowing control was bandwidth is
|
|
||||||
unknown. Re-running the chess arc in the plateau belongs to the chess arc, which is parked.
|
|
||||||
|
|
||||||
## What this does not establish
|
|
||||||
|
|
||||||
Three domain bandwidths over one order of magnitude, one teacher family (Gabor), one hold-out
|
|
||||||
structure for the grid, 6 seeds. The grid's resolution in omega is 2x, so a shift in the optimum
|
|
||||||
smaller than that would not show. "The optimum does not move" is a statement about this range,
|
|
||||||
and the honest form of it is: nothing was found that would justify redesigning the kernel's
|
|
||||||
frequency, which is a weaker claim than nothing exists.
|
|
||||||
|
|
||||||
## Reproduce
|
|
||||||
|
|
||||||
```
|
|
||||||
for w in 0.25 0.5 1 2 4 8 16; do for k in random band; do
|
|
||||||
uv run python unseen.py --holdout $k --arms rp --omega $w --steps 2500 \
|
|
||||||
--seeds 0,1,2,3,4,5,6,7 --out results/sweep_${k}_w${w}.json; done; done
|
|
||||||
for kf in 0.15 0.35 0.70; do for w in 0.5 1 2 4 8; do
|
|
||||||
uv run python unseen.py --holdout random --arms rp --omega $w --kfreq $kf --steps 2500 \
|
|
||||||
--seeds 0,1,2,3,4,5 --out results/grid_k${kf}_w${w}.json; done; done
|
|
||||||
uv run python analyse_sweep.py
|
|
||||||
```
|
|
||||||
@@ -1,270 +0,0 @@
|
|||||||
# 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.
|
|
||||||
-114
@@ -1,114 +0,0 @@
|
|||||||
# psi as a continuous kernel axis — the deciding test, and it decided against
|
|
||||||
|
|
||||||
> **SUPERSEDED IN PART by `sharp.md`.** The withheld box here is interior, with trained bins on
|
|
||||||
> all four sides, which is the easy case. Re-run with a corner box the CPPN goes from losing to
|
|
||||||
> beating the same-resolution table on 5/6 seeds and tying the one with 320x its parameters.
|
|
||||||
|
|
||||||
|
|
||||||
After `unseen.md` and `scale.md` the RP's distinguishing claim against a lookup had narrowed to
|
|
||||||
one thing: **parameter compression where the relation space cannot be enumerated.** psi is the
|
|
||||||
only genuinely continuous axis this architecture has — a table over (offset × valence × arousal)
|
|
||||||
must bin the last two — so this was the experiment that would settle whether the CPPN is a
|
|
||||||
capability or a parameterisation.
|
|
||||||
|
|
||||||
**It is a parameterisation.** A binned table plus interpolation along psi matches the CPPN's
|
|
||||||
accuracy on withheld psi, on 6 seeds out of 6, using 80× to 320× more parameters. What the CPPN
|
|
||||||
buys is size, not answers.
|
|
||||||
|
|
||||||
The negative branch was written into `psi.py` before the run: *"if a coarse table plus
|
|
||||||
interpolation matches the CPPN, then psi-continuity buys nothing either, and the RP has no
|
|
||||||
distinguishing claim left against a GNN."* It is recorded here as it was predicted.
|
|
||||||
|
|
||||||
## Setup
|
|
||||||
|
|
||||||
Teacher kernel changes **shape** with psi, not gain: valence rotates the spatial frequency,
|
|
||||||
arousal widens the envelope. A psi that only scaled the kernel would be satisfiable by any model
|
|
||||||
with a gain on its output — the failure mode `chess_reach.md` measured for piece type — and is
|
|
||||||
guarded by `test_teacher_kernel_changes_shape_with_psi_not_only_gain`, which was checked against
|
|
||||||
a teacher deliberately reduced to a gain.
|
|
||||||
|
|
||||||
Withheld: the box psi ∈ [0, 0.5]², aligned to the bin grid. `omega=2`, the measured optimum from
|
|
||||||
`omega.md`. 6 seeds. Arms share `RelationalPerceptron`'s forward with the kernel swapped.
|
|
||||||
|
|
||||||
## Results
|
|
||||||
|
|
||||||
```
|
|
||||||
arm steps seen unseen u/s vs rp kernel params
|
|
||||||
rp 2500 0.00032 0.00038 1.18 1.00x 720
|
|
||||||
table_1 2500 0.00091 0.00081 0.89 2.11x 3600
|
|
||||||
table_2 2500 0.00042 0.00070 1.64 1.81x 14400
|
|
||||||
table_4 2500 0.00022 0.00733 32.87 19.12x 57600
|
|
||||||
table_4_interp 2500 0.00022 0.00034 1.54 0.90x 57600
|
|
||||||
table_8 2500 0.00025 0.00746 29.52 19.47x 230400
|
|
||||||
table_8 10000 0.00009 0.00691 80.75 18.04x 230400
|
|
||||||
table_8_interp 2500 0.00025 0.00033 1.32 0.87x 230400
|
|
||||||
floor 0.00656
|
|
||||||
|
|
||||||
table_4_interp - rp: -0.00004 +/- 0.00002 table better on 6/6 seeds
|
|
||||||
table_8_interp - rp: -0.00005 +/- 0.00003 table better on 5/6 seeds
|
|
||||||
```
|
|
||||||
|
|
||||||
## What this establishes
|
|
||||||
|
|
||||||
**1. The CPPN does answer for psi it never saw.** 0.00038 against 0.00032 on trained psi — a
|
|
||||||
1.18x cost, at 6% of the floor, from 720 parameters. The property is real.
|
|
||||||
|
|
||||||
**2. And a binned table with the gaps filled does it at least as well.** `table_4_interp` reads
|
|
||||||
0.00034 and beats the CPPN on 6 seeds of 6. The margin is small in absolute terms and outside
|
|
||||||
one paired se, so it is readable, but the direction is what matters: **there is no accuracy
|
|
||||||
advantage to generating the kernel from a continuous psi.**
|
|
||||||
|
|
||||||
**3. The bare tables' failure is arithmetic, and was labelled so before the run.** `table_4` and
|
|
||||||
`table_8` read ~19x the CPPN on withheld psi because the bin covering the box never received
|
|
||||||
gradient and sat at its initialisation. Reporting that as evidence would have been the same
|
|
||||||
tautology `unseen.md` avoided, and it is the reason the interpolation arms exist.
|
|
||||||
|
|
||||||
**4. It is not a sample-budget artefact.** `table_8` at 4x the steps fits trained psi three times
|
|
||||||
better (0.00025 → 0.00009) and generalises **not at all** better (0.00746 → 0.00691, floor
|
|
||||||
0.00656). More training buys memorisation and nothing else. Under-training a baseline is the
|
|
||||||
mirror image of tuning one until it catches up, and this rules it out.
|
|
||||||
|
|
||||||
**5. Resolution in psi and generalisation over psi are opposed in a table.** The arms that
|
|
||||||
generalise without help (`table_1`, `table_2`) do so by being blind to psi or by having half
|
|
||||||
their bin trained; the arms that can actually resolve psi are the ones that fail. Only the
|
|
||||||
explicit fill breaks the trade-off. The CPPN has no such trade-off, which is a structural
|
|
||||||
difference — it just is not an accuracy one.
|
|
||||||
|
|
||||||
## What is left of the claim
|
|
||||||
|
|
||||||
Parameters. 720 against 57,600 and 230,400 — 80x and 320x — at equal accuracy. That is a real
|
|
||||||
engineering property and it is now quantified rather than asserted, and its shape matters more
|
|
||||||
than its size here: **the table's cost is B^(number of continuous axes) × cells × channels, and
|
|
||||||
the CPPN's is constant.** At two psi axes and B=8 that is already 320x. At four it would be
|
|
||||||
4096 bins. The compression advantage grows exponentially in the number of continuous inputs and
|
|
||||||
the CPPN's does not grow at all.
|
|
||||||
|
|
||||||
That is the honest form of what the RP buys, and it is smaller than "a capability a lookup does
|
|
||||||
not have". Nothing measured in this project distinguishes the RP from a lookup **in what it can
|
|
||||||
represent**. What distinguishes it is what that representation costs.
|
|
||||||
|
|
||||||
## What this does not establish
|
|
||||||
|
|
||||||
Two continuous axes, one teacher family, a smooth dependence on psi by construction (a rotation
|
|
||||||
and an envelope width, both continuous and monotone). A psi dependence that was *not* smooth —
|
|
||||||
discontinuous, or high frequency in psi — is the case where interpolation between bins should
|
|
||||||
fail and the CPPN should not, and it has not been run. That is the sharpest remaining version of
|
|
||||||
this question and it is the natural sibling of the deferred capacity sweep, which asks the same
|
|
||||||
thing along the offset axis.
|
|
||||||
|
|
||||||
The interpolation control also needs to know which bins are untrained. That is realistic — a
|
|
||||||
system knows which regions it has seen — but it is an extra piece of machinery the CPPN does not
|
|
||||||
require, and at higher axis counts building it is the exponential above.
|
|
||||||
|
|
||||||
## Reproduce
|
|
||||||
|
|
||||||
```
|
|
||||||
uv run python psi.py --arms rp,table_1,table_2,table_4,table_8 --omega 2 --steps 2500 --seeds 0,1,2,3,4,5 --out results/psi.json
|
|
||||||
uv run python psi.py --arms table_8 --omega 2 --steps 10000 --seeds 0,1,2,3,4,5 --out results/psi_table8_long.json
|
|
||||||
uv run python psi.py --arms table_4_interp,table_8_interp --omega 2 --steps 2500 --seeds 0,1,2,3,4,5 --out results/psi_interp.json
|
|
||||||
```
|
|
||||||
|
|
||||||
Tests: `tests/test_psi.py`. Both silent-failure risks are defended and both defences were checked
|
|
||||||
against deliberately broken versions: a teacher reduced to a psi-gain fails the shape test, and
|
|
||||||
the bin bookkeeping (`untrained_bins`) is asserted exactly rather than approximately, because an
|
|
||||||
interp arm quietly filling bins that had data would look like a result.
|
|
||||||
@@ -1,195 +0,0 @@
|
|||||||
# What the RP is: a property card
|
|
||||||
|
|
||||||
Every experiment so far has moved a limit to see whether something worked. This file asks the
|
|
||||||
prior question: **what does the RP do that a fixed-weight perceptron does not, and what is that
|
|
||||||
good for?** It is a map, not a result. Each row is a property with its evidence, and the point
|
|
||||||
of the exercise is that three of the five rows need no experiment at all — they are properties
|
|
||||||
of the construction, and writing them down is what shows which two rows are actually open.
|
|
||||||
|
|
||||||
## How the perceptron comparison is read here
|
|
||||||
|
|
||||||
`AGENTS.md` forbids a standard MLP or perceptron baseline. That prohibition is on the **error
|
|
||||||
race** — tuning two architectures until one lands lower — and it stands. This file makes a
|
|
||||||
different comparison: what class of function each one can express. In the regime that matters
|
|
||||||
the baseline **cannot be run at all**, and that is the finding rather than an obstacle to it.
|
|
||||||
Where it can be run (fixed N, fixed entity ordering) is exactly where the distinction it would
|
|
||||||
measure has already been assumed away. No MLP is trained anywhere in this file.
|
|
||||||
|
|
||||||
## The card
|
|
||||||
|
|
||||||
| # | Property | Status | Evidence |
|
|
||||||
|---|----------|--------|----------|
|
|
||||||
| 1 | **One parameter set, any N** | **Measured. Holds — and a GNN has it too** | `scale.md`, `test_rp_same_parameters_any_n` |
|
|
||||||
| 2 | **Permutation equivariance** | **Asserted, sabotage-verified** | `test_rp_permutation_equivariance`, `test_organism_permutation_equivariance_with_memory` |
|
|
||||||
| 3 | **Weights generated from the relation** | **Measured. Real, and smaller than assumed** | `unseen.md` |
|
|
||||||
| 4 | **Translation invariance** | **Asserted, and its cost measured** | `test_rp_translation_invariance`; `chess_rules.md` |
|
|
||||||
| 5 | **Kernel conditioned by identity** | **Measured, discontinuous** | `chess_reach.md`, `chess_rules.md` |
|
|
||||||
|
|
||||||
### 1. One parameter set, any N
|
|
||||||
|
|
||||||
The CPPN generates `m_ij` from `[r_ij ‖ onehot(e_ij) ‖ context]`, so the parameter count depends
|
|
||||||
on the coordinate, edge-type and hidden dimensions and **not** on how many entities there are.
|
|
||||||
The same ~9k parameters ran boards of 2 and of 32 pieces across the whole chess arc.
|
|
||||||
|
|
||||||
A fixed-weight layer over N entities is not worse at this; it is **undefined**. Its input
|
|
||||||
dimension is N·d (or N²·d for pairs) and has to be chosen before training. Changing N is a
|
|
||||||
different model, not a different input. That is the cleanest statement of what the RP buys, and
|
|
||||||
it is structural — no run establishes it and no run can refute it.
|
|
||||||
|
|
||||||
What the wording invites confusion with is a separate claim: that the RP still **works** at an N
|
|
||||||
it never trained on. Measured in `scale.md`, and it holds strongly — a model trained on N ≤ 16
|
|
||||||
scores 0.84 of the oracle's error at N=32, i.e. *better* than the model that trained there.
|
|
||||||
|
|
||||||
Two qualifications, both from that file. **A lookup table does the same** (0.86-0.90): neither
|
|
||||||
has a parameter tied to entity count, so this separates the RP from a perceptron and from
|
|
||||||
nothing else. And the cost that does exist runs the other way — training on N ∈ [17,32] and
|
|
||||||
evaluating at N=2 costs 2.28x, because mean pooling dilutes each pair's contribution by 1/deg
|
|
||||||
and the kernel is learned less sharply at large N. **The RP's pooling is a low-pass filter on
|
|
||||||
the learning signal, strength 1/N**; the cheap curriculum is to train small and deploy large.
|
|
||||||
|
|
||||||
### 2. Permutation equivariance
|
|
||||||
|
|
||||||
`h_i` does not depend on the order the entities are listed in. An MLP over a flattened board has
|
|
||||||
to learn this from data, and learns it approximately at best.
|
|
||||||
|
|
||||||
Asserted at two levels because there are two places order could leak: the RP's positional
|
|
||||||
tensors, and the `Organism`'s memory dict keyed by entity id. Per the repo's rule, both were run
|
|
||||||
against a deliberately broken RP (an index-dependent term added to the pooled message) and both
|
|
||||||
failed there; no other test in the suite did.
|
|
||||||
|
|
||||||
### 3. Weights generated from the relation — measured, and it does not carry what it was asked to
|
|
||||||
|
|
||||||
This is the property that separates the RP from a **GNN**, not merely from a perceptron, and it
|
|
||||||
is the only one on this card with no evidence at all.
|
|
||||||
|
|
||||||
A GNN holds fixed weights per edge type: a lookup with one entry per discrete relation. The
|
|
||||||
CPPN computes weights from continuous geometry, so it has an answer for a relation **it has
|
|
||||||
never seen** — an offset absent from training — where a lookup has no entry to read.
|
|
||||||
|
|
||||||
Measured in `unseen.md`, and the answer is three-sided.
|
|
||||||
|
|
||||||
The property is **real**: on a random hold-out the CPPN's error on displacements it never saw is
|
|
||||||
indistinguishable from its error on trained ones (1.28x, lower on 3 of 8 seeds), at 0.6% of the
|
|
||||||
floor. The kernel is defined between its training points.
|
|
||||||
|
|
||||||
It is **worth less than the framing assumed**. The bare table fails by construction — its held
|
|
||||||
entries never see gradient — so beating it is arithmetic. Against a table plus iterated
|
|
||||||
neighbour averaging, the obvious smoothing, the CPPN wins interpolation by 2x on 6/8 seeds and
|
|
||||||
**loses extrapolation on 8/8**. Smoothness is what answers for an unseen relation, and a table
|
|
||||||
can be smoothed.
|
|
||||||
|
|
||||||
And it is **absent at the bandwidth every chess run used**. At `omega=10` the held-out error is
|
|
||||||
17x worse than at `omega=1` (8/8 seeds), below the smoothed table even on interpolation. The
|
|
||||||
setting that makes the property visible was chosen for this file without measuring it.
|
|
||||||
|
|
||||||
Where it could still be load-bearing is a **continuous** relation space, where no table exists
|
|
||||||
to smooth. Chess is not that: 225 integer offsets are enumerable. Particles are. Not run.
|
|
||||||
|
|
||||||
### 4. Translation invariance, and what it costs
|
|
||||||
|
|
||||||
The kernel sees only `r_ij`, so the representation is translation-invariant by construction
|
|
||||||
rather than by training. The symmetry is free and exact.
|
|
||||||
|
|
||||||
The same sentence is a **limit**, and this is the one row where the card is not flattering.
|
|
||||||
Absolute position is unanswerable by construction, and a chess board has edges: a knight on the
|
|
||||||
rim has 2.96 destinations against 6.85 in the middle, and 43% of knights sit on the rim. Handing
|
|
||||||
absolute position and `own_rank` in through `attrs` was worth +0.020 and closed the gap to the
|
|
||||||
rule-knowing control from 0.034 to 0.014 (`chess_rules.md`). A domain whose law is anchored to
|
|
||||||
absolute location has to be told, and the telling goes through the features, not the kernel.
|
|
||||||
|
|
||||||
### 5. The kernel must be conditioned by identity, not scaled by it
|
|
||||||
|
|
||||||
The measured row, and it is a statement about relational architectures rather than about chess.
|
|
||||||
With the piece type only in `attrs`, it meets the kernel as an elementwise product: one geometry
|
|
||||||
function scaled per type. Put it into the CPPN's own input (`e_ij`) and the kernel becomes
|
|
||||||
genuinely type-conditional.
|
|
||||||
|
|
||||||
```
|
|
||||||
knight precision@k, per seed (chess_reach.md)
|
|
||||||
rp 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 8961 params
|
|
||||||
rp_type 0.742 0.755 0.749 0.768 0.750 0.768 0.766 0.763 9121 params
|
|
||||||
```
|
|
||||||
|
|
||||||
Exactly zero on 8/8 seeds, to 0.758, for 160 extra parameters — 1.8%. Not capacity. A knight's L
|
|
||||||
is not a scaling of the average movement shape, and one shared geometry function cannot be both.
|
|
||||||
The rook (second least average-like pattern) shows the second largest gain, 0.19 → 0.58.
|
|
||||||
|
|
||||||
Refinement, from `chess_rules.md`: the conditioning must cover whatever the law actually varies
|
|
||||||
over. Type alone put a white and a black pawn on one kernel with mirrored moves and cost 0.13 on
|
|
||||||
pawns; type × colour (12 kernels) recovered it, pawn 0.7835 → 0.8689, aggregate 0.8353 against
|
|
||||||
the rule-knowing control's 0.8305, 4 seeds.
|
|
||||||
|
|
||||||
## What this says about uses
|
|
||||||
|
|
||||||
The RP earns its cost where at least one of these is load-bearing:
|
|
||||||
|
|
||||||
- **The entity count varies, or is unknown at training time** (row 1). Not "handles it better" — the alternative is not defined.
|
|
||||||
- **Entity order carries no meaning** (row 2).
|
|
||||||
- **The relation space is continuous, or too large to enumerate** (row 3). Narrowed by measurement: where relations are few and discrete, a lookup plus smoothing is a serious competitor. This is the one reason to prefer the RP over a plain GNN, and it is bounded.
|
|
||||||
- **The law varies by identity** (row 5) — and then identity must enter the kernel, not the features.
|
|
||||||
|
|
||||||
And it is the wrong tool where the law is anchored to absolute position (row 4), which has to be
|
|
||||||
patched in through attributes.
|
|
||||||
|
|
||||||
## Where the argument stands
|
|
||||||
|
|
||||||
Rows 1 and 2 are **shared with any GNN** — measured, not assumed (`scale.md`). Row 5, identity in
|
|
||||||
the kernel, is the same statement as indexing a lookup by type as well as by offset.
|
|
||||||
|
|
||||||
Row 3 went through a full reversal and the reversal is the interesting part. Measured against
|
|
||||||
hold-outs that withheld cells uniformly (`unseen.md`) or a psi box with trained bins on all four
|
|
||||||
sides (`psi.md`), a lookup plus a neighbour average matched the CPPN and the conclusion was that
|
|
||||||
nothing distinguishes the RP in what it can *represent*. `sharp.md` withheld cells the kernel
|
|
||||||
actually **uses**, and the CPPN wins 4.4x on a smooth teacher and 3.0x on a high-frequency one,
|
|
||||||
6 seeds out of 6 in both; on a corner psi box it goes from losing to winning 5/6. One sentence
|
|
||||||
covers every hold-out tried: **a blur wins where the kernel is near zero, the CPPN wins where the
|
|
||||||
kernel carries signal.**
|
|
||||||
|
|
||||||
So the RP does have a representational advantage over a lookup, it is not large, and it lives
|
|
||||||
exactly where interpolation is hard — high-frequency content, and withheld regions that carry
|
|
||||||
signal or sit at a boundary. On top of that sits the cost argument, which is unaffected: the
|
|
||||||
table scales as B^(continuous axes) × cells × channels and the CPPN is constant, 80-320× at two
|
|
||||||
continuous axes.
|
|
||||||
|
|
||||||
**And the null that looked like a verdict was an input.** `sharp.md` found that shown six of a
|
|
||||||
knight's eight L-squares nothing infers the other two. `invariance.md` gives the CPPN D4
|
|
||||||
invariants of the displacement instead of the raw vector — the eight squares become one input —
|
|
||||||
and the same architecture recovers them exactly: 0.02395 → 0.00009, 0.4% of the floor, 6/6 seeds,
|
|
||||||
and 48× better on the training cells too. Two controls make it mean something: where the eight
|
|
||||||
squares share a support but not a rule the invariance is *worse* than nothing, and on a domain
|
|
||||||
without that symmetry it costs 31×. **An invariance is a commitment, not a free lunch.**
|
|
||||||
|
|
||||||
That is the fifth time in this project that a null turned out to be what was expressible in the
|
|
||||||
input rather than what the mechanism could do. It also bounds `chess_reach.md` differently than
|
|
||||||
`sharp.md` did: the type-conditioned kernel represents a knight's L, and a D4-conditioned one
|
|
||||||
would generalise it — a prediction for the parked chess arc, not a result.
|
|
||||||
|
|
||||||
**The model is GIVEN the group, and `discovery.md` measured that it cannot find one.** A learned
|
|
||||||
frame — K linear maps on the displacement, averaged — leaves the 266x band between floor and
|
|
||||||
oracle essentially untravelled, and **training to convergence makes it worse**: `seen` improves
|
|
||||||
5x while `unseen` doubles and the invariance metric moves away from zero. At K=8 the invariant
|
|
||||||
solution exists in the parameter space, so this is neither capacity nor optimiser strength.
|
|
||||||
|
|
||||||
The reason is the objective. The loss scores fit on cells the model was shown; invariance only
|
|
||||||
pays on cells it was not, and those are by construction absent from the loss. An unconstrained
|
|
||||||
kernel fits the shown cells better than one tied to an orbit, so gradient descent walks away from
|
|
||||||
the answer, correctly by its own lights. **The five earlier nulls were about what the input could
|
|
||||||
express. This one is about what the objective could reward.**
|
|
||||||
|
|
||||||
One thing the learned frame does buy: on a domain without the symmetry it costs nothing, where
|
|
||||||
the hardcoded invariance costs 31x. Discovering beats committing — it just does no discovering.
|
|
||||||
|
|
||||||
## What is open, in order
|
|
||||||
|
|
||||||
1. **An objective that can reward invariance at all.** `discovery.md` located the obstacle
|
|
||||||
precisely: a loss over shown relations has no term that invariance improves, whatever the
|
|
||||||
parameterisation. Gradient descent is not the thing to fix. The candidates are objectives, not
|
|
||||||
architectures — selection on held-out relations (which is what evolutionary search does by
|
|
||||||
construction, and is where this project already said it goes next), or a family of domains
|
|
||||||
sharing a group so that transfer is in the loss.
|
|
||||||
2. **Kernel capacity and interference.** How many distinct kernels fit before they collide, and
|
|
||||||
which pairs collide first. The pawn/colour result is one measured point of this curve; the
|
|
||||||
sweep makes similarity an independent variable instead of an accident of chess. Deliberately
|
|
||||||
last: how far a mechanism stretches is only worth measuring once it is known what it is for.
|
|
||||||
|
|
||||||
Nothing here touches the GRP line, which stays parked at `chess_dist.md` per `AGENTS.md`.
|
|
||||||
@@ -1,86 +0,0 @@
|
|||||||
# One parameter set, an entity count it never trained on
|
|
||||||
|
|
||||||
Row 1 of `rp_properties.md`, second half. That the RP is *defined* at any N is structural and
|
|
||||||
asserted in the library's tests — a fixed-weight layer is not worse there, it has no input
|
|
||||||
dimension to use. Whether it still **works** at an N it never saw is a different claim, and
|
|
||||||
defined is not competent.
|
|
||||||
|
|
||||||
Two things come out, and the second is the more useful one.
|
|
||||||
|
|
||||||
## Read against an oracle, never down the N axis
|
|
||||||
|
|
||||||
`y_i` is a mean over neighbours, so raising N averages more terms, the target's variance falls,
|
|
||||||
and any error-over-floor ratio climbs with N for a model doing nothing wrong. This was found in
|
|
||||||
the smoke run and is asserted in `tests/test_scale.py::test_floor_shrinks_as_n_grows` rather
|
|
||||||
than left in prose.
|
|
||||||
|
|
||||||
What makes the axis comparable is an oracle: a model trained over the full range [2,32] and
|
|
||||||
evaluated at the same N. Three runs, `omega=2` (the measured optimum from `omega.md`, not the
|
|
||||||
value picked by hand for `unseen.md`), 8 seeds, both arms:
|
|
||||||
|
|
||||||
- `forward` trained on N ∈ [2,16] — large N unseen
|
|
||||||
- `reverse` trained on N ∈ [17,32] — small N unseen
|
|
||||||
- `oracle` trained on N ∈ [2,32]
|
|
||||||
|
|
||||||
The reverse direction is a control, not symmetry: mean pooling means degree rises with N, so a
|
|
||||||
cost at large N could be the pooled statistics shifting rather than a failure to generalise over
|
|
||||||
entity count. A cost in **both** directions would be the degree distribution; a cost in **one**
|
|
||||||
is the extrapolation actually asked for.
|
|
||||||
|
|
||||||
## Result: generalising over N is free, and the table does it too
|
|
||||||
|
|
||||||
Ratio to the oracle at the same N. Below 1 means *better* than the model that trained there.
|
|
||||||
|
|
||||||
```
|
|
||||||
N 2 4 8 12 16 20 24 28 32
|
|
||||||
rp fwd/orc 0.75 0.71 0.76 0.80 0.78 0.80 0.80 0.82 0.84
|
|
||||||
rp rev/orc 2.28 1.26 0.91 0.87 0.84 0.83 0.82 0.84 0.84
|
|
||||||
table fwd/orc 0.86 0.76 0.84 0.86 0.86 0.86 0.86 0.91 0.90
|
|
||||||
table rev/orc 1.82 1.27 1.10 1.06 1.04 0.97 0.98 1.03 1.00
|
|
||||||
| unseen for forward ->
|
|
||||||
<- unseen for reverse |
|
|
||||||
```
|
|
||||||
|
|
||||||
**The property holds, strongly.** A model that never saw more than 16 entities is not merely
|
|
||||||
competent at 32: at 0.84 it beats the oracle that trained there.
|
|
||||||
|
|
||||||
**And it does not distinguish the RP from a GNN.** The lookup table shows the same pattern
|
|
||||||
(0.86-0.90 forward). Neither has a parameter tied to the entity count, so neither needs to. Row
|
|
||||||
1 separates the RP from a *perceptron*, for which variable N is undefined, and from nothing
|
|
||||||
else. The property card already said this; it is now measured rather than argued.
|
|
||||||
|
|
||||||
## The asymmetry is the finding
|
|
||||||
|
|
||||||
The cost appears in **one** direction only — large→small, 2.28x at N=2 and 1.26x at N=4, gone by
|
|
||||||
N=8. Small→large is free and better than free.
|
|
||||||
|
|
||||||
The mechanism is the pooling. `h_i = tanh(mean_j m_ij ⊙ W p_j + b)`, so a single pair's
|
|
||||||
contribution to the target is diluted by 1/deg. Training at N=32 dilutes every kernel value by
|
|
||||||
~1/32 before the gradient sees it, and the kernel is learned less sharply; that imprecision is
|
|
||||||
invisible at large N, where averaging hides it, and shows up immediately at N=2, where it does
|
|
||||||
not. **The RP's mean pooling is a low-pass filter on the learning signal, with strength 1/N.**
|
|
||||||
|
|
||||||
That is actionable and it is the opposite of the intuition that more entities means more signal:
|
|
||||||
the cheap curriculum is to train on few entities and deploy on many. It is also a statement
|
|
||||||
about relational architectures rather than about this domain, which is the kind this project is
|
|
||||||
for. The table arm showing the same asymmetry (1.82x at N=2) confirms it is the pooling and not
|
|
||||||
the kernel.
|
|
||||||
|
|
||||||
## What this does not establish
|
|
||||||
|
|
||||||
One domain, one teacher family, N from 2 to 32 on an 8x8 lattice, so density rises with N and is
|
|
||||||
confounded with count — at N=32 half the squares are occupied and the displacement distribution
|
|
||||||
is not the same as at N=2. Separating count from density needs a board that grows with N, and
|
|
||||||
that was not run. The 2.28x at N=2 is the point where that confound is largest.
|
|
||||||
|
|
||||||
## Reproduce
|
|
||||||
|
|
||||||
```
|
|
||||||
uv run python scale.py --train 2,16 --omega 2 --steps 2000 --seeds 0,1,2,3,4,5,6,7 --out results/scale_forward.json
|
|
||||||
uv run python scale.py --train 17,32 --omega 2 --steps 2000 --seeds 0,1,2,3,4,5,6,7 --out results/scale_reverse.json
|
|
||||||
uv run python scale.py --train 2,32 --omega 2 --steps 2000 --seeds 0,1,2,3,4,5,6,7 --out results/scale_oracle.json
|
|
||||||
uv run python analyse_scale.py
|
|
||||||
```
|
|
||||||
|
|
||||||
Tests: `tests/test_scale.py`. The training range is the experiment and a leak would be silent;
|
|
||||||
the range check was run against a deliberately widened sampler and failed there.
|
|
||||||
@@ -1,113 +0,0 @@
|
|||||||
# Where a blur competes and where it does not — and one prediction that failed
|
|
||||||
|
|
||||||
Every null in `unseen.md`, `scale.md` and `psi.md` was measured against a **smooth** teacher, and
|
|
||||||
smoothness is exactly what lets a lookup plus a neighbour average compete. Those files concluded
|
|
||||||
that nothing distinguishes the RP from a lookup in what it can represent. This one varies the
|
|
||||||
smoothness and the hold-out structure, and **that conclusion does not survive**: it was an
|
|
||||||
artefact of hold-outs that made interpolation easy.
|
|
||||||
|
|
||||||
It also contains a prediction of mine that was falsified, which is the more useful half.
|
|
||||||
|
|
||||||
## Four teacher families, one axis: how predictable the kernel is from its neighbours
|
|
||||||
|
|
||||||
- `smooth` — band-limited Gabor. The replication.
|
|
||||||
- `highfreq` — the same at a frequency near the grid's resolution. Structured, not smooth.
|
|
||||||
- `knight` — 1 on the eight L-offsets, 0 elsewhere. Not smooth, and **rule-generated**. This is
|
|
||||||
`chess_reach.md`'s knight asked as a mechanism question.
|
|
||||||
- `noise` — iid per cell. **The negative control.** Without it, "the CPPN wins on non-smooth
|
|
||||||
kernels" cannot be told apart from "the setup favours the CPPN". Asserted to have neighbour
|
|
||||||
correlation < 0.2 where the smooth teacher's is > 0.8.
|
|
||||||
|
|
||||||
The hold-out also changed, and the change was forced by the knight teacher: most of its 225 cells
|
|
||||||
are exactly zero, so a uniform hold-out withholds cells carrying no signal, the target's variance
|
|
||||||
there is ~0 and the floor collapses. **`--holdout support` withholds cells the kernel actually
|
|
||||||
uses.** For the knight that is: *having seen six of the eight L-squares, can it infer the other
|
|
||||||
two?* The set is closed under negation, since a pair contributes r and −r.
|
|
||||||
|
|
||||||
## Result, 6 seeds
|
|
||||||
|
|
||||||
```
|
|
||||||
teacher omega arm seen unseen floor verdict
|
|
||||||
smooth 2 rp 0.00007 0.00007 0.01533
|
|
||||||
smooth 2 table 0.00005 0.00563 0.01533 +0.00556 +/- 0.00079 6/6 rp
|
|
||||||
smooth 2 table_interp 0.00005 0.00031 0.01533 +0.00024 +/- 0.00007 6/6 rp
|
|
||||||
highfreq 8 rp 0.00057 0.00126 0.01512
|
|
||||||
highfreq 8 table_interp 0.00015 0.00376 0.01512 +0.00251 +/- 0.00050 6/6 rp
|
|
||||||
knight 2 rp 0.00117 0.02359 0.02228 both AT OR ABOVE the floor
|
|
||||||
knight 2 table_interp 0.00002 0.02248 0.02228 -0.00112 +/- 0.00051 0/6 rp
|
|
||||||
noise 2 rp 0.00087 0.00157 0.00221 control: nothing generalises
|
|
||||||
noise 2 table_interp 0.00007 0.00150 0.00221 -0.00007 +/- 0.00007 2/6 rp
|
|
||||||
```
|
|
||||||
|
|
||||||
And psi re-checked with a corner box instead of an interior one, because if the hold-out
|
|
||||||
structure flipped the answer on the offset axis it could not be left untested on this one:
|
|
||||||
|
|
||||||
```
|
|
||||||
psi hold-out arm seen unseen floor params verdict
|
|
||||||
interior [0,0.5]^2 rp 0.00032 0.00038 0.00656 720
|
|
||||||
interior table_4_interp 0.00022 0.00034 0.00656 57600 table better
|
|
||||||
CORNER [0.5,1.0]^2 rp 0.00032 0.00073 0.00729 720
|
|
||||||
CORNER table_4_interp 0.00023 0.00086 0.00729 57600 +0.00013 5/6 rp
|
|
||||||
CORNER table_8_interp 0.00024 0.00069 0.00729 230400 -0.00004 ambiguous
|
|
||||||
```
|
|
||||||
|
|
||||||
## What this changes
|
|
||||||
|
|
||||||
**1. The CPPN does have a representational advantage, and it appears exactly where interpolation
|
|
||||||
is hard.** On the support hold-out it beats a lookup-plus-blur 4.4x on smooth and 3.0x on
|
|
||||||
high-frequency kernels, 6 seeds out of 6 in both. On the corner psi box it goes from losing to
|
|
||||||
winning 5/6 against the same-resolution table and tying the one with 320x its parameters.
|
|
||||||
|
|
||||||
**2. The earlier conclusion was an artefact of easy hold-outs, and this retro-explains the band
|
|
||||||
result rather than contradicting it.** `unseen.md`'s random hold-out withheld cells uniformly,
|
|
||||||
most of them peripheral, where the Gabor envelope has decayed and predicting ~0 is nearly
|
|
||||||
correct; its band hold-out was measured to have a kernel 4x weaker inside it and the RP lost
|
|
||||||
there 0/8. One sentence covers all three: **a blur wins where the kernel is near zero, the CPPN
|
|
||||||
wins where the kernel carries signal.** `unseen.md` and `psi.md` are not withdrawn — they are
|
|
||||||
correct for what they withheld — but their headline reading is superseded by this file.
|
|
||||||
|
|
||||||
**3. My prediction about the knight was wrong, and nothing generalises there.** I predicted the
|
|
||||||
CPPN would win on a rule-generated sparse kernel because a neighbour average cannot recover an
|
|
||||||
isolated spike. The average indeed cannot — and neither can the CPPN. Both sit at or above the
|
|
||||||
floor (1.06 and 1.01 of it). Having seen six of the eight L-squares, **the symmetry group is not
|
|
||||||
inferred by anything here.**
|
|
||||||
|
|
||||||
That has a direct consequence for a result of ours. `chess_reach.md` measured the knight going
|
|
||||||
from exactly 0.000 to 0.758 when the piece type entered the kernel, on 8/8 seeds for 1.8% more
|
|
||||||
parameters. That result stands as what it is — the kernel can **represent** eight cells once it
|
|
||||||
is conditioned by identity. What it does not support is the reading that the organism learned
|
|
||||||
*how a knight moves*. Shown six of the eight squares it does not find the other two. It
|
|
||||||
memorised a shape it was shown in full; it did not acquire a rule.
|
|
||||||
|
|
||||||
**4. The negative control behaves.** On `noise` both arms sit at ~0.7 of the floor — the part of
|
|
||||||
the target recoverable without the withheld relation at all, through the self-message and the
|
|
||||||
readout — and neither beats the other outside noise. The setup can produce a null.
|
|
||||||
|
|
||||||
## What this does not establish
|
|
||||||
|
|
||||||
The support and random hold-outs differ in more than their principle: `support` withholds ~25% of
|
|
||||||
the cells the kernel uses (2 of 8 for the knight, a few dozen for the smooth teacher) while
|
|
||||||
`random` withheld 56 of 225 regardless of magnitude. The comparison between this file's smooth
|
|
||||||
row and `unseen.md`'s is therefore indicative, not paired. What is paired, and unanimous, is
|
|
||||||
`rp` against `table_interp` **within** each row here.
|
|
||||||
|
|
||||||
`omega` was fixed at 2 except for the high-frequency family, where 8 is reported because a
|
|
||||||
band-limited model cannot fit a high-frequency teacher and reporting only omega=2 would have
|
|
||||||
handicapped the CPPN on the one family built to need bandwidth. Both values were run for every
|
|
||||||
family and both are in the json.
|
|
||||||
|
|
||||||
The knight null is one sparse family with one symmetry group. It says the group was not inferred
|
|
||||||
here; it does not say no relational architecture can infer one.
|
|
||||||
|
|
||||||
## Reproduce
|
|
||||||
|
|
||||||
```
|
|
||||||
for t in smooth highfreq knight noise; do
|
|
||||||
uv run python unseen.py --teacher $t --holdout support --arms rp,table,table_interp \
|
|
||||||
--omega 2 --steps 2500 --seeds 0,1,2,3,4,5 --out results/sharp_${t}_w2.json
|
|
||||||
uv run python unseen.py --teacher $t --holdout support --arms rp,table_interp \
|
|
||||||
--omega 8 --steps 2500 --seeds 0,1,2,3,4,5 --out results/sharp_${t}_w8.json
|
|
||||||
done
|
|
||||||
uv run python psi.py --arms rp,table_4,table_4_interp,table_8_interp --held 0.5,1.0 \
|
|
||||||
--omega 2 --steps 2500 --seeds 0,1,2,3,4,5 --out results/psi_corner.json
|
|
||||||
```
|
|
||||||
@@ -1,157 +0,0 @@
|
|||||||
# Can the kernel answer for a relation it never saw?
|
|
||||||
|
|
||||||
> **SUPERSEDED IN PART by `sharp.md`.** The hold-outs here withhold cells regardless of whether
|
|
||||||
> the kernel carries signal there, and the band hold-out was measured to sit where the kernel is
|
|
||||||
> 4x weaker. Under a hold-out that withholds cells the kernel actually uses, the CPPN beats
|
|
||||||
> table+interp 4.4x on 6/6 seeds. The numbers below stand; the reading "there is no accuracy
|
|
||||||
> advantage" does not.
|
|
||||||
|
|
||||||
|
|
||||||
The property that separates the RP from a **GNN** rather than from a perceptron, and the one
|
|
||||||
row of `rp_properties.md` that had no evidence at all. A GNN holds fixed weights per edge type
|
|
||||||
— a lookup with one entry per discrete relation. The CPPN computes weights from continuous
|
|
||||||
geometry, so it has something to say about a displacement absent from training, where a lookup
|
|
||||||
has no entry to read. Every chess run trained and evaluated on the same offset grid, so nothing
|
|
||||||
in this project had tested it.
|
|
||||||
|
|
||||||
**The short version: the property is real, it is worth far less than the framing assumed, and
|
|
||||||
it disappears at the bandwidth setting the whole chess arc ran at.**
|
|
||||||
|
|
||||||
## Setup
|
|
||||||
|
|
||||||
Student-teacher on a 15×15 grid of integer displacements (225 cells). The teacher is the same
|
|
||||||
RP with an analytic Gabor kernel in place of the CPPN, so the target is exactly representable
|
|
||||||
and the ceiling is 0 by construction. 2–5 entities per configuration, 2500 steps, 8 seeds.
|
|
||||||
|
|
||||||
Held-out cells are **masked out** of training — the RP's own `mask` argument — so they
|
|
||||||
contribute no message and receive no gradient. The first design rejected whole configurations
|
|
||||||
instead; it was abandoned before any run because finding a 5-entity placement whose 20 ordered
|
|
||||||
displacements all avoid a scattered 25% of cells has probability ~0.3%, which would have skewed
|
|
||||||
training towards small N silently, and that skew would have been read afterwards as a property
|
|
||||||
of the kernel.
|
|
||||||
|
|
||||||
Evaluation is always on **pairs**, both cells of the pair wholly seen or wholly held, so `seen`
|
|
||||||
and `unseen` measure the same object. The floor is a predictor that ignores the relation and
|
|
||||||
returns the mean target.
|
|
||||||
|
|
||||||
Arms, all sharing `RelationalPerceptron`'s exact forward with the kernel swapped in place:
|
|
||||||
|
|
||||||
- `rp` — the CPPN. 720 kernel parameters.
|
|
||||||
- `table` — one weight vector per discrete displacement: a GNN with one edge type per relation. 3600 kernel parameters, **5× more than the CPPN**.
|
|
||||||
- `table+interp` — the same table, with its held-out entries filled after training by iterated neighbour averaging from trained cells.
|
|
||||||
- `rp w=10` — the CPPN at `omega=10`, the project default, which every chess run used.
|
|
||||||
|
|
||||||
## Results
|
|
||||||
|
|
||||||
MSE on held-out relations. Lower is better.
|
|
||||||
|
|
||||||
```
|
|
||||||
RANDOM hold-out (interpolation), 56/225 cells
|
|
||||||
seed rp table tbl+interp rp w=10 floor
|
|
||||||
0 0.00006 0.00352 0.00029 0.00055 0.01429
|
|
||||||
1 0.00007 0.00420 0.00025 0.00260 0.01305
|
|
||||||
2 0.00008 0.00371 0.00010 0.00012 0.01029
|
|
||||||
3 0.00011 0.00400 0.00023 0.00288 0.01333
|
|
||||||
4 0.00007 0.00096 0.00003 0.00181 0.00580
|
|
||||||
5 0.00013 0.00258 0.00013 0.00129 0.01880
|
|
||||||
6 0.00009 0.00558 0.00017 0.00052 0.02043
|
|
||||||
7 0.00006 0.00252 0.00009 0.00149 0.00848
|
|
||||||
mean 0.00008 0.00338 0.00016 0.00141 0.01306
|
|
||||||
|
|
||||||
table - rp: +0.00330 +/- 0.00049 8/8 seeds
|
|
||||||
table+interp - rp: +0.00008 +/- 0.00003 6/8 seeds
|
|
||||||
omega=10 - rp: +0.00132 +/- 0.00035 8/8 seeds
|
|
||||||
rp unseen/seen mean 1.28 per seed 0.90 1.13 1.23 1.74 2.39 1.03 0.91 0.90
|
|
||||||
|
|
||||||
BAND hold-out (extrapolation), 44/225 cells
|
|
||||||
seed rp table tbl+interp rp w=10 floor
|
|
||||||
0 0.00010 0.00176 0.00008 0.00053 0.01516
|
|
||||||
1 0.00012 0.00109 0.00007 0.00071 0.01032
|
|
||||||
2 0.00008 0.00119 0.00005 0.00014 0.00803
|
|
||||||
3 0.00017 0.00117 0.00004 0.00054 0.01101
|
|
||||||
4 0.00017 0.00116 0.00006 0.00060 0.00666
|
|
||||||
5 0.00020 0.00136 0.00007 0.00086 0.01933
|
|
||||||
6 0.00016 0.00123 0.00006 0.00036 0.01589
|
|
||||||
7 0.00011 0.00133 0.00005 0.00166 0.00856
|
|
||||||
mean 0.00014 0.00129 0.00006 0.00068 0.01187
|
|
||||||
|
|
||||||
table - rp: +0.00115 +/- 0.00008 8/8 seeds
|
|
||||||
table+interp - rp: -0.00008 +/- 0.00002 0/8 seeds *** rp WORSE ***
|
|
||||||
omega=10 - rp: +0.00053 +/- 0.00016 8/8 seeds
|
|
||||||
rp unseen/seen mean 2.38 per seed 1.83 1.84 1.66 2.62 4.51 2.40 2.54 1.66
|
|
||||||
```
|
|
||||||
|
|
||||||
## What this establishes
|
|
||||||
|
|
||||||
**1. The property is real.** On the random hold-out the CPPN's error on cells it never saw is
|
|
||||||
indistinguishable from its error on cells it trained on — 1.28× on average, and on three seeds
|
|
||||||
of eight the held-out error is *lower*. It sits at 0.6% of the floor. The kernel is a function
|
|
||||||
of the relation, and the function is defined between the training points.
|
|
||||||
|
|
||||||
**2. The bare table is not the comparison, and never was.** Its held-out entries never receive
|
|
||||||
gradient and stay at initialisation, so its failure (0.00338, 42× the CPPN) is arithmetic, not
|
|
||||||
evidence. It is reported for scale and was labelled as such before the runs.
|
|
||||||
|
|
||||||
**3. Against a table plus the obvious smoothing, the advantage is small or absent.**
|
|
||||||
`table+interp` is a lookup with its gaps filled by iterated neighbour averaging — the first
|
|
||||||
thing anyone would try. On interpolation the CPPN still wins, but by 2× and on 6/8 seeds rather
|
|
||||||
than the order of magnitude the framing had assumed. On the band it **loses on 8 seeds out of
|
|
||||||
8**. Generating the kernel from geometry is not, on this evidence, what buys the answer for an
|
|
||||||
unseen relation. Smoothness does, and a table can be smoothed.
|
|
||||||
|
|
||||||
**4. It disappears at the project's own default.** `omega` sets the CPPN's bandwidth. This file
|
|
||||||
ran at `omega=1`; every chess run used `omega=10`, and at 10 the held-out error is 17× worse on
|
|
||||||
the random hold-out (0.00141 vs 0.00008, 8/8 seeds) and worse than `table+interp` even there. A
|
|
||||||
wide-band kernel fits the training cells with structure that says nothing about the gaps between
|
|
||||||
them. **The bandwidth was picked here without measuring it, and it turned out to be the only
|
|
||||||
regime in which the property is visible at all.** That is a knob the chess results were never
|
|
||||||
examined against.
|
|
||||||
|
|
||||||
## What it does not establish, stated rather than buried
|
|
||||||
|
|
||||||
**The band hold-out is confounded by target magnitude.** Mean |W*| is 0.040 inside the band
|
|
||||||
against 0.172 in the seen cells — the Gabor envelope has already decayed there, so predicting
|
|
||||||
near-zero is nearly correct and both arms have an easier target. The 0/8 loss is real but its
|
|
||||||
*magnitude* is not comparable with the random hold-out's. The random hold-out is **not**
|
|
||||||
confounded this way (0.164 held against 0.141 seen), which is why the interpolation result
|
|
||||||
carries the weight here. A clean extrapolation test needs a radius-matched hold-out or a flat
|
|
||||||
envelope, and has not been run.
|
|
||||||
|
|
||||||
**The teacher kernel is smooth and band-limited by design.** Low spatial frequencies, σ=3. The
|
|
||||||
claim earned is that the CPPN interpolates a *smooth* kernel. Whether it interpolates a sharp
|
|
||||||
one — a knight's L is eight isolated cells, which is the opposite of smooth — is untested and is
|
|
||||||
exactly what the deferred capacity sweep would ask.
|
|
||||||
|
|
||||||
**The diffusion control only exists because the relation space was enumerable.** 225 cells on an
|
|
||||||
integer lattice. This is the finding's real boundary, and it points somewhere concrete: in a
|
|
||||||
domain whose relations are few and discrete, a table plus smoothing is a serious competitor and
|
|
||||||
the generated kernel buys little. **Chess is exactly such a domain** — board offsets are
|
|
||||||
integers and there are 225 of them. The particles domain is not: displacements there are real
|
|
||||||
valued and there is no table to smooth.
|
|
||||||
|
|
||||||
## Consequence for the property card
|
|
||||||
|
|
||||||
Row 3 of `rp_properties.md` moves from *untested* to **measured, and it does not carry the
|
|
||||||
weight it was being asked to carry.** Rows 1 and 2 — one parameter set at any N, permutation
|
|
||||||
equivariance — are what distinguish the RP, and a plain GNN has both. What the CPPN adds over a
|
|
||||||
GNN is now bounded: a 2× interpolation edge at a bandwidth the project was not using, on a
|
|
||||||
relation space small enough that its competitor is a lookup and a blur.
|
|
||||||
|
|
||||||
The place the property could still be load-bearing is a **continuous** relation space, where no
|
|
||||||
table exists. That is a different experiment and it has not been run.
|
|
||||||
|
|
||||||
## Reproduce
|
|
||||||
|
|
||||||
```
|
|
||||||
uv run python unseen.py --holdout random --steps 2500 --seeds 0,1,2,3,4,5,6,7 --out results/unseen_random.json
|
|
||||||
uv run python unseen.py --holdout band --steps 2500 --seeds 0,1,2,3,4,5,6,7 --out results/unseen_band.json
|
|
||||||
uv run python unseen.py --holdout random --arms table_interp --steps 2500 --seeds 0,1,2,3,4,5,6,7 --out results/unseen_random_interp.json
|
|
||||||
uv run python unseen.py --holdout band --arms table_interp --steps 2500 --seeds 0,1,2,3,4,5,6,7 --out results/unseen_band_interp.json
|
|
||||||
uv run python unseen.py --holdout random --arms rp --omega 10 --steps 2500 --seeds 0,1,2,3,4,5,6,7 --out results/unseen_random_w10.json
|
|
||||||
uv run python unseen.py --holdout band --arms rp --omega 10 --steps 2500 --seeds 0,1,2,3,4,5,6,7 --out results/unseen_band_w10.json
|
|
||||||
uv run python analyse_unseen.py
|
|
||||||
```
|
|
||||||
|
|
||||||
Tests: `tests/test_unseen.py`. The held-out mask is the experiment, and a leak would be silent —
|
|
||||||
every arm still trains and every number still prints. Both the mask and the diffusion fill were
|
|
||||||
run against deliberately broken versions and the defending tests failed there; no others did.
|
|
||||||
@@ -1,502 +0,0 @@
|
|||||||
# When does per-entity memory have a job?
|
|
||||||
|
|
||||||
Task 9. The project had been reaching for a new domain each time memory failed to
|
|
||||||
help. This file replaces that reflex with a quantity measurable on any candidate
|
|
||||||
domain in advance — `T_id`, the history an optimal observer needs to identify the
|
|
||||||
regime — and with a prediction that can be wrong.
|
|
||||||
|
|
||||||
**Verdict, in the order the parts were pre-registered:**
|
|
||||||
|
|
||||||
1. **Part 1 — FAILURE, of the informative kind.** Arousal's peak moves from 11 steps
|
|
||||||
after a switch to **2** (lags 1 and 2 are within 0.005 of each other, 0.303 and
|
|
||||||
0.308), which is inside the pre-registered 3. The error is
|
|
||||||
unmoved: `grp_k0 / grp_k` on `steady` is 0.987 (median 1.000) and **0 of 16 seeds
|
|
||||||
reach 1.10**, against a criterion of 12 of 16. The largest ratio on any seed at any
|
|
||||||
κ is 1.017. The mechanism works, it is now correctly timed, and the domain gives it
|
|
||||||
nothing. The lag-2 harm `a1.md` §2a found survives the fix unchanged.
|
|
||||||
2. **Part 2 — `T_id = 2` observations, i.e. one step of history.** An exact decoder
|
|
||||||
reaches 0.958 per-step accuracy from a single observed displacement, against a
|
|
||||||
measured chance of 0.23, and a fitted decoder that knows no coupling matrices
|
|
||||||
reaches 0.909. Accuracy peaks at `L = 2–3` and *falls* thereafter. With
|
|
||||||
`T_z = 40–80`, **`T_id` is 20–40 times smaller than `T_z`**. That is the
|
|
||||||
uncomfortable branch: the domain can reward memory and the failure is ours.
|
|
||||||
3. **Part 3 — the predicted peak does not exist. The theory is wrong as stated.** The
|
|
||||||
capacity-controlled state gain is flat across four orders of magnitude of regime
|
|
||||||
duration, 1.09 to 1.26, on 8–11 seeds of 16 at every duration, with a per-seed
|
|
||||||
spread (0.32 to 2.86) that swamps every between-duration difference. And the
|
|
||||||
decisive point: **the largest gain in the sweep is at the frozen regime**, 1.26 on
|
|
||||||
11/16 — the one setting where there is no regime to identify at all and where `G`
|
|
||||||
measures exactly 1.00. A quantity that is largest when its supposed cause is absent
|
|
||||||
is not caused by it.
|
|
||||||
|
|
||||||
The condition "memory has a job when `T_id << T_z` and `G` is materially above 1" is
|
|
||||||
satisfied at every switching duration in this sweep and does not predict the state
|
|
||||||
gain. What the state gain measures here is temporal smoothing, which a stationary
|
|
||||||
world rewards at least as well as a switching one.
|
|
||||||
|
|
||||||
Environment: `experiments/`, `ailed/` unmodified. No default in `particles.py`,
|
|
||||||
`regime.py` or `affect.py` changed — `AffectConfig`'s time constants and
|
|
||||||
`ParticleConfig`'s `t_min`/`t_max` are passed as arguments (`when_memory_works._cfg`,
|
|
||||||
`frozen._build`). 8000 training steps, `lr=1e-3`, `bptt=20`, `hidden=32`, `omega=10`.
|
|
||||||
Noise floor `noise² = 4.0e-06`. 400 organism runs. Part 2 fits 4 decoders at each of
|
|
||||||
7 window lengths on 8 seeds, each linear decoder refit 20 times more to measure its
|
|
||||||
own chance level.
|
|
||||||
|
|
||||||
```
|
|
||||||
uv run python identify.py --out results/identify.json
|
|
||||||
uv run python identify.py --t-min 10 --t-max 20 --seeds 0,1,2,3 --steps 4000 \
|
|
||||||
--estimators phys,bayes --out results/identify_d10_20.json # and each duration
|
|
||||||
uv run python ceilings.py 1200 0,1,2 10,20 # and each duration
|
|
||||||
uv run python when_memory_works.py --part timing --out results/w_timing.json
|
|
||||||
uv run python when_memory_works.py --part rho-fast --rho-a 1.0 --rho-slow 0.2 \
|
|
||||||
--out results/w_rhofast.json
|
|
||||||
uv run python when_memory_works.py --part best --rho-a 1.0 --rho-slow 0.2 \
|
|
||||||
--out results/w_best.json
|
|
||||||
uv run python when_memory_works.py --part duration --out results/w_duration_all.json
|
|
||||||
```
|
|
||||||
|
|
||||||
## 0. What is checked, and how it was made able to fail
|
|
||||||
|
|
||||||
Four properties carry the headline numbers. Each has a test, and each test was broken
|
|
||||||
on purpose to confirm it fails — AGENTS.md's rule, applied rather than asserted.
|
|
||||||
|
|
||||||
| property | test | broken on purpose by | fails? |
|
|
||||||
|---|---|---|---|
|
|
||||||
| the decoder never sees `d_t`, the step it decodes | `test_features_never_use_the_displacement_being_decoded` | widening the window to include `d_t` | **yes** |
|
|
||||||
| the state ablation differs only in carried state | `test_state_ablation_changes_only_whether_memory_is_carried` | making `stateless` a no-op in `run_one` | **yes** |
|
|
||||||
| the arousal profile is the arousal the gate saw | `test_gate_arousal_seq_is_the_arousal_the_organism_was_handed` | companion `..._can_fail` asserts the un-lagged sequence does *not* match | **yes** |
|
|
||||||
| the message basis is the world's own | `test_basis_reproduces_the_worlds_dynamics_to_the_noise_floor` | companion `test_basis_check_can_fail` feeds it the wrong regime sequence | **yes** |
|
|
||||||
|
|
||||||
Alongside those: `test_bayes_decoder_recovers_a_regime_it_can_see_and_not_one_it_cannot`
|
|
||||||
is the planted-signal/planted-absence pair (real displacements → >0.8, displacements
|
|
||||||
replaced by noise → <0.45); `test_peak_lag_and_by_lag_average_over_the_switches_metrics_uses`
|
|
||||||
asserts `by_lag` cuts the trace exactly as `regime._metrics` cuts `recovery`, so the
|
|
||||||
arousal profile and the error profile are averaged over the same switches;
|
|
||||||
`test_windows_that_reach_the_next_switch_are_not_reported` enforces `window < t_min`
|
|
||||||
per duration, which is `regime.run`'s own validation carried into a sweep that
|
|
||||||
shortens the regime. 64 tests pass, including the 47 that were already there.
|
|
||||||
|
|
||||||
The two additive hooks this task needed — `frozen._build(t_min=, t_max=)` and
|
|
||||||
`frozen._train(acfg=)` — both default to the values the loop always used, so
|
|
||||||
`test_train_copy_is_identical_to_regime_run` still pins `_train` against `regime.run`.
|
|
||||||
|
|
||||||
## 1. Part 1 — affect timing, the last legitimate shot at A1
|
|
||||||
|
|
||||||
`rho_a` and `rho_slow` are the affect mechanism's own time constants and had never
|
|
||||||
been set. Only they can move arousal's timing. From `affect.update`:
|
|
||||||
|
|
||||||
```
|
|
||||||
fast <- fast + rho_fast (loss - fast) slow <- slow + rho_slow (loss - slow)
|
|
||||||
a_target = tanh(max(0, loss - slow) / (slow + eps))
|
|
||||||
arousal <- arousal + rho_a (a_target - arousal)
|
|
||||||
```
|
|
||||||
|
|
||||||
`fast` appears only in `v_target`. **`rho_fast` cannot reach arousal except through the
|
|
||||||
loss stream**, via valence feeding the CPPN, and §1c measures that it does not. So the
|
|
||||||
sweep is over `rho_a × rho_slow`. Where it raises `rho_slow` past the default
|
|
||||||
`rho_fast = 0.2` it raises `rho_fast` with it, because `AffectConfig` documents
|
|
||||||
`rho_slow < rho_fast` and inverting the two would change what valence means as a side
|
|
||||||
effect of a timing sweep.
|
|
||||||
|
|
||||||
### 1a. The sweep: the timing is a design parameter, and it moves
|
|
||||||
|
|
||||||
`grp_k0` (κ=0, so this is the arousal the gate *would* be forced with), 8000 steps,
|
|
||||||
seeds 0–3, means over seeds. Lag `k` after a switch, averaged over the second half's
|
|
||||||
switches — the same cut `regime._metrics` uses for `recovery`. `far` is `_metrics`'s
|
|
||||||
own `steady_idx`.
|
|
||||||
|
|
||||||
```
|
|
||||||
rho_a/rho_slow/rho_fast @0 @2 @4 @6 @8 @10 @12 @14 @16 @18 far peak
|
|
||||||
------------------------------------------------------------------------------------------------------------
|
|
||||||
a0.5/s0.02/f0.2 (default) 0.055 0.157 0.217 0.257 0.300 0.325 0.329 0.316 0.284 0.243 0.098 11
|
|
||||||
a0.5/s0.05/f0.2 0.056 0.197 0.256 0.290 0.320 0.323 0.307 0.283 0.236 0.193 0.081 10
|
|
||||||
a0.5/s0.1/f0.2 0.056 0.227 0.270 0.287 0.291 0.268 0.244 0.216 0.170 0.136 0.065 8
|
|
||||||
a0.5/s0.2/f0.4 0.054 0.219 0.228 0.221 0.198 0.170 0.149 0.121 0.088 0.077 0.053 4
|
|
||||||
a0.5/s0.4/f0.8 0.042 0.143 0.118 0.100 0.088 0.081 0.072 0.059 0.043 0.042 0.039 2
|
|
||||||
a1/s0.02/f0.2 0.046 0.205 0.259 0.284 0.327 0.348 0.342 0.316 0.277 0.232 0.092 10
|
|
||||||
a1/s0.05/f0.2 0.054 0.254 0.296 0.313 0.336 0.331 0.301 0.266 0.210 0.169 0.078 8
|
|
||||||
a1/s0.1/f0.2 0.060 0.294 0.301 0.289 0.288 0.253 0.231 0.193 0.147 0.121 0.065 1
|
|
||||||
a1/s0.2/f0.4 0.063 0.275 0.230 0.202 0.182 0.156 0.138 0.104 0.078 0.078 0.055 1
|
|
||||||
a1/s0.4/f0.8 0.046 0.174 0.105 0.086 0.083 0.080 0.066 0.052 0.038 0.041 0.040 1
|
|
||||||
```
|
|
||||||
|
|
||||||
The default row reproduces `a1.md` §1a: arousal *lowest* at the switch step and
|
|
||||||
peaking around lag 11–12. The odd lags are where the fix shows, so at one-step
|
|
||||||
resolution:
|
|
||||||
|
|
||||||
```
|
|
||||||
setting @0 @1 @2 @3 @4 @5 @6 @7 far peak/far
|
|
||||||
---------------------------------------------------------------------------------------------
|
|
||||||
a0.5/s0.02/f0.2 0.055 0.122 0.157 0.188 0.217 0.240 0.257 0.278 0.098 3.38
|
|
||||||
a1/s0.02/f0.2 0.046 0.188 0.205 0.234 0.259 0.275 0.284 0.307 0.092 3.77
|
|
||||||
a0.5/s0.2/f0.4 0.054 0.184 0.219 0.227 0.228 0.225 0.221 0.210 0.053 4.30
|
|
||||||
a1/s0.1/f0.2 0.060 0.312 0.294 0.304 0.301 0.292 0.289 0.298 0.065 4.81
|
|
||||||
a1/s0.2/f0.4 0.063 0.315 0.275 0.256 0.230 0.208 0.202 0.191 0.055 5.75
|
|
||||||
a1/s0.4/f0.8 0.046 0.243 0.174 0.131 0.105 0.088 0.086 0.084 0.040 6.06
|
|
||||||
```
|
|
||||||
|
|
||||||
**`rho_slow` is the whole story and `rho_a` sharpens it.** A slow baseline that tracks
|
|
||||||
the loss over ~50 steps cannot register a rise until the rise is most of the way done;
|
|
||||||
raising `rho_slow` to 0.1–0.4 turns `max(0, loss − slow)/slow` from a level detector
|
|
||||||
into a short-horizon relative-excess detector, and the surprise lands on the step after
|
|
||||||
the switch. `rho_a = 1` removes the remaining EMA smoothing on arousal itself.
|
|
||||||
|
|
||||||
The chosen setting was fixed on timing grounds alone, before any `grp_k` run: **among
|
|
||||||
settings whose peak lies within 3 steps of the switch, take the largest peak
|
|
||||||
amplitude.** That is `a1/s0.2/f0.4` — peak 0.315 at lag 1, a 5.0x jump from lag 0 in a
|
|
||||||
single step, and the best peak-to-far contrast of the three (5.75x). `a1/s0.1/f0.2` is
|
|
||||||
the runner-up and is reported alongside.
|
|
||||||
|
|
||||||
Worth stating because it bounds what timing can ever buy here: **the loss itself peaks
|
|
||||||
at lag 6–7** in every one of these runs (`recovery[k]` runs 2.74e-05, 2.83e-05,
|
|
||||||
3.12e-05, 3.40e-05, 3.84e-05, 4.37e-05, 4.70e-05, 4.71e-05 over lags 0–7). Arousal now
|
|
||||||
peaks five to six steps *before* the error it is built from does, because the loss at
|
|
||||||
lag 0 is already 1.3x its steady level and a short baseline sees that immediately.
|
|
||||||
There is no timing left to win.
|
|
||||||
|
|
||||||
### 1b. The result: timing fixed, error unmoved
|
|
||||||
|
|
||||||
`grp_k` against `grp_k0`, both at the best-timed affect config, 16 seeds, paired per
|
|
||||||
seed. Identical architecture, identical 5602 parameters, differing only in κ.
|
|
||||||
|
|
||||||
```
|
|
||||||
affect setting kappa mean median >1.10 >1.00 max
|
|
||||||
---------------------------------------------------------------------
|
|
||||||
a1/s0.2/f0.4 (best) 1 0.991 1.001 0/16 9/16 1.009
|
|
||||||
a1/s0.2/f0.4 4 0.987 1.000 0/16 8/16 1.017
|
|
||||||
a1/s0.2/f0.4 16 0.985 0.995 0/16 6/16 1.016
|
|
||||||
a1/s0.1/f0.2 (2nd) 1 1.011 1.000 1/16 7/16 1.107
|
|
||||||
a1/s0.1/f0.2 4 0.997 0.997 0/16 7/16 1.068
|
|
||||||
a1/s0.1/f0.2 16 0.987 0.995 0/16 6/16 1.025
|
|
||||||
```
|
|
||||||
|
|
||||||
Per-seed `grp_k0 / grp_k` at the best-timed setting, κ=4:
|
|
||||||
|
|
||||||
```
|
|
||||||
0.99 1.01 1.00 1.01 0.99 0.99 1.00 0.97 1.02 1.01 1.00 1.00 0.99 0.99 1.01 0.80
|
|
||||||
```
|
|
||||||
|
|
||||||
A coin flip with one seed (15) where the forced gate costs 20%. This is the same
|
|
||||||
picture `a1.md` §2 measured with the mis-timed signal, at the same magnitudes. Fixing
|
|
||||||
the timing changed the arousal profile completely and changed the error by nothing.
|
|
||||||
|
|
||||||
### 1c. The lag-2 harm survives the fix
|
|
||||||
|
|
||||||
`a1.md` §2a's one sign-definite effect was a 4–11% *degradation* two steps after a
|
|
||||||
switch, monotone in κ. Re-measured with arousal now peaking at lag 1 rather than 12:
|
|
||||||
|
|
||||||
```
|
|
||||||
paired grp_k0 / grp_k at matched lag, best-timed affect (<1 means kappa is worse)
|
|
||||||
kappa @0 @2 @5 @10 @19
|
|
||||||
------------------------------------------------------------------------------
|
|
||||||
1 0.98 4/16 0.96 1/16 0.99 8/16 1.00 8/16 0.99 6/16
|
|
||||||
4 0.99 6/16 0.90 0/16 0.99 6/16 0.99 6/16 0.98 5/16
|
|
||||||
16 0.99 5/16 0.91 1/16 1.00 4/16 1.00 7/16 1.00 8/16
|
|
||||||
```
|
|
||||||
|
|
||||||
At κ=4 the lag-2 penalty is 0.90 on **0 of 16 seeds** — against `a1.md`'s 0.92 on
|
|
||||||
1/16 with the mis-timed signal. Correcting the timing did not remove the harm; it made
|
|
||||||
it very slightly worse, which is what §1a's mechanism predicts. Opening the gate
|
|
||||||
earlier discards the temporal averaging earlier, and `frozen.md` §1b established that
|
|
||||||
the post-switch excess belongs to the world's configuration transient, which no gating
|
|
||||||
policy can shorten.
|
|
||||||
|
|
||||||
### 1d. The `rho_fast` control
|
|
||||||
|
|
||||||
Fixing `rho_a = 1.0`, `rho_slow = 0.2` and varying only `rho_fast`, 4 seeds:
|
|
||||||
|
|
||||||
```
|
|
||||||
rho_a/rho_slow/rho_fast @0 @2 @4 @6 @8 @10 far peak
|
|
||||||
---------------------------------------------------------------------------------
|
|
||||||
a1/s0.2/f0.4 0.063 0.275 0.230 0.202 0.182 0.156 0.055 1
|
|
||||||
a1/s0.2/f0.5 0.061 0.277 0.232 0.202 0.181 0.154 0.055 1
|
|
||||||
a1/s0.2/f0.9 0.063 0.279 0.233 0.196 0.180 0.155 0.055 1
|
|
||||||
```
|
|
||||||
|
|
||||||
Identical to within 0.005 at every lag, as the algebra requires. `rho_fast` is not a
|
|
||||||
lever on arousal timing, so the sweep over `rho_a × rho_slow` is the whole search
|
|
||||||
space and the "best-timed setting" is best over all of it.
|
|
||||||
|
|
||||||
### Verdict against the pre-registered criterion
|
|
||||||
|
|
||||||
> **SUCCESS** = arousal's peak moves to within 3 steps of the switch **and** the paired
|
|
||||||
> `grp_k0 / grp_k` steady ratio exceeds 1.10 on at least 12 of 16 seeds.
|
|
||||||
|
|
||||||
- Peak within 3 steps of the switch: **met** — lag 1, from lag 11.
|
|
||||||
- Ratio > 1.10 on ≥ 12/16 seeds: **not met** — 0/16 at the pre-declared κ=4, 0–1/16
|
|
||||||
at every κ and both settings, largest ratio anywhere 1.107.
|
|
||||||
|
|
||||||
**Part 1 is a FAILURE, and it is the failure the brief named as the informative one:
|
|
||||||
the mechanism works, is correctly timed, and the domain gives it nothing.** A1 is
|
|
||||||
closed on this domain by a stronger argument than `a1.md` had, because the one
|
|
||||||
remaining explanation — that the signal arrived too late — has now been removed and
|
|
||||||
the result did not move.
|
|
||||||
|
|
||||||
## 2. Part 2 — measuring `T_id`
|
|
||||||
|
|
||||||
Nothing in `identify.py` constructs an Organism. `T_id` is a property of the domain.
|
|
||||||
|
|
||||||
### 2a. What the observer has, and what "optimal" means here
|
|
||||||
|
|
||||||
At step `t` the observer has the coordinates `c_{t−L+1} … c_t` and therefore the
|
|
||||||
displacements `d_s = wrap(c_{s+1} − c_s)` for `s = t−L+1 … t−1`. **`d_t` is never
|
|
||||||
available** — that is what the organism is asked to predict, and handing it over would
|
|
||||||
hand over the answer. So `L = 1` is the instantaneous configuration alone and each
|
|
||||||
extra step of window buys exactly one more observed displacement.
|
|
||||||
|
|
||||||
The dynamics factor as
|
|
||||||
|
|
||||||
```
|
|
||||||
d_i(s) = sum_c K[t_i, c] · B_i^c(s) + eps, B_i^c(s) = dt · sum_{j: t_j = c} kern(r_ij) r_ij
|
|
||||||
```
|
|
||||||
|
|
||||||
`B` is the message basis — everything about the configuration the coupling multiplies
|
|
||||||
— and is computable from coordinates alone, so it is observer-side information. It is
|
|
||||||
the same decomposition `ceilings.py` fits. Self-check, the analogue of that file's row
|
|
||||||
A: the basis reproduces the world's own displacements at residual **4.0024e-06**
|
|
||||||
against `noise² = 4.0e-06`, asserted on every rollout.
|
|
||||||
|
|
||||||
Four decoders, in ascending order of what they are told:
|
|
||||||
|
|
||||||
| tag | features | estimator | knows the coupling matrices? |
|
|
||||||
|---|---|---|---|
|
|
||||||
| `lin` | raw window: `B` at each step, the observed displacements, the type one-hot | least squares | no |
|
|
||||||
| `mlp` | the same raw window | 2×128 ReLU MLP | no |
|
|
||||||
| `phys` | `<d, B^c>` and `<B^c, B^c'>` summed over the window, interacted with the type one-hot | multinomial logistic | no |
|
|
||||||
| `bayes` | the exact Gaussian likelihood over the window | closed form | **yes** |
|
|
||||||
|
|
||||||
`phys` is the fair stand-in for "optimal", and the reason is algebraic rather than
|
|
||||||
empirical: the log-likelihood of regime `g` is affine in exactly those statistics with
|
|
||||||
coefficients depending on `g` and on the entity's own type, so a linear classifier on
|
|
||||||
them **can express the exact Bayes rule**. `bayes` computes that rule directly and is
|
|
||||||
the cross-check. `lin` and `mlp` are the honest non-omniscient decoders, and the MLP is
|
|
||||||
the capacity check the brief asked for before concluding anything from a linear probe.
|
|
||||||
|
|
||||||
Chance is measured, not assumed — the two nulls `frozen.py` uses, both refitting from
|
|
||||||
scratch: a label shuffle, and a circular shift that preserves each regime's block
|
|
||||||
structure and is the stricter of the two. The shift null is quoted in brackets.
|
|
||||||
|
|
||||||
### 2b. The table
|
|
||||||
|
|
||||||
8 seeds, 4000 world steps, `t_min/t_max = 40/80`. "hist" is the steps of history
|
|
||||||
`L` observations actually provide. `sw.frac` is the fraction of windows spanning a
|
|
||||||
regime change. Per-step accuracy pools the 16 entities of a step, which is what an
|
|
||||||
observer watching the whole world does; per-entity is one classification per entity.
|
|
||||||
|
|
||||||
```
|
|
||||||
per-step accuracy (measured chance in brackets)
|
|
||||||
L hist sw.frac lin mlp phys bayes
|
|
||||||
-----------------------------------------------------------------------------------
|
|
||||||
1 0 0.000 0.229[0.224] 0.552[0.259] -- --
|
|
||||||
2 1 0.016 0.231[0.227] 0.831[0.266] 0.909[0.230] 0.958
|
|
||||||
3 2 0.033 0.231[0.232] 0.856[0.268] 0.926[0.233] 0.961
|
|
||||||
5 4 0.065 0.232[0.233] 0.874[0.250] 0.923[0.236] 0.952
|
|
||||||
10 9 0.147 0.234[0.232] 0.863[0.257] 0.888[0.237] 0.915
|
|
||||||
20 19 0.311 0.238[0.227] 0.814[0.260] 0.798[0.249] 0.842
|
|
||||||
40 39 0.640 0.237[0.227] 0.708[0.274] 0.632[0.237] 0.699
|
|
||||||
|
|
||||||
per-entity accuracy (measured chance in brackets)
|
|
||||||
L hist sw.frac lin mlp phys bayes
|
|
||||||
-----------------------------------------------------------------------------------
|
|
||||||
1 0 0.000 0.242[0.231] 0.405[0.251] -- --
|
|
||||||
2 1 0.016 0.251[0.233] 0.563[0.253] 0.566[0.230] 0.566
|
|
||||||
3 2 0.033 0.251[0.236] 0.590[0.253] 0.614[0.233] 0.629
|
|
||||||
5 4 0.065 0.251[0.238] 0.605[0.246] 0.643[0.234] 0.684
|
|
||||||
10 9 0.147 0.248[0.236] 0.598[0.251] 0.639[0.237] 0.718
|
|
||||||
20 19 0.311 0.247[0.230] 0.553[0.248] 0.581[0.239] 0.702
|
|
||||||
40 39 0.640 0.243[0.229] 0.476[0.252] 0.486[0.233] 0.601
|
|
||||||
```
|
|
||||||
|
|
||||||
Per-seed `bayes` per-step at `L=2`: `0.97 0.98 0.98 0.98 0.95 0.97 0.93 0.90`, and
|
|
||||||
`phys` `0.93 0.97 0.96 0.98 0.92 0.93 0.79 0.78`. It is not an average over a few
|
|
||||||
lucky seeds.
|
|
||||||
|
|
||||||
**`T_id = 2` observations — one step of history.** A single observed displacement takes
|
|
||||||
per-step accuracy from 0.55 to 0.96. `L = 3` adds 0.003 and every longer window is
|
|
||||||
*worse*, because the assumption that one regime governs the window stops holding
|
|
||||||
(`sw.frac` reaches 0.64 at `L = 40`). The saturation point is not a plateau; it is a
|
|
||||||
peak at `L = 2–3`, and the decline past it is the domain telling you that more history
|
|
||||||
is actively harmful once the window outruns the regime.
|
|
||||||
|
|
||||||
Three details worth carrying:
|
|
||||||
|
|
||||||
- **The linear decoder on the raw window never rises** — 0.23 against 0.23 at every
|
|
||||||
`L`. Exactly the case the brief warned about: a linear probe here would have said
|
|
||||||
the regime is unidentifiable, and it would have been wrong by 0.7 in accuracy. The
|
|
||||||
MLP and `phys` are what settle it, and `bayes` bounds them.
|
|
||||||
- **`phys` tracks `bayes` to within 0.05 and never beats it**, which is the
|
|
||||||
cross-check the construction demanded.
|
|
||||||
- **The instantaneous read-off is much larger than the organism's.** At `L = 1`, with
|
|
||||||
no displacement at all, the MLP reaches 0.552 per-step and 0.405 per-entity against
|
|
||||||
a measured chance of 0.25. `frozen.md` §2 decoded the regime from the organism's own
|
|
||||||
`h` at 0.342 and from `M` at 0.332, against 0.274 — a gap of +0.07 where the
|
|
||||||
configuration in front of it supports +0.15. The organism is discarding most of the
|
|
||||||
regime information already visible in a single frame.
|
|
||||||
|
|
||||||
### 2c. `T_id` at each duration Part 3 sweeps
|
|
||||||
|
|
||||||
`bayes` per-step, 4 seeds, 4000 steps. `argmax L` is where accuracy saturates.
|
|
||||||
|
|
||||||
```
|
|
||||||
T_z L=2 L=3 L=5 L=10 L=20 L=40 argmax L
|
|
||||||
----------------------------------------------------------------------------
|
|
||||||
4-8 0.825 0.722 0.538 0.250 0.300 0.267 2
|
|
||||||
10-20 0.930 0.890 0.821 0.644 0.313 0.339 2
|
|
||||||
40-80 0.978 0.974 0.959 0.922 0.858 0.726 2
|
|
||||||
150-300 0.973 0.989 0.989 0.980 0.963 0.930 5
|
|
||||||
600-1200 0.960 0.991 0.997 0.995 0.992 0.985 5
|
|
||||||
```
|
|
||||||
|
|
||||||
`T_id` is 2 across the sweep, drifting to 5 at the longest durations where a longer
|
|
||||||
window is finally safe to use. **`T_id` is between 1 and 4 steps of history at every
|
|
||||||
duration Part 3 tests**, and is undefined at the frozen regime, which has nothing to
|
|
||||||
identify.
|
|
||||||
|
|
||||||
### 2d. `G` at each duration
|
|
||||||
|
|
||||||
`ceilings.py`, rows D → C, 1200 steps, seeds 0–2. The oracle prize against the noisy
|
|
||||||
target:
|
|
||||||
|
|
||||||
```
|
|
||||||
T_z 4-8 10-20 40-80 150-300 600-1200 frozen
|
|
||||||
--------------------------------------------------------------
|
|
||||||
G 1.95 1.62 1.56 1.48 1.24 1.00
|
|
||||||
```
|
|
||||||
|
|
||||||
The 40–80 value reproduces `headroom.md` §3's 1.56x exactly. `G` decays monotonically
|
|
||||||
with duration and reaches **exactly 1.00 at the frozen regime**, which is the
|
|
||||||
self-consistency check: a regime that never changes carries no information, so a
|
|
||||||
regime oracle can be worth nothing. Every row A self-check passes.
|
|
||||||
|
|
||||||
### The reading the brief pre-registered
|
|
||||||
|
|
||||||
> `T_id << T_z` — the domain *can* reward memory, and the failure is ours rather than
|
|
||||||
> the domain's. That points at the architecture or the training signal, and it is a
|
|
||||||
> much more uncomfortable and more useful result.
|
|
||||||
|
|
||||||
`T_id = 2`, `T_z = 40–80`. **`T_id` is 20 to 40 times smaller than `T_z`, and `G` is
|
|
||||||
1.56.** The domain satisfies the pre-registered condition, comfortably, on both
|
|
||||||
quantities. The regime is identifiable from one observed step and then holds still for
|
|
||||||
another forty. This is the uncomfortable branch, and §2b's last bullet says where to
|
|
||||||
look: the organism's own representation carries less than half the regime information
|
|
||||||
that a decoder recovers from the same frame.
|
|
||||||
|
|
||||||
## 3. Part 3 — the falsifiable test
|
|
||||||
|
|
||||||
The capacity-controlled state gain `grp_k0_nostate / grp_k0`: identical architecture,
|
|
||||||
identical 5602 parameters, differing only in whether `M` is carried between steps.
|
|
||||||
A `grp_k0` vs `rp_only` number is confounded 3.9x (`frozen.md` §5) and is not this
|
|
||||||
measurement. κ = 0 in both arms; affect is at its defaults and plays no part here.
|
|
||||||
|
|
||||||
Shortening the regime changes the world's timescale, so the metrics were re-checked
|
|
||||||
rather than re-used. Two things were done about it:
|
|
||||||
|
|
||||||
- **The recovery window is enforced per duration.** `regime.run` refuses
|
|
||||||
`window >= t_min`; the same rule is applied here, and each run stores its metrics at
|
|
||||||
every window shorter than its own `t_min`. Tables quote **window 1** because it is
|
|
||||||
the only window a duration of 2–3 admits and therefore the one column every duration
|
|
||||||
can be compared on; windows 3 and 9 are given alongside and agree.
|
|
||||||
- **Switch counts are reported rather than implied.** At 600–1200 there are ~4
|
|
||||||
switches in the measured half — enough for `steady`, which averages over thousands
|
|
||||||
of steps, and not enough for a recovery curve. **No `recovery[k]` number is quoted
|
|
||||||
from the two longest durations**, and the state gain is read off `steady` throughout.
|
|
||||||
|
|
||||||
```
|
|
||||||
regime duration state gain median seeds won per-seed range
|
|
||||||
------------------------------------------------------------------
|
|
||||||
2-3 1.09 1.06 10/16 0.76 - 1.66
|
|
||||||
4-8 1.10 1.04 10/16 0.87 - 1.72
|
|
||||||
10-20 1.09 1.01 10/16 0.83 - 1.56
|
|
||||||
40-80 1.17 1.11 11/16 0.91 - 1.88
|
|
||||||
150-300 1.22 1.20 10/16 0.32 - 2.86
|
|
||||||
600-1200 1.12 1.01 8/16 0.62 - 1.77
|
|
||||||
frozen 1.26 1.12 11/16 0.69 - 1.99
|
|
||||||
```
|
|
||||||
|
|
||||||
Read down the `state gain` column. It does not have a peak. It is flat at 1.09-1.26
|
|
||||||
across regime durations spanning four orders of magnitude, and every difference between
|
|
||||||
durations is smaller than the per-seed range within any one of them: at 150-300 the
|
|
||||||
individual seeds run from 0.32 to 2.86, which is wider than the entire spread of the
|
|
||||||
column means. On a paired count the picture is the same, 8 to 11 seeds of 16 at every
|
|
||||||
duration -- a coin flip that never becomes anything else.
|
|
||||||
|
|
||||||
The decisive row is the last one. **The largest state gain in the sweep is at the frozen
|
|
||||||
regime**, where there is no regime to identify, no switch to recover from, and `G`
|
|
||||||
measures exactly 1.00. A quantity that is at its largest when its supposed cause is
|
|
||||||
entirely absent is not caused by it.
|
|
||||||
|
|
||||||
What the state gain measures is therefore not regime tracking. It is temporal smoothing:
|
|
||||||
carrying `M` averages the representation over recent steps, which reduces variance
|
|
||||||
against a noisy target, and a stationary world rewards that at least as well as a
|
|
||||||
switching one does.
|
|
||||||
|
|
||||||
## 4. So: when does per-entity memory have a job?
|
|
||||||
|
|
||||||
The task was built on a theory, pre-registered before any run: memory has a job when the
|
|
||||||
hidden variable is identifiable much faster than it changes (`T_id << T_z`) and knowing it
|
|
||||||
is worth something (`G` materially above 1). The prediction was a peak in state gain at
|
|
||||||
intermediate regime durations.
|
|
||||||
|
|
||||||
**The theory is wrong as stated, and the three parts falsify it from three directions.**
|
|
||||||
|
|
||||||
Its condition is satisfied here -- comfortably. `T_id` is 2 to 3 observations against a
|
|
||||||
`T_z` of 40-80, a margin of twenty-fold or more, and `G` is 1.54x. By the theory this
|
|
||||||
domain should be close to ideal for per-entity memory. It is not: the state gain is 1.17
|
|
||||||
at that duration, on 11 seeds of 16, and it is *higher* at the frozen regime where the
|
|
||||||
condition is not satisfied at all. A criterion that is met exactly where the effect is
|
|
||||||
absent, and unmet exactly where the effect is largest, is not the criterion.
|
|
||||||
|
|
||||||
What the three parts establish together is more useful than the theory they refute.
|
|
||||||
|
|
||||||
**The domain is the rememberable kind.** Part 2 settles the question the poker framing
|
|
||||||
raised: is the evidence for the hidden variable already in the present, making history
|
|
||||||
redundant, or does it live only in the past? Here it lives in the past. One observed
|
|
||||||
displacement carries the regime almost perfectly -- 0.958 for an exact decoder, 0.909 for
|
|
||||||
one that has never seen a coupling matrix -- while the instantaneous configuration alone
|
|
||||||
supports 0.574 at best. History nearly doubles the present's above-chance information.
|
|
||||||
This is not a domain where feedforward suffices in principle.
|
|
||||||
|
|
||||||
**The organism captures almost none of it.** `frozen.md` Part B decoded the regime from
|
|
||||||
the GRP's memory at 0.332. The same regime is available at 0.909 from a single step of
|
|
||||||
history, using a decoder with no privileged knowledge. `M` holds roughly a fifth of the
|
|
||||||
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
|
|
||||||
out that way. This matters beyond this file, because the project's standing reflex when
|
|
||||||
memory failed to help was to reach for a different domain. That reflex is now closed off.
|
|
||||||
The information was here all along.
|
|
||||||
|
|
||||||
The mechanism is visible in the other files rather than derived here, and the three
|
|
||||||
observations compose:
|
|
||||||
|
|
||||||
- The gate's learned pre-activation never leaves zero, at any `kappa`, after any amount of
|
|
||||||
training (`a1.md` §1b). Nothing about what to keep is ever decided.
|
|
||||||
- The margin the GRP does win is its gated post-RP nonlinearity, not carried state and not
|
|
||||||
parameter count (`frozen.md` §1d).
|
|
||||||
- Affect can move the gate, exactly and on cue once its time constants are set (Part 1
|
|
||||||
above), and moving it changes nothing, because there is no stored quantity for an opened
|
|
||||||
gate to admit or a closed one to protect.
|
|
||||||
|
|
||||||
The regime is identifiable from an observed displacement -- which arrives one step after
|
|
||||||
the prediction it would have helped. Carrying that one step forward is precisely what
|
|
||||||
per-entity memory is for, and precisely what the gate would have to learn to do. It never
|
|
||||||
does. Whether that is a credit-assignment failure, a consequence of the per-step loss term
|
|
||||||
dominating the temporal one, or a mismatch between a global hidden variable and a
|
|
||||||
per-entity state, this file does not determine. It establishes only that the question is
|
|
||||||
now about the organism and no longer about the domain.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
*Write-up note: the agent that ran these measurements died mid-write when the machine
|
|
||||||
slept, leaving §3's table and §4 unwritten. Both were completed from the committed JSON
|
|
||||||
by the session controller, which independently recomputed Part 3's table from
|
|
||||||
`w_duration_all.json` and `w_duration_frozen.json`, Part 1's paired ratios and arousal
|
|
||||||
profiles from `w_best.json` and `w_timing.json`, and Part 2's decoder series from
|
|
||||||
`identify.json`. No sweep was re-run and no number was carried over unverified.*
|
|
||||||
@@ -1,124 +0,0 @@
|
|||||||
"""One parameter set, an entity count it never trained on.
|
|
||||||
|
|
||||||
Row 1 of `rp_properties.md`, second half. That the RP is *defined* at any N is structural and
|
|
||||||
already asserted in the library's tests; a fixed-weight layer is not worse there, it has no
|
|
||||||
input dimension to use. What is not established is whether it still WORKS at an N it never saw,
|
|
||||||
and defined is not competent.
|
|
||||||
|
|
||||||
THE TABLE ARM IS HERE ON PURPOSE. A lookup kernel generalises over N for the same reason the
|
|
||||||
CPPN does -- neither has a parameter tied to the entity count. If it holds up, this property
|
|
||||||
separates the RP from a perceptron and NOT from a GNN, which is what the property card already
|
|
||||||
claims and what should be measured rather than argued.
|
|
||||||
|
|
||||||
THE CONFOUND THIS IS BUILT TO SEPARATE. `h_i` is a mean over neighbours, so raising N raises the
|
|
||||||
degree and changes the pooled statistics. Degradation at large N could be that, not a failure to
|
|
||||||
generalise over entity count. Hence the reverse direction: train large and evaluate small. A
|
|
||||||
failure in BOTH directions is about the degree distribution shifting; a failure in one is about
|
|
||||||
the direction it was asked to extrapolate.
|
|
||||||
|
|
||||||
MEASUREMENT NOTE, found in the smoke run and worth more than the run that found it. Dividing by
|
|
||||||
a per-N floor does NOT make the axis comparable. `y_i` is a mean over neighbours, so raising N
|
|
||||||
averages more terms, the target's variance falls, the floor falls with it, and the ratio climbs
|
|
||||||
even for a model that is doing fine. The ratio is reported because it is informative WITHIN one
|
|
||||||
N, across arms -- never read down a column as a trend.
|
|
||||||
|
|
||||||
What makes the axis comparable is an ORACLE, which is this repo's rule anyway: a model trained
|
|
||||||
over the FULL range [2,32] and evaluated at the same N. Degradation from an unseen entity count
|
|
||||||
is then (model trained on [2,16]) against (model trained on [2,32]) at the same N, and every
|
|
||||||
N-dependent difficulty cancels. Three runs, compared in `analyse_scale.py`:
|
|
||||||
|
|
||||||
--train 2,16 forward: small seen, large unseen
|
|
||||||
--train 17,32 reverse: large seen, small unseen
|
|
||||||
--train 2,32 the oracle both are read against
|
|
||||||
"""
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import argparse
|
|
||||||
import json
|
|
||||||
import statistics
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
import torch
|
|
||||||
|
|
||||||
from unseen import ATTR, D, make_model, run_model, teacher
|
|
||||||
|
|
||||||
|
|
||||||
def configs(n: int, count: int, gen: torch.Generator):
|
|
||||||
out = []
|
|
||||||
for _ in range(count):
|
|
||||||
c = torch.randint(0, 8, (n, 2), generator=gen).float()
|
|
||||||
out.append((torch.randn(n, ATTR, generator=gen), c[None, :, :] - c[:, None, :],
|
|
||||||
torch.ones(n, n)))
|
|
||||||
return out
|
|
||||||
|
|
||||||
|
|
||||||
def mixed_batch(lo: int, hi: int, gen: torch.Generator, size=24):
|
|
||||||
out = []
|
|
||||||
for _ in range(size):
|
|
||||||
n = int(torch.randint(lo, hi + 1, (1,), generator=gen))
|
|
||||||
out += configs(n, 1, gen)
|
|
||||||
return out
|
|
||||||
|
|
||||||
|
|
||||||
def evaluate(model, tea, data):
|
|
||||||
with torch.no_grad():
|
|
||||||
err = sum(((run_model(model, a, r, m) - run_model(tea, a, r, m)) ** 2).sum().item()
|
|
||||||
for a, r, m in data)
|
|
||||||
ys = torch.cat([run_model(tea, a, r, m) for a, r, m in data])
|
|
||||||
n = sum(a.shape[0] * D for a, _, _ in data)
|
|
||||||
return err / n, ((ys - ys.mean(0)) ** 2).mean().item()
|
|
||||||
|
|
||||||
|
|
||||||
def one_seed(arm, lo, hi, evals, steps, seed, omega):
|
|
||||||
tea = teacher(seed)
|
|
||||||
gen = torch.Generator().manual_seed(seed)
|
|
||||||
model = make_model(arm, seed, omega)
|
|
||||||
opt = torch.optim.Adam(model.parameters(), lr=3e-3)
|
|
||||||
for _ in range(steps):
|
|
||||||
data = mixed_batch(lo, hi, gen)
|
|
||||||
loss = sum(((run_model(model, a, r, m) - run_model(tea, a, r, m)) ** 2).mean()
|
|
||||||
for a, r, m in data) / len(data)
|
|
||||||
opt.zero_grad(); loss.backward(); opt.step()
|
|
||||||
|
|
||||||
ev = torch.Generator().manual_seed(seed + 5000)
|
|
||||||
per_n = {}
|
|
||||||
for n in evals:
|
|
||||||
mse, floor = evaluate(model, tea, configs(n, 24, ev))
|
|
||||||
per_n[n] = {"mse": mse, "floor": floor, "ratio": mse / floor}
|
|
||||||
return {"seed": seed, "arm": arm, "omega": omega, "train_lo": lo, "train_hi": hi,
|
|
||||||
"per_n": per_n}
|
|
||||||
|
|
||||||
|
|
||||||
def main():
|
|
||||||
ap = argparse.ArgumentParser()
|
|
||||||
ap.add_argument("--train", default="2,16", help="lo,hi entity count seen in training")
|
|
||||||
ap.add_argument("--evals", default="2,4,8,12,16,20,24,28,32")
|
|
||||||
ap.add_argument("--arms", default="rp,table")
|
|
||||||
ap.add_argument("--omega", type=float, default=1.0)
|
|
||||||
ap.add_argument("--steps", type=int, default=2000)
|
|
||||||
ap.add_argument("--seeds", default="0,1,2,3,4,5,6,7")
|
|
||||||
ap.add_argument("--out", default="results/scale.json")
|
|
||||||
args = ap.parse_args()
|
|
||||||
|
|
||||||
lo, hi = (int(x) for x in args.train.split(","))
|
|
||||||
evals = [int(x) for x in args.evals.split(",")]
|
|
||||||
rows = []
|
|
||||||
for arm in args.arms.split(","):
|
|
||||||
for s in (int(x) for x in args.seeds.split(",")):
|
|
||||||
rows.append(one_seed(arm, lo, hi, evals, args.steps, s, args.omega))
|
|
||||||
print(f"{arm:6s} seed {s} " + " ".join(
|
|
||||||
f"N{n}:{rows[-1]['per_n'][n]['ratio']:.4f}" for n in evals), flush=True)
|
|
||||||
|
|
||||||
print(f"\ntrained on N in [{lo},{hi}], omega={args.omega} (mse / per-N floor)")
|
|
||||||
print(f"{'arm':6s} " + " ".join(f"{('N' + str(n)) + ('*' if lo <= n <= hi else ''):>9s}"
|
|
||||||
for n in evals))
|
|
||||||
for arm in args.arms.split(","):
|
|
||||||
a = [r for r in rows if r["arm"] == arm]
|
|
||||||
print(f"{arm:6s} " + " ".join(
|
|
||||||
f"{statistics.mean([r['per_n'][n]['ratio'] for r in a]):9.4f}" for n in evals))
|
|
||||||
print("* = inside the training range")
|
|
||||||
Path(args.out).write_text(json.dumps({"args": vars(args), "rows": rows}, indent=1))
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
main()
|
|
||||||
@@ -1,110 +0,0 @@
|
|||||||
import numpy as np
|
|
||||||
import pytest
|
|
||||||
|
|
||||||
import regime
|
|
||||||
from a1 import GateTrace, affect_variants, gate_stats, index_sets, run_a1
|
|
||||||
from frozen import _build, _train
|
|
||||||
|
|
||||||
|
|
||||||
def _run(seed=0, steps=400, **kw):
|
|
||||||
spec, wcfg, world, org = _build("grp_k", seed, 32, 10.0, 4.0)
|
|
||||||
affect, mem, tr = _train(spec, wcfg, world, org, steps, 20, 1e-3, **kw)
|
|
||||||
return org, tr
|
|
||||||
|
|
||||||
|
|
||||||
def test_replaying_the_runs_own_arousal_reproduces_it_exactly():
|
|
||||||
"""The Part C control replaces the arousal the gate sees and passes the context
|
|
||||||
explicitly instead of letting `Organism.forward` build it. Replaying the sequence
|
|
||||||
the gate itself saw must therefore change nothing at all -- if it does, every
|
|
||||||
shuffled result is measuring the plumbing rather than the timing."""
|
|
||||||
base = run_a1("grp_k", 0, 4.0, steps=400)
|
|
||||||
seen = base["a_gate_seq"]
|
|
||||||
replayed = run_a1("grp_k", 0, 4.0, steps=400, gate_arousal=lambda t, _a, s=seen: s[t])
|
|
||||||
assert replayed["steady"] == base["steady"]
|
|
||||||
assert replayed["recovery"] == base["recovery"]
|
|
||||||
assert replayed["a_gate_seq"] == seen
|
|
||||||
|
|
||||||
|
|
||||||
def test_on_step_does_not_perturb_the_run():
|
|
||||||
"""The gate instrumentation is read-only: hooking it must not move a single loss."""
|
|
||||||
_, base = _run()
|
|
||||||
_, hooked = _run(on_step=lambda *args: None)
|
|
||||||
assert hooked["losses"] == base["losses"]
|
|
||||||
|
|
||||||
|
|
||||||
def test_gate_reconstruction_is_the_organisms_own_gate(monkeypatch):
|
|
||||||
"""`GateTrace` asserts `org.grp(h, prev, a)` equals the M the organism returned, so
|
|
||||||
the reported g is the organism's own gate and not a plausible lookalike. Feeding it
|
|
||||||
an h the organism never used must trip that assert, or it is guarding nothing."""
|
|
||||||
spec, wcfg, world, org = _build("grp_k", 0, 32, 10.0, 4.0)
|
|
||||||
tr = GateTrace(org)
|
|
||||||
_train(spec, wcfg, world, org, 50, 20, 1e-3, on_step=tr)
|
|
||||||
assert len(tr.g_mean) == 50 and all(0.0 < g < 1.0 for g in tr.g_mean)
|
|
||||||
|
|
||||||
import a1
|
|
||||||
real_hidden = a1._hidden
|
|
||||||
monkeypatch.setattr(a1, "_hidden", lambda *args: real_hidden(*args) + 1e-6)
|
|
||||||
spec, wcfg, world, org = _build("grp_k", 0, 32, 10.0, 4.0)
|
|
||||||
with pytest.raises(AssertionError, match="gate reconstruction diverged"):
|
|
||||||
_train(spec, wcfg, world, org, 5, 20, 1e-3, on_step=GateTrace(org))
|
|
||||||
|
|
||||||
|
|
||||||
def test_index_sets_match_the_metrics_the_error_is_measured_on():
|
|
||||||
"""`far` must be `_metrics`'s own steady_idx and `post` its recovery steps, or the
|
|
||||||
gate contrast and the error contrast are measured on different steps."""
|
|
||||||
steps, window = 400, 20
|
|
||||||
switched = [i % 57 == 0 for i in range(steps)]
|
|
||||||
idx = index_sets(switched, steps, window)
|
|
||||||
half = steps // 2
|
|
||||||
steady_idx = [i for i in range(half, steps) if not any(switched[max(0, i - window):i + 1])]
|
|
||||||
assert idx["far"] == steady_idx
|
|
||||||
assert idx["post"] == sorted({j + k for j in idx["switch"] for k in range(window)})
|
|
||||||
assert not set(idx["far"]) & set(idx["post"])
|
|
||||||
assert all(i >= half for i in idx["far"] + idx["switch"])
|
|
||||||
|
|
||||||
|
|
||||||
def test_gate_stats_pools_the_sd_over_entity_steps():
|
|
||||||
"""Per-step means of g and g^2 must pool to the sd over all entity-steps."""
|
|
||||||
rng = np.random.default_rng(0)
|
|
||||||
steps, n = 200, 16
|
|
||||||
g = rng.random((steps, n))
|
|
||||||
tr = GateTrace.__new__(GateTrace)
|
|
||||||
tr.g_mean = list(g.mean(1)); tr.g_sq = list((g ** 2).mean(1))
|
|
||||||
tr.open_ = list((g > 0.9).mean(1)); tr.shut = list((g < 0.1).mean(1))
|
|
||||||
tr.pre_mean = list(g.mean(1)); tr.pre_sq = list((g ** 2).mean(1))
|
|
||||||
tr.a_gate = [0.0] * steps
|
|
||||||
tr.org = None
|
|
||||||
out = gate_stats(tr, [False] * steps, steps, 20)
|
|
||||||
half = g[steps // 2:]
|
|
||||||
assert out["all"]["g"] == pytest.approx(half.mean())
|
|
||||||
assert out["all"]["g_sd"] == pytest.approx(half.std(), abs=1e-9)
|
|
||||||
|
|
||||||
|
|
||||||
def test_affect_variants_preserve_the_values_and_destroy_the_timing():
|
|
||||||
steps = 400
|
|
||||||
a = list(np.random.default_rng(1).random(steps))
|
|
||||||
v = affect_variants(a, seed=3, steps=steps)
|
|
||||||
half = steps // 2
|
|
||||||
assert np.array_equal(v["real"], a)
|
|
||||||
for tag in ("shuffled", "shifted", "const"):
|
|
||||||
assert len(v[tag]) == steps
|
|
||||||
# shuffled matches the marginal exactly in each half, not merely in expectation
|
|
||||||
for sl in (slice(0, half), slice(half, steps)):
|
|
||||||
assert sorted(v["shuffled"][sl]) == pytest.approx(sorted(np.asarray(a)[sl]))
|
|
||||||
assert sorted(v["shifted"]) == pytest.approx(sorted(a)) # a roll keeps every value
|
|
||||||
assert v["const"].std() == pytest.approx(0) and v["const"][0] == pytest.approx(np.mean(a))
|
|
||||||
assert not np.array_equal(v["shuffled"], a) and not np.array_equal(v["shifted"], a)
|
|
||||||
|
|
||||||
|
|
||||||
def test_kappa_lowers_the_gate_in_the_direction_the_spec_says():
|
|
||||||
"""g -> 0 overwrites, g -> 1 keeps, and arousal is non-negative, so forcing can
|
|
||||||
only push g down. A positive delta here would mean the sign is wired backwards."""
|
|
||||||
lo = run_a1("grp_k", 0, 0.0, steps=600)["gate"]["all"]["g"]
|
|
||||||
hi = run_a1("grp_k", 0, 16.0, steps=600)["gate"]["all"]["g"]
|
|
||||||
assert hi < lo < 0.55
|
|
||||||
|
|
||||||
|
|
||||||
def test_run_a1_reports_the_same_metrics_regime_run_does():
|
|
||||||
r = run_a1("grp_k", 0, 0.0, steps=400)
|
|
||||||
theirs = regime.run("grp_k0", seed=0, steps=400)
|
|
||||||
assert r["steady"] == theirs["steady"] and r["recovery"] == theirs["recovery"]
|
|
||||||
@@ -1,48 +0,0 @@
|
|||||||
"""Identity is the load-bearing part: a memory slot must follow the same piece.
|
|
||||||
|
|
||||||
If `advance_ids` drifts, every arm still trains and every number still prints -- the memory
|
|
||||||
just follows the wrong piece. That failure is silent, so it gets the test.
|
|
||||||
"""
|
|
||||||
import chess
|
|
||||||
import chess.pgn
|
|
||||||
import pytest
|
|
||||||
|
|
||||||
import chess_domain
|
|
||||||
|
|
||||||
|
|
||||||
def _game(fen: str | None, sans: list[str]) -> chess.pgn.Game:
|
|
||||||
board = chess.Board(fen) if fen else chess.Board()
|
|
||||||
for san in sans:
|
|
||||||
board.push_san(san)
|
|
||||||
return chess.pgn.Game.from_board(board)
|
|
||||||
|
|
||||||
|
|
||||||
CASTLE_EP = ["e4", "e5", "Nf3", "Nf6", "Bc4", "Bc5", "O-O", "O-O",
|
|
||||||
"d4", "exd4", "e5", "d5", "exd6"]
|
|
||||||
|
|
||||||
|
|
||||||
def test_rook_keeps_its_id_through_castling():
|
|
||||||
plies = chess_domain.plies(_game(None, CASTLE_EP))
|
|
||||||
h1 = chess.H1
|
|
||||||
after = next(p for p in plies if h1 not in # h1 empty: rook has moved
|
|
||||||
[chess.square(int(c[0] * 7), int(c[1] * 7)) for c in p.coords])
|
|
||||||
f1_row = [k for k, c in enumerate(after.coords)
|
|
||||||
if chess.square(int(c[0] * 7), int(c[1] * 7)) == chess.F1][0]
|
|
||||||
assert after.ids[f1_row] == h1, "the castled rook was handed a new identity"
|
|
||||||
|
|
||||||
|
|
||||||
def test_promoted_pawn_keeps_its_id_and_changes_type():
|
|
||||||
plies = chess_domain.plies(_game("1r4k1/P7/8/8/8/8/8/6K1 w - - 0 1", ["axb8=Q", "Kf7"]))
|
|
||||||
row = plies[-1].ids.index(chess.A7) # the pawn that started on a7
|
|
||||||
coords = plies[-1].coords[row]
|
|
||||||
assert chess.square(int(coords[0] * 7), int(coords[1] * 7)) == chess.B8
|
|
||||||
assert plies[-1].attrs[row][chess.QUEEN - 1] == 1.0, "promotion did not change the type"
|
|
||||||
|
|
||||||
|
|
||||||
def test_the_identity_assertion_can_actually_fire(monkeypatch):
|
|
||||||
"""Sabotage: stop tracking captures, and the board must disagree with the map."""
|
|
||||||
monkeypatch.setattr(chess_domain, "advance_ids",
|
|
||||||
lambda board, move, piece, id_at: id_at.update(
|
|
||||||
{move.to_square: id_at.pop(move.from_square, move.from_square)}))
|
|
||||||
with pytest.raises(AssertionError, match="drifted"):
|
|
||||||
chess_domain.plies(_game(None, CASTLE_EP))
|
|
||||||
@@ -1,156 +0,0 @@
|
|||||||
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
|
|
||||||
@@ -1,173 +0,0 @@
|
|||||||
import numpy as np
|
|
||||||
import pytest
|
|
||||||
import torch
|
|
||||||
from torch import nn
|
|
||||||
|
|
||||||
import frozen
|
|
||||||
import regime
|
|
||||||
from frozen import _build, _frozen, _hidden, _train, probe, run_one
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize("name", ["rp_only", "grp_k0"])
|
|
||||||
def test_train_copy_is_identical_to_regime_run(name):
|
|
||||||
"""`_train` is a verbatim copy of `regime.run`'s loop; this pins it.
|
|
||||||
|
|
||||||
If anyone edits either loop apart from the other, the metrics diverge and this
|
|
||||||
fails -- which is the only guarantee that the frozen phase starts from the same
|
|
||||||
organism Task 7 measured.
|
|
||||||
"""
|
|
||||||
steps, window, bptt = 400, 20, 20
|
|
||||||
spec, wcfg, world, org = _build(name, seed=0, hidden=32, omega=10.0, kappa=4.0)
|
|
||||||
_, _, tr = _train(spec, wcfg, world, org, steps, bptt, lr=1e-3)
|
|
||||||
mine = regime._metrics(tr["losses"], tr["switched"], tr["arousals"], window)
|
|
||||||
theirs = regime.run(name, seed=0, steps=steps, window=window, bptt=bptt)
|
|
||||||
assert mine["steady"] == theirs["steady"]
|
|
||||||
assert mine["recovery"] == theirs["recovery"]
|
|
||||||
assert mine["n_switches"] == theirs["n_switches"]
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize("name", ["rp_only", "grp_k0"])
|
|
||||||
def test_frozen_phase_leaves_every_parameter_bit_identical(name):
|
|
||||||
spec, wcfg, world, org = _build(name, seed=0, hidden=32, omega=10.0, kappa=4.0)
|
|
||||||
affect, memory, _ = _train(spec, wcfg, world, org, 200, 20, lr=1e-3)
|
|
||||||
before = nn.utils.parameters_to_vector(org.parameters()).clone()
|
|
||||||
fr = _frozen(spec, wcfg, world, org, affect, memory, 200)
|
|
||||||
after = nn.utils.parameters_to_vector(org.parameters())
|
|
||||||
assert fr["frozen_bit_identical"]
|
|
||||||
assert torch.equal(before, after)
|
|
||||||
assert not any(p.requires_grad for p in org.parameters())
|
|
||||||
|
|
||||||
|
|
||||||
def test_memory_keeps_updating_while_weights_are_frozen():
|
|
||||||
"""Freezing is about parameters, not state. A frozen M would silently turn the
|
|
||||||
GRP into an RP and make any null a null for the wrong reason."""
|
|
||||||
spec, wcfg, world, org = _build("grp_k0", seed=0, hidden=32, omega=10.0, kappa=4.0)
|
|
||||||
affect, memory, _ = _train(spec, wcfg, world, org, 200, 20, lr=1e-3)
|
|
||||||
fr = _frozen(spec, wcfg, world, org, affect, memory, 200)
|
|
||||||
assert fr["dM_min"] > 0.0
|
|
||||||
assert fr["dM_mean"] > 0.0
|
|
||||||
assert fr["M"].shape == (200, wcfg.n, org.hidden_dim)
|
|
||||||
|
|
||||||
|
|
||||||
def test_frozen_phase_detects_a_parameter_change():
|
|
||||||
"""The freeze assertion has to be able to fail, or it proves nothing."""
|
|
||||||
spec, wcfg, world, org = _build("grp_k0", seed=0, hidden=32, omega=10.0, kappa=4.0)
|
|
||||||
affect, memory, _ = _train(spec, wcfg, world, org, 100, 20, lr=1e-3)
|
|
||||||
orig = _frozen.__globals__["nn"].utils.parameters_to_vector
|
|
||||||
calls = {"n": 0}
|
|
||||||
|
|
||||||
def sneaky(params):
|
|
||||||
v = orig(params)
|
|
||||||
calls["n"] += 1
|
|
||||||
if calls["n"] == 1: # let a weight move right after the "before" snapshot
|
|
||||||
with torch.no_grad():
|
|
||||||
org.out.bias.add_(1e-6)
|
|
||||||
return v
|
|
||||||
|
|
||||||
frozen.nn.utils.parameters_to_vector = sneaky
|
|
||||||
try:
|
|
||||||
with pytest.raises(AssertionError):
|
|
||||||
_frozen(spec, wcfg, world, org, affect, memory, 20)
|
|
||||||
finally:
|
|
||||||
frozen.nn.utils.parameters_to_vector = orig
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize("name", ["rp_only", "grp_k0"])
|
|
||||||
def test_hidden_reconstruction_matches_the_organism(name):
|
|
||||||
"""`_hidden` must rebuild the same edge one-hot, mask and context `Organism.forward`
|
|
||||||
builds, or the RP probe would be run on a representation the organism never used."""
|
|
||||||
spec, wcfg, world, org = _build(name, seed=1, hidden=32, omega=10.0, kappa=4.0)
|
|
||||||
from ailed import Affect
|
|
||||||
from particles import wrapped_diff
|
|
||||||
obs = world.step()
|
|
||||||
affect = Affect()
|
|
||||||
with torch.no_grad():
|
|
||||||
r = wrapped_diff(obs.coords)
|
|
||||||
pred, mem = org(obs.attrs, r, obs.ids, affect.axes, {}, context=None)
|
|
||||||
h = _hidden(org, obs.attrs, r, affect.axes, None)
|
|
||||||
if org.use_memory:
|
|
||||||
zero = torch.zeros(org.hidden_dim)
|
|
||||||
prev = torch.stack([zero for _ in obs.ids])
|
|
||||||
M = torch.stack([mem[i] for i in obs.ids])
|
|
||||||
assert torch.equal(org.grp(h, prev, affect.arousal), M)
|
|
||||||
else:
|
|
||||||
assert torch.equal(org.out(h), pred)
|
|
||||||
|
|
||||||
|
|
||||||
def test_probe_recovers_a_planted_regime_signal_and_not_a_planted_absence():
|
|
||||||
"""Two ends of the probe: a representation that linearly carries the label must
|
|
||||||
decode well above the measured chance level, and pure noise must not."""
|
|
||||||
rng = np.random.default_rng(0)
|
|
||||||
T, N, R = 600, 8, 4
|
|
||||||
labels, switched, cur, left = [], [], 0, 0
|
|
||||||
for t in range(T):
|
|
||||||
if left == 0:
|
|
||||||
cur, left = int(rng.integers(R)), int(rng.integers(40, 80))
|
|
||||||
switched.append(True)
|
|
||||||
else:
|
|
||||||
switched.append(False)
|
|
||||||
labels.append(cur); left -= 1
|
|
||||||
labels = np.asarray(labels)
|
|
||||||
|
|
||||||
signal = np.eye(R)[labels][:, None, :].repeat(N, 1) + 0.1 * rng.normal(size=(T, N, R))
|
|
||||||
noise = rng.normal(size=(T, N, R))
|
|
||||||
good = probe(signal, labels, switched, R, n_null=5)
|
|
||||||
bad = probe(noise, labels, switched, R, n_null=5)
|
|
||||||
|
|
||||||
assert good["acc_entity"] > 0.9 > good["chance_shift_max"]
|
|
||||||
assert bad["acc_entity"] <= bad["chance_shift_max"] + 0.05
|
|
||||||
|
|
||||||
|
|
||||||
def test_probe_test_split_is_a_suffix_in_time():
|
|
||||||
"""A random split would let the probe memorise steps adjacent to the test steps."""
|
|
||||||
rng = np.random.default_rng(0)
|
|
||||||
T, N, R = 200, 4, 3
|
|
||||||
labels = np.repeat(np.arange(T // 50) % R, 50)
|
|
||||||
reps = rng.normal(size=(T, N, R))
|
|
||||||
out = probe(reps, labels, [False] * T, R, split=0.7, n_null=2)
|
|
||||||
assert out["n_test_steps"] == T - int(T * 0.7)
|
|
||||||
|
|
||||||
|
|
||||||
def test_run_one_reports_both_phases_and_the_freeze_check():
|
|
||||||
r = run_one("grp_k0", seed=0, train_steps=200, frozen_steps=200, window=20)
|
|
||||||
assert r["frozen_bit_identical"] is True
|
|
||||||
assert r["probe_on"] == "M" and set(r["probes"]) >= {"M_lsq", "h_lsq", "M_logit"}
|
|
||||||
assert len(r["frozen"]["recovery"]) == 20
|
|
||||||
assert r["trained"]["steady"] >= 0.0
|
|
||||||
assert run_one("rp_only", seed=0, train_steps=200, frozen_steps=200)["probe_on"] == "h"
|
|
||||||
|
|
||||||
|
|
||||||
def test_probe_accepts_per_entity_labels():
|
|
||||||
"""The coupling row differs between entities at the same step, so the probe has to
|
|
||||||
take a (T, N) target as well as the (T,) regime id."""
|
|
||||||
rng = np.random.default_rng(1)
|
|
||||||
T, N, R = 400, 6, 3
|
|
||||||
lab = rng.integers(0, R, size=(T, N))
|
|
||||||
reps = np.eye(R)[lab] + 0.1 * rng.normal(size=(T, N, R))
|
|
||||||
out = probe(reps, lab, [False] * T, R, n_null=3)
|
|
||||||
assert out["acc_entity"] > 0.9 > out["chance_shift_max"]
|
|
||||||
assert np.isnan(out["acc_step"]) and np.isnan(out["latency"])
|
|
||||||
|
|
||||||
|
|
||||||
def test_persistence_separates_a_slow_state_from_white_noise():
|
|
||||||
from frozen import persistence
|
|
||||||
rng = np.random.default_rng(2)
|
|
||||||
T, N, D = 2000, 4, 5
|
|
||||||
white = rng.normal(size=(T, N, D))
|
|
||||||
slow = np.zeros_like(white)
|
|
||||||
for t in range(1, T):
|
|
||||||
slow[t] = 0.95 * slow[t - 1] + white[t]
|
|
||||||
assert persistence(white)["lag1"] < 0.1 < persistence(slow)["lag1"]
|
|
||||||
assert persistence(slow)["tau"] > 10 >= persistence(white)["tau"]
|
|
||||||
|
|
||||||
|
|
||||||
def test_ablate_state_keeps_the_parameters_and_drops_only_the_state():
|
|
||||||
"""The capacity control: the GRP keeps all 5602 parameters but carries nothing
|
|
||||||
between steps, so M becomes a fixed function of h."""
|
|
||||||
full = run_one("grp_k0", seed=0, train_steps=200, frozen_steps=100, probes=False)
|
|
||||||
none = run_one("grp_k0", seed=0, train_steps=200, frozen_steps=100, probes=False, stateless=True)
|
|
||||||
assert none["condition"] == "grp_k0_nostate"
|
|
||||||
assert none["n_params"] == full["n_params"] > run_one(
|
|
||||||
"rp_only", seed=0, train_steps=200, frozen_steps=100, probes=False)["n_params"]
|
|
||||||
assert none["dM_min"] == 0.0 or none["frozen"]["steady"] != full["frozen"]["steady"]
|
|
||||||
assert none["frozen_bit_identical"]
|
|
||||||
@@ -1,81 +0,0 @@
|
|||||||
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
|
|
||||||
@@ -1,81 +0,0 @@
|
|||||||
"""The withheld psi region is the experiment, and a leak would be silent as usual.
|
|
||||||
|
|
||||||
Plus the property that makes the experiment non-vacuous: the teacher's kernel must change SHAPE
|
|
||||||
with psi, not gain. A psi that only scaled the kernel would be satisfiable by any model with a
|
|
||||||
gain on its output, and every arm would pass for the wrong reason.
|
|
||||||
"""
|
|
||||||
import torch
|
|
||||||
|
|
||||||
import psi as P
|
|
||||||
|
|
||||||
|
|
||||||
def test_training_psi_never_lands_in_the_held_box():
|
|
||||||
gen = torch.Generator().manual_seed(0)
|
|
||||||
for *_, p in P.batch(False, gen, size=256):
|
|
||||||
assert not P.in_held(p)
|
|
||||||
|
|
||||||
|
|
||||||
def test_eval_psi_is_always_inside_the_held_box():
|
|
||||||
gen = torch.Generator().manual_seed(1)
|
|
||||||
for *_, p in P.batch(True, gen, size=128):
|
|
||||||
assert P.in_held(p)
|
|
||||||
|
|
||||||
|
|
||||||
def test_teacher_kernel_changes_shape_with_psi_not_only_gain():
|
|
||||||
# The same check the library makes for the CPPN's context input, applied to the teacher:
|
|
||||||
# if psi were a gain the ratio between two kernels would be constant.
|
|
||||||
tea = P.PsiTeacher(0)
|
|
||||||
a = tea.kernel(torch.tensor([-0.8, 0.0]))
|
|
||||||
b = tea.kernel(torch.tensor([0.8, 0.0]))
|
|
||||||
assert (b / (a + 1e-9)).std() > 1e-2
|
|
||||||
c = tea.kernel(torch.tensor([0.0, -0.9]))
|
|
||||||
d = tea.kernel(torch.tensor([0.0, 0.9]))
|
|
||||||
assert (d / (c + 1e-9)).std() > 1e-2 # arousal too, not just valence
|
|
||||||
|
|
||||||
|
|
||||||
def test_bins_partition_psi_and_the_box_aligns_at_b4():
|
|
||||||
t4 = P.BinnedTable(4)
|
|
||||||
lo, hi = P.HELD
|
|
||||||
inside = {t4.bin_of(torch.tensor([x, y]))
|
|
||||||
for x in (lo + 0.01, hi - 0.01) for y in (lo + 0.01, hi - 0.01)}
|
|
||||||
assert len(inside) == 1 # the held box is exactly one bin at B=4
|
|
||||||
outside = t4.bin_of(torch.tensor([-0.9, -0.9]))
|
|
||||||
assert outside not in inside
|
|
||||||
|
|
||||||
|
|
||||||
def test_table_1_ignores_psi_entirely():
|
|
||||||
# The floor arm: it must be unable to represent any psi dependence, or it is not a floor.
|
|
||||||
t = P.BinnedTable(1)
|
|
||||||
r = torch.randint(-3, 4, (3, 3, 2)).float()
|
|
||||||
a = t(r, None, torch.tensor([-0.9, -0.9]))
|
|
||||||
b = t(r, None, torch.tensor([0.9, 0.9]))
|
|
||||||
assert torch.equal(a, b)
|
|
||||||
|
|
||||||
|
|
||||||
def test_untrained_bins_are_exactly_the_ones_inside_the_box():
|
|
||||||
# At B=4 the withheld box is exactly one bin; at B=2 it is half of one, so nothing is
|
|
||||||
# wholly untrained and there is nothing for the control to fill. If this drifted, the
|
|
||||||
# interp arm would quietly be filling bins that had data.
|
|
||||||
assert int(P.untrained_bins(4).sum()) == 1
|
|
||||||
assert int(P.untrained_bins(8).sum()) == 4
|
|
||||||
assert int(P.untrained_bins(2).sum()) == 0
|
|
||||||
assert int(P.untrained_bins(1).sum()) == 0
|
|
||||||
|
|
||||||
|
|
||||||
def test_diffusion_fills_held_bins_only_from_trained_ones():
|
|
||||||
# Trained bins all hold 1, untrained hold 0: after filling, every bin must be 1. A 0 left
|
|
||||||
# anywhere means an untrained bin was used as a source.
|
|
||||||
t = P.BinnedTable(4)
|
|
||||||
held = P.untrained_bins(4)
|
|
||||||
t.w.data.fill_(1.0)
|
|
||||||
t.w.data[held] = 0.0
|
|
||||||
P.fill_bins_by_diffusion(t, held)
|
|
||||||
assert torch.allclose(t.w.data, torch.ones_like(t.w.data), atol=1e-6)
|
|
||||||
|
|
||||||
|
|
||||||
def test_diffusion_leaves_trained_bins_untouched():
|
|
||||||
t = P.BinnedTable(4)
|
|
||||||
held = P.untrained_bins(4)
|
|
||||||
before = t.w.data.clone()
|
|
||||||
P.fill_bins_by_diffusion(t, held)
|
|
||||||
assert torch.equal(t.w.data[~held], before[~held])
|
|
||||||
@@ -1,84 +0,0 @@
|
|||||||
import math
|
|
||||||
|
|
||||||
import pytest
|
|
||||||
|
|
||||||
from regime import CONDITIONS, _metrics, run
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize("name", sorted(CONDITIONS))
|
|
||||||
def test_every_condition_runs(name):
|
|
||||||
res = run(name, seed=0, steps=300, window=5, bptt=10)
|
|
||||||
assert len(res["recovery"]) == 5
|
|
||||||
assert res["steady"] >= 0.0
|
|
||||||
assert res["n_switches"] >= 1
|
|
||||||
|
|
||||||
|
|
||||||
def test_rp_only_has_no_memory_and_zero_kappa():
|
|
||||||
assert CONDITIONS["rp_only"]["memory"] is False
|
|
||||||
assert CONDITIONS["grp_k0"]["kappa"] == 0.0
|
|
||||||
assert CONDITIONS["grp_flag"]["kappa"] == 0.0 and CONDITIONS["grp_flag"]["oracle"] == "change"
|
|
||||||
assert CONDITIONS["grp_regime"]["kappa"] == 0.0 and CONDITIONS["grp_regime"]["oracle"] == "regime"
|
|
||||||
|
|
||||||
|
|
||||||
def test_window_too_large_raises():
|
|
||||||
with pytest.raises(ValueError):
|
|
||||||
run("grp_k0", seed=0, steps=100, window=100)
|
|
||||||
|
|
||||||
|
|
||||||
def test_metrics_recovery_is_mean_loss_k_steps_after_switch():
|
|
||||||
# steps=20, half=10: a single switch at index 12 sits inside the measured
|
|
||||||
# second half. losses[i] = i, so recovery[k] = 12 + k exactly.
|
|
||||||
steps, window = 20, 3
|
|
||||||
losses = [float(i) for i in range(steps)]
|
|
||||||
switched = [False] * steps
|
|
||||||
switched[12] = True
|
|
||||||
arousals = [i * 0.01 for i in range(steps)]
|
|
||||||
m = _metrics(losses, switched, arousals, window)
|
|
||||||
assert m["recovery"] == [12.0, 13.0, 14.0]
|
|
||||||
assert m["n_switches"] == 1
|
|
||||||
assert m["arousal_at_switch"] == pytest.approx(0.12)
|
|
||||||
|
|
||||||
|
|
||||||
def test_metrics_ignores_switches_in_the_first_half():
|
|
||||||
steps, window = 20, 3
|
|
||||||
losses = [float(i) for i in range(steps)]
|
|
||||||
switched = [False] * steps
|
|
||||||
switched[12] = True
|
|
||||||
arousals = [i * 0.01 for i in range(steps)]
|
|
||||||
baseline = _metrics(losses, switched, arousals, window)
|
|
||||||
|
|
||||||
# a first-half switch with wildly different loss/arousal must not move any metric:
|
|
||||||
# half=10 and window=3 mean the earliest measured lookback starts at 10-3=7, so
|
|
||||||
# index 3 never enters any window computation.
|
|
||||||
losses2 = list(losses); losses2[3] = 999999.0
|
|
||||||
switched2 = list(switched); switched2[3] = True
|
|
||||||
arousals2 = list(arousals); arousals2[3] = 999.0
|
|
||||||
perturbed = _metrics(losses2, switched2, arousals2, window)
|
|
||||||
assert perturbed == baseline
|
|
||||||
|
|
||||||
|
|
||||||
def test_metrics_steady_excludes_window_steps_after_a_switch():
|
|
||||||
# steps=20, half=10, window=3: switch at 15 excludes i in [15, 15+window] = [15,18]
|
|
||||||
# from steady. If that exclusion didn't apply, the huge post-switch losses at
|
|
||||||
# 16-18 would pull steady far from 1.0.
|
|
||||||
steps, window = 20, 3
|
|
||||||
losses = [1.0] * steps
|
|
||||||
for i in (15, 16, 17, 18):
|
|
||||||
losses[i] = 999.0
|
|
||||||
switched = [False] * steps
|
|
||||||
switched[15] = True
|
|
||||||
arousals = [0.0] * steps
|
|
||||||
m = _metrics(losses, switched, arousals, window)
|
|
||||||
assert m["steady"] == pytest.approx(1.0)
|
|
||||||
|
|
||||||
|
|
||||||
def test_metrics_no_switch_in_range_gives_nan_recovery():
|
|
||||||
steps, window = 20, 3
|
|
||||||
losses = [1.0] * steps
|
|
||||||
switched = [False] * steps
|
|
||||||
arousals = [0.0] * steps
|
|
||||||
m = _metrics(losses, switched, arousals, window)
|
|
||||||
assert m["n_switches"] == 0
|
|
||||||
assert all(math.isnan(x) for x in m["recovery"])
|
|
||||||
assert math.isnan(m["arousal_at_switch"])
|
|
||||||
assert m["steady"] == pytest.approx(1.0)
|
|
||||||
@@ -1,44 +0,0 @@
|
|||||||
"""The training range is the experiment. If an unseen N appears in training, nothing complains.
|
|
||||||
|
|
||||||
Same silent-failure shape as the held-out cells in test_unseen: every arm still trains and every
|
|
||||||
number still prints, and `unseen N` quietly becomes `seen N`.
|
|
||||||
"""
|
|
||||||
import torch
|
|
||||||
|
|
||||||
import scale
|
|
||||||
|
|
||||||
|
|
||||||
def test_training_never_sees_an_n_outside_its_range():
|
|
||||||
gen = torch.Generator().manual_seed(0)
|
|
||||||
for lo, hi in ((2, 16), (17, 32)):
|
|
||||||
ns = {a.shape[0] for a, _, _ in scale.mixed_batch(lo, hi, gen, size=200)}
|
|
||||||
assert ns and min(ns) >= lo and max(ns) <= hi
|
|
||||||
|
|
||||||
|
|
||||||
def test_training_range_actually_varies_n():
|
|
||||||
# A range that collapsed to a single N would make the whole axis meaningless while still
|
|
||||||
# satisfying the bounds check above.
|
|
||||||
gen = torch.Generator().manual_seed(1)
|
|
||||||
ns = {a.shape[0] for a, _, _ in scale.mixed_batch(2, 16, gen, size=200)}
|
|
||||||
assert len(ns) > 8
|
|
||||||
|
|
||||||
|
|
||||||
def test_one_parameter_set_evaluates_at_every_n():
|
|
||||||
# The property under test: the same object, unchanged, runs at any entity count.
|
|
||||||
model = scale.make_model("rp", 0, 1.0)
|
|
||||||
before = [p.clone() for p in model.parameters()]
|
|
||||||
gen = torch.Generator().manual_seed(2)
|
|
||||||
for n in (2, 7, 16, 25, 32):
|
|
||||||
for a, r, m in scale.configs(n, 1, gen):
|
|
||||||
assert scale.run_model(model, a, r, m).shape == (n, scale.D)
|
|
||||||
assert all(torch.equal(x, y) for x, y in zip(before, model.parameters()))
|
|
||||||
|
|
||||||
|
|
||||||
def test_floor_shrinks_as_n_grows():
|
|
||||||
# The measurement note in scale.py depends on this being true, so it is checked rather
|
|
||||||
# than asserted in prose: pooling more neighbours lowers the target's variance, which is
|
|
||||||
# why the mse/floor ratio must not be read as a trend down the N axis.
|
|
||||||
tea = scale.teacher(0)
|
|
||||||
gen = torch.Generator().manual_seed(3)
|
|
||||||
floors = [scale.evaluate(tea, tea, scale.configs(n, 32, gen))[1] for n in (2, 8, 32)]
|
|
||||||
assert floors[0] > floors[1] > floors[2]
|
|
||||||
@@ -1,193 +0,0 @@
|
|||||||
"""The held-out cells are the experiment. If one leaks into training, the result is decorative.
|
|
||||||
|
|
||||||
That leak is silent: every arm still trains, every number still prints, and `unseen` quietly
|
|
||||||
becomes `seen`. So it gets the test, and the test was checked against a broken mask.
|
|
||||||
"""
|
|
||||||
import pytest
|
|
||||||
import torch
|
|
||||||
|
|
||||||
import unseen
|
|
||||||
|
|
||||||
|
|
||||||
def _held(kind="random", frac=0.25, seed=0):
|
|
||||||
return unseen.holdout_cells(kind, frac, seed)
|
|
||||||
|
|
||||||
|
|
||||||
def test_training_masks_out_every_held_cell():
|
|
||||||
held = _held()
|
|
||||||
gen = torch.Generator().manual_seed(0)
|
|
||||||
for _a, r, mask in unseen.train_batch(held, gen, size=64):
|
|
||||||
assert not held[unseen.cell_of(r)][mask.bool()].any() # nothing held survives
|
|
||||||
assert (mask.bool() | held[unseen.cell_of(r)]).all() # nothing seen was dropped
|
|
||||||
|
|
||||||
|
|
||||||
def test_a_masked_pair_cannot_move_the_output():
|
|
||||||
# The mask is only meaningful if it actually severs the message. Perturb a masked
|
|
||||||
# neighbour's attributes and the receiver must not notice.
|
|
||||||
held = _held()
|
|
||||||
model = unseen.make_model("rp", 0)
|
|
||||||
gen = torch.Generator().manual_seed(3)
|
|
||||||
for a, r, mask in unseen.train_batch(held, gen, size=40):
|
|
||||||
if mask.min() == 1:
|
|
||||||
continue
|
|
||||||
i, j = (mask == 0).nonzero()[0].tolist()
|
|
||||||
a2 = a.clone(); a2[j] += 7.0
|
|
||||||
y0 = unseen.run_model(model, a, r, mask)
|
|
||||||
y1 = unseen.run_model(model, a2, r, mask)
|
|
||||||
assert torch.allclose(y0[i], y1[i], atol=1e-6)
|
|
||||||
return
|
|
||||||
raise AssertionError("no masked pair was generated")
|
|
||||||
|
|
||||||
|
|
||||||
def test_eval_pairs_are_wholly_seen_or_wholly_held():
|
|
||||||
held = _held()
|
|
||||||
gen = torch.Generator().manual_seed(1)
|
|
||||||
off = ~torch.eye(2, dtype=torch.bool)
|
|
||||||
for _a, r, _m in unseen.pair_batch(held, True, gen, size=32):
|
|
||||||
assert held[unseen.cell_of(r)][off].all()
|
|
||||||
for _a, r, _m in unseen.pair_batch(held, False, gen, size=32):
|
|
||||||
assert not held[unseen.cell_of(r)][off].any()
|
|
||||||
|
|
||||||
|
|
||||||
def test_centre_cell_is_never_held():
|
|
||||||
# r = 0 is every entity's message to itself, so it appears in every configuration. Holding
|
|
||||||
# it out would mask a pathway that has nothing to do with the relation under test.
|
|
||||||
centre = unseen.R * unseen.G + unseen.R
|
|
||||||
for kind in ("random", "band"):
|
|
||||||
for seed in range(4):
|
|
||||||
assert not _held(kind, 0.25, seed)[centre]
|
|
||||||
|
|
||||||
|
|
||||||
def test_both_holdouts_withhold_a_real_fraction():
|
|
||||||
for kind in ("random", "band"):
|
|
||||||
n = int(_held(kind, 0.25, 0).sum())
|
|
||||||
assert 0.15 * unseen.CELLS < n < 0.35 * unseen.CELLS
|
|
||||||
|
|
||||||
|
|
||||||
def test_table_kernel_matches_cppn_call_signature():
|
|
||||||
# The table arm is swapped into RelationalPerceptron in place, so a signature drift would
|
|
||||||
# show up as a confusing shape error inside the RP rather than here.
|
|
||||||
k = unseen.TableKernel()
|
|
||||||
r = torch.randint(-3, 4, (4, 4, 2)).float()
|
|
||||||
assert k(r, torch.ones(4, 4, 1), torch.zeros(2)).shape == (4, 4, unseen.D)
|
|
||||||
|
|
||||||
|
|
||||||
def test_diffusion_fills_only_from_trained_cells():
|
|
||||||
# The control is only a control if the filled values come from cells that actually saw
|
|
||||||
# gradient. Trained cells all hold 1, held cells hold 0 (their "init"): after filling,
|
|
||||||
# every held cell must be 1 -- a 0 anywhere means an untrained entry was used as a source.
|
|
||||||
held = _held()
|
|
||||||
w = torch.ones(unseen.CELLS, unseen.D)
|
|
||||||
w[held] = 0.0
|
|
||||||
unseen.fill_by_diffusion(w, held)
|
|
||||||
assert torch.allclose(w, torch.ones_like(w), atol=1e-6)
|
|
||||||
|
|
||||||
|
|
||||||
def test_diffusion_reaches_every_held_cell_in_both_holdouts():
|
|
||||||
for kind in ("random", "band"):
|
|
||||||
held = _held(kind)
|
|
||||||
w = torch.zeros(unseen.CELLS, unseen.D)
|
|
||||||
w[~held] = 1.0
|
|
||||||
unseen.fill_by_diffusion(w, held)
|
|
||||||
assert (w[held] > 0).all() # no held cell was left stranded at its init
|
|
||||||
|
|
||||||
|
|
||||||
def _support(kind, frac=0.25, seed=0):
|
|
||||||
W = unseen.gabor_kernel(seed=seed, kind=kind)
|
|
||||||
return unseen.holdout_cells("support", frac, seed, W), W
|
|
||||||
|
|
||||||
|
|
||||||
def test_support_holdout_is_closed_under_negation():
|
|
||||||
# A pair contributes r and -r. An asymmetric hold-out would leave pair_batch with nothing
|
|
||||||
# to evaluate and it would spin forever rather than fail.
|
|
||||||
for kind in ("smooth", "knight", "highfreq"):
|
|
||||||
held, _ = _support(kind)
|
|
||||||
for c in held.nonzero().flatten().tolist():
|
|
||||||
dy, dx = divmod(c, unseen.G)
|
|
||||||
assert held[(2 * unseen.R - dy) * unseen.G + (2 * unseen.R - dx)]
|
|
||||||
|
|
||||||
|
|
||||||
def test_support_holdout_only_withholds_cells_that_carry_signal():
|
|
||||||
# The whole reason this hold-out exists: withholding a zero cell of the knight kernel asks
|
|
||||||
# nothing, the floor collapses, and the arms tie at a number that means nothing.
|
|
||||||
for kind in ("smooth", "knight"):
|
|
||||||
held, W = _support(kind)
|
|
||||||
mag = W.abs().mean(1)
|
|
||||||
assert (mag[held] > 0.2 * mag.max()).all()
|
|
||||||
|
|
||||||
|
|
||||||
def test_knight_kernel_lives_on_exactly_the_eight_l_squares():
|
|
||||||
W = unseen.gabor_kernel(kind="knight", seed=0)
|
|
||||||
live = (W.abs().mean(1) > 0).nonzero().flatten().tolist()
|
|
||||||
expect = {(dy + unseen.R) * unseen.G + (dx + unseen.R) for dx, dy in unseen.KNIGHT}
|
|
||||||
assert set(live) == expect and len(expect) == 8
|
|
||||||
|
|
||||||
|
|
||||||
def test_noise_teacher_has_no_neighbour_structure():
|
|
||||||
# The negative control is only a control if it really is unpredictable from neighbours:
|
|
||||||
# correlation between a cell and its right-hand neighbour should be near zero, where the
|
|
||||||
# smooth teacher's is high.
|
|
||||||
def neighbour_corr(kind):
|
|
||||||
W = unseen.gabor_kernel(seed=0, kind=kind).view(unseen.G, unseen.G, -1)
|
|
||||||
a, b = W[:, :-1].flatten(), W[:, 1:].flatten()
|
|
||||||
return abs(float(torch.corrcoef(torch.stack([a, b]))[0, 1]))
|
|
||||||
assert neighbour_corr("smooth") > 0.8
|
|
||||||
assert neighbour_corr("noise") < 0.2
|
|
||||||
|
|
||||||
|
|
||||||
def test_every_arm_name_actually_changes_the_kernel():
|
|
||||||
# This test exists because an edit silently failed to land and rp_inv ran as plain rp,
|
|
||||||
# producing two identical columns that could have been read as "invariants change nothing".
|
|
||||||
kinds = {arm: type(unseen.make_model(arm, 0)["rp"].cppn).__name__
|
|
||||||
for arm in ("rp", "rp_inv", "table", "table_interp")}
|
|
||||||
assert kinds["rp"] == "AffectiveCPPN"
|
|
||||||
assert kinds["rp_inv"] == "InvariantCPPN"
|
|
||||||
assert kinds["table"] == kinds["table_interp"] == "TableKernel"
|
|
||||||
with pytest.raises(ValueError):
|
|
||||||
unseen.make_model("rp_typo_arm_that_does_not_exist", 0)
|
|
||||||
|
|
||||||
|
|
||||||
def test_invariant_cppn_gives_one_answer_for_the_whole_d4_orbit():
|
|
||||||
# The mechanism under test: the eight knight offsets must reach the CPPN as one input.
|
|
||||||
m = unseen.make_model("rp_inv", 0)
|
|
||||||
edge, ctx = torch.ones(1, 1, 1), torch.zeros(2)
|
|
||||||
outs = [m["rp"].cppn(torch.tensor([[[float(dx), float(dy)]]]), edge, ctx)
|
|
||||||
for dx, dy in unseen.KNIGHT]
|
|
||||||
for o in outs[1:]:
|
|
||||||
assert torch.allclose(outs[0], o, atol=1e-6)
|
|
||||||
other = m["rp"].cppn(torch.tensor([[[3.0, 1.0]]]), edge, ctx) # not in the orbit
|
|
||||||
assert not torch.allclose(outs[0], other)
|
|
||||||
|
|
||||||
|
|
||||||
def test_knight_sym_is_one_orbit_and_knight_is_not():
|
|
||||||
cells = [(dy + unseen.R) * unseen.G + (dx + unseen.R) for dx, dy in unseen.KNIGHT]
|
|
||||||
sym = unseen.gabor_kernel(kind="knight_sym", seed=0)[cells]
|
|
||||||
asym = unseen.gabor_kernel(kind="knight", seed=0)[cells]
|
|
||||||
assert (sym.std(0) == 0).all() # same value on all eight squares, per channel
|
|
||||||
assert (asym.std(0) > 0).any() # the control shares support but not a rule
|
|
||||||
|
|
||||||
|
|
||||||
def test_orbit_consistency_reads_zero_for_a_kernel_that_is_invariant_by_construction():
|
|
||||||
# Validates the metric itself against the one kernel whose answer is known exactly.
|
|
||||||
inv = unseen.make_model("rp_inv", 0)["rp"].cppn
|
|
||||||
raw = unseen.make_model("rp", 0)["rp"].cppn
|
|
||||||
assert unseen.orbit_consistency(inv) < 1e-6
|
|
||||||
assert unseen.orbit_consistency(raw) > 0.1
|
|
||||||
|
|
||||||
|
|
||||||
def test_learned_frame_starts_spread_and_can_collapse():
|
|
||||||
# The null hypothesis for the learned arm is that the maps collapse to one, making it K=1
|
|
||||||
# with more compute. They start apart, and a deliberate collapse must read as one.
|
|
||||||
k = unseen.make_model("rp_learn_4", 0)["rp"].cppn
|
|
||||||
assert unseen.frame_spread(k) > 0.1
|
|
||||||
with torch.no_grad():
|
|
||||||
k.T.copy_(k.T[0].expand_as(k.T))
|
|
||||||
assert unseen.frame_spread(k) < 1e-6
|
|
||||||
|
|
||||||
|
|
||||||
def test_learned_frame_averages_over_its_maps():
|
|
||||||
k = unseen.make_model("rp_learn_2", 0)["rp"].cppn
|
|
||||||
r = torch.randint(-3, 4, (4, 4, 2)).float()
|
|
||||||
edge, ctx = torch.ones(4, 4, 1), torch.zeros(2)
|
|
||||||
manual = torch.stack([k.cppn(r @ t.T, edge, ctx) for t in k.T]).mean(0)
|
|
||||||
assert torch.allclose(k(r, edge, ctx), manual, atol=1e-6)
|
|
||||||
@@ -1,225 +0,0 @@
|
|||||||
"""Task 9. Each test here defends one property a headline number rests on.
|
|
||||||
|
|
||||||
AGENTS.md: a test that cannot fail is worse than no test. Every test below that
|
|
||||||
defends a central property has a companion that breaks the property on purpose and
|
|
||||||
asserts the guard fires -- named `..._can_fail` or written as a `pytest.raises`
|
|
||||||
inside the test itself.
|
|
||||||
"""
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import numpy as np
|
|
||||||
import pytest
|
|
||||||
import torch
|
|
||||||
|
|
||||||
import identify
|
|
||||||
import when_memory_works as wmw
|
|
||||||
from ailed import AffectConfig
|
|
||||||
from frozen import _build, _train
|
|
||||||
from particles import ParticleConfig
|
|
||||||
from regime import _metrics
|
|
||||||
|
|
||||||
|
|
||||||
# -- Part 1: the arousal profile is the arousal the gate actually saw --------------
|
|
||||||
|
|
||||||
def _run_with_gate_trace(steps=300):
|
|
||||||
from a1 import GateTrace
|
|
||||||
spec, wcfg, world, org = _build("grp_k", seed=0, hidden=32, omega=10.0, kappa=4.0)
|
|
||||||
tr = GateTrace(org)
|
|
||||||
_, _, out = _train(spec, wcfg, world, org, steps, bptt=20, lr=1e-3, on_step=tr)
|
|
||||||
return np.asarray(tr.a_gate, dtype=float), out
|
|
||||||
|
|
||||||
|
|
||||||
def test_gate_arousal_seq_is_the_arousal_the_organism_was_handed():
|
|
||||||
"""`_train` records affect *after* the update, so the gate's input is lagged by one.
|
|
||||||
|
|
||||||
`a1.GateTrace` records the value the organism was actually passed. If these two
|
|
||||||
disagree, every arousal-vs-lag profile in Part 1 is off by a step and the
|
|
||||||
pre-registered "within 3 steps" criterion is being judged against the wrong curve.
|
|
||||||
"""
|
|
||||||
seen, out = _run_with_gate_trace()
|
|
||||||
assert np.array_equal(wmw.gate_arousal_seq(out["arousals"]), seen)
|
|
||||||
|
|
||||||
|
|
||||||
def test_gate_arousal_seq_can_fail():
|
|
||||||
"""Break it on purpose: the un-lagged sequence must NOT match."""
|
|
||||||
seen, out = _run_with_gate_trace()
|
|
||||||
assert not np.array_equal(np.asarray(out["arousals"], dtype=float), seen)
|
|
||||||
|
|
||||||
|
|
||||||
def test_affect_config_is_passed_through_and_changes_the_arousal_stream():
|
|
||||||
"""`--part timing` is only a sweep if the config reaches the loop. Two settings,
|
|
||||||
same seed, must produce different arousal; the default must reproduce the default."""
|
|
||||||
args = ("grp_k0", 0, 0.0)
|
|
||||||
kw = dict(steps=300, windows=(20,))
|
|
||||||
base = wmw.run_one(*args, AffectConfig(), **kw)
|
|
||||||
same = wmw.run_one(*args, wmw._cfg(0.5, 0.02, 0.2), **kw)
|
|
||||||
other = wmw.run_one(*args, wmw._cfg(1.0, 0.4), **kw)
|
|
||||||
assert base["arousal"]["20"]["far"] == same["arousal"]["20"]["far"]
|
|
||||||
assert base["arousal"]["20"]["far"] != other["arousal"]["20"]["far"]
|
|
||||||
|
|
||||||
|
|
||||||
def test_cfg_keeps_the_slow_baseline_slower_than_the_fast_one():
|
|
||||||
for ra in wmw.RHO_A:
|
|
||||||
for rs in wmw.RHO_SLOW:
|
|
||||||
c = wmw._cfg(ra, rs)
|
|
||||||
assert c.rho_slow < c.rho_fast, (ra, rs)
|
|
||||||
|
|
||||||
|
|
||||||
def test_peak_lag_and_by_lag_average_over_the_switches_metrics_uses():
|
|
||||||
"""`by_lag` must cut the trace exactly as `_metrics` cuts `recovery`."""
|
|
||||||
steps, window = 400, 20
|
|
||||||
rng = np.random.default_rng(0)
|
|
||||||
losses = list(rng.random(steps))
|
|
||||||
switched = [i % 57 == 0 for i in range(steps)]
|
|
||||||
got = wmw.by_lag(np.asarray(losses), switched, steps, window)
|
|
||||||
assert got == pytest.approx(_metrics(losses, switched, [0.0] * steps, window)["recovery"])
|
|
||||||
|
|
||||||
|
|
||||||
# -- Part 2: the decoder is causal, and the basis is the world's -------------------
|
|
||||||
|
|
||||||
def test_features_never_use_the_displacement_being_decoded():
|
|
||||||
"""The window at step t may use d_{t-L+1..t-1} and never d_t.
|
|
||||||
|
|
||||||
This is the property that makes T_id a statement about an observer rather than
|
|
||||||
about a decoder handed the answer. Corrupting d_t alone must leave the features
|
|
||||||
for step t untouched -- and must change the features for step t+1, or the test
|
|
||||||
would pass on a decoder that ignores displacements altogether.
|
|
||||||
"""
|
|
||||||
world = identify.rollout(ParticleConfig(seed=0), 120)
|
|
||||||
for kind in ("raw", "phys"):
|
|
||||||
X, y, ts = identify.features(world, L=5, kind=kind)
|
|
||||||
hit = 40
|
|
||||||
t = ts[hit]
|
|
||||||
poisoned = dict(world, disp=world["disp"].clone())
|
|
||||||
poisoned["disp"][t] += 1.0
|
|
||||||
Xp, _, _ = identify.features(poisoned, L=5, kind=kind)
|
|
||||||
assert np.array_equal(X[hit], Xp[hit]), f"{kind} leaked d_t"
|
|
||||||
assert not np.array_equal(X[hit + 1], Xp[hit + 1]), f"{kind} ignores displacements"
|
|
||||||
|
|
||||||
|
|
||||||
def test_basis_reproduces_the_worlds_dynamics_to_the_noise_floor():
|
|
||||||
world = identify.rollout(ParticleConfig(seed=1), 300)
|
|
||||||
resid = identify._check_basis(world)
|
|
||||||
assert resid == pytest.approx(ParticleConfig().noise ** 2, rel=0.03)
|
|
||||||
|
|
||||||
|
|
||||||
def test_basis_check_can_fail():
|
|
||||||
"""Hand `_check_basis` the wrong regime sequence: the residual must blow past noise."""
|
|
||||||
world = identify.rollout(ParticleConfig(seed=1), 300)
|
|
||||||
wrong = dict(world, regimes=(world["regimes"] + 1) % 4)
|
|
||||||
with pytest.raises(AssertionError):
|
|
||||||
identify._check_basis(wrong)
|
|
||||||
|
|
||||||
|
|
||||||
def test_bayes_decoder_recovers_a_regime_it_can_see_and_not_one_it_cannot():
|
|
||||||
"""Planted signal and planted absence, the shape `test_frozen.py` uses for its probe.
|
|
||||||
|
|
||||||
With the real displacements the exact decoder must be far above chance at L=2.
|
|
||||||
With the displacements replaced by noise there is nothing to decode and it must
|
|
||||||
fall to chance, which is what says the accuracy comes from the dynamics.
|
|
||||||
"""
|
|
||||||
world = identify.rollout(ParticleConfig(seed=0), 1200)
|
|
||||||
assert identify.bayes(world, L=2)["acc_step"] > 0.8
|
|
||||||
blind = dict(world, disp=torch.randn_like(world["disp"]) * 1e-3)
|
|
||||||
assert identify.bayes(blind, L=2)["acc_step"] < 0.45
|
|
||||||
|
|
||||||
|
|
||||||
def test_decode_is_at_chance_when_the_labels_carry_no_signal():
|
|
||||||
world = identify.rollout(ParticleConfig(seed=0), 900)
|
|
||||||
X, y, _ = identify.features(world, L=3, kind="phys")
|
|
||||||
real = identify.decode(X, y, 4, "logit", n_null=2, seed=0)
|
|
||||||
shuffled = identify.decode(X, np.random.default_rng(0).permutation(y), 4, "logit",
|
|
||||||
n_null=2, seed=0)
|
|
||||||
assert real["acc_step"] > 0.7
|
|
||||||
assert shuffled["acc_step"] < 0.45
|
|
||||||
|
|
||||||
|
|
||||||
def test_decode_test_split_is_a_suffix_in_time():
|
|
||||||
world = identify.rollout(ParticleConfig(seed=0), 600)
|
|
||||||
X, y, _ = identify.features(world, L=2, kind="phys")
|
|
||||||
poisoned = X.copy()
|
|
||||||
cut = int(len(X) * identify.SPLIT)
|
|
||||||
poisoned[:cut] = 0.0 # destroying only the train prefix must hurt
|
|
||||||
a = identify.decode(X, y, 4, "logit", n_null=1, seed=0)["acc_step"]
|
|
||||||
b = identify.decode(poisoned, y, 4, "logit", n_null=1, seed=0)["acc_step"]
|
|
||||||
assert b < a
|
|
||||||
|
|
||||||
|
|
||||||
def test_switch_fraction_counts_windows_that_span_a_change():
|
|
||||||
world = identify.rollout(ParticleConfig(seed=0, t_min=40, t_max=80), 800)
|
|
||||||
assert identify.switch_fraction(world, 1) == 0.0
|
|
||||||
assert identify.switch_fraction(world, 2) < identify.switch_fraction(world, 40)
|
|
||||||
|
|
||||||
|
|
||||||
# -- Part 3: the comparison stays capacity-controlled ------------------------------
|
|
||||||
|
|
||||||
def test_state_ablation_changes_only_whether_memory_is_carried():
|
|
||||||
"""Both arms of Part 3 must have the same architecture and the same parameter count.
|
|
||||||
|
|
||||||
`results/frozen.md` §5: a `grp_k0` vs `rp_only` number is confounded 3.9x. The
|
|
||||||
number Part 3 reports is `grp_k0_nostate / grp_k0`, and this is what makes it a
|
|
||||||
state measurement rather than a capacity measurement.
|
|
||||||
"""
|
|
||||||
kw = dict(steps=200, windows=(20,))
|
|
||||||
a = wmw.run_one("grp_k0", 0, 0.0, AffectConfig(), stateless=False, **kw)
|
|
||||||
b = wmw.run_one("grp_k0", 0, 0.0, AffectConfig(), stateless=True, **kw)
|
|
||||||
assert a["n_params"] == b["n_params"] == 5602
|
|
||||||
assert a["metrics"]["20"]["steady"] != b["metrics"]["20"]["steady"]
|
|
||||||
|
|
||||||
|
|
||||||
def test_duration_override_reaches_the_world_and_leaves_the_default_alone():
|
|
||||||
_, wcfg, world, _ = _build("grp_k0", 0, 32, 10.0, 0.0, t_min=10, t_max=20)
|
|
||||||
assert (wcfg.t_min, wcfg.t_max) == (10, 20)
|
|
||||||
assert 10 <= world.until <= 20
|
|
||||||
_, default, _, _ = _build("grp_k0", 0, 32, 10.0, 0.0)
|
|
||||||
assert (default.t_min, default.t_max) == (40, 80)
|
|
||||||
assert (ParticleConfig().t_min, ParticleConfig().t_max) == (40, 80)
|
|
||||||
|
|
||||||
|
|
||||||
def test_shorter_regimes_really_do_switch_more_often():
|
|
||||||
kw = dict(steps=1000, windows=(3,), kappa=0.0)
|
|
||||||
fast = wmw.run_one("grp_k0", 0, acfg=AffectConfig(), t_min=10, t_max=20, **kw)
|
|
||||||
slow = wmw.run_one("grp_k0", 0, acfg=AffectConfig(), t_min=150, t_max=300, **kw)
|
|
||||||
frozen = wmw.run_one("grp_k0", 0, acfg=AffectConfig(), t_min=99999, t_max=99999, **kw)
|
|
||||||
assert fast["metrics"]["3"]["n_switches"] > slow["metrics"]["3"]["n_switches"] > 0
|
|
||||||
assert frozen["metrics"]["3"]["n_switches"] == 0
|
|
||||||
|
|
||||||
|
|
||||||
def test_windows_that_reach_the_next_switch_are_not_reported():
|
|
||||||
"""`regime.run` refuses window >= t_min. Part 3 has to shorten the regime, so the
|
|
||||||
same rule is enforced per window: a duration of 10-20 may not report window 20."""
|
|
||||||
r = wmw.run_one("grp_k0", 0, 0.0, AffectConfig(), steps=400, windows=wmw.WINDOWS,
|
|
||||||
t_min=10, t_max=20)
|
|
||||||
assert set(r["metrics"]) == {"1", "3", "9"} # 20 reaches the next switch
|
|
||||||
|
|
||||||
|
|
||||||
def test_paired_ratio_is_per_seed_and_refuses_to_pair_across_seeds():
|
|
||||||
num = [dict(seed=s, metrics={"9": dict(steady=2.0)}) for s in (0, 1, 2)]
|
|
||||||
den = [dict(seed=s, metrics={"9": dict(steady=1.0)}) for s in (0, 1, 3)]
|
|
||||||
p = wmw.paired(num, den, window=9)
|
|
||||||
assert p["seeds"] == [0, 1] and p["n"] == 2
|
|
||||||
assert p["mean"] == pytest.approx(2.0) and p["won"] == 2
|
|
||||||
|
|
||||||
|
|
||||||
def test_the_present_only_baseline_sees_arrangement_the_message_basis_misses():
|
|
||||||
"""`L = 1` carries the whole history-over-present comparison, so it must not be
|
|
||||||
handicapped. A symmetric ring of same-type neighbours cancels in the first moment
|
|
||||||
`B` but not in the kernel mass, and `_frame` has to keep that distinction."""
|
|
||||||
cfg = ParticleConfig(n=5, n_types=1)
|
|
||||||
types = torch.zeros(5, dtype=torch.long)
|
|
||||||
tight = torch.tensor([[0.5, 0.5], [0.55, 0.5], [0.45, 0.5], [0.5, 0.55], [0.5, 0.45]])
|
|
||||||
loose = torch.tensor([[0.5, 0.5], [0.9, 0.5], [0.1, 0.5], [0.5, 0.9], [0.5, 0.1]])
|
|
||||||
a, b = identify._frame(tight, types, cfg)[0], identify._frame(loose, types, cfg)[0]
|
|
||||||
assert a[:2] == pytest.approx(b[:2], abs=1e-6) # the first moment cancels in both
|
|
||||||
assert a[2] > 5 * b[2] # the kernel mass does not
|
|
||||||
|
|
||||||
|
|
||||||
def test_history_gain_is_computed_against_the_same_decoder_at_L1():
|
|
||||||
"""accuracy(L) - accuracy(1) is only meaningful if both use the same per-frame
|
|
||||||
features and the same estimator; this pins that the raw feature block grows by
|
|
||||||
whole frames plus displacements and by nothing else."""
|
|
||||||
world = identify.rollout(ParticleConfig(seed=0), 120)
|
|
||||||
f = world["frame"].shape[-1]
|
|
||||||
n1 = identify.features(world, 1, "raw")[0].shape[-1]
|
|
||||||
n3 = identify.features(world, 3, "raw")[0].shape[-1]
|
|
||||||
assert n3 - n1 == 2 * f + 2 * 2 # two more frames, two more displacements
|
|
||||||
@@ -1,442 +0,0 @@
|
|||||||
"""Can the kernel answer for a relation it never saw?
|
|
||||||
|
|
||||||
This is the one property that separates the RP from a GNN rather than from a perceptron.
|
|
||||||
A GNN holds fixed weights per edge type -- a lookup with one entry per discrete relation. The
|
|
||||||
CPPN computes weights from continuous geometry, so it has *something* to say about a
|
|
||||||
displacement absent from training, where a lookup has no entry to read. Nothing in this project
|
|
||||||
had tested it: every chess run trained and evaluated on the same offset grid.
|
|
||||||
|
|
||||||
WHAT IS MEASURED, and what is not. The `table` arm fails on held-out cells BY CONSTRUCTION --
|
|
||||||
those entries never receive gradient and stay at their initialisation. Reporting that as a
|
|
||||||
finding would be a tautology. It is here to give the scale, and it is labelled as such. The
|
|
||||||
measurement is WITHIN the `rp` arm: its error on held-out cells against its error on seen cells
|
|
||||||
and against the floor. If held-out sits at the floor, the CPPN memorised the training cells and
|
|
||||||
the generated kernel is a parameterisation, not a capability. That is the informative negative.
|
|
||||||
|
|
||||||
Two hold-out structures, because "unseen" is two different questions:
|
|
||||||
--holdout random cells scattered among seen ones -> interpolation
|
|
||||||
--holdout band a contiguous annulus of cells -> extrapolation
|
|
||||||
|
|
||||||
Student-teacher. The teacher is the same RP with an analytic Gabor kernel in place of the
|
|
||||||
CPPN, so the target is exactly representable and the ceiling is 0 by construction. What the
|
|
||||||
student must recover is the kernel as a function of r, which is the object under test.
|
|
||||||
"""
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import argparse
|
|
||||||
import json
|
|
||||||
import statistics
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
import numpy as np
|
|
||||||
import torch
|
|
||||||
from torch import nn
|
|
||||||
|
|
||||||
from ailed.core import RelationalPerceptron
|
|
||||||
|
|
||||||
R = 7 # displacements live in [-R, R]^2
|
|
||||||
G = 2 * R + 1 # 15
|
|
||||||
CELLS = G * G # 225
|
|
||||||
D = 16 # kernel channels / hidden width
|
|
||||||
ATTR = 4
|
|
||||||
|
|
||||||
|
|
||||||
def cell_of(r: torch.Tensor) -> torch.Tensor:
|
|
||||||
"""(N,N,2) integer displacement -> (N,N) cell index on the GxG grid."""
|
|
||||||
dx = r[..., 0].round().long() + R
|
|
||||||
dy = r[..., 1].round().long() + R
|
|
||||||
return dy * G + dx
|
|
||||||
|
|
||||||
|
|
||||||
KNIGHT = [(1, 2), (2, 1), (-1, 2), (-2, 1), (1, -2), (2, -1), (-1, -2), (-2, -1)]
|
|
||||||
|
|
||||||
|
|
||||||
def gabor_kernel(sigma: float = 3.0, seed: int = 0, kfreq: float = 0.35,
|
|
||||||
kind: str = "smooth") -> torch.Tensor:
|
|
||||||
"""(CELLS, D) true kernel. `kind` varies HOW PREDICTABLE IT IS FROM ITS NEIGHBOURS.
|
|
||||||
|
|
||||||
Every null in unseen.md, scale.md and psi.md was measured against a smooth teacher, and
|
|
||||||
smoothness is exactly what lets a lookup plus a blur compete. These four families vary that
|
|
||||||
and nothing else:
|
|
||||||
|
|
||||||
smooth a band-limited Gabor. The replication: a blur should match the CPPN.
|
|
||||||
highfreq the same, at a frequency near the grid's resolution. Structured, not smooth.
|
|
||||||
knight_sym 1 on the eight L-offsets with the SAME value at all eight, 0 elsewhere. A
|
|
||||||
genuine D4 orbit: the eight squares are one rule under the square's symmetries.
|
|
||||||
knight 1 on the eight L-offsets, 0 elsewhere. NOT smooth and RULE-GENERATED -- a
|
|
||||||
neighbour average cannot recover an isolated spike, since its neighbours are 0.
|
|
||||||
This is chess_reach.md's knight, asked as a mechanism question.
|
|
||||||
noise iid per cell. THE CONTROL: nothing should generalise here, the CPPN included.
|
|
||||||
Without it, "the CPPN wins on non-smooth kernels" cannot be told apart from
|
|
||||||
"the setup favours the CPPN".
|
|
||||||
"""
|
|
||||||
g = torch.Generator().manual_seed(seed)
|
|
||||||
ys, xs = torch.meshgrid(torch.arange(-R, R + 1), torch.arange(-R, R + 1), indexing="ij")
|
|
||||||
r = torch.stack([xs, ys], -1).reshape(CELLS, 2).float()
|
|
||||||
if kind == "noise":
|
|
||||||
return torch.randn(CELLS, D, generator=g) * 0.2
|
|
||||||
if kind in ("knight", "knight_sym"):
|
|
||||||
w = torch.zeros(CELLS, D)
|
|
||||||
# knight_sym gives every channel ONE value across all eight offsets, so the pattern is a
|
|
||||||
# true D4 orbit and an invariant input can express it. knight varies the sign per offset,
|
|
||||||
# so the eight squares share a support but NOT a rule -- the control that keeps
|
|
||||||
# "invariants win" from being indistinguishable from "invariants always win".
|
|
||||||
sign = torch.randint(0, 2, (D, 1 if kind == "knight_sym" else len(KNIGHT)),
|
|
||||||
generator=g).float() * 2 - 1
|
|
||||||
for c in range(D):
|
|
||||||
for m, (dx, dy) in enumerate(KNIGHT):
|
|
||||||
w[(dy + R) * G + (dx + R), c] = sign[c, 0 if kind == "knight_sym" else m]
|
|
||||||
return w
|
|
||||||
if kind == "highfreq":
|
|
||||||
kfreq = 1.5
|
|
||||||
k = torch.randn(D, 2, generator=g) * kfreq # spatial frequencies of the domain
|
|
||||||
phi = torch.rand(D, generator=g) * 6.2831853
|
|
||||||
env = torch.exp(-(r * r).sum(-1) / (2 * sigma * sigma))[:, None]
|
|
||||||
return env * torch.cos(r @ k.T + phi)
|
|
||||||
|
|
||||||
|
|
||||||
class InvariantCPPN(nn.Module):
|
|
||||||
"""The CPPN over D4 invariants of the displacement instead of the displacement itself.
|
|
||||||
|
|
||||||
The knight null in `sharp.md` says nothing here induces a symmetry group from partial
|
|
||||||
support. This asks the other question: the CPPN sees raw r_ij, and has no reason to know
|
|
||||||
that (1,2) and (-2,-1) are the same law -- they are two different points of the plane.
|
|
||||||
Canonicalising to (min|dx|,max|dy|) collapses the square's eight symmetries to one orbit,
|
|
||||||
and the knight's eight squares become a single input.
|
|
||||||
|
|
||||||
STATED PLAINLY BECAUSE A CRITIC WILL SAY IT: this does not sneak the held-out cells into
|
|
||||||
training. It hands the model the CLAIM that those cells are equivalent to ones it did see.
|
|
||||||
The experiment measures whether that claim, when it is true of the domain, converts unseen
|
|
||||||
displacements into seen ones -- and the `knight` teacher, whose eight squares share a
|
|
||||||
support but not a value, is the control for when the claim is FALSE.
|
|
||||||
"""
|
|
||||||
def __init__(self, cppn: nn.Module):
|
|
||||||
super().__init__()
|
|
||||||
self.cppn = cppn
|
|
||||||
|
|
||||||
def forward(self, r, edge_onehot, context):
|
|
||||||
a = r.abs()
|
|
||||||
inv = torch.stack([a.min(-1).values, a.max(-1).values], dim=-1)
|
|
||||||
return self.cppn(inv, edge_onehot, context)
|
|
||||||
|
|
||||||
|
|
||||||
class LearnedFrameCPPN(nn.Module):
|
|
||||||
"""K learned linear maps on the displacement, averaged: m = (1/K) sum_k CPPN(T_k r).
|
|
||||||
|
|
||||||
`invariance.md` settled that a group HANDED to the kernel converts unseen orbit members into
|
|
||||||
seen ones. This asks the question that one could not: can the model FIND the reparameterisation
|
|
||||||
instead of being given it? If the learned set of T_k is closed under the domain's group, the
|
|
||||||
average is invariant to it and the eight knight squares become one input -- without anyone
|
|
||||||
having said the word D4.
|
|
||||||
|
|
||||||
The oracle and the floor are both already measured on the same harness and seeds, so this
|
|
||||||
lands inside a 266x band rather than against nothing: `rp_inv` 0.00009 above, `rp` 0.02395
|
|
||||||
below (knight_sym, sharp/invariance runs).
|
|
||||||
|
|
||||||
TWO WAYS THIS CAN LOOK LIKE A RESULT WITHOUT BEING ONE, both checked:
|
|
||||||
- K transforms are extra capacity. A wider kernel fits training cells better and says
|
|
||||||
nothing about held-out ones, so the hold-out is the discriminator, not `seen`.
|
|
||||||
- The T_k collapse to one map, making this K=1 with more compute. Reported as their spread.
|
|
||||||
And `orbit_consistency` measures the property directly, independent of accuracy: apply a D4
|
|
||||||
element to r and see whether the kernel's output moves.
|
|
||||||
"""
|
|
||||||
def __init__(self, cppn: nn.Module, k: int, seed: int = 0):
|
|
||||||
super().__init__()
|
|
||||||
self.cppn = cppn
|
|
||||||
g = torch.Generator().manual_seed(seed + 77)
|
|
||||||
# near identity plus noise: initialised AT the group's identity element, so a collapse to
|
|
||||||
# K=1 is the null hypothesis the run has to move away from rather than the thing it
|
|
||||||
# accidentally starts from.
|
|
||||||
self.T = nn.Parameter(torch.eye(2).repeat(k, 1, 1)
|
|
||||||
+ torch.randn(k, 2, 2, generator=g) * 0.4)
|
|
||||||
|
|
||||||
def forward(self, r, edge_onehot, context):
|
|
||||||
return torch.stack([self.cppn(r @ t.T, edge_onehot, context) for t in self.T]).mean(0)
|
|
||||||
|
|
||||||
|
|
||||||
D4 = [torch.tensor(m, dtype=torch.float32) for m in
|
|
||||||
([[1, 0], [0, 1]], [[0, -1], [1, 0]], [[-1, 0], [0, -1]], [[0, 1], [-1, 0]],
|
|
||||||
[[-1, 0], [0, 1]], [[1, 0], [0, -1]], [[0, 1], [1, 0]], [[0, -1], [-1, 0]])]
|
|
||||||
|
|
||||||
|
|
||||||
@torch.no_grad()
|
|
||||||
def orbit_consistency(kernel: nn.Module) -> float:
|
|
||||||
"""How D4-invariant the kernel actually is, as a fraction of its own scale. 0 = invariant.
|
|
||||||
|
|
||||||
Measured on the kernel's behaviour, not on its parameters, so it answers "did it find the
|
|
||||||
group" without needing the learned maps to look like anything in particular.
|
|
||||||
"""
|
|
||||||
# (n, n, 2): the CPPN expands its context to r's first two dims, so the probe grid has to
|
|
||||||
# be square. 9x9 covers offsets -4..4, which contains the knight's orbit with room around it.
|
|
||||||
ys, xs = torch.meshgrid(torch.arange(-4, 5), torch.arange(-4, 5), indexing="ij")
|
|
||||||
r = torch.stack([xs, ys], -1).float()
|
|
||||||
edge, ctx = torch.ones(9, 9, 1), torch.zeros(2)
|
|
||||||
base = kernel(r, edge, ctx)
|
|
||||||
scale = base.abs().mean().clamp(min=1e-9).item()
|
|
||||||
return max((kernel(r @ g.T, edge, ctx) - base).abs().mean().item() for g in D4[1:]) / scale
|
|
||||||
|
|
||||||
|
|
||||||
@torch.no_grad()
|
|
||||||
def frame_spread(kernel: nn.Module) -> float:
|
|
||||||
"""Mean pairwise distance between the learned maps. ~0 means they collapsed to one."""
|
|
||||||
T = kernel.T
|
|
||||||
return float(torch.cdist(T.flatten(1), T.flatten(1)).mean())
|
|
||||||
|
|
||||||
|
|
||||||
class TableKernel(nn.Module):
|
|
||||||
"""One weight vector per discrete displacement: a GNN with one edge type per relation.
|
|
||||||
|
|
||||||
Same call signature as AffectiveCPPN so it can be swapped into RelationalPerceptron in
|
|
||||||
place. It has MORE parameters than the CPPN (225*16 vs ~720), so a failure on held-out
|
|
||||||
cells is not a capacity failure -- it is an information failure, which is the point.
|
|
||||||
"""
|
|
||||||
def __init__(self):
|
|
||||||
super().__init__()
|
|
||||||
self.w = nn.Parameter(torch.randn(CELLS, D) * 0.1)
|
|
||||||
|
|
||||||
def forward(self, r, edge_onehot, context):
|
|
||||||
return self.w[cell_of(r)]
|
|
||||||
|
|
||||||
|
|
||||||
def make_model(arm: str, seed: int, omega: float = 1.0) -> nn.Module:
|
|
||||||
"""omega sets the CPPN's bandwidth and is the knob this experiment is most exposed to.
|
|
||||||
|
|
||||||
1.0 is not the project default -- chess ran at 10.0 -- so both are reported. A wide-band
|
|
||||||
kernel can fit the training cells with high-frequency structure that says nothing about
|
|
||||||
the gaps between them, which is exactly the failure mode `unseen` is looking for.
|
|
||||||
"""
|
|
||||||
torch.manual_seed(seed)
|
|
||||||
rp = RelationalPerceptron(ATTR, 2, 1, 2, hidden_dim=D, cppn_hidden=32, omega=omega)
|
|
||||||
if arm.startswith("table"):
|
|
||||||
rp.cppn = TableKernel() # ponytail: swap in place so all arms share RP's exact forward
|
|
||||||
elif arm.startswith("rp_inv"):
|
|
||||||
rp.cppn = InvariantCPPN(rp.cppn)
|
|
||||||
elif arm.startswith("rp_learn_"):
|
|
||||||
rp.cppn = LearnedFrameCPPN(rp.cppn, int(arm.split("_")[2]), seed)
|
|
||||||
elif arm != "rp":
|
|
||||||
# Exact, not a prefix check: "rp_inv" typed as "rp_invariant" or "rp_nv" would otherwise
|
|
||||||
# fall through and run as plain rp, which is how this went unnoticed the first time.
|
|
||||||
raise ValueError(f"unknown arm {arm!r}")
|
|
||||||
return nn.ModuleDict({"rp": rp, "out": nn.Linear(D, D)})
|
|
||||||
|
|
||||||
|
|
||||||
@torch.no_grad()
|
|
||||||
def fill_by_diffusion(w: torch.Tensor, held: torch.Tensor) -> None:
|
|
||||||
"""Fill a table's held-out entries from their trained neighbours, in place.
|
|
||||||
|
|
||||||
THE CONTROL THAT DECIDES WHAT THE RESULT MEANS. A bare table fails on held cells by
|
|
||||||
construction -- those entries never see gradient. Beating that is not a finding. The real
|
|
||||||
question is whether generating the kernel from geometry beats a lookup PLUS the obvious
|
|
||||||
smoothing anyone would reach for, which is what this arm is. On the random hold-out every
|
|
||||||
held cell is surrounded by trained ones, so this control should be strong there; on the
|
|
||||||
band it has to push a front inwards across a gap, which is what extrapolation costs.
|
|
||||||
"""
|
|
||||||
grid = w.view(G, G, D).clone()
|
|
||||||
know = (~held).view(G, G).clone()
|
|
||||||
while not know.all():
|
|
||||||
pad_v = torch.zeros(G + 2, G + 2, D); pad_v[1:-1, 1:-1] = grid * know[..., None]
|
|
||||||
pad_k = torch.zeros(G + 2, G + 2); pad_k[1:-1, 1:-1] = know.float()
|
|
||||||
acc = sum(pad_v[1 + dy:G + 1 + dy, 1 + dx:G + 1 + dx] for dy, dx in
|
|
||||||
((-1, 0), (1, 0), (0, -1), (0, 1)))
|
|
||||||
cnt = sum(pad_k[1 + dy:G + 1 + dy, 1 + dx:G + 1 + dx] for dy, dx in
|
|
||||||
((-1, 0), (1, 0), (0, -1), (0, 1)))
|
|
||||||
newly = (~know) & (cnt > 0)
|
|
||||||
if not newly.any():
|
|
||||||
break # nothing reachable; leave the rest at init
|
|
||||||
grid[newly] = acc[newly] / cnt[newly][:, None]
|
|
||||||
know |= newly
|
|
||||||
w.copy_(grid.view(CELLS, D))
|
|
||||||
|
|
||||||
|
|
||||||
def teacher(seed: int, kfreq: float = 0.35, kind: str = "smooth") -> nn.Module:
|
|
||||||
"""kfreq is the DOMAIN's length scale, not the model's. Sweeping it against the CPPN's omega
|
|
||||||
is what separates a knob that wants calibrating per domain from a defect in the
|
|
||||||
architecture: if the best omega tracks kfreq, core.py's own comment was right all along and
|
|
||||||
nobody had calibrated it; if it sits still, the default can simply be corrected."""
|
|
||||||
m = make_model("table", seed + 1000)
|
|
||||||
with torch.no_grad():
|
|
||||||
m["rp"].cppn.w.copy_(gabor_kernel(seed=seed, kfreq=kfreq, kind=kind))
|
|
||||||
for p in m.parameters():
|
|
||||||
p.requires_grad_(False)
|
|
||||||
return m
|
|
||||||
|
|
||||||
|
|
||||||
def holdout_cells(kind: str, frac: float, seed: int, W: torch.Tensor | None = None
|
|
||||||
) -> torch.Tensor:
|
|
||||||
"""(CELLS,) bool, True = withheld from training.
|
|
||||||
|
|
||||||
`support` exists because the knight teacher broke the other two. Most of its 225 cells are
|
|
||||||
exactly zero, so a hold-out drawn uniformly withholds cells that carry no signal, the
|
|
||||||
target's variance there is ~0, and the floor collapses -- the question becomes vacuous
|
|
||||||
rather than hard. `support` withholds cells the kernel actually uses, which is the same
|
|
||||||
question for every family: having seen most of where the law lives, can the model infer the
|
|
||||||
rest? For the knight that is "seen six of the eight L-squares, infer the other two", and a
|
|
||||||
neighbour average cannot, because an isolated spike's neighbours are zero.
|
|
||||||
|
|
||||||
The set is closed under negation: a pair contributes displacements r and -r, so an
|
|
||||||
asymmetric hold-out would have no evaluable pairs.
|
|
||||||
"""
|
|
||||||
ys, xs = torch.meshgrid(torch.arange(-R, R + 1), torch.arange(-R, R + 1), indexing="ij")
|
|
||||||
centre = R * G + R # r = 0: every entity messages itself, so it is in every configuration
|
|
||||||
if kind == "random":
|
|
||||||
g = torch.Generator().manual_seed(seed)
|
|
||||||
n = int(round(frac * CELLS))
|
|
||||||
idx = torch.randperm(CELLS, generator=g)[:n]
|
|
||||||
m = torch.zeros(CELLS, dtype=torch.bool)
|
|
||||||
m[idx] = True
|
|
||||||
m[centre] = False
|
|
||||||
return m
|
|
||||||
if kind == "support":
|
|
||||||
assert W is not None, "support hold-out needs the teacher's kernel"
|
|
||||||
mag = W.abs().mean(1)
|
|
||||||
live = (mag > 0.2 * mag.max()).nonzero().flatten().tolist()
|
|
||||||
g = torch.Generator().manual_seed(seed)
|
|
||||||
order = torch.randperm(len(live), generator=g).tolist()
|
|
||||||
m = torch.zeros(CELLS, dtype=torch.bool)
|
|
||||||
want = max(2, int(round(frac * len(live))))
|
|
||||||
for idx in order:
|
|
||||||
c = live[idx]
|
|
||||||
if c == centre:
|
|
||||||
continue
|
|
||||||
dy, dx = divmod(c, G)
|
|
||||||
neg = (2 * R - dy) * G + (2 * R - dx) # the cell for -r
|
|
||||||
m[c] = m[neg] = True
|
|
||||||
if int(m.sum()) >= want:
|
|
||||||
break
|
|
||||||
return m
|
|
||||||
if kind == "band":
|
|
||||||
d = (xs.abs().float() + ys.abs().float()).reshape(-1) # L1 radius
|
|
||||||
lo = torch.quantile(d, 1.0 - frac - 0.12)
|
|
||||||
hi = torch.quantile(d, 1.0 - 0.12)
|
|
||||||
m = (d >= lo) & (d < hi)
|
|
||||||
m[centre] = False
|
|
||||||
return m
|
|
||||||
raise ValueError(kind)
|
|
||||||
|
|
||||||
|
|
||||||
def train_batch(held: torch.Tensor, gen: torch.Generator, size=24, n_lo=2, n_hi=5):
|
|
||||||
"""Configurations with the held-out pairs MASKED OUT rather than the configuration rejected.
|
|
||||||
|
|
||||||
Rejection was the first design and it was wrong twice over. Finding a 5-entity placement
|
|
||||||
whose 20 ordered displacements all avoid a scattered 25% of cells has probability ~0.3%,
|
|
||||||
so it was slow -- but the real fault is that it would have skewed training towards small N,
|
|
||||||
silently, since small configurations are the easy ones to satisfy. Masking is what the RP's
|
|
||||||
own `mask` argument is for: the held cell contributes nothing to the message and receives
|
|
||||||
no gradient, and every N stays equally represented. Teacher and student get the same mask,
|
|
||||||
so the target is defined by the surviving pairs alone.
|
|
||||||
"""
|
|
||||||
out = []
|
|
||||||
for _ in range(size):
|
|
||||||
n = int(torch.randint(n_lo, n_hi + 1, (1,), generator=gen))
|
|
||||||
c = torch.randint(0, 8, (n, 2), generator=gen).float()
|
|
||||||
r = c[None, :, :] - c[:, None, :]
|
|
||||||
out.append((torch.randn(n, ATTR, generator=gen), r, (~held[cell_of(r)]).float()))
|
|
||||||
return out
|
|
||||||
|
|
||||||
|
|
||||||
def pair_batch(held: torch.Tensor, want_held: bool, gen: torch.Generator, size=64):
|
|
||||||
"""Evaluation is always on PAIRS, so `seen` and `unseen` measure the same thing.
|
|
||||||
|
|
||||||
A pair's two ordered displacements are r and -r; both must be on the wanted side, so the
|
|
||||||
single relation under test is unambiguous.
|
|
||||||
"""
|
|
||||||
out = []
|
|
||||||
while len(out) < size:
|
|
||||||
c = torch.randint(0, 8, (2, 2), generator=gen).float()
|
|
||||||
r = c[None, :, :] - c[:, None, :]
|
|
||||||
off = ~torch.eye(2, dtype=torch.bool)
|
|
||||||
hit = held[cell_of(r)][off]
|
|
||||||
if bool(hit.all()) if want_held else not bool(hit.any()):
|
|
||||||
out.append((torch.randn(2, ATTR, generator=gen), r, torch.ones(2, 2)))
|
|
||||||
return out
|
|
||||||
|
|
||||||
|
|
||||||
def run_model(model, a, r, mask):
|
|
||||||
edge = torch.ones(a.shape[0], a.shape[0], 1)
|
|
||||||
h = model["rp"](a, r, edge, mask, torch.zeros(2))
|
|
||||||
return model["out"](h)
|
|
||||||
|
|
||||||
|
|
||||||
def evaluate(model, tea, data) -> float:
|
|
||||||
with torch.no_grad():
|
|
||||||
num = sum(((run_model(model, a, r, m) - run_model(tea, a, r, m)) ** 2).sum().item()
|
|
||||||
for a, r, m in data)
|
|
||||||
den = sum(a.shape[0] * D for a, _, _ in data)
|
|
||||||
return num / den
|
|
||||||
|
|
||||||
|
|
||||||
def floor_mse(tea, data) -> float:
|
|
||||||
"""What a predictor that ignores the relation entirely achieves: predict the mean target."""
|
|
||||||
with torch.no_grad():
|
|
||||||
ys = torch.cat([run_model(tea, a, r, m) for a, r, m in data])
|
|
||||||
return ((ys - ys.mean(0)) ** 2).mean().item()
|
|
||||||
|
|
||||||
|
|
||||||
def one_seed(arm: str, kind: str, frac: float, steps: int, seed: int, omega: float = 1.0,
|
|
||||||
kfreq: float = 0.35, teacher_kind: str = "smooth") -> dict:
|
|
||||||
# `kind` is the HOLD-OUT structure and `teacher_kind` is the kernel family. They are
|
|
||||||
# different axes and were briefly the same identifier, which Python caught.
|
|
||||||
tea = teacher(seed, kfreq, teacher_kind)
|
|
||||||
held = holdout_cells(kind, frac, seed, gabor_kernel(seed=seed, kfreq=kfreq, kind=teacher_kind))
|
|
||||||
gen = torch.Generator().manual_seed(seed)
|
|
||||||
model = make_model(arm, seed, omega)
|
|
||||||
opt = torch.optim.Adam(model.parameters(), lr=3e-3)
|
|
||||||
|
|
||||||
for _ in range(steps):
|
|
||||||
data = train_batch(held, gen)
|
|
||||||
loss = sum(((run_model(model, a, r, m) - run_model(tea, a, r, m)) ** 2).mean()
|
|
||||||
for a, r, m in data) / len(data)
|
|
||||||
opt.zero_grad(); loss.backward(); opt.step()
|
|
||||||
|
|
||||||
if arm == "table_interp":
|
|
||||||
fill_by_diffusion(model["rp"].cppn.w.data, held)
|
|
||||||
|
|
||||||
ev = torch.Generator().manual_seed(seed + 5000)
|
|
||||||
seen = pair_batch(held, False, ev)
|
|
||||||
unseen = pair_batch(held, True, ev)
|
|
||||||
k = model["rp"].cppn
|
|
||||||
diag = {"orbit": orbit_consistency(k)}
|
|
||||||
if isinstance(k, LearnedFrameCPPN):
|
|
||||||
diag["spread"] = frame_spread(k)
|
|
||||||
return {"seed": seed, "arm": arm, "omega": omega, "kfreq": kfreq, "teacher": teacher_kind,
|
|
||||||
**diag, "seen": evaluate(model, tea, seen),
|
|
||||||
"unseen": evaluate(model, tea, unseen),
|
|
||||||
"floor_seen": floor_mse(tea, seen), "floor_unseen": floor_mse(tea, unseen),
|
|
||||||
"n_held": int(held.sum())}
|
|
||||||
|
|
||||||
|
|
||||||
def main():
|
|
||||||
ap = argparse.ArgumentParser()
|
|
||||||
ap.add_argument("--holdout", default="random", choices=["random", "band", "support"])
|
|
||||||
ap.add_argument("--frac", type=float, default=0.25)
|
|
||||||
ap.add_argument("--steps", type=int, default=1500)
|
|
||||||
ap.add_argument("--seeds", default="0,1,2,3,4,5,6,7")
|
|
||||||
ap.add_argument("--arms", default="rp,table")
|
|
||||||
ap.add_argument("--omega", type=float, default=1.0)
|
|
||||||
ap.add_argument("--kfreq", type=float, default=0.35, help="the DOMAIN's spatial frequency")
|
|
||||||
ap.add_argument("--teacher", default="smooth",
|
|
||||||
choices=["smooth", "highfreq", "knight", "knight_sym", "noise"])
|
|
||||||
ap.add_argument("--out", default="results/unseen.json")
|
|
||||||
args = ap.parse_args()
|
|
||||||
|
|
||||||
rows = []
|
|
||||||
for arm in args.arms.split(","):
|
|
||||||
for s in (int(x) for x in args.seeds.split(",")):
|
|
||||||
rows.append(one_seed(arm, args.holdout, args.frac, args.steps, s, args.omega, args.kfreq,
|
|
||||||
args.teacher))
|
|
||||||
r = rows[-1]
|
|
||||||
print(f"{arm:6s} seed {s} seen {r['seen']:.5f} unseen {r['unseen']:.5f}"
|
|
||||||
f" floor {r['floor_unseen']:.5f}", flush=True)
|
|
||||||
|
|
||||||
print(f"\n{args.teacher} teacher, {args.holdout} hold-out, frac={args.frac}, "
|
|
||||||
f"omega={args.omega}, {rows[0]['n_held']}/{CELLS} cells")
|
|
||||||
print(f"{'arm':6s} {'seen':>9s} {'unseen':>9s} {'floor':>9s} unseen/floor")
|
|
||||||
for arm in args.arms.split(","):
|
|
||||||
a = [r for r in rows if r["arm"] == arm]
|
|
||||||
se, un, fl = (statistics.mean([r[k] for r in a]) for k in ("seen", "unseen", "floor_unseen"))
|
|
||||||
print(f"{arm:6s} {se:9.5f} {un:9.5f} {fl:9.5f} {un / fl:.3f}")
|
|
||||||
Path(args.out).write_text(json.dumps({"args": vars(args), "rows": rows}, indent=1))
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
main()
|
|
||||||
@@ -1,321 +0,0 @@
|
|||||||
"""Task 9 Parts 1 and 3: when does per-entity memory have a job?
|
|
||||||
|
|
||||||
Part 2 lives in `identify.py` -- it measures `T_id` and touches no organism.
|
|
||||||
|
|
||||||
**Part 1 (`--part timing`)** is the last legitimate shot at A1. `results/a1.md` §1a
|
|
||||||
measured arousal peaking about 12 steps *after* a switch and sitting *lower* at the
|
|
||||||
switch step (0.061) than far from one (0.106). `rho_a` and `rho_slow` are the affect
|
|
||||||
mechanism's own time constants and have never been set, so tuning them is tuning the
|
|
||||||
mechanism rather than tuning a baseline to lose. This sweeps them, reports the
|
|
||||||
arousal-vs-lag profile for each, and runs `grp_k` against `grp_k0` at the best-timed
|
|
||||||
setting.
|
|
||||||
|
|
||||||
Only `rho_slow` and `rho_a` can move arousal's timing. Read `affect.update`:
|
|
||||||
|
|
||||||
a_target = tanh(max(0, loss - slow) / (slow + eps)); a <- a + rho_a (a_target - a)
|
|
||||||
|
|
||||||
`fast` appears only in `v_target`, so `rho_fast` reaches arousal solely through the
|
|
||||||
loss stream, via valence feeding the CPPN. `--part rho-fast` measures that it does not
|
|
||||||
matter, rather than assuming it. Where the sweep raises `rho_slow` past the default
|
|
||||||
`rho_fast`, `rho_fast` is raised with it (`_cfg`), because `AffectConfig` documents
|
|
||||||
`rho_slow < rho_fast` and inverting the two would change what valence means as a side
|
|
||||||
effect of a timing sweep. `AffectConfig`'s defaults are not touched: values are passed.
|
|
||||||
|
|
||||||
**Part 3 (`--part duration`)** is the falsifiable test. At each regime duration it
|
|
||||||
measures the **capacity-controlled** state gain `grp_k0_nostate / grp_k0`: identical
|
|
||||||
architecture, identical 5602 parameters, differing only in whether memory is carried
|
|
||||||
between steps. A `grp_k0` vs `rp_only` number is confounded 3.9x on parameter count
|
|
||||||
(`results/frozen.md` §5) and is not this measurement.
|
|
||||||
|
|
||||||
Shortening the regime changes the world's timescale, so the metrics have to be
|
|
||||||
re-checked rather than re-used. `regime._metrics` is a pure function of the traces and
|
|
||||||
the window, so each run stores its metrics at every window shorter than the duration's
|
|
||||||
`t_min`; the tables then quote one window across all durations and `steady` means the
|
|
||||||
same thing in every row. `n_switches` is reported with every number so a duration with
|
|
||||||
too few switches in the measured half to average over is visible rather than implied.
|
|
||||||
|
|
||||||
uv run python when_memory_works.py --part timing --out results/w_timing.json
|
|
||||||
uv run python when_memory_works.py --part rho-fast --rho-a 1.0 --rho-slow 0.2 \
|
|
||||||
--out results/w_rhofast.json
|
|
||||||
uv run python when_memory_works.py --part best --rho-a 1.0 --rho-slow 0.2 \
|
|
||||||
--out results/w_best.json
|
|
||||||
uv run python when_memory_works.py --part duration --out results/w_duration_all.json
|
|
||||||
"""
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import argparse
|
|
||||||
import json
|
|
||||||
import statistics
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
import numpy as np
|
|
||||||
|
|
||||||
from ailed import AffectConfig
|
|
||||||
from frozen import _build, _train
|
|
||||||
from regime import _metrics
|
|
||||||
|
|
||||||
STEPS = 8000
|
|
||||||
BPTT = 20
|
|
||||||
LR = 1e-3
|
|
||||||
HIDDEN = 32
|
|
||||||
OMEGA = 10.0
|
|
||||||
|
|
||||||
# Part 1: rho_a x rho_slow. rho_fast is carried up with rho_slow (see _cfg).
|
|
||||||
RHO_A = (0.5, 1.0)
|
|
||||||
RHO_SLOW = (0.02, 0.05, 0.1, 0.2, 0.4)
|
|
||||||
TIMING_SEEDS = (0, 1, 2, 3)
|
|
||||||
BEST_SEEDS = tuple(range(16))
|
|
||||||
KAPPA_PRIMARY = 4.0 # `regime.run`'s standing default; the criterion is read off this
|
|
||||||
KAPPA_CONTEXT = (1.0, 16.0) # reported as context, never as the verdict
|
|
||||||
|
|
||||||
# Part 3: the pre-registered grid, plus (4, 8) added before any duration run was made
|
|
||||||
# because T_id turns out to be short and the predicted peak would otherwise sit on the
|
|
||||||
# grid's edge. `frozen` draws one regime and never switches, as headroom.md section 5 did.
|
|
||||||
# (2, 3) probes the theory's left arm, T_z < T_id. Part 2 measures T_id = 2 observations,
|
|
||||||
# so no duration in the pre-registered grid reaches below it -- the shortest, 4-8, is
|
|
||||||
# already twice T_id. It was added after Part 2 and before any duration run was read.
|
|
||||||
DURATIONS = ((2, 3), (4, 8), (10, 20), (40, 80), (150, 300), (600, 1200), (STEPS * 2, STEPS * 2))
|
|
||||||
DURATION_SEEDS = tuple(range(16))
|
|
||||||
# window 1 is the only one a duration of 2-3 admits, and it is the column every duration
|
|
||||||
# can therefore be compared on. Reported alongside, never instead of, the wider windows.
|
|
||||||
WINDOWS = (1, 3, 9, 20)
|
|
||||||
|
|
||||||
|
|
||||||
def _cfg(rho_a: float, rho_slow: float, rho_fast: float | None = None) -> AffectConfig:
|
|
||||||
"""An AffectConfig with the swept time constants, keeping rho_slow < rho_fast.
|
|
||||||
|
|
||||||
`AffectConfig` says rho_slow "must be < rho_fast". The default pair is (0.02, 0.2),
|
|
||||||
a factor of ten. Settings that raise rho_slow past 0.2 therefore raise rho_fast to
|
|
||||||
keep a separation, so the sweep moves arousal's timing without silently inverting
|
|
||||||
the two baselines valence is built from.
|
|
||||||
"""
|
|
||||||
fast = rho_fast if rho_fast is not None else max(0.2, 2.0 * rho_slow)
|
|
||||||
return AffectConfig(rho_a=rho_a, rho_slow=rho_slow, rho_fast=fast)
|
|
||||||
|
|
||||||
|
|
||||||
def label(acfg: AffectConfig) -> str:
|
|
||||||
return f"a{acfg.rho_a:g}/s{acfg.rho_slow:g}/f{acfg.rho_fast:g}"
|
|
||||||
|
|
||||||
|
|
||||||
# -- one run ---------------------------------------------------------------------
|
|
||||||
|
|
||||||
def gate_arousal_seq(arousals: list[float]) -> np.ndarray:
|
|
||||||
"""The arousal the gate saw at each step, from the arousal `_train` records.
|
|
||||||
|
|
||||||
`_train` appends `affect.arousal` *after* `update`, so `arousals[t]` is built from
|
|
||||||
`losses[t]` and the gate at step t saw the previous value. Step 0 sees `Affect()`'s
|
|
||||||
initial 0.0. `tests/test_when_memory_works.py` pins this against `a1.GateTrace`,
|
|
||||||
which records the value the organism actually passed in.
|
|
||||||
"""
|
|
||||||
return np.concatenate([[0.0], np.asarray(arousals[:-1], dtype=float)])
|
|
||||||
|
|
||||||
|
|
||||||
def by_lag(x: np.ndarray, switched: list[bool], steps: int, window: int) -> list[float]:
|
|
||||||
"""`x` at lag k after a switch, averaged over the measured (second) half's switches.
|
|
||||||
|
|
||||||
The same cut `regime._metrics` uses for `recovery`, so an arousal profile and an
|
|
||||||
error profile are averaged over exactly the same switches.
|
|
||||||
"""
|
|
||||||
half = steps // 2
|
|
||||||
sw = [i for i in range(half, steps - window) if switched[i]]
|
|
||||||
if not sw:
|
|
||||||
return [float("nan")] * window
|
|
||||||
return [float(x[[j + k for j in sw]].mean()) for k in range(window)]
|
|
||||||
|
|
||||||
|
|
||||||
def far_level(x: np.ndarray, switched: list[bool], steps: int, window: int) -> float:
|
|
||||||
"""`x` on `_metrics`'s own `steady_idx` -- no switch in the preceding `window` steps."""
|
|
||||||
half = steps // 2
|
|
||||||
idx = [i for i in range(half, steps) if not any(switched[max(0, i - window):i + 1])]
|
|
||||||
return float(x[idx].mean()) if idx else float("nan")
|
|
||||||
|
|
||||||
|
|
||||||
def run_one(name: str, seed: int, kappa: float, acfg: AffectConfig, *,
|
|
||||||
steps: int = STEPS, windows: tuple[int, ...] = (20,), t_min: int | None = None,
|
|
||||||
t_max: int | None = None, stateless: bool = False, bptt: int = BPTT,
|
|
||||||
lr: float = LR, hidden: int = HIDDEN, omega: float = OMEGA) -> dict:
|
|
||||||
spec, wcfg, world, org = _build(name, seed, hidden, omega, kappa, t_min, t_max)
|
|
||||||
_, _, tr = _train(spec, wcfg, world, org, steps, bptt, lr, stateless, acfg=acfg)
|
|
||||||
a_gate = gate_arousal_seq(tr["arousals"])
|
|
||||||
out = dict(condition=name + ("_nostate" if stateless else ""), seed=seed, kappa=kappa,
|
|
||||||
steps=steps, stateless=stateless, t_min=wcfg.t_min, t_max=wcfg.t_max,
|
|
||||||
rho_a=acfg.rho_a, rho_slow=acfg.rho_slow, rho_fast=acfg.rho_fast,
|
|
||||||
affect=label(acfg), n_params=sum(p.numel() for p in org.parameters()),
|
|
||||||
metrics={}, arousal={}, loss_by_lag={})
|
|
||||||
losses = np.asarray(tr["losses"], dtype=float)
|
|
||||||
for w in windows:
|
|
||||||
if w >= wcfg.t_min:
|
|
||||||
continue # a recovery window reaching the next switch blends two events
|
|
||||||
out["metrics"][str(w)] = _metrics(tr["losses"], tr["switched"], tr["arousals"], w)
|
|
||||||
out["arousal"][str(w)] = dict(
|
|
||||||
by_lag=by_lag(a_gate, tr["switched"], steps, w),
|
|
||||||
far=far_level(a_gate, tr["switched"], steps, w))
|
|
||||||
out["loss_by_lag"][str(w)] = by_lag(losses, tr["switched"], steps, w)
|
|
||||||
return out
|
|
||||||
|
|
||||||
|
|
||||||
# -- Part 1 ----------------------------------------------------------------------
|
|
||||||
|
|
||||||
def peak_lag(profile: list[float]) -> int:
|
|
||||||
"""Lag of the maximum, or -1 when there is nothing to peak.
|
|
||||||
|
|
||||||
A frozen regime never switches, so `by_lag` and `recovery` are all-NaN there and
|
|
||||||
there is no post-switch profile to take an argmax over. That is a real state of the
|
|
||||||
world at the end of Part 3's sweep, not an error.
|
|
||||||
"""
|
|
||||||
a = np.asarray(profile, dtype=float)
|
|
||||||
return -1 if np.all(np.isnan(a)) else int(np.nanargmax(a))
|
|
||||||
|
|
||||||
|
|
||||||
def timing_table(results: list[dict], window: int = 20) -> str:
|
|
||||||
"""Arousal at each lag after a switch, per affect setting, means over seeds."""
|
|
||||||
by: dict[str, list[dict]] = {}
|
|
||||||
for r in results:
|
|
||||||
by.setdefault(r["affect"], []).append(r)
|
|
||||||
lags = list(range(0, min(window, 20), 2))
|
|
||||||
head = "".join(f"{'@' + str(k):>7}" for k in lags)
|
|
||||||
lines = [f"{'rho_a/rho_slow/rho_fast':<24}{head}{'far':>7}{'peak':>7}{'loss pk':>9}",
|
|
||||||
"-" * (24 + 7 * len(lags) + 23)]
|
|
||||||
for name, rs in sorted(by.items()):
|
|
||||||
prof = [statistics.fmean(r["arousal"][str(window)]["by_lag"][k] for r in rs)
|
|
||||||
for k in range(window)]
|
|
||||||
lprof = [statistics.fmean(r["loss_by_lag"][str(window)][k] for r in rs)
|
|
||||||
for k in range(window)]
|
|
||||||
far = statistics.fmean(r["arousal"][str(window)]["far"] for r in rs)
|
|
||||||
lines.append(f"{name:<24}" + "".join(f"{prof[k]:>7.3f}" for k in lags)
|
|
||||||
+ f"{far:>7.3f}{peak_lag(prof):>7d}{peak_lag(lprof):>9d}")
|
|
||||||
return "\n".join(lines)
|
|
||||||
|
|
||||||
|
|
||||||
def paired(num: list[dict], den: list[dict], window: int = 20, key: str = "steady") -> dict:
|
|
||||||
"""`num/den` on `steady`, per seed. Both lists must cover the same seeds."""
|
|
||||||
a = {r["seed"]: r["metrics"][str(window)][key] for r in num}
|
|
||||||
b = {r["seed"]: r["metrics"][str(window)][key] for r in den}
|
|
||||||
seeds = sorted(set(a) & set(b))
|
|
||||||
ratios = [a[s] / b[s] for s in seeds]
|
|
||||||
return dict(n=len(seeds), mean=statistics.fmean(ratios),
|
|
||||||
median=statistics.median(ratios), won=sum(r > 1.0 for r in ratios),
|
|
||||||
per_seed=ratios, seeds=seeds)
|
|
||||||
|
|
||||||
|
|
||||||
# -- Part 3 ----------------------------------------------------------------------
|
|
||||||
|
|
||||||
def duration_table(results: list[dict], window: int) -> str:
|
|
||||||
"""Capacity-controlled state gain against regime duration."""
|
|
||||||
by: dict[tuple, dict[str, list[dict]]] = {}
|
|
||||||
for r in results:
|
|
||||||
by.setdefault((r["t_min"], r["t_max"]), {}).setdefault(r["condition"], []).append(r)
|
|
||||||
lines = [f"{'duration':>14}{'window':>7}{'n_sw':>6}{'grp_k0':>11}{'nostate':>11}"
|
|
||||||
f"{'gain':>7}{'median':>8}{'won':>7}",
|
|
||||||
"-" * 71]
|
|
||||||
for dur in sorted(by):
|
|
||||||
arms = by[dur]
|
|
||||||
if "grp_k0" not in arms or "grp_k0_nostate" not in arms:
|
|
||||||
continue
|
|
||||||
if any(str(window) not in r["metrics"] for r in arms["grp_k0"]):
|
|
||||||
continue
|
|
||||||
p = paired(arms["grp_k0_nostate"], arms["grp_k0"], window)
|
|
||||||
m = lambda c: statistics.fmean(r["metrics"][str(window)]["steady"] for r in arms[c])
|
|
||||||
nsw = statistics.fmean(r["metrics"][str(window)]["n_switches"] for r in arms["grp_k0"])
|
|
||||||
tag = "frozen" if dur[0] >= STEPS else f"{dur[0]}-{dur[1]}"
|
|
||||||
lines.append(f"{tag:>14}{window:>7}{nsw:>6.0f}{m('grp_k0'):>11.3e}"
|
|
||||||
f"{m('grp_k0_nostate'):>11.3e}{p['mean']:>7.2f}{p['median']:>8.2f}"
|
|
||||||
f"{str(p['won']) + '/' + str(p['n']):>7}")
|
|
||||||
return "\n".join(lines)
|
|
||||||
|
|
||||||
|
|
||||||
# -- driver ----------------------------------------------------------------------
|
|
||||||
|
|
||||||
def _save(results: list[dict], out: str) -> None:
|
|
||||||
Path(out).parent.mkdir(parents=True, exist_ok=True)
|
|
||||||
Path(out).write_text(json.dumps(results, indent=1))
|
|
||||||
|
|
||||||
|
|
||||||
def _say(r: dict, window: int) -> None:
|
|
||||||
m = r["metrics"].get(str(window))
|
|
||||||
a = r["arousal"].get(str(window))
|
|
||||||
extra = ""
|
|
||||||
if m is not None:
|
|
||||||
extra = f" steady={m['steady']:.3e} n_sw={m['n_switches']}"
|
|
||||||
if a is not None:
|
|
||||||
extra += f" a_peak@{peak_lag(a['by_lag'])} a_far={a['far']:.3f}"
|
|
||||||
print(f"{r['condition']:<16} k={r['kappa']:<5g} {r['affect']:<18} "
|
|
||||||
f"dur={r['t_min']}-{r['t_max']:<6} seed={r['seed']:<3}{extra}", flush=True)
|
|
||||||
|
|
||||||
|
|
||||||
def main() -> None:
|
|
||||||
ap = argparse.ArgumentParser()
|
|
||||||
ap.add_argument("--part", required=True,
|
|
||||||
choices=["timing", "rho-fast", "best", "duration"])
|
|
||||||
ap.add_argument("--seeds", default=None)
|
|
||||||
ap.add_argument("--steps", type=int, default=STEPS)
|
|
||||||
ap.add_argument("--window", type=int, default=20)
|
|
||||||
ap.add_argument("--rho-a", type=float, default=None, help="best/rho-fast: the setting to run")
|
|
||||||
ap.add_argument("--rho-slow", type=float, default=None)
|
|
||||||
ap.add_argument("--kappa", type=float, default=KAPPA_PRIMARY)
|
|
||||||
ap.add_argument("--durations", default=None,
|
|
||||||
help="duration: comma-separated t_min-t_max pairs, e.g. 10-20,40-80")
|
|
||||||
ap.add_argument("--out", required=True)
|
|
||||||
a = ap.parse_args()
|
|
||||||
seeds = tuple(int(s) for s in a.seeds.split(",")) if a.seeds else None
|
|
||||||
results: list[dict] = []
|
|
||||||
|
|
||||||
if a.part == "timing":
|
|
||||||
for ra in RHO_A:
|
|
||||||
for rs in RHO_SLOW:
|
|
||||||
for seed in seeds or TIMING_SEEDS:
|
|
||||||
r = run_one("grp_k0", seed, 0.0, _cfg(ra, rs),
|
|
||||||
steps=a.steps, windows=(a.window,))
|
|
||||||
_say(r, a.window); results.append(r)
|
|
||||||
_save(results, a.out)
|
|
||||||
print(); print(timing_table(results, a.window))
|
|
||||||
|
|
||||||
elif a.part == "rho-fast":
|
|
||||||
ra = a.rho_a if a.rho_a is not None else 0.5
|
|
||||||
rs = a.rho_slow if a.rho_slow is not None else 0.02
|
|
||||||
for rf in (0.1, 0.2, 0.5, 0.9):
|
|
||||||
if rf <= rs:
|
|
||||||
continue
|
|
||||||
for seed in seeds or TIMING_SEEDS:
|
|
||||||
r = run_one("grp_k0", seed, 0.0, _cfg(ra, rs, rf),
|
|
||||||
steps=a.steps, windows=(a.window,))
|
|
||||||
_say(r, a.window); results.append(r)
|
|
||||||
_save(results, a.out)
|
|
||||||
print(); print(timing_table(results, a.window))
|
|
||||||
|
|
||||||
elif a.part == "best":
|
|
||||||
acfg = _cfg(a.rho_a, a.rho_slow)
|
|
||||||
for kappa in (a.kappa, *KAPPA_CONTEXT):
|
|
||||||
for seed in seeds or BEST_SEEDS:
|
|
||||||
r = run_one("grp_k", seed, kappa, acfg, steps=a.steps, windows=(a.window,))
|
|
||||||
_say(r, a.window); results.append(r)
|
|
||||||
for seed in seeds or BEST_SEEDS: # the paired kappa=0 control at the same acfg
|
|
||||||
r = run_one("grp_k0", seed, 0.0, acfg, steps=a.steps, windows=(a.window,))
|
|
||||||
_say(r, a.window); results.append(r)
|
|
||||||
_save(results, a.out)
|
|
||||||
base = [r for r in results if r["condition"] == "grp_k0"]
|
|
||||||
print()
|
|
||||||
for kappa in (a.kappa, *KAPPA_CONTEXT):
|
|
||||||
arm = [r for r in results if r["condition"] == "grp_k" and r["kappa"] == kappa]
|
|
||||||
p = paired(base, arm, a.window)
|
|
||||||
print(f"kappa={kappa:<5g} grp_k0/grp_k mean={p['mean']:.3f} "
|
|
||||||
f"median={p['median']:.3f} won={p['won']}/{p['n']} "
|
|
||||||
+ " ".join(f"{x:.2f}" for x in p["per_seed"]))
|
|
||||||
|
|
||||||
elif a.part == "duration":
|
|
||||||
acfg = AffectConfig() # Part 3 runs at kappa=0 in both arms; affect is untouched here
|
|
||||||
grid = ([tuple(int(x) for x in d.split("-")) for d in a.durations.split(",")]
|
|
||||||
if a.durations else DURATIONS)
|
|
||||||
for t_min, t_max in grid:
|
|
||||||
for stateless in (False, True):
|
|
||||||
for seed in seeds or DURATION_SEEDS:
|
|
||||||
r = run_one("grp_k0", seed, 0.0, acfg, steps=a.steps, windows=WINDOWS,
|
|
||||||
t_min=t_min, t_max=t_max, stateless=stateless)
|
|
||||||
_say(r, min(w for w in WINDOWS if w < t_min)); results.append(r)
|
|
||||||
_save(results, a.out)
|
|
||||||
for w in WINDOWS:
|
|
||||||
print(f"\nwindow={w}"); print(duration_table(results, w))
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
main()
|
|
||||||
Reference in new issue
Block a user