Data engineering for fine-tuning

  • Production
  • 40 min
  • Lesson 2 of 7 in Fine-tuning
  • Last verified

Open slides(32 slides)

Before you start

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.

SourceStrengthTrap
Written by expertsHighest quality, shaped to your taskSlow and costly; annotators drift apart over time
Production logsReal inputs in the real distributionPersonal data, consent, and “approved” outputs that were never carefully checked
Generated by a stronger modelCheap and fast to scaleThe teacher’s mistakes are copied; provider terms may limit how outputs can be used
Sampled and filtered by a checkerQuality enforced by tests or a judgeA weak checker teaches the model to satisfy the checker
Public datasetsFreeLicence, 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.

Diagram: Training data comes from several sources, each with its own trap, so it is mixed and a core is verified by a human.

when something goes wrong

Expert-written

Mix of sources

Production logs

Generated by a stronger model

Sampled and filtered by a checker

Public datasets

Human-verified core

Provenance recorded on every example

Find and remove the bad source

Diagram summary: Training data comes from several sources, each with its own trap, so it is mixed and a core is verified by a human. Every example records where it came from, which is how you find which source to remove when something goes wrong later.

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.

Diagram: Synthetic data is only usable with verification.

fails

passes

Small hand-made seed set

Generate with varied personas,
difficulty and constraints

Verify with something other than the generator:
run the code, validate the schema, recompute

Drop it

Blend with real data

Train

Real-only test set, never synthetic

Evaluate

Diagram summary: Synthetic data is only usable with verification. Generate from a seed set with varied prompts, check every example with something other than the generator, drop failures, blend the rest with real data, and evaluate on a test set made only of real examples.

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 dataScore on golden set (illustrative)
10 percent61
25 percent70
50 percent74
100 percent74

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.

Diagram: Data moves from sources through filtering, deduplication, decontamination and personal-data removal, then is split by group or time.

Collect
sources with provenance

Filter
length, language, broken or truncated

Deduplicate
exact, then near-duplicate

Decontaminate
against every eval set

Remove personal data
and check licences

Split by group
or by time

Render with the chat template
and mask the loss

Decode a batch
and read it

Diagram summary: Data moves from sources through filtering, deduplication, decontamination and personal-data removal, then is split by group or time. Only after the split is it rendered with the chat template, with the loss masked, and a decoded batch is read by eye before training.

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.

Python

# 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 kept

The 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 0.13=0.0010.1^{3} = 0.001. 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.

Diagram: With a random row split, related rows land on both sides, so a held-out row usually has siblings in the training set and the score flatters...

Group split: no leak

Thread 17: rows a, b, c, d

All four rows go to the same side

Random row split: leaks

Thread 17: rows a, b, c, d

Row a held out, rows b, c, d in training

The test asks about a thread the model has seen

Diagram summary: With a random row split, related rows land on both sides, so a held-out row usually has siblings in the training set and the score flatters the model. Splitting by group sends every row of a thread, user or document to one side only.

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 exampleTokens (invented)Counted in the loss?
System prompt and user message900No (label −100) if completion-only
Assistant answer60Yes
End-of-turn token1Yes, 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: kept

The 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.

  1. 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.
  2. Notice. Which of the nine would a random row split put on both sides? Which one would only a decontamination step catch?
  3. 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.”

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.

0 of 14 answered

Keyboard: arrow keys move between options. Space or Enter selects the focused option.

ObjectiveChoose 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.

  1. Question 1 of 14A team wants a model that writes replies in the house style. They have 300 hand-checked examples and 60,000 unreviewed logs from chat sessions. Which plan fits the goal best?

    Choose one answer.

  2. Question 2 of 14A team generates 20,000 JSON-extraction examples with a stronger model and trains on them directly. A week later the tuned model repeats a systematic mistake. What was skipped?

    Choose one answer.

  3. Question 3 of 14Scores on a fixed golden set for runs trained on 20, 40, 80 and 100 percent of the data are 55, 66, 71 and 71. What is the best conclusion?

    Choose one answer.

ObjectiveOrder the cleaning steps (filter, deduplicate, decontaminate, remove personal data) and explain what each one protects against.

  1. Question 4 of 14Support conversations are collected, and three versions of the same ticket reply appear with minor edits. Where do near-duplicates do the most harm if they are left in?

    Choose one answer.

  2. Question 5 of 14A team filters its training set for 13-word overlaps with an evaluation set of short questions that average six words. What is the likely outcome?

    Choose one answer.

  3. Question 6 of 14A team strips emails and phone numbers from its tuning data and deduplicates it. Which risk has the personal-data step addressed?

    Choose one answer.

  4. Question 13 of 14A team has these steps for a ticket dataset and wants them in a safe order. Which sequence is right?

    Choose one answer.

ObjectiveSplit 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.

  1. Question 7 of 148,000 rows come from 2,000 ticket threads, four rows per thread. A random 80/20 split by row gives a strong validation score. Why can that score mislead?

    Choose one answer.

  2. Question 8 of 14A support product launches new plans every quarter, and the assistant must answer questions about plans it has not seen. Which split best matches that use?

    Choose one answer.

  3. Question 9 of 14After three rounds of adjusting prompts and settings against the same 400 held-out examples, the average rises. What is the best way to protect the final result?

    Choose one answer.

ObjectiveRender 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.

  1. Question 10 of 14A model is tuned on examples rendered with one chat template but served through a different one. Training loss looks normal. What is the most likely symptom?

    Choose one answer.

  2. Question 11 of 14Each training answer is stored without an end-of-turn token. After tuning, the model gives correct answers but keeps generating after them. What explains this?

    Choose one answer.

  3. Question 12 of 14A prompt has 500 tokens and the answer 50. Loss is computed on the whole sequence. What does this setup mostly reward?

    Choose one answer.

  4. Question 14 of 14A model is tuned and the loss looks healthy, yet replies in production start with a stray role marker. Which pre-training check would have caught this?

    Choose one answer.