#!/usr/bin/env python3 """Free-capture probe on the Space (eval-only): measures whether each given checkpoint's greedy policy takes available free material. Ported from D:/projects/pi/training/chess/probe_captures.py so sweep arms and future league checkpoints can be probed where they live (no laptop compute). Usage: --checkpoints a b c (Space paths or hub pulls via --hf-root) --n 100 --seed 42 """ import argparse, json, os, random, sys sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import chess, torch from tinychess.checkpoint import load_model_only from tinychess.batching import encode_batch VALr = {chess.PAWN: 1, chess.KNIGHT: 3, chess.BISHOP: 3, chess.ROOK: 5, chess.QUEEN: 9, chess.KING: 0} def make_probe_positions(n=100, seed=42): rng = random.Random(seed) out = [] tries = 0 while len(out) < n and tries < n * 300: tries += 1 b = chess.Board() k = rng.randint(6, 30) for _ in range(k): ms = list(b.legal_moves) if not ms or b.is_game_over(): break b.push(rng.choice(ms)) if b.is_game_over() or b.is_check(): continue best = None for m in b.legal_moves: if not b.is_capture(m): continue pt = b.piece_type_at(m.to_square) if pt is None: continue if not b.is_attacked_by(not b.turn, m.to_square): v = VALr[pt] if best is None or v > best[1]: best = (m, v) if best: out.append((b.copy(stack=False), best[0], best[1])) return out def any_free(b): return {m for m in b.legal_moves if b.is_capture(m) and not b.is_attacked_by(not b.turn, m.to_square)} @torch.no_grad() def probe(ck, positions, steps=4): model, cfg = load_model_only(ck) model.eval() dev = "cpu" hits = 0 gain = 0.0 for i in range(0, len(positions), 32): chunk = positions[i:i+32] pb = encode_batch([p[0] for p in chunk], [b[-1] if False else None for b in chunk]) out = model(**pb.model_args(), steps=steps, adaptive=False) logits = out["logits"].float() neg = torch.finfo(logits.dtype).min masked = logits.masked_fill(~pb.cand_mask, neg) idx = masked.argmax(-1) for j, p in enumerate(chunk): b = p[0] mv = pb.real_moves[j][int(idx[j])] frees = any_free(b) if mv in frees: hits += 1 gain += VALr[b.piece_type_at(mv.to_square) or chess.KING] n = len(positions) return hits / n, gain / n def main(): ap = argparse.ArgumentParser() ap.add_argument("--checkpoints", nargs="+", default=[]) ap.add_argument("--hf-checkpoints", nargs="+", default=[], help="hub paths under cazyundee/tinychess-ckpt, e.g. ab2_gae_mc/latest.pt") ap.add_argument("--steps", type=int, default=4) ap.add_argument("--n", type=int, default=100) ap.add_argument("--seed", type=int, default=42) ap.add_argument("--out", default="runs/capture_probe.json") a = ap.parse_args() if a.hf_checkpoints: import shutil from huggingface_hub import hf_hub_download os.makedirs("runs/_bench", exist_ok=True) for h in a.hf_checkpoints: src_ = hf_hub_download("cazyundee/tinychess-ckpt", h, token=os.environ.get("HF_TOKEN")) dst = os.path.join("runs/_bench", h.replace("/", "_")) shutil.copy(src_, dst) a.checkpoints.append(dst) if not a.checkpoints: print("no checkpoints given"); raise SystemExit(2) torch.set_num_threads(15) positions = make_probe_positions(a.n, a.seed) print(f"probe set: {len(positions)} positions", flush=True) res = {} for ck in a.checkpoints: r, g = probe(ck, positions, a.steps) res[ck] = {"free_capture_rate": r, "mean_material": g} print(f"{ck}: free-capture {r:.2f} material {g:.2f}", flush=True) json.dump(res, open(a.out, "w"), indent=2) print(f"[saved] {a.out}", flush=True) print("CAPTURE PROBE COMPLETE", flush=True) if __name__ == "__main__": main()