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>
| Changeset | 9b1634b37f2a72f21d166dc46fc28b14f6e500d0 |
|---|---|
| Author (claimed) | Timo Stolz <timo.stolz@nullachtvierzehn.de>, |
| Parents | 72f34d142b74 |
| Children | 1f217976cc30 |
| Pushlog | by timo via ssh by timo via ssh |
modified README.md +11 −8
| @@ -86,15 +86,18 @@ Schlichtes GNOME-Schachprogramm (Python, | ||
| 86 | 86 | ./schach.sh |
| 87 | 87 | |
| 88 | 88 | 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). | |
| 92 | 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). | |
| 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). | |
| 98 | 101 | Optional für „PDF über LaTeX“: `texlive-games` (`xskak`) und `pdflatex`. |
| 99 | 102 | |
| 100 | 103 | Tests: |
modified schach/app.py +19 −3
| @@ -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, 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 | |
| 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 |
| @@ -622,7 +622,7 @@ class Window(OnlineMixin, PuzzleMixin, O | ||
| 622 | 622 | elif self.mode == "review": |
| 623 | 623 | self.title.set_subtitle(f"gegen {self.opponent} · du warst {side}" if self.opponent else "Analyse") |
| 624 | 624 | elif not self.maia_ready: |
| 625 | - self.title.set_subtitle("Maia wird geladen …") | |
| 625 | + self.title.set_subtitle(self.get_application().maia_status) | |
| 626 | 626 | else: |
| 627 | 627 | clock = f" · {self.clock_label}" if self.clock is not None else "" |
| 628 | 628 | thinking = " · Maia überlegt …" if self.maia_thinking and not self._over() else "" |
| @@ -1791,6 +1791,7 @@ class SchachApp(Adw.Application): | ||
| 1791 | 1791 | def __init__(self): |
| 1792 | 1792 | super().__init__(application_id=APP_ID, flags=Gio.ApplicationFlags.DEFAULT_FLAGS) |
| 1793 | 1793 | self.maia_ready = False |
| 1794 | + self.maia_status = "Maia wird geladen …" # Untertitel, solange Maia nicht bereit ist | |
| 1794 | 1795 | self.maia = None |
| 1795 | 1796 | self.stockfish = None |
| 1796 | 1797 | self.stockfish_side = None # zweiter, kleiner Stockfish für Bedrohungen (das Mitdenken läuft weiter) |
| @@ -1807,7 +1808,8 @@ class SchachApp(Adw.Application): | ||
| 1807 | 1808 | set_book_paths(load_settings().get("books", [])) |
| 1808 | 1809 | # eigene Symbole (z. B. das Schwert für Drohungen), eingefärbt wie die GNOME-Symbole |
| 1809 | 1810 | 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) | |
| 1811 | 1813 | self.stockfish = EngineWorker( |
| 1812 | 1814 | STOCKFISH_CMD, options={"Threads": min(8, os.cpu_count() or 2), "Hash": 256} |
| 1813 | 1815 | ) |
| @@ -1954,6 +1956,20 @@ class SchachApp(Adw.Application): | ||
| 1954 | 1956 | dialog.force_close() |
| 1955 | 1957 | self._toast(Adw.Toast(title="Herausforderung zurückgezogen", timeout=3)) |
| 1956 | 1958 | |
| 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 | + | |
| 1957 | 1973 | def _on_maia_ready(self, error): |
| 1958 | 1974 | self.maia_ready = error is None |
| 1959 | 1975 | for win in self.get_windows(): |
modified schach/engines.py +24 −6
| @@ -18,24 +18,30 @@ _PACKAGE_PARENT = os.path.dirname(os.pat | ||
| 18 | 18 | |
| 19 | 19 | |
| 20 | 20 | def maia_command(prefer=None): |
| 21 | - """(Befehl, Arbeitsverzeichnis) für Maia-3. | |
| 21 | + """(Befehl, Arbeitsverzeichnis, Vorbereitung oder None) für Maia-3. | |
| 22 | 22 | |
| 23 | 23 | Bevorzugt die eigene ONNX-Engine (``schach.maia_onnx``, braucht nur onnxruntime); |
| 24 | 24 | ohne onnxruntime das Original ``maia3-uci`` (PyTorch). ``SCHACH_MAIA=torch`` bzw. |
| 25 | 25 | ``=onnx`` erzwingt eine von beiden. |
| 26 | 26 | """ |
| 27 | 27 | 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 | |
| 29 | 29 | if prefer == "onnx": |
| 30 | 30 | return onnx |
| 31 | 31 | if prefer != "torch" and importlib.util.find_spec("onnxruntime") is not None: |
| 32 | 32 | return onnx |
| 33 | 33 | if shutil.which(MAIA3_UCI_CMD[0]): |
| 34 | - return MAIA3_UCI_CMD, None | |
| 34 | + return MAIA3_UCI_CMD, None, None | |
| 35 | 35 | return onnx # meldet dann beim Start, was fehlt |
| 36 | 36 | |
| 37 | 37 | |
| 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() | |
| 39 | 45 | |
| 40 | 46 | |
| 41 | 47 | class EngineWorker: |
| @@ -45,9 +51,14 @@ class EngineWorker: | ||
| 45 | 51 | läuft danach im GTK-Hauptthread. |
| 46 | 52 | """ |
| 47 | 53 | |
| 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.""" | |
| 49 | 58 | self._cmd = cmd |
| 50 | 59 | self._cwd = cwd |
| 60 | + self._prepare = prepare | |
| 61 | + self._on_progress = on_progress | |
| 51 | 62 | self._options = options or {} |
| 52 | 63 | self._on_ready = on_ready |
| 53 | 64 | self._jobs = queue.Queue() |
| @@ -57,8 +68,11 @@ class EngineWorker: | ||
| 57 | 68 | def _run(self): |
| 58 | 69 | engine = None |
| 59 | 70 | try: |
| 71 | + cmd = list(self._cmd) | |
| 72 | + if self._prepare: | |
| 73 | + cmd += self._prepare(self._progress) | |
| 60 | 74 | 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 | |
| 62 | 76 | ) |
| 63 | 77 | if self._options: |
| 64 | 78 | engine.configure(self._options) |
| @@ -89,6 +103,10 @@ class EngineWorker: | ||
| 89 | 103 | except Exception: # noqa: BLE001 |
| 90 | 104 | pass |
| 91 | 105 | |
| 106 | + def _progress(self, *args): | |
| 107 | + if self._on_progress: | |
| 108 | + GLib.idle_add(lambda: self._on_progress(*args) and False) | |
| 109 | + | |
| 92 | 110 | def submit(self, fn, callback): |
| 93 | 111 | self._jobs.put((fn, callback)) |
| 94 | 112 | |
modified schach/maia_onnx.py +85 −15
| @@ -16,8 +16,9 @@ GPU: Ist ``onnxruntime-ep-webgpu`` installiert, rechnet Maia über WebGPU auf der Grafikkarte | ||
| 16 | 16 | (Vulkan unter Linux, D3D12 unter Windows, Metal unter macOS) – 13 statt 170 ms je Zug, |
| 17 | 17 | dort auch mit fp16. Sonst, oder mit ``--device cpu`` / ``SCHACH_MAIA_DEVICE=cpu``, auf der CPU. |
| 18 | 18 | |
| 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. | |
| 21 | 22 | """ |
| 22 | 23 | |
| 23 | 24 | import argparse |
| @@ -31,6 +32,10 @@ import numpy as np | ||
| 31 | 32 | MODEL_REPO = "bqrio/maia3-onnx" |
| 32 | 33 | MODEL_FILE = "maia3-79m.fp16.history.onnx" |
| 33 | 34 | 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" | |
| 34 | 39 | HISTORY = 8 |
| 35 | 40 | DEFAULT_ELO = 1500 |
| 36 | 41 | |
| @@ -100,34 +105,99 @@ def _permille(probs): | ||
| 100 | 105 | |
| 101 | 106 | # --- Modell ------------------------------------------------------------------ |
| 102 | 107 | |
| 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. | |
| 105 | 110 | |
| 106 | 111 | 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). | |
| 109 | 116 | """ |
| 110 | - fp32 = _fp32_cache_path() | |
| 117 | + fp32 = _cache_path(MODEL_FILE.replace(".fp16.", ".fp32.")) | |
| 111 | 118 | if os.path.isfile(fp32): |
| 112 | 119 | 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) | |
| 115 | 121 | try: |
| 116 | - to_fp32(fp16, fp32) | |
| 122 | + import onnx # noqa: F401 – nur prüfen, ob umgewandelt werden kann | |
| 117 | 123 | 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) | |
| 119 | 126 | 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) | |
| 120 | 132 | return fp32 |
| 121 | 133 | |
| 122 | 134 | |
| 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).""" | |
| 124 | 195 | base = os.environ.get("XDG_CACHE_HOME") or os.path.join(os.path.expanduser("~"), ".cache") |
| 125 | 196 | if sys.platform == "win32": |
| 126 | 197 | base = os.environ.get("LOCALAPPDATA", base) |
| 127 | 198 | elif sys.platform == "darwin": |
| 128 | 199 | 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")) | |
| 131 | 201 | |
| 132 | 202 | |
| 133 | 203 | def to_fp32(source, target): |
| @@ -392,7 +462,7 @@ def main(argv=None): | ||
| 392 | 462 | args = parser.parse_args(argv) |
| 393 | 463 | |
| 394 | 464 | 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) | |
| 396 | 466 | print(f"Maia3 (ONNX) rechnet auf: {model.device.upper()}", file=sys.stderr, flush=True) |
| 397 | 467 | return model |
| 398 | 468 | |