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.

Intermediate 5 min readLesson 4 of 14

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.

wt+1=wt−η ∇wL(wt)\mathbf{w}_{t+1} = \mathbf{w}_t - \eta \, \nabla_{\mathbf{w}} L(\mathbf{w}_t)
  • ∇L\nabla L — the gradient: direction of steepest increase of the loss (Math for ML).
  • η\eta — the learning rate: step size.
Python
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.0

The learning rate

The single most important hyperparameter.

Learning rateBehaviour
Too smallPainfully slow; may stall on plateaus
Just rightSteady, fast decrease in loss
Too largeOscillates 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.

VariantGradient computed onProsCons
Batch GDEntire datasetExact, smoothSlow per step; doesn't fit in memory
Stochastic GD (SGD)One exampleVery cheap steps; noise helps escape bad regionsVery noisy; poor hardware utilisation
Mini-batch GDA batch of 32–4,096 examplesBest of both: GPU-friendly, reasonably accurateBatch 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:

vt=βvt−1+∇L(wt),wt+1=wt−ηvt\mathbf{v}_{t} = \beta \mathbf{v}_{t-1} + \nabla L(\mathbf{w}_t), \qquad \mathbf{w}_{t+1} = \mathbf{w}_t - \eta \mathbf{v}_t

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).

OptimiserIdea
AdaGradDivide each parameter's step by the root of its accumulated squared gradients — rarely updated parameters get bigger steps. Steps shrink forever.
RMSPropSame, but with an exponential moving average, so steps don't vanish
AdamMomentum (first moment) + RMSProp (second moment) + bias correction
AdamWAdam with decoupled weight decay — the default for transformers

Adam's update for each parameter:

mt=β1mt−1+(1−β1)gtvt=β2vt−1+(1−β2)gt2m^t=mt/(1−β1t),v^t=vt/(1−β2t)wt+1=wt−η m^t/(v^t+ϵ)\begin{aligned} m_t &= \beta_1 m_{t-1} + (1-\beta_1) g_t \\ v_t &= \beta_2 v_{t-1} + (1-\beta_2) g_t^2 \\ \hat{m}_t &= m_t / (1-\beta_1^t), \quad \hat{v}_t = v_t / (1-\beta_2^t) \\ w_{t+1} &= w_t - \eta \, \hat{m}_t / (\sqrt{\hat{v}_t} + \epsilon) \end{aligned}

Defaults: η = 1e-3 (smaller, e.g. 1e-4 to 3e-4, for transformers), β₁ = 0.9, β₂ = 0.999, ε = 1e-8.

ChooseWhen
AdamWDefault for transformers and most deep learning; robust to hyperparameters
SGD + momentumOften 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.
Python
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 rate

Practical 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.
Key takeaways
  • 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.