skip to content

In PyTorch DDP with gradient accumulation over four micro-batches, how should no_sync be used, and what goes wrong when only backward sits inside it?

level: middleimportance: should knowfreq 16%

answer

  1. skip three all-reduces of four
  2. a context manager on the wrapper
  3. the forward pass arms the reducer
  4. the last micro-batch syncs
  5. every rank must agree on the step

basics

~20 s

Run the forward and backward of micro-batches one to three inside model.no_sync(), so gradients only accumulate locally, and the fourth outside it, so its backward all-reduces the summed gradients once. A forward run outside the context still syncs.

solid answer

~40 s

`model.no_sync()` is a context manager on the DDP wrapper that turns off gradient synchronisation; gradients accumulate in each parameter's `.grad`, and the first forward-backward pass outside the context all-reduces the accumulated sum. With four micro-batches per optimizer step, micro-batches one to three run forward and backward inside `no_sync()`, the fourth runs outside it, and only then do `optimizer.step()` and `zero_grad()` run — one all-reduce round per step instead of four. The forward must be inside: DDP decides at forward time whether the following backward will reduce, so a forward outside the context arms the reducer and a backward inside it still syncs, with no error to say so. Every rank must also leave the context on the same micro-step; ranks that disagree issue mismatched all-reduces and can hang or average the wrong gradients.

code

python · 12 lines
python
import contextlib

accum = 4
for i, batch in enumerate(loader):
    sync_now = (i + 1) % accum == 0          # same answer on every rank
    ctx = contextlib.nullcontext() if sync_now else model.no_sync()
    with ctx:                                # forward AND backward inside
        loss = model(batch.feats, batch.feat_lens, batch.tokens) / accum
        loss.backward()
    if sync_now:
        optimizer.step()
        optimizer.zero_grad(set_to_none=True)

go deeper

for a junior

Recall that no_sync is a context manager on the DDP wrapper and that the last micro-batch of each cycle runs outside it.

for a middle

Explain that DDP decides at forward time whether backward will reduce, why the forward must be inside the context, and how many all-reduce rounds run per step.

for a senior

Spot the silent no-op of a backward-only no_sync, and make the sync decision identical on every rank so collectives never mismatch at an epoch boundary.

for a principal

Judge when accumulation with no_sync is the right lever for a slow inter-node link versus changing the parallel strategy altogether.

## What accumulation needs from DDP **Gradient accumulation** runs several micro-batches through forward and backward, lets their gradients sum in each parameter's `.grad`, and takes one optimizer step for the group. Under DDP, every `backward()` normally triggers the gradient all-reduce: buckets of gradients are averaged across ranks as they become ready. With four micro-batches per step that is four full all-reduce rounds, three of which average gradients that are not yet complete. Only the last one is needed. `DistributedDataParallel.no_sync()` removes the other three. Scaling the loss by the number of micro-batches is part of the accumulation arithmetic itself and is the same as on one GPU; the DDP-specific part is when the all-reduce runs. ## How `no_sync` works `no_sync()` sets the wrapper's `require_backward_grad_sync` flag to `False` for the duration of the `with` block and restores it afterwards. DDP reads that flag **in the forward pass**: a forward with the flag on prepares the reducer to expect gradients and launch bucket all-reduces in the coming backward; a forward with it off does not. Hence the warning in the method's docstring — the forward pass should be inside the context manager, or gradients will still be synchronised. | Micro-step | Forward and backward | All-reduce? | Optimizer | |---|---|---|---| | 1 | inside `no_sync()` | no — gradients sum locally | — | | 2 | inside `no_sync()` | no | — | | 3 | inside `no_sync()` | no | — | | 4 | outside | yes — the accumulated sum is averaged across ranks | `step()`, then `zero_grad()` | ## Three ways to get it wrong 1. **Only `backward()` inside the block.** The forward ran with synchronisation on, so the reducer was armed and the backward all-reduces anyway. Training is correct but no communication is saved, and nothing warns. 2. **Stepping or zeroing every micro-batch.** `zero_grad()` inside the cycle throws away the gradients being accumulated; `step()` inside it updates on partial gradients that were never averaged, so replicas drift apart. 3. **Ranks disagreeing on the sync step.** If the decision comes from something that differs per rank — a loader length, a per-rank data condition — one rank syncs on micro-step 3 while another syncs on 4. DDP requires every rank to issue the same all-reduces in the same order; mismatched calls can hang the backward or average the wrong buckets together. ## Deriving the sync step safely - Use a counter every rank advances identically: `(i + 1) % accum == 0`. - Make sure every rank has the same number of micro-batches, which `DistributedSampler` guarantees by padding. - At the end of an epoch whose length does not divide by `accum`, either drop the partial cycle on every rank or force a sync on the same final step everywhere. ## Confirming the saving - A profiler trace should show all-reduce kernels after every fourth backward only, not after each one. - Compare the gradient norm just before `optimizer.step()` with the norm from an equivalent run without accumulation; if gradients are averaged correctly they agree closely. - Anything that inspects or edits gradients for the whole step, such as clipping, belongs after the synchronising backward and before `optimizer.step()`, where `.grad` holds the averaged sum. ## What it buys - With `accum = 4`, gradient communication per optimizer step falls to a quarter of the naive loop. A rank that sees 1,000 micro-batches per epoch runs 250 synchronising backwards instead of 1,000. - If the loader yields 1,002 micro-batches instead, the last two form a partial cycle that never reaches a sync step under the modulo rule; their gradients sit in `.grad` and leak into the next epoch's first step unless every rank drops or flushes them the same way. - Memory does not grow: the accumulated gradients live in `.grad`, where they would be anyway. - The win is largest when the inter-node link is the bottleneck, as on a two-node job where every all-reduce crosses the network between nodes. The sharding engines in this stack have their own switches for the same purpose; `no_sync` is the DDP one.

  • The training loop wraps only loss.backward() in model.no_sync(); what does a trace or the debug log show?
    An all-reduce round on every micro-batch, the same as without `no_sync`. The forward ran with synchronisation on, so the reducer was already armed when backward started. The results are numerically fine, which is why the mistake survives; the cost is three unnecessary rounds of gradient communication per optimizer step.
  • Can model.no_sync() be combined with a with model.join(): block for uneven inputs?
    Yes. Join's DDP hook asks every iteration whether the non-joined ranks will synchronise in this backward, so ranks that have run out of data shadow only the steps that actually all-reduce. The requirement that all active ranks agree on the sync step still holds.

  • Wrapping only loss.backward() in no_sync is enough to skip the all-reduce
  • no_sync makes DDP keep a second copy of the gradients
  • Each rank can decide its own sync step from its own data
  • optimizer.step() is what triggers DDP's all-reduce