Compare commits

...
7 Commits
Author SHA1 Message Date
chrnxandClaude Opus 5 4fc5b38be9 feat: learned-frame arm and an orbit-consistency diagnostic
rp_learn_K learns K linear maps on the displacement and averages the CPPN over
them, so a set closed under the domain's group makes the kernel invariant to it
without anyone naming the group. orbit_consistency measures that invariance from
the kernel's behaviour rather than its parameters, validated against the two
kernels whose answers are known exactly.

Both false-positive modes are instrumented: fit-versus-held-out separates extra
capacity from discovery, and the spread of the learned maps catches a collapse
to K=1.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HCydQraDSoZ9WoTm2v23Eb
2026-09-07 19:45:14 -05:00
chrnxandClaude Opus 5 ff8ccbc819 feat: D4-invariant kernel input recovers the knight rule from partial support
InvariantCPPN canonicalises the displacement to (min|dx|, max|dy|), collapsing
the square's eight symmetries to one orbit, plus a knight_sym teacher whose
eight L-squares carry one value and are therefore a genuine D4 orbit.

Trained on six of the eight, it recovers the other two at 0.4% of the floor on
6/6 seeds where the raw-displacement kernel sits above the floor.

Two controls, both predicted beforehand: on a teacher whose eight squares share
a support but not a value the invariance is worse than nothing, and on a smooth
teacher with no D4 symmetry it costs 31x.

The arm dispatch now raises on unknown names -- an edit had silently failed to
land and rp_inv ran as plain rp, which looked like a null.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HCydQraDSoZ9WoTm2v23Eb
2026-09-07 19:12:03 -05:00
chrnxandClaude Opus 5 3feba1baac feat: vary kernel sharpness and hold-out structure -- both readings change
Four teacher families on one axis (how predictable the kernel is from its
neighbours): smooth, high-frequency, a rule-generated sparse knight, and iid
noise as the negative control, which is asserted to have neighbour correlation
below 0.2 where the smooth teacher's is above 0.8.

The knight teacher forced a new hold-out: most of its cells are exactly zero, so
withholding uniformly asks nothing and the floor collapses. --holdout support
withholds cells the kernel uses, closed under negation since a pair contributes
r and -r.

Under it the CPPN beats a lookup plus blur 4.4x on smooth and 3.0x on
high-frequency, 6/6 seeds, reversing the earlier headline. And on the knight
nothing generalises at all -- both arms at or above the floor.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HCydQraDSoZ9WoTm2v23Eb
2026-09-07 18:42:15 -05:00
chrnxandClaude Opus 5 ac10bbca4e feat: psi as a continuous kernel axis -- the deciding test
Teacher changes the kernel's shape with psi (valence rotates the frequency,
arousal widens the envelope), never its gain, guarded by a test checked against
a teacher deliberately reduced to a gain.

The CPPN answers for withheld psi at 1.18x its trained-psi error from 720
parameters. A binned table plus interpolation along psi matches it on 6 seeds of
6 using 57,600. Not a sample-budget artefact: the largest table at 4x the steps
fits three times better and generalises not at all better.

The bare tables' 19x failure is arithmetic -- their bin never saw gradient --
and is labelled as scale rather than evidence, which is why the interp arms
exist at all.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HCydQraDSoZ9WoTm2v23Eb
2026-09-07 18:12:53 -05:00
chrnxandClaude Opus 5 d95383f8a2 feat: omega curve and unseen-N, the two steps before psi
omega.md: a plateau at [1,4] that does not track the domain across a 4.7x range,
so the bandwidth is a knob that was set wrong rather than a defect to design
around. omega=8 is an optimisation cliff, not a mis-tune. The project default of
10 is outside the plateau.

scale.md: one parameter set works at an entity count it never trained on --
trained on N<=16 it beats the oracle at N=32 -- and a lookup table does it too.
Read against an oracle because the mse/floor ratio is not comparable across N,
which is asserted as a test rather than claimed in prose. The cost runs
large->small only, at 2.28x, which makes it the pooling's 1/deg dilution rather
than a degree-distribution shift.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HCydQraDSoZ9WoTm2v23Eb
2026-09-07 17:45:41 -05:00
chrnxandClaude Opus 5 6c545fd035 feat: unseen relations -- the one property that separates the RP from a GNN
A GNN holds fixed weights per edge type: a lookup with one entry per discrete
relation. The CPPN computes weights from geometry, so it has something to say
about a displacement absent from training. Every chess run trained and evaluated
on the same offset grid, so this had never been tested.

Student-teacher with an analytic Gabor kernel; held-out cells masked out of
training via the RP's own mask argument; evaluation always on pairs so seen and
unseen measure the same object. Eight seeds, two hold-out structures.

The property is real -- held-out error 1.28x seen error, lower on 3/8 seeds -- and
smaller than the framing assumed. The bare table fails by construction and is
labelled as scale, not evidence. Against a table plus neighbour diffusion the
CPPN wins interpolation 2x on 6/8 seeds and loses extrapolation on 8/8. At
omega=10, the default every chess run used, it is 17x worse and below the
smoothed table even on interpolation.

The boundary is the useful part: the diffusion control exists only because the
relation space was enumerable. Chess is exactly such a domain.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HCydQraDSoZ9WoTm2v23Eb
2026-09-07 17:02:46 -05:00
chrnx 79b0324537 exp: colour in the kernel helps exactly the pieces whose law depends on it
rp_typecol gains on pawn (+0.085), knight (+0.010) and bishop (+0.015) and loses on rook
(-0.022), queen (-0.015) and king (-0.010). The owner named that split in advance from chess,
not from the data. A capacity story predicts a uniform gain and the sign flip rules it out:
twelve kernels halve the data behind each, which pays only where colour changes the law.

First arm to exceed the rule-knowing control in aggregate, 0.8353 against 0.8305 -- by a
different route than rp, which beats it on rook, queen and king where typecol does not.
2026-09-02 20:10:20 -05:00
18 changed files with 2265 additions and 2 deletions

No files matched your search

+46
View File
@@ -0,0 +1,46 @@
"""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")
+39
View File
@@ -0,0 +1,39 @@
"""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}")
+49
View File
@@ -0,0 +1,49 @@
"""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)}")
+269
View File
@@ -0,0 +1,269 @@
"""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()
+26 -2
View File
@@ -90,8 +90,32 @@ The likely cause is specific and testable: `e_ij` carries the piece **type** and
`own_rank` — rank counted from the piece's own back rank — is present in this run and did not `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. fix it on its own, which points at the colour rather than the orientation.
**In flight:** `rp_typecol`, twelve kernels (type x colour) instead of six. Seed 0 reads **`rp_typecol` confirms it, and splits along a line predicted in advance.** Twelve kernels
**0.8330**, above `shape`'s 0.8305 and above `rp`'s 0.8161. One seed, not a result yet. (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 ## Limits
+109
View File
@@ -0,0 +1,109 @@
# 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.
+90
View File
@@ -0,0 +1,90 @@
# 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.
+88
View File
@@ -0,0 +1,88 @@
# 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
```
+114
View File
@@ -0,0 +1,114 @@
# 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.
+195
View File
@@ -0,0 +1,195 @@
# 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`.
+86
View File
@@ -0,0 +1,86 @@
# 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.
+113
View File
@@ -0,0 +1,113 @@
# 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
```
+157
View File
@@ -0,0 +1,157 @@
# 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.
+124
View File
@@ -0,0 +1,124 @@
"""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()
+81
View File
@@ -0,0 +1,81 @@
"""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])
+44
View File
@@ -0,0 +1,44 @@
"""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]
+193
View File
@@ -0,0 +1,193 @@
"""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)
+442
View File
@@ -0,0 +1,442 @@
"""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()