Synthetic Data Pipelines › Diversity Control
Language AI HandbookAll chapters 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 list all -gram occurrences, including repeats. The distinct- ratio counts unique types over occurrences. The implementation below returns zero for an empty list:
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:
Here are the eigenvalues of . The positive-semidefinite kernel has and , 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.
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 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 for candidates and a configured cluster count , 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]Expand
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]Expand
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]Expand
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.720VisualizationOut [33]Expand

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

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