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
Read
In this order, only the parts listed
0 of 3 done
- 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 atoffset = rank * local_bs, 5 SGD steps at lr 0.1 withtorch.allcloseafter each step, shared shuffle seed42 + i - 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
- 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
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.allcloseatatol=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.eqcan fail across different GEMM blockings (a CPU port of Picotron's tensor-parallel test missed by1.8e-7on PyTorch 2.14.1); useassert_closewith 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.
Try it yourself
Closed-book, before checking anything
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.Quiz yourself
Answer first, then mark it. Missed ones go to Review.
0 got · 0 missed
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.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.Why does the CS336 test use
torch.manual_seed(42 + i)on every rank before shuffling?AnswerAll ranks draw the identical permutation, so the two 10-row shards stay disjoint. Different seeds per rank could overlap rows.
4.A CPU port of Picotron's tensor-parallel linear test (2
glooranks, PyTorch 2.14.1) failstorch.eqby1.8e-7on the gathered outputs. Does that point to a broken collective?AnswerNo. 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.
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 copiesSolve 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_parametersand its benchmarking problem with your own implementation.tests/test_ddp.pyruns 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.pyand theDataParallelBucketpath besidetrain.py, and rebuild bucketed overlap with an equality test against one process. ReadDataParallelNaiveas a trap: itsregister_post_accumulate_grad_hookhook 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_naiveandstep6_data_parallel_bucketwith 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 saysoptimizer.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_syncand 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.pyandddp_overlap.py; they refuse one-rank runs. - PyTorch SyncBatchNorm APIPyTorch · reference
Use
convert_sync_batchnormto convert BatchNorm layers before wrapping with DDP, and read the training-only sync plus single-GPU-per-process limits.