Deep learning and neural networksLoading progress…

Autograd

Translate an inspected NumPy model into tensors, modules, automatic differentiation and a clear training loop.

Tensors that remember how they were made

Mark a tensor with requires_grad=True and PyTorch records every operation on it, building the computation graph from the previous chapter as you go. Calling loss.backward() on a scalar result walks that graph backwards and stores each leaf tensor's gradient in its .grad.

  • Only tensors you created with requires_grad=True (the leaves) receive a .grad. Inputs and intermediate results do not keep one.
  • backward() adds to .grad. Two backward calls leave the sum of both.
  • After backward() the saved values of that graph are freed. To call it again you need a fresh forward pass (or retain_graph=True).
  • Anything that leaves PyTorch breaks the history: .item(), .numpy(), converting to a Python number, or .detach(). torch.no_grad() stops recording on purpose.
w = torch.tensor(3.0, requires_grad=True) x = torch.tensor(2.0, requires_grad=False) b = torch.tensor(1.0, requires_grad=True) loss = (w * x + b - 5) ** 2 # (3·2 + 1 − 5)² = 4
requires_grad:
(no actions yet)
tensor.gradmeaning
wNone∂loss/∂w = 2(w·x+b−5)·x = 2·2·2 = 8 per backward
xNone∂loss/∂x = 2(w·x+b−5)·w = 12 per backward
bNone∂loss/∂b = 2(w·x+b−5) = 4 per backward
A tiny loss (w·x + b − 5)². Toggle which tensors require grad and play the actions in any order. Errors are the ones PyTorch raises.

Predict first. You convert an intermediate result to a plain Python number with .item() and keep computing with it. Is the autograd connection preserved?

import torch
w = torch.tensor(3.0, requires_grad=True)
x = torch.tensor(2.0)
b = torch.tensor(1.0, requires_grad=True)
loss = (w * x + b - 5) ** 2
loss.backward()
print(w.grad, b.grad, x.grad)   # tensor(8.) tensor(4.) None
Chapter context

PyTorch provides tensor operations and differentiation infrastructure. The framework removes bookkeeping, but it does not remove the need to understand dimensions, parameter ownership, device placement and evaluation behavior.

Chapter reference: math, worked example & code

This section belongs to the whole chapter, so it is the same on every lesson in it and may cover a different lesson's topic. The code for the experiment you just ran is inside the experiment itself.

Math and notation

For a batch X of shape (B,d), a dense output with h features has shape (B,h). torch.nn.Linear stores weight with shape (h,d) and computes X times weight-transpose plus bias. Parameter count is d*h+h. PyTorch execution belongs in a linked notebook or supported runtime; the chapter does not assume browser PyTorch.

Worked example

A batch has shape (2,4). A Linear(4,3) layer stores a (3,4) weight and a length-three bias. Its output is (2,3). The parameter count is 4×3+3=15. This differs from the batch's element count: model parameters are shared across both examples.

Reference code

The following example uses the Python standard library and does not call a remote service.

batch, inputs, outputs = 2,4,3
weight_shape = (outputs,inputs)
output_shape = (batch,outputs)
assert weight_shape == (3,4)
assert output_shape == (2,3)
assert inputs*outputs+outputs == 15

Python examples are provided for study and local execution; this page does not execute Python.

Common mistakes

eval mode and no_grad are independent. Model parameters do not multiply with batch size. A tensor detached for logging must not replace the tensor used to compute the training loss.