Deep Learning
Training Deep Networks — From Gradient Descent to Modern Optimizers
Master the techniques and best practices for training deep neural networks effectively.
- Optimization algorithms — SGD, Adam, and beyond
- Learning rate schedules — adaptive and warm-up strategies
- Regularization — dropout, weight decay, and early stopping
Success is not final, failure is not fatal: it is the courage to continue that counts.
Training Deep Networks — Complete Guide
Training deep networks requires careful choice of optimizer, learning rate, regularization, and debugging techniques. This guide covers the essential practical knowledge for training models that converge well and generalize.
The Training Loop
How the training loop works: This diagram shows the six-step process that repeats for every batch of data during neural network training. Step 1: Forward pass — the input data flows through the network to produce predictions. Step 2: Compute loss — the loss function (e.g., cross-entropy) measures how wrong the predictions are compared to true labels. Step 3: Zero gradients — clear any accumulated gradients from previous iterations (PyTorch default accumulates). Step 4: Backward pass — backpropagation computes gradients of the loss with respect to every parameter by applying the chain rule through the computational graph. Step 5: Clip gradients — prevent exploding gradients by capping their norm (critical for RNNs and Transformers). Step 6: Update weights — the optimizer adjusts parameters using the computed gradients. The loss curve inset shows the goal: loss should decrease over time as the model learns. The dashed arrow back to Step 1 shows this loop repeats for every batch, typically thousands of times per epoch.
The Loop Written Out
The order of those six steps matters more than it looks. Gradients accumulate inside the parameter tensors, so clearing them — before the forward pass or immediately after the step, either is fine — is what keeps a batch's contribution from being added on top of the previous batch's. Skipping the call for even one batch silently raises the effective learning rate, and the symptom is a loss that oscillates or diverges after a run that started normally.
Clipping belongs after backward and before the step, because clipping is defined in terms of the gradient norm that backward has just produced. The evaluation pass sits outside both loops and must run with the model in evaluation mode, since dropout and batch statistics behave differently there.
import torch
for epoch in range(num_epochs):
model.train()
for x, y in dataloader:
optim.zero_grad() # clear the previous batch
preds = model(x)
loss = loss_fn(preds, y)
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
optim.step()
model.eval()
with torch.no_grad():
val_loss = loss_fn(model(val_x), val_y)
print(f"epoch {epoch:02d} train {loss.item():.3f} val {val_loss.item():.3f}")
Optimizers
Why Adam and AdamW Diverge
Plain SGD carries a single velocity per parameter, so every coordinate moves at the same rate regardless of how informative its gradient is. Adam keeps a second running average, the uncentred second moment, and divides by its square root, which effectively gives rarely updated parameters a larger step and frequently updated ones a smaller one. That is why it converges quickly on the first epochs of almost any problem.
The divergence between Adam and AdamW is narrower but worth understanding, because weight decay is the regulariser you will actually rely on. In classic Adam the decay is folded into the gradient, and since Adam rescales the gradient by the second moment before applying it, large and small weights are shrunk by different amounts. AdamW pulls the decay out of that rescaling and applies it directly to the weights, so the penalty no longer depends on the adaptive statistics. For Transformers this decoupling is the difference between a stable run at a useful decay value and one that has to trade regularisation against convergence speed.
Learning Rate Schedules
Warmup Then Cosine in Practice
At the start of a run the second-moment estimate in Adam is built from a handful of noisy gradients, and a full-size learning rate on top of it can push the weights far enough that the model never recovers. Warmup avoids this by climbing from nearly zero to the peak over the first few hundred steps, long enough for the adaptive statistics to settle. The decay that follows spends most of the run at high resolution and then lets the step size fall as the model approaches a minimum, which tightens the fit in the final epochs without the oscillation a constant rate would produce.
Schedules are stepped once per optimizer step rather than once per epoch, a detail that silently multiplies or divides the effective warmup length by the number of batches.
import math
import torch
from torch.optim.lr_scheduler import LambdaLR
total_steps, warmup_steps, base_lr = 10_000, 500, 3e-4
def cosine_warmup(step):
if step < warmup_steps:
return step / warmup_steps
progress = (step - warmup_steps) / (total_steps - warmup_steps)
return 0.5 * (1 + math.cos(math.pi * progress))
optim = torch.optim.AdamW(model.parameters(), lr=base_lr)
sched = LambdaLR(optim, cosine_warmup)
for x, y in dataloader:
optim.zero_grad()
loss = loss_fn(model(x), y)
loss.backward()
optim.step()
sched.step() # once per step, not once per epoch
Regularization
How the Regularisers Differ
Dropout changes the graph rather than the objective. During training each activation is zeroed with some probability and the survivors are scaled up, so no unit can rely on a particular partner being present and the ensemble of subnetworks that results averages out at inference. This is why the model must be switched to evaluation mode for validation: running dropout there would inject noise into measurements you are using to make decisions.
Batch and layer normalisation solve a different problem, namely that each layer's inputs drift as earlier layers move. Batch statistics make the normalisation depend on the other examples in the mini-batch, which is fine for convolutions on large batches and useless for variable-length sequences where the batch may be two items wide. Layer statistics are computed per example across the feature dimension, so the result does not depend on batch size at all, and that is why Transformers use layer norm and image models use batch norm.
Weight decay and gradient clipping act on the parameters and the updates rather than the activations. Decay pulls weights toward zero on every step and works best when it is decoupled from the adaptive scaling, while clipping rescales any update whose norm exceeds a threshold, converting a single catastrophic step into a normal one. Early stopping needs none of this machinery: it watches validation loss and quits, and it is the one regulariser that also tells you when the extra capacity is not paying for itself.
Debugging Training
Reading the Curve Before Touching Anything
Three curves are worth plotting from the first run: training loss, validation loss, and the norm of the gradients. Training loss that does not move at all usually points at the data rather than the model — shuffled labels, a loss function mismatched to the output activation, or a learning rate so small that the weights barely leave their initialisation. Lowering the rate in that situation makes things worse, which is why the checklist starts by confirming that a single batch can be overfitted to near-zero loss.
A widening gap between the two losses is overfitting, and it is the only one of the three patterns that regularisation fixes. Oscillation with a spiking gradient norm means the rate is too high or a batch is pathological, and clipping will keep the run alive while you investigate. Inspecting activation statistics catches a fourth failure that loss curves hide entirely: if the activations at a given depth collapse to a constant or saturate at their limits, that layer is dead and no amount of extra epochs will bring it back.
Mixed Precision Training
Common Mistakes & How to Avoid Them
Common Mistakes
Leaving zero_grad out of the loop so gradients from every previous batch keep stacking and the effective step size grows without limit
Fix: Call optim.zero_grad at the start of each batch or use set_to_none for speed, and assert once that the gradient norm stays in the expected range
Stepping the learning rate scheduler once per epoch when it was configured in optimizer steps, cutting warmup short by the number of batches
Fix: Count steps explicitly, call sched.step after every optimizer.step, and print the learning rate during the first epoch to confirm it follows the intended curve
Comparing validation accuracy measured with dropout still active against training accuracy and concluding the model is broken
Fix: Switch to model.eval and wrap validation in no_grad before measuring, then switch back to model.train for the next training epoch
Key Takeaways
What to Learn Next
-> Optimizers for Deep Learning Master different optimization algorithms.
-> Loss Functions Choose the right loss for your task.
-> Regularization Prevent overfitting in deep models.
-> Weight Initialization Start training with proper initialization.
-> Neural Networks Understand the models you're training.
-> Transformers Learn the architecture most affected by training choices.