Public repository: timo / schach

Reader

Ein aufgeräumtes Schach-Programm für GNOME

schach / tools / maia_onnx_vergleich.py · 7.3 KB · at 3c63b1d52560 · raw

Outline: 10 definitions
1
"""Vergleich: Maia-3 im Original (PyTorch, maia3) gegen den ONNX-Export (schach.maia_onnx).
2
3
Stellungen: alle Kurslinien aus schach/kurse plus Partien, die Maia (PyTorch) gegen sich
4
selbst spielt (bis ins Endspiel). Für jede Stellung und mehrere Elo-Stufen werden die vollen
5
Zugverteilungen verglichen: Top-1 gleich, Top-5 gleich (als Menge und Reihenfolge),
6
größte Abweichung einer Zugwahrscheinlichkeit und der WDL-Werte.
7
8
Braucht maia3 + PyTorch (nur auf dem Entwicklerrechner):
9
10
    python tools/maia_onnx_vergleich.py [--games 6] [--seed 1]
11
"""
12
13
import argparse
14
import glob
15
import os
16
import random
17
import sys
18
from collections import deque
19
20
import chess
21
import chess.pgn
22
import numpy as np
23
import torch
24
25
sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
26
27
from maia3.dataset import get_historical_tokens, get_legal_moves_mask, tokenize_board  # noqa: E402
28
from maia3.model_registry import apply_model_config, resolve_checkpoint_path, resolve_model_spec  # noqa: E402
29
from maia3.uci import load_model, parse_args  # noqa: E402
30
from maia3.utils import get_all_possible_moves  # noqa: E402
31
32
from schach import maia_onnx  # noqa: E402
33
34
ELOS = [(1100, 1100), (1500, 1500), (1900, 1900), (2300, 2300), (1200, 2000)]
35
36
37
class Torch:
38
    def __init__(self):
39
        device = "cuda" if torch.cuda.is_available() else "cpu"  # Referenz rechnet in fp32, auch auf der GPU
40
        cfg = parse_args(["--model", "79m", "--use-uci-history", "--device", device, "--no-use-amp"])
41
        spec = resolve_model_spec("79m")
42
        apply_model_config(cfg, spec)
43
        cfg.checkpoint_path = resolve_checkpoint_path(spec, local_files_only=True)
44
        self.cfg = cfg
45
        self.model = load_model(cfg)
46
        self.index = {m: i for i, m in enumerate(get_all_possible_moves())}
47
        assert get_all_possible_moves() == maia_onnx.ALL_MOVES, "Zugvokabular weicht ab"
48
49
    @torch.no_grad()
50
    def policy(self, boards, self_elo, oppo_elo):
51
        """boards: Stellungen der Partie bis jetzt (älteste zuerst) → (Wahrscheinlichkeiten, WDL-Logits)."""
52
        history = deque((tokenize_board(b) for b in boards[-8:]), maxlen=8)
53
        tokens = get_historical_tokens(history, self.cfg, 0.0, 0.0, 0.0, 0.0).unsqueeze(0)
54
        dev = self.cfg.device
55
        logits, value, _ = self.model(tokens.to(dev), torch.tensor([self_elo], device=dev),
56
                                      torch.tensor([oppo_elo], device=dev))
57
        logits, value = logits.cpu(), value.cpu()
58
        mask = get_legal_moves_mask(boards[-1], self.index)
59
        logits = logits[0].float().masked_fill(~mask, float("-inf"))
60
        return torch.softmax(logits, -1).double().numpy(), value[0].double().numpy()
61
62
63
class Onnx:
64
    def __init__(self, path=None):
65
        self.model = maia_onnx.Model(path or maia_onnx.model_path())
66
67
    def policy(self, boards, self_elo, oppo_elo):
68
        history = deque((maia_onnx.tokenize(b) for b in boards[-8:]), maxlen=8)
69
        logits, value = self.model.run([history], [self_elo], [oppo_elo])
70
        legal = maia_onnx.legal_index(boards[-1])
71
        full = np.full(len(maia_onnx.ALL_MOVES), -np.inf)
72
        idx = np.fromiter(legal, dtype=np.int64)
73
        full[idx] = logits[0, idx]
74
        return maia_onnx._softmax(full), value[0].astype(np.float64)
75
76
77
def course_lines():
78
    """Jede Kurslinie als Zugfolge (Hauptvariante und alle Varianten bis zum Blatt)."""
79
    lines = []
80
    for path in sorted(glob.glob(os.path.join(os.path.dirname(__file__), "..", "schach", "kurse", "*.pgn"))):
81
        with open(path, encoding="utf-8") as fh:
82
            while (game := chess.pgn.read_game(fh)) is not None:
83
                stack = [(game, [])]
84
                while stack:
85
                    node, moves = stack.pop()
86
                    if not node.variations:
87
                        lines.append(moves)
88
                    for child in node.variations:
89
                        stack.append((child, moves + [child.move]))
90
    return lines
91
92
93
def selfplay(torch_model, rng, count):
94
    games = []
95
    for _ in range(count):
96
        board, moves = chess.Board(), []
97
        elo = rng.choice([1100, 1500, 1900, 2300])
98
        while not board.is_game_over() and len(moves) < 160:
99
            boards = _boards(moves)
100
            probs, _ = torch_model.policy(boards, elo, elo)
101
            idx = rng.choices(range(len(probs)), weights=probs.tolist())[0]
102
            move = maia_onnx.legal_index(board)[idx]
103
            board.push(move)
104
            moves.append(move)
105
        games.append(moves)
106
    return games
107
108
109
def _boards(moves):
110
    board = chess.Board()
111
    boards = [board.copy()]
112
    for move in moves:
113
        board.push(move)
114
        boards.append(board.copy())
115
    return boards
116
117
118
def main():
119
    parser = argparse.ArgumentParser()
120
    parser.add_argument("--games", type=int, default=6, help="Selbstspiel-Partien zusätzlich zu den Kursen")
121
    parser.add_argument("--seed", type=int, default=1)
122
    parser.add_argument("--every", type=int, default=3, help="nur jede n-te Stellung einer Partie prüfen")
123
    parser.add_argument("--model-path", help="ONNX-Datei statt der, die schach.maia_onnx wählt")
124
    args = parser.parse_args()
125
    rng = random.Random(args.seed)
126
127
    ref, onnx = Torch(), Onnx(args.model_path)
128
    print("ONNX-Modell:", args.model_path or maia_onnx.model_path())
129
    sequences = course_lines() + selfplay(ref, rng, args.games)
130
131
    seen, stats = set(), dict(n=0, top1=0, top5set=0, top5order=0)
132
    worst_p, worst_wdl, misses = 0.0, 0.0, []
133
    for moves in sequences:
134
        boards = _boards(moves)
135
        for ply in range(0, len(boards), args.every):
136
            prefix = boards[:ply + 1]
137
            key = tuple(m.uci() for m in moves[:ply])
138
            if key in seen or prefix[-1].is_game_over():
139
                continue
140
            seen.add(key)
141
            for self_elo, oppo_elo in ELOS:
142
                p_ref, v_ref = ref.policy(prefix, self_elo, oppo_elo)
143
                p_onx, v_onx = onnx.policy(prefix, self_elo, oppo_elo)
144
                top_ref = list(np.argsort(-p_ref, kind="stable")[:5])
145
                top_onx = list(np.argsort(-p_onx, kind="stable")[:5])
146
                stats["n"] += 1
147
                stats["top1"] += top_ref[0] == top_onx[0]
148
                stats["top5set"] += set(top_ref) == set(top_onx)
149
                stats["top5order"] += top_ref == top_onx
150
                worst_p = max(worst_p, float(np.max(np.abs(p_ref - p_onx))))
151
                wdl_ref = torch.softmax(torch.tensor(v_ref), -1).numpy()
152
                wdl_onx = maia_onnx._softmax(v_onx)
153
                worst_wdl = max(worst_wdl, float(np.max(np.abs(wdl_ref - wdl_onx))))
154
                if top_ref[0] != top_onx[0]:
155
                    misses.append((prefix[-1].fen(), self_elo, oppo_elo,
156
                                   float(p_ref[top_ref[0]]), float(p_ref[top_onx[0]])))
157
158
    n = stats["n"]
159
    print(f"Stellungen × Elo-Stufen: {n} ({len(seen)} Stellungen)")
160
    print(f"Top-1 gleich:            {stats['top1']}/{n}")
161
    print(f"Top-5 gleiche Menge:     {stats['top5set']}/{n}")
162
    print(f"Top-5 gleiche Reihenfolge: {stats['top5order']}/{n}")
163
    print(f"größte Abweichung Zugwahrscheinlichkeit: {worst_p:.2e}")
164
    print(f"größte Abweichung WDL:                   {worst_wdl:.2e}")
165
    for fen, se, oe, p1, p2 in misses[:10]:
166
        print(f"  Top-1 anders: {fen} (Elo {se}/{oe}): PyTorch {p1:.4f} vs. ONNX-Wahl {p2:.4f}")
167
    return 0 if stats["top1"] == n else 1
168
169
170
if __name__ == "__main__":
171
    sys.exit(main())