Suryanand/ Bootcamp
suryanand.com ↗Let's talk
← Fine-tuningAI guideIntermediate#fine-tuning#data#synthetic-data#datasets
Frame · ai-engineering / fine-tuning / 02-training-data-and-synthetic-data.mdGuide 073 / 103

Preparing training data and synthetic data

The model you get out of fine-tuning is mostly a mirror of the data you put in. I have seen teams spend a week tuning learning rates when the real problem was that a third of their examples had the wrong answer. This doc covers how I build a fine-tuning dataset: where examples come from, how to format them, how to generate synthetic data responsibly, and the cleaning steps that actually move quality.

Why it matters

Quality beats quantity for post-training. The LIMA paper showed that around a thousand carefully curated examples could produce a strong instruction follower, and that result has held up in practice: a small clean set usually beats a large noisy one. Meanwhile, synthetic data from strong "teacher" models has become the default way to bootstrap a dataset, and both the Tulu 3 and DeepSeek-R1 reports lean heavily on generated and filtered data.

Bad data shows up in subtle ways: a model that occasionally emits the wrong JSON key, refuses valid requests because a few training refusals slipped in, or memorises your eval set and looks great until real users arrive.

How it works

A dataset pipeline has four stages: source, format, clean and split. Synthetic generation is just another source, but it needs an extra filtering stage because teachers make mistakes too.

Rendering diagram…

Sources. In order of value: real production inputs with corrected outputs, expert-written examples, and synthetic examples. Real inputs matter most because they capture the messy distribution users actually send.

Format. Modern trainers expect conversational records. TRL's SFTTrainer accepts either a messages list or a prompt / completion pair, and applies the model's chat template for you. Preference methods like DPO need prompt, chosen and rejected. Keep one canonical JSONL format in your repo and convert at training time.

Clean. Deduplicate exact and near-duplicate examples (MinHash or embedding similarity works well), strip PII you do not need, fix inconsistent formatting, and remove any example whose input overlaps with your test set. That last step, decontamination, is the one people skip and regret.

Split. Hold out a test set before you do anything else and never train on it. Split by user, document or time when possible, not randomly by row, so near-identical examples cannot leak across splits.

Reference architecture

Synthetic generation works best as a generate, verify, filter loop. The teacher proposes outputs, a verifier (unit tests, a schema validator, or an LLM judge with a rubric) scores them, and only the passing examples join the pool.

Rendering diagram…

Two practical rules. First, diversify your seed prompts, because a teacher given the same style of prompt produces a narrow, repetitive dataset. Self-Instruct style approaches start from a small seed set and ask the model to write new tasks, then filter for novelty. Second, tag every example with its source (human, logs, synthetic:teacher-name) so you can ablate later and answer the inevitable question "did the synthetic data help?".

Check the teacher model's terms of use before generating training data from it. Several providers restrict using outputs to train competing models, and your legal team will want to know.

Code

A small, real-world cleaning script: convert raw records to TRL's conversational prompt-completion format, drop near-duplicates by embedding similarity, and remove anything that overlaps the test set.

import json
from datasets import Dataset
from sentence_transformers import SentenceTransformer, util

raw = [json.loads(l) for l in open("raw_examples.jsonl")]
test_inputs = {json.loads(l)["input"].strip().lower() for l in open("test.jsonl")}

def to_chat(r):
    return {
        "prompt": [
            {"role": "system", "content": "You convert support tickets into triage JSON."},
            {"role": "user", "content": r["input"]},
        ],
        "completion": [{"role": "assistant", "content": r["output"]}],
        "source": r.get("source", "unknown"),
    }

# 1. decontaminate against the held-out test set
rows = [to_chat(r) for r in raw if r["input"].strip().lower() not in test_inputs]

# 2. near-duplicate removal with embeddings
encoder = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
texts = [r["prompt"][-1]["content"] for r in rows]
emb = encoder.encode(texts, convert_to_tensor=True, normalize_embeddings=True)
keep, seen = [], []
for i in range(len(rows)):
    if seen and util.cos_sim(emb[i], emb[seen]).max() > 0.95:
        continue
    seen.append(i)
    keep.append(rows[i])

ds = Dataset.from_list(keep).train_test_split(test_size=0.1, seed=42)
ds.save_to_disk("triage_sft")
print(len(raw), "raw ->", len(keep), "kept")

The pairwise loop is fine for tens of thousands of rows; for millions, use MinHash LSH or a vector index instead.

Trade-offs and pitfalls

  • Synthetic data collapses diversity. A model trained only on one teacher's outputs inherits its quirks and phrasing. Mix sources and vary prompts and temperatures.
  • Teachers hallucinate. Without a verifier, you are distilling errors. For anything checkable, check it.
  • Format drift kills SFT. If half your examples use "priority": "P1" and half use "priority": 1, the model will do both. Normalise with a schema validator.
  • Training on the prompt tokens. For prompt-completion data, TRL computes loss on the completion only by default; for messages data you need assistant_only_loss=True and a compatible chat template. Training on long system prompts wastes capacity.
  • Leaking evals. Public benchmark questions are all over the web and in synthetic outputs. Decontaminate against every eval set you plan to report.
  • Privacy. Production logs contain personal data. Redact before the data leaves the production boundary, and record consent and retention rules alongside the dataset.

Checklist

  • Freeze a held-out test set first and decontaminate everything against it.
  • Store one canonical JSONL schema with a source tag on every row.
  • Validate outputs against a schema or checker before they enter the pool.
  • Deduplicate exact and near-duplicate examples.
  • Hand-review a random sample of at least 50 to 100 rows per source.
  • Check teacher model terms before using outputs for training.
  • Version the dataset (hash or dataset card) alongside each training run.

Further reading

Why this exists README

I learn best by explaining things, so I record the explanations. Everything here is free, with no sign-up. If a lesson helps you ship something, I'd love to hear about it.