Sub topic 9
Preparing training data
This chapter assumes you can call a chat-style LLM API and read Python. It also assumes you have already built an evaluation set and a baseline, as covered earlier. Fine-tuning is only as good as the examples it learns from, so this chapter covers where those examples come from, how to format them, and how to catch problems before you pay for a training run.
What training data is for
Fine-tuning changes the model's behavior. It does not reliably teach new facts. Each training example is a demonstration: given this input, produce exactly this output. After enough demonstrations, the model imitates the pattern.
This has a direct consequence. If your examples are inconsistent, the model learns the inconsistency. If they contain errors, it learns the errors. The data is the specification, so most of the work in a fine-tuning project is data work.
A useful rule is to choose a small number of high-quality examples over a large number of mediocre ones. Many tasks show clear gains from a few hundred good examples. Providers publish minimum counts, and these are minimums, not targets. Check your provider's current documentation for the limits.
The chat-format JSONL file
Most hosted fine-tuning services accept JSONL (JSON Lines). Each line is one complete JSON object and one training example. Here is one line, with the same structure used throughout this tutorial:
{"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."}]}The three roles do different jobs:
systemholds the standing instruction. Use the same system message you will use in production.userholds the input the model will see at inference time.assistantholds the exact output you want. The model is trained to reproduce this text.
The match between training and production matters. If you train with one system prompt and deploy with another, you lose part of the benefit. Build the training examples with the same code path that builds production requests.
Where examples come from
There are four common sources. Each has different strengths.
| Source | Strength | Risk |
|---|---|---|
| Existing human work (past tickets, edited documents) | Reflects real inputs and your real standards | May contain old mistakes, mixed styles, or personal data |
| Expert-written examples | Highest consistency and quality | Slow and costly to produce |
| Model-generated, then reviewed | Fast to scale | Can bake in the generating model's habits and errors |
| Production logs with corrections | Matches the live input distribution | Needs a reliable way to mark which outputs were good |
A practical approach combines them. Start with a small set of expert-written examples. Use a strong prompted model to draft more. Have a person review and correct each draft. The reviewed output becomes training data.
Do not train on unreviewed model output and expect the result to beat the model that produced it. The tuned model can at best copy the source model's quality, along with its mistakes.
Quality criteria for each example
Review every example against four questions.
- Is the output correct? A wrong answer in the assistant turn teaches the model to give wrong answers.
- Is the output in exactly the target style and format? If half the examples end with a period and half do not, the model will do both.
- Is the input realistic? Training inputs should look like what users actually send, including typos, short fragments, and unclear requests.
- Does the example teach behavior rather than facts? A fact that changes next month does not belong in the weights. Use RAG for that.
Consistency deserves extra attention. Two annotators who label the same input differently produce conflicting signals. Write a short labeling guide with the rules and borderline cases, and have more than one person label a sample so you can measure agreement.
Coverage and balance
The model learns the distribution you show it. If 90% of your examples are one class, the tuned model will lean toward that class. Check three things:
- Class balance. For classification, count examples per label.
- Input variety. Include short and long inputs, easy and hard ones.
- Edge cases and refusals. If the model should say "I don't know" or decline some requests, include examples that do so. Otherwise it will never learn to.
The following script reads a JSONL file, checks the structure, and reports label counts. It assumes each example has a system message, one user message, and one assistant message.
import json
from collections import Counter
VALID_ROLES = ["system", "user", "assistant"]
def load_examples(path):
examples = []
with open(path, encoding="utf-8") as f:
for line_number, line in enumerate(f, start=1):
line = line.strip()
if not line:
continue
try:
record = json.loads(line)
except json.JSONDecodeError as err:
raise ValueError(f"Line {line_number}: invalid JSON ({err})")
examples.append((line_number, record))
return examples
def check_structure(line_number, record):
problems = []
messages = record.get("messages")
if not isinstance(messages, list) or not messages:
return [f"Line {line_number}: missing or empty 'messages'"]
roles = [m.get("role") for m in messages]
if roles != VALID_ROLES:
problems.append(f"Line {line_number}: roles are {roles}, expected {VALID_ROLES}")
for m in messages:
content = m.get("content")
if not isinstance(content, str) or not content.strip():
problems.append(f"Line {line_number}: empty content for role {m.get('role')}")
return problems
def report(path):
examples = load_examples(path)
all_problems = []
labels = Counter()
for line_number, record in examples:
problems = check_structure(line_number, record)
all_problems.extend(problems)
if not problems:
labels[record["messages"][2]["content"].strip()] += 1
print(f"{len(examples)} examples, {len(all_problems)} problems")
for p in all_problems:
print(p)
for label, count in labels.most_common():
print(f"{label}: {count}")
if __name__ == "__main__":
report("train.jsonl")Run it on every new version of the file. A structural error caught here costs seconds. The same error found after a training job starts can cost a failed run.
Duplicates and leakage
Two problems quietly ruin results.
Duplicates. Repeated examples make the model overweight those patterns. Remove exact duplicates, and look for near duplicates such as the same text with different whitespace.
Leakage. If an example from your evaluation set also appears in the training data, your score is inflated. The model has seen the answer. You will believe the tuned model is better than it is, and you will find out in production.
Keep the evaluation set separate from the start, and check for overlap whenever you rebuild the training file.
import json
def normalize(text):
return " ".join(text.lower().split())
def user_inputs(path):
inputs = set()
with open(path, encoding="utf-8") as f:
for line in f:
if not line.strip():
continue
record = json.loads(line)
for message in record["messages"]:
if message["role"] == "user":
inputs.add(normalize(message["content"]))
return inputs
def find_leakage(train_path, eval_path):
return sorted(user_inputs(train_path) & user_inputs(eval_path))
if __name__ == "__main__":
overlap = find_leakage("train.jsonl", "eval.jsonl")
print(f"{len(overlap)} overlapping inputs")
for text in overlap:
print(text)This catches exact matches after normalization. It will not catch paraphrases of the same input, so also split by source document or customer when examples come from the same origin.
Sensitive data
Training data can be memorized, and the model may repeat it to other users. Before you upload anything:
- Remove or mask personal data such as names, emails, and account numbers.
- Remove secrets such as API keys and passwords.
- Check your provider's data-retention terms and your own compliance rules.
Do this before review, not after. Cleaning is much cheaper while the data is still a text file you control.
Splitting the data
Split your examples into three sets:
- Training set. What the model learns from.
- Validation set. A held-out slice that the training job uses to track loss and spot overfitting.
- Evaluation set. Your task-level test, kept apart and used only to compare the tuned model against your baseline.
Overfitting means the model memorizes the training examples and does worse on new inputs. A training loss that keeps falling while validation loss rises is the usual sign.
Common mistakes
- Training on facts that change. The model will state outdated information with confidence. Move those facts to retrieval.
- Mismatched prompts. The training system message differs from the production one.
- Too narrow data. The model does well on the training cases and fails on anything unfamiliar.
- Unreviewed generated data. Errors from the source model are copied.
- No holdout. Without a clean evaluation set, you cannot tell whether tuning helped.
Summary of the workflow
- Define the target behavior and write a short labeling guide.
- Collect examples from real inputs, and draft more with a prompted model if needed.
- Mask sensitive data.
- Review and correct every output.
- Remove duplicates and check class balance.
- Split into training, validation, and evaluation sets.
- Validate the file structure and check for leakage.
- Train, then compare against the baseline on the evaluation set.
Exercise
Your team builds a fine-tuning file from 2,000 past support tickets and the replies agents wrote. The evaluation set was built from 200 tickets chosen at random from that same pool, and nobody removed them from the training file. The tuned model scores 96% on the evaluation set, well above the baseline. Why can you not trust this number, and what two steps would you take?
Show answer
Those 200 evaluation tickets are also in the training data, so the model has already seen the inputs and the target replies. This is leakage, and it inflates the score. First, remove the evaluation tickets from the training file, and run an overlap check such as the normalized-input comparison to confirm that none remain. Second, retrain and re-score. If tickets can come from the same customer or thread, split by customer or thread so near copies do not cross the boundary. Ideally, also collect a fresh evaluation set, since this one has now been seen.
Exercise
A training file has 900 examples labeled "billing", 80 labeled "bug", and 20 labeled "other". The model is meant to classify tickets in production, where bugs are about 30% of traffic. What problem should you expect, and how would you fix it?
Show answer
The model will lean toward "billing" and under-predict "bug" and "other", because the training distribution does not match production. Fix it by collecting or writing more "bug" and "other" examples so the proportions better reflect production and cover the hard cases for each label. Then measure per-label results on the evaluation set, not just overall accuracy, since overall accuracy can look fine while the minority labels fail.