Training and Fine-Tuning
How a language model is pretrained on raw text, how fine-tuning turns it into an assistant, and when to fine-tune instead of prompting or retrieval.
On this page
Training is the process that sets the numbers inside a language model, and it happens in stages. Pretraining on a huge amount of raw text gives the model its knowledge and its command of language, and later fine-tuning stages change how it behaves, so that it answers questions instead of just continuing text. Knowing which stage produces what tells you which problems a better prompt can fix and which need a different model or extra training.
A model that has only been pretrained is called a base model. Given a question, it continues the text the way the web usually does, which often means writing more questions. An assistant needs the extra stages described below.
Pretraining on raw text
A language model outputs a chance for every possible next token (see What Is an LLM). Pretraining teaches it to give good chances, and it needs no human labels. Each training step works as follows:
- Take a piece of real text, for example "The cat slept on the mat".
- Hide the next token and ask the model for its chances for that position.
- Measure how surprised the model was by the real next token.
- Adjust the model's numbers so that it would be slightly less surprised next time.
Because the correct answer is simply the next token in the text, every position in every document is a free practice question. That is why pretraining can use far more text than any labelling effort could cover.
The surprise is measured by the loss, which is minus the natural log of the chance the model gave to the real token. A chance of 0.9 gives a loss of about 0.11, and a chance of 0.01 gives about 4.6. Training means making the average loss over the whole dataset go down.
One training step in detail
Suppose a model predicts the last word of "The cat slept on the ___" from three options, and the real word is "mat". Softmax turns the model's raw scores into chances, as in the attention lesson.
The adjustment is made by subtracting rate × (chance − target) from each word's score. Here rate is the learning rate, and the target is 1 for the real word and 0 for the others. The further a chance is from its target, the bigger the adjustment. This is gradient descent, as described in How Models Learn. The example adjusts three scores directly, whereas a real model adjusts the billions of parameters that produce them.
chances = softmax(scores)loss = -ln(chances[real word])for each word i: target = 1 if i is the real word else 0 scores[i] -= rate * (chances[i] - target)- word0mat1sofa2moonscore00112-1chance00.2410.6720.09
- loss
- 1.41
- rate
- 1
1The model prefers "sofa", but the real word was "mat". It gave "mat" a chance of only 0.24 (0.245 before rounding), so the loss is −ln(0.245) ≈ 1.41.
- word0mat1sofa2moonscore00.7610.332-1.09
- rate
- 1
2The first nudge uses a rate of 1. The score for mat goes from 0 to 0.76, because 0 − (0.24 − 1) = 0.76. The score for sofa drops from 1 to 0.33, and the score for moon drops from −1 to −1.09. The word whose chance is furthest from its target moves the most.
- word0mat1sofa2moonscore00.7610.332-1.09chance00.5510.3620.09
- loss
- 0.6
- rate
- 1
3With the new scores, "mat" leads with a chance of 0.55, and the loss has dropped from 1.41 to 0.60.
- word0mat1sofa2moonscore01.21-0.032-1.18chance00.7210.2120.07
- loss
- 0.33
- rate
- 1
4After a second nudge, "mat" has a chance of 0.72 and the loss is 0.33.
- word0mat1sofa2moonscore01.481-0.242-1.24chance00.810.1420.05
- loss
- 0.22
- rate
- 1
5After a third nudge, "mat" has a chance of 0.80 and the loss is 0.22 (the chances add to 0.99 because of rounding). Each step improves less than the one before, because the chance is already close to the target.
- word0mat1sofa2moonscore01.681-0.382-1.3chance00.8510.1120.04
- loss
- 0.16
- nudges
- 4
6After four nudges, "mat" has a chance of 0.85 and the loss is 0.16, down from 1.41. A real model never gets this sentence perfect, because it has to leave some chance for "sofa" to cover the texts where the cat slept on the sofa.
The last step of the trace shows how pretraining works in general. Training pulls the chances toward what is common across millions of similar texts, so the model ends up with good guesses and does not store documents. The exception is text that appears many times, such as famous quotations, which a model can reproduce word for word.
function softmax(scores) {
const biggest = Math.max(...scores);
const exps = scores.map((s) => Math.exp(s - biggest));
const total = exps.reduce((a, b) => a + b, 0);
return exps.map((e) => e / total);
}
// One training step on one example. Returns the new scores and the loss.
function trainStep(scores, correct, rate) {
const chances = softmax(scores);
const loss = -Math.log(chances[correct]); // surprise at the real word
const newScores = scores.map((s, i) => {
const target = i === correct ? 1 : 0;
return s - rate * (chances[i] - target); // the nudge
});
return { newScores, loss };
}
let scores = [0, 1, -1]; // mat, sofa, moon
for (let step = 0; step < 4; step++) {
const { newScores, loss } = trainStep(scores, 0, 1);
console.log(loss.toFixed(2)); // 1.41, 0.60, 0.33, 0.22
scores = newScores;
}import math
def softmax(scores):
biggest = max(scores)
exps = [math.exp(s - biggest) for s in scores]
total = sum(exps)
return [e / total for e in exps]
# One training step on one example. Returns the new scores and the loss.
def train_step(scores, correct, rate):
chances = softmax(scores)
loss = -math.log(chances[correct]) # surprise at the real word
new_scores = []
for i, (s, c) in enumerate(zip(scores, chances)):
target = 1 if i == correct else 0
new_scores.append(s - rate * (c - target)) # the nudge
return new_scores, loss
scores = [0, 1, -1] # mat, sofa, moon
for step in range(4):
scores, loss = train_step(scores, 0, 1)
print(f"{loss:.2f}") # 1.41, 0.60, 0.33, 0.22Real pretraining runs this idea over trillions of tokens, in batches, on large clusters of specialised chips for weeks or months. That cost is the reason only a few organisations pretrain large models from scratch, and most teams start from an existing one.
From base model to assistant
Two further stages, both much smaller than pretraining, turn a base model into an assistant. Without them, the model behaves like this:
Instruction tuning
Instruction tuning uses the same next-token method as pretraining, but on a small set of carefully written conversations, each consisting of a request and a good reply. The model learns that a user turn is followed by a helpful assistant turn. This stage mainly teaches format and behaviour. The knowledge still comes from pretraining, which is why a small dataset is enough.
The weakness of instruction tuning is that the model only imitates the replies it was shown. If the examples are inconsistent, or they all share one style, the model copies that inconsistency or style. The quality of the examples matters more than their number.
Preference tuning
Preference tuning starts from the instruction-tuned model. The model writes several answers to the same request, and these answers are compared. The judge can be a person, a separate model trained on human judgements, or an automatic check such as whether generated code passes its tests. Training then makes the preferred kinds of answers more likely.
Much of an assistant's tone, its caution and its habit of reasoning step by step comes from this stage. It also has a known cost. Models can learn to produce answers that look good to the judge, such as confident or agreeable answers, even when the content is wrong. This is one reason assistants sometimes agree with a user who is mistaken.
Fine-tuning a model for your own use
Teams can also fine-tune an existing model on their own examples, using the same method as instruction tuning. A typical goal is to make the model always produce a particular output format or follow a house style. The training data is a set of input and ideal-output pairs, usually hundreds to a few thousand of them.
There are two common ways to do this. Full fine-tuning updates all of the model's parameters, which needs a lot of memory and produces a complete new copy of the model. Parameter-efficient methods keep the original parameters frozen and train a small set of added parameters, often called an adapter. This is much cheaper, and one base model can serve many adapters. Hosted services usually hide this choice and expose fine-tuning as an upload-and-train workflow.
Fine-tuning fits when you need consistent behaviour that prompting cannot deliver reliably, or when a short fine-tuned prompt would replace a long one that you send with every request. It does not fit when the problem is missing information. A fine-tuned model also has to be retrained when the base model is replaced, so you take on that maintenance work.
Pitfalls
What this changes in practice
Try the cheaper options first, in this order. Improve the prompt, and add examples to it. If the model lacks information, supply the information through retrieval. Only when behaviour is still unreliable should you fine-tune, because it requires a dataset, training runs, evaluation and retraining whenever the base model changes. If you do fine-tune, write your evaluation before you start, so you can tell whether the new model is actually better (see Evals).
Knowing the stages also helps you read a model's behaviour. Odd or fluent wrong facts come from pretraining and are discussed in Why Models Hallucinate. Excess caution, tone and agreeableness mostly come from preference tuning, and a system prompt can adjust them only to a limited degree.
For each situation, choose the best first approach: a better prompt, documents in the prompt (retrieval), or fine-tuning. Give a one-sentence reason.
Show a sample answer
- Retrieval. Prices are specific facts that change, so put the current price list in the prompt. Fine-tuning would bake in numbers that go stale.
- A prompt with examples first, and fine-tuning if that is not enough. A few examples in the prompt often get the format right. If the format still slips at that volume, fine-tuning on many correct replies gives more consistent behaviour.
- A better prompt. State the length and tone you want, for example "under 100 words, plain and friendly". Training would be far more work for a problem that an instruction solves.
In general, start with the prompt, add information with retrieval, and fine-tune only for behaviour that you cannot get reliably any other way.
Check yourself
The model gave the real next token a chance of 0.5. What is the loss?
Where does pretraining get its correct answers from?
A base model answers a question with a list of more questions. Which stage fixes this?
Your assistant gives wrong answers about this week's shipping rules. What is the best first fix?
What to practise next
Sampling and Temperature covers how one token is chosen from the chances a trained model produces. RAG Basics shows how to give a model current information without training it.