Unit 10 of 12 · about 3 hours · measure
PyTorch profiler traces, memory snapshots and NVTX ranges for a training step
Coarse timers say which phase is slow; traces say why. A labeled step trace plus a snapshot turns hidden synchronization and retained state into visible events.
You'll be able to
- Capture a profiler trace of one full training step with labeled ranges and explain every gap in it.
- Record a CUDA memory snapshot around a peak and attribute the largest allocations to a ledger row.
- Annotate loader, forward, backward and optimizer phases with NVTX ranges that survive into Nsight timelines.
Covers
Read
In this order, only the parts listed
0 of 3 done
- PyTorch profiler recipePyTorch Profiler Recipes
Using profiler to analyze execution time (
activities,record_shapes,record_function, self versus total time); Using profiler to analyze memory consumption (profile_memory); Using tracing functionality (export_chrome_trace); Using profiler to analyze long-running jobs (schedulewith wait, warmup and active pluson_trace_ready) (page read 2026-10-14) - CS336 Assignment 2: traces and snapshotsCS336 Assignment 2 (Spring 2026) - Sections 2 and 3
Section 2.1.4
nsys_profile:nsys profilewith cuda, cudnn, cublas, osrt, nvtx and backtrace flags,torch.cuda.nvtx.rangeannotation and warmup filtering; Section 2.1.6memory_profiling:_record_memory_historywith_dump_snapshotinto the memory visualizer and the forward versus full-step Active timelines - NVTX markers and the allocator viewAI Systems Performance Engineering - Chapters 13 and 14
Chapter 13, NVTX Markers and Profiling Tools; Chapter 13, Profiling PyTorch to Identify Bottlenecks with Using PyTorch Profiler; Chapter 13, Tuning the CUDA Memory Allocator; Chapter 13, Optimizing the Data Input Pipeline
Focus on
- Self time excludes children while total time includes them, so a large
model_inferencetotal with small self time points at the child operator holding the cost. Group by input shape to split one operator name across its call sites. - A trace needs both activities: CPU shows launch order and gaps, CUDA shows kernel execution. A CPU gap with no kernel beneath is launch overhead or a synchronization stall, not compute.
- Snapshots record a few iterations only: start
_record_memory_historyjust before the suspect region and dump right after, then render in the visualizer. Tracing a whole epoch produces an unreadable file. record_functionand NVTX ranges are the labels that make a trace attributable. Wrap each phase so loader waits, forward, backward and optimizer appear as named spans in both the chrome trace and Nsight.
Common mistakes · 3
- Profiling the first step and diagnosing steady state from it. Warmup kernels and allocator prep dominate the first trace; schedule wait plus warmup before the active window.
- Reading CPU-side operator time as device time. Without the CUDA activity the table hides kernel overlap and misattributes device stalls to host operators.
- Leaving memory history recording on for a full run. The buffer grows with every allocation event and perturbs the run it measures; scope it to a few iterations.
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.The table shows
aten::conv2dwith large total time but tiny self time. Where is the cost?AnswerIn a child operator it calls. Self time excludes children, total includes them; descend to the child row holding the self time.
2.A trace shows a long CPU gap with no kernel running beneath it. What does that indicate?Answer
Host-side stall: kernel launch overhead, a synchronization point, or the CPU waiting on data. No device work was even queued in that window.
3.Why does the long-running-jobs API use wait, warmup and active phases?Answer
Wait skips unrepresentative early steps, warmup discards profiler-skewed samples at trace start, and active records the steady window. Continuous tracing would be slow and unreadable.
4.A snapshot shows peak far above the ledger prediction with many small blocks. What is the likely cause?Answer
Allocator fragmentation or retained temporaries, not model state. Check the largest allocations with stack traces and whether freed blocks are reusable.
Practice
- CS336 Assignment 2:
memory_profilingSection 2.1.6 on a model size your GPU fits (the handout uses
xl) at context 128 and 2048: forward versus full-step Active timeline images with stage labels, the 2 by 2 peak-memory table, and the largest-allocation stack-trace analysisA writeup problem with no public tests; checking is your timeline images plus the peak table reconciled against the ledger. Needs one GPU.
You're done when
One labeled trace of your own step has no unexplained gap, and your snapshot attributes its peak to named ledger rows.
Only when you can do this without notes.
Leads to
Notes
Resources · 3 for this unit, 10 more in the section
- 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.
- 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.
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.
- 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.
- 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.
- 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.