Unit 9 of 9 · about 5 hours · measure
Profiling training phases and verifying optimizations
Optimization without a phase breakdown optimizes the wrong line. The profile decides whether the step is data-starved, launch-bound, compute-bound or sync-bound, and the revalidation proves the faster run still learns.
You'll be able to
- Annotate a training step and attribute time to data wait, transfer, forward, backward and optimizer phases.
- Read self versus total time and memory, and split shared operators by input shape.
- Revalidate learning and resume behavior after any optimization, and explain one model-versus-measured discrepancy.
Covers
Read
In this order, only the parts listed
0 of 4 done
- PyTorch Profiler recipePyTorch - reliability and performance recipes
Step 3 execution time with activities,
record_functionandkey_averagesselfversustotal;group_by_input_shapewithrecord_shapes; Step 4 memory withprofile_memory; Step 5 chrome trace export; Step 7schedule,on_trace_readyandprof.stepfor long jobs - Tuning guide: data flow and zeroingPyTorch - reliability and performance recipes
Enable asynchronous data loading and augmentation with
num_workersandpin_memory; Useparameter.grad = Noneinstead of zeroing; Avoid unnecessary CPU-GPU synchronization - Profiler inside a training loopLearn PyTorch - profiler walkthrough
Adjust training function to track results with
SummaryWriter:train_stepwithtensorboard_trace_handler,non_blockingtransfers,autocastforward, andbackwardplusstepinside the profiled rangeTransfer the annotation pattern into your own compact model. Do not keep the tutorial's EfficientNet code, and do not copy its
fp16autocastloop, which has noGradScaler. - Transformer Training FLOP EstimatorTensorTonic - mixed-precision memory and transformer FLOPs
Estimate one training step from forward matrix multiplications and a supplied forward attention cost
Focus on
- Annotate before measuring: one range per phase with
record_function, plusDataLoadertiming outside the step, so data wait cannot hide inside forward. - Self time excludes children and total includes them. A big total with small self points at the children, not at the named line.
- Predict first, then profile. Write the expected slowest phase and the expected memory peak before running, and explain the residual in writing.
- Every optimization revalidates learning: loss, gradients, controls and resume. A faster run that learns differently is a defect, not a win.
Common mistakes · 3
- Profiling with stacks, anomaly detection or
gradcheckon and calling it a measurement. Debug tooling distorts the run; measure the clean configuration. - Tuning the fastest phase. Rank phases first; a 2x win on 5 percent of the step is noise against an unexamined data wait.
- Skipping learning checks after AMP, compile or fusion. Numerics move silently; rerun controls and resume checks before keeping the change.
Try it yourself
Closed-book, before checking anything
train_step total covers its children, export the chrome trace to a nonempty file, and write one sentence attributing the largest phase.Quiz yourself
Answer first, then mark it. Missed ones go to Review.
0 got · 0 missed
1.
key_averagesshows forwardtotal55 percent butself13 percent. Where is the rest?AnswerIn child operators such as
addmm.Selfexcludes children whiletotalincludes them.2.One aten operator appears twice with different shapes. Which flags produce that split?Answer
record_shapesTruewithgroup_by_input_shapeTrueon the averages.3.The memory table shows
aten::emptywith largeselfmemory and convolutions with none. What does that mean?Answeremptyperforms the allocation, so it owns theselfbytes. The convolutions allocate through calls beneath them.4.After AMP, compile and a larger batch, loss matches but step time barely moves. Name the next two checks.Answer
Read which phase dominates; the bottleneck may be data wait or sync, not math. Then confirm debug tooling is off before further tuning.
Practice
- TensorTonic: Transformer Training FLOP Estimator
Estimate one training step from forward matrix multiplications and a supplied forward attention cost
Solve it, then reconcile your estimate with the compact model's profiled step and write down every included and excluded term.
You're done when
Your annotated profile attributes every phase, your prediction names the slowest one before the run, and one optimization ships with passing learning and resume checks.
Only when you can do this without notes.
Leads to
Notes
Resources · 3 for this unit, 6 more in the section
- PyTorch - reliability and performance recipesPyTorch · primary
Use the Profiler, Automatic Mixed Precision, model loading and Benchmark recipes, then the Performance Tuning Guide. Apply each to one compact model from an earlier section and keep a CPU fallback when CUDA is unavailable.
- TensorTonic - mixed-precision memory and transformer FLOPsTensorTonic · support
Solve only Mixed-Precision Training Memory Accountant and Transformer Training FLOP Estimator. Reconcile both with the compact model's profiler and document every included and excluded term.
- Learn PyTorch - profiler walkthroughDaniel Bourke · optional
Use notebook 10 only if the official profiler route remains unclear. Transfer the relevant annotations into the compact model instead of keeping the tutorial code.
Also in this section
- PyTorch - compiler troubleshootingPyTorch · required
Read graph breaks, guards, recompilations and logging. Compile one stable fragment, intentionally trigger a graph break or recompilation, inspect it, and compare eager and compiled outputs and gradients.
- PyTorch - checkpointing, numerical accuracy and CUDA semanticsPyTorch · required
Use the official user-guide entries for torch.utils.checkpoint, numerical accuracy, CUDA semantics, reproducibility and serialization. Predict memory categories before measuring and define resume equivalence before running.
- Deep Learning Training DebuggerRoadmap-Final · reference
Use the failure-injection, measurement and evidence rules as the deeper standard. The full Tier 2 project is a later route and is not added to this stage milestone.
- TrenTorch - precision, checkpointing and resumeTrenTorch · support
Solve Loss Scaling, FP16/BF16 Representable Range, Gradient Checkpointing and Resume-from-checkpoint in NumPy, then reproduce each behavior with the PyTorch API in the compact model.
- Python os - `os.replace`Python Software Foundation · reference
Read
os.replacefor the atomic-rename step of checkpoint writes: save to a temp file in the same directory,flushandfsync, then replace the final name. - Hands-On Machine Learning with Scikit-Learn and PyTorchAurelien Geron (O'Reilly, 2025) · support
Read Appendix B, Reduced Precision Models and Mixed-Precision Training, for why
float16training underflows and whatfp32primary weights and loss scaling fix.