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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
"""T4 mechanism analysis: move-level policy evolution SFT -> RL (App. H of
|
| 3 |
+
arXiv:2607.16097), replicated at reduced scale.
|
| 4 |
+
|
| 5 |
+
For each puzzle and each checkpoint (SFT and RL steps), estimate the
|
| 6 |
+
root-conditioned marginal move policy pi(a|s) by Monte Carlo over traces:
|
| 7 |
+
1. Sample K thinking traces with the verl protocol (fixed 1024-token
|
| 8 |
+
thinking budget, premature </T> replaced by <sep>, forced </T> at the
|
| 9 |
+
budget) -- the same rollout pipeline the authors used for both SFT and
|
| 10 |
+
RL checkpoints.
|
| 11 |
+
2. For each trace r_k, score every legal move a by the product of token
|
| 12 |
+
probabilities of a's LAN serialization given (s, r_k) (teacher-forced,
|
| 13 |
+
KV-cached forward passes).
|
| 14 |
+
3. pi_hat(a|s) = (1/K) * sum_k pi(a|s, r_k), normalized over legal moves.
|
| 15 |
+
|
| 16 |
+
Then categorize the SFT -> RL policy change per puzzle (Table 13, top_k=3,
|
| 17 |
+
eps_tail=0.05): ground-truth amplification, tail discovery, top-k correction,
|
| 18 |
+
ground-truth regression, wrong-mode amplification, other. Report fractions by
|
| 19 |
+
difficulty bin (easy B1 vs hard B4/B5).
|
| 20 |
+
|
| 21 |
+
No-arg invocation = default analysis (SFT 20m_5.3B vs RL steps 100/300/500,
|
| 22 |
+
puzzles from B1 + B4 + B5).
|
| 23 |
+
"""
|
| 24 |
+
import argparse
|
| 25 |
+
import json
|
| 26 |
+
import os
|
| 27 |
+
import re
|
| 28 |
+
import sys
|
| 29 |
+
|
| 30 |
+
import torch
|
| 31 |
+
import chess
|
| 32 |
+
import numpy as np
|
| 33 |
+
from huggingface_hub import hf_hub_download, snapshot_download
|
| 34 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 35 |
+
|
| 36 |
+
BENCH_REPO = "pavelslab-nyu/chess_puzzle_benchmark"
|
| 37 |
+
RESULTS_REPO = "ML-Intern-lab/pre2post-chess-replication"
|
| 38 |
+
BOS, EOS, T_END, SEP, CALL_ENV = 0, 1, 82, 83, 84
|
| 39 |
+
|
| 40 |
+
LAN_RE = re.compile(r"^([KQRBNP])([a-h][1-8])(x?)([a-h][1-8])(=([QRBN]))?$")
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def load_benchmark(bins, limit_per_bin, seed=0):
|
| 44 |
+
import pandas as pd
|
| 45 |
+
frames = []
|
| 46 |
+
for b in bins:
|
| 47 |
+
f = hf_hub_download(BENCH_REPO, f"think/test_{b}.parquet", repo_type="dataset")
|
| 48 |
+
df = pd.read_parquet(f)
|
| 49 |
+
if limit_per_bin:
|
| 50 |
+
df = df.sample(n=min(limit_per_bin, len(df)), random_state=seed)
|
| 51 |
+
frames.append(df)
|
| 52 |
+
df = pd.concat(frames, ignore_index=True)
|
| 53 |
+
|
| 54 |
+
def _gt(v):
|
| 55 |
+
return list(v) if isinstance(v, list) else list(eval(v))
|
| 56 |
+
df["gt"] = df["reward_model"].apply(lambda r: _gt(r["ground_truth"]))
|
| 57 |
+
df["fen"] = df["extra_info"].apply(lambda r: r["FEN"])
|
| 58 |
+
df["bin"] = df["data_source"]
|
| 59 |
+
return df
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
class Adapter:
|
| 63 |
+
def __init__(self, tok):
|
| 64 |
+
self.custom = tok.custom_tokenizer
|
| 65 |
+
self.vocab = self.custom._tok2id
|
| 66 |
+
|
| 67 |
+
def encode_prompt(self, prompt):
|
| 68 |
+
return list(self.custom.encode(prompt))
|
| 69 |
+
|
| 70 |
+
def lan_ids(self, lan):
|
| 71 |
+
return [self.vocab[t] for t in self.custom._lan_move_to_tokens(lan)]
|
| 72 |
+
|
| 73 |
+
def decode(self, ids):
|
| 74 |
+
return self.custom.decode(list(ids))
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def legal_lan_moves(board):
|
| 78 |
+
"""LAN serializations of all legal moves (piece letter as on the board)."""
|
| 79 |
+
out = {}
|
| 80 |
+
for mv in board.legal_moves:
|
| 81 |
+
p = board.piece_at(mv.from_square)
|
| 82 |
+
piece = p.symbol().upper() if p else "P"
|
| 83 |
+
frm = chess.square_name(mv.from_square)
|
| 84 |
+
to = chess.square_name(mv.to_square)
|
| 85 |
+
cap = "x" if board.is_capture(mv) else ""
|
| 86 |
+
lan = f"{piece}{frm}{cap}{to}"
|
| 87 |
+
if mv.promotion:
|
| 88 |
+
lan += "=" + chess.piece_symbol(mv.promotion).upper()
|
| 89 |
+
out[mv.uci()] = lan
|
| 90 |
+
return out
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def strip_pads(ids):
|
| 94 |
+
if EOS in ids:
|
| 95 |
+
ids = ids[: ids.index(EOS) + 1]
|
| 96 |
+
while ids and ids[-1] == BOS:
|
| 97 |
+
ids = ids[:-1]
|
| 98 |
+
return ids
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
@torch.no_grad()
|
| 102 |
+
def gen_round(model, contexts, max_new, stop_ids, temp, device):
|
| 103 |
+
maxlen = max(len(c) for c in contexts)
|
| 104 |
+
input_ids = torch.full((len(contexts), maxlen), BOS, dtype=torch.long)
|
| 105 |
+
attn = torch.zeros((len(contexts), maxlen), dtype=torch.long)
|
| 106 |
+
for j, c in enumerate(contexts):
|
| 107 |
+
input_ids[j, maxlen - len(c):] = torch.tensor(c)
|
| 108 |
+
attn[j, maxlen - len(c):] = 1
|
| 109 |
+
input_ids, attn = input_ids.to(device), attn.to(device)
|
| 110 |
+
out = model.generate(input_ids=input_ids, attention_mask=attn,
|
| 111 |
+
max_new_tokens=max_new, do_sample=temp > 0,
|
| 112 |
+
temperature=max(temp, 1e-5), use_cache=True,
|
| 113 |
+
pad_token_id=BOS,
|
| 114 |
+
eos_token_id=stop_ids if stop_ids else None)
|
| 115 |
+
return [strip_pads(out[j, maxlen:].tolist()) for j in range(len(contexts))]
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
@torch.no_grad()
|
| 119 |
+
def sample_traces(model, adapter, prompt, K, thinking_budget, round_sz, temp, device):
|
| 120 |
+
"""K thinking traces via the verl forced-budget procedure."""
|
| 121 |
+
base = adapter.encode_prompt(prompt)
|
| 122 |
+
ctx = [list(base) for _ in range(K)]
|
| 123 |
+
used = [0] * K
|
| 124 |
+
done = [False] * K
|
| 125 |
+
while not all(done):
|
| 126 |
+
act = [i for i in range(K) if not done[i]]
|
| 127 |
+
gens = gen_round(model, [ctx[i] for i in act], round_sz, [T_END, EOS], temp, device)
|
| 128 |
+
for j, i in enumerate(act):
|
| 129 |
+
toks = gens[j][: thinking_budget - used[i]]
|
| 130 |
+
if not toks:
|
| 131 |
+
ctx[i] += [T_END]; used[i] += 1; done[i] = True; continue
|
| 132 |
+
used[i] += len(toks)
|
| 133 |
+
if toks[-1] == T_END:
|
| 134 |
+
if used[i] < thinking_budget:
|
| 135 |
+
ctx[i] += toks[:-1] + [SEP]
|
| 136 |
+
else:
|
| 137 |
+
ctx[i] += toks
|
| 138 |
+
done[i] = True
|
| 139 |
+
elif toks[-1] == EOS:
|
| 140 |
+
ctx[i] += toks + [T_END]
|
| 141 |
+
done[i] = True
|
| 142 |
+
else:
|
| 143 |
+
ctx[i] += toks
|
| 144 |
+
if used[i] >= thinking_budget:
|
| 145 |
+
ctx[i] += [T_END]
|
| 146 |
+
done[i] = True
|
| 147 |
+
for i in range(K):
|
| 148 |
+
if ctx[i][-1] != T_END:
|
| 149 |
+
ctx[i] += [T_END]
|
| 150 |
+
return [ctx[i][len(base):] for i in range(K)] # trace token lists
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
@torch.no_grad()
|
| 154 |
+
def move_probs_given_trace(model, adapter, base_ids, trace_ids, board, device):
|
| 155 |
+
"""pi(a|s,r) for all legal moves: one teacher-forced forward per move
|
| 156 |
+
(prefix + move tokens, batch=1), gathering the move tokens' logprobs."""
|
| 157 |
+
vocab = adapter.vocab
|
| 158 |
+
prefix = list(base_ids) + list(trace_ids)
|
| 159 |
+
prefix_t = torch.tensor([prefix], dtype=torch.long, device=device)
|
| 160 |
+
moves = legal_lan_moves(board)
|
| 161 |
+
logps = {}
|
| 162 |
+
for uci, lan in moves.items():
|
| 163 |
+
toks = [vocab[t] for t in adapter.custom._lan_move_to_tokens(lan)]
|
| 164 |
+
ids = torch.tensor([prefix + toks], dtype=torch.long, device=device)
|
| 165 |
+
logits = model(input_ids=ids).logits[0] # (L, V)
|
| 166 |
+
# logprob of token t at position i comes from logits at position i-1
|
| 167 |
+
lp = 0.0
|
| 168 |
+
for j, t in enumerate(toks):
|
| 169 |
+
pos = len(prefix) - 1 + j
|
| 170 |
+
lp += torch.log_softmax(logits[pos].float(), dim=-1)[t].item()
|
| 171 |
+
logps[uci] = lp
|
| 172 |
+
ucis = list(logps)
|
| 173 |
+
arr = np.array([logps[u] for u in ucis])
|
| 174 |
+
arr = arr - arr.max()
|
| 175 |
+
p = np.exp(arr)
|
| 176 |
+
p = p / p.sum()
|
| 177 |
+
return {u: float(pi) for u, pi in zip(ucis, p)}
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
def categorize(p_sft, p_rl, gt_uci, top_k=3, eps_tail=0.05):
|
| 181 |
+
def topk(p):
|
| 182 |
+
return set(u for u, _ in sorted(p.items(), key=lambda kv: -kv[1])[:top_k])
|
| 183 |
+
t0, t1 = topk(p_sft), topk(p_rl)
|
| 184 |
+
gt = gt_uci
|
| 185 |
+
d = p_rl.get(gt, 0.0) - p_sft.get(gt, 0.0)
|
| 186 |
+
wrong0 = max(p_sft, key=p_sft.get)
|
| 187 |
+
if gt in t0 and gt in t1 and d > 0:
|
| 188 |
+
return "gt_amplification"
|
| 189 |
+
if gt not in t0 and gt in t1 and p_sft.get(gt, 0.0) < eps_tail:
|
| 190 |
+
return "tail_discovery"
|
| 191 |
+
if gt not in t0 and gt in t1:
|
| 192 |
+
return "topk_correction"
|
| 193 |
+
if gt in t0 and gt not in t1:
|
| 194 |
+
return "gt_regression"
|
| 195 |
+
if gt not in t0 and gt not in t1 and wrong0 in t1 and d != 0 and \
|
| 196 |
+
p_rl.get(wrong0, 0.0) > p_sft.get(wrong0, 0.0):
|
| 197 |
+
return "wrong_mode_amplification"
|
| 198 |
+
return "other"
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
CHECKPOINTS = [
|
| 202 |
+
("sft", "pavelslab-nyu/Chess-SFT-Models", "model_20m_5.3B"),
|
| 203 |
+
("rl_100", "Pre2Post-Chess-RL/Chess-RL-Models", "model_20m_5.3B/global_step_100"),
|
| 204 |
+
("rl_300", "Pre2Post-Chess-RL/Chess-RL-Models", "model_20m_5.3B/global_step_300"),
|
| 205 |
+
("rl_500", "Pre2Post-Chess-RL/Chess-RL-Models", "model_20m_5.3B/global_step_500"),
|
| 206 |
+
]
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
def main():
|
| 210 |
+
ap = argparse.ArgumentParser()
|
| 211 |
+
ap.add_argument("--bins", nargs="+", default=["B1", "B4", "B5"])
|
| 212 |
+
ap.add_argument("--limit-per-bin", type=int, default=12)
|
| 213 |
+
ap.add_argument("--k-traces", type=int, default=12)
|
| 214 |
+
ap.add_argument("--thinking-budget", type=int, default=1024)
|
| 215 |
+
ap.add_argument("--round", type=int, default=256)
|
| 216 |
+
ap.add_argument("--temp", type=float, default=1.0)
|
| 217 |
+
ap.add_argument("--seed", type=int, default=0)
|
| 218 |
+
ap.add_argument("--out", default="/work/results/t4_mechanism.json")
|
| 219 |
+
args = ap.parse_args()
|
| 220 |
+
torch.manual_seed(args.seed)
|
| 221 |
+
|
| 222 |
+
df = load_benchmark(args.bins, args.limit_per_bin, args.seed)
|
| 223 |
+
print(f"T4: {len(df)} puzzles x {len(CHECKPOINTS)} checkpoints, "
|
| 224 |
+
f"K={args.k_traces} traces", flush=True)
|
| 225 |
+
|
| 226 |
+
policies = {} # (ckpt, puzzle) -> {uci: prob}
|
| 227 |
+
for name, repo, sub in CHECKPOINTS:
|
| 228 |
+
local = snapshot_download(repo, allow_patterns=f"{sub}/*")
|
| 229 |
+
path = os.path.join(local, sub)
|
| 230 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 231 |
+
model = AutoModelForCausalLM.from_pretrained(path, trust_remote_code=True).to(device).eval()
|
| 232 |
+
tok = AutoTokenizer.from_pretrained(path, trust_remote_code=True)
|
| 233 |
+
adapter = Adapter(tok)
|
| 234 |
+
for _, row in df.iterrows():
|
| 235 |
+
base = adapter.encode_prompt(row["prompt"])
|
| 236 |
+
traces = sample_traces(model, adapter, row["prompt"], args.k_traces,
|
| 237 |
+
args.thinking_budget, args.round, args.temp, device)
|
| 238 |
+
board = chess.Board(row["fen"])
|
| 239 |
+
acc = None
|
| 240 |
+
for tr in traces:
|
| 241 |
+
p = move_probs_given_trace(model, adapter, base, tr, board, device)
|
| 242 |
+
if acc is None:
|
| 243 |
+
acc = {u: v for u, v in p.items()}
|
| 244 |
+
else:
|
| 245 |
+
for u in acc:
|
| 246 |
+
acc[u] += p.get(u, 0.0)
|
| 247 |
+
acc = {u: v / len(traces) for u, v in acc.items()}
|
| 248 |
+
policies[(name, row["extra_info"]["PuzzleId"])] = acc
|
| 249 |
+
print(f"[{name}] {row['extra_info']['PuzzleId']} ({row['bin']}) done", flush=True)
|
| 250 |
+
del model
|
| 251 |
+
torch.cuda.empty_cache()
|
| 252 |
+
|
| 253 |
+
# categorize SFT -> RL per puzzle
|
| 254 |
+
cats = {}
|
| 255 |
+
for _, row in df.iterrows():
|
| 256 |
+
pid = row["extra_info"]["PuzzleId"]
|
| 257 |
+
gt = row["gt"][0]
|
| 258 |
+
p_sft = policies[("sft", pid)]
|
| 259 |
+
for name, _, _ in CHECKPOINTS[1:]:
|
| 260 |
+
cats.setdefault(name, {}).setdefault(row["bin"], {}).setdefault("counts", {})
|
| 261 |
+
c = categorize(p_sft, policies[(name, pid)], gt)
|
| 262 |
+
counts = cats[name][row["bin"]]["counts"]
|
| 263 |
+
counts[c] = counts.get(c, 0) + 1
|
| 264 |
+
|
| 265 |
+
out = {"config": vars(args), "policies": {f"{k[0]}|{k[1]}": v for k, v in policies.items()},
|
| 266 |
+
"categories": cats}
|
| 267 |
+
os.makedirs(os.path.dirname(args.out) or ".", exist_ok=True)
|
| 268 |
+
with open(args.out, "w") as f:
|
| 269 |
+
json.dump(out, f)
|
| 270 |
+
print(json.dumps(cats, indent=2), flush=True)
|
| 271 |
+
try:
|
| 272 |
+
from huggingface_hub import HfApi
|
| 273 |
+
HfApi().upload_file(path_or_fileobj=args.out, path_in_repo="results/t4_mechanism.json",
|
| 274 |
+
repo_id=RESULTS_REPO, repo_type="dataset")
|
| 275 |
+
print("[upload] t4_mechanism.json", flush=True)
|
| 276 |
+
except Exception as e:
|
| 277 |
+
print(f"[upload] FAILED: {e}", flush=True)
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
if __name__ == "__main__":
|
| 281 |
+
main()
|