Lab: From One GPU to Several with DistributedDataParallel
Turn a single-process training script into a DistributedDataParallel job launched with torchrun, run it on two CPU processes with the gloo backend, show that it reproduces the single-process run exactly, reproduce the classic sampler mistakes, log and checkpoint from rank 0, and work out from memory arithmetic and a small FSDP2 run when sharding is needed instead.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: A single-process reference
- Step 2: The same training with DDP
- Step 3: Two sampler mistakes
- Step 4: Use the rank-0 checkpoint
- Step 5: When DDP is not enough
- Check your understanding
- Apply it
- Review prompt
Lessons of Efficient PyTorch Training
- Lab: Feeding the GPU with Custom Datasets and DataLoaders Lab · 25 min
- Fitting More in Memory: Mixed Precision and Gradient Accumulation Concept · 20 min
- Worked Example: Checkpoint, Crash, Resume Worked example · 20 min
- Lab: Profile a Slow Training Loop and Fix It Lab · 30 min
- Lab: From One GPU to Several with DistributedDataParallel Lab · 25 min
- Check: Speed, Memory and Repeatability Knowledge check · 10 questions
What you will learn
- Scale a training script to several GPUs with DistributedDataParallel launched by torchrun (distributed sampler, rank-zero logging and checkpointing), and explain when a sharded strategy such as FSDP is needed instead.
Prerequisites: Deep Learning Fundamentals
01. Goal and setup
Data parallelism trains one model on several devices by giving each device a different slice of every batch. With PyTorch DistributedDataParallel (DDP) you start one process per GPU. Each process holds a full copy of the model, runs the forward and backward pass on its own slice, and then the processes average their gradients, so every copy takes the same optimizer step and the copies stay identical. The averaging is an all-reduce, a collective operation in which every process contributes a tensor and every process receives the result.
Each process has a rank, its number from 0 to the world size minus 1. torchrun starts the processes and tells each one its rank through environment variables. The communication library is the backend: NCCL on NVIDIA GPUs, gloo on CPUs. Because gloo runs anywhere, this lab runs a real two-process DDP job on a laptop CPU, and the same script switches to NCCL and one GPU per process when GPUs are present.
You need: Python 3.12 and PyTorch 2 (the CPU build includes gloo and torchrun). It helps to have done the checkpointing worked example. torchrun prints a warning that it sets OMP_NUM_THREADS=1 for each process; that is expected.
ddp-lab/
├── common.py data, model and a weight checksum shared by all scripts
├── train_single.py step 1: the single-process reference
├── train_ddp.py step 2: the same training with DDP
├── sampler_bugs.py step 3: two sampler mistakes
├── load_check.py step 4: load the rank-0 checkpoint
├── memory_math.py step 5: memory per GPU, DDP versus FSDP
└── fsdp_demo.py step 5: parameters sharded across 2 processesmkdir ddp-lab && cd ddp-lab
python3.12 -m venv .venv && source .venv/bin/activate
python -m pip install "torch==2.15.*" \
--index-url https://download.pytorch.org/whl/cpu02. Step 1: A single-process reference
common.py builds a seeded dataset of 1,024 rows with four classes and a small network. make_model sets the seed itself, so every process that calls it starts from the same weights. The reference trains for three epochs with a global batch of 64 rows. It uses a DistributedSampler with a single replica only so that its shuffle order is the one the DDP run will use; that makes the two runs directly comparable.
import torch
from torch import nn
from torch.utils.data import TensorDataset
EPOCHS, GLOBAL_BATCH = 3, 64
def make_dataset():
g = torch.Generator().manual_seed(0)
x = torch.randn(1024, 32, generator=g)
y = (x[:, :8].sum(1) > 0).long() + 2 * (x[:, 8:16].sum(1) > 0).long() # 4 classes
return TensorDataset(x, y)
def make_model():
torch.manual_seed(0) # same initial weights in every process
return nn.Sequential(nn.Linear(32, 128), nn.ReLU(), nn.Linear(128, 4))
def checksum(model):
return sum(p.double().sum().item() for p in model.parameters())"""Reference: one process, global batch of 64."""
import torch
from torch import nn
from torch.utils.data import DataLoader, DistributedSampler
from common import EPOCHS, GLOBAL_BATCH, checksum, make_dataset, make_model
ds = make_dataset()
# A sampler with one replica gives the same shuffled order as the DDP run will use
sampler = DistributedSampler(ds, num_replicas=1, rank=0, shuffle=True, seed=0)
loader = DataLoader(ds, batch_size=GLOBAL_BATCH, sampler=sampler)
model = make_model()
opt = torch.optim.SGD(model.parameters(), lr=0.1)
for epoch in range(EPOCHS):
sampler.set_epoch(epoch)
total = 0.0
for x, y in loader:
loss = nn.functional.cross_entropy(model(x), y)
opt.zero_grad()
loss.backward()
opt.step()
total += loss.item()
print(f"epoch {epoch}: mean loss {total / len(loader):.6f}")
print(f"weight checksum {checksum(model):.6f}")python train_single.pyepoch 0: mean loss 1.279655
epoch 1: mean loss 1.094142
epoch 2: mean loss 0.924369
weight checksum -8.75089503. Step 2: The same training with DDP
Read train_ddp.py from the top. init_process_group connects the processes, using the address and rank that torchrun put in the environment. The DistributedSampler gives each rank a disjoint share of the indices: it shuffles all 1,024 with the same seed on every rank, then rank 0 takes every second index from position 0 and rank 1 every second index from position 1. With a per-rank batch of 64 ÷ 2 = 32, the two ranks together still process 64 rows per step. set_epoch at the start of each epoch changes the shuffle, identically on every rank.
Wrapping the model in DDP registers hooks on the gradients. During backward(), DDP groups gradients into buckets and all-reduces each bucket as soon as it is ready, so communication overlaps with the rest of the backward pass; when backward() returns, every rank holds the average gradient. The loss is a different matter: each rank only knows the loss of its own slice, so the script all-reduces the epoch total with ReduceOp.AVG before rank 0, and only rank 0, prints it. The same rank saves the checkpoint, and dist.barrier() makes every rank wait until the file is written. At the end, every rank sends its weight checksum to rank 0.
"""The same training on several processes with DistributedDataParallel."""
import os
import torch
import torch.distributed as dist
from torch import nn
from torch.nn.parallel import DistributedDataParallel as DDP
from torch.utils.data import DataLoader, DistributedSampler
from common import EPOCHS, GLOBAL_BATCH, checksum, make_dataset, make_model
def main():
# torchrun sets RANK, LOCAL_RANK and WORLD_SIZE, plus the rendezvous address
backend = "nccl" if torch.cuda.is_available() else "gloo"
dist.init_process_group(backend)
rank, world = dist.get_rank(), dist.get_world_size()
local_rank = int(os.environ["LOCAL_RANK"])
device = torch.device(f"cuda:{local_rank}" if backend == "nccl" else "cpu")
if backend == "nccl":
torch.cuda.set_device(device)
ds = make_dataset()
sampler = DistributedSampler(ds, num_replicas=world, rank=rank,
shuffle=True, seed=0)
loader = DataLoader(ds, batch_size=GLOBAL_BATCH // world, sampler=sampler)
model = DDP(make_model().to(device),
device_ids=[local_rank] if backend == "nccl" else None)
opt = torch.optim.SGD(model.parameters(), lr=0.1)
seen = [None] * world
dist.all_gather_object(seen, (len(sampler), list(sampler)[:4]))
if rank == 0:
for r, (n, idx) in enumerate(seen):
print(f"rank {r}: {n} samples per epoch, first indices {idx}")
for epoch in range(EPOCHS):
sampler.set_epoch(epoch) # a new shuffle each epoch, the same on all ranks
total = torch.zeros(1, device=device)
for x, y in loader:
x, y = x.to(device), y.to(device)
loss = nn.functional.cross_entropy(model(x), y)
opt.zero_grad()
loss.backward() # DDP averages the gradients across ranks here
opt.step()
total += loss.detach()
dist.all_reduce(total, op=dist.ReduceOp.AVG) # mean over ranks, for logging
if rank == 0:
print(f"epoch {epoch}: mean loss {total.item() / len(loader):.6f}")
if rank == 0: # one copy of the weights is enough: they are identical
torch.save(model.module.state_dict(), "ddp_model.pt")
dist.barrier() # nobody reads the file before rank 0 has written it
sums = [None] * world
dist.all_gather_object(sums, round(checksum(model.module), 6))
if rank == 0:
print(f"weight checksum per rank {sums}")
dist.destroy_process_group()
if __name__ == "__main__":
main()torchrun --standalone --nproc_per_node=2 train_ddp.pyrank 0: 512 samples per epoch, first indices [684, 933, 227, 683]
rank 1: 512 samples per epoch, first indices [217, 11, 705, 980]
epoch 0: mean loss 1.279655
epoch 1: mean loss 1.094142
epoch 2: mean loss 0.924369
weight checksum per rank [-8.750895, -8.750895]Each rank saw 512 different samples per epoch. The epoch losses and the final checksum are the same as the single-process run, to six decimals, and both ranks end with identical weights. That is not luck. In every step, the two ranks process the two halves of the 64-row batch that the reference used; the mean loss of each half, averaged over the two ranks, equals the mean loss of the whole batch, and so do the gradients. DDP changes where the work is done, not what is computed. On real GPUs the results usually match only within a tolerance, because floating-point sums in a different order round differently.
--standalone tells torchrun to run everything on this machine and pick a free port for the rendezvous. On a GPU server you would write --nproc_per_node=gpu for one process per GPU; across several machines you would replace --standalone with --nnodes and a --rdzv-endpoint that all machines can reach.
04. Step 3: Two sampler mistakes
"""Two common sampler mistakes, shown on 2 processes."""
import torch
import torch.distributed as dist
from torch.utils.data import DataLoader, DistributedSampler
from common import make_dataset
dist.init_process_group("gloo")
rank, world = dist.get_rank(), dist.get_world_size()
ds = make_dataset()
def report(title, value):
values = [None] * world
dist.all_gather_object(values, value)
if rank == 0:
print(title)
for r, v in enumerate(values):
print(f" rank {r}: {v}")
# Mistake 1: no DistributedSampler, so every rank walks the whole dataset
loader = DataLoader(ds, batch_size=32, shuffle=True,
generator=torch.Generator().manual_seed(0))
report("plain DataLoader, rows per epoch:", sum(len(y) for _, y in loader))
# Mistake 2: DistributedSampler without set_epoch, so every epoch has the same order
sampler = DistributedSampler(ds, shuffle=True, seed=0)
firsts = [list(sampler)[:4] for epoch in range(2)] # set_epoch never called
report("no set_epoch, first indices of epochs 0 and 1:", firsts)
firsts = []
for epoch in range(2):
sampler.set_epoch(epoch)
firsts.append(list(sampler)[:4])
report("with set_epoch, first indices of epochs 0 and 1:", firsts)
dist.destroy_process_group()torchrun --standalone --nproc_per_node=2 sampler_bugs.pyplain DataLoader, rows per epoch:
rank 0: 1024
rank 1: 1024
no set_epoch, first indices of epochs 0 and 1:
rank 0: [[684, 933, 227, 683], [684, 933, 227, 683]]
rank 1: [[217, 11, 705, 980], [217, 11, 705, 980]]
with set_epoch, first indices of epochs 0 and 1:
rank 0: [[684, 933, 227, 683], [37, 342, 647, 633]]
rank 1: [[217, 11, 705, 980], [708, 9, 767, 291]]With a plain shuffled DataLoader, each rank walks all 1,024 rows, and with the same seed, in the same order. Two GPUs then do the same work twice: an "epoch" is really two passes over the data, and adding GPUs buys nothing. Without set_epoch, the sampler reshuffles with the same seed every epoch, so epoch 1 repeats the order of epoch 0. Training still runs, which is why this mistake is easy to miss, but the model sees the batches in the same order every epoch.
05. Step 4: Use the rank-0 checkpoint
Rank 0 saved model.module.state_dict(), the weights of the plain model inside the DDP wrapper. That file loads into an ordinary model in an ordinary process, for evaluation or serving, without any distributed set-up.
"""Load the rank-0 checkpoint into a plain model in a normal, single process."""
import torch
from common import make_dataset, make_model
model = make_model()
model.load_state_dict(torch.load("ddp_model.pt", weights_only=True))
x, y = make_dataset().tensors
accuracy = (model(x).argmax(1) == y).float().mean().item()
print(f"keys: {list(model.state_dict())[:2]} ... accuracy {accuracy:.3f}")python load_check.pykeys: ['0.weight', '0.bias'] ... accuracy 0.804To resume a DDP run, every rank loads the same file after the barrier, with map_location set to its own device on GPUs, before wrapping the model in DDP. The optimizer state is identical on all ranks too, so rank 0 can save it once, together with the rest of the state from the checkpointing lesson.
06. Step 5: When DDP is not enough
DDP divides the batch, so it reduces the activation memory per GPU, but every GPU still holds the full weights, gradients and optimizer state. With AdamW and mixed precision that is about 16 bytes per parameter, whether you count fp32 weights and gradients plus two fp32 averages, or bf16 weights and gradients plus fp32 master weights and averages.
"""Training memory per GPU for weights, gradients and AdamW state (no activations)."""
BYTES_PER_PARAM = 16 # bf16 weights 2 + bf16 grads 2 + fp32 master, m and v 4 + 4 + 4
GPU_GB, GPUS = 80, 8
print(f"{'model':>6} {'one GPU / DDP':>14} {'FSDP on 8 GPUs':>15}")
for billions in (1, 7, 13, 70):
total = billions * 1e9 * BYTES_PER_PARAM / 1e9 # in GB
ddp, fsdp = total, total / GPUS
fit = lambda gb: f"{gb:6.0f} GB {'ok' if gb < GPU_GB else 'no'}"
print(f"{billions:>5}B {fit(ddp):>14} {fit(fsdp):>15}")python memory_math.py model one GPU / DDP FSDP on 8 GPUs
1B 16 GB ok 2 GB ok
7B 112 GB no 14 GB ok
13B 208 GB no 26 GB ok
70B 1120 GB no 140 GB noActivations come on top of these numbers, so real limits are lower. Once the per-parameter state alone exceeds one GPU, adding DDP replicas cannot help. Fully Sharded Data Parallel (FSDP) splits each parameter, its gradient and its optimizer state across the ranks, so each GPU stores roughly 1/N of them. Just before a layer runs in the forward or backward pass, the ranks all-gather its full weights, use them, and free the gathered copy again; after the backward pass, gradients are reduce-scattered so that each rank keeps only its shard. The price is more communication per step. PyTorch 2 provides this as FSDP2, the fully_shard function, which also runs on gloo.
"""FSDP2 on 2 CPU processes: each rank stores only a shard of every parameter."""
import torch
import torch.distributed as dist
from torch import nn
from torch.distributed.fsdp import fully_shard
from common import make_dataset, make_model
dist.init_process_group("gloo")
rank, world = dist.get_rank(), dist.get_world_size()
model = make_model()
full = sum(p.numel() for p in model.parameters())
for layer in model:
if isinstance(layer, nn.Linear):
fully_shard(layer) # each layer becomes one unit gathered on demand
fully_shard(model)
local = sum(p.to_local().numel() for p in model.parameters()) # this rank's shard
opt = torch.optim.AdamW(model.parameters(), lr=1e-3) # state is sharded too
x, y = make_dataset().tensors
loss = nn.functional.cross_entropy(model(x[rank::world]), y[rank::world])
loss.backward()
opt.step()
held = [None] * world
dist.all_gather_object(held, local)
if rank == 0:
print(f"parameters in the model: {full:,}; held per rank: {held}")
dist.destroy_process_group()torchrun --standalone --nproc_per_node=2 fsdp_demo.pyparameters in the model: 4,740; held per rank: [2370, 2370]Each rank holds 2,370 of the 4,740 parameters, and the AdamW state it creates covers only that shard. For a model this small, sharding is pure overhead. The rule of thumb is the other way round: use DDP while the model, its gradients and its optimizer state fit on one GPU with room for activations, and move to FSDP when they do not. For gradient accumulation with DDP, wrap the micro-batches before the last in model.no_sync(), so that gradients are all-reduced once per optimizer step instead of once per micro-batch.
07. Check your understanding
08. Apply it
Finish the practice package:
- Make your training script run unchanged with
python train.pyand withtorchrun --standalone --nproc_per_node=2 train.py, using the pattern oftrain_ddp.py. - Log, save checkpoints and run evaluation on rank 0 only, with a barrier after each save.
- Show that a two-process run with half the per-rank batch matches the single-process run within a small tolerance, and write down, using
memory_math.py, at what model size your GPU would need FSDP.
09. Review prompt
Without looking back, explain what each DDP process holds and what is all-reduced during backward(); what torchrun provides to each process; what the DistributedSampler and set_epoch do and what happens without each; why logging, checkpointing and barriers are done the way they are; how many bytes per parameter AdamW training needs and why DDP does not reduce them; and how FSDP gathers and frees parameters.
References
- PyTorch Tutorials: Getting Started with Distributed Data Parallel
- PyTorch docs: torchrun (Elastic Launch)
- PyTorch docs: DistributedDataParallel
- PyTorch Tutorials: Getting Started with Fully Sharded Data Parallel (FSDP2)
- Rajbhandari et al. (2019): ZeRO, Memory Optimizations Toward Training Trillion Parameter Models
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.