File size: 25,791 Bytes
78f0b47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
#!/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}<T>, stopping at </T> or
   <eos>. If </T> never appears -> failure (cot_format).
   Move loop: per solver move, generate up to 32 tokens stopping at <call_env>
   or <eos>; the FIRST LAN move in the emission (excluding the stop token) must
   be legal and match the ground truth; env reply injected after <call_env>;
   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 </T> emitted before the
   budget is exhausted is replaced with <sep> and thinking continues; at
   exhaustion </T> is force-appended. Phase 2: up to max_env_calls=6 turns
   within answer_budget tokens; stop at <call_env>, env reply appended after
   it. Extraction per turn: first LAN move after </T>, 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 + <T>

    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 ("<T>", "</T>", "<call_env>", "<sep>"):
            continue
        if is_lan_word(w):
            return w
    return None


def extract_move_verl(adapter, gen_ids):
    """verl reward extraction: after </T>, else last LAN move in segment."""
    text = adapter.decode(gen_ids)
    idx = text.find("</T>")
    if idx >= 0:
        ans = text[idx + 4:].replace("<T>", " ").replace("</T>", " ").replace("<call_env>", " ")
        w = first_lan_word(ans)
        if w:
            return w, "after_t_end"
    seg = text.split("<call_env>")[0]
    for w in reversed(seg.split()):
        if w in ("<T>", "</T>", "<sep>"):
            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 <T>
    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 </T> or <eos>, 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. <call_env>
                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()