Files
ailed-docs-rp/.sdd/task-5-brief.md
T
chrnxandClaude Opus 5 8ed2944518 docs: design, plan, and the execution record
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
2026-09-02 13:17:39 -05:00

257 lines
9.3 KiB
Markdown

# Task 5: Relational particles domain (spec §7)
## 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) <noreply@anthropic.com>
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:**
- 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)
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KAWnnPg2qvmLNySamE2k85"
```