From 95f10f2953168878cc0d343eabe838c9c1962805 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Tue, 1 Sep 2026 23:51:43 -0500 Subject: [PATCH] =?UTF-8?q?feat(core):=20gated=20relational=20perceptron?= =?UTF-8?q?=20and=20organism=20with=20per-entity=20memory=20(spec=20=C2=A7?= =?UTF-8?q?4)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Sonnet 5 Claude-Session: https://claude.ai/code/session_01G1oTwYmaHDJnnqLdmtQW9i --- src/ailed/__init__.py | 6 +++ src/ailed/core.py | 63 +++++++++++++++++++++++++++++++ tests/test_core.py | 87 +++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 156 insertions(+) diff --git a/src/ailed/__init__.py b/src/ailed/__init__.py index 1fa96c2..583a84e 100644 --- a/src/ailed/__init__.py +++ b/src/ailed/__init__.py @@ -1 +1,7 @@ """AILED: relational-affective organism. See AILED_General_Specification.md.""" +from ailed.affect import Affect, AffectConfig, decay, update +from ailed.core import (AffectiveCPPN, GatedRelationalPerceptron, Organism, + RelationalPerceptron, detach_memory) + +__all__ = ["Affect", "AffectConfig", "decay", "update", "AffectiveCPPN", + "GatedRelationalPerceptron", "Organism", "RelationalPerceptron", "detach_memory"] diff --git a/src/ailed/core.py b/src/ailed/core.py index 86c29f1..b734389 100644 --- a/src/ailed/core.py +++ b/src/ailed/core.py @@ -44,3 +44,66 @@ class RelationalPerceptron(nn.Module): 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) + + +class GatedRelationalPerceptron(nn.Module): + """Per-entity recurrent state with a candidate transform and an arousal-biased gate. + + g = σ(W_g [h‖M] + b_g − κ a); M̃ = tanh(W_c [h‖M] + b_c); M ← (1−g) M̃ + g M + g→1 keeps, g→0 overwrites. κ = 0 disables affect on the gate. + """ + + def __init__(self, hidden_dim: int, kappa: float): + super().__init__() + self.gate = nn.Linear(2 * hidden_dim, hidden_dim) + self.cand = nn.Linear(2 * hidden_dim, hidden_dim) + self.kappa = kappa + + def forward(self, h: Tensor, M: Tensor, arousal: float) -> Tensor: + hm = torch.cat([h, M], dim=-1) + g = torch.sigmoid(self.gate(hm) - self.kappa * arousal) + cand = torch.tanh(self.cand(hm)) + return (1.0 - g) * cand + g * M + + +def detach_memory(memory: dict[int, Tensor]) -> dict[int, Tensor]: + return {k: v.detach() for k, v in memory.items()} + + +class Organism(nn.Module): + """Contract A: RP → GRP → linear readout. Memory is a dict keyed by stable entity id.""" + + def __init__(self, attr_dim: int, coord_dim: int, target_dim: int, n_edge_types: int = 1, + context_dim: int = 2, hidden_dim: int = 32, cppn_hidden: int = 32, + omega: float = 10.0, kappa: float = 0.0, memory: bool = True): + super().__init__() + self.n_edge_types = n_edge_types + self.hidden_dim = hidden_dim + self.use_memory = memory + self.rp = RelationalPerceptron(attr_dim, coord_dim, n_edge_types, context_dim, + hidden_dim, cppn_hidden, omega) + self.grp = GatedRelationalPerceptron(hidden_dim, kappa) if memory else None + self.out = nn.Linear(hidden_dim, target_dim) + + def forward(self, attrs: Tensor, r: Tensor, ids: list[int], affect: tuple[float, float], + memory: dict[int, Tensor], context: Tensor | None = None, + edge_types: Tensor | None = None, mask: Tensor | None = None + ) -> tuple[Tensor, dict[int, Tensor]]: + n = attrs.shape[0] + valence, arousal = affect # by name; the tuple is Affect.axes + if context is None: + context = torch.tensor([valence, arousal], dtype=attrs.dtype) + if edge_types is None: + edge_types = torch.zeros(n, n, dtype=torch.long) + if mask is None: + mask = torch.ones(n, n, dtype=attrs.dtype) + edge_onehot = nn.functional.one_hot(edge_types, self.n_edge_types).to(attrs.dtype) + + h = self.rp(attrs, r, edge_onehot, mask, context) + if not self.use_memory: + return self.out(h), {} + zero = torch.zeros(self.hidden_dim, dtype=attrs.dtype) + M_prev = torch.stack([memory.get(i, zero) for i in ids]) + M = self.grp(h, M_prev, arousal) + new_memory = {i: M[k] for k, i in enumerate(ids)} # ids that left are dropped here + return self.out(M), new_memory diff --git a/tests/test_core.py b/tests/test_core.py index b079447..7dc49ca 100644 --- a/tests/test_core.py +++ b/tests/test_core.py @@ -70,3 +70,90 @@ def test_rp_mask_removes_neighbours(): 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]) + + +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_reaches_cppn_through_memory(): + 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 = org.rp.cppn.l1.weight.grad + assert g is not None and g.abs().sum() > 0 + + +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())