Skip to content

Black-box VI, pathwise gradients and Stein particles

When no update has a formula, optimize the ELBO with Monte Carlo gradients: score-function or pathwise. Then move a set of particles instead of one distribution. Learn what each estimator needs and what neither can promise.

Advanced ~14 min10 steps

What runs in CodeSplash

You will be able to

  • Write the score-function and pathwise (reparameterized) ELBO gradients and the conditions each needs
  • Explain why an unbiased gradient doesn't make the variational family right
  • Describe an SVGD update as attraction plus repulsion between particles
  • Say where CodeSplash runs these ideas (ADVI, Pathfinder, VAEs)

Read first

01

When the expectations have no formula

Read

Coordinate ascent needs closed-form updates, which means conjugate pieces. A logistic likelihood, a neural decoder or a custom prior breaks that. Black-box variational inferenceBlack-box variational inferenceOptimizes the ELBO with Monte Carlo gradient estimates (score-function or reparameterized), so no expectation needs a formula. keeps the goal, maximizing the ELBO over a family qλq_\lambda, and estimates its gradient by sampling from qλq_\lambda instead of integrating.

There are two estimators. They target the same gradient; they differ in what they require and how noisy they are.

Reference · INF004 · Runs in CodeSplashBlack-box variational inference and pathwise gradientsOptimizes a variational objective using Monte Carlo gradient estimates instead of deriving every analytic expectation.
02

Score-function and pathwise gradients

Read
∇λL=Eq[∇λlog⁡qλ(z) (log⁡p(x,z)−log⁡qλ(z))](score function),\nabla_\lambda\mathcal L=E_q\big[\nabla_\lambda\log q_\lambda(z)\,\big(\log p(x,z)-\log q_\lambda(z)\big)\big]\quad\text{(score function)}, z=gλ(ϵ), ϵ∼p0:∇λL=Ep0[∇λ(log⁡p(x,gλ(ϵ))−log⁡qλ(gλ(ϵ)))](pathwise).z=g_\lambda(\epsilon),\ \epsilon\sim p_0:\qquad \nabla_\lambda\mathcal L=E_{p_0}\big[\nabla_\lambda\big(\log p(x,g_\lambda(\epsilon))-\log q_\lambda(g_\lambda(\epsilon))\big)\big]\quad\text{(pathwise)}.

The score-function estimator needs only log⁡q\log q's gradient, so it works for discrete latents, but it is noisy and needs baselines. The pathwise one, the reparameterization trickReparameterization trickWrites a random code as z = μ + σ·ε with ε drawn separately, so gradients flow through μ and σ during training., differentiates through the sample itself: far less noise, but it needs a differentiable model and a transform like z=μ+σϵz=\mu+\sigma\epsilon. On the reference's toy, with the same supplied draws, the score estimate is −0.50 and the pathwise estimate −0.50, both equal to the exact gradient −0.50.

03

Unbiased gradients, biased answer

Read

An unbiased gradient finds the best member of the family. It can't find something the family can't represent. A mean-field normal qq trained with perfect gradients still understates correlations and misses skew and second modes.

So treat a black-box VI fit as a fast first look: check its intervals against NUTS on the same model, run predictive checks, or run SBC. Other cautions from the reference: estimate baselines (control variates) on separate samples, or they can bias the gradient; handle bounded parameters through a transform with its Jacobian; and say so if you used a relaxation for discrete latents.

04

Black-box VI in CodeSplash

Read

Bayesian regression model (Stan) offers Stan's ADVI (mean-field and full-rank) and Pathfinder beside NUTS, all with pathwise gradients through the same compiled programs. Pathfinder follows an optimizer's path and fits normal approximations along it.

Bayesian gaussian (normal) model (Stan)Recorded · Python and R agreeRecorded 2026-11-25 · 70 values compared
R

Bayesian gaussian (normal) model of mpg (n = 32), Pathfinder (approximate). Posterior: wt has median -3.86 (95% credible interval -5.21 to -2.69); P(> 0) = 0.00. PSIS-LOO elpd = -78.6 (SE 4.6).

wt (posterior median)
−3.863
95% credible interval
[−5.212, −2.694]
P(effect > 0)
0
elpd (PSIS-LOO)
−78.609
Bayesian R² (median)
0.8114

Assumptions

  • Sampler converged (R-hat, ESS) — Pathfinder (approximate) gives approximate draws with no chains to compare; check important results with NUTS.
  • Leave-one-out is reliable (Pareto k̂) — Pathfinder resamples its draws, so 336 of 400 are distinct. 0 of 32 rows have k̂ above 0.62 (largest 0.50); those rows are influential and their LOO estimate is unreliable.
  • Replicated data look like the observed data — Posterior predictive p-values are between 0.01 and 0.99.
  • Priors stated — Results depend on the priors in the Priors table; rerun with wider priors to see how much.

Posterior summary

ParameterMeanSD95% lowerMedian95% upperR-hatBulk ESSTail ESSP(> 0)
(Intercept)37.3041.61433.81137.35040.120———1
wt−3.8830.5954−5.212−3.863−2.694———0
hp−0.03190.0089−0.0488−0.0318−0.0139———0
sigma2.6840.36112.1012.6573.450———1

Priors

ParameterPriorNote
(Intercept)Normal(20.09, 15.07)at the predictors' means
wtNormal(0, 15.4)autoscaled
hpNormal(0, 0.2198)autoscaled
sigmaExponential(0.1659)residual SD

Leave-one-out cross-validation (PSIS-LOO)

QuantityEstimateSE
elpd_loo (expected log predictive density)−78.6094.606
p_loo (effective number of parameters)3.9121.317
LOOIC (−2 × elpd_loo)157.229.211

Posterior predictive checks

StatisticObservedReplicated (mean)P(rep ≥ obs)
Mean20.09120.1130.4975
Standard deviation6.0276.1080.5425
Maximum33.90031.3610.1125
Minimum10.4006.9830.0400
  • Outcome model: Gaussian (normal).
  • Credible intervals are equal-tailed posterior quantiles; P(> 0) is the share of draws above zero.
  • Bayesian results are not p-values and are not entered in the multiple-testing ledger.
The exact R script · R R version 4.5.1 (2025-06-13)
# Bayesian regression model (Stan)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method bayes.model 1.0.1 · spec ea036d70025873fa
# Dataset: mtcars (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr) # cs_bayes_fit_model (twin of codesplash.bayes.model) on the shared Stan programs (cs_stan_*)

# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/mtcars.parquet", col_select = c("mpg", "wt", "hp")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("mpg", "wt", "hp")]), , drop = FALSE]  # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
  warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("mpg", "wt", "hp"))  # infinite values stop the run (registry/errors.yaml)

outcome <- "mpg"

# %% Model: the precompiled Stan program runs on a data file Python writes byte for byte the same (identical draws)
fit <- cs_bayes_fit_model(
  df,
  outcome = outcome,
  predictors = c("wt", "hp"),
  family = "gaussian",
  trials = NULL,
  exposure = NULL,
  group = NULL,
  slopes = c(),
  group2 = NULL,
  nesting = "nested",
  interactions = "none",
  event_level = NULL,
  prior_dist = "normal",
  prior_scale = 2.5,
  prior_df = 3,
  autoscale = TRUE,
  intercept_scale = 2.5,
  lkj = 1,
  algorithm = "pathfinder",
  chains = as.integer(4),
  iter_warmup = as.integer(1000),
  iter_sampling = as.integer(400),
  seed = 1234,
  adapt_delta = 0.8,
  max_treedepth = as.integer(10),
  use_qr = FALSE,
  prior_only = FALSE,
  loo = TRUE,
  ppc = TRUE,
  cred = 0.95,
  out_dir = cs_ml_out_dir("target/academy-parity/run-8142/bayes.model/pathfinder-mtcars/out-r")
)
values <- fit$values
prep <- fit$prep

# %% Result
cred <- values$cred_level
fixed <- Filter(function(r) r$kind == "fixed", fit$rows)
slopes_only <- Filter(function(r) r$term != "(Intercept)", fixed)
focus <- if (length(slopes_only)) slopes_only[[1]] else if (length(fixed)) fixed[[1]] else fit$rows[[1]]
labels <- c(gaussian = "Gaussian (normal)", student_t = "Student-t (robust)", logistic = "Logistic (Bernoulli)",
            binomial = "Logistic (successes of trials)", poisson = "Poisson", negbinomial = "Negative binomial",
            ordinal = "Ordinal (cumulative logit)")
label <- labels[[prep$family]]
alg_labels <- c(nuts = "NUTS (Hamiltonian Monte Carlo)", pathfinder = "Pathfinder (approximate)", meanfield = "ADVI mean-field (approximate)",
                fullrank = "ADVI full-rank (approximate)", laplace = "Laplace approximation at the mode")
what <- if (isTRUE(values$prior_only)) "Prior predictive draws" else "Posterior"
g3 <- function(x) formatC(signif(x, 3), digits = 3, format = "fg", flag = "#")
summary <- sprintf("Bayesian %s model of %s (n = %d), %s. %s: %s has median %s (%.0f%% credible interval %s to %s); P(> 0) = %.2f.",
                   tolower(label), outcome, values$n, alg_labels[[values$algorithm]], what, focus$term,
                   g3(focus$median), cred * 100, g3(focus$lower), g3(focus$upper), focus$p_positive)
if (!is.null(values$rhat_max) && is.finite(values$rhat_max)) {
  summary <- paste0(summary, sprintf(" Largest R-hat %.3f", values$rhat_max),
                    if (is.finite(values$n_divergent)) sprintf(", %d divergent transitions", as.integer(values$n_divergent)) else "", ".")
}
if (is.finite(values$elpd_loo)) summary <- paste0(summary, sprintf(" PSIS-LOO elpd = %.1f (SE %.1f).", values$elpd_loo, values$elpd_loo_se))
statistics <- list(
  list(key = "focus_median", label = sprintf("%s (posterior median)", focus$term), value = focus$median),
  list(key = "focus_cri", label = sprintf("%.0f%% credible interval", cred * 100), value = c(focus$lower, focus$upper)),
  list(key = "focus_p_positive", label = "P(effect > 0)", value = focus$p_positive)
)
if (!is.null(values$rhat_max) && is.finite(values$rhat_max)) statistics[[length(statistics) + 1L]] <- list(key = "rhat_max", label = "Largest R-hat", value = values$rhat_max)
if (is.finite(values$elpd_loo)) statistics[[length(statistics) + 1L]] <- list(key = "elpd_loo", label = "elpd (PSIS-LOO)", value = values$elpd_loo)
if (is.finite(values$r2_median)) statistics[[length(statistics) + 1L]] <- list(key = "r2_median", label = "Bayesian R² (median)", value = values$r2_median)
notes <- c(
  paste0("Outcome model: ", label, if (!is.null(prep$event) && prep$family == "logistic") paste0("; event: ", prep$event) else "", "."),
  "Credible intervals are equal-tailed posterior quantiles; P(> 0) is the share of draws above zero.",
  "Bayesian results are not p-values and are not entered in the multiple-testing ledger.",
  fit$notes
)
cs_publish(list(
  method = "bayes.model",
  methodVersion = "1.0.1",
  title = if (isTRUE(values$prior_only)) "Prior predictive check (Stan)" else sprintf("Bayesian %s model (Stan)", tolower(label)),
  engine = cs_engine_info("posterior", "loo"),
  n = values$n,
  summary = summary,
  statistics = statistics,
  tables = fit$tables,
  assumptions = fit$assumptions,
  warnings = warnings,
  notes = notes,
  values = values,
  charts = fit$charts,
  artifacts = fit$artifacts
))
Python

Bayesian gaussian (normal) model of mpg (n = 32), Pathfinder (approximate). Posterior: wt has median -3.86 (95% credible interval -5.21 to -2.69); P(> 0) = 0.00. PSIS-LOO elpd = -78.6 (SE 4.6).

wt (posterior median)
−3.863
95% credible interval
[−5.212, −2.694]
P(effect > 0)
0
elpd (PSIS-LOO)
−78.609
Bayesian R² (median)
0.8114

Assumptions

  • Sampler converged (R-hat, ESS) — Pathfinder (approximate) gives approximate draws with no chains to compare; check important results with NUTS.
  • Leave-one-out is reliable (Pareto k̂) — Pathfinder resamples its draws, so 336 of 400 are distinct. 0 of 32 rows have k̂ above 0.62 (largest 0.50); those rows are influential and their LOO estimate is unreliable.
  • Replicated data look like the observed data — Posterior predictive p-values are between 0.01 and 0.99.
  • Priors stated — Results depend on the priors in the Priors table; rerun with wider priors to see how much.

Posterior summary

ParameterMeanSD95% lowerMedian95% upperR-hatBulk ESSTail ESSP(> 0)
(Intercept)37.3041.61433.81137.35040.120———1
wt−3.8830.5954−5.212−3.863−2.694———0
hp−0.03190.0089−0.0488−0.0318−0.0139———0
sigma2.6840.36112.1012.6573.450———1

Priors

ParameterPriorNote
(Intercept)Normal(20.09, 15.07)at the predictors' means
wtNormal(0, 15.4)autoscaled
hpNormal(0, 0.2198)autoscaled
sigmaExponential(0.1659)residual SD

Leave-one-out cross-validation (PSIS-LOO)

QuantityEstimateSE
elpd_loo (expected log predictive density)−78.6094.606
p_loo (effective number of parameters)3.9121.317
LOOIC (−2 × elpd_loo)157.229.211

Posterior predictive checks

StatisticObservedReplicated (mean)P(rep ≥ obs)
Mean20.09120.1130.4975
Standard deviation6.0276.1080.5425
Maximum33.90031.3610.1125
Minimum10.4006.9830.0400
  • Outcome model: Gaussian (normal).
  • Credible intervals are equal-tailed posterior quantiles; P(> 0) is the share of draws above zero.
  • Bayesian results are not p-values and are not entered in the multiple-testing ledger.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Bayesian regression model (Stan)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method bayes.model 1.0.1 · spec ea036d70025873fa
# Dataset: mtcars (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
import numpy as np
import pandas as pd

import codesplash as cs
from codesplash.bayes import model as bm  # data, priors and summaries (twin of codesplashr cs_bayes_*)
from codesplash.ml.run import out_dir

# %% Data
df = pd.read_parquet("tests/parity/fixtures/mtcars.parquet", columns=["mpg", "wt", "hp"])
n_input = len(df)
df = df.dropna(subset=["mpg", "wt", "hp"])  # listwise deletion over the analysis columns
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
    warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
    cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["mpg", "wt", "hp"])  # infinite values stop the run (registry/errors.yaml)

outcome = "mpg"

# %% Model: the precompiled Stan program runs on a data file R writes byte for byte the same (identical draws)
fit = bm.fit_model(
    df,
    outcome=outcome,
    predictors=["wt", "hp"],
    family="gaussian",
    trials=None,
    exposure=None,
    group=None,
    slopes=[],
    group2=None,
    nesting="nested",
    interactions="none",
    event_level=None,
    prior_dist="normal",
    prior_scale=2.5,
    prior_df=3,
    autoscale=True,
    intercept_scale=2.5,
    lkj=1,
    algorithm="pathfinder",
    chains=int(4),
    iter_warmup=int(1000),
    iter_sampling=int(400),
    seed=int(1234),
    adapt_delta=0.8,
    max_treedepth=int(10),
    use_qr=False,
    prior_only=False,
    loo=True,
    ppc=True,
    cred=0.95,
    out_dir=out_dir("target/academy-parity/run-8142/bayes.model/pathfinder-mtcars/out-python"),
)
values = fit["values"]
prep = fit["prep"]

# %% Result
cred = values["cred_level"]
fixed = [r for r in fit["rows"] if r["kind"] == "fixed"]
focus = next((r for r in fixed if r["term"] != "(Intercept)"), fixed[0] if fixed else fit["rows"][0])
label = bm.FAMILIES[prep.family]["label"]
what = "Prior predictive draws" if values["prior_only"] else "Posterior"
summary = (
    f"Bayesian {label.lower()} model of {outcome} (n = {values['n']}), {bm.ALGORITHM_LABELS[values['algorithm']]}. "
    f"{what}: {focus['term']} has median {focus['median']:.3g} ({cred:.0%} credible interval {focus['lower']:.3g} to {focus['upper']:.3g}); "
    f"P(> 0) = {focus['p_positive']:.2f}."
)
if values.get("rhat_max") is not None:
    summary += f" Largest R-hat {values['rhat_max']:.3f}"
    if values.get("n_divergent") is not None:
        summary += f", {values['n_divergent']} divergent transitions"
    summary += "."
if values.get("elpd_loo") is not None:
    summary += f" PSIS-LOO elpd = {values['elpd_loo']:.1f} (SE {values['elpd_loo_se']:.1f})."
statistics = [
    {"key": "focus_median", "label": f"{focus['term']} (posterior median)", "value": focus["median"]},
    {"key": "focus_cri", "label": f"{cred:.0%} credible interval", "value": [focus["lower"], focus["upper"]]},
    {"key": "focus_p_positive", "label": "P(effect > 0)", "value": focus["p_positive"]},
]
if values.get("rhat_max") is not None:
    statistics.append({"key": "rhat_max", "label": "Largest R-hat", "value": values["rhat_max"]})
if values.get("elpd_loo") is not None:
    statistics.append({"key": "elpd_loo", "label": "elpd (PSIS-LOO)", "value": values["elpd_loo"]})
if values.get("r2_median") is not None:
    statistics.append({"key": "r2_median", "label": "Bayesian R² (median)", "value": values["r2_median"]})
notes = [
    f"Outcome model: {label}" + (f"; event: {prep.event}" if prep.event and prep.family == "logistic" else "") + ".",
    "Credible intervals are equal-tailed posterior quantiles; P(> 0) is the share of draws above zero.",
    "Bayesian results are not p-values and are not entered in the multiple-testing ledger.",
] + fit["notes"]
cs.publish({
    "method": "bayes.model",
    "methodVersion": "1.0.1",
    "title": "Prior predictive check (Stan)" if values["prior_only"] else f"Bayesian {label.lower()} model (Stan)",
    "engine": cs.engine_info("pandas", "numpy", "scipy"),
    "n": values["n"],
    "summary": summary,
    "statistics": statistics,
    "tables": fit["tables"],
    "assumptions": fit["assumptions"],
    "warnings": warnings,
    "notes": notes,
    "values": values,
    "charts": fit["charts"],
    "artifacts": fit["artifacts"],
})

Shortened for the Academy: 3 chart(s) dropped to stay under 100 KB; 3 chart(s) dropped to stay under 100 KB.

This fit returns 400 approximate draws in moments. No R-hat or divergence count comes with them: there is no chain to diagnose, which is exactly why a NUTS check matters before reporting intervals.

05

How far is q from the posterior?

Read

A variational autoencoder trains an encoder qϕ(z∣x)q_\phi(z\mid x) with pathwise gradients. The ELBO is a lower bound on the log likelihood; an importance-weighted bound with KK samples is tighter, and the gap between them shows how far qq is from the true posterior.

Variational autoencoder (latent map, anomalies and generated rows)Recorded · Python and R agreeRecorded 2026-11-25 · 43 values compared
R

A variational autoencoder mapped 532 rows into 2 latent coordinates (2 in use); the mean squared reconstruction error is 0.492 per standardized column and the mean KL is 1.26 nats; 27 rows with a loss of at least 11 are flagged as anomalies. The importance-weighted bound with 50 draws is -9.442 nats per row (0.0661 above the ELBO estimate).

Mean reconstruction error
0.4918
Mean KL (nats per row)
1.262
Active latent dimensions
2
Trustworthiness (k = 10)
0.8356
Anomalies
27
Log-likelihood bound (IWAE, 50 draws)
−9.442

Assumptions

  • Latent dimensions in use — 2 of 2 latent dimensions vary across rows (variance of μ > 0.01).

Rows the model finds least typical

RankRowPer-row lossnpregglubpskinbmipedage
115741.5002197709934.7000.575062
239836.1730180786359.4002.42025
31133.5480137403543.1002.28833
429629.8984197703936.7002.32931
536222.1643173824838.4002.13725
627920.47901291104667.1000.319026
725719.6381883042550.496026
822218.12201806639421.89325
946015.515282522228.5001.69925
104815.056292762024.2001.69828
1120814.2221103303843.3000.183033
1240312.8669134743325.9000.460081
131312.5721189602330.1000.398059
1441712.5190173783246.5001.15958
1537512.3022127582427.7001.60025
1649112.30110681062335.5000.285047
1727212.25217163724140.9000.817047
1811112.11241891103128.5000.680037
1935812.04951031083739.2000.305065
2039612.04601891042534.3000.435041

Latent dimensions

DimensionMean KL (nats)Variance of μActive
10.53170.6583yes
20.72990.8052yes
The exact R script · R R version 4.5.1 (2025-06-13)
# Variational autoencoder (latent map, anomalies and generated rows)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.vae 1.2.0 · spec 4fb7211679042758
# Dataset: ml_pima (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)  # cs_deep_fit_vae: torch VAE with shared initial weights (twin of codesplash.deep.generative)

# %% Data — standardized numbers (median-imputed), one-hot categories
IMPUTE <- "median"
SCALE <- "standard"
cs_check_finite_columns(as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_pima.parquet", col_select = c("npreg", "glu", "bp", "skin", "bmi", "ped", "age"))), c("npreg", "glu", "bp", "skin", "bmi", "ped", "age"))
# Training options, live progress and checkpoints (twin: codesplash.deep.trainer.configure).
cs_deep_trainer_configure(list(
  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/discover.vae/pima_iwae_normal/out-r")
FEATURES <- c("npreg", "glu", "bp", "skin", "bmi", "ped", "age")
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_pima.parquet", col_select = FEATURES))
warnings <- list()
design <- cs_ml_design(
  df, FEATURES,
  kinds = list(
    npreg = "numeric",
    glu = "numeric",
    bp = "numeric",
    skin = "numeric",
    bmi = "numeric",
    ped = "numeric",
    age = "numeric"
  ),
  levels = list(
  ),
  impute = IMPUTE,
  scale = SCALE
)
fitted <- cs_ml_design_fit(design, df)
X <- unname(cs_ml_design_apply(fitted, df))  # numbers imputed / scaled; categories one-hot (missing -> all zero)
rows <- seq_len(nrow(df)) - 1L
LABEL <- NULL
if (!is.null(LABEL)) df[[LABEL]] <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_pima.parquet", col_select = LABEL))[[LABEL]]

# %% Variational autoencoder (torch for R, float64, one thread): encoder -> (mu, log sigma^2) -> z = mu + sigma * eps -> decoder
HIDDEN <- as.integer(unlist(c(12)))
LATENT <- as.integer(2)
BETA <- 1
N_SAMPLES <- as.integer(0)
PRIOR <- "normal"  # N(0, I), or a learned Gaussian mixture (VaDE)
IWAE <- as.integer(50)
if (PRIOR == "mixture" && length(rows) <= 3) {
  cs_error("CS_E_TOO_FEW_ROWS", what = "A 3-component mixture prior", min = 3 + 1, n = length(rows))
}
fit <- if (PRIOR == "mixture") {
  cs_deep_fit_vade(
    X, HIDDEN, LATENT, as.integer(3),
    activation = "tanh",
    beta = BETA,
    epochs = as.integer(100),
    lr = 0.005,
    batch_size = 128,
    weight_decay = 0,
    n_samples = N_SAMPLES,
    pretrain_epochs = as.integer(100),
    seed = 42
  )
} else {
  cs_deep_fit_vae(
    X, HIDDEN, LATENT,
    activation = "tanh",
    beta = BETA,
    epochs = as.integer(100),
    lr = 0.005,
    batch_size = 128,
    weight_decay = 0,
    n_samples = N_SAMPLES,
    seed = 42
  )
}
if (any(!is.finite(fit$score))) cs_error("CS_E_NO_CONVERGENCE", what = "Variational autoencoder training")
Z <- fit$embedding  # posterior means mu (n x LATENT)
scores <- fit$score  # squared reconstruction error at z = mu plus beta x KL, per row
errors <- fit$error  # mean squared reconstruction error per standardized column

# %% Anomalies by the per-row loss
RULE <- "share"
flagged <- cs_ml_flag(scores, RULE, 0.05, 10)
flags <- flagged$flag
threshold <- flagged$threshold
ord <- order(-scores, rows)  # largest loss first, ties by row

# %% Neighborhood preservation of the map (same rows in both engines)
sample <- cs_ml_sample_rows(length(rows))
k_eval <- min(10L, length(sample) - 2L)
trust <- if (k_eval >= 1L) cs_ml_trustworthiness(X[sample, , drop = FALSE], Z[sample, , drop = FALSE], k_eval) else NaN  # undefined with fewer than 3 rows

# %% Mixture prior: each row's component at z = mu (canonical ids 1..k by size)
clusters <- NULL
if (PRIOR == "mixture") {
  clusters <- cs_ml_canonical(fit$cluster)
  comp_of <- integer(0)
  for (j in seq_along(fit$pi)) {
    members <- which(fit$cluster == j - 1L)
    if (length(members)) comp_of[as.character(j)] <- clusters[members[1]]
  }
}

# %% Importance-weighted bound on log p(x) (and the ELBO from the same draws)
bound <- if (IWAE > 0L) cs_deep_iwae_bound(X, fit, LATENT, "tanh", IWAE, 42) else NULL

# %% Generated rows: decode prior draws back to the columns' units
gen_cols <- if (N_SAMPLES > 0L) cs_deep_decode_design(fitted, fit$samples) else list()
NUMERIC <- Filter(function(f) identical(design$kinds[[f]], "numeric"), FEATURES)
sample_ks <- list()
if (N_SAMPLES > 0L) for (f in NUMERIC) sample_ks[[f]] <- cs_deep_ks(suppressWarnings(as.numeric(df[[f]])), gen_cols[[f]])

# %% Artifacts
out <- cs_ml_out_dir("target/academy-parity/run-8142/discover.vae/pima_iwae_normal/out-r")
emb <- data.frame(row = as.integer(rows))
for (j in seq_len(LATENT)) emb[[paste0("dim_", j)]] <- Z[, j]
nanoparquet::write_parquet(emb, file.path(out, "embedding.parquet"))
labels_df <- data.frame(row = as.integer(rows), score = scores, anomaly = flags)
if (!is.null(clusters)) labels_df$cluster <- as.integer(clusters)
nanoparquet::write_parquet(labels_df, file.path(out, "labels.parquet"))
hist <- data.frame(
  epoch = vapply(fit$history, function(h) as.numeric(h$epoch), numeric(1)),
  loss = vapply(fit$history, function(h) h$loss, numeric(1)),
  reconstruction = vapply(fit$history, function(h) h$recon, numeric(1)),
  kl = vapply(fit$history, function(h) h$kl, numeric(1))
)
nanoparquet::write_parquet(hist, file.path(out, "history.parquet"))
artifacts <- list(
  list(key = "embedding", path = file.path(out, "embedding.parquet"), format = "parquet"),
  list(key = "labels", path = file.path(out, "labels.parquet"), format = "parquet"),
  list(key = "history", path = file.path(out, "history.parquet"), format = "parquet")
)
if (N_SAMPLES > 0L) {
  nanoparquet::write_parquet(as.data.frame(gen_cols[FEATURES], check.names = FALSE), file.path(out, "samples.parquet"))
  artifacts[[length(artifacts) + 1L]] <- list(key = "samples", path = file.path(out, "samples.parquet"), format = "parquet",
                                              title = "Rows generated from the prior")
}

# %% Result
active <- as.integer(fit$active)
values <- list(
  n = length(rows), n_features = ncol(X), latent_dim = LATENT, recon_mse = mean(errors), kl = mean(fit$kl_row),
  elbo_loss = mean(scores), active_dims = active, error_check = cs_ml_checksum(scores, rows), n_flagged = sum(flags),
  threshold = threshold, final_loss = hist$loss[nrow(hist)], epochs_run = fit$epochs_run, trustworthiness = trust,
  n_samples = N_SAMPLES, sample_ks_mean = if (length(sample_ks)) mean(unlist(sample_ks)) else NaN
)
for (j in seq_len(LATENT)) {
  values[[sprintf("emb_check[%d]", j)]] <- cs_ml_checksum(Z[, j], rows)
  values[[sprintf("kl_dim[%d]", j)]] <- fit$kl_dim[j]
}
for (f in names(sample_ks)) values[[sprintf("sample_ks[%s]", f)]] <- sample_ks[[f]]
if (!is.null(clusters)) {
  values$components <- length(fit$pi)
  values$n_clusters <- length(comp_of)
  for (j in names(comp_of)) {
    values[[sprintf("pi[%d]", comp_of[[j]])]] <- fit$pi[as.integer(j)]
    values[[sprintf("cluster_size[%d]", comp_of[[j]])]] <- sum(clusters == comp_of[[j]])
  }
}
if (!is.null(bound)) {
  values$iwae_samples <- IWAE
  values$iwae_bound <- mean(bound$iwae)
  values$elbo_estimate <- mean(bound$elbo)
  values$iwae_gap <- values$iwae_bound - values$elbo_estimate
}
for (rank in seq_len(min(10L, length(ord)))) {
  values[[sprintf("top_row[%d]", rank)]] <- rows[ord[rank]]
  values[[sprintf("top_score[%d]", rank)]] <- scores[ord[rank]]
}
top <- utils::head(ord, 20L)
table_rows <- lapply(seq_along(top), function(rank) {
  i <- top[rank]
  r <- list(rank = rank, row = rows[i] + 1L, score = scores[i])
  for (f in FEATURES) {
    v <- df[[f]][rows[i] + 1L]
    r[[f]] <- if (is.na(v)) NULL else if (is.numeric(v)) v else as.character(v)
  }
  r
})
dim_rows <- lapply(seq_len(LATENT), function(j) list(dim = j, kl = fit$kl_dim[j], var_mu = fit$mu_var[j], active = fit$mu_var[j] > 0.01))
pick <- cs_ml_sample_rows(length(rows), 5000)
groups <- if (is.null(LABEL)) rep("All rows", length(pick)) else {
  g <- df[[LABEL]][rows[pick] + 1L]
  ifelse(is.na(g), "(missing)", as.character(g))
}
charts <- list()
if (LATENT >= 2L && !is.null(clusters)) {
  cent_ <- as.integer(names(comp_of))[order(comp_of)]
  charts[[length(charts) + 1L]] <- cs_chart("latent", "cluster-scatter", "Latent means by mixture component (component means marked)", list(
    x = cs_col("Latent 1 (μ)", c(Z[pick, 1], fit$mu_c[cent_, 1]), "numeric"),
    y = cs_col("Latent 2 (μ)", c(Z[pick, 2], fit$mu_c[cent_, 2]), "numeric"),
    cluster = cs_col("Component", c(as.character(clusters[pick]), as.character(comp_of[as.character(cent_)])), "categorical",
                     levels = as.character(sort(as.integer(comp_of)))),
    centroid = cs_col("Component mean", c(rep(FALSE, length(pick)), rep(TRUE, length(cent_))), "boolean")
  ), note = if (length(pick) == length(rows)) NULL else sprintf("%s of %s rows shown.", format(length(pick), big.mark = ","), format(length(rows), big.mark = ",")))
} else if (LATENT >= 2L) {
  charts[[length(charts) + 1L]] <- cs_chart("latent", "latent-prior", "Latent means against the N(0, I) prior", list(
    x = cs_col("Latent 1 (μ)", Z[pick, 1], "numeric"),
    y = cs_col("Latent 2 (μ)", Z[pick, 2], "numeric"),
    group = cs_col(if (is.null(LABEL)) "Group" else LABEL, groups, "categorical")
  ), note = if (length(pick) == length(rows)) NULL else sprintf("%s of %s rows shown.", format(length(pick), big.mark = ","), format(length(rows), big.mark = ",")))
}
charts[[length(charts) + 1L]] <- cs_chart("errors", "anomaly-scores", "Per-row loss (reconstruction + β·KL) distribution", list(
  score = cs_col("Per-row loss", scores, "numeric"),
  anomaly = cs_col("Anomaly", flags, "boolean")
), controls = list(threshold = threshold))
ne <- nrow(hist)
charts[[length(charts) + 1L]] <- cs_chart("training", "training-components", "Training loss and its parts by epoch", list(
  x = cs_col("Epoch", rep(hist$epoch, 3), "numeric"),
  value = cs_col("Loss per row", c(hist$loss, hist$reconstruction, hist$kl), "numeric"),
  component = cs_col("Part", rep(c("total", "reconstruction", "KL"), each = ne), "categorical", levels = c("total", "reconstruction", "KL"))
))
if (length(sample_ks)) {
  f0 <- NUMERIC[1]
  d <- cs_synth_density_rows(suppressWarnings(as.numeric(df[[f0]])), as.numeric(gen_cols[[f0]]))
  if (!is.null(d)) {
    charts[[length(charts) + 1L]] <- cs_chart("samples", "density-compare", sprintf("%s: data vs rows generated from the prior", f0), list(
      x = cs_col(f0, d$x, "numeric"), density = cs_col("Density", d$density, "numeric"),
      source = cs_col("Source", d$source, "categorical", levels = c("real", "synthetic"))))
  }
}
assumptions <- list(list(
  key = "active_units", label = "Latent dimensions in use",
  status = if (active == LATENT) "pass" else if (active == 0L) "fail" else "warn",
  detail = paste0(sprintf("%d of %d latent dimension%s vary across rows (variance of μ > 0.01)", active, LATENT, if (LATENT != 1L) "s" else ""),
                  if (active == LATENT) "." else "; the rest collapsed onto the prior and carry no information about the rows.")
))
if (active < LATENT) {
  warnings <- c(warnings, sprintf("Posterior collapse: %d latent dimension%s carry no information (KL ≈ 0). Lower β, shrink the bottleneck, or train longer.",
                                  LATENT - active, if (LATENT - active != 1L) "s" else ""))
}
summary <- sprintf("A variational autoencoder mapped %d rows into %d latent coordinate%s (%d in use); the mean squared reconstruction error is %s per standardized column and the mean KL is %s nats; %d rows with a loss of at least %s are flagged as anomalies.",
                   length(rows), LATENT, if (LATENT != 1L) "s" else "", active, format(signif(mean(errors), 3)), format(signif(mean(fit$kl_row), 3)),
                   sum(flags), format(signif(threshold, 3)))
if (length(sample_ks)) summary <- paste0(summary, sprintf(" %d rows generated from the prior differ from the data by a mean KS distance of %.3f.", N_SAMPLES, values$sample_ks_mean))
if (!is.null(clusters)) summary <- paste0(summary, sprintf(" The mixture prior's %d components hold %d cluster%s of rows.", length(fit$pi), length(comp_of), if (length(comp_of) != 1L) "s" else ""))
if (!is.null(bound)) summary <- paste0(summary, sprintf(" The importance-weighted bound with %d draws is %s nats per row (%s above the ELBO estimate).", IWAE,
                                                       format(signif(values$iwae_bound, 4)), format(signif(values$iwae_gap, 3))))
extra_stats <- list()
if (!is.null(bound)) extra_stats[[1]] <- list(key = "iwae_bound", label = sprintf("Log-likelihood bound (IWAE, %d draws)", IWAE), value = values$iwae_bound)
extra_tables <- list()
if (!is.null(clusters)) {
  ordj <- as.integer(names(comp_of))[order(comp_of)]
  extra_tables[[1]] <- list(
    key = "components", title = "Mixture prior components",
    columns = c(list(list(key = "cluster", label = "Component", type = "integer"), list(key = "size", label = "Rows", type = "integer"),
                     list(key = "weight", label = "Prior weight", type = "number")),
                lapply(seq_len(LATENT), function(d) list(key = sprintf("mu_%d", d), label = sprintf("Mean %d", d), type = "number"))),
    rows = lapply(ordj, function(j) {
      cc <- comp_of[[as.character(j)]]
      r <- list(cluster = cc, size = sum(clusters == cc), weight = fit$pi[j])
      for (d in seq_len(LATENT)) r[[sprintf("mu_%d", d)]] <- fit$mu_c[j, d]
      r
    })
  )
}
cs_publish(list(
  title = "Variational autoencoder (latent map, anomalies and generated rows)",
  engine = cs_engine_info("torch", "nanoparquet"),
  n = length(rows),
  summary = summary,
  statistics = c(list(
    list(key = "recon_mse", label = "Mean reconstruction error", value = mean(errors)),
    list(key = "kl", label = "Mean KL (nats per row)", value = mean(fit$kl_row)),
    list(key = "active_dims", label = "Active latent dimensions", value = active, format = "integer"),
    list(key = "trustworthiness", label = sprintf("Trustworthiness (k = %d)", k_eval), value = trust),
    list(key = "n_flagged", label = "Anomalies", value = sum(flags), format = "integer")
  ), extra_stats),
  tables = c(list(
    list(
      key = "top", title = "Rows the model finds least typical",
      columns = c(list(list(key = "rank", label = "Rank", type = "integer"), list(key = "row", label = "Row", type = "integer"),
                       list(key = "score", label = "Per-row loss", type = "number")),
                  lapply(FEATURES, function(f) list(key = f, label = f))),
      rows = table_rows
    ),
    list(
      key = "latent", title = "Latent dimensions",
      columns = list(list(key = "dim", label = "Dimension", type = "integer"), list(key = "kl", label = "Mean KL (nats)", type = "number"),
                     list(key = "var_mu", label = "Variance of μ", type = "number"), list(key = "active", label = "Active", type = "boolean")),
      rows = dim_rows
    )
  ), extra_tables),
  charts = charts,
  assumptions = assumptions,
  values = values,
  warnings = warnings,
  artifacts = artifacts
))
Python

A variational autoencoder mapped 532 rows into 2 latent coordinates (2 in use); the mean squared reconstruction error is 0.492 per standardized column and the mean KL is 1.26 nats; 27 rows with a loss of at least 11 are flagged as anomalies. The importance-weighted bound with 50 draws is -9.442 nats per row (0.0661 above the ELBO estimate).

Mean reconstruction error
0.4918
Mean KL (nats per row)
1.262
Active latent dimensions
2
Trustworthiness (k = 10)
0.8356
Anomalies
27
Log-likelihood bound (IWAE, 50 draws)
−9.442

Assumptions

  • Latent dimensions in use — 2 of 2 latent dimensions vary across rows (variance of μ > 0.01).

Rows the model finds least typical

RankRowPer-row lossnpregglubpskinbmipedage
115741.5002197709934.7000.575062
239836.1730180786359.4002.42025
31133.5480137403543.1002.28833
429629.8984197703936.7002.32931
536222.1643173824838.4002.13725
627920.47901291104667.1000.319026
725719.6381883042550.496026
822218.12201806639421.89325
946015.515282522228.5001.69925
104815.056292762024.2001.69828
1120814.2221103303843.3000.183033
1240312.8669134743325.9000.460081
131312.5721189602330.1000.398059
1441712.5190173783246.5001.15958
1537512.3022127582427.7001.60025
1649112.30110681062335.5000.285047
1727212.25217163724140.9000.817047
1811112.11241891103128.5000.680037
1935812.04951031083739.2000.305065
2039612.04601891042534.3000.435041

Latent dimensions

DimensionMean KL (nats)Variance of μActive
10.53170.6583yes
20.72990.8052yes
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Variational autoencoder (latent map, anomalies and generated rows)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.vae 1.2.0 · spec 4fb7211679042758
# Dataset: ml_pima (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 import ml as csml
from codesplash.deep import generative as gen  # twin of codesplashr::cs_deep_fit_vae (shared initial weights, Adam written out)
from codesplash.deep import unsupervised as du  # VaDE prior and the importance-weighted bound (twin of codesplashr::cs_deep_fit_vade)
from codesplash.ml import anomaly as csanom
from codesplash.ml import embed as csembed
from codesplash.synth import common as sy

# %% Data — standardized numbers (median-imputed), one-hot categories
IMPUTE = "median"
SCALE = "standard"
cs.check_finite_columns(pd.read_parquet("tests/parity/fixtures/ml_pima.parquet", columns=["npreg", "glu", "bp", "skin", "bmi", "ped", "age"]), ["npreg", "glu", "bp", "skin", "bmi", "ped", "age"])
from codesplash.deep import trainer as deep_trainer  # training options, live progress, checkpoints (twin: cs_deep_trainer_*)

deep_trainer.configure(
    {
        "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/discover.vae/pima_iwae_normal/out-python",
)
FEATURES = ["npreg", "glu", "bp", "skin", "bmi", "ped", "age"]
df = pd.read_parquet("tests/parity/fixtures/ml_pima.parquet", columns=FEATURES)
warnings = []
design = csml.Design.for_frame(
    df,
    FEATURES,
    kinds={
        "npreg": "numeric",
        "glu": "numeric",
        "bp": "numeric",
        "skin": "numeric",
        "bmi": "numeric",
        "ped": "numeric",
        "age": "numeric",
    },
    levels={
    },
    impute=IMPUTE,
    scale=SCALE,
)
fitted = design.fit(df)
X = fitted.transform(df)  # numbers imputed / scaled; categories one-hot (missing → all zero)
rows = np.arange(len(df))
LABEL = None
if LABEL:
    df[LABEL] = pd.read_parquet("tests/parity/fixtures/ml_pima.parquet", columns=[LABEL])[LABEL]

# %% Variational autoencoder (PyTorch, float64, one thread): encoder → (μ, log σ²) → z = μ + σ·ε → decoder
HIDDEN = [int(u) for u in [12]]
LATENT = 2
BETA = 1
N_SAMPLES = 0
PRIOR = "normal"  # N(0, I), or a learned Gaussian mixture (VaDE)
IWAE = 50
if PRIOR == "mixture" and len(rows) <= 3:
    cs.cs_error("CS_E_TOO_FEW_ROWS", what="A 3-component mixture prior", min=3 + 1, n=len(rows))
if PRIOR == "mixture":
    fit = du.fit_vade(
        X, HIDDEN, LATENT, 3,
        activation="tanh",
        beta=BETA,
        epochs=100,
        lr=0.005,
        batch_size=128,
        weight_decay=0,
        n_samples=N_SAMPLES,
        pretrain_epochs=100,
        seed=42,
    )
else:
    fit = gen.fit_vae(
        X, HIDDEN, LATENT,
        activation="tanh",
        beta=BETA,
        epochs=100,
        lr=0.005,
        batch_size=128,
        weight_decay=0,
        n_samples=N_SAMPLES,
        seed=42,
    )
if not np.all(np.isfinite(fit["score"])):
    cs.cs_error("CS_E_NO_CONVERGENCE", what="Variational autoencoder training")
Z = fit["embedding"]  # posterior means μ (n × LATENT)
scores = fit["score"]  # squared reconstruction error at z = μ plus β × KL, per row
errors = fit["error"]  # mean squared reconstruction error per standardized column

# %% Anomalies by the per-row loss
RULE = "share"
flags, threshold = csanom.flag(scores, RULE, 0.05, 10)
order = np.lexsort((rows, -scores))  # largest loss first, ties by row

# %% Neighborhood preservation of the map (same rows in both engines)
sample = csembed.sample_rows(len(rows))
k_eval = min(10, len(sample) - 2)
trust = csembed.trustworthiness(X[sample], Z[sample], k_eval) if k_eval >= 1 else float("nan")  # undefined with fewer than 3 rows

# %% Mixture prior: each row's component at z = μ (canonical ids 1…k by size)
clusters = None
if PRIOR == "mixture":
    from codesplash.ml import cluster as csc

    clusters = csc.canonical(fit["cluster"])
    comp_of = {}
    for j in range(len(fit["pi"])):
        members = np.flatnonzero(fit["cluster"] == j)
        if len(members):
            comp_of[j] = int(clusters[members[0]])

# %% Importance-weighted bound on log p(x) (and the ELBO from the same draws)
bound = du.iwae_bound(X, fit, LATENT, "tanh", IWAE, 42) if IWAE > 0 else None

# %% Generated rows: decode prior draws back to the columns' units
gen_cols = gen.decode_design(fitted, fit["samples"]) if N_SAMPLES > 0 else {}
NUMERIC = [f for f in FEATURES if design.kinds[f] == "numeric"]
sample_ks = {}
for f in NUMERIC if N_SAMPLES > 0 else []:
    real = pd.to_numeric(df[f], errors="coerce").to_numpy(dtype=np.float64)
    sample_ks[f] = gen.ks_distance(real, gen_cols[f])

# %% Artifacts
out = csml.out_dir("target/academy-parity/run-8142/discover.vae/pima_iwae_normal/out-python")
emb = pd.DataFrame({"row": rows.astype(np.int64), **{f"dim_{j + 1}": Z[:, j] for j in range(LATENT)}})
emb.to_parquet(os.path.join(out, "embedding.parquet"), index=False)
pd.DataFrame({"row": rows.astype(np.int64), "score": scores, "anomaly": flags, **({"cluster": clusters} if clusters is not None else {})}).to_parquet(
    os.path.join(out, "labels.parquet"), index=False
)
history = pd.DataFrame({
    "epoch": [h["epoch"] for h in fit["history"]],
    "loss": [h["loss"] for h in fit["history"]],
    "reconstruction": [h["recon"] for h in fit["history"]],
    "kl": [h["kl"] for h in fit["history"]],
})
history.to_parquet(os.path.join(out, "history.parquet"), index=False)
artifacts = [
    {"key": "embedding", "path": os.path.join(out, "embedding.parquet"), "format": "parquet"},
    {"key": "labels", "path": os.path.join(out, "labels.parquet"), "format": "parquet"},
    {"key": "history", "path": os.path.join(out, "history.parquet"), "format": "parquet"},
]
if N_SAMPLES > 0:
    pd.DataFrame({f: gen_cols[f] for f in FEATURES}).to_parquet(os.path.join(out, "samples.parquet"), index=False)
    artifacts.append({"key": "samples", "path": os.path.join(out, "samples.parquet"), "format": "parquet", "title": "Rows generated from the prior"})

# %% Result
active = int(fit["active"])
values = {
    "n": len(rows),
    "n_features": int(X.shape[1]),
    "latent_dim": LATENT,
    "recon_mse": float(np.mean(errors)),
    "kl": float(np.mean(fit["kl_row"])),
    "elbo_loss": float(np.mean(scores)),
    "active_dims": active,
    "error_check": csembed.checksum(scores, rows),
    "n_flagged": int(flags.sum()),
    "threshold": float(threshold),
    "final_loss": float(fit["history"][-1]["loss"]),
    "epochs_run": int(fit["epochs_run"]),
    "trustworthiness": trust,
    "n_samples": N_SAMPLES,
    "sample_ks_mean": float(np.mean(list(sample_ks.values()))) if sample_ks else float("nan"),
}
for j in range(LATENT):
    values[f"emb_check[{j + 1}]"] = csembed.checksum(Z[:, j], rows)
    values[f"kl_dim[{j + 1}]"] = float(fit["kl_dim"][j])
for f, v in sample_ks.items():
    values[f"sample_ks[{f}]"] = v
if clusters is not None:
    values["components"] = int(len(fit["pi"]))
    values["n_clusters"] = len(comp_of)
    for j, c in comp_of.items():
        values[f"pi[{c}]"] = float(fit["pi"][j])
        values[f"cluster_size[{c}]"] = int(np.sum(clusters == c))
if bound is not None:
    values["iwae_samples"] = IWAE
    values["iwae_bound"] = float(np.mean(bound["iwae"]))
    values["elbo_estimate"] = float(np.mean(bound["elbo"]))
    values["iwae_gap"] = values["iwae_bound"] - values["elbo_estimate"]
for rank, i in enumerate(order[:10], start=1):
    values[f"top_row[{rank}]"] = int(rows[i])
    values[f"top_score[{rank}]"] = float(scores[i])
table_rows = []
for rank, i in enumerate(order[:20], start=1):
    r = {"rank": rank, "row": int(rows[i]) + 1, "score": float(scores[i])}
    for f in FEATURES:
        v = df[f].iloc[rows[i]]
        r[f] = None if pd.isna(v) else (v if isinstance(v, (int, float)) else str(v))  # None, NaN, pd.NA, NaT
    table_rows.append(r)
dim_rows = [{"dim": j + 1, "kl": float(fit["kl_dim"][j]), "var_mu": float(fit["mu_var"][j]), "active": bool(fit["mu_var"][j] > 0.01)} for j in range(LATENT)]
pick = csembed.sample_rows(len(rows), 5000)
groups = [("All rows" if LABEL is None else ("(missing)" if pd.isna(v) else str(v))) for v in (df[LABEL].iloc[rows[pick]] if LABEL else [None] * len(pick))]
charts = []
if LATENT >= 2 and clusters is not None:
    _cent = sorted(comp_of, key=lambda j: comp_of[j])
    charts.append(cs.chart("latent", "cluster-scatter", "Latent means by mixture component (component means marked)", {
        "x": cs.col("Latent 1 (μ)", list(Z[pick, 0]) + [float(fit["mu_c"][j, 0]) for j in _cent], "numeric"),
        "y": cs.col("Latent 2 (μ)", list(Z[pick, 1]) + [float(fit["mu_c"][j, 1]) for j in _cent], "numeric"),
        "cluster": cs.col("Component", [str(c) for c in clusters[pick]] + [str(comp_of[j]) for j in _cent], "categorical",
                          levels=[str(c) for c in sorted(comp_of.values())]),
        "centroid": cs.col("Component mean", [False] * len(pick) + [True] * len(_cent), "boolean"),
    }, note=None if len(pick) == len(rows) else f"{len(pick):,} of {len(rows):,} rows shown."))
elif LATENT >= 2:
    charts.append(cs.chart("latent", "latent-prior", "Latent means against the N(0, I) prior", {
        "x": cs.col("Latent 1 (μ)", Z[pick, 0], "numeric"),
        "y": cs.col("Latent 2 (μ)", Z[pick, 1], "numeric"),
        "group": cs.col(LABEL or "Group", groups, "categorical"),
    }, note=None if len(pick) == len(rows) else f"{len(pick):,} of {len(rows):,} rows shown."))
charts.append(cs.chart("errors", "anomaly-scores", "Per-row loss (reconstruction + β·KL) distribution", {
    "score": cs.col("Per-row loss", scores, "numeric"),
    "anomaly": cs.col("Anomaly", [bool(x) for x in flags], "boolean"),
}, controls={"threshold": float(threshold)}))
ep = [h["epoch"] for h in fit["history"]]
charts.append(cs.chart("training", "training-components", "Training loss and its parts by epoch", {
    "x": cs.col("Epoch", ep * 3, "numeric"),
    "value": cs.col("Loss per row", [h["loss"] for h in fit["history"]] + [h["recon"] for h in fit["history"]] + [h["kl"] for h in fit["history"]], "numeric"),
    "component": cs.col("Part", ["total"] * len(ep) + ["reconstruction"] * len(ep) + ["KL"] * len(ep), "categorical", levels=["total", "reconstruction", "KL"]),
}))
if sample_ks:
    f0 = NUMERIC[0]
    xs, dens, src = sy.density_rows(pd.to_numeric(df[f0], errors="coerce").to_numpy(dtype=np.float64), np.asarray(gen_cols[f0], dtype=np.float64))
    if xs:
        charts.append(cs.chart("samples", "density-compare", f"{f0}: data vs rows generated from the prior", {
            "x": cs.col(f0, xs, "numeric"),
            "density": cs.col("Density", dens, "numeric"),
            "source": cs.col("Source", src, "categorical", levels=["real", "synthetic"]),
        }))
assumptions = [{
    "key": "active_units",
    "label": "Latent dimensions in use",
    "status": "pass" if active == LATENT else ("fail" if active == 0 else "warn"),
    "detail": f"{active} of {LATENT} latent dimension{'s' if LATENT != 1 else ''} vary across rows (variance of μ > 0.01)"
              + ("." if active == LATENT else "; the rest collapsed onto the prior and carry no information about the rows."),
}]
if active < LATENT:
    warnings.append(f"Posterior collapse: {LATENT - active} latent dimension{'s' if LATENT - active != 1 else ''} carry no information (KL ≈ 0). Lower β, shrink the bottleneck, or train longer.")
summary = (
    f"A variational autoencoder mapped {len(rows)} rows into {LATENT} latent coordinate{'s' if LATENT != 1 else ''} "
    f"({active} in use); the mean squared reconstruction error is {np.mean(errors):.3g} per standardized column and the mean KL is "
    f"{np.mean(fit['kl_row']):.3g} nats; {int(flags.sum())} rows with a loss of at least {threshold:.3g} are flagged as anomalies."
)
if sample_ks:
    summary += f" {N_SAMPLES} rows generated from the prior differ from the data by a mean KS distance of {values['sample_ks_mean']:.3f}."
if clusters is not None:
    summary += f" The mixture prior's {len(fit['pi'])} components hold {len(comp_of)} cluster{'s' if len(comp_of) != 1 else ''} of rows."
if bound is not None:
    summary += f" The importance-weighted bound with {IWAE} draws is {values['iwae_bound']:.4g} nats per row ({values['iwae_gap']:.3g} above the ELBO estimate)."
extra_stats = []
if bound is not None:
    extra_stats.append({"key": "iwae_bound", "label": f"Log-likelihood bound (IWAE, {IWAE} draws)", "value": values["iwae_bound"]})
extra_tables = []
if clusters is not None:
    extra_tables.append({
        "key": "components",
        "title": "Mixture prior components",
        "columns": [{"key": "cluster", "label": "Component", "type": "integer"}, {"key": "size", "label": "Rows", "type": "integer"},
                    {"key": "weight", "label": "Prior weight", "type": "number"}]
                   + [{"key": f"mu_{d + 1}", "label": f"Mean {d + 1}", "type": "number"} for d in range(LATENT)],
        "rows": [{"cluster": comp_of[j], "size": int(np.sum(clusters == comp_of[j])), "weight": float(fit["pi"][j]),
                  **{f"mu_{d + 1}": float(fit["mu_c"][j, d]) for d in range(LATENT)}} for j in sorted(comp_of, key=lambda j: comp_of[j])],
    })
cs.publish({
    "title": "Variational autoencoder (latent map, anomalies and generated rows)",
    "engine": cs.engine_info("torch", "numpy", "pandas"),
    "n": len(rows),
    "summary": summary,
    "statistics": [
        {"key": "recon_mse", "label": "Mean reconstruction error", "value": float(np.mean(errors))},
        {"key": "kl", "label": "Mean KL (nats per row)", "value": float(np.mean(fit["kl_row"]))},
        {"key": "active_dims", "label": "Active latent dimensions", "value": active, "format": "integer"},
        {"key": "trustworthiness", "label": f"Trustworthiness (k = {k_eval})", "value": trust},
        {"key": "n_flagged", "label": "Anomalies", "value": int(flags.sum()), "format": "integer"},
    ] + extra_stats,
    "tables": [
        {
            "key": "top",
            "title": "Rows the model finds least typical",
            "columns": [{"key": "rank", "label": "Rank", "type": "integer"}, {"key": "row", "label": "Row", "type": "integer"},
                        {"key": "score", "label": "Per-row loss", "type": "number"}] + [{"key": f, "label": f} for f in FEATURES],
            "rows": table_rows,
        },
        {
            "key": "latent",
            "title": "Latent dimensions",
            "columns": [{"key": "dim", "label": "Dimension", "type": "integer"}, {"key": "kl", "label": "Mean KL (nats)", "type": "number"},
                        {"key": "var_mu", "label": "Variance of μ", "type": "number"}, {"key": "active", "label": "Active", "type": "boolean"}],
            "rows": dim_rows,
        },
    ] + extra_tables,
    "charts": charts,
    "assumptions": assumptions,
    "values": values,
    "warnings": warnings,
    "artifacts": artifacts,
})

Shortened for the Academy: 3 chart(s) dropped to stay under 100 KB; 3 chart(s) dropped to stay under 100 KB.

Here the ELBO estimate is −9.51 per row and the bound with 50 samples is −9.44, a gap of 0.066. A gap of zero would mean qq matched the posterior.

06

Particles instead of a family: SVGD

Read

Stein variational gradient descentStein variational gradient descentMoves a set of particles together: each is pulled toward high posterior density and pushed away from the others by a kernel. represents the posterior by NN particles and moves them all at once:

ϕ(θ)=1N∑j=1N[k(θj,θ) ∇log⁡p(θj)+∇θjk(θj,θ)],θi←θi+ϵ ϕ(θi).\phi(\theta)=\frac1N\sum_{j=1}^N\Big[k(\theta_j,\theta)\,\nabla\log p(\theta_j)+\nabla_{\theta_j}k(\theta_j,\theta)\Big],\qquad \theta_i\leftarrow\theta_i+\epsilon\,\phi(\theta_i).

The first term pulls particles toward high density (one particle alone is plain gradient ascent to the mode). The second, the kernel's gradient, pushes them apart so they spread out. In the reference's example three particles at −1,0,1-1, 0, 1 move toward a normal target centered at 2; the first moves to −0.884.

Reference · INF018 · Explained hereStein variational gradient descent (SVGD)Moves interacting particles along a kernel-defined variational direction combining attraction toward high posterior density with repulsion. It offers a particle representation without ordinary MCMC accept/reject steps;
07

Particles aren't independent draws

Read

SVGD is deterministic: its particles are an optimized set, not posterior samples. A few particles in many dimensions usually understate the spread, the kernel bandwidth changes the answer, and repulsion doesn't guarantee every mode gets a particle. Every particle update must use the same previous set, and the kernel's derivative must be taken in its first argument; a sign slip turns repulsion into attraction.

Check SVGD as you would any approximation: plot the particles against a known density in low dimensions, try several particle counts and bandwidths, and compare moments with a reference.

08

Where each idea stands in CodeSplash

Read
EntryIn CodeSplash
Black-box VI and pathwise gradients (INF004)Runs in CodeSplash: ADVI mean-field and full-rank and Pathfinder in Bayesian regression model (Stan); the reparameterized ELBO in Variational autoencoder (Discover)
SVGD (INF018)Explained here: no particle-VI method; the reference's single update is a verified component check
09

Check your understanding

Checkpoint

Check yourself

Your model has a discrete latent variable. Which ELBO gradient estimator can you use without any relaxation?

Show the answer

Answer: b

Pathwise gradients differentiate through a continuous sample. The score-function estimator works for discrete latents, at the cost of higher variance (use baselines), or you can sum the latent out.

Check yourself

A mean-field ADVI fit used many Monte Carlo samples per step, so its ELBO gradients were nearly exact. Are its 95% intervals trustworthy?

Show the answer

Answer: b

Gradient quality and family quality are separate. The optimizer can only be as right as the family it searches.

Check yourself

Why do variational autoencoders train with the pathwise estimator rather than the score-function estimator?

Show the answer

Answer: b

Reparameterization moves the randomness into ϵ\epsilon, so gradients flow through μ\mu and σ\sigma directly.

Check yourself

What does the kernel-gradient term in an SVGD update do?

Show the answer

Answer: b

The weighted score term attracts; the kernel-gradient term repels. With one particle there is nothing to repel, and SVGD becomes gradient ascent.

Check yourself

Ten SVGD particles for a 50-parameter Bayesian network head have a small spread. What's the right reading?

Show the answer

Answer: b

SVGD particles are an optimized set, not samples. Report them as an approximation and check their spread.

10

Recap

Recap
  • Black-box VI estimates ELBO gradients by sampling: score-function (general, noisy) or pathwise (low noise, needs differentiability).
  • Exact gradients find the best member of the family; the family still limits the answer.
  • An importance-weighted bound above the ELBO measures how far qq is from the posterior.
  • SVGD moves particles with attraction plus repulsion; they are an approximation, not draws.

Concepts in this lesson