Optimization: Comparing SGD, Momentum and Adam on a Valley and MNIST, with Warmup and Clipping

Sunhong··16 min read·0 views·Translated from Korean

Key points of this post

  • SGD steps against the gradient, momentum accumulates the directions of past steps to damp oscillation, and Adam divides each coordinate by its gradient magnitude to even out the step size. On a valley mixing steep and gentle directions (slope ratio 1 to 50), reaching loss below 10−310^{-3} took 127 steps for SGD, 69 for momentum and 61 for Adam.
  • Sweeping the learning rate on an MNIST network, SGD did best near 0.3 and Adam at 0.001 to 0.01; with each method at its own learning rate for 8 epochs, test accuracy was nearly the same, 97.2 to 97.7%. Tuning the learning rate matters more than the choice of method.
  • Learning rate schedules (warmup, cosine decay) and gradient clipping let you use a large learning rate safely. On an 8-hidden-layer network, momentum SGD at 0.3 diverged without clipping (accuracy 10.1%) but reached 95.5% with the norm clipped to 1.0, and Adam at 0.01 went from 93.9% to 95.5% with warmup.

This is the fourth post in the AI Note series. In part 1 we said learning means reducing a loss by gradient descent, in part 2 we computed that gradient with backpropagation, and in part 3 we saw how to choose the loss by maximum likelihood. Now we have a loss and a gradient. The remaining question is how to move the weights given the gradient. The gradient descent of part 1 was just "go against the gradient by learning rate times gradient", and in real training this simple rule is often slow or unstable. This post follows SGD, momentum and Adam by hand on the same small valley, measures how sensitive they are to the learning rate on an MNIST network, and finally checks why learning rate schedules, warmup and gradient clipping are needed.

1. Why plain gradient descent is not enough

If the loss is equally steep in every direction of the weights, gradient descent works well. But a neural network's loss is not like that: steep in some directions and gentle in others. In this post we use the simplest shape that has this property, a loss in two weights,

L(x,y)=12(x2+50 y2)L(x, y) = \tfrac{1}{2}\left(x^2 + 50\,y^2\right)

The xx direction is gentle (∂L/∂x=x\partial L/\partial x = x) and the yy direction is 50 times steeper (∂L/∂y=50y\partial L/\partial y = 50y). The minimum is at (0,0)(0, 0). Let us start from (4,1)(4, 1). In a long narrow valley like this, gradient descent has two things holding each other back: a large learning rate makes the steep yy direction bounce out, and a small one makes progress along the gentle xx direction very slow.

2. SGD: the basic form and the learning rate limit

SGD (stochastic gradient descent) is the gradient descent of part 1. "Stochastic" means the gradient is computed on one minibatch rather than on all the data (section 7 of part 2). One step is

w←w−η gw \leftarrow w - \eta\, g

where ww is the weights, gg the gradient and η\eta the learning rate. Let us take three steps in the valley with η=0.035\eta = 0.035.

Step Gradient (x, 50y)(x,\ 50y) xx yy
0 (start) 4 1
1 (4, 50) 4−0.035×4=4 - 0.035 \times 4 = 3.86 1−0.035×50=1 - 0.035 \times 50 = −0.75
2 (3.86, −37.5) 3.725 0.5625
3 (3.725, 28.1) 3.595 −0.4219

yy is multiplied by −0.75 every step, shrinking while flipping sign (it swings back and forth), and xx shrinks by only 3.5% (=1−0.035= 1 - 0.035) per step. The reason is clear from the formula. The yy direction is y←(1−50η) yy \leftarrow (1 - 50\eta)\,y, so we need ∣1−50η∣<1|1 - 50\eta| < 1 to converge, which requires η<2/50=0.04\eta < 2/50 = 0.04. So the learning rate is set by the steepest direction. With an upper limit of 0.04, the gentle xx shrinks by a factor of 1−η1 - \eta per step, at most about 4%. Getting the loss below 10−310^{-3} took 127 steps. The larger the ratio of steepness (the condition number), the worse this problem gets.

3. Momentum: accumulate the direction

Picture a ball rolling down the valley. If it keeps going the same way it gains speed, and the sideways kicks cancel out. Momentum imitates this by keeping a separate velocity vv.

v←βv+g,w←w−η vv \leftarrow \beta v + g, \qquad w \leftarrow w - \eta\, v

β\beta (usually 0.9) is how much of the old velocity to keep. In words: "go with the current gradient mixed with β\beta times the velocity of the last step". With β=0.9\beta = 0.9, gradients in the same direction pile up and the step can grow up to 1/(1−β)=101/(1-\beta) = 10 times. In the same valley, take two steps with η=0.008\eta = 0.008 and β=0.9\beta = 0.9.

Step Gradient Velocity v=0.9 vprev+gv = 0.9\,v_{\text{prev}} + g xx yy
1 (4, 50) (4, 50) 4−0.008×4=4 - 0.008 \times 4 = 3.968 1−0.008×50=1 - 0.008 \times 50 = 0.6
2 (3.968, 30) 0.9×(4,50)+(3.968,30)=0.9 \times (4, 50) + (3.968, 30) = (7.568, 75) 3.9075 0.0

The first step is the same as SGD, but at the second step the yy velocity is 0.9×50+30=750.9 \times 50 + 30 = 75: the direction of the previous step remains. Conversely, once yy starts to oscillate in sign, the sum of velocities cancels and shrinks. In the gentle xx direction the gradient keeps the same sign and accumulates, so speed builds up. It arrived below 10−310^{-3} in 69 steps, almost half of SGD.

(The momentum in this post is the formula of PyTorch SGD(momentum=0.9). Some papers use a variant that multiplies the gradient by (1−β)(1-\beta); only the scale of the learning rate differs.)

4. Adam: match the size per coordinate

Momentum refines the direction. Adam goes one step further and evens out the step size per coordinate. The gradient is large in steep directions and small in gentle ones, so it divides by a moving average of each weight's gradient magnitude, letting every coordinate move at a similar pace. The formula is four lines (tt is the step number).

m←β1m+(1−β1) g,s←β2s+(1−β2) g2m \leftarrow \beta_1 m + (1-\beta_1)\,g, \qquad s \leftarrow \beta_2 s + (1-\beta_2)\,g^2 m^=m1−β1t,s^=s1−β2t,w←w−η m^s^+ϵ\hat m = \frac{m}{1-\beta_1^t}, \quad \hat s = \frac{s}{1-\beta_2^t}, \qquad w \leftarrow w - \eta\,\frac{\hat m}{\sqrt{\hat s} + \epsilon}

mm is a moving average of the gradient (the momentum role) and ss a moving average of the squared gradient (a magnitude estimate). The defaults are β1=0.9\beta_1 = 0.9, β2=0.999\beta_2 = 0.999, ϵ=10−8\epsilon = 10^{-8}. The divisions in the second line are the bias correction. At the start mm and ss begin at 0 and come out smaller than the truth, so we divide by 1−βt1 - \beta^t to fix that.

Let us do the first step by hand. At t=1t = 1, m=0.1 gm = 0.1\,g and s=0.001 g2s = 0.001\,g^2, and after correction m^=g\hat m = g, s^=g2\hat s = g^2, so the step is η⋅g/∣g∣=η⋅sign(g)\eta \cdot g / |g| = \eta\cdot\text{sign}(g). Even with gradient (4, 50), with η=0.3\eta = 0.3 both coordinates move exactly 0.3.

Step xx yy
0 (start) 4 1
1 3.7 0.7
2 3.4008 0.4073
3 3.1032 0.1320

xx with gradient 4 and yy with gradient 50 move at the same pace. It arrived below 10−310^{-3} in 61 steps. There is a downside too. The step size is constant, so with a large learning rate it circles around the minimum (in the figure below the blue path wanders near the origin). That is why the learning rate decay later fits well with it. In practice, AdamW, a variant that applies weight decay separately from the gradient, is widely used (see references).

Trajectories of three methods on the lopsided valley L = 0.5(x² + 50y²). SGD bounces in the y direction and takes 127 steps, momentum oscillates and takes 69, and Adam evens out the coordinates and takes 61 steps to get below loss 1e-3

Correctness check

We checked that the code transcribing the formulas is right. We fed the same gradients for 200 steps to PyTorch's torch.optim.Adam and SGD(momentum=0.9) and to the formulas above written directly in NumPy, and measured how much the weights differ (small linear regression, 64-bit).

Comparison Max weight difference after 200 steps
Hand-written Adam vs torch.optim.Adam 1.6×10−151.6 \times 10^{-15}
Hand-written momentum vs torch.optim.SGD 5.6×10−175.6 \times 10^{-17}

They agree within floating-point error.

5. Experiment 1: sweeping the learning rate on MNIST

Now a real network. We train on 55,000 MNIST images and hold out 5,000 for validation (the 10,000 test images are used only at the end). The network is 784-128-128-10 (ReLU, He initialization) with batch size 128. For each of the three methods we varied the learning rate over 8 values from 0.001 to 3, trained 2 epochs, and measured validation accuracy.

Validation accuracy after 2 epochs by learning rate. SGD peaks at 96.7% at 0.3, momentum gets 97.2% at 0.03 and 0.1, Adam gets 97.2% at 0.001 and 97.3% at 0.003 and collapses to 41.7% at 0.1

Learning rate 0.001 0.01 0.1 0.3 1.0
SGD 67.2% 91.4% 95.6% 96.7% 93.4%
SGD + momentum 91.3% 96.2% 97.2% 96.0% 10.0%
Adam 97.2% 96.8% 41.7% 10.0% 10.0%

Three things can be read off.

  • The location of a good learning rate differs by method. SGD at 0.3, momentum at 0.03 to 0.1 (the effective step is 10x, so smaller), Adam at 0.001 to 0.01. So using one method's learning rate on another fails (Adam at 0.3 gets 10%).
  • Adam is less sensitive at small learning rates. It gets 97.2% even at 0.001, while SGD gets 67.2%. The steps are matched per coordinate, so it is less sensitive to the choice of scale.
  • Everything collapses when the learning rate is too large. Accuracy of 10% (guessing) is the sign.

Here is the result of training 8 epochs with 2 seeds each at the learning rate with the best validation accuracy (SGD 0.3, momentum 0.03, Adam 0.003).

Method Learning rate Test accuracy (2 seeds) Mean
SGD 0.3 97.74%, 97.30% 97.52%
SGD + momentum 0.03 97.73%, 97.61% 97.67%
Adam 0.003 97.32%, 96.98% 97.15%

Training loss during 8 epochs. Adam drops fastest in the first epoch, but near epoch 8 the three methods are almost the same

The honest result is this. On a problem of this size, once the right learning rate is found, the final accuracies of the three methods are almost the same. With 2 seeds we cannot separate differences of around 0.5 points. The visible difference is early speed. In the first epoch (left of the figure) Adam's training loss is lower. The reason Adam is widely used is closer to "the range of learning rates that work when chosen roughly is wide" than to the final score.

6. Learning rate schedules and warmup

Using one learning rate to the end is not the best. It is better to go big early to descend quickly and go small late to polish near the bottom. So we change the learning rate with the step count. The most common is cosine decay. With TT total steps, the learning rate at step tt is

ηt=ηmax⁡⋅12(1+cos⁡πtT)\eta_t = \eta_{\max} \cdot \tfrac{1}{2}\left(1 + \cos\frac{\pi t}{T}\right)

Computing a few points with T=100T = 100:

Step tt 0 25 50 75 100
cos⁡(πt/T)\cos(\pi t / T) 1 0.707 0 −0.707 −1
ηt/ηmax⁡\eta_t / \eta_{\max} 1.000 0.854 0.500 0.146 0

It falls gently at first, drops fastest in the middle, and reaches 0 gently at the end.

Warmup is the opposite: for the first few hundred steps, raise the learning rate from 0 to the target. The reason lies in the instability at the start. The weights are freshly initialized, so gradients are large and rough, and for Adam the magnitude estimate ss is built from only a few steps of data and cannot be trusted. Going straight to the target learning rate then makes one or two steps jump wildly and bend the learning. Going small at first while statistics accumulate, then growing, avoids it.

Experiment 2: checking on an 8-hidden-layer network

The deeper the network, the more unstable the start. We switched to 8 hidden layers (width 256, 3 epochs). There is one seed, so we only trust divergence or large differences of 1 point or more rather than small differences.

Test accuracy after 3 epochs for an 8-hidden-layer network. Adam at 0.01 gets 93.9% without warmup and 95.5% with 500-step warmup. Momentum SGD at 0.3 diverges to 10.1% without clipping and gets 95.5% with clipping at 1.0. Adam at 0.003 gets 96.9% constant, 97.9% with cosine decay, 98.0% with warmup plus cosine

  • Adam at learning rate 0.01 gets 93.9% without warmup and 95.5% with a 500-step warmup. The maximum gradient norm during training also dropped from 91.1 to 12.0, and the final training loss from 0.306 to 0.222.
  • With Adam at 0.003, a constant learning rate gets 96.9%, cosine decay 97.9%, and adding a 200-step warmup 98.0%. The 1-point gain of cosine over constant is worth reading, but the difference between 98.0 and 97.9 means nothing with one seed.

7. Gradient clipping

Sometimes the gradient suddenly becomes explosively large in one step. If that step throws the weights far away, the learning afterwards is ruined. Gradient clipping keeps the direction and shrinks only the length to cc when the whole norm (length) of the gradient exceeds a threshold cc.

g←g⋅min⁡ ⁣(1, c∥g∥)g \leftarrow g \cdot \min\!\left(1,\ \frac{c}{\lVert g \rVert}\right)

By hand: if g=(3,4)g = (3, 4) then ∥g∥=5\lVert g \rVert = 5, and with c=1c = 1 we get g⋅(1/5)=(0.6,0.8)g \cdot (1/5) = (0.6, 0.8), the direction unchanged and the length now 1. If ∥g∥≤c\lVert g \rVert \le c it is left alone. It is a safety device that limits the step size only at steps with large gradients, and it rarely triggers otherwise.

The second group of the experiment above is an example. Running momentum SGD at learning rate 0.3 (too large for this network), the training loss climbed to 103010^{30}, the gradient norm went to infinity, and accuracy after 3 epochs was 10.1% (guessing). With the same setting and clipping at norm 1.0, it learned to 95.5%. Clipping did not lower the learning rate; it only cut the exploding steps. The maximum norm before clipping was 15.1, so 1.0 triggered quite often. The typical places that need such a device are recurrent networks and transformers, which we meet again in later posts.

The setup is the CPU of a MacBook Pro M1 Max (4 threads), PyTorch 2.15.0, NumPy 2.5.4, Python 3.12.13. The learning rate sweep (24 runs x 2 epochs) took 16 seconds, the 8-epoch comparison (6 runs) 19 seconds, the 8-layer experiment (7 runs x 3 epochs) 49 seconds, 87 seconds in all. These times were measured while the Mac was shared with other jobs. To save time we made the networks small (hidden width 128 to 256) and cut the epochs to 2 to 8. This is very different in scale from real large-model training (hundreds of billions of steps, where AdamW with a cosine schedule, warmup and clipping together is standard), and the comparisons in this post are limited to this small setting.

8. Summary

  • SGD's learning rate is tied to the steepest direction, so the gentle direction is slow (127 steps in the valley). Momentum accumulates past directions to reduce oscillation (69 steps). Adam evens out the step size per coordinate (61 steps).
  • The location of a good learning rate differs by method. On the MNIST network, SGD 0.3, momentum 0.03 and Adam 0.003 were best, and at their own learning rates the final accuracies were similar, 97.2 to 97.7%.
  • Adam's advantage is being less sensitive to the learning rate choice and fast early on. Our own implementation agrees with torch.optim to the 10−1510^{-15} level.
  • Cosine decay polishes the late phase (96.9% to 97.9%), warmup reduces the instability at the start (Adam 0.01: 93.9% to 95.5%), and gradient clipping cuts only the exploding steps to prevent divergence (10.1% to 95.5%).

Next post: This time we used He initialization as if it were settled. In part 5 we measure, layer by layer, how initialization sets the size of activations and gradients as they pass through layers, what happens when it is wrong, and how batch normalization (BN) and layer normalization (LN) solve the problem.

References

Similar posts