File size: 5,752 Bytes
a068a40
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
#!/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)

    @torch.inference_mode()
    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()