"""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