Unit 4 of 12 · about 4 hours · implement
Minimal data parallelism with an explicit all-reduce
One explicit collective loop, written by hand, is the reference every wrapper must match. Wrappers hide ordering; this unit makes it visible.
You'll be able to
- Implement naive data parallelism by hand: broadcast at init, shard the batch evenly, all-reduce and average grads, step locally.
- Pass the CS336 DDP public tests for the plain and tied-weight toy models on CPU.
- State the per-step collective volume for the toy model from its parameter count.
Covers
Read
In this order, only the parts listed
0 of 3 done
- Naive DDP: broadcast, shard, all-reduce, stepCS336 Assignment 2 (Spring 2026) - Section 5 Distributed Data Parallel Training
Section 5.2 A Naive Implementation of Distributed Data Parallel Training (p. 33): broadcast from rank 0, shard batch n over d devices, local forward and backward, all-reduce average grads, local optimizer step; problems
naive_ddp(5pt) andnaive_ddp_benchmarking(3pt) - Public DDP tests and adapter contractCS336 Assignment 2 (Spring 2026) - Section 5 Distributed Data Parallel Training
Tests
test_DistributedDataParalleloverToyModelandToyModelWithTiedWeightsat world size 2 on gloo:validate_ddp_net_equivalencebroadcast check, disjoint 10-row shards, 5 SGD steps at lr 0.1 withtorch.allcloseper step; adaptersget_ddpplusddp_on_after_backward - Naive-path trap (read, do not copy)Picotron - Data Parallelism
Class
DataParallelNaive:register_backward_hookwithregister_post_accumulate_grad_hookin_allreduce_grads(lines 33 to 49). Read-only trap: the hook receives the parameter, so this path averages parameters and leavesparam.gradlocal.
Focus on
- Init broadcasts params from rank 0; the CS336 check
validate_ddp_net_equivalenceall-gathers thestate_dictand assertsallcloseon every rank. - Each rank forwards its disjoint shard (20 rows over 2 ranks gives
offset = rank * local_bswith 10 rows each), backprops a local mean loss, thenall_reduceSUM plus divide by world size. - The optimizer step stays local: identical averaged grads plus identical init keep replicas in sync with no per-step broadcast.
- Frozen params with
requires_grad=Falsecarry no grads:no_grad_fixed_paramand the_FC2bias stay equal and untouched.
Common mistakes · 3
- Copying the Picotron naive hook.
register_post_accumulate_grad_hookreceives the parameter tensor, not the grad: the shipped code all-reduces weights while grads diverge (for examplegrad[0,0]of-0.0538on rank 0 versus-0.0662on rank 1 after one backward on different inputs, 2 CPU ranks ongloo, PyTorch 2.14.1). - Dividing by world size twice, or never. All-reduce SUM followed by exactly one division matches the mean oracle.
- Requiring grads for frozen params. The test asserts they stay equal without sync; only
requires_gradparams enter the collective.
Try it yourself
Closed-book, before checking anything
get_ddp and ddp_on_after_backward in your own repo and run pytest tests/test_ddp.py on CPU (world size 2, gloo) until both model variants pass all 5 steps.Quiz yourself
Answer first, then mark it. Missed ones go to Review.
0 got · 0 missed
1.What three operations does naive DDP need, and when?Answer
Broadcast params once at init; per step, all-reduce SUM grads plus one division; local optimizer step. No per-step broadcast.
2.The Picotron naive hook all-reduces its argument and divides. Why do grads still diverge across ranks?Answer
Its argument is the parameter. Parameters get averaged while
param.gradstays local on every rank.3.20 examples, world size 2. Which rows does rank 1 train on?Answer
Rows 10 to 19:
offset = rank * local_bswithlocal_bs10.4.Why does the test call
ddp_on_after_backwardbefore the optimizer step?AnswerAsync implementations wait on grad handles there. A blocking naive version implements it as a no-op.
Practice
- CS336 Assignment 2:
naive_ddpProblem (
naive_ddp), Section 5.2; connect your container toget_ddpintests/adapters.pyand passtests/test_ddp.pyRuns on CPU with gloo. Implement in your own repository; keep the benchmark write-up even where two GPUs are unavailable.
You're done when
Both toy variants pass all 5 steps, and you can explain the Picotron hook trap without notes.
Only when you can do this without notes.
Leads to
Notes
Resources · 2 for this unit, 9 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. - 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.
Also in this section
- 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. - 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. - 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.