Glow, masked autoregressive flows and spline flows
Three more flexible flows: Glow mixes columns with a learned invertible matrix, a masked autoregressive flow conditions each column on earlier ones, a spline flow bends columns with monotone curves.
What runs in CodeSplash
- DNN053Glow Runs in CodeSplash (Experimental)
- DNN054Masked autoregressive flow (MAF) Runs in CodeSplash (Experimental)
- DNN055Neural spline flow Runs in CodeSplash (Experimental)
- Synthetic data — normalizing flow (RealNVP, NICE, MAF, Glow, spline) Experimental
You will be able to
- Explain Glow's actnorm and invertible mixing, and why an LU form makes its log-determinant cheap
- Explain why a masked autoregressive flow scores rows in one pass but samples column by column
- Describe a monotone rational-quadratic spline and why monotone means invertible
- Compare the three flows on held-out log-likelihood
Glow: scale, mix, couple
ReadA coupling layer only transforms half the columns, and which half is fixed in advance. GlowGlowA normalizing flow whose layers scale each column (actnorm), mix the columns with a learned invertible matrix, then apply a coupling. adds two steps before each coupling:
- actnorm: a per-column scale and shift, set from the first batch so outputs start at mean 0 and SD 1;
- invertible mixing: multiply by a learned square matrix , so every column can reach every other.
The mixing's log-determinant is , once per location. Keeping (a fixed permutation, a unit lower-triangular and an upper-triangular matrix) makes it the sum of the logs of 's diagonal.
In the reference's example a 2-by-2 mixing applied at four locations has a total log-determinant of −0.794.
Glow on the customer table
Explore320 synthetic rows over 8 columns from 320 training rows with a normalizing flow. Numeric columns differ from the data by a mean Kolmogorov–Smirnov distance of 0.092 and categories by a mean total variation of 0.036.
- Synthetic rows
- 320
- Mean KS distance
- 0.0918
- Mean TV distance
- 0.0360
- Rows copied from the data
- 0
Plots
View data
| Density | Source | age |
|---|---|---|
| 0.0230 | real | 18.950 |
| 0.0016 | real | 20.850 |
| 0.0049 | real | 22.750 |
| 0.0148 | real | 24.650 |
| 0.0148 | real | 26.550 |
| 0.0181 | real | 28.450 |
| 0.0197 | real | 30.350 |
| 0.0296 | real | 32.250 |
| 0.0362 | real | 34.150 |
| 0.0115 | real | 36.050 |
| 0.0362 | real | 37.950 |
| 0.0313 | real | 39.850 |
| 0.0296 | real | 41.750 |
| 0.0280 | real | 43.650 |
| 0.0280 | real | 45.550 |
| 0.0181 | real | 47.450 |
| 0.0164 | real | 49.350 |
| 0.0197 | real | 51.250 |
| 0.0362 | real | 53.150 |
| 0.0148 | real | 55.050 |
| 0.0164 | real | 56.950 |
| 0.0181 | real | 58.850 |
| 0.0082 | real | 60.750 |
| 0.0164 | real | 62.650 |
| 0.0049 | real | 64.550 |
| 0.0115 | real | 66.450 |
| 0.0066 | real | 68.350 |
| 0.0049 | real | 70.250 |
| 0.0016 | real | 72.150 |
| 0.0049 | real | 74.050 |
| 0.0132 | synthetic | 18.950 |
| 0.0099 | synthetic | 20.850 |
| 0.0066 | synthetic | 22.750 |
| 0.0099 | synthetic | 24.650 |
| 0.0132 | synthetic | 26.550 |
| 0.0181 | synthetic | 28.450 |
| 0.0263 | synthetic | 30.350 |
| 0.0247 | synthetic | 32.250 |
| 0.0230 | synthetic | 34.150 |
| 0.0181 | synthetic | 36.050 |
| 0.0329 | synthetic | 37.950 |
| 0.0362 | synthetic | 39.850 |
| 0.0493 | synthetic | 41.750 |
| 0.0214 | synthetic | 43.650 |
| 0.0395 | synthetic | 45.550 |
| 0.0345 | synthetic | 47.450 |
| 0.0197 | synthetic | 49.350 |
| 0.0296 | synthetic | 51.250 |
| 0.0181 | synthetic | 53.150 |
| 0.0115 | synthetic | 55.050 |
| 0.0115 | synthetic | 56.950 |
| 0.0148 | synthetic | 58.850 |
| 0.0099 | synthetic | 60.750 |
| 0.0099 | synthetic | 62.650 |
| 0.0066 | synthetic | 64.550 |
| 0.0082 | synthetic | 66.450 |
| 0.0033 | synthetic | 68.350 |
| 0 | synthetic | 70.250 |
| 0.0016 | synthetic | 72.150 |
| 0.0049 | synthetic | 74.050 |
View data
| Density | Source | annual income |
|---|---|---|
| 3.010e-6 | real | 6851.93 |
| 1.605e-5 | real | 10141.74 |
| 2.107e-5 | real | 13431.55 |
| 2.408e-5 | real | 16721.36 |
| 3.511e-5 | real | 20011.17 |
| 4.113e-5 | real | 23300.98 |
| 2.809e-5 | real | 26590.79 |
| 2.408e-5 | real | 29880.60 |
| 2.508e-5 | real | 33170.41 |
| 1.605e-5 | real | 36460.22 |
| 1.605e-5 | real | 39750.03 |
| 1.505e-5 | real | 43039.84 |
| 1.003e-5 | real | 46329.65 |
| 5.016e-6 | real | 49619.46 |
| 6.019e-6 | real | 52909.27 |
| 4.013e-6 | real | 56199.07 |
| 4.013e-6 | real | 59488.88 |
| 4.013e-6 | real | 62778.69 |
| 1.003e-6 | real | 66068.50 |
| 1.003e-6 | real | 69358.31 |
| 1.003e-6 | real | 72648.12 |
| 0 | real | 75937.93 |
| 1.003e-6 | real | 79227.74 |
| 1.003e-6 | real | 82517.55 |
| 0 | real | 85807.36 |
| 0 | real | 89097.17 |
| 0 | real | 92386.98 |
| 0 | real | 95676.79 |
| 0 | real | 98966.60 |
| 1.003e-6 | real | 102256.41 |
| 1.304e-5 | synthetic | 6851.93 |
| 8.026e-6 | synthetic | 10141.74 |
| 2.307e-5 | synthetic | 13431.55 |
| 1.404e-5 | synthetic | 16721.36 |
| 2.608e-5 | synthetic | 20011.17 |
| 2.408e-5 | synthetic | 23300.98 |
| 3.612e-5 | synthetic | 26590.79 |
| 4.314e-5 | synthetic | 29880.60 |
| 2.809e-5 | synthetic | 33170.41 |
| 1.605e-5 | synthetic | 36460.22 |
| 2.909e-5 | synthetic | 39750.03 |
| 1.304e-5 | synthetic | 43039.84 |
| 1.104e-5 | synthetic | 46329.65 |
| 3.010e-6 | synthetic | 49619.46 |
| 9.029e-6 | synthetic | 52909.27 |
| 4.013e-6 | synthetic | 56199.07 |
| 1.003e-6 | synthetic | 59488.88 |
| 1.003e-6 | synthetic | 62778.69 |
| 0 | synthetic | 66068.50 |
| 1.003e-6 | synthetic | 69358.31 |
| 0 | synthetic | 72648.12 |
| 0 | synthetic | 75937.93 |
| 0 | synthetic | 79227.74 |
| 0 | synthetic | 82517.55 |
| 0 | synthetic | 85807.36 |
| 0 | synthetic | 89097.17 |
| 0 | synthetic | 92386.98 |
| 0 | synthetic | 95676.79 |
| 0 | synthetic | 98966.60 |
| 0 | synthetic | 102256.41 |
View data
| Density | Source | tenure_months |
|---|---|---|
| 0.0938 | real | 0.7667 |
| 0.0224 | real | 2.300 |
| 0.0183 | real | 3.833 |
| 0.0306 | real | 5.367 |
| 0.0204 | real | 6.900 |
| 0.0265 | real | 8.433 |
| 0.0204 | real | 9.967 |
| 0.0530 | real | 11.500 |
| 0.0183 | real | 13.033 |
| 0.0510 | real | 14.567 |
| 0.0183 | real | 16.100 |
| 0.0367 | real | 17.633 |
| 0.0224 | real | 19.167 |
| 0.0448 | real | 20.700 |
| 0.0469 | real | 22.233 |
| 0.0082 | real | 23.767 |
| 0.0306 | real | 25.300 |
| 0.0061 | real | 26.833 |
| 0.0183 | real | 28.367 |
| 0.0041 | real | 29.900 |
| 0.0143 | real | 31.433 |
| 0.0061 | real | 32.967 |
| 0.0183 | real | 34.500 |
| 0.0020 | real | 36.033 |
| 0.0041 | real | 37.567 |
| 0 | real | 39.100 |
| 0.0061 | real | 40.633 |
| 0.0041 | real | 42.167 |
| 0.0020 | real | 43.700 |
| 0.0041 | real | 45.233 |
| 0.0713 | synthetic | 0.7667 |
| 0.0163 | synthetic | 2.300 |
| 0.0082 | synthetic | 3.833 |
| 0.0224 | synthetic | 5.367 |
| 0.0082 | synthetic | 6.900 |
| 0.0469 | synthetic | 8.433 |
| 0.0143 | synthetic | 9.967 |
| 0.0510 | synthetic | 11.500 |
| 0.0306 | synthetic | 13.033 |
| 0.0652 | synthetic | 14.567 |
| 0.0448 | synthetic | 16.100 |
| 0.0510 | synthetic | 17.633 |
| 0.0265 | synthetic | 19.167 |
| 0.0326 | synthetic | 20.700 |
| 0.0387 | synthetic | 22.233 |
| 0.0183 | synthetic | 23.767 |
| 0.0245 | synthetic | 25.300 |
| 0.0122 | synthetic | 26.833 |
| 0.0122 | synthetic | 28.367 |
| 0 | synthetic | 29.900 |
| 0.0204 | synthetic | 31.433 |
| 0.0082 | synthetic | 32.967 |
| 0.0061 | synthetic | 34.500 |
| 0.0020 | synthetic | 36.033 |
| 0.0061 | synthetic | 37.567 |
| 0.0102 | synthetic | 39.100 |
| 0.0020 | synthetic | 40.633 |
| 0 | synthetic | 42.167 |
| 0 | synthetic | 43.700 |
| 0.0020 | synthetic | 45.233 |
View data
| Density | Source | signup |
|---|---|---|
| 0.0005 | real | 17582.23 |
| 0.0007 | real | 17654.70 |
| 0.0005 | real | 17727.17 |
| 0.0005 | real | 17799.63 |
| 0.0004 | real | 17872.10 |
| 0.0005 | real | 17944.57 |
| 0.0006 | real | 18017.03 |
| 0.0004 | real | 18089.50 |
| 0.0005 | real | 18161.97 |
| 0.0005 | real | 18234.43 |
| 0.0001 | real | 18306.90 |
| 0.0009 | real | 18379.37 |
| 0.0006 | real | 18451.83 |
| 0.0003 | real | 18524.30 |
| 0.0005 | real | 18596.77 |
| 0.0004 | real | 18669.23 |
| 0.0002 | real | 18741.70 |
| 0.0005 | real | 18814.17 |
| 0.0006 | real | 18886.63 |
| 0.0005 | real | 18959.10 |
| 0.0005 | real | 19031.57 |
| 0.0005 | real | 19104.03 |
| 0.0003 | real | 19176.50 |
| 0.0006 | real | 19248.97 |
| 0.0004 | real | 19321.43 |
| 0.0003 | real | 19393.90 |
| 0.0002 | real | 19466.37 |
| 0.0005 | real | 19538.83 |
| 0.0003 | real | 19611.30 |
| 0.0004 | real | 19683.77 |
| 0.0006 | synthetic | 17582.23 |
| 0.0003 | synthetic | 17654.70 |
| 0.0002 | synthetic | 17727.17 |
| 0.0002 | synthetic | 17799.63 |
| 0.0003 | synthetic | 17872.10 |
| 0.0005 | synthetic | 17944.57 |
| 0.0006 | synthetic | 18017.03 |
| 0.0004 | synthetic | 18089.50 |
| 0.0007 | synthetic | 18161.97 |
| 0.0005 | synthetic | 18234.43 |
| 0.0007 | synthetic | 18306.90 |
| 0.0006 | synthetic | 18379.37 |
| 0.0006 | synthetic | 18451.83 |
| 0.0004 | synthetic | 18524.30 |
| 0.0005 | synthetic | 18596.77 |
| 0.0006 | synthetic | 18669.23 |
| 0.0008 | synthetic | 18741.70 |
| 0.0006 | synthetic | 18814.17 |
| 0.0007 | synthetic | 18886.63 |
| 0.0005 | synthetic | 18959.10 |
| 0.0004 | synthetic | 19031.57 |
| 0.0006 | synthetic | 19104.03 |
| 0.0003 | synthetic | 19176.50 |
| 0.0004 | synthetic | 19248.97 |
| 0.0004 | synthetic | 19321.43 |
| 0.0002 | synthetic | 19393.90 |
| 0.0003 | synthetic | 19466.37 |
| 0.0002 | synthetic | 19538.83 |
| 0.0002 | synthetic | 19611.30 |
| 0.0005 | synthetic | 19683.77 |
View data
| plan | Share | Source |
|---|---|---|
| basic | 0.3563 | real |
| plus | 0.3969 | real |
| premium | 0.2469 | real |
| basic | 0.3281 | synthetic |
| plus | 0.4156 | synthetic |
| premium | 0.2562 | synthetic |
View data
| region | Share | Source |
|---|---|---|
| east | 0.2848 | real |
| north | 0.2718 | real |
| south | 0.3042 | real |
| west | 0.1392 | real |
| east | 0.2300 | synthetic |
| north | 0.3003 | synthetic |
| south | 0.3163 | synthetic |
| west | 0.1534 | synthetic |
View data
| churned | Share | Source |
|---|---|---|
| false | 0.7688 | real |
| true | 0.2313 | real |
| false | 0.7937 | synthetic |
| true | 0.2062 | synthetic |
View data
| Column | Column | Difference |
|---|---|---|
| age | age | 0 |
| annual income | age | 0.0943 |
| tenure_months | age | 0.3780 |
| signup | age | −0.0399 |
| visits | age | −0.0713 |
| age | annual income | 0.0943 |
| annual income | annual income | 0 |
| tenure_months | annual income | 0.0071 |
| signup | annual income | 0.0291 |
| visits | annual income | 0.0051 |
| age | tenure_months | 0.3780 |
| annual income | tenure_months | 0.0071 |
| tenure_months | tenure_months | 0 |
| signup | tenure_months | −0.1555 |
| visits | tenure_months | −0.0706 |
| age | signup | −0.0399 |
| annual income | signup | 0.0291 |
| tenure_months | signup | −0.1555 |
| signup | signup | 0 |
| visits | signup | 0.0100 |
| age | visits | −0.0713 |
| annual income | visits | 0.0051 |
| tenure_months | visits | −0.0706 |
| signup | visits | 0.0100 |
| visits | visits | 0 |
In the flow's coordinates (standardized numbers, dequantized categories); lower is better.
View data
| Part | Negative log-likelihood (nats per row) | Epoch |
|---|---|---|
| training rows | 14.030 | 1 |
| training rows | 13.713 | 2 |
| training rows | 13.701 | 3 |
| training rows | 13.472 | 4 |
| training rows | 13.594 | 5 |
| training rows | 13.475 | 6 |
| training rows | 13.351 | 7 |
| training rows | 13.372 | 8 |
| training rows | 13.168 | 9 |
| training rows | 13.107 | 10 |
| training rows | 12.943 | 11 |
| training rows | 12.782 | 12 |
| training rows | 12.839 | 13 |
| training rows | 12.942 | 14 |
| training rows | 12.756 | 15 |
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 negative log-likelihood over the last 10% of epochs averaged 12.8 nats per row.
- Held-out rows are about as likely as training rows — Mean log-likelihood -34.2 nats per training row and -34.6 per held-out row.
- 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.092 (mean Kolmogorov–Smirnov distance); categories 0.036 (mean total variation) — at most 0.10, which the Synthetic studio's scorecard rates as good column fidelity.
Real vs synthetic, column by column
| Column | Kind | Real | Synthetic | Distance | Measure |
|---|---|---|---|---|---|
| age | numeric | 43.14 ± 13.1 | 42.47 ± 11.8 | 0.0844 | Kolmogorov–Smirnov D |
| annual income | numeric | 2.929e+04 ± 1.43e+04 | 2.909e+04 ± 1.21e+04 | 0.1122 | Kolmogorov–Smirnov D |
| tenure_months | numeric | 15 ± 10.7 | 15.52 ± 9.65 | 0.0906 | Kolmogorov–Smirnov D |
| plan | categorical | plus 39.7% | plus 41.6% | 0.0281 | total variation |
| region | categorical | south 30.4% | south 31.6% | 0.0548 | total variation |
| churned | boolean | false 76.9% | false 79.4% | 0.0250 | total variation |
| signup | temporal | 2020-11-05 ± 621 days | 2020-11-19 ± 559 days | 0.0844 | Kolmogorov–Smirnov D |
| visits | numeric | 3.394 ± 2.09 | 3.537 ± 2.04 | 0.0875 | Kolmogorov–Smirnov D |
- 80 of 400 rows (20%) were held out of training so privacy and utility can be checked against rows the generator never saw.
- Categories are smoothed with uniform noise (dequantization), so the log-likelihoods are lower bounds for the category part.
The exact R script · R R version 4.5.1 (2025-06-13)
# Synthetic data — normalizing flow (RealNVP, NICE, MAF, Glow, spline)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method synth.flow 1.1.1 · spec f12c6eb055277e66
# 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.flow/customers_glow/out-r")
# 3 glow layers map standardized numbers and dequantized one-hot categories to N(0, I);
# the exact log-likelihood is the training loss. Twin of codesplash.synth.flows.fit_flow (written from the papers).
HIDDEN <- as.integer(unlist(c(16, 16)))
holdout_cols <- if (length(holdout_rows)) lapply(cols, cs_synth_take, rows = holdout_rows) else NULL
fit <- cs_synth_flow(
train, N_OUT, HIDDEN,
kind = "glow",
layers = as.integer(3),
epochs = as.integer(15),
batch_size = 100,
lr = 0.001,
seed = SEED,
holdout = holdout_cols,
bins = as.integer(8), # spline flows only
tail_bound = 3
)
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))
)
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$dims <- fit$facts$dims
fit_values$final_loss <- mean(history$loss[tail_rows])
fit_values$train_loglik <- fit$facts$train_loglik
if (fit$facts$n_holdout_ll > 0) {
fit_values$holdout_loglik <- fit$facts$holdout_loglik
fit_values$n_holdout_ll <- fit$facts$n_holdout_ll
}
model_note <- " with a normalizing flow"
ne <- nrow(history)
extra_charts[[length(extra_charts) + 1L]] <- cs_chart("training", "training-components", "Negative log-likelihood by epoch", list(
x = cs_col("Epoch", history$epoch, "numeric"),
value = cs_col("Negative log-likelihood (nats per row)", history$loss, "numeric"),
component = cs_col("Part", rep("training rows", ne), "categorical", levels = c("training rows"))
), note = "In the flow's coordinates (standardized numbers, dequantized categories); lower is better.")
finite <- all(is.finite(history$loss))
assumptions[[length(assumptions) + 1L]] <- list(
key = "training_stable", label = "Training stayed finite",
status = if (finite) "pass" else "fail",
detail = if (finite) sprintf("The negative log-likelihood over the last 10%% of epochs averaged %s nats per row.", format(signif(fit_values$final_loss, 3)))
else "The loss became infinite or undefined; lower the learning rate or use fewer layers."
)
if (fit$facts$n_holdout_ll > 0) {
gap <- fit$facts$train_loglik - fit$facts$holdout_loglik
ok <- isTRUE(gap <= 1)
assumptions[[length(assumptions) + 1L]] <- list(
key = "generalizes", label = "Held-out rows are about as likely as training rows",
status = if (ok) "pass" else "warn",
detail = paste0(sprintf("Mean log-likelihood %s nats per training row and %s per held-out row",
format(signif(fit$facts$train_loglik, 3)), format(signif(fit$facts$holdout_loglik, 3))),
if (ok) "." else " — training rows are far more likely, so the flow is memorizing them; use fewer epochs or layers.")
)
} else {
assumptions[[length(assumptions) + 1L]] <- list(
key = "generalizes", label = "Held-out rows are about as likely as training rows", status = "info",
detail = "No complete rows were held out, so generalization can't be checked; set a holdout share to compare."
)
}
if (isTRUE(fit$facts$dequantized)) {
warnings <- c(warnings, "Categories are smoothed with uniform noise (dequantization), so the log-likelihoods are lower bounds for the category part.")
}
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.flow/customers_glow/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 — normalizing flow (RealNVP, NICE, MAF, Glow, spline)",
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,
flow = "glow",
bins = 8,
tail_bound = 3,
layers = 3,
hidden_layers = c(16, 16),
epochs = 15,
batch_size = 100,
learning_rate = 0.001,
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
))
))
320 synthetic rows over 8 columns from 320 training rows with a normalizing flow. Numeric columns differ from the data by a mean Kolmogorov–Smirnov distance of 0.092 and categories by a mean total variation of 0.036.
- Synthetic rows
- 320
- Mean KS distance
- 0.0918
- Mean TV distance
- 0.0360
- 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 negative log-likelihood over the last 10% of epochs averaged 12.8 nats per row.
- Held-out rows are about as likely as training rows — Mean log-likelihood -34.2 nats per training row and -34.6 per held-out row.
- 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.092 (mean Kolmogorov–Smirnov distance); categories 0.036 (mean total variation) — at most 0.10, which the Synthetic studio's scorecard rates as good column fidelity.
Real vs synthetic, column by column
| Column | Kind | Real | Synthetic | Distance | Measure |
|---|---|---|---|---|---|
| age | numeric | 43.14 ± 13.1 | 42.47 ± 11.8 | 0.0844 | Kolmogorov–Smirnov D |
| annual income | numeric | 2.929e+04 ± 1.43e+04 | 2.909e+04 ± 1.21e+04 | 0.1122 | Kolmogorov–Smirnov D |
| tenure_months | numeric | 15 ± 10.7 | 15.52 ± 9.65 | 0.0906 | Kolmogorov–Smirnov D |
| plan | categorical | plus 39.7% | plus 41.6% | 0.0281 | total variation |
| region | categorical | south 30.4% | south 31.6% | 0.0548 | total variation |
| churned | boolean | false 76.9% | false 79.4% | 0.0250 | total variation |
| signup | temporal | 2020-11-05 ± 621 days | 2020-11-19 ± 559 days | 0.0844 | Kolmogorov–Smirnov D |
| visits | numeric | 3.394 ± 2.09 | 3.538 ± 2.04 | 0.0875 | Kolmogorov–Smirnov D |
- 80 of 400 rows (20%) were held out of training so privacy and utility can be checked against rows the generator never saw.
- Categories are smoothed with uniform noise (dequantization), so the log-likelihoods are lower bounds for the category part.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Synthetic data — normalizing flow (RealNVP, NICE, MAF, Glow, spline)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method synth.flow 1.1.1 · spec f12c6eb055277e66
# 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 flows # twin of codesplashr::cs_synth_flow (RealNVP, NICE, MAF, Glow, spline flows; written from the papers)
# %% 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.flow/customers_glow/out-python",
)
# 3 glow layers map standardized numbers and dequantized one-hot categories to N(0, I);
# the exact log-likelihood is the training loss, and running the flow backwards turns noise into rows.
HIDDEN = [int(u) for u in [16, 16]]
holdout_cols = [c.take(holdout_rows) for c in cols] if len(holdout_rows) else None
synth, facts, hist = flows.fit_flow(
train, N_OUT, HIDDEN,
kind="glow",
layers=3,
epochs=15,
batch_size=100,
lr=0.001,
seed=SEED,
holdout=holdout_cols,
bins=8, # spline flows only
tail_bound=3,
)
history = pd.DataFrame(hist)
last = max(1, len(hist) // 10) # the last 10% of epochs
fit_values["batch_size"] = facts["batch_size"]
fit_values["dims"] = facts["dims"]
fit_values["final_loss"] = float(np.mean([h["loss"] for h in hist[-last:]]))
fit_values["train_loglik"] = facts["train_loglik"]
if facts["n_holdout_ll"] > 0:
fit_values["holdout_loglik"] = facts["holdout_loglik"]
fit_values["n_holdout_ll"] = facts["n_holdout_ll"]
model_note = " with a normalizing flow"
ep = history["epoch"].tolist()
extra_charts.append(cs.chart("training", "training-components", "Negative log-likelihood by epoch", {
"x": cs.col("Epoch", ep, "numeric"),
"value": cs.col("Negative log-likelihood (nats per row)", history["loss"].tolist(), "numeric"),
"component": cs.col("Part", ["training rows"] * len(ep), "categorical", levels=["training rows"]),
}, note="In the flow's coordinates (standardized numbers, dequantized categories); lower is better."))
finite = bool(np.all(np.isfinite(history["loss"].to_numpy())))
assumptions.append({
"key": "training_stable",
"label": "Training stayed finite",
"status": "pass" if finite else "fail",
"detail": f"The negative log-likelihood over the last 10% of epochs averaged {fit_values['final_loss']:.3g} nats per row." if finite else "The loss became infinite or undefined; lower the learning rate or use fewer layers.",
})
if facts["n_holdout_ll"] > 0:
gap = facts["train_loglik"] - facts["holdout_loglik"]
assumptions.append({
"key": "generalizes",
"label": "Held-out rows are about as likely as training rows",
"status": "warn" if not gap <= 1.0 else "pass",
"detail": f"Mean log-likelihood {facts['train_loglik']:.3g} nats per training row and {facts['holdout_loglik']:.3g} per held-out row"
+ (" — training rows are far more likely, so the flow is memorizing them; use fewer epochs or layers." if not gap <= 1.0 else "."),
})
else:
assumptions.append({
"key": "generalizes",
"label": "Held-out rows are about as likely as training rows",
"status": "info",
"detail": "No complete rows were held out, so generalization can't be checked; set a holdout share to compare.",
})
if facts["dequantized"]:
warnings.append("Categories are smoothed with uniform noise (dequantization), so the log-likelihoods are lower bounds for the category part.")
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.flow/customers_glow/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 — normalizing flow (RealNVP, NICE, MAF, Glow, spline)",
"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,
"flow": "glow",
"bins": 8,
"tail_bound": 3,
"layers": 3,
"hidden_layers": [16, 16],
"epochs": 15,
"batch_size": 100,
"learning_rate": 0.001,
"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,
}},
})
Flow: Glow scores −34.24 nats per training row and −34.60 per held-out row, after 14 input dimensions (categories become several). Its mean KS distance per column is 0.092.
Held-out log-likelihoods are comparable across flows on the same rows and the same dequantization, which makes them a fair way to choose among flows.
Masked autoregressive flows
ReadA masked autoregressive flowMasked autoregressive flowA flow whose layers predict each column's shift and scale from the columns before it, using a masked network (MADE). transforms each column given the columns before it:
Masks in one network (MADE) make every and see only earlier columns, so scoring a row takes one pass. Sampling has to go column by column: needs first. The inverse autoregressive flow makes the opposite trade.
In the reference's two-column example the first column passes through, the second becomes −0.584, and the log-determinant is −0.06.
MAF in CodeSplash
Explore150 synthetic rows over 3 columns from 120 training rows with a normalizing flow. Numeric columns differ from the data by a mean Kolmogorov–Smirnov distance of 0.188 and categories by a mean total variation of 0.032. 1 synthetic row is identical to a training row.
- Synthetic rows
- 150
- Mean KS distance
- 0.1883
- Mean TV distance
- 0.0317
- Rows copied from the data
- 1
Plots
View data
| Density | Source | sepal_length |
|---|---|---|
| 0.2206 | real | 4.357 |
| 0.0735 | real | 4.470 |
| 0.2206 | real | 4.583 |
| 0.1471 | real | 4.697 |
| 0.2941 | real | 4.810 |
| 0.3676 | real | 4.923 |
| 0.5147 | real | 5.037 |
| 0.7353 | real | 5.150 |
| 0.0735 | real | 5.263 |
| 0.2941 | real | 5.377 |
| 0.4412 | real | 5.490 |
| 0.2941 | real | 5.603 |
| 0.5147 | real | 5.717 |
| 0.5147 | real | 5.830 |
| 0.2206 | real | 5.943 |
| 0.6618 | real | 6.057 |
| 0.2941 | real | 6.170 |
| 0.5882 | real | 6.283 |
| 0.5147 | real | 6.397 |
| 0.2941 | real | 6.510 |
| 0.0735 | real | 6.623 |
| 0.5147 | real | 6.737 |
| 0.3676 | real | 6.850 |
| 0 | real | 6.963 |
| 0.0735 | real | 7.077 |
| 0.0735 | real | 7.190 |
| 0.0735 | real | 7.303 |
| 0.0735 | real | 7.417 |
| 0 | real | 7.530 |
| 0.2941 | real | 7.643 |
| 0.3529 | synthetic | 4.357 |
| 0.1176 | synthetic | 4.470 |
| 0.1176 | synthetic | 4.583 |
| 0 | synthetic | 4.697 |
| 0.2353 | synthetic | 4.810 |
| 0.4118 | synthetic | 4.923 |
| 0.0588 | synthetic | 5.037 |
| 0.4118 | synthetic | 5.150 |
| 0.3529 | synthetic | 5.263 |
| 0.2353 | synthetic | 5.377 |
| 0.5294 | synthetic | 5.490 |
| 0.4118 | synthetic | 5.603 |
| 0.5294 | synthetic | 5.717 |
| 0.2353 | synthetic | 5.830 |
| 0.5882 | synthetic | 5.943 |
| 0.4706 | synthetic | 6.057 |
| 0.5882 | synthetic | 6.170 |
| 0.4118 | synthetic | 6.283 |
| 0.2941 | synthetic | 6.397 |
| 0.8824 | synthetic | 6.510 |
| 0.3529 | synthetic | 6.623 |
| 0.1765 | synthetic | 6.737 |
| 0.1765 | synthetic | 6.850 |
| 0.3529 | synthetic | 6.963 |
| 0.0588 | synthetic | 7.077 |
| 0.0588 | synthetic | 7.190 |
| 0 | synthetic | 7.303 |
| 0.0588 | synthetic | 7.417 |
| 0.0588 | synthetic | 7.530 |
| 0.2941 | synthetic | 7.643 |
View data
| Density | Source | petal_length |
|---|---|---|
| 0.1293 | real | 1.197 |
| 0.7759 | real | 1.390 |
| 0.6466 | real | 1.583 |
| 0.1293 | real | 1.777 |
| 0.0862 | real | 1.970 |
| 0 | real | 2.163 |
| 0 | real | 2.357 |
| 0 | real | 2.550 |
| 0 | real | 2.743 |
| 0.0431 | real | 2.937 |
| 0 | real | 3.130 |
| 0 | real | 3.323 |
| 0.1293 | real | 3.517 |
| 0.0862 | real | 3.710 |
| 0.2586 | real | 3.903 |
| 0.0862 | real | 4.097 |
| 0.2155 | real | 4.290 |
| 0.4310 | real | 4.483 |
| 0.2155 | real | 4.677 |
| 0.3448 | real | 4.870 |
| 0.4741 | real | 5.063 |
| 0.1724 | real | 5.257 |
| 0.1724 | real | 5.450 |
| 0.3448 | real | 5.643 |
| 0.0862 | real | 5.837 |
| 0.1724 | real | 6.030 |
| 0.0431 | real | 6.223 |
| 0 | real | 6.417 |
| 0.0862 | real | 6.610 |
| 0.0431 | real | 6.803 |
| 0.2759 | synthetic | 1.197 |
| 0 | synthetic | 1.390 |
| 0.0690 | synthetic | 1.583 |
| 0.1034 | synthetic | 1.777 |
| 0.2759 | synthetic | 1.970 |
| 0.0345 | synthetic | 2.163 |
| 0.2759 | synthetic | 2.357 |
| 0.1379 | synthetic | 2.550 |
| 0.2759 | synthetic | 2.743 |
| 0.2414 | synthetic | 2.937 |
| 0.2759 | synthetic | 3.130 |
| 0.2069 | synthetic | 3.323 |
| 0.2069 | synthetic | 3.517 |
| 0.3103 | synthetic | 3.710 |
| 0.3448 | synthetic | 3.903 |
| 0.3793 | synthetic | 4.097 |
| 0.2069 | synthetic | 4.290 |
| 0.1379 | synthetic | 4.483 |
| 0.2069 | synthetic | 4.677 |
| 0.2414 | synthetic | 4.870 |
| 0.1034 | synthetic | 5.063 |
| 0.3103 | synthetic | 5.257 |
| 0.1724 | synthetic | 5.450 |
| 0.0690 | synthetic | 5.643 |
| 0.0345 | synthetic | 5.837 |
| 0.1034 | synthetic | 6.030 |
| 0 | synthetic | 6.223 |
| 0.0690 | synthetic | 6.417 |
| 0.0690 | synthetic | 6.610 |
| 0.0345 | synthetic | 6.803 |
View data
| species | Share | Source |
|---|---|---|
| setosa | 0.3417 | real |
| versicolor | 0.3167 | real |
| virginica | 0.3417 | real |
| setosa | 0.3733 | synthetic |
| versicolor | 0.2933 | synthetic |
| virginica | 0.3333 | synthetic |
View data
| Column | Column | Difference |
|---|---|---|
| sepal_length | sepal_length | 0 |
| petal_length | sepal_length | 0.6235 |
| sepal_length | petal_length | 0.6235 |
| petal_length | petal_length | 0 |
In the flow's coordinates (standardized numbers, dequantized categories); lower is better.
View data
| Part | Negative log-likelihood (nats per row) | Epoch |
|---|---|---|
| training rows | 6.194 | 1 |
| training rows | 6.141 | 2 |
| training rows | 6.092 | 3 |
| training rows | 5.996 | 4 |
| training rows | 5.987 | 5 |
| training rows | 5.875 | 6 |
| training rows | 5.813 | 7 |
| training rows | 5.701 | 8 |
| training rows | 5.671 | 9 |
| training rows | 5.641 | 10 |
| training rows | 5.520 | 11 |
| training rows | 5.499 | 12 |
| training rows | 5.388 | 13 |
| training rows | 5.334 | 14 |
| training rows | 5.274 | 15 |
| training rows | 5.236 | 16 |
| training rows | 5.126 | 17 |
| training rows | 5.038 | 18 |
| training rows | 5.032 | 19 |
| training rows | 4.937 | 20 |
| training rows | 4.885 | 21 |
| training rows | 4.792 | 22 |
| training rows | 4.734 | 23 |
| training rows | 4.637 | 24 |
| training rows | 4.643 | 25 |
| training rows | 4.555 | 26 |
| training rows | 4.495 | 27 |
| training rows | 4.472 | 28 |
| training rows | 4.432 | 29 |
| training rows | 4.475 | 30 |
Assumptions
- Enough rows for a neural generator — 120 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 negative log-likelihood over the last 10% of epochs averaged 4.46 nats per row.
- Held-out rows are about as likely as training rows — Mean log-likelihood -4.6 nats per training row and -5.02 per held-out row.
- No synthetic row copies a training row — 1 synthetic row is 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.188 (mean Kolmogorov–Smirnov distance); categories 0.032 (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
| Column | Kind | Real | Synthetic | Distance | Measure |
|---|---|---|---|---|---|
| sepal_length | numeric | 5.828 ± 0.8 | 5.92 ± 0.787 | 0.1217 | Kolmogorov–Smirnov D |
| petal_length | numeric | 3.725 ± 1.76 | 3.691 ± 1.34 | 0.2550 | Kolmogorov–Smirnov D |
| species | categorical | setosa 34.2% | setosa 37.3% | 0.0317 | total variation |
- 30 of 150 rows (20%) were held out of training so privacy and utility can be checked against rows the generator never saw.
- Categories are smoothed with uniform noise (dequantization), so the log-likelihoods are lower bounds for the category part.
The exact R script · R R version 4.5.1 (2025-06-13)
# Synthetic data — normalizing flow (RealNVP, NICE, MAF, Glow, spline)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method synth.flow 1.1.1 · spec 0d9b76a793acea8e
# Dataset: ml_iris (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("sepal_length", "petal_length", "species")
KINDS <- list(
sepal_length = "numeric",
petal_length = "numeric",
species = "categorical"
)
LEVELS <- list(
species = c("setosa", "versicolor", "virginica")
)
SEED <- 42
loaded <- cs_synth_load("tests/parity/fixtures/ml_iris.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 <- 150L
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.flow/iris_maf_species/out-r")
# 2 maf layers map standardized numbers and dequantized one-hot categories to N(0, I);
# the exact log-likelihood is the training loss. Twin of codesplash.synth.flows.fit_flow (written from the papers).
HIDDEN <- as.integer(unlist(c(16)))
holdout_cols <- if (length(holdout_rows)) lapply(cols, cs_synth_take, rows = holdout_rows) else NULL
fit <- cs_synth_flow(
train, N_OUT, HIDDEN,
kind = "maf",
layers = as.integer(2),
epochs = as.integer(30),
batch_size = 50,
lr = 0.001,
seed = SEED,
holdout = holdout_cols,
bins = as.integer(8), # spline flows only
tail_bound = 3
)
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))
)
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$dims <- fit$facts$dims
fit_values$final_loss <- mean(history$loss[tail_rows])
fit_values$train_loglik <- fit$facts$train_loglik
if (fit$facts$n_holdout_ll > 0) {
fit_values$holdout_loglik <- fit$facts$holdout_loglik
fit_values$n_holdout_ll <- fit$facts$n_holdout_ll
}
model_note <- " with a normalizing flow"
ne <- nrow(history)
extra_charts[[length(extra_charts) + 1L]] <- cs_chart("training", "training-components", "Negative log-likelihood by epoch", list(
x = cs_col("Epoch", history$epoch, "numeric"),
value = cs_col("Negative log-likelihood (nats per row)", history$loss, "numeric"),
component = cs_col("Part", rep("training rows", ne), "categorical", levels = c("training rows"))
), note = "In the flow's coordinates (standardized numbers, dequantized categories); lower is better.")
finite <- all(is.finite(history$loss))
assumptions[[length(assumptions) + 1L]] <- list(
key = "training_stable", label = "Training stayed finite",
status = if (finite) "pass" else "fail",
detail = if (finite) sprintf("The negative log-likelihood over the last 10%% of epochs averaged %s nats per row.", format(signif(fit_values$final_loss, 3)))
else "The loss became infinite or undefined; lower the learning rate or use fewer layers."
)
if (fit$facts$n_holdout_ll > 0) {
gap <- fit$facts$train_loglik - fit$facts$holdout_loglik
ok <- isTRUE(gap <= 1)
assumptions[[length(assumptions) + 1L]] <- list(
key = "generalizes", label = "Held-out rows are about as likely as training rows",
status = if (ok) "pass" else "warn",
detail = paste0(sprintf("Mean log-likelihood %s nats per training row and %s per held-out row",
format(signif(fit$facts$train_loglik, 3)), format(signif(fit$facts$holdout_loglik, 3))),
if (ok) "." else " — training rows are far more likely, so the flow is memorizing them; use fewer epochs or layers.")
)
} else {
assumptions[[length(assumptions) + 1L]] <- list(
key = "generalizes", label = "Held-out rows are about as likely as training rows", status = "info",
detail = "No complete rows were held out, so generalization can't be checked; set a holdout share to compare."
)
}
if (isTRUE(fit$facts$dequantized)) {
warnings <- c(warnings, "Categories are smoothed with uniform noise (dequantization), so the log-likelihoods are lower bounds for the category part.")
}
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.flow/iris_maf_species/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 — normalizing flow (RealNVP, NICE, MAF, Glow, spline)",
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 = 150,
flow = "maf",
bins = 8,
tail_bound = 3,
layers = 2,
hidden_layers = c(16),
epochs = 30,
batch_size = 50,
learning_rate = 0.001,
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
))
))
150 synthetic rows over 3 columns from 120 training rows with a normalizing flow. Numeric columns differ from the data by a mean Kolmogorov–Smirnov distance of 0.188 and categories by a mean total variation of 0.032. 1 synthetic row is identical to a training row.
- Synthetic rows
- 150
- Mean KS distance
- 0.1883
- Mean TV distance
- 0.0317
- Rows copied from the data
- 1
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Enough rows for a neural generator — 120 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 negative log-likelihood over the last 10% of epochs averaged 4.46 nats per row.
- Held-out rows are about as likely as training rows — Mean log-likelihood -4.6 nats per training row and -5.02 per held-out row.
- No synthetic row copies a training row — 1 synthetic row is 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.188 (mean Kolmogorov–Smirnov distance); categories 0.032 (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
| Column | Kind | Real | Synthetic | Distance | Measure |
|---|---|---|---|---|---|
| sepal_length | numeric | 5.828 ± 0.8 | 5.92 ± 0.787 | 0.1217 | Kolmogorov–Smirnov D |
| petal_length | numeric | 3.725 ± 1.76 | 3.691 ± 1.34 | 0.2550 | Kolmogorov–Smirnov D |
| species | categorical | setosa 34.2% | setosa 37.3% | 0.0317 | total variation |
- 30 of 150 rows (20%) were held out of training so privacy and utility can be checked against rows the generator never saw.
- Categories are smoothed with uniform noise (dequantization), so the log-likelihoods are lower bounds for the category part.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Synthetic data — normalizing flow (RealNVP, NICE, MAF, Glow, spline)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method synth.flow 1.1.1 · spec 0d9b76a793acea8e
# Dataset: ml_iris (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 flows # twin of codesplashr::cs_synth_flow (RealNVP, NICE, MAF, Glow, spline flows; written from the papers)
# %% Data
COLUMNS = ["sepal_length", "petal_length", "species"]
KINDS = {
"sepal_length": "numeric",
"petal_length": "numeric",
"species": "categorical",
}
LEVELS = {
"species": ["setosa", "versicolor", "virginica"],
}
SEED = 42
cols, n_input = sy.load("tests/parity/fixtures/ml_iris.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 = 150 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.flow/iris_maf_species/out-python",
)
# 2 maf layers map standardized numbers and dequantized one-hot categories to N(0, I);
# the exact log-likelihood is the training loss, and running the flow backwards turns noise into rows.
HIDDEN = [int(u) for u in [16]]
holdout_cols = [c.take(holdout_rows) for c in cols] if len(holdout_rows) else None
synth, facts, hist = flows.fit_flow(
train, N_OUT, HIDDEN,
kind="maf",
layers=2,
epochs=30,
batch_size=50,
lr=0.001,
seed=SEED,
holdout=holdout_cols,
bins=8, # spline flows only
tail_bound=3,
)
history = pd.DataFrame(hist)
last = max(1, len(hist) // 10) # the last 10% of epochs
fit_values["batch_size"] = facts["batch_size"]
fit_values["dims"] = facts["dims"]
fit_values["final_loss"] = float(np.mean([h["loss"] for h in hist[-last:]]))
fit_values["train_loglik"] = facts["train_loglik"]
if facts["n_holdout_ll"] > 0:
fit_values["holdout_loglik"] = facts["holdout_loglik"]
fit_values["n_holdout_ll"] = facts["n_holdout_ll"]
model_note = " with a normalizing flow"
ep = history["epoch"].tolist()
extra_charts.append(cs.chart("training", "training-components", "Negative log-likelihood by epoch", {
"x": cs.col("Epoch", ep, "numeric"),
"value": cs.col("Negative log-likelihood (nats per row)", history["loss"].tolist(), "numeric"),
"component": cs.col("Part", ["training rows"] * len(ep), "categorical", levels=["training rows"]),
}, note="In the flow's coordinates (standardized numbers, dequantized categories); lower is better."))
finite = bool(np.all(np.isfinite(history["loss"].to_numpy())))
assumptions.append({
"key": "training_stable",
"label": "Training stayed finite",
"status": "pass" if finite else "fail",
"detail": f"The negative log-likelihood over the last 10% of epochs averaged {fit_values['final_loss']:.3g} nats per row." if finite else "The loss became infinite or undefined; lower the learning rate or use fewer layers.",
})
if facts["n_holdout_ll"] > 0:
gap = facts["train_loglik"] - facts["holdout_loglik"]
assumptions.append({
"key": "generalizes",
"label": "Held-out rows are about as likely as training rows",
"status": "warn" if not gap <= 1.0 else "pass",
"detail": f"Mean log-likelihood {facts['train_loglik']:.3g} nats per training row and {facts['holdout_loglik']:.3g} per held-out row"
+ (" — training rows are far more likely, so the flow is memorizing them; use fewer epochs or layers." if not gap <= 1.0 else "."),
})
else:
assumptions.append({
"key": "generalizes",
"label": "Held-out rows are about as likely as training rows",
"status": "info",
"detail": "No complete rows were held out, so generalization can't be checked; set a holdout share to compare.",
})
if facts["dequantized"]:
warnings.append("Categories are smoothed with uniform noise (dequantization), so the log-likelihoods are lower bounds for the category part.")
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.flow/iris_maf_species/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 — normalizing flow (RealNVP, NICE, MAF, Glow, spline)",
"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": 150,
"flow": "maf",
"bins": 8,
"tail_bound": 3,
"layers": 2,
"hidden_layers": [16],
"epochs": 30,
"batch_size": 50,
"learning_rate": 0.001,
"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,
}},
})
With two measurements and the species, Flow: MAF scores −4.60 per training row and −5.02 per held-out row. With only 30 held-out rows, that gap is a noisy estimate; on a larger table, check whether it holds.
The column order is a modeling choice. Reorder the columns and the flow, and its likelihood, can change.
Spline flows
ReadAffine couplings only shift and scale. A neural spline flowNeural spline flowA flow whose couplings bend each column with a monotone piecewise rational-quadratic curve; values past the range pass unchanged. bends each transformed column with a monotone, piecewise rational-quadratic curve whose knots and slopes come from the passed-through half. Monotone means one-to-one, so the curve can be inverted exactly, and its slope gives the log-determinant.
The reference evaluates one segment at five points from 0 to 1: 0.00, 0.335, 0.918, 1.551, 2.00. Strictly rising, so invertible. Outside the spline's range, values pass through unchanged.
More layers bend the density further; the log-determinant keeps the bookkeeping exact.
DExplorable · Normalizing flows: change of variables
Why does a normalizing flow need the log-determinant of its Jacobian?
Does the flow's density, as computed here, integrate to 1?
How much each layer stretches: s(y) = α·tanh(u·y + v).
How much each layer bends: t(y) = β·sin(w·y) + c·y.
Commit your prediction above to see the result
Make your prediction to see the result.
A spline flow on penguins
Explore300 synthetic rows over 5 columns from 258 training rows with a normalizing flow. Numeric columns differ from the data by a mean Kolmogorov–Smirnov distance of 0.084 and categories by a mean total variation of 0.030.
- Synthetic rows
- 300
- Mean KS distance
- 0.0838
- Mean TV distance
- 0.0301
- Rows copied from the data
- 0
Plots
View data
| Density | Source | bill_len |
|---|---|---|
| 0.0043 | real | 32.558 |
| 0.0043 | real | 33.475 |
| 0.0213 | real | 34.392 |
| 0.0341 | real | 35.308 |
| 0.0469 | real | 36.225 |
| 0.0469 | real | 37.142 |
| 0.0639 | real | 38.058 |
| 0.0639 | real | 38.975 |
| 0.0511 | real | 39.892 |
| 0.0767 | real | 40.808 |
| 0.0426 | real | 41.725 |
| 0.0384 | real | 42.642 |
| 0.0298 | real | 43.558 |
| 0.0256 | real | 44.475 |
| 0.0980 | real | 45.392 |
| 0.0767 | real | 46.308 |
| 0.0554 | real | 47.225 |
| 0.0384 | real | 48.142 |
| 0.0597 | real | 49.058 |
| 0.0639 | real | 49.975 |
| 0.0682 | real | 50.892 |
| 0.0384 | real | 51.808 |
| 0.0128 | real | 52.725 |
| 0.0085 | real | 53.642 |
| 0.0085 | real | 54.558 |
| 0.0085 | real | 55.475 |
| 0 | real | 56.392 |
| 0 | real | 57.308 |
| 0 | real | 58.225 |
| 0.0043 | real | 59.142 |
| 0.0109 | synthetic | 32.558 |
| 0.0036 | synthetic | 33.475 |
| 0.0073 | synthetic | 34.392 |
| 0.0145 | synthetic | 35.308 |
| 0.0400 | synthetic | 36.225 |
| 0.0509 | synthetic | 37.142 |
| 0.0618 | synthetic | 38.058 |
| 0.0436 | synthetic | 38.975 |
| 0.0618 | synthetic | 39.892 |
| 0.0800 | synthetic | 40.808 |
| 0.0800 | synthetic | 41.725 |
| 0.0436 | synthetic | 42.642 |
| 0.0400 | synthetic | 43.558 |
| 0.0545 | synthetic | 44.475 |
| 0.0655 | synthetic | 45.392 |
| 0.0618 | synthetic | 46.308 |
| 0.0655 | synthetic | 47.225 |
| 0.0582 | synthetic | 48.142 |
| 0.0691 | synthetic | 49.058 |
| 0.0655 | synthetic | 49.975 |
| 0.0364 | synthetic | 50.892 |
| 0.0255 | synthetic | 51.808 |
| 0.0145 | synthetic | 52.725 |
| 0.0036 | synthetic | 53.642 |
| 0.0073 | synthetic | 54.558 |
| 0.0109 | synthetic | 55.475 |
| 0 | synthetic | 56.392 |
| 0 | synthetic | 57.308 |
| 0.0073 | synthetic | 58.225 |
| 0.0073 | synthetic | 59.142 |
View data
| Density | Source | bill_dep |
|---|---|---|
| 0.0424 | real | 13.338 |
| 0.0847 | real | 13.615 |
| 0.1271 | real | 13.892 |
| 0.1412 | real | 14.168 |
| 0.1271 | real | 14.445 |
| 0.1271 | real | 14.722 |
| 0.1412 | real | 14.998 |
| 0.0988 | real | 15.275 |
| 0.0565 | real | 15.552 |
| 0.1553 | real | 15.828 |
| 0.0988 | real | 16.105 |
| 0.1271 | real | 16.382 |
| 0.0847 | real | 16.658 |
| 0.2118 | real | 16.935 |
| 0.2400 | real | 17.212 |
| 0.1412 | real | 17.488 |
| 0.2118 | real | 17.765 |
| 0.1412 | real | 18.042 |
| 0.1271 | real | 18.318 |
| 0.2683 | real | 18.595 |
| 0.2824 | real | 18.872 |
| 0.0847 | real | 19.148 |
| 0.1130 | real | 19.425 |
| 0.0988 | real | 19.702 |
| 0.1130 | real | 19.978 |
| 0.0565 | real | 20.255 |
| 0.0141 | real | 20.532 |
| 0.0282 | real | 20.808 |
| 0.0565 | real | 21.085 |
| 0.0141 | real | 21.362 |
| 0.0723 | synthetic | 13.338 |
| 0.0361 | synthetic | 13.615 |
| 0.0602 | synthetic | 13.892 |
| 0.0602 | synthetic | 14.168 |
| 0.0723 | synthetic | 14.445 |
| 0.1084 | synthetic | 14.722 |
| 0.1325 | synthetic | 14.998 |
| 0.1446 | synthetic | 15.275 |
| 0.0964 | synthetic | 15.552 |
| 0.0843 | synthetic | 15.828 |
| 0.2289 | synthetic | 16.105 |
| 0.1807 | synthetic | 16.382 |
| 0.1446 | synthetic | 16.658 |
| 0.2048 | synthetic | 16.935 |
| 0.2048 | synthetic | 17.212 |
| 0.1446 | synthetic | 17.488 |
| 0.1807 | synthetic | 17.765 |
| 0.1687 | synthetic | 18.042 |
| 0.2530 | synthetic | 18.318 |
| 0.2289 | synthetic | 18.595 |
| 0.1687 | synthetic | 18.872 |
| 0.1446 | synthetic | 19.148 |
| 0.1807 | synthetic | 19.425 |
| 0.0602 | synthetic | 19.702 |
| 0.0723 | synthetic | 19.978 |
| 0.0723 | synthetic | 20.255 |
| 0.0361 | synthetic | 20.532 |
| 0.0120 | synthetic | 20.808 |
| 0.0482 | synthetic | 21.085 |
| 0.0120 | synthetic | 21.362 |
View data
| Density | Source | flipper_len |
|---|---|---|
| 0.0020 | real | 172.98 |
| 0.0020 | real | 174.95 |
| 0.0020 | real | 176.92 |
| 0.0060 | real | 178.88 |
| 0.0159 | real | 180.85 |
| 0.0099 | real | 182.82 |
| 0.0238 | real | 184.78 |
| 0.0258 | real | 186.75 |
| 0.0179 | real | 188.72 |
| 0.0616 | real | 190.68 |
| 0.0218 | real | 192.65 |
| 0.0358 | real | 194.62 |
| 0.0278 | real | 196.58 |
| 0.0258 | real | 198.55 |
| 0.0139 | real | 200.52 |
| 0.0119 | real | 202.48 |
| 0.0060 | real | 204.45 |
| 0.0060 | real | 206.42 |
| 0.0179 | real | 208.38 |
| 0.0218 | real | 210.35 |
| 0.0218 | real | 212.32 |
| 0.0278 | real | 214.28 |
| 0.0199 | real | 216.25 |
| 0.0179 | real | 218.22 |
| 0.0199 | real | 220.18 |
| 0.0079 | real | 222.15 |
| 0.0119 | real | 224.12 |
| 0.0020 | real | 226.08 |
| 0.0119 | real | 228.05 |
| 0.0119 | real | 230.02 |
| 0.0034 | synthetic | 172.98 |
| 0.0034 | synthetic | 174.95 |
| 0.0017 | synthetic | 176.92 |
| 0.0051 | synthetic | 178.88 |
| 0.0068 | synthetic | 180.85 |
| 0.0136 | synthetic | 182.82 |
| 0.0102 | synthetic | 184.78 |
| 0.0203 | synthetic | 186.75 |
| 0.0220 | synthetic | 188.72 |
| 0.0339 | synthetic | 190.68 |
| 0.0407 | synthetic | 192.65 |
| 0.0356 | synthetic | 194.62 |
| 0.0339 | synthetic | 196.58 |
| 0.0339 | synthetic | 198.55 |
| 0.0305 | synthetic | 200.52 |
| 0.0220 | synthetic | 202.48 |
| 0.0220 | synthetic | 204.45 |
| 0.0237 | synthetic | 206.42 |
| 0.0237 | synthetic | 208.38 |
| 0.0153 | synthetic | 210.35 |
| 0.0186 | synthetic | 212.32 |
| 0.0153 | synthetic | 214.28 |
| 0.0068 | synthetic | 216.25 |
| 0.0237 | synthetic | 218.22 |
| 0.0102 | synthetic | 220.18 |
| 0.0068 | synthetic | 222.15 |
| 0.0102 | synthetic | 224.12 |
| 0.0017 | synthetic | 226.08 |
| 0.0068 | synthetic | 228.05 |
| 0.0068 | synthetic | 230.02 |
View data
| Density | Source | body_mass |
|---|---|---|
| 3.498e-5 | real | 2755.83 |
| 0.0001 | real | 2867.50 |
| 6.996e-5 | real | 2979.17 |
| 0.0002 | real | 3090.83 |
| 0.0005 | real | 3202.50 |
| 0.0003 | real | 3314.17 |
| 0.0006 | real | 3425.83 |
| 0.0005 | real | 3537.50 |
| 0.0007 | real | 3649.17 |
| 0.0005 | real | 3760.83 |
| 0.0004 | real | 3872.50 |
| 0.0005 | real | 3984.17 |
| 0.0005 | real | 4095.83 |
| 0.0003 | real | 4207.50 |
| 0.0003 | real | 4319.17 |
| 0.0004 | real | 4430.83 |
| 0.0001 | real | 4542.50 |
| 0.0006 | real | 4654.17 |
| 0.0003 | real | 4765.83 |
| 0.0003 | real | 4877.50 |
| 0.0002 | real | 4989.17 |
| 0.0003 | real | 5100.83 |
| 0.0001 | real | 5212.50 |
| 0.0002 | real | 5324.17 |
| 0.0001 | real | 5435.83 |
| 0.0005 | real | 5547.50 |
| 0.0002 | real | 5659.17 |
| 6.996e-5 | real | 5770.83 |
| 3.498e-5 | real | 5882.50 |
| 0.0001 | real | 5994.17 |
| 0.0001 | synthetic | 2755.83 |
| 8.955e-5 | synthetic | 2867.50 |
| 8.955e-5 | synthetic | 2979.17 |
| 0.0003 | synthetic | 3090.83 |
| 0.0004 | synthetic | 3202.50 |
| 0.0003 | synthetic | 3314.17 |
| 0.0003 | synthetic | 3425.83 |
| 0.0004 | synthetic | 3537.50 |
| 0.0005 | synthetic | 3649.17 |
| 0.0007 | synthetic | 3760.83 |
| 0.0005 | synthetic | 3872.50 |
| 0.0006 | synthetic | 3984.17 |
| 0.0004 | synthetic | 4095.83 |
| 0.0007 | synthetic | 4207.50 |
| 0.0003 | synthetic | 4319.17 |
| 0.0003 | synthetic | 4430.83 |
| 0.0007 | synthetic | 4542.50 |
| 0.0004 | synthetic | 4654.17 |
| 0.0002 | synthetic | 4765.83 |
| 0.0002 | synthetic | 4877.50 |
| 0.0004 | synthetic | 4989.17 |
| 0.0001 | synthetic | 5100.83 |
| 0.0001 | synthetic | 5212.50 |
| 0.0002 | synthetic | 5324.17 |
| 0.0002 | synthetic | 5435.83 |
| 8.955e-5 | synthetic | 5547.50 |
| 0.0001 | synthetic | 5659.17 |
| 0 | synthetic | 5770.83 |
| 8.955e-5 | synthetic | 5882.50 |
| 8.955e-5 | synthetic | 5994.17 |
View data
| species | Share | Source |
|---|---|---|
| Adelie | 0.4419 | real |
| Chinstrap | 0.1899 | real |
| Gentoo | 0.3682 | real |
| Adelie | 0.4367 | synthetic |
| Chinstrap | 0.2200 | synthetic |
| Gentoo | 0.3433 | synthetic |
View data
| Column | Column | Difference |
|---|---|---|
| bill_len | bill_len | 0 |
| bill_dep | bill_len | −0.0747 |
| flipper_len | bill_len | 0.1233 |
| body_mass | bill_len | 0.1537 |
| bill_len | bill_dep | −0.0747 |
| bill_dep | bill_dep | 0 |
| flipper_len | bill_dep | −0.1368 |
| body_mass | bill_dep | −0.0741 |
| bill_len | flipper_len | 0.1233 |
| bill_dep | flipper_len | −0.1368 |
| flipper_len | flipper_len | 0 |
| body_mass | flipper_len | 0.3090 |
| bill_len | body_mass | 0.1537 |
| bill_dep | body_mass | −0.0741 |
| flipper_len | body_mass | 0.3090 |
| body_mass | body_mass | 0 |
In the flow's coordinates (standardized numbers, dequantized categories); lower is better.
View data
| Part | Negative log-likelihood (nats per row) | Epoch |
|---|---|---|
| training rows | 8.678 | 1 |
| training rows | 7.886 | 2 |
| training rows | 7.356 | 3 |
| training rows | 6.962 | 4 |
| training rows | 6.643 | 5 |
| training rows | 6.423 | 6 |
| training rows | 6.240 | 7 |
| training rows | 6.044 | 8 |
| training rows | 5.919 | 9 |
| training rows | 5.886 | 10 |
| training rows | 5.803 | 11 |
| training rows | 5.587 | 12 |
| training rows | 5.576 | 13 |
| training rows | 5.635 | 14 |
| training rows | 5.452 | 15 |
Assumptions
- Enough rows for a neural generator — 256 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 negative log-likelihood over the last 10% of epochs averaged 5.45 nats per row.
- Held-out rows are about as likely as training rows — Mean log-likelihood -17.2 nats per training row and -17.5 per held-out row.
- 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.084 (mean Kolmogorov–Smirnov distance); categories 0.030 (mean total variation) — at most 0.10, which the Synthetic studio's scorecard rates as good column fidelity.
Real vs synthetic, column by column
| Column | Kind | Real | Synthetic | Distance | Measure |
|---|---|---|---|---|---|
| species | categorical | Adelie 44.2% | Adelie 43.7% | 0.0301 | total variation |
| bill_len | numeric | 43.96 ± 5.5 | 44.09 ± 5.3 | 0.0628 | Kolmogorov–Smirnov D |
| bill_dep | numeric | 17.14 ± 1.98 | 17.26 ± 1.83 | 0.0819 | Kolmogorov–Smirnov D |
| flipper_len | numeric | 201.3 ± 14.2 | 200.7 ± 12.5 | 0.1037 | Kolmogorov–Smirnov D |
| body_mass | numeric | 4219 ± 791 | 4167 ± 728 | 0.0870 | Kolmogorov–Smirnov D |
- 86 of 344 rows (25%) were held out of training so privacy and utility can be checked against rows the generator never saw.
- Categories are smoothed with uniform noise (dequantization), so the log-likelihoods are lower bounds for the category part.
The exact R script · R R version 4.5.1 (2025-06-13)
# Synthetic data — normalizing flow (RealNVP, NICE, MAF, Glow, spline)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method synth.flow 1.1.1 · spec c73f0b37824ca811
# Dataset: ml_penguins (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("species", "bill_len", "bill_dep", "flipper_len", "body_mass")
KINDS <- list(
species = "categorical",
bill_len = "numeric",
bill_dep = "numeric",
flipper_len = "numeric",
body_mass = "numeric"
)
LEVELS <- list(
species = c("Adelie", "Chinstrap", "Gentoo")
)
SEED <- 42
loaded <- cs_synth_load("tests/parity/fixtures/ml_penguins.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.25, rng)
train_rows <- sp$train; holdout_rows <- sp$holdout
train <- lapply(cols, cs_synth_take, rows = train_rows)
N_OUT <- 300L
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.flow/penguins_nsf/out-r")
# 3 nsf layers map standardized numbers and dequantized one-hot categories to N(0, I);
# the exact log-likelihood is the training loss. Twin of codesplash.synth.flows.fit_flow (written from the papers).
HIDDEN <- as.integer(unlist(c(16)))
holdout_cols <- if (length(holdout_rows)) lapply(cols, cs_synth_take, rows = holdout_rows) else NULL
fit <- cs_synth_flow(
train, N_OUT, HIDDEN,
kind = "nsf",
layers = as.integer(3),
epochs = as.integer(15),
batch_size = 64,
lr = 0.001,
seed = SEED,
holdout = holdout_cols,
bins = as.integer(8), # spline flows only
tail_bound = 3
)
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))
)
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$dims <- fit$facts$dims
fit_values$final_loss <- mean(history$loss[tail_rows])
fit_values$train_loglik <- fit$facts$train_loglik
if (fit$facts$n_holdout_ll > 0) {
fit_values$holdout_loglik <- fit$facts$holdout_loglik
fit_values$n_holdout_ll <- fit$facts$n_holdout_ll
}
model_note <- " with a normalizing flow"
ne <- nrow(history)
extra_charts[[length(extra_charts) + 1L]] <- cs_chart("training", "training-components", "Negative log-likelihood by epoch", list(
x = cs_col("Epoch", history$epoch, "numeric"),
value = cs_col("Negative log-likelihood (nats per row)", history$loss, "numeric"),
component = cs_col("Part", rep("training rows", ne), "categorical", levels = c("training rows"))
), note = "In the flow's coordinates (standardized numbers, dequantized categories); lower is better.")
finite <- all(is.finite(history$loss))
assumptions[[length(assumptions) + 1L]] <- list(
key = "training_stable", label = "Training stayed finite",
status = if (finite) "pass" else "fail",
detail = if (finite) sprintf("The negative log-likelihood over the last 10%% of epochs averaged %s nats per row.", format(signif(fit_values$final_loss, 3)))
else "The loss became infinite or undefined; lower the learning rate or use fewer layers."
)
if (fit$facts$n_holdout_ll > 0) {
gap <- fit$facts$train_loglik - fit$facts$holdout_loglik
ok <- isTRUE(gap <= 1)
assumptions[[length(assumptions) + 1L]] <- list(
key = "generalizes", label = "Held-out rows are about as likely as training rows",
status = if (ok) "pass" else "warn",
detail = paste0(sprintf("Mean log-likelihood %s nats per training row and %s per held-out row",
format(signif(fit$facts$train_loglik, 3)), format(signif(fit$facts$holdout_loglik, 3))),
if (ok) "." else " — training rows are far more likely, so the flow is memorizing them; use fewer epochs or layers.")
)
} else {
assumptions[[length(assumptions) + 1L]] <- list(
key = "generalizes", label = "Held-out rows are about as likely as training rows", status = "info",
detail = "No complete rows were held out, so generalization can't be checked; set a holdout share to compare."
)
}
if (isTRUE(fit$facts$dequantized)) {
warnings <- c(warnings, "Categories are smoothed with uniform noise (dequantization), so the log-likelihoods are lower bounds for the category part.")
}
synth <- cs_synth_add_missing(synth, train, rng, "none") # each column's missing share, at random
# %% Write and compare
out <- cs_ml_out_dir("target/academy-parity/run-8142/synth.flow/penguins_nsf/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 — normalizing flow (RealNVP, NICE, MAF, Glow, spline)",
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 = 300,
flow = "nsf",
bins = 8,
tail_bound = 3,
layers = 3,
hidden_layers = c(16),
epochs = 15,
batch_size = 64,
learning_rate = 0.001,
missing = "none",
holdout = 0.25,
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
))
))
300 synthetic rows over 5 columns from 258 training rows with a normalizing flow. Numeric columns differ from the data by a mean Kolmogorov–Smirnov distance of 0.084 and categories by a mean total variation of 0.030.
- Synthetic rows
- 300
- Mean KS distance
- 0.0838
- Mean TV distance
- 0.0301
- 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 — 256 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 negative log-likelihood over the last 10% of epochs averaged 5.45 nats per row.
- Held-out rows are about as likely as training rows — Mean log-likelihood -17.2 nats per training row and -17.5 per held-out row.
- 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.084 (mean Kolmogorov–Smirnov distance); categories 0.030 (mean total variation) — at most 0.10, which the Synthetic studio's scorecard rates as good column fidelity.
Real vs synthetic, column by column
| Column | Kind | Real | Synthetic | Distance | Measure |
|---|---|---|---|---|---|
| species | categorical | Adelie 44.2% | Adelie 43.7% | 0.0301 | total variation |
| bill_len | numeric | 43.96 ± 5.5 | 44.09 ± 5.3 | 0.0628 | Kolmogorov–Smirnov D |
| bill_dep | numeric | 17.14 ± 1.98 | 17.26 ± 1.83 | 0.0819 | Kolmogorov–Smirnov D |
| flipper_len | numeric | 201.3 ± 14.2 | 200.7 ± 12.5 | 0.1038 | Kolmogorov–Smirnov D |
| body_mass | numeric | 4219 ± 791 | 4167 ± 728 | 0.0870 | Kolmogorov–Smirnov D |
- 86 of 344 rows (25%) were held out of training so privacy and utility can be checked against rows the generator never saw.
- Categories are smoothed with uniform noise (dequantization), so the log-likelihoods are lower bounds for the category part.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Synthetic data — normalizing flow (RealNVP, NICE, MAF, Glow, spline)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method synth.flow 1.1.1 · spec c73f0b37824ca811
# Dataset: ml_penguins (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 flows # twin of codesplashr::cs_synth_flow (RealNVP, NICE, MAF, Glow, spline flows; written from the papers)
# %% Data
COLUMNS = ["species", "bill_len", "bill_dep", "flipper_len", "body_mass"]
KINDS = {
"species": "categorical",
"bill_len": "numeric",
"bill_dep": "numeric",
"flipper_len": "numeric",
"body_mass": "numeric",
}
LEVELS = {
"species": ["Adelie", "Chinstrap", "Gentoo"],
}
SEED = 42
cols, n_input = sy.load("tests/parity/fixtures/ml_penguins.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.25, rng)
train = [c.take(train_rows) for c in cols]
N_OUT = 300 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.flow/penguins_nsf/out-python",
)
# 3 nsf layers map standardized numbers and dequantized one-hot categories to N(0, I);
# the exact log-likelihood is the training loss, and running the flow backwards turns noise into rows.
HIDDEN = [int(u) for u in [16]]
holdout_cols = [c.take(holdout_rows) for c in cols] if len(holdout_rows) else None
synth, facts, hist = flows.fit_flow(
train, N_OUT, HIDDEN,
kind="nsf",
layers=3,
epochs=15,
batch_size=64,
lr=0.001,
seed=SEED,
holdout=holdout_cols,
bins=8, # spline flows only
tail_bound=3,
)
history = pd.DataFrame(hist)
last = max(1, len(hist) // 10) # the last 10% of epochs
fit_values["batch_size"] = facts["batch_size"]
fit_values["dims"] = facts["dims"]
fit_values["final_loss"] = float(np.mean([h["loss"] for h in hist[-last:]]))
fit_values["train_loglik"] = facts["train_loglik"]
if facts["n_holdout_ll"] > 0:
fit_values["holdout_loglik"] = facts["holdout_loglik"]
fit_values["n_holdout_ll"] = facts["n_holdout_ll"]
model_note = " with a normalizing flow"
ep = history["epoch"].tolist()
extra_charts.append(cs.chart("training", "training-components", "Negative log-likelihood by epoch", {
"x": cs.col("Epoch", ep, "numeric"),
"value": cs.col("Negative log-likelihood (nats per row)", history["loss"].tolist(), "numeric"),
"component": cs.col("Part", ["training rows"] * len(ep), "categorical", levels=["training rows"]),
}, note="In the flow's coordinates (standardized numbers, dequantized categories); lower is better."))
finite = bool(np.all(np.isfinite(history["loss"].to_numpy())))
assumptions.append({
"key": "training_stable",
"label": "Training stayed finite",
"status": "pass" if finite else "fail",
"detail": f"The negative log-likelihood over the last 10% of epochs averaged {fit_values['final_loss']:.3g} nats per row." if finite else "The loss became infinite or undefined; lower the learning rate or use fewer layers.",
})
if facts["n_holdout_ll"] > 0:
gap = facts["train_loglik"] - facts["holdout_loglik"]
assumptions.append({
"key": "generalizes",
"label": "Held-out rows are about as likely as training rows",
"status": "warn" if not gap <= 1.0 else "pass",
"detail": f"Mean log-likelihood {facts['train_loglik']:.3g} nats per training row and {facts['holdout_loglik']:.3g} per held-out row"
+ (" — training rows are far more likely, so the flow is memorizing them; use fewer epochs or layers." if not gap <= 1.0 else "."),
})
else:
assumptions.append({
"key": "generalizes",
"label": "Held-out rows are about as likely as training rows",
"status": "info",
"detail": "No complete rows were held out, so generalization can't be checked; set a holdout share to compare.",
})
if facts["dequantized"]:
warnings.append("Categories are smoothed with uniform noise (dequantization), so the log-likelihoods are lower bounds for the category part.")
sy.add_missing(synth, train, rng, "none") # each column's missing share, at random
# %% Write and compare
out = out_dir("target/academy-parity/run-8142/synth.flow/penguins_nsf/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 — normalizing flow (RealNVP, NICE, MAF, Glow, spline)",
"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": 300,
"flow": "nsf",
"bins": 8,
"tail_bound": 3,
"layers": 3,
"hidden_layers": [16],
"epochs": 15,
"batch_size": 64,
"learning_rate": 0.001,
"missing": "none",
"holdout": 0.25,
"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,
}},
})
Flow: Neural spline scores −17.17 per training row and −17.46 per held-out row, with a mean KS distance of 0.084. Splines suit skewed or many-peaked columns. Its columns differ from the MAF run below, so compare flows on the same columns before choosing.
400 synthetic rows over 7 columns from 258 training rows with a normalizing flow. Numeric columns differ from the data by a mean Kolmogorov–Smirnov distance of 0.141 and categories by a mean total variation of 0.061.
- Synthetic rows
- 400
- Mean KS distance
- 0.1408
- Mean TV distance
- 0.0611
- Rows copied from the data
- 0
Plots
View data
| Density | Source | bill_len |
|---|---|---|
| 0.0043 | real | 32.558 |
| 0.0043 | real | 33.475 |
| 0.0213 | real | 34.392 |
| 0.0341 | real | 35.308 |
| 0.0469 | real | 36.225 |
| 0.0469 | real | 37.142 |
| 0.0639 | real | 38.058 |
| 0.0639 | real | 38.975 |
| 0.0511 | real | 39.892 |
| 0.0767 | real | 40.808 |
| 0.0426 | real | 41.725 |
| 0.0384 | real | 42.642 |
| 0.0298 | real | 43.558 |
| 0.0256 | real | 44.475 |
| 0.0980 | real | 45.392 |
| 0.0767 | real | 46.308 |
| 0.0554 | real | 47.225 |
| 0.0384 | real | 48.142 |
| 0.0597 | real | 49.058 |
| 0.0639 | real | 49.975 |
| 0.0682 | real | 50.892 |
| 0.0384 | real | 51.808 |
| 0.0128 | real | 52.725 |
| 0.0085 | real | 53.642 |
| 0.0085 | real | 54.558 |
| 0.0085 | real | 55.475 |
| 0 | real | 56.392 |
| 0 | real | 57.308 |
| 0 | real | 58.225 |
| 0.0043 | real | 59.142 |
| 0.0027 | synthetic | 32.558 |
| 0.0027 | synthetic | 33.475 |
| 0.0136 | synthetic | 34.392 |
| 0.0082 | synthetic | 35.308 |
| 0.0109 | synthetic | 36.225 |
| 0.0164 | synthetic | 37.142 |
| 0.0218 | synthetic | 38.058 |
| 0.0573 | synthetic | 38.975 |
| 0.0545 | synthetic | 39.892 |
| 0.0355 | synthetic | 40.808 |
| 0.0791 | synthetic | 41.725 |
| 0.0873 | synthetic | 42.642 |
| 0.0900 | synthetic | 43.558 |
| 0.0873 | synthetic | 44.475 |
| 0.0736 | synthetic | 45.392 |
| 0.0764 | synthetic | 46.308 |
| 0.0982 | synthetic | 47.225 |
| 0.0682 | synthetic | 48.142 |
| 0.0627 | synthetic | 49.058 |
| 0.0436 | synthetic | 49.975 |
| 0.0245 | synthetic | 50.892 |
| 0.0273 | synthetic | 51.808 |
| 0.0164 | synthetic | 52.725 |
| 0.0082 | synthetic | 53.642 |
| 0.0136 | synthetic | 54.558 |
| 0.0027 | synthetic | 55.475 |
| 0.0027 | synthetic | 56.392 |
| 0.0027 | synthetic | 57.308 |
| 0 | synthetic | 58.225 |
| 0.0027 | synthetic | 59.142 |
View data
| Density | Source | bill_dep |
|---|---|---|
| 0.0424 | real | 13.338 |
| 0.0847 | real | 13.615 |
| 0.1271 | real | 13.892 |
| 0.1412 | real | 14.168 |
| 0.1271 | real | 14.445 |
| 0.1271 | real | 14.722 |
| 0.1412 | real | 14.998 |
| 0.0988 | real | 15.275 |
| 0.0565 | real | 15.552 |
| 0.1553 | real | 15.828 |
| 0.0988 | real | 16.105 |
| 0.1271 | real | 16.382 |
| 0.0847 | real | 16.658 |
| 0.2118 | real | 16.935 |
| 0.2400 | real | 17.212 |
| 0.1412 | real | 17.488 |
| 0.2118 | real | 17.765 |
| 0.1412 | real | 18.042 |
| 0.1271 | real | 18.318 |
| 0.2683 | real | 18.595 |
| 0.2824 | real | 18.872 |
| 0.0847 | real | 19.148 |
| 0.1130 | real | 19.425 |
| 0.0988 | real | 19.702 |
| 0.1130 | real | 19.978 |
| 0.0565 | real | 20.255 |
| 0.0141 | real | 20.532 |
| 0.0282 | real | 20.808 |
| 0.0565 | real | 21.085 |
| 0.0141 | real | 21.362 |
| 0.0542 | synthetic | 13.338 |
| 0.0090 | synthetic | 13.615 |
| 0.0361 | synthetic | 13.892 |
| 0.0181 | synthetic | 14.168 |
| 0.0271 | synthetic | 14.445 |
| 0.0813 | synthetic | 14.722 |
| 0.1175 | synthetic | 14.998 |
| 0.1446 | synthetic | 15.275 |
| 0.1807 | synthetic | 15.552 |
| 0.1807 | synthetic | 15.828 |
| 0.1627 | synthetic | 16.105 |
| 0.1717 | synthetic | 16.382 |
| 0.1627 | synthetic | 16.658 |
| 0.1717 | synthetic | 16.935 |
| 0.2440 | synthetic | 17.212 |
| 0.3072 | synthetic | 17.488 |
| 0.2982 | synthetic | 17.765 |
| 0.2169 | synthetic | 18.042 |
| 0.1807 | synthetic | 18.318 |
| 0.2530 | synthetic | 18.595 |
| 0.1717 | synthetic | 18.872 |
| 0.0904 | synthetic | 19.148 |
| 0.0813 | synthetic | 19.425 |
| 0.0723 | synthetic | 19.702 |
| 0.0452 | synthetic | 19.978 |
| 0.0090 | synthetic | 20.255 |
| 0.0542 | synthetic | 20.532 |
| 0.0181 | synthetic | 20.808 |
| 0.0271 | synthetic | 21.085 |
| 0.0271 | synthetic | 21.362 |
View data
| Density | Source | flipper_len |
|---|---|---|
| 0.0020 | real | 172.98 |
| 0.0020 | real | 174.95 |
| 0.0020 | real | 176.92 |
| 0.0060 | real | 178.88 |
| 0.0159 | real | 180.85 |
| 0.0099 | real | 182.82 |
| 0.0238 | real | 184.78 |
| 0.0258 | real | 186.75 |
| 0.0179 | real | 188.72 |
| 0.0616 | real | 190.68 |
| 0.0218 | real | 192.65 |
| 0.0358 | real | 194.62 |
| 0.0278 | real | 196.58 |
| 0.0258 | real | 198.55 |
| 0.0139 | real | 200.52 |
| 0.0119 | real | 202.48 |
| 0.0060 | real | 204.45 |
| 0.0060 | real | 206.42 |
| 0.0179 | real | 208.38 |
| 0.0218 | real | 210.35 |
| 0.0218 | real | 212.32 |
| 0.0278 | real | 214.28 |
| 0.0199 | real | 216.25 |
| 0.0179 | real | 218.22 |
| 0.0199 | real | 220.18 |
| 0.0079 | real | 222.15 |
| 0.0119 | real | 224.12 |
| 0.0020 | real | 226.08 |
| 0.0119 | real | 228.05 |
| 0.0119 | real | 230.02 |
| 0 | synthetic | 172.98 |
| 0.0025 | synthetic | 174.95 |
| 0.0013 | synthetic | 176.92 |
| 0.0013 | synthetic | 178.88 |
| 0.0089 | synthetic | 180.85 |
| 0.0140 | synthetic | 182.82 |
| 0.0114 | synthetic | 184.78 |
| 0.0127 | synthetic | 186.75 |
| 0.0216 | synthetic | 188.72 |
| 0.0254 | synthetic | 190.68 |
| 0.0305 | synthetic | 192.65 |
| 0.0343 | synthetic | 194.62 |
| 0.0356 | synthetic | 196.58 |
| 0.0343 | synthetic | 198.55 |
| 0.0369 | synthetic | 200.52 |
| 0.0331 | synthetic | 202.48 |
| 0.0432 | synthetic | 204.45 |
| 0.0254 | synthetic | 206.42 |
| 0.0280 | synthetic | 208.38 |
| 0.0280 | synthetic | 210.35 |
| 0.0140 | synthetic | 212.32 |
| 0.0102 | synthetic | 214.28 |
| 0.0153 | synthetic | 216.25 |
| 0.0064 | synthetic | 218.22 |
| 0.0076 | synthetic | 220.18 |
| 0.0076 | synthetic | 222.15 |
| 0.0051 | synthetic | 224.12 |
| 0.0051 | synthetic | 226.08 |
| 0.0064 | synthetic | 228.05 |
| 0.0025 | synthetic | 230.02 |
View data
| Density | Source | body_mass |
|---|---|---|
| 3.498e-5 | real | 2755.83 |
| 0.0001 | real | 2867.50 |
| 6.996e-5 | real | 2979.17 |
| 0.0002 | real | 3090.83 |
| 0.0005 | real | 3202.50 |
| 0.0003 | real | 3314.17 |
| 0.0006 | real | 3425.83 |
| 0.0005 | real | 3537.50 |
| 0.0007 | real | 3649.17 |
| 0.0005 | real | 3760.83 |
| 0.0004 | real | 3872.50 |
| 0.0005 | real | 3984.17 |
| 0.0005 | real | 4095.83 |
| 0.0003 | real | 4207.50 |
| 0.0003 | real | 4319.17 |
| 0.0004 | real | 4430.83 |
| 0.0001 | real | 4542.50 |
| 0.0006 | real | 4654.17 |
| 0.0003 | real | 4765.83 |
| 0.0003 | real | 4877.50 |
| 0.0002 | real | 4989.17 |
| 0.0003 | real | 5100.83 |
| 0.0001 | real | 5212.50 |
| 0.0002 | real | 5324.17 |
| 0.0001 | real | 5435.83 |
| 0.0005 | real | 5547.50 |
| 0.0002 | real | 5659.17 |
| 6.996e-5 | real | 5770.83 |
| 3.498e-5 | real | 5882.50 |
| 0.0001 | real | 5994.17 |
| 4.478e-5 | synthetic | 2755.83 |
| 6.716e-5 | synthetic | 2867.50 |
| 4.478e-5 | synthetic | 2979.17 |
| 8.955e-5 | synthetic | 3090.83 |
| 0.0002 | synthetic | 3202.50 |
| 0.0002 | synthetic | 3314.17 |
| 0.0005 | synthetic | 3425.83 |
| 0.0004 | synthetic | 3537.50 |
| 0.0005 | synthetic | 3649.17 |
| 0.0006 | synthetic | 3760.83 |
| 0.0007 | synthetic | 3872.50 |
| 0.0006 | synthetic | 3984.17 |
| 0.0006 | synthetic | 4095.83 |
| 0.0006 | synthetic | 4207.50 |
| 0.0004 | synthetic | 4319.17 |
| 0.0006 | synthetic | 4430.83 |
| 0.0005 | synthetic | 4542.50 |
| 0.0004 | synthetic | 4654.17 |
| 0.0004 | synthetic | 4765.83 |
| 0.0005 | synthetic | 4877.50 |
| 0.0003 | synthetic | 4989.17 |
| 0.0002 | synthetic | 5100.83 |
| 0.0002 | synthetic | 5212.50 |
| 8.955e-5 | synthetic | 5324.17 |
| 6.716e-5 | synthetic | 5435.83 |
| 8.955e-5 | synthetic | 5547.50 |
| 2.239e-5 | synthetic | 5659.17 |
| 2.239e-5 | synthetic | 5770.83 |
| 4.478e-5 | synthetic | 5882.50 |
| 0 | synthetic | 5994.17 |
View data
| species | Share | Source |
|---|---|---|
| Adelie | 0.4419 | real |
| Chinstrap | 0.1899 | real |
| Gentoo | 0.3682 | real |
| Adelie | 0.3900 | synthetic |
| Chinstrap | 0.2900 | synthetic |
| Gentoo | 0.3200 | synthetic |
View data
| island | Share | Source |
|---|---|---|
| Biscoe | 0.4806 | real |
| Dream | 0.3643 | real |
| Torgersen | 0.1550 | real |
| Biscoe | 0.4900 | synthetic |
| Dream | 0.3150 | synthetic |
| Torgersen | 0.1950 | synthetic |
View data
| sex | Share | Source |
|---|---|---|
| female | 0.4940 | real |
| male | 0.5060 | real |
| female | 0.4600 | synthetic |
| male | 0.5400 | synthetic |
View data
| Column | Column | Difference |
|---|---|---|
| bill_len | bill_len | 0 |
| bill_dep | bill_len | −0.1320 |
| flipper_len | bill_len | 0.5396 |
| body_mass | bill_len | 0.3186 |
| bill_len | bill_dep | −0.1320 |
| bill_dep | bill_dep | 0 |
| flipper_len | bill_dep | −0.4290 |
| body_mass | bill_dep | −0.3303 |
| bill_len | flipper_len | 0.5396 |
| bill_dep | flipper_len | −0.4290 |
| flipper_len | flipper_len | 0 |
| body_mass | flipper_len | 0.6928 |
| bill_len | body_mass | 0.3186 |
| bill_dep | body_mass | −0.3303 |
| flipper_len | body_mass | 0.6928 |
| body_mass | body_mass | 0 |
In the flow's coordinates (standardized numbers, dequantized categories); lower is better.
View data
| Part | Negative log-likelihood (nats per row) | Epoch |
|---|---|---|
| training rows | 14.728 | 1 |
| training rows | 14.432 | 2 |
| training rows | 14.150 | 3 |
| training rows | 13.778 | 4 |
| training rows | 13.509 | 5 |
| training rows | 13.199 | 6 |
| training rows | 12.907 | 7 |
| training rows | 12.576 | 8 |
| training rows | 12.314 | 9 |
| training rows | 12.033 | 10 |
| training rows | 11.749 | 11 |
| training rows | 11.439 | 12 |
| training rows | 11.128 | 13 |
| training rows | 10.919 | 14 |
| training rows | 10.759 | 15 |
| training rows | 10.484 | 16 |
| training rows | 10.301 | 17 |
| training rows | 10.079 | 18 |
| training rows | 9.948 | 19 |
| training rows | 9.740 | 20 |
Assumptions
- Enough rows for a neural generator — 251 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 negative log-likelihood over the last 10% of epochs averaged 9.84 nats per row.
- Held-out rows are about as likely as training rows — Mean log-likelihood -21.4 nats per training row and -22.1 per held-out row.
- 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.141 (mean Kolmogorov–Smirnov distance); categories 0.061 (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
| Column | Kind | Real | Synthetic | Distance | Measure |
|---|---|---|---|---|---|
| species | categorical | Adelie 44.2% | Adelie 39.0% | 0.1001 | total variation |
| island | categorical | Biscoe 48.1% | Biscoe 49.0% | 0.0493 | total variation |
| bill_len | numeric | 43.96 ± 5.5 | 44.78 ± 4.45 | 0.1859 | Kolmogorov–Smirnov D |
| bill_dep | numeric | 17.14 ± 1.98 | 17.26 ± 1.61 | 0.1288 | Kolmogorov–Smirnov D |
| flipper_len | numeric | 201.3 ± 14.2 | 201.1 ± 11.1 | 0.1433 | Kolmogorov–Smirnov D |
| body_mass | numeric | 4219 ± 791 | 4173 ± 608 | 0.1052 | Kolmogorov–Smirnov D |
| sex | categorical | male 50.6% | male 54.0% | 0.0340 | total variation |
- 86 of 344 rows (25%) were held out of training so privacy and utility can be checked against rows the generator never saw.
- Categories are smoothed with uniform noise (dequantization), so the log-likelihoods are lower bounds for the category part.
The exact R script · R R version 4.5.1 (2025-06-13)
# Synthetic data — normalizing flow (RealNVP, NICE, MAF, Glow, spline)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method synth.flow 1.1.1 · spec f559f5efe6b30ed0
# Dataset: ml_penguins (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("species", "island", "bill_len", "bill_dep", "flipper_len", "body_mass", "sex")
KINDS <- list(
species = "categorical",
island = "categorical",
bill_len = "numeric",
bill_dep = "numeric",
flipper_len = "numeric",
body_mass = "numeric",
sex = "categorical"
)
LEVELS <- list(
species = c("Adelie", "Chinstrap", "Gentoo"),
island = c("Biscoe", "Dream", "Torgersen"),
sex = c("female", "male")
)
SEED <- 42
loaded <- cs_synth_load("tests/parity/fixtures/ml_penguins.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.25, rng)
train_rows <- sp$train; holdout_rows <- sp$holdout
train <- lapply(cols, cs_synth_take, rows = train_rows)
N_OUT <- 400L
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.flow/penguins_maf/out-r")
# 3 maf layers map standardized numbers and dequantized one-hot categories to N(0, I);
# the exact log-likelihood is the training loss. Twin of codesplash.synth.flows.fit_flow (written from the papers).
HIDDEN <- as.integer(unlist(c(16)))
holdout_cols <- if (length(holdout_rows)) lapply(cols, cs_synth_take, rows = holdout_rows) else NULL
fit <- cs_synth_flow(
train, N_OUT, HIDDEN,
kind = "maf",
layers = as.integer(3),
epochs = as.integer(20),
batch_size = 64,
lr = 0.001,
seed = SEED,
holdout = holdout_cols,
bins = as.integer(8), # spline flows only
tail_bound = 3
)
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))
)
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$dims <- fit$facts$dims
fit_values$final_loss <- mean(history$loss[tail_rows])
fit_values$train_loglik <- fit$facts$train_loglik
if (fit$facts$n_holdout_ll > 0) {
fit_values$holdout_loglik <- fit$facts$holdout_loglik
fit_values$n_holdout_ll <- fit$facts$n_holdout_ll
}
model_note <- " with a normalizing flow"
ne <- nrow(history)
extra_charts[[length(extra_charts) + 1L]] <- cs_chart("training", "training-components", "Negative log-likelihood by epoch", list(
x = cs_col("Epoch", history$epoch, "numeric"),
value = cs_col("Negative log-likelihood (nats per row)", history$loss, "numeric"),
component = cs_col("Part", rep("training rows", ne), "categorical", levels = c("training rows"))
), note = "In the flow's coordinates (standardized numbers, dequantized categories); lower is better.")
finite <- all(is.finite(history$loss))
assumptions[[length(assumptions) + 1L]] <- list(
key = "training_stable", label = "Training stayed finite",
status = if (finite) "pass" else "fail",
detail = if (finite) sprintf("The negative log-likelihood over the last 10%% of epochs averaged %s nats per row.", format(signif(fit_values$final_loss, 3)))
else "The loss became infinite or undefined; lower the learning rate or use fewer layers."
)
if (fit$facts$n_holdout_ll > 0) {
gap <- fit$facts$train_loglik - fit$facts$holdout_loglik
ok <- isTRUE(gap <= 1)
assumptions[[length(assumptions) + 1L]] <- list(
key = "generalizes", label = "Held-out rows are about as likely as training rows",
status = if (ok) "pass" else "warn",
detail = paste0(sprintf("Mean log-likelihood %s nats per training row and %s per held-out row",
format(signif(fit$facts$train_loglik, 3)), format(signif(fit$facts$holdout_loglik, 3))),
if (ok) "." else " — training rows are far more likely, so the flow is memorizing them; use fewer epochs or layers.")
)
} else {
assumptions[[length(assumptions) + 1L]] <- list(
key = "generalizes", label = "Held-out rows are about as likely as training rows", status = "info",
detail = "No complete rows were held out, so generalization can't be checked; set a holdout share to compare."
)
}
if (isTRUE(fit$facts$dequantized)) {
warnings <- c(warnings, "Categories are smoothed with uniform noise (dequantization), so the log-likelihoods are lower bounds for the category part.")
}
synth <- cs_synth_add_missing(synth, train, rng, "none") # each column's missing share, at random
# %% Write and compare
out <- cs_ml_out_dir("target/academy-parity/run-8142/synth.flow/penguins_maf/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 — normalizing flow (RealNVP, NICE, MAF, Glow, spline)",
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 = 400,
flow = "maf",
bins = 8,
tail_bound = 3,
layers = 3,
hidden_layers = c(16),
epochs = 20,
batch_size = 64,
learning_rate = 0.001,
missing = "none",
holdout = 0.25,
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
))
))
400 synthetic rows over 7 columns from 258 training rows with a normalizing flow. Numeric columns differ from the data by a mean Kolmogorov–Smirnov distance of 0.141 and categories by a mean total variation of 0.061.
- Synthetic rows
- 400
- Mean KS distance
- 0.1408
- Mean TV distance
- 0.0611
- 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 — 251 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 negative log-likelihood over the last 10% of epochs averaged 9.84 nats per row.
- Held-out rows are about as likely as training rows — Mean log-likelihood -21.4 nats per training row and -22.1 per held-out row.
- 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.141 (mean Kolmogorov–Smirnov distance); categories 0.061 (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
| Column | Kind | Real | Synthetic | Distance | Measure |
|---|---|---|---|---|---|
| species | categorical | Adelie 44.2% | Adelie 39.0% | 0.1001 | total variation |
| island | categorical | Biscoe 48.1% | Biscoe 49.0% | 0.0493 | total variation |
| bill_len | numeric | 43.96 ± 5.5 | 44.78 ± 4.45 | 0.1859 | Kolmogorov–Smirnov D |
| bill_dep | numeric | 17.14 ± 1.98 | 17.26 ± 1.61 | 0.1288 | Kolmogorov–Smirnov D |
| flipper_len | numeric | 201.3 ± 14.2 | 201.1 ± 11.1 | 0.1433 | Kolmogorov–Smirnov D |
| body_mass | numeric | 4219 ± 791 | 4173 ± 608 | 0.1052 | Kolmogorov–Smirnov D |
| sex | categorical | male 50.6% | male 54.0% | 0.0340 | total variation |
- 86 of 344 rows (25%) were held out of training so privacy and utility can be checked against rows the generator never saw.
- Categories are smoothed with uniform noise (dequantization), so the log-likelihoods are lower bounds for the category part.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Synthetic data — normalizing flow (RealNVP, NICE, MAF, Glow, spline)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method synth.flow 1.1.1 · spec f559f5efe6b30ed0
# Dataset: ml_penguins (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 flows # twin of codesplashr::cs_synth_flow (RealNVP, NICE, MAF, Glow, spline flows; written from the papers)
# %% Data
COLUMNS = ["species", "island", "bill_len", "bill_dep", "flipper_len", "body_mass", "sex"]
KINDS = {
"species": "categorical",
"island": "categorical",
"bill_len": "numeric",
"bill_dep": "numeric",
"flipper_len": "numeric",
"body_mass": "numeric",
"sex": "categorical",
}
LEVELS = {
"species": ["Adelie", "Chinstrap", "Gentoo"],
"island": ["Biscoe", "Dream", "Torgersen"],
"sex": ["female", "male"],
}
SEED = 42
cols, n_input = sy.load("tests/parity/fixtures/ml_penguins.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.25, rng)
train = [c.take(train_rows) for c in cols]
N_OUT = 400 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.flow/penguins_maf/out-python",
)
# 3 maf layers map standardized numbers and dequantized one-hot categories to N(0, I);
# the exact log-likelihood is the training loss, and running the flow backwards turns noise into rows.
HIDDEN = [int(u) for u in [16]]
holdout_cols = [c.take(holdout_rows) for c in cols] if len(holdout_rows) else None
synth, facts, hist = flows.fit_flow(
train, N_OUT, HIDDEN,
kind="maf",
layers=3,
epochs=20,
batch_size=64,
lr=0.001,
seed=SEED,
holdout=holdout_cols,
bins=8, # spline flows only
tail_bound=3,
)
history = pd.DataFrame(hist)
last = max(1, len(hist) // 10) # the last 10% of epochs
fit_values["batch_size"] = facts["batch_size"]
fit_values["dims"] = facts["dims"]
fit_values["final_loss"] = float(np.mean([h["loss"] for h in hist[-last:]]))
fit_values["train_loglik"] = facts["train_loglik"]
if facts["n_holdout_ll"] > 0:
fit_values["holdout_loglik"] = facts["holdout_loglik"]
fit_values["n_holdout_ll"] = facts["n_holdout_ll"]
model_note = " with a normalizing flow"
ep = history["epoch"].tolist()
extra_charts.append(cs.chart("training", "training-components", "Negative log-likelihood by epoch", {
"x": cs.col("Epoch", ep, "numeric"),
"value": cs.col("Negative log-likelihood (nats per row)", history["loss"].tolist(), "numeric"),
"component": cs.col("Part", ["training rows"] * len(ep), "categorical", levels=["training rows"]),
}, note="In the flow's coordinates (standardized numbers, dequantized categories); lower is better."))
finite = bool(np.all(np.isfinite(history["loss"].to_numpy())))
assumptions.append({
"key": "training_stable",
"label": "Training stayed finite",
"status": "pass" if finite else "fail",
"detail": f"The negative log-likelihood over the last 10% of epochs averaged {fit_values['final_loss']:.3g} nats per row." if finite else "The loss became infinite or undefined; lower the learning rate or use fewer layers.",
})
if facts["n_holdout_ll"] > 0:
gap = facts["train_loglik"] - facts["holdout_loglik"]
assumptions.append({
"key": "generalizes",
"label": "Held-out rows are about as likely as training rows",
"status": "warn" if not gap <= 1.0 else "pass",
"detail": f"Mean log-likelihood {facts['train_loglik']:.3g} nats per training row and {facts['holdout_loglik']:.3g} per held-out row"
+ (" — training rows are far more likely, so the flow is memorizing them; use fewer epochs or layers." if not gap <= 1.0 else "."),
})
else:
assumptions.append({
"key": "generalizes",
"label": "Held-out rows are about as likely as training rows",
"status": "info",
"detail": "No complete rows were held out, so generalization can't be checked; set a holdout share to compare.",
})
if facts["dequantized"]:
warnings.append("Categories are smoothed with uniform noise (dequantization), so the log-likelihoods are lower bounds for the category part.")
sy.add_missing(synth, train, rng, "none") # each column's missing share, at random
# %% Write and compare
out = out_dir("target/academy-parity/run-8142/synth.flow/penguins_maf/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 — normalizing flow (RealNVP, NICE, MAF, Glow, spline)",
"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": 400,
"flow": "maf",
"bins": 8,
"tail_bound": 3,
"layers": 3,
"hidden_layers": [16],
"epochs": 20,
"batch_size": 64,
"learning_rate": 0.001,
"missing": "none",
"holdout": 0.25,
"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,
}},
})
What runs here
ReadCheck: flexible flows
CheckpointCheck yourself
Why does Glow keep its mixing matrix as P·L·U?
Show the answer
Answer: a
With P a permutation and L unit lower-triangular, only U's diagonal contributes to the determinant.
Check yourself
What does Glow's actnorm do?
Show the answer
Answer: b
Actnorm is initialized so the first batch's outputs have mean 0 and SD 1, then trained like any other parameter. Mixing is the next step.
Check yourself
For a masked autoregressive flow over many columns, which is fast and which is slow?
Show the answer
Answer: a
All conditionals are computed together from the known row when scoring. When sampling, each column needs the ones before it first.
Check yourself
You reorder a table's columns before fitting a MAF. What can change?
Show the answer
Answer: b
An autoregressive model's order is a modeling choice. With finite capacity, some orders fit better than others.
Check yourself
Why must a spline flow's curves be monotone?
Show the answer
Answer: a
Invertibility is what makes a flow a flow. A curve that rose and fell would map two inputs to one output.
Check yourself
How should you choose between Real NVP, Glow, MAF and a spline flow for one table?
Show the answer
Answer: b
On the same rows with the same dequantization, held-out log-likelihoods are comparable. Training values reward memorizing.
Recap
Recap- Glow adds actnorm and a learned invertible mixing kept as P·L·U.
- A MAF conditions each column on earlier ones: one-pass scoring, column-by-column sampling, order matters.
- Spline flows bend columns with monotone curves, invertible by construction.
- Compare flows by held-out log-likelihood on the same columns; all three run in
synth.flow.
Concepts in this lesson