Slides · Fine-tuning

Data engineering for fine-tuning

Data engineering for fine-tuning

Follow one dataset from raw sources to the exact tokens the model trains on, and learn what goes wrong at each step.

By the end you can choose and verify data sources and size a set with a learning curve, order the cleaning steps, split without leakage, and render and mask examples so the loss counts only what you want produced.

Concept

Ten thousand conversations, three problems

  • Kavya reads the count from her sheet: ten thousand example conversations.
  • 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.
  • Ananya asks which belong in the training pile, and how anyone would know.
  • The training set is the specification: a tuned model copies what the data shows, including its mistakes, repeats and formatting accidents, and no hyperparameter repairs a wrong specification.
  • Data mistakes are quiet. A leaked test set gives a high score and no error, and a template mismatch gives a healthy loss curve and a model that rambles in production.
  • The deck follows the data in order: where it comes from, how to clean it, how to split it, and how to turn it into tokens.

Compare

Each source has a strength and a trap

SourceStrengthTrap
Written by expertsHighest quality, shaped to the taskSlow and costly; annotators drift apart
Production logsReal inputs in the real distributionPersonal data, consent, and approved outputs nobody checked
Generated by a stronger modelCheap to scaleThe teacher’s mistakes are copied; provider terms may limit use
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, mismatched distribution
  • This table is course judgment, not a claim from one source.

Diagram

Mix sources, verify a core, record provenance

Diagram: Several sources feed one mixed dataset.

Experts

Mixed dataset

Logs

Teacher model

Checked samples

Human-verified core

Source tag on each row

Remove a bad source later

Diagram summary: Several sources feed one mixed dataset. A human verifies a core of it, and every row keeps a source tag, so a source that turns out bad can be found and removed later.

Concept

Small and clean can teach a format

  • The LIMA study fine-tuned a 65B LLaMA model on 1,000 curated prompts and responses, with no reinforcement learning or preference modelling.
  • Its authors state a “superficial alignment hypothesis”: pretraining supplies nearly all of a model’s knowledge and ability, and tuning mostly teaches which response format to use.
  • Their ablations used 7B models with 2,000 examples per source, scored by ChatGPT on a 1 to 6 scale. Stack Exchange prompts, the more varied source, scored significantly higher than wikiHow (the authors note the two sources may differ in other ways too), quality filtering gave a 0.5-point gain, and doubling the training set did not improve quality.
  • Limits: one study, one model family, conversational style, and ablations graded by ChatGPT. It supports “a small clean varied set can teach a format”. The paper reports good results on a small set of unseen tasks, but its claim is about format and style, not about teaching new facts.

Source1 LIMA: Less Is More for Alignment

Concept

Synthetic data: cheap, with three specific risks

  • Copied errors. The student reproduces the teacher’s wrong answers just as reliably as the right ones.
  • Narrowing. Shumailov and co-authors report that training on model-generated content over successive generations makes the tails of the original distribution vanish, which they call model collapse. They show it for several model types, language models included. The paper studies successive generations, so reading a single round as a milder case is course inference. It is still a reason to mix real data in and to score on real-only examples.
  • Terms of use. Providers set rules about training on their outputs. Read the terms of the teacher model before building on it.
  • The remedy is verification by a checker that is not the generator.

Source2 The Curse of Recursion: Training on Generated Data Makes Models Forget

Diagram

A usable synthetic pipeline

Diagram: Generation starts from a hand-made seed and varied prompts.

fails

passes

Hand-made seed set

Generate: varied personas

Independent check

Drop it

Blend with real data

Train

Real-only test set

Evaluate

Diagram summary: Generation starts from a hand-made seed and varied prompts. An independent check drops failures, the rest is blended with real data, and evaluation uses a test set that contains no synthetic rows.

Check yourself

Check: where does the test set come from?

Provenance: generated practice.

A team generates 8,000 training rows with a stronger model, and an automatic validator rejects 15 percent of them. Before shipping they want a test score. How many rows survive, and should the test set come from the generated rows or from somewhere else?

Answer

15 percent of 8,000 is 1,200 rejected, so 6,800 survive. The test set should be real-only examples. Generated rows carry the teacher’s habits and mistakes, so a model trained on similar rows would look better on them than it will on real traffic.

Worked example

Size the set with a learning curve, not a rule of thumb

Train with the same recipe on growing shares of the data and score each run on the same golden set. All scores below are illustrative.

Share of dataScoreGain over previous
5 percent52
10 percent61+9.0
20 percent67+6.0
40 percent70+3.0
80 percent70.4+0.4
  • Each doubling bought less. The last one bought +0.4, which is smaller than the run-to-run spread you should expect (assume about 1 point here; measure yours with repeated runs).
  • A flat curve says more data of the same kind will not help. The next gain comes from better coverage, cleaner labels aimed at the slices where errors cluster, or a different method.
  • A curve still rising is the signal to collect more.

Diagram

The cleaning order

Diagram: Cleaning runs from cheap filters to deduplication, decontamination and personal-data removal, all before the split.

Collect with provenance

Filter

Deduplicate

Decontaminate

Remove personal data

Split by group or time

Render and mask loss

Decode a batch and read it

Diagram summary: Cleaning runs from cheap filters to deduplication, decontamination and personal-data removal, all before the split. Rendering with the chat template comes last because it needs the final records, and a decoded batch is read by eye before training.

Compare

Why this order

StepProtects againstWhy it sits here
FilterBroken, empty, truncated or off-language rowsCheap rules first, so costly steps see less data
DeduplicateMemorised repeats; copies on both sides of a splitMust finish before the split
DecontaminateTraining rows that match evaluation itemsNeeds evaluation sets built beforehand
Remove personal dataA model that repeats names and contact detailsCannot be undone in trained weights; do it before render or sharing
SplitRelated rows on both sidesAfter cleaning, so copies cannot straddle it
Render and maskWrong tokens, no stop, loss on promptsNeeds 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.

Concept

Why deduplicate: what the evidence shows

  • Lee and co-authors (ACL 2022) found that common language-modelling datasets contain many near-duplicates and long repeated substrings.
  • One 61-word English sentence appeared over 60,000 times in C4. Over 1 percent of unprompted output from models trained on such data was copied verbatim.
  • Models trained on deduplicated data emitted memorised text ten times less often.
  • Train-test overlap affected over 4 percent of the validation sets of standard datasets, so deduplication also protects your evaluation.
  • Start with exact matches, then near-duplicates.

Source3 Deduplicating Training Data Makes Language Models Better

Code

Near-duplicates with MinHash LSH

Python

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 datasketch documentation says the threshold and num_perm are fixed at initialisation, and that queries are approximate: false positives and false negatives both occur. Treat the output as candidates and read a sample.

Source4 MinHash LSH (datasketch documentation)

Worked example

The dedupe function, tested

Each pair below went through dedupe as two records (Python 3.14, datasketch 2.0.0, 2026-10-25), repeated with 500 different MinHash seeds. The first three rows use an empty prompt, so only the reply text is compared; the last row adds the same 14-word prompt to both records. Word-set Jaccard is the similarity MinHash estimates.

PairJaccard of word setsMerged at threshold 0.85Merged at threshold 0.6
Exact repeat of a 36-word reply1.00100 percent100 percent
One word changed in the 36-word reply0.9598 percent100 percent
One word changed in a 6-word reply0.715 percent81 percent
Same 6-word edit, same 14-word prompt on both0.8973 percent100 percent
  • An empty input list returns [].
  • LSH is approximate, so a single run is one draw: a pair near the threshold can land either side of it. Short texts fall well below a high threshold after one edit, so the right threshold depends on the length of your records.
  • The prompt counts, because dedupe joins prompt and reply: a long shared prompt makes near-copies look more alike. A starting guess of 0.85 needs a sample read, not trust.

Source4 MinHash LSH (datasketch documentation)

Concept

Decontaminate against every evaluation set

  • Remove any training item that overlaps your evaluation items, and any public benchmark you will report on.
  • The GPT-3 paper searched for 13-gram overlaps between its test and development sets and its training data. It states that a bug caused only partial removal of the overlaps it found, and that retraining was not feasible.
  • Two lessons: test the filter instead of assuming it worked, and fit the window to the data. In its own overlap analysis the paper sets N per dataset from the 5th percentile of example length in words, with a minimum of 8 on non-synthetic tasks and a maximum of 13.
  • The paper’s clean-benchmark rule also flags an example shorter than 13 words when the whole example overlaps. The plain contaminated function on the next slide has no such rule: with fewer than n words, an item has no n-grams to match.

Source5 Language Models are Few-Shot Learners

Code

An n-gram overlap check, tested

Python

def ngrams(text, n):
    w = text.lower().split()
    return {tuple(w[i:i + n]) for i in range(len(w) - n + 1)}

def contaminated(train_text, test_items, n):
    train = ngrams(train_text, n)
    return [t for t in test_items if ngrams(t, n) & train]

A 10-word test question and a 23-word one, against three training snippets (run 2026-10-25):

Training snippetn=13n = 13n=8n = 8n=5n = 5
Exact copy of the 10-word questionmissedcaughtcaught
Same question, one word edited in the middlemissedmissedcaught
Exact copy of the 23-word questioncaughtcaughtcaught
  • In this function, a test item with fewer words than n has no n-grams at all, and an empty item returns nothing, so neither is ever flagged.
  • A short window catches edited copies but flags more innocent overlaps. Read what each window flags.

Check yourself

Check: a window that is too short

Provenance: generated practice.

A colleague sets the overlap filter to a 3-word window and runs it on 200-word training documents against held-out questions of 7 to 11 words. What goes wrong, and how would you choose the window instead?

Answer

Many common three-word phrases appear in unrelated text, so the filter flags and removes innocent documents, and its flag count says little about real contamination. Pick a window near the shortest items, such as 5 to 7 words here, then read a sample of what it flags.

Concept

Remove personal data before training

  • Carlini and co-authors (USENIX Security 2021) 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 found that larger models were more vulnerable than smaller ones.
  • So strip personal data before training and do not count on the model staying quiet. Deleting one person’s records from trained weights is difficult, so plan a retrain from a cleaned set.
  • Record the dataset version, the filters and the licences, so a retrain is repeatable. Where a contract requires separation, keep per-customer data in per-customer adapters.

Source6 Extracting Training Data from Large Language Models

Worked example

Why row-level splits leak

Take 10,000 rows from 2,500 ticket threads, four rows each, and hold out a random 10 percent of rows.

QuantityValue
Chance a given sibling row is also held outabout 0.1
Chance all three siblings are held out0.1×0.1×0.1=0.0010.1 \times 0.1 \times 0.1 = 0.001
Held-out rows with at least one sibling in trainingabout 99.9 percent
Mean siblings in training per held-out row (expected 3×0.93 \times 0.9)2.7
  • Simulated over five seeds: every held-out row had a sibling in training, and the mean was between 2.67 and 2.72 of 3.
  • A group split of the same data (GroupShuffleSplit) left no held-out thread in training: 0.0 share, 1,000 held-out rows from 250 threads.
  • The score from a row split measures recall of threads the model has already read.

Source7 Cross-validation: evaluating estimator performance (grouped data iterators)

Concept

Split by group, or by time

  • Send a thread, user, document or conversation wholly to one side. The scikit-learn guide describes GroupKFold as ensuring the same group is not in both training and test sets, and says train_test_split cannot account for groups.
  • GroupShuffleSplit holds out a subset of groups for each split; the simulation above left no held-out group in training.
  • When the task drifts (new products, new policies), split by time: train on the past, test on a later period, so the model never sees the future.
  • A split on a single group fails: GroupShuffleSplit raised a ValueError for two rows in one group with test_size=0.5 (scikit-learn 1.9.1).
  • Deduplicate before splitting, or copies of a row can end up on opposite sides.

Source7 Cross-validation: evaluating estimator performance (grouped data iterators)

Worked example

Golden set, validation set and slices

The golden set is a small hand-verified test set that nobody trains on or tunes against; it is for the final answer only. A separate validation set serves early stopping and hyperparameter choices, because each choice made after seeing a set’s score uses that set up a little. Report slices as well as the average. Illustrative golden-set scores before and after a data refresh:

SliceShare of setBeforeAfter
Short inputs60 percent8086
Long inputs30 percent6266
Rare language10 percent6040
Weighted average72.675.4
  • 0.6×80+0.3×62+0.1×60=72.60.6 \times 80 + 0.3 \times 62 + 0.1 \times 60 = 72.6, and 0.6×86+0.3×66+0.1×40=75.40.6 \times 86 + 0.3 \times 66 + 0.1 \times 40 = 75.4.
  • How large the golden set must be depends on how small a difference you need to detect; estimate that from the spread of repeated runs.
  • The average gained 2.8 points while the rare-language slice lost 20. Only the slice table shows it.

Check yourself

Check: pick the unit of the split

Provenance: generated practice.

A model will tag clauses in contracts it has never seen. The data holds 2,000 clauses from 80 contracts, 25 clauses each, and 20 percent is held out. What is the unit of the split, and how many contracts and clauses are held out?

Answer

Split by contract, because clauses from one contract share party names, defined terms and boilerplate. 20 percent of 80 contracts is 16 contracts, which is 16×25=40016 \times 25 = 400 clauses. A row split would put sibling clauses on both sides.

Concept

Templates fix the token format

  • A model family expects particular role markers and control tokens. The Transformers guide notes that models fine-tuned from the same base can use different formats, and that with the wrong control tokens they would perform far worse.
  • Render training data with the same template you will serve, using the tokenizer’s built-in template method.
  • For training, set add_generation_prompt=False: the tokens that invite a reply are not useful when the reply is already in the data.
  • Avoid doubling the special tokens. Templates usually include them already, so tokenize rendered text with add_special_tokens=False, or let apply_chat_template(tokenize=True) do both steps.

Source8 Chat templates (Transformers documentation)

Worked example

What the template does, tested

Transformers 5.20.2, 2026-10-25, one invoice example rendered with three public tokenizers.

TokenizerRendered text ends withTokenizing the text again with default special tokens
Qwen2.5 0.5B Instructits ChatML end marker and a newlinesame ids as the template path
Zephyr 7B beta</s> and a newlineone extra leading <s> id compared with the template path
Mistral 7B Instruct v0.1</s>ids begin 1, 1: a doubled start token
  • Mistral’s rendered text already begins with <s>, and the second tokenizing step added another. With add_special_tokens=False the ids matched the template path exactly.
  • The end-of-turn token is the template’s, so the target must keep it.

Source8 Chat templates (Transformers documentation)

Concept

Mask the loss to the assistant tokens

  • SFT minimises token-level cross-entropy. Positions that should not count carry the label -100; the TRL guide gives this as the default ignore index, used for padding.
  • Whether prompt tokens count is a setting. In TRL’s SFTConfig, completion_only_loss left unset means loss on the completion for prompt-completion data and on the full sequence for plain language-modelling data. For conversational data, assistant_only_loss=True restricts loss to assistant messages and needs a chat template with generation markers. The TRL guide says it patches the template automatically for known model families such as Qwen3; for other models, check that the template includes the markers.
  • The end-of-turn token must be in the target. For a tokenizer that already has a template, the guide says to align the end-of-sequence token with it so responses terminate.
  • For multi-turn data, train on every assistant turn and mask the rest.

Source9 SFT Trainer (TRL documentation)

Code

Render and mask one example

Python

def render(messages, tok):
    assert messages and messages[-1]["role"] == "assistant", "last message must be the assistant answer"
    prompt = tok.apply_chat_template(messages[:-1], tokenize=True,
                                     add_generation_prompt=True, return_dict=True)["input_ids"]
    full = tok.apply_chat_template(messages, tokenize=True, return_dict=True)["input_ids"]
    assert full[:len(prompt)] == prompt, "template is not prefix-stable; mask by hand"
    assert tok.eos_token_id in full[len(prompt):], "end-of-turn token missing"
    labels = [-100] * len(prompt) + full[len(prompt):]
    return full, labels
  • The end-token check searches the whole answer span, because some templates add a space or newline token after it. It handles one assistant answer at the end. Multi-turn data needs a mask for every assistant turn, such as the trainer’s own option.
  • Run on the Zephyr 7B beta and Mistral 7B Instruct v0.1 tokenizers with a similar invoice example, it found the end token and passed; Zephyr’s answer ends with the end token, a space token and a newline.
  • An empty list or a last message that is not the assistant’s fails the first assertion. The prefix check fails loudly for templates that change earlier text depending on the last message.

Sources8 Chat templates (Transformers documentation)9 SFT Trainer (TRL documentation)

Worked example

The mask, tested two ways

Qwen2.5 0.5B Instruct tokenizer, one invoice example (84 tokens), run 2026-10-25 with Transformers 5.20.2 and TRL 1.16.0.

SetupTokens counted in the lossDecoded start of the counted text
render above37 of 84the JSON answer
TRL, prompt-completion data, defaults37 of 84the JSON answer
TRL, completion_only_loss=False84 of 84the system prompt
TRL, messages data, defaults84 of 84the system prompt
TRL, messages data, assistant_only_loss=True38 of 84a newline, then the answer
  • The counted answer ends with the end-of-turn token and a newline, which teaches the model where a turn ends.
  • Failure cases of render: a conversation with no final assistant message, and a template that drops the end token, each raised the assertion.
  • Prompt share: a separate ticket-triage example with a long pasted ticket and a 10-token answer-plus-end came to 493 tokens, so 483 of 493 positions (98.0 percent) are prompt if unmasked, and the loss mostly measures how well the model predicts the user’s text.
  • The one-token difference at 38 shows the assistant mask starting a token earlier than the hand-built one. Decode and read, never assume.

Source9 SFT Trainer (TRL documentation)

Check yourself

Check: spot the doubled start token

Provenance: generated practice.

A decoded batch from a Mistral-style template shows ids that begin 1, 1. What happened, and what are two ways to avoid it?

Answer

The rendered text already begins with the start token, and tokenizing it again with default special tokens added a second one. Tokenize the rendered text with add_special_tokens=False, or call apply_chat_template(tokenize=True) so one step does both.

Concept

How this is asked

Provenance: Common industry pattern.

  • Questions this topic tends to draw: how to build the dataset, why an offline score jumped while production did not move, how many examples are enough, and why the prompt is masked. None is verified as asked by a named company.
  • A strong answer to the offline-jump question lists data-side causes with a test for each: leakage across a row split (re-split by group), duplicates across 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, splitting before deduplicating, and treating a clean training loss as proof.

Summary

Recap

  • The training set is the specification. Mix sources, keep a human-verified core, record provenance, and have a checker other than the generator verify synthetic data.
  • Decide on more data with a learning curve measured on a fixed golden set.
  • Run filtering, deduplication, decontamination and personal-data removal before the split. Each step protects against a different failure.
  • Split by group or by time, never by row, and report slices as well as the average.
  • Render with the serving template, keep the end token, mask the loss, and decode a batch to read it.

References

References & Sources (1 of 2)

  1. LIMA: Less Is More for Alignment (opens in a new tab)

    Chunting Zhou, Pengfei Liu, Puxin Xu, Srini Iyer, et al.2023NeurIPS 2023Paper

    Used for LIMA: 65B model tuned on 1,000 curated examples with no reinforcement learning, the superficial-alignment idea, and the 7B ablations on diversity, filtering (0.5 points) and doubling the set.

  2. The Curse of Recursion: Training on Generated Data Makes Models Forget (opens in a new tab)

    Ilia Shumailov, Zakhar Shumaylov, Yiren Zhao, Yarin Gal, et al.2023Preprint

    Used for Training on model-generated content makes the tails of the original distribution disappear (model collapse), shown for several model types including language models.

  3. Deduplicating Training Data Makes Language Models Better (opens in a new tab)

    Katherine Lee, Daphne Ippolito, Andrew Nystrom, Chiyuan Zhang, et al.2022ACL 2022 (Proceedings of the 60th Annual Meeting of the Association for Computational Linguistics, Volume 1: Long Papers)Paper

    Used for Near-duplicates and repeated substrings in common datasets, the 61-word sentence repeated over 60,000 times in C4, verbatim output above 1 percent, ten times less memorised text after deduplication, and train-test overlap above 4 percent of validation sets.

  4. MinHash LSH (datasketch documentation) (opens in a new tab)

    Eric Zhu2026Documentation

    Used for MinHash LSH threshold and permutation count are fixed at initialisation, and queries are approximate with false positives and false negatives. The documentation version is not shown on the page.

  5. Language Models are Few-Shot Learners (opens in a new tab)

    Tom B. Brown, Benjamin Mann, Nick Ryder, Melanie Subbiah, et al.2020NeurIPS 2020Paper

    Used for 13-gram overlap filtering against test and development sets, the bug that caused partial removal, retraining not being feasible, and the per-dataset window N (5th percentile of example length, minimum 8, maximum 13) in the overlap analysis.

References

References & Sources (2 of 2)

  1. Extracting Training Data from Large Language Models (opens in a new tab)

    Nicholas Carlini, Florian Tramèr, Eric Wallace, Matthew Jagielski, et al.2021USENIX Security 2021Paper

    Used for Hundreds of verbatim training sequences extracted from GPT-2 including names, phone numbers and emails, some from a single document, and larger models being more vulnerable.

  2. Cross-validation: evaluating estimator performance (grouped data iterators) (opens in a new tab)

    scikit-learn2026Documentation

    Used for GroupKFold keeps a group out of both training and test sets, GroupShuffleSplit holds out a subset of groups, and train_test_split cannot account for groups. Page title shows scikit-learn 1.9.1.

  3. Chat templates (Transformers documentation) (opens in a new tab)

    Hugging Face2026Documentation

    Used for Different control tokens across models from one base, add_generation_prompt=False for training, and avoiding duplicated special tokens. Page shows Transformers v5.20.2.

  4. SFT Trainer (TRL documentation) (opens in a new tab)

    Hugging Face2026Documentation

    Used for Token-level cross-entropy, ignore index -100, completion_only_loss and assistant_only_loss behaviour, generation markers, and EOS alignment. Page shows TRL v1.16.0.