Detecting Benchmark Contamination: N-gram Overlap, Embedding Similarity, and Perplexity Methods

Detecting Benchmark Contamination: N-gram Overlap, Embedding Similarity, and Perplexity Methods

Benchmark contamination is not a theoretical concern. It's a measurement failure that quietly invalidates evaluation results, inflates reported scores, and misleads post-training decisions. When a model has seen benchmark items during pre-training or fine-tuning, its performance on those items reflects memorization, not capability. The problem is that contamination is often invisible unless you look for it deliberately. This post covers the three main detection methods, when each applies, and where each one breaks down.

What Is Benchmark Contamination and Why Does Detecting It Matter?

Benchmark contamination occurs when evaluation items, or close variants of them, appear in a model's training data. The result is that benchmark scores don't transfer to real-world capability. Detecting benchmark contamination through n-gram overlap, embedding similarity, and perplexity methods gives evals engineers the evidence they need to either trust a score or discard it.

The practical stakes are high. A post-training team that ships a reward model or SFT checkpoint based on contaminated eval signals may be optimizing against a measurement artifact rather than genuine task performance. The benchmark looks saturated; the model looks capable; neither conclusion is warranted.

For a deeper look at why scores on one benchmark often fail to generalize, see our post on benchmark scores and construct validity in LLM evals.

Method 1: N-gram Overlap for Detecting Benchmark Contamination

N-gram overlap is the most direct contamination signal: it measures whether exact or near-exact sequences from a benchmark item appear in the training corpus. The method is fast, interpretable, and requires no model inference.

How it works

Tokenize both the benchmark item and each training document. Compute the fraction of n-grams in the benchmark item that appear in any training document. A common threshold for flagging potential contamination is 13-gram overlap, borrowed from the approach described in the GPT-3 paper (Brown et al., 2020), though the right threshold depends on item length and domain.

Formula:

overlap(item, doc) = |ngrams(item) ∩ ngrams(doc)| / |ngrams(item)|

Flag an item if max_overlap(item, corpus) > threshold, where threshold is typically 0.8 for 8-grams or 1.0 for 13-grams (any match at all).

Practical protocol

  1. Choose n: 8-grams catch paraphrased contamination; 13-grams catch near-verbatim copies. Use both.

  2. Deduplicate the training corpus before scanning. Duplicate documents inflate apparent overlap rates.

  3. Scan at the item level, not the benchmark level. Aggregate contamination rates obscure which specific items are compromised.

  4. Report the contamination rate as a fraction of items flagged, not just a binary clean/dirty label for the whole benchmark.

  5. Remove flagged items and recompute the score. If the score drops materially, the original score was contaminated.

Limits of n-gram overlap

N-gram overlap misses semantic contamination: a training document that explains the same concept in different words will score zero overlap but still confer an advantage. It also requires access to the training corpus, which is unavailable for most closed models.

Method 2: Embedding Similarity for Detecting Benchmark Contamination

Embedding similarity catches semantic contamination that n-gram methods miss. Instead of comparing token sequences, it compares dense vector representations of benchmark items and training documents.

How it works

Encode each benchmark item and each training document (or a representative sample) using a fixed embedding model. Compute cosine similarity between each benchmark item and its nearest neighbors in the training set. Items with similarity above a threshold are flagged as potentially contaminated.

Decision threshold guidance:

  • Cosine similarity > 0.95: near-verbatim, flag unconditionally.

  • 0.85 to 0.95: semantically close, review manually.

  • 0.70 to 0.85: topically related, not necessarily contaminated; use domain judgment.

  • Below 0.70: unlikely contamination from this document.

These thresholds are illustrative starting points. Calibrate them against a gold set of known-clean and known-contaminated items for your specific domain before applying them at scale.

Choosing the embedding model

The embedding model matters. A general-purpose encoder trained on web text may not distinguish between superficially similar but semantically distinct items in a specialist domain like PLC ladder logic or structural engineering calculations. For domain-specific benchmarks, use an encoder fine-tuned on in-domain text, or validate that the general encoder produces meaningful similarity scores on held-out domain pairs.

Embedding similarity is also computationally heavier than n-gram overlap at scale. For corpora larger than a few hundred million tokens, approximate nearest-neighbor search (for example FAISS) is necessary to make the scan tractable.

Method 3: Perplexity-Based Contamination Detection

Perplexity-based detection works from the model side rather than the corpus side. The intuition is that a model assigns lower perplexity to text it has memorized than to genuinely novel text. Detecting benchmark contamination through perplexity methods is therefore useful precisely when you don't have access to the training corpus.

How it works

Compute the model's perplexity on each benchmark item. Compare this to a reference distribution: either the perplexity of a held-out clean set, or the perplexity of the same items under a model known to be trained without access to the benchmark. Items with anomalously low perplexity relative to the reference are flagged.

Perplexity as a contamination signal:

PPL(item) = exp(-1/N * sum(log P(token_i | context)))

Flag if PPL(item) < mu_reference - k * sigma_reference

Where mu and sigma are the mean and standard deviation of perplexity on the clean reference set, and k is typically 2 or 3. This is a z-score threshold applied to the perplexity distribution.

Min-K% Prob

A refinement described by Shi et al. (2024) in the paper "Detecting Pretraining Data from Large Language Models" uses the average log-probability of the lowest-probability k% of tokens in an item, rather than overall perplexity. The intuition is that memorized text tends to have uniformly high token probabilities, while novel text has a longer tail of low-probability tokens. Min-K% Prob is more robust to length variation than raw perplexity and is worth implementing alongside it.

Limits of perplexity methods

Perplexity is sensitive to item length, formatting, and vocabulary. Short items produce noisy perplexity estimates. Perplexity also conflates memorization with genuine capability on easy items: a model may assign low perplexity to a simple arithmetic problem because it's easy, not because it's memorized. Always interpret perplexity signals alongside n-gram and embedding evidence.

Worked Example: Contamination Audit on a Domain Benchmark

Illustrative example (numbers are constructed to be plausible, not drawn from a real audit):

Suppose you're auditing a 500-item benchmark covering CNC G-code generation. You have access to a 50-billion-token pre-training corpus snapshot.

  1. N-gram scan (13-gram): 38 items (7.6%) return at least one exact 13-gram match in the corpus. These are flagged as high-confidence contaminated.

  2. Embedding scan (cosine > 0.90): An additional 22 items flag as semantically close to training documents, with no 13-gram overlap. These are queued for manual review. After review, 14 are confirmed as contaminated paraphrases; 8 are false positives from generic G-code syntax that appears across many documents.

  3. Perplexity scan (z < -2.5 relative to clean reference): 11 items flag. Of these, 9 overlap with the n-gram or embedding flags. 2 are new: short items where the model assigns near-zero perplexity. Manual inspection shows both are verbatim copies of examples from a widely-circulated CNC tutorial that was in the corpus.

  4. Net result: 53 items (10.6%) are removed from the benchmark. The model's score on the remaining 447 items drops by 6.2 percentage points relative to the full 500-item score. The original score was materially inflated.

This kind of item-level audit is exactly the work that makes benchmark scores trustworthy. For a broader discussion of benchmark design properties that support this kind of auditability, see our post on frontier-grade benchmark construct validity.

Common Failure Modes in Contamination Detection

1. Auditing the benchmark but not the fine-tuning data

Detection: Score on the benchmark is high but score on a private holdout of equivalent difficulty is much lower.

Fix: Run contamination checks against all training data sources, including SFT demonstrations, RLHF preference pairs, and any synthetic data generated from web sources.

2. Using a threshold calibrated on a different domain

Detection: False-positive rate on manual review is above 30%, or obvious contamination is being missed.

Fix: Calibrate thresholds on a small gold set of known-clean and known-contaminated items from the target domain before running the full audit.

3. Reporting aggregate contamination rate instead of item-level flags

Detection: The audit report says "2% contamination" but doesn't identify which items.

Fix: Always produce an item-level flag list. Aggregate rates hide clustering: contamination is often concentrated in specific sub-topics or difficulty bands.

4. Treating perplexity as a standalone signal

Detection: Items flagged by perplexity alone include many short, syntactically simple items that are clearly not memorized.

Fix: Use perplexity as a tiebreaker or supplementary signal, not as a primary filter. Require corroboration from n-gram or embedding evidence before removing an item.

5. Ignoring contamination drift over time

Detection: A benchmark that passed a contamination audit 18 months ago is now showing anomalously low perplexity across many items in a new model generation.

Fix: Re-run contamination checks against new model checkpoints. As models are trained on more data, previously clean benchmarks can become contaminated. This is one reason benchmark discriminative power erodes over time; see our analysis of benchmark discriminative power across model generations.

6. No access to training corpus for closed models

Detection: You cannot run n-gram or embedding scans because the corpus is proprietary.

Fix: Rely on perplexity and Min-K% Prob methods. Supplement with canary insertion: include synthetic items not present anywhere on the public web, and check whether the model treats them as familiar or novel.

Where This Breaks Down

No contamination detection method is complete. N-gram overlap requires corpus access and misses semantic contamination. Embedding similarity depends on the quality of the encoder and produces false positives in domains with shared technical vocabulary. Perplexity conflates memorization with task simplicity and is unreliable on short items.

More fundamentally, all three methods detect contamination after the fact. They don't prevent it. The only reliable prevention is using original, non-web-derived benchmark items authored by domain experts who are working from practitioner knowledge rather than publicly available text. Items that have never appeared on the web cannot be in a pre-training corpus. This is why task provenance, not just post-hoc detection, is the structural solution to contamination. For a full treatment of how benchmark design choices affect contamination risk, see our post on static, dynamic, and private holdout benchmark design.

Chiron Data Labs builds tasks from practitioner knowledge in domains like CNC/CAM, structural engineering, and PCB design, specifically because non-web-derived, expert-authored content is the only category of evaluation data that doesn't require a contamination audit to trust.

FAQ

What n-gram length should I use for contamination detection?

Use both 8-grams and 13-grams. Thirteen-gram overlap catches near-verbatim copies; 8-gram overlap catches shorter paraphrased fragments. The GPT-3 paper (Brown et al., 2020) used 13-grams as the primary threshold. For short benchmark items (under 50 tokens), drop to 5-grams to avoid false negatives from items that are simply too short to produce 13-gram matches.

Can I detect contamination without access to the training corpus?

Yes, with limitations. Perplexity-based methods and Min-K% Prob (Shi et al., 2024) work from model outputs alone. They are noisier than corpus-based methods and cannot identify which specific training documents caused the contamination. Use them as a screening signal, not as definitive evidence. Canary insertion, where you embed novel items not present on the public web, provides a complementary check.

How do I interpret a contamination rate? What is a safe threshold?

There is no universal safe threshold. What matters is whether removing flagged items changes the score materially. If the score drops by more than 2-3 percentage points after removing contaminated items, the original score should not be reported as a valid capability estimate. Always report the contaminated and decontaminated scores separately so readers can judge for themselves.

Does embedding similarity work for code and formal language benchmarks?

With caveats. Code embeddings from models like CodeBERT or similar code-specific encoders are more reliable than general-purpose text embeddings for detecting semantically equivalent code. However, two code snippets can be functionally identical while appearing dissimilar to an embedding model if they use different variable names or control flow structures. Pair embedding similarity with execution-based equivalence checks where possible.

How does contamination interact with benchmark difficulty calibration?

Contamination inflates pass rates on affected items, which distorts item difficulty estimates. If you're using Item Response Theory or empirical pass@k to calibrate difficulty, run contamination detection first and exclude flagged items before calibrating. Otherwise your difficulty model will underestimate true task hardness for the contaminated items. For more on difficulty calibration methods, see our post on IRT for calibrating AI benchmark item difficulty.

What This Means in Practice

Contamination detection is not a one-time step before publication. It's an ongoing process that needs to run against each new model checkpoint and each new version of a training corpus. The three methods covered here, n-gram overlap, embedding similarity, and perplexity analysis, are complementary, not alternatives. Use all three, triangulate the signals, and report at the item level. When contamination is found, remove the affected items and recompute the score before drawing any conclusions about model capability.

The deeper lesson is that detection is a patch. Prevention, through original, expert-authored, non-web-derived tasks, is the architecture. If you're building evals or RL environments where contamination risk is a first-order concern, get in touch with Chiron Data Labs.

Benchmark contamination is not a theoretical concern. It's a measurement failure that quietly invalidates evaluation results, inflates reported scores, and misleads post-training decisions. When a model has seen benchmark items during pre-training or fine-tuning, its performance on those items reflects memorization, not capability. The problem is that contamination is often invisible unless you look for it deliberately. This post covers the three main detection methods, when each applies, and where each one breaks down.

What Is Benchmark Contamination and Why Does Detecting It Matter?

Benchmark contamination occurs when evaluation items, or close variants of them, appear in a model's training data. The result is that benchmark scores don't transfer to real-world capability. Detecting benchmark contamination through n-gram overlap, embedding similarity, and perplexity methods gives evals engineers the evidence they need to either trust a score or discard it.

The practical stakes are high. A post-training team that ships a reward model or SFT checkpoint based on contaminated eval signals may be optimizing against a measurement artifact rather than genuine task performance. The benchmark looks saturated; the model looks capable; neither conclusion is warranted.

For a deeper look at why scores on one benchmark often fail to generalize, see our post on benchmark scores and construct validity in LLM evals.

Method 1: N-gram Overlap for Detecting Benchmark Contamination

N-gram overlap is the most direct contamination signal: it measures whether exact or near-exact sequences from a benchmark item appear in the training corpus. The method is fast, interpretable, and requires no model inference.

How it works

Tokenize both the benchmark item and each training document. Compute the fraction of n-grams in the benchmark item that appear in any training document. A common threshold for flagging potential contamination is 13-gram overlap, borrowed from the approach described in the GPT-3 paper (Brown et al., 2020), though the right threshold depends on item length and domain.

Formula:

overlap(item, doc) = |ngrams(item) ∩ ngrams(doc)| / |ngrams(item)|

Flag an item if max_overlap(item, corpus) > threshold, where threshold is typically 0.8 for 8-grams or 1.0 for 13-grams (any match at all).

Practical protocol

  1. Choose n: 8-grams catch paraphrased contamination; 13-grams catch near-verbatim copies. Use both.

  2. Deduplicate the training corpus before scanning. Duplicate documents inflate apparent overlap rates.

  3. Scan at the item level, not the benchmark level. Aggregate contamination rates obscure which specific items are compromised.

  4. Report the contamination rate as a fraction of items flagged, not just a binary clean/dirty label for the whole benchmark.

  5. Remove flagged items and recompute the score. If the score drops materially, the original score was contaminated.

Limits of n-gram overlap

N-gram overlap misses semantic contamination: a training document that explains the same concept in different words will score zero overlap but still confer an advantage. It also requires access to the training corpus, which is unavailable for most closed models.

Method 2: Embedding Similarity for Detecting Benchmark Contamination

Embedding similarity catches semantic contamination that n-gram methods miss. Instead of comparing token sequences, it compares dense vector representations of benchmark items and training documents.

How it works

Encode each benchmark item and each training document (or a representative sample) using a fixed embedding model. Compute cosine similarity between each benchmark item and its nearest neighbors in the training set. Items with similarity above a threshold are flagged as potentially contaminated.

Decision threshold guidance:

  • Cosine similarity > 0.95: near-verbatim, flag unconditionally.

  • 0.85 to 0.95: semantically close, review manually.

  • 0.70 to 0.85: topically related, not necessarily contaminated; use domain judgment.

  • Below 0.70: unlikely contamination from this document.

These thresholds are illustrative starting points. Calibrate them against a gold set of known-clean and known-contaminated items for your specific domain before applying them at scale.

Choosing the embedding model

The embedding model matters. A general-purpose encoder trained on web text may not distinguish between superficially similar but semantically distinct items in a specialist domain like PLC ladder logic or structural engineering calculations. For domain-specific benchmarks, use an encoder fine-tuned on in-domain text, or validate that the general encoder produces meaningful similarity scores on held-out domain pairs.

Embedding similarity is also computationally heavier than n-gram overlap at scale. For corpora larger than a few hundred million tokens, approximate nearest-neighbor search (for example FAISS) is necessary to make the scan tractable.

Method 3: Perplexity-Based Contamination Detection

Perplexity-based detection works from the model side rather than the corpus side. The intuition is that a model assigns lower perplexity to text it has memorized than to genuinely novel text. Detecting benchmark contamination through perplexity methods is therefore useful precisely when you don't have access to the training corpus.

How it works

Compute the model's perplexity on each benchmark item. Compare this to a reference distribution: either the perplexity of a held-out clean set, or the perplexity of the same items under a model known to be trained without access to the benchmark. Items with anomalously low perplexity relative to the reference are flagged.

Perplexity as a contamination signal:

PPL(item) = exp(-1/N * sum(log P(token_i | context)))

Flag if PPL(item) < mu_reference - k * sigma_reference

Where mu and sigma are the mean and standard deviation of perplexity on the clean reference set, and k is typically 2 or 3. This is a z-score threshold applied to the perplexity distribution.

Min-K% Prob

A refinement described by Shi et al. (2024) in the paper "Detecting Pretraining Data from Large Language Models" uses the average log-probability of the lowest-probability k% of tokens in an item, rather than overall perplexity. The intuition is that memorized text tends to have uniformly high token probabilities, while novel text has a longer tail of low-probability tokens. Min-K% Prob is more robust to length variation than raw perplexity and is worth implementing alongside it.

Limits of perplexity methods

Perplexity is sensitive to item length, formatting, and vocabulary. Short items produce noisy perplexity estimates. Perplexity also conflates memorization with genuine capability on easy items: a model may assign low perplexity to a simple arithmetic problem because it's easy, not because it's memorized. Always interpret perplexity signals alongside n-gram and embedding evidence.

Worked Example: Contamination Audit on a Domain Benchmark

Illustrative example (numbers are constructed to be plausible, not drawn from a real audit):

Suppose you're auditing a 500-item benchmark covering CNC G-code generation. You have access to a 50-billion-token pre-training corpus snapshot.

  1. N-gram scan (13-gram): 38 items (7.6%) return at least one exact 13-gram match in the corpus. These are flagged as high-confidence contaminated.

  2. Embedding scan (cosine > 0.90): An additional 22 items flag as semantically close to training documents, with no 13-gram overlap. These are queued for manual review. After review, 14 are confirmed as contaminated paraphrases; 8 are false positives from generic G-code syntax that appears across many documents.

  3. Perplexity scan (z < -2.5 relative to clean reference): 11 items flag. Of these, 9 overlap with the n-gram or embedding flags. 2 are new: short items where the model assigns near-zero perplexity. Manual inspection shows both are verbatim copies of examples from a widely-circulated CNC tutorial that was in the corpus.

  4. Net result: 53 items (10.6%) are removed from the benchmark. The model's score on the remaining 447 items drops by 6.2 percentage points relative to the full 500-item score. The original score was materially inflated.

This kind of item-level audit is exactly the work that makes benchmark scores trustworthy. For a broader discussion of benchmark design properties that support this kind of auditability, see our post on frontier-grade benchmark construct validity.

Common Failure Modes in Contamination Detection

1. Auditing the benchmark but not the fine-tuning data

Detection: Score on the benchmark is high but score on a private holdout of equivalent difficulty is much lower.

Fix: Run contamination checks against all training data sources, including SFT demonstrations, RLHF preference pairs, and any synthetic data generated from web sources.

2. Using a threshold calibrated on a different domain

Detection: False-positive rate on manual review is above 30%, or obvious contamination is being missed.

Fix: Calibrate thresholds on a small gold set of known-clean and known-contaminated items from the target domain before running the full audit.

3. Reporting aggregate contamination rate instead of item-level flags

Detection: The audit report says "2% contamination" but doesn't identify which items.

Fix: Always produce an item-level flag list. Aggregate rates hide clustering: contamination is often concentrated in specific sub-topics or difficulty bands.

4. Treating perplexity as a standalone signal

Detection: Items flagged by perplexity alone include many short, syntactically simple items that are clearly not memorized.

Fix: Use perplexity as a tiebreaker or supplementary signal, not as a primary filter. Require corroboration from n-gram or embedding evidence before removing an item.

5. Ignoring contamination drift over time

Detection: A benchmark that passed a contamination audit 18 months ago is now showing anomalously low perplexity across many items in a new model generation.

Fix: Re-run contamination checks against new model checkpoints. As models are trained on more data, previously clean benchmarks can become contaminated. This is one reason benchmark discriminative power erodes over time; see our analysis of benchmark discriminative power across model generations.

6. No access to training corpus for closed models

Detection: You cannot run n-gram or embedding scans because the corpus is proprietary.

Fix: Rely on perplexity and Min-K% Prob methods. Supplement with canary insertion: include synthetic items not present anywhere on the public web, and check whether the model treats them as familiar or novel.

Where This Breaks Down

No contamination detection method is complete. N-gram overlap requires corpus access and misses semantic contamination. Embedding similarity depends on the quality of the encoder and produces false positives in domains with shared technical vocabulary. Perplexity conflates memorization with task simplicity and is unreliable on short items.

More fundamentally, all three methods detect contamination after the fact. They don't prevent it. The only reliable prevention is using original, non-web-derived benchmark items authored by domain experts who are working from practitioner knowledge rather than publicly available text. Items that have never appeared on the web cannot be in a pre-training corpus. This is why task provenance, not just post-hoc detection, is the structural solution to contamination. For a full treatment of how benchmark design choices affect contamination risk, see our post on static, dynamic, and private holdout benchmark design.

Chiron Data Labs builds tasks from practitioner knowledge in domains like CNC/CAM, structural engineering, and PCB design, specifically because non-web-derived, expert-authored content is the only category of evaluation data that doesn't require a contamination audit to trust.

FAQ

What n-gram length should I use for contamination detection?

Use both 8-grams and 13-grams. Thirteen-gram overlap catches near-verbatim copies; 8-gram overlap catches shorter paraphrased fragments. The GPT-3 paper (Brown et al., 2020) used 13-grams as the primary threshold. For short benchmark items (under 50 tokens), drop to 5-grams to avoid false negatives from items that are simply too short to produce 13-gram matches.

Can I detect contamination without access to the training corpus?

Yes, with limitations. Perplexity-based methods and Min-K% Prob (Shi et al., 2024) work from model outputs alone. They are noisier than corpus-based methods and cannot identify which specific training documents caused the contamination. Use them as a screening signal, not as definitive evidence. Canary insertion, where you embed novel items not present on the public web, provides a complementary check.

How do I interpret a contamination rate? What is a safe threshold?

There is no universal safe threshold. What matters is whether removing flagged items changes the score materially. If the score drops by more than 2-3 percentage points after removing contaminated items, the original score should not be reported as a valid capability estimate. Always report the contaminated and decontaminated scores separately so readers can judge for themselves.

Does embedding similarity work for code and formal language benchmarks?

With caveats. Code embeddings from models like CodeBERT or similar code-specific encoders are more reliable than general-purpose text embeddings for detecting semantically equivalent code. However, two code snippets can be functionally identical while appearing dissimilar to an embedding model if they use different variable names or control flow structures. Pair embedding similarity with execution-based equivalence checks where possible.

How does contamination interact with benchmark difficulty calibration?

Contamination inflates pass rates on affected items, which distorts item difficulty estimates. If you're using Item Response Theory or empirical pass@k to calibrate difficulty, run contamination detection first and exclude flagged items before calibrating. Otherwise your difficulty model will underestimate true task hardness for the contaminated items. For more on difficulty calibration methods, see our post on IRT for calibrating AI benchmark item difficulty.

What This Means in Practice

Contamination detection is not a one-time step before publication. It's an ongoing process that needs to run against each new model checkpoint and each new version of a training corpus. The three methods covered here, n-gram overlap, embedding similarity, and perplexity analysis, are complementary, not alternatives. Use all three, triangulate the signals, and report at the item level. When contamination is found, remove the affected items and recompute the score before drawing any conclusions about model capability.

The deeper lesson is that detection is a patch. Prevention, through original, expert-authored, non-web-derived tasks, is the architecture. If you're building evals or RL environments where contamination risk is a first-order concern, get in touch with Chiron Data Labs.

© 2026 CHIRON, SAN FRANCISCO, CA