# CS336 Lecture 13: Data I ## Section 1: Why Data Differentiates Language Models and the Volume–Quality Pipeline Every earlier part of building a language model assumes that a clean stream of training tokens already exists on disk. Once architectures, optimizers, and distributed training recipes become broadly understood and widely published, a much harder engineering problem emerges: what data should a model actually train on, and how do you construct a dataset large enough and clean enough to train a competitive model? A striking pattern across open-weight model releases exposes where the true technical moat lies. Consider the historical open-weight release of Llama 3 (July 2024): its technical report published the complete neural network architecture, hyperparameter choices, and training recipe in full detail, yet disclosed almost nothing about the exact training data sources, filtering criteria, or domain mixture ratios. This disclosure asymmetry is not accidental. Frontier laboratories keep their data pipelines secret for two concrete reasons: 1. **Competitive dynamics**: Data curation pipelines directly govern downstream model quality. Two models with identical architectures and compute budgets can diverge sharply in capability depending on how their training corpora were extracted, cleaned, deduplicated, and mixed. 2. **Copyright liability**: Publicly disclosing every source ingested into a training corpus exposes the organization to copyright litigation, a legal constraint we will analyze in full in Section 3. The nature of data engineering has also transformed fundamentally rather than shrinking. In the pre-foundation era of supervised machine learning, data work meant hiring human annotators to label individual examples for narrow tasks. In the foundation-model era, manual per-example labeling plays a much smaller role at the base level; instead, data engineering has exploded into massive-scale **curation, extraction, filtering, and deduplication**. Unlike a neural network architecture—which can be written down precisely in a handful of linear-algebraic equations—data is a **long-tail problem** that scales directly with sustained human engineering effort. Every weird formatting artifact, spam farm, broken character encoding, or boilerplate header on the web represents another edge case that silently degrades the training distribution unless someone inspects the data and engineers a remedy. Because raw text on the internet is never ready for gradient descent, every training corpus is built by pushing raw sources through a five-stage engineering pipeline. Visualize this pipeline left to right as five connected boxes linked by forward arrows: - **Stage 1 — Live Services** (e.g., the public World Wide Web, GitHub, arXiv): dynamic, continuously changing servers where human-authored text and code actually reside. - **Stage 2 — Raw Snapshots** (e.g., WARC web archives, XML dumps, `git` repositories): static, offline copies captured at a point in time so processing is reproducible and does not hammer live infrastructure. - **Stage 3 — Extraction** (HTML or PDF converted to plain text): stripping markup, navigation bars, page headers, and binary wrappers to recover the underlying prose or source code. - **Stage 4 — Filter & Deduplicate** (heuristic rules and learned classifiers): discarding boilerplate, gibberish, unwanted languages, toxic spam, and repeated copies of identical or near-identical text. - **Stage 5 — Data Mixture** (Pre-training, Mid-training, and Post-training blends): combining cleaned domain sources in carefully tuned proportions matched to each stage of model training. Stages 1 and 2 govern access, crawling, and copyright; Stages 3 through 5 govern major source curation and the evolution of modern datasets, bridging into the algorithmic filtering and deduplication methods covered in the next lecture (Data II). Once cleaned corpora exist, modern training does not feed all data into the model uniformly from step zero to the end. Instead, training follows a **volume–quality funnel**. Imagine an inverted trapezoid divided into three stacked horizontal bands narrowing from top to bottom, accompanied by an axis pointing right labeled *Less volume · Higher quality & specificity*: - **Band 1 (widest, top) — Pre-training**: Massive volume of broad raw web pages and general text, spanning roughly $15\text{T}$ to $45\text{T}$ tokens in recent and late-2026 systems. This stage builds broad world knowledge and linguistic fluency. - **Band 2 (middle, narrower) — Mid-training**: Curated, higher-quality text heavily enriched with mathematics, code, and structured reasoning material. An open, fully documented example is the **Dolmino** mid-training mix used in AI2's OLMo 2 (2025). - **Band 3 (narrowest, bottom) — Post-training**: Targeted conversational, reinforcement learning, and distillation data designed to shape instruction following and reasoning behavior. Examples include AI2's **Tülu** post-training suite, **RLVR** (Reinforcement Learning with Verifiable Rewards), and **MOPD** (Multi-Teacher On-Policy Distillation). ::: definition A **base model** is a language model that has completed pre-training and mid-training, learning broad next-token prediction over massive text and curated domain corpora without yet being tuned for conversational instruction following. An **instruct (or chat) model** is produced by applying post-training to a base model so that it responds directly to user prompts and tasks. ::: Although stage boundaries are blurry in practice—some labs blend mid-training smoothly into the late annealing phase of pre-training—every modern recipe moves along this funnel from broad, noisy volume to narrow, high-specificity supervision. Increasingly, laboratories release only the final instruct model rather than the underlying base checkpoint; for instance, the early-2026 model Qwen3.5-397B-A17B was released solely as an instruct model. By contrast, AI2's OLMo 2 (2025) remains a rare open full-pipeline reference that documents pre-training, mid-training (Dolmino), and post-training (Tülu) end to end. At the late-2026 frontier, post-training itself has grown into multi-step pipelines: DeepSeek-V4.1-Flash (Sept 2026) trains via supervised fine-tuning (SFT), followed by asynchronous reinforcement learning, followed by on-policy distillation from more than 40 teacher models; Nemotron 3.5 (Oct 2026) progresses through SFT, RLVR, expert teacher models, and MOPD. ::: misconception You might think that because post-training and mid-training determine a model's chat polish and benchmark-specific reasoning, pre-training volume no longer matters as long as you have a small, pristine dataset. That breaks because pre-training token budgets have grown relentlessly alongside model capability: without tens of trillions of broad tokens in Stage 1, the model lacks the factual breadth, syntactic robustness, and cross-domain representations that mid-training and post-training merely refine and elicit. ::: To see how dramatically the scale of Stage 1 has shifted, inspect the horizontal bar chart of pre-training token budgets from 2020 through late 2026. The horizontal axis spans from $0\text{T}$ to $50\text{T}$ tokens in $10\text{T}$ grid increments, and five horizontal bars are stacked vertically from top (oldest) to bottom (newest): - **GPT-3 (2020, historical)**: $0.4\text{T}$ ($400\text{B}$) tokens — a tiny sliver barely extending past the $0\text{T}$ axis. - **LLaMA (2023, historical)**: $1.2\text{T}$ tokens — still less than one-eighth of the first $10\text{T}$ grid interval. - **Llama 3 (July 2024, historical)**: $15\text{T}$ tokens — jumping past the $10\text{T}$ line halfway to $20\text{T}$. - **Qwen3 (May 2025, earlier)**: $36\text{T}$ tokens — extending more than halfway between $30\text{T}$ and $40\text{T}$. - **DeepSeek-V4.1-Flash (Sept 2026, current frontier)**: $45\text{T}$ tokens — reaching halfway between $40\text{T}$ and $50\text{T}$. We quantify the multiplicative growth in pre-training token budget between two eras using the simple budget ratio: $$R = \frac{T_{\text{target}}}{T_{\text{baseline}}}$$ Here, $T_{\text{baseline}}$ denotes the total pre-training token count of an earlier reference model, $T_{\text{target}}$ denotes the total pre-training token count of a later model, and $R$ gives the dimensionless scaling factor by which the corpus had to expand. As a single conceptual unit, $R$ tells us how many times larger the data supply chain must become to feed modern training runs without endlessly repeating identical text. ::: example Compute the pre-training token scaling factor $R$ from the historical baseline GPT-3 (2020) to the late-2026 frontier model DeepSeek-V4.1-Flash (Sept 2026), and compare it to the jump from Llama 3 (July 2024) to DeepSeek-V4.1-Flash. 1. Identify the token counts from the bar chart: - $T_{\text{GPT-3}} = 0.4\text{T}$ tokens - $T_{\text{Llama 3}} = 15\text{T}$ tokens - $T_{\text{DeepSeek-V4.1-Flash}} = 45\text{T}$ tokens 2. Compute the six-year scaling factor (2020 to 2026): $$R_{2020 \to 2026} = \frac{45\text{T}}{0.4\text{T}} = 112.5\times$$ 3. Compute the two-year scaling factor (2024 to 2026): $$R_{2024 \to 2026} = \frac{45\text{T}}{15\text{T}} = 3.0\times$$ **Interpretation**: In six years, pre-training data budgets expanded by more than two orders of magnitude ($112.5\times$), and even in the two years between Llama 3 and late 2026, token demand tripled. Curated human-edited sources like Wikipedia or digitized public-domain books amount to mere tens of billions of tokens—orders of magnitude too small to fill a $15\text{T}$ to $45\text{T}$ token budget. Web crawl extraction, automated quality filtering, and synthetic data generation are therefore not optional enhancements; they are mathematically mandatory to reach modern scale. ::: ::: keyidea Data engineering—not just model architecture—is the primary differentiator of modern language models, because training progresses through a volume–quality funnel whose pre-training stage now demands $15\text{T}$ to $45\text{T}$ tokens (over $100\times$ the GPT-3 budget), far exceeding what small hand-curated sources can supply. ::: Because hand-curated encyclopedias and books cannot come close to supplying tens of trillions of tokens, engineers are forced to gather text from the open web. That immediately raises a practical systems problem: the web is not a static file sitting on a hard drive waiting to be copied. Understanding what you can—and cannot—actually collect from live web servers is our next step. ### ✎ Check Your Understanding 1. **Quick computation**: If a historical model trained on $1.2\text{T}$ tokens (LLaMA, 2023) and a late-2026 frontier model trains on $45\text{T}$ tokens (DeepSeek-V4.1-Flash, Sept 2026), by what factor did the pre-training token budget increase? Answer: It increased by $\frac{45\text{T}}{1.2\text{T}} = 37.5\times$, using the token budget ratio $R = T_{\text{target}} / T_{\text{baseline}}$. 2. **Yes/No with justification**: Are competitive secrecy and copyright liability the only reasons open-weight models like Llama 3 (2024) withhold their data mixtures, or is it because data pipelines are trivial to describe in a few equations like model architectures? Answer: No, data pipelines are not trivial to specify in a few equations; data is a long-tail problem that scales with human engineering effort, and labs withhold their curation mixtures specifically due to competitive dynamics (curation governs model quality) and copyright liability (disclosing sources invites litigation). --- ## Section 2: From Live Web Services to Static Snapshots — Crawling, Access Barriers, and Shadow Libraries Popular descriptions routinely claim that large language models are "trained on the entire internet." That statement is factually false on two levels. First, the "internet" includes private emails, encrypted messaging, internal corporate networks, and non-web protocols; language models only ever touch a filtered slice of the **public World Wide Web**. Second, even the public web is not a single downloadable archive. It is a distributed network of **live servers** that generate responses on demand whenever a client sends an HTTP request. To see the gap between a live web service and a training token, consider what happens when you issue a single command-line request to a course webpage: ```bash $ curl https://cs336.stanford.edu/ ...

CS336: Language Modeling from Scratch

... ``` The server returns an HTML document wrapped in markup tags, not clean prose, and it only returns the single page you explicitly asked for. You cannot run a training loop directly against live HTTP servers—network latency, server crashes, rate limits, and changing content would make training slow, irreproducible, and destructive to the host sites. Instead, Stage 1 to Stage 2 of our pipeline requires a **web crawler** to convert live servers into static archive snapshots for offline processing. ::: definition A **web crawler** is an automated program that begins from a **seed set** of initial URLs, downloads each corresponding webpage, parses outgoing hyperlinks embedded in the downloaded HTML, enqueues newly discovered URLs to visit next, and stores the fetched responses as static archive snapshots for offline processing. ::: Even with a well-engineered crawler, large fractions of human-written text on the web remain completely unreachable before any copyright lawyer even enters the room. Three distinct technical barriers wall off huge portions of the web: 1. **Dynamic web applications**: Many modern platforms do not serve static HTML documents tied to unique URLs. Content loads interactively via JavaScript only when a user clicks buttons, scrolls infinitely, or submits forms, often without the URL changing at all. Platforms such as Discord and Weights & Biases hold vast technical discussions and logs that a standard HTTP crawler never sees. 2. **Authentication and paywalls**: Enormous volumes of contemporary journalism, social discourse, and professional writing sit behind user accounts and paid subscriptions. Examples include Facebook, X, LinkedIn, and *The New York Times*. A crawler without credentials hits a login screen or a paywall banner instead of the article text. 3. **Technical bot defenses**: Site operators actively control or block automated access using multiple layers: - **`robots.txt` exclusion rules**: A plain-text file placed at the root of a website specifying which automated user agents are permitted or forbidden from crawling which paths. For example, a site operator can explicitly exclude OpenAI's crawler and Common Crawl's crawler with the directives: ```text # Example robots.txt directives User-agent: GPTBot Disallow: / User-agent: CCBot Disallow: / ``` Crucially, `robots.txt` is a **voluntary protocol**—a polite crawler checks and obeys it, whereas an adversarial scraper can technically ignore it. - **Active bot detection and CAPTCHAs**: Infrastructure providers such as Cloudflare inspect request fingerprints, throttle suspicious traffic, and serve interactive challenges designed to block automated clients. - **IP/country blocks and strict rate limits**: Servers reject requests originating from cloud data-center IP ranges or cap requests per second per client. ::: misconception You might think that if a webpage loads publicly in your browser without a login screen and has no `robots.txt` block, you are automatically free to scrape and train a model on it. That breaks for two independent reasons: first, a site's **Terms of Service (ToS)** frequently prohibit automated scraping or bots as a binding contractual condition; second, the technical ability to download a public webpage does not grant a legal **license** to copy that text into a training corpus. ::: Over the past several years, publishers have reacted aggressively to large-scale AI scraping, producing a documented **decline of consent**. A 2024 empirical audit examined `robots.txt` directives and Terms of Service restrictions for the exact URLs contained inside three major open pre-training datasets—C4, RefinedWeb, and Dolma—and tracked how those permissions changed over time. The audit found that website opt-outs and explicit AI-crawler bans have risen steadily, shrinking the fraction of high-value web domains willing to allow automated collection. Ignoring these boundaries is not merely a legal risk; it causes immediate operational damage. Poorly behaved crawlers that ignore `robots.txt` and bypass rate limits hammer origin servers with floods of automated traffic, degrading live services for real human users and imposing substantial bandwidth and compute costs directly on site operators. ::: example Suppose a small independent technical blog hosts 50,000 articles and places `User-agent: CCBot` / `Disallow: /` in its `robots.txt`, along with a server capacity of 20 requests per second before page load times spike for readers. Compare two crawlers attempting to index the site: 1. **Polite crawler**: Fetches `https://blog.example/robots.txt` first, sees `Disallow: /` for its user agent, and skips all 50,000 URLs (0 article requests sent). Even if crawling were allowed, it enforces a rate limit (e.g., 1 request every 2 seconds), taking $100{,}000\text{ s} \approx 27.8\text{ hours}$ while consuming only $2.5\%$ of server capacity. 2. **Aggressive, non-compliant scraper**: Ignores `robots.txt` and fires 100 concurrent requests per second across distributed IPs to finish in $500\text{ s}$ ($8.3\text{ minutes}$). Because $100 > 20$ requests/second, the blog's origin server saturates, legitimate human visitors experience timeouts, and the operator's cloud egress bill spikes—prompting the operator to deploy Cloudflare bot blocking and IP bans that permanently cut off future researchers as well. **Interpretation**: Crawler etiquette is both an operational engineering requirement and a commons-preservation problem; aggressive scraping accelerates the exact technical and contractual lock-down documented in the 2024 consent audit. ::: At the opposite extreme from polite web crawling sit **shadow libraries**—repositories that are technically reachable on the public web, yet explicitly operate outside copyright law and publisher paywalls. Prominent examples include **Library Genesis (LibGen)**, **Z-Library**, **Anna's Archive**, and **Sci-Hub**. Their scale is immense: literature estimates cite roughly $4\text{M}$ books in LibGen (as of 2019) and approximately $88\text{M}$ academic papers in Sci-Hub (as of 2022). ::: definition A **shadow library** is a publicly accessible online archive that aggregates and distributes copyrighted books, journals, or academic articles in circumvention of commercial paywalls and copyright restrictions. ::: Shadow libraries exist in a continuous cat-and-mouse struggle between enforcement and circumvention. Because they bypass commercial academic publishers such as Elsevier, they are routinely targeted by takedown orders, civil lawsuits, and national DNS or ISP blocks; yet decentralized mirrors quickly reappear across different legal jurisdictions. While an ongoing ethical debate surrounds them—advocates argue that publicly funded scientific knowledge should be freely accessible to everyone—their legal status is unambiguous: **downloading works from shadow libraries constitutes piracy and copyright infringement**. We will need this exact distinction between *how a copy was acquired* and *how a model trained on it* when we examine landmark 2025 copyright rulings in Section 3. ::: keyidea Language models are never trained on "the entire internet"; dynamic JavaScript apps, paywalls, bot defenses, Terms of Service, and rising `robots.txt` opt-outs hide vast regions of human text from web crawlers, while bypassing paywalls through shadow libraries crosses directly into illegal piracy. ::: We have now seen that between a live webpage and a training token stand technical walls, voluntary protocols, contractual Terms of Service, and the shadow-library divide. Even when a crawler obeys `robots.txt` and downloads an openly reachable webpage, a deeper question immediately confronts every dataset builder: who owns the words on that page, and under what legal authority can you copy them into a training dataset? That brings us directly to copyright law. ### ✎ Check Your Understanding 1. **Fill-in-the-blank**: A web crawler starts from a __________ of URLs, downloads each page, extracts outgoing hyperlinks into a queue, and checks a site's __________ file—a voluntary protocol—to see which paths automated user agents are asked to avoid. Answer: **seed set**; **`robots.txt`**. 2. **What would happen if...**: What happens to a standard HTTP crawler that tries to harvest discussions from an interactive web application like Discord or articles behind *The New York Times* paywall? Answer: On Discord, content loads dynamically via JavaScript interactions without static URLs, so the crawler cannot retrieve it; on *The New York Times*, authentication and paywall barriers block access, returning a login or paywall wall instead of the article text. --- ## Section 3: Copyright Law, Licensing, and Fair Use for Language Model Training Suppose a polite crawler respects `robots.txt`, stays within rate limits, and saves millions of publicly accessible web pages onto disk. Before a single gradient step is computed, every dataset builder faces a legal reality: **intellectual property (IP)** law governs who may copy and reuse creative work. IP law exists to incentivize the creation of intellectual goods and spans four distinct legal regimes: **copyright** (creative expression), **patents** (inventions), **trademarks** (brand identifiers), and **trade secrets** (confidential business know-how). For text, code, images, and audio corpora, copyright is the controlling regime. Modern copyright traces back to the Statute of Anne (1709, England) and is codified in the United States by the **Copyright Act of 1976**. Under this statute, copyright protects *"original works of authorship fixed in any tangible medium of expression."* Notice how drastically the 1976 Act broadened protection compared to the earlier 1909 Act, which applied only to *published* works. Fixing words onto a hard drive, a blog post, a forum reply, or a source-code file is sufficient. Three structural rules define what copyright covers and how long it lasts: 1. **Expression, not ideas**: Copyright protects the specific creative *expression* of an idea, never the underlying *idea* itself. For example, a particular implementation of the quicksort sorting routine written in a specific way is copyrighted expression, whereas the quicksort algorithm itself—partitioning around a pivot and recursing—is an unprotected idea. Similarly, bare factual collections such as an alphabetical telephone directory are unprotected unless the selection or arrangement itself exhibits creativity. 2. **Automatic creation with a tiny threshold**: Unlike patents—which require an expensive application and examination—copyright attaches automatically the instant an original work is fixed in a tangible medium. No notice or registration is required to hold a copyright; your personal website, class notes, and public forum comments are all automatically copyrighted. Registration (which costs $\$65$ in the US) is only required as a procedural prerequisite before the owner can file an infringement lawsuit in court. 3. **Long duration before entering the public domain**: For an individual author, copyright lasts for the **author's life plus 70 years**. For corporate **works made for hire**, it lasts **95 years from publication**. Only after that term expires does a work enter the **public domain**, where anyone may freely copy and use it—examples include the plays of Shakespeare, the compositions of Beethoven, and most books in Project Gutenberg. The practical consequence for data engineering is stark: **basically everything on the Internet is copyrighted.** ::: misconception You might think that because a blog post, Reddit comment, or snippet on a personal website has no copyright symbol (`©`), was never formally registered, and is readable for free online, it belongs to the public domain. That breaks because under the US Copyright Act of 1976, copyright attaches automatically upon fixation with a minimal creativity threshold; lack of registration only delays a lawsuit (which requires a $\$65$ registration), and public readability never surrenders copyright. ::: Given that nearly all web text is copyrighted, there are only **two legal paths** to use a copyrighted work in a training dataset: **(1) obtain a license**, or **(2) rely on fair use**. ### Path 1: Licenses and the Terms of Service Trap ::: definition A **license** is an instrument of contract law through which a copyright holder (the **licensor**) grants explicit permission to another party (the **licensee**) to use a work under specified conditions—effectively functioning as "a promise not to sue" so long as the licensee obeys those terms. ::: Licenses come in two major flavors relevant to pre-training corpora: - **Open public licenses (Creative Commons)**: Created by Lawrence Lessig and Eric Eldred in 2001 to bridge the rigid gap between full all-rights-reserved copyright and the public domain. Creative Commons licenses underpin massive open knowledge repositories, including Wikipedia, MIT OpenCourseWare, Khan Academy, and the Free Music Archive, as well as roughly $307\text{M}$ Flickr images, $39\text{M}$ MusicBrainz items, and $10\text{M}$ YouTube videos. - **Commercial training deals**: Bilateral contracts negotiated directly between AI laboratories and major content platforms. Documented examples include licensing agreements between **Google and Reddit**, **OpenAI and Shutterstock**, and **OpenAI and StackExchange**. However, holding a copyright license to an item does not override platform contracts. This creates the **Terms of Service (ToS) trap**: a website's ToS can impose contractual bans on downloading or scraping *even over content that is openly licensed or would qualify for fair use*. For example, YouTube hosts $10\text{M}$ Creative Commons-licensed videos, yet YouTube's Terms of Service explicitly prohibit automated downloading of videos from the platform. Violating the ToS breaches a contract with the host platform independently of whether the underlying author granted a Creative Commons license. ### Path 2: Fair Use (17 U.S.C. § 107) Because negotiating individual licenses with millions of web authors is practically impossible at multi-trillion-token scale, most web-scale language model training has relied on the statutory doctrine of **fair use**, codified in **17 U.S.C. § 107**. ::: definition **Fair use** (17 U.S.C. § 107) is a legal doctrine in US copyright law that permits limited unlicensed use of copyrighted material based on a holistic balancing of four statutory factors: purpose and character of the use, nature of the copyrighted work, amount and substantiality used, and effect on the market for the original work. ::: Courts do not apply fair use as a rigid checklist; they weigh all four factors together: | Statutory Factor | What Favors Fair Use | | :--- | :--- | | **1. Purpose & character of the use** | Educational or non-commercial over commercial; **transformative** (creating a new purpose, meaning, or message) over merely reproductive | | **2. Nature of the copyrighted work** | Factual / non-creative works over highly fictional / creative works | | **3. Amount & substantiality used** | Copying a small, non-essential snippet over copying the entire work or its creative heart | | **4. Market effect** | The new use does not harm the existing or potential market for the original work | Classic examples illustrate how courts balance these four factors. Watching a commercial movie and writing a critical summary of it is transformative and does not substitute for buying a ticket. Studying copyrighted source code to understand an algorithm and then cleanly reimplementing the algorithm from scratch uses only the unprotected idea rather than the copyrighted expression. Most relevant to large-scale data ingestion is the landmark **Google Books** case (*Authors Guild v. Google* — filed 2005, decided 2013, and affirmed on appeal in 2015): Google scanned millions of entire copyrighted library books (Factor 3 weighed heavily against it on volume alone), yet courts ruled the project fair use because building a full-text search index that displayed only short snippets was highly transformative (Factor 1) and did not act as a market substitute for purchasing the books (Factor 4). Applying fair use to language model training exposes four deep legal and technical tensions. First, remember that **copyright governs semantics and economics, not merely verbatim byte-for-byte copying**: distinctive fictional plots and characters (such as *Harry Potter*) can be protected even without exact word-for-word quotations, whereas parody—imitating a work specifically to critique or mock it—is often protected as fair use. Against that backdrop, training a language model creates four competing pulls across the statutory factors: 1. **Copying**: Simply downloading and storing web pages or books onto training clusters (Stage 2 of our pipeline) already creates a complete reproduction of the original works, putting immediate pressure on Factor 3. 2. **Transformativeness**: Training does not aim to redistribute copies of the dataset; it optimizes parameters to learn general statistical patterns of language—far closer to transformative indexing than copy-pasting (supporting Factor 1). 3. **Idea vs. expression**: Ideally, a language model extracts general concepts and linguistic structure (learning what *wizards* are in fantasy literature) rather than reproducing specific protected expression (generating *Harry Potter* chapters). Memorization blurs that boundary. 4. **Market impact**: Even if a model never emits a single verbatim sentence from a training book or news article, a highly capable language model can compete economically with human writers, journalists, and artists, placing acute pressure on Factor 4. ::: example Evaluate a hypothetical scenario through the four statutory factors of 17 U.S.C. § 107: an AI lab downloads 100,000 contemporary novels from a shadow library, trains a commercial fiction-writing language model on the full text of every novel, and deploys a paid service that generates new novels in the same genres. 1. **Factor 1 (Purpose & character)**: The use is commercial, which leans against fair use, though learning statistical language weights is arguably transformative—*except* that acquiring pirated copies in bad faith undermines the character of the use. 2. **Factor 2 (Nature of the work)**: Contemporary novels are highly creative fictional works, sitting at the core of copyright protection (weighs against fair use). 3. **Factor 3 (Amount & substantiality)**: The lab copied $100\%$ of every novel to ingest it into the training pipeline (weighs against fair use unless justified as necessary for a transformative purpose). 4. **Factor 4 (Market effect)**: A commercial fiction generator directly competes in the market for contemporary novels and also deprives publishers of potential licensing revenue for training copies (weighs against fair use). **Interpretation**: Even if a court accepts that statistical training itself is transformative under Factor 1, the combination of pirated acquisition, highly creative source works, full-work copying, and direct market competition creates severe legal liability. ::: Exactly these tensions have played out in three landmark AI copyright lawsuits between 2023 and 2025: | Case | Allegation | Key Rulings & Outcomes | | :--- | :--- | :--- | | **NYT v. OpenAI** (2023) | Training on and reproducing *New York Times* articles | Active litigation contesting both the unauthorized training copies and memorized or near-verbatim model outputs | | **Bartz et al. v. Anthropic** (2024 → 2025) | Pirating millions of books from shadow libraries and training on plaintiffs' books | Summary judgment (2025) drew a sharp line: **training itself = fair use**, and **buying and physically scanning books = fair use**, but **pirating copies = NOT fair use**. Outcome: Anthropic paid **$\$1.5\text{B}$** to settle with authors. | | **Kadrey et al. v. Meta** (Summary judgment 2025) | Training on plaintiffs' books (sources revealed in the original LLaMA paper) | Summary judgment (2025): **training on books (in this instance) = fair use**; however, the allegation regarding peer-to-peer **torrenting** of pirated copies remained pending. | Look closely at the pattern across *Bartz v. Anthropic* and *Kadrey v. Meta*. Courts separated the **statistical transformation of training** from the **method of data acquisition**. While specific summary-judgment rulings in 2025 found that training itself qualified as fair use in those particular records, the legal question is not yet settled broadly across all jurisdictions or all market-harm arguments (as ongoing litigation like *NYT v. OpenAI* demonstrates). By contrast, one rule is already crystal clear and extraordinarily expensive to violate: **pirating source copies via shadow libraries or torrents is illegal copyright infringement**, even if the subsequent model training is transformative. We will return to the practical question of whether one can bypass fair-use uncertainty altogether by training solely on permissively licensed data in Section 10. ::: keyidea Under the US Copyright Act of 1976, virtually everything on the web is automatically copyrighted, leaving only licensing or four-factor fair use (17 U.S.C. § 107) as legal paths; landmark 2025 rulings indicate that while training itself can qualify as fair use in specific cases, acquiring pirated copies from shadow libraries is unambiguously illegal. ::: With the access barriers and legal ground rules established, we can now examine the actual raw data sources that feed modern pre-training corpora. Because web crawls supply the bulk of the $15\text{T}$ to $45\text{T}$ tokens required today, we start with the foundational open web archive: Common Crawl, and the surprisingly decisive engineering problem of turning raw HTML into clean text. ### ✎ Check Your Understanding 1. **Yes/No with justification**: In *Bartz et al. v. Anthropic* (2025), did the summary judgment ruling that model training was fair use shield Anthropic from liability for using pirated book copies? Answer: No. The court ruled that training itself and buying-and-scanning books were fair use, but pirating copies was explicitly *not* fair use, and Anthropic paid $\$1.5\text{B}$ to settle with authors. 2. **What would happen if...**: You write a script to download Creative Commons-licensed videos directly from YouTube to transcribe them for a dataset. Which legal barrier do you still violate even though the video creators attached an open license? Answer: You violate YouTube's **Terms of Service (ToS)**—a binding contract with the hosting platform that prohibits downloading videos regardless of whether the underlying content is CC-licensed. --- ## Section 4: Common Crawl and the Engineering of HTML-to-Text Extraction If every AI research group had to run its own global web crawler from scratch, replicating the infrastructure to fetch billions of pages politely every month would consume massive engineering budgets before any language modeling research even began. That bottleneck motivated **Common Crawl**, a non-profit organization founded in 2007 that crawls the public web on a roughly monthly cadence and publishes raw archive snapshots openly for anyone to process. Common Crawl's scale makes it the default raw backbone of nearly every modern open web corpus. Each monthly crawl adds roughly **$3\text{B}$ to $5\text{B}$ pages**, intentionally incorporating some overlap with prior crawls while diversifying across new domains. Across its lifetime, Common Crawl has archived roughly **$300\text{B}$ pages**—for context, the live web contains $O(\text{billions})$ of reachable URLs, while Google's commercial search index exceeds $100\text{ PB}$. To ground this in a concrete recent snapshot, the **April 2026** Common Crawl release alone captured **$2.19\text{B}$ pages totaling $372.2\text{ TB}$**. Common Crawl gathers these snapshots using **Apache Nutch**, an open-source distributed crawler architecture. Visualize the Apache Nutch crawl loop as four stacked rectangular modules connected vertically by downward arrows, with a feedback loop running up the left margin from the bottom module back into the top module: 1. **URL Frontier / Queue (top)**: Initialized with a massive seed set of hundreds of millions of URLs waiting to be visited. 2. **Fetcher — Politeness (second)**: Pulls URLs from the frontier and fetches pages over HTTP while enforcing `robots.txt` exclusions and per-host rate limits so origin servers are not overloaded. 3. **Archive — WARC / WET (third)**: Writes each downloaded response permanently to disk in two formats: raw HTTP responses (WARC) and pre-extracted plain text (WET). 4. **Parse & Select Links (bottom)**: Extracts outgoing hyperlinks from the downloaded HTML, applies **selection** and **re-visit** policies to decide which pages matter and how frequently changing sites should be refreshed, and routes newly selected URLs along the left feedback arrow labeled *enqueue new URLs* back into the URL Frontier. Running this loop reliably at web scale hinges on three core crawler policies—**selection** (which pages among billions are worth fetching?), **politeness** (obeying `robots.txt` and pacing requests per host), and **re-visit** (how often should dynamic news pages versus static archives be re-fetched?)—plus a subtle web-engineering hazard: **dynamic URLs** (for instance, session IDs, tracking parameters, or calendar widgets) can map thousands of syntactically distinct URLs to identical underlying page content, trapping naive crawlers in redundant loops and inflating duplicate volume. Once Common Crawl writes a crawl snapshot to storage, Stage 3 of our pipeline—**HTML-to-text extraction**—begins. Common Crawl publishes every crawl in two primary file formats, and choosing between them has an outsized effect on final language model accuracy. ::: definition **WARC** (Web ARChive) files store the complete raw HTTP response and full HTML Document Object Model (DOM) structure exactly as returned by the web server. **WET** (WARC Encapsulated Text) files store a pre-converted, plain-text version produced by Common Crawl's generic text stripper, discarding the underlying HTML structure. ::: Trace the two-branch extraction diagram starting from a single box on the left labeled **Common Crawl — Raw HTTP response**: - **Upper path (WARC)**: Arrows flow from Raw HTTP response into **WARC (HTML) — Full DOM structure**, then into a **Custom Extractor** (`trafilatura`, `resiliparse`, or `jusText`), and finally into **Cleaner Text — Higher LM accuracy**. - **Lower path (WET)**: Arrows flow downward from Raw HTTP response into **WET (Plain Text) — Lossy pre-conversion**, bypassing custom DOM-aware extraction entirely via a dashed red line straight into **Noisy Text — Nav menus, lossy**. Why does discarding the DOM structure in WET hurt so badly? Look at a minimal three-line HTML page: ```html

Actual article body...

``` In the raw WARC file, semantic HTML tags (`