Learn PyTorch Β· 11/12

Distributed Training and Scaling

9 min read

Hello, aspiring PyTorch developer! πŸ‘‹ Welcome to this guide on Distributed Training and Scaling.

Ever felt like your single GPU is chugging along like an old steam train trying to conquer a mountain? πŸš‚πŸ’¨ You've built a massive model, you have a dataset the size of a small country, and your training loop is taking... well, let's just say you could watch all the seasons of your favorite show before it finishes one epoch.

That's the problem we're here to solve! When your models and data get too big for one GPU to handle efficiently, you need to call in reinforcements. This guide will walk you through how to scale up your PyTorch training from a solo act to a multi-GPU symphony. 🎢

The Core Problem: One GPU is Not Enough!

Training deep learning models is computationally expensive. You're limited by:

  1. GPU Memory: Large models, high-resolution inputs, and big batch sizes can quickly max out your VRAM.
  2. Training Time: Even if everything fits in memory, processing massive datasets takes a very, very long time.

The solution? Use more GPUs! But how do you make them work together? Let's find out.


1. Data Parallelism vs. Distributed Data Parallel (DDP) πŸ‘―β€β™€οΈ

The first idea you might have is to split your data and let multiple GPUs work on different chunks simultaneously. This is called Data Parallelism. PyTorch gives us two main ways to do this.

The Old Way: nn.DataParallel

Imagine you're the manager of a team of artists painting a huge mural. With DataParallel, you (the main GPU) hold the master sketch (the model).

  1. You take a big batch of paint buckets (a data batch).
  2. You hand out a few buckets to each artist (scatter the data to each GPU).
  3. You shout "Here's the master sketch!" to everyone (copy the model to each GPU).
  4. Each artist paints their section.
  5. They all come back to you with their finished sections.
  6. You single-handedly combine their work to update the master sketch (gather the results on the main GPU).

The Problem 😟:
Notice how you, the manager (GPU 0), are doing a lot of work? You're scattering data, gathering results, and calculating the final update. This creates a bottleneck, and the other artist GPUs spend time waiting for you. This often leads to one GPU being overworked while the others are underutilized. It's also held back by Python's Global Interpreter Lock (GIL) because it runs in a single process.

In short, DataParallel is easy to implement but often inefficient. For this reason, the industry has largely moved on.

The Modern & Recommended Way: nn.DistributedDataParallel (DDP) πŸš€

Now, imagine a more collaborative team of artists. With DistributedDataParallel, there is no single "manager".

  1. At the start, every artist gets a perfect copy of the master sketch (the model is replicated on each GPU process).
  2. They all agree to work on different, pre-assigned sections of the mural (the DistributedSampler gives each process a unique chunk of data).
  3. Each artist paints their section and calculates what changes they think should be made to the master sketch (forward and backward pass).
  4. Here’s the magic ✨: Instead of reporting back to a manager, they all talk to each other directly and very efficiently, averaging their proposed changes (gradients are all-reduced across all processes).
  5. With the averaged changes agreed upon, each artist updates their own copy of the master sketch in the exact same way.

The Solution 😊:
This is a true parallel system. Each GPU runs in its own process, has its own optimizer, and performs its own weight updates. The communication of gradients is highly optimized. This avoids the bottleneck of DataParallel and leads to much faster training.

Industry Standard: DistributedDataParallel is the recommended method for data parallelism in PyTorch. It is more performant and scalable. While DataParallel might be tempting for its simplicity, learning DDP is a crucial skill for any serious deep learning practitioner.


2. Setting up and Initializing DistributedDataParallel (DDP) πŸ› οΈ

Alright, let's get our hands dirty. Setting up DDP involves a few key steps. It might look like a bit of boilerplate code at first, but it's a pattern you'll reuse every time.

The Goal: We need to launch a separate process for each GPU, ensure they can communicate with each other, and give each process a unique slice of the data.

Step-by-Step DDP Initialization

Here is the essential boilerplate to get a DDP training script running.

Step 1: Initialize the Process Group
This is like giving each artist a walkie-talkie and assigning them a call sign so they know who they are and how to talk to the others. We need to tell each process what its unique ID (rank) is and how many total processes there are (world_size).

Step 2: Create a DistributedSampler
The sampler's job is to make sure each process gets a different, non-overlapping subset of the training data for each epoch. This is crucial to ensure the model learns from the entire dataset.

Step 3: Wrap the Model with DDP
You take your regular PyTorch model and wrap it in torch.nn.parallel.DistributedDataParallel. This wrapper hooks into the model's backward pass to handle the gradient synchronization magic automatically.

Step 4: The Training Loop
The training loop looks almost identical to a standard loop, with the key difference being the DataLoader now uses the DistributedSampler.

Example Code Snippet

Let's see what this looks like in practice. This is a simplified example of what a DDP training script's setup looks like.

python
import torch
import torch.nn as nn
from torch.utils.data import DataLoader, Dataset
from torch.utils.data.distributed import DistributedSampler
import torch.distributed as dist
import os

def setup(rank, world_size):
    """Initializes the distributed environment."""
    os.environ['MASTER_ADDR'] = 'localhost'
    os.environ['MASTER_PORT'] = '12355'
    # Initialize the process group
    dist.init_process_group("nccl", rank=rank, world_size=world_size)

def cleanup():
    """Cleans up the distributed environment."""
    dist.destroy_process_group()

# --- Your regular PyTorch components ---
class MyModel(nn.Module):
    def __init__(self):
        super(MyModel, self).__init__()
        self.linear = nn.Linear(10, 5)

    def forward(self, x):
        return self.linear(x)

class MyDataset(Dataset):
    def __len__(self):
        return 1000
    def __getitem__(self, idx):
        return torch.randn(10), torch.randn(5)
# ------------------------------------

def train(rank, world_size):
    print(f"Running DDP example on rank {rank}.")
    setup(rank, world_size)

    # 1. Create model and move it to the correct device (GPU)
    #    The device_ids argument is crucial!
    model = MyModel().to(rank)
    ddp_model = nn.parallel.DistributedDataParallel(model, device_ids=[rank])

    # 2. Create your dataset and DistributedSampler
    dataset = MyDataset()
    sampler = DistributedSampler(dataset, num_replicas=world_size, rank=rank)
    
    # The dataloader uses the sampler
    # Note: drop_last=True is often recommended to avoid issues with uneven batch sizes.
    dataloader = DataLoader(dataset, batch_size=32, sampler=sampler)
    
    optimizer = torch.optim.SGD(ddp_model.parameters(), lr=0.001)
    loss_fn = nn.MSELoss()

    # --- Your training loop ---
    for epoch in range(2):
        # Set epoch for the sampler. This is important for shuffling!
        sampler.set_epoch(epoch) 
        for data, labels in dataloader:
            data = data.to(rank)
            labels = labels.to(rank)

            optimizer.zero_grad()
            outputs = ddp_model(data)
            loss = loss_fn(outputs, labels)
            loss.backward() # DDP handles gradient sync here
            optimizer.step()
        
        print(f"Rank {rank}, Epoch {epoch}, Loss: {loss.item()}")

    cleanup()

# To run this code, you would typically use `torchrun` from your terminal:
# torchrun --nproc_per_node=NUM_GPUS your_script.py
# For example, if you have 2 GPUs:
# torchrun --nproc_per_node=2 ddp_example.py

What is torchrun? It's a utility provided by PyTorch that helps launch your script on multiple processes. It automatically handles setting the rank and world_size environment variables for you, making the launch process much cleaner.


3. Implementing Gradient Accumulation for Large Batch Sizes μŒ“κΈ°

The Problem: You're reading a cutting-edge research paper, and they used a massive batch size of 1024 for the best results. You try to set batch_size=1024 in your DataLoader, and... CUDA out of memory. πŸ’₯ Your GPU just can't handle that many samples at once.

Does this mean you can't replicate the results? Not at all!

The Solution: Gradient Accumulation
The core idea is simple: we can simulate a large batch by processing several smaller "micro-batches" and accumulating their gradients before we update the model's weights.

Imagine you're supposed to lift a 100kg weight (the large batch). You can't do it all at once. But you can lift a 25kg weight (a micro-batch) four times in a row, and the total effort is the same.

  1. Forward/Backward Pass: You perform the forward and backward passes for a small micro-batch. This calculates the gradients for that batch.
  2. Don't Step!: Crucially, you do not call optimizer.step() yet. The calculated gradients are automatically added to the previously existing gradients (or initialized if it's the first micro-batch).
  3. Repeat: You repeat this for a set number of accumulation steps.
  4. Step and Zero: Once you've processed enough micro-batches to equal your desired large batch size, you finally call optimizer.step() to update the weights using the accumulated gradients. Then, you call optimizer.zero_grad() to clear the slate for the next large batch.

Example Code Snippet

Let's modify a standard training loop to include gradient accumulation.

python
# --- Assume model, dataloader, optimizer, loss_fn are defined ---

# Desired "virtual" batch size
large_batch_size = 1024 
# Actual batch size your GPU can handle
micro_batch_size = 64

# Calculate accumulation steps
accumulation_steps = large_batch_size // micro_batch_size

# --- The Training Loop with Gradient Accumulation ---
model.train()
optimizer.zero_grad() # Clear gradients at the start

for i, (data, labels) in enumerate(dataloader):
    data = data.to(device)
    labels = labels.to(device)

    # Forward pass
    outputs = model(data)
    loss = loss_fn(outputs, labels)

    # We need to scale the loss here because gradients are averaged by default.
    # By dividing by accumulation_steps, we ensure the final accumulated
    # gradient is the average over the entire large batch, not the sum.
    loss = loss / accumulation_steps
    
    # Backward pass to accumulate gradients
    loss.backward()

    # If we have processed enough micro-batches, update the weights
    if (i + 1) % accumulation_steps == 0:
        optimizer.step()    # Perform the weight update
        optimizer.zero_grad() # Clear gradients for the next large batch

Funny Fact: Forgetting to scale the loss is one of the most common "gotchas" with gradient accumulation. If you don't do it, you're effectively multiplying your learning rate by accumulation_steps, which can cause your training to become very unstable! 🎒

And that's it! You now have the foundational knowledge to scale your PyTorch training. You've learned why DDP is the industry choice, how to set it up, and how to use gradient accumulation to train with massive batch sizes, even on a memory-constrained GPU. Happy training!

Further Reading & References

Challenge

Challenge Instructions

You are tasked with scaling up a deep learning training script. The current script runs on a single GPU but is hitting memory limitations and taking too long to train. Your goal is to modify the script to leverage multi-GPU training using DistributedDataParallel (DDP) and to handle very large batch sizes using Gradient Accumulation.

Requirements:

  1. Integrate DistributedDataParallel (DDP):

    • Assume the script will be launched via torchrun, which automatically sets the RANK and WORLD_SIZE environment variables.
    • Initialize the distributed process group using the nccl backend.
    • Create a torch.utils.data.distributed.DistributedSampler for the train_dataset.
    • Update the DataLoader to use this new sampler and disable its own shuffling (shuffle=False), as the sampler handles it.
    • Wrap the model instance with torch.nn.parallel.DistributedDataParallel, assigning it to the correct device based on its rank.
    • In the training loop, ensure you call train_sampler.set_epoch(epoch) before iterating through the data. This is crucial for proper shuffling across epochs.
  2. Implement Gradient Accumulation:

    • The physical BATCH_SIZE is 16, but you need to simulate a much larger virtual batch size of 64.
    • Calculate the required accumulation_steps.
    • Inside the data loop, perform the forward pass and scale the loss appropriately before the backward pass.
    • Accumulate gradients for the calculated number of steps.
    • Only call optimizer.step() and optimizer.zero_grad() once enough gradients have been accumulated to match the virtual batch size.

Expected result

Your final code should be a complete Python script that correctly integrates DDP and gradient accumulation into the provided template.

The key components of the correct solution are:

  • DDP Setup:

    • dist.init_process_group('nccl') is called to initialize the distributed environment.
    • rank and world_size are correctly obtained from environment variables (e.g., int(os.environ['RANK'])).
    • The model is moved to the correct device using device = f'cuda:{rank}'.
    • A DistributedSampler is created and passed to the DataLoader.
    • The shuffle argument in the DataLoader is set to False.
    • The model is correctly wrapped: model = DDP(model, device_ids=[rank]).
  • Training Loop:

    • train_sampler.set_epoch(epoch) is called at the beginning of each epoch loop.
    • accumulation_steps is calculated as VIRTUAL_BATCH_SIZE // BATCH_SIZE.
    • The loss is scaled down before the backward pass: loss = loss / accumulation_steps.
    • loss.backward() is called on every iteration.
    • optimizer.step() and optimizer.zero_grad() are called conditionally, inside an if block that executes every accumulation_steps iterations (e.g., if (i + 1) % accumulation_steps == 0:).
  • Cleanup:

    • dist.destroy_process_group() is called after the training loop to clean up resources.
python

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.