1.5 Automatic Differentiation

In Section 1.4, deriving the gradient ∇wL=X⊤(2r)=(2,4)\nabla_{\mathbf{w}} L = \mathbf{X}^\top (2\mathbf{r}) = (2, 4) of our two-parameter line model by hand was straightforward, whereas doing so across dozens of layers and billions of parameters would be hopeless. Modern deep learning frameworks automate this via automatic differentiation (autograd): as a program evaluates a scalar loss, the framework traces the elementary operations into a computational graph and traverses that graph in reverse (backpropagation) to apply the chain rule mechanically. Remarkably, whether a model has two parameters or a billion, a single backward sweep computes the exact gradient with respect to all of them at only a small constant multiple of the forward-pass cost.

import torch

1.5.1 Computing Gradients#

1.5.1.1 The Forward Pass#

We first set up the line model L(w)=∥Xw−y∥2L(\mathbf{w}) = \|\mathbf{X}\mathbf{w} - \mathbf{y}\|^2 at w=(1,0)\mathbf{w} = (1, 0) from Section 1.4 using framework tensors, writing only the forward pass:

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()

Because recording operations and saving intermediate activations consumes memory, the framework tracks only operations that depend on parameters explicitly marked for gradients.

Calling w.requires_grad_(True) marks w in place so PyTorch tracks operations involving w and stores the resulting gradient in w.grad:

w.requires_grad_(True)
tensor([1., 0.], requires_grad=True)

We now evaluate L = loss(w), and PyTorch automatically records the sequence of operations connecting w to L:

L = loss(w)
L
tensor(1., grad_fn=<SumBackward0>)

Notice grad_fn=<SumBackward0> on L, recording the final operation in the computational graph.

The recorded trace forms the computational graph shown in Figure 1.5.1, breaking the loss into four primitive operations: y^=Xw\hat{\mathbf{y}} = \mathbf{X}\mathbf{w}, r=y^−y\mathbf{r} = \hat{\mathbf{y}} - \mathbf{y}, s=r⊙r\mathbf{s} = \mathbf{r} \odot \mathbf{r}, and L=∑isiL = \sum_i s_i.

Figure 1.5.1:

The computational graph of L=∥Xw−y∥2L = \|\mathbf{X}\mathbf{w} - \mathbf{y}\|^2 at w=(1,0)\mathbf{w} = (1, 0), with one node for w\mathbf{w} and for each value computed from it; the constants X\mathbf{X} and y\mathbf{y} are not drawn, and r⊙r\mathbf{r} \odot \mathbf{r} is the elementwise square. Each node shows its value (black) and the gradient of LL with respect to it (red). The forward pass (blue) runs from left to right; the backward pass (red) starts from 11 at LL and applies the local rule of each operation, from right to left.

1.5.1.2 The Backward Pass#

Triggering the backward pass propagates sensitivities from ∂L/∂L=1\partial L/\partial L = 1 at the output back to w\mathbf{w} through each node's local derivative rule,

∇sL=1→∇rL=2r→∇y^L=2r→∇wL=X⊤(2r),(1.5.1)\nabla_{\mathbf{s}} L = \mathbf{1} \to \nabla_{\mathbf{r}} L = 2\mathbf{r} \to \nabla_{\hat{\mathbf{y}}} L = 2\mathbf{r} \to \nabla_{\mathbf{w}} L = \mathbf{X}^\top(2\mathbf{r}), \tag{1.5.1}

reproducing (2,4)(2, 4):

L.backward() runs the backward pass and stores the gradient in w.grad.

L.backward()
w.grad
tensor([2., 4.])

Because local backward rules require intermediate activations from the forward pass (such as r\mathbf{r} and X\mathbf{X}), training consumes substantially more memory than inference (Figure 1.5.2).

Figure 1.5.2:

Memory during a forward pass through four layers with outputs h1,…,h4\mathbf{h}_1, \ldots, \mathbf{h}_4. (a) When gradients are tracked, every output is kept, because the backward pass (red) will need it. (b) When they are not, as during inference, an output can be freed as soon as the next layer has used it.

1.5.1.3 Repeated Backward Passes#

What happens when we evaluate the gradient a second time at the same parameter vector w\mathbf{w}?

L = loss(w)
L.backward()
w.grad  # the new gradient was added to the old one
tensor([4., 8.])

In PyTorch, w.grad becomes (4, 8) because PyTorch adds each new gradient into w.grad by default, which makes summing gradients across micro-batches or multiple loss terms convenient. In a standard training loop, always clear the buffer before the next step via w.grad.zero_().

1.5.1.4 Vector-Valued Functions#

When an operation produces a vector of mm outputs u∈Rm\mathbf{u} \in \mathbb{R}^m from nn inputs x∈Rn\mathbf{x} \in \mathbb{R}^n with m×nm \times n Jacobian J\mathbf{J}, a backward pass seeded with a weight vector v∈Rm\mathbf{v} \in \mathbb{R}^m computes the transposed vector--Jacobian product J⊤v=∇x(v⊤u)\mathbf{J}^\top \mathbf{v} = \nabla_{\mathbf{x}}(\mathbf{v}^\top \mathbf{u}) without materializing J\mathbf{J}. Passing v=1\mathbf{v} = \mathbf{1} on the per-example squared errors (r12,r22,r32)(r_1^2, r_2^2, r_3^2) differentiates their sum:

Calling backward() on a non-scalar tensor requires passing v\mathbf{v} explicitly via gradient=torch.ones(3) (equivalent to losses.sum().backward()).

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.])

1.5.2 Controlling the Graph#

1.5.2.1 Detaching Values#

Detaching a tensor creates a view or copy with the same numerical values but no link to its ancestors in the computational graph, so backpropagation treats it as a constant. Consider u=x2u = x^2 and z=uxz = u x on x=(0,1,2,3)\mathbf{x} = (0, 1, 2, 3) (Figure 1.5.3): when uu is attached, gradient flows along both paths to give ∂z/∂x=3x2\partial z/\partial x = 3x^2; when uu is detached to cc, differentiating z=cxz = c x treats cc as a constant and gives ∂z/∂x=c=x2\partial z/\partial x = c = x^2 (essential whenever a network computes its own bootstrap target, as in deep Q-learning, Section 15.4).

Figure 1.5.3:

The product z=uxz = ux with u=x2u = x^2, (a) attached and (b) detached. Blue arrows are operations of the forward pass; red arrows show the backward pass, labeled with the local derivatives it multiplies by. Detaching uu creates a constant cc with the same value and no connection to xx.

u.detach() returns a tensor sharing u's values but stripped of its history.

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.])

By contrast, if we compute z = u * x directly without detaching u, backpropagation flows through both factors of z=x3z = x^3 and returns ∂z/∂x=3x2=(0,3,12,27)\partial z / \partial x = 3x^2 = (0, 3, 12, 27):

x.grad.zero_()
z = u * x
z.sum().backward()
x.grad
tensor([ 0.,  3., 12., 27.])

1.5.2.2 Disabling Gradient Tracking#

During validation, inference, or parameter updates w←w−η∇L(w)\mathbf{w} \leftarrow \mathbf{w} - \eta \nabla L(\mathbf{w}), we disable gradient tracking so those operations are not recorded on the loss graph:

with torch.no_grad(): disables tracking (required when modifying a leaf tensor with requires_grad=True in place).

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))

As in Section 1.4, one step with η=0.1\eta = 0.1 moves w\mathbf{w} from (1,0)(1, 0) to (0.8,−0.4)(0.8, -0.4) and lowers the loss from 11 to 0.40.4.

1.5.3 Differentiating Programs#

1.5.3.1 Control Flow#

Because autograd records the sequence of elementary operations that actually executed on a given input, it differentiates Python functions containing data-dependent while loops and if/else branches directly:

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

For any nonzero scalar aa (at a=0a = 0 the while loop would never terminate), f(a) performs a fixed sequence of multiplications by 22 (and possibly 100100), so f(a) = k * a is piecewise linear with local slope k=f(a)/ak = f(a)/a (Figure 1.5.4). Specifically, a=0.3a = 0.3 doubles 1212 times to reach 0.3×212=1228.8≥10000.3 \times 2^{12} = 1228.8 \ge 1000 and takes the positive branch (k=212=4096k = 2^{12} = 4096), whereas a=−0.75a = -0.75 doubles 1111 times to −1536-1536 and takes the else branch (k=100×211=204,800k = 100 \times 2^{11} = 204{,}800). Autograd recovers both slopes:

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
Figure 1.5.4:

The graphs recorded by f for two inputs. For a=0.3a = 0.3, f doubles aa 1212 times and the first branch runs; for a=−0.75a = -0.75, it doubles aa 1111 times and the second branch runs. Each graph is linear in aa, with its own slope.

Keep in mind that autograd differentiates the executed trace rather than the abstract mathematical function: at a threshold point where the loop count jumps, f(a)f(a) is discontinuous, yet autograd returns the slope of whichever branch ran.

1.5.4 Forward and Reverse Mode#

For a mapping f:Rn→Rm\mathbf{f} : \mathbb{R}^n \to \mathbb{R}^m with m×nm \times n Jacobian J\mathbf{J}, the chain rule can be traversed in either direction (Figure 1.5.5; see Wengert (1964), Linnainmaa (1970) and Section 22.5):

  • Reverse mode (vector--Jacobian product, VJP): A reverse sweep seeded with v∈Rm\mathbf{v} \in \mathbb{R}^m at the outputs computes J⊤v\mathbf{J}^\top \mathbf{v}; seeding with the jthj^\textrm{th} standard basis vector v=ej\mathbf{v} = \mathbf{e}_j extracts row jj of J\mathbf{J} (mm sweeps for the full Jacobian).
  • Forward mode (Jacobian--vector product, JVP): A forward sweep seeded with a tangent d∈Rn\mathbf{d} \in \mathbb{R}^n at the inputs propagates derivatives forward alongside values to compute Jd\mathbf{J}\mathbf{d}; seeding with d=ei\mathbf{d} = \mathbf{e}_i extracts column ii of J\mathbf{J} (nn sweeps for the full Jacobian, with constant 2×2\times memory overhead).
Figure 1.5.5:

Two ways to fill the m×nm \times n Jacobian J\mathbf{J} of a function with nn inputs and mm outputs: (a) forward mode, nn sweeps in all; (b) reverse mode, mm sweeps in all.

PyTorch provides torch.func.vjp, torch.func.jvp, torch.func.jacrev, and torch.func.jacfwd.

A scalar loss function has m=1m = 1 output and nn parameters, so its Jacobian is a single row ∇wL⊤\nabla_{\mathbf{w}} L^\top. Reverse mode (backpropagation) computes all nn components of the gradient in one sweep, whereas forward mode would require nn sweeps, which explains why reverse mode is universal for training deep networks.

1.5.5 Summary#

Automatic differentiation traces the elementary operations of a forward pass into a computational graph and applies local derivative rules in reverse to compute exact gradients, reproducing ∇wL=(2,4)\nabla_{\mathbf{w}} L = (2, 4) on our line model without hand-written derivative code. Detaching an intermediate value severs its history so backpropagation treats it as a constant, while disabling gradient tracking keeps parameter updates and inference evaluations off the graph and avoids caching forward activations. Because the graph records the operations that actually executed on a given input, autograd differentiates seamlessly through Python loops and conditionals. Finally, one forward-mode sweep computes a Jacobian--vector product Jd\mathbf{J}\mathbf{d} (one column per basis seed) whereas one reverse-mode sweep computes a vector--Jacobian product J⊤v\mathbf{J}^\top\mathbf{v} (one row per basis seed), so for a scalar loss (m=1m = 1) a single reverse sweep yields the entire nn-parameter gradient.

1.5.6 Exercises#

  1. [code] Detached intermediates. Let u = x * x and c = u.detach(), and consider z = c * c, z = u * c, and z = u * u. For each z, recompute u and c, reset x.grad, and call backward on the sum of the entries of z. Before running any code, predict the outcome of each call, including the resulting x.grad. Check your predictions, and explain the ratio between the gradients for z = u * c and z = u * u.

  2. [code] Manual parameter updates. Perform the gradient step of this section as w = w - 0.1 * w.grad, outside torch.no_grad(), and inspect w.requires_grad, w.grad_fn, w.is_leaf, and w.grad. Explain what the update has done to the graph, predict what a second forward and backward pass leaves in w.grad, and check.

  1. [code] From scalar to vector input. Replace the scalar input a of the function f defined in Section 1.5.3.1 by a random vector of length 5, and differentiate the sum of the entries of fa = f(a) with respect to a.

    1. Express f(a) in terms of a, and give the Jacobian of f at a and the gradient of the sum of the entries of fa.
    2. Compute this gradient with automatic differentiation and check whether it still equals fa / a elementwise.
    3. Describe the set of inputs a at which f jumps. Which part of this set has no counterpart for a scalar input?
  2. [code] Programs versus functions. Automatic differentiation differentiates the operations that a program executes, not the function that the program computes.

    1. The functions ∣x∣|x| and x2\sqrt{x^2} are equal. Compute the derivative of each at x=0x = 0 by automatic differentiation, using the framework's absolute value and square root. Explain both results from the local derivatives of the operations involved. Neither function has a derivative at 00; which of the two results does more harm in training, and why?
    2. Write a program that returns x2x^2 for every input xx but whose automatic derivative at x=0x = 0 is 11 instead of 00. Explain why automatic differentiation cannot detect the difference.
  3. Cost of second derivatives. ● The counting argument in Section 1.5.4 puts the cost of the gradient of a scalar loss with nn parameters at one reverse sweep. Use the same argument to estimate, in units of function evaluations, the cost of the full Hessian (the n×nn \times n matrix of second derivatives) and the cost of a single Hessian–vector product. Explain the difference between the two costs.

Discussions