rumblr Work in progressWIP

● The AI Primer · Lesson 4 · Part 1: how a language model works

Optimizers

how weights take their steps downhill

This lesson covers How a neural network turns the slope of its loss into a step, and how to set the learning rate

Members · open during launch 30 min8 figures and diagrams7 interactive

What this is

What is an optimizer?

Training a neural network, the kind of program behind modern AI, means adjusting its weights, the numbers inside it, so that its answers get a little less wrong. An optimizer is the rule that decides how big each adjustment is and in which direction. The simplest one, plain gradient descent, takes a step downhill; momentum and Adam add a memory of earlier steps and a step size for every weight.

Why it matters: A training or fine-tuning job asks you for a learning rate before anything else, and a loss curve that spikes, turns to NaN or flattens early is usually the optimizer's doing. Knowing what each setting does lets you choose them instead of copying someone else's.

At a glance

Key takeaways

  1. Gradient descent steps against the slope of the loss, scaled by the learning rate.
  2. The learning rate is the first setting to get right: too high diverges, too low stalls.
  3. Momentum keeps a velocity, so steady directions speed up and zig-zags cancel.
  4. Adam gives every weight its own step size (average gradient ÷ its typical size); AdamW keeps weight decay out of that division, so its strength means what it says.
  5. Large training runs warm the learning rate up, decay it along a cosine, and clip the gradient's total length.

How it works, from scratch

Every optimizer runs the same loop: measure the slope of the loss at the current weights, turn it into a step, take the step, and repeat. Optimizers differ only in the middle part, the rule that turns a slope into a step.

Chapter 1

Gradient descent

Start with the simplest rule, on a valley with one weight, w, that you cannot see. Feel the slope, step against it, and repeat until you reach the bottom.

You're on a hillside in thick fog, trying to reach the bottom of the valley. You can't see the valley, only feel the slope under your feet, so you feel which way is downhill, take a step that way, and repeat. That is gradient descent. The hillside is the loss (how wrong the model is, for every possible setting of its weights), your position is the current weights, and the slope under your feet is the gradient: the slope of the loss along each weight, one number per weight. (Neural networks shows how backpropagation measures it.) The step is the gradient times a small number, the learning rate, taken against the slope.

The simplest valley there is has one weight: the bowl f(w) = w², whose slope at w is 2w. Start at w = 1 with a learning rate of 0.1:

step w slope 2w step taken 0.1 × slope new w
0 1.0 2.0 0.2 0.8
1 0.8 1.6 0.16 0.64

Each step keeps 80% of w, so w slides toward the bottom at 0.

Figure 1 · Diagram

Reading it: follow the arrows round from the current weights to the new ones. Only the diamond changes from one optimizer to the next. Plain gradient descent's rule looks at the current slope alone; momentum and Adam, later in this lesson, also read the dotted box, a memory of past slopes.
The formula and its symbols

Symbols

Symbol Meaning here In the example
the weights at step
the step counter 0, 1, 2, …
"eta", the learning rate (step size) 0.1
the loss
"nabla L", the gradient: the slope of the loss at the current weights, one number per weight

In words: "the next weights are the current weights minus the learning rate times the slope of the loss where we stand."

With the numbers: ; .

In Python
w, eta = 1.0, 0.1
# ∇L for the bowl L = w²
def grad_L(w): return 2 * w
for t in range(2):
    # w_(t+1) = w_t - η ∇L(w_t)
    w = w - eta * grad_L(w)
    print(round(w, 2))  # → 0.8 0.64

New to Σ, ∂ or ‖x‖? The symbols reference decodes each one as a few lines of Python.

A real model's loss is an average over its training examples. Stochastic gradient descent (SGD) estimates the slope from a small random batch of examples instead of the whole dataset, so each step is noisier but reads only the batch.

In code: descend_bowl runs the table; SGD is the general version. View source

Chapter 2

The learning rate

The walk down the bowl used a learning rate of 0.1. In the fog, a short stride is safe but slow, and a long one can carry you past the valley floor and higher up the other side. On the bowl w² the slope is 2w, so a step multiplies w by the same number every time, 1 − 2η, and that number decides the walk:

learning rate η multiplier 1 − 2η w after 1, 2, 3 steps what happens
0.001 0.998 0.998, 0.996, 0.994 stalls: 10 steps only reach 0.980
0.1 0.8 0.8, 0.64, 0.512 smooth progress
0.5 0 0, 0, 0 lands on the bottom in one step
1.1 −1.2 −1.2, 1.44, −1.728 overshoots further each time: diverges

Figure 2 · Chart

0 5 10 15 20 25 30 step 1 0 − 1 2 1 0 − 1 0 1 0 − 8 1 0 − 6 1 0 − 4 1 0 − 2 1 0 0 1 0 2 1 0 4 1 0 6 loss w² (log scale) Learning rate on the bowl f(w) = w² η = 0.001 η = 0.1 η = 0.45 η = 1.1

Over 30 steps, rate 0.001 barely lowers the loss, 0.1 falls steadily, 0.45 plunges below the chart within six steps, and 1.1 climbs as every step overshoots

Reading it: each line is the loss (log scale) over 30 steps for one learning rate. The flat line near the top is 0.001, falling too slowly to see. 0.1 falls steadily. 0.45 falls fastest: its line ends at step 5, because one step later the loss is down to 10⁻¹², the floor of the chart. 1.1 climbs the whole way, because every step overshoots further than the last.
The formula and its symbols

Symbols

Symbol Meaning here In the example
the slope of at 2.0 at
the factor each step multiplies by −1.2 when

In words: "on this bowl, one step multiplies the weight by one minus twice the learning rate; if that factor's size is above 1, the weight grows instead of shrinking."

With the numbers: : , so .

In Python
def three_steps(eta, w=1.0):
    out = []
    for t in range(3):
        # w - η·2w = (1 - 2η) w
        w = (1 - 2 * eta) * w
        out.append(round(w, 3))
    return out
three_steps(1.1)  # → [-1.2, 1.44, -1.728]
three_steps(0.1)  # → [0.8, 0.64, 0.512]
# η = 0.001 after 10 steps: barely moved
round(0.998 ** 10, 3)  # → 0.98

A real model shows the same two failures in its loss curve. With too high a learning rate the loss bounces, spikes or turns to NaN ("not a number", what the arithmetic returns once values overflow); with too low a rate it barely moves, or settles somewhere poor. You cannot compute the right rate for a real model, so you look for the fastest one that does not blow up, and it is the first setting to get right. The steepest direction sets the ceiling: on the bowl, whose slope is 2w, any η above 1 diverges.

In code: descend_bowl takes the learning rate as an argument and reproduces every row of the table. View source

Set any learning rate and watch where ten steps land on the bowl.

Chapter 3

Momentum

The bowl is equally steep in every direction, so one learning rate suits every step. A real loss is steeper in some directions than in others. Picture a long, narrow valley with steep walls on both sides and a gentle slope along the floor. The walls set the ceiling on the learning rate, and at that rate the steps along the floor are tiny: plain gradient descent zig-zags from wall to wall and creeps along the floor. A heavy ball rolling down the same valley does better. Its sideways swings cancel out, while the steady pull along the floor keeps adding up, so it gathers speed along the floor. Momentum gives the optimizer that speed. It keeps a velocity, a running sum of past slopes in which older slopes fade, and steps along the velocity instead of the slope.

On the bowl w², with a learning rate of 0.1 and momentum β = 0.9, the first two steps are:

step slope g = 2w velocity v = 0.9·v + g new w = w − 0.1·v
1 2.0 2.0 1.0 − 0.2 = 0.8
2 1.6 0.9 × 2.0 + 1.6 = 3.4 0.8 − 0.34 = 0.46

After two steps plain descent is at 0.64; momentum is already at 0.46.

Figure 3 · Diagram

Reading it: the velocity box mixes the new slope with 90% of the old velocity, and the velocity, not the raw slope, sets the step. Follow the arrow back: on the next step this velocity becomes the old velocity. Slopes that keep pointing the same way pile up; slopes that flip sign every step, as they do between the walls, mostly cancel.

Figure 4 · Chart

−8 −6 −4 −2 0 2 x (gentle direction) −1.0 −0.5 0.0 0.5 1.0 y (steep direction) 100 steps on the narrow valley ½(x² + 100y²) SGD (η = 0.015) momentum (η = 0.015, β = 0.9) Adam (η = 0.3) minimum

After 100 steps from (-8, 1), plain SGD has only crept to x = -1.8 along the valley floor, while momentum and Adam reach the minimum after some overshoot

Reading it: the ellipses are contour lines of the valley ½(x² + 100y²), the start is at the left and the minimum is the star at the centre. Plain SGD (its learning rate capped by the steep walls) creeps along the floor and after 100 steps is still far from the star. Momentum swings hard: across the valley to y = −1.1 (further out than it started) and past the star to x ≈ 1.9, before the swings die down and it settles 0.003 from the minimum. Adam, which rescales each direction separately, takes a steadier line: it dips to y ≈ −0.5, overshoots to x ≈ 0.6, and ends 0.02 away. Both end far closer than plain SGD; momentum overshoots further on the way.
The formula and its symbols

Symbols

Symbol Meaning here In the example
the gradient (slope) at step 2.0, then 1.6
the velocity: a running, fading sum of past gradients 2.0, then 3.4
"beta", how much old velocity is kept each step (0 to 1) 0.9
learning rate 0.1

In words: "the velocity is 90% of the previous velocity plus the new slope, and the weights move by the learning rate times the velocity."

With the numbers: ; .

In Python
w, v, beta, eta = 1.0, 0.0, 0.9, 0.1
for t in range(2):
    # the slope of w² here
    g = 2 * w
    # v_t = β v_(t-1) + g_t
    v = beta * v + g
    # w_(t+1) = w_t - η v_t
    w = w - eta * v
    print(round(v, 2), round(w, 2))  # → 2.0 0.8 3.4 0.46

On the narrow valley, after 100 steps at the same learning rate, momentum's loss is more than 10,000 times lower than plain SGD's. SGD with momentum is still the usual optimizer for convolutional networks, the neural networks behind most image recognition (see CNNs and RNNs).

In code: momentum_on_bowl runs the table, and run walks any optimizer across narrow_valley. View source

Set the momentum β and the number of steps, and race momentum against plain SGD across the narrow valley.

Chapter 4

Adam: a step size for every weight

Momentum speeds up travel along the floor, but every weight still moves with the same learning rate, and the steep walls still cap it. The narrow valley needs short steps across the walls and long ones along the floor. Adam gives every weight its own step size. For each weight it keeps a running average of the slope (the direction, as momentum does) and a running average of the squared slope (how big that weight's slopes typically are), and divides the first by the square root of the second. A weight with steep slopes and a weight with gentle ones then take steps of about the same size, the learning rate.

The first step shows it most plainly. Adam moves a weight by the learning rate (0.01 here) whether that weight's gradient is 1000, 1 or 0.001. (With bias correction, m̂ = g and v̂ = g², so the step is 0.01 × g / |g| = 0.01.)

Figure 5 · Diagram

Reading it: the gradient feeds two running averages. The top path keeps its direction, the bottom path its typical size. Both start at zero, so for the first few steps they are too small, and the "hat" boxes correct for that. The last box divides direction by size, which makes each weight's step about η long, pointing the way its slope says.
The formula and its symbols

Symbols

Symbol Meaning here In the example (first step, g = 1000)
this weight's gradient at step 1000
running average of the gradient ("first moment")
running average of the squared gradient ("second moment")
how much of the old averages to keep 0.9, 0.999
raised to the step number
"m-hat, v-hat": the bias-corrected averages 1000,
square root
"epsilon", a tiny number to avoid dividing by zero
learning rate 0.01

In words: "keep a running average of the gradient and of its square, correct both for starting at zero, then step by the learning rate times the average gradient divided by its typical size."

With the numbers: , , step .

In Python
import math
beta_1, beta_2, eta, eps, t = 0.9, 0.999, 0.01, 1e-8, 1
def first_step(g):
    # m_1, starting from m_0 = 0
    m = beta_1 * 0 + (1 - beta_1) * g
    # v_1, starting from v_0 = 0
    v = beta_2 * 0 + (1 - beta_2) * g ** 2
    # undo the pull toward zero
    m_hat = m / (1 - beta_1 ** t)
    v_hat = v / (1 - beta_2 ** t)
    return eta * m_hat / (math.sqrt(v_hat) + eps)
# m_1, v_1
round((1 - beta_1) * 1000, 6), round((1 - beta_2) * 1000 ** 2, 6)  # → (100.0, 1000.0)
# the same step every time
[round(first_step(g), 6) for g in (1000, 1, 0.001)]  # → [0.01, 0.01, 0.01]

So one learning rate serves weights whose gradients differ by orders of magnitude, as they do in a transformer, where embeddings, attention and layer norms all behave differently. On the narrow valley Adam reaches a loss below 10⁻¹⁰ in 300 steps, while plain SGD is still near 10⁻³.

In code: Adam applies the five formulas in Adam.step, and adam_first_step takes the first step alone. View source

Back in the narrow valley, drag the start and compare plain gradient descent's first step with Adam's, across the steep walls and along the gentle floor.

Chapter 5

Weight decay, and why AdamW exists

Adam's division has a side effect, and it shows up in weight decay. Weight decay is a leash on every weight: at each step it pulls the weight a little toward zero, so the model prefers small weights to large ones (a form of regularization; see Overfitting and regularization). The classic way to add it is an L2 penalty: add λw to the gradient. With plain SGD that is the same as shrinking each weight by ηλw. With Adam it is not, because Adam divides the whole gradient, penalty included, by its typical size, and the strength λ is divided away with it. AdamW (Loshchilov and Hutter, 2017) decouples the two: it takes Adam's step on the loss gradient alone, then shrinks each weight by ηλw directly.

Take one step with no loss gradient, so only the decay acts, from w = 1 at a learning rate of 0.1:

method decay λ = 0.1 decay λ = 0.001
AdamW (decoupled) 1 − 0.1 × 0.1 = 0.99 1 − 0.1 × 0.001 = 0.9999
Adam with L2 in the gradient 0.9 0.9

With L2 inside Adam, a penalty 100 times weaker shrinks the weight just as much.

Figure 6 · Diagram

Reading it: on the left, the decay term joins the gradient before Adam's rescaling, so it is divided by √v̂ like everything else and its strength is lost. On the right (AdamW), the decay goes round the rescaling and shrinks the weights directly, so each step shrinks every weight by the fraction η·λ.
The formula and its symbols

Symbols

Symbol Meaning here In the example
"lambda", the weight-decay strength 0.1
how much the leash pulls this step
Adam's usual step direction 0 here (no loss gradient)

In words: "take Adam's normal step, then separately shrink every weight by learning rate times decay times the weight."

With the numbers: .

In Python
# no loss gradient: Adam's step is 0
w, eta, adam_step = 1.0, 0.1, 0.0
for lam in (0.1, 0.001):
    # AdamW: shrink by η λ w
    print(round(w - eta * adam_step - eta * lam * w, 4))  # → 0.99 0.9999
for lam in (0.1, 0.001):
    g = lam * w
    print(round(w - eta * g / abs(g), 4))  # → 0.9 0.9

AdamW is the default optimizer for training transformers: Llama 2 was trained with it, and Hugging Face's trainer uses it unless told otherwise.

In code: Adam runs either recipe, and one_decay_step runs the table. View source

Set the decay strength λ anywhere from 0.0001 to 0.1 and follow one weight for thirty steps under each rule.

Chapter 6

Warmup and cosine decay

So far the learning rate has been one number for the whole run. Large runs change it as they go. They warm up: the rate climbs in a straight line from 0 to its peak over the first steps, because at the start the weights are random and Adam's averages rest on a handful of slopes, so a full-size step can throw the weights somewhere bad. Then the rate decays along half a cosine curve toward a small floor, so the last steps are small and the weights settle into a minimum instead of bouncing around it. Llama 2, for one, warmed up for 2,000 steps and decayed to 10% of its peak.

With a peak of 0.001, 100 warmup steps and 1,000 steps in all:

step phase learning rate
50 halfway through warmup 0.0005
100 end of warmup 0.001 (peak)
550 halfway through decay 0.0005
1000 end the floor (e.g. 0.00001)

Figure 7 · Chart

0 200 400 600 800 1000 training step 0.0000 0.0002 0.0004 0.0006 0.0008 0.0010 learning rate Linear warmup, then cosine decay end of warmup

The learning rate ramps straight up from 0 to 0.001 over 100 steps, then falls along a half cosine, passing 0.0005 at step 550 and ending near 0.00001

Reading it: the horizontal axis is the training step and the vertical axis the learning rate. The short straight ramp on the left is warmup. Then the curve rolls over the top, falls fastest in the middle and flattens as it approaches the floor. The four dots are the rows of the table.
The formula and its symbols

Symbols

Symbol Meaning here In the example
the learning rate at step 0.0005 at
the peak learning rate 0.001
the floor 0 (or 0.00001)
number of warmup steps 100
total steps 1000
progress through the decay, from 0 to 1
cosine: 1 at 0, 0 at , −1 at
pi, ≈ 3.1416 (half a turn, in radians)

In words: "during warmup the rate climbs in a straight line to the peak; after that it follows half a cosine wave from the peak down to the floor."

With the numbers: step 550: progress 0.5, , so .

In Python
import math
eta_max, eta_min, T_w, T = 0.001, 0.0, 100, 1000
def eta(t):
    if t < T_w:
        # the straight ramp
        return eta_max * t / T_w
    # 0 to 1 through the decay
    progress = (t - T_w) / (T - T_w)
    return eta_min + (eta_max - eta_min) * (1 + math.cos(math.pi * progress)) / 2
[round(eta(t), 6) for t in (50, 100, 550, 1000)]  # → [0.0005, 0.001, 0.0005, 0.0]

In code: warmup_cosine returns the learning rate for any step. View source

Set the warmup length and the floor, then stop the run early and see which part of the schedule it never reached.

Chapter 7

Gradient clipping

A schedule plans for the start and the end of a run. It cannot plan for the rare batch that produces an enormous gradient, a sudden cliff in the fog, where a full step could throw the weights far from anywhere useful. Gradient clipping puts a limit on the gradient's length: a gradient longer than the limit is scaled down to it, keeping its direction, and a shorter one is left alone.

The gradient (3, 4) has length √(3² + 4²) = 5. With a limit of 1, scale it by 1/5 to get (0.6, 0.8): length 1, same direction. The gradient (0.3, 0.4) has length 0.5, under the limit, so it is left alone.

Figure 8 · Diagram

Reading it: first measure the length of all the gradients together, as if they were one long list. Within the limit, nothing happens. Past it, every gradient is multiplied by the same factor, which shortens the step without turning it.
The formula and its symbols

Symbols

Symbol Meaning here In the example
every gradient, treated as one long list (3, 4)
one entry of that list 3, 4
the norm (length) of : square every entry, add, take the square root 5
the clipping limit 1
the smaller of the two

In words: "if the gradient's length exceeds the limit, scale it down so its length equals the limit; otherwise leave it alone."

With the numbers: .

In Python
import math
def clip(g, c):
    # ‖g‖ = √(Σ g_i²)
    norm = math.sqrt(sum(g_i ** 2 for g_i in g))
    # shrink only if too long
    scale = min(1, c / norm)
    return [round(g_i * scale, 2) for g_i in g]
clip([3, 4], c=1)  # → [0.6, 0.8]
# length 0.5: under the limit, left alone
clip([0.3, 0.4], c=1)  # → [0.3, 0.4]

Llama 2 clipped at 1.0, and Hugging Face's trainer clips at 1.0 by default. Gradients that grow out of control as they pass back through many layers are a separate problem, taken up in Training deep neural networks.

In code: clip_by_global_norm clips a list of gradients together. View source

Drag the gradient's arrow past the circle, the limit, and watch what happens to its length and its direction.

Test yourself

6 questions

Answer each one out loud or on paper before you open it.

Question 1Which setting should you get right first, and what happens at each extreme?Think it through, then reveal

The learning rate. Too high: steps overshoot and training diverges or oscillates (loss spikes, NaNs). Too low: progress is so slow that training stalls or settles in a poor spot.

Question 2Why does momentum help in a narrow valley?Think it through, then reveal

Gradients across the valley flip sign every step and cancel in the velocity, while the small, consistent gradient along the valley accumulates, so the optimizer speeds up in the useful direction.

Question 3What does Adam's division by √v̂ achieve?Think it through, then reveal

It normalizes each weight's step by the typical size of its gradient, so every weight moves roughly η per step regardless of gradient scale. One learning rate then works for all parameters.

Question 4What's the difference between Adam with L2 and AdamW?Think it through, then reveal

With L2, the decay term is added to the gradient and then rescaled by Adam, so its effective strength varies per weight and λ loses its meaning. AdamW applies decay directly to the weights, outside the rescaling.

Question 5Why warm up the learning rate?Think it through, then reveal

At the start, weights are random and Adam's moment estimates are based on a handful of steps, so full-size updates can be wildly wrong and destabilize training. Ramping up gives the statistics time to settle.

Question 6What does gradient clipping protect against, and why clip the global norm?Think it through, then reveal

Rare huge gradients (exploding gradients, bad batches) that would throw the weights far off. Clipping the combined norm scales every tensor by the same factor, which preserves the update's direction.

Primary sources

The papers behind this lesson

Kingma & Ba, Adam: A Method for Stochastic Optimization (2014): Combined momentum with per-weight step sizes and bias correction into the optimizer most networks are trained with.

Read on rumblr →The paper

Loshchilov & Hutter, Decoupled Weight Decay Regularization (AdamW, 2017): Showed that L2 regularization and weight decay differ under Adam, and fixed it by decoupling the decay.

The paper

Sutskever, Martens, Dahl & Hinton, On the importance of initialization and momentum in deep learning (ICML 2013): Demonstrated that well-tuned momentum makes plain SGD competitive on hard deep-network problems.

The paper

Loshchilov & Hutter, SGDR: Stochastic Gradient Descent with Warm Restarts (2016): Introduced cosine learning-rate annealing, now the standard decay shape.

The paper

Pascanu, Mikolov & Bengio, On the difficulty of training recurrent neural networks (2012): Analysed exploding gradients and proposed clipping the gradient norm.

The paper

Researcher's shelf

Further reading

  • Sebastian Ruder, An overview of gradient descent optimization algorithms: https://arxiv.org/abs/1609.04747
  • Gabriel Goh, Why Momentum Really Works (Distill): https://distill.pub/2017/momentum/
  • Kingma & Ba, Adam: A Method for Stochastic Optimization (2014): https://arxiv.org/abs/1412.6980
  • Loshchilov & Hutter, Decoupled Weight Decay Regularization (AdamW, 2017): https://arxiv.org/abs/1711.05101
  • Loshchilov & Hutter, SGDR: Stochastic Gradient Descent with Warm Restarts (cosine schedules, 2016): https://arxiv.org/abs/1608.03983
  • Pascanu, Mikolov & Bengio, On the difficulty of training recurrent neural networks (gradient clipping, 2012): https://arxiv.org/abs/1211.5063
  • CS231n notes, Neural Networks Part 3 (parameter updates): https://cs231n.github.io/neural-networks-3/
  • PyTorch torch.optim docs: https://pytorch.org/docs/stable/optim.html

About this lesson. This is the illustrated edition of a lesson from the open-source AI Primer ↗. Its text, figures and numbers are generated from the Primer's source at commit f8b43d1, so the two always agree: the explanation, the code that builds it and the tests that prove it.