# Chapter 18: Optimizers

> Momentum, RMSProp, and Adam: smarter ways to step. Opening question: Backpropagation gives exact gradients. Why was training still so slow?

From *The Book of Machine Learning*, a free interactive machine learning textbook. Interactive version, with figures to use: https://thebookofml.com/optimizers/

[The last chapter](https://thebookofml.com/backpropagation/) ended with a network that learned, but slowly: 2,000 steps to get 62% of the spiral right. The gradients were exact. What was crude was how we used them: subtract the gradient, times one fixed number, every time. The rule that turns gradients into updates is called an optimizer, and this chapter builds better ones, each fixing a specific weakness of the one before.

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

> **Interactive figure: One learning rate for a lopsided valley.** Each ring joins points of equal height. The path starts at the dark dot and takes 100 steps of plain gradient descent.
> Try it: start at 0.10 and read the verdict. Raise the rate slowly to 0.90, then on to 0.98, then past 1.00.
> (Use it at https://thebookofml.com/optimizers/)

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. Learning-rate decay shrinks the rate as training goes on.

$$
\eta_t = \frac{\eta_0}{1 + \text{decay} \times t}
$$

> **Interactive figure: Letting the bouncing die away.** The starting rate is 0.98, slightly too large for the steep direction.
> Try it: with decay at zero, watch the path bounce. Raise the decay a little, to about 0.02. Then raise it a lot and see the opposite problem.
> (Use it at https://thebookofml.com/optimizers/)

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 momentum. Keep a running velocity. At each step, keep a fraction of the old velocity and add the new gradient step to it.

$$
v \leftarrow \beta\,v - \eta\,\nabla L \qquad\qquad w \leftarrow w + v
$$

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.

> **Interactive figure: A ball that remembers.** The learning rate is fixed at the cautious 0.10 that was too slow on its own.
> Try it: raise the momentum from 0 toward 0.90 and watch the path stretch out along the valley. Then push it to 0.98.
> (Use it at https://thebookofml.com/optimizers/)

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.

**Check your understanding:** During training the gradient for one weight keeps flipping sign: +3, −3, +3, −3. What does momentum do to that weight's updates?

- Makes them larger each time — Momentum builds up only when gradients keep the same sign. Alternating gradients work against each other.
- Makes them smaller, because the opposing gradients partly cancel **(correct)** — Each new gradient is added to a velocity that points the other way. The weight stops being thrown back and forth.
- Nothing, since the average gradient is zero — The updates do change: plain gradient descent would swing fully each time, while momentum damps the swings.

## 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 adaptive learning rate gives each weight its own step size, set from that weight's own history. A weight whose gradients have been large gets a smaller step. A weight whose gradients have been tiny gets a larger one. In the valley, that means short steps across and long steps along, automatically.

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

**Example: Two weights, one update**

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. Adam keeps a momentum-style running average of the gradient *and* an RMSProp-style running average of its square, and divides one by the other.

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.

> **Interactive figure: Four ways down the same valley.** All four start from the same point. Plain gradient descent uses the cautious rate, since its fast rate was on the edge of diverging.
> Try it: press Race and watch the order in which they arrive. Reset and use Step to follow the first ten moves one at a time.
> (Use it at https://thebookofml.com/optimizers/)

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 last chapter](https://thebookofml.com/backpropagation/), unchanged: same data, same 195 weights, same starting point. Only the optimizer differs.

> **Interactive figure: The same network, five optimizers.** Each run starts from identical weights. Choosing an optimizer resets the network.
> Try it: train with plain SGD for a few hundred steps to remember how slow it was. Then choose Adam and train again.
> (Use it at https://thebookofml.com/optimizers/)

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.

**Check your understanding:** You are starting a new project and have to pick an optimizer before knowing anything about the loss surface. What is the sensible default?

- Plain SGD with a learning rate of 1 — It can work, but only if that rate happens to suit the surface. It is the most sensitive choice.
- Adam with its default settings **(correct)** — Adam adapts the step for each weight and adds momentum, so it works acceptably on a wide range of problems with little tuning.
- AdaGrad, because its steps only shrink — Steps that only shrink are its weakness: on long runs it can stall before training is done.

**Common mistake: Carrying a learning rate over to another optimizer**

A learning rate only means something for the optimizer it was chosen for. Plain gradient descent multiplies the rate by the gradient, so a rate of 0.5 or 1 can be reasonable. Adam divides each gradient by its typical size first, so every weight moves by roughly the learning rate itself on every step, and a rate of 1 would throw the weights around wildly. Typical values for Adam are ten to a thousand times smaller. When you switch optimizer, choose the learning rate again from scratch.

## In code

All the optimizers share one small base class that handles the decay. Here are the two most used. The full file, [ch18_optimizers.py](https://github.com/kamileren/quickproject/blob/master/code/ch18_optimizers.py), has all five and runs the comparison.

```python
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.

## What you should now be able to do

- 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

### Exercise (by hand)

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: $1 / (1 + 0) = 1$
- Step 10: $1 / (1 + 1) = 0.5$
- Step 90: $1 / (1 + 9) = 0.1$

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.

### Exercise (by hand)

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 $-0.1$, then $0.9 \times (-0.1) - 0.1 = -0.19$, then $0.9 \times (-0.19) - 0.1 = -0.271$. They keep growing and approach $-0.1 / (1 - 0.9) = -1$. 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 $-0.1$, then $0.9 \times (-0.1) + 0.1 = 0.01$, then $0.9 \times 0.01 - 0.1 = -0.091$. 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.

### Exercise (by hand)

The valley in this chapter is $f(x, y) = 0.05x^2 + y^2$. With plain gradient descent, each step multiplies $y$ by $(1 - 2\eta)$ and $x$ by $(1 - 0.1\eta)$. 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 $y$ grows whenever $1 - 2\eta$ is below −1, which happens as soon as $\eta$ is above 1. The steep direction sets the limit.

**The slowness.** At $\eta = 0.9$ the flat direction is multiplied by $1 - 0.09 = 0.91$ at each step. Shrinking $x$ to a tenth of its starting value takes about 24 steps, since $0.91^{24} \approx 0.1$. The learning rate that $x$ would like, about 10, is ten times beyond what $y$ 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.

### Exercise (think)

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.

### Exercise (with the figure)

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

- H. Kinsley and D. Kukieła, *Neural Networks from Scratch in Python*, chapter 10, [nnfs.io](https://nnfs.io).
- G. Goh, [Why momentum really works](https://distill.pub/2017/momentum/), Distill, 2017.
- D. P. Kingma and J. Ba, [Adam: a method for stochastic optimization](https://arxiv.org/abs/1412.6980), 2014.

## Next

With Adam the network fits the spiral almost perfectly. That creates a new problem, the same one a degree-9 curve had many chapters ago. A network that can fit anything will also fit the noise.
