36 / 90

Day 36: Training Loops and Gradient Failure Diagnosis

Close the MLP block: assemble the full gradient-descent loop on the scalar engine, record real loss curves at different learning rates, and diagnose the three classic gradient failures — saturation, missing zero_grad, and silent shape truncation.

Models, Pretraining & LoRA 480 active minutes (8 hours focused study)
01 120 min

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.

Independent Mastery Criterion

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

linking Modified BSD

PyTorch Documentation: Autograd Mechanics

Author: PyTorch Contributors | Original Source Link ↗

Relevant Section / Range: How autograd encodes the history

Verified Version & Date: PyTorch 2.5 Documentation (Verified: 2026-10-30)

Selection Rationale:

Official reference for computational graph construction, backward pass execution, and in-place mutation pitfalls.

Source Prerequisites:

Basic understanding of computational graphs and tensors.

Safe Fallback (Offline Resilience):

The training loop mechanics and zero_grad requirements are illustrated with runnable Python code.

Compared Candidate Sources & Selection Analysis (2)
TensorFlow tf.GradientTape Documentation ↗ compared_alternative [Apache 2.0]

Alternative tape-based execution; PyTorch dynamic graph semantics are standard in modern LLM research.

JAX autodiff cookbook ↗ compared_alternative [Apache 2.0]

Functional transformations (grad, vjp); PyTorch object-based graph is closer to the beginner micrograd model.

linking CC BY-NC 3.0 noncommercial

Neural Networks and Deep Learning: How the backpropagation algorithm works

Author: Michael Nielsen | Original Source Link ↗

Relevant Section / Range: Section: Learning with gradient descent

Verified Version & Date: Online book (Verified: 2026-10-30)

Selection Rationale:

Clear four-equation derivation of backpropagation with scalar and matrix notation.

Source Prerequisites:

Matrix multiplication and the multivariable chain rule from Days 19-24.

Safe Fallback (Offline Resilience):

All four backprop equations and derivations are self-contained within the lesson text.

Compared Candidate Sources & Selection Analysis (2)
Goodfellow et al. Deep Learning (Chapter 6) ↗ compared_alternative [All Rights Reserved (free to view online)]

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.

02 120 min

Observed Training Runs: Learning-Rate Effects on a Tiny Dataset

Independent Mastery Check

Prerequisites

Loop contract from Activity 36-01 and the MLP classes from Day 34.

Learning Objective

Execute two real training runs of N1 on the four-point dataset — one at $\eta = 0.05$ and one at $\eta = 5.0$ — record the mean loss at epochs 0, 10, 20, 30, and 39, and explain the divergence mechanism in the second run without overgeneralizing from one toy experiment.

Instructions

Run this public project command from the repository root. It resets N1 to the same initial weights for each learning rate, rebuilds the graph per sample, accumulates the four sample gradients, and logs mean loss before each update. The update uses the sum of gradients, not the mean; changing that convention changes the effective learning rate.

python3 - <<'EOF'
from projects.autograd.engine import Value
initial = [0.5, -0.25, 0.1, -0.5, 1.0, -0.2, 1.0, -2.0, 0.3]
data = [((2.0,-1.0),1.0), ((0.5,0.5),-1.0), ((-1.0,1.0),-1.0), ((1.0,1.0),1.0)]
for lr in (0.05, 5.0):
    params = initial[:]
    for epoch in range(40):
        W = [Value(v) for v in params]  # Fresh leaves start with zero gradients.
        total = 0.0
        for (x1, x2), y in data:
            a1 = (W[0]*x1 + W[1]*x2 + W[2]).tanh()
            a2 = (W[3]*x1 + W[4]*x2 + W[5]).tanh()
            loss = (a1*W[6] + a2*W[7] + W[8] - y)**2
            loss.backward()  # Fresh interior graph, shared batch parameter leaves.
            total += loss.data
        if epoch in (0, 10, 20, 30, 39):
            print(lr, epoch, total / len(data))
        params = [p.data - lr*p.grad for p in W]  # Sum-gradient update, not mean.
EOF

Practice & Prediction Log

1. Report the mean loss at epochs 0, 10, 20, 30, 39 for $\eta = 0.05$.
2. Repeat at $\eta = 5.0$ and describe the observed sequence.
3. Explain mechanically why a too-large step overshoots: relate $\eta \cdot \nabla L$ to the local curvature the linear step ignores.
4. State one claim you may NOT make from this single toy run.

Independent Mastery Criterion

Both runs are reproduced with matching loss tables, the divergence is explained as compounding overshoot rather than 'random failure', and the learner explicitly scopes the conclusion to this experiment.

Authoritative Source Resources & Provenance

linking 3Blue1Brown copyright (all rights reserved); site FAQ permits only short clips under stated conditions No video, audio, transcript or frame redistribution permitted

What is backpropagation really doing? (Chapter 3, Deep Learning)

Author: Grant Sanderson (3Blue1Brown) | Original Source Link ↗

Relevant Section / Range: The Intuition for Backpropagation

Verified Version & Date: Online video and article (Verified: 2026-10-30)

Selection Rationale:

Visual and geometric intuition for how nudging weights impacts the final cost function.

Source Prerequisites:

Basic derivative intuition from Days 16-18.

Safe Fallback (Offline Resilience):

The lesson derives the network gradient equations step by step without requiring video playback.

Compared Candidate Sources & Selection Analysis (2)
StatQuest Neural Networks Part 3 ↗ compared_alternative [Proprietary]

Step-by-step arithmetic without calculus notation; 3Blue1Brown provides the calculus-visual link needed.

Khan Academy Multivariable Chain Rule ↗ compared_alternative [CC BY-NC-SA 3.0]

Pure math focus; 3Blue1Brown contextualizes the chain rule specifically for neural network graphs.

linking MIT

micrograd: A tiny scalar-valued autograd engine

Author: Andrej Karpathy | Original Source Link ↗

Relevant Section / Range: micrograd/engine.py: class Value (_backward closures and backward() topological sort); README 'Example usage'

Verified Version & Date: Git commit master (Verified: 2026-10-30)

Selection Rationale:

Minimal, readable implementation of scalar autograd and MLP layers directly matched to our project.

Source Prerequisites:

Python object-oriented programming and operator overloading from Day 31.

Safe Fallback (Offline Resilience):

The local projects/autograd engine is runnable offline and matches micrograd semantics.

Compared Candidate Sources & Selection Analysis (2)
PyTorch autograd C++ engine ↗ compared_alternative [Modified BSD]

Production scale, but too large and complex for tracing by hand in introductory lessons.

Autograd (HIPS) ↗ compared_alternative [MIT]

Vectorized autograd; micrograd's pure scalar model is pedagogical for hand backprop.

03 120 min

Failure Gallery: Saturation, Missing Zero-Grad, and Silent Shape Truncation

Agent-Assisted Engineering Check

Prerequisites

Observed training runs from Activity 36-02.

Learning Objective

Reproduce and diagnose three distinct gradient failures on the local engine: a saturated tanh neuron that stops learning, a missing `zero_grad` that silently doubles every parameter and interior gradient on a reused graph, and a `zip`-truncated weighted sum that silently drops an input.

Instructions

Reproduce all three failures, measure each one, and write the fix.

Failure A — missing zero_grad on a multi-layer graph:

python3 - <<'EOF'
import sys; sys.path.insert(0, '.')
from projects.autograd.engine import Value
x1, x2 = Value(2.0), Value(-1.0)
W = [Value(v) for v in (0.5,-0.25,0.1, -0.5,1.0,-0.2, 1.0,-2.0,0.3)]
a1 = (x1*W[0]+x2*W[1]+W[2]).tanh(); a2 = (x1*W[3]+x2*W[4]+W[5]).tanh()
loss = (a1*W[6]+a2*W[7]+W[8]-1.0)**2
loss.backward(); print('after 1st:', W[0].grad)
loss.backward(); print('after 2nd:', W[0].grad)
EOF

Failure B — saturated initialization: set $b_1 = 8.0$ so $z_1 = 9.25$; record $\tanh'(z_1)$ and the resulting hidden-weight gradients.

Failure C — silent shape bug: evaluate sum(w*x for w,x in zip([0.5,-0.25], [2.0,-1.0,999.0])) and identify what happened to the extra input.

Practice & Prediction Log

For each failure: (a) state the observed number, (b) name the mechanism, (c) write the minimal fix.
1. $w_{11}.grad$ after the first vs second backward() without zeroing.
2. $\tanh'(z_1)$ and the hidden-weight gradient magnitudes at $b_1 = 8.0$ saturation.
3. The computed z value and the identity of the silently dropped term.

Independent Mastery Criterion

The learner reproduces all three measured failures, explains why each produces its specific symptom, and writes the one-line fix for each without prompting.

Authoritative Source Resources & Provenance

linking MIT

CS231n: Backpropagation and Intuitions

Author: Andrej Karpathy / Stanford University | Original Source Link ↗

Relevant Section / Range: Patterns in backward flow

Verified Version & Date: Course notes (Verified: 2026-10-30)

Selection Rationale:

Modular local-gradient interpretation (gate operations: add, multiply, max) and gradient flow intuition.

Source Prerequisites:

Multivariable calculus and basic Python.

Safe Fallback (Offline Resilience):

Local gate definitions and circuit flow diagrams in the lesson provide full coverage.

Compared Candidate Sources & Selection Analysis (2)

Raw circuit view; CS231n notes are more structured with explicit gate derivations.

Fast.ai Practical Deep Learning for Coders ↗ compared_alternative [GPL-3.0]

Top-down approach; CS231n bottom-up modular view matches our first-principles curriculum.

linking CC BY-NC 3.0 noncommercial

Neural Networks and Deep Learning: How the backpropagation algorithm works

Author: Michael Nielsen | Original Source Link ↗

Relevant Section / Range: Saturation and unstable gradients

Verified Version & Date: Online book (Verified: 2026-10-30)

Selection Rationale:

Clear four-equation derivation of backpropagation with scalar and matrix notation.

Source Prerequisites:

Matrix multiplication and the multivariable chain rule from Days 19-24.

Safe Fallback (Offline Resilience):

All four backprop equations and derivations are self-contained within the lesson text.

Compared Candidate Sources & Selection Analysis (2)
Goodfellow et al. Deep Learning (Chapter 6) ↗ compared_alternative [All Rights Reserved (free to view online)]

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.

04 120 min

Independent Mastery Check: Diagnose, Fix, and Explain

Independent Mastery Check

Prerequisites

Activities 36-01 through 36-03.

Learning Objective

Demonstrate unassisted mastery of the whole MLP block: write a correct training loop from memory, diagnose one seeded failure end-to-end (symptom, mechanism, fix), and pass the objective quiz in Independent mode.

Instructions

AI-free protocol: (a) from memory, write the five-step loop contract including where zero_grad belongs; (b) a colleague's run shows w.grad doubling-then-tripling every epoch and the loss diverging — write your diagnosis and fix; (c) take the objective quiz; (d) record which recovery link you would revisit for any missed item.

Practice & Prediction Log

1. Write the loop contract from memory and mark the single line whose removal caused the escalating-gradient symptom.
2. A run reports loss $2.1 \rightarrow 10^{30}$ within a few epochs: name the two most likely causes among $\{\eta$ too large, missing zero_grad, saturated activation$\}$ and the measurement that separates them.
3. Complete the 3-question objective quiz at 100% in Independent mode.

Objective Knowledge Check: Training Loop & Failure Diagnosis

Answer the following questions to verify your understanding. Select your declared assistance condition before submitting.

Declared Assistance Condition

Note: AI-free work is an honest declared condition, not claimed surveillance.

1.

On N1's multi-layer graph, calling loss.backward() a second time without zeroing produced $w_{11}.grad = 4.0135$ after $2.0068$ — exactly $2\times$. Why?

2.

In the observed $\eta = 5.0$ run, the mean loss exploded past $10^{151}$ within 40 epochs. The mechanism is:

3.

Which guard prevents the silent zip shape bug in the scalar Neuron implementation?

Attempt History & Evidence

    Independent Mastery Criterion

    The loop contract is written correctly from memory, the seeded failure is diagnosed with the right mechanism and fix, and the quiz scores 100% in Independent mode.

    Authoritative Source Resources & Provenance

    linking Modified BSD

    PyTorch Documentation: Autograd Mechanics

    Author: PyTorch Contributors | Original Source Link ↗

    Relevant Section / Range: How autograd encodes the history

    Verified Version & Date: PyTorch 2.5 Documentation (Verified: 2026-10-30)

    Selection Rationale:

    Official reference for computational graph construction, backward pass execution, and in-place mutation pitfalls.

    Source Prerequisites:

    Basic understanding of computational graphs and tensors.

    Safe Fallback (Offline Resilience):

    The training loop mechanics and zero_grad requirements are illustrated with runnable Python code.

    Compared Candidate Sources & Selection Analysis (2)
    TensorFlow tf.GradientTape Documentation ↗ compared_alternative [Apache 2.0]

    Alternative tape-based execution; PyTorch dynamic graph semantics are standard in modern LLM research.

    JAX autodiff cookbook ↗ compared_alternative [Apache 2.0]

    Functional transformations (grad, vjp); PyTorch object-based graph is closer to the beginner micrograd model.

    linking MIT

    micrograd: A tiny scalar-valued autograd engine

    Author: Andrej Karpathy | Original Source Link ↗

    Relevant Section / Range: micrograd/engine.py: class Value (_backward closures and backward() topological sort); README 'Example usage'

    Verified Version & Date: 2022 (Verified: 2026-10-30)

    Selection Rationale:

    Deepest bottom-up mechanical clarity for backpropagation engine and computational graph visualization.

    Source Prerequisites:

    High-school calculus (derivatives) and basic Python syntax

    Safe Fallback (Offline Resilience):

    Authored mathematical derivations, interactive Pyodide engine, and local tests provide complete offline study without video streaming.

    Compared Candidate Sources & Selection Analysis (2)
    PyTorch Autograd Internals ↗ compared_alternative [Modified BSD]

    Normative production documentation, but micrograd's pure Python implementation provides far superior initial clarity.

    3Blue1Brown: What is Backpropagation? ↗ compared_alternative [3Blue1Brown copyright (all rights reserved); site FAQ permits only short clips under stated conditions]

    High visual quality, pairs cleanly as optional supplementary visual reference.