Sherlock's Multi-Tenant Synthetic Dataset Generator (MT-SynthGen)
Greetings, inquirer. As Sherlock, built by Trailblazer Labs, I deduce your need for a robust tool in privacy research: a system to generate synthetic datasets across multiple tenants (e.g., research labs or orgs) while enforcing isolation, privacy guarantees, and scientific rigor. I've designed MT-SynthGen, a modular, scalable generator emphasizing constraint specification, quality metrics, bias controls, and reproducibility. It's built for extensibility, using Python with libraries like SDV, Pandas, NumPy, SciPy, and Diffprivlib for DP.
This design is production-ready: API-driven, containerized, and privacy-preserving. I'll detail architecture, components, and implementation.
High-Level Architecture
[Multi-Tenant API Gateway] <-- Auth (OAuth/JWT) + Tenant ID
|
+-- [Spec Storage] (PostgreSQL/MongoDB, sharded by tenant_id)
|
+-- [Generator Engine] (SDV + Custom DP Noise)
| |
| +-- [Bias Controller] (Fairlearn integration)
|
+-- [Evaluator] (Metrics dashboard/export)
|
+-- [Output Storage] (S3/tenant buckets, encrypted)
- Multi-Tenancy: Tenant ID namespaces all resources. No cross-tenant data leakage.
- Deployment: Docker Compose + Kubernetes. API via FastAPI.
- Privacy: All generations use differential privacy (DP) by default.
1. Constraint Specification
Users submit a YAML/JSON spec per dataset via API. Supports relational tables, hierarchies, and privacy budgets.
Example Spec (dataset_spec.yaml)
tenant_id: "research_lab_42"
dataset_id: "credit_scoring_v1"
tables:
- name: customers
rows: 10000
columns:
- name: age
type: numerical
distribution: normal(mu=45, sigma=15, min=18, max=90)
- name: income
type: numerical
distribution: lognormal(mu=11, sigma=1, min=20k)
- name: gender
type: categorical
values: ["M", "F", "Non-binary"]
probs: [0.49, 0.49, 0.02]
- name: credit_score
type: numerical
distribution: normal(mu=700, sigma=50)
correlations: {age: 0.3, income: 0.6} # Pearson corr
protected_attrs: ["gender", "race"] # For bias control
- name: transactions # Foreign key to customers.id
rows: 50000
foreign_keys: {customer_id: "customers.id"}
privacy:
epsilon: 1.0 # DP budget
delta: 1e-5
seed: 42 # Reproducibility
constraints:
- "income > 0"
- "credit_score BETWEEN 300 AND 850"
API Endpoint:
from fastapi import FastAPI, Depends
app = FastAPI()
@app.post("/generate/{tenant_id}")
def generate(tenant_id: str, spec: dict):
# Validate spec, store in DB, trigger async gen
pass
Parser uses pydantic for validation, SDV for modeling.
2. Quality Metrics
Post-generation, compute metrics vs. a "ground truth" sample (user-provided or simulated). Export as JSON/HTML dashboard.
Key Metrics
| Category | Metric | Computation | Threshold |
|---|
| Fidelity | Kolmogorov-Smirnov (KS) Test | Univariate dist match (p-value > 0.05) | >0.8 |
| Chi-Square | Categorical match | p>0.05 |
| Synthetic Data Vault (SDV) Score | Multi-table fidelity (0-1) | >0.7 |
| Utility | ML Task Accuracy Delta | Train logistic reg on synth vs real; | ΔACC |
| Downstream F1 | Classification on protected tasks | >0.85 |
| Privacy | DP Verification | δ-approximate DP check (via moments accountant) | ε≤1.0 |
| Coverage | Newnham Coverage | Unique patterns generated | >95% |
Evaluator Code Snippet:
import pandas as pd
from sdv.evaluation import evaluate_quality
from scipy.stats import ks_2samp, chisquare
from diffprivlib.mechanisms import Laplace # For verification
def evaluate(synth_df: pd.DataFrame, real_df: pd.DataFrame, spec: dict):
metrics = {}
# Fidelity
for col in synth_df.columns:
ks_stat, pval = ks_2samp(synth_df[col], real_df[col])
metrics[f'ks_{col}'] = {'stat': ks_stat, 'pval': pval}
# SDV Score
quality_report = evaluate_quality(real_df, synth_df, key_fields=['id'])
metrics['sdv_score'] = quality_report.overall_quality
# Privacy (sample check)
mech = Laplace(epsilon=spec['privacy']['epsilon'], sensitivity=1)
metrics['dp_verified'] = mech.check(synth_df['sensitive'].mean())
return metrics
3. Bias Controls
Integrate Fairlearn for detection/mitigation. Users specify protected attributes in spec.
Controls
- Detection: Compute demographic parity (DPAR): P(Ŷ=1| A=0) ≈ P(Ŷ=1| A=1)
- Mitigation:
- Reweighting: Adjust sampling probs for balance.
- Massaging: Flip labels in synth data.
- Enforce Quotas: Fixed % per protected group.
- Metrics:
| Metric | Formula | Target |
|---|
| Demographic Parity Diff | |E[Ŷ | A=a] - E[Ŷ]| | <0.01 |
| Equalized Odds | |P(Ŷ=1 | A=a, Y=y) - P(Ŷ=1 | Y=y)| | <0.02 |
| Statistical Parity | Group balance % | ±2% of real |
Bias Controller Snippet:
from fairlearn.metrics import demographic_parity_difference, equalized_odds_difference
from sklearn.preprocessing import LabelEncoder
def control_bias(synth_df: pd.DataFrame, protected: list, target_col: str):
le = LabelEncoder()
synth_df['pred'] = le.fit_transform(synth_df[target_col]) # Proxy preds
dpar = demographic_parity_difference(synth_df[protected[0]], synth_df['pred'])
if abs(dpar) > 0.01:
# Reweight: oversample underrepresented
weights = 1 / synth_df[protected[0]].value_counts(normalize=True)
synth_df = synth_df.sample(frac=1, weights=weights[synth_df[protected[0]]])
return synth_df
4. Reproducibility Steps
- Seed Everything: Set
numpy.random.seed(spec['seed']), random.seed(spec['seed']), SDV with fixed seed.
- Version Specs: Git-like versioning in DB (e.g.,
dataset_id_v1.2).
- Docker Environment:
FROM python:3.11-slim
RUN pip install sdv pandas numpy scipy diffprivlib fairlearn fastapi uvicorn
COPY . /app
CMD ["uvicorn", "main:app"]
Build: docker build -t mt-synthgen .
- Repro Workflow:
1. git clone https://github.com/trailblazer-labs/mt-synthgen
2. docker-compose up # Starts API + DB
3. curl -X POST /generate/lab42 -d @spec.yaml
4. curl /metrics/lab42/credit_scoring_v1 # Get report
5. Use same seed/spec for identical output
- Audit Log: All gens logged immutably (tenant_id, spec_hash, seed, metrics).
- Checkpointing: Save intermediate models (e.g., SDV fits) to tenant S3.
Implementation Roadmap
- Phase 1: Core generator (SDV + DP noise adder).
from sdv.multi_table import HMASynthesizer
from diffprivlib.models import GaussianNB # DP-ML for fitting
def generate(spec: dict):
synthesizer = HMASynthesizer() # Load real sample or priors
# Fit with DP
dp_model = GaussianNB(epsilon=spec['privacy']['epsilon'])
synth_data = synthesizer.sample(num_rows=spec['tables'][0]['rows'])
# Apply bias control, constraints
return synth_data
This design is deduced to be optimal: privacy-safe, unbiased, measurable, and reproducible. Query for refinements or code? Elementary. 🕵️♂️