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.
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.
- three ways to differentiate on a computer — finite differences, symbolic, automatic — and why the third wins;
- the computational graph of a one-neuron network, with every number written out;
- the difference between forward propagation (computing the output) and backward propagation (computing gradients);
- forward-mode AD with dual numbers, and reverse-mode AD (backpropagation), step by step;
- why reverse mode is used for training: the cost with 1, 1 000 and 1 000 000 000 weights;
- how a PINN uses automatic differentiation twice;
- supervised, unsupervised and reinforcement learning — and where PINNs fit.
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$.
| method | how | result 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 |
| Symbolic | apply 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 runs | 2.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:
| step | operation | value | local 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.

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:
| step | value | derivative 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.
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:
- $\bar L = 1$.
- $\bar e = \bar L\cdot\dfrac{\partial L}{\partial e} = 1\cdot 2e = -2$.
- $\bar{\hat y} = \bar e\cdot\dfrac{\partial e}{\partial \hat y} = -2\cdot1 = -2$.
- $\bar m = \bar{\hat y}\cdot1 = -2$ and $\bar b = \bar{\hat y}\cdot1 = -2$.
- $\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.
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
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.
| method | cost of the full gradient | $n = 3$ | $n = 10^6$ | $n = 10^9$ |
|---|---|---|---|---|
| finite differences | $n + 1$ passes (approximate) | 4 | 1 000 001 | $10^9$ |
| forward-mode AD | about $2$–$3\,n$ (one tangent sweep per weight) | ≈ 8 | ≈ $2.5\times10^6$ | ≈ $2.5\times10^9$ |
| reverse-mode AD | about 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.
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:
- 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.
- 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=Truein PyTorch).
Consequences you will meet in practice:
- Cost grows with derivative order. Each extra derivative in the PDE adds another layer of differentiation; a PINN step for a second-order PDE typically costs several times a plain network step.
- High dimensions hurt. The Laplacian $\sum_{i=1}^{d}\partial^2u/\partial x_i^2$ needs $d$ second derivatives; for $d$ in the hundreds this dominates. Research on cheaper estimators is active, e.g. Z. Shi, Z. Hu, M. Lin & K. Kawaguchi, "Stochastic Taylor derivative estimator: efficient amortization for arbitrary differential operators", NeurIPS 2024.
- Activations must be smooth enough. ReLU has $u_{xx} = 0$ almost everywhere, so it cannot represent a second-order residual — use tanh, sine or similar (Chapter 12).
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:
| type | what is given | goal | everyday example |
|---|---|---|---|
| Supervised | inputs with correct answers (labels) | predict the answer for new inputs | photos labelled "cat"/"dog"; house features → price |
| Unsupervised | inputs without answers | find structure: groups, patterns, compressed descriptions | grouping customers by behaviour |
| Reinforcement | an agent, actions and a reward signal | learn a strategy that maximises long-term reward | game-playing programs, robot control |
| Semi-supervised | a few labels + many unlabelled inputs | use both | a few diagnosed scans, many undiagnosed |
| Self-supervised | unlabelled data; the task is built from the data itself | learn representations | predict 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.
- Forward problem with no measurements (solve $y' = x$, $y(0) = 0$): no labelled data at all. The "teacher" is the equation residual, which is computed from the network itself. In the labels sense this is unsupervised (or "self-supervised by physics"); the initial and boundary conditions act like a handful of labels.
- With measurements (the pendulum lab): a few labelled points plus physics at many unlabelled points — structurally like semi-supervised learning, with the equation as the link.
- Inverse problems (learn $g/L$): supervised data fitting regularised by physics.
- Not reinforcement learning: there is no agent, action or reward. (Reinforcement learning has, however, been tried for choosing collocation points or controlling PDE systems — a research topic.)
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").
- Forward propagation computes values and the loss; backward propagation computes gradients. Every training step does both.
- AD differentiates each elementary operation exactly and chains the numbers — no step size, no formula blow-up.
- Forward mode: one pass per input. Reverse mode: one pass per output. Training has one output (the loss) → reverse mode = backpropagation.
- The full gradient costs a small constant times one forward pass, whatever the number of weights; the price is memory.
- PINNs use AD twice: w.r.t. inputs to build the residual, w.r.t. weights to train.
- PINNs mix supervised and unsupervised ideas; they are not reinforcement learning.
Further reading
- A. Griewank & A. Walther, Evaluating Derivatives: Principles and Techniques of Algorithmic Differentiation, 2nd ed., SIAM, 2008.
- A. G. Baydin et al., "Automatic differentiation in machine learning: a survey", JMLR 18(153), 2018.
- W. Baur & V. Strassen, "The complexity of partial derivatives", Theoretical Computer Science 22(3), 1983, 317–330.
- C. C. Margossian, "A review of automatic differentiation and its efficient implementation", WIREs Data Mining and Knowledge Discovery 9(4), 2019, e1305.
- M. Blondel & V. Roulet, The Elements of Differentiable Programming, arXiv:2403.14606, 2024.