Bayesian PPL and diagnostics
Overview
This skill defines a default HMC/NUTS-first Bayesian stack (Stan family, PyMC) with ArviZ (Python) or posterior / bayesplot / brms utilities (R) for diagnostics. Gibbs samplers (JAGS, OpenBUGS/WinBUGS) are legacy / reproduction-only unless there is a documented reason to stay in BUGS language.
Rcpp is for data wrangling, performance bottlenecks outside the sampler, and custom family math—not for replacing Stan’s autodiff + NUTS as the main inference engine.
Primary references: references/reference.md.
When to Use This Skill
Use when you:
- Fit or review hierarchical / multilevel models on tabular or imaging-derived phenotypes.
- Must prove convergence and sampling quality before interpreting posteriors.
- Choose between Stan/CmdStanPy, brms, PyMC, or JAGS/OpenBUGS for a given task.
- Integrate prior/posterior predictive checks and simulation-based calibration into a reproducible pipeline.
Do not treat “posterior means look reasonable” as sufficient evidence of a valid fit.
Core Tooling / Preferred Stack
| Layer |
Preferred tools |
Role |
| Language-first PPL |
Stan + CmdStanPy (Python) or rstan / cmdstanr (R) |
Custom models, stable NUTS, fine-grained control of sampling and diagnostics |
| R formula interface |
brms |
Standard GLMMs / multilevel models without hand-written Stan for common structures |
| Python PPL |
PyMC |
Notebook-centric workflows, tight coupling with NumPy/SciPy/xarray stacks |
| Diagnostics (Python) |
ArviZ |
InferenceData, R-hat, ESS, BFMI, PPC plots, LOO hooks |
| Legacy Gibbs |
JAGS + R2jags; OpenBUGS / WinBUGS |
Reproduce historical BUGS models; teaching; interoperability |
| Acceleration (R) |
Rcpp (+ Armadillo/Eigen as needed) |
Fast pre/post processing, custom brms families, not the main sampler |
CmdStanPy is documented primarily via Stan documentation and the CmdStanPy manual—treat the official docs as the canonical citation surface, not a single “CmdStanPy paper.”
Workflow / Decision Rules
Route selection (which engine first?)
New project default: Stan/brms/PyMC — not JAGS.
Rcpp: allowed roles
- Do: vectorized data prep, expensive covariate construction, lookup tables, custom un-normalized log-likelihood pieces exposed to brms custom families, or post-processing of posterior draws.
- Do not: reimplement HMC or expect Rcpp to fix a misspecified hierarchical geometry; reparameterize the model instead.
Diagnostic workflow (mandatory gates)
Treat the following as blocking before scientific conclusions. Use ArviZ (az.summary, az.plot_trace, az.plot_rank, energy plots) or equivalent R tooling.
Divergent transitions (HMC/NUTS)
- Meaning: numerical instability or geometry too difficult for current parameterization / step size.
- First response: increase
adapt_delta / target_accept (Stan/PyMC), then non-centered reparameterization for hierarchical scales, then rescale covariates / outcomes.
- If still present: treat as model misspecification or prior/data conflict until proven otherwise.
Max treedepth hits
- Meaning: trajectories hitting the cap; often strong posterior correlation or funnel geometry.
- Action: reparameterize (non-centered), simplify model, or allow deeper trees only after ruling out misspecification.
E-BFMI (Bayesian fraction of missing information)
- Meaning: low values suggest difficult global exploration (often funnels).
- Pair with: divergences and energy Bayesian bootstrap checks; fix geometry before “more iterations.”
R-hat
- Use split R-hat; flag > 1.01 (stricter thresholds for publication-critical parameters).
- High R-hat is not fixed by wishful thinning—run longer, more chains, or fix parameterization/multimodality.
Bulk vs tail ESS
- Report both when using ArviZ defaults.
- Tail ESS matters for extreme quantiles and tail statements (e.g. odds ratios far from 0).
Posterior predictive checks (PPC)
- Test systematic discrepancies between replicated and observed data (not just overlap).
- Failure suggests wrong likelihood, missing structure, or wrong link, not “tweak priors only.”
Prior predictive checks
- Run before or alongside early fits to ensure priors imply plausible observables.
- If observables are impossible under the prior, the problem is usually prior / scale, not the MCMC run.
Simulation-based calibration (SBC)
- When feasible, use SBC to check entire inference pipeline (model + sampler settings) over simulated datasets. Flag systematic coverage errors.
Non-centered parameterization
- Default for hierarchical scales and group effects when centered parameterization shows divergences / low BFMI.
- If non-centered is worse (rare), document why and show diagnostics for both.
Disentangling failure modes
| Symptom cluster |
Likely cause |
What to change first |
| PPC fails on location/scale of data |
Likelihood / link / missing covariates |
Model structure |
| PPC OK but prior predictive absurd |
Priors off by orders of magnitude |
Priors + measurement scales |
| Divergences + low BFMI, bad funnel plots |
Geometry / parameterization |
Non-center, rescaling |
| R-hat high, chains stuck in modes |
Multimodality / label switching |
Model constraints, stronger priors, different likelihood |
Common Pitfalls / Validation Notes
- No saved seeds, chain count, thinning policy, and package versions → results are not auditable.
- Ignoring divergences because trace plots “look mixed.”
- Flat or overly wide priors on scales → funnel geometry; fix with weakly informative priors and standardization.
- Mixing Stan and JAGS in one pipeline without documentation and version pins.
- Publishing posterior means without uncertainty intervals and diagnostic summary tables.
References
Canonical papers and documentation URLs are maintained in references/reference.md.
1---2name: bayesian-ppl-diagnostics3description: Executable guidance for Bayesian workflows using Stan/CmdStanPy, brms, PyMC, and ArviZ, with legacy JAGS/OpenBUGS paths and Rcpp acceleration patterns.4license: Apache-2.05---6# Bayesian PPL and diagnostics78## Overview910This skill defines a **default HMC/NUTS-first** Bayesian stack (Stan family, PyMC) with **ArviZ** (Python) or **posterior / bayesplot / brms** utilities (R) for diagnostics. **Gibbs samplers** (JAGS, OpenBUGS/WinBUGS) are **legacy / reproduction-only** unless there is a documented reason to stay in BUGS language.1112**Rcpp** is for **data wrangling, performance bottlenecks outside the sampler, and custom family math**—not for replacing Stan’s autodiff + NUTS as the main inference engine.1314Primary references: [references/reference.md](references/reference.md).1516## When to Use This Skill1718Use when you:1920- Fit or review **hierarchical / multilevel** models on tabular or imaging-derived phenotypes.21- Must **prove convergence and sampling quality** before interpreting posteriors.22- Choose between **Stan/CmdStanPy**, **brms**, **PyMC**, or **JAGS/OpenBUGS** for a given task.23- Integrate **prior/posterior predictive checks** and **simulation-based calibration** into a reproducible pipeline.2425Do **not** treat “posterior means look reasonable” as sufficient evidence of a valid fit.2627## Core Tooling / Preferred Stack2829| Layer | Preferred tools | Role |30|-------|------------------|------|31| Language-first PPL | **Stan** + **CmdStanPy** (Python) or **rstan** / **cmdstanr** (R) | Custom models, stable NUTS, fine-grained control of sampling and diagnostics |32| R formula interface | **brms** | Standard GLMMs / multilevel models without hand-written Stan for common structures |33| Python PPL | **PyMC** | Notebook-centric workflows, tight coupling with NumPy/SciPy/xarray stacks |34| Diagnostics (Python) | **ArviZ** | `InferenceData`, R-hat, ESS, BFMI, PPC plots, LOO hooks |35| Legacy Gibbs | **JAGS** + **R2jags**; **OpenBUGS** / **WinBUGS** | Reproduce historical BUGS models; teaching; interoperability |36| Acceleration (R) | **Rcpp** (+ Armadillo/Eigen as needed) | Fast pre/post processing, custom brms families, not the main sampler |3738**CmdStanPy** is documented primarily via **Stan documentation and the CmdStanPy manual**—treat the official docs as the canonical citation surface, not a single “CmdStanPy paper.”3940## Workflow / Decision Rules4142### Route selection (which engine first?)4344- **Prefer Stan / CmdStanPy** when:45 - The model is **mostly custom** (non-standard likelihoods, ODEs, complex constraints, heavy control of generated quantities).46 - You need **stable HMC/NUTS** with explicit control of adaptation, treedepth, and metric.47 - You need **fine-grained diagnostics** and reproducible Stan programs versioned in git.4849- **Prefer brms** when:50 - The task is a **standard hierarchical / GLMM** structure and a formula interface reduces error.51 - You want **fast iteration** without maintaining `.stan` files, and the model maps cleanly to brms’ supported families.5253- **Prefer PyMC** when:54 - The workflow is **Python-native** (Jupyter, PyTensor graphs, tight integration with ArviZ and scientific Python).55 - You need flexible **model composition** in Python without a separate Stan file.5657- **Fall back to JAGS / OpenBUGS / WinBUGS** only when:58 - You must **replicate an old paper** or run a **legacy BUGS/JAGS** codebase.59 - Historical **discrete-parameter** Gibbs formulations are the explicit target (still consider rewriting in Stan with marginalization when possible).6061**New project default:** Stan/brms/PyMC — not JAGS.6263### Rcpp: allowed roles6465- **Do:** vectorized data prep, expensive covariate construction, lookup tables, custom **un-normalized** log-likelihood pieces exposed to **brms** custom families, or post-processing of posterior draws.66- **Do not:** reimplement HMC or expect Rcpp to fix a misspecified hierarchical geometry; **reparameterize the model** instead.6768### Diagnostic workflow (mandatory gates)6970Treat the following as **blocking** before scientific conclusions. Use ArviZ (`az.summary`, `az.plot_trace`, `az.plot_rank`, energy plots) or equivalent R tooling.71721. **Divergent transitions (HMC/NUTS)** 73 - **Meaning:** numerical instability or **geometry too difficult** for current parameterization / step size. 74 - **First response:** increase `adapt_delta` / `target_accept` (Stan/PyMC), then **non-centered** reparameterization for hierarchical scales, then **rescale** covariates / outcomes. 75 - **If still present:** treat as **model misspecification** or **prior/data conflict** until proven otherwise.76772. **Max treedepth hits** 78 - **Meaning:** trajectories hitting the cap; often **strong posterior correlation** or **funnel** geometry. 79 - **Action:** reparameterize (non-centered), simplify model, or allow deeper trees **only after** ruling out misspecification.80813. **E-BFMI (Bayesian fraction of missing information)** 82 - **Meaning:** low values suggest **difficult global exploration** (often funnels). 83 - **Pair with:** divergences and energy Bayesian bootstrap checks; fix geometry before “more iterations.”84854. **R-hat** 86 - Use **split R-hat**; flag **> 1.01** (stricter thresholds for publication-critical parameters). 87 - **High R-hat** is not fixed by wishful thinning—**run longer**, **more chains**, or fix parameterization/multimodality.88895. **Bulk vs tail ESS** 90 - Report **both** when using ArviZ defaults. 91 - Tail ESS matters for **extreme quantiles** and **tail statements** (e.g. odds ratios far from 0).92936. **Posterior predictive checks (PPC)** 94 - Test **systematic discrepancies** between replicated and observed data (not just overlap). 95 - Failure suggests **wrong likelihood**, **missing structure**, or **wrong link**, not “tweak priors only.”96977. **Prior predictive checks** 98 - Run **before** or alongside early fits to ensure priors imply **plausible observables**. 99 - If observables are impossible under the prior, the problem is usually **prior / scale**, not the MCMC run.1001018. **Simulation-based calibration (SBC)** 102 - When feasible, use **SBC** to check **entire inference pipeline** (model + sampler settings) over simulated datasets. Flag **systematic coverage errors**.1031049. **Non-centered parameterization** 105 - Default for **hierarchical scales and group effects** when centered parameterization shows divergences / low BFMI. 106 - If non-centered is worse (rare), document **why** and show diagnostics for both.107108### Disentangling failure modes109110| Symptom cluster | Likely cause | What to change first |111|-----------------|--------------|----------------------|112| PPC fails on **location/scale** of data | Likelihood / link / missing covariates | Model structure |113| PPC OK but **prior predictive** absurd | Priors off by orders of magnitude | Priors + measurement scales |114| Divergences + low BFMI, bad funnel plots | Geometry / parameterization | Non-center, rescaling |115| R-hat high, chains stuck in modes | Multimodality / label switching | Model constraints, stronger priors, different likelihood |116117## Common Pitfalls / Validation Notes118119- **No saved seeds, chain count, thinning policy, and package versions** → results are not auditable.120- **Ignoring divergences** because trace plots “look mixed.”121- **Flat or overly wide priors** on scales → funnel geometry; fix with weakly informative priors and **standardization**.122- **Mixing Stan and JAGS** in one pipeline without documentation and version pins.123- Publishing **posterior means** without **uncertainty intervals** and diagnostic summary tables.124125## References126127Canonical papers and documentation URLs are maintained in [references/reference.md](references/reference.md).