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 was . The gradient at was . 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, at . By the power rule, .
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 × 3Three new names:
requires_grad=Truetells PyTorch to record every calculation that usesx. Without it, nothing is recorded, and there is no derivative to compute..backward()works out the derivative ofywith respect to every tensor that was marked. Call it on a tensor holding a single number, likey. The backward pass is cheapest from a single number (the chain-rule chapter's Jacobian aside shows why)..gradis where the answer lands.x.gradholds , 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 , which is at .
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 numberfeatures @ w is the matrix-vector product from the tensor chapters: one prediction per delivery. .sum() adds up the three squared misses.
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 = −76torch.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 , 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 is the partial derivative for weight . So .grad is the gradient.
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.7The error is 65 and the gradient is , 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.
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.
The code builds the same graph, one small step per line:
# 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 = 2eWhat the printout shows:
grad_fn.next_functionslists the steps that fed this one, one entry per input. Fore = p - 26.0, that'sAddBackward0(fromp) andNone(the constant 26, which needs no gradient).w1.is_leafisTrue, andw1.grad_fnisNone.AccumulateGradis the last link for a leaf. It adds the arriving gradient intow1.grad.- The gradients are , which is , 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 , which is .
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 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, . Run a backward pass on each delivery's error in turn, then on the total.
w.grad = None
No gradient stored yet. The first backward() creates .grad.
Things to notice:
- A gives , B adds and C adds . Together they make : the three paths from the chain-rule chapter.
- One more backward pass on the total gives , twice the real gradient.
w.grad = Noneempties.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.gradisNone, 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.
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.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 . 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 with a step size of 0.01. Press play.
| Step 0 | w | E | w.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).
The first step is the same for both: the gradient is , and moves to . After that, the loop that forgot keeps the old 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:
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 stepHere is the full loop behind the figure above:
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.gradinsidetorch.no_grad()changeswin place. It stays the same tensor, still marked withrequires_grad, so the next loop can take its gradient again.w.grad = Noneafter each step stops old gradients from piling up. Setclear_grad=Falseto 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.
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.
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:
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 aloneIt 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 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, . 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, , has slope and curvature 8 at :
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.9create_graph=Truerecords the steps that compute the slope. The secondtorch.autograd.gradthen differentiates the slope.torch.func.jacrev(f)takes a function and returns a new function that computesf's gradient. Applied twice, it gives the gradient of the gradient: the Hessian. For the pizza error, that's , 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: . On paper, a smaller 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 , where the true slope is :
float32 | float64 | |
|---|---|---|
| 0.001 | −75.9544 | −75.9620 |
| 0.00001 | −76.2939 | −75.9996 |
| 0.0000001 | 0.0000 | −76.0000 |
In float32, the estimate gets worse as shrinks, and at it's exactly 0. Near 3, float32 can only store numbers about apart. So rounds back to 3, and the rise is 0.
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.0000Autograd never divides by a tiny , so this rounding problem can't happen. It gives in float32. If you check autograd with a nudge test, do it in float64 with around . 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_fnlinks..backward()runs the chain rule back along them to the leaves. .gradadds 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=Truelets you differentiate a derivative again.- PyTorch names in this chapter: autograd (
requires_grad,.backward(),.grad),grad_fnandretain_grad(), gradient accumulation,torch.no_grad(),.detach(),torch.autograd.gradandtorch.func.jacrev. - One idiom to remember: compute the error, call
.backward(), update insidetorch.no_grad(), then set.gradtoNone.