How a language model learns
9 min read
One loop, used twice
Training a language model is one loop that repeats millions of times. The model reads some text and guesses the next token. A LossOne number that says how wrong a model's predictions were. For LLMs it is usually cross-entropy: the negative logarithm of the probability the model gave to the true next token. says how much probability the model gave to the right token. An optimiser then changes the weights a little, using Gradient descentA training method that uses gradients to update trainable parameters in a direction that reduces the loss, repeating the process across examples., so the right token gets more probability next time.
The Lessons Predicting the next token and Loss and gradient descent explain each step in detail. This Lesson uses them for one purpose: to show that fine-tuning is not a different kind of learning. It is the same loop, started from a model that has already learned a lot, and fed a smaller and more focused set of examples.
The loop in miniature
The program below shrinks the loop until you can read all of it. The "model" is a list of four scores, one for each word that might follow the word "my". A softmax turns the scores into probabilities. Each training example is a word that really followed, and each step moves the scores toward it.
import math
vocab = ["cat", "dog", "invoice", "password"]
def softmax(scores):
exps = [math.exp(s) for s in scores]
total = sum(exps)
return [e / total for e in exps]
def train(scores, next_words, epochs, rate):
for _ in range(epochs):
for word in next_words:
probs = softmax(scores)
for i, name in enumerate(vocab):
scores[i] -= rate * (probs[i] - (1 if name == word else 0))
def show(label, scores):
probs = softmax(scores)
print(label, {name: round(p, 2) for name, p in zip(vocab, probs)})
scores = [0.0] * len(vocab)
show("start ", scores)
train(scores, ["cat", "dog", "cat", "dog"], epochs=20, rate=0.1)
show("pre-trained", scores)
train(scores, ["invoice", "password", "invoice", "password"], epochs=20, rate=0.1)
show("fine-tuned ", scores)It prints:
start {'cat': 0.25, 'dog': 0.25, 'invoice': 0.25, 'password': 0.25}
pre-trained {'cat': 0.43, 'dog': 0.45, 'invoice': 0.06, 'password': 0.06}
fine-tuned {'cat': 0.09, 'dog': 0.09, 'invoice': 0.4, 'password': 0.42}Read the three lines in order. At the start every word is equally likely. After the first training run on pet sentences, the model puts its probability on cat and dog. Then the same function runs again on support sentences, and the probability moves to invoice and password. Nothing about the code changed between the two runs. Only the examples did.
The last line also shows something to watch for. Once the model learned the new examples, the probability of cat and dog fell from about 0.44 to 0.09, because the second run never mentioned them. A real model is much more robust than four scores, but the same effect appears in a milder form, and the Lesson Catastrophic forgetting covers how to measure and limit it.
What a real model adds
A real model has the same loop with larger parts.
- The scores come from parameters. They are not stored in a table. A transformer computes them from the whole context, using billions of weights, and one weight affects many predictions.
- The loss averages over many tokens. A single example is a whole passage, and the loss is the average over every position.
- Updates come in batches. The optimiser averages the correction from a batch of examples, which makes each step steadier. The Lesson Batch size, epochs and steps explains this.
- The step size is controlled. A learning rate scales each correction, and it is usually raised and lowered on a schedule.
| Pre-training | Fine-tuning | |
|---|---|---|
| Start | Random weights | A model that already works |
| Data | Trillions of tokens of broad text | Hundreds to thousands of focused examples |
| Length | Weeks on thousands of chips | Minutes to hours on one or a few |
| Aim | Learn language and general knowledge | Change behaviour for one job |
| Risk | Cost, and poor data | Forgetting, and copying mistakes in the examples |
What the loss does and does not tell you
A lower loss means the model gave more probability to the tokens in your examples. It does not mean the answers are useful or true. A model can reach a very low loss on a small dataset by memorising it, and fail on every new question. That is why the next Lessons keep some examples out of training and test on them, as Training, validation and test sets explains.
Which weights change
Training does not have to update every weight. In full fine-tuning the optimiser changes all of them. In methods such as LoRA, most weights stay frozen and only a small added set learns. The loop is identical, and only the list of weights that receive updates is shorter. The Lesson Kinds of fine-tuning compares the options.
For more on how this is done with a library, see the Hugging Face causal language modelling guide.
What does a language model learn to do during training?
A model reads 'The cat sat on the' and has to produce one next token.
Training adjusts the weights so that the correct next token gets a higher probability.
What does the loss measure?
During training the loss number falls from 2.4 to 1.1.
Loss is a score of prediction error. Training tries to lower it by changing the weights.
Why does fine-tuning start from a pre-trained model?
You have 3,000 examples, which is tiny next to the text used for pre-training.
Pre-training gives broad ability. Fine-tuning adapts it to your task with far less data and compute.
Your reading position is saved
0 of 36 complete
Lesson complete
How a language model learns
Up next