Use the derivative providers¶
A derivative provider answers two questions about the energy \(E(x)\) at a
point: the Hessian \(H = \partial^2 E/\partial x^2\) and the Hessian-vector
product \(Hv\). The header gpr/derivatives/DerivativeProvider.h defines the
interface and two working providers. It does not depend on the GP, the
optimiser or any potential, so the same contract can serve gpridge, rgsaddle
and rgpot. Pull request 264 added it.
Status: implemented, header-only, C++ only. No C symbol, Python name,
command-line flag or TOML key exposes it, and no production source includes
it. The tests tests/gpr/derivatives/DerivativeProviderTest.cpp and
tests/gpr/quantum/GPMeanHessianTest.cpp are the only callers. The C ABI is
untouched (docs/design/derivative-provider.md).
To get a Hessian of the posterior mean of a fitted GP from C or Python, use
gpr_model_predict_hessian and gpr_model_predict_hessian_action_checked
(C function reference), or GaussianProcess.predict_hessian in Python.
Those calls are separate from the provider interface.
The contract¶
The class has two methods,
bool hessian(const Vector& x, Matrix& H, std::string* reason = nullptr) const noexcept
and
bool hessianVector(const Vector& x, const Vector& v, Vector& Hv, std::string* reason = nullptr) const noexcept.
Both methods return
falseand leave the output empty (a 0 by 0 matrix or a vector of size 0) when the derivative is unavailable, the position is empty or not finite, the direction has the wrong size, is zero or is not finite, the provider fails, the result has the wrong shape or the result is not finite.A successful Hessian is square with
x.size()rows. A successful product hasx.size()entries.The provider returns the Hessian of the energy. A force callback means the physical force \(F = -\partial E/\partial x\), so a provider built from forces returns \(H = -\partial F/\partial x\). No optimiser may change this sign.
No provider symmetrises its result. An asymmetric result is evidence of an inconsistent force callback, a finite-difference error or a wrong analytic derivative.
Coordinate transforms belong to the adapter that builds the provider. The quantum-path adapter, for example, supplies mass-weighted coordinates.
The three providers¶
Factory |
Source of the derivative |
Status |
|---|---|---|
|
A linear action prepared once at each point |
working |
|
Centred differences of a force callback |
working |
|
Automatic differentiation |
stub, returns an empty provider |
The analytic provider takes a callback that, given a point, returns the
action \(v \mapsto Hv\). For the Hessian it prepares once and applies the
action to each coordinate vector. For the product it prepares once and applies
it to the direction. gpridge adapts the posterior mean this way:
makeAnalyticDerivativeProvider([&gp](const Eigen::VectorXd& x) { return gp.prepareMeanHessian(x.transpose()); }). The callback keeps no model state,
and an action must not outlive a refit of the model.
The finite-difference provider uses
\(h_j = \sqrt[3]{\epsilon}\,\max(s_j, |x_j|)\) for column \(j\), where
\(\epsilon\) is the machine epsilon and \(s_j\) is the coordinate scale.
coordinateScale supplies the default \(s_j=1\); a non-empty
coordinateScales supplies one strictly positive, finite scale per
coordinate instead. It must have the same length as the position. The step
balances the \(O(h^2)\) truncation error of a centred difference against the
\(O(\epsilon/h)\) roundoff. It divides by the displacement that the double
precision representation actually gives. For a product it differences along
\(u=v/\|v\|\), uses
\(h=(h_0/M)\max\bigl(1,\sqrt[3]{\|x\|_2 M/4}\bigr)\) with
\(M=\max_j(|u_j|/\max(|x_j|,s_j))\), and multiplies by \(\|v\|\). The base
step \(h_0/M\) weights each characteristic scale by how much the direction
moves its coordinate. The factor in front raises it when the large coordinates
carry little of the direction, where the displacement of a large coordinate
would fall below the spacing of its floating-point numbers and the stencil
would drop it. It is the minimiser
\(h_r=\sqrt[3]{\epsilon\|x\|_2/(4M^2)}\) of the truncation error
\((hM)^2\) plus the rounding error \(\epsilon\|x\|_2/(2h)\) of the
displacement, written relative to the base step at the default \(h_0\). That
rounding error belongs to the whole vector, so the step is continuous in
\(u\) and a small component of \(v\) on a coordinate of order one does not
change it. The step is proportional to relativeStep, so a stencil at
\(2h_0\) takes twice the step. The derivation is in
docs/design/derivative-provider.md. A zero or non-finite direction is
rejected by every provider without a callback evaluation.
The standalone scale and step helpers have non-throwing overloads that write
to a double& result and accept an optional std::string* reason. They return
false, reset the result to zero and report invalid options, dimensions or
non-finite positions. Their value-returning overloads expose the same
validation by throwing std::invalid_argument or std::out_of_range.
DerivativeProvider::hessian and hessianVector are noexcept. They return
false for unavailable derivatives, invalid inputs, failed callbacks and
invalid callback outputs; both clear the output first and can describe the
failure through their optional std::string* reason. Exceptions from user
force, preparation and Hessian-action callbacks are caught at this provider
boundary and reported as failures, rather than escaping to the caller.
Compare the two working providers¶
The program builds a three-atom Lennard-Jones cluster with \(\sigma=\epsilon=1\). It writes the force and the energy Hessian by hand. It wraps the exact Hessian in the analytic provider and the force in the finite-difference provider, and it checks four things:
the two Hessians agree to a relative \(10^{-7}\);
the two products agree to the same relative size;
a position with a
NaNmakes the provider returnfalseand leave an empty matrix;the Enzyme provider is empty.
#include <Eigen/Core>
#include <cmath>
#include <cstdio>
#include <limits>
#include "gpr/derivatives/DerivativeProvider.h"
namespace dv = gpr::derivatives;
constexpr int n_atoms = 3;
constexpr double relative_tolerance = 1e-7;
// Pair energy 4 (r^-12 - r^-6). The force on atom i from atom j is
// coefficient * (x_i - x_j).
static double pairCoefficient(double r2)
{
const double s6 = std::pow(1.0 / r2, 3);
return 24.0 * (2.0 * s6 * s6 - s6) / r2;
}
static bool force(const dv::Vector& x, dv::Vector& f)
{
f = dv::Vector::Zero(x.size());
for (int i = 0; i < n_atoms; ++i)
for (int j = i + 1; j < n_atoms; ++j) {
const Eigen::Vector3d d = x.segment<3>(3 * i) - x.segment<3>(3 * j);
f.segment<3>(3 * i) += pairCoefficient(d.squaredNorm()) * d;
f.segment<3>(3 * j) -= pairCoefficient(d.squaredNorm()) * d;
}
return true;
}
// Second derivative of the pair energy with respect to x_i, as a 3 by 3 block.
static dv::Matrix energyHessian(const dv::Vector& x)
{
dv::Matrix hessian = dv::Matrix::Zero(x.size(), x.size());
for (int i = 0; i < n_atoms; ++i)
for (int j = i + 1; j < n_atoms; ++j) {
const Eigen::Vector3d d = x.segment<3>(3 * i) - x.segment<3>(3 * j);
const double r2 = d.squaredNorm();
const double s6 = std::pow(1.0 / r2, 3);
const double radial_second = (672.0 * s6 * s6 - 192.0 * s6) / (r2 * r2);
const Eigen::Matrix3d block =
-pairCoefficient(r2) * Eigen::Matrix3d::Identity() +
radial_second * d * d.transpose();
hessian.block<3, 3>(3 * i, 3 * i) += block;
hessian.block<3, 3>(3 * j, 3 * j) += block;
hessian.block<3, 3>(3 * i, 3 * j) -= block;
hessian.block<3, 3>(3 * j, 3 * i) -= block;
}
return hessian;
}
int main()
{
dv::Vector x(9);
x << 0.0, 0.0, 0.0, 1.1, 0.0, 0.1, 0.5, 1.0, -0.1;
dv::Vector direction(9);
direction << 1.0, -2.0, 0.5, 0.3, 0.7, -1.0, 0.0, 1.0, 2.0;
const auto analytic = dv::makeAnalyticDerivativeProvider(
[](const dv::Vector& position) {
const dv::Matrix hessian = energyHessian(position);
return dv::HessianAction(
[hessian](const dv::Vector& v, dv::Vector& out) {
out = hessian * v;
return true;
});
});
const auto differenced = dv::makeFiniteDifferenceForceProvider(force);
dv::Matrix h_analytic, h_differenced;
dv::Vector hv_analytic, hv_differenced;
if (!analytic.hessian(x, h_analytic)) return 1;
if (!differenced.hessian(x, h_differenced)) return 1;
if (!analytic.hessianVector(x, direction, hv_analytic)) return 1;
if (!differenced.hessianVector(x, direction, hv_differenced)) return 1;
const double h_error = (h_analytic - h_differenced).norm() / h_analytic.norm();
const double hv_error =
(hv_analytic - hv_differenced).norm() / hv_analytic.norm();
const double asymmetry =
(h_differenced - h_differenced.transpose()).norm() / h_differenced.norm();
std::printf("Hessian relative difference %.1e\n", h_error);
std::printf("product relative difference %.1e\n", hv_error);
std::printf("finite-difference asymmetry %.1e\n", asymmetry);
if (h_error > relative_tolerance || hv_error > relative_tolerance) return 1;
dv::Vector bad = x;
bad(2) = std::numeric_limits<double>::quiet_NaN();
dv::Matrix failed;
const bool accepted = differenced.hessian(bad, failed);
std::printf("NaN position accepted %d, matrix size %ld by %ld\n", accepted,
static_cast<long>(failed.rows()), static_cast<long>(failed.cols()));
if (accepted || failed.size() != 0) return 1;
const auto enzyme = dv::makeEnzymeDerivativeProvider(force);
std::printf("enzyme provider ready %d, available %d\n",
static_cast<int>(static_cast<bool>(enzyme)),
static_cast<int>(dv::kEnzymeDerivativeProviderAvailable));
if (enzyme) return 1;
std::printf("providers checked\n");
return 0;
}
Hessian relative difference <s>
product relative difference <s>
finite-difference asymmetry <s>
NaN position accepted 0, matrix size 0 by 0
enzyme provider ready 0, available 0
providers checked
The finite-difference Hessian is not exactly symmetric, which is the signal
that the contract keeps visible. The relative difference of the two
Hessians is of order \(10^{-9}\) here. Tests in the repository do not use
a fixed threshold. They compare stencils at \(h\) and \(2h\). The leading
truncation terms differ by a factor of four, so \(\|D(h)-D(2h)\|/3\)
estimates the error of the fine stencil. A named safety factor covers higher
terms, and an \(\epsilon\lVert F\rVert/h\) floor accounts for force evaluation
roundoff across step \(h\) (docs/design/derivative-provider.md).
The Enzyme option¶
The Meson option enzyme takes disabled (the default) or auto. The
default adds no probe and no compiler flag, so the existing numerical paths
are unchanged. auto probes pkg-config for enzyme and defines
GPR_ENZYME_TOOLCHAIN_DETECTED, which appears as kEnzymeToolchainDetected.
Detection does not mean the bridge exists. kEnzymeDerivativeProviderAvailable
is false and makeEnzymeDerivativeProvider returns an empty provider. A
future bridge must pin a Clang, LLVM and Enzyme combination, implement both
methods and pass the agreement tests above before that constant becomes
true.
What is not recorded¶
The pull request records no timing, no call count and no accuracy number for the providers. The accuracy above is from this page’s own run.
The ledger mentions inducing-point branches with predictive Hessians
(sparse-derivative-gp, gp-21). They are not on develop and are not the
providers described here. See Methods: numerics and
Methods: approximations.