Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 2 of 6 · Worked example · 25 min · revision 2

Backpropagation and Autograd, Step by Step

Push one example through a two-layer network by hand, apply the chain rule backwards to get every gradient, check each number against PyTorch autograd, perform one optimizer step by hand and with SGD, watch gradients accumulate, and verify a whole network with a numerical gradient check.

Contentsand lesson path

What you will learn

  • Explain how a forward pass, a loss, backpropagation and an optimizer step update the weights, and inspect gradients with PyTorch autograd.

Prerequisites: Machine Learning Fundamentals, Linear Algebra & Calculus for ML

01. The problem

loss.backward() is one line, and it is easy to treat it as magic. This worked example removes the magic. You take a network small enough to compute on paper, run the forward pass and the backward pass by hand, and check that PyTorch produces the same numbers. Once you have done it once, gradient bugs become something you can reason about.

The network has two inputs, a hidden layer of two ReLU neurons and one linear output neuron. There is one training example, x = (1, 2) with target y = 1, and the loss is the squared error (ŷ − y)². The weights are fixed numbers so that you can follow every step. You need Python 3.12, NumPy and PyTorch 2 (CPU build).

Prerequisite: the derivative and the chain rule from the gradients lesson. The chain rule says that if L depends on a and a depends on w, then dL/dw = dL/da × da/dw. Backpropagation is the chain rule applied systematically, from the loss back to every weight, reusing each intermediate result once.

02. Step 1: Forward and backward pass by hand

The forward pass stores every intermediate value, because the backward pass needs them. Then the backward pass starts at the loss and moves one operation at a time towards the weights. At each operation, the gradient arriving from above is multiplied by the local derivative of that operation:

  • The loss (ŷ − y)² has derivative 2(ŷ − y) with respect to ŷ.
  • ŷ = W₂ · h + b₂, so the gradient for each output weight is that number times the matching hidden value h, and for b₂ it is the number itself.
  • Going further back, the gradient reaching each hidden value is the output gradient times its weight in W₂.
  • ReLU passes a gradient through where its input was positive and blocks it (slope 0) where it was negative.
  • z₁ = W₁x + b₁, so each weight in W₁ gets the gradient of its neuron times the input it multiplies.
Python · by_hand.py
import numpy as np

x = np.array([1.0, 2.0])                     # one example, two features
y = 1.0                                      # its target
W1 = np.array([[0.3, 0.2], [-0.4, 0.1]])     # hidden layer: 2 neurons
b1 = np.array([0.1, 0.1])
W2 = np.array([0.5, -0.6])                   # output layer: 1 neuron
b2 = 0.2

# forward pass, keeping every intermediate value
z1 = W1 @ x + b1                 # hidden pre-activations
h = np.maximum(z1, 0)            # ReLU
y_hat = W2 @ h + b2              # prediction
loss = (y_hat - y) ** 2          # squared error
print("z1 =", z1, " h =", h, f" y_hat = {y_hat:.2f}  loss = {loss:.4f}")

# backward pass: chain rule from the loss towards the inputs
d_yhat = 2 * (y_hat - y)         # dL/dy_hat
d_W2 = d_yhat * h                # y_hat = W2 . h + b2
d_b2 = d_yhat
d_h = d_yhat * W2
d_z1 = d_h * (z1 > 0)            # ReLU slope: 1 if z1 > 0, else 0
d_W1 = np.outer(d_z1, x)         # z1 = W1 @ x + b1
d_b1 = d_z1
print(f"dL/dy_hat = {d_yhat:.2f}")
print("dL/dW2 =", d_W2.round(4) + 0.0, f" dL/db2 = {d_b2:.2f}")  # + 0.0 drops "-0."
print("dL/dh  =", d_h.round(4), " dL/dz1 =", d_z1.round(4))
print("dL/dW1 =", d_W1.round(4).tolist(), " dL/db1 =", d_b1.round(4))
Terminal
python by_hand.py
Expected output
z1 = [ 0.8 -0.1]  h = [0.8 0. ]  y_hat = 0.60  loss = 0.1600
dL/dy_hat = -0.80
dL/dW2 = [-0.64  0.  ]  dL/db2 = -0.80
dL/dh  = [-0.4   0.48]  dL/dz1 = [-0.4  0. ]
dL/dW1 = [[-0.4, -0.8], [0.0, 0.0]]  dL/db1 = [-0.4  0. ]

Follow the numbers. The first hidden neuron gets z = 0.3 × 1 + 0.2 × 2 + 0.1 = 0.8, so h = 0.8; the second gets −0.1 and ReLU turns it into 0. The prediction is 0.5 × 0.8 + 0.2 = 0.6, the target is 1, the loss 0.16. Backwards: 2 × (0.6 − 1) = −0.8. The negative sign says that increasing ŷ would lower the loss. The first output weight gets −0.8 × 0.8 = −0.64.

The second hidden neuron is interesting. A gradient of 0.48 reaches its output h, but its pre-activation was negative, so ReLU blocks it and every weight feeding that neuron gets exactly zero. For this example the neuron does not learn at all. If a neuron is negative for every example, it never learns again: a dead ReLU. Lower learning rates and good initialisation make that less likely.

03. Step 2: Let autograd do it

PyTorch's autograd records every operation on tensors that have requires_grad=True in a computation graph. backward() walks that graph from the loss back to the leaf tensors, the ones you created yourself, and adds each gradient to their .grad attribute. Intermediate tensors such as z1 are not leaves, so their gradients are used and then discarded unless you call retain_grad() on them.

Python · with_autograd.py
import torch

x = torch.tensor([1.0, 2.0])
y = torch.tensor(1.0)
W1 = torch.tensor([[0.3, 0.2], [-0.4, 0.1]], requires_grad=True)
b1 = torch.tensor([0.1, 0.1], requires_grad=True)
W2 = torch.tensor([0.5, -0.6], requires_grad=True)
b2 = torch.tensor(0.2, requires_grad=True)

z1 = W1 @ x + b1                 # same forward pass; autograd records each operation
z1.retain_grad()                 # keep the gradient of this intermediate tensor too
y_hat = W2 @ torch.relu(z1) + b2
loss = (y_hat - y) ** 2
loss.backward()                  # walks the recorded graph backwards

print(f"loss = {loss.item():.4f}")
torch.set_printoptions(precision=4)
print("W2.grad =", W2.grad + 0.0, " b2.grad =", b2.grad)
print("W1.grad =", W1.grad + 0.0)
print("b1.grad =", b1.grad + 0.0)
print("z1.grad =", z1.grad + 0.0, " z1.is_leaf =", z1.is_leaf,
      " W1.is_leaf =", W1.is_leaf)
Terminal
python with_autograd.py
Expected output
loss = 0.1600
W2.grad = tensor([-0.6400,  0.0000])  b2.grad = tensor(-0.8000)
W1.grad = tensor([[-0.4000, -0.8000],
        [ 0.0000,  0.0000]])
b1.grad = tensor([-0.4000,  0.0000])
z1.grad = tensor([-0.4000,  0.0000])  z1.is_leaf = False  W1.is_leaf = True

Every gradient matches the hand calculation, including the zeros of the dead neuron. Without the retain_grad() line, z1.grad would be None and PyTorch would print a UserWarning about reading the .grad of a non-leaf tensor. In a real model the leaves are the parameters inside nn.Linear and other layers, which is why model.parameters() is what you hand to an optimizer.

04. Step 3: One optimizer step, and why gradients must be cleared

Gradients only describe which way is downhill. The optimizer decides how far to move. Plain SGD replaces each weight w by w − lr × w.grad, where lr is the learning rate. The script performs that update by hand and with torch.optim.SGD, then shows a property of backward() that causes real bugs: it adds to .grad instead of overwriting it.

Python · step.py
import torch


def make_params():
    return [torch.tensor([[0.3, 0.2], [-0.4, 0.1]], requires_grad=True),
            torch.tensor([0.1, 0.1], requires_grad=True),
            torch.tensor([0.5, -0.6], requires_grad=True),
            torch.tensor(0.2, requires_grad=True)]


def loss_fn(params, x, y):
    W1, b1, W2, b2 = params
    return (W2 @ torch.relu(W1 @ x + b1) + b2 - y) ** 2


x, y = torch.tensor([1.0, 2.0]), torch.tensor(1.0)
params = make_params()
opt = torch.optim.SGD(params, lr=0.1)
loss_fn(params, x, y).backward()
expected_W2 = params[2].detach() - 0.1 * params[2].grad   # the update, by hand
opt.step()                                                # the same update, by SGD
print("W2 after one step:", params[2].detach(), " by hand:", expected_W2)
print(f"loss before 0.1600, after {loss_fn(params, x, y).item():.4f}")

# Gradients add up: two backward passes without zero_grad() in between
params = make_params()
loss_fn(params, x, y).backward()
print("b2.grad after 1 backward:", params[3].grad)
loss_fn(params, x, y).backward()
print("b2.grad after 2 backwards:", params[3].grad)
params[3].grad = None                                     # what zero_grad() does
print("b2.grad after reset:", params[3].grad)
Terminal
python step.py
Expected output
W2 after one step: tensor([ 0.5640, -0.6000])  by hand: tensor([ 0.5640, -0.6000])
loss before 0.1600, after 0.0178
b2.grad after 1 backward: tensor(-0.8000)
b2.grad after 2 backwards: tensor(-1.6000)
b2.grad after reset: None

With lr = 0.1, the first output weight moves from 0.5 to 0.5 − 0.1 × (−0.64) = 0.564, exactly what SGD does, and the loss on this example falls from 0.16 to 0.0178. A second backward() without clearing doubles b2.grad from −0.8 to −1.6. That accumulation is deliberate, because it lets you sum gradients over several small batches before one step, but in a normal loop it means each step would use the sum of all earlier gradients. That is why a training loop calls optimizer.zero_grad() once per step; by default it sets every .grad to None, as the last line does by hand.

05. Step 4: Check a whole network numerically

For a custom layer or loss you cannot check every gradient by hand. torch.autograd.gradcheck compares autograd with finite differences: it nudges each input element by a tiny amount, measures how the output changes, and compares that slope with the analytic gradient. Finite differences subtract two nearly equal numbers, so they need the precision of float64; in float32 the rounding error is larger than the default tolerances.

Python · check.py
import torch
from torch import nn
from torch.autograd import gradcheck

torch.manual_seed(0)
net = nn.Sequential(nn.Linear(3, 4), nn.Tanh(), nn.Linear(4, 1)).double()
x = torch.randn(5, 3, dtype=torch.float64, requires_grad=True)

# compares autograd with finite differences for every input element
print("float64 check passed:", gradcheck(lambda inp: net(inp).sum(), (x,)))

net32 = net.float()
x32 = x.detach().float().requires_grad_()
try:
    gradcheck(lambda inp: net32(inp).sum(), (x32,))
except Exception as err:  # float32 is too coarse for the default tolerances
    print("float32 check:", type(err).__name__)
Terminal
python check.py
Expected output
float64 check passed: True
float32 check: GradcheckError

The float64 check passes. The float32 run fails with GradcheckError, and PyTorch also prints a UserWarning that the input is not double precision. The failure is about precision, not about a wrong gradient, which is why gradient checks run in float64 even when training runs in float32.

06. Check your understanding

Practice check · 3 questions

Follow the gradients

Use the numbers of this worked example.

Q1. In `by_hand.py`, a gradient of 0.48 reaches the second hidden value, yet every weight feeding that neuron gets a gradient of exactly 0. Why?
Q2. A training loop appends `loss` (not `loss.item()`) to a Python list after every step, and memory use climbs steadily. What is the cause?
Q3. In `check.py`, why does the numerical gradient check pass in float64 but fail in float32 for the same network?
Practice only: not graded, not saved, not evidence.

07. Apply it

Before the practice project, make this example your own.

  1. Change the target to y = 0.2, predict the sign of every gradient on paper, then run by_hand.py and with_autograd.py to check.
  2. Replace ReLU with tanh in both scripts (its derivative is 1 − tanh²) and confirm that the second neuron now learns.
  3. Write a tiny custom function (for example a smooth absolute value √(x² + 0.01)) and verify its gradient with gradcheck in float64.

08. Review prompt

Without looking back, state the chain rule and how backpropagation uses it; describe what the forward pass must store and why; explain what ReLU does to a gradient for positive and negative inputs; say what backward() does to .grad when called twice and why loops clear it; and explain why a numerical gradient check runs in float64.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check