diff --git a/chess_reach.py b/chess_reach.py index 36c40ba..4127e4b 100644 --- a/chess_reach.py +++ b/chess_reach.py @@ -36,6 +36,7 @@ import json import statistics from pathlib import Path +import chess import numpy as np import torch @@ -43,6 +44,28 @@ from ailed import Affect, Organism, detach_memory from chess_domain import ATTR_DIM, flat_diff, load SQ = np.arange(64, dtype=np.uint64) +# how many squares each sliding piece would attack from each square on an EMPTY board. A piece +# attacking fewer than this is blocked, and a blocked ray is the part of chess geometry that +# cannot be memorised as a shape: the knight's L never changes, a rook's does. +_EMPTY_BB, _EMPTY = {}, {} +for _pt in range(1, 7): + for _col in (chess.WHITE, chess.BLACK): + for _sq in chess.SQUARES: + _b = chess.Board(None) + _b.set_piece_at(_sq, chess.Piece(_pt, _col)) + bb = int(_b.attacks(_sq)) + _EMPTY_BB[(_pt, _col, _sq)] = bb + _EMPTY[(_pt, _sq)] = bin(bb).count("1") # colour-free: only sliding uses this +SLIDING = (chess.BISHOP, chess.ROOK, chess.QUEEN) + + +def blocked_flags(ply) -> np.ndarray: + """(N,) True where a sliding piece attacks fewer squares than it would on an empty board.""" + t = ply.attrs[:, :6].argmax(1) + 1 + sq = (np.rint(ply.coords[:, 0] * 7) + 8 * np.rint(ply.coords[:, 1] * 7)).astype(int) + have = np.array([bin(int(r)).count("1") for r in ply.reach]) + full = np.array([_EMPTY.get((int(a), int(b)), -1) for a, b in zip(t, sq)]) + return (full > 0) & (have < full) GRID = 15 * 15 # OFFSET[a, b] is where b sits relative to a, as a cell of the 15x15 displacement grid _f, _r = np.arange(64) % 8, np.arange(64) // 8 @@ -58,12 +81,60 @@ def unpack(ply) -> np.ndarray: return out +def run_shape(games, seed: int) -> dict: + """The control the blocking question needs: knows the piece's type and its movement RULE, + reads nothing from the board. + + Each entity is scored by its EMPTY-BOARD attack set from its own square, ties broken by + the marginal frequency of the offset. For a knight or a king this is the exact answer, so + the arm is also a ceiling: whatever it scores there is what perfect knowledge of the rule + is worth. For a sliding piece it is the un-blocked ray, so beating it means reading + occupancy -- knowing how far the ray is actually cut. + """ + order = np.random.default_rng(seed).permutation(len(games)) + cut = max(1, len(games) // 4) + marg = np.zeros(GRID) + for gi in order[cut:]: + for ply in games[gi]: + marg += unpack(ply).sum(0) + marg = marg / max(marg.max(), 1.0) + + prec, chance, tsum, bsum = [], [], np.zeros((6, 2)), np.zeros((6, 2, 2)) + for gi in order[:cut]: + for ply in games[gi]: + y = torch.from_numpy(unpack(ply)) + t = ply.attrs[:, :6].argmax(1) + 1 + col = ply.attrs[:, 6].astype(bool) + sq = (np.rint(ply.coords[:, 0] * 7) + 8 * np.rint(ply.coords[:, 1] * 7)).astype(int) + score = np.tile(marg, (len(sq), 1)) * 0.5 + for k_, (tt, cc, ss) in enumerate(zip(t, col, sq)): + bb = _EMPTY_BB[(int(tt), bool(cc), int(ss))] + hit_sq = [j for j in range(64) if bb >> j & 1] + score[k_, OFFSET[int(ss)][hit_sq]] += 1.0 + rank = torch.from_numpy((-score).argsort(1).argsort(1)) + k = y.sum(1); keep = k > 0 + if keep.any(): + hit = ((rank < k[:, None]) & (y > 0)).sum(1) / k.clamp(min=1) + prec.append(float(hit[keep].mean())); chance.append(float((k[keep] / GRID).mean())) + kn = keep.numpy(); tt = ply.attrs[:, :6].argmax(1)[kn] + np.add.at(tsum, (tt, 0), hit[keep].numpy()); np.add.at(tsum, (tt, 1), 1.0) + bl = blocked_flags(ply)[kn].astype(int) + np.add.at(bsum, (tt, bl, 0), hit[keep].numpy()) + np.add.at(bsum, (tt, bl, 1), 1.0) + return dict(seed=seed, memory=False, edges=False, hidden=0, params=0, + loss=float("nan"), prec=statistics.fmean(prec), chance=statistics.fmean(chance), + by_type=list(tsum[:, 0] / np.maximum(tsum[:, 1], 1)), + by_block=(bsum[:, :, 0] / np.maximum(bsum[:, :, 1], 1)).tolist(), + n_block=bsum[:, :, 1].tolist()) + + def _stream(org, game, opt, bptt: int, edges: bool, adjacency: bool): memory: dict[int, torch.Tensor] = {} pending, losses, prec, chance = [], [], [], [] # per-type precision is the answer to "does it tell a pawn from a bishop"; the aggregate # can be carried by pawns alone, which are half the pieces on the board by_type = np.zeros((6, 2)) + by_block = np.zeros((6, 2, 2)) zero = Affect().axes with torch.set_grad_enabled(opt is not None): for ply in game: @@ -87,9 +158,13 @@ def _stream(org, game, opt, bptt: int, edges: bool, adjacency: bool): hit = ((rank < k[:, None]) & (y > 0)).sum(1) / k.clamp(min=1) prec.append(float(hit[keep].mean())) chance.append(float((k[keep] / GRID).mean())) # random ranking - tt = ply.attrs[:, :6].argmax(1)[keep.numpy()] + kn = keep.numpy() + tt = ply.attrs[:, :6].argmax(1)[kn] np.add.at(by_type, (tt, 0), hit[keep].numpy()) np.add.at(by_type, (tt, 1), 1.0) + bl = blocked_flags(ply)[kn].astype(int) + np.add.at(by_block, (tt, bl, 0), hit[keep].numpy()) + np.add.at(by_block, (tt, bl, 1), 1.0) if opt is None: continue pending.append(loss) @@ -98,7 +173,7 @@ def _stream(org, game, opt, bptt: int, edges: bool, adjacency: bool): pending = []; memory = detach_memory(memory) if opt is not None and pending: opt.zero_grad(); torch.stack(pending).mean().backward(); opt.step() - return losses, prec, chance, by_type + return losses, prec, chance, by_type, by_block def run(games, memory: bool, hidden: int, cppn_hidden: int, seed: int, lr: float, bptt: int, @@ -111,15 +186,17 @@ def run(games, memory: bool, hidden: int, cppn_hidden: int, seed: int, lr: float cut = max(1, len(games) // 4) for gi in order[cut:]: _stream(org, games[gi], opt, bptt, edges, adjacency) - loss, prec, chance, tsum = [], [], [], np.zeros((6, 2)) + loss, prec, chance, tsum, bsum = [], [], [], np.zeros((6, 2)), np.zeros((6, 2, 2)) for gi in order[:cut]: - l, p, c, t = _stream(org, games[gi], None, bptt, edges, adjacency) - loss += l; prec += p; chance += c; tsum += t + l, p, c, t, b = _stream(org, games[gi], None, bptt, edges, adjacency) + loss += l; prec += p; chance += c; tsum += t; bsum += b return dict(seed=seed, memory=memory, edges=edges, hidden=hidden, params=sum(p.numel() for p in org.parameters()), loss=statistics.fmean(loss), prec=statistics.fmean(prec), chance=statistics.fmean(chance), - by_type=list(tsum[:, 0] / np.maximum(tsum[:, 1], 1))) + by_type=list(tsum[:, 0] / np.maximum(tsum[:, 1], 1)), + by_block=(bsum[:, :, 0] / np.maximum(bsum[:, :, 1], 1)).tolist(), + n_block=bsum[:, :, 1].tolist()) def run_constant(games, seed: int) -> dict: @@ -135,7 +212,7 @@ def run_constant(games, seed: int) -> dict: for ply in games[gi]: marg += unpack(ply).sum(0) rank = torch.from_numpy((-marg).argsort().argsort()) - prec, chance, tsum = [], [], np.zeros((6, 2)) + prec, chance, tsum, bsum = [], [], np.zeros((6, 2)), np.zeros((6, 2, 2)) for gi in order[:cut]: for ply in games[gi]: y = torch.from_numpy(unpack(ply)) @@ -143,11 +220,17 @@ def run_constant(games, seed: int) -> dict: if keep.any(): hit = ((rank[None, :] < k[:, None]) & (y > 0)).sum(1) / k.clamp(min=1) prec.append(float(hit[keep].mean())); chance.append(float((k[keep] / GRID).mean())) - tt = ply.attrs[:, :6].argmax(1)[keep.numpy()] + kn = keep.numpy() + tt = ply.attrs[:, :6].argmax(1)[kn] np.add.at(tsum, (tt, 0), hit[keep].numpy()); np.add.at(tsum, (tt, 1), 1.0) + bl = blocked_flags(ply)[kn].astype(int) + np.add.at(bsum, (tt, bl, 0), hit[keep].numpy()) + np.add.at(bsum, (tt, bl, 1), 1.0) return dict(seed=seed, memory=False, edges=False, hidden=0, params=GRID, loss=float("nan"), prec=statistics.fmean(prec), chance=statistics.fmean(chance), - by_type=list(tsum[:, 0] / np.maximum(tsum[:, 1], 1))) + by_type=list(tsum[:, 0] / np.maximum(tsum[:, 1], 1)), + by_block=(bsum[:, :, 0] / np.maximum(bsum[:, :, 1], 1)).tolist(), + n_block=bsum[:, :, 1].tolist()) def main() -> None: @@ -159,13 +242,13 @@ def main() -> None: ap.add_argument("--lr", type=float, default=1e-3) ap.add_argument("--bptt", type=int, default=20) ap.add_argument("--mask", default="all", choices=("all", "attack")) - ap.add_argument("--arms", default="constant,rp,rp_type,grp_type") + ap.add_argument("--arms", default="constant,shape,rp,rp_type") ap.add_argument("--out", default="results/chess_reach.json") a = ap.parse_args() games = load(a.games) # (memory, edge types) - all_arms = {"constant": None, "rp": (False, False), "rp_type": (False, True), + all_arms = {"constant": None, "shape": "shape", "rp": (False, False), "rp_type": (False, True), "grp": (True, False), "grp_type": (True, True)} arms = {k: all_arms[k] for k in a.arms.split(",")} print(f"{len(games)} games, {sum(len(g) for g in games)} plies, mask={a.mask}\n") @@ -174,6 +257,7 @@ def main() -> None: for name, spec in arms.items(): for seed in (int(s) for s in a.seeds.split(",")): r = (run_constant(games, seed) if spec is None else + run_shape(games, seed) if spec == "shape" else run(games, spec[0], a.hidden, a.cppn_hidden, seed, a.lr, a.bptt, spec[1], a.mask == "attack")) | {"arm": name} print(f"{name:<10} seed={seed} params={r['params']:<6} " @@ -192,6 +276,23 @@ def main() -> None: f"{statistics.fmean(r['prec'] for r in rs):>9.4f}" + "".join(f"{v:>9.4f}" for v in bt)) print(f"\nrandom ranking would score {statistics.fmean(r['chance'] for r in results):.4f}") + + # the blocker split: a knight's L never changes, a sliding piece's ray is cut by occupancy. + # Reported against the floor inside each bucket, because a blocked piece has a smaller + # attack set and therefore a different chance level -- the buckets are not comparable raw. + print(f"\n{'':<10}" + "".join(f"{t:>20}" for t in ("bishop", "rook", "queen"))) + print(f"{'arm':<10}" + "".join(f"{'open':>10}{'blocked':>10}" for _ in range(3))) + print("-" * 70) + for n, rs in by.items(): + row = "" + for i in (2, 3, 4): + for b in (0, 1): + row += f"{statistics.fmean(r['by_block'][i][b] for r in rs):>10.4f}" + print(f"{n:<10}{row}") + counts = by[list(by)[0]][0]["n_block"] + print("share blocked: " + " ".join( + f"{t}={counts[i][1] / max(counts[i][0] + counts[i][1], 1):.2f}" + for i, t in ((2, "bishop"), (3, "rook"), (4, "queen")))) for top, base in (("rp_type", "rp"), ("grp_type", "rp_type"), ("grp", "rp")): if top not in by or base not in by: continue