Skip to content

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.

Advanced ~15 min10 steps

What runs in CodeSplash

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

Read first

01

A controlled experiment

Read

The 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 θ\theta. Then the posterior is exactly normal, with

vn=(τ−2+nσ−2)−1,mn=vn σ−2∑iyi.v_n=\big(\tau^{-2}+n\sigma^{-2}\big)^{-1},\qquad m_n=v_n\,\sigma^{-2}\textstyle\sum_i y_i .

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.

02

Two Metropolis runs

Read

Four 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.

03

R-hat, carefully

Read

With MM chains of NN draws, compare within-chain variance WW with between-chain variance:

W=1M∑msm2,B=N Varm(θˉm),V^=N−1NW+BN,R^=V^/W.W=\tfrac1M\textstyle\sum_m s_m^2,\quad B=N\,\mathrm{Var}_m(\bar\theta_m),\quad \widehat V=\tfrac{N-1}{N}W+\tfrac BN,\quad \widehat R=\sqrt{\widehat V/W}.

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 ∣θ−median∣|\theta-\text{median}| (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.

0.90

How strongly the Gaussian's two coordinates move together.

Sampler

Gibbs needs each coordinate's conditional distribution; only the Gaussian has them here.

0.50

Random-walk proposal scale, or HMC's leapfrog step.

10

HMC only: steps of the simulated trajectory per proposal.

1000

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.

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.

  1. The exact posterior mean

    Store the exact posterior mean mn in m_n, then compare it with the mean of all the good draws.

    Show a solution
    Python
    v_n = 1 / (1 / tau ** 2 + n / sigma ** 2)
    m_n = v_n * y.sum() / sigma ** 2
    R
    v_n <- 1 / (1 / tau^2 + n / sigma^2)
    m_n <- v_n * sum(y) / sigma^2
  2. Split R-hat for the tuned sampler

    Split each of the four good chains 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 in rhat_good.

    Show a solution
    Python
    def 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)
    R
    split_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)
  3. Split R-hat for the sticky sampler

    Store the split R-hat of the sticky chains in rhat_sticky. The usual alarm is R-hat above 1.01.

    Show a solution
    Python
    rhat_sticky = split_rhat(sticky)
    R
    rhat_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.

04

ESS and MCSE

Read

Correlated draws carry less information than independent ones:

Neff=N1+2∑t≥1ρt,MCSE(θˉ)≈sθNeff.N_{\text{eff}}=\frac{N}{1+2\sum_{t\ge1}\rho_t},\qquad \text{MCSE}(\bar\theta)\approx\frac{s_\theta}{\sqrt{N_{\text{eff}}}}.

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 θ\theta, 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 (Stan)Recorded · Python and R agreeRecorded 2026-11-25 · 70 values compared
R

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

ParameterMeanSD95% lowerMedian95% upperR-hatBulk ESSTail ESSP(> 0)
(Intercept)37.2382.90232.02037.09943.2391.002386.17386.131
wt−5.3300.7759−7.063−5.307−3.9001.001366.46355.330
am_f: manual−0.00111.439−2.7080.01622.8311.007377.95380.370.5067
sigma3.2180.45942.5153.1614.2351.001481.46284.881

Priors

ParameterPriorNote
(Intercept)Normal(20.09, 15.07)at the predictors' means
wtNormal(0, 15.4)autoscaled
am_f: manualNormal(0, 30.2)autoscaled
sigmaExponential(0.1659)residual SD

Sampler by chain

ChainDivergentMax tree depth hitsE-BFMIStep sizeMean acceptance
1001.0380.61230.9092
2001.1290.47110.9136

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

QuantityEstimateSE
elpd_loo (expected log predictive density)−84.4354.209
p_loo (effective number of parameters)4.0141.203
LOOIC (−2 × elpd_loo)168.878.419

Posterior predictive checks

StatisticObservedReplicated (mean)P(rep ≥ obs)
Mean20.09120.0810.4967
Standard deviation6.0276.1490.5567
Maximum33.90031.9110.1867
Minimum10.4005.9470.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
))
Python

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

ParameterMeanSD95% lowerMedian95% upperR-hatBulk ESSTail ESSP(> 0)
(Intercept)37.2382.90232.02037.09943.2391.002386.17386.131
wt−5.3300.7759−7.063−5.307−3.9001.001366.46355.330
am_f: manual−0.00111.439−2.7080.01622.8311.007377.95380.370.5067
sigma3.2180.45942.5153.1614.2351.001481.46284.881

Priors

ParameterPriorNote
(Intercept)Normal(20.09, 15.07)at the predictors' means
wtNormal(0, 15.4)autoscaled
am_f: manualNormal(0, 30.2)autoscaled
sigmaExponential(0.1659)residual SD

Sampler by chain

ChainDivergentMax tree depth hitsE-BFMIStep sizeMean acceptance
1001.0380.61230.9092
2001.1290.47110.9136

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

QuantityEstimateSE
elpd_loo (expected log predictive density)−84.4354.209
p_loo (effective number of parameters)4.0141.203
LOOIC (−2 × elpd_loo)168.878.419

Posterior predictive checks

StatisticObservedReplicated (mean)P(rep ≥ obs)
Mean20.09120.0810.4967
Standard deviation6.0276.1490.5567
Maximum33.90031.9110.1867
Minimum10.4005.9470.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.

05

Posterior predictive checks criticize the model

Read

With the computation now trusted, the workflow simulates replicated datasets from exact posterior draws and compares a chosen discrepancy, here the largest absolute residual T(y,θ)=max⁡i∣yi−θ∣T(y,\theta)=\max_i|y_i-\theta|. 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.

06

SBC, and the sampler that ignores the data

Read

Simulation-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 θ\theta from the prior, simulates data, runs the inference and records the rank of the true θ\theta 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).

500

Datasets simulated from the prior; one rank each.

19

Draws per fit; ranks run from 0 to this number.

10

More data makes the exact posterior narrower.

Simulating…
Working…

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.

  1. 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_true among draws_good in chi_good.

    Show a solution
    Python
    chi_good = chi_square((draws_good < theta_true[:, None]).sum(axis=1))
    R
    chi_good <- chi_square(rowSums(draws_good < theta_true))
  2. SBC for the data-ignoring sampler

    Do the same for draws_wrong and store the chi-square in chi_wrong. Would this check catch an algorithm that ignores the data?

    Show a solution
    Python
    chi_wrong = chi_square((draws_wrong < theta_true[:, None]).sum(axis=1))
    R
    chi_wrong <- chi_square(rowSums(draws_wrong < theta_true))
  3. 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_wrong and store the chi-square in chi_wrong_q.

    Show a solution
    Python
    q_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))
    R
    q_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.

07

SBC in CodeSplash

Read

Simulation-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 (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.
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
))
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.
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.

08

Where each idea stands in CodeSplash

Read
IdeaIn CodeSplash
Rank-normalized folded split R-hat, bulk and tail ESS, MCSERuns in CodeSplash: every Bayesian regression model (Stan) fit, Python ≡ R to about 1e-12 against the posterior package
Posterior predictive checksRuns in CodeSplash: the Bayesian models studio's Check step
SBC with a data-dependent quantityRuns in CodeSplash: Simulation-based calibration (parameters plus joint log-likelihood)
The full workflow with Metropolis (INF009) and the planted bugRuns as a notebook: the reference's program, with NUTS (INF012) in the app
09

Check your understanding

Checkpoint

Check 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 ∣θ−median∣|\theta-\text{median}|?

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 1/Neff1/\sqrt{N_{\text{eff}}}.

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.

10

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