7 routes42 sections324 units

Unit 8.1 · about 3 h

221 / 324

Eager execution, autograd nodes and saved tensors

Every memory number and profiler row later in this section is a consequence of this graph. If you cannot name the saved tensors, you cannot explain what checkpointing or the profiler is measuring.

  • explain

You can now

  • Trace one eager operation from the Python call to its backward Function node and name each node on the path.
  • Explain which forward tensors autograd must keep for backward, how long they live, and what frees them.
  • Predict whether an in-place edit raises at the edit or at backward, and state what the version numbers mean.

Covers

  • Eager execution, dispatch and autograd nodes
  • Saved tensors and their lifetimes

Study, in this order

3 steps

  1. How autograd encodes the history
    PyTorch - checkpointing, numerical accuracy and CUDA semantics

    How autograd encodes the history: Function graph rebuilt each iteration, grad_fn entry points, what-you-run-is-what-you-differentiate

  2. Saved tensors
    PyTorch - checkpointing, numerical accuracy and CUDA semantics

    Saved tensors: the x-squared example, save_for_backward, _saved attribute inspection, the pow identity-True and exp identity-False examples with shared storage

  3. In-place checks and saved-tensor hooks
    PyTorch - checkpointing, numerical accuracy and CUDA semantics

    In-place operations with autograd and In-place correctness checks: version counters and the no-error-means-correct-gradients guarantee

    Depth · Skim Hooks for saved tensors after the pack_hook and unpack_hook contract. Skip the multithreading and complex-number sections.

Focus on

  • The graph is rebuilt from scratch every iteration. A grad_fn object from a previous iteration is stale and must never be reused.
  • Forward keeps only what backward needs. For \(x\) squared it keeps \(x\); the rest of the forward temporaries are free to go.
  • Object identity of a saved tensor is an implementation detail. The pow case returns the same object and the exp case returns a different object, but both share storage and compare equal.
  • The first backward frees saved tensors. A second backward without retain_graph fails because the saved values are gone, not because the graph forgot the formula.

Reproduce closed-book

Closed-book on CPU: build y = (x @ W + b).relu().sum() with a \(2 \times 3\) \(x\), a \(3 \times 4\) \(W\) and a bias of 4, all requiring grad. Walk y.grad_fn through next_functions and write down SumBackward0, ReluBackward0, AddBackward0, MmBackward0 and AccumulateGrad in order. Then show (x ** 2).grad_fn._saved_self is x gives True while its storage is shared.

Traps

  • Reading _saved_self is as identity proof. Packing may return a new object sharing storage, so test storage and equality, never identity.
  • Editing a leaf with requires_grad errors at the edit, but editing a saved non-leaf passes and fails at backward with a version error. The two messages describe different checks.
  • Assuming no-grad regions keep no state and therefore cost nothing. They keep no graph, but the forward compute and its live outputs still cost time and memory.

Practice

The section mini-project covers this: saved-tensor accounting and autograd-state instrumentation for the compact model.

Self-test

  1. For y = (x @ W + b).relu().sum(), name the backward node types from y down to the leaves.

  2. x.pow(2).grad_fn._saved_self is x is True, but x.exp().grad_fn._saved_result is y is False. Do both saved tensors share storage with the named tensor?

  3. The first loss.backward() succeeds and the second raises about saved intermediate values. What was freed, and what flag keeps it?

  4. Backward fails with expected version 0 but found version 1 on a saved tensor. What do the two numbers mean?

Completion criterion

Stop when

You complete the reproduce walk without notes, and can predict for any small graph which tensors survive until backward and which edit raises where.

Mark passed, then open 8.2 Only mark this when you can do it without notes.

Leads to

Comes after

Resources for this unit

Also in this section

  • PyTorch - reliability and performance recipes
    PyTorchprimarycourse
    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.
  • PyTorch - compiler troubleshooting
    PyTorchrequiredreference
    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.
  • Deep Learning Training Debugger
    Roadmap-Finalreferenceassessment
    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.
  • TensorTonic - mixed-precision memory and transformer FLOPs
    TensorTonicsupportpractice
    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 walkthrough
    Daniel Bourkeoptionalimplementation
    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.
  • TrenTorch - precision, checkpointing and resume
    TrenTorchsupportpractice
    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 Foundationreferencereference
    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 PyTorch
    Aurelien Geron (O'Reilly, 2025)supporttheory
    Read Appendix B, Reduced Precision Models and Mixed-Precision Training, for why float16 training underflows and what fp32 primary weights and loss scaling fix.

Quick find

Search Michi

Type to search every route, section, unit, topic and resource.

Enter opens the first result Esc closes

Reference

Keyboard shortcuts

n
Continue to the first unit not passed
j / k
Next / previous unit
1 2 3
Toggle learned, practised, passed
/
Open search
?
Show this help
Esc
Close open panels