How to Fill Data Gaps: Inside the LLM-Driven Data Factory

    This article explains why high-quality training data is the real bottleneck for large language models and how an LLM-driven data factory addresses it. It covers the shift from one-off preprocessing scripts to writing data flows as code, the six design goals behind this paradigm, and a four-pillar reference architecture built on storage abstraction, layered interfaces, an operator taxonomy, and plugins. It then details how agents assemble pipelines through intent parsing, operator retrieval, static validation, and small-scale trials, why a small set of verifiable synthetic samples can outperform massive web-scale mixtures, and how to evaluate data quality while avoiding common pitfalls. The article closes with general guidance for running a data factory in the cloud.

    1. Where the Problem Starts: Compute Can Be Bought, Quality Data Cannot

    A conclusion that keeps proving itself in large language model engineering is that data quality sets the ceiling on model intelligence. Gaps in algorithms and compute can usually be closed through procurement and iteration, but weaknesses in training corpora — in coverage, correctness, and difficulty distribution — harden directly into a cap on model capability. So the question “do we lack data to train models?” rarely has a simple yes-or-no answer. The real issue is structural mismatch: generic web text is massively oversupplied, while high-quality reasoning chains, executable code, and math processes with verified answers remain chronically scarce.

    The traditional response treats data preparation as one-time preprocessing: a pile of temporary scripts, a handful of regex rules, some command-line glue, delivered once it runs. This model has three fatal problems. First, the workflow is fragmented — cleaning, deduplication, rewriting, and scoring are scattered across different directories with no unifying abstraction. Second, it is hard to reproduce — rules live in code and in people’s memory, so a new maintainer has to rewrite everything. Third, it cannot scale or be reused — operators are tightly coupled, and replacing one step means changing the entire chain.

    Early batch-oriented data cleaning solutions in the industry were designed to filter and extract from existing massive corpora, and they excelled at “subtraction.” But once model capabilities improved, filtering alone was no longer enough to fill capability gaps, so the industry turned to model-in-the-loop generative data preparation: letting models participate in generating, rewriting, judging, and selecting data to form a closed loop. This is exactly the problem an “LLM-driven data factory” is meant to solve.

    2. Paradigm Shift: Write the Data Flow as a Program

    The core proposition of a data factory is to standardize and codify the data preparation process. Just as deep learning frameworks define how models and gradients are constructed, this class of frameworks defines how data flows are constructed: where data comes from, which transformations it passes through, where it gets filtered, how it is evaluated, and where it finally lands — all expressed as readable, testable, versionable code.

    The design philosophy usually revolves around six goals:

    • Usability: a code-first strategy rather than inventing a complex configuration file format, so developers can describe pipelines with familiar syntax and enjoy editor completion, go-to-definition, and breakpoint debugging.
    • Extensibility: adding a new data transformation should not require modifying the framework core — just implement the agreed interface and register it.
    • Unified paradigm: generation, cleaning, scoring, and distillation share one set of abstractions, avoiding multiple parallel systems.
    • High performance: operators support batching and concurrency internally, and the scheduling layer supports distributed execution and resume-from-checkpoint.
    • Intelligent automation: agents retrieve and orchestrate operators automatically from a task description and generate candidate pipelines.
    • Open source and auditable: the flow is code, so it naturally enters version control and code review.

    A schematic usage pattern looks roughly like this (general pseudocode only, to illustrate the abstraction level):

    1. from dataflow import Pipeline, Storage, operators as ops
    2. pipe = Pipeline(name="math_sft_factory")
    3. # 1) Load and normalize
    4. pipe.add(ops.LoadFromStorage(Storage(kind="object_store", uri="raw://math_seed")))
    5. pipe.add(ops.NormalizeText())
    6. # 2) Model-in-the-loop synthesis: generate problems and reasoning chains
    7. pipe.add(ops.LLMGenerate(prompt_template="gen_problem", temperature=0.8, n=4))
    8. pipe.add(ops.LLMGenerate(prompt_template="gen_cot", role="solver"))
    9. # 3) Quality gates: executable checks + model review
    10. pipe.add(ops.ExecutableCheck(sandbox=True)) # code/math answers are verifiable
    11. pipe.add(ops.LLMScore(rubric="correctness,clarity,difficulty"))
    12. pipe.add(ops.FilterByScore(min_score=0.75))
    13. # 4) Dedup and difficulty tiering, write out as a training set
    14. pipe.add(ops.SemanticDedup(threshold=0.9))
    15. pipe.add(ops.SplitByDifficulty(bins=["easy","mid","hard"]))
    16. pipe.run(resume=True)

    3. Four Pillars of the Architecture: A Practical Reference Skeleton

    Turning that experience into engineering reality usually rests on four parts.

    The first is a global storage abstraction. The objects models process are unstructured text — instructions, responses, chains of thought — but inside the pipeline they need structured representation. A common approach is to use a tabular data structure (such as a columnar or in-memory table) as the unified data unit, where each row is a sample and each column is a field (raw text, generation result, score, metadata). The storage backend is decoupled into pluggable implementations — local files, a distributed file system, or object storage — so the same pipeline code migrates smoothly between single-machine debugging and cluster runs.

    The second is a layered programming interface. The bottom layer is the operator interface, the middle layer is the pipeline and executor, and the top layer is scenario-facing templates and agent entry points. The benefit of layering is separation of concerns: algorithm researchers change operators, platform engineers change scheduling, and business teams only write high-level intent.

    The third is an operator taxonomy. A practical classification includes: read/write operators, text normalization operators, generation operators (prompt synthesis, answer synthesis, chain-of-thought synthesis), transformation operators (rewriting, translation, difficulty up/down, format conversion), evaluation operators (rule checks, model scoring, diversity metrics), filtering and deduplication operators, and aggregation operators (grouping, stratified sampling, mixing ratios). Only with a clear taxonomy can agents retrieve and compose operators automatically.

    The fourth is the extension mechanism. A registry plus agreed interfaces enables plugins: implementing the semantics of apply(batch) -> batch is enough to register an operator; configuration templates and unit test conventions are also provided to ensure community-contributed operators are verifiable and rollback-able.

    4. How Agents Build Pipelines Automatically

    The key to automation is not letting the model “write code freely,” but turning orchestration into a constrained search. A viable path has four steps:

    1. Intent parsing: turn “I want ten thousand medium-difficulty math samples with verifiable answers” into a structured goal (domain, count, difficulty, verification method, budget).
    2. Operator retrieval: do semantic retrieval based on operator descriptions and tags to get a candidate operator set and their input/output contracts.
    3. Plan generation and static validation: the agent generates a directed acyclic graph and checks whether field dependencies are closed, whether cycles exist, and whether a quality gate is missing.
    4. Small-sample trial and iteration: first run at one-thousandth scale, auto-tune parameters based on the output distribution and score feedback (for example, raising temperature to increase diversity or tightening thresholds to improve correctness), then run at full scale.

    Engineering must keep human confirmation points: steps involving data compliance, copyright sources, and sensitive content filtering should be reviewed by people, with the agent only making suggestions.

    5. Why Fewer, Better Samples Beat Million-Scale Piles

    The phenomenon that “only ten thousand high-quality synthetic samples outperform million-scale open-source mixed datasets on math, code, and similar tasks” can be explained in three ways. The first is signal-to-noise ratio: in large-scale web corpora, messy formatting, wrong answers, and repeated templates make up a high proportion, and the model learns the noise along with the rest. The second is difficulty matching: synthetic data can be generated in a targeted way at the edge of the current model’s capability — samples that are “learnable but not easy” — which yields higher learning efficiency. The third is verifiability: math and code naturally come with automatic verification, answers can be checked by execution or derivation, and wrong samples can be intercepted at the generation stage.

    It is worth stressing that this conclusion has boundary conditions: it holds for tasks with clear goals that can be verified automatically. For open-ended writing, common sense, and factual knowledge, synthetic data still needs to be mixed with real corpora and fact-checked, otherwise it amplifies hallucination.

    6. Quality Evaluation and Common Pitfalls

    A three-layer evaluation is recommended:

    • Sample level: rule checks (executable, parseable, length and format), model scoring (correctness/clarity/difficulty), anomaly detection.
    • Dataset level: deduplication rate, distribution entropy, difficulty histogram, domain mix, template diversity.
    • Training side: small-scale ablation experiments comparing the validation-set gains of different data recipes, forming a closed feedback loop.

    Common pitfalls include diversity collapse from model self-distillation; data homogenization from a single prompt template; over-filtering that deletes long-tail hard cases along with the bad ones; bias from a scorer that shares the same origin as the model being scored; and ignoring data provenance and licensing, which creates compliance risk. Corresponding practices are to introduce multi-model cross review, randomize a template pool, reserve a quota for hard cases, and record the source and generation parameters for each sample for auditing.

    7. Engineering Advice for Running It in the Cloud

    To run a data factory in production, you can assemble it from the following general capabilities: use object storage to hold raw and produced corpora; use a container platform to run operators and sandbox checks; use a message queue to decouple operators and smooth out peaks; use a distributed cache to speed up small-table broadcasts; use logging and monitoring/alerting to track throughput, failure rates, and score distributions; and use key management to hold model access credentials. In these scenarios, Baidu AI Cloud typically supports the above general product categories in combination; refer to the official documentation for specific specifications.

    8. Conclusion

    Data preparation is moving from a manual workshop to an automated factory: data flows defined in code, capabilities accumulated in operators, orchestration handled by agents, and quality guarded by automatic verification. The direct benefits for developers are reproducibility, extensibility, and higher data output per unit of compute. For implementation, start with a single verifiable task, build the quality gates before talking about scale, and let ablation experiments drive recipe iteration — the key to filling data gaps is not piling on more text, but producing the right data.