Why Use Hamiltonian Monte Carlo?
A posterior distribution for a nonlinear mixed-effects model (NLME) can involve both population parameters and many individual random effects. A random-walk proposal typically changes these quantities only a little at a time: large changes are often rejected, while small changes can take many iterations to explore the posterior. Hamiltonian Monte Carlo (HMC) uses the posterior’s gradient to guide a proposal across the parameter space, rather than choosing its direction through an unguided random perturbation.
The central idea is to augment the parameter vector with an auxiliary momentum variable. The posterior supplies a potential energy, and the momentum supplies kinetic energy. Hamiltonian dynamics then move through regions of the parameter space according to the gradient of the potential. Exact dynamics preserve the target distribution; a Metropolis correction accommodates the energy error from numerical integration. The posterior geometry discussed in Posterior Geometry in Hierarchical Models helps explain why guided movement can be useful, but HMC still depends on appropriate parameterization and reliable computation of gradients.
Posterior, Potential Energy, and Momentum
Let \(y\) denote the observed data and let \(q\) be a vector containing all continuous unknowns to be sampled. In an NLME model, \(q\) may include population parameters, transformed standard deviations and correlations, and individual random effects. Write the posterior density in these coordinates as \(\pi(q\mid y)\). If a constrained parameter has been transformed to an unconstrained coordinate, its transformation Jacobian must be included in this density.
The momentum distribution is a computational device, not an additional scientific parameter in the NLME model. Because \(p\sim N(0,M)\), its density is proportional to \(\exp[-K(p)]\). The joint density for the augmented state is therefore proportional to
Marginalizing over momentum returns the desired posterior for \(q\). For the standard construction, momentum is refreshed independently at the start of each trajectory, which avoids carrying a persistent direction indefinitely through the chain.
HMC requires a proper posterior target for the intended inference and a differentiable potential \(U(q)\) in the coordinates being sampled, with gradients available where the chain moves. In practice, a smooth likelihood and priors usually provide this, but hard parameter boundaries, discrete unknowns, or nondifferentiable model operations can prevent straightforward use. The mass matrix must be positive definite so the kinetic energy is well defined. All relevant normalizing constants may be omitted from \(U\) if they do not depend on \(q\).
How Gradients Guide the Trajectory
Hamilton’s equations specify how position and momentum change with an artificial time variable \(t\):
The first equation moves the parameter vector in the direction indicated by momentum. The second changes momentum according to the negative posterior-potential gradient. Since lower \(U(q)\) means higher posterior density, this force tends to accelerate the trajectory toward higher-density regions; momentum can then carry it through and beyond a local high-density area. The result can be a distant proposal that remains in a plausible region, rather than a short random displacement.
A short justification shows why this construction targets the posterior. For exact Hamiltonian evolution, the rate of change in total energy is
Thus exact evolution preserves \(H\), and hence the joint density proportional to \(\exp(-H)\). Hamiltonian flow also preserves volume in the joint \((q,p)\) space. Together, these properties mean exact flow preserves the augmented target distribution. In computation, however, the trajectory is approximated numerically, so energy is generally not preserved exactly. HMC corrects for this discrepancy with a Metropolis step.
Worked Example: A Gradient in a Simplified NLME Observation Model
Suppose one hypothetical positive response is modeled as \(f(\theta,b)=\exp(\theta+b)\), where \(\theta\) is a population-level log-scale parameter and \(b\) is an individual random effect. The observed response is \(y=8\), with Gaussian residual standard deviation \(\sigma=2\). For this calculation, suppose the priors are \(\theta\sim N(\log 10,0.5^2)\) and \(b\sim N(0,0.3^2)\), independently. Calculate the gradient of the negative log posterior at \((\theta,b)=(\log 10,0)\), omitting constants independent of these coordinates.
The observation model has prediction \(f=\exp(\theta+b)\). Its negative log-likelihood contribution is \((y-f)^2/(2\sigma^2)\). Differentiating with respect to either \(\theta\) or \(b\), using \(\partial f/\partial\theta=\partial f/\partial b=f\), gives
At the stated point, \(f=\exp(\log 10+0)=10\), so each likelihood derivative is \((10-8)(10)/2^2=20/4=5\). The prior derivative for \(\theta\) is \((\theta-\log 10)/0.5^2=0/0.25=0\). The prior derivative for \(b\) is \(b/0.3^2=0/0.09=0\). Therefore, the full gradient is \(\nabla U(\log 10,0)=(5,5)\). The calculation illustrates how both the likelihood and priors contribute to the force used by HMC.
The Metropolis Correction
A practical HMC iteration first draws momentum \(p\sim N(0,M)\), then numerically integrates the Hamiltonian equations for a chosen duration to obtain a proposed endpoint. Denote the starting state by \((q,p)\) and the endpoint, after reversing its momentum for the acceptance calculation, by \((q',p')\). For a reversible, volume-preserving numerical proposal, the Metropolis acceptance probability is
The correction follows from the Metropolis-Hastings ratio. The augmented target density at a state is proportional to \(\exp[-H]\). Reversibility and volume preservation make the proposal-density and Jacobian factors cancel in the ratio, leaving \(\exp[-H(q',p')]/\exp[-H(q,p)]\). If the proposed state is accepted, the chain moves to \(q'\); otherwise it remains at \(q\). The momentum is an auxiliary variable and is refreshed for the next trajectory.
When the evolution is exact, \(H(q',p')=H(q,p)\), so the acceptance probability is one. With numerical integration, a proposed endpoint with higher energy is accepted with probability \(\exp[-\Delta H]\), where \(\Delta H=H(q',p')-H(q,p)\); a lower-energy endpoint is accepted with probability one. This correction preserves the intended target even when the numerical trajectory has some energy error. It does not, by itself, guarantee that the chain has explored all relevant posterior regions.
Worked Example: Computing an HMC Acceptance Probability
Consider a hypothetical two-dimensional posterior in coordinates \(q=(q_1,q_2)\) with a centered Gaussian shape and covariance matrix
This is a simplified example of correlated posterior coordinates, such as a population parameter and a random effect. Since \(\det(\Sigma)=1-0.8^2=0.36\),
Use \(M=I\). Suppose a numerical trajectory starts at \(q=(1,1)\), \(p=(0.4,-0.2)\), and proposes \(q'=(0.8,1.2)\), \(p'=(-0.2,0.3)\), with the endpoint momentum already reversed for the acceptance calculation. At the initial point, \(q^{\mathsf T}\Sigma^{-1}q=2.7778(1+1)-4.4444(1)=1.1112\), so \(U(q)\approx0.5556\). Also \(K(p)=\frac12(0.4^2+(-0.2)^2)=0.10\), giving \(H(q,p)\approx0.6556\).
At the proposed point, \(q'^{\mathsf T}\Sigma^{-1}q'=2.7778(0.8^2+1.2^2)-4.4444(0.8)(1.2)\approx1.5112\), so \(U(q')\approx0.7556\). Its kinetic energy is \(K(p')=\frac12((-0.2)^2+0.3^2)=0.065\). Thus \(H(q',p')\approx0.8206\), \(\Delta H\approx0.1650\), and
The proposal is accepted with probability about 0.848. For example, a uniform draw of 0.70 would accept it, whereas a draw of 0.90 would reject it. These hypothetical endpoint values illustrate the correction calculation; they do not assert that any particular integration settings produce that trajectory.
Assumptions, Diagnostics, and Alternatives
HMC is most useful when the target is continuous, differentiable, and has gradients that can be evaluated accurately. The model’s likelihood, priors, and any parameter transformations must all be represented in the log posterior used by the sampler. An omitted prior term or transformation Jacobian changes the target, and a wrong gradient can direct trajectories incorrectly even if the acceptance calculation itself is implemented correctly.
A high acceptance rate alone does not establish that HMC is working well. If proposals move only tiny distances, many may be accepted while the chain still explores the posterior slowly. Conversely, frequent rejections or unstable trajectories can indicate that numerical energy errors are too large. Inspect trace plots and other chain diagnostics, and consider whether sampled parameters move meaningfully through the posterior. HMC can also have difficulty in strongly correlated or badly scaled coordinates, and its numerical trajectories can behave poorly near sharp curvature or constrained boundaries. Those problems may call for a different parameterization or numerical settings, rather than a more forceful interpretation of the output.
Compared with random-walk Metropolis, HMC uses gradients to orient longer proposals and is often more efficient for smooth, continuous, moderately high-dimensional targets. Random-walk Metropolis does not require gradients and can handle some targets for which HMC is unsuitable, but often advances through correlated regions more slowly. Gibbs sampling can be attractive when full conditional distributions are available in forms that are easy to sample; it is not a general substitute when NLME posterior conditionals are difficult to draw from. HMC’s own limitations matter: it does not directly sample discrete unknowns, requires differentiable computations, and still needs adequate exploration and convergence assessment.
Worked Example: Interpreting a Rejection Correctly
In a hypothetical HMC iteration, suppose the current Hamiltonian is \(H=12.40\) and the proposed Hamiltonian is \(H'=13.20\). The energy change is \(\Delta H=13.20-12.40=0.80\), so the acceptance probability is \(\exp(-0.80)\approx0.4493\). If the uniform acceptance draw is 0.60, the proposal is rejected because \(0.60>0.4493\), and the position remains at its current value for this iteration.
This one rejection does not mean the proposed parameter value is impossible or that the posterior probability of the current value is 0.60. The draw is part of the algorithm’s random acceptance rule, and the acceptance probability compares the proposed and current augmented states through their Hamiltonians. Rejection is a normal part of preserving the target distribution when numerical integration changes energy.
Common Pitfalls and Practical Limits
- Assuming gradients alone preserve the posterior. Gradients guide the trajectory, but approximate integration can change energy. The Metropolis correction is what adjusts for that numerical error.
- Ignoring transformations. If a constrained parameter is represented on an unconstrained scale, the transformed posterior must include the corresponding Jacobian contribution.
- Treating high acceptance as proof of good mixing. Acceptance must be considered alongside the distance moved and evidence that the chain explores the posterior.
- Assuming HMC is appropriate for every parameter. Discrete variables and nondifferentiable operations are not directly handled by standard HMC.
The practical benefit of HMC is not simply that it uses a sophisticated proposal. It is that posterior gradients can turn information about local shape into directed movement while the Metropolis correction retains the specified posterior as the target. That benefit depends on correctly specified densities, reliable gradients, and trajectories that explore the relevant regions.
Check Your Understanding
Answer each question, then compare your reasoning with the solutions.
- If \(U(q)=-\log\pi(q\mid y)\), which direction does the force \(-\nabla U(q)\) point relative to increasing posterior density?
- For \(M=I\) and momentum \(p=(0.6,0.8)\), calculate the kinetic energy.
- If a proposal has \(\Delta H=-0.25\), what is its Metropolis acceptance probability?
- Name two conditions that can make standard HMC unsuitable or unreliable for an NLME posterior.
Solutions. (1) The force points in the direction of decreasing \(U\), which is the direction of increasing posterior density, since \(U=-\log\pi\). (2) \(K=\frac12(0.6^2+0.8^2)=\frac12(0.36+0.64)=0.50\). (3) \(a=\min(1,\exp[-(-0.25)])=\min(1,\exp[0.25])=1\), so the proposal is accepted. (4) Examples include discrete unknowns, nondifferentiable model calculations, inaccurate gradients, and severe scaling or curvature that destabilizes numerical trajectories.