Gradient Descent (SGD, Momentum, Adam)
Curvature sets the largest learning rate that works. Why plain descent bounces, what momentum keeps, and how Adam rescales every parameter.
Jump to a section
One weight, two learning rates
Take the loss , start at , and take one gradient step. The derivative is . With learning rate 0.1 the weight moves to 1.4 and the loss falls from 1 to 0.04. With learning rate 0.3 it moves to 2.2 and the loss rises to 1.96. Same gradient, same starting point, opposite outcomes.
Gradient descent applies that rule to every parameter at once:
The gradient says which way is downhill from where the parameters stand. The learning rate says how far to trust that local information. Momentum, Adam and every learning-rate schedule are different answers to the second question.
Follow the gradient back to one weight
Read the forward calculation, trace its local derivatives backward, then see what one update actually does.
Reduced motion is on. Use Previous and Next to inspect each state.
dL/dw = 2(wx − 3) × x = −4
Measure the error
With x = 2, target 3 and w = 1, prediction is 2 and squared loss is 1.
Explore the inputs and calculations
- Prediction wx2Local derivative: x = 2
- Error wx − y-1Target y = 3
- Squared loss1dL/d(error) = -2
Violet is the current weight; green is one update. The connecting segment shows the change, not a continuous optimization trajectory.
Can following the negative gradient increase the loss?
Yes, with a step that is too large. For this exact loss, L(w) = (2w−3)², convergence requires 0 < η < 0.25. At η = 0.25 the error flips sign without shrinking.
Curvature sets the speed limit
The example has an exact answer. The optimum is , and one update maps the error to
The error shrinks exactly when , that is, when . At one step lands on the optimum. At 0.25 the error flips sign without shrinking. At 0.3 it grows by a factor of 1.4 every step, and ten steps take the loss from 1 to about 837.
The 8 is the loss's second derivative, its curvature. For any quadratic, a step is stable when , where is the curvature in the direction of the step. Steep directions demand small steps.
Real losses curve differently in different directions. Near a minimum, each eigenvector of the Hessian with eigenvalue gets its own factor , and one learning rate has to serve all of them. The steepest direction caps it below , so the flattest direction moves slowly.
Take curvatures of 100 and 1. The best single learning rate, , shrinks the error along both directions by a factor of per step, so reducing it a hundredfold takes 231 steps. The one-dimensional problem took one. The ratio , the condition number, is what makes plain gradient descent slow, and it is the problem momentum and Adam attack.
1def step(w, lr):
2 return w - lr * (8 * w - 12) # dL/dw for L = (2w - 3)^2
3
4
5def loss(w):
6 return (2 * w - 3) ** 2
7
8
9assert abs(loss(step(1.0, 0.1)) - 0.04) < 1e-12
10assert abs(loss(step(1.0, 0.3)) - 1.96) < 1e-12
11assert step(1.0, 0.125) == 1.5 # one step to the optimum
12
13w = 1.0
14for _ in range(10):
15 w = step(w, 0.3)
16assert round(loss(w)) == 837 # 1.4 ** 20
17
18# Two directions with curvature 100 and 1: L = (100 x^2 + y^2) / 2
19x, y, lr, steps = 1.0, 1.0, 2 / 101, 0
20while max(abs(x), abs(y)) > 0.01:
21 x, y, steps = x - lr * 100 * x, y - lr * y, steps + 1
22assert steps == 231Noisy gradients from mini-batches
The true gradient is an average over every training example. On ImageNet's 1.28 million training images, computing it exactly would make every step cost a full pass over the data. Stochastic gradient descent averages over a small random mini-batch instead: an unbiased estimate of the same quantity at a tiny fraction of the cost.
The price is noise. For independently drawn examples the variance of the mini-batch gradient falls as , so its standard deviation falls as . Quadrupling the batch halves the noise and quadruples the work per step. Larger batches also keep the accelerator busier, until the batch fills it or memory runs out.
Batch size and learning rate move together. Goyal et al. trained ResNet-50 on ImageNet with mini-batches of 8,192 images in one hour, matching the accuracy of the usual 256-image setup, by scaling the learning rate in proportion to the batch size and warming it up gradually at the start. Change one without the other and you are running a different experiment.
Noise also decides how training ends. With a constant learning rate, the iterates keep bouncing around the minimum at a scale set by and the gradient noise. Decaying the rate late in training, with steps or a cosine schedule, is what lets them settle.
Momentum keeps what the gradients agree on
In a narrow valley the gradient points mostly across the valley rather than along it, so plain SGD bounces between the walls while creeping toward the minimum. Momentum keeps a running velocity, with usually 0.9:
Two cases show what that does. A gradient that keeps pointing the same way builds the velocity up to , a step ten times longer. A gradient that alternates sign settles to a velocity of magnitude . Directions where successive gradients agree move about 19 times faster than directions where they cancel, which is what the valley needed.
This form, used by PyTorch, folds the gain of into the step. Switching on momentum 0.9 multiplies the effective step along consistent directions by ten, so a learning rate tuned without momentum has to come down when you add it.
Adam gives every parameter its own step
Momentum still applies one learning rate to every parameter. Below, plain gradient descent, momentum and Adam start from the same point in a valley twenty times steeper across than along.
Adam keeps two running averages per parameter, the mean gradient and the mean squared gradient (a raw second moment, not a centred variance), and corrects both for starting at zero:
The paper's defaults are , and .
Dividing by makes the step independent of the gradient's scale. Multiply a parameter's gradients by 1,000 and both and grow by 1,000, leaving the update unchanged apart from . What sets the step is and how consistently the gradient keeps its sign.
The first step shows why the bias correction exists. After one gradient, and ; corrected, they are exactly and , so every parameter moves by about in the direction of . Without the correction the step would be times larger, because starts out more heavily biased toward zero than . The correction removes a startup distortion; it does not simply enlarge updates.
Adam's two averages cost two extra values per parameter. For a 7-billion-parameter model with fp32 optimizer state, that is 56 GB before the weights and gradients are counted.
Weight decay needs care. Added as an L2 term to the loss, the decay gradient is divided by like everything else, so parameters with a history of large gradients are barely decayed. AdamW, from Loshchilov and Hutter, applies the decay to the weights directly, outside the adaptive step, and is the usual choice for training transformers.
In code
Both updates written out with in-place PyTorch operations. Momentum is two lines. Adam's bias correction uses the step count t, which is why the optimizer has to count steps.
1import torch
2from torch import Tensor
3
4
5@torch.no_grad()
6def sgd_momentum_step(p: Tensor, grad: Tensor, v: Tensor, lr=0.01, beta=0.9) -> Tensor:
7 v.mul_(beta).add_(grad) # v = beta*v + grad
8 p.add_(v, alpha=-lr) # p = p - lr*v
9 return v
10
11
12class Adam:
13 """Dense-gradient example; all parameters are expected to update each step."""
14 def __init__(self, params, lr=1e-3, betas=(0.9, 0.999), eps=1e-8):
15 self.params = list(params)
16 self.lr, (self.b1, self.b2), self.eps = lr, betas, eps
17 self.m = [torch.zeros_like(p) for p in self.params]
18 self.v = [torch.zeros_like(p) for p in self.params]
19 self.t = 0
20
21 @torch.no_grad()
22 def step(self):
23 self.t += 1
24 for i, p in enumerate(self.params):
25 g = p.grad
26 if g is None:
27 continue
28 self.m[i].mul_(self.b1).add_(g, alpha=1 - self.b1)
29 self.v[i].mul_(self.b2).addcmul_(g, g, value=1 - self.b2)
30 m_hat = self.m[i] / (1 - self.b1**self.t) # bias correction
31 v_hat = self.v[i] / (1 - self.b2**self.t)
32 p.addcdiv_(m_hat, v_hat.sqrt().add_(self.eps), value=-self.lr)
33
34
35w = torch.randn(4, requires_grad=True)
36opt = Adam([w])
37(w.pow(2).sum()).backward() # toy loss = ||w||²
38opt.step()Where tuning goes wrong
Comparing optimizers at one learning rate. Adam's 0.001 and SGD's 0.1 are not the same knob, and each optimizer has its own good range and schedule. Tune each one before comparing. Some vision benchmarks favour carefully tuned SGD with momentum over Adam, but that result depends on the schedule, regularisation, data and compute budget, so compare held-out performance rather than assuming an optimizer guarantees generalisation.
Steps past the curvature limit. A loss that spikes or turns into NaN is often the 1.4-per-step growth from the first example, happening along some steep direction. Lower the learning rate or clip the gradient norm before suspecting the model.
Cold starts. At initialisation the weights are random and the gradients large, so the first steps are the most likely to diverge. A short linear warmup of the learning rate is the standard guard, and Goyal et al. needed one to make their large batches work.
Changing the batch and nothing else. A bigger batch gives a less noisy gradient and fewer steps per epoch. Keep the learning rate fixed and you take fewer, more cautious steps through the same data.
Sources and further reading
- Kingma and Ba, Adam: moment estimates, bias correction, and update rules.
- Loshchilov and Hutter, Decoupled Weight Decay Regularization: AdamW and optimizer-dependent weight decay.
- Goyal et al., Accurate, Large Minibatch SGD: Training ImageNet in 1 Hour (2017): linear learning-rate scaling with batch size, and gradual warmup.
Keep going
Ask your own question about Gradient Descent (SGD, Momentum, Adam), or start a guided session on it: six short pages, from the big picture to code you can run.