30 May 2026
How PyTorch Autograd Works
I have written loss.backward() and optimizer.zero_grad() many times without really knowing what happens inside. This week I went through the official PyTorch autograd tutorial and a YouTube explainer, so today I will write down how torch.autograd, PyTorch's automatic differentiation engine, actually works.
In one sentence: the forward pass computes the result and records how it was computed (a graph); the backward pass walks that graph in reverse with the chain rule and sends gradients into the .grad of every leaf tensor.
Two steps of training
- Forward pass:
prediction = model(data) - Backward pass:
loss.backward(), which computes gradients and stores them in each tensor's.grad
Forward pass: what PyTorch computes and stores
The forward pass does two jobs: compute the result, and remember how it got there.
Every tensor has a grad_fn that records the operation that produced it. If you do y = x * 2, then y.grad_fn is MulBackward. These grad_fns link together into the computation graph.
PyTorch also caches the intermediate values that backward will need. This is why you shouldn't modify a tensor in place after the forward pass: the graph holds the original value, and changing it breaks the gradient.
A tensor you create directly, not from another operation, is a leaf tensor. Its grad_fn is None and is_leaf is True. Model weights and biases are leaves.
Backward pass: how gradients flow
After loss.backward(), PyTorch starts from the loss and goes backwards through the graph using the chain rule.
- Gradients are only stored in
.gradfor leaf tensors. Intermediate activations get their gradient, pass it upstream, and then throw it away, unless you callretain_grad(). .gradadds up, it does not overwrite. Everybackward()adds to whatever is already there. That's why each step starts withoptimizer.zero_grad().- After backward the graph is freed by default, so calling
backward()again throws an error unless the first call usedretain_graph=True.
The maths: vector-Jacobian products
For a vector function , the derivative is a Jacobian matrix:
Autograd never builds the full . It computes the vector-Jacobian product for a given vector . If is the gradient of a scalar , then by the chain rule:
When the loss is a scalar, is just 1, which is why loss.backward() needs no argument. You only pass a gradient argument when calling backward on a non-scalar tensor.
The useful attributes and functions
| Attribute | Meaning |
|---|---|
.data | the raw values, no gradient tracking |
.grad | the accumulated gradient, only on leaves |
grad_fn | the operation that produced this tensor |
requires_grad | whether to track gradients for it |
is_leaf | whether it is a leaf |
| Function | What it does |
|---|---|
backward() | runs backpropagation |
zero_grad() | clears gradients |
detach() | cuts a tensor off from the graph |
retain_grad() | keeps the gradient of an intermediate tensor |
torch.no_grad() | no graph and no tracking inside the block, used for inference |
Training only part of a network: detach vs requires_grad=False
Both stop some layers from being updated, but they work differently:
requires_grad=Falseis set on the parameters. Those weights stop storing gradients, but the gradient still flows through that layer to the layers before it.detach()is applied to an activation between layers. It builds a wall: backward stops completely there, and nothing before the wall gets any gradient.
So to freeze the first 5 layers of a 10-layer network, requires_grad=False is the usual choice. It is clear, it doesn't block anything else, and you can unfreeze a layer later by setting it back to True.
zero_grad and gradient accumulation
Each training step is really:
zero_grad():grad = 0backward():grad += new gradientoptimizer.step():w = w - lr * grad
If you forget zero_grad(), the second step uses 2× the real gradient, the third 3×, and so on. PyTorch won't raise any error, so it's a silent bug.
Adding up instead of overwriting does not save memory. It is a design choice that makes gradient accumulation easy. Bigger batches give more stable gradients, but all the samples in a batch need to fit in GPU memory during forward. So you split one big batch into small ones:
I want batch size 128 but my GPU only fits 32. So I run 4 mini-batches, call
backward()on each without clearing, then callstep()andzero_grad()once. Mathematically it's the same as one batch of 128.
Forward mode vs reverse mode
PyTorch uses reverse mode by default, which is everything above. There is also forward mode, which carries the derivative along with the values during the forward computation.
- Reverse mode fits "few outputs, many inputs": one scalar loss and millions of parameters, which is deep learning.
- Forward mode fits "few inputs, many outputs".