Unit 9 of 12 · about 4 hours · measure
Step timelines and repeated-trial benchmark hygiene
Without phase timers every optimization is a guess: input stalls look like slow kernels and allocator warmup looks like a regression. Timelines make the bottleneck state its name.
You'll be able to
- Instrument one step into data, transfer, forward, backward, optimizer and checkpoint phases with honest synchronization.
- Run repeated trials with warmup and report mean, spread and exact settings instead of a best step.
- Attribute a slow step to its phase from timer evidence rather than from intuition.
Covers
Read
In this order, only the parts listed
0 of 3 done
- CS336 Assignment 2: benchmarking methodCS336 Assignment 2 (Spring 2026) - Sections 2 and 3
Section 2.1.3
benchmarking_script:benchmark.pywith selectable forward-only, forward plus backward and plusoptimizer.stepmodes,torch.cuda.synchronizearoundtimeit.default_timer, 5 warmup plus 10 measured steps with mean and standard deviation; Section 2.1.4nsys_profilefor the annotated trace - Per-phase timers and memory statisticsDistributed Training Guide - Chapter 1 and Related Topics
LocalTimerwithdata,forward,backwardandupdatephases usingsynchronizeplustime.time,get_mem_statswith current and peak allocation and reservation, and the per-log_freqlogging line reporting loss, tokens per second and all four timers - What a benchmark must hold fixedMachine Learning Systems Volume I - ML Frameworks, Model Training and Benchmarking
Benchmarking, Training Benchmarks: time to fixed quality rather than raw step speed, the full run envelope, and the distribution of accepted runs rather than a single best run; Benchmarking Best Practices: the methodology limits that decide whether a benchmark carries over to deployment
Focus on
- CUDA launches are asynchronous, so a timer without
torch.cuda.synchronizemeasures launch time, not work time.LocalTimersynchronizes around every phase boundary and the CS336 script around every timed step. - The first steps include allocator prep, compilation and cache fill, so they run slower and allocate differently. The CS336 5-warmup plus 10-measured pattern with 0 versus 1 to 2 warmup comparison exists to show this effect, not to hide it.
- Report mean and standard deviation over the measured steps with model size, batch, sequence, precision, hardware, backend and commit. A single fast step is a sample of one from an unknown distribution.
- Keep data, transfer, forward, backward, optimizer and checkpoint phases separate. The guide logs show all four timers plus tokens per second on every line so a slow step names its phase immediately.
Common mistakes · 3
- Timing the first step and calling it the step time. Allocator and compilation effects make it unrepresentative in both directions.
- Averaging across a checkpoint step. Checkpoint I/O belongs to its own phase; folding it into the mean hides both the steady step and the save cost.
- Comparing steps across machines or commits without restating settings. Interconnect, allocator state and kernel versions move numbers more than most optimizations.
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.Forward time measures near zero while backward looks normal. What is wrong with the timer?Answer
Missing synchronization around the forward phase. The timer recorded kernel launch and returned while the GPU still worked; backward synchronized implicitly and absorbed the forward time.
2.Why do the CS336 instructions ask for runs with 0 and with 1 to 2 warmup steps?Answer
To exhibit the warmup effect directly. The unwarmed mean mixes compilation and allocator prep with steady state; the comparison quantifies the bias warmup removes.
3.Tokens per second rises but time to fixed quality does not. Which benchmark view disagrees and why?Answer
The training-benchmark view: time to quality counts convergence per token, while tokens per second counts throughput. A faster step that harms sample efficiency can lose on quality time.
4.One step in ten is far slower and the slow phase is data. What do you check first?Answer
Loader workers, prefetch depth and storage versus local disk, not kernels. Periodic data-phase spikes with idle compute point at input starvation.
Practice
- CS336 Assignment 2:
benchmarking_scriptSection 2.1.3 on the Table 1 sizes your hardware fits: all three timer modes with mean and standard deviation tables, plus the 0 versus 1 to 2 warmup comparison with its explanation
A writeup problem with no public tests; checking is your timing tables plus the annotated explanation. Needs one GPU; CPU timers cannot stand in for device phases.
You're done when
Your phase table attributes any slow step to a named phase, and a peer can rerun your exact settings from the report alone.
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.
- 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. - 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.
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.
- 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.
- 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.