Building an Instruction Dataset the Model Can Learn From
Turn 528 messy logged support messages into clean train, validation and test files for a JSON extraction task: remove exact and near-duplicate copies, split by phrasing so the test set measures generalisation, render each example with the model chat template, and build the labels by hand with the prompt tokens masked out.
Contentsand lesson path
On this page
- The problem
- Step 1: Look at the raw data
- Step 2: Count the duplicates before you split
- Step 3: Deduplicate, then split by phrasing
- Step 4: Render examples with the chat template
- Step 5: Mask the prompt tokens in the labels
- Check your understanding
- Apply it
- Review prompt
Lessons of LLM Fine-Tuning
- Should You Fine-Tune? A Decision Framework Concept · 20 min
- Building an Instruction Dataset the Model Can Learn From Worked example · 25 min
- LoRA and QLoRA: Training Millions of Parameters Instead of Billions Concept · 20 min
- Lab: Supervised Fine-Tuning with LoRA on a Single GPU Lab · 30 min
- Lab: Base vs Tuned on Held-Out Data Lab · 25 min
- Check: Fine-Tuning Trade-offs Knowledge check · 8 questions
What you will learn
- Prepare an instruction or chat dataset in the model's chat template with deduplication, train/validation splits and loss masking on prompt tokens.
Prerequisites: Transformer Architecture
01. The problem
A shop wants a small model that reads a customer message and replies with four fields as JSON: the order number, the product, the kind of issue (late, damaged, wrong_item or refund) and whether the customer says it is urgent. The team has logged messages together with the fields that an agent filled in by hand. Before any training run, this raw log has to become a dataset the model can learn from, and a test set you can trust.
Fine-tuning learns from whatever you give it, including mistakes. If a message appears in both the training and the test file, the test score measures memory, not skill. If the training text is laid out differently from production, the model learns the wrong layout. If the loss covers the wrong tokens, the model learns the wrong thing. This worked example fixes each problem in turn.
An instruction dataset is a set of examples, each made of an instruction or question and the answer you want. A chat dataset stores the same thing as a list of messages with roles: system (standing instructions), user (the request) and assistant (the answer). We use the chat form because our model is an instruct model trained on chat messages.
You need Python 3.12 and the Transformers library. The scripts only use the tokenizer of HuggingFaceTB/SmolLM2-135M-Instruct, a small open-weight instruct model; the first run downloads its tokenizer files (a few megabytes) and may print a warning about unauthenticated requests, which you can ignore.
mkdir -p ft-data && cd ft-data
python3.12 -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
python -m pip install "torch==2.15.*" --index-url https://download.pytorch.org/whl/cpu
python -m pip install "transformers==5.23.*"02. Step 1: Look at the raw data
The script below stands in for the real log. It writes 32 phrasings (sentence patterns, eight per issue) and fills each one 14 times with random order numbers, products, dates and prices. About 30% of the messages end with an urgency phrase. Then it does what real logging systems do: it saves 40 messages a second time unchanged, and 40 more a second time in capital letters with extra spaces, as if a different tool had stored them. Each row keeps the id of its phrasing, template, because we will need it for the split.
"""Generate raw support messages with their JSON labels (seeded, offline)."""
import json
import random
PRODUCTS = ["kettle", "desk lamp", "rain jacket", "blender", "yoga mat", "backpack",
"toaster", "headphones", "desk chair", "water bottle", "phone case",
"rug"]
PHRASINGS = {
"late": [
"Order {oid} ({product}) still hasn't arrived, it was due on {day} May.",
"Where is my {product}? Order number {oid}, paid {price} pounds.",
"Tracking for {oid} has not moved for {n} days. It's a {product}.",
"My {product} from order {oid} is {n} days late.",
"Hi, order {oid} was meant to come on {day} May. Still no {product}.",
"Still waiting on the {product}, order {oid}, ordered {n} weeks ago.",
"The {product} (order {oid}) is overdue by {n} days, any news?",
"No sign of order {oid} yet. It was one {product} for {price} pounds.",
],
"damaged": [
"The {product} in order {oid} arrived cracked.",
"Order {oid}: the box was crushed and the {product} is broken.",
"My {product} came with a big dent. Order {oid}, delivered on {day} May.",
"Received order {oid} today but the {product} is damaged and won't work.",
"The {product} from {oid} has a torn seam, I paid {price} pounds.",
"Order {oid} - {product} arrived scratched all over.",
"Opened order {oid}: the {product} is snapped in two.",
"{n} parts of the {product} were broken when order {oid} arrived.",
],
"wrong_item": [
"I ordered a {product} (order {oid}) but got something else.",
"Order {oid} contained the wrong item instead of my {product}.",
"You sent me the wrong colour {product}. Order {oid}.",
"Order {oid} should be a {product}, I got {n} of a different product.",
"Got a parcel for order {oid} and it is not the {product} I chose.",
"The item in {oid} is not a {product}. Please swap it.",
"Wrong {product} model in order {oid}, delivered on {day} May.",
"Order {oid}: asked for a {product}, the box has a different item.",
],
"refund": [
"Please refund order {oid}, I no longer need the {product}.",
"I want my {price} pounds back for the {product}, order {oid}.",
"Can I return the {product} from order {oid} for a refund?",
"Order {oid}: I changed my mind about the {product}, refund please.",
"Requesting a refund for {oid}. The {product} is unused.",
"How do I get money back for order {oid}? It was a {product}.",
"Cancel and refund order {oid}, the {product} cost {price} pounds.",
"I sent the {product} back {n} days ago. Where is the refund for {oid}?",
],
}
URGENT = ["This is urgent.", "I need this sorted today.", "Please reply ASAP."]
def make(seed=0, per_template=14):
rng = random.Random(seed)
rows, number = [], 0
for issue, texts in PHRASINGS.items():
for text in texts:
number += 1
for _ in range(per_template):
oid = str(rng.randint(10000, 99999))
product = rng.choice(PRODUCTS)
urgent = rng.random() < 0.3
msg = text.format(oid=oid, product=product, day=rng.randint(2, 28),
price=rng.randint(9, 199), n=rng.randint(2, 9))
if urgent:
msg += " " + rng.choice(URGENT)
label = {"order_id": oid, "product": product,
"issue": issue, "urgent": urgent}
rows.append({"template": f"t{number:02d}", "message": msg,
"label": label})
# Logged data is messy: some messages were saved twice, some with small edits.
for row in rng.sample(rows, 40):
rows.append(dict(row)) # exact copy
for row in rng.sample(rows, 40):
rows.append(dict(row, message=row["message"].upper() + " ")) # edited copy
rng.shuffle(rows)
return rows
if __name__ == "__main__":
rows = make()
with open("raw.jsonl", "w") as f:
for row in rows:
f.write(json.dumps(row) + "\n")
print(f"{len(rows)} raw rows, {len({r['template'] for r in rows})} phrasings")
print(json.dumps(rows[0], indent=1))python make_data.py528 raw rows, 32 phrasings
{
"template": "t11",
"message": "My phone case came with a big dent. Order 17070, delivered on 23 May.",
"label": {
"order_id": "17070",
"product": "phone case",
"issue": "damaged",
"urgent": false
}
}The messages contain other numbers besides the order number (dates, prices, counts of days), so a model that copies the first number it sees will fail on some of them.
03. Step 2: Count the duplicates before you split
An exact duplicate has the same text, character for character. A near-duplicate differs only in small ways, such as letter case, spacing or punctuation. A simple and cheap way to catch the second kind is to normalise the text before comparing: lower-case it, replace punctuation with spaces and collapse runs of spaces. Two messages with the same normalised text are treated as copies.
The script also splits the raw rows at random (80% train, 20% validation), as many first attempts do, and counts the validation rows that have a copy in training.
"""How many duplicates are there, and what would a random split do with them?"""
import json
import random
import re
from collections import Counter
def norm(text):
"""Lower case, drop punctuation, collapse spaces: trivial edits get one key."""
return " ".join(re.sub(r"[^a-z0-9 ]", " ", text.lower()).split())
if __name__ == "__main__":
rows = [json.loads(line) for line in open("raw.jsonl")]
exact = Counter(r["message"] for r in rows)
loose = Counter(norm(r["message"]) for r in rows)
print("rows:", len(rows))
print("extra copies, exact text: ", sum(c - 1 for c in exact.values()))
print("extra copies, normalised text:", sum(c - 1 for c in loose.values()))
# A naive 80/20 random split of the raw rows, before any deduplication.
shuffled = rows[:]
random.Random(0).shuffle(shuffled)
cut = int(0.8 * len(shuffled))
train_keys = {norm(r["message"]) for r in shuffled[:cut]}
val = shuffled[cut:]
leaked = sum(norm(r["message"]) in train_keys for r in val)
print(f"validation rows with a copy in train: {leaked} of {len(val)}")python find_dupes.pyrows: 528
extra copies, exact text: 40
extra copies, normalised text: 80
validation rows with a copy in train: 22 of 106Exact matching finds only the 40 plain copies; normalising finds all 80. With the naive split, 22 of the 106 validation rows, about one in five, already appear in the training data. A model can get those right by memorising them, so the validation score would look better than the model really is. Deduplicate first, then split.
Normalisation has limits. It does not catch a message that was reworded ("has not arrived" against "hasn't arrived"). Large datasets add fuzzy matching, such as MinHash over word shingles or embedding similarity, and someone reviews borderline pairs by hand.
04. Step 3: Deduplicate, then split by phrasing
Even after deduplication, a random split has a quieter problem. Every phrasing appears 14 times with different order numbers. If some of those land in training and others in test, the test set mostly checks whether the model can fill a sentence pattern it has already seen. Real customers will write sentences nobody wrote before. So prepare.py keeps whole phrasings together: two phrasings per issue go to the test set, one per issue to validation, and the other twenty to training. This is a group split; in real data the group might be the customer, the source system or the week the message arrived.
The script writes each example in the prompt-completion layout that the TRL library accepts: prompt holds the system and user messages, completion holds the assistant answer, and we keep the original label dict for scoring later. The answer is compact JSON without spaces, which saves tokens on every example.
"""Deduplicate, split by phrasing and write prompt/completion files in chat format."""
import json
import random
from find_dupes import norm
SYSTEM = ("Reply with JSON only: order_id, product, issue (late, damaged, "
"wrong_item or refund) and urgent (true or false).")
# Two phrasings per issue are held out for the test set, one for validation.
TEST = {"t02", "t07", "t10", "t15", "t18", "t22", "t26", "t30"}
VAL = {"t04", "t12", "t20", "t28"}
def as_json(label):
return json.dumps(label, separators=(",", ":")) # compact: fewer tokens
def to_example(row):
return {
"prompt": [{"role": "system", "content": SYSTEM},
{"role": "user", "content": row["message"]}],
"completion": [{"role": "assistant", "content": as_json(row["label"])}],
"label": row["label"],
}
rows = [json.loads(line) for line in open("raw.jsonl")]
seen, unique = set(), []
for row in rows: # keep the first copy of every normalised text
if norm(row["message"]) not in seen:
seen.add(norm(row["message"]))
unique.append(row)
print(f"raw {len(rows)} -> unique {len(unique)}")
splits = {"train": [], "val": [], "test": []}
for row in unique:
t = row["template"]
splits["test" if t in TEST else "val" if t in VAL else "train"].append(row)
for name, part in splits.items():
random.Random(0).shuffle(part)
with open(f"{name}.jsonl", "w") as f:
for row in part:
f.write(json.dumps(to_example(row)) + "\n")
phrasings = len({r["template"] for r in part})
print(f"{name:5} {len(part):3} rows from {phrasings} phrasings")python prepare.pyraw 528 -> unique 448
train 280 rows from 20 phrasings
val 56 rows from 4 phrasings
test 112 rows from 8 phrasingsExpect a lower test score on unseen phrasings than on a random split: it is the honest number, closer to what users will see. Validation has its own phrasings, so you can tune settings on it without touching the test set.
05. Step 4: Render examples with the chat template
A model does not see a list of messages. It sees one long string of tokens, and the chat template decides how messages turn into that string: which special tokens mark the start and end of a turn and how roles are written. Each instruct model ships its own template in its tokenizer, and tokenizer.apply_chat_template applies it. Training and serving should both go through this function, so that the model sees the same layout in both places.
The script prints one example twice: once without a system message, as a prompt ready for generation (add_generation_prompt=True appends the opening of the assistant turn), and once as a full training example. Long lines are wrapped for the screen.
"""What does the model actually see? Render one example with the chat template."""
import json
import textwrap
from transformers import AutoTokenizer
def show(text): # wrap long lines for the screen
for line in text.splitlines():
print(textwrap.fill(line, 80, subsequent_indent=" ",
break_long_words=False))
tok = AutoTokenizer.from_pretrained("HuggingFaceTB/SmolLM2-135M-Instruct")
ex = json.loads(open("train.jsonl").readline())
print("--- prompt without a system message")
show(tok.apply_chat_template([ex["prompt"][1]], tokenize=False,
add_generation_prompt=True))
print("--- full training example")
show(tok.apply_chat_template(ex["prompt"] + ex["completion"], tokenize=False))python show_template.py--- prompt without a system message
<|im_start|>system
You are a helpful AI assistant named SmolLM, trained by Hugging Face<|im_end|>
<|im_start|>user
Order 30330: asked for a backpack, the box has a different item. I need this
sorted today.<|im_end|>
<|im_start|>assistant
--- full training example
<|im_start|>system
Reply with JSON only: order_id, product, issue (late, damaged, wrong_item or
refund) and urgent (true or false).<|im_end|>
<|im_start|>user
Order 30330: asked for a backpack, the box has a different item. I need this
sorted today.<|im_end|>
<|im_start|>assistant
{"order_id":"30330","product":"backpack","issue":"wrong_item","urgent":true}<|im_end|>Two details matter. First, this template inserts a default system message ("You are a helpful AI assistant named SmolLM…") when you do not give one. If you train without a system message but your application sends its own, the model is trained on text it will never see in production. Our files include the same system message that the application will send. Second, every turn ends with <|im_end|>. That token is how the model says "my answer is finished", so it has to be part of what the model learns to produce.
06. Step 5: Mask the prompt tokens in the labels
A causal language model is trained to predict each next token. In Hugging Face models you pass labels with the same length as input_ids, and the model shifts them by one position inside its loss function. Any label set to -100 is skipped: PyTorch cross-entropy ignores that value by default (its ignore_index). Loss masking uses this to train only on the answer. The prompt tokens still go through the model, so the answer is conditioned on them, but no gradient asks the model to reproduce the system message or the customer text.
The script builds the labels by hand. It tokenises the prompt with the generation prompt appended, tokenises the full example, checks that the first is a prefix of the second, and replaces the prompt part of the labels with -100.
"""Build input_ids and labels by hand, with the prompt tokens masked out (-100)."""
import json
from transformers import AutoTokenizer
tok = AutoTokenizer.from_pretrained("HuggingFaceTB/SmolLM2-135M-Instruct")
ex = json.loads(open("train.jsonl").readline())
prompt = tok.apply_chat_template(ex["prompt"], add_generation_prompt=True)
full = tok.apply_chat_template(ex["prompt"] + ex["completion"])
prompt_ids, full_ids = prompt["input_ids"], full["input_ids"]
assert full_ids[:len(prompt_ids)] == prompt_ids, "prompt is not a prefix"
labels = [-100] * len(prompt_ids) + full_ids[len(prompt_ids):]
trained = sum(x != -100 for x in labels)
print(f"tokens {len(full_ids)}, masked {len(prompt_ids)}, trained on {trained}")
start = len(prompt_ids) - 6
for pos in range(start, start + 10):
shown = "-100" if labels[pos] == -100 else str(labels[pos])
print(f" {pos:3} {tok.decode([full_ids[pos]])!r:14} label {shown}")
print("last two trained tokens:", [tok.decode([t]) for t in full_ids[-2:]])python mask.pytokens 100, masked 71, trained on 29
65 '<|im_end|>' label -100
66 '\n' label -100
67 '<|im_start|>' label -100
68 'ass' label -100
69 'istant' label -100
70 '\n' label -100
71 '{"' label 39428
72 'order' label 2559
73 '_' label 79
74 'id' label 311
last two trained tokens: ['<|im_end|>', '\n']Of 100 tokens, 71 belong to the prompt and are masked; the loss uses the other 29, which are the JSON answer plus the end-of-turn token and the newline after it. Including <|im_end|> teaches the model to stop after the closing brace. The prefix check matters because the mask is placed by counting tokens: if a template rendered the boundary differently when the answer is present, the count would point at the wrong position and you would silently train on part of the prompt or skip part of the answer.
In practice a library does this for you: with a prompt-completion dataset, TRL's SFTTrainer masks the prompt by default (completion_only_loss), and assistant_only_loss does the same for message lists when the template marks assistant turns. Doing it once by hand tells you what to check in the batches it builds, as you will in the next lab.
07. Check your understanding
08. Apply it
For your project (a small instruct model tuned for JSON field extraction), build the dataset the same way before you train anything. Choose the group that defines "unseen" for your task, such as the source system or the customer, and split by it. Write a short data card: raw rows, copies removed and by which rule, and the size of each split. Render three examples with your model's chat template and check them by eye, including the system message. Build the labels for one example by hand, as in step 5, and keep the script to compare with the trainer in the next lab.
09. Review prompt
Without looking back, answer in your own words:
- Why must deduplication happen before the split, and what does normalising text catch and miss?
- What is a group split, and why did we keep whole phrasings in one split?
- What does a chat template do, and which two details of the SmolLM2 template did step 4 point out?
- What does a label of -100 mean, and which tokens of an example should still be trained on?
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.