Skip to content
mentoor

Topic 3 of 5 · 5 min read

Backpropagation and the chain rule

Goal: Work out the gradient for one weight in a two-layer network with the chain rule and check it against a framework's result.

Backpropagation applies the chain rule from the loss backward through the network, reusing each layer's result, so that every weight receives its own gradient in one pass.

Check yourself · 1 of 3

In L = (w * x - t)^2 with x = 2, w = 1 and t = 5, what is dL/dw?

Choose one answer

Why it matters

Training needs the gradient of the loss with respect to every weight: the direction to nudge each one to reduce the loss. A network can have millions of weights. Backpropagation computes all of them at roughly the cost of one extra forward pass, which is why deep learning is practical. Frameworks such as PyTorch do it for you (autograd), but you need to know what they compute to debug a model that does not learn.

The chain rule

If L depends on y, y depends on h, and h depends on w, then dL/dw = dL/dy * dy/dh * dh/dw. Each factor is a local derivative that one layer can compute alone. The backward pass multiplies them together moving from the loss toward the input.

A scalar example

One input, two layers, no biases: z1 = w1 * x, h = relu(z1), y = w2 * h, loss L = (y - t)^2.

With x = 2, w1 = 0.5, w2 = 3, target t = 2:

  1. Forward: z1 = 1, h = 1, y = 3, L = 1.
  2. dL/dy = 2(y - t) = 2.
  3. dL/dw2 = dL/dy * h = 2 * 1 = 2.
  4. dL/dh = dL/dy * w2 = 2 * 3 = 6.
  5. dL/dz1 = dL/dh * relu'(z1) = 6 * 1 = 6 (ReLU's slope is 1 for positive input).
  6. dL/dw1 = dL/dz1 * x = 6 * 2 = 12.

Notice step 4 reuses the error signal from step 2, and step 6 reuses step 5. That reuse is the whole trick.

Check it with a framework

import torch

x = torch.tensor(2.0)
w1 = torch.tensor(0.5, requires_grad=True)
w2 = torch.tensor(3.0, requires_grad=True)
loss = (w2 * torch.relu(w1 * x) - 2.0) ** 2
loss.backward()
print(w1.grad, w2.grad)   # tensor(12.) tensor(2.)

This matches the hand result. Doing this on a toy network is the quickest way to trust a custom layer or loss.

Before and after

Weak: "The network adjusts its weights based on the error."

Better: "The loss gradient flows backward; each layer multiplies it by its local derivative to get its own weights' gradients, and an optimizer then steps the weights against them."

What goes wrong

  • Forgetting zero_grad. PyTorch adds new gradients to old ones. Without optimizer.zero_grad() each step uses a growing sum.
  • Breaking the graph with .detach(), .item() or a NumPy conversion mid-model. Gradients stop at that point and earlier weights never update.
  • Mixing up backprop and the optimizer. Backpropagation computes gradients; gradient descent or Adam decides how to use them.

Examples

Autograd accumulates

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

Every call to backward() adds to the stored gradients. By the tenth step the update uses the sum of ten batches, and the loss behaves erratically. Call optimizer.zero_grad() before each backward().

A broken graph

h = encoder(x)
h = torch.tensor(h.detach().numpy() * 2)
loss = head(h).mean()
loss.backward()

The round trip through NumPy creates a new tensor with no history. The encoder gets no gradient and never trains, and no error is raised.

Key points

  • Backpropagation is the chain rule applied from the loss back to every weight, reusing intermediate results.
  • Each layer only needs its local derivative and the gradient arriving from the layer after it.
  • ReLU's derivative is 1 for positive inputs and 0 for negative ones, which is why dead units get no gradient.
  • Backpropagation computes gradients; an optimizer such as SGD or Adam uses them to update weights.
  • Checking a hand-computed gradient against autograd on a toy network is a reliable way to test custom code.

Common mistakes

  • Calling backpropagation the thing that updates the weights, when the optimizer does that.
  • Not clearing gradients between steps.
  • Detaching tensors or converting to NumPy inside the model and expecting earlier layers to train.
  • Skipping a hand check on a toy input when writing a custom loss or layer.

Check yourself · 2 of 3

What does the backward pass compute?

Choose one answer

Check yourself · 3 of 3

A PyTorch loop calls loss.backward() and optimizer.step() each batch but never zero_grad(). What happens?

Choose one answer

Practice items, not counted towards your mastery.

Start here

More for this topic