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
This commit is contained in:
chrnxandClaude Opus 5 committed 2026-09-07 17:02:46 -05:00
1 parent 79b0324537
commit 6c545fd035
5 files changed
+696

No files matched your search

+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)}")
+140
View File
@@ -0,0 +1,140 @@
# 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** | **Defined: asserted.** Generalises: *untested* | `test_rp_same_parameters_any_n`. ~9k params served N=2..32 throughout the chess arc |
| 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 *is* open is a separate claim that the wording invites confusion with: that the RP still
**works** at an N it never trained on. Defined ≠ competent. Untested (`≤16 → 17-32`).
### 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.
## What is open, in order
1. **Unseen N** (row 1, second half). Train ≤16 entities, evaluate 17-32. Now the first item:
after `unseen.md`, row 1 is the RP's least qualified distinguishing property.
2. **Unseen relations in a CONTINUOUS space** (row 3, second half). The measured result is
bounded by the relation space having been enumerable. Where it is not, the table control
cannot be built and the comparison changes shape.
3. **`omega`.** Raised by `unseen.md` and not on this card before: the bandwidth is a free knob
that moved a result 17x, and every chess number was produced at one unexamined value.
4. **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`.
+150
View File
@@ -0,0 +1,150 @@
# Can the kernel answer for a relation it never saw?
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.
+91
View File
@@ -0,0 +1,91 @@
"""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 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
+266
View File
@@ -0,0 +1,266 @@
"""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) -> 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) * 0.35 # spatial frequencies, low by design
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) -> nn.Module:
m = make_model("table", seed + 1000)
with torch.no_grad():
m["rp"].cppn.w.copy_(gabor_kernel(seed=seed))
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) -> dict:
tea = teacher(seed)
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, "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("--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))
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()