# Task 4 report: Gated Relational Perceptron and Organism ## What was written Followed the brief's Step 1–5 essentially verbatim (the brief's code was already correct and consistent with the Task 3 signatures in `src/ailed/core.py`). **`ailed/tests/test_core.py`** — appended 8 tests after the existing 6 (Task 3): `test_grp_kappa_zero_ignores_arousal`, `test_grp_high_arousal_overwrites`, `test_grp_gate_saturated_keeps`, `test_organism_memory_lifecycle`, `test_organism_without_memory_ignores_history`, `test_organism_context_defaults_to_affect`, `test_gradient_reaches_cppn_through_memory`, `test_detach_memory_cuts_graph`, plus the `make_org` helper and the new import line, all appended to the end of the file (not interleaved with Task 3 content). **`ailed/src/ailed/core.py`** — appended, after `RelationalPerceptron`: - `GatedRelationalPerceptron(hidden_dim, kappa)`: `gate` and `cand` are `nn.Linear(2*hidden_dim, hidden_dim)`. `forward(h, M, arousal)` computes `g = σ(gate([h‖M]) − κ·arousal)`, `cand = tanh(cand([h‖M]))`, returns `(1−g)·cand + g·M`. The arousal term is additive inside the sigmoid and multiplied by `kappa`, so `kappa=0` makes it a no-op regardless of `arousal`'s value — a single flag, no branch. - `detach_memory(memory)`: returns `{k: v.detach() for k, v in memory.items()}`. - `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)`: wraps a `RelationalPerceptron` and, when `memory=True`, a `GatedRelationalPerceptron`. `forward(attrs, r, ids, affect, memory, context=None, edge_types=None, mask=None)`: - unpacks `affect` as `(valence, arousal)` by name (this is the one place outside `Affect.axes` allowed to do so, per spec §5 — it's inside `Organism.forward` itself); - defaults `context` to `torch.tensor([valence, arousal])`, `edge_types` to all-same-type zeros, `mask` to fully connected; - runs the RP to get per-entity hidden state `h`; - if `memory=False`, returns `(self.out(h), {})` — history is never read or written; - if `memory=True`, builds `M_prev` by looking up each id in `ids` against the incoming `memory` dict (`zero` vector for ids not present — i.e. newborns), runs the GRP to fuse `h` and `M_prev` into the new `M`, rebuilds the memory dict as `{i: M[k] for k, i in enumerate(ids)}` (so an id absent from `ids` this step is simply never re-inserted — natural death), and returns `(self.out(M), new_memory)`. **`ailed/src/ailed/__init__.py`** — replaced the docstring-only file with the re-exports from `ailed.affect` and `ailed.core` listed in the brief. ## Verification Step 2 (pre-implementation, expect `ImportError`): ``` $ uv run pytest tests/test_core.py -q ERROR collecting tests/test_core.py ImportError: cannot import name 'GatedRelationalPerceptron' from 'ailed.core' (.../src/ailed/core.py) 1 error in 0.40s ``` Step 4 (post-implementation, full suite): ``` $ uv run pytest -q ........................ [100%] 24 passed in 0.41s ``` 16 pre-existing + 8 new = 24, all green. ## Commit `95f10f2953168878cc0d343eabe838c9c1962805` — `feat(core): gated relational perceptron and organism with per-entity memory (spec §4)` Per the team lead's instruction, the commit uses this session's own attribution trailer (`Claude Sonnet 5` / `session_01G1oTwYmaHDJnnqLdmtQW9i`) rather than the brief's example trailer (`Claude Opus 5 (1M context)` / `session_01KAWnnPg2qvmLNySamE2k85`) — flagged here only for the record, not as a concern, since I was told this gets normalised at the controller. ## Notes on the brief Nothing in the brief was wrong or ambiguous enough to require a deviation — the provided code matched Task 3's actual signatures (`RelationalPerceptron.forward(attrs, r, edge_onehot, mask, context)`, keyword `context` on `Organism.forward`, `attrs.shape[0] == len(ids)` per call) and the test cases exercise exactly the three properties the task cares about: - **Real recurrence**: `test_organism_memory_lifecycle` and `test_gradient_reaches_cppn_through_memory` both round-trip `memory` through repeated calls; the latter confirms gradient actually flows from the loss back through `M` into the CPPN's first linear layer across 3 unrolled steps, which would fail immediately if memory were passed in and the fused state discarded instead of returned. - **Signed additive gate bias, single disable flag**: `test_grp_kappa_zero_ignores_arousal` and `test_grp_high_arousal_overwrites` pin the sign and the disable behaviour directly against the gate/candidate sublayers. - **Entity lifecycle**: `test_organism_memory_lifecycle`'s birth/death assertions (`0 not in mem2 and 99 in mem2`) and the newborn-equals-explicit-zero check exercise exactly the dict-rebuild-from-`ids` mechanism described in the brief. One small thing worth flagging for whoever reads this next (not a defect, just a constraint to keep in mind for Task 6): `Organism.forward` requires `attrs.shape[0] == len(ids)` — `ids` labels positions in a fixed-size attrs/r tensor pair rather than selecting a variable-size subgraph, so the "entity leaves, entity is born" scenario in the test relies on the attribute/coordinate count staying constant across the two calls (`N=6` throughout) while only the id *labels* rotate. The runtime memory dict correctly drops old ids and adds new ones, but the caller is still responsible for supplying `attrs`/`r` of the right shape for whatever `ids` it passes. ## Fix round 1: make the memory tests load-bearing The team lead flagged, correctly, that neither `test_organism_memory_lifecycle` nor `test_gradient_reaches_cppn_through_memory` would have caught the exact regression Task 4 exists to prevent: `Organism.forward` silently ignoring its incoming `memory` argument (e.g. using zero for every entity every call). `core.py` was not touched except for a temporary, reverted sanity check — only `tests/test_core.py` changed. **`test_organism_memory_lifecycle`** — added, after the newborn-equals-explicit-zero check: a run with the *same* `ids2` but every surviving entity's incoming memory forced to zero (`{i: torch.zeros(H) for i in mem}`), asserting both the output and a survivor's resulting memory entry differ (`assert not torch.allclose(...)`) from the real-memory run. A newborn (`99`) is zero either way so it can't anchor this check; a survivor (`ids2[0]`, i.e. original entity `1`) can. **`test_gradient_reaches_cppn_through_memory` → `test_gradient_flows_through_memory_across_steps`** — tightened rather than just renamed. The CPPN runs on every call regardless of memory (it only consumes `r`, `edge_onehot`, `context` — never `attrs` or `M`), so a single unrolled step already guarantees nonzero gradient at `cppn.l1.weight`; that alone doesn't distinguish "memory carries gradient across time" from "the current step's `h` reaches the readout." The new test runs the same 3-step rollout twice: once normally, once calling `detach_memory` on the dict after every step (severing the cross-step graph while leaving each step's own CPPN call intact), and asserts the two resulting `cppn.l1.weight.grad` tensors are *not* `allclose` — if the recurrent chain weren't live, both grads would come from only the last step and would match. **Sanity check (per instruction, then reverted)**: temporarily changed `M_prev = torch.stack([memory.get(i, zero) for i in ids])` to `M_prev = torch.stack([zero for i in ids])` in `core.py` (forcing memory to be ignored, the regression this task exists to catch) and reran just the two strengthened tests: ``` $ uv run pytest tests/test_core.py -q -k "test_organism_memory_lifecycle or test_gradient_flows_through_memory_across_steps" FAILED tests/test_core.py::test_organism_memory_lifecycle - assert not True (assert not torch.allclose(y2, y2_zeroed) — y2 and y2_zeroed were identical: the real-memory and zeroed-memory runs produced the same output, as expected once memory is ignored) FAILED tests/test_core.py::test_gradient_flows_through_memory_across_steps - assert not True (assert not torch.allclose(g_recurrent, g_severed) — the "recurrent" and "severed" gradients were identical, since with M_prev forced to zero there was no cross-step graph left to sever) 2 failed, 12 deselected in 0.38s ``` Both new assertions fail exactly as expected against the simulated regression. Reverted the `core.py` edit (confirmed `git diff src/ailed/core.py` is empty afterward) and reran the full suite against the real implementation: ``` $ uv run pytest -q ........................ [100%] 24 passed in 0.39s ``` ### Commit `58c10fdb9792411153fdc9d56245e5060625b7d8` — `test(core): make organism memory tests load-bearing (spec §4)` Only `tests/test_core.py` changed; `src/ailed/core.py` has no diff from the Task 4 commit.