5#ifndef GPR_NEB_RG_LBFGS_ENGINE_H_
6#define GPR_NEB_RG_LBFGS_ENGINE_H_
8#if defined(__has_include)
9#if !__has_include(<rgmin.h>)
10#error "gpridge requires rgmin include/rgmin.h"
26#ifdef GPR_RG_LBFGS_ENGINE_TEST
37#ifdef GPR_RG_LBFGS_ENGINE_TEST
40struct RgLbfgsEngineTestAccess {
41 static void poisonNextSearchGrad()
45 static bool takePoisonSearchGrad()
47 const bool set = poison();
51 static void recordPushedPair(
const Eigen::VectorXd& s,
52 const Eigen::VectorXd&
y)
58 static void clearPushedPair()
64 static bool havePushedPair()
68 static const Eigen::VectorXd& lastPushedS()
72 static const Eigen::VectorXd& lastPushedY()
80 static bool flag =
false;
83 static bool& havePair()
85 static bool flag =
false;
88 static Eigen::VectorXd& lastS()
90 static Eigen::VectorXd v;
93 static Eigen::VectorXd& lastY()
95 static Eigen::VectorXd v;
138class RgLbfgsEngine final :
public BandRelaxationEngine {
140 explicit RgLbfgsEngine(std::size_t memory = 20)
141 : memory_(memory == 0 ? 20 : memory)
143 options_.memory =
static_cast<int>(memory_);
145 explicit RgLbfgsEngine(GlobalLBFGSOptions options)
147 memory_(options.memory > 0 ? static_cast<std::size_t>(options.memory)
151 ~RgLbfgsEngine()
override
156 RgLbfgsEngine(
const RgLbfgsEngine&) =
delete;
157 RgLbfgsEngine& operator=(
const RgLbfgsEngine&) =
delete;
159 void reset()
override
165 curvature_cap_.reset();
166 if (solver_ !=
nullptr) rgmin_solver_forget(solver_);
170 GlobalLBFGSObjective& objective,
double max_move,
171 std::optional<double> initial_inverse_curvature = std::nullopt)
override
173 emitMaxMoveTrustRegionWarning(max_move, max_move_warned_);
174 const double configured_move = max_move;
178 const std::uint64_t generation = reset_generation_;
179 if (!objective.refresh(
false))
return false;
180 const Eigen::VectorXd pos = objective.positions();
181 if (pos.size() <= 0)
return false;
182 const Eigen::VectorXd force = objective.force();
183 if (force.size() != pos.size() || !pos.allFinite() ||
184 !force.allFinite()) {
187 ensure(
static_cast<std::size_t
>(pos.size()));
188 if (solver_ ==
nullptr)
return false;
190 const bool use_measured_curvature =
191 iteration_ == 0 && initial_inverse_curvature.has_value() &&
192 std::isfinite(*initial_inverse_curvature) &&
193 *initial_inverse_curvature > 0.0;
194 double host_h0 = use_measured_curvature ? *initial_inverse_curvature
195 : fallbackInverseCurvature();
197 const Eigen::VectorXd grad = -force;
198 const std::size_t n =
static_cast<std::size_t
>(pos.size());
199 bool pushed_pair =
false;
200 bool curvature_rejected =
false;
201 Eigen::VectorXd dir(pos.size());
202 if (have_previous_ && previous_x_.size() == pos.size() &&
203 previous_g_.size() == grad.size()) {
204 Eigen::VectorXd s = objective.difference(pos, previous_x_);
205 Eigen::VectorXd
y = grad - previous_g_;
206 if (s.size() == pos.size() &&
y.size() == pos.size()) {
207 applyCurvatureExclusion(s,
y);
208 double step_kappa = 0.0;
209 const double pair_ss = s.squaredNorm();
210 const double pair_sy = s.dot(
y);
211 if (pair_ss > 0.0 && pair_sy > 0.0 && std::isfinite(pair_sy)) {
212 step_kappa = pair_sy / pair_ss;
214 max_move = curvature_cap_.resolve(configured_move, step_kappa,
215 objective.maxMotion(force),
216 options_.newton_agreement);
223 if (hostCurvatureRejected(s,
y)) {
224 if (solver_ !=
nullptr) rgmin_solver_forget(solver_);
226 dir = objective.limitMotion(1000.0 * force, max_move);
227 curvature_rejected =
true;
228 }
else if (s.allFinite() &&
y.allFinite()) {
229 const double sy = s.dot(
y);
233 if (rgRhoDefined(sy)) {
234 (void)rgmin_solver_push_pair(solver_, s.data(),
236 recordHostPair(s,
y);
237#ifdef GPR_RG_LBFGS_ENGINE_TEST
238 RgLbfgsEngineTestAccess::recordPushedPair(s,
y);
241 if (options_.auto_scale) {
250 if (!curvature_rejected) {
251 bool host_fallback =
false;
252 if (iteration_ == 0 && !use_measured_curvature &&
253 options_.auto_scale && options_.finite_difference > 0.0) {
254 host_fallback = !probeFiniteDifferenceH0(
255 objective, max_move, pos, force, dir, host_h0);
257 if (!host_fallback) {
258 const std::vector<std::size_t> sketch_idx = fillSketchIndices();
259 const bool sketched = !sketch_idx.empty();
261 if (solver_ !=
nullptr) rgmin_solver_forget(solver_);
262 loadRgPairs(sketch_idx);
264#ifdef GPR_RG_LBFGS_ENGINE_TEST
265 const double* rg_grad = grad.data();
266 Eigen::VectorXd poisoned_grad;
267 if (RgLbfgsEngineTestAccess::takePoisonSearchGrad()) {
268 poisoned_grad = Eigen::VectorXd::Constant(
269 pos.size(), std::numeric_limits<double>::quiet_NaN());
270 rg_grad = poisoned_grad.data();
272 const rgmin_status_t st = rgmin_solver_search_direction(
273 solver_, rg_grad, dir.data(), n);
275 const rgmin_status_t st = rgmin_solver_search_direction(
276 solver_, grad.data(), dir.data(), n);
279 if (solver_ !=
nullptr) rgmin_solver_forget(solver_);
282 if (st != RGMIN_SUCCESS || !dir.allFinite()) {
283 rejectPushedRgPair(pushed_pair);
291 if (use_measured_curvature ||
292 (iteration_ == 0 && options_.auto_scale &&
293 options_.finite_difference > 0.0)) {
296 const Eigen::VectorXd host_proposed =
297 hostProposed(force, host_h0, sketch_idx);
298 if (!applyHostResets(objective, max_move, force, dir,
299 host_proposed, host_h0)) {
300 dir = clipAtomMaxmove(dir, max_move);
304 if (!dir.allFinite()) {
305 rejectPushedRgPair(pushed_pair);
309 const Eigen::VectorXd next = objective.stepPositions(pos, dir);
310 if (!next.allFinite() || next.size() != pos.size()) {
311 rejectPushedRgPair(pushed_pair);
314 objective.setPositions(next);
315 if (!objective.refresh(
false)) {
316 restoreThroughStepPositions(objective, pos);
317 (void)objective.refresh(
false);
318 rejectPushedRgPair(pushed_pair);
324 if (reset_generation_ != generation)
return true;
325 curvature_cap_.observe(objective.maxMotion(dir), configured_move,
326 objective.maxMotion(force));
329 have_previous_ =
true;
334 void rebuildSketchedH0(
335 const std::function<Eigen::VectorXd(
const Eigen::VectorXd&)>&,
339 void setCurvatureExclusion(Eigen::Index offset,
340 Eigen::Index len)
noexcept override
342 curvature_exclude_offset_ = offset;
343 curvature_exclude_len_ = len;
345 [[nodiscard]]
int iteration()
const override
349 [[nodiscard]]
int historySize()
const override
351 return static_cast<int>(s_hist_.size());
353 [[nodiscard]]
double lastCurvatureDot()
const override
355 return s_hist_.empty() ? 0.0 : s_hist_.back().dot(y_hist_.back());
357 [[nodiscard]]
double lastCurvatureScale()
const override
359 if (s_hist_.empty())
return 0.0;
360 const double ss = s_hist_.back().squaredNorm();
361 if (!(ss > 0.0) || !std::isfinite(ss))
return 0.0;
362 const double scale = lastCurvatureDot() / ss;
363 return std::isfinite(scale) && scale > 0.0 ? scale : 0.0;
370 static Eigen::VectorXd clipAtomMaxmove(
const Eigen::VectorXd& step,
373 if (!(cap > 0.0) || !std::isfinite(cap))
return step;
374 const Eigen::Index n = step.size();
375 double max_atom = 0.0;
378 max_atom = std::max(max_atom, step.segment<3>(i).norm());
381 if (i < n) max_atom = std::max(max_atom, step.tail(n - i).norm());
382 if (max_atom > cap && max_atom > 0.0)
return step * (cap / max_atom);
386 [[nodiscard]]
double fallbackInverseCurvature()
const
388 const double H0 = options_.inverse_curvature;
389 return (H0 > 0.0 && std::isfinite(H0)) ? H0 : 0.01;
397 bool probeFiniteDifferenceH0(GlobalLBFGSObjective& objective,
399 const Eigen::VectorXd& positions,
400 const Eigen::VectorXd& force,
401 Eigen::VectorXd& dir,
double& host_h0)
403 const double force_norm = force.norm();
404 if (!(force_norm > 0.0) || !std::isfinite(force_norm))
return true;
405 const Eigen::VectorXd unit = force / force_norm;
406 const Eigen::VectorXd probed = objective.stepPositions(
407 positions, options_.finite_difference * unit);
408 if (!probed.allFinite() || probed.size() != positions.size()) {
409 dir = objective.limitMotion(host_h0 * force, max_move);
412 objective.setPositions(probed);
413 if (!objective.refresh(
true)) {
414 objective.setPositions(positions);
415 (void)objective.refresh(
false);
416 dir = objective.limitMotion(host_h0 * force, max_move);
419 const Eigen::VectorXd gradient_delta = -objective.force() + force;
420 const double C = gradient_delta.dot(unit) / options_.finite_difference;
421 objective.setPositions(positions);
422 if (!objective.refresh(
false)) {
423 dir = objective.limitMotion(host_h0 * force, max_move);
426 host_h0 = (std::abs(C) < 1e-300) ? -1.0 : 1.0 / C;
427 if (!(host_h0 > 0.0) || !std::isfinite(host_h0)) {
428 if (solver_ !=
nullptr) rgmin_solver_forget(solver_);
430 dir = objective.limitMotion(1000.0 * force, max_move);
436 static bool obtuseToForce(
const Eigen::VectorXd& proposed,
437 const Eigen::VectorXd& force)
439 const double proposed_norm = proposed.norm();
440 const double force_norm = force.norm();
441 if (!(proposed_norm > 0.0) || !(force_norm > 0.0))
return false;
442 double cos_angle = proposed.dot(force) / (proposed_norm * force_norm);
443 cos_angle = std::clamp(cos_angle, -1.0, 1.0);
444 constexpr double pi = 3.14159265358979323846;
445 return std::acos(cos_angle) * 180.0 / pi > 90.0;
448 static bool hostCurvatureRejected(
const Eigen::VectorXd& s,
449 const Eigen::VectorXd&
y)
451 const double sy = s.dot(
y);
452 const double y_norm2 =
y.squaredNorm();
453 return !(sy > 0.0) || !std::isfinite(sy) || !(y_norm2 > 0.0) ||
454 !std::isfinite(y_norm2);
458 static bool rgRhoDefined(
double sy)
460 return std::isfinite(sy) && std::abs(sy) >= 1e-30;
464 void applyCurvatureExclusion(Eigen::VectorXd& s, Eigen::VectorXd&
y)
const
467 s,
y, curvature_exclude_offset_, curvature_exclude_len_);
470 void recordHostPair(
const Eigen::VectorXd& s,
const Eigen::VectorXd&
y)
472 const double sy = s.dot(
y);
477 if (!rgRhoDefined(sy))
return;
478 s_hist_.push_back(s);
479 y_hist_.push_back(
y);
480 rho_hist_.push_back(1.0 / sy);
481 const int memory = std::max(
482 1, std::min(options_.memory,
483 static_cast<int>(std::max<Eigen::Index>(1, s.size()))));
484 while (
static_cast<int>(s_hist_.size()) > memory) {
487 rho_hist_.pop_front();
493 [[nodiscard]] Eigen::VectorXd hostProposed(
494 const Eigen::VectorXd& force,
double H0,
495 const std::vector<std::size_t>& sketch_idx)
const
497 if (sketch_idx.empty()) {
499 s_hist_, y_hist_, rho_hist_, force, H0);
502 std::deque<Eigen::VectorXd> s_sk, y_sk;
503 std::deque<double> rho_sk;
504 for (
const std::size_t i: sketch_idx) {
505 s_sk.push_back(s_hist_[i]);
506 y_sk.push_back(y_hist_[i]);
507 rho_sk.push_back(rho_hist_[i]);
509 const Eigen::VectorXd
z =
517 [[nodiscard]] std::vector<std::size_t> fillSketchIndices()
519 const int k_sketch = options_.sketch_history;
520 const std::size_t m = s_hist_.size();
521 if (k_sketch <= 0 || k_sketch >=
static_cast<int>(m))
return {};
522 if (sketch_rng_state_ == 0) {
524 options_.sketch_seed != 0 ? options_.sketch_seed : 1ULL;
526 std::vector<std::size_t> idx(m);
527 std::iota(idx.begin(), idx.end(), std::size_t{0});
528 for (std::size_t i = 0; i < static_cast<std::size_t>(k_sketch); ++i) {
529 sketch_rng_state_ += 0x9E3779B97F4A7C15ULL;
530 uint64_t z64 = sketch_rng_state_;
531 z64 = (z64 ^ (z64 >> 30)) * 0xBF58476D1CE4E5B9ULL;
532 z64 = (z64 ^ (z64 >> 27)) * 0x94D049BB133111EBULL;
533 z64 = z64 ^ (z64 >> 31);
534 const std::size_t pick = i + (z64 % (m - i));
535 std::swap(idx[i], idx[pick]);
537 std::sort(idx.begin(), idx.begin() + k_sketch);
538 idx.resize(
static_cast<std::size_t
>(k_sketch));
544 void loadRgPairs(
const std::vector<std::size_t>& idx)
546 if (solver_ ==
nullptr)
return;
547 const std::size_t n = dim_;
549 for (std::size_t i = 0; i < s_hist_.size(); ++i) {
550 (void)rgmin_solver_push_pair(solver_, s_hist_[i].data(),
551 y_hist_[i].data(), n);
555 for (
const std::size_t i: idx) {
556 (void)rgmin_solver_push_pair(solver_, s_hist_[i].data(),
557 y_hist_[i].data(), n);
565 bool applyHostResets(GlobalLBFGSObjective& objective,
double max_move,
566 const Eigen::VectorXd& force, Eigen::VectorXd& dir,
567 const Eigen::VectorXd& host_proposed,
double H0)
569 const double proposed_motion = objective.maxMotion(dir);
571 if (options_.distance_reset && max_move > 0.0 &&
572 std::isfinite(max_move) && std::isfinite(proposed_motion) &&
573 proposed_motion >= max_move) {
576 if (!reset && options_.angle_reset &&
577 (obtuseToForce(dir, force) ||
578 obtuseToForce(host_proposed, force))) {
581 if (!reset)
return false;
582 if (solver_ !=
nullptr) rgmin_solver_forget(solver_);
584 dir = objective.limitMotion(H0 * force, max_move);
590 have_previous_ =
false;
591 previous_x_.resize(0);
592 previous_g_.resize(0);
599 static void restoreThroughStepPositions(GlobalLBFGSObjective& objective,
600 const Eigen::VectorXd& origin)
602 const Eigen::VectorXd current = objective.positions();
603 if (current.size() != origin.size() || !current.allFinite() ||
604 !origin.allFinite()) {
607 const Eigen::VectorXd back = objective.difference(origin, current);
608 const Eigen::VectorXd restored = objective.stepPositions(current, back);
609 if (!restored.allFinite() || restored.size() != origin.size()) {
612 objective.setPositions(restored);
619 void rejectPushedRgPair(
bool pushed_pair)
622 if (solver_ !=
nullptr) rgmin_solver_forget(solver_);
628 void clearHostHistory()
637 if (solver_ !=
nullptr) {
638 rgmin_solver_free(solver_);
646 void ensure(std::size_t dim)
648 if (solver_ !=
nullptr && dim_ == dim)
return;
650 rgmin_control_t ctrl{};
654 ctrl.memory = memory_ == 0 ? 20 : memory_;
657 solver_ = rgmin_solver_create(RGMIN_LBFGS, &ctrl, dim);
661 rgmin_solver_set_atom_maxmove(solver_, 0.0);
665 rgmin_solver_t* solver_ =
nullptr;
666 std::size_t dim_ = 0;
667 GlobalLBFGSOptions options_{};
668 std::size_t memory_ = 20;
670 std::uint64_t reset_generation_ = 0;
671 Eigen::VectorXd previous_x_;
672 Eigen::VectorXd previous_g_;
673 bool have_previous_ =
false;
674 bool max_move_warned_ =
false;
675 CurvatureStepCap curvature_cap_;
676 std::deque<Eigen::VectorXd> s_hist_;
677 std::deque<Eigen::VectorXd> y_hist_;
678 std::deque<double> rho_hist_;
679 uint64_t sketch_rng_state_ = 0;
680 Eigen::Index curvature_exclude_offset_ = -1;
681 Eigen::Index curvature_exclude_len_ = 0;
GP-accelerated NEB: AIE and OIE variants.
void set(FieldMatrixd &mat, Index_t i, const Eigen::Vector3d &vec)
The nudged elastic band: path, GP-NEB driver, configuration and result, acquisition,...
double barzilaiBorweinInverseScale(const Eigen::VectorXd &s, const Eigen::VectorXd &y, double fallback)
Scalar BB2 inverse-curvature seed for L-BFGS H0.
void excludeNonPositiveCurvatureBlock(Eigen::VectorXd &s, Eigen::VectorXd &y, Eigen::Index offset, Eigen::Index length)
Eigen::VectorXd twoLoopRecursion(const std::deque< Eigen::VectorXd > &s_hist, const std::deque< Eigen::VectorXd > &y_hist, const std::deque< double > &rho_hist, const Eigen::VectorXd &force, double H0)
Nocedal two-loop recursion (the LBFGS kernel).
void requireCompatibleLibrary()
Gaussian-process regression, kernels, priors, and the searches that run on the surrogate.