We install PyTorch and set up GPU to make machine learning faster and easier. GPU helps computers learn from data quickly.
Installation and GPU setup in PyTorch
pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu121 # Check if GPU is available in PyTorch import torch print(torch.cuda.is_available())
Use pip install to install PyTorch and related packages.
Use torch.cuda.is_available() to check if PyTorch can use your GPU.
pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu121
True if GPU is ready, otherwise False.import torch print(torch.cuda.is_available())
print(torch.cuda.get_device_name(0))
This program checks if GPU is ready, prints the GPU name if yes, or says CPU is used. Then it creates a small tensor and moves it to the chosen device.
import torch # Check if GPU is available if torch.cuda.is_available(): device = torch.device('cuda') print(f'GPU is available: {torch.cuda.get_device_name(0)}') else: device = torch.device('cpu') print('GPU not available, using CPU instead') # Create a tensor and move it to the device x = torch.tensor([1.0, 2.0, 3.0]) x = x.to(device) print(f'Tensor device: {x.device}')
Make sure your computer has a compatible NVIDIA GPU and NVIDIA drivers installed for GPU support.
PyTorch installation commands may vary by system; check the official PyTorch website for your setup.
If torch.cuda.is_available() returns False, GPU is not ready or drivers are missing.
Install PyTorch using pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu121.
Check GPU availability with torch.cuda.is_available().
Use GPU to speed up machine learning tasks if available.