Skip to content

A straightforward method for training your LLM, from downloading data to generating text.

feat(device): pick CUDA, Apple MPS or CPU automatically

FareedKhan-devd69b5c26696f
diff --git a/src/device.py b/src/device.py
new file mode 100644
index 0000000..04526d7
--- /dev/null
+++ b/src/device.py
@@ -0,0 +1,118 @@
+"""
+Pick the device to train on and report what it is.
+
+``resolve_device("auto")`` returns the best available backend in this order:
+CUDA (NVIDIA GPUs) -> MPS (Apple Silicon) -> CPU. You can also ask for one explicitly:
+``"cuda"``, ``"cuda:1"``, ``"mps"``, ``"cpu"`` or ``"xla"`` (Google TPUs through PyTorch/XLA,
+experimental). Asking for a backend that is not available falls back to the CPU with a
+warning instead of crashing, which keeps the scripts usable on any laptop.
+"""
+
+from __future__ import annotations
+
+import contextlib
+import importlib.util
+import os
+import warnings
+from typing import Any
+
+import torch
+
+DEVICE_CHOICES = ("auto", "cpu", "cuda", "mps", "xla")
+
+
+def _mps_available() -> bool:
+ backend = getattr(torch.backends, "mps", None)
+ return bool(backend is not None and backend.is_available())
+
+
+def _xla_available() -> bool:
+ return importlib.util.find_spec("torch_xla") is not None
+
+
+def resolve_device(requested: str | None = "auto") -> str:
+ """Turn ``"auto"`` or an explicit request into a device string that works on this machine."""
+ req = (requested or "auto").lower()
+ if req == "auto":
+ if torch.cuda.is_available():
+ return "cuda"
+ if _mps_available():
+ return "mps"
+ return "cpu"
+ if req.startswith("cuda"):
+ if torch.cuda.is_available():
+ return req
+ warnings.warn("CUDA was requested but is not available, using the CPU instead.", stacklevel=2)
+ return "cpu"
+ if req == "mps":
+ if _mps_available():
+ return "mps"
+ warnings.warn("MPS was requested but is not available, using the CPU instead.", stacklevel=2)
+ return "cpu"
+ if req.startswith("xla"):
+ if _xla_available():
+ import torch_xla # type: ignore[import-not-found] # noqa: F401
+
+ return "xla"
+ warnings.warn("XLA was requested but torch_xla is not installed, using the CPU instead.", stacklevel=2)
+ return "cpu"
+ if req == "cpu":
+ return "cpu"
+ raise ValueError(f"Unknown device {requested!r}; choose one of {DEVICE_CHOICES}")
+
+
+def device_type(device: str | torch.device) -> str:
+ """``"cuda:1"`` -> ``"cuda"``; used for autocast and for capability checks."""
+ return str(device).split(":", 1)[0]
+
+
+def autocast(device: str, dtype: str | None) -> contextlib.AbstractContextManager[Any]:
+ """Mixed-precision context for ``dtype`` in ``{"bf16", "fp16", None}``; a no-op on CPU or when off."""
+ kind = device_type(device)
+ if dtype is None or kind not in ("cuda", "mps", "xla"):
+ return contextlib.nullcontext()
+ torch_dtype = torch.bfloat16 if dtype == "bf16" else torch.float16
+ return torch.autocast(device_type=kind, dtype=torch_dtype)
+
+
+def sync_step(device: str) -> None:
+ """Flush pending work on lazy backends. Needed once per optimizer step on XLA (TPU)."""
+ if device_type(device) == "xla":
+ import torch_xla # type: ignore[import-not-found]
+
+ sync = getattr(torch_xla, "sync", None)
+ if sync is not None:
+ sync()
+ else: # older torch_xla releases
+ import torch_xla.core.xla_model as xm # type: ignore[import-not-found]
+
+ xm.mark_step()
+
+
+def configure_cpu_threads(num_threads: int | None = None) -> int:
+ """Use every physical core for CPU training unless the user set ``OMP_NUM_THREADS``."""
+ if num_threads is None and "OMP_NUM_THREADS" not in os.environ:
+ num_threads = os.cpu_count() or 1
+ if num_threads:
+ torch.set_num_threads(num_threads)
+ return torch.get_num_threads()
+
+
+def describe_device(device: str) -> str:
+ """One line per fact about the runtime, for logs and bug reports."""
+ lines = [f"PyTorch {torch.__version__} | device: {device}"]
+ kind = device_type(device)
+ if kind == "cuda" and torch.cuda.is_available():
+ index = torch.device(device).index or 0
+ props = torch.cuda.get_device_properties(index)
+ lines.append(
+ f"GPU: {props.name} | capability {props.major}.{props.minor} | "
+ f"{props.total_memory / 1024**3:.1f} GiB | CUDA {torch.version.cuda}"
+ )
+ elif kind == "mps":
+ lines.append("GPU: Apple Silicon (MPS)")
+ elif kind == "xla":
+ lines.append("Accelerator: XLA (TPU), experimental support")
+ else:
+ lines.append(f"CPU threads: {torch.get_num_threads()} (of {os.cpu_count()} logical cores)")
+ return "\n".join(lines)
diff --git a/src/post_training/distributed.py b/src/post_training/distributed.py
index 71d33f4..ec2151c 100644
--- a/src/post_training/distributed.py
+++ b/src/post_training/distributed.py
@@ -16,6 +16,8 @@ import torch
import torch.distributed as dist
from torch.nn.parallel import DistributedDataParallel as DDP
+from src.device import configure_cpu_threads, resolve_device
+
@dataclass
class DDPContext:
@@ -33,22 +35,27 @@ class DDPContext:
return self.world_size > 1
-def ddp_setup(device: str = "cuda") -> DDPContext:
+def ddp_setup(device: str = "auto") -> DDPContext:
"""Initialize the process group if launched under torchrun; otherwise single-process.
+ ``device`` is ``"auto"`` (CUDA, then Apple MPS, then CPU), or an explicit ``"cuda"``,
+ ``"mps"`` or ``"cpu"``; an unavailable choice falls back to the CPU with a warning.
+
Reads ``RANK`` / ``LOCAL_RANK`` / ``WORLD_SIZE`` from the environment (set by
torchrun). Uses the NCCL backend on CUDA, gloo on CPU.
"""
+ device = resolve_device(device)
world_size = int(os.environ.get("WORLD_SIZE", "1"))
if world_size == 1:
- dev = device if (device == "cuda" and torch.cuda.is_available()) else "cpu"
- if dev == "cuda":
+ if device == "cuda":
torch.cuda.set_device(0)
- return DDPContext(rank=0, local_rank=0, world_size=1, device=dev)
+ elif device == "cpu":
+ configure_cpu_threads()
+ return DDPContext(rank=0, local_rank=0, world_size=1, device=device)
rank = int(os.environ["RANK"])
local_rank = int(os.environ["LOCAL_RANK"])
- backend = "nccl" if (device == "cuda" and torch.cuda.is_available()) else "gloo"
+ backend = "nccl" if device == "cuda" else "gloo"
dist.init_process_group(backend=backend, rank=rank, world_size=world_size)
if device == "cuda":
torch.cuda.set_device(local_rank)
diff --git a/tests/test_device.py b/tests/test_device.py
new file mode 100644
index 0000000..8d79cdc
--- /dev/null
+++ b/tests/test_device.py
@@ -0,0 +1,32 @@
+"""Device selection: "auto" picks what exists, a missing backend falls back to the CPU."""
+
+from __future__ import annotations
+
+import contextlib
+
+import pytest
+import torch
+
+from src.device import autocast, describe_device, device_type, resolve_device
+
+
+def test_auto_returns_a_usable_device() -> None:
+ device = resolve_device("auto")
+ assert device in ("cuda", "mps", "cpu")
+ torch.zeros(2, device=device) # actually usable
+
+
+def test_missing_backend_falls_back_to_cpu_with_a_warning(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(torch.cuda, "is_available", lambda: False)
+ with pytest.warns(UserWarning, match="CUDA"):
+ assert resolve_device("cuda") == "cpu"
+ assert resolve_device("cpu") == "cpu"
+ with pytest.raises(ValueError):
+ resolve_device("tpu-please")
+
+
+def test_autocast_is_a_no_op_on_cpu() -> None:
+ assert isinstance(autocast("cpu", "bf16"), contextlib.nullcontext)
+ assert isinstance(autocast("cuda", None), contextlib.nullcontext)
+ assert device_type("cuda:1") == "cuda"
+ assert "PyTorch" in describe_device("cpu")