#!/usr/bin/env python """Compute pretraining validation loss L(N,T) for pre2post-chess checkpoints. The paper's Fig. 3a relates post-RL pass@1 to the *pretraining validation loss* on held-out human games. The authors' val split is not released, so we reconstruct a proxy: a held-out sample of Lichess standard rated games from 2023-01 (adjacent period to their 2022 corpus; same generator, properly held out), filtered like their corpus (Elo 800-3000, >=10 plies, blitz/rapid-like time controls). Games are scored with each checkpoint's own LAN tokenizer, mean NLL per token over 1024-token windows. Downloads only a partial slice of the public .pgn.zst dump via HTTP Range. Uploads one JSON per checkpoint to the results repo. No-arg invocation = sweep over the 20M/50M/200M/680M pretrain checkpoints. """ import argparse import io import json import os import re import urllib.request import torch import chess import chess.pgn from huggingface_hub import HfApi, snapshot_download from transformers import AutoModelForCausalLM, AutoTokenizer URL = "https://database.lichess.org/standard/lichess_db_standard_rated_2023-01.pgn.zst" RANGE_BYTES = 80 * 1024 * 1024 RESULTS_REPO = "ML-Intern-lab/pre2post-chess-replication" PRETRAIN_REPO = "pavelslab-nyu/Chess-Pretrain-Models" FAMILIES = ["20m", "50m", "200m", "680m"] def fetch_partial_games(cache_path, range_bytes=RANGE_BYTES): if os.path.exists(cache_path): return open(cache_path).read() import zstandard req = urllib.request.Request(URL, headers={"Range": f"bytes=0-{range_bytes - 1}"}) with urllib.request.urlopen(req, timeout=180) as resp: dctx = zstandard.ZstdDecompressor().stream_reader(resp) text = dctx.read().decode("utf-8", errors="ignore") starts = [m for m in range(len(text)) if text.startswith("[Event ", m)] text = text[: starts[4000]] if len(starts) > 4000 else text os.makedirs(os.path.dirname(cache_path), exist_ok=True) open(cache_path, "w").write(text) return text def filter_games(raw, max_games=3000): out = [] stream = io.StringIO(raw) while len(out) < max_games: game = chess.pgn.read_game(stream) if game is None: break tc = game.headers.get("TimeControl", "") base = tc.split("+")[0] if base and base.isdigit() and int(base) not in (60, 120, 180, 240, 300, 600): continue try: we, be = int(game.headers.get("WhiteElo", 0)), int(game.headers.get("BlackElo", 0)) except ValueError: continue if not (800 <= we <= 3000 and 800 <= be <= 3000): continue b = game.board() sans = [] for mv in game.mainline_moves(): sans.append(b.san(mv)) b.push(mv) if len(sans) < 10: continue out.append(" ".join(sans)) return out def windows_from_games(custom_tok, vocab, games, ctx=1024, min_tokens=64): ids_all = [] for g in games: toks = custom_tok._pgn_to_tokens(g) if not toks: continue ids = [vocab[t] for t in toks if t in vocab] ids = [vocab[""]] + ids for i in range(0, len(ids) - 1 - min_tokens, ctx): w = ids[i:i + ctx] if len(w) > min_tokens: ids_all.append(w) return ids_all @torch.no_grad() def eval_loss(model, vocab, windows, device, batch_size=16): pad = vocab[""] total, ntok = 0.0, 0 for i in range(0, len(windows), batch_size): batch = windows[i:i + batch_size] maxlen = max(len(w) for w in batch) input_ids = torch.full((len(batch), maxlen), pad, dtype=torch.long) attn = torch.zeros((len(batch), maxlen), dtype=torch.long) for j, w in enumerate(batch): input_ids[j, :len(w)] = torch.tensor(w) attn[j, :len(w)] = 1 input_ids, attn = input_ids.to(device), attn.to(device) logits = model(input_ids=input_ids, attention_mask=attn).logits targets = input_ids[:, 1:] mask = attn[:, 1:].bool() ll = torch.nn.functional.cross_entropy( logits[:, :-1].reshape(-1, logits[:, :-1].size(-1)).float(), targets.reshape(-1), reduction="none").view(targets.shape) sel = ll[mask] total += sel.sum().item() ntok += int(mask.sum().item()) return total / ntok, ntok def main(): ap = argparse.ArgumentParser() ap.add_argument("--n-games", type=int, default=3000) ap.add_argument("--max-windows", type=int, default=2048) ap.add_argument("--cache", default="/work/data/lichess_2023_01_head.pgn") ap.add_argument("--families", nargs="+", default=FAMILIES) ap.add_argument("--out-dir", default="/work/results/loss") args = ap.parse_args() raw = fetch_partial_games(args.cache) games = filter_games(raw, args.n_games) print(f"held-out games: {len(games)}", flush=True) api = HfApi() files = api.list_repo_files(PRETRAIN_REPO, repo_type="model") runs = sorted(set(f.split("/")[0] for f in files if f.startswith("model_") and "/" in f)) runs = [r for r in runs if any(r.startswith(f"model_{fam}_") for fam in args.families)] print(f"{len(runs)} checkpoints: {runs}", flush=True) for run in runs: out_path = os.path.join(args.out_dir, f"loss_{run}.json") if os.path.exists(out_path): print(f"[skip] {run} done", flush=True) continue try: local = snapshot_download(PRETRAIN_REPO, allow_patterns=f"{run}/*") path = os.path.join(local, run) 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) custom, vocab = tok.custom_tokenizer, tok.custom_tokenizer._tok2id windows = windows_from_games(custom, vocab, games)[: args.max_windows] loss, ntok = eval_loss(model, vocab, windows, device) # parse size and tokens from the run name, e.g. model_20m_5.3B m = re.match(r"model_(\d+)m_([\d.]+)B", run) size_m, tokens_b = (m.group(1), m.group(2)) if m else ("?", "?") rec = {"run": run, "val_loss": loss, "n_tokens": ntok, "n_windows": len(windows), "n_games": len(games), "size_millions": int(size_m) if size_m != "?" else None, "pretrain_tokens": float(tokens_b) * 1e9 if tokens_b != "?" else None} os.makedirs(args.out_dir, exist_ok=True) with open(out_path, "w") as f: json.dump(rec, f) del model torch.cuda.empty_cache() print(f"[loss] {run}: {loss:.4f} ({ntok} tokens)", flush=True) try: api.upload_file(path_or_fileobj=out_path, path_in_repo=f"results/loss/loss_{run}.json", repo_id=RESULTS_REPO, repo_type="dataset") print(f"[upload] loss_{run}", flush=True) except Exception as e: print(f"[upload] FAILED {run}: {e}", flush=True) except Exception as e: print(f"[loss] {run} FAILED: {e}", flush=True) if __name__ == "__main__": main()