#!/usr/bin/env python """Multi-turn chess puzzle evaluation for pre2post-chess checkpoints (T0/T2). Two protocols, matched to the authors' released code (repo pavelslab-nyu/pre2post-chess): --protocol sft (for SFT checkpoints; sft/evaluation/multiturn_puzzle_evaluator.py): CoT phase: generate up to 1024 tokens from {prompt}, stopping at or . If never appears -> failure (cot_format). Move loop: per solver move, generate up to 32 tokens stopping at or ; the FIRST LAN move in the emission (excluding the stop token) must be legal and match the ground truth; env reply injected after ; max 5 solver moves. temp 1.0. --protocol verl (for RL checkpoints; rl/verl workers + reward_function_multiturn.py): Phase 1: fixed thinking budget (1024 tokens); a emitted before the budget is exhausted is replaced with and thinking continues; at exhaustion is force-appended. Phase 2: up to max_env_calls=6 turns within answer_budget tokens; stop at , env reply appended after it. Extraction per turn: first LAN move after , else last LAN move in the segment (authors' fallback). temp 1.0, response 2560 total. Success (both) = every extracted solver move matches the ground-truth UCI line (= the paper's pass@1; pass@k = solved within k samples). """ import argparse import json import os import re import sys import time import torch import chess import pandas as pd from huggingface_hub import hf_hub_download, snapshot_download from transformers import AutoModelForCausalLM, AutoTokenizer BENCH_REPO = "pavelslab-nyu/chess_puzzle_benchmark" LAN_RE = re.compile(r"^([KQRBNP])([a-h][1-8])(x?)([a-h][1-8])(=([QRBN]))?$") CASTLE_RE = re.compile(r"^(O-O|O-O-O)([+#])?$") BOS, EOS, T_START, T_END, SEP, CALL_ENV = 0, 1, 81, 82, 83, 84 def load_benchmark(bins, think=True, limit_per_bin=None, seed=0): cfg = "think" if think else "non-think" frames = [] for b in bins: f = hf_hub_download(BENCH_REPO, f"{cfg}/test_{b}.parquet", repo_type="dataset") df = pd.read_parquet(f) if limit_per_bin and limit_per_bin > 0: df = df.sample(n=min(limit_per_bin, len(df)), random_state=seed) frames.append(df) df = pd.concat(frames, ignore_index=True) def _gt(v): if isinstance(v, list): return list(v) return list(eval(v)) df["gt"] = df["reward_model"].apply(lambda r: _gt(r["ground_truth"])) df["env_replies"] = df["extra_info"].apply(lambda r: list(r["env_replies"])) df["fen"] = df["extra_info"].apply(lambda r: r["FEN"]) df["rating"] = df["difficulty"] df["bin"] = df["data_source"] return df def lan_to_uci(lan, board): if lan is None: return None s = lan.rstrip("+#") if s in ("O-O", "O-O-O"): for mv in board.legal_moves: if not board.is_castling(mv): continue to_file = chess.square_file(mv.to_square) if (s == "O-O" and to_file == 6) or (s == "O-O-O" and to_file == 2): return mv.uci() return None m = LAN_RE.match(s) if not m: return None piece, frm, _cap, to, _eq, promo = m.groups() sq = chess.parse_square(frm) p = board.piece_at(sq) if p is None or p.symbol().upper() != piece: return None uci = frm + to + (promo.lower() if promo else "") return uci if uci in {mv.uci() for mv in board.legal_moves} else None def is_lan_word(w): return bool(LAN_RE.match(w.rstrip("+#"))) or bool(CASTLE_RE.match(w)) class Adapter: def __init__(self, tok): self.custom = tok.custom_tokenizer self.vocab = self.custom._tok2id def encode_prompt(self, prompt): return list(self.custom.encode(prompt)) # [bos] + pgn + def lan_ids(self, lan): toks = self.custom._lan_move_to_tokens(lan) return [self.vocab[t] for t in toks] def decode(self, ids): return self.custom.decode(list(ids)) def first_lan_word(text): for w in text.split(): if w in ("", "", "", ""): continue if is_lan_word(w): return w return None def extract_move_verl(adapter, gen_ids): """verl reward extraction: after , else last LAN move in segment.""" text = adapter.decode(gen_ids) idx = text.find("") if idx >= 0: ans = text[idx + 4:].replace("", " ").replace("", " ").replace("", " ") w = first_lan_word(ans) if w: return w, "after_t_end" seg = text.split("")[0] for w in reversed(seg.split()): if w in ("", "", ""): continue if is_lan_word(w): return w, "fallback" return None, "none" def parse_args(): ap = argparse.ArgumentParser() ap.add_argument("--hf-repo", default=None) ap.add_argument("--model-subdir", default=None) ap.add_argument("--protocol", choices=["sft", "verl"], default="sft") ap.add_argument("--bins", nargs="+", default=["B3", "B4"]) ap.add_argument("--k", type=int, default=16) ap.add_argument("--temp", type=float, default=1.0) ap.add_argument("--top-k", type=int, default=None) ap.add_argument("--thinking-budget", type=int, default=1024) # verl protocol ap.add_argument("--answer-budget", type=int, default=1536) # verl protocol ap.add_argument("--cot-cap", type=int, default=1024) # sft protocol ap.add_argument("--move-cap", type=int, default=32) # sft protocol ap.add_argument("--max-moves", type=int, default=5) # sft protocol ap.add_argument("--round", type=int, default=256) ap.add_argument("--max-env-calls", type=int, default=6) ap.add_argument("--limit-per-bin", type=int, default=0) ap.add_argument("--seed", type=int, default=0) ap.add_argument("--debug-gens", type=int, default=0) ap.add_argument("--sweep", default=None) ap.add_argument("--out", default=None) return ap.parse_args() DEFAULTS = dict(hf_repo=None, model_subdir=None, protocol="sft", bins=["B3", "B4"], k=16, temp=1.0, top_k=None, thinking_budget=1024, answer_budget=1536, cot_cap=1024, move_cap=32, max_moves=5, round=256, max_env_calls=6, limit_per_bin=0, seed=0, debug_gens=0, out=None) @torch.no_grad() def gen_round(model, contexts, max_new, stop_ids, temp, top_k, device): """Batched (left-padded) generation round; returns list of new-id lists.""" maxlen = max(len(c) for c in contexts) input_ids = torch.full((len(contexts), maxlen), BOS, dtype=torch.long) attn = torch.zeros((len(contexts), maxlen), dtype=torch.long) for j, c in enumerate(contexts): input_ids[j, maxlen - len(c):] = torch.tensor(c) attn[j, maxlen - len(c):] = 1 input_ids, attn = input_ids.to(device), attn.to(device) out = model.generate( input_ids=input_ids, attention_mask=attn, max_new_tokens=max_new, do_sample=temp > 0, temperature=max(temp, 1e-5), top_k=top_k, use_cache=True, pad_token_id=BOS, eos_token_id=stop_ids if stop_ids else None) return [strip_pads(out[j, maxlen:].tolist()) for j in range(len(contexts))] def strip_pads(ids): """Remove trailing pad (BOS) tokens left by batched generation of finished sequences; also cut everything after the first EOS if present.""" if EOS in ids: ids = ids[: ids.index(EOS) + 1] while ids and ids[-1] == BOS: ids = ids[:-1] return ids # --------------------------------------------------------------------------- # # sft protocol (natural CoT termination; sft/evaluation/multiturn_puzzle_evaluator.py) # --------------------------------------------------------------------------- # @torch.no_grad() def eval_puzzle_sft(model, adapter, row, args, device): gt = row["gt"][: args.max_moves] env_replies = row["env_replies"] base = adapter.encode_prompt(row["prompt"]) # already ends with k = args.k fail = {"ok": 0, "cot_format": 0, "move_format": 0, "illegal_move": 0, "wrong_move": 0} success = [0] * k first_ok = [0] * k gen_tokens = [0] * k boards = [chess.Board(row["fen"]) for _ in range(k)] dbg = 0 # CoT phase: stop at or , cot_cap tokens ctxs = [list(base) for _ in range(k)] finished = [False] * k has_t_end = [False] * k while not all(finished): act = [i for i in range(k) if not finished[i]] gens = gen_round(model, [ctxs[i] for i in act], args.cot_cap, [T_END, EOS], args.temp, args.top_k, device) for j, i in enumerate(act): toks = gens[j] gen_tokens[i] += len(toks) ctxs[i] = ctxs[i] + toks has_t_end[i] = T_END in toks finished[i] = has_t_end[i] or toks and toks[-1] == EOS or len(toks) < args.cot_cap for i in range(k): if not has_t_end[i]: fail["cot_format"] += 1 # continue only for samples with a well-formed CoT alive = [i for i in range(k) if has_t_end[i]] # Move loop turn = 0 while alive and turn < len(gt): next_alive = [] gens = gen_round(model, [ctxs[i] for i in alive], args.move_cap, [CALL_ENV, EOS], args.temp, args.top_k, device) for j, i in enumerate(alive): toks = gens[j] gen_tokens[i] += len(toks) hit_call = CALL_ENV in toks if hit_call: cut = toks.index(CALL_ENV) + 1 emission = toks[:cut] # keep raw emission incl. move_ids = toks[: cut - 1] else: emission = toks move_ids = toks lan = first_lan_word(adapter.decode(move_ids)) if move_ids else None if not hit_call: fail["move_format"] += 1 if args.debug_gens and dbg < args.debug_gens: print(f"[gen] turn={turn} move_format " f"tail={adapter.decode(toks)[-160:]!r}", flush=True) dbg += 1 continue board_j = boards[j] uci = lan_to_uci(lan, board_j) if lan else None if uci is None: fail["illegal_move"] += 1 if args.debug_gens and dbg < args.debug_gens: print(f"[gen] turn={turn} illegal lan={lan!r} " f"tail={adapter.decode(toks)[-160:]!r}", flush=True) dbg += 1 continue if uci != gt[turn]: fail["wrong_move"] += 1 if args.debug_gens and dbg < args.debug_gens: print(f"[gen] turn={turn} wrong lan={lan!r} uci={uci} gt={gt[turn]} " f"tail={adapter.decode(toks)[-160:]!r}", flush=True) dbg += 1 continue if turn == 0: first_ok[i] = 1 board_j.push(chess.Move.from_uci(uci)) ctxs[i] = ctxs[i] + emission + adapter.lan_ids(lan) if turn == len(gt) - 1: success[i] = 1 fail["ok"] += 1 continue o = env_replies[turn] o_uci = lan_to_uci(o, board_j) if o_uci is None: continue board_j.push(chess.Move.from_uci(o_uci)) ctxs[i] = ctxs[i] + adapter.lan_ids(o) next_alive.append(i) alive = next_alive turn += 1 return success, first_ok, gen_tokens, fail # --------------------------------------------------------------------------- # # verl protocol (forced thinking budget + answer phase; for RL checkpoints) # --------------------------------------------------------------------------- # @torch.no_grad() def eval_puzzle_verl(model, adapter, row, args, device): gt, env_replies = row["gt"], row["env_replies"] base = adapter.encode_prompt(row["prompt"]) k = args.k total_budget = args.thinking_budget + args.answer_budget ctx = [list(base) for _ in range(k)] used = [0] * k done_think = [False] * k success = [0] * k gen_tokens = [0] * k src_counts = {"after_t_end": 0, "fallback": 0, "none": 0} boards = [chess.Board(row["fen"]) for _ in range(k)] dbg = 0 while not all(done_think): act = [i for i in range(k) if not done_think[i]] gens = gen_round(model, [ctx[i] for i in act], args.round, [T_END, EOS], args.temp, args.top_k, device) for j, i in enumerate(act): toks = gens[j][: args.thinking_budget - used[i]] if not toks: ctx[i] += [T_END]; used[i] += 1; done_think[i] = True; continue gen_tokens[i] += len(toks) used[i] += len(toks) if toks[-1] == T_END: if used[i] < args.thinking_budget: ctx[i] += toks[:-1] + [SEP] else: ctx[i] += toks done_think[i] = True elif toks[-1] == EOS: ctx[i] += toks + [T_END] done_think[i] = True else: ctx[i] += toks if used[i] >= args.thinking_budget: ctx[i] += [T_END] done_think[i] = True for i in range(k): if ctx[i][-1] != T_END: ctx[i] += [T_END] turn = 0 alive = list(range(k)) n_calls = [0] * k while alive and turn < len(gt) and turn < args.max_env_calls: next_alive = [] remaining = [max(total_budget - used[i], 1) for i in alive] max_round = max(1, min(args.round, max(remaining))) gens = gen_round(model, [ctx[i] for i in alive], max_round, [CALL_ENV, EOS], args.temp, args.top_k, device) for j, i in enumerate(alive): toks = gens[j][: remaining[j]] if not toks: continue gen_tokens[i] += len(toks) used[i] += len(toks) hit_call = CALL_ENV in toks if hit_call: cut = toks.index(CALL_ENV) + 1 ctx[i] += toks[:cut] emission = toks[:cut] n_calls[i] += 1 else: ctx[i] += toks emission = toks lan, src = extract_move_verl(adapter, emission) src_counts[src] += 1 if args.debug_gens and dbg < args.debug_gens: print(f"[gen] turn={turn} src={src} parsed={lan!r} gt={gt[turn]!r} " f"tail={adapter.decode(emission)[-200:]!r}", flush=True) dbg += 1 board_j = boards[j] uci = lan_to_uci(lan, board_j) if lan else None wrong = (uci is None) or (uci != gt[turn]) if hit_call: if wrong: continue board_j.push(chess.Move.from_uci(uci)) ctx[i] += adapter.lan_ids(lan) if turn == len(gt) - 1: success[i] = 1 continue o = env_replies[turn] o_uci = lan_to_uci(o, board_j) if o_uci is None: continue board_j.push(chess.Move.from_uci(o_uci)) ctx[i] += adapter.lan_ids(o) next_alive.append(i) else: if (not wrong) and turn == len(gt) - 1: success[i] = 1 alive = next_alive turn += 1 return success, [0] * k, gen_tokens, src_counts def run_eval(cfg): args = argparse.Namespace(**{**DEFAULTS, **cfg}) torch.manual_seed(args.seed) local = snapshot_download(args.hf_repo, allow_patterns=f"{args.model_subdir}/*") path = os.path.join(local, args.model_subdir) device = "cuda" if torch.cuda.is_available() else "cpu" model = AutoModelForCausalLM.from_pretrained(path, trust_remote_code=True).to(device).eval() tok = AutoTokenizer.from_pretrained(path, trust_remote_code=True) adapter = Adapter(tok) df = load_benchmark(args.bins, think=True, limit_per_bin=args.limit_per_bin, seed=args.seed) print(f"evaluating {args.hf_repo}/{args.model_subdir} [{args.protocol}] on {len(df)} " f"puzzles ({args.bins}), k={args.k}, temp={args.temp}", flush=True) eval_fn = eval_puzzle_sft if args.protocol == "sft" else eval_puzzle_verl results = [] diag_total = {"ok": 0, "cot_format": 0, "move_format": 0, "illegal_move": 0, "wrong_move": 0, "after_t_end": 0, "fallback": 0, "none": 0} t0 = time.time() for _, row in df.iterrows(): success, first_ok, gen_tokens, diag = eval_fn(model, adapter, row, args, device) for key, val in diag.items(): diag_total[key] = diag_total.get(key, 0) + val results.append({ "puzzle_id": row["extra_info"]["PuzzleId"], "bin": row["bin"], "rating": int(row["rating"]), "n_moves": len(row["gt"]), "successes": success, "pass1_mean": sum(success) / len(success), "solved_within_k": float(any(success)), "first_move_acc": sum(first_ok) / len(first_ok), "gen_tokens": sum(gen_tokens), }) if len(results) % 10 == 0: print(f" {len(results)}/{len(df)} puzzles, " f"pass1={sum(r['pass1_mean'] for r in results)/len(results):.3f}, " f"{time.time()-t0:.0f}s", flush=True) by_bin = {} for b in sorted(set(r["bin"] for r in results)): rs = [r for r in results if r["bin"] == b] by_bin[b] = {"n": len(rs), "pass1_mean": sum(r["pass1_mean"] for r in rs) / len(rs), "passk_any": sum(r["solved_within_k"] for r in rs) / len(rs), "first_move_acc": sum(r["first_move_acc"] for r in rs) / len(rs), "mean_gen_tokens": sum(r["gen_tokens"] for r in rs) / len(rs)} n = len(results) summary = { "config": vars(args), "summary": { "n_puzzles": n, "by_bin": by_bin, "pass1_mean_overall": sum(r["pass1_mean"] for r in results) / n, "passk_any_overall": sum(r["solved_within_k"] for r in results) / n, "first_move_acc_overall": sum(r["first_move_acc"] for r in results) / n, "diag": diag_total, "wall_seconds": time.time() - t0, }, } os.makedirs(os.path.dirname(args.out) or ".", exist_ok=True) with open(args.out, "w") as f: json.dump(summary, f) print(json.dumps(summary["summary"], indent=2), flush=True) return summary["summary"] CALIB_SWEEP = [ {"hf_repo": "pavelslab-nyu/Chess-SFT-Models", "model_subdir": "model_20m_5.3B", "protocol": "sft", "bins": ["B1", "B2"], "k": 8, "limit_per_bin": 25, "debug_gens": 4, "out": "/work/results/calib_sft20_nat.json"}, {"hf_repo": "pavelslab-nyu/Chess-SFT-Models", "model_subdir": "model_680m_16B", "protocol": "sft", "bins": ["B1", "B2"], "k": 8, "limit_per_bin": 25, "out": "/work/results/calib_sft680_nat.json"}, {"hf_repo": "Pre2Post-Chess-RL/Chess-RL-Models", "model_subdir": "model_20m_5.3B/global_step_5000", "protocol": "verl", "bins": ["B1", "B2"], "k": 8, "limit_per_bin": 25, "thinking_budget": 1024, "answer_budget": 1536, "debug_gens": 3, "out": "results/calib_rl5000_verl.json"}, ] T2_RL_RUNS = ["model_20m_0.53B", "model_20m_1.6B", "model_20m_2.6B", "model_20m_5.3B", "model_20m_11B", "model_20m_16B", "model_20m_21B", "model_20m_32B", "model_20m_40B", "model_20m_53B"] T2_STEP_TARGETS = [300, 750, 1500, 3000, 5000] RESULTS_REPO = "ML-Intern-lab/pre2post-chess-replication" def build_t2_sweep(): """RL sweep over the 20M family: verl protocol, B3+B4, steps nearest targets.""" from huggingface_hub import HfApi files = HfApi().list_repo_files("Pre2Post-Chess-RL/Chess-RL-Models", repo_type="model") avail = {} for f in files: parts = f.split("/") if len(parts) == 3 and parts[1].startswith("global_step_") and f.endswith("config.json"): run, step = parts[0], int(parts[1].replace("global_step_", "")) avail.setdefault(run, []).append(step) specs = [] for run in T2_RL_RUNS: steps = sorted(avail.get(run, [])) if not steps: print(f"[sweep] no checkpoints for {run}, skipping") continue chosen = sorted(set(min(steps, key=lambda s: abs(s - t)) for t in T2_STEP_TARGETS)) for step in chosen: tag = f"{run.replace('model_', '').replace('.', 'p')}_s{step}" specs.append({ "hf_repo": "Pre2Post-Chess-RL/Chess-RL-Models", "model_subdir": f"{run}/global_step_{step}", "protocol": "verl", "bins": ["B3", "B4"], "k": 8, "limit_per_bin": 25, "thinking_budget": 1024, "answer_budget": 1536, "out": f"/work/results/t2_rl_{tag}.json", "tag": f"rl_{tag}", }) return specs def upload_result(out_path, tag): try: from huggingface_hub import HfApi HfApi().upload_file(path_or_fileobj=out_path, path_in_repo=f"results/t2/{tag}.json", repo_id=RESULTS_REPO, repo_type="dataset") print(f"[upload] {tag} -> {RESULTS_REPO}", flush=True) except Exception as e: print(f"[upload] FAILED {tag}: {e}", flush=True) def run_t2_sweep(): specs = build_t2_sweep() print(f"T2 sweep: {len(specs)} evals", flush=True) for i, sp in enumerate(specs): if result_exists(sp["tag"], "t2"): print(f"[skip] {sp['tag']} already uploaded", flush=True) continue print(f"\n===== [{i+1}/{len(specs)}] {sp['model_subdir']} =====", flush=True) try: s = run_eval(sp) upload_result(sp["out"], sp["tag"]) print(f"RESULT {sp['tag']} pass1={s['pass1_mean_overall']:.4f} " f"passk={s['passk_any_overall']:.4f} wall={s['wall_seconds']:.0f}s", flush=True) except Exception as e: print(f"[sweep] eval {sp['tag']} FAILED: {e}", flush=True) T2B_RUNS = ["model_20m_0.53B", "model_20m_1.6B", "model_20m_5.3B", "model_20m_11B", "model_20m_32B", "model_20m_53B"] T2B_STEPS = [300, 1500, 5000] def build_t2b_sweep(): """Focused high-power sweep on B1+B2 (above the resolution floor at our reduced scale): 6 pretraining levels x 3 RL steps, 400 draws per point. Tests R_ref vs pretraining loss and RL slope vs log T (claims 4a/4b).""" from huggingface_hub import HfApi files = HfApi().list_repo_files("Pre2Post-Chess-RL/Chess-RL-Models", repo_type="model") avail = {} for f in files: parts = f.split("/") if len(parts) == 3 and parts[1].startswith("global_step_") and f.endswith("config.json"): avail.setdefault(parts[0], []).append(int(parts[1].replace("global_step_", ""))) specs = [] for run in T2B_RUNS: steps = sorted(avail.get(run, [])) if not steps: continue for target in T2B_STEPS: step = min(steps, key=lambda s: abs(s - target)) tag = f"{run.replace('model_', '').replace('.', 'p')}_s{step}" specs.append({ "hf_repo": "Pre2Post-Chess-RL/Chess-RL-Models", "model_subdir": f"{run}/global_step_{step}", "protocol": "verl", "bins": ["B1", "B2"], "k": 8, "limit_per_bin": 40, "thinking_budget": 1024, "answer_budget": 1536, "out": f"/work/results/t2b_{tag}.json", "tag": f"t2b_{tag}", }) # dedupe (same step chosen for two targets) seen, out = set(), [] for s in specs: if s["tag"] in seen: continue seen.add(s["tag"]) out.append(s) return out def result_exists(tag, subdir): try: from huggingface_hub import HfApi path = f"results/{subdir}/{tag}.json" return path in set(HfApi().list_repo_files(RESULTS_REPO, repo_type="dataset")) except Exception: return False def run_t2b_sweep(): specs = build_t2b_sweep() print(f"T2b sweep: {len(specs)} evals", flush=True) for i, sp in enumerate(specs): if result_exists(sp["tag"], "t2b"): print(f"[skip] {sp['tag']} already uploaded", flush=True) continue print(f"\n===== [{i+1}/{len(specs)}] {sp['model_subdir']} =====", flush=True) try: s = run_eval(sp) upload_result(sp["out"], sp["tag"]) print(f"RESULT {sp['tag']} pass1={s['pass1_mean_overall']:.4f} " f"passk={s['passk_any_overall']:.4f} wall={s['wall_seconds']:.0f}s", flush=True) except Exception as e: print(f"[sweep] eval {sp['tag']} FAILED: {e}", flush=True) def main(): args = parse_args() if args.sweep is None and len(sys.argv) == 1: run_t2_sweep() # completes any missing B3+B4 evals (skips uploaded) run_t2b_sweep() # then the focused B1+B2 high-power sweep return if args.sweep: outs = [] for sp in json.loads(args.sweep): print(f"\n===== run {sp.get('model_subdir')} [{sp.get('protocol')}] =====", flush=True) outs.append({"spec": sp, "summary": run_eval(sp)}) print("\nSWEEP_SUMMARY\n" + json.dumps(outs, indent=2), flush=True) else: run_eval(vars(args)) if __name__ == "__main__": main()