Adagrad and RMSprop
Gradient descent uses one learning rate for every parameter. That is a poor fit when parameters live on very different scales: an embedding row for a word seen once in a million sentences gets a gradient almost never, while a bias term gets one on every step; a weight attached to a feature measured in thousands sees gradients a thousand times larger than one attached to a feature in fractions. Any single is too big for some parameters and too small for others. Adaptive methods give each parameter its own step size, computed from the history of its own gradients. Adagrad (Duchi, Hazan and Singer, 2011) uses the sum of squared gradients; RMSprop (Hinton's 2012 lecture notes) replaces the sum by a moving average. Both lead directly to Adam.
Adagrad
Keep a per-parameter sum of squared gradients and divide each step by its square root (all operations elementwise):
A parameter with large gradients gets small steps; one with small or rare gradients keeps large steps. On the first step , so every parameter moves by exactly in the direction of its gradient's sign, whatever the gradient's size. The catch is that only grows. For a gradient of roughly constant size , , so the effective step decays like , which is good for convex problems with sparse features (Adagrad's original use: linear models on text and click data) but stalls long non-convex training runs.
RMSprop
Replace the sum by an exponential moving average, so old gradients are forgotten:
with around 0.9 to 0.99 (PyTorch's default is 0.99). is the root mean square of recent gradients, hence the name. The step is roughly , so its size is about for every parameter and stays that way for the whole run. Derivations and the connection to diagonal preconditioning are in Adagrad and RMSprop.
A badly scaled bowl
The loss is 100 times steeper in than in . Plain GD must keep to stay stable in , and then moves by only about 2 % of its distance per step.
import numpy as np
curv = np.array([100.0, 1.0]) # f = 1/2 (100 x^2 + y^2): steep in x, flat in y
f = lambda p: 0.5 * np.sum(curv * p ** 2)
grad = lambda p: curv * p
def gd(p, g, s, lr):
return p - lr * g
def adagrad(p, g, s, lr, eps=1e-10):
s["G"] = s.get("G", 0) + g ** 2 # sum of all squared gradients so far
return p - lr * g / (np.sqrt(s["G"]) + eps)
def rmsprop(p, g, s, lr, alpha=0.9, eps=1e-8):
s["E"] = alpha * s.get("E", 0) + (1 - alpha) * g ** 2 # moving average of g^2
return p - lr * g / (np.sqrt(s["E"]) + eps)
print("loss after 25 / 50 / 75 / 100 steps, from (1, 1)")
for name, fn, lr in [("GD", gd, 0.019), ("Adagrad", adagrad, 0.5), ("RMSprop", rmsprop, 0.05)]:
p0 = np.array([1.0, 1.0])
first = fn(p0, grad(p0), {}, lr) - p0 # the very first step
p, s, out = p0, {}, []
for k in range(1, 101):
p = fn(p, grad(p), s, lr)
if k % 25 == 0:
out.append(f"{f(p):.1e}")
print(f"{name:8s} lr {lr:<5}: " + " ".join(out) + f" first step {np.round(first, 3)}")loss after 25 / 50 / 75 / 100 steps, from (1, 1)
GD lr 0.019: 4.5e-01 7.5e-02 2.8e-02 1.1e-02 first step [-1.9 -0.019]
Adagrad lr 0.5 : 2.5e-11 1.8e-23 1.3e-35 9.4e-48 first step [-0.5 -0.5]
RMSprop lr 0.05 : 3.0e-02 1.7e-16 4.9e-36 3.0e-02 first step [-0.158 -0.158]
- GD's first step is : a hundred times bigger in than in . After 100 steps the loss is still 0.011, all of it in the slow direction.
- Adagrad's first step is : exactly in both coordinates. Per-coordinate scaling has removed the 100-to-1 imbalance, and the loss falls to . On a separable quadratic this is the ideal case; the decaying step size does no harm because it is exactly what convergence needs.
- RMSprop's first step is in each coordinate, not 0.05: with , the first average is only , so the step is too large by . Adam corrects exactly this bias. The loss sequence also shows RMSprop's typical behaviour with a constant : it reaches and then bounces back to 0.03. As the gradients shrink, their moving average shrinks too, so stays near 1 and the step stays near ; the iterate cannot settle closer than about to the minimum. A decaying learning rate fixes that.
Effective step sizes over a long run
The difference between "sum" and "average" shows up when the gradient scale changes. Here the gradient is about 2 for 5000 steps and then drops to about 0.2, with 10 % noise; the columns are the actual step sizes with .
import numpy as np
rng = np.random.default_rng(0)
lr = 0.01
G, E = 0.0, 0.0
print(" step |g| Adagrad step RMSprop step")
for t in range(1, 10001):
g = 2.0 if t <= 5000 else 0.2 # gradient size drops 10x halfway
g = g * (1 + 0.1 * rng.normal()) # with a little noise
G += g ** 2
E = 0.99 * E + 0.01 * g ** 2
if t in (1, 10, 100, 1000, 5000, 5001, 5100, 10000):
print(f"{t:6d} {abs(g):5.2f} {lr * abs(g) / np.sqrt(G):12.6f} {lr * abs(g) / np.sqrt(E):12.6f}") step |g| Adagrad step RMSprop step
1 2.03 0.010000 0.100000
10 1.75 0.002732 0.027948
100 1.72 0.000849 0.010655
1000 1.95 0.000309 0.009910
5000 1.62 0.000114 0.008061
5001 0.20 0.000014 0.000981
5100 0.22 0.000015 0.001770
10000 0.22 0.000015 0.011025
Adagrad's step falls from 0.01 to 0.00011 by step 5000, as ; when the gradients shrink tenfold, its step shrinks tenfold too, to 0.000015, and never recovers, because the sum still remembers the big early gradients. RMSprop's step is about during each phase. It drops briefly after the switch (0.00098 at step 5001, while the average still remembers the large gradients), recovers within a few hundred steps (its memory is about steps), and is back at 0.011 by the end. RMSprop's first step, 0.1, is again times too large. For deep networks, whose gradient scales change a lot during training, RMSprop's forgetting is what you want.
In the libraries
| PyTorch (with its defaults) | Notes |
|---|---|
torch.optim.Adagrad(params, lr=0.01, initial_accumulator_value=0, eps=1e-10) |
lr_decay adds an extra factor |
torch.optim.RMSprop(params, lr=0.01, alpha=0.99, eps=1e-8, momentum=0, centered=False) |
centered=True divides by an estimate of the variance instead of the raw second moment; momentum adds a velocity on top |
In both, is added after the square root, as in our code; the optimizer comparison checks our functions against them. RMSprop with momentum was a standard choice for reinforcement learning and recurrent networks before Adam; Adagrad remains useful for sparse linear models and embeddings. The next lesson, Adam and AdamW, combines RMSprop's denominator with momentum and fixes the start-up bias.
Pitfalls
- Adagrad for long training. Its step only decays; a learning rate that is right at the start is far too small after 100,000 steps.
- A tiny with tiny gradients. If a parameter's gradients are near zero, can still be near 1, giving full-size steps to parameters that carry no signal. Larger (e.g. to ) makes the method behave more like SGD for them.
- Expecting convergence with a constant rate. Adaptive methods keep steps near in size; without a schedule they hover around the minimum.
Practice
- Adagrad, , and a constant gradient of 4 for one parameter. What are the first three steps?
Answer
, so the steps are , and : , independent of the gradient's size.
- RMSprop with and : by what factor is the first step too large compared with ?
Answer
, so the step is , matching the 0.158 for in the first example.
Test yourself
What does Adagrad divide each parameter's step by?
- The learning rate
- The square root of the sum of all its past squared gradients
- The number of steps
- The norm of the whole gradient vector
Why can Adagrad stall in long training runs?
- Its accumulator only grows, so the effective learning rate keeps decreasing
- It uses too much memory
- It ignores the gradient's sign
- It needs second derivatives
RMSprop differs from Adagrad by…
- using momentum
- using an exponential moving average of squared gradients instead of their sum
- using one learning rate for all parameters
- using the Hessian
On starting at , Adagrad's first step is with . Why the same in both coordinates?
- Because the gradient is the same in both
- Because on the first step , so each coordinate moves by exactly in the direction of its gradient's sign
- Because Adagrad normalises the whole vector
- By coincidence