Unit 1 of 12 · about 3 hours · explain, implement
Replicated state, disjoint data ownership and DistributedSampler invariants
Every rank trains a full copy of the model on its own shard. Overlapping shards or miscounted padding silently change the global batch, so ownership must be proved before any timing or scaling claim.
You'll be able to
- Explain what each data-parallel rank replicates and what it owns: full parameters, gradients and optimizer state are replicated, while the data shard is disjoint.
- Build a disjoint sharding with
DistributedSampler, callingset_epocheach epoch and stating the padding and drop policy. - Predict how a sharding bug (overlap, repeat, or miscounted padding) changes the global batch.
Covers
Read
In this order, only the parts listed
0 of 3 done
- DDP construction, rank-zero-first downloads and rank-tagged logsDistributed Training Guide - Chapter 2 DDP
Lines 36 to 50: rank, device and process-group init with the
[rank=...]log format; lines 55 to 68:rank0_firstdownloads plus theDistributedDataParallelwrap withbucket_cap_mb=500; lines 272 to 280: therank0_firstdefinition - DistributedSampler with per-epoch
set_epochDistributed Training Guide - Chapter 2 DDPLines 76 to 84: the
DataLoaderwithDistributedSampler(train_data, shuffle=True, drop_last=True); lines 129 to 137: theset_epochcall before iterating, with the shuffle comment - Data partitioning and sampling strategiesDeep Learning at Scale - Chapter 7 Data Parallelism
Chapter 7 Data Parallelism: Data Partitioning and Implications of Data Sampling Strategies (pp. 229 to 231); Distributed Data Parallel (pp. 242 to 243) including the Devil in the details box on DataLoaders and multiprocessing start methods (p. 243)
Focus on
DistributedDataParallelbroadcasts thestate_dictfrom rank 0 at construction. It never shards data; the sampler or manual offsets own disjointness. This extends the single-process loader contract from Datasets, data loaders and samplers.DistributedSamplerdeals strided shards. Withshuffle=Falseover 10 items and 2 ranks, rank 0 owns[0, 2, 4, 6, 8]and rank 1 owns[1, 3, 5, 7, 9].set_epochre-seeds the shuffle each epoch. Without it every epoch repeats the same order on every rank.- With
drop_last=False, short datasets pad by repeating head indices. Over 10 items and 3 ranks each rank holds 4 indices and ranks 1 and 2 repeat 0 and 1, so token counts must account for the repeats.
Common mistakes · 3
- Assuming the DDP wrapper shards batches. The guide states it does not: the wrapper syncs grads while the sampler splits data.
- Forgetting
set_epoch, then reading correlated epochs as a data bug. Same order every epoch is the default without it. - Storing resume position in the sampler. It has no
state_dict; the loop owns the epoch integer, and the dataset version plus worker RNG must be restored beside it.
Try it yourself
Closed-book, before checking anything
TensorDataset of 10 items and two DistributedSampler instances with num_replicas=2 and shuffle=False. Print both index lists, assert they are disjoint and their union is 0 to 9. Then repeat with 3 replicas and drop_last=False and show each rank holds 4 indices with the head repeats.Quiz yourself
Answer first, then mark it. Missed ones go to Review.
0 got · 0 missed
1.What state is replicated on each rank and what differs?Answer
Parameters, gradients and optimizer state are replicated; the data shard differs. After backward the grads are averaged, so the local optimizer steps agree.
2.Ten items over three ranks with
drop_last=False. How many indices per rank, and which repeat?AnswerFour per rank. Rank 0 holds
[0, 3, 6, 9], rank 1 holds[1, 4, 7, 0]and rank 2 holds[2, 5, 8, 1]; 0 and 1 are the head repeats.3.
set_epochis never called withshuffle=True. What breaks?AnswerNothing crashes, but every epoch shuffles identically, so epochs are fully correlated and any epoch-dependent analysis is wrong.
4.Where does sampler resume position live?Answer
In the training loop as the epoch integer, not in the sampler. Resume must also fix the dataset version and worker seeding.
You're done when
Your CPU script prints disjoint even and odd shards for two ranks and the padded 4-per-rank lists for three ranks, and you can state what each rank replicates and what it owns without notes.
Only when you can do this without notes.
Leads to
Notes
Resources · 2 for this unit, 9 more in the section
- 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. - 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.
Also in this 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. - 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. - 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. - 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.