Lecture 6 · Pretraining

Advanced Natural Language Processing · Lecture 06。个人学习讲义与配套实验,按主题整理并持续修订。

课程源码 ZIP ↓

个人整理的学习笔记,非官方讲义;课程来源与整理说明见课程介绍。配套示例未逐一运行验证。

本篇目录

Maps to: CMU 11-711 Spring 2026, Lecture 6 (01/29), slides anlp-s2026-06-pretraining.pdf (some slides adapted from Graham Neubig’s Fall 2024 course); course demo code 06_pretraining/ (pretraining.ipynb: generate text with SmolLM2-360M, inspect a Dolma document). Readings: A. Radford et al., Language Models are Unsupervised Multitask Learners (GPT-2, 2019); G. Penedo et al., The FineWeb Datasets: Decanting the Web for the Finest Text Data at Scale (2024). Additional: J. Devlin et al., BERT (2018); H. Touvron et al., LLaMA (2023); K. Paster et al., OpenWebMath (2023); L. Soldaini et al., Dolma (2024); AI2, OLMo 3 (2025); G. Delétang et al., Language Modeling Is Compression (2023); J. Kaplan et al. (2020) and J. Hoffmann et al. (2022) — the scaling papers belong to Lecture 7. Sources: the public slides, the readings, and the papers cited in each section. Every number labelled “measured” comes from code/lecture06/, run on the author’s machine (Apple M4 Pro, Python 3.13, PyTorch 2.14, one CPU thread). Code: code/lecture06/ — every demo runs in under 90 seconds. Reading time: ~130 minutes for the prose; ~45 more for the demos.


0. How to read this lecture

0.1 Learning goals

After this lecture you should be able to:

  1. Explain the pretrain-then-adapt paradigm and the four reasons to pretrain (transfer, less task data, better performance, one model for many tasks).
  2. Write down the masked (BERT) and autoregressive (GPT) objectives, and say what each lets a position see, what each costs, and why BERT corrupts with 80/10/10.
  3. Derive why maximum likelihood fits the data distribution (cross-entropy = entropy + KL) and why it is compression: a better LM is a shorter code.
  4. Explain why next-token prediction on web text produces task skills, and design a control experiment that tests the explanation.
  5. Describe a web-data pipeline — extraction, language identification, heuristic filtering, deduplication (MinHash + LSH), classifier filtering, mixing — and evaluate each step by precision, recall and small-model ablations.
  6. Explain what duplicates do to a model (memorization) and why FineWeb deduplicated per snapshot.
  7. Explain coverage: why generic filters can erase a domain, and how classifier filtering and mixture optimization bring it back.

0.2 Prerequisites and scope

  • Prerequisites: Lecture 3 (language modeling, cross-entropy, KL, Errand World), Lecture 5 (the Transformer, Adam), Lecture 1 (logistic regression, which reappears as the fastText-style classifiers of the pipeline), Lecture 2 (BPE, transfer with word vectors).
  • Scope: what pretraining optimizes, why it transfers, and how pretraining data is built.
  • Not in scope: how big a model and how many tokens to use for a given budget (scaling laws, Lecture 7); adapting by prompting (Lecture 7) or fine-tuning (Lecture 8); distributed training (Lecture 20).

0.3 Section → code map

SectionIdeaDemo in code/lecture06/
§2.2–2.3causal LM = maximum likelihood = compression; arithmetic coding vs zlib/bz2/lzma01_objectives.py Parts A–B (+ arithcode.py)
§2.4–2.5masked vs causal: what a position sees, pseudo-likelihood, sample efficiency; 80/10/1001_objectives.py Parts C–D (+ pretrain.py)
§3why pretraining transfers: zero-shot, probe, fine-tune; the control without ratings; tracking a run02_why_pretrain.py
§5.2–5.5, §5.7the pipeline on a synthetic crawl: extraction, language ID, heuristic rules, the funnel, small-model ablation03_web_pipeline.py (+ web_world.py, pipeline.py)
§5.6MinHash, LSH, exact vs fuzzy dedup, memorization, per-snapshot vs global04_dedup.py
§5.8–5.9classifier filtering; coverage vs budget; mixture optimization with proxy models05_coverage_mixtures.py

0.4 Notation

SymbolMeaning
p∗p_*the (unknown) data distribution; pθp_\theta the model
D\mathcal{D}a training set of sequences x=(x1,…,x∣x∣)x = (x_1, \dots, x_{\lvert x\rvert})
MMthe set of masked (corrupted) positions; xMx_M the original tokens there, x¬Mx_{\neg M} the rest
H(p)H(p), H(p,q)H(p, q), DKL(p∥q)D_{\mathrm{KL}}(p \Vert q)entropy, cross-entropy, KL divergence
J(A,B)J(A, B)Jaccard similarity of two sets, ∣A∩B∣/∣A∪B∣\lvert A \cap B\rvert / \lvert A \cup B\rvert
kk, bb, rrMinHash signature size; LSH bands and rows per band (k=brk = br)
wdw_dweight (share) of domain dd in a training mixture

1. One model, many tasks

1.1 Where we are

So far every model was trained from scratch, one model per task: a sentiment classifier on labelled reviews (Lectures 1–2), a language model on Errand World (Lecture 3), a translator on parallel sentences (Lecture 4). Each started from random weights and saw only its own task’s data.

Today’s idea is to pretrain a single model, then adapt it to many tasks:

data ──pretrain──> base model ──adapt──> sentiment analysis, translation, dialogue,
                                          instruction following, problem solving, ...

There are two ways to adapt:

  • Prompting (Lecture 7): leave the weights alone and phrase the task as text, e.g. “Translate this sentence into English: この映画が嫌い”. One base model plus different prompts gives translation, sentiment analysis, instruction following.
  • Fine-tuning (Lecture 8): continue training the base model on task data (e.g. Japanese–English sentence pairs) to obtain a fine-tuned model.

A modern open example is OLMo 3 (AI2, Dec 2025), whose whole recipe is public: a pretraining stage on a ~6T-token mixture, then shorter “midtraining” and long-context stages, then post-training into instruction-following and reasoning models.

1.2 Why pretrain?

The slides list four reasons:

  • Transfer learning (迁移学习): take “knowledge” learned on one task and apply it to another.
  • Less task data: reach a given level of performance with fewer labelled examples.
  • Better task performance: reach a higher level than training from scratch.
  • One model, multiple tasks: convenient; the pretraining cost is paid once and amortized; a starting point for many uses.

The first two are easy to see in a small experiment; demo 02 measures them (§3). The third depends on the task and the amount of labelled data, and demo 02 shows a case where it does not hold. The fourth is what made pretrained models the default.

Lecture 2 had a first taste: skip-gram vectors trained on unlabeled reviews and then used in a classifier. That transferred one layer, the word embeddings. Pretraining transfers the whole network.

1.3 Four factors

Pretrained models have names — BERT, GPT-3, Llama, DeepSeek-V3. Each is determined by four factors:

FactorQuestionLecture
Architecturewhich network? (Transformer, Lecture 5)5, 21, 22
Task (objective)what does the model predict? (masked tokens, the next token)today §2
Datawhat text, how cleaned, how mixed?today §5
Hyperparameterslearning rate, batch size, model size, number of tokens5, 7

2. Pretraining objectives

2.1 What makes a good pretraining task?

The objective must be computable on raw text without labels (there is far more raw text than labelled data), and it must be hard in a useful way: solving it should require the knowledge we want the model to have — syntax, word meaning, facts, reasoning. Predicting missing or next words fits both requirements. To fill in “The cat [M] on the mat”, a model must know that a verb is needed and which verbs fit cats and mats.

2.2 Masked language modeling (BERT)

Masked language modeling (MLM, 掩码语言建模) predicts masked tokens xMx_M from the visible tokens x¬Mx_{\neg M}:

LMLM(θ;D)=−1∣D∣∑x∈DEM∼corrupt(x)∑t∈Mlog⁡pθ(xt∣x¬M).\mathcal{L}_{\mathrm{MLM}}(\theta; \mathcal{D}) = -\frac{1}{\lvert\mathcal{D}\rvert}\sum_{x \in \mathcal{D}} \mathbb{E}_{M \sim \mathrm{corrupt}(x)} \sum_{t \in M} \log p_\theta(x_t \mid x_{\neg M}).

Example: “The cat [M] on [M] mat” → predict “sat” and “the”.

Two ways to view it:

  • Denoising (去噪): corrupt xx, then reconstruct it. The model learns which texts are plausible by learning to repair implausible ones.
  • Pseudo-likelihood (伪似然): if each position is masked in turn, the objective sums log⁡pθ(xt∣x¬t)\log p_\theta(x_t \mid x_{\neg t}) over positions. This is not log⁡pθ(x)\log p_\theta(x), and §2.4 measures how different it is.

BERT (Devlin et al., 2018) is the canonical example:

  • Architecture: a Transformer encoder, with no causal mask, so every position attends to every other.
  • Data: BooksCorpus (800M words) and English Wikipedia (2,500M words).
  • Task: MLM, plus a “next sentence prediction” objective that later work (RoBERTa) found unnecessary.
  • Sizes: BERT-Base has 12 layers (110M parameters), BERT-Large 24 layers (340M).

The corruption recipe. Choose 15% of token positions at random. At a chosen position:

  • 80% of the time, substitute the input token with [MASK];
  • 10% of the time, substitute a random token;
  • 10% of the time, leave it unchanged.

The loss is computed only at the chosen positions. Why not always [MASK]? Because at fine-tuning time the input never contains [MASK]. A model that only ever predicts at [MASK] positions has no reason to build a good representation of the tokens it can see, and could take every visible token at face value. The random and unchanged cases force it to represent and check every token. §2.5 measures the effect.

Adapting an MLM. Add an output layer WW that maps a hidden vector to class scores, initialize the rest with BERT, and minimize cross-entropy on, e.g., (movie review, {positive, neutral, negative}) pairs. Either train just WW (“linear probe”, frozen body) or all weights (“fine-tuning”). BERT reached the state of the art on eleven NLP benchmarks this way in 2018.

2.3 Autoregressive language modeling = maximum likelihood = compression

The autoregressive (causal) objective predicts the next token xtx_t from the previous tokens x<tx_{<t}:

LMLE(θ;D)=−1∣D∣∑x∈D∑t=1∣x∣log⁡pθ(xt∣x<t)=−1∣D∣∑x∈Dlog⁡pθ(x).\mathcal{L}_{\mathrm{MLE}}(\theta; \mathcal{D}) = -\frac{1}{\lvert\mathcal{D}\rvert}\sum_{x \in \mathcal{D}}\sum_{t=1}^{\lvert x\rvert} \log p_\theta(x_t \mid x_{<t}) = -\frac{1}{\lvert\mathcal{D}\rvert}\sum_{x \in \mathcal{D}} \log p_\theta(x).

By the chain rule the sum of next-token log-probabilities is the log-probability of the whole text, so this objective maximizes likelihood (Lecture 3). Three views of what it does:

1. It fits the data distribution. Minimizing the KL divergence from the data distribution p∗p_* to the model:

min⁡θDKL(p∗∥pθ)=min⁡θ∑xp∗(x)log⁡p∗(x)pθ(x)≡min⁡θ−Ex∼p∗log⁡pθ(x)≈min⁡θ−1∣D∣∑x∈Dlog⁡pθ(x).\min_\theta D_{\mathrm{KL}}(p_* \Vert p_\theta) = \min_\theta \sum_x p_*(x)\log\frac{p_*(x)}{p_\theta(x)} \equiv \min_\theta -\mathbb{E}_{x \sim p_*}\log p_\theta(x) \approx \min_\theta -\frac{1}{\lvert\mathcal{D}\rvert}\sum_{x \in \mathcal{D}}\log p_\theta(x).

The ∑xp∗log⁡p∗\sum_x p_*\log p_* term does not depend on θ\theta, and the expectation is estimated by the training sample. So maximum likelihood = minimum KL, and

H(p∗,pθ)⏟cross-entropy (the loss)=H(p∗)⏟entropy+DKL(p∗∥pθ).\underbrace{H(p_*, p_\theta)}_{\text{cross-entropy (the loss)}} = \underbrace{H(p_*)}_{\text{entropy}} + D_{\mathrm{KL}}(p_* \Vert p_\theta).

When pθ=p∗p_\theta = p_* the loss equals the entropy. On real text we never know H(p∗)H(p_*). On Errand World we do. Measured (demo 01 Part A): a small LLaMA-style Transformer trained on 4,000 sentences reaches 0.760 nats/token against an entropy of 0.754, so its KL from the truth is only 0.006 nats/token.

2. It learns to compress. Shannon (1948): to encode data from p∗p_* into bits, the minimum expected code length is the entropy, H(p∗)=Ex∼p∗[−∑ilog⁡2p∗(xi∣x<i)]H(p_*) = \mathbb{E}_{x\sim p_*}[-\sum_i \log_2 p_*(x_i \mid x_{<i})]. Arithmetic coding (算术编码) turns any model pp into a code that achieves (almost exactly) −log⁡2p(x)-\log_2 p(x) bits. Picture the interval [0,1)[0, 1):

  • At each step, split the current interval into one piece per possible symbol, sized by its probability.
  • Zoom into the piece of the symbol that occurred.

After nn symbols the interval’s width is ∏tp(xt∣x<t)=p(x)\prod_t p(x_t \mid x_{<t}) = p(x), and about −log⁡2p(x)-\log_2 p(x) bits suffice to name a point inside it. The decoder runs the same model and retraces the same intervals. If we code with a model pθp_\theta, the expected code length is the cross-entropy,

H(p∗,pθ)=H(p∗)+DKL(p∗∥pθ),H(p_*, p_\theta) = H(p_*) + D_{\mathrm{KL}}(p_* \Vert p_\theta),

so to approach the minimum code length, minimize the KL — that is, do maximum likelihood. Training loss and compression rate are the same number in different units.

Measured (demo 01 Part B, 2,000 Errand World test sentences, 22,243 tokens; arithcode.py is a real coder, and every row decodes back to the exact text):

coderbits/tokenbits/char
raw text (8 bits per character)34.698.000
zlib -93.810.879
lzma -9e3.300.760
bz2 -92.070.477
arithmetic coding, uniform over words7.011.617
arithmetic coding, unigram5.851.349
arithmetic coding, bigram1.560.360
arithmetic coding, causal Transformer LM1.100.253
arithmetic coding, the true distribution1.090.250

The LM coder’s output is 24,427 bits for an NLL of 24,388 bits (+0.16%, the cost of rounding probabilities to integers). Better models give shorter codes, in the same order as their perplexities in Lecture 3.

The catch: the decoder needs the model. The Transformer has 115,392 parameters, 3.69 million bits at 32 bits each, which is 151 times the size of the coded test set. Counted honestly, it beats bz2 only once its size is spread over ~340,000 sentences. Delétang et al. (2023) make the same point at scale. Chinchilla 70B, trained mostly on text, compresses ImageNet image patches to 43.4% and LibriSpeech audio to 16.4% of their raw size, better than PNG (58.5%) and FLAC (30.3%). But once its parameters are counted, it is a terrible compressor for any dataset smaller than its own weights. This is the reason the “compression” view connects to the scaling questions of Lecture 7. A model is worth its size only if it is trained on, and used for, enough data.

3. Why this is a good pretraining task. To compress web text well, a model must capture every regularity that makes text predictable: spelling, syntax, facts (“the capital of France is ___”), arithmetic (“142 + 29 = ___”), the sentiment of a review that ends with a rating (§3). The course notebook shows a pretrained SmolLM2-360M continuing such prompts. Whatever the model learned is whatever made the next token more predictable.

2.4 What each objective lets a position see

A causal LM conditions each prediction on the left context only; an MLM conditions on both sides. On Errand World we can compute both optima exactly:

  • the best left-to-right prediction, −log⁡p∗(xt∣x<t)-\log p_*(x_t \mid x_{<t}), from the prefix masses of all 34,320 sentences;
  • the best both-sides prediction, −log⁡p∗(xt∣x¬t)-\log p_*(x_t \mid x_{\neg t}), from the masses of all sentences that differ only at position tt.

Measured (demo 01 Part C, average nats per word over 500 test sentences, one position masked at a time):

word roletruth, left onlycausal LM (12 ep)truth, both sidesmasked LM (12 ep)masked LM (80 ep)
activity (“for tennis class …”)2.0792.0950.0772.0870.084
item (”… own racquet”)0.8440.8670.8442.4340.831
title (“dr jane smith …”)2.5902.5970.0000.0170.003
last name (“dr jane smith …”)0.6690.7330.6690.7320.677
all word positions0.8320.8430.3770.5500.386

Read it role by role:

  • Title. It starts the sentence, so from the left it is almost a guess (2.59 nats). From both sides it is certain (0.00), because the surname that follows belongs to exactly one title. The masked LM learns this quickly: 0.017 after 12 epochs.
  • Activity. It is named by the item 8–21 tokens later (racquet → tennis). The both-sides optimum is 0.08 nats vs log 8 = 2.08 from the left. After 12 epochs the masked LM has not learned the link (2.09). After 80 epochs it has (0.08).
  • Item. The causal LM learns the reverse link, item from activity, within 12 epochs (0.867 vs optimum 0.844). The masked LM after 12 epochs is far worse (2.43).
  • Last name. Nothing after it is informative, so both sides cost the same as the left (0.669).

Why the masked LM is slow: it learns from ~15% of positions. Per pass over the data, the causal LM gets a training signal at every position. The masked LM gets one only at the ~15% it masked. 80 epochs × 15% ≈ 12 signals per position, the same as the causal LM’s 12 epochs, and with that matched signal it caught up. This is the inefficiency that ELECTRA (Clark et al., 2020) was designed around. ELECTRA trains a discriminator to say, at every position, whether a token was replaced.

Pseudo-likelihood is not likelihood. With the exact conditionals, the expected log-likelihood of an Errand World sentence is −8.31 nats, but its expected pseudo-log-likelihood ∑tlog⁡p∗(xt∣x¬t)\sum_t \log p_*(x_t \mid x_{\neg t}) is −3.82. Every conditional sees more context than the chain rule allows. Summed over all 34,320 sentences, exp⁡(PLL)\exp(\mathrm{PLL}) is 420, not 1. A masked LM gives conditionals but no normalized probability of a text, so it cannot be sampled left to right or scored as a language model without extra machinery.

Why GPT-style models took over. Encoders like BERT were the default for classification and extraction from 2018 to about 2020, and still are for embedding models. The field moved to decoder-only causal LMs for several reasons:

  • Every token trains. The causal objective uses every position, as the table shows.
  • Generation and prompting. A causal LM is a generator, and generation is the universal interface: any task can be posed as “continue this text” (§3, Lecture 7).
  • Scaling. Causal LMs turned out to keep improving predictably with size and data (Lecture 7).

None of this says bidirectional context is useless. The table shows it is worth a lot of information per position. Encoder–decoder models (T5) and modern encoders keep it where it pays.

2.5 Measuring the 80/10/10 rule

Measured (demo 01 Part D): two masked LMs trained identically, except that one replaces 100% of the chosen tokens with [MASK]. On 500 test sentences, one random word was replaced by another word without a [MASK] token:

MLM trained withNLL at a [MASK]corrupted word repairedvisible words predicted as themselves
80/10/10 (BERT)0.59670.4%94.9%
100% [MASK]0.56410.8%5.9%

Both predict a [MASK] about equally well. Only the 80/10/10 model has learned anything about the positions it can see. At an unmasked position, the 100%-[MASK] model’s output is essentially untrained: it predicts the visible word itself only 6% of the time and repairs a wrong word 11% of the time. For fine-tuning, where nothing is masked, that is exactly the wrong habit.


3. Why pretraining transfers

3.1 The GPT-2 hypothesis

Radford et al. (2019) trained GPT-2, a 1.5B-parameter Transformer, on WebText: about 8 million documents (40 GB) linked from Reddit posts with at least 3 karma, a cheap human quality filter. They argued that the web contains “naturally occurring demonstrations” of tasks. Two examples:

  • English sentences followed by “in French: …”;
  • articles followed by “TL;DR:” and a summary.

A model that predicts web text well must learn to perform these tasks, and a prompt can then ask for them zero-shot: GPT-2 summarized when its input ended in “TL;DR:”. Hence the title, Language Models are Unsupervised Multitask Learners.

This hypothesis is testable. If it is right, pretraining should help a task only if the pretraining text contains signals of that task.

3.2 The experiment

Demo 02 pretrains the same small LLaMA-style Transformer on 24,000 review pages from Web World (§5). About 30% of the reviews end with a line like “rating : 4 stars .”. The stars come from the review’s true sentiment (4–5 positive, 3 neutral, 1–2 negative), which is the natural label a review site gives away. The control uses the same reviews with the rating lines deleted. Each model is then used in four ways on Cinema World’s 1,000 dev reviews, where majority-class guessing gives ~40%:

  • Zero-shot: no labels and no training. Append ” rating :”, read the next-token probabilities of the star digits, and predict the class with the most mass.
  • Probe: freeze the body and train a new linear layer on the last position’s hidden state, with 100 labels.
  • Fine-tune: train everything, with 100 or 2,000 labels.

Measured (demo 02):

starting pointzero-shotprobe, 100 labelsfine-tune, 100 labels2,000 labels: 1 epoch2,000 labels: best of 10
from scratch (random init)40.1%42.8%54.4%55.4%85.2%
pretrained, ratings removed37.6%52.3%56.6%58.8%84.3%
pretrained, with ratings77.7%78.2%74.7%78.0%84.4%

3.3 What it shows

  • Zero-shot works when the text contains the task. With no labels at all, the model pretrained with ratings classifies 77.7% of reviews correctly. Predicting the rating is classifying the review, and the model learned to do it because ratings were in its training text.
  • Less task data. With 100 labels, a frozen pretrained body plus one linear layer reaches 78.2%, against 54.4% from scratch. Scratch needs 20× the labels and 4 epochs to pass that.
  • The control transfers far less. The same reviews without ratings give a 52.3% probe and 37.6% zero-shot. Next-token prediction learns what the text makes predictable. In a lone review, no later word depends on the review’s sentiment, so the model has no reason to compute it. Lecture 2’s word-vector experiment needed coordination sentences (“the X is A and B”) for the same reason.
  • “Better task performance” did not appear here. With 2,000 labels, the pretrained model starts far ahead (78.0% vs 55.4% after one epoch), but scratch catches up (84.4% vs 85.2% at the best epoch). Cinema World is small enough to learn from 2,000 labels. On real tasks, pretrained models usually also raise the ceiling, because real tasks need knowledge that 2,000 labels cannot teach. Treat that as a property of the task, not a law.

Caveat. Here the rating line is the only planted task signal. Real web text carries thousands of them at once — ratings, titles, Q&A threads, recipes, code with comments, translations — which is why one pretrained model transfers to many tasks.

3.4 Watching a pretraining run

How do we know a pretraining run is going well? The slides list three ways to evaluate a base model: the loss (training, validation, test), few-shot prompting, and fine-tuning. Each has a role:

  • Loss is cheap and smooth, and good for diagnosing the training trajectory and comparing models in the same family. It cannot compare models with different tokenizers or data.
  • Few-shot / zero-shot task accuracy tracks capabilities directly. It is noisier and can move while the loss is flat. Llama’s paper plots this trajectory for many benchmarks during training.
  • Fine-tuning is the most faithful test for downstream use, but too expensive to run often.

Measured (demo 02 Part D, the run with ratings):

step1382764145526908289661104
held-out NLL1.3031.1641.1441.1351.1201.1161.1131.112
zero-shot accuracy (300 reviews)42.7%57.7%57.7%60.3%71.7%74.7%75.0%76.0%

After the second checkpoint the loss moves only 0.052 nats, while zero-shot accuracy climbs from 58% to 76%. The capability is carried by the rating tokens, a small fraction of all tokens, so it barely shows in the average loss.

Choosing evaluation tasks. AI2’s OLMo 3 report groups evaluation tasks into categories (code, math, fill-in-the-middle, multiple-choice QA, …). Tasks belong to the same category if they tend to rank models in the same way. The tasks are then split into two suites:

  • tasks that give a useful signal already at small scale, for development decisions such as data ablations;
  • the downstream metrics that matter for the final model.

Demo 02’s two curves make the same distinction: for a small model, the zero-shot metric is noisy (58% → 58% → 60% between checkpoints), but it measures the capability itself.


4. Two examples, and the key factors

4.1 What we can change

LMLE(θ;D)=−Ex∼D∑t=1∣x∣log⁡pθ(xt∣x<t)\mathcal{L}_{\mathrm{MLE}}(\theta; \mathcal{D}) = -\mathbb{E}_{x\sim\mathcal{D}}\sum_{t=1}^{\lvert x\rvert}\log p_\theta(x_t \mid x_{<t})

has three knobs: θ\theta (the architecture and its size), D\mathcal{D} (the training data), and the optimization hyperparameters (learning rate, batch size, schedule — Lectures 3 and 5, with Adam as Lecture 5’s §5.1). The rest of this lecture is about D\mathcal{D}. Lecture 7 is about choosing sizes.

4.2 GPT-2 and Llama

  • GPT-2 (OpenAI, 2019): a Transformer of up to 1.5B parameters; data WebText, millions of web pages selected through Reddit links.
  • LLaMA (Touvron et al., 2023): Transformers of 6.7B, 13B, 32.5B and 65.2B parameters; 1.0T tokens for the two smaller models, 1.4T for the two larger. The data is public sources only:
sourceshare of samplingepochs
CommonCrawl (CCNet-filtered)67.0%1.10
C415.0%1.06
GitHub4.5%0.64
Wikipedia (20 languages)4.5%2.45
Books (Gutenberg, Books3)4.5%2.23
ArXiv2.5%1.06
StackExchange2.0%1.03

Two things to notice. Web data dominates. And small, high-quality sources (Wikipedia, books) are upsampled: seen more than twice, while the web is seen about once. That is a mixture decision (§5.9). LLaMA’s training loss falls smoothly over the 1.4T tokens, and its few-shot benchmark accuracies rise with it.

Practical tools. The course notebook loads a pretrained model with the HuggingFace transformers library (AutoTokenizer, AutoModelForCausalLM.from_pretrained("HuggingFaceTB/SmolLM2-360M")) and calls model.generate. It also downloads one shard of Dolma and prints a document: a JSON record with the text and metadata (id, source, timestamps). This is what “pretraining data” looks like on disk.


5. Data: quantity, quality, coverage

Better data gives lower loss — and so does more data. The slides frame data around three questions:

  • Quantity: how much data do I have?
  • Quality: is it beneficial for training?
  • Coverage: does the data cover the domain(s) I care about, in the right proportions?

5.1 Quantity

modeltokens of training data
Llama 11.4 trillion
Llama 2~2 trillion
Llama 315 trillion
DeepSeek-V3~15 trillion (14.8T)
for scale: all of English Wikipedia< 10 billion

Trillions of tokens can only come from the web. Common Crawl publishes snapshots of billions of web pages several times a year; FineWeb uses 96 of them (2013–2024). A raw snapshot is mostly not text you want to train on: navigation menus, spam, link farms, broken encodings, and the same page many times over. Turning it into training data takes three kinds of step: extraction → filtering → deduplication.

5.2 A crawl with known truth: Web World

To measure each pipeline step, the demos use Web World (web_world.py), a synthetic crawl in which every page carries its hidden truth. Seven domains:

  • reviews: Cinema World reviews, some with rating lines;
  • errands: Errand World “diaries”;
  • math: practice sheets, “3 + 4 = 7 .” and worked sums;
  • zorbian: reviews in Lecture 1’s made-up language;
  • spam, links (portal pages) and gibberish.

Each page is wrapped in site boilerplate (menu, tracking script, advertisement, footer) in one of two HTML layouts. Duplicates are planted: exact mirrors, near-copies with small edits, and rare “viral” pages copied dozens of times. A pipeline step sees only the HTML; the demos use the truth only to score it.

Measured (demo 03 Part A): one crawl of 3,000 original pages has 5,506 pages (2,506 copies). Only 28.9% of its main-content tokens are good English (reviews, errands, math); spam alone is 47%.

5.3 Extraction

HTML → text. The simplest extractor strips every tag and keeps everything else; Common Crawl’s WET files are roughly that. A main-content extractor (FineWeb uses trafilatura) removes boilerplate blocks and keeps paragraphs. Domain pipelines go further: OpenWebMath wrote its own extractor so that LaTeX and code survive.

Measured (demo 03 Part B):

extractortokens extractedboilerplate shareZorbian pages labeled English
strip all tags375,55448.4%191 of 484
main content193,8170.0%0 of 484

Stripping tags nearly doubles the text, with lines like “home | news | about | contact” repeated on 2,028 pages: tokens that waste compute and get memorized (§5.6). Extraction also changes what later steps see: with the English boilerplate left in, 191 of 484 Zorbian pages look English to the language identifier. (Web World’s two layouts are regular enough that our rule-based extractor is perfect; real extractors are not, and FineWeb compared them by training models on their outputs.)

5.4 Language identification

FineWeb keeps a page if fastText’s language identifier gives English a score ≥ 0.65. fastText is a linear classifier over character n-grams, which is Lecture 1’s logistic regression with different features. pipeline.LangID is exactly that, trained on clean seed text: English, Zorbian, and random letters as “other”.

Measured (demo 03 Part C):

domain→ en→ zb→ othermean confidencekept (en, p ≥ 0.65)
reviews1151000.96100%
errands441000.95100%
math227000.520%
zorbian048400.980%
spam1747000.88100%
links1089010.7786%
gibberish003660.980%

Two lessons:

  • Language ID is not a quality filter. Spam is perfectly good English.
  • A threshold has casualties. “3 + 4 = 7 .” looks like no language the identifier was trained on, so its English score stays near 0.5 and every math page is dropped. Real pipelines lose math, code and tables the same way.

5.5 Heuristic quality filters

Next come cheap rules. FineWeb applies, in order:

  • Gopher’s repetition and quality rules (Rae et al., 2021): too few words, mean word length outside 3–10 characters, symbol-to-word ratio > 0.1, fewer than 2 of 8 common English stop words, too many duplicate lines or n-grams.
  • C4’s rules (Raffel et al., 2020).
  • Three custom rules chosen by ablation:
    • ≤ 12% of lines end in punctuation;
    • ≥ 10% of characters are in duplicated lines;
    • ≥ 67% of lines are shorter than 30 characters.

pipeline.RULES implements eight such rules. Web World’s pages are 10–40 words, so three thresholds are scaled (documented in the code).

Measured (demo 03 Part D, each rule applied alone to every page):

rulepages removedprecisionrecall (of all low-quality)good pages removedmost-hit good domain
few words1303.1%0.1%126reviews (72)
word length2300.0%0.0%230math (227)
symbols1082100.0%33.8%0—
stop words364378.9%89.8%767zorbian (484)
dup lines16479.3%4.1%34reviews (28)
top 2-gram177194.7%52.4%94zorbian (34)
punct lines143299.7%44.6%4reviews (2)
short lines91380.4%22.9%179math (165)
any rule400477.8%97.2%890

Every rule is a classifier with false positives:

  • “Few words” catches almost no junk here, but deletes short good reviews.
  • “Word length” and “short lines” were written against link lists, and they hit math sheets.
  • The stop-word rule removes 90% of the junk and every math page with it.

Reviews and errands survive the full rule set at 88% and 90%; math survives at 0%.

The funnel (demo 03 Part E):

stagepagestokensgood-English sharemath pages
raw: all tags stripped5506375,55431.0%227
main-content extraction5506193,81728.9%227
+ language ID (en, p ≥ 0.65)4280158,66929.0%0
+ heuristic rules150249,01388.3%0
+ exact deduplication121839,36690.4%0

About 10% of the raw tokens survive, which is the order of magnitude real pipelines report. FineWeb kept roughly 15T tokens from far larger raw snapshots. Good English rises from 31% to 90%, and one good domain is gone.

5.6 Deduplication

Why duplicates appear. The web copies itself: mirrors, syndicated articles, templates, re-crawls of the same page in every snapshot. Lee et al. (2022) found a single 61-word sentence repeated over 60,000 times in C4.

Why remove them. First, compute: re-reading a page is a step not spent on new text. Second, memorization: models reproduce duplicated text verbatim. Lee et al. found models trained on deduplicated data emit memorized text about ten times less often. Kandpal et al. (2022) found that regurgitation grows super-linearly with the number of copies.

Exact deduplication hashes each (normalized) document and keeps the first of each hash. It misses near-duplicates: the same article with a different date line, an extra sentence, one word changed.

Fuzzy deduplication with MinHash. Represent a document by its set of word 5-grams (“shingles”) and compare sets with the Jaccard similarity J(A,B)=∣A∩B∣/∣A∪B∣J(A, B) = \lvert A\cap B\rvert / \lvert A \cup B\rvert. Computing JJ for all pairs of nn documents costs O(n2)O(n^2), which is impossible at billions of documents. Two tricks fix this:

  1. MinHash. Apply a random hash function hh to every shingle and keep the minimum. Then P(min⁡h(A)=min⁡h(B))=J(A,B),P\big(\min h(A) = \min h(B)\big) = J(A, B), because the minimum over A∪BA \cup B is equally likely to be any of its elements, and the two minima agree exactly when that element is in A∩BA \cap B. With kk independent hash functions, the fraction of agreeing positions estimates JJ with standard error J(1−J)/k\sqrt{J(1-J)/k}.
  2. Locality-sensitive hashing (LSH) with bands. Split the k=brk = br numbers into bb bands of rr rows, and make two documents candidates if all rr rows agree in at least one band. One band agrees with probability JrJ^r, so P(candidate)=1−(1−Jr)b,P(\text{candidate}) = 1 - (1 - J^r)^b, an S-shaped curve with threshold near (1/b)1/r(1/b)^{1/r}. Each document goes into bb hash buckets, and only documents sharing a bucket are compared. The work is linear in nn.

FineWeb: 5-gram shingles, 112 hashes = 14 bands × 8 rows, aiming at pairs that are at least 75% similar.

Measured (demo 04 Parts A–B): with 112 hashes, the standard error at J=0.5J = 0.5 is 0.048 (theory 0.047), and it falls like 1/k1/\sqrt{k}. The banding curves match theory to within a few points:

bands × rows (threshold)J=0.30.50.60.70.750.80.9
14 × 8 (0.72), theory / measured0.00 / 0.000.05 / 0.040.21 / 0.200.56 / 0.560.77 / 0.730.92 / 0.921.00 / 1.00
28 × 4 (0.43)0.20 / 0.200.84 / 0.830.98 / 0.961.00 / 1.001.00 / 1.001.00 / 1.001.00 / 1.00
8 × 14 (0.86)0.00 / 0.000.00 / 0.000.01 / 0.010.05 / 0.050.13 / 0.100.30 / 0.240.87 / 0.89

More rows per band make the curve steeper and later; more bands make it earlier.

On the crawl (demo 04 Part C), there are 2,506 true extra copies. Exact dedup leaves 1,201 of them. MinHash leaves 217, but merges 519 distinct contents, almost all spam. Spam pages are built from the same eight slogans, so different spam pages really are 75%-similar. (A merge there is harmless; a merge of two different good pages would lose content.)

Memorization, measured (demo 04 Part D): 6,000 base pages, plus 40 pages planted with 1, 3, 10 or 30 copies; two epochs. “Verbatim” means that, given the first half of a page, greedy decoding reproduces the next 8 tokens exactly.

corpusheld-out NLLseen 1×3×10×30×
with duplicates1.072NLL 1.12 / 2%0.98 / 2%0.86 / 2%0.65 / 20%
deduplicated (same steps)1.0451.08 / 0%1.00 / 0%0.98 / 2%0.98 / 0%

The model’s loss on a page falls steadily with the number of copies. At 30 copies, a fifth of the pages can be regurgitated from a prompt. Deduplication returns them to the level of any page seen once. Copies made up 21% of the duplicated corpus; at equal steps, its held-out NLL was 0.027 worse (one seed each, so a small cost).

Too much deduplication can hurt. FineWeb first deduplicated across all 96 snapshots together. In the oldest snapshots this removed up to 90% of the data. Models trained on the kept 10% were worse than models trained on the removed 90%. Their explanation: content that keeps reappearing in later crawls is the content people keep online, which is often the good content. What survives global dedup in an old snapshot is disproportionately the junk that never reappeared. FineWeb therefore deduplicates each snapshot separately. Good content then appears once per snapshot, a mild natural upsampling.

Measured (demo 04 Part E), honestly: in Web World this effect did not appear. The pages that global dedup kept from the oldest snapshot were 100% good English, vs 95.2% in those it removed. An LM test gave 2.695 vs 2.664 nats, within seed-to-seed noise (0.086). The reason is instructive. The junk that survives Web World’s filters is templated spam, which reappears (as near-duplicates) in every snapshot, so global dedup removes old spam too. FineWeb’s explanation needs junk that is unique and short-lived. Whether a dedup strategy helps depends on how the junk of your data is generated, which is why FineWeb decided by ablation, not by argument.

5.7 Judging a step: ablate with small models

Precision and recall need the truth, which real data does not have. FineWeb’s method is to train a small model on the output of each candidate pipeline, at the same token budget, and compare benchmark scores.

Measured (demo 03 Part F, equal budgets of ~39,000 tokens, 8 epochs, held-out NLL per domain):

trained onreviewserrandsmath
raw: all tags stripped3.7703.6342.477
+ language ID1.9711.3289.210
+ rules + exact dedup (the full funnel)1.4680.95410.108

Each step improves the domains it keeps, and the full pipeline cuts review NLL from 3.77 to 1.47. The math column records what the pipeline threw away: an evaluation suite without a math task would never notice.

5.8 Coverage: classifier filtering

The data determines the data distribution, and hence the model: pθ≈pdatap_\theta \approx p_{\text{data}}. Generic web data is not math data, not educational data and not code data, in content or in proportions. If a capability matters, its domain must be covered.

Classifier filtering: train a classifier to detect the desired data, then use it to select it. Two well-known examples:

  • OpenWebMath (Paster et al., 2023): a math-specific extractor that keeps LaTeX, plus a “MathScore” classifier, applied to Common Crawl. The result is ~15B tokens of mathematical web text.
  • FineWeb-Edu (Penedo et al., 2024): Llama-3-70B-Instruct rated ~450–500k FineWeb pages for educational value (0–5). A small, fast classifier trained on those ratings scored all 15T tokens. Keeping pages scored ≥ 3 gives ~1.3–1.4T tokens, on which models do markedly better on knowledge and reasoning benchmarks.

The pattern: an expensive judge labels a sample, and a cheap model scales the judgment.

Measured (demo 05 Part A, a crawl of 5,000 originals with 384 math pages). An “annotator” labels random pages; it misses 10% of math and calls 1% of other pages math. A bag-of-words logistic regression (Lecture 1) trained on those labels gives, at P(math) ≥ 0.8:

annotated pagesfeatureslabeled mathprecisionrecallmain false positives
600unigrams30 (5 wrong)99.5%95.3%spam (1)
600unigrams + bigrams30 (5 wrong)53.0%86.2%spam (293)
2000unigrams + bigrams83 (9 wrong)97.8%94.3%links (4)

Six hundred labels recover the domain the generic pipeline deleted. The middle row is the cautionary tale. With only ~30 positive labels, a few mislabeled spam pages taught the more expressive bigram model that “order|today” and ”!|cheap” mean math. Because spam is heavily duplicated, it then kept 293 spam pages. When the target class is rare, label noise and model capacity interact; more labels fix it.

5.9 Mixtures

In practice a pretraining set is a mixture of sources (LLaMA’s table in §4.2). How much of each? At a fixed token budget, more of one domain means less of another.

Measured (demo 05 Part B, 48,000-token budget, “facts” = accuracy on all 100 prompts “a + b =”):

math sharemath repeatsfacts correctNLL reviewsNLL errandsNLL math
0%0.00%1.5691.0429.488
5%0.211%1.6031.0541.622
15%0.719%1.6791.0961.427
30%1.324%1.8051.1401.356
50%2.226%2.0291.2541.331

Coverage decides what the model can do: no math in the mix, no arithmetic. The first 5% buys most of the math loss (9.49 → 1.62). Every further share is paid for by the other domains: review NLL rises from 1.57 to 2.03.

How AI2 chooses the mixture (OLMo 3):

  1. Classify documents into topics and quality levels.
  2. Train many small models, each on a different mixture over topics.
  3. For each evaluation task, fit a regression f(mixture)→f(\text{mixture}) \to task performance.
  4. Solve for the mixture that optimizes the average task performance, subject to constraints: the token budget, and a maximum number of repeats per source. Muennighoff et al. (2023) found up to ~4 epochs of repeated data cost little.
  5. When upsampling, favor the high-quality documents of a topic.

Measured (demo 05 Part C): nine proxy runs at random mixtures of reviews / errands / math; per domain, a regression NLLd=c0+∑jcjlog⁡(wj+0.02)_d = c_0 + \sum_j c_j \log(w_j + 0.02); the optimum found on a grid under a 4-repeat cap; then check runs:

mixturew (rev, err, math)average NLL (measured)predicted
natural (pool sizes)0.54, 0.30, 0.161.3901.376
natural, another data sample0.54, 0.30, 0.161.3821.376
uniform0.33, 0.33, 0.331.4431.398
regression optimum0.40, 0.40, 0.201.4171.345

Here the method did not pay off, and the numbers say why. Drawing the same mixture twice changes the result by only 0.008, so training noise is not the problem. The regression, however, is off by up to 0.072, more than the gaps it must rank. Its optimum came out 0.027 worse than the natural mixture. With 9 proxies and a simple log-linear form, the fit is the bottleneck. AI2 (and RegMix, Liu et al., 2024) fit such regressions on many more small runs, and validate the chosen mixture at larger scale. The recipe is sound; its reliability is bought with proxy runs.

5.10 Recap and real datasets

  • Web data gives large quantities of text.
  • Extract, filter and deduplicate to improve quality.
  • Filter with classifiers to cover the desired domains.
  • Mix web data with other sources to make a pretraining dataset.
datasetyeardomaintokens
FineWeb2024web15 trillion
RedPajama v22024web30 trillion
Dolma2024mix3 trillion
OLMo 2 mix2025mix4 trillion
Dolma 32025mix6 trillion
OpenWebMath2023math web pages15 billion
AlgebraicStack2023math code11 billion
FineWeb-Edu2024educational web1.4 trillion

OLMo 3’s stages illustrate the whole lecture:

  1. ~5.9T tokens of broad pretraining on the Dolma 3 mix;
  2. ~100B tokens of “midtraining” on a smaller, higher-quality mix (math, code, QA, instruction-like data);
  3. ~50B tokens to extend the context length.

Coverage and quality are adjusted during training, not only before it.


6. Thinking about pretraining at scale (preview)

Pretraining is spending compute. For a Transformer with NN parameters trained on DD tokens, the forward and backward passes cost about C≈6NDC \approx 6ND floating-point operations (Kaplan et al., 2020). For example, 6×7B×2T≈8.4×10226 \times 7\text{B} \times 2\text{T} \approx 8.4\times10^{22} FLOPs for Llama 2 7B. Given a budget CC, should we make the model bigger or the data larger? Lecture 7 answers with scaling laws. The compression view of §2.3 already hints at the answer: a model is only worth its size when it sees, and is used on, enough data.

The slides close with the Adam optimizer — momentum, RMSProp-style normalization and bias correction — as the standard choice for pretraining. Lecture 5 §5.1 derives it and implements it from scratch (code/lecture05/04_training_details.py).


7. Summary

  1. Pretrain, then adapt: one base model, adapted by prompting (Lecture 7) or fine-tuning (Lecture 8). Reasons: transfer, less task data, better performance, one model for many tasks.
  2. Masked LM (BERT): predict 15% corrupted tokens from both sides; 80/10/10 corruption so visible tokens are represented too (repair of a wrong word: 70% vs 11%). It optimizes a pseudo-likelihood, not a likelihood (exp(PLL) sums to 420 over Errand World). It learns from ~15% of positions per pass, so long-distance links took ~6× the epochs.
  3. Causal LM (GPT): maximum likelihood = minimum KL = compression. Loss = entropy + KL (0.760 = 0.754 + 0.006). Arithmetic coding turns the LM into a coder within 0.16% of its NLL (0.25 bits/char vs bz2’s 0.48), but counting the model’s size it pays off only after ~340k sentences.
  4. Why transfer works: web text contains natural demonstrations of tasks (GPT-2). With rating lines in the pretraining text: zero-shot 77.7%, probe 78.2% with 100 labels (scratch 54.4%). Without them: 37.6% / 52.3%. With 2,000 labels, pretraining gave a head start but not a higher ceiling on this small task.
  5. Evaluating a base model: loss (smooth, cheap) vs task metrics (capability, noisy); zero-shot accuracy rose 58% → 76% while the loss moved 0.05 nats.
  6. Data quality: extraction (boilerplate was 48% of naive text), language ID (math 0% kept), heuristic rules (97% recall of junk at 78% precision; they erase math), deduplication (exact leaves 1,201 copies, MinHash 217; 30 copies → 20% verbatim recall). Judge each step by small-model ablations.
  7. Coverage: classifier filtering (600 labels → 99.5% precision math filter; a richer model memorized label noise to 53%), and mixtures under a budget (math 0% → 26% facts, at a cost on other domains); regression on proxy runs needs many proxies to rank close mixtures.
  8. Per-snapshot vs global dedup is an empirical question: FineWeb found global dedup harmful; Web World, whose junk is templated, did not.

Common pitfalls

  • Training on boilerplate. Naive tag stripping doubled the text with menus and footers, which get memorized and waste compute.
  • Treating language ID as quality. Spam passes it; math, code and tables can fail it.
  • Trusting a filter without measuring its false positives. The stop-word rule removed every math page; the “few words” rule removed mostly good short reviews.
  • Exact-only deduplication. It left 1,201 of 2,506 copies; near-duplicates need MinHash.
  • Deduplicating “as much as possible”. Merging across snapshots changed the composition of FineWeb’s data for the worse. Ablate the strategy.
  • Using an MLM’s pseudo-log-likelihood as a likelihood. It is not normalized (Σ exp = 420).
  • Masking 100% of chosen tokens. The model then learns nothing about visible tokens, which is all a fine-tuning input contains.
  • Comparing a masked and a causal LM at equal epochs. The MLM got ~15% of the training signal per epoch.
  • Expecting pretraining to teach what the text does not contain. Without ratings, transfer to sentiment almost vanished.
  • Choosing a mixture from a handful of proxy runs. The regression’s error (0.072) exceeded the differences it ranked.
  • Counting a compressor’s rate without its model. An LM coder that ignores its 3.7-million-bit model looks 2× better than bz2; counting the model, it is worse for anything under ~340k sentences.

Exercises

  1. Cross-entropy decomposition. Show H(p∗,pθ)=H(p∗)+DKL(p∗∥pθ)H(p_*, p_\theta) = H(p_*) + D_{\mathrm{KL}}(p_* \Vert p_\theta), and explain why minimizing the training loss minimizes the KL even though H(p∗)H(p_*) is unknown.

    Answer$H(p_*, p_\theta) = -\sum_x p_*(x)\log p_\theta(x) = -\sum_x p_*\log p_* + \sum_x p_*\log(p_*/p_\theta) = H(p_*) + D_{\mathrm{KL}}$. $H(p_*)$ does not depend on $\theta$, so any change of $\theta$ changes the loss and the KL by the same amount; the minimum of one is the minimum of the other (and equals $H(p_*)$ when $p_\theta = p_*$).
  2. Arithmetic coding by hand. A source emits A with probability 0.8 and B with 0.2, independently. Code “AAB” by interval narrowing (A owns the lower 80%). What is the final interval, its width, and about how many bits are needed?

    AnswerStart [0, 1). A → [0, 0.8). A → [0, 0.64). B → upper 20% of [0, 0.64) = [0.512, 0.64). Width 0.128 = 0.8 × 0.8 × 0.2 = P(AAB). About $-\log_2 0.128 \approx 2.97$ bits, plus up to 2 bits to name a point inside, e.g. binary 0.1001 = 0.5625 (4 bits).
  3. Is pseudo-likelihood normalized? Consider two binary tokens, P(00)=P(11)=0.5P(00) = P(11) = 0.5. Compute exp⁡(PLL)\exp(\mathrm{PLL}) for every string and sum. What does the sum tell you?

    AnswerFor "00": $P(x_1 = 0 \mid x_2 = 0) = 1$ and $P(x_2 = 0 \mid x_1 = 0) = 1$, so PLL = 0 and $\exp = 1$; likewise "11". "01" and "10" have probability 0, and so do their conditionals (e.g. $P(x_1 = 0 \mid x_2 = 1) = 0$), so their $\exp(\mathrm{PLL}) = 0$. The sum is 2, not 1: when tokens are strongly dependent, each conditional "explains" the same information twice. (Errand World's sum is 420.)
  4. The 80/10/10 rule. Why does BERT not simply mask 100% of the chosen tokens? Predict what happens to a 100%-[MASK] model’s predictions at unmasked positions, and check against demo 01 Part D.

    AnswerThe loss is only computed at chosen positions, which always show [MASK]; outputs at visible positions receive no training signal, and the model can treat every visible token as correct. At unmasked positions its predictions are untrained: demo 01 found it predicts the visible word itself only 5.9% of the time and repairs a wrong word in 10.8% of cases, vs 94.9% / 70.4% with 80/10/10. Fine-tuning inputs contain no [MASK], so this mismatch hurts.
  5. MinHash. Prove that P(min⁡h(A)=min⁡h(B))=J(A,B)P(\min h(A) = \min h(B)) = J(A, B) for a random permutation hh. Then compute the candidate probability for FineWeb’s 14 × 8 banding at J=0.75J = 0.75.

    AnswerUnder a random permutation each element of $A \cup B$ is equally likely to be the overall minimum. The two minima agree iff that element is in $A \cap B$: probability $\lvert A\cap B\rvert / \lvert A\cup B\rvert$. Banding: $1 - (1 - 0.75^8)^{14} = 1 - (1 - 0.1001)^{14} = 1 - 0.8999^{14} \approx 1 - 0.228 = 0.772$ (demo 04 measured 0.73 on 300 pairs).
  6. Designing a band structure. You want pairs with J≥0.9J \ge 0.9 caught with probability ≥ 0.99 and pairs with J≤0.5J \le 0.5 with probability ≤ 0.01, using k=112k = 112 hashes. Is 14 × 8 good? Try 8 × 14.

    Answer14 × 8: $J = 0.9$ → 0.9996 ✓; $J = 0.5$ → $1 - (1 - 0.0039)^{14} = 0.053$ ✗ (too many false candidates, though they can be verified afterwards). 8 × 14: $J = 0.9$ → $1 - (1 - 0.229)^8 = 0.875$ ✗; $J = 0.5$ → 0.0005 ✓. Neither meets both with 112 hashes; a steeper S-curve needs more hashes (e.g. 20 × 10 = 200: 0.9998 and 0.019).
  7. Why did the control transfer? In demo 02, pretraining without ratings still raised the 100-label probe from 42.8% to 52.3%. Give a plausible reason, and say what experiment would test it.

    AnswerThe LM still learns useful *word* representations — e.g. that "dull" and "boring" occur in the same slots — so a linear layer can separate some polarity words even though no later word depends on the sentiment. Test: probe accuracy by phenomenon (plain adjectives vs negation vs idioms); word-level features should help plain reviews but not negation or idioms. Or compare with a probe on frozen random embeddings of the same size.
  8. A filter audit. A colleague proposes adding “remove pages whose fraction of digit tokens exceeds 30%” to remove tables of numbers. What would you measure before adopting it, and with which data?

    AnswerIts precision and recall per domain (which good pages it removes: math, code, sports results, financial reports), and a small-model ablation: train at equal budget with and without the rule and compare on an evaluation suite that includes the domains it hits (math/code tasks), not only general benchmarks. Demo 03's lesson: a rule that looks harmless on general text can erase a domain your evaluation does not cover.
  9. Compute. Estimate the training compute of LLaMA-65B (1.4T tokens) with C≈6NDC \approx 6ND. How many days would that take on 2,048 GPUs at an effective 150 TFLOP/s each?

    Answer$C = 6 \times 65\times10^9 \times 1.4\times10^{12} \approx 5.5\times10^{23}$ FLOPs. Throughput $2048 \times 1.5\times10^{14} = 3.1\times10^{17}$ FLOP/s → $1.8\times10^6$ s ≈ 21 days. (The paper reports about 21 days on 2,048 A100-80GB.)
  • Assignment 1 — Build your own LLaMa (released 01/28, due 02/12): implementing and loading a LLaMA-style model is the architecture side of this lecture; pretraining data and objectives are what such a model is trained with. These notes do not provide assignment code.

Further reading

  • A. Radford et al., “Language Models are Unsupervised Multitask Learners”, 2019 (course reading) — WebText, zero-shot task transfer.
  • G. Penedo et al., “The FineWeb Datasets: Decanting the Web for the Finest Text Data at Scale”, 2024 (course reading) — every pipeline step justified by ablations; FineWeb-Edu.
  • J. Devlin et al., “BERT”, NAACL 2019; Y. Liu et al., “RoBERTa”, 2019 (dynamic masking, no next-sentence prediction); K. Clark et al., “ELECTRA”, ICLR 2020.
  • H. Touvron et al., “LLaMA: Open and Efficient Foundation Language Models”, 2023.
  • K. Paster et al., “OpenWebMath”, 2023; L. Soldaini et al., “Dolma”, ACL 2024; AI2, “OLMo 3”, 2025.
  • G. Delétang et al., “Language Modeling Is Compression”, ICLR 2024.
  • J. W. Rae et al., “Scaling Language Models: Methods, Analysis & Insights from Training Gopher”, 2021 (the Gopher rules); C. Raffel et al., “Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer” (T5, C4), JMLR 2020.
  • K. Lee et al., “Deduplicating Training Data Makes Language Models Better”, ACL 2022; N. Kandpal et al., “Deduplicating Training Data Mitigates Privacy Risks in Language Models”, ICML 2022; N. Carlini et al., “Extracting Training Data from Large Language Models”, USENIX Security 2021.
  • A. Broder, “On the Resemblance and Containment of Documents”, 1997 (MinHash); J. Leskovec, A. Rajaraman, J. Ullman, Mining of Massive Datasets, ch. 3 (LSH).
  • N. Muennighoff et al., “Scaling Data-Constrained Language Models”, NeurIPS 2023; Q. Liu et al., “RegMix: Data Mixture as Regression for Language Model Pre-training”, 2024.

Preview of Lecture 7 — Scaling laws and in-context learning

Pretraining is spending compute, C≈6NDC \approx 6ND. Given a fixed budget, should we add data, make the model bigger, or both? Lecture 7 measures scaling laws: loss falls as a power law in data, parameters and compute, until it meets the entropy of the data, which Errand World lets us see directly. They are used to pick model size, token count, batch size and learning rate before an expensive run. Then the other way to adapt a base model: prompting. That covers zero-shot instructions, few-shot in-context learning and its odd phenomena (flipped labels, sensitivity to example order), chat templates and system prompts, and chain-of-thought.


术语表 (Glossary, English → 中文)

English中文
pretraining / pretrain-then-adapt预训练 / 先预训练后适配
base model / foundation model基座模型 / 基础模型
adaptation: prompting / fine-tuning适配:提示 / 微调
transfer learning迁移学习
masked language modeling (MLM)掩码语言建模
autoregressive (causal) language modeling自回归(因果)语言建模
denoising / corruption去噪 / 损坏(扰动)
pseudo-likelihood伪似然
encoder / decoder-only编码器 / 仅解码器
linear probe / frozen body线性探测 / 冻结主干
maximum likelihood estimation (MLE)最大似然估计
entropy / cross-entropy / KL divergence熵 / 交叉熵 / KL 散度
compression / arithmetic coding / code length压缩 / 算术编码 / 码长
naturally occurring demonstrations天然存在的(任务)示范
zero-shot零样本
label efficiency标注效率
checkpoint / training trajectory检查点 / 训练轨迹
web crawl / snapshot (Common Crawl)网页抓取 / 快照
HTML extraction / boilerplate / main contentHTML 正文抽取 / 样板文本 / 正文
language identification语种识别
heuristic filter / stop word启发式过滤 / 停用词
precision / recall / false positive精确率 / 召回率 / 假阳性(误删)
deduplication: exact / fuzzy (near-duplicate)去重:精确 / 模糊(近似重复)
shingle / Jaccard similarity片段(n 元组)/ Jaccard 相似度
MinHash / locality-sensitive hashing (LSH) / band最小哈希 / 局部敏感哈希 / 分带
memorization / regurgitation / verbatim记忆 / 原样复现 / 逐字
ablation消融实验
coverage / domain覆盖度 / 领域
classifier filtering / annotator分类器过滤 / 标注者
data mixture / upsampling / repetition (epochs)数据配比 / 上采样 / 重复(轮数)
proxy model / regression代理模型 / 回归
midtraining中期训练
compute (FLOPs)计算量(浮点运算次数)
← 返回课程目录