chessbenchmate / dataset.py
joshuakgao's picture
Update dataset.py
8bf5158 verified
"""Chessbench dataset of records with a fen board position, a uci move, a win probability after the uci move is made, and a checkmate status."""
import bisect
from pathlib import Path
from typing import Dict, List, Tuple
from torch.utils.data import Dataset
from athena.datasets.chessbenchmate.utils import constants
from athena.datasets.chessbenchmate.utils.bagz import BagReader
class ChessbenchDataset(Dataset):
"""Chessbench dataset of records with a fen board position, a uci move, a win probability after the uci move is made, and a checkmate status."""
def __init__(self, dir: str, mode: str = "train"):
"""Initialize the ChessbenchDataset.
Args:
dir: Root directory containing train/test subdirectories
mode: Either "train" or "test"
"""
self.dir = Path(dir)
self.mode = mode
self.data_dir = self.dir / mode
# Collect and cache all bags with their lengths
self.bags: List[Tuple[Path, int]] = []
self._cumulative_lengths: List[int] = []
self._open_readers: Dict[Path, BagReader] = {} # Cache for open readers
total_records = 0
# Find all bag files in the specified directory
for bag_path in sorted(self.data_dir.glob("action_value*_data.bag")):
bag_reader = BagReader(str(bag_path))
bag_length = len(bag_reader)
self.bags.append((bag_path, bag_length))
total_records += bag_length
self._cumulative_lengths.append(total_records)
self._open_readers[bag_path] = bag_reader
self._total_length = total_records
if len(self.bags) == 0:
raise ValueError(f"No .bag files found in {self.data_dir}")
def __len__(self):
"""Returns the total number of records in the dataset."""
return self._total_length
def __getitem__(self, idx) -> Tuple[str, str, float, str | int]:
"""Gets a record from the dataset.
Args:
idx: The index of the record to retrieve.
Returns:
tuple: (fen_string, move_uci, win_probability)
win_probability will be None for training data
"""
if idx < 0 or idx >= len(self):
raise IndexError(f"Index {idx} out of range [0, {len(self)})")
# Find which bag contains this index
bag_idx = bisect.bisect_right(self._cumulative_lengths, idx)
# Calculate index within the specific bag
if bag_idx > 0:
idx_in_bag = idx - self._cumulative_lengths[bag_idx - 1]
else:
idx_in_bag = idx
# Get or create the reader
bag_path, _ = self.bags[bag_idx]
if bag_path not in self._open_readers:
self._open_readers[bag_path] = BagReader(str(bag_path))
# Get and parse the record
record = self._open_readers[bag_path][idx_in_bag]
fen, move, win_prob, mate = constants.CODERS["action_value_with_mate"].decode(record)
return fen, move, win_prob, mate
@property
def num_bags(self) -> int:
"""Return the number of bag files in this dataset."""
return len(self.bags)
if __name__ == "__main__":
# Example usage
dataset = ChessbenchDataset(dir="src/athena/datasets/chessbenchmate/data", mode="train")
print(f"Total records: {len(dataset)}")
print(f"Number of bags: {dataset.num_bags}")
for i in range(len(dataset)):
fen, move, win_prob, mate = dataset[i]
print(f"Record {i}: {fen}, {move}, {win_prob}, {mate}", end="\r")