KeithG33 commited on
Commit
d42df3a
·
1 Parent(s): 385a18c

update for lc0 train data

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. ChessBot-Dataset.py +45 -10
  2. raw2dataset.py +190 -221
  3. test/pgns-run1-test80-20220503-0054.pgn_part_2.pgn_part_1.pgn.zst +0 -3
  4. test/pgns-run1-test80-20220503-0054.pgn_part_2.pgn_part_10.pgn.zst +0 -3
  5. test/pgns-run1-test80-20220503-0054.pgn_part_2.pgn_part_2.pgn.zst +0 -3
  6. test/pgns-run1-test80-20220503-0054.pgn_part_2.pgn_part_3.pgn.zst +0 -3
  7. test/pgns-run1-test80-20220503-0054.pgn_part_2.pgn_part_4.pgn.zst +0 -3
  8. test/pgns-run1-test80-20220503-0054.pgn_part_2.pgn_part_5.pgn.zst +0 -3
  9. test/pgns-run1-test80-20220503-0054.pgn_part_2.pgn_part_6.pgn.zst +0 -3
  10. test/pgns-run1-test80-20220503-0054.pgn_part_2.pgn_part_7.pgn.zst +0 -3
  11. test/pgns-run1-test80-20220503-0054.pgn_part_2.pgn_part_8.pgn.zst +0 -3
  12. test/pgns-run1-test80-20220503-0054.pgn_part_2.pgn_part_9.pgn.zst +0 -3
  13. test/test_0000.pgn.zst +3 -0
  14. test/test_0001.pgn.zst +3 -0
  15. test/test_0002.pgn.zst +3 -0
  16. test/test_0003.pgn.zst +3 -0
  17. test/test_0004.pgn.zst +3 -0
  18. test/test_0005.pgn.zst +3 -0
  19. test/test_0006.pgn.zst +3 -0
  20. test/test_0007.pgn.zst +3 -0
  21. test/test_0008.pgn.zst +3 -0
  22. test/test_0009.pgn.zst +3 -0
  23. test/test_0010.pgn.zst +3 -0
  24. test/test_0011.pgn.zst +3 -0
  25. test/test_0012.pgn.zst +3 -0
  26. test/test_0013.pgn.zst +3 -0
  27. test/test_0014.pgn.zst +3 -0
  28. test/test_0015.pgn.zst +3 -0
  29. test/test_0016.pgn.zst +3 -0
  30. test/test_0017.pgn.zst +3 -0
  31. test/test_0018.pgn.zst +3 -0
  32. test/test_0019.pgn.zst +3 -0
  33. test/test_0020.pgn.zst +3 -0
  34. test/test_0021.pgn.zst +3 -0
  35. test/test_0022.pgn.zst +3 -0
  36. test/test_0023.pgn.zst +3 -0
  37. test/test_0024.pgn.zst +3 -0
  38. test/test_0025.pgn.zst +3 -0
  39. test/test_0026.pgn.zst +3 -0
  40. test/test_0027.pgn.zst +3 -0
  41. test/test_0028.pgn.zst +3 -0
  42. test/test_0029.pgn.zst +3 -0
  43. test/test_0030.pgn.zst +3 -0
  44. test/test_0031.pgn.zst +3 -0
  45. train/pgns-run1-test80-20220404-0654.pgn_part_1.pgn.zst +0 -3
  46. train/pgns-run1-test80-20220404-1254.pgn_part_1.pgn.zst +0 -3
  47. train/pgns-run1-test80-20220404-1254.pgn_part_2.pgn.zst +0 -3
  48. train/pgns-run1-test80-20220404-1854.pgn_part_1.pgn.zst +0 -3
  49. train/pgns-run1-test80-20220404-1854.pgn_part_2.pgn.zst +0 -3
  50. train/pgns-run1-test80-20220404-1854.pgn_part_3.pgn.zst +0 -3
ChessBot-Dataset.py CHANGED
@@ -10,6 +10,7 @@ from datasets import (
10
  Value,
11
  Array2D,
12
  )
 
13
  from adversarial_gym.chess_env import ChessEnv
14
  import zstandard as zstd
15
 
@@ -22,9 +23,10 @@ class ChessPGNDataset(GeneratorBasedBuilder):
22
  return DatasetInfo(
23
  description="Chess positions + moves + results, streamed from PGN shards",
24
  features=Features({
25
- "state": Array2D((8,8), dtype="int8"),
26
- "action": Value("int16"),
27
- "result": Value("int8"),
 
28
  })
29
  )
30
 
@@ -54,6 +56,33 @@ class ChessPGNDataset(GeneratorBasedBuilder):
54
  gen_kwargs={"shards": test_paths},
55
  ),
56
  ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57
  def _generate_examples(self, shards):
58
  import chess.pgn
59
  uid = 0
@@ -64,18 +93,24 @@ class ChessPGNDataset(GeneratorBasedBuilder):
64
  with decompressor.stream_reader(compressed) as reader:
65
  text_stream = io.TextIOWrapper(reader, encoding='utf-8')
66
  while (game := chess.pgn.read_game(text_stream)) is not None:
67
- # while (game := chess.pgn.read_game(f)) is not None:
68
  board = game.board()
69
- base = {"1-0":1,"0-1":-1}.get(game.headers["Result"], 0)
70
- for move in game.mainline_moves():
 
 
 
 
 
 
 
71
  state = ChessEnv.get_piece_configuration(board)
72
  state = state if board.turn else -state
73
  action = ChessEnv.move_to_action(move)
74
- result = base * (-1 if board.turn == 0 else 1)
75
  yield uid, {
76
- "state": state.astype("int8"),
77
- "action": int(action),
78
- "result": int(result),
 
79
  }
80
  uid += 1
81
  board.push(move)
 
10
  Value,
11
  Array2D,
12
  )
13
+ import chess
14
  from adversarial_gym.chess_env import ChessEnv
15
  import zstandard as zstd
16
 
 
23
  return DatasetInfo(
24
  description="Chess positions + moves + results, streamed from PGN shards",
25
  features=Features({
26
+ "state": Array2D((8,8), dtype="int8"),
27
+ "action": Value("int16"),
28
+ "best_action": Value("int16"), # -1 if not available
29
+ "result": Value("float32"),
30
  })
31
  )
32
 
 
56
  gen_kwargs={"shards": test_paths},
57
  ),
58
  ]
59
+
60
+ @staticmethod
61
+ def _parse_comment(comment, board):
62
+ """Parse a move comment like '-0.2779' or '0.52 e2e4'.
63
+ Returns (q_val or None, best_action or -1).
64
+ q_val is float in [-1, 1] relative to side-to-move.
65
+ best_action is the action index of the best move, or -1 if absent."""
66
+ if not comment:
67
+ return None, -1
68
+ parts = comment.split()
69
+ if not parts:
70
+ return None, -1
71
+ # First token must be a number
72
+ first = parts[0]
73
+ try:
74
+ q_val = float(first)
75
+ except ValueError:
76
+ return None, -1
77
+ if len(parts) < 2:
78
+ return q_val, -1
79
+ # Second token is a UCI best move — must be legal
80
+ best_move = chess.Move.from_uci(parts[1])
81
+ assert best_move in board.legal_moves, \
82
+ f"best move {parts[1]} not legal in {board.fen()}"
83
+ best_action = int(ChessEnv.move_to_action(best_move))
84
+ return q_val, best_action
85
+
86
  def _generate_examples(self, shards):
87
  import chess.pgn
88
  uid = 0
 
93
  with decompressor.stream_reader(compressed) as reader:
94
  text_stream = io.TextIOWrapper(reader, encoding='utf-8')
95
  while (game := chess.pgn.read_game(text_stream)) is not None:
 
96
  board = game.board()
97
+ header_result = {"1-0":1,"0-1":-1}.get(game.headers.get("Result",""), 0)
98
+ for node in game.mainline():
99
+ move = node.move
100
+ # Parse annotated Q-value and best move from comment
101
+ q_val, best_action = self._parse_comment(node.comment, board)
102
+ if q_val is not None:
103
+ result = q_val
104
+ else:
105
+ result = float(header_result * (-1 if board.turn == 0 else 1))
106
  state = ChessEnv.get_piece_configuration(board)
107
  state = state if board.turn else -state
108
  action = ChessEnv.move_to_action(move)
 
109
  yield uid, {
110
+ "state": state.astype("int8"),
111
+ "action": int(action),
112
+ "best_action": int(best_action),
113
+ "result": float(result),
114
  }
115
  uid += 1
116
  board.push(move)
raw2dataset.py CHANGED
@@ -1,244 +1,213 @@
1
- from multiprocessing import Pool
2
- import os
3
- import shutil, random, io
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
  from pathlib import Path
5
- from itertools import cycle
6
- import subprocess
7
- import tarfile
8
- import tempfile
9
  import chess.pgn
10
  import zstandard as zstd
11
  from tqdm import tqdm
12
 
13
- RAW_DATA_DIR = Path("raw_data")
14
- LC0_TEST_DIR = RAW_DATA_DIR / "lc0-test"
15
- NUM_TEST_FILES = 1
16
- TRAIN_DIR = Path("train")
17
- TEST_DIR = Path("test")
18
- ZSTD_LEVEL = 10
19
- GAMES_PER_SHARD = 100000 # As requested: -#100000
20
- PROCESS_COUNT = 25
21
-
22
-
23
- def open_pgn_stream(path: Path):
24
- if path.suffix == '.pgn':
25
- return path.open('r', encoding='utf-8')
26
- elif path.suffix == '.zst':
27
- fb = path.open('rb')
28
- dctx = zstd.ZstdDecompressor()
29
- return io.TextIOWrapper(dctx.stream_reader(fb), encoding='utf-8')
30
- else:
31
- raise ValueError(f"Unsupported extension: {path.suffix}")
32
-
33
 
34
- def open_append_writers(shards, level):
35
- writers = []
36
- for p in shards:
37
- fb = p.open('ab')
38
- cctx = zstd.ZstdCompressor(level=level)
39
- writers.append(io.TextIOWrapper(cctx.stream_writer(fb), encoding='utf-8'))
40
- return writers
41
 
42
 
43
- def prepare_train_test_dirs():
44
- TRAIN_DIR.mkdir(exist_ok=True)
45
- TEST_DIR.mkdir(exist_ok=True)
 
 
 
46
 
47
 
48
- def _worker_split_zst_with_pgn_extract(args):
49
- """
50
- Worker function for the multiprocessing pool. It correctly handles pgn-extract's
51
- behavior by changing the working directory for isolation.
52
- """
53
- input_path, games_per_shard = args
54
- final_shard_paths = []
55
-
56
- # Each worker gets a unique temporary directory to work in.
57
- with tempfile.TemporaryDirectory() as temp_dir:
58
- temp_dir_path = Path(temp_dir)
59
- # The decompressed file will live inside this temp directory.
60
- temp_pgn_path = temp_dir_path / "decompressed.pgn"
61
-
62
- # 1. Decompress the source .zst into the temporary directory.
63
  dctx = zstd.ZstdDecompressor()
64
- with input_path.open('rb') as f_in, temp_pgn_path.open('wb') as f_out:
65
- dctx.copy_stream(f_in, f_out)
66
-
67
- # --- CRITICAL SECTION for correct pgn-extract usage ---
68
- original_cwd = Path.cwd()
69
- try:
70
- # 2. Change into the temporary directory. This isolates the pgn-extract output.
71
- os.chdir(temp_dir_path)
72
-
73
- # 3. Run pgn-extract. It will create 1.pgn, 2.pgn, etc. *here*.
74
- # We only need to pass the filename, as we are in its directory.
75
- command = [
76
- "pgn-extract",
77
- f"-#{games_per_shard}",
78
- temp_pgn_path.name # "decompressed.pgn"
79
- ]
80
-
81
- # This command is now correct according to the documentation.
82
- subprocess.run(command, check=True, capture_output=True, text=True, encoding='latin-1')
83
- except FileNotFoundError:
84
- print("ERROR: 'pgn-extract' command not found. Please install it and ensure it is in your system's PATH.")
85
- raise
86
- except subprocess.CalledProcessError as e:
87
- print(f"--- ERROR during pgn-extract for {input_path.name}: ---\n{e.stderr}\n---")
88
- raise
89
- finally:
90
- os.chdir(original_cwd)
91
- # --- END CRITICAL SECTION ---
92
-
93
- split_pgn_files = sorted(
94
- [p for p in temp_dir_path.glob("*.pgn") if p.stem.isdigit()],
95
- key=lambda p: int(p.stem)
96
- )
97
-
98
- # 6. Re-compress each shard to a unique .zst file in the original script directory.
 
 
 
 
 
99
  cctx = zstd.ZstdCompressor(level=ZSTD_LEVEL)
100
- for pgn_shard_path in split_pgn_files:
101
- final_zst_path = Path(f"{input_path.stem}_part_{pgn_shard_path.stem}.pgn.zst")
102
- with pgn_shard_path.open('rb') as f_in, final_zst_path.open('wb') as f_out:
103
- cctx.copy_stream(f_in, f_out)
104
- final_shard_paths.append(final_zst_path)
105
-
106
- # The temp directory and its contents (decompressed.pgn, 1.pgn, etc.) are now deleted.
107
- return final_shard_paths
108
-
109
-
110
- def resplit_test_files(test_files, games_per_split):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
111
  """
112
- Re-splits each test .pgn.zst file into smaller chunks sequentially.
113
-
114
- Args:
115
- test_files (list of Path): Paths to the original test shards.
116
- games_per_split (int): Number of games per new shard.
117
-
118
- Returns:
119
- List[Path]: List of newly created smaller test shard paths.
120
  """
121
- print(f"\nResplitting {len(test_files)} test shard(s) into smaller shards...")
122
 
123
- new_test_shards = []
124
- for test_file in tqdm(test_files, desc="Resplitting test shards"):
125
- smaller_shards = _worker_split_zst_with_pgn_extract((test_file, games_per_split))
126
- new_test_shards.extend(smaller_shards)
127
- test_file.unlink() # Remove original file
128
 
129
- return new_test_shards
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
130
 
131
- def split_and_distribute_files():
132
- """
133
- Finds all .pgn.zst files, splits them into shards of 100,000 games each,
134
- and distributes the resulting .pgn.zst shards into train/ and test/ folders.
135
-
136
- Returns:
137
- A tuple containing two lists: (train_shard_paths, test_shard_paths)
138
- """
139
- prepare_train_test_dirs()
140
-
141
- all_zst_inputs = list(LC0_TEST_DIR.rglob("*.zst"))
142
- if not all_zst_inputs:
143
- print(f"No .zst files found in {LC0_TEST_DIR}. Cannot perform Step 1.")
144
- return [], []
145
-
146
- print(f"Found {len(all_zst_inputs)} source .pgn.zst files. Starting split process...")
147
-
148
- tasks = [(path, GAMES_PER_SHARD) for path in all_zst_inputs]
149
-
150
- all_new_shards = []
151
- with Pool(processes=PROCESS_COUNT) as pool:
152
- for shards in tqdm(pool.imap(_worker_split_zst_with_pgn_extract, tasks),
153
- total=len(tasks),
154
- desc="Splitting source files"):
155
- all_new_shards.extend(shards)
156
-
157
- print(f"\nCreated a total of {len(all_new_shards)} new shards.")
158
-
159
- # --- Distribution Logic ---
160
- random.shuffle(all_new_shards)
161
- test_selection = all_new_shards[:NUM_TEST_FILES]
162
- train_selection = all_new_shards[NUM_TEST_FILES:]
163
-
164
- print(f"Moving {len(train_selection)} shards to train/ and {len(test_selection)} to test/...")
165
-
166
- for shard in train_selection:
167
- shutil.move(str(shard), TRAIN_DIR / shard.name)
168
-
169
- intermediate_test_paths = []
170
- for shard in test_selection:
171
- final_path = TEST_DIR / shard.name
172
- shutil.move(str(shard), final_path)
173
- intermediate_test_paths.append(final_path)
174
-
175
- # Final re-split of test file(s)
176
- resplit_test_shards = resplit_test_files(intermediate_test_paths, GAMES_PER_SHARD // 10)
177
-
178
- for shard in resplit_test_shards:
179
- shutil.move(str(shard), TEST_DIR / shard.name)
180
-
181
- final_train_paths = [TRAIN_DIR / s.name for s in train_selection]
182
- final_test_paths = [TEST_DIR / s.name for s in resplit_test_shards]
183
-
184
- return final_train_paths, final_test_paths
185
-
186
-
187
-
188
- def get_pgn_file_paths(input_dir):
189
- return list(Path(input_dir).rglob("*.pgn"))
190
-
191
-
192
- def distribute_games_to_zst_shards(pgn_paths, train_shards, test_shards, split_ratio=0.01):
193
- train_writers = open_append_writers(train_shards, level=ZSTD_LEVEL)
194
- test_writers = open_append_writers(test_shards, level=ZSTD_LEVEL)
195
-
196
- train_cycle = cycle(train_writers)
197
- test_cycle = cycle(test_writers)
198
-
199
- total_games = 0
200
- for path in pgn_paths:
201
- with open_pgn_stream(path) as f:
202
- games_iter = iter(lambda: chess.pgn.read_game(f), None)
203
- for game in tqdm(games_iter,
204
- desc=f"Distributing games from {path.name}",
205
- unit="game"):
206
- total_games += 1
207
- if random.random() < split_ratio:
208
- w = next(test_cycle)
209
- else:
210
- w = next(train_cycle)
211
- exporter = chess.pgn.FileExporter(w)
212
- game.accept(exporter)
213
-
214
- for w in train_writers + test_writers:
215
- w.close()
216
-
217
- def compress_raw_data_zst():
218
- """Creates raw_data.tar.zst with Zstd(level=ZSTD_LEVEL) compression."""
219
- zst_path = RAW_DATA_DIR.with_suffix('.tar.zst')
220
- cctx = zstd.ZstdCompressor(level=ZSTD_LEVEL)
221
-
222
- with cctx.stream_writer(zst_path.open('wb')) as zst_writer:
223
- # Build a streaming tar over that writer
224
- with tarfile.open(fileobj=zst_writer, mode='w|') as tar:
225
- for path in tqdm(RAW_DATA_DIR.rglob("*"),
226
- desc="Archiving raw_data",
227
- unit="file"):
228
- # Add each file/dir under raw_data into the tar
229
- tar.add(path, arcname=path.relative_to(RAW_DATA_DIR.parent))
230
 
231
  def main():
232
- print("Step 1: Split & distribute .pgn.zst → train/test")
233
- train_shards, test_shards = split_and_distribute_files()
234
-
235
- print("\nStep 2: Distribute remaining .pgn files")
236
- all_pgns = get_pgn_file_paths(RAW_DATA_DIR)
237
-
238
- print(f"Found {len(all_pgns)} .pgn files. Starting distribution process...")
239
- distribute_games_to_zst_shards(all_pgns, train_shards, test_shards)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
240
 
241
- print("\n✅ Pipeline complete.")
242
 
243
  if __name__ == "__main__":
244
  main()
 
1
+ """
2
+ raw2dataset.py — Convert raw PGN data into sharded train/test .pgn.zst files.
3
+
4
+ Each worker gets a subset of input files and writes its own output shards
5
+ directly — no serialization bottleneck. Games are distributed round-robin
6
+ across each worker's shards for variety within files. Input files are shuffled
7
+ and distributed round-robin across workers so each worker gets a mix of sources.
8
+
9
+ Each shard targets ~POSITIONS_PER_SHARD positions.
10
+
11
+ Usage:
12
+ python raw2dataset.py
13
+ """
14
+
15
+ import io
16
+ import time
17
+ import random
18
  from pathlib import Path
19
+ from multiprocessing import Pool, Value
20
+
 
 
21
  import chess.pgn
22
  import zstandard as zstd
23
  from tqdm import tqdm
24
 
25
+ # ── Configuration ──
26
+ RAW_DATA_DIR = Path("/home/kage/chess_workspace/chess-drive2/pgn-data/raw_data")
27
+ OUTPUT_DIR = Path("/home/kage/chess_workspace/chess-drive2/ChessBot-Dataset")
28
+ TRAIN_DIR = OUTPUT_DIR / "train"
29
+ TEST_DIR = OUTPUT_DIR / "test"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
 
31
+ POSITIONS_PER_SHARD = 2_000_000
32
+ TEST_RATIO = 0.005 # 0.5% of games go to test
33
+ ZSTD_LEVEL = 10
34
+ NUM_WORKERS = 32
 
 
 
35
 
36
 
37
+ def find_input_files(raw_dir: Path) -> list[Path]:
38
+ """Find all .pgn and .pgn.zst files recursively."""
39
+ files = []
40
+ for pattern in ("**/*.pgn", "**/*.pgn.zst"):
41
+ files.extend(raw_dir.glob(pattern))
42
+ return sorted(files)
43
 
44
 
45
+ def open_pgn_reader(path: Path):
46
+ """Open a .pgn or .pgn.zst file and return a text stream."""
47
+ if path.suffixes == [".pgn", ".zst"] or (path.suffix == ".zst" and ".pgn" in path.name):
48
+ fb = path.open("rb")
 
 
 
 
 
 
 
 
 
 
 
49
  dctx = zstd.ZstdDecompressor()
50
+ return io.TextIOWrapper(dctx.stream_reader(fb), encoding="utf-8", errors="replace")
51
+ elif path.suffix == ".pgn":
52
+ return path.open("r", encoding="utf-8", errors="replace")
53
+ else:
54
+ raise ValueError(f"Unsupported file: {path}")
55
+
56
+
57
+ def count_positions(game) -> int:
58
+ """Count positions (moves) in a game's mainline."""
59
+ return sum(1 for _ in game.mainline())
60
+
61
+
62
+ class ShardWriter:
63
+ """Writes games to numbered .pgn.zst shard files, creating new ones as needed.
64
+ Uses a shared counter so all workers produce sequentially numbered files."""
65
+
66
+ def __init__(self, output_dir: Path, prefix: str, positions_per_shard: int, counter):
67
+ self.output_dir = output_dir
68
+ self.prefix = prefix
69
+ self.positions_per_shard = positions_per_shard
70
+ self.counter = counter
71
+ self.positions_in_shard = 0
72
+ self.writer = None
73
+ self.total_positions = 0
74
+ self.total_games = 0
75
+ self.num_shards = 0
76
+ self._open_new_shard()
77
+
78
+ def _next_shard_id(self) -> int:
79
+ with self.counter.get_lock():
80
+ shard_id = self.counter.value
81
+ self.counter.value += 1
82
+ return shard_id
83
+
84
+ def _open_new_shard(self):
85
+ if self.writer is not None:
86
+ self.writer.close()
87
+ shard_id = self._next_shard_id()
88
+ path = self.output_dir / f"{self.prefix}_{shard_id:04d}.pgn.zst"
89
+ fb = path.open("wb")
90
  cctx = zstd.ZstdCompressor(level=ZSTD_LEVEL)
91
+ self.writer = io.TextIOWrapper(cctx.stream_writer(fb), encoding="utf-8")
92
+ self.positions_in_shard = 0
93
+ self.num_shards += 1
94
+
95
+ def write_game(self, pgn_text: str, num_positions: int):
96
+ if self.positions_in_shard >= self.positions_per_shard:
97
+ self._open_new_shard()
98
+ self.writer.write(pgn_text)
99
+ self.writer.write("\n\n")
100
+ self.positions_in_shard += num_positions
101
+ self.total_positions += num_positions
102
+ self.total_games += 1
103
+
104
+ def close(self):
105
+ if self.writer is not None:
106
+ self.writer.close()
107
+ self.writer = None
108
+
109
+
110
+ def _init_worker(train_ctr, test_ctr, file_ctr):
111
+ """Store shared counters in each worker process."""
112
+ global _train_counter, _test_counter, _file_counter
113
+ _train_counter = train_ctr
114
+ _test_counter = test_ctr
115
+ _file_counter = file_ctr
116
+
117
+
118
+ def worker_process(args):
119
  """
120
+ Each worker reads its assigned input files and writes directly to its own
121
+ train/test shard files. Returns stats dict.
 
 
 
 
 
 
122
  """
123
+ worker_id, input_files = args
124
 
125
+ train_writer = ShardWriter(TRAIN_DIR, "train", POSITIONS_PER_SHARD, _train_counter)
126
+ test_writer = ShardWriter(TEST_DIR, "test", POSITIONS_PER_SHARD, _test_counter)
 
 
 
127
 
128
+ for path in input_files:
129
+ try:
130
+ with open_pgn_reader(path) as f:
131
+ while (game := chess.pgn.read_game(f)) is not None:
132
+ positions = count_positions(game)
133
+ if positions == 0:
134
+ continue
135
+ exporter = chess.pgn.StringExporter(headers=True, variations=True, comments=True)
136
+ pgn_text = game.accept(exporter)
137
+
138
+ if random.random() < TEST_RATIO:
139
+ test_writer.write_game(pgn_text, positions)
140
+ else:
141
+ train_writer.write_game(pgn_text, positions)
142
+ except Exception as e:
143
+ print(f"Worker {worker_id} error reading {path}: {e}")
144
+ with _file_counter.get_lock():
145
+ _file_counter.value += 1
146
+
147
+ train_writer.close()
148
+ test_writer.close()
149
+
150
+ return {
151
+ "worker_id": worker_id,
152
+ "train_games": train_writer.total_games,
153
+ "train_positions": train_writer.total_positions,
154
+ "train_shards": train_writer.num_shards,
155
+ "test_games": test_writer.total_games,
156
+ "test_positions": test_writer.total_positions,
157
+ "test_shards": test_writer.num_shards,
158
+ "files_processed": len(input_files),
159
+ }
160
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
161
 
162
  def main():
163
+ TRAIN_DIR.mkdir(parents=True, exist_ok=True)
164
+ TEST_DIR.mkdir(parents=True, exist_ok=True)
165
+
166
+ input_files = find_input_files(RAW_DATA_DIR)
167
+ random.shuffle(input_files)
168
+ print(f"Found {len(input_files)} input files")
169
+
170
+ # Distribute input files round-robin across workers
171
+ worker_files: list[list[Path]] = [[] for _ in range(NUM_WORKERS)]
172
+ for i, f in enumerate(input_files):
173
+ worker_files[i % NUM_WORKERS].append(f)
174
+
175
+ tasks = [(wid, files) for wid, files in enumerate(worker_files) if files]
176
+ print(f"Distributing across {len(tasks)} workers...")
177
+
178
+ train_counter = Value('i', 0)
179
+ test_counter = Value('i', 0)
180
+ file_counter = Value('i', 0)
181
+ total_files = len(input_files)
182
+
183
+ total_train_games = total_train_positions = total_train_shards = 0
184
+ total_test_games = total_test_positions = total_test_shards = 0
185
+
186
+ with Pool(processes=len(tasks), initializer=_init_worker, initargs=(train_counter, test_counter, file_counter)) as pool:
187
+ results = pool.map_async(worker_process, tasks)
188
+
189
+ pbar = tqdm(total=total_files, desc="Processing files", unit="file")
190
+ while not results.ready():
191
+ done = file_counter.value
192
+ pbar.n = done
193
+ pbar.refresh()
194
+ time.sleep(0.5)
195
+ pbar.n = total_files
196
+ pbar.refresh()
197
+ pbar.close()
198
+
199
+ for stats in results.get():
200
+ total_train_games += stats["train_games"]
201
+ total_train_positions += stats["train_positions"]
202
+ total_train_shards += stats["train_shards"]
203
+ total_test_games += stats["test_games"]
204
+ total_test_positions += stats["test_positions"]
205
+ total_test_shards += stats["test_shards"]
206
+
207
+ print(f"\nDone!")
208
+ print(f" Train: {total_train_games:,} games, {total_train_positions:,} positions, {total_train_shards} shards")
209
+ print(f" Test: {total_test_games:,} games, {total_test_positions:,} positions, {total_test_shards} shards")
210
 
 
211
 
212
  if __name__ == "__main__":
213
  main()
test/pgns-run1-test80-20220503-0054.pgn_part_2.pgn_part_1.pgn.zst DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:f4acfac23dcf2b90f8ee6d2775d303a239900ab45e318b31d21140cdf3a6d37a
3
- size 4494116
 
 
 
 
test/pgns-run1-test80-20220503-0054.pgn_part_2.pgn_part_10.pgn.zst DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:7d5e95577df6805d4512973f75f1486fb20407ad44cb86370eb9e51203803af1
3
- size 4476105
 
 
 
 
test/pgns-run1-test80-20220503-0054.pgn_part_2.pgn_part_2.pgn.zst DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:9ac7e3f244515ab41a390d5e520505d6e89b067a18dacf1e95bdd8a8062e27aa
3
- size 4459504
 
 
 
 
test/pgns-run1-test80-20220503-0054.pgn_part_2.pgn_part_3.pgn.zst DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:b02bee28b966caa5de4a7ea6fae0df06595c9861641c3dcea96f7474c60511d5
3
- size 4511345
 
 
 
 
test/pgns-run1-test80-20220503-0054.pgn_part_2.pgn_part_4.pgn.zst DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:00977ac871e4ed45612e7bfeba1b9d110c2bd1245c9a2353058784975b52e1ff
3
- size 4512137
 
 
 
 
test/pgns-run1-test80-20220503-0054.pgn_part_2.pgn_part_5.pgn.zst DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:6babf98590982c9293e37f4bd396be2d0e13a4b54b3be5682f03bddd8907bb70
3
- size 4519850
 
 
 
 
test/pgns-run1-test80-20220503-0054.pgn_part_2.pgn_part_6.pgn.zst DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:1093bd94cdb5eea35fd6067fdf90f30f053e8514391cb090e281694d93f8b9fc
3
- size 4510892
 
 
 
 
test/pgns-run1-test80-20220503-0054.pgn_part_2.pgn_part_7.pgn.zst DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:67dbbb7e1ae9f44e8fa69d809cfc281a70a01c74ee8175219bb296174db34159
3
- size 4464680
 
 
 
 
test/pgns-run1-test80-20220503-0054.pgn_part_2.pgn_part_8.pgn.zst DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:16c7bd6f6e40b1315d9ec8b5e9520758f226105279f7808f12952a72597c453e
3
- size 4466912
 
 
 
 
test/pgns-run1-test80-20220503-0054.pgn_part_2.pgn_part_9.pgn.zst DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:0ff4c35b28ca8e590a88b57764f1933cf23e092f06d998e0f9d19e6bfacec4db
3
- size 4474734
 
 
 
 
test/test_0000.pgn.zst ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1ecba21b52337ce054ab97a10053babc2f4d7265a06a362013301755577465a8
3
+ size 4783995
test/test_0001.pgn.zst ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:43857857de81dfbcd482d3f86b5db958cb45feb3445cbc48256bb643ca3cfc2f
3
+ size 5317083
test/test_0002.pgn.zst ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0611a561f48da1fc34e04c93ad213b8a07ba6f64a3e7acc2328854f83840f641
3
+ size 5916861
test/test_0003.pgn.zst ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8a07ac10d65e530fd572b748e44898888a2ea5d0ea8aaa9794a882176358e793
3
+ size 5015013
test/test_0004.pgn.zst ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b2e6e1ad42f71bb80924ae2ce38de0cb22113c45ee7b5546095c74cf78c22e88
3
+ size 5183179
test/test_0005.pgn.zst ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:999d06d78979e6bb583178794b3ba790a59751010ba39c8375c04adf589fc5f6
3
+ size 5190918
test/test_0006.pgn.zst ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:004d680775b691ddf4bbaaf3f0e4919fa903ed5d6acfa9dfffcb4c0da1ad3a6a
3
+ size 4464981
test/test_0007.pgn.zst ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:88579f00ca2b2b59dca5bdfdf9779db80307970d13b4ed344ef6789758302b0c
3
+ size 5556966
test/test_0008.pgn.zst ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:12a452093c45679db39036771069182cdc3acf5b05a4d6bc2030e1f35af71883
3
+ size 6260120
test/test_0009.pgn.zst ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c7dfa643ea28ebf655275ff300046147740cd1e5d7e91a9dfd2e245aea681be3
3
+ size 5578089
test/test_0010.pgn.zst ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d9332656f3aab8afe0b39b1e985a90de0f9d41123a6630e184b65d58b3799e23
3
+ size 5612755
test/test_0011.pgn.zst ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1b93f16b9ad83a072b368a1426bc807737eecae7238a41c479c3bbe624c758e2
3
+ size 4179410
test/test_0012.pgn.zst ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d48791e2438feafbe78eed7ee0806458a2b25c2efdb9b6d89c8d039e7fd7e14c
3
+ size 5781650
test/test_0013.pgn.zst ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9a4b826470cc33293d312d999a7d39431ba13da0778d12cf0587774770ea5f79
3
+ size 5448820
test/test_0014.pgn.zst ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:19481175dfc1d83b06a42e66331b62f2f022d33b3352551e96d6dd700fe77bf9
3
+ size 5769669
test/test_0015.pgn.zst ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c4da2a027f329462c394eafbe98c132c6d0588a22ad278250c692defcf584df2
3
+ size 5083758
test/test_0016.pgn.zst ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2a333a82a13b0d09105633c5bc59be930cccccac9366694f45ae6d32f4d1a4b0
3
+ size 6065628
test/test_0017.pgn.zst ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:dcfd24d4c95f5a7d1b2ca4cffafb03cceab3a5bebc4978bd70f5a53f32f9049f
3
+ size 4381030
test/test_0018.pgn.zst ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2e91c4019eae7449d134d6182d982a5e7156bb3289ee80c945ac524393d0f592
3
+ size 4670719
test/test_0019.pgn.zst ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8c627d2e1f133ed517a804480fb187407bde4845e8183caf3923fc81c7de6262
3
+ size 5576662
test/test_0020.pgn.zst ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2ee55ccde558affffc0a78490ff2b0dc2a43e3f7c78fa085c1eab52f0a871f80
3
+ size 4216012
test/test_0021.pgn.zst ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f14b585e67b9a7b2c91af8d445f05b43d4035c1afe0640e4f346e97aad8b34a0
3
+ size 5905784
test/test_0022.pgn.zst ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:27ac5750bbeb690fe3991e79e8685c782755f007aef7344f0827ab1cc922f45b
3
+ size 5412100
test/test_0023.pgn.zst ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b40d1ddde5189d7f14d682a32da4ee81251905d9e49f76d535d7c5218e7c8a0d
3
+ size 5297789
test/test_0024.pgn.zst ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3c639343e1b3e7d2f53b0ea7ffa9c31a760d7208c2d08e9027eab54fd2bfa73e
3
+ size 5243005
test/test_0025.pgn.zst ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a9114745499efe64d3cfdb15fdd1d4762bd60f69a0e76b67e98befbdab33f7e4
3
+ size 4995279
test/test_0026.pgn.zst ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:15ac91a88ea0310c260d99f880fb74ed99b5dfe978b53463275ccf7a8908b5a8
3
+ size 5797037
test/test_0027.pgn.zst ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9daa5eb9d4a25cc16595b7f21b70f688429dca1e95682d7aa08c7e8af3d908f0
3
+ size 4805686
test/test_0028.pgn.zst ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cdedb88f9d9a359669c9a39896352e4dcbab4b797c301d19ff4b4a019c4e7973
3
+ size 5087590
test/test_0029.pgn.zst ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:90f727cc9b8924e7648abac260f36a74dabe736d46e9992c55eaced1552ff26a
3
+ size 5050953
test/test_0030.pgn.zst ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f30ba033dea3210a850a9caca562ebf7a13cd85576bd4a051fb959705d27a611
3
+ size 5336609
test/test_0031.pgn.zst ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:72608d49c0cc62cb2fec8d06f5b6d205fe7e12a68b8d52fa736ea5267d6c5eef
3
+ size 5079960
train/pgns-run1-test80-20220404-0654.pgn_part_1.pgn.zst DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:0291d3b461ee4d56da60f4cc7d7c9a91d021087d4d43e63c8419e0cdc59cae26
3
- size 1939586
 
 
 
 
train/pgns-run1-test80-20220404-1254.pgn_part_1.pgn.zst DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:a50fe0e681614beffd3d9fdee0eddace13b245e08a6e47d83a4242f29b0d5ac9
3
- size 23873124
 
 
 
 
train/pgns-run1-test80-20220404-1254.pgn_part_2.pgn.zst DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:b747562d4f08f7d5a59c40e1211267298706f51611291e9659341b8b8428c887
3
- size 7159525
 
 
 
 
train/pgns-run1-test80-20220404-1854.pgn_part_1.pgn.zst DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:0c8690b4b1e96008d370b8f39f537d71e3b79373498b56b189917aabf002cdc6
3
- size 23811945
 
 
 
 
train/pgns-run1-test80-20220404-1854.pgn_part_2.pgn.zst DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:5d4449aa97fcc9d59fbc36b7ec74e66ceffabf0fb46fae90f1649455ff827aa4
3
- size 23771060
 
 
 
 
train/pgns-run1-test80-20220404-1854.pgn_part_3.pgn.zst DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:8e85bcfd48083b8a0ade5b8f0b6774adb28e42d46c4ba152d60d0f045aac7825
3
- size 14511122