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 whenzero_grad,detachorretain_gradis required. - Trigger, read and repair an in-place version-counter failure without guessing.
Covers
Read
In this order, only the parts listed
0 of 4 done
- Tensor Views: view ops, indexing and reshape ambiguityPyTorch - Autograd mechanics, serialization and reproducibility
View definition and
data_ptrexample; transpose contiguity example; full view-ops list with detach; basic versus advanced indexing note; reshape and contiguous special behavior - Autograd mechanics: saved tensors,
requires_grad, grad modes, in-place checksPyTorch - Autograd mechanics, serialization and reproducibilitySaved tensors; Setting
requires_grad; Grad Modes table with no-grad versus inference reuse; In-place operations with autograd and In-place correctness checksSkip Multithreaded Autograd, Autograd for Complex Numbers and the division-by-zero section.
- Autograd:
no_grad,detachand the accumulation demoPyTorch - Learn the BasicsDisabling Gradient Tracking (
no_gradblock anddetach); Optional Reading: Tensor Gradients and Jacobian Products (accumulation across calls, zeroing) - Autograd loop mechanics:
zero_gradandno_gradupdatesDeep Learning with PyTorch, 2nd edition - framework foundationsBook 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 thetorch.no_grad()parameter update
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 withdata_ptrandrequires_grad.- Only leaves with
requires_grad=Trueaccumulate into.grad, and everybackward()adds. Non-leaves needretain_gradbefore 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
.gradon a non-leaf. It staysNoneunlessretain_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 underno_grad.
Try it yourself
Closed-book, before checking anything
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.Quiz yourself
Answer first, then mark it. Missed ones go to Review.
0 got · 0 missed
1.
b = t.view(2, 8);b[0][0] = 3.14. What ist[0][0]?Answer3.14. The view shares storage, so the write is visible through the base.
2.Is
t.reshape(2, 8)guaranteed to behave the same way?AnswerNo. reshape may return a view or a copy, so never rely on aliasing through it.
3.You call
out.backward(torch.ones_like(out), retain_graph=True)twice without zeroing. How doesinp.gradafter the second call relate to the first?AnswerIt is twice the first.
backward()adds into.grad; the autogradqs Jacobian-product section shows this doubling, and zeroinginp.gradresets it.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
- Modules, parameters, buffers and initializationParameters are the leaves you must stop detaching by accident.
- Backward, `zero_grad`, `gradcheck` and evaluation modesTurn accumulation and zeroing into a correct loop.
- Aliasing, mutation and module ownershipRebuild aliasing contracts inside your own engine.
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 afterscaler.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.