Test Set Contamination in LLM Evaluation: Detection and Prevention
Test set contamination can inflate large language model scores and distort model rankings. This article explains common contamination sources and three practical detection methods—n-gram overlap, paraphrase comparisons, and perturbation tests—with reproducible Python examples, screening thresholds, and limitations for interpreting results.
1. What Is Test Set Contamination, and Why Does It Distort Scores?
This article is intended for machine learning engineers, evaluation engineers, and technical leads responsible for publishing model performance claims. It does not address specific individuals, unverified allegations, or brand comparisons. Conclusions should be based on reproducible detection procedures.
Test set contamination occurs when evaluation questions or reference answers appear in a model’s training data. If the model has already encountered the questions during training, evaluation becomes something like an open-book exam. Scores can overstate the model’s actual generalization ability, misleading decisions about model selection, deployment, and public performance claims.
Contamination has two main effects: inflated scores and distorted rankings. When two models have similar underlying capabilities, different levels of contamination can reverse their ranking. Contamination checks are therefore necessary before treating evaluation scores as comparable.
2. Common Sources of Contamination
- Training data crawling: Once evaluation datasets are published as web pages, code repositories, or supplementary materials for papers, general-purpose crawlers may collect them into pretraining corpora.
- Redistribution of published questions: Questions and answers may be reposted on forums, blogs, or question-bank websites and subsequently crawled again.
- Synthetic data feedback: Data generated by one model may be used to train the next generation. If that data includes paraphrased evaluation questions, contamination becomes harder to detect.
- Reuse in human annotation: When the same annotators work on both training and evaluation data, question styles and answer templates may be reused.
3. Detection Methods and Example Code
Three common methods target different signs of contamination. The table below summarizes their computational costs, false-positive risks, and limitations.
| Method | Detection target | Computational cost | Main false-positive risk | Applicability and limitations |
|---|---|---|---|---|
| n-gram overlap | Whether consecutive text fragments from a question appear in the corpus | Low, with an index required at scale | Common phrases and templated sentences | Effective for verbatim copying, but not paraphrases |
| Paraphrase comparison | Whether performance drops unusually after meaning-preserving rewording | Moderate; requires generating paraphrases | Poor-quality paraphrases make conclusions unreliable | Can reveal memorization-related contamination |
| Perturbation testing | Whether scores change sharply after replacing numbers or shuffling answer choices | Low to moderate | Tasks that are inherently sensitive to the perturbation | Suitable for multiple-choice and calculation questions |
3.1 n-gram Overlap Detection
Split each question into consecutive fragments and measure how many appear in the training corpus. For Chinese text, which does not use spaces to separate words, character-level n-grams can be used directly. A length of around 13 characters is a suggested starting point for this setting. Treat the overlap ratio as a screening signal for manual review, not as proof of contamination.
The following example uses Python 3.10 or later and only the standard library. It is deterministic and does not use randomness.
import reN = 13 # Character-level n-gram length; adjust for corpus scaledef char_ngrams(text: str, n: int = N) -> set[str]:text = re.sub(r"\s+", "", text)return {text[i:i + n] for i in range(len(text) - n + 1)}def overlap_ratio(question: str, doc: str, n: int = N) -> float:q = char_ngrams(question, n)if not q:return 0.0return len(q & char_ngrams(doc, n)) / len(q)if __name__ == "__main__":question = ("A tank holds three hundred liters. An inlet supplies fifteen ""liters per minute. How many minutes does it take to fill the tank?")corpus = ["Forum post: A tank holds three hundred liters. An inlet supplies ""fifteen liters per minute. How many minutes does it take to fill ""the tank? The answer is twenty minutes.","The weather is sunny today, ideal for a walk and photography in the park.",]for doc in corpus:ratio = overlap_ratio(question, doc)flag = "Manual review required" if ratio >= 0.5 else "Below threshold"print(f"overlap={ratio:.2f} {flag}")
The first document produces an overlap ratio of 1.00 and is flagged for manual review. The second produces 0.00 and remains below the threshold. These results demonstrate the code’s behavior only; they are not findings from a real training corpus. The English sample retains the character-level implementation for illustration.
Three limitations matter when interpreting the threshold:
- A threshold of 0.5 is only a starting point. Adjust it based on the false-positive rate observed during manual spot checks.
- Questions shorter than n characters cannot produce n-grams. The function returns
0.0in that case, which means the method cannot assess the question—not that it is uncontaminated. - Common phrases can inflate false positives. Filter high-frequency fragments before interpreting overlap scores.
This method detects verbatim or near-verbatim copying, not meaning-preserving rewrites.
3.2 Paraphrase Comparison
Use the following procedure:
- Randomly sample at least 200 questions using a fixed seed so the selection is reproducible.
- Have an independent model or human reviewers produce paraphrases. Each paraphrase must preserve the reference answer.
- Evaluate the original and paraphrased questions separately, recording whether each response is correct.
- Investigate further if accuracy on the original questions exceeds accuracy on the paraphrases by more than 10 percentage points and the difference is significant under McNemar’s test (
p < 0.05).
The 10-percentage-point gap is an initial screening threshold, not a definitive finding of contamination. Conclusions are unreliable unless the paraphrases have been reviewed for quality and answer preservation.
3.3 Perturbation Testing
Replace numbers in a question or shuffle the order of answer choices, updating the reference answer accordingly. If performance drops sharply on a task where the relevant capability should remain stable, the model may have memorized the original questions.
The following example demonstrates number replacement. It requires Python 3.10 or later, uses only the standard library, and sets the random seed to 42.
import randomimport redef perturb_numbers(question: str, seed: int = 42) -> str:rng = random.Random(seed)def repl(m: re.Match) -> str:return str(int(m.group()) + rng.randint(1, 9))return re.sub(r"\d+", repl, question)print(perturb_numbers("The tank holds 300 liters and fills at 15 liters per minute."))
This code demonstrates replacement logic only. The reference answer must be recalculated for the modified question; otherwise, the evaluation is meaningless.
Some tasks are inherently sensitive to numerical changes. Compare the results with those of an uncontaminated baseline model rather than interpreting the absolute score alone.
