"""Build a tiered lc0 self-play position corpus as a VPD1 database. For every run slice named in lc0_runs.TIERS this streams a bounded prefix of several tars, converts them to FENs through the rescorer, samples a few positions per game, and inserts them into the same VPD1 schema the CCRL corpus uses, so the two are directly comparable. Two choices are worth stating. Tars are read as bounded prefixes rather than in full. Positions cost the same number of bytes either way, but a prefix of each of forty tars spans forty points in a run's history, where four whole tars span four. Network diversity per byte downloaded is much better, and it is the diversity that this corpus is for. Only a few positions per game are kept. A game contributes about 110 positions, and consecutive ones are near-duplicates; sampling across phases keeps the effective sample size close to the row count. The CCRL corpus took three per game. Eight is the default here because these tars must be downloaded rather than read from a local archive, and eight cuts the download roughly fourfold for positions that are still tens of plies apart. Nothing is dropped for being hard to train on. Chess960 positions are dropped by default only because their Shredder-FEN castling fields are not standard chess and the rest of this pipeline assumes standard chess; pass --keep-chess960 to retain them. """ from __future__ import annotations import argparse import hashlib import json import random import re import shutil import subprocess import sys import tempfile import time from pathlib import Path import chess sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "vex-position-dataset")) from vpd import ( # noqa: E402 PHASE_NAMES, connect, current_counts, initialize, make_quotas, phase_of, position_record, set_metadata, ) from lc0_runs import EXCLUDED, TIERS, quotas, run_quotas # noqa: E402 BASE = "https://storage.lczero.org/files/training_data" LISTING_ROW = re.compile(r'href="([^"]+\.tar)">[^<]*\s+(\S+)\s+(\S+)\s+(\d+)') STANDARD_CASTLING = set("KQkq-") MIN_REAL_TAR = 50_000_000 INSERT_SQL = """ INSERT OR IGNORE INTO positions( random_key, fen, source_split, source_member, game_number, ply, result, side_to_move, phase, piece_count, non_pawn_material, material_balance, legal_moves, in_check, castling_mask, halfmove_clock ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) """ def spread(count: int) -> list[int]: """Indices 0..count-1 ordered so that any prefix is spread over the range. Van der Corput: reversing the bits of successive integers visits the range at ever finer resolution, so stopping early still leaves the tars taken scattered across the run's history rather than clustered at one end. """ if count <= 0: return [] bits = max(1, (count - 1).bit_length()) seen: list[int] = [] used = set() for i in range(1 << bits): reversed_bits = int(format(i, f"0{bits}b")[::-1], 2) if reversed_bits < count and reversed_bits not in used: used.add(reversed_bits) seen.append(reversed_bits) return seen def list_tars(run: str, cache: dict[str, list[tuple[str, int]]]) -> list[tuple[str, int]]: if run in cache: return cache[run] out = subprocess.run( ["curl", "-sS", "--max-time", "180", f"{BASE}/{run}/"], capture_output=True, text=True, ) rows = [ (name, int(size)) for name, _, _, size in LISTING_ROW.findall(out.stdout) if int(size) >= MIN_REAL_TAR ] cache[run] = rows return rows def fetch_prefix(run: str, tar: str, limit: int, destination: Path) -> int: """Download at most `limit` bytes of a tar. head closes the socket once it has enough, which the CDN honours where it ignores Range requests. """ command = ( f'curl -sS --max-time 900 "{BASE}/{run}/{tar}" | head -c {limit} > "{destination}"' ) subprocess.run(command, shell=True, capture_output=True) return destination.stat().st_size if destination.exists() else 0 def to_plain(rescorer: Path, tar_path: Path, workdir: Path, threads: int) -> Path | None: subprocess.run(["tar", "xf", str(tar_path), "-C", str(workdir)], capture_output=True) chunks = list(workdir.rglob("*.gz")) if not chunks: return None plain = workdir / "positions.plain" subprocess.run( [ str(rescorer), "rescore", f"--input={chunks[0].parent}", "--no-delete-files", f"--nnue-plain-file={plain}", "--nnue-best-score=true", "--nnue-best-move=true", "--deblunder=false", f"--threads={threads}", ], capture_output=True, text=True, ) return plain if plain.exists() else None def games(plain: Path): """Yield (fen, ply, result) lists, one per game. The rescorer appends games back to back and restarts ply at zero for each, so a non-increasing ply is a game boundary. """ current: list[tuple[str, int, str]] = [] fen = None ply = None last_ply = None with open(plain, encoding="utf-8", errors="replace") as handle: for row in handle: if row.startswith("fen "): fen = row[4:].strip() elif row.startswith("ply "): ply = int(row[4:]) elif row.startswith("result "): result = row[7:].strip() elif row.startswith("e") and row.strip() == "e": if fen is None or ply is None: continue if last_ply is not None and ply <= last_ply and current: yield current current = [] current.append((fen, ply, result)) last_ply = ply fen = ply = None if current: yield current def absolute_result(plain_result: str, white_to_move: bool) -> str: """Convert a .plain result to the PGN string VPD1 stores. Stockfish's plain format reports the game outcome from the side to move's perspective as 1/0/-1. VPD1 stores an absolute PGN result, as the CCRL corpus does, so the two are comparable and vpd.py analyze can read them. """ try: value = int(plain_result) except (TypeError, ValueError): return "*" if value == 0: return "1/2-1/2" white_won = (value > 0) == white_to_move return "1-0" if white_won else "0-1" def sample_game( positions: list[tuple[str, int, str]], per_game: int, counts: dict[int, int], phase_quotas: dict[int, int], rng: random.Random, keep_chess960: bool, ) -> list[tuple[chess.Board, int, int, str]]: """Pick a spread of positions from one game, respecting phase quotas.""" by_phase: dict[int, list[tuple[chess.Board, int, str]]] = {p: [] for p in PHASE_NAMES} for fen, ply, result in positions: if not keep_chess960 and not set(fen.split(" ")[2]) <= STANDARD_CASTLING: continue try: board = chess.Board(fen) except ValueError: continue by_phase[phase_of(board, ply)].append((board, ply, result)) # Split the per-game budget in the same 15/60/25 proportion as the corpus # quota. Taking an equal count from each phase instead saturates the small # opening quota long before the others, after which most of a downloaded # game is discarded. total_quota = sum(phase_quotas.values()) or 1 chosen: list[tuple[chess.Board, int, int, str]] = [] for phase, available in by_phase.items(): if not available or counts[phase] >= phase_quotas[phase]: continue wanted = max(1, round(per_game * phase_quotas[phase] / total_quota)) take = min(wanted, len(available), phase_quotas[phase] - counts[phase]) for board, ply, result in rng.sample(available, take): chosen.append((board, phase, ply, result)) return chosen def process_tar( db, rescorer: Path, run: str, tar: str, tier: str, limit: int, threads: int, per_game: int, counts: dict[int, int], phase_quotas: dict[int, int], seed: int, keep_chess960: bool, scratch: Path, ) -> dict[str, int]: stats = {"bytes": 0, "games": 0, "inserted": 0, "chess960": 0} workdir = Path(tempfile.mkdtemp(prefix="lc0tar.", dir=scratch)) try: tar_path = workdir / "prefix.tar" stats["bytes"] = fetch_prefix(run, tar, limit, tar_path) if stats["bytes"] < 100_000: return stats plain = to_plain(rescorer, tar_path, workdir, threads) if plain is None: return stats tar_path.unlink(missing_ok=True) for game_number, positions in enumerate(games(plain), start=1): stats["games"] += 1 stats["chess960"] += sum( not set(f.split(" ")[2]) <= STANDARD_CASTLING for f, _, _ in positions ) rng = random.Random( int.from_bytes( hashlib.blake2b( f"{seed}:{tar}:{game_number}".encode(), digest_size=8 ).digest(), "big", ) ) for board, phase, ply, result in sample_game( positions, per_game, counts, phase_quotas, rng, keep_chess960 ): cursor = db.execute( INSERT_SQL, position_record( board, tier, f"{run}/{tar}", game_number, ply, absolute_result(result, board.turn == chess.WHITE), phase, ), ) if cursor.rowcount: counts[phase] += 1 stats["inserted"] += 1 if all(counts[p] >= phase_quotas[p] for p in phase_quotas): break finally: shutil.rmtree(workdir, ignore_errors=True) return stats def main() -> None: parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument("--output", required=True, type=Path) parser.add_argument("--target", type=int, default=2_000_000) parser.add_argument("--per-game", type=int, default=12) parser.add_argument("--slice-bytes", type=int, default=120_000_000) parser.add_argument("--threads", type=int, default=8) parser.add_argument("--seed", type=int, default=91) parser.add_argument("--keep-chess960", action="store_true") parser.add_argument("--scratch", type=Path, default=Path(tempfile.gettempdir())) parser.add_argument( "--rescorer", type=Path, default=Path(__file__).resolve().parent.parent / "lc0-rescorer/build/release/rescorer", ) parser.add_argument("--dry-run", action="store_true", help="show the plan and exit") args = parser.parse_args() if not args.rescorer.exists(): sys.exit(f"No rescorer at {args.rescorer}") tier_quota = quotas(args.target) plan: list[tuple[str, str, float, float, int]] = [] for tier in TIERS: for key, quota in run_quotas(tier, tier_quota[tier.name]).items(): name, window = key.split(":") first, last = (float(x) for x in window.split("-")) plan.append((tier.name, name, first, last, quota)) print("Excluded runs:") for name, why in EXCLUDED.items(): print(f" {name:9} {why}") print(f"\nTarget {args.target:,} positions, {args.per_game} per game, " f"{args.slice_bytes / 1e6:.0f} MB per tar\n") for tier, run, first, last, quota in plan: print(f" {tier:7} {run:9} [{first:.2f}-{last:.2f}] {quota:>9,}") if args.dry_run: return args.output.parent.mkdir(parents=True, exist_ok=True) db = connect(args.output) initialize(db) set_metadata(db, "corpus", "lc0-selfplay-tiered") set_metadata(db, "source", BASE) set_metadata(db, "target_positions", args.target) set_metadata(db, "seed", args.seed) set_metadata(db, "per_game", args.per_game) set_metadata(db, "slice_bytes", args.slice_bytes) set_metadata(db, "keep_chess960", int(args.keep_chess960)) set_metadata(db, "excluded_runs", json.dumps(EXCLUDED, sort_keys=True)) set_metadata(db, "tier_quotas", json.dumps(tier_quota, sort_keys=True)) db.commit() done_row = db.execute("SELECT value FROM metadata WHERE key='tars_done'").fetchone() tars_done = set(json.loads(done_row[0])) if done_row else set() listing_cache: dict[str, list[tuple[str, int]]] = {} started = time.monotonic() for tier, run, first, last, quota in plan: have = db.execute( "SELECT COUNT(*) FROM positions WHERE source_split=? AND source_member LIKE ?", (tier, f"{run}/%"), ).fetchone()[0] if have >= quota: print(f"[{tier}/{run}] already at {have:,}/{quota:,}") continue tars = list_tars(run, listing_cache) window = tars[int(len(tars) * first) : max(int(len(tars) * last), 1)] if not window: print(f"[{tier}/{run}] no tars in window", file=sys.stderr) continue # Phase quotas are scoped to this run slice so each contributes the same # opening/middlegame/endgame mix as the CCRL corpus. base = { p: db.execute( "SELECT COUNT(*) FROM positions WHERE source_split=? " "AND source_member LIKE ? AND phase=?", (tier, f"{run}/%", p), ).fetchone()[0] for p in PHASE_NAMES } slice_quota = make_quotas(quota) counts = dict(base) print(f"\n[{tier}/{run}] {have:,}/{quota:,} from {len(window)} tars " f"in [{first:.2f}-{last:.2f}]") for index in spread(len(window)): if all(counts[p] >= slice_quota[p] for p in slice_quota): break tar = window[index][0] token = f"{run}/{tar}" if token in tars_done: continue stats = process_tar( db, args.rescorer, run, tar, tier, args.slice_bytes, args.threads, args.per_game, counts, slice_quota, args.seed, args.keep_chess960, args.scratch, ) tars_done.add(token) set_metadata(db, "tars_done", json.dumps(sorted(tars_done))) db.commit() total = sum(counts.values()) elapsed = time.monotonic() - started print( f" {tar[-21:]:21} {stats['bytes'] / 1e6:6.0f}MB " f"games={stats['games']:5,} +{stats['inserted']:6,} " f"-> {total:,}/{quota:,} [{elapsed / 60:.1f}m]", flush=True, ) total = db.execute("SELECT COUNT(*) FROM positions").fetchone()[0] set_metadata(db, "position_count", total) set_metadata(db, "completed_unix", int(time.time())) db.commit() print(f"\nWrote {total:,} positions to {args.output}") for row in db.execute( "SELECT source_split, COUNT(*) FROM positions GROUP BY source_split ORDER BY 2 DESC" ): print(f" {row[0]:8} {row[1]:>9,}") db.close() if __name__ == "__main__": main()