Tutorials › Quantitative Systems Pharmacology (QSP) › Hamiltonian Monte Carlo With ODE Likelihoods

Bayesian Calibration and Uncertainty Quantification · Tutorial 645 of 799

Hamiltonian Monte Carlo With ODE Likelihoods

See how to construct and check gradient-based Hamiltonian Monte Carlo proposals for Bayesian calibration with an ODE-based likelihood.

Advanced 13 min read

What You'll Learn

  • Define the log-posterior gradient needed for Hamiltonian Monte Carlo in an ODE calibration.
  • Differentiate a Gaussian observation likelihood through an ODE model.
  • Follow a leapfrog step from a parameter and momentum to a proposed state.
  • Explain the energy-based Metropolis correction and why it is needed.
  • Check gradients numerically and identify solver or parameterization problems.
  • Compare Hamiltonian proposals with random-walk and blocked Metropolis proposals.

Why Use Gradients in ODE Calibration?

Bayesian calibration of a QSP model can produce a posterior distribution with strong parameter dependence and narrow, curved regions of high probability. A random-walk proposal may move only a short distance before it leaves such a region, or it may propose large numbers of low-probability states. Hamiltonian Monte Carlo (HMC) uses the direction of the log-posterior gradient to construct longer, informed proposals. In an ODE calibration, that gradient must account for how parameters change the model trajectory and therefore the predicted observations.

HMC does not remove the need to define a suitable likelihood, prior, or parameter scale. It is a sampling method for a specified posterior, and its gradient calculations must accurately represent that posterior. The likelihood construction and prior choices are part of the model; here the focus is how their combined log density guides HMC.

Definition: Let \(q\) denote the vector of unconstrained parameters used for sampling, and let \(\ell(q)\) be the log posterior density, up to an additive constant. The log-posterior gradient is \(\nabla_q\ell(q)\), the vector of partial derivatives of \(\ell\) with respect to the components of \(q\). HMC augments \(q\) with a momentum vector \(p\), assigns that momentum a specified probability distribution, and uses approximate Hamiltonian dynamics to propose a new \(q\).

From an ODE to a Log-Posterior Gradient

Suppose the mechanistic state \(x(t)\) satisfies \(dx/dt=f(x(t),q,t)\), with a specified initial condition. At observation time \(t_i\), the model predicts \(m_i(q)=h(x(t_i),q)\). For independent Gaussian observations \(y_i\) with known standard deviations \(\sigma_i\), the log-likelihood, omitting constants that do not depend on \(q\), is

$$ \log L(q)=-\frac{1}{2}\sum_i \frac{(y_i-m_i(q))^2}{\sigma_i^2}. $$

For one observation, differentiation by the chain rule gives

$$ \nabla_q \log L(q) = \frac{y-m(q)}{\sigma^2}\nabla_q m(q). $$

Thus, the gradient combines the observation residual, its uncertainty, and the sensitivity of the predicted observation to the parameters. If \(q\) has prior density \(p(q)\), then \(\ell(q)=\log L(q)+\log p(q)\), again up to an additive constant, and \(\nabla_q\ell(q)=\nabla_q\log L(q)+\nabla_q\log p(q)\). If a transformation is used to represent a constrained parameter on an unconstrained scale, the appropriate transformed prior density includes its change-of-variables term.

ODE sensitivities can be computed by differentiating the state equations. For parameter \(q_j\), define \(S_j(t)=\partial x(t)/\partial q_j\). When the model is differentiable, this sensitivity satisfies

$$ \frac{dS_j}{dt} = \frac{\partial f}{\partial x}S_j + \frac{\partial f}{\partial q_j}, \qquad S_j(0)=\frac{\partial x(0)}{\partial q_j}. $$

The observation sensitivity follows by differentiating \(h(x(t_i),q)\). These equations explain where the likelihood gradient comes from; in practice, automatic differentiation, sensitivity equations, or adjoint calculations may be used. Whatever method is chosen, the resulting gradient must correspond to the same numerical model and log density used to evaluate \(\ell(q)\).

Worked Example: Differentiating a One-Parameter ODE Likelihood

Consider the hypothetical ODE \(dx/dt=-kx\), with \(x(0)=1\), where the positive rate is parameterized as \(k=\exp(q)\). There is one observation at \(t=1\): \(y=0.55\), with Gaussian observation standard deviation \(\sigma=0.10\). The model prediction is \(m(q)=\exp[-\exp(q)]\). Use a prior \(q\sim N(0,1)\), whose log-density kernel is \(-q^2/2\).

At \(q=-0.5108\), \(k=\exp(-0.5108)\approx0.6000\), so \(m(q)=\exp(-0.6000)\approx0.5488\). Differentiating the prediction gives

$$ \frac{dm}{dq}=-\exp(q)\exp[-\exp(q)]\approx-0.3293. $$

Using the displayed rounded prediction and derivative, the likelihood-gradient contribution is

$$ \frac{0.55-0.5488}{0.10^2}(-0.3293) = \frac{0.0012(-0.3293)}{0.01} \approx-0.0395. $$

Using unrounded ODE values gives a contribution of about \(-0.0394\). The prior-gradient contribution is \(-q=0.5108\), so the total log-posterior gradient is approximately \(0.4714\) using unrounded values (or \(0.4713\) using the rounded likelihood contribution). The positive total gradient means that, locally, increasing \(q\) increases the log posterior.

Hamiltonian Dynamics and the Leapfrog Proposal

HMC gives momentum \(p\) a multivariate normal distribution, commonly \(p\sim N(0,M)\), where \(M\) is a positive-definite mass matrix. Define the potential energy \(U(q)=-\ell(q)\) and kinetic energy \(K(p)=p^\mathsf{T}M^{-1}p/2\). The Hamiltonian, or total energy, is \(H(q,p)=U(q)+K(p)\). In exact continuous dynamics, the position and momentum evolve according to

$$ \frac{dq}{dt}=M^{-1}p, \qquad \frac{dp}{dt}=\nabla_q\ell(q). $$

The second equation shows how the log-posterior gradient changes the momentum. HMC cannot usually solve these dynamics exactly, so it uses the leapfrog integrator, which alternates half momentum updates with position updates. For step size \(\epsilon\), one step is

$$ p_{1/2}=p_0+\frac{\epsilon}{2}\nabla_q\ell(q_0),\qquad q_1=q_0+\epsilon M^{-1}p_{1/2},\qquad p_1=p_{1/2}+\frac{\epsilon}{2}\nabla_q\ell(q_1). $$

Repeating these steps produces a proposed endpoint. The method then applies a Metropolis correction: given initial and proposed states \((q_0,p_0)\) and \((q_1,p_1)\), the probability of accepting the proposal is

$$ \min\{1,\exp[H(q_0,p_0)-H(q_1,p_1)]\}. $$

Exact Hamiltonian dynamics conserve energy. Numerical leapfrog steps only approximate that property, so the correction compensates for their energy error. With a reversible, volume-preserving integrator and the momentum reversal used in the proposal construction, this correction preserves the target posterior. Rejected proposals leave the position at its current value. Momentum is refreshed for a subsequent trajectory.

Worked Example: Taking One Leapfrog Step

Continue the hypothetical calibration above, using \(M=1\), step size \(\epsilon=0.10\), initial position \(q_0=-0.5108\), and initial momentum \(p_0=0.4000\). The starting log-posterior gradient is approximately \(0.4714\).

The half-step momentum is \(p_{1/2}=0.4000+(0.10/2)(0.4714)=0.42357\). The position update is \(q_1=-0.5108+0.10(0.42357)=-0.46844\). At this position, the ODE gives \(m(q_1)\approx0.5348\) and \(dm/dq\approx-0.3348\). Therefore, the likelihood-gradient contribution is approximately \((0.55-0.5348)(-0.3348)/0.01=-0.509\). Adding the prior contribution \(-q_1=0.46844\) gives a new log-posterior gradient of about \(-0.04045\).

The final momentum update is \(p_1\approx0.42357+(0.10/2)(-0.04045)=0.42155\). The starting log-posterior kernel is approximately

$$ \ell(q_0) = -\frac{(-0.5108)^2}{2} -\frac{(0.55-0.5488)^2}{2(0.10)^2} \approx-0.1305. $$

Thus \(H(q_0,p_0)\approx0.1305+0.4000^2/2=0.2105\). At the endpoint, \(\ell(q_1)\approx-0.1213\), so \(H(q_1,p_1)\approx0.1213+0.42155^2/2=0.2102\). The small energy difference makes the acceptance probability \(\min\{1,\exp(0.2105-0.2102)\}=1\) at the shown precision. This single step illustrates the calculation; useful trajectories generally contain multiple steps.

Gradient Checks and Numerical Reliability

A gradient error can systematically steer HMC in the wrong direction, and an ODE solver can make an otherwise correct derivative numerically unreliable. A basic check compares an analytic or automatic gradient with a centered finite difference. For component \(j\), the latter is

$$ \frac{\partial\ell(q)}{\partial q_j} \approx \frac{\ell(q+h e_j)-\ell(q-h e_j)}{2h}, $$

where \(e_j\) is the unit vector in coordinate \(j\). The finite-difference step \(h\) should be large enough to avoid domination by numerical noise and small enough to approximate the local derivative. For ODE likelihoods, both evaluations must use sufficiently accurate and consistent solver settings.

Worked Example: Checking a Gradient by Finite Differences

For the one-parameter model, use \(\ell(q)=-q^2/2-\{0.55-\exp[-\exp(q)]\}^2/(2(0.10)^2)\), with constants omitted. At \(q_0=-0.5108\), the analytic derivative is approximately \(0.4714\), as calculated earlier. Evaluate the same log-kernel at \(q_0+h\) and \(q_0-h\), with \(h=0.001\); to the shown precision the values are about \(-0.13006\) and \(-0.13101\), respectively. Then

$$ \frac{-0.13006-(-0.13101)}{2(0.001)} \approx0.475. $$

These displayed log-kernel values are rounded too coarsely for a close numerical comparison. Using the unrounded evaluations gives a centered difference of approximately \(0.4714\), consistent with the analytic gradient. This is why gradient checks should retain adequate numerical precision rather than compare heavily rounded intermediate values.

Practical Diagnostics, Alternatives, and Limits

HMC performance depends on accurate gradients, a suitable parameter scale, and an integration step size that resolves the posterior geometry. A step size that is too large can produce substantial energy errors and frequent rejections. A step size that is extremely small may yield high acceptance but require many ODE solves to travel a useful distance. Poor scaling can make movement easy in one parameter direction and difficult in another. These symptoms should prompt checks of parameterization, gradient calculations, solver tolerances, and the mass matrix; acceptance alone does not establish that a chain explores the posterior well.

For correlated mechanistic parameters, a joint HMC trajectory can use gradient information to move through their dependence, unlike a simple coordinate-wise random walk. A random-walk Metropolis proposal is easier to implement and does not require derivatives, but may explore a narrow posterior inefficiently. Blocked Metropolis updates can respect parameter groupings, yet still rely on proposal distributions rather than gradients to choose directions. HMC is not automatically preferable: it can be difficult when the posterior is nonsmooth, gradients are unavailable or noisy, or ODE computations are too costly. It also does not guarantee that distinct posterior modes will be found.

A common mistake is to assume that a high acceptance rate proves HMC is working well. A very small step size can produce high acceptance while making only tiny moves; conversely, poor gradients can undermine exploration even when some proposals are accepted. Check gradient agreement and energy errors, and assess the sampled chain with appropriate convergence and efficiency diagnostics. Those checks answer different questions: numerical correctness of the proposal is not the same as adequate posterior exploration.

Key takeaway: HMC uses \(\nabla_q\ell(q)\) to guide momentum and position updates, while a Metropolis energy correction accounts for numerical integration error. In ODE calibration, reliable sampling depends on differentiating the entire path from parameters through the ODE solution to the observation likelihood.

Check Your Understanding

Answer each question, then compare with the solutions below.

  1. In the Gaussian observation model, what three ingredients determine the likelihood-gradient contribution for one observation?
  2. Why does HMC use a Metropolis correction after leapfrog integration?
  3. If a finite-difference gradient disagrees with an automatic gradient, name two checks that are especially relevant to ODE calibration.
  4. Why can a high HMC acceptance rate coexist with inefficient exploration?

Solutions. (1) The residual \(y-m(q)\), the observation variance \(\sigma^2\), and the prediction sensitivity \(\nabla_qm(q)\), combined as \((y-m(q))\nabla_qm(q)/\sigma^2\). (2) Leapfrog integration only approximates energy-conserving Hamiltonian dynamics; the correction accounts for the resulting energy difference and preserves the intended posterior under the stated reversibility and volume-preservation conditions. (3) Check that both methods differentiate the same log density, including prior and transformation terms; also examine solver tolerances and whether numerical integration noise is obscuring the finite difference. (4) A very small step size may yield high acceptance but tiny changes in position per trajectory, so many accepted proposals may still cover the posterior slowly.

Clinical Biostats