|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
from datasets import GeneratorBasedBuilder, DatasetInfo, SplitGenerator, Split, Features, Value, Array2D, DownloadManager |
|
|
|
|
|
from pathlib import Path |
|
from datasets import BuilderConfig, Version |
|
|
|
class ChessPGNConfig(BuilderConfig): |
|
def __init__( self, |
|
name: str = "default", |
|
version: Version = Version("1.0.0"), |
|
description: str = "PGN chess shards", |
|
data_dir: str = None, |
|
data_files: dict = None, |
|
**kwargs): |
|
super().__init__( |
|
name=name, |
|
version=version, |
|
description=description, |
|
data_dir=data_dir, |
|
data_files=data_files or {}, |
|
**kwargs |
|
) |
|
class ChessPGNDataset(GeneratorBasedBuilder): |
|
BUILDER_CONFIG_CLASS = ChessPGNConfig |
|
BUILDER_CONFIGS = [ |
|
ChessPGNConfig( |
|
name="default", |
|
data_files={ |
|
"train": [str(p) for p in Path("train").glob("*.pgn")], |
|
"test": [str(p) for p in Path("test").glob("*.pgn")], |
|
}, |
|
) |
|
] |
|
|
|
DEFAULT_WRITER_BATCH_SIZE = 512 |
|
|
|
def _info(self): |
|
return DatasetInfo( |
|
features=Features({ |
|
"state": Array2D((8,8), dtype="int8"), |
|
"action": Value("int16"), |
|
"result": Value("int8"), |
|
}), |
|
) |
|
|
|
def _split_generators(self, dl_manager: DownloadManager): |
|
|
|
train_files = dl_manager.download(self.config.data_files["train"]) |
|
test_files = dl_manager.download(self.config.data_files["test"]) |
|
return [ |
|
SplitGenerator(name=Split.TRAIN, gen_kwargs={"shards": train_files}), |
|
SplitGenerator(name=Split.TEST, gen_kwargs={"shards": test_files}), |
|
] |
|
|
|
def _generate_examples(self, shards): |
|
import chess.pgn, numpy as np |
|
from adversarial_gym.chess_env import ChessEnv |
|
|
|
uid = 0 |
|
for path in sorted(shards): |
|
with open(path) as f: |
|
while (game := chess.pgn.read_game(f)) is not None: |
|
board = game.board() |
|
base = {"1-0":1,"0-1":-1}.get(game.headers["Result"],0) |
|
for move in game.mainline_moves(): |
|
state = ChessEnv.get_piece_configuration(board) |
|
state = state if board.turn else -state |
|
action = ChessEnv.move_to_action(move) |
|
result = base * (-1 if board.turn == 0 else 1) |
|
yield uid, { |
|
"state": state.astype("int8"), |
|
"action": np.int16(action), |
|
"result": np.int8(result), |
|
} |
|
uid += 1 |
|
board.push(move) |
|
|