AI Logic

Optimizers

SGD (Stochastic Gradient Descent)

Updated:

How SGD works. The left side shows one step: choose a mini-batch, compute the gradient, and move the parameters opposite to the gradient. The right side compares, on loss contours, the trajectory of gradient descent using the gradient over all data with that of SGD using noisy mini-batch gradients

Background and Overview

SGD (stochastic gradient descent) is an optimizer that repeatedly computes the gradient of the loss on a randomly chosen subset of the training data (a mini-batch) and moves the parameters a little in the opposite direction. Almost every optimizer in deep learning is SGD with additional tricks.

Gradient descent uses the gradient of the loss over the entire training set. But with millions of examples, computing over all of them for every update is far too expensive. SGD uses the gradient computed on a mini-batch as "an estimate of the full gradient", making each computation cheaper in exchange for more updates. The estimate contains error (noise), but on average it points in the right direction, so the loss can be lowered little by little.

As an analogy, instead of asking everyone in the country to learn public opinion, you ask about 100 people each time and adjust course little by little. Even if each survey is biased, repeated surveys bring you closer to the right direction.

This idea originates in the stochastic approximation method of Robbins and Monro (1951). For a situation where the form of the mean function M(x)M(x) is unknown and only noisy observations yny_n are available, they gave the following update as a way to find xx such that M(x)=αM(x) = \alpha (Eq. (7) in the paper).

xn+1=xn+an(α−yn)x_{n+1} = x_n + a_n(\alpha - y_n)

Treating M(x)M(x) as the gradient of the loss and α\alpha as 0 gives the form of SGD: "find the point where the gradient is 0 using only noisy gradients" (Bottou et al., 2018).

Theory (One Step of the Computation)

At each training step tt, SGD performs the following computation.

  1. Randomly choose a mini-batch BtB_t from the training data.
  2. Compute the gradient of the mean loss over the mini-batch with backpropagation. ℓi\ell_i is the loss of the ii-th example. gt=1∣Bt∣∑i∈Bt∇ℓi(θt−1)g_t = \frac{1}{|B_t|} \sum_{i \in B_t} \nabla \ell_i(\theta_{t-1})
  3. Move the parameters in the opposite direction of the gradient, scaled by the learning rate ηt\eta_t. θt=θt−1−ηt gt\theta_t = \theta_{t-1} - \eta_t\, g_t

The size of the mini-batch ∣Bt∣|B_t| is called the batch size. Updating one example at a time (∣Bt∣=1|B_t| = 1) is sometimes called SGD and using several examples mini-batch SGD, but in deep learning it is common to call both SGD, including the mini-batch case.

Robbins and Monro showed that if the sequence of step sizes ana_n (corresponding to SGD's ηt\eta_t) satisfies the following two conditions, xnx_n converges to the target point even with noise (Eqs. (6) and (26) in the paper). an=1/na_n = 1/n is an example that satisfies both.

∑n=1∞an=∞,∑n=1∞an2<∞\sum_{n=1}^{\infty} a_n = \infty, \qquad \sum_{n=1}^{\infty} a_n^2 < \infty

The first condition, "the sum of step sizes is infinite", guarantees that the target point can be reached however far away it starts. The second condition, "the sum of squared step sizes is finite", guarantees that the accumulated drift due to noise eventually becomes small. Keeping the step size constant violates the second condition, so it keeps oscillating near the minimum. Lowering the learning rate with a learning rate scheduler in deep learning is partly meant to suppress this oscillation.

SGD in PyTorch (Momentum, Nesterov, Weight Decay)

PyTorch's torch.optim.SGD lets three things be added to plain SGD: momentum, Nesterov momentum, and weight decay. The procedure in the official documentation is as follows. γ\gamma is the learning rate (lr), λ\lambda is weight_decay, μ\mu is momentum, and τ\tau is dampening.

  1. Compute the gradient gt=∇θft(θt−1)g_t = \nabla_\theta f_t(\theta_{t-1}).
  2. If λ≠0\lambda \neq 0, add λθt−1\lambda\theta_{t-1} to the gradient (L2 regularization). gt←gt+λ θt−1g_t \leftarrow g_t + \lambda\,\theta_{t-1}
  3. If μ≠0\mu \neq 0, update the momentum buffer btb_t. Only at the first step, b1=g1b_1 = g_1. bt=μ bt−1+(1−τ) gtb_t = \mu\, b_{t-1} + (1-\tau)\, g_t
  4. If nesterov=True, set gt←gt+μ btg_t \leftarrow g_t + \mu\, b_t; otherwise set gt←btg_t \leftarrow b_t.
  5. Update the parameters. θt=θt−1−γ gt\theta_t = \theta_{t-1} - \gamma\, g_t

The meanings and default values of the arguments are as follows.

ArgumentMeaningDefault
lrLearning rate γ\gamma0.001
momentumHow much of past update directions to keep (μ\mu). 0 means plain SGD0
dampeningFraction by which a new gradient is weakened when added to the momentum (τ\tau)0
weight_decayStrength of L2 regularization added to the gradient (λ\lambda)0
nesterovWhether to use Nesterov momentumFalse

Momentum accumulates past gradients to stabilize the update direction. Like a ball rolling down a slope keeping its speed, it cancels the small fluctuations from each mini-batch and moves quickly along the valley floor. Nesterov momentum is a variant that uses, ahead of time, the gradient at the point reached by the momentum.

PyTorch's momentum is written slightly differently from the equations in Sutskever et al. (2013) and others. PyTorch uses bt=μbt−1+gtb_t = \mu b_{t-1} + g_t and θt=θt−1−γbt\theta_t = \theta_{t-1} - \gamma b_t, applying the learning rate outside the buffer. Some other frameworks use vt=μvt−1+γgtv_t = \mu v_{t-1} + \gamma g_t and θt=θt−1−vt\theta_t = \theta_{t-1} - v_t, applying it inside. With a constant learning rate the updates are the same, but they differ in that changing the learning rate mid-training also shrinks the past momentum by the new learning rate. Be careful when porting settings from other frameworks. Also, nesterov=True can only be used when momentum is greater than 0 and dampening is 0 (otherwise it raises an error).

weight_decay is L2 regularization that adds λθ\lambda\theta to the gradient. In plain SGD without momentum, this gives the same update as Weight Decay, which shrinks the weights by a fixed fraction at every update (Proposition 1 of Loshchilov and Hutter, 2019).

Why Training Works with Mini-Batch Gradients

Because mini-batches are chosen at random, the expected value of the mini-batch gradient gtg_t equals the gradient over the whole training set. Each individual direction is off, but on average it points the right way. The right side of the figure at the top compares descending the same loss valley with the exact gradient over all data (gradient descent) and with noisy mini-batch gradients (SGD). The SGD trajectory wobbles, but it heads toward the same valley floor.

Bottou et al. (2018) explain in terms of computational cost why SGD has the advantage when the number of examples nn is large.

  • The cost of one update does not depend on the number of examples: gradient descent needs gradient computations for nn examples per update. SGD only needs those for the mini-batch.
  • It wins on total cost to reach a target accuracy: gradient descent lowers the loss geometrically fast (O(ρk)O(\rho^k)), but its total cost is proportional to nlog⁡(1/ϵ)n \log(1/\epsilon). SGD lowers the loss slowly at O(1/k)O(1/k), but its total cost is proportional to 1/ϵ1/\epsilon and does not depend on nn. The larger nn and the more limited the compute time, the more SGD is favored.
  • The loss on unseen data decreases at the same rate: when new data can keep being drawn, SGD lowers not only the training loss but also the expected loss that we really want to lower (the average loss on unseen data) at the same O(1/k)O(1/k).
MethodCost per updateHow the loss decreasesTotal cost to accuracy ϵ\epsilon
Gradient descent (all data)Proportional to nnO(ρk)O(\rho^k) (0<ρ<10<\rho<1)Proportional to nlog⁡(1/ϵ)n \log(1/\epsilon)
SGDIndependent of nnO(1/k)O(1/k)Proportional to 1/ϵ1/\epsilon

The rates and costs in the table hold under assumptions such as the loss being strongly convex (a single valley curving in every direction). Deep learning losses are not convex, but this comparison is widely cited as an explanation of why SGD is used for large-scale data.

Bottou et al. also show that SGD with a constant learning rate does not reach the minimum itself but keeps oscillating once it gets within a region whose size is proportional to the learning rate (Theorem 4.6). Halving the learning rate also halves that region, but it takes twice as many steps to get there.

Practical Considerations

The default of torch.optim.SGD is plain SGD without momentum (momentum=0). When papers on image classification with ResNet and the like say "trained with SGD", they almost always mean with momentum, such as momentum=0.9. When reproducing a paper's setup, match the values of momentum, weight_decay, and nesterov as well.

  • Always choose the learning rate yourself: the best learning rate varies greatly with the model, data, and batch size. Do not rely on the default; try several values and compare how the loss decreases. Too large and the loss diverges; too small and it does not go down.
  • Combine with a schedule that lowers the learning rate: as seen above, a constant learning rate keeps oscillating near the minimum. It is common to lower the learning rate with step decay or cosine annealing.
  • When changing the batch size, revisit the learning rate: multiplying the batch size by kk reduces the number of updates for the same number of epochs to 1/k1/k. So "linear scaling", which also multiplies the learning rate by kk, is commonly used, combined with warmup, which raises the learning rate gradually at the start. However, training becomes unstable with very large batches, so methods such as LARS, which change the learning rate per layer, have been proposed.
  • Using weight_decay with momentum mixes the weight shrinkage into the momentum: the λθ\lambda\theta from weight_decay is added to the gradient, so it also accumulates in the momentum buffer. Loshchilov and Hutter (2019) also proposed SGDW, which decouples the weight shrinkage from the momentum.

Comparison with Other Optimizers

The table lines up SGD and the main optimizers built on it, from the same perspectives.

MethodUses mean of gradients (momentum)Unit at which step size changesExtra memoryTypical use
SGDNoNone (one global rate)NoneSimplest. The theoretical foundation
SGD with momentumYesNoneOne copy of the parametersStandard for image classification CNNs
AdaGradNoPer parameter (sum of past squared gradients)One copy of the parametersLinear models with many sparse features
AdamYesPer parameter (moving average of squared gradients)Two copies of the parametersThe default for many models
AdamWYesPer parameterTwo copies of the parametersThe default for large models such as Transformers
LARSYesPer layer (ratio of weight norm to gradient norm)One copy of the parametersTraining with very large batches

Rough guidelines for choosing:

  • For training image classification CNNs, SGD with momentum is a strong choice: it has been reported to sometimes achieve higher accuracy on unseen data (generalization performance) than adaptive methods such as Adam (Wilson et al., 2017). However, the learning rate and schedule need tuning.
  • To reduce tuning effort or to train Transformers, use Adam or AdamW: they tend to train well even with settings close to the defaults.
  • To save memory, use SGD: it keeps no extra state, so the optimizer needs no memory of its own (momentum adds one copy of the parameters).

PyTorch example

Show code
python
import torch
import torch.nn as nn


# One step of PyTorch's SGD, written exactly as the procedure in the official documentation
def sgd_step(theta, grad, buf, t, lr, momentum=0.0, dampening=0.0,
             weight_decay=0.0, nesterov=False):
    g = grad
    if weight_decay != 0:
        g = g + weight_decay * theta          # L2 regularization (add λθ to the gradient)
    if momentum != 0:
        if t == 1:
            buf = g.clone()                   # At the first step, buffer = gradient
        else:
            buf = momentum * buf + (1 - dampening) * g
        g = g + momentum * buf if nesterov else buf
    theta = theta - lr * g                    # The learning rate is applied outside the buffer
    return theta, buf


# Check that it matches PyTorch's SGD
torch.manual_seed(0)
w = torch.randn(5, requires_grad=True)
w_manual = w.detach().clone()
buf = None
optimizer = torch.optim.SGD([w], lr=0.1, momentum=0.9, weight_decay=1e-4, nesterov=True)

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, buf = sgd_step(w_manual, grad, buf, t, lr=0.1, momentum=0.9,
                             weight_decay=1e-4, nesterov=True)

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


# Use in actual training: SGD with momentum + a schedule that lowers the learning rate
model = nn.Sequential(nn.Flatten(), nn.Linear(28 * 28, 256), nn.ReLU(), nn.Linear(256, 10))
optimizer = torch.optim.SGD(model.parameters(), lr=0.1, momentum=0.9, weight_decay=5e-4)
scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=100)  # Lower the learning rate over 100 epochs
criterion = nn.CrossEntropyLoss()

for epoch in range(2):                        # Only 2 epochs as an example
    images = torch.randn(64, 1, 28, 28)        # Dummy mini-batch
    labels = torch.randint(0, 10, (64,))
    optimizer.zero_grad()
    loss = criterion(model(images), labels)
    loss.backward()
    optimizer.step()
    scheduler.step()                           # Update the learning rate at the end of each epoch

FAQ

Q. How does SGD differ from gradient descent?
A.

They differ in how much data is used to compute the gradient. Gradient descent computes the gradient over the entire training set, while SGD computes it only on a randomly chosen mini-batch. SGD makes each computation cheaper at the cost of noise in the gradient, but on average it points in the right direction, so it can lower the loss little by little.

Q. Should momentum be added?
A.

In deep learning, momentum=0.9 or thereabouts is added in almost all cases, because it cancels the fluctuations from each mini-batch and moves quickly along the valley floor. PyTorch's default is momentum=0 (no momentum), so specify it explicitly.

Q. How should the learning rate be chosen?
A.

It varies greatly with the model and batch size, so try values a few times apart, such as 0.1, 0.03, and 0.01, and compare how the loss decreases. Linear scaling, which multiplies the learning rate by kk when the batch size is multiplied by kk, is a useful guideline, but for large changes combine it with warmup.

References

  1. H. Robbins and S. Monro, "A Stochastic Approximation Method," The Annals of Mathematical Statistics, vol. 22, no. 3, pp. 400–407, 1951.
  2. L. Bottou, F. E. Curtis, and J. Nocedal, "Optimization Methods for Large-Scale Machine Learning," SIAM Review, vol. 60, no. 2, 2018.
  3. I. Loshchilov and F. Hutter, "Decoupled Weight Decay Regularization," ICLR, 2019.
  4. A. C. Wilson, R. Roelofs, M. Stern, N. Srebro, and B. Recht, "The Marginal Value of Adaptive Gradient Methods in Machine Learning," NeurIPS, 2017.
  5. PyTorch Documentation, "torch.optim.SGD."