Loading...
Searching...
No Matches
INLA.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// Copyright (c) gpridge developers
3// See LICENSE for details.
4
5// INLA (Integrated Nested Laplace Approximation) hyperparameter
6// optimisation. Three methods that bracket the log-box, find the
7// posterior mode under the bracket, and run the full optimization
8// loop with the INLA-specific stopping criteria.
9
10#include <Eigen/Core>
11#include <algorithm>
12#include <cmath>
13#include <cstdint>
14#include <limits>
15#include <vector>
16
20#include "../LaplaceINLA.h"
21#include "../MapObjective.h"
23#include "Helpers.h"
24
25#if defined(__has_include)
26#if !__has_include(<rgmin.h>)
27#error "gpridge requires rgmin include/rgmin.h"
28#endif
29#endif
30#include <rgmin.h>
31
32#include <rgmin/optimize.hpp>
33
34#include "../RgminAbi.h"
35#include "../RgminObjective.h"
36
37namespace gpr {
38
39using detail::inlaClipToLogBox;
40
41namespace {
42
43inline double* destTensorData(DLManagedTensorVersioned* t)
44{
45 return reinterpret_cast<double*>(
46 static_cast<uint8_t*>(t->dl_tensor.data) +
47 static_cast<std::size_t>(t->dl_tensor.byte_offset));
48}
49
50struct InlaDestCtx {
51 GaussianProcessRegression* gp = nullptr;
52 const EigenMatrix* x = nullptr;
53 const Eigen::VectorXd* x_ind = nullptr;
54 const Eigen::VectorXd* y = nullptr;
55 const TrainingKernelGeometry* geom = nullptr;
56 int p = 0;
57 Eigen::VectorXd cached_theta;
58 Eigen::VectorXd cached_grad;
59 Eigen::MatrixXd cached_hessian;
60 double cached_energy = 0.0;
61 bool cache_ok = false;
62 bool factor_ok = false;
63 bool hessian_ok = false;
64 funcmin::RgminCallbackFailure failure;
65
66 void evalAt(const Eigen::VectorXd& theta)
67 {
68 if (gp != nullptr && gp->wallClockLimitReached())
69 throw WallClockLimitReached{};
70 if (cache_ok && cached_theta.size() == theta.size() &&
71 (cached_theta - theta).lpNorm<Eigen::Infinity>() == 0.0) {
72 return;
73 }
74 cache_ok = false;
75 factor_ok = false;
76 cached_theta = theta;
77 cached_grad.resize(theta.size());
78 cached_energy = 0.0;
79 hessian_ok = false;
80 EnergyAndGradient eg(cached_energy, cached_grad);
81 if (geom != nullptr) {
82 gp->evaluateEnergyAndGradientFromGeometry(theta, *geom, *x, *x_ind,
83 *y, eg);
84 } else {
85 gp->evaluateEnergyAndGradient(theta, *x, *x_ind, *y, eg);
86 }
87 cached_grad = eg.gradient;
88 cache_ok = true;
89 factor_ok =
90 std::isfinite(cached_energy) && gp->isDecomposedSuccessfully() &&
91 cached_grad.size() == theta.size() && cached_grad.allFinite();
92 }
93};
94
95rgmin_status_t inlaEvalGrad(void* user, const DLManagedTensorVersioned* x,
96 double* value_out,
97 DLManagedTensorVersioned* grad_out) noexcept
98{
99 auto* ctx = static_cast<InlaDestCtx*>(user);
100 auto gout = funcmin::tensorToVec(grad_out);
101 *value_out = std::numeric_limits<double>::infinity();
102 gout.setConstant(std::numeric_limits<double>::quiet_NaN());
103 return ctx->failure.invoke("INLA objective", [&] {
104 ctx->evalAt(funcmin::tensorToVec(x));
105 if (!ctx->factor_ok) return RGMIN_SUCCESS;
106 *value_out = ctx->cached_energy;
107 gout = ctx->cached_grad;
108 return RGMIN_SUCCESS;
109 });
110}
111
112rgmin_status_t inlaHess(void* user, const DLManagedTensorVersioned* x,
113 DLManagedTensorVersioned* hess_out) noexcept
114{
115 auto* ctx = static_cast<InlaDestCtx*>(user);
116 Eigen::Map<
117 Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>>
118 hout(destTensorData(hess_out), ctx->p, ctx->p);
119 hout.setConstant(std::numeric_limits<double>::quiet_NaN());
120 return ctx->failure.invoke("INLA Hessian", [&] {
121 ctx->evalAt(funcmin::tensorToVec(x));
122 Eigen::MatrixXd H;
123 const bool assembled = ctx->factor_ok &&
124 ctx->gp->assembleExactHessian(
125 *ctx->x_ind, *ctx->x, *ctx->y, ctx->p, H) &&
126 H.rows() == ctx->p && H.cols() == ctx->p &&
127 H.allFinite();
128 if (assembled) {
129 ctx->cached_hessian = H;
130 ctx->hessian_ok = true;
131 } else {
132 H = Eigen::MatrixXd::Identity(ctx->p, ctx->p);
133 ctx->hessian_ok = false;
134 }
135 hout = H;
136 return RGMIN_SUCCESS;
137 });
138}
139
140} // namespace
141
143{
144 double floor = std::max(1.0e-6, range_x * 1.0e-3);
145 if (!ls_seed_chemical_floor_ || !std::isfinite(floor)) return floor;
146 const priors::CovalentBondPrior bond_prior(atoms_config);
147 const Eigen::VectorXd chemical =
148 bond_prior.lengthScalePerPairtype().cwiseInverse();
149 double covalent = 0.0;
150 for (Eigen::Index k = 0; k < chemical.size(); ++k) {
151 if (!std::isfinite(chemical(k)) || !(chemical(k) > 0.0)) continue;
152 covalent =
153 covalent == 0.0 ? chemical(k) : std::min(covalent, chemical(k));
154 }
155 if (covalent > 0.0) floor = std::max(floor, covalent);
156 return floor;
157}
158
159// The ceiling on log(magnSigma2) the MAP objective places over the same
160// targets: log(100 v), v the larger of the robust energy variance and the
161// force-implied variance (MapObjective.h). A fixed ceiling holds the fitted
162// amplitude below what the targets need wherever they span more than it
163// allows, and the fit then shortens every length scale to reach the forces.
165 const EigenMatrix& x, const Eigen::VectorXd& y,
166 const Eigen::VectorXd& theta_seed) const
167{
168 const Eigen::Index columns = x.cols();
169 Eigen::Index energies = columns > 0 ? y.size() / columns : 0;
170 if (!(energies > 0 && energies < y.size() &&
171 energies * columns == y.size()))
172 energies = y.size();
173 const Eigen::Index covariance_parameters =
174 hasTrailingLikelihoodNoiseParameter(theta_seed) ? theta_seed.size() - 1
175 : theta_seed.size();
177 x, energies, y, theta_seed.head(covariance_parameters)));
178}
179
181 const Eigen::VectorXd& theta_seed, const double min_lengthscale,
182 const double max_log_magn_sigma2, Eigen::VectorXd& lower,
183 Eigen::VectorXd& upper) const
184{
185 lower.resize(0);
186 upper.resize(0);
187 if (theta_seed.size() == 0 || sexpat_cov_func == nullptr) return;
188
189 lower.resize(theta_seed.size());
190 upper.resize(theta_seed.size());
191
192 const PriorBase amplitude_prior =
193 sexpat_cov_func->getPriorParametersSqrtt();
194 const double amplitude_scale2 =
195 (amplitude_prior.getS2() > 0.0) ? amplitude_prior.getS2() : 1.0;
196 lower(0) = std::log(std::max(1.0e-12, 1.0e-6 * amplitude_scale2));
197 upper(0) = max_log_magn_sigma2;
198 if (lower(0) >= upper(0)) lower(0) = upper(0) - std::log(1.0e6);
199
200 const PriorBase length_prior =
201 sexpat_cov_func->getPriorParametersGaussian();
202 const double prior_length_scale =
203 (length_prior.getS2() > 0.0) ? std::sqrt(length_prior.getS2()) : 1.0;
204 const double length_center = std::abs(length_prior.getMu());
205 const double lower_length = std::max(1.0e-6, min_lengthscale);
206 const double upper_length =
207 std::max({10.0 * lower_length,
208 length_center + 30.0 * prior_length_scale, 1.0e-2});
209
210 const bool has_noise = hasTrailingLikelihoodNoiseParameter(theta_seed);
211 const Eigen::Index length_end =
212 has_noise ? theta_seed.size() - 1 : theta_seed.size();
213 for (Eigen::Index i = 1; i < length_end; ++i) {
214 lower(i) = std::log(lower_length);
215 upper(i) = std::log(upper_length);
216 if (lower(i) >= upper(i)) lower(i) = upper(i) - std::log(1.0e6);
217 }
218
219 if (has_noise) {
220 const Eigen::Index noise_idx = theta_seed.size() - 1;
221 const double seed_noise = std::exp(theta_seed(noise_idx));
222 const double lower_noise =
223 std::max(1.0e-12, std::min(seed_noise * 1.0e-4, 1.0e-8));
224 const double upper_noise =
225 std::max({1.0e-2, seed_noise * 1.0e4, lower_noise * 1.0e6});
226 lower(noise_idx) = std::log(lower_noise);
227 upper(noise_idx) = std::log(upper_noise);
228 if (lower(noise_idx) >= upper(noise_idx)) {
229 lower(noise_idx) = upper(noise_idx) - std::log(1.0e6);
230 }
231 }
232}
233
235 const EigenMatrix& x, const Eigen::VectorXd& x_ind,
236 const Eigen::VectorXd& y, Eigen::VectorXd& theta_mode,
237 const TrainingKernelGeometry* training_geom)
238{
239 theta_mode.resize(0);
240 if (wallClockLimitReached()) return false;
241 if (sexpat_cov_func == nullptr || y.rows() != x.rows()) return false;
242
243 laplace::ScopedKernelState kernel_guard(*sexpat_cov_func, sigma2,
244 lik_gaussian.get());
245 Eigen::VectorXd theta_seed = packInlaHyperparameters();
246 if (theta_seed.size() == 0 || !theta_seed.allFinite()) return false;
247
248 aux::Distance distance;
249 FieldMatrixd unit_lengthscale(1, 1);
250 unit_lengthscale.setConstant(1.0);
251 const double range_x = distance.range_at(x, atoms_config, unit_lengthscale);
252 const double min_lengthscale = inlaMinimumLengthScale(range_x);
253 Eigen::VectorXd lower;
254 Eigen::VectorXd upper;
255 calculateInlaModeLogBounds(theta_seed, min_lengthscale * 1.05,
256 inlaMaxLogMagnSigma2(x, y, theta_seed), lower,
257 upper);
258 const int p = static_cast<int>(theta_seed.size());
259 if (lower.size() != p || upper.size() != p) return false;
260
261 auto clip_to_bounds = [&](const Eigen::VectorXd& theta) {
262 return inlaClipToLogBox(theta, lower, upper);
263 };
264
265 // Warm-start from the last successful mode. Newton/RFO rebuilds H
266 // each step.
267 const bool can_warm_start = inla_warm_valid_ &&
268 inla_warm_theta_.size() == p &&
269 inla_warm_theta_.allFinite();
270 Eigen::VectorXd theta =
271 clip_to_bounds(can_warm_start ? inla_warm_theta_ : theta_seed);
272 if (theta.size() != p || !theta.allFinite()) return false;
273 if (can_warm_start) {
274 ++inla_warm_start_hits_for_testing_;
275 } else {
276 ++inla_warm_start_misses_for_testing_;
277 }
278
279 constexpr int kMaxIterations = 10;
280 constexpr double kGradientTolerance = 1.0e-4;
281 constexpr double kTrustRadius = 3.0;
282
283 std::vector<double> wbuf(static_cast<std::size_t>(p));
284 Eigen::Map<Eigen::VectorXd>(wbuf.data(), p) = theta;
287 rgmin_tensor_borrow_cpu_f64(wbuf.data(), wbuf.size()));
288 if (!xt) return false;
289
290 InlaDestCtx ctx;
291 ctx.gp = this;
292 ctx.x = &x;
293 ctx.x_ind = &x_ind;
294 ctx.y = &y;
295 ctx.geom = training_geom;
296 ctx.p = p;
297
298 rgmin::Control ctrl;
299 ctrl.maxiter = static_cast<std::size_t>(kMaxIterations);
300 ctrl.gtol = kGradientTolerance;
301 ctrl.istep = 1.0;
302 ctrl.memory = 0;
303 // Hyperparameters, not atoms: no step cap of any kind.
304 ctrl.maxmove = -1.0;
305
306 Eigen::VectorXd best_theta = theta;
307 double best_phi = std::numeric_limits<double>::infinity();
308 Eigen::MatrixXd inverse_hessian = Eigen::MatrixXd::Identity(p, p);
309 ctx.failure.invoke("INLA initial objective", [&] {
310 ctx.evalAt(theta);
311 return RGMIN_SUCCESS;
312 });
313 if (ctx.failure.failed() || !ctx.factor_ok) {
314 ctx.failure.report();
315 return false;
316 }
317 best_phi = ctx.cached_energy;
318 try {
319 rgmin::Solver session(rgmin::Method::Rfo, ctrl,
320 static_cast<std::size_t>(p));
321 session.set_accept(RGMIN_ACCEPT_ENERGY);
322 if (session.set_highs(true) != 0 ||
323 session.set_box(lower.data(), upper.data(),
324 static_cast<std::size_t>(p)) != 0) {
325 return false;
326 }
327 session.set_trust(kTrustRadius);
328
329 rgmin::Report report{};
330 for (int iter = 0; iter < kMaxIterations; ++iter) {
331 if (wallClockLimitReached()) return false;
332 last_inla_iterations_ = static_cast<std::size_t>(iter + 1);
333 report =
334 session.step_hess_fg(&inlaEvalGrad, &inlaHess, &ctx, xt.get());
335 if (ctx.failure.failed()) {
336 ctx.failure.report();
337 return false;
338 }
339 Eigen::Map<const Eigen::VectorXd> walked(wbuf.data(), p);
340 if (walked.size() == p && walked.allFinite() &&
341 std::isfinite(report.value) && report.value < best_phi) {
342 best_phi = report.value;
343 best_theta = walked;
344 }
345 if (report.grad_norm <=
346 kGradientTolerance * (1.0 + std::abs(report.value))) {
347 break;
348 }
349 }
350 } catch (...) {
351 ctx.failure.report();
352 return false;
353 }
354 // dest set_box owns the log-box. A walk that leaves it is a dest
355 // failure, not a reason to clip the iterate after the fact.
356 if (best_theta.size() != p || !best_theta.allFinite()) {
357 return false;
358 }
359 for (int i = 0; i < p; ++i) {
360 if (best_theta(i) < lower(i) - 1.0e-12 ||
361 best_theta(i) > upper(i) + 1.0e-12) {
362 return false;
363 }
364 }
365
366 if (!std::isfinite(best_phi) || best_theta.size() != p ||
367 !best_theta.allFinite()) {
368 return false;
369 }
370
371 setParameters(best_theta);
372 const double phi_mode = evaluateEnergy(x, x_ind, y);
373 if (!std::isfinite(phi_mode) || !is_decomposed_succesfully) {
374 return false;
375 }
376 theta_mode = best_theta;
377 if (retain_fitted_hyperparameter_density_) {
378 funcmin::MapObjectiveConfig density_config;
379 density_config.barrier_strength = 0.0;
381 density_config.parameter_lower = lower;
382 density_config.parameter_upper = upper;
383 const Eigen::Index configurations = (x_ind.array() == 0.0).count();
384 const Eigen::Index dimensions =
385 static_cast<Eigen::Index>(x_ind.maxCoeff());
386 Coord fit_positions;
387 if (dimensions > 0 && dimensions <= x.cols())
388 fit_positions = x.topLeftCorner(configurations, dimensions);
389 captureFittedHyperparameterDensity(fit_positions, y, theta_mode,
390 density_config, 1.0, false);
391 }
392 if (best_theta.size() == p && best_theta.allFinite() &&
393 inverse_hessian.rows() == p && inverse_hessian.cols() == p &&
394 inverse_hessian.allFinite()) {
395 inla_warm_theta_ = best_theta;
396 inla_warm_inverse_hessian_ = inverse_hessian;
397 inla_warm_valid_ = true;
398 }
399 return true;
400}
401
403 const Observation& observation)
404{
405 failedOptimizer = false;
406 const Eigen::VectorXd fallback_parameters = packInlaHyperparameters();
407 if (wallClockLimitReached()) {
408 failedOptimizer = true;
409 last_fit_stop_reason_ = "wall-clock limit";
410 return;
411 }
412
413 Observation optimization_observation =
414 selectOptimizationSubset(observation);
415
417 EigenMatrix opt_R_matrix;
418 Eigen::VectorXd opt_R_indices;
419 Eigen::VectorXd opt_energy_and_gradient;
420 aux_func.assembleMatrixOfRepetitiveCoordinates(optimization_observation.R,
421 opt_R_matrix, opt_R_indices);
422 aux_func.assembleVectorFromEnergyAndGradient(optimization_observation,
423 opt_energy_and_gradient);
424 subtractPriorMeanFromTargets(optimization_observation.R,
425 optimization_observation.E.size(),
426 opt_energy_and_gradient);
427 standardizeTargets(opt_energy_and_gradient,
428 optimization_observation.E.size());
429
430 // The dest Newton/RFO mode-finder (computeInlaPosteriorMode) walks
431 // through NLML + Hessian evaluations per outer dimer iter on the
432 // optimisation subset. Each evaluateEnergy rebuilds the training
433 // covariance matrix; without a distance cache, every rebuild
434 // recomputes the per-pair inverse distances even though the subset
435 // coordinates are fixed across the inner loop. Mirror the SCG
436 // path's cacheDistances / clearDistanceCache discipline (see
437 // performHyperparameterOptimization in Optimize.cpp) so the inner
438 // NLML evals hit the dist_calculator_ cache. Only the
439 // hyperparameters change between inner iters; positions are
440 // constant. RgminScg is the SCG waist.
441 if (sexpat_cov_func != nullptr) {
442 sexpat_cov_func->cacheDistances(optimization_observation.R,
443 optimization_observation.R);
444 }
445
446 // Build the same per-outer-iter geometry handle the SCG driver uses
447 // (Optimize.cpp). The INLA dest Newton/RFO mode finder also evaluates
448 // the marginal log likelihood + gradient + Hessian at fixed training
449 // inputs, so the K-assembly and dK/dtheta geometry path applies.
450 TrainingKernelGeometry inla_geom;
451 const bool inla_geom_ready =
453 prepareTrainingKernelGeometry(opt_R_matrix, opt_R_indices, inla_geom);
454 const TrainingKernelGeometry* inla_geom_ptr =
455 inla_geom_ready ? &inla_geom : nullptr;
456
457 Eigen::VectorXd theta_mode;
458 const bool mode_ok = computeInlaPosteriorMode(opt_R_matrix, opt_R_indices,
459 opt_energy_and_gradient,
460 theta_mode, inla_geom_ptr);
461
462 if (sexpat_cov_func != nullptr) {
463 sexpat_cov_func->clearDistanceCache();
464 }
465
466 if (!mode_ok) {
467 failedOptimizer = true;
468 setParameters(fallback_parameters);
469 if (wallClockLimitReached()) {
470 last_fit_stop_reason_ = "wall-clock limit";
471 return;
472 }
473 updateModelWithFullData(observation);
474 return;
475 }
476
477 setParameters(theta_mode);
478 if (wallClockLimitReached()) {
479 failedOptimizer = true;
480 last_fit_stop_reason_ = "wall-clock limit";
481 setParameters(fallback_parameters);
482 return;
483 }
484 updateModelWithFullData(observation);
486 failedOptimizer = true;
487 setParameters(fallback_parameters);
488 updateModelWithFullData(observation);
489 }
490}
491
492} // namespace gpr
@ x
Definition Enums.h:28
@ y
Definition Enums.h:28
INLA-style Laplace approximation of the GP/TP hyperparameter posterior.
void assembleVectorFromEnergyAndGradient(const gpr::Observation &observation, Eigen::VectorXd &vector)
Combine Energy and gradient into a single Eigen vector.
void assembleMatrixOfRepetitiveCoordinates(const gpr::Coord &coord, gpr::EigenMatrix &matrix, Eigen::VectorXd &ind)
Assemble Eigen matrix with repetitive rows based on provided set of coordinates R.
Methods to calculate distances between atoms.
Definition Distance.h:154
double range_at(const gpr::Coord &positions, const gpr::AtomsConfiguration &conf_info, const gpr::FieldMatrixd &lengthscale)
Definition Distance.cpp:533
Observation selectOptimizationSubset(const Observation &full_observation) const
Select a hyperparameter-optimization subset via FPS-EMD.
double evaluateEnergy(const Eigen::VectorXd &w, const EigenMatrix &x, const Eigen::VectorXd &x_ind, const Eigen::VectorXd &y)
void setParameters(const GPRSetup &parameters)
Set parameters of the GPR model.
bool prepareTrainingKernelGeometry(const EigenMatrix &x, const Eigen::VectorXd &x_ind, TrainingKernelGeometry &out, bool reused=false) const
bool computeInlaPosteriorMode(const EigenMatrix &x, const Eigen::VectorXd &x_ind, const Eigen::VectorXd &y, Eigen::VectorXd &theta_mode, const TrainingKernelGeometry *training_geom)
Definition INLA.cpp:234
bool wallClockLimitReached() const
Collective on the model's process group for distributed fitters.
void calculateInlaModeLogBounds(const Eigen::VectorXd &theta_seed, double min_lengthscale, double max_log_magn_sigma2, Eigen::VectorXd &lower, Eigen::VectorXd &upper) const
Definition INLA.cpp:180
std::unique_ptr< SexpatCF > sexpat_cov_func
void captureFittedHyperparameterDensity(const Coord &positions, const Eigen::VectorXd &targets, const Eigen::VectorXd &theta, const funcmin::MapObjectiveConfig &penalty, double target_scale, bool use_ties)
void optimizeLaplaceINLA(const Observation &observation)
Definition INLA.cpp:402
void updateModelWithFullData(const Observation &full_observation)
bool canUseTrainingGeometryObjective() const noexcept
Definition Optimize.cpp:389
double inlaMinimumLengthScale(double range_x) const
Definition INLA.cpp:142
double inlaMaxLogMagnSigma2(const EigenMatrix &x, const Eigen::VectorXd &y, const Eigen::VectorXd &theta_seed) const
Definition INLA.cpp:164
Class of prior parameters.
Definition PriorBase.h:23
double getMu() const
Definition PriorBase.h:48
double getS2() const
Definition PriorBase.h:53
Eigen::VectorXd lengthScalePerPairtype() const
eon_relax_band_t eon_relax_surface_fn void * user
double mapMaxLogMagnSigma2(double signal_variance) noexcept
Eigen::Map< const Eigen::VectorXd > tensorToVec(const DLManagedTensorVersioned *tensor)
std::unique_ptr< DLManagedTensorVersioned, RgminTensorDeleter > RgminTensorHandle
double mapRobustSignalVarianceAnchor(const gpr::EigenMatrix &x, Eigen::Index n_e, const Eigen::VectorXd &y, const Eigen::VectorXd &w)
void requireCompatibleLibrary()
Definition RgminAbi.h:90
Gaussian-process regression, kernels, priors, and the searches that run on the surrogate.
Definition Macros.h:16
FieldMatrixd Coord
Definition Macros.h:35
Eigen::Matrix< double, EigenDynamic, EigenDynamic, EigenMatrixStorage > EigenMatrix
Definition Macros.h:20
Eigen::Matrix< double, EigenDynamic, EigenDynamic, FieldMatrixStorage > FieldMatrixd
Definition Macros.h:25
double barrier_strength
Already capped with min(current_barrier_strength, 0.5) by the caller.
Eigen::VectorXd parameter_lower
Eigen::VectorXd parameter_upper
gpr::MapPriorWeightMode weight_mode
Observation data: energy, gradient and positions.
FieldMatrixd E