Loading...
Searching...
No Matches
pot::EnginePotential Class Reference

#include <gpr/potentials/EnginePotential.h>

Public Member Functions

 ~EnginePotential ()
 EnginePotential (const EnginePotential &)=delete
EnginePotential & operator= (const EnginePotential &)=delete
int force (long n_atoms, const double *positions, const int *atomic_nrs, const double *box, double *forces, double *energy, double *variance)
bool hasBatch () const noexcept
 True when the engine exports rgpot_engine_force_batch.
int forceBatch (long n_systems, long n_atoms, const double *positions, const int *atomic_nrs, const double *boxes, double *forces, double *energies, double *variances)
bool hasCallbacks () const noexcept
 True when the engine exports rgpot_engine_set_callbacks.
int setCallbacks (const RgpotEngineCallbacks &callbacks)
 Register host callbacks for a learning engine.
bool hasHessianChecked () const noexcept
 True when the engine exports rgpot_engine_hessian_checked.
int hessianChecked (long n_atoms, const double *positions, std::size_t positions_len, const int *atomic_nrs, double *hessian_out, std::size_t hessian_len, const double *box)
 Extent-checked dense Hessian at one geometry.
bool hasHessianActionChecked () const noexcept
 True when the engine exports rgpot_engine_hessian_action_checked.
int hessianActionChecked (long n_atoms, const double *positions, std::size_t positions_len, const int *atomic_nrs, const double *direction, std::size_t direction_len, double *hv_out, std::size_t hv_len, const double *box, unsigned long long *ops_out, double *scale_out)
bool hasPredictionSupportedChecked () const noexcept
int predictionSupportedChecked (long n_atoms, const double *positions, std::size_t positions_len, const int *atomic_nrs, const double *box, int *supported_out)
 Extent-checked prediction-support query.
bool hasGprStats () const noexcept
 True when the engine exports rgpot_engine_gpr_stats.
int gprStats (RgpotEngineGprStats &stats_out) const
 Read learning-engine operation counters.
unsigned long long modelState () const
 Monotone model-state counter; zero for an engine without one.
int hint (const std::vector< unsigned char > &message, std::string &err)
EngineAbiStamp abiStamp () const noexcept
 The stamp the plugin reported, or {1, 0, 1} when it exports none.
int caps (EngineCaps &out, std::string &err)
int hvp (long n_atoms, const double *positions, const int *atomic_nrs, const double *direction, double *hv_out, const double *box, std::string &err)
int taylorJet (long n_systems, long n_atoms, const double *positions, const int *atomic_nrs, const double *directions, long order, double *jet_out, EngineDerivativeReport *report, const double *boxes, std::string &err)
int setCache (const char *path, std::string &err)
int cacheCounts (std::uint64_t &computed, std::uint64_t &served, std::string &err)
std::string lastError () const
bool unloadSafe () const
int abiVersion () const noexcept
int threadCount () const noexcept
 OpenMP team requested explicitly by the host for every engine call.
void setThreadCount (int threads)
const std::string & library () const noexcept
const std::string & resolvedPath () const noexcept
 Absolute path of the loaded object, from the dynamic loader.
bool dead () const noexcept
 True once a negative status was returned: the handle is unusable.

Static Public Member Functions

static std::unique_ptr< EnginePotential > open (const std::string &library, const std::vector< unsigned char > &config, std::string &err, bool torch_cuda=false, int oracle_threads=1)
static PotentialWrapper wrap (std::shared_ptr< EnginePotential > engine)

Detailed Description

One instance owns one engine handle. caps().reentrancy says whether the plugin allows concurrent calls on that handle. This host still uses one handle from one thread; a caller that evaluates from several threads opens one instance per thread.

Definition at line 87 of file EnginePotential.h.

Constructor & Destructor Documentation

◆ ~EnginePotential()

pot::EnginePotential::~EnginePotential ( )

Definition at line 382 of file EnginePotential.cpp.

383{
384 if (pot_ != nullptr && destroy_ != nullptr) {
385 reinterpret_cast<destroy_fn>(destroy_)(
386 static_cast<RgpotEnginePot*>(pot_));
387 }
388 // The handle outlives the potential deliberately: the engine's own
389 // teardown runs inside destroy, and unloading first would pull the code
390 // out from under it. Minor 7 then keeps the library mapped unless
391 // unloadSafe() reports RGPOT_ENGINE_UNLOAD_SAFE.
392 if (handle_ != nullptr && unloadSafe()) dlclose(handle_);
393}

◆ EnginePotential()

pot::EnginePotential::EnginePotential ( const EnginePotential & )
delete

Member Function Documentation

◆ abiStamp()

EngineAbiStamp pot::EnginePotential::abiStamp ( ) const
inlinenodiscardnoexcept

The stamp the plugin reported, or {1, 0, 1} when it exports none.

Definition at line 189 of file EnginePotential.h.

190 {
191 return stamp_;
192 }

◆ abiVersion()

int pot::EnginePotential::abiVersion ( ) const
inlinenodiscardnoexcept

Definition at line 233 of file EnginePotential.h.

234 {
235 return abi_version_;
236 }

◆ cacheCounts()

int pot::EnginePotential::cacheCounts ( std::uint64_t & computed,
std::uint64_t & served,
std::string & err )

Kernel-computed and cache-served counts since the cache was attached. Returns 3 when the plugin exports no query, or when none is attached.

Definition at line 754 of file EnginePotential.cpp.

756{
757 if (dead_) return -1;
758 if (cache_counts_ == nullptr) {
759 err = library_ + ": rgpot_engine_cache_counts is not exported";
760 return RGPOT_ENGINE_ERR_UNSUPPORTED;
761 }
762 const int status = reinterpret_cast<cache_counts_fn>(cache_counts_)(
763 static_cast<RgpotEnginePot*>(pot_), &computed, &served);
764 return noteCall(status, "rgpot_engine_cache_counts", err);
765}
int status

◆ caps()

int pot::EnginePotential::caps ( EngineCaps & out,
std::string & err )

rgpot_engine_caps. Returns 3 when the plugin exports no caps symbol. jet_order is zero when the written size ends before that field.

Definition at line 521 of file EnginePotential.cpp.

522{
523 out = {};
524 if (dead_) {
525 err = library_ + ": engine handle is unusable";
526 return -1;
527 }
528 if (caps_ == nullptr) {
529 err = library_ + ": rgpot_engine_caps is not exported";
530 return RGPOT_ENGINE_ERR_UNSUPPORTED;
531 }
532 RgpotEngineCaps raw{};
533 raw.size = sizeof(raw);
534 const int status = reinterpret_cast<caps_fn>(caps_)(
535 static_cast<const RgpotEnginePot*>(pot_), &raw);
536 if (status != 0) return noteCall(status, "rgpot_engine_caps", err);
537 const std::size_t written = raw.size;
538 auto take = [&](std::size_t end, int value) {
539 return written >= end ? value : 0;
540 };
541 auto endOf = [](std::size_t offset) { return offset + sizeof(int); };
542 out.reentrancy =
543 take(endOf(offsetof(RgpotEngineCaps, reentrancy)), raw.reentrancy);
544 out.per_image_instances =
545 take(endOf(offsetof(RgpotEngineCaps, per_image_instances)),
546 raw.per_image_instances);
547 out.batched = take(endOf(offsetof(RgpotEngineCaps, batched)), raw.batched);
548 out.periodic =
549 take(endOf(offsetof(RgpotEngineCaps, periodic)), raw.periodic);
550 out.stress = take(endOf(offsetof(RgpotEngineCaps, stress)), raw.stress);
551 out.group_collective =
552 take(endOf(offsetof(RgpotEngineCaps, group_collective)),
553 raw.group_collective);
554 out.orbital_selection =
555 take(endOf(offsetof(RgpotEngineCaps, orbital_selection)),
556 raw.orbital_selection);
557 out.orbital_copy =
558 take(endOf(offsetof(RgpotEngineCaps, orbital_copy)), raw.orbital_copy);
559 out.analytic_hvp =
560 take(endOf(offsetof(RgpotEngineCaps, analytic_hvp)), raw.analytic_hvp);
561 out.jet_order =
562 take(endOf(offsetof(RgpotEngineCaps, jet_order)), raw.jet_order);
563 return RGPOT_ENGINE_OK;
564}
eon_relax_band_t eon_relax_surface_fn void eon_relax_outcome_t * out

◆ dead()

bool pot::EnginePotential::dead ( ) const
inlinenodiscardnoexcept

True once a negative status was returned: the handle is unusable.

Definition at line 253 of file EnginePotential.h.

254 {
255 return dead_;
256 }

◆ force()

int pot::EnginePotential::force ( long n_atoms,
const double * positions,
const int * atomic_nrs,
const double * box,
double * forces,
double * energy,
double * variance )

Energy and forces for one system. Returns the engine status; zero is success. variance may be null.

Definition at line 395 of file EnginePotential.cpp.

398{
399 if (dead_) return -1;
400 ScopedOracleThreads oracle_threads(oracle_threads_);
401 const int status = reinterpret_cast<force_fn>(force_)(
402 static_cast<RgpotEnginePot*>(pot_), n_atoms, positions, atomic_nrs,
403 forces, energy, variance, box, nullptr, nullptr);
404 if (status < 0) dead_ = true;
405 return status;
406}

◆ forceBatch()

int pot::EnginePotential::forceBatch ( long n_systems,
long n_atoms,
const double * positions,
const int * atomic_nrs,
const double * boxes,
double * forces,
double * energies,
double * variances )

Strided-uniform batch: n_systems systems of one composition. boxes holds 9 doubles per system.

Definition at line 408 of file EnginePotential.cpp.

412{
413 if (batch_ == nullptr) return -1;
414 if (dead_) return -1;
415 ScopedOracleThreads oracle_threads(oracle_threads_);
416 const int status = reinterpret_cast<batch_fn>(batch_)(
417 static_cast<RgpotEnginePot*>(pot_), n_systems, n_atoms, positions,
418 atomic_nrs, forces, energies, variances, boxes, nullptr, nullptr);
419 if (status < 0) dead_ = true;
420 return status;
421}

◆ gprStats()

int pot::EnginePotential::gprStats ( RgpotEngineGprStats & stats_out) const

Read learning-engine operation counters.

Definition at line 476 of file EnginePotential.cpp.

477{
478 if (gpr_stats_ == nullptr) return RGPOT_ENGINE_ERR_UNSUPPORTED;
479 stats_out.struct_size = sizeof(RgpotEngineGprStats);
480 return reinterpret_cast<gpr_stats_fn>(gpr_stats_)(
481 static_cast<const RgpotEnginePot*>(pot_), &stats_out);
482}

◆ hasBatch()

bool pot::EnginePotential::hasBatch ( ) const
inlinenodiscardnoexcept

True when the engine exports rgpot_engine_force_batch.

Definition at line 112 of file EnginePotential.h.

113 {
114 return batch_ != nullptr;
115 }

◆ hasCallbacks()

bool pot::EnginePotential::hasCallbacks ( ) const
inlinenodiscardnoexcept

True when the engine exports rgpot_engine_set_callbacks.

Definition at line 124 of file EnginePotential.h.

125 {
126 return set_callbacks_ != nullptr;
127 }

◆ hasGprStats()

bool pot::EnginePotential::hasGprStats ( ) const
inlinenodiscardnoexcept

True when the engine exports rgpot_engine_gpr_stats.

Definition at line 173 of file EnginePotential.h.

174 {
175 return gpr_stats_ != nullptr;
176 }

◆ hasHessianActionChecked()

bool pot::EnginePotential::hasHessianActionChecked ( ) const
inlinenodiscardnoexcept

True when the engine exports rgpot_engine_hessian_action_checked.

Definition at line 145 of file EnginePotential.h.

146 {
147 return hessian_action_checked_ != nullptr;
148 }

◆ hasHessianChecked()

bool pot::EnginePotential::hasHessianChecked ( ) const
inlinenodiscardnoexcept

True when the engine exports rgpot_engine_hessian_checked.

Definition at line 133 of file EnginePotential.h.

134 {
135 return hessian_checked_ != nullptr;
136 }

◆ hasPredictionSupportedChecked()

bool pot::EnginePotential::hasPredictionSupportedChecked ( ) const
inlinenodiscardnoexcept

True when the engine exports rgpot_engine_prediction_supported_checked.

Definition at line 161 of file EnginePotential.h.

162 {
163 return prediction_supported_checked_ != nullptr;
164 }

◆ hessianActionChecked()

int pot::EnginePotential::hessianActionChecked ( long n_atoms,
const double * positions,
std::size_t positions_len,
const int * atomic_nrs,
const double * direction,
std::size_t direction_len,
double * hv_out,
std::size_t hv_len,
const double * box,
unsigned long long * ops_out,
double * scale_out )

Extent-checked Hessian-vector product with optional operation accounting.

Definition at line 444 of file EnginePotential.cpp.

449{
450 if (hessian_action_checked_ == nullptr) return RGPOT_ENGINE_ERR_UNSUPPORTED;
451 if (dead_) return -1;
452 const int status =
453 reinterpret_cast<hessian_action_checked_fn>(hessian_action_checked_)(
454 static_cast<RgpotEnginePot*>(pot_), n_atoms, positions,
455 positions_len, atomic_nrs, direction, direction_len, hv_out, hv_len,
456 box, ops_out, scale_out);
457 if (status < 0) dead_ = true;
458 return status;
459}

◆ hessianChecked()

int pot::EnginePotential::hessianChecked ( long n_atoms,
const double * positions,
std::size_t positions_len,
const int * atomic_nrs,
double * hessian_out,
std::size_t hessian_len,
const double * box )

Extent-checked dense Hessian at one geometry.

Definition at line 430 of file EnginePotential.cpp.

434{
435 if (hessian_checked_ == nullptr) return RGPOT_ENGINE_ERR_UNSUPPORTED;
436 if (dead_) return -1;
437 const int status = reinterpret_cast<hessian_checked_fn>(hessian_checked_)(
438 static_cast<RgpotEnginePot*>(pot_), n_atoms, positions, positions_len,
439 atomic_nrs, hessian_out, hessian_len, box);
440 if (status < 0) dead_ = true;
441 return status;
442}

◆ hint()

int pot::EnginePotential::hint ( const std::vector< unsigned char > & message,
std::string & err )

Send a runtime hint message; returns the engine status, or -1 when the engine exports no hint entry point.

Definition at line 491 of file EnginePotential.cpp.

493{
494 if (hint_ == nullptr) {
495 err = library_ + ": engine exports no hint entry point";
496 return -1;
497 }
498 char errbuf[1024]{};
499 const int status = reinterpret_cast<hint_fn>(hint_)(
500 static_cast<RgpotEnginePot*>(pot_),
501 message.empty() ? nullptr : message.data(), message.size(), errbuf,
502 sizeof errbuf);
503 if (status != 0) err = library_ + ": hint rejected: " + errbuf;
504 return status;
505}
size_t char * errbuf

◆ hvp()

int pot::EnginePotential::hvp ( long n_atoms,
const double * positions,
const int * atomic_nrs,
const double * direction,
double * hv_out,
const double * box,
std::string & err )

Analytic Hessian-vector product. Returns 3 when the plugin does not export rgpot_engine_hvp or rgpot_engine_caps, or when analytic_hvp is clear. A negative status marks the handle dead.

Definition at line 566 of file EnginePotential.cpp.

569{
570 if (dead_) return -1;
571 if (hvp_ == nullptr) {
572 err = library_ + ": rgpot_engine_hvp is not exported";
573 return RGPOT_ENGINE_ERR_UNSUPPORTED;
574 }
575 if (caps_ == nullptr) {
576 err = library_ + ": rgpot_engine_hvp requires rgpot_engine_caps";
577 return RGPOT_ENGINE_ERR_UNSUPPORTED;
578 }
579 if (n_atoms <= 0 || positions == nullptr || direction == nullptr ||
580 hv_out == nullptr) {
581 err = library_ + ": rgpot_engine_hvp arguments are invalid";
582 return RGPOT_ENGINE_ERR_INVALID;
583 }
584 const std::size_t n_coord = static_cast<std::size_t>(n_atoms) * 3;
585 const int bad_position = firstNonFinite(positions, n_coord);
586 if (bad_position >= 0) {
587 err = library_ + ": the engine position at element " +
588 std::to_string(bad_position) + " is not finite";
589 return RGPOT_ENGINE_ERR_INVALID;
590 }
591 const int bad_direction = firstNonFinite(direction, n_coord);
592 if (bad_direction >= 0) {
593 err = library_ + ": the engine direction at element " +
594 std::to_string(bad_direction) + " is not finite";
595 return RGPOT_ENGINE_ERR_INVALID;
596 }
597 if (box != nullptr) {
598 const int bad_box = firstNonFinite(box, 9);
599 if (bad_box >= 0) {
600 err = library_ + ": the engine box at element " +
601 std::to_string(bad_box) + " is not finite";
602 return RGPOT_ENGINE_ERR_INVALID;
603 }
604 }
605 if (rangesOverlap(direction, hv_out, n_coord * sizeof(double))) {
606 err = library_ + ": rgpot_engine_hvp direction and output overlap";
607 return RGPOT_ENGINE_ERR_INVALID;
608 }
609 EngineCaps capabilities;
610 const int caps_status = caps(capabilities, err);
611 if (caps_status != 0) return caps_status;
612 if (capabilities.analytic_hvp == 0) {
613 err = library_ + ": analytic_hvp is not advertised";
614 return RGPOT_ENGINE_ERR_UNSUPPORTED;
615 }
616 const int status = reinterpret_cast<hvp_fn>(hvp_)(
617 static_cast<RgpotEnginePot*>(pot_), n_atoms, positions, atomic_nrs,
618 direction, hv_out, box);
619 return noteCall(status, "rgpot_engine_hvp", err);
620}
int caps(EngineCaps &out, std::string &err)

◆ lastError()

std::string pot::EnginePotential::lastError ( ) const
nodiscard

Text of rgpot_engine_last_error, or empty when the plugin exports none or there is no message.

Definition at line 767 of file EnginePotential.cpp.

768{
769 if (last_error_ == nullptr || pot_ == nullptr) return {};
770 char buf[1024]{};
771 const std::size_t length = reinterpret_cast<last_error_fn>(last_error_)(
772 static_cast<const RgpotEnginePot*>(pot_), buf, sizeof buf);
773 if (length == 0 || buf[0] == '\0') return {};
774 return std::string(buf);
775}

◆ library()

const std::string & pot::EnginePotential::library ( ) const
inlinenodiscardnoexcept

Definition at line 243 of file EnginePotential.h.

244 {
245 return library_;
246 }

◆ modelState()

unsigned long long pot::EnginePotential::modelState ( ) const
nodiscard

Monotone model-state counter; zero for an engine without one.

Definition at line 484 of file EnginePotential.cpp.

485{
486 if (model_state_ == nullptr) return 0;
487 return reinterpret_cast<state_fn>(model_state_)(
488 static_cast<const RgpotEnginePot*>(pot_));
489}

◆ open()

std::unique_ptr< EnginePotential > pot::EnginePotential::open ( const std::string & library,
const std::vector< unsigned char > & config,
std::string & err,
bool torch_cuda = false,
int oracle_threads = 1 )
static
Parameters
librarypath or soname handed to dlopen (RTLD_LOCAL).
configcapnp flat-array message for the engine's params arm.
errfailure detail when construction returns nullptr.
torch_cudathe engine evaluates on a CUDA device: load the libtorch_cuda runtime next to the libtorch_cpu the engine brought in before the engine is created. A torch engine links libtorch_cpu only, and the CUDA hooks register when libtorch_cuda is loaded.
oracle_threadsEvaluation thread count; at least one.

Definition at line 189 of file EnginePotential.cpp.

192{
193 if (oracle_threads < 1) {
194 err = "engine oracle thread count must be at least 1";
195 return nullptr;
196 }
197 if (library.empty()) {
198 err = "no engine library for this oracle";
199 return nullptr;
200 }
201 // RTLD_LOCAL, unlike the host's RTLD_GLOBAL: two engines may link
202 // different builds of the same backend, and promoting one's symbols to
203 // global would let it answer the other's calls.
204 void* handle = dlopen(library.c_str(), RTLD_NOW | RTLD_LOCAL);
205 if (handle == nullptr) {
206 const char* e = dlerror();
207 err = "dlopen " + library + ": " + (e != nullptr ? e : "unknown");
208 return nullptr;
209 }
210
211 auto abi =
212 reinterpret_cast<int (*)()>(dlsym(handle, "rgpot_engine_abi_version"));
213 auto create =
214 reinterpret_cast<create_fn>(dlsym(handle, "rgpot_engine_create"));
215 auto destroy =
216 reinterpret_cast<destroy_fn>(dlsym(handle, "rgpot_engine_destroy"));
217 auto force =
218 reinterpret_cast<force_fn>(dlsym(handle, "rgpot_engine_force"));
219 if (abi == nullptr || create == nullptr || destroy == nullptr ||
220 force == nullptr) {
221 dlclose(handle);
222 err = library + ": engine C ABI incomplete";
223 return nullptr;
224 }
225 const int version = abi();
226 if (version != RGPOT_ENGINE_ABI_VERSION) {
227 dlclose(handle);
228 err = library + ": engine C ABI version " + std::to_string(version) +
229 " does not match the host's " +
230 std::to_string(RGPOT_ENGINE_ABI_VERSION);
231 return nullptr;
232 }
233
234 // Minor 11 is the pinned header. A plugin serves this host when the
235 // major and the layout revision match and its minor is at most that.
236 // The optional symbols added since minor 0 (cache, unload, the jet and
237 // its caps field) are absent on an older plugin. A library without
238 // rgpot_engine_abi_stamp is that minor 0, layout 1 case.
239 RgpotEngineAbiStamp stamp{1, 0, 1};
240 dlerror();
241 auto stamp_of =
242 reinterpret_cast<stamp_fn>(dlsym(handle, "rgpot_engine_abi_stamp"));
243 if (stamp_of != nullptr) stamp = stamp_of();
244 if (!stampServesHost(stamp)) {
245 dlclose(handle);
246 err =
247 library + ": engine ABI stamp " + formatStamp(stamp) +
248 " cannot serve host stamp " +
249 formatStamp(
250 static_cast<unsigned short>(RGPOT_ENGINE_ABI_VERSION),
251 static_cast<unsigned short>(RGPOT_ENGINE_ABI_MINOR),
252 static_cast<unsigned short>(RGPOT_ENGINE_ABI_LAYOUT_REVISION));
253 return nullptr;
254 }
255
256 // rgpot_engine_available is optional. An engine that does not export it
257 // is available; an export that returns zero is refused before create.
258 dlerror();
259 auto available =
260 reinterpret_cast<available_fn>(dlsym(handle, "rgpot_engine_available"));
261 if (available != nullptr && available() == 0) {
262 dlclose(handle);
263 err = library +
264 ": rgpot_engine_available reported that the engine is "
265 "unavailable";
266 return nullptr;
267 }
268
269 // An AOTI package's compiled model needs libtorch.so. An engine may link
270 // only libtorch_cpu and libc10, and a model whose own run path names the
271 // environment it was exported in does not search the driver's run paths,
272 // so libtorch.so is loaded here from beside the engine's libtorch_cpu; the
273 // model's dependency then resolves to it by name. It stays loaded, as the
274 // CUDA runtime does, since torch keeps process-wide state.
275 const std::string torch_dir = torchLibraryDirectory(handle);
276 if (!torch_dir.empty()) {
277 const std::string torch_library = torch_dir + "libtorch.so";
278 if (::access(torch_library.c_str(), F_OK) == 0 &&
279 dlopen(torch_library.c_str(), RTLD_NOW | RTLD_LOCAL) == nullptr) {
280 const char* e = dlerror();
281 const std::string loader_error = e != nullptr ? e : "unknown";
282 dlclose(handle);
283 err = "dlopen " + torch_library + ": " + loader_error;
284 return nullptr;
285 }
286 }
287
288 void* cuda_runtime = nullptr;
289 if (torch_cuda) {
290 // libtorch_cuda registers the CUDA device hooks with the
291 // libtorch_cpu already loaded for the engine; the loader resolves
292 // its libtorch_cpu dependency to that same instance.
293 if (torch_dir.empty()) {
294 dlclose(handle);
295 err = library +
296 ": a CUDA device was requested but the engine loads no "
297 "libtorch_cpu";
298 return nullptr;
299 }
300 const std::string cuda_library = torch_dir + "libtorch_cuda.so";
301 cuda_runtime = dlopen(cuda_library.c_str(), RTLD_NOW | RTLD_LOCAL);
302 if (cuda_runtime == nullptr) {
303 const char* e = dlerror();
304 const std::string loader_error = e != nullptr ? e : "unknown";
305 dlclose(handle);
306 err = "dlopen " + cuda_library + ": " + loader_error +
307 " (a CUDA device needs the CUDA build of torch next to "
308 "the engine's libtorch_cpu)";
309 return nullptr;
310 }
311 }
312
313 char errbuf[1024]{};
314 RgpotEnginePot* pot = create(config.empty() ? nullptr : config.data(),
315 config.size(), errbuf, sizeof errbuf);
316 if (pot == nullptr) {
317 dlclose(handle);
318 err = library + ": create failed: " + errbuf;
319 return nullptr;
320 }
321
322 std::unique_ptr<EnginePotential> self(new EnginePotential());
323 self->handle_ = handle;
324 self->pot_ = pot;
325 self->force_ = reinterpret_cast<void*>(force);
326 self->batch_ = dlsym(handle, "rgpot_engine_force_batch");
327 self->set_callbacks_ = dlsym(handle, "rgpot_engine_set_callbacks");
328 self->hessian_checked_ = dlsym(handle, "rgpot_engine_hessian_checked");
329 self->hessian_action_checked_ =
330 dlsym(handle, "rgpot_engine_hessian_action_checked");
331 self->prediction_supported_checked_ =
332 dlsym(handle, "rgpot_engine_prediction_supported_checked");
333 self->gpr_stats_ = dlsym(handle, "rgpot_engine_gpr_stats");
334 self->torch_cuda_ = cuda_runtime;
335 self->destroy_ = reinterpret_cast<void*>(destroy);
336 self->model_state_ = dlsym(handle, "rgpot_engine_model_state");
337 self->hint_ = dlsym(handle, "rgpot_engine_hint");
338 self->set_num_threads_ = dlsym(handle, "rgpot_engine_set_num_threads");
339 self->caps_ = dlsym(handle, "rgpot_engine_caps");
340 self->hvp_ = dlsym(handle, "rgpot_engine_hvp");
341 self->taylor_jet_ = dlsym(handle, "rgpot_engine_taylor_jet");
342 self->set_cache_ = dlsym(handle, "rgpot_engine_set_cache");
343 self->cache_counts_ = dlsym(handle, "rgpot_engine_cache_counts");
344 self->unload_policy_ = dlsym(handle, "rgpot_engine_unload_policy");
345 self->last_error_ = dlsym(handle, "rgpot_engine_last_error");
346 self->stamp_ = {stamp.abi_major, stamp.abi_minor, stamp.layout_revision};
347 self->abi_version_ = version;
348 self->oracle_threads_ = oracle_threads;
349 self->library_ = library;
350 self->resolved_path_ = library;
351 struct link_map* map = nullptr;
352 if (dlinfo(handle, RTLD_DI_LINKMAP, &map) == 0 && map != nullptr &&
353 map->l_name != nullptr && map->l_name[0] != '\0') {
354 self->resolved_path_ = map->l_name;
355 }
356 try {
357 self->setThreadCount(oracle_threads);
358 } catch (const std::exception& exception) {
359 err = library + ": " + exception.what();
360 return nullptr;
361 }
362 return self;
363}
int force(long n_atoms, const double *positions, const int *atomic_nrs, const double *box, double *forces, double *energy, double *variance)
const std::string & library() const noexcept
EnginePotential(const EnginePotential &)=delete
std::string version()
Definition gpridge.hpp:339
bool available() noexcept
Definition CutlassGemm.h:43

◆ operator=()

EnginePotential & pot::EnginePotential::operator= ( const EnginePotential & )
delete

◆ predictionSupportedChecked()

int pot::EnginePotential::predictionSupportedChecked ( long n_atoms,
const double * positions,
std::size_t positions_len,
const int * atomic_nrs,
const double * box,
int * supported_out )

Extent-checked prediction-support query.

Definition at line 461 of file EnginePotential.cpp.

464{
465 if (prediction_supported_checked_ == nullptr)
466 return RGPOT_ENGINE_ERR_UNSUPPORTED;
467 if (dead_) return -1;
468 const int status = reinterpret_cast<prediction_supported_checked_fn>(
469 prediction_supported_checked_)(static_cast<RgpotEnginePot*>(pot_),
470 n_atoms, positions, positions_len,
471 atomic_nrs, box, supported_out);
472 if (status < 0) dead_ = true;
473 return status;
474}

◆ resolvedPath()

const std::string & pot::EnginePotential::resolvedPath ( ) const
inlinenodiscardnoexcept

Absolute path of the loaded object, from the dynamic loader.

Definition at line 248 of file EnginePotential.h.

249 {
250 return resolved_path_;
251 }

◆ setCache()

int pot::EnginePotential::setCache ( const char * path,
std::string & err )

Attach a persistent result cache, or detach it when path is null. Returns 3 when the plugin exports no rgpot_engine_set_cache.

Definition at line 742 of file EnginePotential.cpp.

743{
744 if (dead_) return -1;
745 if (set_cache_ == nullptr) {
746 err = library_ + ": rgpot_engine_set_cache is not exported";
747 return RGPOT_ENGINE_ERR_UNSUPPORTED;
748 }
749 const int status = reinterpret_cast<set_cache_fn>(set_cache_)(
750 static_cast<RgpotEnginePot*>(pot_), path);
751 return noteCall(status, "rgpot_engine_set_cache", err);
752}

◆ setCallbacks()

int pot::EnginePotential::setCallbacks ( const RgpotEngineCallbacks & callbacks)

Register host callbacks for a learning engine.

Definition at line 423 of file EnginePotential.cpp.

424{
425 if (set_callbacks_ == nullptr || dead_) return -1;
426 return reinterpret_cast<set_callbacks_fn>(set_callbacks_)(
427 static_cast<RgpotEnginePot*>(pot_), &callbacks);
428}

◆ setThreadCount()

void pot::EnginePotential::setThreadCount ( int threads)

Definition at line 365 of file EnginePotential.cpp.

366{
367 if (threads < 1)
368 throw std::invalid_argument(
369 "engine oracle thread count must be at least 1");
370 if (set_num_threads_ != nullptr) {
371 const int status = reinterpret_cast<set_num_threads_fn>(
372 set_num_threads_)(static_cast<RgpotEnginePot*>(pot_), threads, 1);
373 // Status 3 is the documented "no tensor runtime" response. The
374 // OpenMP scope still controls a classical engine.
375 if (status != 0 && status != 3)
376 throw std::runtime_error(
377 "engine rejected its explicit thread count");
378 }
379 oracle_threads_ = threads;
380}

◆ taylorJet()

int pot::EnginePotential::taylorJet ( long n_systems,
long n_atoms,
const double * positions,
const int * atomic_nrs,
const double * directions,
long order,
double * jet_out,
EngineDerivativeReport * report,
const double * boxes,
std::string & err )

Directional derivatives of the gradient up to order, one uniform batch. Returns 3 when the plugin exports no jet or caps symbol, or when order exceeds jet_order. A non-finite position, direction or cell, an order below 1, and a negative or non-finite report scale are status 1 and do not replace report. Inputs and output must not overlap.

Definition at line 622 of file EnginePotential.cpp.

627{
628 if (dead_) return -1;
629 if (taylor_jet_ == nullptr) {
630 err = library_ + ": rgpot_engine_taylor_jet is not exported";
631 return RGPOT_ENGINE_ERR_UNSUPPORTED;
632 }
633 if (caps_ == nullptr) {
634 err = library_ + ": rgpot_engine_taylor_jet requires rgpot_engine_caps";
635 return RGPOT_ENGINE_ERR_UNSUPPORTED;
636 }
637 if (order < 1) {
638 err = library_ + ": a jet needs order at least 1";
639 return RGPOT_ENGINE_ERR_INVALID;
640 }
641 if (n_systems <= 0 || n_atoms <= 0 || positions == nullptr ||
642 directions == nullptr || jet_out == nullptr) {
643 err = library_ + ": rgpot_engine_taylor_jet arguments are invalid";
644 return RGPOT_ENGINE_ERR_INVALID;
645 }
646 EngineCaps capabilities;
647 const int caps_status = caps(capabilities, err);
648 if (caps_status != 0) return caps_status;
649 if (capabilities.jet_order < 0) {
650 err = library_ + ": the engine reports a negative jet order " +
651 std::to_string(capabilities.jet_order);
652 return RGPOT_ENGINE_ERR_INVALID;
653 }
654 if (order > capabilities.jet_order) {
655 err = library_ + ": jet order " + std::to_string(order) +
656 " requested; the engine serves " +
657 std::to_string(capabilities.jet_order);
658 return RGPOT_ENGINE_ERR_UNSUPPORTED;
659 }
660 const std::size_t n_coord = static_cast<std::size_t>(n_systems) *
661 static_cast<std::size_t>(n_atoms) * 3;
662 const int bad_position = firstNonFinite(positions, n_coord);
663 if (bad_position >= 0) {
664 err = library_ + ": the engine position at element " +
665 std::to_string(bad_position) + " is not finite";
666 return RGPOT_ENGINE_ERR_INVALID;
667 }
668 const int bad_direction = firstNonFinite(directions, n_coord);
669 if (bad_direction >= 0) {
670 err = library_ + ": the engine direction at element " +
671 std::to_string(bad_direction) + " is not finite";
672 return RGPOT_ENGINE_ERR_INVALID;
673 }
674 if (boxes != nullptr) {
675 const int bad_box =
676 firstNonFinite(boxes, static_cast<std::size_t>(n_systems) * 9);
677 if (bad_box >= 0) {
678 err = library_ + ": the engine box at element " +
679 std::to_string(bad_box) + " is not finite";
680 return RGPOT_ENGINE_ERR_INVALID;
681 }
682 }
683 // jet_out is order blocks of n_coord. A later block still aliases.
684 const std::size_t coord_bytes = n_coord * sizeof(double);
685 const std::size_t jet_bytes = static_cast<std::size_t>(order) * coord_bytes;
686 const std::size_t number_bytes =
687 atomic_nrs == nullptr ? 0
688 : static_cast<std::size_t>(n_atoms) * sizeof(int);
689 const std::size_t box_bytes =
690 boxes == nullptr
691 ? 0
692 : static_cast<std::size_t>(n_systems) * 9 * sizeof(double);
693 if (rangesOverlap(positions, coord_bytes, jet_out, jet_bytes) ||
694 rangesOverlap(directions, coord_bytes, jet_out, jet_bytes) ||
695 rangesOverlap(atomic_nrs, number_bytes, jet_out, jet_bytes) ||
696 rangesOverlap(boxes, box_bytes, jet_out, jet_bytes) ||
697 rangesOverlap(directions, coord_bytes, positions, coord_bytes) ||
698 rangesOverlap(directions, coord_bytes, atomic_nrs, number_bytes) ||
699 rangesOverlap(directions, coord_bytes, boxes, box_bytes)) {
700 err = library_ + ": rgpot_engine_taylor_jet inputs and output overlap";
701 return RGPOT_ENGINE_ERR_INVALID;
702 }
703 RgpotEngineDerivativeReport raw{};
704 const int status = reinterpret_cast<taylor_fn>(taylor_jet_)(
705 static_cast<RgpotEnginePot*>(pot_), n_systems, n_atoms, positions,
706 atomic_nrs, directions, order, jet_out,
707 report != nullptr ? &raw : nullptr, boxes);
708 if (status != 0) return noteCall(status, "rgpot_engine_taylor_jet", err);
709 const std::size_t jet_len = static_cast<std::size_t>(order) * n_coord;
710 const int bad_jet = firstNonFinite(jet_out, jet_len);
711 if (bad_jet >= 0) {
712 err = library_ + ": the engine jet at element " +
713 std::to_string(bad_jet) + " is not finite";
714 return RGPOT_ENGINE_ERR_INVALID;
715 }
716 if (report != nullptr && raw.tracked != 0) {
717 if (raw.operations < 0) {
718 err = library_ +
719 ": the engine reports a negative operation count " +
720 std::to_string(raw.operations);
721 return RGPOT_ENGINE_ERR_INVALID;
722 }
723 if (!std::isfinite(raw.scale)) {
724 err = library_ + ": the engine jet scale is not finite";
725 return RGPOT_ENGINE_ERR_INVALID;
726 }
727 if (raw.scale < 0.0) {
728 err = library_ + ": the engine jet scale is negative";
729 return RGPOT_ENGINE_ERR_INVALID;
730 }
731 report->tracked = raw.tracked;
732 report->operations = raw.operations;
733 report->scale = raw.scale;
734 } else if (report != nullptr) {
735 report->tracked = 0;
736 report->operations = 0;
737 report->scale = 0;
738 }
739 return RGPOT_ENGINE_OK;
740}

◆ threadCount()

int pot::EnginePotential::threadCount ( ) const
inlinenodiscardnoexcept

OpenMP team requested explicitly by the host for every engine call.

Definition at line 238 of file EnginePotential.h.

239 {
240 return oracle_threads_;
241 }

◆ unloadSafe()

bool pot::EnginePotential::unloadSafe ( ) const
nodiscard

True only when the stamp minor is at least 7 and rgpot_engine_unload_policy returns RGPOT_ENGINE_UNLOAD_SAFE.

Definition at line 777 of file EnginePotential.cpp.

778{
779 // Minor 7 is the first stamp that defines rgpot_engine_unload_policy.
780 constexpr unsigned short kUnloadPolicyMinor = 7;
781 if (stamp_.minor < kUnloadPolicyMinor || unload_policy_ == nullptr) {
782 return false;
783 }
784 return reinterpret_cast<unload_fn>(unload_policy_)() ==
785 RGPOT_ENGINE_UNLOAD_SAFE;
786}

◆ wrap()

PotentialWrapper pot::EnginePotential::wrap ( std::shared_ptr< EnginePotential > engine)
static

Adapt a shared engine handle to the host's potential interface. Positive statuses throw EngineError; negative statuses mark the handle dead and throw as well.

Definition at line 788 of file EnginePotential.cpp.

789{
790 if (!engine) {
791 throw std::invalid_argument(
792 "EnginePotential::wrap: engine must not be null");
793 }
795 [engine](long n, const double* positions, const int* atomic_nrs,
796 double* forces, double* energy, double* energy_noise_rms,
797 double* force_noise_rms, const double* box) {
798 if (n <= 0) {
799 throw std::invalid_argument(
800 "EnginePotential::wrap: n_atoms must be positive");
801 }
802 // The engine writes forces and energy as it evaluates. Hold
803 // those in scratch until the variance validates. A null force
804 // pointer is not a caller buffer; never pass one through.
805 const std::size_t n_coord =
806 forces != nullptr ? static_cast<std::size_t>(n) * 3 : 0;
807 std::vector<double> scratch_forces(n_coord);
808 double scratch_energy = 0.0;
809 double variance = 0.0;
810 const int status = engine->force(
811 n, positions, atomic_nrs, box,
812 n_coord > 0 ? scratch_forces.data() : nullptr,
813 energy != nullptr ? &scratch_energy : nullptr, &variance);
814 if (status != 0) {
815 throw EngineError(engine->library(), status,
816 describeStatus(engine->library(), status));
817 }
818 // The engine reports one variance scalar. An exact oracle writes
819 // 0. A surrogate writes its posterior energy variance, and that
820 // is the host's force-noise channel. Publish the caller buffers
821 // only after that variance validates.
822 const double force_noise =
823 validatedForceVariance(engine->library(), variance);
824 if (n_coord > 0)
825 std::copy_n(scratch_forces.data(), n_coord, forces);
826 if (energy != nullptr) *energy = scratch_energy;
827 if (energy_noise_rms) *energy_noise_rms = 0.0;
828 if (force_noise_rms) *force_noise_rms = force_noise;
829 });
830 if (engine->hasBatch()) {
831 wrapper.setForceBatch(
832 [engine](long n, std::size_t systems, const double* positions,
833 const int* atomic_nrs, double* forces, double* energies,
834 double* force_noise_rms, const double* box) {
835 if (n <= 0) {
836 throw std::invalid_argument(
837 "EnginePotential::wrap: n_atoms must be positive");
838 }
839 // The host's batch surface shares one box; the engine takes one
840 // per system. A null box is no cell: the single call forwards
841 // it, and the engine ABI copies a box only when it is present.
842 std::vector<double> boxes;
843 const double* engine_boxes = nullptr;
844 if (box != nullptr) {
845 boxes.resize(9 * systems);
846 for (std::size_t s = 0; s < systems; ++s)
847 std::copy(box, box + 9, boxes.begin() + 9 * s);
848 engine_boxes = boxes.data();
849 }
850 // Publish nothing until every system validates. The engine
851 // writes forces and energies as it goes, and a later invalid
852 // variance must leave the caller buffers as they were. A null
853 // caller pointer is not a caller buffer: scratch exists only
854 // for a pointer the caller passed, and nullptr is forwarded,
855 // as the single call does.
856 const std::size_t dof = static_cast<std::size_t>(n) * 3;
857 std::vector<double> scratch_forces;
858 std::vector<double> scratch_energies;
859 if (forces != nullptr) scratch_forces.resize(systems * dof);
860 if (energies != nullptr) scratch_energies.resize(systems);
861 std::vector<double> variances(systems);
862 const int status = engine->forceBatch(
863 static_cast<long>(systems), n, positions, atomic_nrs,
864 engine_boxes,
865 forces != nullptr ? scratch_forces.data() : nullptr,
866 energies != nullptr ? scratch_energies.data() : nullptr,
867 variances.data());
868 if (status != 0) {
869 throw EngineError(
870 engine->library(), status,
871 describeStatus(engine->library(), status));
872 }
873 std::vector<double> scratch_noise(systems);
874 for (std::size_t s = 0; s < systems; ++s) {
875 scratch_noise[s] =
876 validatedForceVariance(engine->library(), variances[s]);
877 }
878 if (forces != nullptr) {
879 std::copy_n(scratch_forces.data(), scratch_forces.size(),
880 forces);
881 }
882 if (energies != nullptr) {
883 std::copy_n(scratch_energies.data(), systems, energies);
884 }
885 if (force_noise_rms != nullptr) {
886 std::copy_n(scratch_noise.data(), systems, force_noise_rms);
887 }
888 });
889 }
890 return wrapper;
891}
static PotentialWrapper from_force_with_uncertainty(ForceWithUncertaintyFn fn)
double variance(const Weights &w, const Matrix &covariance)

The documentation for this class was generated from the following files: