feat(core): affective CPPN and relational perceptron (spec §3–§4)

This commit is contained in:
chrnx committed 2026-09-01 23:46:45 -05:00
1 parent 7f9968b0b2
commit 89e892f051
2 files changed
+117

No files matched your search

+72
View File
@@ -0,0 +1,72 @@
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])