Normalizing flows: invertible layers and an exact likelihood
A flow is a stack of invertible layers from data to noise. The change-of-variables formula gives an exact log-likelihood, and coupling layers keep it cheap. Build NICE and Real NVP couplings and read a flow's held-out likelihood.
What runs in CodeSplash
- DNN051Nonlinear Independent Components Estimation (NICE) Runs in CodeSplash (Experimental)
- DNN052Real-valued non-volume-preserving flow (Real NVP) Runs in CodeSplash (Experimental)
- Synthetic data — normalizing flow (RealNVP, NICE, MAF, Glow, spline) Experimental
You will be able to
- Apply the change-of-variables formula and say why the log-determinant must be cheap
- Build an additive (NICE) and an affine (Real NVP) coupling and invert each
- Use training and held-out log-likelihoods to spot memorizing
- Say why a high likelihood doesn't flag a row as typical
Invertible all the way
ReadA normalizing flowNormalizing flowA stack of invertible layers that turns each row into normal noise, so noise run backwards gives new rows and likelihoods are exact. is a stack of invertible layers that turns a row into noise with a simple density, usually a standard normal. Run it backwards and noise becomes a row.
Because every layer can be undone, the density of is exact, by the change of variablesChange of variablesThe rule that a density stretched by an invertible map is divided by how much the map stretches volume there.:
The second term accounts for how much the layer stretches or squeezes space near . For a general Jacobian it costs on the order of . Flows are designed so it is nearly free.
Coupling layers
ReadA coupling layerAffine coupling layerA flow layer that scales and shifts half the columns using a small network of the other half; RealNVP stacks them. splits the columns in two halves. The first half passes through unchanged and is used to transform the second:
- NICE (additive): . The Jacobian is triangular with ones on the diagonal, so the log-determinant is exactly 0: volume is preserved.
- Real NVP (affine): . The log-determinant is , a plain sum.
and can be any networks, since they are never inverted. To invert, recompute them from and undo the shift and scale. Alternating which half passes through lets every column be transformed.
Stack coupling layers and check that the density still adds up to one.
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.
Both couplings by hand
ReadIn the reference's NICE example, a two-column row's second value moves to −0.036, the inverse recovers it exactly, and the log-determinant is 0.0. The Real NVP example scales as well as shifts; its log-determinant is 0.114.
import numpy as np
x = np.array([.4, -.7])
s, t = .3 * np.tanh(x[0]), .2 * x[0] # computed from the half that passes through
y = np.array([x[0], x[1] * np.exp(s) + t]) # affine coupling (Real NVP)
back = np.array([y[0], (y[1] - .2 * y[0]) * np.exp(-.3 * np.tanh(y[0]))])
print(y, back, "log det", s)x <- c(.4, -.7)
s <- .3 * tanh(x[1]); t <- .2 * x[1] # computed from the half that passes through
y <- c(x[1], x[2] * exp(s) + t) # affine coupling (Real NVP)
back <- c(y[1], (y[2] - .2 * y[1]) * exp(-.3 * tanh(y[1])))
print(c(y, back, logdet = s))A NICE flow on iris
Explore200 synthetic rows over 4 columns from 150 training rows with a normalizing flow. Numeric columns differ from the data by a mean Kolmogorov–Smirnov distance of 0.144.
- Synthetic rows
- 200
- Mean KS distance
- 0.1442
- Mean TV distance
- —
- Rows copied from the data
- 0
Plots
View data
| Density | Source | sepal_length |
|---|---|---|
| 0.2222 | real | 4.360 |
| 0.0556 | real | 4.480 |
| 0.2222 | real | 4.600 |
| 0.1111 | real | 4.720 |
| 0.2778 | real | 4.840 |
| 0.8889 | real | 4.960 |
| 0.5000 | real | 5.080 |
| 0.2222 | real | 5.200 |
| 0.0556 | real | 5.320 |
| 0.3333 | real | 5.440 |
| 0.7222 | real | 5.560 |
| 0.4444 | real | 5.680 |
| 0.3889 | real | 5.800 |
| 0.1667 | real | 5.920 |
| 0.6667 | real | 6.040 |
| 0.2222 | real | 6.160 |
| 0.5000 | real | 6.280 |
| 0.3889 | real | 6.400 |
| 0.2778 | real | 6.520 |
| 0.1111 | real | 6.640 |
| 0.6111 | real | 6.760 |
| 0.2222 | real | 6.880 |
| 0.0556 | real | 7 |
| 0.0556 | real | 7.120 |
| 0.2222 | real | 7.240 |
| 0.0556 | real | 7.360 |
| 0 | real | 7.480 |
| 0.0556 | real | 7.600 |
| 0.2222 | real | 7.720 |
| 0.0556 | real | 7.840 |
| 0.8333 | synthetic | 4.360 |
| 0.1667 | synthetic | 4.480 |
| 0.1250 | synthetic | 4.600 |
| 0.2917 | synthetic | 4.720 |
| 0.1667 | synthetic | 4.840 |
| 0.1250 | synthetic | 4.960 |
| 0.0417 | synthetic | 5.080 |
| 0.1250 | synthetic | 5.200 |
| 0.1667 | synthetic | 5.320 |
| 0.6250 | synthetic | 5.440 |
| 0.3333 | synthetic | 5.560 |
| 0.2083 | synthetic | 5.680 |
| 0.3333 | synthetic | 5.800 |
| 0.2500 | synthetic | 5.920 |
| 0.4167 | synthetic | 6.040 |
| 0.6667 | synthetic | 6.160 |
| 0.2917 | synthetic | 6.280 |
| 0.4583 | synthetic | 6.400 |
| 0.2917 | synthetic | 6.520 |
| 0.3750 | synthetic | 6.640 |
| 0.3750 | synthetic | 6.760 |
| 0.3333 | synthetic | 6.880 |
| 0.1250 | synthetic | 7 |
| 0.0833 | synthetic | 7.120 |
| 0.2500 | synthetic | 7.240 |
| 0.0417 | synthetic | 7.360 |
| 0.1250 | synthetic | 7.480 |
| 0.0417 | synthetic | 7.600 |
| 0.0833 | synthetic | 7.720 |
| 0.5833 | synthetic | 7.840 |
View data
| Density | Source | sepal_width |
|---|---|---|
| 0.0833 | real | 2.040 |
| 0 | real | 2.120 |
| 0.2500 | real | 2.200 |
| 0.3333 | real | 2.280 |
| 0.2500 | real | 2.360 |
| 0 | real | 2.440 |
| 0.6667 | real | 2.520 |
| 0.4167 | real | 2.600 |
| 0.7500 | real | 2.680 |
| 1.167 | real | 2.760 |
| 0 | real | 2.840 |
| 0.8333 | real | 2.920 |
| 2.167 | real | 3 |
| 0.9167 | real | 3.080 |
| 0 | real | 3.160 |
| 1.083 | real | 3.240 |
| 0.5000 | real | 3.320 |
| 1 | real | 3.400 |
| 0.5000 | real | 3.480 |
| 0.3333 | real | 3.560 |
| 0 | real | 3.640 |
| 0.2500 | real | 3.720 |
| 0.5000 | real | 3.800 |
| 0.1667 | real | 3.880 |
| 0.0833 | real | 3.960 |
| 0 | real | 4.040 |
| 0.0833 | real | 4.120 |
| 0.0833 | real | 4.200 |
| 0 | real | 4.280 |
| 0.0833 | real | 4.360 |
| 0.4375 | synthetic | 2.040 |
| 0.1875 | synthetic | 2.120 |
| 0.1875 | synthetic | 2.200 |
| 0.1875 | synthetic | 2.280 |
| 0.1875 | synthetic | 2.360 |
| 0.1875 | synthetic | 2.440 |
| 0.5000 | synthetic | 2.520 |
| 0.3125 | synthetic | 2.600 |
| 0.7500 | synthetic | 2.680 |
| 0.3750 | synthetic | 2.760 |
| 1.313 | synthetic | 2.840 |
| 0.9375 | synthetic | 2.920 |
| 0.8125 | synthetic | 3 |
| 0.8125 | synthetic | 3.080 |
| 0.7500 | synthetic | 3.160 |
| 0.2500 | synthetic | 3.240 |
| 0.5000 | synthetic | 3.320 |
| 0.5625 | synthetic | 3.400 |
| 0.3750 | synthetic | 3.480 |
| 0.5625 | synthetic | 3.560 |
| 0.7500 | synthetic | 3.640 |
| 0.1875 | synthetic | 3.720 |
| 0.4375 | synthetic | 3.800 |
| 0.1250 | synthetic | 3.880 |
| 0.1875 | synthetic | 3.960 |
| 0.1875 | synthetic | 4.040 |
| 0 | synthetic | 4.120 |
| 0 | synthetic | 4.200 |
| 0 | synthetic | 4.280 |
| 0.4375 | synthetic | 4.360 |
View data
| Density | Source | petal_length |
|---|---|---|
| 0.0678 | real | 1.098 |
| 0.3051 | real | 1.295 |
| 0.8814 | real | 1.492 |
| 0.3729 | real | 1.688 |
| 0.0678 | real | 1.885 |
| 0 | real | 2.082 |
| 0 | real | 2.278 |
| 0 | real | 2.475 |
| 0 | real | 2.672 |
| 0 | real | 2.868 |
| 0.0339 | real | 3.065 |
| 0.0678 | real | 3.262 |
| 0.0678 | real | 3.458 |
| 0.0678 | real | 3.655 |
| 0.1356 | real | 3.852 |
| 0.2712 | real | 4.048 |
| 0.2034 | real | 4.245 |
| 0.4068 | real | 4.442 |
| 0.2712 | real | 4.638 |
| 0.3051 | real | 4.835 |
| 0.4068 | real | 5.032 |
| 0.1356 | real | 5.228 |
| 0.1695 | real | 5.425 |
| 0.3051 | real | 5.622 |
| 0.1695 | real | 5.818 |
| 0.1695 | real | 6.015 |
| 0.0339 | real | 6.212 |
| 0.0339 | real | 6.408 |
| 0.1017 | real | 6.605 |
| 0.0339 | real | 6.802 |
| 0.9153 | synthetic | 1.098 |
| 0.0508 | synthetic | 1.295 |
| 0.1017 | synthetic | 1.492 |
| 0.0254 | synthetic | 1.688 |
| 0.0254 | synthetic | 1.885 |
| 0.1017 | synthetic | 2.082 |
| 0 | synthetic | 2.278 |
| 0.0254 | synthetic | 2.475 |
| 0.1271 | synthetic | 2.672 |
| 0.0254 | synthetic | 2.868 |
| 0.1780 | synthetic | 3.065 |
| 0.1271 | synthetic | 3.262 |
| 0.1271 | synthetic | 3.458 |
| 0.0763 | synthetic | 3.655 |
| 0.2288 | synthetic | 3.852 |
| 0.2034 | synthetic | 4.048 |
| 0.2797 | synthetic | 4.245 |
| 0.1525 | synthetic | 4.442 |
| 0.2542 | synthetic | 4.638 |
| 0.2542 | synthetic | 4.835 |
| 0.1017 | synthetic | 5.032 |
| 0.1271 | synthetic | 5.228 |
| 0.1525 | synthetic | 5.425 |
| 0.2034 | synthetic | 5.622 |
| 0.1525 | synthetic | 5.818 |
| 0.2034 | synthetic | 6.015 |
| 0.2034 | synthetic | 6.212 |
| 0.0763 | synthetic | 6.408 |
| 0.0763 | synthetic | 6.605 |
| 0.5085 | synthetic | 6.802 |
View data
| Density | Source | petal_width |
|---|---|---|
| 0.4167 | real | 0.1400 |
| 2.417 | real | 0.2200 |
| 0.5833 | real | 0.3000 |
| 0.5833 | real | 0.3800 |
| 0 | real | 0.4600 |
| 0.0833 | real | 0.5400 |
| 0.0833 | real | 0.6200 |
| 0 | real | 0.7000 |
| 0 | real | 0.7800 |
| 0 | real | 0.8600 |
| 0 | real | 0.9400 |
| 0.5833 | real | 1.020 |
| 0.2500 | real | 1.100 |
| 0.4167 | real | 1.180 |
| 0 | real | 1.260 |
| 1.083 | real | 1.340 |
| 0.6667 | real | 1.420 |
| 1 | real | 1.500 |
| 0.3333 | real | 1.580 |
| 0.1667 | real | 1.660 |
| 0 | real | 1.740 |
| 1 | real | 1.820 |
| 0.4167 | real | 1.900 |
| 0.5000 | real | 1.980 |
| 0 | real | 2.060 |
| 0.5000 | real | 2.140 |
| 0.2500 | real | 2.220 |
| 0.6667 | real | 2.300 |
| 0.2500 | real | 2.380 |
| 0.2500 | real | 2.460 |
| 2 | synthetic | 0.1400 |
| 0.2500 | synthetic | 0.2200 |
| 0.1250 | synthetic | 0.3000 |
| 0 | synthetic | 0.3800 |
| 0.3125 | synthetic | 0.4600 |
| 0.0625 | synthetic | 0.5400 |
| 0.0625 | synthetic | 0.6200 |
| 0.2500 | synthetic | 0.7000 |
| 0.0625 | synthetic | 0.7800 |
| 0.3125 | synthetic | 0.8600 |
| 0.1875 | synthetic | 0.9400 |
| 0.3750 | synthetic | 1.020 |
| 0.0625 | synthetic | 1.100 |
| 0.3125 | synthetic | 1.180 |
| 0.8125 | synthetic | 1.260 |
| 0.3750 | synthetic | 1.340 |
| 0.5000 | synthetic | 1.420 |
| 0.5625 | synthetic | 1.500 |
| 0.6875 | synthetic | 1.580 |
| 0.6875 | synthetic | 1.660 |
| 0.3125 | synthetic | 1.740 |
| 0.2500 | synthetic | 1.820 |
| 0.3750 | synthetic | 1.900 |
| 0.5625 | synthetic | 1.980 |
| 0.3750 | synthetic | 2.060 |
| 0.2500 | synthetic | 2.140 |
| 0.3125 | synthetic | 2.220 |
| 0.2500 | synthetic | 2.300 |
| 0.3125 | synthetic | 2.380 |
| 1.500 | synthetic | 2.460 |
View data
| Column | Column | Difference |
|---|---|---|
| sepal_length | sepal_length | 0 |
| sepal_width | sepal_length | −0.1687 |
| petal_length | sepal_length | 0.1526 |
| petal_width | sepal_length | 0.1455 |
| sepal_length | sepal_width | −0.1687 |
| sepal_width | sepal_width | 0 |
| petal_length | sepal_width | −0.0472 |
| petal_width | sepal_width | −0.0360 |
| sepal_length | petal_length | 0.1526 |
| sepal_width | petal_length | −0.0472 |
| petal_length | petal_length | 0 |
| petal_width | petal_length | 0.0237 |
| sepal_length | petal_width | 0.1455 |
| sepal_width | petal_width | −0.0360 |
| petal_length | petal_width | 0.0237 |
| petal_width | petal_width | 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 | 5.676 | 1 |
| training rows | 5.573 | 2 |
| training rows | 5.466 | 3 |
| training rows | 5.356 | 4 |
| training rows | 5.247 | 5 |
| training rows | 5.143 | 6 |
| training rows | 5.047 | 7 |
| training rows | 4.961 | 8 |
| training rows | 4.885 | 9 |
| training rows | 4.816 | 10 |
| training rows | 4.749 | 11 |
| training rows | 4.678 | 12 |
| training rows | 4.603 | 13 |
| training rows | 4.522 | 14 |
| training rows | 4.441 | 15 |
| training rows | 4.367 | 16 |
| training rows | 4.307 | 17 |
| training rows | 4.269 | 18 |
| training rows | 4.249 | 19 |
| training rows | 4.235 | 20 |
| training rows | 4.209 | 21 |
| training rows | 4.167 | 22 |
| training rows | 4.118 | 23 |
| training rows | 4.071 | 24 |
| training rows | 4.034 | 25 |
| training rows | 4.006 | 26 |
| training rows | 3.984 | 27 |
| training rows | 3.959 | 28 |
| training rows | 3.927 | 29 |
| training rows | 3.890 | 30 |
| training rows | 3.854 | 31 |
| training rows | 3.824 | 32 |
| training rows | 3.800 | 33 |
| training rows | 3.781 | 34 |
| training rows | 3.763 | 35 |
| training rows | 3.744 | 36 |
| training rows | 3.723 | 37 |
| training rows | 3.700 | 38 |
| training rows | 3.679 | 39 |
| training rows | 3.660 | 40 |
Assumptions
- Enough rows for a neural generator — 150 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 3.69 nats per row.
- Held-out rows are about as likely as training rows — No complete rows were held out, so generalization can't be checked; set a holdout share to compare.
- 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.144 (mean Kolmogorov–Smirnov distance) — 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.843 ± 0.828 | 5.998 ± 1.02 | 0.1383 | Kolmogorov–Smirnov D |
| sepal_width | numeric | 3.057 ± 0.436 | 3.086 ± 0.535 | 0.1133 | Kolmogorov–Smirnov D |
| petal_length | numeric | 3.758 ± 1.77 | 4.043 ± 1.95 | 0.1667 | Kolmogorov–Smirnov D |
| petal_width | numeric | 1.199 ± 0.762 | 1.377 ± 0.796 | 0.1583 | Kolmogorov–Smirnov D |
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 c7122e70e00f1251
# 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", "sepal_width", "petal_length", "petal_width")
KINDS <- list(
sepal_length = "numeric",
sepal_width = "numeric",
petal_length = "numeric",
petal_width = "numeric"
)
LEVELS <- list(
)
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, rng)
train_rows <- sp$train; holdout_rows <- sp$holdout
train <- lapply(cols, cs_synth_take, rows = train_rows)
N_OUT <- 200L
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_nice_no_holdout/out-r")
# 4 nice 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 = "nice",
layers = as.integer(4),
epochs = as.integer(40),
batch_size = NULL,
lr = 0.005,
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_nice_no_holdout/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 = 200,
flow = "nice",
bins = 8,
tail_bound = 3,
layers = 4,
hidden_layers = c(16, 16),
epochs = 40,
batch_size = NULL,
learning_rate = 0.005,
missing = "keep_rate",
holdout = 0,
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
))
))
200 synthetic rows over 4 columns from 150 training rows with a normalizing flow. Numeric columns differ from the data by a mean Kolmogorov–Smirnov distance of 0.144.
- Synthetic rows
- 200
- Mean KS distance
- 0.1442
- Mean TV distance
- —
- 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 — 150 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 3.69 nats per row.
- Held-out rows are about as likely as training rows — No complete rows were held out, so generalization can't be checked; set a holdout share to compare.
- 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.144 (mean Kolmogorov–Smirnov distance) — 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.843 ± 0.828 | 5.998 ± 1.02 | 0.1383 | Kolmogorov–Smirnov D |
| sepal_width | numeric | 3.057 ± 0.436 | 3.086 ± 0.535 | 0.1133 | Kolmogorov–Smirnov D |
| petal_length | numeric | 3.758 ± 1.77 | 4.043 ± 1.95 | 0.1667 | Kolmogorov–Smirnov D |
| petal_width | numeric | 1.199 ± 0.762 | 1.377 ± 0.796 | 0.1583 | Kolmogorov–Smirnov D |
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 c7122e70e00f1251
# 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", "sepal_width", "petal_length", "petal_width"]
KINDS = {
"sepal_length": "numeric",
"sepal_width": "numeric",
"petal_length": "numeric",
"petal_width": "numeric",
}
LEVELS = {
}
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, rng)
train = [c.take(train_rows) for c in cols]
N_OUT = 200 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_nice_no_holdout/out-python",
)
# 4 nice 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="nice",
layers=4,
epochs=40,
batch_size=None,
lr=0.005,
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_nice_no_holdout/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": 200,
"flow": "nice",
"bins": 8,
"tail_bound": 3,
"layers": 4,
"hidden_layers": [16, 16],
"epochs": 40,
"batch_size": None,
"learning_rate": 0.005,
"missing": "keep_rate",
"holdout": 0,
"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: NICE stacks additive couplings, so the only volume change comes from a final per-column scale. On the four iris measurements the mean log-likelihood per training row is −2.908 nats. With no holdout there is nothing to compare it with, so this run says how well the flow fits, not how well it generalizes.
Training against held-out rows
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.073 and categories by a mean total variation of 0.054.
- Synthetic rows
- 320
- Mean KS distance
- 0.0728
- Mean TV distance
- 0.0538
- 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.0148 | synthetic | 18.950 |
| 0.0049 | synthetic | 20.850 |
| 0.0082 | synthetic | 22.750 |
| 0.0049 | synthetic | 24.650 |
| 0.0132 | synthetic | 26.550 |
| 0.0197 | synthetic | 28.450 |
| 0.0247 | synthetic | 30.350 |
| 0.0280 | synthetic | 32.250 |
| 0.0263 | synthetic | 34.150 |
| 0.0049 | synthetic | 36.050 |
| 0.0230 | synthetic | 37.950 |
| 0.0280 | synthetic | 39.850 |
| 0.0329 | synthetic | 41.750 |
| 0.0428 | synthetic | 43.650 |
| 0.0197 | synthetic | 45.550 |
| 0.0378 | synthetic | 47.450 |
| 0.0197 | synthetic | 49.350 |
| 0.0329 | synthetic | 51.250 |
| 0.0230 | synthetic | 53.150 |
| 0.0082 | synthetic | 55.050 |
| 0.0296 | synthetic | 56.950 |
| 0.0148 | synthetic | 58.850 |
| 0.0132 | synthetic | 60.750 |
| 0.0132 | synthetic | 62.650 |
| 0.0066 | synthetic | 64.550 |
| 0.0049 | synthetic | 66.450 |
| 0.0082 | synthetic | 68.350 |
| 0.0066 | synthetic | 70.250 |
| 0.0016 | synthetic | 72.150 |
| 0.0099 | 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 |
| 2.107e-5 | synthetic | 6851.93 |
| 8.026e-6 | synthetic | 10141.74 |
| 1.104e-5 | synthetic | 13431.55 |
| 2.508e-5 | synthetic | 16721.36 |
| 2.006e-5 | synthetic | 20011.17 |
| 3.511e-5 | synthetic | 23300.98 |
| 2.508e-5 | synthetic | 26590.79 |
| 2.809e-5 | synthetic | 29880.60 |
| 2.709e-5 | synthetic | 33170.41 |
| 2.608e-5 | synthetic | 36460.22 |
| 2.107e-5 | synthetic | 39750.03 |
| 1.806e-5 | synthetic | 43039.84 |
| 1.304e-5 | synthetic | 46329.65 |
| 1.104e-5 | synthetic | 49619.46 |
| 6.019e-6 | synthetic | 52909.27 |
| 3.010e-6 | synthetic | 56199.07 |
| 2.006e-6 | synthetic | 59488.88 |
| 1.003e-6 | synthetic | 62778.69 |
| 1.003e-6 | synthetic | 66068.50 |
| 0 | synthetic | 69358.31 |
| 1.003e-6 | 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.0815 | synthetic | 0.7667 |
| 0.0326 | synthetic | 2.300 |
| 0.0122 | synthetic | 3.833 |
| 0.0489 | synthetic | 5.367 |
| 0.0143 | synthetic | 6.900 |
| 0.0387 | synthetic | 8.433 |
| 0.0102 | synthetic | 9.967 |
| 0.0346 | synthetic | 11.500 |
| 0.0326 | synthetic | 13.033 |
| 0.0448 | synthetic | 14.567 |
| 0.0204 | synthetic | 16.100 |
| 0.0469 | synthetic | 17.633 |
| 0.0306 | synthetic | 19.167 |
| 0.0428 | synthetic | 20.700 |
| 0.0285 | synthetic | 22.233 |
| 0.0265 | synthetic | 23.767 |
| 0.0367 | synthetic | 25.300 |
| 0.0102 | synthetic | 26.833 |
| 0.0102 | synthetic | 28.367 |
| 0.0163 | synthetic | 29.900 |
| 0.0122 | synthetic | 31.433 |
| 0.0020 | synthetic | 32.967 |
| 0.0020 | synthetic | 34.500 |
| 0.0041 | synthetic | 36.033 |
| 0.0020 | synthetic | 37.567 |
| 0 | synthetic | 39.100 |
| 0.0061 | synthetic | 40.633 |
| 0 | synthetic | 42.167 |
| 0 | synthetic | 43.700 |
| 0.0041 | 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.0003 | synthetic | 17582.23 |
| 0.0003 | synthetic | 17654.70 |
| 0.0003 | synthetic | 17727.17 |
| 0.0001 | synthetic | 17799.63 |
| 0.0004 | synthetic | 17872.10 |
| 0.0006 | synthetic | 17944.57 |
| 0.0006 | synthetic | 18017.03 |
| 0.0004 | synthetic | 18089.50 |
| 0.0008 | synthetic | 18161.97 |
| 0.0006 | synthetic | 18234.43 |
| 0.0003 | synthetic | 18306.90 |
| 0.0005 | synthetic | 18379.37 |
| 0.0007 | synthetic | 18451.83 |
| 0.0009 | synthetic | 18524.30 |
| 0.0008 | synthetic | 18596.77 |
| 0.0007 | synthetic | 18669.23 |
| 0.0003 | synthetic | 18741.70 |
| 0.0008 | synthetic | 18814.17 |
| 0.0003 | synthetic | 18886.63 |
| 0.0005 | synthetic | 18959.10 |
| 0.0005 | synthetic | 19031.57 |
| 0.0006 | synthetic | 19104.03 |
| 0.0004 | synthetic | 19176.50 |
| 0.0003 | synthetic | 19248.97 |
| 0.0003 | synthetic | 19321.43 |
| 0.0003 | synthetic | 19393.90 |
| 0.0003 | synthetic | 19466.37 |
| 0.0002 | synthetic | 19538.83 |
| 0.0001 | 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.3719 | synthetic |
| plus | 0.3625 | synthetic |
| premium | 0.2656 | synthetic |
View data
| region | Share | Source |
|---|---|---|
| east | 0.2848 | real |
| north | 0.2718 | real |
| south | 0.3042 | real |
| west | 0.1392 | real |
| east | 0.2812 | synthetic |
| north | 0.2652 | synthetic |
| south | 0.2812 | synthetic |
| west | 0.1725 | synthetic |
View data
| churned | Share | Source |
|---|---|---|
| false | 0.7688 | real |
| true | 0.2313 | real |
| false | 0.6750 | synthetic |
| true | 0.3250 | synthetic |
View data
| Column | Column | Difference |
|---|---|---|
| age | age | 0 |
| annual income | age | 0.0956 |
| tenure_months | age | 0.7348 |
| signup | age | −0.0327 |
| visits | age | 0.0324 |
| age | annual income | 0.0956 |
| annual income | annual income | 0 |
| tenure_months | annual income | 0.0573 |
| signup | annual income | 0.0140 |
| visits | annual income | 0.2546 |
| age | tenure_months | 0.7348 |
| annual income | tenure_months | 0.0573 |
| tenure_months | tenure_months | 0 |
| signup | tenure_months | −0.1054 |
| visits | tenure_months | 0.0467 |
| age | signup | −0.0327 |
| annual income | signup | 0.0140 |
| tenure_months | signup | −0.1054 |
| signup | signup | 0 |
| visits | signup | 0.0635 |
| age | visits | 0.0324 |
| annual income | visits | 0.2546 |
| tenure_months | visits | 0.0467 |
| signup | visits | 0.0635 |
| 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 | 17.125 | 1 |
| training rows | 16.754 | 2 |
| training rows | 16.482 | 3 |
| training rows | 16.128 | 4 |
| training rows | 15.892 | 5 |
| training rows | 15.552 | 6 |
| training rows | 15.214 | 7 |
| training rows | 15.016 | 8 |
| training rows | 14.762 | 9 |
| training rows | 14.581 | 10 |
| training rows | 14.335 | 11 |
| training rows | 14.213 | 12 |
| training rows | 14.256 | 13 |
| training rows | 14.282 | 14 |
| training rows | 14.046 | 15 |
| training rows | 13.947 | 16 |
| training rows | 13.927 | 17 |
| training rows | 13.868 | 18 |
| training rows | 13.794 | 19 |
| training rows | 13.668 | 20 |
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 13.7 nats per row.
- Held-out rows are about as likely as training rows — Mean log-likelihood -35.1 nats per training row and -35.4 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.073 (mean Kolmogorov–Smirnov distance); categories 0.054 (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 | 44.41 ± 12.9 | 0.0844 | Kolmogorov–Smirnov D |
| annual income | numeric | 2.929e+04 ± 1.43e+04 | 2.938e+04 ± 1.31e+04 | 0.0891 | Kolmogorov–Smirnov D |
| tenure_months | numeric | 15 ± 10.7 | 14.49 ± 9.96 | 0.0469 | Kolmogorov–Smirnov D |
| plan | categorical | plus 39.7% | plus 36.2% | 0.0344 | total variation |
| region | categorical | south 30.4% | south 28.1% | 0.0334 | total variation |
| churned | boolean | false 76.9% | false 67.5% | 0.0938 | total variation |
| signup | temporal | 2020-11-05 ± 621 days | 2020-11-19 ± 542 days | 0.0938 | Kolmogorov–Smirnov D |
| visits | numeric | 3.394 ± 2.09 | 3.225 ± 1.98 | 0.0500 | 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 0e3358a16f893167
# 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_realnvp/out-r")
# 4 realnvp 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 = "realnvp",
layers = as.integer(4),
epochs = as.integer(20),
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_realnvp/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 = "realnvp",
bins = 8,
tail_bound = 3,
layers = 4,
hidden_layers = c(16, 16),
epochs = 20,
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.073 and categories by a mean total variation of 0.054.
- Synthetic rows
- 320
- Mean KS distance
- 0.0728
- Mean TV distance
- 0.0538
- 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 13.7 nats per row.
- Held-out rows are about as likely as training rows — Mean log-likelihood -35.1 nats per training row and -35.4 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.073 (mean Kolmogorov–Smirnov distance); categories 0.054 (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 | 44.41 ± 12.9 | 0.0844 | Kolmogorov–Smirnov D |
| annual income | numeric | 2.929e+04 ± 1.43e+04 | 2.938e+04 ± 1.31e+04 | 0.0891 | Kolmogorov–Smirnov D |
| tenure_months | numeric | 15 ± 10.7 | 14.49 ± 9.96 | 0.0469 | Kolmogorov–Smirnov D |
| plan | categorical | plus 39.7% | plus 36.2% | 0.0344 | total variation |
| region | categorical | south 30.4% | south 28.1% | 0.0334 | total variation |
| churned | boolean | false 76.9% | false 67.5% | 0.0938 | total variation |
| signup | temporal | 2020-11-05 ± 621 days | 2020-11-19 ± 542 days | 0.0938 | Kolmogorov–Smirnov D |
| visits | numeric | 3.394 ± 2.09 | 3.225 ± 1.98 | 0.0500 | 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 0e3358a16f893167
# 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_realnvp/out-python",
)
# 4 realnvp 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="realnvp",
layers=4,
epochs=20,
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_realnvp/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": "realnvp",
"bins": 8,
"tail_bound": 3,
"layers": 4,
"hidden_layers": [16, 16],
"epochs": 20,
"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,
}},
})
The default Real NVP flow on the customer table holds out rows and scores them too: −35.15 nats per training row against −35.43 per held-out row. About the same, so no sign of memorizing. A training value pulling far ahead of the held-out one would be the warning.
Categories get uniform noise first (dequantizationDequantizationAdding uniform noise to discrete values so a continuous density can model them; its likelihood is a lower bound.), so their part of the likelihood is a lower bound.
A likely row isn't a typical row
PredictPredict first
You want to flag unusual rows using a flow's exact log-likelihood. What's the safer plan?
Reveal
Check it on known unusual rows first. Flows can give higher likelihood to some inputs unlike the training data, for example smooth or low-variance ones, because likelihood mixes "how typical" with "how simple". Calibrate any cutoff on rows with known labels.
What runs here
ReadCheck: flows
CheckpointCheck yourself
What is the log-determinant of a NICE additive coupling layer?
Show the answer
Answer: 0
has a triangular Jacobian with ones on the diagonal, so its determinant is 1 and its log is 0. NICE couplings preserve volume.
Check yourself
To invert , what do you need?
Show the answer
Answer: a
The passed-through half is unchanged, so and . The network itself is never inverted.
Check yourself
What is the log-determinant of a Real NVP affine coupling ?
Show the answer
Answer: b
The Jacobian is triangular with on the transformed part of the diagonal, so the log-determinant is the sum of .
Check yourself
A flow's mean log-likelihood is much higher on training rows than on held-out rows. What does that suggest?
Show the answer
Answer: a
The exact likelihood makes this check possible, which GANs can't offer. A gap like that also means generated rows may sit too close to real ones.
Check yourself
Is a row with high likelihood under a flow necessarily typical of the training data?
Show the answer
Answer: b
An exact density is not a typicality test. Some out-of-distribution inputs get higher likelihood than real data.
Recap
Recap- A flow is invertible; the change of variables gives an exact log-likelihood.
- Coupling layers keep the log-determinant cheap: 0 for NICE, a sum of scales for Real NVP.
- Compare training and held-out log-likelihoods to spot memorizing.
- High likelihood is not a typicality check. CodeSplash runs both couplings in
synth.flow.
Concepts in this lesson