0
0
PyTorchml~20 mins

Installation and GPU setup in PyTorch - ML Experiment: Train & Evaluate

Choose your learning style9 modes available
Experiment - Installation and GPU setup
Problem:You want to install PyTorch and set up your computer to use the GPU for faster training of machine learning models.
Current Metrics:No model training done yet; GPU is not being used.
Issue:PyTorch is installed but only uses the CPU, resulting in slow training times.
Your Task
Install PyTorch with GPU support and verify that the GPU is being used during training.
Use PyTorch version compatible with CUDA 11.8 or higher.
Do not change the model architecture or dataset.
Only modify installation and setup steps.
Hint 1
Hint 2
Hint 3
Hint 4
Solution
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')

# Example: create a tensor and move it to GPU
x = torch.randn(3, 3)
x = x.to(device)
print(f'Tensor device: {x.device}')

# Example model moved to GPU
import torch.nn as nn

model = nn.Linear(3, 1).to(device)
print(f'Model device: {next(model.parameters()).device}')
Installed PyTorch with CUDA support using: pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118
Added code to check for GPU availability with torch.cuda.is_available()
Moved tensors and model to GPU device using .to('cuda')
Results Interpretation

Before: PyTorch runs on CPU only, training is slow.

After: PyTorch uses GPU, confirmed by device printouts, enabling faster training.

Installing PyTorch with GPU support and moving data and models to the GPU can greatly speed up machine learning training.
Bonus Experiment
Try running a simple training loop on the GPU and measure the time difference compared to CPU.
💡 Hint
Use time.time() before and after training on CPU and GPU to compare durations.