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
273 lines
12 KiB
Python
273 lines
12 KiB
Python
"""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
|
|
|
|
|
|
def gabor_kernel(sigma: float = 3.0, seed: int = 0, kfreq: float = 0.35) -> torch.Tensor:
|
|
"""(CELLS, D) true kernel: a smooth, band-limited function of the displacement.
|
|
|
|
Smooth on purpose. A CPPN that cannot interpolate THIS has not failed a hard case, it has
|
|
failed the easy one -- which is what makes a null here worth recording.
|
|
"""
|
|
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()
|
|
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 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
|
|
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) -> 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))
|
|
for p in m.parameters():
|
|
p.requires_grad_(False)
|
|
return m
|
|
|
|
|
|
def holdout_cells(kind: str, frac: float, seed: int) -> torch.Tensor:
|
|
"""(CELLS,) bool, True = withheld from training."""
|
|
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 == "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) -> dict:
|
|
tea = teacher(seed, kfreq)
|
|
held = holdout_cells(kind, frac, 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 = 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, "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"])
|
|
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("--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))
|
|
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.holdout} hold-out, frac={args.frac}, 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()
|