Skip to content

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.

Experimental Python and R agree to 6 decimals Also called SBC, simulation-based calibration, rank histogram…

A real result

Example “Gaussian mtcars”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

Simulation-based calibration (Stan)Recorded · Python and R agreeRecorded 2026-11-21 · 31 values compared
R

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

SBC rank histogramsDoes the posterior recover known parameters — are the SBC ranks uniform?
View data
Rank binSimulations99% band (high)99% band (low)Quantity
159−0(Intercept)
219−0(Intercept)
389−0(Intercept)
449−0(Intercept)
529−0(Intercept)
129−0wt
289−0wt
349−0wt
439−0wt
539−0wt
139−0sigma
249−0sigma
349−0sigma
459−0sigma
549−0sigma
159−0Joint log-likelihood
249−0Joint log-likelihood
339−0Joint log-likelihood
459−0Joint log-likelihood
539−0Joint log-likelihood
SBC rank ECDF difference with a simultaneous 95% bandAre the SBC ranks uniform — and where do they depart?
View data
ECDF − uniformband highband lowQuantityFractional rank
00.1500−0.0500(Intercept)0.0500
00.2000−0.1000(Intercept)0.1000
00.2000−0.1500(Intercept)0.1500
0.05000.2500−0.2000(Intercept)0.2000
00.2500−0.2000(Intercept)0.2500
00.2500−0.2500(Intercept)0.3000
−0.05000.3000−0.2500(Intercept)0.3500
−0.10000.3000−0.2500(Intercept)0.4000
−0.10000.3000−0.2500(Intercept)0.4500
−0.05000.2500−0.2500(Intercept)0.5000
0.10000.2500−0.3000(Intercept)0.5500
0.10000.2500−0.3000(Intercept)0.6000
0.10000.2500−0.3000(Intercept)0.6500
0.05000.2500−0.2500(Intercept)0.7000
0.15000.2000−0.2500(Intercept)0.7500
0.10000.2000−0.2500(Intercept)0.8000
0.15000.1500−0.2500(Intercept)0.8500
0.10000.1000−0.2000(Intercept)0.9000
0.05000.0500−0.1500(Intercept)0.9500
−0.05000.1500−0.0500wt0.0500
−0.10000.2000−0.1000wt0.1000
−0.15000.2000−0.1500wt0.1500
−0.10000.2500−0.2000wt0.2000
−0.05000.2500−0.2000wt0.2500
00.2500−0.2500wt0.3000
0.05000.3000−0.2500wt0.3500
0.10000.3000−0.2500wt0.4000
0.10000.3000−0.2500wt0.4500
0.15000.2500−0.2500wt0.5000
0.10000.2500−0.3000wt0.5500
0.10000.2500−0.3000wt0.6000
0.10000.2500−0.3000wt0.6500
0.05000.2500−0.2500wt0.7000
0.05000.2000−0.2500wt0.7500
0.05000.2000−0.2500wt0.8000
00.1500−0.2500wt0.8500
00.1000−0.2000wt0.9000
0.05000.0500−0.1500wt0.9500
00.1500−0.0500sigma0.0500
00.2000−0.1000sigma0.1000
00.2000−0.1500sigma0.1500
−0.05000.2500−0.2000sigma0.2000
00.2500−0.2000sigma0.2500
−0.05000.2500−0.2500sigma0.3000
00.3000−0.2500sigma0.3500
−0.05000.3000−0.2500sigma0.4000
−0.05000.3000−0.2500sigma0.4500
−0.05000.2500−0.2500sigma0.5000
−0.05000.2500−0.3000sigma0.5500
−0.05000.2500−0.3000sigma0.6000
−0.10000.2500−0.3000sigma0.6500
−0.05000.2500−0.2500sigma0.7000
−0.05000.2000−0.2500sigma0.7500
00.2000−0.2500sigma0.8000
0.05000.1500−0.2500sigma0.8500
00.1000−0.2000sigma0.9000
0.05000.0500−0.1500sigma0.9500
00.1500−0.0500Joint log-likelihood0.0500
0.05000.2000−0.1000Joint log-likelihood0.1000
00.2000−0.1500Joint log-likelihood0.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

QuantityMean rankχ²dfχ² pECDF γECDF test p
(Intercept)8.8507.5004.1120.0775.315
wt9.0505.5004.2400.0775.315
sigma9.9500.50004.9740.4752.950
Joint log-likelihood8.85014.9100.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.
Python

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

QuantityMean rankχ²dfχ² pECDF γECDF test p
(Intercept)8.8507.5004.1120.0775.315
wt9.0505.5004.2400.0775.315
sigma9.9500.50004.9740.4752.950
Joint log-likelihood8.85014.9100.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.
Python

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"],
})
R

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.