TExcelTAD

DDP in PyTorch, Checkpointing and Fault Recovery

The all-reduce lesson averaged gradients by hand, after the whole backward pass. PyTorch's DistributedDataParallel (DDP) does the same thing properly: it overlaps communication with the backward pass and hides almost all the bookkeeping. This lesson shows a real DDP run with two processes, proves that it matches single-process training step for step, and then deals with the other fact of life on many machines: jobs die. A 64-GPU run that crashes after three days without a usable checkpoint has wasted 4,608 GPU-hours. Checkpointing turns a crash into a short delay.

What DDP does for you

Wrapping a model, model = DDP(model), adds four things:

  1. Same start. At construction, rank 0's parameters and buffers are broadcast to every rank, so all replicas start identical even if their seeds differ.
  2. Gradient hooks. DDP registers a hook on every parameter. When a parameter's gradient is ready during loss.backward(), the hook marks it.
  3. Buckets. Gradients are grouped into buckets of about 25 MB, in the reverse order of the forward pass (the last layers' gradients are ready first). As soon as a bucket is complete, DDP starts an asynchronous all-reduce on it while backward keeps computing earlier layers.
  4. Averaging. The all-reduced sum is divided by the world size, so after backward() returns every rank holds the same averaged gradient and opt.step() makes the same update everywhere.
computenetwork forward bwd L4 bwd L3 bwd L2 bwd L1 opt.step bucket 1 bucket 2 all-reduce of bucket 1 = L4, L3bucket 2 = L2, L1 communication runs while backward is still computing only the end of the last bucket delays the update

What DDP does not do: split the data (that is DistributedSampler's job), save checkpoints, or average your logged loss (each rank only knows its own).

A DDP run that matches one process

Two processes on the CPU (gloo backend), each with a per-rank batch of 32 from its own half of the data, so the global batch is 64. The reference is one process that, at every step, takes the union of what the two ranks see and averages the two shard losses. If DDP is exact, the losses and final weights must agree.

python · try it yourself
import os
import torch
import torch.distributed as dist
import torch.multiprocessing as mp
from torch import nn
from torch.nn.parallel import DistributedDataParallel as DDP
from torch.utils.data import TensorDataset, DataLoader, DistributedSampler
from sklearn.datasets import make_moons

def data():
    X, y = make_moons(n_samples=512, noise=0.2, random_state=0)
    return TensorDataset(torch.tensor(X, dtype=torch.float32), torch.tensor(y))

def make_model():
    torch.manual_seed(0)
    return nn.Sequential(nn.Linear(2, 32), nn.Tanh(), nn.Linear(32, 2))

EPOCHS, BATCH = 4, 32                                   # per-rank batch 32 -> global batch 64

def worker(rank, world):
    os.environ.update(MASTER_ADDR="127.0.0.1", MASTER_PORT="29503", GLOO_SOCKET_IFNAME="lo")
    dist.init_process_group("gloo", rank=rank, world_size=world)
    ds = data()
    sampler = DistributedSampler(ds, num_replicas=world, rank=rank, shuffle=True, seed=0)
    loader = DataLoader(ds, batch_size=BATCH, sampler=sampler)     # each rank: its own 256 examples
    model = DDP(make_model())                           # broadcasts rank 0's weights to every rank
    opt = torch.optim.SGD(model.parameters(), lr=0.1, momentum=0.9)
    for epoch in range(EPOCHS):
        sampler.set_epoch(epoch)                        # a new shuffle every epoch, the same on all ranks
        total = torch.zeros(2)
        for xb, yb in loader:
            loss = nn.functional.cross_entropy(model(xb), yb)
            opt.zero_grad()
            loss.backward()                             # DDP all-reduces (averages) gradients here
            opt.step()
            total += torch.tensor([loss.item() * len(yb), len(yb)])
        dist.all_reduce(total)                          # sum loss and count over ranks for logging
        if rank == 0:
            print(f"DDP, 2 processes  epoch {epoch + 1}: mean loss {total[0] / total[1]:.4f}")
    if rank == 0:
        torch.save(model.module.state_dict(), "ddp_final.pt")      # .module = the unwrapped model
    dist.destroy_process_group()

def single_process_reference(world=2):
    """One process, global batch 64 = the union of what both ranks see in each step."""
    ds = data()
    model = make_model()
    opt = torch.optim.SGD(model.parameters(), lr=0.1, momentum=0.9)
    samplers = [DistributedSampler(ds, num_replicas=world, rank=r, shuffle=True, seed=0) for r in range(world)]
    for epoch in range(EPOCHS):
        for s in samplers:
            s.set_epoch(epoch)
        shards = [list(s) for s in samplers]
        losses = []
        for i in range(0, len(shards[0]), BATCH):
            parts = [ds[torch.tensor(sh[i:i + BATCH])] for sh in shards]
            # mean over each rank's 32, then over ranks = what DDP computes
            loss = sum(nn.functional.cross_entropy(model(xb), yb) for xb, yb in parts) / world
            opt.zero_grad(); loss.backward(); opt.step()
            losses.append(loss.item())
        print(f"single process    epoch {epoch + 1}: mean loss {sum(losses) / len(losses):.4f}")
    return model

if __name__ == "__main__":
    mp.spawn(worker, args=(2,), nprocs=2)
    ref = single_process_reference()
    ddp_state = torch.load("ddp_final.pt")
    diff = max((ddp_state[k] - v).abs().max().item() for k, v in ref.state_dict().items())
    print("final weights equal (float32, max difference < 1e-5):", diff < 1e-5)
DDP, 2 processes  epoch 1: mean loss 0.5273
DDP, 2 processes  epoch 2: mean loss 0.3301
DDP, 2 processes  epoch 3: mean loss 0.3221
DDP, 2 processes  epoch 4: mean loss 0.2984
single process    epoch 1: mean loss 0.5273
single process    epoch 2: mean loss 0.3301
single process    epoch 3: mean loss 0.3221
single process    epoch 4: mean loss 0.2984
final weights equal (float32, max difference < 1e-5): True

Every epoch's mean loss agrees to four decimals and the final weights agree to float32 rounding: two processes with DDP trained exactly the model one process would have trained with a batch of 64. Points to notice in the code:

  • DistributedSampler gives each rank a disjoint half of a permutation of the 512 examples. sampler.set_epoch(epoch) changes the permutation every epoch; forget it and every epoch sees the same order.
  • model.module is the original model inside the DDP wrapper. Save model.module.state_dict(), otherwise every key gets a module. prefix and the file only loads into a DDP-wrapped model.
  • The logged loss is all-reduced (sum of losses and counts), so rank 0 prints the mean over all 512 examples, not over its own 256.

Launching for real: torchrun

The examples use torch.multiprocessing.spawn so that one file runs on its own. On real hardware the usual launcher is torchrun, which starts one process per GPU and passes RANK, LOCAL_RANK and WORLD_SIZE in environment variables. A typical GPU script looks like this (shown, not run: it needs GPUs):

python
# train.py, started with:  torchrun --nproc_per_node=4 train.py
import os, torch, torch.distributed as dist
from torch.nn.parallel import DistributedDataParallel as DDP

dist.init_process_group("nccl")                      # rendezvous details come from torchrun
local_rank = int(os.environ["LOCAL_RANK"])
torch.cuda.set_device(local_rank)                    # one GPU per process
model = DDP(build_model().cuda(local_rank), device_ids=[local_rank])
# ... DistributedSampler, the training loop, checkpoints from rank 0 ...
dist.destroy_process_group()

For several machines, the same script is started on each with --nnodes, a shared --rdzv-endpoint and --max-restarts; that last option is the hook for fault recovery below.

Checkpointing: what to save

A checkpoint must contain everything that influences the rest of training, not just the weights:

Save Why
model state_dict (of model.module) the weights and buffers (BatchNorm running statistics)
optimiser state_dict momentum and Adam's moment estimates, per parameter, plus the step count
learning-rate scheduler state_dict where in the schedule you are (warm-up, cosine phase)
epoch and step counters where to continue; the sampler's set_epoch depends on it
RNG states (Python, NumPy, torch, CUDA, per rank) dropout masks, augmentation and shuffles continue as they would have
gradient scaler (mixed precision), best validation score, early-stopping counter the rest of the training state
config, code version, data version so you know what the checkpoint belongs to

(Early stopping and checkpointing covered keeping the best weights; here the goal is to continue training.)

From scratch: resume must reproduce the same losses

The test of a checkpoint is simple: an interrupted and resumed run must produce exactly the losses of an uninterrupted one. The NumPy version trains a small network with SGD with momentum, saves after epoch 3, "crashes", and resumes in a fresh state, once with everything and twice with one piece missing.

python · try it yourself
import io
import json
import numpy as np
from sklearn.datasets import make_moons

X, y = make_moons(n_samples=400, noise=0.2, random_state=0)
X = (X - X.mean(0)) / X.std(0)

def init_state(seed=0):
    rng = np.random.default_rng(seed)
    return {"W1": rng.normal(0, 0.7, (2, 16)), "b1": np.zeros(16), "W2": rng.normal(0, 0.25, (16, 1)), "b2": np.zeros(1),
            "vel": None, "epoch": 0, "rng": rng}

def run_epoch(s, lr=0.3, beta=0.9, batch=32):
    """One epoch of mini-batch SGD with momentum; the shuffle uses s['rng']. Returns the mean loss."""
    params = ["W1", "b1", "W2", "b2"]
    if s["vel"] is None:
        s["vel"] = {k: np.zeros_like(s[k]) for k in params}
    losses = []
    for idx in np.array_split(s["rng"].permutation(len(y)), len(y) // batch):
        h = np.tanh(X[idx] @ s["W1"] + s["b1"])
        p = 1 / (1 + np.exp(-(h @ s["W2"] + s["b2"])[:, 0]))
        losses.append(-np.mean(y[idx] * np.log(p) + (1 - y[idx]) * np.log(1 - p)))
        g = ((p - y[idx]) / len(idx))[:, None]
        gh = g @ s["W2"].T * (1 - h ** 2)
        grads = {"W2": h.T @ g, "b2": g.sum(0), "W1": X[idx].T @ gh, "b1": gh.sum(0)}
        for k in params:
            s["vel"][k] = beta * s["vel"][k] + grads[k]
            s[k] -= lr * s["vel"][k]
    s["epoch"] += 1
    return np.mean(losses)

def save(s):
    """Everything needed to continue: weights, optimizer buffers, counters, RNG state."""
    buf = io.BytesIO()                       # a file on disk in real life
    arrays = {k: s[k] for k in ["W1", "b1", "W2", "b2"]}
    arrays.update({"vel_" + k: v for k, v in s["vel"].items()})
    np.savez(buf, epoch=s["epoch"], rng_state=json.dumps(s["rng"].bit_generator.state), **arrays)
    return buf.getvalue()

def load(blob, with_momentum=True, with_rng=True):
    f = np.load(io.BytesIO(blob))
    s = init_state(seed=123)                 # a fresh process: different random state
    for k in ["W1", "b1", "W2", "b2"]:
        s[k] = f[k].copy()
    s["vel"] = {k: f["vel_" + k].copy() for k in ["W1", "b1", "W2", "b2"]} if with_momentum else None
    if with_rng:
        s["rng"].bit_generator.state = json.loads(str(f["rng_state"]))
    s["epoch"] = int(f["epoch"])
    return s

s = init_state()
full = [run_epoch(s) for _ in range(6)]
print("uninterrupted      :", " ".join(f"{l:.4f}" for l in full))

s = init_state()
first = [run_epoch(s) for _ in range(3)]
blob = save(s)
print(f"checkpoint after epoch {s['epoch']}: {len(blob):,} bytes")
del s                                         # the process "crashes"
for label, kw in [("resumed, full state ", {}),
                  ("resumed, no momentum", {"with_momentum": False}),
                  ("resumed, no RNG     ", {"with_rng": False})]:
    s = load(blob, **kw)
    rest = [run_epoch(s) for _ in range(3)]
    same = all(abs(a - b) < 1e-12 for a, b in zip(full[3:], rest))
    print(f"{label}:", " ".join(f"{l:.4f}" for l in first + rest), "| identical:", same)
uninterrupted      : 0.3986 0.3214 0.2737 0.2606 0.2227 0.1902
checkpoint after epoch 3: 4,178 bytes
resumed, full state : 0.3986 0.3214 0.2737 0.2606 0.2227 0.1902 | identical: True
resumed, no momentum: 0.3986 0.3214 0.2737 0.2653 0.2449 0.2086 | identical: False
resumed, no RNG     : 0.3986 0.3214 0.2737 0.2454 0.1963 0.1772 | identical: False

With the full state the resumed run reproduces the uninterrupted losses exactly. Without the momentum buffer the next epochs differ (0.2653 instead of 0.2606 in epoch 4), because the first resumed steps lose their accumulated velocity. Without the RNG state the shuffles of epochs 4 to 6 differ, so the run continues as a different (here, by chance, lower-loss) run: not wrong as training, but no longer reproducible, which matters when you debug or compare experiments.

Fault recovery with DDP

In a DDP job, rank 0 writes the checkpoint and all ranks read it on restart. Three details matter:

  • One writer, atomic writes. Write to a temporary file and os.replace it onto the real name; a crash during the write then leaves the previous checkpoint intact instead of a truncated file.
  • A barrier after saving, so no rank races ahead and a restart never sees a checkpoint older than some rank's progress.
  • Per-rank RNG states, gathered to rank 0, because each rank has its own dropout masks.

The example trains 6 epochs with dropout and a cosine learning-rate schedule. Run 1 is uninterrupted. Run 2 is killed after epoch 3 and restarted; the restart finds checkpoint.pt and continues.

python · try it yourself
import os
import torch
import torch.distributed as dist
import torch.multiprocessing as mp
from torch import nn
from torch.nn.parallel import DistributedDataParallel as DDP
from torch.utils.data import TensorDataset, DataLoader, DistributedSampler
from sklearn.datasets import make_moons

CKPT, EPOCHS = "checkpoint.pt", 6

def save_checkpoint(model, opt, sched, epoch, rank, world):
    rng_states = [None] * world
    dist.all_gather_object(rng_states, torch.get_rng_state())   # every rank's dropout RNG
    if rank == 0:                                               # one writer
        state = {"model": model.module.state_dict(), "optimizer": opt.state_dict(),
                 "scheduler": sched.state_dict(), "epoch": epoch, "rng": rng_states}
        torch.save(state, CKPT + ".tmp")
        os.replace(CKPT + ".tmp", CKPT)                         # atomic: never a half-written file
    dist.barrier()                                              # nobody runs ahead of the save

def worker(rank, world, crash_after):
    os.environ.update(MASTER_ADDR="127.0.0.1", MASTER_PORT="29504", GLOO_SOCKET_IFNAME="lo")
    dist.init_process_group("gloo", rank=rank, world_size=world)
    X, y = make_moons(n_samples=512, noise=0.2, random_state=0)
    ds = TensorDataset(torch.tensor(X, dtype=torch.float32), torch.tensor(y))
    sampler = DistributedSampler(ds, num_replicas=world, rank=rank, seed=0)
    loader = DataLoader(ds, batch_size=32, sampler=sampler)
    torch.manual_seed(0)
    model = DDP(nn.Sequential(nn.Linear(2, 32), nn.Tanh(), nn.Dropout(0.2), nn.Linear(32, 2)))
    opt = torch.optim.SGD(model.parameters(), lr=0.1, momentum=0.9)
    sched = torch.optim.lr_scheduler.CosineAnnealingLR(opt, T_max=EPOCHS)
    torch.manual_seed(100 + rank)                     # each rank its own dropout masks
    start = 0
    if os.path.exists(CKPT):                          # resume if a checkpoint exists
        state = torch.load(CKPT, weights_only=False)  # our own file, so unpickling is safe
        model.module.load_state_dict(state["model"])
        opt.load_state_dict(state["optimizer"])
        sched.load_state_dict(state["scheduler"])
        torch.set_rng_state(state["rng"][rank])
        start = state["epoch"] + 1
        if rank == 0:
            print(f"  resumed from the checkpoint of epoch {start}")
    for epoch in range(start, EPOCHS):
        sampler.set_epoch(epoch)
        model.train()
        total = torch.zeros(2)
        for xb, yb in loader:
            loss = nn.functional.cross_entropy(model(xb), yb)
            opt.zero_grad(); loss.backward(); opt.step()
            total += torch.tensor([loss.item() * len(yb), len(yb)])
        sched.step()
        dist.all_reduce(total)
        if rank == 0:
            print(f"  epoch {epoch + 1}: loss {total[0] / total[1]:.4f}, lr {sched.get_last_lr()[0]:.4f}")
        save_checkpoint(model, opt, sched, epoch, rank, world)
        if epoch + 1 == crash_after:
            if rank == 0:
                print(f"  -- job killed after epoch {epoch + 1} --")
            break
    dist.destroy_process_group()

if __name__ == "__main__":
    print("run 1: uninterrupted", flush=True)
    mp.spawn(worker, args=(2, None), nprocs=2)
    os.remove(CKPT)
    print("run 2: killed after epoch 3, then restarted", flush=True)
    mp.spawn(worker, args=(2, 3), nprocs=2)
    mp.spawn(worker, args=(2, None), nprocs=2)        # the restart finds checkpoint.pt
run 1: uninterrupted
  epoch 1: loss 0.5228, lr 0.0933
  epoch 2: loss 0.3447, lr 0.0750
  epoch 3: loss 0.3393, lr 0.0500
  epoch 4: loss 0.3247, lr 0.0250
  epoch 5: loss 0.3090, lr 0.0067
  epoch 6: loss 0.3135, lr 0.0000
run 2: killed after epoch 3, then restarted
  epoch 1: loss 0.5228, lr 0.0933
  epoch 2: loss 0.3447, lr 0.0750
  epoch 3: loss 0.3393, lr 0.0500
  -- job killed after epoch 3 --
  resumed from the checkpoint of epoch 3
  epoch 4: loss 0.3247, lr 0.0250
  epoch 5: loss 0.3090, lr 0.0067
  epoch 6: loss 0.3135, lr 0.0000

The restarted job continues with epoch 4 at the right learning rate (0.0250) and reproduces the uninterrupted run's losses for epochs 4 to 6 exactly: the weights, momentum, scheduler position, sampler epoch and both ranks' dropout RNGs were all restored. (weights_only=False is needed because the checkpoint contains Python objects such as the RNG list; only do this for files you wrote yourself, since unpickling runs code.)

How often to checkpoint

Saving costs time CC (seconds to minutes for a large model). Saving rarely loses up to one interval TT of work per failure; on average half of it. With a mean time between failures MM, the expected fraction of time wasted is about

waste(T)≈CT+T2M,minimised atT∗=2CM\text{waste}(T) \approx \frac{C}{T} + \frac{T}{2M}, \qquad \text{minimised at} \quad T^{*} = \sqrt{2CM}

(Young's approximation). For a checkpoint that takes C=2C = 2 minutes on a job whose hardware fails on average every M=8M = 8 hours: T∗=2⋅2⋅480≈44T^{*} = \sqrt{2 \cdot 2 \cdot 480} \approx 44 minutes, and the waste is about 2/44+44/960≈9%2/44 + 44/960 \approx 9\%. The more devices, the smaller MM (each device can fail), so large jobs checkpoint more often and invest in fast, asynchronous saves that write while training continues. Keep the last two or three checkpoints, not just one: a checkpoint can be corrupt, or the run can diverge just before it.

Elastic training

torchrun --max-restarts=3 restarts all processes when one fails; with the resume-from-checkpoint logic above the job continues on its own. Elastic jobs (--nnodes=2:4) may even continue with fewer machines. Then the world size changes, the global batch changes, and so does the effective learning rate (see the scaling rule in data parallelism): a resumed elastic job is not bit-for-bit the same run, and the checkpoint must not hard-code the number of ranks (store the per-rank RNG states by rank, and re-create the sampler for the new world size).

Pitfalls

  • Saving from every rank. Several processes writing the same file corrupt it. Rank 0 saves; the others wait at a barrier.
  • Saving the DDP wrapper. Keys get a module. prefix. Save model.module.state_dict().
  • Weights only. A checkpoint without optimiser, scheduler and RNG state resumes as a different run, as the NumPy example showed.
  • Forgetting sampler.set_epoch, so every epoch uses the same shuffle.
  • Loading onto the wrong device. A checkpoint written from GPU 0 loads onto GPU 0 in every process unless you pass map_location (for example {"cuda:0": f"cuda:{local_rank}"}).
  • Conditional code paths on one rank. If only rank 0 runs an extra forward pass or skips a batch, the ranks call all-reduce a different number of times and the job hangs. Every rank must run the same collective operations in the same order (validation included, or none).
  • Untested restore. Test resume on a small run, as above, before you need it on a big one.

Practice

  1. A 16-GPU job checkpoints every 2 hours and crashes after 7 h 50 min. How many GPU-hours of work are lost, ignoring restart time?
  2. Why does DDP all-reduce the gradients of the last layers first?
  3. The checkpoint stores epoch = 3, but the code resumes with sampler.set_epoch(0). What goes wrong?
  4. Compute T∗T^{*} for C=30C = 30 seconds and M=24M = 24 hours.
Answers
  1. The last checkpoint was at 6 h, so 1 h 50 min of work is lost on each of 16 GPUs: about 29.3 GPU-hours.
  2. Backward computes gradients from the output towards the input, so the last layers' gradients are ready first. Starting their all-reduce immediately overlaps communication with the remaining backward computation.
  3. Epoch 4 would see the same shuffle as epoch 1, so the resumed run differs from the uninterrupted one (and over many restarts some orderings repeat). Call set_epoch(epoch) with the restored epoch number.
  4. C=0.5C = 0.5 min, M=1440M = 1440 min: T∗=2⋅0.5⋅1440=1440≈38T^{*} = \sqrt{2 \cdot 0.5 \cdot 1440} = \sqrt{1440} \approx 38 minutes.

Test yourself

What does DistributedDataParallel do during loss.backward()?

  1. Nothing; gradients are averaged in opt.step()
  2. It all-reduces gradients in buckets as they become ready, overlapping with the rest of backward, and averages them
  3. It sends all gradients to rank 0
  4. It splits the model's layers across devices

Which checkpoint lets an interrupted run reproduce the uninterrupted run's losses exactly?

  1. The model weights
  2. Weights and optimiser state
  3. Weights, optimiser, scheduler, epoch counter and every rank's RNG state
  4. The last logged loss

Why write the checkpoint to a temporary file and then os.replace it?

  1. It is faster
  2. A crash during the write leaves the previous complete checkpoint in place instead of a truncated file
  3. So that every rank can write at once
  4. To compress it

With checkpoint cost CC and mean time between failures MM, what interval minimises the expected waste (Young's approximation)?

  1. T=CT = C
  2. T=M/2T = M/2
  3. T=2CMT = \sqrt{2CM}
  4. T=CMT = CM