12#define RGPOT_ENGINE_BUILD
34#include "gpridge_version.h"
37#if defined(USE_CAPNP) && __has_include("rgpot/rpc/Potentials.capnp.h")
38#define GPR_ENGINE_HAS_POTENTIAL_SPEC 1
39#include <capnp/message.h>
40#include <capnp/serialize.h>
42#include "rgpot/rpc/Potentials.capnp.h"
50template <
typename Reader,
typename Builder>
51std::vector<unsigned char> reserialise(Reader src)
53 capnp::MallocMessageBuilder msg;
55 const kj::Array<capnp::word> words = capnp::messageToFlatArray(msg);
56 const kj::ArrayPtr<const kj::byte> bytes = words.asBytes();
57 return std::vector<unsigned char>(bytes.begin(), bytes.end());
62bool oracleFromSpec(::PotentialSpec::Reader spec, std::string& library,
63 std::vector<unsigned char>& config, std::string& err)
65 switch (spec.which()) {
66 case ::PotentialSpec::UMA:
71 spec.getUma().getModelPath().cStr());
72 }
catch (
const std::exception& error) {
77 config = reserialise<::UmaParams::Reader, ::UmaParams::Builder>(
80 case ::PotentialSpec::METATOMIC:
83 reserialise<::MetatomicParams::Reader,
84 ::MetatomicParams::Builder>(spec.getMetatomic());
86 case ::PotentialSpec::NWCHEM:
89 reserialise<::NWChemParams::Reader, ::NWChemParams::Builder>(
92 case ::PotentialSpec::CPMD:
94 config = reserialise<::CPMDParams::Reader, ::CPMDParams::Builder>(
97#ifdef GPR_SCHEMA_HAS_CP2K_CONFIG
98 case ::PotentialSpec::CP2K:
100 config = reserialise<::CP2KParams::Reader, ::CP2KParams::Builder>(
104 case ::PotentialSpec::LAMMPS:
107 reserialise<::LammpsParams::Reader, ::LammpsParams::Builder>(
110 case ::PotentialSpec::BUILTIN: {
111 const auto b = spec.getBuiltin();
112 library = b.getLibrary().size() > 0
113 ? std::string(b.getLibrary().cStr())
115 if (library.empty()) {
116 err = std::string(
"oracle arm 'builtin' names '") +
118 "', which has no engine plugin; give it an explicit "
126 err =
"oracle spec carries no arm";
138 std::snprintf(
errbuf,
errlen,
"%s", msg !=
nullptr ? msg :
"unknown");
141bool checked_add_u64(
unsigned long long a,
unsigned long long b,
142 unsigned long long&
out)
144 if (a > std::numeric_limits<unsigned long long>::max() - b)
return false;
149bool checked_mul_u64(
unsigned long long a,
unsigned long long b,
150 unsigned long long&
out)
152 if (a != 0 && b > std::numeric_limits<unsigned long long>::max() / a)
158bool checked_add_size(std::size_t a, std::size_t b, std::size_t&
out)
160 if (a > std::numeric_limits<std::size_t>::max() - b)
return false;
165bool checked_mul_size(std::size_t a, std::size_t b, std::size_t&
out)
167 if (a != 0 && b > std::numeric_limits<std::size_t>::max() / a)
return false;
172bool checked_int_count(std::size_t n,
int&
out)
174 if (n >
static_cast<std::size_t
>(std::numeric_limits<int>::max())) {
177 out =
static_cast<int>(n);
181bool gemv_ops(
unsigned long long rows,
unsigned long long cols,
182 unsigned long long&
out)
184 unsigned long long twice = 0;
185 if (!checked_mul_u64(cols, 2, twice) || twice == 0)
return false;
186 return checked_mul_u64(rows, twice - 1,
out);
189bool sexpat_action_ops(std::size_t n_obs, std::size_t n_dof,
190 unsigned long long&
out)
192 const auto n =
static_cast<unsigned long long>(n_obs);
193 const auto d =
static_cast<unsigned long long>(n_dof);
194 const unsigned long long atoms = d / 3;
195 unsigned long long ops = 0;
196 unsigned long long term = 0;
197 if (!gemv_ops(n, d, term) || !checked_add_u64(ops, term, ops))
return false;
198 if (!gemv_ops(n, d, term) || !checked_add_u64(ops, term, ops))
return false;
199 if (!checked_mul_u64(n, 3, term) || !checked_add_u64(ops, term, ops))
201 if (!checked_add_u64(ops, n, ops))
return false;
202 if (!gemv_ops(d, n, term) || !checked_add_u64(ops, term, ops))
return false;
203 if (!gemv_ops(d, n, term) || !checked_add_u64(ops, term, ops))
return false;
204 if (!checked_add_u64(ops, d, ops))
return false;
205 if (!checked_mul_u64(atoms, 3, term) || !checked_add_u64(ops, term, ops))
207 if (!checked_mul_u64(n, 4, term) || !checked_add_u64(ops, term, ops))
213struct SaddleQuadratic {
214 std::vector<double> x;
216 std::vector<double> g;
217 std::vector<double> h;
219 void energy_gradient(
const double* pos,
double& e_out,
220 std::vector<double>& g_out)
const
222 const std::size_t d = x.size();
223 std::vector<double> dx(d, 0.0);
224 for (std::size_t a = 0; a < d; ++a)
225 dx[a] = pos[a] - x[a];
226 std::vector<double> hdx(d, 0.0);
227 for (std::size_t a = 0; a < d; ++a) {
228 double row_sum = 0.0;
229 const double* row = h.data() + a * d;
230 for (std::size_t b = 0; b < d; ++b)
231 row_sum += row[b] * dx[b];
234 double g_dot_dx = 0.0;
235 double dx_dot_hdx = 0.0;
236 for (std::size_t a = 0; a < d; ++a) {
237 g_dot_dx += g[a] * dx[a];
238 dx_dot_hdx += dx[a] * hdx[a];
240 e_out = e + g_dot_dx + 0.5 * dx_dot_hdx;
242 for (std::size_t a = 0; a < d; ++a)
243 g_out[a] = g[a] + hdx[a];
247struct ResidualSession {
248 static constexpr std::size_t kEmbedAnchors = 4;
249 static constexpr std::size_t kEmbedOffset = 3 * kEmbedAnchors;
252 static constexpr std::size_t kEmbedScaleFactor = 12;
256 gpr_model_config_t model_cfg{};
258 std::size_t n_dof = 0;
259 std::size_t model_dof = 0;
260 bool embed_coords =
false;
261 double embed_scale = 0.0;
262 std::vector<int> atomic_nrs;
263 std::vector<int> atom_types;
266 SaddleQuadratic saddle;
267 std::vector<double> raw_x;
268 std::vector<double> rows_x;
269 std::vector<double> rows_e;
270 std::vector<double> rows_g;
271 std::set<std::vector<std::uint64_t>> seen;
273 std::size_t training_window = 0;
274 bool fixed_refits =
false;
277 std::size_t fitted_first = 0;
278 std::size_t fitted_rows = 0;
279 unsigned long long epoch = 0;
280 void (*model_update)(
void*,
unsigned long long) =
nullptr;
281 void* model_update_ctx =
nullptr;
282 RgpotEngineGprStats stats{};
286 stats.struct_size =
sizeof(RgpotEngineGprStats);
294 bool hill_from_oracle()
const
300 bool refuse_true_hill_curvature(std::string& error_out)
const
302 if (!hill_from_oracle())
return false;
304 "gpr engine: Hill phase under RGPOT_GPR_HILL_TRUE takes "
305 "curvature from the oracle";
325 static bool derive_embed_scale(
const std::vector<double>& x_ts,
326 const std::vector<double>& raw_x,
327 std::size_t n_obs,
double& scale_out,
328 std::string& error_out)
330 const std::size_t d = x_ts.size();
331 if (d == 0 || n_obs == 0 || raw_x.size() < n_obs * d) {
333 "gpr engine: cannot derive embedding scale from empty "
338 double max_abs = 0.0;
339 for (std::size_t i = 0; i < n_obs; ++i) {
340 for (std::size_t j = 0; j < d; ++j) {
341 const double delta = raw_x[i * d + j] - x_ts[j];
342 if (!std::isfinite(delta)) {
344 "gpr engine: non-finite coordinate displacement in "
348 sum_sq += delta * delta;
349 max_abs = std::max(max_abs, std::abs(delta));
352 const double rms = std::sqrt(sum_sq /
static_cast<double>(n_obs));
354 static_cast<double>(kEmbedScaleFactor * (d + kEmbedAnchors)) *
356 if (!std::isfinite(scale) || !(scale > 0.0)) {
358 "gpr engine: degenerate coordinate spread; cannot derive "
359 "positive embedding scale";
366 bool init_embedded_atoms(
double scale, std::string& error_out)
368 const std::size_t n_blocks = (n_dof + 2) / 3;
369 const std::size_t total_atoms = kEmbedAnchors + n_blocks;
370 std::vector<int> is_frozen(total_atoms, 0);
371 for (std::size_t a = 0; a < kEmbedAnchors; ++a) {
374 std::vector<double> ref_pos(3 * total_atoms, 0.0);
382 for (std::size_t k = 0; k < n_blocks; ++k) {
383 const double base = scale *
static_cast<double>(k + 1);
384 ref_pos[kEmbedOffset + 3 * k] = base;
385 ref_pos[kEmbedOffset + 3 * k + 1] = base;
386 ref_pos[kEmbedOffset + 3 * k + 2] = base;
388 gpr_atoms_config_t acfg =
392 if (!atomic_nrs.empty()) {
397 if (new_atoms ==
nullptr) {
402 if (new_model ==
nullptr) {
424 bool reset_cartesian_model(std::string& error_out)
426 if (atoms ==
nullptr) {
427 error_out =
"gpr engine: Cartesian model has no atoms";
431 if (new_model ==
nullptr) {
445 void embed_point(
const double*
x,
double* r_out)
const
448 std::copy(
x,
x + n_dof, r_out);
451 std::fill(r_out, r_out + model_dof, 0.0);
452 const std::size_t n_blocks = (n_dof + 2) / 3;
453 for (std::size_t k = 0; k < n_blocks; ++k) {
454 const double base = embed_scale *
static_cast<double>(k + 1);
456 r_out[3 * k + 1] = base;
457 r_out[3 * k + 2] = base;
459 for (std::size_t j = 0; j < n_dof; ++j) {
460 const double delta =
x[j] - saddle.x[j];
465 void embed_direction(
const double* v,
double* v_out)
const
468 std::copy(v, v + n_dof, v_out);
471 std::fill(v_out, v_out + model_dof, 0.0);
472 std::copy(v, v + n_dof, v_out);
475 void project_vector(
const double* v_model,
double* v_out)
const
477 std::copy(v_model, v_model + n_dof, v_out);
480 static std::vector<std::uint64_t> bit_key(
const double*
x, std::size_t d)
482 std::vector<std::uint64_t> key(d, 0);
483 for (std::size_t i = 0; i < d; ++i) {
484 std::uint64_t bits = 0;
485 std::memcpy(&bits,
x + i,
sizeof(
double));
491 bool learn(
const double* xs, std::size_t n,
const double* energy,
492 const double* gradient, std::string& error_out)
494 const std::size_t d = n_dof;
495 const std::size_t md = model_dof;
497 if (!checked_mul_size(n, d, nd)) {
498 error_out =
"gpr engine: learn_points coordinate count overflows";
501 for (std::size_t i = 0; i < nd; ++i) {
502 if (!std::isfinite(xs[i]) || !std::isfinite(gradient[i])) {
504 "gpr engine: learn_points requires finite coordinates and "
509 for (std::size_t i = 0; i < n; ++i) {
510 if (!std::isfinite(energy[i])) {
511 error_out =
"gpr engine: learn_points requires finite energies";
515 std::vector<double> g_q;
516 std::vector<double> r_emb(md, 0.0);
517 std::vector<double> g_emb(md, 0.0);
519 for (std::size_t i = 0; i < n; ++i) {
520 const double*
x = xs + off;
521 auto key = bit_key(
x, d);
522 if (seen.find(key) != seen.end()) {
527 saddle.energy_gradient(
x, e_q, g_q);
530 const double e_res = energy[i] - e_q;
531 if (!std::isfinite(e_res)) {
533 "gpr engine: learn_points residual energy is not finite";
536 std::fill(g_emb.begin(), g_emb.end(), 0.0);
537 for (std::size_t a = 0; a < d; ++a) {
538 const double g_res = gradient[off + a] - g_q[a];
539 if (!std::isfinite(g_res)) {
541 "gpr engine: learn_points residual gradient is not "
547 seen.insert(std::move(key));
549 raw_x.insert(raw_x.end(),
x,
x + d);
551 embed_point(
x, r_emb.data());
552 rows_x.insert(rows_x.end(), r_emb.begin(), r_emb.end());
554 rows_e.push_back(e_res);
556 rows_g.insert(rows_g.end(), g_emb.begin(), g_emb.end());
557 ++stats.observations;
563 void publish_model_update()
565 if (model_update !=
nullptr) {
566 model_update(model_update_ctx, epoch);
570 int set_training(std::size_t window,
bool fixed, std::string& error_out)
574 if (fixed && !fixed_refits) {
576 if (model !=
nullptr &&
579 error_out = std::string(
"gpr engine: Cholesky backend: ") +
581 return RGPOT_ENGINE_ERR_EVAL;
584 const bool changed = training_window != window || fixed_refits != fixed;
585 training_window = window;
586 fixed_refits = fixed;
589 if (changed && !rows_e.empty()) stale =
true;
590 return RGPOT_ENGINE_OK;
593 int fit(std::string& error_out)
595 if (!stale)
return RGPOT_ENGINE_OK;
596 const std::size_t total = rows_e.size();
597 const std::size_t md = model_dof;
598 const std::size_t first = training_window > 0 && total > training_window
599 ? total - training_window
606 if (fixed_refits && training_window == 0 && !embed_coords &&
607 fitted_first == 0 && fitted_rows > 0 && fitted_rows < total) {
608 const std::size_t from = fitted_rows;
609 const std::size_t n_new = total - from;
612 if (!checked_int_count(n_new, n_new_i) ||
613 !checked_int_count(md, md_i)) {
615 "gpr engine: observation count does not fit in the C API";
616 return RGPOT_ENGINE_ERR_INVALID;
619 model, rows_x.data() + from * md, n_new * md,
620 rows_e.data() + from, n_new, rows_g.data() + from * md,
621 n_new * md, n_new_i, md_i);
623 ++stats.fixed_appends;
627 publish_model_update();
628 return RGPOT_ENGINE_OK;
631 error_out =
"gpr_model_append_fixed_checked on " +
632 std::to_string(n_new) +
634 return RGPOT_ENGINE_ERR_EVAL;
637 if (fixed_refits && !embed_coords && fitted_rows > 0 &&
638 fitted_first != first && !reset_cartesian_model(error_out)) {
639 return RGPOT_ENGINE_ERR_EVAL;
641 const std::size_t n = total - first;
642 if (embed_coords && total > 0) {
644 if (!derive_embed_scale(saddle.x, raw_x, total, scale, error_out)) {
645 return RGPOT_ENGINE_ERR_INVALID;
647 if (!init_embedded_atoms(scale, error_out)) {
648 return RGPOT_ENGINE_ERR_EVAL;
650 rows_x.resize(total * model_dof, 0.0);
651 for (std::size_t i = 0; i < total; ++i) {
652 embed_point(raw_x.data() + i * n_dof,
653 rows_x.data() + i * model_dof);
658 if (!checked_int_count(n, n_i) || !checked_int_count(md, md_i)) {
660 "gpr engine: observation count does not fit in the C API";
661 return RGPOT_ENGINE_ERR_INVALID;
664 model, rows_x.data() + first * md, n * md, rows_e.data() + first, n,
665 rows_g.data() + first * md, n * md, n_i, md_i);
667 error_out =
"gpr_model_train on " + std::to_string(n) +
669 return RGPOT_ENGINE_ERR_EVAL;
673 fitted_first = first;
676 publish_model_update();
677 return RGPOT_ENGINE_OK;
680 int predict(
const double* xs, std::size_t n,
double* energies,
681 double* forces, std::string& error_out)
683 const std::size_t d = n_dof;
684 const std::size_t md = model_dof;
687 if (!checked_mul_size(n, d, nd) || !checked_mul_size(n, md, nmd)) {
688 error_out =
"gpr engine: predict coordinate count overflows";
689 return RGPOT_ENGINE_ERR_INVALID;
691 for (std::size_t i = 0; i < nd; ++i) {
692 if (!std::isfinite(xs[i])) {
693 error_out =
"gpr engine: predict requires finite coordinates";
694 return RGPOT_ENGINE_ERR_INVALID;
697 const int fit_rc = fit(error_out);
698 if (fit_rc != RGPOT_ENGINE_OK)
return fit_rc;
699 std::vector<double> e(n, 0.0);
700 std::vector<double> g_model(nmd, 0.0);
701 if (!rows_e.empty()) {
702 std::vector<double> xs_emb;
703 const double* query_ptr = xs;
705 xs_emb.resize(nmd, 0.0);
707 std::size_t moff = 0;
708 for (std::size_t i = 0; i < n; ++i) {
709 embed_point(xs + off, xs_emb.data() + moff);
713 query_ptr = xs_emb.data();
715 constexpr std::size_t kPredictBlock = 64;
716 std::size_t start = 0;
718 const std::size_t m = std::min(kPredictBlock, n - start);
719 std::size_t block = 0;
720 std::size_t start_md = 0;
721 if (!checked_mul_size(m, md, block) ||
722 !checked_mul_size(start, md, start_md)) {
724 "gpr engine: predict coordinate count overflows";
725 return RGPOT_ENGINE_ERR_INVALID;
728 model, query_ptr + start_md, block, e.data() + start, m,
729 g_model.data() + start_md, block,
nullptr, 0,
nullptr, 0,
730 static_cast<int>(m),
static_cast<int>(md));
732 error_out = std::string(
"gpr_model_predict_batch: ") +
734 return RGPOT_ENGINE_ERR_EVAL;
739 std::vector<double> g_q;
740 std::vector<double> e_out(n, 0.0);
741 std::vector<double> f_out(forces !=
nullptr ? nd : 0, 0.0);
743 std::size_t moff = 0;
744 for (std::size_t i = 0; i < n; ++i) {
746 saddle.energy_gradient(xs + off, e_q, g_q);
747 const double e_tot = e[i] + e_q;
748 if (!std::isfinite(e[i]) || !std::isfinite(e_tot)) {
749 error_out =
"predict: gpridge returned a non-finite energy";
750 return RGPOT_ENGINE_ERR_EVAL;
753 for (std::size_t a = 0; a < d; ++a) {
754 const double gm = g_model[moff + a];
755 const double f_tot = -(gm + g_q[a]);
756 if (!std::isfinite(gm) || !std::isfinite(f_tot)) {
758 "predict: gpridge returned a non-finite gradient";
759 return RGPOT_ENGINE_ERR_EVAL;
761 if (forces !=
nullptr) {
762 f_out[off + a] = f_tot;
768 std::copy(e_out.begin(), e_out.end(), energies);
769 if (forces !=
nullptr) {
770 std::copy(f_out.begin(), f_out.end(), forces);
772 stats.gp_predictions +=
static_cast<unsigned long long>(n);
773 return RGPOT_ENGINE_OK;
776 int predict_variance(
const double* xs, std::size_t xs_len, std::size_t n,
777 double* var_e, std::size_t var_e_len,
double* var_g,
778 std::size_t var_g_len, std::string& error_out)
780 const std::size_t d = n_dof;
781 const std::size_t md = model_dof;
784 if (!checked_mul_size(n, d, nd) || !checked_mul_size(n, md, nmd)) {
785 error_out =
"predict_variance: geometry batch length overflows";
786 return RGPOT_ENGINE_ERR_INVALID;
788 if (xs ==
nullptr || var_e ==
nullptr || var_g ==
nullptr ||
789 xs_len < nd || var_e_len < n || var_g_len < nd) {
790 error_out =
"predict_variance: geometry batch length";
791 return RGPOT_ENGINE_ERR_INVALID;
793 for (std::size_t i = 0; i < nd; ++i) {
794 if (!std::isfinite(xs[i])) {
795 error_out =
"predict_variance: a geometry is not finite";
796 return RGPOT_ENGINE_ERR_INVALID;
799 if (rows_e.empty()) {
800 error_out =
"predict_variance: the process has no observations";
801 return RGPOT_ENGINE_ERR_EVAL;
803 const int fit_rc = fit(error_out);
804 if (fit_rc != RGPOT_ENGINE_OK)
return fit_rc;
805 std::vector<double> xs_emb;
806 const double* query_ptr = xs;
808 xs_emb.resize(nmd, 0.0);
810 std::size_t moff = 0;
811 for (std::size_t i = 0; i < n; ++i) {
812 embed_point(xs + off, xs_emb.data() + moff);
816 query_ptr = xs_emb.data();
818 std::vector<double> mean_e(n, 0.0);
819 std::vector<double> mean_g(nmd, 0.0);
820 std::vector<double> var_g_model(nmd, 0.0);
821 constexpr std::size_t kPredictBlock = 64;
822 std::size_t start = 0;
824 const std::size_t m =
825 (n - start < kPredictBlock) ? (n - start) : kPredictBlock;
826 std::size_t block = 0;
827 std::size_t start_md = 0;
828 if (!checked_mul_size(m, md, block) ||
829 !checked_mul_size(start, md, start_md)) {
830 error_out =
"predict_variance: geometry batch length overflows";
831 return RGPOT_ENGINE_ERR_INVALID;
834 model, query_ptr + start_md, block, mean_e.data() + start, m,
835 mean_g.data() + start_md, block, var_e + start, m,
836 var_g_model.data() + start_md, block,
static_cast<int>(m),
837 static_cast<int>(md));
839 error_out = std::string(
"gpr_model_predict_batch_checked: ") +
841 return RGPOT_ENGINE_ERR_EVAL;
846 std::size_t moff = 0;
847 for (std::size_t i = 0; i < n; ++i) {
848 if (!std::isfinite(var_e[i]) || var_e[i] < 0.0) {
850 "predict_variance: gpridge returned a negative or "
851 "non-finite variance";
852 return RGPOT_ENGINE_ERR_EVAL;
854 for (std::size_t a = 0; a < d; ++a) {
855 const double vg = var_g_model[moff + a];
856 if (!std::isfinite(vg) || vg < 0.0) {
858 "predict_variance: gpridge returned a negative "
859 "or non-finite variance";
860 return RGPOT_ENGINE_ERR_EVAL;
867 return RGPOT_ENGINE_OK;
870 int hessian(
const double*
x, std::size_t x_len,
double* h_out,
871 std::size_t h_len, std::string& error_out)
873 if (refuse_true_hill_curvature(error_out)) {
874 return RGPOT_ENGINE_ERR_UNSUPPORTED;
877 if (!checked_mul_size(n_dof, n_dof, dd)) {
878 error_out =
"gpr engine: hessian coordinate count overflows";
879 return RGPOT_ENGINE_ERR_INVALID;
881 if (
x ==
nullptr || h_out ==
nullptr || x_len < n_dof || h_len < dd) {
882 error_out =
"gpr engine: invalid buffer length for hessian";
883 return RGPOT_ENGINE_ERR_INVALID;
885 for (std::size_t i = 0; i < n_dof; ++i) {
886 if (!std::isfinite(
x[i])) {
887 error_out =
"gpr engine: hessian requires finite coordinates";
888 return RGPOT_ENGINE_ERR_INVALID;
891 const int fit_rc = fit(error_out);
892 if (fit_rc != RGPOT_ENGINE_OK)
return fit_rc;
893 const std::size_t d = n_dof;
894 const std::size_t md = model_dof;
895 std::fill(h_out, h_out + dd, 0.0);
896 if (!rows_e.empty()) {
899 model,
x, x_len, h_out, h_len,
static_cast<int>(d));
901 error_out = std::string(
"gpr_model_predict_hessian: ") +
903 return RGPOT_ENGINE_ERR_EVAL;
906 std::vector<double> r_emb(md, 0.0);
907 embed_point(
x, r_emb.data());
909 if (!checked_mul_size(md, md, md2)) {
911 "gpr engine: hessian coordinate count overflows";
912 return RGPOT_ENGINE_ERR_INVALID;
914 std::vector<double> h_emb(md2, 0.0);
916 model, r_emb.data(), r_emb.size(), h_emb.data(),
917 h_emb.size(),
static_cast<int>(md));
919 error_out = std::string(
"gpr_model_predict_hessian: ") +
921 return RGPOT_ENGINE_ERR_EVAL;
923 for (std::size_t r = 0; r < d; ++r) {
924 for (std::size_t c = 0; c < d; ++c) {
925 h_out[r * d + c] = h_emb[r * md + c];
930 std::vector<double> h_tot(dd, 0.0);
931 for (std::size_t k = 0; k < dd; ++k) {
932 const double hk = h_out[k] + saddle.h[k];
933 if (!std::isfinite(h_out[k]) || !std::isfinite(hk)) {
934 error_out =
"hessian: gpridge returned a non-finite Hessian";
935 return RGPOT_ENGINE_ERR_EVAL;
939 std::copy(h_tot.begin(), h_tot.end(), h_out);
941 return RGPOT_ENGINE_OK;
944 int prediction_supported(
const double*
x, std::size_t x_len,
945 int* supported_out, std::string& error_out)
947 if (
x ==
nullptr || supported_out ==
nullptr || x_len < n_dof) {
949 "gpr engine: invalid buffer length for prediction_supported";
950 return RGPOT_ENGINE_ERR_INVALID;
952 for (std::size_t i = 0; i < n_dof; ++i) {
953 if (!std::isfinite(
x[i])) {
955 "gpr engine: prediction_supported requires finite "
957 return RGPOT_ENGINE_ERR_INVALID;
960 const int fit_rc = fit(error_out);
961 if (fit_rc != RGPOT_ENGINE_OK)
return fit_rc;
962 if (rows_e.empty()) {
964 return RGPOT_ENGINE_OK;
967 std::vector<double> r_emb;
968 const double* query_ptr =
x;
969 std::size_t query_len = x_len;
971 r_emb.resize(model_dof, 0.0);
972 embed_point(
x, r_emb.data());
973 query_ptr = r_emb.data();
974 query_len = r_emb.size();
977 model, query_ptr, query_len,
static_cast<int>(model_dof), &sup);
980 std::string(
"gpr_model_prediction_supported_checked: ") +
982 return RGPOT_ENGINE_ERR_EVAL;
984 *supported_out = sup;
985 return RGPOT_ENGINE_OK;
988 int hessian_action(
const double*
x, std::size_t x_len,
const double* v,
989 std::size_t v_len,
double* hv_out, std::size_t hv_len,
990 unsigned long long* ops_out,
double* scale_out,
991 std::string& error_out)
993 if (refuse_true_hill_curvature(error_out)) {
994 return RGPOT_ENGINE_ERR_UNSUPPORTED;
996 const std::size_t d = n_dof;
997 const std::size_t md = model_dof;
998 if (
x ==
nullptr || v ==
nullptr || hv_out ==
nullptr || x_len < d ||
999 v_len < d || hv_len < d) {
1000 error_out =
"gpridge directional length";
1001 return RGPOT_ENGINE_ERR_INVALID;
1003 for (std::size_t i = 0; i < d; ++i) {
1004 if (!std::isfinite(
x[i]) || !std::isfinite(v[i])) {
1006 "gpr engine: hessian_action requires finite coordinates "
1008 return RGPOT_ENGINE_ERR_INVALID;
1011 const int fit_rc = fit(error_out);
1012 if (fit_rc != RGPOT_ENGINE_OK)
return fit_rc;
1014 std::vector<double> hv(d, 0.0);
1015 unsigned long long ops = 0;
1017 if (!rows_e.empty()) {
1018 std::vector<double> r_emb;
1019 std::vector<double> v_emb;
1020 const double* x_ptr =
x;
1021 std::size_t x_qlen = x_len;
1022 const double* v_ptr = v;
1023 std::size_t v_qlen = v_len;
1025 r_emb.resize(md, 0.0);
1026 v_emb.resize(md, 0.0);
1027 embed_point(
x, r_emb.data());
1028 embed_direction(v, v_emb.data());
1029 x_ptr = r_emb.data();
1030 x_qlen = r_emb.size();
1031 v_ptr = v_emb.data();
1032 v_qlen = v_emb.size();
1036 model, x_ptr, x_qlen,
static_cast<int>(md), &supported);
1039 std::string(
"gpr_model_prediction_supported_checked: ") +
1041 return RGPOT_ENGINE_ERR_EVAL;
1043 if (supported == 0) {
1045 "gpridge prediction query is outside kernel support";
1048 std::vector<double> hv_model(md, 0.0);
1050 model, x_ptr, x_qlen, v_ptr, v_qlen, hv_model.data(),
1051 hv_model.size(),
static_cast<int>(md));
1054 std::string(
"gpr_model_predict_hessian_action_checked: ") +
1056 return RGPOT_ENGINE_ERR_EVAL;
1058 project_vector(hv_model.data(), hv.data());
1059 for (std::size_t i = 0; i < d; ++i) {
1060 if (!std::isfinite(hv[i])) {
1062 "hessian_action: gpridge returned a non-finite "
1064 return RGPOT_ENGINE_ERR_EVAL;
1067 ++stats.gp_hessians;
1068 unsigned long long action_ops = 0;
1069 if (!sexpat_action_ops(rows_e.size(), md, action_ops) ||
1070 !checked_add_u64(ops, action_ops, ops)) {
1071 error_out =
"gpridge directional operation count wrapped";
1072 return RGPOT_ENGINE_ERR_EVAL;
1074 for (std::size_t i = 0; i < d; ++i) {
1075 scale = std::max(scale, std::abs(hv[i]));
1078 for (std::size_t row = 0; row < d; ++row) {
1080 for (std::size_t column = 0; column < d; ++column) {
1081 const double term = saddle.h[row * d + column] * v[column];
1083 scale = std::max(scale, std::abs(term));
1084 if (!checked_add_u64(ops, 2, ops)) {
1085 error_out =
"gpridge directional operation count wrapped";
1086 return RGPOT_ENGINE_ERR_EVAL;
1090 scale = std::max(scale, std::abs(hv[row]));
1091 if (!checked_add_u64(ops, 1, ops)) {
1092 error_out =
"gpridge directional operation count wrapped";
1093 return RGPOT_ENGINE_ERR_EVAL;
1096 if (!std::isfinite(scale)) {
1098 "hessian_action: gpridge returned a non-finite Hessian action";
1099 return RGPOT_ENGINE_ERR_EVAL;
1101 for (std::size_t row = 0; row < d; ++row) {
1102 if (!std::isfinite(hv[row])) {
1104 "hessian_action: gpridge returned a non-finite "
1106 return RGPOT_ENGINE_ERR_EVAL;
1109 std::copy(hv.begin(), hv.end(), hv_out);
1110 if (ops_out !=
nullptr) *ops_out = ops;
1111 if (scale_out !=
nullptr) *scale_out = scale;
1112 return RGPOT_ENGINE_OK;
1119 std::shared_ptr<gpr::neb::ActiveLearningSession>
session;
1144 long n_atoms,
const double* positions,
1145 const int* atomic_nrs)
1148 std::vector<int> unique_species;
1149 std::vector<int> species_index(
static_cast<std::size_t
>(n), 0);
1151 const int z = atomic_nrs !=
nullptr ? atomic_nrs[i] : 1;
1152 auto found = std::find(unique_species.begin(), unique_species.end(),
z);
1153 if (found == unique_species.end()) {
1154 species_index[i] =
static_cast<int>(unique_species.size());
1155 unique_species.push_back(
z);
1158 static_cast<int>(std::distance(unique_species.begin(), found));
1165 cfg.
positions(0, i) = positions !=
nullptr ? positions[i] : 0.0;
1169 cfg.
id.resize(1, n);
1171 cfg.
type.resize(1, n);
1173 cfg.
id(0, i) =
static_cast<int>(i);
1174 cfg.
atomicNrs(0, i) = atomic_nrs !=
nullptr ? atomic_nrs[i] : 1;
1175 cfg.
type(0, i) = species_index[
static_cast<std::size_t
>(i)];
1187 cfg.
pairtype.resize(n_species, n_species);
1205 long n_atoms,
const double* positions,
1206 const int* atomic_nrs)
1208 if (
pot->surrogate)
return true;
1209 if (
pot->nested_oracle !=
nullptr && !
pot->callbacks_set) {
1212 if (
pot->surrogate ==
nullptr) {
1213 pot->surrogate = std::make_unique<pot::ActiveGP>(
1214 pot->session,
pot->nested_oracle->asOracle(),
pot->config);
1218 if (!
pot->callbacks_set ||
pot->callbacks.oracle ==
nullptr) {
1220 "gpr engine: no oracle; call rgpot_engine_set_callbacks first");
1223 if (!
pot->session_configured) {
1226 "gpr engine: cannot configure the model without a system");
1230 configureSessionForSystem(*
pot->session, n_atoms, positions,
1232 pot->session_configured =
true;
1233 }
catch (
const std::exception& e) {
1238 RgpotEngineCallbacks cb =
pot->callbacks;
1239 auto oracle = [cb](
long n_atoms,
const double* positions,
1240 const int* atomic_nrs,
const double* box,
double* energy,
1241 double* forces) ->
int {
1242 return cb.oracle(cb.ctx, n_atoms, positions, atomic_nrs, forces, energy,
1246 pot->surrogate = std::make_unique<pot::ActiveGP>(
1247 pot->session, std::move(oracle),
pot->config);
1248 }
catch (
const std::exception& e) {
1252 if (cb.on_acquire !=
nullptr) {
1253 pot->surrogate->setAcquireHook(
1255 rgpot_engine_acquire_reason r = RGPOT_ACQUIRE_VARIANCE;
1258 r = RGPOT_ACQUIRE_CERTIFY;
1261 r = RGPOT_ACQUIRE_BATCH;
1264 r = RGPOT_ACQUIRE_REJECT;
1269 cb.on_acquire(cb.ctx, r);
1272 if (cb.on_model_update !=
nullptr) {
1273 pot->surrogate->setModelUpdateHook(
1274 [cb](std::uint64_t
epoch) { cb.on_model_update(cb.ctx,
epoch); });
1285 "gpr engine: residual prior config shorter than header");
1289 std::memcpy(&hdr, config,
sizeof(hdr));
1292 "gpr engine: unsupported residual prior config version");
1297 "gpr engine: residual prior requires positive n_atoms");
1302 "gpr engine: residual prior n_coords must be non-negative");
1322 "gpr engine: residual prior hyperparameters must be finite");
1327 const auto reject_overflow = [&]() {
1329 "gpr engine: residual prior config size overflows");
1334 d =
static_cast<std::size_t
>(hdr.
n_coords);
1335 }
else if (!checked_mul_size(
static_cast<std::size_t
>(hdr.
n_atoms), 3, d)) {
1336 return reject_overflow();
1341 "gpr engine: residual prior requires positive coordinate count");
1344 const bool direct_cartesian =
1345 (d >= 6 && d % 3 == 0 &&
static_cast<long>(d / 3) == hdr.
n_atoms);
1346 const std::size_t moving_atoms = direct_cartesian
1347 ?
static_cast<std::size_t
>(hdr.
n_atoms)
1348 : d / 3 + (d % 3 != 0 ? 1 : 0);
1349 std::size_t model_atoms = moving_atoms;
1350 if (!direct_cartesian &&
1351 !checked_add_size(moving_atoms, ResidualSession::kEmbedAnchors,
1353 return reject_overflow();
1355 if (
static_cast<std::size_t
>(hdr.
n_atoms) != model_atoms) {
1356 set_err(errbuf, errlen,
1357 "gpr engine: residual prior n_atoms does not match coordinate "
1361 const std::size_t g_doubles = hdr.
has_gradient != 0 ? d : 0;
1362 std::size_t hessian_doubles = 0;
1363 std::size_t payload_doubles = 0;
1364 std::size_t payload_bytes = 0;
1365 std::size_t atomic_nrs_bytes = 0;
1366 std::size_t expected_bytes = 0;
1367 if (!checked_mul_size(d, d, hessian_doubles) ||
1368 !checked_add_size(d, g_doubles, payload_doubles) ||
1369 !checked_add_size(payload_doubles, hessian_doubles, payload_doubles) ||
1370 !checked_mul_size(payload_doubles,
sizeof(
double), payload_bytes) ||
1372 !checked_mul_size(model_atoms,
sizeof(
int), atomic_nrs_bytes)) ||
1375 !checked_add_size(expected_bytes, atomic_nrs_bytes, expected_bytes)) {
1376 return reject_overflow();
1380 "gpr engine: residual prior config length mismatch");
1384 const auto* payload =
reinterpret_cast<const double*
>(
1385 static_cast<const unsigned char*
>(config) +
1387 for (std::size_t i = 0; i < payload_doubles; ++i) {
1388 if (!std::isfinite(payload[i])) {
1390 "gpr engine: residual prior saddle state must be finite");
1395 auto res = std::make_unique<ResidualSession>();
1396 res->n_atoms =
static_cast<long>(model_atoms);
1398 res->embed_coords = !direct_cartesian;
1399 res->model_dof = moving_atoms * 3;
1403 res->saddle.x.assign(payload, payload + d);
1406 res->saddle.g.assign(payload + d, payload + 2 * d);
1408 res->saddle.g.assign(d, 0.0);
1410 const double* h_ptr = payload + d + g_doubles;
1411 res->saddle.h.assign(h_ptr, h_ptr + d * d);
1414 const auto* z_ptr =
reinterpret_cast<const int*
>(
1415 reinterpret_cast<const unsigned char*
>(payload) +
1416 payload_doubles *
sizeof(double));
1417 std::vector<int> unique_species;
1418 res->atomic_nrs.assign(z_ptr, z_ptr + model_atoms);
1419 res->atom_types.assign(model_atoms, 0);
1420 for (std::size_t i = 0; i < model_atoms; ++i) {
1421 const int z = z_ptr[i];
1424 "gpr engine: atomic_nrs must be positive");
1428 std::find(unique_species.begin(), unique_species.end(),
z);
1429 if (it == unique_species.end()) {
1430 res->atom_types[i] =
static_cast<int>(unique_species.size());
1431 unique_species.push_back(
z);
1433 res->atom_types[i] =
1434 static_cast<int>(std::distance(unique_species.begin(), it));
1456 res->model_cfg = mcfg;
1458 if (direct_cartesian) {
1459 if (!res->atomic_nrs.empty()) {
1468 if (res->atoms ==
nullptr) {
1473 if (res->model ==
nullptr) {
1483 pot->residual = std::move(res);
1490bool residual_callback_scratch(std::size_t n_atoms, std::size_t n_dof,
1491 std::size_t n_sys,
const double* packed,
1493 std::vector<double>& cartesian,
1494 std::string& error_out,
bool batch)
1496 std::size_t cart_count = 0;
1497 if (!checked_mul_size(n_atoms, 3, cart) || cart < n_dof ||
1498 !checked_mul_size(cart, n_sys, cart_count)) {
1499 error_out = batch ?
"gpr engine: force_batch coordinate count overflows"
1500 :
"gpr engine: force coordinate count overflows";
1503 cartesian.assign(cart_count, 0.0);
1504 for (std::size_t s = 0; s < n_sys; ++s) {
1505 const double* src = packed + s * n_dof;
1506 double* dst = cartesian.data() + s * cart;
1507 std::copy(src, src + n_dof, dst);
1512void residual_pack_prefix(
const std::vector<double>& cartesian,
1513 std::size_t n_sys, std::size_t n_dof,
1514 std::size_t cart, std::vector<double>& packed)
1516 packed.resize(n_sys * n_dof);
1517 for (std::size_t s = 0; s < n_sys; ++s) {
1518 const double* src = cartesian.data() + s * cart;
1519 std::copy(src, src + n_dof, packed.data() + s * n_dof);
1523bool oracle_sample_finite(
const double* energy,
const double* forces,
1524 std::size_t n_force, std::string& error_out)
1526 if (energy ==
nullptr || !std::isfinite(*energy)) {
1527 error_out =
"gpr engine: oracle energy is not finite";
1530 if (forces !=
nullptr) {
1531 for (std::size_t i = 0; i < n_force; ++i) {
1532 if (!std::isfinite(forces[i])) {
1533 error_out =
"gpr engine: oracle force is not finite";
1547 return RGPOT_ENGINE_ABI_VERSION;
1552 if (stamp ==
nullptr)
return 0;
1553 return stamp->abi_major == RGPOT_ENGINE_ABI_VERSION &&
1554 stamp->layout_revision == RGPOT_ENGINE_ABI_LAYOUT_REVISION &&
1555 RGPOT_ENGINE_ABI_MINOR <= stamp->abi_minor
1577 auto pot = std::make_unique<RgpotEnginePot>();
1578 pot->session = std::make_shared<gpr::neb::ActiveLearningSession>();
1582 std::memcpy(&magic, config,
sizeof(
unsigned));
1589 return pot.release();
1591#ifdef GPR_ENGINE_HAS_POTENTIAL_SPEC
1598 magic != RGPOT_ENGINE_GPR_GATE_MAGIC) {
1600 const kj::ArrayPtr<const capnp::word> words(
1601 reinterpret_cast<const capnp::word*
>(config),
1603 capnp::FlatArrayMessageReader reader(words);
1604 const auto params = reader.getRoot<::GprParams>();
1606 if (params.getSigmaLoFactor() > 0.0)
1607 pot->config.sigma_lo_factor = params.getSigmaLoFactor();
1608 if (params.getSigmaHiFactor() > 0.0)
1609 pot->config.sigma_hi_factor = params.getSigmaHiFactor();
1610 pot->config.certify_below_force =
1611 params.getCertifyBelowForce();
1612 pot->config.refit_training_revisions =
1613 params.getRefitTrainingRevisions();
1614 if (!(
pot->config.sigma_hi_factor >=
1615 pot->config.sigma_lo_factor)) {
1617 "gpr engine: need sigmaLoFactor <= "
1622 std::string library, oerr;
1623 std::vector<unsigned char> ocfg;
1624 if (!oracleFromSpec(params.getOracle(), library, ocfg,
1627 (
"gpr engine: " + oerr).c_str());
1630 pot->nested_oracle =
1632 if (
pot->nested_oracle ==
nullptr) {
1634 (
"gpr engine: oracle " + oerr).c_str());
1637 return pot.release();
1638 }
catch (
const kj::Exception&) {
1646 "gpr engine: config is neither an "
1647 "RgpotEngineGprGate nor a GprParams message");
1652 if (
config_len !=
sizeof(RgpotEngineGprGate)) {
1654 "gpr engine: config is neither an RgpotEngineGprGate "
1655 "nor a GprParams message");
1658 RgpotEngineGprGate gate{};
1659 std::memcpy(&gate, config,
sizeof(gate));
1660 if (gate.magic != RGPOT_ENGINE_GPR_GATE_MAGIC) {
1664 if (gate.version != RGPOT_ENGINE_GPR_GATE_VERSION) {
1666 "gpr engine: unsupported config "
1670 if (!(gate.sigmaLoFactor > 0.0) || !(gate.sigmaHiFactor > 0.0) ||
1671 gate.sigmaHiFactor < gate.sigmaLoFactor) {
1673 "gpr engine: need 0 < sigmaLoFactor <= sigmaHiFactor");
1676 pot->config.sigma_lo_factor = gate.sigmaLoFactor;
1677 pot->config.sigma_hi_factor = gate.sigmaHiFactor;
1678 pot->config.certify_below_force = gate.certifyBelowForce;
1679 pot->config.refit_training_revisions =
1680 static_cast<std::uint64_t
>(gate.refitTrainingRevisions);
1682 return pot.release();
1683 }
catch (
const std::exception& e) {
1695 const RgpotEngineCallbacks* callbacks)
1697 if (
pot ==
nullptr || callbacks ==
nullptr)
return -1;
1698 if (callbacks->oracle ==
nullptr)
return -1;
1699 pot->callbacks = *callbacks;
1700 pot->callbacks_set =
true;
1701 if (
pot->residual) {
1702 pot->residual->model_update = callbacks->on_model_update;
1703 pot->residual->model_update_ctx = callbacks->ctx;
1705 pot->surrogate.reset();
1711 if (
pot ==
nullptr)
return 0;
1712 if (
pot->residual)
return pot->residual->epoch;
1713 if (!
pot->surrogate)
return 0;
1714 return pot->surrogate->modelState();
1719 if (
pot ==
nullptr)
return 0;
1720 const std::size_t full =
pot->last_error.size();
1721 if (buf !=
nullptr && len > 0) {
1722 const std::size_t copied = std::min(full, len - 1);
1723 std::memcpy(buf,
pot->last_error.data(), copied);
1731 if (
pot ==
nullptr ||
out ==
nullptr ||
out->size <
sizeof(
unsigned))
1732 return RGPOT_ENGINE_ERR_INVALID;
1733 RgpotEngineCaps caps{};
1734 caps.size =
sizeof(RgpotEngineCaps);
1735 caps.reentrancy = 1;
1736 caps.per_image_instances = 0;
1740 caps.group_collective = 0;
1741 caps.orbital_selection = 0;
1742 caps.orbital_copy = 0;
1743 caps.analytic_hvp =
pot->residual !=
nullptr ? 1 : 0;
1744 const unsigned n =
out->size <
sizeof(RgpotEngineCaps)
1746 :
sizeof(RgpotEngineCaps);
1747 std::memcpy(
out, &caps, n);
1749 return RGPOT_ENGINE_OK;
1759 return "gpr/" GPRIDGE_VERSION;
1766 if (buf !=
nullptr && len > 0) buf[0] =
'\0';
1773 if (
pot ==
nullptr)
return RGPOT_ENGINE_ERR_INVALID;
1774 if (intra_op < 1 && inter_op < 1) {
1775 pot->last_error.clear();
1776 return RGPOT_ENGINE_OK;
1778 pot->last_error =
"gpr engine: backend has no tensor runtime";
1779 return RGPOT_ENGINE_ERR_UNSUPPORTED;
1785 if (
pot ==
nullptr || spin < 1)
return RGPOT_ENGINE_ERR_INVALID;
1786 pot->last_error =
"gpr engine: charge/spin state is unsupported";
1787 return RGPOT_ENGINE_ERR_UNSUPPORTED;
1793 if (
pot ==
nullptr)
return RGPOT_ENGINE_ERR_INVALID;
1794 pot->last_error =
"gpr engine: backend has no orbital selection";
1795 return RGPOT_ENGINE_ERR_UNSUPPORTED;
1803 if (
pot ==
nullptr)
return RGPOT_ENGINE_ERR_INVALID;
1804 pot->last_error =
"gpr engine: backend has no orbital copy";
1805 return RGPOT_ENGINE_ERR_UNSUPPORTED;
1809 RgpotEngineNeighborOptions* opts,
1819 const int* atomicNrs,
const double* direction,
1820 double* hv_out,
const double* box)
1822 if (
pot ==
nullptr)
return RGPOT_ENGINE_ERR_INVALID;
1823 if (!
pot->residual) {
1825 "gpr engine: analytic HVP requires a configured residual session";
1826 return RGPOT_ENGINE_ERR_UNSUPPORTED;
1828 if (positions ==
nullptr || atomicNrs ==
nullptr || direction ==
nullptr ||
1829 hv_out ==
nullptr || box ==
nullptr || nAtoms <= 0 ||
1830 nAtoms !=
pot->residual->n_atoms) {
1831 pot->last_error =
"gpr engine: invalid HVP argument";
1832 return RGPOT_ENGINE_ERR_INVALID;
1834 for (
long i = 0; i < nAtoms; ++i) {
1835 if (atomicNrs[i] <= 0) {
1836 pot->last_error =
"gpr engine: invalid atomic number in HVP";
1837 return RGPOT_ENGINE_ERR_INVALID;
1840 const std::size_t d =
pot->residual->n_dof;
1841 std::size_t coord_bytes = 0;
1842 std::size_t atomic_bytes = 0;
1843 if (!checked_mul_size(d,
sizeof(
double), coord_bytes) ||
1844 !checked_mul_size(
static_cast<std::size_t
>(nAtoms),
sizeof(
int),
1846 pot->last_error =
"gpr engine: HVP coordinate count overflows";
1847 return RGPOT_ENGINE_ERR_INVALID;
1849 const auto hb =
reinterpret_cast<std::uintptr_t
>(hv_out);
1850 const auto bytes =
static_cast<std::uintptr_t
>(coord_bytes);
1851 const auto overlaps = [hb, bytes](
const void* input,
1852 std::uintptr_t input_bytes) {
1853 const auto begin =
reinterpret_cast<std::uintptr_t
>(input);
1854 return hb < begin + input_bytes && begin < hb + bytes;
1856 if (overlaps(direction, bytes) || overlaps(positions, bytes) ||
1857 overlaps(atomicNrs,
static_cast<std::uintptr_t
>(atomic_bytes)) ||
1858 overlaps(box, 9 *
sizeof(
double))) {
1859 pot->last_error =
"gpr engine: HVP output overlaps an input buffer";
1860 return RGPOT_ENGINE_ERR_INVALID;
1863 const int rc =
pot->residual->hessian_action(
1864 positions, d, direction, d, hv_out, d,
nullptr,
nullptr, err);
1865 if (rc != RGPOT_ENGINE_OK) {
1866 pot->last_error = err;
1869 pot->last_error.clear();
1870 return RGPOT_ENGINE_OK;
1871}
catch (
const std::bad_alloc&) {
1873 pot->last_error =
"gpr engine: HVP coordinate count overflows";
1874 return RGPOT_ENGINE_ERR_INVALID;
1875}
catch (
const std::length_error&) {
1877 pot->last_error =
"gpr engine: HVP coordinate count overflows";
1878 return RGPOT_ENGINE_ERR_INVALID;
1879}
catch (
const std::exception& ex) {
1880 if (
pot !=
nullptr)
pot->last_error = ex.what();
1887 if (
pot ==
nullptr || stats_out ==
nullptr || stats_out->
struct_size == 0) {
1888 return RGPOT_ENGINE_ERR_INVALID;
1892 if (
pot->residual) {
1893 current =
pot->residual->stats;
1894 }
else if (
pot->surrogate) {
1896 static_cast<unsigned long long>(
pot->surrogate->oracleCalls());
1898 static_cast<unsigned long long>(
pot->surrogate->oracleCalls());
1900 static_cast<unsigned long long>(
pot->surrogate->trainingSize());
1901 current.
fits =
pot->surrogate->modelState();
1903 const std::size_t room =
1905 std::memcpy(stats_out, ¤t, room);
1907 return RGPOT_ENGINE_OK;
1911 const double* positions,
const int* atomicNrs,
1912 double* forces,
double* energy,
double* variance,
1914 rgpot_engine_coord_transform transform,
1915 void* transform_user)
1917 if (
pot ==
nullptr || positions ==
nullptr || energy ==
nullptr ||
1921 if (
pot->residual) {
1922 if (nAtoms !=
pot->residual->n_atoms) {
1923 pot->last_error =
"gpr engine: nAtoms mismatch with saddle";
1924 return RGPOT_ENGINE_ERR_INVALID;
1926 const std::size_t d =
pot->residual->n_dof;
1927 std::size_t cart = 0;
1928 std::vector<double> R;
1929 std::string scratch_err;
1930 if (!residual_callback_scratch(
static_cast<std::size_t
>(nAtoms), d, 1,
1931 positions, cart, R, scratch_err,
1933 pot->last_error = scratch_err;
1934 return RGPOT_ENGINE_ERR_INVALID;
1936 std::vector<double> cell(9, 0.0);
1937 if (box !=
nullptr) std::copy(box, box + 9, cell.begin());
1938 if (transform !=
nullptr) {
1940 transform(transform_user, nAtoms, R.data(), cell.data());
1941 if (rc != 0)
return rc;
1943 std::vector<double> geom;
1944 residual_pack_prefix(R, 1, d, cart, geom);
1951 if (variance !=
nullptr && !
pot->residual->rows_e.empty()) {
1952 std::vector<double> var_g(d);
1953 const int vrc =
pot->residual->predict_variance(
1954 geom.data(), d, 1, variance, 1, var_g.data(), d, err);
1955 if (vrc != RGPOT_ENGINE_OK) {
1956 pot->last_error = err;
1961 pot->residual->predict(geom.data(), 1, energy, forces, err);
1962 if (rc != RGPOT_ENGINE_OK) {
1963 pot->last_error = err;
1966 if (variance !=
nullptr &&
pot->residual->rows_e.empty()) {
1969 pot->last_error.clear();
1970 return RGPOT_ENGINE_OK;
1972 if (!
pot->callbacks_set ||
pot->callbacks.oracle ==
nullptr) {
1974 "gpr engine: no oracle; call rgpot_engine_set_callbacks first";
1975 return RGPOT_ENGINE_ERR_INVALID;
1977 std::vector<double> f_scratch;
1978 double* f_oracle =
nullptr;
1979 if (forces !=
nullptr) {
1980 f_scratch.assign(cart, 0.0);
1981 f_oracle = f_scratch.data();
1983 const int rc =
pot->callbacks.oracle(
1984 pot->callbacks.ctx, nAtoms, R.data(), atomicNrs, f_oracle, energy,
1985 box !=
nullptr ? cell.data() :
nullptr);
1986 if (rc != 0)
return rc;
1987 std::string finite_err;
1988 if (!oracle_sample_finite(energy, f_oracle, cart, finite_err)) {
1989 pot->last_error = finite_err;
1990 return RGPOT_ENGINE_ERR_INVALID;
1992 pot->residual->stats.true_energy_calls += 1;
1993 if (forces !=
nullptr) {
1994 pot->residual->stats.true_gradient_calls += 1;
1996 if (forces !=
nullptr && !
pot->residual->hill_from_oracle()) {
1997 std::vector<double> grad(d);
1998 for (std::size_t i = 0; i < d; ++i)
1999 grad[i] = -f_scratch[i];
2001 if (!
pot->residual->learn(geom.data(), 1, energy, grad.data(),
2003 pot->last_error = err;
2004 return RGPOT_ENGINE_ERR_INVALID;
2007 if (forces !=
nullptr) {
2008 std::copy(f_scratch.data(), f_scratch.data() + d, forces);
2010 if (variance !=
nullptr) *variance = 0.0;
2011 pot->last_error.clear();
2012 return RGPOT_ENGINE_OK;
2014 if (forces ==
nullptr)
return -1;
2015 char err[512] = {0};
2016 if (!ensure_surrogate(
pot, err,
sizeof err, nAtoms, positions, atomicNrs)) {
2017 pot->last_error = err;
2018 std::fprintf(stderr,
"rgpot_engine_force(gpr): %s\n", err);
2021 const std::size_t n_atoms =
static_cast<std::size_t
>(nAtoms);
2022 std::size_t stride = 0;
2023 if (!checked_mul_size(n_atoms, 3, stride)) {
2024 pot->last_error =
"gpr engine: force coordinate count overflows";
2025 return RGPOT_ENGINE_ERR_INVALID;
2027 std::vector<double> R(positions, positions + stride);
2028 std::vector<double> cell(9, 0.0);
2029 if (box !=
nullptr) std::copy(box, box + 9, cell.begin());
2030 if (transform !=
nullptr) {
2031 const int rc = transform(transform_user, nAtoms, R.data(), cell.data());
2032 if (rc != 0)
return rc;
2035 return pot->surrogate->force(nAtoms, R.data(), atomicNrs, forces,
2037 box !=
nullptr ? cell.data() :
nullptr);
2038 }
catch (
const std::exception& e) {
2039 pot->last_error = e.what();
2040 std::fprintf(stderr,
"rgpot_engine_force(gpr): %s\n", e.what());
2043}
catch (
const std::bad_alloc&) {
2045 pot->last_error =
"gpr engine: force coordinate count overflows";
2046 return RGPOT_ENGINE_ERR_INVALID;
2047}
catch (
const std::length_error&) {
2049 pot->last_error =
"gpr engine: force coordinate count overflows";
2050 return RGPOT_ENGINE_ERR_INVALID;
2051}
catch (
const std::exception& ex) {
2052 if (
pot !=
nullptr)
pot->last_error = ex.what();
2053 std::fprintf(stderr,
"rgpot_engine_force(gpr): %s\n", ex.what());
2058 const double* positions,
const int* atomicNrs,
2059 double* forces,
double* energies,
2060 double* variances,
const double* boxes,
2061 rgpot_engine_coord_transform transform,
2062 void* transform_user)
2064 if (
pot ==
nullptr || positions ==
nullptr || energies ==
nullptr ||
2065 nSystems <= 0 || nAtoms <= 0) {
2068 if (
pot->residual) {
2069 if (nAtoms !=
pot->residual->n_atoms) {
2070 pot->last_error =
"gpr engine: nAtoms mismatch with saddle";
2071 return RGPOT_ENGINE_ERR_INVALID;
2073 const std::size_t d =
pot->residual->n_dof;
2074 const std::size_t n_sys =
static_cast<std::size_t
>(nSystems);
2075 std::size_t packed = 0;
2076 std::size_t cell_count = 0;
2077 if (!checked_mul_size(d, n_sys, packed) ||
2078 !checked_mul_size(
static_cast<std::size_t
>(9), n_sys, cell_count)) {
2080 "gpr engine: force_batch coordinate count overflows";
2081 return RGPOT_ENGINE_ERR_INVALID;
2083 std::size_t cart = 0;
2084 std::vector<double> R;
2085 std::string scratch_err;
2086 if (!residual_callback_scratch(
static_cast<std::size_t
>(nAtoms), d,
2087 n_sys, positions, cart, R, scratch_err,
2089 pot->last_error = scratch_err;
2090 return RGPOT_ENGINE_ERR_INVALID;
2092 std::vector<double> cells(cell_count, 0.0);
2093 if (boxes !=
nullptr) {
2094 std::copy(boxes, boxes + cell_count, cells.begin());
2096 if (transform !=
nullptr) {
2097 std::size_t coord_off = 0;
2098 std::size_t cell_off = 0;
2099 for (
long s = 0; s < nSystems; ++s) {
2101 transform(transform_user, nAtoms, R.data() + coord_off,
2102 cells.data() + cell_off);
2103 if (rc != 0)
return rc;
2108 std::vector<double> geom;
2109 residual_pack_prefix(R, n_sys, d, cart, geom);
2114 if (variances !=
nullptr && !
pot->residual->rows_e.empty()) {
2115 std::vector<double> var_g(packed);
2116 const int vrc =
pot->residual->predict_variance(
2117 geom.data(), packed, n_sys, variances, n_sys, var_g.data(),
2119 if (vrc != RGPOT_ENGINE_OK) {
2120 pot->last_error = err;
2124 const int rc =
pot->residual->predict(geom.data(), n_sys, energies,
2126 if (rc != RGPOT_ENGINE_OK) {
2127 pot->last_error = err;
2130 if (variances !=
nullptr &&
pot->residual->rows_e.empty()) {
2131 std::fill(variances, variances + n_sys, 0.0);
2133 pot->last_error.clear();
2134 return RGPOT_ENGINE_OK;
2136 if (!
pot->callbacks_set ||
pot->callbacks.oracle ==
nullptr) {
2138 "gpr engine: no oracle; call rgpot_engine_set_callbacks first";
2139 return RGPOT_ENGINE_ERR_INVALID;
2141 std::vector<double> f_scratch;
2142 if (forces !=
nullptr) f_scratch.assign(n_sys * cart, 0.0);
2143 std::size_t cell_off = 0;
2144 for (
long s = 0; s < nSystems; ++s) {
2145 const std::size_t coord_off =
static_cast<std::size_t
>(s) * cart;
2147 forces !=
nullptr ? f_scratch.data() + coord_off :
nullptr;
2148 const double* b_ptr =
2149 boxes !=
nullptr ? cells.data() + cell_off :
nullptr;
2150 const int rc =
pot->callbacks.oracle(
2151 pot->callbacks.ctx, nAtoms, R.data() + coord_off, atomicNrs,
2152 f_ptr, energies + s, b_ptr);
2153 if (rc != 0)
return rc;
2154 std::string finite_err;
2155 if (!oracle_sample_finite(energies + s, f_ptr, cart, finite_err)) {
2156 pot->last_error = finite_err;
2157 return RGPOT_ENGINE_ERR_INVALID;
2161 pot->residual->stats.true_energy_calls +=
2162 static_cast<unsigned long long>(n_sys);
2163 if (forces !=
nullptr) {
2164 pot->residual->stats.true_gradient_calls +=
2165 static_cast<unsigned long long>(n_sys);
2167 if (forces !=
nullptr && !
pot->residual->hill_from_oracle()) {
2168 std::vector<double> grads(packed);
2169 for (std::size_t s = 0; s < n_sys; ++s) {
2170 for (std::size_t a = 0; a < d; ++a) {
2171 grads[s * d + a] = -f_scratch[s * cart + a];
2175 if (!
pot->residual->learn(geom.data(), n_sys, energies,
2176 grads.data(), err)) {
2177 pot->last_error = err;
2178 return RGPOT_ENGINE_ERR_INVALID;
2181 if (forces !=
nullptr) {
2182 for (std::size_t s = 0; s < n_sys; ++s) {
2183 std::copy(f_scratch.data() + s * cart,
2184 f_scratch.data() + s * cart + d, forces + s * d);
2187 if (variances !=
nullptr) {
2188 std::fill(variances, variances + n_sys, 0.0);
2190 pot->last_error.clear();
2191 return RGPOT_ENGINE_OK;
2193 if (forces ==
nullptr)
return -1;
2194 char err[512] = {0};
2195 if (!ensure_surrogate(
pot, err,
sizeof err, nAtoms, positions, atomicNrs)) {
2196 pot->last_error = err;
2197 std::fprintf(stderr,
"rgpot_engine_force_batch(gpr): %s\n", err);
2200 const std::size_t n_atoms =
static_cast<std::size_t
>(nAtoms);
2201 const std::size_t n_sys =
static_cast<std::size_t
>(nSystems);
2202 std::size_t stride = 0;
2203 std::size_t coord_count = 0;
2204 std::size_t cell_count = 0;
2205 if (!checked_mul_size(n_atoms, 3, stride) ||
2206 !checked_mul_size(stride, n_sys, coord_count) ||
2207 !checked_mul_size(
static_cast<std::size_t
>(9), n_sys, cell_count)) {
2208 pot->last_error =
"gpr engine: force_batch coordinate count overflows";
2209 return RGPOT_ENGINE_ERR_INVALID;
2211 std::vector<double> R(positions, positions + coord_count);
2212 std::vector<double> cells(cell_count, 0.0);
2213 if (boxes !=
nullptr) {
2214 std::copy(boxes, boxes + cell_count, cells.begin());
2216 if (transform !=
nullptr) {
2217 std::size_t coord_off = 0;
2218 std::size_t cell_off = 0;
2219 for (
long s = 0; s < nSystems; ++s) {
2221 transform(transform_user, nAtoms, R.data() + coord_off,
2222 cells.data() + cell_off);
2223 if (rc != 0)
return rc;
2224 coord_off += stride;
2229 return pot->surrogate->forceBatch(
2230 nSystems, nAtoms, R.data(), atomicNrs, forces, energies, variances,
2231 boxes !=
nullptr ? cells.data() :
nullptr);
2232 }
catch (
const std::exception& e) {
2233 pot->last_error = e.what();
2234 std::fprintf(stderr,
"rgpot_engine_force_batch(gpr): %s\n", e.what());
2237}
catch (
const std::bad_alloc&) {
2239 pot->last_error =
"gpr engine: force_batch coordinate count overflows";
2240 return RGPOT_ENGINE_ERR_INVALID;
2241}
catch (
const std::length_error&) {
2243 pot->last_error =
"gpr engine: force_batch coordinate count overflows";
2244 return RGPOT_ENGINE_ERR_INVALID;
2245}
catch (
const std::exception& ex) {
2246 if (
pot !=
nullptr)
pot->last_error = ex.what();
2247 std::fprintf(stderr,
"rgpot_engine_force_batch(gpr): %s\n", ex.what());
2252 const double* positions,
size_t positions_len,
2253 const int* atomicNrs,
double* hessian_out,
2254 size_t hessian_len,
const double* box)
2258 if (
pot ==
nullptr)
return RGPOT_ENGINE_ERR_INVALID;
2259 if (
pot->residual) {
2260 if (nAtoms !=
pot->residual->n_atoms) {
2261 pot->last_error =
"gpr engine: nAtoms mismatch with saddle";
2262 return RGPOT_ENGINE_ERR_INVALID;
2265 const int rc =
pot->residual->hessian(positions, positions_len,
2266 hessian_out, hessian_len, err);
2267 if (rc != RGPOT_ENGINE_OK) {
2268 pot->last_error = err;
2271 pot->last_error.clear();
2272 return RGPOT_ENGINE_OK;
2274 pot->last_error =
"gpr engine: dense Hessian requires a configured session";
2275 return RGPOT_ENGINE_ERR_UNSUPPORTED;
2276}
catch (
const std::bad_alloc&) {
2277 if (
pot !=
nullptr)
pot->last_error =
"gpr engine: size overflows";
2278 return RGPOT_ENGINE_ERR_INVALID;
2279}
catch (
const std::length_error&) {
2280 if (
pot !=
nullptr)
pot->last_error =
"gpr engine: size overflows";
2281 return RGPOT_ENGINE_ERR_INVALID;
2282}
catch (
const std::exception& ex) {
2283 if (
pot !=
nullptr)
pot->last_error = ex.what();
2289 size_t positions_len,
const int* atomicNrs,
const double* direction,
2290 size_t direction_len,
double* hv_out,
size_t hv_len,
const double* box,
2291 unsigned long long* ops_out,
double* scale_out)
2295 if (
pot ==
nullptr)
return RGPOT_ENGINE_ERR_INVALID;
2296 if (
pot->residual) {
2297 if (nAtoms !=
pot->residual->n_atoms) {
2298 pot->last_error =
"gpr engine: nAtoms mismatch with saddle";
2299 return RGPOT_ENGINE_ERR_INVALID;
2302 const int rc =
pot->residual->hessian_action(
2303 positions, positions_len, direction, direction_len, hv_out, hv_len,
2304 ops_out, scale_out, err);
2305 if (rc != RGPOT_ENGINE_OK) {
2306 pot->last_error = err;
2309 pot->last_error.clear();
2310 return RGPOT_ENGINE_OK;
2313 "gpr engine: Hessian action requires a configured session";
2314 return RGPOT_ENGINE_ERR_UNSUPPORTED;
2315}
catch (
const std::bad_alloc&) {
2316 if (
pot !=
nullptr)
pot->last_error =
"gpr engine: size overflows";
2317 return RGPOT_ENGINE_ERR_INVALID;
2318}
catch (
const std::length_error&) {
2319 if (
pot !=
nullptr)
pot->last_error =
"gpr engine: size overflows";
2320 return RGPOT_ENGINE_ERR_INVALID;
2321}
catch (
const std::exception& ex) {
2322 if (
pot !=
nullptr)
pot->last_error = ex.what();
2327 const double* positions,
2328 size_t positions_len,
2329 const int* atomicNrs,
2335 if (
pot ==
nullptr)
return RGPOT_ENGINE_ERR_INVALID;
2336 if (
pot->residual) {
2337 if (nAtoms !=
pot->residual->n_atoms) {
2338 pot->last_error =
"gpr engine: nAtoms mismatch with saddle";
2339 return RGPOT_ENGINE_ERR_INVALID;
2342 const int rc =
pot->residual->prediction_supported(
2343 positions, positions_len, supported_out, err);
2344 if (rc != RGPOT_ENGINE_OK) {
2345 pot->last_error = err;
2348 pot->last_error.clear();
2349 return RGPOT_ENGINE_OK;
2352 "gpr engine: prediction support query requires a configured session";
2353 return RGPOT_ENGINE_ERR_UNSUPPORTED;
2354}
catch (
const std::bad_alloc&) {
2355 if (
pot !=
nullptr)
pot->last_error =
"gpr engine: size overflows";
2356 return RGPOT_ENGINE_ERR_INVALID;
2357}
catch (
const std::length_error&) {
2358 if (
pot !=
nullptr)
pot->last_error =
"gpr engine: size overflows";
2359 return RGPOT_ENGINE_ERR_INVALID;
2360}
catch (
const std::exception& ex) {
2361 if (
pot !=
nullptr)
pot->last_error = ex.what();
2367 size_t positions_len,
const int* atomicNrs,
double* var_energy_out,
2368 size_t var_energy_len,
double* var_gradient_out,
size_t var_gradient_len,
2369 const double* boxes)
2373 if (
pot ==
nullptr || nSystems < 0)
return RGPOT_ENGINE_ERR_INVALID;
2374 if (
pot->residual) {
2375 if (nAtoms !=
pot->residual->n_atoms) {
2376 pot->last_error =
"gpr engine: nAtoms mismatch with saddle";
2377 return RGPOT_ENGINE_ERR_INVALID;
2379 const std::size_t n_sys =
static_cast<std::size_t
>(nSystems);
2380 std::size_t coord_count = 0;
2381 std::size_t model_count = 0;
2382 if (!checked_mul_size(n_sys,
pot->residual->n_dof, coord_count) ||
2383 !checked_mul_size(n_sys,
pot->residual->model_dof, model_count)) {
2385 "predict_variance: geometry batch length overflows";
2386 return RGPOT_ENGINE_ERR_INVALID;
2391 const int rc =
pot->residual->predict_variance(
2392 positions, positions_len, n_sys, var_energy_out, var_energy_len,
2393 var_gradient_out, var_gradient_len, err);
2394 if (rc != RGPOT_ENGINE_OK) {
2395 pot->last_error = err;
2398 pot->last_error.clear();
2399 return RGPOT_ENGINE_OK;
2402 "gpr engine: predict_variance requires a configured session";
2403 return RGPOT_ENGINE_ERR_UNSUPPORTED;
2404}
catch (
const std::bad_alloc&) {
2406 pot->last_error =
"predict_variance: geometry batch length overflows";
2407 return RGPOT_ENGINE_ERR_INVALID;
2408}
catch (
const std::length_error&) {
2410 pot->last_error =
"predict_variance: geometry batch length overflows";
2411 return RGPOT_ENGINE_ERR_INVALID;
2412}
catch (
const std::exception& ex) {
2413 if (
pot !=
nullptr)
pot->last_error = ex.what();
2420 if (
pot ==
nullptr) {
2424 if (
pot->residual) {
2425 if (msg ==
nullptr || msg_len == 0) {
2427 const int rc =
pot->residual->fit(err);
2428 if (rc != RGPOT_ENGINE_OK) {
2429 pot->last_error = err;
2436 return RGPOT_ENGINE_ERR_INVALID;
2439 std::memcpy(&hint, msg,
sizeof(hint));
2443 "gpr engine: invalid hint magic or version");
2444 return RGPOT_ENGINE_ERR_INVALID;
2448 const int rc =
pot->residual->fit(err);
2449 if (rc != RGPOT_ENGINE_OK) {
2450 pot->last_error = err;
2459 return RGPOT_ENGINE_ERR_INVALID;
2462 return RGPOT_ENGINE_OK;
2466 pot->residual->n_dof) {
2468 "gpr engine: invalid LEARN_POINTS dimensions");
2469 return RGPOT_ENGINE_ERR_INVALID;
2471 const auto n =
static_cast<std::size_t
>(hint.
n_points);
2472 const std::size_t d =
pot->residual->n_dof;
2474 std::size_t doubles = 0;
2475 std::size_t expected = 0;
2476 if (!checked_mul_size(n, d, nd) ||
2477 !checked_mul_size(nd, 2, doubles) ||
2478 !checked_add_size(doubles, n, doubles) ||
2479 !checked_mul_size(doubles,
sizeof(
double), expected) ||
2483 "gpr engine: LEARN_POINTS payload size overflows");
2484 return RGPOT_ENGINE_ERR_INVALID;
2486 if (msg_len != expected) {
2488 "gpr engine: LEARN_POINTS payload size mismatch");
2489 return RGPOT_ENGINE_ERR_INVALID;
2492 const auto* data =
reinterpret_cast<const double*
>(
2493 static_cast<const unsigned char*
>(msg) +
2495 const double* xs = data;
2496 const double* es = data + nd;
2497 const double* gs = data + nd + n;
2499 if (!
pot->residual->learn(xs, n, es, gs, err)) {
2500 pot->last_error = err;
2502 return RGPOT_ENGINE_ERR_INVALID;
2505 return RGPOT_ENGINE_OK;
2510 "gpr engine: invalid SET_TRAINING arguments");
2511 return RGPOT_ENGINE_ERR_INVALID;
2514 const int rc =
pot->residual->set_training(
2515 static_cast<std::size_t
>(hint.
n_points), hint.
phase == 1, err);
2516 if (rc != RGPOT_ENGINE_OK) {
2517 pot->last_error = err;
2525 "gpr engine: invalid RECORD_TRUE_CALLS arguments");
2526 return RGPOT_ENGINE_ERR_INVALID;
2528 const auto count =
static_cast<unsigned long long>(hint.
n_points);
2529 pot->residual->stats.true_energy_calls += count;
2530 if (hint.
phase >= 1) {
2531 pot->residual->stats.true_gradient_calls += count;
2533 if (hint.
phase >= 2) {
2534 pot->residual->stats.true_hessian_calls += count;
2536 return RGPOT_ENGINE_OK;
2539 return RGPOT_ENGINE_ERR_INVALID;
2546 if (!
pot->surrogate)
return 0;
2548 pot->surrogate->incorporate();
2550 }
catch (
const std::exception& e) {
2554}
catch (
const std::bad_alloc&) {
2555 const char* overflow =
"gpr engine: size overflows";
2556 if (
pot !=
nullptr)
pot->last_error = overflow;
2558 return RGPOT_ENGINE_ERR_INVALID;
2559}
catch (
const std::length_error&) {
2560 const char* overflow =
"gpr engine: size overflows";
2561 if (
pot !=
nullptr)
pot->last_error = overflow;
2563 return RGPOT_ENGINE_ERR_INVALID;
2564}
catch (
const std::exception& ex) {
2565 if (
pot !=
nullptr)
pot->last_error = ex.what();
Host check for the instruction set an AOTInductor package needs.
static void set_err(char *errbuf, size_t errlen, const char *msg)
const char * rgpot_engine_name(void)
int rgpot_engine_hvp(RgpotEnginePot *pot, long nAtoms, const double *positions, const int *atomicNrs, const double *direction, double *hv_out, const double *box)
int rgpot_engine_set_callbacks(RgpotEnginePot *pot, const RgpotEngineCallbacks *callbacks)
int rgpot_engine_force(RgpotEnginePot *pot, long nAtoms, const double *positions, const int *atomicNrs, double *forces, double *energy, double *variance, const double *box, rgpot_engine_coord_transform transform, void *transform_user)
int rgpot_engine_caps(const RgpotEnginePot *pot, RgpotEngineCaps *out)
int rgpot_engine_set_charge_spin(RgpotEnginePot *pot, int charge, int spin)
size_t rgpot_engine_last_error(const RgpotEnginePot *pot, char *buf, size_t len)
int rgpot_engine_gpr_stats(const RgpotEnginePot *pot, RgpotEngineGprStats *stats_out)
int rgpot_engine_select_orbitals(RgpotEnginePot *pot, long long key)
int rgpot_engine_abi_compatible(const RgpotEngineAbiStamp *stamp)
int rgpot_engine_available(void)
int rgpot_engine_hint(RgpotEnginePot *pot, const void *msg, std::size_t msg_len, char *errbuf, std::size_t errlen)
const char * rgpot_engine_version(void)
int rgpot_engine_abi_version(void)
void rgpot_engine_destroy(RgpotEnginePot *pot)
size_t rgpot_engine_model_digest(const RgpotEnginePot *pot, char *buf, size_t len)
unsigned long long rgpot_engine_model_state(const RgpotEnginePot *pot)
int rgpot_engine_predict_variance_checked(RgpotEnginePot *pot, long nSystems, long nAtoms, const double *positions, size_t positions_len, const int *atomicNrs, double *var_energy_out, size_t var_energy_len, double *var_gradient_out, size_t var_gradient_len, const double *boxes)
RgpotEnginePot * rgpot_engine_create(const void *config, std::size_t config_len, char *errbuf, std::size_t errlen)
long rgpot_engine_neighbor_options(const RgpotEnginePot *pot, RgpotEngineNeighborOptions *opts, long capacity)
int rgpot_engine_copy_orbitals(RgpotEnginePot *pot, long long from_key, long long to_key)
int rgpot_engine_force_batch(RgpotEnginePot *pot, long nSystems, long nAtoms, const double *positions, const int *atomicNrs, double *forces, double *energies, double *variances, const double *boxes, rgpot_engine_coord_transform transform, void *transform_user)
int rgpot_engine_hessian_checked(RgpotEnginePot *pot, long nAtoms, const double *positions, size_t positions_len, const int *atomicNrs, double *hessian_out, size_t hessian_len, const double *box)
int rgpot_engine_hessian_action_checked(RgpotEnginePot *pot, long nAtoms, const double *positions, size_t positions_len, const int *atomicNrs, const double *direction, size_t direction_len, double *hv_out, size_t hv_len, const double *box, unsigned long long *ops_out, double *scale_out)
int rgpot_engine_set_num_threads(RgpotEnginePot *pot, int intra_op, int inter_op)
int rgpot_engine_prediction_supported_checked(RgpotEnginePot *pot, long nAtoms, const double *positions, size_t positions_len, const int *atomicNrs, const double *box, int *supported_out)
ActiveLearningSession: shared GP + training data across GP-NEB and GP-Dimer phases.
Set up the GP-dimer problem.
void setPairtypeForMovingAtoms(const gpr::FieldMatrixIdx &atomtype_mov, gpr::Index_t &n_pt, gpr::FieldMatrixi &pairtype)
Set pairtype indices for moving+moving atom pairs and gives the updated number of active pairtypes.
AcquireReason
Fired when a point is delegated, before the oracle runs.
static std::unique_ptr< NestedEngineOracle > open(const std::string &library, const std::vector< unsigned char > &config, std::string &err)
eon_relax_band_t eon_relax_surface_fn void eon_relax_outcome_t * out
size_t char size_t errlen
@ RGPOT_ENGINE_GPR_HINT_LEARN_POINTS
@ RGPOT_ENGINE_GPR_HINT_SET_PHASE
@ RGPOT_ENGINE_GPR_HINT_RECORD_TRUE_CALLS
@ RGPOT_ENGINE_GPR_HINT_SET_TRAINING
@ RGPOT_ENGINE_GPR_HINT_INCORPORATE
#define RGPOT_ENGINE_GPR_RESIDUAL_PRIOR_VERSION
#define RGPOT_ENGINE_GPR_RESIDUAL_PRIOR_MAGIC
#define RGPOT_ENGINE_ERR_OUTSIDE_SUPPORT
#define RGPOT_ENGINE_GPR_HINT_VERSION
#define RGPOT_ENGINE_GPR_HINT_MAGIC
@ RGPOT_GPR_PHASE_SURROGATE
C API of libgpridge: Gaussian process accelerated saddle point searches and minimisation on potential...
void gpr_atoms_destroy(gpr_atoms_t atoms)
Destroy atoms configuration. Destroying NULL or a live handle clears gpr_last_status() and gpr_last_e...
gpr_atoms_t gpr_atoms_create(const gpr_atoms_config_t *config)
Create an atoms configuration handle from descriptor. Returns NULL on failure (check gpr_last_error()...
gpr_atoms_t gpr_atoms_create_simple(int n_atoms)
Convenience: create an atoms handle for N identical moving atoms. Equivalent to gpr_atoms_create(&gpr...
gpr_atoms_config_t gpr_atoms_simple(int n_atoms)
Convenience: N identical moving atoms, one pair type.
gpr_model_config_t gpr_model_config_defaults(void)
Library defaults of every gpr_model_config_t field.
gpridge_alg_t
Hyperparameter optimization algorithm.
@ GPR_HSSVD_BACKEND_CHOLESKY
const char * gpr_last_error(void)
Thread-local error message from last failing call. Never NULL.
struct gpr_model_s * gpr_model_t
Type-safe opaque handles. In Fortran, declare as type(c_ptr). The compiler catches type mismatches (u...
struct gpr_atoms_s * gpr_atoms_t
int gpr_model_set_hssvd_backend(gpr_model_t model, int selection)
Select the posterior solver for the next train (ABI 1.19). The value is a gpr_hssvd_backend_t,...
int gpr_model_init(gpr_model_t model, const gpr_model_config_t *config, gpr_atoms_t atoms)
Initialize model with configuration and atom setup. Must be called before train()....
int gpr_model_predict_hessian_action_checked(gpr_model_t model, const double *R_query, size_t R_len, const double *v, size_t v_len, double *Hv_out, size_t Hv_len, int n_coords)
Extent-checked mean-Hessian action (ABI 1.12).
gpr_model_t gpr_model_create(gpr_model_type_t type)
Create a GP or TP model. Returns NULL on failure.
int gpr_model_prediction_supported_checked(gpr_model_t model, const double *R_query, size_t R_len, int n_coords, int *supported)
Extent-checked prediction-support query (ABI 1.12).
int gpr_model_train_checked(gpr_model_t model, const double *R, size_t R_len, const double *E, size_t E_len, const double *G, size_t G_len, int n_obs, int n_coords)
Extent-checked forms of the training and prediction calls (ABI 1.11).
void gpr_model_destroy(gpr_model_t model)
Destroy model. Destroying NULL or a live handle clears gpr_last_status() and gpr_last_error(),...
int gpr_model_predict_hessian_checked(gpr_model_t model, const double *R_query, size_t R_len, double *H_out, size_t H_len, int n_coords)
Extent-checked mean-Hessian prediction (ABI 1.24).
int gpr_model_predict_batch_checked(gpr_model_t model, const double *R_queries, size_t R_len, double *E_out, size_t E_len, double *G_out, size_t G_len, double *var_E_out, size_t var_E_len, double *var_G_out, size_t var_G_len, int n_queries, int n_coords)
Extent-checked gpr_model_predict_batch (ABI 1.11).
int gpr_model_append_fixed_checked(gpr_model_t model, const double *R_new, size_t R_len, const double *E_new, size_t E_len, const double *G_new, size_t G_len, int n_new, int n_coords)
Append rows at the fitted hyperparameters by a Cholesky block update (ABI 1.13).
Potential wrappers and the batched oracle interface.
void requireAotiPackageRunsOnHost(const std::string &path)
std::string engineLibraryForSpecArm(const std::string &arm)
unsigned long long true_gradient_calls
unsigned long long true_energy_calls
unsigned long long observations
RgpotEngineCallbacks callbacks
std::string reactant_path
std::unique_ptr< pot::NestedEngineOracle > nested_oracle
pot::ActiveGP::Config config
std::shared_ptr< gpr::neb::ActiveLearningSession > session
std::unique_ptr< ResidualSession > residual
std::unique_ptr< pot::ActiveGP > surrogate
Stores configurations of all atoms in the system.
FieldMatrixi atomicNrs
Atomic Number of each atom.
FieldMatrixU8 is_frozen
Indicates whether atom is frozen or not.
FieldMatrixIdx id
ID of each atom (we do not use it).
AtomsPositionAndType atoms_mov
Info on moving atoms.
FieldMatrixIdx type
Type of each atom.
Coord positions
Positions of all atoms in the system.
void resize(const Index_t num_atoms)
std::function< void(gpr::InputParameters &, gpr::AtomsConfiguration &)> gp_setup
Atoms configuration descriptor. Describes the atomic system for the GP kernel (pair types,...
GP/TP model configuration. All fields have sensible defaults via gpr_model_config_defaults().