Files
ailed-rp/tests/test_core.py
T
chrnxandClaude Opus 5 3ef8868ffa test: assert the two RP properties that need no experiment
One parameter set serves any entity count, and entity order carries no meaning.
Both are properties of the construction rather than results, and both are what
distinguishes the RP from a fixed-weight layer -- which is not worse at variable
N, it is undefined there.

Permutation equivariance was already asserted at the RP level; the Organism
keys memory by entity id, which is a second place order could leak, so it gets
its own test. Checked against a broken RP (an index-dependent term in the pooled
message): both permutation tests fail there and no others do.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HCydQraDSoZ9WoTm2v23Eb
2026-09-07 17:02:38 -05:00

217 lines
8.3 KiB
Python

import torch
from ailed.core import AffectiveCPPN, RelationalPerceptron
torch.manual_seed(0)
N, K, D_ATTR, E, C, H = 6, 2, 3, 1, 2, 8
def flat_diff(coords):
return coords[None, :, :] - coords[:, None, :] # r_ij = c_j - c_i
def make_inputs():
attrs = torch.randn(N, D_ATTR)
coords = torch.rand(N, K)
edge = torch.zeros(N, N, E); edge[..., 0] = 1.0
mask = torch.ones(N, N)
ctx = torch.tensor([0.1, 0.2])
return attrs, coords, edge, mask, ctx
def test_cppn_shape():
cppn = AffectiveCPPN(K, E, C, hidden=16, out_dim=H)
_, coords, edge, _, ctx = make_inputs()
out = cppn(flat_diff(coords), edge, ctx)
assert out.shape == (N, N, H)
def test_cppn_context_changes_kernel_shape_not_only_scale():
cppn = AffectiveCPPN(K, E, C, hidden=16, out_dim=H)
_, coords, edge, _, _ = make_inputs()
r = flat_diff(coords)
a = cppn(r, edge, torch.tensor([0.0, 0.0]))
b = cppn(r, edge, torch.tensor([0.0, 1.0]))
ratio = b / (a + 1e-9)
assert ratio.std() > 1e-3 # a pure gain would give a constant ratio
def test_rp_shape():
rp = RelationalPerceptron(D_ATTR, K, E, C, hidden_dim=H)
attrs, coords, edge, mask, ctx = make_inputs()
h = rp(attrs, flat_diff(coords), edge, mask, ctx)
assert h.shape == (N, H)
def test_rp_translation_invariance():
rp = RelationalPerceptron(D_ATTR, K, E, C, hidden_dim=H)
attrs, coords, edge, mask, ctx = make_inputs()
h0 = rp(attrs, flat_diff(coords), edge, mask, ctx)
h1 = rp(attrs, flat_diff(coords + 3.7), edge, mask, ctx)
assert torch.allclose(h0, h1, atol=1e-5)
def test_rp_permutation_equivariance():
rp = RelationalPerceptron(D_ATTR, K, E, C, hidden_dim=H)
attrs, coords, edge, mask, ctx = make_inputs()
perm = torch.randperm(N)
h0 = rp(attrs, flat_diff(coords), edge, mask, ctx)
h1 = rp(attrs[perm], flat_diff(coords[perm]), edge[perm][:, perm], mask[perm][:, perm], ctx)
assert torch.allclose(h0[perm], h1, atol=1e-5)
def test_rp_mask_removes_neighbours():
rp = RelationalPerceptron(D_ATTR, K, E, C, hidden_dim=H)
attrs, coords, edge, mask, ctx = make_inputs()
r = flat_diff(coords)
full = rp(attrs, r, edge, mask, ctx)
mask2 = mask.clone(); mask2[0, 1:] = 0.0 # entity 0 sees only itself
attrs2 = attrs.clone(); attrs2[1:] += 5.0 # perturb everyone else
masked_a = rp(attrs, r, edge, mask2, ctx)
masked_b = rp(attrs2, r, edge, mask2, ctx)
assert torch.allclose(masked_a[0], masked_b[0], atol=1e-5)
assert not torch.allclose(full[0], masked_a[0])
from ailed.core import GatedRelationalPerceptron, Organism, detach_memory
def test_grp_kappa_zero_ignores_arousal():
grp = GatedRelationalPerceptron(H, kappa=0.0)
h, M = torch.randn(N, H), torch.randn(N, H)
assert torch.allclose(grp(h, M, 0.0), grp(h, M, 1.0))
def test_grp_high_arousal_overwrites():
grp = GatedRelationalPerceptron(H, kappa=50.0)
h, M = torch.randn(N, H), torch.randn(N, H)
out = grp(h, M, 1.0)
cand = torch.tanh(grp.cand(torch.cat([h, M], -1)))
assert torch.allclose(out, cand, atol=1e-3)
def test_grp_gate_saturated_keeps():
grp = GatedRelationalPerceptron(H, kappa=1.0)
with torch.no_grad():
grp.gate.weight.zero_(); grp.gate.bias.fill_(50.0)
h, M = torch.randn(N, H), torch.randn(N, H)
assert torch.allclose(grp(h, M, 0.0), M, atol=1e-3)
def make_org(**kw):
return Organism(attr_dim=D_ATTR, coord_dim=K, target_dim=2, hidden_dim=H, cppn_hidden=16, **kw)
def test_organism_memory_lifecycle():
org = make_org(memory=True)
attrs, coords, _, _, _ = make_inputs()
r = flat_diff(coords)
ids = list(range(N))
y, mem = org(attrs, r, ids, (0.0, 0.0), {})
assert y.shape == (N, 2)
assert set(mem) == set(ids)
# entity 0 leaves, entity 99 is born
ids2 = ids[1:] + [99]
y2, mem2 = org(attrs, r, ids2, (0.0, 0.0), mem)
assert 0 not in mem2 and 99 in mem2
# a newborn's previous state was zero: its update equals the update from an explicit zero
_, mem3 = org(attrs, r, ids2, (0.0, 0.0), {**mem, 99: torch.zeros(H)})
assert torch.allclose(mem2[99], mem3[99])
# memory must be load-bearing: zeroing a survivor's incoming state changes the outcome
survivor = ids2[0]
zeroed_mem = {i: torch.zeros(H) for i in mem}
y2_zeroed, mem2_zeroed = org(attrs, r, ids2, (0.0, 0.0), zeroed_mem)
assert not torch.allclose(y2, y2_zeroed)
assert not torch.allclose(mem2[survivor], mem2_zeroed[survivor])
def test_organism_without_memory_ignores_history():
org = make_org(memory=False)
attrs, coords, _, _, _ = make_inputs()
r = flat_diff(coords); ids = list(range(N))
y0, mem0 = org(attrs, r, ids, (0.0, 0.0), {})
y1, _ = org(attrs, r, ids, (0.0, 0.0), {i: torch.randn(H) for i in ids})
assert torch.allclose(y0, y1) and mem0 == {}
def test_organism_context_defaults_to_affect():
org = make_org(memory=True)
attrs, coords, _, _, _ = make_inputs()
r = flat_diff(coords); ids = list(range(N))
y_a, _ = org(attrs, r, ids, (0.3, 0.6), {})
y_b, _ = org(attrs, r, ids, (0.3, 0.6), {}, context=torch.tensor([0.3, 0.6]))
y_c, _ = org(attrs, r, ids, (0.3, 0.6), {}, context=torch.zeros(2))
assert torch.allclose(y_a, y_b)
assert not torch.allclose(y_a, y_c)
def test_gradient_flows_through_memory_across_steps():
# A single step already sends gradient into the CPPN (it runs every call, memory
# or not) so that alone doesn't prove the recurrence is live. Compare the real
# 3-step rollout against one where memory is detached after every step, which
# severs the cross-step graph but leaves each step's own CPPN call intact: if
# memory actually carries gradient across time the two must disagree.
org = make_org(memory=True, kappa=1.0)
attrs, coords, _, _, _ = make_inputs()
r = flat_diff(coords); ids = list(range(N))
mem = {}
for _ in range(3):
y, mem = org(attrs, r, ids, (0.0, 0.5), mem)
y.pow(2).sum().backward()
g_recurrent = org.rp.cppn.l1.weight.grad.clone()
org.zero_grad()
mem = {}
for _ in range(3):
y, mem = org(attrs, r, ids, (0.0, 0.5), mem)
mem = detach_memory(mem)
y.pow(2).sum().backward()
g_severed = org.rp.cppn.l1.weight.grad.clone()
assert g_recurrent.abs().sum() > 0
assert not torch.allclose(g_recurrent, g_severed)
def test_detach_memory_cuts_graph():
org = make_org(memory=True)
attrs, coords, _, _, _ = make_inputs()
r = flat_diff(coords); ids = list(range(N))
_, mem = org(attrs, r, ids, (0.0, 0.0), {})
assert all(m.requires_grad for m in mem.values())
assert not any(m.requires_grad for m in detach_memory(mem).values())
# --- Property card rows: what the RP is, asserted rather than assumed. -------------------
# These two are not experiments and must never become them. They state properties that hold
# by construction, and exist so a future change cannot remove one silently. Both were checked
# against a deliberately broken RP (see results/rp_properties.md) and both failed there.
def test_rp_same_parameters_any_n():
"""One parameter set serves any entity count. A fixed-weight layer over N entities is
not worse here, it is undefined: its input dimension is N (or N^2) and has to be chosen."""
rp = RelationalPerceptron(D_ATTR, K, E, C, hidden_dim=H)
before = [p.clone() for p in rp.parameters()]
for n in (2, 7, 32):
attrs, coords = torch.randn(n, D_ATTR), torch.rand(n, K)
edge = torch.zeros(n, n, E); edge[..., 0] = 1.0
h = rp(attrs, flat_diff(coords), edge, torch.ones(n, n), torch.tensor([0.1, 0.2]))
assert h.shape == (n, H)
assert all(torch.equal(a, b) for a, b in zip(before, rp.parameters())) # no shape adapted
def test_organism_permutation_equivariance_with_memory():
"""The RP-level test uses positional tensors; the Organism keys memory by entity id, which
is a second place the order could leak in."""
org = make_org(memory=True)
attrs, coords, _, _, _ = make_inputs()
r, ids = flat_diff(coords), list(range(N))
mem = {i: torch.randn(H) for i in ids}
y0, m0 = org(attrs, r, ids, (0.0, 0.0), mem)
perm = torch.randperm(N)
ids_p = [ids[k] for k in perm.tolist()]
y1, m1 = org(attrs[perm], flat_diff(coords[perm]), ids_p, (0.0, 0.0), mem)
assert torch.allclose(y0[perm], y1, atol=1e-5)
assert all(torch.allclose(m0[i], m1[i], atol=1e-5) for i in ids)