Unit 5 of 11 · about 5 hours · derive, implement

Exact deduplication and MinHash near-deduplication thresholds

Duplicates waste training tokens, inflate memorization, and let evaluation text leak into training. MinHash lets you find near-duplicates without comparing every pair, but its parameters are easy to get wrong by a factor that the code never reports.

You'll be able to

  • Derive the probability that two documents with Jaccard similarity share a bucket, and the threshold where it rises, then choose and for a target similarity.
  • Implement exact line deduplication and MinHash-LSH document deduplication that verifies each candidate pair with exact Jaccard, clusters duplicates and keeps one document by a fixed rule.
  • State what the shingle size, the threshold and the scope of deduplication (per snapshot or global) trade, and keep a record of each duplicate cluster.

Covers

Stable exact document and line deduplicationMinHash, LSH and task-appropriate near-deduplication thresholds
1

Read

In this order, only the parts listed

0 of 5 done

  1. CS336 Assignment 4 handoutCS336 Assignment 4 - Data

    Section 3 introduction, Section 3.1 with Problem (exact_deduplication) (pp. 9 to 10), and Section 3.2 with Problem (minhash_deduplication): MinHashing, locality-sensitive hashing and clustering (pp. 10 to 12)

  2. CS336 2026 Lecture 14: Data II (executable trace)CS336 2026 - Data Lectures 13 and 14

    The deduplication step: the design space (item, match rule, action), hash_functions, exact_deduplication, jaccard_minhash and locality_sensitive_hashing

    In locality_sensitive_hashing the closing example sets n = 9000 with b = 20 and r = 450 and then reads a threshold of about 0.99 from it. That is not the setting of Lee et al.; see the first trap before you use those numbers.

  3. Deduplicating Training Data Makes Language Models Better (Lee et al., 2022)Deduplicating Training Data Makes Language Models Better (Lee et al., 2022)

    Section 4.2 (approximate matching with MinHash) and Appendix A (parameters), Section 5.1 and 5.3 (how much each dataset loses, and train-test leakage), Section 6.1 and 6.2 (perplexity and copied text)

    Skip the suffix-array material in Sections 4.1 and Appendix B; read only that exact-substring matching uses a 50-token threshold chosen for English web text.

  4. FineWeb (Penedo et al., 2024) and the DataTrove exampleFineWeb Paper and DataTrove Pipeline

    FineWeb paper (https://arxiv.org/abs/2406.17557v2) Section 3.4 with Figures 3 and 4: per-snapshot versus global MinHash; then examples/fineweb.py at the pinned commit, the MinhashConfig with 14 buckets of 8 hashes and word 5-grams

  5. datasketch: MinHash LSHResiliparse, fastText and datasketch on Four Documents

    'Retrieval characteristics and parameter tuning' and 'Common Issues with MinHash LSH' (page read 2026-10-16, datasketch 2.0.0)

2

Focus on

  • Fix three choices before you code: the item that is compared (line, paragraph, document or n-gram span), the match rule (exact, shared piece, fraction shared), and the action (drop all, keep one). Exact dedup is a hash of the normalized item; equal hashes are a candidate until the bytes are compared.
  • MinHash gives for one random hash. With hashes split into bands of rows, two documents collide if any band matches, which has probability . More rows per band raises the threshold, more bands lowers it.
  • LSH proposes candidates and does not decide. Check each candidate with exact Jaccard on the shingles, as the handout does, then cluster by connected components and keep one document per cluster by a fixed rule. Normalize only for the key (the handout lists lowercasing, punctuation, whitespace, accents and NFD) and keep the raw text and the cluster record.
  • The threshold is a modeling choice. Lee et al. use word 5-grams with a Jaccard test at 0.8 followed by an edit-similarity test at 0.8, Gopher uses 13-grams at 0.8, FineWeb uses 5-grams targeting about 75%, and FineWeb found that deduplicating each snapshot separately beat deduplicating all of them together.
Common mistakes · 3
  • Lee et al. name the parameters the other way round from the lecture and the handout. Their Section 4.2 writes with hashes per bucket and buckets, which is 450 bands of 20 rows. The lecture's code puts 20 bands of 450 rows through and gets a threshold near 0.99, where two documents at essentially never collide. Always check which variable counts bands and test the result against the target similarity.
  • Treating a library threshold as a hard cutoff. MinHashLSH(threshold=0.9, num_perm=128) in datasketch 2.0.0 picks 5 bands of 25 rows, and threshold=0.5 picks 25 bands of 5 rows, by balancing false positives and false negatives. It returns candidates; keep the exact Jaccard check.
  • Believing that more deduplication is always better. FineWeb's global MinHash removed up to 90% of the oldest snapshots and left worse text than it removed, and Lee et al. note that train and test duplicates must be handled on purpose (they kept the copy in the evaluation set).
3

Try it yourself

Closed-book, before checking anything

Derive and the threshold . Then compute, with 9000 hashes as Lee et al. arrange them (450 bands of 20 rows, their Appendix A), the threshold and at ; repeat for 20 bands of 450 rows as the lecture example reads them; and for 100 hashes in 10 bands (the first MinHash test in the handout) at . Expect a threshold of about 0.737 and ; a threshold of about 0.993 and about ; and .
4

Quiz yourself

Answer first, then mark it. Missed ones go to Review.

0 got · 0 missed

  1. 1.A 128-hash signature is split as 16 bands of 8 rows, or as 8 bands of 16 rows. Which setup has the lower threshold, and what does the lower threshold cost?Answer

    16 bands of 8 rows: its threshold is , against . The lower threshold raises recall and also produces more candidate pairs, so more exact checks and, if you skip them, more false positives.

  2. 2.With 10 bands of 10 rows, what is the chance that documents at collide, and at ?Answer

    At : . At : about 0.0097. That is small for one pair but not for a corpus: with a million documents there are about pairs, so even rare collisions give many candidates to verify.

  3. 3.Two different documents hash to the same value in exact deduplication, here with a 1-bit hash. What must the algorithm do?Answer

    Treat the hash only as a bucket key and compare the normalized text inside the bucket, keeping both documents when the texts differ. Dropping on a hash match alone silently deletes distinct documents.

  4. 4.FineWeb's globally deduplicated data trained a model barely better than the undeduplicated data. Name one reason the paper gives.Answer

    Global deduplication removed most of the older snapshots, and the part it kept was worse text (more ads and keyword lists) than the part it removed. Removing duplicates also removes the many repeats of good pages, so what remains need not be better. Per-snapshot deduplication gave the improvement.

5

Practice

  • CS336 Assignment 4: exact and MinHash deduplication

    Problems (exact_deduplication) and (minhash_deduplication); connect run_exact_line_deduplication and run_minhash_deduplication in tests/adapters.py and pass the three tests in tests/test_deduplication.py

    The fuzzy test uses two MIT license texts with 5-word shingles; compute their exact Jaccard yourself and compare it with the collision probability for 50 bands of 10 rows. Implement it in your own repository.

  • TensorTonic: Perform Stable Exact Deduplication and Build Deterministic MinHash Signatures

    cs336-l14-stable-exact-deduplication (https://www.tensortonic.com/problems/cs336-l14-stable-exact-deduplication) and cs336-l14-minhash-signatures

    Both are free. The first normalizes with NFKC and case folding and keeps unequal texts apart even under a 1-bit hash. The second hashes with SHA-256 of a seed and shingle, so its signatures will not match datasketch's. The public cases check these edge cases only, so keep your own tests beside each solution.

You're done when

You pass the three A4 deduplication tests, you can compute the collision probability and threshold for any and without notes, and you know how to tell which variable counts bands in a source.

Only when you can do this without notes.

Leads to

Notes

Resources · 5 for this unit, 16 more in the section
  • CS336 Assignment 4 - DataStanford University · primary

    Implement the handout functions in Sections 2.2 to 2.7 (extract_text, language_identification, the PII masks, the harmful-content classifiers, gopher_quality_filter, classify_quality) and Section 3 (exact_deduplication, minhash_deduplication) until the 21 tests in tests/ pass on CPU. The 8-GPU leaderboard run is out of reach: replace it with one small local training comparison on a filtered sample and keep the retained-token and source-mix tables as evidence.

  • CS336 2026 - Data Lectures 13 and 14Stanford University · required

    Step through the Lecture 13 trace (sources: WebText, Common Crawl, CCNet, C4, The Pile, MassiveText, RefinedWeb, Dolma, DCLM, Nemotron-CC, copyright) and the Lecture 14 trace (KenLM and fastText filters, importance resampling, Bloom filters, MinHash and LSH) at cs336.stanford.edu/lectures/?trace=lecture_13 and ?trace=lecture_14. Reconcile each lecture claim with your Assignment 4 implementation.

  • Deduplicating Training Data Makes Language Models Better (Lee et al., 2022)Google Research · required

    Read Section 4 (exact substring matching with suffix arrays, 50-token threshold justified in Appendix B, and MinHash near-duplicate removal) Section 5 (how much each dataset loses, including train-test overlap) and Section 6 (effects on perplexity and memorization). This is the method behind Assignment 4 Section 3; the 50-token threshold is tuned to English web text.

  • FineWeb Paper and DataTrove PipelineHugging Face · support

    Read FineWeb Section 3 (each extraction, filtering and per-snapshot MinHash decision ablated on small models) and trace examples/fineweb.py in DataTrove at commit 1977fbb (14 bands x 8 hashes = 112 hashes, 5-gram words). LanguageFilter() with no arguments keeps every language above 0.65, so pass languages yourself; the cluster script is a reference, not a local run.

  • Resiliparse, fastText and datasketch on Four DocumentsOpen source · support

    Build one CPU exercise: extract text with Resiliparse extract_plain_text (it keeps navigation unless you pass main_content=True), identify language with fastText lid.176.bin and predict(text, k=1), and find near duplicates with datasketch MinHashLSH. Check every candidate against exact shingle Jaccard: at threshold=0.9 the index uses 5 bands x 25 rows, so it is a candidate filter, not a hard cutoff.

Also in this section

  • Scaling Language Models: Methods, Analysis and Insights from Training Gopher, Appendix ADeepMind · support

    Read Appendix A.1 for the exact quality rules behind "Gopher-style" filters (50 to 100,000 words, mean word length 3 to 10, symbol ratios, bullet and ellipsis lines, the stop-word test) and A.5 for the datasheet. The rules are English-specific.

  • Dolma ToolkitAllen Institute for AI · required

    Read docs/data-format.md (stable source and id, attributes aligned row for row), docs/taggers.md, docs/deduplication.md and docs/mixer.md after your CS336 pipeline works. Its deduplication is a Bloom filter over document keys or paragraphs, with possible false positives, not MinHash; record which production concerns your smaller pipeline omits.

  • Dolma: an Open Corpus of Three Trillion Tokens for Language Model Pretraining Research (Soldaini et al., 2024)Allen Institute for AI · support

    Read Section 4.2 (data ablations) and Table 1 (the corpus card) as the template for your own data card. The token count depends on the tokenizer used to count.

  • Language Model Tokenizers Introduce Unfairness Between Languages (Petrov et al., 2023)University of Oxford · support

    Read Section 3 (tokenization parity and premium) and Sections 4 and 5 (premiums on FLORES-200, cost and context consequences), then measure the premium of your own tokenizer on a parallel slice.

  • Analysing the Impact of Sequence Composition on Language Model Pre-Training (Zhao et al., 2024)University of Edinburgh · support

    Read Section 2 (random, same-source and retrieval packing; causal versus intra-document masking) and Table 1 (perplexity for each strategy). It is the source for testing cross-document attention leakage in your packed batches.

  • Documenting Large Webtext Corpora: A Case Study on the Colossal Clean Crawled Corpus (Dodge et al., 2021)Allen Institute for AI · support

    Read Sections 3 to 5: what C4 contains, what its filters removed, and how the blocklist removed text from and about minority groups. Use it to audit the trade-offs of your own PII and harm filters; it audits, it does not propose a recipe.

  • Data Cards PlaybookGoogle Research · support

    Follow the guide steps and use the templates to write the card for your filtered corpus: sources, rights, filters with removal rates, known gaps and intended use.

  • Modern LLM Notebook - Data EngineeringWalking Labs · support

    Work through notebooks-en/part2-training/15-data-engineering.ipynb (extraction, quality filtering, deduplication, mixing). Reproduce its compact examples, then compare their assumptions with the stricter CS336 tests.

  • TensorTonic - Data Processing SetTensorTonic · support

    Solve Perform Stable Exact Deduplication (cs336-l14-stable-exact-deduplication), Build Deterministic MinHash Signatures (cs336-l14-minhash-signatures) and Compute Temperature-Based Data Mixtures (cs336-l14-temperature-data-mixture). Its MinHash uses SHA-256 of a seed and shingle, so outputs will not match datasketch. Public test cases check the listed edge cases, not gradients or the hidden grader, so keep your own tests beside each solution.

  • Tokenizer and Corpus PipelineRoadmap-Final · support

    Reuse the project correctness, lineage and contamination contracts. Extend the artifact instead of starting another tokenizer implementation.

  • DataComp for Language ModelsDataComp-LM Team · depth

    Read Section 4.4 and Table 4 (a fastText classifier keeping the top 10% of documents beat other filters), Figure 4 (removal at each stage) and the Section 3 compute table after the bounded data experiment. The repository dedups with a Bloom-filter tool (BFF), not MinHash, and CORE scores changed between v1 and v2, so never compare them directly.

  • Unicode Standard Annex #15: Unicode Normalization FormsUnicode Consortium · reference

    Read Sections 1.1 and 1.2: canonical versus compatibility equivalence, the four forms NFD, NFC, NFKD and NFKC, and why the compatibility forms can remove distinctions that matter. Use it to decide which form belongs to a matching key and which, if any, to stored text.

  • Tulu 3: Pushing Frontiers in Open Language Model Post-Training, Section 3.2Allen Institute for AI · support

    Read Section 3.2 'Prompt Decontamination' (p. 14 of arXiv:2411.15124v5): the comparison of full-string, n-gram and embedding matching, the 8-gram rule on prompts only, the 50% token-coverage test per instance and the 2% rule per dataset. Use it as a worked example of choosing the match unit and thresholds from the evaluation items.

  • FLORES-200 parallel sentencesMeta AI · support

    Use the devtest split (1,012 sentences, the same sentences in the same order for every language) to measure tokenizer premiums and per-language language-ID retention. The dataset card lists CC BY-SA 4.0 (page read 2026-10-16). The repository is archived and points to a successor; keep the original release for results you want to compare with Petrov et al.

  • Scaling Data-Constrained Language Models (Muennighoff et al., 2023)Hugging Face · support

    Read Section 3.1 (Equation 5, the effective-data term for repeated tokens), Section 6 with Figure 1 (return on compute when repeating data) and Appendix A (the derivation and the fitted constants). Use it to convert epochs into effective tokens and to see how far that fit reaches: models up to 9B parameters on C4 subsets.

  • Hugging Face Datasets: StreamHugging Face · reference

    Read Shard, Shuffle, Interleave, and Save a dataset checkpoint and resume iteration, including the tip that shuffle-buffer contents are lost when resuming. Use tiny local data and check resume by comparing document ids with an uninterrupted run; do not stream a web-scale corpus or upload to the Hub.