Skip to content
BIASED

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. LL is a scalar loss and uˉ=∂L/∂u\bar u = \partial L / \partial u is the adjoint of a quantity uu, with the same shape as uu. A tensor's shape is written like (64,10)(64, 10); dimension 0 is the first. η\eta is the learning rate.

Tensors and broadcasting

A tensor is an nn-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 (2,3)(2, 3) by subtracting X.mean(0) of shape (3,)(3,) works without a copy: the mean is read as (1,3)(1, 3).

The same rule produces a silent bug. Predictions of shape (n,1)(n, 1) minus targets of shape (n,)(n,) broadcast to (n,n)(n, n). For matching values (1,2,3)(1,2,3) the intended MSE is 0, but the broadcast MSE averages nine squares and equals 12/9=1.33312/9 = 1.333. 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 uu feeds nodes v1,…,vkv_1, \dots, v_k, then

uˉ=∑c=1kvˉc ∂vc∂u.\bar u = \sum_{c=1}^{k} \bar v_c\, \frac{\partial v_c}{\partial u}.

Worked example. L=(ab+a)2L = (ab + a)^2 at a=2a=2, b=−3b=-3: c=ab=−6c=ab=-6, d=c+a=−4d=c+a=-4, L=16L=16. From Lˉ=1\bar L=1: dˉ=−8\bar d=-8; through the sum aa gets −8-8; through the product bˉ=−16\bar b=-16 and aa gets 2424. Total aˉ=16\bar a = 16. Check: L=a2(b+1)2L = a^2(b+1)^2, so ∂L/∂a=2a(b+1)2=16\partial L/\partial a = 2a(b+1)^2 = 16.

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:

  1. A Dataset returns one example by index.
  2. A DataLoader stacks them into batches; with 1437 training images and batch_size=64 an epoch has ⌈1437/64⌉=23\lceil 1437/64\rceil = 23 batches, the last holding 29.
  3. An nn.Module holds parameters and defines forward. A 64→128→1064 \to 128 \to 10 net has 64⋅128+128+128⋅10+10=961064\cdot 128 + 128 + 128\cdot 10 + 10 = 9610 parameters.
  4. A loss such as F.cross_entropy on logits (next topic).
  5. 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 kk uses ∑j=0kgj\sum_{j=0}^{k} g_j: momentum with β=1\beta=1. On L(w)=12(w−3)2L(w)=\tfrac12(w-3)^2 with η=0.1\eta=0.1, correct SGD approaches 3; without zero_grad the weight oscillates forever between about −0.04-0.04 and 6.046.04 with period ≈19.8\approx 19.8 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.

    Open practice

Full notes

Answers are saved on the server and tied to this browser until you sign in.