Loading...
Searching...
No Matches
RgLbfgsEngine.h
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// Copyright (c) gpridge developers
3// See LICENSE for details.
4
5#ifndef GPR_NEB_RG_LBFGS_ENGINE_H_
6#define GPR_NEB_RG_LBFGS_ENGINE_H_
7
8#if defined(__has_include)
9#if !__has_include(<rgmin.h>)
10#error "gpridge requires rgmin include/rgmin.h"
11#endif
12#endif
13#include <rgmin.h>
14
15#include <Eigen/Dense>
16#include <algorithm>
17#include <cmath>
18#include <cstddef>
19#include <cstdint>
20#include <deque>
21#include <numeric>
22#include <optional>
23#include <vector>
24
25#include "../ml/RgminAbi.h"
26#ifdef GPR_RG_LBFGS_ENGINE_TEST
27#include <limits>
28#endif
29
31#include "GPNEB.h"
32
33namespace gpr {
34namespace neb {
35namespace detail {
36
37#ifdef GPR_RG_LBFGS_ENGINE_TEST
40struct RgLbfgsEngineTestAccess {
41 static void poisonNextSearchGrad()
42 {
43 poison() = true;
44 }
45 static bool takePoisonSearchGrad()
46 {
47 const bool set = poison();
48 poison() = false;
49 return set;
50 }
51 static void recordPushedPair(const Eigen::VectorXd& s,
52 const Eigen::VectorXd& y)
53 {
54 lastS() = s;
55 lastY() = y;
56 havePair() = true;
57 }
58 static void clearPushedPair()
59 {
60 lastS().resize(0);
61 lastY().resize(0);
62 havePair() = false;
63 }
64 static bool havePushedPair()
65 {
66 return havePair();
67 }
68 static const Eigen::VectorXd& lastPushedS()
69 {
70 return lastS();
71 }
72 static const Eigen::VectorXd& lastPushedY()
73 {
74 return lastY();
75 }
76
77private:
78 static bool& poison()
79 {
80 static bool flag = false;
81 return flag;
82 }
83 static bool& havePair()
84 {
85 static bool flag = false;
86 return flag;
87 }
88 static Eigen::VectorXd& lastS()
89 {
90 static Eigen::VectorXd v;
91 return v;
92 }
93 static Eigen::VectorXd& lastY()
94 {
95 static Eigen::VectorXd v;
96 return v;
97 }
98};
99#endif
100
138class RgLbfgsEngine final : public BandRelaxationEngine {
139public:
140 explicit RgLbfgsEngine(std::size_t memory = 20)
141 : memory_(memory == 0 ? 20 : memory)
142 {
143 options_.memory = static_cast<int>(memory_);
144 }
145 explicit RgLbfgsEngine(GlobalLBFGSOptions options)
146 : options_(options),
147 memory_(options.memory > 0 ? static_cast<std::size_t>(options.memory)
148 : 20)
149 {
150 }
151 ~RgLbfgsEngine() override
152 {
153 release();
154 }
155
156 RgLbfgsEngine(const RgLbfgsEngine&) = delete;
157 RgLbfgsEngine& operator=(const RgLbfgsEngine&) = delete;
158
159 void reset() override
160 {
161 ++reset_generation_;
162 iteration_ = 0;
163 clearHostPair();
164 clearHostHistory();
165 curvature_cap_.reset();
166 if (solver_ != nullptr) rgmin_solver_forget(solver_);
167 }
168
169 bool step(
170 GlobalLBFGSObjective& objective, double max_move,
171 std::optional<double> initial_inverse_curvature = std::nullopt) override
172 {
173 emitMaxMoveTrustRegionWarning(max_move, max_move_warned_);
174 const double configured_move = max_move;
175 // The host's refresh re-enters reset() when the climbing marker
176 // moves; the step commits its bookkeeping only if no reset
177 // happened meanwhile.
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()) {
185 return false;
186 }
187 ensure(static_cast<std::size_t>(pos.size()));
188 if (solver_ == nullptr) return false;
189
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();
196
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;
213 }
214 max_move = curvature_cap_.resolve(configured_move, step_kappa,
215 objective.maxMotion(force),
216 options_.newton_agreement);
217 // Host Internal L-BFGS (GPNEB.cpp getStep) drops a
218 // non-positive force secant, clears history, and takes
219 // a bounded force step. rgmin refuses sy <= 0 and
220 // would otherwise two-loop on leftover dest pairs.
221 // The shared CI block policy preserves admissible reflected
222 // curvature before the full-pair check.
223 if (hostCurvatureRejected(s, y)) {
224 if (solver_ != nullptr) rgmin_solver_forget(solver_);
225 clearHostHistory();
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);
230 // Host GlobalLBFGSOptimizer::update skips a pair
231 // when rho is undefined. dest two-loop must not
232 // ingest that pair either.
233 if (rgRhoDefined(sy)) {
234 (void)rgmin_solver_push_pair(solver_, s.data(),
235 y.data(), n);
236 recordHostPair(s, y);
237#ifdef GPR_RG_LBFGS_ENGINE_TEST
238 RgLbfgsEngineTestAccess::recordPushedPair(s, y);
239#endif
240 pushed_pair = true;
241 if (options_.auto_scale) {
243 s, y, host_h0);
244 }
245 }
246 }
247 }
248 }
249
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);
256 }
257 if (!host_fallback) {
258 const std::vector<std::size_t> sketch_idx = fillSketchIndices();
259 const bool sketched = !sketch_idx.empty();
260 if (sketched) {
261 if (solver_ != nullptr) rgmin_solver_forget(solver_);
262 loadRgPairs(sketch_idx);
263 }
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();
271 }
272 const rgmin_status_t st = rgmin_solver_search_direction(
273 solver_, rg_grad, dir.data(), n);
274#else
275 const rgmin_status_t st = rgmin_solver_search_direction(
276 solver_, grad.data(), dir.data(), n);
277#endif
278 if (sketched) {
279 if (solver_ != nullptr) rgmin_solver_forget(solver_);
280 loadRgPairs({});
281 }
282 if (st != RGMIN_SUCCESS || !dir.allFinite()) {
283 rejectPushedRgPair(pushed_pair);
284 return false;
285 }
286 // dest empty-history search_direction is d = -g = force
287 // (ctrl.istep=1.0). InternalLbfgsEngine first step is
288 // H0 * force. Scale dest dir by the host measured H0 or
289 // the auto-scale FD probe so dest production takes the
290 // same first-step scale. dest istep stays 1.0.
291 if (use_measured_curvature ||
292 (iteration_ == 0 && options_.auto_scale &&
293 options_.finite_difference > 0.0)) {
294 dir *= host_h0;
295 }
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);
301 }
302 }
303 }
304 if (!dir.allFinite()) {
305 rejectPushedRgPair(pushed_pair);
306 return false;
307 }
308
309 const Eigen::VectorXd next = objective.stepPositions(pos, dir);
310 if (!next.allFinite() || next.size() != pos.size()) {
311 rejectPushedRgPair(pushed_pair);
312 return false;
313 }
314 objective.setPositions(next);
315 if (!objective.refresh(false)) {
316 restoreThroughStepPositions(objective, pos);
317 (void)objective.refresh(false);
318 rejectPushedRgPair(pushed_pair);
319 return false;
320 }
321 // Commit the pair and the counter only after the post-step refresh:
322 // a reset landing there has cleared both books, and a rejected step
323 // must not leave a half-committed previous point behind.
324 if (reset_generation_ != generation) return true;
325 curvature_cap_.observe(objective.maxMotion(dir), configured_move,
326 objective.maxMotion(force));
327 previous_x_ = pos;
328 previous_g_ = grad;
329 have_previous_ = true;
330 ++iteration_;
331 return true;
332 }
333
334 void rebuildSketchedH0(
335 const std::function<Eigen::VectorXd(const Eigen::VectorXd&)>&,
336 int) override
337 {
338 }
339 void setCurvatureExclusion(Eigen::Index offset,
340 Eigen::Index len) noexcept override
341 {
342 curvature_exclude_offset_ = offset;
343 curvature_exclude_len_ = len;
344 }
345 [[nodiscard]] int iteration() const override
346 {
347 return iteration_;
348 }
349 [[nodiscard]] int historySize() const override
350 {
351 return static_cast<int>(s_hist_.size());
352 }
353 [[nodiscard]] double lastCurvatureDot() const override
354 {
355 return s_hist_.empty() ? 0.0 : s_hist_.back().dot(y_hist_.back());
356 }
357 [[nodiscard]] double lastCurvatureScale() const override
358 {
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;
364 }
365
366private:
370 static Eigen::VectorXd clipAtomMaxmove(const Eigen::VectorXd& step,
371 double cap)
372 {
373 if (!(cap > 0.0) || !std::isfinite(cap)) return step;
374 const Eigen::Index n = step.size();
375 double max_atom = 0.0;
376 Eigen::Index i = 0;
377 while (i + 3 <= n) {
378 max_atom = std::max(max_atom, step.segment<3>(i).norm());
379 i += 3;
380 }
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);
383 return step;
384 }
385
386 [[nodiscard]] double fallbackInverseCurvature() const
387 {
388 const double H0 = options_.inverse_curvature;
389 return (H0 > 0.0 && std::isfinite(H0)) ? H0 : 0.01;
390 }
391
397 bool probeFiniteDifferenceH0(GlobalLBFGSObjective& objective,
398 double max_move,
399 const Eigen::VectorXd& positions,
400 const Eigen::VectorXd& force,
401 Eigen::VectorXd& dir, double& host_h0)
402 {
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);
410 return false;
411 }
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);
417 return false;
418 }
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);
424 return false;
425 }
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_);
429 clearHostHistory();
430 dir = objective.limitMotion(1000.0 * force, max_move);
431 return false;
432 }
433 return true;
434 }
435
436 static bool obtuseToForce(const Eigen::VectorXd& proposed,
437 const Eigen::VectorXd& force)
438 {
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;
446 }
447
448 static bool hostCurvatureRejected(const Eigen::VectorXd& s,
449 const Eigen::VectorXd& y)
450 {
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);
455 }
456
458 static bool rgRhoDefined(double sy)
459 {
460 return std::isfinite(sy) && std::abs(sy) >= 1e-30;
461 }
462
464 void applyCurvatureExclusion(Eigen::VectorXd& s, Eigen::VectorXd& y) const
465 {
467 s, y, curvature_exclude_offset_, curvature_exclude_len_);
468 }
469
470 void recordHostPair(const Eigen::VectorXd& s, const Eigen::VectorXd& y)
471 {
472 const double sy = s.dot(y);
473 // eOn / InternalLbfgsEngine admit every non-degenerate pair so
474 // a climbing or non-conservative y can make the host two-loop
475 // ascent; rgmin drops sy <= 0, so the host book is what
476 // angle_reset inspects.
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) {
485 s_hist_.pop_front();
486 y_hist_.pop_front();
487 rho_hist_.pop_front();
488 }
489 }
490
493 [[nodiscard]] Eigen::VectorXd hostProposed(
494 const Eigen::VectorXd& force, double H0,
495 const std::vector<std::size_t>& sketch_idx) const
496 {
497 if (sketch_idx.empty()) {
498 const Eigen::VectorXd z = gpr::optim::twoLoopRecursion(
499 s_hist_, y_hist_, rho_hist_, force, H0);
500 return -z;
501 }
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]);
508 }
509 const Eigen::VectorXd z =
510 gpr::optim::twoLoopRecursion(s_sk, y_sk, rho_sk, force, H0);
511 return -z;
512 }
513
517 [[nodiscard]] std::vector<std::size_t> fillSketchIndices()
518 {
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) {
523 sketch_rng_state_ =
524 options_.sketch_seed != 0 ? options_.sketch_seed : 1ULL;
525 }
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]);
536 }
537 std::sort(idx.begin(), idx.begin() + k_sketch);
538 idx.resize(static_cast<std::size_t>(k_sketch));
539 return idx;
540 }
541
544 void loadRgPairs(const std::vector<std::size_t>& idx)
545 {
546 if (solver_ == nullptr) return;
547 const std::size_t n = dim_;
548 if (idx.empty()) {
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);
552 }
553 return;
554 }
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);
558 }
559 }
560
565 bool applyHostResets(GlobalLBFGSObjective& objective, double max_move,
566 const Eigen::VectorXd& force, Eigen::VectorXd& dir,
567 const Eigen::VectorXd& host_proposed, double H0)
568 {
569 const double proposed_motion = objective.maxMotion(dir);
570 bool reset = false;
571 if (options_.distance_reset && max_move > 0.0 &&
572 std::isfinite(max_move) && std::isfinite(proposed_motion) &&
573 proposed_motion >= max_move) {
574 reset = true;
575 }
576 if (!reset && options_.angle_reset &&
577 (obtuseToForce(dir, force) ||
578 obtuseToForce(host_proposed, force))) {
579 reset = true;
580 }
581 if (!reset) return false;
582 if (solver_ != nullptr) rgmin_solver_forget(solver_);
583 clearHostHistory();
584 dir = objective.limitMotion(H0 * force, max_move);
585 return true;
586 }
587
588 void clearHostPair()
589 {
590 have_previous_ = false;
591 previous_x_.resize(0);
592 previous_g_.resize(0);
593 }
594
599 static void restoreThroughStepPositions(GlobalLBFGSObjective& objective,
600 const Eigen::VectorXd& origin)
601 {
602 const Eigen::VectorXd current = objective.positions();
603 if (current.size() != origin.size() || !current.allFinite() ||
604 !origin.allFinite()) {
605 return;
606 }
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()) {
610 return;
611 }
612 objective.setPositions(restored);
613 }
614
619 void rejectPushedRgPair(bool pushed_pair)
620 {
621 if (pushed_pair) {
622 if (solver_ != nullptr) rgmin_solver_forget(solver_);
623 clearHostHistory();
624 }
625 clearHostPair();
626 }
627
628 void clearHostHistory()
629 {
630 s_hist_.clear();
631 y_hist_.clear();
632 rho_hist_.clear();
633 }
634
635 void release()
636 {
637 if (solver_ != nullptr) {
638 rgmin_solver_free(solver_);
639 solver_ = nullptr;
640 dim_ = 0;
641 }
642 clearHostPair();
643 clearHostHistory();
644 }
645
646 void ensure(std::size_t dim)
647 {
648 if (solver_ != nullptr && dim_ == dim) return;
649 release();
650 rgmin_control_t ctrl{};
651 ctrl.maxiter = 1;
652 ctrl.gtol = 0.0;
653 ctrl.istep = 1.0;
654 ctrl.memory = memory_ == 0 ? 20 : memory_;
655 ctrl.maxmove = 0.0;
657 solver_ = rgmin_solver_create(RGMIN_LBFGS, &ctrl, dim);
658 // The band engine applies its own per-atom cap from its options;
659 // clear the one rgmin installs on a Cartesian session by default
660 // so the stepper keeps its two-loop path and the host cap governs.
661 rgmin_solver_set_atom_maxmove(solver_, 0.0);
662 dim_ = dim;
663 }
664
665 rgmin_solver_t* solver_ = nullptr;
666 std::size_t dim_ = 0;
667 GlobalLBFGSOptions options_{};
668 std::size_t memory_ = 20;
669 int iteration_ = 0;
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;
682};
683
684} // namespace detail
685} // namespace neb
686} // namespace gpr
687
688#endif /* GPR_NEB_RG_LBFGS_ENGINE_H_ */
@ z
Definition Enums.h:28
@ y
Definition Enums.h:28
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.
Definition LBFGS.cpp:39
void excludeNonPositiveCurvatureBlock(Eigen::VectorXd &s, Eigen::VectorXd &y, Eigen::Index offset, Eigen::Index length)
Definition LBFGS.cpp:25
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).
Definition LBFGS.cpp:51
void requireCompatibleLibrary()
Definition RgminAbi.h:90
Gaussian-process regression, kernels, priors, and the searches that run on the surrogate.
Definition Macros.h:16