TExcelTAD
Home › Math for Deep Learning & LLMs › Computational Graphs and the Chain Rule

Computational Graphs and the Chain Rule

Backpropagation is the chain rule of calculus applied systematically to a computational graph: a directed acyclic graph whose nodes are elementary operations and whose edges carry values. Drawing the graph turns gradient computation into a mechanical procedure: each node only needs to know its own local derivative. The calculus is reviewed in Backpropagation and Backpropagation and Autodiff.

Building the graph

Take f(x,y,z)=(x+y) zf(x, y, z) = (x + y)\,z. Introduce an intermediate q=x+yq = x + y, so f=qzf = qz. Every operation is a node:

x,y→+q,q,z→×fx, y \xrightarrow{+} q, \qquad q, z \xrightarrow{\times} f

The forward pass evaluates nodes in topological order. The backward pass visits them in reverse, starting from ∂f∂f=1\frac{\partial f}{\partial f} = 1, and each node multiplies the incoming gradient (the upstream gradient) by its local gradient:

∂f∂z=q,∂f∂q=z,∂f∂x=∂f∂q∂q∂x=z⋅1\frac{\partial f}{\partial z} = q, \qquad \frac{\partial f}{\partial q} = z, \qquad \frac{\partial f}{\partial x} = \frac{\partial f}{\partial q}\frac{\partial q}{\partial x} = z \cdot 1
python · try it yourself
x, y, z = -2.0, 5.0, -4.0
# forward
q = x + y
f = q * z
# backward
df = 1.0
dq, dz = z * df, q * df          # multiply node: swap the inputs
dx, dy = 1.0 * dq, 1.0 * dq      # add node: pass the gradient through
print(f"f = {f}")
print(f"df/dx = {dx}, df/dy = {dy}, df/dz = {dz}")
f = -12.0
df/dx = -4.0, df/dy = -4.0, df/dz = 3.0

Gate patterns

The local rules of a few nodes cover most of backprop:

Node Forward Backward (upstream gg)
add a+ba + b both inputs receive gg
multiply abab aa receives gbgb, bb receives gaga
max max⁡(a,b)\max(a, b) the larger input receives gg, the other 0
copy (fan-out) aa used twice the gradients from both uses add
matrix multiply XWTXW^T ∂/∂X=GW\partial/\partial X = GW, ∂/∂W=GTX\partial/\partial W = G^TX

The fan-out rule is the multivariate chain rule: if a value feeds several nodes, its total derivative is the sum over all paths.

A sigmoid neuron, node by node

f(w,x)=σ(w0x0+w1x1+w2)f(\mathbf{w}, \mathbf{x}) = \sigma(w_0x_0 + w_1x_1 + w_2) breaks into multiplies, adds, a negation, an exponential, a +1+1 and a reciprocal. Backprop through all of them gives the same answer as the shortcut σ′(a)=σ(a)(1−σ(a))\sigma'(a) = \sigma(a)(1 - \sigma(a)): you may group nodes into bigger ones whenever their local derivative is simple.

python · try it yourself
import numpy as np

w0, x0, w1, x1, w2 = 2.0, -1.0, -3.0, -2.0, -3.0
# forward, one elementary node at a time
a = w0 * x0 + w1 * x1 + w2
n1 = -a; n2 = np.exp(n1); n3 = 1 + n2; f = 1 / n3
# backward, one node at a time
d3 = -1 / n3**2          # d(1/u)/du
d2 = d3 * 1              # +1
d1 = d2 * np.exp(n1)     # exp
da = d1 * -1             # negation
print(f"f = {f:.4f}")
print(f"node-by-node da = {da:.4f}, shortcut f(1-f) = {f * (1 - f):.4f}")
print(f"dw0 = {da * x0:.4f}, dx0 = {da * w0:.4f}, dw1 = {da * x1:.4f}, dx1 = {da * w1:.4f}, dw2 = {da:.4f}")
f = 0.7311
node-by-node da = 0.1966, shortcut f(1-f) = 0.1966
dw0 = -0.1966, dx0 = 0.3932, dw1 = -0.3932, dx1 = -0.5898, dw2 = 0.1966

Why reverse order is efficient

For a scalar loss and nn parameters, one backward pass gives all nn partial derivatives for a cost of a small constant times one forward pass. Computing them one at a time by finite differences would take nn forward passes. This is the reason networks with billions of parameters can be trained at all (Forward and Reverse Mode).

In software

  • PyTorch builds the graph dynamically as operations run ("define by run"); loss.backward() walks it in reverse. tensor.grad_fn shows the node that produced a tensor.
  • JAX traces a function into a graph (a jaxpr) and transforms it with grad.
  • torch.autograd.gradcheck compares backprop to finite differences.

Exercises

Exercise 1: Fan-out

f(x)=x⋅xf(x) = x \cdot x written as a multiply node with both inputs from the same xx. Use the gate rules to find f′(x)f'(x).

Answer

2x2x.

Solution

The multiply node sends g⋅xg \cdot x to each input; both inputs are the same variable, so the contributions add: x+x=2xx + x = 2x.

Exercise 2: Max gate

f=max⁡(x,y)⋅zf = \max(x, y) \cdot z with x=3x = 3, y=1y = 1, z=2z = 2. Find all three partial derivatives.

Answer

∂f/∂x=2\partial f/\partial x = 2, ∂f/∂y=0\partial f/\partial y = 0, ∂f/∂z=3\partial f/\partial z = 3.

Solution

m=max⁡(3,1)=3m = \max(3, 1) = 3. The multiply node gives ∂f/∂m=z=2\partial f/\partial m = z = 2 and ∂f/∂z=m=3\partial f/\partial z = m = 3. The max routes 2 to xx (the larger input) and 0 to yy.

Exercise 3: Check against finite differences (code)

For f(x,y)=(x+2y)2sin⁡(x)f(x, y) = (x + 2y)^2\sin(x), backpropagate by hand at (1,0.5)(1, 0.5) and compare with central differences.

Answer

Both give ∂f/∂x≈5.5271\partial f/\partial x \approx 5.5271 and ∂f/∂y≈6.7318\partial f/\partial y \approx 6.7318.

Solution

With q=x+2yq = x + 2y, s=q2s = q^2, f=ssin⁡xf = s\sin x: ∂f/∂s=sin⁡x\partial f/\partial s = \sin x, ∂f/∂q=2qsin⁡x\partial f/\partial q = 2q\sin x, so ∂f/∂y=4qsin⁡x\partial f/\partial y = 4q\sin x and ∂f/∂x=2qsin⁡x+scos⁡x\partial f/\partial x = 2q\sin x + s\cos x (fan-out of xx).

python · try it yourself
import numpy as np
x, y = 1.0, 0.5
q = x + 2 * y; s = q**2; f = s * np.sin(x)
ds = np.sin(x); dq = ds * 2 * q
dx = dq * 1 + s * np.cos(x); dy = dq * 2
F = lambda x, y: (x + 2 * y)**2 * np.sin(x); h = 1e-6
print(round(dx, 4), round(dy, 4), round((F(x + h, y) - F(x - h, y)) / (2 * h), 4), round((F(x, y + h) - F(x, y - h)) / (2 * h), 4))
5.5271 6.7318 5.5271 6.7318

Test yourself

In the backward pass, an add node…

  1. swaps its inputs
  2. passes the upstream gradient unchanged to both inputs
  3. sends 0 to both inputs
  4. doubles the gradient

When a value is used by two later nodes, its gradient is…

  1. the larger of the two incoming gradients
  2. the sum of the incoming gradients
  3. the product of the incoming gradients
  4. always zero

Reverse-mode differentiation of a scalar loss with nn parameters costs about…

  1. nn forward passes
  2. a small constant times one forward pass
  3. n2n^2 forward passes
  4. nothing