Skip to content

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.

Advanced ~15 min10 steps

What runs in CodeSplash

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

Read first

01

Why random walks are slow

Read

A random-walk Metropolis chain moves a distance of about one step size per iteration, in a random direction. To cross a posterior that is LL step sizes wide it needs on the order of L2L^2 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 U(q)=−log⁡p~(q)U(q)=-\log\tilde p(q) as a landscape and the parameters qq 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…
02

Momentum and leapfrog steps

Read

Each iteration draws a momentum p∼N(0,M)p\sim N(0,M) and follows Hamilton's equations for H(q,p)=U(q)+12p⊤M−1pH(q,p)=U(q)+\tfrac12 p^\top M^{-1}p 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., LL times:

p1/2=p−ϵ2∇U(q),q+=q+ϵM−1p1/2,p+=p1/2−ϵ2∇U(q+).p_{1/2}=p-\tfrac\epsilon2\nabla U(q),\qquad q^+=q+\epsilon M^{-1}p_{1/2},\qquad p^+=p_{1/2}-\tfrac\epsilon2\nabla U(q^+).

Exact dynamics would keep HH constant. Leapfrog steps keep it only approximately, so the endpoint is accepted with probability min⁡(1,eHold−Hnew)\min\big(1,e^{H_{old}-H_{new}}\big). In the reference's one-dimensional example the energy error was −0.00069, so the acceptance probability was 1.00. The mass matrix MM, 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.

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.

03

How long to roll? NUTS

Read

Too 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,

Δq⊤p−<0orΔq⊤p+<0,Δq=q+−q−,\Delta q^\top p^-<0\quad\text{or}\quad \Delta q^\top p^+<0,\qquad \Delta q=q^+-q^-,

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

Not any turn rule will do

Read

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

05

NUTS in CodeSplash

Read

Every 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 (Stan)Recorded · Python and R agreeRecorded 2026-11-25 · 90 values compared
R

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

ParameterMeanSD95% lowerMedian95% upperR-hatBulk ESSTail ESSP(> 0)
(Intercept)250.947.397236.23251.03265.051.006378.30408.081
Days10.5651.7047.02910.61013.8950.9980384.06302.391
sigma25.8081.54323.04725.73429.0511.002624.86317.041
sd(Subject: (Intercept))26.3286.76515.02225.63040.9621.008303.12345.911
sd(Subject: Days)6.5041.3904.3326.3409.9611.002434.12415.561
cor(Subject: (Intercept), Days)0.14200.2936−0.42830.15040.71291.006147.45185.340.6867

Priors

ParameterPriorNote
(Intercept)Normal(298.1, 141.5)at the predictors' means
DaysNormal(0, 48.85)autoscaled
sigmaExponential(0.01767)residual SD
sd(Subject: (Intercept))Exponential(0.01767)
sd(Subject: Days)Exponential(0.01767)
cor(Subject)LKJ( 1)

Sampler by chain

ChainDivergentMax tree depth hitsE-BFMIStep sizeMean acceptance
1000.68240.10050.9460
2000.67650.09100.9580

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

QuantityEstimateSE
elpd_loo (expected log predictive density)−846.7022.724
p_loo (effective number of parameters)33.9278.768
LOOIC (−2 × elpd_loo)1693.4045.447

Posterior predictive checks

StatisticObservedReplicated (mean)P(rep ≥ obs)
Mean298.07298.190.5217
Standard deviation56.59156.7260.5350
Maximum466.35471.200.5750
Minimum194.33168.590.0417

Varying effects by level

GroupLevelEffectMean95% lower95% upper
Subject308(Intercept)1.764−26.56827.838
Subject308Days8.9253.66914.197
Subject309(Intercept)−39.735−66.942−11.624
Subject309Days−8.812−14.520−3.886
Subject310(Intercept)−38.562−65.376−10.413
Subject310Days−5.616−11.018−0.1130
Subject330(Intercept)22.462−3.87349.486
Subject330Days−4.662−10.2690.7299
Subject331(Intercept)22.159−5.97847.655
Subject331Days−2.363−7.9802.891
Subject332(Intercept)8.390−15.43632.571
Subject332Days−0.3063−5.4865.174
Subject333(Intercept)17.060−9.29542.335
Subject333Days−0.1652−5.3745.842
Subject334(Intercept)−6.429−31.16818.210
Subject334Days0.9945−4.0025.914
Subject335(Intercept)−0.6551−24.85325.528
Subject335Days−10.683−16.370−5.427
Subject337(Intercept)34.40710.62760.525
Subject337Days8.7003.33913.934
Subject349(Intercept)−23.572−53.5153.232
Subject349Days0.9461−4.3736.403
Subject350(Intercept)−11.630−40.38914.241
Subject350Days6.2430.766011.784
Subject351(Intercept)5.436−20.20533.931
Subject351Days−3.034−8.7092.455
Subject352(Intercept)16.442−10.14441.397
Subject352Days4.048−1.0179.816
Subject369(Intercept)3.525−23.93730.338
Subject369Days0.8796−4.5756.816
Subject370(Intercept)−23.620−49.9974.088
Subject370Days4.546−0.681110.270
Subject371(Intercept)0.7514−24.78827.692
Subject371Days−0.9866−6.3764.122
Subject372(Intercept)11.995−13.72836.499
Subject372Days1.203−4.1146.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
))
Python

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

ParameterMeanSD95% lowerMedian95% upperR-hatBulk ESSTail ESSP(> 0)
(Intercept)250.947.397236.23251.03265.051.006378.30408.081
Days10.5651.7047.02910.61013.8950.9980384.06302.391
sigma25.8081.54323.04725.73429.0511.002624.86317.041
sd(Subject: (Intercept))26.3286.76515.02225.63040.9621.008303.12345.911
sd(Subject: Days)6.5041.3904.3326.3409.9611.002434.12415.561
cor(Subject: (Intercept), Days)0.14200.2936−0.42830.15040.71291.006147.45185.340.6867

Priors

ParameterPriorNote
(Intercept)Normal(298.1, 141.5)at the predictors' means
DaysNormal(0, 48.85)autoscaled
sigmaExponential(0.01767)residual SD
sd(Subject: (Intercept))Exponential(0.01767)
sd(Subject: Days)Exponential(0.01767)
cor(Subject)LKJ(1)

Sampler by chain

ChainDivergentMax tree depth hitsE-BFMIStep sizeMean acceptance
1000.68240.10050.9460
2000.67650.09100.9580

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

QuantityEstimateSE
elpd_loo (expected log predictive density)−846.7022.724
p_loo (effective number of parameters)33.9278.768
LOOIC (−2 × elpd_loo)1693.4045.447

Posterior predictive checks

StatisticObservedReplicated (mean)P(rep ≥ obs)
Mean298.07298.190.5217
Standard deviation56.59156.7260.5350
Maximum466.35471.200.5750
Minimum194.33168.590.0417

Varying effects by level

GroupLevelEffectMean95% lower95% upper
Subject308(Intercept)1.764−26.56827.838
Subject308Days8.9253.66914.197
Subject309(Intercept)−39.735−66.942−11.624
Subject309Days−8.812−14.520−3.886
Subject310(Intercept)−38.562−65.376−10.413
Subject310Days−5.616−11.018−0.1130
Subject330(Intercept)22.462−3.87349.486
Subject330Days−4.662−10.2690.7299
Subject331(Intercept)22.159−5.97847.655
Subject331Days−2.363−7.9802.891
Subject332(Intercept)8.390−15.43632.571
Subject332Days−0.3063−5.4865.174
Subject333(Intercept)17.060−9.29542.335
Subject333Days−0.1652−5.3745.842
Subject334(Intercept)−6.429−31.16818.210
Subject334Days0.9945−4.0025.914
Subject335(Intercept)−0.6551−24.85325.528
Subject335Days−10.683−16.370−5.427
Subject337(Intercept)34.40710.62760.525
Subject337Days8.7003.33913.934
Subject349(Intercept)−23.572−53.5153.232
Subject349Days0.9461−4.3736.403
Subject350(Intercept)−11.630−40.38914.241
Subject350Days6.2430.766011.784
Subject351(Intercept)5.436−20.20533.931
Subject351Days−3.034−8.7092.455
Subject352(Intercept)16.442−10.14441.397
Subject352Days4.048−1.0179.816
Subject369(Intercept)3.525−23.93730.338
Subject369Days0.8796−4.5756.816
Subject370(Intercept)−23.620−49.9974.088
Subject370Days4.546−0.681110.270
Subject371(Intercept)0.7514−24.78827.692
Subject371Days−0.9866−6.3764.122
Subject372(Intercept)11.995−13.72836.499
Subject372Days1.203−4.1146.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.

06

What the sampler tells you

Read
SignalMeansChange
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 missedRaise adapt_delta, reparameterize (non-centered), tighten priors
Tree-depth hitsTrajectories hit the length capUsually efficiency, not bias; reparameterize or raise the cap
E-BFMI below 0.30.3Momentum refreshes can't move through energy levelsHeavy 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.

07

ESS can exceed the draws

Read

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

08

Where each idea stands in CodeSplash

Read
EntryIn 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.
09

Check your understanding

Checkpoint

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

10

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