File size: 2,186 Bytes
25e4412
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
"""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()