0
0
PyTorchml~5 mins

Installation and GPU setup in PyTorch

Choose your learning style9 modes available
Introduction

We install PyTorch and set up GPU to make machine learning faster and easier. GPU helps computers learn from data quickly.

When you want to start using PyTorch for machine learning projects.
When you want your computer to train models faster using GPU.
When you need to check if your GPU is ready for PyTorch.
When you want to update PyTorch or CUDA for better performance.
Syntax
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.

Examples
Installs PyTorch and its vision and audio libraries.
PyTorch
pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu121
Prints True if GPU is ready, otherwise False.
PyTorch
import torch
print(torch.cuda.is_available())
Shows the name of the first GPU device.
PyTorch
print(torch.cuda.get_device_name(0))
Sample Model

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.

PyTorch
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}')
OutputSuccess
Important Notes

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.

Summary

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.