What plain gradient descent gets wrong
To see the weakness clearly we need a simple surface that shows it. Here is a long, narrow valley: gentle along its length, twenty times steeper across its width. Loss surfaces of real networks are full of shapes like this.
One learning rate for a lopsided valley
- Height after 10 steps
- 3.416
- Height after 100 steps
- 0.543
- Verdict
- Not there after 100 steps
The trouble is that a single learning rate has to serve both directions.
- At 0.10 the steps across the valley are well behaved, but progress along it is a crawl. After 100 steps the path is still well short of the bottom.
- At 0.90 it arrives in 24 steps. That is as good as it gets.
- At 0.98 each step overshoots the steep direction, and the path wastes its effort bouncing from wall to wall.
- Just past 1.00 every bounce is bigger than the last, and the run diverges.
The steep direction sets a hard ceiling on the learning rate, and the gentle direction wants a rate far above that ceiling. The best single value sits on the edge of disaster, and you can only find it by trial and error. Real networks have millions of directions, each with its own steepness.
Start big, finish small
A first, easy improvement: do not keep the learning rate fixed. Large steps are useful early on, when the weights are far from anywhere good. Small steps are needed late, to settle instead of bouncing.
current rate = starting rate ÷ (1 + decay × number of steps so far)
Letting the bouncing die away
- Height after 10 steps
- 4.493
- Height after 100 steps
- 0.003
- Verdict
- Near the bottom in 64 steps
With no decay the path takes 64 steps to settle. A decay of 0.02 cuts that to 27, because the bounces shrink as the rate does. But decay is one more setting that can be wrong: at 0.2 the rate collapses so quickly that the path runs out of energy before it arrives.
Momentum
The bouncing has a pattern worth exploiting. Across the valley, successive gradients point in opposite directions: left, right, left. Along the valley they all point the same way. If each step remembered the previous ones, the back-and-forth would cancel and the consistent direction would add up.
That is
velocity = momentum × old velocity − learning rate × gradient; then move by the velocity
The picture is a heavy ball rolling downhill. It does not turn on the spot when the slope changes; it carries on, and picks up speed where the slope keeps pointing the same way.
A ball that remembers
- Height after 10 steps
- 3.416
- Height after 100 steps
- 0.543
- Verdict
- Not there after 100 steps
With momentum at 0.9, the cautious learning rate that never arrived now gets there in 24 steps, as fast as the best hand-tuned rate, and without sitting next to the cliff. The usual value is 0.9. Too much, and the ball has so much inertia that it sails past the bottom and has to come back.
During training the gradient for one weight keeps flipping sign: +3, −3, +3, −3. What does momentum do to that weight's updates?
A step size for every weight
Momentum smooths the direction. A different idea attacks the original problem head on: why should every weight share one learning rate at all?
An
The mechanism is simple: keep a running total of each weight’s squared gradients, and divide its step by the square root of that total.
| Method | What it remembers | Consequence |
|---|---|---|
| AdaGrad | The sum of all squared gradients so far | Steps only ever shrink. Training can stall before it is finished. |
| RMSProp | A fading average of recent squared gradients | Steps adapt to the current terrain and do not shrink for ever. |
Suppose two weights have recently seen gradients of typical size 10 and 0.1.
- Plain gradient descent with rate 0.01 moves them by 0.1 and 0.001. The second weight is barely moving.
- RMSProp divides each step by the typical gradient size: both move by about 0.01.
Every weight makes progress at a similar pace, whatever the scale of its gradients.
Adam, and a race
The last step is to use both ideas together.
It adds one small correction. Both averages start at zero, so for the first few steps they are too small. Adam divides each by a factor that undoes this, and the effect is that its very first step has a sensible size.
Here are four optimizers on the same valley, each with ordinary default-style settings and no tuning to this surface.
Four ways down the same valley
- Plain SGD (rate 0.1)
- Momentum (rate 0.1, momentum 0.9)
- RMSProp (rate 0.3)
- Adam (rate 0.5)
- Plain SGD
- height 13.050
- Momentum
- height 13.050
- RMSProp
- height 13.050
- Adam
- height 13.050
Momentum, RMSProp and Adam all reach the bottom in 20 to 30 steps. Plain gradient descent is still on its way after 100.
To be fair to it: we saw that plain gradient descent can match them here, at a rate of 0.9. The difference is that it needed exactly the right rate, found by search, right next to the value at which it blows up. The others got there with settings chosen before looking at the surface. That robustness, more than raw speed, is why Adam became the default.
On a real network
Now the test that matters. This is the spiral network from
The same network, five optimizers
- Class 1, and where the network predicts it
- Class 2, and where the network predicts it
- Class 3, and where the network predicts it
- Steps
- 0
- Loss
- 1.173
- Right on the 300 shown
- 32%
- Right on 300 new points
- 34%
After 2,000 steps each:
| Optimizer | Loss | Right on the training points | Right on new points |
|---|---|---|---|
| Plain SGD | 0.788 | 62% | 58% |
| AdaGrad | 0.751 | 63% | 60% |
| RMSProp | 0.238 | 92% | 85% |
| SGD with momentum and decay | 0.031 | 99% | 96% |
| Adam | 0.015 | 99% | 95% |
Adam passes 96% within the first 300 steps. Nothing about the network or the data changed. The gradients were always good enough; they only needed to be used well.
You are starting a new project and have to pick an optimizer before knowing anything about the loss surface. What is the sensible default?
In code
All the optimizers share one small base class that handles the decay. Here are the two most used. The full file, code/ch18_optimizers.py (run it in Colab), has all five and runs the comparison.
class Optimizer_SGD(Optimizer):
def update_params(self, layer):
# Keep part of the last step, add the new gradient step.
layer.weight_momentums = self.momentum * layer.weight_momentums - self.current_learning_rate * layer.dweights
layer.weights += layer.weight_momentums
# ...and the same two lines for the biases
class Optimizer_Adam(Optimizer):
def update_params(self, layer):
# Momentum: a running average of the gradients.
layer.weight_momentums = self.beta_1 * layer.weight_momentums + (1 - self.beta_1) * layer.dweights
# Cache: a running average of the squared gradients.
layer.weight_cache = self.beta_2 * layer.weight_cache + (1 - self.beta_2) * layer.dweights ** 2
# Both start at zero, so early on they are too small. Dividing corrects that.
step = self.iterations + 1
weight_momentums = layer.weight_momentums / (1 - self.beta_1 ** step)
weight_cache = layer.weight_cache / (1 - self.beta_2 ** step)
layer.weights -= self.current_learning_rate * weight_momentums / (np.sqrt(weight_cache) + self.epsilon)
In the training loop, the single line that updated the weights is the only thing that changes. The Python version, run for 2,000 epochs, gives 53% with plain SGD and 99% with either momentum or Adam.
Key Takeaways
- Plain gradient descent uses one learning rate for every direction, and the steepest direction limits it.
- Decay starts with large steps and ends with small ones.
- Momentum carries speed from step to step: consistent directions build up, back-and-forth cancels.
- RMSProp gives each weight its own step size, based on its recent gradients.
- Adam combines momentum and per-weight step sizes, and is the usual default.
- Explain why one learning rate cannot suit a lopsided loss surface.
- Work out a decayed learning rate and a momentum update by hand.
- Say what RMSProp and Adam each add, and why Adam is the usual first choice.
- Pick sensible starting settings for an optimizer.
Exercises
Try each one before opening its solution. Getting stuck for a few minutes is where most of the learning happens.
A run uses a starting learning rate of 1 and a decay of 0.1. What is the learning rate at step 0, at step 10 and at step 90?
Hint
Current rate = starting rate ÷ (1 + decay × steps so far).
Solution
The rule is: current rate = starting rate ÷ (1 + decay × steps so far).
- Step 0:
- Step 10:
- Step 90:
The rate halves in the first ten steps and then takes another eighty to fall to a tenth. Decay acts quickly at first and ever more gently later.
With momentum, each update is 0.9 times the previous update, minus the learning rate times the gradient. The learning rate is 0.1. First suppose the gradient is 1 at every step: what are the first three updates, and what do they approach? Then suppose the gradient alternates between 1 and −1: what are the first three updates?
Hint
Compute each update from the one before: 0.9 times the previous update, minus 0.1 times the gradient.
Solution
Steady gradient. The updates are , then , then . They keep growing and approach . In a direction where the gradient always agrees with itself, momentum ends up moving ten times as fast as a plain step.
Alternating gradient. The updates are , then , then . They never build up, and none is larger than a plain step, because each one is partly cancelled by what came before.
That is the whole benefit: fast along the valley, calm across it.
The valley in this chapter is . With plain gradient descent, each step multiplies by and by . Use this to explain why the run diverges just above a learning rate of 1, and why it is slow even at 0.9.
Hint
A value multiplied by a number larger than 1 in size grows. One multiplied by 0.91 shrinks slowly.
Solution
The limit. The size of grows whenever is below −1, which happens as soon as is above 1. The steep direction sets the limit.
The slowness. At the flat direction is multiplied by at each step. Shrinking to a tenth of its starting value takes about 24 steps, since . The learning rate that would like, about 10, is ten times beyond what can survive.
One rate has to serve two directions with very different steepness. Momentum and the adaptive methods are both ways out of that bind.
Two weights have gradients that are steadily 100 and 0.01. With plain gradient descent and a learning rate of 0.01, how far does each move in one step? Roughly how far does each move in one step of Adam with the same learning rate? What does that tell you about when Adam helps?
Hint
Plain gradient descent moves a weight by the rate times its gradient. Adam first divides the gradient by its typical size.
Solution
Plain gradient descent moves each weight by the rate times its gradient: 1 for the first weight and 0.0001 for the second. One of them is moving ten thousand times faster than the other.
Adam divides each gradient by its own typical size before applying the rate, so both weights move by about 0.01.
Adam helps when gradients differ greatly in size from weight to weight, which is normal in a deep network: layers near the output usually see larger gradients than layers near the input. It removes the need to find one rate that suits them all.
In the figure “A ball that remembers”, raise the momentum from 0 to 0.9 and count the steps to settle. Then try 0.98. What goes wrong, and how does it differ from a learning rate that is too large?
Hint
With plain steps and a cautious rate, the run never arrived within 100 steps.
Solution
With no momentum the cautious learning rate does not arrive in 100 steps. At 0.9 it gets there in 24, because steps along the valley floor all point the same way and build on each other.
At 0.98 the ball carries so much speed that it sails past the lowest point and has to come back, swinging to and fro before it settles. That is different from a learning rate that is too large. The ball still settles in the end, because friction removes a little speed at every step, whereas too large a learning rate makes each step bigger than the last and never recovers.
Going further
The learning rate still matters
Adaptive optimizers are forgiving, not magic. Adam’s rate still needs to be roughly right, and it is usually the first thing to adjust when training misbehaves: try values a factor of three or ten apart. Schedules that warm the rate up from zero and then lower it are standard for large models.
When plain SGD is preferred
For some problems, especially image models trained for a long time, SGD with momentum and a careful schedule ends at solutions that generalize slightly better than Adam’s. It costs more tuning. Adam, and its variant AdamW with a corrected weight penalty, remain the place to start.
References and further reading
- H. Kinsley and D. Kukieła, Neural Networks from Scratch in Python, chapter 10, nnfs.io.
- G. Goh, Why momentum really works, Distill, 2017.
- D. P. Kingma and J. Ba, Adam: a method for stochastic optimization, 2014.