The Training Loop: Forward, Loss, Zero-Grad, Backward, Step
Agent-Assisted Engineering Check
Prerequisites
Day 35 hand derivation of all nine N1 gradients.
Learning Objective
State the five-step gradient-descent loop contract — forward, loss, zero_grad, backward, parameter step $\theta \leftarrow \theta - \eta \nabla L$ — explain the role of the learning rate $\eta$, and distinguish full-batch descent from per-sample stochastic updates.
Instructions
Read the loop contract, then predict before running.
for epoch in range(EPOCHS):
for p in model.parameters():
p.grad = 0.0 # 1. zero stale gradients
total = 0.0
for (x, y) in dataset:
out = model(x) # 2. forward
loss = (out - y) ** 2 # 3. loss
loss.backward() # 4. backward (accumulates batch grads)
total += loss.data
for p in model.parameters():
p.data -= lr * p.grad # 5. step along -gradient
log(epoch, total / len(dataset))
Two properties matter: zero must run before backward in every epoch (gradients accumulate by design), and the step size $\eta$ scales the update. Today's toy dataset: four points $(x, y)$: $((2,-1), 1)$, $((0.5,0.5), -1)$, $((-1,1), -1)$, $((1,1), 1)$; N1's initial mean squared loss is $2.106$.
Practice & Prediction Log
1. For the first sample $((2,-1), 1)$, $b_o$'s gradient is $4.2511$: predict the sign and size of a single-sample (stochastic) update at $\eta = 0.05$.
2. In the full-batch loop, the four per-sample gradients accumulate; measured, $b_o$'s epoch-0 batch gradient is $3.2111$. Predict that step.
3. Predict what happens to the mean loss after 40 epochs at $\eta = 0.05$ — decrease, plateau, or divergence?
4. State precisely where zero_grad must sit in the loop and what single-line bug removes its effect.
A positive gradient means the parameter must decrease to reduce loss: the stochastic step is $b_o \leftarrow 0.3 - 0.05 \times 4.2511$, while the batch step uses the accumulated $3.2111$. For this full-batch update, zero the parameter gradients once before the sample loop. Zeroing before each sample would discard earlier samples' contributions; it is appropriate only when each sample has its own stochastic update.
Reference Solution:
1. Stochastic step: $\Delta b_o = -0.05 \times 4.2511 = -0.2126$, so $b_o$ would fall from $0.3$ to $\approx 0.0874$.
2. Full-batch step: $\Delta b_o = -0.05 \times 3.2111 = -0.1606$, giving $b_o \approx 0.1394$ after epoch 0 — same direction, different magnitude, because the batch gradient sums all four samples.
3. Measured: the mean loss falls monotonically from $2.106$ to $\approx 0.13$ over 40 epochs at $\eta = 0.05$ (single toy run — evidence the loop works, not a general guarantee).
4. zero_grad must run once per epoch before any backward() call; omitting it keeps every previous gradient in .grad, so the step uses a corrupted sum.
The learner writes the five-step contract in order, predicts the direction and size of a parameter update, and explains the accumulation policy that makes zero_grad mandatory.
Authoritative Source Resources & Provenance
PyTorch Documentation: Autograd Mechanics
Relevant Section / Range: How autograd encodes the history
Verified Version & Date: PyTorch 2.5 Documentation (Verified: 2026-10-30)
Official reference for computational graph construction, backward pass execution, and in-place mutation pitfalls.
Basic understanding of computational graphs and tensors.
The training loop mechanics and zero_grad requirements are illustrated with runnable Python code.
Compared Candidate Sources & Selection Analysis (2)
Alternative tape-based execution; PyTorch dynamic graph semantics are standard in modern LLM research.
Functional transformations (grad, vjp); PyTorch object-based graph is closer to the beginner micrograd model.
Neural Networks and Deep Learning: How the backpropagation algorithm works
Relevant Section / Range: Section: Learning with gradient descent
Verified Version & Date: Online book (Verified: 2026-10-30)
Clear four-equation derivation of backpropagation with scalar and matrix notation.
Matrix multiplication and the multivariable chain rule from Days 19-24.
All four backprop equations and derivations are self-contained within the lesson text.
Compared Candidate Sources & Selection Analysis (2)
Comprehensive graduate reference, but heavier tensor notation than needed for first MLP derivations.
Modular computational graph view; used as secondary source on Days 35-36.