Module 2 · Training data
Decontamination and deduplication
7 min read
A fine-tuned model that scores 100% on its evaluation set may have understood everything… or simply already seen the questions. That is contamination: evaluation examples identical or nearly identical to training examples. It inflates scores, hides overfitting, and leads to bad decisions. This lesson measures it on Forge, with a spectacular result, then presents the tools to detect it.
The experiment: two evaluation sets
Forge builds two evaluation sets from the same 60 templates:
- validation uses the same templates as training (with other products, greetings, noise);
- test uses 15 reserved templates, never seen in training.
for cat, templates in TEMPLATES.items():
for i, t in enumerate(templates):
(test_t if i >= len(templates) - N_TEST_TEMPLATES else train_t).append((f"{cat}-{i}", t))
After the LoRA training of lesson 3.2, the same model gets:
| Set | Valid JSON | Exact match (4 fields right) | Category | Urgency |
|---|---|---|---|---|
| Validation (known templates) | 1.00 | 1.00 | 1.00 | 1.00 |
| Test (new templates) | 1.00 | 0.65 | 0.72 | 0.93 |
A perfect score on one side, 65% on the other. Validation does not measure the ability to handle a new message: it measures the ability to recognize variants of sentences already learned. A project that only looked at validation would have shipped a model much worse than advertised.
What the model really learned
Breaking down errors by test template is enlightening:
| Test template | Exact | Dominant error |
|---|---|---|
| « On m'a facturé des frais de livraison alors que la livraison devait être offerte. » | 0/26 | payment → delivery |
| « Le livreur a récupéré [produit] hier, quand serai-je remboursé ? » | 0/21 | return → delivery |
| « Je ne garde pas [produit], vous pouvez organiser l'enlèvement ? » | 2/17 | return → delivery |
| « Quelle est la procédure pour rendre [produit] acheté le mois dernier ? » | 3/18 | return → warranty |
| « Le colis est bloqué au point relais depuis plusieurs jours. » | 19/19 | — |
(In order: delivery fees were charged although delivery was supposed to be free; the courier picked up the product yesterday, when will I be refunded?; I'm not keeping the product, can you arrange pickup?; what is the procedure to return a product bought last month?; the parcel has been stuck at the pickup point for days.) The model learned lexical shortcuts: « livraison » (delivery), « livreur » (courier) or « enlèvement » (pickup) ⇒ delivery category. On the training templates, those keywords were enough; on new phrasings that use them in another sense, they mislead. With 9 phrasings per category, the model could not learn anything else: it is a data diversity problem, which lesson 2.2 tackles.
Detecting contamination: n-grams
When you do not control data generation (web corpora, customer data, public datasets), you have to detect overlaps. The standard method compares the n-grams (sequences of n words) of the evaluation set with those of training:
counts: dict[str, int] = defaultdict(int)
for e in train:
for g in ngrams(e.message, n):
counts[g] += 1
limit = max(1, max_doc_freq * len(train))
common = {g for g, c in counts.items() if c > limit}
out = []
for e in test:
grams = ngrams(e.message, n) - common
if grams:
ratio = sum(g in counts for g in grams) / len(grams)
if ratio >= min_overlap:
out.append((e, ratio))
Two settings avoid false positives, and their effect can be measured:
| Criterion | Test (new templates) | Validation (known templates) |
|---|---|---|
| At least one shared 8-gram | 47 / 300 "contaminated" | 143 / 150 |
| ≥ 50% of 8-grams already seen, boilerplate excluded | 0 / 300 | 88 / 150 |
The naive criterion — a single shared n-gram — flags 47 test messages, although none comes from a training template: they only share boilerplate phrases (« Sans réponse sous 24 h, je saisis une association de consommateurs » — "without an answer within 24 hours, I'm contacting a consumer association"). Hence Forge's two settings: ignore n-grams present in more than 1% of training examples, and require that a large share of the text has already been seen. The test set is then clean, and validation appears for what it is: heavily contaminated by construction.
The n-gram length matters too: 13 words is the convention for long documents; on messages of 15 to 40 words, Forge uses 8. Shorter, everything looks alike; longer, nothing overlaps any more.
Near-duplicates: MinHash
Within the training set itself, near-duplicates (the same message with another signature or order number) overweight some phrasings. Comparing all pairs is too expensive beyond a few thousand examples; MinHash estimates Jaccard similarity with compact signatures, and LSH (splitting signatures into bands) only compares promising pairs:
def minhash(sets: list[set[str]], num_perm: int = 64, seed: int = 0) -> np.ndarray:
"""Signature MinHash : pour chaque permutation (simulée par un hachage salé), le plus petit haché
de l'ensemble. La part de signatures égales entre deux textes estime leur similarité de Jaccard."""
On Forge's 1,179 cleaned examples, the number of near-duplicates removed depends strongly on the threshold:
| Similarity threshold | Removed | Remaining |
|---|---|---|
| 0.9 | 23 | 1,156 |
| 0.8 | 79 | 1,100 |
| 0.7 | 211 | 968 |
| 0.5 | 573 | 606 |
« Ma carte a été débitée mais la commande n'apparaît pas dans mon compte. Ma commande : NB-18163. » (my card was charged but the order does not appear in my account) and the same sentence preceded by « Bonjour » with another number are 0.83 similar: true duplicates for learning. At 0.5, on the other hand, half the set is removed, including useful variants. As always, choose the threshold by reading pairs at several similarity levels. Specialized libraries (datasketch, text-dedup) apply the same principle to millions of documents.
The rules of a reliable test set
- Split by source, not by example: by template, customer, document, period — never by drawing random rows from a single set of variants.
- Freeze the test set before training, and never use it to choose hyperparameters (that is validation's job).
- Decontaminate training against the test set, especially after any synthetic generation (lesson 2.2).
- Break down errors by source or template: learned shortcuts show up there.
Key takeaways
- On Forge, the same model scores 100% on known templates and 65% on new ones: validation was contaminated by construction.
- The errors reveal lexical shortcuts learned for lack of diversity.
- N-gram detection: ignore boilerplate and require a share of already-seen text, otherwise everything looks contaminated.
- MinHash + LSH detects near-duplicates at scale; choose the threshold by reading pairs.
- Split by source, freeze the test set, decontaminate after every data addition.
Practice
- Compute the contamination of validation and test with 5-, 8- and 13-word n-grams: how do the numbers change?
- Remove near-duplicates at the 0.8 threshold, retrain, and compare exact match on the test set.
- Break down your own model's errors by data source: which sources concentrate the errors?