PyTorch primer4 / 6

Lesson 4 · Gradients, randomness and numbers

Autograd: derivatives in PyTorch

The problem

In the Maths toolkit you worked out slopes by hand for the pizza error. The slope of the error slice at w1=3w_1 = 3 was −76-76. The gradient at (3,5)(3, 5) was (−98,−32)(-98, -32). You got them from the derivative rules and the chain rule.

A real model has millions of weights. Nobody works those gradients out by hand. PyTorch does it for you, and this chapter shows how. Every number below is one you already know, so you can check that PyTorch agrees.

A first derivative

PyTorch's system for derivatives is called autograd (automatic differentiation). As your code runs, it records each operation. When you ask for a derivative, it applies the derivative rule for each recorded operation, and chains them together.

Here's the smallest example, y=x2y = x^2 at x=3x = 3. By the power rule, dy/dx=2x=6dy/dx = 2x = 6.

A first derivative
x = torch.tensor(3.0, requires_grad=True)  # record everything computed from x
y = x**2                                    # y = x², so dy/dx = 2x
y.backward()                                # compute dy/dx and store it in x.grad
print(x.grad)                               # tensor(6.)  -> 2 × 3

Three new names:

  • requires_grad=True tells PyTorch to record every calculation that uses x. Without it, nothing is recorded, and there is no derivative to compute.
  • .backward() works out the derivative of y with respect to every tensor that was marked. Call it on a tensor holding a single number, like y. The backward pass is cheapest from a single number (the chain-rule chapter's Jacobian aside shows why).
  • .grad is where the answer lands. x.grad holds dy/dxdy/dx, which is 6.

Predict first

You make x = torch.tensor(3.0, requires_grad=True) and print x.grad before calling .backward(). What do you see?

Only floating-point tensors can record gradients. torch.tensor(3, requires_grad=True) holds an integer and raises an error. Write 3.0.

Now the error slice from the derivatives chapter: the pizza error with the traffic weight fixed at 6. By hand, its slope is 76w1−30476w_1 - 304, which is −76-76 at w1=3w_1 = 3.

The pizza data and the error
features = torch.tensor([[2.0, 0.0],   # A: 2 km, traffic 0
                         [5.0, 1.0],   # B: 5 km, traffic 1
                         [3.0, 2.0]])  # C: 3 km, traffic 2     shape (3, 2)
times = torch.tensor([8.0, 26.0, 24.0])  # real minutes          shape (3,)


def total_error(w: torch.Tensor) -> torch.Tensor:
    """E(w): the sum of the three squared misses. Zero at the true weights (4, 6)."""
    misses = features @ w - times  # shape (3,): one miss per delivery
    return (misses**2).sum()       # shape (): a single number

features @ w is the matrix-vector product from the tensor chapters: one prediction per delivery. .sum() adds up the three squared misses.

The slope of the error slice
def slice_slope(w1: float) -> float:
    """dE/dw1 with the traffic weight held at 6. By hand (1.6): 76 w1 − 304."""
    w1_t = torch.tensor(float(w1), requires_grad=True)
    w = torch.stack([w1_t, torch.tensor(6.0)])  # w2 is a plain constant: no gradient for it
    total_error(w).backward()
    return w1_t.grad.item()


print(slice_slope(3.0))  # -76.0, and 76 × 3 − 304 = −76

torch.stack joins the two one-number tensors into a vector of 2. Only w1_t was marked, so the 6 acts as a plain constant. .item() turns a one-number tensor into a Python number. Autograd gives exactly −76-76, matching the rule.

Gradients of several inputs

Mark a whole vector of weights, and .grad comes back as a vector of the same shape. Entry ii is the partial derivative for weight ii. So .grad is the gradient.

The gradient at (3, 5)
w = torch.tensor([3.0, 5.0], requires_grad=True)  # both weights are recorded
error = total_error(w)
error.backward()
print(error.item())  # 65.0 = 4 + 36 + 25
print(w.grad)        # tensor([-98., -32.]): (∂E/∂w1, ∂E/∂w2), the gradient from 1.7

The error is 65 and the gradient is (−98,−32)(-98, -32), as in the gradients chapter.

The recorded graph: grad_fn

In the chain-rule chapter, you drew a formula as a computational graph. Values flow forward through it. Gradients flow backward, multiplied by each box's local slope. Autograd builds exactly this graph as your code runs.

Each tensor that came out of a recorded operation has a grad_fn: a link to the step that made it. The names say what each step was. PowBackward0 is a power, SubBackward0 a subtraction, and so on.

A tensor you made yourself, like w1, rather than one computed from other tensors, is called a leaf. Leaves have no grad_fn, because no step made them. They are the ends of the graph. .backward() walks the grad_fn links from the output back to the leaves, and stores the gradients there. Running this backward pass through a whole network is called backpropagation, and the Neural-net foundations course covers it.

This is the graph from the chain-rule chapter, for delivery B, with each box labelled the way PyTorch records it. Press play to see the forward pass, then the backward pass.

AccumulateGradw₁constantx₁AccumulateGradw₂constantx₂MulBackward0w₁x₁MulBackward0w₂x₂AddBackward0pconstanttimeSubBackward0ePowBackward0s

Delivery B: x = (5 km, traffic 1), real time 26 min

Press play. The forward pass computes each value and records the step that made it.

Step 0 of 10
Delivery B's squared error as autograd records it. Each box's top label is its grad_fn. The leaves you made get AccumulateGrad, which adds the arriving gradient into .grad.

The code builds the same graph, one small step per line:

Walking the recorded graph
# Delivery B from 1.8, one small step per line, so autograd records the same boxes as the figure.
w1 = torch.tensor(3.0, requires_grad=True)
w2 = torch.tensor(5.0, requires_grad=True)
m1 = w1 * 5.0  # MulBackward0
m2 = w2 * 1.0  # MulBackward0
p = m1 + m2    # AddBackward0: the prediction, 20
e = p - 26.0   # SubBackward0: the miss, −6
s = e**2       # PowBackward0: the squared error, 36

print(s.grad_fn)                 # <PowBackward0 ...>
print(s.grad_fn.next_functions)  # ((<SubBackward0 ...>, 0),): the step that fed it
print(e.grad_fn.next_functions)  # ((<AddBackward0 ...>, 0), (None, 0)): 26 is a constant
print(w1.is_leaf, w1.grad_fn)    # True None: you made w1, no step did
e.retain_grad()                  # keep .grad for e too, though it isn't a leaf
s.backward()
print(w1.grad, w2.grad)          # tensor(-60.) tensor(-12.): 2e × x = 2(−6)(5, 1)
print(e.grad)                    # tensor(-12.): ds/de = 2e

What the printout shows:

  • grad_fn.next_functions lists the steps that fed this one, one entry per input. For e = p - 26.0, that's AddBackward0 (from p) and None (the constant 26, which needs no gradient).
  • w1.is_leaf is True, and w1.grad_fn is None.
  • AccumulateGrad is the last link for a leaf. It adds the arriving gradient into w1.grad.
  • The gradients are (−60,−12)(-60, -12), which is 2e×x=2(−6)(5,1)2e \times \mathbf{x} = 2(-6)(5, 1), as in the table in the chain-rule chapter.

By default, only leaves keep a .grad. Reading e.grad normally gives None and a warning. To keep it, call e.retain_grad() before s.backward(), as the code does. Then e.grad is −12-12, which is 2e2e.

When you write the whole error at once, as total_error(w) does, features @ w is recorded as one step, MvBackward0 (matrix times vector). The figure splits it into multiplies and an add so that you can see each slope.

.grad adds up

The total error adds up three deliveries, so w1w_1 reaches it along three paths. The chain rule says to add the paths. Within one backward pass, autograd adds the three paths inside the graph and writes .grad once.

Across calls, .grad adds up. Each .backward() adds its gradient to whatever .grad already holds. This is called gradient accumulation. It's deliberate: it lets you combine gradients from separate calls, such as several batches of data.

Try it below. All the buttons act on the same weights, (3,5)(3, 5). Run a backward pass on each delivery's error in turn, then on the total.

w.grad[0]∂E/∂w1 = -98w.grad[1]∂E/∂w2 = -32

w.grad = None

No gradient stored yet. The first backward() creates .grad.

    Each press rebuilds the graph with a fresh forward pass, then calls backward(), which adds into w.grad. A, then B, then C reaches the dashed line, the gradient of E. Pressing E then doubles it.

    Things to notice:

    • A gives (−8,0)(-8, 0), B adds (−60,−12)(-60, -12) and C adds (−30,−20)(-30, -20). Together they make (−98,−32)(-98, -32): the three paths from the chain-rule chapter.
    • One more backward pass on the total gives (−196,−64)(-196, -64), twice the real gradient.
    • w.grad = None empties .grad. w.grad.zero_() keeps the tensor but fills it with zeros. The trailing underscore means "change this tensor in place". w.grad.zero_() fails when .grad is None, so that button stays greyed out until there is a gradient.

    The code does the same. It uses .tolist(), which copies a tensor's numbers into a plain Python list. The copy is a snapshot: it won't change when w.grad does.

    One backward() per delivery
    def grad_by_delivery() -> list[list[float]]:
        """Call backward() once per delivery, without clearing .grad. Returns .grad after each call."""
        w = torch.tensor([3.0, 5.0], requires_grad=True)
        history = []
        for i in range(3):
            miss = features[i] @ w - times[i]  # a fresh forward pass for each call
            (miss**2).backward()               # adds this delivery's gradient into w.grad
            history.append(w.grad.tolist())
        return history
    
    
    print(grad_by_delivery())  # [[-8.0, -0.0], [-68.0, -12.0], [-98.0, -32.0]]: A, then A + B, then A + B + C
    # -0.0 is A's 2 × (−2) × 0: a zero that kept the minus sign. It equals 0.
    Two calls, then clear
    w = torch.tensor([3.0, 5.0], requires_grad=True)
    total_error(w).backward()
    total_error(w).backward()  # a second forward and backward, without clearing
    print(w.grad)              # tensor([-196., -64.]): twice the gradient
    w.grad = None              # clear it: the next backward() starts fresh
    # (w.grad.zero_() also works: it fills the existing tensor with zeros)

    Either way of clearing works. None is the usual choice, because it frees the memory and the next .backward() makes a fresh tensor.

    Predict first

    You compute error = total_error(w) once, then call error.backward() twice in a row. What is w.grad?

    Forgetting to clear .grad

    Gradient descent repeats one step: find the gradient, then move the weights a little against it. In the gradients chapter that was w←w−0.01∇E(w)\mathbf{w} \leftarrow \mathbf{w} - 0.01 \nabla E(\mathbf{w}). In PyTorch, each step runs a fresh forward pass, calls .backward(), and updates w with w.grad.

    If you forget to clear .grad between steps, each step uses the sum of every gradient so far. Both loops below start at (3,5)(3, 5) with a step size of 0.01. Press play.

    0246810020406080steperror Eclearedforgot
    Step 0wEw.grad
    cleared(3, 5)65(-98, -32)
    forgot(3, 5)65(-98, -32)

    Each step: a fresh forward pass and backward(), then w -= 0.01 * w.grad.

    Step 0: both loops start at (3, 5) with the true gradient (−98, −32).

    Step 0 of 11
    Two loops from (3, 5). The solid one clears w.grad each step and settles down. The dashed one forgets, so each step uses the sum of every gradient so far, and the error swings up and down.

    The first step is the same for both: the gradient is (−98,−32)(-98, -32), and w\mathbf{w} moves to (3.98,5.32)(3.98, 5.32). After that, the loop that forgot keeps the old (−98,−32)(-98, -32) inside .grad. Its next step overshoots to an error of about 41. The code still runs and raises no error, so nothing warns you.

    Updating weights: torch.no_grad

    The update w -= lr * w.grad is not part of the error's calculation. So autograd must not record it. Try it without any protection first:

    The update, unprotected
    def update_without_no_grad() -> str:
        """An in-place update on a leaf that requires grad, outside torch.no_grad(), raises an error."""
        w = torch.tensor([3.0, 5.0], requires_grad=True)
        total_error(w).backward()
        try:
            w -= 0.01 * w.grad
        except RuntimeError as err:
            return str(err)
        return "no error"
    
    
    print(update_without_no_grad())  # a leaf Variable that requires grad is being used in an in-place operation.
    RuntimeError: a leaf Variable that requires grad is being used in an in-place operation.

    w is a leaf, and -= changes it in place. Autograd needs a leaf's value to stay as it was while the graph uses it, so PyTorch refuses.

    The fix is torch.no_grad(), a block in which PyTorch records nothing:

      error = total_error(w)
      error.backward()
    - w -= lr * w.grad          # RuntimeError: in-place change to a leaf
    + with torch.no_grad():     # stop recording
    +     w -= lr * w.grad      # an ordinary update, not part of the graph
      w.grad = None             # clear it for the next step

    Here is the full loop behind the figure above:

    Gradient descent on the pizza error
    def descend(start: tuple[float, float], lr: float = 0.01, steps: int = 12, clear_grad: bool = True) -> list[dict]:
        """Gradient descent on the pizza error. Returns w, E and w.grad at every step."""
        w = torch.tensor(start, dtype=torch.float32, requires_grad=True)  # floats: integers cannot require grad
        history = []
        for _ in range(steps):
            error = total_error(w)
            error.backward()                 # adds ∇E into w.grad
            history.append({"w": w.tolist(), "error": error.item(), "grad": w.grad.tolist()})
            with torch.no_grad():            # the update is not part of the error: don't record it
                w -= lr * w.grad             # step against the gradient, in place
            if clear_grad:
                w.grad = None                # forget this, and the next step uses old gradients too
        return history
    
    
    for row in descend((3.0, 5.0))[:3]:
        print(row)
    # {'w': [3.0, 5.0], 'error': 65.0, 'grad': [-98.0, -32.0]}
    # {'w': [3.98, 5.32], 'error': 2.63, 'grad': [-16.48, -7.24]}   (rounded)
    # {'w': [4.14, 5.39], 'error': 0.71, 'grad': [-2.36, -2.89]}
    • w -= lr * w.grad inside torch.no_grad() changes w in place. It stays the same tensor, still marked with requires_grad, so the next loop can take its gradient again.
    • w.grad = None after each step stops old gradients from piling up. Set clear_grad=False to get the dashed loop.

    Cutting the graph: .detach()

    .detach() returns a tensor with the same numbers but no grad_fn. Autograd treats the result as a constant, so no gradient flows back through it.

    Predict first

    For delivery B at (3, 5), you write the square as s = e * e.detach() instead of e ** 2. What are s and the gradient?

    Tick "Write the square as e * e.detach()" below, then step to the end to watch every gradient halve.

    AccumulateGradw₁constantx₁AccumulateGradw₂constantx₂MulBackward0w₁x₁MulBackward0w₂x₂AddBackward0pconstanttimeSubBackward0ePowBackward0s

    Delivery B: x = (5 km, traffic 1), real time 26 min

    Press play. The forward pass computes each value and records the step that made it.

    Step 0 of 10
    The same graph, with the option to detach one copy of e. The square becomes a MulBackward0, and only one of its inputs passes a gradient.
    .detach() stops the gradient
    def detached_square_grad() -> list[float]:
        """s = e × e.detach(): the same value, but only one copy of e passes a gradient back."""
        w1 = torch.tensor(3.0, requires_grad=True)
        w2 = torch.tensor(5.0, requires_grad=True)
        e = w1 * 5.0 + w2 * 1.0 - 26.0
        s = e * e.detach()  # e.detach(): the same number, −6, cut off from the graph
        s.backward()
        return [w1.grad.item(), w2.grad.item()]
    
    
    print(detached_square_grad())  # [-30.0, -6.0]: half the real gradient (−60, −12)

    Detach when you mean "use this value, but don't learn through it". Common uses are logging a loss, converting to NumPy, and holding a target fixed. Don't detach anything you want to train through.

    No gradient? Check the chain

    If the chain from a weight to the output is broken, either .backward() raises an error or the weight's .grad stays None. There are three common causes:

    • the weight wasn't made with requires_grad=True
    • something on the way was detached
    • a value went through .item() or NumPy and came back as a new tensor

    Walk the grad_fn links back from the output to find the break.

    Gradients as a return value: torch.autograd.grad

    Sometimes you want the gradient as a value, without touching .grad. torch.autograd.grad hands it back:

    torch.autograd.grad
    w = torch.tensor([3.0, 5.0], requires_grad=True)
    (grad,) = torch.autograd.grad(total_error(w), w)  # a tuple: one gradient per input asked about
    print(grad)    # tensor([-98., -32.])
    print(w.grad)  # None: torch.autograd.grad leaves .grad alone

    It returns a tuple with one gradient for each input you ask about. That's why the code writes (grad,) = ... to unpack the single entry. Nothing is added to w.grad, so there's nothing to clear. It can also ask about a middle box: torch.autograd.grad(s, e) gives ∂s/∂e\partial s / \partial e without retain_grad(). Use it instead of .backward(), not after it, since .backward() frees the graph.

    Second derivatives

    The second derivative is the slope of the slope. In the approximation chapter's slope-of-slope figure, it's the steepness of the bottom curve, E′E'. To get it, autograd must treat the slope as something it can differentiate again. So it must record how it computed the slope. create_graph=True asks for that: it lets autograd take the slope of that bottom curve.

    The approximation chapter's bumpy curve, E(w)=(w2−4)2/4+w/2+2E(w) = (w^2 - 4)^2 / 4 + w/2 + 2, has slope 0.50.5 and curvature 8 at w=2w = 2:

    Slope, curvature and the Hessian
    def bumpy_error(w: torch.Tensor) -> torch.Tensor:
        """The two-valley curve from 1.9: E(w) = (w² − 4)² / 4 + w / 2 + 2."""
        return (w**2 - 4) ** 2 / 4 + w / 2 + 2
    
    
    def slope_and_curvature(w0: float) -> tuple[float, float]:
        """E′(w0) and E″(w0). create_graph=True records how the slope was computed."""
        w = torch.tensor(float(w0), requires_grad=True)
        (slope,) = torch.autograd.grad(bumpy_error(w), w, create_graph=True)
        (curvature,) = torch.autograd.grad(slope, w)
        return slope.item(), curvature.item()
    
    
    print(slope_and_curvature(2.0))  # (0.5, 8.0)
    
    # torch.func.jacrev(f) returns a new function that computes f's gradient.
    # Apply it twice: the gradient of the gradient is the Hessian.
    hessian_fn = torch.func.jacrev(torch.func.jacrev(total_error))
    print(hessian_fn(torch.tensor([4.0, 6.0])))  # tensor([[76., 22.], [22., 10.]]): the Hessian from 1.9
    • create_graph=True records the steps that compute the slope. The second torch.autograd.grad then differentiates the slope.
    • torch.func.jacrev(f) takes a function and returns a new function that computes f's gradient. Applied twice, it gives the gradient of the gradient: the Hessian. For the pizza error, that's (76222210)\begin{pmatrix} 76 & 22 \\ 22 & 10 \end{pmatrix}, as in the approximation chapter.

    Predict first

    You leave out create_graph=True in the first torch.autograd.grad call. What does the second call do?

    DigressionWhy autograd beats the nudge test on a computerIn float32, a tiny nudge rounds away to nothing. Autograd never divides by a tiny h. · 3 min

    The nudge test from the derivatives chapter estimates a slope with rise over run: (f(x+h)−f(x))/h(f(x + h) - f(x)) / h. On paper, a smaller hh always gives a better estimate. On a computer it doesn't, because numbers are stored with limited digits.

    PyTorch's default number type, float32, keeps about 7 significant digits. float64 keeps about 16. Here is the nudge test on the error slice at w1=3w_1 = 3, where the true slope is −76-76:

    hhfloat32float64
    0.001−75.9544−75.9620
    0.00001−76.2939−75.9996
    0.00000010.0000−76.0000

    In float32, the estimate gets worse as hh shrinks, and at h=10−7h = 10^{-7} it's exactly 0. Near 3, float32 can only store numbers about 2.4×10−72.4 \times 10^{-7} apart. So 3+10−73 + 10^{-7} rounds back to 3, and the rise is 0.

    The nudge test in float32 and float64
    def nudge_slope(dtype: torch.dtype, h: float) -> float:
        """Rise over run on the error slice 38(w1 − 4)² at w1 = 3. The true slope is −76."""
        at = torch.tensor(3.0, dtype=dtype)
        f = lambda a: 38 * (a - 4) ** 2
        return ((f(at + h) - f(at)) / h).item()
    
    
    for h in (1e-3, 1e-5, 1e-7):
        print(f"h = {h:g}: float32 {nudge_slope(torch.float32, h):9.4f}, float64 {nudge_slope(torch.float64, h):9.4f}")
    # h = 0.001: float32  -75.9544, float64  -75.9620
    # h = 1e-05: float32  -76.2939, float64  -75.9996
    # h = 1e-07: float32    0.0000, float64  -76.0000

    Autograd never divides by a tiny hh, so this rounding problem can't happen. It gives −76-76 in float32. If you check autograd with a nudge test, do it in float64 with hh around 10−410^{-4}. Chapter 2.6, "Numbers and stability", covers float32 in depth.

    Common misconceptions

    "Autograd is a nudge test." It never nudges anything. It records the operations and applies the exact rule for each one. It's also cheap: one backward pass gives every partial derivative, while nudging needs one extra run per input.

    "Calling .backward() again recomputes the gradient." If you run the forward pass again, a second .backward() adds onto the old gradient. On the same graph, it raises an error.

    ".detach() deletes the value." It keeps the value and drops the link to the graph. Only the gradient stops.

    "torch.no_grad() stops the weights from changing." It stops autograd from recording. The weights change as normal inside it.

    Recap

    • Mark a tensor with requires_grad=True, compute one number from it, and call .backward(). The exact derivative lands in .grad.
    • Autograd records the computational graph as grad_fn links. .backward() runs the chain rule back along them to the leaves.
    • .grad adds up across calls, so clear it before each new gradient.
    • Update weights inside torch.no_grad(), so autograd doesn't record the update. .detach() cuts a link in the graph.
    • create_graph=True lets you differentiate a derivative again.
    • PyTorch names in this chapter: autograd (requires_grad, .backward(), .grad), grad_fn and retain_grad(), gradient accumulation, torch.no_grad(), .detach(), torch.autograd.grad and torch.func.jacrev.
    • One idiom to remember: compute the error, call .backward(), update inside torch.no_grad(), then set .grad to None.