23#if defined(USE_CAPNP) && __has_include("rgpot/rpc/Potentials.capnp.h")
24#define GPR_ENGINE_REGISTRY_SCHEMA 1
25#include <capnp/message.h>
26#include <capnp/serialize.h>
28#include "rgpot/rpc/Potentials.capnp.h"
35enum class Arm { Uma, Metatomic, Cpmd, Cp2k, Lammps,
Builtin,
None };
49constexpr Entry kTable[] = {
50 {
"uma", Arm::Uma,
"libuma_engine.so",
"",
true,
"UmaPot"},
51 {
"omol", Arm::Uma,
"libuma_engine.so",
"",
true,
"UmaPot"},
54 {
"cpmd", Arm::Cpmd,
"libcpmd_engine.so",
"",
true,
"CPMDPot"},
58 {
"cp2k", Arm::Cp2k,
"libcp2k_engine.so",
"",
true,
"CP2KPot"},
61 {
"lammps", Arm::Lammps,
"liblammps_engine.so",
"",
true,
""},
62 {
"metatomic", Arm::Metatomic,
"libmetatomic_engine.so",
"",
false,
64 {
"xtb", Arm::Builtin,
"libxtb_engine.so",
"xtb",
false,
"XTBPot"},
65 {
"gfn2", Arm::Builtin,
"libxtb_engine.so",
"xtb",
false,
"XTBPot"},
66 {
"gfnff", Arm::Builtin,
"libxtb_engine.so",
"gfnff",
false,
"XTBPot"},
67 {
"lj", Arm::Builtin,
"",
"lj",
false,
""},
68 {
"morse", Arm::Builtin,
"",
"morse",
false,
""},
69 {
"cuh2", Arm::Builtin,
"",
"cuh2",
false,
""},
70 {
"mopac", Arm::Builtin,
"",
"mopac",
false,
""},
73const Entry* find(
const std::string& name)
75 for (
const auto& entry: kTable) {
76 if (name == entry.name)
return &entry;
81std::string executableDirectory()
84 const auto path = std::filesystem::read_symlink(
"/proc/self/exe", ec);
85 return ec ? std::string() : path.parent_path().string();
88std::string joinPath(
const std::string& dir,
const std::string& name)
90 if (dir.empty())
return name;
91 return dir.back() ==
'/' ? dir + name : dir +
"/" + name;
97void locateLibrary(
const EngineRequest& request,
const std::string& name,
100 if (!request.engine_dir.empty()) {
102 binding.library = joinPath(request.engine_dir, name);
108 binding.library = name;
109 for (
const std::string& dir: binding.searched) {
110 const std::string candidate = joinPath(dir, name);
112 if (std::filesystem::exists(candidate, ec)) {
113 binding.library = candidate;
119bool readParamsFile(
const std::string& path, std::vector<unsigned char>&
out,
122 std::ifstream in(path, std::ios::binary);
124 err =
"cannot read engine parameters " + path;
127 out.assign(std::istreambuf_iterator<char>(in), {});
129 err =
"cannot read engine parameters " + path;
135bool resolvePlugin(
const EngineRequest& request,
const char* table_library,
139 binding.model_path = request.model_path;
140 const std::string label =
141 request.plugin_name.empty() ? request.potential : request.plugin_name;
142 if (!request.library.empty()) {
143 if (request.library.find(
'/') != std::string::npos)
144 binding.library = request.library;
146 locateLibrary(request, request.library, binding);
147 }
else if (table_library !=
nullptr && table_library[0] !=
'\0') {
148 locateLibrary(request, table_library, binding);
150 err =
"engine parameters for '" + label +
151 "' need a library: pass --potential-library or set "
152 "[oracle.plugin] library_path";
155 if (!request.params_payload.empty()) {
156 binding.config = request.params_payload;
157 }
else if (!readParamsFile(request.params_path, binding.config, err)) {
160 binding.params_arm =
"plugin:" + label;
164#ifdef GPR_ENGINE_REGISTRY_SCHEMA
165std::vector<unsigned char> serialize(capnp::MessageBuilder& message)
167 const kj::Array<capnp::word> words = capnp::messageToFlatArray(message);
168 const kj::ArrayPtr<const kj::byte> bytes = words.asBytes();
169 return std::vector<unsigned char>(bytes.begin(), bytes.end());
172std::string trim(
const std::string& text)
174 const auto first = text.find_first_not_of(
" \t\r");
175 if (first == std::string::npos)
return {};
176 const auto last = text.find_last_not_of(
" \t\r");
177 return text.substr(first, last - first + 1);
180bool parseBool(
const std::string& text,
bool&
out)
182 if (text ==
"on" || text ==
"true" || text ==
"yes" || text ==
"1") {
186 if (text ==
"off" || text ==
"false" || text ==
"no" || text ==
"0") {
196bool readLammpsParamsFile(::LammpsParams::Builder params,
197 const std::string& path, std::string& err)
199 std::ifstream in(path);
201 err =
"cannot read --lammps-params " + path;
204 std::string units =
"metal";
205 std::string atom_style =
"atomic";
206 std::string pair_style;
207 std::string boundary =
"f f f";
209 std::vector<std::string> coeffs;
210 std::vector<int> types;
211 std::vector<double> masses;
214 while (std::getline(in, line)) {
216 const std::string text = trim(line);
217 if (text.empty() || text[0] ==
'#')
continue;
218 const auto gap = text.find_first_of(
" \t");
219 const std::string key =
220 gap == std::string::npos ? text : text.substr(0, gap);
221 const std::string value =
222 gap == std::string::npos ? std::string() : trim(text.substr(gap));
223 auto fail = [&](
const std::string& why) {
224 err = path +
":" + std::to_string(lineno) +
": " + why;
227 if (key ==
"units") {
228 if (value.empty())
return fail(
"units needs a style");
230 }
else if (key ==
"atom_style") {
231 if (value.empty())
return fail(
"atom_style needs a style");
233 }
else if (key ==
"pair_style") {
234 if (value.empty())
return fail(
"pair_style needs arguments");
236 }
else if (key ==
"pair_coeff") {
237 if (value.empty())
return fail(
"pair_coeff needs arguments");
238 coeffs.push_back(value);
239 }
else if (key ==
"type") {
241 std::size_t used = 0;
242 const int z = std::stoi(value, &used);
243 if (used != value.size() ||
z <= 0)
244 return fail(
"type takes one positive atomic number");
246 }
catch (
const std::exception&) {
247 return fail(
"type takes one positive atomic number");
249 }
else if (key ==
"mass") {
251 std::size_t used = 0;
252 const double mass = std::stod(value, &used);
253 if (used != value.size() || !(mass > 0.0))
254 return fail(
"mass takes one positive mass in amu");
255 masses.push_back(mass);
256 }
catch (
const std::exception&) {
257 return fail(
"mass takes one positive mass in amu");
259 }
else if (key ==
"boundary") {
260 if (value.empty())
return fail(
"boundary needs three tokens");
262 }
else if (key ==
"newton_pair") {
263 if (!parseBool(value, newton))
264 return fail(
"newton_pair takes on or off");
265 }
else if (key ==
"extra" || key ==
"suffix") {
266 return fail(key +
" is not applied by lammpc");
268 return fail(
"unknown key '" + key +
"'");
271 if (pair_style.empty()) {
272 err = path +
": pair_style is required";
276 err = path +
": at least one type line is required";
279 if (coeffs.empty()) {
280 err = path +
": at least one pair_coeff line is required";
283 if (!masses.empty() && masses.size() != types.size()) {
284 err = path +
": mass lines must match type lines, or be omitted";
287 params.setUnitsStyle(units);
288 params.setAtomStyle(atom_style);
289 params.setPairStyle(pair_style);
290 auto coeff_list = params.initPairCoeffs(coeffs.size());
291 for (std::size_t i = 0; i < coeffs.size(); ++i)
292 coeff_list.set(i, coeffs[i]);
293 auto type_list = params.initTypeToAtomicNumber(types.size());
294 for (std::size_t i = 0; i < types.size(); ++i)
295 type_list.set(i, types[i]);
296 if (!masses.empty()) {
297 auto mass_list = params.initMasses(masses.size());
298 for (std::size_t i = 0; i < masses.size(); ++i)
299 mass_list.set(i, masses[i]);
301 params.setNewtonPair(newton);
302 params.setBoundary(boundary);
311 const Entry* entry = find(potential);
312 return entry !=
nullptr && entry->generic;
321 const std::string& potential,
bool plugin)
323 if (plugin && requested !=
"direct")
324 return {
true, requested ==
"engine"
325 ?
"--oracle-path engine"
326 :
"default: the engine parameters name a plugin"};
331 const std::string& potential)
333 if (requested ==
"direct")
return {
false,
"--oracle-path direct"};
334 if (requested ==
"engine")
return {
true,
"--oracle-path engine"};
337 return {
true,
"default: " + potential +
" has a generic engine"};
339 return {
false,
"default: " + potential +
" has no generic engine"};
342 return {
false,
"default: this binary has no Cap'n Proto"};
347 const std::string& potential)
350 {{
"path", choice.
engine ?
"engine" :
"direct"},
351 {
"potential", potential},
352 {
"reason",
"\"" + choice.
reason +
"\""}});
358 if (run ==
nullptr)
return false;
359 run->
logParam(
"oracle.path", choice.
engine ?
"engine" :
"direct");
365 const std::string& potential)
367 std::vector<std::string> dirs;
368 auto add = [&dirs](
const std::string& dir) {
369 if (dir.empty())
return;
370 if (std::find(dirs.begin(), dirs.end(), dir) == dirs.end())
374 if (
const char* env = std::getenv(
"RGPOT_ENGINE_PATH")) {
375 std::string list = env;
376 std::size_t start = 0;
377 while (start <= list.size()) {
378 const std::size_t colon = list.find(
':', start);
379 add(list.substr(start, colon == std::string::npos
382 if (colon == std::string::npos)
break;
387 if (exe.empty()) exe = executableDirectory();
389 const std::filesystem::path base(exe);
390 add((base /
".." /
"lib").lexically_normal().
string());
391 add((base /
".." /
"lib64").lexically_normal().
string());
392 add(base.lexically_normal().string());
393 const Entry* entry = find(potential);
394 if (entry !=
nullptr && entry->subdir[0] !=
'\0') {
395 add((base /
"subprojects" /
"rgpot" /
"CppCore" /
"rgpot" /
406 return find(potential) !=
nullptr;
412 const Entry* entry = find(request.
potential);
414 return resolvePlugin(request, entry ? entry->library :
nullptr, binding,
416 if (entry ==
nullptr) {
418 "no engine is registered for potential '" + request.
potential +
"'";
423 if (!request.
library.empty()) {
425 }
else if (entry->library[0] !=
'\0') {
426 locateLibrary(request, entry->library, binding);
428 err =
"potential '" + request.
potential +
429 "' has no shipped engine library; pass --potential-library";
432#ifdef GPR_ENGINE_REGISTRY_SCHEMA
437 if (!binding.
config.empty()) {
438 switch (entry->arm) {
456 "The selected engine does not accept native "
457 "constructor settings; use --oracle-path direct";
460 if (entry->arm == Arm::Uma)
464 }
catch (
const std::exception& error) {
469 capnp::MallocMessageBuilder message;
470 switch (entry->arm) {
473 err =
"--model is required for '" + request.
potential +
"'";
478 }
catch (
const std::exception& error) {
482 auto params = message.initRoot<::UmaParams>();
485 params.setDevice(request.
device);
486 params.setCharge(request.
charge);
487 params.setSpin(request.
spin);
491 case Arm::Metatomic: {
493 err =
"--model is required for '" + request.
potential +
"'";
496 auto params = message.initRoot<::MetatomicParams>();
498 params.setDevice(request.
device);
503 auto params = message.initRoot<::CPMDParams>();
504 params.setFunctional(
"BLYP");
505 params.setCutOffRy(70.0);
506 auto sections = params.initInputSections(3);
507 auto system = sections[0].initSystem();
508 system.setSymmetry(1);
509 system.setAngstrom(
true);
510 system.setCutOffRy(70.0);
511 system.setCellAbsolute(
true);
512 system.setCellDegree(
true);
515 auto cell = system.initCell(6);
522 auto atoms = sections[1].initAtoms();
523 auto pp = atoms.initPseudopotentials(2);
524 pp[0].setElement(
"Si");
525 pp[0].setPath(
"Si_MT_BLYP.psp");
528 pp[0].setKleinmanBylander(
true);
529 pp[1].setElement(
"N");
530 pp[1].setPath(
"N_MT_BLYP.psp");
533 pp[1].setKleinmanBylander(
true);
539 auto cpmd = sections[2].initCpmd();
540 cpmd.setOptimizeWavefunction(
true);
545 params.setEnginePath(
"libcpmdc.so");
550#ifdef GPR_SCHEMA_HAS_CP2K_CONFIG
557 auto params = message.initRoot<::CP2KParams>();
558 params.setFunctional(
"PBE");
559 params.setBasisSet(
"DZVP-MOLOPT-SR-GTH");
560 params.setPseudopotential(
"GTH-PBE");
561 params.setBasisSetFile(
"BASIS_MOLOPT");
562 params.setPotentialFile(
"GTH_POTENTIALS");
563 params.setCutoffRy(650.0);
564 params.setRelCutoffRy(70.0);
566 params.setPeriodic(
"XYZ");
573 params.setEnginePath(
"libcp2kc_rgpot.so");
577 err =
"this rgpot schema has no CP2KParams arm";
583 err =
"--lammps-params is required for '" + request.
potential +
587 auto params = message.initRoot<::LammpsParams>();
594 auto params = message.initRoot<::BuiltinParams>();
595 params.setName(entry->builtin);
601 err =
"potential '" + request.
potential +
"' has no params arm";
604 binding.
config = serialize(message);
608 "the engine registry needs Cap'n Proto and the rgpot RPC arm "
609 "(-Duse_capnp=true with an rgpot potential that enables it)";
620 EngineBinding& target = binding !=
nullptr ? *binding : local;
622 const Entry* entry = find(request.
potential);
623 const bool uses_torch = entry !=
nullptr && (entry->arm == Arm::Uma ||
624 entry->arm == Arm::Metatomic);
625 const bool torch_cuda = uses_torch && request.
device.rfind(
"cuda", 0) == 0;
627 torch_cuda, oracle_threads);
628 if (!engine && !target.
searched.empty() &&
629 target.
library.find(
'/') == std::string::npos) {
632 for (
const std::string& dir: target.
searched)
633 err +=
" " + dir +
",";
634 err +=
" then the loader's search path (rpath, LD_LIBRARY_PATH)";
650 const std::string& model_sha256)
664 if (model_path.empty()) {
665 std::promise<std::string> empty;
666 empty.set_value(std::string());
667 return empty.get_future().share();
669 return std::async(std::launch::async,
gpr::sha256File, model_path).share();
674 std::vector<gpr::startup::Field> fields = {
679 fields.emplace_back(
"model", report.
model_path);
680 fields.emplace_back(
"sha256", report.
model_sha256.empty()
690 if (run ==
nullptr)
return false;
Host check for the instruction set an AOTInductor package needs.
void logParam(std::string_view key, std::string_view value)
void flush()
Send buffered metrics, params and tags to the tracking server.
const std::string & resolvedPath() const noexcept
Absolute path of the loaded object, from the dynamic loader.
int abiVersion() const noexcept
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)
const std::string & library() const noexcept
eon_relax_band_t eon_relax_surface_fn void eon_relax_outcome_t * out
std::string line(const std::string &topic, const std::vector< Field > &fields)
MlflowRun * activeRun() noexcept
std::string sha256File(const std::string &path)
Digest of a file's contents; empty when the file cannot be read.
Potential wrappers and the batched oracle interface.
bool resolveEngine(const EngineRequest &request, EngineBinding &binding, std::string &err)
bool engineRegistryKnows(const std::string &potential)
True when the registry maps potential to an engine params arm.
bool recordOraclePath(const OraclePathChoice &choice)
Record the choice on the active tracking run as oracle.path.
std::unique_ptr< EnginePotential > openEngine(const EngineRequest &request, std::string &err, EngineBinding *binding, int oracle_threads)
resolveEngine followed by EnginePotential::open.
bool engineIsGeneric(const std::string &potential)
bool engineRequestIsPlugin(const EngineRequest &request)
std::string formatOraclePath(const OraclePathChoice &choice, const std::string &potential)
std::vector< unsigned char > potentialConfigArm(const std::vector< unsigned char > &config, const std::string &potential)
OraclePathChoice selectOraclePath(const std::string &requested, const std::string &potential, bool plugin)
bool recordEngineProvenance(const EngineReport &report)
void requireAotiPackageRunsOnHost(const std::string &path)
std::string formatEngineReport(const EngineReport &report)
std::shared_future< std::string > startModelDigest(const std::string &model_path)
std::vector< std::string > engineSearchDirectories(const EngineRequest &request, const std::string &potential)
EngineReport reportEngine(const EnginePotential &engine, const EngineBinding &binding)
A name resolved to an engine library and the capnp params message it takes.
std::string params_arm
capnp root struct, e.g. UmaParams
std::string library
path or soname for dlopen
std::vector< std::string > searched
std::vector< unsigned char > config
flat-array message
What a run needs to state about the engine that answered it.
std::string library
as requested of the loader
std::string resolved_path
file the loader mapped
std::string model_path
empty for engines that load no model
std::string params_arm
capnp root struct the engine read
std::string model_sha256
digest of the model file; empty if unread
int abi_version
rgpot_engine_abi_version()
What a driver knows when it asks for a potential by name.
double cpmd_scf_convergence
–cpmd-scf-convergence: CPMD's CONVERGENCE ORBITALS criterion.
std::string model_path
–model
double cp2k_eps_scf
–cp2k-eps-scf: CP2K's &SCF EPS_SCF for the default cp2k deck.
std::string task_name
–task-name (UMA task head)
std::string potential
–potential: uma, omol, metatomic, ...
std::string lammps_params_path
–lammps-params: pair style, coefficients and type map for lammps.
std::string device
–device
std::string executable_dir
std::vector< unsigned char > potential_config
Optional canonical rgpot PotentialConfig shared with the direct path.
int spin
–uma-spin (multiplicity)
int cp2k_outer_max_scf
&OUTER_SCF MAX_SCF of the default cp2k deck; 0 drops the outer loop.
std::string library
–potential-library: overrides the table
std::vector< unsigned char > params_payload
Which route a run takes to its potential, and why.