File size: 4,741 Bytes
1289ac1
26d9e5b
62e368e
 
 
 
 
 
 
 
 
f57ac4c
62e368e
d42df3a
e799ee4
1289ac1
 
 
0c1723c
33d949e
e799ee4
26d9e5b
0c1723c
 
62e368e
0c1723c
d42df3a
 
 
f57ac4c
d42df3a
62e368e
0c1723c
 
38cb927
44049cc
 
9d1c4bb
26d9e5b
38cb927
 
 
9d1c4bb
26d9e5b
 
 
39b6876
38cb927
 
62e368e
38cb927
 
 
 
 
 
 
 
 
 
d42df3a
 
 
 
 
 
 
 
 
 
 
 
5c56160
d42df3a
 
 
 
 
5c56160
 
d42df3a
 
5c56160
 
 
 
 
 
 
d42df3a
 
 
0c1723c
62e368e
b6473ab
62e368e
9d1c4bb
1289ac1
 
 
 
 
 
d42df3a
 
 
 
 
 
 
 
 
1289ac1
 
 
f57ac4c
1289ac1
d42df3a
 
 
f57ac4c
d42df3a
1289ac1
 
 
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
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)