Models
Every weight moves a little
From plain gradient descent to AdamW, the schedule and the batch
The lesson How wrong, and which way ended with a slope for each of the model's 32,762,123,264 weights. This one is about the piece of code that uses them, the optimizer. The plain rule, weight minus learning rate times slope, is not good enough for a language model, and the reasons lead step by step to AdamW, which trains nearly every large model today. The lesson then covers the settings around it: how the learning rate warms up and decays, how large a batch should be, how a batch too large for memory is built from small ones, why slopes are clipped, and what a run saves so that it can be resumed.
Chapter 1 of 12
Plain steps on noisy slopes
Stochastic gradient descent, and its two problems
The optimizer is the code behind the call optimizer.step(). The simplest one applies the rule from the last lesson unchanged: new weight equals old weight minus the learning rate times the slope. When the slope comes from a random batch of the data, and not from all of the data at once, the method is called stochastic gradient descent, SGD. Stochastic means random.
Because each batch is a random sample, its slope is a noisy estimate. It points roughly downhill and never exactly. One batch may be mostly Python code and the next mostly recipes, and each pulls the weights its own way. Follow one weight whose true slope over all the text is plus 0.15. Three batches in a row report plus 0.30, minus 0.10 and plus 0.26. With a learning rate of 0.1 the weight goes from 0.500 to 0.470, back up to 0.480, then down to 0.454. It gets there, and it wastes movement on the way.
That is the first problem with plain SGD: noisy slopes make the weights zigzag. The second is that one learning rate has to serve every weight. Some weights get a large slope on every step. Others, such as the embedding row of a rare token, get a small slope once in a while. A rate that is safe for the busy weights barely moves the quiet ones. The next chapters fix the two problems one at a time.
Chapter 2 of 12
Momentum: a running average of slopes
Keep what the batches agree on, cancel what they don't
Plain SGD has no memory. At each step it looks at the slope under it, moves, and forgets. A ball rolling down a hill does not behave like that. It builds up speed in the direction it has been rolling and is not turned around by one small bump. Momentum gives the optimizer the same kind of memory. For each weight it keeps a running average of recent slopes and moves along the average.
The average is updated with a simple rule. Take nine tenths of the old average and add one tenth of the new slope. The 0.9 is a setting named beta1. Follow two weights. The first gets a slope of plus 1 on six steps in a row. Its average climbs 0.100, 0.190, 0.271, 0.344, 0.410, 0.469 and keeps heading for 1. Every batch agrees, so the signal builds. The second gets plus 1, minus 1, plus 1, minus 1. Its average goes 0.100, minus 0.010, 0.091, minus 0.018, 0.084, minus 0.025 and stays close to zero. The batches disagree, so the noise cancels and the weight is barely moved.
That is the first problem solved: the zigzag is averaged away and the steady direction is kept. The price is one more number stored for every weight. Notice also that the average starts at zero and takes many steps to catch up with a steady slope. After six steps of plus 1 it has reached only 0.469. A later chapter deals with that.
Chapter 3 of 12
A step size for every weight
Adam's second average tracks how large the slopes are
The second problem was that weights differ widely in how large their slopes usually are. The fix is to give each weight a step size of its own, and the optimizer that adds this to momentum is called Adam. Adam keeps two running averages for every weight. The first is the average slope from the last chapter, which says which way the weight has been pushed. The second is a running average of the squared slope. Squaring removes the sign, so this one tracks how large the slopes of this weight usually are, whichever way they point. Its setting is named beta2 and is usually 0.999 or 0.95.
To take a step Adam divides the first average by the square root of the second. Roughly, the step is the learning rate times the average slope over the usual size of the slope. That division normalises every weight. A weight whose slopes are huge has a huge number under the line, and its step shrinks. A weight whose slopes are tiny has a tiny number under the line, and its step is boosted.
Take two weights with a learning rate of 0.001. The first gets a slope of 20 on every step, the second a slope of 0.002, ten thousand times smaller. Plain SGD would move the first by 0.02 and the second by 0.000002. Adam moves both by 0.001. A weight's step now depends on how consistent its slopes are, and no longer on their raw size. The embedding row of a rare token finally moves at a useful pace.
Chapter 4 of 12
The first steps, and bias correction
Both averages start at zero and have to be scaled up
Both of Adam's averages start at zero, and that makes them too small at the beginning. After the first step, with beta1 at 0.9, the average slope holds one tenth of the first slope. After the first step, with beta2 at 0.999, the average squared slope holds one thousandth of the first squared slope. Used as they are, they would give a wildly wrong step.
Adam corrects for this before every step. It divides the first average by one minus beta1 to the power of the step number, and the second by one minus beta2 to the same power. At step 1 those divisors are 0.1 and 0.001, which exactly undo the shrinkage. As the step number grows the divisors approach 1 and the correction fades away.
Follow one weight with a learning rate of 0.001 and slopes of 0.4, 0.2 and 0.3. At step 1 the corrected averages are 0.4 and 0.16, and the step is 0.001 times 0.4 over the root of 0.16, which is exactly 0.001. At step 2 the step is 0.00093, and at step 3 it is 0.00095. Two things follow. The first step of every weight is one learning rate in size, whatever its slope. And as long as the slopes keep their sign, the steps stay close to the learning rate. The Adam paper states this as a rule: the size of a step is approximately bounded by the learning rate. That is why the learning rate is the setting that matters most.
Chapter 5 of 12
A weight that can't decide
Flipping slopes give a small step, and what epsilon is for
The division has one more effect, and it is the most useful one. Take a weight whose slope flips between plus 0.5 and minus 0.5 on every step. The slopes are as large as before, so the second average is the same as for a steady slope of 0.5, and its root is 0.5. The first average is different. The pluses and minuses cancel, so it stays near zero. A small number divided by 0.5 is small. Adam is saying, in effect: the batches disagree about this weight, so it will not be moved much.
The numbers show it. With a learning rate of 0.001 the first step is the full 0.001, since one slope alone looks like a steady direction. The second is minus 0.00005, the third plus 0.00034, the fourth minus 0.00005. After the first step the weight moves a twentieth to a third of the learning rate, and in alternating directions, so it stays almost where it was. A weight with a steady slope of 0.5 would have moved 0.004 in the same four steps.
One small constant completes the formula. The step divides by the root of the second average plus epsilon. Epsilon is there so that a weight whose slopes have all been zero does not cause a division by zero. The paper's default is one part in a hundred million. Llama 2 reports a larger value, one part in a hundred thousand, which also caps the boost given to weights with very small slopes.
Chapter 6 of 12
AdamW: decay, kept apart
A steady pull towards zero that does not pass through the averages
Large language models are almost always trained with a version of Adam named AdamW. The W stands for weight decay. On every step, before the Adam step, each weight is shrunk a little towards zero: it loses the learning rate times the decay setting times its own value. With a learning rate of 0.00015 and a decay of 0.1, a weight of 0.8 loses 0.000012, which is fifteen millionths of itself. It works like a small tax on size. A weight that is large has to keep earning it through slopes that push it back out. That stops the model leaning on a handful of huge weights and tends to make training steadier.
The word decoupled is the point of AdamW. The older way was to add the decay into the slope, as decay times weight, and then run Adam as usual. But Adam divides every slope by the usual size of that weight's slopes. So the decay was divided too, and weights with large slopes were decayed less than weights with small ones. AdamW applies the decay directly to the weight, outside the two averages, so every weight is taxed at the same rate.
Adam's memory has a cost. The two averages are two more numbers for every weight. For this model that is 65.5 billion extra numbers, and at 4 bytes each they take 262 GB, twice the 131 GB of the weights themselves at 4 bytes. The optimizer's state is the largest part of the model state held in memory during training. The activations kept for the backward pass are counted apart, and they grow with the window length and the batch, so with long windows or large batches they can be larger still.
Chapter 7 of 12
Warm-up
The learning rate starts near zero and climbs
Whatever the optimizer, one setting matters more than almost any other: the learning rate. Too small and training crawls. Too large and each step overshoots, and the loss can climb without limit, which is called diverging. For a large model the rate is not held at one value. It follows a plan called the learning rate schedule, and the usual plan has two parts, a warm-up and a decay.
Warm-up is the start of the run. The rate begins near zero and rises in a straight line to its peak over the first few thousand steps. There are two reasons to begin slowly. The weights are random, so the slopes are large and point in directions that will not last. And Adam's averages are young. The second average has seen only a few batches and is a poor estimate of each weight's usual slope size, yet every step is divided by it. Remember that an Adam step is about one learning rate in size for every weight. A full-size rate from step 1 would move all 32.8 billion weights by that much on the strength of one batch, and the model could land somewhere it never recovers from.
In the run this lesson follows, the peak is 0.00015 and the warm-up is 2,000 steps, the figures the LLaMA papers report for their larger models. The rate at step 1 is 0.000000075. At step 500 it is 0.0000375, a quarter of the peak. At step 2,000 it reaches 0.00015.
Chapter 8 of 12
Cosine decay
From the peak down to a tenth of it
After warm-up the learning rate falls for the rest of the run. The most common shape is half a cosine wave. The rate drops slowly at first, fastest in the middle of the run, and flattens out again near the end. The reason to decay at all is that the job changes. Early on the model is far from a good solution and large steps cover ground quickly. Later it is in a good region, and large steps would make it bounce around the best point without settling. Smaller steps let it adjust its weights more precisely.
The formula has four inputs: the peak rate, the lowest rate, how far the run has come and how long it is. The rate is the lowest rate plus half the gap between peak and lowest, times one plus the cosine of pi times the fraction of the decay completed. This lesson's run has 160,000 steps of 4,194,304 tokens, 671 billion tokens in all, and decays to a tenth of the peak as LLaMA does. Those 671 billion tokens are close to the 655 billion that the rule of about 20 tokens per weight gives this model. Qwen3's real run was far longer, 36 trillion tokens, and the lesson A training run at scale works with that figure. The step counts, run times and loss values in this lesson belong to the shorter run. A quarter of the way through the decay the rate is still 0.00013. Halfway it is 0.0000825, the midpoint of peak and floor. At the end it is 0.000015.
The peak itself depends on the size of the model. LLaMA used 0.0003 for its 7 and 13 billion models and 0.00015 for the larger ones. Llama 3 used 0.00008 for 405 billion. Larger models take smaller peaks. The usual explanation, a rule of thumb rather than a proven cause, is that with more weights the same step in each changes the model's behaviour by more.
Chapter 9 of 12
How big a batch
Cleaner slopes against fewer updates
Every step uses a batch, and the loss is a mean over every token in it, so the slope is a mean over all those tokens too. That averaging is what makes the slope trustworthy. A slope from one sentence is very noisy. If the sentence is about medieval history, it pushes the model in a direction that is good for medieval history and random for everything else. Average over millions of tokens from every kind of text and the noise cancels, leaving a direction that helps across the board. Larger batches also suit GPUs, which are built to do a great many calculations side by side.
A larger batch has a price. For the same amount of text it means fewer updates. This lesson's 671 billion tokens make 160,000 steps at 4,194,304 tokens a step. At four times the batch they would make 40,000. And the gain fades: noise in a mean falls with the square root of the count, so four times the batch only halves it. Past a point each step costs much more compute without being a much better step.
So the batches are large and finite. LLaMA and Llama 2 used 4 million tokens. GPT-3 used 3.2 million for its largest model. Many runs also grow the batch as they go. Early on the model is learning obvious patterns and even a rough slope points somewhere useful. Later the patterns are subtler and a cleaner signal is worth paying for. Llama 3's largest model began at 4 million tokens and ended at 16 million.
Chapter 10 of 12
One big batch from several small ones
Gradient accumulation, and the division it needs
A batch of four million tokens does not fit on one GPU. The results kept for the backward pass would overflow its memory long before. Here the behaviour of PyTorch that looked like a trap turns out to be useful. A call to backward() adds its slopes to whatever .grad already holds. So the batch can be split into smaller pieces called micro-batches. Run the forward and backward pass on the first micro-batch, and its slopes are stored. Run the second, and its slopes are added on top. Only after the last one is optimizer.step() called, followed by optimizer.zero_grad(). The stored results of each micro-batch are freed before the next one starts, so memory only ever holds one of them.
One detail decides whether the result equals one big batch. The loss of each micro-batch is a mean over its own tokens. Add up the slopes of four micro-batches and you have four times the slope of the big batch. So each micro-batch's loss is divided by the number of micro-batches before backward() is called. PyTorch's own example of accumulation does exactly this.
Take one weight and four micro-batches with slopes of 0.8, 1.2, minus 0.4 and 0.4. Divided by four and added up, .grad holds 0.2, then 0.5, then 0.4, then 0.5. The mean of the four slopes is 0.5, so the two agree exactly. Without the division .grad would end at 2.0. The cost of accumulation is time: four micro-batches take four passes where one large batch would take one.
Chapter 11 of 12
Clipping the gradient
A limit on the length of the whole gradient
Sometimes one batch produces a gradient far larger than usual: a run of odd text, or a position where the model was sure and badly wrong. Adam's division softens this but does not remove it, since the average squared slope takes many steps to react. One oversized step can undo thousands of careful ones. The usual guard is gradient clipping, and nearly every large run uses it. Llama 2 reports gradient clipping of 1.0. GPT-3 reports clipping the global norm of the gradient at 1.0.
The global norm is the length of the gradient when all its numbers are treated as one long list: square every slope, add them all up, take the square root. Clipping sets a limit on that length. If the norm is at or below the limit, nothing changes. If it is above, every slope is multiplied by the same factor, the limit divided by the norm, so the length comes down to the limit. Because every slope is scaled by the same factor, the direction of the gradient is unchanged. Only its length is.
A gradient of three numbers shows it. The slopes 3, 4 and 12 have a norm of 13. With a limit of 1.0 each is multiplied by one thirteenth and becomes 0.231, 0.308 and 0.923, a list whose norm is 1. In the training loop clipping sits between backward() and step(), and the function returns the norm it measured, which makes it a useful number to log.
Chapter 12 of 12
What a run writes down
Checkpoints, and the numbers to watch
A run of 160,000 steps lasts days or weeks, and hardware fails in that time. So the run saves a checkpoint at intervals: a file from which training can continue as if nothing had happened. The weights alone are not enough for that. The PyTorch tutorial on saving says a checkpoint for resuming must also hold the optimizer's state, because it contains buffers that are updated as the model trains. Those buffers are Adam's two averages and its step count. Without them a resumed run would start with empty averages, and its first steps would be the blind ones that warm-up exists to tame. The position in the learning rate schedule is saved for the same reason. So are the data reader's position, so the resumed run neither repeats nor skips text, and the random-number generators' state.
The size follows from the bytes. The 4-byte weights are 131 GB and the two averages are 262 GB, so a full checkpoint of this model is about 393 GB. The tutorial gives the same picture in general terms: such a checkpoint is often two to three times larger than the model alone.
While the run goes on, a few numbers are watched. The first loss should be near 11.93. The training loss should then fall quickly and later slowly. The loss on held-out text should fall with it. The gradient norm, measured before clipping, shows trouble early: a sudden jump often comes just before a spike in the loss. Runs do sometimes spike or diverge. The Llama 3 paper notes that its recipe was stable, with few loss spikes and no interventions needed.
What to keep
Slopes in, small moves out
Plain gradient descent on random batches zigzags and gives every weight the same step size. A running average of the slopes removes the zigzag. A running average of the squared slopes gives each weight a step of its own, and together they are Adam, whose steps are about one learning rate in size for any weight with a steady slope. AdamW adds a decay applied straight to the weight. Around the optimizer sits a schedule that warms the learning rate up and lets it fall along a cosine curve, a batch of millions of tokens that can be built from micro-batches, and a clip on the length of the gradient. A checkpoint saves the weights together with the optimizer's averages, three numbers for every weight.