interviewpath
  • 0day streak
  • 10total XP
  • Level 1
0/6

Unit 7 · ML & applied AI · Lesson 6 of 13

Training loops, optimizers and model debugging

The engineering of training: a correct loop, optimizer and learning-rate choices, gradient hygiene, checkpointing, and a systematic way to debug a model that does not learn. Expect practical questions such as "the loss is flat, what do you check?" and "why AdamW with warmup?".
About 4 hFocus mode

Step 1: Learn the ideas

  • Loop anatomy: modes, zero_grad, backward, step, evaluation without gradients
  • SGD, momentum and Nesterov momentum
  • Adam, bias correction and AdamW
  • Learning-rate sweeps, warmup and cosine or linear decay
  • Batch size and gradient accumulation
  • Gradient clipping and gradient-norm monitoring
  • Checkpointing and exact resumption
  • Debugging: initial loss, tiny-batch overfit, shape and data-pipeline bugs
  • Reproducibility: seeds and nondeterministic kernels

Why it matters

Training failures are usually quiet: the loss falls a little, metrics look plausible, and the model is still wrong because of a masking bug, misaligned labels or a learning rate off by a factor of ten. Interviewers ask you to read a loss curve or justify optimizer choices because it reveals whether you have trained models yourself and whether you debug methodically.

Core ideas

Loop anatomy. Each step: set train mode, fetch a batch, forward, compute the loss, zero gradients, backward, optionally clip, optimizer.step(), scheduler.step(). Evaluation uses eval mode (dropout off, batch norm on running statistics) and no gradient tracking. Forgetting to zero gradients accumulates them across steps; forgetting eval mode makes validation noisy and wrong. Gradient accumulation deliberately sums gradients over several micro-batches before one optimizer step to emulate a larger batch; scale the loss accordingly.

Optimizers.

  • SGD with momentum keeps a velocity v <- mu * v + g and steps along it, damping oscillation across steep directions and accelerating along consistent ones.
  • Adam keeps exponential moving averages of the gradient and of the squared gradient, corrects both for their zero initialization, and divides each parameter's step by the square root of its second-moment estimate. That is two extra tensors per parameter, so optimizer state is about twice the model size at the same precision.
  • AdamW applies weight decay directly to the weights instead of adding an L2 term to the gradient, where Adam's per-parameter scaling would weaken the decay for parameters with large gradients. It is the usual choice for transformers, often with biases and normalization weights excluded from decay.

Learning rate. The most sensitive hyperparameter: sweep it on a log scale and watch the early loss. Warmup ramps the rate up over the first steps, because early second-moment estimates are noisy and the network is far from a stable regime, so full-size steps can diverge or spike. Afterwards, decay (cosine or linear) lets the model settle. Changing the batch size usually means retuning the learning rate.

Gradient hygiene. Clip by global norm (rescale all gradients together when their joint norm exceeds a threshold) to survive rare spikes without distorting every update. Log the gradient norm: sudden jumps often precede divergence, and near-zero norms in early layers indicate vanishing gradients.

Checkpointing. Save model weights, optimizer state, scheduler state, the step counter, RNG states and the data-loader position, written atomically (temporary file, then rename). Resuming from weights alone silently resets Adam's moments and the schedule, which shows up as a loss spike. Keep the best checkpoint by validation metric as well as the latest.

Debugging recipe.

  1. Check the initial loss: for C balanced classes it should be near ln(C), about 2.3 for 10 classes. Far off means a bug in the loss, labels or initialization.
  2. Overfit one small batch to near-zero loss. If you cannot, the problem is in the model, loss or optimizer wiring, not in generalization.
  3. Look at real inputs and labels exactly as the model receives them after the data pipeline: augmentation, normalization, label alignment, padding and masks.
  4. Check shapes and broadcasting: subtracting a (n, 1) tensor from an (n,) tensor silently yields (n, n).
  5. Compare against a trivial baseline, change one thing at a time, and log every run's configuration and seed.

Reproducibility. Seed Python, NumPy and the framework; even then some GPU kernels are nondeterministic, so measure seed-to-seed variance before attributing a small difference to a change.

Common misconceptions

  • "Adam does not need learning-rate tuning." It is less sensitive than SGD, but the learning rate and schedule still dominate results.
  • "Adam with L2 is the same as AdamW." The L2 gradient gets rescaled by Adam's adaptive denominator; decoupled decay does not.
  • "Clipping fixes a learning rate that is too high." It caps rare spikes; if clipping triggers on most steps, the step size or the model is wrong.
  • "If the training loss falls, the pipeline is correct." Networks can fit shuffled labels or leaked features; validate the data and compare with baselines.
  • "Saving the weights is a checkpoint." Without optimizer, scheduler and RNG state, resuming is not the same run.
  • "One run shows the improvement." Differences smaller than seed-to-seed variation are not evidence.

How to approach it

Write a training loop from scratch at least once, including checkpointing, and verify exact resumption by comparing loss curves with an uninterrupted run. Inject bugs one at a time (missing zero_grad, eval mode forgotten, labels shifted by one, learning rate times 100) and learn their symptoms. Senior-level discussions add loss spikes at scale, batch-size scaling and bisecting a training regression.

Suggested order

  1. 1Read Karpathy’s "A Recipe for Training Neural Networks" and turn its steps into your own debugging checklist.
  2. 2Read the CS231n notes "Neural Networks Part 3: Learning and Evaluation" (gradient checks, sanity checks, babysitting the learning process, parameter updates).
  3. 3Read D2L 12.6 (Momentum), 12.10 (Adam) and 12.11 (Learning Rate Scheduling), running the code.
  4. 4Read the introduction and method of the AdamW paper until you can explain decoupled weight decay in two sentences.
  5. 5Read the Deep Learning Tuning Playbook sections on choosing the optimizer and batch size and on the incremental tuning strategy.
  6. 6Implement the CS336 Assignment 1 parts for cross-entropy, AdamW, the cosine schedule with warmup, gradient clipping and checkpointing, or an equivalent loop of your own.

Step 2: Check off what you can do

Tap each one you can genuinely do or explain. Each earns 10 XP.

Step 3: Go deeper

  • A Recipe for Training Neural NetworksStart here

    Andrej Karpathy's blog

    A step-by-step training process and debugging checklist: inspect data, baselines, overfit one batch, then regularize and tune.

    Open(opens in a new tab)Link responded, 5 Oct 2026
  • Stanford CS231n Deep Learning for Computer VisionStart here

    Stanford University

    Section: Course notes: Neural Networks Part 3: Learning and Evaluation

    Sanity checks, reading loss and accuracy curves, update-to-weight ratios and the main parameter update rules.

    Open(opens in a new tab)Link responded, 5 Oct 2026
  • Dive into Deep Learning

    d2l.ai (open-source book)

    Section: Ch. 12: Optimization Algorithms

    Momentum (12.6), Adam (12.10) and learning-rate scheduling (12.11) with runnable code.

    Open(opens in a new tab)Link responded, 5 Oct 2026
  • Decoupled Weight Decay Regularization

    arXiv

    Why L2 regularization and weight decay differ under Adam, and the decoupled fix.

    Open(opens in a new tab)Link responded, 5 Oct 2026
  • Deep Learning Tuning Playbook

    Google Research on GitHub (not an officially supported Google product)

    Choosing optimizer, batch size and initial configuration, then running hypothesis-driven tuning experiments.

    Open(opens in a new tab)Link responded, 5 Oct 2026

Step 4: Practice

In CS336 Assignment 1, the AdamW, cosine schedule with warmup, gradient clipping, checkpointing and training-loop parts are exactly this topic; write them without copying library code and compare against the PyTorch implementations. In the CS231n assignments, use the optimizer and loss-curve sections. Separately, take a working loop and inject one bug at a time (missing zero_grad, eval mode forgotten, labels shifted by one, learning rate 100 times too high), recording the symptom each produces; then resume from a mid-run checkpoint and confirm the loss curve matches an uninterrupted run.

Record attempts on each problem’s page (+15 XP, +10 more when solved on your own).

Step 5: Test yourself

Answer each one out loud or on paper before you finish the lesson.

  1. Question 1What should the initial loss be for a 100-class classifier, and what does an initial loss of 40 suggest?
  2. Question 2Why does warmup help when training transformers with Adam?
  3. Question 3What state must a checkpoint contain for exact resumption?
  4. Question 4How does clipping by global norm differ from clipping each gradient value?
  5. Question 5Why can validation loss computed in train mode differ from eval mode?
  6. Question 6How would you decide whether a 0.3% improvement is real across runs?

You’re done when you can

  • Write a training loop with exact checkpoint and resume from memory, and show identical curves after resuming.
  • Explain Adam, its bias correction and AdamW decoupled decay in under three minutes.
  • Given a described loss curve (flat, diverging, spiking, or a large train-validation gap), name the likely causes and the next check.
  • Overfit a single batch as the first debugging step on a new model without being prompted.

Finish the lesson

How confident do you feel?

Lesson complete!

+50 XP

Reviews will come up on the Practice tab so it sticks.

Unlocks next: Fine-tuning, LoRA, instruction tuning and preference optimization, Training memory accounting

Your notes and study time

Log study time