Unit 4 of 12 · about 4 hours · explain, implement
Who owns parameters, buffers, gradients, optimizer, scheduler, scaler, RNG and loader state
Every later sharding and checkpoint decision is a question of who owns which tensor and when. An ownership table turns silent state bugs into checkable rows.
You'll be able to
- Explain which object owns parameters, buffers, gradients, optimizer state, scheduler, scaler, RNG and loader state during one step.
- Build a state-ownership table for your trainer and show the update each entry receives per step.
- Predict which missing entry diverges a resume and which leaves memory allocated but unused.
Covers
Read
In this order, only the parts listed
0 of 3 done
- Anatomy of a training stepMachine Learning Systems Volume I - ML Frameworks, Model Training and Benchmarking
ML Frameworks, Anatomy of a Training Step: the seven-statement two-layer MLP traced through forward dispatch,
loss.backwardtraversal with.gradaccumulation and freed saved tensors, and the optimizer update - Every state object in one fileDistributed Training Guide - Chapter 1 and Related Topics
train_llm.pymodel init withtorch.compile,DataLoaderwithnum_workers=1andprefetch_factor=2,AdamW(fused=True),CosineAnnealingLR, thezero_grad(set_to_none=True)update block, and the checkpoint block saving model, optimizer and scheduler state dicts - RNG ownership and deterministic flagsMachine Learning Engineering Open Book - Training and PyTorch Debugging
enforce_reproducibility: torch, CUDA, NumPy and Python RNG streams seeded together,CUBLAS_WORKSPACE_CONFIGbefore CUDA init, andtorch.use_deterministic_algorithms(True)withcudnn.benchmark=False; check the round trip oftorch.get_rng_stateandtorch.set_rng_stateyourself, since this note does not cover it
Focus on
- Parameters and buffers live in the module; gradients accumulate into
.gradon leaves; optimizer state (momentum, variance, plus an FP32 master copy when parameters are stored in low precision) lives in the optimizer; scheduler step count lives in the scheduler. Each has exactly one writer per step. - The scaler owns the scale factor and the skip-or-step decision; the RNG streams owned by torch, CUDA, NumPy and Python decide dropout, init and shuffle draws; the loader owns worker processes, prefetch queues and the sampler cursor.
- Buffers such as BatchNorm running statistics update by moving average, not by gradient. Forgetting them in a checkpoint corrupts evaluation while training loss looks fine.
zero_grad()sets.gradto None by default (set_to_none=True) instead of filling zeros. Code that adds into.gradbefore the next backward then raises on None rather than reading zeros.
Common mistakes · 3
- Constructing the optimizer before the parameters it should track, or adding new parameters later without extending the optimizer. Those parameters train with no update while the loss still falls.
- Saving the model but not the scaler. The resumed run restarts from the initial scale, so it repeats the early overflow skips and its updates differ from the uninterrupted run.
- Moving the model to a device after the optimizer has stepped. The parameters move in place, but the existing optimizer state stays on the first device and the next step raises a device-mismatch error. Move the model first, then build the optimizer.
Try it yourself
Closed-book, before checking anything
Quiz yourself
Answer first, then mark it. Missed ones go to Review.
0 got · 0 missed
1.Which objects must be saved so an AdamW plus cosine-schedule run resumes its exact trajectory?Answer
Model, optimizer, scheduler and scaler state dicts plus RNG states and the data position record. Weights alone restart the schedule and the scale history at the wrong point.
2.Why do BatchNorm running statistics need checkpointing if they receive no gradients?Answer
They are updated by forward moving averages and used at evaluation. Restoring weights without them shifts every normalized activation at test time.
3.What does
zero_grad(set_to_none=True)change about.gradownership?AnswerIt sets
.gradto None instead of zeros, and it is the default. The next backward allocates a fresh gradient; code that adds into.gradin between fails on None, and code that reads it sees None, not zeros.4.A resumed run diverges although model and optimizer were restored. Name two other owners to check first.Answer
Scheduler position and RNG plus loader position. A shifted schedule or a different example and dropout sequence changes every later update.
Practice
- 01-single-gpu: state-ownership table
Walk
train_llm.pytop to bottom and list every stateful object with its owner, dtype and per-step writer; then delete one saved entry at a time from a resumed run and record which deletion diverges the trajectoryKeep the table; later sharding units add an owner column per rank.
You're done when
Your table names every stateful object in your loop with its writer, and you can predict the symptom of deleting any single row.
Only when you can do this without notes.
Leads to
Notes
Resources · 3 for this unit, 10 more in the 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.
- 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.
Also in this section
- 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 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. - 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.