AI Logic

Optimizers

AdaGrad

Updated:

How AdaGrad works. The left shows one step: squared gradients are accumulated, and parameters are updated with a per-parameter step size divided by the square root of that sum. The right compares trajectories on loss contours: gradient descent with a single learning rate zigzags, while AdaGrad heads straight to the bottom of the valley

Background and overview

AdaGrad (Adaptive Gradient) is an optimizer that keeps, for each parameter, the sum of all squared gradients so far and divides by its square root to set the step size. Parameters that receive gradients often take small steps, and parameters that rarely receive gradients move with large steps. Duchi, Hazan, and Singer published it in JMLR in 2011 (a preliminary version appeared at COLT 2010).

SGD moves all parameters with the same learning rate. But in data such as text classification, with millions of feature dimensions of which only a few are nonzero in any one example (sparse data), the rarest features are often the most decisive. With a single global learning rate, setting it small to suit frequent features leaves the weights of rare features barely trained.

The paper likens this situation to "finding needles in haystacks" and proposes AdaGrad as a way to vary the learning rate per feature so that the learner "takes notice" when a rare feature appears. It applies, automatically and on the learning-rate side, the same idea as the long-standing TF-IDF (a text feature that gives rarer words larger weights).

AdaGrad's idea of "dividing by squared gradients to vary the step size per parameter" was inherited by later methods such as RMSprop and Adam.

Theory (one step of computation)

The diagonal version of AdaGrad, which is central to the paper, performs the following computation at each training step tt (Eqs. (1) and (5) of the paper, unconstrained case). The computation is done separately for each parameter component ii.

  1. Compute the gradient gtg_t on a mini-batch (a single example in the paper).
  2. Add the square of each gradient component to the running sum. It starts from G0,i=0G_{0,i} = 0. Gt,i=Gt−1,i+gt,i2=∑τ=1tgτ,i2G_{t,i} = G_{t-1,i} + g_{t,i}^2 = \sum_{\tau=1}^{t} g_{\tau,i}^2
  3. Update the parameters with a step size divided by the square root of the sum. η\eta is the global learning rate and δ≥0\delta \ge 0 is a small value that prevents division by zero. θt+1,i=θt,i−ηδ+Gt,i gt,i\theta_{t+1,i} = \theta_{t,i} - \frac{\eta}{\delta + \sqrt{G_{t,i}}}\, g_{t,i}

In matrix form, only the diagonal of the sum of gradient outer products Gt=∑τ=1tgτgτ⊤G_t = \sum_{\tau=1}^{t} g_\tau g_\tau^\top is used, giving θt+1=θt−η diag(Gt)−1/2gt\theta_{t+1} = \theta_t - \eta\, \mathrm{diag}(G_t)^{-1/2} g_t. The paper also presents a version that uses the full matrix (dividing by Gt1/2G_t^{1/2}), but computing a matrix square root is too expensive when the dimension dd is large, so the diagonal version is used in practice.

The step size η/Gt,i\eta / \sqrt{G_{t,i}} in step 3 is determined by the total magnitude of the gradients that parameter ii has received so far. The more often a component receives gradients, the faster its sum grows and the smaller its step size becomes. Components that rarely receive gradients keep a small sum, so they can move a lot when a gradient does arrive. The right side of the figure at the top shows a valley that is steep vertically (θ2\theta_2) and gentle horizontally (θ1\theta_1): gradient descent with a single learning rate zigzags, while AdaGrad equalizes the step size per component and heads straight to the bottom of the valley.

Why it is strong on sparse data

The paper guarantees AdaGrad's performance in terms of regret in online learning (a setting where data arrive one at a time while learning): the difference between the total loss incurred while learning and the total loss of the single best weight chosen in hindsight. The regret of the diagonal version is bounded as follows.

R(T)=O ⁣(∥x∗∥∞∑i=1d∥g1:T,i∥2)R(T) = O\!\left( \lVert x^* \rVert_\infty \sum_{i=1}^{d} \lVert g_{1:T,i} \rVert_2 \right)

∥g1:T,i∥2\lVert g_{1:T,i} \rVert_2 is the length of the sequence of component ii's gradients over TT steps. For components that rarely receive gradients, this value is small. In other words, the sparser the data, the smaller the guaranteed regret.

As a concrete example, the paper considers sparse data in which feature ii appears with probability pi∝i−αp_i \propto i^{-\alpha} (a few features are frequent and most are rare). In this case, the regret of ordinary online gradient descent is O(dT)O(\sqrt{dT}), whereas AdaGrad achieves O(log⁡d⋅T)O(\log d \cdot \sqrt{T}) when α≥2\alpha \ge 2, an exponentially smaller dependence on the dimension dd.

The paper also constructs a sequence in which one feature is seen many times and then other features appear once each. Ordinary gradient descent, whose learning rate η/t\eta/\sqrt{t} has become too small, can barely learn the new features, while AdaGrad classifies correctly after seeing each feature only once. From this result the paper argues that "using a single global learning rate is unreasonable compared with keeping a learning rate per feature."

Experimental results

The paper compared AdaGrad with conventional methods that do not adapt the learning rate (RDA, FOBOS, and others) in a setting where data arrive one at a time and the training data are passed through only once.

Test error rates on four top-level categories of text classification (Reuters RCV1, about 800,000 articles, about 2 million bigram features), with hinge loss and ℓ1\ell_1 regularization:

CategoryRDAAdaGrad (RDA version)FOBOSAdaGrad (FOBOS version)
ECAT0.0510.0440.0580.044
CCAT0.0640.0530.1110.053
GCAT0.0460.0400.0560.040
MCAT0.0370.0350.0560.034

Test accuracy on image ranking over 15,000 ImageNet classes (a ranking learned for each class):

MethodAverage precisionP@1P@5
AdaGrad (RDA version)0.60220.85020.8130
AROW0.58130.85970.8165
PA0.55810.84550.7957
RDA0.50420.74960.6950
  • In text classification, the error rate dropped in every category: simply switching the step size to AdaGrad within the same frameworks (RDA and FOBOS) lowered the error rate. The paper reports that the adaptive methods outperformed the non-adaptive ones in every RCV1 experiment.
  • In image ranking, average precision was the highest: AROW was slightly better in top-1 precision (P@1), but AdaGrad had the highest average precision.

These are results for convex linear models. Performance on deep learning models was not studied in this paper.

Practical caveats

The learning rate keeps decreasing monotonically, and in long training runs learning can stall. Because Gt,iG_{t,i} only keeps accumulating squared gradients and never decreases, the step size η/Gt,i\eta/\sqrt{G_{t,i}} only shrinks. In convex problems this guarantees convergence, but in problems like deep learning, where training is long and the loss landscape changes along the way, parameters may barely move late in training. RMSprop eases this problem by using an exponential moving average instead of the sum of squares, and Adam inherits this idea.

In PyTorch, use torch.optim.Adagrad. The procedure in the official documentation is the paper's diagonal version plus learning rate decay and L2 regularization.

ArgumentMeaningDefault
lrGlobal learning rate η\eta0.01
lr_decayLowers the learning rate at each step to η/(1+(t−1) d)\eta/(1+(t-1)\,d) (dd is this value)0
weight_decayStrength of L2 regularization that adds λθ\lambda\theta to the gradient0
initial_accumulator_valueInitial value of the sum of squares G0,iG_{0,i}0
epsSmall value added to the denominator (corresponds to the paper's δ\delta)10−1010^{-10}
  • eps is added outside the square root: PyTorch's update is θ←θ−γ g/(G+ϵ)\theta \leftarrow \theta - \gamma\, g / (\sqrt{G} + \epsilon), the same form as the paper's δ+G\delta + \sqrt{G}.
  • weight_decay acts as L2 regularization: the λθ\lambda\theta added to the gradient is also divided by G\sqrt{G}, so the amount of shrinkage varies from weight to weight, just as the AdamW paper pointed out for Adam. The AdamW paper states that the same result is expected to apply to AdaGrad.
  • It handles sparse gradients directly: Adagrad can perform updates even when gradients are sparse tensors, as when training word embeddings with nn.Embedding(..., sparse=True). Sparse gradients cannot be combined with weight_decay, however.
  • Start with a relatively large learning rate: since the step size shrinks automatically, start from a larger learning rate than for SGD (such as the default 0.01).

Comparison with other optimizers

The table lists AdaGrad and later methods that vary the step size per parameter from the same viewpoints.

MethodQuantity that sets the step sizeHow the step size changesAverage of gradients (momentum)Suitable problems
SGDNone (one global learning rate)Set by a scheduleNot used (momentum can be added)CNNs for image classification, etc.
AdaGradSum of squared gradientsDecreases monotonicallyNot usedLinear models with many sparse features, convex problems
RMSpropExponential moving average of squared gradientsRises and falls with recent gradientsNot usedProblems whose loss landscape changes
AdamExponential moving average of squared gradientsRises and fallsUsedMost deep learning models

A rough guide for choosing:

  • For linear models with many sparse features, or convex problems, use AdaGrad: it learns rare features quickly and comes with theoretical guarantees.
  • For deep learning models, use later methods such as Adam: because AdaGrad's learning rate keeps shrinking, Adam or RMSprop is often easier to work with in long training runs.
  • When sparse gradients update only some parameters, as in word embeddings, AdaGrad is also a candidate: rarer words can be moved by larger amounts.

PyTorch example

Show code
python
import torch
import torch.nn as nn


# One step of AdaGrad (diagonal version), written exactly as in the paper's equations
def adagrad_step(theta, grad, state_sum, lr=1e-2, eps=1e-10):
    state_sum = state_sum + grad ** 2                  # keep adding squared gradients (never decreases)
    theta = theta - lr * grad / (state_sum.sqrt() + eps)  # update with a per-parameter step size
    return theta, state_sum


# Check that it gives the same result as PyTorch's Adagrad
torch.manual_seed(0)
w = torch.randn(5, requires_grad=True)
w_manual = w.detach().clone()
state_sum = torch.zeros_like(w_manual)
optimizer = torch.optim.Adagrad([w], lr=0.1)

for t in range(1, 11):
    loss = ((w - 3.0) ** 2).sum()                     # example: move toward 3
    optimizer.zero_grad()
    loss.backward()
    grad = w.grad.detach().clone()
    optimizer.step()
    w_manual, state_sum = adagrad_step(w_manual, grad, state_sum, lr=0.1)

print(torch.allclose(w.detach(), w_manual, atol=1e-6))  # should be True
print(0.1 / state_sum.sqrt())                         # actual step size; shrinks with every step


# Using sparse gradients: word embeddings (rarer words move more)
vocab_size, dim = 10000, 64
embedding = nn.Embedding(vocab_size, dim, sparse=True)   # returns gradients as sparse tensors
classifier = nn.Linear(dim, 2)
opt_sparse = torch.optim.Adagrad(embedding.parameters(), lr=0.1)  # weight_decay cannot be used with sparse gradients
opt_dense = torch.optim.Adagrad(classifier.parameters(), lr=0.1, weight_decay=1e-4)

tokens = torch.randint(0, vocab_size, (32, 20))           # dummy sentences (32 sentences × 20 words)
labels = torch.randint(0, 2, (32,))
logits = classifier(embedding(tokens).mean(dim=1))
loss = nn.functional.cross_entropy(logits, labels)
opt_sparse.zero_grad()
opt_dense.zero_grad()
loss.backward()
opt_sparse.step()
opt_dense.step()

FAQ

Q. How do AdaGrad and Adam differ?
A.

AdaGrad keeps summing squared gradients, so its step size decreases monotonically. Adam uses an exponential moving average of squared gradients, so its step size rises and falls with recent gradients. Adam also uses the average of gradients (momentum). In deep learning Adam is often easier to work with, but for linear models with sparse features AdaGrad remains a strong option.

Q. The loss stopped decreasing partway through training. What should I do?
A.

AdaGrad's step size η/Gt\eta/\sqrt{G_t} keeps shrinking, so long training runs can stall. Consider increasing the learning rate lr, or switching to RMSprop or Adam, which use a moving average instead of the sum of squares.

Q. What is initial_accumulator_value for?
A.

It is the initial value of the sum of squares G0G_0. With the default of 0, the first step size is η\eta regardless of the gradient's magnitude (because g/g2=±1g/\sqrt{g^2} = \pm 1). Setting the initial value to something like 0.1 dampens the step size for the first few steps.

References

  1. J. Duchi, E. Hazan, and Y. Singer, "Adaptive Subgradient Methods for Online Learning and Stochastic Optimization," Journal of Machine Learning Research, vol. 12, pp. 2121–2159, 2011.
  2. I. Loshchilov and F. Hutter, "Decoupled Weight Decay Regularization," ICLR, 2019.
  3. PyTorch Documentation, "torch.optim.Adagrad."