Public repository: timo / schach

Reader

Ein aufgeräumtes Schach-Programm für GNOME

feat(engines): download the Maia model in the app with progress

public

feat(engines): download the Maia model in the app with progress

The app now fetches and converts the model itself before starting the
engine, so the 300 s engine timeout no longer covers the download. The
title bar shows "Maia wird heruntergeladen … 42 % · 65 von 156 MB".
The download resumes after an abort and is checked against a pinned
SHA-256; huggingface_hub is no longer needed (an existing HF cache copy
is still used). The fp16 copy is removed after the fp32 conversion.

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

modified README.md +11 −8

@@ -86,15 +86,18 @@ Schlichtes GNOME-Schachprogramm (Python,
8686
     ./schach.sh
8787
 
8888
 Abhängigkeiten: `python-gobject`, `libadwaita`, `librsvg`, `python-chess`,
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).
89
+`stockfish`, `python-requests`, `python-keyring`, und für Maia-3 `onnxruntime-cpu` (oder eine
90
+andere onnxruntime-Variante), `python-numpy` sowie `python-onnx` (wandelt das Modell einmal
91
+nach fp32 um – ohne rechnet Maia auf der CPU rund zehnmal langsamer).
9292
 
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).
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, per Prüfsumme festgelegt) lädt
95
+beim ersten Start; die Titelleiste zeigt den Fortschritt, ein abgebrochener Download wird
96
+fortgesetzt. Ablage: `~/.cache/schach/`. Optional rechnet Maia auf der Grafikkarte, wenn
97
+`onnxruntime-ep-webgpu` installiert ist (pip; Vulkan, D3D12 oder Metal) – sonst auf der CPU.
98
+Ohne onnxruntime nimmt das Programm `maia3-uci` (AUR `maia3-git`, PyTorch), falls installiert;
99
+`SCHACH_MAIA=torch` bzw. `=onnx` erzwingt eins von beiden, `SCHACH_MAIA_DEVICE=cpu` die CPU.
100
+Abgleich mit dem Original: `python tools/maia_onnx_vergleich.py` (braucht maia3 und PyTorch).
98101
 Optional für „PDF über LaTeX“: `texlive-games` (`xskak`) und `pdflatex`.
99102
 
100103
 Tests:

modified schach/app.py +19 −3

@@ -19,7 +19,7 @@ from . import annotate, clipboard, liche
1919
 from .board import BoardView, available_themes  # noqa: E402
2020
 from .movelist import MoveList  # noqa: E402
2121
 from .prefs import Preferences  # noqa: E402
22
-from .engines import MAIA_CMD, MAIA_CWD, STOCKFISH_CMD, EngineWorker, maia_candidates, maia_move  # noqa: E402
22
+from .engines import MAIA_CMD, MAIA_CWD, MAIA_PREPARE, STOCKFISH_CMD, EngineWorker, maia_candidates, maia_move  # noqa: E402
2323
 from .threat import null_board, threat_job  # noqa: E402
2424
 from .online import OnlineMixin  # noqa: E402
2525
 from .puzzles import PuzzleMixin  # noqa: E402
@@ -622,7 +622,7 @@ class Window(OnlineMixin, PuzzleMixin, O
622622
         elif self.mode == "review":
623623
             self.title.set_subtitle(f"gegen {self.opponent} · du warst {side}" if self.opponent else "Analyse")
624624
         elif not self.maia_ready:
625
-            self.title.set_subtitle("Maia wird geladen …")
625
+            self.title.set_subtitle(self.get_application().maia_status)
626626
         else:
627627
             clock = f" · {self.clock_label}" if self.clock is not None else ""
628628
             thinking = " · Maia überlegt …" if self.maia_thinking and not self._over() else ""
@@ -1791,6 +1791,7 @@ class SchachApp(Adw.Application):
17911791
     def __init__(self):
17921792
         super().__init__(application_id=APP_ID, flags=Gio.ApplicationFlags.DEFAULT_FLAGS)
17931793
         self.maia_ready = False
1794
+        self.maia_status = "Maia wird geladen …"  # Untertitel, solange Maia nicht bereit ist
17941795
         self.maia = None
17951796
         self.stockfish = None
17961797
         self.stockfish_side = None  # zweiter, kleiner Stockfish für Bedrohungen (das Mitdenken läuft weiter)
@@ -1807,7 +1808,8 @@ class SchachApp(Adw.Application):
18071808
         set_book_paths(load_settings().get("books", []))
18081809
         # eigene Symbole (z. B. das Schwert für Drohungen), eingefärbt wie die GNOME-Symbole
18091810
         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, cwd=MAIA_CWD)
1811
+        self.maia = EngineWorker(MAIA_CMD, on_ready=self._on_maia_ready, cwd=MAIA_CWD,
1812
+                                 prepare=MAIA_PREPARE, on_progress=self._on_maia_progress)
18111813
         self.stockfish = EngineWorker(
18121814
             STOCKFISH_CMD, options={"Threads": min(8, os.cpu_count() or 2), "Hash": 256}
18131815
         )
@@ -1954,6 +1956,20 @@ class SchachApp(Adw.Application):
19541956
                 dialog.force_close()
19551957
                 self._toast(Adw.Toast(title="Herausforderung zurückgezogen", timeout=3))
19561958
 
1959
+    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) …"
1966
+        if text == self.maia_status:
1967
+            return
1968
+        self.maia_status = text
1969
+        for win in self.get_windows():
1970
+            if isinstance(win, Window) and not win.maia_ready:
1971
+                win._refresh_chrome()
1972
+
19571973
     def _on_maia_ready(self, error):
19581974
         self.maia_ready = error is None
19591975
         for win in self.get_windows():

modified schach/engines.py +24 −6

@@ -18,24 +18,30 @@ _PACKAGE_PARENT = os.path.dirname(os.pat
1818
 
1919
 
2020
 def maia_command(prefer=None):
21
-    """(Befehl, Arbeitsverzeichnis) für Maia-3.
21
+    """(Befehl, Arbeitsverzeichnis, Vorbereitung oder None) für Maia-3.
2222
 
2323
     Bevorzugt die eigene ONNX-Engine (``schach.maia_onnx``, braucht nur onnxruntime);
2424
     ohne onnxruntime das Original ``maia3-uci`` (PyTorch). ``SCHACH_MAIA=torch`` bzw.
2525
     ``=onnx`` erzwingt eine von beiden.
2626
     """
2727
     prefer = prefer or os.environ.get("SCHACH_MAIA", "")
28
-    onnx = [sys.executable, "-m", "schach.maia_onnx"], _PACKAGE_PARENT
28
+    onnx = [sys.executable, "-m", "schach.maia_onnx"], _PACKAGE_PARENT, _prepare_onnx
2929
     if prefer == "onnx":
3030
         return onnx
3131
     if prefer != "torch" and importlib.util.find_spec("onnxruntime") is not None:
3232
         return onnx
3333
     if shutil.which(MAIA3_UCI_CMD[0]):
34
-        return MAIA3_UCI_CMD, None
34
+        return MAIA3_UCI_CMD, None, None
3535
     return onnx  # meldet dann beim Start, was fehlt
3636
 
3737
 
38
-MAIA_CMD, MAIA_CWD = maia_command()
38
+def _prepare_onnx(progress):
39
+    """Modell laden/umwandeln (im Thread des Workers, mit Fortschritt) → Zusatzargumente."""
40
+    from . import maia_onnx
41
+    return ["--model-path", maia_onnx.prepare(progress)]
42
+
43
+
44
+MAIA_CMD, MAIA_CWD, MAIA_PREPARE = maia_command()
3945
 
4046
 
4147
 class EngineWorker:
@@ -45,9 +51,14 @@ class EngineWorker:
4551
     läuft danach im GTK-Hauptthread.
4652
     """
4753
 
48
-    def __init__(self, cmd, options=None, on_ready=None, cwd=None):
54
+    def __init__(self, cmd, options=None, on_ready=None, cwd=None, prepare=None, on_progress=None):
55
+        """``prepare(progress) -> [Zusatzargumente]`` läuft vor dem Start im Thread (z. B. Modell
56
+        herunterladen); ``on_progress(stufe, fertig, gesamt)`` kommt im GTK-Thread an. Die Frist
57
+        von 300 s gilt erst danach, für Start und Laden der Engine."""
4958
         self._cmd = cmd
5059
         self._cwd = cwd
60
+        self._prepare = prepare
61
+        self._on_progress = on_progress
5162
         self._options = options or {}
5263
         self._on_ready = on_ready
5364
         self._jobs = queue.Queue()
@@ -57,8 +68,11 @@ class EngineWorker:
5768
     def _run(self):
5869
         engine = None
5970
         try:
71
+            cmd = list(self._cmd)
72
+            if self._prepare:
73
+                cmd += self._prepare(self._progress)
6074
             engine = chess.engine.SimpleEngine.popen_uci(
61
-                self._cmd, timeout=300, stderr=subprocess.DEVNULL, cwd=self._cwd
75
+                cmd, timeout=300, stderr=subprocess.DEVNULL, cwd=self._cwd
6276
             )
6377
             if self._options:
6478
                 engine.configure(self._options)
@@ -89,6 +103,10 @@ class EngineWorker:
89103
             except Exception:  # noqa: BLE001
90104
                 pass
91105
 
106
+    def _progress(self, *args):
107
+        if self._on_progress:
108
+            GLib.idle_add(lambda: self._on_progress(*args) and False)
109
+
92110
     def submit(self, fn, callback):
93111
         self._jobs.put((fn, callback))
94112
 

modified schach/maia_onnx.py +85 −15

@@ -16,8 +16,9 @@ GPU: Ist ``onnxruntime-ep-webgpu`` installiert, rechnet Maia über WebGPU auf der Grafikkarte
1616
 (Vulkan unter Linux, D3D12 unter Windows, Metal unter macOS) – 13 statt 170 ms je Zug,
1717
 dort auch mit fp16. Sonst, oder mit ``--device cpu`` / ``SCHACH_MAIA_DEVICE=cpu``, auf der CPU.
1818
 
19
-Start: ``python -m schach.maia_onnx`` (lädt das Modell beim ersten ``isready`` von
20
-Hugging Face bzw. aus dessen Cache) oder ``--model-path DATEI``.
19
+Start: ``python -m schach.maia_onnx`` (lädt das Modell beim ersten ``isready``) oder
20
+``--model-path DATEI``. Das Programm selbst ruft vorher ``prepare()`` mit Fortschritts-
21
+anzeige auf und übergibt den Pfad.
2122
 """
2223
 
2324
 import argparse
@@ -31,6 +32,10 @@ import numpy as np
3132
 MODEL_REPO = "bqrio/maia3-onnx"
3233
 MODEL_FILE = "maia3-79m.fp16.history.onnx"
3334
 MODEL_REVISION = "923df9a2e9396b54a09b168bb858ebbd5e5b76bc"
35
+MODEL_SHA256 = "7cbad622698119e446a86ba9be8b50c0164c1755c8ac8a3a8fea478859f1df51"
36
+MODEL_SIZE = 156_141_348
37
+MODEL_URL = f"https://huggingface.co/{MODEL_REPO}/resolve/{MODEL_REVISION}/{MODEL_FILE}"
38
+USER_AGENT = "schach-gtk/1.0"
3439
 HISTORY = 8
3540
 DEFAULT_ELO = 1500
3641
 
@@ -100,34 +105,99 @@ def _permille(probs):
100105
 
101106
 # --- Modell ------------------------------------------------------------------
102107
 
103
-def model_path(local_files_only=False):
104
-    """Pfad zum Modell: die einmal umgewandelte fp32-Fassung, sonst das fp16-Original.
108
+def prepare(progress=None, local_only=False):
109
+    """Modell bereitstellen und Pfad liefern: die umgewandelte fp32-Fassung, sonst fp16.
105110
 
106111
     fp16 ist halb so groß zum Herunterladen, rechnet auf der CPU aber rund zehnmal
107
-    langsamer (ONNX Runtime wandelt dort jede Rechnung hin und her). Mit dem Paket
108
-    ``onnx`` wird es deshalb einmal nach fp32 umgeschrieben und im Cache abgelegt.
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.
114
+
115
+    ``progress(stufe, fertig, gesamt)`` – stufe "download" (Bytes) oder "convert" (None, None).
109116
     """
110
-    fp32 = _fp32_cache_path()
117
+    fp32 = _cache_path(MODEL_FILE.replace(".fp16.", ".fp32."))
111118
     if os.path.isfile(fp32):
112119
         return fp32
113
-    from huggingface_hub import hf_hub_download
114
-    fp16 = hf_hub_download(MODEL_REPO, MODEL_FILE, revision=MODEL_REVISION, local_files_only=local_files_only)
120
+    fp16 = _fp16_path(progress, local_only)
115121
     try:
116
-        to_fp32(fp16, fp32)
122
+        import onnx  # noqa: F401 – nur prüfen, ob umgewandelt werden kann
117123
     except ImportError:
118
-        print("Hinweis: Paket „onnx“ fehlt – Maia rechnet mit fp16 (langsamer).", file=sys.stderr, flush=True)
124
+        print("Hinweis: Paket „onnx“ fehlt – Maia rechnet mit fp16 (auf der CPU langsamer).",
125
+              file=sys.stderr, flush=True)
119126
         return fp16
127
+    if progress:
128
+        progress("convert", None, None)
129
+    to_fp32(fp16, fp32)
130
+    if fp16 == _cache_path(MODEL_FILE):
131
+        os.remove(fp16)  # unsere eigene Kopie wird nicht mehr gebraucht (den HF-Cache fassen wir nicht an)
120132
     return fp32
121133
 
122134
 
123
-def _fp32_cache_path():
135
+model_path = prepare  # alter Name (tools/maia_onnx_vergleich.py)
136
+
137
+
138
+def _fp16_path(progress, local_only):
139
+    ours = _cache_path(MODEL_FILE)
140
+    if os.path.isfile(ours):
141
+        return ours
142
+    try:  # schon im Hugging-Face-Cache (z. B. von maia3 oder einer früheren Version)?
143
+        from huggingface_hub import hf_hub_download
144
+        return hf_hub_download(MODEL_REPO, MODEL_FILE, revision=MODEL_REVISION, local_files_only=True)
145
+    except Exception:  # noqa: BLE001 – kein Paket oder nicht im Cache
146
+        pass
147
+    if local_only:
148
+        raise FileNotFoundError(f"Maia-Modell nicht im Cache: {ours}")
149
+    download(MODEL_URL, ours, MODEL_SHA256, progress)
150
+    return ours
151
+
152
+
153
+def download(url, target, sha256, progress=None, chunk=1 << 20):
154
+    """Datei laden, nach ``target.part``; ein abgebrochener Download wird fortgesetzt.
155
+    Erst nach geprüfter Prüfsumme heißt die Datei ``target``. Kein Gesamt-Zeitlimit –
156
+    nur eine Frist, falls die Verbindung minutenlang steht."""
157
+    import hashlib
158
+
159
+    import requests
160
+
161
+    os.makedirs(os.path.dirname(target), exist_ok=True)
162
+    partial = target + ".part"
163
+    have = os.path.getsize(partial) if os.path.exists(partial) else 0
164
+    headers = {"User-Agent": USER_AGENT}
165
+    if have:
166
+        headers["Range"] = f"bytes={have}-"
167
+    with requests.get(url, headers=headers, stream=True, timeout=(20, 120)) as resp:
168
+        if resp.status_code == 416:  # schon vollständig
169
+            have, mode = os.path.getsize(partial), None
170
+        elif resp.status_code == 206:
171
+            mode = "ab"
172
+        else:
173
+            resp.raise_for_status()
174
+            have, mode = 0, "wb"  # Server kann nicht fortsetzen: von vorn
175
+        if mode:
176
+            total = have + int(resp.headers.get("Content-Length", 0)) or None
177
+            with open(partial, mode) as fh:
178
+                for block in resp.iter_content(chunk):
179
+                    fh.write(block)
180
+                    have += len(block)
181
+                    if progress:
182
+                        progress("download", have, total)
183
+    digest = hashlib.sha256()
184
+    with open(partial, "rb") as fh:
185
+        while block := fh.read(chunk):
186
+            digest.update(block)
187
+    if digest.hexdigest() != sha256:
188
+        os.remove(partial)
189
+        raise ValueError("Maia-Modell: Prüfsumme stimmt nicht – Download verworfen")
190
+    os.replace(partial, target)
191
+
192
+
193
+def _cache_path(filename):
194
+    """Cache-Datei mit der Modell-Revision im Namen (neue Revision → neue Datei)."""
124195
     base = os.environ.get("XDG_CACHE_HOME") or os.path.join(os.path.expanduser("~"), ".cache")
125196
     if sys.platform == "win32":
126197
         base = os.environ.get("LOCALAPPDATA", base)
127198
     elif sys.platform == "darwin":
128199
         base = os.path.join(os.path.expanduser("~"), "Library", "Caches")
129
-    name = MODEL_FILE.replace(".fp16.", ".fp32.").replace(".onnx", f".{MODEL_REVISION[:7]}.onnx")
130
-    return os.path.join(base, "schach", name)
200
+    return os.path.join(base, "schach", filename.replace(".onnx", f".{MODEL_REVISION[:7]}.onnx"))
131201
 
132202
 
133203
 def to_fp32(source, target):
@@ -392,7 +462,7 @@ def main(argv=None):
392462
     args = parser.parse_args(argv)
393463
 
394464
     def load():
395
-        model = Model(args.model_path or model_path(args.local_files_only), args.device)
465
+        model = Model(args.model_path or prepare(local_only=args.local_files_only), args.device)
396466
         print(f"Maia3 (ONNX) rechnet auf: {model.device.upper()}", file=sys.stderr, flush=True)
397467
         return model
398468