File size: 15,413 Bytes
0040de1 | 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 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 | """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)">[^<]*</a>\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()
|