How to Use GPU for Training in PyTorch
In this article
Using a GPU in PyTorch can speed up model training by 10–100x compared to CPU, especially for deep learning tasks. This guide shows you how to check for GPU availability, move tensors and models to the GPU, and run training loops efficiently. You need PyTorch installed with CUDA support (see below) and a compatible NVIDIA GPU.
What You'll Need
- An NVIDIA GPU with CUDA compute capability 3.0 or higher (most GTX 900 series and later).
- PyTorch installed with CUDA support. Install via
pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu121(adjust cu version to match your driver). - NVIDIA drivers installed (usually already present if you have a GPU).
- Basic knowledge of PyTorch tensors and model definitions.
Step-by-Step
- Check GPU availability – Run
import torch; print(torch.cuda.is_available()). If it printsTrue, CUDA is working. IfFalse, see Troubleshooting. - Set the device – Create a variable
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu'). This lets your code fall back to CPU if no GPU is found. - Move your model to the GPU – After defining your model (e.g.,
model = MyModel()), callmodel.to(device). This transfers all model parameters to the GPU. - Move your data to the GPU – For each batch in your training loop, transfer the input and target tensors:
inputs, labels = inputs.to(device), labels.to(device). Do this inside the loop, not on the whole dataset, to avoid memory overflow. - Run your training loop – The loop itself stays the same: forward pass, loss computation, backward pass, optimizer step. Just ensure the tensors are on the device.
- Move results back to CPU when needed – For evaluation or saving, use
tensor.cpu()ortensor.item()for scalars. For example, to get accuracy:correct = (predicted == labels).sum().item(). - Use
with torch.no_grad()for inference – When evaluating or predicting, wrap the forward pass inwith torch.no_grad():to save memory and speed up computation. - For multiple GPUs (optional) – Wrap your model with
torch.nn.DataParallel(model)to use multiple GPUs. Then call.to(device)as usual. For more control, usetorch.distributed.
Common Mistakes
- Forgetting to move the model – If you only move data to GPU but not the model, you'll get a runtime error about mixed device types.
- Moving the entire dataset to GPU – This can cause out-of-memory errors. Move data batch by batch inside the loop.
- Using
.cuda()directly – This is less flexible. Use.to(device)so you can switch to CPU easily. - Not calling
model.train()/model.eval()– Some layers (dropout, batch norm) behave differently. Set the mode appropriately. - Ignoring the device of tensors created manually – If you create a tensor with
torch.zeros(...), it's on CPU. Passdevice=deviceto the constructor.
Tips
- Use
torch.cuda.memory_summary()to debug memory usage. - Prefetch data: use
DataLoaderwithnum_workers>0andpin_memory=Truefor faster data transfer. - Use mixed precision (float16) with
torch.cuda.ampto speed up training on newer GPUs (Volta and later). - Keep your batch size moderate; if you run out of memory, reduce it.
- Set
torch.backends.cudnn.benchmark = Trueto let cuDNN auto-tune for your hardware, which can speed up convolutions.
Troubleshooting
torch.cuda.is_available()returns False – Check that you installed a CUDA-enabled PyTorch (not the CPU-only version). Runpip list | grep torchto see the version. Reinstall with the correct index URL. Also verify your NVIDIA driver withnvidia-smi.- RuntimeError: Expected all tensors to be on the same device – This means some tensors are on CPU and others on GPU. Trace back which tensors you forgot to move. Use
print(tensor.device)to debug. - CUDA out of memory – Reduce batch size, use smaller input images, or free up memory with
delandtorch.cuda.empty_cache(). Also check for memory leaks by not accumulating gradients. - Slow training despite GPU – Make sure you're not moving data to GPU every iteration (that's fine, but avoid moving the model repeatedly). Also check that your GPU utilization is high using
nvidia-smi; if it's low, your data loading may be the bottleneck. - Error: 'cuda' device not found – This can happen if you run on a system without GPU or if PyTorch was built without CUDA. Reinstall with the appropriate CUDA version.
Frequently Asked Questions
How do I know if my GPU is compatible with PyTorch?
Check your GPU model with nvidia-smi or in system info. PyTorch supports NVIDIA GPUs with compute capability 3.0 or higher. Most modern NVIDIA GPUs work.
Can I use an AMD GPU with PyTorch?
Yes, but it's more complex. PyTorch has ROCm support for some AMD GPUs, but installation is not as straightforward as CUDA. Check the official PyTorch ROCm installation guide.
What is the difference between .cuda() and .to(device)?
.cuda() moves a tensor/model to GPU, but it's hardcoded. .to(device) is more flexible because you can set device to 'cpu' or 'cuda' dynamically, making your code portable.
How do I use multiple GPUs for training?
Use torch.nn.DataParallel for simple multi-GPU. For more advanced distributed training, use torch.distributed with torch.nn.parallel.DistributedDataParallel. Both require moving the model to a device first.
Why is my GPU not being used even though it's available?
Make sure you called model.to(device) and that your data batches are also on the GPU. Also check that you're not accidentally running inference in torch.no_grad() on CPU tensors.
Can I use the GPU for inference only?
Yes, the same steps apply. Move the model to GPU, load your input tensors to GPU, and run forward pass. Use torch.no_grad() to save memory.