Chapter 10
Deduplication, Quality, and Contamination
Every deduplication or quality threshold changes the empirical training distribution. Evaluate filtering and contamination controls as statistical interventions, with explicit effects on coverage, repetition, and held-out evidence.
A candidate-generation stage proposes pairs, verification creates edges, and grouping creates units for retention or split assignment. Similarity is not transitive: a connected component need not be a clique.
Deduplication at several radii¶
Deduplication changes the empirical training distribution. It can reduce wasted compute, benchmark overlap, and repeated memorization, but an overly broad rule can erase legitimate repetition, minority sources, translations, version history, or pedagogically useful variants.
Define the target relation before the algorithm:
- byte identity: exactly the same raw bytes;
- canonical identity: exactly the same normalized payload;
- near duplication: high surface overlap after limited editing or templating;
- containment: most of a short item appears inside a longer one;
- structural duplication: the same code or template with renamed identifiers and literals;
- semantic duplication: equivalent meaning with little lexical overlap.
These relations are not transitive in the same way. Exact identity forms clean equivalence classes. Thresholded similarity can create chains: A is close to B and B to C, while A is not close to C. Blind connected components can therefore merge an entire topic through bridging documents.
Exact deduplication¶
Compute a cryptographic digest over a declared canonical serialization. Preserve all source memberships even when one content object becomes the representative:
Example status: Illustrative Python excerpt; not standalone.
def exact_identity(record, normalizer_version, digest):
canonical = serialize_canonical(record)
payload = normalizer_version.encode() + b"\x00" + canonical
return digest(payload).hexdigest()
The null separator makes this concatenation unambiguous only if the version field cannot itself contain a null byte. A production schema should enforce that restriction or use length-prefixed fields. It also stores digest algorithm, serialization version, byte length, and source revision IDs.
Decide the scope:
- global deduplication removes repeats across all snapshots and sources;
- snapshot-local deduplication preserves temporal recurrence across snapshots;
- source-local deduplication prevents one source from dominating without erasing corroboration across independent sources.
The right scope depends on the objective. News recurrence may encode importance and temporal change; repeated scraped navigation usually does not.
Shingles and Jaccard similarity¶
Represent a document by a set of shingles, such as word 5-grams:
S(D) = {all distinct length-5 token windows in D}.
For sets A and B, Jaccard similarity is:
Jaccard similarity measures intersection relative to union.
This treats repeated occurrences inside one document as one set element. Multiset Jaccard or frequency-aware methods are different contracts. Token shingles are robust to small character changes but depend on tokenizer and language; character shingles handle tokenization variation but can overemphasize boilerplate.
Containment is asymmetric:
Containment asks what fraction of a nonempty reference set A appears in B.
A need not be smaller than B; the denominator defines the direction. Route empty shingle sets separately because division by zero and a MinHash minimum are undefined. If a 100-shingle answer appears inside a 10,000-shingle book, containment can be one while Jaccard is near 0.01. Use containment when short benchmark items, quotations, or snippets embedded in long documents matter.
Deriving MinHash¶
Computing exact Jaccard for every pair is quadratic. MinHash creates a fixed-size signature. Choose a random permutation pi of the shingle universe and define:
h_pi(A) = min_{x in A} pi(x).
In the union A union B, every element is equally likely to be first under a random permutation. The two minima agree exactly when that first element belongs to A intersect B. Therefore:
A MinHash collision occurs with probability equal to Jaccard similarity.
With k independent permutations or suitably constructed hash functions:
The matching fraction across independent hashes estimates Jaccard similarity.
Each indicator is Bernoulli with mean J, so:
The MinHash collision estimator is unbiased for Jaccard similarity.
and, under independence,
Estimator variance falls inversely with the number of hashes.
The standard error is largest near J=0.5. With k=128, it is at most sqrt(0.25/128) ~= 0.044. A signature is a noisy similarity estimate, not proof of duplication.
Real systems approximate independent permutations using seeded hash families. Seeds, shingling, tokenizer, hash width, empty-document behavior, and signature length are part of the serialized state.
Locality-sensitive hashing¶
Even fixed-size signatures are expensive to compare all-pairs. Divide a k = b r MinHash signature into b bands of r rows. Make a candidate pair when at least one complete band matches.
If true Jaccard similarity is s, one band matches with probability s^r. Assuming independent bands:
LSH banding converts similarity into a tunable candidate-retrieval probability.
This is an S-shaped retrieval curve, not a hard threshold. With k=128, b=16, and r=8:
- at
s=0.8, candidate probability is about0.947; - at
s=0.5, candidate probability is about0.061.
Increasing r reduces low-similarity candidates but can miss real duplicates. Increasing b improves recall and increases index and verification work. Select parameters from labeled duplicate pairs and operational budgets, then compute exact Jaccard or a stronger comparison for retrieved candidates.
Scale accounting¶
A 128-entry signature with 64-bit hashes consumes 1,024 bytes before IDs, index structures, and compression. For 100 million documents, raw signatures alone are:
100,000,000 * 1,024 bytes ~= 95.4 GiB.
The band index, shuffle copies, candidate edges, and cluster metadata can exceed that. Capacity planning must include:
- signatures and their replication;
- band-key postings and skew from empty or boilerplate documents;
- candidate verification reads;
- graph or cluster state;
- intermediate shuffle and checkpoint storage;
- incremental updates and old-version coexistence.
Exclude extremely short or low-information documents from ordinary LSH paths or use separate rules; otherwise common boilerplate shingles create huge hot buckets.
Cluster construction and representative choice¶
Candidate generation is not clustering. After verification, choose one of:
- pairwise suppression against already selected representatives;
- star clusters around a stable representative;
- bounded-diameter clustering;
- connected components with an explicit chaining-risk audit;
- source-aware quotas that keep independent or temporally important variants.
Representative selection is a product decision. The shortest item may lose context; the longest may preserve spam. Use a deterministic ranking over:
- policy and rights confidence;
- source authority and provenance completeness;
- parse integrity and information density;
- contextual completeness;
- recency or temporal relevance;
- stable source and content IDs as final tie breakers.
Retain cluster membership even when only one item trains. This enables deletion propagation, audit, and later policy changes.
Code, conversations, and semantic deduplication¶
Code requires repository-aware and structure-aware handling. Exact file hashes miss renamed variables; token or abstract-syntax signatures can catch copied functions. But common licenses, generated clients, test fixtures, and API boilerplate should not bridge unrelated repositories into one cluster. Split by repository or repository family before file-level assignment.
Conversation deduplication should distinguish identical user prompts, identical assistant answers, and identical full trajectories. Repeated prompts with independently diverse valid answers may be useful; repeated template refusals may dominate behavior.
Embedding similarity can retrieve paraphrases, translations, and generated variants, but it also merges distinct facts within one topic. Use it as candidate generation with domain-specific adjudication, not a universal delete rule. Record the embedding model and threshold because a model change changes cluster membership.
Split before leakage¶
All related items must land in the same split. A safe order is:
- construct source and duplicate groups;
- add repository, conversation, author, temporal, or generation-family constraints;
- assign groups, not individual documents, to train, validation, or evaluation;
- freeze evaluation IDs;
- run a final contamination scan from every training descendant back to evaluation groups.
Splitting individual rows and deduplicating afterward can keep one duplicate in train and one in evaluation, producing an optimistic metric.
Reference near-duplicate flow¶
Example status: Illustrative Python excerpt; not standalone.
def near_duplicate_candidates(record, lsh_index, config):
shingles = make_shingles(record, config.shingle_width)
if len(shingles) < config.minimum_shingles:
return route_short_record(record)
signature = minhash(
shingles,
seeds=config.hash_seeds,
hash_width=config.hash_width,
)
candidates = set()
for band_id, band_key in make_bands(signature, config.rows_per_band):
candidates.update(lsh_index.lookup(band_id, band_key))
verified = []
for candidate in candidates:
score = exact_jaccard(shingles, load_shingles(candidate))
if score >= config.threshold_for(record.domain):
verified.append((candidate, score))
return signature, verified
The code makes the two error layers visible: LSH can miss a pair, and the verification threshold can misclassify a retrieved pair. Measure both recall and precision on representative labeled pairs.
Quality scoring¶
Quality means expected value for a declared training objective, not resemblance to one prestigious writing style. A document can be fluent but false, authoritative but irrelevant, noisy but uniquely useful, or safe for pretraining but unsuitable for supervised imitation.
Keep a score vector¶
Useful dimensions include:
| Dimension | Example evidence | Common proxy failure |
|---|---|---|
| Integrity | Parse success, low corruption, coherent boundaries | Penalizes poetry, logs, or unconventional layout |
| Factual support | Citations, retrieval agreement, trusted source | Rewards citation-shaped hallucinations |
| Instructional value | Explanations, worked steps, clear examples | Confuses verbosity and formal tone with teaching |
| Originality | Low duplicate/boilerplate score | Penalizes legitimate standards and shared facts |
| Domain utility | Executable code, symbolic validity, expert rubric | Overfits to one toolchain or evaluator |
| Safety and privacy | Policy classifiers, PII detection, red-team rules | Creates false confidence outside labeled risks |
| Representation | Language, dialect, source, topic, difficulty coverage | Treats demographic inference as ground truth |
Store raw features and component scores alongside any aggregate. A scalar:
A composite score is interpretable only when its components and weights remain visible.
is convenient for ranking but hides compensation: a very high fluency score could offset a privacy warning unless policy gates are separated. Policy-disallowed records should not become eligible merely because their weighted sum is high.
Define labels by downstream use¶
Scorer labels should answer a concrete question, such as:
- "Would an expert include this document in a general pretraining mixture?"
- "Does this solution provide a correct and teachable code trajectory?"
- "Is this conversation an exemplary response for supervised imitation?"
- "Will this record add novel capability after existing mixture coverage?"
These are different targets. Write a rubric with positive, negative, and borderline examples. Measure annotator disagreement; ambiguity in the label is a property of the task, not just noise to average away. Adjudicate policy labels separately from utility preferences.
Split scorer training and validation by source, time, and duplicate cluster. A random row split lets the scorer memorize site templates and produces misleading accuracy.
Calibration and threshold metrics¶
Suppose a binary scorer emits p_i, its estimated probability that example i satisfies a defined usefulness rubric, with label y_i in {0,1}. The Brier score is:
The Brier score measures probability calibration and discrimination together.
Calibration means that among records assigned score near 0.8, roughly 80 percent satisfy the rubric. Check reliability curves and Brier score by domain, language, source type, and length. A globally calibrated score can be badly miscalibrated on a small domain.
For a hard threshold tau, report:
- retention rate;
- precision among retained examples;
- false-rejection rate among useful examples;
- token mass, not only document count;
- per-slice versions of all three;
- score drift on new crawl snapshots.
ROC area alone is insufficient when the operating point retains 10 percent of a billion-document pool. Precision and slice-specific false rejection at the actual threshold determine what trains.
Filter, weight, or route¶
Use three actions deliberately:
- filter for prohibited use, severe corruption, confirmed leakage, or extremely low expected value;
- weight when utility is continuous and uncertainty should influence exposure gradually;
- route when data is valuable but needs a specialized parser, mixture, objective, or reviewer.
If a score becomes a sampling weight, bound it:
w_i = clip(g(S_i), w_min, w_max).
Without a cap, a small score error can cause one style or source to repeat for many epochs. Record both raw count and effective token weight.
Evaluate a filter causally¶
A shorter filtered dataset can appear better for the wrong reason:
- it may receive more epochs under a fixed step budget;
- it may change token length and therefore optimization dynamics;
- it may remove evaluation-like material while improving genuine generalization, or the reverse;
- it may change language and domain mixture;
- its scorer may have been trained on the same benchmark family used for evaluation.
Run controlled pilots:
- fixed training tokens and compute: compare candidate and baseline mixtures at equal optimizer steps and sequence length;
- fixed unique-data exposure: compare whether gains come from repeating a small retained set;
- matched mixture: hold domain/language mass constant while changing the quality rule;
- filter complement: train or evaluate on removed data to learn what signal was lost;
- threshold sweep: estimate utility versus retention rather than testing one arbitrary cutoff;
- fresh holdouts: use evaluations not seen by scorer training or threshold selection.
Track validation loss by source slice, downstream capability, calibration, safety, memorization, and rare-domain regressions. A filter is justified by the model trained from its output, not by aesthetically pleasing retained samples.
As a concrete confound, suppose a filter reduces 100 million documents to 30 million. If both runs train on 100 million document draws, the filtered run sees about 3.3 nominal passes through its retained pool while the baseline sees one. Any gain may come from repeated exposure rather than quality. Report unique documents and effective repeats.
Diagnose representation bias¶
If a scorer rejects dialectal text:
- freeze the scorer and preserve affected records;
- quantify rejection by dialect, source, topic, length, code-switching, and annotation confidence;
- manually audit matched pairs that differ in dialect but not utility;
- inspect labels and annotator guidance for prestige-language bias;
- test whether fluency, perplexity, or source-domain proxies dominate the score;
- relabel with qualified annotators and explicit dialect coverage;
- recalibrate or use slice-specific routing rather than hiding the issue with one threshold;
- retrain small controlled models and check both target utility and cross-dialect regressions.
The goal is not demographic parity for every data property. It is to prevent an irrelevant proxy from suppressing valuable signal and to make intentional distribution choices visible.
Adversarial and operational testing¶
Quality scorers can be gamed by keyword stuffing, citation-shaped text, formal formatting, or generated prose tuned to the scorer. Inspect the highest-scoring new records, not only random samples. Maintain challenge sets for spam, duplicated templates, fabricated citations, and model-generated style imitation.
Version scorer weights, feature code, calibration data, and thresholds independently. A scorer update should create a new feature column and release candidate, not rewrite historical scores in place.
Contamination and benchmark leakage¶
Contamination is information from an evaluation target entering model development in a way that makes the reported metric overstate the intended generalization. It is broader than copying an exact test string.
Contamination taxonomy¶
| Path | Example | Why exact matching misses it |
|---|---|---|
| Direct | Test question and answer in pretraining | Formatting or tokenization changed |
| Partial | Answer explanation without the prompt | Only a small substring overlaps |
| Derivative | Tutorial solves the same benchmark task | Surface wording differs |
| Paraphrase or translation | Synthetic rewrite of a test item | Semantic identity, low lexical overlap |
| Code-family | Same repository or solution with renamed symbols | Function text is modified |
| Generator leakage | Teacher saw the benchmark, then generates a variant | Benchmark text may never appear |
| Process leakage | Evaluation data influences filter, prompt, or checkpoint selection | No training row contains the item |
| Interactive leakage | Repeated evaluation feedback drives model changes | Human optimization targets the test |
A public benchmark can remain useful for iteration, but then it is a development set. Final claims require protected or freshly constructed evaluations.
Detection layers¶
Freeze a canonical evaluation registry before training. For each evaluation item, retain raw form, canonical forms, n-grams, structural features, source family, creation time, and access policy.
Use multiple scans:
- exact raw and normalized hashes;
- substring and n-gram overlap;
- MinHash or suffix-based retrieval for partial overlap;
- code AST, repository, or test-signature matching;
- embedding retrieval for paraphrase candidates;
- model- or human-assisted adjudication of high-risk candidates;
- lineage checks for shared generators, sources, and annotators.
For evaluation n-gram set G(E) and training document n-grams G(D), asymmetric containment is:
C(E in D) = |G(E) intersect G(D)| / |G(E)|.
This is more appropriate than Jaccard when a short question appears in a long document. Thresholds must depend on item length and n-gram width. One matching 8-gram is strong evidence for a ten-word item and weak evidence for a long standards document.
Embedding similarity increases recall but can flag legitimate shared concepts. Treat it as retrieval, then adjudicate using answer identity, uncommon details, source history, and temporal evidence. A high semantic score alone does not prove leakage.
Quantify risk without hiding uncertainty¶
Report at least:
Report the affected evaluation mass together with detection thresholds and uncertainty.
This is a detector flag rate, not established contamination prevalence. Report confirmed, uncertain, and unreviewed flags separately. Estimating prevalence additionally requires evidence about false positives and missed cases; an unflagged item is not proof of independence.
and:
flagged_mass_rate = sum_i weight_i * flagged_i / sum_i weight_i.
The second can weight items by token count, benchmark importance, or another declared measure. Also report severity:
- exact prompt and answer;
- exact prompt only;
- substantial n-gram containment;
- likely paraphrase or derivative;
- shared source family;
- uncertain candidate.
Publish clean-slice and full-set scores when possible, but do not assume removing flagged items fixes selection bias. If only the hardest or most popular items leaked, the clean remainder is a different benchmark.
Prevention is stronger than post hoc scanning¶
Protect the evaluation supply chain:
- separate storage accounts, credentials, and compute roles for private evaluation;
- prevent evaluation objects from entering crawl, labeling, generation, and retrieval indexes;
- log every access and join against evaluation IDs;
- prohibit benchmark text in scorer prompts and synthetic seeds;
- use canary IDs or content markers where appropriate;
- rotate private tests and maintain one-time final evaluations;
- assign duplicate, repository, author, and generation families to one split before row-level sampling.
For code, split at repository or repository-family level and use hidden tests. For temporal knowledge, use time-split sources whose facts did not exist at the training cutoff. For mathematical or reasoning tasks, generate parameterized variants with independent solvers and keep final generators private.
Remediation and interpretation¶
When contamination is found:
- quarantine matching training records and descendants;
- identify releases, checkpoints, scorers, and generation jobs exposed through lineage;
- rerun clean-slice and fresh evaluations;
- decide whether a new training release or checkpoint is necessary;
- document detection limits and residual risk;
- rotate the compromised evaluation if it influenced repeated decisions.
Overlap does not prove the model memorized an item, and absence of detected overlap does not prove independence. Use extraction tests, perturbations, fresh variants, and behavior analysis to distinguish memorization from robust capability. Report evidence and uncertainty rather than a binary "decontaminated" label.
For the cumulative record, duplicate membership and adjudicated flags become selection metadata. The next stage may create synth:B as a new descendant; it must retain the parent relation rather than treating generated text as an independent source.