diff --git a/chess_history.py b/chess_history.py index 5172841..455066f 100644 --- a/chess_history.py +++ b/chess_history.py @@ -105,22 +105,52 @@ def collect(n_games: int, hist: int, min_moves: int, seed: int): 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) +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() @@ -128,7 +158,9 @@ def main() -> None: 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(",")): @@ -139,14 +171,14 @@ def main() -> None: 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]) + 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_eval(Bs[tr], y[tr], Bs[te], y[te]) + 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}") diff --git a/results/chess_history.md b/results/chess_history.md new file mode 100644 index 0000000..0bd78bb --- /dev/null +++ b/results/chess_history.md @@ -0,0 +1,93 @@ +# Does a piece's own past predict its next move, beyond the current board? + +The 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, before committing to it. + +**Answer: yes, and it survives a stronger estimator.** A piece's own history of squares +predicts its next square beyond what the board says. The gain is +0.034 accuracy with a +non-linear decoder — eleven paired standard errors from zero — against a shuffled-history +control that is *negative*. + +This is the property particles lacked. There, the per-entity state held no more about the +hidden variable than the memoryless representation it was built from (`frozen.md` Part B, +`pooled.md`), because the hidden variable was **global** — one coupling matrix shared by all +sixteen particles, belonging to no entity. Here what there is to remember belongs to the +piece. + +## Setup + +1500 games from the local Lichess PGN, 38 719 moves from pieces with at least two prior moves. +Two predictors of the same target — the destination square of the piece that moves — given the +same conditioning: + +| arm | features | +|---|---| +| present | board occupancy (64), the moving piece's type (6) and colour (1), its current square (64) | +| + history | the same 135, plus the squares that piece occupied on its previous 3 moves (192) | + +Both arms are told which piece moves and from where. The only difference is the piece's own +past, so the gap between them is that past's contribution and nothing else. + +Two things guard the number: + +- **The split is by game, never by position.** Two positions from one game share almost + everything; splitting inside a game leaks the answer across the split. +- **A shuffled-history control.** The same 327 features, with the history block permuted across + rows so its marginal distribution is intact and only its alignment with the target is broken. + This is what the real gain has to beat: it controls for the extra features themselves. + +## Results + +``` +estimator present +history gain shuffled seeds paired se +----------------------------------------------------------------------- +ridge 0.1227 0.1789 +0.0563 0.1190 6/6 0.0011 +mlp 2x128 0.1586 0.1926 +0.0341 0.1489 3/3 0.0031 +``` + +Per-seed, every seed positive in both arms. The shuffled control gains **−0.0036** (ridge) and +**−0.0096** (mlp) over the present-only arm: adding the history features with their timing +destroyed makes the predictor slightly *worse*, so the real gain is about the alignment +between a piece's past and its future, not about feature count. + +## What the estimator comparison says, and the caveat it carries + +The MLP reads more from the board alone than ridge does — 0.1586 against 0.1227 — so part of +what history supplied to the linear model was recoverable from the present by a non-linear one. +The gain shrinks accordingly, from +0.056 to +0.034. + +**That trend is the honest caveat: a stronger estimator shrinks the gain, and this measurement +does not establish where it stops.** What it does establish is that the gain is still there, +and large relative to its error, for a decoder that is not linear. The particles result it is +being compared against went the other way — there the per-entity representation held *less* +than the memoryless one, at every estimator tried. + +Other limits worth stating rather than discovering later: + +- 1500 games and three seeds for the MLP arm. This project has already been bitten by eight + seeds reporting the wrong sign (`pooled.md`); three is enough for a gain of eleven se, and + would not be enough for a smaller one. +- The target — a piece's destination square — is a proxy chosen because it is cheap and needs + no organism. It is not the contract the organism is trained on. +- Move quality is not controlled. These are blitz games across a wide rating range, and a + piece's past may predict its future partly because weaker players shuffle pieces. + +## What it means + +Chess has the property the memory line needs and particles did not: **information that belongs +to an entity, is absent from the present, and persists.** That is the condition the poker +framing named — the evidence lives in the past rather than being redundant with the present — +and it is here at a size a decoder can see. + +This does not say the GRP will work on chess. It says the domain is not the reason it would +fail, which is exactly what could not be said of particles. `credit.md` established that the +state update can hold per-entity properties (the entity's type, at 0.738 against chance 0.333) +and cannot hold a global one; this file establishes that chess's rememberable content is the +per-entity kind. + +Reproduce with: + +```bash +uv run --with chess python chess_history.py --games 1500 --seeds 0,1,2,3,4,5 +uv run --with chess python chess_history.py --games 1500 --seeds 0,1,2 --estimator mlp +```