Skip to content

Normalizing flows: invertible layers and an exact likelihood

A flow is a stack of invertible layers from data to noise. The change-of-variables formula gives an exact log-likelihood, and coupling layers keep it cheap. Build NICE and Real NVP couplings and read a flow's held-out likelihood.

Advanced ~15 min9 steps

What runs in CodeSplash

You will be able to

  • Apply the change-of-variables formula and say why the log-determinant must be cheap
  • Build an additive (NICE) and an affine (Real NVP) coupling and invert each
  • Use training and held-out log-likelihoods to spot memorizing
  • Say why a high likelihood doesn't flag a row as typical

Read first

01

Invertible all the way

Read

A normalizing flowNormalizing flowA stack of invertible layers that turns each row into normal noise, so noise run backwards gives new rows and likelihoods are exact. is a stack of invertible layers ff that turns a row xx into noise z=f(x)z = f(x) with a simple density, usually a standard normal. Run it backwards and noise becomes a row.

Because every layer can be undone, the density of xx is exact, by the change of variablesChange of variablesThe rule that a density stretched by an invertible map is divided by how much the map stretches volume there.:

log⁡pX(x)=log⁡pZ(f(x))+log⁡∣det⁡∂f(x)∂x∣.\log p_X(x) = \log p_Z\big(f(x)\big) + \log \left| \det \frac{\partial f(x)}{\partial x} \right| .

The second term accounts for how much the layer stretches or squeezes space near xx. For a general d×dd \times d Jacobian it costs on the order of d3d^3. Flows are designed so it is nearly free.

02

Coupling layers

Read

A coupling layerAffine coupling layerA flow layer that scales and shifts half the columns using a small network of the other half; RealNVP stacks them. splits the columns in two halves. The first half passes through unchanged and is used to transform the second:

  • NICE (additive): y2=x2+t(x1)y_2 = x_2 + t(x_1). The Jacobian is triangular with ones on the diagonal, so the log-determinant is exactly 0: volume is preserved.
  • Real NVP (affine): y2=x2⊙es(x1)+t(x1)y_2 = x_2 \odot e^{s(x_1)} + t(x_1). The log-determinant is ∑s(x1)\sum s(x_1), a plain sum.

ss and tt can be any networks, since they are never inverted. To invert, recompute them from y1=x1y_1 = x_1 and undo the shift and scale. Alternating which half passes through lets every column be transformed.

Stack coupling layers and check that the density still adds up to one.

DExplorable · Normalizing flows: change of variables

Why does a normalizing flow need the log-determinant of its Jacobian?

Does the flow's density, as computed here, integrate to 1?

How sure?
3
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.

03

Both couplings by hand

Read

In the reference's NICE example, a two-column row's second value moves to −0.036, the inverse recovers it exactly, and the log-determinant is 0.0. The Real NVP example scales as well as shifts; its log-determinant is 0.114.

Python
import numpy as np
x = np.array([.4, -.7])
s, t = .3 * np.tanh(x[0]), .2 * x[0]             # computed from the half that passes through
y = np.array([x[0], x[1] * np.exp(s) + t])       # affine coupling (Real NVP)
back = np.array([y[0], (y[1] - .2 * y[0]) * np.exp(-.3 * np.tanh(y[0]))])
print(y, back, "log det", s)
R
x <- c(.4, -.7)
s <- .3 * tanh(x[1]); t <- .2 * x[1]             # computed from the half that passes through
y <- c(x[1], x[2] * exp(s) + t)                  # affine coupling (Real NVP)
back <- c(y[1], (y[2] - .2 * y[1]) * exp(-.3 * tanh(y[1])))
print(c(y, back, logdet = s))
04

A NICE flow on iris

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

200 synthetic rows over 4 columns from 150 training rows with a normalizing flow. Numeric columns differ from the data by a mean Kolmogorov–Smirnov distance of 0.144.

Synthetic rows
200
Mean KS distance
0.1442
Mean TV distance
—
Rows copied from the data
0

Plots

sepal_length: real vs syntheticDoes the synthetic data reproduce the shape of a numeric column?
View data
DensitySourcesepal_length
0.2222real4.360
0.0556real4.480
0.2222real4.600
0.1111real4.720
0.2778real4.840
0.8889real4.960
0.5000real5.080
0.2222real5.200
0.0556real5.320
0.3333real5.440
0.7222real5.560
0.4444real5.680
0.3889real5.800
0.1667real5.920
0.6667real6.040
0.2222real6.160
0.5000real6.280
0.3889real6.400
0.2778real6.520
0.1111real6.640
0.6111real6.760
0.2222real6.880
0.0556real7
0.0556real7.120
0.2222real7.240
0.0556real7.360
0real7.480
0.0556real7.600
0.2222real7.720
0.0556real7.840
0.8333synthetic4.360
0.1667synthetic4.480
0.1250synthetic4.600
0.2917synthetic4.720
0.1667synthetic4.840
0.1250synthetic4.960
0.0417synthetic5.080
0.1250synthetic5.200
0.1667synthetic5.320
0.6250synthetic5.440
0.3333synthetic5.560
0.2083synthetic5.680
0.3333synthetic5.800
0.2500synthetic5.920
0.4167synthetic6.040
0.6667synthetic6.160
0.2917synthetic6.280
0.4583synthetic6.400
0.2917synthetic6.520
0.3750synthetic6.640
0.3750synthetic6.760
0.3333synthetic6.880
0.1250synthetic7
0.0833synthetic7.120
0.2500synthetic7.240
0.0417synthetic7.360
0.1250synthetic7.480
0.0417synthetic7.600
0.0833synthetic7.720
0.5833synthetic7.840
sepal_width: real vs syntheticDoes the synthetic data reproduce the shape of a numeric column?
View data
DensitySourcesepal_width
0.0833real2.040
0real2.120
0.2500real2.200
0.3333real2.280
0.2500real2.360
0real2.440
0.6667real2.520
0.4167real2.600
0.7500real2.680
1.167real2.760
0real2.840
0.8333real2.920
2.167real3
0.9167real3.080
0real3.160
1.083real3.240
0.5000real3.320
1real3.400
0.5000real3.480
0.3333real3.560
0real3.640
0.2500real3.720
0.5000real3.800
0.1667real3.880
0.0833real3.960
0real4.040
0.0833real4.120
0.0833real4.200
0real4.280
0.0833real4.360
0.4375synthetic2.040
0.1875synthetic2.120
0.1875synthetic2.200
0.1875synthetic2.280
0.1875synthetic2.360
0.1875synthetic2.440
0.5000synthetic2.520
0.3125synthetic2.600
0.7500synthetic2.680
0.3750synthetic2.760
1.313synthetic2.840
0.9375synthetic2.920
0.8125synthetic3
0.8125synthetic3.080
0.7500synthetic3.160
0.2500synthetic3.240
0.5000synthetic3.320
0.5625synthetic3.400
0.3750synthetic3.480
0.5625synthetic3.560
0.7500synthetic3.640
0.1875synthetic3.720
0.4375synthetic3.800
0.1250synthetic3.880
0.1875synthetic3.960
0.1875synthetic4.040
0synthetic4.120
0synthetic4.200
0synthetic4.280
0.4375synthetic4.360
petal_length: real vs syntheticDoes the synthetic data reproduce the shape of a numeric column?
View data
DensitySourcepetal_length
0.0678real1.098
0.3051real1.295
0.8814real1.492
0.3729real1.688
0.0678real1.885
0real2.082
0real2.278
0real2.475
0real2.672
0real2.868
0.0339real3.065
0.0678real3.262
0.0678real3.458
0.0678real3.655
0.1356real3.852
0.2712real4.048
0.2034real4.245
0.4068real4.442
0.2712real4.638
0.3051real4.835
0.4068real5.032
0.1356real5.228
0.1695real5.425
0.3051real5.622
0.1695real5.818
0.1695real6.015
0.0339real6.212
0.0339real6.408
0.1017real6.605
0.0339real6.802
0.9153synthetic1.098
0.0508synthetic1.295
0.1017synthetic1.492
0.0254synthetic1.688
0.0254synthetic1.885
0.1017synthetic2.082
0synthetic2.278
0.0254synthetic2.475
0.1271synthetic2.672
0.0254synthetic2.868
0.1780synthetic3.065
0.1271synthetic3.262
0.1271synthetic3.458
0.0763synthetic3.655
0.2288synthetic3.852
0.2034synthetic4.048
0.2797synthetic4.245
0.1525synthetic4.442
0.2542synthetic4.638
0.2542synthetic4.835
0.1017synthetic5.032
0.1271synthetic5.228
0.1525synthetic5.425
0.2034synthetic5.622
0.1525synthetic5.818
0.2034synthetic6.015
0.2034synthetic6.212
0.0763synthetic6.408
0.0763synthetic6.605
0.5085synthetic6.802
petal_width: real vs syntheticDoes the synthetic data reproduce the shape of a numeric column?
View data
DensitySourcepetal_width
0.4167real0.1400
2.417real0.2200
0.5833real0.3000
0.5833real0.3800
0real0.4600
0.0833real0.5400
0.0833real0.6200
0real0.7000
0real0.7800
0real0.8600
0real0.9400
0.5833real1.020
0.2500real1.100
0.4167real1.180
0real1.260
1.083real1.340
0.6667real1.420
1real1.500
0.3333real1.580
0.1667real1.660
0real1.740
1real1.820
0.4167real1.900
0.5000real1.980
0real2.060
0.5000real2.140
0.2500real2.220
0.6667real2.300
0.2500real2.380
0.2500real2.460
2synthetic0.1400
0.2500synthetic0.2200
0.1250synthetic0.3000
0synthetic0.3800
0.3125synthetic0.4600
0.0625synthetic0.5400
0.0625synthetic0.6200
0.2500synthetic0.7000
0.0625synthetic0.7800
0.3125synthetic0.8600
0.1875synthetic0.9400
0.3750synthetic1.020
0.0625synthetic1.100
0.3125synthetic1.180
0.8125synthetic1.260
0.3750synthetic1.340
0.5000synthetic1.420
0.5625synthetic1.500
0.6875synthetic1.580
0.6875synthetic1.660
0.3125synthetic1.740
0.2500synthetic1.820
0.3750synthetic1.900
0.5625synthetic1.980
0.3750synthetic2.060
0.2500synthetic2.140
0.3125synthetic2.220
0.2500synthetic2.300
0.3125synthetic2.380
1.500synthetic2.460
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
sepal_widthsepal_length−0.1687
petal_lengthsepal_length0.1526
petal_widthsepal_length0.1455
sepal_lengthsepal_width−0.1687
sepal_widthsepal_width0
petal_lengthsepal_width−0.0472
petal_widthsepal_width−0.0360
sepal_lengthpetal_length0.1526
sepal_widthpetal_length−0.0472
petal_lengthpetal_length0
petal_widthpetal_length0.0237
sepal_lengthpetal_width0.1455
sepal_widthpetal_width−0.0360
petal_lengthpetal_width0.0237
petal_widthpetal_width0
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 rows5.6761
training rows5.5732
training rows5.4663
training rows5.3564
training rows5.2475
training rows5.1436
training rows5.0477
training rows4.9618
training rows4.8859
training rows4.81610
training rows4.74911
training rows4.67812
training rows4.60313
training rows4.52214
training rows4.44115
training rows4.36716
training rows4.30717
training rows4.26918
training rows4.24919
training rows4.23520
training rows4.20921
training rows4.16722
training rows4.11823
training rows4.07124
training rows4.03425
training rows4.00626
training rows3.98427
training rows3.95928
training rows3.92729
training rows3.89030
training rows3.85431
training rows3.82432
training rows3.80033
training rows3.78134
training rows3.76335
training rows3.74436
training rows3.72337
training rows3.70038
training rows3.67939
training rows3.66040

Assumptions

  • Enough rows for a neural generator — 150 complete training rows — neural generators have many weights to learn and can memorize small tables; compare with the copula or sequential trees.
  • Training stayed finite — The negative log-likelihood over the last 10% of epochs averaged 3.69 nats per row.
  • Held-out rows are about as likely as training rows — No complete rows were held out, so generalization can't be checked; set a holdout share to compare.
  • No synthetic row copies a training row — 0 synthetic rows are identical to a training row; the scorecard's distance to closest record checks near-copies.
  • Synthetic columns match the data — Distance from the training rows: numeric columns 0.144 (mean Kolmogorov–Smirnov distance) — above 0.10, so some columns' distributions differ visibly from the data; the scorecard shows which columns and pairs.

Real vs synthetic, column by column

ColumnKindRealSyntheticDistanceMeasure
sepal_lengthnumeric5.843 ± 0.8285.998 ± 1.020.1383Kolmogorov–Smirnov D
sepal_widthnumeric3.057 ± 0.4363.086 ± 0.5350.1133Kolmogorov–Smirnov D
petal_lengthnumeric3.758 ± 1.774.043 ± 1.950.1667Kolmogorov–Smirnov D
petal_widthnumeric1.199 ± 0.7621.377 ± 0.7960.1583Kolmogorov–Smirnov D
The exact R script · R R version 4.5.1 (2025-06-13)
# Synthetic data — normalizing flow (RealNVP, NICE, MAF, Glow, spline)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method synth.flow 1.1.1 · spec c7122e70e00f1251
# Dataset: ml_iris (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)

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

# %% Generate
# Training options, live progress and checkpoints (twin: codesplash.deep.trainer.configure).
cs_deep_trainer_configure(list(
  dp_epsilon = NULL,
  dp_noise_multiplier = NULL,
  dp_max_grad_norm = 1,
  dp_delta = NULL,
  dp_sampling = "poisson",
  optimizer = "default",
  lr_schedule = "none",
  warmup_epochs = 0,
  grad_clip = 0,
  ema_decay = 0,
  swa_start = 0,
  history_every_step = FALSE,
  profile = "parity",
  checkpoint_every = NULL
), out_dir = "target/academy-parity/run-8142/synth.flow/iris_nice_no_holdout/out-r")
# 4 nice layers map standardized numbers and dequantized one-hot categories to N(0, I);
# the exact log-likelihood is the training loss. Twin of codesplash.synth.flows.fit_flow (written from the papers).
HIDDEN <- as.integer(unlist(c(16, 16)))
holdout_cols <- if (length(holdout_rows)) lapply(cols, cs_synth_take, rows = holdout_rows) else NULL
fit <- cs_synth_flow(
  train, N_OUT, HIDDEN,
  kind = "nice",
  layers = as.integer(4),
  epochs = as.integer(40),
  batch_size = NULL,
  lr = 0.005,
  seed = SEED,
  holdout = holdout_cols,
  bins = as.integer(8),  # spline flows only
  tail_bound = 3
)
synth <- fit$cols
hist <- fit$history
history <- data.frame(
  epoch = vapply(hist, function(h) as.numeric(h$epoch), numeric(1)),
  loss = vapply(hist, function(h) h$loss, numeric(1))
)
last <- max(1L, nrow(history) %/% 10L)  # the last 10% of epochs
tail_rows <- (nrow(history) - last + 1L):nrow(history)
fit_values$batch_size <- fit$facts$batch_size
fit_values$dims <- fit$facts$dims
fit_values$final_loss <- mean(history$loss[tail_rows])
fit_values$train_loglik <- fit$facts$train_loglik
if (fit$facts$n_holdout_ll > 0) {
  fit_values$holdout_loglik <- fit$facts$holdout_loglik
  fit_values$n_holdout_ll <- fit$facts$n_holdout_ll
}
model_note <- " with a normalizing flow"
ne <- nrow(history)
extra_charts[[length(extra_charts) + 1L]] <- cs_chart("training", "training-components", "Negative log-likelihood by epoch", list(
  x = cs_col("Epoch", history$epoch, "numeric"),
  value = cs_col("Negative log-likelihood (nats per row)", history$loss, "numeric"),
  component = cs_col("Part", rep("training rows", ne), "categorical", levels = c("training rows"))
), note = "In the flow's coordinates (standardized numbers, dequantized categories); lower is better.")
finite <- all(is.finite(history$loss))
assumptions[[length(assumptions) + 1L]] <- list(
  key = "training_stable", label = "Training stayed finite",
  status = if (finite) "pass" else "fail",
  detail = if (finite) sprintf("The negative log-likelihood over the last 10%% of epochs averaged %s nats per row.", format(signif(fit_values$final_loss, 3)))
           else "The loss became infinite or undefined; lower the learning rate or use fewer layers."
)
if (fit$facts$n_holdout_ll > 0) {
  gap <- fit$facts$train_loglik - fit$facts$holdout_loglik
  ok <- isTRUE(gap <= 1)
  assumptions[[length(assumptions) + 1L]] <- list(
    key = "generalizes", label = "Held-out rows are about as likely as training rows",
    status = if (ok) "pass" else "warn",
    detail = paste0(sprintf("Mean log-likelihood %s nats per training row and %s per held-out row",
                            format(signif(fit$facts$train_loglik, 3)), format(signif(fit$facts$holdout_loglik, 3))),
                    if (ok) "." else " — training rows are far more likely, so the flow is memorizing them; use fewer epochs or layers.")
  )
} else {
  assumptions[[length(assumptions) + 1L]] <- list(
    key = "generalizes", label = "Held-out rows are about as likely as training rows", status = "info",
    detail = "No complete rows were held out, so generalization can't be checked; set a holdout share to compare."
  )
}
if (isTRUE(fit$facts$dequantized)) {
  warnings <- c(warnings, "Categories are smoothed with uniform noise (dequantization), so the log-likelihoods are lower bounds for the category part.")
}
synth <- cs_synth_add_missing(synth, train, rng, "keep_rate")  # each column's missing share, at random

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

200 synthetic rows over 4 columns from 150 training rows with a normalizing flow. Numeric columns differ from the data by a mean Kolmogorov–Smirnov distance of 0.144.

Synthetic rows
200
Mean KS distance
0.1442
Mean TV distance
—
Rows copied from the data
0

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

Assumptions

  • Enough rows for a neural generator — 150 complete training rows — neural generators have many weights to learn and can memorize small tables; compare with the copula or sequential trees.
  • Training stayed finite — The negative log-likelihood over the last 10% of epochs averaged 3.69 nats per row.
  • Held-out rows are about as likely as training rows — No complete rows were held out, so generalization can't be checked; set a holdout share to compare.
  • No synthetic row copies a training row — 0 synthetic rows are identical to a training row; the scorecard's distance to closest record checks near-copies.
  • Synthetic columns match the data — Distance from the training rows: numeric columns 0.144 (mean Kolmogorov–Smirnov distance) — above 0.10, so some columns' distributions differ visibly from the data; the scorecard shows which columns and pairs.

Real vs synthetic, column by column

ColumnKindRealSyntheticDistanceMeasure
sepal_lengthnumeric5.843 ± 0.8285.998 ± 1.020.1383Kolmogorov–Smirnov D
sepal_widthnumeric3.057 ± 0.4363.086 ± 0.5350.1133Kolmogorov–Smirnov D
petal_lengthnumeric3.758 ± 1.774.043 ± 1.950.1667Kolmogorov–Smirnov D
petal_widthnumeric1.199 ± 0.7621.377 ± 0.7960.1583Kolmogorov–Smirnov D
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Synthetic data — normalizing flow (RealNVP, NICE, MAF, Glow, spline)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method synth.flow 1.1.1 · spec c7122e70e00f1251
# Dataset: ml_iris (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os

import numpy as np
import pandas as pd

import codesplash as cs
from codesplash.errors import check_finite
from codesplash.ml.run import out_dir
from codesplash.stats.rng import Rng
from codesplash.synth import common as sy
from codesplash.synth import flows  # twin of codesplashr::cs_synth_flow (RealNVP, NICE, MAF, Glow, spline flows; written from the papers)

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

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

deep_trainer.configure(
    {
        "dp_epsilon": None,
        "dp_noise_multiplier": None,
        "dp_max_grad_norm": 1,
        "dp_delta": None,
        "dp_sampling": "poisson",
        "optimizer": "default",
        "lr_schedule": "none",
        "warmup_epochs": 0,
        "grad_clip": 0,
        "ema_decay": 0,
        "swa_start": 0,
        "history_every_step": False,
        "profile": "parity",
        "checkpoint_every": None,
    },
    out_dir="target/academy-parity/run-8142/synth.flow/iris_nice_no_holdout/out-python",
)
# 4 nice layers map standardized numbers and dequantized one-hot categories to N(0, I);
# the exact log-likelihood is the training loss, and running the flow backwards turns noise into rows.
HIDDEN = [int(u) for u in [16, 16]]
holdout_cols = [c.take(holdout_rows) for c in cols] if len(holdout_rows) else None
synth, facts, hist = flows.fit_flow(
    train, N_OUT, HIDDEN,
    kind="nice",
    layers=4,
    epochs=40,
    batch_size=None,
    lr=0.005,
    seed=SEED,
    holdout=holdout_cols,
    bins=8,  # spline flows only
    tail_bound=3,
)
history = pd.DataFrame(hist)
last = max(1, len(hist) // 10)  # the last 10% of epochs
fit_values["batch_size"] = facts["batch_size"]
fit_values["dims"] = facts["dims"]
fit_values["final_loss"] = float(np.mean([h["loss"] for h in hist[-last:]]))
fit_values["train_loglik"] = facts["train_loglik"]
if facts["n_holdout_ll"] > 0:
    fit_values["holdout_loglik"] = facts["holdout_loglik"]
    fit_values["n_holdout_ll"] = facts["n_holdout_ll"]
model_note = " with a normalizing flow"
ep = history["epoch"].tolist()
extra_charts.append(cs.chart("training", "training-components", "Negative log-likelihood by epoch", {
    "x": cs.col("Epoch", ep, "numeric"),
    "value": cs.col("Negative log-likelihood (nats per row)", history["loss"].tolist(), "numeric"),
    "component": cs.col("Part", ["training rows"] * len(ep), "categorical", levels=["training rows"]),
}, note="In the flow's coordinates (standardized numbers, dequantized categories); lower is better."))
finite = bool(np.all(np.isfinite(history["loss"].to_numpy())))
assumptions.append({
    "key": "training_stable",
    "label": "Training stayed finite",
    "status": "pass" if finite else "fail",
    "detail": f"The negative log-likelihood over the last 10% of epochs averaged {fit_values['final_loss']:.3g} nats per row." if finite else "The loss became infinite or undefined; lower the learning rate or use fewer layers.",
})
if facts["n_holdout_ll"] > 0:
    gap = facts["train_loglik"] - facts["holdout_loglik"]
    assumptions.append({
        "key": "generalizes",
        "label": "Held-out rows are about as likely as training rows",
        "status": "warn" if not gap <= 1.0 else "pass",
        "detail": f"Mean log-likelihood {facts['train_loglik']:.3g} nats per training row and {facts['holdout_loglik']:.3g} per held-out row"
                  + (" — training rows are far more likely, so the flow is memorizing them; use fewer epochs or layers." if not gap <= 1.0 else "."),
    })
else:
    assumptions.append({
        "key": "generalizes",
        "label": "Held-out rows are about as likely as training rows",
        "status": "info",
        "detail": "No complete rows were held out, so generalization can't be checked; set a holdout share to compare.",
    })
if facts["dequantized"]:
    warnings.append("Categories are smoothed with uniform noise (dequantization), so the log-likelihoods are lower bounds for the category part.")
sy.add_missing(synth, train, rng, "keep_rate")  # each column's missing share, at random

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

Flow: NICE stacks additive couplings, so the only volume change comes from a final per-column scale. On the four iris measurements the mean log-likelihood per training row is −2.908 nats. With no holdout there is nothing to compare it with, so this run says how well the flow fits, not how well it generalizes.

05

Training against held-out rows

Explore
Synthetic data — normalizing flow (RealNVP, NICE, MAF, Glow, spline)Recorded · Python and R agreeRecorded 2026-11-25 · 52 values compared · largest relative difference 2.5e-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.073 and categories by a mean total variation of 0.054.

Synthetic rows
320
Mean KS distance
0.0728
Mean TV distance
0.0538
Rows copied from the data
0

Plots

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.0148synthetic18.950
0.0049synthetic20.850
0.0082synthetic22.750
0.0049synthetic24.650
0.0132synthetic26.550
0.0197synthetic28.450
0.0247synthetic30.350
0.0280synthetic32.250
0.0263synthetic34.150
0.0049synthetic36.050
0.0230synthetic37.950
0.0280synthetic39.850
0.0329synthetic41.750
0.0428synthetic43.650
0.0197synthetic45.550
0.0378synthetic47.450
0.0197synthetic49.350
0.0329synthetic51.250
0.0230synthetic53.150
0.0082synthetic55.050
0.0296synthetic56.950
0.0148synthetic58.850
0.0132synthetic60.750
0.0132synthetic62.650
0.0066synthetic64.550
0.0049synthetic66.450
0.0082synthetic68.350
0.0066synthetic70.250
0.0016synthetic72.150
0.0099synthetic74.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
2.107e-5synthetic6851.93
8.026e-6synthetic10141.74
1.104e-5synthetic13431.55
2.508e-5synthetic16721.36
2.006e-5synthetic20011.17
3.511e-5synthetic23300.98
2.508e-5synthetic26590.79
2.809e-5synthetic29880.60
2.709e-5synthetic33170.41
2.608e-5synthetic36460.22
2.107e-5synthetic39750.03
1.806e-5synthetic43039.84
1.304e-5synthetic46329.65
1.104e-5synthetic49619.46
6.019e-6synthetic52909.27
3.010e-6synthetic56199.07
2.006e-6synthetic59488.88
1.003e-6synthetic62778.69
1.003e-6synthetic66068.50
0synthetic69358.31
1.003e-6synthetic72648.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.0815synthetic0.7667
0.0326synthetic2.300
0.0122synthetic3.833
0.0489synthetic5.367
0.0143synthetic6.900
0.0387synthetic8.433
0.0102synthetic9.967
0.0346synthetic11.500
0.0326synthetic13.033
0.0448synthetic14.567
0.0204synthetic16.100
0.0469synthetic17.633
0.0306synthetic19.167
0.0428synthetic20.700
0.0285synthetic22.233
0.0265synthetic23.767
0.0367synthetic25.300
0.0102synthetic26.833
0.0102synthetic28.367
0.0163synthetic29.900
0.0122synthetic31.433
0.0020synthetic32.967
0.0020synthetic34.500
0.0041synthetic36.033
0.0020synthetic37.567
0synthetic39.100
0.0061synthetic40.633
0synthetic42.167
0synthetic43.700
0.0041synthetic45.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.0003synthetic17582.23
0.0003synthetic17654.70
0.0003synthetic17727.17
0.0001synthetic17799.63
0.0004synthetic17872.10
0.0006synthetic17944.57
0.0006synthetic18017.03
0.0004synthetic18089.50
0.0008synthetic18161.97
0.0006synthetic18234.43
0.0003synthetic18306.90
0.0005synthetic18379.37
0.0007synthetic18451.83
0.0009synthetic18524.30
0.0008synthetic18596.77
0.0007synthetic18669.23
0.0003synthetic18741.70
0.0008synthetic18814.17
0.0003synthetic18886.63
0.0005synthetic18959.10
0.0005synthetic19031.57
0.0006synthetic19104.03
0.0004synthetic19176.50
0.0003synthetic19248.97
0.0003synthetic19321.43
0.0003synthetic19393.90
0.0003synthetic19466.37
0.0002synthetic19538.83
0.0001synthetic19611.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.3719synthetic
plus0.3625synthetic
premium0.2656synthetic
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.2812synthetic
north0.2652synthetic
south0.2812synthetic
west0.1725synthetic
churned: real vs syntheticDoes the synthetic data keep the category proportions of the real data?
View data
churnedShareSource
false0.7688real
true0.2313real
false0.6750synthetic
true0.3250synthetic
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.0956
tenure_monthsage0.7348
signupage−0.0327
visitsage0.0324
ageannual income0.0956
annual incomeannual income0
tenure_monthsannual income0.0573
signupannual income0.0140
visitsannual income0.2546
agetenure_months0.7348
annual incometenure_months0.0573
tenure_monthstenure_months0
signuptenure_months−0.1054
visitstenure_months0.0467
agesignup−0.0327
annual incomesignup0.0140
tenure_monthssignup−0.1054
signupsignup0
visitssignup0.0635
agevisits0.0324
annual incomevisits0.2546
tenure_monthsvisits0.0467
signupvisits0.0635
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 rows17.1251
training rows16.7542
training rows16.4823
training rows16.1284
training rows15.8925
training rows15.5526
training rows15.2147
training rows15.0168
training rows14.7629
training rows14.58110
training rows14.33511
training rows14.21312
training rows14.25613
training rows14.28214
training rows14.04615
training rows13.94716
training rows13.92717
training rows13.86818
training rows13.79419
training rows13.66820

Assumptions

  • Enough rows for a neural generator — 293 complete training rows — neural generators have many weights to learn and can memorize small tables; compare with the copula or sequential trees.
  • Training stayed finite — The negative log-likelihood over the last 10% of epochs averaged 13.7 nats per row.
  • Held-out rows are about as likely as training rows — Mean log-likelihood -35.1 nats per training row and -35.4 per held-out row.
  • No synthetic row copies a training row — 0 synthetic rows are identical to a training row; the scorecard's distance to closest record checks near-copies.
  • Synthetic columns match the data — Distance from the training rows: numeric columns 0.073 (mean Kolmogorov–Smirnov distance); categories 0.054 (mean total variation) — at most 0.10, which the Synthetic studio's scorecard rates as good column fidelity.

Real vs synthetic, column by column

ColumnKindRealSyntheticDistanceMeasure
agenumeric43.14 ± 13.144.41 ± 12.90.0844Kolmogorov–Smirnov D
annual incomenumeric2.929e+04 ± 1.43e+042.938e+04 ± 1.31e+040.0891Kolmogorov–Smirnov D
tenure_monthsnumeric15 ± 10.714.49 ± 9.960.0469Kolmogorov–Smirnov D
plancategoricalplus 39.7%plus 36.2%0.0344total variation
regioncategoricalsouth 30.4%south 28.1%0.0334total variation
churnedbooleanfalse 76.9%false 67.5%0.0938total variation
signuptemporal2020-11-05 ± 621 days2020-11-19 ± 542 days0.0938Kolmogorov–Smirnov D
visitsnumeric3.394 ± 2.093.225 ± 1.980.0500Kolmogorov–Smirnov D
  • 80 of 400 rows (20%) were held out of training so privacy and utility can be checked against rows the generator never saw.
  • Categories are smoothed with uniform noise (dequantization), so the log-likelihoods are lower bounds for the category part.
The exact R script · R R version 4.5.1 (2025-06-13)
# Synthetic data — normalizing flow (RealNVP, NICE, MAF, Glow, spline)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method synth.flow 1.1.1 · spec 0e3358a16f893167
# Dataset: g1_customers (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)

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

# %% Generate
# Training options, live progress and checkpoints (twin: codesplash.deep.trainer.configure).
cs_deep_trainer_configure(list(
  dp_epsilon = NULL,
  dp_noise_multiplier = NULL,
  dp_max_grad_norm = 1,
  dp_delta = NULL,
  dp_sampling = "poisson",
  optimizer = "default",
  lr_schedule = "none",
  warmup_epochs = 0,
  grad_clip = 0,
  ema_decay = 0,
  swa_start = 0,
  history_every_step = FALSE,
  profile = "parity",
  checkpoint_every = NULL
), out_dir = "target/academy-parity/run-8142/synth.flow/customers_realnvp/out-r")
# 4 realnvp layers map standardized numbers and dequantized one-hot categories to N(0, I);
# the exact log-likelihood is the training loss. Twin of codesplash.synth.flows.fit_flow (written from the papers).
HIDDEN <- as.integer(unlist(c(16, 16)))
holdout_cols <- if (length(holdout_rows)) lapply(cols, cs_synth_take, rows = holdout_rows) else NULL
fit <- cs_synth_flow(
  train, N_OUT, HIDDEN,
  kind = "realnvp",
  layers = as.integer(4),
  epochs = as.integer(20),
  batch_size = 100,
  lr = 0.001,
  seed = SEED,
  holdout = holdout_cols,
  bins = as.integer(8),  # spline flows only
  tail_bound = 3
)
synth <- fit$cols
hist <- fit$history
history <- data.frame(
  epoch = vapply(hist, function(h) as.numeric(h$epoch), numeric(1)),
  loss = vapply(hist, function(h) h$loss, numeric(1))
)
last <- max(1L, nrow(history) %/% 10L)  # the last 10% of epochs
tail_rows <- (nrow(history) - last + 1L):nrow(history)
fit_values$batch_size <- fit$facts$batch_size
fit_values$dims <- fit$facts$dims
fit_values$final_loss <- mean(history$loss[tail_rows])
fit_values$train_loglik <- fit$facts$train_loglik
if (fit$facts$n_holdout_ll > 0) {
  fit_values$holdout_loglik <- fit$facts$holdout_loglik
  fit_values$n_holdout_ll <- fit$facts$n_holdout_ll
}
model_note <- " with a normalizing flow"
ne <- nrow(history)
extra_charts[[length(extra_charts) + 1L]] <- cs_chart("training", "training-components", "Negative log-likelihood by epoch", list(
  x = cs_col("Epoch", history$epoch, "numeric"),
  value = cs_col("Negative log-likelihood (nats per row)", history$loss, "numeric"),
  component = cs_col("Part", rep("training rows", ne), "categorical", levels = c("training rows"))
), note = "In the flow's coordinates (standardized numbers, dequantized categories); lower is better.")
finite <- all(is.finite(history$loss))
assumptions[[length(assumptions) + 1L]] <- list(
  key = "training_stable", label = "Training stayed finite",
  status = if (finite) "pass" else "fail",
  detail = if (finite) sprintf("The negative log-likelihood over the last 10%% of epochs averaged %s nats per row.", format(signif(fit_values$final_loss, 3)))
           else "The loss became infinite or undefined; lower the learning rate or use fewer layers."
)
if (fit$facts$n_holdout_ll > 0) {
  gap <- fit$facts$train_loglik - fit$facts$holdout_loglik
  ok <- isTRUE(gap <= 1)
  assumptions[[length(assumptions) + 1L]] <- list(
    key = "generalizes", label = "Held-out rows are about as likely as training rows",
    status = if (ok) "pass" else "warn",
    detail = paste0(sprintf("Mean log-likelihood %s nats per training row and %s per held-out row",
                            format(signif(fit$facts$train_loglik, 3)), format(signif(fit$facts$holdout_loglik, 3))),
                    if (ok) "." else " — training rows are far more likely, so the flow is memorizing them; use fewer epochs or layers.")
  )
} else {
  assumptions[[length(assumptions) + 1L]] <- list(
    key = "generalizes", label = "Held-out rows are about as likely as training rows", status = "info",
    detail = "No complete rows were held out, so generalization can't be checked; set a holdout share to compare."
  )
}
if (isTRUE(fit$facts$dequantized)) {
  warnings <- c(warnings, "Categories are smoothed with uniform noise (dequantization), so the log-likelihoods are lower bounds for the category part.")
}
synth <- cs_synth_add_missing(synth, train, rng, "keep_rate")  # each column's missing share, at random

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

Synthetic rows
320
Mean KS distance
0.0728
Mean TV distance
0.0538
Rows copied from the data
0

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

Assumptions

  • Enough rows for a neural generator — 293 complete training rows — neural generators have many weights to learn and can memorize small tables; compare with the copula or sequential trees.
  • Training stayed finite — The negative log-likelihood over the last 10% of epochs averaged 13.7 nats per row.
  • Held-out rows are about as likely as training rows — Mean log-likelihood -35.1 nats per training row and -35.4 per held-out row.
  • No synthetic row copies a training row — 0 synthetic rows are identical to a training row; the scorecard's distance to closest record checks near-copies.
  • Synthetic columns match the data — Distance from the training rows: numeric columns 0.073 (mean Kolmogorov–Smirnov distance); categories 0.054 (mean total variation) — at most 0.10, which the Synthetic studio's scorecard rates as good column fidelity.

Real vs synthetic, column by column

ColumnKindRealSyntheticDistanceMeasure
agenumeric43.14 ± 13.144.41 ± 12.90.0844Kolmogorov–Smirnov D
annual incomenumeric2.929e+04 ± 1.43e+042.938e+04 ± 1.31e+040.0891Kolmogorov–Smirnov D
tenure_monthsnumeric15 ± 10.714.49 ± 9.960.0469Kolmogorov–Smirnov D
plancategoricalplus 39.7%plus 36.2%0.0344total variation
regioncategoricalsouth 30.4%south 28.1%0.0334total variation
churnedbooleanfalse 76.9%false 67.5%0.0938total variation
signuptemporal2020-11-05 ± 621 days2020-11-19 ± 542 days0.0938Kolmogorov–Smirnov D
visitsnumeric3.394 ± 2.093.225 ± 1.980.0500Kolmogorov–Smirnov D
  • 80 of 400 rows (20%) were held out of training so privacy and utility can be checked against rows the generator never saw.
  • Categories are smoothed with uniform noise (dequantization), so the log-likelihoods are lower bounds for the category part.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Synthetic data — normalizing flow (RealNVP, NICE, MAF, Glow, spline)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method synth.flow 1.1.1 · spec 0e3358a16f893167
# Dataset: g1_customers (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os

import numpy as np
import pandas as pd

import codesplash as cs
from codesplash.errors import check_finite
from codesplash.ml.run import out_dir
from codesplash.stats.rng import Rng
from codesplash.synth import common as sy
from codesplash.synth import flows  # twin of codesplashr::cs_synth_flow (RealNVP, NICE, MAF, Glow, spline flows; written from the papers)

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

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

deep_trainer.configure(
    {
        "dp_epsilon": None,
        "dp_noise_multiplier": None,
        "dp_max_grad_norm": 1,
        "dp_delta": None,
        "dp_sampling": "poisson",
        "optimizer": "default",
        "lr_schedule": "none",
        "warmup_epochs": 0,
        "grad_clip": 0,
        "ema_decay": 0,
        "swa_start": 0,
        "history_every_step": False,
        "profile": "parity",
        "checkpoint_every": None,
    },
    out_dir="target/academy-parity/run-8142/synth.flow/customers_realnvp/out-python",
)
# 4 realnvp layers map standardized numbers and dequantized one-hot categories to N(0, I);
# the exact log-likelihood is the training loss, and running the flow backwards turns noise into rows.
HIDDEN = [int(u) for u in [16, 16]]
holdout_cols = [c.take(holdout_rows) for c in cols] if len(holdout_rows) else None
synth, facts, hist = flows.fit_flow(
    train, N_OUT, HIDDEN,
    kind="realnvp",
    layers=4,
    epochs=20,
    batch_size=100,
    lr=0.001,
    seed=SEED,
    holdout=holdout_cols,
    bins=8,  # spline flows only
    tail_bound=3,
)
history = pd.DataFrame(hist)
last = max(1, len(hist) // 10)  # the last 10% of epochs
fit_values["batch_size"] = facts["batch_size"]
fit_values["dims"] = facts["dims"]
fit_values["final_loss"] = float(np.mean([h["loss"] for h in hist[-last:]]))
fit_values["train_loglik"] = facts["train_loglik"]
if facts["n_holdout_ll"] > 0:
    fit_values["holdout_loglik"] = facts["holdout_loglik"]
    fit_values["n_holdout_ll"] = facts["n_holdout_ll"]
model_note = " with a normalizing flow"
ep = history["epoch"].tolist()
extra_charts.append(cs.chart("training", "training-components", "Negative log-likelihood by epoch", {
    "x": cs.col("Epoch", ep, "numeric"),
    "value": cs.col("Negative log-likelihood (nats per row)", history["loss"].tolist(), "numeric"),
    "component": cs.col("Part", ["training rows"] * len(ep), "categorical", levels=["training rows"]),
}, note="In the flow's coordinates (standardized numbers, dequantized categories); lower is better."))
finite = bool(np.all(np.isfinite(history["loss"].to_numpy())))
assumptions.append({
    "key": "training_stable",
    "label": "Training stayed finite",
    "status": "pass" if finite else "fail",
    "detail": f"The negative log-likelihood over the last 10% of epochs averaged {fit_values['final_loss']:.3g} nats per row." if finite else "The loss became infinite or undefined; lower the learning rate or use fewer layers.",
})
if facts["n_holdout_ll"] > 0:
    gap = facts["train_loglik"] - facts["holdout_loglik"]
    assumptions.append({
        "key": "generalizes",
        "label": "Held-out rows are about as likely as training rows",
        "status": "warn" if not gap <= 1.0 else "pass",
        "detail": f"Mean log-likelihood {facts['train_loglik']:.3g} nats per training row and {facts['holdout_loglik']:.3g} per held-out row"
                  + (" — training rows are far more likely, so the flow is memorizing them; use fewer epochs or layers." if not gap <= 1.0 else "."),
    })
else:
    assumptions.append({
        "key": "generalizes",
        "label": "Held-out rows are about as likely as training rows",
        "status": "info",
        "detail": "No complete rows were held out, so generalization can't be checked; set a holdout share to compare.",
    })
if facts["dequantized"]:
    warnings.append("Categories are smoothed with uniform noise (dequantization), so the log-likelihoods are lower bounds for the category part.")
sy.add_missing(synth, train, rng, "keep_rate")  # each column's missing share, at random

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

The default Real NVP flow on the customer table holds out rows and scores them too: −35.15 nats per training row against −35.43 per held-out row. About the same, so no sign of memorizing. A training value pulling far ahead of the held-out one would be the warning.

Categories get uniform noise first (dequantizationDequantizationAdding uniform noise to discrete values so a continuous density can model them; its likelihood is a lower bound.), so their part of the likelihood is a lower bound.

06

A likely row isn't a typical row

Predict

Predict first

You want to flag unusual rows using a flow's exact log-likelihood. What's the safer plan?

Flag rows with low likelihood as unusual and trust itTreat likelihood as one signal and check it on known unusual rows
Reveal

Check it on known unusual rows first. Flows can give higher likelihood to some inputs unlike the training data, for example smooth or low-variance ones, because likelihood mixes "how typical" with "how simple". Calibrate any cutoff on rows with known labels.

07

What runs here

Read
08

Check: flows

Checkpoint

Check yourself

What is the log-determinant of a NICE additive coupling layer?

Show the answer

Answer: 0

y2=x2+t(x1)y_2 = x_2 + t(x_1) has a triangular Jacobian with ones on the diagonal, so its determinant is 1 and its log is 0. NICE couplings preserve volume.

Check yourself

To invert y2=x2+t(x1)y_2 = x_2 + t(x_1), what do you need?

Show the answer

Answer: a

The passed-through half is unchanged, so t(y1)=t(x1)t(y_1) = t(x_1) and x2=y2−t(y1)x_2 = y_2 - t(y_1). The network tt itself is never inverted.

Check yourself

What is the log-determinant of a Real NVP affine coupling y2=x2es(x1)+t(x1)y_2 = x_2 e^{s(x_1)} + t(x_1)?

Show the answer

Answer: b

The Jacobian is triangular with ese^{s} on the transformed part of the diagonal, so the log-determinant is the sum of ss.

Check yourself

A flow's mean log-likelihood is much higher on training rows than on held-out rows. What does that suggest?

Show the answer

Answer: a

The exact likelihood makes this check possible, which GANs can't offer. A gap like that also means generated rows may sit too close to real ones.

Check yourself

Is a row with high likelihood under a flow necessarily typical of the training data?

Show the answer

Answer: b

An exact density is not a typicality test. Some out-of-distribution inputs get higher likelihood than real data.

09

Recap

Recap
  • A flow is invertible; the change of variables gives an exact log-likelihood.
  • Coupling layers keep the log-determinant cheap: 0 for NICE, a sum of scales for Real NVP.
  • Compare training and held-out log-likelihoods to spot memorizing.
  • High likelihood is not a typicality check. CodeSplash runs both couplings in synth.flow.

Concepts in this lesson