Forward and backward: automatic differentiation and backpropagation

To learn, a network needs the slope of its loss with respect to every weight. Automatic differentiation gets all of them exactly — and running it backwards gets them for the price of a few evaluations, whether there are ten weights or ten billion.

⏱ 45 minNeeds: chain rule (Chapter 2), gradient descent (Chapter 10)2 labs · 1 animation · 1 video
In plain words

A computer program is a chain of tiny steps: multiply, add, square. Each tiny step has an easy derivative. The chain rule glues them together. Forward propagation runs the chain from inputs to loss and remembers every intermediate number. Backward propagation then walks the chain in reverse, multiplying the easy derivatives, and at the end holds the slope of the loss with respect to every weight at once. The two are not rivals — every training step does both, in that order.

You will learn
Level 1 · basicThree ways to differentiate; the graph; forward then backward Level 2 · standardDual numbers, reverse mode, the lab, the cost of each Level 3 · advancedDouble differentiation in PINNs, memory, higher derivatives
Video (46 s, no sound): one neuron, one forward pass, one backward pass, one weight update — and why going backwards is cheap.

1. Why we need derivatives of a program

In Chapter 10 every update needed a slope, $w \leftarrow w - \eta\,\partial L/\partial w$. For one apple price we differentiated by hand. A real network is a program with thousands of lines of arithmetic and millions of weights. We need a machine that, given any program computing a loss, returns the derivative of that loss with respect to every weight — exactly and fast. PINNs need even more: derivatives of the network output with respect to its inputs ($u_x$, $u_{xx}$, $u_t$) to build the equation residual (section 8).

2. Three ways to differentiate on a computer

Take $f(x) = x^2\sin x$ at $x = 1$. The exact derivative is $f'(x) = 2x\sin x + x^2\cos x$, so $f'(1) = 2\sin 1 + \cos 1 \approx 2.2232$.

methodhowresult at $x=1$trouble
Finite differences$\dfrac{f(1+h) - f(1)}{h}$ with $h = 10^{-4}$2.2233… (approximate)error from $h$ and from round-off; one extra evaluation per input
Symbolicapply rules to the formula: $2x\sin x + x^2\cos x$2.2232 (exact)formulas grow explosively for long programs ("expression swell"); loops and if-statements are awkward
Automatic (AD)apply the chain rule to the numbers as the program runs2.2232 (exact up to rounding)needs memory (reverse mode); otherwise none

AD is neither numerical approximation nor symbolic algebra: it differentiates each elementary operation exactly and combines the numerical values with the chain rule. A. G. Baydin, B. A. Pearlmutter, A. A. Radul & J. M. Siskind, "Automatic differentiation in machine learning: a survey", J. Mach. Learn. Res. 18(153), 2018, 1–43.

3. The computational graph: one neuron, every number

Our toy network is a single linear neuron: prediction $\hat y = w\,x + b$, loss $L = (\hat y - y)^2$. Data: input $x = 2$, target $y = 3$. Current weights: $w = 0.5$, $b = 1$. Break the program into elementary steps, one new variable per step:

stepoperationvaluelocal derivatives (easy!)
1$m = w\cdot x$$0.5\times2 = 1$$\partial m/\partial w = x = 2$, $\;\partial m/\partial x = w = 0.5$
2$\hat y = m + b$$1 + 1 = 2$$\partial\hat y/\partial m = 1$, $\;\partial\hat y/\partial b = 1$
3$e = \hat y - y$$2 - 3 = -1$$\partial e/\partial\hat y = 1$
4$L = e^2$$(-1)^2 = 1$$\partial L/\partial e = 2e = -2$

Drawn as boxes and arrows this is the computational graph: inputs on the left, the loss on the right. Every deep-learning library builds such a graph (explicitly or implicitly) while your code runs.

4. Forward propagation and backward propagation

Two words that are often confused:

Forward propagation (forward pass)

Go left → right through the graph and compute the values: $m$, $\hat y$, $e$, $L$. This is simply "running the network". Store every intermediate value.

Output: the prediction and the loss.

Backward propagation (backward pass, backprop)

Go right → left and compute the gradients $\partial L/\partial(\cdot)$ of the loss with respect to each node, using the stored values.

Output: the slope for every weight.

So the question "why use backward propagation instead of forward propagation?" has a precise answer: we always use both. Forward propagation computes the loss; backward propagation computes its gradient. The real choice is how to compute the gradient: by sweeping derivatives forward alongside the values (forward-mode AD, section 5) or backward after the values (reverse-mode AD = backpropagation, section 6). Section 7 shows why backwards wins for training.

Animation: a computational graph; blue values fill in from left to right during the forward pass, then orange gradients flow from right to left during the backward pass, followed by a weight update.
Watch: blue numbers = forward pass (values). Orange numbers = backward pass (gradients). At the end both $\partial L/\partial w = -4$ and $\partial L/\partial b = -2$ are known, and one gradient-descent step with $\eta = 0.1$ makes the prediction exact.

5. Forward-mode AD: carry a derivative along

Idea: next to every value $v$ also carry its derivative $\dot v$ with respect to one chosen input (say $w$). Start with $\dot w = 1$ (the derivative of $w$ with respect to itself) and $\dot x = \dot b = \dot y = 0$. Apply the chain rule at each step as you go forward:

stepvaluederivative w.r.t. $w$ ("tangent")
$m = wx$1$\dot m = \dot w\,x + w\,\dot x = 1\cdot2 + 0.5\cdot0 = 2$
$\hat y = m + b$2$\dot{\hat y} = \dot m + \dot b = 2$
$e = \hat y - y$−1$\dot e = \dot{\hat y} - \dot y = 2$
$L = e^2$1$\dot L = 2e\,\dot e = 2(-1)(2) = -4 = \partial L/\partial w$ ✓

One forward sweep gave $\partial L/\partial w$. For $\partial L/\partial b$ we must repeat the whole sweep with $\dot b = 1$, $\dot w = 0$. One sweep per input. With a million weights: a million sweeps.

Simplest example · dual numbers

Invent a number $\varepsilon$ with $\varepsilon^2 = 0$ (but $\varepsilon \ne 0$). Then for $f(x) = x^2 + 3x$: $$f(2 + \varepsilon) = (2+\varepsilon)^2 + 3(2+\varepsilon) = 4 + 4\varepsilon + \varepsilon^2 + 6 + 3\varepsilon = 10 + 7\varepsilon.$$ The ordinary part is $f(2) = 10$; the $\varepsilon$-part is $f'(2) = 2\cdot2 + 3 = 7$. Computing with these "dual numbers" is forward-mode AD. R. E. Wengert, "A simple automatic derivative evaluation program", Comm. ACM 7(8), 1964, 463–464.

class Dual:
    """a + b·ε with ε² = 0: 'a' is the value, 'b' the derivative"""
    def __init__(self, a, b=0.0): self.a, self.b = a, b
    def __add__(self, o): o = o if isinstance(o, Dual) else Dual(o); return Dual(self.a + o.a, self.b + o.b)
    __radd__ = __add__
    def __sub__(self, o): o = o if isinstance(o, Dual) else Dual(o); return Dual(self.a - o.a, self.b - o.b)
    def __mul__(self, o): o = o if isinstance(o, Dual) else Dual(o); return Dual(self.a * o.a, self.a * o.b + self.b * o.a)
    __rmul__ = __mul__
    def __repr__(self): return f"value {self.a}, derivative {self.b}"

x, y = 2.0, 3.0
def loss(w, b):  return (w * x + b - y) * (w * x + b - y)

print("seed w:", loss(Dual(0.5, 1.0), Dual(1.0, 0.0)))   # derivative = dL/dw
print("seed b:", loss(Dual(0.5, 0.0), Dual(1.0, 1.0)))   # derivative = dL/db  (a second pass!)

6. Reverse-mode AD: backpropagation

Idea: first do the forward pass and store all values. Then go backwards carrying the adjoint $\bar v = \partial L/\partial v$ of each node — "how much does the loss change if this node changes?" Start at the end with $\bar L = \partial L/\partial L = 1$. At each node, multiply the incoming adjoint by the node's local derivative and pass it to the node's inputs:

  1. $\bar L = 1$.
  2. $\bar e = \bar L\cdot\dfrac{\partial L}{\partial e} = 1\cdot 2e = -2$.
  3. $\bar{\hat y} = \bar e\cdot\dfrac{\partial e}{\partial \hat y} = -2\cdot1 = -2$.
  4. $\bar m = \bar{\hat y}\cdot1 = -2$ and $\bar b = \bar{\hat y}\cdot1 = -2$.
  5. $\bar w = \bar m\cdot\dfrac{\partial m}{\partial w} = -2\cdot x = -4$ (and $\bar x = \bar m\cdot w = -1$).

One backward sweep produced both $\partial L/\partial w = -4$ and $\partial L/\partial b = -2$ — and would produce a million gradients just as well. If a node feeds several later nodes, its adjoint is the sum of what comes back along each path (the multivariable chain rule). This is exactly the backpropagation algorithm. S. Linnainmaa (1970, MSc thesis, Helsinki) — reverse-mode AD; D. E. Rumelhart, G. E. Hinton & R. J. Williams, "Learning representations by back-propagating errors", Nature 323, 1986, 533–536.

Then the weight update

With $\eta = 0.1$: $w \leftarrow 0.5 - 0.1(-4) = 0.9$, $b \leftarrow 1 - 0.1(-2) = 1.2$. New prediction $0.9\cdot2 + 1.2 = 3.0$ = target. (One step is enough here only because the example is tiny and linear.)

7. Lab: step through the graph yourself

Lab · forward pass, backward pass, forward modeone press = one node
Blue: values (forward pass). Orange: gradients (backward pass). Green: tangents (forward mode). In reverse mode, one forward + one backward pass gives every gradient. In forward mode you need one complete pass per weight — switch the seed from w to b and count the passes. "Update weights" performs one gradient-descent step; press it a few times with different targets.

8. The cost: why backwards wins for training

Take a model with $n$ weights and one output, the loss (training always has one loss). Let one forward pass cost 1 unit.

methodcost of the full gradient$n = 3$$n = 10^6$$n = 10^9$
finite differences$n + 1$ passes (approximate)41 000 001$10^9$
forward-mode ADabout $2$–$3\,n$ (one tangent sweep per weight)≈ 8≈ $2.5\times10^6$≈ $2.5\times10^9$
reverse-mode ADabout 3–4 passes, whatever $n$ is≈ 3≈ 3≈ 3

This is the cheap gradient principle: for a scalar function, reverse mode delivers the entire gradient at a small constant multiple of the cost of evaluating the function itself (Baur & Strassen, 1983; Griewank & Walther, 2008). If one forward pass of a large network takes 0.1 s, the full gradient by finite differences of a billion-weight model would take about three years; by backpropagation, about 0.3 s.

Lab · how long does one gradient take?slide the number of weights
When is forward mode better?

The rule is: reverse mode costs a few passes per output; forward mode costs a few passes per input. Training has millions of inputs (weights) and one output (loss) → reverse. A function with one input and many outputs — for example the derivative of a whole velocity field with respect to a single time variable — favours forward mode. Reverse mode's price is memory: all intermediate values of the forward pass must be stored (or recomputed, "checkpointing").

9. Automatic differentiation inside a PINN: used twice

A PINN (Chapter 16) for, say, the heat equation $u_t = \alpha u_{xx}$ uses AD in two different directions:

  1. Derivatives with respect to the inputs $x$, $t$. The network $u_\theta(x,t)$ is a program in $x$ and $t$; AD gives $u_t$, $u_x$ and, by differentiating again, $u_{xx}$ — exactly, at any point, with no mesh. These enter the residual $r = u_t - \alpha u_{xx}$ at each collocation point.
  2. Derivatives with respect to the weights $\theta$. The loss $\mathcal L(\theta) = \frac1N\sum r^2 + \dots$ now contains $u_t$ and $u_{xx}$, so backpropagation must differentiate through the derivatives — derivatives of derivatives. Libraries allow this by keeping the graph of the first differentiation (create_graph=True in PyTorch).

Consequences you will meet in practice:

import torch
net = torch.nn.Sequential(torch.nn.Linear(2, 32), torch.nn.Tanh(), torch.nn.Linear(32, 1))
alpha = 0.1
xt = torch.rand(100, 2, requires_grad=True)          # 100 collocation points (x, t)

u = net(xt)                                           # forward propagation
# --- use 1: derivatives w.r.t. the INPUTS (x, t) ---
du = torch.autograd.grad(u, xt, torch.ones_like(u), create_graph=True)[0]
u_x, u_t = du[:, 0:1], du[:, 1:2]
u_xx = torch.autograd.grad(u_x, xt, torch.ones_like(u_x), create_graph=True)[0][:, 0:1]
residual = u_t - alpha * u_xx                         # heat equation residual
loss = (residual ** 2).mean()                         # (+ boundary/initial terms in practice)

# --- use 2: derivatives w.r.t. the WEIGHTS (backpropagation through the derivatives) ---
loss.backward()
print("gradient of the loss for the first-layer weights:", net[0].weight.grad.shape)

10. What kind of learning is a PINN?

Machine learning is usually divided by what information the learner gets:

typewhat is givengoaleveryday example
Supervisedinputs with correct answers (labels)predict the answer for new inputsphotos labelled "cat"/"dog"; house features → price
Unsupervisedinputs without answersfind structure: groups, patterns, compressed descriptionsgrouping customers by behaviour
Reinforcementan agent, actions and a reward signallearn a strategy that maximises long-term rewardgame-playing programs, robot control
Semi-superviseda few labels + many unlabelled inputsuse botha few diagnosed scans, many undiagnosed
Self-supervisedunlabelled data; the task is built from the data itselflearn representationspredict the next word (large language models)

Where do PINNs fit? Honest answer: they do not sit neatly in one box, and authors use different words.

Raissi, Perdikaris and Karniadakis themselves called the two settings "data-driven solution" and "data-driven discovery" of PDEs. The umbrella term today is physics-informed machine learning (Karniadakis et al., Nature Reviews Physics, 2021).

11. Build backpropagation yourself (40 lines)

class Value:
    def __init__(self, data, parents=(), op=""):
        self.data, self.grad, self.parents, self.op = data, 0.0, parents, op
        self._back = lambda: None
    def __add__(self, o):
        o = o if isinstance(o, Value) else Value(o)
        out = Value(self.data + o.data, (self, o), "+")
        def back(): self.grad += out.grad; o.grad += out.grad          # local derivative 1, 1
        out._back = back; return out
    def __sub__(self, o): return self + (o * -1 if isinstance(o, Value) else Value(-o))
    def __mul__(self, o):
        o = o if isinstance(o, Value) else Value(o)
        out = Value(self.data * o.data, (self, o), "*")
        def back(): self.grad += o.data * out.grad; o.grad += self.data * out.grad
        out._back = back; return out
    def backward(self):
        order, seen = [], set()
        def visit(v):                                   # topological order of the graph
            if id(v) not in seen:
                seen.add(id(v)); [visit(p) for p in v.parents]; order.append(v)
        visit(self); self.grad = 1.0                    # dL/dL = 1
        for v in reversed(order): v._back()             # walk the graph backwards

w, b = Value(0.5), Value(1.0)
x, y = 2.0, 3.0
e = w * x + b - y          # forward pass builds the graph
L = e * e
L.backward()               # backward pass fills every .grad
print("loss", L.data, " dL/dw =", w.grad, " dL/db =", b.grad)

This is the idea behind PyTorch's autograd, written small (in the spirit of A. Karpathy's "micrograd").

Key takeaways

Further reading