Tutorials › Nonlinear Mixed-Effects Models (NLME) › Computing Gradients Through NLME Models

Bayesian NLME with MCMC · Tutorial 244 of 797

Computing Gradients Through NLME Models

Compare gradient methods for nonlinear NLME predictions and learn how to check their reliability around dose events and numerical ODE solutions.

Advanced 12 min read

What You'll Learn

  • Trace how NLME prediction derivatives contribute to an HMC log-posterior gradient.
  • Derive and solve forward sensitivity equations for an ODE prediction.
  • Compare automatic differentiation, sensitivity equations, and finite differences.
  • Account for gradients through fixed and parameter-dependent dose events.
  • Diagnose gradient errors caused by finite-difference step sizes and ODE tolerances.
  • Validate computed gradients with directional checks and tolerance refinement.

Why Gradients Through NLME Predictions Need Care

Hamiltonian Monte Carlo uses derivatives of the log posterior to guide its simulated motion through parameter space. In an NLME model, that log posterior depends on predictions that may involve nonlinear transformations, individual random effects, and numerical solutions of differential equations. A gradient error in any of these components can therefore affect the proposed trajectory. The goal is not merely to obtain a derivative, but to understand which derivative is being computed and whether it accurately represents the model.

Write \(q\) for the unconstrained computational parameters used by the sampler. These may include transformed population parameters and random effects. For individual \(i\), let \(\eta_i\) denote their random effects, let \(x_i(t)\) be the model state, and let \(\widehat y_i(t)\) be the predicted observation. Between events, a common model structure is

$$ \frac{d x_i(t)}{dt}=f\bigl(t,x_i(t),q,\eta_i\bigr), \qquad \widehat y_i(t)=g\bigl(t,x_i(t),q,\eta_i\bigr). $$

The posterior log density, denoted here by \(\ell(q)\), combines the log likelihood and log prior, including any parameter-transformation terms required by the chosen coordinates. Its gradient includes derivatives through every prediction that depends on \(q\). Differentiating the likelihood while treating a parameter-dependent prediction as fixed would omit part of the gradient.

Definition: A gradient through an NLME model is the vector of derivatives of a model quantity, such as \(\widehat y_i(t)\) or \(\ell(q)\), with respect to the selected computational parameters. It includes the chain of dependence through parameter transformations, random effects, ODE states, event updates, and the observation model.

Three Ways to Compute the Derivative

The three approaches considered here differ in how they represent the calculation that leads from parameters to predictions.

  • Automatic differentiation (AD) applies derivative rules to the operations in a computer program. It computes derivatives of the implemented calculation, subject to the program’s operations and numerical solver. Forward-mode AD is often useful for a small number of inputs; reverse-mode AD can be efficient when there are many parameters and a scalar output, such as a log posterior.
  • Sensitivity equations augment the ODE with equations for derivatives of its state with respect to parameters. They directly represent how a continuous model solution changes as parameters change.
  • Finite differences approximate a derivative by evaluating the prediction at nearby parameter values. They require no derivative code, but their accuracy depends on the perturbation size and the accuracy of each prediction.

None is automatically reliable in every implementation. AD may differentiate solver steps or event-handling code in ways that do not match the intended continuous model. Sensitivity equations require correct derivatives of the ODE and event rules. Finite differences balance approximation error against numerical error in the predictions.

Worked Example: Differentiating a One-Compartment Prediction

Consider a hypothetical bolus prediction \(C(t)=D V^{-1}\exp(-kt)\), with dose \(D=100\) mg, volume \(V=20\) L, elimination rate \(k=0.10\) h\(^{-1}\), and time \(t=5\) h. Use unconstrained coordinates \(q_V=\log V\) and \(q_k=\log k\). The prediction is

$$ C= \frac{100\ \mathrm{mg}}{20\ \mathrm{L}}\exp[-(0.10\ \mathrm{h}^{-1})(5\ \mathrm{h})] =5\exp(-0.5)=3.033\ \mathrm{mg/L}. $$

Since \(V=\exp(q_V)\) and \(k=\exp(q_k)\), differentiating with respect to these coordinates gives

$$ \frac{\partial C}{\partial q_V}=-C=-3.033\ \mathrm{mg/L}, \qquad \frac{\partial C}{\partial q_k}=-ktC =-(0.10)(5)(3.033)=-1.516\ \mathrm{mg/L}. $$

For comparison, a central finite difference with step \(h=0.001\) for \(q_k\) is

$$ \frac{C(q_k+h)-C(q_k-h)}{2h} \approx \frac{3.03114-3.03417}{0.002} =-1.515\ \mathrm{mg/L}. $$

The small difference from \(-1.516\) is consistent with finite-difference approximation and rounding. This calculation also illustrates why the differentiation coordinate matters: the derivative with respect to \(q_k=\log k\) is \(k\) times the derivative with respect to \(k\).

Sensitivity Equations and Their Derivation

For an ODE state \(x(t)\) governed by \(x'=f(t,x,\theta)\), define the sensitivity matrix \(S(t)=\partial x(t)/\partial\theta\), where \(\theta\) is a vector of model parameters. Differentiating the ODE with respect to \(\theta\), using the chain rule, yields

$$ \frac{dS}{dt} = \frac{\partial f}{\partial x}S + \frac{\partial f}{\partial \theta}. $$

The initial condition is \(S(t_0)=\partial x(t_0)/\partial\theta\). If the initial state does not depend on \(\theta\), this sensitivity is zero. For an observation prediction \(g(t,x,\theta)\), the derivative is

$$ \frac{\partial g}{\partial\theta} = \frac{\partial g}{\partial x}S + \frac{\partial g}{\partial\theta}\bigg|_{x}. $$

The final term is the direct dependence of the observation function on the parameter while holding the state fixed. These equations follow because a small parameter change affects the prediction both by changing the state trajectory and, potentially, by changing the observation function directly.

For example, if \(x'=-kx\), then \(f_x=-k\) and \(f_k=-x\). The sensitivity \(s=\partial x/\partial k\) therefore satisfies \(s'=-ks-x\), not merely \(s'=-ks\). The additional term accounts for the direct appearance of \(k\) in the ODE.

Worked Example: Solving a Sensitivity Equation

Suppose a hypothetical state follows \(x'=-kx\), with \(x(0)=10\) units and \(k=0.20\) h\(^{-1}\). The analytic state is \(x(t)=10\exp(-kt)\). Because the initial value is fixed, \(s(0)=\partial x(0)/\partial k=0\), and the sensitivity equation is \(s'=-ks-x\).

Differentiating the analytic state gives \(s(t)=-t\,10\exp(-kt)=-t x(t)\). At \(t=3\) h,

$$ x(3)=10\exp[-(0.20)(3)]=5.488\ \mathrm{units}, \qquad s(3)=-(3\ \mathrm{h})(5.488\ \mathrm{units}) =-16.46\ \mathrm{units\ per\ h^{-1}}. $$

The units express change in state per change in the rate parameter. For a numerical ODE model, solving the state and sensitivity equations together provides the corresponding prediction derivative, subject to the solver’s numerical accuracy.

What Changes at a Dose Event?

A dose or other discrete intervention changes the state through an event rule. Write \(x^-\) for the state immediately before an event and \(x^+\) for the state immediately after it. For a parameter-dependent update \(x^+=R(x^-,\theta)\) at a fixed, known event time, the sensitivity update is

$$ S^+=R_x S^-+R_\theta. $$

Here \(R_x\) and \(R_\theta\) are derivatives of the event rule with respect to the pre-event state and parameters. For a bolus added to a state, \(R(x,D)=x+D\), so the sensitivity with respect to the dose increases by one across the event. If an event time \(\tau\) depends on a parameter, its movement also affects the state; for a smooth ODE on both sides of the event, the update at a fixed time after the event includes the term \((R_x f^- - f^+)\,\partial\tau/\partial\theta\). Omitting this term can give an incorrect derivative.

An observation exactly at an event also requires a defined convention: it may use the pre-event or post-event state. A prediction can jump at the event, so a derivative across the jump is not interchangeable with a derivative on either smooth segment.

Worked Example: Differentiating a Parameter-Dependent Dose Time

Suppose a hypothetical amount receives a bolus \(D=50\) mg at time \(\tau\), then decays according to \(x'=-kx\), with \(k=0.10\) h\(^{-1}\). At \(t=8\) h, let \(\tau=3\) h. There is no amount before the dose, so the post-dose prediction is \(x(t)=D\exp[-k(t-\tau)]\).

The prediction and its derivative with respect to event time are

$$ x(8)=50\exp[-(0.10)(8-3)]=30.33\ \mathrm{mg}, \qquad \frac{\partial x(8)}{\partial\tau} =kx(8)=(0.10)(30.33)=3.033\ \mathrm{mg/h}. $$

A later dose time leaves less time for elimination, so the positive derivative has the expected sign. The event-time derivative is not obtained by differentiating only the post-dose decay rate; it accounts for the change in the duration \(t-\tau\).

Finite Differences, Tolerances, and Practical Checks

For a scalar prediction \(F(\theta)\), the central finite-difference approximation is \([F(\theta+h)-F(\theta-h)]/(2h)\). For a smooth function its truncation error is typically proportional to \(h^2\), but very small \(h\) makes the subtraction vulnerable to rounding and prediction error. In an ODE model, solver error can dominate the difference when the two predictions are nearly equal. Thus, reducing \(h\) indefinitely does not guarantee a better derivative.

ODE solver tolerances control the numerical accuracy of the state solution, not automatically the accuracy of its gradient. A useful check is to tighten tolerances and see whether predictions and gradients stabilize to the precision needed for the calculation. For finite differences, compare several sensible step sizes; for AD or sensitivity equations, compare a directional derivative with an independently computed finite difference. A directional check uses a vector \(v\) and compares \(\nabla F(\theta)^\mathsf{T}v\) with \([F(\theta+hv)-F(\theta-hv)]/(2h)\).

1
Check the model path.
Confirm that predictions use the intended parameter coordinates, random effects, event ordering, and pre-event or post-event observation convention.
2
Check numerical stability.
Repeat the gradient calculation with tighter ODE tolerances and, for finite differences, a small range of step sizes. Large changes indicate that the derivative is not yet numerically stable.
3
Check a direction independently.
Compare the reported gradient projected onto a test direction with a finite-difference change in the full prediction or log posterior. Test away from event discontinuities as well as near relevant events.

AD has the advantage of applying chain rules systematically through supported operations, but a solver may contain adaptive step decisions or event branches that make its computed derivative noisy or only locally representative of the implemented algorithm. Sensitivity equations expose the continuous derivative structure and can be efficient when there are relatively few parameters, but coding all parameter and event derivatives is demanding. Finite differences are easy to implement and useful as a check, but can be expensive and sensitive to step size, solver tolerances, and discontinuities. When an event time, event order, or conditional branch changes with parameters, the prediction may fail to be smoothly differentiable there; no gradient method can make a genuinely discontinuous target smooth.

Common Pitfall and Limitations

A common mistake is to interpret a stable-looking AD gradient as proof that the continuous NLME model has been differentiated correctly. AD differentiates the operations it is given. If the event update is missing, the observation is assigned to the wrong side of a dose, or a parameter transform is omitted, AD can return a precise gradient for the wrong calculation. Conversely, disagreement between AD and finite differences near an event does not by itself prove which result is wrong: the finite-difference perturbation may cross an event boundary, or the solver error may be too large relative to the prediction change.

Gradient checks are most informative when the compared methods use the same model definition, parameter coordinates, and event conventions. They establish numerical consistency at tested points, not correctness everywhere. Gradients can be particularly difficult near state constraints, parameter-dependent event ordering, or sharp nonlinear transitions. In those settings, inspect predictions and event logic in addition to numerical derivative values.

Key takeaway: A trustworthy gradient requires both a suitable derivative method and a correct, numerically stable prediction calculation. Verify parameter transformations and event rules, refine ODE tolerances, and compare methods or directional derivatives at representative parameter values.

Check Your Understanding

Answer each question, then compare with the solutions below.

  1. For \(x'=-kx\), state the sensitivity equation for \(s=\partial x/\partial k\), and identify the term that represents direct dependence on \(k\).
  2. A state receives a fixed-time additive dose \(D\), so \(x^+=x^-+D\). What is the sensitivity update with respect to \(D\), assuming the pre-event state does not depend on \(D\)?
  3. Why can making a finite-difference step extremely small worsen a gradient estimate from an ODE model?
  4. For \(x(t)=D\exp[-k(t-\tau)]\), what is the sign of the derivative with respect to \(\tau\), and what does that sign mean?

Solutions. (1) \(s'=-ks-x\), with \(s(0)=\partial x(0)/\partial k\). The term \(-x\) is the direct derivative \(f_k\). (2) Since \(x^+=x^-+D\), \(\partial x^+/\partial D=\partial x^-/\partial D+1=1\) under the stated assumption. (3) The two predictions become very close, so rounding and ODE solution error can dominate their difference; the resulting quotient can become noisy. (4) Differentiation gives \(\partial x/\partial\tau=kx\), which is positive when \(k>0\) and \(x>0\): delaying the dose shortens the elimination period and increases the amount remaining at \(t\).