Stanford CS336: Language Modeling from Scratch Lecture 13 — Data I: Sources, Copyright & Pretraining Corpora

From Live Web Services to Curated Training Datasets
Stanford University · Late 2026

What Data Should We Train On?

Live Services Web, GitHub, arXiv Raw Snapshots WARC, dumps, git Extraction HTML/PDF → text Filter & Dedup Rules, classifiers Data Mixture Pre / Mid / Post Access, Crawling & Copyright (Today) Major Sources & Dataset Evolution (Today → Data II)

Today covers where data comes from, what is legal to use, and how pretraining corpora evolved from 2019 to 2026.

Why Data Is the Key Differentiator

Data is a long-tail problem that scales with human engineering effort — unlike model architectures, which can be specified in a few equations.

Training Stages: The Volume–Quality Funnel

1. Pre-training Huge volume, raw web & text (e.g., 15T–45T tokens) 2. Mid-training Curated HQ data, math, code (e.g., OLMo 2 Dolmino) 3. Post-training Chat, RL, distillation (e.g., Tülu / RLVR / MOPD) Less volume · Higher quality & specificity →
  • Base model: after pre-training + mid-training
  • Instruct / chat model: after post-training
    • Increasingly, labs release only instruct models (e.g., early-2026 Qwen3.5-397B-A17B)
  • Open full-pipeline reference: AI2's OLMo 2 (2025) documents pre-training, mid-training (Dolmino), and post-training (Tülu)
  • Late-2026 frontier post-training:
    • DeepSeek-V4.1-Flash (Sept 2026): SFT → async RL → on-policy distillation from >40 teachers
    • Nemotron 3.5 (Oct 2026): SFT → RLVR → expert teachers → MOPD

Stage boundaries are blurry in practice, but every modern recipe progresses from broad raw text to targeted high-quality data.

The Growth in Pretraining Token Budgets

0T10T20T 30T40T50T tokens GPT-3 (2020) hist. 0.4T (400B) LLaMA (2023) hist. 1.2T Llama 3 (2024) hist. 15T Qwen3 (2025) earlier 36T DeepSeek-V4.1-Flash (2026) 45T

Myth: "Trained on the Entire Internet"

$ curl https://cs336.stanford.edu/
<!doctype html><html>...<h1>CS336: Language Modeling from Scratch</h1>...</html>

Between a live webpage and a training token lie technical barriers, Terms of Service, and copyright law.

Why You Cannot Download All of the Web

  • Dynamic web apps
    • Content loads interactively via JS; URLs often do not change
    • Requires clicking buttons or submitting forms (e.g., Discord, Weights & Biases)
  • Authentication & paywalls
    • Huge text volumes sit behind accounts and subscriptions
    • Examples: Facebook, X, LinkedIn, New York Times
  • Technical bot defenses
    • robots.txt exclusion rules (voluntary protocol)
    • Bot detection & CAPTCHAs (e.g., Cloudflare)
    • IP / country blocks and strict rate limits
# Example robots.txt directives
User-agent: GPTBot
Disallow: /

User-agent: CCBot
Disallow: /

Even before legal questions arise, modern web architecture hides large fractions of human-written text from crawlers.

Legal Restrictions & the Decline of Consent

As more high-value publishers block crawlers, scraping creates both technical friction and escalating legal risk.

Shadow Libraries

As recent lawsuits demonstrate, how a copy was acquired can decide a case independently of how it was trained on.

US Copyright Law Fundamentals

Bottom line: basically everything on the Internet is copyrighted.

Using Copyrighted Data: Licenses & ToS

Only two legal paths to use a copyrighted work: (1) obtain a license, or (2) rely on fair use.

  • Licenses (contract law): licensor grants permission to licensee — effectively "a promise not to sue"
  • Creative Commons (Lessig & Eldred, 2001): bridges copyright and public domain
    • Wikipedia, Open Courseware, Khan Academy, Free Music Archive
    • 307M Flickr images, 39M MusicBrainz items, 10M YouTube videos
  • Commercial training deals:
    • Google & Reddit
    • OpenAI & Shutterstock
    • OpenAI & StackExchange
  • Terms of Service (ToS) trap:
    • ToS can add contractual bans even over licensed or fair-use content
    • Example: YouTube's ToS prohibits downloading videos even when CC-licensed

Fair Use (17 U.S.C. § 107)

Statutory FactorWhat Favors Fair Use
1. Purpose & characterEducational over commercial; transformative over reproductive
2. Nature of the workFactual / non-creative over fictional / creative
3. Amount & substantialitySmall snippet over copying the entire work
4. Market effectDoes not harm the market (or potential market) for the original

Applying Fair Use to Language Models

Whether LM training qualifies as fair use hinges on how courts weigh transformativeness against acquisition and market harm.

Landmark AI Copyright Lawsuits

CaseAllegationKey Rulings & Outcomes
NYT v. OpenAI
2023
Training on and reproducing New York Times articles Active litigation over both training copies and memorized/near-verbatim outputs
Bartz et al. v. Anthropic
2024 → 2025
Pirating millions of books and training on plaintiffs' books Summary judgment (2025): training = fair use; buying & scanning books = fair use; pirating copies = NOT fair use.
Outcome: Anthropic paid $1.5B to settle with authors.
Kadrey et al. v. Meta
Summary judgment 2025
Training on plaintiffs' books (revealed in Llama paper) Summary judgment (2025): training on books (in this instance) = fair use; torrenting allegation remained pending.

Raw Source 1: Common Crawl

Apache Nutch Crawl Loop URL Frontier / Queue Seeds: hundreds of millions of URLs Fetcher (Politeness) Respect robots.txt & rate limits Archive (WARC / WET) Store raw HTTP + extracted text Parse & Select Links Selection + re-visit policies enqueue new URLs
  • Non-profit founded in 2007; runs ~monthly crawls adding 3–5B pages (some overlap, aims to diversify)
  • Scale:
    • 300B pages archived so far ($O(\text{billions})$ of live URLs; Google index $\ge 100\text{ PB}$)
    • April 2026 crawl: 2.19B pages (372.2 TB)
  • Core crawler policies:
    • Selection: which pages to fetch?
    • Politeness: honor robots.txt, avoid overloading hosts
    • Re-visit: how often to refresh changing pages
    • Challenge: dynamic URLs map many URLs to identical content

WARC vs. WET: HTML-to-Text Extraction Matters

Common Crawl Raw HTTP response WARC (HTML) Full DOM structure Custom Extractor trafilatura · resiliparse · jusText Cleaner Text Higher LM accuracy WET (Plain Text) Lossy pre-conversion Noisy Text Nav menus, lossy
<nav>Home | Login | Subscribe</nav>
<article><p>Actual article body...</p></article>
<footer>Cookies · Terms of Use</footer>
  • DCLM (2024) showed HTML→text extraction directly affects downstream task accuracy
  • Choice trades precision vs. recall: trafilatura strips aggressively; jusText retains more tokens

Modern pipelines (The Pile, RefinedWeb, DCLM, Nemotron-CC) start from WARC rather than WET.

Raw Source 2: Wikipedia & Data Poisoning

Aside: Scheduled-Dump Data Poisoning Vulnerability (2023) 1. Malicious Edit Injected just before scheduled dump 2. Periodic Dump Snapshots poisoned article permanently 3. Admin Rollback Fixed live, but too late for the dump

Poisoning examples can make models assign negative sentiment to trigger phrases (e.g., "iPhone") — even high-quality sources carry risk.

Raw Source 3: Code — GitHub & Software Heritage

GitHub (2008; Microsoft 2018)
  • Octoverse 2024: >518M projects (open source, public and private)
  • Rich artifacts: directory trees, commit history, issues, PRs, review comments
  • Heavy duplication from forks and copied code
  • Train on public repos with permissive licenses (MIT, Apache)
  • Two access paths:
    • Repos: git protocol (not HTML scraping)
    • Metadata: GitHub API & hourly event stream on GitHub Archive
Software Heritage (2016)
  • Non-profit founded to collect and preserve public software source code
  • Aggregates multiple forges and package registries:
    • GitHub, GitLab, Bitbucket, PyPI, and more
  • Focused on source repositories rather than social metadata (issues, PR comments)
  • Backbone for open code corpora such as The Stack v2

Raw Source 4: Scientific Papers & Q&A Forums

arXiv (since 1991)
  • Free preprint repository: physics (original), math, CS, statistics, and more
  • ~3M submissions; light moderation (not peer review)
  • Each submission has metadata, PDF, and optional LaTeX source (cleaner for math/tables)
  • Licensing: metadata is CC0; authors pick all-rights-reserved or Creative Commons (e.g., CC-BY)
  • Bulk download from Amazon S3 — no crawling required
Stack Exchange (since 2008)
  • User-contributed Q&A network starting with StackOverflow, spanning math, literature, and more
  • Reputation points and badges incentivize accurate answers
  • Q&A structure closely matches instruction following and real user queries
  • Rich metadata (votes, tags, accepted answers, comments) enables high-precision filtering
  • Released as anonymized XML dumps

Raw Source 5: Books — Public Domain vs. Taken Down

CorpusOrigin & ScaleLegal / Access StatusNotes
Project Gutenberg
1971 · PG-19
~75K books (2025), mostly English Copyright-cleared
(mostly public domain)
Founded by Michael Hart; PG-19 collects pre-2019 books; older prose style
BooksCorpus
2015
7K self-published books (985M words) priced at $0 Taken down
(violated Smashwords ToS)
Scraped from Smashwords (2024: 150K authors, 500K books); used to train BERT
Books3
Presser, 2020
196K books from shadow library Bibliotik Taken down
(copyright infringement & lawsuits)
Included contemporary authors (e.g., Stephen King, Min Jin Lee, Zadie Smith); part of The Pile & LLaMA

How Pretraining Corpora Evolved (2019–2026)

1. Small Curated 2019 (Historical) BERT Wiki + BooksCorpus GPT-2 WebText Reddit karma ≥ 3 (40 GB) Human proxies; cannot scale to T tokens 2. Rule & LM CC 2019–2024 (Historical) CCNet · C4 · MassiveText Heuristics, KenLM The Pile · LLaMA · Dolma Curated multi-source RefinedWeb · FineWeb WARC + rules + MinHash Scales to 15T tokens 3. Classifier Filter 2020 / 2024+ GPT-3 (early) Classifier vs. WebText DCLM-baseline fastText vs. OpenHermes & ELI5 (240T → 3.8T) High accuracy, but discards ~90% of tokens 4. Ensembles & Synthetic / Legal Nemotron-CC Distilled LLM scorers + synthetic rephrasing The Stack v2 Code + PRs + LLVM IR Common Pile Permissive-only (8 TB)

Next: trace each generation to see what problem it solved and what limitation forced the next jump.

Early Curated Corpora: BERT & WebText (2019)

Historical baselines — before Common Crawl filtering became standard.

BERT (2019)
  • Sources: Wikipedia + BooksCorpus
  • Crucial design shift: trained on contiguous documents rather than shuffled single sentences
  • Contrasted with the 1 Billion Word Benchmark (Chelba et al., 2013), built from isolated machine-translation sentences
WebText (GPT-2, 2019)
  • Idea: use human upvotes as a quality proxy — scrape outgoing links from Reddit posts with $\text{karma} \ge 3$
  • Yield: 8M webpages, 40 GB of text
  • OpenWebTextCorpus: open replication using Reddit URLs + fastText English filter + near-deduplication

Automatic Web Filtering: CCNet (2019)

Historical baseline — proved filtered Common Crawl could beat Wikipedia alone and scale to low-resource languages (e.g., Urdu).

Common Crawl Multilingual raw 1. Deduplication Remove duplicate paragraphs (light norm) 2. Language ID fastText classifier per target language 3. LM Quality Filter KenLM 5-gram trained on Wikipedia (keep low PPL)

Heuristic Web Filtering: C4 (T5, 2019)

Historical baseline — Colossal Clean Crawled Corpus, released alongside the T5 text-to-text paper.

Classifiers vs. Multi-Source Curation (2020–2021)

Historical baselines — two influential responses to scaling past C4.

GPT-3 Dataset (2020) · 570 GB (400B)
  • Mixture: processed Common Crawl, WebText2, undisclosed Books1 & Books2, Wikipedia
  • Quality classifier: trained to distinguish {WebText, Wiki, Books} from raw Common Crawl
  • Fuzzy deduplication across documents, WebText, and evaluation benchmarks
The Pile (2021) · 825 GB (~275B)
  • Grassroots open-source effort (trained GPT-J, GPT-NeoX) across 22 curated domains
  • Pile-CC: WARC + jusText (cleaner than WET)
  • Specialized domains: PubMed Central (5M NIH-mandated papers), arXiv (LaTeX), Enron emails (500K emails, 150 executives, 2002), Gutenberg, Books3, Stack Exchange

Scaling Curated Mixtures: Gopher & LLaMA

Historical baselines — combining web pipelines with domain-specific corpora.

Gopher / MassiveText (2021)
  • 10.5 TB total (Gopher trained on 300B tokens, ~12%); MassiveWeb + C4 + Books + News + GitHub + Wiki
  • MassiveWeb: English, dedup, train–test overlap removal
  • Deliberately used manual rules (e.g., $\ge 80\%$ of words have an alphabetic char), not ML classifiers
  • Google SafeSearch for toxicity instead of brittle word lists
LLaMA (2023) · 1.2T tokens
  • CCNet + classifier for pages cited as Wikipedia references; plus C4 for diversity
  • Permissive GitHub + rules; Wikipedia (20 langs, Jun–Aug 2022); Gutenberg + Books3
  • arXiv (comments/bib stripped, macros expanded); Stack Exchange (28 largest sites, sorted by score)
  • Open clones: RedPajama v1 (1T) → SlimPajama (627B after MinHashLSH dedup)

"Web Data Is All You Need": RefinedWeb & FineWeb

Historical baselines (2023–2024) — showing high-volume web filtering could rival curated multi-source mixes.

RefinedWeb (Falcon, 2023)
  • Thesis: properly cleaned Common Crawl alone suffices
  • WARC + trafilatura HTML extraction
  • Gopher heuristic rules — avoided ML classifiers to avoid domain bias
  • Fuzzy deduplication via MinHash over 5-grams
  • Built 5T tokens (600B released)
FineWeb (HuggingFace, 2024)
  • Started as a RefinedWeb replication, then scaled and refined across 95 CC dumps
  • URL filtering + language ID ($p(\text{en}) > 0.65$)
  • Gopher + C4 + additional manual quality rules
  • MinHash fuzzy deduplication + PII anonymization (emails & public IPs)
  • Result: 15T tokens

Open Multi-Source Curation: Dolma (2024)

Historical baseline — AI2's open 3T-token pretraining corpus for OLMo.

Model-Based Filtering: DataComp-LM (2024)

Standardized benchmark for comparing data curation algorithms on a fixed Common Crawl pool.

DCLM-pool 240T tokens fastText Quality Classifier Positives (200K) OpenHermes-2.5 + Reddit ELI5 Negatives (200K) RefinedWeb (typical web sample) DCLM-baseline 3.8T tokens

Overcoming Token Starvation: Nemotron-CC

Synthetic Rephrasing & Task Generation

Scored Web Ensemble Classifier Lower-Quality Docs Normally discarded by 90% filter cutoffs LM Rephrasing Rewrite into clean, well-structured prose Recovered Tokens High-Quality Docs Rich factual or educational content LM Task Synthesis Generate QA pairs, key-info extraction Amplified HQ Supervision

Code Pretraining Corpora: The Stack & Stack v2

The Stack (2022) · 3.1 TB
  • Repo names from GitHub Archive (2015–2022)
  • git cloned 137M repos → 51B files, of which only 5B were unique ($\approx 10\times$ exact duplication!)
  • Permissive licenses only (MIT, Apache) via go-license-detector
  • Near-deduplication via MinHash + Jaccard similarity $J(A,B) = \frac{|A \cap B|}{|A \cup B|}$
The Stack v2 (2024)
  • Repos from Software Heritage + issues/PRs/comments from GitHub Archive
  • Crawled docs (PyPI, npm, devdocs.io) + math/code datasets (GSM8K, code contests, StackOverflow, arXiv, Wiki, OpenWebMath)
  • Cleaning: remove binaries, malware, bot activity; deduplicate; redact PII; subsample PRs
  • Pairs low-resource code (e.g., Nim) with shared LLVM IR for cross-language transfer

From Structured Code Objects to Token Streams

A GitHub pull request is a nested graph of metadata, diffs, files, and threads — an LM needs a flat token sequence.

PR Metadata File Context Code Diff Review Thread Linearize & Subsample
<pr_title>Fix empty-list edge case</pr_title>
<file path="parser.py">
  # surrounding inline file context
  def parse(items):
-     return items[0]
+     return items[0] if items else None
</file>
<comment>Add a unit test for None.</comment>
  • Inlining code context around each diff makes edits learnable without feeding the entire repository
  • Subsampling PRs prevents noisy automated commits from dominating the corpus

Permissively Licensed Pretraining: Common Pile

Empirical takeaway: permissive-only models perform decently, but struggle to compete with frontier models without far more tokens.

Pretraining Corpora at a Glance

Dataset (Year)ScalePrimary SourcesFiltering MethodKey Highlight
C4 (2019)156B tok (806 GB)1 CC snapshot (1.4T raw)Manual rules, bad-words, langdetectFirst large rule-cleaned CC
GPT-3 (2020)400B tok (570 GB)CC, WebText2, Books, WikiClassifier vs. WebText/Wiki/BooksFuzzy dedup incl. evals
The Pile (2021)~275B tok (825 GB)22 domains (CC+jusText, PubMed, arXiv, Books3…)Domain curationWARC+jusText over WET
LLaMA (2023)1.2T tokCCNet, C4, GitHub, Wiki, Books, arXiv, SECCNet + Wiki-ref classifier + rulesSlimPajama: 627B MinHash
FineWeb (2024)15T tok95 CC dumps (WARC+trafilatura)URL, lang ID, Gopher+C4+custom rulesMinHash dedup + PII redaction
Dolma (2024)3T tokCC, Pushshift Reddit, PeS2o, C4, Wiki, BooksfastText en, Gopher+C4, Jigsaw toxicityBloom-filter dedup
DCLM-base (2024)3.8T tok (from 240T)Common CrawlfastText classifier (OpenHermes + ELI5)Model filter beats rules
Nemotron-CC (2024)6.3T tok (1.1T HQ)CC (jusText) + syntheticEnsemble (DCLM + distilled 340B)LM rephrasing & QA synthesis
The Stack (2022)3.1 TBGitHub (permissive MIT/Apache)go-license-detector51B→5B unique + MinHash
Common Pile (2025)8 TBStrictly permissive sourcesLicense verification & curationTests permissive-only limit

Frontier 2025–2026 budgets (Qwen3 36T; DeepSeek-V4.1-Flash 45T) combine multi-source curation, classifier ensembles, and synthetic data.

Summary & Key Takeaways

Next lecture (Data II): the algorithms behind filtering, deduplication, and data mixing.