Loading...
Searching...
No Matches
GprEngineAbi.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// Copyright (c) gpridge developers
3// See LICENSE for details.
4//
5// libgpr_engine.so: the learning GP behind the generic rgpot engine C
6// ABI. A host that can dlopen a potential plugin --
7// eOn through GenericEngineLoader, ASE through the rgpot bindings --
8// gets learn-on-the-fly with no loop ownership and no knowledge of
9// the GP: it supplies the oracle through the callbacks struct and
10// calls force() as usual.
11
12#define RGPOT_ENGINE_BUILD
13#include <algorithm>
14#include <cmath>
15#include <cstdint>
16#include <cstdio>
17#include <cstring>
18#include <exception>
19#include <limits>
20#include <memory>
21#include <new>
22#include <set>
23#include <stdexcept>
24#include <string>
25#include <vector>
26
27#include "ActiveGP.h"
28#include "AotiPackageIsa.h"
29#include "NestedEngineOracle.h"
31#include "gpr/capi/gpridge_c.h"
32#include "gpr/neb/Session.h"
34#include "gpridge_version.h"
35#include "rgpot_engine_c_abi.h"
36
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>
41
42#include "rgpot/rpc/Potentials.capnp.h"
43
44namespace {
45
50template <typename Reader, typename Builder>
51std::vector<unsigned char> reserialise(Reader src)
52{
53 capnp::MallocMessageBuilder msg;
54 msg.setRoot(src);
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());
58}
59
62bool oracleFromSpec(::PotentialSpec::Reader spec, std::string& library,
63 std::vector<unsigned char>& config, std::string& err)
64{
65 switch (spec.which()) {
66 case ::PotentialSpec::UMA:
67 // A package compiled for CPU extensions this host lacks would
68 // stop at its first force call with SIGILL.
69 try {
71 spec.getUma().getModelPath().cStr());
72 } catch (const std::exception& error) {
73 err = error.what();
74 return false;
75 }
76 library = pot::engineLibraryForSpecArm("uma");
77 config = reserialise<::UmaParams::Reader, ::UmaParams::Builder>(
78 spec.getUma());
79 return true;
80 case ::PotentialSpec::METATOMIC:
81 library = pot::engineLibraryForSpecArm("metatomic");
82 config =
83 reserialise<::MetatomicParams::Reader,
84 ::MetatomicParams::Builder>(spec.getMetatomic());
85 return true;
86 case ::PotentialSpec::NWCHEM:
87 library = pot::engineLibraryForSpecArm("nwchem");
88 config =
89 reserialise<::NWChemParams::Reader, ::NWChemParams::Builder>(
90 spec.getNwchem());
91 return true;
92 case ::PotentialSpec::CPMD:
93 library = pot::engineLibraryForSpecArm("cpmd");
94 config = reserialise<::CPMDParams::Reader, ::CPMDParams::Builder>(
95 spec.getCpmd());
96 return true;
97#ifdef GPR_SCHEMA_HAS_CP2K_CONFIG
98 case ::PotentialSpec::CP2K:
99 library = pot::engineLibraryForSpecArm("cp2k");
100 config = reserialise<::CP2KParams::Reader, ::CP2KParams::Builder>(
101 spec.getCp2k());
102 return true;
103#endif
104 case ::PotentialSpec::LAMMPS:
105 library = pot::engineLibraryForSpecArm("lammps");
106 config =
107 reserialise<::LammpsParams::Reader, ::LammpsParams::Builder>(
108 spec.getLammps());
109 return true;
110 case ::PotentialSpec::BUILTIN: {
111 const auto b = spec.getBuiltin();
112 library = b.getLibrary().size() > 0
113 ? std::string(b.getLibrary().cStr())
114 : pot::engineLibraryForSpecArm(b.getName().cStr());
115 if (library.empty()) {
116 err = std::string("oracle arm 'builtin' names '") +
117 b.getName().cStr() +
118 "', which has no engine plugin; give it an explicit "
119 "library path";
120 return false;
121 }
122 config.clear();
123 return true;
124 }
125 }
126 err = "oracle spec carries no arm";
127 return false;
128}
129
130} // namespace
131#endif
132
133namespace {
134
135void set_err(char* errbuf, std::size_t errlen, const char* msg)
136{
137 if (errbuf == nullptr || errlen == 0) return;
138 std::snprintf(errbuf, errlen, "%s", msg != nullptr ? msg : "unknown");
139}
140
141bool checked_add_u64(unsigned long long a, unsigned long long b,
142 unsigned long long& out)
143{
144 if (a > std::numeric_limits<unsigned long long>::max() - b) return false;
145 out = a + b;
146 return true;
147}
148
149bool checked_mul_u64(unsigned long long a, unsigned long long b,
150 unsigned long long& out)
151{
152 if (a != 0 && b > std::numeric_limits<unsigned long long>::max() / a)
153 return false;
154 out = a * b;
155 return true;
156}
157
158bool checked_add_size(std::size_t a, std::size_t b, std::size_t& out)
159{
160 if (a > std::numeric_limits<std::size_t>::max() - b) return false;
161 out = a + b;
162 return true;
163}
164
165bool checked_mul_size(std::size_t a, std::size_t b, std::size_t& out)
166{
167 if (a != 0 && b > std::numeric_limits<std::size_t>::max() / a) return false;
168 out = a * b;
169 return true;
170}
171
172bool checked_int_count(std::size_t n, int& out)
173{
174 if (n > static_cast<std::size_t>(std::numeric_limits<int>::max())) {
175 return false;
176 }
177 out = static_cast<int>(n);
178 return true;
179}
180
181bool gemv_ops(unsigned long long rows, unsigned long long cols,
182 unsigned long long& out)
183{
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);
187}
188
189bool sexpat_action_ops(std::size_t n_obs, std::size_t n_dof,
190 unsigned long long& out)
191{
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))
200 return false;
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))
206 return false;
207 if (!checked_mul_u64(n, 4, term) || !checked_add_u64(ops, term, ops))
208 return false;
209 out = ops;
210 return true;
211}
212
213struct SaddleQuadratic {
214 std::vector<double> x;
215 double e = 0.0;
216 std::vector<double> g;
217 std::vector<double> h;
218
219 void energy_gradient(const double* pos, double& e_out,
220 std::vector<double>& g_out) const
221 {
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];
232 hdx[a] = row_sum;
233 }
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];
239 }
240 e_out = e + g_dot_dx + 0.5 * dx_dot_hdx;
241 g_out.resize(d);
242 for (std::size_t a = 0; a < d; ++a)
243 g_out[a] = g[a] + hdx[a];
244 }
245};
246
247struct ResidualSession {
248 static constexpr std::size_t kEmbedAnchors = 4;
249 static constexpr std::size_t kEmbedOffset = 3 * kEmbedAnchors;
250 // Heuristic scale multiplier keeping |delta| / L = O(1 / (12 (d + 4))) in
251 // the linear regime of the inverse-interatomic-distance feature map.
252 static constexpr std::size_t kEmbedScaleFactor = 12;
253
254 gpr_atoms_t atoms = nullptr;
255 gpr_model_t model = nullptr;
256 gpr_model_config_t model_cfg{};
257 long n_atoms = 0;
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;
264 int hill_policy = RGPOT_GPR_HILL_GP;
265 int phase = RGPOT_GPR_PHASE_SADDLE;
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;
272 bool stale = false;
273 std::size_t training_window = 0;
274 bool fixed_refits = false;
275 // The factor holds stored rows [fitted_first, fitted_rows). An append
276 // can only extend a factor that already starts at row 0.
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{};
283
284 ResidualSession()
285 {
286 stats.struct_size = sizeof(RgpotEngineGprStats);
287 }
288
289 // Under RGPOT_GPR_HILL_TRUE the host's oracle answers deriv=2 in the
290 // Hill phase. The engine then serves no Hill curvature and keeps the
291 // posterior it held entering the phase, so an oracle point it acquires
292 // there is not learned. RGPOT_GPR_HILL_GP learns those points and
293 // answers the curvature from the posterior.
294 bool hill_from_oracle() const
295 {
296 return phase == RGPOT_GPR_PHASE_HILL &&
297 hill_policy == RGPOT_GPR_HILL_TRUE;
298 }
299
300 bool refuse_true_hill_curvature(std::string& error_out) const
301 {
302 if (!hill_from_oracle()) return false;
303 error_out =
304 "gpr engine: Hill phase under RGPOT_GPR_HILL_TRUE takes "
305 "curvature from the oracle";
306 return true;
307 }
308
309 ~ResidualSession()
310 {
311 if (model != nullptr) gpr_model_destroy(model);
312 if (atoms != nullptr) gpr_atoms_destroy(atoms);
313 }
314
315 // Derive the embedding simplex edge length L from all accumulated
316 // displacements delta_i = x_i - x_0:
317 // delta_rms = sqrt( (1/n) sum_{i=1}^n ||x_i - x_0||^2 ),
318 // delta_max = max_{i,j} |x_{i,j} - x_{0,j}|,
319 // L = kEmbedScaleFactor * (d + kEmbedAnchors) * (delta_rms + delta_max).
320 // Here kEmbedScaleFactor = 12 is a heuristic scale multiplier keeping
321 // |delta| / L = O(1 / (12 (d + 4))) in the linear regime of the
322 // inverse-interatomic-distance feature map.
323 // The embedding is order-invariant, but the trained posterior is NOT,
324 // because of pre-existing gpridge row-order dependence.
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)
329 {
330 const std::size_t d = x_ts.size();
331 if (d == 0 || n_obs == 0 || raw_x.size() < n_obs * d) {
332 error_out =
333 "gpr engine: cannot derive embedding scale from empty "
334 "observations";
335 return false;
336 }
337 double sum_sq = 0.0;
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)) {
343 error_out =
344 "gpr engine: non-finite coordinate displacement in "
345 "embedding scale";
346 return false;
347 }
348 sum_sq += delta * delta;
349 max_abs = std::max(max_abs, std::abs(delta));
350 }
351 }
352 const double rms = std::sqrt(sum_sq / static_cast<double>(n_obs));
353 const double scale =
354 static_cast<double>(kEmbedScaleFactor * (d + kEmbedAnchors)) *
355 (rms + max_abs);
356 if (!std::isfinite(scale) || !(scale > 0.0)) {
357 error_out =
358 "gpr engine: degenerate coordinate spread; cannot derive "
359 "positive embedding scale";
360 return false;
361 }
362 scale_out = scale;
363 return true;
364 }
365
366 bool init_embedded_atoms(double scale, std::string& error_out)
367 {
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) {
372 is_frozen[a] = 1;
373 }
374 std::vector<double> ref_pos(3 * total_atoms, 0.0);
375 // Four non-coplanar frozen anchor atoms at (0,0,0), (L,0,0), (0,L,0),
376 // (0,0,L) form a 3D simplex so every displacement vector delta = x -
377 // x_ts has a unique set of distances to the anchors (no reflection or
378 // rotational aliasing in any coordinate).
379 ref_pos[3] = scale;
380 ref_pos[7] = scale;
381 ref_pos[11] = scale;
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;
387 }
388 gpr_atoms_config_t acfg =
389 gpr_atoms_simple(static_cast<int>(total_atoms));
390 acfg.is_frozen = is_frozen.data();
391 acfg.positions = ref_pos.data();
392 if (!atomic_nrs.empty()) {
393 acfg.atomic_nrs = atomic_nrs.data();
394 acfg.atom_types = atom_types.data();
395 }
396 gpr_atoms_t new_atoms = gpr_atoms_create(&acfg);
397 if (new_atoms == nullptr) {
398 error_out = gpr_last_error();
399 return false;
400 }
402 if (new_model == nullptr) {
403 gpr_atoms_destroy(new_atoms);
404 error_out = gpr_last_error();
405 return false;
406 }
407 if (gpr_model_init(new_model, &model_cfg, new_atoms) != GPR_SUCCESS) {
408 error_out = gpr_last_error();
409 gpr_model_destroy(new_model);
410 gpr_atoms_destroy(new_atoms);
411 return false;
412 }
413 if (model != nullptr) gpr_model_destroy(model);
414 if (atoms != nullptr) gpr_atoms_destroy(atoms);
415 atoms = new_atoms;
416 model = new_model;
417 embed_scale = scale;
418 return true;
419 }
420
421 // A full train on a different row span must not warm-start from the
422 // factor it is replacing. model_cfg already carries the Cholesky
423 // switch fixed refits asked for.
424 bool reset_cartesian_model(std::string& error_out)
425 {
426 if (atoms == nullptr) {
427 error_out = "gpr engine: Cartesian model has no atoms";
428 return false;
429 }
431 if (new_model == nullptr) {
432 error_out = gpr_last_error();
433 return false;
434 }
435 if (gpr_model_init(new_model, &model_cfg, atoms) != GPR_SUCCESS) {
436 error_out = gpr_last_error();
437 gpr_model_destroy(new_model);
438 return false;
439 }
440 if (model != nullptr) gpr_model_destroy(model);
441 model = new_model;
442 return true;
443 }
444
445 void embed_point(const double* x, double* r_out) const
446 {
447 if (!embed_coords) {
448 std::copy(x, x + n_dof, r_out);
449 return;
450 }
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);
455 r_out[3 * k] = base;
456 r_out[3 * k + 1] = base;
457 r_out[3 * k + 2] = base;
458 }
459 for (std::size_t j = 0; j < n_dof; ++j) {
460 const double delta = x[j] - saddle.x[j];
461 r_out[j] += delta;
462 }
463 }
464
465 void embed_direction(const double* v, double* v_out) const
466 {
467 if (!embed_coords) {
468 std::copy(v, v + n_dof, v_out);
469 return;
470 }
471 std::fill(v_out, v_out + model_dof, 0.0);
472 std::copy(v, v + n_dof, v_out);
473 }
474
475 void project_vector(const double* v_model, double* v_out) const
476 {
477 std::copy(v_model, v_model + n_dof, v_out);
478 }
479
480 static std::vector<std::uint64_t> bit_key(const double* x, std::size_t d)
481 {
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));
486 key[i] = bits;
487 }
488 return key;
489 }
490
491 bool learn(const double* xs, std::size_t n, const double* energy,
492 const double* gradient, std::string& error_out)
493 {
494 const std::size_t d = n_dof;
495 const std::size_t md = model_dof;
496 std::size_t nd = 0;
497 if (!checked_mul_size(n, d, nd)) {
498 error_out = "gpr engine: learn_points coordinate count overflows";
499 return false;
500 }
501 for (std::size_t i = 0; i < nd; ++i) {
502 if (!std::isfinite(xs[i]) || !std::isfinite(gradient[i])) {
503 error_out =
504 "gpr engine: learn_points requires finite coordinates and "
505 "gradients";
506 return false;
507 }
508 }
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";
512 return false;
513 }
514 }
515 std::vector<double> g_q;
516 std::vector<double> r_emb(md, 0.0);
517 std::vector<double> g_emb(md, 0.0);
518 std::size_t off = 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()) {
523 off += d;
524 continue;
525 }
526 double e_q = 0.0;
527 saddle.energy_gradient(x, e_q, g_q);
528 // Finite inputs can still overflow the saddle quadratic.
529 // Reject the row before it is stored.
530 const double e_res = energy[i] - e_q;
531 if (!std::isfinite(e_res)) {
532 error_out =
533 "gpr engine: learn_points residual energy is not finite";
534 return false;
535 }
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)) {
540 error_out =
541 "gpr engine: learn_points residual gradient is not "
542 "finite";
543 return false;
544 }
545 g_emb[a] = g_res;
546 }
547 seen.insert(std::move(key));
548 if (embed_coords) {
549 raw_x.insert(raw_x.end(), x, x + d);
550 } else {
551 embed_point(x, r_emb.data());
552 rows_x.insert(rows_x.end(), r_emb.begin(), r_emb.end());
553 }
554 rows_e.push_back(e_res);
555 off += d;
556 rows_g.insert(rows_g.end(), g_emb.begin(), g_emb.end());
557 ++stats.observations;
558 stale = true;
559 }
560 return true;
561 }
562
563 void publish_model_update()
564 {
565 if (model_update != nullptr) {
566 model_update(model_update_ctx, epoch);
567 }
568 }
569
570 int set_training(std::size_t window, bool fixed, std::string& error_out)
571 {
572 // Fixed appends extend a dense Cholesky factor, which the HS-SVD
573 // backend does not keep; the switch applies from the next full fit.
574 if (fixed && !fixed_refits) {
575 model_cfg.use_hssvd_backend = GPR_HSSVD_BACKEND_CHOLESKY;
576 if (model != nullptr &&
579 error_out = std::string("gpr engine: Cholesky backend: ") +
581 return RGPOT_ENGINE_ERR_EVAL;
582 }
583 }
584 const bool changed = training_window != window || fixed_refits != fixed;
585 training_window = window;
586 fixed_refits = fixed;
587 // A fitted posterior would otherwise ignore the new window until
588 // another row arrived. The hint takes effect at the next fit.
589 if (changed && !rows_e.empty()) stale = true;
590 return RGPOT_ENGINE_OK;
591 }
592
593 int fit(std::string& error_out)
594 {
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
600 : 0;
601 // An embedded session re-derives its coordinate map at every full
602 // fit, so only a Cartesian posterior can be extended in place.
603 // Append only extends a factor that already holds [0, fitted_rows).
604 // A windowed factor starts later; opening the window trains the
605 // omitted prefix in full.
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;
610 int n_new_i = 0;
611 int md_i = 0;
612 if (!checked_int_count(n_new, n_new_i) ||
613 !checked_int_count(md, md_i)) {
614 error_out =
615 "gpr engine: observation count does not fit in the C API";
616 return RGPOT_ENGINE_ERR_INVALID;
617 }
618 const int rc = gpr_model_append_fixed_checked(
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);
622 if (rc == GPR_SUCCESS) {
623 ++stats.fixed_appends;
624 ++epoch;
625 fitted_rows = total;
626 stale = false;
627 publish_model_update();
628 return RGPOT_ENGINE_OK;
629 }
630 if (rc != GPR_ERR_UNSUPPORTED) {
631 error_out = "gpr_model_append_fixed_checked on " +
632 std::to_string(n_new) +
633 " rows: " + gpr_last_error();
634 return RGPOT_ENGINE_ERR_EVAL;
635 }
636 }
637 if (fixed_refits && !embed_coords && fitted_rows > 0 &&
638 fitted_first != first && !reset_cartesian_model(error_out)) {
639 return RGPOT_ENGINE_ERR_EVAL;
640 }
641 const std::size_t n = total - first;
642 if (embed_coords && total > 0) {
643 double scale = 0.0;
644 if (!derive_embed_scale(saddle.x, raw_x, total, scale, error_out)) {
645 return RGPOT_ENGINE_ERR_INVALID;
646 }
647 if (!init_embedded_atoms(scale, error_out)) {
648 return RGPOT_ENGINE_ERR_EVAL;
649 }
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);
654 }
655 }
656 int n_i = 0;
657 int md_i = 0;
658 if (!checked_int_count(n, n_i) || !checked_int_count(md, md_i)) {
659 error_out =
660 "gpr engine: observation count does not fit in the C API";
661 return RGPOT_ENGINE_ERR_INVALID;
662 }
663 const int rc = gpr_model_train_checked(
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);
666 if (rc != GPR_SUCCESS) {
667 error_out = "gpr_model_train on " + std::to_string(n) +
668 " rows: " + gpr_last_error();
669 return RGPOT_ENGINE_ERR_EVAL;
670 }
671 ++stats.fits;
672 ++epoch;
673 fitted_first = first;
674 fitted_rows = total;
675 stale = false;
676 publish_model_update();
677 return RGPOT_ENGINE_OK;
678 }
679
680 int predict(const double* xs, std::size_t n, double* energies,
681 double* forces, std::string& error_out)
682 {
683 const std::size_t d = n_dof;
684 const std::size_t md = model_dof;
685 std::size_t nd = 0;
686 std::size_t nmd = 0;
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;
690 }
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;
695 }
696 }
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;
704 if (embed_coords) {
705 xs_emb.resize(nmd, 0.0);
706 std::size_t off = 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);
710 off += d;
711 moff += md;
712 }
713 query_ptr = xs_emb.data();
714 }
715 constexpr std::size_t kPredictBlock = 64;
716 std::size_t start = 0;
717 while (start < n) {
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)) {
723 error_out =
724 "gpr engine: predict coordinate count overflows";
725 return RGPOT_ENGINE_ERR_INVALID;
726 }
727 const int rc = gpr_model_predict_batch_checked(
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));
731 if (rc != GPR_SUCCESS) {
732 error_out = std::string("gpr_model_predict_batch: ") +
734 return RGPOT_ENGINE_ERR_EVAL;
735 }
736 start += m;
737 }
738 }
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);
742 std::size_t off = 0;
743 std::size_t moff = 0;
744 for (std::size_t i = 0; i < n; ++i) {
745 double e_q = 0.0;
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;
751 }
752 e_out[i] = e_tot;
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)) {
757 error_out =
758 "predict: gpridge returned a non-finite gradient";
759 return RGPOT_ENGINE_ERR_EVAL;
760 }
761 if (forces != nullptr) {
762 f_out[off + a] = f_tot;
763 }
764 }
765 off += d;
766 moff += md;
767 }
768 std::copy(e_out.begin(), e_out.end(), energies);
769 if (forces != nullptr) {
770 std::copy(f_out.begin(), f_out.end(), forces);
771 }
772 stats.gp_predictions += static_cast<unsigned long long>(n);
773 return RGPOT_ENGINE_OK;
774 }
775
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)
779 {
780 const std::size_t d = n_dof;
781 const std::size_t md = model_dof;
782 std::size_t nd = 0;
783 std::size_t nmd = 0;
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;
787 }
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;
792 }
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;
797 }
798 }
799 if (rows_e.empty()) {
800 error_out = "predict_variance: the process has no observations";
801 return RGPOT_ENGINE_ERR_EVAL;
802 }
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;
807 if (embed_coords) {
808 xs_emb.resize(nmd, 0.0);
809 std::size_t off = 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);
813 off += d;
814 moff += md;
815 }
816 query_ptr = xs_emb.data();
817 }
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;
823 while (start < n) {
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;
832 }
833 const int rc = gpr_model_predict_batch_checked(
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));
838 if (rc != GPR_SUCCESS) {
839 error_out = std::string("gpr_model_predict_batch_checked: ") +
841 return RGPOT_ENGINE_ERR_EVAL;
842 }
843 start += m;
844 }
845 std::size_t off = 0;
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) {
849 error_out =
850 "predict_variance: gpridge returned a negative or "
851 "non-finite variance";
852 return RGPOT_ENGINE_ERR_EVAL;
853 }
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) {
857 error_out =
858 "predict_variance: gpridge returned a negative "
859 "or non-finite variance";
860 return RGPOT_ENGINE_ERR_EVAL;
861 }
862 var_g[off + a] = vg;
863 }
864 off += d;
865 moff += md;
866 }
867 return RGPOT_ENGINE_OK;
868 }
869
870 int hessian(const double* x, std::size_t x_len, double* h_out,
871 std::size_t h_len, std::string& error_out)
872 {
873 if (refuse_true_hill_curvature(error_out)) {
874 return RGPOT_ENGINE_ERR_UNSUPPORTED;
875 }
876 std::size_t dd = 0;
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;
880 }
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;
884 }
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;
889 }
890 }
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()) {
897 if (!embed_coords) {
899 model, x, x_len, h_out, h_len, static_cast<int>(d));
900 if (rc != GPR_SUCCESS) {
901 error_out = std::string("gpr_model_predict_hessian: ") +
903 return RGPOT_ENGINE_ERR_EVAL;
904 }
905 } else {
906 std::vector<double> r_emb(md, 0.0);
907 embed_point(x, r_emb.data());
908 std::size_t md2 = 0;
909 if (!checked_mul_size(md, md, md2)) {
910 error_out =
911 "gpr engine: hessian coordinate count overflows";
912 return RGPOT_ENGINE_ERR_INVALID;
913 }
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));
918 if (rc != GPR_SUCCESS) {
919 error_out = std::string("gpr_model_predict_hessian: ") +
921 return RGPOT_ENGINE_ERR_EVAL;
922 }
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];
926 }
927 }
928 }
929 }
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;
936 }
937 h_tot[k] = hk;
938 }
939 std::copy(h_tot.begin(), h_tot.end(), h_out);
940 ++stats.gp_hessians;
941 return RGPOT_ENGINE_OK;
942 }
943
944 int prediction_supported(const double* x, std::size_t x_len,
945 int* supported_out, std::string& error_out)
946 {
947 if (x == nullptr || supported_out == nullptr || x_len < n_dof) {
948 error_out =
949 "gpr engine: invalid buffer length for prediction_supported";
950 return RGPOT_ENGINE_ERR_INVALID;
951 }
952 for (std::size_t i = 0; i < n_dof; ++i) {
953 if (!std::isfinite(x[i])) {
954 error_out =
955 "gpr engine: prediction_supported requires finite "
956 "coordinates";
957 return RGPOT_ENGINE_ERR_INVALID;
958 }
959 }
960 const int fit_rc = fit(error_out);
961 if (fit_rc != RGPOT_ENGINE_OK) return fit_rc;
962 if (rows_e.empty()) {
963 *supported_out = 1;
964 return RGPOT_ENGINE_OK;
965 }
966 int sup = 0;
967 std::vector<double> r_emb;
968 const double* query_ptr = x;
969 std::size_t query_len = x_len;
970 if (embed_coords) {
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();
975 }
977 model, query_ptr, query_len, static_cast<int>(model_dof), &sup);
978 if (rc != GPR_SUCCESS) {
979 error_out =
980 std::string("gpr_model_prediction_supported_checked: ") +
982 return RGPOT_ENGINE_ERR_EVAL;
983 }
984 *supported_out = sup;
985 return RGPOT_ENGINE_OK;
986 }
987
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)
992 {
993 if (refuse_true_hill_curvature(error_out)) {
994 return RGPOT_ENGINE_ERR_UNSUPPORTED;
995 }
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;
1002 }
1003 for (std::size_t i = 0; i < d; ++i) {
1004 if (!std::isfinite(x[i]) || !std::isfinite(v[i])) {
1005 error_out =
1006 "gpr engine: hessian_action requires finite coordinates "
1007 "and direction";
1008 return RGPOT_ENGINE_ERR_INVALID;
1009 }
1010 }
1011 const int fit_rc = fit(error_out);
1012 if (fit_rc != RGPOT_ENGINE_OK) return fit_rc;
1013
1014 std::vector<double> hv(d, 0.0);
1015 unsigned long long ops = 0;
1016 double scale = 0.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;
1024 if (embed_coords) {
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();
1033 }
1034 int supported = 0;
1035 const int support_rc = gpr_model_prediction_supported_checked(
1036 model, x_ptr, x_qlen, static_cast<int>(md), &supported);
1037 if (support_rc != GPR_SUCCESS) {
1038 error_out =
1039 std::string("gpr_model_prediction_supported_checked: ") +
1041 return RGPOT_ENGINE_ERR_EVAL;
1042 }
1043 if (supported == 0) {
1044 error_out =
1045 "gpridge prediction query is outside kernel support";
1047 }
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));
1052 if (rc != GPR_SUCCESS) {
1053 error_out =
1054 std::string("gpr_model_predict_hessian_action_checked: ") +
1056 return RGPOT_ENGINE_ERR_EVAL;
1057 }
1058 project_vector(hv_model.data(), hv.data());
1059 for (std::size_t i = 0; i < d; ++i) {
1060 if (!std::isfinite(hv[i])) {
1061 error_out =
1062 "hessian_action: gpridge returned a non-finite "
1063 "Hessian action";
1064 return RGPOT_ENGINE_ERR_EVAL;
1065 }
1066 }
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;
1073 }
1074 for (std::size_t i = 0; i < d; ++i) {
1075 scale = std::max(scale, std::abs(hv[i]));
1076 }
1077 }
1078 for (std::size_t row = 0; row < d; ++row) {
1079 double sum = 0.0;
1080 for (std::size_t column = 0; column < d; ++column) {
1081 const double term = saddle.h[row * d + column] * v[column];
1082 sum += term;
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;
1087 }
1088 }
1089 hv[row] += sum;
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;
1094 }
1095 }
1096 if (!std::isfinite(scale)) {
1097 error_out =
1098 "hessian_action: gpridge returned a non-finite Hessian action";
1099 return RGPOT_ENGINE_ERR_EVAL;
1100 }
1101 for (std::size_t row = 0; row < d; ++row) {
1102 if (!std::isfinite(hv[row])) {
1103 error_out =
1104 "hessian_action: gpridge returned a non-finite "
1105 "Hessian action";
1106 return RGPOT_ENGINE_ERR_EVAL;
1107 }
1108 }
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;
1113 }
1114};
1115
1116} // namespace
1117
1118struct RgpotEnginePot {
1119 std::shared_ptr<gpr::neb::ActiveLearningSession> session;
1120 std::unique_ptr<pot::ActiveGP> surrogate;
1121 std::unique_ptr<ResidualSession> residual;
1122 RgpotEngineCallbacks callbacks{};
1123 bool callbacks_set = false;
1126 std::string reactant_path;
1127 // Oracle named by the config rather than registered by the host. A
1128 // host that cannot call set_callbacks -- eOn's loader does not --
1129 // still gets a usable engine this way.
1130 std::unique_ptr<pot::NestedEngineOracle> nested_oracle;
1131 std::string last_error;
1132};
1133
1134namespace {
1135
1143void configureSessionForSystem(gpr::neb::ActiveLearningSession& session,
1144 long n_atoms, const double* positions,
1145 const int* atomic_nrs)
1146{
1147 const gpr::Index_t n = static_cast<gpr::Index_t>(n_atoms);
1148 std::vector<int> unique_species;
1149 std::vector<int> species_index(static_cast<std::size_t>(n), 0);
1150 for (gpr::Index_t i = 0; i < n; ++i) {
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);
1156 } else {
1157 species_index[i] =
1158 static_cast<int>(std::distance(unique_species.begin(), found));
1159 }
1160 }
1161
1163 cfg.positions.resize(1, 3 * n);
1164 for (gpr::Index_t i = 0; i < 3 * n; ++i) {
1165 cfg.positions(0, i) = positions != nullptr ? positions[i] : 0.0;
1166 }
1167 cfg.is_frozen.resize(1, n);
1168 cfg.is_frozen.setConstant(0);
1169 cfg.id.resize(1, n);
1170 cfg.atomicNrs.resize(1, n);
1171 cfg.type.resize(1, n);
1172 for (gpr::Index_t i = 0; i < n; ++i) {
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)];
1176 }
1177 cfg.atoms_mov.resize(n);
1178 cfg.atoms_mov.type.resize(1, n);
1179 cfg.atoms_mov.type = cfg.type;
1180 cfg.atoms_mov.positions.resize(1, 3 * n);
1181 cfg.atoms_mov.positions = cfg.positions;
1182
1183 // One pairtype per unordered pair of species present, which is what
1184 // the covariance function indexes its lengthscales by.
1185 const gpr::Index_t n_species =
1186 static_cast<gpr::Index_t>(unique_species.size());
1187 cfg.pairtype.resize(n_species, n_species);
1188 cfg.pairtype.setConstant(EMPTY);
1189 cfg.n_pt = 0;
1190 aux::ProblemSetUp problem;
1192 cfg.pairtype);
1193
1194 session.gp_setup = [cfg](gpr::InputParameters& params,
1195 gpr::AtomsConfiguration& atoms) {
1196 atoms = cfg;
1197 params.report_level.value = 0;
1198 };
1199 session.initialise();
1200}
1201
1204bool ensure_surrogate(RgpotEnginePot* pot, char* errbuf, std::size_t errlen,
1205 long n_atoms, const double* positions,
1206 const int* atomic_nrs)
1207{
1208 if (pot->surrogate) return true;
1209 if (pot->nested_oracle != nullptr && !pot->callbacks_set) {
1210 // Config-named oracle: build the surrogate against the engine the
1211 // spec pointed at, with no host involvement at all.
1212 if (pot->surrogate == nullptr) {
1213 pot->surrogate = std::make_unique<pot::ActiveGP>(
1214 pot->session, pot->nested_oracle->asOracle(), pot->config);
1215 }
1216 return true;
1217 }
1218 if (!pot->callbacks_set || pot->callbacks.oracle == nullptr) {
1220 "gpr engine: no oracle; call rgpot_engine_set_callbacks first");
1221 return false;
1222 }
1223 if (!pot->session_configured) {
1224 if (n_atoms <= 0) {
1226 "gpr engine: cannot configure the model without a system");
1227 return false;
1228 }
1229 try {
1230 configureSessionForSystem(*pot->session, n_atoms, positions,
1231 atomic_nrs);
1232 pot->session_configured = true;
1233 } catch (const std::exception& e) {
1234 set_err(errbuf, errlen, e.what());
1235 return false;
1236 }
1237 }
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,
1243 box);
1244 };
1245 try {
1246 pot->surrogate = std::make_unique<pot::ActiveGP>(
1247 pot->session, std::move(oracle), pot->config);
1248 } catch (const std::exception& e) {
1249 set_err(errbuf, errlen, e.what());
1250 return false;
1251 }
1252 if (cb.on_acquire != nullptr) {
1253 pot->surrogate->setAcquireHook(
1254 [cb](pot::ActiveGP::AcquireReason reason) {
1255 rgpot_engine_acquire_reason r = RGPOT_ACQUIRE_VARIANCE;
1256 switch (reason) {
1258 r = RGPOT_ACQUIRE_CERTIFY;
1259 break;
1261 r = RGPOT_ACQUIRE_BATCH;
1262 break;
1264 r = RGPOT_ACQUIRE_REJECT;
1265 break;
1266 default:
1267 break;
1268 }
1269 cb.on_acquire(cb.ctx, r);
1270 });
1271 }
1272 if (cb.on_model_update != nullptr) {
1273 pot->surrogate->setModelUpdateHook(
1274 [cb](std::uint64_t epoch) { cb.on_model_update(cb.ctx, epoch); });
1275 }
1276 return true;
1277}
1278
1279bool create_residual_session(RgpotEnginePot* pot, const void* config,
1280 std::size_t config_len, char* errbuf,
1281 std::size_t errlen)
1282{
1285 "gpr engine: residual prior config shorter than header");
1286 return false;
1287 }
1289 std::memcpy(&hdr, config, sizeof(hdr));
1292 "gpr engine: unsupported residual prior config version");
1293 return false;
1294 }
1295 if (hdr.n_atoms <= 0) {
1297 "gpr engine: residual prior requires positive n_atoms");
1298 return false;
1299 }
1300 if (hdr.n_coords < 0) {
1302 "gpr engine: residual prior n_coords must be non-negative");
1303 return false;
1304 }
1305 if (hdr.hill_policy != RGPOT_GPR_HILL_TRUE &&
1307 set_err(errbuf, errlen, "gpr engine: invalid hill_policy");
1308 return false;
1309 }
1310 if (!std::isfinite(hdr.reference_energy) ||
1311 !(std::isfinite(hdr.sigma2) && hdr.sigma2 > 0.0) ||
1312 !(std::isfinite(hdr.jitter_sigma2) && hdr.jitter_sigma2 >= 0.0) ||
1313 !(std::isfinite(hdr.magn_sigma2) && hdr.magn_sigma2 >= 0.0) ||
1314 !(std::isfinite(hdr.const_sigma2) && hdr.const_sigma2 >= 0.0) ||
1315 !std::isfinite(hdr.prior_mu) || !std::isfinite(hdr.prior_nu) ||
1316 !std::isfinite(hdr.prior_s2) ||
1317 !(std::isfinite(hdr.tol_func) && hdr.tol_func > 0.0) ||
1318 !(std::isfinite(hdr.tol_sol) && hdr.tol_sol > 0.0) ||
1319 !std::isfinite(hdr.tp_hyperprior_a) ||
1320 !std::isfinite(hdr.tp_hyperprior_b)) {
1322 "gpr engine: residual prior hyperparameters must be finite");
1323 return false;
1324 }
1325 // Every size below derives from caller-supplied counts, so each product
1326 // and sum is checked before config_len is compared or payload is read.
1327 const auto reject_overflow = [&]() {
1329 "gpr engine: residual prior config size overflows");
1330 return false;
1331 };
1332 std::size_t d = 0;
1333 if (hdr.n_coords > 0) {
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();
1337 }
1338 if (d == 0) {
1339 set_err(
1340 errbuf, errlen,
1341 "gpr engine: residual prior requires positive coordinate count");
1342 return false;
1343 }
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,
1352 model_atoms)) {
1353 return reject_overflow();
1354 }
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 "
1358 "layout");
1359 return false;
1360 }
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) ||
1371 (hdr.has_atomic_nrs != 0 &&
1372 !checked_mul_size(model_atoms, sizeof(int), atomic_nrs_bytes)) ||
1373 !checked_add_size(sizeof(RgpotEngineGprResidualPrior), payload_bytes,
1374 expected_bytes) ||
1375 !checked_add_size(expected_bytes, atomic_nrs_bytes, expected_bytes)) {
1376 return reject_overflow();
1377 }
1378 if (config_len != expected_bytes) {
1380 "gpr engine: residual prior config length mismatch");
1381 return false;
1382 }
1383
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");
1391 return false;
1392 }
1393 }
1394
1395 auto res = std::make_unique<ResidualSession>();
1396 res->n_atoms = static_cast<long>(model_atoms);
1397 res->n_dof = d;
1398 res->embed_coords = !direct_cartesian;
1399 res->model_dof = moving_atoms * 3;
1400 res->hill_policy = hdr.hill_policy;
1401 res->phase = RGPOT_GPR_PHASE_SADDLE;
1402
1403 res->saddle.x.assign(payload, payload + d);
1404 res->saddle.e = hdr.reference_energy;
1405 if (hdr.has_gradient != 0) {
1406 res->saddle.g.assign(payload + d, payload + 2 * d);
1407 } else {
1408 res->saddle.g.assign(d, 0.0);
1409 }
1410 const double* h_ptr = payload + d + g_doubles;
1411 res->saddle.h.assign(h_ptr, h_ptr + d * d);
1412
1413 if (hdr.has_atomic_nrs != 0) {
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];
1422 if (z <= 0) {
1424 "gpr engine: atomic_nrs must be positive");
1425 return false;
1426 }
1427 auto it =
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);
1432 } else {
1433 res->atom_types[i] =
1434 static_cast<int>(std::distance(unique_species.begin(), it));
1435 }
1436 }
1437 }
1438
1440 mcfg.sigma2 = hdr.sigma2;
1441 mcfg.jitter_sigma2 = hdr.jitter_sigma2;
1442 mcfg.magn_sigma2 = hdr.magn_sigma2;
1443 mcfg.const_sigma2 = hdr.const_sigma2;
1444 mcfg.prior_mu = hdr.prior_mu;
1445 mcfg.prior_nu = hdr.prior_nu;
1446 mcfg.prior_s2 = hdr.prior_s2;
1447 mcfg.optim_alg = static_cast<gpridge_alg_t>(hdr.optim_alg);
1448 mcfg.max_iter = hdr.max_iter;
1449 mcfg.tol_func = hdr.tol_func;
1450 mcfg.tol_sol = hdr.tol_sol;
1451 mcfg.report_level = hdr.report_level;
1456 res->model_cfg = mcfg;
1457
1458 if (direct_cartesian) {
1459 if (!res->atomic_nrs.empty()) {
1460 gpr_atoms_config_t acfg =
1461 gpr_atoms_simple(static_cast<int>(model_atoms));
1462 acfg.atomic_nrs = res->atomic_nrs.data();
1463 acfg.atom_types = res->atom_types.data();
1464 res->atoms = gpr_atoms_create(&acfg);
1465 } else {
1466 res->atoms = gpr_atoms_create_simple(static_cast<int>(model_atoms));
1467 }
1468 if (res->atoms == nullptr) {
1470 return false;
1471 }
1472 res->model = gpr_model_create(GPR_MODEL_GP);
1473 if (res->model == nullptr) {
1475 return false;
1476 }
1477 if (gpr_model_init(res->model, &res->model_cfg, res->atoms) !=
1478 GPR_SUCCESS) {
1480 return false;
1481 }
1482 }
1483 pot->residual = std::move(res);
1484 return true;
1485}
1486
1487// Host residual coordinates stay packed n_dof per system. The transform and
1488// the oracle are promised a cartesian block of 3*nAtoms, so each system is
1489// copied into the front of a zeroed block of that width.
1490bool residual_callback_scratch(std::size_t n_atoms, std::size_t n_dof,
1491 std::size_t n_sys, const double* packed,
1492 std::size_t& cart,
1493 std::vector<double>& cartesian,
1494 std::string& error_out, bool batch)
1495{
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";
1501 return false;
1502 }
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);
1508 }
1509 return true;
1510}
1511
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)
1515{
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);
1520 }
1521}
1522
1523bool oracle_sample_finite(const double* energy, const double* forces,
1524 std::size_t n_force, std::string& error_out)
1525{
1526 if (energy == nullptr || !std::isfinite(*energy)) {
1527 error_out = "gpr engine: oracle energy is not finite";
1528 return false;
1529 }
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";
1534 return false;
1535 }
1536 }
1537 }
1538 return true;
1539}
1540
1541} // namespace
1542
1543extern "C" {
1544
1546{
1547 return RGPOT_ENGINE_ABI_VERSION;
1548}
1549
1550int rgpot_engine_abi_compatible(const RgpotEngineAbiStamp* stamp)
1551{
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
1556 ? 1
1557 : 0;
1558}
1559
1561{
1562 return 1;
1563}
1564
1565RgpotEnginePot* rgpot_engine_create(const void* config, std::size_t config_len,
1566 char* errbuf, std::size_t errlen)
1567{
1568 // The config arm will be a capnp GprParams message whose oracle
1569 // field is a nested PotentialSpec. Until that schema lands, accept
1570 // the interim gate struct so a host can at least turn on the
1571 // convergence certificate; dispatch is on the magic word, so the
1572 // capnp message can arrive here later without ambiguity. A config
1573 // that is neither is not silently ignored: a caller that meant to
1574 // configure the engine and did not would otherwise get a surface
1575 // that never checks its own convergence claim.
1576 try {
1577 auto pot = std::make_unique<RgpotEnginePot>();
1578 pot->session = std::make_shared<gpr::neb::ActiveLearningSession>();
1579 if (config != nullptr && config_len > 0) {
1580 unsigned magic = 0;
1581 if (config_len >= sizeof(unsigned)) {
1582 std::memcpy(&magic, config, sizeof(unsigned));
1583 }
1585 if (!create_residual_session(pot.get(), config, config_len,
1586 errbuf, errlen)) {
1587 return nullptr;
1588 }
1589 return pot.release();
1590 }
1591#ifdef GPR_ENGINE_HAS_POTENTIAL_SPEC
1592 // A capnp message is word-aligned and a multiple of a word;
1593 // the interim struct is neither, in general. Dispatch on that
1594 // before the magic check so a GprParams message is read as
1595 // one rather than rejected for the wrong size.
1596 if (config_len % sizeof(capnp::word) == 0 &&
1597 config_len != sizeof(RgpotEngineGprGate) &&
1598 magic != RGPOT_ENGINE_GPR_GATE_MAGIC) {
1599 try {
1600 const kj::ArrayPtr<const capnp::word> words(
1601 reinterpret_cast<const capnp::word*>(config),
1602 config_len / sizeof(capnp::word));
1603 capnp::FlatArrayMessageReader reader(words);
1604 const auto params = reader.getRoot<::GprParams>();
1605
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 <= "
1618 "sigmaHiFactor");
1619 return nullptr;
1620 }
1621
1622 std::string library, oerr;
1623 std::vector<unsigned char> ocfg;
1624 if (!oracleFromSpec(params.getOracle(), library, ocfg,
1625 oerr)) {
1627 ("gpr engine: " + oerr).c_str());
1628 return nullptr;
1629 }
1630 pot->nested_oracle =
1631 pot::NestedEngineOracle::open(library, ocfg, oerr);
1632 if (pot->nested_oracle == nullptr) {
1634 ("gpr engine: oracle " + oerr).c_str());
1635 return nullptr;
1636 }
1637 return pot.release();
1638 } catch (const kj::Exception&) {
1639 // A zero-filled buffer is not a Cap'n Proto root. The
1640 // KJ exception text includes a process-specific stack, so
1641 // malformed wire data receives the stable diagnosis below.
1642 // Standard exceptions from GprParams validation and nested
1643 // engine construction escape to the outer handler with
1644 // their actionable message intact.
1646 "gpr engine: config is neither an "
1647 "RgpotEngineGprGate nor a GprParams message");
1648 return nullptr;
1649 }
1650 }
1651#endif
1652 if (config_len != sizeof(RgpotEngineGprGate)) {
1654 "gpr engine: config is neither an RgpotEngineGprGate "
1655 "nor a GprParams message");
1656 return nullptr;
1657 }
1658 RgpotEngineGprGate gate{};
1659 std::memcpy(&gate, config, sizeof(gate));
1660 if (gate.magic != RGPOT_ENGINE_GPR_GATE_MAGIC) {
1661 set_err(errbuf, errlen, "gpr engine: bad config magic");
1662 return nullptr;
1663 }
1664 if (gate.version != RGPOT_ENGINE_GPR_GATE_VERSION) {
1666 "gpr engine: unsupported config "
1667 "version");
1668 return nullptr;
1669 }
1670 if (!(gate.sigmaLoFactor > 0.0) || !(gate.sigmaHiFactor > 0.0) ||
1671 gate.sigmaHiFactor < gate.sigmaLoFactor) {
1673 "gpr engine: need 0 < sigmaLoFactor <= sigmaHiFactor");
1674 return nullptr;
1675 }
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);
1681 }
1682 return pot.release();
1683 } catch (const std::exception& e) {
1684 set_err(errbuf, errlen, e.what());
1685 return nullptr;
1686 }
1687}
1688
1690{
1691 delete pot;
1692}
1693
1695 const RgpotEngineCallbacks* callbacks)
1696{
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;
1704 }
1705 pot->surrogate.reset();
1706 return 0;
1707}
1708
1710{
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();
1715}
1716
1717size_t rgpot_engine_last_error(const RgpotEnginePot* pot, char* buf, size_t len)
1718{
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);
1724 buf[copied] = '\0';
1725 }
1726 return full;
1727}
1728
1729int rgpot_engine_caps(const RgpotEnginePot* pot, RgpotEngineCaps* out)
1730{
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;
1737 caps.batched = 0;
1738 caps.periodic = 0;
1739 caps.stress = 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)
1745 ? out->size
1746 : sizeof(RgpotEngineCaps);
1747 std::memcpy(out, &caps, n);
1748 out->size = n;
1749 return RGPOT_ENGINE_OK;
1750}
1751
1752const char* rgpot_engine_name(void)
1753{
1754 return "gpr";
1755}
1756
1757const char* rgpot_engine_version(void)
1758{
1759 return "gpr/" GPRIDGE_VERSION;
1760}
1761
1763 size_t len)
1764{
1765 (void)pot;
1766 if (buf != nullptr && len > 0) buf[0] = '\0';
1767 return 0;
1768}
1769
1771 int inter_op)
1772{
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;
1777 }
1778 pot->last_error = "gpr engine: backend has no tensor runtime";
1779 return RGPOT_ENGINE_ERR_UNSUPPORTED;
1780}
1781
1783{
1784 (void)charge;
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;
1788}
1789
1791{
1792 (void)key;
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;
1796}
1797
1799 long long to_key)
1800{
1801 (void)from_key;
1802 (void)to_key;
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;
1806}
1807
1809 RgpotEngineNeighborOptions* opts,
1810 long capacity)
1811{
1812 (void)pot;
1813 (void)opts;
1814 (void)capacity;
1815 return 0;
1816}
1817
1818int rgpot_engine_hvp(RgpotEnginePot* pot, long nAtoms, const double* positions,
1819 const int* atomicNrs, const double* direction,
1820 double* hv_out, const double* box)
1821try {
1822 if (pot == nullptr) return RGPOT_ENGINE_ERR_INVALID;
1823 if (!pot->residual) {
1824 pot->last_error =
1825 "gpr engine: analytic HVP requires a configured residual session";
1826 return RGPOT_ENGINE_ERR_UNSUPPORTED;
1827 }
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;
1833 }
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;
1838 }
1839 }
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),
1845 atomic_bytes)) {
1846 pot->last_error = "gpr engine: HVP coordinate count overflows";
1847 return RGPOT_ENGINE_ERR_INVALID;
1848 }
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;
1855 };
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;
1861 }
1862 std::string err;
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;
1867 return rc;
1868 }
1869 pot->last_error.clear();
1870 return RGPOT_ENGINE_OK;
1871} catch (const std::bad_alloc&) {
1872 if (pot != nullptr)
1873 pot->last_error = "gpr engine: HVP coordinate count overflows";
1874 return RGPOT_ENGINE_ERR_INVALID;
1875} catch (const std::length_error&) {
1876 if (pot != nullptr)
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();
1881 return -2;
1882}
1883
1885 RgpotEngineGprStats* stats_out)
1886{
1887 if (pot == nullptr || stats_out == nullptr || stats_out->struct_size == 0) {
1888 return RGPOT_ENGINE_ERR_INVALID;
1889 }
1890 RgpotEngineGprStats current{};
1891 current.struct_size = sizeof(RgpotEngineGprStats);
1892 if (pot->residual) {
1893 current = pot->residual->stats;
1894 } else if (pot->surrogate) {
1895 current.true_energy_calls =
1896 static_cast<unsigned long long>(pot->surrogate->oracleCalls());
1897 current.true_gradient_calls =
1898 static_cast<unsigned long long>(pot->surrogate->oracleCalls());
1899 current.observations =
1900 static_cast<unsigned long long>(pot->surrogate->trainingSize());
1901 current.fits = pot->surrogate->modelState();
1902 }
1903 const std::size_t room =
1904 std::min(stats_out->struct_size, sizeof(RgpotEngineGprStats));
1905 std::memcpy(stats_out, &current, room);
1906 stats_out->struct_size = room;
1907 return RGPOT_ENGINE_OK;
1908}
1909
1911 const double* positions, const int* atomicNrs,
1912 double* forces, double* energy, double* variance,
1913 const double* box,
1914 rgpot_engine_coord_transform transform,
1915 void* transform_user)
1916try {
1917 if (pot == nullptr || positions == nullptr || energy == nullptr ||
1918 nAtoms <= 0) {
1919 return -1;
1920 }
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;
1925 }
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,
1932 false)) {
1933 pot->last_error = scratch_err;
1934 return RGPOT_ENGINE_ERR_INVALID;
1935 }
1936 std::vector<double> cell(9, 0.0);
1937 if (box != nullptr) std::copy(box, box + 9, cell.begin());
1938 if (transform != nullptr) {
1939 const int rc =
1940 transform(transform_user, nAtoms, R.data(), cell.data());
1941 if (rc != 0) return rc;
1942 }
1943 std::vector<double> geom;
1944 residual_pack_prefix(R, 1, d, cart, geom);
1945 if (pot->residual->phase == RGPOT_GPR_PHASE_SURROGATE) {
1946 std::string err;
1947 // Zero would report the surrogate as exact and floor its
1948 // uncertainty. The energy variance is the posterior's; with no
1949 // observations the answer is the reference quadratic. Gradient
1950 // variance stays on rgpot_engine_predict_variance_checked.
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;
1957 return vrc;
1958 }
1959 }
1960 const int rc =
1961 pot->residual->predict(geom.data(), 1, energy, forces, err);
1962 if (rc != RGPOT_ENGINE_OK) {
1963 pot->last_error = err;
1964 return rc;
1965 }
1966 if (variance != nullptr && pot->residual->rows_e.empty()) {
1967 *variance = 0.0;
1968 }
1969 pot->last_error.clear();
1970 return RGPOT_ENGINE_OK;
1971 }
1972 if (!pot->callbacks_set || pot->callbacks.oracle == nullptr) {
1973 pot->last_error =
1974 "gpr engine: no oracle; call rgpot_engine_set_callbacks first";
1975 return RGPOT_ENGINE_ERR_INVALID;
1976 }
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();
1982 }
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;
1991 }
1992 pot->residual->stats.true_energy_calls += 1;
1993 if (forces != nullptr) {
1994 pot->residual->stats.true_gradient_calls += 1;
1995 }
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];
2000 std::string err;
2001 if (!pot->residual->learn(geom.data(), 1, energy, grad.data(),
2002 err)) {
2003 pot->last_error = err;
2004 return RGPOT_ENGINE_ERR_INVALID;
2005 }
2006 }
2007 if (forces != nullptr) {
2008 std::copy(f_scratch.data(), f_scratch.data() + d, forces);
2009 }
2010 if (variance != nullptr) *variance = 0.0;
2011 pot->last_error.clear();
2012 return RGPOT_ENGINE_OK;
2013 }
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);
2019 return -1;
2020 }
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;
2026 }
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;
2033 }
2034 try {
2035 return pot->surrogate->force(nAtoms, R.data(), atomicNrs, forces,
2036 energy, variance,
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());
2041 return -2;
2042 }
2043} catch (const std::bad_alloc&) {
2044 if (pot != nullptr)
2045 pot->last_error = "gpr engine: force coordinate count overflows";
2046 return RGPOT_ENGINE_ERR_INVALID;
2047} catch (const std::length_error&) {
2048 if (pot != nullptr)
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());
2054 return -2;
2055}
2056
2057int rgpot_engine_force_batch(RgpotEnginePot* pot, long nSystems, long nAtoms,
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)
2063try {
2064 if (pot == nullptr || positions == nullptr || energies == nullptr ||
2065 nSystems <= 0 || nAtoms <= 0) {
2066 return -1;
2067 }
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;
2072 }
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)) {
2079 pot->last_error =
2080 "gpr engine: force_batch coordinate count overflows";
2081 return RGPOT_ENGINE_ERR_INVALID;
2082 }
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,
2088 true)) {
2089 pot->last_error = scratch_err;
2090 return RGPOT_ENGINE_ERR_INVALID;
2091 }
2092 std::vector<double> cells(cell_count, 0.0);
2093 if (boxes != nullptr) {
2094 std::copy(boxes, boxes + cell_count, cells.begin());
2095 }
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) {
2100 const int rc =
2101 transform(transform_user, nAtoms, R.data() + coord_off,
2102 cells.data() + cell_off);
2103 if (rc != 0) return rc;
2104 coord_off += cart;
2105 cell_off += 9;
2106 }
2107 }
2108 std::vector<double> geom;
2109 residual_pack_prefix(R, n_sys, d, cart, geom);
2110 if (pot->residual->phase == RGPOT_GPR_PHASE_SURROGATE) {
2111 std::string err;
2112 // Same variance rule as rgpot_engine_force: a trained posterior
2113 // reports its energy variance, and an untrained reference is 0.
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(),
2118 packed, err);
2119 if (vrc != RGPOT_ENGINE_OK) {
2120 pot->last_error = err;
2121 return vrc;
2122 }
2123 }
2124 const int rc = pot->residual->predict(geom.data(), n_sys, energies,
2125 forces, err);
2126 if (rc != RGPOT_ENGINE_OK) {
2127 pot->last_error = err;
2128 return rc;
2129 }
2130 if (variances != nullptr && pot->residual->rows_e.empty()) {
2131 std::fill(variances, variances + n_sys, 0.0);
2132 }
2133 pot->last_error.clear();
2134 return RGPOT_ENGINE_OK;
2135 }
2136 if (!pot->callbacks_set || pot->callbacks.oracle == nullptr) {
2137 pot->last_error =
2138 "gpr engine: no oracle; call rgpot_engine_set_callbacks first";
2139 return RGPOT_ENGINE_ERR_INVALID;
2140 }
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;
2146 double* f_ptr =
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;
2158 }
2159 cell_off += 9;
2160 }
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);
2166 }
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];
2172 }
2173 }
2174 std::string err;
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;
2179 }
2180 }
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);
2185 }
2186 }
2187 if (variances != nullptr) {
2188 std::fill(variances, variances + n_sys, 0.0);
2189 }
2190 pot->last_error.clear();
2191 return RGPOT_ENGINE_OK;
2192 }
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);
2198 return -1;
2199 }
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;
2210 }
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());
2215 }
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) {
2220 const int rc =
2221 transform(transform_user, nAtoms, R.data() + coord_off,
2222 cells.data() + cell_off);
2223 if (rc != 0) return rc;
2224 coord_off += stride;
2225 cell_off += 9;
2226 }
2227 }
2228 try {
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());
2235 return -2;
2236 }
2237} catch (const std::bad_alloc&) {
2238 if (pot != nullptr)
2239 pot->last_error = "gpr engine: force_batch coordinate count overflows";
2240 return RGPOT_ENGINE_ERR_INVALID;
2241} catch (const std::length_error&) {
2242 if (pot != nullptr)
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());
2248 return -2;
2249}
2250
2252 const double* positions, size_t positions_len,
2253 const int* atomicNrs, double* hessian_out,
2254 size_t hessian_len, const double* box)
2255try {
2256 (void)atomicNrs;
2257 (void)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;
2263 }
2264 std::string err;
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;
2269 return rc;
2270 }
2271 pot->last_error.clear();
2272 return RGPOT_ENGINE_OK;
2273 }
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();
2284 return -2;
2285}
2286
2288 RgpotEnginePot* pot, long nAtoms, const double* positions,
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)
2292try {
2293 (void)atomicNrs;
2294 (void)box;
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;
2300 }
2301 std::string err;
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;
2307 return rc;
2308 }
2309 pot->last_error.clear();
2310 return RGPOT_ENGINE_OK;
2311 }
2312 pot->last_error =
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();
2323 return -2;
2324}
2325
2327 const double* positions,
2328 size_t positions_len,
2329 const int* atomicNrs,
2330 const double* box,
2331 int* supported_out)
2332try {
2333 (void)atomicNrs;
2334 (void)box;
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;
2340 }
2341 std::string err;
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;
2346 return rc;
2347 }
2348 pot->last_error.clear();
2349 return RGPOT_ENGINE_OK;
2350 }
2351 pot->last_error =
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();
2362 return -2;
2363}
2364
2366 RgpotEnginePot* pot, long nSystems, long nAtoms, const double* positions,
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)
2370try {
2371 (void)atomicNrs;
2372 (void)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;
2378 }
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)) {
2384 pot->last_error =
2385 "predict_variance: geometry batch length overflows";
2386 return RGPOT_ENGINE_ERR_INVALID;
2387 }
2388 (void)coord_count;
2389 (void)model_count;
2390 std::string err;
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;
2396 return rc;
2397 }
2398 pot->last_error.clear();
2399 return RGPOT_ENGINE_OK;
2400 }
2401 pot->last_error =
2402 "gpr engine: predict_variance requires a configured session";
2403 return RGPOT_ENGINE_ERR_UNSUPPORTED;
2404} catch (const std::bad_alloc&) {
2405 if (pot != nullptr)
2406 pot->last_error = "predict_variance: geometry batch length overflows";
2407 return RGPOT_ENGINE_ERR_INVALID;
2408} catch (const std::length_error&) {
2409 if (pot != nullptr)
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();
2414 return -2;
2415}
2416
2417int rgpot_engine_hint(RgpotEnginePot* pot, const void* msg, std::size_t msg_len,
2418 char* errbuf, std::size_t errlen)
2419try {
2420 if (pot == nullptr) {
2421 set_err(errbuf, errlen, "gpr engine: null potential");
2422 return -1;
2423 }
2424 if (pot->residual) {
2425 if (msg == nullptr || msg_len == 0) {
2426 std::string err;
2427 const int rc = pot->residual->fit(err);
2428 if (rc != RGPOT_ENGINE_OK) {
2429 pot->last_error = err;
2430 set_err(errbuf, errlen, err.c_str());
2431 }
2432 return rc;
2433 }
2434 if (msg_len < sizeof(RgpotEngineGprHint)) {
2435 set_err(errbuf, errlen, "gpr engine: hint shorter than header");
2436 return RGPOT_ENGINE_ERR_INVALID;
2437 }
2438 RgpotEngineGprHint hint{};
2439 std::memcpy(&hint, msg, sizeof(hint));
2440 if (hint.magic != RGPOT_ENGINE_GPR_HINT_MAGIC ||
2443 "gpr engine: invalid hint magic or version");
2444 return RGPOT_ENGINE_ERR_INVALID;
2445 }
2447 std::string err;
2448 const int rc = pot->residual->fit(err);
2449 if (rc != RGPOT_ENGINE_OK) {
2450 pot->last_error = err;
2451 set_err(errbuf, errlen, err.c_str());
2452 }
2453 return rc;
2454 }
2456 if (hint.phase < RGPOT_GPR_PHASE_SADDLE ||
2458 set_err(errbuf, errlen, "gpr engine: invalid phase in hint");
2459 return RGPOT_ENGINE_ERR_INVALID;
2460 }
2461 pot->residual->phase = hint.phase;
2462 return RGPOT_ENGINE_OK;
2463 }
2465 if (hint.n_points < 0 || static_cast<std::size_t>(hint.n_coords) !=
2466 pot->residual->n_dof) {
2468 "gpr engine: invalid LEARN_POINTS dimensions");
2469 return RGPOT_ENGINE_ERR_INVALID;
2470 }
2471 const auto n = static_cast<std::size_t>(hint.n_points);
2472 const std::size_t d = pot->residual->n_dof;
2473 std::size_t nd = 0;
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) ||
2480 !checked_add_size(expected, sizeof(RgpotEngineGprHint),
2481 expected)) {
2483 "gpr engine: LEARN_POINTS payload size overflows");
2484 return RGPOT_ENGINE_ERR_INVALID;
2485 }
2486 if (msg_len != expected) {
2488 "gpr engine: LEARN_POINTS payload size mismatch");
2489 return RGPOT_ENGINE_ERR_INVALID;
2490 }
2491 if (n > 0) {
2492 const auto* data = reinterpret_cast<const double*>(
2493 static_cast<const unsigned char*>(msg) +
2494 sizeof(RgpotEngineGprHint));
2495 const double* xs = data;
2496 const double* es = data + nd;
2497 const double* gs = data + nd + n;
2498 std::string err;
2499 if (!pot->residual->learn(xs, n, es, gs, err)) {
2500 pot->last_error = err;
2501 set_err(errbuf, errlen, err.c_str());
2502 return RGPOT_ENGINE_ERR_INVALID;
2503 }
2504 }
2505 return RGPOT_ENGINE_OK;
2506 }
2508 if (hint.n_points < 0 || (hint.phase != 0 && hint.phase != 1)) {
2510 "gpr engine: invalid SET_TRAINING arguments");
2511 return RGPOT_ENGINE_ERR_INVALID;
2512 }
2513 std::string err;
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;
2518 set_err(errbuf, errlen, err.c_str());
2519 }
2520 return rc;
2521 }
2523 if (hint.n_points < 0 || hint.phase < 0 || hint.phase > 2) {
2525 "gpr engine: invalid RECORD_TRUE_CALLS arguments");
2526 return RGPOT_ENGINE_ERR_INVALID;
2527 }
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;
2532 }
2533 if (hint.phase >= 2) {
2534 pot->residual->stats.true_hessian_calls += count;
2535 }
2536 return RGPOT_ENGINE_OK;
2537 }
2538 set_err(errbuf, errlen, "gpr engine: unknown hint kind");
2539 return RGPOT_ENGINE_ERR_INVALID;
2540 }
2541 // The hint arm is the host-initiated incorporation boundary. The
2542 // capnp payload is reserved for tunables; an empty hint means
2543 // "incorporate now".
2544 (void)msg;
2545 (void)msg_len;
2546 if (!pot->surrogate) return 0;
2547 try {
2548 pot->surrogate->incorporate();
2549 return 0;
2550 } catch (const std::exception& e) {
2551 set_err(errbuf, errlen, e.what());
2552 return -2;
2553 }
2554} catch (const std::bad_alloc&) {
2555 const char* overflow = "gpr engine: size overflows";
2556 if (pot != nullptr) pot->last_error = overflow;
2557 set_err(errbuf, errlen, 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;
2562 set_err(errbuf, errlen, overflow);
2563 return RGPOT_ENGINE_ERR_INVALID;
2564} catch (const std::exception& ex) {
2565 if (pot != nullptr) pot->last_error = ex.what();
2566 set_err(errbuf, errlen, ex.what());
2567 return -2;
2568}
2569
2570} // extern "C"
Host check for the instruction set an AOTInductor package needs.
static void set_err(char *errbuf, size_t errlen, const char *msg)
@ z
Definition Enums.h:28
@ x
Definition Enums.h:28
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)
#define EMPTY
Definition Macros.h:39
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.
Definition ActiveGP.h:64
ActiveGPConfig Config
Definition ActiveGP.h:69
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
uint64_t epoch
size_t char * errbuf
size_t config_len
@ 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
@ RGPOT_GPR_HILL_TRUE
@ RGPOT_GPR_HILL_GP
#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_HILL
@ RGPOT_GPR_PHASE_SADDLE
@ 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.
Definition gpridge_c.h:256
@ GPR_MODEL_GP
Definition gpridge_c.h:319
@ GPR_HSSVD_BACKEND_CHOLESKY
Definition gpridge_c.h:273
const char * gpr_last_error(void)
Thread-local error message from last failing call. Never NULL.
@ GPR_SUCCESS
Definition gpridge_c.h:208
@ GPR_ERR_UNSUPPORTED
Definition gpridge_c.h:220
struct gpr_model_s * gpr_model_t
Type-safe opaque handles. In Fortran, declare as type(c_ptr). The compiler catches type mismatches (u...
Definition gpridge_c.h:384
struct gpr_atoms_s * gpr_atoms_t
Definition gpridge_c.h:389
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).
uint32_t Index_t
Definition Macros.h:17
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 fits
unsigned long long true_energy_calls
unsigned long long observations
RgpotEngineCallbacks callbacks
std::string reactant_path
std::string last_error
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.
Definition Structures.h:832
FieldMatrixi atomicNrs
Atomic Number of each atom.
Definition Structures.h:836
FieldMatrixU8 is_frozen
Indicates whether atom is frozen or not.
Definition Structures.h:834
FieldMatrixIdx id
ID of each atom (we do not use it).
Definition Structures.h:835
AtomsPositionAndType atoms_mov
Info on moving atoms.
Definition Structures.h:844
FieldMatrixIdx type
Type of each atom.
Definition Structures.h:839
Coord positions
Positions of all atoms in the system.
Definition Structures.h:833
void resize(const Index_t num_atoms)
Definition Structures.h:814
Structure of the input parameters. All input parameters are pairs of string names and values.
Definition Structures.h:370
KeyValuePair< int > report_level
Definition Structures.h:673
std::function< void(gpr::InputParameters &, gpr::AtomsConfiguration &)> gp_setup
Definition Session.h:1141
Atoms configuration descriptor. Describes the atomic system for the GP kernel (pair types,...
Definition gpridge_c.h:480
const int * atom_types
Definition gpridge_c.h:485
const int * atomic_nrs
Definition gpridge_c.h:486
const int * is_frozen
Definition gpridge_c.h:483
const double * positions
Definition gpridge_c.h:488
GP/TP model configuration. All fields have sensible defaults via gpr_model_config_defaults().
Definition gpridge_c.h:508
gpridge_alg_t optim_alg
Definition gpridge_c.h:516