#!/usr/bin/env python3 """Generate a Stockfish-distillation chess dataset. Positions are produced by short self-play at weak Stockfish skill levels (3..7, i.e. around the target SF5 band), then labeled by full-strength Stockfish at a fixed depth. Output is Parquet shards ready for HF upload. Usage: python distill.py --target 100000 --workers 8 --depth 12 --out data On Kaggle CPU: python distill.py --target 500000 --workers 4 --depth 12 --out /kaggle/working/data """ from __future__ import annotations import argparse import os import random import shutil import subprocess import sys import time from dataclasses import dataclass from multiprocessing import get_context from pathlib import Path import chess import pyarrow as pa import pyarrow.parquet as pq from tqdm import tqdm CREATE_NO_WINDOW = 0x08000000 if os.name == "nt" else 0 SCHEMA = pa.schema( [ ("fen", pa.string()), ("move_uci", pa.string()), ("move_san", pa.string()), ("cp", pa.int16()), ("mate", pa.int8()), ("wdl", pa.int8()), ("pv", pa.string()), ("depth", pa.int16()), ("nodes", pa.int64()), ("source", pa.string()), ] ) @dataclass class Info: cp: int | None = None mate: int | None = None wdl: int | None = None pv: list[str] | None = None depth: int | None = None nodes: int | None = None class UCIEngine: def __init__(self, path: str, hash_mb: int = 16): self.path = path self.proc = subprocess.Popen( [path], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, encoding="utf-8", errors="replace", bufsize=1, creationflags=CREATE_NO_WINDOW, ) self._send("uci") self._wait("uciok") self._send("setoption name Threads value 1") self._send(f"setoption name Hash value {hash_mb}") self._send("setoption name UCI_ShowWDL value true") self._send("setoption name Skill Level value 20") self._send("isready") self._wait("readyok") self.skill = 20 def _send(self, line: str) -> None: self.proc.stdin.write(line + "\n") self.proc.stdin.flush() def _readline(self) -> str: line = self.proc.stdout.readline() if not line: raise RuntimeError("Stockfish closed stdout") return line.strip() def _wait(self, token: str) -> None: while self._readline() != token: pass def set_skill(self, skill: int) -> None: skill = max(0, min(20, int(skill))) if skill != self.skill: self._send(f"setoption name Skill Level value {skill}") self.skill = skill def best(self, board: chess.Board, depth: int) -> tuple[str, Info]: self._send("position fen " + board.fen()) self._send(f"go depth {depth}") info = Info() best = "" while True: line = self._readline() if line.startswith("info "): tokens = line.split() if "depth" in tokens: try: info.depth = int(tokens[tokens.index("depth") + 1]) except Exception: pass if "nodes" in tokens: try: info.nodes = int(tokens[tokens.index("nodes") + 1]) except Exception: pass if "score" in tokens: i = tokens.index("score") kind = tokens[i + 1] try: value = int(tokens[i + 2]) except Exception: value = 0 if kind == "cp": info.cp = value info.mate = None elif kind == "mate": info.mate = value info.cp = None if "wdl" in tokens: i = tokens.index("wdl") try: win, draw, loss = (int(tokens[i + 1]), int(tokens[i + 2]), int(tokens[i + 3])) if win > max(draw, loss): info.wdl = 2 elif loss > max(win, draw): info.wdl = 0 else: info.wdl = 1 except Exception: pass if "pv" in tokens: i = tokens.index("pv") info.pv = tokens[i + 1:] elif line.startswith("bestmove"): parts = line.split() best = parts[1] if len(parts) > 1 else "" break return best, info def close(self) -> None: try: self._send("quit") self.proc.wait(timeout=5) except Exception: try: self.proc.kill() except Exception: pass # ------------------------------------------------------------------ workers ENGINE: UCIEngine | None = None WORK_DEPTH = 12 MIN_PLIES = 6 MAX_PLIES = 36 GEN_SKILLS = (3, 4, 5, 6, 7) def _init_worker(stockfish: str, depth: int, min_plies: int, max_plies: int) -> None: global ENGINE, WORK_DEPTH, MIN_PLIES, MAX_PLIES ENGINE = UCIEngine(stockfish) WORK_DEPTH = depth MIN_PLIES = min_plies MAX_PLIES = max_plies def _make_positions(rng: random.Random, count: int) -> list[str]: positions: list[str] = [] attempts = 0 max_attempts = max(10, count * 20) while len(positions) < count and attempts < max_attempts: attempts += 1 board = chess.Board() # A few random opening plies, then weak-engine self-play. for _ in range(rng.randint(0, 4)): moves = list(board.legal_moves) if not moves: break board.push(rng.choice(moves)) target_plies = rng.randint(MIN_PLIES, MAX_PLIES) while not board.is_game_over(claim_draw=True) and len(board.move_stack) < target_plies: if len(board.move_stack) >= MIN_PLIES: positions.append(board.fen()) if len(positions) >= count: break ENGINE.set_skill(rng.choice(GEN_SKILLS)) depth = rng.choice((1, 2, 2, 3)) uci, _ = ENGINE.best(board, depth) if not uci or uci in ("(none)", "0000"): break try: move = chess.Move.from_uci(uci) except ValueError: break if move not in board.legal_moves: break board.push(move) return positions[:count] def _label(fen: str, depth: int) -> dict | None: board = chess.Board(fen) if board.is_game_over(claim_draw=True): return None ENGINE.set_skill(20) uci, info = ENGINE.best(board, depth) if not uci or uci in ("(none)", "0000"): return None try: move = chess.Move.from_uci(uci) except ValueError: return None if move not in board.legal_moves: return None cp = info.cp mate = info.mate if cp is not None: cp = max(-30000, min(30000, cp)) if mate is not None: mate = max(-127, min(127, mate)) wdl = info.wdl if wdl is None: if mate is not None: wdl = 2 if mate > 0 else 0 elif cp is not None: wdl = 2 if cp >= 100 else 0 if cp <= -100 else 1 else: wdl = 1 pv = " ".join((info.pv or [])[:6]) return { "fen": board.fen(), "move_uci": move.uci(), "move_san": board.san(move), "cp": cp, "mate": mate, "wdl": wdl, "pv": pv, "depth": info.depth or depth, "nodes": info.nodes or 0, "source": "sf_selfplay", } def _work(task: tuple[int, int]) -> list[dict]: seed, count = task rng = random.Random(seed) positions = _make_positions(rng, count) records = [] for fen in positions: try: record = _label(fen, WORK_DEPTH) except Exception: record = None if record is not None: records.append(record) return records # ------------------------------------------------------------------ output def _existing_rows(out_dir: Path) -> int: total = 0 for path in sorted(out_dir.glob("*.parquet")): try: total += pq.ParquetFile(path).metadata.num_rows except Exception: pass return total def _write_shard(out_dir: Path, index: int, records: list[dict]) -> Path: table = pa.Table.from_pylist(records, schema=SCHEMA) path = out_dir / f"train-{index:05d}.parquet" pq.write_table(table, path, compression="zstd") return path def find_stockfish(explicit: str | None) -> str: candidates = [] if explicit: candidates.append(explicit) env = os.environ.get("STOCKFISH_PATH") if env: candidates.append(env) candidates += [ "stockfish", "stockfish.exe", "engines/stockfish/stockfish/stockfish-windows-x86-64-universal.exe", str(Path.home() / "stockfish" / "stockfish-windows-x86-64-universal.exe"), "D:/AuroraAI17/chess_client/engines/stockfish/stockfish/stockfish-windows-x86-64-universal.exe", ] for candidate in candidates: if candidate and (os.path.isfile(candidate) or shutil.which(candidate)): return candidate raise SystemExit( "Stockfish not found. Pass --stockfish PATH or set STOCKFISH_PATH." ) def main() -> None: parser = argparse.ArgumentParser() parser.add_argument("--target", type=int, default=100_000) parser.add_argument("--workers", type=int, default=max(1, (os.cpu_count() or 4) - 1)) parser.add_argument("--depth", type=int, default=12) parser.add_argument("--chunk", type=int, default=250) parser.add_argument("--shard-size", type=int, default=50_000) parser.add_argument("--min-plies", type=int, default=6) parser.add_argument("--max-plies", type=int, default=36) parser.add_argument("--out", default="data") parser.add_argument("--stockfish", default=None) parser.add_argument("--seed", type=int, default=1234) args = parser.parse_args() stockfish = find_stockfish(args.stockfish) out_dir = Path(args.out) out_dir.mkdir(parents=True, exist_ok=True) already = _existing_rows(out_dir) remaining = max(0, args.target - already) print(f"stockfish: {stockfish}") print(f"target: {args.target:,}; existing: {already:,}; remaining: {remaining:,}") if remaining == 0: return chunks = [] done = 0 chunk_index = 0 while done < remaining: count = min(args.chunk, remaining - done) chunks.append((args.seed + chunk_index * 7919, count)) done += count chunk_index += 1 buffer: list[dict] = [] shard_index = already // args.shard_size total = 0 started = time.time() ctx = get_context("spawn") with ctx.Pool( processes=args.workers, initializer=_init_worker, initargs=(stockfish, args.depth, args.min_plies, args.max_plies), ) as pool: progress = tqdm(total=remaining, unit="pos", smoothing=0.05) for records in pool.imap_unordered(_work, chunks): buffer.extend(records) total += len(records) progress.update(len(records)) while len(buffer) >= args.shard_size: shard = buffer[: args.shard_size] del buffer[: args.shard_size] path = _write_shard(out_dir, shard_index, shard) shard_index += 1 print(f"\nwrote {path} ({len(shard):,} rows)", flush=True) progress.close() if buffer: path = _write_shard(out_dir, shard_index, buffer) print(f"wrote {path} ({len(buffer):,} rows)", flush=True) elapsed = time.time() - started print( f"done: {total:,} rows in {elapsed:.1f}s " f"({total / max(elapsed, 1e-9):.1f} pos/s)" ) if __name__ == "__main__": main()