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
- 14Metropolis-Hastings algorithmDetailed balanceOptimal scaling of random-walk MetropolisMCMC effective sample sizeRank-normalized split R-hat
- 03Initial value problem for ODEs
- 09Symplectic integratorsExplicit and implicit Euler methodsRunge-Kutta methodsForward-mode automatic differentiationReverse-mode automatic differentiation
- 06Stochastic gradient descent
Using posterior geometry
A high-dimensional random walk may require small steps and explore slowly. Hamiltonian dynamics for sampling introduces auxiliary momentum and defines
The joint proportional to has the desired posterior as its marginal in . Equations and 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:
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.
In Hamiltonian Monte Carlo, resample , integrate steps, reverse momentum and accept with . 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 and matters: trajectories too short diffuse and long ones can retrace their steps.
Dual averaging tunes 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 and : 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.
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, and : when is very negative, variables narrow. One fixed step must resolve very different scales.
These runs were generated with seed 2323 and threshold 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 , ULA uses . 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.
"""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_wimport 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))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)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 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.
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))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.
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 , 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.
"""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)npm run lab and open the connection link.Exercises
Step 1 of 3. What determinant does each momentum half-step have?
Step 1 of 3. Which transformation is proposed?
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):
passSummary
- 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.