Files
ailed-experiments-rp/chess_history.py
T
chrnx 38a090e1f7 exp: chess has the per-entity history particles lacked
A piece's own past predicts its next square beyond the board: +0.056 with ridge on 6/6
seeds, +0.034 with a 2x128 MLP on 3/3, eleven paired standard errors from zero. The
shuffled-history control is negative in both arms, so the gain is about the alignment
between a piece's past and its future rather than about feature count. Split by game,
never by position.

The MLP reads more from the board alone than ridge does, so part of what history gave the
linear model was recoverable from the present; the gain shrinks from +0.056 to +0.034 and
this measurement does not establish where that stops. Stated as the caveat it is.

This is the property particles lacked. There the hidden variable was global -- one coupling
matrix belonging to no entity -- and the per-entity state held less about it than the
memoryless representation it was built from. Here what there is to remember belongs to the
piece.
2026-09-02 17:20:45 -05:00

204 lines
8.6 KiB
Python

"""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_ridge(Xtr, ytr, Xte, yte, l2: float = 1.0):
"""Ridge onto one-hot targets, argmax at test."""
Y = np.zeros((len(ytr), 64), 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 fit_mlp(Xtr, ytr, Xte, yte, hidden: int = 128, epochs: int = 12, bs: int = 512):
"""A 2xN ReLU net on the same features.
Task 11 is why this arm exists: on the particles domain a linear decoder read 0.23
where an MLP read 0.83 on identical features, so a linear null there would have been
wrong by 0.6 in accuracy. A linear-only null here would inherit that objection.
"""
import torch
g = torch.Generator().manual_seed(0)
Xtr_t = torch.from_numpy(Xtr); ytr_t = torch.from_numpy(ytr).long()
net = torch.nn.Sequential(
torch.nn.Linear(Xtr.shape[1], hidden), torch.nn.ReLU(),
torch.nn.Linear(hidden, hidden), torch.nn.ReLU(),
torch.nn.Linear(hidden, 64))
opt = torch.optim.Adam(net.parameters(), lr=1e-3)
n = len(ytr_t)
for _ in range(epochs):
perm = torch.randperm(n, generator=g)
for i in range(0, n, bs):
idx = perm[i:i + bs]
opt.zero_grad()
torch.nn.functional.cross_entropy(net(Xtr_t[idx]), ytr_t[idx]).backward()
opt.step()
with torch.no_grad():
pred = net(torch.from_numpy(Xte)).argmax(1).numpy()
return float((pred == yte).mean())
FITS = {"ridge": fit_ridge, "mlp": fit_mlp}
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("--estimator", default="ridge", choices=sorted(FITS))
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")
fit = FITS[a.estimator]
gains = []
print(f"estimator: {a.estimator}\n")
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(A[tr], y[tr], A[te], y[te])
acc_b = fit(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(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()