BBayesian · bayes.sbc
Simulation-based calibration (Bayesian model check)
Does the Bayesian model and its sampler recover known parameters — are its posteriors calibrated?
Checks a Bayesian model specification before you trust it (Talts et al. 2018): draws parameters from the priors, simulates an outcome from the model for each draw, fits the model to every simulated dataset and records where the true value falls among the posterior draws. When the model, priors and sampler are right those ranks are uniform. Each parameter (and the joint log-likelihood) gets a rank histogram with a 99% band, an ECDF-difference plot with a simultaneous 95% band and the ECDF test of Säilynoja, Bürkner & Vehtari (2022), plus a χ² test. Uses the same Stan programs and settings as the Bayesian regression model; Python and R simulate and fit the same datasets, so their ranks are identical.
A real result
Example “Gaussian mtcars”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
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.
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.
Do it in CodeSplash Run it on your own data. It's in the Experimental lane in the app.
Worked examples in the app
- Gaussian mtcarsmtcars · outcome: mpg · predictors: wt
- Logistic mtcarsmtcars · outcome: am_f · predictors: wt
- Poisson group cbpps1_cbpp · group: herd · outcome: incidence · predictors: period
- Degenerate constantmtcars · outcome: mpg · predictors: wt
In the guides
Where it sits in the decision guides
- Repeated / clustered: mixed models, GEE · Statistics Guide · D — Predict an outcome
What you need
- Outcomenumeric / categorical / boolean · 1 column
- The outcome of the model to check; only its type and size are used (SBC simulates new outcomes).
- Predictorsnumeric / categorical / boolean · 0–20 columns · 2–30 levels
- The predictors of the model to check; their observed values are kept fixed in every simulation.
- Trialsnumeric · 0–1 column
- Logistic with counts: the number of trials per row.
- Exposurenumeric · 0–1 column
- Counts: time at risk or size per row (> 0); its log is an offset.
- Grouping factorcategorical / numeric / boolean · 0–1 column
- The unit rows belong to; each level gets its own intercept.
- Varying slopesnumeric · 0–2 columns
- Numeric predictors whose effect may differ between levels of the grouping factor.
- Second grouping factorcategorical / numeric / boolean · 0–1 column
- A second grouping factor with its own varying intercept.
Choices you make
model
- Outcome modeldefault gaussian
The distribution of the outcome in the model to check.
- Gaussian (normal)(default) — For a continuous outcome.
- Student-t (robust) — A continuous outcome with heavy tails.
- Logistic (yes/no or successes of trials) — For a yes/no outcome, or successes out of trials.
- Poisson (counts) — For counts.
- Negative binomial (overdispersed counts) — For counts more spread out than Poisson.
- Ordinal (cumulative logit) — For ordered categories.
- Event (modeled level)default —
Yes/no outcomes: the level whose probability is modeled (default: the second level).
- Interactionsdefault none
Interaction terms in the model to check.
- None (main effects only)(default) — Main effects only.
- First two predictors (A × B) — Adds the product of the first two predictors.
- All pairs of predictors — Adds every two-way product.
- Second grouping factor isdefault nested
Whether the second grouping factor sits inside the first or is separate from it.
- Nested in the first(default) — Levels of the second factor only make sense within the first.
- Crossed with the first — The two factors are separate.
- Coefficient priordefault normal
The prior on every coefficient; SBC needs a proper prior to draw from.
- Normal (weakly informative)(default) — rstanarm's default: Normal(0, 2.5) on a scale set by the data.
- Student-t (heavier tails) — Allows a few large effects while shrinking small ones.
- Cauchy (very heavy tails) — A Student-t with one degree of freedom.
- Coefficient prior scaledefault 2.5
Spread of the coefficient prior before autoscaling.
Advanced
- Prior degrees of freedomdefault 3
Degrees of freedom of the Student-t coefficient prior.
- Scale priors to the datadefault on
rstanarm's rule, computed once from the observed data; every simulated dataset is then fitted with those same priors.
- Intercept prior scaledefault 2.5
Spread of the intercept's Normal prior before autoscaling.
- Correlation prior (LKJ η)default 1
Prior on the correlation of varying intercepts and slopes.
- Thinningdefault 3
Keep every k-th draw so the L draws are close to independent (autocorrelated draws make ranks look non-uniform).
- Target acceptance (adapt_delta)default 0.8
Raise it when the simulation fits report divergent transitions.
- Maximum tree depthdefault 10
Caps the length of each trajectory at 2^depth steps.
- Null simulations for the ECDF testdefault 1000
Uniform rank sets simulated to calibrate the ECDF test and its simultaneous band.
options
- Simulationsdefault 100
Simulated datasets, each fitted once; more simulations detect smaller miscalibration but take longer.
- Posterior draws per fit (L)default 99
Thinned draws each rank is counted among; ranks run from 0 to L.
- Warmup iterations per fitdefault 500
Warmup iterations of each fit.
- Random seeddefault 1234
Fixes the prior draws, the simulated data and every fit, so reruns are identical in Python and in R.
statistics
- Histogram binsdefault 20
Bins of the rank histograms and of the χ² test.
Checks and remedies
CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.
Ranks are uniform (SBC)
The ECDF test of each quantity's ranks, Bonferroni-corrected for the number of quantities; non-uniform ranks mean the posterior is too narrow, too wide or shifted.
No divergent transitions in the simulation fits
Fits with divergent transitions may not reach the posterior, so their ranks can be off.
- If violated → Smaller steps (adapt_delta 0.95) — Divergences in the simulation fits make their ranks unreliable; a higher target acceptance usually removes them.
What it reports
- n
- How many independent units the analysis used; it sets precision and power.
- n_sims
- Datasets simulated from the priors and fitted once each.
- posterior_draws
- Thinned draws each SBC rank counts among, so ranks run from 0 to L.
- bins
- Bins of the SBC rank histograms and of the χ² test.
- family
- The distribution assumed for the outcome: Gaussian, Student-t, logistic, binomial, Poisson, negative binomial or ordinal.
- n_divergent
- Draws that ended in a divergent transition; want 0.
- sims_with_divergences
- Simulation fits that had at least one divergent transition; their ranks can be off.
- gamma_alpha
- The pointwise level that makes the ECDF band cover the whole curve with 95% probability (by simulation).
- gamma_p_min
- The smallest uniformity p-value over the checked quantities, before the Bonferroni correction.
- chi2_p_min
- The smallest χ² uniformity p-value over the checked quantities.
- n_params
- Parameters plus the joint log-likelihood whose SBC ranks were tested.
Per group, level or term: chi2[<quantity>], chi2_p[<quantity>], gamma[<quantity>], gamma_p[<quantity>], mean_rank[<quantity>]
Python and R
Python and R agree to 6 decimals (relative tolerance 1e-8). Python uses pandas, numpy, scipy, pyarrow, codesplash; R uses posterior, loo, nanoparquet, jsonlite, codesplashr.
Default traps between the two languages
- The prior draws, simulated datasets and every fit come from the same Stan program on byte-identical data files with the same seeds, so the ranks are identical; the ECDF test's null distribution is simulated on the shared Wichmann–Hill stream.
- The joint log-likelihood of the true parameters is computed by each engine's own densities (scipy / R stats, equal to about 1e-14); a tie with a posterior draw at that precision would change one rank by one, which has not happened in practice.
The exact script CodeSplash ran for example “Gaussian mtcars” · 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"],
})
The exact script CodeSplash ran for example “Gaussian mtcars” · 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
))
Sources
- Talts, S., Betancourt, M., Simpson, D., Vehtari, A., & Gelman, A. (2018). Validating Bayesian inference algorithms with simulation-based calibration. arXiv:1804.06788.
- Säilynoja, T., Bürkner, P.-C., & Vehtari, A. (2022). Graphical test for discrete uniformity and its applications in goodness-of-fit evaluation and multiple sample comparison. Statistics and Computing, 32, 32.
- Modrák, M., Moon, A. H., Kim, S., Bürkner, P., Huurre, N., Faltejsková, K., Gelman, A., & Vehtari, A. (2023). Simulation-based calibration checking for Bayesian computation: The choice of test quantities shapes sensitivity. Bayesian Analysis.
From the CodeSplash method registry · bayes.sbc v1.0.0.