exp: does the organism learn how a piece moves

Reachability in relative-offset space, not absolute squares: the CPPN sees only r_ij, so an
entity's representation is translation-invariant and an absolute-square target is
unanswerable by construction. In offset space a knight's L is eight cells.

The floor is 'every piece moves like the average piece', which is the control the question
needs: beating it means the model tells a pawn from a bishop. Precision is also reported per
piece type, since pawns are half the board and can carry the aggregate on their own.

--edges type puts the receiving piece's type into e_ij, the spec's own channel into the CPPN.
Without it the kernel is type-blind: type reaches it only as an elementwise product.
This commit is contained in:
chrnx committed 2026-09-02 18:03:03 -05:00
1 parent 1c28987649
commit 2b11e2acd2
2 files changed
+208 -1

No files matched your search

+2 -1
View File
@@ -58,6 +58,7 @@ class Ply:
true_dest: int # index into dests true_dest: int # index into dests
past: np.ndarray # (N, 2*hist) each entity's previous squares, as displacements past: np.ndarray # (N, 2*hist) each entity's previous squares, as displacements
mask: np.ndarray # (N, N) the attack/defend graph, symmetric, self-loops on mask: np.ndarray # (N, N) the attack/defend graph, symmetric, self-loops on
reach: np.ndarray # (N,) each entity's attack set as a bitboard, for chess_reach.py
def advance_ids(board: chess.Board, move: chess.Move, piece: chess.Piece, def advance_ids(board: chess.Board, move: chess.Move, piece: chess.Piece,
@@ -131,7 +132,7 @@ def plies(game: chess.pgn.Game, hist: int = 3) -> list[Ply]:
for t in legal], dtype=np.float32) for t in legal], dtype=np.float32)
j = legal.index(move.to_square) j = legal.index(move.to_square)
out.append(Ply([id_at[s] for s in squares], attrs, coords, mover, dests[j], dests, j, out.append(Ply([id_at[s] for s in squares], attrs, coords, mover, dests[j], dests, j,
past, mask)) past, mask, bb.copy()))
seen.setdefault(id_at[move.from_square], []).append(move.from_square) seen.setdefault(id_at[move.from_square], []).append(move.from_square)
advance_ids(board, move, piece, id_at) advance_ids(board, move, piece, id_at)
+206
View File
@@ -0,0 +1,206 @@
"""Does the organism learn how a piece moves? Spec §3: the kernel is a function of geometry.
The move-prediction task in `chess_domain.py` never asks this. It hands legality to the model
for free at readout time -- the prediction is snapped to the nearest legal destination -- so
the model is never scored on knowing that a knight goes in an L. Its target also mixes what is
legal with what a human chose, and move quality is not controlled. This file asks the first
question instead: given the board, which squares can each piece reach?
Target: `board.attacks(square)` for every live piece, expressed as a 15x15 grid of RELATIVE
offsets rather than 64 absolute squares. That is not a convenience -- the CPPN sees only
`r_ij`, so an entity's representation is translation-invariant and cannot know which absolute
square it stands on. An absolute target is unanswerable by construction. In offset space the
question is the one worth asking: a knight's L is eight cells, a bishop's is four rays.
Deterministic, present-determined, same definition for all six types. The pawn caveat is real
and stated rather than hidden: `attacks` is the two diagonals, not the forward push, so for
pawns this measures the capture geometry only.
Two things this design is built to separate:
**Does the piece's type reach the kernel?** The CPPN sees `[r_ij ‖ onehot(e_ij) ‖ context]`.
The piece type is NOT in there -- it lives in `attrs`, which enters through `feat` and only
meets the kernel as an elementwise product. So the geometry function is shared across all six
types. `--edges type` puts the receiving piece's type into `e_ij`, which is the spec's own
sanctioned channel, and makes the kernel genuinely type-conditional: a knight-kernel and a
bishop-kernel rather than one kernel scaled by a type vector.
**Memory is the control here, not the hypothesis.** Reachability is fully determined by the
present -- type, square, blockers. This is the redundant case, so memory SHOULD buy nothing.
An arm that shows no memory gain here is the instrument working, not a null about memory.
"""
from __future__ import annotations
import argparse
import json
import statistics
from pathlib import Path
import numpy as np
import torch
from ailed import Affect, Organism, detach_memory
from chess_domain import ATTR_DIM, flat_diff, load
SQ = np.arange(64, dtype=np.uint64)
GRID = 15 * 15
# OFFSET[a, b] is where b sits relative to a, as a cell of the 15x15 displacement grid
_f, _r = np.arange(64) % 8, np.arange(64) // 8
OFFSET = ((_r[None, :] - _r[:, None] + 7) * 15 + (_f[None, :] - _f[:, None] + 7))
def unpack(ply) -> np.ndarray:
"""Each entity's attack set as a (N, 225) multi-hot over relative offsets."""
bits = ((ply.reach[:, None] >> SQ[None, :]) & np.uint64(1)).astype(np.float32) # (N,64)
sq = (np.rint(ply.coords[:, 0] * 7) + 8 * np.rint(ply.coords[:, 1] * 7)).astype(int)
out = np.zeros((len(sq), GRID), dtype=np.float32)
np.add.at(out, (np.arange(len(sq))[:, None], OFFSET[sq]), bits)
return out
def _stream(org, game, opt, bptt: int, edges: bool, adjacency: bool):
memory: dict[int, torch.Tensor] = {}
pending, losses, prec, chance = [], [], [], []
# per-type precision is the answer to "does it tell a pawn from a bishop"; the aggregate
# can be carried by pawns alone, which are half the pieces on the board
by_type = np.zeros((6, 2))
zero = Affect().axes
with torch.set_grad_enabled(opt is not None):
for ply in game:
n = len(ply.ids)
y = torch.from_numpy(unpack(ply)) # (N,225)
et = None
if edges: # receiver's type
t = torch.from_numpy(ply.attrs[:, :6]).argmax(1)
et = t[:, None].expand(n, n).contiguous()
pred, memory = org(torch.from_numpy(ply.attrs), flat_diff(torch.from_numpy(ply.coords)),
ply.ids, zero, memory, edge_types=et,
mask=torch.from_numpy(ply.mask) if adjacency else None)
loss = torch.nn.functional.binary_cross_entropy_with_logits(pred, y)
losses.append(loss.item())
with torch.no_grad():
k = y.sum(1)
keep = k > 0
if keep.any():
# precision@k: of the k squares it ranks highest, how many are reachable
rank = pred.argsort(1, descending=True).argsort(1)
hit = ((rank < k[:, None]) & (y > 0)).sum(1) / k.clamp(min=1)
prec.append(float(hit[keep].mean()))
chance.append(float((k[keep] / GRID).mean())) # random ranking
tt = ply.attrs[:, :6].argmax(1)[keep.numpy()]
np.add.at(by_type, (tt, 0), hit[keep].numpy())
np.add.at(by_type, (tt, 1), 1.0)
if opt is None:
continue
pending.append(loss)
if len(pending) == bptt:
opt.zero_grad(); torch.stack(pending).mean().backward(); opt.step()
pending = []; memory = detach_memory(memory)
if opt is not None and pending:
opt.zero_grad(); torch.stack(pending).mean().backward(); opt.step()
return losses, prec, chance, by_type
def run(games, memory: bool, hidden: int, cppn_hidden: int, seed: int, lr: float, bptt: int,
edges: bool, adjacency: bool) -> dict:
torch.manual_seed(seed)
org = Organism(ATTR_DIM, 2, GRID, n_edge_types=6 if edges else 1, hidden_dim=hidden,
cppn_hidden=cppn_hidden, kappa=0.0, memory=memory)
opt = torch.optim.Adam(org.parameters(), lr=lr)
order = np.random.default_rng(seed).permutation(len(games))
cut = max(1, len(games) // 4)
for gi in order[cut:]:
_stream(org, games[gi], opt, bptt, edges, adjacency)
loss, prec, chance, tsum = [], [], [], np.zeros((6, 2))
for gi in order[:cut]:
l, p, c, t = _stream(org, games[gi], None, bptt, edges, adjacency)
loss += l; prec += p; chance += c; tsum += t
return dict(seed=seed, memory=memory, edges=edges, hidden=hidden,
params=sum(p.numel() for p in org.parameters()),
loss=statistics.fmean(loss), prec=statistics.fmean(prec),
chance=statistics.fmean(chance),
by_type=list(tsum[:, 0] / np.maximum(tsum[:, 1], 1)))
def run_constant(games, seed: int) -> dict:
"""The floor: every piece moves like the average piece. Type-blind and position-blind.
This is the control the question needs. Beating it means the model distinguishes a pawn
from a bishop; sitting on it means it learned one average movement shape for everything.
"""
order = np.random.default_rng(seed).permutation(len(games))
cut = max(1, len(games) // 4)
marg = np.zeros(GRID)
for gi in order[cut:]:
for ply in games[gi]:
marg += unpack(ply).sum(0)
rank = torch.from_numpy((-marg).argsort().argsort())
prec, chance, tsum = [], [], np.zeros((6, 2))
for gi in order[:cut]:
for ply in games[gi]:
y = torch.from_numpy(unpack(ply))
k = y.sum(1); keep = k > 0
if keep.any():
hit = ((rank[None, :] < k[:, None]) & (y > 0)).sum(1) / k.clamp(min=1)
prec.append(float(hit[keep].mean())); chance.append(float((k[keep] / GRID).mean()))
tt = ply.attrs[:, :6].argmax(1)[keep.numpy()]
np.add.at(tsum, (tt, 0), hit[keep].numpy()); np.add.at(tsum, (tt, 1), 1.0)
return dict(seed=seed, memory=False, edges=False, hidden=0, params=GRID,
loss=float("nan"), prec=statistics.fmean(prec), chance=statistics.fmean(chance),
by_type=list(tsum[:, 0] / np.maximum(tsum[:, 1], 1)))
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--games", type=int, default=400)
ap.add_argument("--seeds", default="0,1,2,3,4,5,6,7")
ap.add_argument("--hidden", type=int, default=32)
ap.add_argument("--cppn-hidden", type=int, default=32)
ap.add_argument("--lr", type=float, default=1e-3)
ap.add_argument("--bptt", type=int, default=20)
ap.add_argument("--mask", default="all", choices=("all", "attack"))
ap.add_argument("--arms", default="constant,rp,rp_type,grp_type")
ap.add_argument("--out", default="results/chess_reach.json")
a = ap.parse_args()
games = load(a.games)
# (memory, edge types)
all_arms = {"constant": None, "rp": (False, False), "rp_type": (False, True),
"grp": (True, False), "grp_type": (True, True)}
arms = {k: all_arms[k] for k in a.arms.split(",")}
print(f"{len(games)} games, {sum(len(g) for g in games)} plies, mask={a.mask}\n")
results = []
for name, spec in arms.items():
for seed in (int(s) for s in a.seeds.split(",")):
r = (run_constant(games, seed) if spec is None else
run(games, spec[0], a.hidden, a.cppn_hidden, seed, a.lr, a.bptt, spec[1],
a.mask == "attack")) | {"arm": name}
print(f"{name:<10} seed={seed} params={r['params']:<6} "
f"loss={r['loss']:.4f} prec@k={r['prec']:.4f}", 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))
by = {n: [r for r in results if r["arm"] == n] for n in arms}
names = ["pawn", "knight", "bishop", "rook", "queen", "king"]
print(f"\n{'arm':<10}{'loss':>9}{'prec@k':>9}" + "".join(f"{t:>9}" for t in names))
print("-" * (28 + 9 * 6))
for n, rs in by.items():
bt = [statistics.fmean(r["by_type"][i] for r in rs) for i in range(6)]
print(f"{n:<10}{statistics.fmean(r['loss'] for r in rs):>9.4f}"
f"{statistics.fmean(r['prec'] for r in rs):>9.4f}"
+ "".join(f"{v:>9.4f}" for v in bt))
print(f"\nrandom ranking would score {statistics.fmean(r['chance'] for r in results):.4f}")
for top, base in (("rp_type", "rp"), ("grp_type", "rp_type"), ("grp", "rp")):
if top not in by or base not in by:
continue
d = [x["prec"] - y["prec"] for x, y in zip(by[top], by[base])]
se = statistics.stdev(d) / len(d) ** 0.5 if len(d) > 1 else float("nan")
print(f"\n{top} - {base}: {statistics.fmean(d):+.4f} +/- {se:.4f} (paired se), "
f"{sum(x > 0 for x in d)}/{len(d)} seeds -- "
f"{'ambiguous' if abs(statistics.fmean(d)) < se else 'a direction'}")
if __name__ == "__main__":
main()