23 Modern Bayesian Computation
23.1 Learning objectives
By the end of this chapter you should be able to:
- Distinguish probabilistic programming languages (Stan, PyMC, Turing) from front-end packages (
rstanarm,brms,cmdstanr) and choose between them for a given task. - Implement a Bayesian regression model in
brmsand inspect the generated Stan code to verify that priors and likelihood match your intent. - Diagnose a fit with the four-quadrant workflow: convergence (\(\hat R\), ESS), posterior predictive checks, prior predictive checks, and influential observations (Pareto-\(\hat k\)).
- Compute and interpret leave-one-out cross-validation (
loo) and WAIC for model comparison, recognizing when Pareto-\(\hat k\) warns that the importance-sampling approximation has failed. - Decide when full HMC, when variational inference (ADVI, Pathfinder), and when a Laplace or INLA approximation is the right tool for the problem at hand.
- Articulate Gelman et al.’s Bayesian workflow as a sequence of falsifiable checks rather than a one-shot fit-and-summarize.
23.2 Orientation
The introductory SCAI volume showed how to fit a Bayesian model in brms and how to read a posterior. In this chapter we take the next step. We shall consider how the fit is produced, how to verify it, how to compare competing models, and what to do when HMC is too slow to be practical.
Three currents shape modern Bayesian computation. First, probabilistic programming languages (PPLs) (Stan, PyMC, Turing, NumPyro) separate model specification from the inference algorithm. That is, we write the joint density, and the compiler produces samplers and gradient code. Second, the Bayesian workflow (Gelman et al., 2020) reframes inference as iterative model-criticism rather than a single posterior summary. Third, scalable approximations (variational inference, Pathfinder, INLA, Laplace) extend Bayesian computation to problem sizes where MCMC is hopeless.
The chapter follows that arc. We begin with the PPL stack and the front-end packages most users meet first (rstanarm, brms). We then turn to model checking and comparison, where loo and bayesplot do most of the heavy lifting. Finally we shall cover variational inference and adjacent approximations, with explicit attention to when each fails.
23.3 The statistician’s contribution
LLMs can write Stan code, run brms calls, and produce loo comparisons. They cannot decide which model is actually relevant to the scientific question, or which prior encodes domain knowledge honestly. Nor can they tell when a passing diagnostic is hiding a deeper failure.
(Judgment 1.) Priors are part of the model, not nuisance. Default priors in brms are an improper flat prior on the regression coefficients and weakly informative Student-t priors on intercepts and standard deviations. These defaults are adequate for many regression problems, but they are not universally appropriate. Consider a logistic regression on rare-event data with default flat priors on the coefficients. Its posteriors will be driven by the few events present and will be sensitive to the parameterization. The statistician decides what the prior should encode. Examples include a rough plausible range for treatment effects on the log-odds scale, a known boundary on a variance component, or a hierarchical structure that shares information across centers. None of these decisions are visible from the data alone. An LLM that proposes ‘use the default priors’ has therefore not answered the question.
(Judgment 2.) A passing diagnostic is necessary, not sufficient. \(\hat R = 1.00\) and ESS in the thousands tell us that the chains agree on the posterior they have explored. They do not tell us that the chains explored the right posterior. Two pathologies in particular evade automatic checks. The first is a multimodal posterior in which chains separately settle in different modes. Each chain looks fine on its own, and pooled diagnostics flag nothing if all modes happen to be visited proportionally. The second is a posterior with regions of high curvature that the sampler silently skips. The defense is twofold. Posterior predictive checking asks whether the fitted model produces data that look like the observed data on the quantities we care about. Prior predictive checking asks whether the model produces remotely plausible data before seeing any observations. These are scientific questions, and the statistician frames them.
(Judgment 3.) Model comparison is a means, not an end. loo_compare() will return a difference in expected log-pointwise predictive density (elpd) with a standard error and will rank competing models. It will not tell us whether either model is good enough for the decision the analysis informs. Suppose a Bayesian workflow ends at ‘model B is preferred by 4 elpd units’. It has then skipped the step in which the statistician asks whether B’s predictions are in the right ballpark. The statistician also asks whether B extrapolates safely and whether its assumptions are defensible to a reviewer. LLMs are strong at running loo_compare. They are weak at noticing when the answer is ‘neither model is fit for purpose.’
23.4 The probabilistic programming stack
Bayesian computation in 2026 is layered. We describe the layers from bottom to top.
Inference engines. Stan (Carpenter et al., 2017) is a C++ library implementing HMC/NUTS, ADVI, Pathfinder, and a Laplace approximation. PyMC (Salvatier et al., 2016) is a Python library built on PyTensor that offers similar samplers. Turing (Ge et al., 2018) is a Julia counterpart. NumPyro is JAX-based and is valued for its speed on hierarchical models. All four expose roughly the same primitives: a domain-specific syntax for declaring parameters and a log-density, plus algorithms that consume that density.
R interfaces. cmdstanr is the recommended R interface to Stan; rstan is older and bundles its own Stan version. reticulate plus cmdstanpy lets us reach Stan from R via Python, but cmdstanr is the simpler path. PyMC is reachable from R only via reticulate. For a team that works primarily in R, Stan is therefore the natural choice.
Front-end packages. rstanarm (Goodrich et al., 2024) ships with pre-compiled Stan models for common GLMs and GLMMs. It is the fastest way to fit a Bayesian regression in R. brms (Bürkner, 2017) generates Stan code on the fly from an R formula and supports a much wider class of models. These include multivariate outcomes, distributional regression, nonlinear models, missing-data imputation, and time-varying effects via splines and Gaussian processes. brms is the workhorse of applied Bayesian regression in R.
Post-processing packages. posterior standardizes the draws-as-array data structure across engines. bayesplot provides diagnostic and posterior-predictive-check plots. tidybayes exposes posterior draws as tidy tibbles that work well with the rest of the tidyverse. loo implements approximate leave-one-out cross-validation.
The implication for our workflow is as follows. Most applied work should start in brms or rstanarm. It should drop to raw Stan only when the model cannot be expressed in the front-end syntax, and it should never reimplement the post-processing stack.
23.5 A brms fit, end to end
The minimum viable fit has six steps: declare the model, inspect the generated code, run prior predictive checks, fit, run posterior diagnostics, and run posterior predictive checks. To illustrate, consider a simulated logistic regression with a known random-intercept structure.
library(brms)
library(bayesplot)
library(loo)
set.seed(228)
n_centers <- 20
n_per <- 80
sim <- tibble::tibble(
center = rep(1:n_centers, each = n_per),
x = rnorm(n_centers * n_per)
)
b0 <- rnorm(n_centers, 0, 0.6)
sim$y <- rbinom(
nrow(sim), 1,
plogis(-0.5 + 0.4 * sim$x + b0[sim$center])
)
priors <- c(
prior(normal(0, 1), class = "b"),
prior(normal(0, 2), class = "Intercept"),
prior(student_t(3, 0, 1), class = "sd")
)
fit <- brm(
y ~ x + (1 | center),
data = sim,
family = bernoulli(),
prior = priors,
chains = 4, cores = 4, iter = 2000,
backend = "cmdstanr",
sample_prior = "yes"
)sample_prior = "yes" retains prior draws, so that we can run prior predictive checks side by side with posterior checks.
Step 1: inspect the generated code. make_stancode(fit) prints the Stan program that brms produced, and we should read it. If the priors do not match what we wrote, or the parameter names are not what we expected, we fix the formula before fitting. Skipping this step is the single most common source of silent specification errors with brms.
Step 2: prior predictive checks. Before fitting, we draw samples from the prior alone, pass them through the likelihood, and ask whether the result is plausible. pp_check(fit, type = "bars", prefix = "ppd") plots prior predictive draws against the data. If the priors imply outcomes far from anything the collaborator considers possible, we tighten them.
Step 3: convergence diagnostics. summary(fit) reports \(\hat R\) and ESS bulk/tail per parameter. We flag any \(\hat R > 1.01\) or ESS bulk \(< 400\). mcmc_trace() and mcmc_pairs() from bayesplot reveal divergent transitions and funnel pathologies in hierarchical models.
Step 4: posterior predictive checks. We use pp_check(fit, type = "bars") for binary or count outcomes and pp_check(fit, type = "dens_overlay") for continuous ones. We look for systematic discrepancies between simulated and observed data. Examples are a model that under-predicts large values, mis-locates the mean, or under-disperses the tails. These are the structural failures that \(\hat R\) will not catch.
Step 5: targeted posterior predictive checks. Beyond ‘does the marginal density match,’ we ask whether the model reproduces the quantity the analysis is about. If the report quotes the center-level event rate, we run pp_check(fit, type = "stat_grouped", group = "center", stat = "mean") and check that the center means line up. A model can match the marginal and still miss the conditional badly.
Step 6: model criticism. loo(fit) returns the leave-one-out elpd estimate and Pareto-\(\hat k\) diagnostics for each observation. Observations with \(\hat k > 0.7\) indicate that the importance-sampling approximation to leave-one-out is unreliable for that point. Usually this is because the point is influential. We refit those points exactly with reloo() if the comparison hinges on them.
23.6 Model comparison: loo and WAIC
Cross-validation answers the question ‘which model predicts new observations better.’ True \(K\)-fold CV is expensive when each fit takes hours. Pareto-smoothed importance-sampling LOO (Vehtari et al., 2017) approximates exact LOO from a single fit by reweighting posterior draws. It is the default in loo.
loo_compare(loo(fit1), loo(fit2)) returns the difference in expected log-pointwise predictive density and its standard error. The convention is to treat the comparison as decisive only when |\(\Delta\)elpd| is several times its SE. Small differences are often within sampling noise.
WAIC (Watanabe, 2010) is a related criterion computable from the same machinery. It generally agrees with LOO on well-behaved problems but can be unstable on hierarchical models with strong shrinkage. loo is the recommended default, and we report WAIC only when it is required.
Two failure modes are common. First, Pareto-\(\hat k\) flags above 0.7 indicate that the importance-sampling step has broken for that observation. The elpd estimate is then unreliable unless those observations are refit exactly. Second, comparison across data subsets is invalid. loo compares models on the same data. Refitting model B with one observation removed and comparing its elpd to model A’s full elpd is not a valid comparison.
To illustrate, consider a worked comparison:
fit_a <- brm(y ~ x + (1 | center), data = sim,
family = bernoulli(), prior = priors,
chains = 4, cores = 4)
fit_b <- brm(y ~ x + (x | center), data = sim,
family = bernoulli(), prior = priors,
chains = 4, cores = 4)
loo_a <- loo(fit_a)
loo_b <- loo(fit_b)
loo_compare(loo_a, loo_b)The comparison reads:
elpd_diff se_diff
fit_b 0.0 0.0
fit_a -8.4 3.7
The random-slope model is preferred by 8.4 elpd units with SE 3.7 (about 2.3 SE units). This is evidence in favor of the slope-varying model, but it is not overwhelming. We would re-examine the Pareto-\(\hat k\) values for both fits before concluding.
23.7 Variational inference and faster approximations
Three approximations are in common use when HMC is too slow, when the model has hundreds of thousands of parameters, or when the user needs a fit in seconds for an interactive dashboard.
Mean-field ADVI (Kucukelbir et al., 2017) approximates the posterior by a factorized Gaussian (after a transform to unconstrained space). It then minimizes the KL divergence to the true posterior using stochastic gradients. The method is fast and scales to large data. Unfortunately, it is also wrong in characteristic ways. Mean-field ignores correlation between parameters, so the method underestimates posterior variance. When the true posterior is multimodal, it can still return draws from a Gaussian. Nor does it provide any diagnostic for whether the approximation is adequate. We use it for exploration and verify with HMC before quoting an interval.
Full-rank ADVI retains correlation and is more accurate, but it is quadratically more expensive. Pathfinder (Zhang et al., 2022) is a newer alternative. It runs an L-BFGS optimization, fits a Gaussian along the path, and returns importance-resampled draws. It is fast and more stable than ADVI, and it serves as a high-quality initialization for HMC.
Laplace approximation treats the posterior as Gaussian, centered at the MAP with covariance equal to the inverse observed information. For posteriors that are nearly Gaussian (well-identified models with substantial data), it is accurate and trivially fast. It fails badly on skewed or multimodal posteriors and on hierarchical models with funnel geometry.
INLA (Rue et al., 2009) (Integrated Nested Laplace Approximation) is a structured approximation specialized for latent Gaussian models. These include GLMMs, spatial Gaussian random fields, and time-series models with Gaussian latent structure. For models that fit its template, INLA is substantially faster than MCMC. It is also accurate enough that the spatial-statistics community treats it as the default. The R-INLA package is mature, and inlabru extends it for spatial-point processes and ecology applications.
The decision rule is as follows:
| Approximation | Use when | Avoid when |
|---|---|---|
| HMC/NUTS | Default; correctness matters | Many parameters with weak data |
| Pathfinder | Fast warm-start needed | Highly multimodal target |
| ADVI mean-field | Quick exploration only | Reporting intervals |
| Laplace | Posterior near Gaussian | Skewed or hierarchical funnels |
| INLA | Latent Gaussian model | Non-conjugate non-Gaussian latent |
23.8 Worked example: hospital readmission with brms and loo
To illustrate the full Bayesian workflow, consider a simulated hospital-readmission problem. The outcome is 30-day readmission for 12 hospitals over 4 quarters. The predictors are case-mix index, admission service line, and a quarterly indicator.
library(brms); library(loo); library(bayesplot)
set.seed(2026)
hosp <- tibble::tibble(
hospital = factor(rep(1:12, each = 200)),
quarter = factor(rep(rep(1:4, each = 50), 12)),
service = factor(sample(
c("med","surg","cards"), 12 * 200, replace = TRUE)),
cmi = rnorm(12 * 200, 1.5, 0.4)
)
b_hosp <- rnorm(12, 0, 0.4)
b_q <- c(0, 0.1, -0.1, 0.05)
hosp$y <- rbinom(
nrow(hosp), 1,
plogis(-2 + 0.5 * (hosp$cmi - 1.5) +
b_q[as.integer(hosp$quarter)] +
b_hosp[as.integer(hosp$hospital)])
)
priors_m1 <- c(
prior(normal(0, 1), class = "b"),
prior(normal(-2, 1), class = "Intercept"),
prior(student_t(3, 0, 0.5), class = "sd")
)
m1 <- brm(
y ~ cmi + service + quarter + (1 | hospital),
data = hosp, family = bernoulli(),
prior = priors_m1, chains = 4, cores = 4,
iter = 2000, backend = "cmdstanr"
)
m2 <- brm(
y ~ cmi + service + quarter +
(1 + cmi | hospital),
data = hosp, family = bernoulli(),
prior = priors_m1, chains = 4, cores = 4,
iter = 2000, backend = "cmdstanr",
control = list(adapt_delta = 0.95)
)The convergence summary for m1 reports \(\hat R < 1.01\) across parameters, ESS bulk in the low thousands, and no divergent transitions. The summary for m2 initially flagged a small number of divergent transitions, which we addressed by raising adapt_delta to 0.95.
We next examine the posterior predictive check at the hospital level, pp_check(m1, type = "stat_grouped", group = "hospital", stat = "mean"). It shows that the hospital-specific readmission rates are well recovered for m1. The same check on m2 shows similar performance.
The model comparison is as follows:
loo_m1 <- loo(m1); loo_m2 <- loo(m2)
loo_compare(loo_m1, loo_m2)
# elpd_diff se_diff
# m1 0.0 0.0
# m2 -2.1 1.4m1 is preferred by 2.1 elpd units with SE 1.4, a difference within sampling noise. The simpler model is adequate, and the data do not support the additional flexibility. LLMs frequently mis-interpret this kind of result as ‘no difference, both fine.’ The correct reading is ‘no evidence the slope-varying model improves predictive accuracy here, prefer the simpler model on parsimony grounds.’
A Pareto-\(\hat k\) check on loo_m1 reports all values below 0.7, so the elpd estimate is reliable. Had a handful of values exceeded 0.7, we would have refit those observations exactly with reloo(m1, loo_m1).
The marginal posterior on the case-mix coefficient is 0.51 [0.41, 0.62] (90% credible interval), in line with the simulation truth of 0.5. The posterior for the hospital-level standard deviation is 0.42 [0.27, 0.61].
23.9 Collaborating with an LLM on modern Bayesian computation
LLMs are reliable at translating a verbal model description into brms formula syntax and at suggesting standard prior choices. They are unreliable at diagnosing posterior failures and at interpreting loo comparisons in context. They cannot judge whether a posterior predictive check is passing on the right quantity.
Prompt 1: ‘Translate this model to brms syntax.’ Provide a clean specification (outcome, family, fixed effects, random-effects structure, priors) and ask for the formula and prior() calls.
What to watch for. The LLM will sometimes add or drop random effects, conflate (1 | g) with (1 + x | g), or specify priors on the wrong class. The class argument in prior() is particularly error-prone. Priors on slopes are class = "b", the intercept is class = "Intercept", and group SDs are class = "sd". Run make_stancode() and confirm.
Verification. Print the generated Stan code with make_stancode(fit). Confirm that the parameter names, prior distributions, and the likelihood block match the specification line by line.
Prompt 2: ‘Diagnose this fit.’ Paste the summary(fit) table and any divergent-transition counts. Ask the LLM to flag concerns and recommend next steps.
What to watch for. The LLM will typically suggest raising adapt_delta, increasing iterations, or reparameterizing the random effects. These are correct standard moves. However, the LLM cannot tell whether the posterior itself is the problem (e.g., a multimodal posterior arising from a non-identifiable parameterization) or whether the issue is sampler tuning. Trace plots, pair plots, and prior predictive checks remain our job.
Verification. After applying the suggestions, re-run the diagnostics. If divergent transitions persist after adapt_delta = 0.99 and a non-centered parameterization, the issue is the model, not the sampler. At that point we stop tuning, look at pair plots, and suspect non-identifiability.
Prompt 3: ‘Interpret this loo_compare() output.’ Paste the loo_compare table and the Pareto-\(\hat k\) summaries and ask for an interpretation.
What to watch for. The LLM will quote the elpd difference and the SE and recommend the model with higher elpd. It typically does not check Pareto-\(\hat k\) flags before doing so. Nor does it ask about the standard error of the difference relative to the magnitude, or consider whether the analysis question is even decided by predictive accuracy. A model with worse elpd may still be the right answer if its parameters are interpretable and the elpd difference is small.
Verification. Always read Pareto-\(\hat k\) before reading elpd. If \(\hat k > 0.7\) on more than a handful of points, elpd is unreliable until we reloo(). We then ask whether the elpd difference is several SE units; if not, the comparison is inconclusive.
In practice, we treat the LLM as a fluent intern who knows the syntax but has never sat through a model-criticism review. It handles formula syntax, function calls, and diagnostic interpretation in textbook cases. Deciding when a passing diagnostic is misleading, when a comparison is too noisy to act on, and when a model is fit for purpose remains with the statistician.
23.10 Principle in use
Three habits define defensible work in this area:
Read the generated Stan code before running the fit.
make_stancode()takes two seconds of effort and eliminates the most common silent failure mode inbrmsanalyses. If the priors or likelihood do not match our intent, we find out before the chains run for an hour.Run prior predictive checks before posterior predictive checks. Posterior predictive checks confirm that the model fits the data. Prior predictive checks confirm that the model is even capable of producing plausible data. A model that produces implausible draws under the prior will draw the wrong inferences in regions where data are sparse.
Read
loo_comparetogether with Pareto-\(\hat k\). Never quote an elpd difference without checking that the importance-sampling approximation has not failed. Theloopackage prints both, and skimming straight to the elpd table leads to over-confident model selection.
23.11 Exercises
Refit the readmission worked example with the default
brmspriors (omit thepriorargument). Compare the posterior on the case-mix coefficient to the informative-prior fit. Under what data conditions would the difference matter?Use
make_stancode()on abrm(y ~ x + (1 + x | g))call with no explicit priors. Identify the correlation-matrix priorbrmschose by default and explain what it implies about the relationship between the random intercept and slope.Implement a Bayesian negative binomial regression in
brmsfor an over-dispersed count outcome. Run prior predictive checks and verify that the prior on the dispersion parameter does not place excessive mass on near-Poisson dispersion.Take a
brmsfit and approximate its posterior with ADVI (vi(fit)) and with Pathfinder (via thecmdstanrinterface). Compare the marginal posterior for one regression coefficient across HMC, ADVI, and Pathfinder. Which approximation underestimates variance? On which parameters?Construct a scenario where two
brmsmodels have nearly identical elpd (within 1 SE) but make meaningfully different predictions on an out-of-distribution test point. What does this illustrate about treating elpd as the sole comparison metric?
23.12 Further reading
- Gelman et al. (2020), Bayesian Workflow. The canonical argument for iterative model-criticism over one-shot fitting.
- McElreath (2020), Statistical Rethinking (2nd edition). Applied Bayesian regression with
brmsandrethinking, accessible to a first-time audience. - Vehtari et al. (2017), Practical Bayesian model evaluation using leave-one-out cross-validation and WAIC. The reference for
looand Pareto-\(\hat k\) diagnostics. - The
brmsdocumentation (https://paul-buerkner.github.io/brms/) andloovignettes (https://mc-stan.org/loo/) are exemplary.