"""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 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 != "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) return {"seed": seed, "arm": arm, "omega": omega, "kfreq": kfreq, "teacher": teacher_kind, "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()