Course map
Stage 1: Foundations
Stage 2: Machine Learning
Stage 3: Deep Learning
Stage 4: LLMs & Generative AI
Stage 5: Production & Specialization

Part 10 / Topic 2 of 7

Autograd

Set requires_grad=True and PyTorch records every operation; loss.backward() replays the tape in reverse — Part 9's backward pass, automated:

# examples/01_autograd_computes_gradients_for_you.py
w = torch.tensor(2.0, requires_grad=True)
x, y = torch.tensor(3.0), torch.tensor(12.0)
loss = (w * x - y) ** 2
loss.backward()
print(w.grad.item())   # -36.0 — same as Part 2's hand-derived 2*(w*x-y)*x

One behaviour to burn in: gradients accumulate. Calling backward() twice on 2*w leaves w.grad == 4, not 2 (verified in this environment). That is why the training loop starts with zero_grad().

🧪 Quick quiz

  1. Why call optimizer.zero_grad() every step?
Show the answer

Gradients accumulate across backward() calls by default — two backward passes on 2·w leave a gradient of 4, not 2. Without zeroing, every step would mix in stale gradients.

Done here? The practice set for Part 10 — 4 exercises with solutions — is on the part page.

Search the guide