Loading...
Searching...
No Matches
EnginePotential.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#include "EnginePotential.h"
6
7#include <dlfcn.h>
8#include <link.h>
9#include <unistd.h>
10
11#include <algorithm>
12#include <cmath>
13#include <cstddef>
14#include <cstdint>
15#include <cstdlib>
16#include <stdexcept>
17#include <utility>
18
19#if defined(_OPENMP)
20#include <omp.h>
21#endif
22
23#include "rgpot_engine_c_abi.h"
24
25namespace pot {
26
27namespace {
28
29struct ScopedOracleThreads {
30#if defined(_OPENMP)
31 int saved_omp = 1;
32 bool changed = false;
33 explicit ScopedOracleThreads(int target) : saved_omp(omp_get_max_threads())
34 {
35 if (saved_omp != target) {
36 omp_set_num_threads(target);
37 changed = true;
38 }
39 }
40 ~ScopedOracleThreads()
41 {
42 if (changed) omp_set_num_threads(saved_omp);
43 }
44 ScopedOracleThreads(const ScopedOracleThreads&) = delete;
45 ScopedOracleThreads& operator=(const ScopedOracleThreads&) = delete;
46#else
47 explicit ScopedOracleThreads(int) { }
48#endif
49};
50
51using create_fn = RgpotEnginePot* (*)(const void*, std::size_t, char*,
52 std::size_t);
53using destroy_fn = void (*)(RgpotEnginePot*);
54using force_fn = int (*)(RgpotEnginePot*, long, const double*, const int*,
55 double*, double*, double*, const double*,
56 rgpot_engine_coord_transform, void*);
57using batch_fn = int (*)(RgpotEnginePot*, long, long, const double*, const int*,
58 double*, double*, double*, const double*,
59 rgpot_engine_coord_transform, void*);
60using set_callbacks_fn = int (*)(RgpotEnginePot*, const RgpotEngineCallbacks*);
61using hessian_checked_fn = int (*)(RgpotEnginePot*, long, const double*,
62 std::size_t, const int*, double*,
63 std::size_t, const double*);
64using hessian_action_checked_fn = int (*)(RgpotEnginePot*, long, const double*,
65 std::size_t, const int*,
66 const double*, std::size_t, double*,
67 std::size_t, const double*,
68 unsigned long long*, double*);
69using prediction_supported_checked_fn = int (*)(RgpotEnginePot*, long,
70 const double*, std::size_t,
71 const int*, const double*,
72 int*);
73using gpr_stats_fn = int (*)(const RgpotEnginePot*, RgpotEngineGprStats*);
74using last_error_fn = std::size_t (*)(const RgpotEnginePot*, char*,
75 std::size_t);
76using state_fn = unsigned long long (*)(const RgpotEnginePot*);
77using hint_fn = int (*)(RgpotEnginePot*, const void*, std::size_t, char*,
78 std::size_t);
79using set_num_threads_fn = int (*)(RgpotEnginePot*, int, int);
80using caps_fn = int (*)(const RgpotEnginePot*, RgpotEngineCaps*);
81using hvp_fn = int (*)(RgpotEnginePot*, long, const double*, const int*,
82 const double*, double*, const double*);
83using taylor_fn = int (*)(RgpotEnginePot*, long, long, const double*,
84 const int*, const double*, long, double*,
85 RgpotEngineDerivativeReport*, const double*);
86using set_cache_fn = int (*)(RgpotEnginePot*, const char*);
87using cache_counts_fn = int (*)(RgpotEnginePot*, std::uint64_t*,
88 std::uint64_t*);
89using unload_fn = int (*)();
90using stamp_fn = RgpotEngineAbiStamp (*)();
91using available_fn = int (*)();
92
93std::string formatStamp(unsigned short major, unsigned short minor,
94 unsigned short layout)
95{
96 return std::to_string(major) + "." + std::to_string(minor) + " (layout " +
97 std::to_string(layout) + ")";
98}
99
100std::string formatStamp(const RgpotEngineAbiStamp& stamp)
101{
102 return formatStamp(stamp.abi_major, stamp.abi_minor, stamp.layout_revision);
103}
104
105bool stampServesHost(const RgpotEngineAbiStamp& stamp)
106{
107 return stamp.abi_major == RGPOT_ENGINE_ABI_VERSION &&
108 stamp.layout_revision == RGPOT_ENGINE_ABI_LAYOUT_REVISION &&
109 stamp.abi_minor <= RGPOT_ENGINE_ABI_MINOR;
110}
111
112int firstNonFinite(const double* values, std::size_t count)
113{
114 if (values == nullptr) return -1;
115 for (std::size_t i = 0; i < count; ++i) {
116 if (!std::isfinite(values[i])) return static_cast<int>(i);
117 }
118 return -1;
119}
120
121bool rangesOverlap(const void* left, std::size_t left_bytes, const void* right,
122 std::size_t right_bytes)
123{
124 if (left == nullptr || right == nullptr || left_bytes == 0 ||
125 right_bytes == 0) {
126 return false;
127 }
128 const auto* a = static_cast<const unsigned char*>(left);
129 const auto* b = static_cast<const unsigned char*>(right);
130 return a < b + right_bytes && b < a + left_bytes;
131}
132
133bool rangesOverlap(const void* left, const void* right, std::size_t bytes)
134{
135 return rangesOverlap(left, bytes, right, bytes);
136}
137
140std::string torchLibraryDirectory(void* handle)
141{
142 // An explicit handle limits symbol lookup to the engine and its
143 // dependencies. The AOTI C shim identifies the defining Torch library
144 // without traversing other engines loaded into the same namespace.
145 const void* marker = dlsym(handle, "aoti_torch_device_type_cpu");
146 Dl_info info{};
147 if (marker == nullptr || dladdr(marker, &info) == 0 ||
148 info.dli_fname == nullptr) {
149 return {};
150 }
151 const std::string name(info.dli_fname);
152 const std::string tail = "/libtorch_cpu.so";
153 if (name.size() > tail.size() &&
154 name.compare(name.size() - tail.size(), tail.size(), tail) == 0) {
155 return name.substr(0, name.size() - tail.size() + 1);
156 }
157 return {};
158}
159
160std::string describeStatus(const std::string& library, int status)
161{
162 if (status == RGPOT_ENGINE_ERR_LOCK) {
163 return library +
164 ": acquiring an engine or handle lock failed (status " +
165 std::to_string(status) + ")";
166 }
167 return library + ": engine evaluation " +
168 (status < 0 ? "failed fatally" : "failed at this input") +
169 " (status " + std::to_string(status) + ")";
170}
171
172double validatedForceVariance(const std::string& library, double variance)
173{
174 if (!std::isfinite(variance) || variance < 0.0) {
175 throw std::domain_error(library +
176 ": engine reported an invalid force variance");
177 }
178 return variance;
179}
180
181} // namespace
182
184 const std::string& what)
185 : std::runtime_error(what), library_(std::move(library)), status_(status)
186{
187}
188
189std::unique_ptr<EnginePotential> EnginePotential::open(
190 const std::string& library, const std::vector<unsigned char>& config,
191 std::string& err, bool torch_cuda, int oracle_threads)
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}
364
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}
381
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}
394
395int EnginePotential::force(long n_atoms, const double* positions,
396 const int* atomic_nrs, const double* box,
397 double* forces, double* energy, double* variance)
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}
407
408int EnginePotential::forceBatch(long n_systems, long n_atoms,
409 const double* positions, const int* atomic_nrs,
410 const double* boxes, double* forces,
411 double* energies, double* variances)
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}
422
423int EnginePotential::setCallbacks(const RgpotEngineCallbacks& callbacks)
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}
429
430int EnginePotential::hessianChecked(long n_atoms, const double* positions,
431 std::size_t positions_len,
432 const int* atomic_nrs, double* hessian_out,
433 std::size_t hessian_len, const double* box)
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}
443
445 long n_atoms, const double* positions, std::size_t positions_len,
446 const int* atomic_nrs, const double* direction, std::size_t direction_len,
447 double* hv_out, std::size_t hv_len, const double* box,
448 unsigned long long* ops_out, double* scale_out)
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}
460
462 long n_atoms, const double* positions, std::size_t positions_len,
463 const int* atomic_nrs, const double* box, int* supported_out)
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}
475
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}
483
484unsigned long long EnginePotential::modelState() const
485{
486 if (model_state_ == nullptr) return 0;
487 return reinterpret_cast<state_fn>(model_state_)(
488 static_cast<const RgpotEnginePot*>(pot_));
489}
490
491int EnginePotential::hint(const std::vector<unsigned char>& message,
492 std::string& err)
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}
506
507int EnginePotential::noteCall(int status, const char* operation,
508 std::string& err)
509{
510 if (status < 0) dead_ = true;
511 if (status == 0) return 0;
512 err = library_ + ": " + operation + " failed";
513 const std::string detail = lastError();
514 if (!detail.empty())
515 err += ": " + detail;
516 else
517 err += " (status " + std::to_string(status) + ")";
518 return status;
519}
520
521int EnginePotential::caps(EngineCaps& out, std::string& err)
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}
565
566int EnginePotential::hvp(long n_atoms, const double* positions,
567 const int* atomic_nrs, const double* direction,
568 double* hv_out, const double* box, std::string& err)
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}
621
622int EnginePotential::taylorJet(long n_systems, long n_atoms,
623 const double* positions, const int* atomic_nrs,
624 const double* directions, long order,
625 double* jet_out, EngineDerivativeReport* report,
626 const double* boxes, std::string& err)
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}
741
742int EnginePotential::setCache(const char* path, std::string& err)
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}
753
754int EnginePotential::cacheCounts(std::uint64_t& computed, std::uint64_t& served,
755 std::string& err)
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}
766
767std::string EnginePotential::lastError() const
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}
776
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}
787
788PotentialWrapper EnginePotential::wrap(std::shared_ptr<EnginePotential> engine)
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}
892
893} // namespace pot
EngineError(std::string library, int status, const std::string &what)
const std::string & library() const noexcept
int status() const noexcept
std::string lastError() const
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.
int gprStats(RgpotEngineGprStats &stats_out) const
Read learning-engine operation counters.
void setThreadCount(int threads)
int setCache(const char *path, std::string &err)
int force(long n_atoms, const double *positions, const int *atomic_nrs, const double *box, double *forces, double *energy, double *variance)
static PotentialWrapper wrap(std::shared_ptr< EnginePotential > engine)
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)
int caps(EngineCaps &out, std::string &err)
int cacheCounts(std::uint64_t &computed, std::uint64_t &served, std::string &err)
int setCallbacks(const RgpotEngineCallbacks &callbacks)
Register host callbacks for a learning engine.
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)
const std::string & library() const noexcept
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)
EnginePotential(const EnginePotential &)=delete
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.
int hint(const std::vector< unsigned char > &message, std::string &err)
unsigned long long modelState() const
Monotone model-state counter; zero for an engine without one.
int forceBatch(long n_systems, long n_atoms, const double *positions, const int *atomic_nrs, const double *boxes, double *forces, double *energies, double *variances)
Type-erased wrapper around any potential that provides a force() interface.
static PotentialWrapper from_force_with_uncertainty(ForceWithUncertaintyFn fn)
eon_relax_band_t eon_relax_surface_fn void eon_relax_outcome_t * out
int status
size_t char * errbuf
double variance(const Weights &w, const Matrix &covariance)
Potential wrappers and the batched oracle interface.
STL namespace.