zero-evaluator / scripts /build_human_corpus.py
Pawitt's picture
Add lc0 self-play and Lichess Elite position collections
0040de1 verified
Raw History Blame Contribute Delete
11.3 kB
"""Build the human partition of the corpus from the Lichess Elite Database.
The Elite Database is the Lichess standard database filtered to games where a
2400+ player faced a 2200+ player. It is published as one zip per month at
database.nikonoel.fr.
Composition, measured on 2025-08: about 88% of games are 3+0 or 3+2 blitz, 6%
rapid, under 1% classical, with White Elo median 2550 and a maximum of 3215.
The partition is therefore strong human blitz, not considered classical play.
That is a real characteristic rather than a defect for this corpus: the point of
a human partition is positions engines do not reach, and human blitz reaches
plenty. It is recorded in the database metadata so it is never a surprise.
Games below --min-base-seconds are dropped, which removes bullet.
Sampling is two-phase per month. chess.pgn.read_headers skips move text and runs
at about 75,000 games/s, against 1,300 for a full parse, so the whole month is
indexed by byte offset first and only the games actually selected are parsed.
That keeps selection uniform over games — sampling by byte offset instead would
have favoured long games — while costing seconds rather than minutes.
"""
from __future__ import annotations
import argparse
import collections
import hashlib
import json
import random
import re
import shutil
import subprocess
import sys
import tempfile
import time
import zipfile
from pathlib import Path
import chess
import chess.pgn
sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "vex-position-dataset"))
from vpd import ( # noqa: E402
PHASE_NAMES,
connect,
initialize,
make_quotas,
phase_of,
position_record,
set_metadata,
)
from build_selfplay_corpus import INSERT_SQL, spread # noqa: E402
BASE = "https://database.nikonoel.fr"
MONTH = re.compile(r"lichess_elite_(\d{4}-\d{2})\.zip")
def list_months() -> list[str]:
out = subprocess.run(
["curl", "-sS", "--max-time", "120", f"{BASE}/"], capture_output=True, text=True
)
return sorted(set(MONTH.findall(out.stdout)))
SPEEDS = ("ultrabullet", "bullet", "blitz", "rapid", "classical", "correspondence")
def base_seconds(time_control: str) -> int:
"""Seconds on the clock before increment; 0 when unparseable."""
head = (time_control or "").split("+")[0]
return int(head) if head.isdigit() else 0
def speed_category(headers) -> str:
"""Classify a game's speed from whichever headers the month provides.
The Elite Database changed schema partway through its history. Months from
2025 carry TimeControl, LichessURL and UTCDate; older months instead carry
EventType and PlyCount and no TimeControl at all. Reading only TimeControl
silently rejects every game in the older format, so all three sources are
tried and anything still unrecognised is kept rather than dropped.
"""
base = base_seconds(headers.get("TimeControl", ""))
if base:
if base < 60:
return "ultrabullet"
if base < 180:
return "bullet"
if base < 480:
return "blitz"
if base < 1500:
return "rapid"
return "classical"
event_type = headers.get("EventType", "").strip().lower()
if event_type in SPEEDS:
return event_type
event = headers.get("Event", "").lower()
for name in SPEEDS:
if name in event:
return name
return "unknown"
def index_month(pgn: Path, excluded: frozenset[str]) -> tuple[list[int], collections.Counter]:
"""Byte offsets of every eligible game, plus the speed mix."""
offsets: list[int] = []
mix: collections.Counter = collections.Counter()
# utf-8-sig: some months begin with a byte order mark.
with open(pgn, encoding="utf-8-sig", errors="replace") as handle:
while True:
offset = handle.tell()
headers = chess.pgn.read_headers(handle)
if headers is None:
break
speed = speed_category(headers)
mix[speed] += 1
if speed not in excluded:
offsets.append(offset)
return offsets, mix
def sample_positions(
game: chess.pgn.Game,
per_game: int,
counts: dict[int, int],
phase_quotas: dict[int, int],
rng: random.Random,
) -> list[tuple[chess.Board, int, int, str]]:
"""Reservoir one position per phase, as the CCRL extractor does."""
board = game.board()
reservoir: dict[int, tuple[chess.Board, int]] = {}
seen = {phase: 0 for phase in PHASE_NAMES}
try:
for ply, move in enumerate(game.mainline_moves(), start=1):
board.push(move)
phase = phase_of(board, ply)
if counts[phase] >= phase_quotas[phase]:
continue
seen[phase] += 1
if rng.randrange(seen[phase]) == 0:
reservoir[phase] = (board.copy(stack=False), ply)
except (ValueError, AssertionError):
return []
result = game.headers.get("Result", "*")
picks = [(b, phase, ply, result) for phase, (b, ply) in reservoir.items()]
rng.shuffle(picks)
return picks[:per_game]
def process_month(
db, month: str, counts: dict[int, int], phase_quotas: dict[int, int],
quota: int, per_game: int, excluded: frozenset[str], seed: int, scratch: Path,
) -> dict[str, object]:
stats: dict[str, object] = {"games": 0, "inserted": 0, "eligible": 0, "mix": {}}
workdir = Path(tempfile.mkdtemp(prefix="elite.", dir=scratch))
try:
archive = workdir / f"{month}.zip"
subprocess.run(
["curl", "-fsS", "--max-time", "1800", f"{BASE}/lichess_elite_{month}.zip",
"-o", str(archive)],
capture_output=True,
)
if not archive.exists() or archive.stat().st_size < 1_000_000:
return stats
with zipfile.ZipFile(archive) as zf:
name = zf.namelist()[0]
pgn = workdir / name
with zf.open(name) as src, open(pgn, "wb") as dst:
shutil.copyfileobj(src, dst, 1 << 20)
archive.unlink()
offsets, mix = index_month(pgn, excluded)
stats["eligible"] = len(offsets)
stats["mix"] = dict(mix.most_common())
if not offsets:
return stats
rng = random.Random(
int.from_bytes(
hashlib.blake2b(f"{seed}:{month}".encode(), digest_size=8).digest(), "big"
)
)
rng.shuffle(offsets)
with open(pgn, encoding="utf-8-sig", errors="replace") as handle:
for offset in offsets:
if sum(counts.values()) >= quota:
break
handle.seek(offset)
game = chess.pgn.read_game(handle)
if game is None:
continue
stats["games"] += 1
picks = sample_positions(game, per_game, counts, phase_quotas, rng)
for board, phase, ply, result in picks:
cursor = db.execute(
INSERT_SQL,
position_record(
board, "human", f"lichess-elite/{month}",
stats["games"], ply, result, phase,
),
)
if cursor.rowcount:
counts[phase] += 1
stats["inserted"] = int(stats["inserted"]) + 1
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=300_000)
parser.add_argument("--per-game", type=int, default=3)
parser.add_argument("--months", type=int, default=12)
parser.add_argument("--exclude-speeds", default="ultrabullet,bullet",
help="comma-separated speeds to drop; empty keeps everything")
parser.add_argument("--seed", type=int, default=91)
parser.add_argument("--scratch", type=Path, default=Path(tempfile.gettempdir()))
parser.add_argument("--dry-run", action="store_true")
args = parser.parse_args()
excluded = frozenset(x.strip() for x in args.exclude_speeds.split(",") if x.strip())
available = list_months()
if not available:
sys.exit("Could not list months from database.nikonoel.fr")
chosen = sorted(available[i] for i in spread(len(available))[: args.months])
print(f"{len(available)} months available ({available[0]} .. {available[-1]})")
print(f"Using {len(chosen)}: {', '.join(chosen)}")
print(f"Target {args.target:,} positions, {args.per_game} per game, "
f"excluding {sorted(excluded) or ['nothing']}")
if args.dry_run:
return
args.output.parent.mkdir(parents=True, exist_ok=True)
db = connect(args.output)
initialize(db)
set_metadata(db, "corpus", "lichess-elite-human")
set_metadata(db, "source", f"{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, "excluded_speeds", args.exclude_speeds)
set_metadata(db, "months", json.dumps(chosen))
db.commit()
counts = {
p: db.execute("SELECT COUNT(*) FROM positions WHERE phase=?", (p,)).fetchone()[0]
for p in PHASE_NAMES
}
done_row = db.execute("SELECT value FROM metadata WHERE key='months_done'").fetchone()
months_done = set(json.loads(done_row[0])) if done_row else set()
mixes: dict[str, dict] = {}
started = time.monotonic()
# Each month gets an equal share, otherwise the first month alone fills the
# target and the spread across the database's history never happens.
for index, month in enumerate(chosen, start=1):
if sum(counts.values()) >= args.target or month in months_done:
continue
cumulative = min(args.target, round(args.target * index / len(chosen)))
stats = process_month(
db, month, counts, make_quotas(cumulative), cumulative, args.per_game,
excluded, args.seed, args.scratch,
)
mixes[month] = stats["mix"]
months_done.add(month)
set_metadata(db, "months_done", json.dumps(sorted(months_done)))
set_metadata(db, "speed_mix", json.dumps(mixes, sort_keys=True))
db.commit()
print(
f" {month} eligible={stats['eligible']:>7,} read={stats['games']:>7,} "
f"+{stats['inserted']:>6,} -> {sum(counts.values()):,}/{args.target:,} "
f"[{(time.monotonic() - started) / 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 phase, count in db.execute(
"SELECT phase, COUNT(*) FROM positions GROUP BY phase ORDER BY phase"
):
print(f" {PHASE_NAMES[phase]:11} {count:>8,}")
db.close()
if __name__ == "__main__":
main()