Lesson 31.5 · 5 of 5 · 8 min read · Reviewed 24 Nov 2026
Lab: build a small preference dataset
By the end, you can
- Build a small, clean preference dataset for one task.
- Run the checks that make a preference dataset trustworthy before training.
- Split and format the dataset for a DPO trainer.
This lab lesson puts 101.1 and 101.2 together. You will build a small preference dataset for one task, check it, and save it in the shape a DPODPO: Direct preference optimization: training directly on pairs of preferred and rejected responses, without a separate reward model. trainer expects. The Playground lab below does the checking and splitting in code. The rating is up to you.
The task
Pick something narrow, where “better” can be written down. This walk-through uses replies to customers whose delivery is late. Better means: apologises once, gives a concrete next step, does not invent facts, stays under 80 words.
Step 1: write the rating guide
One page is enough. For each quality, give a rule and an example.
| Quality | Rule | Good | Bad |
|---|---|---|---|
| Action | Offers a concrete next step | “I’ll send a tracking link now.” | “Please be patient.” |
| Honesty | No made-up dates or facts | “I can’t see a delivery date yet.” | “It will arrive at 3pm.” |
| Tone | One apology, no grovelling | “Sorry for the wait.” | “We are so, so sorry…” |
| Length | Under 80 words | 45 words | 140 words |
Add a tie rule: if neither answer is clearly better, mark it tie. Ties are dropped, not guessed.
Step 2: collect prompts
Write or gather 50 to 100 prompts. Vary them: polite and angry customers, short and long messages, one or two that ask for something the agentAgent: A system where a model decides its own next steps, calling tools in a loop until the task is done. cannot do. Breadth beats volume.
Step 3: generate answers
For each prompt, generate two answers from the model you plan to tune, at a normal temperatureTemperature: A sampling setting that controls randomness: lower values make output more predictable, higher values more varied.. Using its own answers keeps the pairs on-policy: the model learns to choose between things it actually writes.
Step 4: rate
Rate each pair against the guide: chosen, rejected, and a one-line reason. Have a second person rate a random 20% of the pairs without seeing the first ratings.
Step 5: run the checks
| Check | Target |
|---|---|
| Agreement on the double-rated sample | At least 80% the same choice |
| Share of pairs where chosen is longer | Between 40% and 60% |
| Near-duplicates (answers almost identical) | Dropped |
| Ties and empty answers | Dropped |
If agreement is low, the guide is unclear. Fix the guide and re-rate, rather than training on noise. If chosen is almost always longer, add pairs where the shorter answer wins.
Step 6: split and save
Split by prompt: every pair for a given prompt goes to the same side. Keep about 10% for testing. Save one record per line:
{"prompt": "My parcel is three days late.", "chosen": "Sorry for the wait. I've ...", "rejected": "Delays happen. Please ..."}
This prompt, chosen, rejected shape is what common DPO trainers read. If your model uses a chat template, apply it consistently (29.8).
What you end up with
A file of perhaps 60 to 90 clean pairs, a test file of 6 to 10, the rating guide, and a short note of the check results. That is enough to try a small DPO run with LoRALoRA: Low-rank adaptation: fine-tuning a small set of added weights instead of the whole model. on an open model, and, just as useful, enough to discover whether your idea of “better” is clear.
Common mistakes
- Rating before writing the guide. Taste drifts over a session.
- Splitting by pair. The same prompt in train and test makes test scores look better than they are.
- Keeping every pair. Twenty clean pairs teach more than a hundred noisy ones.
Key points
- Start from one narrow task and a written rating guide, then collect varied prompts.
- Generate two or more answers per prompt from the model you plan to tune, and rate them against the guide.
- Check length balance, ties, near-duplicates and agreement on a double-rated sample before you keep any pair.
- Split by prompt, so no prompt appears in both training and test, and save one JSON record per line.
Package a clean preference dataset
Turn rated pairs into a checked, split dataset in the prompt, chosen, rejected shape.
You will have: A list of clean train and test records, an agreement figure, and one JSON line ready for a DPO trainer.
Steps
- Count agreement on the double-rated pairs.
- Skip ties, disagreements and near-duplicates.
- Split by prompt with a stable hash, so a prompt never lands on both sides.
- Print the counts, the length share and the first train line as JSON.
Done when
- Agreement prints 3/4.
- Prompts in both splits prints 0.
- The JSON line has exactly prompt, chosen and rejected.
Open in the Playground No API key needed.
Starter code (Python)
# Turn rated pairs into a clean, split preference dataset in JSON lines.
import json
import zlib
rated = [
# prompt, answer A, answer B, rater 1 choice, rater 2 choice (None if not double-rated)
("My parcel is three days late.", "Sorry for the wait. I've sent a tracking link.", "Delays happen. Please wait.", "A", "A"),
("My parcel is three days late.", "Sorry. I can't see a date yet; I'll email you when it moves.", "It will arrive at 3pm today.", "A", None),
("The courier left it at the wrong house.", "Please contact the courier.", "Sorry about that. I've opened a claim and a new one ships today.", "B", "B"),
("Where is my order?", "It's on its way. Here is the tracking link.", "It's on its way. Here is the tracking link!", "A", None),
("Can I change my delivery address?", "Yes, I've updated it to the new address.", "You can change it in Settings.", "tie", None),
("My order never arrived.", "Sorry. I've sent a replacement by express delivery.", "Have you checked with your neighbours?", "A", "B"),
("Why is my parcel late?", "There was a delay at the depot. It should reach you tomorrow.", "Parcels are sometimes late for many reasons, including weather, staffing and volume, so please be patient.", "A", None),
("The box was crushed.", "Sorry it arrived like that. Would you like a refund or a replacement?", "Please send photos first.", "A", "A"),
]
pairs, agree, double = [], 0, 0
for prompt, a, b, r1, r2 in rated:
# TODO: count agreement on double-rated pairs (r2 is not None)
# TODO: skip ties, disagreements and near-duplicates (answers equal once trailing "!" and "." are removed)
chosen, rejected = (a, b) if r1 == "A" else (b, a)
pairs.append({"prompt": prompt, "chosen": chosen, "rejected": rejected})
def side(prompt):
# TODO: split by prompt, for example zlib.crc32(prompt.encode()) % 10 < 2 goes to "test"
return "train"
train = [p for p in pairs if side(p["prompt"]) == "train"]
test = [p for p in pairs if side(p["prompt"]) == "test"]
print(f"kept pairs: {len(pairs)} (train {len(train)}, test {len(test)})")
print("first train line:", json.dumps(train[0]))
Show a solution
# Turn rated pairs into a clean, split preference dataset in JSON lines.
import json
import zlib
rated = [
# prompt, answer A, answer B, rater 1 choice, rater 2 choice (None if not double-rated)
("My parcel is three days late.", "Sorry for the wait. I've sent a tracking link.", "Delays happen. Please wait.", "A", "A"),
("My parcel is three days late.", "Sorry. I can't see a date yet; I'll email you when it moves.", "It will arrive at 3pm today.", "A", None),
("The courier left it at the wrong house.", "Please contact the courier.", "Sorry about that. I've opened a claim and a new one ships today.", "B", "B"),
("Where is my order?", "It's on its way. Here is the tracking link.", "It's on its way. Here is the tracking link!", "A", None),
("Can I change my delivery address?", "Yes, I've updated it to the new address.", "You can change it in Settings.", "tie", None),
("My order never arrived.", "Sorry. I've sent a replacement by express delivery.", "Have you checked with your neighbours?", "A", "B"),
("Why is my parcel late?", "There was a delay at the depot. It should reach you tomorrow.", "Parcels are sometimes late for many reasons, including weather, staffing and volume, so please be patient.", "A", None),
("The box was crushed.", "Sorry it arrived like that. Would you like a refund or a replacement?", "Please send photos first.", "A", "A"),
]
pairs, agree, double = [], 0, 0
for prompt, a, b, r1, r2 in rated:
if r2 is not None:
double += 1
agree += r1 == r2
if r1 == "tie" or (r2 is not None and r1 != r2):
continue # ties and disagreements are dropped
if a.rstrip("!.") == b.rstrip("!."):
continue # near-duplicate
chosen, rejected = (a, b) if r1 == "A" else (b, a)
pairs.append({"prompt": prompt, "chosen": chosen, "rejected": rejected})
def side(prompt):
# Split by prompt: the same prompt always lands on the same side.
return "test" if zlib.crc32(prompt.encode()) % 10 < 2 else "train"
train = [p for p in pairs if side(p["prompt"]) == "train"]
test = [p for p in pairs if side(p["prompt"]) == "test"]
shared = {p["prompt"] for p in train} & {p["prompt"] for p in test}
longer = sum(len(p["chosen"]) > len(p["rejected"]) for p in pairs) / len(pairs)
print(f"agreement on double-rated pairs: {agree}/{double}")
print(f"kept pairs: {len(pairs)} (train {len(train)}, test {len(test)})")
print(f"prompts in both splits: {len(shared)}")
print(f"chosen longer in {longer:.0%} of pairs")
print("first train line:", json.dumps(train[0]))
Finished the chapter? Take the chapter check.