Going Downhill
Every model here learns by walking downhill on its loss, so why does it matter so much how you walk?
The part opens with four walkers in Rosenbrock's valley, gradient descent, the heavy ball, Adam and Lion, each at its best step size, and asks why they finish so far apart. Cauchy's gradient descent of 1847 is derived with its rate, which pays for the condition number; Polyak's heavy ball and Nesterov's method pay for its square root, and the measured contractions sit on the derived ones. Small batches make each step cheap and noisy, and the noise acts like a temperature set by the step size over the batch size; full-batch training on the spirals climbs to the edge of stability, where the sharpness hovers at 2 over the step. The part turns from one step size for all weights to geometry: Adam and its sign limit, weight decay that is not L2, the natural gradient and K-FAC, Shampoo and SOAP, and Muon, steepest descent under the spectral norm, computed by Newton-Schulz polynomials. Six optimizers then race on the character model with equal tuning, the same data order and three seeds. It ends with schedules and the river valley, schedule-free training, and what keeps very large runs from blowing up: QK-clip, gradient clipping and weight decay's equilibrium.
What you need. Multivariable calculus (gradients, a second-order Taylor expansion), eigenvalues and the singular value decomposition.
- Mathematics and history
- convergence rates, SGD as an SDE, edge of stability, momentum, Adam/AdamW, natural gradient, Shampoo, Muon, schedules
What you will be able to do
Undergraduate
- Explain why a step larger than 2 / L diverges on a bowl of curvature L, and what the condition number does to gradient descent.
- Describe what momentum, a random batch and Adam's per-weight step sizes each change about a gradient step.
Master's
- Derive the descent lemma and the linear rate of gradient descent, and the heavy ball's tuned momentum from the roots of its recurrence.
- Derive Adam's bias correction and its sign-descent limit, and show that decoupled weight decay and L2 differ under Adam.
- Derive Muon's step as steepest descent under the spectral norm, and one Newton-Schulz round as a polynomial on every singular value.
Research
- State the stochastic differential equation that models SGD, the stationary covariance it predicts, and the assumptions under which the step size over the batch size acts as a temperature.
- Derive the natural gradient as steepest descent under the Fisher metric, show its invariance to reparametrization, and state what K-FAC and Shampoo approximate.
Engineering
- Run a fair optimizer comparison: tune each baseline over a grid, match budgets and data order, use several seeds and report the spread.
- Choose a schedule (warmup, cosine, warmup-stable-decay or schedule-free) and diagnose a loss spike with gradient clipping, QK-clip or weight decay.
Contents
Each chapter has a home level. Choose a track to see what to read and watch: Undergraduate 14 min · Master's 45 min · Research 55 min · Engineering 23 min.
- 0Racing downhillUndergraduate2 min
- 1Gradient descent, derivedUndergraduate3 min
- 2The heavy ball and NesterovMaster's4 min
- 3Stochastic gradientsUndergraduate2 min
- 4Noise as temperatureResearch4 min
- 5The edge of stabilityMaster's3 min
- 6AdaGrad, RMSProp, AdamUndergraduate3 min
- 7Weight decay is not L2Master's2 min
- 8The natural gradient and K-FACResearch3 min
- 9Shampoo and SOAPMaster's3 min
- 10Muon, derivedMaster's3 min
- 11Newton-SchulzMaster's4 min
- 12The race, run fairlyEngineering3 min
- 13Schedules and the river valleyEngineering3 min
- 14Without a scheduleMaster's3 min
- 15Keeping training stableEngineering4 min
- 16The optimizer race, 2024 to 2026Research3 min
- Recap, problems, and what comes nextAll tracks2 min
Also on this page: Lecture · Key results · Try it · Lab · Problems · Notes and sources · 中文 · Build the film.
Lecture
The text of each chapter is the film's narration, as it is spoken, so you can read along or revise without the film. The pictures are in the film. A dashed box stands for a number the film computes when it is rendered (hover over it to see what is computed); the README's figures for each chapter, where it lists them, follow the chapter's text.
Racing downhillUndergraduate2 min
Every model in this series learns by walking downhill on its loss. But how you walk matters enormously. Here is a famous curved valley, Rosenbrock's, with its lowest point marked in white, and four walkers starting from the same place, each with its best step size from a grid of . Plain gradient descent, the heavy ball, Adam, and Lion. In steps, gets there first, in steps. This part is about why.
The idea is old. In 1847, Augustin Cauchy, solving the equations of planetary orbits, proposed stepping against the gradient: steepest descent. In 1951, Herbert Robbins and Sutton Monro showed that steps along noisy estimates still converge, if the steps shrink at the right rate. In 1964, Boris Polyak added momentum: a heavy ball. In 1983, Yurii Nesterov found the provably fastest way to use it. In 1986, backpropagation made gradients of networks cheap, and networks were trained by stochastic gradient descent with momentum for the next twenty-five years. Then came step sizes for every weight: AdaGrad in 2011, RMSProp in 2012, which was never published as a paper, only as a slide in Geoffrey Hinton's online course, and Adam in 2014, which trained almost everything for a decade. In 2018, Shampoo preconditioned whole matrices. In 2024, a public benchmark, AlgoPerf, measured the contenders fairly, and a new optimizer, Muon, appeared in a speedrun. In 2025 a version of it, MuonClip, trained Kimi K2, a model with a trillion parameters, and in 2026 DeepSeek trained its fourth generation with Muon too.
This is Part 11 of AI, Built. In it: why gradient descent converges, and how fast; momentum; what the noise of small batches does; why training lives at the edge of instability; how Adam is built, and why weight decay is not what it seems; optimizers that see the geometry of whole matrices, ending with Muon; a fair race between them on our own model; schedules; and how the field keeps very large runs from blowing up.
1Gradient descent, derivedUndergraduate3 min
In 1847 Augustin Cauchy, solving the equations of astronomy, proposed a general method: measure which way the error falls fastest, and step that way. To say how fast it works, we need two numbers. The loss is L-smooth if its curvature never exceeds L: it lies below a bowl of curvature L. It is mu-strongly convex if its curvature is never below mu: it lies above a bowl of curvature mu. Their ratio, kappa, is the condition number: how much more steeply the valley curves one way than another.
Now the derivation. Take one step. Because the loss lies below the bowl of curvature L, the step lowers it by eta times the gradient squared, minus a penalty of L eta squared over two. The best step this bound allows is eta equals one over L, and it guarantees a drop of the gradient squared over two L. Strong convexity says the gradient can't be small while we are far from the bottom: its square is at least two mu times the gap. Put the two together: each step shrinks the gap by a factor of one minus mu over L. Repeat, and the gap falls geometrically, one minus one over kappa per step. So the number of steps grows in proportion to the condition number. A valley a thousand times steeper one way than another needs about a thousand times more steps.
Using convexity alone gives a weaker guarantee: a bound proportional to one over k, the number of steps. Here is gradient descent on a quadratic with curvatures from one to a millionth. We do not use its tiny positive strong convexity; the bound is dashed.
Check it. Quadratic valleys in fifty dimensions, with condition numbers from one to a thousand, and gradient descent with step one over L. The steps it needs, on log axes, rise along a line of slope : The dashed line is the quadratic worst-case estimate; these valleys do better, because only one direction is slowest. For these quadratics, positions contract by one minus one over kappa in that slow mode. The
Pause and predict. On a valley thirty times steeper one way, a step of one over L is safe. What about a step just over two over L? The safe step slides down the long axis. The large one overshoots the steep axis by more each time and is thrown out: a step multiplies the distance by one minus eta lambda, and past two over lambda that is below minus one. Chapter five returns to this edge.
So: gradient descent's speed is set by the condition number, and ill-conditioned valleys are slow. Next, momentum, which turns kappa into its square root.
2The heavy ball and NesterovMaster's4 min
In 1964 Boris Polyak, in Moscow, asked how to speed gradient descent up, and answered with physics: give the walker mass. Each step adds a fraction beta of the previous step. On the steep axis, successive steps point in opposite directions, so the memory cancels them out; on the long, gentle axis they all point the same way, so the memory adds them up. The heavy ball sways across the valley a little, but it travels down it much faster: after sixty steps it is 103 times closer to the bottom than gradient descent.
Why does it work, and how fast? On a quadratic, every direction of the valley is separate. Along a direction of curvature lambda, the update is a recurrence in the last two positions. Try powers of a number z, and z must solve a quadratic equation. When its roots are complex, their modulus is the square root of beta, whatever lambda is. This sets the oscillation envelope, not the change in position at every step. So choose eta and beta to put every curvature between mu and L into that spiralling regime: the two ends of the range just on its edge. Solving, the square root of beta is root kappa minus one over root kappa plus one. The endpoints have repeated roots, which can add a factor of k to the decay. For large kappa, the root modulus is about one minus two over root kappa: the steps now grow with the square root of the condition number. A thousand becomes about thirty.
In 1983 Yurii Nesterov, also in Moscow, changed one thing: take the gradient not where you are, but where momentum is about to carry you. With that look-ahead, the acceleration is guaranteed on every smooth convex function, not only on quadratics: the gap falls like one over k squared instead of one over k. And Arkadi Nemirovski and David Yudin had shown that no method using only gradients can do better in the worst case: Nesterov's rate is optimal.
Back to Chapter 1's fifty-dimensional valleys, now with momentum. Gradient descent rises with slope . The heavy ball and Nesterov rise with slopes and : At kappa a thousand that is steps against and . And the late geometric-mean ratios for the square root of the gap are for heavy ball, against root modulus ; Nesterov , against . One warning. The heavy ball's guarantee is for quadratics: on other convex losses there are examples where it circles forever. Nesterov's form is the one with a proof.
So momentum is memory: it cancels the zigzag and accumulates the slope, and turns kappa into its square root. But every gradient so far was exact. Real training can only estimate it.
3Stochastic gradientsUndergraduate2 min
The loss of a model is an average over its training examples, and so is its gradient. Computing it exactly means going through all the data for every single step; real models train on trillions of words. Instead, average over a small random batch. On average that estimate is exactly right. For independent draws the covariance falls like one over B; sampling without replacement adds a finite-population correction. Herbert Robbins and Sutton Monro, statisticians at North Carolina, asked in 1951 when steps along such noisy estimates still reach the answer.
Here's a real loss with two weights: part six's logistic regression, telling Austen from Dickens by two word rates. With all 448 training pages, each step goes straight downhill. With sixteen random pages per step, the path wobbles, but each step costs 28 times less. With one page at a time it is wild, but it still heads for the bottom.
Keep a constant step, and the walker never quite stops: it jiggles around the bottom forever, in a cloud. Robbins and Monro's answer: let the steps shrink, but not too fast. Their sum must be infinite, so the walker can still get anywhere; the sum of their squares must be finite, so the total noise it collects is finite. A step that shrinks like one over k does both. Measured:
This noisy method became the workhorse of neural networks. The 1986 backpropagation paper already trained with momentum. Yann LeCun, Leon Bottou and colleagues wrote down the practical craft in 1998: update after every example or small batch, shuffle the data, normalize the inputs. And in 2012 AlexNet, the network that started the deep learning boom, was trained by stochastic gradient descent with momentum zero point nine, dividing the step by ten whenever progress stalled.
So a random batch gives a gradient that is right on average and cheap, at the price of noise. With a constant step, training ends in a cloud around the bottom. How big is that cloud, and is the noise only a cost?
4Noise as temperatureResearch4 min
How big is the cloud? Part five's stochastic differential equations answer it. A step of stochastic gradient descent is the true gradient step, plus the batch's noise, with covariance sigma over B. Call the step size eta a small time interval, dt. The noise term is approximated by the square root of dt, times a Gaussian, times the square root of eta over B. This Gaussian surrogate is one Euler step of a stochastic differential equation: a push downhill, plus random kicks whose strength is eta over B. The learning rate and the batch size enter through their ratio in this approximation. It acts like a temperature; general SGD noise need not be isotropic or thermal.
Near a strict minimum, assume stable small steps and nearly constant noise covariance. Linearize the gradient as the Hessian times the distance. The cloud then approaches a stationary covariance: its covariance S comes out of each step the same as it went in. That is an equation for S. For small steps it simplifies to H S plus S H equals eta over B times the noise's covariance C. Take the trace: the cloud's mean squared size is eta over two B, times the trace of H inverse C. For our two-weight loss that trace is , close to two. For a well-specified likelihood at its population optimum, the score covariance and Hessian match; our example is close to that idealization.
Measure it. Four learning rates, six batch sizes, three seeds each: twenty-four clouds. Plotted against the temperature, eta over B, The dashed line is the predicted stationary size.
This explains a rule found by experiment. Multiply the batch by k, and the learning rate by k too: the temperature stays the same. In 2017 a Facebook team used it, with a short warmup, to train an ImageNet classifier on batches of eight thousand images in one hour. For Adam, which divides by the gradient's size, the analysis says scale by root k within the SDE regime, while also scaling the momentum time scales and epsilon. It is not a universal large-batch rule. And past a critical batch size the noise is already small, and bigger batches stop buying fewer steps; Part twelve measures where.
Is the noise only a cost? On the real loss, sixteen times the batch gives a cloud 3.8 times narrower, close to root sixteen. Now picture a sharp pit beside a wide basin: a hot walker is kicked out of the pit and settles where the valley is wide. In 2017 Nitish Keskar and colleagues found that very large batches end in sharper minima that generalize worse. The same year Laurent Dinh and colleagues found the catch: rescale one layer up and the next down, and the same function has a different sharpness. Flatness is a useful picture, not a law.
In this local, small-step approximation, SGD has an effective temperature, eta over B, which sets the size of the cloud it ends in, and keeping that ratio fixed is the linear scaling rule. But how large can the step itself be?
5The edge of stabilityMaster's3 min
Chapter one ended with a valley that threw the walker out. Here is the reason, on the simplest possible loss: a bowl with curvature lambda, and a step of size eta. Each step multiplies the distance from the bottom by one minus eta times lambda. If that's between minus one and one, the steps shrink and settle. If eta times lambda is more than two, each step overshoots further than the last, and it blows up. So gradient descent can only be stable where the curvature is below two over eta.
The classical advice follows: measure the sharpness, the largest curvature, the Hessian's top eigenvalue, and choose a step below two over it. But training changes the landscape it walks on. Pause and predict: on a real network, at a fixed step, what does the sharpness do as training goes on?
Here is the answer, measured: the spirals from part nine, trained with the full gradient at two step sizes. Every forty steps we estimate curvature with twenty power iterations. Interpreting this signed estimate as the largest eigenvalue assumes convergence and a positive dominant-magnitude eigenvalue. Here, Double the step size, and Cohen and colleagues reported training near the edge in 2021. These traces test that behavior here.
Why? While the sharpness is below two over eta, training tends to make the valley steeper: progressive sharpening. Once it passes the edge, the walker starts to bounce along the steepest direction, further each step. But the bounce carries it to where that direction curves less, and the sharpness falls back. Alex Damian, Eshaan Nichani and Jason Lee showed in 2022 that the two effects balance exactly at the edge. Gradient descent regulates its own curvature.
The edge moves with the optimizer. With momentum beta, a step can survive more curvature, up to two plus two beta over eta. Adam lives at an edge too: the curvature measured after its rescaling rises to thirty-eight over eta, the same rule for its momentum of zero point nine. Jeremy Cohen and colleagues, with researchers at Google, measured it in 2022. It is one reason a run needs to start with small steps, which comes back in Chapter 13.
Training can approach its stability edge, so the step size can shape the curvatures it visits. Next, optimizers that give every weight a step size of its own.
6AdaGrad, RMSProp, AdamUndergraduate3 min
One learning rate for every weight is a strange choice: some weights see large gradients, others tiny ones. In 2011 John Duchi, Elad Hazan and Yoram Singer proposed AdaGrad: divide each weight's step by the root of its summed squared gradients. A rare word gets a big step when it does appear. The catch: the sum only grows, so every step shrinks like one over root t for a steady gradient, and a long run slows to a crawl.
The fix came from an online course. In 2012 one slide of Geoffrey Hinton's Coursera class proposed RMSProp: an average that forgets, nine tenths old plus one tenth new. It was never written up; papers cited the slide.
In 2014 Diederik Kingma and Jimmy Ba combined the two. m, a running average of the gradient: momentum. v, a running average of its square: RMSProp. Correct both for starting at zero, and step by m over the root of v. This is Adam, the default for the next decade.
Why the corrections? Unroll m from zero: a weighted sum of the gradients so far. If their mean is steady, its expectation is that mean times a geometric sum, one minus beta to the t: early on m is biased towards zero, and dividing removes it. One weight of our model, its first sixty steps: raw m starts near zero, the corrected one tracks the gradients at once. Without the corrections the first step would be about times eta; with them, nearly eta when the gradient is large compared with epsilon.
Now Adam's limit. Turn both memories off and let epsilon go to zero: the gradient over its own size is its sign for a nonzero gradient; a zero gradient gives no sign step. Here is how far each weight of our hidden matrix moves, in units of eta. At the first step, about of the weights move by more than zero point nine eta.
That limit became an optimizer. In 2023 a Google team searched over programs for update rules and found Lion: step by the sign of a blend of momentum and gradient, then update the momentum more slowly. One state per weight, not two, and since its nonzero sign component is full size, a smaller learning rate and a larger decay. It runs in our race in Chapter 12.
So Adam is momentum over a running size, corrected for its start; its limit is sign descent. Next, a subtle bug in how it was used for years.
7Weight decay is not L2Master's2 min
There are two ways to keep a network's weights small. Add a penalty to the loss, lambda over two times the squared size of the weights: L2 regularization. Take a gradient step on it, and the penalty contributes lambda times theta. Rearranged, that is: shrink every weight by a factor one minus eta lambda, then take the ordinary step. Weight decay. For plain gradient descent the two are identical, so for decades the words were used interchangeably.
Adam breaks that equivalence. Put an L2 penalty into Adam, and the penalty's pull goes through Adam's division by the root mean square gradient. A weight whose gradients are large is barely decayed at all, and one whose gradients are tiny is decayed hard: the opposite of what one would want. Ilya Loshchilov and Frank Hutter pointed this out in 2017, and proposed applying the decay directly to the weights, outside Adam: AdamW. It became the default optimizer of the transformer era.
Does it matter? A test where regularization should matter: a smaller character model that sees only fifty thousand characters of training text, over and over. On the left, AdamW at five learning rates and six decay strengths; on the right, Adam with an L2 penalty, on the same grid of rates. Brighter is better. The best of each, rerun from three seeds:
Watch the held-out loss during training, seed zero. In large language models trained on fresh data, it does something else, which Chapter fifteen measures.
So in Adam, an L2 penalty and weight decay are different things, and the decoupled version is the one the field adopted. Next, a deeper question: what is the right way to measure the size of a step at all?
8The natural gradient and K-FACResearch3 min
Gradient descent has a hidden assumption. Take Chapter three's two-weight loss, and write the second weight four times as large: the same model, the same loss, a new label on one axis. Gradient descent now takes a different path, because the steepest direction depends on how you measure a step. In general, the steepest step under a ruler M is minus M inverse times the gradient. Gradient descent is the choice M equals the identity: every weight counts the same, whatever it means.
In 1998 Shun-ichi Amari proposed the ruler that doesn't care about labels: measure a step by how much it changes the model's predictions. For a small step, part one's KL divergence between the old and new predictions is a quadratic form, and its matrix is the Fisher information: the covariance of the model's own score, with the labels drawn from its own predictions. The steepest step in that ruler is the natural gradient, minus eta F inverse g. On our two-weight loss, written both ways, its two paths are one path. It sees the model, not the coordinates.
The catch is size. The Fisher has one row and one column per weight: for our tiny spiral network, 722 by 722, for a billion-weight model, a billion billion entries. In 2015 James Martens and Roger Grosse found a shortcut. A layer's weight gradient is an outer product, the gradient at its output times its input. So its block of the Fisher is the expected Kronecker product of the two outer products. Pretend the inputs and the gradients are independent, and it factors into a Kronecker product of two small matrices: the inputs' second moment A and the output gradients' G. A Kronecker product inverts factor by factor, so the natural gradient of a layer becomes G inverse, times its gradient, times A inverse. That is K-FAC: Kronecker-factored approximate curvature.
Race them on part nine's spirals: gradient descent, Adam, damped K-FAC and a damped full-Fisher natural gradient, each at its best of five learning rates, three seeds each. After a hundred steps, the order is , then , and . On the right, what the network believes, as it trains: gradient descent's map and the natural gradient's, at the same steps. The full Fisher acts on parameters. Here a Woodbury identity computes the damped direction through a smaller system of equations, one per training example. At scale, even full-Fisher geometry is costly, so K-FAC uses layer factors. Next chapter's Shampoo uses a related Kronecker idea.
So the natural gradient measures a step by what it does to the model, and K-FAC makes that affordable with two small matrices per layer. Next, Shampoo, which gets its two matrices from the gradient alone.
9Shampoo and SOAPMaster's3 min
Adam and AdaGrad treat each weight on its own. The full version of AdaGrad would precondition by a matrix with a row and a column for every weight of the layer, which no one can store. In 2018 Vineet Gupta, Tomer Koren and Yoram Singer, at Google, used the shape of a layer. Keep two small running sums instead: G G transpose, over the rows, and G transpose G, over the columns. They proved that the big matrix is bounded by a Kronecker product of the two. So precondition the gradient matrix from both sides, by the inverse fourth roots of L and R. They called it Shampoo: K-FAC's Kronecker trick, with both factors taken from the gradient itself.
Here is a surprise hidden in Shampoo. Switch off its memory, so the two factors come from the current gradient alone. Use the compact singular value decomposition on its nonzero singular directions, from part three. Then L to the minus a quarter, and R to the minus a quarter, are built from the same singular vectors, with the singular values raised to minus a half. Multiply out, using inverse roots on that nonzero support, and every nonzero singular value cancels: what is left is U V transpose, the gradient with all its nonzero singular values set to one. Jeremy Bernstein and Laker Newhouse pointed this out in 2024. Remember that matrix: it is Muon's step.
Shampoo was hard to use. Inverse fourth roots need eigendecompositions, which are slow, so they are refreshed only every few steps; the factors are badly conditioned and need damping; and the size of its step is awkward, so practical versions graft on Adam's size and keep only Shampoo's direction. Engineers at Meta and Google made it practical as Distributed Shampoo, and in 2024 it won the external-tuning track of AlgoPerf, a benchmark that times training algorithms to a target on eight workloads with fixed hardware: about twenty-eight percent faster than the baseline, counting its extra cost per step.
In 2024 a group at Harvard simplified it. Shampoo's two factors have eigenvectors: a rotation of the rows, and one of the columns. Rotate the gradient into those bases, run plain Adam there, coordinate by coordinate, and rotate the step back. The rotation is refreshed every few steps; Adam does the rest. They called it SOAP, and reported reaching AdamW's loss in over forty percent fewer steps in large-batch runs on language models of up to six hundred and sixty million parameters. Shampoo, it turns out, is close to a cheap form of Adam in its own eigenbasis. SOAP runs in our race too.
So Shampoo preconditions a whole matrix with two small factors, SOAP runs Adam in their eigenbasis, and Shampoo without memory is the orthogonalized gradient. Next, why that matrix is the steepest step of all.
10Muon, derivedMaster's3 min
Adam treats every weight separately. But a layer's weights form a matrix, and a matrix has structure: part three's singular values. Here is a real gradient matrix from our character model. A few directions dominate: the largest ten of its 256 singular values carry 77% of its squared size. A step along it mostly pushes those few directions further. In December 2024 Keller Jordan and collaborators published Muon, after it set records in a public speedrun to train a small GPT. Muon replaces the gradient's singular values by ones: the same push in every direction.
Why set the singular values to one? Because it is the steepest step under the right notion of size. A layer multiplies its input by W. The most a step can change the output, relative to the input, is the step's largest stretch: its spectral norm. That is the natural size for a matrix. Picture what a matrix does to a circle of directions. The gradient stretches it into a long thin ellipse; Muon's step keeps it a circle. Ask for the step that lowers the loss fastest, to first order, among all steps that stretch nothing by more than eta. Write the gradient in its singular directions. Each term can be pushed down by at most eta times its singular value. And one step achieves every bound at once: minus eta times U V transpose.
This puts the optimizers of this part in one family. Bound the step by its Euclidean length, and the steepest step is the normalized gradient. Bound every weight separately, and it is the sign of the gradient: Adam's limit, and Lion. Bound each matrix by how much it can stretch a vector, and it is U V transpose: Muon. The difference between them is only the ruler.
Muon in practice, as Moonshot AI scaled it up in 2025. Keep momentum on the gradient, orthogonalize the look-ahead, with five rounds of Newton–Schulz, the next chapter, and step, with weight decay, scaled by zero point two times the square root of the larger dimension. That scale makes the typical entry of Muon's ideal step about zero point two times eta in entry RMS. Five rounds approximate that factor; Adam's median is a different size statistic. Our own Adam, in Chapter six, moved its median weight by eta. Muon is only for the hidden matrices; embeddings, the output layer and the small vectors stay with AdamW.
So Muon is steepest descent when a matrix's step is measured by how far it can stretch a vector, and its step is the gradient with every singular value set to one. Computing that exactly takes an SVD, which is slow on a GPU. Next, how Muon avoids it.
11Newton-SchulzMaster's4 min
An SVD is slow on a GPU, but multiplying matrices is what a GPU does best. So scale the gradient so its singular values are at most one, and repeat a round made only of products: X becomes a X, plus b X X transpose X, plus c times X X transpose squared, X. Write X by its singular value decomposition, which we never actually compute. Inside each product the U's and V's cancel, and the round leaves the singular vectors alone. It just applies one polynomial, p of sigma, to every singular value at once. So the whole problem is a question about one function of one variable: which polynomial, repeated, sends everything between zero and one to one?
Three candidates. The classical cubic, one and a half sigma minus half sigma cubed, fixes one with zero slope, so near one it converges fast; but its slope at zero is only one and a half, so tiny values grow slowly. Keller Jordan tuned a fifth-degree polynomial for Muon: slope three point four at zero, so small values grow fast, at the price of never quite reaching one; everything ends between about zero point seven and one point three, which training doesn't mind. A third, two sigma minus one and a half sigma cubed plus a half sigma to the fifth, also fixes one with zero slope, and near one it squares the error's magnitude and halves it, three times better than the cubic.
Now on real data: the gradient matrix from Chapter ten. Follow one middling starting singular value through Jordan's polynomial. Here are all singular values, sorted afresh each round. Set n to the initial count above a hundredth of the largest: . After rounds, the current largest n sit between and . This summarizes ranks, not the same initial directions; smaller current values are excluded from this summary. For the current largest n, the classical cubic in the same rounds has worst distance from one, and needs
The newest practice combines them. For each matrix, fix n as its initial count above a hundredth of the largest singular value. Each curve shows the worst distance from one among the current largest n, not the full spectrum or the same initial directions. Jordan's displayed sequence ends at . DeepSeek's fourth generation, in 2026, runs eight rounds of Jordan's polynomial and then two of the exact one, which settles values already close: on our gradient the worst distance within that current top n ends at from one. The dashed curves use the trained weight matrix's own n. And in 2025 Noah Amsel and colleagues derived the best polynomial for each round, the Polar Express: the search for cheap orthogonalization is still on.
So orthogonalizing is a polynomial applied to every singular value at once, using nothing but matrix products, and choosing that polynomial trades speed against exactness. Now let's race all the optimizers of this part, fairly, on our own model.
12The race, run fairlyEngineering3 min
Now a fair race between this part's optimizers, on our character model. Same batches in the same order, same three thousand steps, same schedule. Each one, SGD with momentum, AdamW, Lion, Shampoo, SOAP and Muon, gets its own grid of learning rates, a factor of two apart: six initial rates, with up to three edge extensions. A method can look bad from the wrong rate. The best runs again from two more seeds, so we can see what is luck.
First the learning-rate sweeps. Each optimizer's final loss on the full validation slice against its learning rates: too small and it crawls, too large and it overshoots, and in between a valley. Its lowest point is the rate it races at.
Now the race itself, replayed: curves use the first twenty thousand validation predictions, the line the median of three seeds, the band their spread. Final standings use the full validation slice. Last comes , at .
What do these numbers read like? Here SGD with momentum and the best non-SGD comparison, , continue the same three words with the same sampling seed, at checkpoints of their seed-zero runs. The displayed bits are interpolated from the twenty-thousand-prediction validation curve. Before training, the random model scores bits per character: noise from the whole alphabet. Here is its text after steps. Here it is at step . And by the end, at bits for ,
Steps are not free, though. Here is each optimizer's mean timed-loop wall time per step across three seeds, relative to AdamW, on this computer: Muon times, Shampoo times. This includes periodic validation and four seventy-two-character samples, excluding initial and final evaluation. Take that with care: one shared processor thread, and a model so small that the extra matrix work is a large share of each step. For large language models on GPUs, Muon's author estimates its extra arithmetic at under one percent, and AlgoPerf scores optimizers by wall-clock time for exactly this reason.
So on our model, with every optimizer at its own best rate and equal steps, SOAP came first. The rate was tuned for each, and the schedule fixed for all. Next: how that schedule should be shaped.
13Schedules and the river valleyEngineering3 min
Chapter three's lesson was that a constant step ends in a cloud, and only a shrinking step settles. So real runs change the learning rate as they go. Almost all begin with a warmup: a short ramp, sixty tiny, growing steps here, while the weights are random, Adam's running sizes are still unknown, and, as Chapter five showed, the landscape is sharp. For years the standard was a cosine, from Ilya Loshchilov and Frank Hutter in 2016: glide smoothly from the peak to zero. The newer standard holds the rate flat for most of the run and decays it only at the end: warmup, stable, decay, popularized by the MiniCPM team in 2024.
Why does holding the rate high, then dropping it, work so well? In 2024 Kaiyue Wen and colleagues at Stanford offered a picture: a river valley. The loss has a valley floor, a river, that descends slowly, and steep hills on either side. With a large constant step, the noise throws the walker up the hills, but it travels fast down the river. With a small step it stays near the floor, but crawls. This WSD-style toy omits warmup: it travels down the river at the high rate, then drops onto the floor at the end.
Split the loss into its two parts. At a constant rate, the last hundred steps have mean hill loss . A fixed-x linear hill reference gives ; this bent valley also has noisy, coupled motion along x. The river part measures progress along the valley; here the larger rate moves faster. At the end, Decay can reduce transverse noise while also changing progress along the river; it need not preserve the same trajectory.
Now on our character model, with AdamW. Three cosine runs, one for each length: a thousand, two thousand and four thousand steps. And a single constant-rate run, with a branch leaving it at four fifths of each length to cool down. The constant run plateaus. Each branch drops sharply as its rate falls: at the end, by bits below the constant run. The verdict: One shared constant-rate trunk plus short cool-down branches gave all three. Here that costs five thousand four hundred training updates per seed, instead of seven thousand for three independent runs, plus evaluation overhead.
So a high learning rate travels; a falling one settles; and warmup, stable, decay lets you decide when to settle after the fact. Can we drop the schedule altogether?
14Without a scheduleMaster's3 min
Go back to Chapter three's cloud. The walker keeps fluctuating around the solution. So don't take the last position: take the average of all of them. David Ruppert, and Boris Polyak with Anatoli Juditsky, proved asymptotic efficiency under stochastic-approximation assumptions; that is not a guarantee for this fixed-step nonlinear cloud. Here all cached cloud points are typically 0.49 from the best weights; their running average ends 0.154 away. Deep learning uses a version that forgets the start: an exponential moving average of the weights.
Apply it to Chapter thirteen's constant-rate run: keep an average of the weights with a memory of about five hundred steps, and score the average instead. Averaging and a learning-rate cool-down can both reduce fluctuations.
In 2024 Aaron Defazio and colleagues turned averaging into an optimizer with no schedule at all. Keep two sets of weights: a fast walker z, stepped at a constant rate, and its running average x, which is the model you use. The trick is where the gradient is taken: at y, a point between the two. With beta at zero it is plain averaging; at one, the gradient is taken at the average itself; nine tenths works in practice. Schedule-free AdamW won the self-tuning track of AlgoPerf in 2024, about eight percent faster than the baseline, with no learning-rate schedule to tune.
Does it work here? Schedule-free AdamW on our character model, its learning rate chosen from four multiples of AdamW's, the best being times. One run of steps, scored as it goes, against the scheduled runs of Chapter thirteen, each trained for one length. The verdict: Checked on all our held-out text at steps: schedule-free bits, cosine , warmup–stable–decay .
In a stable local quadratic model, averaging can reduce fluctuations around the solution. Schedule-free methods build averaging into the updates and can reduce the need for a scheduled learning-rate cool-down. Next: what happens when training doesn't just wander, but blows up.
15Keeping training stableEngineering4 min
Large runs sometimes blow up, and Part eighteen tells that story at scale. Here is one mechanism, provoked on purpose in a one-layer transformer on our books. The curves show seed zero's pre-update forward scores, recorded every ten steps. Across two seeds, the mean of each run's largest recorded score is about with Muon at the moderate rate. At four times the rate that mean is about . Large differences between scores can make the softmax nearly a hard choice and weaken gradients through it. Raw maxima alone do not measure that.
In 2025 Moonshot AI met exactly this training Kimi K2 with Muon, and fixed it surgically. Record each head's largest score during the forward pass, then take the optimizer step. For frozen inputs and weights, scaling both query and key matrices by root gamma scales the score by gamma. Use the stored forward score to choose gamma, then rescale the updated matrices as feedback. There is no hard cap at tau on post-update or next-batch scores. With tau at a hundred, Kimi K2, a trillion parameters on fifteen and a half trillion tokens, reports zero loss spikes.
On our small transformer, with QK-clip at tau a hundred, the largest recorded pre-update forward score across the two fast Muon seeds is about ; recording is every ten steps, The AdamW runs compare QK-clip with gradient clipping, from 2013: whenever the raw gradient is longer than c, shrink it to length c before the optimizer update. This caps the gradient norm, not AdamW's parameter-step length. QK-clip, which targets the cause, gives and .
Weight decay has a second life. Most weight matrices are followed by a normalization, so W and twice W give the same network. Then the gradient is orthogonal to W. Decay shrinks W by a factor; Adam's update u need not be orthogonal to it. Model the updates as stationary noise whose correlations decay like momentum. At small decay, their cumulative effect balances the shrinkage. This model predicts a norm proportional to root eta over lambda. So here weight decay doesn't regularize: it sets the size at which each step is a fixed fraction of the matrix, an effective learning rate.
Measured on our character model, with a normalization after its second hidden matrix, at three decay strengths, each four times the last: each norm settles to a level, faster for stronger decay. Without the momentum factor the prediction would be for the first, far too small. And four times the decay halves the norm: the fitted power is , against minus a half derived.
So the best fixes target causes: QK-clip feeds forward scores back into query and key rescaling after the update; gradient clipping caps the raw gradient norm, and weight decay sets the size of normalized matrices. Finally: the optimizer race since 2024.
16The optimizer race, 2024 to 2026Research3 min
In two years the race moved from small benchmarks to the largest models. In 2024, AlgoPerf crowned Distributed Shampoo, and Muon set records in a speedrun. In February 2025 Moonshot AI scaled Muon to a sixteen-billion-parameter mixture of experts, Moonlight, and reported about twice AdamW's efficiency in compute-optimal training. In July they trained Kimi K2, a trillion parameters, with MuonClip. Zhipu's GLM-4.5 used Muon too. Then came careful, independent benchmarks, and smaller numbers. And in 2026 DeepSeek trained its fourth generation with Muon for most of the model, using the hybrid Newton–Schulz of Chapter eleven, and normalizing queries and keys instead of clipping them.
How big are the gains really? New optimizers had claimed one and a half to two times AdamW's speed. In 2025 Kaiyue Wen, David Hall, Tengyu Ma and Percy Liang at Stanford tested eleven of them with equal care, tuning every one, AdamW included, on models up to one point two billion parameters. Tuning AdamW's learning rate alone could double its speed on a small model: many claimed gains were against weak baselines. The best, the matrix-based ones, Muon and SOAP, were about one point four times faster at a hundred million parameters, and only one point one times at a billion. Muon led with little data per parameter, SOAP with a lot. In 2026 a team at NVIDIA trained mixtures of experts up to seventy-two billion parameters with Muon and modified SOAP or KL-SOAP. They found these variants stable at batches of a hundred million tokens where AdamW degraded, with modest, mixed gains.
Meanwhile the descendants multiply. For Muon: better polynomials, like the Polar Express; Microsoft's Dion, which splits the work across machines, and its 2026 successor, reporting Muon's loss with a step up to six times faster; and a stream of 2026 preprints. For Shampoo: Distributed Shampoo, SOAP, and larger-scale variants. Most of these claims are their authors' own. Which is the race's real lesson: tune the baseline as hard as the newcomer, compare at equal budgets, use several seeds, and report the spread.
So by 2026 the matrix optimizers had won a place at the frontier: Muon trains some of the largest open models. But measured carefully, their edge over a well-tuned AdamW is real, smaller than first claimed, and shrinks as models grow.
Recap, problems, and what comes nextAll tracks2 min
Let's take stock. On our strongly convex quadratics, rate-based step estimates scale with the condition number for gradient descent and with its square root for appropriately tuned momentum, at fixed accuracy. A random batch makes each step cheap and noisy; in a stable local, small-step model, eta over B acts like a temperature for the stationary cloud. In our full-batch fixed-step example, a signed power estimate tracks curvature near two over eta; this is observed behavior, not a universal rule. Adam rescales every weight and in its limit is sign descent; Shampoo and Muon see whole matrices. Muon's ideal polar step, steepest under the spectral norm, sets nonzero singular values to one; its practical polynomial approximates that step. In a fair race on our own model, came first. A high learning rate travels down the river and a falling one settles, and a stationary correlated-update model predicts how weight decay sets a normalized matrix's scale.
All of this comes back. Part twelve measures the critical batch and keeps a learning rate as models grow wider and deeper. The transformers of parts thirteen and fourteen train with AdamW and a warmup. Part eighteen trains a model with the full modern recipe, Muon included, and keeps it stable at scale. And reinforcement learning and fine-tuning, in parts twenty-six and twenty-seven, run on the same optimizers.
Here are six problems, from gradient descent's rate to weight decay's equilibrium. Pause here and work through them; full solutions are in this part's notes.
Next time: the mathematics of scale. Why bigger models get better so predictably, how to split a budget between parameters and data, and how to choose a learning rate once and keep it as the model grows. Straight lines on log–log plots, and what they promise.
Bottou, Curtis and Nocedal's survey is the best single account of stochastic optimization, and Jeremy Bernstein's essays explain Muon's geometry. Thanks for watching, and see you in part twelve.
Where it goes next. The critical batch is measured and the learning rate carried across width and depth in Part 12; the transformers of Parts 13 and 14 train with AdamW and a warmup; Part 18 trains with the full recipe, Muon included, and keeps it stable at scale; Parts 26 and 27 run reinforcement learning and fine-tuning on the same optimizers.
Key results
The part's results in one place, for revision.
Try it
Lab 11 · Three ways downhill, against their derived rates
Run gradient descent, the tuned heavy ball and Nesterov's method on a 50-dimensional quadratic with condition number 1,000, with gradients from the series' autodiff, and compare each one's measured contraction per step with the rate the part derives. Then count the steps to a millionth of the starting gap as the condition number grows.
python -m videos.ai.labs 11
needs numpy, scipy, matplotlib · download lab11.py ·
source on GitHubgradient descent: contraction per step 0.9990 (derived 0.9990)
heavy ball: contraction per step 0.9432 (derived 0.9387)
Nesterov: contraction per step 0.9709 (derived 0.9684)
steps to 1e-6 of the gap, kappa = 1,000 gradient descent 3,412 heavy ball 156 Nesterov 159
slope of steps against kappa (log axes) gradient descent 0.91 heavy ball 0.56 Nesterov 0.46 (theory 1, 1/2, 1/2)
gradient descent with step 2.05 / L gap grows 3.2e+14 times in 400 steps
Plain gradient descent pays for the condition number, momentum for its square root: each measured contraction sits on the root of its recurrence, and a step past 2 / L does not converge at all.
The code (124 lines; it asserts its own result)
"""Lab 11: race gradient descent, the heavy ball and Nesterov down a quadratic valley, against their derived rates."""
import numpy as np
from videos.coursekit import labs
from explainer.ai.autodiff import Tensor
TITLE = "Three ways downhill, against their derived rates"
GOAL = ("Run gradient descent, the tuned heavy ball and Nesterov's method on a 50-dimensional quadratic with condition "
"number 1,000, with gradients from the series' autodiff, and compare each one's measured contraction per step "
"with the rate the part derives. Then count the steps to a millionth of the starting gap as the condition "
"number grows.")
TASKS = [
"Run gradient descent with step=1.9, 2.0 and 2.05 (in units of 1/L). Which direction grows, and by what factor a step?",
"Give the heavy ball Nesterov's momentum (drop the square in `beta`) and compare its step count at kappa = 1,000.",
"Replace the quadratic by sum(h * x**4): the loss is still convex. Do the three rates still hold?",
]
def make_loss(h):
"""f(x) = 1/2 sum_i h_i x_i^2 as an autodiff graph; returns a function x -> (f, gradient)."""
def f_and_grad(x):
t = Tensor(x, requires_grad=True)
loss = ((t * t) * h).sum() * 0.5
loss.backward()
return float(loss.data), t.grad
return f_and_grad
def run_method(name, h, x0, steps, step=1.0):
"""The objective gaps f(x_k) - f* (f* = 0) along a run of one method with its textbook tuning; ``step`` is
gradient descent's step in units of 1/L."""
L, mu = h.max(), h.min()
kappa = L / mu
f = make_loss(h)
x, prev, gaps = x0.copy(), x0.copy(), []
for _ in range(steps):
if name == "gd": # x - (1/L) grad
val, g = f(x)
new = x - step * g / L
elif name == "heavy": # Polyak (1964): tuned step and momentum
beta = ((np.sqrt(kappa) - 1) / (np.sqrt(kappa) + 1)) ** 2
eta = 4 / (np.sqrt(L) + np.sqrt(mu)) ** 2
val, g = f(x)
new = x - eta * g + beta * (x - prev)
else: # Nesterov (1983): the gradient is taken at the look-ahead point
beta = (np.sqrt(kappa) - 1) / (np.sqrt(kappa) + 1)
val = f(x)[0]
y = x + beta * (x - prev)
new = y - f(y)[1] / L
gaps.append(val)
x, prev = new, x
return np.array(gaps)
def late_ratio(gaps):
"""The geometric-mean contraction of sqrt(gap) per step, over the stretch where the gap falls from 1e-6 to 1e-12
of its start (late enough for the slowest direction to dominate, early enough to stay above rounding)."""
rel = gaps / gaps[0]
a = int(np.argmax(rel < 1e-6))
b = int(np.argmax(rel < 1e-12)) or len(rel) - 1
return (rel[b] / rel[a]) ** (0.5 / (b - a))
def steps_to(gaps, tol=1e-6):
return int(np.argmax(gaps / gaps[0] < tol))
def run(seed=0):
rng = np.random.default_rng(seed)
d = 50
x0 = rng.standard_normal(d)
lab = labs.Lab()
kappa = 1000.0
h = np.geomspace(1.0, 1 / kappa, d) # curvatures from L = 1 down to mu = 1/kappa
budget = {"gd": 16000, "heavy": 700, "nesterov": 700}
derived = {"gd": 1 - 1 / kappa, "heavy": (np.sqrt(kappa) - 1) / (np.sqrt(kappa) + 1), "nesterov": 1 - 1 / np.sqrt(kappa)}
label = {"gd": "gradient descent", "heavy": "heavy ball", "nesterov": "Nesterov"}
runs = {m: run_method(m, h, x0, budget[m]) for m in budget}
measured = {m: late_ratio(runs[m]) for m in budget}
count = {m: steps_to(runs[m]) for m in budget}
for m in budget:
lab.row(f"{label[m]}: contraction per step", f"{measured[m]:.4f} (derived {derived[m]:.4f})")
lab.row("steps to 1e-6 of the gap, kappa = 1,000",
" ".join(f"{label[m]} {count[m]:,}" for m in budget))
kappas = np.array([10.0, 30.0, 100.0, 300.0, 1000.0])
sweep = {m: [] for m in budget}
for k in kappas:
hk = np.geomspace(1.0, 1 / k, d)
for m in budget:
sweep[m].append(steps_to(run_method(m, hk, x0, int(16 * k) if m == "gd" else int(30 * np.sqrt(k)) + 60)))
slope = {m: np.polyfit(np.log(kappas), np.log(sweep[m]), 1)[0] for m in budget}
lab.row("slope of steps against kappa (log axes)",
" ".join(f"{label[m]} {slope[m]:.2f}" for m in budget) + " (theory 1, 1/2, 1/2)")
diverge = run_method("gd", h, x0, 400, step=2.05) # eta * L = 2.05 > 2: the steepest direction flips and grows
lab.row("gradient descent with step 2.05 / L", f"gap grows {diverge[-1] / diverge[0]:.1e} times in 400 steps")
lab.note = ("Plain gradient descent pays for the condition number, momentum for its square root: each measured "
"contraction sits on the root of its recurrence, and a step past 2 / L does not converge at all.")
assert abs(measured["gd"] - derived["gd"]) < 5e-4, "gradient descent contracts by 1 - 1/kappa"
assert abs(measured["heavy"] - derived["heavy"]) < 0.012, "the heavy ball's roots have modulus sqrt(beta)"
assert abs(measured["nesterov"] - derived["nesterov"]) < 0.012, "Nesterov's double root is 1 - 1/sqrt(kappa)"
assert count["heavy"] < count["gd"] / 8 and count["nesterov"] < count["gd"] / 8, "momentum is far faster"
assert 0.8 < slope["gd"] < 1.1 and 0.4 < slope["heavy"] < 0.65 and 0.4 < slope["nesterov"] < 0.65, slope
assert diverge[-1] > 1e6 * diverge[0], "a step over 2/L diverges"
fig, ax = labs.figure(2, size=(11, 4.2))
color = {"gd": labs.BLUE, "heavy": labs.GOLD, "nesterov": labs.GREEN}
for m in budget:
g = runs[m] / runs[m][0]
keep = g > 1e-14
ax[0].semilogy(np.arange(len(g))[keep], g[keep], color=color[m], label=f"{label[m]}: {measured[m]:.4f} a step")
ax[0].axhline(1e-6, color=labs.MUTED, ls="--", lw=1)
ax[0].set(title="The gap at condition number 1,000", xlabel="step", ylabel="(f - f*) / starting gap", xscale="log")
ax[0].legend(loc="lower left")
for m in budget:
ax[1].loglog(kappas, sweep[m], "o-", color=color[m], label=f"{label[m]}: slope {slope[m]:.2f}")
ax[1].set(title="Steps to a millionth of the gap", xlabel="condition number kappa", ylabel="steps")
ax[1].legend()
lab.fig = fig
return lab
Now change it
- Run gradient descent with step=1.9, 2.0 and 2.05 (in units of 1/L). Which direction grows, and by what factor a step?
- Give the heavy ball Nesterov's momentum (drop the square in `beta`) and compare its step count at kappa = 1,000.
- Replace the quadratic by sum(h * x**4): the loss is still convex. Do the three rates still hold?
Problems, with solutions
Try each problem before opening its solution.
1. Gradient descent's linear rate. For an L-smooth f, show f(x − ∇f(x)/L) ≤ f(x) − ‖∇f(x)‖²/2L. If also ‖∇f‖² ≥ 2μ(f − f*), deduce f(x_k) − f* ≤ (1 − μ/L)^k (f(x₀) − f*).
Solution
L-smoothness gives the quadratic upper bound f(y) ≤ f(x) + ∇f(x)ᵀ(y − x) + (L/2)‖y − x‖². Put y = x − ∇f(x)/L: f(y) ≤ f(x) − ‖∇f‖²/L + ‖∇f‖²/2L = f(x) − ‖∇f‖²/2L. Subtract f* and use the Polyak–Łojasiewicz inequality ‖∇f‖² ≥ 2μ(f(x) − f*): f(y) − f* ≤ (f(x) − f*) − (μ/L)(f(x) − f*) = (1 − μ/L)(f(x) − f*). Induction on k gives the claim. (μ-strong convexity implies the inequality: minimize its lower bowl over y.)
2. The heavy ball, tuned. On f = (λ/2)x², x_{k+1} = (1 + β − ηλ)x_k − βx_{k−1}. Show that nonreal roots of z² − (1 + β − ηλ)z + β have modulus √β. Find η, β putting all λ ∈ [μ, L] in this equal-modulus regime, allowing repeated real roots at its endpoints. Estimate the steps from the dominant root factors for κ = 10⁴ and a 10⁶-fold objective-gap reduction, against gradient descent with η = 1/L. Explain the limitation of this estimate.
Solution
The product of the two roots is β; nonreal roots are conjugate, so |z|² = z z̄ = β. They are nonreal when (1 + β − ηλ)² < 4β, with the same modulus at equality. The equal-modulus regime is (1 − √β)² ≤ ηλ ≤ (1 + √β)². Put ημ = (1 − √β)² and ηL = (1 + √β)². Dividing gives √β = (√κ − 1)/(√κ + 1) and η = 4/(√L + √μ)². For κ = 10⁴, ρ = √β = 99/101. Ignoring polynomial and initialization prefactors, the gap envelope decays like ρ²ᵏ: k ≈ ln 10⁶ / (−2 ln(99/101)) ≈ 345. Repeated endpoint roots can give position terms (a + bk)ρᵏ, so this is an asymptotic estimate, not a per-step contraction or guaranteed finite count. GD's slowest position mode has factor 1 − 10⁻⁴, giving the gap-reduction estimate ln 10⁶ / [−2 ln(1 − 10⁻⁴)] ≈ 69,000, about two hundred times larger.
3. SGD's stationary variance. SGD on f = (λ/2)x² with gradient noise of variance σ²/B: show the stationary variance is ησ²/(Bλ(2 − ηλ)), and that it depends on η and B only through η/B when ηλ ≪ 1.
Solution
x_{k+1} = (1 − ηλ)x_k − ηξ_k with E ξ = 0, Var ξ = σ²/B, independent of x_k. In the stationary state V = (1 − ηλ)²V + η²σ²/B, so V(2ηλ − η²λ²) = η²σ²/B and V = ησ²/(Bλ(2 − ηλ)). For ηλ ≪ 1, V ≈ (η/B)·σ²/(2λ): only the ratio η/B enters. (In d dimensions this is the Lyapunov equation of Chapter 4, tr S ≈ (η/2B) tr(H⁻¹C).)
4. Steepest steps under three norms. Show that min over ‖Δ‖∞ ≤ η of gᵀΔ is −η‖g‖₁, attained at −η sign(g), and that min over ‖Δ‖₂→₂ ≤ η of ⟨G, Δ⟩ is −η‖G‖* (the nuclear norm, the sum of the singular values), attained at −ηUVᵀ.
Solution
gᵀΔ = Σᵢ gᵢΔᵢ ≥ −Σᵢ |gᵢ||Δᵢ| ≥ −η Σᵢ |gᵢ|, with equality when every Δᵢ = −η sign(gᵢ). For matrices write G = Σᵢ σᵢ uᵢvᵢᵀ; then ⟨G, Δ⟩ = Σᵢ σᵢ uᵢᵀΔvᵢ, and |uᵢᵀΔvᵢ| ≤ ‖Δ‖₂ ≤ η for unit uᵢ, vᵢ, so ⟨G, Δ⟩ ≥ −η Σᵢ σᵢ. The step Δ = −ηUVᵀ has spectral norm η and uᵢᵀΔvᵢ = −η for every i, so it attains the bound.
5. Newton–Schulz near one. For p(σ) = (3/2)σ − (1/2)σ³, show p(1) = 1, p′(1) = 0, and that e = 1 − σ obeys e ↦ (3/2)e² + O(e³). For q(σ) = 2σ − (3/2)σ³ + (1/2)σ⁵ show q′(1) = 0 too, and find c in e ↦ c e². Which starts faster from small σ?
Solution
p(1) = 3/2 − 1/2 = 1, p′(σ) = 3/2 − (3/2)σ², so p′(1) = 0. Expanding, p(1 − e) = 1 − (3/2)e² + (1/2)e³: the new error is (3/2)e² − (1/2)e³, quadratic convergence. For q: q(1) = 2 − 3/2 + 1/2 = 1, q′(σ) = 2 − (9/2)σ² + (5/2)σ⁴, q′(1) = 0, q″(σ) = −9σ + 10σ³, q″(1) = 1, so q(1 − e) = 1 + e²/2 + O(e³): the new signed error is −e²/2 + O(e³), hence c = −1/2. Its magnitude has leading term e²/2 (the value overshoots one slightly), three times smaller than the cubic's leading error. Near zero p(σ) ≈ 1.5σ and q(σ) ≈ 2σ: q starts faster, and Jordan's quintic, with slope 3.4445, faster still, at the price of not converging to 1.
6. Weight decay's equilibrium, a correlated-update model. Let W_{t+1} = (1 − ηλ)W_t − ηu_t, with stationary zero-mean updates satisfying E⟨u_t, u_{t+k}⟩ = U²β^{|k|}, where U² = E‖u_t‖² and 0 ≤ β < 1. Show the equilibrium E‖W‖² ≈ (ηU²/2λ)(1 + β)/(1 − β) when 0 < ηλ ≪ 1 − β. Do not assume uₜ ⟂ Wₜ.
Solution
With a = 1 − ηλ and |a| < 1, unrolling gives W_t = a^t W_0 − η Σ_{m=0}^{t−1} a^m u_{t−1−m}; the finite-second-moment initial transient dies out. By the assumed autocorrelation, E‖W_t‖² → η²U² Σ_{m,n≥0} a^{m+n} β^{|m−n|} = η²U² (1 + aβ)/((1 − a²)(1 − aβ)). When ηλ ≪ 1 − β, use 1 − a² ≈ 2ηλ and (1 + aβ)/(1 − aβ) ≈ (1 + β)/(1 − β) to obtain the stated approximation. For fixed U² and β, the RMS norm scales like √(η/λ). Setting β = β₁ = 0.9 gives the model's factor 19; this is an approximate correlation model for Chapter 15's AdamW measurements, not a theorem that actual AdamW updates have exactly that autocorrelation. No measured values or numerical producers are changed by this correction.
Gradient orthogonality under scale invariance does not imply that a momentum update is orthogonal to the current weights; see Kosson, Messmer & Jaggi (2024), §3.1. If exact uₜ ⟂ Wₜ were imposed instead, the squared-norm recurrence would give η²U²/(1 − a²), without the correlation multiplier.
Notes and sources
Glossary
| English | 中文 |
|---|---|
| steepest descent | 最速下降 |
| L-smooth, μ-strongly convex | L-光滑,μ-强凸 |
| condition number (κ) | 条件数(κ) |
| descent lemma, Polyak–Łojasiewicz inequality | 下降引理,波利亚克–洛亚谢维奇不等式 |
| linear convergence, contraction factor | 线性收敛,收缩因子 |
| heavy ball (Polyak momentum) | 重球法(波利亚克动量) |
| Nesterov's accelerated gradient, look-ahead | 涅斯捷罗夫加速梯度,前瞻 |
| lower bound (Nemirovski–Yudin) | 下界(涅米罗夫斯基–尤丁) |
| stochastic approximation (Robbins–Monro) | 随机逼近(罗宾斯–门罗) |
| stationary covariance, Lyapunov equation | 平稳协方差,李雅普诺夫方程 |
| temperature (η/B), linear scaling rule, square-root rule | 温度(η/B),线性缩放规则,平方根规则 |
| sharp minimum, flat minimum | 尖锐极小值,平坦极小值 |
| sharpness, edge of stability | 锐度,稳定性边缘 |
| progressive sharpening, self-stabilization | 渐进锐化,自稳定 |
| power iteration, Hessian-vector product | 幂迭代,黑塞–向量积 |
| AdaGrad, RMSProp, Adam, AdamW | AdaGrad,RMSProp,Adam,AdamW |
| bias correction | 偏差校正 |
| sign descent, Lion | 符号下降,Lion |
| L2 regularization, decoupled weight decay | L2正则化,解耦权重衰减 |
| natural gradient, Fisher information matrix | 自然梯度,费希尔信息矩阵 |
| Kronecker product, K-FAC | 克罗内克积,K-FAC |
| preconditioner, preconditioning | 预条件子,预条件 |
| Shampoo, grafting, SOAP, eigenbasis | Shampoo,嫁接,SOAP,特征基 |
| orthogonalization, polar factor (UVᵀ) | 正交化,极分解因子(UVᵀ) |
| spectral norm, nuclear norm | 谱范数,核范数 |
| Muon, Newton–Schulz iteration | Muon,牛顿–舒尔茨迭代 |
| hybrid Newton–Schulz | 混合牛顿–舒尔茨迭代 |
| AlgoPerf, external tuning, self-tuning | AlgoPerf,外部调参,自调参 |
| learning-rate sweep, grid edge | 学习率扫描,网格边缘 |
| warmup, cosine schedule, warmup–stable–decay (WSD) | 预热,余弦调度,预热–稳定–衰减(WSD) |
| river valley, river and hill loss | 河谷,河损失与山坡损失 |
| cool-down branch | 冷却分支 |
| iterate averaging (Polyak–Ruppert), EMA of weights | 迭代平均(波利亚克–鲁珀特),权重的指数移动平均 |
| schedule-free optimization | 免调度优化 |
| attention logit (score) growth, QK-clip, MuonClip | 注意力分数增长,QK-Clip,MuonClip |
| gradient clipping | 梯度裁剪 |
| scale invariance, norm equilibrium, effective learning rate | 尺度不变性,范数平衡,有效学习率 |
Sources
From the repo root:
python -m unittest discover -s tests -p 'test_ai11*.py' -v
python -m unittest discover -s tests -p 'test_text_tables.py' -v
These source checks use extracted code and explicitly synthetic fixtures; they do not train models, produce scientific outcomes, render video or synthesize narration. The original generation and build commands are not acceptance steps for this source-only tree. In particular, an end-to-end build can explicitly invoke the unchanged original producers; it must not be used to bypass the scene-loader gate or imply corrected science.
The historical compute.py estimate was about 2.5 CPU-hours on one thread (the race about an hour, the
weight-decay grid and the schedules about 15 minutes each). Every run is seeded; the long items save each
finished run (CACHE.partial) and resume;
AI11_WORKERS=4 runs their pieces in four processes (spawn), AI11_THREADS sets torch's threads per process
(default 1). Nothing sets torch's thread count at import time.
Race protocol and metric domains
A fresh six-optimizer race schedules 48–66 runs (144,000–198,000 requested updates), including six initial seed-0 rates, up to three edge extensions, and two additional selected-rate seeds per optimizer. An edge optimum can remain after the cap; rates are the best tried, not guaranteed global optima. The inherited runtime estimate above is not a bound for a separately corrected producer.
Curves score the first 20,000 validation predictions (requiring 20,008 characters); tuning and final standings use the full 100,000-character validation slice, which has 99,992 scored predictions after the eight-character context. Final standings show the mean and observed min–max across three seeds, not a significance interval. Text is sampled from seed 0 at the shown steps. Its adjacent bits are interpolated from the validation curve: step 100 lies between evaluations 0/150, and step 1,000 between 900/1,050.
Each timing bar is the optimizer's mean per-step loop time across its three selected-rate seeds divided by AdamW's corresponding mean, not a mean of paired ratios. Time per step is amortized timed-loop wall time, including 20 periodic prefix validations and four 72-character continuations in a completed 3,000-step run; initial evaluation/writing and final full-slice evaluation are excluded. It is not optimizer-kernel timing. Runs share initialization and batches within each seed; text sampling uses its own fixed Torch generator and does not consume the training-batch RNG. The historical results below retain their original provenance; no corrected race cache is supplied by this note.
Sources
Checked against primary sources on 30 October 2026:
- AlgoPerf (Kasimbeg et al., ICLR 2025, arXiv 2502.15015): 18 submissions from 10 teams; external tuning won by Distributed Shampoo, "≈28% faster model training" across the eight base workloads (score 0.7784 against the NAdamW baseline's 0.5707); self-tuning won by Schedule-Free AdamW, "≈8% faster" than the self-tuning baseline.
- Muon (Keller Jordan's post, 8 December 2024): MomentUm Orthogonalized by Newton–Schulz; coefficients (3.4445, −4.7750, 2.0315), 5 steps, chosen to maximize the slope at zero with the limit values in about [0.7, 1.3]; the earlier baseline (2, −1.5, 0.5); NanoGPT speedrun 1.35×; FLOP overhead below 1% (0.7% NanoGPT, 0.5% Llama 405B); Bernstein & Newhouse's observation that Shampoo without accumulation is the orthogonalized gradient.
- Moonlight (Liu et al., arXiv 2502.16982, February 2025): weight decay and a per-parameter update scale; "~2× computational efficiency" against AdamW in compute-optimal training; a 3B-activated / 16B-total MoE on 5.7T tokens. The 0.2 √max(m, n) scale is the one Kimi K2's report gives for MuonClip.
- Kimi K2 (arXiv 2507.20534, July 2025): MuonClip, τ = 100, per-head S_max, W_q and W_k each scaled by √γ (for MLA, the head-specific parts; the shared rotary key untouched); 1.04T total and 32B activated parameters; "pre-trained on 15.5 trillion tokens with zero loss spike"; vanilla Muon's logits "quickly exceed a magnitude of 1000" in a mid-scale run. Part 18 has its 12.7%-of-heads figure.
- DeepSeek-V4 (arXiv 2606.19348, 26 April 2026): Muon for most modules, AdamW for the embedding, the prediction head, mHC's static biases and gating factors and the RMSNorm weights; hybrid Newton–Schulz, 10 iterations, 8 with (3.4445, −4.7750, 2.0315) and 2 with (2, −1.5, 0.5) "which stabilize the singular values precisely at 1"; RMSNorm on queries and KV entries instead of QK-Clip; Muon momentum 0.95, weight decay 0.1, update RMS rescaled to 0.18.
- GLM-4.5 (2025) trained with Muon: as checked for Part 18.
- Wen, Hall, Ma & Liang, Fantastic Pretraining Optimizers and Where to Find Them (arXiv 2509.02046, September 2025; v3 October 2026): eleven optimizers (AdamW, NAdamW, Mars, Cautious, Lion, Adam-mini, Muon, Scion, Kron, Soap, Sophia), 0.1B–1.2B parameters, 1–8× Chinchilla data; claimed speedups 1.4–2×; tuning one hyperparameter of the GPT-3 recipe up to 2× on a 100M model; no optimizer above about 1.4× after tuning; matrix-based optimizers 1.4× at 0.1B falling to 1.1× at 1.2B; Muon best at low data ratios, Soap and Kron at 8×. The bar chart in Chapter 16 draws these three numbers only.
- NVIDIA, Khona et al., SOAP, Muon, and Beyond: Pushing LLM Pretraining Scales (arXiv 2607.20548, July 2026): hybrid Mamba–Transformer MoEs up to 8B active / 72B total on 1T tokens; stable training at batches up to 100M tokens "where AdamW degrades"; mixed task-level comparisons (single company source).
- SOAP (Vyas et al., arXiv 2409.11321): over 40% fewer iterations and over 35% less wall-clock time than AdamW, about 20% better than Shampoo, at 360M and 660M parameters in the large-batch regime (the authors' own measurement).
- Lion (Chen et al., arXiv 2302.06675): program search; only the momentum kept; a smaller learning rate than Adam because of the sign's larger update norm (no multiplier is claimed on screen).
- Dion (Ahn et al., Microsoft, arXiv 2504.05295, 2025); Dion3 (Amsel et al., Microsoft Research, August 2026: "reducing optimizer step time by up to 6x" at Muon's loss); the Polar Express (Amsel, Persson, Musco & Gower, arXiv 2505.16932, ICLR 2026); MONA (arXiv 2605.26842), MUON+ (arXiv 2602.21545), T-MUON (arXiv 2610.24938) are named only, as preprints whose claims are their authors'.
- Historical: Cauchy, Méthode générale pour la résolution des systèmes d'équations simultanées (Comptes rendus 25, 1847); Robbins & Monro (Ann. Math. Statist. 1951, University of North Carolina); Polyak (1964); Nesterov (1983); Rumelhart, Hinton & Williams (1986, with a momentum term α); LeCun, Bottou, Orr & Müller, Efficient BackProp (1998); Krizhevsky, Sutskever & Hinton (2012: SGD, batch 128, momentum 0.9, weight decay 0.0005, the learning rate divided by 10 when the validation error stopped improving); RMSProp's formula from Lecture 6e of Hinton's Coursera course (2012); Goyal et al. (2017: batch 8,192, one hour, gradual warmup).
Sources
Books: J. Nocedal & S. J. Wright, Numerical Optimization (2006); Y. Nesterov, Lectures on Convex Optimization (2018); L. Bottou, F. E. Curtis & J. Nocedal, Optimization Methods for Large-Scale Machine Learning (2018); S. J. D. Prince, Understanding Deep Learning (2023), chapter 6.
Papers: Cauchy (1847); Robbins & Monro (1951); Polyak (1964); Nesterov (1983); Nemirovski & Yudin (1983); Rumelhart, Hinton & Williams (1986); Ruppert (1988); Polyak & Juditsky (1992); Amari (1998); LeCun et al. (1998); Duchi, Hazan & Singer (2011); Tieleman & Hinton (2012); Pascanu, Mikolov & Bengio (2013); Kingma & Ba (2014); Martens & Grosse (2015); Carlson et al. (2015); Lessard, Recht & Packard (2016); Loshchilov & Hutter (2016, 2017); Goyal et al. (2017); Keskar et al. (2017); Dinh et al. (2017); Li, Tai & E (2017); Mandt, Hoffman & Blei (2017); van Laarhoven (2017); Smith & Le (2018); Gupta, Koren & Singer (2018); Cohen et al. (2021, 2022); Damian, Nichani & Lee (2022); Malladi et al. (2022); Zhai et al. (2022); Chen et al. (2023); Bernstein & Newhouse (2024); Jordan et al. (2024); Vyas et al. (2024); Hu et al. (2024); Wen et al. (2024); Defazio et al. (2024); Kalra & Barkeshli (2024); Kosson, Messmer & Jaggi (2024); Kasimbeg et al. (2025); Liu et al. (2025); Kimi Team (2025); Amsel et al. (2025); Ahn et al. (2025); Wen, Hall, Ma & Liang (2025); DeepSeek-AI (2026); Khona et al. (2026).
What is computed and built
These numerical paragraphs are inherited records from the video-making source. Their numbers and rankings are retained; they are not certified here as fresh runs or recovered outcome artifacts. The legacy SOAP ranking does not validate a corrected SOAP implementation: the separately reviewed basis/state correction is isolated, and its synthetic checks do not establish full reference-optimizer equivalence or corrected training performance.
(from .cache/ai11/ on the machine that made the video; the narration branches on whichever way they come out.)
Numbers from the run that made the video (Linux, one thread, a shared machine):
- Racing downhill. Rosenbrock's valley (b = 5) from (−1.5, 2.2), 150 steps, the best of 25 rates each: Adam (η = 0.68) under 0.01 after 30 steps, the heavy ball (0.0147) after 41, Lion (0.032) after 122, gradient descent (0.032) after 141.
- Gradient descent. Steps to a millionth of the starting objective gap for κ = 1 … 1,000 in 50 dimensions: 1, 14, 46, 126, 373, 978, 2,745 (slope 0.89 on log axes; 1.01 with η = 2/(L + μ)); the late geometric-mean √(f − f*) ratio at κ = 1,000: 0.9990 measured, 0.9990 derived. On the convex quadratic (curvatures 1/i², 1,000 dimensions) the gap stays under L‖x₀ − x*‖²/2k at every one of 2,000 steps.
- Momentum. At κ = 1,000: 187 steps for the heavy ball and 142 for Nesterov against 2,745 (slopes 0.58 and 0.46); late geometric-mean √(f − f*) ratios 0.9418 (root modulus 0.9387) and 0.9702 (root modulus 0.9684). On the convex quadratic Nesterov ends with a gap 118 times smaller than gradient descent's and stays under 2L‖x₀ − x*‖²/(k + 1)².
- SGD. Part 6's 448 training pages: the stationary cloud's RMS distance 0.49 at batch 1 and 0.13 at batch 16 (3.8 times narrower). One page per step for 20,000 steps (5 seeds): the squared distance stalls at 0.33 with a constant step and reaches 0.00025 with η₀/(1 + k/100).
- Temperature. 4 rates × 6 batch sizes × 3 seeds: E‖w − w*‖² against η/B has slope 1.00 on log axes; measured over the discrete-Lyapunov prediction 0.93 … 1.14; tr(H⁻¹C) = 1.90.
- Edge of stability. η = 0.05: the sharpness first passes 90% of 2/η = 40 at step 1,520; second-half median 39.7, maximum 42.6. η = 0.1: at step 280; median 19.9 (2/η = 20), maximum 20.1.
- Adam. Without bias correction the first step would be 3.16η; with it, 99.99% of the weights move by more than 0.9η at step 1; the median move is 0.13η at step 100 and 0.16η at step 1,000.
- Natural gradient. The 2–24–24–2 network (722 weights), 300 full-batch steps, the best of 5 rates, 3 seeds: median training loss after 100 steps 0.00013 (natural gradient, η = 0.3), 0.014 (Adam, 0.1), 0.045 (K-FAC, 0.1), 4.2 (gradient descent, 3.0, still unstable then); at 300 steps 0.0, 0.0071, 0.0060 and 0.0080. The two parametrizations' natural-gradient paths differ by 2 × 10⁻¹⁶; gradient descent's by 4.4.
- Spikes. One-layer transformer, 2,000 steps, 2 seeds (held-out bits / largest recorded pre-update forward score, sampled every 10 steps): Muon η = 0.03: 2.86, 2.88 / 883, 1,152; η = 0.12: 2.97, 3.16 / 25,703, 24,233; η = 0.12 with QK-clip τ = 100: 2.88, 2.92 / 146, 139. AdamW η = 0.05: 3.69, 3.82 / 179,276, 230,454; with gradient clipping at 1: 2.89, 3.61 (one seed rescued); with QK-clip: 2.96, 3.39.
- Equilibrium. A LayerNorm after the second hidden matrix, AdamW η = 0.003 constant, 4,000 steps: ‖W‖ = 26.9, 12.7, 6.6 at λ = 0.1, 0.4, 1.6 against 29.5, 15.0, 7.2 predicted (within 15%; 6.8, 3.4, 1.6 without the momentum factor); fitted power −0.51 against −0.5; the update's cosine with W −0.05 … −0.18.
- Newton–Schulz. The second hidden matrix's gradient at step 300 of AdamW (132 singular values above 1% of the largest): after Jordan's 5 rounds they lie in 0.76 … 1.20; the classical cubic leaves its worst 0.35 from one after 12 rounds; DeepSeek-V4's hybrid (8 + 2) ends within 0.0018 of one. The trained weight matrix (241 above 1%): 0.69 … 1.20, 0.67, 0.0005. The scalar polynomial on the singular values matches the matrix iteration to 2 × 10⁻⁶.
- The race. 3,000 steps, warmup and cosine, each optimizer's best rate (the grid extended to 7 rates for Lion), 3 seeds, held-out bits on all 100,000 characters (mean, min–max): SOAP 2.334 (2.331–2.336, η = 0.008), Muon 2.341 (2.339–2.344, 0.008), Shampoo 2.351 (2.349–2.354, 0.008), SGD with momentum 2.407 (2.399–2.416, 0.2), AdamW 2.453 (2.434–2.474, 0.008), Lion 2.604 (2.578–2.624, 0.0032). Time per step relative to AdamW on this CPU: SGD 0.8×, Lion 1.4×, Shampoo 1.8×, SOAP 2.1×, Muon 2.1×.
- Schedules. AdamW at the race's best rate (0.008), 2 seeds, held-out bits on all 100,000 characters: cosine runs of 1,000, 2,000 and 4,000 steps 2.629, 2.502, 2.414; the constant run's cool-down branches (the last fifth decayed linearly to zero) 2.665, 2.566, 2.491; the constant run without decay 2.674 at 4,000. Here the cosine wins at every length, by 0.04–0.08 bits, and the narration says so. The shared 4,000-step trunk plus its three cooldowns require 5,400 updates per seed, versus 7,000 for three independent runs, excluding evaluation overhead.
- River valley. The toy (A = 4, σ = 1, η₀ = 0.25, 400 steps, 20 seeds): final loss 0.211 constant, 0.194 small constant, 0.036 cosine, 0.024 WSD; the constant rate's hill loss 0.128 against 0.125 predicted.
- Averaging and schedule-free. An EMA (β = 0.998) of the constant run's weights at step 4,000: 2.510 and 2.459 against the raw weights' 2.620 and 2.553 (20,000 characters), about half of what the cool-down gained. Schedule-free AdamW (best of 0.5, 1, 2, 4 × AdamW's rate: 2×), one run per seed, on the same 20,000 characters at 1,000, 2,000, 4,000 steps: 2.485, 2.351, 2.245, against cosine 2.556, 2.412, 2.305 and WSD 2.593, 2.489, 2.391; on all 100,000 at 4,000 steps 2.370 against cosine 2.414.
- Weight decay. 128 units, 50,000 training characters, 2,000 steps; 5 learning rates × 6 strengths for each: best AdamW (η = 0.016, λ = 0.3, the largest rate tried) 2.801 over 3 seeds (2.793–2.807); best Adam + L2 (η = 0.008, λ = 0.001) 2.832 (2.826–2.838); no decay at its best rate 2.944. AdamW's best strength moves from 0 to 0.3 across the learning rates.
Chapter notes
- Racing downhill. Gradient descent, the heavy ball, Adam and Lion on Rosenbrock's valley in 3D, each at its best of 25 learning rates, 150 steps; how we got here, 1847–2026 (Cauchy 1847; Robbins & Monro 1951; Polyak 1964; Nesterov 1983; backpropagation with momentum 1986; AdaGrad 2011; RMSProp 2012; Adam 2014; Shampoo 2018; Muon and AlgoPerf 2024; MuonClip and Kimi K2 2025; DeepSeek-V4 2026); the plan.
- 1. Gradient descent, derived. Cauchy (1847); L-smoothness and strong convexity drawn as two bowls; the descent lemma, the Polyak–Łojasiewicz step and the linear rate (1 − 1/κ)^k; the convex O(1/k) bound against gradient descent on a quadratic with curvatures 1 … 10⁻⁶; iterations against κ = 1 … 1,000 in 50 dimensions, and the measured late contraction against 1 − 1/κ; pause and predict: a step just over 2/L.
- 2. The heavy ball and Nesterov. Polyak (1964); the recurrence and its characteristic roots, the tuned √β = (√κ − 1)/(√κ + 1) derived; Nesterov (1983) and the O(1/k²) bound against our convex quadratic; Nemirovski & Yudin's lower bound; iterations against κ for all three (slopes), measured contraction against derived; the heavy ball's failure on non-quadratic convex losses (Lessard, Recht & Packard 2016).
- 3. Stochastic gradients. The batch gradient's mean and covariance Σ/B; Robbins & Monro (1951) and Σηₖ = ∞, Σηₖ² < ∞; Part 6's two-weight logistic regression (Austen against Dickens): full-batch, 16-page and 1-page paths; the cloud of a constant step against a step shrinking like 1/k (5 seeds); the workhorse era (Rumelhart, Hinton & Williams 1986; LeCun et al. 1998; AlexNet 2012).
- 4. Noise as temperature. SGD as an Euler–Maruyama step of dθ = −∇L dt + √(η/B) Σ^{1/2} dW (Li, Tai & E 2017; Mandt, Hoffman & Blei 2017); the stationary covariance (discrete Lyapunov equation; tr S ≈ (η/2B) tr(H⁻¹C)); measured on 4 learning rates × 6 batch sizes × 3 seeds against the prediction; the linear scaling rule (Goyal et al. 2017) and Adam's square-root rule (Malladi et al. 2022); the critical batch (Part 12); sharp and flat minima (Keskar et al. 2017) and the reparametrization catch (Dinh et al. 2017).
- 5. The edge of stability. Stability of a step on a bowl, ηλ < 2; pause and predict; full-batch gradient descent on Part 9's spirals at η = 0.05 and 0.1, the sharpness by power iteration on Hessian-vector products every 40 steps, replayed with the loss (Cohen et al. 2021); progressive sharpening and self-stabilization (Damian, Nichani & Lee 2022); the edge for momentum, (2 + 2β)/η, and for Adam, 38/η (Cohen et al. 2022).
- 6. AdaGrad, RMSProp, Adam. AdaGrad (Duchi, Hazan & Singer 2011); RMSProp (Tieleman & Hinton, Lecture 6e, 2012); Adam (Kingma & Ba 2014) and its bias correction derived, on one real weight's first 60 gradients; the first step with and without the corrections ((1 − β₁)/√(1 − β₂) ≈ 3.16η); the sign limit and every weight's step at steps 1, 100 and 1,000 of our model; Lion, found by program search (Chen et al. 2023).
- 7. Weight decay is not L2. L2 and decoupled decay are the same for SGD and different in Adam, derived (Loshchilov & Hutter 2017); AdamW against Adam + L2 on a 128-unit model that sees only 50,000 characters: held-out bits over 5 learning rates × 6 strengths each, the best of each from 3 seeds, and the training curves.
- 8. The natural gradient and K-FAC. Gradient descent depends on how the weights are written (two parametrizations of the same loss); steepest descent under a ruler M; the Fisher and the natural gradient (Amari 1998), shown invariant on the two-weight loss; K-FAC's Kronecker factors derived (Martens & Grosse 2015); gradient descent, Adam, damped K-FAC (sampled model-label factors) and a damped full-Fisher natural gradient on the spirals (a 2–24–24–2 network, the best of 5 rates each, 3 seeds), with a sample-space Woodbury solve for the natural direction and the decision maps replayed.
- 9. Shampoo and SOAP. Full-matrix AdaGrad and Shampoo's two factors (Gupta, Koren & Singer 2018); Shampoo without memory is UVᵀ (Bernstein & Newhouse 2024); why it took years (roots, damping, grafting); AlgoPerf 2024 (Distributed Shampoo ≈ 28% faster than the baseline; Kasimbeg et al. 2025); SOAP, Adam in Shampoo's eigenbasis (Vyas et al. 2024).
- 10. Muon, derived. A real gradient's singular values (a few dominate); Muon (Jordan et al. 2024); steepest descent under the spectral norm, ΔW = −ηUVᵀ, derived; one recipe and three norms (normalized gradient descent, sign descent, Muon); the practical recipe with Moonlight's 0.2 √max(m, n) scale (Liu et al. 2025), checked against our own Adam's typical step.
- 11. Newton–Schulz. One round is a polynomial on every singular value, derived; the classical cubic, Jordan's quintic (3.4445, −4.7750, 2.0315) and (2, −1.5, 0.5); the real gradient's 256 singular values round by round, a cobweb for one of them; the scalar polynomial against the matrix iteration; DeepSeek-V4's hybrid (8 + 2 rounds) on the gradient and on the trained weight matrix; band and worst-distance summaries use the current largest n, with n fixed by the initial count above 1% of the initial largest value, rather than tracking the same initial directions or reporting full-spectrum worst error; the Polar Express (Amsel et al. 2025).
- 12. The race, run fairly. SGD with momentum, AdamW, Lion, Shampoo, SOAP and Muon on the character model: the same data order, 3,000 steps, warmup and cosine for all; 6 initial learning rates each (seed 0), up to 3 factor-two edge extensions per optimizer, the selected rate rerun from 2 more seeds; the sweeps, the race replayed with its spread, what the models write at checkpoints, and the time per step.
- 13. Schedules and the river valley. Warmup (Goyal et al. 2017; Kalra & Barkeshli 2024), cosine (Loshchilov & Hutter 2016), warmup–stable–decay (Zhai et al. 2022; Hu et al. 2024); the river valley (Wen et al. 2024) as a computed toy with constant, small constant, cosine and WSD schedules (20 seeds), the loss split into river and hill against the stationary prediction; AdamW with cosine schedules of 1,000, 2,000 and 4,000 steps against one constant run with a cool-down branch at each length (2 seeds).
- 14. Without a schedule. Iterate averaging (Ruppert 1988; Polyak & Juditsky 1992) on Chapter 3's cloud; an EMA of the constant run's weights against its cool-down; schedule-free AdamW (Defazio et al. 2024; AlgoPerf's self-tuning winner, ≈ 8%), its interpolation, and one run of it scored at every length against the scheduled runs.
- 15. Keeping training stable. A one-layer transformer on our books trained too fast: the largest attention score runs away (Muon at η = 0.03 and 0.12, AdamW at 0.05; 2 seeds each); QK-clip derived (Kimi K2's MuonClip, τ = 100) and applied; gradient clipping (Pascanu, Mikolov & Bengio 2013); weight decay's equilibrium for a scale-invariant matrix derived (van Laarhoven 2017; Kosson, Messmer & Jaggi 2024) and measured at three decay strengths.
- 16. The optimizer race, 2024 to 2026. AlgoPerf, Moonlight's ~2×, Kimi K2's MuonClip, GLM-4.5, DeepSeek-V4's Muon; the careful benchmarks (Wen, Hall, Ma & Liang 2025: speedups ≤ 1.4× at 0.1B, 1.1× at 1.2B; NVIDIA 2026); successors (Polar Express, Dion, Dion3, SOAP variants, 2026 preprints); the lesson: tune the baseline, equal budgets, several seeds.
- Recap, problems, and what comes next (Part 12, The Mathematics of Scale), references.
Companion material in this repository
The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
- GD rates for L-smooth and strongly convex losses, derived.
- SGD noise; the SDE view with temperature η/B; linear scaling and the critical batch (gradient noise scale).
- Edge of stability (sharpness measured at 2/η).
- Heavy ball and Nesterov on quadratics.
- Adam derived (bias correction, sign limit); AdamW and why L2 ≠ weight decay; Lion.
- Natural gradient and the Fisher; K-FAC.
- Shampoo and SOAP.
- Muon: spectral steepest descent, Newton–Schulz as a polynomial map on singular values, MuonClip/QK-clip (Kimi K2).
- Schedules: warmup, cosine, WSD and the river valley, schedule-free.
- Clipping, loss spikes, weight decay as norm equilibrium, EMA.
Visuals: optimizers racing on one 3D landscape; singular values pushed to 1 by Newton–Schulz.
中文讲义
本讲的中文部分(与英文版对应)。
习题与解答
1. 梯度下降的线性收敛。 对 L-光滑的 f,证明 f(x − ∇f(x)/L) ≤ f(x) − ‖∇f(x)‖²/2L。若还有 ‖∇f‖² ≥ 2μ(f − f*),推出 f(x_k) − f* ≤ (1 − μ/L)^k (f(x₀) − f*)。
解答
L-光滑给出二次上界 f(y) ≤ f(x) + ∇f(x)ᵀ(y − x) + (L/2)‖y − x‖²。取 y = x − ∇f(x)/L: f(y) ≤ f(x) − ‖∇f‖²/L + ‖∇f‖²/2L = f(x) − ‖∇f‖²/2L。两边减去 f*,再用波利亚克–洛亚谢维奇不等式 ‖∇f‖² ≥ 2μ(f(x) − f*):f(y) − f* ≤ (1 − μ/L)(f(x) − f*)。对 k 归纳即得。(μ-强凸蕴含这个不等式:对 y 最小化下方的碗。)
2. 调好参数的重球法。 在 f = (λ/2)x² 上,x_{k+1} = (1 + β − ηλ)x_k − βx_{k−1}。证明 z² − (1 + β − ηλ)z + β 的 非实根模长为 √β。求出 η、β,使所有 λ ∈ [μ, L] 都处于等模区,允许端点出现实重根。对 κ = 10⁴、目标差距缩小 10⁶ 倍, 用主导根因子估计步数,并与 η = 1/L 的梯度下降比较。说明这个估计的局限。
解答
两根之积为 β;非实根互为共轭,所以 |z|² = z z̄ = β。非实根的条件是 (1 + β − ηλ)² < 4β;等号处的实重根也有相同模长。 等模区为 (1 − √β)² ≤ ηλ ≤ (1 + √β)²。令 ημ = (1 − √β)²,ηL = (1 + √β)²,得到 √β = (√κ − 1)/(√κ + 1),η = 4/(√L + √μ)²。κ = 10⁴ 时 ρ = √β = 99/101。忽略多项式与初始化的前置因子, 差距包络按 ρ²ᵏ 衰减:k ≈ ln 10⁶ / (−2 ln(99/101)) ≈ 345。端点重根可能产生位置项 (a + bk)ρᵏ,所以这是渐近估计, 不是每步收缩因子,也不是保证达到的有限步数。梯度下降最慢的位置模态因子是 1 − 10⁻⁴,相应的差距缩减估计为 ln 10⁶ / [−2 ln(1 − 10⁻⁴)] ≈ 69000,约为重球法估计的两百倍。
3. SGD 的平稳方差。 在 f = (λ/2)x² 上做 SGD,梯度噪声方差为 σ²/B:证明平稳方差是 ησ²/(Bλ(2 − ηλ)),并说明 ηλ ≪ 1 时它只通过 η/B 依赖于 η 和 B。
解答
x_{k+1} = (1 − ηλ)x_k − ηξ_k,E ξ = 0,Var ξ = σ²/B,与 x_k 独立。平稳时 V = (1 − ηλ)²V + η²σ²/B, 所以 V(2ηλ − η²λ²) = η²σ²/B,V = ησ²/(Bλ(2 − ηλ))。ηλ ≪ 1 时 V ≈ (η/B)·σ²/(2λ):只出现比值 η/B。(d 维时就是第4章的 李雅普诺夫方程,tr S ≈ (η/2B) tr(H⁻¹C)。)
4. 三种范数下的最陡一步。 证明在 ‖Δ‖∞ ≤ η 上 gᵀΔ 的最小值是 −η‖g‖₁,在 −η sign(g) 处取到;在 ‖Δ‖₂→₂ ≤ η 上 ⟨G, Δ⟩ 的最小值是 −η‖G‖*(核范数,奇异值之和),在 −ηUVᵀ 处取到。
解答
gᵀΔ = Σᵢ gᵢΔᵢ ≥ −Σᵢ |gᵢ||Δᵢ| ≥ −η Σᵢ |gᵢ|,当每个 Δᵢ = −η sign(gᵢ) 时取等号。对矩阵写 G = Σᵢ σᵢ uᵢvᵢᵀ; 于是 ⟨G, Δ⟩ = Σᵢ σᵢ uᵢᵀΔvᵢ,而对单位向量 |uᵢᵀΔvᵢ| ≤ ‖Δ‖₂ ≤ η,所以 ⟨G, Δ⟩ ≥ −η Σᵢ σᵢ。Δ = −ηUVᵀ 的谱范数是 η, 且对每个 i 都有 uᵢᵀΔvᵢ = −η,所以达到这个界。
5. 1附近的牛顿–舒尔茨迭代。 对 p(σ) = (3/2)σ − (1/2)σ³,证明 p(1) = 1、p′(1) = 0,并且 e = 1 − σ 满足 e ↦ (3/2)e² + O(e³)。对 q(σ) = 2σ − (3/2)σ³ + (1/2)σ⁵,证明 q′(1) = 0 也成立,并求 e ↦ c e² 中的 c。从小的 σ 出发, 哪个起步更快?
解答
p(1) = 3/2 − 1/2 = 1,p′(σ) = 3/2 − (3/2)σ²,所以 p′(1) = 0。展开得 p(1 − e) = 1 − (3/2)e² + (1/2)e³:新的 误差是 (3/2)e² − (1/2)e³,二次收敛。对 q:q(1) = 1,q′(σ) = 2 − (9/2)σ² + (5/2)σ⁴,q′(1) = 0,q″(σ) = −9σ + 10σ³, q″(1) = 1,所以 q(1 − e) = 1 + e²/2 + O(e³):新的有符号误差是 −e²/2 + O(e³),因此 c = −1/2。 误差大小的首项是 e²/2(值略微越过1),是三次多项式首项的三分之一。在0附近 p(σ) ≈ 1.5σ,q(σ) ≈ 2σ:q 起步更快;乔丹的五次多项式斜率是 3.4445,更快,代价是不收敛到1。
6. 权重衰减的平衡:相关更新模型。 令 W_{t+1} = (1 − ηλ)W_t − ηu_t,更新平稳且均值为零,并满足 E⟨u_t, u_{t+k}⟩ = U²β^{|k|},其中 U² = E‖u_t‖²、0 ≤ β < 1。证明 0 < ηλ ≪ 1 − β 时,平衡值 E‖W‖² ≈ (ηU²/2λ)(1 + β)/(1 − β)。不要假设 uₜ ⟂ Wₜ。
解答
令 a = 1 − ηλ、|a| < 1,展开得 W_t = a^t W_0 − η Σ_{m=0}^{t−1} a^m u_{t−1−m};初始值二阶矩有限时, 初始瞬态衰减掉。由假定的自相关,E‖W_t‖² → η²U² Σ_{m,n≥0} a^{m+n} β^{|m−n|} = η²U² (1 + aβ)/((1 − a²)(1 − aβ))。ηλ ≪ 1 − β 时,1 − a² ≈ 2ηλ,且 (1 + aβ)/(1 − aβ) ≈ (1 + β)/(1 − β),得到所述近似。U²、β 固定时,均方根范数按 √(η/λ) 缩放。 取 β = β₁ = 0.9,模型给出因子19;这是对第15章 AdamW 测量的近似相关模型,并不证明真实更新恰有这样的自相关。 这项更正不改变任何测量值或数值计算程序。
尺度不变性下梯度与权重正交,并不意味着动量更新也与当前权重正交,见 Kosson、Messmer 与 Jaggi(2024)第3.1节。若另行严格要求 uₜ ⟂ Wₜ, 范数平方递推会给出 η²U²/(1 − a²),不带相关性乘数。
Build the film
python -m videos.ai.ai11.compute # the part's numbers, into .cache/ai11
python tools/build.py ai11 # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py ai11 Hook # one chapter, silent, with a contact sheet
Scenes: videos/ai/ai11. Setup: see the course page. Source of these notes: the README and the scenes' narration.