Lecture guides›
✎

Lecture guide: Data: filtering, deduplication, mixing, synthetic data#

Lecturer: course staff · Course: Stanford CS336 Language Modeling from Scratch, Spring 2026, lecture 14 · Length: 1:26:00 Video: watch on YouTube Chapters that cite this lecture: 10. Training Data

In one sentence: Percy Liang walks the pretraining data pipeline step by step, text extraction, filtering with fast classifiers, deduplication with minhash and locality-sensitive hashing, mixing sources by regression at small scale, and ends with the synthetic data that post-training now runs on.

Before you watch#

This continues the previous lecture, which covered where data comes from and the law around it; the extraction of text and the data sets were introduced there. The middle third is an algorithms lesson, Jaccard similarity, minhash and banded hashing, which needs only comfort with probability. The last stretch is on post-training data, mostly for coding. The video has no chapter marks. The chapter Training Data follows the pipeline in the same order.

The lecture, part by part#

0:00–6:00 Transformation: HTML and PDFs into text#

Data does not fall from the sky: the internet is live services whose content must be dumped or crawled, then processed, under terms of service and copyright that call for a licence or fair use. Today: the pipeline itself, then post-training data. Transformation first. Raw data is not text: Common Crawl holds HTML, sometimes PDFs, and GitHub repositories are directories. Most of the work is on HTML, and it is heuristic: strip the boilerplate, navigation and advertisements, and extract the content. What counts as content is not always clear, since navigation might teach a model what pages look like. Images and tables raise their own questions. The process is inherently lossy, since HTML, hierarchical or visual, becomes a line of tokens. Simple tables render as markdown, nested tables defeat the converter, which must approximate or give up. Processors are rule-based because they must be fast and need little intelligence; model-based extraction could do more if it were fast enough. Imperfections remain, and the choice of tool matters: on the extended DCLM evaluations Resiliparse extracted better text than the alternatives. PDFs are the subject of Hugging Face's FinePDFs: a PDF must be rendered, Common Crawl holds some, often truncated because files are large, which calls for a new crawl, and some are scans, so conversion means optical character recognition with a vision-language model, far costlier than text. They are a small share of the web and a valuable one, since anyone who makes a PDF probably had something to say, though a PDF is all about layout and keeps less semantic structure than HTML's headings and paragraphs. In this book: Training Data › 2. Transform.

6:00–12:00 Filtering: the general skeleton#

Filtering has one shape. There is a small amount of target data, high quality, and a vast amount of raw data, and the task is to find a subset of the raw data that resembles the target. The reasons vary: language identification, quality, toxicity. Two demands follow: the method must generalize beyond the target, which is already in hand, and it must be extremely fast, since it runs over the whole internet, a hundred trillion tokens, and keeps a single-digit share. The scheme fits a model from target and raw data to obtain a score and keeps documents by score. Two kinds of model serve. A generative model of the target data, kept cheap: KenLM, a five-gram model whose perplexity ranks documents. More common now is a classifier: the target data as positives, a random subset of the raw data as negatives, trained with fastText, which is close to a linear model over words. Each new document is scored, and a threshold set by the quality bar keeps it, sometimes stochastically. Data sets of a few years ago avoided model-based filtering to stay unbiased; now everyone filters with models unless compute is plentiful, in which case one can train on everything. The first instantiation, language identification: Meta's fastText models cover 176 languages, trained on multilingual sites, and the problem is easy, a few words suffice, with subtleties only for code-switching and dialects. It is not a bottleneck. In this book: Training Data › 3. Filter.

12:00–16:00 Filtering in practice: mathematics, GPT-3, Phi-1, toxicity#

To gather data of one kind, say mathematics, a pipeline of several filters is built, as in OpenWebMath: rules that look for LaTeX commands, a KenLM model trained on a corpus of proofs with a perplexity threshold, and a fastText classifier for mathematical writing with two thresholds, a lower bar when LaTeX is present and a higher one when it is not. The result, 15 billion tokens, trained models better at mathematics than models trained on twenty times more unfiltered data. Quality means whatever one defines it to mean. GPT-3 fits the skeleton with Wikipedia, WebText and some books as positives and random web pages as negatives, keeping what a linear classifier scores highly; LLaMA 1 used pages that Wikipedia cites. Phi-1, from Microsoft, starts from a Python subset of The Stack, has GPT-4 judge a subset of it by educational value with a prompt, keeps the positives as the target, and trains a cheaper classifier, a random forest, to select from the rest; the selected data trains a better model in fewer steps. Toxicity works the same way with the Jigsaw corpus of Wikipedia talk pages annotated for toxic comments. In this book: Training Data › 3. Filter · Training Data › What the practitioners say.

16:00–22:00 No optimal threshold: quality depends on the training budget#

What one wants from data depends on the model to be trained, in particular on how many tokens it will train on, so there is no optimal threshold: 0.9 is not "best". A longer run tolerates lower quality; a shorter one wants higher quality. Given a fixed pool, a preliminary experiment makes this concrete: a 157-million-parameter model trained on a tiny fraction of Common Crawl, filtered as DCLM filters or nearly unfiltered, for epoch after epoch. The filtered data starts far lower; the unfiltered data starts worse and keeps falling as the epochs accumulate, until with many tokens the high-quality data no longer wins. With high-quality data one would stop before overfitting anyway, yet even that point is worse than training longer on low-quality data. In questions: each point is a single run, repeats with confidence intervals would be better practice but each run is expensive, and pretraining runs are in his experience stable; and had one more high-quality data, every data set still has diminishing returns, only lower down. So filtering is critical when compute is constrained, as it is for nearly everyone, and unnecessary with infinite compute. The recipe: decide what good data looks like, either an existing data set or a prompt that has a language model prefilter a pool, and train a classifier that extends that judgement to the whole crawl. In this book: Training Data › 3. Filter · Training Data › What the practitioners say.

22:00–28:00 Duplicates, and why they matter#

Filtered data still contains duplicates. Exact ones come from mirror sites, whose purpose is duplication that a crawler may not recognize, and from forks, which change a few files and leave 99% of a repository the same. Near duplicates differ by a few tokens: licences such as MIT repeated across pages, the headers and footers shared by a site, articles that differ by a comma, and templates in which one country name replaces another, pure waste for a GPU. An audit of C4 found one product description, of a gas mask, 61,000 times. Why deduplicate? For efficiency: the data set shrinks with no loss of information. To avoid memorizing what is repeated, which matters for copyrighted content and privacy. And the related task of decontamination, keeping the test set out of the training set, arguably matters even more. The design space asks three questions: which items, sentences, paragraphs or documents; what counts as a match, exact equality, a shared sub-item or a fraction of shared sub-items; and what to do with a match, remove all copies or all but one. The algorithmic challenge is that filtering judges each item alone, in parallel linear time, while deduplication compares items with items, and the quadratic comparison of everything with everything is impossible at web scale. Hashing is the way out. A hash function maps a value to a much smaller one; two distinct items may collide. The collision-resistant cryptographic kind is unnecessary; the fast kind used for hash tables, where collisions are tolerable, is the one to use. In this book: Training Data › 4. Deduplicate.

28:00–37:00 Exact deduplication; Jaccard similarity and minhash#

Exact deduplication is simple: hash each item and keep one of each, written in a map-reduce style so that it scales. It does not suffice for near duplicates. C4, from the T5 paper, deduplicated spans of three sentences by exact match and removed all but one, which tears three sentences out of a document and breaks its coherence; that, he notes, is what they did. For near duplicates an approximate match must be defined, and the standard is the Jaccard similarity of two sets: the size of their intersection over the size of their union, 3 over 5, hence 0.6, for a set {1, 2, 3, 4} against {1, 2, 3, 5}. Two documents are near duplicates when their similarity exceeds a threshold, say 0.99. Finding them in linear time is a solved algorithms problem, in two steps. The first is minhash: a random hash function under which the probability that two sets collide equals their Jaccard similarity. Usually hash functions are built to avoid collisions; here they are wanted, but controlled, so that similar sets collide more than distant ones. The definition: hash every element of a set and keep the minimum. The reason it works: the hash induces a random order of all elements, and the minima of two sets agree exactly when the first element of that order belongs to both. Among the five elements, three are shared, so the probability is 0.6, which a check with a hundred seeded hash functions confirms. The minhash of each set is computed once, and only collisions are looked for. In this book: Training Data › 4. Deduplicate.

37:00–43:00 Locality-sensitive hashing: bands sharpen the probability#

One minhash is not enough: a collision says only that the similarity equals the collision probability, and that is too stochastic to decide whether two documents lie above the threshold. Locality-sensitive hashing, a classic of theoretical computer science, sharpens it with more independent hash functions. The n functions are split into B bands of r functions each: twelve functions make three bands of four. Two sets collide if in some band all r functions agree, an and within a band and an or across bands; not every function has to agree. The probability follows in two steps. A fixed band matches with probability J to the power r, since its r functions must all agree. No band matches with probability 1 minus that, raised to B; so the probability of a collision is 1 minus (1 − J^r)^B. With a similarity of 0.8, five bands and ten functions per band, it is about 0.4, higher than one band alone would give because there are five tries. In this book: Training Data › 4. Deduplicate.

43:00–48:00 The S-curve, and choosing bands and rows#

Plotted against the similarity, the collision probability is an S-shape from 0 to 1: the sharpening that was wanted, a phase transition in which similarities below a threshold almost never collide and those above almost always do. With ten bands of ten, similarities from 0.7 to 0.98 give collision probabilities from 0.25 to 1: passable. False positives below a chosen threshold can be filtered afterwards; those above are mostly kept. Raising r sharpens the curve and moves it right: matching becomes harder, and the collision probability at 0.7 falls from 0.25 to 0.008. Raising B moves it left: more bands are more chances, and at 0.9 the probability rises from 0.72 to 0.92. The transition can be made as sharp as desired, at growing cost. A real paper used 20 bands of 450 functions, which gives a sense of the magnitudes. The transition sits near (1/B) to the power 1/r, so to catch similarities above 0.9 one picks B and r with that value equal to 0.9 and then sharpens it. At that point the collision probability is about 0.64, the centre of the transition, which goes to 0 below and to 1 above as B and r grow. The method is called minhash LSH, since locality-sensitive hashing works for other hash families and minhash is the one that matches Jaccard. One last note: deduplication must run across the whole data set, not only within a source, because sources repeat each other. In this book: Training Data › 4. Deduplicate.

48:00–54:00 Data mixing: weights over sources#

Extraction, filtering and deduplication happen per source, but a model trains on many. Marin's website tracks the sources of its next model, Nemotron data, FinePDFs, institutional books, code, and The Pile listed its sources years ago. The question is the weights: a data mixture is a distribution over sources. Options: set it by hand on intuition, which happens more often than one would think, even in recent papers; sample uniformly; or sample proportionally to each source's tokens, rational enough, except that a huge low-quality source would eat the budget. Quality argues for upweighting good sources, with two cautions. Sources are often incomparable, literature against code against papers, and a model that does well needs diversity, not all its mass on papers. And every source is finite: too much weight on a small one means epoching over the same tokens, which is bad for reasons soon shown. A worked example: a low-quality source of 10 trillion tokens, a high-quality source of 10 billion, as high-quality sources tend to be, a run of one trillion tokens, and a uniform mixture. The low-quality source is barely touched: the requested half trillion is 5% of it, each token seen once. The high-quality source is seen 50 times. Some large runs have messed this up: a distribution chosen by quality alone ignores how many tokens a source holds. In this book: Training Data › 5. Mix.

54:00–60:00 Watch the epochs: caps, and how a mixture is realized#

Why 50 epochs? One should not: at best it wastes compute, at worst it overfits; the number appears only because a mixture defined without attention produces it. The lesson is to look at the epochs actually run. How is a mixture realized? A batch is filled with sequences, each drawn from one source, so that each batch reflects the mixture; one does not train a step of Python, then a step of C, and sampling is per sequence, not per token, to keep the variance low. The problem has been known for a long time in multilingual training, where some languages have very little data. Earlier work flattened proportional mixing by raising it to a power; one paper made the idea explicit: give every source equal weight, under a hard cap on epochs, say 20, after which a source yields no more tokens. It is a safety net: the probability of a source times the training tokens must not exceed the cap, and a simple procedure finds a mixture under that constraint. In this book: Training Data › 5. Mix · Training Data › Pitfalls.

60:00–66:00 Regression-based mixing#

How should the weights be defined in the first place, with 50 sources and 50 numbers to fill? Proportional mixing is not enough and weighting by a quality estimate is still a heuristic. The most principled and the easiest to follow are the regression-based methods, RegMix and the OLMo work among them. At small scale, say 300 million parameters, a swarm of small models is trained on different mixtures of the sources. Each yields a loss on some target, downstream evaluations or perplexity. A regression is fitted from mixture weights to loss, a cheap model that answers what loss a given mixture would produce, and the mixture for the large model is found by optimizing it. The resemblance to scaling laws is plain: cheap computations first, scale afterwards. The design choices: how mixtures are sampled, often from a Dirichlet distribution; the regression, linear, log-log-linear, or boosted decision trees; the target, where one must not overfit the evaluations, since pretraining is meant to produce a general model, and a target made of code evaluations simply upweights all the code until the poetry suffers, a danger that uniform and proportional mixing do not have; and the size of the proxy models, tens of millions of parameters in the OLMo table, a trade-off between cost and how representative they are. In this book: Training Data › 5. Mix.

66:00–72:00 Two leaps of faith, and epoching at scale#

Two leaps of faith deserve care. The regression is fitted on sampled mixtures and then optimized, and the optimum may lie at an extreme where few mixtures were sampled; a random mixture is predicted safely by ordinary generalization, a pushed one less so. And the optimal mixture must transfer from small to large scale, which at the scales of the open community seems true, or at least not blatantly false, though the optima surely differ: as the filtering experiment showed, a long run tolerates lower quality. One scale effect must be handled explicitly. A small model trained on few tokens never epochs, so its optimum may put most weight on Wikipedia; the large model then epochs on it and overfits. Two fixes exist. Cap the epochs, as the OLMo paper does. Or use simulated epoching: make the small scale look like the large one, the principle behind muP as well. Downsample every source by the ratio of the runs, one in a hundred for runs of 10 billion and one trillion tokens; the small run cannot then train on all of Wikipedia, epochs heavily, shows a bad loss, and the optimizer turns to balanced mixtures. The scarcity of the large regime is simulated at small cost. The lesson: whoever optimizes something risks optimizing the wrong thing. In questions: a source downsampled to too few tokens simply receives little weight, with rounding errors that can skip a source altogether, to be avoided by always training on it once; and mixing also applies inside a data set, as Nemotron and some OLMo work split Common Crawl by topic and by quality, and mix the cells of that grid. In this book: Training Data › 5. Mix · Training Data › Pitfalls.

72:00–78:00 Post-training data: OpenThoughts#

Everything so far was pretraining or mid-training data, task-agnostic by nature. Post-training data depends on the task, and the lecture names a few recent data sets, for coding in particular. The general recipe: define environments, for code perhaps GitHub repositories; define tasks or prompts; collect responses from a strong model, the teacher. In the open community almost all post-training data is generated this way; a human teacher is slow and expensive, though frontier labs now mix human and model work. OpenThoughts was motivated by the reasoning models: how to build good post-training data for mathematics and science. It produced 1.2 million examples with a teacher model, drawing questions from human sources such as Stack Exchange and NuminaMath and from synthetic ones; the coding sources include exercises, code golf and code review. Its analysis of response generation: a few sources beat all sources; sampling several generations, 16 in its case, helps; better models are not necessarily better teachers, since a 32-billion model that is now old and small, QwQ, taught better than DeepSeek R1, then among the strongest open models; and filtering by the correctness of the answer did not help. The pipeline deduplicates, downsamples the questions, generates 16 answers each and assembles the set, so the 1.2 million examples cover a sixteenth as many questions. In this book: Training Data › 6. Synthetic data.

78:00–82:00 Agentic coding data: SWE-smith and SWE-Zero#

More recent is the interest in a model that does software development, not merely writes code. SWE-smith takes a repository, has an agent make it usable, installing its dependencies, and has a language model generate tasks by modifying the code, for instance by introducing bugs; after verification these are task instances, synthetic ones, 50,000 at the time, which was large. NVIDIA's SWE-Zero starts from the observation that software tasks, unlike mathematics, carry heavy dependencies: most GitHub repositories do not run, and installing their outdated dependencies, at the state of an old pull request, is a nightmare. Rather than a Docker image per repository, it relies on the finding that models solve many of these tasks without execution feedback: about 80% with execution against almost 70% without, which suggests some internal sense of what code does. It generated 300,000 agent trajectories on real pull requests, realistic unlike SWE-smith's, with the OpenHands scaffold. Agents try to cheat: the instruction is to explore, test and implement, and the SWE-Zero version forbids running Python and allows only simple text operations, with trajectories distilled from a large coding model and filtered when the model executed anyway. A further 13,000 trajectories do use execution feedback; models fine-tuned on SWE-Zero first and on those second made progress, though the frontier remains high. SWE-rebench is another effort to gather many pull requests. In this book: Training Data › 6. Synthetic data.

82:00–1:26:00 Scaling the trajectories, and a summary#

A paper released that day scales the SWE-Zero idea to 12 million agent trajectories, which SWE-Zero's lightness allows: where SWE-rebench had to make its tasks execute and managed only part of them, SWE-Zero uses every pull request regardless. With so much data a small model suffices. The data sets grow more sophisticated, from the environment-free tasks of mathematics to coding, and a spectrum runs from fully synthetic data through semi-synthetic, a real environment with synthetic tasks, to real tasks. Responses come from capable models that must also teach well. Code environments are a pain, and much filtering has no time in the lecture. The summary: for filtering, define good data, train a lightweight classifier and run it over the crawl; deduplication avoids overfitting and saves FLOPs; mixing tries mixtures at small scale and extrapolates; and post-training data is largely synthetic. Data work is grungy and domain-specific, and it means looking at concrete examples, so the lecture conveys the landscape rather than the work itself. In this book: Training Data › 6. Synthetic data · Training Data › Key takeaways.

What to take away#

Sources#