Synthetic Data Pipelines

Michael BrenndoerferNovember 25, 202658 min read

Build an auditable synthetic data pipeline: generation, verification, deduplication, decontamination, diversity control, and provenance records.

Language AI HandbookAll chapters
Part 21 of 67Data Governance, Provenance, and Synthetic Ecosystems
Chapter 152Synthetic Data Pipelines
Reading the full chapter · 11 sections · 58 min11 sections · 58 min

All 11 sections · 58 min read

Reading settings

Definitions

Choose how many terms have tooltips.

Article links

Make inline references clickable

Notes & comments

Synthetic Data Pipelines

A model that can write a plausible word problem is not the same as a corpus that can teach one. The gap between the two is a pipeline: a sequence of generation, validation, filtering, selection, and record-keeping stages that turns raw model output into training signal you would be willing to defend in an audit.

Suppose a team trains on generated word problems and finds three failures later: recurring phrasing, too few three-step problems, and exact copies of evaluation prompts. The pipeline needs a separate diagnostic for each. A benchmark gain alone cannot tell the team which failures are present.

Synthetic data

Training examples whose text was produced by a model or a program rather than written by a human. The category is broader than it sounds: it includes a teacher model's answers distilled into a smaller student, template-generated arithmetic problems with programmatic answers, paraphrases of human seed text, agent trajectories, and generated samples selected by a reward model. What unites them is that a generator stands between the human source and the training token.

A script that emits multiplication tables and a model that writes tutoring dialogues need different checks. For multiplication tables you can recompute the answer. For dialogue you may need to assess clarity or appropriateness separately.

Part XX: Data Curation covers when to use synthetic data. Here we will build a pipeline and record which generated rows survive each check.

A generated item can combine a plausible style with a wrong answer. The simulator below produces wrong answers and repeats on purpose. It also copies from a small evaluation fixture so you can see which copies the overlap check catches.

Budget for generation, validation, and manual review separately. A low cost per raw example still leaves you with a high cost per kept example if few rows pass the filters.

So the mental model for this chapter is this: a synthetic pipeline is a distribution transformer. You feed it the generator's distribution, and it returns a reweighted one. Every stage applies a weight: verification up-weights items whose answers can be checked, deduplication down-weights the modes, diversity caps flatten the head of the distribution, curriculum mixing reweights by difficulty. The final corpus is not "what the model thinks." It is what the model thinks, filtered through a set of decisions you made and, if you did the job properly, recorded in writing.

The framing is quantitative. If a stage retains an item with a known probability conditional on surviving earlier stages, those probabilities multiply to give the item's chance of survival. Normalize those weights to describe the distribution among survivors. Resampling for a curriculum can then change how often a surviving item appears.

The retained corpus reflects its filters. A checker designed for exact answers favors tasks it can score, such as arithmetic. A model judge can reward fluency or length alongside the intended property. Inspect what each stage rejects and retains to find out which behaviors the corpus emphasizes.

The Pipeline Is the Product

Before the mechanics, it is worth being precise about what a pipeline outputs, because the answer determines everything about how you engineer it.

The output is not a pile of text. It is a dataset plus a set of claims about that dataset:

  • which generator produced it, at which revision, with which decoding parameters;
  • which prompt template was used, and what that template looked like at the time;
  • which filters ran, in what order, with what thresholds;
  • what fraction of raw samples survived each stage;
  • what verification was applied and what it could and could not catch;
  • what the seeds were and under what terms they were licensed.

Those details give readers a way to check how a corpus was built. Dataset Lineage and Provenance in Part XXI covers the governance side. Here we build the artifacts those checks rely on.

A README paragraph can make a checkable claim if a reader has the evidence they need. To check “filtered at a near-duplicate threshold of 0.90,” for example, retain the relevant configuration and the record of which filter ran.

Pipeline yield

Overall yield is the fraction of generated rows that survives to the final corpus. A stage's conditional yield is the fraction of the rows reaching it that pass. Use overall yield to calculate generation cost per kept item. Track filtering and review costs separately.

The yield ledger

Suppose a run retains at least one row. Let a1,a2,…,aka_1, a_2, \dots, a_k be the stage acceptance rates, each measured among rows that reach its stage. If each raw sample costs cc to generate, the generation cost per kept sample is

generation cost per kept sample=c∏i=1kai.\text{generation cost per kept sample} = \frac{c}{\prod_{i=1}^{k} a_i}.

With four stages each retaining half its input, generation costs sixteen times as much per kept example as per raw example. Running the filters adds to that cost. For example, if lowering a judge threshold raised yield from 20% to 45% at a loss of three precision points, compare the reduced generation cost per retained sample at a fixed raw cost with the value of the precision lost.

A pipeline can save work in later stages by applying inexpensive, high-recall checks before costly ones where their dependencies allow it. For example, judge fewer rows by removing exact duplicates first when that ordering preserves the decision you want.

A cheap check that rejects half its input can halve the cost of later per-row checks, provided it leaves their cost per row unchanged. The best order also depends on which rows the checks reject and which earlier outputs they require. Compare both compute and acceptance on representative data.

A final count alone cannot locate a yield drop. Log the number of rows reaching and passing each stage. If one stage drops from 60% to 15% acceptance, compare its inputs, including generator and prompt revisions, and its own settings and implementation before assigning the cause.

Best-of-n with a fixed generator

Best-of-n can help when the generator sometimes produces an acceptable result and the verifier recognizes it.

Rejection sampling

Generate nn independent samples from a model, score each with a verifier, and keep the best or the ones above a threshold. If a single sample is acceptable with probability pp and the verifier is perfect, then best-of-nn produces an acceptable sample with probability 1−(1−p)n1 - (1-p)^n.

With p=0.3p = 0.3, eight independent draws give 1−0.78≈0.941 - 0.7^8 \approx 0.94. With p=0.05p = 0.05, forty give 1−0.9540≈0.871 - 0.95^{40} \approx 0.87. For fixed positive pp, success approaches certainty as the number of independent draws grows.

With a verifier that identifies acceptable results, repeated draws can increase the chance of collecting an acceptable example. The formula describes that collection step. It gives no estimate of the student’s performance after training.

If the teacher assigns zero probability to an acceptable answer for a task, no number of draws from that fixed distribution can supply one. Search with tools, a new prompt, or an external verifier used during generation can change the distribution that the pipeline samples.

When filtering plateaus, test whether the teacher ever supplies acceptable examples for the missing task types under the same prompt and sampler. A student may generalize from related tasks, but the retained examples alone do not show that it did.

The formula also assumes independent draws with the same success probability. Lower temperature can produce repeated answers even when draws are independent. The simulator below models a different mechanism: it deliberately copies a previous result on some draws, so observing an earlier draw changes the distribution of a later one.

In this simulator the first draw is fresh, and each later draw is fresh with probability one-half. An echo cannot turn a run of failures into a success. The chance of at least one acceptable result is therefore 1−(1−p)(1−p/2)n−11 - (1-p)(1-p/2)^{n-1} for this copy process. At eight draws with p=0.30p=0.30, the independent formula gives about 0.942, while the seeded simulation succeeds in about 0.776 of runs by the eighth draw.

PythonIn [4]
CollapseExpand
NS = np.arange(1, 41)
PS = [0.05, 0.30, 0.50]
indep_curves = {p: 1.0 - (1.0 - p) ** NS for p in PS}

# Correlated decoder: each draw is fresh with probability 1 - ECHO_SHARE, and
# otherwise a verbatim copy of an earlier draw from the same run. Simulation is
# seeded with the chapter SEED and uses TRIALS independent runs, each tracked over all sample counts.
ECHO_SHARE = 0.5
BASE_P = 0.30
TRIALS = 4000
corr_rng = np.random.default_rng(SEED)
draws = np.zeros((TRIALS, NS.size), dtype=bool)
for t in range(TRIALS):
    pool = []
    for i in range(NS.size):
        if pool and corr_rng.random() < ECHO_SHARE:
            good = pool[corr_rng.integers(len(pool))]
        else:
            good = corr_rng.random() < BASE_P
            pool.append(good)
        draws[t, i] = good
corr_curve = np.maximum.accumulate(draws, axis=1).mean(axis=0)
VisualizationOut [5]
CollapseExpand
Success probability vs number of draws for independent and correlated sampling.
Probability that at least one acceptable sample appears in n draws. Solid lines assume independent draws at three per-sample success rates; the dashed line shows a decoder that repeats earlier draws half the time at p=0.30. At eight draws, about 78% of simulated runs have succeeded, compared with about 94% under independence at the same fresh-draw rate.

Generation: Where the Raw Material Comes From

Choose the teacher, the prompt, and the decoder for the task types you need. A downstream selector can only select from candidates that generation supplies.

Assess generation and selection separately. Check whether acceptable candidates for a task occur in the raw pool, then estimate how often your filters retain those candidates.

Choosing the teacher

Teacher–student distillation uses one model to generate training outputs for another. Other pipelines synthesize both sides of an instruction pair or combine a generated side with human text:

  • Self-instruct. Wang et al. (2023) seeded a task pool with 175 human-written examples, generated instructions and instances, and filtered the additions. Self-Instruct, §2.2.
  • Instruction backtranslation. Li et al. generated candidate instructions from human-written web passages. A seed instruction model rated how well each passage answered its inferred instruction on a five-point rubric. Self-Alignment with Instruction Backtranslation, §§2.2–2.3.
  • Evolutionary rewriting. Xu et al. introduced WizardLM's Evol-Instruct in a 2023 preprint. Its rewrites can add constraints, deepen the task, make it more concrete, or request more reasoning steps. WizardLM, §3.1.
  • Seedless prompting. Magpie gave an aligned model its chat template up to the slot for the user message. The model filled that slot with an instruction, then generated its response in a second step. Magpie, §2, ICLR 2025.
  • Program-aided generation. Sample a program, execute it to get a reference answer, then express the task in natural language. The worked example uses fixed arithmetic templates.

These methods can be combined. Choose the generation method and the checks together. For an instruction rewrite, a rubric or a human review can assess the transformation. For arithmetic generated from a program, execution supplies an independent check on the response's final number.

A program can supply a reference answer before the task is rendered. This requires a program that represents the intended task and an execution environment appropriate for the inputs.

The text still has to express the same task as the program. For example, a story in which Ben gives himself eight stickers describes a different transaction from one where a second person gives Ben eight. Check the rendering separately from the final answer.

Prompt design as distribution design

Compare prompts under a fixed teacher and decoding setup. For example, contrast “write a math word problem” with “write a two-step problem whose second operation is multiplication and whose answer is between 20 and 60.” Measure the share of valid two-step problems under both prompts.

The prompt conditions the model's next-token distribution. At a fixed prefix, temperature rescales the logits before sampling. Because a sampled token becomes part of the next prefix, temperature can also change the mix of tasks you see across complete outputs.

The practical techniques:

  • Seed conditioning. Try human-written examples that span the task types you want. Compare generated coverage with and without the seed examples.
  • Metadata-first generation. Choose a topic, difficulty, and format outside the model for each generation request. Track coverage after verification, since assigned requests can be rejected or yield a different kind of item.
  • Negative constraints. If you want to exclude names or number ranges, state the exclusions and verify compliance on a sample.
  • Persona and register variation. Keep the task fixed and ask for different audiences or registers. Check whether the resulting texts vary in the surface features you intend.

Planning assignments across a metadata grid controls which requests go to the model. To meet a target number of valid items per cell, count accepted responses by cell and resample where needed. Include extra requests and checks in your cost estimate.

Version prompt templates and record their content hashes. Keep the template itself so the hash can be checked later.

If you regenerate half a corpus after a prompt edit, record which rows came from each revision. The template hash can identify a recorded revision, while evaluating the effect of the change needs a comparison that controls other inputs.

Decoding parameters and the diversity/error tradeoff

Temperature τ\tau rescales logits before the softmax:

pi(τ)=exp⁡(zi/τ)∑jexp⁡(zj/τ).p_i(\tau) = \frac{\exp(z_i / \tau)}{\sum_j \exp(z_j / \tau)}.

As τ\tau approaches zero from above, the probability mass concentrates on the largest logit or is divided among tied maxima. For a fixed finite set of logits, very large temperatures approach a uniform distribution. Top-pp sampling retains the smallest probability-ranked prefix with cumulative mass at least pp, then renormalizes over it. Holtzman et al., §3.1.

Temperature reshapes the distribution before truncation, which may also change which tokens enter the nucleus. Compare the resulting diversity on the task and sampling setup you intend to use.

Higher temperature flattens the softmax at a fixed prompt. Its effect on errors depends on which continuations are correct. The worked simulator changes several settings together, including the answer-error rate, and reports the resulting yields for that design.

Compare decoding settings using the number and variety of items that pass the same verifier.

More candidate samples can raise verification cost. Measure that cost alongside accepted diversity when choosing a sampling setting.

A Worked Pipeline

We build the pipeline with a seeded template simulator in place of a teacher model. Each later stage operates on the simulator's output. To use a model instead, adapt its response to the expected record format and supply whatever validation labels the task requires.

The simulator inserts repeats, evaluation copies, malformed outputs and answer errors at known stages. That lets us count what each filter removes in a seeded run. Use the same kinds of diagnostics on real outputs and estimate their rates separately.

The task is grade-school arithmetic word problems with integer answers. We chose it because it has three properties that make pipeline mechanics visible:

  • answers are computable, so we have an executor as an oracle;
  • templates are few, so duplicate and near-duplicate structure appears naturally;
  • errors are easy to inject, so we can measure what each filter catches.

The simulator records reference answers and format labels for every candidate, so we can calculate judge precision and recall for this run. For a production audit you can estimate those rates from a labeled sample.

Setup

The hidden setup at the start initializes the random seed and imports the numerical and plotting tools used by the examples below.

The generator's world

The four example seed records show how few-shot demonstrations could be stored. Their license values are illustrative metadata. The simulator does not read this table when generating rows. The same four prompts also appear in the six-item evaluation fixture, which the direct-copy branch uses.

PythonIn [6]
CollapseExpand
NAMES = [
    "Ana",
    "Ben",
    "Chen",
    "Dara",
    "Elif",
    "Farid",
    "Gita",
    "Hugo",
    "Imani",
    "Jonas",
]
ITEMS = ["stickers", "marbles", "pencils", "notebooks", "tokens", "buttons"]

ILLUSTRATIVE_SEEDS = [
    {
        "seed_id": "seed-001",
        "license": "CC-BY-4.0",
        "text": "Ana has 12 stickers. Ben gives Ana 7 more stickers. How many stickers does Ana have now?",
    },
    {
        "seed_id": "seed-002",
        "license": "CC-BY-4.0",
        "text": "Each box holds 6 pencils. Dara has 4 boxes. How many pencils are there in total?",
    },
    {
        "seed_id": "seed-003",
        "license": "CC-BY-4.0",
        "text": "Elif has 20 tokens. Farid gives Elif 5 more, then Elif gives away 8. How many tokens does Elif have left?",
    },
    {
        "seed_id": "seed-004",
        "license": "CC-BY-4.0",
        "text": "Gita buys 3 packs of 7 buttons and already has 4. How many buttons does Gita have in total?",
    },
]

RUN_ID = "syn-arith-2025-06-01"
RUN_TS = (
    "2025-06-01T00:00:00Z"  # fixed, not wall-clock, so hashes are reproducible
)

Each template pairs a surface pattern with the program that defines its answer. On a fresh template draw, the sampler rescales the configured logits by temperature. Higher-logit templates dominate more at low temperature, and the distribution flattens as temperature rises.

The first template has a logit of 3.0, and the last has a logit of 0.0. At the lowest tested temperature, the fresh template draw puts most of its mass on add-give and little on the two-step templates. The programmed skew gives us a concrete distribution to inspect before and after selection.

PythonIn [7]
CollapseExpand
TEMPLATES = [
    {
        "tid": "add-give",
        "steps": 1,
        "logit": 3.0,
        "program": "a + b",
        "pattern": "{n1} has {a} {item}. {n2} gives {n1} {b} more {item}. How many {item} does {n1} have now?",
    },
    {
        "tid": "add-buy",
        "steps": 1,
        "logit": 2.0,
        "program": "a + b",
        "pattern": "{n1} had {a} {item} and bought {b} more. How many {item} does {n1} have now?",
    },
    {
        "tid": "mul-box",
        "steps": 1,
        "logit": 1.5,
        "program": "a * b",
        "pattern": "Each box holds {a} {item}. {n1} has {b} boxes. How many {item} are there in total?",
    },
    {
        "tid": "two-give-away",
        "steps": 2,
        "logit": 0.5,
        "program": "a + b - c",
        "pattern": "{n1} has {a} {item}. {n2} gives {n1} {b} more, then {n1} gives away {c}. How many {item} does {n1} have left?",
    },
    {
        "tid": "two-packs",
        "steps": 2,
        "logit": 0.0,
        "program": "a * b + c",
        "pattern": "{n1} buys {b} packs of {a} {item} and already has {c}. How many {item} does {n1} have in total?",
    },
]

EVAL_SET = [
    {
        "qid": "eval-01",
        "answer": 19,
        "steps": 1,
        "max_operand": 12,
        "prompt": "Ana has 12 stickers. Ben gives Ana 7 more stickers. How many stickers does Ana have now?",
    },
    {
        "qid": "eval-02",
        "answer": 23,
        "steps": 1,
        "max_operand": 14,
        "prompt": "Chen had 14 marbles and bought 9 more. How many marbles does Chen have now?",
    },
    {
        "qid": "eval-03",
        "answer": 24,
        "steps": 1,
        "max_operand": 6,
        "prompt": "Each box holds 6 pencils. Dara has 4 boxes. How many pencils are there in total?",
    },
    {
        "qid": "eval-04",
        "answer": 17,
        "steps": 2,
        "max_operand": 20,
        "prompt": "Elif has 20 tokens. Farid gives Elif 5 more, then Elif gives away 8. How many tokens does Elif have left?",
    },
    {
        "qid": "eval-05",
        "answer": 25,
        "steps": 2,
        "max_operand": 7,
        "prompt": "Gita buys 3 packs of 7 buttons and already has 4. How many buttons does Gita have in total?",
    },
    {
        "qid": "eval-06",
        "answer": 17,
        "steps": 1,
        "max_operand": 9,
        "prompt": "Hugo has 9 notebooks. Imani gives Hugo 8 more notebooks. How many notebooks does Hugo have now?",
    },
]


def canonical(obj) -> str:
    """Stable JSON serialization used for every content hash in this chapter."""
    return json.dumps(
        obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False
    )


ILLUSTRATIVE_SEED_HASH = hashlib.sha256(
    canonical(ILLUSTRATIVE_SEEDS).encode()
).hexdigest()
TEMPLATE_HASH = hashlib.sha256(canonical(TEMPLATES).encode()).hexdigest()
EVAL_FIXTURE_HASH = hashlib.sha256(canonical(EVAL_SET).encode()).hexdigest()
ConsoleOut [8]
CollapseExpand
illustrative seed set hash: f0642fffdef3ef1d...
template definitions hash:  61cea3259d17bd62...
evaluation fixture hash:    153ca092bd0dcd4f...

The illustrative seed digest starts with f0642fff. The template digest binds all template fields, including the logits and step counts. The evaluation fixture has a separate digest for the items read by the direct-copy branch and the overlap filter.

The canonical helper gives these JSON objects a stable encoding for hashing. The manifest also hashes the bytes of the written JSONL file so a reader can check the exact artifact that was distributed.

The synthesis function

The simulator records three emission labels: fresh, echo, and direct evaluation copy. Malformed response text is one possible outcome within the fresh branch.

  • Fresh sampling draws a template and slot values and renders the task.
  • Echoing copies an earlier response and carries its provenance forward.
  • Direct copying takes a prompt from the evaluation fixture. The code labels this branch “memorized” for the demonstration.
  • Malformed response text can replace the formatted answer on the fresh branch; later echoes can inherit it.

Fresh answers can be corrupted at the configured error rate before rendering, and the evaluation-copy branch uses its own 10% answer-perturbation probability.

A candidate can have more than one problem. For example, an echo can repeat a malformed answer or copy an evaluation prompt indirectly. Keep separate diagnostic fields and verify what each filter catches.

PythonIn [9]
CollapseExpand
def _softmax(logits, temperature):
    z = np.asarray(logits, dtype=float) / temperature
    z = z - z.max()
    p = np.exp(z)
    return p / p.sum()


def synthesize(
    n,
    temperature,
    seed,
    model="teacher-sim-1",
    prompt_version="arith-v3",
    echo_base=0.30,
    memorize_p=0.04,
    error_base=0.05,
    error_slope=0.30,
    malformed_p=0.03,
):
    rng = random.Random(f"{model}|{prompt_version}|{temperature}|{seed}")
    template_probs = _softmax([t["logit"] for t in TEMPLATES], temperature)
    active_names = NAMES[: max(2, int(round(3 + 7 * temperature)))]
    max_operand = max(4, int(round(6 + 18 * temperature)))
    echo_p = echo_base * (1.2 - 0.9 * (temperature - 0.3) / 0.7)
    error_p = min(0.6, error_base + error_slope * temperature)
    out = []

    for i in range(n):
        u = rng.random()

        if out and u < echo_p:  # mode collapse
            row = dict(out[rng.randrange(len(out))])
            row.update(
                {
                    "sample_idx": i,
                    "emission": "echo",
                    "source_sample_idx": row["sample_idx"],
                }
            )
            out.append(row)
            continue

        if echo_p <= u < echo_p + memorize_p:  # benchmark regurgitation
            item = EVAL_SET[rng.randrange(len(EVAL_SET))]
            answer = item["answer"]
            if rng.random() < 0.10:
                answer += rng.choice([-2, -1, 1, 2])
            out.append(
                {
                    "sample_idx": i,
                    "temperature": temperature,
                    "problem": item["prompt"],
                    "response": f"The answer is {answer}.",
                    "program": None,
                    "slots": {},
                    "ground_truth": item["answer"],
                    "template_id": "memorized-eval",
                    "steps": item["steps"],
                    "max_operand": item["max_operand"],
                    "emission": "memorized",
                    "eval_qid": item["qid"],
                }
            )
            continue

        t_idx = min(
            int(np.searchsorted(np.cumsum(template_probs), rng.random())),
            len(TEMPLATES) - 1,
        )
        tpl = TEMPLATES[t_idx]
        a = rng.randint(1, max_operand)
        b = rng.randint(1, max_operand)
        c = rng.randint(1, max(2, max_operand // 2))
        if tpl["program"] == "a + b - c":
            c = min(c, a + b - 1)
        recipient = rng.choice(active_names)
        giver = rng.choice(active_names)
        if giver == recipient:
            giver = active_names[
                (active_names.index(recipient) + 1) % len(active_names)
            ]
        slots = {
            "n1": recipient,
            "n2": giver,
            "item": rng.choice(ITEMS),
            "a": a,
            "b": b,
            "c": c,
        }
        gt = int(eval(tpl["program"], {"__builtins__": {}}, dict(slots)))
        problem = tpl["pattern"].format(**slots)

        shown = gt
        if rng.random() < error_p:
            shown = gt + rng.choice([-10, -3, -2, -1, 1, 2, 3, 10])
            if shown < 0:
                shown = gt + 1

        style = rng.choice(["bare", "sentence", "answer_is", "equation"])
        if rng.random() < malformed_p:
            response = rng.choice(
                ["I'm not sure.", "Let me think.", "The answer is", ""]
            )
        elif style == "bare":
            response = str(shown)
        elif style == "sentence":
            response = f"{slots['n1']} has {shown} {slots['item']}."
        elif style == "answer_is":
            response = f"The answer is {shown}."
        else:
            expr = tpl["program"]
            for name in ("a", "b", "c"):
                expr = expr.replace(name, str(slots[name]))
            response = f"{expr} = {shown}"

        used = [k for k in ("a", "b", "c") if k in tpl["program"]]
        out.append(
            {
                "sample_idx": i,
                "temperature": temperature,
                "problem": problem,
                "response": response,
                "program": tpl["program"],
                "slots": slots,
                "ground_truth": gt,
                "template_id": tpl["tid"],
                "steps": tpl["steps"],
                "max_operand": max(slots[k] for k in used),
                "emission": "fresh",
            }
        )

    return out

A note on eval with {"__builtins__": {}}: this disables builtins and is adequate for an expression built out of integers and arithmetic operators, but it is not a sandbox. Real pipelines execute candidate code in a container or a WASM runtime with resource limits. The pattern to copy here is the architecture (program produces ground truth before text exists), not the isolation strategy. The example evaluates a fixed set of arithmetic expressions that the chapter defines. It never evaluates the generated response. When a pipeline accepts executable inputs from elsewhere, its resource and isolation controls belong outside the expression evaluator.

The template logits and temperature determine the categorical draw within the simulator's template branch. Other choices, including the repeat, copy, and answer-error settings, also affect which rows the generator emits.

PythonIn [10]
CollapseExpand
TEMP_GRID = [0.3, 0.7, 1.0]
template_probs = np.array(
    [_softmax([t["logit"] for t in TEMPLATES], tau) for tau in TEMP_GRID]
)
template_labels = [t["tid"] for t in TEMPLATES]
VisualizationOut [11]
CollapseExpand
Grouped bars showing template sampling probability flattening as temperature rises.
Template probabilities conditional on a fresh draw at three sampling temperatures. At tau=0.3 the skewed logits put most of the mass on add-give; by tau=1.0 the distribution is flatter, but add-give still takes about 58% of fresh template draws.

Running the generator

We sweep three temperatures with 150 samples each. In production this would be an API call loop with a request id per call; here it is a function call.

Keep the request ID alongside the exact submitted prompt, sampling parameters and any returned model-revision information. A request ID helps correlate records with provider logs when those logs are available.

PythonIn [12]
CollapseExpand
TEMPERATURES = [0.3, 0.7, 1.0]
N_PER_TEMPERATURE = 150

rows = []
for i, temp in enumerate(TEMPERATURES):
    rows.extend(synthesize(N_PER_TEMPERATURE, temp, seed=1000 + i))

df = pd.DataFrame(rows)
df["row_id"] = np.arange(len(df))

INT_RE = re.compile(r"-?\d+")


def parse_final_int(text):
    hits = INT_RE.findall(text or "")
    return int(hits[-1]) if hits else None


df["parsed"] = df["response"].map(parse_final_int)
df["correct"] = df["parsed"] == df["ground_truth"]
df["format_ok"] = (
    df["parsed"].notna()
    & df["response"].str.len().between(1, 120)
    & ~df["response"].str.lower().str.contains("cannot", regex=False)
)
ConsoleOut [13]
CollapseExpand
generated samples: 450
               n  format_ok  correct  echoes  memorized
temperature                                            
0.3          150      1.000    0.873   0.300      0.033
0.7          150      0.960    0.713   0.193      0.053
1.0          150      0.973    0.720   0.080      0.067

In this seeded run, 45 of the 150 low-temperature samples are echoes. The direct-copy branch emits 5, 8, and 10 rows across the three temperatures. The branch has a configured 4% probability. An echo can inherit an evaluation prompt while remaining labeled as an echo.

The format_ok column combines three separate predicates: the response parses, its length is between 1 and 120 characters, and it does not contain “cannot” after lowercasing. Log the component results to see which checks failed. A parseable final integer still needs an answer check.

Filtering and Verification

The check you choose determines what you can claim about a surviving row. The following checks establish different properties and carry different costs.

You do not choose a rung once and stay there; you climb as far as the domain and the budget allow, and you report where you ended up. A pipeline that verifies 90% of its corpus by execution and 10% by judge is a different artifact from one that verifies 10% by execution and 90% by judge, even if the final row counts are identical.

The verifier ladder

Match the check to the property you need to verify:

  1. Formal check. A proof assistant checks a stated proposition relative to its axioms. A type checker checks the program's stated typing properties.
  2. Execution. Evaluate an expression, compare against a trusted database, or run tests. Each check is only as broad as the reference and cases it covers.
  3. Agreement. Compare answers across sampled reasoning paths or models. In the original self-consistency method, a single model samples multiple paths and the decoder aggregates the final answers.
  4. Reward model or judge. Use the score as a proxy and measure its errors against task-specific labels. The studies below give examples of judge bias.
  5. Heuristics. Try checks for length, punctuation, refusal phrases, language, or perplexity as early filters where they are appropriate. Measure what they reject.

Choose a check that covers the claim you need to make. A parse establishes syntactic validity, a test establishes behavior on its inputs, and a proof establishes its stated proposition. For proxy checks, estimate error rates against independent labels, and state the scope of the labels.

Report what each check establishes and how much of the dataset it covers. For a learned or heuristic proxy, estimate acceptance errors on a labeled sample.

Verification gap

The share of samples for which the pipeline lacks a reference check for the property it wants to verify. A prompt can have an exact format check and still need expert review of its factual content.

A reference answer can make it inexpensive to check many candidates. Where the target is writing quality or appropriateness, budget for sampling and human review and state what the labels measure.

Judges are proxies, and biased ones

A judge scores samples against a rubric. Zheng et al., §3.2 measured position and verbosity effects in tested judge models. Check those and other possible failure modes on the target task:

  • Position bias. Reversing pair order can change preference, and the preferred position can vary by judge and task.
  • Verbosity bias. In the study's repetitive-list test, some judges preferred responses padded with repeated material.
  • Self-preference. Some tested judges favored their own generations under controlled comparisons. Panickssery et al. (2024).
  • Score compression. A narrow band of scores leaves little room to move a threshold without accepting or rejecting many candidates.
  • Prompt and language sensitivity. Pilot wording and presentation, and measure agreement in the languages the filter will judge. The level of agreement can vary by language and task. Fu and Liu (2025).

Measure agreement and errors for the rubric you plan to run. Changing the judge model or pool of candidates can change the result.

These are reasons to audit judges, and to record the rubric verbatim alongside the scores. A judge whose rubric you cannot reproduce is not a filter, it is a rumor.

For a judge audit, manually label a random sample or use a score-stratified design to get more examples near the threshold. Report per-stratum results. For corpus-level precision and recall from unequal sampling rates, weight each label by the inverse of its selection probability when estimating the confusion counts.

Agreement filtering, and why independence matters

If one judge is noisy, ask three and require a majority. The math is seductive. Suppose each judge accepts a bad sample with probability uu and a good one with probability tt, and suppose their errors are independent. Requiring kk of nn votes converts the per-judge false-positive rate uu into

uk=∑j=kn(nj)uj(1−u)n−j,u_k = \sum_{j=k}^{n} \binom{n}{j} u^{j} (1-u)^{n-j},

For unanimity, the false-positive rate is unu^n. With u=0.3u=0.3 and three independent judges, this is 0.0270.027. Precision also depends on how often good items pass and how common they are in the pool.

The binomial formula applies to independent votes conditional on the true class. In the simulator the noise term is drawn separately for each judge, but all judges see the same item length and truth label. The measured agreement therefore describes this fixture. With perfectly correlated errors, unanimity has the same false-positive rate as a single judge.

Try a mix of models and compare scoring in both response orders, then measure how often their mistakes coincide on labeled items. Diversity of model families is no guarantee of independent errors. Compare the extra calls with any measured gain.

Purity and yield arithmetic

Let ff be the fraction of raw items your labels mark as good, tt the true-positive rate, and uu the false-positive rate. These three quantities determine yield and, if anything passes, purity. They leave other properties of the retained corpus unspecified.

purity=ftft+(1−f)u,yield=ft+(1−f)u.\text{purity} = \frac{f t}{f t + (1-f) u}, \qquad \text{yield} = f t + (1-f) u.

Increasing a score threshold can only reduce or preserve yield on the same candidates. With positive tt and uu, purity rises if the accepted true-to-false-positive rate ratio t/ut/u rises. At fixed rates with t>ut>u, a higher base rate ff improves yield and purity when both classes can pass. For f=0.9f=0.9, t=0.9t=0.9, and u=0.2u=0.2, purity is about 0.9760.976 and yield is 0.830.83. The filter rejects 0.090.09 of all candidates even though they are good, alongside 0.080.08 that are bad.

Track purity and yield together. For a fixed target corpus size, a lower yield usually requires generating more candidates. If the budget is in tokens, also measure the lengths of accepted rows and the cost of checking them.

Sweeping an assumed relation between the two acceptance rates gives an illustrative operating curve. The plot below uses the same specified relation at three base rates. Compare it with a curve measured on your own scores and labels.

PythonIn [14]
CollapseExpand
# Sweep the false-positive rate u downward (a rising threshold) and tie the
# true-positive rate to it as t = u ** 0.45, a curve on which the filter is
# always better than chance. Monotone, deterministic, and independent of SEED.
u_grid = np.linspace(0.02, 0.60, 240)
t_grid = u_grid**0.45
GOOD_RATES = [0.20, 0.50, 0.90]
frontier = {}
for f in GOOD_RATES:
    hit = f * t_grid
    frontier[f] = {
        "yield": hit + (1.0 - f) * u_grid,
        "purity": hit / (hit + (1.0 - f) * u_grid),
    }
VisualizationOut [15]
CollapseExpand
Purity against yield for three generator base rates as the filter threshold varies.
Purity and yield on the illustrative curve t = u^0.45 at three base rates. Along this curve, lower false-positive rates trade yield for purity. The 0.90 base-rate curve starts and stays closer to purity one than the 0.20 curve.

Implementing the gate and auditing the judges

We simulate judges of differing strength and bias. Known labels help manufacture the toy scores and also let us audit them. In production, score candidates with the judge independently of the audit labels. Then use a manually labeled sample to estimate errors.

The simulated judges differ in four parameters. The bias shifts the latent score, the correctness weight rewards format-valid correct answers, the length weight increases the score for longer responses, and the noise scale controls the spread of the random term. Compare their resulting errors under the same threshold.

PythonIn [16]
CollapseExpand
JUDGES = [
    {
        "name": "j1",
        "bias": -0.4,
        "correct_w": 1.30,
        "len_w": 0.15,
        "noise": 0.85,
    },
    {
        "name": "j2",
        "bias": -0.1,
        "correct_w": 1.10,
        "len_w": 0.35,
        "noise": 0.95,
    },
    {
        "name": "j3",
        "bias": -0.7,
        "correct_w": 1.40,
        "len_w": 0.25,
        "noise": 0.75,
    },
]
JUDGE_THRESHOLD = 3.5


def judge_score(row, judge):
    rng = random.Random(f"{judge['name']}|{row['row_id']}|{row['temperature']}")
    good = bool(row["correct"]) and bool(row["format_ok"])
    z = judge["bias"] + judge["correct_w"] * float(good)
    z += judge["len_w"] * math.log1p(len(row["response"]))
    z += rng.gauss(0.0, judge["noise"])
    return 1.0 + 4.0 / (1.0 + math.exp(-z))


for judge in JUDGES:
    df[f"score_{judge['name']}"] = df.apply(
        lambda r, j=judge: judge_score(r, j), axis=1
    )

score_cols = [f"score_{j['name']}" for j in JUDGES]
df["judge_mean"] = df[score_cols].mean(axis=1)
df["votes"] = (df[score_cols] >= JUDGE_THRESHOLD).sum(axis=1)
PythonIn [17]
CollapseExpand
def precision_recall(accept, truth):
    accept, truth = accept.astype(bool), truth.astype(bool)
    tp = int((accept & truth).sum())
    fp = int((accept & ~truth).sum())
    fn = int((~accept & truth).sum())
    return {
        "accepted": int(accept.sum()),
        "precision": tp / (tp + fp) if tp + fp else float("nan"),
        "recall": tp / (tp + fn) if tp + fn else float("nan"),
    }


truth = df["format_ok"] & df["correct"]
policies = {
    "no filter": pd.Series(True, index=df.index),
    "1 judge": df["score_j1"] >= JUDGE_THRESHOLD,
    "2 of 3": df["votes"] >= 2,
    "3 of 3": df["votes"] == 3,
}
audit = pd.DataFrame(
    [
        {"policy": name, **precision_recall(accept, truth)}
        for name, accept in policies.items()
    ]
)
ConsoleOut [18]
CollapseExpand
base rate of acceptable samples: 0.769
   policy  accepted  precision  recall
no filter       450      0.769   1.000
  1 judge       298      0.893   0.769
   2 of 3       353      0.912   0.931
   3 of 3       203      0.975   0.572

In this run, the two-of-three policy has higher precision and recall than judge 1 alone. Those policies can accept different examples. Unanimity accepts a subset of the two-of-three policy's examples, raising precision on this dataset and lowering recall.

VisualizationOut [19]
CollapseExpand
Grouped bar chart comparing precision and recall for one judge, two of three, and three of three policies.
Precision and recall against the toy format and final-answer labels. Two of three has higher precision and recall than judge 1 alone in this run. Requiring all three yields the highest precision and lowest recall among the judge-based policies.

Auditing the filter reveals its precision and the recall it gives up.

Precision depends on the prevalence of acceptable samples alongside the true-positive and false-positive rates. Recall is the true-positive rate on acceptable samples. It can also change between corpora if the mix of acceptable examples changes.

Execution verification

The gate requires both the toy format rule and equality between the last integer-like substring and the stored arithmetic answer. The answer comes from the fixed template or a labeled evaluation fixture item. Judge scores rank later survivors within clusters.

The gate verifies an answer under the toy task's rules. It does not validate a derivation in the response or resolve a poorly written prompt. Within the accepted set, the judge can change which rows survive the diversity cap but cannot admit an answer that failed the earlier gate.

PythonIn [20]
CollapseExpand
verified = df[df["format_ok"] & df["correct"]].copy()
verified["norm"] = (
    verified["problem"]
    .str.lower()
    .str.replace(r"[^a-z0-9 ]", " ", regex=True)
    .str.replace(r"\s+", " ", regex=True)
    .str.strip()
)
ConsoleOut [21]
CollapseExpand
format-valid: 440  ->  answer-verified: 346

Deduplication uses an ASCII-specific normalizer because this fixture contains English text. It lowercases, replaces characters outside letters a–z, digits and spaces, then collapses whitespace. This would discard information in text with accented letters or other scripts. Choose a normalization policy for the languages and distinctions your task needs.

Deduplication as a filter

The Deduplication and MinHash chapters describe exact and approximate matching. Here exact matching detects normalized copies, while lexical near-deduplication can group closely related templates and slot fills. When template IDs are available, they provide a separate way to count reuse of a template.

Changing the sticker count creates another instance of the same template. Keep both if you need coverage over quantities. The example below materializes every pairwise similarity in a dense matrix, so memory grows quadratically with the number of rows. For larger collections, restrict comparisons to candidates from a retrieval index and check how many near-duplicates the retrieval step misses.

PythonIn [22]
CollapseExpand
def near_dedup_keep(texts, threshold):
    """Greedy near-duplicate removal over character n-gram TF-IDF cosine similarity."""
    vec = TfidfVectorizer(
        analyzer="char_wb", ngram_range=(3, 5), sublinear_tf=True
    )
    X = normalize(vec.fit_transform(texts))
    sims = (X @ X.T).toarray()
    kept = []
    for i in range(sims.shape[0]):
        if not kept or sims[i, kept].max() < threshold:
            kept.append(i)
    return kept


exact = verified.drop_duplicates("norm").reset_index(drop=True)

sensitivity = []
for thr in (0.70, 0.80, 0.90, 0.95):
    sensitivity.append(
        {
            "threshold": thr,
            "kept": len(near_dedup_keep(exact["norm"].tolist(), thr)),
        }
    )
sensitivity = pd.DataFrame(sensitivity)
ConsoleOut [23]
CollapseExpand
after exact dedup: 261 (removed 85 duplicate rows)
 threshold  kept
      0.70    44
      0.80    75
      0.90   130
      0.95   207

The table reports 207 survivors at 0.95 and 44 at 0.70. This shows how much the retained count depends on the character n-gram cutoff in this fixture. Inspect examples near the cutoff to see whether the rule is merging distinct arithmetic tasks.

The chart displays retained counts across the tested cutoffs. To tell whether nearby examples are paraphrases or materially different tasks, inspect them.

PythonIn [24]
CollapseExpand
dedup_thresholds = sensitivity["threshold"].to_numpy(dtype=float)
dedup_kept = sensitivity["kept"].to_numpy(dtype=int)
exact_count = int(len(exact))
VisualizationOut [25]
CollapseExpand
Surviving sample counts at four near-duplicate thresholds against the exact-dedup count.
Survivor counts at four character TF-IDF cosine thresholds, with the normalized exact-dedup count as reference. Lower thresholds remove more rows in this fixture. The counts depend on the representation and the order of greedy selection.

Templated text can share many character n-grams even when a slot value changes. The char_wb analyzer constructs character n-grams within word boundaries, padding the start and end of each word with spaces. scikit-learn, TfidfVectorizer.

PythonIn [26]
CollapseExpand
NEAR_DUP_THRESHOLD = 0.90
keep_idx = near_dedup_keep(exact["norm"].tolist(), NEAR_DUP_THRESHOLD)
deduped = exact.iloc[keep_idx].reset_index(drop=True)
ConsoleOut [27]
CollapseExpand
after near dedup at 0.9: 130

Decontamination

A teacher can sometimes reproduce text from its training data. In this simulator, a dedicated branch copies from the six evaluation prompts to demonstrate an overlap audit. Exact matching can detect identical prompts. Lexical overlap can also flag closely related text, with recall limited by the wording and representation. Carlini et al. (2021).

Check synthetic outputs against the evaluation sets you plan to report. Distinguish verbatim matches from suspected variants, and audit samples on both sides of the threshold if the decision matters.

Contamination

Training–evaluation contamination is overlap in content or information that compromises the intended evaluation. How it changes a score depends on the benchmark, the model and the overlap.

PythonIn [28]
CollapseExpand
def word_ngrams(text, n=8):
    toks = re.findall(r"[a-z0-9]+", text.lower())
    return {tuple(toks[i : i + n]) for i in range(max(0, len(toks) - n + 1))}


EVAL_GRAMS = [word_ngrams(item["prompt"]) for item in EVAL_SET]


def max_eval_overlap(text):
    grams = word_ngrams(text)
    if not grams:
        return 0.0
    return max(len(grams & ref) / len(grams | ref) for ref in EVAL_GRAMS)


deduped["eval_overlap"] = deduped["problem"].map(max_eval_overlap)
DECONTAM_THRESHOLD = 0.25
clean = deduped[deduped["eval_overlap"] < DECONTAM_THRESHOLD].reset_index(
    drop=True
)
ConsoleOut [29]
CollapseExpand
flagged as contaminated: 4 of 130
max overlap seen: 1.000
remaining after decontamination: 126

The fixture compares sets of eight-word grams at a Jaccard threshold of 0.25. Its regular expression tokenizes ASCII letters and digits, so a string without either yields zero grams and is assigned zero overlap. A multilingual audit needs a segmentation policy appropriate to its scripts. Changing gram length changes the overlap signal, so report it along with the score threshold.

Containment divides the intersection by the evaluation item's gram count. With the same overlap and a larger generated set, it can retain a signal that Jaccard dilutes. It still requires shared grams and misses reformulations without them.

Diversity Control

The fixture has now passed its format, answer, deduplication, and overlap checks. Check which task types remain, since each stage tests a particular property.

Coverage and correctness are different properties. A corpus can contain only correct single-step additions and still have no multiplication or two-step items. Evaluate transfer to those families on separate examples.

Measuring diversity

Diversity is not one number, and the choice of metric determines what you end up optimizing. Three families are in common use.

Lexical diversity. Let GnG_n list all nn-gram occurrences, including repeats. The distinct-nn ratio counts unique types over occurrences. The implementation below returns zero for an empty list:

distinct-n=∣set⁡(Gn)∣∣Gn∣,∣Gn∣>0.\text{distinct-}n = \frac{|\operatorname{set}(G_n)|}{|G_n|}, \qquad |G_n| > 0.

Adding novel tokens can raise this ratio without adding a task type. Self-BLEU (Zhu et al., 2018, in Texygen) uses each generated sentence as a candidate and compares it with the others as references. Texygen, §2.2.3.

For example, append a different new token to each copy of the same sentence. Its distinct-bigram ratio rises as each new ending adds a unique bigram, even though the sentences still describe the same task. Use lexical diversity for monitoring and inspect task coverage separately.

Semantic diversity. Embed the samples and choose a similarity kernel. The Vendi score (Friedman and Dieng, 2023) is the exponential of the Shannon entropy of the eigenvalues of the normalized similarity matrix:

VS(K)=exp⁡(−∑iλilog⁡λi),\text{VS}(K) = \exp\left(-\sum_i \lambda_i \log \lambda_i\right),

Here λi\lambda_i are the eigenvalues of K/nK/n. The positive-semidefinite kernel has Kij=k(xi,xj)K_{ij}=k(x_i,x_j) and k(xi,xi)=1k(x_i,x_i)=1, so those eigenvalues sum to one. A zero eigenvalue contributes zero to the sum. The score is an effective count under that similarity definition. Friedman and Dieng, §§3.1–3.2.

The count depends on the kernel. Report the similarity representation when comparing scores, and inspect examples to see which variation it rewards.

Structural diversity. Cluster the corpus and report occupied cluster counts or the entropy of the cluster frequencies. For a template generator, also count examples by template or operation so the chosen grouping is explicit.

Report sizes and inspect members before acting on a small cluster. Three members could be a rare task you want more of, or three errors that should be removed.

Mode collapse (in the corpus sense)

A synthetic corpus can overrepresent a few templates or styles relative to the intended variety. Mode-seeking decoding or selection that favors common variants can intensify the concentration. Compare observed counts with the coverage the task needs.

Mechanisms

Four options to test:

  • Prompt and seed diversity. Vary the conditioning inputs, then compare which task types survive verification.
  • Decoding temperature and nucleus size. Vary these to explore candidate diversity and measure how the verified yield changes on the resulting samples.
  • Cluster-capped selection. Cluster the candidates, then keep at most cc per cluster. This adjusts the retained mix using the existing pool.
  • Marginal-coverage selection. Select a subset of the existing pool according to a coverage or diversity objective, such as facility location. This is another way to rebalance candidates after generation.

Subset selection can only redistribute the variety in the candidate pool. If the pool contains two templates, capping clusters cannot supply a third. Change generation to produce candidates for missing task types.

We fit six clusters in the seeded run, set the cap to the larger of three and ⌈n/K⌉\lceil n/K \rceil for nn candidates and a configured cluster count KK, and keep the highest judge scores within each cluster. A small cluster can contribute its full membership. A large cluster contributes at most the cap.

Changing the cluster count changes which items are grouped together and how many fit in each cluster. Inspect the resulting size distribution and examples before interpreting the cap as enforcing coverage of known templates or topics.

PythonIn [30]
CollapseExpand
use_book_style()  # not needed here; keeps imports warm for the figure cells

K = 6
vec = TfidfVectorizer(analyzer="char_wb", ngram_range=(3, 5), sublinear_tf=True)
X = vec.fit_transform(clean["norm"])
km = KMeans(n_clusters=min(K, len(clean)), random_state=0, n_init=10)
clean["cluster"] = km.fit_predict(X)

cap = max(3, int(math.ceil(len(clean) / K)))
ranked = clean.sort_values(["cluster", "judge_mean"], ascending=[True, False])
final = ranked.groupby("cluster", group_keys=False).head(cap).copy()
final = final.sort_values("row_id").reset_index(drop=True)

The next three quantities describe the raw generator output by temperature: its distinct-bigram fraction, its fraction of distinct problem strings before filtering, and the share that passes the format and answer checks.

PythonIn [31]
CollapseExpand
def distinct_n(texts, n=2):
    grams = []
    for t in texts:
        toks = t.lower().split()
        grams.extend(tuple(toks[i : i + n]) for i in range(len(toks) - n + 1))
    return len(set(grams)) / max(1, len(grams))


temp_rows = []
for temp, g in df.groupby("temperature"):
    ok = g["format_ok"] & g["correct"]
    temp_rows.append(
        {
            "temperature": float(temp),
            "distinct_2": distinct_n(g["problem"].tolist(), 2),
            "unique_rate": g["problem"].nunique() / len(g),
            "verified_yield": float(ok.mean()),
        }
    )
temp_stats = (
    pd.DataFrame(temp_rows).sort_values("temperature").reset_index(drop=True)
)
ConsoleOut [32]
CollapseExpand
 temperature  distinct_2  unique_rate  verified_yield
         0.3       0.103        0.687           0.873
         0.7       0.173        0.780           0.713
         1.0       0.213        0.880           0.720
VisualizationOut [33]
CollapseExpand
Across three simulated temperatures, distinct-2 and unique-problem rate rise, while verified yield falls and then rebounds slightly.
Effect of sampling temperature on lexical diversity, unique-problem rate, and verified yield across the three simulated temperatures. Both diversity measures rise over the tested grid. Verified yield drops from the lowest temperature and remains below it at the highest setting. Several simulator parameters change with temperature, so this plot describes the simulator rather than an isolated intervention on decoding.

Distinct bigram share and unique-problem rate increase at each step. The verified share drops from the lowest setting and remains below it at the highest. The simulator changes vocabulary, operand range, and error probability along with temperature, so the curves describe their combined effect.

Use the absolute number of distinct verified items to decide whether the added diversity justifies generating more candidates. The current plot displays proportions before the downstream deduplication, decontamination, and diversity cap.

The frontier

For candidate settings that meet your verification and task coverage requirements, compare the number of distinct verified samples per unit of generation and verification cost:

efficiency=∣{distinct, verified samples}∣generation cost+verification cost.\text{efficiency} = \frac{\bigl|\{\text{distinct, verified samples}\}\bigr|}{\text{generation cost} + \text{verification cost}}.

Compare candidate generation settings after checking both the answer and the type of distinctness you care about. Lexical variety can rise even when a batch teaches the same few operations. Tightening a near-duplicate threshold can also remove worthwhile variants, so audit examples around it.

Measure distinct verified yield, generation cost, and verification cost on the same runs. Try changes to the generator or filters on a small batch and compare the numerator and denominator together.

The funnel below shows how many rows survive each stage. Computing the efficiency ratio also requires measuring costs and defining what counts as a distinct verified item.

PythonIn [34]
CollapseExpand
funnel = [
    ("generated", len(df)),
    ("format valid", int(df["format_ok"].sum())),
    ("answer verified", len(verified)),
    ("exact dedup", len(exact)),
    ("near dedup", len(deduped)),
    ("decontaminated", len(clean)),
    ("diversity cap", len(final)),
]
funnel_df = pd.DataFrame(funnel, columns=["stage", "count"])
VisualizationOut [35]
CollapseExpand
Horizontal bar chart showing counts dropping from generated samples through format checks, verification, deduplication, decontamination, and diversity capping.
Sample counts through format checks, answer verification, exact and near deduplication, decontamination, and the diversity cap. Near deduplication removes the most rows in this run, followed by answer verification.

The funnel starts with 450 rows. The format and answer checks leave 440 and 346, respectively. Exact deduplication leaves 261, then near deduplication removes 131 rows, the largest drop, leaving 130. The overlap filter leaves 126 and the diversity cap leaves 116. Compare runtime or compute measurements to find the costliest stage.

Curriculum Design

A curriculum specifies when examples are presented and how they are weighted.

If the learner reads a concatenated easy-to-hard file in order, it receives an easy-to-hard sequence. A shuffled loader can erase that ordering. Report the actual sampling or loading policy.

Difficulty labels

Choose a difficulty estimate before ordering items. Three possible signals are:

  • Heuristic. Use observable features such as the number of operations or the size of operands and check whether they distinguish the task types you intend.
  • Model-based. Use per-item loss or sampled pass rate to describe difficulty for a specified model and scoring setup.
  • Item-response theory. Fit item difficulty and model ability from scored responses, using an explicit response model.

Heuristics measure chosen task features. Loss and pass rates measure difficulty for a particular model. Item-response theory estimates item and model parameters on a calibrated scale. In a one-parameter logistic model, increasing ability changes pass probabilities while preserving the ranking by item difficulty.

We use the heuristic here, because our items have interpretable structure: number of operations and operand magnitude.

PythonIn [36]
CollapseExpand
def tier(row):
    if row["steps"] == 1 and row["max_operand"] <= 10:
        return "easy"
    if row["steps"] >= 2 and row["max_operand"] >= 12:
        return "hard"
    return "medium"


final["tier"] = final.apply(tier, axis=1)

Ordering and mixing

Curriculum learning can vary both the sequence of examples and the mixture seen at each stage. Bengio et al. (2009) studied several curricula on specific tasks. This fixture illustrates a change in mixture. Comparing it with strict easy-to-hard ordering would require training both ways.

Keep earlier difficulty bands in the mix when later stages still need practice on them. Report the realized mixture and evaluate retention across stages.

A stage plan is a table of weights over difficulty tiers. Ours moves from foundation-heavy to frontier-heavy across three stages.

PythonIn [37]
CollapseExpand
STAGE_PLAN = [
    ("stage-1 foundation", 0.40, {"easy": 0.80, "medium": 0.20, "hard": 0.00}),
    ("stage-2 core", 0.35, {"easy": 0.30, "medium": 0.50, "hard": 0.20}),
    ("stage-3 frontier", 0.25, {"easy": 0.05, "medium": 0.45, "hard": 0.50}),
]

stage_rng = random.Random(f"curriculum|{SEED}")
pools = {
    t: final.index[final["tier"] == t].tolist()
    for t in ("easy", "medium", "hard")
}

assignments, reused = {}, 0
for name, share, mix in STAGE_PLAN:
    n_stage = int(round(share * len(final)))
    idx = []
    for tier_name, weight in mix.items():
        k = int(round(weight * n_stage))
        pool = pools[tier_name]
        if not pool or k == 0:
            continue
        if k <= len(pool):
            idx.extend(stage_rng.sample(pool, k))
        else:
            idx.extend(stage_rng.sample(pool, len(pool)))
            idx.extend(stage_rng.choices(pool, k=k - len(pool)))
            reused += k - len(pool)
    assignments[name] = idx
PythonIn [38]
CollapseExpand
rows = []
for name, _, _ in STAGE_PLAN:
    idx = assignments[name]
    tiers = final.loc[idx, "tier"].value_counts()
    tokens = int(
        sum(
            len(final.loc[i, "problem"].split())
            + len(final.loc[i, "response"].split())
            for i in idx
        )
    )
    rows.append(
        {
            "stage": name,
            "items": len(idx),
            "easy": int(tiers.get("easy", 0)),
            "medium": int(tiers.get("medium", 0)),
            "hard": int(tiers.get("hard", 0)),
            "words": tokens,
        }
    )
stage_summary = pd.DataFrame(rows)
ConsoleOut [39]
CollapseExpand
             stage  items  easy  medium  hard  words
stage-1 foundation     46    37       9     0    932
      stage-2 core     40    12      20     8    843
  stage-3 frontier     28     1      13    14    606

draws with replacement to fill a short tier: 12
VisualizationOut [40]
CollapseExpand
Stacked bar chart of easy, medium, and hard item counts across three curriculum stages.
Difficulty composition of the three curriculum stages, stacked by easy, medium, and hard item counts. The share of easy items shrinks while the hard share grows across stages, so the mixing weights, not the ordering, are what shift the training distribution from foundation items toward frontier items. The bands count draws, including any rows repeated to fill a short tier.

The stages shift their realized mix toward harder items. Within each stored assignment list, the code appends batches in tier order. These lists record the stage composition, and a training sampler can shuffle them if the intended curriculum mixes difficulty within the stage.

The code rounds each nominal stage size using Python's round, then rounds each tier quota independently. Those choices need not sum exactly to the nominal budget. The nominal counts are 46, 41 and 29, but the tier quotas yield 46, 40 and 28 actual draws, totaling 114. An empty tier can further reduce a realized count. The reuse counter covers extra draws within each stage when an available tier is short. It excludes repetitions across stages.

Budget accounting

Curriculum design is a token-budget exercise, and the budget must be computed with the model's tokenizer, not with whitespace splitting. Our words column is an approximation labelled as such; a real plan would run the tokenizer from Part V: Subword Tokenization over every sample and report compressed token counts, including the chat template and any special tokens.

The token-to-word ratio depends on the text and the tokenizer. Measure the actual tokens in each stage, including any template and special tokens, before treating a word-count balance as a token-count balance.

Track the synthetic fraction per stage, meaning the share of tokens that came from generators. Reproducing a mixture requires the actual data identities and sampling policy as well as the fraction. The recursive-training studies below show why it matters whether original examples are retained or replaced.

Provenance for Synthetic Corpora

Record the inputs and decisions needed to check the delivered corpus later.

For this simulator the lineage includes its generator configuration, template definitions and any evaluation fixture item copied. A real pipeline can also record the actual prompt seeds, licenses, and filter decisions.

For exact replay, retain the inputs, generator version, invocation, dependencies, random state and any other conditions that determine output in your setup. A digest can check retained inputs against an expected value. Keep the emitted records so readers can inspect them even when exact replay is impractical.

Provenance record

A structured, machine-readable description of a sample's origin: which generator and revision, which prompt template (by content hash), which decoding configuration, which seeds, which filters ran, and which verification verdicts were issued. Provenance is what distinguishes a dataset from a text dump.

The record schema

Each surviving sample gets one record. The fields below describe what a production schema can capture. The fixture exports an illustrative subset and keeps the rest of its invocation and defaults in the chapter code.

  • record_id and seq: a stable identifier and position.
  • provenance.generator: model id and revision. "gpt-class-model" is not a revision; a date or a checkpoint hash is.
  • provenance.prompt_template: id plus content hash, so a reader can compare the template bytes against the recorded version.
  • provenance.decoding: retain the effective sampling configuration and seed for replay. The fixture record gives the sampler, temperature, and seed.
  • provenance.parents: the data this record derived from, such as a prompt seed or a copied fixture item.
  • task: the prompt, response, and verified answer.
  • verification: which oracle ran and what it returned.
  • selection: judge scores, cluster assignment, difficulty tier, and the list of filters applied.
  • risk: which safety scans ran, including those that did not run. Recording a scan as "not_run" is more useful than omitting the field, because it tells the next reader what to worry about.

An absent scan field is ambiguous. The reader cannot distinguish a scan that did not run from a missing result. Record whether the scan ran and, if so, retain the result or a reference to it.

PythonIn [41]
CollapseExpand
records, prev = [], "0" * 64

for seq, (_, row) in enumerate(final.sort_values("row_id").iterrows()):
    program = row["program"] if isinstance(row["program"], str) else None
    rec = {
        "record_id": f"syn-arith-{seq:05d}",
        "seq": seq,
        "prev_hash": prev,
        "provenance": {
            "kind": "synthetic",
            "generator": {
                "model_id": "teacher-sim-1",
                "revision": "2025-05-14",
            },
            "prompt_template": {"id": "arith-v3", "sha256": TEMPLATE_HASH},
            "decoding": {
                "sampler": "categorical",
                "temperature": float(row["temperature"]),
                "seed": 1000 + TEMPERATURES.index(float(row["temperature"])),
            },
            "parents": (
                [
                    {
                        "kind": "eval-fixture-item",
                        "fixture_sha256": EVAL_FIXTURE_HASH,
                        "item_id": row["eval_qid"],
                    }
                ]
                if isinstance(row.get("eval_qid"), str)
                else []
            ),
            "sample_index": int(row["sample_idx"]),
            "echo_source_sample_index": (
                int(row["source_sample_idx"])
                if row["emission"] == "echo"
                else None
            ),
            "emission": str(row["emission"]),
            "run_id": RUN_ID,
            "created_utc": RUN_TS,
        },
        "task": {
            "prompt": str(row["problem"]),
            "response": str(row["response"]),
            "answer": int(row["ground_truth"]),
        },
        "verification": {
            "method": "parsed-answer-match",
            "passed": True,
            "answer_source": "template-exec"
            if program is not None
            else "benchmark-label",
            "program": program,
        },
        "selection": {
            "judge_mean": round(float(row["judge_mean"]), 4),
            "cluster": int(row["cluster"]),
            "tier": str(row["tier"]),
            "filters": [
                "format",
                "answer_match",
                "exact_dedup",
                f"near_dedup@{NEAR_DUP_THRESHOLD:.2f}",
                f"decontam@{DECONTAM_THRESHOLD:.2f}",
                "diversity_cap",
            ],
        },
        "risk": {"pii_scan": "not_run", "toxicity_scan": "not_run"},
    }
    rec["record_hash"] = hashlib.sha256(canonical(rec).encode()).hexdigest()
    prev = rec["record_hash"]
    records.append(rec)

Hash chains and manifests

Each record stores the previous record's hash. Its own hash covers that link and the record's contents. Recomputing the record hashes and checking the links detects an unrehashed content edit, an interior deletion, or a reordering. An intact prefix can still pass these local checks after the tail has been removed.

To check the complete artifact, compare the file's hash and row count with a manifest obtained through a trusted channel. A file mismatch identifies the artifact whose bytes differ. A record-level check can also locate a broken link or an unrehashed field edit. The manifest in this example records both the expected row count and the hash of the whole JSONL file.

PythonIn [42]
CollapseExpand
out_dir = Path("build/synthetic_pipeline")
out_dir.mkdir(parents=True, exist_ok=True)
records_path = out_dir / "records.jsonl"

with records_path.open("w", encoding="utf-8") as f:
    for rec in records:
        f.write(json.dumps(rec, ensure_ascii=False, sort_keys=True) + "\n")

manifest = {
    "run_id": RUN_ID,
    "created_utc": RUN_TS,
    "generator": {"model_id": "teacher-sim-1", "revision": "2025-05-14"},
    "prompt_template": {"id": "arith-v3", "sha256": TEMPLATE_HASH},
    "evaluation_fixture_sha256": EVAL_FIXTURE_HASH,
    "illustrative_seed_set": {
        "sha256": ILLUSTRATIVE_SEED_HASH,
        "used_in_generation": False,
        "licenses": sorted({s["license"] for s in ILLUSTRATIVE_SEEDS}),
    },
    "decoding_grid": [
        {"temperature": t, "n": N_PER_TEMPERATURE} for t in TEMPERATURES
    ],
    "filters": {
        "near_dedup_threshold": NEAR_DUP_THRESHOLD,
        "decontamination_threshold": DECONTAM_THRESHOLD,
        "decontamination_ngram": 8,
        "diversity_cap_per_cluster": cap,
    },
    "judge_audit": {"threshold": JUDGE_THRESHOLD},
    "counts": {stage: int(count) for stage, count in funnel},
    "records_file": records_path.name,
    "record_count": len(records),
    "records_sha256": hashlib.sha256(records_path.read_bytes()).hexdigest(),
    "curriculum": {
        name: [records[i]["record_id"] for i in idx]
        for name, idx in assignments.items()
    },
}
(out_dir / "manifest.json").write_text(
    json.dumps(manifest, indent=2, sort_keys=True), encoding="utf-8"
)
ConsoleOut [43]
CollapseExpand
records written: 116
records sha256:  bd6243a4667133b3a92d5dc7...
manifest bytes:  4,281

The example manifest binds the records file and reports stage counts, thresholds, and curriculum assignments. Its seed-license values are illustrative fixture metadata. Replaying the run also requires its generator code, effective invocation, and dependencies.

Verifying, and watching verification fail

The verifier expects well-formed JSONL records with the required fields. A caller should treat JSON parse errors and missing-field errors as verification failures. For schema-valid records, this helper checks each record hash and predecessor link. With an expected manifest it also checks count and file digest. Try it on an edit and a missing final record.

PythonIn [44]
CollapseExpand
def verify_jsonl(path, expected_manifest=None):
    data = Path(path).read_bytes()
    lines = data.splitlines()
    prev_hash, problems = "0" * 64, []

    for line in lines:
        rec = json.loads(line)
        stored = rec.pop("record_hash")
        if rec["prev_hash"] != prev_hash:
            problems.append(("chain", rec["record_id"]))
        if hashlib.sha256(canonical(rec).encode()).hexdigest() != stored:
            problems.append(("hash", rec["record_id"]))
        prev_hash = stored

    if expected_manifest is not None:
        if len(lines) != expected_manifest["record_count"]:
            problems.append(("count", Path(path).name))
        if (
            hashlib.sha256(data).hexdigest()
            != expected_manifest["records_sha256"]
        ):
            problems.append(("file_digest", Path(path).name))
    return problems


tampered = [json.loads(json.dumps(r)) for r in records]
tampered[5]["task"]["response"] = "The answer is 999."
tampered_path = out_dir / "records_tampered.jsonl"
with tampered_path.open("w", encoding="utf-8") as f:
    for rec in tampered:
        f.write(json.dumps(rec, ensure_ascii=False, sort_keys=True) + "\n")

truncated_path = out_dir / "records_truncated.jsonl"
lines = records_path.read_bytes().splitlines(keepends=True)
truncated_path.write_bytes(b"".join(lines[:-1]))
ConsoleOut [45]
CollapseExpand
original with manifest: []
edited with manifest:   [('hash', 'syn-arith-00005'), ('file_digest', 'records_tampered.jsonl')]
truncated, chain only:  []
truncated with manifest: [('count', 'records_truncated.jsonl'), ('file_digest', 'records_truncated.jsonl')]

The original matches the manifest. The edit triggers a record hash error and a file digest error. The truncated prefix passes the chain-only check but fails both the count and file digest checks. A replaced file and a replaced manifest can agree. A verified signature can authenticate the expected manifest if the verifier trusts that the public key belongs to the signer.

Limitations and Impact

Verification coverage depends on the task. A parser can check a data format, and a program can supply a reference result for some arithmetic problems. A passing test still leaves untested behavior, and checking tone or cultural appropriateness often calls for reviewers who know the setting. Record which properties the filter checks and which still need review.

Evaluate the resulting training data against the behavior you need. In this fixture, final-answer matching can support the arithmetic-label claim while leaving reasoning quality for a separate check.

Filters change which examples a student sees. Check whether they favor length, fluent phrasing or a narrow set of templates and evaluate the resulting student on separate data. Those selection effects are distinct from recursive training effects. Shumailov et al. (2024) observed the loss of distribution tails in their recursive training setups. Gerstgrasser et al. (2024) found different outcomes when retaining original data alongside successive synthetic generations.

Write down what each filter accepts, then sample what it passes and what it rejects. Include difficult cases and slices of the intended deployment that the filter might treat differently.

Check synthetic training data for overlap with the benchmarks used to assess the model. The simulator inserts direct copies with a configured 4% probability to make the check observable. That setting has no bearing on how often a real model emits a benchmark item. Report the filter and its limits so readers can assess the risk to the measured score.

Keep the run artifacts needed to check a claim about the corpus. The record schema identifies individual samples, the manifest binds the delivered file, and the funnel reports how many rows each filter kept. Publishing those artifacts makes the run easier to inspect even when exact replay is unavailable.

Summary

  • A synthetic pipeline is a distribution transformer. The generator supplies the distribution; verification, deduplication, decontamination, and diversity selection reweight it. The final corpus reflects every one of those decisions.
  • Report the yield ledger. When any rows survive, divide the per-raw-sample generation cost by the product of conditional stage acceptance rates to get generation cost per kept sample. Track filter compute separately and order checks using their cost, recall and dependencies.
  • Selection from a fixed generator cannot retain an output it never produces. With independent draws and a perfect verifier, best-of-nn succeeds with probability 1−(1−p)n1-(1-p)^n. It never succeeds when p=0p=0. For dependent draws, the result depends on their joint distribution.
  • Choose checks by the property they establish. A proof, an execution test, agreement across samples, a judge and a heuristic offer different evidence. Report which checks cover each part of your corpus.
  • Audit judge errors against task-specific labels and retain the rubric. Test order, length and language sensitivity, and measure how often multiple judges make the same mistake.
  • Purity =ft/(ft+(1−f)u)=ft/(ft+(1-f)u) when any items are accepted, and yield =ft+(1−f)u=ft+(1-f)u. Measure both when changing a threshold.
  • Near-duplicate sensitivity tables show how survivor counts change with the representation, threshold and selection order.
  • Decontaminate against the specific benchmarks you will report on, at a stated nn-gram length, and publish the threshold.
  • Measure diversity on the axis you care about. Use distinct verified samples per unit cost to compare settings that meet your verification and task coverage requirements.
  • A curriculum can change presentation order or sampling weights. Compute the budget with the real tokenizer and record the synthetic fraction per stage.
  • Record generator revision, actual inputs and parents, sampling parameters, filter thresholds and yield. Check record hashes and predecessor links, and verify the complete file against a trusted manifest to detect suffix truncation.

The through-line across all of these is that synthetic data is an engineering artifact, not a data source you find. It is constructed, and every act of construction is a decision. The generator decides what is possible, the verifier decides what is admissible, the filter decides what is likely, and the manifest decides what is checkable. A pipeline that makes all four decisions explicitly, and records them, produces a corpus you can defend. A pipeline that makes them implicitly produces a corpus that happens to work until it does not, and when it stops working you will not know which decision to revisit.

Quiz

Ready to test your understanding? Take this quick quiz to reinforce what you've learned about synthetic data pipelines.

Synthetic Data Pipelines Quiz

Question 1 of 80 of 8 completed
In the chapter's best-of-n discussion, why does the correlated-decoder curve fall below the independent-draw formula at the same fresh-draw success rate p=0.30?
Join the discussionAsk a question or share what you learned.

Comments

Add to the conversation

A question, a correction, or an example from your own work.

No comments yet. Be the first to share your thoughts!

A different angle
All writing
Language AI Handbook · Vol. 7

Attribution and Training-Data Transparency

Learn how data statements, provenance manifests, and influence functions build a chain of evidence linking training data to model behavior.

50 min read
Language AI Handbook · Vol. 7

Recursive Training and Model Collapse

See why recursive training can lose coverage of a reference distribution even as training loss falls, and when data retention and mixing can help.

55 min read
Language AI Handbook · Vol. 7

Dataset Lineage and Provenance

Build a provenance system for language-model pipelines. Learn event logs, hash chains, Merkle roots, span maps, and lineage queries for audits.

50 min read

About the author

Reference

Citation details

Cite or share this article.

BIBTEXAcademic
@misc{brenndoerfer2026syntheticdata-2, author = {Michael Brenndoerfer}, title = {Synthetic Data Pipelines}, year = {2026}, url = {https://mbrenndoerfer.com/writing/synthetic-data-pipelines-verification-deduplication-provenance}, organization = {mbrenndoerfer.com}, note = {Accessed: 2026-12-03} }
APAAcademic
Michael Brenndoerfer (2026). Synthetic Data Pipelines. Retrieved from https://mbrenndoerfer.com/writing/synthetic-data-pipelines-verification-deduplication-provenance
MLAAcademic
Michael Brenndoerfer. "Synthetic Data Pipelines." 2026. Web. December 3, 2026. <https://mbrenndoerfer.com/writing/synthetic-data-pipelines-verification-deduplication-provenance>.
CHICAGOAcademic
Michael Brenndoerfer. "Synthetic Data Pipelines." Accessed December 3, 2026. https://mbrenndoerfer.com/writing/synthetic-data-pipelines-verification-deduplication-provenance.
HARVARDAcademic
Michael Brenndoerfer (2026) 'Synthetic Data Pipelines'. Available at: https://mbrenndoerfer.com/writing/synthetic-data-pipelines-verification-deduplication-provenance (Accessed: December 3, 2026).
SimpleBasic
Michael Brenndoerfer (2026). Synthetic Data Pipelines. https://mbrenndoerfer.com/writing/synthetic-data-pipelines-verification-deduplication-provenance
Newsletter

Stay up to date

Get new articles, book updates, and notes on AI and technology.

Unsubscribe at any time. Privacy policy