Key takeaways
- Gradient descent takes a small step against the gradient, θ←θ−ηg. The learning rate η is limited by the steepest direction: too big and training diverges, too small and it crawls.
- SGD estimates the true gradient from a small batch of data (a mini-batch). It's noisy, but cheap, and right on average.
- Momentum is a running average of the gradient: consistent directions are kept, back-and-forth zigzags cancel out.
- Adam divides by v^+ϵ to give every parameter its own step size, and uses bias correction to undo the effect of starting from zero. The price: four numbers stored per parameter, about 4× the parameter memory.
- AdamW (decoupled weight decay), plus gradient clipping, warmup and cosine decay, is the standard setup for training large models today.
So you have the gradient. Now what?
Picture yourself halfway down a mountain in thick fog, trying to reach the lowest point of the valley. You can't see into the distance. All you can feel is which way the ground under your feet tilts, and how steeply.
Training a neural network is exactly that:
- the height of the ground is the loss;
- where you stand is the model's parameters;
- the slope under your feet is the gradient that backpropagation computed last episode.
Knowing the slope, which way should you step, and how far? The thing that answers this is the optimizer: it decides the direction and size of every parameter update. This episode starts from plain gradient descent and works up to AdamW, the optimizer behind almost every large model today.
Gradient descent: a small step downhill
Start with the simplest case: one parameter θ, and the loss
L(θ)=(θ−3)2
The lowest point is obviously at θ=3, but the model doesn't know that; all it sees is the slope under its feet. Start at θ=0, where the loss is 9 and the slope (the derivative) is L′(θ)=2(θ−3)=−6. The minus sign says moving right is downhill. The gradient points uphill, so we go the opposite way:
θ←θ−ηg
Here η is the learning rate, which sets the step size, and g is the current gradient. This is the vanilla SGD update θ←θ−ηgt. Try η=0.1:
- Step 1: θ=0−0.1×(−6)=0.6, and the loss drops from 9 to 5.76.
- Step 2: the slope is now −4.8, so θ=0.6−0.1×(−4.8)=1.08, and the loss falls to 3.69.
Keep going and the point creeps toward the bottom. The closer it gets, the gentler the slope, so the steps shrink automatically. That's gradient descent: compute the gradient, step the opposite way, repeat. All of deep learning training is built on this one line.
Learning rate: how big a step?
How big should the learning rate be? Redo the calculation with letters. Subtract 3 from the new position:
θ′−3=(θ−3)−η⋅2(θ−3)=(1−2η)(θ−3)
So every step multiplies the distance to the bottom by the same factor, 1−2η:
| η |
factor 1−2η |
what happens |
| 0.02 |
0.96 |
shrinks only 4% a step: slow |
| 0.1 |
0.8 |
shrinks 20% a step |
| 0.5 |
0 |
lands on the bottom in one jump (luck) |
| 0.9 |
−0.8 |
overshoots and bounces, but closes in |
| 1.1 |
−1.2 |
bounces farther each time: diverges |
So the learning rate has a ceiling: the factor must be less than 1 in absolute value,
∣1−2η∣<1⟺0<η<1
That ceiling depends on how steep the bowl is. Make the loss L=10(θ−3)2, a narrower, steeper bowl (the same derivation gives the factor 1−20η), and the ceiling drops to η<0.1.
Intuition: The steeper the bowl, the smaller your steps must be. The learning rate is one of the most important hyperparameters: too big and training diverges, too small and it's slow. Once there are two parameters, this fact causes real trouble.
Stochastic gradient descent and mini-batches
There's a practical problem: the loss is really an average over all the training data. Say the training set has just 8 examples, each with its own gradient: 3,−1,2,1,0,4,−2,1. The true gradient is their average:
true gradient=83−1+2+1+0+4−2+1=88=1
But a large model trains on trillions of tokens, and running through all of them for every tiny step would be far too slow. The fix: at each step, randomly grab a small batch, say 2 examples, and use their average gradient instead. That small batch is a mini-batch.
Shuffle the 8 and pair them up. The first batch draws 4 and 3 (average 3.5), the second −1 and 0 (average −0.5), and the last two give −0.5 and 1.5. Every batch disagrees, and two even point the wrong way, but the average of the four is still exactly 1.
That's an unbiased estimate: any single one is noisy, but on average it points the right way. Updating with gradients sampled like this is stochastic gradient descent (SGD).
- Bigger batches give better estimates: with 4 per batch, the two batches give 1.5 and 0.5, much closer to 1.
- Rule of thumb: a batch 4× bigger cuts the noise roughly in half (noise ∝1/B, where B is the batch size).
- Large models typically use a few million tokens per batch, a balance between getting the gradient accurately and getting it fast.
From here on, "the gradient" means this kind of estimate: computed on a mini-batch, and a little noisy.
Two parameters: a long, narrow valley
Real models have more than one parameter. With two, the loss becomes a landscape over θ1 (horizontal) and θ2 (vertical), drawn with contour lines: along one line the loss is constant, and it gets lower toward the middle. The illustrative example is
L=21(0.01θ12+θ22)
- At any point the gradient is perpendicular to the contour line, pointing steepest uphill; we walk the opposite way.
- But the steepest way down doesn't point at the bottom. It points almost straight across the valley.
- This valley is narrow and steep up-and-down, but wide and flat left-to-right. Shapes like this are very common in neural networks.
Run gradient descent with a learning rate of 1.8 and it zigzags in the steep up-down direction while barely creeping left to right. That's the factor from the last section at work: up-down, each step multiplies the distance by −0.8, so it bounces; left-right, it multiplies by 0.98, so it hardly moves. (Push the learning rate above 2 and the up-down direction diverges.)
Raise the learning rate to speed up the left-right motion? Up-down blows up. Lower it? Left-right gets even slower. A single learning rate can't suit every direction at once, and mini-batch noise makes the path messier still.
Two ideas fix this: give the motion inertia so it isn't yanked around by every wobble, and give each direction its own step size.
Momentum: get the ball rolling
Picture a heavy ball rolling downhill. It doesn't swerve at every bump; it builds up speed and charges along the overall direction. Instead of using this step's gradient directly, keep a running average of the gradient, m:
m←βm+(1−β)g,θ←θ−ηm
With β=0.9, m keeps 90% of its old value and mixes in 10% of the new gradient each step. Some numbers, starting from m=0:
- If the gradient in some direction is always 1, m goes 0.1, 0.19, 0.27, … and slowly climbs to 1.
- In the zigzag direction, where the gradient flips between +4 and −4, m goes 0.4, −0.04, 0.36, … and just hovers around 0.
Intuition: Momentum is a filter. The consistent part of the gradient is kept, the parts that fight each other cancel, and random noise gets partly averaged away. If the gradient keeps pointing one way, momentum builds velocity and moves more confidently, barrelling through the noise.
Race it in the valley: the momentum path is much smoother. It still sways across the valley, but rolls faster and faster along it. After the same 50 steps it's almost at the bottom, while gradient descent has covered only a little over half the distance. Because the back-and-forth parts cancel, momentum also tolerates a bigger learning rate without diverging (in this valley, plain gradient descent diverges once its learning rate passes 2).
Watch out: Some code, PyTorch's SGD for example, writes momentum as v←βv+g, without the 1−β. That just rescales the learning rate by a constant; it's the same idea.
Second moment: a step size for each parameter
Now the second idea. The root problem is that different parameters can have gradients whose sizes differ by orders of magnitude: say parameter A's gradient is always around 10, and parameter B's around 0.1.
The natural fix is to divide each parameter's gradient by its own typical size. To measure that size, keep a running average of the squared gradient, v. This is the second moment:
v←β2v+(1−β2)g2
Why square it? Positive and negative values would cancel; squaring keeps only the size. When we use it we take v, which brings us back to the gradient's units.
- Parameter A: gradient around 10, so v≈10.
- Parameter B: gradient around 0.1, so v≈0.1.
- Divide each gradient by its v and both come out around 1: their steps are now on the same scale.
In other words, every parameter automatically gets its own effective learning rate:
effective learning rate=v+ϵη,ϵ=10−8
Parameters whose gradients have been big all along take smaller steps; those with tiny gradients take bigger ones. The tiny ϵ in the denominator keeps us from dividing by zero.
Adam: both ideas together
Combine momentum (the first moment) with the second moment and you get Adam, the most widely used optimizer today:
θ←θ−ηv+ϵm
The numerator m handles direction (it's the smoothed gradient); the denominator v handles scale (it keeps every parameter's step about the same size). Each has its own coefficient. The usual values are β1=0.9 and β2=0.999; for large models β2 is often 0.95.
Bias correction: don't let zero hold you back
One glitch: m and v both start at 0. Say the first gradient is g=2:
m1=0.9×0+0.1×2=0.2,v1=0.999×0+0.001×22=0.004
But the real gradient is 2. So m is 10× too small (it should be about 2) and v is 1000× too small (it should be about 4), both dragged down by the starting zero. Used as is, m1/v1=0.2/0.063≈3.16 when it should be 1: the first step is way too big.
The fix is to divide by 1−βt, where t is the step number:
m^t=1−β1tmt,v^t=1−β2tvt
Why that number? Suppose the gradient is the same g at every step:
m1m2m3mt=(1−β)g=β(1−β)g+(1−β)g=(1−β)(1+β)g=(1−β)(1+β+β2)g=(1−β)(1+β+β2+⋯+βt−1)g
The bracket is a geometric series, 1+β+⋯+βt−1=1−β1−βt, so the 1−β out front cancels:
mt=(1−βt)g
So m is exactly the true gradient times (1−βt); divide by that and the bias is undone. The same reasoning works for v. Check the example: m^1=0.2/0.1=2 and v^1=0.004/0.001=4, with 4=2. Spot on.
As training goes on, βt→0 and the correction factor →1, so the correction quietly switches itself off; it only matters early in training. The closer β is to 1, the longer it lasts.
One full step of Adam is these four lines:
mvm^θ←β1m+(1−β1)g←β2v+(1−β2)g2=m/(1−β1t),v^=v/(1−β2t)←θ−ηm^/(v^+ϵ)
The race: gradient descent, momentum and Adam
Back in the valley, let all three set off from the same point. Gradient descent zigzags, momentum swings its way down, and Adam heads almost diagonally, straight for the bottom. After dividing by v, its up-down and left-right steps are about the same size: no more bouncing in the steep direction, no more dawdling in the flat one.
Of course, this is a hand-picked two-dimensional example; a real loss landscape has billions of dimensions. Still, for training Transformers, Adam-style methods really are fast and stable, which is why they became the default.
Adam's price is memory. For every parameter, training stores four things: the parameter θ, its gradient g, the first moment m and the second moment v (m and v both start at 0). That's 4× the parameter memory. For a 7-billion-parameter model at 4 bytes per number, one copy is 28 GB, so four copies are 112 GB.
Watch out: That's before counting intermediate activations. Episode 10 does the full memory accounting, and episode 17 shows how to split this state across many GPUs.
Weight decay and AdamW
The optimizer behind almost every large model today is a variant of Adam: AdamW. The W is for weight decay: on every step, on top of the normal update, pull every parameter a little toward 0:
θ←θ−ηv^+ϵm^−ηλθ
How hard? ηλθ, proportional to the parameter itself: the bigger the parameter, the harder the pull. With η=0.001 and λ=0.1, each step does θ←θ×(1−0.0001), shrinking parameters by one ten-thousandth. Tiny per step, but over tens of thousands of steps it really adds up.
This is regularization: it keeps parameters from growing too large and nudges the model toward simpler solutions, so it's less likely to memorize the training data, that is, to overfit.
Why make a point of the W? The older approach added the decay term λθ to the gradient, so it got divided by v^ along with the gradient. The result: parameters with large gradients ended up with weaker decay. AdamW decouples the two. The decay acts directly on the parameters, so every parameter is pulled toward 0 by the same fraction.
Watch out: In practice, biases and normalization-layer parameters (such as LayerNorm) usually get no weight decay. There are very few of them and no real reason to pull them toward 0; the layers' weight matrices do get decay. To do this, split the parameters into two parameter groups, each with its own weight decay.
torch.optim.AdamW([
{'params': decay_params, 'weight_decay': 0.01},
{'params': no_decay_params, 'weight_decay': 0.0},
])
AdamW in code
When you create an optimizer, you hand it the model's parameters (telling it which numbers to optimize) and a learning rate lr (which sets the update size), as in AdamW(model.parameters(), lr=...). Passing model.parameters() creates a single parameter group; passing a list like the one above gives each group its own hyperparameters (different learning rates for different layers, say). The defaults dict supplies a fallback for any hyperparameter a group doesn't set.
Here's AdamW written from scratch:
class AdamW(torch.optim.Optimizer):
def __init__(self, params, lr, betas, eps, weight_decay):
defaults = {"lr": lr, "betas": betas, "eps": eps, "weight_decay": weight_decay}
super().__init__(params, defaults)
def step(self):
for group in self.param_groups:
lr = group["lr"]; beta1, beta2 = group["betas"]
eps = group["eps"]; weight_decay = group["weight_decay"]
for p in group["params"]:
if p.grad is None:
continue
state = self.state[p]
t = state.get("t", 0)
m = state.get("m", torch.zeros_like(p.data))
v = state.get("v", torch.zeros_like(p.data))
# weight decay (first, since it depends only on the parameter)
p.data -= lr * weight_decay * p.data
# Adam update
grad = p.grad.data
m = beta1 * m + (1 - beta1) * grad
v = beta2 * v + (1 - beta2) * grad**2
m_hat = m / (1 - beta1 ** (t + 1))
v_hat = v / (1 - beta2 ** (t + 1))
p.data -= lr * m_hat / (v_hat.sqrt() + eps)
state["t"] = t + 1; state["m"] = m; state["v"] = v
Reading it alongside the math:
- Load the state: each parameter's step count
t, first moment m and second moment v, all zero the first time we see it.
- Weight decay first: the formula decays the parameter's value from before the update (it depends only on the parameter), so it goes before anything else.
- Update
m and v: exactly the two running-average formulas.
- Bias correction:
t counts from 0 in code, so we write t + 1 (the formula's t starts at 1).
- Update the parameter: divide m^ by v^+ϵ, multiply by the learning rate, subtract; then store the new state for the next step.
Gradient clipping: a cap on the step
Every so often you hit a really bad batch, or wander up to a "cliff" in the landscape, and the gradient suddenly becomes enormous. Update as usual and the parameters get flung far away in one step, possibly wrecking all the training so far.
Gradient clipping caps the gradient's length at c. Treat the gradients of all parameters as one big vector and compute its length, the global norm. If it's over the cap, scale every gradient down by the same factor to fit:
g←g⋅min(1, ∥g∥c)
Example: two parameters with g=(3,4), so ∥g∥=32+42=5. With a cap of c=1, 5 is over the limit, so multiply by 51 to get (0.6, 0.8).
- Every component shrinks by the same factor, so the direction is unchanged; the vector just gets shorter. If the length was already under the cap, nothing happens.
- In a real model, the vector holds all the billions of gradients, but the algorithm is the same. Large models usually use a cap of 1.0.
Back at the cliff: after clipping, the parameters move just a small step, and training stays stable. Clipping keeps any single step from being catastrophically large.
Learning rate schedules: warmup and cosine decay
Should the learning rate stay fixed from start to finish? In practice, large models almost always vary it over time. First, a distinction:
Watch out: How do you decide whether something belongs in the learning rate schedule or in the optimizer? If it depends only on the current step t and is the same for every parameter, it's a schedule. If it needs each parameter's history (like m and v), it's the optimizer.
The most common schedule has two phases.
Phase 1: warmup. The learning rate starts at 0 and climbs linearly to its maximum ηmax. Why?
- At the start the parameters are random, so gradient directions are unreliable, and Adam's v has seen only a few steps, so its estimate is still off.
- With a big learning rate now, the first few batches would have far too much influence (a primacy effect) and push the parameters somewhere strange. Small steps first, speed up once the direction settles.
Phase 2: decay, most commonly cosine decay: the learning rate follows half a cosine curve, sliding smoothly from its maximum to its minimum:
ηt=ηmin+21(ηmax−ηmin)(1+cos(π⋅progress))
Progress runs from 0 to 1. Check: at progress 0, cos0=1, the bracket is 2, and we get ηmax; at progress 1, cosπ=−1, the bracket is 0, leaving ηmin. The minimum is usually about 101 of the peak.
Why decay at all? Near the bottom, gradient noise keeps the parameters jittering around, and the bigger the learning rate, the worse the jitter. Lower it gradually (say from 0.3 to 0.03) and the jitter shrinks with it, so the parameters settle neatly into the bottom.
A real training recipe
You can now read a real training recipe. Here's Llama 2 (source: the Llama 2 paper, Touvron et al., 2023):
| Setting |
Value |
| optimizer |
AdamW |
| β1, β2 |
0.9, 0.95 |
| ϵ |
10−5 |
| weight decay λ |
0.1 |
| gradient clipping |
1.0 |
| LR schedule |
2000 warmup steps, cosine decay to 10% of peak |
| peak LR (7B) |
3×10−4 |
Tying the episode together, one training step is this loop:
- grab a mini-batch;
- forward pass: compute the loss;
- backpropagate: compute the gradients;
- clip the gradients;
- look up this step's learning rate from the schedule;
- update the parameters with AdamW;
- zero the gradients, and go back to step 1.
Training a large model runs this loop hundreds of thousands of times.
Recap
Gradient descent steps against the gradient, and the learning rate is capped by the steepest direction (steeper bowl, smaller steps). SGD estimates the gradient from a mini-batch: noisy, but cheap and right on average. Momentum smooths out the zigzags, the second moment gives each parameter its own step size, and together they make Adam, with bias correction fixing the zero start, at the cost of about 4× the parameter memory. AdamW applies weight decay directly to the parameters (usually skipping biases and normalization parameters), and together with gradient clipping, warmup and cosine decay it's the standard way large models are trained. We've spent the whole episode making the loss smaller. Next time: what is that loss, the cross-entropy, actually measuring?