Skip to content
MAMasterAI Now
4 / 11约 14 分钟阅读难度: Intermediate5 张卡片

用 LSH 做数据去重

重复文本会毒害模型。在网页规模上找出近似重复。

⚠ 本阶段已翻译为中文 3%,其余卡片暂以英文显示。 发现有误?欢迎提交翻译修正。

阅读进度0%
Card 1 — the crime第 1 / 5 张卡片

Duplicates teach your model to memorise

If the same sentence appears 400 times, the model learns the sentence, not the language.

Web crawls are full of copies: mirrored sites, boilerplate footers, syndicated news, the same recipe reformatted by 300 blogs. Train on that raw and the loss is dominated by whichever text is most repeated.

  • Memorisation: the model can recite duplicated passages verbatim instead of generalising.
  • Benchmark leakage: if test data leaked into training, your "great results" are an illusion.
  • Wasted compute: every duplicated token is a training token you paid for twice.
  • Distorted distribution: a duplicated topic silently becomes over-weighted.
Analogy
The photocopier exam

Revisiting the same page of a textbook forty times feels like studying. It is not. It is memorising one page. Data curation is the act of choosing which pages deserve your attention — and how much.

进入下一张卡片前的一个小检查

What is benchmark leakage?

5 个知识检查

🔒

实验区已锁定

完成全部 5 张卡片及其知识检查,即可解锁这个模拟实验。

Read the full stage transcript (all 5 cards, no JavaScript required)
Card 1 — the crime

1. Duplicates teach your model to memorise

If the same sentence appears 400 times, the model learns the sentence, not the language.

Web crawls are full of copies: mirrored sites, boilerplate footers, syndicated news, the same recipe reformatted by 300 blogs. Train on that raw and the loss is dominated by whichever text is most repeated.

  • Memorisation: the model can recite duplicated passages verbatim instead of generalising.
  • Benchmark leakage: if test data leaked into training, your "great results" are an illusion.
  • Wasted compute: every duplicated token is a training token you paid for twice.
  • Distorted distribution: a duplicated topic silently becomes over-weighted.
Analogy
The photocopier exam

Revisiting the same page of a textbook forty times feels like studying. It is not. It is memorising one page. Data curation is the act of choosing which pages deserve your attention — and how much.

Knowledge check: What is benchmark leakage?

  • a. Test examples accidentally appear in the training set, inflating measured performance← correct
  • b. The model runs out of GPU memory while benchmarking
  • c. The test set is too small

Deduplication must run across the train/test boundary, not just within the training set.

Card 2 — the measure

2. MinHash: fingerprint a document in 128 numbers

Compare shingles, not strings.

Exact matching misses near-duplicates. Instead, break each document into overlapping shingles (every 5-word window) and compare the Jaccard similarity of the two shingle sets: the size of the intersection divided by the size of the union.

Computing Jaccard for every pair is O(n²) — impossible at a billion documents. MinHash fixes it with a trick: hash every shingle, keep the minimum hash value. Do that with 128 different hash functions and a document becomes a 128-number signature. The beautiful part: the fraction of positions where two signatures agree is an unbiased estimate of their Jaccard similarity.

P(minhashₖ(A) = minhashₖ(B)) = |A ∩ B| / |A ∪ B|
The probability a random hash gives the same minimum equals the Jaccard similarity itself.
Shingle overlapJaccardVerdict
Identical document1.00Exact duplicate
Same article, different ads≈ 0.9Near duplicate — drop
Same topic, different wording≈ 0.3Keep both
Nothing in common≈ 0.0Keep both

Knowledge check: What does a MinHash signature look like, and what does it estimate?

  • a. A single hash of the whole file, estimating file size
  • b. A vector of per-hash minima, whose agreement rate estimates Jaccard similarity← correct
  • c. A list of every word, estimating vocabulary size

MinHash compresses an unbounded set into a fixed-size sketch while preserving the similarity structure you care about.

Card 3 — the acceleration

3. LSH: turn billion-pair comparison into bucketing

Do not compare everything. Arrange for similar things to land in the same bucket.

Comparing every pair of documents is O(n²): a billion documents would need 5×10¹⁷ comparisons. Locality Sensitive Hashing cuts this to near-linear by exploiting one idea: similar items should collide more often than dissimilar ones.

  1. 1Compute a 128-dimension MinHash signature for every document.
  2. 2Split the signature into bands — say 16 bands of 8 rows each.
  3. 3Hash every band independently; documents landing in the same bucket for any band become candidates.
  4. 4Only compute exact Jaccard similarity for those candidate pairs, then drop the near-duplicates.
P(candidate | similarity s) = 1 − (1 − sʳ)ᵇ
r = rows per band, b = number of bands. Together they set the similarity threshold.
Bands × rowsEffective thresholdBehaviour
4 × 32≈ 0.95Very strict — only almost identical texts collide
16 × 8≈ 0.70Balanced default for web crawls
32 × 4≈ 0.50Aggressive — flags same-topic articles
NoteTuning intuition

More rows per band sharpens the S-curve (fewer false positives). More bands shifts it left (more recall). Production crawlers stack a Bloom filter for exact URLs on top, then MinHash/LSH for near-duplicates, then a semantic embedding pass for paraphrases.

Knowledge check: You want fewer false positives — only nearly identical documents flagged. What do you change?

  • a. Increase rows per band (r), which sharpens the similarity threshold← correct
  • b. Decrease the shingle size to one word
  • c. Delete the signatures

With P = 1 − (1 − sʳ)ᵇ, a larger r makes the transition from "never collide" to "always collide" steeper and moves it to higher similarity.

Card 4 — the pipeline

4. A production-grade dedup pass

Three filters, escalating in cost, each cheaper than the one after it.

py
# 1. Exact: normalise and hash the full document
key = sha256(normalise(text).encode()).hexdigest()

# 2. Near-duplicate: MinHash + LSH bands
sig = minhash(normalise(text), num_perm=128)
if lsh.insert(sig) is not None:      # collided with an existing bucket
    drop(text)

# 3. Semantic: paraphrase detection on the survivors
emb = embed(normalise(text))
if any(cosine(emb, e) > 0.95 for e in kept_embeddings):
    drop(text)
  • Normalise first: lowercase, strip HTML, collapse whitespace, drop boilerplate.
  • Deduplicate across train/validation/test splits, not inside each one.
  • Log what you dropped — a sudden 60% drop usually means a pipeline bug, not dirty data.
  • Track the duplicate rate over crawl dates to catch template regressions.
Good to knowReal-world impact

Published dedup studies on web-scale corpora report large fractions of redundant documents. Removing them reduces training time and measurably improves the quality of what the model produces, because verbatim memorisation drops.

Knowledge check: In a cost-escalating dedup pipeline, which order is correct?

  • a. Embeddings → MinHash → exact hash
  • b. Exact hash → MinHash/LSH → semantic embedding similarity← correct
  • c. Order does not matter

Run the cheapest filter first so expensive stages (and expensive embeddings) only ever see the survivors.

Card 5 — the payoff

5. What dedup does to a language model

Data curation is the cheapest quality win in the entire LLM lifecycle.

Deduplication is not hygiene for its own sake. It changes what the model can do: fewer verbatim copies means more gradient signal spent on generalisable patterns, and less capacity burned on memorised strings.

  • Less memorisation: regurgitating training text is a legal and reputational risk, and it grows with duplication.
  • Better generalisation: the effective dataset is more diverse, so the model sees more of the language.
  • Cheaper training: fewer tokens to process for the same effective coverage.
  • Fairer evaluation: no leaked test data inflating your benchmark numbers.
Watch outOver-dedup is also a bug

Aggressive thresholds delete legitimately distinct documents — the same legal clause in 500 contracts, or a common idioms list. Always eyeball a random sample of what your filter removed before you trust it.

NoteNext up

Your corpus is clean. Now it has to become integers. Stage 5 introduces Byte-Pair Encoding, the tokenizer trick that every modern LLM depends on.

Knowledge check: Which of these is NOT a reason to deduplicate a training corpus?

  • a. Reducing verbatim memorisation
  • b. Removing leaked test examples
  • c. Increasing the number of unique parameters in the model← correct

Deduplication changes the data, never the model size. Parameter count is an architecture decision.