TExcelTAD
Home › Deep Learning: Neural Networks, Architectures & PyTorch › Devices and Device-Agnostic Code

Devices and Device-Agnostic Code

The same PyTorch program should run on a laptop CPU, an NVIDIA GPU and an Apple-silicon Mac without edits. That works if you follow three habits: pick the device once at the top, create or move every tensor that takes part in a computation onto it, and remember that a GPU runs asynchronously, so timing and error messages show up later than the line that caused them. This lesson builds those habits. Everything recorded here ran on a CPU (the course's Docker image has no GPU, and the owner's machine never trains on one), so the GPU-specific behaviour is described in the text and modelled in a small runnable simulation rather than measured.

The three devices you will meet

Device String When it exists Notes
CPU "cpu" always the default for every tensor; uses several threads (torch.get_num_threads())
NVIDIA GPU "cuda", "cuda:0", "cuda:1" CUDA build of PyTorch plus an NVIDIA driver "cuda" means the current GPU, normally number 0
Apple GPU "mps" macOS on Apple silicon Metal Performance Shaders; a few operations are missing or fall back to the CPU

AMD GPUs with the ROCm build of PyTorch also appear as "cuda", so code written for NVIDIA runs there unchanged. There is a fourth device that every installation has: "meta", which stores shapes and dtypes but no numbers. It is used to build huge models without allocating them, and below it gives a real device-mismatch error on a machine without a GPU.

Device-agnostic code

Choose the device in one place and pass it around. The order of the checks is a preference: CUDA if present, then MPS, then the CPU.

python · try it yourself
import torch
from torch import nn

def pick_device():
    if torch.cuda.is_available():
        return torch.device("cuda")
    if torch.backends.mps.is_available():
        return torch.device("mps")
    return torch.device("cpu")

device = pick_device()
print("device:", device)

torch.manual_seed(0)
model = nn.Sequential(nn.Linear(4, 8), nn.ReLU(), nn.Linear(8, 3))
w_before = model[0].weight
moved = model.to(device)
print("module.to returns the same module:", moved is model, "| same Parameter objects:", model[0].weight is w_before)
print("model on:", next(model.parameters()).device)

x = torch.randn(5, 4)
x_dev = x.to(device)
print("tensor.to on the same device returns itself:", x_dev is x)
x64 = x.to(torch.float64)
print("tensor.to with a new dtype returns a new tensor:", x64 is x, x64.dtype)
y = torch.tensor([0, 2, 1, 1, 0], device=device)
loss = nn.functional.cross_entropy(model(x_dev), y)
print("loss on", loss.device, f"{loss.item():.4f}")

try:
    loss.detach().requires_grad_().numpy()
except RuntimeError as e:
    print("RuntimeError:", e)
print("to NumPy:", [round(v, 4) for v in model(x_dev)[0].detach().cpu().numpy().tolist()])
device: cpu
module.to returns the same module: True | same Parameter objects: True
model on: cpu
tensor.to on the same device returns itself: True
tensor.to with a new dtype returns a new tensor: False torch.float64
loss on cpu 1.0744
RuntimeError: Can't call numpy() on Tensor that requires grad. Use tensor.detach().numpy() instead.
to NumPy: [0.5114, 0.2926, -0.2845]

The recording printed device: cpu; on a GPU machine the same file prints cuda and nothing else changes. Note the asymmetry the output shows:

  • module.to(device) works in place. It moves every parameter and buffer and returns the same module, so model.to(device) on its own line is enough. The Parameter objects stay the same objects; only their data moves.
  • tensor.to(device) returns a tensor. If the tensor is already there with the right dtype it returns the tensor itself; otherwise a new copy. x.to(device) on its own line does nothing useful; write x = x.to(device).
  • Creating directly on the device is cheaper than creating on the CPU and copying: torch.zeros(n, device=device), torch.tensor(labels, device=device).
  • Coming back to NumPy needs .detach() (leave the graph) and .cpu() (NumPy arrays live in CPU memory): t.detach().cpu().numpy(). On the CPU, .cpu() costs nothing, so always write it.

What must be on the same device

An operation runs on the device of its inputs, and all tensor inputs must agree. In one training step that means:

Must be on device How
the model's parameters and buffers model.to(device) once, before training
each input batch xb = xb.to(device) inside the loop
the targets and anything else the loss reads (masks, class weights) yb = yb.to(device); nn.CrossEntropyLoss(weight=w.to(device))
tensors you create inside forward torch.zeros(..., device=x.device), or register them as buffers (next lessons)
the optimizer's state create the optimizer after model.to(device)

Python numbers are fine anywhere (x * 0.5), and so are 0-dimensional CPU tensors in most operations. The last row needs explaining. Because .to() keeps the Parameter objects, an optimizer created before the move still holds the right parameters. The trouble starts when the optimizer already has state: Adam creates its moment estimates at the first step(), on the device and dtype the weights had then. Move the model afterwards and the state stays behind. On a CPU-only machine the same thing can be shown with a dtype change:

python · try it yourself
import torch
from torch import nn

torch.manual_seed(0)
model = nn.Linear(3, 1)
opt = torch.optim.Adam(model.parameters(), lr=0.1)
model(torch.randn(4, 3)).sum().backward()
opt.step()                                         # Adam creates its state now, like the weights
print("Adam state:", {k: str(v.dtype)[6:] for k, v in opt.state[model.weight].items()})
model.double()                                     # stands in for model.to("cuda") after training started
opt.zero_grad()
model(torch.randn(4, 3, dtype=torch.float64)).sum().backward()
try:
    opt.step()
except RuntimeError as e:
    print("RuntimeError:", e)

big = nn.Linear(3, 1, device="meta")               # a second device that exists on every machine
for name, fn in [("weights meta, input cpu", lambda: big(torch.randn(2, 3))),
                 ("cat of cpu and meta", lambda: torch.cat([torch.ones(2), torch.ones(2, device="meta")]))]:
    try:
        fn()
    except RuntimeError as e:
        print(f"{name}: RuntimeError: {e}")
try:
    torch.ones(2).pin_memory()
except RuntimeError as e:
    print("pin_memory without a GPU: RuntimeError:", e)
Adam state: {'step': 'float32', 'exp_avg': 'float32', 'exp_avg_sq': 'float32'}
RuntimeError: expected dtype float for `end` but got dtype double
weights meta, input cpu: RuntimeError: Tensor on device meta is not on the expected device cpu!
cat of cpu and meta: RuntimeError: Tensor on device meta is not on the expected device cpu!
pin_memory without a GPU: RuntimeError: Cannot access accelerator device when none is available.

The first error is Adam's exp_avg (float32) meeting a float64 gradient. With CUDA the same mistake gives a device error at opt.step() instead. The two meta errors are the CPU-only cousin of the most common error in GPU code; with a model on the GPU and a batch left on the CPU it reads "Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu!" (the exact wording varies between PyTorch versions). Whatever the wording, look for the tensor you forgot to move: usually the batch, the targets, or a tensor created inside forward without device=. Loading a checkpoint saved on a GPU on a CPU-only machine needs torch.load(path, map_location="cpu") (or map_location=device).

Pinned memory and non-blocking copies

A copy from CPU memory to the GPU goes through the PCIe bus by DMA, which can only read page-locked (pinned) memory. From ordinary memory, CUDA first copies into a pinned staging buffer, and the transfer blocks the CPU. With pinned memory the copy can run in the background while the CPU prepares the next batch:

python
loader = DataLoader(train_ds, batch_size=256, shuffle=True, num_workers=4,
                    pin_memory=torch.cuda.is_available())      # workers return pinned batches
for xb, yb in loader:
    xb = xb.to(device, non_blocking=True)                     # returns at once, copy runs async
    yb = yb.to(device, non_blocking=True)
    loss = loss_fn(model(xb), yb)                             # queued after the copy on the same stream

On a CPU, non_blocking is ignored and pin_memory raises, as the recording shows, which is why it is guarded with torch.cuda.is_available(). Pinned memory is a limited resource: pin batches, not your whole data set.

The GPU runs asynchronously

When Python executes y = model(x) on a CUDA tensor, PyTorch queues the kernels on the GPU and returns immediately; the GPU works through the queue on its own. The CPU waits only when it needs a result: .item(), .cpu(), .tolist(), print(tensor), a Python if on a tensor value, or an explicit torch.cuda.synchronize(). Two consequences:

  1. Naive timing lies. time.perf_counter() around GPU code measures how long it took to queue the work.
  2. Errors appear late. A failing kernel (an index out of range inside nn.Embedding or cross-entropy, for example) reports at the next synchronisation point, often a later line. Running with CUDA_LAUNCH_BLOCKING=1 makes every launch synchronous so the traceback points at the real line, or reproduce the bug on the CPU, where errors are immediate and clearer.

This plain-Python model of a GPU queue runs in the browser. It has a CPU clock and a "GPU free at" time; a launch costs the CPU 0.01 ms and returns, a synchronisation moves the CPU clock forward to when the GPU is done.

python · try it yourself
class ToyGPU:
    """A toy model of how CUDA runs work: the CPU queues kernels and moves on at once."""
    LAUNCH_MS = 0.01                       # CPU cost of queueing one kernel

    def __init__(self):
        self.cpu_ms = 0.0                  # the CPU's clock (what time.perf_counter sees)
        self.gpu_free_at = 0.0             # when the GPU will have finished its queue

    def launch(self, kernel_ms):
        start = max(self.cpu_ms, self.gpu_free_at)
        self.gpu_free_at = start + kernel_ms
        self.cpu_ms += self.LAUNCH_MS      # returns before the kernel has run

    def cpu_work(self, ms):                # Python code, data loading, logging ...
        self.cpu_ms += ms

    def synchronize(self):                 # torch.cuda.synchronize(), .item(), .cpu(), print(tensor)
        self.cpu_ms = max(self.cpu_ms, self.gpu_free_at)

gpu = ToyGPU()
t0 = gpu.cpu_ms
for _ in range(100):
    gpu.launch(2.0)                        # 100 matrix products of 2 ms each
print(f"naive timing:        {gpu.cpu_ms - t0:7.2f} ms  (only the launches)")
gpu.synchronize()
print(f"after synchronize(): {gpu.cpu_ms - t0:7.2f} ms  (the real GPU time)")

def train(steps, item_every_step):
    g = ToyGPU()
    for _ in range(steps):
        g.cpu_work(1.5)                    # prepare the next batch on the CPU
        g.launch(2.0)                      # forward + backward + step on the GPU
        if item_every_step:
            g.synchronize()                # loss.item() waits for the GPU
    g.synchronize()
    return g.cpu_ms

print(f"100 steps, CPU and GPU overlap:    {train(100, False):6.1f} ms")
print(f"100 steps, loss.item() every step: {train(100, True):6.1f} ms")
naive timing:           1.00 ms  (only the launches)
after synchronize():  200.00 ms  (the real GPU time)
100 steps, CPU and GPU overlap:     201.5 ms
100 steps, loss.item() every step:  350.0 ms

The naive measurement says 1.00 ms for work that takes 200.00 ms. The second pair is the practical lesson: when the CPU prepares the next batch while the GPU computes, the 1.5 ms of CPU work per step hides behind the 2 ms of GPU work and 100 steps take 201.5 ms. Call loss.item() every step and the two can no longer overlap: 3.5 ms per step, 350.0 ms in total. Real loops therefore accumulate the loss on the device and call .item() every few dozen steps, or once per epoch.

To time GPU code for real, synchronise before reading the clock, and warm up first (the first calls include memory allocation and kernel selection):

python
for _ in range(3):
    model(xb)                                   # warm-up
torch.cuda.synchronize()
t0 = time.perf_counter()
for _ in range(20):
    model(xb)
torch.cuda.synchronize()                        # wait for the queue to drain
print((time.perf_counter() - t0) / 20)

torch.cuda.Event(enable_timing=True) measures on the GPU's own clock, and torch.profiler shows CPU and GPU time per operation; both handle the asynchrony for you.

Pitfalls

  • x.to(device) without assigning. Tensors are not moved in place; modules are.
  • Hard-coded .cuda() calls. They crash on a CPU or a Mac. Use .to(device) everywhere, device= when creating tensors, and map_location when loading.
  • The optimizer created before the model moved, after it had state, or state loaded from a checkpoint saved on another device. Create the optimizer after model.to(device); optimizer.load_state_dict moves loaded state to the device of the parameters.
  • .item() or print(loss) every step on a GPU. Each one is a synchronisation that stalls the pipeline.
  • Timing without torch.cuda.synchronize(). You measure the queue, not the work.
  • Assuming the same numbers on every device. GPU kernels sum in a different order than CPU kernels, so results agree to a few decimals, not bit for bit (Checkpoints and reproducibility explains why).

Practice

  1. This loop raises "Expected all tensors to be on the same device". Find the two bugs.
python
model = Net().to(device)
class_w = torch.tensor([1.0, 4.0])                    # up-weight the rare class
loss_fn = nn.CrossEntropyLoss(weight=class_w)
for xb, yb in loader:
    xb.to(device)
    loss = loss_fn(model(xb), yb.to(device))
Answer

xb.to(device) returns a new tensor that is thrown away, so the model receives the CPU batch: write xb = xb.to(device). The class weights are a tensor the loss reads, and they were created on the CPU: write torch.tensor([1.0, 4.0], device=device). (yb.to(device) inside the call is fine.) If the error persists, look inside Net.forward for a tensor created without device=x.device.

  1. In the toy model, the CPU needs 3 ms per step and the GPU 2 ms. How long do 100 steps take with and without a .item() every step?
Answer

Without synchronising, the slower side decides: the CPU, about 300 ms, and the GPU sits idle a third of the time (the job is input-bound, so faster data loading or more num_workers would help, not a faster GPU). With .item() every step: 3 + 2 = 5 ms per step, 500 ms.

  1. A colleague's script reports that a forward pass takes 0.2 ms on the GPU and 15 ms on the CPU. Why might the comparison be wrong, and how do you fix the measurement?
Answer

Without torch.cuda.synchronize() before stopping the clock, the GPU number is only the launch time. Synchronise after the loop (and before starting it), warm up first, and average over many calls, or use CUDA events or torch.profiler.

Test yourself

What does x.to(device) do when x is a CPU tensor and device is a GPU?

  1. Moves x in place
  2. Returns a new tensor on the GPU; x stays on the CPU
  3. Raises an error unless x is pinned
  4. Moves the whole storage of every view of x

Why should the optimizer be created after model.to(device)?

  1. to() replaces the Parameter objects
  2. Optimizer state such as Adam's moments is created on the device the weights had, and does not follow a later move
  3. The learning rate depends on the device
  4. Optimizers can only be created on the CPU

Which line forces the CPU to wait for the GPU?

  1. y = model(x)
  2. loss.backward()
  3. total += loss.item()
  4. optimizer.step()

What does pin_memory=True in a DataLoader buy you on a CUDA machine?

  1. Batches are stored on the GPU
  2. Batches are in page-locked memory, so to(device, non_blocking=True) can copy them asynchronously
  3. The data set is cached between epochs
  4. Workers share one copy of the data set