Careers Post-AI
AI infrastructure and systems: all chapters

AI infrastructure and systemsPart 3: Training and data systems

Chapter 9Distributed training

30 min read, 1 lab, Intermediate

Training a 70-billion-parameter model with the Adam optimizer needs roughly 1.1 TB of memory for weights, gradients and optimizer state before a single activation is stored, which is more than a dozen 80 GB GPUs hold. Distributed training is the set of tricks that splits that work across many devices, keeps them busy and survives when one of them dies at 3 a.m.

After this chapter you can

  • Explain what one training step does to memory, compute and the network
  • Run data-parallel training with PyTorch DDP and torchrun
  • Choose between DDP, FSDP, tensor and pipeline parallelism for a given model size
  • Apply mixed precision, gradient accumulation and activation checkpointing to fit a job in memory
  • Build checkpoint and restart logic that survives a killed process
  • Measure scaling efficiency and find where it is lost in a profile

The training step as a systems workload

Every training step does the same four things: load a batch, run the forward pass, run the backward pass to get gradients, and let the optimizer update the weights. In How AI systems work you saw this as math. Here you look at it as a workload: memory, compute and communication per step.

Memory is the first wall. With mixed-precision Adam, each parameter costs about 16 bytes before any activations, as the ZeRO paper laid out:

bf16 weights            2 bytes
bf16 gradients          2 bytes
fp32 master weights     4 bytes
fp32 Adam momentum      4 bytes
fp32 Adam variance      4 bytes
-----------------------------------
total                  16 bytes per parameter
 
7B model  ->  ~112 GB   (does not fit one 80 GB GPU)
70B model -> ~1.1 TB

Activations come on top. They are the intermediate tensors the forward pass saves for the backward pass, and they grow with batch size, sequence length and layer count. For long sequences they often exceed the 16 bytes per parameter.

Compute per step is predictable. A dense transformer needs about 6 FLOPs per parameter per token for forward plus backward, so you can estimate step time from the model size, batch size and the GPU's realistic throughput.

FLOPs per step ~= 6 * parameters * tokens_per_step
example: 1B params, 1M tokens per step -> 6e15 FLOPs
on a GPU sustaining 400 TFLOP/s -> ~15 s per step on one GPU

Data parallelism and gradient synchronization

Data parallelism is the simplest split. Every GPU holds a full copy of the model, each gets a different slice of the batch, and after the backward pass all copies average their gradients so they apply the identical update. PyTorch implements this as DistributedDataParallel (DDP).

The averaging is an all-reduce: a collective operation after which every rank holds the sum of everyone's tensors. NCCL (NVIDIA's collective library) runs it on GPUs and Gloo runs it on CPUs. In a ring all-reduce each rank sends and receives about twice the gradient size, no matter how many ranks there are, which is why data parallelism scales well until the network becomes the limit.

DDP does not wait for the whole backward pass to finish. It groups gradients into buckets (25 MB by default) and starts the all-reduce for a bucket as soon as its gradients are ready, so communication overlaps the rest of the backward computation. If the network is fast enough, the all-reduce hides completely behind compute.

ddp_minimal.py
import os, torch, torch.distributed as dist
from torch.nn.parallel import DistributedDataParallel as DDP
 
dist.init_process_group(backend="nccl")          # "gloo" on CPU
local_rank = int(os.environ["LOCAL_RANK"])       # set by torchrun
torch.cuda.set_device(local_rank)
 
model = build_model().cuda(local_rank)
model = DDP(model, device_ids=[local_rank])      # registers gradient hooks
sampler = torch.utils.data.DistributedSampler(dataset)  # disjoint shards per rank
loader = torch.utils.data.DataLoader(dataset, batch_size=32, sampler=sampler)

Sharding and model parallelism

DDP still needs the full 16 bytes per parameter on every GPU. Once that does not fit, you shard. The table shows the main options, from least to most invasive.

TechniqueWhat is splitCommunicationUse when
DDPData only, full replica per GPUAll-reduce of gradients per stepModel state fits one GPU
ZeRO-1 / ZeRO-2Optimizer state, then gradientsReduce-scatter plus all-gatherOptimizer state is the problem
FSDP (ZeRO-3)Weights, gradients and optimizer stateAll-gather weights per layer, reduce-scatter gradientsModel does not fit, fast intra-node links
Tensor parallelIndividual matrix multiplies across GPUsAll-reduce inside every layerHuge layers, NVLink within one node
Pipeline parallelGroups of layers across GPUsActivations between stagesMany layers, slower links between nodes

FSDP (Fully Sharded Data Parallel) keeps only a 1/N slice of every parameter on each GPU. Before a layer runs, it all-gathers that layer's full weights, computes, then frees them; after backward it reduce-scatters gradients so each rank keeps only its slice. The current PyTorch API is fully_shard (often called FSDP2), and the PyTorch docs mark the older FullyShardedDataParallel wrapper as deprecated for new code.

fsdp_sketch.py
from torch.distributed.fsdp import fully_shard
 
for block in model.layers:      # shard bottom-up, one unit per transformer block
    fully_shard(block)
fully_shard(model)              # then the root

Tensor parallelism splits a single weight matrix column-wise or row-wise across GPUs, so every layer needs an all-reduce. That traffic is only affordable over NVLink inside one node. Pipeline parallelism puts layer groups on different GPUs and streams micro-batches through them; its cost is the pipeline bubble, the time stages sit idle while the pipeline fills and drains.

Frontier runs combine all of these into "3D" or "4D" parallelism, adding context parallelism for very long sequences and expert parallelism for mixture-of-experts models. Networking for AI clusters covers the interconnects that make those choices possible.

Fitting the job: precision, accumulation and recomputation

Before reaching for more GPUs, squeeze the step itself. Four techniques do most of the work, and they compose.

  • Mixed precision. Run matmuls in bf16 (or fp16) while keeping fp32 master weights for the update. bf16 has the same exponent range as fp32, so it rarely needs loss scaling; fp16 needs a GradScaler to stop small gradients underflowing to zero. Use torch.autocast(device_type="cuda", dtype=torch.bfloat16).
  • Gradient accumulation. Run several micro-batches forward and backward, summing gradients, then step once. This gives a large effective batch with small activation memory. Under DDP, wrap the non-final micro-batches in model.no_sync() so you all-reduce once per step, not once per micro-batch.
  • Activation checkpointing. Save only some activations and recompute the rest during backward. It costs roughly one extra forward pass (about a third more compute) and can cut activation memory several-fold.
  • Optimizer and offload choices. 8-bit optimizers, or offloading optimizer state to CPU memory as DeepSpeed ZeRO-Offload does, trade speed for capacity.
accumulation.py
accum = 8                                   # effective batch = 8 x micro-batch x world_size
for i, (x, y) in enumerate(loader):
    last = (i + 1) % accum == 0
    ctx = contextlib.nullcontext() if last else model.no_sync()
    with ctx, torch.autocast("cuda", dtype=torch.bfloat16):
        loss = loss_fn(model(x), y) / accum   # scale so the sum is an average
        loss.backward()
    if last:
        torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
        opt.step(); opt.zero_grad(set_to_none=True)

Launchers, checkpoints and fault tolerance

A distributed job needs every process to know its rank, the world size and where to rendezvous. torchrun handles this: it spawns one process per GPU, sets RANK, LOCAL_RANK and WORLD_SIZE, and can restart the whole group when a worker fails.

launch
# one machine, 8 GPUs
torchrun --standalone --nproc_per_node=8 train.py
 
# two machines, same command on each, elastic restart up to 3 times
torchrun --nnodes=2 --nproc_per_node=8 --max-restarts=3 \
  --rdzv-backend=c10d --rdzv-endpoint=node0.internal:29400 --rdzv-id=job42 train.py

Hugging Face Accelerate wraps the same mechanics behind accelerate launch and a config file, so one script can run single-GPU, DDP, FSDP or DeepSpeed without code changes. On Slurm clusters you usually call srun torchrun ... from a batch script, as Cluster scheduling and orchestration shows.

Failures are not rare at scale. Meta's Llama 3 paper reported 419 unexpected interruptions in a 54-day pre-training run on 16,384 GPUs, roughly one every three hours. Restarting is only cheap if checkpoints are frequent, complete and fast to write.

A complete checkpoint holds more than weights:

  • model and optimizer state (the optimizer is usually the larger part)
  • learning-rate scheduler and gradient scaler state
  • step counter and the data loader position, so you do not retrain on the same samples
  • RNG states, if you need bitwise reproducibility

Write to a temporary name and rename when the write finishes, so a crash mid-save never leaves a "latest" checkpoint that is corrupt. For sharded models, torch.distributed.checkpoint (DCP) has every rank write its own shard in parallel and can reload onto a different number of GPUs.

Scaling efficiency and reading a profile

Scaling efficiency compares what N GPUs achieve against N times one GPU. For weak scaling (fixed batch per GPU) it is:

efficiency(N) = throughput(N) / (N * throughput(1))
 
1 GPU: 10,000 tokens/s    8 GPUs: 68,000 tokens/s
efficiency = 68,000 / 80,000 = 0.85

The other headline number is MFU (model FLOPs utilization): achieved FLOPs from the 6-times-parameters formula divided by the hardware peak. Published large dense training runs report MFU of roughly 35 to 50 percent (Meta reported 38 to 43 percent for Llama 3 405B); much lower means something is starving the GPUs.

Efficiency leaks in predictable places:

Symptom in the profileLikely causeFirst fix
GPU idle at the start of each stepData loader too slowMore workers, pinned memory, better format (see Data pipelines and storage)
Long NCCL kernels after backward endsAll-reduce not overlappedLarger buckets, faster interconnect, gradient accumulation
Many tiny kernels with gaps between themPython and launch overheadLarger micro-batch, torch.compile, CUDA graphs
One rank consistently slowerStraggler: bad GPU, thermal throttling, noisy neighbourCheck per-rank step times, cordon the node
Periodic long stallsSynchronous checkpoint writesAsync checkpointing, faster storage
profile_steps.py
from torch.profiler import profile, schedule, ProfilerActivity, tensorboard_trace_handler
 
with profile(activities=[ProfilerActivity.CPU, ProfilerActivity.CUDA],
             schedule=schedule(wait=2, warmup=2, active=3),
             on_trace_ready=tensorboard_trace_handler("./trace")) as prof:
    for step, batch in enumerate(loader):
        train_step(batch)
        prof.step()
        if step == 8: break
print(prof.key_averages().table(sort_by="cuda_time_total", row_limit=15))

Open the trace in Perfetto (ui.perfetto.dev) or TensorBoard. Look at the GPU stream timeline: compute kernels should be packed back to back, nccl:all_reduce should overlap backward kernels, and the gap between the end of one step and the start of the next should be nearly zero.

Key terms

Data parallelism
Every device holds a full model copy and processes a different slice of each batch.
All-reduce
A collective operation that leaves every rank holding the combined (summed or averaged) tensor from all ranks.
FSDP
Fully Sharded Data Parallel: shards weights, gradients and optimizer state across ranks and gathers each layer only when needed.
Tensor parallelism
Splitting individual weight matrices across devices so each computes part of every layer.
Pipeline bubble
Idle time in pipeline parallelism while stages wait for the pipeline to fill or drain.
Gradient accumulation
Summing gradients over several micro-batches before one optimizer step to get a larger effective batch.
Activation checkpointing
Discarding some forward activations and recomputing them in the backward pass to save memory.
MFU
Model FLOPs utilization: useful model FLOPs per second divided by the hardware's peak FLOPs per second.
Goodput
The share of consumed compute time that turns into retained training progress.
Lab

Train with DDP, measure scaling and survive a crash

Intermediate, 75 min

Goal: run the same training script on 1, 2 and 4 processes, compute scaling efficiency, then crash a worker and watch the run resume from its last checkpoint.

You need: Python 3.10 or newer and PyTorch. Everything runs on a laptop CPU with the Gloo backend. For real GPUs, a free Kaggle notebook offers a "GPU T4 x2" accelerator; change the backend to nccl and the device to cuda:LOCAL_RANK.

setup
python -m venv .venv && source .venv/bin/activate
pip install torch
mkdir ddp-lab && cd ddp-lab
  1. Save the training script. It builds a roughly 8M-parameter MLP on synthetic data, checkpoints atomically every 20 steps from rank 0, and can crash on purpose.
train_ddp.py
import os, time, itertools, torch, torch.nn as nn, torch.distributed as dist
from torch.nn.parallel import DistributedDataParallel as DDP
from torch.utils.data import TensorDataset, DataLoader, DistributedSampler
 
CKPT, STEPS, BATCH = "ckpt.pt", int(os.getenv("STEPS", 200)), 64
dist.init_process_group("gloo")
rank, world = dist.get_rank(), dist.get_world_size()
torch.set_num_threads(max(1, os.cpu_count() // world))  # fair CPU split
 
g = torch.Generator().manual_seed(0)
X = torch.randn(20000, 512, generator=g); Y = X @ torch.randn(512, 1, generator=g) / 512 ** 0.5
data = TensorDataset(X, Y)
sampler = DistributedSampler(data, shuffle=True, seed=0)
loader = DataLoader(data, batch_size=BATCH, sampler=sampler, drop_last=True)
 
model = DDP(nn.Sequential(nn.Linear(512, 1024), nn.ReLU(),
                          *[m for _ in range(6) for m in (nn.Linear(1024, 1024), nn.ReLU())],
                          nn.Linear(1024, 1)))
opt = torch.optim.AdamW(model.parameters(), lr=1e-4)
step = 0
if os.path.exists(CKPT):
    s = torch.load(CKPT, map_location="cpu")
    model.module.load_state_dict(s["model"]); opt.load_state_dict(s["opt"]); step = s["step"]
    if rank == 0: print(f"resumed from step {step}", flush=True)
 
per_epoch = len(loader)
crash_at = int(os.getenv("CRASH_AT", -1))
t0, start = time.time(), step
while step < STEPS:
    epoch, offset = divmod(step, per_epoch)
    sampler.set_epoch(epoch)                    # same epoch -> same order -> skip what we did
    for x, y in itertools.islice(loader, offset, None):
        loss = nn.functional.mse_loss(model(x), y)
        opt.zero_grad(); loss.backward(); opt.step(); step += 1
        if rank == 1 and step == crash_at and os.getenv("TORCHELASTIC_RESTART_COUNT") == "0":
            os._exit(1)                         # simulate a dead worker, first attempt only
        if step % 20 == 0 and rank == 0:
            torch.save({"model": model.module.state_dict(), "opt": opt.state_dict(),
                        "step": step}, CKPT + ".tmp")
            os.replace(CKPT + ".tmp", CKPT)     # atomic: never a half-written ckpt.pt
            print(f"step {step} loss {loss.item():.4f}", flush=True)
        if step >= STEPS: break
 
elapsed = time.time() - t0
if rank == 0:
    sps = (step - start) * BATCH * world / elapsed
    print(f"world={world} samples/s={sps:.0f}")
dist.destroy_process_group()
  1. Measure throughput at 1, 2 and 4 processes. Delete the checkpoint between runs so each starts fresh.
scaling
for n in 1 2 4; do rm -f ckpt.pt; STEPS=100 torchrun --standalone --nproc_per_node=$n train_ddp.py | grep samples; done

Expect one world=N samples/s=... line per run. Absolute numbers depend entirely on your CPU; what matters is the ratio. On an older 4-core laptop, 2 processes gave about 1.6 times the single-process throughput, an efficiency near 0.8.

  1. Compute efficiency for each N with samples_per_sec(N) / (N * samples_per_sec(1)). Record them in a table in your notes.

  2. Now crash a worker. Rank 1 exits at step 50 on the first attempt; torchrun tears down the group and restarts it.

crash and resume
rm -f ckpt.pt
CRASH_AT=50 STEPS=200 torchrun --standalone --nproc_per_node=2 --max-restarts=2 train_ddp.py

You should see step 40 loss ..., an error report naming the failed local rank, then resumed from step 40 and training continuing to step 200.

  1. Kill a run by hand. Start a long run, press Ctrl-C after a few checkpoints, then rerun the same command.
manual kill
rm -f ckpt.pt; STEPS=400 torchrun --standalone --nproc_per_node=2 train_ddp.py
# Ctrl-C after "step 100", then:
STEPS=400 torchrun --standalone --nproc_per_node=2 train_ddp.py

Check your work: you have a table of samples per second and efficiency for 1, 2 and 4 processes, and a log showing a restart that prints resumed from step 40 and still reaches step 200.

Stretch: wrap the loop in torch.profiler for 5 steps at world=4 and find the allreduce events in the trace. Then double the model width and re-measure: does efficiency go up or down, and why? (Hint: compare how compute and gradient size each grow.)

Check yourself

A 3B-parameter model trains with mixed-precision Adam. Roughly how much GPU memory does the model state need on each GPU under plain DDP, before activations?

Your DDP job uses gradient accumulation over 8 micro-batches, and the profile shows an all-reduce after every micro-batch. What is the fix?

Why is tensor parallelism usually kept within a single node while FSDP or pipeline parallelism spans nodes?

A run saves checkpoints by writing directly to latest.pt. A node dies halfway through a save. What happens on restart and what would have prevented it?

Scaling from 1 to 8 GPUs gives 5.6 times the throughput, and the profile shows GPUs idle at the start of every step while NCCL kernels overlap well. What is the most likely bottleneck?

Recap

  • Mixed-precision Adam costs about 16 bytes per parameter before activations, which sets when you must shard.
  • DDP replicates the model and overlaps bucketed gradient all-reduce with the backward pass.
  • FSDP shards everything and gathers per layer; tensor and pipeline parallelism split the model itself and depend on fast links.
  • Mixed precision, gradient accumulation with no_sync and activation checkpointing fit a job before you add GPUs.
  • Checkpoints must include optimizer and data position and be written atomically; at scale, failures are a certainty.
  • Scaling efficiency and MFU tell you how much you lose; the profile timeline tells you where.

Go deeper