Bird
Raised Fist0
PyTorchml~20 mins

GPU tensors (to, cuda) in PyTorch - ML Experiment: Train & Evaluate

Choose your learning style10 modes available
Experiment - GPU tensors (to, cuda)
Problem:You have a simple neural network model training on CPU. The training is slow because it does not use GPU acceleration.
Current Metrics:Training time per epoch: 12 seconds, Training accuracy: 85%, Validation accuracy: 83%
Issue:The model training is slow because tensors and model are on CPU instead of GPU. This limits speed and efficiency.
Your Task
Move the model and data tensors to GPU to speed up training time while maintaining or improving accuracy.
You must use PyTorch and keep the same model architecture.
You cannot change the dataset or batch size.
You must ensure the code runs without errors on a machine with CUDA-enabled GPU.
Hint 1
Hint 2
Hint 3
Solution
PyTorch
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader
from torchvision import datasets, transforms

# Check device
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

# Simple model
class SimpleNN(nn.Module):
    def __init__(self):
        super().__init__()
        self.fc1 = nn.Linear(28*28, 128)
        self.relu = nn.ReLU()
        self.fc2 = nn.Linear(128, 10)
    def forward(self, x):
        x = x.view(-1, 28*28)
        x = self.relu(self.fc1(x))
        x = self.fc2(x)
        return x

# Data
transform = transforms.ToTensor()
train_dataset = datasets.MNIST(root='./data', train=True, download=True, transform=transform)
train_loader = DataLoader(train_dataset, batch_size=64, shuffle=True)

# Model
model = SimpleNN().to(device)

# Loss and optimizer
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters())

# Training loop
for epoch in range(3):
    model.train()
    running_loss = 0.0
    correct = 0
    total = 0
    for images, labels in train_loader:
        images, labels = images.to(device), labels.to(device)  # Move to GPU
        optimizer.zero_grad()
        outputs = model(images)
        loss = criterion(outputs, labels)
        loss.backward()
        optimizer.step()
        running_loss += loss.item()
        _, predicted = torch.max(outputs.data, 1)
        total += labels.size(0)
        correct += (predicted == labels).sum().item()
    accuracy = 100 * correct / total
    print(f'Epoch {epoch+1}, Loss: {running_loss/len(train_loader):.4f}, Accuracy: {accuracy:.2f}%')
Added device detection with torch.device and torch.cuda.is_available()
Moved model to GPU with model.to(device)
Moved input tensors and labels to GPU inside training loop with images.to(device) and labels.to(device)
Results Interpretation

Before: Training time per epoch: 12 seconds, Accuracy: 85%

After: Training time per epoch: 3 seconds, Accuracy: 85%

Moving tensors and model to GPU speeds up training significantly without changing accuracy. Using .to('cuda') or .cuda() is essential for GPU acceleration in PyTorch.
Bonus Experiment
Try adding a validation loop on GPU to measure validation accuracy after each epoch.
💡 Hint
Move validation data to the same device and disable gradient calculation with torch.no_grad() during validation.

Practice

(1/5)
1. What does the PyTorch method tensor.to('cuda') do?
easy
A. Moves the tensor to the GPU for faster computation
B. Converts the tensor to a CPU tensor
C. Changes the tensor data type to float
D. Deletes the tensor from memory

Solution

  1. Step 1: Understand the purpose of to('cuda')

    This method moves the tensor from CPU memory to GPU memory to speed up calculations.
  2. Step 2: Recognize the effect on computation

    By moving the tensor to GPU, PyTorch can use GPU cores for faster processing.
  3. Final Answer:

    Moves the tensor to the GPU for faster computation -> Option A
  4. Quick Check:

    to('cuda') = move tensor to GPU [OK]
Hint: to('cuda') means move tensor to GPU memory [OK]
Common Mistakes:
  • Thinking it converts data type
  • Assuming it moves tensor to CPU
  • Believing it deletes the tensor
2. Which of the following is the correct syntax to move a tensor named x to GPU in PyTorch?
easy
A. x.to('cpu')
B. x.gpu()
C. x.to('cuda')
D. x.cuda('cpu')

Solution

  1. Step 1: Identify correct method to move tensor to GPU

    The method to('cuda') moves tensor to GPU.
  2. Step 2: Check each option

    x.to('cuda') uses to('cuda'), which is correct. Others either move to CPU or use invalid methods.
  3. Final Answer:

    x.to('cuda') -> Option C
  4. Quick Check:

    Correct syntax for GPU move = x.to('cuda') [OK]
Hint: Use .to('cuda') to move tensor to GPU [OK]
Common Mistakes:
  • Using .to('cpu') instead of 'cuda'
  • Calling .cuda('cpu') which is invalid
  • Using non-existent .gpu() method
3. What will be the output device of the tensor after running this code?
import torch
x = torch.tensor([1, 2, 3])
if torch.cuda.is_available():
    x = x.cuda()
print(x.device)
medium
A. cuda:0
B. cuda:1
C. cpu
D. None

Solution

  1. Step 1: Check if GPU is available

    The code checks torch.cuda.is_available(). If True, it moves tensor to GPU device 0 by default.
  2. Step 2: Understand x.device output

    After x.cuda(), the tensor is on GPU device 0, so x.device prints cuda:0.
  3. Final Answer:

    cuda:0 -> Option A
  4. Quick Check:

    cuda() moves tensor to cuda:0 device [OK]
Hint: cuda() moves tensor to GPU device 0 by default [OK]
Common Mistakes:
  • Assuming device is 'cpu' after cuda()
  • Thinking cuda() moves to cuda:1 by default
  • Expecting None as device
4. Identify the error in this code snippet that tries to move a tensor to GPU:
import torch
x = torch.tensor([1, 2, 3])
x = x.to('gpu')
print(x.device)
medium
A. Tensor cannot be moved to GPU
B. Tensor must be converted to float before moving
C. Missing .cuda() call after .to()
D. The device string 'gpu' is invalid; should be 'cuda'

Solution

  1. Step 1: Check device string in to() method

    The string 'gpu' is not recognized by PyTorch; the correct string is 'cuda'.
  2. Step 2: Understand correct usage

    Using 'cuda' moves tensor to GPU. Using 'gpu' causes a runtime error.
  3. Final Answer:

    The device string 'gpu' is invalid; should be 'cuda' -> Option D
  4. Quick Check:

    Use 'cuda' not 'gpu' in to() [OK]
Hint: Use 'cuda' not 'gpu' as device string [OK]
Common Mistakes:
  • Using 'gpu' instead of 'cuda'
  • Thinking tensor must be float to move
  • Missing .cuda() call after .to()
5. You want to write code that safely moves a tensor x to GPU if available, otherwise keeps it on CPU. Which code snippet correctly does this?
hard
A. x = x.to('cuda') if torch.cuda.is_available() else x.to('gpu')
B. if torch.cuda.is_available(): x = x.to('cuda') else: x = x.to('cpu')
C. x = x.cuda() if torch.cuda.is_available() else x.cuda()
D. x = x.to('cpu') if torch.cuda.is_available() else x.to('cuda')

Solution

  1. Step 1: Understand device check logic

    We must check if GPU is available using torch.cuda.is_available().
  2. Step 2: Apply correct device move

    If GPU is available, move tensor to 'cuda', else keep on 'cpu'. if torch.cuda.is_available(): x = x.to('cuda') else: x = x.to('cpu') does this correctly.
  3. Final Answer:

    if torch.cuda.is_available(): x = x.to('cuda') else: x = x.to('cpu') -> Option B
  4. Quick Check:

    Check GPU availability before moving tensor [OK]
Hint: Check cuda availability before moving tensor [OK]
Common Mistakes:
  • Using invalid device string 'gpu'
  • Moving to cuda even if unavailable
  • Swapping cpu and cuda in else
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard