Four hikers start on the same foggy slope, and each follows a different rule for the next step. Drag the step slider and watch: at the same pace setting, plain gradient descent (SGD) needs 109 steps to reach the valley floor and Nesterov needs 32.
Learn gradient descent, momentum, Nesterov, Adam, learning-rate schedules and the Shampoo idea from zero. Then see why the Compute Islands post uses an inner optimizer and an outer one.
Drag Steps taken to the right and watch four rules walk down the same valley. Then change the learning rate. Then we build each rule, piece by piece, and end with the two-level optimizer that lets far-apart clusters train one model.
You need the idea of a slope (how steeply a curve rises) and a little Python for the code. We build the rest from zero.
Prerequisite 5 of Training on Compute Islands, built for Rohan Anil’s Core Automation post The Hitchhiker’s Guide to Training on Compute Islands (2 November 2026). Sources: the DiLoCo, FedOpt, SlowMo, Adam and Shampoo papers, listed in the Field Guide. Every idea is re-taught here in our own words and devices.
Illustrative toy: a two-number problem with loss 0.5 × (0.1 x² + 4 y²), start at (−4, 1.5), so it is shallow along x and steep along y. Momentum and Nesterov use factor 0.9; Adam uses the paper’s defaults (0.9, 0.999, 1e-8). All four use the same learning rate, and the paths are computed live in your browser.
Chapter 0
Feel your way down a foggy hillside, and see why the Compute Islands post names three different optimizers
Picture a hillside in thick fog. You must reach the valley floor, but you can see only the ground under your boots. You feel which way the ground tilts, and you take a step downhill. Then you feel again. That is the whole idea of this lesson.
Training a model works the same way. The model holds a long list of numbers called parameters (also called weights). They are the knobs the model turns to make its guesses. A number called the loss says how wrong the model is on its training text. High loss is the hillside. Low loss is the valley floor.
At each step the computer finds the gradient. It is a list with one slope per parameter. It tells you, for every knob, which way to turn it to raise the loss fastest. Go the other way and the loss falls. (Backpropagation, the method that finds the gradient, has its own lesson: optimization and backprop.)
The gradient says which way. It does not say how far, or whether to remember where you walked before. Those choices belong to the optimizer: the rule that turns gradients into changes to the parameters. This lesson teaches the main rules, and each one fixes a flaw in the one before.
Think about the scale. A model with 32 billion parameters has a gradient with 32 billion slopes. One optimizer step is 32 billion small subtractions, repeated hundreds of thousands of times. Any rule that wastes a step, or that blows up once, wastes real money. So the choice of rule is not a detail. It decides how many steps the run needs, how much memory the GPUs hold besides the weights, and how often the clusters must talk.
The Core Automation post, “The Hitchhiker’s Guide to Training on Compute Islands” (Rohan Anil, 2 November 2026), names optimizers in three places. In the history table, DiLoCo is described as an “AdamW inner optimizer, Nesterov outer optimizer, hundreds of local steps between exchanges”. In the case study, “Each site used a variant of Distributed Shampoo” as its local optimizer. And the authors credit “a stronger optimization method derived from Distributed Shampoo”.
If those names are new, that is fine. Here is the plan. A cluster in one place runs many steps on its own with a fast rule (the inner optimizer). Far-apart clusters then trade only a summary of what they learned, and a second rule (the outer optimizer) folds that summary in. To follow that, you need the rules themselves. We start with the simplest.
Try the fog walk below. Drag the position along the curve. Notice that the slope tells you the direction, and a steeper slope is a bigger signal.
The curve is the loss as one knob turns. The teal dot is where the model is now. The arrow points downhill. Drag the position and watch the slope change sign at the bottom.
Illustrative toy: the loss is 0.5 × w² + 0.5, so the slope at w is exactly w. Real models have billions of knobs, and the gradient has one slope for each.
Look at what the read-out says. Far from the bottom the slope is large and the signal is loud. Near the bottom it fades toward zero. A simple walker takes steps in proportion to this signal, so it moves fast when far and slows near the floor. Chapter 1 builds that walker.
Chapter 1
Take a step against the slope, and learn why one number, the learning rate, can make training crawl or explode
You are back on the foggy hillside. You feel a slope of 8 under your boots. How far should you step? A tiny shuffle wastes the morning. A giant leap might carry you over the valley and up the far side.
The simplest answer is to step in proportion to the slope. Steep ground gets a long step. Flat ground gets a short one. You pick one fixed number to scale it. That number is the learning rate, written η (the Greek letter eta). The rule is called gradient descent.
Take the simplest bowl: loss = w², one knob w. Its slope is g = 2w. Start at w = 4 and pick η = 0.1.
Each step multiplies w by the same number, 0.8. In general, new w = w − η × 2w = (1 − 2η) × w. That one factor decides everything. If it lies between −1 and 1, w shrinks toward 0 and you settle. If it falls outside that range, w grows and training diverges: the loss rises instead of falling, and soon the numbers overflow.
So there is a speed limit. For this bowl the factor stays inside the safe range only when η is below 1. A steeper bowl, loss = c × w² with a bigger c, has a lower limit: η < 1/c. Remember this: the steepest direction sets the largest safe learning rate.
This also explains a number that surprises newcomers. Real learning rates are tiny: the DiLoCo setup peaks at 4 × 10−4, not at 0.1. A big model has directions of very high curvature, so the speed limit 1 / c is small. A rate that looks timid is often close to the limit for the steepest direction. Raise it by a factor of three and the run may diverge in the first hundred steps.
The line shows w over 30 steps, starting at 4, on the bowl loss = w². Slide the learning rate up through 0.5 and past 1. Then add gradient noise and watch the line start to shake.
Illustrative toy: loss = w², gradient 2w plus noise from a fixed random seed, so the same noise appears every visit. The factor (1 − 2η) is exact.
At η = 0.5 the factor is zero and w lands on 0 in a single step: a perfect jump, possible only because we know the bowl. At η = 1 the factor is −1, so w bounces between 4 and −4 forever. Past 1 it grows. This is the first failure you will meet in real training: the symptom is a loss curve that shoots up until the numbers overflow. The measurement is to compare η with the steepest curvature. The fix is a smaller η.
Real training never sees the whole dataset at once. It takes a minibatch: a small random handful of training examples, say a few thousand tokens. The gradient from that handful is an estimate of the true one. Average more examples and the estimate gets better; the shake falls roughly as 1 over the square root of the batch size. The word stochastic just means random, so SGD is gradient descent on random minibatches.
Noise changes the picture. With a fixed η the line no longer settles. It jitters around the bottom, and a bigger η gives a bigger jitter. That is why the learning rate usually shrinks late in training (Chapter 5), and why one site doing many steps on a big batch is a different thing from many sites doing small ones.
A small worked case shows the scale of the noise. Say one example gives a gradient with noise of size 1. A minibatch of 100 examples averages 100 independent noises, so the noise falls to 1 / √100 = 0.1. To halve the noise again you need four times the batch, 400 examples. This square-root law is why bigger batches help with diminishing returns, and why each island in a low-communication run can use a large local batch without the network’s help.
Now return to the hero valley. It is steep across (curvature 4) and shallow along its length (curvature 0.1). The speed limit comes from the steep side: η below 2 / 4 = 0.5. At η = 0.2 the steep side is fine, but the shallow side then shrinks by a factor of only 1 − 0.2 × 0.1 = 0.98 per step. We need 0.98 raised to 2t, times a starting loss of 0.8, to fall below 0.01, which takes 109 steps. You cannot raise η to speed up the shallow side, because the steep side would blow up. This tension is the reason for every rule in the next chapters.
Chapter 2
Keep a running total of past gradients so that steady directions speed up and zigzags cancel
Roll a marble down a long, narrow gutter. It does not stop and restart at every bump. It builds up speed along the gutter, and the small sideways wobbles die out because they push left, then right, then left. The marble remembers where it was heading.
Plain gradient descent has no such memory. In the long valley of the hero it gets stuck in the worst way. The steep walls force a small learning rate, so progress along the gentle floor crawls. We want to speed up along the floor and not along the walls. Momentum does exactly that.
Add one new number for each parameter: the velocity v. At each step, v keeps a fraction β of its old value and adds the new gradient. Then the parameters move along v, not along the raw gradient. The fraction β is the momentum factor; 0.9 is the usual choice.
First, a steady push. Suppose the gradient is always 1 and β = 0.9. Then v is 1, then 0.9 × 1 + 1 = 1.9, then 0.9 × 1.9 + 1 = 2.71, then 3.439, and so on. It climbs toward 1 / (1 − 0.9) = 10. A steady direction ends up moving ten times faster than with plain descent.
Now a zigzag: the gradient alternates +1, −1, +1, −1. The velocity is 1, then 0.9 × 1 − 1 = −0.1, then 0.9 × (−0.1) + 1 = 0.91, then −0.181. It never grows past about 1 in size, and settles to a swing of 0.53 either way, about 1 / (1 + 0.9). The two directions are in the same sum, and the zigzag nearly cancels.
So one running total does two jobs. It boosts the direction that stays the same from step to step (along the valley) and it damps the direction that flips (across the valley). A rule of thumb: v is roughly an average of the last 1 / (1 − β) gradients, so 0.9 remembers about 10 steps and 0.99 about 100.
There is one more consequence, and it trips up many newcomers. Along a steady direction, momentum multiplies the step by 1 / (1 − β). With η = 0.2 and β = 0.9, the effective learning rate along the floor is 0.2 × 10 = 2.0, ten times the plain value. That is the whole gain on the valley floor. It is also why raising β usually means lowering η: the two multiply. A setting that is safe at β = 0 can be unstable at β = 0.99 with the same η.
The warm path is momentum at learning rate 0.2; the faint blue path is plain descent with the same learning rate. Drag the momentum factor from 0 to 0.99 and watch how the path changes, and how soon it settles.
Illustrative toy: the hero valley, loss 0.5 × (0.1 x² + 4 y²), start (−4, 1.5), learning rate 0.2. “Settled” means the loss falls below 0.01 and stays there for 300 steps; the values are computed live.
Slide to 0.8. The path swings across the valley a few times and then runs straight down the floor: the toy settles in 26 steps, against 109 for plain descent. At 0.9 the ball is heavier, so it overshoots the bottom and has to come back, and settling takes 60. At 0.99 the memory is so long that it never settles within 300 steps. A heavier ball is not always a faster one.
So how do you pick β? Start at 0.9, the value used throughout this lesson and by DiLoCo’s outer optimizer. Watch the loss curve for waves. If you see them, lower β before touching anything else. If the curve is smooth but slow, raise η first, since β and η multiply, and check the stability limit again after every change.
Too much momentum has a clear symptom: the loss curve rises and falls in waves, or the path overshoots the goal and curves back. The measurement is to count how often the sign of the error flips, or to watch the overshoot. The fix is to lower β or η. Real training usually keeps β near 0.9 and tunes η first.
One cost is worth noting now. The velocity v has one number for every parameter. That is extra memory the optimizer must keep, the first example of optimizer state. For a model with 32 billion parameters, v in 32-bit numbers (4 bytes each) takes 32 × 109 × 4 = 128 GB. Later chapters will add to this bill.
torch.optim.SGD(params, lr=0.2, momentum=0.9). PyTorch writes it exactly as above: v = momentum * v + grad, then param -= lr * v.Chapter 3
Measure the slope where momentum is about to carry you, and brake before the overshoot, not after
A skier races toward the bottom of a dip. Classical momentum is a skier who looks at the snow under her skis, and decides how hard to push from that. But she is moving fast. In a moment she will be somewhere else, and the slope there may point the other way. A better skier looks at where she is about to be.
That is Nesterov momentum, named for the mathematician Yurii Nesterov. It changes one thing: the gradient is measured at the place the velocity is about to carry you, not at the place you stand. If you are about to shoot past the bottom, the look-ahead gradient already points back, and the velocity gets braked early.
Take the bowl loss = ½ w² (slope = w), start at w = 4, with η = 0.1 and β = 0.9. Step 1 is identical, because v starts at 0. Both rules read slope 4, set v = 4, and move to 3.6.
Step 2 is where they part. Classical momentum reads the slope at 3.6, so g = 3.6, v = 0.9 × 4 + 3.6 = 7.2, and w = 3.6 − 0.72 = 2.88. Nesterov first finds the look-ahead point: 3.6 − 0.1 × 0.9 × 4 = 3.24. There the slope is smaller, so g = 3.24, v = 3.6 + 3.24 = 6.84, and w = 3.6 − 0.684 = 2.916. Nesterov has already taken a slightly smaller step, because the ground ahead is flatter.
Step 3 repeats the idea. Classical: g = 2.88, v = 9.36, w = 1.944. Nesterov: look-ahead 2.916 − 0.09 × 6.84 = 2.30, so g = 2.30, v = 8.456 and w = 2.070. The gap grows. Near the bottom, Nesterov’s look-ahead point crosses to the far side before the real position does, so the gradient flips sign early and brakes the ball. Try it below.
Step 4 widens the gap again: classical momentum is at 0.907 and Nesterov at 1.178. Nesterov is behind at this moment. That is the point of the rule: it spends less speed early so it has less to cancel later. Computing the gradient at a predicted point is like a pilot who aims for where the runway will be, not for where it is now. First predict with the old velocity, then correct with the gradient seen at the prediction.
Two balls roll down the bowl loss = ½ w² from w = 4. Warm is classical momentum; purple is Nesterov. The line at 0 is the bottom. Change the learning rate and momentum factor, and compare the swings.
Illustrative toy: one knob, curvature 1, start w = 4, plotted for 60 steps; the settle and overshoot numbers come from 300 steps computed live. “Settled” means |w| stays under 0.01. Libraries rearrange the same idea so only one gradient, taken at the stored point, is needed per step.
At the defaults (η = 0.1, β = 0.9) classical momentum swings down to −2.41 and settles after 110 steps. Nesterov swings to only −1.42 and settles after 53. Same memory, same cost, half the wait.
The gain can be larger. Raise the learning rate to 0.3 with β = 0.9: classical momentum settles in 112 steps, Nesterov in 24. The classical ball swings down to −3.11, so it wastes most of its time on the far side of the bowl. Nesterov swings only to −1.19. In PyTorch you ask for this with nesterov=True. The library rearranges the update so it needs one gradient at the stored point, with the same effect.
Slide the learning rate up to about 1.5. Nesterov, the faster rule at gentle settings, suddenly flies apart, while classical momentum still settles. Its look-ahead step reacts more sharply, so it tolerates less aggressive rates. For a bowl of curvature c, the safe limits are ηc < 2(1 + β) for classical momentum and ηc < 2(1 + β) / (1 + 2β) for Nesterov. At β = 0.9 that is 3.8 against 1.36.
You saw this in the hero. Its steep side has curvature 4, so Nesterov’s limit is η < 1.36 / 4 = 0.34. At 0.35 it blew up while the other three did not. The symptom is a loss that explodes; the measurement is to compare η with the limit; the fix is the same as in Chapter 1.
The DiLoCo paper (Douillard et al., 2023) uses Nesterov as its outer optimizer, with an outer learning rate of 0.7 and momentum 0.9. It tried plain SGD and Adam in that role and found them worse. The authors suspect that the look-ahead correction helps because each outer gradient covers hundreds of training steps. Chapter 7 shows what that gradient is.
Chapter 4
Divide each knob’s step by how big its gradients usually are, and see what that memory costs
Imagine a mixing desk with two knobs. Turning the first knob a little changes the sound a lot: its gradient is 10. Turning the second changes it barely at all: its gradient is 0.01. You hold one rule for both: “move by the learning rate times the gradient.” Now the first knob lurches and the second one hardly moves. One learning rate cannot suit both.
A model has billions of knobs, and their gradients differ by factors of thousands. Adam (Kingma and Ba, 2014) gives each knob its own step size. It divides the knob’s step by a measure of how large that knob’s gradients have recently been. Knobs with loud gradients get calmed. Knobs with quiet gradients get a boost.
Adam keeps two numbers for every parameter. The first, m, is a running average of the gradient: it is momentum, written as an average. The second, v, is a running average of the gradient squared. Squaring removes the sign, so v measures how big the gradients are, whichever way they point. In statistics an average of a power is called a moment, so m is the first moment and v is the second.
Every operation here is elementwise. The tensors m and v have exactly the shape of θ. A weight matrix of shape [4096, 4096] gets an m of shape [4096, 4096] and a v of the same shape.
Take the two knobs from the mixing desk, with gradients 0.01 and 10, and η = 0.1. At step 1, m = 0.1 × g (since m started at 0): 0.001 and 1. And v = 0.001 × g²: 10−7 and 0.1. Now correct the bias: m̂ = m / 0.1 gives 0.01 and 10 again, and v̂ = v / 0.001 gives 10−4 and 100. The step is η × m̂ / √v̂ = 0.1 × 0.01 / 0.01 = 0.1 for the first knob, and 0.1 × 10 / 10 = 0.1 for the second. Plain descent would have moved them by 0.001 and 1. Adam moved both by exactly η.
In the steady state the step is about η times (average gradient) divided by (typical gradient size). If a gradient keeps the same sign, that ratio is near 1 and the knob moves a full η. If the gradient is mostly noise, flipping sign, the average is small next to the typical size, so the ratio shrinks and the knob barely moves. Adam is a built-in signal-to-noise gauge.
Knob A has a gradient of size 1 that is mixed with noise. Knob B has a clean gradient that is much larger. Bars show the size of one step, on a log scale. Raise B’s gradient, then raise A’s noise.
Illustrative toy: learning rate 0.01 for both rules. Knob A’s gradient is 1 plus noise of the size shown; knob B’s is the multiple shown, with no noise. Adam’s step is the long-run value η × mean / √(mean² + noise²), which is what its running averages settle to.
At the start (B is 100 times larger, A has no noise), plain descent moves B by 1 and A by 0.01: B moves a hundred times farther. Adam moves both by 0.01. Now drag A’s noise to 3. Adam’s step for A falls to 0.0032, because the gradient it sees points a different way almost every time. Plain descent does not notice: its step for A stays 0.01 on average, but the path jitters.
Adam holds m and v: two extra numbers per parameter. In 32-bit numbers (4 bytes each) that is 8 bytes per parameter. The post’s sparse mixture-of-experts model has about 32 billion total parameters, so m and v together take 32 × 109 × 8 = 256 GB, twice the 128 GB that momentum alone needs. This is the bill Chapters 6 and 7 build on, and it is why training systems split the optimizer state across many GPUs (see parallelism, pipeline and FSDP).
A very small v makes the division large. The symptom is a loss spike late in training, after a long run of tiny gradients. The measurement is the ratio m̂ / √v̂ for the spiking tensor. The fix is a larger ε, a smaller η, or clipping the gradient. The DiLoCo paper hit a version of this: when it used Adam as the outer optimizer it was “particularly unstable with a high second order momentum norm”, and a larger ε of 0.1 eased it. Even so, Nesterov was still the better outer choice.
Chapter 5
Change the learning rate over the run, and learn what the “W” in AdamW adds
A driver does not pull away from the kerb at top speed, and does not hit the brakes only at the moment of parking. She eases in, cruises, then slows well before the end. A training run does the same with its learning rate. The learning rate is not one number but a curve over time: the learning-rate schedule.
Recall the first Adam step from Chapter 4: both knobs moved by exactly η, whatever their gradients. On step 1 the model is random and Adam has seen a single gradient. Every one of billions of knobs takes a full-size step on that one noisy reading. The averages m and v need time to settle.
The fix is warmup: raise η in a straight line from 0 to its peak over the first few hundred or thousand steps. The DiLoCo paper’s setup, for example, uses a peak inner learning rate of 4 × 10−4 and 1,000 warmup steps. At step 500 the rate is half the peak, 2 × 10−4.
Chapter 1 showed that with noisy gradients a fixed η never settles: the weights jitter around the bottom, and a bigger η gives a bigger jitter. To get the last bit of quality you shrink η near the end, so the jitter fades. The common shape is cosine decay, a smooth half-wave from the peak down to a small floor.
A worked case with illustrative numbers: ηmax = 4 × 10−4, ηmin = 4 × 10−5, 1,000 warmup steps and 10,000 steps in all. Halfway through the decay, at step 5,500, p = 0.5 and cos(π/2) = 0. So η = 4 × 10−5 + ½ × 3.6 × 10−4 = 2.2 × 10−4. At the last step p = 1 and η = 4 × 10−5.
How does cosine differ from a straight-line (linear) decay? Both reach the same midpoint, 2.2 × 10−4. A quarter of the way down (p = 0.25), linear gives 4 × 10−4 − 0.25 × 3.6 × 10−4 = 3.1 × 10−4, while cosine gives 4 × 10−5 + ½ × 3.6 × 10−4 × (1 + cos(π/4)) = 3.47 × 10−4. Cosine stays near the peak longer and then falls faster near the end. Try both in the device and compare the two curves.
The line is the learning rate over 10,000 steps. Choose a decay shape, change the warmup, then slide the marker along the run and read the rate and its effect on the weights.
Illustrative: peak 4 × 10−4 and warmup 1,000 steps echo the DiLoCo paper’s inner setup (Table 5); the floor of 4 × 10−5 and the 10,000-step length are made up. Weight decay 0.1 is the paper’s value; the shrink figure multiplies (1 − η × 0.1) over every step so far.
Set the warmup to 0 and look at step 0: the rate starts at the peak. That is the instant the unprepared model takes its biggest, most blind step. Now pick Constant and drag the marker to the end: the rate is still at the peak, so the jitter never fades.
Skipping warmup has its own failure. The symptom is a loss that spikes or blows up within the first few hundred steps, before the run has learned anything. The measurement is the size of the parameter change per step in those first steps: with Adam it equals η for nearly every knob. The fix is a longer warmup or a lower peak rate.
Weight decay pulls every weight a little toward zero on each step. It keeps weights small and tends to help the model generalize. In AdamW (Loshchilov and Hutter, 2019) the pull is decoupled: it is applied straight to the weight and is not mixed into the gradient.
The reason is Adam’s division. If a penalty were added to the gradient, Adam would divide it by √v̂ like everything else, and the pull would depend on each knob’s gradient history. The decoupled step is simply θ ← θ − η(m̂ / (√v̂ + ε) + λθ). With λ = 0.1 and η = 4 × 10−4, every weight shrinks by a factor of 1 − 4 × 10−5 per step, tiny alone but steady over thousands. DiLoCo uses AdamW as its inner optimizer with weight decay 0.1.
The inner schedule also shapes the outer one. The DiLoCo authors tried cosine decay on the outer learning rate and found it made little difference. Their reason: because the inner rate decays, the outer gradient “gets naturally smaller” over the run, which removes the need to decay the outer rate too. Keep this in mind for Chapter 7: the outer step reads what the inner phase produced.
Chapter 6
Use the curvature of the loss to turn a long tilted valley into a round bowl, and see how Shampoo does it cheaply
Suppose a map shows the east-west axis in miles and the north-south axis in inches. A valley on that map looks like a long thin slit. Walk by its slopes and you zigzag. Now redraw the map so both axes use the same unit. The valley becomes a round bowl, and walking straight downhill takes you to the bottom.
That redrawing is preconditioning. Instead of stepping along the raw gradient, you first multiply it by a matrix P that undoes the stretch. Every optimizer so far was a kind of preconditioning in disguise: momentum filters the gradient over time, and Adam rescales each axis on its own.
The gradient is the first derivative: the slope. The curvature is the second derivative: how fast the slope itself changes. A valley wall has high curvature, since the slope changes quickly as you cross it. The valley floor has low curvature. For many knobs the curvatures form a matrix, the Hessian H. Optimizers that use it are called second-order.
The ideal step is Newton’s: θ ← θ − H−1g, where H−1 is the matrix inverse. On a perfect bowl it jumps to the bottom in one step, whatever the stretch. The catch is size. A model with n parameters has an H with n² entries. For 32 billion parameters that is about 1021 numbers, far too many to store or invert.
See the idea in one dimension. For loss = ½ c w² the curvature is c, and the slope at w is c × w. Newton’s step is w minus (c × w) / c = 0. It lands on the bottom at once, for any c, steep or flat. Plain descent with a fixed η cannot do that, because the right step size is 1 / c and c differs from one direction to the next. Preconditioning is the art of supplying that 1 / c for every direction without paying for the full matrix.
Adam keeps only the diagonal: one scale per knob, no interactions. That works when the valley is lined up with the knobs, so each knob has its own stretch. It fails when the valley is tilted. Then a good move needs two knobs turned together, and a per-knob rescale cannot see that. Tilt the valley below and compare.
The same valley as before, rotated by the tilt you choose. Three paths start from the same spot: plain descent (blue), Adam (pink) and a full preconditioner that knows the curvature (teal). Drag the tilt from 0 to 45 degrees.
Illustrative toy: curvature 0.1 along the valley and 4 across it, learning rate 0.2 for plain descent and Adam, start rotated with the valley. The full preconditioner steps −0.5 × H−1g with the exact H; Shampoo only approximates this, so treat it as the target, not as Shampoo itself. “Settled” means the loss stays under 0.01.
At 0 degrees Adam does well, settling in 52 steps against 109 for plain descent. At 45 degrees its edge is nearly gone: 106 steps. The full preconditioner needs 5 at every tilt, because it undoes the stretch whichever way it points. The gap between Adam and the target is what a better preconditioner can win.
Most big weights are matrices. A layer might hold a weight W of shape [m, n] and get a gradient G of the same shape. Treating every entry as its own knob would need an H of size (mn)². Shampoo (Gupta, Koren and Singer, 2018) keeps just two small matrices, one for each side of the weight. One sums G·GT over steps (size m × m). The other sums GT·G (size n × n).
A worked step shows the effect. Let G be the 2 × 2 matrix with 2 and 0.5 on its diagonal and 0 elsewhere. Then L = G GT = diag(4, 0.25), and R is the same. The power −1/4 of each diagonal entry is 4−1/4 = 0.707 and 0.25−1/4 = 1.414. So the update is diag(0.707 × 2 × 0.707, 1.414 × 0.5 × 1.414) = diag(1, 1). A direction that was 4 times louder than the other now matches it. Shampoo flattens the gradient’s size in every direction, not only along the knob axes.
The memory is m² + n² per matrix. For a square 4096 × 4096 weight (16.8 million numbers) that is 2 × 16.8 = 33.6 million, twice the weight, the same bill as Adam’s m and v. For a tall 4096 × 11008 feed-forward weight (45.1 million numbers) it is 16.8 + 121.2 = 138 million, about 3.1 times the weight. The matrix roots are also costly, so implementations typically refresh them only every so many steps.
Distributed Shampoo (Shi et al., 2023) handles this at scale. It splits each parameter’s blocks across GPUs and, by its authors’ report, costs at most 10% more per step than diagonal methods such as Adam. The Compute Islands post says each site ran “a variant of Distributed Shampoo” as its local optimizer. It does not give the variant’s details, so this lesson teaches the idea only.
Chapter 7
Let each island walk alone for many steps, then fold their journeys into one move with a second optimizer
Four surveyors are sent into a mountain range with the same starting map. Phoning each other after every step would be slow, and the phone line is poor. So each walks on their own for a day, taking notes. At dusk they meet and compare. Each says “I moved this far this way.” The group averages the four journeys and sets out the next morning from that new shared spot.
That is low-communication training. In the usual setup, called data parallel, every GPU computes a gradient and all GPUs average them after every step (the all-reduce from the data-parallel lesson). That needs a fast network. Across far-apart clusters the network is slow, so we make the walkers independent for H steps between meetings.
Δ is called a pseudo-gradient because no loss produced it. It is the net distance the islands walked, backwards. It points uphill, like a gradient does, so the same “subtract it” machinery of momentum and Nesterov applies. This view comes from federated learning. The FedOpt paper (Reddi et al., 2020) shows that classic federated averaging equals running plain SGD on Δ with learning rate 1. Using any other outer rule is a free choice, and DiLoCo (Douillard et al., 2023) picked Nesterov momentum with outer learning rate 0.7 and momentum 0.9, with H = 500.
Use one knob. The shared value starts at 4 and the best value is 0. After H inner steps the islands end at 3.0, 2.6 and 3.4, so their average is 3.0 and Δ = 4 − 3 = 1.0. Plain averaging (outer SGD, rate 1) moves to 3.0, exactly the average.
Now use the DiLoCo outer rule. The momentum buffer starts at 0, so the first buffer is 1.0 and the step is 0.7 × (1.0 + 0.9 × 1.0) = 1.33. The shared value moves to 2.67. In round two the islands only manage a Δ of 0.9. The buffer becomes 0.9 × 1.0 + 0.9 = 1.8, and the step is 0.7 × (0.9 + 0.9 × 1.8) = 1.764, bigger than the islands asked for. The shared value reaches 0.906. The outer momentum has noticed that the islands keep walking the same way, and has carried the shared model further than any island’s own average.
Left: round 1 on the valley. Four islands start at the same spot, walk alone, and the shared model takes the outer step (purple path). Right: loss after each round, with plain averaging dashed. Change the outer rule, the local steps and the round count.
Illustrative toy, not the paper’s run: four islands, plain SGD inside (learning rate 0.05), gradient noise 0.3 from a fixed seed, on the hero valley. Real DiLoCo uses AdamW inside. Outer Nesterov follows PyTorch: buffer = mu × buffer + Δ, step = rate × (Δ + mu × buffer). Loss is the exact valley loss at the shared model.
With 10 local steps and 10 rounds, plain averaging leaves a loss of 0.30 and the Nesterov outer rule reaches 0.0022. The rule helps because each round makes only a small move along the shallow floor, and momentum adds them up. Now push H to 50. Each island walks so far that averaging alone does well, and the outer rule’s extra push starts to overshoot. The best outer settings depend on H.
On C4 (a large public set of web text), with a 150-million-parameter model, DiLoCo with 8 workers and H = 500 reached validation perplexity 15.02. Perplexity is a score of how surprised the model is by held-out text, so lower is better. A baseline using 8 times the batch with an all-reduce every step reached 15.30, and DiLoCo sent 500 times less data (Table 2 of the paper). The paper also tested non-i.i.d. shards. In plain words: i.i.d. means every island sees data that looks alike, and non-i.i.d. means each island sees a different slice, which is the harder case.
Two facts about state matter. First, each island keeps its own AdamW state (m and v). The authors tried synchronizing it as well and saw no significant gain for three times the data to send. Second, memory grows. The Streaming DiLoCo paper counts parameters (1×), Adam state (2×), the outer copy of the parameters (1×) and the outer Nesterov buffer (1×): 5 units against 3 for plain data parallel, which is 66% more. For 32 billion parameters in 32-bit numbers one unit is 128 GB, so that is 640 GB against 384 GB.
pythonimport numpy as np def outer_round(theta, shards, H, inner_step, buf, lr=0.7, mu=0.9): deltas = [] for shard in shards: # one island each, in parallel p = theta.copy() for _ in range(H): # H local steps, no network p = inner_step(p, shard.next_batch()) # AdamW; its state stays local deltas.append(theta - p) # same shape as theta delta = np.mean(deltas, axis=0) # the only traffic: one tensor per island buf[:] = mu * buf + delta # outer Nesterov buffer return theta - lr * (delta + mu * buf)
Two things go wrong. If H is too large, the islands drift apart, mostly with non-i.i.d. data, and their average is a poor move: the symptom is a loss that jumps at each sync and then recovers. The measurement is to compare the loss just before and just after the outer step. The fix is a smaller H, or a lower outer rate or momentum. For unequal shards, DiLoCo also rescales each island’s Δ by its shard size. The second problem is that the outer rule overshoots like the heavy ball of Chapter 2; the fix is again a lower momentum.
Chapter 8
Count the bytes in one exchange, shrink them with compression, and keep the lost bits with error feedback
You now have two optimizers. The inner one runs on each island and never touches the long-distance link. The outer one needs the pseudo-gradient from every island. That tensor is as big as the whole model. For a 32-billion-parameter model it is 32 billion numbers, and the link between the clusters is slow. This chapter does the arithmetic and shows the three tricks that make it fit.
The post’s setup has two clusters about 9,000 miles apart on a link of 25 Gbps. A Gbps is a billion bits per second; divide by 8 to get bytes. So 25 Gbps carries 25 ÷ 8 = 3.125 GB each second. (We assume this speed holds in each direction at once; the post says “bidirectional” without more detail.)
Each number in the pseudo-gradient takes some bytes. In 32-bit form it takes 4, in 16-bit form 2. So one full pseudo-gradient is 32 × 109 × 4 = 128 GB in 32-bit, or 64 GB in 16-bit. At 3.125 GB per second the 16-bit one needs 64 ÷ 3.125 = 20.5 seconds to cross. If the sites sent that after every training step, and a step takes 2 seconds, the GPUs would wait 20.5 seconds for every 2 seconds of work. They would be busy under 9% of the time. Sending every 50 steps spreads the same 20.5 seconds over 100 seconds of work, and the picture changes.
One round of the 32-billion-parameter model over a 25 Gbps link. The blue bar is compute between exchanges. The yellow bar is the send. Change the number format, the steps between exchanges, the step time, and whether sending overlaps with compute.
Arithmetic from the post’s figures: about 32 billion parameters, a 25 Gbps link, a 50-step exchange schedule. The 2 seconds per step and the number formats are our assumptions; the post gives neither. The real run also staggers fragments, so its peak traffic is lower than this whole-model send.
At the defaults (16-bit, 50 steps, 2 seconds) compute lasts 100 seconds and the send 20.5 seconds. Without overlap the GPUs idle for those 20.5 seconds, a busy share of 83%. With overlap the send hides behind the next round’s compute, and the busy share is 100%. Now drag the exchange interval down to 1. The state chip turns red and the busy share falls below 10%.
Overlap. Do not stop to send. Keep training while the pseudo-gradient crosses, and apply it when it lands, a few steps late. The post says “a late-arriving update can still be committed”, and in its pairwise experiment a cell blends the result in two steps after sending. The lesson on unreliable and mixed compute covers late arrivals.
Fragments. Split the model into F pieces and send them in turns across the window. With F = 8, each piece in 16-bit is 64 ÷ 8 = 8 GB and crosses in 2.56 seconds. The link carries the same total, but no single burst is large. Streaming DiLoCo (Douillard et al., 2025) does this, and the post borrows the idea.
Compress. Fewer bits per number means fewer bytes. Dropping from 32-bit to 8-bit cuts the 41-second send to 10 seconds. The risk: rounding throws information away.
Overlap has a hidden cost too. The update that lands was computed from parameters a few steps old, so it is slightly stale. The symptom is a loss that ripples after each landing. The measurement is the delay, counted in steps between sending and applying. The fix is a short delay, a lower outer rate, or blending the result in at partial weight, as the post’s pairwise exchange does.
Suppose a weight needs a small push of 0.3 each step, and the link can send only whole numbers (a coarse grid). Rounding 0.3 to the nearest whole number gives 0, every time. After 20 steps the true total is 6.0 and the receiver has 0. All the signal is lost, and it is lost in a biased way.
Error feedback fixes this. Keep the part you could not send, called the residual, and add it to the next value. Step 1: value 0.3, send 0, keep 0.3. Step 2: value 0.3 + 0.3 = 0.6, send 1, keep −0.4. Step 3: 0.3 − 0.4 = −0.1, send 0, keep −0.1. Step 4: 0.2, send 0, keep 0.2. Step 5: 0.5, send 1 (a tie rounds up), keep −0.5. Nothing is lost for good; each lump of 0.3 is delayed, then sent.
The earliest use is 1-bit SGD (Seide et al., 2014). The other option, stochastic rounding, rounds up with probability equal to the fractional part, so the average is right, but any single run is noisy. The post combines both.
Each step the sender wants to send the value you choose, but the link carries only whole numbers. The dashed line is the true running total; the coloured line is what the receiver has. Try each way of rounding.
Toy: 20 steps, a link that carries whole numbers only. Error feedback keeps the residual (value plus carried residual, minus what was sent). Stochastic rounding uses a fixed random seed, so one noisy run is shown, the same on every visit.
With the value at 0.3, nearest rounding ends at 0 of a true 6.0. Error feedback ends at 6 (within 0.5 of the truth at every step, by construction). Stochastic rounding lands near the truth but wobbles. The symptom of missing error feedback is a model that trains slower than the uncompressed run and plateaus higher. The measurement is the gap between the compressed and uncompressed totals. The fix is to keep the residual.
Chapter 9
Keep the numbers, the checklist and the core code, then follow the links to the rest of the series
An optimizer turns a gradient into a step. Plain descent steps against the slope, and its speed limit comes from the steepest direction. Momentum keeps a running total, and Nesterov reads the slope at the look-ahead point. Adam divides each step by the typical gradient size and costs two extra numbers per parameter. A schedule warms the rate up and cools it down. Shampoo uses curvature to reshape the valley. Low-communication training adds a second level: an inner optimizer on each island for H steps, then an outer optimizer on the pseudo-gradient.
| Term | Plain meaning | Number to remember |
|---|---|---|
| Learning rate η | The scale of each step | Plain descent is stable only if η × curvature < 2; DiLoCo’s inner peak is 4 × 10−4 |
| Momentum β | A decaying sum of past gradients | β = 0.9 remembers about 10 steps; a steady gradient moves 10 times farther per step |
| Nesterov | Momentum with the gradient taken at the look-ahead point | Limit ηc < 2(1 + β) / (1 + 2β), which is 1.36 at β = 0.9; DiLoCo outer rate 0.7, momentum 0.9 |
| Adam | Each step divided by the typical size of that knob’s gradient | β1 0.9, β2 0.999, ε 10−8; state of 2 numbers per parameter, 256 GB at 32 billion in 32-bit |
| AdamW | Adam with weight decay applied directly to the weights | Weight decay 0.1 in the DiLoCo setup |
| Warmup and cosine decay | Ramp the rate up, then glide it down | 1,000 warmup steps in DiLoCo’s setup; halfway through a cosine decay the rate is the midpoint of peak and floor |
| Shampoo | Precondition a weight matrix with one small matrix per side | Memory m² + n² per m × n weight; Distributed Shampoo costs at most 10% more per step than diagonal methods |
| Pseudo-gradient | Start of round minus average of the islands after H steps | One tensor the size of the model per island per round |
| DiLoCo | AdamW inside, Nesterov outside, H steps between exchanges | H = 500, 8 workers, 500 times less communication; perplexity 15.02 against 15.30 for an every-step baseline |
| Memory of the two levels | Parameters, Adam state, outer copy, outer buffer | 5 units against 3 for data parallel: 66% more (640 GB against 384 GB at 32 billion in 32-bit) |
| One exchange | Bytes of the model divided by the link speed | 32 billion × 2 bytes ÷ 3.125 GB/s = 20.5 s over a 25 Gbps link |
| Error feedback | Keep what rounding removed and add it to the next send | Turns a total of 0 of 6.0 into 6 in the 0.3-per-step toy |
pythonimport numpy as np def sgd_momentum(p, g, s, lr, beta=0.9): s["v"] = beta * s["v"] + g # velocity return p - lr * s["v"] def nesterov(p, grad_fn, s, lr, beta=0.9): g = grad_fn(p - lr * beta * s["v"]) # gradient at the look-ahead point s["v"] = beta * s["v"] + g return p - lr * s["v"] def adamw(p, g, s, lr, b1=0.9, b2=0.999, eps=1e-8, wd=0.1): s["t"] += 1 s["m"] = b1 * s["m"] + (1 - b1) * g # first moment s["v"] = b2 * s["v"] + (1 - b2) * g * g # second moment mh = s["m"] / (1 - b1 ** s["t"]) # bias correction vh = s["v"] / (1 - b2 ** s["t"]) return p - lr * (mh / (np.sqrt(vh) + eps) + wd * p) # decoupled decay def cosine_lr(t, T, warm, peak=4e-4, floor=4e-5): if t < warm: return peak * t / warm # warmup p = (t - warm) / (T - warm) return floor + 0.5 * (peak - floor) * (1 + np.cos(np.pi * p)) def shampoo_matrix_step(W, G, s, lr, eps=1e-6): s["L"] += G @ G.T # m x m s["R"] += G.T @ G # n x n def inv_root(M, k=4): # M^(-1/k) via eigendecomposition w, Q = np.linalg.eigh(M + eps * np.eye(len(M))) return (Q * w ** (-1.0 / k)) @ Q.T return W - lr * inv_root(s["L"]) @ G @ inv_root(s["R"]) def outer_round(theta, delta, buf, lr=0.7, mu=0.9): # delta = theta - mean(island params) buf[:] = mu * buf + delta return theta - lr * (delta + mu * buf)
The Shampoo step here is the toy form: it uses an eigendecomposition for the inverse roots, which production code replaces with cheaper, less frequent refreshes. Fed the 2 × 2 example from Chapter 6, it returns an update of exactly diag(1, 1). The outer step reproduces the 2.67 and 0.906 of Chapter 7.
Now press Teach and explain, from memory, why Nesterov brakes early and what a pseudo-gradient is. Then go back to the valley and watch the four rules again.