Skip to content
mentoor

Topic 2 of 5 · 4 min read

Autograd and computation graphs

Goal: Use autograd to get the gradients of a small function and explain why gradients must be zeroed every step.

Autograd records the operations on tensors that require gradients, and backward() walks that record to fill each tensor's .grad with the derivative of a single scalar.

Check yourself · 1 of 3

You call loss.backward() three times in a row on freshly built graphs without zeroing. What does w.grad hold?

Choose one answer

Why it matters

You never write derivatives by hand in PyTorch. But you do have to know when gradients are tracked, when they accumulate, and when to switch tracking off. Missing any of these produces training that looks fine and learns nothing, or inference that wastes memory.

How to do it

  1. Mark what to learn. w = torch.tensor(2.0, requires_grad=True). Model parameters already have this set.
  2. Compute a scalar. Autograd builds a graph as you compute: loss = (w * 3 - 5) ** 2.
  3. Call backward. loss.backward() fills w.grad. Here the loss is (3w - 5)^2, so the gradient is 2 * (3w - 5) * 3, which is 6 at w = 2.
  4. Zero the gradients every step. .grad values add up across backward calls. optimizer.zero_grad() before each backward call resets them.
  5. Turn tracking off when not training. with torch.no_grad(): skips graph building for validation and inference, saving memory and time. .detach() cuts one tensor out of the graph.

Before and after

# Weak: gradients pile up across iterations
for x, y in loader:
    loss = loss_fn(model(x), y)
    loss.backward()
    optimizer.step()

On the second batch, .grad holds the sum of two batches' gradients, on the third, three. The effective step grows each iteration and training drifts or diverges.

# Fixed
for x, y in loader:
    optimizer.zero_grad()
    loss = loss_fn(model(x), y)
    loss.backward()
    optimizer.step()

What goes wrong

  • Forgotten zero_grad. Accumulation is intentional (it enables gradient accumulation over several small batches), so PyTorch never zeroes it for you.
  • backward on a non-scalar. Calling .backward() on a [32] tensor raises an error. Reduce it with .mean() or .sum() first.
  • Validation with tracking on. Without torch.no_grad(), every validation batch builds a graph and memory grows.
  • Calling backward twice on the same graph raises an error because the graph is freed after the first call.

Examples

A gradient by hand and by autograd

w = torch.tensor(2.0, requires_grad=True)
loss = (w * 3 - 5) ** 2
loss.backward()
print(w.grad)  # tensor(6.)

By hand: d/dw (3w - 5)^2 = 2(3w - 5) * 3 = 2 * 1 * 3 = 6. Calling loss.backward() a second time without zeroing would make w.grad read 12 after rebuilding the graph.

Evaluating without tracking

model.eval()
with torch.no_grad():
    preds = model(x_val)

This gives the same predictions but stores no graph, so a large validation set does not exhaust GPU memory.

Key points

  • A tensor with requires_grad=True is tracked, and backward() on a scalar fills .grad on every tracked leaf.
  • Gradients accumulate in .grad across backward calls, so they must be zeroed before each new backward pass.
  • backward() needs a scalar, so reduce a per-example loss with mean() or sum() first.
  • torch.no_grad() stops graph building during validation and inference and saves memory.
  • detach() removes a tensor from the graph, which is how you stop gradients flowing into part of a computation.

Common mistakes

  • Omitting zero_grad() and assuming PyTorch resets gradients after step().
  • Calling backward() on a loss that has not been reduced to a scalar.
  • Running validation without torch.no_grad() and running out of memory.
  • Calling .item() or converting to NumPy inside the graph and then expecting gradients to flow.

Check yourself · 2 of 3

What does torch.no_grad() do during validation?

Choose one answer

Check yourself · 3 of 3

loss has shape [32], one value per example. What happens when you call loss.backward()?

Choose one answer

Practice items, not counted towards your mastery.

Start here