Is the sampler right? Diagnostics that can miss errors
R-hat, effective sample size, predictive checks and simulation-based calibration each answer a different question, and each can miss a broken computation. Walk a validation workflow with a planted wrong algorithm.
What runs in CodeSplash
- INF009Metropolis–Hastings (MH) Runs as a notebook
- INF012No-U-Turn Sampler (NUTS) Partly runs in CodeSplash (Experimental)
- Bayesian regression model (Stan) Experimental
- Simulation-based calibration (Bayesian model check) Experimental
You will be able to
- Compute the idea behind rank-normalized, folded, split R-hat and say what it can't detect
- Separate Monte Carlo error (MCSE) from posterior uncertainty
- Explain why a posterior predictive check criticizes the model, not the sampler
- Explain how a sampler that ignores the data can pass SBC on parameters, and what catches it
A controlled experiment
ReadThe reference's validation workflow uses a model small enough to solve by hand: 24 measurements, normal with known SD 1, a normal prior on the location . Then the posterior is exactly normal, with
Having the exact answer lets each diagnostic be judged against the truth instead of against another approximation. The last measurement is deliberately replaced by an outlier, so the model is wrong in a known way even when the computation is right. Hold on to the three questions from lesson 1.
Two Metropolis runs
ReadFour Metropolis chains start apart. One run uses a proposal scaled to the posterior SD; the other uses a step hundreds of times smaller.
- The well-scaled run accepts a bit over half its proposals and matches the exact posterior.
- The tiny-step run accepts over 99% and its chains sit in separate bands.
The surprise is the tiny-step run's pooled mean: it lands near the right value, because chains started on either side balance out. Checking only that average would pass a badly wrong distribution. Trace plots and chain-aware diagnostics catch it.
R-hat, carefully
ReadWith chains of draws, compare within-chain variance with between-chain variance:
The modern version splits each chain in half (a drifting chain disagrees with itself), rank-normalizes the pooled draws (heavy tails can't hide), and repeats on folded draws (chains with equal centers but different spreads get caught). Report the larger. The tiny-step run's R-hatR-hat (rank-normalized)Compares the spread between chains with the spread within them; 1.01 or less means the chains agree. is far above 1; the good run's is about 1.
What R-hat can't see: several chains that all miss the same mode, or a derived quantity you didn't check.
Try the two-mode target: chains that each stay in one mode give a large R-hat; all four in the same mode would look fine.
EExplorable · MCMC samplers: acceptance is not mixing
Do four chains of a sampler agree about the target, and does a high acceptance rate mean they will?
Target
The distribution the chains try to sample.
How strongly the Gaussian's two coordinates move together.
Sampler
Gibbs needs each coordinate's conditional distribution; only the Gaussian has them here.
Random-walk proposal scale, or HMC's leapfrog step.
HMC only: steps of the simulated trajectory per proposal.
Draws in each of the four chains.
- Chain 1, starts at (-3, -3)
- Chain 2, starts at (3, 3)
- Chain 3, starts at (-3, 3)
- Chain 4, starts at (3, -3)
- Acceptance rate
- 0.533
- R-hat of x₁
- 1.029
- Bulk ESS of x₁
- 72
- ESS per draw
- 0.018
- Puzzle: Find a sampler and step size with R-hat below 1.01 and a bulk ESS above 400.
- Puzzle: Push the acceptance rate above 90% while R-hat stays above 1.05.
Random-walk Metropolis on the correlated Gaussian: 53% of proposals accepted, R-hat 1.029, bulk ESS 72 of 4000 draws. The four chains still disagree, so these draws don't describe the target yet. The acceptance rate alone says nothing about mixing.
Notebook exercise · ~15 min
Metropolis chains and split R-hat
Check a Metropolis sampler against an exact posterior, then compute split R-hat for a well-tuned and a sticky sampler.
- The exact posterior mean
Store the exact posterior mean mn in
m_n, then compare it with the mean of all thegooddraws.Show a solution
Pythonv_n = 1 / (1 / tau ** 2 + n / sigma ** 2) m_n = v_n * y.sum() / sigma ** 2Rv_n <- 1 / (1 / tau^2 + n / sigma^2) m_n <- v_n * sum(y) / sigma^2 - Split R-hat for the tuned sampler
Split each of the four
goodchains into halves (8 chains of N = 500). With W the mean of their variances and B = N × the variance of their means, R-hat = √(((N − 1)/N · W + B/N) / W). Store it inrhat_good.Show a solution
Pythondef split_rhat(chains): parts = np.vstack([chains[:, :500], chains[:, 500:]]) N = 500 W = parts.var(axis=1, ddof=1).mean() B = N * parts.mean(axis=1).var(ddof=1) return math.sqrt(((N - 1) / N * W + B / N) / W) rhat_good = split_rhat(good)Rsplit_rhat <- function(chains) { parts <- rbind(chains[, 1:500], chains[, 501:1000]) N <- 500 W <- mean(apply(parts, 1, var)) B <- N * var(rowMeans(parts)) sqrt(((N - 1) / N * W + B / N) / W) } rhat_good <- split_rhat(good) - Split R-hat for the sticky sampler
Store the split R-hat of the
stickychains inrhat_sticky. The usual alarm is R-hat above 1.01.Show a solution
Pythonrhat_sticky = split_rhat(sticky)Rrhat_sticky <- split_rhat(sticky)
In the app this opens as a Python or R notebook with the sample data, and its checks mark your progress.
ESS and MCSE
ReadCorrelated draws carry less information than independent ones:
The Monte Carlo standard errorMonte Carlo standard errorHow much a Monte Carlo estimate would move with a new set of draws or replicates; it shrinks as the number of draws (or ESS) grows. measures numerical error in a posterior summary, and it shrinks with more draws. The posterior SD measures uncertainty about , and more draws don't shrink it. Bulk and tail ESS differ: a mean can be precise while an interval's end, a tail quantile, is not.
Bayesian gaussian (normal) model of mpg (n = 32), NUTS (Hamiltonian Monte Carlo). Posterior: wt has median -5.31 (95% credible interval -7.06 to -3.90); P(> 0) = 0.00. Largest R-hat 1.007, 0 divergent transitions. PSIS-LOO elpd = -84.4 (SE 4.2).
- wt (posterior median)
- −5.307
- 95% credible interval
- [−7.063, −3.900]
- P(effect > 0)
- 0
- Largest R-hat
- 1.007
- elpd (PSIS-LOO)
- −84.435
- Bayesian R² (median)
- 0.7320
Assumptions
- Sampler converged (R-hat, ESS) — Largest R-hat 1.007 (want ≤ 1.01); smallest bulk ESS 366 and tail ESS 285 (want ≥ 400).
- No divergent transitions — No divergent transitions.
- Trajectories within the tree depth — No draw hit the maximum tree depth.
- Energy (E-BFMI ≥ 0.3) — Smallest E-BFMI across chains 1.04 (below 0.3 means the sampler explores the tails poorly).
- Leave-one-out is reliable (Pareto k̂) — 1 of 32 rows have k̂ above 0.64 (largest 0.68); 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
| Parameter | Mean | SD | 95% lower | Median | 95% upper | R-hat | Bulk ESS | Tail ESS | P(> 0) |
|---|---|---|---|---|---|---|---|---|---|
| (Intercept) | 37.238 | 2.902 | 32.020 | 37.099 | 43.239 | 1.002 | 386.17 | 386.13 | 1 |
| wt | −5.330 | 0.7759 | −7.063 | −5.307 | −3.900 | 1.001 | 366.46 | 355.33 | 0 |
| am_f: manual | −0.0011 | 1.439 | −2.708 | 0.0162 | 2.831 | 1.007 | 377.95 | 380.37 | 0.5067 |
| sigma | 3.218 | 0.4594 | 2.515 | 3.161 | 4.235 | 1.001 | 481.46 | 284.88 | 1 |
Priors
| Parameter | Prior | Note |
|---|---|---|
| (Intercept) | Normal(20.09, 15.07) | at the predictors' means |
| wt | Normal(0, 15.4) | autoscaled |
| am_f: manual | Normal(0, 30.2) | autoscaled |
| sigma | Exponential(0.1659) | residual SD |
Sampler by chain
| Chain | Divergent | Max tree depth hits | E-BFMI | Step size | Mean acceptance |
|---|---|---|---|---|---|
| 1 | 0 | 0 | 1.038 | 0.6123 | 0.9092 |
| 2 | 0 | 0 | 1.129 | 0.4711 | 0.9136 |
Leave-one-out cross-validation (PSIS-LOO)
| Quantity | Estimate | SE |
|---|---|---|
| elpd_loo (expected log predictive density) | −84.435 | 4.209 |
| p_loo (effective number of parameters) | 4.014 | 1.203 |
| LOOIC (−2 × elpd_loo) | 168.87 | 8.419 |
Posterior predictive checks
| Statistic | Observed | Replicated (mean) | P(rep ≥ obs) |
|---|---|---|---|
| Mean | 20.091 | 20.081 | 0.4967 |
| Standard deviation | 6.027 | 6.149 | 0.5567 |
| Maximum | 33.900 | 31.911 | 0.1867 |
| Minimum | 10.400 | 5.947 | 0.0450 |
- 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 188a0d6aba408b25
# 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", "am_f")))
n_input <- nrow(df)
df[["am_f"]] <- factor(df[["am_f"]], levels = c("automatic", "manual")) # stored level order
df <- df[stats::complete.cases(df[c("mpg", "wt", "am_f")]), , 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", "am_f")) # 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", "am_f"),
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 = "nuts",
chains = as.integer(2),
iter_warmup = as.integer(300),
iter_sampling = as.integer(300),
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/gaussian-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
))
Bayesian gaussian (normal) model of mpg (n = 32), NUTS (Hamiltonian Monte Carlo). Posterior: wt has median -5.31 (95% credible interval -7.06 to -3.9); P(> 0) = 0.00. Largest R-hat 1.007, 0 divergent transitions. PSIS-LOO elpd = -84.4 (SE 4.2).
- wt (posterior median)
- −5.307
- 95% credible interval
- [−7.063, −3.900]
- P(effect > 0)
- 0
- Largest R-hat
- 1.007
- elpd (PSIS-LOO)
- −84.435
- Bayesian R² (median)
- 0.7320
Assumptions
- Sampler converged (R-hat, ESS) — Largest R-hat 1.007 (want ≤ 1.01); smallest bulk ESS 366 and tail ESS 285 (want ≥ 400).
- No divergent transitions — No divergent transitions.
- Trajectories within the tree depth — No draw hit the maximum tree depth.
- Energy (E-BFMI ≥ 0.3) — Smallest E-BFMI across chains 1.04 (below 0.3 means the sampler explores the tails poorly).
- Leave-one-out is reliable (Pareto k̂) — 1 of 32 rows have k̂ above 0.64 (largest 0.68); 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
| Parameter | Mean | SD | 95% lower | Median | 95% upper | R-hat | Bulk ESS | Tail ESS | P(> 0) |
|---|---|---|---|---|---|---|---|---|---|
| (Intercept) | 37.238 | 2.902 | 32.020 | 37.099 | 43.239 | 1.002 | 386.17 | 386.13 | 1 |
| wt | −5.330 | 0.7759 | −7.063 | −5.307 | −3.900 | 1.001 | 366.46 | 355.33 | 0 |
| am_f: manual | −0.0011 | 1.439 | −2.708 | 0.0162 | 2.831 | 1.007 | 377.95 | 380.37 | 0.5067 |
| sigma | 3.218 | 0.4594 | 2.515 | 3.161 | 4.235 | 1.001 | 481.46 | 284.88 | 1 |
Priors
| Parameter | Prior | Note |
|---|---|---|
| (Intercept) | Normal(20.09, 15.07) | at the predictors' means |
| wt | Normal(0, 15.4) | autoscaled |
| am_f: manual | Normal(0, 30.2) | autoscaled |
| sigma | Exponential(0.1659) | residual SD |
Sampler by chain
| Chain | Divergent | Max tree depth hits | E-BFMI | Step size | Mean acceptance |
|---|---|---|---|---|---|
| 1 | 0 | 0 | 1.038 | 0.6123 | 0.9092 |
| 2 | 0 | 0 | 1.129 | 0.4711 | 0.9136 |
Leave-one-out cross-validation (PSIS-LOO)
| Quantity | Estimate | SE |
|---|---|---|
| elpd_loo (expected log predictive density) | −84.435 | 4.209 |
| p_loo (effective number of parameters) | 4.014 | 1.203 |
| LOOIC (−2 × elpd_loo) | 168.87 | 8.419 |
Posterior predictive checks
| Statistic | Observed | Replicated (mean) | P(rep ≥ obs) |
|---|---|---|---|
| Mean | 20.091 | 20.081 | 0.4967 |
| Standard deviation | 6.027 | 6.149 | 0.5567 |
| Maximum | 33.900 | 31.911 | 0.1867 |
| Minimum | 10.400 | 5.947 | 0.0450 |
- 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 188a0d6aba408b25
# 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", "am_f"])
n_input = len(df)
df["am_f"] = pd.Categorical(df["am_f"], categories=["automatic", "manual"]) # stored level order
df = df.dropna(subset=["mpg", "wt", "am_f"]) # listwise deletion over the analysis columns
df["am_f"] = df["am_f"].cat.remove_unused_categories()
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", "am_f"]) # 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", "am_f"],
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="nuts",
chains=int(2),
iter_warmup=int(300),
iter_sampling=int(300),
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/gaussian-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: 8 chart(s) dropped to stay under 100 KB; 8 chart(s) dropped to stay under 100 KB.
This short fit has a largest R-hat of 1.007, a smallest bulk ESS of 366 and a smallest tail ESS of 285 from 600 draws.
Posterior predictive checks criticize the model
ReadWith the computation now trusted, the workflow simulates replicated datasets from exact posterior draws and compares a chosen discrepancy, here the largest absolute residual . Not one replicate is as extreme as the observed data: the known-SD normal model can't produce the outlier. That is a posterior predictive checkPosterior predictive checkCompare data simulated from the fitted model with the observed data; a systematic gap shows what the model misses. doing its job, and it says nothing about the sampler.
Two cautions. Zero exceedances in a few thousand replicates doesn't make the probability zero; it bounds it. And a check that passes only shows the model reproduces that statistic.
SBC, and the sampler that ignores the data
ReadSimulation-based calibrationCalibration check (simulation-based calibration)Simulated data sets with known true values: if the algorithm is calibrated, each true value's rank in its posterior is uniform. draws from the prior, simulates data, runs the inference and records the rank of the true among the posterior draws. Right computation means uniform ranks.
Now the planted bug: an "inference" that ignores the data and returns prior draws. True values come from the prior, and so do the "posterior" draws, so the ranks are perfectly uniform. Parameter-only SBC passes a sampler that never looked at the data. A data-dependent quantity exposes it, such as the rank of the log-likelihood, or a check that posteriors are narrower than the prior.
Compare a correct sampler with a broken one, including one that ignores the data, and see which rank histograms notice.
EExplorable · Simulation-based calibration
Does an inference algorithm give calibrated posteriors, and what can a calibration check miss?
Posterior sampler
The algorithm under test. θ ~ N(0, 1), each observation ~ N(θ, 1).
Datasets simulated from the prior; one rank each.
Draws per fit; ranks run from 0 to this number.
More data makes the exact posterior narrower.
Working…
Notebook exercise · ~15 min
Simulation-based calibration and the wrong algorithm
Run simulation-based calibration on a correct and a data-ignoring posterior sampler, and see which test quantity catches the broken one.
- SBC for the correct sampler
For each replicate, the rank is the number of the 19 draws below the true θ. Store the chi-square of the ranks of
theta_trueamongdraws_goodinchi_good.Show a solution
Pythonchi_good = chi_square((draws_good < theta_true[:, None]).sum(axis=1))Rchi_good <- chi_square(rowSums(draws_good < theta_true)) - SBC for the data-ignoring sampler
Do the same for
draws_wrongand store the chi-square inchi_wrong. Would this check catch an algorithm that ignores the data?Show a solution
Pythonchi_wrong = chi_square((draws_wrong < theta_true[:, None]).sum(axis=1))Rchi_wrong <- chi_square(rowSums(draws_wrong < theta_true)) - A test quantity that uses the data
Rank a quantity that depends on the data instead of θ itself: q(θ) = −(θ − ȳ)², closeness to the replicate's data mean. Rank q(true θ) among q of the 19
draws_wrongand store the chi-square inchi_wrong_q.Show a solution
Pythonq_true = -(theta_true - ybar) ** 2 q_draws = -(draws_wrong - ybar[:, None]) ** 2 chi_wrong_q = chi_square((q_draws < q_true[:, None]).sum(axis=1))Rq_true <- -(theta_true - ybar)^2 q_draws <- -(draws_wrong - ybar)^2 chi_wrong_q <- chi_square(rowSums(q_draws < q_true))
In the app this opens as a Python or R notebook with the sample data, and its checks mark your progress.
SBC in CodeSplash
ReadSimulation-based calibration ranks every parameter and the joint log-likelihood, a data-dependent quantity of exactly the kind the planted bug needs.
Simulation-based calibration of a Bayesian gaussian model of mpg: 20 datasets simulated from the priors, ranks among 19 posterior draws. Smallest ECDF-test p = 0.315 ((Intercept)) across 4 quantities.
- Smallest ECDF-test p
- 0.3150
- Smallest χ² p
- 0.1117
- Divergent transitions (all fits)
- 0
Plots
View data
| Rank bin | Simulations | 99% band (high) | 99% band (low) | Quantity |
|---|---|---|---|---|
| 1 | 5 | 9 | −0 | (Intercept) |
| 2 | 1 | 9 | −0 | (Intercept) |
| 3 | 8 | 9 | −0 | (Intercept) |
| 4 | 4 | 9 | −0 | (Intercept) |
| 5 | 2 | 9 | −0 | (Intercept) |
| 1 | 2 | 9 | −0 | wt |
| 2 | 8 | 9 | −0 | wt |
| 3 | 4 | 9 | −0 | wt |
| 4 | 3 | 9 | −0 | wt |
| 5 | 3 | 9 | −0 | wt |
| 1 | 3 | 9 | −0 | sigma |
| 2 | 4 | 9 | −0 | sigma |
| 3 | 4 | 9 | −0 | sigma |
| 4 | 5 | 9 | −0 | sigma |
| 5 | 4 | 9 | −0 | sigma |
| 1 | 5 | 9 | −0 | Joint log-likelihood |
| 2 | 4 | 9 | −0 | Joint log-likelihood |
| 3 | 3 | 9 | −0 | Joint log-likelihood |
| 4 | 5 | 9 | −0 | Joint log-likelihood |
| 5 | 3 | 9 | −0 | Joint log-likelihood |
View data
| ECDF − uniform | band high | band low | Quantity | Fractional rank |
|---|---|---|---|---|
| 0 | 0.1500 | −0.0500 | (Intercept) | 0.0500 |
| 0 | 0.2000 | −0.1000 | (Intercept) | 0.1000 |
| 0 | 0.2000 | −0.1500 | (Intercept) | 0.1500 |
| 0.0500 | 0.2500 | −0.2000 | (Intercept) | 0.2000 |
| 0 | 0.2500 | −0.2000 | (Intercept) | 0.2500 |
| 0 | 0.2500 | −0.2500 | (Intercept) | 0.3000 |
| −0.0500 | 0.3000 | −0.2500 | (Intercept) | 0.3500 |
| −0.1000 | 0.3000 | −0.2500 | (Intercept) | 0.4000 |
| −0.1000 | 0.3000 | −0.2500 | (Intercept) | 0.4500 |
| −0.0500 | 0.2500 | −0.2500 | (Intercept) | 0.5000 |
| 0.1000 | 0.2500 | −0.3000 | (Intercept) | 0.5500 |
| 0.1000 | 0.2500 | −0.3000 | (Intercept) | 0.6000 |
| 0.1000 | 0.2500 | −0.3000 | (Intercept) | 0.6500 |
| 0.0500 | 0.2500 | −0.2500 | (Intercept) | 0.7000 |
| 0.1500 | 0.2000 | −0.2500 | (Intercept) | 0.7500 |
| 0.1000 | 0.2000 | −0.2500 | (Intercept) | 0.8000 |
| 0.1500 | 0.1500 | −0.2500 | (Intercept) | 0.8500 |
| 0.1000 | 0.1000 | −0.2000 | (Intercept) | 0.9000 |
| 0.0500 | 0.0500 | −0.1500 | (Intercept) | 0.9500 |
| −0.0500 | 0.1500 | −0.0500 | wt | 0.0500 |
| −0.1000 | 0.2000 | −0.1000 | wt | 0.1000 |
| −0.1500 | 0.2000 | −0.1500 | wt | 0.1500 |
| −0.1000 | 0.2500 | −0.2000 | wt | 0.2000 |
| −0.0500 | 0.2500 | −0.2000 | wt | 0.2500 |
| 0 | 0.2500 | −0.2500 | wt | 0.3000 |
| 0.0500 | 0.3000 | −0.2500 | wt | 0.3500 |
| 0.1000 | 0.3000 | −0.2500 | wt | 0.4000 |
| 0.1000 | 0.3000 | −0.2500 | wt | 0.4500 |
| 0.1500 | 0.2500 | −0.2500 | wt | 0.5000 |
| 0.1000 | 0.2500 | −0.3000 | wt | 0.5500 |
| 0.1000 | 0.2500 | −0.3000 | wt | 0.6000 |
| 0.1000 | 0.2500 | −0.3000 | wt | 0.6500 |
| 0.0500 | 0.2500 | −0.2500 | wt | 0.7000 |
| 0.0500 | 0.2000 | −0.2500 | wt | 0.7500 |
| 0.0500 | 0.2000 | −0.2500 | wt | 0.8000 |
| 0 | 0.1500 | −0.2500 | wt | 0.8500 |
| 0 | 0.1000 | −0.2000 | wt | 0.9000 |
| 0.0500 | 0.0500 | −0.1500 | wt | 0.9500 |
| 0 | 0.1500 | −0.0500 | sigma | 0.0500 |
| 0 | 0.2000 | −0.1000 | sigma | 0.1000 |
| 0 | 0.2000 | −0.1500 | sigma | 0.1500 |
| −0.0500 | 0.2500 | −0.2000 | sigma | 0.2000 |
| 0 | 0.2500 | −0.2000 | sigma | 0.2500 |
| −0.0500 | 0.2500 | −0.2500 | sigma | 0.3000 |
| 0 | 0.3000 | −0.2500 | sigma | 0.3500 |
| −0.0500 | 0.3000 | −0.2500 | sigma | 0.4000 |
| −0.0500 | 0.3000 | −0.2500 | sigma | 0.4500 |
| −0.0500 | 0.2500 | −0.2500 | sigma | 0.5000 |
| −0.0500 | 0.2500 | −0.3000 | sigma | 0.5500 |
| −0.0500 | 0.2500 | −0.3000 | sigma | 0.6000 |
| −0.1000 | 0.2500 | −0.3000 | sigma | 0.6500 |
| −0.0500 | 0.2500 | −0.2500 | sigma | 0.7000 |
| −0.0500 | 0.2000 | −0.2500 | sigma | 0.7500 |
| 0 | 0.2000 | −0.2500 | sigma | 0.8000 |
| 0.0500 | 0.1500 | −0.2500 | sigma | 0.8500 |
| 0 | 0.1000 | −0.2000 | sigma | 0.9000 |
| 0.0500 | 0.0500 | −0.1500 | sigma | 0.9500 |
| 0 | 0.1500 | −0.0500 | Joint log-likelihood | 0.0500 |
| 0.0500 | 0.2000 | −0.1000 | Joint log-likelihood | 0.1000 |
| 0 | 0.2000 | −0.1500 | Joint log-likelihood | 0.1500 |
First 60 of 76 rows.
Assumptions
- Ranks are uniform (SBC) — Smallest ECDF-test p = 0.315 ((Intercept)); 1.000 after a Bonferroni correction for 4 quantities. No sign that the computation misstates the posterior.
- No divergent transitions in the simulation fits — No divergent transitions.
Simulation-based calibration
| Quantity | Mean rank | χ² | df | χ² p | ECDF γ | ECDF test p |
|---|---|---|---|---|---|---|
| (Intercept) | 8.850 | 7.500 | 4 | .112 | 0.0775 | .315 |
| wt | 9.050 | 5.500 | 4 | .240 | 0.0775 | .315 |
| sigma | 9.950 | 0.5000 | 4 | .974 | 0.4752 | .950 |
| Joint log-likelihood | 8.850 | 1 | 4 | .910 | 0.4503 | .910 |
- Each simulated dataset was fitted with the prior scales computed from the observed outcome, so the prior is the same for every fit.
- Ranks count the 19 thinned posterior draws (every 2th) below the true value, so they run from 0 to 19.
- SBC checks the computation (model, priors and sampler together), not how well the model fits your data.
The exact R script · R R version 4.5.1 (2025-06-13)
# Simulation-based calibration (Bayesian model check)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method bayes.sbc 1.0.0 · spec addabb6f58331e08
# 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_run_sbc (twin of codesplash.bayes.sbc) 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")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("mpg", "wt")]), , 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")) # infinite values stop the run (registry/errors.yaml)
outcome <- "mpg"
# %% Simulate from the priors, fit every simulated dataset and rank the true values
res <- cs_bayes_run_sbc(
df,
outcome = outcome,
predictors = c("wt"),
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,
n_sims = as.integer(20),
posterior_draws = as.integer(19),
thin = as.integer(2),
iter_warmup = as.integer(150),
adapt_delta = 0.8,
max_treedepth = as.integer(10),
bins = as.integer(5),
seed = 1234,
n_null = as.integer(200),
out_dir = cs_ml_out_dir("target/academy-parity/run-20754/bayes.sbc/gaussian-mtcars/out-r")
)
values <- res$values
# %% Result
gp <- vapply(res$rows, function(r) r$gamma_p, 0)
worst <- res$rows[[which.min(gp)]]
summary <- paste0(
sprintf("Simulation-based calibration of a Bayesian %s model of %s: %d datasets simulated from the priors, ranks among %d posterior draws. ",
values$family, outcome, values$n_sims, values$posterior_draws),
sprintf("Smallest ECDF-test p = %.3f (%s) across %d quantities", worst$gamma_p, worst$parameter, values$n_params),
if (values$n_divergent > 0) sprintf("; %d fits had divergent transitions.", values$sims_with_divergences) else "."
)
cs_publish(list(
method = "bayes.sbc",
methodVersion = "1.0.0",
title = "Simulation-based calibration (Stan)",
engine = cs_engine_info("posterior", "loo"),
n = values$n,
summary = summary,
statistics = list(
list(key = "gamma_p_min", label = "Smallest ECDF-test p", value = values$gamma_p_min),
list(key = "chi2_p_min", label = "Smallest χ² p", value = values$chi2_p_min),
list(key = "n_divergent", label = "Divergent transitions (all fits)", value = values$n_divergent, format = "integer")
),
tables = res$tables,
assumptions = res$assumptions,
warnings = warnings,
notes = c(res$notes, "SBC checks the computation (model, priors and sampler together), not how well the model fits your data."),
values = values,
charts = res$charts,
artifacts = res$artifacts
))
Simulation-based calibration of a Bayesian gaussian model of mpg: 20 datasets simulated from the priors, ranks among 19 posterior draws. Smallest ECDF-test p = 0.315 ((Intercept)) across 4 quantities.
- Smallest ECDF-test p
- 0.3150
- Smallest χ² p
- 0.1117
- Divergent transitions (all fits)
- 0
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Ranks are uniform (SBC) — Smallest ECDF-test p = 0.315 ((Intercept)); 1.000 after a Bonferroni correction for 4 quantities. No sign that the computation misstates the posterior.
- No divergent transitions in the simulation fits — No divergent transitions.
Simulation-based calibration
| Quantity | Mean rank | χ² | df | χ² p | ECDF γ | ECDF test p |
|---|---|---|---|---|---|---|
| (Intercept) | 8.850 | 7.500 | 4 | .112 | 0.0775 | .315 |
| wt | 9.050 | 5.500 | 4 | .240 | 0.0775 | .315 |
| sigma | 9.950 | 0.5000 | 4 | .974 | 0.4752 | .950 |
| Joint log-likelihood | 8.850 | 1 | 4 | .910 | 0.4503 | .910 |
- Each simulated dataset was fitted with the prior scales computed from the observed outcome, so the prior is the same for every fit.
- Ranks count the 19 thinned posterior draws (every 2th) below the true value, so they run from 0 to 19.
- SBC checks the computation (model, priors and sampler together), not how well the model fits your data.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Simulation-based calibration (Bayesian model check)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method bayes.sbc 1.0.0 · spec addabb6f58331e08
# 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 sbc # simulation-based calibration (twin of codesplashr cs_bayes_run_sbc)
from codesplash.ml.run import out_dir
# %% Data
df = pd.read_parquet("tests/parity/fixtures/mtcars.parquet", columns=["mpg", "wt"])
n_input = len(df)
df = df.dropna(subset=["mpg", "wt"]) # 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"]) # infinite values stop the run (registry/errors.yaml)
outcome = "mpg"
# %% Simulate from the priors, fit every simulated dataset and rank the true values
res = sbc.run_sbc(
df,
outcome=outcome,
predictors=["wt"],
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,
n_sims=int(20),
posterior_draws=int(19),
thin=int(2),
iter_warmup=int(150),
adapt_delta=0.8,
max_treedepth=int(10),
bins=int(5),
seed=int(1234),
n_null=int(200),
out_dir=out_dir("target/academy-parity/run-20754/bayes.sbc/gaussian-mtcars/out-python"),
)
values = res["values"]
# %% Result
worst = min(res["rows"], key=lambda r: r["gamma_p"])
summary = (
f"Simulation-based calibration of a Bayesian {values['family']} model of {outcome}: {values['n_sims']} datasets simulated "
f"from the priors, ranks among {values['posterior_draws']} posterior draws. Smallest ECDF-test p = {worst['gamma_p']:.3f} "
f"({worst['parameter']}) across {values['n_params']} quantities"
+ (f"; {values['sims_with_divergences']} fits had divergent transitions." if values["n_divergent"] else ".")
)
cs.publish({
"method": "bayes.sbc",
"methodVersion": "1.0.0",
"title": "Simulation-based calibration (Stan)",
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": values["n"],
"summary": summary,
"statistics": [
{"key": "gamma_p_min", "label": "Smallest ECDF-test p", "value": values["gamma_p_min"]},
{"key": "chi2_p_min", "label": "Smallest χ² p", "value": values["chi2_p_min"]},
{"key": "n_divergent", "label": "Divergent transitions (all fits)", "value": values["n_divergent"], "format": "integer"},
],
"tables": res["tables"],
"assumptions": res["assumptions"],
"warnings": warnings,
"notes": res["notes"] + ["SBC checks the computation (model, priors and sampler together), not how well the model fits your data."],
"values": values,
"charts": res["charts"],
"artifacts": res["artifacts"],
})
For the Gaussian model, the smallest ECDF-test p-value across quantities is 0.315, against a Bonferroni-corrected level of 0.0118. For the Poisson model with groups it is 0.035: still above the level, but with only 20 simulations the test has little power. Passing a weak test isn't strong evidence; the default is 100.
Where each idea stands in CodeSplash
Read| Idea | In CodeSplash |
|---|---|
| Rank-normalized folded split R-hat, bulk and tail ESS, MCSE | Runs in CodeSplash: every Bayesian regression model (Stan) fit, Python ≡ R to about 1e-12 against the posterior package |
| Posterior predictive checks | Runs in CodeSplash: the Bayesian models studio's Check step |
| SBC with a data-dependent quantity | Runs in CodeSplash: Simulation-based calibration (parameters plus joint log-likelihood) |
| The full workflow with Metropolis (INF009) and the planted bug | Runs as a notebook: the reference's program, with NUTS (INF012) in the app |
Check your understanding
CheckpointCheck yourself
Four Metropolis chains with a tiny step size have a pooled mean almost exactly equal to the true posterior mean. Is the sampler fine?
Show the answer
Answer: b
A right mean can come from a wrong distribution. Chain-aware diagnostics compare chains with each other, which a pooled average can't.
Check yourself
Why does the modern R-hat also look at folded draws ?
Show the answer
Answer: b
Splitting catches drift, rank-normalizing handles heavy tails, folding catches scale differences. Report the larger of the bulk and folded versions.
Check yourself
You quadruple the number of posterior draws. What happens to the posterior SD of a parameter and to its Monte Carlo standard error?
Show the answer
Answer: b
Posterior uncertainty is a property of the model and data. MCSE is numerical error from finite draws and falls like .
Check yourself
The posterior predictive check for the largest residual fails badly, using exact posterior draws. What does it say about the Metropolis sampler?
Show the answer
Answer: b
The draws were exact, so the failure is the model's. Keep "is the computation right?" and "is the model useful?" apart.
Check yourself
An inference routine has a bug: it returns prior draws and never uses the data. Parameter-only SBC shows uniform ranks. Why?
Show the answer
Answer: b
Uniform parameter ranks are necessary, not sufficient. Rank a data-dependent quantity (such as the log-likelihood) or check that posteriors contract relative to the prior.
Recap
Recap- A right pooled mean can hide unmixed chains; split, rank-normalized, folded R-hat compares chains.
- MCSE is numerical error; the posterior SD is uncertainty. Bulk and tail ESS differ.
- Posterior predictive checks criticize the model, not the sampler.
- A data-ignoring sampler passes parameter-only SBC; rank a data-dependent quantity too, as CodeSplash's SBC does.
Concepts in this lesson