AI Logic

Optimizers

RMSprop

Updated:

How RMSprop works. The left side shows one step: compute the moving average of squared gradients and update with a per-parameter step size divided by its square root. The right side is a graph comparing, for an example where the gradient magnitude drops to 1/10 partway through, how the amount moved per step keeps shrinking with AdaGrad but recovers to match recent gradients with RMSprop

Background and Overview

RMSprop is an optimizer that keeps a moving average of squared gradients for each parameter and updates by dividing the gradient by its square root (a measure of the recent gradient magnitude). Parameters whose gradients are consistently large move less, parameters with small gradients move more, and the amount every parameter moves is equalized.

RMSprop was not published as a paper. Hinton introduced it in 2012 in Lecture 6e of his online course "Neural Networks for Machine Learning", where the lecture describes it as an unpublished trick by Tieleman. Later papers (such as Graves, 2013 and Liu et al., 2019) cite the lecture slides as the source, and it became one of the representative optimizers in deep learning.

RMSprop is described as a version of the Rprop method that works with mini-batches.

  • Rprop: ignores the gradient magnitude and uses only the sign (direction), moving each weight by a step size determined per weight. Even if gradient magnitudes differ greatly across weights, there is no need to choose a single global learning rate. It is suited to computing gradients over the entire training set (full batch).
  • RMSprop: divides the gradient by "the recent gradient magnitude". Dividing by the gradient magnitude has an effect close to using only the sign. The trick is to make the divisor a moving average so that it barely changes between adjacent mini-batches.

It differs from AdaGrad, which divides by the sum of squared gradients, in using a moving average. A moving average gradually forgets old gradients, so the step size does not keep shrinking. This idea was carried over into the later Adam.

Theory (One Step of the Computation)

The lecture slides say to update, for each weight ww, a moving average of squared gradients MeanSquare(w,t)\mathrm{MeanSquare}(w, t) as follows, and to divide the gradient by MeanSquare(w,t)\sqrt{\mathrm{MeanSquare}(w, t)}.

MeanSquare(w,t)=0.9 MeanSquare(w,t−1)+0.1(∂E∂w(t))2\mathrm{MeanSquare}(w, t) = 0.9\, \mathrm{MeanSquare}(w, t-1) + 0.1 \left(\frac{\partial E}{\partial w}(t)\right)^2

Writing the decay rate (0.9 on the slide) as α\alpha, the learning rate as η\eta, and the gradient as gtg_t, each step tt performs the following computation. The computation is element-wise over the parameters.

  1. Compute the gradient gtg_t on a mini-batch.
  2. Update the moving average of squared gradients vtv_t (v0=0v_0 = 0).
  3. Move the parameters by the gradient divided by vt\sqrt{v_t}.

As equations: ϵ\epsilon is a small value that prevents division by zero; it is not on the slides, but implementations always add it.

vt=αvt−1+(1−α) gt2,θt=θt−1−ηvt+ϵ gtv_t = \alpha v_{t-1} + (1-\alpha)\, g_t^2, \qquad \theta_t = \theta_{t-1} - \frac{\eta}{\sqrt{v_t} + \epsilon}\, g_t

vt\sqrt{v_t} is the square root of the mean of recent squared gradients (Root Mean Square, RMS). This is where the name RMSprop comes from.

The amount moved per step is η⋅∣gt∣/vt\eta \cdot |g_t| / \sqrt{v_t}. If the gradient magnitude stays the same for a while, vt≈∣gt∣\sqrt{v_t} \approx |g_t|, and the amount moved is about η\eta regardless of the gradient magnitude. If the gradient is multiplied by cc, both the numerator and the denominator are multiplied by cc and cancel out, so even when gradient magnitudes differ greatly across layers or weights, they can be handled with the same learning rate.

Why Using Only the Sign Fails with Mini-Batches

The lecture explains with the following example why Rprop cannot be used as is with mini-batches.

Suppose a weight gets a gradient of +0.1+0.1 on nine mini-batches and −0.9-0.9 on the tenth. On average the gradient is 0, so we would like this weight to stay almost still. With ordinary SGD, if the learning rate is small, the gradients are averaged, so the nine small +0.1+0.1 gradients and the one large −0.9-0.9 gradient cancel out.

With Rprop, which uses only the sign, however, the weight is increased by about the same amount nine times and decreased by the same amount only once. Because the difference in gradient magnitude is ignored, the weight grows substantially.

The lecture reinterpreted Rprop as "dividing the gradient by its magnitude" and pointed out that the problem is that the divisor differs from mini-batch to mini-batch. RMSprop therefore makes the divisor a moving average of squared gradients so that it barely changes between adjacent mini-batches. In the example above, the divisor is nearly the same for every mini-batch, so the difference in gradient magnitude (0.10.1 versus 0.90.9) is preserved, and the gradients cancel out just as with SGD.

The lecture states that RMSprop aims to combine three things.

  • The robustness of Rprop: handling gradient magnitudes that differ greatly across weights
  • The efficiency of mini-batches: each computation is cheap
  • Averaging gradients across mini-batches: letting noisy gradients cancel each other out

Differences from AdaGrad

The right side of the figure at the top computes, from the equations, the amount moved per step (as a ratio to the learning rate η\eta) for an example where the gradient magnitude is 1 up to step 50 and 1/10 afterward.

  • AdaGrad keeps moving less and less: its denominator is the sum of squared gradients, so it grows as the steps progress. When the gradient becomes small, the amount moved drops to about 0.014 and never recovers.
  • RMSprop recovers to match recent gradients: its denominator is a moving average, so it gradually forgets old large gradients. With α=0.9\alpha = 0.9, the amount moved drops to 0.1 right after the gradient becomes small, but recovers to near 1 within about 50 steps.
  • The closer α\alpha is to 1, the slower it forgets: with α=0.99\alpha = 0.99, the average covers roughly the last 100 steps, so it takes longer to recover.

In problems like deep learning, which train for a long time and where gradient magnitudes change along the way, AdaGrad can nearly stop moving in the later part of training. RMSprop mitigates this problem with a moving average.

Looking at the left edge of the figure, the amount moved in RMSprop's first steps is larger than η\eta. Because it starts from v0=0v_0 = 0, vtv_t is smaller than its true value at first, making the denominator small. At the first step v1=(1−α)g12v_1 = (1-\alpha) g_1^2, so the amount moved is η/1−α\eta / \sqrt{1-\alpha}: about 3.2 times with α=0.9\alpha = 0.9 and 10 times with α=0.99\alpha = 0.99. Adam corrects this bias with bias correction.

How Papers Use It

Because the source of RMSprop is a set of lecture slides, the original material has no experimental numbers comparing performance. The lecture only says that dividing the gradient by MeanSquare\sqrt{\mathrm{MeanSquare}} "makes the learning work much better." Here are two ways later papers have used it.

  • Centered RMSprop (Graves, 2013): to train an LSTM that generates handwriting, Graves used a version that keeps not only the moving average of squared gradients nn but also the moving average of gradients gˉ\bar{g}, and divides by n−gˉ2+ϵ\sqrt{n - \bar{g}^2 + \epsilon} (an estimate of the gradient variance) (Eqs. (38)–(41) in the paper). It combines momentum as well, with decay rate 0.95, momentum 0.9, learning rate 10−410^{-4}, and ϵ=10−4\epsilon = 10^{-4}. PyTorch's centered=True corresponds to this version.
  • Relationship to warmup (Liu et al., 2019): the RAdam paper analyzes, using Adam, the problem that the variation of the adaptive learning rate becomes large early in training, and states that the same problem applies to methods like RMSprop that use a similar adaptive learning rate.

The lecture also mentions further developments of RMSprop.

  • Combining with ordinary momentum: at the time of the lecture, momentum was said to help less than usual and to need more investigation.
  • Combining with Nesterov momentum: the lecture states that it works best if the division by the RMS of recent gradients is applied to the correction (gradient) rather than the momentum jump.

The lecture's summary recommends using mini-batches for large, redundant datasets and trying gradient descent with momentum or RMSprop (with momentum, too).

Practical Considerations

The default decay rate alpha of PyTorch's torch.optim.RMSprop is 0.99, unlike the lecture's example (0.9). Also, because there is no bias correction as in Adam, the amount moved in the first few steps swells to up to 1/1−α1/\sqrt{1-\alpha} times the learning rate (10 times with alpha=0.99). If the loss spikes at the start of training, try lowering the learning rate, adding warmup, or reducing alpha.

The meanings and default values of PyTorch's arguments are as follows.

ArgumentMeaningDefault
lrLearning rate η\eta0.01
alphaDecay rate α\alpha of the moving average of squared gradients0.99
epsSmall value ϵ\epsilon added to the denominator10−810^{-8}
weight_decayStrength of L2 regularization that adds λθ\lambda\theta to the gradient0
momentumMomentum coefficient applied to the update after division0
centeredWhether to divide by a variance estimate that subtracts the squared mean gradientFalse
  • eps is added outside the square root: PyTorch's denominator is vt+ϵ\sqrt{v_t} + \epsilon. The documentation notes that TensorFlow does these in the opposite order (adding inside the square root). Graves's centered version also adds it inside the square root. When porting settings, note that the effect of ϵ\epsilon changes.
  • centered=True divides by the variance: PyTorch also keeps a moving average of gradients gˉt\bar{g}_t and divides by the square root of v~t=vt−gˉt2\tilde{v}_t = v_t - \bar{g}_t^2. The larger the mean gradient (the more consistent its direction), the smaller the denominator and the larger the step. Memory increases by one copy of the parameters.
  • momentum is applied to the update after division: PyTorch computes bt=μbt−1+gt/(v~t+ϵ)b_t = \mu b_{t-1} + g_t / (\sqrt{\tilde{v}_t} + \epsilon) and θt=θt−1−ηbt\theta_t = \theta_{t-1} - \eta b_t.
  • weight_decay acts as L2 regularization: the λθ\lambda\theta added to the gradient is also divided by vt\sqrt{v_t}, so, as with Adam, the amount of shrinkage varies from weight to weight.

Comparison with Other Optimizers

The table lines up RMSprop and methods that change the step size per parameter, from the same perspectives.

MethodQuantity that sets the step sizeHow the step size changesMean of gradients (momentum)Correction of initial biasExtra memory
AdaGradSum of squared gradientsShrinks monotonicallyNot used(no bias, since it is a sum)One copy of the parameters
RMSpropMoving average of squared gradientsRises and falls with recent gradientsNot used (can be added with momentum)NoneOne copy of the parameters
AdamMoving average of squared gradientsRises and fallsUsedYesTwo copies of the parameters
RAdamMoving average of squared gradientsRises and falls (suppressed at first according to the variance)UsedYesTwo copies of the parameters

Rough guidelines for choosing:

  • When in doubt, start with Adam: it adds the mean of gradients (momentum) and bias correction to RMSprop and is easy to use with the default values.
  • To save a little memory or avoid momentum, use RMSprop: the only state it keeps is the moving average of squared gradients, so it needs one copy of the parameters less than Adam. If a paper's setup uses RMSprop, match that setup.
  • For linear models with sparse features that are not trained for long, AdaGrad is also a candidate: it can move rare features more.

Liu et al. (2019) list, as variants of AdaGrad, AdaDelta and Nadam in addition to RMSprop and Adam.

PyTorch example

Show code
python
import torch
import torch.nn as nn


# One step of RMSprop, written exactly as the equations in the lecture (Lecture 6e) (eps outside the square root, as in PyTorch)
def rmsprop_step(theta, grad, v, lr=1e-2, alpha=0.99, eps=1e-8):
    v = alpha * v + (1 - alpha) * grad ** 2          # Moving average of squared gradients
    theta = theta - lr * grad / (v.sqrt() + eps)     # Divide by the recent gradient magnitude (RMS)
    return theta, v


# Check that it matches PyTorch's RMSprop
torch.manual_seed(0)
w = torch.randn(5, requires_grad=True)
w_manual = w.detach().clone()
v = torch.zeros_like(w_manual)                       # v_0 = 0 (no bias correction)
optimizer = torch.optim.RMSprop([w], lr=1e-2, alpha=0.9)  # alpha=0.9 to match the lecture's example

for t in range(1, 11):
    loss = ((w - 3.0) ** 2).sum()                    # Example: drive w toward 3
    optimizer.zero_grad()
    loss.backward()
    grad = w.grad.detach().clone()
    optimizer.step()
    w_manual, v = rmsprop_step(w_manual, grad, v, lr=1e-2, alpha=0.9)

print(torch.allclose(w.detach(), w_manual, atol=1e-6))  # Should be True


# Use in actual training: centered version with momentum (settings close to Graves, 2013)
model = nn.LSTM(input_size=3, hidden_size=64, batch_first=True)
head = nn.Linear(64, 3)
params = list(model.parameters()) + list(head.parameters())
optimizer = torch.optim.RMSprop(params, lr=1e-4, alpha=0.95, eps=1e-4,
                                momentum=0.9, centered=True)

x = torch.randn(8, 50, 3)                            # Dummy sequences (8 sequences × 50 steps)
y = torch.randn(8, 50, 3)
out, _ = model(x)
loss = nn.functional.mse_loss(head(out), y)
optimizer.zero_grad()
loss.backward()
optimizer.step()

FAQ

Q. What is the original paper for RMSprop?
A.

There is no paper. The source is the slides of Lecture 6e of Hinton's 2012 online course "Neural Networks for Machine Learning", and many papers cite these slides. The lecture introduces it as an unpublished trick by Tieleman.

Q. How does RMSprop differ from Adam?
A.

Both divide by a moving average of squared gradients, but Adam additionally uses a moving average of gradients (momentum) and corrects, with bias correction, the initial bias caused by starting from v0=0v_0 = 0. RMSprop does no correction, so the amount moved is larger in the first few steps.

Q. What value should alpha be?
A.

The lecture's example uses 0.9, and PyTorch's default is 0.99. The closer it is to 1, the longer the period over which gradients are averaged (roughly 1/(1−α)1/(1-\alpha) steps), which stabilizes the denominator but makes it slower to catch up when the gradient magnitude changes. Try the default first and change it if training is unstable.

References

  1. T. Tieleman and G. Hinton, "Neural Networks for Machine Learning, Lecture 6e: rmsprop: Divide the gradient by a running average of its recent magnitude," Coursera, 2012.
  2. A. Graves, "Generating Sequences With Recurrent Neural Networks," arXiv:1308.0850, 2013.
  3. L. Liu, H. Jiang, P. He, W. Chen, X. Liu, J. Gao, and J. Han, "On the Variance of the Adaptive Learning Rate and Beyond," ICLR, 2020.
  4. PyTorch Documentation, "torch.optim.RMSprop."