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.device) 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() == True does 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 raises RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu!.
  • Inspecting model.device directly fails on standard nn.Module subclasses:
    • Standard torch.nn.Module instances do not have a .device attribute (unlike Hugging Face PreTrainedModel). Always inspect next(model.parameters()).device (or check all parameters/buffers with {p.device for p in model.parameters()} in case a submodule was left on CPU).
  • Why torch.cuda.is_available() returns False on an NVIDIA machine:
    • CPU-only PyTorch wheel installed: Running pip install torch on some platforms or environments pulls a +cpu build (print(torch.__version__) shows 2.x.x+cpu and torch.version.cuda is None). Reinstall the CUDA wheel from pytorch.org matching your driver.
    • Driver / CUDA toolkit mismatch or hidden GPU: Check nvidia-smi in your terminal and ensure CUDA_VISIBLE_DEVICES is not set to "" or -1.
  • Monitoring real-time compute utilization vs. mere memory reservation (nvidia-smi):
    • torch.cuda.memory_allocated() confirms tensors occupy VRAM, while running watch -n 1 nvidia-smi (or nvidia-smi dmon) in a second terminal confirms active SM compute (GPU-Util % > 0%) rather than a CPU data-loading bottleneck stalling the GPU at 0% utilization.
  • Apple Silicon Macs (mps backend):
    • On macOS M1/M2/M3/M4 chips, torch.cuda.is_available() is always False; check torch.backends.mps.is_available() and move models/tensors to torch.device("mps").

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.device (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.