22.3 The Chain Rule on Computational Graphs

Every training step in this book begins with a single call, backward() or grad, that returns the slope of the loss with respect to every weight in the network. In Section 22.2 we saw what those slopes mean: together they form the gradient, the vector that predicts how the loss changes under any small joint move of the parameters. What we have not yet explained is how a program computes millions of these slopes in roughly the time it takes to evaluate the network a few times. The naive approach, nudging one weight at a time and rerunning the network for each perturbation, requires a separate pass per weight and quickly becomes infeasible.

The chain rule does vastly better, and the reason is easy to see before writing down any algebra. A neural network is a deep composition of simple functions, so the derivatives with respect to its many weights share almost all of their work: every weight's influence has to travel through the later layers to reach the loss. A single nested formula hides this shared structure, whereas a computational graph lays it bare: one node for each intermediate value and one directed edge for each direct dependence. Viewed on a graph, the chain rule becomes a sum over paths, and exploiting the shared work amounts to choosing how to group that sum. Grouping the paths from the output backward yields the derivative with respect to every input in a single pass. That grouping is backpropagation.

To make every step concrete and easy to verify by hand, we work on small graphs of scalar variables with integer values throughout. The entire development rests on one fact from Section 22.2: near any point where a function is differentiable, its change is approximated by the dot product of the step with its gradient, the linear model of Section 22.2.1.2. Extending the idea to layers that map vectors to vectors, and measuring its computational cost on real networks, comes in the two sections that follow.

22.3.1 The Chain Rule as a Sum over Paths#

22.3.1.1 A Graph of Scalars#

Let us start with a concrete example small enough to trace completely by hand. Four scalar inputs w,x,y,zw, x, y, z feed through two layers of intermediate variables to produce a single scalar output:

f(u,v)=(u+v)2,u(a,b)=(a+b)2,v(a,b)=(a−b)2,a(w,x,y,z)=(w+x+y+z)2,b(w,x,y,z)=(w+x−y−z)2.(22.3.1)\begin{aligned} f(u, v) & = (u+v)^{2}, \\ u(a, b) & = (a+b)^{2}, \qquad v(a, b) = (a-b)^{2}, \\ a(w, x, y, z) & = (w+x+y+z)^{2}, \qquad b(w, x, y, z) = (w+x-y-z)^2. \end{aligned} \tag{22.3.1}

These equations define a directed acyclic graph (Figure 22.3.1), where each node holds an intermediate value and each arrow indicates a direct functional dependence. There is nothing special about the squaring operations; we choose them simply because they keep all intermediate values and derivatives exact integers. Throughout this section, ff denotes the scalar output of the graph under study.

Figure 22.3.1:

The dependency graph of (22.3.1): each node represents a variable and each directed edge represents a direct functional dependence.

22.3.1.2 Two Paths through One Step#

Before tackling the whole graph, consider just its final composite step, f(u(a,b),v(a,b))f(u(a,b), v(a,b)), and ask how ff responds when we nudge aa by a small amount ϵ\epsilon. Both intermediate nodes feel the perturbation according to their partial derivatives: uu shifts to u+ϵ∂u∂au + \epsilon\frac{\partial u}{\partial a}, and vv shifts to v+ϵ∂v∂av + \epsilon\frac{\partial v}{\partial a}. Substituting both shifts into the first-order linear approximation (Section 22.2.1.2) of ff yields

f ⁣(u+ϵ∂u∂a, v+ϵ∂v∂a)≈f(u,v)+ϵ[∂f∂u∂u∂a+∂f∂v∂v∂a].f\!\left(u + \epsilon\tfrac{\partial u}{\partial a},\, v + \epsilon\tfrac{\partial v}{\partial a}\right) \approx f(u, v) + \epsilon\left[\frac{\partial f}{\partial u}\frac{\partial u}{\partial a} + \frac{\partial f}{\partial v}\frac{\partial v}{\partial a}\right].

Reading off the coefficient of ϵ\epsilon gives the derivative of the composite function with respect to aa, which is the multivariable chain rule:

dfda=∂f∂u∂u∂a+∂f∂v∂v∂a.\frac{\mathrm{d} f}{\mathrm{d} a} = \frac{\partial f}{\partial u}\frac{\partial u}{\partial a} + \frac{\partial f}{\partial v}\frac{\partial v}{\partial a}.

Notice the two different symbols for differentiation; we will keep them strictly separate from here on. The curly ∂\partial denotes the derivative of a single node's defining function with respect to one of its direct arguments, holding its other arguments fixed. The upright d\mathrm{d} denotes the total derivative df/da\mathrm{d}f/\mathrm{d}a, which allows every variable downstream of aa to respond. (For an input node, the total derivative coincides with the ordinary partial derivative of ff viewed as a function of the inputs alone.) Geometrically, there are two directed paths by which aa influences ff, namely a→u→fa \to u \to f and a→v→fa \to v \to f. Each path contributes the product of the derivatives along its edges, and the total derivative sums those contributions across all paths.

This derivation mirrors the one-variable proof of the chain rule (Section 22.1.2): we feed the linear change of the inner functions into the linear model of the outer one. Because two variables move simultaneously, however, ff must be differentiable at (u,v)(u, v), not merely possess partial derivatives. Recall the counterexample 2xy/(x2+y2)2xy/(x^2+y^2) from Section 22.2.1.2: along the diagonal x=y=tx = y = t, both partial derivatives vanish at the origin, so the chain rule would predict a derivative of 00 at t=0t = 0, yet the function jumps discontinuously from 00 to 11 there.

22.3.1.3 Edge Derivatives and Total Derivatives#

The same reasoning extends by induction to any directed acyclic graph. Define the edge derivative of a node with respect to one of its parents as the partial derivative of that node's function with respect to that parent, with all other parents held fixed. Then the total derivative of an output ff with respect to an input xx is

dfdx=∑directed paths x→⋯→f    ∏edges on the path(edge derivative).(22.3.2)\frac{\mathrm{d} f}{\mathrm{d} x} = \sum_{\text{directed paths } x \to \cdots \to f} \;\; \prod_{\text{edges on the path}} (\text{edge derivative}). \tag{22.3.2}

In words, each directed path from xx to ff multiplies the local rates of change along its edges, and the total derivative adds those path products together.

A graph with a skip connection makes it clear why edge derivatives and total derivatives must never be confused. Consider the five-node system

p(x,y)=x+y,q(x,y)=x−y,r(p)=p2,s(q)=q2,f(r,p,s)=r+p+s.(22.3.3)\begin{aligned} p(x, y) & = x + y, \qquad q(x, y) = x - y, \\ r(p) & = p^2, \qquad s(q) = q^2, \\ f(r, p, s) & = r + p + s. \end{aligned} \tag{22.3.3}

Here ff depends on rr and ss, and also directly on pp through a skip edge (Figure 22.3.2). Consequently, the input yy reaches ff along three distinct paths: y→p→r→fy \to p \to r \to f, the shortcut y→p→fy \to p \to f, and y→q→s→fy \to q \to s \to f. The local edge derivatives are ∂f/∂r=∂f/∂p=∂f/∂s=1\partial f/\partial r = \partial f/\partial p = \partial f/\partial s = 1, ∂r/∂p=2p\partial r/\partial p = 2p, ∂s/∂q=2q\partial s/\partial q = 2q, ∂p/∂y=1\partial p/\partial y = 1, and ∂q/∂y=−1\partial q/\partial y = -1. Summing the three path products gives

dfdy=1⋅2p⋅1⏟y→p→r→f+1⋅1⏟y→p→f+1⋅2q⋅(−1)⏟y→q→s→f=2p+1−2q=1+4y.\begin{aligned} \frac{\mathrm{d} f}{\mathrm{d} y} &= \underbrace{1 \cdot 2p \cdot 1}_{y \to p \to r \to f} + \underbrace{1 \cdot 1}_{y \to p \to f} + \underbrace{1 \cdot 2q \cdot (-1)}_{y \to q \to s \to f} \\ &= 2p + 1 - 2q = 1 + 4y. \end{aligned}

We can check this directly by substituting everything into ff: f=(x+y)2+(x+y)+(x−y)2f = (x+y)^2 + (x+y) + (x-y)^2, whose derivative with respect to yy is indeed 1+4y1 + 4y. At (x,y)=(1,2)(x, y) = (1, 2), we have p=3p = 3 and q=−1q = -1, so the three paths contribute 6+1+2=9=1+4⋅26 + 1 + 2 = 9 = 1 + 4 \cdot 2. Notice the sharp distinction at node pp: the edge derivative ∂f/∂p\partial f/\partial p is just 11 (holding rr fixed), whereas the total derivative df/dp\mathrm{d}f/\mathrm{d}p accounts for both the skip edge and the indirect route through rr, giving 2p+1=72p + 1 = 7. Confusing these two quantities is the single most common mistake when applying the multivariable chain rule.

Figure 22.3.2:

The dependency graph of (22.3.3): the input yy reaches ff by three paths, namely y→p→r→fy\to p\to r\to f, the skip edge y→p→fy\to p\to f, and y→q→s→fy\to q\to s\to f.

This path-sum viewpoint also explains how gradients travel through deep architectures. Mechanisms that open or close paths, such as the gates in an LSTM (Section 12.1) or the skip connections in a residual network (Section 7.4), shape learning directly by controlling which paths carry gradient signal back to earlier layers.

22.3.2 Backpropagation#

As a mathematical identity, the sum over paths (22.3.2) is completely general: it gives every derivative of every computational graph. As a literal algorithm, however, it is hopeless, because the number of paths can grow exponentially with depth. Even a simple chain of mm stages with two parallel nodes per stage already contains 2m2^m paths from start to finish. Fortunately, those paths overlap heavily, and any sub-product shared by many paths needs to be computed only once. The order in which we factor out those shared sub-products determines the computational cost.

22.3.2.1 Forward Mode#

Let us compare two ways of factoring the sum on our four-input function (22.3.1) at the point (w,x,y,z)=(1,1,−2,1)(w, x, y, z) = (1, 1, -2, 1). A forward pass evaluates the nodes in topological order: a=12=1a = 1^2 = 1, b=32=9b = 3^2 = 9, u=102=100u = 10^2 = 100, v=(−8)2=64v = (-8)^2 = 64, and f=1642=26896f = 164^2 = 26896. From these node values we read off all the local edge derivatives:

∂f∂u=∂f∂v=2(u+v)=328,∂u∂a=∂u∂b=2(a+b)=20,∂v∂a=2(a−b)=−16,∂v∂b=−2(a−b)=16,∂a∂w=∂a∂x=∂a∂y=∂a∂z=2(w+x+y+z)=2,∂b∂w=∂b∂x=2(w+x−y−z)=6,∂b∂y=∂b∂z=−6.\begin{aligned} \frac{\partial f}{\partial u} = \frac{\partial f}{\partial v} &= 2(u+v) = 328, \\ \frac{\partial u}{\partial a} = \frac{\partial u}{\partial b} &= 2(a+b) = 20, \\ \frac{\partial v}{\partial a} = 2(a-b) &= -16, \qquad \frac{\partial v}{\partial b} = -2(a-b) = 16, \\ \frac{\partial a}{\partial w} = \frac{\partial a}{\partial x} = \frac{\partial a}{\partial y} = \frac{\partial a}{\partial z} &= 2(w+x+y+z) = 2, \\ \frac{\partial b}{\partial w} = \frac{\partial b}{\partial x} = 2(w+x-y-z) &= 6, \qquad \frac{\partial b}{\partial y} = \frac{\partial b}{\partial z} = -6. \end{aligned}

Each edge derivative is a local number computed solely from a node and its immediate parents.

To find df/dw\mathrm{d}f/\mathrm{d}w, notice that all four paths from ww to ff pass first through aa or bb and then through uu or vv. Factoring the paths from the input ww forward through the graph gives

dfdw=∂f∂u(∂u∂a∂a∂w+∂u∂b∂b∂w)+∂f∂v(∂v∂a∂a∂w+∂v∂b∂b∂w)=328 (20⋅2+20⋅6)+328 (−16⋅2+16⋅6)=328⋅224=73472.\begin{aligned} \frac{\mathrm{d} f}{\mathrm{d} w} &= \frac{\partial f}{\partial u}\Bigl(\frac{\partial u}{\partial a}\frac{\partial a}{\partial w} + \frac{\partial u}{\partial b}\frac{\partial b}{\partial w}\Bigr) + \frac{\partial f}{\partial v}\Bigl(\frac{\partial v}{\partial a}\frac{\partial a}{\partial w} + \frac{\partial v}{\partial b}\frac{\partial b}{\partial w}\Bigr) \\ &= 328\,(20\cdot 2 + 20 \cdot 6) + 328\,(-16 \cdot 2 + 16 \cdot 6) \\ &= 328 \cdot 224 = 73472. \end{aligned}

The two parenthesized sums are simply du/dw=160\mathrm{d}u/\mathrm{d}w = 160 and dv/dw=64\mathrm{d}v/\mathrm{d}w = 64, the total derivatives of the intermediate nodes with respect to ww. Propagating the sensitivity to one input forward through the graph in this way is called forward mode. We can verify this calculation in plain Python:

w, x, y, z = 1, 1, -2, 1
# Forward pass: node values
a, b = (w + x + y + z)**2, (w + x - y - z)**2
u, v = (a + b)**2, (a - b)**2
f = (u + v)**2
print('a, b, u, v, f =', a, b, u, v, f)

# Edge derivatives
df_du, df_dv = 2*(u + v), 2*(u + v)
du_da, du_db, dv_da, dv_db = 2*(a + b), 2*(a + b), 2*(a - b), -2*(a - b)
da_dw, db_dw = 2*(w + x + y + z), 2*(w + x - y - z)

# Forward mode: push the dependence on w through the graph
du_dw, dv_dw = du_da*da_dw + du_db*db_dw, dv_da*da_dw + dv_db*db_dw
df_dw = df_du*du_dw + df_dv*dv_dw
print('df/dw =', df_dw)
a, b, u, v, f = 1 9 100 64 26896
df/dw = 73472

Forward mode returns df/dw=73472\mathrm{d}f/\mathrm{d}w = 73472, but none of its intermediate derivatives can be reused for xx, yy, or zz: both du/dw\mathrm{d}u/\mathrm{d}w and dv/dw\mathrm{d}v/\mathrm{d}w are tied to ww alone. Because training a neural network requires the derivative of a single scalar loss with respect to every parameter, computing them one input at a time leaves most of the shared structure unused.

22.3.2.2 Adjoints and the Backward Pass#

The remedy is to reverse the perspective: keep the output fixed rather than the input. Forward mode fixed one input and asked how every downstream node responds to it. Now we fix the single output ff and ask how it responds to every upstream node. Define the adjoint nˉ\bar{n} of a node nn as the total derivative df/dn\mathrm{d}f/\mathrm{d}n of the output with respect to nn: the sum of the edge-derivative products over all directed paths from nn to ff. Every such path must leave nn through one of its immediate children cc, and the remaining paths from cc to ff sum to cˉ\bar{c}. Grouping the path sum (22.3.2) by this first edge turns it into a simple recursion:

fˉ=1,nˉ=∑children c of ncˉ ∂c∂n.(22.3.4)\bar{f} = 1, \qquad \bar{n} = \sum_{\text{children } c \text{ of } n} \bar{c}\,\frac{\partial c}{\partial n}. \tag{22.3.4}

Only local edge derivatives and the adjoints of downstream nodes appear on the right-hand side. Starting from fˉ=1\bar f = 1 and visiting the nodes in reverse topological order, every child's adjoint is already known by the time we need it. On the skip-edge graph (22.3.3), for instance, the recursion gives rˉ=1\bar r = 1 and pˉ=rˉ⋅2p+fˉ⋅1=7\bar p = \bar r \cdot 2p + \bar f \cdot 1 = 7, matching the total derivative we found earlier. Applying the same sweep to our four-input graph gives:

  • uˉ=vˉ=328\bar{u} = \bar{v} = 328;
  • aˉ=uˉ⋅20+vˉ⋅(−16)=1312\bar{a} = \bar{u}\cdot 20 + \bar{v}\cdot(-16) = 1312 and bˉ=uˉ⋅20+vˉ⋅16=11808\bar{b} = \bar{u}\cdot 20 + \bar{v}\cdot 16 = 11808;
  • wˉ=xˉ=aˉ⋅2+bˉ⋅6=73472\bar{w} = \bar{x} = \bar{a}\cdot 2 + \bar{b}\cdot 6 = 73472 and yˉ=zˉ=aˉ⋅2−bˉ⋅6=−68224\bar{y} = \bar{z} = \bar{a}\cdot 2 - \bar{b}\cdot 6 = -68224.

A single backward pass thus produces the partial derivatives with respect to all four inputs at once (Figure 22.3.3). Let us run this backward sweep in Python, reusing the edge derivatives from the previous cell.

Figure 22.3.3:

(a) The forward pass records every node value and local edge derivative. (b) The backward pass accumulates adjoints starting from fˉ=1\bar f = 1, giving aˉ=328⋅20+328⋅(−16)=1312\bar a = 328\cdot 20 + 328\cdot(-16) = 1312 and wˉ=1312⋅2+11808⋅6=73472\bar w = 1312\cdot 2 + 11808\cdot 6 = 73472.

da_dy, db_dy = 2*(w + x + y + z), -2*(w + x - y - z)  # also for x, z
# Backward pass: adjoints from the output toward the inputs
u_bar, v_bar = df_du, df_dv
a_bar = u_bar*du_da + v_bar*dv_da
b_bar = u_bar*du_db + v_bar*dv_db
print(f'adjoints: u {u_bar}, v {v_bar}, a {a_bar}, b {b_bar}')
w_bar = a_bar*da_dw + b_bar*db_dw  # x enters a, b like w
y_bar = a_bar*da_dy + b_bar*db_dy  # z enters a, b like y
print('gradient:', {'w': w_bar, 'x': w_bar, 'y': y_bar, 'z': y_bar})
adjoints: u 328, v 328, a 1312, b 11808
gradient: {'w': 73472, 'x': 73472, 'y': -68224, 'z': -68224}

The derivatives with respect to ww and xx match, as do those with respect to yy and zz, because ff depends on its inputs only through the combinations w+xw + x and y+zy + z.

A quick operation count makes the advantage concrete. Forward mode needs six multiplications per input (two each for du/dw\mathrm{d}u/\mathrm{d}w, dv/dw\mathrm{d}v/\mathrm{d}w, and df/dw\mathrm{d}f/\mathrm{d}w), or 2424 in total for all four inputs. The backward pass needs four multiplications to compute aˉ\bar a and bˉ\bar b and then two per input, or 1212 in total, because it traverses the shared upper part of the graph only once. A factor of two on a toy graph is modest, but the gap widens rapidly with the number of inputs: every additional input costs forward mode an entire pass through the graph, whereas the backward pass needs only two more multiplications.

22.3.2.3 Backpropagation in a Framework#

Computing derivatives by propagating adjoints from the output back to the inputs is backpropagation (Rumelhart et al., 1986), which Section 4.3 applies to multilayer perceptrons. Every modern automatic differentiation engine executes the same two passes: it records intermediate values (or the operations needed to form edge derivatives) during the forward pass, and then accumulates adjoints during the backward pass. Let us check our hand computation against the framework's automatic differentiation on the same four inputs.

wxyz = torch.tensor([1., 1., -2., 1.], requires_grad=True)
w, x, y, z = wxyz
a, b = (w + x + y + z)**2, (w + x - y - z)**2
u, v = (a + b)**2, (a - b)**2
f = (u + v)**2
f.backward()  # one backward pass
print(wxyz.grad)
tensor([ 73472.,  73472., -68224., -68224.])

The framework returns (73472,73472,−68224,−68224)(73472, 73472, -68224, -68224), matching the adjoints from our hand calculation. The agreement is exact rather than approximate because every intermediate number is an integer below 2242^{24}, which single precision represents without rounding error.

So far every node in our graphs has been a scalar, and we could count multiplications on the back of an envelope. In a real neural network, each layer maps a vector to a vector, so the edge derivatives become matrices and the order in which those matrices are multiplied matters far more than the order of scalar multiplications. We take that step in Section 22.4.

22.3.3 Summary#

On a computational graph, the total derivative of an output with respect to an input equals the sum, over all directed paths between them, of the products of the local edge derivatives. The adjoint of a node, the total derivative of the output with respect to that node, collects every path leaving it. Factoring those paths by their first outgoing edge yields a recursion that, run backward from the output, computes every adjoint in a single pass. This reverse accumulation is backpropagation. Propagating one input forward instead computes only that input's derivative, which is why differentiating a scalar loss with respect to many parameters is always done backward.

22.3.4 Exercises#

  1. [code] Backward pass for two tanh units. A network with one input xx, two hidden units, and one output computes, for a target tt,
hi=tanh⁡(wix+bi)(i=1,2),f=v1h1+v2h2,ℓ=12(f−t)2.h_i = \tanh(w_i x + b_i) \quad (i = 1, 2), \qquad f = v_1 h_1 + v_2 h_2, \qquad \ell = \tfrac12 (f - t)^2.
  1. Draw the dependency graph of ℓ\ell. In plain Python, write a forward pass that stores every intermediate value and a backward pass that returns the partial derivatives of ℓ\ell with respect to all six parameters w1,b1,w2,b2,v1,v2w_1, b_1, w_2, b_2, v_1, v_2. Check them against automatic differentiation at x=1.5x = 1.5, t=0.5t = 0.5, and (w1,b1,w2,b2,v1,v2)=(0.5,0,−1,0.2,1,−0.5)(w_1, b_1, w_2, b_2, v_1, v_2) = (0.5, 0, -1, 0.2, 1, -0.5). Which intermediate derivative does every one of the six partials reuse?

  2. Set w1=5w_1 = 5 and x=2x = 2, keeping the other values. Compute ∂ℓ/∂w1\partial \ell / \partial w_1 with the plain-Python backward pass and explain its size from the product of edge derivatives along its path. Compare it with the value that automatic differentiation returns in single precision, and explain the difference. What does this imply for training a unit whose pre-activation is large?

  3. Set w1=w2w_1 = w_2, b1=b2b_1 = b_2, and v1=v2v_1 = v_2. Show from the backward pass that both units receive identical gradients, so that gradient descent keeps them identical at every step. What does this imply for the initialization of hidden units?

  4. Paths through a residual stack. ● In a one-dimensional model of the residual networks of Section 7.4, scalar blocks compute xl+1=xl+gl(xl)x_{l+1} = x_l + g_l(x_l) for l=0,…,m−1l = 0, \ldots, m-1 with differentiable functions glg_l.

    1. Use the chain rule to write ∂xm/∂x0\partial x_m / \partial x_0 as a product of mm factors.
    2. Expand the product and match each term to a directed path from x0x_0 to xmx_m in the dependency graph. How many paths are there, and how many of them pass through exactly kk of the functions glg_l? Compare the number of paths with the number of multiplications that a backward pass needs to compute ∂xm/∂x0\partial x_m / \partial x_0.
    3. For a trained network of m=54m = 54 residual blocks, Veit et al. (2016) found that almost all of the gradient flows along the paths through 55 to 1717 blocks. What fraction of all paths are these? Now assume that gl′(xl)=c>0g_l'(x_l) = c > 0 for every block. Which value of cc makes the paths through about 1111 blocks contribute the most to ∂xm/∂x0\partial x_m / \partial x_0, and what share of the derivative do the paths through 55 to 1717 blocks then carry?
  5. [code] Gradient checks in single precision. ● A gradient check compares a backward pass with the central difference (f(w+h,x,y,z)−f(w−h,x,y,z))/(2h)\bigl(f(w + h, x, y, z) - f(w - h, x, y, z)\bigr) / (2h). Let ff be the function of (22.3.1), whose exact partial derivative at (w,x,y,z)=(1,1,−2,1)(w, x, y, z) = (1, 1, -2, 1) is ∂f/∂w=73472\partial f / \partial w = 73472.

    1. Implement ff in NumPy and compute the central difference at this point for h=10−1,10−2,…,10−12h = 10^{-1}, 10^{-2}, \ldots, 10^{-12}, once in float64 and once in float32. Plot the relative error against hh on log-log axes for both precisions, and read off the best hh and the smallest relative error of each.
    2. The error of the central difference is a truncation part of order h2h^2 plus a rounding part of order εmach∣f∣/h\varepsilon_{\textrm{mach}} |f| / h, where the machine epsilon εmach\varepsilon_{\textrm{mach}} is about 2.2×10−162.2 \times 10^{-16} for float64 and 1.2×10−71.2 \times 10^{-7} for float32. By which factors should the best hh and the smallest relative error change from float64 to float32? Compare the predicted factors with the plot.
    3. Which tolerance on the relative error can a float32 gradient check use without rejecting a correct backward pass? Why are gradient checks run in double precision?
    4. Why does the float32 estimate become exactly zero for the smallest values of hh?

Discussions