With PyTorch's DistributedSampler in a DDP training loop, what goes wrong when sampler.set_epoch(epoch) is never called, and why?
answer
- DDP does not split the input
- one shared permutation, strided by rank
- seed plus epoch
- epoch stays at zero
- call it before iterating the loader
basics
~20 sDistributedSampler shuffles with a generator seeded by seed plus epoch, and its epoch stays 0 until set_epoch is called. Without the call every epoch replays one permutation, so each rank sees the same shard in the same order.
solid answer
~50 sDDP does not shard the input, so each rank needs its own slice of the data; `DistributedSampler` provides it. With `shuffle=True` (the default) it builds one permutation of the whole dataset from a generator seeded with `seed + epoch` — identical on every rank because `seed` defaults to 0 everywhere — pads or trims it to a multiple of the world size, and gives rank `r` every `num_replicas`-th index starting at `r`. `set_epoch(epoch)` is the only thing that changes `epoch`; never call it and the permutation is the same every epoch, so rank 3 trains on the same sixteenth of the corpus in the same order for the whole run. Nothing crashes — the run simply loses the reshuffling it was meant to have. Call `sampler.set_epoch(epoch)` at the top of each epoch, before iterating the loader, and leave the DataLoader's own `shuffle` off.
go deeper
Recall that DDP does not split the input, that DistributedSampler hands each rank its own slice, and that set_epoch goes at the top of every epoch.
Explain the mechanism: one permutation seeded by seed plus epoch, identical on every rank, padded to a multiple of the world size and strided by rank.
Recognise the silent symptoms of a missing set_epoch or per-rank seeds, and know why a custom per-rank sampler with uneven batch counts hangs the job.
Weigh the built-in sampler's equal-count guarantee against custom duration-bucketed sampling, and decide who owns keeping per-rank step counts equal.
## Why DDP needs a sampler at all `DistributedDataParallel` synchronises gradients; it does **not** chunk or distribute the input. Every rank runs its own `DataLoader`, and if all sixteen loaders iterate the full dataset in the same order, every replica computes the same gradient and the extra GPUs do redundant work. Each rank must see a different, non-overlapping slice — **rank-aware sampling**. `torch.utils.data.distributed.DistributedSampler` is PyTorch's built-in way to get it. ## How DistributedSampler splits the data | Argument | Default | Effect | |---|---|---| | `num_replicas` | world size of the default group | how many slices to cut | | `rank` | this process's rank | which slice to return | | `shuffle` | `True` | permute before slicing | | `seed` | `0` | base of the permutation; must match on every rank | | `drop_last` | `False` | pad the tail (False) or drop it (True) so slices are equal | On every iteration the sampler does the same three steps on every rank: 1. Build a permutation of all indices with a `torch.Generator` seeded by **`seed + epoch`** (or take the indices in order if `shuffle=False`). 2. Make the length a multiple of `num_replicas`: with `drop_last=False` it **repeats indices from the start** to pad; with `drop_last=True` it trims the tail. 3. Take every `num_replicas`-th index starting at `rank` — rank 3 of 16 gets positions 3, 19, 35 and so on. Because every rank computes the *same* permutation, the strided slices are disjoint and together cover the dataset (plus any padding). That is why `seed` must be identical across ranks: different seeds give different permutations, and the slices then overlap and miss samples. ## What `set_epoch` changes The sampler stores `epoch`, which starts at 0. `set_epoch(epoch)` is the only method that changes it, and the docstring is explicit: call it at the beginning of each epoch, **before** the DataLoader iterator is created, or the same ordering is always used. Without the call: - the permutation is identical every epoch, so each rank keeps the same sixteenth of the corpus; - the order inside that sixteenth is identical too, so batches repeat with the same composition; - nothing errors and the loss still falls, which is why the bug survives for weeks. The model still sees every sample once per epoch across the job (plus any padding), but it loses the epoch-to-epoch reshuffle that single-GPU training had — the comparison the team is trying to match. ## Wiring it into the loop ```python sampler = DistributedSampler(train_set) # shuffle=True, seed=0 loader = DataLoader(train_set, batch_size=32, sampler=sampler, collate_fn=collate_asr) # no shuffle= here for epoch in range(start_epoch, num_epochs): sampler.set_epoch(epoch) # before iterating for batch in loader: train_step(model, batch) ``` - Pass the sampler through `sampler=` and leave the DataLoader's `shuffle` off; the sampler owns the order. - When resuming at `start_epoch`, calling `set_epoch(start_epoch)` reproduces that epoch's order. The sampler keeps no position inside an epoch, so a mid-epoch resume has to skip the batches already consumed itself. - `len(loader)` is per rank: about one sixteenth of the single-GPU count. ## When ranks end up with different batch counts `DistributedSampler` deliberately gives every rank the **same number of samples**, so with a fixed batch size every rank runs the same number of steps. Replacing it with a per-rank sampler that batches utterances by duration breaks that guarantee: one rank can have one more batch than the rest. That rank enters an all-reduce nobody else joins and blocks until the process-group timeout. Equalise the batch counts, or wrap the loop in `with model.join():` so ranks that run out shadow the others' collectives. ## A quick check that shuffling works - On rank 0, log the first few indices the sampler yields in epochs 0 and 1; they should differ. - On any rank, `len(sampler)` times the world size should equal the padded total — for 280,000 training utterances on 16 ranks that is 17,500 per rank and no padding, because 280,000 divides by 16. - If two ranks log the same first indices in the same epoch, the seeds differ or the rank was not passed correctly. ## Mistakes to recognise - Calling `set_epoch` after the epoch's loop instead of before it, so each epoch uses the previous value. - Seeding the sampler per rank "for diversity", which breaks disjointness. - Setting `shuffle=True` on the DataLoader as well as passing the sampler.
- The team swaps DistributedSampler for a per-rank sampler that batches utterances by duration; what can now go wrong?Ranks can get different numbers of batches. The rank with an extra batch enters a gradient all-reduce the others never join and blocks until the process-group timeout kills the job. Make the counts equal, or wrap the loop in `model.join()` so finished ranks shadow the remaining collectives; if the model runs other collectives such as `SyncBatchNorm`, use `model.join(throw_on_early_termination=True)`, which makes every rank raise once one runs out.
- How do you resume a DistributedSampler-driven run from a checkpoint taken at the end of epoch 11?Restore the model and optimizer, then start the epoch loop at 12 and call `sampler.set_epoch(12)` before iterating, so the order matches what an uninterrupted run would have used. The sampler keeps no position within an epoch, so resuming mid-epoch also needs the training code to skip the batches already consumed.
- DDP splits each batch across the GPUs, so no sampler is needed
- Give each rank a different sampler seed so their shuffles differ
- DistributedSampler reshuffles automatically at the start of every epoch
- Each rank receives a contiguous block of the dataset
- Set shuffle=True on the DataLoader as well as passing the sampler