Synthetic Data Pipelines › Filtering and Verification
Language AI HandbookAll chapters 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:
- Formal check. A proof assistant checks a stated proposition relative to its axioms. A type checker checks the program's stated typing properties.
- 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.
- 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.
- 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.
- 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.
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 and a good one with probability , and suppose their errors are independent. Requiring of votes converts the per-judge false-positive rate into
For unanimity, the false-positive rate is . With and three independent judges, this is . 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 be the fraction of raw items your labels mark as good, the true-positive rate, and the false-positive rate. These three quantities determine yield and, if anything passes, purity. They leave other properties of the retained corpus unspecified.
Increasing a score threshold can only reduce or preserve yield on the same candidates. With positive and , purity rises if the accepted true-to-false-positive rate ratio rises. At fixed rates with , a higher base rate improves yield and purity when both classes can pass. For , , and , purity is about and yield is . The filter rejects of all candidates even though they are good, alongside 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]Expand
# 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]Expand

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]Expand
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]Expand
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]Expand
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]Expand

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]Expand
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]Expand
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]Expand
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]Expand
after exact dedup: 261 (removed 85 duplicate rows)
threshold kept
0.70 44
0.80 75
0.90 130
0.95 207The 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]Expand
dedup_thresholds = sensitivity["threshold"].to_numpy(dtype=float)
dedup_kept = sensitivity["kept"].to_numpy(dtype=int)
exact_count = int(len(exact))VisualizationOut [25]Expand

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]Expand
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]Expand
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.
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]Expand
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]Expand
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.
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!