1.5 Automatic Differentiation
In Section 1.4, deriving the gradient 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 torch1.5.1 Computing Gradients#
1.5.1.1 The Forward Pass#
We first set up the line model at 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)
Ltensor(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: , , , and .
The computational graph of at , with one node for and for each value computed from it; the constants and are not drawn, and is the elementwise square. Each node shows its value (black) and the gradient of with respect to it (red). The forward pass (blue) runs from left to right; the backward pass (red) starts from at 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 at the output back to through each node's local derivative rule,
reproducing :
L.backward() runs the backward pass and stores the gradient in w.grad.
L.backward()
w.gradtensor([2., 4.])
Because local backward rules require intermediate activations from the forward pass (such as and ), training consumes substantially more memory than inference (Figure 1.5.2).
Memory during a forward pass through four layers with outputs . (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 ?
L = loss(w)
L.backward()
w.grad # the new gradient was added to the old onetensor([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 outputs from inputs with Jacobian , a backward pass seeded with a weight vector computes the transposed vector--Jacobian product without materializing . Passing on the per-example squared errors differentiates their sum:
Calling backward() on a non-scalar tensor requires passing 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.gradtensor([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 and on (Figure 1.5.3): when is attached, gradient flows along both paths to give ; when is detached to , differentiating treats as a constant and gives (essential whenever a network computes its own bootstrap target, as in deep Q-learning, Section 15.4).
The product with , (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 creates a constant with the same value and no connection to .
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.gradtensor([0., 1., 4., 9.])
By contrast, if we compute z = u * x directly without detaching u, backpropagation flows through both factors of and returns :
x.grad.zero_()
z = u * x
z.sum().backward()
x.gradtensor([ 0., 3., 12., 27.])
1.5.2.2 Disabling Gradient Tracking#
During validation, inference, or parameter updates , 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 moves from to and lowers the loss from to .
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 cFor any nonzero scalar (at the while loop would never terminate), f(a) performs a fixed sequence of multiplications by (and possibly ), so f(a) = k * a is piecewise linear with local slope (Figure 1.5.4). Specifically, doubles times to reach and takes the positive branch (), whereas doubles times to and takes the else branch (). 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
The graphs recorded by f for two inputs. For , f doubles times and the first branch runs; for , it doubles times and the second branch runs. Each graph is linear in , 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, is discontinuous, yet autograd returns the slope of whichever branch ran.
1.5.4 Forward and Reverse Mode#
For a mapping with Jacobian , 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 at the outputs computes ; seeding with the standard basis vector extracts row of ( sweeps for the full Jacobian).
- Forward mode (Jacobian--vector product, JVP): A forward sweep seeded with a tangent at the inputs propagates derivatives forward alongside values to compute ; seeding with extracts column of ( sweeps for the full Jacobian, with constant memory overhead).
Two ways to fill the Jacobian of a function with inputs and outputs: (a) forward mode, sweeps in all; (b) reverse mode, sweeps in all.
PyTorch provides torch.func.vjp, torch.func.jvp, torch.func.jacrev, and torch.func.jacfwd.
A scalar loss function has output and parameters, so its Jacobian is a single row . Reverse mode (backpropagation) computes all components of the gradient in one sweep, whereas forward mode would require 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 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 (one column per basis seed) whereas one reverse-mode sweep computes a vector--Jacobian product (one row per basis seed), so for a scalar loss () a single reverse sweep yields the entire -parameter gradient.
1.5.6 Exercises#
-
[code] Detached intermediates. Let
u = x * xandc = u.detach(), and considerz = c * c,z = u * c, andz = u * u. For eachz, recomputeuandc, resetx.grad, and callbackwardon the sum of the entries ofz. Before running any code, predict the outcome of each call, including the resultingx.grad. Check your predictions, and explain the ratio between the gradients forz = u * candz = u * u. -
[code] Manual parameter updates. Perform the gradient step of this section as
w = w - 0.1 * w.grad, outsidetorch.no_grad(), and inspectw.requires_grad,w.grad_fn,w.is_leaf, andw.grad. Explain what the update has done to the graph, predict what a second forward and backward pass leaves inw.grad, and check.
-
[code] From scalar to vector input. Replace the scalar input
aof the functionfdefined in Section 1.5.3.1 by a random vector of length 5, and differentiate the sum of the entries offa = f(a)with respect toa.- Express
f(a)in terms ofa, and give the Jacobian offataand the gradient of the sum of the entries offa. - Compute this gradient with automatic differentiation and check
whether it still equals
fa / aelementwise. - Describe the set of inputs
aat whichfjumps. Which part of this set has no counterpart for a scalar input?
- Express
-
[code] Programs versus functions. Automatic differentiation differentiates the operations that a program executes, not the function that the program computes.
- The functions and are equal. Compute the derivative of each at 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 ; which of the two results does more harm in training, and why?
- Write a program that returns for every input but whose automatic derivative at is instead of . Explain why automatic differentiation cannot detect the difference.
-
Cost of second derivatives. ● The counting argument in Section 1.5.4 puts the cost of the gradient of a scalar loss with parameters at one reverse sweep. Use the same argument to estimate, in units of function evaluations, the cost of the full Hessian (the matrix of second derivatives) and the cost of a single Hessian–vector product. Explain the difference between the two costs.