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

Profiler annotations and phase timingData wait, transfer, forward, backward and optimizer decompositionCorrectness and learning checks after optimization
1

Read

In this order, only the parts listed

0 of 4 done

  1. PyTorch Profiler recipePyTorch - reliability and performance recipes

    Step 3 execution time with activities, record_function and key_averages self versus total; group_by_input_shape with record_shapes; Step 4 memory with profile_memory; Step 5 chrome trace export; Step 7 schedule, on_trace_ready and prof.step for long jobs

  2. Tuning guide: data flow and zeroingPyTorch - reliability and performance recipes

    Enable asynchronous data loading and augmentation with num_workers and pin_memory; Use parameter.grad = None instead of zeroing; Avoid unnecessary CPU-GPU synchronization

  3. Profiler inside a training loopLearn PyTorch - profiler walkthrough

    Adjust training function to track results with SummaryWriter: train_step with tensorboard_trace_handler, non_blocking transfers, autocast forward, and backward plus step inside the profiled range

    Transfer the annotation pattern into your own compact model. Do not keep the tutorial's EfficientNet code, and do not copy its fp16 autocast loop, which has no GradScaler.

  4. Transformer Training FLOP EstimatorTensorTonic - mixed-precision memory and transformer FLOPs

    Estimate one training step from forward matrix multiplications and a supplied forward attention cost

2

Focus on

  • Annotate before measuring: one range per phase with record_function, plus DataLoader timing 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 gradcheck on 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.
3

Try it yourself

Closed-book, before checking anything

On CPU, profile one annotated step of a small MLP with forward, backward and optimizer ranges. Show the train_step total covers its children, export the chrome trace to a nonempty file, and write one sentence attributing the largest phase.
4

Quiz yourself

Answer first, then mark it. Missed ones go to Review.

0 got · 0 missed

  1. 1.key_averages shows forward total 55 percent but self 13 percent. Where is the rest?Answer

    In child operators such as addmm. Self excludes children while total includes them.

  2. 2.One aten operator appears twice with different shapes. Which flags produce that split?Answer

    record_shapes True with group_by_input_shape True on the averages.

  3. 3.The memory table shows aten::empty with large self memory and convolutions with none. What does that mean?Answer

    empty performs the allocation, so it owns the self bytes. The convolutions allocate through calls beneath them.

  4. 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.

5

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.replace for the atomic-rename step of checkpoint writes: save to a temp file in the same directory, flush and fsync, 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 float16 training underflows and what fp32 primary weights and loss scaling fix.