File size: 1,750 Bytes
4807d4b | 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 | """The one place that decides which device and dtype code runs on.
Every component asks this module instead of probing hardware itself, so the
same code runs on a Mac (MPS), a cloud GPU (CUDA) or a CPU-only test box.
"""
from __future__ import annotations
import torch
_DTYPES: dict[str, torch.dtype] = {
"float32": torch.float32,
"fp32": torch.float32,
"float16": torch.float16,
"fp16": torch.float16,
"bfloat16": torch.bfloat16,
"bf16": torch.bfloat16,
}
def resolve_device(name: str = "auto") -> torch.device:
"""Return the device to use. ``auto`` picks cuda > mps > cpu."""
if name == "auto":
if torch.cuda.is_available():
return torch.device("cuda")
if torch.backends.mps.is_available():
return torch.device("mps")
return torch.device("cpu")
device = torch.device(name)
if device.type == "cuda" and not torch.cuda.is_available():
raise RuntimeError("device 'cuda' requested but CUDA is not available")
if device.type == "mps" and not torch.backends.mps.is_available():
raise RuntimeError("device 'mps' requested but MPS is not available")
return device
def resolve_dtype(name: str, device: torch.device) -> torch.dtype:
"""Return the dtype to use.
``auto`` means float32 on CPU and float16 on accelerators. bfloat16 is available but never
chosen implicitly: its lower precision can flip close answers.
"""
if name == "auto":
return torch.float32 if device.type == "cpu" else torch.float16
try:
return _DTYPES[name]
except KeyError:
expected = ", ".join(sorted(_DTYPES))
raise ValueError(f"unknown dtype {name!r}; expected 'auto' or one of: {expected}") from None
|