14 · Building a training dataset
Run it in Colab View the .ipynb
You are reading this notebook. To run it, open it in Colab with the button above - no install, no GPU needed for most of them - or clone the repository and open it in Jupyter.
- 14.1 · The format
- 14.2 · Loss masking: the thing nobody mentions
- 14.3 · Build a real dataset
- 14.4 · Validate before you train
- 14.5 · Deduplication
- 14.6 · Splitting without leaking
- 14.7 · Look at the shape of your data
- 14.8 · Write it out
- 14.9 · How much data do you need?
- Checkpoint
Training track · ~75 minutes · no GPU needed
Notebook 11 fine-tuned on twelve examples written by hand. That is enough to show the mechanics and nowhere near enough to do anything useful.
This notebook is about the part that actually determines whether a fine-tune works: the data. It is unglamorous, it is most of the job, and it is where almost every failed fine-tune goes wrong.
By the end you will be able to:
- structure data in the format trainers expect, and explain loss masking;
- split train and evaluation sets without leaking between them;
- deduplicate, including near-duplicates, and say why it matters;
- validate a dataset and catch the silent format bugs;
- decide how much data you actually need.
No GPU, no model, no training run. Everything here is text processing — which tells you something about where the real work is.
# --- Setup: works on your laptop AND in Google Colab ------------------------
import os
import subprocess
import sys
from pathlib import Path
if "google.colab" in sys.modules:
if not Path("/content/ROBT407LLM").exists():
subprocess.run(["git", "clone", "--depth", "1",
"https://github.com/berdakh/ROBT407LLM.git",
"/content/ROBT407LLM"], check=True)
os.chdir("/content/ROBT407LLM")
subprocess.run([sys.executable, "-m", "pip", "install", "-q",
"-r", "requirements.txt"], check=True)
REPO_ROOT = next(p for p in [Path.cwd(), *Path.cwd().parents]
if (p / "src" / "qwen_workshop").is_dir())
sys.path.insert(0, str(REPO_ROOT / "src"))
print("repo root:", REPO_ROOT)
import hashlib
import json
import random
import re
from collections import Counter
random.seed(613)
14.1 · The format
Every supervised fine-tuning trainer expects the same shape: a list of
examples, each a conversation. One JSON object per line (.jsonl), because
you can stream it without loading the whole file.
{"messages": [
{"role": "system", "content": "..."},
{"role": "user", "content": "..."},
{"role": "assistant", "content": "..."}
]}
Training data must look exactly like production input. If your app sends a system prompt, your training data has one. If it does not, it does not. A mismatch here is the single most common reason a fine-tune “works in training and fails in the app”.
SYSTEM = ("You are a teaching assistant for a workshop on open-weight language "
"models. Answer in at most three sentences. If the answer is not in "
"the course material, say so.")
def example(user: str, assistant: str, system: str = SYSTEM) -> dict:
return {"messages": [
{"role": "system", "content": system},
{"role": "user", "content": user},
{"role": "assistant", "content": assistant},
]}
demo = example("What is a token?",
"A token is the unit a model reads and writes - roughly four "
"characters of English. Not a word and not a letter, which is "
"why counting letters is hard for a model.")
print(json.dumps(demo, indent=2)[:400], "...")
In plain terms. Loss masking is marking only the answers on an exam script, not the questions. The question is there for context; it is not something you want the student to learn to write. Grade the questions too and you train a model that is excellent at inventing plausible user queries — a skill nobody asked for.
14.2 · Loss masking: the thing nobody mentions
Here is a question with a non-obvious answer. When you train on that example, which tokens does the model get a loss signal on?
- The whole sequence, including the system prompt and the user’s question?
- Only the assistant’s reply?
Both are used, and they teach different things:
| Trains on | Teaches | Use when | |
|---|---|---|---|
| Completion-only | assistant tokens | how to respond | almost always |
| Full sequence | everything | the whole distribution, including how users write | the prompts are themselves in-domain and scarce |
trl’s SFTTrainer can do either. Getting this wrong rarely crashes — it
just makes training mysteriously less effective, because a chunk of your
gradient is spent teaching the model to generate questions.
def show_masking(messages: list[dict]) -> None:
"""Which parts of the sequence carry loss, under each scheme."""
for message in messages:
role, content = message["role"], message["content"]
trained_completion_only = role == "assistant"
mark = "LOSS " if trained_completion_only else " - "
print(f"{mark}{role:<10}{content[:58]}...")
print("\n'LOSS' marks what completion-only training learns from.")
print("Full-sequence training would mark every line.")
show_masking(demo["messages"])
14.3 · Build a real dataset
We will generate a Q&A dataset from the workshop’s own documentation — which is a realistic situation: you have a corpus of knowledge and want a model that answers questions about it.
In practice you would generate candidate pairs with a larger model and then review them by hand. That is distillation (handbook chapter 3), and it is how most instruction datasets are actually made. Here we write them directly so the notebook runs without a model.
RAW_EXAMPLES = [
("What does a language model output at each step?",
"A probability distribution over every token in the vocabulary. Not a "
"word - a full distribution, which is then sampled from."),
("Why does the same prompt give different answers?",
"Because the next token is sampled from a distribution rather than chosen. "
"Set do_sample=False and the answers become identical."),
("What is the difference between open weights and open source?",
"Open weights means you get the trained parameters but not the training "
"data or recipe. Open source, as software people mean it, would include "
"both."),
("Why is counting letters hard for a model?",
"The model sees tokens, not characters. 'strawberry' is about three "
"opaque chunks, so the letters are not visible to it. Give it a tool."),
("What does temperature do?",
"It rescales the logits before softmax. Low values sharpen the "
"distribution, high values flatten it. It changes how boldly the model "
"samples, not what it knows."),
("Why is top-p usually better than top-k?",
"Top-p adapts to the model's confidence: it keeps one token when the "
"model is sure and many when it is not. Top-k keeps a fixed number "
"regardless."),
("What does quantization store for each group of weights?",
"A scale at higher precision, plus each weight as a small integer. The "
"value is reconstructed as scale times integer."),
("Should I use a bigger model at Q4 or a smaller one at Q8?",
"The bigger model at Q4, at the same file size. Capacity buys more than "
"precision in that range."),
("Why must I slice the output of generate()?",
"Because generate() returns the prompt and the completion concatenated. "
"Without the slice your application echoes the user's own question back."),
("What are the four stages of RAG?",
"Chunk the documents, embed and index them, retrieve the nearest chunks "
"to the question, then generate an answer from only those chunks."),
("Why measure retrieval separately from answer quality?",
"They fail for different reasons and have different fixes. If retrieval "
"failed, no amount of prompt engineering helps - the model never received "
"the text."),
("What does recall@k measure?",
"The fraction of questions where a relevant chunk appears in the top k "
"results. It is the number to fix before touching the prompt."),
("In tool calling, which step executes the function?",
"Your code does. The model only ever emits a request; every security "
"property lives in your decision whether to honour it."),
("Why is a good docstring a good prompt?",
"Because the docstring becomes the tool description the model reads when "
"choosing. A vague docstring produces vague tool selection."),
("What is the difference between a chain and an agent?",
"In a chain you decide the steps; in an agent the model decides how many "
"and which. You trade predictability for flexibility."),
("Name a defence against prompt injection that does not rely on the model.",
"Least privilege: an agent with no tool that can send data has nothing to "
"exfiltrate with. Confirmation gates and trust separation also qualify."),
("What does LoRA learn?",
"Two thin matrices whose product is added to the frozen original weights. "
"At rank 16 that is well under one percent of the parameters."),
("When should I fine-tune instead of using RAG?",
"When you need behaviour rather than knowledge: a consistent tone or "
"format that prompting cannot hold. Never for facts."),
("What does finish_reason equal to 'length' mean?",
"Generation was cut off by max_tokens rather than finishing. Your output "
"may be truncated while still looking complete."),
("Why does a chatbot's prompt grow every turn?",
"The model has no memory between calls. The whole transcript is re-sent "
"each turn, which is what 'memory' actually means."),
]
dataset = [example(q, a) for q, a in RAW_EXAMPLES]
print(f"{len(dataset)} examples")
14.4 · Validate before you train
Run these checks every time. Each one catches a bug that otherwise costs you a training run and leaves no obvious trace.
def validate(rows: list[dict], max_chars: int = 4000) -> dict:
"""Structural checks on a dataset. Returns problems grouped by kind."""
problems: dict[str, list] = {}
def flag(kind: str, index: int, detail: str = "") -> None:
problems.setdefault(kind, []).append(f"row {index}{': ' + detail if detail else ''}")
for i, row in enumerate(rows):
messages = row.get("messages")
if not messages:
flag("no messages", i)
continue
roles = [m.get("role") for m in messages]
# The conversation must end on the assistant - that is the only thing
# the model is asked to produce. A trailing user turn trains nothing.
if roles[-1] != "assistant":
flag("does not end with assistant", i, f"ends with {roles[-1]}")
# Roles must alternate after any system message.
body = [r for r in roles if r != "system"]
if any(a == b for a, b in zip(body, body[1:])):
flag("consecutive same role", i, "->".join(roles))
for m in messages:
content = m.get("content")
if not isinstance(content, str) or not content.strip():
flag("empty content", i, m.get("role", "?"))
elif len(content) > max_chars:
flag("very long", i, f"{m['role']} is {len(content)} chars")
# A system prompt on some rows and not others teaches the model that
# the system prompt is optional, which is rarely what you want.
if roles.count("system") > 1:
flag("multiple system messages", i)
return problems
# Plant three deliberate bugs so the checks have something to find.
broken = list(dataset)
broken.append({"messages": [{"role": "user", "content": "unanswered question"}]})
broken.append({"messages": [{"role": "system", "content": SYSTEM},
{"role": "user", "content": "hi"},
{"role": "assistant", "content": " "}]})
broken.append({"messages": [{"role": "system", "content": SYSTEM},
{"role": "user", "content": "a"},
{"role": "user", "content": "b"},
{"role": "assistant", "content": "ok"}]})
found = validate(broken)
print("problems found:\n")
for kind, rows in found.items():
print(f" {kind:<32}{len(rows)} ({rows[0]})")
print("\nclean dataset:", validate(dataset) or "no problems")
14.5 · Deduplication
Duplicates get memorised rather than learned. They also inflate your apparent dataset size and, if the same item lands in both splits, make your evaluation meaningless.
Exact duplicates are easy. Near-duplicates are the ones that hurt.
def exact_key(row: dict) -> str:
"""Hash of the full conversation - catches identical rows."""
text = json.dumps(row["messages"], sort_keys=True)
return hashlib.sha256(text.encode()).hexdigest()
def normalised_question(row: dict) -> str:
"""The user turn, stripped to its content words.
Catches 'What is a token?' vs 'what is a token' vs 'What is a token!!' -
which an exact hash does not.
"""
user = next(m["content"] for m in row["messages"] if m["role"] == "user")
words = re.findall(r"[a-z0-9]+", user.lower())
stop = {"what", "is", "a", "an", "the", "does", "do", "how", "why", "in", "of", "to"}
return " ".join(sorted(w for w in words if w not in stop))
def deduplicate(rows: list[dict]) -> tuple[list[dict], dict]:
seen_exact, seen_near = set(), set()
kept, dropped = [], Counter()
for row in rows:
key = exact_key(row)
if key in seen_exact:
dropped["exact"] += 1
continue
near = normalised_question(row)
if near in seen_near:
dropped["near"] += 1
continue
seen_exact.add(key)
seen_near.add(near)
kept.append(row)
return kept, dict(dropped)
# Add duplicates of both kinds.
with_dupes = list(dataset)
with_dupes.append(dataset[0]) # exact
with_dupes.append(example("what is a token", RAW_EXAMPLES[0][1])) # near
with_dupes.append(example("What IS a token?!", "A different answer entirely.")) # near
clean, stats = deduplicate(with_dupes)
print(f"in : {len(with_dupes)}")
print(f"out : {len(clean)}")
print(f"dropped: {stats}")
The third duplicate had a different answer. Contradictory examples are worse than redundant ones: the model learns that the same question has two answers, and produces an average of them. Near-duplicate detection catches this; exact hashing does not.
14.6 · Splitting without leaking
You need a held-out set to tell learning from memorisation. The naive approach — shuffle and slice — leaks whenever near-duplicates exist, because a question can land in train and its paraphrase in evaluation.
Deduplicate first, then split. And if your data has groups (several questions about one document, several turns from one conversation), split by group, not by row.
def split_dataset(rows: list[dict], eval_fraction: float = 0.2, seed: int = 613):
"""Deduplicate, then split. Order matters: the reverse leaks."""
rows, _ = deduplicate(rows)
shuffled = rows[:]
random.Random(seed).shuffle(shuffled)
n_eval = max(1, int(len(shuffled) * eval_fraction))
return shuffled[n_eval:], shuffled[:n_eval]
train_rows, eval_rows = split_dataset(dataset)
print(f"train: {len(train_rows)} eval: {len(eval_rows)}")
# Prove there is no overlap, by content rather than by object identity.
overlap = {exact_key(r) for r in train_rows} & {exact_key(r) for r in eval_rows}
print(f"overlapping rows: {len(overlap)} (must be 0)")
near_overlap = {normalised_question(r) for r in train_rows} & \
{normalised_question(r) for r in eval_rows}
print(f"overlapping questions after normalisation: {len(near_overlap)} (must be 0)")
14.7 · Look at the shape of your data
Before training, look at the distribution. Skew here shows up as skew in the model’s behaviour.
def describe(rows: list[dict]) -> None:
answers = [m["content"] for r in rows for m in r["messages"] if m["role"] == "assistant"]
questions = [m["content"] for r in rows for m in r["messages"] if m["role"] == "user"]
lengths = sorted(len(a.split()) for a in answers)
print(f"examples : {len(rows)}")
print(f"answer words : min {lengths[0]}, median {lengths[len(lengths) // 2]}, "
f"max {lengths[-1]}")
print(f"question starts : {Counter(q.split()[0] for q in questions).most_common(5)}")
# A rough token estimate at ~4 characters per token (notebook 01).
chars = sum(len(m["content"]) for r in rows for m in r["messages"])
print(f"approx tokens : {chars // 4:,}")
describe(train_rows)
What to look for:
- Length skew. If every answer is 30 words, the model will produce 30-word answers forever, including when one word would do.
- Question monoculture. Twenty questions all starting “What is” teaches a narrow trigger. Vary the phrasing.
- Hidden formatting. Markdown in some answers and not others teaches the model that formatting is random.
Exercise 1. Add ten examples whose answers are deliberately much longer than the rest. Re-run
describe. Then predict what the fine-tuned model’s answer length distribution would look like, and why that is a problem.
14.8 · Write it out
OUT_DIR = REPO_ROOT / "data" / "sft"
OUT_DIR.mkdir(parents=True, exist_ok=True)
def write_jsonl(rows: list[dict], path: Path) -> None:
with path.open("w", encoding="utf-8") as handle:
for row in rows:
handle.write(json.dumps(row, ensure_ascii=False) + "\n")
print(f"wrote {len(rows):>3} rows to {path.relative_to(REPO_ROOT)}")
write_jsonl(train_rows, OUT_DIR / "train.jsonl")
write_jsonl(eval_rows, OUT_DIR / "eval.jsonl")
# Read one back to confirm the round trip.
first = json.loads((OUT_DIR / "train.jsonl").read_text(encoding="utf-8").splitlines()[0])
print(f"\nround trip ok: {first['messages'][1]['content'][:60]}...")
14.9 · How much data do you need?
| Examples | What it buys |
|---|---|
| 10–50 | Format and tone transfer. Often genuinely enough. |
| 100–1,000 | Reliable behaviour on a narrow task |
| 1,000–10,000 | A genuinely specialised model |
| 10,000+ | Diminishing returns without careful curation |
Quality beats quantity, decisively. Fifty consistent, carefully written examples beat a thousand scraped ones, because every inconsistency in your data is an instruction to the model to be inconsistent.
The practical test: if you cannot explain why each example is in the set, it probably should not be.
Exercise 2. Take the twenty examples here and deliberately make five of them inconsistent — different answer length, different tone, markdown where the others have none. You now have a 25% corruption rate. Predict what the fine-tuned model does, then test the prediction by feeding the corrupted file to notebook 11’s LoRA run.
Checkpoint
- What shape does a fine-tuning example take, and why
.jsonl? - What is loss masking, and which scheme is the usual default?
- Why are near-duplicates worse than exact duplicates?
- Why must you deduplicate before splitting?
- Name three distributional problems you would look for before training.
- Fifty careful examples or a thousand scraped ones — which, and why?
➡️ Next: 15_preference_tuning_dpo.ipynb —
teaching the model which of two good answers people prefer.