← Case studies

diffu-syn

A tabular diffusion model behind a FastAPI and Celery job API

Training a generative model takes minutes, which is too long for an HTTP request. diffu-syn puts a denoising diffusion model for numeric tabular data behind a FastAPI service that queues training, generation and evaluation as Celery jobs on Redis, with files on a shared volume. It shows the job-API pattern end to end, plus a from-scratch DDPM that I can explain line by line.

Type
Case study
Built with
Python, PyTorch, FastAPI, Celery, Redis, Docker
Published
Reading time
9 min

The problem

Teams often need data that looks like their production tables (same columns, similar distributions) but contains no real records. A generative model can produce that, but training one is slow and CPU/GPU heavy. If an API does the training inside the request handler, the request times out, a crash takes the web process down with it, and there is no way to see what is running.

diffu-syn is my attempt at both halves of that: a small diffusion model for numeric tables, usable as a Python library (TabularDiffusion().fit(df).generate(n)), and a service that runs the same code as background jobs. You upload a CSV, get a task id, poll for status, trigger generation from the trained model, download the synthetic CSV, and optionally ask for a quality report.

Architecture

docker compose Client upload CSV, poll API service FastAPI + uvicorn Redis broker + results Celery worker train / generate / eval Flower job monitor ./data volume raw, models, out enqueue task result upload in, synthetic CSV out

Figure 1. Job flow in the version I ran end to end: the API only stores files and enqueues; the worker does the heavy work and reports back through the Redis result backend.

The codebase is split into two packages:

  • diffusyn.core: the library. TabularModel (an MLP noise predictor), DiffusionEngine (the DDPM forward and reverse processes), DiffuSynDataset (a Polars-backed IterableDataset), and TabularDiffusion, which ties them together with a min-max scaler, fit / generate / save / load, and an SDMetrics quality report.
  • diffusyn.interface: the service. api.py (FastAPI routes /train, /status/{id}, /generate, /evaluate, /download/{file}), worker.py (Celery tasks), storage.py (a storage interface plus a local-disk implementation) and config.py (pydantic-settings, all overridable with DIFFUSYN_* env vars).

POST /train streams the upload to data/raw/<uuid>.csv and enqueues a training task. The worker trains, saves a .pth checkpoint under data/models/, and returns {"model_path": ...} as the task result. POST /generate takes the training task id, reads its result from Redis to find the checkpoint, and enqueues a generation task that writes data/outputs/syn_<uuid>.csv. /evaluate runs an SDMetrics column-shape report on a worker. The API and worker containers share the ./data mount, which is how the model file written by one is visible to the other. Flower runs as a separate container for watching the queue.

Key design decisions

Celery workers instead of training in the request. FastAPI’s BackgroundTasks would have been simpler (no broker, no second container), but it runs in the API process: a long PyTorch job competes with request handling and dies with it. Celery puts training in its own process with retries (self.retry(countdown=60, max_retries=3)), event reporting (-E) and a dashboard (Flower). The cost is two more moving parts (Redis and the worker) and the need for a shared filesystem between API and worker.

The task id is the handle; there is no database. Generation looks up the training task’s result in the Celery result backend to find the model path. That avoids a jobs table and a migration story, at the cost of durability: Redis results expire (Celery’s default is one day), so after that a model can no longer be found by id even though the file is still on disk. A small jobs table is the obvious next step.

A storage interface before there is a second backend. StorageService is a typing.Protocol with save_upload and get_local_path; LocalStorage writes uploads with aiofiles in 1 MB chunks so a large CSV never sits in API memory. Workers ask for a local path, so an S3 implementation would download to a temp dir first and the training code would not change.

Library first, server as an extra. pyproject.toml keeps the core deps (torch, polars, sdmetrics) separate from a [server] extra (FastAPI, Celery, Redis). The dev Dockerfile installs CPU-only PyTorch in its own layer before copying pyproject.toml, so source edits do not trigger a multi-GB reinstall. Dockerfile.prod is a two-stage build: dependencies go into a venv in a builder image, and the runtime image copies only the venv and runs as a non-root user.

DDPM on min-max-scaled numbers rather than a GAN. Diffusion training is a plain regression (predict the noise that was added), so it is stable without GAN tricks. The price is slow sampling: generation runs the network 1,000 times per batch. Data is scaled to [-1, 1] to match the Gaussian noise, and the scaler’s min/max values are saved inside the checkpoint so load() restores both the model and the inverse transform.

Inside the code

The heart of the model is about twenty lines in core/diffusion.py. Training picks a random timestep per row, noises the data in closed form, and asks the network to predict that noise:

def q_sample(self, x_0, t, noise=None):
    """ Forward Process (Add Noise) """
    if noise is None:
        noise = torch.randn_like(x_0)
    sqrt_alphas_cumprod_t = torch.sqrt(self.alphas_cumprod[t])[:, None]
    sqrt_one_minus_alphas_cumprod_t = torch.sqrt(
        1 - self.alphas_cumprod[t])[:, None]
    return (sqrt_alphas_cumprod_t * x_0
            + sqrt_one_minus_alphas_cumprod_t * noise), noise

def compute_loss(self, x_0):
    """ Training Loss """
    batch_size = x_0.shape[0]
    t = torch.randint(0, self.steps, (batch_size,), device=self.device)
    noise = torch.randn_like(x_0)
    x_t, real_noise = self.q_sample(x_0, t, noise)
    predicted_noise = self.model(x_t, t)
    return F.mse_loss(predicted_noise, real_noise)

Because alphas_cumprod is precomputed, the model never has to step through 1,000 noising steps during training; any timestep is one multiply-add away. In a quick local run (5,000 rows, two columns, 40 epochs on CPU) the generated columns came back with means and standard deviations close to the originals.

The chaining between jobs lives in interface/api.py. The generate endpoint refuses to queue work against a model that does not exist yet:

@app.post("/generate")
async def trigger_generation(request: GenerateRequest, req: Request):
    training_result = celery_app.AsyncResult(request.task_id)

    if not training_result.successful():
        raise HTTPException(
            status_code=400,
            detail=f"Training not complete or failed. "
                   f"Status: {training_result.status}")

    full_model_path = training_result.result.get("model_path")
    if not full_model_path:
        raise HTTPException(
            status_code=404,
            detail="Model info not found in training result")
    # … enqueue the generation task, return its id and a download URL

This is where the “task id as handle” decision shows up: the API stays stateless, and Redis is the source of truth for whether a model is ready.

Running it

# redis, api on :8000, worker, flower on :5555
docker compose up -d --build
# 50 training jobs from 10 threads; watch Flower drain the queue
python tests/stress_test.py
pytest tests/unit tests/api
# production image: multi-stage build, non-root user
docker compose -f docker-compose.prod.yml up -d --build

What I’d do next

The honest state of the repo:

  • The latest commit is a scaffold, not a working path. In July 2026 I added core/orchestration.py and core/streaming.py to sketch named GPU queues and chunked training. The /train and /generate routes now go through that code, and it is not finished: the worker tasks it calls use placeholder models, the compose worker does not subscribe to the new queues, and the orchestrator reads a different env var for its Redis URL. The train, generate, download flow above is the January 2026 version (commit 1c62e98), which I ran end to end against a real Redis and Celery worker. Restoring that path under the new names is the first fix.
  • Memory: fit() reads the whole CSV with pl.read_csv because the scaler needs global min/max. Streaming training needs a first pass for statistics, then a batched pass. The file-path branch of DiffuSynDataset.__iter__ is also broken (it checks for an attribute it never sets); only the in-memory branch is used today.
  • Data types: numeric columns only; categoricals must be encoded beforehand. Generated values are not clipped to [-1, 1] before un-scaling, so some fall slightly outside the training range.
  • Ops: the CI workflow file and Makefile are empty, there is no health endpoint, no auth, and logs are print. One unit test is out of date (validation moved into __init__). Opacus is a dependency but differential privacy is not implemented.

Skills this shows

  • Async job orchestration: FastAPI producer, Celery consumer, Redis broker and result backend, retries with back-off, job chaining by task id, Flower for visibility.
  • Containerisation: layer-cached CPU PyTorch install, multi-stage production image with a venv and non-root user, compose with Redis health-check gating and shared volumes.
  • Backend API design: chunked async uploads, config through env-prefixed pydantic settings, a storage interface that keeps S3 a drop-in change.
  • Applied ML: a DDPM implemented from the equations (beta schedule, closed-form forward process, posterior variance in sampling), sinusoidal time embeddings, residual MLP, checkpointing model plus scaler, SDMetrics evaluation.
  • Testing and load: pytest with a mocked Celery result backend, and a threaded stress script that pushes jobs through the real API.