Forward Propagation, Loss and Backpropagation
Three of the training concepts always come together. Forward propagation turns an input into a prediction, the loss turns the prediction into one number, and backpropagation turns that number back into a gradient for every parameter. In the NumPy MLP you wrote the backward pass by hand for one specific network. This lesson explains the general recipe, the computational graph and the chain rule, and the one test that tells you whether a backward pass is right: the numerical gradient check.
The computational graph
Any model is a composition of simple operations. Write each operation as a node, with arrows for the values flowing between them. Here is a single neuron with a tanh activation and a squared-error loss, :
Forward propagation evaluates the nodes from left to right and keeps the intermediate values , , : the backward pass needs them.
The chain rule, one node at a time
Backpropagation evaluates the graph from right to left. Each node receives the gradient of the loss with respect to its output and multiplies it by its local derivative to get the gradient with respect to its inputs:
That is the whole algorithm. A network with millions of parameters is the same, with matrices instead of scalars: the gradient of a matrix product with respect to is times the incoming gradient, which is the rule you used in the MLP. Because each intermediate gradient is computed once and reused, backprop costs about as much as one or two forward passes, however many parameters there are. The derivation is in Backpropagation and Automatic Differentiation and Computational Graphs.
import numpy as np
x, w, b, y = 1.5, 0.8, -0.2, 0.5
# forward: keep every intermediate value
u = w * x
a = u + b
h = np.tanh(a)
L = (h - y) ** 2
print(f"forward: u = {u:.4f} a = {a:.4f} h = {h:.4f} L = {L:.6f}")
# backward: right to left, local derivative times incoming gradient
dL_dh = 2 * (h - y)
dL_da = dL_dh * (1 - h ** 2)
dL_db = dL_da
dL_du = dL_da
dL_dw = dL_du * x
print(f"backward: dL/dh = {dL_dh:.4f} dL/da = {dL_da:.4f} dL/dw = {dL_dw:.4f} dL/db = {dL_db:.4f}")
# check: nudge w and b by a tiny amount and watch the loss
f = lambda w, b: (np.tanh(w * x + b) - y) ** 2
eps = 1e-6
print(f"numerical: dL/dw = {(f(w + eps, b) - f(w - eps, b)) / (2 * eps):.4f}"
f" dL/db = {(f(w, b + eps) - f(w, b - eps)) / (2 * eps):.4f}")forward: u = 1.2000 a = 1.0000 h = 0.7616 L = 0.068432
backward: dL/dh = 0.5232 dL/da = 0.2197 dL/dw = 0.3296 dL/db = 0.2197
numerical: dL/dw = 0.3296 dL/db = 0.2197
With , , : , , , and the loss against is . Going back, ; the tanh node multiplies by to give ; the add node copies it to ; the multiply node multiplies by to give . Nudging and by gives the same numbers.
The gradient check
The last three lines of that example are the most useful debugging tool in deep learning. The central difference
has an error of order , so with in float64 it agrees with a correct analytic gradient to 7 or more digits. Compare the two with a relative error, which does not depend on the size of the gradient:
Rules of thumb in float64: below is correct, around deserves a look (often a kink such as ReLU at 0), and above is a bug. The check below runs on a 3-5-2 network with a tanh hidden layer and a softmax cross-entropy loss over 2 classes, for all 32 parameters. Then it plants a classic bug, forgetting the activation's derivative, and shows how the check catches it. More on the technique: Gradient Checking.
import numpy as np
rng = np.random.default_rng(0)
X = rng.normal(size=(8, 3)) # 8 examples, 3 features
Y = np.eye(2)[rng.integers(0, 2, 8)] # one-hot labels, 2 classes
params = {"W1": rng.normal(0, 0.5, (3, 5)), "b1": np.zeros(5),
"W2": rng.normal(0, 0.5, (5, 2)), "b2": np.zeros(2)}
def loss_and_grads(P, buggy=False):
A1 = X @ P["W1"] + P["b1"]
H = np.tanh(A1)
Z = H @ P["W2"] + P["b2"]
Z = Z - Z.max(axis=1, keepdims=True) # stable softmax
S = np.exp(Z) / np.exp(Z).sum(axis=1, keepdims=True)
L = -np.mean(np.sum(Y * np.log(S), axis=1)) # mean cross-entropy
dZ = (S - Y) / len(X) # softmax + CE gradient
dH = dZ @ P["W2"].T
dA1 = dH if buggy else dH * (1 - H ** 2) # the bug: forgets tanh'
return L, {"W1": X.T @ dA1, "b1": dA1.sum(axis=0), "W2": H.T @ dZ, "b2": dZ.sum(axis=0)}
def numerical_grads(P, eps=1e-6):
grads = {}
for k, v in P.items():
g = np.zeros_like(v)
for i in np.ndindex(v.shape):
old = v[i]
v[i] = old + eps; Lp, _ = loss_and_grads(P)
v[i] = old - eps; Lm, _ = loss_and_grads(P)
v[i] = old
g[i] = (Lp - Lm) / (2 * eps)
grads[k] = g
return grads
num = numerical_grads(params)
for buggy in (False, True):
_, ana = loss_and_grads(params, buggy)
print("buggy backward" if buggy else "correct backward")
for k in params:
rel = np.linalg.norm(ana[k] - num[k]) / (np.linalg.norm(ana[k]) + np.linalg.norm(num[k]))
print(f" {k}: relative error {rel:.1e}")correct backward
W1: relative error 2.5e-10
b1: relative error 1.3e-10
W2: relative error 4.8e-10
b2: relative error 1.6e-10
buggy backward
W1: relative error 1.5e-01
b1: relative error 6.4e-02
W2: relative error 4.8e-10
b2: relative error 1.6e-10
The correct backward pass agrees with the numerical gradient to about for all four tensors. The buggy one is caught, and the check also says where: the output layer (, ) is still right, because the bug sits below it, while and are off by 15 % and 6 %. Checking per tensor localises a bug to a layer.
The same gradients from PyTorch's autograd
Frameworks build the computational graph while the forward pass runs and walk it backwards when you call loss.backward(). They apply exactly the local rules above, so on the same numbers they must give the same gradients as a correct hand-written backward pass. This example is recorded (PyTorch does not run in the browser).
import numpy as np
import torch
x, w, b, y = 1.5, 0.8, -0.2, 0.5
w_t = torch.tensor(w, dtype=torch.float64, requires_grad=True)
b_t = torch.tensor(b, dtype=torch.float64, requires_grad=True)
L = (torch.tanh(w_t * x + b_t) - y) ** 2 # forward: autograd records the graph
L.backward() # backward: fills .grad
print(f"autograd: L = {L.item():.6f} dL/dw = {w_t.grad.item():.4f} dL/db = {b_t.grad.item():.4f}")
print("grad_fn chain:", L.grad_fn.name(), "<-", L.grad_fn.next_functions[0][0].name(),
"<-", L.grad_fn.next_functions[0][0].next_functions[0][0].name())autograd: L = 0.068432 dL/dw = 0.3296 dL/db = 0.2197
grad_fn chain: PowBackward0 <- SubBackward0 <- TanhBackward0
Autograd gives and , the same as the hand-written chain rule. The grad_fn attributes are the recorded graph: the square (PowBackward0), the subtraction of and the tanh, the same nodes as in the figure, walked from the loss backwards.
Pitfalls
- Gradient checking in float32. With 7 significant digits, loses most of its precision to rounding. Check in float64.
- Checking with dropout or random augmentation on. The two loss evaluations must use the same randomness, otherwise the difference measures noise. Switch them off (or fix the mask) for the check.
- Kinks. At ReLU has no derivative; if a perturbation crosses a kink, the check reports a moderate error for a correct gradient. Use a few random points.
- Checking only the total loss. A falling loss does not prove the gradient is right; many wrong gradients still point roughly downhill, so a buggy backward pass can lower the loss for a while and hide the bug.
- Checking everything on a large model. A numerical gradient costs two forward passes per parameter. Check a tiny version of the model, or a random subset of the parameters.
Practice
- For with the sigmoid , write with the chain rule.
Answer
with : the loss's derivative, the sigmoid's local derivative , and the multiply node's .
- A node computes and receives . With and , what gradients does it pass to and ?
Answer
and . A multiply node sends each input the incoming gradient times the other input.
- A model has 10,000 parameters and one forward pass takes 1 ms. Roughly how long does a full numerical gradient check take, and how long does one backprop take?
Answer
The check needs forward passes, about 20 s. Backprop gives all 10,000 derivatives for the cost of a few forward passes, a few milliseconds. That ratio is why training uses backprop and the numerical gradient is only a test.
Test yourself
Why does the forward pass store intermediate values such as and ?
- For logging only
- The backward pass needs them to evaluate the local derivatives, such as for tanh
- To compute the validation loss
- They are needed by the optimizer's learning rate
What does an addition node pass back to its inputs?
- The incoming gradient, unchanged, to both inputs
- The incoming gradient times the other input
- Zero
- Half the incoming gradient to each
A gradient check reports a relative error of for one weight matrix in float64. What is most likely?
- Everything is correct
- A bug in the backward pass for that layer or the layers after it
- is too small
- The learning rate is too high
Why is backpropagation used for training instead of numerical gradients?
- Numerical gradients are always wrong
- Backprop gives all derivatives for the cost of a few forward passes; numerical gradients need two forward passes per parameter
- Backprop does not need the loss function
- Numerical gradients cannot be computed in float64