Loading...
Searching...
No Matches
XtsciOptimizer.cpp
Go to the documentation of this file.
1/*
2** This file is part of eOn.
3**
4** SPDX-License-Identifier: BSD-3-Clause
5**
6** Copyright (c) 2010--present, eOn Development Team
7** All rights reserved.
8**
9** Repo:
10** https://github.com/TheochemUI/eOn
11*/
12#include "eon/XtsciOptimizer.h"
13#include "eon/PairHessian.h"
14#include "eon/XtsciEindir.h"
15
16#include <algorithm>
17#include <stdexcept>
18#include <string>
19#include <vector>
20
21#include <rgmin.h>
22
23#if RGMIN_ABI_VERSION_MINOR < 10
24#error "rgmin ABI minor 10 or newer is required for set_periodic"
25#endif
26
27namespace {
28
29struct XtsObjectiveContext {
30 eonc::ObjectiveFunction *objective;
31 eonc::PotType pot;
32 std::string precon;
33 double precon_A;
34 double precon_mu;
35 double precon_rcut;
36 Eigen::VectorXd *cached_x;
37 eonc::xtsci_eindir::State *eindir;
38};
39
40Eigen::Map<const Eigen::VectorXd>
41map_input(const DLManagedTensorVersioned *tensor) {
42 const auto &dl = tensor->dl_tensor;
43 if (dl.ndim != 1 || dl.dtype.code != kDLFloat || dl.dtype.bits != 64 ||
44 dl.dtype.lanes != 1 || dl.device.device_type != kDLCPU ||
45 dl.shape == nullptr || dl.data == nullptr) {
46 throw std::runtime_error("rgmin objective requires a CPU f64 vector");
47 }
48 return {static_cast<const double *>(dl.data) +
49 dl.byte_offset / sizeof(double),
50 static_cast<Eigen::Index>(dl.shape[0])};
51}
52
53Eigen::Map<Eigen::VectorXd> map_output(DLManagedTensorVersioned *tensor) {
54 const auto &dl = tensor->dl_tensor;
55 if (dl.ndim != 1 || dl.dtype.code != kDLFloat || dl.dtype.bits != 64 ||
56 dl.dtype.lanes != 1 || dl.device.device_type != kDLCPU ||
57 dl.shape == nullptr || dl.data == nullptr) {
58 throw std::runtime_error("rgmin tensor requires a CPU f64 vector");
59 }
60 return {static_cast<double *>(dl.data) + dl.byte_offset / sizeof(double),
61 static_cast<Eigen::Index>(dl.shape[0])};
62}
63
64// Matter::setPositions always dirties the PES cache. Energy and
65// forces come from one potential->force() call, so eval then grad at
66// the same x must not setPositions twice.
67void set_positions_if_changed(eonc::ObjectiveFunction *obj,
68 const Eigen::VectorXd &x,
69 Eigen::VectorXd *cached) {
70 if (cached != nullptr && cached->size() == x.size() &&
71 (*cached - x).isZero(0.0)) {
72 return;
73 }
74 // First host iteration: relaxMatter already called isConverged()
75 // at this geometry. Do not dirty that cache.
76 const auto cur = obj->getPositions();
77 if (cur.size() == x.size() && (cur - x).isZero(0.0)) {
78 if (cached != nullptr) {
79 *cached = x;
80 }
81 return;
82 }
83 obj->setPositions(x);
84 if (cached != nullptr) {
85 *cached = x;
86 }
87}
88
89// One Matter::computePotential. Energy and forces share that call.
90rgmin_status_t evaluate_gradient(void *user, const DLManagedTensorVersioned *x,
91 double *value_out,
92 DLManagedTensorVersioned *gradient_out) {
93 try {
94 auto *context = static_cast<XtsObjectiveContext *>(user);
95 if (context->eindir != nullptr) {
96 return static_cast<rgmin_status_t>(eonc::xtsci_eindir::eval_grad(
97 context->eindir, x, value_out, gradient_out));
98 }
99 const auto positions = map_input(x);
100 set_positions_if_changed(context->objective, positions, context->cached_x);
101 *value_out = context->objective->getEnergy();
102 const auto gradient_value = context->objective->getGradient();
103 auto output = map_output(gradient_out);
104 if (output.size() != gradient_value.size()) {
105 return RGMIN_INVALID_PARAMETER;
106 }
107 output = gradient_value;
108 return RGMIN_SUCCESS;
109 } catch (...) {
110 return RGMIN_INTERNAL_ERROR;
111 }
112}
113
114rgmin_status_t hessian(void *user, const DLManagedTensorVersioned *x,
115 DLManagedTensorVersioned *hess_out) {
116 try {
117 auto *context = static_cast<XtsObjectiveContext *>(user);
118 const auto positions = map_input(x);
119 const Eigen::MatrixXd H = eonc::pairhess::build(
120 positions, context->precon, context->pot, context->precon_A,
121 context->precon_mu, context->precon_rcut, *context->objective);
122 auto output = map_output(hess_out);
123 const Eigen::Index n = H.rows();
124 if (output.size() != n * n) {
125 return RGMIN_INVALID_PARAMETER;
126 }
127 for (Eigen::Index i = 0; i < n; ++i) {
128 for (Eigen::Index j = 0; j < n; ++j) {
129 output[i * n + j] = H(i, j);
130 }
131 }
132 return RGMIN_SUCCESS;
133 } catch (...) {
134 return RGMIN_INTERNAL_ERROR;
135 }
136}
137
138rgmin_method_t method_from_name(const std::string &name) {
139 if (name == "lbfgs") {
140 return RGMIN_LBFGS;
141 }
142 if (name == "bfgs") {
143 return RGMIN_BFGS;
144 }
145 if (name == "sr1") {
146 return RGMIN_SR1;
147 }
148 if (name == "sr2") {
149 return RGMIN_SR2;
150 }
151 if (name == "newton") {
152 return RGMIN_NEWTON;
153 }
154 if (name == "rfo") {
155 return RGMIN_RFO;
156 }
157 if (name == "steepest") {
158 return RGMIN_STEEPEST;
159 }
160 if (name == "adam") {
161 return RGMIN_ADAM;
162 }
163 if (name == "pso") {
164 return RGMIN_PSO;
165 }
166 if (name == "polak_ribiere" || name == "nlcg" || name == "pr") {
167 return RGMIN_POLAK_RIBIERE;
168 }
169 if (name == "fletcher_reeves") {
170 return RGMIN_FLETCHER_REEVES;
171 }
172 if (name == "hestenes_stiefel") {
173 return RGMIN_HESTENES_STIEFEL;
174 }
175 if (name == "dai_yuan") {
176 return RGMIN_DAI_YUAN;
177 }
178 if (name == "conjugate_descent") {
179 return RGMIN_CONJUGATE_DESCENT;
180 }
181 if (name == "hager_zhang") {
182 return RGMIN_HAGER_ZHANG;
183 }
184 if (name == "liu_storey") {
185 return RGMIN_LIU_STOREY;
186 }
187 if (name == "fr_pr") {
188 return RGMIN_FR_PR;
189 }
190 if (name == "fire") {
191 return RGMIN_FIRE;
192 }
193 if (name == "bb" || name == "barzilai_borwein") {
194 return RGMIN_BB;
195 }
196 if (name == "dogleg") {
197 return RGMIN_DOGLEG;
198 }
199 if (name == "fire2") {
200 return RGMIN_FIRE2;
201 }
202#if RGMIN_ABI_VERSION_MINOR >= 29
203 if (name == "quickmin") {
204 return RGMIN_QUICKMIN;
205 }
206#endif
207 throw std::invalid_argument(
208 "unknown Xtsci.method '" + name +
209 "' (lbfgs, bfgs, sr1, sr2, newton, rfo, steepest, adam, pso, "
210 "polak_ribiere, fletcher_reeves, hestenes_stiefel, dai_yuan, "
211 "conjugate_descent, hager_zhang, liu_storey, fr_pr, fire, bb, "
212 "dogleg, fire2, quickmin)");
213}
214
215bool is_dynamics(rgmin_method_t method) {
216 bool dynamics = method == RGMIN_FIRE || method == RGMIN_FIRE2;
217#if RGMIN_ABI_VERSION_MINOR >= 29
218 dynamics = dynamics || method == RGMIN_QUICKMIN;
219#endif
220 return dynamics;
221}
222
223// rgmin_control_t::istep. FIRE and quick-min read it as the time step,
224// the other methods as the first step length.
225double initial_step(rgmin_method_t method,
227 double a_maxMove) {
228 if (!is_dynamics(method)) {
229 return std::max(a_maxMove, 1.0e-12);
230 }
231 if (opts.time_step > 0.0) {
232 return opts.time_step;
233 }
234 if (opts.time_step_input > 0.0) {
235 return opts.time_step_input;
236 }
237 return 0.1;
238}
239
240bool is_host_precon(const std::string &name) {
241 return name == "pair" || name == "pair_abs" || name == "pair_full" ||
242 name == "exp" || name == "c1" || name == "lindh" ||
243 name == "lindh_full" || name == "fischer" || name == "schlegel" ||
244 name == "swart";
245}
246
247// [Xtsci] qn_step / precon are the natural knobs. [LBFGS] lbfgs_step
248// and lbfgs_precon stay on the native optimizer and fill in when the
249// Xtsci fields are still at their defaults.
250std::string
251resolved_qn_step(const eonc::Parameters::optimizer_options_t &opts) {
252 if (opts.xtsci.qn_step != "lbfgs") {
253 return opts.xtsci.qn_step;
254 }
255 if (opts.lbfgs.step == "newton" || opts.lbfgs.step == "rfo") {
256 return opts.lbfgs.step;
257 }
258 return opts.xtsci.qn_step;
259}
260
261std::string resolved_precon(const eonc::Parameters::optimizer_options_t &opts) {
262 if (opts.xtsci.precon != "none") {
263 return opts.xtsci.precon;
264 }
265 return opts.lbfgs.precon;
266}
267
268std::string resolved_accept(const eonc::Parameters::optimizer_options_t &opts) {
269 if (opts.xtsci.accept != "none") {
270 return opts.xtsci.accept;
271 }
272 if (opts.lbfgs.accept == "energy" || opts.lbfgs.accept == "nonmonotone") {
273 return opts.lbfgs.accept;
274 }
275 return opts.xtsci.accept;
276}
277
278} // namespace
279
280namespace eonc {
281
283 rgmin_solver_free(m_solver);
285 m_eindir = nullptr;
286}
287
288void XtsciOptimizer::ensureSolver(double a_maxMove) {
289 if (m_solver != nullptr) {
290 return;
291 }
292 const auto dim = static_cast<size_t>(m_objf->degreesOfFreedom());
293 if (dim == 0) {
294 return;
295 }
296 const auto stamp = rgmin_abi_stamp();
297 if (rgmin_abi_compatible(&stamp) == 0) {
298 throw std::runtime_error("incompatible rgmin ABI");
299 }
300 const auto &lbfgs = m_optConfig.opts.lbfgs;
301 const rgmin_method_t method = method_from_name(m_method);
302#if RGMIN_ABI_VERSION_MINOR < 27
303 if (method == RGMIN_FIRE2) {
304 throw std::runtime_error(
305 "Xtsci.method = fire2 needs rgmin ABI minor 27 or newer for "
306 "rgmin_solver_set_fire_variant");
307 }
308#endif
309 rgmin_control_t control{
310 static_cast<size_t>(std::max<long>(1, m_optConfig.opts.max_iterations)),
311 m_optConfig.opts.converged_force,
312 initial_step(method, m_optConfig.opts, a_maxMove),
313 static_cast<size_t>(std::max<long>(0, lbfgs.memory)),
314 0.0,
315 };
316 m_solver = rgmin_solver_create(method, &control, dim);
317 if (m_solver == nullptr) {
318 throw std::runtime_error(rgmin_last_error());
319 }
320#if RGMIN_ABI_VERSION_MINOR >= 27
321 // The default RGMIN_FIRE2 schedule keeps the FIRE 1.0 parameters.
322 // The variant reads dt0 from control.istep, so it follows create.
323 if (method == RGMIN_FIRE2) {
324 rgmin_solver_set_fire_variant(m_solver, RGMIN_FIRE_GUENOLE2020);
325 }
326#endif
327 const auto step = resolved_qn_step(m_optConfig.opts);
328 if (step == "newton") {
329 rgmin_solver_set_qn_step(m_solver, RGMIN_QN_NEWTON);
330 } else if (step == "rfo") {
331 rgmin_solver_set_qn_step(m_solver, RGMIN_QN_RFO);
332 } else {
333 rgmin_solver_set_qn_step(m_solver, RGMIN_QN_LBFGS);
334 }
335 const auto accept = m_objf->gradientMatchesEnergy()
336 ? resolved_accept(m_optConfig.opts)
337 : std::string("none");
338 if (accept == "energy") {
339 rgmin_solver_set_accept(m_solver, RGMIN_ACCEPT_ENERGY);
340 } else if (accept == "nonmonotone") {
341 rgmin_solver_set_accept(m_solver, RGMIN_ACCEPT_NONMONOTONE);
342 } else {
343 rgmin_solver_set_accept(m_solver, RGMIN_ACCEPT_NONE);
344 }
345 rgmin_solver_set_project_rigid(m_solver, lbfgs.project_rigid ? 1 : 0);
346 rgmin_solver_set_extra_updates(
347 m_solver, static_cast<size_t>(std::max<long>(0, lbfgs.extra_updates)));
348 if (lbfgs.curvature == "cautious") {
349 rgmin_solver_set_cautious(m_solver, lbfgs.cautious_eps,
350 lbfgs.cautious_alpha);
351 } else {
352 rgmin_solver_set_cautious(m_solver, 0.0, lbfgs.cautious_alpha);
353 }
354 if (m_optConfig.opts.xtsci.highs) {
355 if (rgmin_solver_set_highs(m_solver, 1) != 0) {
356 throw std::runtime_error(
357 "Xtsci.highs needs rgmin built with --features highs");
358 }
359 }
360 const auto &mani = m_optConfig.opts.xtsci.manifold;
361 if (mani == "so3" && dim != 9) {
362 throw std::runtime_error(
363 "Xtsci.manifold=so3 needs length 9; a 3N cluster is "
364 "rigid_quotient (Sella R^{3N}/SE(3)), not a packed rotation");
365 }
366 if (mani == "se3" && dim != 12) {
367 throw std::runtime_error(
368 "Xtsci.manifold=se3 needs length 12; a 3N cluster is "
369 "rigid_quotient (Sella R^{3N}/SE(3)), not an SE(3) prefix");
370 }
371 if ((mani == "rigid_quotient" || mani == "mw_rigid" || mani == "sella" ||
372 mani == "eckart" || mani == "irc") &&
373 (dim < 6 || dim % 3 != 0)) {
374 throw std::runtime_error("Xtsci.manifold=" + mani +
375 " needs 3N Cartesians with N >= 2");
376 }
377 if (mani == "sphere") {
378 rgmin_solver_set_manifold(m_solver, RGMIN_MANIFOLD_SPHERE);
379 } else if (mani == "so3") {
380 rgmin_solver_set_manifold(m_solver, RGMIN_MANIFOLD_SO3);
381 } else if (mani == "stiefel") {
382 rgmin_solver_set_manifold(m_solver, RGMIN_MANIFOLD_STIEFEL);
383 } else if (mani == "se3") {
384 rgmin_solver_set_manifold(m_solver, RGMIN_MANIFOLD_SE3);
385 } else if (mani == "rigid_quotient" || mani == "sella") {
386 rgmin_solver_set_manifold(m_solver, RGMIN_MANIFOLD_RIGID_QUOTIENT);
387 } else if (mani == "mw_rigid" || mani == "eckart" || mani == "irc") {
388 rgmin_solver_set_manifold(m_solver, RGMIN_MANIFOLD_MW_RIGID);
389 const auto masses = m_objf->getMasses();
390 if (masses.size() > 0) {
391 rgmin_solver_set_masses(m_solver, masses.data(),
392 static_cast<size_t>(masses.size()));
393 }
394 } else {
395 rgmin_solver_set_manifold(m_solver, RGMIN_MANIFOLD_EUCLIDEAN);
396 }
397 if (mani == "rigid_quotient" || mani == "mw_rigid" || mani == "sella" ||
398 mani == "eckart" || mani == "irc") {
399 rgmin_solver_set_periodic(m_solver, m_objf->getPeriodic() ? 1 : 0);
400 }
401 if (m_eindir == nullptr) {
403 }
404}
405
406int XtsciOptimizer::step(double a_maxMove) {
407 if (m_objf->degreesOfFreedom() <= 0) {
408 return m_objf->isConverged() ? 1 : 0;
409 }
410 ensureSolver(a_maxMove);
411 if (m_solver == nullptr) {
412 return m_objf->isConverged() ? 1 : 0;
413 }
414 // Native LBFGS clips by the largest per-atom move, not ||d||_2.
415 rgmin_solver_set_maxmove(m_solver, 0.0);
416 rgmin_solver_set_atom_maxmove(m_solver, std::max(a_maxMove, 0.0));
417
418 if (m_x.size() == 0) {
419 m_x = m_objf->getPositions();
420 }
421 if (m_x.size() != m_objf->degreesOfFreedom()) {
422 throw std::runtime_error("rgmin objective position dimension mismatch");
423 }
424 auto *tensor =
425 rgmin_tensor_borrow_cpu_f64(m_x.data(), static_cast<size_t>(m_x.size()));
426 if (tensor == nullptr) {
427 throw std::runtime_error("could not allocate rgmin objective tensor");
428 }
429 const auto &lbfgs = m_optConfig.opts.lbfgs;
430 std::string precon = resolved_precon(m_optConfig.opts);
431 const rgmin_method_t method = method_from_name(m_method);
432 if (method == RGMIN_DOGLEG && !is_host_precon(precon)) {
433 precon = "pair";
434 }
435 XtsObjectiveContext context{
436 m_objf.get(), m_optConfig.potential, precon, lbfgs.precon_A,
437 lbfgs.precon_mu, lbfgs.precon_rcut, &m_cached_x, m_eindir,
438 };
439 rgmin_report_t report{};
440 const bool want_hess = method == RGMIN_NEWTON || method == RGMIN_RFO ||
441 method == RGMIN_DOGLEG || is_host_precon(precon);
442 rgmin_status_t status;
443 if (want_hess) {
444 status = rgmin_solver_step_hess_fg(m_solver, evaluate_gradient, hessian,
445 &context, tensor, &report);
446 } else {
447 status = rgmin_solver_step_fg(m_solver, evaluate_gradient, &context, tensor,
448 &report);
449 }
450 rgmin_tensor_free(tensor);
451 if (status != RGMIN_SUCCESS) {
452 throw std::runtime_error(rgmin_last_error());
453 }
454 return m_objf->isConverged() ? 1 : 0;
455}
456
457int XtsciOptimizer::run(size_t a_maxIterations, double a_maxMove) {
458 if (m_objf->degreesOfFreedom() <= 0 || a_maxIterations == 0) {
459 return m_objf->isConverged() ? 1 : 0;
460 }
461 ensureSolver(a_maxMove);
462 const auto &lbfgs = m_optConfig.opts.lbfgs;
463 std::string precon = resolved_precon(m_optConfig.opts);
464 const rgmin_method_t method = method_from_name(m_method);
465 if (method == RGMIN_DOGLEG && !is_host_precon(precon)) {
466 precon = "pair";
467 }
468 const bool want_hess = method == RGMIN_NEWTON || method == RGMIN_RFO ||
469 method == RGMIN_DOGLEG || is_host_precon(precon);
470 // A full minimize without a host Hessian goes through the eindir entry.
471 // step() stays one session iteration so the host loop keeps its memory.
472 // rgmin_minimize_eindir takes no FIRE variant, so fire2 stays on the
473 // session.
474 if (m_eindir != nullptr && !want_hess && method != RGMIN_FIRE2) {
475 if (m_x.size() == 0) {
476 m_x = m_objf->getPositions();
477 }
478 double value = 0.0;
479 const int status = xtsci_eindir::minimize(
480 m_eindir, m_x.data(), static_cast<size_t>(m_x.size()), a_maxIterations,
481 m_optConfig.opts.converged_force,
482 initial_step(method, m_optConfig.opts, a_maxMove),
483 static_cast<size_t>(std::max<long>(0, lbfgs.memory)),
484 static_cast<int>(method), &value);
485 if (status != RGMIN_SUCCESS) {
486 throw std::runtime_error(rgmin_last_error());
487 }
488 m_objf->setPositions(m_x);
489 m_cached_x = m_x;
490 static_cast<void>(value);
491 return m_objf->isConverged() ? 1 : 0;
492 }
493 for (size_t i = 0; i < a_maxIterations; ++i) {
494 if (step(a_maxMove) != 0) {
495 return 1;
496 }
497 }
498 return m_objf->isConverged() ? 1 : 0;
499}
500
501} // namespace eonc
virtual VectorXd getPositions()=0
virtual void setPositions(const VectorXd &x)=0
const OptimizerConfig m_optConfig
Definition Optimizer.h:73
std::shared_ptr< ObjectiveFunction > m_objf
Definition Optimizer.h:74
eonc::optimizer_options_t optimizer_options_t
Definition Parameters.h:70
int run(size_t a_maxIterations, double a_maxMove) override
void ensureSolver(double a_maxMove)
Eigen::VectorXd m_cached_x
const std::string & method() const
rgmin_solver_t * m_solver
Eigen::VectorXd m_x
int step(double a_maxMove) override
xtsci_eindir::State * m_eindir
Eigen::MatrixXd build(const Eigen::VectorXd &pos, const std::string &kind, PotType pot, double A, double mu, double rcut_in, ObjectiveFunction &objf)
Analytic pair or model Hessian.
int minimize(State *state, double *x, std::size_t n, std::size_t maxiter, double gtol, double istep, std::size_t memory, int method, double *value_out)
xts_minimize_eindir on a caller-owned buffer. The caller keeps State.
void release(State *state)
State * bind(ObjectiveFunction *objective, Eigen::VectorXd *cached)
Borrow an ObjectiveFunction as an eindir objective.
int eval_grad(State *state, const DLManagedTensorVersioned *x, double *value, DLManagedTensorVersioned *gradient)
One fused energy and gradient through the borrowed eindir handle.
RAII resource manager for the ARTn C library with global synchronization.
struct eonc::optimizer_options_t::xtsci_t xtsci
struct eonc::optimizer_options_t::lbfgs_t lbfgs