Skip to content

Probabilistic inference, Monte Carlo, and posterior computation · Probabilistic computation and inference foundations · INF011 · Algorithm

Hamiltonian 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…

Partly runs in CodeSplash (Experimental) Component demo, not a trained model CodeSplash's run and the reference's record

In CodeSplash

A CodeSplash method covers part of this entry; some options or variants aren't built yet. The methods that run it are Experimental.

Do it in CodeSplash Run it on your own data. It's in the Experimental lane in the app.

Availability
Partly runs in CodeSplash (Experimental)
Code example
Component demo, not a trained model
Who ran it
CodeSplash's run and the reference's record
CodeSplash's run
The reference's example ran in Python and R here, and they agree.
The reference's record
Python: Ran in the reference's review. The report doesn't record which version of the code ran. R: Reviewed but not run: R wasn't available to the reference's authors.

Purpose

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 geometry and gradient cost.

Question / hypotheses

Can approximate Hamiltonian trajectories move across the posterior efficiently while a Metropolis correction removes numerical integration error?

Architecture / computational structure

Refresh momentum, integrate leapfrog steps, construct a reversible proposal, and accept with min(1,exp(H_old-H_new)). Full gradients are used in ordinary HMC. The mass matrix supplies a metric; its convention must match both momentum covariance and position updates.

Assumptions

The target must admit usable continuous-coordinate gradients after valid constraint transformations. The integrator and proposal construction must have the required reversibility and volume preservation. Discrete latent states require marginalization, a separate update, or another inference method.

Formula / computational definition

H(q,p)=U(q)+12pTM−1p, U=−log⁡π~;p1/2=p−ϵ2∇U(q), q+=q+ϵM−1p1/2, p+=p1/2−ϵ2∇U(q+).H(q,p)=U(q)+\tfrac12p^TM^{-1}p,\ U=-\log\tilde\pi;\quad p_{1/2}=p-\tfrac\epsilon2\nabla U(q),\ q^+=q+\epsilon M^{-1}p_{1/2},\ p^+=p_{1/2}-\tfrac\epsilon2\nabla U(q^+).

Parameters and notation

q contains model unknowns; p is auxiliary momentum sampled from N(0,M), not an additional model parameter. Hyperparameters are step size epsilon, trajectory length or leapfrog count L, mass matrix M, warmup, and chain count. Coordinate reparameterization often improves geometry more than simply increasing computation.

Fitting, fine-tuning, and adaptation

Adapt step size and metric during warmup, then apply the declared sampling kernel. For a changed posterior, repeat sufficient warmup and inspect geometry. Bayesian neural sampling draws weights; it is not ordinary fine-tuning to a point estimate. Freezing a backbone defines a smaller conditional posterior and must be reported.

How to use and calibrate

Run multiple chains and inspect divergence reports, energy behavior, effective sample sizes, Monte Carlo error, and convergence summaries. Plot traces and posterior correlations. Validate gradients and compare a low-dimensional target to known answers before fitting a large hierarchy.

Example application

Infer correlated continuous parameters in a hierarchical latent-state or neural likelihood model whose posterior is accessible through a differentiable log joint.

Interpretation / pitfalls

Watch out

A high acceptance rate can reflect steps that are too small, while divergent trajectories may reveal serious geometry failures. Merely plugging minibatch gradients into this integrator does not yield ordinary exact HMC. Finite-run diagnostics cannot prove all modes have been explored.

Python and R code examples

Scope: One leapfrog trajectory and its Metropolis acceptance probability for a one-dimensional Gaussian target; no complete chain or adaptation.

Implementation route: The component uses native NumPy/base R. Full HMC is available through Stan with CmdStanPy and CmdStanR, requiring a model, compiler/toolchain, transformed-density correctness, and diagnostic review.

Dependencies and validation: Python — executed successfully on the supplied synthetic inputs; imports identify NumPy/SciPy dependencies. R — base R, reviewed but not executed because Rscript is unavailable. Random-number streams differ between languages; matching seed integers do not imply matching draws.

Python and R

The reference's own programs, shown as written. A component demo shows one central piece of the method; it doesn't train a full model.

Python

Component demo, not a trained model — One leapfrog trajectory and its Metropolis acceptance probability for a one-dimensional Gaussian target; no complete chain or adaptation. · needs numpy

import numpy as np
q=1.; p=.8; q0=q; p0=p; step=.15; L=10
p-=.5*step*q
for j in range(L):
    q+=step*p
    if j<L-1: p-=step*q
p-=.5*step*q; p=-p
old=.5*(q0*q0+p0*p0); new=.5*(q*q+p*p)
print('proposal',q,'energy error',new-old,'acceptance',min(1.,np.exp(old-new)))
R

Component demo, not a trained model — One leapfrog trajectory and its Metropolis acceptance probability for a one-dimensional Gaussian target; no complete chain or adaptation.

q <- 1; p <- .8; q0 <- q; p0 <- p; step <- .15; L <- 10
p <- p-.5*step*q
for(j in 1:L) {q <- q+step*p; if(j<L) p <- p-step*q}
p <- p-.5*step*q; p <- -p
old <- .5*(q0*q0+p0*p0); new <- .5*(q*q+p*p)
print(c(proposal=q,energy.error=new-old,acceptance=min(1,exp(old-new))))

Sources

From the CodeSplash reference, entry INF011.