# Distributed data parallel training across 8 GPUs



Learn how to implement PyTorch Distributed Data Parallel (DDP) to scale your training across 8 GPUs and launch it efficiently using the Podstack API.



Training · 2026-09-21 · 3 min read



Distributed training is no longer a luxury reserved for massive research labs; it is a necessity for anyone fine-tuning large language models (LLMs) or training computer vision models on massive datasets. When a single GPU becomes a bottleneck for memory or compute, moving to a Multi-GPU setup using Distributed Data Parallel (DDP) is the logical next step.

In this guide, we will walk through the mechanics of scaling a PyTorch training script from a single card to an 8-GPU node. We will focus on the practical implementation using PyTorch’s `DistributedDataParallel` and how to orchestrate this on Podstack’s high-performance infrastructure.

## Why Distributed Data Parallel?

Distributed Data Parallel (DDP) works by replicating your model across multiple GPUs. Each GPU receives a unique shard of the data batch, computes the gradients independently, and then synchronizes those gradients across all cards before the optimizer step.

Compared to the older `DataParallel` (DP), DDP is significantly faster because it uses multi-processing instead of multi-threading, avoiding Python’s Global Interpreter Lock (GIL) and reducing overhead by using collective communication (NCCL).

## Step 1: Initialize the Process Group

To coordinate 8 GPUs, PyTorch needs a backend to manage communication. For NVIDIA GPUs, `nccl` is the industry standard. Your script must initialize the distributed environment by identifying the "Rank" (the ID of the current GPU) and the "World Size" (the total number of GPUs).

```python
import os
import torch
import torch.distributed as dist
from torch.nn.parallel import DistributedDataParallel as DDP

def setup_distributed():
    # These are typically set by the launcher
    rank = int(os.environ["RANK"])
    world_size = int(os.environ["WORLD_SIZE"])
    local_rank = int(os.environ["LOCAL_RANK"])

    # Initialize the process group
    dist.init_process_group(backend="nccl", rank=rank, world_size=world_size)
    
    # Set the device for this process
    torch.cuda.set_device(local_rank)
    return local_rank

def cleanup():
    dist.destroy_process_group()
```

## Step 2: Preparing the Data and Model

When training on 8 GPUs, you cannot simply feed the same data to every card. You must use a `DistributedSampler` to ensure that each GPU sees a distinct subset of the dataset.

```python
from torch.utils.data.distributed import DistributedSampler

def train():
    local_rank = setup_distributed()
    
    # Load your model and move to the specific GPU
    model = MyModel().to(local_rank)
    model = DDP(model, device_ids=[local_rank])

    # Prepare dataset
    dataset = MyDataset()
    sampler = DistributedSampler(dataset, shuffle=True)
    dataloader = torch.utils.data.DataLoader(
        dataset, 
        batch_size=32, 
        sampler=sampler,
        num_workers=4
    )

    optimizer = torch.optim.AdamW(model.parameters(), lr=1e-4)

    for epoch in range(10):
        # Important: set epoch for the sampler to ensure different shuffling every time
        sampler.set_epoch(epoch)
        
        for inputs, targets in dataloader:
            inputs, targets = inputs.to(local_rank), targets.to(local_rank)
            
            optimizer.zero_grad()
            outputs = model(inputs)
            loss = criterion(outputs, targets)
            loss.backward()
            optimizer.step()
    
    cleanup()
```

## Step 3: Launching the Job

While you can manually launch 8 processes, the most efficient way is to use the `torchrun` utility. This tool automatically sets the `RANK`, `WORLD_SIZE`, and `MASTER_ADDR` environment variables for you.

To run this locally on an 8-GPU machine:
```bash
torchrun --nproc_per_node=8 train_script.py
```

## Practical Tips for 8-GPU Training

1.  **Scale your Learning Rate:** When you move from 1 GPU to 8, your effective batch size increases by 8x. You often need to increase your learning rate (a common rule of thumb is the linear scaling rule) or use a warmup period to prevent divergence.
2.  **Monitor GPU Utilization:** Ensure that your data loading isn't the bottleneck. If your GPUs are at 60% utilization, increase the `num_workers` in your `DataLoader`.
3.  **Checkpointing:** When saving your model, ensure you only save from `rank 0`. Saving from all 8 processes simultaneously will cause file corruption and wasted I/O.
    ```python
    if dist.get_rank() == 0:
        torch.save(model.module.state_dict(), "model.pt")
    ```

## Scaling on Podstack

Provisioning 8-GPU nodes (such as H100s or A100s) can be complex, but Podstack simplifies this into a single command. With Podstack, you get per-second billing, meaning you only pay for the high-compute time required for your training run.

First, ensure your environment is authenticated:
```bash
export PODSTACK_API_KEY="your_api_key_here"
```

You can deploy your distributed training job using the Podstack API. By specifying a multi-GPU instance, Podstack handles the underlying drivers and networking required for NCCL to operate at peak performance.

```text
Podstack does not ship a command-line interface. Use the console, the Python package `podstack-sdk`, or the API at https://podstack.ai/api/v1 with a `ps_live_` key.
```

Podstack’s serverless inference and GPU functions allow you to immediately transition from training to deployment. Once your 8-GPU training job completes and saves the weights to a persistent volume, you can spin up a serverless endpoint to serve the model without managing the underlying hardware.

## Conclusion

Distributing your training across 8 GPUs reduces iteration time from days to hours. By using PyTorch DDP and offloading the infrastructure management to Podstack, you can focus on optimizing your model architecture rather than troubleshooting NVLink configurations or driver versions. Ready to scale? Spin up an 8-GPU instance on Podstack and start training in seconds.
