The thinking behind the organism, versioned alongside the three code repos rather than living only on one machine. - AILED_General_Specification.md, the authoritative design, and the implementation plan the code was built from - AGENTS.md, the project-wide rules, including the two that were learned the hard way: this is not a performance benchmark, and a null recorded early beats a claim propped up later - the nine superseded module specs, each carrying a banner naming what replaced it - .sdd/, the execution ledger and every task brief and report: each ruling taken, what it would cost if wrong, every correction, and every number verified independently The three code repos are siblings, each its own repository, and are git-ignored here so nothing is nested. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01KAWnnPg2qvmLNySamE2k85
201 lines
8.6 KiB
Plaintext
201 lines
8.6 KiB
Plaintext
REPO: ailed range 85a0f9d..HEAD
|
||
95f10f2 feat(core): gated relational perceptron and organism with per-entity memory (spec §4)
|
||
---- stat ----
|
||
src/ailed/__init__.py | 6 ++++
|
||
src/ailed/core.py | 63 +++++++++++++++++++++++++++++++++++++
|
||
tests/test_core.py | 87 +++++++++++++++++++++++++++++++++++++++++++++++++++
|
||
3 files changed, 156 insertions(+)
|
||
---- diff -U10 ----
|
||
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
|
||
@@ -37,10 +37,73 @@ class RelationalPerceptron(nn.Module):
|
||
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)
|
||
+
|
||
+
|
||
+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
|
||
@@ -63,10 +63,97 @@ 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])
|
||
+
|
||
+
|
||
+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())
|