Files
ailed-experiments-rp/chess_reach.py
T
chrnx 18345f2a3e exp: the shape control — knows the movement rule, reads nothing from the board
The open/blocked split cannot work as posed: in real games a rook and a queen are blocked
essentially always (share blocked 1.00, 1.00, bishop 0.89), so there is no open bucket to
contrast against. The control that does answer the question is a floor that knows each
piece's type and its empty-board attack set and nothing else. Beating it means reading
occupancy. For a knight or a king it is the exact answer, so it doubles as a ceiling.
2026-09-02 19:00:00 -05:00

308 lines
16 KiB
Python

"""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 chess
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)
# how many squares each sliding piece would attack from each square on an EMPTY board. A piece
# attacking fewer than this is blocked, and a blocked ray is the part of chess geometry that
# cannot be memorised as a shape: the knight's L never changes, a rook's does.
_EMPTY_BB, _EMPTY = {}, {}
for _pt in range(1, 7):
for _col in (chess.WHITE, chess.BLACK):
for _sq in chess.SQUARES:
_b = chess.Board(None)
_b.set_piece_at(_sq, chess.Piece(_pt, _col))
bb = int(_b.attacks(_sq))
_EMPTY_BB[(_pt, _col, _sq)] = bb
_EMPTY[(_pt, _sq)] = bin(bb).count("1") # colour-free: only sliding uses this
SLIDING = (chess.BISHOP, chess.ROOK, chess.QUEEN)
def blocked_flags(ply) -> np.ndarray:
"""(N,) True where a sliding piece attacks fewer squares than it would on an empty board."""
t = ply.attrs[:, :6].argmax(1) + 1
sq = (np.rint(ply.coords[:, 0] * 7) + 8 * np.rint(ply.coords[:, 1] * 7)).astype(int)
have = np.array([bin(int(r)).count("1") for r in ply.reach])
full = np.array([_EMPTY.get((int(a), int(b)), -1) for a, b in zip(t, sq)])
return (full > 0) & (have < full)
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 run_shape(games, seed: int) -> dict:
"""The control the blocking question needs: knows the piece's type and its movement RULE,
reads nothing from the board.
Each entity is scored by its EMPTY-BOARD attack set from its own square, ties broken by
the marginal frequency of the offset. For a knight or a king this is the exact answer, so
the arm is also a ceiling: whatever it scores there is what perfect knowledge of the rule
is worth. For a sliding piece it is the un-blocked ray, so beating it means reading
occupancy -- knowing how far the ray is actually cut.
"""
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)
marg = marg / max(marg.max(), 1.0)
prec, chance, tsum, bsum = [], [], np.zeros((6, 2)), np.zeros((6, 2, 2))
for gi in order[:cut]:
for ply in games[gi]:
y = torch.from_numpy(unpack(ply))
t = ply.attrs[:, :6].argmax(1) + 1
col = ply.attrs[:, 6].astype(bool)
sq = (np.rint(ply.coords[:, 0] * 7) + 8 * np.rint(ply.coords[:, 1] * 7)).astype(int)
score = np.tile(marg, (len(sq), 1)) * 0.5
for k_, (tt, cc, ss) in enumerate(zip(t, col, sq)):
bb = _EMPTY_BB[(int(tt), bool(cc), int(ss))]
hit_sq = [j for j in range(64) if bb >> j & 1]
score[k_, OFFSET[int(ss)][hit_sq]] += 1.0
rank = torch.from_numpy((-score).argsort(1).argsort(1))
k = y.sum(1); keep = k > 0
if keep.any():
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()))
kn = keep.numpy(); tt = ply.attrs[:, :6].argmax(1)[kn]
np.add.at(tsum, (tt, 0), hit[keep].numpy()); np.add.at(tsum, (tt, 1), 1.0)
bl = blocked_flags(ply)[kn].astype(int)
np.add.at(bsum, (tt, bl, 0), hit[keep].numpy())
np.add.at(bsum, (tt, bl, 1), 1.0)
return dict(seed=seed, memory=False, edges=False, hidden=0, params=0,
loss=float("nan"), prec=statistics.fmean(prec), chance=statistics.fmean(chance),
by_type=list(tsum[:, 0] / np.maximum(tsum[:, 1], 1)),
by_block=(bsum[:, :, 0] / np.maximum(bsum[:, :, 1], 1)).tolist(),
n_block=bsum[:, :, 1].tolist())
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))
by_block = np.zeros((6, 2, 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
kn = keep.numpy()
tt = ply.attrs[:, :6].argmax(1)[kn]
np.add.at(by_type, (tt, 0), hit[keep].numpy())
np.add.at(by_type, (tt, 1), 1.0)
bl = blocked_flags(ply)[kn].astype(int)
np.add.at(by_block, (tt, bl, 0), hit[keep].numpy())
np.add.at(by_block, (tt, bl, 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, by_block
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, bsum = [], [], [], np.zeros((6, 2)), np.zeros((6, 2, 2))
for gi in order[:cut]:
l, p, c, t, b = _stream(org, games[gi], None, bptt, edges, adjacency)
loss += l; prec += p; chance += c; tsum += t; bsum += b
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)),
by_block=(bsum[:, :, 0] / np.maximum(bsum[:, :, 1], 1)).tolist(),
n_block=bsum[:, :, 1].tolist())
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, bsum = [], [], np.zeros((6, 2)), np.zeros((6, 2, 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()))
kn = keep.numpy()
tt = ply.attrs[:, :6].argmax(1)[kn]
np.add.at(tsum, (tt, 0), hit[keep].numpy()); np.add.at(tsum, (tt, 1), 1.0)
bl = blocked_flags(ply)[kn].astype(int)
np.add.at(bsum, (tt, bl, 0), hit[keep].numpy())
np.add.at(bsum, (tt, bl, 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)),
by_block=(bsum[:, :, 0] / np.maximum(bsum[:, :, 1], 1)).tolist(),
n_block=bsum[:, :, 1].tolist())
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,shape,rp,rp_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, "shape": "shape", "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_shape(games, seed) if spec == "shape" 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}")
# the blocker split: a knight's L never changes, a sliding piece's ray is cut by occupancy.
# Reported against the floor inside each bucket, because a blocked piece has a smaller
# attack set and therefore a different chance level -- the buckets are not comparable raw.
print(f"\n{'':<10}" + "".join(f"{t:>20}" for t in ("bishop", "rook", "queen")))
print(f"{'arm':<10}" + "".join(f"{'open':>10}{'blocked':>10}" for _ in range(3)))
print("-" * 70)
for n, rs in by.items():
row = ""
for i in (2, 3, 4):
for b in (0, 1):
row += f"{statistics.fmean(r['by_block'][i][b] for r in rs):>10.4f}"
print(f"{n:<10}{row}")
counts = by[list(by)[0]][0]["n_block"]
print("share blocked: " + " ".join(
f"{t}={counts[i][1] / max(counts[i][0] + counts[i][1], 1):.2f}"
for i, t in ((2, "bishop"), (3, "rook"), (4, "queen"))))
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()