8.16 Forward-mode automatic differentiation
nlmx evaluates model code generically over either ordinary f64 values or dual numbers. A dual number carries a value and one derivative slot per seeded ETA:
Arithmetic, supported smooth functions, linear propagation and ODE integration apply the chain rule as the subject is simulated. The result contains prediction and residual-variance derivatives with respect to active random effects without differencing the entire simulation.
Width and cost
Runtime dispatch selects the smallest compiled dual width that covers the number of active directions, up to the engine maximum. A two-ETA model carries two derivatives rather than the maximum width. Forward-mode work grows with the number of directions, making it well suited to subject-level ETA vectors but not free.
Exact means algorithmic
“Exact gradient” means the derivative of the implemented arithmetic path up to floating-point rounding. It does not mean a discontinuous model has a unique mathematical derivative, nor does it remove ODE discretisation error. Adaptive step selection uses value parts; accepted steps propagate dual arithmetic.
Piecewise operations choose a branch from values and propagate that branch. INT/NINT return constants, comparisons have no smooth derivative, and min/max follow the selected operand. At a boundary, validate one-sided behavior.
Where finite differences remain
The residual EPS sensitivities are symmetric differences. The Laplace Hessian is a central difference of exact ETA gradients. Fisher-information and covariance workflows can use their own finite-difference steps. Document each derivative layer separately rather than describing the whole application as AD-only.
Verification
For a smooth fixture, compare dual derivatives against centred finite differences over a step-size sweep. Agreement should improve then plateau with rounding. Repeat near event-time dependencies, ODE systems and branches.
Common mistakes
- Claiming every derivative in nlmx is AD-derived.
- Treating branch-boundary derivatives as smooth truth.
- Comparing gradients without matching solver tolerances.
Checklist
- Identify seeded directions and dual width.
- Classify AD, symmetric-difference and Hessian calculations.
- Test smooth and nonsmooth cases separately.
Further reading
See expressions, ODE tolerances and Chapter 9's forthcoming numerical-core chapter.