TExcelTAD

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 η\eta 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):

Gt=Gt−1+gt2,wt=wt−1−ηGt+ϵ gt\mathbf{G}_t = \mathbf{G}_{t-1} + \mathbf{g}_t^2, \qquad \mathbf{w}_t = \mathbf{w}_{t-1} - \frac{\eta}{\sqrt{\mathbf{G}_t} + \epsilon} \, \mathbf{g}_t

A parameter with large gradients gets small steps; one with small or rare gradients keeps large steps. On the first step G1=∣g1∣\sqrt{G_1} = \lvert g_1 \rvert, so every parameter moves by exactly η\eta in the direction of its gradient's sign, whatever the gradient's size. The catch is that Gt\mathbf{G}_t only grows. For a gradient of roughly constant size gg, Gt≈gt\sqrt{G_t} \approx g\sqrt{t}, so the effective step decays like η/t\eta/\sqrt{t}, 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:

Et=α Et−1+(1−α) gt2,wt=wt−1−ηEt+ϵ gt\mathbf{E}_t = \alpha \, \mathbf{E}_{t-1} + (1 - \alpha) \, \mathbf{g}_t^2, \qquad \mathbf{w}_t = \mathbf{w}_{t-1} - \frac{\eta}{\sqrt{\mathbf{E}_t} + \epsilon} \, \mathbf{g}_t

with α\alpha around 0.9 to 0.99 (PyTorch's default is 0.99). Et\sqrt{\mathbf{E}_t} is the root mean square of recent gradients, hence the name. The step is roughly η⋅g/RMS(g)\eta \cdot g / \text{RMS}(g), so its size is about η\eta 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 f=12(100x2+y2)f = \frac{1}{2}(100x^2 + y^2) is 100 times steeper in xx than in yy. Plain GD must keep η<2/100=0.02\eta < 2/100 = 0.02 to stay stable in xx, and then yy moves by only about 2 % of its distance per step.

python · try it yourself
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 (−1.9,−0.019)(-1.9, -0.019): a hundred times bigger in xx than in yy. After 100 steps the loss is still 0.011, all of it in the slow yy direction.
  • Adagrad's first step is (−0.5,−0.5)(-0.5, -0.5): exactly η\eta in both coordinates. Per-coordinate scaling has removed the 100-to-1 imbalance, and the loss falls to 10−4710^{-47}. 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 0.158=0.05/0.10.158 = 0.05/\sqrt{0.1} in each coordinate, not 0.05: with E0=0\mathbf{E}_0 = 0, the first average is only (1−α)g2(1 - \alpha) g^2, so the step is too large by 1/1−α1/\sqrt{1 - \alpha}. Adam corrects exactly this bias. The loss sequence also shows RMSprop's typical behaviour with a constant η\eta: it reaches 10−3610^{-36} and then bounces back to 0.03. As the gradients shrink, their moving average shrinks too, so g/Eg/\sqrt{E} stays near 1 and the step stays near η\eta; the iterate cannot settle closer than about η\eta 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 η∣g∣/⋅\eta \lvert g \rvert / \sqrt{\cdot} with η=0.01\eta = 0.01.

python · try it yourself
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 1/t1/\sqrt{t}; 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 η=0.01\eta = 0.01 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 1/(1−α)=1001/(1 - \alpha) = 100 steps), and is back at 0.011 by the end. RMSprop's first step, 0.1, is again 1/1−0.99=101/\sqrt{1 - 0.99} = 10 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 1/(1+(t−1)⋅decay)1/(1 + (t-1) \cdot \text{decay}) 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, ϵ\epsilon 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 ϵ\epsilon with tiny gradients. If a parameter's gradients are near zero, g/(E+ϵ)g/(\sqrt{E} + \epsilon) can still be near 1, giving full-size steps to parameters that carry no signal. Larger ϵ\epsilon (e.g. 10−610^{-6} to 10−310^{-3}) makes the method behave more like SGD for them.
  • Expecting convergence with a constant rate. Adaptive methods keep steps near η\eta in size; without a schedule they hover around the minimum.

Practice

  1. Adagrad, η=0.1\eta = 0.1, and a constant gradient of 4 for one parameter. What are the first three steps?
Answer

G=16,32,48G = 16, 32, 48, so the steps are 0.1⋅4/4=0.10.1 \cdot 4/4 = 0.1, 0.1⋅4/32≈0.07070.1 \cdot 4/\sqrt{32} \approx 0.0707 and 0.1⋅4/48≈0.05770.1 \cdot 4/\sqrt{48} \approx 0.0577: η/t\eta/\sqrt{t}, independent of the gradient's size.

  1. RMSprop with α=0.9\alpha = 0.9 and E0=0\mathbf{E}_0 = 0: by what factor is the first step too large compared with η⋅sign⁡(g)\eta \cdot \operatorname{sign}(g)?
Answer

E1=0.1g2E_1 = 0.1 g^2, so the step is ηg/(0.1∣g∣)=η/0.1≈3.16η\eta g / (\sqrt{0.1} \lvert g \rvert) = \eta / \sqrt{0.1} \approx 3.16 \eta, matching the 0.158 for η=0.05\eta = 0.05 in the first example.

Test yourself

What does Adagrad divide each parameter's step by?

  1. The learning rate
  2. The square root of the sum of all its past squared gradients
  3. The number of steps
  4. The norm of the whole gradient vector

Why can Adagrad stall in long training runs?

  1. Its accumulator only grows, so the effective learning rate keeps decreasing
  2. It uses too much memory
  3. It ignores the gradient's sign
  4. It needs second derivatives

RMSprop differs from Adagrad by…

  1. using momentum
  2. using an exponential moving average of squared gradients instead of their sum
  3. using one learning rate for all parameters
  4. using the Hessian

On f=12(100x2+y2)f = \frac{1}{2}(100x^2 + y^2) starting at (1,1)(1, 1), Adagrad's first step is (−0.5,−0.5)(-0.5, -0.5) with η=0.5\eta = 0.5. Why the same in both coordinates?

  1. Because the gradient is the same in both
  2. Because on the first step G1=∣g1∣\sqrt{G_1} = \lvert g_1 \rvert, so each coordinate moves by exactly η\eta in the direction of its gradient's sign
  3. Because Adagrad normalises the whole vector
  4. By coincidence