The Chain Rule on Computational Graphs

Dive into Deep Learning · §34.3

The Chain Rule on Computational Graphs
dependency DAGs · edge vs. total derivatives · sum over paths · forward mode · adjoints & backpropagation

Why One Backward Pass Replaces a Million Perturbations

Motivation

  • Perturbation Bottleneck: Nudging N = 10^8 parameters one by one requires 10^8 separate forward passes.
  • Shared Downstream Sub-Paths: Every early parameter’s effect travels through the exact same upper layers to reach the scalar loss f.
  • Backpropagation as Path Factoring: Grouping the path-sum chain rule from f backward reuses every downstream derivative across all inputs.

Representing a Function as a Computation Graph

Directed Acyclic Graphs

  • Concrete 4-input integer benchmark: Four inputs (w, x, y, z) pass through Layer 1 nodes a = (w + x + y + z)^2 and b = (w + x - y - z)^2, then Layer 2 nodes u = (a + b)^2 and v = (a - b)^2, to produce scalar output: f(u, v) = (u + v)^2
  • Nodes and directed edges: Each node stores one intermediate variable, and a directed edge n \to c indicates that node c’s defining formula directly takes n as an argument.
  • Exact integer arithmetic: Squaring keeps all node values and derivatives exact integers so we can verify every step without floating-point rounding.

Propagating a Perturbation Across Parallel Branches

Multivariable Chain Rule

  • 1. Perturb Intermediate Children: Nudging a \mapsto a + \epsilon shifts u by \Delta u \approx \epsilon\frac{\partial u}{\partial a} and v by \Delta v \approx \epsilon\frac{\partial v}{\partial a}.
  • 2. Substitute into Linear Model of f(u, v): \Delta f \approx \frac{\partial f}{\partial u}\Delta u + \frac{\partial f}{\partial v}\Delta v.
  • 3. Sum Parallel Branches: \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}.

Edge Derivatives (∂) vs. Total Derivatives (d)

Notation & Semantics

  • Edge Derivative \frac{\partial c}{\partial n}: Local partial of child c’s formula with respect to parent n, holding all other direct parents of c fixed.
  • Total Derivative (Adjoint) \bar{n} = \frac{\mathrm{d}f}{\mathrm{d}n}: Total rate of change of final output f when node n is nudged and all downstream nodes respond along every directed path n \to \cdots \to f.

The General Chain Rule as a Sum Over Paths

Path-Sum Formula

  • Path-Sum Chain Rule: \frac{\mathrm{d}f}{\mathrm{d}x} = \sum_{\text{paths } x \to \cdots \to f} \prod_{(u \to v)} \frac{\partial v}{\partial u} (multiply along edges of each path, add across parallel paths).
  • Exponential Blow-Up of Naive Enumeration: An m-stage graph with 2 parallel nodes per stage has 2^m paths; dynamic programming (AD) factors shared nodes in O(|\text{Edges}|) time.

Skip Connections and Multi-Path Interference

Worked Example

  • A 5-node DAG with a skip edge: Let p = x + y, q = x - y, r = p^2, s = q^2, and f(r, p, s) = r + p + s.
  • Three paths from y to f: Path y \to p \to r \to f contributes 1 \cdot 2p \cdot 1 = 2p, the skip edge y \to p \to f contributes 1 \cdot 1 = 1, and path y \to q \to s \to f contributes 1 \cdot 2q \cdot (-1) = -2q: \frac{\mathrm{d}f}{\mathrm{d}y} = 2p + 1 - 2q = 1 + 4y
  • At (x, y) = (1, 2) (p = 3, q = -1): The three paths contribute 6 + 1 + 2 = 9 = 1 + 4(2).
  • Edge vs. total at node p: The direct skip edge has \frac{\partial f}{\partial p} = 1 (holding r fixed), whereas the total derivative is \frac{\mathrm{d}f}{\mathrm{d}p} = 2p + 1 = 7.

Architectural Lesson: ResNets and Gates Shape Paths

Deep Learning Connection

  • Residual Stack (x_{l+1} = x_l + g_l(x_l)): Each block branches into an identity skip edge (slope 1) and a residual branch (slope g_l'), yielding \frac{\mathrm{d}x_m}{\mathrm{d}x_0} = \prod_{l=0}^{m-1}(1 + g_l'(x_l)).
  • Path Ensemble (2^m Paths): Expanding the product gives \binom{m}{k} paths passing through k nonlinear blocks and skipping m - k blocks with unit slope (Veit et al., 2016).

Forward Pass and Local Edge Derivatives

Hand Trace: Step 1

  • Forward Values at (1, 1, -2, 1): Layer 1 gives a = 1^2 = 1 and b = 3^2 = 9; Layer 2 gives u = 10^2 = 100 and v = (-8)^2 = 64; output is f = 164^2 = 26{,}896.
  • All 14 Edge Slopes Known Immediately: Local partials (\partial a/\partial w = 2, \partial b/\partial w = 6, \partial u/\partial a = 20, \partial v/\partial a = -16, \partial f/\partial u = 328) depend only on each node and its immediate parents.

Forward Mode: Factoring Paths from One Input Outward

Forward Accumulation

  • Push One Input Sensitivity Forward: Fixing w, we compute \mathrm{d}a/\mathrm{d}w = 2, \mathrm{d}b/\mathrm{d}w = 6 \implies \mathrm{d}u/\mathrm{d}w = 160, \mathrm{d}v/\mathrm{d}w = 64 \implies \mathrm{d}f/\mathrm{d}w = 328(160 + 64) = 73{,}472.
  • Why Forward Mode Scales Poorly with N: Intermediate tangents \mathrm{d}u/\mathrm{d}w and \mathrm{d}v/\mathrm{d}w are specific to w, requiring N separate sweeps (4 \times 6 = 24 mults) for N inputs.

Executing Forward Mode in Plain Python

Code Verification

Running the forward pass and pushing the sensitivity to w forward in Python confirms \mathrm{d}f/\mathrm{d}w = 73472 at a cost of 6 multiplications for that single input:

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)

Executing Forward Mode in Plain Python (cont.)

Code Verification

a, b, u, v, f = 1 9 100 64 26896
df/dw = 73472

Computing the full gradient over all 4 inputs by forward mode requires 4 \times 6 = 24 multiplications (N separate forward sweeps for N inputs).

Adjoints and Reverse-Mode Path Factoring

Backward Accumulation

  • Flip the perspective—fix the output f: Define the adjoint \bar{n} = \frac{\mathrm{d}f}{\mathrm{d}n} of node n as the total derivative of the final output f with respect to n, seeded at \bar{f} = 1.
  • Group paths by their first outgoing edge: Every path from n to f must step first to some immediate child c of n, and the remaining paths from c to f sum to \bar{c}: \bar{n} = \sum_{c \in \mathrm{children}(n)} \bar{c}\,\frac{\partial c}{\partial n}
  • One reverse sweep for all inputs: Visiting nodes in reverse topological order ensures every child adjoint \bar{c} is ready before \bar{n} is computed.

Tracing the Backward Sweep Across All Nodes

Hand Trace: Step 2

  • Top-Down Adjoint Recursion (\bar{n} = \sum_c \bar{c}\frac{\partial c}{\partial n}): Seed \bar{f} = 1 \implies \bar{u} = \bar{v} = 328 \implies \bar{a} = 1{,}312, \bar{b} = 11{,}808.
  • All 4 Inputs in 12 Multiplications: \bar{w} = \bar{x} = 1312(2) + 11808(6) = 73{,}472 and \bar{y} = \bar{z} = 1312(2) - 11808(6) = -68{,}224.

Executing the Backward Sweep in Plain Python

Code Verification

Because \bar{a} = 1312 and \bar{b} = 11808 already summarize the entire upper graph, each additional input costs only 2 multiplications at the bottom layer:

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}

Symmetry check: w and x enter a and b only through w + x, so \bar{w} = \bar{x} = 73472; similarly y and z enter only through y + z with a minus sign in b, so \bar{y} = \bar{z} = -68224.

Verifying Hand Adjoints Against Framework Autograd

Framework Execution

Every modern automatic differentiation engine executes this exact two-phase algorithm—recording values during the forward pass and accumulating adjoints during backward():

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.], matching our hand calculation bit-for-bit because every integer intermediate is below 2^{24} \approx 1.68 \times 10^7, the exact integer limit of IEEE 754 float32.

Practical Pitfall: Gradient Checks in Float32

Numerical Verification

  • Competing Errors in Central Differences: Truncation error scales as O(h^2) for large h, while subtractive cancellation scales as O(\varepsilon_{\text{mach}}|f|/h) for small h, giving optimal h^\star \propto \varepsilon_{\text{mach}}^{1/3} and min error O(\varepsilon_{\text{mach}}^{2/3}).
  • Why float64 Is Mandatory: float64 reaches \sim 10^{-11} relative error at h^\star \approx 10^{-5}, whereas float32 stalls at \sim 10^{-4} and underflows w + h == w to zero for h \le 10^{-8}.

Concept Check: Chain Rule on Computation Graphs

Review & Practice

Work out these three questions on computation graphs and adjoints:

  1. Edge vs. total derivative: In the graph p = x + y, r = p^2, f = r + 3p, what are the edge derivative \frac{\partial f}{\partial p} and the total derivative (adjoint) \bar{p} = \frac{\mathrm{d}f}{\mathrm{d}p} at p = 4?
  2. Shared intermediate adjoint: In a network with two hidden units h_1, h_2, prediction f = v_1 h_1 + v_2 h_2, and loss \ell = \tfrac{1}{2}(f - t)^2, which adjoint is computed once and reused by every weight in the network?
  3. Symmetry Pitfall (Weight Initialization): If two hidden units h_1 = \tanh(w_1 x + b_1) and h_2 = \tanh(w_2 x + b_2) are initialized identically (w_1 = w_2, b_1 = b_2, v_1 = v_2), what happens to their adjoints \bar{w}_1, \bar{w}_2 during backpropagation?

Answers:

  1. The direct edge derivative holding r fixed is \frac{\partial f}{\partial p} = 3. The total derivative sums both paths out of p: \bar{p} = \frac{\partial f}{\partial r}\frac{\partial r}{\partial p} + \frac{\partial f}{\partial p} = 1(2p) + 3 = 2(4) + 3 = 11.
  2. Every parameter path to \ell passes through f, so the prediction adjoint \bar{f} = \frac{\mathrm{d}\ell}{\mathrm{d}f} = f - t is computed once and shared by all parameters.
  3. Because the two paths are symmetric, \bar{h}_1 = \bar{h}_2, \bar{w}_1 = \bar{w}_2, and \bar{b}_1 = \bar{b}_2 at every step, so gradient descent updates both units identically forever. Hidden units must be initialized with random asymmetry.

Summary: Computation Graphs & Backpropagation

Key Takeaways

Concept / Method Mathematical Formula Computational & Architectural Role
Edge Derivative (\partial) \frac{\partial c}{\partial n} (other direct parents of c fixed) Local sensitivity of a single elementary operation
Total Derivative (\mathrm{d} / \bar{n}) \bar{n} = \frac{\mathrm{d}f}{\mathrm{d}n} (all downstream nodes respond) True sensitivity of final output f to intermediate node n
Path-Sum Chain Rule \frac{\mathrm{d}f}{\mathrm{d}x} = \sum_{\text{paths } x \to f} \prod_{(u \to v)} \frac{\partial v}{\partial u} Explains skip-connection gradient highways (2^m paths in ResNets)
Forward-Mode Sweep \dot{n} = \frac{\mathrm{d}n}{\mathrm{d}x_j} = \sum_{p \in \mathrm{parents}(n)} \frac{\partial n}{\partial p}\dot{p} Pushes one input seed forward; requires N sweeps for N parameters
Reverse-Mode (Backprop) \bar{f} = 1, \bar{n} = \sum_{c \in \mathrm{children}(n)} \bar{c}\frac{\partial c}{\partial n} Pulls one output seed backward; computes all N gradients in 1 sweep
Central-Difference Check \frac{f(w+h)-f(w-h)}{2h} = f'(w) + O(h^2) + O(\frac{\varepsilon_{\text{mach}}}{h}) Must run in float64 (h \approx 10^{-5}) to avoid float32 roundoff floor