Training Loops & Learning Rate Schedulers
Write robust training/eval loops and schedule learning rates for stable convergence.
In plain words
Training repeats guess, check, adjust over and over. A scheduler starts with careful small adjustments, speeds up in the middle and slows down again at the end so the model can settle.
Think of it like…
Training for a marathon. The loop is the daily routine (run, measure, rest), the scheduler is the training plan (build up gently, push in the middle, taper at the end) and the checkpoint is writing down your personal best so a bad final day doesn't erase it.
Where you’ve seen it
A classifier trains on 50,000 images with batch size 128, so each epoch has 391 steps and a 20-epoch run has 7,820 steps. The team uses AdamW with a peak learning rate of 1e-3, a linear warm-up over the first 5% of steps (391 steps, one epoch) and cosine decay to zero: lr = 0.5 × 1e-3 × (1 + cos(π × progress)), which gives exactly 5e-4 when halfway through the decay (about step 4,106) and approaches 0 at step 7,820. Halfway through warm-up (step 195) the rate is about 5e-4. Without warm-up, the first 50 steps produced a loss of NaN on one seed. Gradient clipping at norm 1.0 rescales any larger gradient: a norm of 4.0 is multiplied by 0.25. With 32-image micro-batches and 4 accumulation steps the effective batch is 128, and the loss is divided by 4 before each backward pass so the accumulated gradient matches the large-batch gradient. Each epoch they evaluate in model.eval() under torch.no_grad(), log training and validation loss, and checkpoint when validation improves; a bug where the validation loader accidentally shuffled and where model.eval() was missing (dropout still on) gave noisy curves until fixed. Early stopping with patience 5 and the best checkpoint restored gives the final model.
Words you’ll hear
- Epoch / step
- One pass over the data, and one optimiser update.
- Warm-up
- A short ramp from a tiny learning rate to the peak to stabilise early training.
- Cosine decay
- A smooth schedule that lowers the rate from the peak to near zero.
- Gradient accumulation
- Summing gradients over several micro-batches before stepping to emulate a larger batch.
Visual diagram
Theory & deep dive
The loop, step by step
A reliable loop keeps each action in the right order: model.train() at the start of each epoch; for each batch, move data to the device, optimizer.zero_grad(set_to_none=True), forward pass, loss, loss.backward(), optional clip_grad_norm_, optimizer.step() and, for per-step schedules, scheduler.step(). After the epoch, switch to model.eval() and use torch.no_grad() so dropout is off, BatchNorm uses running statistics and no graph is built. Track training loss as a running average and compute validation metrics over the whole set, not a single batch. Log the learning rate and gradient norm too; they diagnose most instabilities.
Robustness extras: gradient accumulation (divide the loss by the number of accumulation steps and step every k micro-batches: 32 × 4 = an effective batch of 128), mixed precision with autocast and a gradient scaler for speed and memory, checkpointing both model and optimiser state so a crashed run can resume, seeding for reproducibility and early stopping with a restored best model. Clip gradients by norm (commonly 1.0): a gradient norm of 4.0 is multiplied by 1.0 / 4.0 = 0.25, preserving direction while capping size.
50,000 images ÷ 128 = 390.6 → 391 steps per epoch; 20 epochs = 7,820 steps. With micro-batches of 32 and 4 accumulation steps, each optimiser step sees 4 × 32 = 128 images, and the loss is divided by 4 before backward.
Learning-rate schedules
Warm-up raises the rate linearly from near zero to the peak over the first few percent of training; adaptive optimisers have poor second-moment estimates at the start, so large early steps can blow up. After the peak, cosine decay follows lr = 0.5 × lr_max × (1 + cos(π × progress)), where progress runs from 0 to 1: at progress 0.5 the factor is 0.5 × (1 + 0) = 0.5, so the rate is half the peak, and at 1 it reaches 0. Step decay multiplies by a factor (for example ×0.1 every 30 epochs: 0.1 → 0.01 → 0.001) and remains common for CNN recipes. ReduceLROnPlateau halves the rate when validation loss stalls for a patience of 3 epochs. One-cycle warms up to a high rate and anneals far below the start, often allowing faster convergence.
Choose based on the run length known in advance: cosine or one-cycle need the total number of steps, plateau schedules do not. Set the peak rate with a learning-rate range test (increase it exponentially over a few hundred steps and pick a value a factor of 3 to 10 below where the loss starts to rise). Remember to call scheduler.step() at the cadence it was designed for (per step or per epoch), since the wrong cadence makes the schedule 391 times too slow or fast. For fine-tuning, use much smaller peaks (1e-5 to 5e-5) and shorter warm-ups.
lr_max = 1e-3, decay over steps 391 to 7,820. Progress 0 → 1.0e-3; progress 0.25 → 0.5 × (1 + 0.707) × 1e-3 = 8.5e-4; progress 0.5 → 5.0e-4; progress 0.75 → 1.5e-4; progress 1 → 0.
How it works, step by step
Step 1 of 41. Write the train step
Order matters: zero gradients, forward, loss, backward, clip, optimiser step.
- Log
- loss, lr, grad norm
When to use it & trade-offs
What it is
A training loop repeats a fixed cycle: fetch a batch, run the forward pass, compute the loss, clear old gradients, call backward(), optionally clip the gradient norm, step the optimiser and (for per-step schedules) step the scheduler. After each epoch an evaluation loop runs with model.eval() and torch.no_grad() on validation data, logs metrics and saves a checkpoint when validation improves. A learning-rate scheduler changes the learning rate over time: linear warm-up avoids early instability, step or cosine decay lets the model settle into a minimum, ReduceLROnPlateau reacts to stalls and one-cycle ramps up then down. Together the loop and schedule determine whether a run converges, how stable it is and whether you can reproduce it.
Why it matters: Most training failures are loop failures: the model left in the wrong mode, a missing zero_grad(), gradients that explode in the first hundred steps, validation leaking into training or a checkpoint that saves the last model instead of the best. The learning rate is the most influential hyperparameter and a good schedule can matter more than the optimiser choice. A robust, instrumented loop is also what lets you compare experiments honestly.
When to reach for it
- Warm-up with AdamW on transformers
- Gradient accumulation when memory limits the batch size
- Best-checkpoint restore with early stopping
When to avoid or be careful
- Evaluating without eval mode and no_grad
- Stepping a per-step scheduler once per epoch
- Reporting the last epoch's weights instead of the best validation checkpoint
Learning-rate schedules
Strengths: Stable start; smooth finish.
Watch out: Needs the total step count.
Strengths: Simple and well-tested.
Watch out: Abrupt changes; extra hyperparameters.
Strengths: Reacts to validation stalls.
Watch out: Noisy validation can trigger it early.
Strengths: High rates act as regularisation.
Watch out: Sensitive to the peak rate.
Interview signals & numbers to know
When this topic comes up
- “Why warm up the learning rate?”
- Cosine versus step decay
- Gradient accumulation and effective batch size
- Gradient clipping
- Checkpointing and resuming
Benchmarks & rules of thumb
- 7,820 steps
- 20 epochs of 391 steps
- 0.5 × lr_max
- cosine schedule value at the halfway point
- 32 × 4 = 128
- effective batch with 4 accumulation steps
Common mistakes & follow-ups
Common interview mistakes
- Calling scheduler.step() at the wrong cadence.
- Forgetting to divide the loss by the accumulation count, which gives oversized gradients.
- Choosing the peak learning rate without a range test.
Likely interviewer follow-ups
- How do you decide the peak learning rate?
- Why does Adam need warm-up?
- How would you resume a run that crashed?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Training Loops & Learning Rate Schedulers with data science interview Q&A and hands-on practice.