zero-evaluator / scripts /vpd_to_parquet.py
Pawitt's picture
Publish high-variance 1.5M chess position Parquet dataset
5f87c14 verified
Raw
History Blame Contribute Delete
7.37 kB
#!/usr/bin/env python3
"""Convert a VPD1 SQLite database to a partitioned Parquet dataset."""
from __future__ import annotations
import argparse
import hashlib
import json
import sqlite3
import time
from pathlib import Path
import pyarrow as pa
import pyarrow.dataset as pads
import pyarrow.parquet as pq
PHASE_NAMES = {0: "opening", 1: "middlegame", 2: "endgame"}
COLUMNS = [
"id",
"random_key",
"fen",
"source_member",
"game_number",
"ply",
"result",
"side_to_move",
"piece_count",
"non_pawn_material",
"material_balance",
"legal_moves",
"in_check",
"castling_mask",
"halfmove_clock",
]
SCHEMA = pa.schema(
[
("id", pa.int64()),
("random_key", pa.int64()),
("fen", pa.string()),
("source_member", pa.string()),
("game_number", pa.int64()),
("ply", pa.int16()),
("result", pa.string()),
("side_to_move", pa.int8()),
("piece_count", pa.int8()),
("non_pawn_material", pa.int16()),
("material_balance", pa.int16()),
("legal_moves", pa.int16()),
("in_check", pa.bool_()),
("castling_mask", pa.int8()),
("halfmove_clock", pa.int16()),
]
)
def sha256(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as source:
while chunk := source.read(8 * 1024 * 1024):
digest.update(chunk)
return digest.hexdigest()
def table_from_rows(rows: list[tuple[object, ...]], schema: pa.Schema) -> pa.Table:
arrays = []
for index, field in enumerate(schema):
values = [row[index] for row in rows]
if pa.types.is_boolean(field.type):
values = [bool(value) for value in values]
arrays.append(pa.array(values, type=field.type))
return pa.Table.from_arrays(arrays, schema=schema)
def convert(args: argparse.Namespace) -> None:
source = Path(args.input).resolve()
output = Path(args.output).resolve()
if output.exists() and any(output.iterdir()):
raise RuntimeError(f"output directory is not empty: {output}")
output.mkdir(parents=True, exist_ok=True)
db = sqlite3.connect(f"file:{source}?mode=ro&immutable=1", uri=True)
metadata = dict(db.execute("SELECT key, value FROM metadata"))
schema = SCHEMA.with_metadata(
{
b"vpd_format": metadata.get("format", "unknown").encode(),
b"source_sha256": sha256(source).encode(),
b"fen_fullmove_normalization": metadata.get(
"fen_fullmove_normalization", "unknown"
).encode(),
}
)
source_total = db.execute("SELECT COUNT(*) FROM positions").fetchone()[0]
splits = [
row[0]
for row in db.execute(
"SELECT DISTINCT source_split FROM positions ORDER BY source_split"
)
]
manifest: dict[str, object] = {
"format": "VPD1-Parquet",
"source": str(source),
"source_sha256": sha256(source),
"compression": args.compression,
"compression_level": args.compression_level,
"row_group_size": args.row_group_size,
"partitioning": ["source_split", "phase"],
"rows": 0,
"partitions": [],
}
started = time.monotonic()
for split in splits:
for phase_id, phase_name in PHASE_NAMES.items():
count = db.execute(
"SELECT COUNT(*) FROM positions WHERE source_split=? AND phase=?",
(split, phase_id),
).fetchone()[0]
if not count:
continue
partition_dir = output / f"source_split={split}" / f"phase={phase_name}"
partition_dir.mkdir(parents=True, exist_ok=True)
parquet_path = partition_dir / "positions.parquet"
query = (
f"SELECT {', '.join(COLUMNS)} FROM positions "
"WHERE source_split=? AND phase=? ORDER BY id"
)
cursor = db.execute(query, (split, phase_id))
written = 0
row_groups = 0
min_id = None
max_id = None
with pq.ParquetWriter(
parquet_path,
schema,
compression=args.compression,
compression_level=args.compression_level,
use_dictionary=["source_member", "result"],
write_statistics=True,
) as writer:
while rows := cursor.fetchmany(args.row_group_size):
table = table_from_rows(rows, schema)
writer.write_table(table, row_group_size=len(rows))
written += len(rows)
row_groups += 1
min_id = rows[0][0] if min_id is None else min_id
max_id = rows[-1][0]
if written != count:
raise RuntimeError(
f"partition count mismatch for {split}/{phase_name}: "
f"expected {count}, wrote {written}"
)
manifest["rows"] += written
manifest["partitions"].append(
{
"source_split": split,
"phase": phase_name,
"rows": written,
"row_groups": row_groups,
"min_id": min_id,
"max_id": max_id,
"bytes": parquet_path.stat().st_size,
"file": str(parquet_path.relative_to(output)),
"sha256": sha256(parquet_path),
}
)
print(
f"wrote {split}/{phase_name}: {written:,} rows, "
f"{parquet_path.stat().st_size / (1024 * 1024):.1f} MiB",
flush=True,
)
db.close()
if manifest["rows"] != source_total:
raise RuntimeError(
f"total mismatch: source has {source_total}, wrote {manifest['rows']}"
)
manifest["elapsed_seconds"] = round(time.monotonic() - started, 3)
# Leading underscore keeps the JSON sidecar out of PyArrow's default
# Parquet dataset discovery while leaving it next to the data it describes.
manifest_path = output / "_manifest.json"
manifest_path.write_text(
json.dumps(manifest, indent=2, sort_keys=True) + "\n", encoding="utf-8"
)
dataset = pads.dataset(output, format="parquet", partitioning="hive")
parquet_total = dataset.count_rows()
if parquet_total != source_total:
raise RuntimeError(
f"PyArrow validation mismatch: expected {source_total}, got {parquet_total}"
)
print(
json.dumps(
{
"rows": parquet_total,
"files": len(dataset.files),
"manifest": str(manifest_path),
"elapsed_seconds": manifest["elapsed_seconds"],
},
indent=2,
)
)
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--input", required=True)
parser.add_argument("--output", required=True)
parser.add_argument("--row-group-size", type=int, default=65_536)
parser.add_argument("--compression", default="zstd")
parser.add_argument("--compression-level", type=int, default=6)
convert(parser.parse_args())
if __name__ == "__main__":
main()