Download play.py from xLeverd/chess: direct link, hf CLI and curl.
- Browser
- Download file 5.75 kB
-
https://huggingface.co/datasets/xLeverd/chess/resolve/main/play.py
- Command line
-
hf download hf://datasets/xLeverd/chess/play.py
-
curl -L -o play.py https://huggingface.co/datasets/xLeverd/chess/resolve/main/play.py
5.75 kB
| #!/usr/bin/env python3 | |
| """Play the distilled model against Stockfish levels.""" | |
| from __future__ import annotations | |
| import argparse | |
| import time | |
| from pathlib import Path | |
| import chess | |
| import chess.pgn | |
| import numpy as np | |
| import torch | |
| from model import ChessNet | |
| from prepare import encode_board, legal_bits | |
| from stockfish_engine import StockfishEngine, DEFAULT_PATH | |
| class ModelPlayer: | |
| def __init__(self, checkpoint: str, device: str = "cuda", search: str = "value"): | |
| self.device = torch.device(device if torch.cuda.is_available() else "cpu") | |
| payload = torch.load(checkpoint, map_location=self.device, weights_only=False) | |
| self.model = ChessNet( | |
| channels=payload.get("channels", 128), | |
| blocks=payload.get("blocks", 10), | |
| ).to(self.device).eval() | |
| self.model.load_state_dict(payload["model"]) | |
| self.search = search | |
| def _encode(self, board: chess.Board): | |
| planes = torch.from_numpy(encode_board(board)).float().unsqueeze(0) | |
| planes[:, 18] /= 100.0 | |
| mask = np.unpackbits(legal_bits(board)).astype(np.bool_) | |
| legal = torch.from_numpy(mask).unsqueeze(0) | |
| return planes.to(self.device), legal.to(self.device) | |
| def choose(self, board: chess.Board) -> chess.Move | None: | |
| legal_moves = list(board.legal_moves) | |
| if not legal_moves: | |
| return None | |
| planes, legal = self._encode(board) | |
| with torch.autocast("cuda", dtype=torch.float16, enabled=(self.device.type == "cuda")): | |
| logits, value, _ = self.model(planes, legal) | |
| logits = logits.float()[0] | |
| if self.search == "policy": | |
| index = int(torch.argmax(logits)) | |
| candidates = [m for m in legal_moves | |
| if m.from_square * 64 + m.to_square == index] | |
| return _prefer_promotion(candidates) | |
| # One-ply value search over all legal moves, batched. | |
| child_planes = [] | |
| child_policy = [] | |
| for move in legal_moves: | |
| board.push(move) | |
| child_planes.append(encode_board(board)) | |
| child_policy.append(float(logits[move.from_square * 64 + move.to_square])) | |
| board.pop() | |
| batch = torch.from_numpy(np.stack(child_planes)).float() | |
| batch[:, 18] /= 100.0 | |
| batch = batch.to(self.device) | |
| with torch.autocast("cuda", dtype=torch.float16, enabled=(self.device.type == "cuda")): | |
| _, child_values, _ = self.model(batch) | |
| scores = -child_values.float() + 0.05 * torch.tensor(child_policy, device=self.device) | |
| best = int(torch.argmax(scores)) | |
| return legal_moves[best] | |
| def _prefer_promotion(moves: list[chess.Move]) -> chess.Move | None: | |
| if not moves: | |
| return None | |
| for move in moves: | |
| if move.promotion == chess.QUEEN: | |
| return move | |
| return moves[0] | |
| def play_game(model: ModelPlayer, sf: StockfishEngine, model_white: bool, max_plies: int): | |
| board = chess.Board() | |
| while not board.is_game_over(claim_draw=True) and len(board.move_stack) < max_plies: | |
| model_turn = (board.turn == chess.WHITE) == model_white | |
| if model_turn: | |
| move = model.choose(board) | |
| else: | |
| uci = sf.best_move(board) | |
| move = chess.Move.from_uci(uci) if uci not in ("(none)", "0000") else None | |
| if move is None or move not in board.legal_moves: | |
| break | |
| board.push(move) | |
| return board | |
| def main() -> None: | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument("--model", default="checkpoints/chessnet.pt") | |
| parser.add_argument("--games", type=int, default=10) | |
| parser.add_argument("--sf-skill", type=int, default=5) | |
| parser.add_argument("--sf-movetime", type=int, default=100) | |
| parser.add_argument("--search", choices=("policy", "value"), default="value") | |
| parser.add_argument("--max-plies", type=int, default=200) | |
| parser.add_argument("--stockfish", default=DEFAULT_PATH) | |
| parser.add_argument("--pgn", default="checkpoints/model_vs_sf.pgn") | |
| args = parser.parse_args() | |
| model = ModelPlayer(args.model, search=args.search) | |
| sf = StockfishEngine(path=args.stockfish, skill=args.sf_skill, | |
| movetime_ms=args.sf_movetime) | |
| wins = draws = losses = 0 | |
| games = [] | |
| started = time.time() | |
| try: | |
| for i in range(1, args.games + 1): | |
| model_white = i % 2 == 1 | |
| sf.new_game() | |
| board = play_game(model, sf, model_white, args.max_plies) | |
| outcome = board.outcome(claim_draw=True) | |
| if outcome is None: | |
| result = "*" | |
| else: | |
| result = outcome.result() | |
| if result == "1/2-1/2" or result == "*": | |
| draws += 1 | |
| elif (result == "1-0") == model_white: | |
| wins += 1 | |
| else: | |
| losses += 1 | |
| print(f"game {i}: {'white' if model_white else 'black'} {result}", flush=True) | |
| game = chess.pgn.Game.from_board(board) | |
| game.headers["Event"] = f"AChess vs SF{args.sf_skill}" | |
| game.headers["White"] = "AChess" if model_white else f"SF{args.sf_skill}" | |
| game.headers["Black"] = f"SF{args.sf_skill}" if model_white else "AChess" | |
| game.headers["Result"] = result | |
| games.append(game) | |
| finally: | |
| sf.close() | |
| print(f"summary: {wins}W {draws}D {losses}L in {time.time() - started:.1f}s") | |
| Path(args.pgn).parent.mkdir(parents=True, exist_ok=True) | |
| with open(args.pgn, "w", encoding="utf-8") as handle: | |
| for game in games: | |
| handle.write(str(game) + "\n\n") | |
| print("pgn:", args.pgn) | |
| if __name__ == "__main__": | |
| main() | |