Files
ailed-experiments-rp/chess_domain.py
T

328 lines
17 KiB
Python

"""Chess under contract A: which piece moves is given, where it goes is predicted.
Spec §2, contract A, on the chess instance. What justified coming here is
`results/chess_history.md`: a piece's own past predicts its next square beyond the board,
+0.034 with a non-linear decoder. That measured headroom is what this file spends.
Two design decisions, both load-bearing.
**The target is the mover's displacement, and the loss is masked to the mover.** Exactly one
piece moves per ply, so the spec's literal default -- every entity's displacement -- is 31/32
zeros and the constant predictor "nobody moves" wins. That leaves a mechanism no job, which is
the shape of four nulls in the predecessor project. The cost of the fix is that the model is
told *which* piece moves. It is not told where it goes, and this is the same conditioning the
probe measured under, so the probe's number is the ceiling on this task and not on some other.
**Affect is held neutral.** psi = (0, 0), kappa = 0, so the only thing separating the arms is
per-entity memory. `--affect stream` runs the real EMA chain instead; it exists so the neutral
default is a choice rather than an absence.
There is no regime switch in chess. A1 -- arousal opens the gate after an unannounced change --
has no analogue here and is not tested by this file.
"""
from __future__ import annotations
import argparse
import json
import statistics
from dataclasses import dataclass
from pathlib import Path
import chess
import chess.pgn
import numpy as np
import torch
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
def flat_diff(coords: torch.Tensor) -> torch.Tensor:
"""r_ij = c_j - c_i. Chess is flat: no wrap, unlike `particles.wrapped_diff`."""
return coords[None, :, :] - coords[:, None, :]
@dataclass
class Ply:
ids: list[int] # stable piece ids, the row order of everything below
attrs: np.ndarray # (N, ATTR_DIM)
coords: np.ndarray # (N, 2) file, rank, scaled
mover: int # row index of the piece that moves
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
mask: np.ndarray # (N, N) the attack/defend graph, symmetric, self-loops on
reach: np.ndarray # (N,) each entity's attack set as a bitboard, for chess_reach.py
def advance_ids(board: chess.Board, move: chess.Move, piece: chess.Piece,
id_at: dict[int, int]) -> None:
"""Follow piece identity across a move, so "this knight" means the same knight later.
Castling moves the rook too; en passant removes a pawn from a square the mover never
touches; promotion keeps the identity and changes only the type.
ponytail: this repeats the bookkeeping inside `chess_history.py` rather than importing it.
That file is a committed measurement and is left untouched; the two must agree, and
`plies()` asserts the result stays in sync with the board either way.
"""
if board.is_en_passant(move):
id_at.pop(move.to_square + (-8 if piece.color == chess.WHITE else 8), None)
id_at.pop(move.to_square, None) # a normal capture
id_at[move.to_square] = id_at.pop(move.from_square, move.from_square)
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)
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)
if piece is None:
break
# the identity map must name exactly the occupied squares, or a memory slot is
# following the wrong piece and every number downstream is meaningless
assert id_at.keys() == board.piece_map().keys(), "identity map drifted from the board"
squares = sorted(id_at)
attrs = np.zeros((len(squares), ATTR_DIM), dtype=np.float32)
coords = np.zeros((len(squares), 2), dtype=np.float32)
for k, sq in enumerate(squares):
p = board.piece_at(sq)
attrs[k, p.piece_type - 1] = 1.0
attrs[k, 6] = float(p.color == chess.WHITE)
coords[k] = (chess.square_file(sq) / SCALE, chess.square_rank(sq) / SCALE)
mover = squares.index(move.from_square)
attrs[mover, 7] = 1.0
# the spec's optional adjacency input (§2), which chess actually has: i sees j when
# either attacks the other's square. With the all-ones default an entity's own
# attributes reach it only through the diagonal term and are divided by deg ~= 30.
sq = np.array(squares, dtype=np.uint64)
bb = np.array([int(board.attacks(int(t))) for t in squares], dtype=np.uint64)
att = ((bb[:, None] >> sq[None, :]) & np.uint64(1)).astype(np.float32)
mask = np.maximum(att, att.T)
np.fill_diagonal(mask, 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))
dests = np.array([[(chess.square_file(t) - chess.square_file(move.from_square)) / SCALE,
(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[s] for s in squares], attrs, coords, mover, dests[j], dests, j,
past, mask, bb.copy()))
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, 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, hist)
if len(p) >= min_plies:
games.append(p)
return games
def n_params(memory: bool, hidden: int, cppn_hidden: int, attr_dim: int = ATTR_DIM,
n_edge: int = 1) -> int:
org = Organism(attr_dim, 2, 2, n_edge_types=n_edge, hidden_dim=hidden,
cppn_hidden=cppn_hidden, memory=memory)
return sum(p.numel() for p in org.parameters())
def match_width(hidden: int, cppn_hidden: int, n_edge: int = 1) -> int:
"""The memoryless width whose parameter count lands nearest the gated model's.
`rp_only` at 1442 against `grp_k0` at 5602 is confounded 3.9x and is not a memory
result (`results/frozen.md` §1d). This is how that confound is removed here.
"""
target = n_params(True, hidden, cppn_hidden, n_edge=n_edge)
return min(range(hidden, 8 * hidden),
key=lambda h: abs(n_params(False, h, cppn_hidden, n_edge=n_edge) - target))
def _stream(org: Organism, game: list[Ply], affect: Affect, acfg: AffectConfig,
opt: torch.optim.Optimizer | None, bptt: int, use_affect: bool,
oracle: bool, adjacency: bool, edges: bool):
"""One game as one continuous stream. Memory starts empty: new game, new pieces."""
memory: dict[int, torch.Tensor] = {}
pending: list[torch.Tensor] = []
losses, hits, chance = [], [], []
with torch.set_grad_enabled(opt is not None):
for ply in game:
coords = torch.from_numpy(ply.coords)
attrs = np.concatenate([ply.attrs, ply.past], 1) if oracle else ply.attrs
# the receiving piece's type, into the CPPN's own channel. Without this the kernel
# is one geometry function shared by all six types -- see results/chess_reach.md,
# where that costs the knight's L entirely.
et = None
if edges:
t = torch.from_numpy(ply.attrs[:, :6]).argmax(1)
et = t[:, None].expand(len(ply.ids), len(ply.ids)).contiguous()
pred, memory = org(torch.from_numpy(attrs), flat_diff(coords), ply.ids,
affect.axes, memory, edge_types=et,
mask=torch.from_numpy(ply.mask) if adjacency else None)
p = pred[ply.mover]
loss = ((p - torch.from_numpy(ply.target)) ** 2).mean() # masked to the mover
if use_affect:
affect = update(affect, loss.item(), acfg)
losses.append(loss.item())
# snap to the nearest legal destination, so the number is comparable to the
# accuracies in results/chess_history.md rather than to a raw MSE
k = int(((torch.from_numpy(ply.dests) - p.detach()) ** 2).sum(1).argmin())
hits.append(float(k == ply.true_dest))
chance.append(1.0 / len(ply.dests))
if opt is None:
continue
pending.append(loss)
if len(pending) == bptt:
opt.zero_grad(); torch.stack(pending).mean().backward(); opt.step()
pending = []; memory = detach_memory(memory)
if opt is not None and pending:
opt.zero_grad(); torch.stack(pending).mean().backward(); opt.step()
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, oracle: bool = False,
adjacency: bool = False, edges: bool = False) -> dict:
torch.manual_seed(seed)
attr_dim = ATTR_DIM + (games[0][0].past.shape[1] if oracle else 0)
org = Organism(attr_dim, 2, 2, n_edge_types=6 if edges else 1, hidden_dim=hidden,
cppn_hidden=cppn_hidden, kappa=kappa, memory=memory)
opt = torch.optim.Adam(org.parameters(), lr=lr)
acfg, affect = AffectConfig(), Affect()
# split by GAME, never inside one: two positions from one game share almost everything
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, oracle, adjacency, edges)
mse, hits, chance = [], [], []
for gi in order[:cut]:
affect, l, h, c = _stream(org, games[gi], affect, acfg, None, bptt, use_affect, oracle, adjacency, edges)
mse += l; hits += h; chance += c
return dict(seed=seed, hidden=hidden, memory=memory, oracle=oracle, mask=adjacency, edges=edges,
params=sum(p.numel() for p in org.parameters()), plies=len(mse),
mse=statistics.fmean(mse), acc=statistics.fmean(hits),
chance=statistics.fmean(chance))
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)
ap.add_argument("--lr", type=float, default=1e-3)
ap.add_argument("--bptt", type=int, default=20)
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("--edges", default="none", choices=("none", "type"),
help="type puts the receiving piece's type into e_ij, the CPPN's channel")
ap.add_argument("--mask", default="all", choices=("all", "attack"),
help="all is the spec default; attack is the domain's own adjacency")
ap.add_argument("--out", default="results/chess.json")
a = ap.parse_args()
games = load(a.games, a.hist)
wide = match_width(a.hidden, a.cppn_hidden, 6 if a.edges == 'type' else 1)
# 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(",")}
deg = statistics.fmean(float(p.mask.sum(1).mean()) for g in games for p in g)
print(f"{len(games)} games, {sum(len(g) for g in games)} plies; "
f"width-matched memoryless arm at hidden={wide}; mask={a.mask}, "
f"mean degree {deg if a.mask == 'attack' else statistics.fmean(len(p.ids) for g in games for p in g):.1f}\n")
results = []
for name, (mem, h, orc) in arms.items():
for seed in (int(s) for s in a.seeds.split(",")):
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, a.mask == "attack",
a.edges == "type")) | {"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)
Path(a.out).parent.mkdir(parents=True, exist_ok=True)
Path(a.out).write_text(json.dumps(results, indent=1))
by = {n: [r for r in results if r["arm"] == n] for n in arms}
print(f"\n{'arm':<8}{'params':>8}{'mse':>10}{'acc':>9}{'chance':>9}")
print("-" * 44)
for n, rs in by.items():
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 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"\n{top} - {base}: {statistics.fmean(d):+.4f} +/- {se:.4f} (paired se), "
f"{sum(x > 0 for x in d)}/{len(d)} seeds -- {verdict}")
if __name__ == "__main__":
main()