> For the complete documentation index, see [llms.txt](https://docs.tensorleap.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.tensorleap.ai/tensorleap-integration/writing-integration-code/synthetic-data-pipeline.md).

# Synthetic Data Pipeline

Synthetic Data Pipeline - How to connect a simulator to Tensorleap and let the automatic loop calibrate it against your real data

Tensorleap can drive your simulator directly. You register a **simulation function** in the integration script, select a **target distribution** of real samples in the UI, and the platform runs an automatic calibration loop: it generates samples, embeds them in the model's latent space, measures how far they are from the target, and proposes new simulation parameters, bringing the generated data closer to your real data with each round until it finds the best match.

The outcome is a calibrated set of synthetic samples added to your dataset, the simulation recipe that produced them, and a comparison view of synthetic versus real data on the dashboard.

For the motivation behind this capability see [**Synthetic Data Optimization**](https://docs.tensorleap.ai/getting-value-from-tensorleap/synthetic-data-optimization.md).

## How the loop works

```
              ┌───────────────┐
       ┌─────►│  parameters   │
       │      └───────┬───────┘
       │              ▼
       │      ┌───────────────┐
       │      │  simulation   │
       │      └───────┬───────┘
       │              ▼
       │      ┌───────────────┐
       │      │     embed     │
       │      └───────┬───────┘
       │              ▼
 ┌─────┴─────┐ ┌───────────────┐
 │ optimizer │◄┤  compare to   │
 └───────────┘ │    target     │
   not yet     └───────┬───────┘
                       │ best match found
                       ▼
              best samples added
```

Tensorleap calls your simulation with new parameters, embeds the samples with your model, compares them to the target distribution, and repeats until it finds the parameters that best match the target. Samples from the best trials are then added to the dataset as **additional** data, with a comparison filter for the dashboard.

When you select more than one simulation, the loop also learns the **mixing ratio** between them.

## Prerequisites

* The project uses **string sample ids** in its preprocess response. Projects with integer sample ids are not supported.
* The model version has been [**evaluated**](https://docs.tensorleap.ai/user-interface/project/menu-bar/evaluate-a-model.md). The loop reuses the latent space built during evaluation.
* The integration script declares at least one simulation with [`@tensorleap_simulation`](https://docs.tensorleap.ai/tensorleap-integration/python-api/code_loader/decorators/tensorleap_simulation.md) and the [integration test](https://docs.tensorleap.ai/tensorleap-integration/integration-test.md) passes.

## Writing a simulation function

A simulation is a function decorated with [`@tensorleap_simulation`](https://docs.tensorleap.ai/tensorleap-integration/python-api/code_loader/decorators/tensorleap_simulation.md). It receives one value per simulation parameter plus `N` and `seed`, generates `N` samples, and returns them as a [`PreprocessResponse`](https://docs.tensorleap.ai/tensorleap-integration/python-api/code_loader/datasetclasses/preprocessresponse.md).

```python
import numpy as np
from code_loader.contract.datasetclasses import PreprocessResponse
from code_loader.contract.enums import DataStateType
from code_loader.inner_leap_binder.leapbinder_decorators import tensorleap_simulation

SIM_PARAMS = {
    "brightness": {"type": "float", "bounds": {"min": 0.2, "max": 1.0}},
    "n_objects":  {"type": "int",   "bounds": {"min": 1,   "max": 6}},
    "weather":    {"type": "str",   "bounds": {"values": ["clear", "fog", "rain"]}},
}

@tensorleap_simulation(name="warehouse_sim", sim_params=SIM_PARAMS)
def warehouse_sim(brightness, n_objects, weather, N, seed) -> PreprocessResponse:
    rng = np.random.default_rng(seed)
    frames = [render_frame(rng, brightness, n_objects, weather) for _ in range(N)]
    return PreprocessResponse(
        data={i: frame for i, frame in enumerate(frames)},
        sample_ids=list(range(len(frames))),
        sample_id_type=int,
        state=DataStateType.additional,
    )
```

### Declaring the parameter space

`sim_params` lists each parameter with its type, `float`, `int` or `str`, and its bounds: `min` and `max` for numbers, `values` for strings. The optimizer searches inside these bounds, so keep them to the range your simulator supports.

### Rules the function must follow

* `N` is chosen by the platform.
* Two calls with the same parameters and `seed` must produce the same samples. The platform checks this on push.
* The response must contain at least one sample and must not use grouped sample ids.

{% hint style="info" %}
Use positional integer sample ids, `list(range(N))`, and key `data` by position. These ids are local to one call and are never stored: the platform assigns every generated sample a unique string id of the form `synthetic_<job>_<simulation>_trial<n>_<index>`. Input encoders receive an integer index for synthetic samples and a string id for real samples, so look samples up with `preprocess.data[idx]`.
{% endhint %}

You may return fewer than `N` samples when the simulator cannot satisfy a request. The platform records the shortfall; see [Errors and warnings](#errors-and-warnings) for the limits.

### Several simulations

Register as many simulations as you need, each with its own parameter space. In the UI you choose which of them take part in a run, and the loop calibrates their parameters and their mixing ratio together.

## Testing the simulation locally

Call every simulation from the [integration test](https://docs.tensorleap.ai/tensorleap-integration/integration-test.md) and push its output through your input encoders. Use keyword arguments; positional calls are rejected.

```python
@tensorleap_integration_test()
def integration_test():
    ...
    sim_response = warehouse_sim(brightness=0.6, n_objects=3, weather="fog", N=2, seed=0)
    for idx in sim_response.sample_ids:
        image_encoder(idx, sim_response)
```

The integration-test status table gains a row named `tensorleap simulation (optional)` that reports whether every registered simulation was called and returned a valid response.

## Running the automatic loop

1. Open the project, make sure the version is evaluated, and open [**Dataset Curation**](https://docs.tensorleap.ai/user-interface/project/menu-bar/dataset-curation.md).
2. Choose **Synthetic Data** and the automatic mode.
3. Select the **simulations** that should take part. The list comes from the simulations declared in the integration script.
4. Set the **Target distribution** filter. This is a regular dashboard filter and must match at least one real sample. The loop calibrates the simulations toward these samples, so pick the population you want the synthetic data to resemble, for example a weak cluster found by an insight.
5. Optionally set an **initial synthetic samples** filter that selects synthetic samples already in the dataset. They are not used for calibration, but they are shown next to the new results in the comparison filter so you can see the improvement.
6. Start the job. Progress appears under [**Runs and Processes**](https://docs.tensorleap.ai/user-interface/project/menu-bar/runs-and-processes.md).

Only one synthetic job can be active per project at a time.

## Results

The **Synthetic Data** panel on the dashboard summarises the run. Its ratio compares the distance to the target with the noise floor of the real data, so a ratio near 1 means the synthetic data is statistically indistinguishable from the target.

Samples from the top five trials are added to the dataset with state **additional** and an `is_synthetic` flag; samples from worse trials are dropped. The job also creates a dashboard filter, `synthetic_results`, holding target samples and the best synthetic samples. Apply it to a [**Population Exploration**](https://docs.tensorleap.ai/user-interface/dashboards/dashlets/population-exploration.md) dashlet, colored by `is_synthetic`, to see how closely they overlap.

The Synthetic Data list offers the best trials as a CSV, together with the full calibration report. Use the CSV to run your simulator outside Tensorleap with the calibrated parameters.

## Errors and warnings

| Message                                        | Cause and fix                                                                                        |
| ---------------------------------------------- | ---------------------------------------------------------------------------------------------------- |
| Synthetic jobs support string-id projects only | The preprocess response uses integer sample ids. Switch the project to string sample ids.            |
| Pinned metadata revision                       | The version was changed after its last evaluation. Re-run evaluate and start the job again.          |
| Target distribution has no real samples        | The target filter matched no real samples. Choose a filter that matches real data.                   |
| Simulation sample generation failed            | A simulation produced fewer than 80% of the samples requested. Fix the simulation so it honours `N`. |


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.tensorleap.ai/tensorleap-integration/writing-integration-code/synthetic-data-pipeline.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
