Unit 2 of 12 · about 4 hours · derive, implement

Loss reduction, update equivalence and the single-process oracle

Equivalence to one process is the contract that buckets, hooks, compression and sharding must all preserve. An oracle plus a tolerance turns silent scale bugs into loud failures.

You'll be able to

  • Derive when averaged rank-local mean gradients equal the full-batch gradient, and how sum reduction changes the answer by a factor of the rank count.
  • Implement a single-process oracle and compare losses, gradients, parameters and optimizer state under a stated tolerance.
  • Explain why the CS336 test shuffles with one shared seed across ranks.

Covers

Local loss, gradient sum or average and update equivalenceSingle-process numerical oracle and tolerance policy
1

Read

In this order, only the parts listed

0 of 3 done

  1. DDP oracle test: one process versus two disjoint shardsCS336 Assignment 2 (Spring 2026) - Section 5 Distributed Data Parallel Training

    Function _test_DistributedDataParallel: non-parallel baseline on all 20 fixture rows, per-rank disjoint 10-row shards at offset = rank * local_bs, 5 SGD steps at lr 0.1 with torch.allclose after each step, shared shuffle seed 42 + i

  2. Data-parallel averaging during backwardUltra-Scale Playbook - Data Parallelism

    Data Parallelism through the first optimization (overlap gradient synchronization with backward pass): per-GPU micro-batches with gradient averaging by all-reduce before the optimizer step

  3. Sum versus mean loss across nodesPyTorch DDP Tutorial, Design Note and Communication Hooks

    Note on training on M nodes with batch N: summed losses give M-times-smaller grads than the single-node batch M times N; treat mean-reduction models as equivalent at the same global batch

2

Focus on

  • With per-rank mean loss, averaging local grads equals the full-batch mean grad. A 2-rank CPU run on an 8-row oracle matches params with torch.allclose at atol=1e-6.
  • With per-rank sum loss, averaging gives the full-batch sum divided by the rank count. Sum the grads, or scale the learning rate, to match a summed oracle.
  • The oracle fixes init, data pool and global batch, then compares loss, grads, params and optimizer state. Exact torch.eq can fail across different GEMM blockings (a CPU port of Picotron's tensor-parallel test missed by 1.8e-7 on PyTorch 2.14.1); use assert_close with a stated tolerance.
  • One shared shuffle seed keeps shards disjoint. Rank-dependent seeds can deal overlapping rows to both ranks.
Common mistakes · 3
  • Comparing a mean-reduction DP run against a sum-reduction oracle and blaming the collective for the factor-of-R gap.
  • Demanding bitwise equality between sharded and full GEMM paths. Rounding differs by blocking; tolerance is the contract.
  • Shuffling per rank with rank-dependent seeds and silently overlapping shards. The shared seed is load-bearing.
3

Try it yourself

Closed-book, before checking anything

Run two CPU ranks on a fixed 8-row linear-regression oracle with MSELoss mean reduction: rank shards of 4 rows, local backward, all_reduce SUM then divide by 2, one SGD step. Assert both ranks match the oracle params with torch.allclose. Then repeat with sum reduction and show averaging misses by the rank count unless grads are summed.
4

Quiz yourself

Answer first, then mark it. Missed ones go to Review.

0 got · 0 missed

  1. 1.Two ranks hold mean-loss grads over disjoint halves. What does their average equal?Answer

    The gradient of the mean loss over the concatenated batch: is the full-batch mean gradient.

  2. 2.Same setup with sum losses. What does averaging give relative to the full-batch sum gradient?Answer

    The full-batch sum gradient divided by 2. Average to match a mean oracle; sum to match a sum oracle.

  3. 3.Why does the CS336 test use torch.manual_seed(42 + i) on every rank before shuffling?Answer

    All ranks draw the identical permutation, so the two 10-row shards stay disjoint. Different seeds per rank could overlap rows.

  4. 4.A CPU port of Picotron's tensor-parallel linear test (2 gloo ranks, PyTorch 2.14.1) fails torch.eq by 1.8e-7 on the gathered outputs. Does that point to a broken collective?Answer

    No. Splitting a GEMM changes its blocking and rounding, and the same port passes assert_close. A DP oracle meets the same effect: per-rank half-batch GEMMs round differently from the full batch.

5

Practice

  • TensorTonic: Synchronize Data-Parallel Gradients

    Function data_parallel_gradient_sync(parameter_replicas, gradient_replicas, learning_rate): public cases check two-rank means, a zero local gradient, and three ranks with two parameter shapes; mean grads are stored in each parameter dtype and updated replicas are independent copies

    Solve before the CS336 DDP tests, as the pool orders it. It checks the averaging arithmetic, not the collective.

You're done when

Your 2-rank gloo run matches the oracle with assert_close, and you can derive the sum-versus-mean factor without notes.

Only when you can do this without notes.

Leads to

Notes

Resources · 3 for this unit, 8 more in the section
  • CS336 Assignment 2 (Spring 2026) - Section 5 Distributed Data Parallel TrainingStanford University · primary

    Complete naive_ddp, naive_ddp_benchmarking, minimal_ddp_flat_benchmarking, ddp_overlap_individual_parameters and its benchmarking problem with your own implementation. tests/test_ddp.py runs on CPU with Gloo; keep the benchmark method and written derivations even when multiple GPUs are unavailable. This year's handout has no bucketed problem: build buckets from Picotron.

  • Ultra-Scale Playbook - Data ParallelismHugging Face · required

    Read Data Parallelism through Revisiting global batch size and Our journey up to now (overlap, bucketing, accumulation and the global batch equation). Derive replicated-state memory, gradient communication and batch constraints for your tiny model before measuring it; ZeRO belongs to DT-4.

  • PyTorch DDP Tutorial, Design Note and Communication HooksPyTorch · support

    Use the tutorial for setup, DistributedSampler, no_sync, unused parameters and teardown, the design note at https://docs.pytorch.org/docs/2.14/notes/ddp.html for buckets and gradient-ready order, and https://docs.pytorch.org/docs/2.14/ddp_comm_hooks.html for communication hooks. Consult them after the from-scratch path so wrappers do not replace the mechanism model.

Also in this section

  • Picotron - Data ParallelismHugging Face · required

    Read data_parallel/bucket.py and the DataParallelBucket path beside train.py, and rebuild bucketed overlap with an equality test against one process. Read DataParallelNaive as a trap: its register_post_accumulate_grad_hook hook receives the parameter, so it averages parameters and leaves gradients local; show the unequal gradients on two CPU ranks.

  • Picotron Tutorial - Steps 5 and 6 and Part 3 VideoHugging Face · support

    Follow step5_data_parallel_naive and step6_data_parallel_bucket with the Part 3 video. Step 5 carries the same parameter-hook trap as Picotron; use step 6 for the equivalence gate.

  • Distributed Training Guide - Chapter 2 DDPLambda Labs · support

    Apply Chapter 2 to a tiny causal-LM loop: torchrun, rank-aware logs, DistributedSampler, rank-zero side effects and the ZeRO memory subsection, plus the gradient-accumulation and effective-batch related topics. Its README says optimizer.step() synchronizes gradients; DDP averages them during backward, so correct that line in your notes.

  • PyTorch Distributed: Experiences on Accelerating Data Parallel TrainingLi et al. (VLDB 2020) · support

    Read the design sections on gradient bucketing, overlap with backward, no_sync and unused-parameter detection. Use them to explain why buckets follow reverse registration order.

  • Deep Learning at Scale - Chapter 7 Data ParallelismSuneeta Mall (O'Reilly) · support

    Read Data Partitioning, Sampling Strategies, DDP and the data-pipeline sections, and use the small DDP exercises as extra practice. Its FSDP and ZeRO material predates FSDP2.

  • TensorTonic - Synchronize Data-Parallel GradientsTensorTonic · support

    Solve Synchronize Data-Parallel Gradients before the CS336 DDP tests.

  • AI Systems Performance Engineering - Chapter 4 Overlap and DDP StrategiesChris Fregly (O'Reilly) · support

    Read Overlapping Communication and Computation, Achieving Maximal Overlap in Practice and Distributed Data Parallel Strategies in Chapter 4, and the Chapter 13 streams section on overlapping communication. With two or more GPUs, compare code/ch04/ddp_no_overlap.py and ddp_overlap.py; they refuse one-rank runs.

  • PyTorch SyncBatchNorm APIPyTorch · reference

    Use convert_sync_batchnorm to convert BatchNorm layers before wrapping with DDP, and read the training-only sync plus single-GPU-per-process limits.