Bird
Raised Fist0
PyTorchml~5 mins

Multi-GPU training in PyTorch

Choose your learning style10 modes available
Introduction

Using multiple GPUs helps train machine learning models faster by sharing the work. It lets you handle bigger data and models efficiently.

When training a large neural network that takes too long on one GPU.
When you want to speed up training by splitting data across GPUs.
When your model or batch size is too big for a single GPU's memory.
When experimenting with bigger datasets that require more computing power.
Syntax
PyTorch
model = YourModel()
model = torch.nn.DataParallel(model)
model = model.to(device)

for data, target in dataloader:
    data, target = data.to(device), target.to(device)
    optimizer.zero_grad()
    output = model(data)
    loss = loss_fn(output, target)
    loss.backward()
    optimizer.step()

torch.nn.DataParallel wraps your model to run on multiple GPUs automatically.

Make sure your input data and model are moved to the correct device (usually 'cuda').

Examples
This wraps the model to use all available GPUs and moves it to GPU memory.
PyTorch
model = MyModel()
model = torch.nn.DataParallel(model)
model = model.cuda()
Move each batch of data to GPU before feeding it to the model.
PyTorch
for inputs, labels in dataloader:
    inputs, labels = inputs.cuda(), labels.cuda()
    outputs = model(inputs)
Sample Model

This code trains a simple model on dummy data using multiple GPUs if available. It prints the average loss per epoch.

PyTorch
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader, TensorDataset

# Simple model
class SimpleNet(nn.Module):
    def __init__(self):
        super().__init__()
        self.fc = nn.Linear(10, 2)
    def forward(self, x):
        return self.fc(x)

# Create dummy data
x = torch.randn(100, 10)
y = torch.randint(0, 2, (100,))

# Dataset and loader
dataset = TensorDataset(x, y)
dataloader = DataLoader(dataset, batch_size=20)

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

# Model
model = SimpleNet()
if torch.cuda.device_count() > 1:
    model = nn.DataParallel(model)
model = model.to(device)

# Loss and optimizer
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(), lr=0.1)

# Training loop
model.train()
for epoch in range(2):
    total_loss = 0
    for inputs, labels in dataloader:
        inputs, labels = inputs.to(device), labels.to(device)
        optimizer.zero_grad()
        outputs = model(inputs)
        loss = criterion(outputs, labels)
        loss.backward()
        optimizer.step()
        total_loss += loss.item()
    print(f'Epoch {epoch+1}, Loss: {total_loss/len(dataloader):.4f}')
OutputSuccess
Important Notes

DataParallel splits input batches automatically across GPUs and gathers results.

For better performance on multiple GPUs, consider using torch.nn.parallel.DistributedDataParallel in real projects.

Always check if GPUs are available with torch.cuda.is_available() before using them.

Summary

Multi-GPU training speeds up model training by sharing work across GPUs.

Use torch.nn.DataParallel to easily enable multi-GPU support.

Move both model and data to GPUs to ensure proper training.

Practice

(1/5)
1. What is the main purpose of using torch.nn.DataParallel in PyTorch?
easy
A. To reduce the model size by pruning layers
B. To convert the model to a CPU-only version
C. To split the model and data across multiple GPUs for faster training
D. To visualize the model architecture

Solution

  1. Step 1: Understand the role of DataParallel

    torch.nn.DataParallel is designed to distribute the model and input data across multiple GPUs to speed up training.
  2. Step 2: Compare options

    Reducing the model size by pruning layers, converting the model to a CPU-only version, and visualizing the model architecture do not relate to multi-GPU training. Only splitting the model and data across multiple GPUs for faster training correctly describes the purpose.
  3. Final Answer:

    To split the model and data across multiple GPUs for faster training -> Option C
  4. Quick Check:

    Multi-GPU training = DataParallel usage [OK]
Hint: DataParallel splits model and data across GPUs for speed [OK]
Common Mistakes:
  • Thinking DataParallel reduces model size
  • Confusing DataParallel with CPU conversion
  • Assuming DataParallel is for visualization
2. Which of the following is the correct way to wrap a PyTorch model for multi-GPU training?
easy
A. model = torch.nn.DataParallel(model)
B. model = torch.nn.Sequential(model)
C. model = torch.nn.ModuleList(model)
D. model = torch.nn.Parameter(model)

Solution

  1. Step 1: Identify the correct wrapper for multi-GPU

    To enable multi-GPU training, PyTorch provides torch.nn.DataParallel which wraps the model.
  2. Step 2: Check other options

    Sequential chains layers, ModuleList stores layers, and Parameter is for tensors, none enable multi-GPU.
  3. Final Answer:

    model = torch.nn.DataParallel(model) -> Option A
  4. Quick Check:

    Wrap model with DataParallel for multi-GPU [OK]
Hint: Use DataParallel(model) to enable multi-GPU training [OK]
Common Mistakes:
  • Using Sequential or ModuleList instead of DataParallel
  • Trying to wrap model with Parameter
  • Forgetting to wrap the model at all
3. Consider this code snippet for multi-GPU training:
import torch
model = MyModel()
model = torch.nn.DataParallel(model)
model.cuda()
inputs = inputs.cuda()
outputs = model(inputs)
print(outputs.device)
What will be printed if multiple GPUs are available?
medium
A. cuda:0
B. cpu
C. cuda:1
D. cuda:all

Solution

  1. Step 1: Understand DataParallel device behavior

    When using DataParallel, the model replicates on all GPUs but the output is gathered on the default device, usually cuda:0.
  2. Step 2: Analyze the print statement

    The outputs.device will show the device of the gathered output tensor, which is cuda:0, not all GPUs or CPU.
  3. Final Answer:

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

    DataParallel output device = cuda:0 [OK]
Hint: DataParallel gathers output on cuda:0 device [OK]
Common Mistakes:
  • Expecting output on all GPUs simultaneously
  • Thinking output is on CPU
  • Assuming output device is cuda:1 or others
4. You wrote this code for multi-GPU training but get an error:
model = MyModel()
model = torch.nn.DataParallel(model)
inputs = inputs.cuda()
outputs = model(inputs)
The error says: 'Expected all tensors to be on the same device'. What is the likely cause?
medium
A. Model should be wrapped with Sequential instead
B. Model is not moved to GPU before wrapping with DataParallel
C. DataParallel requires inputs on CPU
D. Inputs are not on CPU

Solution

  1. Step 1: Check model and input device placement

    The model must be moved to GPU (e.g., model.cuda()) before wrapping with DataParallel to ensure all parts are on the same device.
  2. Step 2: Analyze error cause

    If the model is on CPU but inputs are on GPU, the error about device mismatch occurs.
  3. Final Answer:

    Model is not moved to GPU before wrapping with DataParallel -> Option B
  4. Quick Check:

    Model and inputs must be on same device [OK]
Hint: Move model to GPU before DataParallel wrap [OK]
Common Mistakes:
  • Wrapping model before moving to GPU
  • Assuming inputs must be on CPU
  • Using wrong wrapper like Sequential
5. You want to train a model on 4 GPUs using PyTorch. Which of these steps is NOT necessary for correct multi-GPU training?
hard
A. Move input data to GPU before passing to the model
B. Move the model to GPU before wrapping
C. Wrap the model with torch.nn.DataParallel
D. Manually split input batches and send each to a different GPU

Solution

  1. Step 1: Review multi-GPU training steps

    Using DataParallel automatically splits input batches and sends them to multiple GPUs, so manual splitting is not needed.
  2. Step 2: Confirm necessary steps

    Wrapping the model, moving it to GPU, and moving inputs to GPU are all required for proper multi-GPU training.
  3. Final Answer:

    Manually split input batches and send each to a different GPU -> Option D
  4. Quick Check:

    DataParallel handles input splitting automatically [OK]
Hint: DataParallel auto-splits inputs; manual split not needed [OK]
Common Mistakes:
  • Trying to manually split inputs across GPUs
  • Forgetting to move model to GPU
  • Not wrapping model with DataParallel
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