Skip to main content

Preparing a corpus for pretraining

Provenance, filtering, deduplication, splits, and tokenizer fitting

A model is not trained directly on “the internet” or on an abstract collection of text: it consumes sequences built from selected and transformed sources. Corpus preparation defines what enters the experiment, what must remain independent for evaluation, and which transformations must be auditable. This work is distinct from tokenizing a prompt and from constructing training windows.

Questions and exercises: Open the dedicated practice page.

By the end of this page, you will be able to: - define eligible sources and preserve provenance and usage conditions; - distinguish parsing, filtering, deduplication, and tokenizer normalization; - choose splits that match the generalization claim an evaluation is intended to test; - fit and freeze a tokenizer without contaminating a held-out evaluation; - design a traceable annotation protocol and interpret annotator disagreement; - hand a prepared corpus off to encoding and training-example construction.

1. A chain of decisions, not a universal recipe

Stage Question to document Possible operations Evidence to retain
1. Scope the sources Which sources are relevant and eligible for the objective? Select sources, time range, languages, domains, and document units Source identifiers, provenance, licences/rights, collection dates, and constraints
2. Parse How can comparable content be extracted from source formats? Extract text and metadata, decode, handle malformed or empty documents Parser version, errors, extracted fields, and rejection rules
3. Filter Which items are out of scope or below the required quality? Documented language, quality, spam, safety, or policy filters Rules, thresholds, before/after counts, and audited samples
4. Deduplicate Are repeated or near-identical items over-represented? Exact deduplication; approximate detection where justified Method, thresholds, duplicate groups, and retention decisions
5. Split Which unit must remain independent for evaluation? Split by source, document family, user, or time; audit overlap Split identifiers, any random seed, grouping rules, and audit results
6. Fit the tokenizer Which text may influence the vocabulary and rules? Train on permitted data, then freeze an exact revision Fitting corpus, configuration, version, vocabulary, and fingerprint
7. Encode and hand off How can a reproducible token stream be produced? Encode with the frozen tokenizer, handle boundaries, and serialize Tokenizer revision, encoding parameters, statistics, and provenance

The exact order depends on the corpus and protocol. For example, deduplication may precede splitting to prevent exact copies crossing partitions; a group-aware split followed by a cross-partition near-duplicate audit may be preferable in other settings. The requirement is not a dogmatic order: make the strategy that supports the generalization claim explicit and verify it.

2. Deduplication and split leakage

Evaluation leakage occurs when information that should remain independent influences training or makes evaluation artificially easy. Exact copies are an obvious case; near-duplicates, overlapping chunks, documents from the same family, or items after a temporal cutoff can also create dependencies.

  • Define the separation unit from the evaluation question: document, author, source, user, group, or time period.
  • Do not assume a random split of chunks guarantees independent partitions.
  • Audit exact and approximate overlap after splitting, using documented methods and thresholds.
  • Preserve identifiers and provenance needed to explain why a document was retained, excluded, or grouped.

Deduplication is not unconditionally beneficial: removing repetition can reduce over-representation, but it can also alter a corpus’s natural distribution or remove legitimate occurrences. Document the trade-off and measure the effect of the chosen rules.

3. Fit the tokenizer without contaminating evaluation

For a conventional held-out experiment, fit a learned tokenizer on the training partition only, then freeze it before encoding validation and test. Otherwise, its vocabulary or rules may incorporate information from texts reserved for evaluation. This safeguard applies to experiments claiming generalization to unseen data; it does not necessarily describe every industrial pretraining pipeline, which may use different data-construction and tracking conventions.

Keep four operations distinct:

  1. Corpus preparation: source selection, parsing, filtering, deduplication, and document splitting.
  2. Tokenizer training: building its vocabulary and parameters from the fitting corpus.
  3. Tokenizer pipeline: configured normalization and pre-tokenization, applied during training and encoding.
  4. Encoding: converting text into IDs with a frozen tokenizer version.
NoteThree quantities that must not be confused
  • Training-token occurrences: the total number of token instances processed across a corpus or training run. The same token ID can occur many times.
  • Tokenizer vocabulary size: the number of distinct token IDs the frozen tokenizer can emit.
  • Model parameters: the learned numerical values in the neural network.

A corpus containing trillions of token occurrences does not imply a tokenizer with trillions of vocabulary entries. Report the corpus/token budget, vocabulary size, and parameter count separately, with their measurement scope and source.

Normalization and pre-tokenization do not replace document filtering. Conversely, cleaning a corpus does not by itself define tokenizer behaviour.

4. Human annotation and label quality

A corpus intended for training or evaluation may require human annotations. This is not merely adding columns: it turns an application question into an observable task with explicit units, categories, and decision rules.

A defensible protocol should specify:

  • The annotation unit and question: document, passage, complete answer, span, or response pair. An ambiguous task produces ambiguous labels.
  • The annotation guidelines: operational definitions, positive and negative examples, edge cases, priority rules, and a procedure for cases that cannot be resolved.
  • Calibration: have several people annotate a small pilot batch, discuss disagreements, and revise the guidelines before scaling up.
  • Disagreement controls: independently annotate a subset with multiple people, measure agreement using a statistic appropriate to the task, and preserve disagreements before adjudication.
  • Traceability: retain the guideline version, individual responses, adjudication decisions, and dataset versions.

Inter-annotator agreement is a diagnostic of the protocol, not automatic proof of truth. High agreement can reflect overly simple instructions or shared biases; disagreement can reveal genuine task ambiguity. The choice of statistic (for example, raw agreement, kappa, or alpha) depends on the label type, number of annotators, and sampling design.

Chapter 10 of the Hugging Face course illustrates this workflow with Argilla: configuring fields and questions, writing guidelines, collaborative annotation, multiple responses, and export. Argilla is a workflow tool here; it does not replace the scientific definition of the task or analysis of annotation quality.

5. Handoff contract to the next stages

Scaling access: memory mapping or streaming?

Corpus size requires separating data access mode from data quality. The two strategies presented by 🤗 Datasets are not interchangeable:

  • Memory mapping / Apache Arrow: a local dataset can be read and traversed from mapped files without loading all its columns into RAM. Local storage is still required, and disk access and caching still matter.
  • Streaming: an IterableDataset yields examples on demand without necessarily downloading the entire corpus. Some random-access operations are unavailable; transformations and splitting must respect iteration order.
  • Mixing sources: interleaving streams changes the observed distribution. Mixing probabilities or proportions should be explicit, versioned, and justified.

A subtle point: shuffle(buffer_size=N) on a stream does not produce a global random permutation. It shuffles the elements in a bounded buffer and replenishes it as iteration proceeds. take() and skip() depend on that order. A fixed seed helps reproducibility, but does not replace a stable, verifiable, leakage-safe split protocol. Define train/validation/test units before turning the stream into training examples, and retain enough provenance to audit the partitions.

Takeaway: memory mapping and streaming solve access and memory constraints; they do not filter data, check rights, deduplicate the corpus, or guarantee representativeness.

See Hugging Face — Big data, memory, and streaming, especially the distinction between mapped files and IterableDataset, buffer-based shuffling, and source interleaving.

Dataset cards: documenting the shared artifact

An internal provenance register and a public dataset card have complementary roles. The latter helps users understand and reuse a published dataset. At minimum, it should describe the objective and intended uses, sources and versions, known licence or access conditions, collection and transformation methods, splits, fields, languages, filtering criteria, known limitations and biases, and privacy precautions.

A dataset card does not prove that data may legally be reused and does not replace provenance logs, leakage checks, or risk analysis. It makes decisions and limitations visible; it does not validate them.

The Creating your own dataset lesson connects corpus construction, Hub publication, and writing a dataset card.

At the end of this stage, it should be possible to recover:

  • sources, licences/rights, dates, and collection rules;
  • parser and filter versions, with before/after counts;
  • deduplication parameters and overlap audits;
  • split definitions and leakage checks;
  • the exact tokenizer configuration and revision;
  • encoding statistics and document-boundary rules.

The prepared corpus can then be encoded into token streams. The training examples page covers the next stage: input-target shifting, windows, packing, padding, and masks. The text and data page retains the shorter inference path from prompt text to initial representations.

TipRevision sheet — preparing a corpus
  • Provenance before volume: define the objective, eligible sources, rights, dates, and document unit.
  • Traceable transformations: version parsing, filtering, deduplication, and retention rules; preserve counts and audit samples.
  • Splits matched to the question: separate genuinely independent units (source, family, user, or time period) and check overlap after splitting.
  • Tokenizer without leakage: for a conventional held-out evaluation, fit the tokenizer on training data, then freeze its version before encoding validation and test.
  • Handoff contract: pass token IDs with provenance, tokenizer version, encoding parameters, useful statistics, and document-boundary rules.

Limitations

This page defines a traceability framework and separation of responsibilities, not a legal policy, universal filtering recipe, or ready-made contamination detector. Thresholds, tools, and split units must be justified by the data, applicable rights, and the experimental claim being made.

Supplementary resources Experiment, explore further, and practise the ideas from this lesson.

Additional implementation resources