Sub topic 14
Generating synthetic training text
This chapter shows how to ask a language model to write new labeled examples, and how to keep that data from misleading you. It assumes you have read the earlier chapters on labeling functions, the label model, and LLMs as labeling sources. It also assumes basic Python and a trained text classifier whose F1 you can measure.
Labeling versus generating
The earlier chapters started from real, unlabeled text and attached labels to it. Synthetic generation reverses the order. You choose the label first, then ask a model to write text that fits it. The label is intended by construction, not predicted, so it is cheap and usually right. The text is the uncertain part, because it comes from the model's habits and not from your real users.
Generation helps in three situations:
- Rare classes. Real data has 40 examples of "refund fraud" and 40,000 of everything else.
- No unlabeled text yet. The product has not launched, or privacy rules block access to real messages.
- Coverage gaps. Your labeling functions fire on obvious phrasings and miss paraphrases, so you want varied wordings.
Generation does not replace real text. A classifier trained only on generated text learns the generator's style, and its scores on that style say little about production.
The generation pipeline
Each stage below removes a specific kind of damage.
Build prompts from a spec
A single prompt repeated 1,000 times produces 1,000 near-copies. Vary the prompt along axes you care about, such as topic, tone, length, and the writer's persona. Each (label, topic, style) combination becomes one call. This also lets you control class balance directly.
Put the label in the prompt exactly once and avoid naming the other classes. Mentioning "not negative" tends to pull the output toward the thing you excluded.
Parse, deduplicate and check
Models return lists with numbering, bullets, and stray commentary, so parse defensively. Then drop duplicates after normalizing case and punctuation, and drop near-duplicates by word overlap. Finally, run a round-trip check: classify each generated text with an independent labeler and keep it only if that labeler agrees with the label you asked for. This is the confidence filter from the previous chapter, applied to intended labels. The check removes texts that came out ambiguous, such as a "negative" review that reads as mixed.
A runnable generator
The code takes the model as a plain function, ask, that maps a prompt string to a reply string. That keeps it independent of any vendor library. The demo uses a stub in place of a real model so that it runs as written.
import itertools
import re
LABELS = ('positive', 'negative')
def build_prompt(label, topic, style, n):
return (
f'Write {n} different short product reviews about {topic}. '
f'Each review must express a {label} opinion. Style: {style}. '
'Put one review per line, numbered.'
)
def parse_lines(reply):
out = []
for line in reply.splitlines():
line = re.sub(r'^\s*(?:\d+[.)]|[-*])\s*', '', line).strip()
if line:
out.append(line)
return out
def normalize(text):
return re.sub(r'\W+', ' ', text.lower()).strip()
def jaccard(a, b):
sa, sb = set(a.split()), set(b.split())
union = sa | sb
return len(sa & sb) / len(union) if union else 0.0
def deduplicate(pairs, max_overlap=0.8):
"""Drop (text, label) pairs that nearly repeat an earlier one."""
kept, seen = [], []
for text, label in pairs:
norm = normalize(text)
if any(jaccard(norm, s) >= max_overlap for s in seen):
continue
seen.append(norm)
kept.append((text, label))
return kept
def generate(ask, topics, styles, n=3):
pairs = []
for label, topic, style in itertools.product(LABELS, topics, styles):
reply = ask(build_prompt(label, topic, style, n))
pairs.extend((t, label) for t in parse_lines(reply))
return deduplicate(pairs)
def round_trip_filter(pairs, classify):
"""Keep pairs where an independent classifier agrees with the intended label."""
return [(t, y) for t, y in pairs if classify(t) == y]
# Stub model and stub classifier so the example runs without any API.
def fake_ask(prompt):
if 'negative' in prompt:
return ('1. The case cracked after two days.\n'
'2. Battery dies by noon.\n'
'3. Battery dies by noon!\n'
'4. Great idea, but it broke immediately.')
return ('1. Love the screen, very sharp.\n'
'2. Fast delivery and it works well.\n'
'3. Excellent value for the price.')
def fake_classify(text):
t = text.lower()
if any(w in t for w in ('cracked', 'dies', 'broke')):
return 'negative'
if any(w in t for w in ('love', 'works well', 'excellent')):
return 'positive'
return None
pairs = generate(fake_ask, topics=['a phone'], styles=['casual'])
print(len(pairs)) # 7 -> the exact repeat of 'Battery dies by noon' was removed
clean = round_trip_filter(pairs, fake_classify)
print(len(clean)) # 6 -> the mixed review is still counted as negative by the stub
for text, label in clean:
print(label, '|', text)The deduplication step removes the third negative line, which differs from the second only by punctuation. With a real model you should expect more near-duplicates than this, and raising max_overlap or lowering it changes how aggressively you prune. Check how many examples survive at each stage, because a large drop at the round-trip step means your prompts are producing ambiguous text.
Mixing synthetic and real data
Treat generated text as a supplement. A workable default is to start with real weakly labeled text and add synthetic examples only for classes or phrasings where error analysis shows gaps. Then compare the end model with and without them on the gold set, as in the earlier evaluation chapter. If the synthetic data does not raise gold-set F1, leave it out.
Two practical points apply when you mix:
- Seed with real examples. Put two or three real, representative texts in the prompt as few-shot examples. Generated text then drifts less from your domain's length, vocabulary and typos.
- Track provenance. Store a
sourcecolumn (real_weak,synthetic) with every row. You will need it to run ablations and to debug later.
Risks specific to synthetic text
Low diversity
Models repeat their favorite phrasings. Ten thousand "reviews" may share a dozen openings. Measure diversity directly: count distinct unigrams or bigrams, or the share of examples that start with the same three words. Low diversity makes the classifier brittle, since it learns the phrasings and not the concept.
Label leakage through style
If every positive example says "I absolutely love" and every negative one says "Unfortunately," the classifier can learn those openers and ignore everything else. It will score well on synthetic validation data and poorly on real text. Check by training a bag-of-words model on the synthetic set and inspecting its top features. Strong, generator-specific tokens are a warning sign.
Distribution shift
Real text has typos, sarcasm, code-switching, and truncated sentences. Generated text is usually fluent and polite. A model trained mostly on the latter can fail on the former. Ask for noise explicitly in the style axis ("typos, no punctuation, all lowercase"), and judge the result only on real data.
Contamination and feedback loops
Never put synthetic examples in the gold set or test set. If the same model generates training text and later labels or evaluates it, errors reinforce each other and your metrics look better than reality. When the generator and the round-trip classifier come from the same model family, their blind spots overlap, so the agreement check is weaker than it appears. Use a different model or a rule-based check for at least a sample.
Decision criteria
| Situation | Suggested approach |
|---|---|
| Plenty of real unlabeled text | Label it with functions and an LLM; skip generation. |
| One rare class with few examples | Generate for that class only, seeded with the real examples. |
| No real text available | Generate broadly, then replace it with real weakly labeled text as soon as possible. |
| Gold-set F1 does not improve | Remove the synthetic data and inspect it for leakage and low diversity. |
Exercise
A team generates 5,000 negative and 5,000 positive support messages with one prompt, trains a classifier, and reports 98% accuracy on a held-out slice of that same synthetic data. On real messages the accuracy is 71%. Give two likely causes and one check for each.
Show answer
Cause 1: low diversity or label leakage through style. The generator uses consistent openers and vocabulary per class, so the classifier learns those cues. Check by training a bag-of-words model on the synthetic set and reading its top features, and by counting repeated openings. Cause 2: distribution shift, with the fluent generated text unlike real messages that contain typos, sarcasm and fragments. Check by comparing length, vocabulary and error rates between a sample of real and synthetic messages, then regenerate with noisy styles and real few-shot seeds. The 98% figure is also invalid evidence because the evaluation slice was synthetic. It should be replaced with a real gold set.
Exercise
In the code above, why does round_trip_filter take the classifier as an argument, and what goes wrong if it is the same model that generated the text?
Show answer
Passing the classifier in lets you use a labeler independent of the generator. If the generator also does the checking, it tends to agree with its own output, so ambiguous or wrongly styled examples pass. The filter then removes fewer bad examples than it appears to, and errors the model makes in both roles reinforce each other.