TExcelTAD
Home › Training Mechanics, Evaluation & Model Improvement › Forward Propagation, Loss and Backpropagation

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, L=(tanh⁡(wx+b)−y)2L = (\tanh(wx + b) - y)^2:

x w * u b + a tanh h y (h - y)^2 L forward: values, left to right backward: dL/dh, dL/da, dL/du, then dL/dw and dL/db, right to left each node multiplies the incoming gradient by its own local derivative

Forward propagation evaluates the nodes from left to right and keeps the intermediate values uu, aa, hh: 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:

∂L∂h=2(h−y)squared error∂L∂a=∂L∂h⋅(1−h2)tanh⁡′(a)=1−tanh⁡2(a)∂L∂b=∂L∂a⋅1,∂L∂u=∂L∂a⋅1an add node copies the gradient∂L∂w=∂L∂u⋅x,∂L∂x=∂L∂u⋅wa multiply node swaps its inputs\begin{aligned} \frac{\partial L}{\partial h} &= 2(h - y) && \text{squared error} \\ \frac{\partial L}{\partial a} &= \frac{\partial L}{\partial h} \cdot (1 - h^2) && \tanh'(a) = 1 - \tanh^2(a) \\ \frac{\partial L}{\partial b} &= \frac{\partial L}{\partial a} \cdot 1, \qquad \frac{\partial L}{\partial u} = \frac{\partial L}{\partial a} \cdot 1 && \text{an add node copies the gradient} \\ \frac{\partial L}{\partial w} &= \frac{\partial L}{\partial u} \cdot x, \qquad \frac{\partial L}{\partial x} = \frac{\partial L}{\partial u} \cdot w && \text{a multiply node swaps its inputs} \end{aligned}

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 XWXW with respect to WW is X⊤X^\top 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.

python · try it yourself
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 x=1.5x = 1.5, w=0.8w = 0.8, b=−0.2b = -0.2: u=1.2u = 1.2, a=1a = 1, h=tanh⁡1=0.7616h = \tanh 1 = 0.7616, and the loss against y=0.5y = 0.5 is 0.26162=0.0684320.2616^2 = 0.068432. Going back, ∂L/∂h=2⋅0.2616=0.5232\partial L / \partial h = 2 \cdot 0.2616 = 0.5232; the tanh node multiplies by 1−0.76162=0.421 - 0.7616^2 = 0.42 to give 0.21970.2197; the add node copies it to bb; the multiply node multiplies by x=1.5x = 1.5 to give ∂L/∂w=0.3296\partial L / \partial w = 0.3296. Nudging ww and bb by 10−610^{-6} 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

∂L∂θj≈L(θ+ϵej)−L(θ−ϵej)2ϵ\frac{\partial L}{\partial \theta_j} \approx \frac{L(\theta + \epsilon \mathbf{e}_j) - L(\theta - \epsilon \mathbf{e}_j)}{2 \epsilon}

has an error of order ϵ2\epsilon^2, so with ϵ≈10−6\epsilon \approx 10^{-6} 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:

rel. error=∥ganalytic−gnumerical∥∥ganalytic∥+∥gnumerical∥\text{rel. error} = \frac{\lVert \mathbf{g}_{\text{analytic}} - \mathbf{g}_{\text{numerical}} \rVert}{\lVert \mathbf{g}_{\text{analytic}} \rVert + \lVert \mathbf{g}_{\text{numerical}} \rVert}

Rules of thumb in float64: below 10−710^{-7} is correct, around 10−410^{-4} deserves a look (often a kink such as ReLU at 0), and above 10−210^{-2} 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.

python · try it yourself
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 10−1010^{-10} for all four tensors. The buggy one is caught, and the check also says where: the output layer (W2W_2, b2\mathbf{b}_2) is still right, because the bug sits below it, while W1W_1 and b1\mathbf{b}_1 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).

python · try it yourself
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 0.32960.3296 and 0.21970.2197, the same as the hand-written chain rule. The grad_fn attributes are the recorded graph: the square (PowBackward0), the subtraction of yy and the tanh, the same nodes as in the figure, walked from the loss backwards.

Pitfalls

  • Gradient checking in float32. With 7 significant digits, (L+−L−)/(2ϵ)(L_+ - L_-)/(2\epsilon) 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 a=0a = 0 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

  1. For L=(σ(wx+b)−y)2L = (\sigma(wx + b) - y)^2 with the sigmoid σ\sigma, write ∂L/∂w\partial L / \partial w with the chain rule.
Answer

∂L∂w=2(σ(a)−y)⋅σ(a)(1−σ(a))⋅x\frac{\partial L}{\partial w} = 2(\sigma(a) - y) \cdot \sigma(a)(1 - \sigma(a)) \cdot x with a=wx+ba = wx + b: the loss's derivative, the sigmoid's local derivative σ′(a)=σ(a)(1−σ(a))\sigma'(a) = \sigma(a)(1 - \sigma(a)), and the multiply node's xx.

  1. A node computes c=a⋅bc = a \cdot b and receives ∂L/∂c=3\partial L / \partial c = 3. With a=2a = 2 and b=−4b = -4, what gradients does it pass to aa and bb?
Answer

∂L/∂a=3⋅b=−12\partial L / \partial a = 3 \cdot b = -12 and ∂L/∂b=3⋅a=6\partial L / \partial b = 3 \cdot a = 6. A multiply node sends each input the incoming gradient times the other input.

  1. 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 2⋅10000=200002 \cdot 10000 = 20000 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 aa and hh?

  1. For logging only
  2. The backward pass needs them to evaluate the local derivatives, such as 1−h21 - h^2 for tanh
  3. To compute the validation loss
  4. They are needed by the optimizer's learning rate

What does an addition node a=u+ba = u + b pass back to its inputs?

  1. The incoming gradient, unchanged, to both inputs
  2. The incoming gradient times the other input
  3. Zero
  4. Half the incoming gradient to each

A gradient check reports a relative error of 0.40.4 for one weight matrix in float64. What is most likely?

  1. Everything is correct
  2. A bug in the backward pass for that layer or the layers after it
  3. ϵ\epsilon is too small
  4. The learning rate is too high

Why is backpropagation used for training instead of numerical gradients?

  1. Numerical gradients are always wrong
  2. Backprop gives all derivatives for the cost of a few forward passes; numerical gradients need two forward passes per parameter
  3. Backprop does not need the loss function
  4. Numerical gradients cannot be computed in float64