Diego's call. Removed from all four repos' history and from every source that mandated it: the plan's global constraints, its per-task commit blocks, and the nine task briefs. Task reports and the ledger keep their mentions on purpose — they record what happened, including the trailer disagreement between subagents, and editing them would falsify the record.
1226 lines
45 KiB
Markdown
1226 lines
45 KiB
Markdown
# AILED General Organism Implementation Plan
|
||
|
||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||
|
||
**Goal:** Build the domain-free organism (affective CPPN, RP, GRP, 2-axis affect) as a library, the relational-particles domain plus the regime-switch experiment as a separate repo, and run claims A1 and A2 against their oracles.
|
||
|
||
**Architecture:** Three sibling git repos under a non-git root: `ailed/` (library, `src/ailed/{affect,core}.py`), `experiments/` (installs `../ailed` editable; `particles.py` simulator, `regime.py` runner), `paper/` (manuscript, scaffold only). Everything is PyTorch autograd, CPU, small. Affect is a pure function outside the graph.
|
||
|
||
**Tech Stack:** Python ≥3.11, uv, PyTorch ≥2.2, NumPy, pytest.
|
||
|
||
**Spec:** `AILED_General_Specification.md` (same directory as this plan). Section numbers below refer to it.
|
||
|
||
## 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 carry **no** co-authoring or session trailer.
|
||
|
||
---
|
||
|
||
## File map
|
||
|
||
| Path | Responsibility |
|
||
| :--- | :--- |
|
||
| `ailed/pyproject.toml` | package metadata, torch + numpy deps, pytest dev group |
|
||
| `ailed/src/ailed/__init__.py` | re-exports |
|
||
| `ailed/src/ailed/affect.py` | spec §5: `AffectConfig`, `Affect`, `update`, `decay`. No torch. |
|
||
| `ailed/src/ailed/core.py` | spec §3–§4: `AffectiveCPPN`, `RelationalPerceptron`, `GatedRelationalPerceptron`, `Organism`, `detach_memory` |
|
||
| `ailed/tests/test_affect.py` | affect invariants |
|
||
| `ailed/tests/test_core.py` | shape, invariance, gate, lifecycle, gradient |
|
||
| `experiments/pyproject.toml` | depends on `../ailed` editable |
|
||
| `experiments/particles.py` | spec §7: `ParticleConfig`, `ParticleWorld`, `Observation`, `wrapped_diff` |
|
||
| `experiments/regime.py` | spec §8: `CONDITIONS`, `run`, `main` writing `results/*.json` and a table |
|
||
| `experiments/tests/test_particles.py` | determinism, oracle byte-identity, switch timing |
|
||
| `experiments/tests/test_regime.py` | smoke run of every condition for a few steps |
|
||
| `paper/README.md` | the two claims and the pointer to the spec |
|
||
|
||
---
|
||
|
||
### Task 1: Scaffold the three repos
|
||
|
||
**Files:**
|
||
- Create: `ailed/pyproject.toml`, `ailed/src/ailed/__init__.py`, `ailed/tests/test_smoke.py`, `ailed/.gitignore`
|
||
- Create: `experiments/pyproject.toml`, `experiments/tests/test_smoke.py`, `experiments/.gitignore`
|
||
- Create: `paper/README.md`, `paper/.gitignore`
|
||
|
||
**Interfaces:**
|
||
- Produces: importable package `ailed`; `experiments` environment that can `import ailed`.
|
||
|
||
- [ ] **Step 1: Library repo**
|
||
|
||
```bash
|
||
cd /Users/chrnx/workspace/chrnx-dev/ia-stuff
|
||
mkdir -p ailed/src/ailed ailed/tests && cd ailed && git init -q
|
||
```
|
||
|
||
`ailed/pyproject.toml`:
|
||
```toml
|
||
[project]
|
||
name = "ailed"
|
||
version = "0.1.0"
|
||
description = "Relational-affective organism: affective CPPN, RP, GRP, 2-axis affect"
|
||
requires-python = ">=3.11"
|
||
dependencies = ["torch>=2.2", "numpy>=1.26"]
|
||
|
||
[dependency-groups]
|
||
dev = ["pytest>=8"]
|
||
|
||
[build-system]
|
||
requires = ["hatchling"]
|
||
build-backend = "hatchling.build"
|
||
|
||
[tool.hatch.build.targets.wheel]
|
||
packages = ["src/ailed"]
|
||
```
|
||
|
||
`ailed/src/ailed/__init__.py`:
|
||
```python
|
||
"""AILED: relational-affective organism. See AILED_General_Specification.md."""
|
||
```
|
||
|
||
`ailed/tests/test_smoke.py`:
|
||
```python
|
||
def test_import():
|
||
import ailed # noqa: F401
|
||
```
|
||
|
||
`ailed/.gitignore`:
|
||
```
|
||
.venv/
|
||
__pycache__/
|
||
*.egg-info/
|
||
.pytest_cache/
|
||
```
|
||
|
||
- [ ] **Step 2: Run the smoke test**
|
||
|
||
Run: `cd ailed && uv sync && uv run pytest -q`
|
||
Expected: `1 passed`
|
||
|
||
- [ ] **Step 3: Commit**
|
||
|
||
```bash
|
||
cd ailed && git add -A && git commit -q -m "chore: scaffold ailed library
|
||
```
|
||
|
||
- [ ] **Step 4: Experiments repo**
|
||
|
||
```bash
|
||
cd /Users/chrnx/workspace/chrnx-dev/ia-stuff
|
||
mkdir -p experiments/tests experiments/results && cd experiments && git init -q
|
||
```
|
||
|
||
`experiments/pyproject.toml`:
|
||
```toml
|
||
[project]
|
||
name = "ailed-experiments"
|
||
version = "0.1.0"
|
||
requires-python = ">=3.11"
|
||
dependencies = ["ailed", "torch>=2.2", "numpy>=1.26"]
|
||
|
||
[tool.uv.sources]
|
||
ailed = { path = "../ailed", editable = true }
|
||
|
||
[dependency-groups]
|
||
dev = ["pytest>=8"]
|
||
|
||
[tool.pytest.ini_options]
|
||
pythonpath = ["."]
|
||
```
|
||
|
||
`experiments/tests/test_smoke.py`:
|
||
```python
|
||
def test_library_importable():
|
||
import ailed # noqa: F401
|
||
```
|
||
|
||
`experiments/.gitignore`:
|
||
```
|
||
.venv/
|
||
__pycache__/
|
||
.pytest_cache/
|
||
results/*.json
|
||
```
|
||
|
||
- [ ] **Step 5: Run the smoke test**
|
||
|
||
Run: `cd experiments && uv sync && uv run pytest -q`
|
||
Expected: `1 passed`
|
||
|
||
- [ ] **Step 6: Commit**
|
||
|
||
```bash
|
||
cd experiments && git add -A && git commit -q -m "chore: scaffold experiments repo depending on ../ailed
|
||
```
|
||
|
||
- [ ] **Step 7: Paper repo**
|
||
|
||
```bash
|
||
cd /Users/chrnx/workspace/chrnx-dev/ia-stuff && mkdir -p paper && cd paper && git init -q
|
||
```
|
||
|
||
`paper/README.md`:
|
||
```markdown
|
||
# AILED: A Domain-Free Relational-Affective Organism
|
||
|
||
Manuscript for the second AILED paper. Design: `../AILED_General_Specification.md`.
|
||
|
||
Claims:
|
||
- **A1, affect-gated adaptation.** Arousal biases the memory gate; recovery after an unannounced regime change approaches the change-flag oracle.
|
||
- **A2, affective topology.** The CPPN kernel with affect as input recovers part of the regime-id oracle's ceiling.
|
||
|
||
Results are produced by `../experiments/regime.py` and copied here as tables.
|
||
```
|
||
|
||
`paper/.gitignore`:
|
||
```
|
||
*.aux
|
||
*.log
|
||
*.out
|
||
_build/
|
||
```
|
||
|
||
```bash
|
||
git add -A && git commit -q -m "chore: paper scaffold
|
||
```
|
||
|
||
---
|
||
|
||
### Task 2: Affect (spec §5)
|
||
|
||
**Files:**
|
||
- Create: `ailed/src/ailed/affect.py`
|
||
- Test: `ailed/tests/test_affect.py`
|
||
|
||
**Interfaces:**
|
||
- Produces:
|
||
- `AffectConfig(rho_fast=0.2, rho_slow=0.02, rho_a=0.5, rho_v=0.1, reward_scale=1.0, decay=0.2, eps=1e-6)` frozen dataclass
|
||
- `Affect(valence=0.0, arousal=0.0, fast=0.0, slow=0.0, steps=0)` frozen dataclass with `.axes -> tuple[float, float]` returning `(valence, arousal)`
|
||
- `update(state: Affect, loss: float, cfg: AffectConfig, reward: float = 0.0) -> Affect`
|
||
- `decay(state: Affect, cfg: AffectConfig) -> Affect`
|
||
|
||
- [ ] **Step 1: Write the failing tests**
|
||
|
||
`ailed/tests/test_affect.py`:
|
||
```python
|
||
from ailed.affect import Affect, AffectConfig, update, decay
|
||
|
||
CFG = AffectConfig()
|
||
|
||
|
||
def run(losses, rewards=None, cfg=CFG):
|
||
s = Affect()
|
||
rewards = rewards or [0.0] * len(losses)
|
||
out = []
|
||
for l, r in zip(losses, rewards):
|
||
s = update(s, l, cfg, reward=r)
|
||
out.append(s)
|
||
return out
|
||
|
||
|
||
def test_first_step_is_not_a_surprise():
|
||
s = update(Affect(), 5.0, CFG)
|
||
assert s.arousal == 0.0
|
||
assert s.fast == 5.0 and s.slow == 5.0
|
||
|
||
|
||
def test_constant_loss_settles_at_zero():
|
||
s = run([1.0] * 200)[-1]
|
||
assert abs(s.arousal) < 1e-6
|
||
assert abs(s.valence) < 1e-6
|
||
|
||
|
||
def test_spike_raises_arousal_then_decays():
|
||
hist = run([1.0] * 100 + [10.0] + [1.0] * 60)
|
||
assert hist[100].arousal > 0.4
|
||
assert hist[-1].arousal < 0.05
|
||
|
||
|
||
def test_decreasing_loss_gives_positive_valence():
|
||
losses = [1.0 - 0.004 * i for i in range(200)]
|
||
assert run(losses)[-1].valence > 0.05
|
||
|
||
|
||
def test_increasing_loss_gives_negative_valence():
|
||
losses = [0.2 + 0.004 * i for i in range(200)]
|
||
assert run(losses)[-1].valence < -0.05
|
||
|
||
|
||
def test_reward_moves_valence_with_flat_loss():
|
||
s = run([1.0] * 100, rewards=[0.0] * 50 + [1.0] * 50)[-1]
|
||
assert s.valence > 0.3
|
||
|
||
|
||
def test_decay_moves_toward_neutral():
|
||
s = Affect(valence=0.8, arousal=0.6, fast=1.0, slow=1.0, steps=10)
|
||
d = decay(s, CFG)
|
||
assert d.valence == 0.8 * (1 - CFG.decay)
|
||
assert d.arousal == 0.6 * (1 - CFG.decay)
|
||
assert d.fast == 1.0 and d.slow == 1.0
|
||
|
||
|
||
def test_update_is_pure():
|
||
s = Affect(valence=0.1, arousal=0.2, fast=1.0, slow=1.0, steps=5)
|
||
update(s, 3.0, CFG)
|
||
assert s == Affect(valence=0.1, arousal=0.2, fast=1.0, slow=1.0, steps=5)
|
||
|
||
|
||
def test_axes_by_name():
|
||
s = Affect(valence=0.3, arousal=0.7)
|
||
assert s.axes == (0.3, 0.7)
|
||
```
|
||
|
||
- [ ] **Step 2: Run to verify failure**
|
||
|
||
Run: `cd ailed && uv run pytest tests/test_affect.py -q`
|
||
Expected: `ImportError` / collection error on `ailed.affect`.
|
||
|
||
- [ ] **Step 3: Implement**
|
||
|
||
`ailed/src/ailed/affect.py`:
|
||
```python
|
||
"""Two-axis affect from the organism's own error stream. Spec §5.
|
||
|
||
Pure functions: state in, state out. No torch, no gradient by construction.
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import math
|
||
from dataclasses import dataclass, replace
|
||
|
||
|
||
@dataclass(frozen=True)
|
||
class AffectConfig:
|
||
rho_fast: float = 0.2 # fast error baseline rate
|
||
rho_slow: float = 0.02 # slow error baseline rate, must be < rho_fast
|
||
rho_a: float = 0.5 # arousal reactivity
|
||
rho_v: float = 0.1 # valence reactivity
|
||
reward_scale: float = 1.0 # s_r
|
||
decay: float = 0.2 # between-episode decay toward neutral
|
||
eps: float = 1e-6
|
||
|
||
|
||
@dataclass(frozen=True)
|
||
class Affect:
|
||
valence: float = 0.0 # v in [-1, 1]
|
||
arousal: float = 0.0 # a in [0, 1]
|
||
fast: float = 0.0 # L̄_fast
|
||
slow: float = 0.0 # L̄_slow
|
||
steps: int = 0
|
||
|
||
@property
|
||
def axes(self) -> tuple[float, float]:
|
||
"""(valence, arousal). Consumers read by name; this is the only positional export."""
|
||
return (self.valence, self.arousal)
|
||
|
||
|
||
def update(state: Affect, loss: float, cfg: AffectConfig, reward: float = 0.0) -> Affect:
|
||
if state.steps == 0:
|
||
fast = slow = loss # baselines initialise to the first loss: step one is not a surprise
|
||
else:
|
||
fast = state.fast + cfg.rho_fast * (loss - state.fast)
|
||
slow = state.slow + cfg.rho_slow * (loss - state.slow)
|
||
denom = slow + cfg.eps
|
||
a_target = math.tanh(max(0.0, loss - slow) / denom)
|
||
v_target = math.tanh((slow - fast) / denom + reward / cfg.reward_scale)
|
||
return Affect(
|
||
valence=state.valence + cfg.rho_v * (v_target - state.valence),
|
||
arousal=state.arousal + cfg.rho_a * (a_target - state.arousal),
|
||
fast=fast,
|
||
slow=slow,
|
||
steps=state.steps + 1,
|
||
)
|
||
|
||
|
||
def decay(state: Affect, cfg: AffectConfig) -> Affect:
|
||
k = 1.0 - cfg.decay
|
||
return replace(state, valence=state.valence * k, arousal=state.arousal * k)
|
||
```
|
||
|
||
- [ ] **Step 4: Run to verify pass**
|
||
|
||
Run: `cd ailed && uv run pytest tests/test_affect.py -q`
|
||
Expected: `9 passed`. If `test_spike_raises_arousal_then_decays` fails on the second assert, the spike lifted `slow` and 60 steps is too short; raise the tail to 100 steps and note it in the commit, do not touch `rho_slow`.
|
||
|
||
- [ ] **Step 5: Commit**
|
||
|
||
```bash
|
||
cd ailed && git add -A && git commit -q -m "feat(affect): two-axis affect from the error stream (spec §5)
|
||
```
|
||
|
||
---
|
||
|
||
### Task 3: Affective CPPN and Relational Perceptron (spec §3, §4)
|
||
|
||
**Files:**
|
||
- Create: `ailed/src/ailed/core.py`
|
||
- Test: `ailed/tests/test_core.py`
|
||
|
||
**Interfaces:**
|
||
- Produces:
|
||
- `AffectiveCPPN(coord_dim, n_edge_types, context_dim, hidden, out_dim, omega=10.0)`; `forward(r: (N,N,k), edge_onehot: (N,N,E), context: (C,)) -> (N,N,out_dim)`
|
||
- `RelationalPerceptron(attr_dim, coord_dim, n_edge_types, context_dim, hidden_dim, cppn_hidden=32, omega=10.0)`; `forward(attrs: (N,d), r: (N,N,k), edge_onehot: (N,N,E), mask: (N,N), context: (C,)) -> (N,hidden_dim)`
|
||
|
||
- [ ] **Step 1: Write the failing tests**
|
||
|
||
`ailed/tests/test_core.py` (first half; Task 4 appends):
|
||
```python
|
||
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])
|
||
```
|
||
|
||
- [ ] **Step 2: Run to verify failure**
|
||
|
||
Run: `cd ailed && uv run pytest tests/test_core.py -q`
|
||
Expected: collection error, `ailed.core` missing.
|
||
|
||
- [ ] **Step 3: Implement**
|
||
|
||
`ailed/src/ailed/core.py`:
|
||
```python
|
||
"""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)
|
||
# ponytail: 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)
|
||
```
|
||
|
||
- [ ] **Step 4: Run to verify pass**
|
||
|
||
Run: `cd ailed && uv run pytest tests/test_core.py -q`
|
||
Expected: `6 passed`
|
||
|
||
- [ ] **Step 5: Commit**
|
||
|
||
```bash
|
||
cd ailed && git add -A && git commit -q -m "feat(core): affective CPPN and relational perceptron (spec §3–§4)
|
||
```
|
||
|
||
---
|
||
|
||
### Task 4: GRP and Organism (spec §4)
|
||
|
||
**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)
|
||
```
|
||
|
||
---
|
||
|
||
### Task 5: Relational particles domain (spec §7)
|
||
|
||
**Files:**
|
||
- Create: `experiments/particles.py`
|
||
- Test: `experiments/tests/test_particles.py`
|
||
|
||
**Interfaces:**
|
||
- Produces:
|
||
- `wrapped_diff(coords: (N,2)) -> (N,N,2)` with entries in `[-0.5, 0.5)`
|
||
- `ParticleConfig(n=16, n_types=3, dt=0.05, sigma=0.2, noise=0.002, n_regimes=4, t_min=40, t_max=80, seed=0, oracle="none")`; `oracle ∈ {"none","change","regime"}`
|
||
- `Observation(attrs: Tensor (N,d), coords: Tensor (N,2), ids: list[int], target: Tensor (N,2), switched: bool, regime: int)`
|
||
- `ParticleWorld(cfg)` with `.step() -> Observation` and `.attr_dim` property
|
||
|
||
- [ ] **Step 1: Write the failing tests**
|
||
|
||
`experiments/tests/test_particles.py`:
|
||
```python
|
||
import torch
|
||
from particles import ParticleConfig, ParticleWorld, wrapped_diff
|
||
|
||
|
||
def test_wrapped_diff_range_and_antisymmetry():
|
||
c = torch.rand(10, 2)
|
||
d = wrapped_diff(c)
|
||
assert d.shape == (10, 10, 2)
|
||
assert d.min() >= -0.5 and d.max() < 0.5
|
||
assert torch.allclose(torch.diagonal(d, dim1=0, dim2=1), torch.zeros(2, 10))
|
||
# a pair separated by 0.7 along x must read as -0.3, not 0.7
|
||
two = torch.tensor([[0.1, 0.0], [0.8, 0.0]])
|
||
assert torch.allclose(wrapped_diff(two)[0, 1], torch.tensor([-0.3, 0.0]), atol=1e-6)
|
||
|
||
|
||
def rollout(cfg, steps):
|
||
w = ParticleWorld(cfg)
|
||
return [w.step() for _ in range(steps)]
|
||
|
||
|
||
def test_same_seed_same_trajectory():
|
||
a = rollout(ParticleConfig(seed=3), 50)
|
||
b = rollout(ParticleConfig(seed=3), 50)
|
||
for x, y in zip(a, b):
|
||
assert torch.equal(x.coords, y.coords) and torch.equal(x.target, y.target)
|
||
|
||
|
||
def test_oracles_do_not_change_the_world():
|
||
base = rollout(ParticleConfig(seed=1), 200)
|
||
for oracle in ("change", "regime"):
|
||
alt = rollout(ParticleConfig(seed=1, oracle=oracle), 200)
|
||
for x, y in zip(base, alt):
|
||
assert torch.equal(x.coords, y.coords)
|
||
assert torch.equal(x.target, y.target)
|
||
assert x.regime == y.regime and x.switched == y.switched
|
||
|
||
|
||
def test_attr_width_per_oracle():
|
||
assert ParticleWorld(ParticleConfig()).attr_dim == 3
|
||
assert ParticleWorld(ParticleConfig(oracle="change")).attr_dim == 4
|
||
assert ParticleWorld(ParticleConfig(oracle="regime")).attr_dim == 3 + 4
|
||
|
||
|
||
def test_change_flag_only_on_switch_steps():
|
||
obs = rollout(ParticleConfig(seed=2, oracle="change"), 300)
|
||
for o in obs:
|
||
flag = o.attrs[:, 3]
|
||
assert bool(flag.max()) == o.switched
|
||
assert flag.min() == flag.max()
|
||
|
||
|
||
def test_regime_onehot_matches_regime():
|
||
obs = rollout(ParticleConfig(seed=2, oracle="regime"), 300)
|
||
for o in obs:
|
||
assert torch.equal(o.attrs[0, 3:].argmax(), torch.tensor(o.regime))
|
||
|
||
|
||
def test_switches_happen_within_bounds_and_change_regime():
|
||
obs = rollout(ParticleConfig(seed=5, t_min=20, t_max=30), 400)
|
||
switch_steps = [i for i, o in enumerate(obs) if o.switched]
|
||
assert len(switch_steps) >= 10
|
||
gaps = [b - a for a, b in zip(switch_steps, switch_steps[1:])]
|
||
assert all(20 <= g <= 30 for g in gaps)
|
||
for i in switch_steps:
|
||
assert obs[i].regime != obs[i - 1].regime
|
||
|
||
|
||
def test_target_is_next_delta():
|
||
w = ParticleWorld(ParticleConfig(seed=7))
|
||
o1 = w.step(); o2 = w.step()
|
||
expected = (o2.coords - o1.coords + 0.5) % 1.0 - 0.5
|
||
assert torch.allclose(expected, o1.target, atol=1e-6)
|
||
|
||
|
||
def test_zero_regime_and_no_noise_is_static():
|
||
cfg = ParticleConfig(seed=0, noise=0.0)
|
||
w = ParticleWorld(cfg)
|
||
w.regimes[w.regime] = torch.zeros(3, 3)
|
||
o = w.step()
|
||
assert torch.allclose(o.target, torch.zeros_like(o.target))
|
||
```
|
||
|
||
- [ ] **Step 2: Run to verify failure**
|
||
|
||
Run: `cd experiments && uv run pytest tests/test_particles.py -q`
|
||
Expected: `ModuleNotFoundError: particles`.
|
||
|
||
- [ ] **Step 3: Implement**
|
||
|
||
`experiments/particles.py`:
|
||
```python
|
||
"""Relational particles with unannounced regime switches. Spec §7.
|
||
|
||
The world is deterministic given `seed`. Oracles only append columns to `attrs`;
|
||
they never touch the trajectory (asserted in tests).
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
from dataclasses import dataclass
|
||
|
||
import numpy as np
|
||
import torch
|
||
from torch import Tensor
|
||
|
||
ORACLES = ("none", "change", "regime")
|
||
|
||
|
||
def wrapped_diff(coords: Tensor) -> Tensor:
|
||
"""r_ij = c_j - c_i on the unit torus, in [-0.5, 0.5)."""
|
||
d = coords[None, :, :] - coords[:, None, :]
|
||
return d - torch.floor(d + 0.5)
|
||
|
||
|
||
@dataclass(frozen=True)
|
||
class ParticleConfig:
|
||
n: int = 16
|
||
n_types: int = 3
|
||
dt: float = 0.05
|
||
sigma: float = 0.2
|
||
noise: float = 0.002
|
||
n_regimes: int = 4
|
||
t_min: int = 40
|
||
t_max: int = 80
|
||
seed: int = 0
|
||
oracle: str = "none"
|
||
|
||
|
||
@dataclass
|
||
class Observation:
|
||
attrs: Tensor # (N, d)
|
||
coords: Tensor # (N, 2)
|
||
ids: list[int]
|
||
target: Tensor # (N, 2): coords[t+1] - coords[t], wrapped
|
||
switched: bool # True on the first step of a new regime
|
||
regime: int
|
||
|
||
|
||
class ParticleWorld:
|
||
def __init__(self, cfg: ParticleConfig):
|
||
assert cfg.oracle in ORACLES, cfg.oracle
|
||
self.cfg = cfg
|
||
self.rng = np.random.default_rng(cfg.seed)
|
||
self.torch_gen = torch.Generator().manual_seed(cfg.seed)
|
||
self.regimes = self._distinct_regimes()
|
||
self.types = torch.tensor(self.rng.integers(0, cfg.n_types, size=cfg.n))
|
||
self.coords = torch.tensor(self.rng.random((cfg.n, 2)), dtype=torch.float32)
|
||
self.regime = int(self.rng.integers(0, cfg.n_regimes))
|
||
self.until = self._next_switch(0)
|
||
self.t = 0
|
||
self.ids = list(range(cfg.n))
|
||
|
||
# -- setup ---------------------------------------------------------------
|
||
|
||
def _distinct_regimes(self) -> list[Tensor]:
|
||
seen, out = set(), []
|
||
while len(out) < self.cfg.n_regimes:
|
||
k = self.rng.choice([-1, 0, 1], size=(self.cfg.n_types, self.cfg.n_types))
|
||
key = k.tobytes()
|
||
if key in seen or not k.any():
|
||
continue
|
||
seen.add(key)
|
||
out.append(torch.tensor(k, dtype=torch.float32))
|
||
return out
|
||
|
||
def _next_switch(self, now: int) -> int:
|
||
return now + int(self.rng.integers(self.cfg.t_min, self.cfg.t_max + 1))
|
||
|
||
# -- dynamics ------------------------------------------------------------
|
||
|
||
def _delta(self) -> Tensor:
|
||
r = wrapped_diff(self.coords) # (N,N,2)
|
||
k = self.regimes[self.regime][self.types[:, None], self.types[None, :]] # (N,N)
|
||
kern = torch.exp(-(r ** 2).sum(-1) / self.cfg.sigma ** 2) # (N,N)
|
||
kern.fill_diagonal_(0.0)
|
||
force = (k * kern)[:, :, None] * r # (N,N,2)
|
||
noise = self.cfg.noise * torch.randn(self.cfg.n, 2, generator=self.torch_gen)
|
||
return self.cfg.dt * force.sum(1) + noise
|
||
|
||
@property
|
||
def attr_dim(self) -> int:
|
||
return self.cfg.n_types + {"none": 0, "change": 1, "regime": self.cfg.n_regimes}[self.cfg.oracle]
|
||
|
||
def _attrs(self, switched: bool) -> Tensor:
|
||
cols = [torch.nn.functional.one_hot(self.types, self.cfg.n_types).float()]
|
||
if self.cfg.oracle == "change":
|
||
cols.append(torch.full((self.cfg.n, 1), float(switched)))
|
||
elif self.cfg.oracle == "regime":
|
||
onehot = torch.zeros(self.cfg.n, self.cfg.n_regimes); onehot[:, self.regime] = 1.0
|
||
cols.append(onehot)
|
||
return torch.cat(cols, dim=1)
|
||
|
||
def step(self) -> Observation:
|
||
switched = False
|
||
if self.t == self.until:
|
||
choices = [i for i in range(self.cfg.n_regimes) if i != self.regime]
|
||
self.regime = int(self.rng.choice(choices))
|
||
self.until = self._next_switch(self.t)
|
||
switched = True
|
||
delta = self._delta()
|
||
obs = Observation(attrs=self._attrs(switched), coords=self.coords.clone(),
|
||
ids=list(self.ids), target=delta, switched=switched, regime=self.regime)
|
||
self.coords = (self.coords + delta) % 1.0
|
||
self.t += 1
|
||
return obs
|
||
```
|
||
|
||
- [ ] **Step 4: Run to verify pass**
|
||
|
||
Run: `cd experiments && uv run pytest tests/test_particles.py -q`
|
||
Expected: `9 passed`. If `test_switches_happen_within_bounds_and_change_regime` fails on `>= 10`, 400 steps with gaps ≤30 always yields ≥13; check the `until` bookkeeping before touching the test.
|
||
|
||
- [ ] **Step 5: Commit**
|
||
|
||
```bash
|
||
cd experiments && git add -A && git commit -q -m "feat: relational particles world with regime switches and opt-in oracles (spec §7)
|
||
```
|
||
|
||
---
|
||
|
||
### Task 6: Regime experiment runner (spec §8)
|
||
|
||
**Files:**
|
||
- Create: `experiments/regime.py`
|
||
- Test: `experiments/tests/test_regime.py`
|
||
|
||
**Interfaces:**
|
||
- Consumes: `Organism`, `detach_memory`, `Affect`, `AffectConfig`, `update` from `ailed`; `ParticleConfig`, `ParticleWorld`, `wrapped_diff` from `particles`.
|
||
- Produces:
|
||
- `CONDITIONS: dict[str, dict]` with keys `rp_only, grp_k0, grp_k, grp_flag, grp_regime, rp_flag, grp_k_noctx, grp_k_regimectx`
|
||
- `run(name: str, seed: int, steps: int, window: int = 20, bptt: int = 20, lr: float = 1e-3, hidden: int = 32, kappa: float = 4.0) -> dict` with keys `recovery` (list of `window` floats), `steady` (float), `n_switches` (int), `arousal_at_switch` (float), `arousal_steady` (float)
|
||
- `main()` CLI: `--conditions a,b,c --seeds 0,1,2 --steps 20000 --out results/a1.json`
|
||
|
||
- [ ] **Step 1: Write the failing smoke test**
|
||
|
||
`experiments/tests/test_regime.py`:
|
||
```python
|
||
import pytest
|
||
from regime import CONDITIONS, run
|
||
|
||
|
||
@pytest.mark.parametrize("name", sorted(CONDITIONS))
|
||
def test_every_condition_runs(name):
|
||
res = run(name, seed=0, steps=300, window=5, bptt=10)
|
||
assert len(res["recovery"]) == 5
|
||
assert res["steady"] >= 0.0
|
||
assert res["n_switches"] >= 1
|
||
|
||
|
||
def test_rp_only_has_no_memory_and_zero_kappa():
|
||
assert CONDITIONS["rp_only"]["memory"] is False
|
||
assert CONDITIONS["grp_k0"]["kappa"] == 0.0
|
||
assert CONDITIONS["grp_flag"]["kappa"] == 0.0 and CONDITIONS["grp_flag"]["oracle"] == "change"
|
||
assert CONDITIONS["grp_regime"]["kappa"] == 0.0 and CONDITIONS["grp_regime"]["oracle"] == "regime"
|
||
```
|
||
|
||
- [ ] **Step 2: Run to verify failure**
|
||
|
||
Run: `cd experiments && uv run pytest tests/test_regime.py -q`
|
||
Expected: `ModuleNotFoundError: regime`.
|
||
|
||
- [ ] **Step 3: Implement**
|
||
|
||
`experiments/regime.py`:
|
||
```python
|
||
"""Claims A1 and A2 on relational particles. Spec §8.
|
||
|
||
One continuous online stream per (condition, seed). Truncated BPTT every `bptt`
|
||
steps. Affect is updated from loss.item() so it never carries gradient.
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import argparse
|
||
import json
|
||
import statistics
|
||
from pathlib import Path
|
||
|
||
import torch
|
||
|
||
from ailed import Affect, AffectConfig, Organism, detach_memory, update
|
||
from particles import ParticleConfig, ParticleWorld, wrapped_diff
|
||
|
||
KAPPA_FLAG = "kappa" # resolved from run(kappa=...) when the value is this sentinel
|
||
|
||
CONDITIONS: dict[str, dict] = {
|
||
# A1
|
||
"rp_only": dict(memory=False, kappa=0.0, oracle="none", ctx="affect"),
|
||
"grp_k0": dict(memory=True, kappa=0.0, oracle="none", ctx="affect"),
|
||
"grp_k": dict(memory=True, kappa=KAPPA_FLAG, oracle="none", ctx="affect"),
|
||
"grp_flag": dict(memory=True, kappa=0.0, oracle="change", ctx="affect"),
|
||
"grp_regime": dict(memory=True, kappa=0.0, oracle="regime", ctx="affect"),
|
||
# control that cannot show an effect
|
||
"rp_flag": dict(memory=False, kappa=0.0, oracle="change", ctx="affect"),
|
||
# A2 (on the affect-gated model)
|
||
"grp_k_noctx": dict(memory=True, kappa=KAPPA_FLAG, oracle="none", ctx="zeros"),
|
||
"grp_k_regimectx": dict(memory=True, kappa=KAPPA_FLAG, oracle="none", ctx="regime"),
|
||
}
|
||
|
||
|
||
def _context(kind: str, affect: Affect, regime: int, n_regimes: int) -> torch.Tensor | None:
|
||
if kind == "affect":
|
||
return None # Organism defaults to (valence, arousal)
|
||
if kind == "zeros":
|
||
return torch.zeros(2)
|
||
if kind == "regime":
|
||
c = torch.zeros(n_regimes); c[regime] = 1.0
|
||
return c
|
||
raise ValueError(kind)
|
||
|
||
|
||
def run(name: str, seed: int, steps: int, window: int = 20, bptt: int = 20,
|
||
lr: float = 1e-3, hidden: int = 32, kappa: float = 4.0) -> dict:
|
||
spec = dict(CONDITIONS[name])
|
||
if spec["kappa"] == KAPPA_FLAG:
|
||
spec["kappa"] = kappa
|
||
torch.manual_seed(seed)
|
||
wcfg = ParticleConfig(seed=seed, oracle=spec["oracle"])
|
||
world = ParticleWorld(wcfg)
|
||
ctx_dim = wcfg.n_regimes if spec["ctx"] == "regime" else 2
|
||
org = Organism(attr_dim=world.attr_dim, coord_dim=2, target_dim=2, context_dim=ctx_dim,
|
||
hidden_dim=hidden, kappa=spec["kappa"], memory=spec["memory"])
|
||
opt = torch.optim.Adam(org.parameters(), lr=lr)
|
||
acfg = AffectConfig()
|
||
affect = Affect()
|
||
memory: dict[int, torch.Tensor] = {}
|
||
|
||
losses, switched, arousals = [], [], []
|
||
pending = []
|
||
for t in range(steps):
|
||
obs = world.step()
|
||
ctx = _context(spec["ctx"], affect, obs.regime, wcfg.n_regimes)
|
||
pred, memory = org(obs.attrs, wrapped_diff(obs.coords), obs.ids, affect.axes, memory, context=ctx)
|
||
loss = ((pred - obs.target) ** 2).mean()
|
||
pending.append(loss)
|
||
affect = update(affect, loss.item(), acfg)
|
||
losses.append(loss.item()); switched.append(obs.switched); arousals.append(affect.arousal)
|
||
if len(pending) == bptt:
|
||
opt.zero_grad()
|
||
torch.stack(pending).mean().backward()
|
||
opt.step()
|
||
pending = []
|
||
memory = detach_memory(memory)
|
||
|
||
# metrics on the second half only: the first half is training warm-up
|
||
half = steps // 2
|
||
switch_idx = [i for i in range(half, steps - window) if switched[i]]
|
||
recovery = [statistics.fmean(losses[i + k] for i in switch_idx) for k in range(window)] if switch_idx else [float("nan")] * window
|
||
steady_idx = [i for i in range(half, steps) if not any(switched[max(0, i - window):i + 1])]
|
||
steady = statistics.fmean(losses[i] for i in steady_idx) if steady_idx else float("nan")
|
||
return dict(
|
||
condition=name, seed=seed, steps=steps,
|
||
recovery=recovery, steady=steady, n_switches=len(switch_idx),
|
||
arousal_at_switch=statistics.fmean(arousals[i] for i in switch_idx) if switch_idx else float("nan"),
|
||
arousal_steady=statistics.fmean(arousals[i] for i in steady_idx) if steady_idx else float("nan"),
|
||
)
|
||
|
||
|
||
def table(results: list[dict]) -> str:
|
||
by = {}
|
||
for r in results:
|
||
by.setdefault(r["condition"], []).append(r)
|
||
lines = [f"{'condition':<18}{'steady':>10}{'rec@0':>10}{'rec@2':>10}{'rec@5':>10}{'rec@10':>10}{'a@switch':>10}{'a@steady':>10}",
|
||
"-" * 88]
|
||
for name, rs in by.items():
|
||
m = lambda key, idx=None: statistics.fmean((r[key][idx] if idx is not None else r[key]) for r in rs)
|
||
lines.append(f"{name:<18}{m('steady'):>10.5f}{m('recovery', 0):>10.5f}{m('recovery', 2):>10.5f}"
|
||
f"{m('recovery', 5):>10.5f}{m('recovery', 10):>10.5f}{m('arousal_at_switch'):>10.3f}{m('arousal_steady'):>10.3f}")
|
||
return "\n".join(lines)
|
||
|
||
|
||
def main() -> None:
|
||
ap = argparse.ArgumentParser()
|
||
ap.add_argument("--conditions", default=",".join(CONDITIONS))
|
||
ap.add_argument("--seeds", default="0,1,2")
|
||
ap.add_argument("--steps", type=int, default=20000)
|
||
ap.add_argument("--window", type=int, default=20)
|
||
ap.add_argument("--kappa", type=float, default=4.0)
|
||
ap.add_argument("--out", default="results/run.json")
|
||
a = ap.parse_args()
|
||
results = []
|
||
for name in a.conditions.split(","):
|
||
for seed in (int(s) for s in a.seeds.split(",")):
|
||
r = run(name, seed, a.steps, window=a.window, kappa=a.kappa)
|
||
print(f"{name:<18} seed={seed} steady={r['steady']:.5f} rec@0={r['recovery'][0]:.5f}", flush=True)
|
||
results.append(r)
|
||
Path(a.out).parent.mkdir(parents=True, exist_ok=True)
|
||
Path(a.out).write_text(json.dumps(results, indent=1))
|
||
print(); print(table(results))
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|
||
```
|
||
|
||
- [ ] **Step 4: Run to verify pass**
|
||
|
||
Run: `cd experiments && uv run pytest -q`
|
||
Expected: all pass (`1 + 9 + 9`).
|
||
|
||
- [ ] **Step 5: Commit**
|
||
|
||
```bash
|
||
cd experiments && git add -A && git commit -q -m "feat: regime-switch runner for claims A1 and A2 (spec §8)
|
||
```
|
||
|
||
---
|
||
|
||
### Task 7: Verify the oracle is read and the setup has headroom
|
||
|
||
This is the spec's "measure before chasing" rule (§7, §8). Nothing in A1 means anything until these two numbers are in.
|
||
|
||
**Files:**
|
||
- Create: `experiments/results/headroom.md`
|
||
|
||
- [ ] **Step 1: Run the two ceilings and the two floors, one seed, short**
|
||
|
||
```bash
|
||
cd experiments && uv run python regime.py --conditions rp_only,grp_k0,grp_regime,rp_flag --seeds 0 --steps 8000 --out results/headroom.json
|
||
```
|
||
|
||
- [ ] **Step 2: Read the table against these three requirements**
|
||
|
||
1. `grp_regime` steady error must sit near the noise floor `noise² = 4e-6` (within ~3x). If it does not, the regime oracle is not being read: check `attr_dim` reaches `Organism` and that `omega` lets the CPPN represent the kernel (try `omega` 5 and 20 by editing the `Organism` call in `run`; keep the winner and record it).
|
||
2. `grp_k0` must beat `rp_only` on `steady` and on `rec@10`. If not, memory has no job in this setup: raise `sigma` to 0.3 or lower `noise`, re-run, record.
|
||
3. `rp_flag` must equal `rp_only` within seed noise on every column. If it does not, the flag leaks something other than "a change happened"; stop and investigate before A1.
|
||
|
||
- [ ] **Step 3: Write `results/headroom.md`**
|
||
|
||
Record the table verbatim, which of the three requirements held, and any knob changed with its before/after value. This file is the audit trail for the paper's setup section.
|
||
|
||
- [ ] **Step 4: Commit**
|
||
|
||
```bash
|
||
cd experiments && git add results/headroom.md && git commit -q -m "exp: headroom check for the regime setup
|
||
```
|
||
|
||
---
|
||
|
||
### Task 8: Claim A1
|
||
|
||
**Files:**
|
||
- Create: `experiments/results/a1.md`
|
||
|
||
- [ ] **Step 1: Run the five conditions plus the control, three seeds**
|
||
|
||
```bash
|
||
cd experiments && uv run python regime.py --conditions rp_only,grp_k0,grp_k,grp_flag,grp_regime,rp_flag --seeds 0,1,2 --steps 20000 --out results/a1.json
|
||
```
|
||
|
||
Takes minutes on CPU; run it in the background and read the JSON when it finishes.
|
||
|
||
- [ ] **Step 2: Decide A1 from the table, by the spec's rule**
|
||
|
||
A1 holds if `grp_k` beats `grp_k0` on `rec@0..rec@5` and closes part of the gap to `grp_flag`. Report the three per-seed deltas, not only the mean. If `grp_flag` does not beat `grp_k0`, arousal had no job: say so in `a1.md`, do not tune `kappa` to manufacture a result. A single `kappa` sweep (`--kappa 1,4,16` as three runs) is allowed and must be reported in full.
|
||
|
||
- [ ] **Step 3: Write `results/a1.md`** with the table, the per-seed deltas, and the verdict in one line. Copy the table to `paper/README.md` under a `## Results` heading.
|
||
|
||
- [ ] **Step 4: Commit both repos**
|
||
|
||
```bash
|
||
cd experiments && git add results/a1.md && git commit -q -m "exp: claim A1 results
|
||
cd ../paper && git add README.md && git commit -q -m "results: A1 table
|
||
```
|
||
|
||
---
|
||
|
||
### Task 9: Claim A2
|
||
|
||
**Files:**
|
||
- Create: `experiments/results/a2.md`
|
||
|
||
- [ ] **Step 1: Run the three CPPN contexts on the affect-gated model**
|
||
|
||
```bash
|
||
cd experiments && uv run python regime.py --conditions grp_k,grp_k_noctx,grp_k_regimectx --seeds 0,1,2 --steps 20000 --out results/a2.json
|
||
```
|
||
|
||
- [ ] **Step 2: Decide A2**
|
||
|
||
Fraction recovered = `(noctx − affect) / (noctx − regimectx)` on `steady` and on `rec@5`. Report it per seed. The spec predicts a small effect; a fraction near zero is a valid, reportable result and does not get re-run with different knobs.
|
||
|
||
- [ ] **Step 3: Write `results/a2.md`**, append the table to `paper/README.md`, commit both repos as in Task 8 with messages `exp: claim A2 results` and `results: A2 table`.
|
||
|
||
---
|
||
|
||
## Self-review
|
||
|
||
**Spec coverage.** §2 contract A: Task 4 `Organism` + Task 5 target. §3 relation and CPPN: Tasks 3, 5. §4 RP, GRP, lifecycle, readout A: Tasks 3, 4. §5 affect incl. first-step init and decay: Task 2. §6 table: only the two "built" rows have tasks, by design; contract B readout, metabolism and S2 are out of scope per §9. §7 domain and three oracle rules: Task 5 (byte-identity test), Task 7 (saturation and no-effect control). §8 A1 and A2 with protocol rules: Tasks 7–9. §11 file shape: matched, split across two repos per the monorepo decision.
|
||
|
||
**Placeholders.** None; every code step is complete.
|
||
|
||
**Type consistency.** `Affect.axes -> (valence, arousal)` is what `Organism.forward(affect=...)` unpacks. `Organism(context_dim=...)` matches `_context` sizes (2 or `n_regimes`). `ParticleWorld.attr_dim` feeds `Organism(attr_dim=...)`. `detach_memory` is used in `run` and tested in Task 4. `KAPPA_FLAG` is resolved before `Organism` is built.
|