How to Use GPU on PyTorch
In this article
Yes, you can use a GPU with PyTorch to accelerate deep learning tasks—provided you have a compatible NVIDIA GPU and the correct software stack installed. PyTorch automatically leverages GPU acceleration when available, but you must explicitly move your models and data to the GPU device using .to(device) or similar methods. This guide walks you through setting up and using GPU support in PyTorch, avoiding common pitfalls and ensuring optimal performance.
What You'll Need
- An NVIDIA GPU with CUDA support (most modern GeForce, Quadro, or Tesla cards)
- CUDA drivers installed and up to date
- PyTorch installed with CUDA support
- Python environment (preferably via conda or venv)
- Basic knowledge of Python and PyTorch tensors and models
Step-by-Step
- Check if your system has a compatible NVIDIA GPU. Open a terminal and run
nvidia-smi. If it returns GPU information, your hardware is recognized. If not, ensure drivers are properly installed. - Verify CUDA is available. In Python, run:
If this returnsimport torch print(torch.cuda.is_available())True, CUDA is working. If not, reinstall or update your GPU drivers. - Install or reinstall PyTorch with CUDA support. Use the official PyTorch website to generate the correct install command for your system. Example:
This installs PyTorch with CUDA 11.8 support. Choose the version matching your CUDA driver.pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118 - Confirm PyTorch sees your GPU. Run:
This should return the device index and GPU name (e.g., 'GeForce RTX 3070').print(torch.cuda.current_device()) print(torch.cuda.get_device_name(0)) - Define the device for your model and data. Add this line at the start of your script:
This setsdevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')deviceto GPU if available, otherwise falls back to CPU. - Move your model to the GPU. After defining your model, use:
This transfers all model parameters and buffers to GPU memory.model = model.to(device) - Move input data (tensors) to the GPU. Before passing data to the model, ensure it’s on the same device:
Mismatched devices cause runtime errors.inputs = inputs.to(device) labels = labels.to(device) - Train or infer as usual. The forward and backward passes will now run on GPU. Monitor GPU usage with
nvidia-smito confirm activity. - Move output back to CPU if needed. For example, to convert predictions to NumPy:
GPU tensors cannot be directly converted to NumPy; they must first be on CPU.predictions = predictions.cpu().detach().numpy() - Free GPU memory when done. Delete tensors and call
torch.cuda.empty_cache()if reusing GPU across experiments:
This helps avoid out-of-memory errors.del outputs, loss torch.cuda.empty_cache()
Common Mistakes
- Forgetting to move both model and data to GPU: If only one is on GPU, operations fail with device mismatch errors.
- Using CPU tensors in GPU model: Even one CPU tensor in a forward pass crashes the code. Always check device alignment.
- Assuming CUDA is available without checking: Always wrap GPU code in
if torch.cuda.is_available()or use the fallback pattern. - Ignoring GPU memory limits: Large batch sizes or models may exceed VRAM. Monitor usage and reduce batch size if needed.
- Not clearing cache after deleting tensors: PyTorch does not always free memory immediately. Use
empty_cache()cautiously—it doesn’t help with fragmentation.
Tips
- Use
device = torch.device('cuda')only if you’re certain GPU is available. Better to use the conditional form. - For multi-GPU systems, use
torch.nn.DataParallelortorch.nn.parallel.DistributedDataParallelto leverage multiple cards. - Batch size can often be increased on GPU. Experiment to find the largest size that fits in memory.
- Use mixed precision training (
torch.cuda.amp) to reduce memory usage and speed up training. - Always test your script with CPU fallback enabled, especially when sharing code.
- Run
nvidia-smi. If it fails, reinstall GPU drivers. - Check
torch.cuda.is_available(). IfFalse, reinstall PyTorch with the correct CUDA version. - Ensure your Python environment matches the PyTorch install (e.g., same conda environment).
- Look for version conflicts: mismatched CUDA driver and PyTorch build cause silent failures.
- If you see 'out of memory' errors, reduce batch size or use
torch.cuda.empty_cache(). - Restart your kernel or script—sometimes stale GPU memory blocks new allocations.
Troubleshooting
If GPU usage fails, start with these checks:
Frequently Asked Questions
Can I use AMD GPUs with PyTorch?
AMD GPUs are not supported via CUDA. However, experimental support exists through ROCm on Linux. This requires specific AMD cards and ROCm drivers. Most users rely on NVIDIA for reliable PyTorch GPU support.Do I need to install CUDA separately?
No, PyTorch comes with its own CUDA runtime. You only need NVIDIA drivers installed. The CUDA toolkit (nvcc) is optional unless you’re compiling custom extensions.Why is my GPU not detected?
This usually means outdated drivers, incorrect PyTorch build, or no CUDA support in the installed version. Runnvidia-smi and torch.cuda.is_available() to isolate the issue.
Can I use GPU on Google Colab?
Yes. In Colab, go to Runtime > Change runtime type > select GPU. Then run!nvidia-smi and your PyTorch code. GPU is preconfigured.
Does using GPU always speed up training?
Not always. Small models or datasets may not benefit due to GPU transfer overhead. GPUs shine with large models and batch sizes.How do I switch back to CPU?
Setdevice = torch.device('cpu') and move model and data using .to('cpu'). No restart needed.