PREP WITH PROOF
Menu
PYTORCH / PRACTICAL GUIDE

PyTorch DDP no_sync: Where to Wrap Gradient Accumulation

Place DDP no_sync around forward and backward on non-final microbatches. See how the last pass synchronizes gradients and how to test a short window.

THE QUICK ANSWER

With PyTorch DistributedDataParallel (DDP), wrap both the forward pass and backward pass of every non-final microbatch in no_sync(). Run the final forward and backward outside that context, then take one optimizer step. For a short final accumulation window, the last microbatch you actually have is the one that synchronizes.

Put the context around the whole microbatch

Think of an accumulation window as all the microbatches that contribute to one optimizer step. The helper below expects a nonempty list of batches for that window, the same window length on every rank, equally sized microbatches across ranks, and a mean loss with equal weighting. It assumes ordinary DDP gradient averaging, with no custom communication hook. Call it once per window on every rank.

The context starts before ddp(inputs). If you compute predictions outside it and wrap only loss.backward(), DDP can still synchronize on that microbatch. The last pass runs normally so it can synchronize the accumulated gradients before optimizer.step(). Clearing gradients inside the loop would discard previous contributions.

from contextlib import nullcontext

def update_window(ddp, optimizer, loss_fn, batches):
    """Run one nonempty, equally sized microbatch window per rank."""
    optimizer.zero_grad(set_to_none=True)
    for index, (inputs, targets) in enumerate(batches):
        last = index == len(batches) - 1
        context = nullcontext() if last else ddp.no_sync()
        with context:
            predictions = ddp(inputs)
            loss = loss_fn(predictions, targets) / len(batches)
            loss.backward()
    optimizer.step()

Source: PyTorch documentation — DistributedDataParallel.no_sync ↗

Trace one update across two ranks

Suppose you have one scalar parameter and three equally sized microbatches per rank. Each table cell shows the hypothetical gradient of that microbatch’s mean loss before dividing by three. Stop before reading the result and predict the gradient each rank should use for its update.

Rank 0 contributes a local mean of 4 and rank 1 contributes a local mean of 12. Default DDP averaging gives both ranks 8 on the final backward pass. Plain SGD with learning rate 0.1 and no momentum or weight decay subtracts 0.8 on both. If all three passes are wrapped in no_sync(), an immediate optimizer step instead uses 4 on rank 0 and 12 on rank 1. This example counts synchronized backward passes. DDP can communicate several gradient buckets within one synchronized pass.

MicrobatchRank 0 gradientRank 1 gradientSynchronize accumulated gradients?
1210No
2412No
3614Yes

Source: PyTorch documentation — DistributedDataParallel.no_sync ↗

Make the last available microbatch the sync point

Suppose you have five microbatches per rank and target three per update. Pass a list of three batches to the helper, then a list of two. The sync points are microbatches three and five. The final window divides each equally weighted mean loss by two. A loop that checks only whether the global index is a multiple of three would miss the second update boundary.

Start your check with identical model weights, fixed inputs and a deterministic model. Compare parameters after each update against an otherwise identical run that synchronizes on every backward pass. The parameters should match within numerical tolerance. Use a profiler if you also need to establish that the intermediate gradient reductions went away. If batch sizes or the effective number of loss terms differ, derive the denominator separately. no_sync() determines when gradients are shared.

Source: PyTorch Performance Tuning Guide — skip unnecessary all-reduce ↗

Use the loop to solve the PTCA sample question

Read a DDP loop from the optimizer step backwards. Find the last backward pass that contributes to that step. Confirm its forward pass is also outside no_sync(), then check that the earlier forward and backward calls are both inside it. A backward-only wrapper and an optimizer step before the final synchronized backward fail for different reasons.

Open the free PTCA sample below in Study mode and look for the no_sync question. Mark the lines that need to sit inside the context, then compare your choice with the explanation.

Source: PyTorch documentation — DistributedDataParallel.no_sync ↗

KEEP THESE THREE THINGS

Your next steps

  1. Wrap forward and backward together on non-final microbatches.
  2. Synchronize on the actual last microbatch before stepping the optimizer.
  3. Check short windows and loss weighting independently.

Sources & official resources

Linked resources checked on 2026-11-27. Technical behavior and provider guidance can change; check the documentation for the version you use.

About this guide and its recommendations

Published by Prep With Proof with AI-assisted drafting. Study routines and examples are editorial suggestions, not official exam instructions or claims of a learner's personal results. Cited provider facts are linked; ownership of recommended Prep With Proof products is disclosed. No competitor endorsement or guaranteed certification outcome is implied.

Suggest a correction →