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.
311 lines
13 KiB
Python
311 lines
13 KiB
Python
"""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()
|