Public repository: timo / schach

Reader

Ein aufgeräumtes Schach-Programm für GNOME

perf(engines): drop the per-candidate WDL pass from the ONNX Maia engine

public

perf(engines): drop the per-candidate WDL pass from the ONNX Maia engine

The program only reads Maia's moves (evaluation comes from Stockfish),
but every request ran one extra network pass per candidate for win/
draw/loss. Without it a request takes about 100 ms on the CPU with fp16
and 35 ms with fp32, instead of 1.8 s and 170 ms.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Changeset7cc599b649b346dfdc353b957479bb58f07ba0cc
Author (claimed)Timo Stolz <timo.stolz@nullachtvierzehn.de>,
Parents1f217976cc30
Children6e5a3c880600
Pushlog
by timo via ssh
by timo via ssh

modified schach/maia_onnx.py +14 −34

@@ -1,7 +1,7 @@
11
 """Maia-3 als UCI-Engine mit ONNX Runtime statt PyTorch.
22
 
33
 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),
4
+SelfElo, OppoElo, Temperature, TopP, MultiPV; Kandidaten als MultiPV-Zeilen, ohne WDL),
55
 aber ohne PyTorch: ONNX Runtime ist 17–28 MB statt 130–540 MB, das Modell in fp16
66
 156 statt 316 MB, und ONNX ist reines Datenformat (``.pt`` ist ein Pickle).
77
 
@@ -10,10 +10,10 @@ Kodierung von Stellung und Zügen nach CSSLab/maia3 (``dataset.py``, ``utils.py``,
1010
 UofTCSSLab/Maia3-79M), auf einen Commit festgelegt.
1111
 
1212
 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.
13
+``onnx``, optional) – auf der CPU rund 35 statt 100 ms je Zug, gleiche Züge.
1414
 
1515
 GPU: Ist ``onnxruntime-ep-webgpu`` installiert, rechnet Maia über WebGPU auf der Grafikkarte
16
-(Vulkan unter Linux, D3D12 unter Windows, Metal unter macOS) – 13 statt 170 ms je Zug,
16
+(Vulkan unter Linux, D3D12 unter Windows, Metal unter macOS) – rund 13 ms je Durchgang,
1717
 dort auch mit fp16. Sonst, oder mit ``--device cpu`` / ``SCHACH_MAIA_DEVICE=cpu``, auf der CPU.
1818
 
1919
 Start: ``python -m schach.maia_onnx`` (lädt das Modell beim ersten ``isready``) oder
@@ -93,24 +93,14 @@ def _softmax(x):
9393
     return e / e.sum()
9494
 
9595
 
96
-def _permille(probs):
97
-    """Wahrscheinlichkeiten → ganze Promille mit Summe 1000 (wie maia3)."""
98
-    scaled = [max(0.0, float(p)) * 1000 for p in probs]
99
-    ints = [int(v) for v in scaled]
100
-    order = sorted(range(len(scaled)), key=lambda i: scaled[i] - ints[i], reverse=True)
101
-    for i in order[:max(0, 1000 - sum(ints))]:
102
-        ints[i] += 1
103
-    return tuple(ints)
104
-
105
-
10696
 # --- Modell ------------------------------------------------------------------
10797
 
10898
 def prepare(progress=None, local_only=False):
10999
     """Modell bereitstellen und Pfad liefern: die umgewandelte fp32-Fassung, sonst fp16.
110100
 
111
-    fp16 ist halb so groß zum Herunterladen, rechnet auf der CPU aber rund zehnmal
112
-    langsamer (ONNX Runtime hat dort kaum fp16-Rechenwege). Mit dem Paket ``onnx`` wird es
113
-    deshalb einmal nach fp32 umgeschrieben und im Cache abgelegt.
101
+    fp16 ist halb so groß zum Herunterladen, rechnet auf der CPU aber langsamer (auf x86
102
+    hat ONNX Runtime kaum fp16-Rechenwege; ein Durchgang 350 statt 50 ms). Ist das Paket
103
+    ``onnx`` da, wird es deshalb einmal nach fp32 umgeschrieben und im Cache abgelegt.
114104
 
115105
     ``progress(stufe, fertig, gesamt)`` – stufe "download" (Bytes) oder "convert" (None, None).
116106
     """
@@ -341,7 +331,11 @@ class Engine:
341331
         return int(self.rng.choice(len(probs), p=probs))
342332
 
343333
     def analyse(self):
344
-        """(gewählter Zug, [(Zug, Wahrscheinlichkeit, (W, D, L) in Promille)]) – wie maia3."""
334
+        """(gewählter Zug, [(Zug, Wahrscheinlichkeit)]), wahrscheinlichster zuerst.
335
+
336
+        Anders als maia3 ohne Gewinn/Remis/Verlust je Kandidat: Das kostete einen weiteren
337
+        Durchgang pro Kandidat (auf der CPU mit fp16 rund 0,35 s je Stück), und das
338
+        Programm nutzt nur die Züge – bewertet wird mit Stockfish."""
345339
         legal = legal_index(self.board)
346340
         if not legal or self.board.is_game_over():
347341
             return None, []
@@ -356,21 +350,7 @@ class Engine:
356350
         top = np.argsort(-probs, kind="stable")[:count]
357351
         candidates = [(legal[int(i)], float(probs[i])) for i in top]
358352
 
359
-        # WDL je Kandidat: Stellung nach dem Zug, aus Sicht des Gegners bewertet, dann umgedreht.
360
-        after = []
361
-        for move, _p in candidates:
362
-            board = self.board.copy(stack=False)
363
-            board.push(move)
364
-            history = deque(self.history, maxlen=HISTORY)
365
-            history.append(tokenize(board))
366
-            after.append(history)
367
-        _, values = self.model.run(after, [self.oppo_elo] * len(after), [self.self_elo] * len(after))
368
-        lines = []
369
-        for (move, prob), value in zip(candidates, values):
370
-            loss, draw, win = _softmax(value.astype(np.float64))
371
-            w, d, l = _permille((win, draw, loss))  # aus Sicht des Gegners
372
-            lines.append((move, prob, (l, d, w)))
373
-        return chosen, lines
353
+        return chosen, candidates
374354
 
375355
     # UCI
376356
 
@@ -402,8 +382,8 @@ class Engine:
402382
         elif cmd == "go":
403383
             self.ensure_model()
404384
             move, lines = self.analyse()
405
-            for rank, (cand, _prob, (w, d, l)) in enumerate(lines, start=1):
406
-                out(f"info depth 1 multipv {rank} score cp {w - l} wdl {w} {d} {l} pv {cand.uci()}")
385
+            for rank, (cand, _prob) in enumerate(lines, start=1):
386
+                out(f"info depth 1 multipv {rank} pv {cand.uci()}")
407387
             if "infinite" in parts:
408388
                 self.pending = move
409389
                 return True

modified tests/test_maia_onnx.py +1 −2

@@ -77,8 +77,7 @@ class UciTest(unittest.TestCase):
7777
         self.assertTrue(infos[1].endswith("pv d7d5"))
7878
         self.assertEqual(self.out[-1], "bestmove e7e5")
7979
         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])
80
+        self.assertEqual(len(self.model.calls), 1)  # ein Durchgang, keine Bewertung je Kandidat
8281
 
8382
     def test_history_follows_moves(self):
8483
         self.send("position startpos moves e2e4 e7e5 g1f3")