Gradient Descent & Optimisers
How models learn — loss landscapes, batch, stochastic and mini-batch gradient descent, the learning rate, momentum, RMSProp and Adam/AdamW, learning-rate schedules and warm-up, local minima and saddle points, and practical tuning tips.
Training a model means finding the parameters that minimise a loss function. For anything beyond linear regression there's no closed-form solution, so we search iteratively. Gradient descent is that search — and every neural network, from a small classifier to a frontier LLM, is trained with a variant of it.
The idea
Imagine standing on a foggy mountainside, trying to reach the valley floor. You can't see far, but you can feel the slope under your feet. Take a step downhill; repeat.
- — the gradient: direction of steepest increase of the loss (Math for ML).
- — the learning rate: step size.
def gradient_descent(grad_fn, w, lr=0.1, steps=100):
for _ in range(steps):
w = w - lr * grad_fn(w)
return w
# Minimise L(w) = (w - 3)²; gradient = 2(w - 3)
print(gradient_descent(lambda w: 2 * (w - 3), w=-5.0)) # → 3.0The learning rate
The single most important hyperparameter.
| Learning rate | Behaviour |
|---|---|
| Too small | Painfully slow; may stall on plateaus |
| Just right | Steady, fast decrease in loss |
| Too large | Oscillates around the minimum or diverges (loss explodes to NaN) |
Practical approach: try values on a log scale (1e-1, 1e-2, 1e-3, 1e-4), or run a learning-rate range test (increase it exponentially over a short run and pick a value just below where the loss starts rising).
Batch, stochastic and mini-batch
The true gradient averages over all training examples. Computing it every step is expensive for millions of examples.
| Variant | Gradient computed on | Pros | Cons |
|---|---|---|---|
| Batch GD | Entire dataset | Exact, smooth | Slow per step; doesn't fit in memory |
| Stochastic GD (SGD) | One example | Very cheap steps; noise helps escape bad regions | Very noisy; poor hardware utilisation |
| Mini-batch GD | A batch of 32–4,096 examples | Best of both: GPU-friendly, reasonably accurate | Batch size is another hyperparameter |
Mini-batch is the universal default (and is usually just called "SGD"). One pass over the full dataset is an epoch.
The noise in mini-batch gradients is a feature: it acts as regularisation and helps escape sharp minima, which tend to generalise worse than flat ones.
The loss landscape
For linear and logistic regression the loss is convex — a single bowl, so gradient descent finds the global minimum. Neural network losses are non-convex, with many minima, plateaus and saddle points. In high dimensions:
- Saddle points (downhill in some directions, uphill in others) are far more common than bad local minima, and momentum helps escape them.
- Many local minima are about as good as the global one.
- Ill-conditioning — steep in some directions, flat in others — makes plain gradient descent zig-zag. Adaptive optimisers address this.
Momentum
Accumulate a running average of past gradients — like a ball rolling downhill that builds speed in consistent directions and damps oscillations:
With β ≈ 0.9. Nesterov momentum evaluates the gradient at the look-ahead position for slightly better behaviour.
Adaptive optimisers
Different parameters may need different step sizes (rare features, different layers).
| Optimiser | Idea |
|---|---|
| AdaGrad | Divide each parameter's step by the root of its accumulated squared gradients — rarely updated parameters get bigger steps. Steps shrink forever. |
| RMSProp | Same, but with an exponential moving average, so steps don't vanish |
| Adam | Momentum (first moment) + RMSProp (second moment) + bias correction |
| AdamW | Adam with decoupled weight decay — the default for transformers |
Adam's update for each parameter:
Defaults: η = 1e-3 (smaller, e.g. 1e-4 to 3e-4, for transformers), β₁ = 0.9, β₂ = 0.999, ε = 1e-8.
| Choose | When |
|---|---|
| AdamW | Default for transformers and most deep learning; robust to hyperparameters |
| SGD + momentum | Often generalises slightly better for CNNs on vision tasks with careful tuning |
| Newer (Lion, Shampoo, Muon, Sophia) | Research and very large-scale training |
Adam stores two extra values per parameter, so optimiser state triples the memory of the weights — significant for large models.
Learning-rate schedules
A fixed learning rate is rarely optimal: big steps early to make progress, small steps later to settle into a minimum.
- Step decay: multiply by 0.1 every N epochs.
- Cosine decay: smoothly decrease along a cosine curve to near zero.
- Warm-up: start tiny and increase linearly for the first few hundred or thousand steps — essential for transformers, whose early updates with Adam can be unstable.
- Reduce on plateau: lower the rate when validation loss stops improving.
- One-cycle: rise then fall within one training run.
import torch
model = torch.nn.Linear(10, 1)
opt = torch.optim.AdamW(model.parameters(), lr=3e-4, weight_decay=0.01)
sched = torch.optim.lr_scheduler.OneCycleLR(opt, max_lr=3e-4, total_steps=10_000, pct_start=0.05)
for step, (x, y) in enumerate(loader):
loss = torch.nn.functional.mse_loss(model(x), y)
opt.zero_grad()
loss.backward() # compute gradients (backprop)
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) # gradient clipping
opt.step() # update weights
sched.step() # update learning ratePractical tips
- Normalise inputs, and use normalisation layers (BatchNorm, LayerNorm) — they make the landscape easier to optimise.
- Gradient clipping (cap the gradient norm) prevents occasional huge updates — standard for RNNs and transformers.
- Batch size and learning rate interact: when you multiply the batch size by k, scale the learning rate up (roughly linearly, with warm-up) as a starting point.
- Watch the curves: plot training and validation loss. Training loss not decreasing → learning rate or bug; validation rising while training falls → overfitting (Model evaluation).
- Overfit a tiny batch first: if the model can't drive the loss near zero on 10 examples, there's a bug.
- Early stopping: stop when validation loss stops improving; keep the best checkpoint.
- Gradient descent steps the parameters against the gradient of the loss; the learning rate sets the step size.
- Mini-batch SGD is the default: GPU-efficient, and its noise helps generalisation.
- Non-convex neural losses have saddle points and plateaus; momentum and adaptive methods help.
- Adam/AdamW combine momentum with per-parameter scaling — the default optimiser for transformers.
- Use learning-rate schedules with warm-up and decay; clip gradients; normalise inputs.
- Debug by overfitting a tiny batch and watching training and validation loss curves.