Unit 2 of 11 · about 4 hours · implement
WARC and HTML text extraction with document boundaries preserved
Extraction decides what text exists at all. Navigation text left in becomes repeated text that every later step must catch, and a document that loses its record id can no longer be traced to a source or deleted.
You'll be able to
- Implement text extraction from raw HTML bytes that tries UTF-8 first, falls back to a detected encoding, and records which route it took.
- Iterate the response records of a WARC file so that each record yields exactly one document that keeps its record id, URL and date.
- Compare full-page and main-content extraction on pages you have read, and say what each one removes, keeps and cannot recover.
Covers
Read
In this order, only the parts listed
0 of 5 done
- CS336 Assignment 4 handoutCS336 Assignment 4 - Data
Section 2.2, HTML to text conversion, and Problem (
extract_text) parts (a) and (b) (pp. 3 to 4), with the FastWARC noteRead Section 2.1 (WARC, WAT and WET) only for the definitions of the three formats.
- CS336 2026 Lecture 14: Data II (executable trace)CS336 2026 - Data Lectures 13 and 14
The
transformationstep: raw data is HTML, PDF or directories, HTML to text is lossy and needs linearizing, the rule-based tools, and why extraction accuracy matters - FineWeb (Penedo et al., 2024)FineWeb Paper and DataTrove Pipeline
Section 3.1 (experimental setup, for how each choice is ablated) and Section 3.2 (text extraction: WARC versus WET, Figure 1)
Stop after Section 3.2 here; Sections 3.3 and 3.4 belong to the filtering and deduplication units.
- DataComp-LM (Li et al., 2024)DataComp for Language Models
Section 4.2 'Text extraction' and Table 3 (resiliparse, trafilatura and the WET files compared at 1B-1x scale)
Optional second opinion on extraction. Read the scores as that paper's results on its own recipe; the authors report resiliparse as about 8 times faster than trafilatura at similar CORE.
- Resiliparse: HTML2Text and FastWARCResiliparse, fastText and datasketch on Four Documents
HTML2Text sections 'Basic Plain Text Conversion' and 'Main Content Extraction'; then the FastWARC page at https://resiliparse.chatnoir.eu/en/stable/man/fastwarc.html, sections 'Iterating WARC Files', 'Filtering Records', 'Record Properties' and 'Freezing Records' (page read 2026-10-16, Resiliparse and FastWARC 1.0.9)
Focus on
- A WARC file interleaves record types. Only
responserecords hold a page;request,warcinfoandmetadatarecords are not documents. Select the type when you open the iterator. - The document identity comes from the WARC header:
record_idis theWARC-Record-ID, and the target URI and date sit beside it. Write them next to the text at the moment you extract, because nothing later can recover them. - Extraction is lossy and a choice, not a fact. With
main_content=False(the default)extract_plain_textkeeps navigation and footer text; withmain_content=Trueit removes them, and it can also remove short real text such as list items and captions. FineWeb found WET text retained too much menu text and that extraction changed the trained model. - Bytes come first. Try UTF-8, fall back to
detect_encoding, and keep the encoding you used in the record, since a wrong guess produces plausible but damaged text.
Common mistakes · 3
- Passing the course test and believing boilerplate is gone. The fixture's expected text equals the default output (
main_content=False), and withmain_content=Trueit no longer matches, so the test checks decoding and plain-text conversion, not boilerplate removal. Measure that separately on pages you read. - Reading
record.reader.read()twice. The reader is a live stream, so the second call returns empty bytes; callfreeze()first if you need the payload again. - Storing documents as one text file and treating each line as a document. Extracted pages contain newlines, so the handout's tokenization starter, which adds the end-of-text token after every line, would insert document boundaries inside documents. Store one JSON object per document and tokenize each document as a unit.
Try it yourself
Closed-book, before checking anything
extract_records(warc_path) that opens the file with FastWARC, keeps only response records, decodes the body (UTF-8 first, then the detected encoding), calls extract_plain_text, and yields a dict with record_id, url, date, encoding and text. On a WARC you build with three response records and one request record, show that you get three documents and that record_id matches the header. Then run one page with main_content=False and True and write down one piece of text the second setting removed correctly and, if you can find one, one it removed wrongly.Quiz yourself
Answer first, then mark it. Missed ones go to Review.
0 got · 0 missed
1.A WARC file has 10 records: 1
warcinfo, 4requestand 5response. How many documents should extraction produce, and where does each one's id come from?AnswerFive, one per response record. The id is the
WARC-Record-IDheader of that record, read asrecord_idin FastWARC.2.Why can the same HTML give different training text under
main_content=Trueandmain_content=False, and which output is the better training data?AnswerThe default keeps navigation, footer and sign-in text, and the main-content setting removes it and can also remove short real text such as a list item. Neither is better in general: it depends on what the page is and on what the model is for, so decide by reading samples and by an ablation, as FineWeb did, not by assumption.
3.A page declares no charset and its bytes are Latin-1 text. What happens if you decode it as UTF-8 with
errors='replace', and what should the pipeline do instead?AnswerBytes above 127 usually fail as UTF-8 and become replacement characters, so accented letters are lost silently. Fall back to a detected encoding, keep the encoding you used in the record, and count how often the fallback runs.
4.Why is it a boundary bug to concatenate extracted documents into one file separated by blank lines?Answer
A blank line also occurs inside documents, so the original document boundaries cannot be recovered. Use an explicit record format with the id, or an end-of-document marker that cannot occur in the text, and test that the document count survives a write and read.
Practice
- CS336 Assignment 4:
extract_textProblem (
extract_text) in Section 2.2; connect your function torun_extract_text_from_html_bytesintests/adapters.pyand passtest_extract_text_from_html_bytesThe test compares your output with a stored extraction of one HTML page. Then do part (b) on the example WARC and its WET file. The section mini-project covers the record-preserving iterator from the reproduce step. Implement it in your own repository.
You're done when
Your extraction function passes test_extract_text_from_html_bytes, and your WARC iterator turns a file with mixed record types into one document per response record with the record id attached.
Only when you can do this without notes.
Leads to
- Language and domain identification, and irreversible normalization decisionsScore each extracted document for language and decide what text cleaning you can undo.
- Exact deduplication and MinHash near-deduplication thresholdsBoilerplate that survives extraction is the first thing deduplication has to find.
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 intests/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_13and?trace=lecture_14. Reconcile each lecture claim with your Assignment 4 implementation. - 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.pyin 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 passlanguagesyourself; 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 passmain_content=True), identify language with fastTextlid.176.binandpredict(text, k=1), and find near duplicates with datasketchMinHashLSH. Check every candidate against exact shingle Jaccard: atthreshold=0.9the index uses 5 bands x 25 rows, so it is a candidate filter, not a hard cutoff. - 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.
Also in this section
- 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.
- 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.mdanddocs/mixer.mdafter 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.
- 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.