PyTorch and automatic differentiation
Tensors and broadcasting, reverse-mode differentiation, PyTorch's computational graph, the Dataset → Module → optimizer pipeline, and silent bugs such as a forgotten zero_grad.
From the loop to a library
The topic What deep learning is reduced training any network to one loop: take a batch, run the model forward, compute the loss, run backward for the gradient, take a step. A library must supply four things for that loop: arrays that hold batches and parameters, a forward pass that remembers what it computed, a backward pass that turns that memory into gradients, and optimizers that apply them. This topic covers how PyTorch supplies each, builds reverse-mode differentiation for scalars from scratch, and ends with the bugs that make a pipeline run without errors and still train badly.
Notation. is a scalar loss and is the adjoint of a quantity , with the same shape as . A tensor's shape is written like ; dimension 0 is the first. is the learning rate.
Tensors and broadcasting
A tensor is an -dimensional array with a shape, a dtype and a device. The default floating type is float32. A tensor is a view of a block of memory, described by a shape and strides. Reshaping and transposing usually change only the description: x.view(2, 3) shares memory with x, so editing the view edits x.
Broadcasting compares shapes from the last dimension backwards. Two sizes are compatible when they are equal or one of them is 1. The result size is the larger of the two. Centring a batch of shape by subtracting X.mean(0) of shape works without a copy: the mean is read as .
The same rule produces a silent bug. Predictions of shape minus targets of shape broadcast to . For matching values the intended MSE is 0, but the broadcast MSE averages nine squares and equals . Cure: make shapes equal before the loss, e.g. pred.squeeze(1).
Reverse mode
Key idea. Reverse-mode differentiation needs each operation's local derivatives, computed from forward values, and a reverse topological order. If feeds nodes , then
Worked example. at , : , , . From : ; through the sum gets ; through the product and gets . Total . Check: , so .
A scalar Value sketch — storing parents and local grads, then walking the graph backwards with += into .grad — follows the same chain-rule order as torch.autograd; a numerical check against the library belongs in an optional notebook, not in a Code section of this topic. PyTorch's nodes are whole tensor operations with vector–Jacobian products, not scalar Python objects; the order is the same cheap one as in Backpropagation.
The graph in PyTorch
A tensor created with requires_grad=True, and every parameter of a module, is a leaf. Each operation returns a result with a grad_fn. L.backward() walks the chain and adds each leaf's adjoint into .grad — hence zero_grad() before each step. After backward() the graph is freed unless retain_graph=True.
Our Value |
PyTorch | Role |
|---|---|---|
Value(2.0) |
tensor(..., requires_grad=True) |
a leaf |
parents, local_grads |
grad_fn, saved tensors |
the recorded graph |
p.grad += ... |
.grad is accumulated |
hence zero_grad() |
| graph kept forever | graph freed after backward() |
second backward needs retain_graph |
torch.no_grad() stops recording. .detach() returns the same data with no history. Evaluation needs both model.eval() (right layer behaviour) and no_grad() (memory).
The training pipeline
The loop becomes five objects:
- A Dataset returns one example by index.
- A DataLoader stacks them into batches; with 1437 training images and
batch_size=64an epoch has batches, the last holding 29. - An
nn.Moduleholds parameters and definesforward. A net has parameters. - A loss such as
F.cross_entropyon logits (next topic). - An optimizer:
zero_grad(), forward,backward(),step().
model.train() / model.eval() switch layers that differ at test time (dropout, batch norm). On digits such a pipeline with SGD and momentum reaches about 0.86 test accuracy after one epoch and 0.96 after five in a reference run — reproduction belongs in an optional notebook.
Common bugs
The expensive bugs raise no error.
Forgetting zero_grad. backward() adds into .grad. Without clearing, step uses : momentum with . On with , correct SGD approaches 3; without zero_grad the weight oscillates forever between about and with period steps.
In-place ops. x += 1 or x.mul_(2) can invalidate tensors saved for backward and raise an error — or silently corrupt a view's base.
Softmax over the wrong dim. Logits of shape (batch, classes) need dim=1. With dim=0, rows need not sum to 1 and each example's "probabilities" depend on the rest of the batch. Safest fix: pass logits to the loss and never softmax beforehand.
Also: shapes that broadcast, evaluating in training mode, and total += loss (keeps every batch graph alive) instead of total += loss.item().
Toward losses and regularization
| NumPy + hand gradients | PyTorch | |
|---|---|---|
| Backward | derived per layer | derived from the recorded forward |
| Graph unit | one formula per layer | one tensor op with a VJP |
| New layer | new derivative code | only the forward |
| Silent bugs | a wrong derivative | broadcasting, missing zero_grad, wrong dim/mode |
Autograd differentiates the program, not the mathematics: ReLU at 0 has derivative 0 by convention; argmax passes no gradient. Memory grows with the stored activations.
The pipeline uses cross-entropy without asking why. The next topic, Losses and regularization, asks which loss and which regularizer for which head — and how to keep a network that can memorize its training set from doing exactly that.
Check your understanding
The same questions as in Pulse. Answers are shared between modes.
Go deeper — optional
Code and labs do not count toward the main percentage or the certificate.
- Broadcasting, gradients, and tensor shapeoptional
NumPy notebook — silent (n,1)×(n,) broadcasting, grad accumulation without clearing, and shape alignment. Self-check in the notebook.
~25 min · easier on a computer · The PyTorch and autograd topic read; basic NumPy.
Self-check in the notebook — not part of mastery or the certificate.
- Softmax in codeoptional
Turn a batch of logits into distributions without overflowing.
~15 min · easier on a computer · The PyTorch and autograd topic; softmax along the class axis.
Answers are saved on the server and tied to this browser until you sign in.