feat(engines): run Maia on the GPU via the WebGPU provider when available
public
feat(engines): run Maia on the GPU via the WebGPU provider when available With onnxruntime-ep-webgpu installed Maia uses the GPU through Vulkan, D3D12 or Metal: 35 ms per move over UCI instead of 166 ms on the CPU, identical results in the comparison test. Any failure falls back to the CPU; --device / SCHACH_MAIA_DEVICE forces one. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
| Changeset | 72f34d142b74c12c6b02e92f4f8808614eeec010 |
|---|---|
| Author (claimed) | Timo Stolz <timo.stolz@nullachtvierzehn.de>, |
| Parents | d50f901fa346 |
| Children | 9b1634b37f2a |
| Pushlog | by timo via ssh by timo via ssh |
modified schach/maia_onnx.py +60 −6
| @@ -12,6 +12,10 @@ UofTCSSLab/Maia3-79M), auf einen Commit | ||
| 12 | 12 | Modell: fp16 herunterladen (156 MB), einmal nach fp32 umschreiben (braucht das Paket |
| 13 | 13 | ``onnx``) – auf der CPU 0,17 s statt 1,8 s je Zug, gleiche Züge. |
| 14 | 14 | |
| 15 | +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, | |
| 17 | +dort auch mit fp16. Sonst, oder mit ``--device cpu`` / ``SCHACH_MAIA_DEVICE=cpu``, auf der CPU. | |
| 18 | + | |
| 15 | 19 | Start: ``python -m schach.maia_onnx`` (lädt das Modell beim ersten ``isready`` von |
| 16 | 20 | Hugging Face bzw. aus dessen Cache) oder ``--model-path DATEI``. |
| 17 | 21 | """ |
| @@ -158,12 +162,57 @@ def to_fp32(source, target): | ||
| 158 | 162 | os.replace(partial, target) |
| 159 | 163 | |
| 160 | 164 | |
| 165 | +def _options(ort): | |
| 166 | + options = ort.SessionOptions() | |
| 167 | + options.log_severity_level = 3 # keine Warnungen über ungenutzte Initialisierer | |
| 168 | + return options | |
| 169 | + | |
| 170 | + | |
| 171 | +def _gpu_session(ort, path): | |
| 172 | + """Sitzung auf der GPU über den WebGPU-Provider (Vulkan, D3D12 oder Metal) – oder None. | |
| 173 | + | |
| 174 | + Optional: braucht das Paket ``onnxruntime-ep-webgpu``. Jeder Fehler (kein Paket, keine | |
| 175 | + GPU, Treiber verweigert, unbrauchbares Ergebnis) fällt still auf die CPU zurück. | |
| 176 | + """ | |
| 177 | + try: | |
| 178 | + import onnxruntime_ep_webgpu as webgpu | |
| 179 | + except ImportError: | |
| 180 | + return None | |
| 181 | + try: | |
| 182 | + name = webgpu.get_ep_name() | |
| 183 | + try: | |
| 184 | + ort.register_execution_provider_library(name, webgpu.get_library_path()) | |
| 185 | + except Exception: # noqa: BLE001 – schon registriert | |
| 186 | + pass | |
| 187 | + devices = [d for d in ort.get_ep_devices() | |
| 188 | + if d.ep_name == name and d.device.type == ort.OrtHardwareDeviceType.GPU] | |
| 189 | + if not devices: | |
| 190 | + return None | |
| 191 | + options = _options(ort) | |
| 192 | + options.add_provider_for_devices(devices[:1], {}) | |
| 193 | + session = ort.InferenceSession(path, options) | |
| 194 | + probe = np.zeros((1, 64, 96), np.float32) | |
| 195 | + moves, values = session.run(None, {"tokens": probe[:, :, -12:].copy(), "history": probe, | |
| 196 | + "elo_self": np.full(1, 1500, np.float32), | |
| 197 | + "elo_oppo": np.full(1, 1500, np.float32)}) | |
| 198 | + if not (np.isfinite(moves).all() and np.isfinite(values).all()): | |
| 199 | + return None | |
| 200 | + return session | |
| 201 | + except Exception as exc: # noqa: BLE001 | |
| 202 | + print(f"GPU nicht nutzbar ({exc}) – Maia rechnet auf der CPU.", file=sys.stderr, flush=True) | |
| 203 | + return None | |
| 204 | + | |
| 205 | + | |
| 161 | 206 | class Model: |
| 162 | - def __init__(self, path): | |
| 207 | + """``device``: "auto" (GPU, wenn möglich), "gpu" (dasselbe, aber mit Meldung, wenn nicht) oder "cpu".""" | |
| 208 | + | |
| 209 | + def __init__(self, path, device="auto"): | |
| 163 | 210 | 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"]) | |
| 211 | + session = _gpu_session(ort, path) if device in ("auto", "gpu") else None | |
| 212 | + if session is None and device == "gpu": | |
| 213 | + print("Keine GPU über WebGPU gefunden – Maia rechnet auf der CPU.", file=sys.stderr, flush=True) | |
| 214 | + self.device = "gpu" if session is not None else "cpu" | |
| 215 | + self._session = session or ort.InferenceSession(path, _options(ort), providers=["CPUExecutionProvider"]) | |
| 167 | 216 | |
| 168 | 217 | def run(self, histories, self_elos, oppo_elos): |
| 169 | 218 | """histories: Liste von deques → (logits_move [n, 4352], logits_value [n, 3]).""" |
| @@ -182,7 +231,7 @@ class Model: | ||
| 182 | 231 | |
| 183 | 232 | class Engine: |
| 184 | 233 | def __init__(self, model_loader, elo=DEFAULT_ELO, temperature=1.0, top_p=1.0, multipv=5, seed=None): |
| 185 | - self._load = model_loader | |
| 234 | + self._load = model_loader # () -> Model; lädt erst bei „isready“ oder „go“ | |
| 186 | 235 | self.model = None |
| 187 | 236 | self.self_elo = self.oppo_elo = elo |
| 188 | 237 | self.temperature = temperature |
| @@ -335,12 +384,17 @@ def main(argv=None): | ||
| 335 | 384 | parser = argparse.ArgumentParser(description="Maia-3 (ONNX) als UCI-Engine") |
| 336 | 385 | parser.add_argument("--model-path", help="lokale .onnx-Datei statt Download") |
| 337 | 386 | parser.add_argument("--local-files-only", action="store_true", help="nur aus dem Hugging-Face-Cache") |
| 387 | + parser.add_argument("--device", choices=("auto", "gpu", "cpu"), | |
| 388 | + default=os.environ.get("SCHACH_MAIA_DEVICE", "auto"), | |
| 389 | + help="GPU über WebGPU (braucht onnxruntime-ep-webgpu) oder CPU") | |
| 338 | 390 | parser.add_argument("--temperature", type=float, default=1.0) |
| 339 | 391 | parser.add_argument("--seed", type=int, default=None) |
| 340 | 392 | args = parser.parse_args(argv) |
| 341 | 393 | |
| 342 | 394 | def load(): |
| 343 | - return Model(args.model_path or model_path(args.local_files_only)) | |
| 395 | + model = Model(args.model_path or model_path(args.local_files_only), args.device) | |
| 396 | + print(f"Maia3 (ONNX) rechnet auf: {model.device.upper()}", file=sys.stderr, flush=True) | |
| 397 | + return model | |
| 344 | 398 | |
| 345 | 399 | engine = Engine(load, temperature=args.temperature, seed=args.seed) |
| 346 | 400 | |