Unit 5 of 12 · about 5 hours · explain, implement

Autograd graphs, backward scheduling, saved tensors and gradient hooks

Distributed overlap hooks into gradient readiness: a hook that fires late or mutates state delays or corrupts every collective built on top of it. The single-process ordering must be exact first.

You'll be able to

  • Explain how the backward graph is rebuilt each iteration, which tensors are saved for backward, and when each gradient becomes ready.
  • Implement a custom autograd Function with explicit forward and backward and verify it against a numeric gradient.
  • Predict hook firing order and which hook side effects break accumulation or overlap.

Covers

Autograd graph creation, backward scheduling and saved tensorsGradient hooks, readiness order and synchronization side effectsCustom autograd Function with explicit forward and backward
1

Read

In this order, only the parts listed

0 of 2 done

  1. Graph encoding, saved tensors and hook orderPyTorch Autograd mechanics note

    How autograd encodes the history with Saved tensors (save_for_backward, _saved attributes, pack and unpack hooks); Backward Hooks execution (whether each of register_hook, register_post_accumulate_grad_hook, node pre and post hooks fires, and their firing order)

  2. Differentiation problem and backward costMachine Learning Systems Volume I - ML Frameworks, Model Training and Benchmarking

    ML Frameworks, Differentiation Problem: why reverse mode wins for a scalar loss over millions of parameters and the stored-intermediate memory price; the backward-at-twice-forward FLOP ratio is in the Model Training chapter

2

Focus on

  • The graph is rebuilt from scratch every iteration: what you run is what you differentiate. Control flow may change the graph shape each step, so a hook registered on one iteration's node may not exist on the next.
  • Only operations with at least one input requiring grad are recorded, and only leaves with requires_grad=True accumulate .grad. A register_hook fires while its gradient is computed; a register_post_accumulate_grad_hook fires once after accumulation into .grad, and only on leaves.
  • Saved tensors are the forward intermediates backward needs: x.pow(2) saves its input for the gradient. Pack hooks run once at save time while unpack hooks may run many times; mutating their inputs in place is forbidden.
  • In-place operations bump a version counter that is checked when backward unpacks a saved tensor, so an in-place change to a saved value raises. Mutation through .data skips the counter, so that route can still produce a silent wrong gradient.
Common mistakes · 3
  • Misusing a post-accumulate hook. On a non-leaf tensor it errors even after retain_grad(); on a leaf it receives the parameter itself, not the gradient, so read param.grad. Picotron's DataParallelNaive hook all-reduces its argument, so it averages parameters and leaves the gradients unsynchronized.
  • Mutating a gradient inside a register_hook and expecting later hooks to see the original. Hooks compose in order, so each sees the previous hook's output.
  • Doing collective or CUDA-sync side effects inside a hook during overlap experiments. The hook runs inside backward scheduling, so a blocking call serializes the very overlap being measured.
3

Try it yourself

Closed-book, before checking anything

From a blank file, implement a custom autograd Function for with save_for_backward in forward and the chain-rule product in backward, verify it against a finite-difference gradient, and log the firing order of a tensor hook versus a post-accumulate hook over two steps with accumulation.
4

Quiz yourself

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

0 got · 0 missed

  1. 1.Why does y = x.pow(2) keep x alive after forward?Answer

    Backward needs the input to compute . The gradient function saves it at forward time and releases it once backward completes, unless the graph is retained.

  2. 2.A tensor hook and a post-accumulate hook are registered on the same leaf. Which fires first?Answer

    The tensor hook, while that gradient is computed. The post-accumulate hook fires right after the gradient is accumulated into that leaf's .grad, still during backward, not at the end of the whole pass.

  3. 3.Backward is called twice without retain_graph=True. What fails and why?Answer

    The second call finds freed saved tensors. The first backward releases intermediates as it traverses unless retention was requested.

  4. 4.When does a node hook not fire although its tensor received a gradient?Answer

    When the node itself did not execute, for example a tensor passed as inputs to torch.autograd.grad whose grad_fn was skipped. Tensor hooks still fire; node hooks do not.

You're done when

Your custom Function matches finite differences, and you can predict for any hook whether it fires, when, and what it observes.

Only when you can do this without notes.

Leads to

Notes

Resources · 2 for this unit, 11 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.

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

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_profiling and gradient_checkpointing on 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.py end 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.

  • 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_last padding and worker seeding. Use it to define sampler position and worker sharding for the lineage and resume units.