Unit 2 of 8 · about 4 hours · explain, measure

Autograd state: views, in-place ops, leaves and accumulation

In-place edits and hidden views are the most common source of corrupt gradients that still run. This unit makes the failure loud and the fix routine.

You'll be able to

  • Classify an op as view, copy or ambiguous, including basic versus advanced indexing, and predict aliasing with data_ptr.
  • Explain leaf versus non-leaf gradient storage, accumulation into .grad, and when zero_grad, detach or retain_grad is required.
  • Trigger, read and repair an in-place version-counter failure without guessing.

Covers

Views, copies, clone, detach and safe in-place operationsrequires_grad, leaves, nonleaves and gradient accumulation
1

Read

In this order, only the parts listed

0 of 4 done

  1. Tensor Views: view ops, indexing and reshape ambiguityPyTorch - Autograd mechanics, serialization and reproducibility

    View definition and data_ptr example; transpose contiguity example; full view-ops list with detach; basic versus advanced indexing note; reshape and contiguous special behavior

  2. Autograd mechanics: saved tensors, requires_grad, grad modes, in-place checksPyTorch - Autograd mechanics, serialization and reproducibility

    Saved tensors; Setting requires_grad; Grad Modes table with no-grad versus inference reuse; In-place operations with autograd and In-place correctness checks

    Skip Multithreaded Autograd, Autograd for Complex Numbers and the division-by-zero section.

  3. Autograd: no_grad, detach and the accumulation demoPyTorch - Learn the Basics

    Disabling Gradient Tracking (no_grad block and detach); Optional Reading: Tensor Gradients and Jacobian Products (accumulation across calls, zeroing)

  4. Autograd loop mechanics: zero_grad and no_grad updatesDeep Learning with PyTorch, 2nd edition - framework foundations

    Book Sections 5.5.1 Computing the gradient automatically and 5.5.5 Autograd nits and switching it off (printed pp. 128-132 and 142-144). Notebook cells with params.grad.zero_(), loss.backward() and the torch.no_grad() parameter update

2

Focus on

  • detach() is a view that shares storage but cuts grad history. clone() is absent from the view-ops list, so it copies the data. Test both claims with data_ptr and requires_grad.
  • Only leaves with requires_grad=True accumulate into .grad, and every backward() adds. Non-leaves need retain_grad before the backward that consumes them.
  • Inference-mode tensors cannot re-enter grad-mode computation; no-grad tensors can. Use inference mode only for pure evaluation paths.
  • An in-place bump of a saved tensor raises a version-counter error at backward. Clone before the saving op or move the mutation earlier; do not catch and ignore.
Common mistakes · 3
  • Treating detach() as a copy. It shares storage, so an in-place edit through either side is visible to both.
  • Reading .grad on a non-leaf. It stays None unless retain_grad() was called; only leaves accumulate.
  • Updating a leaf that requires grad in place outside torch.no_grad(). PyTorch refuses at once ("a leaf Variable that requires grad is being used in an in-place operation"); manual parameter updates belong under no_grad.
3

Try it yourself

Closed-book, before checking anything

Closed-book, write x = torch.randn(4, requires_grad=True) and y = (x ** 2).sum(). Show that x.add_(1) fails at once because x is a leaf that requires grad. Then do the same update under torch.no_grad() and read the version-counter error that y.backward() raises, because pow saved x. Repair it by computing y from z = x.clone(), and check that x.grad equals 2 times the value x had during the forward.
4

Quiz yourself

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

0 got · 0 missed

  1. 1.b = t.view(2, 8); b[0][0] = 3.14. What is t[0][0]?Answer

    3.14. The view shares storage, so the write is visible through the base.

  2. 2.Is t.reshape(2, 8) guaranteed to behave the same way?Answer

    No. reshape may return a view or a copy, so never rely on aliasing through it.

  3. 3.You call out.backward(torch.ones_like(out), retain_graph=True) twice without zeroing. How does inp.grad after the second call relate to the first?Answer

    It is twice the first. backward() adds into .grad; the autogradqs Jacobian-product section shows this doubling, and zeroing inp.grad resets it.

  4. 4.What is the practical difference between no-grad and inference mode for tensors you keep?Answer

    Both skip graph recording, but inference-mode tensors cannot be used in later grad-mode computation while no-grad tensors can.

You're done when

You classify ten ops as view, copy or ambiguous without the list, and your version-counter script fails before the fix and passes after.

Only when you can do this without notes.

Leads to

Notes

Resources · 3 for this unit, 4 more in the section
  • PyTorch - Learn the BasicsPyTorch · primary

    Complete Tensors, Datasets and DataLoaders, Transforms, Build Model, Autograd, Optimization, and Save and Load Model. Rebuild each essential example in a small src package instead of retaining a tutorial notebook.

  • PyTorch - Autograd mechanics, serialization and reproducibilityPyTorch · required

    Read Autograd mechanics, Serialization semantics and Reproducibility. Test leaf behavior, saved tensors, grad modes, state dictionaries and the exact tolerance promised by one interrupted and resumed run.

  • Deep Learning with PyTorch, 2nd edition - framework foundationsHoward Huang, Luca Antiga, Eli Stevens and Thomas Viehmann (Manning) · support

    Read Sections 3.8-3.9 and 5.5 when tensor storage, strides or autograd need a second explanation, with the Chapter 3 and 5 companion notebooks for runnable cells. Inspect the Chapter 4 and 7 code only for a diagnosed data-representation or loading gap.

Also in this section

  • Learn PyTorch - selected framework exercisesDaniel Bourke · required

    Complete exercise 00, tasks 1-5 in 01, tasks 1-7 in 02, tasks 5-13 in 03, tasks 1-3 in 05, and exercises 1-2 in 07. Recreate solutions independently and verify behavior against current official docs.

  • NeetCode ML - PyTorch closing drillsNeetCode · optional

    After the module gate, solve Pytorch Basics, Layer Normalization, Batch Normalization and RMS Normalization cold. Explain shapes, state and train-evaluation behavior aloud. These do not replace the package and resume test.

  • PyTorch Automatic Mixed Precision recipe - Saving/ResumingPyTorch · reference

    Read the Saving/Resuming section: save scaler.state_dict() with the model and optimizer state, at the start of an iteration or after scaler.update(), and how to resume with or without AMP.

  • Hands-On Machine Learning with Scikit-Learn and PyTorchAurelien Geron (O'Reilly, 2025) · support

    Read Chapter 10, Implementing Mini-Batch Gradient Descent Using DataLoaders and Model Evaluation, for the train and evaluate loops and how batch metrics must be aggregated.