Runtime capability detection
A program needs to determine whether GPU acceleration is available before choosing a device.
PyTorch · Module
torch.cuda provides PyTorch support for CUDA tensor types and GPU computation. Import it safely, then use torch.cuda.is_available() to determine whether CUDA can be used.
The torch.cuda module provides CUDA-backed tensor support and GPU operations. It can be imported safely because CUDA initialization is lazy; check availability before selecting a CUDA device or allocating CUDA tensors.
torch.cudatorch.cuda.is_available() to test whether the current installation and system can use CUDA.torch.cuda.is_available() before relying on GPU support.import torch
if torch.cuda.is_available():
device = torch.device("cuda")
x = torch.randn(2, 3, device=device)
print(x.device)
else:
print("CUDA is unavailable")Checks CUDA support before creating a tensor on the CUDA device.
A program needs to determine whether GPU acceleration is available before choosing a device.
Tensor workloads should execute on a CUDA-capable GPU rather than the CPU.
An application needs PyTorch's CUDA-specific device, stream, or initialization utilities.
torch.cuda?torch.cuda is PyTorch's CUDA support module. It provides CUDA tensor types and GPU-oriented operations while following the same general tensor-function model as CPU tensors.
Follow-up: How should code handle systems without CUDA? Check torch.cuda.is_available() and select a compatible fallback device before allocating tensors.
CUDA initialization is lazy, so importing torch.cuda is safe even when the system does not support CUDA. Availability is determined with torch.cuda.is_available().
Follow-up: Why is lazy initialization useful? It lets portable programs import CUDA-related functionality without immediately requiring a usable CUDA runtime.
CUDA tensors use GPUs for computation, so tensors must be allocated on or moved to a CUDA device to run those operations there. A device can be represented with torch.device("cuda").
Follow-up: What should a multi-GPU program add? Select a specific device, such as cuda:0, and manage the active device deliberately.
torch.devicetorch.cuda.is_availabletorch.cuda.inittorch.cuda.is_initializedtorch.cuda.devicetorch.cuda.Stream