Public repository: timo / schach

Reader

Ein aufgeräumtes Schach-Programm für GNOME

refactor(engines): drop the fp32 conversion of the Maia model

public

refactor(engines): drop the fp32 conversion of the Maia model

Without the WDL pass fp16 needs about 100 ms per request on the CPU;
fp32 would save 65 ms but cost the onnx package and 312 MB of disk.

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

modified README.md +1 −2

@@ -88,8 +88,7 @@ Schlichtes GNOME-Schachprogramm (Python,
8888
 
8989
 Abhängigkeiten: `python-gobject`, `libadwaita`, `librsvg`, `python-chess`,
9090
 `stockfish`, `python-requests`, `python-keyring`, und für Maia-3 `onnxruntime-cpu` (oder eine
91
-andere onnxruntime-Variante), `python-numpy`; optional `python-onnx` (wandelt das Modell einmal
92
-nach fp32 um – auf der CPU rund 35 statt 100 ms je Zug).
91
+andere onnxruntime-Variante), `python-numpy`.
9392
 
9493
 Maia-3 läuft über ONNX Runtime statt PyTorch (`schach/maia_onnx.py`). Das Modell (ONNX-Export
9594
 von Maia3-79M mit Zughistorie, `bqrio/maia3-onnx`, 156 MB, per Prüfsumme festgelegt) lädt

modified schach/app.py +3 −6

@@ -1957,12 +1957,9 @@ class SchachApp(Adw.Application):
19571957
                 self._toast(Adw.Toast(title="Herausforderung zurückgezogen", timeout=3))
19581958
 
19591959
     def _on_maia_progress(self, stage, done, total):
1960
-        if stage == "download":
1961
-            mb = f"{done / 1e6:.0f} von {total / 1e6:.0f} MB" if total else f"{done / 1e6:.0f} MB"
1962
-            percent = f"{100 * done // total} % · " if total else ""
1963
-            text = f"Maia wird heruntergeladen (einmalig) … {percent}{mb}"
1964
-        else:
1965
-            text = "Maia wird vorbereitet (einmalig) …"
1960
+        mb = f"{done / 1e6:.0f} von {total / 1e6:.0f} MB" if total else f"{done / 1e6:.0f} MB"
1961
+        percent = f"{100 * done // total} % · " if total else ""
1962
+        text = f"Maia wird heruntergeladen (einmalig) … {percent}{mb}"
19661963
         if text == self.maia_status:
19671964
             return
19681965
         self.maia_status = text

modified schach/maia_onnx.py +8 −56

@@ -9,12 +9,11 @@ Kodierung von Stellung und Zügen nach CSSLab/maia3 (``dataset.py``, ``utils.py``,
99
 ``uci.py``; AGPL-3.0). Modell: ONNX-Export von bqrio (AGPL-3.0, Ableitung von
1010
 UofTCSSLab/Maia3-79M), auf einen Commit festgelegt.
1111
 
12
-Modell: fp16 herunterladen (156 MB), einmal nach fp32 umschreiben (braucht das Paket
13
-``onnx``, optional) – auf der CPU rund 35 statt 100 ms je Zug, gleiche Züge.
12
+Modell: fp16 (156 MB), einmal heruntergeladen – auf der CPU rund 100 ms je Zug.
1413
 
1514
 GPU: Ist ``onnxruntime-ep-webgpu`` installiert, rechnet Maia über WebGPU auf der Grafikkarte
1615
 (Vulkan unter Linux, D3D12 unter Windows, Metal unter macOS) – rund 13 ms je Durchgang,
17
-dort auch mit fp16. Sonst, oder mit ``--device cpu`` / ``SCHACH_MAIA_DEVICE=cpu``, auf der CPU.
16
+Sonst, oder mit ``--device cpu`` / ``SCHACH_MAIA_DEVICE=cpu``, auf der CPU.
1817
 
1918
 Start: ``python -m schach.maia_onnx`` (lädt das Modell beim ersten ``isready``) oder
2019
 ``--model-path DATEI``. Das Programm selbst ruft vorher ``prepare()`` mit Fortschritts-
@@ -96,30 +95,15 @@ def _softmax(x):
9695
 # --- Modell ------------------------------------------------------------------
9796
 
9897
 def prepare(progress=None, local_only=False):
99
-    """Modell bereitstellen und Pfad liefern: die umgewandelte fp32-Fassung, sonst fp16.
98
+    """Modell bereitstellen (aus dem Cache oder herunterladen) und Pfad liefern.
10099
 
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.
100
+    Das Modell ist fp16. Auf der CPU rechnet ONNX Runtime damit langsamer als mit fp32
101
+    (x86 hat kaum fp16-Rechenwege), mit rund 100 ms je Zug aber schnell genug – eine
102
+    fp32-Umwandlung brächte 65 ms, kostete aber das Paket ``onnx`` und 312 MB Platte.
104103
 
105
-    ``progress(stufe, fertig, gesamt)`` – stufe "download" (Bytes) oder "convert" (None, None).
104
+    ``progress(stufe, fertig, gesamt)`` – stufe "download", fertig/gesamt in Bytes.
106105
     """
107
-    fp32 = _cache_path(MODEL_FILE.replace(".fp16.", ".fp32."))
108
-    if os.path.isfile(fp32):
109
-        return fp32
110
-    fp16 = _fp16_path(progress, local_only)
111
-    try:
112
-        import onnx  # noqa: F401 – nur prüfen, ob umgewandelt werden kann
113
-    except ImportError:
114
-        print("Hinweis: Paket „onnx“ fehlt – Maia rechnet mit fp16 (auf der CPU langsamer).",
115
-              file=sys.stderr, flush=True)
116
-        return fp16
117
-    if progress:
118
-        progress("convert", None, None)
119
-    to_fp32(fp16, fp32)
120
-    if fp16 == _cache_path(MODEL_FILE):
121
-        os.remove(fp16)  # unsere eigene Kopie wird nicht mehr gebraucht (den HF-Cache fassen wir nicht an)
122
-    return fp32
106
+    return _fp16_path(progress, local_only)
123107
 
124108
 
125109
 model_path = prepare  # alter Name (tools/maia_onnx_vergleich.py)
@@ -190,38 +174,6 @@ def _cache_path(filename):
190174
     return os.path.join(base, "schach", filename.replace(".onnx", f".{MODEL_REVISION[:7]}.onnx"))
191175
 
192176
 
193
-def to_fp32(source, target):
194
-    """fp16-Modell → fp32: Gewichte, Konstanten, Umwandlungen und Typangaben. Gleiche Gewichte,
195
-    nur breiter gerechnet. Schreibt erst in eine Zwischendatei, damit kein halbes Modell liegen bleibt."""
196
-    import onnx
197
-    from onnx import TensorProto, numpy_helper
198
-
199
-    f16, f32 = TensorProto.FLOAT16, TensorProto.FLOAT
200
-
201
-    def widen(tensor):
202
-        return numpy_helper.from_array(numpy_helper.to_array(tensor).astype(np.float32), tensor.name)
203
-
204
-    model = onnx.load(source)
205
-    graph = model.graph
206
-    for i, tensor in enumerate(graph.initializer):
207
-        if tensor.data_type == f16:
208
-            graph.initializer[i].CopyFrom(widen(tensor))
209
-    for node in graph.node:
210
-        for attr in node.attribute:
211
-            if node.op_type == "Cast" and attr.name == "to" and attr.i == f16:
212
-                attr.i = f32
213
-            elif attr.type == onnx.AttributeProto.TENSOR and attr.t.data_type == f16:
214
-                attr.t.CopyFrom(widen(attr.t))
215
-    for info in [*graph.value_info, *graph.input, *graph.output]:
216
-        if info.type.tensor_type.elem_type == f16:
217
-            info.type.tensor_type.elem_type = f32
218
-    onnx.checker.check_model(model)
219
-    os.makedirs(os.path.dirname(target), exist_ok=True)
220
-    partial = target + ".part"
221
-    onnx.save(model, partial)
222
-    os.replace(partial, target)
223
-
224
-
225177
 def _options(ort):
226178
     options = ort.SessionOptions()
227179
     options.log_severity_level = 3  # keine Warnungen über ungenutzte Initialisierer