Unit 7 of 7 · about 3 hours · explain, measure

Aliasing, mutation and module ownership

Views alias memory, in-place ops rewrite history, and detach cuts the graph without warning. Ownership rules decide which tensor the optimizer may touch and which state merely travels along.

You'll be able to

  • Predict when an in-place or view mutation corrupts backward, and route around it with out-of-place ops or no-grad updates.
  • Explain detach as a provenance cut, and diagnose detached-path and forgotten-zeroing gradient bugs from their signatures.
  • State module ownership at mechanism level: recursive parameter collection, parameters versus buffers, and who may mutate what.

Covers

Aliasing, mutation and detached-path hazardsParameter, buffer and module ownership at mechanism level
1

Read

In this order, only the parts listed

0 of 3 done

  1. In-place hazards and the version counterPyTorch Autograd mechanics - in-place operations

    In-place operations with autograd: in-place is discouraged because it rewrites the graph instead of allocating new nodes; In-place correctness checks: every tensor keeps a version counter, and accessing a saved tensor whose version changed raises an error

  2. Detach and the training loop contractD2L - tensors, autograd, MLP and backpropagation

    Section 2.5.3 Detaching Computation: u = y.detach() with z = u * x gives gradient , not , while the graph to y persists; Section 2.5.1: the gradient buffer accumulates, so x.grad.zero_() resets it between objectives

  3. Parameters versus buffers`torch.nn.Module` - parameters, buffers and state

    Parameters and buffers documentation: modules collect parameters recursively for the optimizer; register_buffer holds persistent non-parameter tensors that are saved alongside parameters without getting gradients

2

Focus on

  • Every tensor carries a version counter, bumped by each in-place op. Backward saved the counter value too, so mutating a needed value raises an error instead of computing a wrong gradient. Treat the error as a correct alarm, not an obstacle.
  • In-place graph rewrites are only safe for updates outside tracking: optimizer steps mutate parameters under no-grad. Anything inside the tracked graph should allocate new nodes.
  • Detach cuts provenance silently: gradients stop at the cut and read as correct-looking smaller values ( instead of ). A forgotten zero_() is the mirror bug: values look plausible but sum two objectives.
  • Ownership: a module owns its parameters recursively (TensorTonic parameter collection below), the optimizer mutates exactly those, and buffers carry persistent non-differentiated state such as running statistics.
Common mistakes · 3
  • Silencing the version-counter error by mutating through .data. Changes made through .data skip the version counter, so backward runs without an error on the mutated value and returns a wrong gradient. Fix the order of operations or clone before the mutation instead.
  • Detaching a hidden activation on the path to the loss. Everything before the cut gets no gradient (.grad stays None) with no error, while later layers still train. Detaching the loss itself does fail loudly; the silent case is the middle of the network.
  • Registering persistent state as a Parameter. It then gets gradients and optimizer updates it should never have; buffers travel in state without differentiation.
3

Try it yourself

Closed-book, before checking anything

Closed-book, write the two canonical failures. First, h = x.sigmoid() saves its output; mutate h in place with h.mul_(2) before backward and read the version-counter error. Second, with y = x * x and u = y.detach(), show that z = x * u gives , not . Then state the parameter-versus-buffer rule for a layer with a running counter.
4

Quiz yourself

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

0 got · 0 missed

  1. 1.You modify a saved activation in place, then call backward. What happens?Answer

    PyTorch raises a version-counter error when backward accesses the modified saved tensor. The counter recorded at save time no longer matches.

  2. 2.For z = x * u with u = y.detach() and y = x * x, what is ?Answer

    , i.e. in value. Provenance through is cut, so the path contributes nothing and the total is not .

  3. 3.Two backward calls with no zero_(): what is in .grad, and when is that what you want?Answer

    The sum of both gradients. Wanted when optimizing a sum of objectives; a bug when the calls were meant to be separate batch updates.

  4. 4.A layer keeps a running event counter alongside its weights. Parameter or buffer?Answer

    Buffer. It must persist and save with the module but never receive gradients or optimizer updates.

5

Practice

You're done when

You can predict the version error, the detach signature and the accumulation signature on sight, and your module separates parameters from buffers with a stated mutation rule for each.

Only when you can do this without notes.

Leads to

Notes

Resources · 3 for this unit, 10 more in the section
  • D2L - tensors, autograd, MLP and backpropagationD2L authors · required

    Use chapter_preliminaries ndarray and autograd, then MLP, backpropagation, and numerical stability and initialization. Recreate scalar operations, affine maps, activation, reduction, stable cross-entropy, topological backward and unbroadcast in a blank file.

  • PyTorch Autograd mechanics - in-place operationsPyTorch · reference

    Read In-place operations with autograd (why in-place rewrites the graph and is discouraged) and In-place correctness checks (the version counter and the error on accessing a modified saved tensor).

  • `torch.nn.Module` - parameters, buffers and statePyTorch · reference

    Read the parameters and buffers documentation: modules collect parameters recursively for the optimizer, while register_buffer holds persistent non-parameter tensors saved alongside them.

Also in this section

  • Understanding Deep Learning - Chapters 3 to 7Simon J. D. Prince · primary

    Read Chapters 3-7, emphasizing Chapter 5 for likelihood-derived losses and Chapter 7 for backpropagation and initialization. Use notebooks 3.1, 4.1, 5.1, 6.1 and 7.1 only as equation and plot companions.

  • TensorTonic - Build Micrograd from ScratchTensorTonic · required

    Use the 25-problem Micrograd study plan in order for derivatives, gradient checks, value graphs, reverse mode, accumulation, operators, modules, losses and training. Preserve local tests as the evidence instead of a platform score.

  • Deep-ML candidate - autograd and loss problemsDeep-ML · optional

    After the five-sample platform check passes, use at most one of 26 Basic Autograd Operations, 997 Manual Cross-Entropy Backprop or 1227 Stable Softmax as a changed-prompt drill.

  • CS231n Linear Classification - Softmax classifier and numeric stabilityStanford CS231n · reference

    Read the Softmax classifier section for the cross-entropy form , then the Practical issues: Numeric stability part for the max-subtraction code f -= np.max(f).

  • CS231n Neural Networks 3 - Gradient checksStanford CS231n · reference

    Read the Gradient Checks section only: centered formula with error, relative error with thresholds, double precision, step size near 1e-5, kinks, few datapoints, burn-in, regularization and dropout discipline, and checking a few dimensions per parameter.

  • PyTorch Broadcasting semanticsPyTorch · reference

    Read General semantics for the trailing-dimension rules, prepend-1 alignment and max-size result, with the (5, 1, 4, 1) plus (3, 1, 1) examples; read In-place semantics for why an in-place tensor may not change shape.

  • `torch.autograd.gradcheck` API and tolerancesPyTorch · reference

    Read the gradcheck signature defaults (eps 1e-6, atol 1e-5, rtol 1e-3) and the note that inputs with overlapping memory, such as expand outputs, will likely fail the check.

  • `torch.nn.functional.cross_entropy` - `reduction` and `ignore_index`PyTorch · reference

    Read the ignore_index and reduction parameters: ignored targets contribute no gradient, and mean reduction averages over the non-ignored targets only.

  • PyTorch Tensor ViewsPyTorch · reference

    Read the view and storage sharing example (data_ptr, mutating the view changes the base), the transpose non-contiguous example, the full view-ops list, and the special notes: reshape may copy, contiguous copies only when needed, basic indexing returns views while advanced indexing copies.

  • `torch.Tensor.stride` - stride and storage offsetPyTorch · reference

    Read the stride definition: strides are per-dimension element steps, and with storage_offset they locate every element. Combine with the Tensor Views page for transposed and expanded layouts.