diff --git a/chess_domain.py b/chess_domain.py new file mode 100644 index 0000000..872d274 --- /dev/null +++ b/chess_domain.py @@ -0,0 +1,249 @@ +"""Chess under contract A: which piece moves is given, where it goes is predicted. + +Spec §2, contract A, on the chess instance. What justified coming here is +`results/chess_history.md`: a piece's own past predicts its next square beyond the board, ++0.034 with a non-linear decoder. That measured headroom is what this file spends. + +Two design decisions, both load-bearing. + +**The target is the mover's displacement, and the loss is masked to the mover.** Exactly one +piece moves per ply, so the spec's literal default -- every entity's displacement -- is 31/32 +zeros and the constant predictor "nobody moves" wins. That leaves a mechanism no job, which is +the shape of four nulls in the predecessor project. The cost of the fix is that the model is +told *which* piece moves. It is not told where it goes, and this is the same conditioning the +probe measured under, so the probe's number is the ceiling on this task and not on some other. + +**Affect is held neutral.** psi = (0, 0), kappa = 0, so the only thing separating the arms is +per-entity memory. `--affect stream` runs the real EMA chain instead; it exists so the neutral +default is a choice rather than an absence. + +There is no regime switch in chess. A1 -- arousal opens the gate after an unannounced change -- +has no analogue here and is not tested by this file. +""" +from __future__ import annotations + +import argparse +import json +import statistics +from dataclasses import dataclass +from pathlib import Path + +import chess +import chess.pgn +import numpy as np +import torch + +from ailed import Affect, AffectConfig, Organism, detach_memory, update + +PGN = "/Users/chrnx/workspace/ailed/model/data/slice.pgn" +ATTR_DIM = 8 # piece type (6), colour (1), "this is the one that moves" (1) +SCALE = 7.0 # file/rank -> [0,1], so a relation lands in [-1,1] like the torus does + + +def flat_diff(coords: torch.Tensor) -> torch.Tensor: + """r_ij = c_j - c_i. Chess is flat: no wrap, unlike `particles.wrapped_diff`.""" + return coords[None, :, :] - coords[:, None, :] + + +@dataclass +class Ply: + ids: list[int] # stable piece ids, the row order of everything below + attrs: np.ndarray # (N, ATTR_DIM) + coords: np.ndarray # (N, 2) file, rank, scaled + mover: int # row index of the piece that moves + target: np.ndarray # (2,) that piece's displacement + dests: np.ndarray # (L, 2) displacement of every legal move from its square + true_dest: int # index into dests + + +def advance_ids(board: chess.Board, move: chess.Move, piece: chess.Piece, + id_at: dict[int, int]) -> None: + """Follow piece identity across a move, so "this knight" means the same knight later. + + Castling moves the rook too; en passant removes a pawn from a square the mover never + touches; promotion keeps the identity and changes only the type. + + ponytail: this repeats the bookkeeping inside `chess_history.py` rather than importing it. + That file is a committed measurement and is left untouched; the two must agree, and + `plies()` asserts the result stays in sync with the board either way. + """ + if board.is_en_passant(move): + id_at.pop(move.to_square + (-8 if piece.color == chess.WHITE else 8), None) + id_at.pop(move.to_square, None) # a normal capture + id_at[move.to_square] = id_at.pop(move.from_square, move.from_square) + if board.is_castling(move): + back = 0 if piece.color == chess.WHITE else 56 + r_from, r_to = ((back + 7, back + 5) if chess.square_file(move.to_square) == 6 + else (back, back + 3)) + if r_from in id_at: + id_at[r_to] = id_at.pop(r_from) + + +def plies(game: chess.pgn.Game) -> list[Ply]: + board = game.board() + id_at = {sq: sq for sq in chess.SQUARES if board.piece_at(sq)} + out: list[Ply] = [] + for move in game.mainline_moves(): + piece = board.piece_at(move.from_square) + if piece is None: + break + # the identity map must name exactly the occupied squares, or a memory slot is + # following the wrong piece and every number downstream is meaningless + assert id_at.keys() == board.piece_map().keys(), "identity map drifted from the board" + squares = sorted(id_at) + attrs = np.zeros((len(squares), ATTR_DIM), dtype=np.float32) + coords = np.zeros((len(squares), 2), dtype=np.float32) + for k, sq in enumerate(squares): + p = board.piece_at(sq) + attrs[k, p.piece_type - 1] = 1.0 + attrs[k, 6] = float(p.color == chess.WHITE) + coords[k] = (chess.square_file(sq) / SCALE, chess.square_rank(sq) / SCALE) + mover = squares.index(move.from_square) + attrs[mover, 7] = 1.0 + + # every legal destination for that piece, as a displacement; promotions collapse + legal = list(dict.fromkeys(m.to_square for m in board.legal_moves + if m.from_square == move.from_square)) + dests = np.array([[(chess.square_file(t) - chess.square_file(move.from_square)) / SCALE, + (chess.square_rank(t) - chess.square_rank(move.from_square)) / SCALE] + for t in legal], dtype=np.float32) + j = legal.index(move.to_square) + out.append(Ply([id_at[sq] for sq in squares], attrs, coords, mover, dests[j], dests, j)) + + advance_ids(board, move, piece, id_at) + board.push(move) + return out + + +def load(n_games: int, min_plies: int = 20) -> list[list[Ply]]: + games: list[list[Ply]] = [] + with open(PGN, encoding="utf-8", errors="replace") as fh: + while len(games) < n_games: + g = chess.pgn.read_game(fh) + if g is None: + break + p = plies(g) + if len(p) >= min_plies: + games.append(p) + return games + + +def n_params(memory: bool, hidden: int, cppn_hidden: int) -> int: + org = Organism(ATTR_DIM, 2, 2, hidden_dim=hidden, cppn_hidden=cppn_hidden, memory=memory) + return sum(p.numel() for p in org.parameters()) + + +def match_width(hidden: int, cppn_hidden: int) -> int: + """The memoryless width whose parameter count lands nearest the gated model's. + + `rp_only` at 1442 against `grp_k0` at 5602 is confounded 3.9x and is not a memory + result (`results/frozen.md` §1d). This is how that confound is removed here. + """ + target = n_params(True, hidden, cppn_hidden) + return min(range(hidden, 8 * hidden), + key=lambda h: abs(n_params(False, h, cppn_hidden) - target)) + + +def _stream(org: Organism, game: list[Ply], affect: Affect, acfg: AffectConfig, + opt: torch.optim.Optimizer | None, bptt: int, use_affect: bool): + """One game as one continuous stream. Memory starts empty: new game, new pieces.""" + memory: dict[int, torch.Tensor] = {} + pending: list[torch.Tensor] = [] + losses, hits, chance = [], [], [] + with torch.set_grad_enabled(opt is not None): + for ply in game: + coords = torch.from_numpy(ply.coords) + pred, memory = org(torch.from_numpy(ply.attrs), flat_diff(coords), ply.ids, + affect.axes, memory) + p = pred[ply.mover] + loss = ((p - torch.from_numpy(ply.target)) ** 2).mean() # masked to the mover + if use_affect: + affect = update(affect, loss.item(), acfg) + losses.append(loss.item()) + # snap to the nearest legal destination, so the number is comparable to the + # accuracies in results/chess_history.md rather than to a raw MSE + k = int(((torch.from_numpy(ply.dests) - p.detach()) ** 2).sum(1).argmin()) + hits.append(float(k == ply.true_dest)) + chance.append(1.0 / len(ply.dests)) + 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 affect, losses, hits, chance + + +def run(games: list[list[Ply]], memory: bool, hidden: int, cppn_hidden: int, seed: int, + lr: float, bptt: int, kappa: float, use_affect: bool) -> dict: + torch.manual_seed(seed) + org = Organism(ATTR_DIM, 2, 2, hidden_dim=hidden, cppn_hidden=cppn_hidden, + kappa=kappa, memory=memory) + opt = torch.optim.Adam(org.parameters(), lr=lr) + acfg, affect = AffectConfig(), Affect() + + # split by GAME, never inside one: two positions from one game share almost everything + order = np.random.default_rng(seed).permutation(len(games)) + cut = max(1, len(games) // 4) + for gi in order[cut:]: + affect, *_ = _stream(org, games[gi], affect, acfg, opt, bptt, use_affect) + mse, hits, chance = [], [], [] + for gi in order[:cut]: + affect, l, h, c = _stream(org, games[gi], affect, acfg, None, bptt, use_affect) + mse += l; hits += h; chance += c + return dict(seed=seed, hidden=hidden, memory=memory, + params=sum(p.numel() for p in org.parameters()), plies=len(mse), + mse=statistics.fmean(mse), acc=statistics.fmean(hits), + chance=statistics.fmean(chance)) + + +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("--kappa", type=float, default=0.0) + ap.add_argument("--affect", default="neutral", choices=("neutral", "stream"), + help="neutral holds psi at (0,0); stream runs the real EMA chain") + ap.add_argument("--out", default="results/chess.json") + a = ap.parse_args() + + games = load(a.games) + wide = match_width(a.hidden, a.cppn_hidden) + arms = {"rp": (False, a.hidden), "grp": (True, a.hidden), "rp_wide": (False, wide)} + print(f"{len(games)} games, {sum(len(g) for g in games)} plies; " + f"width-matched memoryless arm at hidden={wide}\n") + + results = [] + for name, (mem, h) in arms.items(): + for seed in (int(s) for s in a.seeds.split(",")): + r = run(games, mem, h, a.cppn_hidden, seed, a.lr, a.bptt, a.kappa, + a.affect == "stream") | {"arm": name} + print(f"{name:<8} seed={seed} params={r['params']:<6} " + f"mse={r['mse']:.5f} acc={r['acc']:.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} + print(f"\n{'arm':<8}{'params':>8}{'mse':>10}{'acc':>9}{'chance':>9}") + print("-" * 44) + for n, rs in by.items(): + print(f"{n:<8}{rs[0]['params']:>8}{statistics.fmean(r['mse'] for r in rs):>10.5f}" + f"{statistics.fmean(r['acc'] for r in rs):>9.4f}" + f"{statistics.fmean(r['chance'] for r in rs):>9.4f}") + for base in ("rp", "rp_wide"): + d = [g["acc"] - b["acc"] for g, b in zip(by["grp"], by[base])] + se = statistics.stdev(d) / len(d) ** 0.5 if len(d) > 1 else float("nan") + verdict = "ambiguous" if abs(statistics.fmean(d)) < se else "a direction" + print(f"\ngrp - {base}: {statistics.fmean(d):+.4f} +/- {se:.4f} (paired se), " + f"{sum(x > 0 for x in d)}/{len(d)} seeds -- {verdict}") + + +if __name__ == "__main__": + main() diff --git a/tests/test_chess_domain.py b/tests/test_chess_domain.py new file mode 100644 index 0000000..3d09d39 --- /dev/null +++ b/tests/test_chess_domain.py @@ -0,0 +1,48 @@ +"""Identity is the load-bearing part: a memory slot must follow the same piece. + +If `advance_ids` drifts, every arm still trains and every number still prints -- the memory +just follows the wrong piece. That failure is silent, so it gets the test. +""" +import chess +import chess.pgn +import pytest + +import chess_domain + + +def _game(fen: str | None, sans: list[str]) -> chess.pgn.Game: + board = chess.Board(fen) if fen else chess.Board() + for san in sans: + board.push_san(san) + return chess.pgn.Game.from_board(board) + + +CASTLE_EP = ["e4", "e5", "Nf3", "Nf6", "Bc4", "Bc5", "O-O", "O-O", + "d4", "exd4", "e5", "d5", "exd6"] + + +def test_rook_keeps_its_id_through_castling(): + plies = chess_domain.plies(_game(None, CASTLE_EP)) + h1 = chess.H1 + after = next(p for p in plies if h1 not in # h1 empty: rook has moved + [chess.square(int(c[0] * 7), int(c[1] * 7)) for c in p.coords]) + f1_row = [k for k, c in enumerate(after.coords) + if chess.square(int(c[0] * 7), int(c[1] * 7)) == chess.F1][0] + assert after.ids[f1_row] == h1, "the castled rook was handed a new identity" + + +def test_promoted_pawn_keeps_its_id_and_changes_type(): + plies = chess_domain.plies(_game("1r4k1/P7/8/8/8/8/8/6K1 w - - 0 1", ["axb8=Q", "Kf7"])) + row = plies[-1].ids.index(chess.A7) # the pawn that started on a7 + coords = plies[-1].coords[row] + assert chess.square(int(coords[0] * 7), int(coords[1] * 7)) == chess.B8 + assert plies[-1].attrs[row][chess.QUEEN - 1] == 1.0, "promotion did not change the type" + + +def test_the_identity_assertion_can_actually_fire(monkeypatch): + """Sabotage: stop tracking captures, and the board must disagree with the map.""" + monkeypatch.setattr(chess_domain, "advance_ids", + lambda board, move, piece, id_at: id_at.update( + {move.to_square: id_at.pop(move.from_square, move.from_square)})) + with pytest.raises(AssertionError, match="drifted"): + chess_domain.plies(_game(None, CASTLE_EP))