Lesson 1.6 — Gradients & Backpropagation
From control sensitivity to backpropagation
Forward pass
Compute the prediction, the residual and the loss. Save the intermediate values that the reverse pass will need.
Backward pass
Start from the scalar loss and move against the dependency arrows, multiplying local derivatives along every path.
Optimizer
Use the gradients to update parameters. Backpropagation itself changes no parameter.
Scope. Backpropagation computes gradients; it does not update parameters. The
optimizer step applies θ ← θ − ηg. Building the graph automatically with
requires_grad and backward() is Lesson 1.7; full training is Lesson 1.8.
Key idea: a gradient is not the error and not a weight. It is the local sensitivity of the loss to each parameter, evaluated at the current parameters.
Derivative and gradient — local sensitivity
Tangent / finite difference · gradient field
x = torch.tensor(1, dtype=torch.float64)
h = 0.5
f = lambda t: t.square()
print('forward difference:', (f(x+h)-f(x))/h)
print('exact derivative:', 2*x)
Two views of the same object. The secant slope is a numerical estimate built
from two forward evaluations. The tangent is the analytic derivative. For f(x)=x²
the forward-difference error is exactly h; a step that is too small can also lose
precision to floating-point cancellation.
Chain rule — multiply local derivatives
Scalar Backpropagation Player
import math
x, w, b, y = 1.5, 0.5, 0, 0.5
z = w*x + b
a = math.tanh(z)
L = (a - y)**2
ga = 2*(a-y)
gz = ga*(1-a*a)
gw, gb, gx = gz*x, gz, gz*w
print(L, gw, gb, gx)
Notation. The adjoint of a node is gᵥ = ∂L/∂v. It is not the same
quantity as a local derivative. When tanh saturates, 1−a² approaches zero and the
gradient becomes very small; systematic gradient stability is a Chapter 2 topic.
Fan-out — sum every contribution
A small change to reaches the same loss twice. Follow the dependencies forward to see what changes. Follow them backward to measure how much each change contributes.
| Forward path | Effect of an input change | Contribution to the slope of |
|---|---|---|
| changes by | ||
| changes by |
Adding the two changes gives . The coefficient of is the gradient. At the two first-order changes cancel. The loss can still change by for a finite step.
Fan-out Gradient Accumulation
Parameter sharing. A weight used by several batch samples receives one contribution per sample; those contributions are reduced by accumulation. The averaging coefficient of a mean loss must be kept as well.
Jacobian — derivatives of vector-valued maps
Jacobian Column Inspector
x = torch.tensor([1, 0.5], dtype=torch.float64)
h = 0.011
a, b = x
def f(v):
u, w = v
return torch.stack([u*u+w, u*w, w.sin()])
e = torch.eye(2, dtype=x.dtype)[0]
fd = (f(x+h*e) - f(x-h*e)) / (2*h)
print(fd)
Row and column convention. Outputs index rows; inputs index columns. Column
j predicts how all outputs change when only input j is perturbed:
f(x+Δx) ≈ f(x) + J(x)Δx.
VJP — propagate a scalar loss
The VJP applies the same branch rule to vectors. Freeze an input coordinate and look down column of . Each entry is multiplied by that output's upstream gradient before summation. In the diagram, a seed with a one at output i and zeros elsewhere leaves just row i of , read as a column gradient.
VJP Contribution Mapper
x, y = torch.tensor([1, 0.5], dtype=torch.float64)
J = torch.stack([
torch.stack([2*x, torch.ones_like(x)]),
torch.stack([y, x]),
torch.stack([torch.zeros_like(y), torch.cos(y)]),
])
g = torch.tensor([1,-2,1], dtype=torch.float64)
print(J.T @ g)
print((g[:, None] * J).sum(dim=0))
Efficiency. The VJP can be formed directly without materializing the full
Jacobian. This is why reverse-mode automatic differentiation is cheap when there are many
parameters and one scalar objective. Some texts write the row-vector form gᵧᵀJ;
the column-vector convention Jᵀgᵧ denotes the same product.
Two-layer network — derive every parameter gradient
Forward and backward shape trace
| Quantity | Shape | Meaning |
|---|---|---|
| X | (B, 2) | Input batch |
| W₁, b₁ | (2, 2), (2,) | First layer |
| Z, H | (B, 2) | Hidden pre- and post-activation |
| W₂, b₂ | (1, 2), (1,) | Second layer |
| P, Y, Gₚ | (B, 1) | Prediction, target, output gradient |
Two-layer Manual Backpropagation · 2→2→1
Z = X @ W1.T + b1
H = Z.tanh()
P = H @ W2.T + b2
L = (P - Y).square().mean()
Gp = 2 * (P - Y) / P.numel()
GW2, Gb2 = Gp.T @ H, Gp.sum(dim=0)
Gh = Gp @ W2
Gz = Gh * (1 - H.square())
GW1, Gb1 = Gz.T @ X, Gz.sum(dim=0)
Gx = Gz @ W1
Check the shapes. dL/dW₁ has the same shape as W₁,
and likewise for every bias. Bias gradients sum over the batch. The 2/B factor
belongs to G_P, so do not divide by B again when summing the biases.
For multi-output mean squared error the denominator is B × D_out.
Verify the mathematics with PyTorch tensors
Manual two-layer backward plus finite-difference check
The finite-difference loop temporarily changes one parameter at a time and restores it. Use float64 for a meaningful comparison.
import torch
torch.set_default_dtype(torch.float64)
X = torch.tensor([[1., -0.5], [0.5, 1.]])
Y = torch.tensor([[0.3], [-0.2]])
W1 = torch.tensor([[0.5, -0.25], [0.4, 0.6]])
b1 = torch.tensor([0.1, -0.1])
W2 = torch.tensor([[1., -0.5]])
b2 = torch.tensor([0.2])
def loss():
H = torch.tanh(X @ W1.T + b1)
return ((H @ W2.T + b2 - Y)**2).mean()
Z = X @ W1.T + b1
H = Z.tanh()
P = H @ W2.T + b2
L = (P - Y).square().mean()
Gp = 2 * (P - Y) / P.numel()
GW2, Gb2 = Gp.T @ H, Gp.sum(dim=0)
Gh = Gp @ W2
Gz = Gh * (1 - H.square())
GW1, Gb1 = Gz.T @ X, Gz.sum(dim=0)
Gx = Gz @ W1
print('loss:', L.item())
h = 1e-5
for name, param, grad in [('W1', W1, GW1), ('b1', b1, Gb1),
('W2', W2, GW2), ('b2', b2, Gb2)]:
fd = torch.zeros_like(param)
for k in range(param.numel()):
p = param.view(-1)
old = p[k].item()
p[k] = old + h
plus = loss().item()
p[k] = old - h
minus = loss().item()
p[k] = old
fd.view(-1)[k] = (plus - minus) / (2 * h)
torch.testing.assert_close(grad, fd, atol=1e-8, rtol=1e-6)
print(name, 'max abs error:', (grad - fd).abs().max().item())
Nine parameter entries: four in W1, two in b1, two in W2 and one in b2.
Scalar chain rule, vectorized exactly as above
x, w, b, y = 1.5, 0.5, 0.0, 0.5
z = w * x + b
a = torch.tanh(torch.tensor(z))
L = (a - y)**2
ga = 2 * (a - y)
gz = ga * (1 - a*a)
gw, gb, gx = gz*x, gz, gz*w
print(L.item(), gw.item(), gb.item(), gx.item())
Before updating. Save the forward intermediates, check every gradient shape, and confirm that all gradients come from the same old parameters.
After computing gradients. The parameters have not moved yet. The optimizer
step θ ← θ − ηg is a separate operation and is introduced with training in a later
lesson.