feat(engines): run Maia-3 with ONNX Runtime instead of PyTorch
public
feat(engines): run Maia-3 with ONNX Runtime instead of PyTorch Own UCI engine (schach.maia_onnx) with the same options as maia3-uci, using bqrio's ONNX export of Maia3-79M with move history (pinned revision). The fp16 download (156 MB) is rewritten once to fp32 with the onnx package: on the CPU 0.17 s per move instead of 1.84 s (fp16) or 0.44 s (PyTorch). Falls back to maia3-uci without onnxruntime. tools/maia_onnx_vergleich.py compares against the PyTorch original: best move identical in 1904/1905 cases, max probability error 1.5e-3. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
| Changeset | d50f901fa346470c0e9ee81e1230e406e364b1eb |
|---|---|
| Author (claimed) | Timo Stolz <timo.stolz@nullachtvierzehn.de>, |
| Parents | 6458a91ca1fc |
| Children | 72f34d142b74 |
| Pushlog | by timo via ssh by timo via ssh |
modified README.md +11 −2
| @@ -86,7 +86,15 @@ Schlichtes GNOME-Schachprogramm (Python, | ||
| 86 | 86 | ./schach.sh |
| 87 | 87 | |
| 88 | 88 | Abhängigkeiten: `python-gobject`, `libadwaita`, `librsvg`, `python-chess`, |
| 89 | -`stockfish`, `maia3-git` (AUR), `python-requests`, `python-keyring`. | |
| 89 | +`stockfish`, `python-requests`, `python-keyring`, und für Maia-3 `onnxruntime-cpu`, | |
| 90 | +`python-huggingface-hub`, `python-numpy` sowie `python-onnx` (wandelt das Modell einmal nach | |
| 91 | +fp32 um – ohne rechnet Maia auf der CPU rund zehnmal langsamer). | |
| 92 | + | |
| 93 | +Maia-3 läuft über ONNX Runtime statt PyTorch (`schach/maia_onnx.py`): Das Modell (ONNX-Export | |
| 94 | +von Maia3-79M mit Zughistorie, `bqrio/maia3-onnx`, 156 MB) lädt beim ersten Start von Hugging | |
| 95 | +Face. Ohne onnxruntime nimmt das Programm `maia3-uci` (AUR `maia3-git`, PyTorch), falls | |
| 96 | +installiert; `SCHACH_MAIA=torch` bzw. `=onnx` erzwingt eins von beiden. Abgleich mit dem | |
| 97 | +Original: `python tools/maia_onnx_vergleich.py` (braucht maia3 und PyTorch). | |
| 90 | 98 | Optional für „PDF über LaTeX“: `texlive-games` (`xskak`) und `pdflatex`. |
| 91 | 99 | |
| 92 | 100 | Tests: |
| @@ -130,5 +138,6 @@ Ins App-Menü aufnehmen: | ||
| 130 | 138 | |
| 131 | 139 | ## Lizenz |
| 132 | 140 | |
| 133 | -AGPL-3.0-or-later, siehe `LICENSE` (passend zu Maia-3 unter AGPL-3 und Stockfish unter GPL-3). | |
| 141 | +AGPL-3.0-or-later, siehe `LICENSE` (passend zu Maia-3 unter AGPL-3 – Code, Gewichte und der | |
| 142 | +ONNX-Export von bqrio – und Stockfish unter GPL-3). | |
| 134 | 143 | Geplante Erweiterungen: `ROADMAP.md`. |
modified schach/app.py +2 −2
| @@ -19,7 +19,7 @@ from . import annotate, clipboard, liche | ||
| 19 | 19 | from .board import BoardView, available_themes # noqa: E402 |
| 20 | 20 | from .movelist import MoveList # noqa: E402 |
| 21 | 21 | from .prefs import Preferences # noqa: E402 |
| 22 | -from .engines import MAIA_CMD, STOCKFISH_CMD, EngineWorker, maia_candidates, maia_move # noqa: E402 | |
| 22 | +from .engines import MAIA_CMD, MAIA_CWD, STOCKFISH_CMD, EngineWorker, maia_candidates, maia_move # noqa: E402 | |
| 23 | 23 | from .threat import null_board, threat_job # noqa: E402 |
| 24 | 24 | from .online import OnlineMixin # noqa: E402 |
| 25 | 25 | from .puzzles import PuzzleMixin # noqa: E402 |
| @@ -1807,7 +1807,7 @@ class SchachApp(Adw.Application): | ||
| 1807 | 1807 | set_book_paths(load_settings().get("books", [])) |
| 1808 | 1808 | # eigene Symbole (z. B. das Schwert für Drohungen), eingefärbt wie die GNOME-Symbole |
| 1809 | 1809 | Gtk.IconTheme.get_for_display(Gdk.Display.get_default()).add_search_path(ICON_DIR) |
| 1810 | - self.maia = EngineWorker(MAIA_CMD, on_ready=self._on_maia_ready) | |
| 1810 | + self.maia = EngineWorker(MAIA_CMD, on_ready=self._on_maia_ready, cwd=MAIA_CWD) | |
| 1811 | 1811 | self.stockfish = EngineWorker( |
| 1812 | 1812 | STOCKFISH_CMD, options={"Threads": min(8, os.cpu_count() or 2), "Hash": 256} |
| 1813 | 1813 | ) |
modified schach/engines.py +30 −3
| @@ -1,15 +1,41 @@ | ||
| 1 | 1 | """UCI-Engines in eigenen Threads, Ergebnisse kommen über GLib.idle_add zurück.""" |
| 2 | 2 | |
| 3 | +import importlib.util | |
| 4 | +import os | |
| 3 | 5 | import queue |
| 6 | +import shutil | |
| 4 | 7 | import subprocess |
| 8 | +import sys | |
| 5 | 9 | import threading |
| 6 | 10 | |
| 7 | 11 | import chess |
| 8 | 12 | import chess.engine |
| 9 | 13 | from gi.repository import GLib |
| 10 | 14 | |
| 11 | -MAIA_CMD = ["maia3-uci", "--model", "79m", "--use-uci-history"] | |
| 12 | 15 | STOCKFISH_CMD = ["stockfish"] |
| 16 | +MAIA3_UCI_CMD = ["maia3-uci", "--model", "79m", "--use-uci-history"] # Original mit PyTorch | |
| 17 | +_PACKAGE_PARENT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | |
| 18 | + | |
| 19 | + | |
| 20 | +def maia_command(prefer=None): | |
| 21 | + """(Befehl, Arbeitsverzeichnis) für Maia-3. | |
| 22 | + | |
| 23 | + Bevorzugt die eigene ONNX-Engine (``schach.maia_onnx``, braucht nur onnxruntime); | |
| 24 | + ohne onnxruntime das Original ``maia3-uci`` (PyTorch). ``SCHACH_MAIA=torch`` bzw. | |
| 25 | + ``=onnx`` erzwingt eine von beiden. | |
| 26 | + """ | |
| 27 | + prefer = prefer or os.environ.get("SCHACH_MAIA", "") | |
| 28 | + onnx = [sys.executable, "-m", "schach.maia_onnx"], _PACKAGE_PARENT | |
| 29 | + if prefer == "onnx": | |
| 30 | + return onnx | |
| 31 | + if prefer != "torch" and importlib.util.find_spec("onnxruntime") is not None: | |
| 32 | + return onnx | |
| 33 | + if shutil.which(MAIA3_UCI_CMD[0]): | |
| 34 | + return MAIA3_UCI_CMD, None | |
| 35 | + return onnx # meldet dann beim Start, was fehlt | |
| 36 | + | |
| 37 | + | |
| 38 | +MAIA_CMD, MAIA_CWD = maia_command() | |
| 13 | 39 | |
| 14 | 40 | |
| 15 | 41 | class EngineWorker: |
| @@ -19,8 +45,9 @@ class EngineWorker: | ||
| 19 | 45 | läuft danach im GTK-Hauptthread. |
| 20 | 46 | """ |
| 21 | 47 | |
| 22 | - def __init__(self, cmd, options=None, on_ready=None): | |
| 48 | + def __init__(self, cmd, options=None, on_ready=None, cwd=None): | |
| 23 | 49 | self._cmd = cmd |
| 50 | + self._cwd = cwd | |
| 24 | 51 | self._options = options or {} |
| 25 | 52 | self._on_ready = on_ready |
| 26 | 53 | self._jobs = queue.Queue() |
| @@ -31,7 +58,7 @@ class EngineWorker: | ||
| 31 | 58 | engine = None |
| 32 | 59 | try: |
| 33 | 60 | engine = chess.engine.SimpleEngine.popen_uci( |
| 34 | - self._cmd, timeout=300, stderr=subprocess.DEVNULL | |
| 61 | + self._cmd, timeout=300, stderr=subprocess.DEVNULL, cwd=self._cwd | |
| 35 | 62 | ) |
| 36 | 63 | if self._options: |
| 37 | 64 | engine.configure(self._options) |
added schach/maia_onnx.py +356 −0
| @@ -0,0 +1,356 @@ | ||
| 1 | +"""Maia-3 als UCI-Engine mit ONNX Runtime statt PyTorch. | |
| 2 | + | |
| 3 | +Gleiches UCI-Verhalten wie ``maia3-uci --model 79m --use-uci-history`` (Optionen Elo, | |
| 4 | +SelfElo, OppoElo, Temperature, TopP, MultiPV; Kandidaten als MultiPV-Zeilen mit WDL), | |
| 5 | +aber ohne PyTorch: ONNX Runtime ist 17–28 MB statt 130–540 MB, das Modell in fp16 | |
| 6 | +156 statt 316 MB, und ONNX ist reines Datenformat (``.pt`` ist ein Pickle). | |
| 7 | + | |
| 8 | +Kodierung von Stellung und Zügen nach CSSLab/maia3 (``dataset.py``, ``utils.py``, | |
| 9 | +``uci.py``; AGPL-3.0). Modell: ONNX-Export von bqrio (AGPL-3.0, Ableitung von | |
| 10 | +UofTCSSLab/Maia3-79M), auf einen Commit festgelegt. | |
| 11 | + | |
| 12 | +Modell: fp16 herunterladen (156 MB), einmal nach fp32 umschreiben (braucht das Paket | |
| 13 | +``onnx``) – auf der CPU 0,17 s statt 1,8 s je Zug, gleiche Züge. | |
| 14 | + | |
| 15 | +Start: ``python -m schach.maia_onnx`` (lädt das Modell beim ersten ``isready`` von | |
| 16 | +Hugging Face bzw. aus dessen Cache) oder ``--model-path DATEI``. | |
| 17 | +""" | |
| 18 | + | |
| 19 | +import argparse | |
| 20 | +import os | |
| 21 | +import sys | |
| 22 | +from collections import deque | |
| 23 | + | |
| 24 | +import chess | |
| 25 | +import numpy as np | |
| 26 | + | |
| 27 | +MODEL_REPO = "bqrio/maia3-onnx" | |
| 28 | +MODEL_FILE = "maia3-79m.fp16.history.onnx" | |
| 29 | +MODEL_REVISION = "923df9a2e9396b54a09b168bb858ebbd5e5b76bc" | |
| 30 | +HISTORY = 8 | |
| 31 | +DEFAULT_ELO = 1500 | |
| 32 | + | |
| 33 | + | |
| 34 | +# --- Kodierung (wie maia3) --------------------------------------------------- | |
| 35 | + | |
| 36 | +def _all_moves(): | |
| 37 | + """Zugvokabular: 64×64 Von-Nach-Paare, dann 256 Umwandlungen von Reihe 7 nach 8.""" | |
| 38 | + names = [chess.square_name(s) for s in chess.SQUARES] | |
| 39 | + moves = [a + b for a in names for b in names] | |
| 40 | + moves += [f"{f}7{t}8{p}" for f in "abcdefgh" for t in "abcdefgh" for p in "qrbn"] | |
| 41 | + return moves | |
| 42 | + | |
| 43 | + | |
| 44 | +ALL_MOVES = _all_moves() | |
| 45 | +MOVE_INDEX = {m: i for i, m in enumerate(ALL_MOVES)} | |
| 46 | + | |
| 47 | + | |
| 48 | +def _mirror_uci(uci): | |
| 49 | + """Reihen spiegeln: Das Modell sieht die Stellung immer aus Sicht der Seite am Zug.""" | |
| 50 | + return uci[0] + str(9 - int(uci[1])) + uci[2] + str(9 - int(uci[3])) + uci[4:] | |
| 51 | + | |
| 52 | + | |
| 53 | +def tokenize(board): | |
| 54 | + """(64, 12): je Feld ein One-Hot über 6 eigene + 6 gegnerische Figurenarten.""" | |
| 55 | + tokens = np.zeros((64, 12), dtype=np.float32) | |
| 56 | + if board.turn == chess.BLACK: | |
| 57 | + board = board.mirror() | |
| 58 | + for square, piece in board.piece_map().items(): | |
| 59 | + tokens[square, piece.piece_type - 1 + (6 if piece.color == chess.BLACK else 0)] = 1.0 | |
| 60 | + return tokens | |
| 61 | + | |
| 62 | + | |
| 63 | +def history_tensor(history): | |
| 64 | + """(64, 96): acht Stellungen, älteste zuerst; zu kurze Partien vorne mit der ersten aufgefüllt.""" | |
| 65 | + slots = list(history) | |
| 66 | + slots = [slots[0]] * (HISTORY - len(slots)) + slots | |
| 67 | + return np.concatenate(slots, axis=1) | |
| 68 | + | |
| 69 | + | |
| 70 | +def legal_index(board): | |
| 71 | + """{Vokabular-Index: Zug} für alle legalen Züge.""" | |
| 72 | + found = {} | |
| 73 | + for move in board.legal_moves: | |
| 74 | + uci = move.uci() if board.turn == chess.WHITE else _mirror_uci(move.uci()) | |
| 75 | + index = MOVE_INDEX.get(uci) | |
| 76 | + if index is not None: | |
| 77 | + found[index] = move | |
| 78 | + return found | |
| 79 | + | |
| 80 | + | |
| 81 | +def _softmax(x): | |
| 82 | + x = x - np.max(x) | |
| 83 | + e = np.exp(x) | |
| 84 | + return e / e.sum() | |
| 85 | + | |
| 86 | + | |
| 87 | +def _permille(probs): | |
| 88 | + """Wahrscheinlichkeiten → ganze Promille mit Summe 1000 (wie maia3).""" | |
| 89 | + scaled = [max(0.0, float(p)) * 1000 for p in probs] | |
| 90 | + ints = [int(v) for v in scaled] | |
| 91 | + order = sorted(range(len(scaled)), key=lambda i: scaled[i] - ints[i], reverse=True) | |
| 92 | + for i in order[:max(0, 1000 - sum(ints))]: | |
| 93 | + ints[i] += 1 | |
| 94 | + return tuple(ints) | |
| 95 | + | |
| 96 | + | |
| 97 | +# --- Modell ------------------------------------------------------------------ | |
| 98 | + | |
| 99 | +def model_path(local_files_only=False): | |
| 100 | + """Pfad zum Modell: die einmal umgewandelte fp32-Fassung, sonst das fp16-Original. | |
| 101 | + | |
| 102 | + fp16 ist halb so groß zum Herunterladen, rechnet auf der CPU aber rund zehnmal | |
| 103 | + langsamer (ONNX Runtime wandelt dort jede Rechnung hin und her). Mit dem Paket | |
| 104 | + ``onnx`` wird es deshalb einmal nach fp32 umgeschrieben und im Cache abgelegt. | |
| 105 | + """ | |
| 106 | + fp32 = _fp32_cache_path() | |
| 107 | + if os.path.isfile(fp32): | |
| 108 | + return fp32 | |
| 109 | + from huggingface_hub import hf_hub_download | |
| 110 | + fp16 = hf_hub_download(MODEL_REPO, MODEL_FILE, revision=MODEL_REVISION, local_files_only=local_files_only) | |
| 111 | + try: | |
| 112 | + to_fp32(fp16, fp32) | |
| 113 | + except ImportError: | |
| 114 | + print("Hinweis: Paket „onnx“ fehlt – Maia rechnet mit fp16 (langsamer).", file=sys.stderr, flush=True) | |
| 115 | + return fp16 | |
| 116 | + return fp32 | |
| 117 | + | |
| 118 | + | |
| 119 | +def _fp32_cache_path(): | |
| 120 | + base = os.environ.get("XDG_CACHE_HOME") or os.path.join(os.path.expanduser("~"), ".cache") | |
| 121 | + if sys.platform == "win32": | |
| 122 | + base = os.environ.get("LOCALAPPDATA", base) | |
| 123 | + elif sys.platform == "darwin": | |
| 124 | + base = os.path.join(os.path.expanduser("~"), "Library", "Caches") | |
| 125 | + name = MODEL_FILE.replace(".fp16.", ".fp32.").replace(".onnx", f".{MODEL_REVISION[:7]}.onnx") | |
| 126 | + return os.path.join(base, "schach", name) | |
| 127 | + | |
| 128 | + | |
| 129 | +def to_fp32(source, target): | |
| 130 | + """fp16-Modell → fp32: Gewichte, Konstanten, Umwandlungen und Typangaben. Gleiche Gewichte, | |
| 131 | + nur breiter gerechnet. Schreibt erst in eine Zwischendatei, damit kein halbes Modell liegen bleibt.""" | |
| 132 | + import onnx | |
| 133 | + from onnx import TensorProto, numpy_helper | |
| 134 | + | |
| 135 | + f16, f32 = TensorProto.FLOAT16, TensorProto.FLOAT | |
| 136 | + | |
| 137 | + def widen(tensor): | |
| 138 | + return numpy_helper.from_array(numpy_helper.to_array(tensor).astype(np.float32), tensor.name) | |
| 139 | + | |
| 140 | + model = onnx.load(source) | |
| 141 | + graph = model.graph | |
| 142 | + for i, tensor in enumerate(graph.initializer): | |
| 143 | + if tensor.data_type == f16: | |
| 144 | + graph.initializer[i].CopyFrom(widen(tensor)) | |
| 145 | + for node in graph.node: | |
| 146 | + for attr in node.attribute: | |
| 147 | + if node.op_type == "Cast" and attr.name == "to" and attr.i == f16: | |
| 148 | + attr.i = f32 | |
| 149 | + elif attr.type == onnx.AttributeProto.TENSOR and attr.t.data_type == f16: | |
| 150 | + attr.t.CopyFrom(widen(attr.t)) | |
| 151 | + for info in [*graph.value_info, *graph.input, *graph.output]: | |
| 152 | + if info.type.tensor_type.elem_type == f16: | |
| 153 | + info.type.tensor_type.elem_type = f32 | |
| 154 | + onnx.checker.check_model(model) | |
| 155 | + os.makedirs(os.path.dirname(target), exist_ok=True) | |
| 156 | + partial = target + ".part" | |
| 157 | + onnx.save(model, partial) | |
| 158 | + os.replace(partial, target) | |
| 159 | + | |
| 160 | + | |
| 161 | +class Model: | |
| 162 | + def __init__(self, path): | |
| 163 | + import onnxruntime as ort | |
| 164 | + options = ort.SessionOptions() | |
| 165 | + options.log_severity_level = 3 # keine Warnungen über ungenutzte Initialisierer | |
| 166 | + self._session = ort.InferenceSession(path, options, providers=["CPUExecutionProvider"]) | |
| 167 | + | |
| 168 | + def run(self, histories, self_elos, oppo_elos): | |
| 169 | + """histories: Liste von deques → (logits_move [n, 4352], logits_value [n, 3]).""" | |
| 170 | + hist = np.stack([history_tensor(h) for h in histories]) | |
| 171 | + feeds = { | |
| 172 | + "tokens": np.ascontiguousarray(hist[:, :, -12:]), # aktuelle Stellung; vom Modell nicht genutzt | |
| 173 | + "history": hist, | |
| 174 | + "elo_self": np.asarray(self_elos, dtype=np.float32), | |
| 175 | + "elo_oppo": np.asarray(oppo_elos, dtype=np.float32), | |
| 176 | + } | |
| 177 | + moves, values = self._session.run(["logits_move", "logits_value"], feeds) | |
| 178 | + return moves, values | |
| 179 | + | |
| 180 | + | |
| 181 | +# --- Engine ------------------------------------------------------------------ | |
| 182 | + | |
| 183 | +class Engine: | |
| 184 | + def __init__(self, model_loader, elo=DEFAULT_ELO, temperature=1.0, top_p=1.0, multipv=5, seed=None): | |
| 185 | + self._load = model_loader | |
| 186 | + self.model = None | |
| 187 | + self.self_elo = self.oppo_elo = elo | |
| 188 | + self.temperature = temperature | |
| 189 | + self.top_p = top_p | |
| 190 | + self.multipv = multipv | |
| 191 | + self.rng = np.random.default_rng(seed) | |
| 192 | + self.board = chess.Board() | |
| 193 | + self.history = deque([tokenize(self.board)], maxlen=HISTORY) | |
| 194 | + self.pending = None | |
| 195 | + | |
| 196 | + def ensure_model(self): | |
| 197 | + if self.model is None: | |
| 198 | + self.model = self._load() | |
| 199 | + | |
| 200 | + def set_position(self, board, moves): | |
| 201 | + history = deque([tokenize(board)], maxlen=HISTORY) | |
| 202 | + board = board.copy() | |
| 203 | + for move in moves: | |
| 204 | + if move not in board.legal_moves: | |
| 205 | + return False | |
| 206 | + board.push(move) | |
| 207 | + history.append(tokenize(board)) | |
| 208 | + self.board, self.history = board, history | |
| 209 | + return True | |
| 210 | + | |
| 211 | + def _sample(self, logits): | |
| 212 | + if self.temperature <= 0: | |
| 213 | + return int(np.argmax(logits)) | |
| 214 | + probs = _softmax(logits / self.temperature) | |
| 215 | + if self.top_p < 1.0: | |
| 216 | + order = np.argsort(-probs, kind="stable") | |
| 217 | + keep = np.cumsum(probs[order]) <= self.top_p | |
| 218 | + keep[0] = True | |
| 219 | + order = order[keep] | |
| 220 | + kept = probs[order] / probs[order].sum() | |
| 221 | + return int(order[self.rng.choice(len(order), p=kept)]) | |
| 222 | + return int(self.rng.choice(len(probs), p=probs)) | |
| 223 | + | |
| 224 | + def analyse(self): | |
| 225 | + """(gewählter Zug, [(Zug, Wahrscheinlichkeit, (W, D, L) in Promille)]) – wie maia3.""" | |
| 226 | + legal = legal_index(self.board) | |
| 227 | + if not legal or self.board.is_game_over(): | |
| 228 | + return None, [] | |
| 229 | + logits_move, _ = self.model.run([self.history], [self.self_elo], [self.oppo_elo]) | |
| 230 | + logits = np.full(len(ALL_MOVES), -np.inf, dtype=np.float64) | |
| 231 | + idx = np.fromiter(legal, dtype=np.int64) | |
| 232 | + logits[idx] = logits_move[0, idx] | |
| 233 | + | |
| 234 | + chosen = legal[self._sample(logits)] | |
| 235 | + probs = _softmax(logits) | |
| 236 | + count = min(self.multipv, len(legal)) | |
| 237 | + top = np.argsort(-probs, kind="stable")[:count] | |
| 238 | + candidates = [(legal[int(i)], float(probs[i])) for i in top] | |
| 239 | + | |
| 240 | + # WDL je Kandidat: Stellung nach dem Zug, aus Sicht des Gegners bewertet, dann umgedreht. | |
| 241 | + after = [] | |
| 242 | + for move, _p in candidates: | |
| 243 | + board = self.board.copy(stack=False) | |
| 244 | + board.push(move) | |
| 245 | + history = deque(self.history, maxlen=HISTORY) | |
| 246 | + history.append(tokenize(board)) | |
| 247 | + after.append(history) | |
| 248 | + _, values = self.model.run(after, [self.oppo_elo] * len(after), [self.self_elo] * len(after)) | |
| 249 | + lines = [] | |
| 250 | + for (move, prob), value in zip(candidates, values): | |
| 251 | + loss, draw, win = _softmax(value.astype(np.float64)) | |
| 252 | + w, d, l = _permille((win, draw, loss)) # aus Sicht des Gegners | |
| 253 | + lines.append((move, prob, (l, d, w))) | |
| 254 | + return chosen, lines | |
| 255 | + | |
| 256 | + # UCI | |
| 257 | + | |
| 258 | + def handle(self, line, out): | |
| 259 | + parts = line.split() | |
| 260 | + if not parts: | |
| 261 | + return True | |
| 262 | + cmd = parts[0] | |
| 263 | + if cmd == "uci": | |
| 264 | + out("id name Maia3 (ONNX)") | |
| 265 | + out("id author CSSLab; ONNX-Export bqrio") | |
| 266 | + out(f"option name Elo type spin default {DEFAULT_ELO} min 0 max 5000") | |
| 267 | + out(f"option name SelfElo type spin default {DEFAULT_ELO} min 0 max 5000") | |
| 268 | + out(f"option name OppoElo type spin default {DEFAULT_ELO} min 0 max 5000") | |
| 269 | + out(f"option name Temperature type string default {self.temperature}") | |
| 270 | + out(f"option name TopP type string default {self.top_p}") | |
| 271 | + out(f"option name MultiPV type spin default {self.multipv} min 1 max 20") | |
| 272 | + out("uciok") | |
| 273 | + elif cmd == "isready": | |
| 274 | + self.ensure_model() | |
| 275 | + out("readyok") | |
| 276 | + elif cmd == "ucinewgame": | |
| 277 | + self.set_position(chess.Board(), []) | |
| 278 | + self.pending = None | |
| 279 | + elif cmd == "setoption": | |
| 280 | + self._setoption(line) | |
| 281 | + elif cmd == "position": | |
| 282 | + self._position(parts) | |
| 283 | + elif cmd == "go": | |
| 284 | + self.ensure_model() | |
| 285 | + move, lines = self.analyse() | |
| 286 | + for rank, (cand, _prob, (w, d, l)) in enumerate(lines, start=1): | |
| 287 | + out(f"info depth 1 multipv {rank} score cp {w - l} wdl {w} {d} {l} pv {cand.uci()}") | |
| 288 | + if "infinite" in parts: | |
| 289 | + self.pending = move | |
| 290 | + return True | |
| 291 | + out(f"bestmove {move.uci() if move else '0000'}") | |
| 292 | + elif cmd == "stop": | |
| 293 | + if self.pending is not None: | |
| 294 | + out(f"bestmove {self.pending.uci()}") | |
| 295 | + self.pending = None | |
| 296 | + elif cmd == "quit": | |
| 297 | + return False | |
| 298 | + return True | |
| 299 | + | |
| 300 | + def _setoption(self, line): | |
| 301 | + try: | |
| 302 | + name, _, value = line.split("name", 1)[1].partition("value") | |
| 303 | + name, value = name.strip().lower(), value.strip() | |
| 304 | + if name == "elo": | |
| 305 | + self.self_elo = self.oppo_elo = int(value) | |
| 306 | + elif name == "selfelo": | |
| 307 | + self.self_elo = int(value) | |
| 308 | + elif name == "oppoelo": | |
| 309 | + self.oppo_elo = int(value) | |
| 310 | + elif name == "temperature": | |
| 311 | + self.temperature = float(value) | |
| 312 | + elif name == "topp": | |
| 313 | + self.top_p = float(value) | |
| 314 | + elif name == "multipv": | |
| 315 | + self.multipv = min(20, max(1, int(value))) | |
| 316 | + except (IndexError, ValueError): | |
| 317 | + pass | |
| 318 | + | |
| 319 | + def _position(self, parts): | |
| 320 | + try: | |
| 321 | + if parts[1] == "startpos": | |
| 322 | + board, rest = chess.Board(), parts[2:] | |
| 323 | + elif parts[1] == "fen": | |
| 324 | + board, rest = chess.Board(" ".join(parts[2:8])), parts[8:] | |
| 325 | + else: | |
| 326 | + return | |
| 327 | + moves = [chess.Move.from_uci(m) for m in rest[1:]] if rest[:1] == ["moves"] else [] | |
| 328 | + except (IndexError, ValueError): | |
| 329 | + return | |
| 330 | + self.set_position(board, moves) | |
| 331 | + self.pending = None | |
| 332 | + | |
| 333 | + | |
| 334 | +def main(argv=None): | |
| 335 | + parser = argparse.ArgumentParser(description="Maia-3 (ONNX) als UCI-Engine") | |
| 336 | + parser.add_argument("--model-path", help="lokale .onnx-Datei statt Download") | |
| 337 | + parser.add_argument("--local-files-only", action="store_true", help="nur aus dem Hugging-Face-Cache") | |
| 338 | + parser.add_argument("--temperature", type=float, default=1.0) | |
| 339 | + parser.add_argument("--seed", type=int, default=None) | |
| 340 | + args = parser.parse_args(argv) | |
| 341 | + | |
| 342 | + def load(): | |
| 343 | + return Model(args.model_path or model_path(args.local_files_only)) | |
| 344 | + | |
| 345 | + engine = Engine(load, temperature=args.temperature, seed=args.seed) | |
| 346 | + | |
| 347 | + def out(text): | |
| 348 | + print(text, flush=True) | |
| 349 | + | |
| 350 | + for raw in sys.stdin: | |
| 351 | + if not engine.handle(raw.strip(), out): | |
| 352 | + break | |
| 353 | + | |
| 354 | + | |
| 355 | +if __name__ == "__main__": | |
| 356 | + main() | |
added tests/test_maia_onnx.py +96 −0
| @@ -0,0 +1,96 @@ | ||
| 1 | +"""Maia-3 über ONNX: Kodierung und UCI-Verhalten, ohne das echte Modell.""" | |
| 2 | + | |
| 3 | +import unittest | |
| 4 | +from collections import deque | |
| 5 | + | |
| 6 | +import chess | |
| 7 | +import numpy as np | |
| 8 | + | |
| 9 | +from schach import maia_onnx | |
| 10 | + | |
| 11 | + | |
| 12 | +class EncodingTest(unittest.TestCase): | |
| 13 | + def test_vocabulary(self): | |
| 14 | + self.assertEqual(len(maia_onnx.ALL_MOVES), 4352) | |
| 15 | + self.assertEqual(len(set(maia_onnx.ALL_MOVES)), 4352) | |
| 16 | + self.assertEqual(maia_onnx.ALL_MOVES[0], "a1a1") | |
| 17 | + self.assertEqual(maia_onnx.ALL_MOVES[4096], "a7a8q") | |
| 18 | + | |
| 19 | + def test_black_sees_board_mirrored(self): | |
| 20 | + board = chess.Board() | |
| 21 | + board.push_san("e4") | |
| 22 | + black = maia_onnx.tokenize(board) | |
| 23 | + board.push_san("e5") | |
| 24 | + # Nach 1.e4 aus Schwarz' Sicht: eigene Bauern auf Reihe 2, Bauer e4 → gegnerischer Bauer auf e5 | |
| 25 | + self.assertEqual(black[chess.E2, 0], 1) | |
| 26 | + self.assertEqual(black[chess.E5, 6], 1) | |
| 27 | + self.assertEqual(black[chess.E7, 6], 0) | |
| 28 | + self.assertEqual(black.sum(), 32) | |
| 29 | + | |
| 30 | + def test_legal_index_covers_all_moves(self): | |
| 31 | + for fen in (chess.STARTING_FEN, "8/1P4k1/8/8/8/8/6Kp/8 b - - 0 1", "8/1P4k1/8/8/8/8/6Kp/8 w - - 0 1", | |
| 32 | + "r3k2r/8/8/8/8/8/8/R3K2R b KQkq - 0 1"): | |
| 33 | + board = chess.Board(fen) | |
| 34 | + legal = maia_onnx.legal_index(board) | |
| 35 | + self.assertEqual(set(legal.values()), set(board.legal_moves), fen) | |
| 36 | + | |
| 37 | + def test_history_pads_with_oldest(self): | |
| 38 | + a, b = np.zeros((64, 12), np.float32), np.ones((64, 12), np.float32) | |
| 39 | + hist = maia_onnx.history_tensor(deque([a, b])) | |
| 40 | + self.assertEqual(hist.shape, (64, 96)) | |
| 41 | + self.assertEqual(hist[:, :84].sum(), 0) # 7× die älteste Stellung | |
| 42 | + self.assertEqual(hist[:, 84:].sum(), 64 * 12) # aktuelle zuletzt | |
| 43 | + | |
| 44 | + | |
| 45 | +class FakeModel: | |
| 46 | + """Bevorzugt immer e2e4/e7e5 (gespiegelt dasselbe Vokabularfeld) und merkt sich die Elo.""" | |
| 47 | + | |
| 48 | + def __init__(self): | |
| 49 | + self.calls = [] | |
| 50 | + | |
| 51 | + def run(self, histories, self_elos, oppo_elos): | |
| 52 | + self.calls.append((len(histories), list(self_elos), list(oppo_elos))) | |
| 53 | + logits = np.zeros((len(histories), 4352), np.float32) | |
| 54 | + logits[:, maia_onnx.MOVE_INDEX["e2e4"]] = 5 | |
| 55 | + logits[:, maia_onnx.MOVE_INDEX["d2d4"]] = 4 | |
| 56 | + values = np.tile(np.array([0.0, 0.0, 30.0], np.float32), (len(histories), 1)) # Gewinn für die Seite am Zug | |
| 57 | + return logits, values | |
| 58 | + | |
| 59 | + | |
| 60 | +class UciTest(unittest.TestCase): | |
| 61 | + def setUp(self): | |
| 62 | + self.model = FakeModel() | |
| 63 | + self.engine = maia_onnx.Engine(lambda: self.model, temperature=0, multipv=3, seed=1) | |
| 64 | + self.out = [] | |
| 65 | + | |
| 66 | + def send(self, *lines): | |
| 67 | + for line in lines: | |
| 68 | + self.engine.handle(line, self.out.append) | |
| 69 | + | |
| 70 | + def test_go_reports_multipv_and_bestmove(self): | |
| 71 | + self.send("uci", "isready", "setoption name Elo value 1700", "position startpos moves e2e4", "go movetime 100") | |
| 72 | + self.assertIn("uciok", self.out) | |
| 73 | + self.assertIn("readyok", self.out) | |
| 74 | + infos = [l for l in self.out if l.startswith("info")] | |
| 75 | + self.assertEqual(len(infos), 3) | |
| 76 | + self.assertTrue(infos[0].endswith("pv e7e5")) # e2e4 gespiegelt = e7e5 für Schwarz | |
| 77 | + self.assertTrue(infos[1].endswith("pv d7d5")) | |
| 78 | + self.assertEqual(self.out[-1], "bestmove e7e5") | |
| 79 | + self.assertEqual(self.model.calls[0], (1, [1700], [1700])) | |
| 80 | + # Kandidaten werden aus Sicht des Gegners bewertet: Der gewinnt laut Fake → für uns Verlust | |
| 81 | + self.assertIn("wdl 0 0 1000", infos[0]) | |
| 82 | + | |
| 83 | + def test_history_follows_moves(self): | |
| 84 | + self.send("position startpos moves e2e4 e7e5 g1f3") | |
| 85 | + self.assertEqual(len(self.engine.history), 4) | |
| 86 | + self.send("position fen 8/8/8/8/8/8/6k1/4K2R w K - 0 1") | |
| 87 | + self.assertEqual(len(self.engine.history), 1) | |
| 88 | + | |
| 89 | + def test_illegal_move_keeps_old_position(self): | |
| 90 | + self.send("position startpos moves e2e4") | |
| 91 | + self.send("position startpos moves e2e5") | |
| 92 | + self.assertEqual(self.engine.board.move_stack, [chess.Move.from_uci("e2e4")]) | |
| 93 | + | |
| 94 | + | |
| 95 | +if __name__ == "__main__": | |
| 96 | + unittest.main() | |
added tools/maia_onnx_vergleich.py +171 −0
| @@ -0,0 +1,171 @@ | ||
| 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()) | |