File size: 11,250 Bytes
45c434b | 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 | #!/usr/bin/env python
"""T4 mechanism analysis: move-level policy evolution SFT -> RL (App. H of
arXiv:2607.16097), replicated at reduced scale.
For each puzzle and each checkpoint (SFT and RL steps), estimate the
root-conditioned marginal move policy pi(a|s) by Monte Carlo over traces:
1. Sample K thinking traces with the verl protocol (fixed 1024-token
thinking budget, premature </T> replaced by <sep>, forced </T> at the
budget) -- the same rollout pipeline the authors used for both SFT and
RL checkpoints.
2. For each trace r_k, score every legal move a by the product of token
probabilities of a's LAN serialization given (s, r_k) (teacher-forced,
KV-cached forward passes).
3. pi_hat(a|s) = (1/K) * sum_k pi(a|s, r_k), normalized over legal moves.
Then categorize the SFT -> RL policy change per puzzle (Table 13, top_k=3,
eps_tail=0.05): ground-truth amplification, tail discovery, top-k correction,
ground-truth regression, wrong-mode amplification, other. Report fractions by
difficulty bin (easy B1 vs hard B4/B5).
No-arg invocation = default analysis (SFT 20m_5.3B vs RL steps 100/300/500,
puzzles from B1 + B4 + B5).
"""
import argparse
import json
import os
import re
import sys
import torch
import chess
import numpy as np
from huggingface_hub import hf_hub_download, snapshot_download
from transformers import AutoModelForCausalLM, AutoTokenizer
BENCH_REPO = "pavelslab-nyu/chess_puzzle_benchmark"
RESULTS_REPO = "ML-Intern-lab/pre2post-chess-replication"
BOS, EOS, T_END, SEP, CALL_ENV = 0, 1, 82, 83, 84
LAN_RE = re.compile(r"^([KQRBNP])([a-h][1-8])(x?)([a-h][1-8])(=([QRBN]))?$")
def load_benchmark(bins, limit_per_bin, seed=0):
import pandas as pd
frames = []
for b in bins:
f = hf_hub_download(BENCH_REPO, f"think/test_{b}.parquet", repo_type="dataset")
df = pd.read_parquet(f)
if limit_per_bin:
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):
return list(v) if isinstance(v, list) else list(eval(v))
df["gt"] = df["reward_model"].apply(lambda r: _gt(r["ground_truth"]))
df["fen"] = df["extra_info"].apply(lambda r: r["FEN"])
df["bin"] = df["data_source"]
return df
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))
def lan_ids(self, lan):
return [self.vocab[t] for t in self.custom._lan_move_to_tokens(lan)]
def decode(self, ids):
return self.custom.decode(list(ids))
def legal_lan_moves(board):
"""LAN serializations of all legal moves (piece letter as on the board)."""
out = {}
for mv in board.legal_moves:
p = board.piece_at(mv.from_square)
piece = p.symbol().upper() if p else "P"
frm = chess.square_name(mv.from_square)
to = chess.square_name(mv.to_square)
cap = "x" if board.is_capture(mv) else ""
lan = f"{piece}{frm}{cap}{to}"
if mv.promotion:
lan += "=" + chess.piece_symbol(mv.promotion).upper()
out[mv.uci()] = lan
return out
def strip_pads(ids):
if EOS in ids:
ids = ids[: ids.index(EOS) + 1]
while ids and ids[-1] == BOS:
ids = ids[:-1]
return ids
@torch.no_grad()
def gen_round(model, contexts, max_new, stop_ids, temp, device):
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), 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))]
@torch.no_grad()
def sample_traces(model, adapter, prompt, K, thinking_budget, round_sz, temp, device):
"""K thinking traces via the verl forced-budget procedure."""
base = adapter.encode_prompt(prompt)
ctx = [list(base) for _ in range(K)]
used = [0] * K
done = [False] * K
while not all(done):
act = [i for i in range(K) if not done[i]]
gens = gen_round(model, [ctx[i] for i in act], round_sz, [T_END, EOS], temp, device)
for j, i in enumerate(act):
toks = gens[j][: thinking_budget - used[i]]
if not toks:
ctx[i] += [T_END]; used[i] += 1; done[i] = True; continue
used[i] += len(toks)
if toks[-1] == T_END:
if used[i] < thinking_budget:
ctx[i] += toks[:-1] + [SEP]
else:
ctx[i] += toks
done[i] = True
elif toks[-1] == EOS:
ctx[i] += toks + [T_END]
done[i] = True
else:
ctx[i] += toks
if used[i] >= thinking_budget:
ctx[i] += [T_END]
done[i] = True
for i in range(K):
if ctx[i][-1] != T_END:
ctx[i] += [T_END]
return [ctx[i][len(base):] for i in range(K)] # trace token lists
@torch.no_grad()
def move_probs_given_trace(model, adapter, base_ids, trace_ids, board, device):
"""pi(a|s,r) for all legal moves: one teacher-forced forward per move
(prefix + move tokens, batch=1), gathering the move tokens' logprobs."""
vocab = adapter.vocab
prefix = list(base_ids) + list(trace_ids)
prefix_t = torch.tensor([prefix], dtype=torch.long, device=device)
moves = legal_lan_moves(board)
logps = {}
for uci, lan in moves.items():
toks = [vocab[t] for t in adapter.custom._lan_move_to_tokens(lan)]
ids = torch.tensor([prefix + toks], dtype=torch.long, device=device)
logits = model(input_ids=ids).logits[0] # (L, V)
# logprob of token t at position i comes from logits at position i-1
lp = 0.0
for j, t in enumerate(toks):
pos = len(prefix) - 1 + j
lp += torch.log_softmax(logits[pos].float(), dim=-1)[t].item()
logps[uci] = lp
ucis = list(logps)
arr = np.array([logps[u] for u in ucis])
arr = arr - arr.max()
p = np.exp(arr)
p = p / p.sum()
return {u: float(pi) for u, pi in zip(ucis, p)}
def categorize(p_sft, p_rl, gt_uci, top_k=3, eps_tail=0.05):
def topk(p):
return set(u for u, _ in sorted(p.items(), key=lambda kv: -kv[1])[:top_k])
t0, t1 = topk(p_sft), topk(p_rl)
gt = gt_uci
d = p_rl.get(gt, 0.0) - p_sft.get(gt, 0.0)
wrong0 = max(p_sft, key=p_sft.get)
if gt in t0 and gt in t1 and d > 0:
return "gt_amplification"
if gt not in t0 and gt in t1 and p_sft.get(gt, 0.0) < eps_tail:
return "tail_discovery"
if gt not in t0 and gt in t1:
return "topk_correction"
if gt in t0 and gt not in t1:
return "gt_regression"
if gt not in t0 and gt not in t1 and wrong0 in t1 and d != 0 and \
p_rl.get(wrong0, 0.0) > p_sft.get(wrong0, 0.0):
return "wrong_mode_amplification"
return "other"
CHECKPOINTS = [
("sft", "pavelslab-nyu/Chess-SFT-Models", "model_20m_5.3B"),
("rl_100", "Pre2Post-Chess-RL/Chess-RL-Models", "model_20m_5.3B/global_step_100"),
("rl_300", "Pre2Post-Chess-RL/Chess-RL-Models", "model_20m_5.3B/global_step_300"),
("rl_500", "Pre2Post-Chess-RL/Chess-RL-Models", "model_20m_5.3B/global_step_500"),
]
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--bins", nargs="+", default=["B1", "B4", "B5"])
ap.add_argument("--limit-per-bin", type=int, default=12)
ap.add_argument("--k-traces", type=int, default=12)
ap.add_argument("--thinking-budget", type=int, default=1024)
ap.add_argument("--round", type=int, default=256)
ap.add_argument("--temp", type=float, default=1.0)
ap.add_argument("--seed", type=int, default=0)
ap.add_argument("--out", default="/work/results/t4_mechanism.json")
args = ap.parse_args()
torch.manual_seed(args.seed)
df = load_benchmark(args.bins, args.limit_per_bin, args.seed)
print(f"T4: {len(df)} puzzles x {len(CHECKPOINTS)} checkpoints, "
f"K={args.k_traces} traces", flush=True)
policies = {} # (ckpt, puzzle) -> {uci: prob}
for name, repo, sub in CHECKPOINTS:
local = snapshot_download(repo, allow_patterns=f"{sub}/*")
path = os.path.join(local, sub)
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)
for _, row in df.iterrows():
base = adapter.encode_prompt(row["prompt"])
traces = sample_traces(model, adapter, row["prompt"], args.k_traces,
args.thinking_budget, args.round, args.temp, device)
board = chess.Board(row["fen"])
acc = None
for tr in traces:
p = move_probs_given_trace(model, adapter, base, tr, board, device)
if acc is None:
acc = {u: v for u, v in p.items()}
else:
for u in acc:
acc[u] += p.get(u, 0.0)
acc = {u: v / len(traces) for u, v in acc.items()}
policies[(name, row["extra_info"]["PuzzleId"])] = acc
print(f"[{name}] {row['extra_info']['PuzzleId']} ({row['bin']}) done", flush=True)
del model
torch.cuda.empty_cache()
# categorize SFT -> RL per puzzle
cats = {}
for _, row in df.iterrows():
pid = row["extra_info"]["PuzzleId"]
gt = row["gt"][0]
p_sft = policies[("sft", pid)]
for name, _, _ in CHECKPOINTS[1:]:
cats.setdefault(name, {}).setdefault(row["bin"], {}).setdefault("counts", {})
c = categorize(p_sft, policies[(name, pid)], gt)
counts = cats[name][row["bin"]]["counts"]
counts[c] = counts.get(c, 0) + 1
out = {"config": vars(args), "policies": {f"{k[0]}|{k[1]}": v for k, v in policies.items()},
"categories": cats}
os.makedirs(os.path.dirname(args.out) or ".", exist_ok=True)
with open(args.out, "w") as f:
json.dump(out, f)
print(json.dumps(cats, indent=2), flush=True)
try:
from huggingface_hub import HfApi
HfApi().upload_file(path_or_fileobj=args.out, path_in_repo="results/t4_mechanism.json",
repo_id=RESULTS_REPO, repo_type="dataset")
print("[upload] t4_mechanism.json", flush=True)
except Exception as e:
print(f"[upload] FAILED: {e}", flush=True)
if __name__ == "__main__":
main()
|