Loading...
Searching...
No Matches
GPMinimizer.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#include "GPMinimizer.h"
6
7#include <algorithm>
8#include <cmath>
9#include <cstddef>
10#include <cstdint>
11#include <cstring>
12#include <iostream>
13#include <limits>
14#include <random>
15#include <stdexcept>
16#include <type_traits>
17
21#include "../neb/Session.h"
22#include "LBFGS.h"
23#include "RgminStep.h"
24#include "TrustRegionSegment.h"
25
26namespace gpr {
27namespace optim {
28namespace {
29
30using detail::maxAtomDisplacement;
31
32double energyVarianceAt(GaussianProcessRegression& gp, const Eigen::VectorXd& x)
33{
34 Observation query;
35 query.R.resize(1, x.size());
36 query.R.row(0) = x.transpose();
37 gp.calculateVarianceDispatched(query);
38 if (query.E.size() == 0 || !query.E.allFinite()) {
39 return std::numeric_limits<double>::quiet_NaN();
40 }
41 return std::abs(query.E(0, 0));
42}
43
44void clipAtomMaxMove(Eigen::VectorXd& delta, double max_move)
45{
46 if (!(max_move > 0.0) || !std::isfinite(max_move)) return;
47 const double max_disp = maxAtomDisplacement(delta);
48 if (max_disp > max_move) {
49 delta *= (max_move / max_disp);
50 }
51}
52
53double minTrainingAtomDistance(const Observation& obs, const Eigen::VectorXd& x)
54{
55 double min_dist = std::numeric_limits<double>::infinity();
56 for (Eigen::Index r = 0; r < obs.R.rows(); ++r) {
57 const double d_t = maxAtomDisplacement(x - obs.R.row(r).transpose());
58 min_dist = std::min(min_dist, d_t);
59 }
60 return min_dist;
61}
62
63class RecentAnchoredSizeCapPolicy final : public policy::TrainingPolicy {
64public:
65 explicit RecentAnchoredSizeCapPolicy(int max_size,
66 Eigen::VectorXd anchor_pos)
67 : max_size_(max_size), anchor_pos_(std::move(anchor_pos))
68 {
69 }
70
71 [[nodiscard]] std::vector<int> retain_training_rows(
72 const std::vector<Eigen::VectorXd>& current_positions) const override
73 {
74 const int n = static_cast<int>(current_positions.size());
75 if (max_size_ <= 0 || n <= max_size_) {
76 std::vector<int> all(static_cast<std::size_t>(n));
77 for (int i = 0; i < n; ++i) {
78 all[static_cast<std::size_t>(i)] = i;
79 }
80 return all;
81 }
82 std::vector<int> selected;
83 selected.reserve(static_cast<std::size_t>(max_size_));
84 std::vector<bool> chosen(static_cast<std::size_t>(n), false);
85 const auto pick = [&](int idx) {
86 if (idx < 0 || idx >= n || chosen[static_cast<std::size_t>(idx)] ||
87 static_cast<int>(selected.size()) >= max_size_) {
88 return;
89 }
90 chosen[static_cast<std::size_t>(idx)] = true;
91 selected.push_back(idx);
92 };
93 pick(n - 1);
94 if (anchor_pos_.size() > 0) {
95 for (int i = n - 1; i >= 0; --i) {
96 if (neb::detail::positionsCoincide(
97 current_positions[static_cast<std::size_t>(i)],
98 anchor_pos_)) {
99 pick(i);
100 break;
101 }
102 }
103 }
104 if (max_size_ >= 2 && static_cast<int>(selected.size()) < 2) {
105 pick(n - 2);
106 }
107
108 std::vector<double> min_dist_sq(
109 static_cast<std::size_t>(n),
110 std::numeric_limits<double>::infinity());
111 for (int s: selected) {
112 for (int i = 0; i < n; ++i) {
113 const double d2 =
114 (current_positions[static_cast<std::size_t>(i)] -
115 current_positions[static_cast<std::size_t>(s)])
116 .squaredNorm();
117 min_dist_sq[static_cast<std::size_t>(i)] =
118 std::min(min_dist_sq[static_cast<std::size_t>(i)], d2);
119 }
120 }
121 while (static_cast<int>(selected.size()) < max_size_) {
122 int next = -1;
123 double best = -1.0;
124 for (int i = 0; i < n; ++i) {
125 if (chosen[static_cast<std::size_t>(i)]) continue;
126 const double d2 = min_dist_sq[static_cast<std::size_t>(i)];
127 if (d2 > best) {
128 best = d2;
129 next = i;
130 }
131 }
132 if (next < 0) break;
133 pick(next);
134 for (int i = 0; i < n; ++i) {
135 const double d2 =
136 (current_positions[static_cast<std::size_t>(i)] -
137 current_positions[static_cast<std::size_t>(next)])
138 .squaredNorm();
139 min_dist_sq[static_cast<std::size_t>(i)] =
140 std::min(min_dist_sq[static_cast<std::size_t>(i)], d2);
141 }
142 }
143 std::sort(selected.begin(), selected.end());
144 return selected;
145 }
146
147private:
148 int max_size_ = 0;
149 Eigen::VectorXd anchor_pos_;
150};
151
152std::vector<Eigen::VectorXd> trainingPositions(const Observation& obs)
153{
154 std::vector<Eigen::VectorXd> rows;
155 rows.reserve(static_cast<std::size_t>(obs.R.rows()));
156 for (Eigen::Index r = 0; r < obs.R.rows(); ++r) {
157 rows.emplace_back(obs.R.row(r).transpose());
158 }
159 return rows;
160}
161
162void refuseStaleMinimizationConfig(const MinimizationConfig& config)
163{
164 struct Prefix {
165 std::uint32_t abi_version;
166 std::uint32_t reserved;
167 std::uint32_t config_bytes;
168 std::uint32_t result_bytes;
169 };
170 static_assert(std::is_standard_layout_v<MinimizationConfig>);
171 static_assert(sizeof(Prefix) == 16);
172 static_assert(offsetof(MinimizationConfig, abi_version) == 0);
173 static_assert(offsetof(MinimizationConfig, reserved) == 4);
174 static_assert(offsetof(MinimizationConfig, config_bytes) == 8);
175 static_assert(offsetof(MinimizationConfig, result_bytes) == 12);
176 static_assert(offsetof(MinimizationConfig, trust_radius) == 16);
177 Prefix prefix{};
178 std::memcpy(&prefix, &config, sizeof(prefix));
179 const auto expected = compiledMinimizationLayout();
180 if (prefix.abi_version == expected.version &&
181 prefix.config_bytes == expected.config_bytes &&
182 prefix.result_bytes == expected.result_bytes)
183 return;
184 throw std::runtime_error(
185 "MinimizationConfig layout mismatch: caller reported version " +
186 std::to_string(prefix.abi_version) + " (" +
187 std::to_string(prefix.config_bytes) + " config bytes, " +
188 std::to_string(prefix.result_bytes) +
189 " result bytes) but this libgpridge has version " +
190 std::to_string(expected.version) + " (" +
191 std::to_string(expected.config_bytes) + " config bytes, " +
192 std::to_string(expected.result_bytes) + " result bytes)");
193}
194
195} // namespace
196
201
202MinimizationResult gp_minimize(OracleFn oracle, const Eigen::VectorXd& x_init,
203 const AtomsConfiguration& atoms_config,
204 const MinimizationConfig& config,
206 const Observation* seed,
207 const io::TrainedGpState* gp_state)
208{
209 refuseStaleMinimizationConfig(config);
210 if (config.max_inner_steps < 1) {
211 throw std::invalid_argument(
212 "MinimizationConfig::max_inner_steps must be >= 1");
213 }
214 // Direct BFGS maintains positive definiteness for positive-curvature
215 // secants. SR1 and Bofill deliberately retain indefinite curvature, so
216 // they cannot safely initialise a minimization Newton solve.
217 if (config.secant.seed_curvature &&
219 throw std::invalid_argument(
220 "minimization secant curvature seed requires the BFGS method");
221 const int d = static_cast<int>(x_init.size());
222 MinimizationResult result;
223 result.x_final = x_init;
224
228 session.gp_setup = [&](InputParameters& params, AtomsConfiguration& ac) {
229 params.gp_sigma2.value = 1e-8;
230 params.jitter_sigma2.value = config.jitter_sigma2;
231 params.sigma2.value = 1e-8;
232 params.magnSigma2.value = 0.0;
233 params.constSigma2.value = 0.0;
234 params.prior_mu.value = 0;
235 params.prior_nu.value = 20;
236 params.prior_s2.value = 1;
237 params.optimization_alg.value = "SCG_opt";
238 params.max_iter.value = config.gp_train_iter;
239 params.tolerance_func.value = 1e-4;
240 params.tolerance_sol.value = 1e-4;
241 params.report_level.value = config.verbose ? 1 : 0;
242 params.fps_history.value = config.fps_history;
243 ac = atoms_config;
244 };
245 session.initialise();
246 session.gp.setHssvdBackend(config.use_hssvd_solver);
249
250 bool warm_kernel_pending = false;
251 if (seed != nullptr || gp_state != nullptr) {
253 if (gp_state != nullptr) warm = *gp_state;
254 if (seed != nullptr && seed->R.rows() > 0)
256 if (warm.observations.R.rows() > 0 || warm.has_pair_kernel) {
258 session, warm, /*require_identity=*/true, x_init.size());
259 warm_kernel_pending = warm.has_pair_kernel;
260 }
261 }
262
263 int hyperparameter_refits = 0;
264 bool has_fitted_gp = false;
265 bool has_conditioned_gp = false;
266 Eigen::Index seeded_row_count = 0;
267 SecantHessian secant(config.secant.method);
268 std::size_t checked_secant_pairs = 0;
269 std::size_t prior_secant_pairs = 0;
270 SecantNewtonFactor newton_factor;
271 std::size_t newton_factor_pairs = 0;
272 // A secant Newton step moves no atom farther than one trusted step.
273 double seed_bound = std::numeric_limits<double>::infinity();
274 if (config.max_move > 0.0 && std::isfinite(config.max_move))
275 seed_bound = config.max_move;
276 if (config.trust_radius > 0.0 && std::isfinite(config.trust_radius))
277 seed_bound = std::min(seed_bound, config.trust_radius);
278
279 // Every attempted evaluation counts toward max_oracle_calls, finite or
280 // not, and no evaluation is started once the budget is spent.
281 const auto budget_allows = [&]() {
282 return config.max_oracle_calls <= 0 ||
283 result.oracle_calls < config.max_oracle_calls;
284 };
285 const auto measure = [&](const Eigen::VectorXd& x) {
286 ++result.oracle_calls;
287 auto measured = oracle(x);
288 // A non-finite energy is still an observation. The secant then drops
289 // its reference energy instead of keeping the previous geometry's.
290 if (config.secant.enabled() && measured.second.size() == x.size() &&
291 measured.second.allFinite()) {
292 const bool had_reference =
293 secant.referencePosition().size() == x.size();
294 const bool moved =
295 had_reference &&
296 !(secant.referencePosition().array() == x.array()).all();
297 const bool updated =
298 secant.observe(x, measured.second, measured.first);
299 if (moved && !updated) ++result.secant_update_failures;
300 result.secant_pairs = static_cast<int>(secant.pairs());
301 }
302 return measured;
303 };
304 const auto allow_call = [&](policy::OracleRole role,
305 const Eigen::VectorXd& x, double variance,
306 double distance, bool within_trust,
307 bool surrogate_stop) {
308 if (!budget_allows()) return false;
309 if (policy == nullptr) return true;
312 state.role = role;
313 state.iteration = result.total_iterations;
314 state.oracle_calls = result.oracle_calls;
315 state.training_size = static_cast<int>(session.training_obs.R.rows());
316 state.hyperparameter_refits = hyperparameter_refits;
317 state.posterior_variance = variance;
318 state.trust_radius = config.trust_radius;
319 state.distance_to_training = distance;
320 state.within_trust = within_trust;
321 state.surrogate_proposes_stop = surrogate_stop;
322 state.engine_would_call_oracle = true;
323 state.positions = x.data();
324 state.n_coords = d;
325 state.gp = has_conditioned_gp ? &session.gp : nullptr;
327 };
328 double best_observed_energy = std::numeric_limits<double>::infinity();
329 Eigen::VectorXd best_observed_x = x_init;
330 Eigen::VectorXd best_observed_g = Eigen::VectorXd::Zero(d);
331 bool has_best_observed = false;
332 result.e_final = std::numeric_limits<double>::quiet_NaN();
333 result.g_final =
334 Eigen::VectorXd::Constant(d, std::numeric_limits<double>::quiet_NaN());
335
336 // Exact, unmerged oracle evaluations. ActiveLearningSession merges
337 // near-coincident rows (within 1e-6) by averaging targets, so convergence
338 // checks and returned results must never read from session.training_obs.
339 struct RawOracleObservation {
340 Eigen::VectorXd x;
341 double energy = 0.0;
342 Eigen::VectorXd gradient;
343 };
344 std::vector<RawOracleObservation> raw_oracle_obs;
345 const auto find_exact_raw_observation =
346 [&](const Eigen::VectorXd& x) -> const RawOracleObservation* {
347 for (auto it = raw_oracle_obs.rbegin(); it != raw_oracle_obs.rend();
348 ++it) {
349 if (it->x.size() == x.size() &&
350 (it->x.array() == x.array()).all()) {
351 return &(*it);
352 }
353 }
354 return nullptr;
355 };
356
357 bool pending_retain = false;
358 const auto admit = [&](const Eigen::VectorXd& x, double energy,
359 const Eigen::VectorXd& gradient, bool engine_would) {
360 if (!engine_would) return false;
361 bool add = true;
362 if (policy != nullptr) {
363 policy::CandidatePoint candidate;
364 candidate.positions = x;
365 candidate.energy = energy;
366 candidate.gradient = gradient;
367 const std::vector<Eigen::VectorXd> current_rows =
368 trainingPositions(session.training_obs);
369 const std::vector<int> indices =
371 current_rows);
372 add = policy::admitsFirstCandidate(indices);
373 }
374 if (add) {
375 session.appendObservation(x, energy, gradient);
376 }
377 if (config.max_training_points > 0 &&
378 session.training_obs.R.rows() > config.max_training_points) {
379 const Eigen::VectorXd anchor =
380 has_best_observed ? best_observed_x : x;
381 RecentAnchoredSizeCapPolicy cap(config.max_training_points, anchor);
382 session.retainTrainingRowsForPolicy(cap);
383 }
384 pending_retain = true;
385 return add &&
386 neb::detail::findPositionRow(session.training_obs, x) >= 0;
387 };
388 // retain_training_rows runs once after the initial design and once per
389 // outer step, after that step's admission.
390 const auto retain_admitted = [&]() {
391 if (policy != nullptr && pending_retain) {
393 }
394 pending_retain = false;
395 };
396
397 const auto record_initial_observation =
398 [&](const Eigen::VectorXd& x, double energy,
399 const Eigen::VectorXd& gradient) {
400 if (!std::isfinite(energy) || gradient.size() != d ||
401 !gradient.allFinite()) {
402 return false;
403 }
404 raw_oracle_obs.push_back({x, energy, gradient});
405 result.energy_trajectory.push_back(energy);
406 if (!has_best_observed || energy < best_observed_energy) {
407 best_observed_energy = energy;
408 best_observed_x = x;
409 best_observed_g = gradient;
410 has_best_observed = true;
411 result.x_final = x;
412 result.e_final = energy;
413 result.g_final = gradient;
414 }
415 return admit(x, energy, gradient, true);
416 };
417
418 for (Eigen::Index row = 0; row < session.training_obs.R.rows(); ++row) {
419 const Eigen::VectorXd seeded_x =
420 session.training_obs.R.row(row).transpose();
421 const double seeded_energy = session.training_obs.E(row, 0);
422 const Eigen::VectorXd seeded_gradient =
423 session.training_obs.G.row(row).transpose();
424 if (seeded_x.size() != d)
425 throw std::runtime_error(
426 "gp-state.npz coordinates do not match this search (" +
427 std::to_string(seeded_x.size()) + " columns, this search has " +
428 std::to_string(d) + ")");
429 if (!seeded_x.allFinite() || !std::isfinite(seeded_energy) ||
430 seeded_gradient.size() != d || !seeded_gradient.allFinite())
431 throw std::runtime_error("gp-state.npz seed row " +
432 std::to_string(row) + " is non-finite");
433 raw_oracle_obs.push_back({seeded_x, seeded_energy, seeded_gradient});
434 }
435
436 // Step 1: Initial oracle evaluations. A seed row at x_init is prior
437 // data and is not an oracle call.
438 if (const RawOracleObservation* seeded =
439 find_exact_raw_observation(x_init)) {
440 result.energy_trajectory.push_back(seeded->energy);
441 best_observed_energy = seeded->energy;
442 best_observed_x = seeded->x;
443 best_observed_g = seeded->gradient;
444 has_best_observed = true;
445 result.x_final = seeded->x;
446 result.e_final = seeded->energy;
447 result.g_final = seeded->gradient;
448 } else if (allow_call(policy::OracleRole::InitialDesign, x_init,
449 std::numeric_limits<double>::quiet_NaN(),
450 std::numeric_limits<double>::infinity(), false,
451 false)) {
452 auto [e_init, g_init] = measure(x_init);
453 record_initial_observation(x_init, e_init, g_init);
454 }
455 if (!has_best_observed && result.oracle_calls == 0) return result;
456
457 // Optional initial perturbations for GP diversity
458 std::mt19937 rng(config.seed);
459 std::uniform_real_distribution<double> dist(-0.5, 0.5);
460 for (int k = 0; k < config.n_initial_perturb; ++k) {
461 if (!budget_allows()) break;
462 Eigen::VectorXd x_p = x_init;
463 for (int i = 0; i < d; ++i) {
464 x_p(i) += dist(rng) * config.perturb_scale;
465 }
466 if (!allow_call(policy::OracleRole::InitialDesign, x_p,
467 std::numeric_limits<double>::quiet_NaN(),
468 std::numeric_limits<double>::infinity(), false,
469 false)) {
470 continue;
471 }
472 auto [e_p, g_p] = measure(x_p);
473 record_initial_observation(x_p, e_p, g_p);
474 }
475 retain_admitted();
476
477 if (!has_best_observed) {
478 return result;
479 }
480
481 if (best_observed_g.size() == d && best_observed_g.allFinite() &&
482 best_observed_g.norm() < config.conv_tol) {
483 result.converged = true;
484 result.x_final = best_observed_x;
485 result.e_final = best_observed_energy;
486 result.g_final = best_observed_g;
487 return result;
488 }
489
490 if (session.training_obs.R.rows() == 0) {
491 return result;
492 }
493
494 Eigen::VectorXd x_curr = best_observed_x;
495 RgminStep gp_stepper;
496
497 // Step 2: Main outer loop
498 for (int outer = 0; outer < config.max_iter; ++outer) {
499 if (!budget_allows()) break;
500 if (session.training_obs.R.rows() == 0) break;
501
502 if (warm_kernel_pending) {
503 session.applySeededModel();
504 if (session.gp.hasBeenOptimized()) {
506 seeded_row_count = session.training_obs.R.rows();
507 has_fitted_gp = true;
508 has_conditioned_gp = true;
509 gp_stepper.forget();
510 }
511 warm_kernel_pending = false;
512 }
513
514 session.publishPolicyProgress(
515 result.total_iterations, result.oracle_calls, hyperparameter_refits,
516 static_cast<int>(session.training_obs.R.rows()));
517 // The GP is conditioned on the residual of the latest secant
518 // quadratic, which moves with every accepted pair.
519 bool secant_prior_moved = false;
520 if (config.secant.quadratic_prior_mean && secant.available() &&
521 prior_secant_pairs != secant.pairs()) {
522 // referenceEnergy() throws when the accepted geometry had a
523 // non-finite oracle energy. Refuse that pair here, with the
524 // reason, instead of aborting inside the accessor.
525 if (!secant.hasReferenceEnergy())
526 throw std::runtime_error(
527 "secant quadratic prior mean requires a finite oracle "
528 "energy at the reference geometry");
530 secant.referencePosition(), secant.referenceGradient(),
531 secant.hessian(), secant.referenceEnergy());
532 prior_secant_pairs = secant.pairs();
533 secant_prior_moved = true;
534 }
535 if (!session.hyperparametersNeedRefit() && secant_prior_moved) {
537 has_conditioned_gp = true;
538 gp_stepper.forget();
539 }
540 if (session.hyperparametersNeedRefit()) {
542 const Eigen::Index current_rows = session.training_obs.R.rows();
543 const bool reinit_seeds =
544 !has_fitted_gp ||
545 (seeded_row_count < 3 && current_rows > seeded_row_count);
546 if (session.refitGP(reinit_seeds)) {
547 ++hyperparameter_refits;
548 has_fitted_gp = true;
549 if (reinit_seeds) {
550 seeded_row_count = std::min<Eigen::Index>(
551 3, std::max(seeded_row_count, current_rows));
552 }
553 }
554 has_conditioned_gp = true;
555 gp_stepper.forget();
556 }
557
558 // Compare the posterior Hessian action with the latest true-gradient
559 // secant. A disagreement buys exactly one forward force probe along
560 // that visited direction; the next outer conditions the posterior on
561 // the resulting row.
562 if (config.secant.consistency_check && secant.available() &&
563 secant.pairs() > checked_secant_pairs) {
564 const Eigen::VectorXd direction =
565 secant.lastDirection().normalized();
566 Coord at_reference(1, d);
567 at_reference.row(0) = secant.referencePosition().transpose();
568 Eigen::VectorXd posterior_action;
570 at_reference, direction, posterior_action)) {
571 throw std::runtime_error(
572 "secant consistency requested but GP Hessian action "
573 "is unavailable");
574 }
575 const SecantConsistency consistency = secant.consistency(
576 posterior_action, config.secant.consistency_relative_tolerance);
577 if (!consistency.available)
578 throw std::runtime_error(
579 "secant consistency requested but comparison is invalid");
580 result.last_secant_relative_error = consistency.relative_error;
581 checked_secant_pairs = secant.pairs();
582 if (!consistency.trusted &&
583 result.finite_difference_hvp_calls == 0 && budget_allows()) {
584 if (!(config.secant.finite_difference_step > 0.0) ||
585 !std::isfinite(config.secant.finite_difference_step))
586 throw std::invalid_argument(
587 "secant finite-difference step must be positive");
588 const Eigen::VectorXd probe =
589 secant.referencePosition() +
591 consistency.direction;
592 const double variance = energyVarianceAt(session.gp, probe);
593 const double probe_distance =
594 minTrainingAtomDistance(session.training_obs, probe);
595 const bool probe_within_trust =
596 config.trust_radius > 0.0 &&
597 std::isfinite(config.trust_radius) &&
598 probe_distance < config.trust_radius;
599 if (allow_call(policy::OracleRole::TrustExit, probe, variance,
600 probe_distance, probe_within_trust, false)) {
601 auto [probe_energy, probe_gradient] = measure(probe);
602 if (!std::isfinite(probe_energy) ||
603 probe_gradient.size() != d ||
604 !probe_gradient.allFinite())
605 break;
606 raw_oracle_obs.push_back(
607 {probe, probe_energy, probe_gradient});
608 admit(probe, probe_energy, probe_gradient, true);
609 retain_admitted();
610 result.energy_trajectory.push_back(probe_energy);
612 gp_stepper.forget();
613 if (probe_energy <= best_observed_energy) {
614 best_observed_energy = probe_energy;
615 best_observed_x = probe;
616 best_observed_g = probe_gradient;
617 x_curr = probe;
618 } else {
619 x_curr = best_observed_x;
620 }
621 if (probe_gradient.norm() < config.conv_tol) {
622 result.converged = true;
623 result.x_final = probe;
624 result.e_final = probe_energy;
625 result.g_final = probe_gradient;
626 break;
627 }
628 continue;
629 }
630 }
631 }
632
633 const double trust_boundary_tol =
634 1e-9 * std::max(1.0, config.trust_radius);
635 const int max_inner_steps = config.max_inner_steps;
636 Eigen::VectorXd x_inner = x_curr;
637 bool surrogate_converged = false;
638 bool left_trust_region = false;
639 bool inner_stopped = false;
640 bool retried_overshoot = false;
641 double exit_min_dist = 0.0;
642
643 for (int inner = 0; inner < max_inner_steps; ++inner) {
644 Observation query;
645 query.R.resize(1, d);
646 query.R.row(0) = x_inner.transpose();
647 session.gp.calculatePotentialDispatched(query);
648 const double e_curr = query.E(0, 0);
649 Eigen::VectorXd g_pred = query.G.row(0).transpose();
650 double g_norm = g_pred.norm();
651 if (!std::isfinite(e_curr) || !g_pred.allFinite() ||
652 !std::isfinite(g_norm)) {
653 inner_stopped = true;
654 break;
655 }
656
657 // The gradient the step is taken from belongs to the surrogate
658 // unless a held exact evaluation replaces it below. The stepper
659 // drops its curvature history when this changes between steps.
660 RgminStep::Objective step_objective =
662
663 // The surrogate gradient only proposes a stop. Convergence,
664 // x_final, e_final and g_final must come from an actual oracle
665 // evaluation at that exact point; a measured gradient above the
666 // tolerance becomes the step direction.
667 if (g_norm < config.conv_tol) {
668 if (const RawOracleObservation* held =
669 find_exact_raw_observation(x_inner)) {
670 if (held->gradient.norm() < config.conv_tol) {
671 result.converged = true;
672 result.x_final = held->x;
673 result.e_final = held->energy;
674 result.g_final = held->gradient;
675 inner_stopped = true;
676 break;
677 }
678 gp_stepper.forget();
679 step_objective = RgminStep::Objective::Exact;
680 g_pred = held->gradient;
681 g_norm = g_pred.norm();
682 } else {
683 surrogate_converged = true;
684 break;
685 }
686 }
687
688 Eigen::VectorXd x_trial = x_inner;
689 bool secant_step = false;
690 if (config.secant.seed_curvature && secant.available()) {
691 if (newton_factor_pairs != secant.pairs()) {
692 newton_factor = secantNewtonFactor(secant);
693 newton_factor_pairs = secant.pairs();
694 }
695 SecantSeedStatus status = newton_factor.status;
696 Eigen::VectorXd seed_step;
698 seed_step = newton_factor.factor.solve(-g_pred);
699 const double reach = maxAtomDisplacement(seed_step);
700 if (!seed_step.allFinite() || !std::isfinite(reach))
702 else if (reach > seed_bound)
703 seed_step *= seed_bound / reach;
704 }
706 x_trial += seed_step;
707 secant_step = true;
709 } else {
710 if (config.verbose &&
711 (result.secant_curvature_seed_refusals == 0 ||
713 std::cout << "[secant-seed] minimization keeps the "
714 "surrogate step: "
715 << secantSeedStatusName(status) << "\n";
717 }
719 }
720
721 // An empty curvature memory makes the step steepest descent.
722 // Clipping an unscaled -g to max_move lands on the default
723 // trust radius, so the first inner step leaves the region and
724 // spends the oracle call max_inner_steps was meant to withhold.
725 // The same cap the rgmin stepper uses on an empty memory keeps
726 // that step inside.
727 double empty_scale = 1.0;
728 const double g_atom_max = maxAtomDisplacement(g_pred);
729 const double probe_cap =
730 session.training_obs.R.rows() == 1
731 ? (0.5 * config.max_move)
732 : (0.25 * std::min(config.max_move, config.trust_radius));
733 if (probe_cap > 0.0 && std::isfinite(probe_cap) &&
734 g_atom_max > probe_cap) {
735 empty_scale = probe_cap / g_atom_max;
736 }
737 if (!secant_step && !gp_stepper.step(x_trial, g_pred, 0.0,
738 empty_scale, step_objective)) {
739 inner_stopped = true;
740 break;
741 }
742 Eigen::VectorXd step = x_trial - x_inner;
743 if (!step.allFinite()) {
744 inner_stopped = true;
745 break;
746 }
747 clipAtomMaxMove(step, config.max_move);
748 Eigen::VectorXd x_next = x_inner + step;
749 ++result.total_iterations;
750
751 const bool trust_active =
752 config.trust_radius > 0.0 && std::isfinite(config.trust_radius);
753 bool crossed_trust_boundary = false;
754 if (trust_active) {
755 // The step is trusted only while every point of it lies in
756 // some training row's ball. The end point alone is not enough:
757 // a step can leave one ball, cross the gap and end inside
758 // another. The first uncovered point is where it exits.
759 const double covered = detail::trustCoveredFraction(
760 session.training_obs.R, x_inner, x_next,
761 config.trust_radius);
762 const double raw_min_dist =
763 minTrainingAtomDistance(session.training_obs, x_next);
764 const bool leaves_union = covered < 1.0;
765 crossed_trust_boundary =
766 leaves_union ||
767 raw_min_dist >= config.trust_radius - trust_boundary_tol;
768 if (leaves_union) {
769 x_next = x_inner + covered * (x_next - x_inner);
770 step = x_next - x_inner;
771 }
772 }
773
774 if (crossed_trust_boundary) {
775 if (!retried_overshoot && std::isfinite(e_curr) &&
776 g_pred.dot(step) < 0.0) {
777 Observation probe;
778 probe.R.resize(1, d);
779 probe.R.row(0) = x_next.transpose();
780 session.gp.calculatePotentialDispatched(probe);
781 const double e_next = probe.E(0, 0);
782 const Eigen::VectorXd g_next = probe.G.row(0).transpose();
783 if (std::isfinite(e_next) && g_next.allFinite() &&
784 e_next > e_curr && g_next.dot(step) > 0.0) {
785 gp_stepper.forget();
786 const double dg0 = -g_pred.dot(step);
787 const double dg1 = g_next.dot(step);
788 const double alpha =
789 std::clamp(dg0 / (dg0 + dg1), 0.1, 0.5);
790 x_inner += alpha * step;
791 retried_overshoot = true;
792 continue;
793 }
794 }
795 x_inner = x_next;
796 left_trust_region = true;
797 exit_min_dist =
798 minTrainingAtomDistance(session.training_obs, x_inner);
799 break;
800 }
801
802 x_inner = x_next;
803 if (step.norm() <= 1e-14) {
804 break;
805 }
806 }
807
808 if (result.converged || inner_stopped) {
809 break;
810 }
811
812 if (surrogate_converged) {
813 if (find_exact_raw_observation(x_inner) != nullptr) {
814 break;
815 }
816 const double min_dist =
817 minTrainingAtomDistance(session.training_obs, x_inner);
818 const double variance =
819 policy == nullptr ? std::numeric_limits<double>::quiet_NaN()
820 : energyVarianceAt(session.gp, x_inner);
821 if (!allow_call(policy::OracleRole::ConvergenceCheck, x_inner,
822 variance, min_dist, true, true)) {
823 break;
824 }
825 auto [e_true, g_true] = measure(x_inner);
826 if (!std::isfinite(e_true) || g_true.size() != d ||
827 !g_true.allFinite()) {
828 break;
829 }
830 raw_oracle_obs.push_back({x_inner, e_true, g_true});
831 admit(x_inner, e_true, g_true, true);
832 retain_admitted();
833 result.energy_trajectory.push_back(e_true);
834 if (e_true <= best_observed_energy) {
835 best_observed_energy = e_true;
836 x_curr = x_inner;
837 best_observed_x = x_inner;
838 best_observed_g = g_true;
839 } else {
840 gp_stepper.forget();
841 x_curr = best_observed_x;
842 }
843 if (g_true.norm() < config.conv_tol) {
844 result.converged = true;
845 result.x_final = x_inner;
846 result.e_final = e_true;
847 result.g_final = g_true;
848 break;
849 }
850 continue;
851 }
852
853 if (!left_trust_region) {
854 if (neb::detail::positionsCoincide(x_inner, x_curr)) {
855 break;
856 }
857 x_curr = x_inner;
858 continue;
859 }
860
861 if (const RawOracleObservation* held =
862 find_exact_raw_observation(x_inner)) {
863 // A measured row that retention or the size cap removed is
864 // admitted again from its record. It is not a new oracle result,
865 // so the trajectory and the best observation do not change.
866 if (neb::detail::findPositionRow(session.training_obs, x_inner) >=
867 0) {
868 break;
869 }
870 const RawOracleObservation record = *held;
871 admit(record.x, record.energy, record.gradient, true);
872 retain_admitted();
873 if (neb::detail::findPositionRow(session.training_obs, x_inner) <
874 0) {
875 break;
876 }
877 if (record.energy <= best_observed_energy) {
878 x_curr = x_inner;
879 } else {
880 gp_stepper.forget();
881 x_curr = best_observed_x;
882 }
883 continue;
884 }
885 if (!budget_allows()) break;
886 const double variance = policy == nullptr
887 ? std::numeric_limits<double>::quiet_NaN()
888 : energyVarianceAt(session.gp, x_inner);
889 if (!allow_call(policy::OracleRole::TrustExit, x_inner, variance,
890 exit_min_dist, false, false)) {
891 break;
892 }
893
894 auto [e_new, g_new] = measure(x_inner);
895 if (!std::isfinite(e_new) || g_new.size() != d || !g_new.allFinite()) {
896 break;
897 }
898 raw_oracle_obs.push_back({x_inner, e_new, g_new});
899 admit(x_inner, e_new, g_new, true);
900 retain_admitted();
901 result.energy_trajectory.push_back(e_new);
902
903 if (e_new <= best_observed_energy) {
904 best_observed_energy = e_new;
905 x_curr = x_inner;
906 best_observed_x = x_inner;
907 best_observed_g = g_new;
908 } else {
909 gp_stepper.forget();
910 x_curr = best_observed_x;
911 }
912
913 if (g_new.norm() < config.conv_tol) {
914 result.converged = true;
915 result.x_final = x_inner;
916 result.e_final = e_new;
917 result.g_final = g_new;
918 break;
919 }
920 }
921
922 if (!result.converged) {
923 result.x_final = best_observed_x;
924 result.e_final = best_observed_energy;
925 result.g_final = best_observed_g;
926 }
927
928 return result;
929}
930
931MinimizationResult gp_minimize(OracleFn oracle, const Eigen::VectorXd& x_init,
932 const AtomsConfiguration& atoms_config,
933 const MinimizationConfig& config)
934{
935 return gp_minimize(std::move(oracle), x_init, atoms_config, config,
936 nullptr);
937}
938
939} // namespace optim
940} // namespace gpr
@ x
Definition Enums.h:28
GP-accelerated geometry minimization.
ActiveLearningSession: shared GP + training data across GP-NEB and GP-Dimer phases.
Exact coverage of a straight step by the union of trust balls.
void setObjectiveStationaritySkipAuto(bool use) noexcept
void setOptimizationSubsetHistory(int rows) noexcept
void setSecantQuadraticPrior(const Eigen::VectorXd &position, const Eigen::VectorXd &gradient, const Eigen::MatrixXd &hessian, double reference_energy)
bool calculateMeanHessianVectorDispatched(const Coord &R, const Eigen::VectorXd &direction, Eigen::VectorXd &hessian_vector)
void setHssvdBackend(bool enabled) noexcept
void calculatePotentialDispatched(Observation &image1)
Definition Predict.cpp:982
bool step(Eigen::VectorXd &x, const Eigen::VectorXd &gradient, double max_move, double empty_scale, Objective objective=Objective::Unspecified)
Definition RgminStep.h:122
bool available() const noexcept
bool hasReferenceEnergy() const noexcept
SecantConsistency consistency(const Eigen::VectorXd &posterior_action, double relative_tolerance) const
const Eigen::VectorXd & referenceGradient() const noexcept
const Eigen::VectorXd & lastDirection() const noexcept
const Eigen::MatrixXd & hessian() const noexcept
const Eigen::VectorXd & referencePosition() const noexcept
double referenceEnergy() const
bool observe(const Eigen::VectorXd &position, const Eigen::VectorXd &gradient)
std::size_t pairs() const noexcept
int status
std::pair< int, int > abi_version()
Definition gpridge.hpp:351
TrainedGpState observationState(const Observation &observations)
A state that carries observations and no pair kernel.
Definition GpState.cpp:556
int seedSession(neb::ActiveLearningSession &session, const TrainedGpState &state, bool require_identity, Eigen::Index expected_cols)
Definition GpState.cpp:638
MinimizationResult gp_minimize(OracleFn oracle, const Eigen::VectorXd &x_init, const AtomsConfiguration &atoms_config, const MinimizationConfig &config, const policy::TrainingPolicy *policy, const Observation *seed, const io::TrainedGpState *gp_state)
GP-accelerated geometry minimization with a training policy.
std::function< std::pair< double, Eigen::VectorXd >( const Eigen::VectorXd &positions)> OracleFn
Oracle function: positions -> (energy, gradient).
SecantNewtonFactor secantNewtonFactor(const SecantHessian &secant)
MinimizationLayoutStamp libraryMinimizationLayout()
What libgpridge was built with. Defined in the library, not inline.
double maxAtomDisplacement(const Eigen::VectorXd &delta)
const char * secantSeedStatusName(SecantSeedStatus status) noexcept
MinimizationLayoutStamp compiledMinimizationLayout() noexcept
bool admitsFirstCandidate(const std::vector< int > &indices)
bool consensusShouldCallOracle(const TrainingPolicy &policy, const SearchState &state)
std::vector< int > consensusSelectTrainingPoints(const TrainingPolicy &policy, const std::vector< CandidatePoint > &candidates, const std::vector< Eigen::VectorXd > &current_set)
Gaussian-process regression, kernels, priors, and the searches that run on the surrogate.
Definition Macros.h:16
FieldMatrixd Coord
Definition Macros.h:35
Stores configurations of all atoms in the system.
Definition Structures.h:832
Structure of the input parameters. All input parameters are pairs of string names and values.
Definition Structures.h:370
KeyValuePair< double > prior_s2
Definition Structures.h:650
KeyValuePair< int > max_iter
Definition Structures.h:674
KeyValuePair< std::string > optimization_alg
Definition Structures.h:614
KeyValuePair< int > fps_history
Definition Structures.h:665
KeyValuePair< double > prior_nu
Definition Structures.h:649
KeyValuePair< int > report_level
Definition Structures.h:673
KeyValuePair< double > jitter_sigma2
Definition Structures.h:613
KeyValuePair< double > constSigma2
Definition Structures.h:618
KeyValuePair< double > tolerance_func
Definition Structures.h:675
KeyValuePair< double > tolerance_sol
Definition Structures.h:676
KeyValuePair< double > prior_mu
Definition Structures.h:648
KeyValuePair< double > sigma2
Definition Structures.h:616
KeyValuePair< double > magnSigma2
Definition Structures.h:617
KeyValuePair< double > gp_sigma2
Definition Structures.h:612
Observation data: energy, gradient and positions.
FieldMatrixd E
Observation observations
Definition GpState.h:22
void noteExternalHyperparameterFit() noexcept
Definition Session.h:1325
std::function< void(gpr::InputParameters &, gpr::AtomsConfiguration &)> gp_setup
Definition Session.h:1141
bool hyperparametersNeedRefit() const noexcept
Definition Session.h:3292
gpr::Observation training_obs
Definition Session.h:246
bool retainTrainingRowsForPolicy(const policy::TrainingPolicy &policy)
Definition Session.h:1777
bool refitGP(bool reinit_seeds)
Definition Session.h:3111
void publishPolicyProgress(int iteration, int oracle_calls, int refits, int training_size) noexcept
Definition Session.h:3281
gpr::GaussianProcessRegression gp
Definition Session.h:471
void appendObservation(const Eigen::VectorXd &positions, double energy, const Eigen::VectorXd &gradient, ObservationRetention retention=ObservationRetention::RecordAcquisition, optim::SecantAccounting secant_accounting=optim::SecantAccounting::Count)
Definition Session.h:1574
Configuration for GP-guided minimization.
Definition GPMinimizer.h:56
SecantHessianConfig secant
True-force secant curvature features. Every member is off by default.
Definition GPMinimizer.h:82
Byte counts of the minimization structs this translation unit compiled.
Result of GP-guided minimization.
Definition GPMinimizer.h:96
int prior_observations
Rows supplied by the caller. They are not included in oracle_calls.
SecantSeedStatus last_secant_seed_status
std::vector< double > energy_trajectory
bool enabled() const noexcept
Eigen::LLT< Eigen::MatrixXd > factor
Read-only view of one decision. Pointers are valid only for the call.
const GaussianProcessRegression * gp