|
| 1 | +"""Device-name resolution helpers shared by CLI entrypoints.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import sys |
| 6 | + |
| 7 | +import torch |
| 8 | + |
| 9 | +AUTO_DEVICE: str = "auto" |
| 10 | + |
| 11 | + |
| 12 | +def _mps_is_available() -> bool: |
| 13 | + """Return True when the current PyTorch build supports Apple Metal (MPS).""" |
| 14 | + backend = getattr(torch.backends, "mps", None) |
| 15 | + if backend is None: |
| 16 | + return False |
| 17 | + is_available = getattr(backend, "is_available", None) |
| 18 | + if is_available is None: |
| 19 | + return False |
| 20 | + try: |
| 21 | + return bool(is_available()) |
| 22 | + except Exception: |
| 23 | + return False |
| 24 | + |
| 25 | + |
| 26 | +def resolve_device(device_name: str) -> torch.device: |
| 27 | + """Resolve a user-supplied device name into a concrete ``torch.device``. |
| 28 | +
|
| 29 | + ``"auto"`` selects the best available device in this order: CUDA (NVIDIA |
| 30 | + GPU) > MPS (Apple Silicon GPU) > CPU. Any other value is passed through |
| 31 | + to ``torch.device`` as-is so that explicit requests like ``"cuda"`` or |
| 32 | + ``"mps"`` still fail loudly when the underlying backend is unavailable. |
| 33 | + """ |
| 34 | + if device_name == AUTO_DEVICE: |
| 35 | + if torch.cuda.is_available(): |
| 36 | + return torch.device("cuda") |
| 37 | + if _mps_is_available(): |
| 38 | + print( |
| 39 | + "info: no CUDA device detected; using Apple Metal (MPS).", |
| 40 | + file=sys.stderr, |
| 41 | + flush=True, |
| 42 | + ) |
| 43 | + return torch.device("mps") |
| 44 | + print( |
| 45 | + "info: no CUDA or MPS device detected; falling back to CPU " |
| 46 | + "(pass --device cuda or --device mps to override).", |
| 47 | + file=sys.stderr, |
| 48 | + flush=True, |
| 49 | + ) |
| 50 | + return torch.device("cpu") |
| 51 | + return torch.device(device_name) |
0 commit comments