Preparing Fine-Tuning Data

Updated · 12 min read
hardPython 3.13aillmfine-tuningdatasetsjsonldata-quality

Fine-tuning data is a set of examples of exactly what you want the model to do: an input, usually a chat conversation, and the ideal reply. The model learns to imitate these replies, including their mistakes, so the quality and consistency of the examples matter more than anything else in fine-tuning. A few hundred clean, consistent examples often beat thousands of messy ones.

This lesson builds the dataset for the chapter checkpoint: teaching Campus Helper to answer parents' questions from school documents, in a fixed style.

What Good Fine-Tuning Data Looks Like

PropertyDescription
FormatIt is used to match what the model will see in use: chat messages with roles, stored one example per line (JSONL)
ConsistencyEvery reply follows the same style and rules, so the model learns one clear pattern
CoverageExamples cover the real range of inputs, including hard and unanswerable ones
CorrectnessEvery reply is right; the model will copy errors as faithfully as good answers
A held-out test setExamples kept out of training, to measure the result honestly
No leakageNo test example, or a near copy, appears in the training data

The Campus Helper Style

The goal is to teach behavior, not facts. The facts come from documents in the prompt, as in RAG; the model must learn to:

  1. Find the one document sentence that answers the question among three.
  2. Repeat it and cite it, as (Source: FAQ #number).
  3. Decline in a fixed way when no document answers: "I couldn't find that in the school's documents. Please contact the school office."

Example: Building the Dataset

This program uses faq.json, the 50 school answers from "Semantic Search". It pairs each one with a real parent question, adds 12 questions the documents can't answer, and writes train.jsonl and test.jsonl.

Consistent examples, an honest split, and checks before training
Python
import json
import random
 
faq = {item["id"]: item["text"] for item in json.load(open("faq.json"))}   # from "Semantic Search"
 
# One real parent question for each FAQ entry (entry number: question)
QUESTIONS = {
    1: "How much is the science lab fee?", 2: "What does a field trip cost?", 3: "Is there a library fee?",
    4: "How much is tuition each month?", 5: "Can I pay fees online?", 6: "Can I pay in cash?",
    7: "What happens if I pay late?", 8: "We can't afford the fees. Is there help?", 9: "Is there a discount for siblings?",
    10: "Will I get a receipt?", 11: "How do refunds work if a trip is cancelled?", 12: "How much is the sports program?",
    13: "What does graduation cost?", 14: "When are admission forms due?", 15: "What documents do I need to apply?",
    16: "How long is the admission interview?", 17: "When will we hear about admission?", 18: "We're moving from Texas. Can my son start mid-year?",
    19: "Is there an entrance test for grade 9?", 20: "Does grade 11 have a placement test?", 21: "What proof of address do you need?",
    22: "When are vaccination records due?", 23: "Can we visit the campus?", 24: "How does the waiting list work?",
    25: "What does an international student need?", 26: "When does spring term start?", 27: "When does fall term begin?",
    28: "What are the school hours?", 29: "Why do students leave early on Wednesdays?", 30: "When are final exams?",
    31: "When are midterms?", 32: "How long is winter break?", 33: "When is spring break?",
    34: "When are parent-teacher conferences?", 35: "Is school open the day after Thanksgiving?", 36: "Where can I see my child's class schedule?",
    37: "What time is lunch?", 38: "What time does the bus come?", 39: "My daughter lost her jacket. Where should I look?",
    40: "Does my child need an ID badge?", 41: "Can students use phones in class?", 42: "Are there vegetarian meals?",
    43: "How do I report an absence?", 44: "Is there free tutoring?", 45: "Where is the counselor?",
    46: "Where can my son park his bike?", 47: "I forgot my parent portal password.", 48: "What clubs are there?",
    49: "When is the nurse available?", 50: "Do visitors need to sign in?",
}
# Questions the FAQ can't answer: Campus Helper must decline
UNANSWERABLE = [
    "Can you waive our late fee this month?", "What grade did my son get in math?", "Who is the principal's favorite student?",
    "Can you give me another family's phone number?", "Is the cafeteria pizza good?", "Will it snow next week?",
    "How much do teachers get paid?", "Can my daughter skip the final exam?", "What is the Wi-Fi password?",
    "Can you write my son's history essay?", "Which college should my daughter apply to?", "Is the math teacher strict?",
]
DECLINE = "I couldn't find that in the school's documents. Please contact the school office."
 
def example(question, context_ids, answer):
    context = "\n".join(f"[FAQ #{i}] {faq[i]}" for i in context_ids)
    return {"messages": [
        {"role": "user", "content": f"Documents:\n{context}\n\nQuestion: {question}"},
        {"role": "assistant", "content": answer},
    ]}
 
rng = random.Random(29)
ids = list(QUESTIONS)
rng.shuffle(ids)
test_ids = set(ids[:15])                              # 15 FAQ entries are never seen in training
data = {"train": [], "test": []}
for i, question in QUESTIONS.items():
    others = rng.sample([j for j in faq if j != i], 2)
    context = rng.sample([i] + others, 3)              # the right entry, in a random place among 3
    split = "test" if i in test_ids else "train"
    data[split].append(example(question, context, f"{faq[i]} (Source: FAQ #{i})"))
for k, question in enumerate(UNANSWERABLE):
    split = "test" if k < 4 else "train"
    data[split].append(example(question, rng.sample(list(faq), 3), DECLINE))
 
for split, rows in data.items():
    rng.shuffle(rows)
    with open(f"{split}.jsonl", "w") as f:
        for row in rows:
            f.write(json.dumps(row) + "\n")
    declines = sum(r["messages"][1]["content"] == DECLINE for r in rows)
    print(f"{split}.jsonl: {len(rows)} examples ({len(rows) - declines} answers, {declines} declines)")
 
print("\nOne training example:")
print(json.dumps(data["train"][0], indent=1))
Output
train.jsonl: 43 examples (35 answers, 8 declines)
test.jsonl: 19 examples (15 answers, 4 declines)
 
One training example:
{
 "messages": [
  {
   "role": "user",
   "content": "Documents:\n[FAQ #23] Families can book a campus tour on Tuesdays and Thursdays.\n[FAQ #13] Graduation costs $40, which covers the cap, gown and ceremony.\n[FAQ #32] Winter break runs from December 21 to January 4.\n\nQuestion: Can we visit the campus?"
  },
  {
   "role": "assistant",
   "content": "Families can book a campus tour on Tuesdays and Thursdays. (Source: FAQ #23)"
  }
 ]
}

Explanation:

  • Each example is a conversation: a user message with three documents and a question, and the ideal assistant reply. This is the same chat format the model uses, so training matches real use.
  • The right document is placed at random among two others, so the model must find it instead of always copying the first line.
  • The split is by FAQ entry, not by example. 15 of the 50 entries appear only in the test set, so the test checks whether the model learned the behavior on documents it has never seen, rather than memorizing answers.
  • Declines are part of the data: 8 in training and 4 in testing. A model trained only on answers learns to always answer.
  • JSONL stores one JSON object per line, the usual format for fine-tuning files.

Example: Checking the Data Before Training

Mistakes in the data are cheap to find before training and expensive to find after. This program runs six checks.

Python
import json
from collections import Counter
 
from transformers import AutoTokenizer
 
tokenizer = AutoTokenizer.from_pretrained("HuggingFaceTB/SmolLM2-135M-Instruct")
DECLINE = "I couldn't find that in the school's documents. Please contact the school office."
data = {split: [json.loads(line) for line in open(f"{split}.jsonl")] for split in ["train", "test"]}
 
def question(row):
    return row["messages"][0]["content"].split("Question: ")[1]
 
for split, rows in data.items():
    # 1. Every example has the right shape: one user message, one assistant reply
    assert all([m["role"] for m in r["messages"]] == ["user", "assistant"] for r in rows)
    # 2. Length in tokens, with the chat template, as the model will see it
    lengths = [len(tokenizer.apply_chat_template(r["messages"], return_dict=True)["input_ids"]) for r in rows]
    # 3. Balance between answers and declines
    kinds = Counter("decline" if r["messages"][1]["content"] == DECLINE else "answer" for r in rows)
    print(f"{split}: {len(rows)} examples, {dict(kinds)}, tokens {min(lengths)} to {max(lengths)}"
          f" (average {sum(lengths) / len(lengths):.0f})")
 
# 4. Duplicates inside the training data
dupes = [q for q, n in Counter(question(r) for r in data["train"]).items() if n > 1]
print("Duplicate training questions:", dupes or "none")
 
# 5. Leakage: a test question or answer that also appears in training
train_questions = {question(r) for r in data["train"]}
train_answers = {r["messages"][1]["content"] for r in data["train"]} - {DECLINE}
leaks = [question(r) for r in data["test"]
         if question(r) in train_questions or r["messages"][1]["content"] in train_answers]
print("Test examples leaked into training:", leaks or "none")
 
# 6. Every answer must come from its own documents, word for word
bad = [question(r) for rows in data.values() for r in rows
       if r["messages"][1]["content"] != DECLINE
       and r["messages"][1]["content"].split(" (Source")[0] not in r["messages"][0]["content"]]
print("Answers not found in their documents:", bad or "none")
Output
train: 43 examples, {'answer': 35, 'decline': 8}, tokens 128 to 165 (average 139)
test: 19 examples, {'answer': 15, 'decline': 4}, tokens 125 to 162 (average 139)
Duplicate training questions: none
Test examples leaked into training: none
Answers not found in their documents: none

Explanation:

CheckResultWhy it matters
ShapeEvery example is user then assistantA broken example can silently teach the wrong pattern
Length128 to 165 tokens, average 139Long outliers slow training; very short ones may be broken
Balance35 answers and 8 declines in trainingToo few of one kind and the model rarely produces it
DuplicatesNoneRepeated examples get extra weight
LeakageNoneA leaked test example makes the score look better than it is
GroundingEvery answer is word for word in its documentsThe model must never learn to answer from outside the documents

The balance check is worth a second look: only 8 decline examples in training. The checkpoint shows what that costs.

Where Fine-Tuning Data Comes From

SourceNotes
Real conversations, cleanedThe most realistic; remove personal data and fix bad replies first
Written by expertsHigh quality but slow; good for the hardest cases
Generated by a larger modelFast and common (synthetic data); review a sample by hand and filter
Existing documents turned into Q and AAs in this lesson: questions written for known answers

Common Mistakes

Splitting by example instead of by source. Near-copies end up on both sides and the test score is too high.

Forgetting the "no answer" cases. The model will answer everything, as confidently as possible.

Inconsistent replies. Different people writing in different styles gives a model with no clear style.

Training on the test set by accident. Keep the test file separate from the start, and check for overlap.

Interview Corner

How do you prepare a dataset for fine-tuning an LLM?

Collect or write examples in the model's chat format, make the replies consistent and correct, cover hard and unanswerable cases, split off a test set by source to avoid leakage, and check shape, length, balance, duplicates and grounding before training.

How much data do you need to fine-tune?

It depends on the task: a format or style can be learned from tens to hundreds of good examples with LoRA, while a new skill can need thousands. Quality and consistency matter more than quantity, and an evaluation set tells you when you have enough.

Practice

Exercise: more declines. Add 12 more unanswerable questions to UNANSWERABLE, so training has 20 declines. Rerun both programs. How does the balance change? After the checkpoint in the next lesson, does the model decline better?

Check your understanding:

  1. Why is the split done by FAQ entry rather than by example?
  2. What could go wrong if the training data had no decline examples?
  3. What does the grounding check protect against?

Quick check: fine-tuning data

4 questions
1What format does the dataset use?
2How many test FAQ entries never appear in training?
3What does the leakage check look for?
4What did the balance check show?

Key Takeaways

Quick reference

NeedCode
One chat example{"messages": [{"role": "user", ...}, {"role": "assistant", ...}]}
Write JSONLf.write(json.dumps(row) + "\n")
Read JSONL[json.loads(line) for line in open(path)]
Tokens per examplelen(tokenizer.apply_chat_template(messages, return_dict=True)["input_ids"])
Count kindsCounter(...) from collections

Was this tutorial helpful?

Lesson 152 of 186