Pawitt commited on
Commit
5f87c14
·
verified ·
1 Parent(s): 8eab099

Publish high-variance 1.5M chess position Parquet dataset

Browse files

Adds six train/test and game-phase Parquet partitions, checksums, variance audit, documentation, and reproducibility scripts.

FORMAT.md ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # VPD1: Vex Position Dataset
2
+
3
+ VPD1 is an indexed SQLite container for independent chess positions. Its file
4
+ extension is `.vpd`. It is designed for static teacher labeling, where a
5
+ consumer needs one complete board immediately without replaying a game.
6
+
7
+ ## Position identity
8
+
9
+ Each row stores a legal six-field FEN. The fullmove number is normalized to
10
+ `1`; it does not affect board state or lc0 evaluation. The halfmove clock is
11
+ preserved because it affects draw rules. En-passant state and castling rights
12
+ are preserved.
13
+
14
+ The `fen` column is unique, so duplicate positions from different games are
15
+ removed.
16
+
17
+ ## Tables
18
+
19
+ `metadata(key, value)` records provenance, format version, sampling seed,
20
+ target size, quotas, progress, and completion information.
21
+
22
+ `positions` contains:
23
+
24
+ | Column | Meaning |
25
+ | --- | --- |
26
+ | `id` | Integer row identifier |
27
+ | `random_key` | Indexed deterministic 63-bit key for fast random sampling |
28
+ | `fen` | Normalized six-field FEN |
29
+ | `source_split` | Original train/test split if present |
30
+ | `source_member` | PGN member inside the source archive |
31
+ | `game_number` | Sequential source-game number |
32
+ | `ply` | Ply at which the position was sampled |
33
+ | `result` | Source game result; metadata, not a static WDL label |
34
+ | `side_to_move` | `1` for White, `0` for Black |
35
+ | `phase` | `0` opening, `1` middlegame, `2` endgame |
36
+ | `piece_count` | Occupied squares |
37
+ | `non_pawn_material` | Combined N/B/R/Q material in pawn units |
38
+ | `material_balance` | White material minus Black material |
39
+ | `legal_moves` | Legal move count |
40
+ | `in_check` | Whether the side to move is in check |
41
+ | `castling_mask` | KQkq availability as four bits |
42
+ | `halfmove_clock` | Fifty-move-rule clock |
43
+
44
+ ## Immediate access
45
+
46
+ By row identifier:
47
+
48
+ ```sql
49
+ SELECT fen FROM positions WHERE id = 12345;
50
+ ```
51
+
52
+ Near-constant-time random access uses the indexed `random_key`:
53
+
54
+ ```sql
55
+ SELECT fen
56
+ FROM positions
57
+ WHERE random_key >= :random_63_bit_integer
58
+ ORDER BY random_key
59
+ LIMIT 1;
60
+ ```
61
+
62
+ The supplied `vpd.py sample` command implements wraparound when the random key
63
+ is above the largest stored key.
64
+
65
+ ## Parquet derivative
66
+
67
+ `vpd_to_parquet.py` converts the same rows into a columnar training dataset.
68
+ The output uses Hive directories for `source_split` and `phase`; those two
69
+ columns are therefore encoded in paths instead of duplicated inside each
70
+ file. Each remaining VPD1 column retains its meaning, except `phase` is exposed
71
+ as the strings `opening`, `middlegame`, and `endgame`.
72
+
73
+ Files use Zstandard compression and 65,536-row groups. `_manifest.json`
74
+ contains the source database checksum plus per-file row counts, sizes, row
75
+ groups, ID bounds, and checksums. This representation is optimized for batch
76
+ and filtered scans; retain VPD1 SQLite for indexed single-position lookup.
77
+
78
+ ## Sampling policy
79
+
80
+ At most one position per game and phase is selected with reservoir sampling.
81
+ The default 1.5-million-position build uses fixed phase quotas:
82
+
83
+ - 15% opening
84
+ - 60% middlegame
85
+ - 25% endgame
86
+
87
+ This reduces correlation between adjacent plies and prevents ordinary
88
+ middlegames from overwhelming openings and endgames.
89
+
90
+ Phase classification is deterministic:
91
+
92
+ - opening: ply 20 or earlier with at least 50 combined non-pawn material;
93
+ - endgame: at most 20 combined non-pawn material or at most 12 pieces;
94
+ - middlegame: everything else.
95
+
96
+ ## Variance contract
97
+
98
+ A database is marked `high_variance=true` only if every declared threshold in
99
+ the JSON report passes. The checks cover corpus size, phase entropy, minimum
100
+ phase and result shares, side-to-move balance, legal-move spread, piece-count
101
+ spread, material imbalance, castling-state coverage, and positions in check.
README.md CHANGED
@@ -1,8 +1,106 @@
1
  ---
2
  license: mit
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  ---
4
 
5
- The dataset consist of millions of chess games, with high variance.
6
- suitable for engine training.
7
 
8
- Additionally it may conssit the depth zero wdl evaluation by lc0. depth zero imply no tree search and a immediate evaluation of board.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
  license: mit
3
+ pretty_name: Zero Evaluator High-Variance Chess Positions
4
+ language:
5
+ - en
6
+ tags:
7
+ - chess
8
+ - leela-chess-zero
9
+ - parquet
10
+ - fen
11
+ size_categories:
12
+ - 1M<n<10M
13
+ configs:
14
+ - config_name: default
15
+ data_files:
16
+ - split: train
17
+ path: data/source_split=train/**/*.parquet
18
+ - split: test
19
+ path: data/source_split=test/**/*.parquet
20
  ---
21
 
22
+ # Zero Evaluator High-Variance Chess Positions
 
23
 
24
+ This dataset contains **1,509,201 unique chess positions** extracted from Leela
25
+ Chess Zero's published CCRL standard corpus. Positions are stored as normalized
26
+ six-field FEN records for immediate board reconstruction without replaying a
27
+ game.
28
+
29
+ The selection deliberately balances opening, middlegame, and endgame coverage
30
+ and retains the original source train/test split. The complete variance audit
31
+ is in `variance-report.json` and `RESULTS.md`.
32
+
33
+ ## Data layout
34
+
35
+ The release consists of six Zstandard-compressed Parquet files partitioned by:
36
+
37
+ - `source_split`: `train` or `test`
38
+ - `phase`: `opening`, `middlegame`, or `endgame`
39
+
40
+ | Split | Opening | Middlegame | Endgame | Total |
41
+ | --- | ---: | ---: | ---: | ---: |
42
+ | Train | 182,691 | 723,841 | 295,196 | 1,201,728 |
43
+ | Test | 51,510 | 176,159 | 79,804 | 307,473 |
44
+ | Total | 234,201 | 900,000 | 375,000 | 1,509,201 |
45
+
46
+ `data/_manifest.json` contains file sizes, row counts, ID bounds, and SHA-256
47
+ checksums.
48
+
49
+ ## Load the dataset
50
+
51
+ Hugging Face Datasets:
52
+
53
+ ```python
54
+ from datasets import load_dataset
55
+
56
+ positions = load_dataset("Pawitt/zero-evaluator")
57
+ print(positions["train"][0]["fen"])
58
+ ```
59
+
60
+ For Hive partition columns and streaming Arrow batches, use PyArrow directly:
61
+
62
+ ```python
63
+ import pyarrow.dataset as ds
64
+
65
+ positions = ds.dataset(
66
+ "data",
67
+ format="parquet",
68
+ partitioning="hive",
69
+ )
70
+ scanner = positions.scanner(
71
+ filter=ds.field("source_split") == "train",
72
+ columns=["fen", "result", "phase"],
73
+ batch_size=8192,
74
+ )
75
+ for batch in scanner.to_batches():
76
+ pass
77
+ ```
78
+
79
+ When downloading from the Hub first, point `ds.dataset` at the downloaded
80
+ `data/` directory.
81
+
82
+ ## Columns
83
+
84
+ Each record includes normalized `fen`, source-game provenance, ply and result,
85
+ side to move, piece and material statistics, legal-move count, check state,
86
+ castling mask, and halfmove clock. See `FORMAT.md` for exact semantics.
87
+
88
+ The source-game `result` is provenance metadata. It is **not** an lc0
89
+ depth-zero WDL label. Static WDL values can be added by running the positions
90
+ through an lc0 zero-search evaluation pass.
91
+
92
+ ## Validation
93
+
94
+ - All 1,509,201 source rows were reproduced in Parquet.
95
+ - All six partition counts match the source database.
96
+ - All 26 row groups use Zstandard compression.
97
+ - All six file checksums match the manifest.
98
+ - 6,000 sampled FEN records were reconstructed successfully with python-chess.
99
+
100
+ ## Source
101
+
102
+ The source is the [Leela Chess Zero standard CCRL dataset](https://lczero.org/blog/2018/09/a-standard-dataset/),
103
+ published as 2.5 million CCRL 40/40 and 40/4 engine games with an original
104
+ 80/20 train/test split.
105
+
106
+ The extraction and conversion scripts are included for reproducibility.
RESULTS.md ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Completed Dataset Results
2
+
3
+ ## Artifacts
4
+
5
+ - Dataset: `data/ccrl-high-variance-1p5m.vpd`
6
+ - Training dataset: `data/ccrl-high-variance-1p5m.parquet/`
7
+ - Parquet manifest: `data/ccrl-high-variance-1p5m.parquet/_manifest.json`
8
+ - Variance report: `data/variance-report.json`
9
+ - Source archive: `source/ccrl-pgn.tar.bz2`
10
+ - Extractor and reader: `vpd.py`
11
+ - Format specification: `FORMAT.md`
12
+
13
+ ## Provenance
14
+
15
+ The source is Leela Chess Zero's published CCRL standard dataset: 2.5 million
16
+ CCRL 40/40 and 40/4 engine games with an 80/20 train/test split. Extraction
17
+ used 910,462 source games and completed with zero PGN parse errors.
18
+
19
+ The final VPD1 database contains 1,509,201 unique normalized FEN positions and
20
+ is 438,558,720 bytes.
21
+
22
+ The Parquet derivative contains the same 1,509,201 rows in six Hive-style
23
+ `source_split`/`phase` partitions. It is 52 MiB on disk, uses Zstandard level 6
24
+ compression, and has 26 row groups capped at 65,536 rows.
25
+
26
+ ## Variance result
27
+
28
+ Overall result: **HIGH VARIANCE — PASS**
29
+
30
+ Every declared threshold in `data/variance-report.json` passed.
31
+
32
+ | Dimension | Result |
33
+ | --- | ---: |
34
+ | Opening | 234,201 (15.52%) |
35
+ | Middlegame | 900,000 (59.63%) |
36
+ | Endgame | 375,000 (24.85%) |
37
+ | Normalized phase entropy | 0.858704 |
38
+ | White wins | 570,602 (37.81%) |
39
+ | Draws | 481,726 (31.92%) |
40
+ | Black wins | 456,873 (30.27%) |
41
+ | White to move | 758,019 (50.23%) |
42
+ | Black to move | 751,182 (49.77%) |
43
+ | Positions in check | 103,519 (6.86%) |
44
+ | Positions with castling rights | 289,814 (19.20%) |
45
+ | Positions without castling rights | 1,219,387 (80.80%) |
46
+ | Material imbalance of at least 3 | 234,018 (15.51%) |
47
+
48
+ Legal move counts span 0–87, with p10 12, median 33, p90 44, and standard
49
+ deviation 12.064. Piece counts span 2–32, with p10 10, median 21, p90 30, and
50
+ standard deviation 7.5146.
51
+
52
+ ## Validation
53
+
54
+ - SQLite `PRAGMA integrity_check`: `ok`
55
+ - Random FEN validation: 1,000/1,000 valid
56
+ - Indexed random retrieval: 1,000 queries in 4.404 ms
57
+ - Mean in-process lookup latency: 0.004404 ms per board
58
+ - Parquet row-count validation: 1,509,201/1,509,201
59
+ - Parquet partition-count validation: 6/6 exact matches
60
+ - Parquet FEN validation sample: 6,000/6,000 valid
61
+ - Parquet file checksums: 6/6 match `_manifest.json`
62
+ - Parquet compression audit: all 26 row groups use Zstandard
63
+ - Source archive SHA-256:
64
+ `5f4d7ec86a99ba56fd3e46b1eb35f3ae109890bc77fecc3e605a6174ea717e76`
65
+ - Dataset SHA-256:
66
+ `2f3af2973d1e4cb2d7e0d54e7e7a0f12def44d982915df0c9cab1735f6b138cc`
67
+ - Report SHA-256:
68
+ `759699d7bc704fd265524a6df320c1a0c925f902e29a60b83366d987d3ab507e`
69
+
70
+ ## Retrieve one board
71
+
72
+ ```bash
73
+ cd /Users/pawit/Documents/vexilon/tmp/vex-position-dataset
74
+ PYTHONDONTWRITEBYTECODE=1 .venv/bin/python vpd.py sample \
75
+ data/ccrl-high-variance-1p5m.vpd
76
+ ```
77
+
78
+ Example output:
79
+
80
+ ```json
81
+ {"id":257499,"fen":"8/4p3/p6p/1p3k1K/1n3P2/1P4P1/r3RN2/8 w - - 0 1","phase":"endgame","result":"1-0"}
82
+ ```
83
+
84
+ The source `result` is provenance metadata. It is not the depth-zero static WDL
85
+ label; lc0 can add that label in a subsequent pass.
data/_manifest.json ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "compression": "zstd",
3
+ "compression_level": 6,
4
+ "elapsed_seconds": 4.922,
5
+ "format": "VPD1-Parquet",
6
+ "partitioning": [
7
+ "source_split",
8
+ "phase"
9
+ ],
10
+ "partitions": [
11
+ {
12
+ "bytes": 1585824,
13
+ "file": "source_split=test/phase=opening/positions.parquet",
14
+ "max_id": 1406490,
15
+ "min_id": 1,
16
+ "phase": "opening",
17
+ "row_groups": 1,
18
+ "rows": 51510,
19
+ "sha256": "57fb6ae73a7b001f845032e833efcba73724d6cb13336ee73e75d2f22fcdff51",
20
+ "source_split": "test"
21
+ },
22
+ {
23
+ "bytes": 6721156,
24
+ "file": "source_split=test/phase=middlegame/positions.parquet",
25
+ "max_id": 1506802,
26
+ "min_id": 2,
27
+ "phase": "middlegame",
28
+ "row_groups": 3,
29
+ "rows": 176159,
30
+ "sha256": "8499cd54cecf657a5fc7569d45f2dabf9385a2526f47030d39e9499e47e7e0ad",
31
+ "source_split": "test"
32
+ },
33
+ {
34
+ "bytes": 2606046,
35
+ "file": "source_split=test/phase=endgame/positions.parquet",
36
+ "max_id": 969894,
37
+ "min_id": 3,
38
+ "phase": "endgame",
39
+ "row_groups": 2,
40
+ "rows": 79804,
41
+ "sha256": "29996caf5229cf0ef9bb860c1495061047c03084da627f3d8343a8f827f12e86",
42
+ "source_split": "test"
43
+ },
44
+ {
45
+ "bytes": 5593410,
46
+ "file": "source_split=train/phase=opening/positions.parquet",
47
+ "max_id": 1430066,
48
+ "min_id": 5230,
49
+ "phase": "opening",
50
+ "row_groups": 3,
51
+ "rows": 182691,
52
+ "sha256": "51fe5555204e9802a738dfcb89b8b0ffa409afdfcb2d825d1a5fd11dfcc2e536",
53
+ "source_split": "train"
54
+ },
55
+ {
56
+ "bytes": 27538546,
57
+ "file": "source_split=train/phase=middlegame/positions.parquet",
58
+ "max_id": 1509201,
59
+ "min_id": 5228,
60
+ "phase": "middlegame",
61
+ "row_groups": 12,
62
+ "rows": 723841,
63
+ "sha256": "3bcc0554d9ff4d5bde9de114e76b6c44c9e15864e87c9e52111890058a43f356",
64
+ "source_split": "train"
65
+ },
66
+ {
67
+ "bytes": 9598882,
68
+ "file": "source_split=train/phase=endgame/positions.parquet",
69
+ "max_id": 978071,
70
+ "min_id": 5229,
71
+ "phase": "endgame",
72
+ "row_groups": 5,
73
+ "rows": 295196,
74
+ "sha256": "752da7ca0dc00288b564926f89413678101dff90ee1be8c24f37c24d44df0020",
75
+ "source_split": "train"
76
+ }
77
+ ],
78
+ "row_group_size": 65536,
79
+ "rows": 1509201,
80
+ "source": "/Users/pawit/Documents/vexilon/tmp/vex-position-dataset/data/ccrl-high-variance-1p5m.vpd",
81
+ "source_sha256": "2f3af2973d1e4cb2d7e0d54e7e7a0f12def44d982915df0c9cab1735f6b138cc"
82
+ }
data/source_split=test/phase=endgame/positions.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:29996caf5229cf0ef9bb860c1495061047c03084da627f3d8343a8f827f12e86
3
+ size 2606046
data/source_split=test/phase=middlegame/positions.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8499cd54cecf657a5fc7569d45f2dabf9385a2526f47030d39e9499e47e7e0ad
3
+ size 6721156
data/source_split=test/phase=opening/positions.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:57fb6ae73a7b001f845032e833efcba73724d6cb13336ee73e75d2f22fcdff51
3
+ size 1585824
data/source_split=train/phase=endgame/positions.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:752da7ca0dc00288b564926f89413678101dff90ee1be8c24f37c24d44df0020
3
+ size 9598882
data/source_split=train/phase=middlegame/positions.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3bcc0554d9ff4d5bde9de114e76b6c44c9e15864e87c9e52111890058a43f356
3
+ size 27538546
data/source_split=train/phase=opening/positions.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:51fe5555204e9802a738dfcb89b8b0ffa409afdfcb2d825d1a5fd11dfcc2e536
3
+ size 5593410
requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ python-chess==1.999
2
+ pyarrow==25.0.1
scripts/vpd.py ADDED
@@ -0,0 +1,559 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Build, analyze, and sample a Vex Position Dataset (VPD1) database."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import hashlib
8
+ import io
9
+ import json
10
+ import math
11
+ import random
12
+ import sqlite3
13
+ import statistics
14
+ import sys
15
+ import tarfile
16
+ import time
17
+ from pathlib import Path
18
+
19
+ import chess
20
+ import chess.pgn
21
+
22
+
23
+ FORMAT_VERSION = "VPD1"
24
+ DEFAULT_TARGET = 1_500_000
25
+ PHASE_NAMES = {0: "opening", 1: "middlegame", 2: "endgame"}
26
+ PHASE_IDS = {name: value for value, name in PHASE_NAMES.items()}
27
+ PIECE_VALUES = {
28
+ chess.PAWN: 1,
29
+ chess.KNIGHT: 3,
30
+ chess.BISHOP: 3,
31
+ chess.ROOK: 5,
32
+ chess.QUEEN: 9,
33
+ }
34
+
35
+
36
+ class NonSeekableReader(io.RawIOBase):
37
+ """Adapt tarfile's streaming member object for TextIOWrapper on Python 3.14."""
38
+
39
+ def __init__(self, source: object) -> None:
40
+ self.source = source
41
+
42
+ def readable(self) -> bool:
43
+ return True
44
+
45
+ def seekable(self) -> bool:
46
+ return False
47
+
48
+ def readinto(self, buffer: bytearray) -> int:
49
+ chunk = self.source.read(len(buffer))
50
+ if not chunk:
51
+ return 0
52
+ buffer[: len(chunk)] = chunk
53
+ return len(chunk)
54
+
55
+
56
+ def connect(path: Path) -> sqlite3.Connection:
57
+ db = sqlite3.connect(path)
58
+ db.execute("PRAGMA journal_mode=WAL")
59
+ db.execute("PRAGMA synchronous=NORMAL")
60
+ db.execute("PRAGMA temp_store=MEMORY")
61
+ db.execute("PRAGMA cache_size=-262144")
62
+ db.execute("PRAGMA foreign_keys=ON")
63
+ return db
64
+
65
+
66
+ def initialize(db: sqlite3.Connection) -> None:
67
+ db.executescript(
68
+ """
69
+ CREATE TABLE IF NOT EXISTS metadata (
70
+ key TEXT PRIMARY KEY,
71
+ value TEXT NOT NULL
72
+ ) WITHOUT ROWID;
73
+
74
+ CREATE TABLE IF NOT EXISTS positions (
75
+ id INTEGER PRIMARY KEY,
76
+ random_key INTEGER NOT NULL UNIQUE,
77
+ fen TEXT NOT NULL UNIQUE,
78
+ source_split TEXT NOT NULL,
79
+ source_member TEXT NOT NULL,
80
+ game_number INTEGER NOT NULL,
81
+ ply INTEGER NOT NULL,
82
+ result TEXT NOT NULL,
83
+ side_to_move INTEGER NOT NULL CHECK(side_to_move IN (0, 1)),
84
+ phase INTEGER NOT NULL CHECK(phase BETWEEN 0 AND 2),
85
+ piece_count INTEGER NOT NULL,
86
+ non_pawn_material INTEGER NOT NULL,
87
+ material_balance INTEGER NOT NULL,
88
+ legal_moves INTEGER NOT NULL,
89
+ in_check INTEGER NOT NULL CHECK(in_check IN (0, 1)),
90
+ castling_mask INTEGER NOT NULL CHECK(castling_mask BETWEEN 0 AND 15),
91
+ halfmove_clock INTEGER NOT NULL
92
+ );
93
+
94
+ CREATE INDEX IF NOT EXISTS positions_phase ON positions(phase);
95
+ CREATE INDEX IF NOT EXISTS positions_result ON positions(result);
96
+ CREATE INDEX IF NOT EXISTS positions_legal_moves ON positions(legal_moves);
97
+ CREATE INDEX IF NOT EXISTS positions_piece_count ON positions(piece_count);
98
+ CREATE INDEX IF NOT EXISTS positions_material_balance
99
+ ON positions(material_balance);
100
+ CREATE INDEX IF NOT EXISTS positions_split ON positions(source_split);
101
+ """
102
+ )
103
+ set_metadata(db, "format", FORMAT_VERSION)
104
+ set_metadata(db, "fen_fullmove_normalization", "1")
105
+
106
+
107
+ def set_metadata(db: sqlite3.Connection, key: str, value: object) -> None:
108
+ db.execute(
109
+ "INSERT INTO metadata(key, value) VALUES (?, ?) "
110
+ "ON CONFLICT(key) DO UPDATE SET value=excluded.value",
111
+ (key, str(value)),
112
+ )
113
+
114
+
115
+ def normalized_fen(board: chess.Board) -> str:
116
+ fields = board.fen(en_passant="fen").split()
117
+ fields[5] = "1"
118
+ return " ".join(fields)
119
+
120
+
121
+ def phase_of(board: chess.Board, ply: int) -> int:
122
+ non_pawn = sum(
123
+ PIECE_VALUES[piece_type]
124
+ * (
125
+ len(board.pieces(piece_type, chess.WHITE))
126
+ + len(board.pieces(piece_type, chess.BLACK))
127
+ )
128
+ for piece_type in (chess.KNIGHT, chess.BISHOP, chess.ROOK, chess.QUEEN)
129
+ )
130
+ piece_count = chess.popcount(board.occupied)
131
+ if ply <= 20 and non_pawn >= 50:
132
+ return PHASE_IDS["opening"]
133
+ if non_pawn <= 20 or piece_count <= 12:
134
+ return PHASE_IDS["endgame"]
135
+ return PHASE_IDS["middlegame"]
136
+
137
+
138
+ def castling_mask(board: chess.Board) -> int:
139
+ return (
140
+ int(board.has_kingside_castling_rights(chess.WHITE))
141
+ | (int(board.has_queenside_castling_rights(chess.WHITE)) << 1)
142
+ | (int(board.has_kingside_castling_rights(chess.BLACK)) << 2)
143
+ | (int(board.has_queenside_castling_rights(chess.BLACK)) << 3)
144
+ )
145
+
146
+
147
+ def material(board: chess.Board) -> tuple[int, int]:
148
+ white = sum(
149
+ PIECE_VALUES[piece_type] * len(board.pieces(piece_type, chess.WHITE))
150
+ for piece_type in PIECE_VALUES
151
+ )
152
+ black = sum(
153
+ PIECE_VALUES[piece_type] * len(board.pieces(piece_type, chess.BLACK))
154
+ for piece_type in PIECE_VALUES
155
+ )
156
+ non_pawn = sum(
157
+ PIECE_VALUES[piece_type]
158
+ * (
159
+ len(board.pieces(piece_type, chess.WHITE))
160
+ + len(board.pieces(piece_type, chess.BLACK))
161
+ )
162
+ for piece_type in (chess.KNIGHT, chess.BISHOP, chess.ROOK, chess.QUEEN)
163
+ )
164
+ return white - black, non_pawn
165
+
166
+
167
+ def random_key(fen: str) -> int:
168
+ raw = hashlib.blake2b(fen.encode("ascii"), digest_size=8).digest()
169
+ return int.from_bytes(raw, "big") & ((1 << 63) - 1)
170
+
171
+
172
+ def position_record(
173
+ board: chess.Board,
174
+ source_split: str,
175
+ source_member: str,
176
+ game_number: int,
177
+ ply: int,
178
+ result: str,
179
+ phase: int,
180
+ ) -> tuple[object, ...]:
181
+ fen = normalized_fen(board)
182
+ balance, non_pawn = material(board)
183
+ return (
184
+ random_key(fen),
185
+ fen,
186
+ source_split,
187
+ source_member,
188
+ game_number,
189
+ ply,
190
+ result,
191
+ int(board.turn == chess.WHITE),
192
+ phase,
193
+ chess.popcount(board.occupied),
194
+ non_pawn,
195
+ balance,
196
+ board.legal_moves.count(),
197
+ int(board.is_check()),
198
+ castling_mask(board),
199
+ board.halfmove_clock,
200
+ )
201
+
202
+
203
+ def split_for(member_name: str) -> str:
204
+ lowered = member_name.lower()
205
+ if "test" in lowered:
206
+ return "test"
207
+ if "train" in lowered:
208
+ return "train"
209
+ return "unspecified"
210
+
211
+
212
+ def make_quotas(target: int) -> dict[int, int]:
213
+ opening = round(target * 0.15)
214
+ endgame = round(target * 0.25)
215
+ return {0: opening, 1: target - opening - endgame, 2: endgame}
216
+
217
+
218
+ def current_counts(db: sqlite3.Connection) -> dict[int, int]:
219
+ counts = {phase: 0 for phase in PHASE_NAMES}
220
+ counts.update(dict(db.execute("SELECT phase, COUNT(*) FROM positions GROUP BY phase")))
221
+ return counts
222
+
223
+
224
+ def extract(args: argparse.Namespace) -> None:
225
+ source = Path(args.source).resolve()
226
+ output = Path(args.output).resolve()
227
+ output.parent.mkdir(parents=True, exist_ok=True)
228
+ db = connect(output)
229
+ initialize(db)
230
+ quotas = make_quotas(args.target)
231
+ counts = current_counts(db)
232
+ resume_row = db.execute(
233
+ "SELECT source_member FROM positions ORDER BY id DESC LIMIT 1"
234
+ ).fetchone()
235
+ resume_member = resume_row[0] if resume_row else None
236
+ games_seen = int(
237
+ db.execute("SELECT COALESCE(value, '0') FROM metadata WHERE key='games_seen'")
238
+ .fetchone()[0]
239
+ if db.execute("SELECT 1 FROM metadata WHERE key='games_seen'").fetchone()
240
+ else 0
241
+ )
242
+ candidates_attempted = int(
243
+ db.execute(
244
+ "SELECT COALESCE(value, '0') FROM metadata "
245
+ "WHERE key='candidates_attempted'"
246
+ ).fetchone()[0]
247
+ if db.execute(
248
+ "SELECT 1 FROM metadata WHERE key='candidates_attempted'"
249
+ ).fetchone()
250
+ else 0
251
+ )
252
+ parse_errors = 0
253
+ inserted_since_commit = 0
254
+ started = time.monotonic()
255
+
256
+ set_metadata(db, "source", str(source))
257
+ set_metadata(db, "target_positions", args.target)
258
+ set_metadata(db, "seed", args.seed)
259
+ set_metadata(db, "phase_quotas", json.dumps(quotas, sort_keys=True))
260
+ db.commit()
261
+
262
+ insert_sql = """
263
+ INSERT OR IGNORE INTO positions(
264
+ random_key, fen, source_split, source_member, game_number, ply,
265
+ result, side_to_move, phase, piece_count, non_pawn_material,
266
+ material_balance, legal_moves, in_check, castling_mask, halfmove_clock
267
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
268
+ """
269
+
270
+ with tarfile.open(source, mode="r|bz2") as archive:
271
+ corpus_game_number = 0
272
+ finished = False
273
+ reached_resume_member = resume_member is None
274
+ for member in archive:
275
+ if finished:
276
+ break
277
+ if not member.isfile() or not member.name.lower().endswith(".pgn"):
278
+ continue
279
+ if not reached_resume_member:
280
+ if member.name != resume_member:
281
+ continue
282
+ reached_resume_member = True
283
+ raw = archive.extractfile(member)
284
+ if raw is None:
285
+ continue
286
+ split = split_for(member.name)
287
+ buffered = io.BufferedReader(NonSeekableReader(raw))
288
+ with io.TextIOWrapper(buffered, encoding="utf-8", errors="replace") as pgn:
289
+ member_game_number = 0
290
+ while True:
291
+ try:
292
+ game = chess.pgn.read_game(pgn)
293
+ except Exception as exc: # Keep streaming past isolated bad games.
294
+ parse_errors += 1
295
+ print(f"PGN parse error in {member.name}: {exc}", file=sys.stderr)
296
+ continue
297
+ if game is None:
298
+ break
299
+ corpus_game_number += 1
300
+ member_game_number += 1
301
+ games_seen += 1
302
+ board = game.board()
303
+ result = game.headers.get("Result", "*")
304
+ reservoirs: dict[int, tuple[chess.Board, int]] = {}
305
+ phase_seen = {phase: 0 for phase in PHASE_NAMES}
306
+ game_seed = int.from_bytes(
307
+ hashlib.blake2b(
308
+ f"{args.seed}:{member.name}:{member_game_number}".encode(),
309
+ digest_size=8,
310
+ ).digest(),
311
+ "big",
312
+ )
313
+ game_rng = random.Random(game_seed)
314
+
315
+ try:
316
+ for ply, move in enumerate(game.mainline_moves(), start=1):
317
+ board.push(move)
318
+ phase = phase_of(board, ply)
319
+ if counts[phase] >= quotas[phase]:
320
+ continue
321
+ phase_seen[phase] += 1
322
+ if game_rng.randrange(phase_seen[phase]) == 0:
323
+ reservoirs[phase] = (board.copy(stack=False), ply)
324
+ except Exception:
325
+ parse_errors += 1
326
+ continue
327
+
328
+ for phase, (candidate, ply) in reservoirs.items():
329
+ if counts[phase] >= quotas[phase]:
330
+ continue
331
+ candidates_attempted += 1
332
+ cursor = db.execute(
333
+ insert_sql,
334
+ position_record(
335
+ candidate,
336
+ split,
337
+ member.name,
338
+ corpus_game_number,
339
+ ply,
340
+ result,
341
+ phase,
342
+ ),
343
+ )
344
+ if cursor.rowcount:
345
+ counts[phase] += 1
346
+ inserted_since_commit += 1
347
+
348
+ if inserted_since_commit >= args.commit_every:
349
+ set_metadata(db, "games_seen", games_seen)
350
+ set_metadata(db, "candidates_attempted", candidates_attempted)
351
+ set_metadata(db, "parse_errors", parse_errors)
352
+ db.commit()
353
+ inserted_since_commit = 0
354
+
355
+ if games_seen % args.progress_every == 0:
356
+ elapsed = max(time.monotonic() - started, 0.001)
357
+ total = sum(counts.values())
358
+ print(
359
+ f"games={games_seen:,} positions={total:,}/{args.target:,} "
360
+ f"opening={counts[0]:,} middle={counts[1]:,} "
361
+ f"endgame={counts[2]:,} rate={total / elapsed:,.0f} pos/s",
362
+ flush=True,
363
+ )
364
+
365
+ if all(counts[p] >= quotas[p] for p in quotas):
366
+ finished = True
367
+ break
368
+
369
+ set_metadata(db, "games_seen", games_seen)
370
+ set_metadata(db, "candidates_attempted", candidates_attempted)
371
+ set_metadata(db, "parse_errors", parse_errors)
372
+ set_metadata(db, "completed_unix", int(time.time()))
373
+ set_metadata(db, "position_count", sum(counts.values()))
374
+ db.commit()
375
+ db.execute("PRAGMA optimize")
376
+ db.execute("PRAGMA wal_checkpoint(TRUNCATE)")
377
+ db.close()
378
+ print(json.dumps(analyze_database(output), indent=2, sort_keys=True))
379
+
380
+
381
+ def grouped(db: sqlite3.Connection, column: str) -> dict[str, int]:
382
+ return {
383
+ str(key): count
384
+ for key, count in db.execute(
385
+ f"SELECT {column}, COUNT(*) FROM positions GROUP BY {column}"
386
+ )
387
+ }
388
+
389
+
390
+ def quantile(db: sqlite3.Connection, column: str, q: float, total: int) -> int:
391
+ offset = max(0, min(total - 1, round((total - 1) * q)))
392
+ return db.execute(
393
+ f"SELECT {column} FROM positions ORDER BY {column} LIMIT 1 OFFSET ?",
394
+ (offset,),
395
+ ).fetchone()[0]
396
+
397
+
398
+ def numeric_stats(db: sqlite3.Connection, column: str, total: int) -> dict[str, float]:
399
+ mean, mean_square, minimum, maximum = db.execute(
400
+ f"SELECT AVG({column}), AVG({column} * {column}), "
401
+ f"MIN({column}), MAX({column}) FROM positions"
402
+ ).fetchone()
403
+ variance = max(0.0, mean_square - mean * mean)
404
+ return {
405
+ "min": minimum,
406
+ "p10": quantile(db, column, 0.10, total),
407
+ "median": quantile(db, column, 0.50, total),
408
+ "p90": quantile(db, column, 0.90, total),
409
+ "max": maximum,
410
+ "mean": round(mean, 4),
411
+ "stdev": round(math.sqrt(variance), 4),
412
+ }
413
+
414
+
415
+ def normalized_entropy(counts: list[int]) -> float:
416
+ total = sum(counts)
417
+ probabilities = [count / total for count in counts if count]
418
+ entropy = -sum(value * math.log(value) for value in probabilities)
419
+ return entropy / math.log(len(counts))
420
+
421
+
422
+ def analyze_database(path: Path) -> dict[str, object]:
423
+ db = sqlite3.connect(f"file:{path}?mode=ro&immutable=1", uri=True)
424
+ total = db.execute("SELECT COUNT(*) FROM positions").fetchone()[0]
425
+ if total == 0:
426
+ raise RuntimeError("dataset is empty")
427
+ phases_raw = grouped(db, "phase")
428
+ phases = {PHASE_NAMES[int(key)]: value for key, value in phases_raw.items()}
429
+ results = grouped(db, "result")
430
+ sides = grouped(db, "side_to_move")
431
+ splits = grouped(db, "source_split")
432
+ legal = numeric_stats(db, "legal_moves", total)
433
+ pieces = numeric_stats(db, "piece_count", total)
434
+ balance = numeric_stats(db, "material_balance", total)
435
+ no_castling = db.execute(
436
+ "SELECT COUNT(*) FROM positions WHERE castling_mask=0"
437
+ ).fetchone()[0]
438
+ with_castling = total - no_castling
439
+ checks = db.execute("SELECT COUNT(*) FROM positions WHERE in_check=1").fetchone()[0]
440
+ imbalanced = db.execute(
441
+ "SELECT COUNT(*) FROM positions WHERE ABS(material_balance)>=3"
442
+ ).fetchone()[0]
443
+ min_phase_share = min(phases.values()) / total
444
+ known_results = [results.get(key, 0) for key in ("1-0", "1/2-1/2", "0-1")]
445
+ min_result_share = min(known_results) / max(1, sum(known_results))
446
+ white_share = int(sides.get("1", 0)) / total
447
+
448
+ checks_map = {
449
+ "at_least_1_5m_positions": total >= 1_500_000,
450
+ "phase_min_share_at_least_15pct": min_phase_share >= 0.15,
451
+ "phase_entropy_at_least_0_85": normalized_entropy(list(phases.values())) >= 0.85,
452
+ "result_min_share_at_least_20pct": min_result_share >= 0.20,
453
+ "side_to_move_between_47_and_53pct_white": 0.47 <= white_share <= 0.53,
454
+ "legal_move_stdev_at_least_8": legal["stdev"] >= 8,
455
+ "legal_move_p10_at_most_22": legal["p10"] <= 22,
456
+ "legal_move_p90_at_least_38": legal["p90"] >= 38,
457
+ "piece_count_stdev_at_least_5": pieces["stdev"] >= 5,
458
+ "material_imbalance_at_least_15pct": imbalanced / total >= 0.15,
459
+ "both_castling_states_at_least_10pct": min(no_castling, with_castling) / total
460
+ >= 0.10,
461
+ "checks_at_least_1pct": checks / total >= 0.01,
462
+ }
463
+ metadata = dict(db.execute("SELECT key, value FROM metadata"))
464
+ report = {
465
+ "format": metadata.get("format"),
466
+ "database": str(path),
467
+ "positions": total,
468
+ "database_bytes": path.stat().st_size,
469
+ "distributions": {
470
+ "phase": phases,
471
+ "result": results,
472
+ "side_to_move": {"black": sides.get("0", 0), "white": sides.get("1", 0)},
473
+ "source_split": splits,
474
+ "with_castling_rights": with_castling,
475
+ "without_castling_rights": no_castling,
476
+ "in_check": checks,
477
+ "material_imbalance_abs_ge_3": imbalanced,
478
+ },
479
+ "numeric": {
480
+ "legal_moves": legal,
481
+ "piece_count": pieces,
482
+ "material_balance_white_minus_black": balance,
483
+ },
484
+ "normalized_phase_entropy": round(
485
+ normalized_entropy(list(phases.values())), 6
486
+ ),
487
+ "thresholds": checks_map,
488
+ "high_variance": all(checks_map.values()),
489
+ "metadata": metadata,
490
+ }
491
+ db.close()
492
+ return report
493
+
494
+
495
+ def analyze(args: argparse.Namespace) -> None:
496
+ report = analyze_database(Path(args.database).resolve())
497
+ rendered = json.dumps(report, indent=2, sort_keys=True)
498
+ print(rendered)
499
+ if args.report:
500
+ Path(args.report).write_text(rendered + "\n", encoding="utf-8")
501
+
502
+
503
+ def sample(args: argparse.Namespace) -> None:
504
+ path = Path(args.database).resolve()
505
+ db = sqlite3.connect(f"file:{path}?mode=ro&immutable=1", uri=True)
506
+ if args.id is not None:
507
+ row = db.execute(
508
+ "SELECT id, fen, phase, result FROM positions WHERE id=?", (args.id,)
509
+ ).fetchone()
510
+ else:
511
+ key = random.SystemRandom().randrange(1 << 63)
512
+ row = db.execute(
513
+ "SELECT id, fen, phase, result FROM positions "
514
+ "WHERE random_key>=? ORDER BY random_key LIMIT 1",
515
+ (key,),
516
+ ).fetchone()
517
+ if row is None:
518
+ row = db.execute(
519
+ "SELECT id, fen, phase, result FROM positions ORDER BY random_key LIMIT 1"
520
+ ).fetchone()
521
+ db.close()
522
+ if row is None:
523
+ raise RuntimeError("position not found")
524
+ print(
525
+ json.dumps(
526
+ {"id": row[0], "fen": row[1], "phase": PHASE_NAMES[row[2]], "result": row[3]},
527
+ separators=(",", ":"),
528
+ )
529
+ )
530
+
531
+
532
+ def parser() -> argparse.ArgumentParser:
533
+ root = argparse.ArgumentParser(description=__doc__)
534
+ commands = root.add_subparsers(dest="command", required=True)
535
+
536
+ extract_cmd = commands.add_parser("extract", help="stream PGNs into VPD1")
537
+ extract_cmd.add_argument("--source", required=True)
538
+ extract_cmd.add_argument("--output", required=True)
539
+ extract_cmd.add_argument("--target", type=int, default=DEFAULT_TARGET)
540
+ extract_cmd.add_argument("--seed", type=int, default=91)
541
+ extract_cmd.add_argument("--commit-every", type=int, default=10_000)
542
+ extract_cmd.add_argument("--progress-every", type=int, default=10_000)
543
+ extract_cmd.set_defaults(func=extract)
544
+
545
+ analyze_cmd = commands.add_parser("analyze", help="calculate variance")
546
+ analyze_cmd.add_argument("database")
547
+ analyze_cmd.add_argument("--report")
548
+ analyze_cmd.set_defaults(func=analyze)
549
+
550
+ sample_cmd = commands.add_parser("sample", help="return one board immediately")
551
+ sample_cmd.add_argument("database")
552
+ sample_cmd.add_argument("--id", type=int)
553
+ sample_cmd.set_defaults(func=sample)
554
+ return root
555
+
556
+
557
+ if __name__ == "__main__":
558
+ arguments = parser().parse_args()
559
+ arguments.func(arguments)
scripts/vpd_to_parquet.py ADDED
@@ -0,0 +1,216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Convert a VPD1 SQLite database to a partitioned Parquet dataset."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import hashlib
8
+ import json
9
+ import sqlite3
10
+ import time
11
+ from pathlib import Path
12
+
13
+ import pyarrow as pa
14
+ import pyarrow.dataset as pads
15
+ import pyarrow.parquet as pq
16
+
17
+
18
+ PHASE_NAMES = {0: "opening", 1: "middlegame", 2: "endgame"}
19
+ COLUMNS = [
20
+ "id",
21
+ "random_key",
22
+ "fen",
23
+ "source_member",
24
+ "game_number",
25
+ "ply",
26
+ "result",
27
+ "side_to_move",
28
+ "piece_count",
29
+ "non_pawn_material",
30
+ "material_balance",
31
+ "legal_moves",
32
+ "in_check",
33
+ "castling_mask",
34
+ "halfmove_clock",
35
+ ]
36
+ SCHEMA = pa.schema(
37
+ [
38
+ ("id", pa.int64()),
39
+ ("random_key", pa.int64()),
40
+ ("fen", pa.string()),
41
+ ("source_member", pa.string()),
42
+ ("game_number", pa.int64()),
43
+ ("ply", pa.int16()),
44
+ ("result", pa.string()),
45
+ ("side_to_move", pa.int8()),
46
+ ("piece_count", pa.int8()),
47
+ ("non_pawn_material", pa.int16()),
48
+ ("material_balance", pa.int16()),
49
+ ("legal_moves", pa.int16()),
50
+ ("in_check", pa.bool_()),
51
+ ("castling_mask", pa.int8()),
52
+ ("halfmove_clock", pa.int16()),
53
+ ]
54
+ )
55
+
56
+
57
+ def sha256(path: Path) -> str:
58
+ digest = hashlib.sha256()
59
+ with path.open("rb") as source:
60
+ while chunk := source.read(8 * 1024 * 1024):
61
+ digest.update(chunk)
62
+ return digest.hexdigest()
63
+
64
+
65
+ def table_from_rows(rows: list[tuple[object, ...]], schema: pa.Schema) -> pa.Table:
66
+ arrays = []
67
+ for index, field in enumerate(schema):
68
+ values = [row[index] for row in rows]
69
+ if pa.types.is_boolean(field.type):
70
+ values = [bool(value) for value in values]
71
+ arrays.append(pa.array(values, type=field.type))
72
+ return pa.Table.from_arrays(arrays, schema=schema)
73
+
74
+
75
+ def convert(args: argparse.Namespace) -> None:
76
+ source = Path(args.input).resolve()
77
+ output = Path(args.output).resolve()
78
+ if output.exists() and any(output.iterdir()):
79
+ raise RuntimeError(f"output directory is not empty: {output}")
80
+ output.mkdir(parents=True, exist_ok=True)
81
+
82
+ db = sqlite3.connect(f"file:{source}?mode=ro&immutable=1", uri=True)
83
+ metadata = dict(db.execute("SELECT key, value FROM metadata"))
84
+ schema = SCHEMA.with_metadata(
85
+ {
86
+ b"vpd_format": metadata.get("format", "unknown").encode(),
87
+ b"source_sha256": sha256(source).encode(),
88
+ b"fen_fullmove_normalization": metadata.get(
89
+ "fen_fullmove_normalization", "unknown"
90
+ ).encode(),
91
+ }
92
+ )
93
+ source_total = db.execute("SELECT COUNT(*) FROM positions").fetchone()[0]
94
+ splits = [
95
+ row[0]
96
+ for row in db.execute(
97
+ "SELECT DISTINCT source_split FROM positions ORDER BY source_split"
98
+ )
99
+ ]
100
+ manifest: dict[str, object] = {
101
+ "format": "VPD1-Parquet",
102
+ "source": str(source),
103
+ "source_sha256": sha256(source),
104
+ "compression": args.compression,
105
+ "compression_level": args.compression_level,
106
+ "row_group_size": args.row_group_size,
107
+ "partitioning": ["source_split", "phase"],
108
+ "rows": 0,
109
+ "partitions": [],
110
+ }
111
+ started = time.monotonic()
112
+
113
+ for split in splits:
114
+ for phase_id, phase_name in PHASE_NAMES.items():
115
+ count = db.execute(
116
+ "SELECT COUNT(*) FROM positions WHERE source_split=? AND phase=?",
117
+ (split, phase_id),
118
+ ).fetchone()[0]
119
+ if not count:
120
+ continue
121
+ partition_dir = output / f"source_split={split}" / f"phase={phase_name}"
122
+ partition_dir.mkdir(parents=True, exist_ok=True)
123
+ parquet_path = partition_dir / "positions.parquet"
124
+ query = (
125
+ f"SELECT {', '.join(COLUMNS)} FROM positions "
126
+ "WHERE source_split=? AND phase=? ORDER BY id"
127
+ )
128
+ cursor = db.execute(query, (split, phase_id))
129
+ written = 0
130
+ row_groups = 0
131
+ min_id = None
132
+ max_id = None
133
+ with pq.ParquetWriter(
134
+ parquet_path,
135
+ schema,
136
+ compression=args.compression,
137
+ compression_level=args.compression_level,
138
+ use_dictionary=["source_member", "result"],
139
+ write_statistics=True,
140
+ ) as writer:
141
+ while rows := cursor.fetchmany(args.row_group_size):
142
+ table = table_from_rows(rows, schema)
143
+ writer.write_table(table, row_group_size=len(rows))
144
+ written += len(rows)
145
+ row_groups += 1
146
+ min_id = rows[0][0] if min_id is None else min_id
147
+ max_id = rows[-1][0]
148
+ if written != count:
149
+ raise RuntimeError(
150
+ f"partition count mismatch for {split}/{phase_name}: "
151
+ f"expected {count}, wrote {written}"
152
+ )
153
+ manifest["rows"] += written
154
+ manifest["partitions"].append(
155
+ {
156
+ "source_split": split,
157
+ "phase": phase_name,
158
+ "rows": written,
159
+ "row_groups": row_groups,
160
+ "min_id": min_id,
161
+ "max_id": max_id,
162
+ "bytes": parquet_path.stat().st_size,
163
+ "file": str(parquet_path.relative_to(output)),
164
+ "sha256": sha256(parquet_path),
165
+ }
166
+ )
167
+ print(
168
+ f"wrote {split}/{phase_name}: {written:,} rows, "
169
+ f"{parquet_path.stat().st_size / (1024 * 1024):.1f} MiB",
170
+ flush=True,
171
+ )
172
+
173
+ db.close()
174
+ if manifest["rows"] != source_total:
175
+ raise RuntimeError(
176
+ f"total mismatch: source has {source_total}, wrote {manifest['rows']}"
177
+ )
178
+ manifest["elapsed_seconds"] = round(time.monotonic() - started, 3)
179
+ # Leading underscore keeps the JSON sidecar out of PyArrow's default
180
+ # Parquet dataset discovery while leaving it next to the data it describes.
181
+ manifest_path = output / "_manifest.json"
182
+ manifest_path.write_text(
183
+ json.dumps(manifest, indent=2, sort_keys=True) + "\n", encoding="utf-8"
184
+ )
185
+
186
+ dataset = pads.dataset(output, format="parquet", partitioning="hive")
187
+ parquet_total = dataset.count_rows()
188
+ if parquet_total != source_total:
189
+ raise RuntimeError(
190
+ f"PyArrow validation mismatch: expected {source_total}, got {parquet_total}"
191
+ )
192
+ print(
193
+ json.dumps(
194
+ {
195
+ "rows": parquet_total,
196
+ "files": len(dataset.files),
197
+ "manifest": str(manifest_path),
198
+ "elapsed_seconds": manifest["elapsed_seconds"],
199
+ },
200
+ indent=2,
201
+ )
202
+ )
203
+
204
+
205
+ def main() -> None:
206
+ parser = argparse.ArgumentParser(description=__doc__)
207
+ parser.add_argument("--input", required=True)
208
+ parser.add_argument("--output", required=True)
209
+ parser.add_argument("--row-group-size", type=int, default=65_536)
210
+ parser.add_argument("--compression", default="zstd")
211
+ parser.add_argument("--compression-level", type=int, default=6)
212
+ convert(parser.parse_args())
213
+
214
+
215
+ if __name__ == "__main__":
216
+ main()
variance-report.json ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "database": "/Users/pawit/Documents/vexilon/tmp/vex-position-dataset/data/ccrl-high-variance-1p5m.vpd",
3
+ "database_bytes": 438558720,
4
+ "distributions": {
5
+ "in_check": 103519,
6
+ "material_imbalance_abs_ge_3": 234018,
7
+ "phase": {
8
+ "endgame": 375000,
9
+ "middlegame": 900000,
10
+ "opening": 234201
11
+ },
12
+ "result": {
13
+ "0-1": 456873,
14
+ "1-0": 570602,
15
+ "1/2-1/2": 481726
16
+ },
17
+ "side_to_move": {
18
+ "black": 751182,
19
+ "white": 758019
20
+ },
21
+ "source_split": {
22
+ "test": 307473,
23
+ "train": 1201728
24
+ },
25
+ "with_castling_rights": 289814,
26
+ "without_castling_rights": 1219387
27
+ },
28
+ "format": "VPD1",
29
+ "high_variance": true,
30
+ "metadata": {
31
+ "candidates_attempted": "2115584",
32
+ "completed_unix": "1787309415",
33
+ "fen_fullmove_normalization": "1",
34
+ "format": "VPD1",
35
+ "games_seen": "910462",
36
+ "parse_errors": "0",
37
+ "phase_quotas": "{\"0\": 225000, \"1\": 900000, \"2\": 375000}",
38
+ "position_count": "1509201",
39
+ "seed": "91",
40
+ "source": "/Users/pawit/Documents/vexilon/tmp/vex-position-dataset/source/ccrl-pgn.tar.bz2",
41
+ "target_positions": "1500000"
42
+ },
43
+ "normalized_phase_entropy": 0.858704,
44
+ "numeric": {
45
+ "legal_moves": {
46
+ "max": 87,
47
+ "mean": 30.5172,
48
+ "median": 33,
49
+ "min": 0,
50
+ "p10": 12,
51
+ "p90": 44,
52
+ "stdev": 12.064
53
+ },
54
+ "material_balance_white_minus_black": {
55
+ "max": 75,
56
+ "mean": 0.0943,
57
+ "median": 0,
58
+ "min": -51,
59
+ "p10": -2,
60
+ "p90": 2,
61
+ "stdev": 2.6234
62
+ },
63
+ "piece_count": {
64
+ "max": 32,
65
+ "mean": 20.713,
66
+ "median": 21,
67
+ "min": 2,
68
+ "p10": 10,
69
+ "p90": 30,
70
+ "stdev": 7.5146
71
+ }
72
+ },
73
+ "positions": 1509201,
74
+ "thresholds": {
75
+ "at_least_1_5m_positions": true,
76
+ "both_castling_states_at_least_10pct": true,
77
+ "checks_at_least_1pct": true,
78
+ "legal_move_p10_at_most_22": true,
79
+ "legal_move_p90_at_least_38": true,
80
+ "legal_move_stdev_at_least_8": true,
81
+ "material_imbalance_at_least_15pct": true,
82
+ "phase_entropy_at_least_0_85": true,
83
+ "phase_min_share_at_least_15pct": true,
84
+ "piece_count_stdev_at_least_5": true,
85
+ "result_min_share_at_least_20pct": true,
86
+ "side_to_move_between_47_and_53pct_white": true
87
+ }
88
+ }