Skip to content

ASynthetic data · synth.tvae

Synthetic data — tabular VAE (TVAE)

Can a variational autoencoder trained on this table's rows generate new rows that keep its distributions and relationships?

An encoder network squeezes each row into a small Gaussian code and a decoder rebuilds the row from a draw of it; the loss balances rebuilding the row against keeping the codes close to a standard normal, so decoding fresh normal draws gives new rows. Numbers enter through mode-specific normalization — each column's own Gaussian mixture, so skewed and multi-peaked columns survive — and categories as one-hot blocks, as in the TVAE of the CTGAN paper (written from the paper; the BUSL-licensed CTGAN/SDV code is not used). It usually trains more steadily than a GAN. A share of rows is held out for the privacy and utility checks. Lab tier: torch in both engines from the same initial weights and noise draws.

Experimental Python and R use different algorithms; results agree in substance Seeded Also called TVAE, tabular VAE, tabular variational autoencoder…

A real result

Example “Customers all”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

Synthetic data — tabular VAE (TVAE)Recorded · Python and R agreeRecorded 2026-11-25 · 57 values compared · largest relative difference 3.6e-15
R

320 synthetic rows over 8 columns from 320 training rows with a tabular variational autoencoder. Numeric columns differ from the data by a mean Kolmogorov–Smirnov distance of 0.107 and categories by a mean total variation of 0.053.

Synthetic rows
320
Mean KS distance
0.1072
Mean TV distance
0.0533
Rows copied from the data
0

Plots

age: real vs syntheticDoes the synthetic data reproduce the shape of a numeric column?
View data
DensitySourceage
0.0230real18.950
0.0016real20.850
0.0049real22.750
0.0148real24.650
0.0148real26.550
0.0181real28.450
0.0197real30.350
0.0296real32.250
0.0362real34.150
0.0115real36.050
0.0362real37.950
0.0313real39.850
0.0296real41.750
0.0280real43.650
0.0280real45.550
0.0181real47.450
0.0164real49.350
0.0197real51.250
0.0362real53.150
0.0148real55.050
0.0164real56.950
0.0181real58.850
0.0082real60.750
0.0164real62.650
0.0049real64.550
0.0115real66.450
0.0066real68.350
0.0049real70.250
0.0016real72.150
0.0049real74.050
0.0214synthetic18.950
0.0016synthetic20.850
0.0148synthetic22.750
0.0033synthetic24.650
0.0164synthetic26.550
0.0066synthetic28.450
0.0132synthetic30.350
0.0362synthetic32.250
0.0230synthetic34.150
0.0181synthetic36.050
0.0197synthetic37.950
0.0329synthetic39.850
0.0230synthetic41.750
0.0345synthetic43.650
0.0313synthetic45.550
0.0181synthetic47.450
0.0164synthetic49.350
0.0230synthetic51.250
0.0378synthetic53.150
0.0197synthetic55.050
0.0280synthetic56.950
0.0164synthetic58.850
0.0148synthetic60.750
0.0099synthetic62.650
0.0016synthetic64.550
0.0099synthetic66.450
0.0033synthetic68.350
0.0099synthetic70.250
0.0016synthetic72.150
0.0197synthetic74.050
annual income: real vs syntheticDoes the synthetic data reproduce the shape of a numeric column?
View data
DensitySourceannual income
3.010e-6real6851.93
1.605e-5real10141.74
2.107e-5real13431.55
2.408e-5real16721.36
3.511e-5real20011.17
4.113e-5real23300.98
2.809e-5real26590.79
2.408e-5real29880.60
2.508e-5real33170.41
1.605e-5real36460.22
1.605e-5real39750.03
1.505e-5real43039.84
1.003e-5real46329.65
5.016e-6real49619.46
6.019e-6real52909.27
4.013e-6real56199.07
4.013e-6real59488.88
4.013e-6real62778.69
1.003e-6real66068.50
1.003e-6real69358.31
1.003e-6real72648.12
0real75937.93
1.003e-6real79227.74
1.003e-6real82517.55
0real85807.36
0real89097.17
0real92386.98
0real95676.79
0real98966.60
1.003e-6real102256.41
1.104e-5synthetic6851.93
2.408e-5synthetic10141.74
2.207e-5synthetic13431.55
4.213e-5synthetic16721.36
4.113e-5synthetic20011.17
2.809e-5synthetic23300.98
3.010e-5synthetic26590.79
2.608e-5synthetic29880.60
2.207e-5synthetic33170.41
7.022e-6synthetic36460.22
1.204e-5synthetic39750.03
1.204e-5synthetic43039.84
5.016e-6synthetic46329.65
4.013e-6synthetic49619.46
2.006e-6synthetic52909.27
2.006e-6synthetic56199.07
2.006e-6synthetic59488.88
2.006e-6synthetic62778.69
2.006e-6synthetic66068.50
1.003e-6synthetic69358.31
1.003e-6synthetic72648.12
2.006e-6synthetic75937.93
0synthetic79227.74
1.003e-6synthetic82517.55
0synthetic85807.36
1.003e-6synthetic89097.17
0synthetic92386.98
0synthetic95676.79
0synthetic98966.60
1.003e-6synthetic102256.41
tenure_months: real vs syntheticDoes the synthetic data reproduce the shape of a numeric column?
View data
DensitySourcetenure_months
0.0938real0.7667
0.0224real2.300
0.0183real3.833
0.0306real5.367
0.0204real6.900
0.0265real8.433
0.0204real9.967
0.0530real11.500
0.0183real13.033
0.0510real14.567
0.0183real16.100
0.0367real17.633
0.0224real19.167
0.0448real20.700
0.0469real22.233
0.0082real23.767
0.0306real25.300
0.0061real26.833
0.0183real28.367
0.0041real29.900
0.0143real31.433
0.0061real32.967
0.0183real34.500
0.0020real36.033
0.0041real37.567
0real39.100
0.0061real40.633
0.0041real42.167
0.0020real43.700
0.0041real45.233
0.1223synthetic0.7667
0.0245synthetic2.300
0.0306synthetic3.833
0.0448synthetic5.367
0.0102synthetic6.900
0.0387synthetic8.433
0.0204synthetic9.967
0.0591synthetic11.500
0.0245synthetic13.033
0.0489synthetic14.567
0.0163synthetic16.100
0.0428synthetic17.633
0.0224synthetic19.167
0.0448synthetic20.700
0.0265synthetic22.233
0.0082synthetic23.767
0.0143synthetic25.300
0.0061synthetic26.833
0.0082synthetic28.367
0.0061synthetic29.900
0.0082synthetic31.433
0.0020synthetic32.967
0.0061synthetic34.500
0.0041synthetic36.033
0.0041synthetic37.567
0.0020synthetic39.100
0.0041synthetic40.633
0synthetic42.167
0.0020synthetic43.700
0synthetic45.233
signup: real vs syntheticDoes the synthetic data reproduce the shape of a numeric column?
View data
DensitySourcesignup
0.0005real17582.23
0.0007real17654.70
0.0005real17727.17
0.0005real17799.63
0.0004real17872.10
0.0005real17944.57
0.0006real18017.03
0.0004real18089.50
0.0005real18161.97
0.0005real18234.43
0.0001real18306.90
0.0009real18379.37
0.0006real18451.83
0.0003real18524.30
0.0005real18596.77
0.0004real18669.23
0.0002real18741.70
0.0005real18814.17
0.0006real18886.63
0.0005real18959.10
0.0005real19031.57
0.0005real19104.03
0.0003real19176.50
0.0006real19248.97
0.0004real19321.43
0.0003real19393.90
0.0002real19466.37
0.0005real19538.83
0.0003real19611.30
0.0004real19683.77
0.0006synthetic17582.23
0.0004synthetic17654.70
0.0005synthetic17727.17
0.0002synthetic17799.63
0.0004synthetic17872.10
0.0006synthetic17944.57
0.0003synthetic18017.03
0.0004synthetic18089.50
0.0004synthetic18161.97
0.0004synthetic18234.43
0.0005synthetic18306.90
0.0004synthetic18379.37
0.0004synthetic18451.83
0.0003synthetic18524.30
0.0005synthetic18596.77
0.0003synthetic18669.23
0.0004synthetic18741.70
0.0003synthetic18814.17
0.0003synthetic18886.63
0.0003synthetic18959.10
0.0004synthetic19031.57
0.0008synthetic19104.03
0.0003synthetic19176.50
0.0005synthetic19248.97
0.0003synthetic19321.43
0.0002synthetic19393.90
0.0004synthetic19466.37
0.0007synthetic19538.83
0.0012synthetic19611.30
0.0009synthetic19683.77
plan: real vs syntheticDoes the synthetic data keep the category proportions of the real data?
View data
planShareSource
basic0.3563real
plus0.3969real
premium0.2469real
basic0.3594synthetic
plus0.3844synthetic
premium0.2562synthetic
region: real vs syntheticDoes the synthetic data keep the category proportions of the real data?
View data
regionShareSource
east0.2848real
north0.2718real
south0.3042real
west0.1392real
east0.3738synthetic
north0.2236synthetic
south0.2300synthetic
west0.1725synthetic
churned: real vs syntheticDoes the synthetic data keep the category proportions of the real data?
View data
churnedShareSource
false0.7688real
true0.2313real
false0.7438synthetic
true0.2562synthetic
Correlation difference (real − synthetic)What do the values of a square or rectangular result matrix look like at a glance?
View data
ColumnColumnDifference
ageage0
annual incomeage0.3306
tenure_monthsage0.8144
signupage0.0037
visitsage0.0790
ageannual income0.3306
annual incomeannual income0
tenure_monthsannual income0.0613
signupannual income−0.1297
visitsannual income0.2451
agetenure_months0.8144
annual incometenure_months0.0613
tenure_monthstenure_months0
signuptenure_months−0.1346
visitstenure_months0.0903
agesignup0.0037
annual incomesignup−0.1297
tenure_monthssignup−0.1346
signupsignup0
visitssignup−0.0712
agevisits0.0790
annual incomevisits0.2451
tenure_monthsvisits0.0903
signupvisits−0.0712
visitsvisits0
TVAE loss by epochIs the network still learning, and which part of its loss moves?

Reconstruction measures how well rows are rebuilt from their codes; the KL divergence keeps the codes close to a standard normal.

View data
PartLossEpoch
total104.751
total86.9782
total67.3833
total54.8944
total49.2775
total44.5156
total37.9807
total32.8258
total29.2259
total26.19410
total24.81611
total22.42712
total20.76713
total19.01114
total18.16115
total18.25416
total16.77817
total16.35918
total16.37119
total14.86720
total15.33421
total14.41622
total14.43223
total13.68324
total13.56325
total13.81026
total13.22527
total13.09628
total13.27029
total12.57330
reconstruction103.231
reconstruction85.5582
reconstruction66.0013
reconstruction53.5064
reconstruction47.8585
reconstruction43.0496
reconstruction36.4597
reconstruction31.2298
reconstruction27.5469
reconstruction24.42910
reconstruction22.97811
reconstruction20.51812
reconstruction18.78413
reconstruction16.95914
reconstruction16.05215
reconstruction16.09616
reconstruction14.58417
reconstruction14.13418
reconstruction14.12719
reconstruction12.60820
reconstruction13.07121
reconstruction12.16222
reconstruction12.19823
reconstruction11.47724
reconstruction11.38825
reconstruction11.66426
reconstruction11.10227
reconstruction10.99128
reconstruction11.17729
reconstruction10.49030

First 60 of 90 rows.

Assumptions

  • Enough rows for a neural generator — 293 complete training rows — neural generators have many weights to learn and can memorize small tables; compare with the copula or sequential trees.
  • Training stayed finite — The loss over the last 10% of epochs averaged 13 (reconstruction 10.9, KL 2.09).
  • No synthetic row copies a training row — 0 synthetic rows are identical to a training row; the scorecard's distance to closest record checks near-copies.
  • Synthetic columns match the data — Distance from the training rows: numeric columns 0.107 (mean Kolmogorov–Smirnov distance); categories 0.053 (mean total variation) — above 0.10, so some columns' distributions differ visibly from the data; the scorecard shows which columns and pairs.

Real vs synthetic, column by column

ColumnKindRealSyntheticDistanceMeasure
agenumeric43.14 ± 13.145.01 ± 13.80.0781Kolmogorov–Smirnov D
annual incomenumeric2.929e+04 ± 1.43e+042.614e+04 ± 1.46e+040.1518Kolmogorov–Smirnov D
tenure_monthsnumeric15 ± 10.712.24 ± 9.70.1250Kolmogorov–Smirnov D
plancategoricalplus 39.7%plus 38.4%0.0125total variation
regioncategoricalsouth 30.4%south 23.0%0.1224total variation
churnedbooleanfalse 76.9%false 74.4%0.0250total variation
signuptemporal2020-11-05 ± 621 days2021-04-05 ± 684 days0.1375Kolmogorov–Smirnov D
visitsnumeric3.394 ± 2.093.212 ± 1.960.0438Kolmogorov–Smirnov D

Modes per numeric column (mode-specific normalization)

ColumnMixture modes
age5
annual income5
tenure_months5
signup5
visits5
  • 80 of 400 rows (20%) were held out of training so privacy and utility can be checked against rows the generator never saw.
Python

320 synthetic rows over 8 columns from 320 training rows with a tabular variational autoencoder. Numeric columns differ from the data by a mean Kolmogorov–Smirnov distance of 0.107 and categories by a mean total variation of 0.053.

Synthetic rows
320
Mean KS distance
0.1072
Mean TV distance
0.0533
Rows copied from the data
0

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • Enough rows for a neural generator — 293 complete training rows — neural generators have many weights to learn and can memorize small tables; compare with the copula or sequential trees.
  • Training stayed finite — The loss over the last 10% of epochs averaged 13 (reconstruction 10.9, KL 2.09).
  • No synthetic row copies a training row — 0 synthetic rows are identical to a training row; the scorecard's distance to closest record checks near-copies.
  • Synthetic columns match the data — Distance from the training rows: numeric columns 0.107 (mean Kolmogorov–Smirnov distance); categories 0.053 (mean total variation) — above 0.10, so some columns' distributions differ visibly from the data; the scorecard shows which columns and pairs.

Real vs synthetic, column by column

ColumnKindRealSyntheticDistanceMeasure
agenumeric43.14 ± 13.145.01 ± 13.80.0781Kolmogorov–Smirnov D
annual incomenumeric2.929e+04 ± 1.43e+042.614e+04 ± 1.46e+040.1518Kolmogorov–Smirnov D
tenure_monthsnumeric15 ± 10.712.24 ± 9.70.1250Kolmogorov–Smirnov D
plancategoricalplus 39.7%plus 38.4%0.0125total variation
regioncategoricalsouth 30.4%south 23.0%0.1224total variation
churnedbooleanfalse 76.9%false 74.4%0.0250total variation
signuptemporal2020-11-05 ± 621 days2021-04-05 ± 684 days0.1375Kolmogorov–Smirnov D
visitsnumeric3.394 ± 2.093.212 ± 1.960.0438Kolmogorov–Smirnov D

Modes per numeric column (mode-specific normalization)

ColumnMixture modes
age5
annual income5
tenure_months5
signup5
visits5
  • 80 of 400 rows (20%) were held out of training so privacy and utility can be checked against rows the generator never saw.

Do it in CodeSplash Run it on your own data. It's in the Experimental lane in the app.

Worked examples in the app

  • Customers allg1_customers · columns: age, annual income, tenure_months, plan, region, churned, signup, visits
  • Penguins no missingml_penguins · columns: species, island, bill_len, bill_dep, flipper_len, body_mass, sex
  • Iris numeric no holdoutml_iris · columns: sepal_length, sepal_width, petal_length, petal_width
  • Penguins categories onlyml_penguins · columns: species, island, sex
  • Degenerate all nag1_customers · columns: age, annual income, tenure_months, plan, region, churned, signup, visits
  • Degenerate n2g1_customers · columns: age, annual income, tenure_months, plan, region, churned, signup, visits
  • Degenerate infg1_customers · columns: age, annual income, tenure_months, plan, region, churned, signup, visits
  • Iris dp epsilonml_iris · columns: sepal_length, sepal_width, petal_length, petal_width

In the guides

Where it sits in the decision guides

  • Generative models (GMM, VAEs) · DS & ML Decision Guide · Generate
  • Generate: quality (human or automated); relevance, safety, bias; task-specific metrics (BLEU, ROUGE, LLM-as-judge) · DS & ML Decision Guide · How to evaluate — common metrics by question type

What you need

Columnsnumeric / categorical / boolean / temporal · 1–100 columns
The columns to synthesize. Leave out direct identifiers (names, e-mails, IDs) — they should never be modeled.

Choices you make

options

Synthetic rowsdefault —

How many synthetic rows to generate. Leave empty to match the number of real rows.

Missing valuesdefault keep_rate

Whether synthetic data keeps each column's share of missing values (placed at random).

  • Keep each column's missing share (at random)(default) — Blanks synthetic values at each column's real missing share, at random; keeps the data's gaps in overall rate.
  • No missing values — Produces complete synthetic data with no gaps; pick it when downstream tools can't handle missing values.

model

Hidden layers (units)default 128,128

Units in each encoder layer, input side first; the decoder mirrors them.

Latent dimensionsdefault 32

Length of the Gaussian code each row is squeezed into; new rows are decoded from normal draws of this length.

Epochsdefault 300

Passes over the training rows.

Batch sizedefault 500

Rows per gradient step; batches follow a seeded shuffle each epoch (the same in Python and R).

Learning ratedefault 0.001

Adam's step size.

Modes per numeric columndefault 5

Most Gaussian components fitted to each number for mode-specific normalization; tiny ones are dropped.

Advanced

KL weight (β)default 1

Weight of the term that keeps codes near a standard normal; larger values give smoother, blurrier rows.

Privacy budget ε (differential privacy)default —

Trains with DP-SGD so the trained network reveals little about any one training row: smaller ε is more private and usually less accurate (1–10 is common). The noise is set to reach this ε. Off by default.

Privacy noise multiplierdefault —

DP-SGD with this noise level instead of a target ε (noise SD = multiplier × clipping norm); the ε it gives is reported. Leave off when you set ε.

Privacy clipping normdefault 1

With differential privacy: each row's gradient is scaled down to at most this size before noise is added.

Privacy δdefault —

With differential privacy: the small chance the ε bound may fail. Automatic = 0.00001, or 0.1 ÷ training rows when that is smaller.

Privacy batch samplingdefault poisson

With differential privacy: how batches are drawn. The ε analysis assumes Poisson sampling.

  • Poisson (exact ε)(default) — Every row joins each batch with chance batch size ÷ rows, so batch sizes vary; the reported ε applies.
  • Shuffled batches (approximate ε) — The usual fixed-size shuffled batches; the reported ε is labeled approximate.
Optimizerdefault default

How the weights are updated. The method's own choice is the usual one.

  • Method's own(default) — Adam or AdamW, as the method describes; the usual choice.
  • Adam — Adam without decoupled weight decay (an AdamW method's weight decay is then not applied).
  • AdamW — Adam with decoupled weight decay; on an Adam method it adds decay 0.01 on weight matrices.
  • SGD with momentum — Plain gradient steps with momentum 0.9; often needs a larger learning rate and a schedule.
Learning-rate scheduledefault none

How the learning rate changes over training.

  • Constant(default) — The same learning rate every epoch (the method's default).
  • Cosine — Falls smoothly from the learning rate toward 0 over the epochs.
  • Step — Divides the learning rate by 10 after each third of the epochs.
  • One cycle — Rises from a 25th of the learning rate to the full rate over the first 30% of steps, then falls far below it.
  • Reduce on plateau — Divides the learning rate by 10 after 10 epochs without improvement in the validation loss.
Warm-up epochsdefault 0

Epochs at the start that ramp the learning rate up linearly; 0 = no warm-up.

Gradient clippingdefault 0

Largest gradient size (L2 norm over all weights) before a step; larger gradients are scaled down. 0 = off.

Weight average (EMA)default 0

Keeps a moving average of the weights (for example 0.99) and uses it for validation and the result. 0 = off.

Weight average from epoch (SWA)default 0

Averages the weights at the end of every epoch from this one on and returns the average. 0 = off; not with EMA.

Record every stepdefault off

Saves the loss, learning rate and gradient size after every batch in the training history, not only per epoch.

Compute profiledefault parity

Where and how precisely the network trains. Parity matches the other engine; the faster profiles can give slightly different numbers.

  • Parity(default) — Double precision on one CPU thread: the same numbers in Python and R, run after run (the default).
  • Faster CPU — Single precision on all performance cores; repeatable on this Mac, results differ slightly from Parity.
  • Apple GPU — Single precision on the Apple GPU (macOS 15 or later); results can differ slightly. Falls back to Faster CPU without a GPU.
Checkpoint every (epochs)default —

Saves the training state this often and when training ends, so a stopped run can resume where it was. Automatic saves about every 30 seconds; 0 = off. Each save holds the weights and the optimizer's state, so a large text encoder tuned on every layer can take 1–2 GB per fold.

validation

Holdout for privacy and utility checksdefault 0.2

Share of rows kept out of training. The scorecard compares synthetic rows with these unseen rows.

Checks and remedies

CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.

  • Enough rows for a neural generator

    Below about 1,000 complete rows a VAE has more weights than evidence; it can memorize rows or blur rare ones.

    • If violated → Gaussian copula — A copula learns each column's distribution and one correlation matrix, which small tables can support without memorizing rows. Changes the question: Interactions and clusters beyond pairwise rank correlation are not reproduced.
  • Training stayed finite

    The loss must stay finite; if it does not, lower the learning rate.

  • No synthetic row copies a training row

    Exact copies leak real records; the scorecard's distance to closest record also checks near-copies.

    • If violated → Gaussian copula with interpolated values — Interpolated values fall between observed ones, so exact copies of records become unlikely. Changes the question: Synthetic numbers no longer keep the data's exact set of values.
  • Synthetic columns match the data

    Each column's distribution is compared with the training rows (Kolmogorov–Smirnov distance for numbers, total variation for categories); a mean above 0.10 means some columns differ visibly.

    • If violated → Gaussian copula — A copula rebuilds each column from its own values, so column distributions match closely even when a neural generator hasn't learned them. Changes the question: Dependence between columns is limited to rank correlation; clusters and interactions are not reproduced.

What it reports

n_rows
How many independent units the analysis used; it sets precision and power.
n_real
How many independent units the analysis used; it sets precision and power.
n_input
How many independent units the analysis used; it sets precision and power.
n_holdout
How many independent units the analysis used; it sets precision and power.
n_columns
How many independent units the analysis used; it sets precision and power.
exact_matches
How far a row sits from its nearest training row; synthetic rows should sit no closer than real rows the generator never saw.
fidelity_ks_mean
How closely synthetic rows match the real ones, column by column, in pairs, and as whole rows.
fidelity_tv_mean
How closely synthetic rows match the real ones, column by column, in pairs, and as whole rows.
batch_size
A variational autoencoder for tables that codes numbers by mode-specific normalization and categories as one-hot blocks.
latent_dim
A variational autoencoder for tables that codes numbers by mode-specific normalization and categories as one-hot blocks.
final_loss
A variational autoencoder for tables that codes numbers by mode-specific normalization and categories as one-hot blocks.
reconstruction
A variational autoencoder for tables that codes numbers by mode-specific normalization and categories as one-hot blocks.
kl
A variational autoencoder for tables that codes numbers by mode-specific normalization and categories as one-hot blocks.

Per group, level or term: mean[<column>], sd[<column>], wmean[<column>], share[<column>=<level>], wcode[<column>], missing[<column>], ks[<column>], tv[<column>], modes[<column>], sigma_mean, corr_mad

Python and R

Python and R use different algorithms; results agree in substance (relative tolerance 1e-9). Python uses torch, pyarrow, codesplash; R uses torch, nanoparquet, codesplashr.

Default traps between the two languages

  • Lab tier. Both engines run the codesplash twin (codesplash.synth.tvae.fit_tvae ↔ codesplashr::cs_synth_tvae): the same encoder and decoder on LibTorch in double precision on one thread, the mode-specific encoding of the WGAN-GP twin, initial weights, batches, reparameterization noise and generation draws from the shared Wichmann–Hill stream, Adam written out with torch's arithmetic (training kernel v2). Python's and R's torch ship different LibTorch builds, so single kernels can differ by an ulp, which training can amplify; on the fixtures every value is identical (measured), and the tolerance leaves room for an ulp.
  • Written from the paper. CTGAN/SDV (BUSL-1.1) are not used: the learned scale of each α column is clamped to [0.01, 1] inside the loss, the reconstruction term is not reweighted, and new α values add the learned scale's noise before clipping to [−1, 1].
Python

The exact script CodeSplash ran for example “Customers all” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0

# Synthetic data — tabular VAE (TVAE)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method synth.tvae 1.0.1 · spec c592bbd6d043a651
# Dataset: g1_customers (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os

import numpy as np
import pandas as pd

import codesplash as cs
from codesplash.errors import check_finite
from codesplash.ml.run import out_dir
from codesplash.stats.rng import Rng
from codesplash.synth import common as sy
from codesplash.synth import tvae  # twin of codesplashr::cs_synth_tvae (clean-room TVAE; no CTGAN/SDV code)

# %% Data
COLUMNS = ["age", "annual income", "tenure_months", "plan", "region", "churned", "signup", "visits"]
KINDS = {
    "age": "numeric",
    "annual income": "numeric",
    "tenure_months": "numeric",
    "plan": "categorical",
    "region": "categorical",
    "churned": "boolean",
    "signup": "temporal",
    "visits": "numeric",
}
LEVELS = {
    "plan": ["basic", "plus", "premium"],
    "region": ["east", "north", "south", "west"],
}
SEED = 42
cols, n_input = sy.load("tests/parity/fixtures/g1_customers.parquet", COLUMNS, KINDS, LEVELS)
for c in cols:
    if c.kind == "numeric":
        check_finite(c.values, c.name)  # infinite values stop the run (registry/errors.yaml)
rng = Rng(SEED)  # shared stream: the same holdout and the same synthetic rows in Python and R
train_rows, holdout_rows = sy.split_holdout(n_input, 0.2, rng)
train = [c.take(train_rows) for c in cols]
N_OUT = None or len(train_rows)
warnings = []
fit_values = {}
extra_tables = []
extra_charts = []
assumptions = []
model_note = ""
if len(holdout_rows):
    warnings.append(f"{len(holdout_rows):,} of {n_input:,} rows ({len(holdout_rows) / n_input:.0%}) were held out of training so privacy and utility can be checked against rows the generator never saw.")
for c in train:
    share = float(np.mean(c.missing()))
    if share == 1.0:
        cs.cs_error("CS_E_ALL_MISSING", column=c.name)  # no values in the training rows
n_complete = len(sy.complete_rows(train))
assumptions.append({
    "key": "enough_rows",
    "label": "Enough rows for a neural generator",
    "status": "pass" if n_complete >= 1000 else "warn",
    "detail": f"{n_complete:,} complete training rows"
              + ("." if n_complete >= 1000 else " — neural generators have many weights to learn and can memorize small tables; compare with the copula or sequential trees."),
})

# %% Generate
from codesplash.deep import trainer as deep_trainer  # training options, live progress, checkpoints (twin: cs_deep_trainer_*)

deep_trainer.configure(
    {
        "dp_epsilon": None,
        "dp_noise_multiplier": None,
        "dp_max_grad_norm": 1,
        "dp_delta": None,
        "dp_sampling": "poisson",
        "optimizer": "default",
        "lr_schedule": "none",
        "warmup_epochs": 0,
        "grad_clip": 0,
        "ema_decay": 0,
        "swa_start": 0,
        "history_every_step": False,
        "profile": "parity",
        "checkpoint_every": None,
    },
    out_dir="target/academy-parity/run-8142/synth.tvae/customers_all/out-python",
)
# Tabular VAE on rows encoded by mode-specific normalization (numbers → [α, mode one-hot], categories one-hot):
# encoder → N(μ, σ²) code of 8 dimensions → decoder; KL weight β = 1.
HIDDEN = [int(u) for u in [32, 32]]
synth, facts, hist = tvae.fit_tvae(
    train, N_OUT, rng, HIDDEN,
    latent_dim=8,
    epochs=30,
    batch_size=100,
    lr=0.001,
    beta=1,
    n_modes=5,
    seed=SEED,
)
history = pd.DataFrame(hist)
last = max(1, len(hist) // 10)  # the last 10% of epochs
fit_values["batch_size"] = facts["batch_size"]
fit_values["latent_dim"] = facts["latent_dim"]
fit_values["final_loss"] = float(np.mean([h["loss"] for h in hist[-last:]]))
fit_values["reconstruction"] = float(np.mean([h["reconstruction"] for h in hist[-last:]]))
fit_values["kl"] = float(np.mean([h["kl"] for h in hist[-last:]]))
if not np.isnan(facts["sigma_mean"]):
    fit_values["sigma_mean"] = facts["sigma_mean"]
for c, k in zip(COLUMNS, facts["modes"]):
    if k is not None:
        fit_values[f"modes[{c}]"] = int(k)
model_note = " with a tabular variational autoencoder"
ep = history["epoch"].tolist()
extra_charts.append(cs.chart("training", "training-components", "TVAE loss by epoch", {
    "x": cs.col("Epoch", ep * 3, "numeric"),
    "value": cs.col("Loss", history["loss"].tolist() + history["reconstruction"].tolist() + history["kl"].tolist(), "numeric"),
    "component": cs.col("Part", ["total"] * len(ep) + ["reconstruction"] * len(ep) + ["KL divergence"] * len(ep), "categorical",
                        levels=["total", "reconstruction", "KL divergence"]),
}, note="Reconstruction measures how well rows are rebuilt from their codes; the KL divergence keeps the codes close to a standard normal."))
finite = bool(np.all(np.isfinite(history[["loss", "reconstruction", "kl"]].to_numpy())))
assumptions.append({
    "key": "training_stable",
    "label": "Training stayed finite",
    "status": "pass" if finite else "fail",
    "detail": f"The loss over the last 10% of epochs averaged {fit_values['final_loss']:.3g} (reconstruction {fit_values['reconstruction']:.3g}, KL {fit_values['kl']:.3g})." if finite else "A loss became infinite or undefined; lower the learning rate.",
})
mode_rows = [{"column": c, "modes": int(k)} for c, k in zip(COLUMNS, facts["modes"]) if k is not None]
if mode_rows:
    extra_tables.append({
        "key": "modes",
        "title": "Modes per numeric column (mode-specific normalization)",
        "columns": [{"key": "column", "label": "Column", "type": "string"}, {"key": "modes", "label": "Mixture modes", "type": "integer"}],
        "rows": mode_rows,
    })
sy.add_missing(synth, train, rng, "keep_rate")  # each column's missing share, at random

# %% Write and compare
out = out_dir("target/academy-parity/run-8142/synth.tvae/customers_all/out-python")
path = sy.write(os.path.join(out, "synthetic.parquet"), synth)
split = sy.write_split(os.path.join(out, "split.parquet"), n_input, train_rows, holdout_rows)
history.to_parquet(os.path.join(out, "history.parquet"), index=False)
values, table, charts = sy.summarize(train, synth, len(train_rows), n_input, len(holdout_rows), fit_values)
assumptions.append({
    "key": "no_copies",
    "label": "No synthetic row copies a training row",
    "status": "pass" if values["exact_matches"] == 0 else "warn",
    "detail": f"{values['exact_matches']:,} synthetic row{'s are' if values['exact_matches'] != 1 else ' is'} identical to a training row; the scorecard's distance to closest record checks near-copies.",
})
# Fidelity (Stage 12.10): judged on the mean column distances, the scorecard's column fidelity (good at ≥ 0.9 = 1 − 0.1).
fid_parts = []
if not np.isnan(values["fidelity_ks_mean"]):
    fid_parts.append((values["fidelity_ks_mean"], f"numeric columns {values['fidelity_ks_mean']:.3f} (mean Kolmogorov–Smirnov distance)"))
if not np.isnan(values["fidelity_tv_mean"]):
    fid_parts.append((values["fidelity_tv_mean"], f"categories {values['fidelity_tv_mean']:.3f} (mean total variation)"))
fid_worst = max((d for d, _ in fid_parts), default=None)
assumptions.append({
    "key": "fidelity",
    "label": "Synthetic columns match the data",
    "status": "info" if fid_worst is None else ("pass" if fid_worst <= 0.1 else "warn"),
    "detail": "No column could be compared with the data." if fid_worst is None else
              "Distance from the training rows: " + "; ".join(t for _, t in fid_parts)
              + (" — at most 0.10, which the Synthetic studio's scorecard rates as good column fidelity." if fid_worst <= 0.1 else
                 " — above 0.10, so some columns' distributions differ visibly from the data; the scorecard shows which columns and pairs."),
})
summary = (
    f"{values['n_rows']:,} synthetic rows over {len(COLUMNS)} column{'s' if len(COLUMNS) != 1 else ''} from "
    f"{len(train_rows):,} training rows{model_note}."
)
if not np.isnan(values["fidelity_ks_mean"]):
    summary += f" Numeric columns differ from the data by a mean Kolmogorov–Smirnov distance of {values['fidelity_ks_mean']:.3f}"
    summary += f" and categories by a mean total variation of {values['fidelity_tv_mean']:.3f}." if not np.isnan(values["fidelity_tv_mean"]) else "."
elif not np.isnan(values["fidelity_tv_mean"]):
    summary += f" Categories differ from the data by a mean total variation of {values['fidelity_tv_mean']:.3f}."
if values["exact_matches"]:
    summary += f" {values['exact_matches']:,} synthetic row{'s are' if values['exact_matches'] != 1 else ' is'} identical to a training row."
cs.publish({
    "title": "Synthetic data — tabular VAE (TVAE)",
    "engine": cs.engine_info("torch", "pyarrow", "codesplash", "numpy", "pyarrow"),
    "n": values["n_real"],
    "summary": summary,
    "statistics": [
        {"key": "n_rows", "label": "Synthetic rows", "value": values["n_rows"], "format": "integer"},
        {"key": "fidelity_ks_mean", "label": "Mean KS distance", "value": values.get("fidelity_ks_mean")},
        {"key": "fidelity_tv_mean", "label": "Mean TV distance", "value": values.get("fidelity_tv_mean")},
        {"key": "exact_matches", "label": "Rows copied from the data", "value": values["exact_matches"], "format": "integer"},
    ],
    "tables": [table, *extra_tables],
    "values": values,
    "charts": charts + extra_charts,
    "assumptions": assumptions,
    "warnings": warnings,
    "artifacts": [
        {"key": "synthetic", "path": path, "format": "parquet", "title": "Synthetic rows"},
        {"key": "split", "path": split, "format": "parquet", "title": "Training and holdout rows"},
        {"key": "history", "path": os.path.join(out, "history.parquet"), "format": "parquet", "title": "Training history"},
    ],
    "model": {"kind": "generator", "columns": COLUMNS, "params": {
        "n_rows": None,
        "hidden_layers": [32, 32],
        "latent_dim": 8,
        "epochs": 30,
        "batch_size": 100,
        "learning_rate": 0.001,
        "beta": 1,
        "n_modes": 5,
        "missing": "keep_rate",
        "holdout": 0.2,
        "dp_epsilon": None,
        "dp_noise_multiplier": None,
        "dp_max_grad_norm": 1,
        "dp_delta": None,
        "dp_sampling": "poisson",
        "optimizer": "default",
        "lr_schedule": "none",
        "warmup_epochs": 0,
        "grad_clip": 0,
        "ema_decay": 0,
        "swa_start": 0,
        "history_every_step": False,
        "profile": "parity",
        "checkpoint_every": None,
    }},
})
R

The exact script CodeSplash ran for example “Customers all” · R version 4.5.1 (2025-06-13)

# Synthetic data — tabular VAE (TVAE)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method synth.tvae 1.0.1 · spec c592bbd6d043a651
# Dataset: g1_customers (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)

# %% Data
COLUMNS <- c("age", "annual income", "tenure_months", "plan", "region", "churned", "signup", "visits")
KINDS <- list(
  age = "numeric",
  `annual income` = "numeric",
  tenure_months = "numeric",
  plan = "categorical",
  region = "categorical",
  churned = "boolean",
  signup = "temporal",
  visits = "numeric"
)
LEVELS <- list(
  plan = c("basic", "plus", "premium"),
  region = c("east", "north", "south", "west")
)
SEED <- 42
loaded <- cs_synth_load("tests/parity/fixtures/g1_customers.parquet", COLUMNS, KINDS, LEVELS)
cols <- loaded$cols; n_input <- loaded$n
for (c in cols) if (c$kind == "numeric") cs_check_finite(c$values, c$name)  # infinite values stop the run (registry/errors.yaml)
rng <- cs_rng(SEED)  # shared stream: the same holdout and the same synthetic rows in Python and R
sp <- cs_synth_split(n_input, 0.2, rng)
train_rows <- sp$train; holdout_rows <- sp$holdout
train <- lapply(cols, cs_synth_take, rows = train_rows)
N_OUT <- length(train_rows)
warnings <- list()
fit_values <- list()
extra_tables <- list()
extra_charts <- list()
assumptions <- list()
model_note <- ""
if (length(holdout_rows)) {
  warnings <- c(warnings, sprintf("%s of %s rows (%.0f%%) were held out of training so privacy and utility can be checked against rows the generator never saw.",
                                  format(length(holdout_rows), big.mark = ","), format(n_input, big.mark = ","), 100 * length(holdout_rows) / n_input))
}
for (c in train) if (mean(cs_synth_missing(c)) == 1) cs_error("CS_E_ALL_MISSING", column = c$name)  # no values in the training rows
n_complete <- length(cs_synth_complete(train))
assumptions[[1]] <- list(
  key = "enough_rows", label = "Enough rows for a neural generator",
  status = if (n_complete >= 1000) "pass" else "warn",
  detail = paste0(sprintf("%s complete training rows", format(n_complete, big.mark = ",")),
                  if (n_complete >= 1000) "." else " — neural generators have many weights to learn and can memorize small tables; compare with the copula or sequential trees.")
)

# %% Generate
# Training options, live progress and checkpoints (twin: codesplash.deep.trainer.configure).
cs_deep_trainer_configure(list(
  dp_epsilon = NULL,
  dp_noise_multiplier = NULL,
  dp_max_grad_norm = 1,
  dp_delta = NULL,
  dp_sampling = "poisson",
  optimizer = "default",
  lr_schedule = "none",
  warmup_epochs = 0,
  grad_clip = 0,
  ema_decay = 0,
  swa_start = 0,
  history_every_step = FALSE,
  profile = "parity",
  checkpoint_every = NULL
), out_dir = "target/academy-parity/run-8142/synth.tvae/customers_all/out-r")
# Tabular VAE on rows encoded by mode-specific normalization (numbers -> [alpha, mode one-hot], categories one-hot):
# encoder -> N(mu, sigma^2) code of 8 dimensions -> decoder; KL weight beta = 1.
# Twin of codesplash.synth.tvae.fit_tvae (clean-room; no CTGAN/SDV code).
HIDDEN <- as.integer(unlist(c(32, 32)))
fit <- cs_synth_tvae(
  train, N_OUT, rng, HIDDEN,
  latent_dim = as.integer(8),
  epochs = as.integer(30),
  batch_size = 100,
  lr = 0.001,
  beta = 1,
  n_modes = as.integer(5),
  seed = SEED
)
synth <- fit$cols
hist <- fit$history
history <- data.frame(
  epoch = vapply(hist, function(h) as.numeric(h$epoch), numeric(1)),
  loss = vapply(hist, function(h) h$loss, numeric(1)),
  reconstruction = vapply(hist, function(h) h$reconstruction, numeric(1)),
  kl = vapply(hist, function(h) h$kl, numeric(1))
)
last <- max(1L, nrow(history) %/% 10L)  # the last 10% of epochs
tail_rows <- (nrow(history) - last + 1L):nrow(history)
fit_values$batch_size <- fit$facts$batch_size
fit_values$latent_dim <- fit$facts$latent_dim
fit_values$final_loss <- mean(history$loss[tail_rows])
fit_values$reconstruction <- mean(history$reconstruction[tail_rows])
fit_values$kl <- mean(history$kl[tail_rows])
if (!is.nan(fit$facts$sigma_mean)) fit_values$sigma_mean <- fit$facts$sigma_mean
for (j in seq_along(COLUMNS)) {
  k <- fit$facts$modes[[j]]
  if (!is.null(k)) fit_values[[sprintf("modes[%s]", COLUMNS[j])]] <- as.integer(k)
}
model_note <- " with a tabular variational autoencoder"
ne <- nrow(history)
extra_charts[[length(extra_charts) + 1L]] <- cs_chart("training", "training-components", "TVAE loss by epoch", list(
  x = cs_col("Epoch", rep(history$epoch, 3), "numeric"),
  value = cs_col("Loss", c(history$loss, history$reconstruction, history$kl), "numeric"),
  component = cs_col("Part", rep(c("total", "reconstruction", "KL divergence"), each = ne), "categorical",
                     levels = c("total", "reconstruction", "KL divergence"))
), note = "Reconstruction measures how well rows are rebuilt from their codes; the KL divergence keeps the codes close to a standard normal.")
finite <- all(is.finite(c(history$loss, history$reconstruction, history$kl)))
assumptions[[length(assumptions) + 1L]] <- list(
  key = "training_stable", label = "Training stayed finite",
  status = if (finite) "pass" else "fail",
  detail = if (finite) sprintf("The loss over the last 10%% of epochs averaged %s (reconstruction %s, KL %s).",
                               format(signif(fit_values$final_loss, 3)), format(signif(fit_values$reconstruction, 3)), format(signif(fit_values$kl, 3)))
           else "A loss became infinite or undefined; lower the learning rate."
)
mode_rows <- list()
for (j in seq_along(COLUMNS)) {
  k <- fit$facts$modes[[j]]
  if (!is.null(k)) mode_rows[[length(mode_rows) + 1L]] <- list(column = COLUMNS[j], modes = as.integer(k))
}
if (length(mode_rows)) {
  extra_tables[[length(extra_tables) + 1L]] <- list(
    key = "modes", title = "Modes per numeric column (mode-specific normalization)",
    columns = list(list(key = "column", label = "Column", type = "string"), list(key = "modes", label = "Mixture modes", type = "integer")),
    rows = mode_rows)
}
synth <- cs_synth_add_missing(synth, train, rng, "keep_rate")  # each column's missing share, at random

# %% Write and compare
out <- cs_ml_out_dir("target/academy-parity/run-8142/synth.tvae/customers_all/out-r")
path <- cs_synth_write(file.path(out, "synthetic.parquet"), synth)
split <- cs_synth_write_split(file.path(out, "split.parquet"), n_input, train_rows, holdout_rows)
nanoparquet::write_parquet(history, file.path(out, "history.parquet"))
sm <- cs_synth_summarize(train, synth, length(train_rows), n_input, length(holdout_rows), fit_values)
values <- sm$values
assumptions[[length(assumptions) + 1L]] <- list(
  key = "no_copies", label = "No synthetic row copies a training row",
  status = if (values$exact_matches == 0) "pass" else "warn",
  detail = sprintf("%s synthetic row%s identical to a training row; the scorecard's distance to closest record checks near-copies.",
                   format(values$exact_matches, big.mark = ","), if (values$exact_matches != 1) "s are" else " is")
)
# Fidelity (Stage 12.10): judged on the mean column distances, the scorecard's column fidelity (good at >= 0.9 = 1 - 0.1).
fid_d <- numeric(); fid_t <- character()
if (!is.nan(values$fidelity_ks_mean)) {
  fid_d <- c(fid_d, values$fidelity_ks_mean)
  fid_t <- c(fid_t, sprintf("numeric columns %.3f (mean Kolmogorov–Smirnov distance)", values$fidelity_ks_mean))
}
if (!is.nan(values$fidelity_tv_mean)) {
  fid_d <- c(fid_d, values$fidelity_tv_mean)
  fid_t <- c(fid_t, sprintf("categories %.3f (mean total variation)", values$fidelity_tv_mean))
}
assumptions[[length(assumptions) + 1L]] <- if (!length(fid_d)) {
  list(key = "fidelity", label = "Synthetic columns match the data", status = "info",
       detail = "No column could be compared with the data.")
} else {
  list(key = "fidelity", label = "Synthetic columns match the data",
       status = if (max(fid_d) <= 0.1) "pass" else "warn",
       detail = paste0("Distance from the training rows: ", paste(fid_t, collapse = "; "),
                       if (max(fid_d) <= 0.1) " — at most 0.10, which the Synthetic studio's scorecard rates as good column fidelity."
                       else " — above 0.10, so some columns' distributions differ visibly from the data; the scorecard shows which columns and pairs."))
}
summary <- sprintf("%s synthetic rows over %d column%s from %s training rows%s.",
                   format(values$n_rows, big.mark = ","), length(COLUMNS), if (length(COLUMNS) != 1) "s" else "",
                   format(length(train_rows), big.mark = ","), model_note)
if (!is.nan(values$fidelity_ks_mean)) {
  summary <- paste0(summary, sprintf(" Numeric columns differ from the data by a mean Kolmogorov–Smirnov distance of %.3f", values$fidelity_ks_mean),
                    if (!is.nan(values$fidelity_tv_mean)) sprintf(" and categories by a mean total variation of %.3f.", values$fidelity_tv_mean) else ".")
} else if (!is.nan(values$fidelity_tv_mean)) {
  summary <- paste0(summary, sprintf(" Categories differ from the data by a mean total variation of %.3f.", values$fidelity_tv_mean))
}
if (values$exact_matches > 0) {
  summary <- paste0(summary, sprintf(" %s synthetic row%s identical to a training row.", format(values$exact_matches, big.mark = ","),
                                     if (values$exact_matches != 1) "s are" else " is"))
}
cs_publish(list(
  title = "Synthetic data — tabular VAE (TVAE)",
  engine = cs_engine_info("torch", "nanoparquet", "codesplashr", "nanoparquet"),
  n = values$n_real, summary = summary,
  statistics = list(
    list(key = "n_rows", label = "Synthetic rows", value = values$n_rows, format = "integer"),
    list(key = "fidelity_ks_mean", label = "Mean KS distance", value = values$fidelity_ks_mean),
    list(key = "fidelity_tv_mean", label = "Mean TV distance", value = values$fidelity_tv_mean),
    list(key = "exact_matches", label = "Rows copied from the data", value = values$exact_matches, format = "integer")),
  tables = c(list(sm$table), extra_tables),
  values = values, charts = c(sm$charts, extra_charts), assumptions = assumptions, warnings = warnings,
  artifacts = list(list(key = "synthetic", path = path, format = "parquet", title = "Synthetic rows"),
                   list(key = "split", path = split, format = "parquet", title = "Training and holdout rows"),
                   list(key = "history", path = file.path(out, "history.parquet"), format = "parquet", title = "Training history")),
  model = list(kind = "generator", columns = I(COLUMNS), params = list(
    n_rows = NULL,
    hidden_layers = c(32, 32),
    latent_dim = 8,
    epochs = 30,
    batch_size = 100,
    learning_rate = 0.001,
    beta = 1,
    n_modes = 5,
    missing = "keep_rate",
    holdout = 0.2,
    dp_epsilon = NULL,
    dp_noise_multiplier = NULL,
    dp_max_grad_norm = 1,
    dp_delta = NULL,
    dp_sampling = "poisson",
    optimizer = "default",
    lr_schedule = "none",
    warmup_epochs = 0,
    grad_clip = 0,
    ema_decay = 0,
    swa_start = 0,
    history_every_step = FALSE,
    profile = "parity",
    checkpoint_every = NULL
  ))
))

Sources

  • Xu L, Skoularidou M, Cuesta-Infante A, Veeramachaneni K (2019). Modeling tabular data using conditional GAN. NeurIPS 2019 (TVAE, mode-specific normalization).
  • Kingma DP, Welling M (2014). Auto-encoding variational Bayes. ICLR 2014.
  • Higgins I, Matthey L, Pal A, et al. (2017). β-VAE: learning basic visual concepts with a constrained variational framework. ICLR 2017.

From the CodeSplash method registry · synth.tvae v1.0.1.