Unit 2 of 12 · about 4 hours · implement
Dataset manifests, document-to-batch lineage and deterministic sampler position
Data order is optimizer input: a duplicated shard or a reshuffle on resume silently trains a different model. Lineage plus sampler position makes every example accountable before ranks are added.
You'll be able to
- Implement a restartable sharded sampler with deterministic shuffle, disjoint coverage and a stated padding or drop policy.
- Trace any batch back to document IDs and a manifest version, and serialize sampler position as epoch plus RNG state.
- Diagnose duplicate or omitted samples and seed collisions across ranks and loader workers.
Covers
Read
In this order, only the parts listed
0 of 3 done
- Sampler order, sharding and worker randomnessPyTorch data loading API - DataLoader, Sampler and multi-process loading
Data Loading Order and Sampler; Single- and Multi-process Data Loading with Randomness in multi-process data loading;
DistributedSamplerentry:set_epoch,seed,drop_lasthead padding,lenreporting the per-rank countRead the sampler contract, not the whole loader reference. Note that
DistributedSamplerhas nostate_dict; position is the epoch integer plus the loop-owned RNG state. - Determinism and data-loading notesDistributed Training Guide - Chapter 1 and Related Topics
RNG save and restore (
rng.ptwith torch, NumPy and Python states),torch.use_deterministic_algorithms(True), seededGeneratorwith_seed_worker; related-topicsoptimizing-data-loadingREADME fornum_workers,prefetch_factorand the rank-wait timer - Deterministic seeding and worker disciplineMachine Learning Engineering Open Book - Training and PyTorch Debugging
enforce_reproducibility(use_seed=None): seeds forrandom, NumPy, torch and CUDA,CUBLAS_WORKSPACE_CONFIGset before CUDA init,torch.use_deterministic_algorithms(True)andcudnn.benchmark=False. For the copied-generator trap read Randomness in multi-process data loading in https://docs.pytorch.org/docs/2.14/data.html and reseed inside each loader worker from the seed thattorch.utils.data.get_worker_info()reports
Focus on
- Sampler position is an epoch integer owned by the training loop plus dataset version and RNG state. Call
set_epoch(n)every epoch or every epoch repeats the first epoch's order. - With
shuffle=Falseanddrop_last=Falsean uneven split pads with head indices: 10 items over 3 ranks yield per-rank rows , and . Padding duplicates examples, so token and sample counts must use the manifest, not the batch count. - Main-process shuffling assigns indices to loader workers, but an RNG object created in
Dataset.__init__is fork-copied identically into each worker. Seed inside each worker process from the seed thattorch.utils.data.get_worker_info()reports instead. - Document-to-batch lineage means each batch element records its document ID, shard and position. A manifest fixes ordered shard paths, checksums, counts and recipe version; resume under a changed manifest is rejected.
Common mistakes · 3
- Calling
DistributedSampler.state_dict. It does not exist; resume restores the epoch integer and the loop-owned RNG and worker state. - Assuming padding is free. Padded head items are real repeated examples that inflate token counts unless the loss denominator excludes them.
- Seeding only the main process and trusting it to cover workers. Since PyTorch 1.9 each worker gets a per-worker seed for torch and the
randomand NumPy global RNGs, but an RNG object built inDataset.__init__is still copied identically into every worker. Build or reseed generators inside each worker from the seed thatget_worker_inforeports.
Try it yourself
Closed-book, before checking anything
drop_last True and False, and show that set_epoch(0) and set_epoch(1) give different orders while re-setting the same epoch reproduces them. Save and restore the epoch plus RNG state mid-epoch and continue the identical sequence.Quiz yourself
Answer first, then mark it. Missed ones go to Review.
0 got · 0 missed
1.Ten items, 3 replicas,
shuffle=False,drop_last=False. Which indices does rank 1 yield?Answer. Each rank takes every third index and rank 1 pads with head index 0 to reach length 4.
2.What must be saved to resume a shuffled sampler exactly?Answer
The epoch integer passed to
set_epoch, the dataset and recipe version, and the RNG state feeding shuffle and workers. The sampler object itself holds no serializable position.3.Two loader workers produce identical augmentations. What is the likely cause on a current PyTorch?Answer
An RNG object created in
Dataset.__init__was copied identically into both workers. Build or reseed the generator in each process from the seed thatget_worker_inforeports.4.Why must resume be rejected when the manifest changed?Answer
Shard order, counts or recipe changes remap positions to different documents. Continuing from the old cursor silently duplicates some examples and omits others.
You're done when
Your sampler prints disjoint per-rank rows for both padding policies, and a mid-epoch save and restore continues the identical example sequence.
Only when you can do this without notes.
Leads to
Notes
Resources · 3 for this unit, 10 more in the section
- Distributed Training Guide - Chapter 1 and Related TopicsLambda Labs · required
Trace
01-single-gpu/train_llm.pyend to end with its README (argument parsing, model initialization, checkpoint save of model, optimizer and scheduler, timers and memory statistics), then the related-topics folders on determinism, gradient accumulation, effective batch size and optimized data loading. Produce a state-ownership table and prove identical data order and optimizer trajectory after a controlled interruption. - Machine Learning Engineering Open Book - Training and PyTorch DebuggingStas Bekman · required
Read training/README.md, training/dtype.md, training/reproducibility/README.md and the tiny-model, memory and profiling sections of debug/pytorch.md. Use its commands as a field checklist while diagnosing your own loop.
- PyTorch data loading API - DataLoader, Sampler and multi-process loadingPyTorch · reference
Read Data Loading Order and Sampler, Single- and Multi-process Data Loading with its Randomness subsection, and the DistributedSampler entry for
set_epoch,drop_lastpadding and worker seeding. Use it to define sampler position and worker sharding for the lineage and resume units.
Also in this section
- Machine Learning Systems Volume I - ML Frameworks, Model Training and BenchmarkingML Systems Textbook · primary
Read Model Training (Iron Law of Training Performance, Pipeline Architecture, Identifying Bottlenecks, Pipeline Optimizations), then ML Frameworks (Execution Problem, Differentiation Problem, Anatomy of a Training Step) at https://mlsysbook.ai/vol1/frameworks/frameworks.html and Benchmarking (Training Benchmarks, Benchmarking Best Practices) at https://mlsysbook.ai/vol1/benchmarking/benchmarking.html. Turn the reading into a state-ownership table and a deterministic train-resume trace before the CS336 exercises.
- Ultra-Scale Playbook - First Steps: Training on One GPUHugging Face · required
Read Memory usage in transformers, Activation recomputation and Gradient accumulation, then Appendix A1 on profiling. Derive weight, gradient, optimizer and activation bytes for your tiny model before measuring; the interactive calculator does not show its sequence length or recomputation setting, so compare it with the formulas only after setting both.
- CS336 Assignment 2 (Spring 2026) - Sections 2 and 3Stanford University · required
Complete
benchmarking_script,nsys_profile,mixed_precision_accumulation,benchmarking_mixed_precision,memory_profilingandgradient_checkpointingon model sizes your hardware fits, with your own solutions. Keep timing tables, memory predictions and failure notes; the FlashAttention kernel (Section 4) and the leaderboard (Section 9) are outside this stage. - AI Systems Performance Engineering - Chapters 13 and 14Chris Fregly (O'Reilly) · support
Read Chapter 13 on NVTX markers, the PyTorch profiler, memory and allocator tuning, activation checkpointing and the data input pipeline, and the Chapter 14 sections on graph breaks and recompilation. Use them to explain one profiled step of your own trainer; treat bundled expectations as the author's hardware results.
- Transformer Math 101EleutherAI · support
Use the compute, parameter, optimizer, gradient and activation memory equations as a second derivation of your memory ledger. Check each per-dtype byte count against your own trainer's state.
- Mixed Precision TrainingMicikevicius et al. (ICLR 2018) · support
Read the sections on FP32 master weights, loss scaling and FP32 accumulation. Connect each to a failure your trainer can show: lost small updates, underflowed gradients or overflowed products.
- PyTorch Profiler RecipesPyTorch · support
Use the profiler, memory snapshot and benchmark recipes only when the CS336 handout calls for them. Annotate one complete step and explain every visible gap or synchronization event.
- TensorTonic - Training Arithmetic ProblemsTensorTonic · support
Solve Training FLOP Estimator, Mixed-Precision Training Memory Accountant and Gradient Accumulation Equivalence (free problems in the Language Modeling from Scratch plan) before the CS336 measurements.
- Distributed Training SubsystemRoadmap-Final · support
Start Milestone A with the deterministic sampler, state manifest, event trace and single-process oracle. Keep extending this repository through DT-9.
- PyTorch Autograd mechanics notePyTorch · reference
Read How autograd encodes the history with Saved tensors, Hooks for saved tensors, and Backward Hooks execution (whether each hook fires and in which order). Use it for the autograd graph, saved-tensor and hook-ordering claims.