Data engineering for fine-tuning
- Production
- 40 min
- Lesson 2 of 7 in Fine-tuning
- Last verified
Select text in the lesson first to keep it with your note. With the keyboard, move focus here and press the button: the note goes with the section you are reading.
In this module
On this page
Before you start
- Completed:When to tune, and what it costs
- Completed:Fine-tuning data, risks and shippingEvaluation and model adaptation
You will be able to
- Choose data sources for a tuning goal and say what each one risks, verify synthetic data before trusting it, and use a learning curve rather than a rule of thumb to decide whether more data will help.
- Order the cleaning steps (filter, deduplicate, decontaminate, remove personal data) and explain what each one protects against.
- Split by group or by time rather than by row, keep a golden test set that nobody trains on, and report slices as well as the average.
- Render examples with the exact serving chat template, include the end-of-turn token, mask the loss to the assistant tokens, and audit the result by decoding a batch.
Kavya brings ten thousand example conversations and reads the count from her sheet.
Some are exact copies. Some are twins with one word changed. Three match, line for line, the conversations Ananya set aside for the final test.
Which belong in the training pile, and how would you know?
Concept
Fine-tuning data, risks and shipping gave you the short version: quality beats volume, match the production format, hold out a test set, decontaminate. When to tune, and what it costs said that most disappointing runs are data or evaluation problems. This lesson is the work behind those sentences. It follows one dataset from raw sources to the exact tokens the model is trained on, and it names what goes wrong at each step.
The central idea: the training set is the specification. A tuned model copies what the data shows, including its mistakes, its duplicates and its formatting accidents. No hyperparameter repairs a wrong specification.
Why It Matters
Data mistakes are quiet. A leaked test set produces a high score and no error message. A template mismatch produces a loss curve that looks fine and a model that rambles in production. A pile of near-duplicates trains well and then memorises. In each case the run “worked”, and the damage shows up later, often after the model has shipped. A candidate who can walk through the data pipeline in order, and say what each step protects against, sounds like someone who has debugged a real tune.
Mental Model
Think of the training data as a textbook that Aarav studies and the held-out test as an exam that Ananya sets. A good textbook is accurate, varied and written in the voice you want him to use. It never contains the exam questions, and it never contains the same page forty times. The pipeline in this lesson is the editor’s job: check the sources, remove the repeats, pull out anything that matches the exam, and print the pages exactly as the model will see them in use.
Where the analogy breaks: a person can skim past a bad page. A model trains on every token it is given, so a bad page costs you in proportion to how often it appears.
Where the data comes from
Each source has a strength and a trap. This table is adapted from the usual lists of data sources and regrouped by what each one costs you.
| Source | Strength | Trap |
|---|---|---|
| Written by experts | Highest quality, shaped to your task | Slow and costly; annotators drift apart over time |
| Production logs | Real inputs in the real distribution | Personal data, consent, and “approved” outputs that were never carefully checked |
| Generated by a stronger model | Cheap and fast to scale | The teacher’s mistakes are copied; provider terms may limit how outputs can be used |
| Sampled and filtered by a checker | Quality enforced by tests or a judge | A weak checker teaches the model to satisfy the checker |
| Public datasets | Free | Licence, overlap with your evaluation sets, and a mismatched distribution |
Mix sources, keep a core that a human has verified, and record where each example came from. When something goes wrong later, provenance is how you find which source to remove.
Quality and diversity before volume
The LIMA paper (Zhou et al., 2023) fine-tuned a 65B LLaMA model on 1,000 curated prompts and responses, with no reinforcement learning, and reported that it generalised to unseen tasks. The authors propose a “superficial alignment” reading: knowledge is learned almost entirely in pretraining, and tuning mostly teaches which response format to use. Their 7B ablations (2,000 examples each, scored by ChatGPT on a 1-to-6 scale) found that diverse prompts beat a homogeneous set, that filtered data beat unfiltered data by about 0.5 points, and that doubling the training set did not improve quality.
Read this with care. It is one study, with one family of base models, on conversational style and format. It supports “a small, clean, varied set can teach a format”. It does not say a new skill or new facts can be taught with a thousand examples. The authors themselves name the effort of writing such examples as the main limit.
Synthetic data, carefully
Generating examples with a stronger model is attractive because it is cheap. Its failure modes are specific.
- Copied errors. The student learns the teacher’s wrong answers as faithfully as its right ones.
- Narrowing. Shumailov et al. (2023) report that training on model-generated content, repeatedly, makes the tails of the original distribution disappear, which they call model collapse. They show it in several model types, including language models. Your single round of generated data is a milder case, but it is the reason to blend in real data and keep a real-only test set.
- Terms of use. Providers set rules about using outputs to train models. Read the terms of the model you use as a teacher before you build on its outputs.
The discipline that makes synthetic data usable is verification. Write a small hand-made seed set that is realistic and varied. Generate with varied personas, difficulty and constraints, not one prompt template. Then check every example by something other than the generator: run the code, validate the JSON against its schema, recompute the arithmetic, or use a second model or rules as a judge. Drop what fails. Then deduplicate, because generators repeat themselves.
Sizing with a learning curve
“How many examples do I need?” has no universal answer. Measure it. Train on 10, 25, 50 and 100 percent of the data with the same recipe, and score each run on the same golden set.
| Share of data | Score on golden set (illustrative) |
|---|---|
| 10 percent | 61 |
| 25 percent | 70 |
| 50 percent | 74 |
| 100 percent | 74 |
The invented numbers show the shape to look for. Going from 50 to 100 percent added nothing, so more data of the same kind will not help. The next move is better coverage or cleaner labels, aimed at the slices where errors cluster, or a different method. If the curve were still rising, you would collect more. Real curves are noisy, so repeat runs before you trust a small difference, as in Evaluating LLM systems.
Clean, dedupe, decontaminate
Run these in a fixed order, because each protects against a different failure and later steps depend on earlier ones. Cheap filters go first, so the costlier steps see less data. Deduplication comes before the split, so two copies of one example cannot end up on opposite sides. Decontamination comes before training, against evaluation sets that were built separately beforehand. Personal data comes out before anything is rendered or shared, because it cannot be taken back out of trained weights. Rendering is last because it needs the final records. The order of deduplication and personal-data removal is flexible; what must hold is that both finish before the split and the render.
Filter. Cheap rules first: length bounds, language identification, empty or refusal-only answers, broken markup, truncated responses. Model-based scores (a judge, a reward model, a classifier) come after, and they inherit the bias of whatever scored them.
Deduplicate. Start with exact matches, then near-duplicates. Lee et al. (2021) found that language-modelling datasets contain many near-duplicates and long repeated substrings: more than 1 percent of unprompted output from models trained on them was copied verbatim, one 61-word sentence appeared over 60,000 times in C4, and deduplicated training made models emit memorised text ten times less often. They also found train-test overlap affecting over 4 percent of the validation sets of standard datasets, which is why this step also protects your evaluation.
MinHash with locality-sensitive hashing is a common way to find near-duplicates without comparing every pair. It is approximate: the index returns candidates that may fall below your threshold and can miss some above it.
# Illustrative, cannot be run as-is: keep a record only if no near-duplicate is already kept.
from datasketch import MinHash, MinHashLSH
def signature(text, num_perm=128):
m = MinHash(num_perm=num_perm)
for word in set(text.lower().split()):
m.update(word.encode("utf-8"))
return m
def dedupe(records, threshold=0.85):
index, kept = MinHashLSH(threshold=threshold, num_perm=128), []
for i, r in enumerate(records):
sig = signature(r["prompt"] + " " + r["response"])
if not index.query(sig):
index.insert(str(i), sig)
kept.append(r)
return keptThe threshold of 0.85 is a starting guess. Read a sample of what it merges and what it keeps.
Decontaminate. Remove any training item that overlaps your evaluation or test items, and any public benchmark you will report on. The GPT-3 paper (Brown et al., 2020) is the well-known example: it filtered training documents for 13-word overlaps with benchmark sets, and reports that a bug in the filtering let some overlaps through and that retraining was not feasible. Two lessons follow. Test the filter instead of assuming it worked. And choose the window to fit your data: a 13-word window cannot match a five-word test question. For its own overlap analysis the paper set N per dataset from the short end of the example lengths, with a minimum of 8. This is the training-side half of benchmark contaminationBenchmark contaminationBenchmark content having leaked into a model's training data, which inflates its scores. Use public benchmarks to shortlist, not to decide.Open the glossary entry.
Remove personal data. Carlini et al. (2020) extracted hundreds of verbatim training sequences from GPT-2, including names, phone numbers and email addresses, and some appeared in only one training document. They also found larger models more vulnerable. So strip personal data before training; do not count on the model not repeating it. Keep per-customer data in per-customer adapters where the contract requires separation, and record the dataset version, the filters and the licences, so you can retrain from a cleaned set. Removing one person’s data from trained weights is hard, so plan to retrain instead.
Splits that do not leak
A split is leaking when something in the held-out set is nearly present in the training set. Row-level random splits leak whenever rows are related.
Worked example (illustrative)
Take 10,000 rows that come from 2,500 ticket threads, four rows each, and hold out a random 10 percent of rows. For a held-out row, the chance that a given sibling row is also held out is about 0.1, so the chance that all three siblings are held out is . In about 99.9 percent of cases, at least one sibling is in training. The evaluation mostly asks the model about threads it has already read.
The fix is to split by group: a thread, user, document or conversation goes entirely to one side. scikit-learn’s grouped splitters exist for this (GroupKFold, GroupShuffleSplit), with the stated aim that the same group is never in both training and test. Plain train_test_split cannot account for groups.
When the task drifts (new products, new policies), split by time: train on the past, test on the later period. A random split would let the model see the future.
The golden set and slices
Keep a small golden test set, hand-verified, that nobody trains on or tunes against (the golden setGolden setA curated set of questions with known good answers or sources, used to score a system on every change. Keep slices tagged and add real failures over time.Open the glossary entry). Keep a separate validation set for early stopping and hyperparameters. Every decision made while looking at a set wears it out a little, so the golden set is for the final answer only. How large it should be depends on how small a difference you need to detect; no verified minimum is given here.
Report slices, not only the average: rare intents, long inputs, languages, the edge cases such as empty input. An average that rises can hide a slice that fell.
Rendering and loss masking
The last step turns records into tokens, and it is where the quietest failures live.
The chat templateChat templateThe exact message format a model was trained with. Training on a different format from production is a common cause of a model that looks good offline and worse live.Open the glossary entry is the contract. A model family expects particular role markers and control tokens, and the Hugging Face guide notes that models fine-tuned from the same base can use different formats and that the wrong control tokens would hurt performance. Render training data with the same template you will serve, through the tokenizer’s own template function. Two details from the docs: for training, do not add the generation prompt, because the tokens that invite a reply are not useful when the reply is already in the data; and do not add special tokens twice, because templates usually include the beginning and end tokens already.
Teach the model to stop. The end-of-turn token must be in the target. The TRL documentation warns that for a model whose tokenizer already has a template, you still need to align the end-of-sequence token with that template so responses terminate correctly.
Mask the loss. SFTSFTShort for supervised fine-tuning: fine-tuning on pairs of a prompt and an ideal response.Open the glossary entry minimises cross-entropy over target tokens. Positions that should not count carry the label -100, the default ignore index in TRL, which is how padding is excluded. Whether prompt tokens count is a setting, and the default depends on the data format: in TRL, loss is on the completion only for prompt-completion data, and on the whole sequence for plain language-modelling data. For conversational data, assistant-only loss is an option you switch on, and it needs a chat template with generation markers. The usual choice for chat tuning is to learn from the assistant turns only, because those are what you want produced.
Why it matters, with invented numbers: if a prompt has 900 tokens and the answer 60, then without masking 900 of 960 positions, 93.75 percent, are prompt tokens. The loss would mostly measure how well the model predicts the user’s text. For multi-turn data, train on every assistant turn and mask the rest.
| Part of the example | Tokens (invented) | Counted in the loss? |
|---|---|---|
| System prompt and user message | 900 | No (label −100) if completion-only |
| Assistant answer | 60 | Yes |
| End-of-turn token | 1 | Yes, so the model learns to stop |
Without masking, 900 of 961 positions (about 93.7%) would be prompt tokens, and the loss would mostly measure how well the model predicts the user’s text.
Packing. TRL can pack several short examples into one fixed-length sequence to cut padding. Lesson 4 covers training practice.
Decoded batch audit (illustrative layout; what you should see, not real output)
[system] You extract invoice fields as JSON. label: -100 (ignored)
[user] Invoice 884, total 120.50, due 2026-11-01 label: -100 (ignored)
[assistant] {"invoice_id": "884", "total": 120.50, ...} label: kept
[end turn] <the template's end-of-turn token> label: keptThe audit takes five minutes: decode a few real batches with their labels shown, and confirm by eye that the template matches serving, the end token is present and the masks are where you meant them. A mismatch is invisible in the loss.
Real-World Application
Suppose a team has 40,000 support conversations and wants a model that turns each ticket into a JSON triage record (illustrative scenario). A sound plan, in order: filter broken and truncated threads; deduplicate near-identical conversations; decontaminate against the golden set, which was built separately beforehand; strip personal data; group the rows by conversation and split by group, with a later time period reserved for testing if the product is changing; render with the serving template and the end token; mask to the assistant turns; decode a batch. Then run the learning curve before collecting more. If the curve is flat, spend the effort on the slices with errors.
Interview Perspective
Expect: “How would you build the dataset?”, “Your offline score jumped 15 points after a data refresh and production did not move. Why?”, “How many examples do you need?”, “Why mask the prompt?”
A strong answer for the second question lists data-side causes and a test for each: leakage across a row-level split (re-split by group), duplicates crossing the split (deduplicate and compare), overlap with the evaluation set (decontaminate), and a train-versus-serve template mismatch (decode and compare). Common mistakes: answering “more data” without a learning curve, forgetting that the split is made after deduplication, and treating a clean training loss as proof.
Provenance: Common industry pattern. These are questions this topic tends to draw; none is verified for a named company.
Practice Questions
Provenance: generated practice.
- Basic: Why mask the prompt tokens in SFT loss, and what is the label that marks them?
- Intermediate: You have 40,000 support conversations. List your filtering, deduplication, split and personal-data steps in order, and say why the order matters.
- Advanced: Eval accuracy rose 15 points after a data refresh, but production did not improve. Give three data-side causes and how you would test each.
- Product: A teammate proposes generating 50,000 training examples with a larger model over a weekend. What do you ask for before agreeing?
Activity
Do, notice, apply.
- Do. Write six synthetic support tickets by hand, then add two near-duplicates of one ticket and one that copies a ticket from your imaginary golden set.
- Notice. Which of the nine would a random row split put on both sides? Which one would only a decontamination step catch?
- Apply. Write the exact order of cleaning steps for the nine tickets, and for each step the example it removes.
Homework
Write a one-page data plan for a tuning task of your choice: sources with provenance, the cleaning order, the split rule and why it is not row-level, the golden set and its slices, the chat template and end token, the loss mask, and the learning-curve experiment you would run first. State every number as an assumption.
Quick Revision
- The training set is the specification. Quality and variety first; volume only if the learning curve is still rising.
- Mix sources, keep a human-verified core, record provenance. Verify synthetic data with something other than the generator.
- Filter, deduplicate, decontaminate, remove personal data, then split. Each protects against a different failure.
- Split by group or by time, never by row. Keep a golden set nobody trains on and report slices.
- Render with the serving template, include the end token, mask the loss, and decode a batch to read it.
Check yourself
- Checkpoint (answer aloud, no notes): Design the data plan for tuning a model to turn support tickets into a JSON triage record.
- Re-test (nearby variant): The same task, but the examples are all generated by a larger model. What changes?
- Misconception to avoid: “More data is always better.”
Related
Practice
Test what you just read. Quizzes and cards are grouped by module: Fine-tuning.
Check yourself14 questions on what this lesson set out to teach
Checking answers needs JavaScript. You can still read every question and option below.
Keyboard: arrow keys move between options. Space or Enter selects the focused option.