Devices & Accelerators: CUDA, ROCm, MPS, XPU, CPU

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

Every tensor and every module lives on a device, and operations require their operands to be on the same one. This page covers the device types PyTorch 2.15 supports, the unified torch.accelerator API for writing device-agnostic code, the per-backend details and the pitfalls (asynchronous execution, unsupported dtypes, memory caches). It targets Python 3.13 and PyTorch 2.15. Examples were run on Python 3.13 with PyTorch 2.15 on 2026-10-31 on a macOS arm64 machine, where torch.accelerator selects Apple MPS; the two CUDA-only examples (device syntax with cuda:1 and the CUDA timing example) need NVIDIA GPUs and were not executed, and the XPU example took its fallback branch. Installing the right build is covered in Installation and Versions.

torch.device

A torch.device has a type (cpu, cuda, mps, xpu, meta, …​) and an optional index. Without an index it means the current device of that type. Everywhere a device is accepted you can pass a string ("cuda:0"), a torch.device, or an integer, which means the current accelerator type with that ordinal.

import torch

cpu = torch.device("cpu")
gpu1 = torch.device("cuda", 1)       # same as torch.device("cuda:1")
x = torch.zeros(2, device="cuda")    # current CUDA device
y = x.to("cpu")                      # copy to host
z = torch.zeros(2, device=0)         # ordinal 0 of the current accelerator type

with torch.device("cuda:1"):         # default device for factory calls in the block
    w = torch.ones(3)                # allocated on cuda:1
torch.set_default_device("cpu")      # global default

Rules worth remembering:

  • Tensors never move between devices automatically. Mixing a CPU tensor and a GPU tensor in one operation raises a RuntimeError. The one exception is a zero-dimensional CPU tensor (a scalar), which is transferred when needed.

  • The with torch.device(...) context manager has a small overhead on every torch call, and an explicit device= argument to a factory function overrides it.

  • tensor.to(device) returns the same tensor when it is already there and a copy otherwise, so reassign the result. module.to(device) moves parameters and buffers in place and also returns the module.

The torch.accelerator API

PyTorch 2.15 documents torch.accelerator as a backend-neutral API. It replaces the habit of hard-coding torch.cuda calls.

import torch

if torch.accelerator.is_available():
    acc = torch.accelerator.current_accelerator()      # e.g. device(type='cuda')
    device = torch.device(acc.type)
    print(device, torch.accelerator.device_count())    # mps 1 on an Apple silicon Mac
else:
    device = torch.device("cpu")

x = torch.randn(4, 4, device=device)
torch.accelerator.synchronize()                        # wait for queued kernels

print(torch.accelerator.memory_allocated(),            # bytes held by tensors
      torch.accelerator.memory_reserved())             # bytes held by the allocator
torch.accelerator.empty_cache()                        # release unused cached memory

The documented functions fall into groups:

  • Device and runtime: device_count, is_available, current_accelerator, set_device_index, current_device_index, device_index (a context manager), get_device_capability, set_stream, current_stream, synchronize. The older set_device_idx and current_device_idx spellings are deprecated.

  • Memory: empty_cache, empty_host_cache, get_memory_info, memory_allocated, memory_reserved, max_memory_allocated, max_memory_reserved, memory_stats, reset_peak_memory_stats, reset_accumulated_memory_stats.

  • Random numbers: get_rng_state, get_rng_state_all, initial_seed.

  • Graphs: the Graph class for capture and replay.

is_available() is true only when the build includes the backend, the drivers are present and at least one device is visible. The accelerator types named in the documentation include CUDA, XPU, MPS and MTIA; which of them a build supports depends on the wheel you installed. Per-backend modules (torch.cuda, torch.xpu, torch.mps) still exist and expose backend-specific features such as CUDA streams, events and graphs.

CPU

The CPU is always available. Intra-op parallelism uses a thread pool whose size defaults to the number of physical cores and is controlled with torch.set_num_threads(n) or the OMP_NUM_THREADS environment variable. torch.get_num_threads() reports it. Oversubscription is a common slowdown: a DataLoader with several worker processes each using all cores contends badly, so cap threads per worker (see Workers, Pinned Memory and Samplers and Performance Tuning Guide).

CUDA (NVIDIA)

CUDA is the most complete backend. Operations are asynchronous: a call returns after queueing a kernel on the current stream, and errors can surface later at an unrelated line. Synchronization points are torch.cuda.synchronize(), .item(), .cpu(), print of a tensor and similar host reads. This matters for timing, as the next example shows.

import time
import torch

assert torch.cuda.is_available()
dev = torch.device("cuda")
a = torch.randn(4096, 4096, device=dev)

torch.cuda.synchronize()
t0 = time.perf_counter()
for _ in range(10):
    b = a @ a
torch.cuda.synchronize()          # without this the loop only measures queueing
print((time.perf_counter() - t0) / 10, "s per matmul")

print(torch.cuda.get_device_name(0), torch.cuda.get_device_capability(0))
print(torch.cuda.memory_allocated() / 2**20, "MiB allocated")

Other CUDA facts:

  • Choose visible GPUs with the CUDA_VISIBLE_DEVICES environment variable before the process starts; inside the process, indices are renumbered from 0.

  • A caching allocator keeps freed blocks reserved, so nvidia-smi shows more memory than torch.cuda.memory_allocated(). See GPU Memory and Activation Checkpointing.

  • Copies from pinned (page-locked) host memory can be asynchronous with non_blocking=True; see the DataLoader page above.

  • Precision options such as TF32 and bfloat16 are covered in Mixed Precision with torch.amp and the general Hardware, Memory and Mixed Precision page.

ROCm (AMD)

ROCm builds reuse the CUDA interface through HIP. You write torch.device("cuda"), .cuda() and torch.cuda.* exactly as for NVIDIA; the strings "rocm" and "hip" are not valid device names. To tell the builds apart, test torch.version.hip, which is set on ROCm builds, and torch.version.cuda for CUDA builds; torch.cuda.is_available() returns the same kind of answer on both.

import torch

if torch.cuda.is_available():
    kind = "ROCm/HIP" if torch.version.hip else "CUDA"
    print(kind, torch.cuda.get_device_name(0))

Documented ROCm differences include: the caching allocator keeps memory reserved, so tools such as amd-smi show it as used; the nccl and gloo distributed backends are the supported ones (the nccl name is served by RCCL); TF32 is supported on MI300 through hipBLASLt; the FFT plan cache size cannot be set; and PYTORCH_NO_HIP_MEMORY_CACHING=1 disables the allocator cache for debugging. The page does not describe HIP_VISIBLE_DEVICES; consult the ROCm documentation for device visibility (this claim is unverified here).

MPS (Apple silicon)

The MPS backend runs on the GPU of Apple-silicon Macs through Metal. Check availability first; torch.backends.mps.is_built() distinguishes a build without MPS from unsupported hardware or an OS that is too old (the page lists macOS 15.0 or later).

import torch

if torch.backends.mps.is_available():
    device = torch.device("mps")
    x = torch.ones(5, device=device)
    y = x * 2
    print(y.device)
else:
    print("built with MPS:", torch.backends.mps.is_built())

The main pitfall is precision: torch.float64 and torch.complex128 are not supported on MPS because Metal has no double type. Creating such a tensor on mps raises a TypeError, and .to("mps") on a float64 tensor raises instead of silently downcasting. PYTORCH_ENABLE_MPS_FALLBACK=1 does not help with these dtypes; do the double-precision work on the CPU. Unified memory means there is no separate GPU memory budget to monitor in the CUDA sense.

XPU (Intel GPUs)

XPU supports Intel Data Center GPU Max and Intel Arc client GPUs (including Core Ultra processors with Arc graphics), with the operating-system and driver prerequisites listed in the official guide. Install the xpu wheel from https://download.pytorch.org/whl/xpu (see the installation page). Porting CUDA code is mostly replacing "cuda" with "xpu".

import torch

if torch.xpu.is_available():
    device = torch.device("xpu")
    model = torch.nn.Linear(8, 2).to(device)
    out = model(torch.randn(4, 8, device=device))
    torch.xpu.synchronize()
    print(out.device)
else:
    print("check the Intel GPU driver installation")

The guide notes that its AMP training example uses a gradient scaler, which requires FP64 support that Intel Arc A-Series GPUs lack, so the scaler must be disabled on those devices.

The meta device

device="meta" creates tensors that have shapes and dtypes but no storage. Operations on them only propagate shape and dtype, which makes it possible to build or inspect very large models without allocating memory and is used by tools that shard or lazily initialize models (see nn.Module).

import torch

with torch.device("meta"):
    layer = torch.nn.Linear(10_000, 10_000)     # no memory allocated
print(layer.weight.shape, layer.weight.device)   # torch.Size([10000, 10000]) meta
layer = layer.to_empty(device="cpu")             # allocate uninitialized storage (400 MB)

Reading values from a meta tensor is an error, and to_empty leaves the parameters uninitialized, so run your initialization afterwards.

A device-agnostic pattern

import torch
from torch import nn


def pick_device() -> torch.device:
    if torch.accelerator.is_available():
        return torch.device(torch.accelerator.current_accelerator().type)
    return torch.device("cpu")


device = pick_device()
model = nn.Linear(16, 4).to(device)
batch = torch.randn(32, 16).to(device, non_blocking=True)
print(model(batch).shape, device)

Create tensors directly on the target device (torch.zeros(..., device=device)) rather than creating on the CPU and copying, create the optimizer after moving the model, and keep checkpoint loading in mind: torch.load(..., map_location=device) controls where saved tensors land (see Saving and Loading Models).

Common errors

  • "Expected all tensors to be on the same device": one operand (often a mask, an index tensor or a freshly created constant) was built on the CPU.

  • "CUDA error: device-side assert triggered": usually an out-of-range index. Rerun on the CPU to get a readable message, or set CUDA_LAUNCH_BLOCKING=1 to make errors synchronous.

  • "CUDA out of memory": reduce batch size, use mixed precision or activation checkpointing; see the memory page.

  • Silent slowness from implicit synchronization in a hot loop (.item() every step); log every N steps instead.