7.1 Data Parallelism (DP/DDP)
Two GPUs each see half of a training batch. Where should the two gradients meet, and which copy of the model should the optimizer update? PyTorch offers two ways to organize this step. Both keep a full copy of the model on each device and split the data across devices.
1. The Naive Approach: DataParallel (DP)
PyTorch’s DataParallel uses one process. On each forward pass it scatters the batch across devices, replicates the module, runs each replica on its slice, then gathers the outputs on the configured output device. During backward, autograd sums the replica gradients into the original module on the first device. The optimizer updates that module. Its updated parameters are the source for the replicas on the next forward pass. [3]
Take one scalar weight and two target values and , one per device. Let the prediction be and each example’s loss be . Its gradient is , giving and . Our training objective is the mean of the two example losses, so its gradient must be . Follow where the factor of two enters each implementation. [3] [4]
- Loss — Gather the predictions and take one mean over the two example losses on the output device.
- Backward — The mean gives each example half the weight. The original parameter receives contributions of +0.5 and −1.5.
- Update — The original gradient is −1. One optimizer changes the original weight from 1 to 1.5.
- Loss — Each rank holds one example, so its local mean loss is just that example’s loss.
- Backward — Rank 0 computes +1 and rank 1 computes −3. The default reducer averages the two local gradients.
- Update — Both ranks receive −1. Each optimizer changes its own weight from 1 to 1.5.
The calculation uses plain SGD at a learning rate of 0.5 with zero momentum and weight decay. We checked the gathered loss with CPU autograd and the distributed update with two Gloo ranks in PyTorch 2.15. Download the Python check
Here each rank contributes one target. What changes when padding leaves one rank with fewer targets?
Why DDP is preferred
PyTorch recommends DDP for multi-GPU training, including on one machine. Rebuilding replicas each forward adds work in DP. Gathering large outputs can also raise memory use on the output device. DDP keeps replicas between steps and can overlap gradient communication with backward computation. To compare the two on a workload, record peak memory per device, step time and time spent waiting for gradient synchronization. [3] [4]
2. The Standard: Distributed Data Parallel (DDP)
In the usual one-process-per-GPU configuration, each process has a rank, one model replica, and its own optimizer. The training code assigns inputs to ranks, for example with a DistributedSampler. DDP synchronizes initial module state by default and then synchronizes gradients in backward. Each optimizer applies the same update locally. Buffers such as BatchNorm statistics can also be broadcast depending on configuration. [2] [4]
Two ranks, four valid tokens. Which gradient reaches the optimizer?
Give each rank three positions. Keep one target on rank 0 and all three on rank 1. At , the four valid targets contribute gradients . Averaging within each rank first gives . Giving each target one vote gives . A learning rate of 0.5 turns that choice into two different weights after a single SGD step.
These are CPU measurements with PyTorch 2.15, two Gloo processes and a Boolean loss mask. Every row starts at . The last column computes the mean over the same valid positions together on one CPU. Each entry gives (gradient, updated weight).
| Valid targets on ranks 0, 1 | DDP with rank means | DDP with global token mean | Unsharded reference |
|---|---|---|---|
| 1, 1 | (−1, 1.5) | (−1, 1.5) | (−1, 1.5) |
| 1, 3 | (−1, 1.5) | (−2, 2) | (−2, 2) |
| 0, 3 | (−1.5, 1.75) | (−3, 2.5) | (−3, 2.5) |
| 0, 0 | (no gradient, 1) | (no gradient, 1) | (no gradient, 1) |
The mean of an empty rank is undefined. In the third row, the rank-mean baseline gives the empty rank a zero contribution. DDP then averages zero with −3 and halves the update. For the global token mean, sum the valid counts across ranks first. On each rank, backpropagate its sum of valid losses times world_size / total_valid. Default DDP’s gradient averaging then yields the four-token mean in row two and the three-token mean in row three. [4]
An empty rank still runs forward and backward if its peer has data. In the script, losses[valid].sum() remains connected to the model even when the mask selects nothing. When both masks are empty, the shared count is zero and both ranks skip the forward pass and optimizer step. Download the two-rank check and run python verify-dp-ddp-gradients.py to reproduce all four rows.
Did every validation example get one vote?
Five examples have permanent IDs 0 through 4. Only the prediction for ID 0 is wrong. With shuffling off, PyTorch’s default DistributedSampler assigns [0, 2, 4] to rank 0 and [1, 3, 0] to rank 1. Both ranks process three examples. Summing correct predictions and visits across them gives 4/6, although the five distinct examples scored 4/5. The extra visit pads the shorter shard. [5]
The sampler’s drop_last=True drops ID 4 in this example. Leaving the sampler alone and setting drop_last=True on a loader with local batch size two also omits ID 4, this time when each rank drops its last partial batch. Either way, four observed IDs are too few to score this five-example set. Run the CPU sampler audit and inspect every delivered batch.
The Mathematics of Ring All-Reduce
An all-reduce specifies the result that each rank receives. The backend chooses how to move the data. Ring, tree and hierarchical implementations are possible. [2]
Consider ranks with bytes of gradients per rank. In a centralized reduction, a designated rank receives bytes from peers. In the ring algorithm, each rank sends and receives only part of the gradient at each step. [1]
In Ring All-Reduce, the GPUs are logically arranged in a circle. The algorithm operates in two phases:
- Reduce-Scatter: The gradient tensor is chunked into blocks. Each GPU sends one block to its right neighbor and receives a different block from its left neighbor, continuously accumulating the values. After steps, every GPU holds the fully aggregated sum for exactly one of the blocks.
- All-Gather: The fully aggregated blocks are circulated around the ring again. After another steps, every GPU has the complete, aggregated gradient tensor.
Each rank sends the following number of bytes and receives the same amount.
Bytes approach as grows, but latency is not independent of rank count. With startup cost per phase step and effective bandwidth ,
Topology, congestion and stragglers add costs; large-scale efficiency still requires measurement.
3. Engineering the Overlap: Gradient Bucketing
Waiting until the final parameter gradient is ready leaves all communication on the critical path. DDP groups parameter gradients into buckets. Once a bucket is ready and its turn arrives in the reduction order, its collective can overlap computation of later gradients. Small buckets can start earlier but require more collective launches. Large buckets amortize launch overhead but take longer to fill. [2] [4]
Interactive: Compute and Communication Overlap
Move the clock from 3 to 4. Layer 3 finishes its gradient, so the first bucket can start communicating while layer 2 computes. At time 8, all four gradients are ready. How much communication is left before the optimizer can use them? On a real workload, measure that exposed time when tuning bucket_cap_mb.
All ranks follow the same backward schedule in this example. Both rows use the same clock, in illustrative time units.
B1 = L4 + L3 · B2 = L2 + L1
At time 4, L3 finishes and the all-reduce for B1 starts alongside the gradient calculation for L2. B2 needs L1, the last gradient, at time 8. Its reduction ends at 10, leaving 2 units of communication after compute.
4. PyTorch Implementation
CPU teaching example. The inputs are 1,024 generated sequences of 32 integer IDs. The target at each position is the input ID plus one, modulo 256. The model has an embedding and two linear layers. Every position counts towards cross-entropy. The example omits checkpointing, variable-length masks and recovery from a failed rank. The optional CUDA/NCCL path has not been run here.
Save the linked file and run torchrun --standalone --nproc-per-node=2 ddp_token_training.py with PyTorch 2.15. Each CPU rank receives eight sequences per full batch. In this run 1,024 divides evenly across the two ranks, so the epoch total is token visits. The script sums both loss and token visits across ranks before the global rank 0 prints their ratio. A different dataset size can add visits through sampler padding.
Download the training example (ddp_token_training.py)
"""A synthetic token classifier for the DDP exercise in section 7.1.
CPU: torchrun --standalone --nproc-per-node=2 ddp_token_training.py
GPU: add --cuda and start one process per available GPU.
Requires PyTorch. Generates its own data; no downloads.
"""
import argparse
import os
import torch
import torch.distributed as dist
from torch import nn
from torch.nn.parallel import DistributedDataParallel
from torch.utils.data import DataLoader, DistributedSampler, TensorDataset
def train(device):
torch.manual_seed(7)
model = nn.Sequential(nn.Embedding(256, 64), nn.Linear(64, 128),
nn.GELU(), nn.Linear(128, 256)).to(device)
replicas = DistributedDataParallel(
model, device_ids=[device.index] if device.type == "cuda" else None,
gradient_as_bucket_view=True,
)
generator = torch.Generator().manual_seed(42)
inputs = torch.randint(256, (1024, 32), generator=generator)
data = TensorDataset(inputs, (inputs + 1) % 256)
sampler = DistributedSampler(data, shuffle=True)
loader = DataLoader(data, sampler=sampler, batch_size=8)
optimizer = torch.optim.AdamW(replicas.parameters(), lr=1e-4)
criterion = nn.CrossEntropyLoss(reduction="sum")
for epoch in range(3):
sampler.set_epoch(epoch)
totals = torch.zeros(2, device=device, dtype=torch.float64)
for tokens, targets in loader:
tokens, targets = tokens.to(device), targets.to(device)
optimizer.zero_grad(set_to_none=True)
logits = replicas(tokens)
loss_sum = criterion(logits.flatten(0, 1), targets.flatten())
# The sampler gives every rank equally many fixed-length rows here.
(loss_sum / targets.numel()).backward()
optimizer.step()
totals[0] += loss_sum.detach().double()
totals[1] += targets.numel()
# Losses stay local in DDP. Aggregate token loss and visits separately.
dist.all_reduce(totals)
if dist.get_rank() == 0:
loss, visits = totals.tolist()
print(f"epoch={epoch} token_visits={int(visits)} loss_per_token={loss/visits:.6f}",
flush=True)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--cuda", action="store_true")
use_cuda = parser.parse_args().cuda
device = torch.device("cpu")
if use_cuda:
device = torch.device("cuda", int(os.environ["LOCAL_RANK"]))
torch.cuda.set_device(device)
dist.init_process_group(backend="nccl" if use_cuda else "gloo")
try:
train(device)
finally:
dist.destroy_process_group()
The two Gloo ranks reported mean losses of 5.447021, 5.201997 and 4.933845 over the three epochs in PyTorch 2.15.0+cpu. A one-rank control with batch size 16 visited the same examples in each global step and matched to the six decimal places shown. These are training losses on the generated labels.
In ordinary DDP, the required gradient synchronization completes with backward, so each local optimizer updates from the synchronized gradients. optimizer.step() is not itself a distributed barrier. A slow rank can delay peers at collectives; accumulation with no_sync() requires synchronization on the final backward.
Summary
DDP retains model replicas and overlaps data-parallel computation with gradient communication. Benefits depend on the compute-to-communication ratio and stragglers. Bucketing can reduce exposed communication; it guarantees neither linear scaling nor complete latency hiding.
In ordinary, unsharded DDP, each GPU holds model weights, gradients and its local optimizer state. Adding GPUs leaves this per-replica requirement in place.
One illustrative mixed-precision Adam budget uses 2 bytes for BF16 weights, 2 for BF16 gradients, 4 for FP32 master weights and 8 for two FP32 moments: 16 bytes per parameter. Implementations with FP32 gradients differ. Add sequence- and batch-dependent activations, temporary buffers, collectives, checkpoint and evaluation overhead; there is no universal parameter cutoff for an 80GB device.
Section 7.2 follows the optimizer state, gradients and parameters as ZeRO partitions them across ranks.
Before adapting this skeleton to training
Pin the input manifest, tokenizer and model/config hashes; compare averaged gradients against a single-device reference on the same data. Batch 8, AdamW learning rate and three epochs above are synthetic demonstration settings. A real run must specify effective global token batch, precision, accumulation and loss masks.
Record token-normalized train/validation loss and domain slices, nonfinite/overflow counts, gradient/activation norms, throughput/MFU, data wait, collective time and stragglers, and reconstructable batch IDs. Abort coherently across ranks on nonfinite loss or collective failure and restore the last validated checkpoint. Save model, optimizer, scheduler and precision state, step/tokens, RNG, sampler, exact data cursor and hashes. Release only after continuation-equivalence checks, isolated offline quality/safety/performance evaluation and rehearsal of switching back to the last known-good bundle.
Quizzes
Quiz 1: The two example gradients are +1 and −3. Why do DP and default DDP both produce −1?
In DP, the global mean loss scales the contributions to +0.5 and −1.5 before they are summed. In default DDP, each rank has one example, and the reducer averages +1 and −3.
Quiz 2: How do ring bytes and latency differ at 10 and 1,000 ranks?
Transmitted bytes rise from to , about 11%. Startup cost rises from to , so similar byte counts do not imply similar latency.
Quiz 3: What is the primary purpose of “Gradient Bucketing” in DDP?
A ready bucket can begin synchronizing while backward computes later gradients. Any communication still running after compute finishes adds to step time.
Quiz 4: If you have a 100-billion parameter model and a cluster of 1,024 GPUs (each with 80GB VRAM), can you train it using standard DDP? Why or why not?
No, you cannot. Standard DDP requires a full replica of the model weights, gradients, and optimizer states to reside in the VRAM of every single GPU. A 100B parameter model in mixed precision requires roughly 1.6 Terabytes of VRAM for the weights, gradients and Adam state under the 16-byte budget above, which vastly exceeds the 80GB limit of a single GPU. This necessitates advanced techniques like ZeRO or Tensor Parallelism.
Quiz 5: Two ranks report four correct predictions in six visits. What would you need to recover accuracy on five examples?
Match each visit to a stable example ID and check all five expected IDs are present. Repeated visits must agree on label and prediction in this fixed-output experiment. Counting each ID once gives 4/5. If an ID is missing, its prediction is still needed.
References
- Gibiansky, A. (2017). “Bringing HPC Techniques to Deep Learning.” Baidu Research. Link.
- Li, S., et al. (2020). PyTorch Distributed: Experiences on Accelerating Data Parallel Training. VLDB. arXiv:2006.15704.
- PyTorch. DataParallel, PyTorch 2.15.
- PyTorch. DistributedDataParallel, PyTorch 2.15.
- PyTorch. DistributedSampler and its padding and dropping rules, PyTorch 2.15.