Skip to content

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.

Advanced ~14 min9 steps

What runs in CodeSplash

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

Read first

01

Glow: scale, mix, couple

Read

A 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 WW, so every column can reach every other.

The mixing's log-determinant is log⁡∣det⁡W∣\log|\det W|, once per location. Keeping W=PLUW = PLU (a fixed permutation, a unit lower-triangular and an upper-triangular matrix) makes it the sum of the logs of UU's diagonal.

In the reference's example a 2-by-2 mixing applied at four locations has a total log-determinant of −0.794.

02

Glow on the customer table

Explore
Synthetic data — normalizing flow (RealNVP, NICE, MAF, Glow, spline)Recorded · Python and R agreeRecorded 2026-11-25 · 52 values compared · largest relative difference 1.7e-15
R

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

Plots

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

In the flow's coordinates (standardized numbers, dequantized categories); lower is better.

View data
PartNegative log-likelihood (nats per row)Epoch
training rows14.0301
training rows13.7132
training rows13.7013
training rows13.4724
training rows13.5945
training rows13.4756
training rows13.3517
training rows13.3728
training rows13.1689
training rows13.10710
training rows12.94311
training rows12.78212
training rows12.83913
training rows12.94214
training rows12.75615

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

ColumnKindRealSyntheticDistanceMeasure
agenumeric43.14 ± 13.142.47 ± 11.80.0844Kolmogorov–Smirnov D
annual incomenumeric2.929e+04 ± 1.43e+042.909e+04 ± 1.21e+040.1122Kolmogorov–Smirnov D
tenure_monthsnumeric15 ± 10.715.52 ± 9.650.0906Kolmogorov–Smirnov D
plancategoricalplus 39.7%plus 41.6%0.0281total variation
regioncategoricalsouth 30.4%south 31.6%0.0548total variation
churnedbooleanfalse 76.9%false 79.4%0.0250total variation
signuptemporal2020-11-05 ± 621 days2020-11-19 ± 559 days0.0844Kolmogorov–Smirnov D
visitsnumeric3.394 ± 2.093.537 ± 2.040.0875Kolmogorov–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
  ))
))
Python

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

ColumnKindRealSyntheticDistanceMeasure
agenumeric43.14 ± 13.142.47 ± 11.80.0844Kolmogorov–Smirnov D
annual incomenumeric2.929e+04 ± 1.43e+042.909e+04 ± 1.21e+040.1122Kolmogorov–Smirnov D
tenure_monthsnumeric15 ± 10.715.52 ± 9.650.0906Kolmogorov–Smirnov D
plancategoricalplus 39.7%plus 41.6%0.0281total variation
regioncategoricalsouth 30.4%south 31.6%0.0548total variation
churnedbooleanfalse 76.9%false 79.4%0.0250total variation
signuptemporal2020-11-05 ± 621 days2020-11-19 ± 559 days0.0844Kolmogorov–Smirnov D
visitsnumeric3.394 ± 2.093.538 ± 2.040.0875Kolmogorov–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.

03

Masked autoregressive flows

Read

A 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:

zi=(xi−μi(x<i))e−αi(x<i),log⁡∣det⁡∣=−∑iαi.z_i = \left(x_i - \mu_i(x_{<i})\right) e^{-\alpha_i(x_{<i})}, \qquad \log|\det| = -\sum_i \alpha_i .

Masks in one network (MADE) make every μi\mu_i and αi\alpha_i see only earlier columns, so scoring a row takes one pass. Sampling has to go column by column: x2x_2 needs x1x_1 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.

04

MAF in CodeSplash

Explore
Synthetic data — normalizing flow (RealNVP, NICE, MAF, Glow, spline)Recorded · Python and R agreeRecorded 2026-11-25 · 28 values compared
R

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

Plots

sepal_length: real vs syntheticDoes the synthetic data reproduce the shape of a numeric column?
View data
DensitySourcesepal_length
0.2206real4.357
0.0735real4.470
0.2206real4.583
0.1471real4.697
0.2941real4.810
0.3676real4.923
0.5147real5.037
0.7353real5.150
0.0735real5.263
0.2941real5.377
0.4412real5.490
0.2941real5.603
0.5147real5.717
0.5147real5.830
0.2206real5.943
0.6618real6.057
0.2941real6.170
0.5882real6.283
0.5147real6.397
0.2941real6.510
0.0735real6.623
0.5147real6.737
0.3676real6.850
0real6.963
0.0735real7.077
0.0735real7.190
0.0735real7.303
0.0735real7.417
0real7.530
0.2941real7.643
0.3529synthetic4.357
0.1176synthetic4.470
0.1176synthetic4.583
0synthetic4.697
0.2353synthetic4.810
0.4118synthetic4.923
0.0588synthetic5.037
0.4118synthetic5.150
0.3529synthetic5.263
0.2353synthetic5.377
0.5294synthetic5.490
0.4118synthetic5.603
0.5294synthetic5.717
0.2353synthetic5.830
0.5882synthetic5.943
0.4706synthetic6.057
0.5882synthetic6.170
0.4118synthetic6.283
0.2941synthetic6.397
0.8824synthetic6.510
0.3529synthetic6.623
0.1765synthetic6.737
0.1765synthetic6.850
0.3529synthetic6.963
0.0588synthetic7.077
0.0588synthetic7.190
0synthetic7.303
0.0588synthetic7.417
0.0588synthetic7.530
0.2941synthetic7.643
petal_length: real vs syntheticDoes the synthetic data reproduce the shape of a numeric column?
View data
DensitySourcepetal_length
0.1293real1.197
0.7759real1.390
0.6466real1.583
0.1293real1.777
0.0862real1.970
0real2.163
0real2.357
0real2.550
0real2.743
0.0431real2.937
0real3.130
0real3.323
0.1293real3.517
0.0862real3.710
0.2586real3.903
0.0862real4.097
0.2155real4.290
0.4310real4.483
0.2155real4.677
0.3448real4.870
0.4741real5.063
0.1724real5.257
0.1724real5.450
0.3448real5.643
0.0862real5.837
0.1724real6.030
0.0431real6.223
0real6.417
0.0862real6.610
0.0431real6.803
0.2759synthetic1.197
0synthetic1.390
0.0690synthetic1.583
0.1034synthetic1.777
0.2759synthetic1.970
0.0345synthetic2.163
0.2759synthetic2.357
0.1379synthetic2.550
0.2759synthetic2.743
0.2414synthetic2.937
0.2759synthetic3.130
0.2069synthetic3.323
0.2069synthetic3.517
0.3103synthetic3.710
0.3448synthetic3.903
0.3793synthetic4.097
0.2069synthetic4.290
0.1379synthetic4.483
0.2069synthetic4.677
0.2414synthetic4.870
0.1034synthetic5.063
0.3103synthetic5.257
0.1724synthetic5.450
0.0690synthetic5.643
0.0345synthetic5.837
0.1034synthetic6.030
0synthetic6.223
0.0690synthetic6.417
0.0690synthetic6.610
0.0345synthetic6.803
species: real vs syntheticDoes the synthetic data keep the category proportions of the real data?
View data
speciesShareSource
setosa0.3417real
versicolor0.3167real
virginica0.3417real
setosa0.3733synthetic
versicolor0.2933synthetic
virginica0.3333synthetic
Correlation difference (real − synthetic)What do the values of a square or rectangular result matrix look like at a glance?
View data
ColumnColumnDifference
sepal_lengthsepal_length0
petal_lengthsepal_length0.6235
sepal_lengthpetal_length0.6235
petal_lengthpetal_length0
Negative log-likelihood by epochIs the network still learning, and which part of its loss moves?

In the flow's coordinates (standardized numbers, dequantized categories); lower is better.

View data
PartNegative log-likelihood (nats per row)Epoch
training rows6.1941
training rows6.1412
training rows6.0923
training rows5.9964
training rows5.9875
training rows5.8756
training rows5.8137
training rows5.7018
training rows5.6719
training rows5.64110
training rows5.52011
training rows5.49912
training rows5.38813
training rows5.33414
training rows5.27415
training rows5.23616
training rows5.12617
training rows5.03818
training rows5.03219
training rows4.93720
training rows4.88521
training rows4.79222
training rows4.73423
training rows4.63724
training rows4.64325
training rows4.55526
training rows4.49527
training rows4.47228
training rows4.43229
training rows4.47530

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

ColumnKindRealSyntheticDistanceMeasure
sepal_lengthnumeric5.828 ± 0.85.92 ± 0.7870.1217Kolmogorov–Smirnov D
petal_lengthnumeric3.725 ± 1.763.691 ± 1.340.2550Kolmogorov–Smirnov D
speciescategoricalsetosa 34.2%setosa 37.3%0.0317total 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
  ))
))
Python

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

ColumnKindRealSyntheticDistanceMeasure
sepal_lengthnumeric5.828 ± 0.85.92 ± 0.7870.1217Kolmogorov–Smirnov D
petal_lengthnumeric3.725 ± 1.763.691 ± 1.340.2550Kolmogorov–Smirnov D
speciescategoricalsetosa 34.2%setosa 37.3%0.0317total 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.

05

Spline flows

Read

Affine 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 sure?
5
0.50

How much each layer stretches: s(y) = α·tanh(u·y + v).

1.00

How much each layer bends: t(y) = β·sin(w·y) + c·y.

0.50
−0.50
Simulating…

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

06

A spline flow on penguins

Explore
Synthetic data — normalizing flow (RealNVP, NICE, MAF, Glow, spline)Recorded · Python and R agreeRecorded 2026-11-25 · 36 values compared
R

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

Plots

bill_len: real vs syntheticDoes the synthetic data reproduce the shape of a numeric column?
View data
DensitySourcebill_len
0.0043real32.558
0.0043real33.475
0.0213real34.392
0.0341real35.308
0.0469real36.225
0.0469real37.142
0.0639real38.058
0.0639real38.975
0.0511real39.892
0.0767real40.808
0.0426real41.725
0.0384real42.642
0.0298real43.558
0.0256real44.475
0.0980real45.392
0.0767real46.308
0.0554real47.225
0.0384real48.142
0.0597real49.058
0.0639real49.975
0.0682real50.892
0.0384real51.808
0.0128real52.725
0.0085real53.642
0.0085real54.558
0.0085real55.475
0real56.392
0real57.308
0real58.225
0.0043real59.142
0.0109synthetic32.558
0.0036synthetic33.475
0.0073synthetic34.392
0.0145synthetic35.308
0.0400synthetic36.225
0.0509synthetic37.142
0.0618synthetic38.058
0.0436synthetic38.975
0.0618synthetic39.892
0.0800synthetic40.808
0.0800synthetic41.725
0.0436synthetic42.642
0.0400synthetic43.558
0.0545synthetic44.475
0.0655synthetic45.392
0.0618synthetic46.308
0.0655synthetic47.225
0.0582synthetic48.142
0.0691synthetic49.058
0.0655synthetic49.975
0.0364synthetic50.892
0.0255synthetic51.808
0.0145synthetic52.725
0.0036synthetic53.642
0.0073synthetic54.558
0.0109synthetic55.475
0synthetic56.392
0synthetic57.308
0.0073synthetic58.225
0.0073synthetic59.142
bill_dep: real vs syntheticDoes the synthetic data reproduce the shape of a numeric column?
View data
DensitySourcebill_dep
0.0424real13.338
0.0847real13.615
0.1271real13.892
0.1412real14.168
0.1271real14.445
0.1271real14.722
0.1412real14.998
0.0988real15.275
0.0565real15.552
0.1553real15.828
0.0988real16.105
0.1271real16.382
0.0847real16.658
0.2118real16.935
0.2400real17.212
0.1412real17.488
0.2118real17.765
0.1412real18.042
0.1271real18.318
0.2683real18.595
0.2824real18.872
0.0847real19.148
0.1130real19.425
0.0988real19.702
0.1130real19.978
0.0565real20.255
0.0141real20.532
0.0282real20.808
0.0565real21.085
0.0141real21.362
0.0723synthetic13.338
0.0361synthetic13.615
0.0602synthetic13.892
0.0602synthetic14.168
0.0723synthetic14.445
0.1084synthetic14.722
0.1325synthetic14.998
0.1446synthetic15.275
0.0964synthetic15.552
0.0843synthetic15.828
0.2289synthetic16.105
0.1807synthetic16.382
0.1446synthetic16.658
0.2048synthetic16.935
0.2048synthetic17.212
0.1446synthetic17.488
0.1807synthetic17.765
0.1687synthetic18.042
0.2530synthetic18.318
0.2289synthetic18.595
0.1687synthetic18.872
0.1446synthetic19.148
0.1807synthetic19.425
0.0602synthetic19.702
0.0723synthetic19.978
0.0723synthetic20.255
0.0361synthetic20.532
0.0120synthetic20.808
0.0482synthetic21.085
0.0120synthetic21.362
flipper_len: real vs syntheticDoes the synthetic data reproduce the shape of a numeric column?
View data
DensitySourceflipper_len
0.0020real172.98
0.0020real174.95
0.0020real176.92
0.0060real178.88
0.0159real180.85
0.0099real182.82
0.0238real184.78
0.0258real186.75
0.0179real188.72
0.0616real190.68
0.0218real192.65
0.0358real194.62
0.0278real196.58
0.0258real198.55
0.0139real200.52
0.0119real202.48
0.0060real204.45
0.0060real206.42
0.0179real208.38
0.0218real210.35
0.0218real212.32
0.0278real214.28
0.0199real216.25
0.0179real218.22
0.0199real220.18
0.0079real222.15
0.0119real224.12
0.0020real226.08
0.0119real228.05
0.0119real230.02
0.0034synthetic172.98
0.0034synthetic174.95
0.0017synthetic176.92
0.0051synthetic178.88
0.0068synthetic180.85
0.0136synthetic182.82
0.0102synthetic184.78
0.0203synthetic186.75
0.0220synthetic188.72
0.0339synthetic190.68
0.0407synthetic192.65
0.0356synthetic194.62
0.0339synthetic196.58
0.0339synthetic198.55
0.0305synthetic200.52
0.0220synthetic202.48
0.0220synthetic204.45
0.0237synthetic206.42
0.0237synthetic208.38
0.0153synthetic210.35
0.0186synthetic212.32
0.0153synthetic214.28
0.0068synthetic216.25
0.0237synthetic218.22
0.0102synthetic220.18
0.0068synthetic222.15
0.0102synthetic224.12
0.0017synthetic226.08
0.0068synthetic228.05
0.0068synthetic230.02
body_mass: real vs syntheticDoes the synthetic data reproduce the shape of a numeric column?
View data
DensitySourcebody_mass
3.498e-5real2755.83
0.0001real2867.50
6.996e-5real2979.17
0.0002real3090.83
0.0005real3202.50
0.0003real3314.17
0.0006real3425.83
0.0005real3537.50
0.0007real3649.17
0.0005real3760.83
0.0004real3872.50
0.0005real3984.17
0.0005real4095.83
0.0003real4207.50
0.0003real4319.17
0.0004real4430.83
0.0001real4542.50
0.0006real4654.17
0.0003real4765.83
0.0003real4877.50
0.0002real4989.17
0.0003real5100.83
0.0001real5212.50
0.0002real5324.17
0.0001real5435.83
0.0005real5547.50
0.0002real5659.17
6.996e-5real5770.83
3.498e-5real5882.50
0.0001real5994.17
0.0001synthetic2755.83
8.955e-5synthetic2867.50
8.955e-5synthetic2979.17
0.0003synthetic3090.83
0.0004synthetic3202.50
0.0003synthetic3314.17
0.0003synthetic3425.83
0.0004synthetic3537.50
0.0005synthetic3649.17
0.0007synthetic3760.83
0.0005synthetic3872.50
0.0006synthetic3984.17
0.0004synthetic4095.83
0.0007synthetic4207.50
0.0003synthetic4319.17
0.0003synthetic4430.83
0.0007synthetic4542.50
0.0004synthetic4654.17
0.0002synthetic4765.83
0.0002synthetic4877.50
0.0004synthetic4989.17
0.0001synthetic5100.83
0.0001synthetic5212.50
0.0002synthetic5324.17
0.0002synthetic5435.83
8.955e-5synthetic5547.50
0.0001synthetic5659.17
0synthetic5770.83
8.955e-5synthetic5882.50
8.955e-5synthetic5994.17
species: real vs syntheticDoes the synthetic data keep the category proportions of the real data?
View data
speciesShareSource
Adelie0.4419real
Chinstrap0.1899real
Gentoo0.3682real
Adelie0.4367synthetic
Chinstrap0.2200synthetic
Gentoo0.3433synthetic
Correlation difference (real − synthetic)What do the values of a square or rectangular result matrix look like at a glance?
View data
ColumnColumnDifference
bill_lenbill_len0
bill_depbill_len−0.0747
flipper_lenbill_len0.1233
body_massbill_len0.1537
bill_lenbill_dep−0.0747
bill_depbill_dep0
flipper_lenbill_dep−0.1368
body_massbill_dep−0.0741
bill_lenflipper_len0.1233
bill_depflipper_len−0.1368
flipper_lenflipper_len0
body_massflipper_len0.3090
bill_lenbody_mass0.1537
bill_depbody_mass−0.0741
flipper_lenbody_mass0.3090
body_massbody_mass0
Negative log-likelihood by epochIs the network still learning, and which part of its loss moves?

In the flow's coordinates (standardized numbers, dequantized categories); lower is better.

View data
PartNegative log-likelihood (nats per row)Epoch
training rows8.6781
training rows7.8862
training rows7.3563
training rows6.9624
training rows6.6435
training rows6.4236
training rows6.2407
training rows6.0448
training rows5.9199
training rows5.88610
training rows5.80311
training rows5.58712
training rows5.57613
training rows5.63514
training rows5.45215

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

ColumnKindRealSyntheticDistanceMeasure
speciescategoricalAdelie 44.2%Adelie 43.7%0.0301total variation
bill_lennumeric43.96 ± 5.544.09 ± 5.30.0628Kolmogorov–Smirnov D
bill_depnumeric17.14 ± 1.9817.26 ± 1.830.0819Kolmogorov–Smirnov D
flipper_lennumeric201.3 ± 14.2200.7 ± 12.50.1037Kolmogorov–Smirnov D
body_massnumeric4219 ± 7914167 ± 7280.0870Kolmogorov–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
  ))
))
Python

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

ColumnKindRealSyntheticDistanceMeasure
speciescategoricalAdelie 44.2%Adelie 43.7%0.0301total variation
bill_lennumeric43.96 ± 5.544.09 ± 5.30.0628Kolmogorov–Smirnov D
bill_depnumeric17.14 ± 1.9817.26 ± 1.830.0819Kolmogorov–Smirnov D
flipper_lennumeric201.3 ± 14.2200.7 ± 12.50.1038Kolmogorov–Smirnov D
body_massnumeric4219 ± 7914167 ± 7280.0870Kolmogorov–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.

Synthetic data — normalizing flow (RealNVP, NICE, MAF, Glow, spline)Recorded · Python and R agreeRecorded 2026-11-25 · 45 values compared · largest relative difference 8.7e-16
R

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

bill_len: real vs syntheticDoes the synthetic data reproduce the shape of a numeric column?
View data
DensitySourcebill_len
0.0043real32.558
0.0043real33.475
0.0213real34.392
0.0341real35.308
0.0469real36.225
0.0469real37.142
0.0639real38.058
0.0639real38.975
0.0511real39.892
0.0767real40.808
0.0426real41.725
0.0384real42.642
0.0298real43.558
0.0256real44.475
0.0980real45.392
0.0767real46.308
0.0554real47.225
0.0384real48.142
0.0597real49.058
0.0639real49.975
0.0682real50.892
0.0384real51.808
0.0128real52.725
0.0085real53.642
0.0085real54.558
0.0085real55.475
0real56.392
0real57.308
0real58.225
0.0043real59.142
0.0027synthetic32.558
0.0027synthetic33.475
0.0136synthetic34.392
0.0082synthetic35.308
0.0109synthetic36.225
0.0164synthetic37.142
0.0218synthetic38.058
0.0573synthetic38.975
0.0545synthetic39.892
0.0355synthetic40.808
0.0791synthetic41.725
0.0873synthetic42.642
0.0900synthetic43.558
0.0873synthetic44.475
0.0736synthetic45.392
0.0764synthetic46.308
0.0982synthetic47.225
0.0682synthetic48.142
0.0627synthetic49.058
0.0436synthetic49.975
0.0245synthetic50.892
0.0273synthetic51.808
0.0164synthetic52.725
0.0082synthetic53.642
0.0136synthetic54.558
0.0027synthetic55.475
0.0027synthetic56.392
0.0027synthetic57.308
0synthetic58.225
0.0027synthetic59.142
bill_dep: real vs syntheticDoes the synthetic data reproduce the shape of a numeric column?
View data
DensitySourcebill_dep
0.0424real13.338
0.0847real13.615
0.1271real13.892
0.1412real14.168
0.1271real14.445
0.1271real14.722
0.1412real14.998
0.0988real15.275
0.0565real15.552
0.1553real15.828
0.0988real16.105
0.1271real16.382
0.0847real16.658
0.2118real16.935
0.2400real17.212
0.1412real17.488
0.2118real17.765
0.1412real18.042
0.1271real18.318
0.2683real18.595
0.2824real18.872
0.0847real19.148
0.1130real19.425
0.0988real19.702
0.1130real19.978
0.0565real20.255
0.0141real20.532
0.0282real20.808
0.0565real21.085
0.0141real21.362
0.0542synthetic13.338
0.0090synthetic13.615
0.0361synthetic13.892
0.0181synthetic14.168
0.0271synthetic14.445
0.0813synthetic14.722
0.1175synthetic14.998
0.1446synthetic15.275
0.1807synthetic15.552
0.1807synthetic15.828
0.1627synthetic16.105
0.1717synthetic16.382
0.1627synthetic16.658
0.1717synthetic16.935
0.2440synthetic17.212
0.3072synthetic17.488
0.2982synthetic17.765
0.2169synthetic18.042
0.1807synthetic18.318
0.2530synthetic18.595
0.1717synthetic18.872
0.0904synthetic19.148
0.0813synthetic19.425
0.0723synthetic19.702
0.0452synthetic19.978
0.0090synthetic20.255
0.0542synthetic20.532
0.0181synthetic20.808
0.0271synthetic21.085
0.0271synthetic21.362
flipper_len: real vs syntheticDoes the synthetic data reproduce the shape of a numeric column?
View data
DensitySourceflipper_len
0.0020real172.98
0.0020real174.95
0.0020real176.92
0.0060real178.88
0.0159real180.85
0.0099real182.82
0.0238real184.78
0.0258real186.75
0.0179real188.72
0.0616real190.68
0.0218real192.65
0.0358real194.62
0.0278real196.58
0.0258real198.55
0.0139real200.52
0.0119real202.48
0.0060real204.45
0.0060real206.42
0.0179real208.38
0.0218real210.35
0.0218real212.32
0.0278real214.28
0.0199real216.25
0.0179real218.22
0.0199real220.18
0.0079real222.15
0.0119real224.12
0.0020real226.08
0.0119real228.05
0.0119real230.02
0synthetic172.98
0.0025synthetic174.95
0.0013synthetic176.92
0.0013synthetic178.88
0.0089synthetic180.85
0.0140synthetic182.82
0.0114synthetic184.78
0.0127synthetic186.75
0.0216synthetic188.72
0.0254synthetic190.68
0.0305synthetic192.65
0.0343synthetic194.62
0.0356synthetic196.58
0.0343synthetic198.55
0.0369synthetic200.52
0.0331synthetic202.48
0.0432synthetic204.45
0.0254synthetic206.42
0.0280synthetic208.38
0.0280synthetic210.35
0.0140synthetic212.32
0.0102synthetic214.28
0.0153synthetic216.25
0.0064synthetic218.22
0.0076synthetic220.18
0.0076synthetic222.15
0.0051synthetic224.12
0.0051synthetic226.08
0.0064synthetic228.05
0.0025synthetic230.02
body_mass: real vs syntheticDoes the synthetic data reproduce the shape of a numeric column?
View data
DensitySourcebody_mass
3.498e-5real2755.83
0.0001real2867.50
6.996e-5real2979.17
0.0002real3090.83
0.0005real3202.50
0.0003real3314.17
0.0006real3425.83
0.0005real3537.50
0.0007real3649.17
0.0005real3760.83
0.0004real3872.50
0.0005real3984.17
0.0005real4095.83
0.0003real4207.50
0.0003real4319.17
0.0004real4430.83
0.0001real4542.50
0.0006real4654.17
0.0003real4765.83
0.0003real4877.50
0.0002real4989.17
0.0003real5100.83
0.0001real5212.50
0.0002real5324.17
0.0001real5435.83
0.0005real5547.50
0.0002real5659.17
6.996e-5real5770.83
3.498e-5real5882.50
0.0001real5994.17
4.478e-5synthetic2755.83
6.716e-5synthetic2867.50
4.478e-5synthetic2979.17
8.955e-5synthetic3090.83
0.0002synthetic3202.50
0.0002synthetic3314.17
0.0005synthetic3425.83
0.0004synthetic3537.50
0.0005synthetic3649.17
0.0006synthetic3760.83
0.0007synthetic3872.50
0.0006synthetic3984.17
0.0006synthetic4095.83
0.0006synthetic4207.50
0.0004synthetic4319.17
0.0006synthetic4430.83
0.0005synthetic4542.50
0.0004synthetic4654.17
0.0004synthetic4765.83
0.0005synthetic4877.50
0.0003synthetic4989.17
0.0002synthetic5100.83
0.0002synthetic5212.50
8.955e-5synthetic5324.17
6.716e-5synthetic5435.83
8.955e-5synthetic5547.50
2.239e-5synthetic5659.17
2.239e-5synthetic5770.83
4.478e-5synthetic5882.50
0synthetic5994.17
species: real vs syntheticDoes the synthetic data keep the category proportions of the real data?
View data
speciesShareSource
Adelie0.4419real
Chinstrap0.1899real
Gentoo0.3682real
Adelie0.3900synthetic
Chinstrap0.2900synthetic
Gentoo0.3200synthetic
island: real vs syntheticDoes the synthetic data keep the category proportions of the real data?
View data
islandShareSource
Biscoe0.4806real
Dream0.3643real
Torgersen0.1550real
Biscoe0.4900synthetic
Dream0.3150synthetic
Torgersen0.1950synthetic
sex: real vs syntheticDoes the synthetic data keep the category proportions of the real data?
View data
sexShareSource
female0.4940real
male0.5060real
female0.4600synthetic
male0.5400synthetic
Correlation difference (real − synthetic)What do the values of a square or rectangular result matrix look like at a glance?
View data
ColumnColumnDifference
bill_lenbill_len0
bill_depbill_len−0.1320
flipper_lenbill_len0.5396
body_massbill_len0.3186
bill_lenbill_dep−0.1320
bill_depbill_dep0
flipper_lenbill_dep−0.4290
body_massbill_dep−0.3303
bill_lenflipper_len0.5396
bill_depflipper_len−0.4290
flipper_lenflipper_len0
body_massflipper_len0.6928
bill_lenbody_mass0.3186
bill_depbody_mass−0.3303
flipper_lenbody_mass0.6928
body_massbody_mass0
Negative log-likelihood by epochIs the network still learning, and which part of its loss moves?

In the flow's coordinates (standardized numbers, dequantized categories); lower is better.

View data
PartNegative log-likelihood (nats per row)Epoch
training rows14.7281
training rows14.4322
training rows14.1503
training rows13.7784
training rows13.5095
training rows13.1996
training rows12.9077
training rows12.5768
training rows12.3149
training rows12.03310
training rows11.74911
training rows11.43912
training rows11.12813
training rows10.91914
training rows10.75915
training rows10.48416
training rows10.30117
training rows10.07918
training rows9.94819
training rows9.74020

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

ColumnKindRealSyntheticDistanceMeasure
speciescategoricalAdelie 44.2%Adelie 39.0%0.1001total variation
islandcategoricalBiscoe 48.1%Biscoe 49.0%0.0493total variation
bill_lennumeric43.96 ± 5.544.78 ± 4.450.1859Kolmogorov–Smirnov D
bill_depnumeric17.14 ± 1.9817.26 ± 1.610.1288Kolmogorov–Smirnov D
flipper_lennumeric201.3 ± 14.2201.1 ± 11.10.1433Kolmogorov–Smirnov D
body_massnumeric4219 ± 7914173 ± 6080.1052Kolmogorov–Smirnov D
sexcategoricalmale 50.6%male 54.0%0.0340total 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
  ))
))
Python

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

ColumnKindRealSyntheticDistanceMeasure
speciescategoricalAdelie 44.2%Adelie 39.0%0.1001total variation
islandcategoricalBiscoe 48.1%Biscoe 49.0%0.0493total variation
bill_lennumeric43.96 ± 5.544.78 ± 4.450.1859Kolmogorov–Smirnov D
bill_depnumeric17.14 ± 1.9817.26 ± 1.610.1288Kolmogorov–Smirnov D
flipper_lennumeric201.3 ± 14.2201.1 ± 11.10.1433Kolmogorov–Smirnov D
body_massnumeric4219 ± 7914173 ± 6080.1052Kolmogorov–Smirnov D
sexcategoricalmale 50.6%male 54.0%0.0340total 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,
    }},
})
07

What runs here

Read
08

Check: flexible flows

Checkpoint

Check 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.

09

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