Files
ailed-rp/tests/test_core.py
T

182 lines
6.6 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())