25 / 28 · Scaling and LLM Pretraining
Pretraining data for large language models
Trace a documented data pipeline through extraction, filtering, deduplication, evaluation overlap, sampling and packing with newly composed tiny documents.
Scaling laws and compute-optimal training · Corpora and evaluation · Tokenization
On this page 10
Baseline: train on the raw crawl#
The scaling calculation treated a processed training token as a unit of budget. A web collection does not arrive in that form. A page may mix an article with navigation, repeat another page, contain an evaluation answer or have no documented permission for the intended use. Counting all of it equally hides decisions that change both training and evaluation.
Here the working collection consists of five short documents written for this note. It is not a sample from a crawl or a substitute for a representative language corpus:
| ID | Original text |
|---|---|
| d1 | Keep the amber crate beside the gate. |
| d2 | KEEP the amber crate beside the gate! |
| d3 | Keep the amber crate beside the wall. |
| d4 | Move the blue box beside the gate. |
| d5 | The lamp is stored inside bay seven. |
Their small differences let us inspect normalization, duplicate detection and overlap exactly. No third-party dataset is needed to run the example.
The pipeline from crawl to batches#
A reproducible pipeline needs an inventory before a token count. For each input, retain its source, revision or collection date, intended use and rights decision. Keep the original identifier through extraction and filtering, then record the transformation versions, rejection reasons, duplicate groups, split assignment and mixture weight.
One useful order is: select permitted sources; extract text; apply language and quality checks; form duplicate groups; reserve evaluation material and check overlap; construct the training mixture; tokenize and pack. Privacy review and removal requests can require revisiting earlier stages. This ordering is a planning design for the example, not a claim that every corpus uses the same pipeline.
Rights and technical quality are separate decisions. A clean, deduplicated document can still be unsuitable for use. A license attached to collection software does not by itself clear the documents it processes. The examples here remain entirely within the newly composed collection.
Extraction: from HTML to text#
Text extraction decides which characters become training evidence. Consider the original fragment:
<nav>Library</nav><p>Store <b>amber</b> crates.</p><script>secret()</script>
The small standard-library parser in the accompanying calculation collects text nodes, inserts spaces around paragraph boundaries and excludes script and style contents. Its output is Library Store amber crates. It did not identify the article: navigation is still present. Removing tags and extracting the main content are different operations.
The parser never executes JavaScript. It is a demonstration for this well-formed fragment, not a general browser renderer, sanitizer or production extractor. Images, tables, broken markup and layout-dependent reading order require additional decisions. Preserve document boundaries and enough source metadata to inspect extraction errors later.
Language identification and quality filtering#
A language detector supplies a prediction, not a guarantee. Short text, mixed languages and code make a single document label especially coarse. A quality score likewise reflects a chosen target: filtering for similarity to one reference collection can exclude useful text outside its style.
Dodge et al. (§2 and §5–§6) document how C4’s filtering affected what remained and what was excluded. In particular, a word blocklist removed some non-offensive material and affected language varieties differently. No examples or filters from that corpus are imported here.
For an actual pipeline, inspect accepted and rejected samples by language, length and source, and report retention rates. Our five documents cannot measure those effects. Even their normalization is deliberately narrow: lowercasing and keeping [a-z]+ words suits these English strings, but would erase Cyrillic letters and discard meaningful digits. It must not be promoted to a multilingual preprocessing rule.
Deduplication#
Exact matching first needs a definition of equality. Raw d1 and d2 differ; after our chosen normalization both become keep the amber crate beside the gate. Hashing that normalized string gives the same SHA-256 for both. Store the normalization version with the hash and, when resolving a match, compare the normalized content. A digest is a convenient lookup key, not proof of authorship or semantic identity.
Near-duplicate detection asks a different question. Represent a document by the set of adjacent word pairs, or bigrams. Repeated occurrences count once in this set. For d1, the six elements are keep the, the amber, amber crate, crate beside, beside the, and the gate. The last pair in d3 is instead the wall. With sets and , their Jaccard similarity is
The value is high despite a change in the location being described. A threshold such as would group these two instructions. Whether to keep both depends on the application; textual overlap is not semantic equivalence. Short shingles also create many incidental matches. Lee et al. (§4) distinguish exact substring matching from approximate document matching; those catch different kinds of repetition.
MinHash estimates set overlap without storing every pairwise intersection. In the ideal construction, choose one uniform random ordering of the union and retain the earliest element of each nonempty set. These two representatives coincide exactly when the earliest union element belongs to the intersection. Every union element is equally likely to be first, so
For our seven-element union, there are orderings. Exhaustive enumeration gives 3600 matches, and . This verifies the identity for the constructed pair; it is not a scalable implementation. Averaging match indicators over independent orderings estimates Jaccard similarity. Li and Li (§1.1) state this classical estimator; their newer circulant construction is outside this note.
Real implementations replace ideal orderings with specified hashing schemes and candidate-search procedures. Signature length and candidate thresholds influence error; a single matching signature does not certify a duplicate. Empty sets need an explicit convention. Our code assigns two empty shingle sets similarity one, but such documents should be handled separately before corpus deduplication.
Decontamination against evaluation sets#
Duplicates within training overrepresent some text. Overlap between training and evaluation threatens a different claim: how well the model handles material it has not seen. Dodge et al. (§4.2) distinguish overlap of task inputs from overlap that includes target labels or outputs. Both deserve inspection, but they do not imply identical exposure.
Take our invented evaluation question, Where is the amber crate beside the wall? Its bigram set shares five pairs with d3: the amber, amber crate, crate beside, beside the, and the wall. A lexical rule can flag this relation; it cannot prove whether the model memorized an answer, or detect every paraphrase.
Assign whole duplicate groups to splits before training, and check held-out examples against the eventual training collection. Keep match evidence and the action taken. Do not tune removal thresholds on the final test score and then call that test independent. A clean lexical scan is bounded evidence about its matching rule, not a certificate that no evaluation information remains.
Safety and personal data#
Sensitive information can be present even in technically valid text. Pattern matching can catch some formats; it also has false positives and misses context-dependent disclosures. A toxicity score does not decide whether a passage is a quotation, criticism or an instruction. Privacy, content suitability and source permission need distinct review decisions.
For a real collection, define what may be retained, who may inspect it and how a document can be removed from future versions. Avoid publishing raw sensitive examples in audit logs. A hash or identifier can support a removal workflow without reproducing the text in every report. None of the five constructed documents contains real personal information, so this example does not evaluate a privacy filter.
Mixture weights and epochs#
After filtering, mixture weights control exposure. Suppose two sources have and tokens available, and we draw training tokens with source probabilities . Within each source, assume uniform token sampling with replacement. The expected number of times each token from source appears is
Thus and . Equal source weights produce four times as much exposure per available token in the smaller source. These are expected exposure counts, not a guarantee that every token appears that often. Sampling documents uniformly would require a different calculation when document lengths differ.
This also shows why processed tokens and unique tokens differ. Increasing the weight of a small source changes repetition as well as domain balance. Record sampling units and replacement rules alongside weights; otherwise the mixture cannot be reconstructed from the percentages alone.
Tokenization and batches#
Tokenization changes lengths; packing changes how those lengths share memory and context. Suppose three documents have lengths four, three and five, including an end marker. Padding each to length five uses 15 slots. Concatenating the 12 tokens into two packs of width six removes those unused slots.
Removing padding does not determine the attention semantics. If the documents remain independent and their complete contexts are preserved, the number of permitted causal query–key pairs is
Two unrestricted causal packs of width six instead permit pairs. Some connect different documents, while splitting a document across packs can remove its earlier context. An end token alone does not enforce an attention boundary. The two totals describe different layouts, not equivalent computations or measured runtimes.
To preserve an intended document-level objective, specify boundary masks, position handling, target-loss masks and the policy for split documents. Independent blocks that retain complete documents can reproduce their separate contexts; arbitrary concatenation into fixed windows generally cannot. Padding positions should not enter the language-model loss denominator.
What changed#
A token budget now has an auditable route back to documents and transformations. Normalization changed which strings counted as equal; shingling exposed a near match; evaluation matching identified a possible leak; mixture weights altered repetition; and packing required an explicit context policy. Each decision affects a different property of the resulting training stream.
Limitations#
Five invented English documents and a well-formed HTML fragment establish only exact behavior on these inputs. They do not test multilingual extraction, production hash performance, semantic decontamination, privacy detection or downstream model quality. No web corpus is downloaded or model trained. The source papers explain mechanisms and observations; their dataset availability is not permission to reuse every underlying document.
What you should remember#
Document source decisions and transformations before reporting token counts. Separate exact equality, approximate overlap and evaluation exposure. Check what filters exclude as well as what they retain. State the sampling unit for mixture weights and the context boundaries for packing. A technically successful pipeline does not settle source rights.
Code#
This self-contained standard-library example checks normalization, bigram overlap and every ideal ordering for d1 and d3. It fetches nothing and uses only the strings printed above.
import itertools
import re
from fractions import Fraction
def words(text):
return re.findall(r"[a-z]+", text.casefold())
def pairs(text):
tokens = words(text)
return set(zip(tokens, tokens[1:]))
d1 = "Keep the amber crate beside the gate."
d2 = "KEEP the amber crate beside the gate!"
d3 = "Keep the amber crate beside the wall."
a, b = pairs(d1), pairs(d3)
match = total = 0
for order in itertools.permutations(sorted(a | b)):
left = next(x for x in order if x in a)
right = next(x for x in order if x in b)
match += left == right
total += 1
print(words(d1) == words(d2))
print(len(a & b), len(a | b), Fraction(len(a & b), len(a | b)))
print(match, total, Fraction(match, total))
True
5 7 5/7
3600 5040 5/7
Next#
Continue to fine-tuning. After deciding what enters pretraining, adaptation introduces a new supervised collection, split and objective; those need their own provenance and evaluation checks.
References#
- Dodge et al. (2021), Documenting Large Webtext Corpora: A Case Study on the Colossal Clean Crawled Corpus, §2, §4.2, §5–§6. Filtering, evaluation contamination and corpus documentation.
- Lee et al. (2022), Deduplicating Training Data Makes Language Models Better, §4–§5.3. Exact and approximate duplicate detection and split overlap.
- Xiaoyun Li and Ping Li (2022), C-MinHash: Improving Minwise Hashing with Circulant Permutation, §1.1. The classical independent-permutation MinHash estimator only.
The papers are conceptual references. No corpus excerpt, source code, figure, model asset or benchmark result is redistributed. All working documents, the HTML fragment, evaluation question and numerical cases were composed for these notes.