import io import logging from datasets import ( GeneratorBasedBuilder, DatasetInfo, SplitGenerator, Split, DownloadManager, Features, Value, Array2D, Sequence, ) import chess from adversarial_gym.chess_env import ChessEnv import zstandard as zstd class ChessPGNDataset(GeneratorBasedBuilder): VERSION = "0.0.1" def _info(self): return DatasetInfo( description="Chess positions + moves + results, streamed from PGN shards", features=Features({ "state": Array2D((8,8), dtype="int8"), "action": Value("int16"), "best_action": Value("int16"), # -1 if not available "legal_actions": Sequence(Value("int16")), "result": Value("float32"), }) ) def _split_generators(self, dl_manager: DownloadManager): from pathlib import Path import os if self.config.data_dir: repo_root = Path(self.config.data_dir) train_files = [repo_root / 'train' / f for f in os.listdir(repo_root / 'train')] test_files = [repo_root / 'test' / f for f in os.listdir(repo_root / 'test')] elif self.config.data_files: train_files = self.config.data_files["train"] test_files = self.config.data_files["test"] train_paths = dl_manager.download(train_files) test_paths = dl_manager.download(test_files) return [ SplitGenerator( name=Split.TRAIN, gen_kwargs={"shards": train_paths}, ), SplitGenerator( name=Split.TEST, gen_kwargs={"shards": test_paths}, ), ] @staticmethod def _parse_comment(comment, board): """Parse a move comment like '-0.2779' or '0.52 e2e4'. Returns (q_val or None, best_action or -1). q_val is float in [-1, 1] relative to side-to-move. best_action is the action index of the best move, or -1 if absent.""" if not comment: return None, -1 parts = comment.split() if not parts: return None, -1 # First token must be a number in [-1, 1] first = parts[0] try: q_val = float(first) except ValueError: return None, -1 if not (-1.0 <= q_val <= 1.0): return None, -1 if len(parts) < 2: return q_val, -1 # Second token is a UCI best move — must be valid and legal try: best_move = chess.Move.from_uci(parts[1]) if best_move not in board.legal_moves: return q_val, -1 except Exception: return q_val, -1 best_action = int(ChessEnv.move_to_action(best_move)) return q_val, best_action def _generate_examples(self, shards): import chess.pgn uid = 0 for path in shards: decompressor = zstd.ZstdDecompressor() with open(path, "rb") as compressed: with decompressor.stream_reader(compressed) as reader: text_stream = io.TextIOWrapper(reader, encoding='utf-8') while (game := chess.pgn.read_game(text_stream)) is not None: board = game.board() header_result = {"1-0":1,"0-1":-1}.get(game.headers.get("Result",""), 0) for node in game.mainline(): move = node.move # Parse annotated Q-value and best move from comment q_val, best_action = self._parse_comment(node.comment, board) if q_val is not None: result = q_val else: result = float(header_result * (-1 if board.turn == 0 else 1)) state = ChessEnv.get_piece_configuration(board) state = state if board.turn else -state action = ChessEnv.move_to_action(move) legal = [int(ChessEnv.move_to_action(m)) for m in board.legal_moves] yield uid, { "state": state.astype("int8"), "action": int(action), "best_action": int(best_action), "legal_actions": legal, "result": float(result), } uid += 1 board.push(move)