AI State of the Art
Fundamentals/Machine Learning: The Basics/21 min
Section 10

Gradient Descent: SGD, Momentum, Nesterov

Listen as a podcast →

Introduction: Descending a Mountain in the Fog

Imagine: you're at the top of a mountain in thick fog. You can't see the village down below. But you feel a slope under your feet. You take a step in the direction where it goes down the steepest. Then another. Little by little, you descend.

This is exactly what gradient descent does. It measures the "slope" (gradient) and moves in the opposite direction to reduce the error.

3D visualization of gradient descent
The coloured surface is the error landscape: red on the high ground, blue in the hollows. Follow the black line, where each cross is one step, and you get our fog-bound walker: step after step, always downhill, until the bottom of the blue basin.Source : Towards AI

The Fundamental Equation

θnew=θold−η⋅∇L(θ)\theta_{\text{new}} = \theta_{\text{old}} - \eta \cdot \nabla L(\theta)

Symbol by symbol:

  • θ\theta ("theta"): all the model's learned parameters at once, its millions of dials gathered under one name. This is what gets changed.
  • L(θ)L(\theta): the loss obtained with those particular settings. This is what we want to bring down.
  • ∇\nabla ("nabla"): the gradient. For every dial, which way and how far to turn it in order to make the loss go up.
  • η\eta ("eta"): the learning rate, the step size. A plain number, often 0.001.

The minus sign is the whole mechanism: the gradient says where uphill is, and we go the other way. If the error rises sharply when a dial turns right, turn it left.

The Learning Rate: Your Biggest Lever

It is the setting that matters most. It is called a hyperparameter: something you choose before training, as opposed to the parameters that training itself discovers.

Comparison of learning rates in gradient descent
The same error curve, walked with three different step sizes. On the left, a swarm of tiny arrows that still has not reached the bottom. In the middle, a handful of steps is enough. On the right, the steps are so large that the ball bounces from wall to wall and climbs instead of descending.Source : AI Mind

Too High

Learning rate = 0.1. You take huge leaps. You jump over the minimum. Your weights oscillate. Or worse, they diverge (explode toward infinity). The error goes up instead of down.

Too Low

Learning rate = 0.00001. You advance at a snail's pace. Training takes days. And you risk getting stuck in a small local minimum.

The middle ground

You need the right dose: large enough to make progress, small enough not to overshoot. In practice you do not look for a single value, you start high and reduce as training goes on. That is called a learning rate schedule.

While we are here: an epoch is one complete pass over the whole training set.

EpochLearning rateStrategy
1-100.01Big steps to explore
10-500.001Medium steps
50+0.0001Tiny steps to fine-tune
Comparison of decaying vs constant learning rates
Watch how long the red arrows are. On the left the step shrinks as the bottom gets closer, which is exactly the shrinking schedule in the table above. On the right the step stays the same size from start to finish.Source : Deep Learning Wizard

Three Ways to Compute the Slope

Three variants of gradient descent
The same error landscape seen from above: the rings are levels of error, the cross in the middle is the minimum. On the left the path is a straight line, but every step is expensive. In the middle it wobbles a little. On the right it darts all over the place and still ends up at the centre.Source : GeeksforGeeks

Full-batch gradient descent

You compute the gradient on all your data before making a single weight update.

Advantage: very precise.

Disadvantage: ultra slow. With 1 million examples, you wait a long time before the first update.

In practice: almost never used.

Stochastic Gradient Descent (SGD)

You compute the gradient on a single example at a time. "Stochastic" simply means "drawn at random". Update after each example.

Advantage: very fast.

Disadvantage: noisy, unstable. Gradients from one example can be weird.

In practice: reserved for cases where data arrives as a continuous stream, one item at a time.

Mini-batch SGD (the standard)

You compute the gradient on 32, 64, or 128 examples at a time.

Advantage: the right compromise. Enough data at once to keep a Graphics Processing Unit (GPU) busy, since it computes in parallel; few enough to make many updates.

Disadvantage: none really.

In practice: this is what's always used. When someone says "SGD," they actually mean mini-batch.

Batch size?

32-256 is standard. On GPU, you can go 512 or more. On a small computer, 32 is enough. Larger = more stable but fewer updates per epoch.

Momentum: Avoiding Oscillations

Problem with plain SGD: if the error surface is a "ravine" (very steep in one direction, almost flat in another), the gradient oscillates in a zigzag instead of going straight.

It's like a ball in a narrow bowl. It bounces from one side to the other, slowing down at each turn. Frustrating.

Solution: accumulate velocity. Remember past gradients.

vt=β⋅vt−1+∇L(θ)v_t = \beta \cdot v_{t-1} + \nabla L(\theta) θ=θ−η⋅vt\theta = \theta - \eta \cdot v_t

Symbol by symbol: tt numbers the training steps; vtv_t (for velocity) is the momentum accumulated at step tt; vt−1v_{t-1} is the previous step's; β\beta ("beta") is a number between 0 and 1 saying what fraction of the old momentum is kept; ∇L(θ)\nabla L(\theta) is the current gradient, and η\eta the learning rate as above.

In one sentence: instead of following the slope of the moment, follow an average of the recent slopes, and let that average move the parameters.

This is how a rolling ball behaves: it picks up speed on steady descents. The left-right oscillations, meanwhile, cancel from one step to the next and average out, which is precisely the effect being sought.

β=0.9\beta = 0.9 is the typical value: 90% of the previous momentum is kept, so the memory spans about ten steps. At 0.990.99 the inertia is stronger, at 0.50.5 weaker.

Nesterov Accelerated Gradient (NAG)

Clever trick: instead of computing the gradient where you are now, compute it where you would be after the momentum step.

It's like taking a step forward, looking at the slope there, then adjusting your direction. This helps avoid overshooting minima.

Faster than classic momentum. Used in modern optimizers.

Comparison of Momentum and Nesterov
On the left, momentum carries the ball too far: it overshoots the bottom and has to come back (steps 5 and 6). On the right, Nesterov first peeks at where the momentum would land it (the dotted orange arrow) and only then commits, so it overshoots far less.Source : Medium

The Error Landscape in High Dimensions

In 2D, you imagine a mountain. Local minima, plateaus. Simple.

In millions of dimensions (millions of weights), it gets weird:

Saddle Points vs Local Minima

In very high dimensions, true "trap" local minima are rare. Most stationary points are saddle points: one direction goes down, another goes up. Why a non-convex landscape still lets itself be descended is the subject of convexity; the notion of a gradient is rebuilt from scratch in derivatives and gradients, and the algorithm's variants in gradient methods.

When descending, you naturally pass through the saddle point (continue in the descending direction).

3D surface with saddle point
This horse-saddle shape is the saddle point. At the centre the surface falls away if you move forward and rises if you move sideways. It is not a real hollow, which is why descent eventually escapes it.Source : Bibm@th

Low-Error Valleys

Good minima (with low error) are often connected by "valleys" of similar error. There isn't one minimum, there are thousands that are all good.

This means: you don't need to find the best weights. You can stop anywhere in the right valley.

Skip Connections for a Smoother Landscape

Residual networks (ResNets) use residual connections, also called skip connections: a direct path lets the data, and therefore the gradient, bypass certain layers. Result: the error landscape is much smoother.

Comparison of CNN vs ResNet with skip connections
Top row, the classic network: the image passes through the layers one after another, single file. Bottom row, the ResNet adds bridges that skip over each layer and are added back to its output (the small plus signs). Those shortcuts are what smooths out the error landscape.Source : Ultralytics

This is why we can train very deep networks (100+ layers) now. Before, they would diverge. Skip connections make gradient descent more robust.

Instability in Depth

Problem: during backpropagation the gradient must cross every layer, being multiplied at each one. In a deep network it ends up either swelling out of control (exploding gradients) or dying out (vanishing gradients). See Backpropagation for the mechanism.

Solutions:

Gradient clipping: when the gradient exceeds a set length it is shortened to that length, without changing its direction.

Comparison of gradient descent with and without clipping
The error landscape again, seen from above. On the left, with no cap, some steps are so long that they throw the model right out of the rings. On the right, every step is trimmed to a maximum length, so the path stays inside the bowl and reaches the cross at the centre.Source : ResearchGate

Smart initialization: the Xavier and He methods pick the weights' starting values from the number of inputs each layer has, so the gradient crosses the layers without either swelling or dying out.

Comparison of loss with He and Xavier initialization
Two identical training runs that differ only in the starting values of the weights. The orange curve freezes almost immediately, while the blue one keeps going down over a thousand passes through the data. The starting point alone changes the final result.Source : ResearchGate

Normalization: BatchNorm, LayerNorm. Keeps activations within a healthy range.

Comparison of unnormalized and normalized gradient descent
On the left, without normalization, the error levels form a long stretched ellipse and the descent zigzags along that narrow valley. On the right they are almost circular and the path heads straight for the centre. That is the comfort normalization buys.

Practical Summary

Start with SGD plus momentum (β=0.9\beta = 0.9) and batches of 64 to 256 examples.

For the learning rate, the classic empirical method: run a very short training while ramping the rate from 0.0001 up to 0.1, and watch which range makes the loss fall fastest.

If you want something more modern, use Adam or AdamW, covered in Modern optimizers.

Add a schedule: start high, reduce progressively.

Simple as that, and it works for the majority of cases.

Check your understanding0 / 5

1. In the update θ = θ − η · ∇L, what exactly does the gradient provide, and what decides the step size?

2. What happens with a learning rate that is far too high?

3. When a practitioner says they train « with SGD », what are they almost always doing in reality?

4. How does momentum kill the zigzags in a ravine of the error landscape?

5. In millions of dimensions, must you find THE global minimum of the error landscape?