1.5  Automatic Differentiation

In Section 1.4, deriving the gradient \(\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
import tensorflow as tf
import jax
from jax import numpy as jnp
from mxnet import autograd, np as mnp, npx
npx.set_np()

1.5.1 Computing Gradients

1.5.1.1 The Forward Pass

We first set up the line model \(L(\mathbf{w}) = \|\mathbf{X}\mathbf{w} - \mathbf{y}\|^2\) at \(\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()
X = tf.constant([[1.0, 0.0], [1.0, 1.0], [1.0, 2.0]])  # [1, input]
y = tf.constant([1.0, 1.0, 0.0])
w = tf.constant([1.0, 0.0])

def loss(w):
    return tf.reduce_sum((tf.linalg.matvec(X, w) - y) ** 2)
X = jnp.array([[1.0, 0.0], [1.0, 1.0], [1.0, 2.0]])  # [1, input]
y = jnp.array([1.0, 1.0, 0.0])
w = jnp.array([1.0, 0.0])

def loss(w):
    return ((X @ w - y) ** 2).sum()
X = mnp.array([[1.0, 0.0], [1.0, 1.0], [1.0, 2.0]])  # [1, input]
y = mnp.array([1.0, 1.0, 0.0])
w = mnp.array([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.

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

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:

Wrapping w in tf.Variable marks it as a trainable parameter that gradient tapes watch automatically:

Calling w.attach_grad() marks w for gradient tracking and allocates its gradient buffer w.grad (initialized to zeros):

w.requires_grad_(True)
tensor([1., 0.], requires_grad=True)
w = tf.Variable(w)
w.attach_grad()
w.grad
array([0., 0.])

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

We now evaluate L = loss(w) inside a with tf.GradientTape() as t: block so TensorFlow records the operations connecting w to L on the tape t:

JAX takes a purely functional approach: arrays carry no mutable gradient buffers, so evaluating loss(w) on its own runs ordinary array arithmetic and returns 1.0. Instead, jax.grad(loss) will trace loss when we differentiate it below:

We now evaluate L = loss(w) inside a with autograd.record(): block so MXNet records the operations connecting w to L:

L = loss(w)
L
tensor(1., grad_fn=<SumBackward0>)
with tf.GradientTape() as t:  # record the operations on the tape t
    L = loss(w)
L
<tf.Tensor: shape=(), dtype=float32, numpy=1.0>
loss(w)
Array(1., dtype=float32)
with autograd.record():  # record the operations that compute the loss
    L = loss(w)
L
array(1.)

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: \(\hat{\mathbf{y}} = \mathbf{X}\mathbf{w}\), \(\mathbf{r} = \hat{\mathbf{y}} - \mathbf{y}\), \(\mathbf{s} = \mathbf{r} \odot \mathbf{r}\), and \(L = \sum_i s_i\).

Figure 1.5.1: The computational graph of \(L = \|\mathbf{X}\mathbf{w} - \mathbf{y}\|^2\) at \(\mathbf{w} = (1, 0)\), with one node for \(\mathbf{w}\) and for each value computed from it; the constants \(\mathbf{X}\) and \(\mathbf{y}\) are not drawn, and \(\mathbf{r} \odot \mathbf{r}\) is the elementwise square. Each node shows its value (black) and the gradient of \(L\) with respect to it (red). The forward pass (blue) runs from left to right; the backward pass (red) starts from \(1\) at \(L\) 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 \(\partial L/\partial L = 1\) at the output back to \(\mathbf{w}\) through each node’s local derivative rule,

\[\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)\):

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

t.gradient(L, w) computes the gradient of L with respect to w from the tape t.

jax.grad(loss)(w) evaluates the gradient function at w.

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

L.backward()
w.grad
tensor([2., 4.])
t.gradient(L, w)
<tf.Tensor: shape=(2,), dtype=float32, numpy=array([2., 4.], dtype=float32)>
jax.grad(loss)(w)
Array([2., 4.], dtype=float32)
L.backward()
w.grad
array([2., 4.])

Because local backward rules require intermediate activations from the forward pass (such as \(\mathbf{r}\) and \(\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 \(\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 \(\mathbf{w}\)?

Because jax.grad(loss)(w) is a pure function that returns a fresh array on every call and stores no state on w, calling it repeatedly always returns (2, 4) without side effects; to accumulate gradients across micro-batches, you simply sum the returned arrays explicitly.

L = loss(w)
L.backward()
w.grad  # the new gradient was added to the old one
tensor([4., 8.])
with tf.GradientTape() as t:
    L = loss(w)
t.gradient(L, w)  # a new tensor; nothing is stored in w
<tf.Tensor: shape=(2,), dtype=float32, numpy=array([2., 4.], dtype=float32)>
with autograd.record():
    L = loss(w)
L.backward()
w.grad  # overwritten by the new gradient
array([2., 4.])

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

t.gradient(L, w) returns a fresh tensor without storing state on w, giving (2, 4) again; to accumulate gradients across micro-batches, sum the returned tensors explicitly.

MXNet overwrites w.grad on each new backward pass by default, returning (2, 4) again.

1.5.1.4 Vector-Valued Functions

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

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

t.gradient accepts \(\mathbf{v}\) via output_gradients (defaulting to \(\mathbf{1}\) if omitted).

jax.vjp(losses, w) returns the forward value and a function mapping \(\mathbf{v}\) to \((\mathbf{J}^\top\mathbf{v},)\).

losses.backward(v) accepts \(\mathbf{v}\) (defaulting to \(\mathbf{1}\) if omitted).

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.])
with tf.GradientTape() as t:
    losses = (tf.linalg.matvec(X, w) - y) ** 2  # per-example losses
t.gradient(losses, w, output_gradients=tf.ones(3))  # v = 1
<tf.Tensor: shape=(2,), dtype=float32, numpy=array([2., 4.], dtype=float32)>
def losses(w):
    return (X @ w - y) ** 2  # one loss per example

_, vjp = jax.vjp(losses, w)  # vjp maps v to J^T v
vjp(jnp.ones(3))[0]  # v = 1
Array([2., 4.], dtype=float32)
with autograd.record():
    losses = (X @ w - y) ** 2  # one loss per example
losses.backward(mnp.ones(3))  # v = 1: differentiates losses.sum()
w.grad
array([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 = x^2\) and \(z = u x\) on \(\mathbf{x} = (0, 1, 2, 3)\) (Figure 1.5.3): when \(u\) is attached, gradient flows along both paths to give \(\partial z/\partial x = 3x^2\); when \(u\) is detached to \(c\), differentiating \(z = c x\) treats \(c\) as a constant and gives \(\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 = ux\) with \(u = 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 \(u\) creates a constant \(c\) with the same value and no connection to \(x\).

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

tf.stop_gradient(u) passes u forward while blocking backward gradients.

jax.lax.stop_gradient(u) blocks gradients inside a differentiated function.

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.])
x = tf.Variable(tf.range(4.0))
with tf.GradientTape() as t:
    u = x * x
    c = tf.stop_gradient(u)  # values of u, no history
    z = c * x
t.gradient(z, x)
<tf.Tensor: shape=(4,), dtype=float32, numpy=array([0., 1., 4., 9.], dtype=float32)>
x = jnp.arange(4.0)

def z(x):
    u = x * x
    c = jax.lax.stop_gradient(u)  # values of u, no history
    return c * x

jax.grad(lambda x: z(x).sum())(x)
Array([0., 1., 4., 9.], dtype=float32)
x = mnp.arange(4.0)
x.attach_grad()
with autograd.record():
    u = x * x
    c = u.detach()  # values of u, no history
    z = c * x
z.backward()
x.grad
array([0., 1., 4., 9.])

By contrast, if we compute z = u * x directly without detaching u, backpropagation flows through both factors of \(z = x^3\) and returns \(\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.])
with tf.GradientTape() as t:
    u = x * x
    z = u * x
t.gradient(z, x)
<tf.Tensor: shape=(4,), dtype=float32, numpy=array([ 0.,  3., 12., 27.], dtype=float32)>
jax.grad(lambda x: (x * x * x).sum())(x)
Array([ 0.,  3., 12., 27.], dtype=float32)
with autograd.record():
    u = x * x
    z = u * x
z.backward()
x.grad
array([ 0.,  3., 12., 27.])

1.5.2.2 Disabling Gradient Tracking

During validation, inference, or parameter updates \(\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).

Code outside tf.GradientTape runs unrecorded; w.assign_sub(...) updates w in place.

Outside jax.grad, array arithmetic runs untraced.

Code outside autograd.record() runs unrecorded; w[:] = ... updates w in place while keeping w.grad.

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))
with tf.GradientTape() as t:
    L = loss(w)
w.assign_sub(0.1 * t.gradient(L, w))  # outside the tape
w.numpy(), round(float(loss(w)), 4)
(array([ 0.8, -0.4], dtype=float32), 0.4)
w = w - 0.1 * jax.grad(loss)(w)
w, loss(w)
(Array([ 0.8, -0.4], dtype=float32), Array(0.4, dtype=float32))
w[:] = w - 0.1 * w.grad  # outside autograd.record(): not recorded
w, loss(w)
(array([ 0.8, -0.4]), array(0.4))

As in Section 1.4, one step with \(\eta = 0.1\) moves \(\mathbf{w}\) from \((1, 0)\) to \((0.8, -0.4)\) and lowers the loss from \(1\) to \(0.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
def f(a):
    b = a * 2
    while tf.norm(b) < 1000:
        b = b * 2
    if tf.reduce_sum(b) > 0:
        c = b
    else:
        c = 100 * b
    return c
def f(a):
    b = a * 2
    while jnp.linalg.norm(b) < 1000:
        b = b * 2
    if b.sum() > 0:
        c = b
    else:
        c = 100 * b
    return c
def f(a):
    b = a * 2
    while mnp.linalg.norm(b) < 1000:
        b = b * 2
    if b.sum() > 0:
        c = b
    else:
        c = 100 * b
    return c

For any nonzero scalar \(a\) (at \(a = 0\) the while loop would never terminate), f(a) performs a fixed sequence of multiplications by \(2\) (and possibly \(100\)), so f(a) = k * a is piecewise linear with local slope \(k = f(a)/a\) (Figure 1.5.4). Specifically, \(a = 0.3\) doubles \(12\) times to reach \(0.3 \times 2^{12} = 1228.8 \ge 1000\) and takes the positive branch (\(k = 2^{12} = 4096\)), whereas \(a = -0.75\) doubles \(11\) times to \(-1536\) and takes the else branch (\(k = 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
for value in (0.3, -0.75):
    a = tf.Variable(value)
    with tf.GradientTape() as t:
        fa = f(a)
    print(f'a = {value:5.2f}   f(a) / a = {float(fa) / value:6.0f}   '
          f'gradient = {float(t.gradient(fa, a)):6.0f}')
a =  0.30   f(a) / a =   4096   gradient =   4096
a = -0.75   f(a) / a = 204800   gradient = 204800
for value in (0.3, -0.75):
    a = jnp.array(value)
    print(f'a = {value:5.2f}   f(a) / a = {f(a) / a:6.0f}   '
          f'gradient = {jax.grad(f)(a):6.0f}')
a =  0.30   f(a) / a =   4096   gradient =   4096
a = -0.75   f(a) / a = 204800   gradient = 204800
for value in (0.3, -0.75):
    a = mnp.array(value)
    a.attach_grad()
    with autograd.record():
        fa = f(a)
    fa.backward()
    print(f'a = {value:5.2f}   f(a) / a = {float(fa) / value:6.0f}   '
          f'gradient = {float(a.grad):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.3\), f doubles \(a\) \(12\) times and the first branch runs; for \(a = -0.75\), it doubles \(a\) \(11\) times and the second branch runs. Each graph is linear in \(a\), 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)\) is discontinuous, yet autograd returns the slope of whichever branch ran.

1.5.4 Forward and Reverse Mode

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

  • Reverse mode (vector–Jacobian product, VJP): A reverse sweep seeded with \(\mathbf{v} \in \mathbb{R}^m\) at the outputs computes \(\mathbf{J}^\top \mathbf{v}\); seeding with the \(j^\textrm{th}\) standard basis vector \(\mathbf{v} = \mathbf{e}_j\) extracts row \(j\) of \(\mathbf{J}\) (\(m\) sweeps for the full Jacobian).
  • Forward mode (Jacobian–vector product, JVP): A forward sweep seeded with a tangent \(\mathbf{d} \in \mathbb{R}^n\) at the inputs propagates derivatives forward alongside values to compute \(\mathbf{J}\mathbf{d}\); seeding with \(\mathbf{d} = \mathbf{e}_i\) extracts column \(i\) of \(\mathbf{J}\) (\(n\) sweeps for the full Jacobian, with constant \(2\times\) memory overhead).
Figure 1.5.5: Two ways to fill the \(m \times n\) Jacobian \(\mathbf{J}\) of a function with \(n\) inputs and \(m\) outputs: (a) forward mode, \(n\) sweeps in all; (b) reverse mode, \(m\) sweeps in all.

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

TensorFlow provides GradientTape.jacobian (reverse mode) and tf.autodiff.ForwardAccumulator (forward mode).

JAX provides jax.vjp, jax.jvp, jax.jacrev, and jax.jacfwd.

MXNet implements reverse-mode automatic differentiation only.

A scalar loss function has \(m = 1\) output and \(n\) parameters, so its Jacobian is a single row \(\nabla_{\mathbf{w}} L^\top\). Reverse mode (backpropagation) computes all \(n\) components of the gradient in one sweep, whereas forward mode would require \(n\) 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 \(\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 \(\mathbf{J}\mathbf{d}\) (one column per basis seed) whereas one reverse-mode sweep computes a vector–Jacobian product \(\mathbf{J}^\top\mathbf{v}\) (one row per basis seed), so for a scalar loss (\(m = 1\)) a single reverse sweep yields the entire \(n\)-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.

  3. [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?
  4. [code] Programs versus functions. Automatic differentiation differentiates the operations that a program executes, not the function that the program computes.

    1. The functions \(|x|\) and \(\sqrt{x^2}\) are equal. Compute the derivative of each at \(x = 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 \(0\); which of the two results does more harm in training, and why?
    2. Write a program that returns \(x^2\) for every input \(x\) but whose automatic derivative at \(x = 0\) is \(1\) instead of \(0\). Explain why automatic differentiation cannot detect the difference.
  5. Cost of second derivatives. ● The counting argument in Section 1.5.4 puts the cost of the gradient of a scalar loss with \(n\) parameters at one reverse sweep. Use the same argument to estimate, in units of function evaluations, the cost of the full Hessian (the \(n \times n\) matrix of second derivatives) and the cost of a single Hessian–vector product. Explain the difference between the two costs.

  1. [code] Detached intermediates. Let u = x * x and c = tf.stop_gradient(u) inside a persistent tf.GradientTape t. Before running any code, predict t.gradient(z, x) for each of z = c * c, z = u * c, and z = u * u, all computed inside t. Check your predictions, and explain the ratio between the results 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 * g, where g is the gradient returned by the tape, instead of with assign_sub, and inspect type(w). Predict what gradient returns for a second forward pass under a new tape, check, and explain why a training loop updates variables with assign_sub.

  3. [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?
  4. [code] Programs versus functions. Automatic differentiation differentiates the operations that a program executes, not the function that the program computes.

    1. The functions \(|x|\) and \(\sqrt{x^2}\) are equal. Compute the derivative of each at \(x = 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 \(0\); which of the two results does more harm in training, and why?
    2. Write a program that returns \(x^2\) for every input \(x\) but whose automatic derivative at \(x = 0\) is \(1\) instead of \(0\). Explain why automatic differentiation cannot detect the difference.
  5. Cost of second derivatives. ● The counting argument in Section 1.5.4 puts the cost of the gradient of a scalar loss with \(n\) parameters at one reverse sweep. Use the same argument to estimate, in units of function evaluations, the cost of the full Hessian (the \(n \times n\) matrix of second derivatives) and the cost of a single Hessian–vector product. Explain the difference between the two costs.

  1. [code] Detached intermediates. Write three functions of x that compute u = x * x and c = jax.lax.stop_gradient(u) and return c * c, u * c, and u * u, respectively. Before running any code, predict the gradient of the sum of the entries of each result with respect to x. Check your predictions with jax.grad, and explain the ratio between the results for u * c and u * u.

  2. [code] Manual parameter updates. Let w = jnp.arange(4.0) and g = lambda x: (w * x).sum(), which reads w from the enclosing scope. Predict jax.grad(g)(x), check, and state with respect to which array jax.grad differentiates. Then rewrite g so that jax.grad returns the gradient of (w * x).sum() with respect to w, use it for one update of w with learning rate 0.1, and explain what this implies for how a JAX training loop must pass the parameters to the loss function.

  3. [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?
  4. [code] Programs versus functions. Automatic differentiation differentiates the operations that a program executes, not the function that the program computes.

    1. The functions \(|x|\) and \(\sqrt{x^2}\) are equal. Compute the derivative of each at \(x = 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 \(0\); which of the two results does more harm in training, and why?
    2. Write a program that returns \(x^2\) for every input \(x\) but whose automatic derivative at \(x = 0\) is \(1\) instead of \(0\). Explain why automatic differentiation cannot detect the difference.
  5. Cost of second derivatives. ● The counting argument in Section 1.5.4 puts the cost of the gradient of a scalar loss with \(n\) parameters at one reverse sweep. Use the same argument to estimate, in units of function evaluations, the cost of the full Hessian (the \(n \times n\) matrix of second derivatives) and the cost of a single Hessian–vector product. Explain the difference between the two costs.

  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, compute u, c, and z afresh inside an autograd.record() scope and call z.backward(). 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 instead of w[:] = w - 0.1 * w.grad, and inspect w.grad. Explain what the rebinding has done to the buffer allocated by attach_grad, predict what a second recorded forward pass followed by backward does, and check.

  3. [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?
  4. [code] Programs versus functions. Automatic differentiation differentiates the operations that a program executes, not the function that the program computes.

    1. The functions \(|x|\) and \(\sqrt{x^2}\) are equal. Compute the derivative of each at \(x = 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 \(0\); which of the two results does more harm in training, and why?
    2. Write a program that returns \(x^2\) for every input \(x\) but whose automatic derivative at \(x = 0\) is \(1\) instead of \(0\). Explain why automatic differentiation cannot detect the difference.
  5. Cost of second derivatives. ● The counting argument in Section 1.5.4 puts the cost of the gradient of a scalar loss with \(n\) parameters at one reverse sweep. Use the same argument to estimate, in units of function evaluations, the cost of the full Hessian (the \(n \times n\) matrix of second derivatives) and the cost of a single Hessian–vector product. Explain the difference between the two costs.