Skip to content
LearnAI
PART 3 · TRAINING LLMS/ Making training work

3.3Optimizers: SGD → Adam/AdamW → Muon

Why plain gradient descent struggles in narrow valleys, how Adam adapts a step size per parameter, and how Muon orthogonalizes whole weight-matrix updates.

⏱ 15 minIntermediate

The problem with walking straight downhill

In the gradient descent lesson you rolled a ball downhill with the update θ←θ−η∇L\theta \leftarrow \theta - \eta \nabla L. That rule, SGDStochastic gradient descent (SGD)Gradient descent that estimates the gradient on a small random batch of examples instead of the full dataset. when the gradient comes from a mini-batch, is correct but naive. Real loss landscapes are full of ravines: directions where the surface curves steeply next to directions where it is almost flat.

In a ravine, the gradient points mostly across the valley (steep walls), not along it (gentle floor). A learning rate big enough to make progress along the floor makes you bounce between the walls; one small enough to stop the bouncing makes progress along the floor painfully slow. With a curvature ratio of 100 between the two directions, plain gradient descent needs on the order of 100 steps to make the progress it could make in one if the landscape were round. Deep networks have curvature ratios far larger than that, and they differ wildly between parameters: embeddings, attention weights, normalization gains.

Every optimizer in this lesson is a different answer to the same question: how do we take big steps along gentle directions and small steps along steep ones, without computing the full curvature (which, for a billion parameters, would be a billion-by-billion matrix)?

ANALOGY· Skiing down a gully

A nervous beginner points their skis straight down the steepest slope at every moment. In a narrow gully, that means ricocheting from wall to wall while barely moving down the mountain. An experienced skier carries momentum along the gully and lets the side-to-side wobbles cancel out. A clever one also adjusts their stance per direction: stiff legs for the bumpy cross-slope, relaxed for the smooth run-out.

Momentum is the skier’s speed. Adam’s per-parameter step size is the per-direction stance. Muon is a skier who refuses to let any single direction take over their effort, and spreads it evenly across every independent direction they can move in.

Momentum, RMSProp and Adam

Momentum keeps a running average of past gradients and steps along that. Components that consistently point the same way (along the valley) add up; components that flip sign every step (across the valley) cancel. It is a heavy ball rather than a cautious hiker.

RMSProp attacks the problem differently. It keeps a running average of each parameter’s squared gradient, vv, and divides that parameter’s step by v\sqrt{v}. A parameter with consistently large gradients gets a small effective learning rate; one with tiny gradients gets a large one. The step size becomes roughly scale-free.

AdamAdam / AdamWAn optimizer that combines momentum with a per-parameter adaptive step size. AdamW decouples weight decay from the update. (Kingma and Ba, 2014) combines the two. For each parameter it tracks a first moment mm (the momentum: a moving average of the gradient) and a second moment vv (a moving average of the squared gradient), and steps by m/vm / \sqrt{v}. Typical decay rates are β1=0.9\beta_1 = 0.9 for mm and β2=0.999\beta_2 = 0.999 for vv (LLM training usually lowers β2\beta_2 to around 0.95 for stability). Because both averages start at zero, they are biased toward zero for the first steps; Adam corrects this with bias correction, dividing by 1−βt1 - \beta^t. The Math Corner shows what goes wrong without it.

A useful mental model: m/vm / \sqrt{v} is roughly a signal-to-noise ratio per parameter. If a parameter’s gradient is consistent, ∣m∣≈v|m| \approx \sqrt{v} and the step is about η\eta. If it’s noisy and keeps changing sign, mm averages toward zero while vv stays large, so the step shrinks.

INTERACTIVEOptimizer race
Landscape
LR schedule

A long valley aligned with the x-axis: the curvature across it is 100× steeper than along it. Click the map to choose a new start (+ marks the minimum).

step 0 / 400
loss 5.3792
loss 5.3792
loss 5.3792
loss 5.3792
loss 5.3792
Five optimizers start from the same point. Press Race, compare their paths and losses, then switch landscapes. Each optimizer has its own learning-rate slider; click the map to move the start point.

Things to try:

  1. Ravine. SGD zig-zags and creeps; push its η above 0.5 and it diverges (the steep direction’s limit is 2/curvature=0.52/\text{curvature} = 0.5). RMSProp and Adam scale each coordinate separately and sprint down the valley.
  2. Tilted ravine. The same valley turned 45°. Now Adam and RMSProp lose much of their edge, because their per-coordinate scaling can’t see a valley that runs diagonally across the coordinates. Momentum barely notices the rotation. This is a real limitation: Adam’s preconditioning is diagonal.
  3. Rosenbrock. A curved valley. Plain SGD needs a tiny learning rate to survive the steep walls, so it barely moves.
  4. Muon-like at constant LR. It gets close fast, then jitters around the minimum, because every step has the same length. Switch to Warmup + cosine and it settles. That’s exactly why schedules matter.

AdamW: weight decay done right

Weight decayWeight decay (L2 regularization)A penalty on the squared size of the weights that shrinks every weight slightly toward zero on each training step, favoring smoother functions that generalize better. shrinks every weight a little toward zero at each step, a classic regularizer. The textbook way to implement it is to add an L2 penalty λ2∥θ∥2\tfrac{\lambda}{2}\|\theta\|^2 to the loss, which adds λθ\lambda\theta to the gradient. For SGD that is the same as decaying the weights directly. For Adam it isn’t: the λθ\lambda\theta term gets divided by v\sqrt{v} along with the gradient, so weights with large gradient history are barely decayed and weights with small gradients are decayed heavily. The regularization ends up tangled with the gradient statistics.

AdamW (Loshchilov and Hutter, 2017) fixes this by decoupling the decay: compute the Adam step from the gradient alone, then separately shrink the weights by ηλθ\eta\lambda\theta. It is a one-line change that made weight decay behave predictably, and AdamW became the default optimizer for Transformers. Llama 2, for example, used AdamW with β2=0.95\beta_2 = 0.95 and weight decay 0.1.

Learning-rate schedules

Large models are almost never trained with a constant learning rateLearning rateThe step size in gradient descent. Too small is slow; too large overshoots or diverges.. A typical scheduleLearning-rate scheduleHow the learning rate changes during training, typically a short linear warmup followed by cosine or linear decay (or a warmup-stable-decay shape). has two or three phases:

  • Warmup. Start near zero and increase linearly for the first few hundred to few thousand steps. Early on, the weights are random, gradients are large and erratic, and Adam’s second-moment estimates are based on very few samples. Big steps then can push the model into a bad region or cause a loss spike.
  • Decay. Bring the learning rate down for the rest of training, commonly with a cosine curve to around 10% of the peak, or linearly. Large steps explore; small final steps settle into the bottom of the valley (as you saw with the Muon-like racer).
  • Warmup-stable-decay (WSD). Hold the learning rate constant for most of training and decay only in a short final phase. You can branch a decay off any checkpoint, which makes it easy to continue training or to run the annealing phase on high-quality data.

Muon: orthogonalized updates

MuonMuonAn optimizer that orthogonalizes the momentum update of each weight matrix (via Newton–Schulz iterations) before applying it. (MomentUm Orthogonalized by Newton–Schulz) was introduced by Keller Jordan in late 2024 and set speed records in the community NanoGPT training “speedrun”. It is designed for the 2D weight matrices in a network’s hidden layers; embeddings, the output head and scalar parameters keep using AdamW.

For each weight matrix WW, Muon:

  1. Keeps a momentum buffer MM of gradients, as in SGD with (Nesterov) momentum.
  2. Replaces MM by its nearest orthogonal matrix: same singular vectors, but every singular value set to (about) 1. If M=UΣV⊤M = U \Sigma V^\top, the update is UV⊤U V^\top.
  3. Steps W←W−η UV⊤W \leftarrow W - \eta \, U V^\top.

Why would that help? Gradient updates for Transformer weight matrices tend to be dominated by a handful of directions: their singular values are very uneven, so the matrix is nearly low-rank. A plain update spends almost all its “effort” on those few directions. Orthogonalizing boosts the rare directions to the same strength, so learning spreads across the whole matrix. Computing an exact SVD every step would be slow, so Muon uses the Newton–Schulz iterationNewton–Schulz iterationA few matrix multiplications that push all singular values of a matrix toward 1, approximately orthogonalizing it. Muon uses it on each update.: a few matrix multiplications that push all singular values toward 1 and run efficiently in BF16 on GPUs.

INTERACTIVENewton–Schulz orthogonalization
Gradient matrix G:
G (scaled)after 5 stepsdotted: unit circle
Polynomial
singular values of G
2.94, 0.05
ratio σ₁/σ₂ of G
61.9
after 5 steps
0.87, 0.70
ratio after
1.25
Smaller singular value after each step

The tuned quintic pushes small singular values up very fast, but only into a band around 1 (about 0.7–1.13 after five steps) rather than exactly 1; that is accurate enough for an update direction. The classic cubic converges exactly but needs many more steps when σ starts tiny.

A 2×2 gradient matrix maps the unit circle to an ellipse; its axes are the singular values. Each Newton–Schulz step pushes the ellipse toward a circle, meaning every direction gets an equal-strength update. Compare Muon's tuned quintic with the classic cubic.

Moonshot AI’s 2025 paper “Muon is Scalable for LLM Training” showed that two additions make Muon work at LLM scale: adding weight decay, and scaling each matrix’s update so its average size (RMS) matches what AdamW would produce, which lets you reuse AdamW’s learning rates and hyperparameters. In their scaling-law experiments Muon reached the same loss with roughly half the training FLOPs of AdamW. They trained Moonlight, a 3B-active/16B-total MoE, on 5.7T tokens with it, and Moonshot later trained Kimi K2 with a Muon variant called MuonClip (see the Kimi lesson). A bonus: Muon keeps one momentum buffer per parameter instead of Adam’s two, which saves memory (see distributed training).

MATH CORNER · optionalAdam's update, step by step, and the Newton–Schulz idea

Adam. With gradient gtg_t at step tt:

mt=β1mt−1+(1−β1) gt,vt=β2vt−1+(1−β2) gt2,m^t=mt1−β1t,v^t=vt1−β2t,θt=θt−1−η(m^tv^t+ϵ+λ θt−1)(the λ term is AdamW’s decoupled decay)\begin{aligned} m_t &= \beta_1 m_{t-1} + (1-\beta_1)\, g_t, & v_t &= \beta_2 v_{t-1} + (1-\beta_2)\, g_t^2,\\ \hat m_t &= \frac{m_t}{1-\beta_1^t}, & \hat v_t &= \frac{v_t}{1-\beta_2^t},\\ \theta_t &= \theta_{t-1} - \eta \left( \frac{\hat m_t}{\sqrt{\hat v_t} + \epsilon} + \lambda\, \theta_{t-1} \right) && \text{(the } \lambda \text{ term is AdamW's decoupled decay)} \end{aligned}

Worked example (one parameter, θ0=1\theta_0 = 1, η=0.1\eta = 0.1, β1=0.9\beta_1 = 0.9, β2=0.999\beta_2 = 0.999, λ=0\lambda = 0):

ttgtg_tmtm_tvtv_tm^t\hat m_tv^t\hat v_tstep ηm^/v^\eta \hat m / \sqrt{\hat v}θt\theta_t
12.00.2000.004002.0004.0000.10000.9000
21.00.2800.005001.4742.4990.09320.8068

The first step has size exactly η\eta, whatever the gradient’s scale: that’s Adam’s scale invariance. Without bias correction, step 1 would be 0.1×0.2/0.004≈0.3160.1 \times 0.2 / \sqrt{0.004} \approx 0.316, more than three times too large, because vv starts much closer to zero (relative to its true value) than mm does.

Newton–Schulz. Normalize X0=G/∥G∥FX_0 = G / \|G\|_F so all singular values are at most 1. Then iterate

Xk+1=aXk+b (XkXk⊤)Xk+c (XkXk⊤)2Xk.X_{k+1} = a X_k + b\,(X_k X_k^\top) X_k + c\,(X_k X_k^\top)^2 X_k .

If Xk=UΣV⊤X_k = U \Sigma V^\top, then XkXk⊤Xk=UΣ3V⊤X_k X_k^\top X_k = U \Sigma^3 V^\top, so the iteration leaves U,VU, V alone and maps each singular value through the polynomial p(σ)=aσ+bσ3+cσ5p(\sigma) = a\sigma + b\sigma^3 + c\sigma^5. The classic choice (a,b,c)=(1.5,−0.5,0)(a, b, c) = (1.5, -0.5, 0) converges to exactly 1, but slowly from small σ\sigma. Muon’s tuned coefficients (3.4445,−4.7750,2.0315)(3.4445, -4.7750, 2.0315) have a steep slope at zero, trading exactness for speed:

step012345
quintic, σ0=0.1\sigma_0 = 0.10.1000.3400.9920.7071.1070.712
cubic, σ0=0.1\sigma_0 = 0.10.1000.1500.2230.3280.4750.659

After five steps the quintic leaves singular values scattered roughly between 0.7 and 1.1, rather than exactly at 1. Empirically that’s good enough for an update direction.

In code

AdamW in PyTorch with a warmup + cosine schedule, and the core of Muon’s orthogonalization (adapted from Keller Jordan’s reference implementation):

import math, torch

opt = torch.optim.AdamW(model.parameters(), lr=3e-4, betas=(0.9, 0.95), weight_decay=0.1)
def lr_at(step, warmup=2000, total=100_000, floor=0.1):
    if step < warmup:
        return (step + 1) / warmup
    p = (step - warmup) / (total - warmup)
    return floor + (1 - floor) * 0.5 * (1 + math.cos(math.pi * p))
sched = torch.optim.lr_scheduler.LambdaLR(opt, lr_at)

def newton_schulz5(G, steps=5, eps=1e-7):
    a, b, c = 3.4445, -4.7750, 2.0315
    X = G.bfloat16() / (G.norm() + eps)
    if G.size(0) > G.size(1):
        X = X.T                      # work with the wide orientation
    for _ in range(steps):
        A = X @ X.T
        X = a * X + (b * A + c * A @ A) @ X
    return X.T if G.size(0) > G.size(1) else X
COMMON MISCONCEPTIONS
  • “Adam adapts the learning rate, so it doesn’t need tuning.” Adam rescales steps per parameter, but the global learning rate, schedule, β2\beta_2 and weight decay still matter a lot. Bad settings still cause divergence and loss spikes.
  • “AdamW is just Adam with L2 regularization.” That’s precisely what it isn’t. L2 regularization inside Adam gets divided by v\sqrt{v}; AdamW applies the decay directly to the weights, separately from the adaptive step.
  • “Warmup is only needed for bad initializations.” Warmup protects the early phase where gradients are large and Adam’s moment estimates are unreliable. It’s standard even with good initialization.
  • “Muon replaces Adam everywhere.” Muon handles the 2D hidden-layer weight matrices. Embeddings, the output layer, norms and biases are still typically trained with AdamW.
  • “Muon computes an SVD every step.” It approximates the orthogonal factor with five Newton–Schulz iterations, a few matrix multiplications, so the overhead is small.

Check your understanding

0/5 answered
  1. Q1.In a long, narrow valley aligned with one coordinate axis, why does Adam beat plain SGD?

  2. Q2.Rotate that valley by 45°. What happens to Adam's advantage?

  3. Q3.Without bias correction, what goes wrong in Adam's first steps?

  4. Q4.What does AdamW change compared with Adam + L2 regularization?

  5. Q5.What does Muon's Newton–Schulz step do to a momentum matrix M = UΣVᵀ?

Further reading

Progress is saved in this browser only.
Type to search across all lessons and glossary terms.