Download src/discerna/device.py from CrazyH0rse/Discerna-v1-475M: direct link, hf CLI and curl.
- Browser
- Download file 1.75 kB
-
https://huggingface.co/CrazyH0rse/Discerna-v1-475M/resolve/main/src/discerna/device.py
- Command line
-
hf download hf://CrazyH0rse/Discerna-v1-475M/src/discerna/device.py
-
curl -L -o device.py https://huggingface.co/CrazyH0rse/Discerna-v1-475M/resolve/main/src/discerna/device.py
1.75 kB
| """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 | |