skip to content

Your 16-GPU DDP validation pass using PyTorch's DistributedSampler reports a different word error rate than the single-GPU run on the same checkpoint — why?

level: middleimportance: should knowfreq 12%

answer

  1. equal counts per rank
  2. the tail is padded, not dropped
  3. drop_last trims instead
  4. sum the counts, not the rates
  5. shard without padding for evaluation

basics

~20 s

DistributedSampler pads the validation set with repeated utterances so every rank gets the same count, so some are scored twice; drop_last=True drops some instead. Averaging per-rank error rates is a separate, second error. Shard without padding and all-reduce raw counts.

solid answer

~40 s

`DistributedSampler` is built for training, where every rank must run the same number of steps, so with `drop_last=False` (the default) it pads the index list by repeating indices from its start until the length divides by the world size. With 2,705 validation utterances on 16 ranks each rank gets 170 and 15 utterances are scored twice; `drop_last=True` instead trims one utterance so each rank gets 169. Either way the corpus differs from the single-GPU pass. A second error often rides along: averaging sixteen per-rank word error rates weights each rank equally, whereas WER is total word edits divided by total reference words. For an exact number, give each rank `range(rank, len(val_set), world_size)` with no padding, decode under `torch.no_grad()`, accumulate edits and reference-word counts in a tensor, and call `dist.all_reduce(..., op=dist.ReduceOp.SUM)` once per rank.

code

python · 18 lines
python
import torch
import torch.distributed as dist
from torch.utils.data import DataLoader, Subset

rank, world = dist.get_rank(), dist.get_world_size()
shard = Subset(val_set, range(rank, len(val_set), world))   # 170 or 169, no repeats
loader = DataLoader(shard, batch_size=16, collate_fn=collate_asr)

counts = torch.zeros(2, dtype=torch.float64, device="cuda")  # [edits, ref words]
model.eval()
with torch.no_grad():
    for batch in loader:
        hyps = greedy_decode(model.module, batch)
        edits, words = word_edit_counts(hyps, batch.transcripts)
        counts += torch.tensor([edits, words], dtype=torch.float64, device="cuda")

dist.all_reduce(counts, op=dist.ReduceOp.SUM)   # once per rank
wer = (counts[0] / counts[1]).item()

go deeper

for a junior

Recall that DistributedSampler pads with repeated samples by default so every rank gets the same count, and that drop_last=True trims instead.

for a middle

Work the padding arithmetic for a given set size and world size, and explain why a ratio metric must be reduced as summed numerator and denominator.

for a senior

Build an exact distributed evaluation: unpadded shards, no per-batch collectives, one SUM all-reduce, and checks that the scored count matches the set size.

for a principal

Decide when exact distributed evaluation is worth its code against scoring on one rank, and make metric parity with single-GPU runs a release gate.

## The symptom A speech team moves its conformer acoustic model from one GPU to two nodes of eight. Training looks fine, but the validation pass on the same checkpoint reports a slightly different **word error rate** (WER) than the single-GPU evaluation script. The model is not the cause; the difference comes from which utterances were scored, and how the per-rank results were combined. ## Cause one: padding duplicates samples `DistributedSampler` guarantees every rank the **same number of samples**, because in training a rank that runs out early would leave the others waiting in a gradient all-reduce. It enforces that in one of two ways, chosen by `drop_last`: | `drop_last` | What the sampler does | 2,705 utterances on 16 ranks | |---|---|---| | `False` (default) | repeats indices from the start of the list until the length divides by 16 | 170 per rank, 2,720 scored, **15 utterances counted twice** | | `True` | trims the tail to the largest multiple of 16 it keeps | 169 per rank, 2,704 scored, **1 utterance never scored** | The arithmetic for the default: 2,705 / 16 = 169.06, rounded up to 170 per rank; 16 × 170 = 2,720, so 15 padded positions. With `shuffle=True` (also the default) the repeated utterances are whichever ones the permutation put first, so the error is different again each time the seed or epoch changes. ## Cause two: averaging rates instead of counts WER is **total word edits** (substitutions, deletions and insertions) divided by **total reference words**. A common distributed shortcut computes WER per rank and averages the sixteen numbers. That weights every rank equally even though their shards contain different numbers of words, so the average differs from the corpus WER even when no utterance is duplicated. The same trap applies to averaging per-utterance WERs. ## The fix 1. **Shard without padding.** Give each rank `range(rank, len(val_set), world_size)` through `torch.utils.data.Subset`. With 2,705 utterances rank 0 gets 170 and ranks 1-15 get 169; nothing is repeated or lost. 2. **Decode without the wrapper's machinery.** Run the forward pass under `torch.no_grad()` through `model.module`, the plain module inside DDP. 3. **Accumulate raw counts.** Keep a float64 tensor of `[word_edits, reference_words]` on the rank's GPU. 4. **Reduce once.** After its loop, every rank calls `dist.all_reduce(counts, op=dist.ReduceOp.SUM)` exactly once, then computes WER from the totals. Uneven shard sizes are safe here because the only collective is that single all-reduce after the loop, and every rank reaches it the same number of times — once. Uneven counts are what breaks *training*, where every step contains collectives. ## Alternatives and their costs - **Score on rank 0 only**: exact and simple, but fifteen GPUs sit idle while one decodes the whole set. - **Keep the padded sampler and deduplicate**: gather `(utterance_id, edits, words)` tuples to rank 0 with `dist.all_gather_object` and drop repeated ids. Exact, but it moves Python objects through the process group, which is slower than reducing a two-element tensor. - **Set `drop_last=True`**: removes the duplicates but still loses samples whenever the set does not divide evenly. ## Why the sampler pads at all The padding is not a bug. In **training**, every step contains gradient all-reduces, and every rank must run the same number of steps or the rank with the extra batch waits on a collective nobody else joins. Repeating a handful of samples is a harmless price there: fifteen duplicates in an epoch of thousands barely move the gradient. In **evaluation** the same fifteen duplicates enter a metric that is meant to be exact and comparable across runs, and the team's requirement — the same WER as the single-GPU script — makes them visible. The behaviour also changes with the hardware. Moving the same set from 16 ranks to 12 changes the padding from fifteen to seven (2,705 rounds up to 226 per rank, 12 × 226 = 2,712), so the reported WER shifts again without any change to the model. A metric that depends on the world size is a metric nobody can compare. ## Checks before trusting a distributed metric - The number of utterances scored, summed across ranks, equals `len(val_set)`. - The metric is computed from summed numerators and denominators, never from averaged ratios. - Every rank calls each collective the same number of times, whatever its shard size.

  • Why is it safe for rank 0 to score 170 utterances while the others score 169 here, when uneven inputs hang training?
    Training issues gradient all-reduces on every step, so a rank with an extra batch waits on a collective nobody else joins. This evaluation loop issues no collective per batch: decoding runs through `model.module` under `torch.no_grad()`, and the only collective is one SUM all-reduce after the loop, which every rank calls exactly once.
  • Would SUM-reducing per-rank utterance counts and mean per-utterance WERs give the corpus WER?
    No. That reconstructs the average of per-utterance WERs, which weights a two-word utterance the same as a forty-word one. Corpus WER is total edits over total reference words, so reduce those two numbers and divide once at the end.

  • DistributedSampler splits the validation set exactly, so the metric cannot change
  • Setting drop_last=True makes the distributed metric exact
  • Averaging the per-rank WERs gives the corpus WER
  • Uneven shard sizes in evaluation always hang the job