Loading...
Searching...
No Matches
Optimize.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// Hyperparameter optimisation entrypoints (SCG warm-start, monitor /
6// adapt history, full-data refit, ARD-disabled factorized path) plus
7// the configuration update hook. All methods stay on
8// GaussianProcessRegression; their definitions move into this TU so the
9// monolithic .cpp can keep shrinking.
10
11#include <Eigen/Core>
12#include <Eigen/Eigenvalues>
13#include <algorithm>
14#include <chrono>
15#include <cmath>
16#include <cstddef>
17#include <cstdint>
18#include <cstdio>
19#include <cstdlib>
20#include <fstream>
21#include <iomanip>
22#include <limits>
23#include <optional>
24#include <random>
25#include <stdexcept>
26#include <type_traits>
27#include <typeinfo>
28#include <unordered_set>
29#include <utility>
30
37#include "../PhaseTimers.h"
38#include "Helpers.h"
41#ifdef GPR_LINALG_SCALAPACK
43#endif
44#include "../AnnealStage.h"
47#ifdef GPR_LINALG_KOKKOS
49#endif
50#include "../JointObservation.h"
51#include "../NoiseGridSearch.h"
53#include "OptimizerState.h"
54#include "QuadraticEvidence.h"
56
57namespace {
58template <typename T>
59inline constexpr bool kUsesScg = std::is_same_v<T, funcmin::RgminScg>;
60// Rgmin SCG and rgmin L-BFGS share the MAP settings and the
61// exhausted-budget flag. A single trait keeps the call sites from
62// drifting as alternatives are added to the variant.
63template <typename T>
64inline constexpr bool kIsScgLike = std::is_same_v<T, funcmin::RgminScg> ||
65 std::is_same_v<T, funcmin::RgminOpt>;
66} // namespace
67
68namespace gpr {
69namespace {
70
71std::vector<bool> fullRefitMask(const SexpatCF* kernel,
72 const LikGaussian* likelihood)
73{
74 if (kernel == nullptr) return {};
75 return std::vector<bool>(
76 1 + kernel->getLengthScaleRef().size() +
77 (likelihood != nullptr && likelihood->getOptimizeSigma2()),
78 true);
79}
80
81// Profile C = sf2 * (Kt + rho * I). Kt is the sexpat kernel at unit signal
82// variance, without the constant kernel and without observation noise.
83// FactorizedLikelihood adds rho to the eigenvalues of Kt and returns sf2.
84// The observation noise of that covariance is sf2 * rho, in training units.
85// scripts/derive_chem_factorized_hyper.py pins the closed form.
86struct ProfiledKernelScale {
87 double signal = 0.0;
88 double noise = 0.0;
89 double nlml = std::numeric_limits<double>::infinity();
90 bool ok = false;
91};
92
93ProfiledKernelScale profileUnitKernelScale(GaussianProcessRegression& model,
94 const EigenMatrix& rows,
95 const Eigen::VectorXd& indices,
96 const Eigen::VectorXd& targets)
97{
98 ProfiledKernelScale scale;
99 if (model.sexpat_cov_func == nullptr || rows.rows() != targets.size() ||
100 rows.rows() == 0 || !targets.allFinite())
101 return scale;
102 const double saved_signal = model.sexpat_cov_func->getMagnSigma2();
103 model.sexpat_cov_func->setMagnSigma2(1.0);
104 struct RestoreSignal {
105 SexpatCF* kernel;
106 double saved;
107 bool armed = true;
108 ~RestoreSignal()
109 {
110 if (armed && kernel != nullptr) kernel->setMagnSigma2(saved);
111 }
112 } restore{model.sexpat_cov_func.get(), saved_signal};
113
114 EigenMatrix kernel;
115 model.evaluateTrainingCovarianceMatrix(rows, indices, kernel, false, false,
116 false);
117 if (kernel.rows() != targets.size() || kernel.cols() != targets.size() ||
118 !kernel.allFinite())
119 return scale;
120 Eigen::SelfAdjointEigenSolver<EigenMatrix> solver(kernel);
121 if (solver.info() != Eigen::Success || !solver.eigenvalues().allFinite() ||
122 !solver.eigenvectors().allFinite())
123 return scale;
124 FactorizedLikelihood likelihood;
125 likelihood.setEigendecomposition(solver.eigenvalues(),
126 solver.eigenvectors(), targets);
127 const NoiseSearchResult result = NoiseGridSearch().searchGP(likelihood);
128 const double signal = result.best_prefactor;
129 const double noise = signal * result.best_noise;
130 if (!std::isfinite(result.best_likelihood) || !(signal > 0.0) ||
131 !std::isfinite(noise) || !(noise > 0.0))
132 return scale;
133 scale.signal = signal;
134 scale.noise = noise;
135 scale.nlml = result.best_likelihood;
136 scale.ok = true;
137 return scale;
138}
139
140// A pair type's length scale is resolved by the fit rows when their
141// inverse-distance features of that type span at least one length scale,
142// where the kernel has fallen by 1/e. Rows that span less see only the
143// quadratic part of the kernel, so the marginal likelihood does not
144// identify the length scale and the MAP point is set by the priors.
145std::vector<bool> lengthScalesResolvedByRows(const SexpatCF& kernel,
146 const Coord& rows)
147{
148 const auto& length_scales = kernel.getLengthScaleRef();
149 const Eigen::Index count = length_scales.size();
150 std::vector<bool> resolved(static_cast<std::size_t>(count), false);
151 const auto& configuration = kernel.getConfInfo();
152 const double far_radius = kernel.farFieldRadius();
153 const std::vector<int> pair_types =
154 InverseDistanceDescriptor::featurePairtypes(configuration, far_radius);
155 Eigen::VectorXd low, high, features;
156 for (Eigen::Index row = 0; row < rows.rows(); ++row) {
157 const Coord position = rows.row(row);
158 InverseDistanceDescriptor::compute(position, configuration, features,
159 far_radius);
160 if (features.size() != static_cast<Eigen::Index>(pair_types.size()) ||
161 !features.allFinite())
162 return std::vector<bool>(static_cast<std::size_t>(count), true);
163 if (row == 0) {
164 low = features;
165 high = features;
166 } else {
167 low = low.cwiseMin(features);
168 high = high.cwiseMax(features);
169 }
170 }
171 if (rows.rows() < 2) return resolved;
172 for (std::size_t feature = 0; feature < pair_types.size(); ++feature) {
173 const int type = pair_types[feature];
174 if (type < 0 || type >= count) continue;
175 const auto f = static_cast<Eigen::Index>(feature);
176 if (high(f) - low(f) >= *(length_scales.data() + type))
177 resolved[static_cast<std::size_t>(type)] = true;
178 }
179 return resolved;
180}
181
182struct TrainingGeometryObjective {
183 GaussianProcessRegression& gp;
184 const TrainingKernelGeometry& geometry;
185
186 void evaluateEnergyAndGradient(const Eigen::VectorXd& w,
187 const EigenMatrix& x,
188 const Eigen::VectorXd& x_ind,
189 const Eigen::VectorXd& y,
190 EnergyAndGradient& energy_and_gradient)
191 {
192 if (gp.getHyperparameterObjectiveMode() ==
194 gp.evaluateLeaveOneOutEnergyAndGradientFromGeometry(
195 w, geometry, x, x_ind, y, energy_and_gradient);
196 return;
197 }
198 if (gp.getHyperparameterObjectiveMode() ==
200 gp.evaluateLocalNeighborhoodLooEnergyAndGradientFromGeometry(
201 w, geometry, x, x_ind, y, energy_and_gradient);
202 return;
203 }
204 gp.evaluateEnergyAndGradientFromGeometry(w, geometry, x, x_ind, y,
205 energy_and_gradient);
206 }
207
208 double evaluateEnergy(const Eigen::VectorXd& w, const EigenMatrix& x,
209 const Eigen::VectorXd& x_ind,
210 const Eigen::VectorXd& y)
211 {
212 if (gp.getHyperparameterObjectiveMode() ==
214 double energy = 0.0;
215 Eigen::VectorXd gradient;
216 EnergyAndGradient energy_and_gradient(energy, gradient);
217 gp.evaluateLeaveOneOutEnergyAndGradientFromGeometry(
218 w, geometry, x, x_ind, y, energy_and_gradient);
219 return energy_and_gradient.energy;
220 }
221 if (gp.getHyperparameterObjectiveMode() ==
223 return gp.evaluateLocalNeighborhoodLooEnergy(w, x, x_ind, y);
224 }
225 return gp.evaluateEnergyFromGeometry(w, geometry, x, x_ind, y);
226 }
227
228 bool evaluateGradientAfterEnergy(const Eigen::VectorXd& w,
229 const EigenMatrix& x,
230 const Eigen::VectorXd& x_ind,
231 const Eigen::VectorXd& y,
232 Eigen::VectorXd& gradient)
233 {
234 if (gp.getHyperparameterObjectiveMode() ==
236 gp.getHyperparameterObjectiveMode() ==
238 return false;
239 }
240 return gp.evaluateGradientAfterEnergyFromGeometry(w, geometry, x, x_ind,
241 y, gradient);
242 }
243
244 bool evaluateDirectionalCurvature(const Eigen::VectorXd& x_ind,
245 const EigenMatrix& x,
246 const Eigen::VectorXd& y,
247 const Eigen::VectorXd& direction,
248 double& curvature)
249 {
250 return gp.evaluateDirectionalCurvature(x_ind, x, y, direction,
251 curvature, &geometry);
252 }
253
254 [[nodiscard]] bool exactNlmlHessianVectorAvailable() const
255 {
256 return gp.exactNlmlHessianVectorAvailable();
257 }
258
259 bool evaluateNlmlHessianVector(const Eigen::VectorXd& x_ind,
260 const EigenMatrix& x,
261 const Eigen::VectorXd& y,
262 const Eigen::VectorXd& direction,
263 Eigen::VectorXd& product)
264 {
265 return gp.evaluateNlmlHessianVector(x_ind, x, y, direction, product,
266 &geometry);
267 }
268};
269
270#ifdef GPR_LINALG_SCALAPACK
271struct CanonicalDistributedMapObjective {
272 GaussianProcessRegression& gp;
273 const TrainingKernelGeometry& geometry;
274
275 void evaluateEnergyAndGradient(const Eigen::VectorXd& w,
276 const EigenMatrix& x,
277 const Eigen::VectorXd& x_ind,
278 const Eigen::VectorXd& y,
279 EnergyAndGradient& energy_and_gradient)
280 {
281 const auto process_group = gp.mpiContext();
282
283 double energy = std::numeric_limits<double>::quiet_NaN();
284 Eigen::VectorXd gradient(w.size());
285 EnergyAndGradient local(energy, gradient);
286 if (gp.getHyperparameterObjectiveMode() ==
287 HyperparameterObjectiveMode::LOO) {
288 gp.evaluateLeaveOneOutEnergyAndGradientFromGeometry(
289 w, geometry, x, x_ind, y, local);
290 } else if (gp.getHyperparameterObjectiveMode() ==
291 HyperparameterObjectiveMode::LOCAL_LOO) {
292 // Already an MPI collective internally (round-robin geometry
293 // partition + ordered_sum_bcast), so every rank already holds
294 // the identical energy/gradient here; the Bcast below is a
295 // harmless no-op that keeps this branch uniform with the
296 // other two objectives.
297 gp.evaluateLocalNeighborhoodLooEnergyAndGradientFromGeometry(
298 w, geometry, x, x_ind, y, local);
299 } else {
300 gp.evaluateEnergyAndGradientFromGeometry(w, geometry, x, x_ind, y,
301 local);
302 }
303 energy = local.energy;
304 if (local.gradient.size() == w.size()) {
305 gradient = local.gradient;
306 } else {
307 gradient.setZero();
308 }
309
310 MPI_Bcast(&energy, 1, MPI_DOUBLE, 0, process_group.comm);
311 MPI_Bcast(gradient.data(), static_cast<int>(gradient.size()),
312 MPI_DOUBLE, 0, process_group.comm);
313 energy_and_gradient.energy = energy;
314 energy_and_gradient.gradient = gradient;
315 }
316
317 double evaluateEnergy(const Eigen::VectorXd& w, const EigenMatrix& x,
318 const Eigen::VectorXd& x_ind,
319 const Eigen::VectorXd& y)
320 {
321 const auto process_group = gp.mpiContext();
322
323 double energy = 0.0;
324 if (gp.getHyperparameterObjectiveMode() ==
325 HyperparameterObjectiveMode::LOO) {
326 Eigen::VectorXd gradient;
327 EnergyAndGradient local(energy, gradient);
328 gp.evaluateLeaveOneOutEnergyAndGradientFromGeometry(
329 w, geometry, x, x_ind, y, local);
330 energy = local.energy;
331 } else if (gp.getHyperparameterObjectiveMode() ==
332 HyperparameterObjectiveMode::LOCAL_LOO) {
333 energy = gp.evaluateLocalNeighborhoodLooEnergy(w, x, x_ind, y);
334 } else {
335 energy = gp.evaluateEnergyFromGeometry(w, geometry, x, x_ind, y);
336 }
337 MPI_Bcast(&energy, 1, MPI_DOUBLE, 0, process_group.comm);
338 return energy;
339 }
340
341 bool evaluateGradientAfterEnergy(const Eigen::VectorXd& w,
342 const EigenMatrix& x,
343 const Eigen::VectorXd& x_ind,
344 const Eigen::VectorXd& y,
345 Eigen::VectorXd& gradient)
346 {
347 if (gp.getHyperparameterObjectiveMode() ==
348 HyperparameterObjectiveMode::LOO ||
349 gp.getHyperparameterObjectiveMode() ==
350 HyperparameterObjectiveMode::LOCAL_LOO) {
351 return false;
352 }
353
354 const auto process_group = gp.mpiContext();
355 bool ok = gp.evaluateGradientAfterEnergyFromGeometry(
356 w, geometry, x, x_ind, y, gradient);
357 int ok_int = ok ? 1 : 0;
358 if (!ok || gradient.size() != w.size()) {
359 gradient = Eigen::VectorXd::Zero(w.size());
360 }
361 MPI_Bcast(&ok_int, 1, MPI_INT, 0, process_group.comm);
362 MPI_Bcast(gradient.data(), static_cast<int>(gradient.size()),
363 MPI_DOUBLE, 0, process_group.comm);
364 return ok_int != 0 && gradient.allFinite();
365 }
366
367 bool evaluateDirectionalCurvature(const Eigen::VectorXd& x_ind,
368 const EigenMatrix& x,
369 const Eigen::VectorXd& y,
370 const Eigen::VectorXd& direction,
371 double& curvature)
372 {
373 const auto process_group = gp.mpiContext();
374 bool ok = gp.evaluateDirectionalCurvature(x_ind, x, y, direction,
375 curvature, &geometry);
376 int ok_int = ok ? 1 : 0;
377 if (!ok) {
378 curvature = std::numeric_limits<double>::quiet_NaN();
379 }
380 MPI_Bcast(&ok_int, 1, MPI_INT, 0, process_group.comm);
381 MPI_Bcast(&curvature, 1, MPI_DOUBLE, 0, process_group.comm);
382 return ok_int != 0 && std::isfinite(curvature);
383 }
384};
385#endif
386
387} // namespace
388
390{
391 return typeid(*this) == typeid(GaussianProcessRegression);
392}
393
394namespace {
395
396bool sameMatrix(const Eigen::MatrixXd& a, const Eigen::MatrixXd& b)
397{
398 return a.rows() == b.rows() && a.cols() == b.cols() &&
399 (a.array() == b.array()).all();
400}
401
402bool sameAtomicEnvironmentGeometry(const AtomsConfiguration& left,
403 const AtomsConfiguration& right)
404{
405 const auto equal = [](const auto& a, const auto& b) {
406 return a.rows() == b.rows() && a.cols() == b.cols() &&
407 (a.size() == 0 ||
408 std::equal(a.data(), a.data() + a.size(), b.data()));
409 };
410 if (!equal(left.atomicNrs, right.atomicNrs) ||
411 !equal(left.is_frozen, right.is_frozen))
412 return false;
413 if (left.is_frozen.size() == 0) return true;
414 if (left.positions.size() != right.positions.size() ||
415 left.positions.size() != 3 * left.is_frozen.size())
416 return false;
417 for (Eigen::Index atom = 0; atom < left.is_frozen.size(); ++atom) {
418 if (left.is_frozen.data()[atom] == MOVING_ATOM) continue;
419 for (Eigen::Index axis = 0; axis < 3; ++axis)
420 if (left.positions.data()[3 * atom + axis] !=
421 right.positions.data()[3 * atom + axis])
422 return false;
423 }
424 return true;
425}
426
427// An empty mask and an all-true mask describe the same fitted tangent space.
428std::vector<bool> canonicalMask(std::vector<bool> mask)
429{
430 if (std::all_of(mask.begin(), mask.end(), [](bool on) { return on; }))
431 mask.clear();
432 return mask;
433}
434
435bool sameSettings(const ScgOptimizationSettings& a,
437{
438 return a.common.check_derivative == b.common.check_derivative &&
439 a.common.max_iter == b.common.max_iter &&
440 a.common.tolerance_func == b.common.tolerance_func &&
441 a.common.tolerance_sol == b.common.tolerance_sol &&
442 a.lambda_limit == b.lambda_limit && a.lambda == b.lambda &&
443 a.use_tail_lower_barrier == b.use_tail_lower_barrier &&
444 a.tail_lower_barrier == b.tail_lower_barrier &&
445 a.curvature_mode == b.curvature_mode &&
446 a.model_profile == b.model_profile &&
447 a.map_prior_weight_mode == b.map_prior_weight_mode &&
448 a.map_use_configured_magn_prior == b.map_use_configured_magn_prior &&
449 a.map_use_lognormal_magn_prior == b.map_use_lognormal_magn_prior &&
450 a.map_magn_prior_mu == b.map_magn_prior_mu &&
451 a.map_magn_prior_s2 == b.map_magn_prior_s2 &&
452 a.map_magn_prior_nu == b.map_magn_prior_nu &&
453 a.map_use_configured_lengthscale_prior ==
454 b.map_use_configured_lengthscale_prior &&
455 a.map_lengthscale_prior_mu == b.map_lengthscale_prior_mu &&
456 a.map_lengthscale_prior_s2 == b.map_lengthscale_prior_s2 &&
457 a.map_lengthscale_prior_nu == b.map_lengthscale_prior_nu &&
458 a.stationarity_step_stop == b.stationarity_step_stop &&
459 canonicalMask(a.active_parameters) ==
460 canonicalMask(b.active_parameters);
461}
462
463template <typename Fit>
464bool samePriors(const Fit& last, SexpatCF& kernel)
465{
466 const PriorBase gaussian = kernel.getPriorParametersGaussian();
467 const PriorBase sqrtt = kernel.getPriorParametersSqrtt();
468 return last.prior_gaussian[0] == gaussian.getMu() &&
469 last.prior_gaussian[1] == gaussian.getS2() &&
470 last.prior_gaussian[2] == gaussian.getNu() &&
471 last.prior_sqrtt[0] == sqrtt.getMu() &&
472 last.prior_sqrtt[1] == sqrtt.getS2() &&
473 last.prior_sqrtt[2] == sqrtt.getNu();
474}
475
476} // namespace
477
478bool GaussianProcessRegression::subsetFitUnchanged(
479 const Observation& fit_observation) const
480{
481 const ConvergedSubsetFit& last = converged_subset_fit_;
482 if (!skip_unchanged_subset_fit_ || !last.valid || !sexpat_cov_func ||
483 !lik_gaussian)
484 return false;
485 // Bitwise equality of the rows, the theta, the likelihood noise and the
486 // configuration that define the objective and its start.
487 return last.optimization_mode == hyperparameter_optimization_mode_ &&
488 last.objective_mode == hyperparameter_objective_mode_ &&
489 last.lengthscale_floor == lengthscale_floor_ &&
490 last.kappa_max == kappa_max_ &&
491 last.principled_nugget == principled_nugget_ &&
492 last.entry_mask ==
493 canonicalMask(scg_opt_settings.active_parameters) &&
494 sameSettings(last.settings, scg_opt_settings) &&
495 last.optimize_sigma2 == lik_gaussian->getOptimizeSigma2() &&
496 last.constant_sigma2 ==
497 (const_cov_fun ? const_cov_fun->getConstSigma2() : 0.0) &&
498 last.jitter_sigma2 == jitter_sigma2 &&
499 last.model_profile == model_profile_ &&
500 last.hssvd_backend == use_hssvd_backend_ &&
501 detail::sameSexpatGeometry(last.atoms_config, atoms_config) &&
502 detail::sameSexpatGeometry(
503 last.kernel_configuration, sexpat_cov_func->getConfInfo(),
504 last.far_field_radius, sexpat_cov_func->farFieldRadius()) &&
505 samePriors(last, *sexpat_cov_func) &&
506 last.sigma2 == lik_gaussian->getSigma2() &&
507 last.theta == sexpat_cov_func->combineParameters() &&
508 sameMatrix(last.subset.R, fit_observation.R) &&
509 sameMatrix(last.subset.E, fit_observation.E) &&
510 sameMatrix(last.subset.G, fit_observation.G);
511}
512
513void GaussianProcessRegression::recordConvergedSubsetFit(
514 const Observation& fit_observation, const std::vector<bool>& entry_mask)
515{
516 if (!skip_unchanged_subset_fit_ || !sexpat_cov_func || !lik_gaussian)
517 return;
518 ConvergedSubsetFit& last = converged_subset_fit_;
519 last.valid = true;
520 last.subset = fit_observation;
521 last.theta = sexpat_cov_func->combineParameters();
522 last.sigma2 = lik_gaussian->getSigma2();
523 last.entry_mask = canonicalMask(entry_mask);
524 last.optimization_mode = hyperparameter_optimization_mode_;
525 last.objective_mode = hyperparameter_objective_mode_;
526 last.lengthscale_floor = lengthscale_floor_;
527 last.kappa_max = kappa_max_;
528 last.principled_nugget = principled_nugget_;
529 last.settings = scg_opt_settings;
530 last.settings.active_parameters = canonicalMask(entry_mask);
531 const PriorBase gaussian = sexpat_cov_func->getPriorParametersGaussian();
532 const PriorBase sqrtt = sexpat_cov_func->getPriorParametersSqrtt();
533 last.prior_gaussian[0] = gaussian.getMu();
534 last.prior_gaussian[1] = gaussian.getS2();
535 last.prior_gaussian[2] = gaussian.getNu();
536 last.prior_sqrtt[0] = sqrtt.getMu();
537 last.prior_sqrtt[1] = sqrtt.getS2();
538 last.prior_sqrtt[2] = sqrtt.getNu();
539 last.optimize_sigma2 = lik_gaussian->getOptimizeSigma2();
540 last.constant_sigma2 =
541 const_cov_fun ? const_cov_fun->getConstSigma2() : 0.0;
542 last.jitter_sigma2 = jitter_sigma2;
543 last.model_profile = model_profile_;
544 last.hssvd_backend = use_hssvd_backend_;
545 last.atoms_config = atoms_config;
546 last.kernel_configuration = sexpat_cov_func->getConfInfo();
547 last.far_field_radius = sexpat_cov_func->farFieldRadius();
548}
549
551{
552 const auto optimize_start = std::chrono::steady_clock::now();
553 const double solve0 = linalg::teamSolveWallSeconds();
554 const double factor0 = linalg::teamFactorWallSeconds();
555 const double eigen0 = PhaseTimers::eigensolve_seconds;
556 const double kernel0 = PhaseTimers::assembly_seconds;
557 const double gradient0 = PhaseTimers::gradient_seconds;
558 const double curvature0 = PhaseTimers::curvature_seconds;
559 const double energy0 = PhaseTimers::energy_seconds;
560 const double subset0 = PhaseTimers::subset_seconds;
561 const double cache0 = PhaseTimers::cache_seconds;
562 const double descriptor0 = PhaseTimers::descriptor_seconds;
563 const double posterior0 = PhaseTimers::posterior_seconds;
564 struct ExclusiveOptimize {
565 std::chrono::steady_clock::time_point start;
566 double solve0, factor0, eigen0, kernel0, gradient0, curvature0, energy0,
567 subset0, cache0, descriptor0, posterior0;
568 ~ExclusiveOptimize()
569 {
570 const double wall = std::chrono::duration<double>(
571 std::chrono::steady_clock::now() - start)
572 .count();
573 const double nested =
574 (linalg::teamSolveWallSeconds() - solve0) +
575 (linalg::teamFactorWallSeconds() - factor0) +
578 (PhaseTimers::gradient_seconds - gradient0) +
579 (PhaseTimers::curvature_seconds - curvature0) +
580 (PhaseTimers::energy_seconds - energy0) +
581 (PhaseTimers::subset_seconds - subset0) +
582 (PhaseTimers::cache_seconds - cache0) +
583 (PhaseTimers::descriptor_seconds - descriptor0) +
584 (PhaseTimers::posterior_seconds - posterior0);
585 PhaseTimers::schedule_seconds += std::max(0.0, wall - nested);
586 }
587 } exclusive_optimize{optimize_start, solve0, factor0, eigen0,
588 kernel0, gradient0, curvature0, energy0,
589 subset0, cache0, descriptor0, posterior0};
590 detail::requireJointTrainingObservation(
591 observation, "GaussianProcessRegression::optimize");
592 if (wallClockLimitReached()) {
593 failedOptimizer = true;
594 last_fit_stop_reason_ = "wall-clock limit";
595 return;
596 }
597 if (atomic_environment_model_) {
599 fitAtomicEnvironmentModel(observation, true);
600 return;
601 }
602 fitted_hyperparameter_density_.reset();
604 const bool select_components = hasPendingResidualModelRefit();
605 const auto active =
606 select_components
607 ? std::vector<bool>(sexpat_cov_func->getLengthScaleRef().size(),
608 true)
609 : active_refit_lengths_;
610 const bool skipped_setup = active_refit_setup_skipped_;
612 const bool fitted = fitActivePosteriorImpl(
613 observation, active, select_components, select_components);
614 // An independent, anchor-conditioned residual expands the retained
615 // posterior even when both components use the pair primitive. The
616 // fitted candidate evidence determines which correction is retained.
617 if (fitted) {
618 has_been_optimized_ = true;
619 return;
620 }
621 active_posterior_.reset();
622 mode_refit_policy_.reset();
623 if (skipped_setup)
624 setHyperparameters(observation, atoms_config, false, false, false);
625 if (report_level >= 1)
626 log_man << "Active correction did not converge; refitting all GP "
627 "hyperparameters.\n";
628 }
629 active_posterior_.reset();
630 if (has_been_optimized_ && scg_opt_settings.active_parameters.empty()) {
631 // A full refit releases the seed's identifiability mask. Active
632 // refits carry an explicit mask or an anchor-conditioned residual;
633 // a changed target must not remain confined to the seed's amplitude.
634 scg_opt_settings.active_parameters =
635 fullRefitMask(sexpat_cov_func.get(), lik_gaussian.get());
636 }
637 if (sexpat_cov_func &&
638 lengthScaleTiesActive(sexpat_cov_func->getLengthScaleRef().size())) {
639 // Subset selection and identifiability use the same constrained
640 // kernel as the objective, independently of tied members' inputs.
641 Eigen::VectorXd tied = sexpat_cov_func->combineParameters();
643 setParameters(tied);
644 }
645 // The leave-one-out objectives use the pair-distance training geometry
646 // that a composite chart kernel does not have; a charted Sexpat is
647 // fitted on the marginal likelihood, whose gradient the chart kernel
648 // provides in closed form, for the duration of this call.
649 struct ObjectiveOverride {
651 const HyperparameterObjectiveMode saved;
652 ObjectiveOverride(HyperparameterObjectiveMode& s,
654 : slot(s), saved(s)
655 {
656 slot = mode;
657 }
658 ~ObjectiveOverride()
659 {
660 slot = saved;
661 }
662 };
663 std::optional<ObjectiveOverride> chart_objective;
664 if (sexpat_cov_func && sexpat_cov_func->usesManifoldChart() &&
665 hyperparameter_objective_mode_ != HyperparameterObjectiveMode::NLML) {
666 chart_objective.emplace(hyperparameter_objective_mode_,
668 }
669 has_been_optimized_ = true;
670 last_warm_start_infeasible_ = false;
671 // A length scale held for a pooled subset is held for that fit only.
672 struct ReleaseHeldLengthScales {
673 std::vector<bool>& mask;
674 const bool entry_empty;
675 std::vector<std::size_t> slots;
676 ~ReleaseHeldLengthScales()
677 {
678 if (slots.empty()) return;
679 if (entry_empty) {
680 mask.clear();
681 return;
682 }
683 for (const std::size_t slot: slots)
684 if (slot < mask.size()) mask[slot] = true;
685 }
686 } held_length_scales{scg_opt_settings.active_parameters,
687 scg_opt_settings.active_parameters.empty(),
688 {}};
689
690 if (hyperparameter_optimization_mode_ ==
692 optimizeLaplaceINLA(observation);
693 return;
694 }
695
696 if (use_chem_factorized_hyper_) {
697 optimizeChemistryFactorized(observation);
698 return;
699 }
700
701 const int max_retries = 3; // To prevent potential infinite loops
702 int retry_count = 0;
703 const Eigen::VectorXd fallback_parameters =
704 sexpat_cov_func->combineParameters();
705 bool retry_full_observation = false;
706 bool optimizer_attempted = false;
707
708 while (retry_count <= max_retries) {
709 optimizer_state_->last_input_marginal_likelihood_nonfinite = false;
710 if (wallClockLimitReached()) {
711 failedOptimizer = true;
712 last_fit_stop_reason_ = "wall-clock limit";
713 break;
714 }
715 // 1. Select a subset of data for efficient optimization based on the
716 // current history size.
717 Observation optimization_observation =
718 retry_full_observation ? observation
719 : selectOptimizationSubset(observation);
720 if (!retry_full_observation &&
721 optimization_row_pool_.size() ==
722 static_cast<std::size_t>(observation.R.rows()))
723 for (const std::size_t slot:
724 holdLengthScalesUnresolvedBySubset(optimization_observation))
725 held_length_scales.slots.push_back(slot);
726
727 // The minimizer depends on the selected rows and the start alone: an
728 // append that leaves both as the last converged fit left them has no
729 // objective to minimize, and the new rows are conditioned below at
730 // the fitted theta.
731 if (!retry_full_observation &&
732 subsetFitUnchanged(optimization_observation)) {
733 ++unchanged_subset_fit_skips_;
734 last_fit_evaluations_ = 0;
735 last_fit_budget_evaluations_ = 0;
736 failedOptimizer = false;
737 last_failed_fit_improved_ = false;
738 if (report_level >= 1) {
739 log_man << "The fit subset is unchanged since the last "
740 "converged fit; holding its hyperparameters.\n";
741 }
742 break;
743 }
744 const std::vector<bool> entry_mask = scg_opt_settings.active_parameters;
745 if (optimizer_attempted) PhaseTimers::recordFitRestart();
746 optimizer_attempted = true;
747
748 // 2. Run the numerical optimization on the subset.
749 // Pre-cache inverse distances: positions are fixed during optimization,
750 // only lengthscales change. This avoids redundant coordinate
751 // extractions and norm computations on every iteration.
752 {
754 sexpat_cov_func->cacheDistances(optimization_observation.R,
755 optimization_observation.R);
756 }
757 const Eigen::VectorXd fit_start = sexpat_cov_func->combineParameters();
758 const int fit_evaluations_before = PhaseTimers::objective_count;
759 Eigen::VectorXd optimized_parameters =
760 performHyperparameterOptimization(optimization_observation);
761 if (wallClockLimitReached()) {
762 sexpat_cov_func->clearDistanceCache();
763 failedOptimizer = true;
764 last_fit_stop_reason_ = "wall-clock limit";
765 setParameters(fallback_parameters);
766 break;
767 }
768 sexpat_cov_func->clearDistanceCache();
770 std::max(0, PhaseTimers::objective_count - fit_evaluations_before),
771 fit_start.size() > 0 &&
772 optimized_parameters.size() >= fit_start.size() &&
773 (optimized_parameters.head(fit_start.size()) - fit_start)
774 .cwiseAbs()
775 .maxCoeff() <= scg_opt_settings.common.tolerance_sol);
776
777 // A failed stationarity check can still leave a feasible improvement
778 // of the same MAP objective. Preserve it without reporting convergence.
779 if (failedOptimizer) {
780 // A rejected L-BFGS recovery already put the feasible SCG point
781 // in optimized_parameters. Keeping fallback_parameters here would
782 // discard that restore while the stop reason still names it.
783 const bool restored_scg_point =
784 optimizer_state_->last_fallback_rejected;
785 if (report_level >= 1) {
786 log_man << "Hyperparameter optimizer did not converge; "
787 << (restored_scg_point
788 ? "restoring the earlier SCG point.\n"
789 : (last_failed_fit_improved_
790 ? "retaining its feasible MAP "
791 "improvement.\n"
792 : "retaining the input "
793 "hyperparameters.\n"));
794 }
795 setParameters(last_failed_fit_improved_ || restored_scg_point
796 ? optimized_parameters
797 : fallback_parameters);
798 // The estimator is fixed by the configuration, not by the outcome
799 // of the previous attempt: a subset fit that stalls keeps its
800 // objective unless the subset carries no evaluable likelihood.
801 const bool escalate =
802 subset_failure_escalation_ || !last_failed_fit_evaluable_;
803 if (escalate && !retry_full_observation &&
804 optimization_observation.E.size() < observation.E.size()) {
805 retry_full_observation = true;
806 last_warm_start_infeasible_ = false;
807 scg_opt_settings.active_parameters =
808 fullRefitMask(sexpat_cov_func.get(), lik_gaussian.get());
809 mode_refit_policy_.reset();
810 if (report_level >= 1) {
811 log_man << "Retrying the failed subset fit with all "
812 << observation.E.size()
813 << " retained observations and length scales.\n";
814 }
815 continue;
816 }
817 // A non-finite marginal at the input theta is recorded when the
818 // retain above kept that input. A restored SCG point and a
819 // feasible MAP improvement are different points and keep their
820 // own stop reason. An illegal prior does not arrive here as a
821 // NaN: the density throws before it divides by nu or s2.
822 if (!restored_scg_point && !last_failed_fit_improved_ &&
823 optimizer_state_->last_input_marginal_likelihood_nonfinite) {
824 ++optimizer_state_->nonfinite_marginal_likelihood_rejections;
825 last_fit_stop_reason_ = "non-finite marginal likelihood";
826 }
827 break;
828 }
829
830 // 3. Set the new parameters so they can be monitored.
831 setParameters(optimized_parameters);
832 if (retry_full_observation) break;
833 {
834 const double gradient_tolerance =
835 std::min(scg_opt_settings.common.tolerance_func,
836 scg_opt_settings.common.tolerance_sol);
837 if (std::isfinite(last_fit_gradient_norm_) &&
838 last_fit_gradient_norm_ <= gradient_tolerance) {
839 recordConvergedSubsetFit(optimization_observation, entry_mask);
840 } else {
841 converged_subset_fit_.valid = false;
842 }
843 }
844
845 // 4. Monitor for instability. If it returns true, we need to retry.
846 if (use_hod) {
847 bool should_retry =
848 monitorAndAdaptHyperparameters(optimized_parameters);
849
850 if (should_retry) {
851 retry_count++;
852 if (report_level >= 1) {
853 log_man << "Instability detected. Re-running optimization "
854 "with an increased dataset. Attempt "
855 << retry_count << "/" << max_retries << ".\n";
856 }
857 } else {
858 // Stability is acceptable, optimization is complete.
859 if (report_level >= 1) {
860 log_man << "Hyperparameters appear stable. Finalizing "
861 "optimization.\n";
862 }
863 break; // Exit the while loop
864 }
865 } else {
866 // no oscillation check, just exit
867 break; // Exit the while loop
868 }
869 }
870
871 if (retry_count > max_retries) {
872 if (report_level >= 1) {
873 log_man << "Warning: Reached max retries for optimization due to "
874 "persistent instability.\n";
875 }
876 }
877 if (wallClockLimitReached()) return;
878
879 // 5. Update the model's internal state using the full dataset and the last
880 // successful set of hyperparameters.
881 updateModelWithFullData(observation);
882
884 !optimizer_state_->last_fallback_rejected) {
885 if (report_level >= 1) {
886 log_man << "Reverting to the last feasible hyperparameters after "
887 "full-dataset factorization failed.\n";
888 }
889 setParameters(fallback_parameters);
890 updateModelWithFullData(observation);
891 }
892
893 // RFF layered predict: rebuild the random-feature model on the
894 // freshly-fit kernel hyperparameters. Per-fit cost O(N D D_rff +
895 // D_rff^3); per-call mean predict cost then drops from O(N (D+1))
896 // to O(D_rff D), constant in N. Skipped when D_rff <= 0
897 // (default; bit-identical to main). The LaplacePosteriorStamp
898 // policy invalidates the slice/PSIS cache on the same boundary
899 // so RFF stays in sync with the variance arm.
900 // Skip the layered build when updateModelWithFullData already replaced
901 // the exact solve with RFF (rff_replaces_exact_): the model is built
902 // and the eigensolve was skipped, so rebuilding here would be pure
903 // redundant work. The layered path remains for the below-cutoff case
904 // where the exact decompose ran and RFF only accelerates the mean.
905 if (rff_features_requested_ > 0 && is_decomposed_succesfully &&
906 observation.E.size() > 0 && !rff_replaces_exact_) {
907 // Overdetermined-BLR guard: the RFF design matrix has
908 // n_obs * (1 + D) rows and D_rff columns. The Bayesian linear
909 // regression needs the system to be at least 2x overdetermined
910 // for the BLR posterior mean to be well-conditioned (otherwise
911 // the predict mean is dominated by the prior and produces NaN
912 // gradients downstream of the dimer). Skip the build until
913 // the observation count crosses that threshold; the dispatch
914 // then falls back to the cheap-mean MAP predict for the
915 // early outer iters (when N is small enough that MAP is
916 // already cheap anyway).
917 const Eigen::Index n_obs = observation.R.rows();
918 const Eigen::Index D = observation.R.cols();
919 const Eigen::Index n_design = n_obs * (1 + D);
920 if (n_design < 2 * static_cast<Eigen::Index>(rff_features_requested_)) {
921 if (report_level >= 1) {
922 log_man << "RFF layered predict: skipping build (n_design="
923 << n_design
924 << " < 2 * D_rff=" << 2 * rff_features_requested_
925 << "); MAP cross-cov path retained for this iter.\n";
926 }
927 rff_features_ = 0;
928 } else {
929 try {
930 buildRFFModel(observation, rff_features_requested_);
931 if (report_level >= 1) {
932 log_man << "RFF layered predict: built D_rff="
933 << rff_features_requested_ << " features on "
934 << n_obs << " observations (n_design=" << n_design
935 << ", backend="
936 << rff_model_.normalEquationBackendName() << ").\n";
937 }
938 } catch (const std::exception& ex) {
939 // RFF build failure is non-fatal: the dispatch falls
940 // back to MAP cross-cov + matvec. Log and continue.
941 rff_features_ = 0;
942 if (report_level >= 1) {
943 log_man << "RFF build failed: " << ex.what()
944 << "; falling back to exact GP predict.\n";
945 }
946 }
947 }
948 }
949}
950
953 const Observation& observation)
954{
955 detail::requireJointTrainingObservation(
956 observation, "GaussianProcessRegression::optimizeMarginalLikelihood");
957 if (model_profile_ != GPModelProfile::EXTENDED)
958 throw std::logic_error(
959 "prior-free marginal likelihood requires the EXTENDED model "
960 "profile");
961 if (atomic_environment_model_)
962 throw std::logic_error(
963 "prior-free marginal likelihood is unavailable for the atomic "
964 "environment model");
965
966 sexpat_cov_func->clearHierarchicalPrior();
967 sexpat_cov_func->clearPcLengthScalePrior();
968 sexpat_cov_func->setUseLogNormalMagnPrior(false);
969 lik_gaussian->setOptimizeSigma2(true);
970 // The companion fixed-parameter update is a Cholesky bordering
971 // operation, so retain that exact factor as the fitted posterior.
972 setHssvdBackend(false);
974
975 struct Restore {
976 bool& flag;
977 bool saved;
978 int& history;
979 int saved_history;
980 int& latest;
981 int saved_latest;
982 bool& scg_stalled;
983 bool saved_scg_stalled;
984 ScgStallScope& scg_stall_scope;
985 ScgStallScope saved_scg_stall_scope;
986 ~Restore()
987 {
988 flag = saved;
989 history = saved_history;
990 latest = saved_latest;
991 scg_stalled = saved_scg_stalled;
992 scg_stall_scope = std::move(saved_scg_stall_scope);
993 }
994 } restore{unregularized_marginal_likelihood_,
995 unregularized_marginal_likelihood_,
996 fps_options.history,
997 fps_options.history,
998 fps_options.latest_points,
999 fps_options.latest_points,
1000 scg_stalled_,
1001 scg_stalled_,
1002 scg_stall_scope_,
1003 scg_stall_scope_};
1004 // Switching to the prior-free marginal-likelihood objective or enabling
1005 // the trailing noise parameter changes the objective landscape and
1006 // parameter dimension: any warm quasi-Newton session or SCG-stall state
1007 // from an earlier MAP fit no longer describes this problem. The latch
1008 // is cleared only after Restore has saved the caller's copy.
1010 unregularized_marginal_likelihood_ = true;
1011 scg_stalled_ = false;
1012 scg_stall_scope_ = {};
1013 // This API fits the likelihood of exactly the supplied data, not the
1014 // adaptive optimization subset used by long-running searches.
1015 fps_options.history = static_cast<int>(observation.R.rows());
1016 fps_options.latest_points = 0;
1017 optimize(observation);
1018 int optimizer_restarts = 0;
1019 if (failedOptimizer) {
1020 // Safety net when the first start fails: if it did not reach a
1021 // decomposed signal-dominated iterate, reseed covariance and noise
1022 // scales from the observation's energy variance and descriptor
1023 // spread; otherwise continue from the retained feasible iterate
1024 // keeping its 3D quasi-Newton curvature memory.
1025 const int first_pass_iterations = last_fit_iterations_;
1026 if (!last_failed_fit_improved_ || !is_decomposed_succesfully ||
1027 !(lik_gaussian->getSigma2() > 0.0 &&
1028 lik_gaussian->getSigma2() < 1.0 &&
1029 std::isfinite(lik_gaussian->getSigma2()))) {
1030 const double noise_seed =
1031 (jitter_sigma2 > 0.0 && std::isfinite(jitter_sigma2))
1032 ? std::max(1.0e-4, jitter_sigma2)
1033 : 1.0e-4;
1034 // Reseeding installs the configured length-scale priors again.
1035 auto prior_state = sexpat_cov_func->priorState();
1036 setHyperparameters(observation, atoms_config, true, true, true);
1037 sexpat_cov_func->restorePriorState(std::move(prior_state));
1038 lik_gaussian->setSigma2(noise_seed);
1039 sigma2 = trainingToPhysicalNoiseVariance(noise_seed);
1040 invalidateLikelihoodNoiseDependentState();
1041 scg_stalled_ = false;
1042 scg_stall_scope_ = {};
1044 }
1045 failedOptimizer = false;
1046 ++optimizer_restarts;
1047 optimize(observation);
1048 last_fit_iterations_ += first_pass_iterations;
1049 }
1050 last_fit_restarts_ = optimizer_restarts;
1051 if (failedOptimizer)
1052 throw std::runtime_error(
1053 "prior-free marginal-likelihood optimizer did not converge");
1056 throw std::runtime_error(
1057 "prior-free marginal-likelihood fit did not produce a posterior");
1058
1060 const double output_scale = outputScale();
1061 if (!(output_scale > 0.0) || !std::isfinite(output_scale))
1062 throw std::runtime_error(
1063 "prior-free marginal-likelihood output scale is invalid");
1064 Eigen::Index report_rows = b.size();
1065 double log_determinant = 2.0 * trainingSolver().halfLogDeterminant();
1066 double quadratic = b.squaredNorm();
1067 if (rigid_deflation_.isActiveForFullOrder(R_matrix.rows())) {
1068 report_rows = R_matrix.rows();
1069 log_determinant += rigid_deflation_.rigid_logdet_only;
1070 quadratic += rigid_deflation_.rigid_quad_term;
1071 }
1072#ifdef GPR_LINALG_KOKKOS
1073 if (hasDevicePosterior()) {
1074 const auto parts = device_posterior_->objectiveParts();
1075 report_rows = device_posterior_->order();
1076 log_determinant = 2.0 * parts[0];
1077 quadratic = parts[1];
1078 }
1079#endif
1080 const double physical_log_scale =
1081 static_cast<double>(report_rows) * 2.0 * numerics::log(output_scale);
1082 report.log_determinant = log_determinant + physical_log_scale;
1083 report.quadratic = quadratic;
1084 report.objective =
1085 0.5 * static_cast<double>(report_rows) * numerics::log(2.0 * M_PI) +
1086 0.5 * report.log_determinant + 0.5 * report.quadratic;
1087 if (!std::isfinite(report.objective))
1088 throw std::runtime_error(
1089 "prior-free marginal-likelihood objective is not finite");
1090 report.signal_variance =
1091 trainingToPhysicalNoiseVariance(sexpat_cov_func->getMagnSigma2());
1092 report.noise_variance = sigma2;
1093 report.length_scales = Eigen::Map<const Eigen::VectorXd>(
1094 sexpat_cov_func->getLengthScaleRef().data(),
1095 sexpat_cov_func->getLengthScaleRef().size());
1096 report.iterations = last_fit_iterations_;
1097 report.optimizer_restarts = optimizer_restarts;
1098 return report;
1099}
1100
1102 const Observation& full_observation)
1103{
1104 detail::requireJointTrainingObservation(
1105 full_observation,
1106 "GaussianProcessRegression::appendFixedHyperparameters");
1107 const Eigen::Index old_n = full_fit_observations_.R.rows();
1108 if (!has_been_optimized_ || !is_decomposed_succesfully || old_n <= 0 ||
1109 full_observation.R.rows() <= old_n ||
1110 full_observation.R.cols() != full_fit_observations_.R.cols() ||
1111 full_observation.G.cols() != full_fit_observations_.G.cols() ||
1112 !(full_observation.R.topRows(old_n).array() ==
1113 full_fit_observations_.R.array())
1114 .all() ||
1115 !(full_observation.E.topRows(old_n).array() ==
1116 full_fit_observations_.E.array())
1117 .all() ||
1118 !(full_observation.G.topRows(old_n).array() ==
1119 full_fit_observations_.G.array())
1120 .all() ||
1121 !trainingFactorAppendable(full_observation.R.rows())) {
1122 return false;
1123 }
1124
1125 struct RequireAppend {
1126 bool& flag;
1127 ~RequireAppend()
1128 {
1129 flag = false;
1130 }
1131 } require{require_factor_append_};
1132 const Observation previous_observation = full_fit_observations_;
1133 require_factor_append_ = true;
1134 try {
1135 updateModelWithFullData(full_observation);
1136 } catch (...) {
1137 require_factor_append_ = false;
1138 try {
1139 updateModelWithFullData(previous_observation);
1140 } catch (...) {
1141 // Preserve the original append exception for the C API boundary.
1142 }
1143 throw;
1144 }
1145 if (is_decomposed_succesfully) return true;
1146
1147 // A rejected border must leave the fitted posterior usable. The old
1148 // factor signature is still live because the append path commits L and C
1149 // only after the Schur complement factors successfully.
1150 require_factor_append_ = false;
1151 updateModelWithFullData(previous_observation);
1152 return false;
1153}
1154
1157 const Observation& held_out, const double nominal_probability)
1158{
1159 const double central_probability = 0.5 * (1.0 + nominal_probability);
1160 if (!(nominal_probability > 0.0 && nominal_probability < 1.0) ||
1161 !(central_probability < 1.0) || held_out.R.rows() <= 0 ||
1162 held_out.R.cols() <= 0 || held_out.G.rows() != held_out.R.rows() ||
1163 held_out.G.cols() != held_out.R.cols() || !held_out.R.allFinite() ||
1164 !held_out.G.allFinite()) {
1165 throw std::invalid_argument(
1166 "held-out force calibration requires finite matching positions "
1167 "and gradients and a nominal probability in (0,1)");
1168 }
1169
1170 Observation mean;
1171 mean.R = held_out.R;
1173 struct RestoreVarianceConvention {
1175 VarianceConvention saved;
1176 ~RestoreVarianceConvention()
1177 {
1178 model.setVarianceConvention(saved);
1179 }
1180 } restore_variance{*this, varianceConvention()};
1182 Observation variance;
1183 variance.R = held_out.R;
1185 if (mean.G.rows() != held_out.G.rows() ||
1186 mean.G.cols() != held_out.G.cols() ||
1187 variance.G.rows() != held_out.G.rows() ||
1188 variance.G.cols() != held_out.G.cols()) {
1189 throw std::runtime_error("held-out force prediction shape mismatch");
1190 }
1191
1192 const double reported_scale = reportedVarianceCalibrationFactor();
1193 if (!(reported_scale > 0.0) || !std::isfinite(reported_scale))
1194 throw std::runtime_error("posterior variance scale is invalid");
1195 const double quantile = math::DistributionFunctions().normalCDFInverse(
1196 central_probability, 0.0, 1.0);
1197 double sum = 0.0;
1198 double sumsq = 0.0;
1199 double sum_log_predictive_density = 0.0;
1200 std::size_t covered = 0;
1201 std::vector<double> standardized;
1202 standardized.reserve(static_cast<std::size_t>(held_out.G.size()));
1203 for (Eigen::Index row = 0; row < held_out.G.rows(); ++row) {
1204 for (Eigen::Index col = 0; col < held_out.G.cols(); ++col) {
1205 const double raw_variance = variance.G(row, col) / reported_scale;
1206 // A kernel may make symmetry-protected force components exactly
1207 // deterministic. They carry no calibration information when the
1208 // residual is also exactly zero, so omit them without introducing
1209 // a numerical variance floor.
1210 const double residual = mean.G(row, col) - held_out.G(row, col);
1211 if (raw_variance == 0.0 && residual == 0.0) continue;
1212 if (!(raw_variance > 0.0) || !std::isfinite(raw_variance))
1213 throw std::runtime_error(
1214 "held-out posterior force variance is not positive at "
1215 "component " +
1216 std::to_string(row * held_out.G.cols() + col) + ": " +
1217 std::to_string(raw_variance));
1218 // Force residual F_true-F_mean equals G_mean-G_true.
1219 const double z = residual / std::sqrt(raw_variance);
1220 if (!std::isfinite(z))
1221 throw std::runtime_error(
1222 "held-out standardized force residual is not finite");
1223 standardized.push_back(z);
1224 sum += z;
1225 sumsq += z * z;
1226 sum_log_predictive_density -=
1227 0.5 * (numerics::log(2.0 * M_PI * raw_variance) + z * z);
1228 if (std::abs(z) <= quantile) ++covered;
1229 }
1230 }
1231 if (standardized.empty())
1232 throw std::runtime_error(
1233 "held-out force calibration has no stochastic components");
1234
1236 report.components = standardized.size();
1237 report.nominal_probability = nominal_probability;
1238 report.posterior_variance_scale = reported_scale;
1240 sum / static_cast<double>(report.components);
1242 std::sqrt(sumsq / static_cast<double>(report.components));
1245 sum_log_predictive_density / static_cast<double>(report.components);
1246 report.empirical_coverage =
1247 static_cast<double>(covered) / static_cast<double>(report.components);
1248 std::size_t calibrated_covered = 0;
1249 for (const double z: standardized)
1250 if (std::abs(z) <= quantile * report.calibration_scale)
1251 ++calibrated_covered;
1252 report.calibrated_coverage = static_cast<double>(calibrated_covered) /
1253 static_cast<double>(report.components);
1254 return report;
1255}
1256
1271 const Observation& full_observation) const
1272{
1274 const int num_optimization_points = fps_options.history;
1275 const int num_latest_points = fps_options.latest_points;
1276 const int num_total_points = full_observation.R.rows();
1277 // TODO(rg): Make this a configurable parameter
1278 const double force_threshold = std::numeric_limits<double>::infinity();
1279 std::vector<int> valid_indices;
1280 valid_indices.reserve(num_total_points);
1281 std::vector<int> required_indices;
1282 const bool have_required =
1283 optimization_required_positions_.cols() == full_observation.R.cols();
1284
1285 const bool pooled =
1286 static_cast<int>(optimization_row_pool_.size()) == num_total_points;
1287 for (int i = 0; i < num_total_points; ++i) {
1288 bool required = false;
1289 if (have_required)
1290 for (Eigen::Index row = 0;
1291 row < optimization_required_positions_.rows(); ++row)
1292 if ((full_observation.R.row(i).array() ==
1293 optimization_required_positions_.row(row).array())
1294 .all()) {
1295 required = true;
1296 break;
1297 }
1298 if (!required && pooled &&
1299 !optimization_row_pool_[static_cast<std::size_t>(i)])
1300 continue;
1301 double max_force = 0.0;
1302 bool finite_force = true;
1303 for (int j = 0; j < full_observation.G.cols(); ++j) {
1304 const double component = full_observation.G(i, j);
1305 if (!std::isfinite(component)) {
1306 finite_force = false;
1307 break;
1308 }
1309 max_force = std::max(max_force, std::abs(component));
1310 }
1311 if (finite_force && max_force < force_threshold) {
1312 valid_indices.push_back(i);
1313 if (required) required_indices.push_back(i);
1314 }
1315 }
1316
1317 const int num_valid_points = valid_indices.size();
1318
1319 if (num_valid_points <= num_optimization_points) return valid_indices;
1320
1321 // --- Combined Latest + Farthest Point Sampling (FPS) on VALID points ---
1322 aux::Distance distance_calculator;
1323 std::vector<int> selected_indices = required_indices;
1324 std::unordered_set<int> selected_indices_set(required_indices.begin(),
1325 required_indices.end());
1326 const int actual_latest_points =
1327 std::min(num_latest_points, num_valid_points);
1328 const int subset_size =
1329 std::max({num_optimization_points, actual_latest_points,
1330 static_cast<int>(required_indices.size())});
1331
1332 // 1. Start with the 'num_latest_points' most recent *valid* points.
1333 for (int i = 0; i < actual_latest_points &&
1334 static_cast<int>(selected_indices.size()) < subset_size;
1335 ++i) {
1336 int current_idx = valid_indices[num_valid_points - 1 - i];
1337 if (selected_indices_set.insert(current_idx).second)
1338 selected_indices.push_back(current_idx);
1339 }
1340 const int num_fps_points_to_select =
1341 std::max(0, subset_size - static_cast<int>(selected_indices.size()));
1342
1343 if (num_fps_points_to_select > 0) {
1344 // --- FPS Implementation for the remaining points ---
1345 std::unordered_map<int, double> min_dists_map;
1346 const Eigen::Index n_cols = full_observation.R.cols();
1347
1348 // Pre-allocate reusable buffers outside loops
1349 FieldMatrixd candidate_coord(1, n_cols);
1350 FieldMatrixd ref_coord(1, n_cols);
1351 FieldMatrixd dist_matrix;
1352
1353 // Helper lambda to compute distance between two single-row coords
1354 auto compute_dist = [&](const FieldMatrixd& c1,
1355 const FieldMatrixd& c2) -> double {
1356 switch (fps_options.metric) {
1358 distance_calculator.dist_max1Dlog(
1359 c1, c2, this->atoms_config, dist_matrix);
1360 break;
1362 distance_calculator.dist_emd(c1, c2, this->atoms_config,
1363 dist_matrix);
1364 break;
1366 distance_calculator.dist_rmsd(c1, c2, this->atoms_config,
1367 dist_matrix);
1368 break;
1369 default:
1370 throw("Invalid distance metric for FPS.");
1371 }
1372 return dist_matrix(0, 0);
1373 };
1374
1375 // Initialize min_dists for all valid, unselected points
1376 for (int candidate_idx: valid_indices) {
1377 if (selected_indices_set.count(candidate_idx) == 0) {
1378 double current_min_dist = std::numeric_limits<double>::max();
1379 candidate_coord.row(0) = full_observation.R.row(candidate_idx);
1380
1381 for (int latest_idx: selected_indices) {
1382 ref_coord.row(0) = full_observation.R.row(latest_idx);
1383 current_min_dist =
1384 std::min(current_min_dist,
1385 compute_dist(candidate_coord, ref_coord));
1386 }
1387 min_dists_map[candidate_idx] = current_min_dist;
1388 }
1389 }
1390
1391 // 2. Iteratively select the remaining FPS points.
1392 for (int i = 0; i < num_fps_points_to_select; ++i) {
1393 std::vector<std::pair<int, double>> candidate_distances;
1394 candidate_distances.reserve(min_dists_map.size());
1395 for (auto const& [idx, dist]: min_dists_map) {
1396 candidate_distances.emplace_back(idx, dist);
1397 }
1398 const int farthest_point_idx =
1399 chooseFarthestPointDeterministic(candidate_distances);
1400
1401 if (farthest_point_idx != -1) {
1402 selected_indices.push_back(farthest_point_idx);
1403 selected_indices_set.insert(farthest_point_idx);
1404 min_dists_map.erase(farthest_point_idx);
1405
1406 ref_coord.row(0) = full_observation.R.row(farthest_point_idx);
1407
1408 for (auto& [candidate_idx, current_min_dist]: min_dists_map) {
1409 candidate_coord.row(0) =
1410 full_observation.R.row(candidate_idx);
1411 current_min_dist =
1412 std::min(current_min_dist,
1413 compute_dist(candidate_coord, ref_coord));
1414 }
1415 } else {
1416 break;
1417 }
1418 }
1419 }
1420
1421 std::sort(selected_indices.begin(), selected_indices.end());
1422 return selected_indices;
1423}
1424
1425std::vector<std::size_t>
1427 const Observation& subset)
1428{
1429 // A pooled subset is the search's own footprint, and those rows can
1430 // lie a few thousandths of an angstrom apart. Fitting a length scale
1431 // they do not resolve moves it by an order of magnitude on the priors
1432 // alone; the posterior conditioned at those parameters is flat beside
1433 // the rows, and its curvature is the prior mean's. Such a length scale
1434 // keeps its value. Signal and likelihood variances still fit.
1435 if (!sexpat_cov_func || sexpat_cov_func->usesManifoldChart() ||
1436 sexpat_cov_func->usesGeodesicHeatKernel())
1437 return {};
1438 std::vector<bool> resolved =
1439 lengthScalesResolvedByRows(*sexpat_cov_func, subset.R);
1440 const Eigen::Index count = static_cast<Eigen::Index>(resolved.size());
1441 if (lengthScaleTiesActive(count)) {
1442 // A tie group moves as one length scale.
1443 std::vector<bool> group(resolved.size(), false);
1444 for (Eigen::Index t = 0; t < count; ++t)
1445 if (resolved[static_cast<std::size_t>(t)])
1446 group[static_cast<std::size_t>(
1447 length_scale_ties_.leader[static_cast<std::size_t>(t)])] =
1448 true;
1449 for (Eigen::Index t = 0; t < count; ++t)
1450 resolved[static_cast<std::size_t>(t)] =
1451 group[static_cast<std::size_t>(
1452 length_scale_ties_.leader[static_cast<std::size_t>(t)])];
1453 }
1454 if (std::all_of(resolved.begin(), resolved.end(),
1455 [](bool value) { return value; }))
1456 return {};
1457 std::vector<bool>& mask = scg_opt_settings.active_parameters;
1458 if (mask.empty())
1459 mask = fullRefitMask(sexpat_cov_func.get(), lik_gaussian.get());
1460 if (mask.size() < 1 + resolved.size()) return {};
1461 std::vector<std::size_t> held_slots;
1462 for (Eigen::Index k = 0; k < count; ++k) {
1463 const std::size_t slot = static_cast<std::size_t>(1 + k);
1464 if (resolved[static_cast<std::size_t>(k)] || !mask[slot]) continue;
1465 mask[slot] = false;
1466 held_slots.push_back(slot);
1467 }
1468 const auto held = held_slots.size();
1469 if (held > 0 && report_level >= 1)
1470 log_man << "Hyperparameter subset: " << subset.R.rows()
1471 << " rows span less than one length scale in " << held << " of "
1472 << count
1473 << " pair types; those length scales keep their values.\n";
1474 return held_slots;
1475}
1476
1491 const Observation& full_observation) const
1492{
1493 Observation optimization_observation;
1494 const int num_total_points = full_observation.R.rows();
1495 const bool energy_is_row_vector =
1496 full_observation.E.rows() == 1 &&
1497 full_observation.E.cols() == num_total_points;
1498 const std::vector<int> selected_indices =
1499 selectOptimizationSubsetRows(full_observation);
1500 const int num_final = selected_indices.size();
1501 optimization_observation.R.resize(num_final, full_observation.R.cols());
1502 optimization_observation.R.setZero();
1503 if (energy_is_row_vector) {
1504 optimization_observation.E.resize(1, num_final);
1505 } else {
1506 optimization_observation.E.resize(num_final, full_observation.E.cols());
1507 }
1508 optimization_observation.E.setZero();
1509 optimization_observation.G.resize(num_final, full_observation.G.cols());
1510 optimization_observation.G.setZero();
1511 for (int i = 0; i < num_final; ++i) {
1512 const int idx = selected_indices[i];
1513 optimization_observation.R.row(i) = full_observation.R.row(idx);
1514 if (energy_is_row_vector) {
1515 optimization_observation.E(0, i) = full_observation.E(0, idx);
1516 } else {
1517 optimization_observation.E.row(i) = full_observation.E.row(idx);
1518 }
1519 optimization_observation.G.row(i) = full_observation.G.row(idx);
1520 }
1521 return optimization_observation;
1522}
1523
1525 const std::vector<std::pair<int, double>>& candidate_distances,
1526 double tolerance)
1527{
1528 double max_min_dist = -std::numeric_limits<double>::infinity();
1529 int farthest_point_idx = -1;
1530
1531 for (const auto& [idx, dist]: candidate_distances) {
1532 if (dist > max_min_dist + tolerance) {
1533 max_min_dist = dist;
1534 farthest_point_idx = idx;
1535 continue;
1536 }
1537
1538 if (std::abs(dist - max_min_dist) <= tolerance &&
1539 (farthest_point_idx == -1 || idx < farthest_point_idx)) {
1540 farthest_point_idx = idx;
1541 }
1542 }
1543
1544 return farthest_point_idx;
1545}
1546
1549 Eigen::VectorXd& targets, Eigen::Index energy_count, Eigen::VectorXd* theta)
1550{
1553 lik_gaussian ? lik_gaussian->getSigma2() : 0.0;
1554 frame.saved_jitter_sigma2 = jitter_sigma2;
1555 frame.has_const_covariance = static_cast<bool>(const_cov_fun);
1556 frame.saved_const_sigma2 =
1557 const_cov_fun ? const_cov_fun->getConstSigma2() : 0.0;
1558
1559 if (disable_output_normalization_) {
1560 // Center the energy block first (standardizeTargets divides by
1561 // y_scale_ == 1 under this flag, so it centers only). RMS-scaling
1562 // RAW absolute targets makes the frame scale |mean(E)|-sized: the
1563 // objective then fits a near-constant O(1) energy signal with
1564 // crushed gradients, and the exit un-shift multiplies the fitted
1565 // signal variance by rms^2 ~ E_abs^2 (observed as magnSigma2
1566 // exploding to ~4e4 on raw PET-MAD energies). Centered targets
1567 // give an eV-scale rms and a benign scale-free objective frame.
1568 standardizeTargets(targets, energy_count);
1569 const Eigen::Index m = targets.size();
1570 if (m > 0) {
1571 const double rms =
1572 std::sqrt(targets.squaredNorm() / static_cast<double>(m));
1573 if (std::isfinite(rms) && rms > 0.0) {
1574 frame.target_scale = rms;
1575 targets /= frame.target_scale;
1576 }
1577 }
1578 } else {
1579 standardizeTargets(targets, energy_count);
1580 }
1581
1582 if (frame.target_scale != 1.0) {
1583 const double log_scale = std::log(frame.target_scale);
1584 if (theta != nullptr && theta->size() > 0) {
1585 (*theta)(0) -= 2.0 * log_scale;
1586 }
1587
1588 const double inv_c2 = 1.0 / (frame.target_scale * frame.target_scale);
1589 if (lik_gaussian) {
1590 lik_gaussian->setSigma2(frame.saved_likelihood_sigma2 * inv_c2);
1591 }
1592 jitter_sigma2 = frame.saved_jitter_sigma2 * inv_c2;
1593 if (const_cov_fun) {
1594 const_cov_fun->setConstSigma2(frame.saved_const_sigma2 * inv_c2);
1595 }
1596 if (sexpat_cov_func &&
1597 usesClassicJointEnergyForcePrior(model_profile_)) {
1598 // The prior is a Student-t density on sqrt(signal variance).
1599 // Its location and scale follow the target units; the induced
1600 // log-variance density and its derivatives are invariant.
1601 frame.saved_magnitude_prior =
1602 sexpat_cov_func->getPriorParametersSqrtt();
1603 PriorBase prior = *frame.saved_magnitude_prior;
1604 prior.setMu(prior.getMu() / frame.target_scale);
1605 prior.setS2(prior.getS2() * inv_c2);
1606 sexpat_cov_func->setPriorParametersSqrtt(prior);
1607 }
1608 }
1609
1610 return frame;
1611}
1612
1614 const OptimizationObjectiveFrame& frame, Eigen::VectorXd* theta) noexcept
1615{
1616 if (frame.target_scale == 1.0) return;
1617
1618 if (lik_gaussian) {
1619 lik_gaussian->setSigma2(frame.saved_likelihood_sigma2);
1620 }
1621 jitter_sigma2 = frame.saved_jitter_sigma2;
1622 if (frame.has_const_covariance && const_cov_fun) {
1623 const_cov_fun->setConstSigma2(frame.saved_const_sigma2);
1624 }
1625 if (frame.saved_magnitude_prior && sexpat_cov_func) {
1626 sexpat_cov_func->setPriorParametersSqrtt(*frame.saved_magnitude_prior);
1627 }
1628
1629 if (theta != nullptr && theta->size() > 0) {
1630 (*theta)(0) += 2.0 * std::log(frame.target_scale);
1631 // A trailing likelihood-noise entry is a variance in frame units
1632 // and un-scales exactly like the log-magnitude.
1633 if (hasTrailingLikelihoodNoiseParameter(*theta)) {
1634 (*theta)(theta->size() - 1) += 2.0 * std::log(frame.target_scale);
1635 }
1636 }
1637}
1638
1650 struct Row {
1651 double force_sd;
1653 };
1654
1655 State(const GaussianProcessRegression& model, const Observation& acquired,
1656 ConvergenceNormType norm, std::vector<Row> values)
1657 : owner(&model),
1658 likelihood(model.lik_gaussian.get()),
1659 posterior(model.currentLaplacePosteriorStamp()),
1660 factor_epoch(model.factor_epoch_),
1662 model.lik_gaussian ? model.lik_gaussian->geometryNoiseRevision()
1663 : 0),
1664 active_posterior(model.active_posterior_),
1665 uncertainty_mode(model.uncertainty_mode_),
1666 optimization_mode(model.hyperparameter_optimization_mode_),
1667 active_refits(model.active_posterior_refits_),
1668 hssvd(model.use_hssvd_backend_),
1669 rff(model.rff_replaces_exact_),
1671 fitted(model.has_been_optimized_),
1674 model.hasTrainingCholeskyFactor(model.R_matrix.rows())),
1675 output_mean(model.y_mean_),
1676 output_scale(model.y_scale_),
1678 variance_convention(model.variance_convention_),
1679 variance_subset_configurations(model.variance_subset_configurations_),
1680 variance_subset_forced_ids(model.variance_subset_forced_ids_),
1681 observations(acquired),
1682 force_norm(norm),
1683 rows(std::move(values))
1684 {
1685 }
1686
1688 const Observation& acquired, ConvergenceNormType norm) const
1689 {
1690 // Integrated uncertainty can update its quadrature during prediction.
1691 // Reuse is confined to the fixed MAP posterior represented by this
1692 // stamp.
1693 return uncertainty_mode == UncertaintyMode::MAP && owner == &model &&
1694 likelihood == model.lik_gaussian.get() &&
1695 factor_epoch == model.factor_epoch_ &&
1697 (model.lik_gaussian
1698 ? model.lik_gaussian->geometryNoiseRevision()
1699 : 0) &&
1700 active_posterior == model.active_posterior_ &&
1701 uncertainty_mode == model.uncertainty_mode_ &&
1702 optimization_mode == model.hyperparameter_optimization_mode_ &&
1703 active_refits == model.active_posterior_refits_ &&
1704 hssvd == model.use_hssvd_backend_ &&
1705 rff == model.rff_replaces_exact_ &&
1706 precision == model.use_precision_ &&
1707 fitted == model.has_been_optimized_ &&
1710 model.hasTrainingCholeskyFactor(model.R_matrix.rows()) &&
1711 output_mean == model.y_mean_ && output_scale == model.y_scale_ &&
1714 variance_convention == model.variance_convention_ &&
1716 model.variance_subset_configurations_ &&
1718 model.variance_subset_forced_ids_ &&
1719 force_norm == norm &&
1720 rows.size() == static_cast<std::size_t>(acquired.R.rows()) &&
1721 detail::matrixExactlyEqual(observations.R, acquired.R) &&
1722 detail::matrixExactlyEqual(observations.G, acquired.G) &&
1723 posterior.matches(model.currentLaplacePosteriorStamp());
1724 }
1725
1729 std::uint64_t factor_epoch;
1731 std::shared_ptr<const ActivePosteriorState> active_posterior;
1742 std::vector<Row> rows;
1743};
1744
1746 const Observation& oracle, const Coord& mode, double force_tolerance,
1747 ConvergenceNormType force_norm)
1748{
1750 if (atomic_environment_model_) return false;
1751 // A rejected active fit releases every parameter. An empty mask lets
1752 // the automatic identifiability policy hold length scales instead.
1753 scg_opt_settings.active_parameters =
1754 fullRefitMask(sexpat_cov_func.get(), lik_gaussian.get());
1755 double force_error = 0.0, force_sd = 0.0;
1756 if (mode.rows() != 1 || mode.cols() != oracle.R.cols() ||
1757 !measureModeRefitTrust(oracle, force_sd, force_error, force_norm)) {
1758 mode_refit_policy_.reset();
1759 return false;
1760 }
1761 return selectModeRefit(oracle, mode, force_tolerance, force_sd,
1762 force_error);
1763}
1764
1765bool GaussianProcessRegression::measureModeRefitTrust(
1766 const Observation& oracle, double& force_sd, double& force_error,
1767 ConvergenceNormType force_norm)
1768{
1769 // A conditional correction uses the fitted MAP posterior independently
1770 // of the optimizer that estimated its background hyperparameters.
1771 const bool conditional = active_posterior_refits_ &&
1772 uncertainty_mode_ == UncertaintyMode::MAP &&
1773 !rff_replaces_exact_;
1774 const bool supported = conditional ||
1775 hyperparameter_optimization_mode_ ==
1777 hyperparameter_optimization_mode_ ==
1779 hyperparameter_optimization_mode_ ==
1781 hyperparameter_optimization_mode_ ==
1783 if (!supported || !has_been_optimized_ || !is_decomposed_succesfully ||
1784 !sexpat_cov_func || sexpat_cov_func->usesManifoldChart() ||
1785 oracle.R.rows() != 1 || oracle.R.cols() <= 0 || !oracle.R.allFinite() ||
1786 oracle.G.rows() != 1 || oracle.G.cols() != oracle.R.cols() ||
1787 !oracle.G.allFinite()) {
1788 mode_refit_policy_.reset();
1789 return false;
1790 }
1791 Observation prediction;
1792 prediction.R = oracle.R;
1793 prediction.E.resize(1, 1);
1794 prediction.G.resize(1, oracle.R.cols());
1795 calculatePotentialDispatched(prediction);
1796 if (prediction.G.rows() != oracle.G.rows() ||
1797 prediction.G.cols() != oracle.G.cols() || !prediction.G.allFinite()) {
1798 mode_refit_policy_.reset();
1799 return false;
1800 }
1801 const Eigen::RowVectorXd force_residual = (prediction.G - oracle.G).row(0);
1802 force_error = gpr::forceNorm(force_residual, force_norm);
1803 calculateVarianceDispatched(prediction);
1804 force_sd =
1805 prediction.G.allFinite() && prediction.G.size() == oracle.G.size()
1806 ? gpr::forceNorm(prediction.G.row(0).cwiseMax(0.0).cwiseSqrt(),
1807 force_norm)
1808 : std::numeric_limits<double>::infinity();
1809 return std::isfinite(force_sd) && std::isfinite(force_error);
1810}
1811
1814 const Observation& rows, ConvergenceNormType force_norm,
1815 double* max_force_error, double* max_force_sd, double* evidence_nats,
1816 double variance_calibration, RefitTrustReport* trust_report)
1817{
1818 if (trust_report) trust_report->state_.reset();
1819 std::vector<RefitTrustReport::State::Row> measured_trust;
1820 double worst_error = 0.0, worst_sd = 0.0;
1821 if (max_force_error) *max_force_error = worst_error;
1822 if (max_force_sd) *max_force_sd = worst_sd;
1823 if (evidence_nats) *evidence_nats = 0.0;
1824 if (rows.R.rows() <= 0 || rows.G.rows() != rows.R.rows() ||
1825 rows.G.cols() != rows.R.cols())
1827 // A row contradicts the posterior when the evidence it can add
1828 // exceeds one nat: under the posterior's own Gaussian a residual of
1829 // e against a spread of sd is worth at most (e/sd)^2/2 - 1/2 in log
1830 // likelihood over a model that reproduced it. Any row above one
1831 // spread used to force a refit, so a 1.5-spread row at 3 meV/A
1832 // against 2 meV/A (04_cope's dimer, 21 of 25 fits improving the
1833 // objective by under 0.2 nats) bought a correction fit every phase.
1834 double evidence = 0.0;
1835 for (Eigen::Index row = 0; row < rows.R.rows(); ++row) {
1836 Observation measured;
1837 measured.R = rows.R.middleRows(row, 1);
1838 measured.G = rows.G.middleRows(row, 1);
1839 double row_sd = 0.0, row_error = 0.0;
1840 if (!measureModeRefitTrust(measured, row_sd, row_error, force_norm))
1842 if (trust_report) measured_trust.push_back({row_sd, row_error});
1843 // The spread the row is judged against is the one the caller has
1844 // measured for this posterior: the reported variance times its
1845 // trial calibration.
1846 if (std::isfinite(variance_calibration) && variance_calibration > 1.0)
1847 row_sd *= std::sqrt(variance_calibration);
1848 worst_error = std::max(worst_error, row_error);
1849 worst_sd = std::max(worst_sd, row_sd);
1850 if (row_error > row_sd) {
1851 const double ratio = row_sd > 0.0
1852 ? row_error / row_sd
1853 : std::numeric_limits<double>::infinity();
1854 evidence += std::isfinite(ratio)
1855 ? 0.5 * (ratio * ratio - 1.0)
1856 : std::numeric_limits<double>::infinity();
1857 }
1858 }
1859 if (trust_report)
1860 trust_report->state_ = std::make_shared<RefitTrustReport::State>(
1861 *this, rows, force_norm, std::move(measured_trust));
1862 if (max_force_error) *max_force_error = worst_error;
1863 if (max_force_sd) *max_force_sd = worst_sd;
1864 if (evidence_nats) *evidence_nats = evidence;
1865 if (evidence >= 1.0) {
1866 // Rows the posterior cannot explain move the marginal likelihood by
1867 // more than their expected log predictive density: the next fit
1868 // may land in another basin, and the previous fit's curvature
1869 // record would steer it. The fit opens cold.
1872 }
1874}
1875
1877 const Observation& oracle, double force_tolerance,
1878 ConvergenceNormType force_norm, const RefitTrustReport* trust_report)
1879{
1881 if (atomic_environment_model_) return false;
1882 scg_opt_settings.active_parameters =
1883 fullRefitMask(sexpat_cov_func.get(), lik_gaussian.get());
1884 double force_sd = 0.0, force_error = 0.0;
1885 if (!active_posterior_refits_ || !(force_tolerance > 0.0) ||
1886 !std::isfinite(force_tolerance) || oracle.R.rows() <= 0 ||
1887 oracle.G.rows() != oracle.R.rows() ||
1888 oracle.G.cols() != oracle.R.cols()) {
1889 mode_refit_policy_.reset();
1890 return false;
1891 }
1892 const auto* measured_trust =
1893 trust_report && trust_report->state_ &&
1894 trust_report->state_->matches(*this, oracle, force_norm)
1895 ? trust_report->state_.get()
1896 : nullptr;
1897 Observation witness;
1898 double worst_trust = -1.0;
1899 bool overconfident = false;
1900 bool full_length_fit = false;
1901 bool component_contradiction = false;
1902 for (Eigen::Index row = 0; row < oracle.R.rows(); ++row) {
1903 Observation measured;
1904 measured.R = oracle.R.middleRows(row, 1);
1905 measured.G = oracle.G.middleRows(row, 1);
1906 double row_sd = 0.0, row_error = 0.0;
1907 bool eligible = true;
1908 if (measured_trust) {
1909 const auto& row_trust = measured_trust->rows[row];
1910 row_sd = row_trust.force_sd;
1911 row_error = row_trust.force_error;
1912 } else {
1913 eligible =
1914 measureModeRefitTrust(measured, row_sd, row_error, force_norm);
1915 }
1916 if (!eligible) {
1917 if (report_level >= 1)
1918 log_man << "Minimum-mode refit: full fit, acquired row " << row
1919 << "/" << oracle.R.rows() << ", eligible " << eligible
1920 << ", fitted " << has_been_optimized_ << ", decomposed "
1921 << is_decomposed_succesfully << ", force uncertainty "
1922 << row_sd << ", measured force error " << row_error
1923 << "\n";
1924 mode_refit_policy_.reset();
1925 return false;
1926 }
1927 full_length_fit = full_length_fit || row_sd >= force_tolerance;
1928 component_contradiction =
1929 component_contradiction ||
1930 ((environment_residuals_ || additive_pair_residuals_) &&
1931 row_error > row_sd);
1932 overconfident = overconfident || row_error >= force_tolerance;
1933 // A measured force error at the tolerance is evidence against the
1934 // surrogate's hyperparameters: the next full fit's anneal stage.
1935 if (row_error >= force_tolerance) surrogate_contradicted_ = true;
1936 force_sd = std::max(force_sd, row_sd);
1937 force_error = std::max(force_error, row_error);
1938 const double trust = std::max(row_sd, row_error);
1939 if (trust > worst_trust) {
1940 worst_trust = trust;
1941 witness = std::move(measured);
1942 }
1943 }
1944 if (active_posterior_ && overconfident) {
1945 // The measured contradiction is against the combined posterior.
1946 // Refitting only its conditional correction keeps the background
1947 // fixed at its anchors and cannot reassess that part of the model.
1948 mode_refit_policy_.reset();
1949 if (report_level >= 1)
1950 log_man << "Minimum-mode refit: full fit of contradicted combined "
1951 "posterior, force uncertainty "
1952 << force_sd << ", measured force error " << force_error
1953 << "\n";
1954 return false;
1955 }
1956 if (full_length_fit) {
1957 // Any acquired contradiction can require a richer kernel, even
1958 // when another acquired row has high, calibrated uncertainty.
1959 // All residual length scales vary; candidate evidence decides
1960 // whether to retain the background and adopt the correction.
1961 residual_model_refit_ = component_contradiction;
1962 if (report_level >= 1)
1963 log_man << "Minimum-mode refit: "
1964 << (residual_model_refit_ ? "residual model fit"
1965 : "full fit")
1966 << ", acquired rows " << oracle.R.rows()
1967 << ", force uncertainty " << force_sd
1968 << ", measured force error " << force_error << "\n";
1969 mode_refit_policy_.reset();
1970 return false;
1971 }
1972 if (overconfident) {
1973 residual_model_refit_ = true;
1974 if (report_level >= 1)
1975 log_man << "Residual model refit: " << oracle.R.rows()
1976 << " measured rows, force uncertainty " << force_sd
1977 << ", measured force error " << force_error
1978 << ", residual variance from the sparse posterior ("
1979 << last_residual_inducing_count_ << " inducing of "
1980 << last_residual_configuration_count_
1981 << " configurations in the last fit, exact per "
1982 "configuration)\n";
1983 mode_refit_policy_.reset();
1984 return false;
1985 }
1986 const Eigen::Index dof = oracle.R.cols();
1987 EigenMatrix hessian;
1989 if (prepareMeanHessianVectorHssvd(witness.R, prepared)) {
1991 prepared, EigenMatrix::Identity(dof, dof), hessian)) {
1992 // The prepared block owns the curvature. A failed apply is a
1993 // refusal: the exact kernel and the stencil are not matrices
1994 // this refit may diagonalize.
1995 mode_refit_policy_.reset();
1996 return false;
1997 }
1998 } else {
1999 hessian.resize(dof, dof);
2000 const auto mean_hessian = prepareMeanHessian(witness.R);
2001 if (!mean_hessian) {
2002 mode_refit_policy_.reset();
2003 return false;
2004 }
2005 for (Eigen::Index column = 0; column < dof; ++column) {
2006 Eigen::VectorXd action;
2007 if (!mean_hessian(Eigen::VectorXd::Unit(dof, column), action)) {
2008 mode_refit_policy_.reset();
2009 return false;
2010 }
2011 hessian.col(column) = action;
2012 }
2013 }
2014 hessian = 0.5 * (hessian + hessian.transpose()).eval();
2015 Eigen::SelfAdjointEigenSolver<EigenMatrix> modes(hessian);
2016 if (modes.info() != Eigen::Success || !modes.eigenvalues().allFinite() ||
2017 modes.eigenvalues()(0) >=
2018 -std::sqrt(std::numeric_limits<double>::epsilon()) *
2019 hessian.norm()) {
2020 mode_refit_policy_.reset();
2021 return false;
2022 }
2023 const Coord mode = modes.eigenvectors().col(0).transpose();
2024 return selectModeRefit(witness, mode, force_tolerance, force_sd,
2025 force_error);
2026}
2027
2028bool GaussianProcessRegression::selectModeRefit(const Observation& oracle,
2029 const Coord& mode,
2030 double force_tolerance,
2031 double force_sd,
2032 double force_error)
2033{
2034 const auto& lengths = sexpat_cov_func->getLengthScaleRef();
2035 const auto active = mode_refit_policy_.select(
2036 oracle.R, atoms_config, lengths, mode.transpose(), force_sd,
2037 force_error, force_tolerance,
2038 /*require_parameter_reduction=*/!active_posterior_refits_);
2039 if (active.empty()) {
2040 residual_model_refit_ =
2041 active_posterior_refits_ && !active_posterior_ &&
2042 std::isfinite(force_tolerance) && force_tolerance > 0.0 &&
2043 std::isfinite(force_sd) && std::isfinite(force_error) &&
2044 ((force_sd < force_tolerance && force_error >= force_tolerance) ||
2045 ((environment_residuals_ || additive_pair_residuals_) &&
2046 force_error > force_sd));
2047 if (report_level >= 1) {
2048 log_man << "Mode refit: full length scales, "
2049 << "force uncertainty " << force_sd
2050 << ", measured force error " << force_error << "\n";
2051 }
2052 return false;
2053 }
2054 if (active_posterior_refits_) {
2055 active_refit_lengths_ = active;
2056 if (report_level >= 1)
2057 log_man << "Mode refit: retained full posterior with "
2058 << std::count(active.begin(), active.end(), true) << "/"
2059 << active.size() << " active correction lengths.\n";
2060 return true;
2061 }
2062 auto& mask = scg_opt_settings.active_parameters;
2063 mask.assign(1 + active.size() +
2064 (lik_gaussian && lik_gaussian->getOptimizeSigma2() ? 1 : 0),
2065 true);
2066 std::copy(active.begin(), active.end(), mask.begin() + 1);
2067 if (report_level >= 1) {
2068 log_man << "Mode refit: active length scales "
2069 << std::count(active.begin(), active.end(), true) << "/"
2070 << active.size() << ", force uncertainty " << force_sd
2071 << ", measured force error " << force_error << "\n";
2072 }
2073 return true;
2074}
2075
2077 const Observation& opt_observation)
2078{
2082 "this fit",
2083 "the objective has no exact NLML Hessian-vector product");
2084 }
2085 if (const char* path = std::getenv("GPR_TRAINING_AUDIT")) {
2086 // Audit ownership follows the model's communicator, including
2087 // fits that have not configured a distributed factorization grid.
2088 if (backend().mpi().rank == 0) {
2089 std::ofstream audit(path, std::ios::app);
2090 if (!audit)
2091 throw std::runtime_error("cannot open GP training audit");
2092 audit << std::setprecision(17) << "fit " << opt_observation.R.rows()
2093 << ' ' << outputMean() << ' ' << outputScale() << '\n';
2094 for (Eigen::Index row = 0; row < opt_observation.R.rows(); ++row)
2095 audit << "row " << row << ' ' << opt_observation.R.row(row)
2096 << ' ' << opt_observation.E.data()[row] << ' '
2097 << opt_observation.G.row(row) << '\n';
2098 }
2099 }
2100 last_scg_fallback_used_ = false;
2101 optimizer_state_->last_fallback_rejected = false;
2102 // Steps the SCG attempt finished before the L-BFGS fallback of the
2103 // same call. A stall skip does not run SCG, so this stays zero and
2104 // the reported count is the fallback alone. A later tie-release
2105 // refit replaces both, because that refit owns the accepted point.
2106 int scg_steps_before_fallback = 0;
2107 last_failed_fit_improved_ = false;
2108 last_failed_fit_evaluable_ = true;
2109 last_fit_gradient_norm_ = std::numeric_limits<double>::quiet_NaN();
2110 last_fit_configurations_ = static_cast<std::size_t>(
2111 std::max<Eigen::Index>(0, opt_observation.R.rows()));
2112 struct OneRefitMask {
2113 std::vector<bool>& mask;
2114 ~OneRefitMask()
2115 {
2116 mask.clear();
2117 }
2118 } one_refit_mask{scg_opt_settings.active_parameters};
2119 // Rows that all lie within one length scale of each other identify only
2120 // the ratio of amplitude to length scale: the likelihood is flat along
2121 // m / l^2 = F^2 and the optimizer runs to the length-scale floor with a
2122 // vanishing amplitude (14_hydro's supplied-seed dimer: two rows 0.01 A
2123 // apart, mag2 7e-7 and every length at the 0.02 floor, kept through 39
2124 // rows by warm starts). Such rows hold the length scales where they are
2125 // and fit the amplitude and noise; the lengths move once the rows spread
2126 // past one length scale, the kernel's own support scale.
2127 if (scg_opt_settings.active_parameters.empty() && sexpat_cov_func &&
2128 opt_observation.R.rows() > 1 && !sexpat_cov_func->usesManifoldChart() &&
2129 sexpat_cov_func->getLengthScaleRef().size() > 0) {
2130 FieldMatrixd scores;
2131 sexpat_cov_func->correlationDistances(
2132 opt_observation.R, opt_observation.R, atoms_config, scores);
2133 double farthest = 0.0;
2134 bool finite = scores.rows() == opt_observation.R.rows();
2135 for (Eigen::Index i = 0; finite && i < scores.rows(); ++i)
2136 for (Eigen::Index j = i + 1; j < scores.cols(); ++j) {
2137 if (!std::isfinite(scores(i, j))) {
2138 finite = false;
2139 break;
2140 }
2141 farthest = std::max(farthest, scores(i, j));
2142 }
2143 if (finite && farthest < 1.0) {
2144 const Eigen::Index lengths =
2145 sexpat_cov_func->getLengthScaleRef().size();
2146 auto& mask = scg_opt_settings.active_parameters;
2147 mask.assign(
2148 static_cast<std::size_t>(1 + lengths) +
2149 (lik_gaussian && lik_gaussian->getOptimizeSigma2() ? 1 : 0),
2150 true);
2151 std::fill(mask.begin() + 1, mask.begin() + 1 + lengths, false);
2152 if (report_level >= 1)
2153 log_man << "Hyperparameter identifiability: the training rows "
2154 "lie within "
2155 << farthest
2156 << " length scales of each other; holding the length "
2157 "scales and fitting the amplitude.\n";
2158 }
2159 }
2161 Eigen::MatrixXd opt_R_matrix;
2162 Eigen::VectorXd opt_R_indices;
2163 Eigen::VectorXd opt_energy_and_gradient;
2164 // The fit's block geometry lives for the fit.
2165 struct FitGeometryLease {
2166 const GaussianProcessRegression& model;
2167 ~FitGeometryLease()
2168 {
2169 model.releaseFitGeometry();
2170 }
2171 } fit_geometry_lease{*this};
2172
2173 aux_func.assembleMatrixOfRepetitiveCoordinates(opt_observation.R,
2174 opt_R_matrix, opt_R_indices);
2175 aux_func.assembleVectorFromEnergyAndGradient(opt_observation,
2176 opt_energy_and_gradient);
2177 subtractPriorMeanFromTargets(opt_observation.R, opt_observation.E.size(),
2178 opt_energy_and_gradient);
2179 Eigen::VectorXd parameters_cf = sexpat_cov_func->combineParameters();
2180 const OptimizationObjectiveFrame objective_frame =
2182 opt_energy_and_gradient, opt_observation.E.size(), &parameters_cf);
2183 const Eigen::Index covariance_parameter_count = parameters_cf.size();
2184 // Learned likelihood noise: append log(sigma2) AFTER the frame entry
2185 // so the entry carries frame units (the frame already rescaled the
2186 // lik sigma2 by 1/target_scale^2, exactly the transform the
2187 // log-magnitude entry received); leaveOptimizationObjectiveFrame
2188 // un-shifts it symmetrically and the caller's setParameters applies
2189 // the physical value.
2190 if (lik_gaussian && lik_gaussian->getOptimizeSigma2()) {
2191 const double frame_sigma2 = lik_gaussian->getSigma2();
2192 if (std::isfinite(frame_sigma2) && frame_sigma2 > 0.0) {
2193 const Eigen::Index n0 = parameters_cf.size();
2194 parameters_cf.conservativeResize(n0 + 1);
2195 parameters_cf(n0) = std::log(frame_sigma2);
2196 }
2197 }
2198 double log_lengthscale_lower = -std::numeric_limits<double>::infinity();
2199 if (opt_observation.R.rows() > 0 && opt_observation.R.cols() > 0) {
2200 aux::Distance distance;
2201 FieldMatrixd dist;
2202 FieldMatrixd unit_lengthscale(1, 1);
2203 unit_lengthscale.setConstant(1.0);
2204 distance.dist_at(opt_observation.R, opt_observation.R, atoms_config,
2205 unit_lengthscale, dist);
2206 if (dist.size() > 0 && dist.allFinite()) {
2207 const double min_lengthscale =
2208 lengthscaleProjectionFloor(dist.maxCoeff(), lengthscale_floor_);
2209 if (std::isfinite(min_lengthscale) && min_lengthscale > 0.0) {
2210 log_lengthscale_lower = std::log(min_lengthscale);
2211 }
2212 }
2213 }
2214 const auto project_lengthscales_to_domain = [&](Eigen::VectorXd& theta) {
2215 if (!std::isfinite(log_lengthscale_lower) || theta.size() <= 1) return;
2216 const double interior_lower = std::nextafter(
2217 log_lengthscale_lower, std::numeric_limits<double>::infinity());
2218 for (Eigen::Index i = 1; i < covariance_parameter_count; ++i) {
2219 if (!(theta(i) > log_lengthscale_lower)) theta(i) = interior_lower;
2220 }
2221 };
2222 if (std::isfinite(log_lengthscale_lower) &&
2223 scg_opt_settings.active_parameters.size() ==
2224 static_cast<std::size_t>(parameters_cf.size())) {
2225 for (Eigen::Index i = 1; i < covariance_parameter_count; ++i) {
2226 if (!scg_opt_settings
2227 .active_parameters[static_cast<std::size_t>(i)] &&
2228 !(parameters_cf(i) > log_lengthscale_lower)) {
2229 scg_opt_settings.active_parameters.clear();
2230 mode_refit_policy_.reset();
2231 if (report_level >= 1) {
2232 log_man << "A fixed length scale is outside the fitted "
2233 "domain; refitting all length scales.\n";
2234 }
2235 break;
2236 }
2237 }
2238 }
2239 const bool ties_active =
2240 lengthScaleTiesActive(covariance_parameter_count - 1);
2241 // The mask before the ties: which length scales the data identify.
2242 // An empty mask means every parameter is fitted; the mask is left as
2243 // it is, since a non-empty mask also marks the active-subspace refit
2244 // regime for the code after the fit.
2245 const std::vector<bool> identifiable_mask =
2246 scg_opt_settings.active_parameters;
2247 // Tied members start at their leader's scale; the structure (mask,
2248 // bounds, priors) is applied once the MAP configuration exists.
2249 if (ties_active) tieLengthScaleParameters(parameters_cf);
2250 project_lengthscales_to_domain(parameters_cf);
2251 Eigen::VectorXd old_parameters_cf = parameters_cf;
2252 Eigen::VectorXd parameter_lower = Eigen::VectorXd::Constant(
2253 parameters_cf.size(), -std::numeric_limits<double>::infinity());
2254 Eigen::VectorXd parameter_upper = -parameter_lower;
2255 if (std::isfinite(log_lengthscale_lower) &&
2256 covariance_parameter_count > 1) {
2257 parameter_lower.segment(1, covariance_parameter_count - 1)
2258 .setConstant(
2259 std::nextafter(log_lengthscale_lower,
2260 std::numeric_limits<double>::infinity()));
2261 }
2262 // The bounds before any parameter is pinned: a released tie member
2263 // returns to these.
2264 const Eigen::VectorXd general_lower = parameter_lower;
2265 const Eigen::VectorXd general_upper = parameter_upper;
2266 if (scg_opt_settings.active_parameters.size() ==
2267 static_cast<std::size_t>(parameters_cf.size())) {
2268 for (Eigen::Index i = 0; i < parameters_cf.size(); ++i) {
2269 if (!scg_opt_settings
2270 .active_parameters[static_cast<std::size_t>(i)]) {
2271 parameter_lower(i) = parameters_cf(i);
2272 parameter_upper(i) = parameters_cf(i);
2273 }
2274 }
2275 }
2276
2277 // Scale-free MAP lengthscale-prior anchor: rho0_k = per-pairtype
2278 // descriptor std, the same data-derived scale setHyperparameters uses to
2279 // seed the length scales (see computePairtypeDescriptorScale). Computed
2280 // once per hyperparameter-optimization call (not per rgmin SCG or L-BFGS
2281 // probe). Left empty when the descriptor spread is degenerate (no
2282 // positions, or a pairtype has fewer than two observations); the shared
2283 // MAP objective then falls back to its raw-unit Student-t prior
2284 // (MapObjective.h), matching the pre-fix behaviour exactly.
2285 Eigen::VectorXd lengthscale_rho0;
2286 computePairtypeDescriptorScale(opt_observation.R, atoms_config,
2287 lengthscale_rho0);
2288 poolDescriptorScaleByTies(lengthscale_rho0);
2289 if (ls_seed_chemical_floor_ && lengthscale_rho0.size() > 0 &&
2290 lengthscale_rho0.size() == atoms_config.n_pt) {
2291 // The MAP prior anchors each length scale at rho0_k; floor it the
2292 // way the seed is floored so the prior does not pull a barely
2293 // moving pair back to its collapsed spread.
2294 const priors::CovalentBondPrior bond_prior(atoms_config);
2295 const Eigen::VectorXd chemical =
2296 bond_prior.lengthScalePerPairtype().cwiseInverse();
2297 for (Eigen::Index k = 0; k < lengthscale_rho0.size(); ++k) {
2298 if (std::isfinite(chemical(k)) && chemical(k) > 0.0)
2299 lengthscale_rho0(k) =
2300 std::max(lengthscale_rho0(k), chemical(k));
2301 }
2302 }
2303
2304 // A pair type the population prior has seen is anchored at the
2305 // campaign's location for its element pair (after the tie pooling: the
2306 // members of a group share the element pair and so the anchor).
2307 if (!population_prior_.empty() && atoms_config.n_pt > 0) {
2308 const auto entries = population_prior_.perPairtype(atoms_config);
2309 // Without a descriptor scale (too few rows per pair type) the
2310 // population still anchors the types it has seen; the others fall
2311 // back per index as before.
2312 if (lengthscale_rho0.size() != atoms_config.n_pt)
2313 lengthscale_rho0 = Eigen::VectorXd::Constant(
2314 atoms_config.n_pt, std::numeric_limits<double>::quiet_NaN());
2315 for (Eigen::Index k = 0; k < lengthscale_rho0.size(); ++k) {
2316 const auto* entry = entries[static_cast<std::size_t>(k)];
2317 if (entry != nullptr)
2318 lengthscale_rho0(k) = std::exp(entry->log_length_mu);
2319 }
2320 }
2321
2322 // The coordinate box excludes collapsed length scales without adding a
2323 // reciprocal barrier to the MAP objective. The half-Student-t prior
2324 // supplies smooth regularisation inside the domain.
2325 scg_opt_settings.use_tail_lower_barrier = false;
2326 scg_opt_settings.tail_lower_barrier =
2327 -std::numeric_limits<double>::infinity();
2328
2329 // Refresh configured MAP prior parameters from the live SexpatCF hierarchy
2330 // when the opt-in flags are set (default off keeps weakly-informative
2331 // half-Cauchy / Student-t defaults identical to the built-in MAP priors).
2332 if (sexpat_cov_func != nullptr) {
2333 scg_opt_settings.map_use_lognormal_magn_prior =
2334 sexpat_cov_func->useLogNormalMagnPrior();
2335 if (scg_opt_settings.map_use_lognormal_magn_prior) {
2336 const PriorBase magn_p =
2337 sexpat_cov_func->getPriorParametersLogNormal();
2338 scg_opt_settings.map_magn_prior_mu = magn_p.getMu();
2339 scg_opt_settings.map_magn_prior_s2 = magn_p.getS2();
2340 scg_opt_settings.map_magn_prior_nu = magn_p.getNu();
2341 } else if (scg_opt_settings.map_use_configured_magn_prior) {
2342 const PriorBase magn_p = sexpat_cov_func->getPriorParametersSqrtt();
2343 scg_opt_settings.map_magn_prior_mu = magn_p.getMu();
2344 scg_opt_settings.map_magn_prior_s2 = magn_p.getS2();
2345 scg_opt_settings.map_magn_prior_nu = magn_p.getNu();
2346 }
2347 if (scg_opt_settings.map_use_configured_lengthscale_prior) {
2348 const PriorBase ls_p =
2349 sexpat_cov_func->getPriorParametersGaussian();
2350 scg_opt_settings.map_lengthscale_prior_mu = ls_p.getMu();
2351 scg_opt_settings.map_lengthscale_prior_s2 = ls_p.getS2();
2352 scg_opt_settings.map_lengthscale_prior_nu = ls_p.getNu();
2353 }
2354 }
2355
2356 auto optimizer_settings = scg_opt_settings;
2357 // Collective fits share one parameter sequence. Its trace belongs to
2358 // the model communicator's root, independently of the process count.
2359 if (backend().mpi().rank != 0) optimizer_settings.common.report_level = 0;
2360 std::visit(
2361 [&](auto& opt) {
2362 using OptType = std::decay_t<decltype(opt)>;
2363 if constexpr (kIsScgLike<OptType>) {
2364 auto settings = optimizer_settings;
2365 opt.setAlgorithmSettings(settings);
2366 }
2367#ifdef USE_CERES
2368 else if constexpr (std::is_same_v<OptType, funcmin::Ceres>) {
2369 opt.setAlgorithmSettings(ceres_opt_settings);
2370 }
2371#endif
2372 },
2373 optimizer_state_->optimizer);
2374
2375 if (this->report_level >= 2) {
2376 log_man << "Starting optimization with " << opt_R_matrix.rows()
2377 << " data points.\n";
2378 if (scg_opt_settings.use_tail_lower_barrier) {
2379 log_man << "Lengthscale lower barrier at exp("
2380 << scg_opt_settings.tail_lower_barrier
2381 << ") = " << std::exp(scg_opt_settings.tail_lower_barrier)
2382 << "\n";
2383 }
2384 }
2385
2386 double initial_strength = 1e-4;
2387 double growth_factor = 1e-3;
2388 double current_barrier_strength =
2389 initial_strength +
2390 growth_factor * gpr::coord::numPoints(opt_observation.R);
2391 auto start = std::chrono::steady_clock::now();
2392
2393 // Per-outer-iter training-kernel geometry handle. Built once here and
2394 // owned by a lexical objective holder so the inner-iter K assembly skips
2395 // dist_at + per-pair derivative recompute and applies theta to the
2396 // per-block unit-lengthscale geometry. The live evaluateEnergyAndGradient
2397 // callback handles inputs without a geometry representation, keeping
2398 // dispatch at the driver level.
2399 TrainingKernelGeometry training_geom;
2400 const bool training_geom_ready =
2401 canUseTrainingGeometryObjective() && use_training_geometry_handle_ &&
2402 prepareTrainingKernelGeometry(opt_R_matrix, opt_R_indices,
2403 training_geom, /*reused=*/true);
2404 const bool using_loo_objective =
2405 hyperparameter_objective_mode_ == HyperparameterObjectiveMode::LOO;
2406 // Unlike LOO, LOCAL_LOO does not need the training geometry handle
2407 // (every held-out geometry gets its own small dense solve), so it is
2408 // deliberately NOT part of the training_geom_ready hard-failure guard
2409 // below. It still needs to be excluded from the stationarity-skip
2410 // secant cache further down: that branch calls
2411 // evaluateEnergyAndGradientFromGeometry / evaluateEnergyAndGradient
2412 // directly rather than through this dispatch struct, and (for the
2413 // training_geom_ready path) the *FromGeometry variant is the NLML
2414 // one -- routing LOCAL_LOO through it there would silently cache a
2415 // secant built from the WRONG objective.
2416 const bool using_local_loo_objective =
2417 hyperparameter_objective_mode_ ==
2419 if (using_loo_objective && !training_geom_ready) {
2420 if (report_level >= 1) {
2421 log_man << "LOO hyperparameter objective requires the training "
2422 "geometry handle.\n";
2423 }
2424 failedOptimizer = true;
2425 // No objective can be evaluated: the all-rows fit is the only
2426 // remaining estimator.
2427 last_failed_fit_evaluable_ = false;
2428 leaveOptimizationObjectiveFrame(objective_frame, &parameters_cf);
2429 return old_parameters_cf;
2430 }
2431
2432 // Learned log(sigma2) is appended after the covariance parameters.
2433 // The signal anchor and the length-scale prior must not treat it as
2434 // another length scale.
2435 const Eigen::VectorXd kernel_parameters =
2436 parameters_cf.head(covariance_parameter_count);
2437 funcmin::MapObjectiveConfig map_objective_config =
2439 opt_R_matrix, opt_energy_and_gradient, kernel_parameters,
2440 current_barrier_strength, lengthscale_rho0, scg_opt_settings,
2441 hyperparameter_optimization_mode_ !=
2443 map_objective_config.lengthscale_count =
2444 std::max<Eigen::Index>(covariance_parameter_count - 1, 0);
2445 if (unregularized_marginal_likelihood_) {
2446 map_objective_config.barrier_strength = 0.0;
2447 map_objective_config.weight_mode = MapPriorWeightMode::Annealed;
2448 map_objective_config.use_magn_ceiling = false;
2449 map_objective_config.use_tail_lower_barrier = false;
2450 map_objective_config.use_configured_magn_prior = false;
2451 map_objective_config.use_lognormal_magn_prior = false;
2452 map_objective_config.use_configured_lengthscale_prior = false;
2453 }
2454 if (usesClassicJointEnergyForcePrior(model_profile_)) {
2455 // The model objective includes its complete log-parameter prior.
2456 // Optimizers preserve that density and the supplied parameter box.
2457 map_objective_config.barrier_strength = 0.0;
2458 map_objective_config.weight_mode = MapPriorWeightMode::Annealed;
2459 map_objective_config.use_magn_ceiling = false;
2460 map_objective_config.use_tail_lower_barrier = false;
2461 }
2462 map_objective_config.parameter_lower = parameter_lower;
2463 map_objective_config.parameter_upper = parameter_upper;
2464 // The tie structure: the leader of each group is its one parameter,
2465 // with the group's single prior; a member has no prior of its own and
2466 // keeps the general bounds and its place in the mask: the wrapped
2467 // objective gives it no gradient, so the optimizer never moves it,
2468 // while a masked-out member would lose its share of the group sum and
2469 // a degenerate box would stop the bounded optimizer short. Reapplied
2470 // when the review changes the structure.
2471 auto refresh_tie_structure = [&]() {
2472 if (!ties_active) return;
2473 const auto& ties = length_scale_ties_;
2474 // The mask is not touched: a member stays in it, since the
2475 // objective zeroes the gradient of a masked parameter before the
2476 // reduction sums a group; the member is held by its zero reduced
2477 // gradient instead.
2478 const bool masked = identifiable_mask.size() ==
2479 static_cast<std::size_t>(parameters_cf.size());
2480 map_objective_config.prior_weight =
2481 Eigen::VectorXd::Ones(parameters_cf.size());
2482 for (Index_t t = 0; t < ties.count(); ++t) {
2483 const Eigen::Index i = 1 + t;
2484 const auto index = static_cast<std::size_t>(i);
2485 const bool leader = ties.leader[static_cast<std::size_t>(t)] == t;
2486 const bool identified = !masked || identifiable_mask[index];
2487 map_objective_config.prior_weight(i) = leader ? 1.0 : 0.0;
2488 if (!leader || identified) {
2489 parameter_lower(i) = general_lower(i);
2490 parameter_upper(i) = general_upper(i);
2491 } else {
2492 parameter_lower(i) = parameters_cf(i);
2493 parameter_upper(i) = parameters_cf(i);
2494 }
2495 }
2496 map_objective_config.parameter_lower = parameter_lower;
2497 map_objective_config.parameter_upper = parameter_upper;
2498 };
2499 refresh_tie_structure();
2501 map_objective_config);
2502 // Log-parameter proposals use the configured prior's width. Unit width
2503 // is the factor-e scale of a log parameter without a configured prior.
2504 const double prior_s2 =
2505 scg_opt_settings.map_use_configured_lengthscale_prior
2506 ? scg_opt_settings.map_lengthscale_prior_s2
2507 : (sexpat_cov_func != nullptr
2508 ? sexpat_cov_func->getPriorParametersGaussian().getS2()
2509 : 0.0);
2510 const double parameter_search_halfwidth =
2511 std::isfinite(prior_s2) && prior_s2 > 0.0 ? std::sqrt(prior_s2) : 1.0;
2512 auto run_map_optimizer = [&](auto& optimizer, auto& objective,
2513 auto callback) {
2514 // The selected optimizer is rgmin. A stall falls back to rgmin L-BFGS.
2515 using Optimizer = std::decay_t<decltype(optimizer)>;
2516 // Each attempt reports its own SCG steps plus, when it falls
2517 // back, that fallback. A previous attempt's latch must not
2518 // attribute its L-BFGS steps to a later SCG-only refit.
2519 last_scg_fallback_used_ = false;
2520 optimizer_state_->last_fallback_rejected = false;
2521 scg_steps_before_fallback = 0;
2522 if constexpr (std::is_same_v<Optimizer, funcmin::RgminOpt>) {
2523 optimizer.setBox(parameter_lower, parameter_upper);
2524 optimizer.setPersistentSession(rgmin_warm_start_);
2525 optimizer.setInitialLogMove(rgmin_initial_log_move_);
2526 optimizer.setInitialLogMoveWholeSession(
2527 rgmin_initial_log_move_whole_session_);
2528 }
2529 const Eigen::VectorXd initial_parameters = parameters_cf;
2530 const int objective_count_before = PhaseTimers::objective_count;
2531 std::size_t rgmin_logical_work = 0;
2532 std::size_t rgmin_physical_work = 0;
2533 const auto retain_feasible_improvement = [&](bool failed) {
2534 // Diagnostics measure executed work. The anneal budget follows
2535 // the single-entry request policy for the local rgmin fit.
2536 last_fit_evaluations_ = static_cast<std::size_t>(std::max(
2537 0, PhaseTimers::objective_count - objective_count_before));
2538 last_fit_budget_evaluations_ =
2539 last_fit_evaluations_ -
2540 std::min(last_fit_evaluations_, rgmin_physical_work) +
2541 rgmin_logical_work;
2542 if (failed) surrogate_contradicted_ = true;
2543 if (scg_opt_settings.common.check_derivative &&
2544 parameters_cf.allFinite()) {
2545 const Eigen::VectorXd theta = parameters_cf;
2546 struct ObjectiveSample {
2547 double raw_value = 0.0;
2548 double map_value = 0.0;
2549 Eigen::VectorXd raw_gradient;
2550 Eigen::VectorXd map_gradient;
2551 };
2552 const auto sample = [&](const Eigen::VectorXd& point) {
2553 ObjectiveSample result;
2554 result.raw_gradient.resize(point.size());
2555 EnergyAndGradient eg(result.raw_value, result.raw_gradient);
2556 (objective.*callback)(point, opt_R_matrix, opt_R_indices,
2557 opt_energy_and_gradient, eg);
2558 result.map_value = result.raw_value;
2559 result.map_gradient = result.raw_gradient;
2560 funcmin::applyMapPenalty(point, map_objective_config,
2561 result.map_value,
2562 &result.map_gradient);
2563 return result;
2564 };
2565 const auto center = sample(theta);
2566 EigenMatrix audit_factor;
2567 if (!use_correction_ && !principled_nugget_ &&
2568 hyperparameter_objective_mode_ ==
2570#ifdef GPR_LINALG_SCALAPACK
2571 auto& state = backend().distributed();
2572 if (state.has_cached_L() &&
2573 state.cached_n() == opt_energy_and_gradient.size())
2574 audit_factor = state.gather(
2575 state.cached_L(), state.cached_L_desc(),
2576 state.cached_n(), state.cached_n(), true);
2577#else
2578 audit_factor = L;
2579#endif
2580 }
2581 Eigen::VectorXd audit_upper = parameter_upper;
2582 if (map_objective_config.use_magn_ceiling)
2583 audit_upper(0) =
2584 std::min(audit_upper(0),
2585 map_objective_config.max_log_magnSigma2);
2586 bool audit_root = true;
2587#ifdef GPR_LINALG_SCALAPACK
2588 audit_root = backend().distributed().is_root();
2589#endif
2590 if (audit_root && !use_correction_ && !principled_nugget_ &&
2591 hyperparameter_objective_mode_ ==
2593 EigenMatrix covariance;
2594 const bool cached_objective =
2595 hssvdObjectiveStampMatches() &&
2596 hssvd_objective_trace_via_cholesky_ &&
2597 hssvd_objective_pending_covariance_.rows() ==
2598 opt_energy_and_gradient.size();
2599 if (cached_objective) {
2600 covariance = hssvd_objective_pending_covariance_;
2601 if (!hssvd_objective_pending_permutation_.perm.empty())
2602 covariance = gpr::unpermuteSymmetricMatrix(
2603 covariance,
2604 hssvd_objective_pending_permutation_);
2605 } else {
2607 opt_R_matrix, opt_R_indices, covariance, true);
2608 covariance.diagonal().array() += jitter_sigma2;
2609 }
2610 log_man << "GP objective snapshot covariance: "
2611 << (cached_objective ? "active objective cache"
2612 : "independent assembly")
2613 << "\n";
2614 const double noise =
2615 lik_gaussian->getSigma2() + jitter_sigma2;
2616 const double constant = const_cov_fun->getConstSigma2();
2617 const double prior = -const_cov_fun->calculateLogPrior() -
2618 sexpat_cov_func->calculateLogPrior() -
2619 lik_gaussian->evaluateLogPrior();
2620 const FieldMatrixd prior_gradient =
2621 sexpat_cov_func->calculateLogPriorGradient();
2622 const double prior_amplitude_gradient =
2623 prior_gradient.size() ? -prior_gradient(0, 0) : 0.0;
2624 const std::uint64_t sizes[] = {
2625 static_cast<std::uint64_t>(covariance.rows()),
2626 static_cast<std::uint64_t>(opt_observation.E.size())};
2627 const double metadata[] = {noise,
2628 constant,
2629 center.raw_value,
2630 prior,
2631 center.raw_gradient(0),
2632 prior_amplitude_gradient};
2633 std::ofstream snapshot("gp-map-objective.bin",
2634 std::ios::binary);
2635 snapshot.write(reinterpret_cast<const char*>(sizes),
2636 sizeof(sizes));
2637 snapshot.write(reinterpret_cast<const char*>(metadata),
2638 sizeof(metadata));
2639 snapshot.write(
2640 reinterpret_cast<const char*>(covariance.data()),
2641 covariance.size() * sizeof(double));
2642 snapshot.write(
2643 reinterpret_cast<const char*>(
2644 opt_energy_and_gradient.data()),
2645 opt_energy_and_gradient.size() * sizeof(double));
2646 if (!snapshot)
2647 throw std::runtime_error(
2648 "cannot write GP objective covariance snapshot");
2649 if (cached_objective &&
2650 audit_factor.rows() == covariance.rows() &&
2651 b.size() == covariance.rows() &&
2652 hssvd_objective_alpha_.size() == covariance.rows()) {
2653 audit_factor
2654 .template triangularView<Eigen::StrictlyUpper>()
2655 .setZero();
2656 std::vector<std::int64_t> permutation(
2657 covariance.rows());
2658 for (Eigen::Index i = 0; i < covariance.rows(); ++i)
2659 permutation[i] = hasTrainingPermutation()
2660 ? training_permutation_.perm[i]
2661 : i;
2662 const std::uint64_t factor_header[] = {1, sizes[0]};
2663 std::ofstream factor_snapshot("gp-map-factor.bin",
2664 std::ios::binary);
2665 factor_snapshot.write(
2666 reinterpret_cast<const char*>(factor_header),
2667 sizeof(factor_header));
2668 factor_snapshot.write(
2669 reinterpret_cast<const char*>(permutation.data()),
2670 permutation.size() * sizeof(std::int64_t));
2671 for (const auto* matrix: {&audit_factor})
2672 factor_snapshot.write(
2673 reinterpret_cast<const char*>(matrix->data()),
2674 matrix->size() * sizeof(double));
2675 for (const auto* vector: {&b, &hssvd_objective_alpha_})
2676 factor_snapshot.write(
2677 reinterpret_cast<const char*>(vector->data()),
2678 vector->size() * sizeof(double));
2679 if (!factor_snapshot)
2680 throw std::runtime_error(
2681 "cannot write GP objective factor snapshot");
2682 }
2683 }
2684 for (Eigen::Index index = 0; index < theta.size(); ++index) {
2685 for (double step: {1e-2, 1e-3, 1e-4, 1e-5, 1e-6}) {
2686 Eigen::VectorXd first = theta, second = theta;
2687 double c1 = 0.0, c2 = 0.0;
2688 const char* stencil = nullptr;
2689 if (theta(index) - step >= parameter_lower(index) &&
2690 theta(index) + step < audit_upper(index)) {
2691 first(index) += step;
2692 second(index) -= step;
2693 c1 = 1.0;
2694 c2 = -1.0;
2695 stencil = "central";
2696 } else if (theta(index) + 2.0 * step <
2697 audit_upper(index)) {
2698 first(index) += step;
2699 second(index) += 2.0 * step;
2700 c1 = 4.0;
2701 c2 = -1.0;
2702 stencil = "forward";
2703 } else if (theta(index) - 2.0 * step >=
2704 parameter_lower(index)) {
2705 first(index) -= step;
2706 second(index) -= 2.0 * step;
2707 c1 = -4.0;
2708 c2 = 1.0;
2709 stencil = "backward";
2710 } else {
2711 continue;
2712 }
2713 const auto a = sample(first), b = sample(second);
2714 const double derivative =
2715 (c1 * (a.map_value - center.map_value) +
2716 c2 * (b.map_value - center.map_value)) /
2717 (2.0 * step);
2718 const double raw_derivative =
2719 (c1 * (a.raw_value - center.raw_value) +
2720 c2 * (b.raw_value - center.raw_value)) /
2721 (2.0 * step);
2722 std::fprintf(
2723 stderr,
2724 "[map-gradient] index=%lld step=%.17g "
2725 "stencil=%s theta=%.17g value=%.17g "
2726 "gradient=%.17g derivative=%.17g "
2727 "raw_gradient=%.17g raw_derivative=%.17g\n",
2728 static_cast<long long>(index), step, stencil,
2729 theta(index), center.map_value,
2730 center.map_gradient(index), derivative,
2731 center.raw_gradient(index), raw_derivative);
2732 }
2733 }
2734 // Restore the covariance and objective caches at the fitted
2735 // parameters so diagnostics preserve the model state.
2736 const auto repeated = sample(theta);
2737 if (audit_root)
2738 std::fprintf(
2739 stderr,
2740 "[map-gradient-repeat] value_delta=%.17g "
2741 "gradient_delta=%.17g\n",
2742 repeated.raw_value - center.raw_value,
2743 (repeated.raw_gradient - center.raw_gradient).norm());
2744 }
2745 if (!failed) return failed;
2746 const auto objective_value = [&](const Eigen::VectorXd& theta) {
2747 double value = 0.0;
2748 Eigen::VectorXd gradient(theta.size());
2749 EnergyAndGradient result(value, gradient);
2750 (objective.*callback)(theta, opt_R_matrix, opt_R_indices,
2751 opt_energy_and_gradient, result);
2752 funcmin::applyMapPenalty(theta, map_objective_config, value,
2753 &gradient);
2754 return gradient.allFinite() && std::isfinite(value)
2755 ? value
2756 : std::numeric_limits<double>::infinity();
2757 };
2758 // With no feasible fitted point the input theta is the only
2759 // candidate; probe it to record whether the marginal likelihood
2760 // is non-finite there, and when subset_failure_escalation_ is off
2761 // also record whether the penalized objective is evaluable.
2762 const auto note_input_evaluability = [&]() {
2763 double value = 0.0;
2764 Eigen::VectorXd gradient(initial_parameters.size());
2765 EnergyAndGradient result(value, gradient);
2766 (objective.*callback)(initial_parameters, opt_R_matrix,
2767 opt_R_indices, opt_energy_and_gradient,
2768 result);
2769 if (!std::isfinite(value))
2770 optimizer_state_->last_input_marginal_likelihood_nonfinite =
2771 true;
2773 initial_parameters, map_objective_config, value, &gradient);
2774 if (!subset_failure_escalation_)
2775 last_failed_fit_evaluable_ = std::isfinite(value);
2776 };
2777 if (!parameters_cf.allFinite()) {
2778 note_input_evaluability();
2779 return failed;
2780 }
2781 project_lengthscales_to_domain(parameters_cf);
2782 const double fitted_value = objective_value(parameters_cf);
2783 if (!std::isfinite(fitted_value)) {
2784 note_input_evaluability();
2785 return failed;
2786 }
2787 const double initial_value = objective_value(initial_parameters);
2788 last_failed_fit_improved_ = fitted_value < initial_value;
2789 if (last_failed_fit_improved_ && report_level >= 1) {
2790 log_man << "Feasible MAP objective decrease: " << initial_value
2791 << " -> " << fitted_value << ".\n";
2792 }
2793 return failed;
2794 };
2795#ifdef USE_ANNEAL
2796 // The global stage: on the first fit and every anneal_every_-th
2797 // fit after it, anneal's box ensemble searches the box around the
2798 // warm start and hands its best point to the local optimizer.
2799 // A restricted fit (an amplitude-only or active-subspace refit)
2800 // is not a search over the box: only a fit of every parameter
2801 // counts and runs the stage.
2802 const bool full_fit =
2803 scg_opt_settings.active_parameters.empty() ||
2804 std::all_of(scg_opt_settings.active_parameters.begin(),
2805 scg_opt_settings.active_parameters.end(),
2806 [](bool active) { return active; });
2807 if (anneal_enabled_ && full_fit)
2808 last_anneal_stage_.fits = ++anneal_fit_counter_;
2809 const bool stage_due =
2810 anneal_enabled_ && full_fit &&
2811 (anneal_every_ > 0
2812 ? (anneal_fit_counter_ - 1) % anneal_every_ == 0
2813 : anneal_fit_counter_ == 1 || surrogate_contradicted_);
2814 if (stage_due) {
2815 surrogate_contradicted_ = false;
2816 funcmin::AnnealStageSettings stage;
2817 Eigen::VectorXd anneal_lower = parameter_lower;
2818 Eigen::VectorXd anneal_upper = parameter_upper;
2819 if (ties_active) {
2820 // Only leaders parameterize the tied objective. Pinning its
2821 // redundant storage coordinates keeps the ensemble's box
2822 // distance and proposals in the independent subspace.
2823 for (Index_t t = 0; t < length_scale_ties_.count(); ++t) {
2824 if (length_scale_ties_.leader[t] == t) continue;
2825 anneal_lower(1 + t) = parameters_cf(1 + t);
2826 anneal_upper(1 + t) = parameters_cf(1 + t);
2827 }
2828 }
2829 const auto independent_parameters = static_cast<std::size_t>(
2830 (anneal_lower.array() < anneal_upper.array()).count());
2831 // The last local fit's work, with one opening evaluation and
2832 // one per independent parameter as the automatic minimum.
2833 stage.budget = anneal_budget_ > 0
2834 ? anneal_budget_
2835 : std::max(last_fit_budget_evaluations_,
2836 independent_parameters + 1);
2837 stage.replicas = anneal_replicas_;
2838 // The box: the length-scale prior's scale either way from the
2839 // warm start; a factor e when no prior scale is configured.
2840 stage.box_halfwidth = parameter_search_halfwidth;
2841 last_anneal_stage_.budget = stage.budget;
2842 last_anneal_stage_.box_halfwidth = stage.box_halfwidth;
2843 // The counter was advanced above: the first stage runs
2844 // with seed + 1, each later one with its own fit number.
2845 stage.seed = anneal_seed_ + anneal_fit_counter_;
2846 const auto report = funcmin::annealMapStage(
2847 opt_R_matrix, opt_R_indices, opt_energy_and_gradient,
2848 parameters_cf, objective, callback, map_objective_config,
2849 anneal_lower, anneal_upper, stage,
2850 optimizer_settings.common.report_level);
2851 last_anneal_stage_.ran = report.ran;
2852 last_anneal_stage_.failed = report.failed;
2853 last_anneal_stage_.improved = report.improved;
2854 // The stage's point is another basin: the previous fit's
2855 // quasi-Newton memory does not describe it.
2856 if (report.improved) forgetRgminSessions();
2857 last_anneal_stage_.start_value = report.start_value;
2858 last_anneal_stage_.value = report.value;
2859 last_anneal_stage_.evaluations = report.evaluations;
2860 last_anneal_stage_.gradients = report.gradients;
2861 last_anneal_stage_.hops = report.hops;
2862 if (report.ran) ++last_anneal_stage_.runs;
2863 if (report_level >= 1 && report.ran) {
2864 log_man << "Anneal stage: objective " << report.start_value
2865 << " -> " << report.value << " in "
2866 << report.evaluations << " evaluations, "
2867 << report.gradients << " gradients, " << report.hops
2868 << " hops"
2869 << (report.improved ? "; the local fit starts there"
2870 : "; the warm start stands")
2871 << ".\n";
2872 }
2873 }
2874#endif
2875 // The unchanged-subset skip may hold only a fit that met the
2876 // gradient tolerance: a step-size exit is not stationarity. Every
2877 // fit that ends without failing, including the rgmin retry after a
2878 // stalled SCG, reports the MAP gradient norm at its parameters.
2879 auto record_fit_gradient = [&]() {
2880 if (!skip_unchanged_subset_fit_ || !parameters_cf.allFinite())
2881 return;
2882 double value = 0.0;
2883 Eigen::VectorXd gradient(parameters_cf.size());
2884 EnergyAndGradient result(value, gradient);
2885 (objective.*callback)(parameters_cf, opt_R_matrix, opt_R_indices,
2886 opt_energy_and_gradient, result);
2887 funcmin::applyMapPenalty(parameters_cf, map_objective_config, value,
2888 &gradient);
2889 funcmin::projectMapGradient(map_objective_config, gradient);
2890 if (std::isfinite(value) && gradient.allFinite())
2891 last_fit_gradient_norm_ = gradient.norm();
2892 };
2893 // The MAP fit is judged by its gradient. SCG stops on its own step
2894 // and objective-change test with that gradient orders of magnitude
2895 // above the tolerance on every outer of a large cell (11_grignard:
2896 // 0.4 against 0.001, 55 of 53 outers), and the rgmin L-BFGS retry
2897 // then does the fit. A stall is remembered: from then on the fit
2898 // starts with L-BFGS and the stalled optimizer is not run again,
2899 // which removes the wasted half of the refit wall (measured 5.6 s
2900 // against 13.2 s per outer on 17_oxycope).
2901 bool rejected_nonimproving_fallback = false;
2902 auto run_alternative = [&](double gradient_tolerance) {
2903 rejected_nonimproving_fallback = false;
2904 optimizer_state_->last_fallback_rejected = false;
2905 const Eigen::VectorXd scg_point = parameters_cf;
2906 const bool scg_point_feasible =
2907 scg_point.allFinite() &&
2908 (scg_point.array() >= parameter_lower.array()).all() &&
2909 (scg_point.array() <= parameter_upper.array()).all();
2910 const auto map_value = [&](const Eigen::VectorXd& point) {
2911 double value = 0.0;
2912 Eigen::VectorXd gradient(point.size());
2913 EnergyAndGradient result(value, gradient);
2914 (objective.*callback)(point, opt_R_matrix, opt_R_indices,
2915 opt_energy_and_gradient, result);
2916 funcmin::applyMapPenalty(point, map_objective_config, value,
2917 &gradient);
2918 return std::isfinite(value)
2919 ? value
2920 : std::numeric_limits<double>::infinity();
2921 };
2922 last_scg_fallback_used_ = true;
2923 funcmin::RgminOpt& alternative = optimizer_state_->scg_alternative;
2924 alternative.setPersistentSession(rgmin_warm_start_);
2925 alternative.setAlgorithmSettings(optimizer_settings);
2926 alternative.setMethod(RGMIN_LBFGS);
2927 alternative.setGradTol(gradient_tolerance);
2928 alternative.setBox(parameter_lower, parameter_upper);
2929 double lbfgs_opening_value =
2930 std::numeric_limits<double>::quiet_NaN();
2931 double lbfgs_last_value = std::numeric_limits<double>::quiet_NaN();
2932 alternative.optimizeWithObjectiveValues(
2933 opt_R_matrix, opt_R_indices, opt_energy_and_gradient,
2934 parameters_cf, callback, objective, current_barrier_strength,
2935 lengthscale_rho0, &map_objective_config, &lbfgs_opening_value,
2936 &lbfgs_last_value);
2937 rgmin_logical_work += alternative.logicalObjectiveWork();
2938 rgmin_physical_work += alternative.physicalObjectiveWork();
2939 if (alternative.failedOptim && report_level >= 2) {
2940 log_man << "Failed rgmin MAP parameters: "
2941 << parameters_cf.transpose() << "\n";
2942 }
2943 // A dimer search asks to keep L-BFGS only when it lowers the
2944 // MAP objective by more than the absolute tolerance
2945 // improvement_tol (1e-3 in objective units, not a ratio). Both
2946 // values are the ones this fit already computed: scoring them again
2947 // leaves the factor off the point L-BFGS restored. Only a rejection
2948 // restores a feasible SCG point and rebuilds the factor there.
2949 if (optimizer_state_->require_scg_fallback_improvement &&
2950 !alternative.failedOptim && scg_point_feasible) {
2951 const double lbfgs_value = lbfgs_last_value;
2952 const double scg_value = lbfgs_opening_value;
2953 const bool comparable =
2954 std::isfinite(lbfgs_value) && std::isfinite(scg_value);
2955 const double improvement_tol = 1.0e-3;
2956 if (comparable &&
2957 !(lbfgs_value < scg_value - improvement_tol)) {
2958 parameters_cf = scg_point;
2959 (void)map_value(parameters_cf);
2960 rejected_nonimproving_fallback = true;
2961 optimizer_state_->last_fallback_rejected = true;
2962 last_scg_fallback_used_ = false;
2963 }
2964 }
2965 if (!alternative.failedOptim && !rejected_nonimproving_fallback) {
2966 record_fit_gradient();
2967 }
2968 return retain_feasible_improvement(alternative.failedOptim ||
2969 rejected_nonimproving_fallback);
2970 };
2971 const auto drop_rejected_stall = [&]() {
2972 if (!rejected_nonimproving_fallback) return;
2973 scg_stalled_ = false;
2974 scg_stall_scope_ = {};
2975 };
2976 const auto scg_dim = static_cast<std::size_t>(parameters_cf.size());
2977 const ScgStallScope current_scg_scope{
2978 scg_dim,
2979 map_objective_config.active_parameters.empty()
2980 ? std::vector<bool>(scg_dim, true)
2981 : map_objective_config.active_parameters,
2982 hyperparameter_objective_mode_,
2983 model_profile_,
2984 unregularized_marginal_likelihood_,
2985 lik_gaussian != nullptr && lik_gaussian->getOptimizeSigma2(),
2986 disable_output_normalization_,
2987 zblPriorMeanActive() && !ffPriorMeanActive(),
2988 ffPriorMeanActive(),
2990 ties_active,
2991 ties_active ? length_scale_ties_.released : std::vector<bool>{}};
2992 if constexpr (kUsesScg<Optimizer>) {
2993 if (scg_stalled_ && scg_stall_scope_ != current_scg_scope) {
2994 scg_stalled_ = false;
2995 scg_stall_scope_ = {};
2996 }
2997 if (scg_stalled_) {
2998 const bool failed = run_alternative(
2999 std::min(scg_opt_settings.common.tolerance_func,
3000 scg_opt_settings.common.tolerance_sol));
3001 drop_rejected_stall();
3002 return failed;
3003 }
3004 }
3005 optimizer.optimize(opt_R_matrix, opt_R_indices, opt_energy_and_gradient,
3006 parameters_cf, callback, objective,
3007 current_barrier_strength, lengthscale_rho0,
3008 &map_objective_config);
3009 if constexpr (kUsesScg<Optimizer>) {
3010 if (optimizer.hessianVectorFallback) {
3012 "the MAP optimizer",
3013 "the exact NLML Hessian-vector product was unavailable or "
3014 "failed during the fit");
3015 }
3016 }
3017 if constexpr (std::is_same_v<Optimizer, funcmin::RgminOpt>) {
3018 rgmin_logical_work += optimizer.logicalObjectiveWork();
3019 rgmin_physical_work += optimizer.physicalObjectiveWork();
3020 }
3021 if constexpr (kUsesScg<Optimizer>) {
3022 const double gradient_tolerance =
3023 std::min(scg_opt_settings.common.tolerance_func,
3024 scg_opt_settings.common.tolerance_sol);
3025 bool needs_alternative =
3026 optimizer.failedOptim || !parameters_cf.allFinite() ||
3027 (parameters_cf.array() < parameter_lower.array()).any() ||
3028 (parameters_cf.array() > parameter_upper.array()).any();
3029 if (!needs_alternative) {
3030 double value = 0.0;
3031 Eigen::VectorXd gradient(parameters_cf.size());
3032 EnergyAndGradient result(value, gradient);
3033 (objective.*callback)(parameters_cf, opt_R_matrix,
3034 opt_R_indices, opt_energy_and_gradient,
3035 result);
3036 funcmin::applyMapPenalty(parameters_cf, map_objective_config,
3037 value, &gradient);
3038 funcmin::projectMapGradient(map_objective_config, gradient);
3039 needs_alternative = !std::isfinite(value) ||
3040 !gradient.allFinite() ||
3041 gradient.norm() > gradient_tolerance;
3042 if (needs_alternative && report_level >= 1) {
3043 log_man << "SCG stopped with MAP gradient norm "
3044 << gradient.norm() << " above tolerance "
3045 << gradient_tolerance << ".\n";
3046 }
3047 }
3048 if (needs_alternative) {
3049 // A requested iteration limit does not establish a solver
3050 // stall or change the optimizer sequence of later fits.
3051 // The steps SCG already took belong to this fit even
3052 // though L-BFGS finishes it.
3053 scg_steps_before_fallback = optimizer.completedIterations;
3054 if (!optimizer.exhaustedIterationBudget) {
3055 scg_stalled_ = true;
3056 scg_stall_scope_ = current_scg_scope;
3057 }
3058 if (report_level >= 2) {
3059 log_man
3060 << "MAP input parameters: "
3061 << initial_parameters.transpose()
3062 << "\nSCG returned parameters: "
3063 << parameters_cf.transpose()
3064 << "\nMAP lower bounds: " << parameter_lower.transpose()
3065 << "\nMAP upper bounds: " << parameter_upper.transpose()
3066 << "\n";
3067 }
3068 if (report_level >= 1) {
3069 log_man << "SCG did not converge; retrying the MAP fit "
3070 "with rgmin L-BFGS.\n";
3071 }
3072 const bool failed = run_alternative(gradient_tolerance);
3073 drop_rejected_stall();
3074 return failed;
3075 }
3076 }
3077 if (!optimizer.failedOptim) record_fit_gradient();
3078 return retain_feasible_improvement(optimizer.failedOptim);
3079 };
3080
3081 auto optimize_objective = [&](auto& objective) {
3082 using Objective = std::decay_t<decltype(objective)>;
3083 const auto callback = &Objective::evaluateEnergyAndGradient;
3084 std::visit(
3085 [&](auto& optimizer) {
3086 using Optimizer = std::decay_t<decltype(optimizer)>;
3087 if constexpr (kIsScgLike<Optimizer>) {
3088 failedOptimizer =
3089 run_map_optimizer(optimizer, objective, callback);
3090 } else {
3091 optimizer.optimize(opt_R_matrix, opt_R_indices,
3092 opt_energy_and_gradient, parameters_cf,
3093 callback, objective,
3094 current_barrier_strength);
3095 failedOptimizer = optimizer.failedOptim;
3096 if (failedOptimizer && !subset_failure_escalation_) {
3097 double value = 0.0;
3098 Eigen::VectorXd gradient(parameters_cf.size());
3099 EnergyAndGradient result(value, gradient);
3100 (objective.*callback)(parameters_cf, opt_R_matrix,
3101 opt_R_indices,
3102 opt_energy_and_gradient, result);
3103 last_failed_fit_evaluable_ =
3104 std::isfinite(value) && gradient.allFinite();
3105 }
3106 }
3107 },
3108 optimizer_state_->optimizer);
3109 };
3110 if (report_level >= 1) {
3111 log_man << "GP parameter optimizer: "
3113 << " backend=" << getHyperparameterOptimizerBackend();
3114 if (ties_active)
3115 log_man << " tied length scales="
3116 << length_scale_ties_.count() -
3117 std::count(length_scale_ties_.released.begin(),
3118 length_scale_ties_.released.end(), true);
3119 log_man << "\n";
3120 }
3121 // Release tied length scales on accumulated evidence. Releases are
3122 // monotone: a released scale stays its own. Each fit screens the tied
3123 // members by the quadratic model along their own coordinate, g^2/(2h)
3124 // against the Occam cost of one parameter, half the log of the row
3125 // count. The curvatures h come from Hutchinson's diagonal estimator
3126 // (Bekas, Kokiopoulou and Saad 2007): gradient differences along
3127 // random sign vectors over the candidate coordinates, taken one at a
3128 // time until every candidate is settled to one standard error or the
3129 // candidates still ambiguous number no more than the probes spent, at
3130 // which point those are probed exactly. The screened set is released
3131 // in a trial refit, the realized change of the negative log marginal
3132 // likelihood is attributed to the candidates in proportion to their
3133 // predicted gains, and each candidate's share less the Occam cost
3134 // feeds its cumulative sum (Page 1954), floored at zero; a candidate
3135 // whose sum reaches the Occam cost is released, the others return to
3136 // their groups. Evidence from one subset fit that falls short is thus
3137 // kept, and a marginal scale is released only once several fits agree.
3138 auto review_length_scale_ties = [&](auto& objective, auto callback) {
3139 if (!ties_active || failedOptimizer) return;
3140 const auto t0 = std::chrono::steady_clock::now();
3141 auto& ties = length_scale_ties_;
3142 if (ties.evidence.size() != ties.parent.size())
3143 ties.evidence.assign(ties.parent.size(), 0.0);
3144 // The objective's energy carries the covariance function's own
3145 // prior, whose terms change with the tie structure (a released
3146 // type gains one); the evidence compares likelihoods, so that
3147 // prior is added back at the evaluated point.
3148 const auto evaluate = [&](const Eigen::VectorXd& point, double& nlml,
3149 Eigen::VectorXd& gradient) {
3150 nlml = 0.0;
3151 gradient = Eigen::VectorXd::Zero(point.size());
3152 EnergyAndGradient eg(nlml, gradient);
3153 (objective.*callback)(point, opt_R_matrix, opt_R_indices,
3154 opt_energy_and_gradient, eg);
3155 if (sexpat_cov_func != nullptr && std::isfinite(nlml))
3156 nlml += sexpat_cov_func->calculateLogPrior();
3157 double penalised = nlml;
3158 funcmin::applyMapPenalty(point, map_objective_config, penalised,
3159 &gradient);
3160 return std::isfinite(nlml) && gradient.size() == point.size() &&
3161 gradient.allFinite();
3162 };
3163 const double occam =
3164 0.5 * std::log(static_cast<double>(opt_energy_and_gradient.size()));
3165 double nlml0 = 0.0;
3166 Eigen::VectorXd base;
3167 if (!evaluate(parameters_cf, nlml0, base)) return;
3168 const double step = std::cbrt(std::numeric_limits<double>::epsilon());
3169 // Candidates: tied members the data identify.
3170 std::vector<Index_t> candidates;
3171 for (Index_t t = 0; t < ties.count(); ++t) {
3172 const auto index = static_cast<std::size_t>(t);
3173 if (ties.released[index] || ties.leader[index] == t) continue;
3174 const auto p = static_cast<std::size_t>(1 + t);
3175 if (scg_opt_settings.active_parameters.size() ==
3176 static_cast<std::size_t>(parameters_cf.size()) &&
3177 !scg_opt_settings.active_parameters[p])
3178 continue;
3179 candidates.push_back(t);
3180 }
3181 if (candidates.empty()) return;
3182 // The quadratic is local to the same prior-width neighborhood used
3183 // for hyperparameter exploration, intersected with the fit domain.
3184 const auto lower_step = [&](Index_t p) {
3185 return std::max(parameter_lower(p) - parameters_cf(p),
3186 -parameter_search_halfwidth);
3187 };
3188 const auto upper_step = [&](Index_t p) {
3189 return std::min(parameter_upper(p) - parameters_cf(p),
3190 parameter_search_halfwidth);
3191 };
3192 const auto gain_at = [&](Index_t t, double curvature) {
3193 const auto p = 1 + t;
3194 return detail::quadraticEvidenceGain(base(p), curvature,
3195 lower_step(p), upper_step(p));
3196 };
3197 // Curvature and gain belong to this likelihood at this parameter
3198 // vector. Changed training rows require their own screening probes.
3199 // Hutchinson diagonal over the candidate coordinates.
3200 const std::size_t count = candidates.size();
3201 std::vector<double> sum(count, 0.0), sum_sq(count, 0.0);
3202 std::vector<int> settled(count, 0); // 1 pass, -1 fail, 0 ambiguous
3203 std::vector<double> curvature(count, 0.0);
3204 int probes = 0;
3205 std::mt19937_64 signs(static_cast<std::uint64_t>(
3206 opt_energy_and_gradient.size() + ties.count()));
3207 // Under nlml_hessian_vector the product is exact at the factor the
3208 // base evaluate() built. Without the product, or from the first
3209 // product that fails, the screen takes the one-sided differences of
3210 // finite_difference.
3211 bool hessian_vector_probes = nlmlHessianVectorCurvatureRequested();
3212 if (hessian_vector_probes &&
3214 hessian_vector_probes = false;
3216 "the length-scale tie screen",
3217 "the objective has no exact NLML Hessian-vector product");
3218 }
3219 const auto probe_along = [&](const Eigen::VectorXd& direction,
3220 Eigen::VectorXd& hv) {
3221 if (hessian_vector_probes) {
3222 ++probes;
3224 objective, opt_R_indices, opt_R_matrix,
3225 opt_energy_and_gradient, direction, hv)) {
3226 funcmin::mapPenaltyHessianVector(parameters_cf, direction,
3227 map_objective_config, hv);
3228 if (hv.allFinite()) return true;
3229 }
3230 --probes;
3231 hessian_vector_probes = false;
3233 "the length-scale tie screen",
3234 "the exact NLML Hessian-vector product failed");
3235 }
3236 Eigen::VectorXd point = parameters_cf + step * direction;
3237 double nlml_probe = 0.0;
3238 Eigen::VectorXd shifted;
3239 ++probes;
3240 if (!evaluate(point, nlml_probe, shifted)) return false;
3241 hv = (shifted - base) / step;
3242 return true;
3243 };
3244 bool stochastic = count > 2;
3245 if (stochastic) {
3246 std::vector<int> z(count, 1);
3247 for (std::size_t i = 1; i <= count; ++i) {
3248 for (std::size_t c = 0; c < count; ++c)
3249 z[c] = (signs() & 1U) ? 1 : -1;
3250 Eigen::VectorXd direction =
3251 Eigen::VectorXd::Zero(parameters_cf.size());
3252 for (std::size_t c = 0; c < count; ++c)
3253 direction(1 + candidates[c]) = z[c];
3254 Eigen::VectorXd hv;
3255 if (!probe_along(direction, hv)) {
3256 stochastic = false;
3257 break;
3258 }
3259 for (std::size_t c = 0; c < count; ++c) {
3260 const double d = z[c] * hv(1 + candidates[c]);
3261 sum[c] += d;
3262 sum_sq[c] += d * d;
3263 }
3264 if (i < 2) continue;
3265 std::size_t ambiguous = 0;
3266 for (std::size_t c = 0; c < count; ++c) {
3267 const double mean = sum[c] / static_cast<double>(i);
3268 const double variance = std::max(
3269 0.0, sum_sq[c] / static_cast<double>(i) - mean * mean);
3270 const double error =
3271 std::sqrt(variance / static_cast<double>(i - 1));
3272 const double low = mean - error, high = mean + error;
3273 const auto p = 1 + candidates[c];
3274 settled[c] =
3275 static_cast<int>(detail::screenQuadraticEvidence(
3276 base(p), low, high, occam, lower_step(p),
3277 upper_step(p)));
3278 curvature[c] = mean;
3279 if (settled[c] == 0) ++ambiguous;
3280 }
3281 if (ambiguous == 0 || ambiguous <= i) break;
3282 }
3283 }
3284 // Exact probes for the ambiguous candidates, or for all of them
3285 // when the stochastic screen was not used.
3286 for (std::size_t c = 0; c < count; ++c) {
3287 if (stochastic && settled[c] != 0) continue;
3288 Eigen::VectorXd direction =
3289 Eigen::VectorXd::Zero(parameters_cf.size());
3290 direction(1 + candidates[c]) = 1.0;
3291 Eigen::VectorXd hv;
3292 if (!probe_along(direction, hv)) {
3293 settled[c] = -1;
3294 continue;
3295 }
3296 curvature[c] = hv(1 + candidates[c]);
3297 settled[c] = gain_at(candidates[c], curvature[c]) > occam ? 1 : -1;
3298 }
3299 last_tie_screen_probes_ = probes;
3300 last_tie_screen_hessian_vector_ = hessian_vector_probes;
3301 last_tie_screen_curvatures_ = curvature;
3302 std::vector<Index_t> screened;
3303 std::vector<double> predicted;
3304 for (std::size_t c = 0; c < count; ++c) {
3305 if (settled[c] != 1) continue;
3306 screened.push_back(candidates[c]);
3307 predicted.push_back(gain_at(candidates[c], curvature[c]));
3308 }
3309 int released_now = 0;
3310 if (!screened.empty()) {
3311 // Trial release of the screened set.
3312 const std::vector<bool> released_before = ties.released;
3313 const Eigen::VectorXd parameters_before = parameters_cf;
3314 const Eigen::VectorXd prior_weight_before =
3315 map_objective_config.prior_weight;
3316 const auto mask_before = scg_opt_settings.active_parameters;
3317 const Eigen::VectorXd lower_before = parameter_lower;
3318 const Eigen::VectorXd upper_before = parameter_upper;
3319 for (const Index_t t: screened)
3320 ties.released[static_cast<std::size_t>(t)] = true;
3322 refresh_tie_structure();
3323 detail::TiedLengthScaleObjective<std::decay_t<decltype(objective)>>
3324 tied{objective, *this};
3325 optimize_objective(tied);
3326 tieLengthScaleParameters(parameters_cf);
3327 double nlml_after = 0.0;
3328 Eigen::VectorXd gradient_after;
3329 const bool ok = !failedOptimizer &&
3330 evaluate(parameters_cf, nlml_after, gradient_after);
3331 const double change = ok ? nlml0 - nlml_after : 0.0;
3332 double predicted_total = 0.0;
3333 for (const double g: predicted)
3334 predicted_total += g;
3335 std::vector<Index_t> keep;
3336 for (std::size_t k = 0; k < screened.size(); ++k) {
3337 const auto index = static_cast<std::size_t>(screened[k]);
3338 const double share =
3339 predicted_total > 0.0
3340 ? change * predicted[k] / predicted_total
3341 : change / static_cast<double>(screened.size());
3342 double& evidence = ties.evidence[index];
3343 evidence =
3344 ok ? std::max(0.0, evidence + share - occam) : evidence;
3345 if (ok && evidence >= occam) keep.push_back(screened[k]);
3346 }
3347 if (report_level >= 1) {
3348 log_man << "Length-scale ties: trial release of "
3349 << screened.size() << " pair type(s)";
3350 for (std::size_t k = 0; k < screened.size(); ++k)
3351 log_man
3352 << " " << screened[k] << "/"
3353 << ties.parent[static_cast<std::size_t>(screened[k])]
3354 << "("
3355 << ties.evidence[static_cast<std::size_t>(screened[k])]
3356 << ")";
3357 log_man << (ok ? " changed the objective by " : " failed; ")
3358 << (ok ? std::to_string(change) : std::string())
3359 << " against " << occam
3360 << " per parameter: " << keep.size() << " released.\n";
3361 }
3362 if (keep.size() == screened.size() && ok) {
3363 released_now = static_cast<int>(keep.size());
3364 } else {
3365 // Return the others to their groups; a kept release keeps
3366 // its fitted scale, the next fit refines the rest.
3367 ties.released = released_before;
3368 for (const Index_t t: keep)
3369 ties.released[static_cast<std::size_t>(t)] = true;
3371 if (keep.empty()) {
3372 parameters_cf = parameters_before;
3373 map_objective_config.prior_weight = prior_weight_before;
3374 scg_opt_settings.active_parameters = mask_before;
3375 parameter_lower = lower_before;
3376 parameter_upper = upper_before;
3377 map_objective_config.parameter_lower = parameter_lower;
3378 map_objective_config.parameter_upper = parameter_upper;
3379 } else {
3380 refresh_tie_structure();
3381 tieLengthScaleParameters(parameters_cf);
3382 }
3383 released_now = static_cast<int>(keep.size());
3384 failedOptimizer = false;
3385 }
3386 }
3387 if (report_level >= 1 && (probes > 0 || released_now > 0)) {
3388 log_man << "Length-scale ties: " << probes << " probes ("
3389 << (stochastic ? "stochastic" : "exact") << "), "
3390 << screened.size() << " screened, " << released_now
3391 << " released, "
3392 << std::count(ties.released.begin(), ties.released.end(),
3393 true)
3394 << "/" << ties.count() << " own scales, occam " << occam
3395 << ", "
3396 << std::chrono::duration<double>(
3397 std::chrono::steady_clock::now() - t0)
3398 .count()
3399 << " s.\n";
3400 }
3401 };
3402 auto optimize_with_ties = [&](auto& objective) {
3403 using Objective = std::decay_t<decltype(objective)>;
3404 if (ties_active) {
3405 detail::TiedLengthScaleObjective<Objective> tied{objective, *this};
3406 optimize_objective(tied);
3407 // The optimizer's iterate is the tied point up to the per-index
3408 // domain clamps; restate the ties before reading it.
3409 tieLengthScaleParameters(parameters_cf);
3410 review_length_scale_ties(objective,
3411 &Objective::evaluateEnergyAndGradient);
3412 } else {
3413 optimize_objective(objective);
3414 }
3415 };
3416 if (training_geom_ready) {
3417#ifdef GPR_LINALG_SCALAPACK
3418 auto& st = backend().distributed();
3419 st.initialize();
3420 if (st.nprocs() > 1) {
3421 CanonicalDistributedMapObjective objective{*this, training_geom};
3422 optimize_with_ties(objective);
3423 } else
3424#endif
3425 {
3426 TrainingGeometryObjective objective{*this, training_geom};
3427 optimize_with_ties(objective);
3428 }
3429 } else {
3430 optimize_with_ties(*this);
3431 }
3432
3433 last_scg_exhausted_iteration_budget_ = false;
3434 last_fit_iterations_ = 0;
3435 last_fit_restarts_ = 0;
3436 last_fit_stop_reason_ = "unset";
3437 if (last_scg_fallback_used_) {
3438 const auto& alt = optimizer_state_->scg_alternative;
3439 last_scg_exhausted_iteration_budget_ = alt.exhaustedIterationBudget;
3440 last_fit_iterations_ =
3441 scg_steps_before_fallback + alt.completedIterations;
3442 last_fit_stop_reason_ =
3443 alt.exhaustedIterationBudget ? "budget" : "library";
3444 } else {
3445 std::visit(
3446 [&](auto& _popt) {
3447 using OptType = std::decay_t<decltype(_popt)>;
3448 if constexpr (std::is_same_v<OptType, funcmin::RgminScg> ||
3449 std::is_same_v<OptType, funcmin::RgminOpt>) {
3450 last_scg_exhausted_iteration_budget_ =
3451 _popt.exhaustedIterationBudget;
3452 last_fit_iterations_ = _popt.completedIterations;
3453 last_fit_stop_reason_ =
3454 _popt.exhaustedIterationBudget ? "budget" : "library";
3455 }
3456 },
3457 optimizer_state_->optimizer);
3458 }
3459 if (optimizer_state_->last_fallback_rejected) {
3460 last_fit_stop_reason_ = "restored scg point";
3461 }
3462
3463 project_lengthscales_to_domain(parameters_cf);
3464
3465 const double skip_scg_threshold =
3466 objectiveStationaritySkipThreshold(parameters_cf);
3467 if (!failedOptimizer && !using_loo_objective &&
3468 !using_local_loo_objective && skip_scg_threshold > 0.0) {
3469 bool stationarity_cache_ready = false;
3470 const bool use_bb_stationarity =
3471 use_hssvd_backend_ && objective_stationarity_bb_valid_;
3472 // Automatic checks reuse optimizer curvature or evaluate a directional
3473 // secant when observations change. A dense Hessian costs quadratically
3474 // many directional probes as environment-specific length scales grow.
3475 const bool explicit_stationarity_hessian =
3476 laplace_skip_scg_threshold_ > 0.0 &&
3477 std::isfinite(laplace_skip_scg_threshold_);
3478 if (!stationarity_cache_ready && !use_bb_stationarity &&
3479 explicit_stationarity_hessian) {
3480 stationarity_cache_ready = cacheObjectiveStationarityHessian(
3481 opt_R_indices, opt_R_matrix, opt_energy_and_gradient,
3482 parameters_cf);
3483 }
3484 if (!stationarity_cache_ready && !use_bb_stationarity) {
3485 invalidateObjectiveStationarityHessian();
3486 }
3487 } else if (failedOptimizer) {
3488 invalidateObjectiveStationarityHessian();
3489 }
3490
3491 if (this->report_level >= 2) {
3492 auto elp_time = (std::chrono::steady_clock::now() - start);
3493 auto elp_seconds =
3494 std::chrono::duration_cast<std::chrono::duration<double>>(elp_time);
3495
3496 log_man << "Optimization finished in: " << elp_seconds.count()
3497 << "s. Success: " << !failedOptimizer << "\n";
3498 log_man << "Parameter change norm: "
3499 << (old_parameters_cf - parameters_cf).norm() << "\n";
3500 }
3501
3503 opt_observation.R, opt_energy_and_gradient, parameters_cf,
3504 map_objective_config, objective_frame.target_scale, true);
3505 leaveOptimizationObjectiveFrame(objective_frame, &parameters_cf);
3506 return parameters_cf;
3507}
3508
3522 const Eigen::VectorXd& new_parameters)
3523{
3524 // 1. Store the latest hyperparameter vector and maintain history buffer
3525 // size.
3526 hyperparameter_history_.push_back(new_parameters);
3527 while (static_cast<int>(hyperparameter_history_.size()) >
3528 monitoring_window_ + 1) {
3529 hyperparameter_history_.pop_front();
3530 }
3531
3532 // 2. Check for instability only if we have enough data and history is not
3533 // maxed out.
3534 if (static_cast<int>(hyperparameter_history_.size()) !=
3535 monitoring_window_ + 1 ||
3536 fps_options.history >= max_history_) {
3537 return false; // Not enough data or already maxed out, so no retry.
3538 }
3539
3540 const int num_params = new_parameters.size();
3541 // A tied member mirrors its leader; only the fitted parameters count.
3542 const auto counted = [&](int j) {
3543 const auto& ties = length_scale_ties_;
3544 if (!ties.valid || j < 1 || j > static_cast<int>(ties.count()))
3545 return true;
3546 const auto t = static_cast<std::size_t>(j - 1);
3547 return ties.leader[t] == static_cast<Index_t>(t);
3548 };
3549 int counted_params = 0;
3550 for (int j = 0; j < num_params; ++j)
3551 if (counted(j)) ++counted_params;
3552 const int total_possible_flips = counted_params * (monitoring_window_ - 1);
3553 if (total_possible_flips <= 0) {
3554 return false; // Cannot compute flips, so no retry.
3555 }
3556
3557 int sign_flips = 0;
3558 // Iterate through a 3-point sliding window to check for oscillations.
3559 for (int i = 0; i < monitoring_window_ - 1; ++i) {
3560 const Eigen::VectorXd& h_old = hyperparameter_history_[i];
3561 const Eigen::VectorXd& h_mid = hyperparameter_history_[i + 1];
3562 const Eigen::VectorXd& h_new = hyperparameter_history_[i + 2];
3563
3564 Eigen::VectorXd delta1 = h_mid - h_old;
3565 Eigen::VectorXd delta2 = h_new - h_mid;
3566
3567 // Check for sign flips for each hyperparameter component
3568 for (int j = 0; j < num_params; ++j) {
3569 if (!counted(j)) continue;
3570 if (delta1(j) * delta2(j) < -1e-9) { // Using a small tolerance
3571 sign_flips++;
3572 }
3573 }
3574 }
3575
3576 // 3. If instability is detected, increase the history size and signal for a
3577 // retry.
3578 double flip_ratio = static_cast<double>(sign_flips) / total_possible_flips;
3579 if (flip_ratio > flip_threshold_) {
3580 if (report_level >= 1) {
3581 log_man << "Hyperparameter instability detected! Flip ratio: "
3582 << flip_ratio << " > " << flip_threshold_ << "\n";
3583 }
3584
3585 int old_history = fps_options.history;
3586 // A history already at or beyond the cap (the full-set setting is
3587 // INT_MAX) stays: old_history + increment would overflow.
3588 if (old_history < max_history_) {
3589 fps_options.history =
3590 std::min(old_history + history_increment_, max_history_);
3591 }
3592
3593 if (report_level >= 1) {
3594 log_man << "Increasing FPS history size from " << old_history
3595 << " to " << fps_options.history << "\n";
3596 }
3597
3598 // Clear history after adjustment to start fresh monitoring on the next
3599 // attempt.
3601 return true; // Signal to retry
3602 }
3603
3604 // No instability detected, no retry needed.
3605 return false;
3606}
3607
3609 const noexcept
3610{
3611 if (optimizer_state_ == nullptr) return 0;
3612 std::size_t warm = optimizer_state_->scg_alternative.warmStarts();
3613 std::visit(
3614 [&](const auto& optimizer) {
3615 using Optimizer = std::decay_t<decltype(optimizer)>;
3616 if constexpr (std::is_same_v<Optimizer, funcmin::RgminOpt>)
3617 warm += optimizer.warmStarts();
3618 },
3619 optimizer_state_->optimizer);
3620 return warm;
3621}
3622
3624{
3625 if (optimizer_state_ == nullptr) return 0;
3626 std::size_t pairs = optimizer_state_->scg_alternative.warmPairs();
3627 std::visit(
3628 [&](const auto& optimizer) {
3629 using Optimizer = std::decay_t<decltype(optimizer)>;
3630 if constexpr (std::is_same_v<Optimizer, funcmin::RgminOpt>)
3631 pairs += optimizer.warmPairs();
3632 },
3633 optimizer_state_->optimizer);
3634 return pairs;
3635}
3636
3638{
3639 scg_stalled_ = false;
3640 scg_stall_scope_ = {};
3641 if (optimizer_state_ == nullptr) return;
3642 optimizer_state_->scg_alternative.forgetSession();
3643 std::visit(
3644 [&](auto& optimizer) {
3645 using Optimizer = std::decay_t<decltype(optimizer)>;
3646 if constexpr (std::is_same_v<Optimizer, funcmin::RgminOpt>)
3647 optimizer.forgetSession();
3648 },
3649 optimizer_state_->optimizer);
3650}
3651
3652double GaussianProcessRegression::objectiveStationaritySkipThreshold(
3653 const Eigen::VectorXd& theta_reference) const noexcept
3654{
3655 double threshold = 0.0;
3656 if (laplace_skip_scg_threshold_ > 0.0 &&
3657 std::isfinite(laplace_skip_scg_threshold_)) {
3658 threshold = laplace_skip_scg_threshold_;
3659 }
3660 if (objective_stationarity_skip_auto_ && theta_reference.size() > 0 &&
3661 theta_reference.allFinite()) {
3662 const double auto_threshold = scg_opt_settings.common.tolerance_sol *
3663 (1.0 + theta_reference.norm());
3664 if (auto_threshold > 0.0 && std::isfinite(auto_threshold)) {
3665 threshold = threshold > 0.0 ? std::min(threshold, auto_threshold)
3666 : auto_threshold;
3667 }
3668 }
3669 return threshold;
3670}
3671
3674 const Eigen::VectorXd& w, const EigenMatrix& x,
3675 const Eigen::VectorXd& x_ind, const Eigen::VectorXd& y,
3677{
3678 const bool loo =
3679 hyperparameter_objective_mode_ == HyperparameterObjectiveMode::LOO;
3680 const bool local_loo = hyperparameter_objective_mode_ ==
3682 if (loo || local_loo) {
3685 use_training_geometry_handle_ &&
3687 if (loo) {
3689 w, geometry, x, x_ind, y, energy_and_gradient);
3690 } else {
3692 w, geometry, x, x_ind, y, energy_and_gradient);
3693 }
3694 return;
3695 }
3696 }
3698}
3699
3701 const EigenMatrix& opt_R_matrix, const Eigen::VectorXd& opt_R_indices,
3702 const Eigen::VectorXd& opt_y, const Eigen::VectorXd& theta_reference,
3703 Eigen::VectorXd* shift_out, double* energy_out,
3704 Eigen::VectorXd* gradient_out)
3705{
3706 if (sexpat_cov_func == nullptr || lik_gaussian == nullptr) {
3707 return std::numeric_limits<double>::infinity();
3708 }
3709 if (theta_reference.size() == 0) {
3710 return std::numeric_limits<double>::infinity();
3711 }
3712
3713 // The predicate consumes the Euclidean predicted-shift norm
3714 // ||H^{-1} g_new||_2.
3715 // Laplace stores L with H^{-1} = L L^T. Slice/PSIS and MAP/SCG store U
3716 // with H = U^T U.
3717 const Eigen::MatrixXd* L_posterior = nullptr;
3718 const Eigen::MatrixXd* U_hessian = nullptr;
3719 const Eigen::MatrixXd* H_inverse = nullptr;
3720 if (laplace_posterior_ && laplace_posterior_->valid) {
3721 const Eigen::MatrixXd& L_p = laplace_posterior_->laplace.lScale();
3722 if (L_p.size() > 0) {
3723 L_posterior = &L_p;
3724 }
3725 }
3726 if (L_posterior == nullptr && slice_laplace_state_ &&
3727 slice_laplace_state_->valid &&
3728 slice_laplace_state_->hessian_chol_U.size() > 0) {
3729 U_hessian = &slice_laplace_state_->hessian_chol_U;
3730 }
3731 if (L_posterior == nullptr && U_hessian == nullptr &&
3732 objective_stationarity_hessian_valid_ &&
3733 objective_stationarity_hessian_chol_U_.rows() ==
3734 theta_reference.size()) {
3735 U_hessian = &objective_stationarity_hessian_chol_U_;
3736 }
3737 if (L_posterior == nullptr && U_hessian == nullptr &&
3738 objective_stationarity_inverse_hessian_valid_ &&
3739 objective_stationarity_inverse_hessian_.rows() ==
3740 theta_reference.size()) {
3741 H_inverse = &objective_stationarity_inverse_hessian_;
3742 }
3743 const bool use_bb_scalar =
3744 L_posterior == nullptr && U_hessian == nullptr &&
3745 H_inverse == nullptr && objective_stationarity_bb_valid_ &&
3746 objective_stationarity_bb_dimension_ == theta_reference.size() &&
3747 objective_stationarity_bb_inverse_scale_ > 0.0 &&
3748 std::isfinite(objective_stationarity_bb_inverse_scale_);
3749 last_stationarity_model_ = L_posterior != nullptr ? 1
3750 : U_hessian != nullptr ? 2
3751 : H_inverse != nullptr ? 3
3752 : use_bb_scalar ? 4
3753 : 0;
3754 if (L_posterior == nullptr && U_hessian == nullptr &&
3755 H_inverse == nullptr && !use_bb_scalar) {
3756 return std::numeric_limits<double>::infinity();
3757 }
3758
3759 double energy_buf = 0.0;
3760 Eigen::VectorXd grad_buf = Eigen::VectorXd::Zero(theta_reference.size());
3761 EnergyAndGradient eg(energy_buf, grad_buf);
3762 // The marginal likelihood at the reference goes through the fit's
3763 // cached training geometry, the same route as the optimizer's own
3764 // evaluations; the live block walk it replaced cost 11_grignard a
3765 // sixth of its band wall at one evaluation per outer.
3766 bool device_objective = false;
3767#ifdef GPR_LINALG_KOKKOS
3768 device_objective = canUseDevicePosterior();
3769#endif
3770 const TrainingKernelGeometry* reference_geometry =
3771 hyperparameter_objective_mode_ == HyperparameterObjectiveMode::NLML &&
3773 use_training_geometry_handle_ && !device_objective
3774 ? fitGeometryFor(opt_R_matrix, opt_R_indices)
3775 : nullptr;
3776 if (reference_geometry != nullptr) {
3778 *reference_geometry, opt_R_matrix,
3779 opt_R_indices, opt_y, eg);
3780 } else {
3782 theta_reference, opt_R_matrix, opt_R_indices, opt_y, eg);
3783 }
3784 const Eigen::Index hdim =
3785 L_posterior != nullptr
3786 ? L_posterior->rows()
3787 : (U_hessian != nullptr
3788 ? U_hessian->rows()
3789 : (H_inverse != nullptr
3790 ? H_inverse->rows()
3791 : objective_stationarity_bb_dimension_));
3792 if (!std::isfinite(energy_buf) || grad_buf.size() != hdim ||
3793 !grad_buf.allFinite()) {
3794 return std::numeric_limits<double>::infinity();
3795 }
3796
3797 if (energy_out != nullptr) *energy_out = energy_buf;
3798 if (gradient_out != nullptr) *gradient_out = grad_buf;
3799 Eigen::VectorXd v;
3800 if (L_posterior != nullptr) {
3801 v = (*L_posterior) * (L_posterior->transpose() * grad_buf);
3802 } else if (U_hessian != nullptr) {
3803 const Eigen::VectorXd rhs = U_hessian->transpose()
3804 .template triangularView<Eigen::Lower>()
3805 .solve(grad_buf);
3806 v = U_hessian->template triangularView<Eigen::Upper>().solve(rhs);
3807 } else if (H_inverse != nullptr) {
3808 v = (*H_inverse) * grad_buf;
3809 } else {
3810 if (shift_out != nullptr) {
3811 *shift_out = objective_stationarity_bb_inverse_scale_ * grad_buf;
3812 }
3813 return objective_stationarity_bb_inverse_scale_ * grad_buf.norm();
3814 }
3815 if (shift_out != nullptr) *shift_out = v;
3816 return v.norm();
3817}
3818
3820 const EigenMatrix& opt_R_matrix, const Eigen::VectorXd& opt_R_indices,
3821 const Eigen::VectorXd& opt_y)
3822{
3823 const Eigen::VectorXd theta_reference =
3824 sexpat_cov_func ? sexpat_cov_func->combineParameters()
3825 : Eigen::VectorXd{};
3826 return computeObjectiveStationarityShiftNorm(opt_R_matrix, opt_R_indices,
3827 opt_y, theta_reference);
3828}
3829
3831 const Observation& full_observation, double* shift_norm_out)
3832{
3833 if (shift_norm_out != nullptr)
3834 *shift_norm_out = std::numeric_limits<double>::infinity();
3835 if (atomic_environment_model_) return false;
3836 // A retained active correction does not block the test: the full
3837 // fit the test stands in for rebuilds every row at the held or
3838 // stepped parameters and replaces the correction either way. Only a
3839 // pending correction or residual-model fit is a different objective.
3841 return false;
3842 last_stationarity_model_ = -1;
3844 return false;
3845 }
3846 if (std::find(scg_opt_settings.active_parameters.begin(),
3847 scg_opt_settings.active_parameters.end(),
3848 false) != scg_opt_settings.active_parameters.end()) {
3849 // The full inverse Hessian does not solve the restricted quadratic:
3850 // its cross terms can move frozen length scales. The selected
3851 // optimizer owns stationarity and warm steps in the active subspace.
3852 last_refit_kind_ = 2;
3853 last_stationarity_shift_ = std::numeric_limits<double>::infinity();
3854 return false;
3855 }
3856
3857 // The stationarity question is asked of the objective the optimizer
3858 // minimizes: the FPS subset when the training set exceeds the fit
3859 // history, else the full set. Probing the full-data objective costs
3860 // an O(N^3) evaluation per probe (45 s each on a 22-atom band at 75
3861 // configurations) while the fit itself runs on the subset.
3862 const Observation& fit_observation_ref =
3864 ? full_observation
3865 : selectOptimizationSubset(full_observation);
3866 const Observation fit_observation = fit_observation_ref;
3867 // The fitted theta is already the minimizer of this subset's objective:
3868 // no probe is needed, and the rows condition at the held theta.
3869 if (subsetFitUnchanged(fit_observation)) {
3870 ++unchanged_subset_fit_skips_;
3871 last_refit_kind_ = 0;
3872 last_stationarity_shift_ = 0.0;
3873 if (report_level >= 1) {
3874 log_man << "The fit subset is unchanged since the last converged "
3875 "fit; refreshing the posterior at fixed theta.\n";
3876 }
3877 updateModelWithFullData(full_observation);
3879 }
3881 EigenMatrix opt_R_matrix;
3882 Eigen::VectorXd opt_R_indices;
3883 Eigen::VectorXd opt_y;
3884 aux_func.assembleMatrixOfRepetitiveCoordinates(fit_observation.R,
3885 opt_R_matrix, opt_R_indices);
3886 aux_func.assembleVectorFromEnergyAndGradient(fit_observation, opt_y);
3887 subtractPriorMeanFromTargets(fit_observation.R, fit_observation.E.size(),
3888 opt_y);
3889
3890 const Eigen::VectorXd raw_theta = sexpat_cov_func->combineParameters();
3891 Eigen::VectorXd theta_reference = raw_theta;
3892 OptimizationObjectiveFrame objective_frame =
3893 enterOptimizationObjectiveFrame(opt_y, fit_observation.E.size(),
3894 &theta_reference);
3895 const double skip_threshold =
3896 objectiveStationaritySkipThreshold(theta_reference);
3897 if (!(skip_threshold > 0.0) || !std::isfinite(skip_threshold)) {
3898 leaveOptimizationObjectiveFrame(objective_frame, &theta_reference);
3899 setParameters(raw_theta);
3900 return false;
3901 }
3902 Eigen::VectorXd shift;
3903 double energy_reference = std::numeric_limits<double>::quiet_NaN();
3904 Eigen::VectorXd gradient_reference;
3905 double shift_norm = computeObjectiveStationarityShiftNorm(
3906 opt_R_matrix, opt_R_indices, opt_y, theta_reference, &shift,
3907 &energy_reference, &gradient_reference);
3908 // Under nlml_hessian_vector the scale along the gradient is the exact
3909 // Barzilai-Borwein step |g|^2 / g^T H g, with H g the NLML product at a
3910 // factor rebuilt at the reference point. Without the product, or when it
3911 // fails, the secant below supplies the scale as under finite_difference.
3912 if (!std::isfinite(shift_norm) && nlmlHessianVectorCurvatureRequested() &&
3915 "the stationarity check",
3916 "the objective has no exact NLML Hessian-vector product");
3917 } else if (!std::isfinite(shift_norm) &&
3919 double energy_here = std::numeric_limits<double>::quiet_NaN();
3920 Eigen::VectorXd gradient_here =
3921 Eigen::VectorXd::Zero(theta_reference.size());
3922 EnergyAndGradient eg_here(energy_here, gradient_here);
3923 evaluateEnergyAndGradient(theta_reference, opt_R_matrix, opt_R_indices,
3924 opt_y, eg_here);
3925 Eigen::VectorXd hessian_vector;
3926 if (std::isfinite(energy_here) && gradient_here.allFinite() &&
3927 gradient_here.norm() > 0.0 &&
3928 evaluateNlmlHessianVector(opt_R_indices, opt_R_matrix, opt_y,
3929 gradient_here, hessian_vector) &&
3930 hessian_vector.size() == gradient_here.size() &&
3931 hessian_vector.allFinite()) {
3932 energy_reference = energy_here;
3933 gradient_reference = gradient_here;
3934 const double denom = gradient_here.dot(hessian_vector);
3935 if (denom > 0.0 && std::isfinite(denom)) {
3936 const double alpha = gradient_here.squaredNorm() / denom;
3937 if (alpha > 0.0 && std::isfinite(alpha)) {
3938 shift = alpha * gradient_here;
3939 shift_norm = shift.norm();
3940 last_stationarity_model_ = 6;
3941 }
3942 }
3943 }
3944 if (!std::isfinite(shift_norm)) {
3946 "the stationarity check",
3947 "the exact NLML Hessian-vector product failed or had no "
3948 "positive curvature along the gradient");
3949 }
3950 }
3951 // No cached curvature model of the objective being fitted. Under the
3952 // leave-one-out objectives the refit runs: a one-probe secant along the
3953 // gradient measures curvature along that direction only and, from a
3954 // collapsed seed where the LOO gradient is flat, reported a
3955 // microscopic shift and held the seed for a whole run (Baker 01_hcn
3956 // under LOO, oracle count tripled). Under the marginal likelihood the
3957 // secant is the Barzilai-Borwein scale of the objective whose optimum
3958 // the previous fit certified, and it is what kept every refit at a
3959 // fraction of a second on the boards: without it every refit ran the
3960 // exact-Hessian probes (24-34 s each on 17_claisen and 16_h2po4_anion,
3961 // with the dense kernel rebuild that took both cells to the OOM killer).
3962 if (!std::isfinite(shift_norm) &&
3963 hyperparameter_objective_mode_ == HyperparameterObjectiveMode::NLML) {
3964 // The probes evaluate the same NLML the fit minimizes; through the
3965 // training geometry they apply theta to the cached per-block
3966 // geometry instead of rebuilding every pair derivative live (a
3967 // 22-atom band spent a seventh of its wall in these two probes).
3968 TrainingKernelGeometry probe_geometry;
3969 const bool probe_geometry_ready =
3971 use_training_geometry_handle_ &&
3972 prepareTrainingKernelGeometry(opt_R_matrix, opt_R_indices,
3973 probe_geometry, /*reused=*/true);
3974 const auto probe = [&](const Eigen::VectorXd& theta,
3975 EnergyAndGradient& eg) {
3976 if (probe_geometry_ready)
3977 evaluateEnergyAndGradientFromGeometry(theta, probe_geometry,
3978 opt_R_matrix,
3979 opt_R_indices, opt_y, eg);
3980 else
3981 evaluateEnergyAndGradient(theta, opt_R_matrix, opt_R_indices,
3982 opt_y, eg);
3983 };
3984 if (gradient_reference.size() == 0) {
3985 double energy_here = std::numeric_limits<double>::quiet_NaN();
3986 gradient_reference = Eigen::VectorXd::Zero(theta_reference.size());
3987 EnergyAndGradient eg_here(energy_here, gradient_reference);
3988 probe(theta_reference, eg_here);
3989 energy_reference = energy_here;
3990 }
3991 const double g_norm = gradient_reference.allFinite()
3992 ? gradient_reference.norm()
3993 : std::numeric_limits<double>::quiet_NaN();
3994 if (std::isfinite(g_norm) && g_norm > 0.0 &&
3995 std::isfinite(energy_reference)) {
3996 const double tau =
3997 std::sqrt(std::numeric_limits<double>::epsilon()) *
3998 (1.0 + theta_reference.norm());
3999 const Eigen::VectorXd s_probe =
4000 -(tau / g_norm) * gradient_reference;
4001 const Eigen::VectorXd theta_probe = theta_reference + s_probe;
4002 double energy_probe = std::numeric_limits<double>::quiet_NaN();
4003 Eigen::VectorXd gradient_probe =
4004 Eigen::VectorXd::Zero(theta_reference.size());
4005 EnergyAndGradient eg_probe(energy_probe, gradient_probe);
4006 probe(theta_probe, eg_probe);
4007 if (gradient_probe.allFinite()) {
4008 const Eigen::VectorXd y_probe =
4009 gradient_probe - gradient_reference;
4010 const double denom = s_probe.dot(y_probe);
4011 if (denom > 0.0 && std::isfinite(denom)) {
4012 const double alpha = s_probe.squaredNorm() / denom;
4013 if (alpha > 0.0 && std::isfinite(alpha)) {
4014 shift = alpha * gradient_reference;
4015 shift_norm = shift.norm();
4016 last_stationarity_model_ = 5;
4017 }
4018 }
4019 }
4020 }
4021 }
4022 // Still no curvature model (leave-one-out objectives, or a secant that
4023 // did not validate): the refit runs.
4024 if (!std::isfinite(shift_norm)) {
4025 if (shift_norm_out != nullptr) *shift_norm_out = shift_norm;
4026 last_stationarity_shift_ = shift_norm;
4027 last_stationarity_threshold_ = skip_threshold;
4028 leaveOptimizationObjectiveFrame(objective_frame, &theta_reference);
4029 setParameters(raw_theta);
4030 if (report_level >= 1) {
4031 log_man << "Objective refit: no cached curvature model for the "
4032 "fitted objective.\n";
4033 }
4034 last_refit_kind_ = 2;
4035 return false;
4036 }
4037 if (shift_norm_out != nullptr) *shift_norm_out = shift_norm;
4038 last_stationarity_shift_ = shift_norm;
4039 last_stationarity_threshold_ = skip_threshold;
4040 // A Newton step within sqrt(eps) of the skip threshold is the
4041 // curvature probe's own rounding. Hold theta instead of launching
4042 // a refit that would move the length scales by a last bit.
4043 if (!std::isfinite(shift_norm) ||
4044 gpr::numerics::exceedsThreshold(shift_norm, skip_threshold)) {
4045 // The optimum moved. The predicted shift is the Newton step of
4046 // the cached objective model at the new data: take it on descent
4047 // as the optimizer's warm start. One accepted step is not a fit:
4048 // held as the refit it leaves the lengthscales where the previous
4049 // data put them and the band relaxes on a stale model (Baker
4050 // 12_ethane: magnitude decayed from 0.67 to 0.27 over 120 outers
4051 // and the cell timed out). The optimizer's own tolerance decides
4052 // when the objective is stationary.
4053 bool newton_accepted = false;
4054 if (std::isfinite(shift_norm) && std::isfinite(energy_reference) &&
4055 shift.size() == theta_reference.size() && shift.allFinite()) {
4056 const Eigen::VectorXd theta_trial = theta_reference - shift;
4057 double energy_trial = std::numeric_limits<double>::quiet_NaN();
4058 Eigen::VectorXd grad_trial =
4059 Eigen::VectorXd::Zero(theta_trial.size());
4060 EnergyAndGradient eg_trial(energy_trial, grad_trial);
4061 // The trial is judged on the objective the reference was
4062 // measured on; the parameters it maps to must be finite and
4063 // positive (a secant step scaled by a wild curvature estimate
4064 // can send log-parameters past the exponent range, which
4065 // setParameters rejects: 01_hcn aborted there).
4066 bool trial_ok = theta_trial.allFinite();
4067 if (trial_ok) {
4069 theta_trial, opt_R_matrix, opt_R_indices, opt_y, eg_trial);
4070 }
4071 if (trial_ok && std::isfinite(energy_trial) &&
4072 grad_trial.allFinite() && energy_trial < energy_reference) {
4073 Eigen::VectorXd theta_accepted = theta_trial;
4074 leaveOptimizationObjectiveFrame(objective_frame,
4075 &theta_accepted);
4076 bool applied = theta_accepted.allFinite();
4077 if (applied) {
4078 try {
4079 setParameters(theta_accepted);
4080 } catch (const std::invalid_argument&) {
4081 applied = false;
4082 }
4083 }
4084 if (!applied) {
4085 // Re-enter the frame so the refit branch below can
4086 // leave it and restore the raw parameters.
4087 objective_frame = enterOptimizationObjectiveFrame(
4088 opt_y, fit_observation.E.size(), &theta_reference);
4089 }
4090 newton_accepted = applied;
4091 if (report_level >= 1) {
4092 log_man
4093 << "Objective warm start: ||H^-1 g_new||=" << shift_norm
4094 << " >= " << skip_threshold << ", objective "
4095 << energy_reference << " -> " << energy_trial << ".\n";
4096 }
4097 }
4098 }
4099 if (!newton_accepted) {
4100 leaveOptimizationObjectiveFrame(objective_frame, &theta_reference);
4101 setParameters(raw_theta);
4102 if (report_level >= 1) {
4103 log_man << "Objective refit: ||H^-1 g_new||=" << shift_norm
4104 << " >= " << skip_threshold << ".\n";
4105 }
4106 last_refit_kind_ = 2;
4107 return false;
4108 }
4109 // The caller runs the optimizer from the warm-started parameters.
4110 last_refit_kind_ = 1;
4111 return false;
4112 }
4113 leaveOptimizationObjectiveFrame(objective_frame, &theta_reference);
4114 setParameters(raw_theta);
4115 if (report_level >= 1) {
4116 log_man << "Objective fixed-theta refresh: ||H^-1 g_new||="
4117 << shift_norm << " < " << skip_threshold << ".\n";
4118 }
4119 last_refit_kind_ = 0;
4120 updateModelWithFullData(full_observation);
4122}
4123
4125 const Eigen::MatrixXd& U)
4126{
4127 laplace_posterior_.reset();
4128 slice_laplace_state_ = std::make_unique<SliceLaplaceState>();
4129 slice_laplace_state_->hessian_chol_U = U;
4130 slice_laplace_state_->valid = U.rows() > 0 && U.rows() == U.cols();
4131}
4132
4133bool GaussianProcessRegression::cacheObjectiveStationarityHessian(
4134 const Eigen::VectorXd& opt_R_indices, const EigenMatrix& opt_R_matrix,
4135 const Eigen::VectorXd& opt_y, const Eigen::VectorXd& theta_reference)
4136{
4137 invalidateObjectiveStationarityHessian();
4138 if (theta_reference.size() == 0) return false;
4139
4140 double energy_buf = 0.0;
4141 Eigen::VectorXd grad_buf = Eigen::VectorXd::Zero(theta_reference.size());
4142 EnergyAndGradient eg(energy_buf, grad_buf);
4144 theta_reference, opt_R_matrix, opt_R_indices, opt_y, eg);
4145 if (!std::isfinite(energy_buf) || !grad_buf.allFinite()) return false;
4146
4147 Eigen::MatrixXd H;
4148 if (!assembleExactHessian(opt_R_indices, opt_R_matrix, opt_y,
4149 static_cast<int>(theta_reference.size()), H)) {
4150 return false;
4151 }
4152 if (H.rows() != theta_reference.size() ||
4153 H.cols() != theta_reference.size() || !H.allFinite()) {
4154 return false;
4155 }
4156
4157 H = 0.5 * (H + H.transpose().eval());
4158 const double scale = std::max(1.0, H.cwiseAbs().maxCoeff());
4159 Eigen::LLT<Eigen::MatrixXd> llt(H);
4160 if (llt.info() != Eigen::Success) {
4161 const double eps = std::numeric_limits<double>::epsilon();
4162 bool factored = false;
4163 for (int attempt = 0; attempt < 12; ++attempt) {
4164 Eigen::MatrixXd H_jittered = H;
4165 const double jitter =
4166 scale * std::sqrt(eps) * std::pow(10.0, attempt);
4167 H_jittered.diagonal().array() += jitter;
4168 llt.compute(H_jittered);
4169 if (llt.info() == Eigen::Success) {
4170 factored = true;
4171 break;
4172 }
4173 }
4174 if (!factored) return false;
4175 }
4176
4177 objective_stationarity_hessian_chol_U_ = llt.matrixU();
4178 objective_stationarity_hessian_valid_ =
4179 objective_stationarity_hessian_chol_U_.rows() == theta_reference.size();
4180 return objective_stationarity_hessian_valid_;
4181}
4182
4183bool GaussianProcessRegression::cacheObjectiveStationarityInverseHessian(
4184 const Eigen::MatrixXd& H_inverse, const Eigen::VectorXd& theta_reference)
4185{
4186 invalidateObjectiveStationarityHessian();
4187 if (theta_reference.size() == 0) return false;
4188 if (H_inverse.rows() != theta_reference.size() ||
4189 H_inverse.cols() != theta_reference.size() || !H_inverse.allFinite()) {
4190 return false;
4191 }
4192
4193 Eigen::MatrixXd H_inverse_sym =
4194 0.5 * (H_inverse + H_inverse.transpose().eval());
4195 Eigen::LLT<Eigen::MatrixXd> llt(H_inverse_sym);
4196 if (llt.info() != Eigen::Success) return false;
4197
4198 objective_stationarity_inverse_hessian_ = std::move(H_inverse_sym);
4199 objective_stationarity_inverse_hessian_valid_ =
4200 objective_stationarity_inverse_hessian_.rows() ==
4201 theta_reference.size();
4202 return objective_stationarity_inverse_hessian_valid_;
4203}
4204
4206 const Observation& full_observation)
4207{
4209 detail::requireJointTrainingObservation(
4210 full_observation, "GaussianProcessRegression::updateModelWithFullData");
4211 if (atomic_environment_model_) {
4213 fitAtomicEnvironmentModel(full_observation, false);
4214 return;
4215 }
4216 // Automatic selection and its candidate model build run before this
4217 // rebuild mutates the posterior. A refusal throws and leaves the previous
4218 // model in place; a deferral (fewer than two geometries) keeps the exact
4219 // path. Fixed counts do not enter this branch.
4220 int selected_features = rff_features_requested_;
4221 std::optional<RFFModel> staged_auto_rff;
4222 if (rff_auto_) {
4223 const RFFFeatureSelection selection =
4224 selectRFFFeatures(full_observation);
4225 selected_features = selection.accepted ? selection.features : 0;
4226 if (selected_features > 0 && full_observation.E.size() > 0) {
4227 const Eigen::Index n_design =
4228 full_observation.R.rows() * (1 + full_observation.R.cols());
4229 if (n_design < 2 * static_cast<Eigen::Index>(selected_features)) {
4230 RFFFeatureSelection failed = rff_selection_;
4231 failed.accepted = false;
4232 failed.features = 0;
4233 failed.status = "rejected";
4234 failed.detail =
4235 "RFF feature selection refused: the validated count is not "
4236 "twice overdetermined on the full design. No feature count "
4237 "was installed.";
4238 rff_selection_ = failed;
4239 logRFFFeatureSelection(failed);
4240 throw RFFFeatureSelectionError(std::move(failed));
4241 }
4242 try {
4243 double energy_noise = 0.0;
4244 double gradient_noise = 0.0;
4245 const Observation residual = rffStandardizedResidual(
4246 full_observation, energy_noise, gradient_noise);
4247 std::shared_ptr<const linalg::MpiCommunicator> comm;
4248#if defined(GPR_HAVE_MPI) || defined(GPR_LINALG_SCALAPACK)
4249 const auto comm_ctx = mpiContext();
4250 if (comm_ctx.comm != linalg::kMpiCommNull) {
4251 comm = std::make_shared<linalg::MpiCommunicator>(
4252 comm_ctx.comm);
4253 }
4254#endif
4255 RFFModel candidate = comm ? RFFModel(comm) : RFFModel();
4256 candidate.build(*sexpat_cov_func, atoms_config, residual,
4257 selected_features, energy_noise,
4258 gradient_noise);
4259 PhaseTimers::notePeak("rff_build");
4260 staged_auto_rff = std::move(candidate);
4261 } catch (const RFFFeatureSelectionError&) {
4262 throw;
4263 } catch (const std::exception& ex) {
4264 RFFFeatureSelection failed = rff_selection_;
4265 failed.accepted = false;
4266 failed.features = 0;
4267 failed.status = "rejected";
4268 failed.detail = std::string(
4269 "RFF feature selection refused after "
4270 "validation: the chosen model did not "
4271 "build (") +
4272 ex.what() +
4273 "). No feature count was installed.";
4274 rff_selection_ = failed;
4275 logRFFFeatureSelection(failed);
4276 throw RFFFeatureSelectionError(std::move(failed));
4277 }
4278 }
4279 }
4280 active_posterior_.reset();
4281 full_fit_observations_ = full_observation;
4282#ifdef GPR_LINALG_SCALAPACK
4283 parked_training_cholesky_.clear();
4284#endif
4285 ++full_data_rebuilds_for_testing_;
4286 ++factor_epoch_;
4288
4289 if (this->report_level >= 2) {
4290 log_man << "Full-data rebuild: assemble observations n="
4291 << full_observation.R.rows()
4292 << " dim=" << full_observation.R.cols() << ".\n";
4293 }
4294
4295 // Assemble matrices with the full dataset.
4296 aux_func.assembleMatrixOfRepetitiveCoordinates(full_observation.R, R_matrix,
4297 R_indices);
4298 aux_func.assembleVectorFromEnergyAndGradient(full_observation,
4300 subtractPriorMeanFromTargets(full_observation.R, full_observation.E.size(),
4302 if (this->report_level >= 2) {
4303 log_man << "Full-data rebuild: assembled design rows="
4304 << R_matrix.rows() << " cols=" << R_matrix.cols()
4305 << " targets=" << energy_and_gradient.size() << ".\n";
4306 }
4307 standardizeTargets(energy_and_gradient, full_observation.E.size());
4308 if (this->report_level >= 2) {
4309 log_man << "Full-data rebuild: targets standardized scale=" << y_scale_
4310 << " mean=" << y_mean_ << ".\n";
4311 }
4312 ++laplace_model_revision_;
4313 // Do not reset laplace_posterior_ here. The stamp on the cached posterior
4314 // captures the old laplace_model_revision_; ensureLaplacePosterior()
4315 // detects the mismatch and rebuilds on next use. Keeping the old H around
4316 // is required for the Laplace-driven skip-SCG predicate, which uses the
4317 // old H to estimate the Newton-step magnitude under the new data.
4318
4319 // RFF scale cutoff. Above n_design >= 2*D_rff the exact dual-kernel
4320 // eigensolve (O(rank^3) per outer; the rank-6000 hermes_123
4321 // bottleneck) is replaced by the RFF Bayesian linear
4322 // regression (O(N D D_rff + D_rff^3), self-contained on the raw
4323 // targets via its own BLR precision). The RFF model then supplies
4324 // BOTH the predict mean and variance, so the eigensolve is skipped
4325 // entirely. Below the cutoff (small-rank systems) this branch is
4326 // never taken and the exact path below runs bit-identically -- the
4327 // artifact-free guarantee. The 2x-overdetermined guard keeps the BLR
4328 // posterior well-conditioned (matches the layered-RFF gate). RFF
4329 // build failure falls through to the exact decompose.
4330 rff_replaces_exact_ = false;
4331 if (rff_auto_ && selected_features == 0) {
4332 rff_features_ = 0;
4333 rff_standardized_targets_ = false;
4334 }
4335 if (selected_features > 0 && full_observation.E.size() > 0) {
4336 const Eigen::Index n_design =
4337 full_observation.R.rows() * (1 + full_observation.R.cols());
4338 if (n_design >= 2 * static_cast<Eigen::Index>(selected_features)) {
4339 try {
4340 if (rff_auto_) {
4341 rff_model_ = std::move(*staged_auto_rff);
4342 rff_features_ = selected_features;
4343 rff_standardized_targets_ = true;
4344 } else {
4345 buildRFFModel(full_observation, selected_features);
4346 }
4347 C.resize(0, 0);
4349 a.resize(0);
4350 b.resize(0);
4351 descriptor_predictor_ready_ = false;
4352 clearHssvdBasisState();
4353 rff_replaces_exact_ = true;
4355 if (this->report_level >= 2) {
4356 log_man << "Full-data rebuild: RFF replaces exact solve "
4357 "(n_design="
4358 << n_design
4359 << " >= 2*D_rff=" << 2 * selected_features
4360 << ", D_rff=" << selected_features
4361 << "); dual-kernel eigensolve skipped.\n";
4362 }
4363 return;
4364 } catch (const RFFFeatureSelectionError&) {
4365 throw;
4366 } catch (const std::exception& ex) {
4367 rff_replaces_exact_ = false;
4368 rff_features_ = 0;
4369 rff_standardized_targets_ = false;
4370 if (this->report_level >= 1) {
4371 log_man << "RFF replace build failed: " << ex.what()
4372 << "; falling back to exact decompose.\n";
4373 }
4374 }
4375 }
4376 }
4377
4378 // Re-decompose the covariance matrix with new hyperparameters and full data
4379 if (this->report_level >= 2) {
4380 log_man << "Full-data rebuild: covariance decompose start hssvd="
4381 << (use_hssvd_backend_ ? 1 : 0) << ".\n";
4382 }
4383 bool posterior_refreshed = false;
4384 const auto condition_on_rows = [&]() {
4385 posterior_refreshed = false;
4386 if (use_hssvd_backend_) {
4387 posterior_refreshed = refreshFullDataPosteriorHssvd();
4388 is_decomposed_succesfully = posterior_refreshed;
4389 }
4390 if (!posterior_refreshed) {
4393 }
4394 };
4395 condition_on_rows();
4396 // Robust rows: one EM sweep per rebuild. The E-step reads the
4397 // conditioned model's leave-one-geometry-out residuals; the M-step
4398 // is the same conditioning with the reweighted noise.
4399 if (is_decomposed_succesfully && robust_nu_ > 0.0 &&
4400 updateRobustRowWeights(full_observation)) {
4401 condition_on_rows();
4402 }
4403 if (this->report_level >= 2) {
4404 log_man << "Full-data rebuild: covariance decompose status="
4405 << (is_decomposed_succesfully ? 1 : 0)
4406 << " hssvd_valid=" << (hssvd_basis_valid_ ? 1 : 0)
4407 << " hssvd_rank=" << hssvd_basis_.rank() << ".\n";
4408 }
4409
4411 if (report_level >= 1) {
4412 log_man << "Warning! Matrix L is not positive definite after "
4413 "re-evaluation with full dataset.\n";
4414 }
4415 } else if (!posterior_refreshed) {
4416 if (this->report_level >= 2) {
4417 log_man << "Full-data rebuild: posterior refresh start.\n";
4418 }
4419 refreshPosteriorWeights(energy_and_gradient);
4420 if (this->report_level >= 2) {
4421 log_man << "Full-data rebuild: posterior refresh done.\n";
4422 }
4423 }
4424
4425 if (this->report_level >= 2) {
4426 log_man << "Final model updated with " << full_observation.R.rows()
4427 << " data points.\n";
4428 log_man << "magnSigma2: " << sexpat_cov_func->getMagnSigma2() << "\n";
4429 log_man << "lengthScales:\n"
4430 << Eigen::Map<Eigen::VectorXd>(
4431 sexpat_cov_func->getLengthScaleRef().data(),
4432 sexpat_cov_func->getLengthScaleRef().size())
4433 << "\n";
4434 }
4435 if (report_level >= 2 && backend().mpi().rank == 0) {
4436 const auto& ls = sexpat_cov_func->getLengthScaleRef();
4437 std::fprintf(stderr, "[GPR_TRACE_LS] N=%lld magnSigma2=%.6g ls=[",
4438 static_cast<long long>(full_observation.R.rows()),
4439 sexpat_cov_func->getMagnSigma2());
4440 for (Eigen::Index k = 0; k < ls.size(); ++k)
4441 std::fprintf(stderr, "%s%.6g", k ? " " : "", *(ls.data() + k));
4442 std::fprintf(stderr, "] sigma2n=%.6g\n",
4443 lik_gaussian ? lik_gaussian->getSigma2() : -1.0);
4444 }
4445}
4446
4448 const AtomsConfiguration& conf_info)
4449{
4450 const bool changed_pair_hierarchy =
4451 atoms_config.n_pt != conf_info.n_pt ||
4452 atoms_config.n_base_pt != conf_info.n_base_pt ||
4453 atoms_config.pair_type_parent != conf_info.pair_type_parent;
4454 const AtomsConfiguration& kernel_conf = sexpat_cov_func != nullptr
4455 ? sexpat_cov_func->getConfInfo()
4456 : atoms_config;
4457 const double far_radius =
4458 sexpat_cov_func != nullptr ? sexpat_cov_func->farFieldRadius() : 0.0;
4459 if (!detail::sameSexpatGeometry(kernel_conf, conf_info, far_radius,
4460 far_radius) ||
4461 (atomic_environment_model_ &&
4462 !sameAtomicEnvironmentGeometry(atoms_config, conf_info))) {
4463 // Pair features determine every posterior representation, including
4464 // parked factors whose dimensions can match a different environment.
4465 invalidateLikelihoodNoiseDependentState();
4466 pending_hyperparameter_posterior_ = {};
4467 serial_factor_signature_.valid = false;
4468 active_posterior_.reset();
4469 full_fit_observations_.clear();
4470 active_kernel_evidence_.clear();
4472 ++factor_epoch_;
4473 }
4474 this->atoms_config = conf_info;
4475 // Geometry updates retain learned releases. A changed chemical typing
4476 // requires the hierarchy that belongs to those pair indices.
4477 if (changed_pair_hierarchy) configureLengthScaleTies(conf_info);
4478 configureZBLPriorMean(conf_info);
4479 configureFFPriorMean(conf_info);
4480
4481 if (sexpat_cov_func != nullptr) {
4482 sexpat_cov_func->setConfInfo(conf_info);
4483 }
4484
4486 ++laplace_model_revision_;
4487 laplace_posterior_.reset();
4488 invalidateObjectiveStationarityHessian();
4489}
4490
4492 const Observation& observation)
4493{
4494 // For ARD (multiple lengthscales per pairtype), the factorized path
4495 // does not apply. Fall back to the SCG-based optimizer.
4496 if (sexpat_cov_func->getLengthScaleRef().cols() > 1) {
4497 optimize(observation);
4498 return;
4499 }
4500
4502 EigenMatrix opt_R_matrix;
4503 Eigen::VectorXd opt_R_indices;
4504 Eigen::VectorXd opt_energy_and_gradient;
4505
4506 // Assemble training coordinates and targets
4507 aux_func.assembleMatrixOfRepetitiveCoordinates(observation.R, opt_R_matrix,
4508 opt_R_indices);
4509 aux_func.assembleVectorFromEnergyAndGradient(observation,
4510 opt_energy_and_gradient);
4511 subtractPriorMeanFromTargets(observation.R, observation.E.size(),
4512 opt_energy_and_gradient);
4513 standardizeTargets(opt_energy_and_gradient, observation.E.size());
4514
4515 // Kt is the unit signal kernel. The grid variable is rho, and the
4516 // observation noise installed below is sf2 * rho.
4517 const ProfiledKernelScale scale = profileUnitKernelScale(
4518 *this, opt_R_matrix, opt_R_indices, opt_energy_and_gradient);
4519 if (!scale.ok) {
4520 failedOptimizer = true;
4521 return;
4522 }
4523 failedOptimizer = false;
4524
4525 sexpat_cov_func->setMagnSigma2(scale.signal);
4526 lik_gaussian->setSigma2(scale.noise);
4527 sigma2 = trainingToPhysicalNoiseVariance(scale.noise);
4528
4529 if (this->report_level >= 2) {
4530 log_man << "Factorized optimization: noise=" << scale.noise
4531 << " prefactor=" << scale.signal << " NLML=" << scale.nlml
4532 << "\n";
4533 }
4534
4535 // Rebuild the model with optimal parameters using the full dataset
4536 updateModelWithFullData(observation);
4537}
4538
4540 const Observation& observation, const Coord& band_positions,
4541 Eigen::VectorXd& influence, bool collective)
4542{
4543 return observationBandInfluence(observation, band_positions, influence,
4544 collective, {});
4545}
4546
4548 const Observation& observation, const Coord& band_positions,
4549 Eigen::VectorXd& influence, bool collective,
4550 const std::vector<char>& protected_rows, Eigen::VectorXd* removal_norm)
4551{
4552 // Exact block downdate (scripts/derive_adaptive_pruning_influence.py):
4553 // removing observation j shifts the posterior mean at query x* by
4554 // k(x*,X) P E_j (E_j^T P E_j)^{-1} E_j^T alpha, P = C^{-1},
4555 // whose first factor is the block leave-one-out residual and whose
4556 // second is the smoother's reliance on j at x*.
4557 //
4558 // The mean is not the whole story. Removing a row also widens the
4559 // posterior at x*, by the quadratic form
4560 // w_j^T (E_j^T P E_j)^{-1} w_j, w_j = (k(x*,X) P) E_j,
4561 // which is non-negative because the middle factor is a diagonal
4562 // block of a positive definite inverse: dropping data never
4563 // sharpens a belief. Acquisition reads that variance, so a row can
4564 // leave the predicted energy untouched and still move where the
4565 // search looks next. Scoring the mean alone lets such a row be
4566 // dropped as inert and then changes the acquisition sequence, which
4567 // is the opposite of inert.
4568 //
4569 // Reported per observation as the worst over the band's energy
4570 // channel and every Cartesian force channel of the mean shift and
4571 // the standard-deviation inflation, both in the model's own target
4572 // units so one noise-sigma gate covers both. A row that leaves the
4573 // energy profile untouched can still move a force the search reads.
4574 const Eigen::Index n_obs = observation.R.rows();
4575 const Eigen::Index dim = observation.R.cols();
4576 if (n_obs == 0 || dim == 0 || band_positions.rows() == 0 ||
4577 band_positions.cols() != dim || observation.E.size() != n_obs ||
4578 observation.G.rows() != n_obs || observation.G.cols() != dim ||
4579 (!protected_rows.empty() &&
4580 protected_rows.size() != static_cast<std::size_t>(n_obs))) {
4581 return false;
4582 }
4583 const Eigen::Index block = dim + 1;
4584 Eigen::VectorXi excluded = Eigen::VectorXi::Zero(n_obs);
4585 for (std::size_t row = 0; row < protected_rows.size(); ++row)
4586 excluded(static_cast<Eigen::Index>(row)) = protected_rows[row] != 0;
4587
4589 EigenMatrix x;
4590 Eigen::VectorXd x_ind;
4591 aux_func.assembleMatrixOfRepetitiveCoordinates(observation.R, x, x_ind);
4592 Eigen::VectorXd y;
4593 aux_func.assembleVectorFromEnergyAndGradient(observation, y);
4594 subtractPriorMeanFromTargets(observation.R, observation.E.size(), y);
4595 // No standardizeTargets: the classic profile runs normalization-free,
4596 // so raw targets already are the frame the likelihood noise lives in
4597 // and the caller compares influences against that noise directly.
4598
4599 const Eigen::Index order = y.size();
4600 // A count-dependent nugget prevents appending to a factor, but a factor
4601 // at this exact order already contains the required regularization.
4602 bool reuse_factor = !use_hssvd_backend_ && !active_posterior_ &&
4603 !use_correction_ && sexpat_cov_func != nullptr &&
4604 lik_gaussian != nullptr &&
4605 !sexpat_cov_func->usesManifoldChart() &&
4606 !sexpat_cov_func->usesGeodesicHeatKernel() &&
4608 if (reuse_factor) {
4609 const EigenMatrix ordered_rows = permuteTrainingRows(x);
4610#ifdef GPR_LINALG_KOKKOS
4611 if (hasDevicePosterior()) {
4612 const auto& lengths = sexpat_cov_func->getLengthScaleRef();
4613 reuse_factor = device_posterior_->matchesTraining(
4614 ordered_rows, permuteTrainingVector(x_ind),
4615 lik_gaussian->evaluateTrainingVariance(ordered_rows),
4616 Eigen::Map<const Eigen::VectorXd>(lengths.data(),
4617 lengths.size()),
4618 sexpat_cov_func->getMagnSigma2(),
4619 const_cov_fun->getConstSigma2(), kernelNuggetCoefficient(order),
4620 jitter_sigma2);
4621 } else {
4622#endif
4623#ifdef GPR_LINALG_SCALAPACK
4624 const auto& signature = distributed_factor_signature_;
4625 reuse_factor =
4626 collective && signature.jitter == 0.0 &&
4627 signature.configured_jitter == jitter_sigma2 &&
4628 detail::sameSexpatGeometry(signature.kernel_configuration,
4629 sexpat_cov_func->getConfInfo(),
4630 signature.far_field_radius,
4631 sexpat_cov_func->farFieldRadius());
4632#else
4633 const auto& signature = serial_factor_signature_;
4634 reuse_factor =
4635 signature.valid && signature.indices.size() == x_ind.size() &&
4636 signature.jitter_sigma2 == jitter_sigma2 &&
4637 !signature.manifold_chart && !signature.geodesic_heat &&
4638 signature.indices == permuteTrainingVector(x_ind) &&
4639 detail::sameSexpatGeometry(
4640 signature.kernel_geometry, sexpat_cov_func->getConfInfo(),
4641 signature.far_field_radius, sexpat_cov_func->farFieldRadius());
4642#endif
4643 reuse_factor =
4644 reuse_factor && signature.valid &&
4645 signature.nugget_coefficient ==
4646 kernelNuggetCoefficient(order) &&
4647 signature.theta == sexpat_cov_func->combineParameters() &&
4648 signature.rows.rows() == order &&
4649 signature.rows.cols() == ordered_rows.cols() &&
4650 signature.rows == ordered_rows;
4651 if (reuse_factor) {
4652 const Eigen::VectorXd noise = permuteTrainingVector(
4653 lik_gaussian->evaluateTrainingVariance(x));
4654 const Eigen::VectorXd constant =
4655 permuteTrainingVector(detail::constantCovarianceUpdate(
4656 const_cov_fun.get(), x_ind));
4657 reuse_factor =
4658 noise == signature.noise && constant == signature.constant;
4659 }
4660#ifdef GPR_LINALG_KOKKOS
4661 }
4662#endif
4663 }
4664#ifdef GPR_LINALG_SCALAPACK
4665 if (collective) {
4666 const auto context = backend().mpi();
4667 int reusable = reuse_factor ? 1 : 0;
4668 if (context.is_distributed())
4669 MPI_Allreduce(MPI_IN_PLACE, &reusable, 1, MPI_INT, MPI_MIN,
4670 context.comm);
4671 if (context.is_distributed())
4672 MPI_Allreduce(MPI_IN_PLACE, excluded.data(),
4673 static_cast<int>(n_obs), MPI_INT, MPI_MIN,
4674 context.comm);
4675 reuse_factor = reusable != 0;
4676 }
4677#else
4678 (void)collective;
4679#endif
4680 // The local factor is taken in observation-major order, so that the
4681 // rows of geometry j are the contiguous block [j b, (j + 1) b),
4682 // b = dim + 1. With C' = Q C Q^T = L' L'^T the precision block is
4683 // E_j^T C^-1 E_j = V_j^T V_j, L'[s:, s:] V_j = [I_b; 0], s = j b,
4684 // because L'^-1 e_c vanishes above row c. Each block then costs a
4685 // solve on the trailing (order - s) rows instead of all of them, and
4686 // the blocks together cost order^3 / 3 rather than order^3.
4687 // (scripts/derive_band_influence_trailing_blocks.py checks the identity.)
4688 EigenMatrix local_lower;
4689 Eigen::PermutationMatrix<Eigen::Dynamic, Eigen::Dynamic, int>
4690 observation_major;
4691 // A collective call shares the covariance blocks out across the ranks;
4692 // the disjoint exact sum returns the single-rank matrix to every rank.
4693 bool collective_assembly = false;
4694#ifdef GPR_LINALG_SCALAPACK
4695 collective_assembly = collective && backend().mpi().is_distributed();
4696#endif
4697 if (!reuse_factor) {
4698 if (order != n_obs * block) return false;
4699 EigenMatrix covariance;
4701 x, x_ind, covariance, /*serial_per_rank=*/!collective_assembly);
4702 if (covariance.rows() != order) return false;
4703 // Channel-major row j + b n_obs is observation-major row j b + b.
4704 observation_major.resize(order);
4705 for (Eigen::Index j = 0; j < n_obs; ++j)
4706 for (Eigen::Index b = 0; b < block; ++b)
4707 observation_major.indices()(j + b * n_obs) =
4708 static_cast<int>(j * block + b);
4709 // Q C Q^T, lower triangle only (the factorization and every solve
4710 // read no other entry). Each target column gathers contiguous
4711 // channel segments of one source column.
4712 local_lower = EigenMatrix::Zero(order, order);
4713 for (Eigen::Index j = 0; j < n_obs; ++j) {
4714 for (Eigen::Index b = 0; b < block; ++b) {
4715 const Eigen::Index target = j * block + b;
4716 const double* source = covariance.col(j + b * n_obs).data();
4717 double* column = local_lower.col(target).data();
4718 for (Eigen::Index channel = 0; channel < block; ++channel) {
4719 const double* segment = source + channel * n_obs;
4720 // Rows j' block + channel at or below the diagonal.
4721 const Eigen::Index first =
4722 target > channel
4723 ? (target - channel + block - 1) / block
4724 : 0;
4725 for (Eigen::Index row = first; row < n_obs; ++row)
4726 column[row * block + channel] = segment[row];
4727 }
4728 }
4729 }
4730 covariance.resize(0, 0);
4731 if (jitter_sigma2 > 0.0)
4732 local_lower.diagonal().array() += jitter_sigma2;
4733 const Eigen::LLT<Eigen::Ref<EigenMatrix>> factor(local_lower);
4734 if (factor.info() != Eigen::Success) return false;
4735 } else {
4736 ++band_influence_factor_reuses_for_testing_;
4737 }
4738 influence = Eigen::VectorXd::Constant(
4739 n_obs, std::numeric_limits<double>::infinity());
4740 if (removal_norm != nullptr) *removal_norm = influence;
4741 if (excluded.minCoeff() != 0) return true;
4742 const auto whiten = [&](EigenMatrix rhs) -> EigenMatrix {
4743 if (reuse_factor) {
4744 EigenMatrix rhs_perm = permuteTrainingRows(rhs);
4745 if (rigid_deflation_.isActiveForFullOrder(rhs_perm.rows()))
4746 rhs_perm = rigid_deflation_.projectRows(rhs_perm);
4747 return trainingSolver().whitenColumns(rhs_perm);
4748 }
4749 rhs = observation_major * rhs;
4750 local_lower.template triangularView<Eigen::Lower>().solveInPlace(rhs);
4751 return rhs;
4752 };
4753 const auto solve = [&](const EigenMatrix& rhs) -> EigenMatrix {
4754 if (reuse_factor && rigid_deflation_.isActiveForFullOrder(rhs.rows())) {
4755 EigenMatrix rhs_perm = permuteTrainingRows(rhs);
4756 EigenMatrix rhs_proj = rigid_deflation_.projectRows(rhs_perm);
4757 EigenMatrix solved_r = trainingSolver().solveColumns(rhs_proj);
4758 EigenMatrix result =
4759 rigid_deflation_.liftSolvedColumns(rhs_perm, solved_r);
4761 result =
4763 return result;
4764 }
4765 EigenMatrix result = whiten(rhs);
4766 if (reuse_factor) {
4767 result = trainingSolver().unwhitenColumns(result);
4769 result =
4771 } else {
4772 local_lower.transpose()
4773 .template triangularView<Eigen::Upper>()
4774 .solveInPlace(result);
4775 result = observation_major.transpose() * result;
4776 }
4777 return result;
4778 };
4779 const Eigen::VectorXd alpha = solve(y);
4780
4781 // Band queries on the energy channel and every Cartesian force
4782 // channel. Channel 0 is the energy; channel c = 1..dim is the
4783 // derivative along Cartesian coordinate c - 1, the same trailing
4784 // column assembleMatrixOfRepetitiveCoordinates writes.
4785 const Eigen::Index n_band = band_positions.rows();
4786 const Eigen::Index n_queries = n_band * block;
4787 EigenMatrix xq(n_queries, dim + 1);
4788 Eigen::VectorXd xq_ind(n_queries);
4789 for (Eigen::Index channel = 0; channel < block; ++channel) {
4790 const Eigen::Index row0 = channel * n_band;
4791 xq.middleRows(row0, n_band).leftCols(dim) = band_positions;
4792 xq.middleRows(row0, n_band)
4793 .col(dim)
4794 .setConstant(static_cast<double>(channel));
4795 xq_ind.segment(row0, n_band).setConstant(static_cast<double>(channel));
4796 }
4797 EigenMatrix K_qt;
4798 evaluateCovarianceMatrix(xq, x, xq_ind, x_ind, K_qt,
4799 /*serial_per_rank=*/true);
4800 if (K_qt.rows() != n_queries || K_qt.cols() != order) return false;
4801
4802 const EigenMatrix W = solve(K_qt.transpose()).transpose();
4803 // Only one geometry's precision block is needed at a time:
4804 // E_j^T C^-1 E_j = (L^-1 E_j)^T (L^-1 E_j). Streaming these
4805 // right-hand sides bounds scratch storage by order * (dim + 1).
4806 EigenMatrix columns;
4807 if (reuse_factor) columns = EigenMatrix::Zero(order, block);
4808
4809 // The local factor is replicated, so the geometries can be shared out:
4810 // each one's precision block, and everything derived from it, is
4811 // computed whole by a single rank, and a minimum against +inf on the
4812 // others hands the values back unchanged. The distributed factor's
4813 // solves are collective and stay on every rank.
4814 int owner_rank = 0, owners = 1;
4815#ifdef GPR_LINALG_SCALAPACK
4816 const bool share_geometries = !reuse_factor && collective_assembly;
4817 if (share_geometries) {
4818 owner_rank = backend().mpi().rank;
4819 owners = backend().mpi().nprocs;
4820 }
4821#endif
4822
4823 Eigen::VectorXi idx(block);
4824 EigenMatrix gram(block, block);
4825 Eigen::VectorXd alpha_block(block);
4826 for (Eigen::Index j = 0; j < n_obs; ++j) {
4827 if (excluded(j)) continue;
4828 if (j % owners != owner_rank) continue;
4829 for (Eigen::Index b = 0; b < block; ++b)
4830 idx(b) = static_cast<int>(j + b * n_obs);
4831 for (Eigen::Index r = 0; r < block; ++r)
4832 alpha_block(r) = alpha(idx(r));
4833 EigenMatrix block_whitened;
4834 if (reuse_factor) {
4835 columns.setZero();
4836 for (Eigen::Index r = 0; r < block; ++r)
4837 columns(idx(r), r) = 1.0;
4838 block_whitened = whiten(columns);
4839 } else {
4840 const Eigen::Index first = j * block;
4841 const Eigen::Index trailing = order - first;
4842 block_whitened = EigenMatrix::Zero(trailing, block);
4843 block_whitened.topRows(block).setIdentity();
4844 local_lower.bottomRightCorner(trailing, trailing)
4845 .template triangularView<Eigen::Lower>()
4846 .solveInPlace(block_whitened);
4847 }
4848 gram.noalias() = block_whitened.transpose() * block_whitened;
4849 if (reuse_factor && rigid_deflation_.isActiveForFullOrder(order)) {
4850 const EigenMatrix cols_perm = permuteTrainingRows(columns);
4851 for (Eigen::Index i = 0; i < rigid_deflation_.num_geometries; ++i) {
4852 const auto& blk =
4853 rigid_deflation_.blocks[static_cast<std::size_t>(i)];
4854 if (blk.rigid_modes <= 0) continue;
4855 const auto g_block = cols_perm.middleRows(
4856 blk.full_row_offset + 1, blk.full_grad_dim);
4857 if (g_block.isZero(0.0)) continue;
4858 const EigenMatrix r_proj = blk.R.transpose() * g_block;
4859 gram.noalias() += (1.0 / blk.grad_noise_variance) *
4860 (r_proj.transpose() * r_proj);
4861 }
4862 }
4863 const Eigen::LDLT<EigenMatrix> gram_solver(gram);
4864 if (gram_solver.info() != Eigen::Success) {
4865 // Undecidable: never prune on a failed downdate.
4866 influence(j) = std::numeric_limits<double>::infinity();
4867 continue;
4868 }
4869 const Eigen::VectorXd u = gram_solver.solve(alpha_block);
4870 if (removal_norm != nullptr) {
4871 // mu - mu_{-J} = k(., X) P E_J u has squared kernel norm
4872 // u^T (E_J^T P E_J) u = alpha_J^T u.
4873 const double squared = alpha_block.dot(u);
4874 if (std::isfinite(squared))
4875 (*removal_norm)(j) = std::sqrt(std::max(squared, 0.0));
4876 }
4877 double worst = 0.0;
4878 Eigen::VectorXd w_j(block);
4879 for (Eigen::Index i = 0; i < n_queries; ++i) {
4880 double shift = 0.0;
4881 for (Eigen::Index r = 0; r < block; ++r) {
4882 w_j(r) = W(i, idx(r));
4883 shift += w_j(r) * u(r);
4884 }
4885 worst = std::max(worst, std::abs(shift));
4886 // Variance inflation at this band point, as a standard
4887 // deviation so it shares the noise-sigma yardstick with the
4888 // mean shift. The form is non-negative by construction; a
4889 // negative value is a broken factorization, not a sharper
4890 // posterior, so it is treated as undecidable.
4891 const double var_gain = w_j.dot(gram_solver.solve(w_j));
4892 if (!std::isfinite(var_gain)) {
4893 worst = std::numeric_limits<double>::infinity();
4894 break;
4895 }
4896 if (var_gain > 0.0) {
4897 worst = std::max(worst, std::sqrt(var_gain));
4898 }
4899 }
4900 influence(j) = std::isfinite(worst)
4901 ? worst
4902 : std::numeric_limits<double>::infinity();
4903 }
4904#ifdef GPR_LINALG_SCALAPACK
4905 if (share_geometries) {
4906 const auto context = backend().mpi();
4907 MPI_Allreduce(MPI_IN_PLACE, influence.data(), static_cast<int>(n_obs),
4908 MPI_DOUBLE, MPI_MIN, context.comm);
4909 if (removal_norm != nullptr)
4910 MPI_Allreduce(MPI_IN_PLACE, removal_norm->data(),
4911 static_cast<int>(n_obs), MPI_DOUBLE, MPI_MIN,
4912 context.comm);
4913 }
4914#endif
4915 return true;
4916}
4917
4919 const Observation& observation)
4920{
4921 const Eigen::VectorXd fallback_parameters =
4922 sexpat_cov_func->combineParameters();
4923 const auto stopForWallClock = [&]() {
4924 if (!wallClockLimitReached()) return false;
4925 failedOptimizer = true;
4926 last_fit_stop_reason_ = "wall-clock limit";
4927 setParameters(fallback_parameters);
4928 return true;
4929 };
4930 if (stopForWallClock()) return;
4931 // Chemistry-constrained ARD: per-pairtype lengthscale RATIOS come
4932 // from the descriptor spreads (the same quantity the SCG seed and
4933 // the MAP ls-prior anchor use), leaving a global scale s as the
4934 // only lengthscale degree of freedom. For each s on a warm-centered
4935 // log grid the (prefactor, noise) subproblem is solved exactly by
4936 // the factorized likelihood on one eigendecomposition, so a full
4937 // refit costs a handful of factorizations instead of an SCG
4938 // trajectory's tens of them, and the pairtype ratios cannot churn
4939 // between refits (the sloppy-valley magnitude/lengthscale swings
4940 // die structurally).
4941 // Fallbacks route to the SCG core directly (never back through
4942 // optimize(), which dispatches here when the mode is enabled).
4943 Eigen::VectorXd ratio;
4944 if (!computePairtypeDescriptorScale(observation.R, atoms_config, ratio) ||
4945 ratio.size() == 0 || !(ratio.minCoeff() > 0.0)) {
4947 return;
4948 }
4949 FieldMatrixd& ls = sexpat_cov_func->getLengthScaleRef();
4950 if (ls.size() == 0) {
4952 return;
4953 }
4954 // Normalize ratios to geometric mean 1 so s carries the scale.
4955 const Eigen::VectorXd log_ratio = ratio.array().log();
4956 const double log_gm = log_ratio.mean();
4957 const Eigen::VectorXd unit_ratio = (log_ratio.array() - log_gm).exp();
4958
4959 // Warm start: current fitted geometric-mean lengthscale, or the
4960 // descriptor scale itself on a cold model.
4961 double s_center = std::exp(log_gm);
4962 if (ls.size() > 0 && (ls.array() > 0.0).all()) {
4963 s_center =
4964 std::exp(Eigen::Map<const Eigen::ArrayXd>(ls.data(), ls.size())
4965 .log()
4966 .mean());
4967 }
4968
4970 EigenMatrix opt_R_matrix;
4971 Eigen::VectorXd opt_R_indices;
4972 Eigen::VectorXd opt_energy_and_gradient;
4973 aux_func.assembleMatrixOfRepetitiveCoordinates(observation.R, opt_R_matrix,
4974 opt_R_indices);
4975 aux_func.assembleVectorFromEnergyAndGradient(observation,
4976 opt_energy_and_gradient);
4977 subtractPriorMeanFromTargets(observation.R, observation.E.size(),
4978 opt_energy_and_gradient);
4979 standardizeTargets(opt_energy_and_gradient, observation.E.size());
4980
4981 const auto fillLengthscales = [&](double s) {
4982 Eigen::Index k = 0;
4983 for (Eigen::Index r = 0; r < ls.rows(); ++r) {
4984 for (Eigen::Index c = 0; c < ls.cols(); ++c) {
4985 const Eigen::Index pt = ls.cols() > 1 ? c : r;
4986 const double ratio_pt =
4987 pt < unit_ratio.size() ? unit_ratio(pt) : 1.0;
4988 ls(r, c) = s * ratio_pt;
4989 ++k;
4990 }
4991 }
4992 (void)k;
4993 };
4994
4995 // 7-point log grid, half-decade span around the warm center: the
4996 // NLML in s is unimodal over far wider ranges in practice, and the
4997 // cadence keeps consecutive optima close.
4998 constexpr int kGridPoints = 7;
4999 constexpr double kLogSpan = 0.5 * 2.302585092994046; // half a decade
5000 struct GridCandidate {
5001 double s = 0.0;
5002 double prefactor = 0.0;
5003 double noise = 0.0;
5004 double nlml = std::numeric_limits<double>::infinity();
5005 };
5006 std::vector<GridCandidate> candidates;
5007 candidates.reserve(kGridPoints);
5008 for (int g = 0; g < kGridPoints; ++g) {
5009 if (stopForWallClock()) return;
5010 const double t = kGridPoints > 1
5011 ? -1.0 + 2.0 * static_cast<double>(g) /
5012 static_cast<double>(kGridPoints - 1)
5013 : 0.0;
5014 const double s = s_center * std::exp(t * kLogSpan);
5015 fillLengthscales(s);
5016 const ProfiledKernelScale scale = profileUnitKernelScale(
5017 *this, opt_R_matrix, opt_R_indices, opt_energy_and_gradient);
5018 if (!scale.ok) continue;
5019 // noise is the observation variance sf2 * rho, not the ratio rho.
5020 candidates.push_back({s, scale.signal, scale.noise, scale.nlml});
5021 }
5022 if (candidates.empty()) {
5024 return;
5025 }
5026 std::sort(candidates.begin(), candidates.end(),
5027 [](const GridCandidate& a, const GridCandidate& b) {
5028 return a.nlml < b.nlml;
5029 });
5030
5031 // Physics-informed selection (constrained empirical Bayes): among
5032 // the top NLML candidates, reject those whose posterior energy
5033 // profile along the collocation path (the live band, the discrete
5034 // IRC) oscillates. A single-barrier valley profile has total
5035 // variation ~ 2x its range; a churned-lengthscale posterior
5036 // wiggles and its TV blows past that. The bound is scale-free, so
5037 // there is no penalty weight to tune; if every candidate fails the
5038 // filter, pure NLML decides (the filter constrains, never
5039 // invents).
5040 // Derived filter (scripts/derive_chem_factorized_hyper.py): a
5041 // piecewise-monotone profile with at most B barriers satisfies
5042 // TV <= 2 B range exactly, and predictive noise sigma_i moves the
5043 // measured TV by at most sigma_TV = sum_i (sigma_i + sigma_{i-1}).
5044 // Reject a candidate only when its profile exceeds the B-barrier
5045 // bound SIGNIFICANTLY: TV - 2 B range > sigma_TV. At low data the
5046 // predictive sigmas are large, sigma_TV dominates, and the filter
5047 // self-disables; no separate low-data guard exists.
5048 // kMaxBarriers = 2 is a chemistry assumption (one intermediate
5049 // along the band), not a tuning constant.
5050 auto bandProfileAccepted = [&](const GridCandidate& c) {
5051 if (wallClockLimitReached()) return false;
5052 if (physics_collocation_path_.rows() < 4) return true;
5053 fillLengthscales(c.s);
5054 sexpat_cov_func->setMagnSigma2(c.prefactor);
5055 lik_gaussian->setSigma2(c.noise);
5056 sigma2 = trainingToPhysicalNoiseVariance(c.noise);
5057 updateModelWithFullData(observation);
5058 const Eigen::Index m = physics_collocation_path_.rows();
5059 Eigen::VectorXd profile(m);
5060 Eigen::VectorXd sigma(m);
5061 for (Eigen::Index i = 0; i < m; ++i) {
5062 if (wallClockLimitReached()) return false;
5063 gpr::Observation probe;
5064 probe.R.resize(1, physics_collocation_path_.cols());
5065 probe.R.row(0) = physics_collocation_path_.row(i);
5067 if (probe.E.size() == 0 || !std::isfinite(probe.E(0, 0)))
5068 return true; // no usable profile: do not filter
5069 profile(i) = probe.E(0, 0);
5070 gpr::Observation variance_probe;
5071 variance_probe.R.resize(1, physics_collocation_path_.cols());
5072 variance_probe.R.row(0) = physics_collocation_path_.row(i);
5073 calculateVarianceDispatched(variance_probe);
5074 const double energy_variance =
5075 variance_probe.E.size() > 0 ? variance_probe.E(0, 0) : 0.0;
5076 sigma(i) = std::isfinite(energy_variance) && energy_variance > 0.0
5077 ? std::sqrt(energy_variance)
5078 : 0.0;
5079 }
5080 const double range = profile.maxCoeff() - profile.minCoeff();
5081 if (!(range > 0.0)) return true;
5082 double total_variation = 0.0;
5083 double sigma_tv = 0.0;
5084 for (Eigen::Index i = 1; i < m; ++i) {
5085 total_variation += std::abs(profile(i) - profile(i - 1));
5086 sigma_tv += sigma(i) + sigma(i - 1);
5087 }
5088 constexpr int kMaxBarriers = 2;
5089 const double bound = 2.0 * kMaxBarriers * range;
5090 return total_variation - bound <= sigma_tv;
5091 };
5092
5093 constexpr int kPhysicsCheckedCandidates = 3;
5094 const GridCandidate* selected = nullptr;
5095 const int check_count = std::min<int>(kPhysicsCheckedCandidates,
5096 static_cast<int>(candidates.size()));
5097 for (int c = 0; c < check_count; ++c) {
5098 if (bandProfileAccepted(candidates[static_cast<std::size_t>(c)])) {
5099 selected = &candidates[static_cast<std::size_t>(c)];
5100 break;
5101 }
5102 if (stopForWallClock()) return;
5103 }
5104 if (selected == nullptr) selected = &candidates.front();
5105
5106 fillLengthscales(selected->s);
5107 sexpat_cov_func->setMagnSigma2(selected->prefactor);
5108 lik_gaussian->setSigma2(selected->noise);
5109 sigma2 = trainingToPhysicalNoiseVariance(selected->noise);
5110 if (this->report_level >= 2) {
5111 log_man << "Chem-factorized optimization: s=" << selected->s
5112 << " noise=" << selected->noise
5113 << " prefactor=" << selected->prefactor
5114 << " NLML=" << selected->nlml << " (rank "
5115 << (selected - candidates.data()) << " after physics filter)"
5116 << "\n";
5117 }
5118 if (stopForWallClock()) return;
5119 updateModelWithFullData(observation);
5120}
5121
5123 bool enabled) noexcept
5124{
5125 optimizer_state_->require_scg_fallback_improvement = enabled;
5126}
5127
5129{
5130 return optimizer_state_->require_scg_fallback_improvement;
5131}
5132
5134 const noexcept
5135{
5136 return optimizer_state_->nonfinite_marginal_likelihood_rejections;
5137}
5138
5139} // namespace gpr
A global stage before the local MAP fit: anneal's communicating box ensemble over the hyperparameter ...
@ z
Definition Enums.h:28
@ x
Definition Enums.h:28
@ y
Definition Enums.h:28
@ MOVING_ATOM
Definition Enums.h:35
ConvergenceNormType
Definition Enums.h:48
Eigendecomposition-based log marginal likelihood evaluation.
Exponential grid search for noise hyperparameter optimization.
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
void dist_at(const gpr::Coord &x1, const gpr::Coord &x2, const gpr::AtomsConfiguration &conf_info, const gpr::FieldMatrixd &lengthscale, gpr::FieldMatrixd &dist, bool take_sqrt=true)
Give the distance between two atomic configurations as defined in the special GPstuff covariance func...
Definition Distance.cpp:620
void dist_max1Dlog(const gpr::Coord &x1, const gpr::Coord &x2, const gpr::AtomsConfiguration &conf_info, gpr::FieldMatrixd &dist)
Give the maximum difference in the logarithmic inter-atomic distances between atomic configurations C...
Definition Distance.cpp:462
void dist_emd(const gpr::Coord &x1, const gpr::Coord &x2, const gpr::AtomsConfiguration &conf_info, gpr::FieldMatrixd &dist)
Calculates the Earth Mover's Distance between sets of configurations.
void dist_rmsd(const gpr::Coord &x1, const gpr::Coord &x2, const gpr::AtomsConfiguration &conf_info, gpr::FieldMatrixd &dist)
Calculates the aligned Root Mean Square Deviation (RMSD) between sets of configurations.
Definition Distance.cpp:410
void setPersistentSession(bool keep) noexcept
Definition RgminOpt.h:154
void setAlgorithmSettings(const gpr::ScgOptimizationSettings &s)
Definition RgminOpt.h:44
std::size_t logicalObjectiveWork() const noexcept
Objective-count units for the fit under a single-entry request cache.
Definition RgminOpt.h:204
void setMethod(rgmin::Method m) noexcept
Definition RgminOpt.h:49
std::size_t physicalObjectiveWork() const noexcept
Executed objective-count units, including final holder restoration.
Definition RgminOpt.h:209
void optimizeWithObjectiveValues(const gpr::EigenMatrix &x, const Eigen::VectorXd &x_ind, const Eigen::VectorXd &y, Eigen::VectorXd &w, FuncName func_to_min, ClassName &holder, double barrier_strength, const Eigen::VectorXd &lengthscale_rho0, const MapObjectiveConfig *objective_config, double *opening_value_out, double *last_value_out)
Definition RgminOpt.inl:31
void setBox(Eigen::VectorXd lower, Eigen::VectorXd upper)
Coordinate box on x + p. Empty is unbounded on that side.
Definition RgminOpt.h:136
void setGradTol(double g) noexcept
Definition RgminOpt.h:130
void setEigendecomposition(const Eigen::VectorXd &eigenvalues, const EigenMatrix &eigenvectors, const Eigen::VectorXd &targets)
Cache the eigendecomposition of K_XX for repeated noise sweeps.
void tieLengthScaleParameters(Eigen::VectorXd &theta) const
Sets every tied member to its leader's log length (theta(1 + t)).
linalg::BackendContext & backend() const
void setSliceLaplaceHessianCholForTesting(const Eigen::MatrixXd &U)
Eigen::VectorXd permuteTrainingVector(const Eigen::VectorXd &input) const
MarginalLikelihoodReport optimizeMarginalLikelihood(const Observation &observation)
Definition Optimize.cpp:952
void poolDescriptorScaleByTies(Eigen::VectorXd &scales) const
Observation selectOptimizationSubset(const Observation &full_observation) const
Select a hyperparameter-optimization subset via FPS-EMD.
void evaluateCovarianceMatrix(const EigenMatrix &x1, const EigenMatrix &x2, const Eigen::VectorXd &x1_ind, const Eigen::VectorXd &x2_ind, EigenMatrix &C, bool serial_per_rank=false) const
Evaluate covariance matrix between two input vectors.
void evaluateEnergyAndGradient(const Eigen::VectorXd &w, const EigenMatrix &x, const Eigen::VectorXd &x_ind, const Eigen::VectorXd &y, EnergyAndGradient &energy_and_gradient)
Evaluate the energy function (un-normalized negative marginal log posterior) and its gradient.
MeasuredRowVerdict
Agreement between measured rows and the current posterior.
void setParameters(const GPRSetup &parameters)
Set parameters of the GPR model.
void optimizeChemistryFactorized(const Observation &observation)
Chemistry-constrained ARD refit: pairtype lengthscale ratios fixed from descriptor spreads,...
void buildRFFModel(const Observation &training_data, int D_rff)
Definition RFF.cpp:17
void setHyperparameterObjectiveMode(HyperparameterObjectiveMode mode) noexcept
bool objectiveStationaritySkipMayBeActive() const noexcept
std::size_t rgminWarmPairsForTesting() const noexcept
Curvature pairs the last rgmin fit transplanted from that record.
bool refreshFullDataPosteriorIfObjectiveStationary(const Observation &full_observation, double *shift_norm_out=nullptr)
detail::RigidDeflationState rigid_deflation_
OptimizationObjectiveFrame enterOptimizationObjectiveFrame(Eigen::VectorXd &targets, Eigen::Index energy_count, Eigen::VectorXd *theta)
RFFFeatureSelection selectRFFFeatures(const Observation &observation, std::uint64_t memory_cap_bytes=kRFFValidationMemoryCapBytes)
bool usesFullObservationForHyperparameterOptimization(const Observation &observation) const noexcept
bool decomposeCovarianceMatrix(const EigenMatrix &x, const Eigen::VectorXd &x_ind)
Evaluate and decompose the covariance matrix using Cholesky decomposition.
EigenMatrix permuteTrainingRows(const EigenMatrix &input) const
bool prepareTrainingKernelGeometry(const EigenMatrix &x, const Eigen::VectorXd &x_ind, TrainingKernelGeometry &out, bool reused=false) const
bool updateRobustRowWeights(const Observation &full_observation)
std::size_t rgminWarmStartsForTesting() const noexcept
Fits the rgmin sessions opened with the previous fit's record.
void leaveOptimizationObjectiveFrame(const OptimizationObjectiveFrame &frame, Eigen::VectorXd *theta) noexcept
void calculateVarianceDispatched(Observation &image1)
void optimizeFactorized(const Observation &observation)
Alternative optimization via eigendecomposition + noise grid search.
bool hasPendingResidualModelRefit() const noexcept
static bool computePairtypeDescriptorScale(const Coord &R, const AtomsConfiguration &conf_info, Eigen::VectorXd &ls_k)
Per-pairtype motion scale rho0_k = sqrt(sum_f var(1/r_f)). Each pair feature is centered across confi...
bool wallClockLimitReached() const
Collective on the model's process group for distributed fitters.
bool hasPendingActivePosteriorRefit() const noexcept
double computeLaplaceSkipScgShiftNorm(const EigenMatrix &opt_R_matrix, const Eigen::VectorXd &opt_R_indices, const Eigen::VectorXd &opt_y)
void optimize(const Observation &observation)
Optimize paramaters of a Gaussian process.
Definition Optimize.cpp:550
bool configureMinimumModeRefit(const Observation &oracle, double force_tolerance, ConvergenceNormType force_norm=ConvergenceNormType::L2_NORM, const RefitTrustReport *trust_report=nullptr)
void refreshLengthScaleLeaders()
Recomputes the leaders from the released flags.
bool requiresScgFallbackImprovement() const noexcept
double reportedVarianceCalibrationFactor() const noexcept
void evaluateLeaveOneOutEnergyAndGradientFromGeometry(const Eigen::VectorXd &w, const TrainingKernelGeometry &geom, const EigenMatrix &x, const Eigen::VectorXd &x_ind, const Eigen::VectorXd &y, EnergyAndGradient &energy_and_gradient)
std::vector< int > selectOptimizationSubsetRows(const Observation &full_observation) const
Select a hyperparameter-optimization subset via FPS-EMD.
bool assembleExactHessian(const Eigen::VectorXd &x_ind, const EigenMatrix &x, const Eigen::VectorXd &y, int n_hyperparameters, Eigen::MatrixXd &H)
Assemble the full p x p observed-information Hessian of the negative log marginal likelihood at the c...
Definition Hessian.cpp:568
void setRequireScgFallbackImprovement(bool enabled) noexcept
std::shared_ptr< linalg::KokkosMolecularPosterior > device_posterior_
bool evaluateNlmlHessianVector(const Eigen::VectorXd &x_ind, const EigenMatrix &x, const Eigen::VectorXd &y, const Eigen::VectorXd &direction, Eigen::VectorXd &product, const TrainingKernelGeometry *training_geom=nullptr)
Exact Hessian-vector product of the negative log marginal likelihood, including the covariance-functi...
Definition Hessian.cpp:371
bool hasDevicePosterior() const noexcept
void setVarianceConvention(VarianceConvention convention) noexcept
static int chooseFarthestPointDeterministic(const std::vector< std::pair< int, double > > &candidate_distances, double tolerance=1e-12)
std::unique_ptr< SexpatCF > sexpat_cov_func
bool prepareMeanHessianVectorHssvd(const Coord &R, PreparedHssvdHessianVector &prepared) const
ForceCalibrationReport calibrateHeldOutForces(const Observation &held_out, double nominal_probability)
std::size_t nonfiniteMarginalLikelihoodRejections() const noexcept
bool monitorAndAdaptHyperparameters(const Eigen::VectorXd &new_parameters)
Monitors hyperparameter history for oscillations and adapts the FPS history size.
void evaluateLocalNeighborhoodLooEnergyAndGradientFromGeometry(const Eigen::VectorXd &w, const TrainingKernelGeometry &geom, const EigenMatrix &x, const Eigen::VectorXd &x_ind, const Eigen::VectorXd &y, EnergyAndGradient &energy_and_gradient)
bool observationBandInfluence(const Observation &observation, const Coord &band_positions, Eigen::VectorXd &influence, bool collective=false)
Per-observation influence on the band posterior.
bool configureModeRefit(const Observation &oracle, const Coord &mode, double force_tolerance, ConvergenceNormType force_norm=ConvergenceNormType::L2_NORM)
void captureFittedHyperparameterDensity(const Coord &positions, const Eigen::VectorXd &targets, const Eigen::VectorXd &theta, const funcmin::MapObjectiveConfig &penalty, double target_scale, bool use_ties)
void setHssvdBackend(bool enabled) noexcept
void optimizeLaplaceINLA(const Observation &observation)
Definition INLA.cpp:402
void calculatePotentialDispatched(Observation &image1)
Definition Predict.cpp:982
void updateModelWithFullData(const Observation &full_observation)
linalg::linop::DenseCholeskySolver trainingSolver() const
void forgetRgminSessions() noexcept
bool trainingFactorAppendable(Eigen::Index observations) const
bool appendFixedHyperparameters(const Observation &full_observation)
void updateConfiguration(const AtomsConfiguration &conf_info)
Update the internal atoms configuration. Use this when the set of active/frozen atoms changes dynamic...
bool nlmlHessianVectorCurvatureRequested() const noexcept
std::deque< Eigen::VectorXd > hyperparameter_history_
const char * getHyperparameterOptimizerBackend() const noexcept
bool applyMeanHessianBlockHssvd(const PreparedHssvdHessianVector &prepared, const Eigen::MatrixXd &directions, Eigen::MatrixXd &hessian_block) const
void noteNlmlHessianVectorFallback(const char *where, const char *why)
Definition Hessian.cpp:361
bool canUseTrainingGeometryObjective() const noexcept
Definition Optimize.cpp:389
void evaluateEnergyAndGradientFromGeometry(const Eigen::VectorXd &w, const TrainingKernelGeometry &geom, const EigenMatrix &x, const Eigen::VectorXd &x_ind, const Eigen::VectorXd &y, EnergyAndGradient &energy_and_gradient)
void setHyperparameters(const Observation &all_obs, const AtomsConfiguration &conf_info, const bool update_sexpat_cf_param=true, const bool update_const_cf_param=true, const bool update_sqrt_prior_param=true)
Set up hyperparameters for GPR.
void evaluateHyperparameterObjectiveEnergyAndGradient(const Eigen::VectorXd &w, const EigenMatrix &x, const Eigen::VectorXd &x_ind, const Eigen::VectorXd &y, EnergyAndGradient &energy_and_gradient)
MeasuredRowVerdict measuredRowsAgreeWithPosterior(const Observation &rows, ConvergenceNormType force_norm, double *max_force_error=nullptr, double *max_force_sd=nullptr, double *evidence_nats=nullptr, double variance_calibration=1.0, RefitTrustReport *trust_report=nullptr)
virtual bool exactNlmlHessianVectorAvailable() const noexcept
bool hasTrainingCholeskyFactor(Eigen::Index expected_rows) const noexcept
double computeObjectiveStationarityShiftNorm(const EigenMatrix &opt_R_matrix, const Eigen::VectorXd &opt_R_indices, const Eigen::VectorXd &opt_y, const Eigen::VectorXd &theta_reference, Eigen::VectorXd *shift_out=nullptr, double *energy_out=nullptr, Eigen::VectorXd *gradient_out=nullptr)
VarianceConvention varianceConvention() const noexcept
void configureLengthScaleTies(const AtomsConfiguration &configuration)
MeanHessianAction prepareMeanHessian(const Coord &R)
Linear action of the physical posterior mean at one geometry.
std::vector< std::size_t > holdLengthScalesUnresolvedBySubset(const Observation &subset)
Hold, for the next fit, the length scales a pooled subset does not resolve: its inverse-distance feat...
void evaluateTrainingCovarianceMatrix(const EigenMatrix &x, const Eigen::VectorXd &x_ind, EigenMatrix &cov_matrix, bool serial_per_rank=false, bool include_constant=true, bool include_noise=true)
Evaluate training covariance matrix (gp_cov + noise covariance).
Eigen::VectorXd performHyperparameterOptimization(const Observation &opt_observation)
const TrainingKernelGeometry * fitGeometryFor(const EigenMatrix &x, const Eigen::VectorXd &x_ind) const
bool lengthScaleTiesActive(Eigen::Index length_count) const noexcept
const char * hyperparameterOptimizationModeName() const noexcept
Name of the hyperparameter fit in force, for the run report.
static std::vector< int > featurePairtypes(const AtomsConfiguration &conf_info)
Pairtype index for each feature.
static void compute(const Coord &x, const AtomsConfiguration &conf_info, Eigen::VectorXd &phi)
Compute phi(x) for a single configuration.
Gaussian noise with variance.
Definition LikGaussian.h:29
std::vector< bool > select(const Coord &positions, const AtomsConfiguration &configuration, const FieldMatrixd &lengths, const Eigen::VectorXd &mode, double force_sd, double force_error, double force_tolerance, bool require_parameter_reduction=true)
Exponential grid search over noise hyperparameter.
NoiseSearchResult searchGP(const FactorizedLikelihood &likelihood) const
Search for optimal noise using GP factorized likelihood.
Class of prior parameters.
Definition PriorBase.h:23
void setMu(const double value)
Definition PriorBase.h:63
void setS2(const double value)
Definition PriorBase.h:68
double getMu() const
Definition PriorBase.h:48
double getS2() const
Definition PriorBase.h:53
double getNu() const
Definition PriorBase.h:58
Random Fourier Features (RFF) approximation to the SE kernel.
Definition RFFModel.h:51
void build(SexpatCF &kernel, const AtomsConfiguration &conf_info, const Observation &training_data, int D_rff, double noise_var=1e-6, double grad_noise_var=1e-4)
Build the RFF model from trained hyperparameters and data.
Definition RFFModel.cpp:42
Pair-type inverse-distance squared-exponential primitive.
Definition SexpatCF.h:74
EigenMatrix solveColumns(const EigenMatrix &B) const
K^{-1} B through the two triangular solves.
EigenMatrix whitenColumns(const EigenMatrix &B) const
EigenMatrix unwhitenColumns(const EigenMatrix &B) const
Eigen::VectorXd lengthScalePerPairtype() const
Auxiliary functions for CDF calculation.
double normalCDFInverse(const double p, double const mu, const double sigma)
Inverse complementary error function.
void restoreMapAmplitudeFeasibility(Eigen::VectorXd &w, const MapObjectiveConfig &cfg)
MapObjectiveConfig makeMapObjectiveConfig(const gpr::EigenMatrix &x, const Eigen::VectorXd &y, const Eigen::VectorXd &w, double current_barrier_strength, const Eigen::VectorXd &lengthscale_rho0, const gpr::ScgOptimizationSettings &settings, bool robust_signal_anchor=true)
bool holderHasNlmlHessianVector(Holder &holder)
void applyMapPenalty(const Eigen::VectorXd &w, const MapObjectiveConfig &cfg, double &energy, Eigen::VectorXd *gradient)
void mapPenaltyHessianVector(const Eigen::VectorXd &w, const Eigen::VectorXd &direction, const MapObjectiveConfig &cfg, Eigen::VectorXd &product)
void projectMapGradient(const MapObjectiveConfig &cfg, Eigen::VectorXd &gradient)
bool holderNlmlHessianVector(Holder &holder, const Eigen::VectorXd &x_ind, const gpr::EigenMatrix &x, const Eigen::VectorXd &y, const Eigen::VectorXd &direction, Eigen::VectorXd &product)
Index_t numPoints(const FieldMatrixd &mat)
double teamFactorWallSeconds()
double teamSolveWallSeconds()
constexpr MpiCommType kMpiCommNull
Definition MpiContext.h:56
bool exceedsThreshold(double value, double threshold) noexcept
double log(double x) noexcept
Gaussian-process regression, kernels, priors, and the searches that run on the surrogate.
Definition Macros.h:16
FieldMatrixd Coord
Definition Macros.h:35
bool usesClassicJointEnergyForcePrior(GPModelProfile profile) noexcept
Definition Structures.h:206
uint32_t Index_t
Definition Macros.h:17
double forceNorm(const Eigen::MatrixBase< Derived > &force, ConvergenceNormType norm)
Definition ForceNorm.h:45
EigenMatrix unpermuteSymmetricMatrix(const EigenMatrix &input, const StructuredPermutation &p)
double lengthscaleProjectionFloor(double max_pair_distance, double absolute_floor)
EigenMatrix unpermuteMatrixRows(const EigenMatrix &input, const StructuredPermutation &p)
Eigen::Matrix< double, EigenDynamic, EigenDynamic, EigenMatrixStorage > EigenMatrix
Definition Macros.h:20
Eigen::Matrix< double, EigenDynamic, EigenDynamic, FieldMatrixStorage > FieldMatrixd
Definition Macros.h:25
UncertaintyMode
Definition Structures.h:177
HyperparameterOptimizationMode
Definition Enums.h:56
HyperparameterObjectiveMode
Definition Enums.h:70
bool resolved(Dual value, Dual error, const BridgeResidualOptions &options)
STL namespace.
double barrier_strength
Already capped with min(current_barrier_strength, 0.5) by the caller.
Eigen::VectorXd prior_weight
Eigen::VectorXd parameter_lower
Eigen::VectorXd parameter_upper
std::vector< bool > active_parameters
gpr::MapPriorWeightMode weight_mode
Stores configurations of all atoms in the system.
Definition Structures.h:832
std::vector< Index_t > pair_type_parent
Definition Structures.h:854
Index_t n_base_pt
Number of base pair types (0: none).
Definition Structures.h:855
Structure of energy and gradient stored in Eigen-compatible form.
Definition Structures.h:359
Componentwise held-out force calibration in physical units.
Result of a prior-free negative log marginal-likelihood fit.
int iterations
Optimizer iterations summed over the first pass and the restart.
Performs the numerical optimization of hyperparameters.
bool matches(const GaussianProcessRegression &model, const Observation &acquired, ConvergenceNormType norm) const
std::shared_ptr< const ActivePosteriorState > active_posterior
State(const GaussianProcessRegression &model, const Observation &acquired, ConvergenceNormType norm, std::vector< Row > values)
Result of a noise grid search.
Observation data: energy, gradient and positions.
FieldMatrixd E
static double cache_seconds
Inverse-distance cache built once before the hyperparameter fit.
static void recordFitRestart() noexcept
static double condition_seconds
static void notePeak(const char *phase) noexcept
static double eigensolve_seconds
static double subset_seconds
static double energy_seconds
Objective energy outside factor, solve, eigen, kernel, and curvature.
static double assembly_seconds
static double gradient_seconds
static double descriptor_seconds
static void recordFit(long evaluations, bool unmoved) noexcept
static double schedule_seconds
Optimizer outside the named numerical leaves.
static double curvature_seconds
static double posterior_seconds
static int objective_count
Measured result of one automatic selection. Unmeasured errors stay NaN.
SCG-specific settings (trust-region scale, log-magnSigma2 barriers, curvature mode).
Definition Structures.h:246
bool is_distributed() const noexcept
Definition MpiContext.h:67