The Chain Rule Applied to Computation Graphs
Draw a calculation as a graph, run a forward and backward pass by hand, and build a tiny automatic differentiator in Python.
Key takeaways
- Each node in a computation graph only needs to know the derivative of its own operation.
- Derivatives multiply along a path and add across different paths.
- A forward pass computes and stores values; a backward pass visits nodes in reverse order and accumulates gradients.
- One backward pass yields the derivative of a scalar loss with respect to every input and parameter.
- Long chains multiply many factors, which is the source of vanishing and exploding gradients.
A computation graph breaks a calculation into small operations, with each result feeding the next. The chain rule then gives you every derivative: multiply local derivatives along a path, and add the results when several paths connect the same two quantities.
Running that rule from the output back toward the inputs is backpropagation. It is how deep learning libraries obtain gradients for millions or billions of parameters.
The chain rule in one line
If z depends on y and y depends on x, then:
dz/dx = (dz/dy) · (dy/dx) With y = 3x and z = y², at x = 2 you get y = 6, dz/dy = 12 and dy/dx = 3, so dz/dx = 36. Check by substitution: z = 9x², with derivative 18x = 36.
A graph with a loss at the end
Consider a one-weight model with squared error, written as separate steps. Let x = 2, w = 3, b = −1 and y = 4.
forward pass
u = w · x = 6
z = u + b = 5
e = z − y = 1
L = e² = 1 Now walk backward. Start with dL/dL = 1 and apply one local rule per step.
backward pass
dL/de = 2e = 2
dL/dz = dL/de · 1 = 2
dL/dy = dL/de · (−1) = −2
dL/du = dL/dz · 1 = 2
dL/db = dL/dz · 1 = 2
dL/dw = dL/du · x = 4
dL/dx = dL/du · w = 6 Every quantity received its derivative exactly once, and each step used only the incoming gradient and values saved from the forward pass.
A logistic neuron as a graph
Now take two inputs and a probability output: z = w₁x₁ + w₂x₂ + b, p = σ(z) and L = −ln p, for an example whose label is 1. Here σ is the sigmoid and ln the natural logarithm.
Use x = (1, 2), w = (0.5, −0.25) and b = 0.
forward: z = 0.5 − 0.5 + 0 = 0, p = 0.5, L = ln 2 ≈ 0.693
backward: dL/dp = −1/p = −2
dp/dz = p (1 − p) = 0.25
dL/dz = −2 · 0.25 = −0.5
dL/dw₁ = −0.5 · x₁ = −0.5
dL/dw₂ = −0.5 · x₂ = −1.0
dL/db = −0.5
dL/dx₁ = −0.5 · w₁ = −0.25
dL/dx₂ = −0.5 · w₂ = 0.125 Notice how much is shared. The value dL/dz is computed once and then reused for five derivatives. That reuse is the entire efficiency of backpropagation: it is dynamic programming on the graph, storing partial results that many paths pass through.
Local rules for common operations
| Operation | What flows back to each input, given gradient g at the output |
|---|---|
| c = a + b | g to a, g to b |
| c = a · b | g · b to a, g · a to b |
| c = a − b | g to a, −g to b |
| c = exp(a) | g · c to a |
| c = ln a, with a > 0 | g / a to a |
| c = max(a, b), with a ≠ b | g to the larger, 0 to the other |
| c = ReLU(a), with a ≠ 0 | g if a > 0, otherwise 0 |
Addition copies the gradient. Multiplication swaps the inputs. Maximum routes the gradient to the winner. At exact ties and at zero for ReLU the derivative does not exist, and libraries pick a convention.
When paths branch and rejoin
Let q = x + y and r = x · q, at x = 3 and y = 2. The forward values are q = 5 and r = 15. Here x reaches r by two routes.
dr/dq = x = 3
dr/dx, direct use = q = 5
dr/dx, through q = 3 · 1 = 3
dr/dx, total = 8
dr/dy, through q = 3 · 1 = 3 Expanding r = x² + xy confirms it: ∂r/∂x = 2x + y = 8 and ∂r/∂y = x = 3.
This adding rule is the one implementations must get right. Weight sharing, as in convolutions and recurrent networks, is branching on a large scale: one parameter is used many times, and its gradient is the sum over all uses. Backpropagation through time is exactly this on an unrolled sequence.
Nodes that handle arrays
In real models nodes pass matrices. The full table of partial derivatives for a matrix operation, its Jacobian, would be enormous, so backward passes compute only its product with the incoming gradient.
For Y = XW with X of shape (n, d) and W of shape (d, k), let G be the gradient of the scalar loss with respect to Y, shape (n, k).
gradient for W = Xᵀ G shape (d, k)
gradient for X = G Wᵀ shape (n, d) Shapes provide a check: a gradient always has the same shape as the thing it belongs to. If an input was broadcast during the forward pass, its gradient must be summed over the repeated axes. See Jacobians and vector-Jacobian products.
Why backward is the efficient direction
A training loss is a single number that depends on very many parameters. One reverse sweep produces all the derivatives at a cost that is a small multiple of the forward pass in arithmetic.
Working forward from each parameter would need roughly one pass per parameter. The price of reverse mode is memory, because many intermediate values must be kept until the backward pass reaches them. Activation checkpointing discards some and recomputes them later.
Long chains
Along a deep path, the gradient is a product of many local factors. The sigmoid function has a derivative of at most 0.25. Ten such factors, ignoring the weights, are at most 0.25¹⁰, about 0.00000095. Weights can offset or worsen this, and products above 1 can grow without bound.
A residual connection computes y = x + f(x), so the local derivative is 1 + f′(x). The added 1 gives the gradient a direct route backward. It helps considerably, although it does not guarantee well-behaved gradients. More remedies appear in vanishing and exploding gradients.
A tiny differentiator
This short class supports addition and multiplication of single numbers. It records parents with local derivatives, orders the nodes and accumulates with +=.
class Value:
def __init__(self, data, parents=()):
self.data, self.grad, self.parents = data, 0.0, parents
def __add__(self, other):
return Value(self.data + other.data, ((self, 1.0), (other, 1.0)))
def __mul__(self, other):
return Value(self.data * other.data,
((self, other.data), (other, self.data)))
def backward(self):
order, seen = [], set()
def visit(node):
if node not in seen:
seen.add(node)
for parent, _ in node.parents:
visit(parent)
order.append(node)
visit(self)
self.grad = 1.0
for node in reversed(order):
for parent, local in node.parents:
parent.grad += node.grad * local
x, y = Value(3.0), Value(2.0)
r = x * (x + y)
r.backward()
print(r.data, x.grad, y.grad) # 15.0 8.0 3.0 The ordering matters. A node must receive all contributions from later nodes before it passes its own gradient on. Libraries add array support, many more operations and ways to switch recording off.
Choosing where to cut the nodes
You can draw the same calculation with fine or coarse nodes. A sigmoid can be four small operations or one node with the local derivative p(1 − p). The derivatives agree in exact arithmetic, but the numerics may not.
The logistic loss is the standard case. Computing p first and then ln p fails when p rounds to 0, giving an infinite loss. A combined node that works from the score z avoids this, using a rearranged formula for label y.
L = max(z, 0) − z · y + ln(1 + exp(−|z|))
dL/dz = σ(z) − y At z = 0 and y = 1 the first line gives 0 − 0 + ln 2, matching the example above. At z = −1000 and y = 1 it gives 1000 without overflow, with a derivative of essentially −1. This is why many libraries offer a loss that accepts raw scores. Pass it scores, not probabilities, and check which it expects.
To test any custom node, compare its backward rule with central finite differences in double precision, at several random inputs and away from kinks. A node can have a correct forward value and a wrong derivative, and training may still creep downhill enough to hide the mistake.
Mistakes the graph explains
- Stale gradients. Many libraries add new gradients to whatever is stored, so you clear them between updates unless you intend to accumulate.
- A cut graph. Converting a value to a plain number, or detaching it, removes the path, and upstream parameters get no gradient from it.
- Overwritten values. Changing an array in place can destroy a value the backward pass needs.
- Non-differentiable steps. Rounding or taking an index of the maximum gives zero or no useful gradient.
- Retained history. Storing loss objects across iterations can keep whole graphs in memory.
When a parameter does not learn, trace its path to the loss and find where the gradient becomes zero or disappears. A tiny network worked with numbers is a good exercise for doing that.
Common questions
Is backpropagation the same as gradient descent?
No. Backpropagation computes derivatives. Gradient descent, or another optimizer, uses them to change parameters.
Does the graph have to be fixed in advance?
No. Some systems build it as your Python code runs, so loops and branches become part of that particular graph. Others trace or compile it first. Check how your library handles data-dependent control flow.