ELLMEngineering Large
Language Models
Download PDF

Chapter 09

Data Contracts, Provenance, and Normalization

On this page

Removing a source requires tracing it from raw object through normalized records and packed sequences to affected releases and checkpoints. That lineage makes a training dataset a versioned product with an enforceable contract.

A dataset is the result of transformations and gates. Every retained example should have provenance and a reason to exist.
Open full diagram ↗

A dataset is the result of transformations and gates. Every retained example should have provenance and a reason to exist.

Start with the data contract

The word "example" hides several distinct objects:

  • a source object is the retrieved file, page, repository revision, conversation, image, or record;
  • a document is a parsed logical unit with boundaries and metadata;
  • a training example is a selected or generated unit before token packing;
  • a sequence is the tokenizer-specific tensor presented to the model;
  • a dataset release is an immutable manifest selecting exact versions of those objects.

Counts at these layers are not interchangeable. Deduplicating documents can leave repeated substrings inside long documents. Packing can join examples and obscure their source boundaries unless lineage is carried separately. A report that says "we trained on 10 billion examples" is incomplete without the unit, tokenizer, filtering version, and sample weights.

Before building the pipeline, define:

Dimension Questions that determine the implementation
Intended use Pretraining, supervised tuning, preference learning, retrieval, evaluation, or red-teaming?
Unit Document, turn, function, repository, image-text pair, trajectory, or packed sequence?
Rights and policy What use is permitted, for how long, in which products, and under what deletion obligations?
Identity What makes two records the same source revision, the same bytes, or the same semantic example?
Utility Which capabilities should improve, and what evidence makes an example useful?
Risk Privacy, toxicity, security, leakage, poisoning, and representational harms?
Distribution Which domains, languages, difficulty levels, and rare critical slices need what mass?
Reproducibility Can a release be reconstructed byte-for-byte from immutable inputs and versioned code?

Use notation consistently:

  • N is a document or example count, as stated locally;
  • T is a token count under a named tokenizer version;
  • n_d is available token mass in domain d;
  • q_d is the probability of sampling domain d;
  • w_i is the effective training weight of example i;
  • H(bytes) is a cryptographic content digest, not a semantic identifier.

The main design principle is separation of concerns. A policy gate answers "may this data be used?" A corruption gate answers "can it be parsed safely?" A quality score estimates expected utility. A mixture policy decides how often an eligible example should influence gradients. Combining all four into one opaque scalar makes failures difficult to diagnose and reverse.

Source contracts and provenance

For every source, record the acquisition and use contract before expensive processing. At minimum:

  • source namespace, stable source ID, revision, retrieval time, and retrieval method;
  • owner or publisher, asserted license or agreement, policy decision, and decision owner;
  • permitted purposes, geographic or product restrictions, retention period, and deletion obligations;
  • original URI or object location, raw byte digest, media type, and declared encoding;
  • consent or privacy classification where applicable;
  • language, domain, temporal coverage, and known collection bias;
  • parent objects, transformations, generated descendants, and release memberships.

This metadata supports engineering and governance review; it is not a substitute for legal or privacy judgment. Unknown rights should be represented as unknown, not silently mapped to permitted.

Identity is layered

Use different identifiers for different questions:

source_revision_id = H(source_namespace || source_id || revision)

identifies one logical revision from one source. A raw content hash:

raw_content_id = H(raw_bytes)

finds byte-identical objects across locations. A normalized content hash:

normalized_content_id = H(normalizer_version || normalized_bytes)

finds exact duplicates after a declared transformation. These IDs must remain separate. If the source ID is mixed into the content digest, mirrors will no longer deduplicate. If only a content hash is kept, two independently licensed copies become indistinguishable for deletion and rights analysis.

Hashes also have scope. A hash collision is unlikely with an appropriate cryptographic digest, but a digest does not prove authorship, permission, semantic equivalence, or absence of personal information. Store the algorithm and canonical serialization in the schema. The concatenation symbol above denotes an encoded tuple, not undelimited strings: ("ab","c") and ("a","bc") must not both serialize as abc. Use a versioned typed encoding or length-prefixed fields, bind field order, and include an object-type tag so a source identity cannot be confused with a transform identity.

Model provenance as a graph

Represent provenance as a directed acyclic graph:

  • entities: raw objects, parsed documents, normalized examples, synthetic records, shards, manifests, and checkpoints;
  • activities: fetch, parse, normalize, deduplicate, score, generate, verify, sample, tokenize, and pack;
  • agents: source owners, pipelines, models, reviewers, and approving teams.

An output entity points to its input entities and the exact activity version that produced it. A packed sequence may therefore point to several examples; a synthetic answer points to its seed, generator checkpoint, prompt template, decoding parameters, verifier, and adjudication record.

The graph must answer both forward and reverse questions:

  • Which release and checkpoint contain descendants of source object s?
  • Which raw objects, transforms, scorers, and random seeds produced sequence z?
  • Which examples changed when normalizer version v7 replaced v6?
  • Which evaluations used a benchmark item that entered a training release?

Lineage that exists only in logs is fragile. Keep durable edge tables or manifests, version their schema, and test impact queries before an incident.

A minimal record envelope

Example status: Illustrative Python excerpt; not standalone.

from dataclasses import dataclass

@dataclass(frozen=True)
class DataEnvelope:
    source_revision_id: str
    raw_content_id: str
    parent_ids: tuple[str, ...]
    acquisition_time: str
    use_policy_id: str
    transform_version: str
    payload_uri: str
    metadata_uri: str

The payload can remain in object storage while the envelope flows through distributed transforms. Derived records receive new IDs and retain parent edges. Mutating a record in place destroys the ability to explain an old release.

One record through the release

Keep one schematic artifact in view as the next chapters add decisions. The names below are readable teaching IDs, not literal cryptographic hashes. Actual identities bind canonical bytes and transform versions as specified above. The lineage uses the same raw:A, synth:B and pack:C relationship exercised later by examples/data_release.py.

Boundary Artifact and newly recorded fields What remains traceable
Acquisition raw:A: source revision manual@17, raw digest, permitted-use decision and acquisition time Original bytes and source contract
Normalization norm:A: normalized digest, parser/normalizer version and source offsets Parent raw:A; changed whitespace is distinguishable from changed policy text
Duplicate grouping Group g7: norm:A chosen over a mirrored copy by the declared representative rule Both source memberships; shared content does not erase different permissions
Synthetic generation synth:B: a question derived from norm:A, with generator, prompt, seed and verifier result Seed parent and generation activity; a plausible answer is not automatically verified
Mixture selection Selection entry for synth:B: language/domain, eligibility snapshot and effective token weight Why it receives gradient mass; the selection record does not overwrite the source
Token packing pack:C: spans from synth:B and unrelated norm:D, tokenizer and target mask Which positions came from each example and which are scored
Release and consumption release:1: complete shard manifest and validation report; checkpoint:1: consumed release ID Reproducible inputs and affected checkpoints if the source is later revoked

A higher quality score changes the selection record; it does not change raw:A or erase norm:D. Revoking raw:A reaches the synthetic question and packed sequence, while norm:D remains independently eligible and can be repacked. A tokenizer change instead creates a new packed representation and release without requiring a new raw acquisition. Use these differences to decide which stage a proposed change must rerun. The following deduplication, synthetic-data and release chapters supply the algorithms behind these fields.

Worked deletion trace

Suppose repository revision R17 produced 800 parsed files, 620 normalized examples, 410 deduplicated representatives, and 75 synthetic debugging tasks. Three released manifests selected 190 of those descendants, and two checkpoints trained on the releases.

A valid deletion workflow:

  1. tombstones R17 and blocks it from future selection;
  2. traverses all descendant edges, including synthetic records;
  3. creates replacement manifests without affected records;
  4. invalidates caches, indexes, and pending generation jobs;
  5. records which checkpoints and evaluations were exposed;
  6. applies the organization's model-remediation policy;
  7. emits an auditable completion record.

Deleting the current copy of R17 from raw storage is insufficient. It leaves derived shards, packed sequences, indexes, and model artifacts unexplained.

Normalization without erasing signal

Normalization converts heterogeneous source objects into stable, comparable records. It should remove representation accidents while preserving task-relevant meaning. The contract is domain-specific: whitespace collapse that helps web prose can corrupt Python; stripping markup can destroy tables, equations, links, or speaker roles.

Separate parsing from canonicalization

A robust pipeline uses explicit stages:

  1. decode: validate bytes, encoding, decompression limits, and media type;
  2. parse: recover logical structure such as title, headings, paragraphs, code blocks, turns, and tables;
  3. canonicalize: standardize safe representation details;
  4. clean: remove source-specific boilerplate using versioned rules;
  5. segment: create training units without crossing protected boundaries;
  6. validate: check invariants and compare with the raw object.

Keep the raw payload immutable. Store the normalized representation, structured parse, offset map where feasible, normalizer version, and a diff summary. If a later parser improves table recovery, the release can be rebuilt without recrawling or guessing what was removed.

Unicode and encoding choices

Canonical Unicode normalization such as NFC maps canonically equivalent sequences to a stable representation. Compatibility normalization such as NFKC can also fold distinctions including width, superscripts, and some mathematical character variants. That may help identifier matching and deduplication, but it can erase meaning in mathematics, code, linguistics, and historical text. Unicode Standard Annex #15 defines these forms and explains why compatibility normalization must not be applied indiscriminately.

Therefore:

  • default prose may use NFC after valid decoding;
  • code should preserve bytes or apply a language-aware representation;
  • mathematical text should retain compatibility distinctions unless a reviewed transform says otherwise;
  • case folding belongs in a comparison view, not necessarily in the training payload;
  • control characters, bidirectional markers, and zero-width characters need explicit policy and security review.

Do not silently replace decoding errors with an undifferentiated placeholder and then treat the result as clean text. Track replacement count and byte ranges, route high-error documents to quarantine, and retain the original bytes.

Preserve structure that carries supervision

Document and example boundaries affect the objective. Preserve:

  • indentation and newline structure in code;
  • cell, header, and row relationships in tables;
  • equation spans and surrounding prose;
  • speaker, tool, and system roles in conversations;
  • repository path and file relationships for code;
  • title, heading, list, citation, and hyperlink structure where useful;
  • page or section location when later grounding or deletion requires it.

Boilerplate removal should operate on parsed regions, not arbitrary repeated lines alone. A copyright footer repeated across a site may be removable; a repeated function signature or safety warning may be the exact signal the model needs.

Determinism and invariants

For fixed raw bytes and configuration, normalization should be deterministic:

normalize(raw, version, config) -> (structured_record, audit_metadata).

Useful invariants include:

  • idempotence: normalize(normalize(x)) = normalize(x) for the canonical text view;
  • bounded loss: removed characters and regions are counted and classified;
  • boundary preservation: protected code, table, and conversation regions cannot merge accidentally;
  • stable identity: content IDs include the normalizer version;
  • resource safety: decompression ratio, nesting depth, field length, and parse time are bounded;
  • replayability: locale, Unicode version, parser model, and rule bundle are pinned.

Sample diffs by source, language, and document type. Aggregate averages can hide a rule that corrupts every document in a small language.

Language and modality routing

Language identification should return scores and coverage, not only one label. A document can contain English explanation, a Spanish quotation, and code. Record predictions at document and segment level, plus model version and confidence.

Route low-confidence, mixed-language, code-heavy, OCR-heavy, and formula-heavy content to specialized parsers or conservative paths. A hard English-only threshold can remove code, named entities, transliteration, and minority dialects while appearing highly accurate on a benchmark dominated by clean monolingual prose.

Normalization review checklist

Before publishing normalized data, verify:

  • round-trip links to raw objects and offset maps for audited samples;
  • per-domain distributions of length, replacement characters, removed fraction, and parse failures;
  • code compilation or parser success where applicable;
  • table, equation, and conversation-turn preservation;
  • deterministic rerun hashes;
  • security limits against archive bombs, malformed markup, and adversarial nesting;
  • no train/evaluation split decision was made using a representation unavailable during reconstruction.

The cumulative record now has stable raw and normalized identities. The next chapter decides whether norm:A represents a duplicate group and which evidence can justify selecting it; neither decision changes its source bytes.