Module contents
Lesson 23 of 27Advanced 120 min

Hamiltonian Monte Carlo, NUTS and Langevin dynamics

Random walks scale poorly with dimension; gradients offer another approach. We interpret the posterior as a potential-energy landscape, simulate Hamiltonian dynamics with the symplectic, reversible leapfrog integrator and correct error with Metropolis. We outline NUTS, diagnose divergences and finish with Langevin methods (ULA, MALA and SGLD).

After this lesson you can

  • Formulate HMC with potential energy -log p and Gaussian-momentum kinetic energy.
  • Prove leapfrog preserves volume and is reversible, and explain why that validates the Metropolis step.
  • Implement HMC with dual-averaging step-size adaptation and compare ESS per gradient with Metropolis.
  • Explain the U-turn criterion and NUTS tree construction conceptually.
  • Diagnose divergences and energy errors and relate them to target geometry.
  • Implement MALA and SGLD and understand the bias of uncorrected methods.

Before you start

Using posterior geometry

A high-dimensional random walk may require small steps and explore slowly. Hamiltonian dynamics for sampling introduces auxiliary momentum p∼N(0,M)\vb p\sim\Normal(\vb0,\mat M) and defines

H(q,p)=U(q)+K(p),U(q)=−log⁡π~(q),K(p)=12p⊤M−1p.H(\vb q,\vb p)=U(\vb q)+K(\vb p),\qquad U(\vb q)=-\log\tilde\pi(\vb q),\quad K(\vb p)=\tfrac12\vb p\T\mat M\inv\vb p.

The joint proportional to e−He^{-H} has the desired posterior as its marginal in q\vb q. Equations q˙=M−1p\dot{\vb q}=\mat M\inv\vb p and p˙=−∇U(q)\dot{\vb p}=-\nabla U(\vb q) preserve energy and volume in exact dynamics. The positive mass matrix defines trajectory scales; a poor choice may require very small steps. Numerical integration introduces error, so Metropolis corrects it.

Leapfrog and correction

The leapfrog integrator alternates a half momentum step, a full position step and another half momentum step:

p1/2=p0−ϵ2∇U(q0),q1=q0+ϵM−1p1/2,p1=p1/2−ϵ2∇U(q1).\begin{aligned} \vb p_{1/2}&=\vb p_0-\tfrac\epsilon2\nabla U(\vb q_0),\\ \vb q_1&=\vb q_0+\epsilon\mat M\inv\vb p_{1/2},\\ \vb p_1&=\vb p_{1/2}-\tfrac\epsilon2\nabla U(\vb q_1). \end{aligned}

Each update is a shear with Jacobian determinant one. Their composition preserves volume and is symplectic; reversing momentum and repeating the trajectory inverts the map. Energy is not exactly constant, but for stable steps it usually oscillates without explicit Euler’s typical systematic drift. Large steps can destroy stability; volume preservation does not guarantee accuracy.

InteractiveLaunch a particle across the posterior
q₁ horizontal and q₂ vertical, both −4 to 4. lower energy; higher energy.
Total energy along the trajectory
Target
0.20
16
1.2
Energy change0.007
Acceptance probability0.993
Change target, momentum, step size and length. The trajectory is deterministic for those values; energy change and Metropolis acceptance probability are displayed.
InteractiveEuler versus leapfrog
  • Explicit Euler and its cloud
  • Leapfrog and its cloud
0.15
40
Euler energy1.218
Leapfrog energy0.500
Euler area factor2.44
The harmonic oscillator shows trajectories and transformed small clouds. Euler increases area; leapfrog preserves it, though its energy has error.

In Hamiltonian Monte Carlo, resample p\vb p, integrate LL steps, reverse momentum and accept with min⁡(1,e−ΔH)\min(1,e^{-\Delta H}). Reversibility of the map with reversal and unit volume allow the same detailed-balance proof as MH. Refreshing momentum adds exploration between trajectories; without refresh or other suitable randomization, deterministic dynamics may remain in orbits and not explore the marginal. Choosing ϵ\epsilon and LL matters: trajectories too short diffuse and long ones can retrace their steps.

Dual averaging tunes ϵ\epsilon during warmup using acceptance probabilities and freezes the smoothed average for sampling. An isolated target rate does not guarantee diagnosis of all geometry. The lab uses identity mass and bounds log step size during adaptation to avoid numerical overflow.

NUTS and divergences

The No-U-Turn Sampler (NUTS) builds a trajectory in both directions by doubling and stops growth when it detects a U-turn. For identity mass a geometric criterion uses (q+−q−)⊤p−(\vb q^+-\vb q^-)\T\vb p^- and (q+−q−)⊤p+(\vb q^+-\vb q^-)\T\vb p^+: a negative product indicates one endpoint returns toward the other. Recursive construction and balanced selection of valid states are essential; simply choosing the last point when detecting a turn does not implement NUTS.

InteractiveHow the NUTS tree grows
Depth0
States1
U-turnNo
Selected position0.000
Doubling illustration for an oscillator: trajectory, selection among candidates under a height, and endpoint turn are shown. This is a geometric demonstration, not a complete implementation of NUTS recursive selection.

An HMC divergence flags a trajectory whose numerical energy error exceeds a threshold or is nonfinite. It may indicate integrator failure in a high-curvature region, not merely a rejected proposal. In Neal’s funnel, v∼N(0,32)v\sim\Normal(0,3^2) and xj∣v∼N(0,ev)x_j\mid v\sim\Normal(0,e^v): when vv is very negative, variables xx narrow. One fixed step must resolve very different scales.

InteractiveDivergences in Neal's funnel
  • State after transition
  • Divergent transition
Step ε
Divergences12
Saved transitions1500
Outside window157
Actual HMC runs with identity mass, 15 steps and 1500 saved transitions after 500 initial ones. The starting state of a divergent transition is marked; points outside the window are counted separately.

These runs were generated with seed 2323 and threshold ∣ΔH∣>1000|\Delta H|>1000 or nonfinite energy. They are not NUTS or a universal diagnosis of that threshold. Non-centered parameterization can help by decoupling scales, though its effect depends on model and data. E-BFMI compares energy changes between transitions with energy variation; low values may indicate poor exploration and should be examined alongside divergences, depth, R-hat, ESS and traces.

Langevin

Overdamped Langevin dynamics combine drift and noise. With step hh, ULA uses q′=q+h2∇log⁡π(q)+hξ\vb q'=\vb q+\tfrac h2\nabla\log\pi(\vb q)+\sqrt h\vb\xi. Fixed-step discretization generally introduces bias. MALA and SGLD start from the same idea: MALA adds MH correction with an asymmetric proposal ratio; SGLD replaces the gradient with a stochastic estimate and usually omits that correction. Its bias depends on step size, gradient noise and adaptation regime; decreasing step size requires additional conditions and does not make every finite run exact.

Labs

HMC, MALA and random walk from scratch

Use the m14-l07 module with the same generator and prior precision 1.5; you can also download it. The integrator uses identity mass and log-posterior gradient, so the half-step adds the gradient. HMC uses 500 adaptation steps and 1000 samples; random walk uses the same budget and adapts only in warmup. MALA uses a fixed step and discards its first 500 of 2000 iterations. One chain per method is insufficient to ensure convergence.

[ ]Model from m14-l07Browser
"""MAP logístico con prior gaussiano y aproximación de Laplace."""
import numpy as np
from scipy.special import expit


def negative_log_posterior(w, X, y, alpha):
    z = X @ w
    p = expit(z)
    value = np.logaddexp(0., z).sum() - y @ z + .5 * alpha * (w @ w)
    gradient = X.T @ (p-y) + alpha*w
    H = X.T @ ((p*(1-p))[:,None]*X) + alpha*np.eye(X.shape[1])
    return value, gradient, H


def fit_laplace(X, y, alpha=1., tol=1e-9, max_iter=100):
    X=np.asarray(X,dtype=float);y=np.asarray(y,dtype=float)
    if X.ndim!=2 or y.shape!=(X.shape[0],) or X.shape[1]==0:
        raise ValueError('dimensiones incompatibles')
    if not np.all(np.isfinite(X)) or not np.all(np.isfinite(y)) or np.any((y!=0)&(y!=1)) or not np.isfinite(alpha) or alpha<=0 or tol<=0 or max_iter<1:
        raise ValueError('datos finitos, etiquetas binarias, alpha y tolerancia positivos y al menos una iteración')
    w=np.zeros(X.shape[1]); converged=False
    for iteration in range(max_iter):
        value,gradient,H=negative_log_posterior(w,X,y,alpha)
        if np.linalg.norm(gradient,np.inf)<tol:
            converged=True;break
        direction=np.linalg.solve(H,gradient)
        rate=1.
        while rate>1e-12:
            candidate=w-rate*direction
            if negative_log_posterior(candidate,X,y,alpha)[0]<=value-1e-4*rate*(gradient@direction):
                break
            rate*=.5
        if rate<=1e-12:break
        w=candidate
    value,gradient,H=negative_log_posterior(w,X,y,alpha)
    if np.linalg.norm(gradient,np.inf)<tol:converged=True
    cov=np.linalg.solve(H,np.eye(X.shape[1]))
    return w,cov,{'converged':converged,'iterations':iteration+1,
                  'gradient_inf':np.linalg.norm(gradient,np.inf),'objective':value}


def predict_probit(X, mean, covariance):
    X=np.asarray(X,dtype=float)
    variance=np.einsum('ij,jk,ik->i',X,covariance,X)
    return expit((X@mean)/np.sqrt(1+np.pi*np.maximum(variance,0)/8))


def synthetic_data(seed=2026,n_train=40,n_test=2000):
    """Datos sintéticos Bernoulli, partición de test independiente en el mismo generador."""
    rng=np.random.default_rng(seed)
    true_w=np.array([-.4,1.4,-1.])
    def generate(n):
        X=np.column_stack((np.ones(n),rng.normal(size=(n,2))))
        y=rng.binomial(1,expit(X@true_w))
        return X,y
    X,y=generate(n_train);X_test,y_test=generate(n_test)
    return X,y,X_test,y_test,true_w
[ ]Leapfrog, HMC, MH and MALABrowser
import numpy as np
from scipy.special import expit

def leapfrog(grad_logp,q,p,eps,L):
    q=q.copy();p=p.copy();p+=.5*eps*grad_logp(q)
    for i in range(L):
        q+=eps*p
        if i<L-1:p+=eps*grad_logp(q)
    p+=.5*eps*grad_logp(q)
    return q,p

def hmc(logp,grad,start,seed,warmup=500,draws=1000,L=8,eps0=.05,target=.8):
    rng=np.random.default_rng(seed);q=np.array(start,dtype=float);logs=np.log(eps0);mu=np.log(10*eps0);bar=0.;logavg=logs;out=[];accept=[];energies=[]
    for t in range(1,warmup+draws+1):
        p=rng.normal(size=q.size);H0=-logp(q)+.5*(p@p)
        prop,p1=leapfrog(grad,q,p,np.exp(logs),L);H1=-logp(prop)+.5*(p1@p1)
        delta=H1-H0;prob=np.exp(min(0.,-delta)) if np.isfinite(delta) else 0.
        if rng.random()<prob:q=prop
        if t<=warmup:
            bar=(1-1/(t+10))*bar+(target-prob)/(t+10)
            logs=np.clip(mu-np.sqrt(t)*bar/.05,-10,2)
            weight=t**(-.75);logavg=weight*logs+(1-weight)*logavg
            if t==warmup:logs=logavg
        else:out.append(q.copy());accept.append(prob);energies.append(delta)
    return np.array(out),np.mean(accept),np.exp(logs),np.array(energies)

def rwm(logp,start,seed,warmup=500,draws=1000,scale=.1):
    rng=np.random.default_rng(seed);q=np.array(start,dtype=float);lp=logp(q);logs=np.log(scale);out=[];accepted=0
    for t in range(warmup+draws):
        prop=q+np.exp(logs)*rng.normal(size=q.size);new=logp(prop);take=np.log(rng.random())<min(0.,new-lp)
        if take:q=prop;lp=new
        if t<warmup:logs+=.8*(t+20)**(-.6)*(take-.234)
        else:out.append(q.copy());accepted+=take
    return np.array(out),accepted/draws,np.exp(logs)

def mala(logp,grad,start,seed,steps=2000,eps=.2):
    rng=np.random.default_rng(seed);q=np.array(start,dtype=float);lp=logp(q);g=grad(q);out=[];accepted=0
    for i in range(steps):
        forward=q+.5*eps**2*g;prop=forward+eps*rng.normal(size=q.size);new=logp(prop);gnew=grad(prop)
        reverse=prop+.5*eps**2*gnew
        logratio=new-lp-.5*np.sum((q-reverse)**2)/eps**2+.5*np.sum((prop-forward)**2)/eps**2
        if np.log(rng.random())<min(0.,logratio):q=prop;lp=new;g=gnew;accepted+=1
        out.append(q.copy())
    return np.array(out),accepted/steps

def ess(x):
    x=x-x.mean();n=len(x);size=1<<(2*n-1).bit_length();f=np.fft.rfft(x,n=size);a=np.fft.irfft(f*np.conjugate(f),n=size)[:n];rho=a/a[0];pairs=[]
    for i in range(0,n-1,2):
        pair=rho[i]+rho[i+1]
        if pair<0:break
        pairs.append(min(pair,pairs[-1]) if pairs else pair)
    return n/max(1/np.log10(n),-1+2*sum(pairs))
[ ]Prepare logistic posteriorBrowser
X,y,_,_,_=synthetic_data();alpha=1.5
def logp(w):
    z=X@w
    return float([email protected](0,z).sum()-.5*alpha*(w@w))
def grad(w):return X.T@(y-expit(X@w))-alpha*w
mode,cov,_=fit_laplace(X,y,alpha)
[ ]Logistic comparisonBrowser
samples,rate,eps,energy=hmc(logp,grad,mode,23)
rw,rwrate,rwscale=rwm(logp,mode,24)
ml,mlrate=mala(logp,grad,mode,25)
print('HMC media',samples.mean(0),'probabilidad media de aceptación',rate,'paso',eps,'ESS',*[round(ess(samples[:,j]),2) for j in range(3)],'máximo |delta H|',np.max(np.abs(energy)))
print('paseo media',rw.mean(0),'aceptación',rwrate,'ESS',*[round(ess(rw[:,j]),2) for j in range(3)])
print('MALA media',ml[500:].mean(0),'aceptación',mlrate,'ESS',*[round(ess(ml[500:,j]),2) for j in range(3)])

For a 100-dimensional normal with variances between 0.01 and 1, measure ESS of the first coordinate and evaluations during the retained phase. HMC uses L+1L+1 gradients per transition in this implementation; random walk calculates no gradients, so its ESS per gradient is undefined. We also show ESS per log-density evaluation for each method: this illustrative count is not compute time and excludes warmup.

[ ]100-dimensional GaussianBrowser
var=np.geomspace(.01,1,100)
def normal_log(q):return -.5*np.sum(q*q/var)
def normal_grad(q):return -q/var
hs,hr,he,dh=hmc(normal_log,normal_grad,np.zeros(100),43,L=10)
rs,rr,rscl=rwm(normal_log,np.zeros(100),44,scale=.03)
print('HMC probabilidad media de aceptación',hr,'paso',he,'ESS',ess(hs[:,0]),'ESS/gradiente',ess(hs[:,0])/(11*len(hs)),'ESS/logp',ess(hs[:,0])/(2*len(hs)))
print('paseo aceptación',rr,'escala',rscl,'ESS',ess(rs[:,0]),'ESS/logp',ess(rs[:,0])/len(rs))
[ ]Check reversibilityBrowser
q=np.array([1.,-.3]);p=np.array([.2,.9]);grad0=lambda x:-x
q1,p1=leapfrog(grad0,q,p,.2,10);q2,p2=leapfrog(grad0,q1,-p1,.2,10)
print('errores de inversión',np.max(abs(q-q2)),np.max(abs(p+p2)))

ESS can exceed the number of states with negative autocorrelation. In this run HMC achieves mean acceptance probability near 0.81 in 100 dimensions, while the walk shows very small ESS for the narrow coordinate. Do not extrapolate that contrast to other masses, lengths or budgets.

SGLD estimates the gradient of the sum of log likelihoods with a uniform minibatch with replacement and adds the full prior gradient. Two fixed steps are compared and 2000 states discarded. A smaller step reduces discretization error under appropriate conditions, but may also mix more slowly: these two finite chains do not isolate discretization bias from Monte Carlo error.

[ ]SGLD with minibatchesBrowser
def sgld(X,y,start,alpha,h,steps=10000,batch=10,seed=33):
    rng=np.random.default_rng(seed);w=np.array(start,dtype=float);out=[];n=len(y)
    for _ in range(steps):
        ids=rng.integers(n,size=batch);xb=X[ids];yb=y[ids]
        g=n/batch*(xb.T@(yb-expit(xb@w)))-alpha*w
        w=w+.5*h*g+np.sqrt(h)*rng.normal(size=w.size);out.append(w.copy())
    return np.array(out)
for h in (.002,.02):
    s=sgld(X,y,mode,alpha,h)
    print('paso',h,'media',s[2000:].mean(0),'desviación',s[2000:].std(0))

NUTS with PyMC

The local cell reproduces the same data in PyMC 6.4, uses four chains, 300 warmup steps and 500 samples per chain, and shows divergences, maximum depth, E-BFMI, R-hat and bulk ESS. In the checked run mean was approximately (−0.417,1.863,−0.484)(-0.417,1.863,-0.484), there were zero divergences and maximum depth was 3. These diagnostics and short budgets do not prove convergence or exact equivalence with manual HMC. The available installation uses the PyTensor backend without a C++ compiler.

[ ]NUTS with PyMCLocal GPU
"""MAP logístico con prior gaussiano y aproximación de Laplace."""
import numpy as np
from scipy.special import expit


def negative_log_posterior(w, X, y, alpha):
    z = X @ w
    p = expit(z)
    value = np.logaddexp(0., z).sum() - y @ z + .5 * alpha * (w @ w)
    gradient = X.T @ (p-y) + alpha*w
    H = X.T @ ((p*(1-p))[:,None]*X) + alpha*np.eye(X.shape[1])
    return value, gradient, H


def fit_laplace(X, y, alpha=1., tol=1e-9, max_iter=100):
    X=np.asarray(X,dtype=float);y=np.asarray(y,dtype=float)
    if X.ndim!=2 or y.shape!=(X.shape[0],) or X.shape[1]==0:
        raise ValueError('dimensiones incompatibles')
    if not np.all(np.isfinite(X)) or not np.all(np.isfinite(y)) or np.any((y!=0)&(y!=1)) or not np.isfinite(alpha) or alpha<=0 or tol<=0 or max_iter<1:
        raise ValueError('datos finitos, etiquetas binarias, alpha y tolerancia positivos y al menos una iteración')
    w=np.zeros(X.shape[1]); converged=False
    for iteration in range(max_iter):
        value,gradient,H=negative_log_posterior(w,X,y,alpha)
        if np.linalg.norm(gradient,np.inf)<tol:
            converged=True;break
        direction=np.linalg.solve(H,gradient)
        rate=1.
        while rate>1e-12:
            candidate=w-rate*direction
            if negative_log_posterior(candidate,X,y,alpha)[0]<=value-1e-4*rate*(gradient@direction):
                break
            rate*=.5
        if rate<=1e-12:break
        w=candidate
    value,gradient,H=negative_log_posterior(w,X,y,alpha)
    if np.linalg.norm(gradient,np.inf)<tol:converged=True
    cov=np.linalg.solve(H,np.eye(X.shape[1]))
    return w,cov,{'converged':converged,'iterations':iteration+1,
                  'gradient_inf':np.linalg.norm(gradient,np.inf),'objective':value}


def predict_probit(X, mean, covariance):
    X=np.asarray(X,dtype=float)
    variance=np.einsum('ij,jk,ik->i',X,covariance,X)
    return expit((X@mean)/np.sqrt(1+np.pi*np.maximum(variance,0)/8))


def synthetic_data(seed=2026,n_train=40,n_test=2000):
    """Datos sintéticos Bernoulli, partición de test independiente en el mismo generador."""
    rng=np.random.default_rng(seed)
    true_w=np.array([-.4,1.4,-1.])
    def generate(n):
        X=np.column_stack((np.ones(n),rng.normal(size=(n,2))))
        y=rng.binomial(1,expit(X@true_w))
        return X,y
    X,y=generate(n_train);X_test,y_test=generate(n_test)
    return X,y,X_test,y_test,true_w
import numpy as np
import pymc as pm
import arviz as az
X,y,_,_,_=synthetic_data()
with pm.Model() as model:
    w=pm.Normal('w',mu=0,sigma=1/np.sqrt(1.5),shape=X.shape[1])
    pm.Bernoulli('y',logit_p=pm.math.dot(X,w),observed=y)
    fit=pm.sample(draws=500,tune=300,chains=4,cores=1,random_seed=[123,124,125,126],target_accept=.8,progressbar=False)
print('PyMC',pm.__version__,'ArviZ',az.__version__)
print('mean',fit['posterior']['w'].values.mean(axis=(0,1)))
print('divergences',int(fit['sample_stats']['diverging'].values.sum()))
print('tree depth max',int(fit['sample_stats']['tree_depth'].values.max()))
print('E-BFMI',az.bfmi(fit))
print('rank Rhat',az.rhat(fit,method='rank')['w'].values)
print('bulk ESS',az.ess(fit,method='bulk')['w'].values)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

NumericOne leapfrog step
For H=(q2+p2)/2H=(q^2+p^2)/2, start at (q,p)=(1,0)(q,p)=(1,0) and apply one leapfrog step with ϵ=0.5\epsilon=0.5. What is ΔH=H1−H0\Delta H=H_1-H_0?
QuizRefreshing momentum
What does resampling momentum between HMC trajectories provide?
QuizFixed step in SGLD
What can happen with fixed-step SGLD without Metropolis correction?
ProofLeapfrog volume and reversibility
Prove: Leapfrog preserves volume and is inverted by reversing momentum and repeating the step.
0
Consider identity mass and a differentiable potential function.

Step 1 of 3. What determinant does each momentum half-step have?

ProofHMC invariance
Prove: The corrected HMC step preserves the joint proportional to e−H(q,p)e^{-H(q,p)}.
0
Assume reversible unit-volume leapfrog and refresh pp from its Gaussian conditional.

Step 1 of 3. Which transformation is proposed?

CodeImplement leapfrog
Implement leapfrog(grad_logp, q, p, eps, L) with identity mass and L at least 1. Return copies (q_nueva, p_nuevo) without modifying inputs. grad_logp(q) returns the log-density gradient.
def leapfrog(grad_logp, q, p, eps, L):
  pass
Shift+Enter to run

Summary

Key idea
HMC combines gradient-informed trajectories with MH correction; geometry and diagnostics determine whether those trajectories explore the posterior well.
  • Leapfrog is reversible and preserves volume, though its energy has error.
  • NUTS adapts length with a tree and turning criterion; divergences and E-BFMI help detect problematic geometries.
  • MALA corrects its asymmetric proposal; fixed-step SGLD without correction may be biased.

Main sources: Neal, HMC; Hoffman and Gelman, NUTS; Betancourt, geometry and diagnostics.