Hamiltonian Monte Carlo and NUTS: following the gradient
Give the chain momentum and let the posterior's gradient steer it, and one proposal can cross the whole posterior. Learn leapfrog steps, the energy accept test, how NUTS picks the path length, and what divergences and tree-depth hits mean.
What runs in CodeSplash
- INF011Hamiltonian Monte Carlo (HMC) Partly runs in CodeSplash (Experimental)
- INF012No-U-Turn Sampler (NUTS) Partly runs in CodeSplash (Experimental)
- Bayesian regression model (Stan) Experimental
You will be able to
- Describe an HMC proposal as momentum plus leapfrog steps, accepted by energy error
- Explain how NUTS chooses the trajectory length, and why a naive turn rule isn't NUTS
- Read divergences, tree-depth hits and E-BFMI, and say what each one asks you to change
- Say what CodeSplash's Stan fits run, and what they don't
Why random walks are slow
ReadA random-walk Metropolis chain moves a distance of about one step size per iteration, in a random direction. To cross a posterior that is step sizes wide it needs on the order of iterations, and the step size must shrink as dimensions grow. In a hierarchical model with hundreds of parameters, that is hopeless.
Hamiltonian Monte CarloHamiltonian Monte Carlo (fixed path length)MCMC that adds a random momentum and follows the log density's gradient for L leapfrog steps, so one proposal travels far. (HMC) borrows physics: treat as a landscape and the parameters as a ball rolling on it. Give the ball a random push, let it roll, and where it ends up is the proposal. It can travel far and still land somewhere probable.
Reference · INF011 · Partly runs in CodeSplashHamiltonian Monte Carlo (HMC)Uses gradients and auxiliary momentum to propose distant posterior moves that avoid much random-walk behavior. It is useful for differentiable continuous latent-variable and Bayesian neural models, subject to posterior…Momentum and leapfrog steps
ReadEach iteration draws a momentum and follows Hamilton's equations for with the leapfrog integratorLeapfrog integratorAlternates half momentum steps and full position steps; it is reversible and keeps volume, which HMC's accept step relies on., times:
Exact dynamics would keep constant. Leapfrog steps keep it only approximately, so the endpoint is accepted with probability . In the reference's one-dimensional example the energy error was −0.00069, so the acceptance probability was 1.00. The mass matrix , tuned in warmup, rescales directions so one step size fits them all.
Switch the sampler to HMC on the same targets and compare its R-hat and ESS with random-walk Metropolis at a similar cost.
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.
How strongly the Gaussian's two coordinates move together.
Sampler
Gibbs needs each coordinate's conditional distribution; only the Gaussian has them here.
Random-walk proposal scale, or HMC's leapfrog step.
HMC only: steps of the simulated trajectory per proposal.
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.
How long to roll? NUTS
ReadToo few leapfrog steps and HMC is a random walk again; too many and the trajectory loops back, wasting gradients. NUTSNUTS (No-U-Turn Sampler)Stan's default MCMC: it follows the posterior's gradient and stops each trajectory when it starts to turn back. (the No-U-Turn Sampler) chooses the length per iteration: it doubles the trajectory forward or backward in time until the two ends start to come back toward each other,
then picks the next state from the whole trajectory by a rule that keeps the target exact. In the reference's example the endpoint dot products are 1.2 and −0.5: one is negative, so doubling stops.
Reference · INF012 · Partly runs in CodeSplashNo-U-Turn Sampler (NUTS)Chooses HMC trajectory lengths dynamically using a no-U-turn criterion and a valid candidate-selection scheme, reducing the need to hand-select a leapfrog count.Not any turn rule will do
ReadThe criterion above is the original identity-metric version; modern Stan uses a generalized one with the metric. More important: stopping at the first turn and keeping the endpoint is not NUTS. That rule prefers some states over others and samples the wrong distribution. NUTS is the tree building, the turn check and a balanced choice of state together.
Likewise, HMC needs full-data gradients. Swapping in minibatch gradients without a correction (lesson 7) breaks the exactness, and so does applying HMC to discrete parameters, which must be summed out first.
NUTS in CodeSplash
ReadEvery Bayesian regression model (Stan) fit runs NUTS by default, from programs compiled ahead of time; Python and R run the same program on the same data file with the same seed.
Bayesian gaussian (normal) model of Reaction (n = 177), NUTS (Hamiltonian Monte Carlo). Posterior: Days has median 10.6 (95% credible interval 7.03 to 13.9); P(> 0) = 1.00. Largest R-hat 1.008, 0 divergent transitions. PSIS-LOO elpd = -846.7 (SE 22.7).
- Days (posterior median)
- 10.610
- 95% credible interval
- [7.029, 13.895]
- P(effect > 0)
- 1
- Largest R-hat
- 1.008
- elpd (PSIS-LOO)
- −846.70
- Bayesian R² (median)
- 0.7936
Assumptions
- Sampler converged (R-hat, ESS) — Largest R-hat 1.008 (want ≤ 1.01); smallest bulk ESS 147 and tail ESS 185 (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 0.68 (below 0.3 means the sampler explores the tails poorly).
- Leave-one-out is reliable (Pareto k̂) — 9 of 177 rows have k̂ above 0.64 (largest 1.62); 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
| Parameter | Mean | SD | 95% lower | Median | 95% upper | R-hat | Bulk ESS | Tail ESS | P(> 0) |
|---|---|---|---|---|---|---|---|---|---|
| (Intercept) | 250.94 | 7.397 | 236.23 | 251.03 | 265.05 | 1.006 | 378.30 | 408.08 | 1 |
| Days | 10.565 | 1.704 | 7.029 | 10.610 | 13.895 | 0.9980 | 384.06 | 302.39 | 1 |
| sigma | 25.808 | 1.543 | 23.047 | 25.734 | 29.051 | 1.002 | 624.86 | 317.04 | 1 |
| sd(Subject: (Intercept)) | 26.328 | 6.765 | 15.022 | 25.630 | 40.962 | 1.008 | 303.12 | 345.91 | 1 |
| sd(Subject: Days) | 6.504 | 1.390 | 4.332 | 6.340 | 9.961 | 1.002 | 434.12 | 415.56 | 1 |
| cor(Subject: (Intercept), Days) | 0.1420 | 0.2936 | −0.4283 | 0.1504 | 0.7129 | 1.006 | 147.45 | 185.34 | 0.6867 |
Priors
| Parameter | Prior | Note |
|---|---|---|
| (Intercept) | Normal(298.1, 141.5) | at the predictors' means |
| Days | Normal(0, 48.85) | autoscaled |
| sigma | Exponential(0.01767) | residual SD |
| sd(Subject: (Intercept)) | Exponential(0.01767) | |
| sd(Subject: Days) | Exponential(0.01767) | |
| cor(Subject) | LKJ( 1) |
Sampler by chain
| Chain | Divergent | Max tree depth hits | E-BFMI | Step size | Mean acceptance |
|---|---|---|---|---|---|
| 1 | 0 | 0 | 0.6824 | 0.1005 | 0.9460 |
| 2 | 0 | 0 | 0.6765 | 0.0910 | 0.9580 |
Leave-one-out cross-validation (PSIS-LOO)
| Quantity | Estimate | SE |
|---|---|---|
| elpd_loo (expected log predictive density) | −846.70 | 22.724 |
| p_loo (effective number of parameters) | 33.927 | 8.768 |
| LOOIC (−2 × elpd_loo) | 1693.40 | 45.447 |
Posterior predictive checks
| Statistic | Observed | Replicated (mean) | P(rep ≥ obs) |
|---|---|---|---|
| Mean | 298.07 | 298.19 | 0.5217 |
| Standard deviation | 56.591 | 56.726 | 0.5350 |
| Maximum | 466.35 | 471.20 | 0.5750 |
| Minimum | 194.33 | 168.59 | 0.0417 |
Varying effects by level
| Group | Level | Effect | Mean | 95% lower | 95% upper |
|---|---|---|---|---|---|
| Subject | 308 | (Intercept) | 1.764 | −26.568 | 27.838 |
| Subject | 308 | Days | 8.925 | 3.669 | 14.197 |
| Subject | 309 | (Intercept) | −39.735 | −66.942 | −11.624 |
| Subject | 309 | Days | −8.812 | −14.520 | −3.886 |
| Subject | 310 | (Intercept) | −38.562 | −65.376 | −10.413 |
| Subject | 310 | Days | −5.616 | −11.018 | −0.1130 |
| Subject | 330 | (Intercept) | 22.462 | −3.873 | 49.486 |
| Subject | 330 | Days | −4.662 | −10.269 | 0.7299 |
| Subject | 331 | (Intercept) | 22.159 | −5.978 | 47.655 |
| Subject | 331 | Days | −2.363 | −7.980 | 2.891 |
| Subject | 332 | (Intercept) | 8.390 | −15.436 | 32.571 |
| Subject | 332 | Days | −0.3063 | −5.486 | 5.174 |
| Subject | 333 | (Intercept) | 17.060 | −9.295 | 42.335 |
| Subject | 333 | Days | −0.1652 | −5.374 | 5.842 |
| Subject | 334 | (Intercept) | −6.429 | −31.168 | 18.210 |
| Subject | 334 | Days | 0.9945 | −4.002 | 5.914 |
| Subject | 335 | (Intercept) | −0.6551 | −24.853 | 25.528 |
| Subject | 335 | Days | −10.683 | −16.370 | −5.427 |
| Subject | 337 | (Intercept) | 34.407 | 10.627 | 60.525 |
| Subject | 337 | Days | 8.700 | 3.339 | 13.934 |
| Subject | 349 | (Intercept) | −23.572 | −53.515 | 3.232 |
| Subject | 349 | Days | 0.9461 | −4.373 | 6.403 |
| Subject | 350 | (Intercept) | −11.630 | −40.389 | 14.241 |
| Subject | 350 | Days | 6.243 | 0.7660 | 11.784 |
| Subject | 351 | (Intercept) | 5.436 | −20.205 | 33.931 |
| Subject | 351 | Days | −3.034 | −8.709 | 2.455 |
| Subject | 352 | (Intercept) | 16.442 | −10.144 | 41.397 |
| Subject | 352 | Days | 4.048 | −1.017 | 9.816 |
| Subject | 369 | (Intercept) | 3.525 | −23.937 | 30.338 |
| Subject | 369 | Days | 0.8796 | −4.575 | 6.816 |
| Subject | 370 | (Intercept) | −23.620 | −49.997 | 4.088 |
| Subject | 370 | Days | 4.546 | −0.6811 | 10.270 |
| Subject | 371 | (Intercept) | 0.7514 | −24.788 | 27.692 |
| Subject | 371 | Days | −0.9866 | −6.376 | 4.122 |
| Subject | 372 | (Intercept) | 11.995 | −13.728 | 36.499 |
| Subject | 372 | Days | 1.203 | −4.114 | 6.358 |
- 3 of 180 rows were left out because a value was missing.
- 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 de47c4fd3c3948ac
# Dataset: s1_sleep (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/s1_sleep.parquet", col_select = c("Reaction", "Days", "Subject")))
n_input <- nrow(df)
df[["Subject"]] <- factor(df[["Subject"]], levels = c("308", "309", "310", "330", "331", "332", "333", "334", "335", "337", "349", "350", "351", "352", "369", "370", "371", "372")) # stored level order
df <- df[stats::complete.cases(df[c("Reaction", "Days", "Subject")]), , 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("Reaction", "Days", "Subject")) # infinite values stop the run (registry/errors.yaml)
outcome <- "Reaction"
# %% 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("Days"),
family = "gaussian",
trials = NULL,
exposure = NULL,
group = "Subject",
slopes = c("Days"),
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.95,
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-sleep-slopes/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
))
Bayesian gaussian (normal) model of Reaction (n = 177), NUTS (Hamiltonian Monte Carlo). Posterior: Days has median 10.6 (95% credible interval 7.03 to 13.9); P(> 0) = 1.00. Largest R-hat 1.008, 0 divergent transitions. PSIS-LOO elpd = -846.7 (SE 22.7).
- Days (posterior median)
- 10.610
- 95% credible interval
- [7.029, 13.895]
- P(effect > 0)
- 1
- Largest R-hat
- 1.008
- elpd (PSIS-LOO)
- −846.70
- Bayesian R² (median)
- 0.7936
Assumptions
- Sampler converged (R-hat, ESS) — Largest R-hat 1.008 (want ≤ 1.01); smallest bulk ESS 147 and tail ESS 185 (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 0.68 (below 0.3 means the sampler explores the tails poorly).
- Leave-one-out is reliable (Pareto k̂) — 9 of 177 rows have k̂ above 0.64 (largest 1.62); 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
| Parameter | Mean | SD | 95% lower | Median | 95% upper | R-hat | Bulk ESS | Tail ESS | P(> 0) |
|---|---|---|---|---|---|---|---|---|---|
| (Intercept) | 250.94 | 7.397 | 236.23 | 251.03 | 265.05 | 1.006 | 378.30 | 408.08 | 1 |
| Days | 10.565 | 1.704 | 7.029 | 10.610 | 13.895 | 0.9980 | 384.06 | 302.39 | 1 |
| sigma | 25.808 | 1.543 | 23.047 | 25.734 | 29.051 | 1.002 | 624.86 | 317.04 | 1 |
| sd(Subject: (Intercept)) | 26.328 | 6.765 | 15.022 | 25.630 | 40.962 | 1.008 | 303.12 | 345.91 | 1 |
| sd(Subject: Days) | 6.504 | 1.390 | 4.332 | 6.340 | 9.961 | 1.002 | 434.12 | 415.56 | 1 |
| cor(Subject: (Intercept), Days) | 0.1420 | 0.2936 | −0.4283 | 0.1504 | 0.7129 | 1.006 | 147.45 | 185.34 | 0.6867 |
Priors
| Parameter | Prior | Note |
|---|---|---|
| (Intercept) | Normal(298.1, 141.5) | at the predictors' means |
| Days | Normal(0, 48.85) | autoscaled |
| sigma | Exponential(0.01767) | residual SD |
| sd(Subject: (Intercept)) | Exponential(0.01767) | |
| sd(Subject: Days) | Exponential(0.01767) | |
| cor(Subject) | LKJ(1) |
Sampler by chain
| Chain | Divergent | Max tree depth hits | E-BFMI | Step size | Mean acceptance |
|---|---|---|---|---|---|
| 1 | 0 | 0 | 0.6824 | 0.1005 | 0.9460 |
| 2 | 0 | 0 | 0.6765 | 0.0910 | 0.9580 |
Leave-one-out cross-validation (PSIS-LOO)
| Quantity | Estimate | SE |
|---|---|---|
| elpd_loo (expected log predictive density) | −846.70 | 22.724 |
| p_loo (effective number of parameters) | 33.927 | 8.768 |
| LOOIC (−2 × elpd_loo) | 1693.40 | 45.447 |
Posterior predictive checks
| Statistic | Observed | Replicated (mean) | P(rep ≥ obs) |
|---|---|---|---|
| Mean | 298.07 | 298.19 | 0.5217 |
| Standard deviation | 56.591 | 56.726 | 0.5350 |
| Maximum | 466.35 | 471.20 | 0.5750 |
| Minimum | 194.33 | 168.59 | 0.0417 |
Varying effects by level
| Group | Level | Effect | Mean | 95% lower | 95% upper |
|---|---|---|---|---|---|
| Subject | 308 | (Intercept) | 1.764 | −26.568 | 27.838 |
| Subject | 308 | Days | 8.925 | 3.669 | 14.197 |
| Subject | 309 | (Intercept) | −39.735 | −66.942 | −11.624 |
| Subject | 309 | Days | −8.812 | −14.520 | −3.886 |
| Subject | 310 | (Intercept) | −38.562 | −65.376 | −10.413 |
| Subject | 310 | Days | −5.616 | −11.018 | −0.1130 |
| Subject | 330 | (Intercept) | 22.462 | −3.873 | 49.486 |
| Subject | 330 | Days | −4.662 | −10.269 | 0.7299 |
| Subject | 331 | (Intercept) | 22.159 | −5.978 | 47.655 |
| Subject | 331 | Days | −2.363 | −7.980 | 2.891 |
| Subject | 332 | (Intercept) | 8.390 | −15.436 | 32.571 |
| Subject | 332 | Days | −0.3063 | −5.486 | 5.174 |
| Subject | 333 | (Intercept) | 17.060 | −9.295 | 42.335 |
| Subject | 333 | Days | −0.1652 | −5.374 | 5.842 |
| Subject | 334 | (Intercept) | −6.429 | −31.168 | 18.210 |
| Subject | 334 | Days | 0.9945 | −4.002 | 5.914 |
| Subject | 335 | (Intercept) | −0.6551 | −24.853 | 25.528 |
| Subject | 335 | Days | −10.683 | −16.370 | −5.427 |
| Subject | 337 | (Intercept) | 34.407 | 10.627 | 60.525 |
| Subject | 337 | Days | 8.700 | 3.339 | 13.934 |
| Subject | 349 | (Intercept) | −23.572 | −53.515 | 3.232 |
| Subject | 349 | Days | 0.9461 | −4.373 | 6.403 |
| Subject | 350 | (Intercept) | −11.630 | −40.389 | 14.241 |
| Subject | 350 | Days | 6.243 | 0.7660 | 11.784 |
| Subject | 351 | (Intercept) | 5.436 | −20.205 | 33.931 |
| Subject | 351 | Days | −3.034 | −8.709 | 2.455 |
| Subject | 352 | (Intercept) | 16.442 | −10.144 | 41.397 |
| Subject | 352 | Days | 4.048 | −1.017 | 9.816 |
| Subject | 369 | (Intercept) | 3.525 | −23.937 | 30.338 |
| Subject | 369 | Days | 0.8796 | −4.575 | 6.816 |
| Subject | 370 | (Intercept) | −23.620 | −49.997 | 4.088 |
| Subject | 370 | Days | 4.546 | −0.6811 | 10.270 |
| Subject | 371 | (Intercept) | 0.7514 | −24.788 | 27.692 |
| Subject | 371 | Days | −0.9866 | −6.376 | 4.122 |
| Subject | 372 | (Intercept) | 11.995 | −13.728 | 36.499 |
| Subject | 372 | Days | 1.203 | −4.114 | 6.358 |
- 3 of 180 rows were left out because a value was missing.
- 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 de47c4fd3c3948ac
# Dataset: s1_sleep (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/s1_sleep.parquet", columns=["Reaction", "Days", "Subject"])
n_input = len(df)
df["Subject"] = pd.Categorical(df["Subject"], categories=["308", "309", "310", "330", "331", "332", "333", "334", "335", "337", "349", "350", "351", "352", "369", "370", "371", "372"]) # stored level order
df = df.dropna(subset=["Reaction", "Days", "Subject"]) # listwise deletion over the analysis columns
df["Subject"] = df["Subject"].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, ["Reaction", "Days", "Subject"]) # infinite values stop the run (registry/errors.yaml)
outcome = "Reaction"
# %% 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=["Days"],
family="gaussian",
trials=None,
exposure=None,
group="Subject",
slopes=["Days"],
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.95,
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-sleep-slopes/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: 9 chart(s) dropped to stay under 100 KB; 9 chart(s) dropped to stay under 100 KB.
This varying-slopes fit was run with adapt_delta raised to 0.95, smaller steps for a curved posterior. It reports 0 divergent transitions, 0 tree-depth hits and a lowest E-BFMI of 0.68. The simpler mtcars regression has a lowest E-BFMI of 1.04.
What the sampler tells you
Read| Signal | Means | Change |
|---|---|---|
| Divergent transitionDivergent transitionA NUTS step whose simulated trajectory blew up: the sampler hit curvature it can't follow, and may miss that region. | The leapfrog energy error blew up: curvature the step size can't follow, so a region may be missed | Raise adapt_delta, reparameterize (non-centered), tighten priors |
| Tree-depth hits | Trajectories hit the length cap | Usually efficiency, not bias; reparameterize or raise the cap |
| E-BFMI below | Momentum refreshes can't move through energy levels | Heavy tails or poor scaling; reparameterize |
A raised tree-depth cap only allows more work; it doesn't fix a funnel. And zero divergences is necessary, not sufficient: no finite run proves every mode was found.
ESS can exceed the draws
ReadBecause HMC proposals travel far, successive draws can be negatively correlated. Then the effective sample size of a mean can exceed the number of draws, and that is legitimate, not a bug to clip away. Tail quantiles usually have a smaller ESS than the mean, which is why bulk and tail ESS are reported separately.
Where each idea stands in CodeSplash
Read| Entry | In CodeSplash |
|---|---|
| HMC (INF011) | Partly runs in CodeSplash: Stan's NUTS is an adaptive HMC, run by Bayesian regression model (Stan) and Simulation-based calibration. A fixed-path-length HMC option isn't offered; the reference's leapfrog program is a verified component check. |
| NUTS (INF012) | Partly runs in CodeSplash: the default algorithm of those two methods, for their built-in model families (Gaussian, Student-t, logistic and binomial, Poisson, negative binomial, ordinal). You can't write your own Stan program. |
Check your understanding
CheckpointCheck yourself
Why does HMC still need an accept step after its leapfrog trajectory?
Show the answer
Answer: b
The integrator is reversible and keeps volume, so a Metropolis test on the energy error makes the chain exact despite discretization.
Check yourself
An HMC chain accepts 99.9% of its trajectories. What could that mean?
Show the answer
Answer: b
Tiny steps keep energy error near zero, so nearly everything is accepted, but at a high cost per draw. Stan's warmup aims at a target acceptance (adapt_delta) to balance this.
Check yourself
To save time on a large dataset, you replace HMC's full-data gradient with the gradient of a random minibatch, keeping everything else. What happens?
Show the answer
Answer: b
Plain HMC's guarantees assume exact gradients. Stochastic-gradient variants add friction and noise corrections, and they are approximate.
Check yourself
A custom sampler runs leapfrog steps until the trajectory starts to turn, then always keeps the final point. Is it NUTS?
Show the answer
Answer: b
Tree building, the turn criterion and a balanced selection among visited states work together. Any one alone isn't the algorithm.
Check yourself
A hierarchical fit reports 30 divergent transitions concentrated at small values of a group SD, and many tree-depth hits. A colleague raises the maximum tree depth from 10 to 15. Does that fix the problem?
Show the answer
Answer: b
A larger cap permits more leapfrog steps; it doesn't change the curvature that makes the integrator blow up.
Recap
Recap- HMC adds momentum and follows the gradient with leapfrog steps, then accepts by energy error.
- NUTS grows the path until it turns and selects a state with an exactness-preserving rule.
- Divergences mean missed regions; depth hits mean slow trajectories; low E-BFMI means poor energy exploration.
- In CodeSplash, NUTS runs every Stan fit by default; fixed-length HMC isn't offered.
Concepts in this lesson