diff --git a/chess_history.py b/chess_history.py new file mode 100644 index 0000000..5172841 --- /dev/null +++ b/chess_history.py @@ -0,0 +1,171 @@ +"""Does a piece's own past predict its next move, beyond the current board? + +The same question `identify.py` asked of the particles domain, asked of chess. Nothing here +builds or trains the organism — this measures a property of the domain. + +In particles the answer was that the past held the hidden variable almost perfectly (one +observed displacement identified the regime at 0.958) while the present held much less. The +per-entity version of that question is different and is the one chess is supposed to answer +differently: does *this piece's own history* say something about where it goes next that the +current board does not? + +Two predictors of the same target, given the same conditioning: + + A (present) board occupancy, the moving piece's type and colour, its current square + B (+history) the same, plus the squares that piece occupied on its previous moves + +The gap B - A is the per-entity history's contribution. If it is ~0, chess is like particles +for this purpose and a per-entity memory has nothing to carry. +""" +from __future__ import annotations + +import argparse +import random +from collections import defaultdict + +import chess +import chess.pgn +import numpy as np + +PGN = "/Users/chrnx/workspace/ailed/model/data/slice.pgn" + + +def piece_histories(game: chess.pgn.Game, hist: int): + """Yield (piece_key, from_sq, to_sq, prev_squares, board) per move, tracking identity. + + Identity is the point: `id_at[square]` follows a piece across its moves so that "this + knight" means the same knight ten moves later. Castling moves the rook too; en passant + removes a pawn from a square the mover never touches; promotion keeps the identity and + changes the type. + """ + board = game.board() + id_at: dict[int, int] = {sq: sq for sq in chess.SQUARES if board.piece_at(sq)} + past: dict[int, list[int]] = defaultdict(list) + nxt = 64 + + for move in game.mainline_moves(): + piece = board.piece_at(move.from_square) + if piece is None: + return + key = id_at.get(move.from_square) + if key is None: + key = nxt; nxt += 1 + prev = past[key][-hist:] + yield key, move.from_square, move.to_square, prev, board.copy(stack=False), piece + + # advance identity bookkeeping alongside the board + if board.is_en_passant(move): + cap = move.to_square + (-8 if piece.color == chess.WHITE else 8) + id_at.pop(cap, None) + id_at.pop(move.to_square, None) # a normal capture + id_at[move.to_square] = id_at.pop(move.from_square, key) + 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) + past[key].append(move.from_square) + board.push(move) + + +def features(from_sq, prev, board, piece, hist: int, with_history: bool): + """Present-only features, then optionally the piece's own past squares.""" + f = np.zeros(64 + 6 + 1 + 64 + (64 * hist if with_history else 0), dtype=np.float32) + f[from_sq] = 1.0 # where it is now + f[64 + piece.piece_type - 1] = 1.0 # what it is + f[70] = 1.0 if piece.color == chess.WHITE else 0.0 + occ = board.occupied + for sq in chess.SQUARES: # what the board looks like + if occ >> sq & 1: + f[71 + sq] = 1.0 + if with_history: + base = 135 + for i in range(hist): # where it has been + if i < len(prev): + f[base + i * 64 + prev[-1 - i]] = 1.0 + return f + + +def collect(n_games: int, hist: int, min_moves: int, seed: int): + rng = random.Random(seed) + A, B, y, gid = [], [], [], [] + with open(PGN, encoding="utf-8", errors="replace") as fh: + for g in range(n_games): + game = chess.pgn.read_game(fh) + if game is None: + break + for key, frm, to, prev, board, piece in piece_histories(game, hist): + if len(prev) < min_moves: # only pieces with a history to speak of + continue + A.append(features(frm, prev, board, piece, hist, False)) + B.append(features(frm, prev, board, piece, hist, True)) + y.append(to) + gid.append(g) + return np.array(A), np.array(B), np.array(y), np.array(gid) + + +def fit_eval(Xtr, ytr, Xte, yte, l2: float = 1.0): + """Ridge onto one-hot targets, argmax at test. One estimator for both arms, so the + difference between them is about the features and not about the fit.""" + K = 64 + Y = np.zeros((len(ytr), K), dtype=np.float32) + Y[np.arange(len(ytr)), ytr] = 1.0 + d = Xtr.shape[1] + W = np.linalg.solve(Xtr.T @ Xtr + l2 * np.eye(d, dtype=np.float32), Xtr.T @ Y) + return float((np.argmax(Xte @ W, axis=1) == yte).mean()) + + +def main() -> None: + ap = argparse.ArgumentParser() + ap.add_argument("--games", type=int, default=3000) + ap.add_argument("--hist", type=int, default=3, help="how many past squares B may see") + ap.add_argument("--min-moves", type=int, default=2, help="skip a piece's first moves") + ap.add_argument("--seeds", default="0,1,2,3,4,5,6,7,8,9,10,11") + a = ap.parse_args() + + A, B, y, gid = collect(a.games, a.hist, a.min_moves, 0) + print(f"{len(y)} moves from {gid.max() + 1} games, {A.shape[1]} present features, " + f"{B.shape[1]} with history\n") + + gains = [] + print(f"{'seed':>5}{'present':>10}{'+history':>10}{'gain':>9}{'shuffled':>10}") + print("-" * 44) + for s in (int(x) for x in a.seeds.split(",")): + # split by GAME, never by position: two positions from one game share almost + # everything, and splitting inside a game leaks the answer across the split. + games = np.unique(gid) + rng = np.random.default_rng(s) + rng.shuffle(games) + te = np.isin(gid, games[: max(1, len(games) // 4)]) + tr = ~te + acc_a = fit_eval(A[tr], y[tr], A[te], y[te]) + acc_b = fit_eval(B[tr], y[tr], B[te], y[te]) + # chance for the history arm: same features, history block shuffled across rows, + # so its marginal is intact and only its alignment with the target is broken + Bs = B.copy() + idx = rng.permutation(len(Bs)) + Bs[:, 135:] = Bs[idx, 135:] + acc_s = fit_eval(Bs[tr], y[tr], Bs[te], y[te]) + gains.append((acc_a, acc_b, acc_b - acc_a, acc_s)) + print(f"{s:>5}{acc_a:>10.4f}{acc_b:>10.4f}{acc_b - acc_a:>+9.4f}{acc_s:>10.4f}") + + g = np.array(gains) + se = g[:, 2].std(ddof=1) / np.sqrt(len(g)) + print("-" * 44) + print(f"{'mean':>5}{g[:, 0].mean():>10.4f}{g[:, 1].mean():>10.4f}" + f"{g[:, 2].mean():>+9.4f}{g[:, 3].mean():>10.4f}") + print(f"\nhistory gain {g[:, 2].mean():+.4f} +/- {se:.4f} (paired se), " + f"{(g[:, 2] > 0).sum()}/{len(g)} seeds positive") + print(f"shuffled-history control gains {g[:, 3].mean() - g[:, 0].mean():+.4f} over present, " + f"which is what the real gain must beat to mean anything") + if abs(g[:, 2].mean()) < se: + print("\nVERDICT: inside one se of zero — ambiguous, not a direction.") + elif g[:, 2].mean() > 0: + print("\nVERDICT: a piece's own past predicts its next square beyond the board.") + else: + print("\nVERDICT: the piece's own past adds nothing over the board.") + + +if __name__ == "__main__": + main()