Autograd and detach
Quick answer
Autograd records differentiable operations involving tensors that require gradients, then applies the chain rule in reverse. Backward accumulates gradients into leaf tensors; detach breaks the recorded dependency without necessarily copying storage. Static examples tested locally with PyTorch 2.10.0+cpu; ByteMind execution is unverified.
Differentiate a polynomial
import torchx=torch.tensor(3.,requires_grad=True)loss=x*x+2*xloss.backward()print(x.grad.item())Expected output: 8.0. The derivative is 2*x+2.
How it works
For scalar L, L.backward() computes derivatives with respect to participating leaves. For a vector output, pass an upstream gradient or reduce to a scalar, depending on the objective. Gradients accumulate by default, so clear them before the next optimization step. torch.autograd.grad returns requested gradients without filling leaf .grad in ordinary use. detach() returns a graph-disconnected tensor sharing storage; clone().detach() is useful when a separate copy is needed. no_grad disables reverse-mode recording for a block, with exceptions such as factory functions accepting requires_grad. inference_mode also disables extra autograd bookkeeping and creates more restricted tensors; avoid feeding inference tensors into computations that require saved values for backward. Neither mode changes dropout or batch normalization behavior.
Compare graph modes
import torchx=torch.tensor(2.,requires_grad=True)y=x*xwith torch.no_grad(): z=x*xwith torch.inference_mode(): q=x*xprint(y.requires_grad,y.detach().requires_grad,z.requires_grad,q.requires_grad,q.is_inference())Expected output: True False False False True. All three alternatives avoid recording the dependency, but only q is an inference tensor.
Common mistakes
Calling backward twice on the same graph normally fails because saved intermediates are released. Recompute the forward pass. Do not use detach to hide shape or gradient bugs; it may remove an intended learning signal. Do not mutate a detached alias of a tensor needed by backward.
Practice and next steps
Derive the gradient of a sum of squared errors, then compare with autograd. Next learn how parameters become discoverable by optimizers.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Autograd and detach — knowledge check
Apply autograd and detach to small examples and debugging scenarios.
What is d(x²+2x)/dx at x=3?
What happens to a leaf gradient on a second fresh backward without clearing?
Does detach guarantee independent storage?
Which mode also changes dropout behavior?
How to differentiate a vector output against a weighted sum?