Skip to content
King Jin

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 .grad for leaf tensors. Intermediate activations get their gradient, pass it upstream, and then throw it away, unless you call retain_grad().
  • .grad adds up, it does not overwrite. Every backward() adds to whatever is already there. That's why each step starts with optimizer.zero_grad().
  • After backward the graph is freed by default, so calling backward() again throws an error unless the first call used retain_graph=True.

The maths: vector-Jacobian products

For a vector function y⃗=f(x⃗)\vec{y}=f(\vec{x}), the derivative is a Jacobian matrix:

J=(∂y1∂x1⋯∂y1∂xn⋮⋱⋮∂ym∂x1⋯∂ym∂xn)J=\begin{pmatrix}\dfrac{\partial y_1}{\partial x_1} & \cdots & \dfrac{\partial y_1}{\partial x_n}\\ \vdots & \ddots & \vdots\\ \dfrac{\partial y_m}{\partial x_1} & \cdots & \dfrac{\partial y_m}{\partial x_n}\end{pmatrix}

Autograd never builds the full JJ. It computes the vector-Jacobian product JT⋅v⃗J^T\cdot\vec{v} for a given vector v⃗\vec{v}. If v⃗\vec{v} is the gradient of a scalar l=g(y⃗)l=g(\vec{y}), then by the chain rule:

JT⋅v⃗=(∂l∂x1⋮∂l∂xn)J^T\cdot\vec{v}=\begin{pmatrix}\dfrac{\partial l}{\partial x_1}\\ \vdots\\ \dfrac{\partial l}{\partial x_n}\end{pmatrix}

When the loss is a scalar, v⃗\vec{v} 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

AttributeMeaning
.datathe raw values, no gradient tracking
.gradthe accumulated gradient, only on leaves
grad_fnthe operation that produced this tensor
requires_gradwhether to track gradients for it
is_leafwhether it is a leaf
FunctionWhat 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=False is 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:

  1. zero_grad(): grad = 0
  2. backward(): grad += new gradient
  3. optimizer.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 call step() and zero_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".

References

OlderWhy Claude Opus 4.7 System Card is 232 Pages →