"""Hardware detection. The API process probes torch in a short-lived subprocess so it never creates a CUDA context itself (that would permanently hold ~300 MB of a 4 GB GPU).""" from __future__ import annotations import json import logging import subprocess import sys import threading from dataclasses import dataclass log = logging.getLogger(__name__) PROBE_CODE = """ import json, torch info = {"torch_version": torch.__version__, "device": "cpu", "gpu_name": None, "vram_gb": None} if torch.cuda.is_available(): p = torch.cuda.get_device_properties(0) info.update(device="cuda", gpu_name=p.name, vram_gb=round(p.total_memory / 2**30, 1)) elif getattr(torch.backends, "mps", None) and torch.backends.mps.is_available(): info.update(device="mps", gpu_name="Apple Silicon GPU") print(json.dumps(info)) """ @dataclass(frozen=True) class DeviceInfo: device: str gpu_name: str | None vram_gb: float | None torch_version: str _cached: DeviceInfo | None = None _lock = threading.Lock() def detect_in_process() -> str: """Used inside worker subprocesses (they need torch anyway): cuda > mps > cpu.""" import torch if torch.cuda.is_available(): return "cuda" if getattr(torch.backends, "mps", None) and torch.backends.mps.is_available(): return "mps" return "cpu" def probe() -> DeviceInfo: global _cached with _lock: if _cached is not None: return _cached try: proc = subprocess.run([sys.executable, "-c", PROBE_CODE], capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=120, check=True) data = json.loads(proc.stdout.strip().splitlines()[-1]) _cached = DeviceInfo(data["device"], data["gpu_name"], data["vram_gb"], data["torch_version"]) except Exception: # noqa: BLE001 log.exception("device probe failed; assuming CPU") _cached = DeviceInfo("cpu", None, None, "unknown") log.info("device: %s", _cached) return _cached def probe_in_background() -> None: threading.Thread(target=probe, name="device-probe", daemon=True).start()