Check torch.cuda.is_available() to confirm PyTorch detects a CUDA-enabled GPU, verify that both your model parameters (next(model.parameters()).device) and input tensors (x) reside on cuda (or mps on Apple Silicon), and monitor live GPU utilization/memory allocation via torch.cuda.memory_allocated() or nvidia-smi during a forward/backward pass.
Basic Example
import torch
import torch.nn as nn
# 1. Check driver & PyTorch GPU backend availability (NVIDIA CUDA or Apple Silicon MPS)
print(f"CUDA available: {torch.cuda.is_available()}")
if torch.cuda.is_available():
print(f"Device count: {torch.cuda.device_count()}")
print(f"Current device: {torch.cuda.get_device_name(torch.cuda.current_device())}")
# 2. Select target device and verify BOTH model parameters and input tensors live on it
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = nn.Linear(1024, 1024).to(device)
x = torch.randn(64, 1024, device=device)
print(f"Model device: {next(model.parameters()).device}") # Output: cuda:0
print(f"Tensor device: {x.device}") # Output: cuda:0
# 3. Confirm active GPU execution & VRAM allocation during forward pass
out = model(x)
print(f"Output device: {out.device}") # Output: cuda:0
print(f"VRAM allocated: {torch.cuda.memory_allocated(device) / 1024**2:.2f} MB")
Key Details & Edge Cases
torch.cuda.is_available() == Truedoes NOT mean your code is using the GPU:is_available()only proves the CUDA runtime and GPU driver are visible to PyTorch. If you forget.to(device)on either the model or every input batch (inputs = inputs.to(device)), PyTorch either silently runs on CPU or raisesRuntimeError: Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu!.
- Inspecting
modeldirectly fails on standardnn.Modulesubclasses:- Standard
torch.nn.Moduleinstances do not have a.deviceattribute (unlike Hugging FacePreTrainedModel). Always inspectnext(model.parameters()).device(or check all parameters/buffers with{p.device for p in model.parameters()}in case a submodule was left on CPU).
- Standard
- Why
torch.cuda.is_available()returnsFalseon an NVIDIA machine:- CPU-only PyTorch wheel installed: Running
pip install torchon some platforms or environments pulls a+cpubuild (print(torch.__version__)shows2.x.x+cpuandtorch.version.cudaisNone). Reinstall the CUDA wheel frompytorchmatching your driver. - Driver / CUDA toolkit mismatch or hidden GPU: Check
nvidia-smiin your terminal and ensureCUDA_VISIBLE_DEVICESis not set to""or-1.
- CPU-only PyTorch wheel installed: Running
- Monitoring real-time compute utilization vs. mere memory reservation (
nvidia-smi):torch.cuda.memory_allocated()confirms tensors occupy VRAM, while runningwatch -n 1 nvidia-smi(ornvidia-smi dmon) in a second terminal confirms active SM compute (GPU-Util > 0) rather than a CPU data-loading bottleneck stalling the GPU at0%utilization.
- Apple Silicon Macs (
mpsbackend):- On macOS M1/M2/M3/M4 chips,
torch.cuda.is_available()is alwaysFalse; checktorch.backends.mps.is_available()and move models/tensors totorch("mps").
- On macOS M1/M2/M3/M4 chips,
Comparison of PyTorch GPU Verification Checks
| Check / Tool | What It Verifies | Catches Silent CPU Execution? | Backend Scope | Best Used When |
|---|---|---|---|---|
next(model.parameters()).device & x (Essential) |
Exact device (cuda:0, mps:0, cpu) holding weights and data |
Yes | All (cuda, mps, cpu) |
Asserting inside training/inference scripts that weights and batches moved to GPU. |
torch.cuda.memory_allocated() |
Bytes of active GPU VRAM currently occupied by PyTorch tensors | Yes (stays 0 if on CPU) |
NVIDIA CUDA (torch.mps.current_allocated_memory() on Mac) |
Verifying GPU memory growth across forward/backward steps and debugging OOM leaks. |
torch.cuda.is_available() & torch.version.cuda |
Whether PyTorch was compiled with CUDA and detects a GPU driver | No (hardware capability only) | NVIDIA CUDA | Startup environment diagnostics and choosing device = torch.device(...). |
nvidia-smi (CLI) |
Live hardware GPU-Util %, VRAM usage, temperature, and PID |
Yes | NVIDIA CUDA | Confirming high GPU compute utilization (vs. slow CPU data-loader stalls) during training. |
You must log in or register to comment.
