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
168 lines
7.1 KiB
Python
168 lines
7.1 KiB
Python
"""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
|