python-pytorchHow can I use a GPU to run Python and PyTorch?
Using a GPU to run Python and PyTorch is relatively straightforward. Here is an example of code that can be used to check if a GPU is being used:
import torch
if torch.cuda.is_available():
device = torch.device("cuda") # a CUDA device object
print("CUDA is available")
else:
print("CUDA is not available")
Output example
CUDA is available
To use a GPU with PyTorch, the code needs to be modified to include the following components:
-
A device object that will be used to run operations on the GPU. This can be done with the following line of code:
device = torch.device("cuda")
. -
A function that will transfer data from the CPU to the GPU. This can be done with the following line of code:
data = data.to(device)
. -
A function that will transfer data from the GPU to the CPU. This can be done with the following line of code:
data = data.cpu()
. -
A function that will run operations on the GPU. This can be done with the following line of code:
output = model(data)
.
Helpful links
More of Python Pytorch
- How can I use Python PyTorch with CUDA?
- How can I optimize a PyTorch model using ROCm on Python?
- How do I convert a Python Torch tensor to a float?
- How can I use PyTorch with Python 3.8 on a Jetson device?
- How can I use Python PyTorch without CUDA?
- How do I plot a PyTorch tensor using Python?
- How do I install PyTorch with GPU support using Python?
- How can I use Python Torch to categorize a tensor?
- How can I use Python.net and PyTorch together?
- How do I install Python version 2.0 for PyTorch?
See more codes...