"""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()