Automatic Differentiation

Dive into Deep Learning · §1.5

Automatic Differentiation: Computational Graphs, Reverse-Mode AD, and Dynamic Programs
forward & reverse mode · computational graphs · VJPs · detaching & memory control · dynamic control flow

Three Ways to Differentiate Code: Why Deep Learning Needs Autograd

Motivation

  • Symbolic algebra: Exponential expression swell; fails on Python loops and branches.
  • Numerical finite differences: Costs O(n) forward evaluations (10^9 per step) and loses half of float32 precision to subtraction cancellation.
  • Reverse-mode autograd: Applies exact local VJP rules along the execution trace to compute \nabla_{\mathbf{w}} L \in \mathbb{R}^n in one backward sweep.

Forward-Mode vs. Reverse-Mode AD: The n ≫ m Asymmetry

Jacobians & Sweeps

For \mathbf{f}: \mathbb{R}^n \to \mathbb{R}^m with m \times n Jacobian \mathbf{J} (J_{ji} = \partial f_j / \partial x_i):

  • Forward mode (JVP, \mathbf{d} \mapsto \mathbf{J}\mathbf{d}): Seeds input tangent \dot{\mathbf{x}} = \mathbf{e}_i and propagates forward, computing one column of \mathbf{J} per sweep (n sweeps).
  • Reverse mode (VJP, \mathbf{v} \mapsto \mathbf{J}^\top \mathbf{v}): Seeds output adjoint \bar{\mathbf{y}} = \mathbf{e}_j and propagates backward, computing one row of \mathbf{J} per sweep (m sweeps).
  • Why backprop scales: A scalar loss has m = 1 \ll n, so reverse mode computes all n components of \nabla_{\mathbf{w}} L in one backward pass.

Defining the Forward Pass: From Mathematical Loss to Code

Forward Trace

  • In deep learning frameworks, we write only the forward pass; no hand-written derivative formula ever appears in model code.
  • Running example (§1.4): Our linear model L(\mathbf{w}) = \|\mathbf{X}\mathbf{w} - \mathbf{y}\|^2 with design matrix \mathbf{X} \in \mathbb{R}^{3 \times 2} and targets \mathbf{y} = [1, 1, 0]^\top, evaluated at \mathbf{w} = [1, 0]^\top.
  • Each primitive operator in loss(w) (matrix–vector product, subtraction, elementwise square, and sum) carries its own local backward VJP rule.
X = torch.tensor([[1.0, 0.0], [1.0, 1.0], [1.0, 2.0]])  # [1, input]
y = torch.tensor([1.0, 1.0, 0.0])
w = torch.tensor([1.0, 0.0])

def loss(w):
    return ((X @ w - y) ** 2).sum()

Opting In to Gradient Tracking and Recording the Forward Trace

Graph Construction

  • Explicit opt-in saves VRAM: Frameworks only record DAG nodes for parameters explicitly marked for gradient tracking.
w.requires_grad_(True)
tensor([1., 0.], requires_grad=True)
L = loss(w)
L
tensor(1., grad_fn=<SumBackward0>)

Inside the Computational Graph: Forward Values and Backward Adjoints

How Backpropagation Works

  • Forward pass (blue, left \to right): Evaluates and caches intermediate activations at \mathbf{w} = (1, 0):
    • \hat{\mathbf{y}} = \mathbf{X}\mathbf{w} = (1,1,1) \to \mathbf{r} = \hat{\mathbf{y}} - \mathbf{y} = (0,0,1)
    • \mathbf{s} = \mathbf{r}^{\odot 2} = (0,0,1) \to L = \sum_i s_i = 1
  • Backward pass (red, right \to left): Seeds \bar{L} = 1 and applies each node’s local VJP rule:
    • \bar{L}=1 \to \bar{\mathbf{s}}=(1,1,1) \to \bar{\mathbf{r}} = 2\mathbf{r} \odot \bar{\mathbf{s}} = (0,0,2)
    • \bar{\hat{\mathbf{y}}} = \bar{\mathbf{r}} = (0,0,2) \to \bar{\mathbf{w}} = \mathbf{X}^\top \bar{\hat{\mathbf{y}}} = (2,4)

Executing the Backward Pass and Verifying Analytical Gradients

Backward Pass

  • Triggering the backward pass traverses the graph in reverse topological order and recovers the exact analytical gradient \nabla_{\mathbf{w}} L = \mathbf{X}^\top(2\mathbf{r}) = [2, 4]^\top.
  • Hand verification at \mathbf{w} = [1, 0]^\top:
    • Residuals: \mathbf{r} = \mathbf{X}\mathbf{w} - \mathbf{y} = [1, 1, 1]^\top - [1, 1, 0]^\top = [0, 0, 1]^\top.
    • Backward VJP: \mathbf{X}^\top(2\mathbf{r}) = \begin{bmatrix} 1 & 1 & 1 \\ 0 & 1 & 2 \end{bmatrix} \begin{bmatrix} 0 \\ 0 \\ 2 \end{bmatrix} = \begin{bmatrix} 2 \\ 4 \end{bmatrix}.
L.backward()
w.grad
tensor([2., 4.])

Gradient Accumulation: Why PyTorch Adds into .grad by Default

Stateful Buffers

  • Accumulation by default (w.grad += g): Enables summing gradients across micro-batches when a full batch exceeds GPU memory.
  • Classic bug: Forgetting w.grad.zero_() before the next step adds onto stale gradients ((2, 4) + (2, 4) = (4, 8)).
L = loss(w)
L.backward()
w.grad  # the new gradient was added to the old one
tensor([4., 8.])

Backward for Non-Scalar Outputs: Vector–Jacobian Products (VJPs)

Vector Outputs

  • Differentiating \mathbf{u}(\mathbf{w}) \in \mathbb{R}^m never forms an m \times n Jacobian; a backward pass seeded with \mathbf{v} \in \mathbb{R}^m computes \mathbf{J}^\top \mathbf{v} = \nabla_{\mathbf{w}}(\mathbf{v}^\top \mathbf{u}) (\mathbf{v} = \mathbf{1} sums per-example gradients).
w.grad.zero_()
losses = (X @ w - y) ** 2  # one loss per example
losses.backward(gradient=torch.ones(3))  # = losses.sum().backward()
w.grad
tensor([2., 4.])

Detaching Subgraphs with detach and stop_gradient

Graph Surgery

  • For u = x^2 and z = u \cdot x = x^3:
    • Attached (a): Gradients flow through both paths \implies \frac{\partial z}{\partial x} = 2x^2 + x^2 = 3x^2.
    • Detached (b): c = u.detach() (stop_gradient(u)) freezes u as constant x^2 \implies \frac{\partial z}{\partial x}\big|_c = c = x^2.
  • ML use cases: DQN target networks, BYOL/SimSiam teacher branches, and GAN discriminator updates.

Detaching in Code: Comparing Attached (3x²) vs. Detached (x²) Gradients

Detaching in Practice

  • With detach() / stop_gradient() (z = c * x): At \mathbf{x} = [0, 1, 2, 3]^\top, c = \mathbf{x}^2 = [0, 1, 4, 9]^\top acts as a constant, yielding \nabla_{\mathbf{x}} \sum_i z_i = \mathbf{x}^2 = [0, 1, 4, 9]^\top:
x = torch.arange(4.0, requires_grad=True)
u = x * x
c = u.detach()  # values of u, no history
z = c * x
z.sum().backward()
x.grad
tensor([0., 1., 4., 9.])
  • Without detach() (z = u * x): Both paths from \mathbf{x} to \mathbf{z} carry gradients, yielding the full cubic derivative \nabla_{\mathbf{x}} \sum_i z_i = 3\mathbf{x}^2 = [0, 3, 12, 27]^\top:
x.grad.zero_()
z = u * x
z.sum().backward()
x.grad
tensor([ 0.,  3., 12., 27.])

Activation Memory and Disabling Gradient Tracking

Memory & Inference

  • Training caches O(L) activations: Backward VJPs need forward intermediates (\mathbf{r} for 2\mathbf{r}, \mathbf{X} for \mathbf{X}^\top), pinning every layer’s activations in HBM until the backward pass.
  • Inference with tracking off: Frees each layer buffer immediately (O(1) depth memory) and keeps SGD steps off the tape.
with torch.no_grad():  # nothing in this block is recorded
    w -= 0.1 * w.grad
    L = loss(w)
w, L
(tensor([ 0.8000, -0.4000], requires_grad=True), tensor(0.4000))

Dynamic Control Flow: Differentiating Through Python Loops and Branches

Differentiable Programs

  • Define-by-run tracing: Every forward evaluation records the exact sequence of primitive tensor operations that actually ran on that concrete input.
  • Consider f(a):
    1. Repeatedly doubles b inside a data-dependent while loop until \|\mathbf{b}\|_2 \ge 1000 (k doublings in total).
    2. Branches on b.sum() > 0 to return either b or 100 * b.
  • For any scalar input a \neq 0, the executed trace is a chain of multiplications f(a) = m \cdot 2^k \cdot a with m \in \{1, 100\}.
def f(a):
    b = a * 2
    while torch.linalg.vector_norm(b) < 1000:
        b = b * 2
    if b.sum() > 0:
        c = b
    else:
        c = 100 * b
    return c

Each Execution Trace Builds Its Own Graph and Recovers Its Exact Slope

Trace vs. Function

  • Since f(a) = k \cdot a is piecewise linear along each execution path, its derivative equals the exact slope k = f(a) / a:
    • a = 0.3 > 0: 12 doublings (if branch) \implies k = 2^{12} = 4096.
    • a = -0.75 < 0: 11 doublings (else branch) \implies k = 100 \cdot 2^{11} = 204{,}800.
  • Caveat: Autograd differentiates the executed trace—at jump thresholds where loop iterations change, it returns the slope of the branch that ran.
for value in (0.3, -0.75):
    a = torch.tensor(value, requires_grad=True)
    fa = f(a)
    fa.backward()
    print(f'a = {value:5.2f}   f(a) / a = {fa.item() / value:6.0f}   '
          f'gradient = {a.grad.item():6.0f}')
a =  0.30   f(a) / a =   4096   gradient =   4096
a = -0.75   f(a) / a = 204800   gradient = 204800

Concept Check: Activation Memory, Detach, and Accumulation Bugs

Check Your Understanding

Predict the behavior and gradient outcome in each scenario:

  1. Missing reset: You evaluate 3 micro-batches and call L.backward() on each without calling w.grad.zero_(). What does w.grad hold?
  2. Detached branches: Let u = x * x and c = u.detach() (or stop_gradient(u)). What is \nabla_{\mathbf{x}} \sum_i z_i for (a) z = u * u, (b) z = u * c, and (c) z = c * c?
  3. Forward vs. reverse sweeps: A physics simulator maps n = 3 wing-shape parameters to m = 10^6 mesh pressures. Which AD mode computes the full 10^6 \times 3 Jacobian faster, and in how many sweeps?

Answers:

  1. The sum of all 3 micro-batch gradients (\sum_{b=1}^3 \nabla_{\mathbf{w}} L_b). Intentional for micro-batch gradient accumulation; a bug if you already stepped the optimizer after micro-batches 1 and 2.
    1. z = u * u = x^4 \implies 4\mathbf{x}^3; (b) z = u * c = c * x^2 \implies 2c\mathbf{x} = 2\mathbf{x}^3 (half of 4\mathbf{x}^3, since one factor is frozen); (c) z = c * c has no active path to x \implies 0 (or no grad_fn).
  2. Forward mode (JVP) needs only n = 3 sweeps (one per column), whereas reverse mode needs m = 10^6 sweeps (one per row).

Summary: Autograd Primitives, Memory Effects, and ML Use Cases

Key Takeaways

Operation / Concept API Graph & Memory Behavior Primary Deep Learning Role
Opt-in / Trace w.requires_grad_(True) Caches forward activations in VRAM for backward VJPs Standard neural network training (O(1) reverse sweep)
Reverse Sweep (VJP) L.backward() or u.backward(v) Frees activation buffers after computing \mathbf{J}^\top \mathbf{v} Backpropagation of scalar loss (m = 1) or upstream vector \mathbf{v}
Reset / Accumulate w.grad.zero_() (adds += by default) Decides whether a new gradient adds to or replaces the last one Micro-batch gradient accumulation vs. fresh optimizer step
Detach Subgraph u.detach() Zero-copy constant view; cuts backward edge RL target networks, BYOL/SimSiam teacher branch, GAN steps
Inference / No-Grad with torch.no_grad(): Skips graph construction & activation caching (3\text{--}10\times less VRAM) Validation loops, production inference, parameter updates