Sub-chapter 6.5

Gradient Descent & Optimization

Rolling a ball downhill on a foggy loss landscape — how neural networks actually learn, one tiny step at a time.

24 min read Intermediate 2 Interactive Demos

The Intuition: A Ball on a Foggy Hillside

Imagine standing on a vast hillside in dense fog. You can’t see the valley below, but you can feel the slope under your boots. To find the bottom, you take a small step in whichever direction feels steepest downhill, then re-check the slope and repeat. That, in one sentence, is gradient descent — the workhorse algorithm that trains every modern neural network.

What is the gradient?

The gradient ∇L(θ) is a vector that points in the direction of steepest ascent of the loss function. To minimize loss, we move in the opposite direction — the negative gradient.

Civil Engineering Analogy

Training a neural network is like surveying a watershed in fog with only a digital level. Every parameter is a coordinate on a topographic map; the loss is the elevation. You can’t see the whole basin, but at every spot you can measure the local slope and step downhill.

  • Loss landscape = topographic map of a complex watershed
  • Gradient = direction of steepest uphill (read from the level)
  • Step size (learning rate) = stride length
  • Momentum = inertia of a rolling ball that smooths out potholes
  • Adaptive LR = automatically shortening your stride on rocky ground

The Update Rule

All of gradient descent boils down to one beautifully simple equation:

Vanilla Gradient Descent
θt+1 ← θt − η · ∇L(θt)

where:
  θ        = model parameters (weights, biases)
  η        = learning rate (step size)
  ∇L(θ)  = gradient of the loss with respect to θ
  t        = iteration index

That’s it. Repeat this update a few thousand (or few million) times and a randomly-initialized network will gradually morph into a useful model. Everything else in this sub-chapter — momentum, Adam, schedules — is just a clever twist on this single line.

Why the minus sign? The gradient points uphill. We want to go downhill, so we subtract. Forget the sign and your loss explodes upward instead of converging — a classic first-day-on-the-job bug.

The Learning Rate η: The Most Important Knob

The learning rate is the single most consequential hyperparameter in deep learning. Get it wrong and nothing else matters.

Too Large

The ball overshoots the valley, bounces up the opposite wall, overshoots again, and diverges. Loss explodes to NaN.

Just Right

Smooth, monotonic descent. Loss curve is a nice clean exponential-looking decay.

Too Small

Painfully slow. You burn GPU hours making microscopic progress and may never reach a good minimum.

Typical starting values: 1e-3 for Adam, 1e-2 for SGD with momentum. Always tune on a log scale.

Demo 1: Learning Rate Tuner

Drag the slider and watch a ball descend a simple convex bowl. See first-hand how the learning rate decides whether you converge, oscillate, or fly off into space.

Convex Bowl Descent

Ready
Iterations 0
Current loss —
Verdict —

Three Flavors: Batch, Stochastic, Mini-batch

How much data should we look at before each step? Three choices, three tradeoffs.

Batch Gradient Descent

Compute the gradient using the entire dataset before each update. Smooth, deterministic, but each step is expensive. With millions of samples it is impractical.

Stochastic Gradient Descent (SGD)

Update after every single sample. Extremely fast per step, but noisy — the path zig-zags wildly. The noise can actually help escape shallow local minima.

Mini-batch SGD — The Practical Sweet Spot

Use a small batch (32, 64, 128, 256). Vectorizes nicely on GPUs, gives a smooth-ish gradient estimate, and is what virtually every modern training loop uses. Batch size is itself a tunable hyperparameter.

Mini-batch loop, conceptually
for epoch in range(num_epochs):
    for x_batch, y_batch in dataloader:        # batch of 32-256
        y_pred = model(x_batch)
        loss   = loss_fn(y_pred, y_batch)
        loss.backward()                        # compute gradients
        optimizer.step()                       # apply update rule
        optimizer.zero_grad()                  # clear for next batch

Momentum: Giving the Ball Some Inertia

Plain SGD is forgetful — each step uses only the current gradient. Momentum remembers past gradients and builds up velocity, the way a real rolling ball would.

SGD with Momentum
vt+1 = β · vt + ∇L(θt)
θt+1 = θt − η · vt+1

  β ≈ 0.9 (momentum coefficient)
  v   = velocity (moving average of past gradients)
  • Dampens oscillations across narrow ravines
  • Accelerates progress along consistent downhill directions
  • Helps escape shallow local minima and plateaus

Nesterov Accelerated Gradient (NAG)

A clever twist: compute the gradient at the lookahead position θ − ηβv rather than at θ itself. Often converges a bit faster than vanilla momentum because it “peeks ahead” before committing.

Adaptive Optimizers: Per-Parameter Step Sizes

What if some weights need big steps and others tiny ones? Adaptive optimizers maintain a separate effective learning rate for every parameter, automatically.

Adagrad

Divides the learning rate by the square root of the sum of all past squared gradients. Great for sparse features, but the effective LR decays monotonically and eventually becomes too small to learn.

RMSprop

Fixes Adagrad’s decay problem by using an exponentially-weighted moving average of squared gradients instead of a sum. Old gradients are forgotten, recent ones dominate.

Adam — The Default

Combines momentum (first moment of gradients) with RMSprop-style adaptive scaling (second moment). Robust, insensitive to hyperparameters, and the default starting point in 2026.

AdamW

Adam with decoupled weight decay. Fixes a subtle interaction between L2 regularization and adaptive LR. The standard optimizer for Transformers (BERT, GPT, ViT, etc.).

Adam, in full
mt = β1 mt-1 + (1-β1) ∇L           // first moment (momentum)
vt = β2 vt-1 + (1-β2) (∇L)2      // second moment (RMSprop)
m̂t = mt / (1 - β1t)                // bias correction
v̂t = vt / (1 - β2t)
θt+1 = θt - η m̂t / (√v̂t + ε)

defaults:  β1=0.9   β2=0.999   ε=1e-8   η=1e-3
SGD still wins sometimes. For computer vision on ResNets and similar, well-tuned SGD with momentum often generalizes better than Adam. Adam converges faster, but the minima it finds can be sharper. Always benchmark both on your task.

Demo 2: Optimizer Race

Three optimizers, one nasty banana-shaped (Rosenbrock-style) loss surface. Pick a starting point, hit Start, and watch SGD, SGD+Momentum, and Adam race to the minimum simultaneously.

Race on a Banana Valley

Idle
Optimizers
Starting point
SGD iters —
SGD loss —
Mom iters —
Mom loss —
Adam iters —
Adam loss —

Learning Rate Schedules

A constant learning rate is a blunt tool. In practice we schedule η to change over training: large at the start (cover ground fast), small at the end (settle into the minimum).

Step Decay

Multiply η by 0.1 every N epochs. Simple, effective, the classic ResNet recipe.

Cosine Annealing

Smoothly decay η from ηmax to ~0 along a cosine curve. Standard in modern image and language models.

Warm Restarts

Cosine anneal, then suddenly reset η back up. Periodic kicks help escape sharp minima (SGDR).

Warmup

Linearly ramp η from 0 to ηmax over the first ~1000 steps. Essential for Transformers and large-batch training.

The modern recipe for training a Transformer: linear warmup + cosine decay + AdamW. Boring, but it works astonishingly well.

Saddle Points, Local Minima & Loss-Landscape Myths

Early deep learning lore worried obsessively about local minima — tiny dips that aren’t the true valley. Modern theory says: stop worrying.

The Surprising Truth

In high-dimensional spaces (millions of parameters), the probability that every direction curves upward at a random critical point is essentially zero. Most critical points are saddle points, not local minima. And the local minima that do exist tend to have similar loss values — they’re all about equally good.

CE Analogy: Saddle Points

A saddle point is a mountain pass: downhill in some directions (the trail through the pass), uphill in others (the peaks on either side). A naive ball can stall on a saddle, but momentum and stochastic noise easily knock it loose.

This is a major reason SGD’s built-in noise, and momentum-based methods, are so effective — they don’t get stuck on saddles.

Practical Recipes

  • Start with AdamW, lr=3e-4. The famous Karpathy default.
  • If training is unstable in early steps, add linear warmup.
  • If loss plateaus, try cosine decay or step decay.
  • If you have lots of compute and care about generalization, try well-tuned SGD + momentum.
  • Always plot the loss curve. Diverging? LR too high. Flat? LR too low or stuck on a saddle.
  • Clip gradients (norm 1.0) for RNNs and Transformers to avoid exploding gradients.
  • Tune learning rate first, before anything else.

Civil Engineering Application

Foundation Optimization

Gradient descent optimizes foundation dimensions the same way it trains neural networks — the "loss" is cost, the "parameters" are width and depth. Adam optimizer handles the noisy, multi-variable landscape better than manual iteration, finding the cheapest design that meets bearing capacity requirements.

Dam Shape Optimization

The cross-section of a gravity dam can be optimized via gradient-based methods. The loss function combines sliding stability, overturning safety, and material volume. Learning rate is critical: too high and the optimizer overshoots into unsafe designs, too low and it converges on expensive over-designed sections.

Quick Check

1. Why do we subtract the gradient instead of adding it?

  • Because gradients are always negative numbers.
  • The gradient points uphill, and we want to go downhill to minimize the loss.
  • It cancels floating-point rounding errors.
  • Because PyTorch requires it.

2. Your training loss explodes to NaN after a few steps. Most likely culprit?

  • The dataset is too small.
  • You forgot to call .backward().
  • Learning rate is too large — the optimizer is diverging.
  • Adam is incompatible with this model.

3. Which statement about Adam is correct?

  • Adam computes the exact Hessian of the loss.
  • Adam combines momentum (first moment) with RMSprop-style scaling (second moment).
  • Adam works only on convex problems.
  • Adam doesn’t need a learning rate hyperparameter.

4. Why is mini-batch SGD preferred over full-batch GD in practice?

  • Mini-batches always give a more accurate gradient.
  • Full-batch GD cannot reach a minimum.
  • Mini-batches eliminate the need for a learning rate.
  • Mini-batches are GPU-friendly, fast per step, and the noise helps generalization.

Recap

  • Gradient descent is the iterative rule θ ← θ − η∇L.
  • The learning rate is the most important hyperparameter — tune it first.
  • Mini-batch SGD is the practical default; batch sizes 32–256 dominate.
  • Momentum smooths and accelerates; Adam adds per-parameter adaptive scaling.
  • AdamW + warmup + cosine decay is the modern Transformer recipe.
  • Saddle points are the real obstacle in high dimensions, not local minima.
Try it interactively

Watch gradient descent climb down — or diverge

Slide the learning rate on a log scale and watch the live training-loss curve. Too small: glacial. Too big: bouncing or NaN. Just right: the textbook descent.

Open Lab
Mini case study

Adam beats hand-tuned SGD — convergence study on concrete strength

Kingma and Ba’s Adam optimizer (2014) is now the default in PyTorch, TensorFlow and JAX; it has accumulated more than 200,000 citations — the most-cited paper in modern machine learning. The reason it became default is mundane: it converges on the messy, ill-scaled, mid-sized datasets that fill engineering practice without the LR-tuning ceremony that plain SGD demands. We replay the comparison on the canonical CE benchmark.

0Adam paper citations
0Optimizers benchmarked
0RMSE — SGD baseline
0RMSE — AdamW

Train an MLP regressor for 28-day concrete compressive strength on Yeh’s 1030-row UCI dataset. Inputs are scaled in radically different magnitudes (cement 100–540 kg/m³; SP 0–32 kg/m³; age 1–365 d). Plain SGD requires per-feature learning-rate tuning to behave; adaptive optimizers should remove that burden.

“Adaptive optimizers are the price you pay to never tune another learning rate.”

  • Fixed architecture — 8 → 64 ReLU → 32 ReLU → 1, MSE loss.
  • Five optimizers — plain SGD, SGD + momentum (0.9), RMSProp, Adam, AdamW (default LRs from each paper).
  • Same 80/20 split, same seed, 2000 epochs, batch size 32; track training loss every epoch.
Training-loss trajectories for five optimizers (UCI Concrete, same MLP)

Adaptive optimizers (RMSProp, Adam, AdamW) reach a lower plateau ~10× faster — the “default” settings just work; SGD needs hand-tuned LR + warmup to compete.

  • RMSE 6.2 MPa → 3.9 MPa on hold-out by swapping SGD for AdamW.
  • 10× fewer epochs to reach a usable loss with adaptive methods.
  • AdamW beats Adam by ~5% — the decoupled weight-decay fix matters even on tiny networks.
  • Start with Adam / AdamW. Switch to SGD only when you have GPUs to burn and need to chase the last fraction of accuracy.
  • Adaptive optimizers tolerate bad feature scaling — engineering data rarely arrives pre-scaled.
  • Decoupled weight decay (AdamW) is now standard — the original Adam regularises through gradients in a subtly broken way.