AI Wiki中文/EN

Training-data deduplication: a match is a decision, not just a hash

训练数据去重

Build an auditable small deduplication pipeline and test hash collisions, candidate recall, graph chaining and split priority.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

If A resembles B and B resembles C, must C be deleted?

Consider three authored documents with word sets a b c, a b c d, and b c d. The first and second share three of four distinct words; so do the second and third. But the first and third share only two of four. At a similarity threshold of 0.75, the first two pairs match and the endpoints do not.

A connected-component policy still puts all three in one group. Keeping one representative can therefore delete a document that does not directly match the survivor. This is a consequence of the grouping policy, not a broken similarity calculation.

Training-data deduplication requires such decisions: what counts as a duplicate, at what unit, and which copy should survive? Repeated documents can overweight material, repeated passages can remain inside otherwise different documents, and train–test overlap can make evaluation misleading. Lee and colleagues distinguish exact repeated substrings from near-duplicate documents and describe separate methods for them. “Hash the files and keep one” is a useful non-AI baseline, but it addresses only one version of the problem.

Candidate probability, direct similarity and connected-component deletion are three different decisions.
Candidate probability, direct similarity and connected-component deletion are three different decisions.

Separate candidate generation from the removal decision

Begin with a declared representation C(x)C(x). Identity preserves raw text; another policy might case-fold and collapse whitespace. Exact equality under that representation is

x≡Cy⟺C(x)=C(y).x\equiv_C y\quad\Longleftrightarrow\quad C(x)=C(y).

A hash can place likely-equal representations into the same bucket, but equality must still be verified if collisions must not merge unequal records. Our implementation checks the text inside each bucket. Its optional canonicalization is Python case folding plus whitespace splitting/joining—not Unicode NFKC and not a semantic-equivalence test. It can merge US with us, so its normalization policy needs justification.

For near-duplicate candidates, tokenize a document into words t1,…,tmt_1,\ldots,t_m and form a set of contiguous nn-grams, also called shingles:

Sn(x)={(ti,…,ti+n−1):1≤i≤m−n+1}.S_n(x)=\{(t_i,\ldots,t_{i+n-1}):1\le i\le m-n+1\}.

A set ignores multiplicity and, for n=1n=1, all word order. Jaccard similarity compares overlap with the size of the union:

J(A,B)=∣A∩B∣∣A∪B∣.J(A,B)=\frac{|A\cap B|}{|A\cup B|}.

The code assigns two empty sets similarity one as an explicit convention, but rejects empty sets at the MinHash stage. A document shorter than the chosen shingle width needs a separate policy; silently treating all such documents as interchangeable would discard information.

Under a uniform random permutation π\pi of the shingle universe, the minimum-ranked element of a set defines a MinHash value. For nonempty sets,

hπ(A)=min⁡a∈Aπ(a),Pr⁡[hπ(A)=hπ(B)]=J(A,B).h_\pi(A)=\min_{a\in A}\pi(a),\qquad \Pr[h_\pi(A)=h_\pi(B)]=J(A,B).

The identity follows because the first element of A∪BA\cup B under a uniform permutation is equally likely to be any union element. The minima match exactly when that element lies in the intersection. Repeating with KK independent permutations gives an estimate

J^(A,B)=1K∑j=1K1{hπj(A)=hπj(B)}.\widehat J(A,B)=\frac1K\sum_{j=1}^{K}\mathbf1\{h_{\pi_j}(A)=h_{\pi_j}(B)\}.

This estimate has sampling error. The teaching code really shuffles a finite universe, which is convenient for inspecting the assumption but not scalable to an enormous corpus. Production hash families approximate the permutation behavior and need their own collision and implementation analysis.

Locality-sensitive hashing can split a signature into bb bands of rr rows each, proposing a pair when any entire band matches. Under the independent-permutation model, a pair with similarity ss becomes a candidate with probability

Pcandidate(s)=1−(1−sr)b.P_{\mathrm{candidate}}(s)=1-(1-s^r)^b.

With 20 bands and 6 rows, the probability is about 0.980154 at s=0.75s=0.75, but about 0.270187 at s=0.5s=0.5. Candidate generation is neither a hard threshold nor a guarantee of recall. The pipeline must verify candidates with its actual similarity rule, and it may still miss true above-threshold pairs that were never proposed.

The toy uses exact Jaccard at threshold 0.75 for verification. Lee et al. use a different production design: MinHash candidates followed by an edit-similarity filter, alongside a separate suffix-array substring method. Their concrete settings should not be confused with our deliberately small unigram example.

Finally, connect verified pairs into a graph. The opening counterexample has

J(A,B)=0.75,J(B,C)=0.75,J(A,C)=0.5.J(A,B)=0.75,\qquad J(B,C)=0.75,\qquad J(A,C)=0.5.

Connected components take a transitive closure of the pairwise relation. A representative-first policy that compares each new document only with retained representatives makes a different trade-off and can depend on processing order. Neither policy is automatically equivalent to the statement “every deleted document directly matches the survivor.”

Seven documents and an audit trail

The complete Python 3.12 standard-library program uses seven authored records. Three form the similarity chain, one repeats a record exactly, one changes its spaces, one is a validation copy, and one is unrelated teaching text. No real personal data or internet corpus is included. The pipeline exposes exact groups, normalized groups, MinHash candidates, verified pairs, connected components and the final survivor map.

"""Original tiny deduplication pipeline with inspectable candidate/decision stages."""
from collections import defaultdict
import hashlib
import itertools
import json
import random


def canonical(text):
    return ' '.join(text.casefold().split())


def exact_groups(documents, normalize=False, digest=None):
    digest=digest or (lambda text:hashlib.sha256(text.encode('utf-8')).digest())
    buckets=defaultdict(list)
    for ident,text in sorted(documents.items()):
        value=canonical(text) if normalize else text
        # A hash match only chooses a bucket; equality is checked independently.
        groups=buckets[digest(value)]
        match=next((g for g in groups if g['text']==value),None)
        if match is None:
            match=dict(text=value,ids=[]);groups.append(match)
        match['ids'].append(ident)
    return sorted([g['ids'] for groups in buckets.values() for g in groups])


def shingles(text,n=1):
    if not isinstance(n,int) or n<1:
        raise ValueError("Positive shingle width required")
    tokens=canonical(text).split()
    return {tuple(tokens[i:i+n]) for i in range(len(tokens)-n+1)}


def jaccard(a,b):
    union=a|b
    return len(a&b)/len(union) if union else 1.


def signatures(sets,count=120,seed=13):
    if not sets or any(not s for s in sets.values()) or not isinstance(count,int) or count<1:
        raise ValueError("Nonempty shingle sets and positive signature length required")
    universe=sorted(set().union(*sets.values()));rng=random.Random(seed)
    signatures={key:[] for key in sets}
    for _ in range(count):
        order=universe.copy();rng.shuffle(order);rank={x:i for i,x in enumerate(order)}
        for key,values in sets.items():signatures[key].append(min(rank[x] for x in values))
    return signatures


def candidates(sig,bands=20):
    lengths={len(x) for x in sig.values()}
    if len(lengths)!=1 or not isinstance(bands,int) or bands<1:
        raise ValueError("Equal-length signatures and positive bands required")
    size=next(iter(lengths))
    if size==0 or size%bands:
        raise ValueError("Signature length must divide into equal bands")
    rows=size//bands;out=set()
    for band in range(bands):
        buckets=defaultdict(list)
        for key,values in sorted(sig.items()):buckets[tuple(values[band*rows:(band+1)*rows])].append(key)
        for keys in buckets.values():out.update(itertools.combinations(keys,2))
    return out


def components(ids,edges):
    neighbors={x:set() for x in ids}
    for a,b in edges:
        if a not in neighbors or b not in neighbors:raise ValueError("Unknown document ID")
        neighbors[a].add(b);neighbors[b].add(a)
    unseen=set(ids);out=[]
    while unseen:
        root=min(unseen);unseen.remove(root);todo=[root];group=[]
        while todo:
            current=todo.pop();group.append(current)
            for other in sorted(neighbors[current]&unseen):unseen.remove(other);todo.append(other)
        out.append(sorted(group))
    return sorted(out)


def choose_representatives(groups,splits):
    # A declared policy: protect a validation representative, otherwise lowest ID.
    if set(splits.values())-{'train','valid'}:raise ValueError("Unknown split")
    kept=[];removed={}
    for group in groups:
        winner=min(group,key=lambda x:(splits[x]!='valid',x));kept.append(winner)
        removed.update({x:winner for x in group if x!=winner})
    return sorted(kept),removed


def demo():
    docs={'a':'alpha beta gamma','b':'alpha beta gamma delta','c':'beta gamma delta',
          'copy':'alpha beta gamma','spaces':'alpha  beta gamma',
          'valid':'alpha beta gamma','unique':'an unrelated teaching note'}
    splits={x:('valid' if x=='valid' else 'train') for x in docs}
    sets={key:shingles(text) for key,text in docs.items()}
    sig=signatures(sets);proposed=candidates(sig)
    scores={f'{a}|{b}':jaccard(sets[a],sets[b]) for a,b in itertools.combinations(sorted(docs),2)}
    truth={(a,b) for a,b in itertools.combinations(sorted(docs),2) if jaccard(sets[a],sets[b])>=.75}
    verified={(a,b) for a,b in proposed if jaccard(sets[a],sets[b])>=.75}
    clusters=components(docs,verified);kept,removed=choose_representatives(clusters,splits)
    return dict(documents=docs,splits=splits,exact=exact_groups(docs),normalized_exact=exact_groups(docs,True),
                similarities=scores,candidates=[list(x) for x in sorted(proposed)],
                verified=[list(x) for x in sorted(verified)],missed=[list(x) for x in sorted(truth-verified)],
                clusters=clusters,kept=kept,removed=removed,
                chain=[scores['a|b'],scores['b|c'],scores['a|c']],
                candidate_probabilities={str(s):1-(1-s**6)**20 for s in [.5,.75,1.]},
                minhash_ab=sum(x==y for x,y in zip(sig['a'],sig['b']))/len(sig['a']))


if __name__=='__main__':
    print(json.dumps(demo(),indent=2))

Raw equality produces five groups. Case-folded whitespace-normalized equality produces four because the extra-space record joins the exact copies. The near-duplicate stage uses 120 permutations with seed 13. In this particular sample it proposes eleven pairs, verifies all eleven, and misses none of the above-threshold pairs found by an independent all-pairs calculation. That is one measured tiny-corpus result, not a promise that MinHash has perfect recall.

The resulting policy keeps valid and unique. It deletes c in favor of valid, although their direct similarity is only 0.5. The audit map records the representative; the graph edges show that the justification is a path through another document. This is exactly the aggressive chain behavior discussed above.

Validation priority is a declared choice inspired by the split priority described in Lee et al., not a universal rule for every dataset. If a trusted evaluation set must be preserved, remove its overlapping training material. If you control a new split, grouping related records before assigning groups to splits can prevent leakage. Do not silently alter a benchmark’s test set or tune thresholds using its answers.

For MM documents, total text length LL, total shingle occurrences across stored sets HH, universe size UU, and KK permutations, ordinary hashing is approximately O(L)O(L) expected work before collision verification. This explicit permutation implementation costs O(K(U+H))O(K(U+H)) and stores O(KM+U+H)O(KM+U+H) data. Candidate buckets can still emit O(M2)O(M^2) pairs in the worst case. Verifying candidates costs their actual set-comparison work; components cost O(M+∣E∣)O(M+|E|). The transparent implementation is a small-data baseline, not a replacement for external-memory or distributed corpus tooling.

Deduplication is not proof of cleanliness or privacy

Whole-document equality misses shared passages inside different documents. Shingle sets can confuse boilerplate overlap with equivalent meaning, and case folding can erase useful distinctions. A repeated quotation may be legitimate; a single sensitive record may be harmful even when it has no duplicate. Record why a policy removes data and inspect representative samples of both removed and retained records.

Kandpal and colleagues report reduced generation of memorized material after deduplication in their studied language models. Their evaluation concerns particular duplication definitions, models and attack measurements. Removing duplicates does not provide a formal privacy guarantee or demonstrate that no training record can be recovered. Their discussion also distinguishes exact recovery from broader approximate or semantic duplication.

Before a corpus-scale run, version the normalization, shingle width, signature construction, band settings, similarity threshold, representative rule and split policy. Preserve stable IDs and removal reasons. Measure candidate recall against an exact comparison on a manageable audit subset, quantify removed tokens as well as removed documents, and check whether rare languages or domains are disproportionately removed. These are different questions from “did the script finish?”

Audit a deletion before accepting it

  1. Two documents have the same hash. Is deleting one necessarily safe?

Answer: No. A hash match selects a bucket; a collision can join unequal values. Compare the declared normalized representations before deleting. The tests force every document into one hash bucket and still keep unequal texts separate.

  1. For sets abc, abcd, bcd, calculate all three Jaccard similarities. What does a 0.75 connected-component policy do?

Answer: They are 0.75, 0.75 and 0.5. The two accepted edges connect all three vertices. Keeping one component representative may delete an endpoint that fails the direct threshold against that representative.

  1. If a MinHash candidate pair passes one matching band, can the exact verification stage be skipped?

Answer: No. Even a pair with similarity 0.5 has candidate probability about 0.270187 under the example’s band model. Candidate generation trades recall and cost; the final similarity decision is separate. It also cannot recover above-threshold pairs that were missed before verification.

  1. The pipeline removes five of seven documents and the remaining corpus has no detected near-duplicate pair. Has it proved privacy or improved model quality?

Answer: Neither. It has established the result of a particular detector and retention policy on seven synthetic records. Privacy needs its own threat model and evidence; model quality needs training and evaluation. The chain deletion also shows why removed content must be audited.

Keep the duplicate definition next to the result

Lee et al., sections 4–5, provide the distinction between substring and document deduplication, candidate/filter separation, graph grouping and split priority. Kandpal et al., the duplication discussion and section 5, connect a specified deduplication procedure to measured memorization risks. This chapter tests an original small pipeline with exact all-pairs auditing, not those corpus-scale experiments. Return to data mixtures to account for how deletion changes effective training proportions.

Make a prediction, then check

A matches B and B matches C above a threshold. Must A match C?

Choose one answer

Learning objectives

  • Specify the normalization and unit of duplication before removing records.
  • Separate MinHash candidate generation from an exact similarity decision.
  • Audit how connected components and split priority can remove indirectly related documents.

Prerequisites & connections

Explore related knowledge →

References

  1. Deduplicating Training Data Makes Language Models Better
    Katherine Lee; Daphne Ippolito; Andrew Nystrom; Chiyuan Zhang; Douglas Eck; Chris Callison-Burch; Nicholas Carlini · 2022
  2. Deduplicating Training Data Mitigates Privacy Risks in Language Models
    Nikhil Kandpal; Eric Wallace; Colin Raffel · 2022

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-20 · Single AI author read Lee ACL2022 sections4–5/PDF3–5 and Kandpal ICML2022 PDF3/6 plus selected section6 text. Seven paired equations and four explained exercises. Original seven-record pipeline, forced hash collision, all-permutation MinHash identity, candidate verification/all-pairs audit, nontransitive chain and validation-first representative. Engineering article; no corpus-scale replication or formal privacy guarantee.

  • Single AI author read Lee ACL2022 sections4–5/PDF3–5 and Kandpal ICML2022 PDF3/6 plus selected section6 text. Seven paired equations and four explained exercises. Original seven-record pipeline, forced hash collision, all-permutation MinHash identity, candidate verification/all-pairs audit, nontransitive chain and validation-first representative. Engineering article; no corpus-scale replication or formal privacy guarantee.
  • Four computed SVG variants per topic;9 numeric/geometry tests and18 responsive cases passed. Six final Chinese-mobile/English-desktop screenshots actually inspected. Full article acceptance recorded separately.

Source locations checked:

  • Deduplicating Training Data Makes Language Models Better · Read sections 4–4.2 and beginning of 5; visually checked PDF3–5. Exact substrings versus near-duplicate documents, suffix arrays, MinHash candidates plus edit-similarity filter, connected components and validation/test priority. No corpus-scale benchmark reproduced.
  • Deduplicating Training Data Mitigates Privacy Risks in Language Models · Visually checked PDF3 and6: duplicate definition, sequence versus document duplication and section5 comparison of two 1.5B C4 models; read section6 text on broader duplication. Reported mitigations are not a formal privacy guarantee or our replication.

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.