Sub topic 8
Fine-tuning: changing the model's behavior
This chapter assumes you have called a chat-style LLM API, can read Python, and know what a context window is. Earlier chapters covered prompting and RAG. Here you will learn what fine-tuning changes inside a model, which problems it fits, and how it fails.
What fine-tuning changes
Prompting and RAG leave the model alone. They change the input. Fine-tuning changes the model. You continue training a pretrained model on your own examples, and the optimizer updates its weights so that the outputs in your examples become more likely.
Each training example pairs an input with the exact output you want. After training, the model produces that kind of output without being told to in the prompt. You have moved instructions out of the prompt and into the weights.
That makes fine-tuning a tool for behavior. It is a poor tool for knowledge. A model trained on a few hundred examples does not reliably memorize the facts inside them. It picks up patterns such as tone, structure, vocabulary, and how to handle a type of request. If you train on facts the model did not already know, it can learn to state facts confidently in that style without recalling them correctly. Use RAG for missing knowledge.
Problems fine-tuning fits
Fine-tuning is a good candidate when a behavior gap persists after you have tried a well-built prompt with few-shot examples:
- Consistent style or voice. The model should always write in your house style, and prompts keep drifting from it.
- Strict output format. You need valid JSON in a fixed schema, or labels from a closed set, and the failure rate with prompting is too high.
- Narrow task specialization. A smaller, cheaper model must match a larger model on one task. You train the small model on the large model's good outputs, or on human-labeled data.
- Prompt compression. Your prompt carries thousands of tokens of instructions and examples on every call. Training those behaviors in shortens the prompt, which cuts cost and latency per request.
- Hard-to-describe judgment. You can show the right answer far more easily than you can explain the rule.
It is a poor fit for facts that change often, for knowledge that must be cited, and for data that individual users may or may not be allowed to see. Weights cannot enforce access control, and retraining for each update is slow.
| Need | Better lever | Why |
|---|---|---|
| Answer from last week's policy document | RAG | Facts are fetched at query time and can be updated by editing the index |
| Cite the source of a claim | RAG | Retrieved passages can be shown to the user |
| Always reply in a fixed JSON schema | Fine-tuning (after prompting fails) | Format is a behavior |
| Match a brand voice across thousands of outputs | Fine-tuning | Style is hard to hold with instructions alone |
| Per-user permissions on data | RAG with filters | Weights cannot enforce access control |
The training data format
Chat models are usually fine-tuned on JSONL files. Each line is one JSON object with a messages list. The final message is the assistant reply you want the model to learn.
{"messages": [{"role": "system", "content": "You write release notes in our house style."}, {"role": "user", "content": "Fixed crash when exporting empty reports."}, {"role": "assistant", "content": "Fix: exporting an empty report no longer crashes the app."}]}Providers differ in the exact schema and in limits on file size and example count, so check your provider's documentation before you build the file. The structure above is the common core.
The system message in training should match the one you will use in production. The model learns the pairing of context and response. If the two differ, behavior in production can differ from what you tested.
The fine-tuning loop
Fine-tuning is an experiment you repeat. You do not run it once and ship the result.
The baseline matters because it tells you whether fine-tuning bought you anything. A fine-tuned model that scores 88% on your evaluation set sounds good until you find that a better prompt on the base model scores 90%.
Preparing and checking data
Data quality decides the outcome. A model trained on inconsistent examples learns the inconsistency. Common data problems are:
- Conflicting labels. The same input appears with two different outputs.
- Noisy outputs. Examples contain typos, truncated text, or old formats that you do not want repeated.
- Narrow coverage. Every example looks alike, so the model fails on inputs outside that range.
- Leakage. Evaluation inputs also appear in the training file, which inflates your score.
Quality beats quantity. A few hundred clean, varied examples often move behavior more than thousands of messy ones. Start small, inspect the results, and add data where the failures cluster.
The script below checks the structure of each record, drops duplicate inputs, and splits the data so that the evaluation examples never reach training. It runs as written.
import json
import random
def validate(record, line_number):
messages = record.get("messages")
if not isinstance(messages, list) or len(messages) < 2:
raise ValueError(f"line {line_number}: needs a messages list with at least 2 items")
if messages[-1]["role"] != "assistant":
raise ValueError(f"line {line_number}: last message must be from the assistant")
if not messages[-1]["content"].strip():
raise ValueError(f"line {line_number}: assistant reply is empty")
def load_jsonl(lines):
records = []
for number, line in enumerate(lines, start=1):
if not line.strip():
continue
record = json.loads(line)
validate(record, number)
records.append(record)
return records
def dedupe_by_input(records):
seen = set()
unique = []
for record in records:
key = json.dumps(record["messages"][:-1], sort_keys=True)
if key not in seen:
seen.add(key)
unique.append(record)
return unique
def split(records, eval_fraction=0.2, seed=7):
shuffled = records[:]
random.Random(seed).shuffle(shuffled)
cut = max(1, int(len(shuffled) * eval_fraction))
return shuffled[cut:], shuffled[:cut] # train, eval
raw = [
json.dumps({"messages": [
{"role": "user", "content": f"Fixed bug {i}."},
{"role": "assistant", "content": f"Fix: bug {i} no longer occurs."},
]})
for i in range(10)
]
raw.append(raw[0]) # a duplicate input
records = dedupe_by_input(load_jsonl(raw))
train, held_out = split(records)
print(len(records), len(train), len(held_out))It prints 10 8 2. The duplicate is removed, then eight examples go to training and two are held out for evaluation.
Reading the results
Score the tuned model on the held-out set with the same metric you used for the baseline. Then read the failures yourself. Each one points to a cause:
- Wrong content in the right style. The model lacks knowledge. Add RAG. More training will not help.
- Right content in the wrong format. The training data is too small or too inconsistent in format.
- Good on training-like inputs, bad on others. The data lacks coverage, or the model overfit.
- Worse than the base model on general tasks. The model has partly forgotten earlier skills, which is called catastrophic forgetting. Reduce training intensity, mix in varied data, or use a lighter method.
Overfitting means the model memorizes training examples instead of learning the pattern. You see training performance rise while held-out performance stalls or drops. Fewer training passes (epochs), more varied data, and a lower learning rate are the usual remedies.
Full versus parameter-efficient tuning
Full fine-tuning updates every weight. It needs a lot of GPU memory and produces a complete new copy of the model. Parameter-efficient methods such as LoRA freeze the original weights and train a small set of added weights. The result is a small adapter file that sits on top of the base model. This lowers training cost and lets you keep several adapters for several tasks. A later chapter covers LoRA. For now, treat it as the default choice for open-weight models when your hardware is limited. Hosted APIs usually hide this choice and handle it for you.
Costs and ongoing obligations
Fine-tuning has costs beyond the training run:
- Upfront effort. Building and cleaning data usually costs more than the compute.
- Inference price and hosting. Hosted tuned models can carry a different per-token price than the base model. Self-hosted ones need serving infrastructure.
- Staleness. The model's knowledge stays at its training cutoff. Updating facts means retraining or adding RAG.
- Base model upgrades. When the provider retires or replaces the base model, your tuned version may need to be retrained on the new one. Keep your data and evaluation set, because they are the assets that carry over.
- Regression risk. Every retrain can change behavior you did not intend. Rerun the full evaluation each time.
On the benefit side, a tuned model can run with a short prompt, which lowers token cost and latency per call. If your volume is high, that saving can repay the upfront cost.
When to say no
Hold off on fine-tuning when you have no evaluation set, when the prompt baseline already passes, when the failures are about missing facts, or when you cannot get at least a few hundred good examples. In those cases, the cheaper levers come first.
Exercise
Your support bot answers correctly but ignores your required reply format about one time in five, even with a clear system prompt and three few-shot examples. You have 400 reviewed ideal replies and a held-out evaluation set. Which lever do you try next, and how do you decide whether it worked?
Show answer
Try fine-tuning, because the failure is a behavior gap (format), not a knowledge gap, and prompting with few-shot examples has already been tried. Train on the 400 reviewed replies, keeping the evaluation inputs out of the training file. Then score the tuned model on the held-out set with the same format-compliance metric used for the prompt baseline. It worked if compliance rises clearly above the baseline without hurting answer correctness. Also check that general behavior has not regressed.
Exercise
After fine-tuning on release notes, the model writes in the right style but invents version numbers that are not in the input. Is more fine-tuning the right fix?
Show answer
No. Inventing facts is a knowledge or grounding problem, and fine-tuning teaches style, not reliable recall. Supply the version numbers in the prompt or through retrieval, and instruct the model to use only the given context. Add evaluation cases that check the numbers against the source.