# Task 4: GRP and Organism (spec §4) ## Global constraints - Root `ia-stuff/` is **not** a git repo; `ailed/`, `experiments/`, `paper/` each are. Commit inside the repo you touched. - No hand-written backward passes. Autograd only (spec §1, §11). - $\psi$ never carries gradient: it is built from `loss.item()` (spec §5). - Every oracle is opt-in and must leave the non-oracle trajectory byte-identical (spec §7). - $\kappa = 0$ must be a single flag that disables affect on the gate (spec §4). - Affect axes are read by name (`valence`, `arousal`), never by position, outside `Organism.forward` (spec §5). - Commit messages end with the attribution trailer of the session driving this plan: ``` Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_01KAWnnPg2qvmLNySamE2k85 ``` Implementers use these two lines verbatim, not the attribution of their own subagent session — the commits belong to one plan run. **Files:** - Modify: `ailed/src/ailed/core.py` (append) - Modify: `ailed/src/ailed/__init__.py` - Test: `ailed/tests/test_core.py` (append) **Interfaces:** - Consumes: `RelationalPerceptron` from Task 3. - Produces: - `GatedRelationalPerceptron(hidden_dim, kappa: float)`; `forward(h: (N,D), M: (N,D), arousal: float) -> (N,D)` - `Organism(attr_dim, coord_dim, target_dim, n_edge_types=1, context_dim=2, hidden_dim=32, cppn_hidden=32, omega=10.0, kappa=0.0, memory=True)` - `Organism.forward(attrs, r, 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 (N,target_dim), dict[int, Tensor]]` - `detach_memory(memory: dict[int, Tensor]) -> dict[int, Tensor]` - [ ] **Step 1: Append the failing tests** Append to `ailed/tests/test_core.py`: ```python 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()) ``` - [ ] **Step 2: Run to verify failure** Run: `cd ailed && uv run pytest tests/test_core.py -q` Expected: `ImportError: cannot import name 'GatedRelationalPerceptron'`. - [ ] **Step 3: Implement** Append to `ailed/src/ailed/core.py`: ```python 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 ``` `ailed/src/ailed/__init__.py`: ```python """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"] ``` - [ ] **Step 4: Run to verify pass** Run: `cd ailed && uv run pytest -q` Expected: all tests pass (`1 + 9 + 14`). - [ ] **Step 5: Commit** ```bash cd ailed && git add -A && git commit -q -m "feat(core): gated relational perceptron and organism with per-entity memory (spec §4) Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_01KAWnnPg2qvmLNySamE2k85" ```