Models
How wrong, and which way
Loss, gradient and backpropagation, worked by hand
The lesson Which token comes next followed a prompt through a finished model. This one starts earlier, when nearly all of the 32.8 billion weights of that model are random numbers and it writes noise. The exceptions are the 676,864 weights of its norm layers, which all start at 1. Pre-training fixes that with one small step repeated a very large number of times. This lesson takes the first half of the step apart: how a batch of text becomes millions of questions with known answers, how one number says how wrong the model was, and how that number is turned into a direction for every weight. Each stage is worked with numbers small enough to check by hand. The next lesson, Every weight moves a little, takes over where the direction is used.
Chapter 1 of 11
One task, repeated
Why nobody has to label the training text
A model that answers in the factory went through several stages of training. Pre-training is the first, and it costs far more than all the others together. It is where the model picks up nearly everything it knows: grammar, facts, how code is written, how a runbook is laid out. All of it comes from one task. Show the model some text, let it guess the token that follows, compare the guess with the token that really follows, and change the weights a little so the guess would have been better.
Most machine learning needs people to supply the answers. To teach a model house prices, someone has to write down what each house sold for. To teach it handwriting, someone has to say which digit each picture shows. Text needs none of that. In the sentence "The pod is stuck in Pending", the answer to "what follows The pod is stuck in" is the next word of the sentence. The data supplies its own answers, which is why this is called self-supervised learning.
That is what lets the training text be as large as the written internet. No team of labellers could keep up, and none is needed. What comes out at the end is called a base model. It continues text and does nothing else. Making it answer like an assistant is a later and much cheaper stage, covered in the lesson From base model to your model.
Chapter 2 of 11
A batch is cut from a stream of tokens
Inputs, and the same tokens shifted by one
Before any arithmetic the text is run through the tokenizer, and what training reads is one long stream of token numbers. A training example is a window cut from that stream. This lesson uses windows of 4,096 tokens. To make one, take 4,097 tokens in a row. The first 4,096 are the input. The last 4,096, which are the same tokens moved along by one, are the targets. Position 0 of the input is paired with position 1 of the stream, and so on to the end.
One window therefore asks 4,096 questions, and the model answers all of them in a single forward pass. That is only fair because of a rule inside attention: a token may look at itself and at what came before it, never at what comes after. So the answer at position 10 is computed without sight of token 11, even though token 11 is sitting in the same window as the input for the next question.
A batch is many windows stacked. With 1,024 windows of 4,096 tokens a batch holds 4,194,304 questions, close to the 4 million tokens per step that the LLaMA papers report. The output head produces 151,936 scores for each of them. For one window alone that is 622 million scores, 1.24 GB at 2 bytes each. For the whole batch it is 1.27 TB, which is one reason a batch of this size is never processed on a single GPU.
Chapter 3 of 11
From scores to shares
Logits, and the two steps of softmax
Follow one of those 4.2 million questions. The input so far is "The pod is stuck in" and the target is Pending. Data moving through the model from tokens to scores is called the forward pass. The raw scores it ends with are called logits. There are 151,936 of them for this one position. To keep the arithmetic visible, pretend the vocabulary has only four entries, and say the model, some way into training, gives Pending 1.5, Running 1.0, Failed 0.0 and purple minus 1.5.
A logit is only a score. It can be negative, it can be larger than one, and the four do not add up to anything in particular. A higher logit means the model rates that token as a better candidate. To compare the guess with the answer the scores have to become shares of 100 percent, and the function that does it is softmax.
Softmax works in two steps. First it raises e, the constant 2.718, to the power of each logit. That makes every number positive and it stretches the gaps, because a logit one higher gives a result 2.718 times larger. Here the results are 4.482, 2.718, 1.000 and 0.223. Second it divides each by their total, 8.423. The shares come out as 53.2, 32.3, 11.9 and 2.6 percent. At inference a token would now be drawn from these shares. In training nothing is drawn, because the answer is already known.
Chapter 4 of 11
One number for one guess
Cross-entropy looks only at the share given to the right token
The model put 53.2 percent on Pending. Training needs a number that says how good that was, and the one used to pre-train nearly every language model is the cross-entropy loss. For a single guess the rule is short. Take the share the model gave to the right token, take its natural logarithm, and flip the sign. Here that is minus ln 0.532, which is 0.631. The shares given to the three wrong tokens do not appear in the formula at all.
The shape of this function is what makes it useful. A share of 90 percent on the right token gives 0.105. A share of 50 percent gives 0.693. From there the loss climbs faster and faster: 10 percent gives 2.303, 1 percent gives 4.605, and one in a thousand gives 6.908. A model that was nearly sure of the right answer has little to fix. A model that put 99.9 percent on purple was sure and wrong, and the loss is large so that the correction is large. Think of a quiz where you must spread a stake over the answers. A small stake on the right answer costs a little, and nearly all of it on a wrong one costs a lot.
A share of 100 percent would give a loss of exactly zero, and no model gets there, because text is not that predictable. After "For lunch I had" many tokens are reasonable. A perfect model would still spread its shares, and its loss would stay above zero.
Chapter 5 of 11
One number for a batch
The average, and the first value you should expect to see
The model makes 4,194,304 guesses in a batch and each has a loss of its own. They are averaged into one number, in the same way a mean squared error is averaged over all the houses in a set. Take six positions with losses of 0.631, 2.303, 0.105, 4.605, 0.223 and 1.204. Their mean is 1.512. That single number is the training loss for the step, and it is what the whole run tries to push down. In PyTorch this is the default behaviour of the cross-entropy function, whose reduction setting is mean.
There is a check hidden in this number that engineers make before anything else. At step 0 the weights are small random numbers and the model knows nothing. Small weights give logits that are all close to each other, so the shares come out nearly even. With 151,936 tokens each gets about one share in 151,936, and the loss should be close to the natural logarithm of 151,936, which is 11.93. For a vocabulary of 50,000 the same sum gives 10.82. Even shares are not the best a model can do without reading the context. Giving each token the share it has across all text, more for " the" and less for " purple", scores lower than 11.93, and a model learns that within its first steps. The 11.93 is simply what nearly equal logits produce.
If the first loss is close to that value, the output head and the loss are wired together correctly. If it is far above, something is probably wrong before training has begun. The weights may have been initialised so large that the model is confident from the start, and that confidence is nearly always misplaced. Or the logits may have the wrong shape or scale, for example a vocabulary size that does not match the tokenizer. A start that is too confident often recovers, after a number of wasted steps. A wrong shape does not. Either way the fix belongs before training, so the first number on the screen is read with care.
This check does not catch every mistake. If the targets are out of line with the inputs, shifted by the wrong amount for example, the first loss is still about 11.93, because nearly equal shares give the same loss whichever token is the target. That mistake shows up later, as a loss that will not go down the way it should.
Chapter 6 of 11
Perplexity, and text the model has not seen
The same loss in a unit that is easier to picture
A loss of 1.512 or 3.4 means little to a person, so it is often converted. Perplexity is e raised to the power of the loss. A loss of 0.631 gives 1.88. A loss of 1.512 gives 4.54. A loss of 2 gives 7.39. At step 0, a loss of 11.93 gives 151,936, which is the size of the vocabulary. That is the way to read it: perplexity is the number of equally likely tokens the model is in effect still choosing between. At 151,936 it is choosing blindly among all of them. At 7.39 it is as unsure as if it had narrowed the next token down to about seven candidates.
The two numbers always move together, since one is a fixed function of the other. A lower loss is a lower perplexity and both mean a better model. Training dashboards plot the loss. Papers and model comparisons often quote perplexity.
Where the number is measured matters more than which form it takes. A model can lower its loss on the training text by memorising it. So some text is held back and never trained on. A validation set is checked during the run, and a test set is kept for the end. Perplexity is normally reported on held-out text of this kind. A low loss there means the model has learned patterns that carry over to text it has never seen, which is the whole purpose of training it.
Chapter 7 of 11
A slope for every weight
Derivative, partial derivative, gradient
The loss says how wrong the model was. It does not say what to change. For that each weight needs a slope. Start with a model that has one weight, w. Change w by a tiny amount and the loss changes by a tiny amount too. The ratio of the two, change in loss divided by change in weight, is the derivative. Its sign gives the direction. A positive derivative means raising the weight raises the loss, so the weight should go down. A negative one means raising the weight lowers the loss, so it should go up. Its size says how sensitive the loss is to that weight.
A real model has billions of weights, and the same question is asked of each one in turn: if this weight moves a little and every other weight stays frozen, how much does the loss move. The answer for one weight is called a partial derivative. Collect the partial derivatives of every weight into one long list and that list is the gradient. For this model it has 32,762,123,264 entries, one per weight.
Taken as a whole the gradient points in the direction in which the loss rises fastest. Training goes the other way. The plain rule is: new weight equals old weight minus the learning rate times that weight's slope. The learning rate is a small number that sets the size of the step. The rule is applied to every weight at once.
Chapter 8 of 11
The slope at the scores
Share minus target, and one step to see it work
Go back to the four logits. When softmax is followed by cross-entropy, the slope of the loss with respect to each logit takes a very plain form: the share the model gave that token, minus the target share. The target is 1 for the right token and 0 for every other. Pending got 0.532 and should have had 1, so its slope is minus 0.468. Running got 0.323 and should have had 0, so its slope is plus 0.323. Failed is plus 0.119 and purple plus 0.026.
Read those with the update rule in mind. The step goes against the slope. Pending has a negative slope, so its logit goes up. The other three have positive slopes, so their logits go down, each in proportion to the share it took. Running took the most from Pending and is pushed down the most. Purple took almost nothing and is barely touched. The four slopes add up to zero.
Take one step with a step size of 1 to see it work. The logits become 1.968, 0.677, minus 0.119 and minus 1.526. Through softmax, Pending now has 70.0 percent where it had 53.2, and the loss falls from 0.631 to 0.357. There is a catch. A logit is an output, produced by all the weights below it, and it can't be set directly. The real question is how each of 32.8 billion weights should move so that the logits move this way.
Chapter 9 of 11
The chain rule, link by link
A small network, run forwards with every result written down
A neural network is a long chain of simple operations: multiply by weights, add a bias, apply a simple curve, multiply again, and at the end softmax and the loss. Each operation takes the output of the one before. The rule that says how something early in a chain affects something at the end is the chain rule, and capacity planning uses it every day. Say one more request per second needs half a GPU more, and one GPU costs 3 euros an hour. Then one more request per second costs 0.5 times 3, which is 1.5 euros an hour. The effect of the whole chain is the product of the effects of its links.
Here is a network small enough to follow every number. It has two weights and a bias. The input x is multiplied by w1 to give h. Then h goes through a curve called ReLU, which passes positive numbers unchanged and turns negative ones into zero, giving a. Then a is multiplied by w2 and the bias b is added, giving the output y. The loss is the squared gap between y and a target. Squared error is used here because its arithmetic is short. A transformer with cross-entropy follows exactly the same procedure with many more links.
Set x to 2, w1 to 0.5, w2 to 3, b to 1 and the target to 2. The forward pass gives h = 1, a = 1, y = 4, a gap of 2 and a loss of 4. Every one of those intermediate results is kept, because the backward pass will need them.
Chapter 10 of 11
Backwards by hand
Backpropagation is the chain rule applied from the loss back to the input
Now walk the chain in reverse, asking at each link how much the loss changes if this value changes. The loss is the gap squared, and the slope of a square is twice the thing squared, so the slope at the gap is 2 times 2, which is 4. The gap is y minus the target, so y moves it one for one and the slope at y is also 4. Next, y is w2 times a plus b. Raising b by one raises y by one, so the slope for b is 4. Raising w2 by one raises y by a, which is 1, so the slope for w2 is 4. Raising a by one raises y by w2, which is 3, so the slope at a is 12.
The ReLU link passes the slope on unchanged when its input was positive, and blocks it when its input was negative. Here h was 1, so the slope at h is 12. Last, h is w1 times x, so the slope for w1 is 12 times 2, which is 24. This procedure is backpropagation: each stage is handed the slope of its output and works out the slopes of its inputs and its weights.
All three slopes are positive, so all three values should fall, which is right because the output was 4 and the target 2. With a learning rate of 0.005 the loss drops from 4 to 1.55. Nudging w1 by 0.001 and rerunning gives a slope of 24.04, which confirms the result. That check costs one forward pass per weight, plus one to start from. Backpropagation costs one backward pass in total, about twice a forward pass.
Chapter 11 of 11
The framework keeps the tape
Autograd, five lines of PyTorch, and what it costs in memory
Nobody writes those derivatives out for a transformer with 64 blocks. A deep learning framework such as PyTorch or JAX does it with automatic differentiation, autograd for short. While the forward pass runs, the framework records every operation: which values went in and which came out. The record is called the computational graph. For the small network it has six nodes: a multiply, a ReLU, a multiply, an add, a subtract and a square. Each node knows how to compute its output, and it knows its own local slope. The multiply node knows that its output changes by one input when the other input goes up by one. No node knows anything about the rest of the network.
A training step in PyTorch comes down to five lines. The first runs the model on the inputs and records the graph. The second computes the cross-entropy loss against the targets. The third, loss.backward(), walks the graph in reverse and stores a slope for every weight in that weight's .grad attribute. The fourth, optimizer.step(), uses the slopes to update the weights. The fifth, optimizer.zero_grad(), clears the slopes. It is needed because backward() adds to whatever .grad already holds. Leave it out and the slopes of old batches pile up, and the model drifts in directions no batch asked for.
Autograd has a cost in memory. The backward pass needs the intermediate results of the forward pass, so they are all held until it has finished. These stored results are called activations. For a transformer reading thousands of tokens through 64 blocks they can take more GPU memory than the weights.
What to keep
A direction for every weight
A training step begins with a batch cut from a stream of tokens, where the targets are the inputs shifted by one. The forward pass gives a logit for every token at every position, and softmax turns logits into shares. The cross-entropy loss is minus the logarithm of the share on the right token, averaged over the batch into one number that starts near the logarithm of the vocabulary size. The slope of that number at each logit is the share minus the target. Backpropagation carries the slopes back through every operation with the chain rule, in one backward pass that costs about two forward passes. Autograd records the forward pass so this happens automatically, at the price of keeping every intermediate result in memory.