Module: L2-M02 · Duration: ~90 min (estimate, including the independent exercise) · Previous: L03 · Next: L05
1. Introduction
Real logs are biased and expert-written cases take effort. Synthetic data, meaning cases generated in bulk by a model or a script, sounds like the way out: cheap, fast, covers many variants. It is also the source most likely to ruin a dataset, because its errors arrive silently and in bulk: one wrong case is multiplied a hundred times and still looks like real data.
This lesson teaches how to use synthetic data under control: know which kinds of errors it produces, build a filtering step for each kind, read the filter funnel, and say plainly what the filter does not catch. The product of the lesson is a set of generated cases with a reported filtering step. The whole lab runs offline: the "model that generates cases" here is a seeded script with planted defects, so that we know the truth when we check the filter.
2. Learning objectives
- State when synthetic data is reasonable and its four groups of risk.
- Build a generate-then-filter pipeline: schema, PII, language, answer verification, overlap with existing data, near-duplicates, a limit on the number of cases per sentence template.
- Read the filter funnel (how many cases were rejected for which reason) and compute the diversity of the result.
- Point out an error that your filter does not catch, and add a check step for it.
- Explain why a synthetic set usually gives nicer measurements than reality, and why you must report separately by source.
3. Prerequisites and tools
- L2-M02-L01 to L03: sources, coverage, labels and reference answers.
- L2-M01-L04: pass rate; this lesson compares rates across different datasets.
- The code lab
code-labs/l2-m02. No API key needed; there are no real model calls.
4. Concepts
4.1 What synthetic data is, and when it is reasonable
Synthetic data in this lesson is a case created by an automated process from existing cases or from a description: a model writing more similar questions, a script changing the numbers and names in a sentence template. It is reasonable when you need many variants of a situation you already understand well (for example the same division problem with different numbers), or need to cover the empty cells of the matrix (L02) that the log does not have.
OpenAI's guidance puts synthetic data in its list of eval sources and suggests using it to build diverse test sets across many scenarios [R1]. Self-Instruct, a study on letting a model generate instructions itself, shows the standard process: generate then filter. The authors added a new instruction to the pool only when its ROUGE-L similarity to every existing instruction was below 0.7, excluded instructions containing certain keywords the model could not handle, dropped instances (a specific input/output pair) that were duplicates or had the same input but a different output, and dropped invalid generations using heuristics [R2]. They also noted that the generated instances "may contain more noise" than the instructions [R2]. Two lessons: filtering is part of the method, not a side step; and the label quality of generated data must be doubted.
4.2 Four groups of risk
- Wrong labels or answers. A model writes "24 divided by 4 equals 7" with great confidence. If you do not recheck, you grade the system against a wrong answer.
- Duplication. Bulk generation yields many near-identical copies. They make the measurement "heavy" on one situation and make the sample less independent than you think (L2-M01-L04: the unit of sampling is the case).
- Homogeneity. The same generator has habits: the same sentence template, the same kind of numbers, the same writing style. The dataset looks big but covers only one corner, usually the
cleancolumn and thehintintent of the matrix. - Too easy compared with real. Generated cases rarely carry the typing errors, missing diacritics, trailing-off sentences or vague intent of real users. Measurements on them are usually higher than measurements on real traffic.
One more risk, about leakage: if the same model both generates the cases and is the system being measured, or generated cases are reused as examples in the prompt, the measurement is skewed in ways that are hard to see. This lesson has no source it read for two related hypotheses: (a) the system under measurement has an advantage when the cases were generated by itself (or by the same model family); (b) a judge model favors answers it wrote itself (L2-M04 will return to this). Treat both as hypotheses to test in your own project, and see L05 on contamination.
5. Technical deep dive
5.1 The generate-then-filter pipeline
synth.SimulatedGenerator(seed, existing_texts) generates candidates from four math sentence templates (divide, subtract, multiply, add) with preset proportions skewed toward division, and plants defects at fixed rates: a wrong answer, the wrong language, a copy of an existing case, a phone number, a near-duplicate, and a sentence with insufficient data. The defect field is the hidden truth that lets the demo grade the filter; a real pipeline has no such field.
synth.filter_candidates(cands, existing_texts, near_threshold, per_template_cap) runs the steps in order and rejects each candidate at the first step it fails:
| Step | What it checks |
|---|---|
schema |
Has a cand_id and a non-empty question |
pii |
Contains PII (uses lab.pii from L01) |
language |
Is Vietnamese, counting function words, with or without diacritics |
answer |
Recomputes the answer from the structured fields and compares it with the claimed answer |
existing |
Too similar to an existing case (avoids copying into the dataset) |
near_duplicate |
Too similar to a candidate already kept |
template_cap |
Over the allowed count for one sentence template |
Similarity uses Jaccard over the set of words (the share of common words; it ignores order and repeat counts, so "12 candies ... 3 boxes" and "3 candies ... 12 boxes" give 1.0 and are treated as duplicates, while a copy typed without diacritics scores low and slips through), with a default threshold of 0.9, and the threshold must be in (0, 1]; a threshold of 0 would treat everything as a duplicate, so the function raises an error. This is the lab's own choice, not Self-Instruct's ROUGE-L 0.7 [R2]; which measure and threshold to choose is your decision, so record it.
5.2 Reading the funnel: 200 candidates
Demo A generates 200 candidates (seed 21) and filters them. 150 remain; 19 were rejected for the answer, 14 for near-duplication, 10 for language, 7 for PII. Among the 200, 48 candidates had a planted defect (14 wrong answers, 12 near-duplicates, 9 wrong language, 6 with PII, 5 missing data, 2 copies), and no planted defect remains among the 150 kept candidates. Do not read that as "a perfect filter": we planted only the errors the filter was written to catch. The funnel shows two more details. Two candidates that defect records as having no defect (S076, S112) were also rejected as near-duplicates, and the filter was right: each is word-for-word identical to a candidate already kept (S076 matches S025, S112 matches S108, Jaccard 1.0). The generator happened to repeat a sentence, and the hidden truth defect does not mark that. Also, the 19 rejections at the answer step consist of 14 wrong answers and 5 sentences with missing data (the claimed answer is empty). And the existing step was not triggered in this run, because both copied cases had already failed an earlier step (one on PII, one on language); tests/test_l04_synthetic.py checks that step separately.
5.3 What the filter does not catch: plausibility and diversity
synth.verify_answer recomputes the answer from op, a, b and compares it with the claimed value. It catches arithmetic errors. It does not check that the question matches the fields (the sentence says 24 marbles but the field says 25), and does not check whether the result is plausible. Demo D: "24 marbles split equally among 5 friends" with a claimed answer of 4.8 passes both verify_answer and the filter, and a subtraction that comes out negative (5 - 9 = -4 marbles) passes too. The tests pin both as blind spots. The fix is to add a step: the exercise in §9 asks you to write whole_number_ok and apply it.
On diversity, the generator's habit shows clearly: division makes up 0.525 of the 200 candidates (addition only 0.095). per_template_cap=10 makes the four sentence templates account for 0.25 each, at the price of only 40 cases remaining. The gain is that the set is not dominated by one habit; the loss is that many valid cases are dropped. Choose the cap by the coverage goal, not by a nice-looking number.
6. The QA perspective
6.1 Measurements on a synthetic set are usually nicer than reality
The lab compares the true pass rate (the simulation knows the failure probability) on two sets: the whole fictional log 0.876; the 150 kept synthetic cases 0.920. This difference comes from the construction of the simulation: every synthetic case has the hint intent and the clean style, so it falls where the simulated system fails least. This is not a measurement on a real model, but its direction is what QA must guard against: an easy set gives a nice number. The consequence for reporting: report separately by source (production, expert, synthetic), do not merge everything into one number; and do not use the synthetic set to make a decision in place of the production or expert set.
6.2 Manually review a subset, and the rules of use
The automatic filter catches the errors it knows. For the rest, a person reviews a random sample of the filtered set: large enough to see a group of errors, recording the number of errors found and their kinds. If the review finds a new kind of error, add a filter step for it (like whole_number_ok) and filter the whole set again. Each synthetic case must carry origin: synthetic plus the generator name and seed, so that later you can separate them out when in doubt. A short rule of use: synthetic to widen variants and fill empty cells, expert-written cases or real logs to anchor the dataset in reality.
7. Real-world scenarios
Scenario 1 (fictional): "A thousand cases in one afternoon". The team asked a model to generate 1,000 math sentences and put them straight into the dataset. Nobody recomputed the results. With a planted answer-error rate like the lab's (14 out of 200, which is 7%), about 70 cases have a wrong answer. For a check like "the tutor does not state the result", a wrong reference answer means the check forbids the wrong number by mistake: an answer that reveals the correct result still passes, while an answer that correctly confirms in a check case is unfairly graded as a failure. This error is built by construction to illustrate; nobody knows in advance the true rate of a generating model.
Scenario 2 (fictional): "A nice number". A team reported 0.92 pass on the synthetic set and 0.88 on the real log (the simulation's numbers) as two separate numbers, but the presentation kept only the first because "the set is bigger". The release decision rested on a nice-looking number, not on a number representing users.
8. Hands-on tutorial
8.1 Setup
cd academy-content/code-labs/l2-m02
python3 -m venv .venv && source .venv/bin/activate # Windows: .venv\Scripts\activate
python -m pip install -r requirements.txt
python -m pytest # 73 passed
8.2 Run the demo
python -m lab.demo l04
Output (copied from a real run on Python 3.14.6 and 3.12.14, 2026-11-03; the two versions give identical output):
A. 200 generated candidates through the filter (seed 21)
kept 150; rejected: answer 19, near_duplicate 14, language 10, pii 7
candidates with a planted defect: 48; planted defects still in kept: 0
B. diversity: share of each template before and after a cap of 10 per template
all candidates {'add': 0.095, 'div': 0.525, 'mul': 0.18, 'sub': 0.2}
after cap {'add': 0.25, 'div': 0.25, 'mul': 0.25, 'sub': 0.25} (40 kept)
C. the pass rate the simulated system truly has on different datasets
whole production log 0.876
kept synthetic cases 0.920
D. what the verifier does not check
24 / 5 = 4.8 marbles: verify_answer -> True, filter kept -> True
Reading the output:
- A. The funnel: 150 kept, 50 rejected; no planted defect remains.
- B. Division makes up more than half before the cap; after
per_template_cap=10the four sentence templates are all 0.25 and 40 cases remain. - C. The true pass rate of the simulated system: 0.876 on the log, 0.920 on the filtered synthetic set (by construction, not a measurement of a real model).
- D. The sentence with the answer 4.8 passes both.
8.3 Run the filter on a small batch
Save as try_l04.py inside the lab folder:
from lab import synth
cands = synth.SimulatedGenerator(seed=5).generate(30)
kept, rejected = synth.filter_candidates(cands)
print(len(kept), {k: len(v) for k, v in rejected.items()})
print(sum(bool(c["defect"]) for c in cands), sum(bool(c["defect"]) for c in kept))
print(synth.language_of("lan co 24 vien bi, chia deu cho 4 ban"), synth.language_of("How many marbles has each friend"))
print(synth.verify_answer({"op": "sub", "a": 5, "b": 9, "claimed": -4}))
Run python try_l04.py. Output:
21 {'answer': 5, 'near_duplicate': 1, 'pii': 1, 'language': 2}
9 0
vi en
True
This time there is no existing_texts, so that step does not run. Line 3: the language detector handles a sentence without diacritics. Line 4: a negative number is still treated as a valid answer.
8.4 Run the lesson's tests
python -m pytest tests/test_l04_synthetic.py -v
Result: 8 passed. Read test_verify_answer_catches_slips_and_pins_what_it_does_not_catch and test_filter_reports_the_first_failing_step.
8.5 Troubleshooting
| Symptom | Cause | Fix |
|---|---|---|
ValueError: near_threshold must be in (0, 1] |
The threshold is 0 or greater than 1 | Use a value in (0, 1] |
A valid Vietnamese case is rejected for language |
A short sentence with few function words is recognised as unknown |
language_of is a rough heuristic; extend the word list or review the rejected cases by hand |
The funnel has no existing line |
The candidates failed an earlier step | Normal; check that step with its own test |
9. Independent exercise
Problem: Read the filter funnel of a batch of candidates and add the check step the filter is missing.
Requirements: complete exercises/test_l04_filter.py:
- TODO 1: fill in
FUNNEL: the number of candidates rejected for each reason when runningsynth.filter_candidates(CANDS)oncandidates.json(leave out reasons with 0). - TODO 2: fill in
UNREALISTIC: the ids (in order) of the candidates the filter keeps but that cannot have a plausible whole-number answer. - TODO 3: write
whole_number_ok(c)returningFalsefor a division with a remainder, a negative result or a divisor of 0, andTruefor the remaining cases.
Test data: exercises/candidates.json (20 fictional candidates with planted defects and some unrealistic sentences).
Deliverable: two variables and one function you wrote.
Acceptance criteria: python -m pytest exercises/test_l04_filter.py passes (3 tests); your function handles the boundaries correctly: division by 0, a result of 0, and multiplication.
Hint: run the filter first and look at the kept part; a claimed answer can be a decimal; a subtraction that comes out 0 is still valid.
10. Knowledge check
0/14 done · Results are kept in this browser only.
P02 · True or false
P04 · Select all that apply
P05 · Put in order
P06 · Match
P07 · Spot the bug
The snippet below is taken from try_l04.py in §8.3 with one spot changed. Running it reports ValueError: near_threshold must be in (0, 1]. Find the bug.
from lab import synth
cands = synth.SimulatedGenerator(seed=5).generate(30)
kept, rejected = synth.filter_candidates(cands, near_threshold=0)
print(len(kept), {k: len(v) for k, v in rejected.items()})P08 · Short answer
Demo A reports planted defects still in kept: 0. Why is that not evidence that the filter is perfect, and what do you do next?
P09 · Essay
The team asks the model to generate 1,000 math problems and puts them straight into the dataset, with nobody recomputing the answers. Write 5-8 sentences: estimate how many cases have a wrong answer (use the lab's rate), the consequence for the measurement, and how you would build the process.
P10 · Multiple choice
P11 · Fill in the blank
P12 · Recall
Lesson: L2-M02-L02P13 · Recall
Lesson: L2-M01-L0411. Summary
- Concepts: synthetic data widens variants and fills empty cells but carries four risks: wrong labels, duplication, homogeneity, too easy; generation always goes together with filtering.
- Skills: build a multi-step filter funnel; read the rejection reasons; measure diversity; add a step for a new error; report separately by source.
- Traps: treating "no planted errors left" as "no errors left"; treating a large synthetic set as representative; merging the measurements of different sources.
- You can now: take a synthetic set and ask: what is filtered, what is not, who recomputed the answers, and is the measurement looking nice because the set is too easy.
12. References
| ID | Title | Publisher | URL | Accessed | Relevance |
|---|---|---|---|---|---|
| R1 | Evaluation best practices | OpenAI | https://developers.openai.com/api/docs/guides/evaluation-best-practices | 2026-11-03 | Synthetic data in the list of eval sources; building diverse test sets |
| R2 | Self-Instruct: Aligning Language Models with Self-Generated Instructions (Wang et al., arXiv:2212.10560) | arXiv | https://arxiv.org/abs/2212.10560 | 2026-11-03 | Generate then filter: ROUGE-L threshold 0.7, duplicate removal, heuristics; noisier instances (full PDF read) |
Key terms (English ↔ Vietnamese)
| English | Tiếng Việt |
|---|---|
| Synthetic data generation | Sinh dữ liệu tổng hợp |
| Filtering step / filter funnel | Bước lọc / phễu lọc |
| Near-duplicate | Bản gần trùng |
| Template / template cap | Khuôn câu / giới hạn số case mỗi khuôn câu |
| Diversity | Độ đa dạng |
| Verifier | Bộ xác minh đáp án |
| Homogeneity | Đồng dạng: các case giống nhau về văn phong và khuôn câu |