Skip to content

Flow matching: learn the velocity from noise to data

Draw a straight line from a noise draw to a real row and ask a network for the velocity along it. Averaged over many lines, that velocity carries noise to data. Sample with an ODE solver in a handful of steps.

Advanced ~13 min9 steps

What runs in CodeSplash

You will be able to

  • Write the straight-line path and its target velocity
  • Explain why the flow-matching loss levels off above zero
  • Choose sampler steps and read the evaluations they cost
  • Compare flow matching with diffusion on the same scorecard

Read first

01

A straight line per pair

Read

Flow matchingFlow matchingTraining a network to give the velocity that moves noise straight to data; new rows follow it from time 0 to 1. picks a noise draw x0x_0, a real row x1x_1 and a time tt between 0 and 1, and places a point on the straight line between them. The velocity along that line is constant:

xt=(1−t) x0+t x1,ut=x1−x0.x_t = (1 - t)\, x_0 + t\, x_1, \qquad u_t = x_1 - x_0 .

A network vθ(xt,t)v_\theta(x_t, t) is trained to output that velocity:

L=Et,x0,x1∥vθ(xt,t)−(x1−x0)∥2.L = \mathbb{E}_{t, x_0, x_1} \left\lVert v_\theta(x_t, t) - (x_1 - x_0) \right\rVert^2 .

No simulation, no noise schedule to tune, no likelihood: one regression per training point.

02

Two points by hand

Read

The reference places two points on their lines, one a quarter of the way and one three quarters. The first lands at (0.40, −0.125), and its target velocity is (0.8, 1.5). The program also checks that velocity against a numerical derivative of the path.

Python
import numpy as np
x0 = np.array([[.2, -.5], [.1, .4]])   # noise draws
x1 = np.array([[1., 1.], [-1., .5]])   # real rows
t = np.array([[.25], [.75]])
xt = (1 - t) * x0 + t * x1             # points on the straight lines
print(xt, x1 - x0)                      # and the target velocities
R
x0 <- matrix(c(.2, -.5, .1, .4), 2, byrow = TRUE)   # noise draws
x1 <- matrix(c(1, 1, -1, .5), 2, byrow = TRUE)      # real rows
t <- c(.25, .75)
xt <- (1 - t) * x0 + t * x1                          # points on the straight lines
print(list(xt, x1 - x0))                             # and the target velocities
03

Why the loss stays above zero

Predict

Predict first

You train flow matching for a long time. Where should its loss end up?

It should reach zero with enough trainingIt levels off above zero, by design
Reveal

Above zero. Many lines from different noise–row pairs cross the same point with different velocities, and one network output can only give their average there. That average is exactly what carries noise to data, so a floor above zero is expected, not a failure.

Exact velocities on a ring of modes: count the Euler steps the samples need.

DExplorable · Flow matching: straight paths

Why can flow matching sample in a few steps, and when does it still need more?

With this many Euler steps, where do the samples end up?

How sure?

Path

Straight: x_t = (1 − t)x₀ + t·x₁. Curved: the variance-preserving path of diffusion.

8
6
0.20
300
  • Sample paths
  • Where samples end
  • Modes (three spreads)

Path length ÷ straight line: 1.320

Distance to the nearest mode: 0.235

Largest gap between a mode's share and its weight: 0.043

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.

04

Flow matching in CodeSplash

Explore
Synthetic data — flow matchingRecorded · Python and R agreeRecorded 2026-11-25 · 50 values compared · largest relative difference 2.2e-15
R

320 synthetic rows over 8 columns from 320 training rows with flow matching. Numeric columns differ from the data by a mean Kolmogorov–Smirnov distance of 0.049 and categories by a mean total variation of 0.093.

Synthetic rows
320
Mean KS distance
0.0492
Mean TV distance
0.0928
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.0461synthetic18.950
0.0016synthetic20.850
0.0033synthetic22.750
0.0230synthetic24.650
0.0115synthetic26.550
0.0164synthetic28.450
0.0214synthetic30.350
0.0296synthetic32.250
0.0247synthetic34.150
0.0115synthetic36.050
0.0362synthetic37.950
0.0280synthetic39.850
0.0148synthetic41.750
0.0345synthetic43.650
0.0197synthetic45.550
0.0148synthetic47.450
0.0214synthetic49.350
0.0148synthetic51.250
0.0411synthetic53.150
0.0082synthetic55.050
0.0197synthetic56.950
0.0132synthetic58.850
0.0115synthetic60.750
0.0132synthetic62.650
0.0049synthetic64.550
0.0066synthetic66.450
0.0099synthetic68.350
0.0115synthetic70.250
0.0049synthetic72.150
0.0082synthetic74.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
3.010e-6synthetic6851.93
1.705e-5synthetic10141.74
2.006e-5synthetic13431.55
2.207e-5synthetic16721.36
3.612e-5synthetic20011.17
3.812e-5synthetic23300.98
2.207e-5synthetic26590.79
2.608e-5synthetic29880.60
2.307e-5synthetic33170.41
1.705e-5synthetic36460.22
1.705e-5synthetic39750.03
2.207e-5synthetic43039.84
7.022e-6synthetic46329.65
6.019e-6synthetic49619.46
9.029e-6synthetic52909.27
4.013e-6synthetic56199.07
6.019e-6synthetic59488.88
4.013e-6synthetic62778.69
1.003e-6synthetic66068.50
0synthetic69358.31
1.003e-6synthetic72648.12
0synthetic75937.93
0synthetic79227.74
0synthetic82517.55
0synthetic85807.36
0synthetic89097.17
0synthetic92386.98
1.003e-6synthetic95676.79
1.003e-6synthetic98966.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.1121synthetic0.7667
0.0265synthetic2.300
0.0143synthetic3.833
0.0245synthetic5.367
0.0122synthetic6.900
0.0163synthetic8.433
0.0102synthetic9.967
0.0530synthetic11.500
0.0102synthetic13.033
0.0367synthetic14.567
0.0143synthetic16.100
0.0367synthetic17.633
0.0285synthetic19.167
0.0448synthetic20.700
0.0510synthetic22.233
0.0102synthetic23.767
0.0346synthetic25.300
0.0020synthetic26.833
0.0285synthetic28.367
0.0061synthetic29.900
0.0346synthetic31.433
0.0082synthetic32.967
0.0183synthetic34.500
0synthetic36.033
0.0061synthetic37.567
0synthetic39.100
0.0041synthetic40.633
0.0020synthetic42.167
0.0041synthetic43.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.0003synthetic17582.23
0.0006synthetic17654.70
0.0006synthetic17727.17
0.0008synthetic17799.63
0.0005synthetic17872.10
0.0007synthetic17944.57
0.0005synthetic18017.03
0.0002synthetic18089.50
0.0006synthetic18161.97
0.0004synthetic18234.43
0.0002synthetic18306.90
0.0007synthetic18379.37
0.0003synthetic18451.83
0.0003synthetic18524.30
0.0007synthetic18596.77
0.0005synthetic18669.23
0.0004synthetic18741.70
0.0005synthetic18814.17
0.0007synthetic18886.63
0.0005synthetic18959.10
0.0006synthetic19031.57
0.0004synthetic19104.03
0.0005synthetic19176.50
0.0006synthetic19248.97
0.0003synthetic19321.43
0.0003synthetic19393.90
0.0001synthetic19466.37
0.0004synthetic19538.83
0.0003synthetic19611.30
0.0003synthetic19683.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.3750synthetic
plus0.3344synthetic
premium0.2906synthetic
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.3514synthetic
north0.2204synthetic
south0.2428synthetic
west0.1853synthetic
churned: real vs syntheticDoes the synthetic data keep the category proportions of the real data?
View data
churnedShareSource
false0.7688real
true0.2313real
false0.6656synthetic
true0.3344synthetic
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.1622
tenure_monthsage0.7205
signupage−0.0666
visitsage−0.0917
ageannual income0.1622
annual incomeannual income0
tenure_monthsannual income0.1429
signupannual income−0.0486
visitsannual income0.2082
agetenure_months0.7205
annual incometenure_months0.1429
tenure_monthstenure_months0
signuptenure_months−0.1531
visitstenure_months−0.0793
agesignup−0.0666
annual incomesignup−0.0486
tenure_monthssignup−0.1531
signupsignup0
visitssignup−0.0522
agevisits−0.0917
annual incomevisits0.2082
tenure_monthsvisits−0.0793
signupvisits−0.0522
visitsvisits0
Velocity loss by epochIs the network still learning, and which part of its loss moves?

The loss can't reach 0: many noise–row pairs cross the same point with different velocities, so it levels off.

View data
PartMean squared velocity errorEpoch
training rows1.9191
training rows1.8152
training rows1.8183
training rows1.8554
training rows1.8185
training rows1.6726
training rows1.6007
training rows1.6158
training rows1.6169
training rows1.57710
training rows1.52911
training rows1.60512
training rows1.55013
training rows1.65114
training rows1.61815
training rows1.53516
training rows1.55517
training rows1.52518
training rows1.56819
training rows1.54620

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 velocity loss over the last 10% of epochs averaged 1.56.
  • 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.049 (mean Kolmogorov–Smirnov distance); categories 0.093 (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.62 ± 14.70.0563Kolmogorov–Smirnov D
annual incomenumeric2.929e+04 ± 1.43e+042.988e+04 ± 1.44e+040.0429Kolmogorov–Smirnov D
tenure_monthsnumeric15 ± 10.715.71 ± 11.30.0656Kolmogorov–Smirnov D
plancategoricalplus 39.7%plus 33.4%0.0625total variation
regioncategoricalsouth 30.4%south 24.3%0.1128total variation
churnedbooleanfalse 76.9%false 66.6%0.1031total variation
signuptemporal2020-11-05 ± 621 days2020-10-17 ± 602 days0.0375Kolmogorov–Smirnov D
visitsnumeric3.394 ± 2.093.503 ± 1.980.0437Kolmogorov–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.
The exact R script · R R version 4.5.1 (2025-06-13)
# Synthetic data — flow matching
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method synth.flow_matching 1.0.1 · spec 63f9d71e9f455a9a
# 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_matching/customers_rk4/out-r")
# A velocity network learns to carry N(0, I) noise along straight lines to the rows (normal scores of numbers,
# one-hot categories); new rows follow it from t = 0 to 1 in 8 rk4 steps.
# Twin of codesplash.synth.flows.fit_flow_matching (written from the papers).
HIDDEN <- as.integer(unlist(c(32, 32)))
fit <- cs_synth_flow_matching(
  train, N_OUT, HIDDEN,
  epochs = as.integer(20),
  batch_size = 100,
  lr = 0.001,
  time_dim = as.integer(16),
  steps = as.integer(8),
  sampler = "rk4",
  seed = SEED
)
synth <- fit$cols
hist <- fit$history
history <- data.frame(
  epoch = vapply(hist, function(h) as.numeric(h$epoch), numeric(1)),
  loss = vapply(hist, function(h) h$loss, numeric(1))
)
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$final_loss <- mean(history$loss[tail_rows])
fit_values$steps <- fit$facts$steps
fit_values$evaluations <- fit$facts$evaluations
model_note <- " with flow matching"
ne <- nrow(history)
extra_charts[[length(extra_charts) + 1L]] <- cs_chart("training", "training-components", "Velocity loss by epoch", list(
  x = cs_col("Epoch", history$epoch, "numeric"),
  value = cs_col("Mean squared velocity error", history$loss, "numeric"),
  component = cs_col("Part", rep("training rows", ne), "categorical", levels = c("training rows"))
), note = "The loss can't reach 0: many noise–row pairs cross the same point with different velocities, so it levels off.")
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 velocity loss over the last 10%% of epochs averaged %s.", format(signif(fit_values$final_loss, 3)))
           else "The loss became infinite or undefined; lower the learning rate."
)
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_matching/customers_rk4/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 — flow matching",
  engine = cs_engine_info("torch", "nanoparquet", "codesplashr", "nanoparquet"),
  n = values$n_real, summary = summary,
  statistics = list(
    list(key = "n_rows", label = "Synthetic rows", value = values$n_rows, format = "integer"),
    list(key = "fidelity_ks_mean", label = "Mean KS distance", value = values$fidelity_ks_mean),
    list(key = "fidelity_tv_mean", label = "Mean TV distance", value = values$fidelity_tv_mean),
    list(key = "exact_matches", label = "Rows copied from the data", value = values$exact_matches, format = "integer")),
  tables = c(list(sm$table), extra_tables),
  values = values, charts = c(sm$charts, extra_charts), assumptions = assumptions, warnings = warnings,
  artifacts = list(list(key = "synthetic", path = path, format = "parquet", title = "Synthetic rows"),
                   list(key = "split", path = split, format = "parquet", title = "Training and holdout rows"),
                   list(key = "history", path = file.path(out, "history.parquet"), format = "parquet", title = "Training history")),
  model = list(kind = "generator", columns = I(COLUMNS), params = list(
    n_rows = NULL,
    hidden_layers = c(32, 32),
    epochs = 20,
    batch_size = 100,
    learning_rate = 0.001,
    time_dim = 16,
    sampler = "rk4",
    steps = 8,
    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 flow matching. Numeric columns differ from the data by a mean Kolmogorov–Smirnov distance of 0.049 and categories by a mean total variation of 0.093.

Synthetic rows
320
Mean KS distance
0.0492
Mean TV distance
0.0928
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 velocity loss over the last 10% of epochs averaged 1.56.
  • 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.049 (mean Kolmogorov–Smirnov distance); categories 0.093 (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.62 ± 14.70.0562Kolmogorov–Smirnov D
annual incomenumeric2.929e+04 ± 1.43e+042.988e+04 ± 1.44e+040.0429Kolmogorov–Smirnov D
tenure_monthsnumeric15 ± 10.715.71 ± 11.30.0656Kolmogorov–Smirnov D
plancategoricalplus 39.7%plus 33.4%0.0625total variation
regioncategoricalsouth 30.4%south 24.3%0.1128total variation
churnedbooleanfalse 76.9%false 66.6%0.1031total variation
signuptemporal2020-11-05 ± 621 days2020-10-17 ± 602 days0.0375Kolmogorov–Smirnov D
visitsnumeric3.394 ± 2.093.503 ± 1.980.0438Kolmogorov–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.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Synthetic data — flow matching
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method synth.flow_matching 1.0.1 · spec 63f9d71e9f455a9a
# 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_matching (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_matching/customers_rk4/out-python",
)
# A velocity network learns to carry N(0, I) noise along straight lines to the rows (normal scores of numbers,
# one-hot categories); new rows follow it from t = 0 to 1 in 8 rk4 steps.
HIDDEN = [int(u) for u in [32, 32]]
synth, facts, hist = flows.fit_flow_matching(
    train, N_OUT, HIDDEN,
    epochs=20,
    batch_size=100,
    lr=0.001,
    time_dim=16,
    steps=8,
    sampler="rk4",
    seed=SEED,
)
history = pd.DataFrame(hist)
last = max(1, len(hist) // 10)  # the last 10% of epochs
fit_values["batch_size"] = facts["batch_size"]
fit_values["final_loss"] = float(np.mean([h["loss"] for h in hist[-last:]]))
fit_values["steps"] = facts["steps"]
fit_values["evaluations"] = facts["evaluations"]
model_note = " with flow matching"
ep = history["epoch"].tolist()
extra_charts.append(cs.chart("training", "training-components", "Velocity loss by epoch", {
    "x": cs.col("Epoch", ep, "numeric"),
    "value": cs.col("Mean squared velocity error", history["loss"].tolist(), "numeric"),
    "component": cs.col("Part", ["training rows"] * len(ep), "categorical", levels=["training rows"]),
}, note="The loss can't reach 0: many noise–row pairs cross the same point with different velocities, so it levels off."))
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 velocity loss over the last 10% of epochs averaged {fit_values['final_loss']:.3g}." if finite else "The loss became infinite or undefined; lower the learning rate.",
})
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_matching/customers_rk4/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 — flow matching",
    "engine": cs.engine_info("torch", "scipy", "pyarrow", "codesplash", "numpy", "pyarrow"),
    "n": values["n_real"],
    "summary": summary,
    "statistics": [
        {"key": "n_rows", "label": "Synthetic rows", "value": values["n_rows"], "format": "integer"},
        {"key": "fidelity_ks_mean", "label": "Mean KS distance", "value": values.get("fidelity_ks_mean")},
        {"key": "fidelity_tv_mean", "label": "Mean TV distance", "value": values.get("fidelity_tv_mean")},
        {"key": "exact_matches", "label": "Rows copied from the data", "value": values["exact_matches"], "format": "integer"},
    ],
    "tables": [table, *extra_tables],
    "values": values,
    "charts": charts + extra_charts,
    "assumptions": assumptions,
    "warnings": warnings,
    "artifacts": [
        {"key": "synthetic", "path": path, "format": "parquet", "title": "Synthetic rows"},
        {"key": "split", "path": split, "format": "parquet", "title": "Training and holdout rows"},
        {"key": "history", "path": os.path.join(out, "history.parquet"), "format": "parquet", "title": "Training history"},
    ],
    "model": {"kind": "generator", "columns": COLUMNS, "params": {
        "n_rows": None,
        "hidden_layers": [32, 32],
        "epochs": 20,
        "batch_size": 100,
        "learning_rate": 0.001,
        "time_dim": 16,
        "sampler": "rk4",
        "steps": 8,
        "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 Synthetic studio's Flow matching generator samples by integrating the learned velocity from noise at time 0 to rows at time 1 with an ODE samplerODE sampler (Euler, Runge–Kutta)Following a learned velocity in small time steps; RK4 averages four velocities per step and is far more accurate than Euler.. This run takes 8 Runge–Kutta steps, 32 network evaluations per batch. Its final velocity loss is 1.557 and its mean KS distance per column 0.049.

05

Steps, solvers and cost

Explore
Synthetic data — flow matchingRecorded · Python and R agreeRecorded 2026-11-25 · 43 values compared · largest relative difference 4.3e-16
R

400 synthetic rows over 7 columns from 258 training rows with flow matching. Numeric columns differ from the data by a mean Kolmogorov–Smirnov distance of 0.065 and categories by a mean total variation of 0.098.

Synthetic rows
400
Mean KS distance
0.0645
Mean TV distance
0.0982
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.0164synthetic32.558
0.0136synthetic33.475
0.0545synthetic34.392
0.0491synthetic35.308
0.0600synthetic36.225
0.0573synthetic37.142
0.0764synthetic38.058
0.0655synthetic38.975
0.0355synthetic39.892
0.0682synthetic40.808
0.0382synthetic41.725
0.0273synthetic42.642
0.0218synthetic43.558
0.0300synthetic44.475
0.0845synthetic45.392
0.0545synthetic46.308
0.0300synthetic47.225
0.0436synthetic48.142
0.0464synthetic49.058
0.0382synthetic49.975
0.0382synthetic50.892
0.0464synthetic51.808
0.0300synthetic52.725
0.0136synthetic53.642
0.0164synthetic54.558
0.0136synthetic55.475
0.0027synthetic56.392
0.0082synthetic57.308
0.0082synthetic58.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.0633synthetic13.338
0.1265synthetic13.615
0.1355synthetic13.892
0.1536synthetic14.168
0.1446synthetic14.445
0.1084synthetic14.722
0.1536synthetic14.998
0.0542synthetic15.275
0.0271synthetic15.552
0.2259synthetic15.828
0.1265synthetic16.105
0.0813synthetic16.382
0.0723synthetic16.658
0.2530synthetic16.935
0.1536synthetic17.212
0.1536synthetic17.488
0.1265synthetic17.765
0.1627synthetic18.042
0.0813synthetic18.318
0.1807synthetic18.595
0.2801synthetic18.872
0.0994synthetic19.148
0.1084synthetic19.425
0.0994synthetic19.702
0.1627synthetic19.978
0.0452synthetic20.255
0.0271synthetic20.532
0.0271synthetic20.808
0.1084synthetic21.085
0.0723synthetic21.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
0synthetic174.95
0.0013synthetic176.92
0.0025synthetic178.88
0.0178synthetic180.85
0.0051synthetic182.82
0.0343synthetic184.78
0.0356synthetic186.75
0.0165synthetic188.72
0.0534synthetic190.68
0.0254synthetic192.65
0.0305synthetic194.62
0.0280synthetic196.58
0.0191synthetic198.55
0.0127synthetic200.52
0.0140synthetic202.48
0.0064synthetic204.45
0.0064synthetic206.42
0.0140synthetic208.38
0.0229synthetic210.35
0.0216synthetic212.32
0.0292synthetic214.28
0.0114synthetic216.25
0.0191synthetic218.22
0.0267synthetic220.18
0.0114synthetic222.15
0.0140synthetic224.12
0.0025synthetic226.08
0.0178synthetic228.05
0.0089synthetic230.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
0.0002synthetic2867.50
2.239e-5synthetic2979.17
0.0002synthetic3090.83
0.0006synthetic3202.50
0.0004synthetic3314.17
0.0004synthetic3425.83
0.0004synthetic3537.50
0.0006synthetic3649.17
0.0005synthetic3760.83
0.0004synthetic3872.50
0.0002synthetic3984.17
0.0005synthetic4095.83
0.0002synthetic4207.50
0.0002synthetic4319.17
0.0004synthetic4430.83
8.955e-5synthetic4542.50
0.0007synthetic4654.17
0.0004synthetic4765.83
0.0002synthetic4877.50
0.0004synthetic4989.17
0.0002synthetic5100.83
0.0001synthetic5212.50
0.0003synthetic5324.17
0.0002synthetic5435.83
0.0005synthetic5547.50
0.0003synthetic5659.17
0.0001synthetic5770.83
4.478e-5synthetic5882.50
0.0002synthetic5994.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.4200synthetic
Chinstrap0.2875synthetic
Gentoo0.2925synthetic
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.3175synthetic
Dream0.4350synthetic
Torgersen0.2475synthetic
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_len0.2489
flipper_lenbill_len0.6270
body_massbill_len0.2847
bill_lenbill_dep0.2489
bill_depbill_dep0
flipper_lenbill_dep−0.6588
body_massbill_dep−0.1541
bill_lenflipper_len0.6270
bill_depflipper_len−0.6588
flipper_lenflipper_len0
body_massflipper_len0.6794
bill_lenbody_mass0.2847
bill_depbody_mass−0.1541
flipper_lenbody_mass0.6794
body_massbody_mass0
Velocity loss by epochIs the network still learning, and which part of its loss moves?

The loss can't reach 0: many noise–row pairs cross the same point with different velocities, so it levels off.

View data
PartMean squared velocity errorEpoch
training rows2.4751
training rows2.3282
training rows2.2093
training rows2.2094
training rows2.2765
training rows2.0786
training rows1.9947
training rows1.8838
training rows1.8039
training rows1.79010
training rows1.80311
training rows1.81012
training rows1.65713
training rows1.71414
training rows1.69615
training rows1.64816
training rows1.64517
training rows1.63818
training rows1.71719
training rows1.61920

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 velocity loss over the last 10% of epochs averaged 1.67.
  • 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.065 (mean Kolmogorov–Smirnov distance); categories 0.098 (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 42.0%0.0976total variation
islandcategoricalBiscoe 48.1%Biscoe 31.8%0.1631total variation
bill_lennumeric43.96 ± 5.543.27 ± 6.390.1037Kolmogorov–Smirnov D
bill_depnumeric17.14 ± 1.9817.17 ± 2.180.0575Kolmogorov–Smirnov D
flipper_lennumeric201.3 ± 14.2202 ± 14.40.0380Kolmogorov–Smirnov D
body_massnumeric4219 ± 7914259 ± 8590.0589Kolmogorov–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.
The exact R script · R R version 4.5.1 (2025-06-13)
# Synthetic data — flow matching
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method synth.flow_matching 1.0.1 · spec 7b5403b091a529da
# 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_matching/penguins_euler/out-r")
# A velocity network learns to carry N(0, I) noise along straight lines to the rows (normal scores of numbers,
# one-hot categories); new rows follow it from t = 0 to 1 in 25 euler steps.
# Twin of codesplash.synth.flows.fit_flow_matching (written from the papers).
HIDDEN <- as.integer(unlist(c(32)))
fit <- cs_synth_flow_matching(
  train, N_OUT, HIDDEN,
  epochs = as.integer(20),
  batch_size = 64,
  lr = 0.001,
  time_dim = as.integer(16),
  steps = as.integer(25),
  sampler = "euler",
  seed = SEED
)
synth <- fit$cols
hist <- fit$history
history <- data.frame(
  epoch = vapply(hist, function(h) as.numeric(h$epoch), numeric(1)),
  loss = vapply(hist, function(h) h$loss, numeric(1))
)
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$final_loss <- mean(history$loss[tail_rows])
fit_values$steps <- fit$facts$steps
fit_values$evaluations <- fit$facts$evaluations
model_note <- " with flow matching"
ne <- nrow(history)
extra_charts[[length(extra_charts) + 1L]] <- cs_chart("training", "training-components", "Velocity loss by epoch", list(
  x = cs_col("Epoch", history$epoch, "numeric"),
  value = cs_col("Mean squared velocity error", history$loss, "numeric"),
  component = cs_col("Part", rep("training rows", ne), "categorical", levels = c("training rows"))
), note = "The loss can't reach 0: many noise–row pairs cross the same point with different velocities, so it levels off.")
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 velocity loss over the last 10%% of epochs averaged %s.", format(signif(fit_values$final_loss, 3)))
           else "The loss became infinite or undefined; lower the learning rate."
)
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_matching/penguins_euler/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 — flow matching",
  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,
    hidden_layers = c(32),
    epochs = 20,
    batch_size = 64,
    learning_rate = 0.001,
    time_dim = 16,
    sampler = "euler",
    steps = 25,
    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 flow matching. Numeric columns differ from the data by a mean Kolmogorov–Smirnov distance of 0.065 and categories by a mean total variation of 0.098.

Synthetic rows
400
Mean KS distance
0.0645
Mean TV distance
0.0982
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 velocity loss over the last 10% of epochs averaged 1.67.
  • 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.065 (mean Kolmogorov–Smirnov distance); categories 0.098 (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 42.0%0.0976total variation
islandcategoricalBiscoe 48.1%Biscoe 31.8%0.1631total variation
bill_lennumeric43.96 ± 5.543.27 ± 6.390.1038Kolmogorov–Smirnov D
bill_depnumeric17.14 ± 1.9817.17 ± 2.180.0575Kolmogorov–Smirnov D
flipper_lennumeric201.3 ± 14.2202 ± 14.40.0380Kolmogorov–Smirnov D
body_massnumeric4219 ± 7914259 ± 8590.0589Kolmogorov–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.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Synthetic data — flow matching
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method synth.flow_matching 1.0.1 · spec 7b5403b091a529da
# 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_matching (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_matching/penguins_euler/out-python",
)
# A velocity network learns to carry N(0, I) noise along straight lines to the rows (normal scores of numbers,
# one-hot categories); new rows follow it from t = 0 to 1 in 25 euler steps.
HIDDEN = [int(u) for u in [32]]
synth, facts, hist = flows.fit_flow_matching(
    train, N_OUT, HIDDEN,
    epochs=20,
    batch_size=64,
    lr=0.001,
    time_dim=16,
    steps=25,
    sampler="euler",
    seed=SEED,
)
history = pd.DataFrame(hist)
last = max(1, len(hist) // 10)  # the last 10% of epochs
fit_values["batch_size"] = facts["batch_size"]
fit_values["final_loss"] = float(np.mean([h["loss"] for h in hist[-last:]]))
fit_values["steps"] = facts["steps"]
fit_values["evaluations"] = facts["evaluations"]
model_note = " with flow matching"
ep = history["epoch"].tolist()
extra_charts.append(cs.chart("training", "training-components", "Velocity loss by epoch", {
    "x": cs.col("Epoch", ep, "numeric"),
    "value": cs.col("Mean squared velocity error", history["loss"].tolist(), "numeric"),
    "component": cs.col("Part", ["training rows"] * len(ep), "categorical", levels=["training rows"]),
}, note="The loss can't reach 0: many noise–row pairs cross the same point with different velocities, so it levels off."))
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 velocity loss over the last 10% of epochs averaged {fit_values['final_loss']:.3g}." if finite else "The loss became infinite or undefined; lower the learning rate.",
})
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_matching/penguins_euler/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 — flow matching",
    "engine": cs.engine_info("torch", "scipy", "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,
        "hidden_layers": [32],
        "epochs": 20,
        "batch_size": 64,
        "learning_rate": 0.001,
        "time_dim": 16,
        "sampler": "euler",
        "steps": 25,
        "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,
    }},
})

Sampler: Euler uses one evaluation per step; this penguins run takes 25 steps for 25 evaluations, and reaches a mean KS distance of 0.065.

Straight training paths don't make the learned flow perfectly straight, since crossing paths are averaged, so a few solver steps are still needed. Try fewer steps and check the scorecard: if fidelity holds, sampling gets cheaper for free.

06

Same scorecard as diffusion

Reflect
Synthetic data — tabular diffusion (TabDDPM-style)Recorded · Python and R agreeRecorded 2026-11-25 · 91 values compared
R

320 synthetic rows over 8 columns from 320 training rows with a diffusion model. Numeric columns differ from the data by a mean Kolmogorov–Smirnov distance of 0.136 and categories by a mean total variation of 0.025.

Synthetic rows
320
Mean KS distance
0.1361
Mean TV distance
0.0250
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.0411synthetic18.950
0.0049synthetic20.850
0.0066synthetic22.750
0.0197synthetic24.650
0.0132synthetic26.550
0.0164synthetic28.450
0.0263synthetic30.350
0.0362synthetic32.250
0.0477synthetic34.150
0.0115synthetic36.050
0.0411synthetic37.950
0.0411synthetic39.850
0.0280synthetic41.750
0.0296synthetic43.650
0.0280synthetic45.550
0.0181synthetic47.450
0.0214synthetic49.350
0.0132synthetic51.250
0.0280synthetic53.150
0.0082synthetic55.050
0.0099synthetic56.950
0.0033synthetic58.850
0.0066synthetic60.750
0.0132synthetic62.650
0.0016synthetic64.550
0.0049synthetic66.450
0.0033synthetic68.350
0.0033synthetic70.250
0synthetic72.150
0synthetic74.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
5.016e-6synthetic6851.93
1.906e-5synthetic10141.74
2.608e-5synthetic13431.55
3.210e-5synthetic16721.36
3.912e-5synthetic20011.17
4.615e-5synthetic23300.98
2.608e-5synthetic26590.79
2.107e-5synthetic29880.60
2.709e-5synthetic33170.41
1.003e-5synthetic36460.22
1.505e-5synthetic39750.03
1.104e-5synthetic43039.84
9.029e-6synthetic46329.65
2.006e-6synthetic49619.46
3.010e-6synthetic52909.27
3.010e-6synthetic56199.07
3.010e-6synthetic59488.88
4.013e-6synthetic62778.69
0synthetic66068.50
1.003e-6synthetic69358.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.1916synthetic0.7667
0.0285synthetic2.300
0.0285synthetic3.833
0.0611synthetic5.367
0.0163synthetic6.900
0.0326synthetic8.433
0.0265synthetic9.967
0.0408synthetic11.500
0.0122synthetic13.033
0.0571synthetic14.567
0.0102synthetic16.100
0.0204synthetic17.633
0.0265synthetic19.167
0.0183synthetic20.700
0.0122synthetic22.233
0.0082synthetic23.767
0.0143synthetic25.300
0.0102synthetic26.833
0.0102synthetic28.367
0.0041synthetic29.900
0.0061synthetic31.433
0.0020synthetic32.967
0.0082synthetic34.500
0synthetic36.033
0.0020synthetic37.567
0synthetic39.100
0.0020synthetic40.633
0.0020synthetic42.167
0synthetic43.700
0synthetic45.233
signup: real vs syntheticDoes the synthetic data reproduce the shape of a numeric column?
View data
DensitySourcesignup
0.0005real17582.23
0.0007real17654.70
0.0005real17727.17
0.0005real17799.63
0.0004real17872.10
0.0005real17944.57
0.0006real18017.03
0.0004real18089.50
0.0005real18161.97
0.0005real18234.43
0.0001real18306.90
0.0009real18379.37
0.0006real18451.83
0.0003real18524.30
0.0005real18596.77
0.0004real18669.23
0.0002real18741.70
0.0005real18814.17
0.0006real18886.63
0.0005real18959.10
0.0005real19031.57
0.0005real19104.03
0.0003real19176.50
0.0006real19248.97
0.0004real19321.43
0.0003real19393.90
0.0002real19466.37
0.0005real19538.83
0.0003real19611.30
0.0004real19683.77
8.625e-5synthetic17582.23
0.0004synthetic17654.70
0.0006synthetic17727.17
0.0004synthetic17799.63
0.0002synthetic17872.10
0.0005synthetic17944.57
0.0004synthetic18017.03
0.0002synthetic18089.50
0.0004synthetic18161.97
0.0006synthetic18234.43
8.625e-5synthetic18306.90
0.0007synthetic18379.37
0.0005synthetic18451.83
0.0004synthetic18524.30
0.0007synthetic18596.77
0.0005synthetic18669.23
0.0002synthetic18741.70
0.0004synthetic18814.17
0.0005synthetic18886.63
0.0005synthetic18959.10
0.0005synthetic19031.57
0.0007synthetic19104.03
0.0006synthetic19176.50
0.0010synthetic19248.97
0.0006synthetic19321.43
0.0003synthetic19393.90
0.0001synthetic19466.37
0.0004synthetic19538.83
0.0004synthetic19611.30
0.0007synthetic19683.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.3656synthetic
plus0.4281synthetic
premium0.2062synthetic
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.3003synthetic
north0.2684synthetic
south0.3035synthetic
west0.1278synthetic
churned: real vs syntheticDoes the synthetic data keep the category proportions of the real data?
View data
churnedShareSource
false0.7688real
true0.2313real
false0.7500synthetic
true0.2500synthetic
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.0421
tenure_monthsage0.0710
signupage−0.1504
visitsage−0.0133
ageannual income0.0421
annual incomeannual income0
tenure_monthsannual income−0.0589
signupannual income−0.0369
visitsannual income0.0470
agetenure_months0.0710
annual incometenure_months−0.0589
tenure_monthstenure_months0
signuptenure_months−0.1931
visitstenure_months0.0302
agesignup−0.1504
annual incomesignup−0.0369
tenure_monthssignup−0.1931
signupsignup0
visitssignup0.0255
agevisits−0.0133
annual incomevisits0.0470
tenure_monthsvisits0.0302
signupvisits0.0255
visitsvisits0
Denoising loss by epochIs the network still learning, and which part of its loss moves?
View data
PartLossEpoch
total1.3861
total1.0962
total0.96673
total0.87944
total0.82505
total0.78826
total0.77817
total0.77518
total0.67829
total0.674010
total0.687211
total0.663712
total0.587913
total0.612814
total0.674515
total0.613216
total0.642717
total0.549418
total0.640619
total0.611320
total0.605321
total0.575522
total0.586123
total0.620124
total0.587725
total0.574726
total0.568627
total0.549328
total0.548629
total0.653130
total0.536331
total0.497132
total0.506833
total0.541034
total0.590335
total0.474536
total0.493937
total0.515138
total0.576039
total0.504640
total0.495041
total0.500542
total0.506143
total0.549344
total0.526345
total0.548146
total0.535547
total0.501848
total0.524949
total0.519750
total0.561251
total0.498952
total0.544253
total0.539354
total0.550255
total0.518556
total0.525657
total0.495758
total0.528159
total0.460460

First 60 of 300 rows.

Denoising loss by diffusion stepAt which noise levels does a diffusion model still struggle to denoise?

Small t is almost clean data (a fine-detail task); large t is almost pure noise.

View data
PartDiffusion step tLoss
Gaussian (numbers)21.091
Gaussian (numbers)51.007
Gaussian (numbers)80.9521
Gaussian (numbers)100.8506
Gaussian (numbers)120.8196
Gaussian (numbers)150.7090
Gaussian (numbers)180.6306
Gaussian (numbers)200.5891
Gaussian (numbers)220.5913
Gaussian (numbers)250.4474
Gaussian (numbers)280.3712
Gaussian (numbers)300.3342
Gaussian (numbers)320.2898
Gaussian (numbers)350.2229
Gaussian (numbers)380.1493
Gaussian (numbers)400.1219
Gaussian (numbers)420.0991
Gaussian (numbers)450.0652
Gaussian (numbers)480.0622
Gaussian (numbers)500.0569
multinomial (categories)20.0161
multinomial (categories)50.0265
multinomial (categories)80.0272
multinomial (categories)100.0332
multinomial (categories)120.0323
multinomial (categories)150.0365
multinomial (categories)180.0344
multinomial (categories)200.0326
multinomial (categories)220.0289
multinomial (categories)250.0253
multinomial (categories)280.0208
multinomial (categories)300.0179
multinomial (categories)320.0146
multinomial (categories)350.0095
multinomial (categories)380.0061
multinomial (categories)400.0037
multinomial (categories)420.0021
multinomial (categories)450.0006
multinomial (categories)486.345e-5
multinomial (categories)509.501e-7

Assumptions

  • Enough rows for a neural generator — 293 complete training rows — neural generators have many weights to learn and can memorize small tables; compare with the copula or sequential trees.
  • Training stayed finite — The loss over the last 10% of epochs averaged 0.493.
  • 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.136 (mean Kolmogorov–Smirnov distance); categories 0.025 (mean total variation) — above 0.10, so some columns' distributions differ visibly from the data; the scorecard shows which columns and pairs.

Real vs synthetic, column by column

ColumnKindRealSyntheticDistanceMeasure
agenumeric43.14 ± 13.139.21 ± 120.1313Kolmogorov–Smirnov D
annual incomenumeric2.929e+04 ± 1.43e+042.644e+04 ± 1.24e+040.0990Kolmogorov–Smirnov D
tenure_monthsnumeric15 ± 10.79.8 ± 9.530.2344Kolmogorov–Smirnov D
plancategoricalplus 39.7%plus 42.8%0.0406total variation
regioncategoricalsouth 30.4%south 30.4%0.0155total variation
churnedbooleanfalse 76.9%false 75.0%0.0187total variation
signuptemporal2020-11-05 ± 621 days2021-03-30 ± 601 days0.1156Kolmogorov–Smirnov D
visitsnumeric3.394 ± 2.093.013 ± 1.780.1000Kolmogorov–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.
The exact R script · R R version 4.5.1 (2025-06-13)
# Synthetic data — tabular diffusion (TabDDPM-style)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method synth.diffusion 1.0.2 · spec 9e3bbe3915d08f98
# 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
# Gaussian diffusion of normal scores + multinomial diffusion of categories over 50 steps (cosine schedule);
# one MLP predicts the noise and the categories' x0 from [x_t, one-hot x_t, time embedding].
# Twin of codesplash.synth.neural.fit_diffusion (TabDDPM-style, written from the papers).
HIDDEN <- as.integer(unlist(c(64, 64)))
fit <- cs_synth_diffusion(
  train, N_OUT, HIDDEN,
  steps = as.integer(50),
  epochs = as.integer(100),
  batch_size = 128,
  lr = 0.002,
  time_dim = as.integer(16),
  seed = SEED
)
synth <- fit$cols
hist <- fit$history
history <- data.frame(
  epoch = vapply(hist, function(h) as.numeric(h$epoch), numeric(1)),
  loss = vapply(hist, function(h) h$loss, numeric(1)),
  loss_num = vapply(hist, function(h) h$loss_num, numeric(1)),
  loss_cat = vapply(hist, function(h) h$loss_cat, numeric(1))
)
HAS_NUM <- any(vapply(train, function(c) !c$coded, logical(1)))
HAS_CAT <- any(vapply(train, function(c) c$coded, logical(1)))
last <- max(1L, nrow(history) %/% 10L)  # the last 10% of epochs
tail_rows <- (nrow(history) - last + 1L):nrow(history)
fit_values$steps <- fit$facts$steps
fit_values$batch_size <- fit$facts$batch_size
fit_values$final_loss <- mean(history$loss[tail_rows])
if (HAS_NUM) fit_values$loss_num <- mean(history$loss_num[tail_rows])
if (HAS_CAT) fit_values$loss_cat <- mean(history$loss_cat[tail_rows])
model_note <- " with a diffusion model"
parts <- c(total = "loss")
if (HAS_NUM) parts <- c(parts, `Gaussian (numbers)` = "loss_num")
if (HAS_CAT) parts <- c(parts, `multinomial (categories)` = "loss_cat")
ne <- nrow(history)
extra_charts[[length(extra_charts) + 1L]] <- cs_chart("training", "training-components", "Denoising loss by epoch", list(
  x = cs_col("Epoch", rep(history$epoch, length(parts)), "numeric"),
  value = cs_col("Loss", unlist(lapply(parts, function(k) history[[k]]), use.names = FALSE), "numeric"),
  component = cs_col("Part", rep(names(parts), each = ne), "categorical", levels = names(parts))
))
by_t <- fit$by_t
t_parts <- c()
if (HAS_NUM) t_parts <- c(t_parts, `Gaussian (numbers)` = 2L)
if (HAS_CAT) t_parts <- c(t_parts, `multinomial (categories)` = 3L)
extra_charts[[length(extra_charts) + 1L]] <- cs_chart("timesteps", "timestep-loss", "Denoising loss by diffusion step", list(
  t = cs_col("Diffusion step t", rep(by_t[, 1], length(t_parts)), "numeric"),
  value = cs_col("Loss", unlist(lapply(t_parts, function(j) by_t[, j]), use.names = FALSE), "numeric"),
  component = cs_col("Part", rep(names(t_parts), each = nrow(by_t)), "categorical", levels = names(t_parts))
), note = "Small t is almost clean data (a fine-detail task); large t is almost pure noise.")
for (r in seq_len(nrow(by_t))) {
  if (HAS_NUM) fit_values[[sprintf("loss_t_num[%d]", as.integer(by_t[r, 1]))]] <- by_t[r, 2]
  if (HAS_CAT) fit_values[[sprintf("loss_t_cat[%d]", as.integer(by_t[r, 1]))]] <- by_t[r, 3]
}
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 loss over the last 10%% of epochs averaged %s.", format(signif(fit_values$final_loss, 3))) else
    "A loss became infinite or undefined; lower the learning rate."
)
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.diffusion/customers_all/out-r")
path <- cs_synth_write(file.path(out, "synthetic.parquet"), synth)
split <- cs_synth_write_split(file.path(out, "split.parquet"), n_input, train_rows, holdout_rows)
nanoparquet::write_parquet(history, file.path(out, "history.parquet"))
sm <- cs_synth_summarize(train, synth, length(train_rows), n_input, length(holdout_rows), fit_values)
values <- sm$values
assumptions[[length(assumptions) + 1L]] <- list(
  key = "no_copies", label = "No synthetic row copies a training row",
  status = if (values$exact_matches == 0) "pass" else "warn",
  detail = sprintf("%s synthetic row%s identical to a training row; the scorecard's distance to closest record checks near-copies.",
                   format(values$exact_matches, big.mark = ","), if (values$exact_matches != 1) "s are" else " is")
)
# Fidelity (Stage 12.10): judged on the mean column distances, the scorecard's column fidelity (good at >= 0.9 = 1 - 0.1).
fid_d <- numeric(); fid_t <- character()
if (!is.nan(values$fidelity_ks_mean)) {
  fid_d <- c(fid_d, values$fidelity_ks_mean)
  fid_t <- c(fid_t, sprintf("numeric columns %.3f (mean Kolmogorov–Smirnov distance)", values$fidelity_ks_mean))
}
if (!is.nan(values$fidelity_tv_mean)) {
  fid_d <- c(fid_d, values$fidelity_tv_mean)
  fid_t <- c(fid_t, sprintf("categories %.3f (mean total variation)", values$fidelity_tv_mean))
}
assumptions[[length(assumptions) + 1L]] <- if (!length(fid_d)) {
  list(key = "fidelity", label = "Synthetic columns match the data", status = "info",
       detail = "No column could be compared with the data.")
} else {
  list(key = "fidelity", label = "Synthetic columns match the data",
       status = if (max(fid_d) <= 0.1) "pass" else "warn",
       detail = paste0("Distance from the training rows: ", paste(fid_t, collapse = "; "),
                       if (max(fid_d) <= 0.1) " — at most 0.10, which the Synthetic studio's scorecard rates as good column fidelity."
                       else " — above 0.10, so some columns' distributions differ visibly from the data; the scorecard shows which columns and pairs."))
}
summary <- sprintf("%s synthetic rows over %d column%s from %s training rows%s.",
                   format(values$n_rows, big.mark = ","), length(COLUMNS), if (length(COLUMNS) != 1) "s" else "",
                   format(length(train_rows), big.mark = ","), model_note)
if (!is.nan(values$fidelity_ks_mean)) {
  summary <- paste0(summary, sprintf(" Numeric columns differ from the data by a mean Kolmogorov–Smirnov distance of %.3f", values$fidelity_ks_mean),
                    if (!is.nan(values$fidelity_tv_mean)) sprintf(" and categories by a mean total variation of %.3f.", values$fidelity_tv_mean) else ".")
} else if (!is.nan(values$fidelity_tv_mean)) {
  summary <- paste0(summary, sprintf(" Categories differ from the data by a mean total variation of %.3f.", values$fidelity_tv_mean))
}
if (values$exact_matches > 0) {
  summary <- paste0(summary, sprintf(" %s synthetic row%s identical to a training row.", format(values$exact_matches, big.mark = ","),
                                     if (values$exact_matches != 1) "s are" else " is"))
}
cs_publish(list(
  title = "Synthetic data — tabular diffusion (TabDDPM-style)",
  engine = cs_engine_info("torch", "nanoparquet", "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,
    steps = 50,
    hidden_layers = c(64, 64),
    epochs = 100,
    batch_size = 128,
    learning_rate = 0.002,
    time_dim = 16,
    missing = "keep_rate",
    holdout = 0.2
  ))
))
Python

320 synthetic rows over 8 columns from 320 training rows with a diffusion model. Numeric columns differ from the data by a mean Kolmogorov–Smirnov distance of 0.136 and categories by a mean total variation of 0.025.

Synthetic rows
320
Mean KS distance
0.1361
Mean TV distance
0.0250
Rows copied from the data
0

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

Assumptions

  • Enough rows for a neural generator — 293 complete training rows — neural generators have many weights to learn and can memorize small tables; compare with the copula or sequential trees.
  • Training stayed finite — The loss over the last 10% of epochs averaged 0.493.
  • 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.136 (mean Kolmogorov–Smirnov distance); categories 0.025 (mean total variation) — above 0.10, so some columns' distributions differ visibly from the data; the scorecard shows which columns and pairs.

Real vs synthetic, column by column

ColumnKindRealSyntheticDistanceMeasure
agenumeric43.14 ± 13.139.21 ± 120.1312Kolmogorov–Smirnov D
annual incomenumeric2.929e+04 ± 1.43e+042.644e+04 ± 1.24e+040.0990Kolmogorov–Smirnov D
tenure_monthsnumeric15 ± 10.79.8 ± 9.530.2344Kolmogorov–Smirnov D
plancategoricalplus 39.7%plus 42.8%0.0406total variation
regioncategoricalsouth 30.4%south 30.4%0.0155total variation
churnedbooleanfalse 76.9%false 75.0%0.0188total variation
signuptemporal2020-11-05 ± 621 days2021-03-30 ± 601 days0.1156Kolmogorov–Smirnov D
visitsnumeric3.394 ± 2.093.013 ± 1.780.1000Kolmogorov–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.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Synthetic data — tabular diffusion (TabDDPM-style)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method synth.diffusion 1.0.2 · spec 9e3bbe3915d08f98
# 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 neural  # twin of codesplashr::cs_synth_diffusion (TabDDPM-style, 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
# Gaussian diffusion of normal scores + multinomial diffusion of categories over 50 steps (cosine schedule);
# one MLP predicts the noise and the categories' x₀ from [xₜ, one-hot xₜ, time embedding].
HIDDEN = [int(u) for u in [64, 64]]
synth, facts, hist, by_t = neural.fit_diffusion(
    train, N_OUT, HIDDEN,
    steps=50,
    epochs=100,
    batch_size=128,
    lr=0.002,
    time_dim=16,
    seed=SEED,
)
history = pd.DataFrame([{k: v for k, v in h.items() if k != "valid_loss"} for h in hist])
HAS_NUM = any(not c.coded for c in train)
HAS_CAT = any(c.coded for c in train)
last = max(1, len(hist) // 10)  # the last 10% of epochs
fit_values["steps"] = facts["steps"]
fit_values["batch_size"] = facts["batch_size"]
fit_values["final_loss"] = float(np.mean([h["loss"] for h in hist[-last:]]))
if HAS_NUM:
    fit_values["loss_num"] = float(np.mean([h["loss_num"] for h in hist[-last:]]))
if HAS_CAT:
    fit_values["loss_cat"] = float(np.mean([h["loss_cat"] for h in hist[-last:]]))
model_note = " with a diffusion model"
ep = history["epoch"].tolist()
parts = [("total", "loss")] + ([("Gaussian (numbers)", "loss_num")] if HAS_NUM else []) + ([("multinomial (categories)", "loss_cat")] if HAS_CAT else [])
extra_charts.append(cs.chart("training", "training-components", "Denoising loss by epoch", {
    "x": cs.col("Epoch", ep * len(parts), "numeric"),
    "value": cs.col("Loss", [v for _, k in parts for v in history[k].tolist()], "numeric"),
    "component": cs.col("Part", [p for p, _ in parts for _ in ep], "categorical", levels=[p for p, _ in parts]),
}))
t_parts = ([("Gaussian (numbers)", 1)] if HAS_NUM else []) + ([("multinomial (categories)", 2)] if HAS_CAT else [])
extra_charts.append(cs.chart("timesteps", "timestep-loss", "Denoising loss by diffusion step", {
    "t": cs.col("Diffusion step t", [r[0] for _, _ in t_parts for r in by_t], "numeric"),
    "value": cs.col("Loss", [r[j] for _, j in t_parts for r in by_t], "numeric"),
    "component": cs.col("Part", [p for p, _ in t_parts for _ in by_t], "categorical", levels=[p for p, _ in t_parts]),
}, note="Small t is almost clean data (a fine-detail task); large t is almost pure noise."))
for tt, ln, lc in by_t:
    if HAS_NUM:
        fit_values[f"loss_t_num[{tt}]"] = ln
    if HAS_CAT:
        fit_values[f"loss_t_cat[{tt}]"] = lc
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 loss over the last 10% of epochs averaged {fit_values['final_loss']:.3g}." if finite else "A loss became infinite or undefined; lower the learning rate.",
})
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.diffusion/customers_all/out-python")
path = sy.write(os.path.join(out, "synthetic.parquet"), synth)
split = sy.write_split(os.path.join(out, "split.parquet"), n_input, train_rows, holdout_rows)
history.to_parquet(os.path.join(out, "history.parquet"), index=False)
values, table, charts = sy.summarize(train, synth, len(train_rows), n_input, len(holdout_rows), fit_values)
assumptions.append({
    "key": "no_copies",
    "label": "No synthetic row copies a training row",
    "status": "pass" if values["exact_matches"] == 0 else "warn",
    "detail": f"{values['exact_matches']:,} synthetic row{'s are' if values['exact_matches'] != 1 else ' is'} identical to a training row; the scorecard's distance to closest record checks near-copies.",
})
# Fidelity (Stage 12.10): judged on the mean column distances, the scorecard's column fidelity (good at ≥ 0.9 = 1 − 0.1).
fid_parts = []
if not np.isnan(values["fidelity_ks_mean"]):
    fid_parts.append((values["fidelity_ks_mean"], f"numeric columns {values['fidelity_ks_mean']:.3f} (mean Kolmogorov–Smirnov distance)"))
if not np.isnan(values["fidelity_tv_mean"]):
    fid_parts.append((values["fidelity_tv_mean"], f"categories {values['fidelity_tv_mean']:.3f} (mean total variation)"))
fid_worst = max((d for d, _ in fid_parts), default=None)
assumptions.append({
    "key": "fidelity",
    "label": "Synthetic columns match the data",
    "status": "info" if fid_worst is None else ("pass" if fid_worst <= 0.1 else "warn"),
    "detail": "No column could be compared with the data." if fid_worst is None else
              "Distance from the training rows: " + "; ".join(t for _, t in fid_parts)
              + (" — at most 0.10, which the Synthetic studio's scorecard rates as good column fidelity." if fid_worst <= 0.1 else
                 " — above 0.10, so some columns' distributions differ visibly from the data; the scorecard shows which columns and pairs."),
})
summary = (
    f"{values['n_rows']:,} synthetic rows over {len(COLUMNS)} column{'s' if len(COLUMNS) != 1 else ''} from "
    f"{len(train_rows):,} training rows{model_note}."
)
if not np.isnan(values["fidelity_ks_mean"]):
    summary += f" Numeric columns differ from the data by a mean Kolmogorov–Smirnov distance of {values['fidelity_ks_mean']:.3f}"
    summary += f" and categories by a mean total variation of {values['fidelity_tv_mean']:.3f}." if not np.isnan(values["fidelity_tv_mean"]) else "."
elif not np.isnan(values["fidelity_tv_mean"]):
    summary += f" Categories differ from the data by a mean total variation of {values['fidelity_tv_mean']:.3f}."
if values["exact_matches"]:
    summary += f" {values['exact_matches']:,} synthetic row{'s are' if values['exact_matches'] != 1 else ' is'} identical to a training row."
cs.publish({
    "title": "Synthetic data — tabular diffusion (TabDDPM-style)",
    "engine": cs.engine_info("torch", "scipy", "pyarrow", "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,
        "steps": 50,
        "hidden_layers": [64, 64],
        "epochs": 100,
        "batch_size": 128,
        "learning_rate": 0.002,
        "time_dim": 16,
        "missing": "keep_rate",
        "holdout": 0.2,
    }},
})

On the same customer table, diffusion ran 50 denoising steps per sample and reached a mean KS distance of 0.136; flow matching used 32 evaluations. One table and one seed each: write down which you'd keep, and which scorecard number would make you switch.

07

What runs here

Read
08

Check: flow matching

Checkpoint

Check yourself

On the straight path from noise x0x_0 to row x1x_1, what velocity does flow matching train toward?

Show the answer

Answer: a

A straight line has constant velocity. The network regresses on it from points along many such lines.

Check yourself

A flow-matching run's loss flattens well above zero. What does that mean?

Show the answer

Answer: b

The irreducible part of the loss comes from averaging conflicting targets. Judge the model by its samples.

Check yourself

Flow matching samples with 8 Runge–Kutta (RK4) steps. How many network evaluations is that per batch?

Show the answer

Answer: 32

RK4 evaluates the velocity four times per step: 8 × 4 = 32.

Check yourself

Does CodeSplash's flow-matching generator report a held-out log-likelihood?

Show the answer

Answer: b

A continuous flow's likelihood would need the trace integral along every path. The method doesn't compute it; use the fidelity, privacy and utility checks.

09

Recap

Recap
  • Flow matching regresses a network on the constant velocity of straight noise-to-row lines.
  • Its loss levels off above zero by design.
  • Sampling integrates the learned velocity with Euler or RK4; fewer steps are cheaper, so check fidelity holds.
  • It runs as the Synthetic studio's Flow matching generator, judged on the same scorecard.

Concepts in this lesson