Synthetic Data Pipelines › A Worked Pipeline
Language AI HandbookAll chapters 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]Expand
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]Expand
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]Expand
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]Expand
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 outA 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]Expand
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]Expand

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