Prepare Your Fine-Tuning Dataset
Your dataset decides what your model learns. A few hundred clean, consistent examples beat thousands of messy ones. In this lesson you will build a small dataset in the standard chat format, check its quality, and split it into training and test sets the right way.
All code here is for Google Colab or your own Python setup. Our browser playground cannot run it, because it needs the Hugging Face libraries.
What You'll Learn
- The chat ("messages") format that modern training tools expect
- What a chat template is and why it must match your model
- How to write good examples, and how many you need
- How to split data into train and test sets without leakage
- How to load your data with the Hugging Face
datasetslibrary
The Example Project
We will teach a small model to turn a messy customer message into a short support ticket in JSON. Here is one input and the output we want:
Input: hi my order 4471 still not here after 2 weeks?? i paid for express. not happy
Output: {"category": "shipping", "urgency": "high", "order_id": "4471", "summary": "Express order not delivered after 2 weeks"}
A good prompt can often do this with a large model. We fine-tune a small one so it runs cheaply on our own machine and always returns the same JSON shape.
The Chat Format
Most training tools today expect each example as a list of messages. Each message has a role (system, user or assistant) and content. This is the same shape chat apps use.
One example, as a Python dictionary:
example = {
"messages": [
{"role": "system", "content": "Turn the customer message into a JSON support ticket."},
{"role": "user", "content": "hi my order 4471 still not here after 2 weeks?? i paid for express. not happy"},
{"role": "assistant", "content": '{"category": "shipping", "urgency": "high", "order_id": "4471", "summary": "Express order not delivered after 2 weeks"}'}
]
}
Store many of these in a JSONL file. JSONL means one JSON object per line:
{"messages": [{"role": "system", "content": "..."}, {"role": "user", "content": "..."}, {"role": "assistant", "content": "..."}]}
{"messages": [{"role": "system", "content": "..."}, {"role": "user", "content": "..."}, {"role": "assistant", "content": "..."}]}
Keep the system message the same in every example. Later you will use that same system message when you call the model.
Chat Templates
A model does not read a Python list. It reads one long string with special marker tokens that show where each message starts and ends. Every model family uses its own markers. The rules for turning messages into that string are called the chat template, and they ship with the model's tokenizer.
You can see the string for yourself:
from transformers import AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3-1.7B")
text = tokenizer.apply_chat_template(example["messages"], tokenize=False)
print(text)
The golden rule: train and run with the same chat template as your base model. If you train with one template and chat with another, the model sees markers it never learned and quality drops. The training tools in lesson 4 apply the right template for you when your data is in the messages format.
Quality Over Size
How many examples do you need? It depends on the task, but here is a rough guide:
| Task | Rough starting size |
|---|---|
| Fixed output format, simple labels | 200 to 500 examples |
| Tone or style of writing | 500 to 1,000 examples |
| Harder, varied task | 1,000 to 5,000 examples |
Quality matters more than these numbers. Check every example against this list:
- Correct. Every output is exactly what you want the model to say. The model will copy mistakes too.
- Consistent. Same field names, same order, same style in every output. If half your tickets say
"urgency": "High"and half say"high", the model will mix them. - Varied inputs. Short and long messages, typos, polite and angry, different topics. Real users are messy.
- Covers the edge cases. Include messages with no order number, two problems at once, or a language you support.
- No private data. Remove names, emails, phone numbers and card numbers. A model can repeat what it saw in training.
Where Examples Come From
- Your own past data, such as real tickets that a person already labeled well. Clean and anonymize it first.
- Writing them by hand. Slow, but the quality is high. Even 50 hand-written examples are a great test set.
- Generating them with a large model, then checking each one yourself. This is common and fast. Check the large model's terms of use first, since some providers limit using outputs to train other models.
Train and Test Split
Before training, set aside some examples the model will never see during training. This is the test set (also called the held-out set). In lesson 5 you will use it to check if training helped.
A common split is 90% train and 10% test. With 500 examples, that is 450 to train and 50 to test.
from datasets import load_dataset
dataset = load_dataset("json", data_files="tickets.jsonl", split="train")
split = dataset.train_test_split(test_size=0.1, seed=42)
train_data = split["train"]
test_data = split["test"]
print(len(train_data), len(test_data))
train_test_split shuffles before it splits. Setting a seed makes the shuffle repeatable, so you get the same split every time you run the notebook.
Avoid Data Leakage
Leakage means the test set contains examples the model already saw in training, or near copies of them. Your test score then looks great, but the model fails on real users.
Common causes and fixes:
- Exact duplicates. Remove them before you split.
- Near duplicates. The same message with one word changed. If you made variations of one message, keep all of them on the same side of the split.
- Same customer or same thread. Messages from one conversation are much alike. Split by conversation, not by message.
A quick way to drop exact duplicates. Run it right after load_dataset, before the split above:
from datasets import Dataset
seen = set()
unique_rows = []
for row in dataset:
key = row["messages"][1]["content"].strip().lower()
if key not in seen:
seen.add(key)
unique_rows.append(row)
print(len(dataset), "rows,", len(unique_rows), "unique")
dataset = Dataset.from_list(unique_rows)
split = dataset.train_test_split(test_size=0.1, seed=42)
Check Your Lengths
Long examples use more GPU memory. Count tokens so you know what maximum length to set in training:
lengths = [
len(tokenizer.apply_chat_template(row["messages"], tokenize=True, return_dict=False))
for row in train_data
]
print("longest:", max(lengths), "average:", sum(lengths) // len(lengths))
If a few examples are much longer than the rest, consider shortening or removing them.
Key Takeaways
- Store examples as JSONL in the chat format: a list of messages with
system,userandassistantroles. - A chat template turns messages into the exact string a model expects. Train and run with your base model's own template.
- A few hundred correct, consistent, varied examples often beat thousands of messy ones.
- Hold out about 10% as a test set the model never trains on.
- Prevent leakage by removing duplicates and keeping near copies on the same side of the split.
Quiz
Up next · Lesson 4 of 6
Train a Small Model in Free Google Colab
7 min read
3 of 6 lessons done

Ask Byte about this lesson
A private chat about this lesson. Byte has read the whole lesson, answers in seconds, and shows the section each answer comes from. Ask follow-ups in any language.
Questions & Answers
Public questions about this lesson. The AI Tutor answers right away in your language, the FreeAcademy team checks answers, and every learner can read them.

