Compare commits

...
5 Commits
Author SHA1 Message Date
chrnx 9859bad9d7 exp: the RP learns the movement rules, and reads the board where it counts
Beats the rule-knowing control on rook (+0.016), queen (+0.006) and king (+0.009) -- the
pieces whose moves are cut by occupancy. Still below on pawn, bishop and knight.

Absolute position is worth +0.020 and halves the gap to the control, which had been handed
the square all along. The rim mechanism proposed for why it pays is recorded as unverified:
per type the gain is flat and the knight, 43% of which sit on the rim, gained less than the
queen.
2026-09-02 20:04:43 -05:00
chrnx 67cf06bd71 exp: type-by-colour edge types, twelve kernels instead of six
The type-conditional kernel lost 0.14 on pawns and nothing elsewhere, because e_ij carried the
piece type and not its colour: a white pawn and a black pawn share one kernel and their moves
are mirrored. typecol gives each colour its own.
2026-09-02 19:59:14 -05:00
chrnx 4567c2e18b exp: absolute position and own-side rank as attributes
The CPPN sees only r_ij, so the representation is translation-invariant and a chess board has
edges: a knight has 2.96 destinations on the rim against 6.85 in the middle, and 43% of them
sit on the rim. Relative geometry to other pieces cannot recover that on a near-empty board,
and the shape control is handed the square while the organism was not.

own_rank is rank from the piece's own back rank, so a pawn's push, its double-push rank, its
promotion and castling are one law rather than two mirrored ones.
2026-09-02 19:38:10 -05:00
chrnx 9e7f347464 exp: teach the movement rules directly, on generated positions
Games are a bad curriculum for this and both reasons are measured. Coverage: a rook or queen
is blocked in 98-100% of real positions, so the model learned the geometry it saw and scored
worse in open positions than blocked ones. Content: the reachability target left out three
rules entirely -- a pawn on e2 attacks d3 and f3 while its moves are e3 and e4, no overlap at
all; castling and en passant never appeared. The target here is generate_pseudo_legal_moves.

Piece count is sampled uniformly from 2 to 32, so an empty board is as common as a crowded
one. Castling rights and the ep square are handed over as attributes, because they are state
rather than position and without them the same board has two correct answers. Taking them
away is the cleanest memory experiment available, and belongs to the parked GRP line.

Positions are streamed, never stored: 200k dense targets would be 6 GB.
2026-09-02 19:16:49 -05:00
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
4 changed files with 551 additions and 11 deletions

No files matched your search

+15
View File
@@ -47,6 +47,21 @@ directory.
domain's own structure; a null on a model that has not is uninterpretable. This is the
sibling of the oracle rule: the oracle asks whether the information pays, this asks whether
the architecture can hold it.
- **Teach the basics before measuring anything on top of them.** Training from scratch means
the domain's laws have to be *reachable* from what the organism is given, and on chess five
separate things were not, each found by measurement rather than argument:
the piece type never entered the kernel (knight's L at exactly 0.000, `chess_reach.md`);
the target was `attacks`, which for a pawn on e2 returns d3/f3 while its moves are e3/e4 —
no overlap — and omits castling and en passant entirely;
games never show an open board (a rook is blocked in 98-100% of real positions), so the rule
cannot be induced from play;
absolute position was erased by a translation-invariant input, while the answer depends on it
(a knight has 2.96 destinations on the rim and 6.85 in the middle, and 43% sit on the rim);
and rank was not oriented to the piece's own side, which splits one pawn law into two
mirrored ones.
Every memory null measured before these were fixed stands as a fact about that setup and
about nothing else. Before asking what a mechanism adds, check that the domain's own laws
are expressible in the inputs, the target, and the training distribution.
- **Pre-register when the result could be argued either way.** State the success criterion,
the seed count, and what counts as failure, in `.sdd/progress.md`, before the run. Then
accept what comes back. No re-running with adjusted criteria.
+112 -11
View File
@@ -36,6 +36,7 @@ import json
import statistics
from pathlib import Path
import chess
import numpy as np
import torch
@@ -43,6 +44,28 @@ 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
@@ -58,12 +81,60 @@ def unpack(ply) -> np.ndarray:
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:
@@ -87,9 +158,13 @@ def _stream(org, game, opt, bptt: int, edges: bool, adjacency: bool):
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()]
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)
@@ -98,7 +173,7 @@ def _stream(org, game, opt, bptt: int, edges: bool, adjacency: bool):
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
return losses, prec, chance, by_type, by_block
def run(games, memory: bool, hidden: int, cppn_hidden: int, seed: int, lr: float, bptt: int,
@@ -111,15 +186,17 @@ def run(games, memory: bool, hidden: int, cppn_hidden: int, seed: int, lr: float
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))
loss, prec, chance, tsum, bsum = [], [], [], np.zeros((6, 2)), np.zeros((6, 2, 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
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_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:
@@ -135,7 +212,7 @@ def run_constant(games, seed: int) -> dict:
for ply in games[gi]:
marg += unpack(ply).sum(0)
rank = torch.from_numpy((-marg).argsort().argsort())
prec, chance, tsum = [], [], np.zeros((6, 2))
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))
@@ -143,11 +220,17 @@ def run_constant(games, seed: int) -> dict:
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()]
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_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:
@@ -159,13 +242,13 @@ def main() -> None:
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("--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, "rp": (False, False), "rp_type": (False, True),
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")
@@ -174,6 +257,7 @@ def main() -> None:
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} "
@@ -192,6 +276,23 @@ def main() -> None:
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
+310
View File
@@ -0,0 +1,310 @@
"""How the pieces move, taught directly instead of inferred from games.
Two things games got wrong as a curriculum, both measured rather than assumed:
**Coverage.** In real play a rook or queen is blocked in 98-100% of positions
(`chess_shape.json`), so the model learns the geometry it sees rather than the rule that
generates it -- it scored *worse* in open positions than blocked ones. Here the number of
pieces is sampled uniformly from 2 to 32, so an empty board is as common as a crowded one.
**The target left out three rules entirely.** `board.attacks` is what the reachability task
asked for, and for a pawn on e2 it returns d3 and f3 while the pawn's actual moves are e3 and
e4 -- *no overlap at all*. Castling never appeared (the king's attack set is five adjacent
squares; c1 and g1 are not in it). Nor did en passant. The model did not fail to learn these;
it was never asked. The target here is `generate_pseudo_legal_moves`, which carries pushes,
castling and en passant.
Castling rights and the en-passant square are **state, not position**: a rook must remember
whether it has moved, and en passant depends on the opponent's last move. They are handed over
as per-entity attributes here so the rule is learnable at all -- without them the same board
has two different correct answers. Taking them away is the cleanest memory experiment this
project has available, and it belongs to the GRP line, which is parked (`AGENTS.md`).
No memory in this file. One position, one answer, no stream: this is the RP question alone.
"""
from __future__ import annotations
import argparse
import json
import statistics
from dataclasses import dataclass
from pathlib import Path
import chess
import numpy as np
import torch
from ailed import Affect, Organism
from chess_domain import flat_diff
from chess_reach import GRID, OFFSET
# type (6), colour (1), castling right (1), ep flag (1), file, rank, rank-from-my-own-side (3)
ATTR_DIM = 12
# The last three exist because the CPPN sees only r_ij, which makes the representation
# translation-invariant -- and a chess board has EDGES. A knight on the rim has 2.96
# destinations on average and one in the middle has 6.85, and 43% of knights sit on the rim
# (measured). Relative geometry to other pieces cannot recover that on a near-empty board.
# `own_rank` is rank from the piece's own back rank: a pawn's push, its double-push rank, its
# promotion rank and castling are all one law in that frame and two mirrored laws without it.
HOME = ((chess.WHITE, chess.E1, chess.H1, chess.A1), (chess.BLACK, chess.E8, chess.H8, chess.A8))
@dataclass
class Position:
attrs: np.ndarray # (N, 9)
coords: np.ndarray # (N, 2)
types: np.ndarray # (N,) 0-5, for the per-type breakdown
y: np.ndarray # (N, 225) multi-hot over relative offsets
shape: np.ndarray # (N, 225) what knowing the rule alone would answer
def _rights(b: chess.Board, rng) -> None:
fen = ""
for col, k_sq, r_k, r_q in HOME:
if b.piece_at(k_sq) == chess.Piece(chess.KING, col):
for r_sq, ch in ((r_k, "k"), (r_q, "q")):
if b.piece_at(r_sq) == chess.Piece(chess.ROOK, col) and rng.random() < 0.7:
fen += ch.upper() if col else ch
b.set_castling_fen(fen or "-")
def random_board(rng) -> chess.Board | None:
"""A position sampled for coverage, not for plausibility. Density is uniform by design."""
for _ in range(60):
b = chess.Board(None)
sqs = rng.permutation(64)
b.set_piece_at(int(sqs[0]), chess.Piece(chess.KING, chess.WHITE))
b.set_piece_at(int(sqs[1]), chess.Piece(chess.KING, chess.BLACK))
for sq in sqs[2:int(rng.integers(2, 33))]:
pt = int(rng.choice([1, 2, 3, 4, 5], p=[0.42, 0.16, 0.16, 0.16, 0.10]))
if pt == chess.PAWN and chess.square_rank(int(sq)) in (0, 7):
continue
b.set_piece_at(int(sq), chess.Piece(pt, bool(rng.integers(2))))
b.turn = bool(rng.integers(2))
_rights(b, rng)
if not b.is_valid():
continue
# an en-passant square, where a pawn sits as if it had just double-pushed
rank = 4 if b.turn == chess.WHITE else 3
cands = [s for s in chess.SQUARES if b.piece_at(s) == chess.Piece(chess.PAWN, not b.turn)
and chess.square_rank(s) == rank]
if cands and rng.random() < 0.35:
keep = b.ep_square
b.ep_square = int(rng.choice(cands)) + (8 if b.turn == chess.WHITE else -8)
if not b.is_valid():
b.ep_square = keep
return b
return None
def _dests(b: chess.Board) -> dict[int, set[int]]:
"""Every piece's pseudo-legal destinations, for both colours. Pushes, castling, ep."""
out: dict[int, set[int]] = {}
turn = b.turn
for col in (chess.WHITE, chess.BLACK):
b.turn = col
for m in b.generate_pseudo_legal_moves():
out.setdefault(m.from_square, set()).add(m.to_square)
b.turn = turn
return out
_RULE_CACHE: dict[tuple, frozenset] = {}
def _rule_only(piece: chess.Piece, sq: int, right: bool, ep: int | None) -> set[int]:
"""The control: this piece's moves on an EMPTY board, plus its own flags. Reads nothing.
Memoised: it is deterministic in its arguments and was rebuilding a Board per piece per
position, which dominated generation.
"""
key = (piece.piece_type, piece.color, sq, right, ep)
if key in _RULE_CACHE:
return _RULE_CACHE[key]
b = chess.Board(None)
b.set_piece_at(sq, piece)
b.turn = piece.color
b.set_castling_fen("-")
out = {m.to_square for m in b.generate_pseudo_legal_moves()}
if right and piece.piece_type == chess.KING:
out |= {sq - 2, sq + 2} # both castling destinations
if ep is not None and piece.piece_type == chess.PAWN:
out.add(ep)
_RULE_CACHE[key] = frozenset(out)
return _RULE_CACHE[key]
def build(b: chess.Board) -> Position:
dests = _dests(b)
squares = sorted(b.piece_map())
n = len(squares)
attrs = np.zeros((n, ATTR_DIM), dtype=np.float32)
coords = np.zeros((n, 2), dtype=np.float32)
types = np.zeros(n, dtype=np.int64)
y = np.zeros((n, GRID), dtype=np.float32)
shape = np.zeros((n, GRID), dtype=np.float32)
for k, sq in enumerate(squares):
p = b.piece_at(sq)
types[k] = p.piece_type - 1
attrs[k, p.piece_type - 1] = 1.0
attrs[k, 6] = float(p.color == chess.WHITE)
right = ((p.piece_type == chess.KING and bool(b.castling_rights & (
chess.BB_RANK_1 if p.color else chess.BB_RANK_8)))
or (p.piece_type == chess.ROOK and bool(b.castling_rights & chess.BB_SQUARES[sq])))
attrs[k, 7] = float(right)
ep = b.ep_square if (b.ep_square is not None and p.piece_type == chess.PAWN
and b.ep_square in _rule_only(p, sq, False, None)) else None
attrs[k, 8] = float(ep is not None)
f, r = chess.square_file(sq), chess.square_rank(sq)
coords[k] = (f / 7.0, r / 7.0)
attrs[k, 9] = f / 7.0
attrs[k, 10] = r / 7.0
attrs[k, 11] = (r if p.color == chess.WHITE else 7 - r) / 7.0
for t in dests.get(sq, ()):
y[k, OFFSET[sq][t]] = 1.0
for t in _rule_only(p, sq, right, ep):
if 0 <= t < 64:
shape[k, OFFSET[sq][t]] = 1.0
return Position(attrs, coords, types, y, shape)
def stream(n: int, seed: int):
"""Positions are generated, never stored: training is a single pass and 200k dense targets
would be 6 GB. The test set is materialised because every arm must see the same one."""
rng = np.random.default_rng(seed)
made = 0
while made < n:
b = random_board(rng)
if b is not None:
made += 1
yield build(b)
def _precision(score: np.ndarray, y: np.ndarray):
"""precision@k per entity, k = the true number of destinations."""
s = torch.as_tensor(score); yy = torch.as_tensor(y)
k = yy.sum(1)
keep = k > 0
rank = s.argsort(1, descending=True).argsort(1)
hit = ((rank < k[:, None]) & (yy > 0)).sum(1) / k.clamp(min=1)
return hit, keep, k
def evaluate(scores, batch, tsum):
hit, keep, k = _precision(scores, batch.y)
if not keep.any():
return [], []
np.add.at(tsum, (batch.types[keep.numpy()], 0), hit[keep].numpy())
np.add.at(tsum, (batch.types[keep.numpy()], 1), 1.0)
return list(hit[keep].numpy()), list((k[keep] / GRID).numpy())
EDGES = {"none": 1, "type": 6, "typecol": 12}
def _edge_types(pos: Position, kind: str, n: int):
"""What the CPPN is told about the pieces it relates, beyond their geometry.
`type` shares one kernel between a white pawn and a black pawn, whose moves are mirrored --
which is why the type-conditional arm lost 0.14 on pawns and nothing elsewhere. `typecol`
gives each colour its own.
"""
if kind == "none":
return None
t = torch.from_numpy(pos.types if kind == "type"
else pos.types * 2 + (1 - pos.attrs[:, 6].astype(np.int64)))
return t[:, None].expand(n, n).contiguous()
def run(n_train: int, seed_train: int, test, hidden: int, cppn_hidden: int, seed: int,
lr: float, batch: int, edges: str) -> dict:
torch.manual_seed(seed)
org = Organism(ATTR_DIM, 2, GRID, n_edge_types=EDGES[edges], hidden_dim=hidden,
cppn_hidden=cppn_hidden, memory=False)
opt = torch.optim.Adam(org.parameters(), lr=lr)
zero = Affect().axes
pending = []
for pos in stream(n_train, seed_train):
n = len(pos.types)
pred, _ = org(torch.from_numpy(pos.attrs), flat_diff(torch.from_numpy(pos.coords)),
list(range(n)), zero, {}, edge_types=_edge_types(pos, edges, n))
pending.append(torch.nn.functional.binary_cross_entropy_with_logits(
pred, torch.from_numpy(pos.y)))
if len(pending) == batch:
opt.zero_grad(); torch.stack(pending).mean().backward(); opt.step(); pending = []
prec, chance, tsum = [], [], np.zeros((6, 2))
with torch.no_grad():
for pos in test:
n = len(pos.types)
pred, _ = org(torch.from_numpy(pos.attrs), flat_diff(torch.from_numpy(pos.coords)),
list(range(n)), zero, {}, edge_types=_edge_types(pos, edges, n))
p, c = evaluate(pred.numpy(), pos, tsum)
prec += p; chance += c
return dict(seed=seed, params=sum(q.numel() for q in org.parameters()),
prec=statistics.fmean(prec), chance=statistics.fmean(chance),
by_type=list(tsum[:, 0] / np.maximum(tsum[:, 1], 1)))
def run_baseline(n_marg: int, seed_train: int, test, seed: int, kind: str) -> dict:
"""`shape` knows each piece's rule and reads no other piece. `constant` knows neither."""
marg = np.zeros(GRID)
for pos in stream(n_marg, seed_train):
marg += pos.y.sum(0)
marg /= max(marg.max(), 1.0)
prec, chance, tsum = [], [], np.zeros((6, 2))
for pos in test:
score = np.tile(marg, (len(pos.types), 1)) * 0.5
if kind == "shape":
score = score + pos.shape
p, c = evaluate(score, pos, tsum)
prec += p; chance += c
return dict(seed=seed, params=0, 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("--positions", type=int, default=200000)
ap.add_argument("--test", type=int, default=4000)
ap.add_argument("--seeds", default="0,1,2,3")
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("--batch", type=int, default=16)
ap.add_argument("--arms", default="constant,shape,rp,rp_type,rp_typecol")
ap.add_argument("--out", default="results/chess_rules.json")
a = ap.parse_args()
test = list(stream(a.test, 10_000)) # a different seed: never a training position
print(f"{a.positions} training positions streamed, {a.test} held out "
f"({sum(int(p.y.sum()) for p in test)} moves to predict), "
f"{a.positions // a.batch} optimiser steps\n")
results = []
for name in a.arms.split(","):
for seed in (int(s) for s in a.seeds.split(",")):
r = (run_baseline(min(a.positions, 5000), seed, test, seed, name)
if name in ("constant", "shape") else
run(a.positions, seed, test, a.hidden, a.cppn_hidden, seed, a.lr, a.batch,
{"rp": "none", "rp_type": "type",
"rp_typecol": "typecol"}[name])) | {"arm": name}
print(f"{name:<10} seed={seed} params={r['params']:<6} 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))
names = ["pawn", "knight", "bishop", "rook", "queen", "king"]
by = {n: [r for r in results if r["arm"] == n] for n in a.arms.split(",")}
print(f"\n{'arm':<10}{'prec@k':>9}" + "".join(f"{t:>9}" for t in names))
print("-" * (19 + 9 * 6))
for n, rs in by.items():
print(f"{n:<10}{statistics.fmean(r['prec'] for r in rs):>9.4f}"
+ "".join(f"{statistics.fmean(r['by_type'][i] for r in rs):>9.4f}" for i in range(6)))
print(f"\nrandom ranking would score {statistics.fmean(r['chance'] for r in results):.4f}")
if __name__ == "__main__":
main()
+114
View File
@@ -0,0 +1,114 @@
# Teaching the movement rules, on generated positions
The organism was never taught how the pieces move. Every memory result before this file was
measured on top of that gap. This is the base.
**Where it stands: the RP learns the rules from a generated curriculum and, on the pieces where
reading the board matters most, exceeds a control that knows the rules and cannot see.**
## Why not games
Two failures of games as a curriculum, both measured rather than argued:
- **Coverage.** A rook or queen is blocked in 98-100% of real positions (`chess_shape.json`), so
the model learned the geometry it saw instead of the rule behind it — it scored *worse* in
open positions (rook 0.811) than blocked ones (0.891). Here the piece count is sampled
uniformly from 2 to 32, so a near-empty board is as common as a crowded one, and every piece
type visits all its legal squares: measured at 3000 positions, a knight lands on each of the
64 squares between 65 and 107 times.
- **The target left out three rules entirely.** The reachability task asked for
`board.attacks`, which for a pawn on e2 returns d3 and f3 while its moves are e3 and e4 —
**no overlap at all**. Castling never appeared (a king's attack set is its five adjacent
squares; c1 and g1 are not in it) and neither did en passant. The model did not fail to learn
these. It was never asked. The target here is `generate_pseudo_legal_moves`.
## Setup
300 000 generated positions streamed for training (never stored: dense targets would be 6 GB),
4 000 held out from a disjoint seed. Target: every piece's pseudo-legal destinations, as a
multi-hot over the 15x15 grid of relative offsets. Metric: precision@k per piece, k the true
number of destinations. 4 seeds. No memory anywhere in this file — this is the RP question
alone, per the sequencing policy in `AGENTS.md`.
**`shape` is the control**: it knows each piece's type, its movement rule and its own flags, and
reads *nothing else on the board*. It proposes the un-blocked ray. Beating it is what "reads the
occupancy" means, and it is the bar this file is measured against — not 1.0.
Castling rights and the en-passant square are handed over as per-entity attributes. They are
**state, not position** — a rook must remember whether it has moved — and without them the same
board has two different correct answers. Removing them is the cleanest memory experiment this
project has available, with exact ground truth instead of a 0.03 correlation, and it belongs to
the parked GRP line.
## Results
```
arm prec@k pawn knight bishop rook queen king
constant 0.4075 0.4491 0.0000 0.1730 0.4947 0.5609 0.7781
rp_type 0.7793 0.6573 0.8574 0.7856 0.7569 0.7510 0.9124
rp 0.8161 0.7835 0.8481 0.7748 0.7837 0.7680 0.9227
shape 0.8305 0.8156 0.8624 0.8299 0.7679 0.7618 0.9134
random ranking scores 0.0233
```
**The RP exceeds the rule-knower on rook (+0.016), queen (+0.006) and king (+0.009)** — the
pieces whose moves are cut by occupancy, where ignoring the board costs most. It remains below
on pawn (-0.032), bishop (-0.055) and knight (-0.014).
Absolute position, added as attributes, is worth +0.020 and closes the gap to `shape` from
0.034 to 0.014:
```
without position with position
rp 0.7962 0.8161
rp_type 0.7583 0.7793
shape (was always given it) 0.8305 0.8305
```
The CPPN sees only `r_ij`, which makes the representation translation-invariant, and a chess
board has edges: a knight has 2.96 destinations on the rim against 6.85 in the middle, and 43%
of knights sit on the rim. `shape` was handed the square all along, so the comparison had been
biased *against* the organism.
**A prediction that did not verify.** The improvement was predicted to concentrate on rim
pieces. Per type it is roughly flat — pawn +0.008, knight +0.016, bishop +0.028, rook +0.028,
queen +0.029, king +0.022 — and the knight, 43% of which sit on the rim, gained *less* than the
queen. The per-type cut cannot settle a per-square hypothesis, so this is recorded as
unverified rather than as either confirmed or refuted. Position pays; the mechanism proposed
for why it pays is not demonstrated.
## Type in the kernel reverses sign with coverage
On game data, putting the piece type into `e_ij` was worth +0.10 and took the knight's L from
exactly zero to 0.758 (`chess_reach.md`). On the generated curriculum `rp_type` lands *below*
`rp`, and the whole deficit is the pawn: 0.6573 against 0.7835, with knight and bishop still
slightly ahead. That earlier jump was in part a crutch against scarce data.
The likely cause is specific and testable: `e_ij` carries the piece **type** and not its
**colour**, so a white pawn and a black pawn share one kernel while their moves are mirrored.
`own_rank` — rank counted from the piece's own back rank — is present in this run and did not
fix it on its own, which points at the colour rather than the orientation.
**In flight:** `rp_typecol`, twelve kernels (type x colour) instead of six. Seed 0 reads
**0.8330**, above `shape`'s 0.8305 and above `rp`'s 0.8161. One seed, not a result yet.
## Limits
- One training pass, no schedule, no ordering. A graded curriculum (piece alone, then one
blocker, then a full board) has not been tried; the sampler is i.i.d.
- The model is still data-limited: 6k positions gave 0.41, 30k gave 0.61, 300k gives 0.82. It
had not plateaued at any budget measured.
- Legality of the *position* is not modelled: these are sampled placements, valid but not
reachable from the opening.
- Pins and check are excluded — the target is pseudo-legal. King safety is a global rule and a
separate question.
- `shape` is a control, not a ceiling: it scores 0.83 because it cannot see the board, and the
true ceiling is 1.0.
Reproduce with:
```bash
uv run --with chess python chess_rules.py --positions 300000 --seeds 0,1,2,3
uv run --with chess python chess_rules.py --positions 300000 --seeds 0,1,2,3 --arms rp_typecol
```