File size: 20,330 Bytes
5f87c14 | 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 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 | #!/usr/bin/env python3
"""Build, analyze, and sample a Vex Position Dataset (VPD1) database."""
from __future__ import annotations
import argparse
import hashlib
import io
import json
import math
import random
import sqlite3
import statistics
import sys
import tarfile
import time
from pathlib import Path
import chess
import chess.pgn
FORMAT_VERSION = "VPD1"
DEFAULT_TARGET = 1_500_000
PHASE_NAMES = {0: "opening", 1: "middlegame", 2: "endgame"}
PHASE_IDS = {name: value for value, name in PHASE_NAMES.items()}
PIECE_VALUES = {
chess.PAWN: 1,
chess.KNIGHT: 3,
chess.BISHOP: 3,
chess.ROOK: 5,
chess.QUEEN: 9,
}
class NonSeekableReader(io.RawIOBase):
"""Adapt tarfile's streaming member object for TextIOWrapper on Python 3.14."""
def __init__(self, source: object) -> None:
self.source = source
def readable(self) -> bool:
return True
def seekable(self) -> bool:
return False
def readinto(self, buffer: bytearray) -> int:
chunk = self.source.read(len(buffer))
if not chunk:
return 0
buffer[: len(chunk)] = chunk
return len(chunk)
def connect(path: Path) -> sqlite3.Connection:
db = sqlite3.connect(path)
db.execute("PRAGMA journal_mode=WAL")
db.execute("PRAGMA synchronous=NORMAL")
db.execute("PRAGMA temp_store=MEMORY")
db.execute("PRAGMA cache_size=-262144")
db.execute("PRAGMA foreign_keys=ON")
return db
def initialize(db: sqlite3.Connection) -> None:
db.executescript(
"""
CREATE TABLE IF NOT EXISTS metadata (
key TEXT PRIMARY KEY,
value TEXT NOT NULL
) WITHOUT ROWID;
CREATE TABLE IF NOT EXISTS positions (
id INTEGER PRIMARY KEY,
random_key INTEGER NOT NULL UNIQUE,
fen TEXT NOT NULL UNIQUE,
source_split TEXT NOT NULL,
source_member TEXT NOT NULL,
game_number INTEGER NOT NULL,
ply INTEGER NOT NULL,
result TEXT NOT NULL,
side_to_move INTEGER NOT NULL CHECK(side_to_move IN (0, 1)),
phase INTEGER NOT NULL CHECK(phase BETWEEN 0 AND 2),
piece_count INTEGER NOT NULL,
non_pawn_material INTEGER NOT NULL,
material_balance INTEGER NOT NULL,
legal_moves INTEGER NOT NULL,
in_check INTEGER NOT NULL CHECK(in_check IN (0, 1)),
castling_mask INTEGER NOT NULL CHECK(castling_mask BETWEEN 0 AND 15),
halfmove_clock INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS positions_phase ON positions(phase);
CREATE INDEX IF NOT EXISTS positions_result ON positions(result);
CREATE INDEX IF NOT EXISTS positions_legal_moves ON positions(legal_moves);
CREATE INDEX IF NOT EXISTS positions_piece_count ON positions(piece_count);
CREATE INDEX IF NOT EXISTS positions_material_balance
ON positions(material_balance);
CREATE INDEX IF NOT EXISTS positions_split ON positions(source_split);
"""
)
set_metadata(db, "format", FORMAT_VERSION)
set_metadata(db, "fen_fullmove_normalization", "1")
def set_metadata(db: sqlite3.Connection, key: str, value: object) -> None:
db.execute(
"INSERT INTO metadata(key, value) VALUES (?, ?) "
"ON CONFLICT(key) DO UPDATE SET value=excluded.value",
(key, str(value)),
)
def normalized_fen(board: chess.Board) -> str:
fields = board.fen(en_passant="fen").split()
fields[5] = "1"
return " ".join(fields)
def phase_of(board: chess.Board, ply: int) -> int:
non_pawn = sum(
PIECE_VALUES[piece_type]
* (
len(board.pieces(piece_type, chess.WHITE))
+ len(board.pieces(piece_type, chess.BLACK))
)
for piece_type in (chess.KNIGHT, chess.BISHOP, chess.ROOK, chess.QUEEN)
)
piece_count = chess.popcount(board.occupied)
if ply <= 20 and non_pawn >= 50:
return PHASE_IDS["opening"]
if non_pawn <= 20 or piece_count <= 12:
return PHASE_IDS["endgame"]
return PHASE_IDS["middlegame"]
def castling_mask(board: chess.Board) -> int:
return (
int(board.has_kingside_castling_rights(chess.WHITE))
| (int(board.has_queenside_castling_rights(chess.WHITE)) << 1)
| (int(board.has_kingside_castling_rights(chess.BLACK)) << 2)
| (int(board.has_queenside_castling_rights(chess.BLACK)) << 3)
)
def material(board: chess.Board) -> tuple[int, int]:
white = sum(
PIECE_VALUES[piece_type] * len(board.pieces(piece_type, chess.WHITE))
for piece_type in PIECE_VALUES
)
black = sum(
PIECE_VALUES[piece_type] * len(board.pieces(piece_type, chess.BLACK))
for piece_type in PIECE_VALUES
)
non_pawn = sum(
PIECE_VALUES[piece_type]
* (
len(board.pieces(piece_type, chess.WHITE))
+ len(board.pieces(piece_type, chess.BLACK))
)
for piece_type in (chess.KNIGHT, chess.BISHOP, chess.ROOK, chess.QUEEN)
)
return white - black, non_pawn
def random_key(fen: str) -> int:
raw = hashlib.blake2b(fen.encode("ascii"), digest_size=8).digest()
return int.from_bytes(raw, "big") & ((1 << 63) - 1)
def position_record(
board: chess.Board,
source_split: str,
source_member: str,
game_number: int,
ply: int,
result: str,
phase: int,
) -> tuple[object, ...]:
fen = normalized_fen(board)
balance, non_pawn = material(board)
return (
random_key(fen),
fen,
source_split,
source_member,
game_number,
ply,
result,
int(board.turn == chess.WHITE),
phase,
chess.popcount(board.occupied),
non_pawn,
balance,
board.legal_moves.count(),
int(board.is_check()),
castling_mask(board),
board.halfmove_clock,
)
def split_for(member_name: str) -> str:
lowered = member_name.lower()
if "test" in lowered:
return "test"
if "train" in lowered:
return "train"
return "unspecified"
def make_quotas(target: int) -> dict[int, int]:
opening = round(target * 0.15)
endgame = round(target * 0.25)
return {0: opening, 1: target - opening - endgame, 2: endgame}
def current_counts(db: sqlite3.Connection) -> dict[int, int]:
counts = {phase: 0 for phase in PHASE_NAMES}
counts.update(dict(db.execute("SELECT phase, COUNT(*) FROM positions GROUP BY phase")))
return counts
def extract(args: argparse.Namespace) -> None:
source = Path(args.source).resolve()
output = Path(args.output).resolve()
output.parent.mkdir(parents=True, exist_ok=True)
db = connect(output)
initialize(db)
quotas = make_quotas(args.target)
counts = current_counts(db)
resume_row = db.execute(
"SELECT source_member FROM positions ORDER BY id DESC LIMIT 1"
).fetchone()
resume_member = resume_row[0] if resume_row else None
games_seen = int(
db.execute("SELECT COALESCE(value, '0') FROM metadata WHERE key='games_seen'")
.fetchone()[0]
if db.execute("SELECT 1 FROM metadata WHERE key='games_seen'").fetchone()
else 0
)
candidates_attempted = int(
db.execute(
"SELECT COALESCE(value, '0') FROM metadata "
"WHERE key='candidates_attempted'"
).fetchone()[0]
if db.execute(
"SELECT 1 FROM metadata WHERE key='candidates_attempted'"
).fetchone()
else 0
)
parse_errors = 0
inserted_since_commit = 0
started = time.monotonic()
set_metadata(db, "source", str(source))
set_metadata(db, "target_positions", args.target)
set_metadata(db, "seed", args.seed)
set_metadata(db, "phase_quotas", json.dumps(quotas, sort_keys=True))
db.commit()
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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
"""
with tarfile.open(source, mode="r|bz2") as archive:
corpus_game_number = 0
finished = False
reached_resume_member = resume_member is None
for member in archive:
if finished:
break
if not member.isfile() or not member.name.lower().endswith(".pgn"):
continue
if not reached_resume_member:
if member.name != resume_member:
continue
reached_resume_member = True
raw = archive.extractfile(member)
if raw is None:
continue
split = split_for(member.name)
buffered = io.BufferedReader(NonSeekableReader(raw))
with io.TextIOWrapper(buffered, encoding="utf-8", errors="replace") as pgn:
member_game_number = 0
while True:
try:
game = chess.pgn.read_game(pgn)
except Exception as exc: # Keep streaming past isolated bad games.
parse_errors += 1
print(f"PGN parse error in {member.name}: {exc}", file=sys.stderr)
continue
if game is None:
break
corpus_game_number += 1
member_game_number += 1
games_seen += 1
board = game.board()
result = game.headers.get("Result", "*")
reservoirs: dict[int, tuple[chess.Board, int]] = {}
phase_seen = {phase: 0 for phase in PHASE_NAMES}
game_seed = int.from_bytes(
hashlib.blake2b(
f"{args.seed}:{member.name}:{member_game_number}".encode(),
digest_size=8,
).digest(),
"big",
)
game_rng = random.Random(game_seed)
try:
for ply, move in enumerate(game.mainline_moves(), start=1):
board.push(move)
phase = phase_of(board, ply)
if counts[phase] >= quotas[phase]:
continue
phase_seen[phase] += 1
if game_rng.randrange(phase_seen[phase]) == 0:
reservoirs[phase] = (board.copy(stack=False), ply)
except Exception:
parse_errors += 1
continue
for phase, (candidate, ply) in reservoirs.items():
if counts[phase] >= quotas[phase]:
continue
candidates_attempted += 1
cursor = db.execute(
insert_sql,
position_record(
candidate,
split,
member.name,
corpus_game_number,
ply,
result,
phase,
),
)
if cursor.rowcount:
counts[phase] += 1
inserted_since_commit += 1
if inserted_since_commit >= args.commit_every:
set_metadata(db, "games_seen", games_seen)
set_metadata(db, "candidates_attempted", candidates_attempted)
set_metadata(db, "parse_errors", parse_errors)
db.commit()
inserted_since_commit = 0
if games_seen % args.progress_every == 0:
elapsed = max(time.monotonic() - started, 0.001)
total = sum(counts.values())
print(
f"games={games_seen:,} positions={total:,}/{args.target:,} "
f"opening={counts[0]:,} middle={counts[1]:,} "
f"endgame={counts[2]:,} rate={total / elapsed:,.0f} pos/s",
flush=True,
)
if all(counts[p] >= quotas[p] for p in quotas):
finished = True
break
set_metadata(db, "games_seen", games_seen)
set_metadata(db, "candidates_attempted", candidates_attempted)
set_metadata(db, "parse_errors", parse_errors)
set_metadata(db, "completed_unix", int(time.time()))
set_metadata(db, "position_count", sum(counts.values()))
db.commit()
db.execute("PRAGMA optimize")
db.execute("PRAGMA wal_checkpoint(TRUNCATE)")
db.close()
print(json.dumps(analyze_database(output), indent=2, sort_keys=True))
def grouped(db: sqlite3.Connection, column: str) -> dict[str, int]:
return {
str(key): count
for key, count in db.execute(
f"SELECT {column}, COUNT(*) FROM positions GROUP BY {column}"
)
}
def quantile(db: sqlite3.Connection, column: str, q: float, total: int) -> int:
offset = max(0, min(total - 1, round((total - 1) * q)))
return db.execute(
f"SELECT {column} FROM positions ORDER BY {column} LIMIT 1 OFFSET ?",
(offset,),
).fetchone()[0]
def numeric_stats(db: sqlite3.Connection, column: str, total: int) -> dict[str, float]:
mean, mean_square, minimum, maximum = db.execute(
f"SELECT AVG({column}), AVG({column} * {column}), "
f"MIN({column}), MAX({column}) FROM positions"
).fetchone()
variance = max(0.0, mean_square - mean * mean)
return {
"min": minimum,
"p10": quantile(db, column, 0.10, total),
"median": quantile(db, column, 0.50, total),
"p90": quantile(db, column, 0.90, total),
"max": maximum,
"mean": round(mean, 4),
"stdev": round(math.sqrt(variance), 4),
}
def normalized_entropy(counts: list[int]) -> float:
total = sum(counts)
probabilities = [count / total for count in counts if count]
entropy = -sum(value * math.log(value) for value in probabilities)
return entropy / math.log(len(counts))
def analyze_database(path: Path) -> dict[str, object]:
db = sqlite3.connect(f"file:{path}?mode=ro&immutable=1", uri=True)
total = db.execute("SELECT COUNT(*) FROM positions").fetchone()[0]
if total == 0:
raise RuntimeError("dataset is empty")
phases_raw = grouped(db, "phase")
phases = {PHASE_NAMES[int(key)]: value for key, value in phases_raw.items()}
results = grouped(db, "result")
sides = grouped(db, "side_to_move")
splits = grouped(db, "source_split")
legal = numeric_stats(db, "legal_moves", total)
pieces = numeric_stats(db, "piece_count", total)
balance = numeric_stats(db, "material_balance", total)
no_castling = db.execute(
"SELECT COUNT(*) FROM positions WHERE castling_mask=0"
).fetchone()[0]
with_castling = total - no_castling
checks = db.execute("SELECT COUNT(*) FROM positions WHERE in_check=1").fetchone()[0]
imbalanced = db.execute(
"SELECT COUNT(*) FROM positions WHERE ABS(material_balance)>=3"
).fetchone()[0]
min_phase_share = min(phases.values()) / total
known_results = [results.get(key, 0) for key in ("1-0", "1/2-1/2", "0-1")]
min_result_share = min(known_results) / max(1, sum(known_results))
white_share = int(sides.get("1", 0)) / total
checks_map = {
"at_least_1_5m_positions": total >= 1_500_000,
"phase_min_share_at_least_15pct": min_phase_share >= 0.15,
"phase_entropy_at_least_0_85": normalized_entropy(list(phases.values())) >= 0.85,
"result_min_share_at_least_20pct": min_result_share >= 0.20,
"side_to_move_between_47_and_53pct_white": 0.47 <= white_share <= 0.53,
"legal_move_stdev_at_least_8": legal["stdev"] >= 8,
"legal_move_p10_at_most_22": legal["p10"] <= 22,
"legal_move_p90_at_least_38": legal["p90"] >= 38,
"piece_count_stdev_at_least_5": pieces["stdev"] >= 5,
"material_imbalance_at_least_15pct": imbalanced / total >= 0.15,
"both_castling_states_at_least_10pct": min(no_castling, with_castling) / total
>= 0.10,
"checks_at_least_1pct": checks / total >= 0.01,
}
metadata = dict(db.execute("SELECT key, value FROM metadata"))
report = {
"format": metadata.get("format"),
"database": str(path),
"positions": total,
"database_bytes": path.stat().st_size,
"distributions": {
"phase": phases,
"result": results,
"side_to_move": {"black": sides.get("0", 0), "white": sides.get("1", 0)},
"source_split": splits,
"with_castling_rights": with_castling,
"without_castling_rights": no_castling,
"in_check": checks,
"material_imbalance_abs_ge_3": imbalanced,
},
"numeric": {
"legal_moves": legal,
"piece_count": pieces,
"material_balance_white_minus_black": balance,
},
"normalized_phase_entropy": round(
normalized_entropy(list(phases.values())), 6
),
"thresholds": checks_map,
"high_variance": all(checks_map.values()),
"metadata": metadata,
}
db.close()
return report
def analyze(args: argparse.Namespace) -> None:
report = analyze_database(Path(args.database).resolve())
rendered = json.dumps(report, indent=2, sort_keys=True)
print(rendered)
if args.report:
Path(args.report).write_text(rendered + "\n", encoding="utf-8")
def sample(args: argparse.Namespace) -> None:
path = Path(args.database).resolve()
db = sqlite3.connect(f"file:{path}?mode=ro&immutable=1", uri=True)
if args.id is not None:
row = db.execute(
"SELECT id, fen, phase, result FROM positions WHERE id=?", (args.id,)
).fetchone()
else:
key = random.SystemRandom().randrange(1 << 63)
row = db.execute(
"SELECT id, fen, phase, result FROM positions "
"WHERE random_key>=? ORDER BY random_key LIMIT 1",
(key,),
).fetchone()
if row is None:
row = db.execute(
"SELECT id, fen, phase, result FROM positions ORDER BY random_key LIMIT 1"
).fetchone()
db.close()
if row is None:
raise RuntimeError("position not found")
print(
json.dumps(
{"id": row[0], "fen": row[1], "phase": PHASE_NAMES[row[2]], "result": row[3]},
separators=(",", ":"),
)
)
def parser() -> argparse.ArgumentParser:
root = argparse.ArgumentParser(description=__doc__)
commands = root.add_subparsers(dest="command", required=True)
extract_cmd = commands.add_parser("extract", help="stream PGNs into VPD1")
extract_cmd.add_argument("--source", required=True)
extract_cmd.add_argument("--output", required=True)
extract_cmd.add_argument("--target", type=int, default=DEFAULT_TARGET)
extract_cmd.add_argument("--seed", type=int, default=91)
extract_cmd.add_argument("--commit-every", type=int, default=10_000)
extract_cmd.add_argument("--progress-every", type=int, default=10_000)
extract_cmd.set_defaults(func=extract)
analyze_cmd = commands.add_parser("analyze", help="calculate variance")
analyze_cmd.add_argument("database")
analyze_cmd.add_argument("--report")
analyze_cmd.set_defaults(func=analyze)
sample_cmd = commands.add_parser("sample", help="return one board immediately")
sample_cmd.add_argument("database")
sample_cmd.add_argument("--id", type=int)
sample_cmd.set_defaults(func=sample)
return root
if __name__ == "__main__":
arguments = parser().parse_args()
arguments.func(arguments)
|