diff --git a/chess_domain.py b/chess_domain.py index 872d274..9694978 100644 --- a/chess_domain.py +++ b/chess_domain.py @@ -37,6 +37,8 @@ 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) +ORACLES = ("none", "history") # `history` hands each entity its own past, the thing memory + # would have to learn to carry. Opt-in, and it only adds columns. SCALE = 7.0 # file/rank -> [0,1], so a relation lands in [-1,1] like the torus does @@ -54,6 +56,7 @@ class Ply: 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 + past: np.ndarray # (N, 2*hist) each entity's previous squares, as displacements def advance_ids(board: chess.Board, move: chess.Move, piece: chess.Piece, @@ -79,9 +82,10 @@ def advance_ids(board: chess.Board, move: chess.Move, piece: chess.Piece, id_at[r_to] = id_at.pop(r_from) -def plies(game: chess.pgn.Game) -> list[Ply]: +def plies(game: chess.pgn.Game, hist: int = 3) -> list[Ply]: board = game.board() id_at = {sq: sq for sq in chess.SQUARES if board.piece_at(sq)} + seen: dict[int, list[int]] = {} out: list[Ply] = [] for move in game.mainline_moves(): piece = board.piece_at(move.from_square) @@ -101,6 +105,14 @@ def plies(game: chess.pgn.Game) -> list[Ply]: mover = squares.index(move.from_square) attrs[mover, 7] = 1.0 + # each entity's own past, relative to where it stands now. Absent history is zero, + # which is also "I am where I was" -- the ambiguity costs the oracle, never the model. + past = np.zeros((len(squares), 2 * hist), dtype=np.float32) + for k, sq in enumerate(squares): + for j, old in enumerate(reversed(seen.get(id_at[sq], [])[-hist:])): + past[k, 2 * j] = (chess.square_file(old) - chess.square_file(sq)) / SCALE + past[k, 2 * j + 1] = (chess.square_rank(old) - chess.square_rank(sq)) / SCALE + # 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)) @@ -108,28 +120,30 @@ def plies(game: chess.pgn.Game) -> list[Ply]: (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)) + out.append(Ply([id_at[sq] for sq in squares], attrs, coords, mover, dests[j], dests, j, + past)) + seen.setdefault(id_at[move.from_square], []).append(move.from_square) advance_ids(board, move, piece, id_at) board.push(move) return out -def load(n_games: int, min_plies: int = 20) -> list[list[Ply]]: +def load(n_games: int, hist: int = 3, 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) + p = plies(g, hist) 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) +def n_params(memory: bool, hidden: int, cppn_hidden: int, attr_dim: int = ATTR_DIM) -> 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()) @@ -145,7 +159,8 @@ def match_width(hidden: int, cppn_hidden: int) -> int: def _stream(org: Organism, game: list[Ply], affect: Affect, acfg: AffectConfig, - opt: torch.optim.Optimizer | None, bptt: int, use_affect: bool): + opt: torch.optim.Optimizer | None, bptt: int, use_affect: bool, + oracle: bool): """One game as one continuous stream. Memory starts empty: new game, new pieces.""" memory: dict[int, torch.Tensor] = {} pending: list[torch.Tensor] = [] @@ -153,7 +168,8 @@ def _stream(org: Organism, game: list[Ply], affect: Affect, acfg: AffectConfig, 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, + attrs = np.concatenate([ply.attrs, ply.past], 1) if oracle else ply.attrs + pred, memory = org(torch.from_numpy(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 @@ -176,10 +192,32 @@ def _stream(org: Organism, game: list[Ply], affect: Affect, acfg: AffectConfig, return affect, losses, hits, chance +def run_constant(games: list[list[Ply]], seed: int) -> dict: + """The floor: predict the mean displacement, ignore everything else. + + Chance levels are measured here, never assumed. If a trained arm sits on this line it + learned nothing about the position and the arms cannot be told apart -- which is a fact + about the task, not about any mechanism in it. + """ + order = np.random.default_rng(seed).permutation(len(games)) + cut = max(1, len(games) // 4) + mean = np.mean([p.target for gi in order[cut:] for p in games[gi]], 0) + mse, hits, chance = [], [], [] + for gi in order[:cut]: + for ply in games[gi]: + mse.append(float(((mean - ply.target) ** 2).mean())) + hits.append(float(int(((ply.dests - mean) ** 2).sum(1).argmin()) == ply.true_dest)) + chance.append(1.0 / len(ply.dests)) + return dict(seed=seed, hidden=0, memory=False, oracle=False, params=2, plies=len(mse), + mse=statistics.fmean(mse), acc=statistics.fmean(hits), + chance=statistics.fmean(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: + lr: float, bptt: int, kappa: float, use_affect: bool, oracle: bool = False) -> dict: torch.manual_seed(seed) - org = Organism(ATTR_DIM, 2, 2, hidden_dim=hidden, cppn_hidden=cppn_hidden, + attr_dim = ATTR_DIM + (games[0][0].past.shape[1] if oracle else 0) + 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() @@ -188,12 +226,12 @@ def run(games: list[list[Ply]], memory: bool, hidden: int, cppn_hidden: int, see 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) + affect, *_ = _stream(org, games[gi], affect, acfg, opt, bptt, use_affect, oracle) mse, hits, chance = [], [], [] for gi in order[:cut]: - affect, l, h, c = _stream(org, games[gi], affect, acfg, None, bptt, use_affect) + affect, l, h, c = _stream(org, games[gi], affect, acfg, None, bptt, use_affect, oracle) mse += l; hits += h; chance += c - return dict(seed=seed, hidden=hidden, memory=memory, + return dict(seed=seed, hidden=hidden, memory=memory, oracle=oracle, params=sum(p.numel() for p in org.parameters()), plies=len(mse), mse=statistics.fmean(mse), acc=statistics.fmean(hits), chance=statistics.fmean(chance)) @@ -202,6 +240,7 @@ def run(games: list[list[Ply]], memory: bool, hidden: int, cppn_hidden: int, see def main() -> None: ap = argparse.ArgumentParser() ap.add_argument("--games", type=int, default=400) + ap.add_argument("--hist", type=int, default=3, help="past squares the oracle hands over") 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) @@ -210,20 +249,28 @@ def main() -> None: 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("--arms", default="rp,grp,rp_wide,rp_oracle") ap.add_argument("--out", default="results/chess.json") a = ap.parse_args() - games = load(a.games) + games = load(a.games, a.hist) wide = match_width(a.hidden, a.cppn_hidden) - arms = {"rp": (False, a.hidden), "grp": (True, a.hidden), "rp_wide": (False, wide)} + # rp_oracle is the ceiling, not a competitor: the memoryless model is HANDED each piece's + # own past, which is exactly what memory would have to learn to carry. If it does not pay, + # a memory null here is about the setup and not about memory. + all_arms = {"rp": (False, a.hidden, False), "grp": (True, a.hidden, False), + "rp_wide": (False, wide, False), "rp_oracle": (False, wide, True), + "constant": (False, 0, False)} + arms = {k: all_arms[k] for k in a.arms.split(",")} 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 name, (mem, h, orc) 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} + r = (run_constant(games, seed) if name == "constant" else + run(games, mem, h, a.cppn_hidden, seed, a.lr, a.bptt, a.kappa, + a.affect == "stream", orc)) | {"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) @@ -237,11 +284,13 @@ def main() -> None: 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])] + for top, base in (("grp", "rp"), ("grp", "rp_wide"), ("rp_oracle", "rp_wide")): + if top not in by or base not in by: + continue + d = [x["acc"] - y["acc"] for x, y in zip(by[top], 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), " + print(f"\n{top} - {base}: {statistics.fmean(d):+.4f} +/- {se:.4f} (paired se), " f"{sum(x > 0 for x in d)}/{len(d)} seeds -- {verdict}")