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

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KAWnnPg2qvmLNySamE2k85
This commit is contained in:
chrnxandClaude Opus 5 committed 2026-09-01 23:46:45 -05:00
1 parent 8822ab3cd8
commit 23f06e1ff5
2 files changed
+117

No files matched your search

+45
View File
@@ -0,0 +1,45 @@
"""Affective CPPN, Relational Perceptron, Gated Relational Perceptron, Organism.
Spec §3–§4. Shapes: N entities, k coords, d attrs, E edge types, C context dims, D hidden.
"""
from __future__ import annotations
import torch
from torch import Tensor, nn
class AffectiveCPPN(nn.Module):
"""m_ij = W2 sin(omega * (W1 [r_ij ‖ onehot(e_ij) ‖ context] + b1)). One weight per channel."""
def __init__(self, coord_dim: int, n_edge_types: int, context_dim: int,
hidden: int, out_dim: int, omega: float = 10.0):
super().__init__()
self.l1 = nn.Linear(coord_dim + n_edge_types + context_dim, hidden)
self.l2 = nn.Linear(hidden, out_dim)
# omega is the calibration knob for kernel bandwidth; default
# Linear init cannot reach the ~1/sigma frequencies a local kernel needs.
self.omega = omega
def forward(self, r: Tensor, edge_onehot: Tensor, context: Tensor) -> Tensor:
n = r.shape[0]
ctx = context.view(1, 1, -1).expand(n, n, -1)
z = torch.cat([r, edge_onehot, ctx], dim=-1)
return self.l2(torch.sin(self.omega * self.l1(z)))
class RelationalPerceptron(nn.Module):
"""h_i = tanh( mean_{j in N_i} m_ij ⊙ (W_feat p_j) + b )."""
def __init__(self, attr_dim: int, coord_dim: int, n_edge_types: int, context_dim: int,
hidden_dim: int, cppn_hidden: int = 32, omega: float = 10.0):
super().__init__()
self.cppn = AffectiveCPPN(coord_dim, n_edge_types, context_dim, cppn_hidden, hidden_dim, omega)
self.feat = nn.Linear(attr_dim, hidden_dim, bias=False)
self.bias = nn.Parameter(torch.zeros(hidden_dim))
def forward(self, attrs: Tensor, r: Tensor, edge_onehot: Tensor, mask: Tensor, context: Tensor) -> Tensor:
m = self.cppn(r, edge_onehot, context) # (N,N,D)
f = self.feat(attrs) # (N,D)
msg = m * f[None, :, :] * mask[:, :, None] # (N,N,D)
deg = mask.sum(dim=1, keepdim=True).clamp(min=1.0) # (N,1)
return torch.tanh(msg.sum(dim=1) / deg + self.bias)
+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])