Tutorials › Pharmacometric Workflows and Reproducible Modeling › Analytic and Finite-Difference Gradients

Initial Estimates and Estimation Settings · Tutorial 112 of 399

Analytic and Finite-Difference Gradients

Learn how analytic and finite-difference gradients are computed, what they cost, and how to recognize errors caused by curvature, numerical noise, or implementation.

Advanced 10 min read

What You'll Learn

  • Define the gradient of a negative log-likelihood objective and relate it to likelihood maximization.
  • Distinguish analytic derivatives from forward and central finite differences.
  • Derive the smoothness conditions that support the usual finite-difference error orders.
  • Compare gradient-evaluation costs as the number of estimated parameters grows.
  • Identify how integration error, Monte Carlo variability, and inner-solver tolerances affect gradient reliability.
  • Check gradient calculations with fully worked likelihood-objective examples.

Why Gradient Computation Matters

An optimizer uses a gradient to determine how an objective changes when model parameters move. In nonlinear mixed-effects estimation, that objective may require substantial computation: evaluating a likelihood can involve integrating over random effects, locating conditional modes, or using a numerical approximation. A gradient method can therefore spend much of its time not in the parameter-update rule, but in repeatedly evaluating or differentiating that objective.

This tutorial compares two ways to obtain the gradient: differentiating the objective analytically, and approximating its derivatives by finite differences. The comparison concerns both computational cost and reliability. A derivative formula may be exact on paper but difficult to implement correctly through an integral or iterative inner calculation. A finite difference is easy to define, but it can be inaccurate when objective evaluations are noisy or when the perturbation is poorly scaled.

Objective and Gradient Definitions

Definition: Let \(\boldsymbol\theta=(\theta_1,\ldots,\theta_p)\) denote the vector of estimated parameters, and let \(Q(\boldsymbol\theta)\) be a differentiable objective to be minimized, such as a negative log-likelihood or a negative log-likelihood approximation. Its gradient is \(\nabla Q(\boldsymbol\theta)=(\partial Q/\partial\theta_1,\ldots,\partial Q/\partial\theta_p)^\mathsf{T}\). The \(j\)th component describes the local rate of change in \(Q\) per unit change in \(\theta_j\), with the other coordinates held fixed.

If the estimation target is a log-likelihood \(\ell(\boldsymbol\theta)\) to be maximized, one can instead minimize \(Q(\boldsymbol\theta)=-\ell(\boldsymbol\theta)\). The gradient then has the opposite sign: \(\nabla Q=-\nabla\ell\). This tutorial uses the minimization convention. A gradient is a local quantity; a small gradient alone does not establish that the objective has a well-behaved minimum or that the statistical model is adequate.

An analytic gradient is obtained by differentiating the stated objective using calculus and implementing the resulting derivatives. “Analytic” does not necessarily mean a short closed-form expression: derivatives can be evaluated by automatic differentiation or by carefully implemented derivative recursions. A finite-difference gradient approximates each partial derivative using changes in objective values at perturbed parameter vectors.

Finite-Difference Formulas and Their Error

Let \(\mathbf e_j\) be the vector whose \(j\)th entry is one and whose other entries are zero. For a nonzero perturbation \(h\), the forward difference for coordinate \(j\) is

$$ D_j^{\mathrm{F}}Q(\boldsymbol\theta;h) = \frac{Q(\boldsymbol\theta+h\mathbf e_j)-Q(\boldsymbol\theta)}{h}. $$

The central difference uses objective values on both sides:

$$ D_j^{\mathrm{C}}Q(\boldsymbol\theta;h) = \frac{Q(\boldsymbol\theta+h\mathbf e_j)-Q(\boldsymbol\theta-h\mathbf e_j)}{2h}. $$

The formulas approximate \(\partial Q/\partial\theta_j\), not the whole gradient at once. Repeating the calculation for all \(p\) coordinates gives an approximate gradient vector. The forward formula can reuse the unperturbed objective value; the central formula uses two perturbed evaluations per coordinate.

Justification: Suppose the one-coordinate function \(q(t)=Q(\boldsymbol\theta+t\mathbf e_j)\) has a bounded second derivative near zero. Taylor expansion gives \(q(h)=q(0)+hq'(0)+O(h^2)\), so \([q(h)-q(0)]/h=q'(0)+O(h)\). Thus the forward difference has first-order truncation error. If \(q\) has a continuous third derivative near zero, Taylor expansion gives \(q(\pm h)=q(0)\pm hq'(0)+\frac{h^2}{2}q''(0)\pm\frac{h^3}{6}q'''(0)+O(h^4)\) when the fourth derivative is bounded; more generally, continuity of the third derivative gives a remainder \(o(h^3)\) after the cubic term. Subtracting the two expansions and dividing by \(2h\) cancels the even-power terms and yields \(D_j^{\mathrm{C}}=q'(0)+\frac{h^2}{6}q'''(0)+o(h^2)\). In particular, the central difference has \(O(h^2)\) error under these smoothness conditions. Continuous second derivatives alone do not justify a cubic-order Taylor remainder or that central-difference error order.

These are truncation-error statements: they describe how the formulas behave when objective values can be evaluated exactly and \(h\) is small. In computation, making \(h\) smaller also makes the numerator a difference between increasingly similar numbers. Rounding, approximate integration, stochastic evaluation, and incomplete convergence of an inner solver can then dominate. The displayed orders do not promise that reducing \(h\) always improves an implemented gradient.

Worked Example: Forward and Central Differences for a Likelihood Objective

Worked Example: Forward and Central Differences for a Likelihood Objective

Suppose a hypothetical model has independent observations \(y=(1,2,3)\) from a normal distribution with unknown mean \(\mu\) and known standard deviation \(1\). Ignoring constants that do not depend on \(\mu\), the negative log-likelihood is \(Q(\mu)=\frac12\sum_{i=1}^3(y_i-\mu)^2\). Compute the gradient at \(\mu=1.5\) analytically and by finite differences with \(h=0.1\).

Analytic result. Differentiation gives \(Q'(\mu)=\sum_{i=1}^3(\mu-y_i)=3\mu-6\). Therefore \(Q'(1.5)=4.5-6=-1.5\), in units of objective units per unit of \(\mu\).

Forward difference. At \(\mu=1.5\), the squared residuals sum to \(0.5^2+(-0.5)^2+(-1.5)^2=2.75\), so \(Q(1.5)=1.375\). At \(\mu=1.6\), they sum to \(0.6^2+(-0.4)^2+(-1.4)^2=2.48\), so \(Q(1.6)=1.24\). Thus \(D^{\mathrm F}=[1.24-1.375]/0.1=-1.35\).

Central difference. At \(\mu=1.4\), the squared residuals sum to \(0.4^2+(-0.6)^2+(-1.6)^2=3.08\), so \(Q(1.4)=1.54\). Hence \(D^{\mathrm C}=[1.24-1.54]/0.2=-1.50\), which matches the analytic derivative in this quadratic example. The forward error, \(-1.35-(-1.5)=0.15\), is consistent with its first-order truncation error.

Computational Cost as the Parameter Dimension Grows

If one objective evaluation costs \(C_Q\), a forward-difference gradient requires approximately \(p+1\) objective evaluations when the baseline value \(Q(\boldsymbol\theta)\) is not already available. A central-difference gradient requires \(2p\) perturbed evaluations. If the optimizer has already computed the baseline objective, the incremental forward cost is about \(p\) evaluations. These counts concern objective evaluations; they are not direct counts of arithmetic operations or wall-clock time.

An analytic gradient may be much cheaper than \(p\) separate objective evaluations when derivatives can be propagated alongside the calculations. It may also be comparable in cost to, or more expensive than, finite differences if differentiating the objective requires substantial additional work. The actual comparison depends on the model, implementation, and objective-evaluation cost. A single analytic-gradient call is not automatically “one objective evaluation” in computational effort.

Worked Example: Evaluation Counts for a Two-Parameter Objective

Consider an illustrative smooth objective \(Q(x,y)=(x-1)^2+2(y+1)^2+\frac12xy\), evaluated at \((x,y)=(0,0)\). This is a simple calculation for comparing gradient methods, not a full mixed-effects likelihood. Its gradient is \((2(x-1)+\frac12y,\;4(y+1)+\frac12x)^\mathsf{T}\), so the exact gradient at \((0,0)\) is \((-2,4)^\mathsf{T}\).

Central differences with \(h=0.1\). Here \(Q(0.1,0)=2.81\) and \(Q(-0.1,0)=3.21\), giving the first component \((2.81-3.21)/0.2=-2\). Also, \(Q(0,0.1)=3.42\) and \(Q(0,-0.1)=2.62\), giving the second component \((3.42-2.62)/0.2=4\). The central-difference gradient is therefore \((-2,4)^\mathsf{T}\).

With \(p=2\), this calculation uses four perturbed objective evaluations. In general, central differences use \(2p\) such evaluations, while forward differences use \(p\) perturbed evaluations plus a baseline if it is not already stored. The exact agreement here is not a general guarantee: the objective is quadratic, so central differences recover its first derivatives exactly in exact arithmetic.

Why Mixed-Effects Likelihoods Make the Comparison Important

A marginal likelihood contribution for one individual can be written schematically as \(L_i(\boldsymbol\theta)=\int f(y_i\mid\boldsymbol\eta,\boldsymbol\theta)g(\boldsymbol\eta\mid\boldsymbol\theta)\,d\boldsymbol\eta\), where \(y_i\) is that individual’s data and \(\boldsymbol\eta\) denotes random effects. If the integrand and its parameter derivative satisfy conditions that permit differentiation under the integral sign, then

$$ \frac{\partial \log L_i}{\partial\theta_j} = \frac{ \int \frac{\partial}{\partial\theta_j} \left[f(y_i\mid\boldsymbol\eta,\boldsymbol\theta) g(\boldsymbol\eta\mid\boldsymbol\theta)\right]\,d\boldsymbol\eta }{ L_i(\boldsymbol\theta) }. $$

This identity illustrates the analytic route: differentiate the likelihood contribution and evaluate the resulting expression. In practice, an estimation method may instead define an approximate objective involving conditional modes, quadrature, or other numerical calculations. The gradient must correspond to the objective actually supplied to the optimizer. Differentiating a theoretical likelihood while evaluating a different approximation can produce a gradient that is internally inconsistent with the objective values.

Finite differences automatically target the implemented objective as a black box, provided each evaluation computes that same objective accurately and reproducibly. But they may be expensive because each perturbation can repeat the inner calculations. If the evaluation includes Monte Carlo variability, varying numerical integration error, or an inner optimization that stops at different precision, the apparent change in \(Q\) may reflect evaluation noise rather than the parameter perturbation.

Worked Example: Objective Noise Can Distort a Finite-Difference Gradient

Suppose a hypothetical one-parameter objective is \(Q(\theta)=\frac12(\theta-2)^2\). At \(\theta=1\), its exact derivative is \(Q'(1)=-1\). A central difference with \(h=0.01\) uses \(Q(1.01)=0.49005\) and \(Q(0.99)=0.51005\), giving \((0.49005-0.51005)/0.02=-1\).

Now suppose numerical evaluation adds errors of \(-0.0001\) at \(1.01\) and \(+0.0002\) at \(0.99\). The computed values become \(0.48995\) and \(0.51025\). The finite-difference estimate is then \((0.48995-0.51025)/0.02=-1.015\). Its discrepancy of \(-0.015\) arises from evaluation error: the net error in the numerator is \(-0.0003\), and \(-0.0003/0.02=-0.015\).

This example shows why gradient reliability depends on objective accuracy relative to the perturbation. If the same objective has stochastic error, repeating evaluations with different random draws can add variability to the difference. For a meaningful comparison, hold numerical settings fixed and, where appropriate, use reproducible or shared random numbers across perturbed evaluations.

Diagnostics, Alternatives, and Limitations

A useful diagnostic is to compare analytic and finite-difference gradients at selected parameter vectors, using more than one coordinate and more than one perturbation scale. Agreement supports consistency between the implemented derivative and objective in those locations; disagreement is a signal to investigate, not proof that one method is correct. Check that the same data, objective definition, integration settings, parameter scale, and convergence criteria are used in each evaluation. Large discrepancies can indicate a derivative coding error, a discontinuity or kink, inaccurate inner calculations, or finite-difference cancellation.

Common warning signs include a gradient component that changes erratically under small parameter perturbations, a numerical derivative that changes greatly when the perturbation is modestly altered, and a derivative that disagrees in sign with observed objective changes. Such checks do not by themselves identify a single cause. In nonlinear mixed-effects calculations, also inspect whether conditional modes or numerical integration results are stable across the perturbed evaluations. A finite difference through an incompletely converged inner solver can measure changes in solver behavior as well as changes in the intended objective.

ApproachMain advantageMain concern
Analytic or automatically differentiated gradientCan avoid repeated full objective evaluations and can be precise for the implemented computationRequires correct derivative propagation through the objective and its numerical components
Forward finite differencesSimple and uses fewer perturbed evaluations than central differencesFirst-order truncation error and sensitivity to baseline or perturbed evaluation error
Central finite differencesTypically has second-order truncation error under stronger smoothness conditionsUses two evaluations per parameter and can amplify numerical noise through cancellation

No method removes all numerical or modeling limitations. Analytic derivatives can be wrong because of implementation mistakes or because they differentiate a different target than the objective being optimized. Finite differences can be unreliable near non-smooth behavior, parameter boundaries, or regions where objective evaluations are noisy. When the objective is stochastic, a derivative estimate may vary between runs; when the objective is an approximation, its gradient is the gradient of that approximation, not necessarily of the exact likelihood.

A common mistake is to assume that central differences must be more accurate because their formal truncation error is of higher order, and therefore to make \(h\) as small as possible. The formal order assumes smoothness and sufficiently accurate objective values. If \(h\) is too small, rounding or integration error can dominate the numerator; if it is too large, curvature can dominate the approximation. The correction is to treat gradient comparison as a diagnostic under controlled objective evaluations, rather than as a guarantee based on the formula alone. Detailed selection of the perturbation scale is a separate issue.

Key takeaway: Analytic and finite-difference gradients are alternative ways to approximate the local change in the same objective. Compare them with the objective’s actual computational structure in mind: smoothness determines truncation behavior, parameter dimension affects evaluation cost, and numerical noise can overwhelm small finite differences.

Check Your Understanding

Answer each question, then compare your reasoning with the solutions.

  1. For a forward difference, what is the usual truncation-error order if the relevant second derivative is bounded near the evaluation point?
  2. For \(p\) parameters, how many perturbed objective evaluations does a central-difference gradient require?
  3. Why might a finite-difference gradient of a mixed-effects objective be unstable even when the model is smooth in its parameters?
  4. A central difference is computed from two objective values whose errors are \(+0.0004\) and \(-0.0002\), respectively, with \(h=0.02\). What error do these evaluation errors add to the derivative estimate?
  5. Does agreement between an analytic gradient and a finite-difference gradient at one parameter vector prove that the objective is globally well behaved? Explain.

Solutions. (1) The forward difference has \(O(h)\) truncation error under the stated bounded-second-derivative condition. (2) It requires \(2p\) perturbed objective evaluations. (3) Each objective evaluation may include integration, Monte Carlo variability, or an inner solver; inconsistent numerical error across perturbations can be mistaken for a parameter effect. (4) The numerator error is \(0.0004-(-0.0002)=0.0006\), so the derivative-estimate error is \(0.0006/(2\times0.02)=0.015\). (5) No. Agreement is evidence of local consistency at that point, but does not establish global smoothness, global optimizer behavior, or model adequacy.

Clinical Biostats