Loading...
Searching...
No Matches
MetatomicPotential Class Reference

A potential class that uses a metatomic model for energy and force calculations. More...

#include <MetatomicPotential.h>

Inheritance diagram for MetatomicPotential:

Classes

struct  CloneTag

Public Member Functions

EON_MTA_POT_API MetatomicPotential (const eonc::Parameters &params)
 Constructor for the MetatomicPotential.
 MetatomicPotential (const eonc::Parameters::metatomic_options_t &opts, long random_seed=0)
 ~MetatomicPotential () override=default
 Destructor.
std::shared_ptr< eonc::Potential > clonePotential () const override
 Independent instance that does not reload from disk.
void force (long nAtoms, const double *positions, const int *atomicNrs, double *forces, double *energy, double *variance, const double *box) override
 Calculates the energy and forces for a given atomic configuration.
bool isThreadSafe () const noexcept override
 Single shared instance, serialized via mutex.
bool needsPerImageInstance () const noexcept override
 Whether NEB should create separate Potential instances per image for true parallel force evaluation.
bool supportsBatchEvaluation () const noexcept override
 Batched evaluation via single shared instance.
void forceBatch (long nSystems, long nAtoms, const double *const *positions, const int *const *atomicNrs, double *const *forces, double *energies, double *variances, const double *const *boxes) override
Public Member Functions inherited from eonc::Potential
void recordForceCall () noexcept
 Charge one evaluated geometry to this potential and its owning registry.
IPotRegistry & registry () const noexcept
 The registry this potential charges its force calls to.
 Potential (PotType a_ptype)
 Production default: construction-scope registry, else PotRegistry::get().
 Potential (PotType a_ptype, IPotRegistry &registry)
 Test seam: injected registry, no process-default get() counters.
 Potential (PotType a_ptype, const Parameters &p)
 Potential (const Parameters &a_params)
virtual ~Potential ()
void force (std::span< const double > positions, std::span< const int > atomicNrs, std::span< double > forces, double *energy, double *variance, std::span< const double > box)
 C++ call site: size-checked view over the raw FFI force().
virtual void setFixedMask (long nAtoms, const double *isFixed)
 Optional frozen-atom mask (nAtoms*3, 1.0 = fixed).
std::tuple< double, AtomMatrix > get_ef (const AtomMatrix &pos, const VectorXi &atmnrs, const Matrix3d &box)
PotType getType () const
virtual unsigned long long surfaceEpoch () const noexcept
 Host-visible surface generation.
virtual double finiteCutoff () const noexcept
 Finite interaction range in position length units.
virtual bool isSurrogate () const noexcept
 Whether this is a surrogate (GP) potential.
virtual bool requiresIsolatedMoleculeLayout () const noexcept
 True for molecular QM / non-PBC backends (NWChem socket, ASE ORCA/NWChem, …).
virtual unsigned layoutFlags () const noexcept
virtual bool isSharedInstanceThreadSafe () const noexcept
 Conservative gate for sharing one Potential instance across threads.
virtual void bindBand (const std::vector< std::shared_ptr< Matter > > &)
 NEB calls this with the finished band before the first force evaluation, so a host surface can name each image.
virtual bool forwardsStoredCell () const noexcept
 A host that owns the cell reads the stored matrix.
virtual bool computesStress () const noexcept
 True when force() leaves a Cauchy stress that cauchyStress() can read until the next force() on this instance.
virtual Matrix3d cauchyStress () const
 Cauchy stress in eV/Angstrom^3.
virtual void forceBatchOwned (long nSystems, long nAtoms, const double *const *positions, const int *const *atomicNrs, double *const *forces, double *energies, double *variances, const double *const *boxes, const long *owners)
 Evaluate forces for N systems in a single call.
virtual double hessianRange () const noexcept
 Distance beyond which every Hessian block between two atoms is exactly zero, in position length units.

Private Member Functions

metatensor_torch::TensorBlock computeNeighbors (metatomic_torch::NeighborListOptions request, long nAtoms, const double *positions, const double *box, const bool periodic[3])
 Computes neighbor list using the vesin library.
 MetatomicPotential (const MetatomicPotential &src, CloneTag)
void forceBatchNative (long nSystems, long nAtoms, const double *const *positions, const int *const *atomicNrs, double *const *forces, double *energies, double *variances, const double *const *boxes)

Private Attributes

eonc::log::Scoped m_log
eonc::Parameters::metatomic_options_t m_metatomic_opts
metatensor_torch::Module model_
metatomic_torch::ModelCapabilities capabilities_
std::vector< metatomic_torch::NeighborListOptions > nl_requests_
metatomic_torch::ModelEvaluationOptions evaluations_options_
torch::ScalarType dtype_
c10::DeviceType device_type_
torch::Device device_
bool check_consistency_
std::string energy_key_
std::string energy_uncertainty_key_
std::string nc_forces_key_
bool non_conservative_ {false}
bool random_rotation_ {false}
long n_symmetry_rotations_ {0}
double uncertainty_threshold_ {-1.0}
std::mutex inference_mutex_

Additional Inherited Members

Public Types inherited from eonc::Potential
enum class  PotLayout : unsigned { InProcess = 1u << 0 , NeedsWorkingDirectory = 1u << 1 , Subprocess = 1u << 2 }
 How the pot is executed. Combine with bitwise or. More...
Public Attributes inherited from eonc::Potential
std::atomic< size_t > forceCallCounter
Protected Attributes inherited from eonc::Potential
PotType ptype

Detailed Description

A potential class that uses a metatomic model for energy and force calculations.

This class loads a pre-trained atomistic model (via metatomic/PyTorch) and uses it to compute the potential energy and corresponding forces on atoms. It uses the vesin library to compute neighbor lists required by the model.

Definition at line 64 of file MetatomicPotential.h.

Constructor & Destructor Documentation

◆ MetatomicPotential() [1/3]

MetatomicPotential::MetatomicPotential ( const eonc::Parameters & params)

Constructor for the MetatomicPotential.

Parameters
paramsA shared pointer to the simulation parameters object. This object should contain the settings needed for the metatomic model.

Definition at line 57 of file MetatomicPotential.cpp.

59 params.main_options().randomSeed) {}
EON_MTA_POT_API MetatomicPotential(const eonc::Parameters &params)
Constructor for the MetatomicPotential.
const metatomic_options_t & metatomic_options() const
const main_options_t & main_options() const

◆ MetatomicPotential() [2/3]

MetatomicPotential::MetatomicPotential ( const eonc::Parameters::metatomic_options_t & opts,
long random_seed = 0 )

Definition at line 61 of file MetatomicPotential.cpp.

63 : eonc::Potential(eonc::PotType::METATOMIC),
64 m_metatomic_opts{opts},
65 model_(torch::jit::Module()),
66 device_type_(c10::DeviceType::CPU),
67 device_(torch::Device(device_type_)) {
68
69 // Determinism knobs (see
70 // https://rgoswami.me/snippets/pytorch-deterministic-regression/): JIT
71 // profiling specializes graphs after the first few forwards, so a fresh model
72 // instance can differ at ULP level from a warm one — bad for parallel NEB.
73 // cuBLAS / index_add_ on CUDA are likewise nondeterministic unless forced.
74 // [Metatomic] deterministic=true (default) applies the safe defaults;
75 // deterministic_strict=true requires CUBLAS_WORKSPACE_CONFIG (e.g. :4096:8)
76 // and fails on nondeterministic ops instead of warning.
77 if (m_metatomic_opts.deterministic) {
78 torch::jit::getProfilingMode() = false;
79 const bool strict = m_metatomic_opts.deterministic_strict ||
80 (std::getenv("CUBLAS_WORKSPACE_CONFIG") != nullptr);
81 at::globalContext().setDeterministicAlgorithms(true,
82 /*warn_only=*/!strict);
83 at::globalContext().setBenchmarkCuDNN(false);
84 QUILL_LOG_INFO(m_log,
85 "[MetatomicPotential] Deterministic algorithms enabled "
86 "(strict={})",
87 strict);
88 } else {
89 QUILL_LOG_INFO(m_log,
90 "[MetatomicPotential] Deterministic algorithms disabled "
91 "(faster, may diverge across runs / NEB images)");
92 }
93
94 eonc::FPEHandler fpeh;
95 fpeh.eat_fpe();
96
97 QUILL_LOG_INFO(m_log, "[MetatomicPotential] Initializing...");
98
99 // 1. Load the model from the path specified in parameters
100 torch::optional<std::string> extensions_directory = torch::nullopt;
101 if (!m_metatomic_opts.extensions_directory.empty()) {
102 extensions_directory = m_metatomic_opts.extensions_directory;
103 }
104
105 try {
106 QUILL_LOG_INFO(m_log, "[MetatomicPotential] Loading model from '{}'",
107 m_metatomic_opts.model_path);
108 this->model_ = metatomic_torch::load_atomistic_model(
109 m_metatomic_opts.model_path, extensions_directory);
110 } catch (const std::exception &e) {
111 QUILL_LOG_ERROR(m_log, "[MetatomicPotential] Failed to load model: {}",
112 e.what());
113 throw;
114 }
115
116 // 2. Extract capabilities and neighbor list requests from the model
117 this->capabilities_ =
118 this->model_.run_method("capabilities")
119 .toCustomClass<metatomic_torch::ModelCapabilitiesHolder>();
120 auto requests_ivalue = this->model_.run_method("requested_neighbor_lists");
121 for (const auto &request_ivalue : requests_ivalue.toList()) {
122 auto request =
123 request_ivalue.get()
124 .toCustomClass<metatomic_torch::NeighborListOptionsHolder>();
125 this->nl_requests_.push_back(request);
126 }
127
128 // 3. Determine and set up the device (CPU/CUDA/MPS)
129 torch::optional<std::string> desired = torch::nullopt;
130 if (!m_metatomic_opts.device.empty()) {
131 desired = m_metatomic_opts.device;
132 }
133 device_type_ = metatomic_torch::pick_device(
134 this->capabilities_->supported_devices, desired);
135
136 device_ = torch::Device(device_type_);
137 QUILL_LOG_INFO(m_log, "[MetatomicPotential] Using device: {}", device_.str());
138
139 move_atomistic_model(this->model_, this->device_);
140
141 // 4. Set data type (float32/float64) based on model capabilities
142 if (this->capabilities_->dtype() == "float64") {
143 this->dtype_ = torch::kFloat64;
144 } else if (this->capabilities_->dtype() == "float32") {
145 this->dtype_ = torch::kFloat32;
146 } else {
147 throw std::runtime_error("Unsupported dtype: " +
148 this->capabilities_->dtype());
149 }
150 QUILL_LOG_INFO(m_log, "[MetatomicPotential] Using dtype: {}",
151 this->capabilities_->dtype().c_str());
152
153 // 5. Resolve energy / force output keys: explicit keys (#215) or variants
154 // (#296 for non_conservative_force)
155 auto outputs = this->capabilities_->outputs();
156
157 auto v_base = normalize_variant(m_metatomic_opts.variant.base);
158 auto v_energy = m_metatomic_opts.variant.energy.empty()
159 ? v_base
160 : normalize_variant(m_metatomic_opts.variant.energy);
161 auto v_energy_uq =
162 m_metatomic_opts.variant.energy_uncertainty.empty()
163 ? v_energy
164 : normalize_variant(m_metatomic_opts.variant.energy_uncertainty);
165 auto v_force = m_metatomic_opts.variant.force.empty()
166 ? v_energy
167 : normalize_variant(m_metatomic_opts.variant.force);
168
169 if (!m_metatomic_opts.energy_output.empty()) {
170 this->energy_key_ = m_metatomic_opts.energy_output;
171 } else {
172 this->energy_key_ =
173 metatomic_torch::pick_output("energy", outputs, v_energy);
174 }
175
176 this->non_conservative_ = m_metatomic_opts.non_conservative;
177 this->random_rotation_ = m_metatomic_opts.random_rotation;
178 this->n_symmetry_rotations_ = m_metatomic_opts.n_symmetry_rotations;
179 if (this->non_conservative_) {
180 if (!m_metatomic_opts.force_output.empty()) {
181 this->nc_forces_key_ = m_metatomic_opts.force_output;
182 if (!outputs.contains(this->nc_forces_key_)) {
183 throw std::runtime_error(
184 "Missing explicit force_output in metatomic model: " +
185 this->nc_forces_key_);
186 }
187 } else {
188 this->nc_forces_key_ = metatomic_torch::pick_output(
189 "non_conservative_force", outputs, v_force);
190 }
191 QUILL_LOG_INFO(m_log,
192 "[MetatomicPotential] Non-conservative forces from '{}'",
193 this->nc_forces_key_);
194 }
195 if (this->n_symmetry_rotations_ > 0) {
196 QUILL_LOG_INFO(m_log,
197 "[MetatomicPotential] Symmetry averaging over {} rotations",
199 } else if (this->random_rotation_) {
200 QUILL_LOG_INFO(
201 m_log, "[MetatomicPotential] Per-call random SO(3) rotation enabled");
202 }
203 if ((this->random_rotation_ || this->n_symmetry_rotations_ > 0) &&
204 random_seed > 0) {
205 torch::manual_seed(static_cast<uint64_t>(random_seed));
206 QUILL_LOG_INFO(m_log,
207 "[MetatomicPotential] torch RNG seeded from "
208 "main.randomSeed={}",
209 random_seed);
210 }
211
212 if (!outputs.contains(this->energy_key_)) {
213 QUILL_LOG_ERROR(
214 m_log,
215 "[MetatomicPotential] The model does not provide an '{}' output.",
216 this->energy_key_);
217 throw std::runtime_error("Missing energy output in metatomic model");
218 }
219
220 // 6. Set up evaluation options to request total energy
222 torch::make_intrusive<metatomic_torch::ModelEvaluationOptionsHolder>();
223 evaluations_options_->set_length_unit(m_metatomic_opts.length_unit);
224
225 auto model_output = outputs.at(this->energy_key_);
226 auto requested_output =
227 torch::make_intrusive<metatomic_torch::ModelOutputHolder>();
228
229 // Per-atom granularity is sample_kind == "atom" (get/set_per_atom removed).
230 requested_output->set_sample_kind(model_output->sample_kind());
231 requested_output->explicit_gradients = {};
232 requested_output->set_unit("eV");
233 evaluations_options_->outputs.insert(this->energy_key_, requested_output);
234
235 // Request non-conservative forces when enabled (#296)
236 if (this->non_conservative_ && !this->nc_forces_key_.empty()) {
237 auto nc_info = outputs.at(this->nc_forces_key_);
238 auto requested_nc =
239 torch::make_intrusive<metatomic_torch::ModelOutputHolder>();
240 requested_nc->set_sample_kind(nc_info->sample_kind());
241 requested_nc->explicit_gradients = {};
242 requested_nc->set_unit("eV/Angstrom");
243 evaluations_options_->outputs.insert(this->nc_forces_key_, requested_nc);
244 }
245
246 // 7. Optionally request energy uncertainty if threshold is positive
247 if (m_metatomic_opts.uncertainty_threshold > 0) {
248 this->uncertainty_threshold_ = m_metatomic_opts.uncertainty_threshold;
249 const bool explicit_uq_key =
250 !m_metatomic_opts.energy_uncertainty_output.empty();
251 if (explicit_uq_key) {
252 // User-specified key: hard fail if missing (not soft-disabled).
254 m_metatomic_opts.energy_uncertainty_output;
255 if (!outputs.contains(this->energy_uncertainty_key_)) {
256 QUILL_LOG_ERROR(m_log,
257 "[MetatomicPotential] energy_uncertainty_output '{}' "
258 "is not provided by the model.",
260 throw std::runtime_error(
261 "Missing explicit energy_uncertainty_output in metatomic model: " +
263 }
264 } else {
265 try {
266 this->energy_uncertainty_key_ = metatomic_torch::pick_output(
267 "energy_uncertainty", outputs, v_energy_uq);
268 } catch (const std::exception &e) {
269 QUILL_LOG_DEBUG(
270 m_log, "[MetatomicPotential] No uncertainty output available: {}",
271 e.what());
272 this->uncertainty_threshold_ = -1.0;
273 }
274 }
275
276 if (this->uncertainty_threshold_ > 0) {
277 auto uncertainty_info = outputs.at(this->energy_uncertainty_key_);
278 if (uncertainty_info->sample_kind() == "atom") {
279 auto requested_uncertainty =
280 torch::make_intrusive<metatomic_torch::ModelOutputHolder>();
281 requested_uncertainty->set_sample_kind("atom");
282 requested_uncertainty->explicit_gradients = {};
283 requested_uncertainty->set_unit("eV");
284 evaluations_options_->outputs.insert(this->energy_uncertainty_key_,
285 requested_uncertainty);
286 QUILL_LOG_INFO(m_log,
287 "[MetatomicPotential] Requested per-atom "
288 "'{}' from model (threshold = {})",
291 } else {
292 QUILL_LOG_DEBUG(m_log,
293 "[MetatomicPotential] Model provides '{}' "
294 "but sample_kind is not \"atom\"; skipping uncertainty "
295 "checks.",
297 this->uncertainty_threshold_ = -1.0;
298 }
299 }
300 }
301
302 this->check_consistency_ = m_metatomic_opts.check_consistency;
303 QUILL_LOG_INFO(m_log, "[MetatomicPotential] Initialization complete.");
304
305 fpeh.restore_fpe();
306}
static torch::optional< std::string > normalize_variant(const std::string &s)
std::vector< metatomic_torch::NeighborListOptions > nl_requests_
metatomic_torch::ModelEvaluationOptions evaluations_options_
eonc::log::Scoped m_log
metatomic_torch::ModelCapabilities capabilities_
std::string energy_uncertainty_key_
eonc::Parameters::metatomic_options_t m_metatomic_opts
c10::DeviceType device_type_
metatensor_torch::Module model_
torch::ScalarType dtype_

◆ ~MetatomicPotential()

MetatomicPotential::~MetatomicPotential ( )
overridedefault

Destructor.

◆ MetatomicPotential() [3/3]

MetatomicPotential::MetatomicPotential ( const MetatomicPotential & src,
CloneTag  )
private

Definition at line 308 of file MetatomicPotential.cpp.

Member Function Documentation

◆ clonePotential()

std::shared_ptr< eonc::Potential > MetatomicPotential::clonePotential ( ) const
nodiscardoverridevirtual

Independent instance that does not reload from disk.

nullptr means the caller should use makePotential().

Reimplemented from eonc::Potential.

Definition at line 329 of file MetatomicPotential.cpp.

329 {
330 return std::shared_ptr<eonc::Potential>(
331 new MetatomicPotential(*this, CloneTag{}));
332}

◆ computeNeighbors()

metatensor_torch::TensorBlock MetatomicPotential::computeNeighbors ( metatomic_torch::NeighborListOptions request,
long nAtoms,
const double * positions,
const double * box,
const bool periodic[3] )
private

Computes neighbor list using the vesin library.

This function calls vesin_neighbors to build a neighbor list based on the model's requirements (cutoff, full/half list) and converts it into a metatensor::TensorBlock suitable for metatomic.

Parameters
requestThe neighbor list options requested by the model.
nAtomsThe number of atoms in the system.
positionsPointer to the atomic positions array.
boxPointer to the simulation box matrix.
periodicPeriodicity flags for the three cell axes.
Returns
A metatensor_torch::TensorBlock containing the neighbor list.

Definition at line 577 of file MetatomicPotential.cpp.

579 {
580
581 auto cutoff = request->engine_cutoff(m_metatomic_opts.length_unit);
582
583 // Zero-init so vesin 0.6 skin/n_threads stay 0 when compiling against 0.6
584 // headers (must match linked libvesin — pin vesin>=0.6 for metatomic builds).
585 VesinOptions options{};
586 options.cutoff = cutoff;
587 options.full = request->full_list();
588 options.sorted = false;
589 options.return_shifts = true;
590 options.return_distances = false; // we don't need distances
591 options.return_vectors = true; // metatomic uses vectors for autograd
592
593 auto owned_list = std::make_unique<VesinNeighborList>();
594 VesinNeighborList *vesin_neighbor_list = owned_list.get();
595
596 VesinDevice cpu{VesinCPU, 0};
597 const char *error_message = nullptr;
598 int status = vesin_neighbors(reinterpret_cast<const double (*)[3]>(positions),
599 static_cast<size_t>(nAtoms),
600 reinterpret_cast<const double (*)[3]>(box),
601 const_cast<bool *>(periodic), cpu, options,
602 vesin_neighbor_list, &error_message);
603
604 if (status != EXIT_SUCCESS) {
605 std::string err_str = "vesin_neighbors failed";
606 if (error_message != nullptr) {
607 err_str += ": " + std::string(error_message);
608 } else {
609 err_str += " (no message; vesin header/lib ABI mismatch? need vesin>=0.6 "
610 "with matching engine)";
611 }
612 throw std::runtime_error(err_str);
613 }
614
615 // Convert from vesin to metatomic format
616 auto n_pairs = static_cast<int64_t>(vesin_neighbor_list->length);
617 auto labels_options_cpu =
618 torch::TensorOptions().dtype(torch::kInt32).device(torch::kCPU);
619
620 auto pair_samples_values = torch::empty({n_pairs, 5}, labels_options_cpu);
621 auto pair_samples_values_ptr = pair_samples_values.accessor<int32_t, 2>();
622 for (int64_t i = 0; i < n_pairs; i++) {
623 pair_samples_values_ptr[i][0] =
624 static_cast<int32_t>(vesin_neighbor_list->pairs[i][0]);
625 pair_samples_values_ptr[i][1] =
626 static_cast<int32_t>(vesin_neighbor_list->pairs[i][1]);
627 pair_samples_values_ptr[i][2] = vesin_neighbor_list->shifts[i][0];
628 pair_samples_values_ptr[i][3] = vesin_neighbor_list->shifts[i][1];
629 pair_samples_values_ptr[i][4] = vesin_neighbor_list->shifts[i][2];
630 }
631
632 // Custom deleter to free vesin's memory when the torch tensor is destroyed
633 auto *raw_list = owned_list.release();
634 auto deleter = [raw_list](void *) {
635 vesin_free(raw_list);
636 std::unique_ptr<VesinNeighborList> reclaim(raw_list);
637 };
638 vesin_neighbor_list = raw_list;
639
640 auto pair_vectors = torch::from_blob(
641 vesin_neighbor_list->vectors, {n_pairs, 3, 1}, deleter,
642 torch::TensorOptions().dtype(torch::kFloat64).device(torch::kCPU));
643
644 auto neighbor_samples = torch::make_intrusive<metatensor_torch::LabelsHolder>(
645 std::vector<std::string>{"first_atom", "second_atom", "cell_shift_a",
646 "cell_shift_b", "cell_shift_c"},
647 pair_samples_values.to(this->device_));
648
649 auto labels_options_dev =
650 torch::TensorOptions().dtype(torch::kInt32).device(this->device_);
651 auto neighbor_component =
652 torch::make_intrusive<metatensor_torch::LabelsHolder>(
653 "xyz", torch::tensor({0, 1, 2}, labels_options_dev).reshape({3, 1}));
654 auto neighbor_properties =
655 torch::make_intrusive<metatensor_torch::LabelsHolder>(
656 "distance", torch::zeros({1, 1}, labels_options_dev));
657
658 return torch::make_intrusive<metatensor_torch::TensorBlockHolder>(
659 pair_vectors.to(this->dtype_).to(this->device_), neighbor_samples,
660 std::vector<metatensor_torch::Labels>{neighbor_component},
661 neighbor_properties);
662}

◆ force()

void MetatomicPotential::force ( long nAtoms,
const double * positions,
const int * atomicNrs,
double * forces,
double * energy,
double * variance,
const double * box )
overridevirtual

Calculates the energy and forces for a given atomic configuration.

This is the core method of the potential. It takes the current atomic positions, builds the necessary data structures for metatomic, executes the model to get the potential energy, and uses PyTorch's autograd to compute forces.

Parameters
nAtomsNumber of atoms.
positionsFlat array of atomic positions (size nAtoms * 3).
atomicNrsFlat array of atomic numbers (size nAtoms), used for consistency checks.
forcesFlat array to store the calculated forces (size nAtoms * 3).
energyPointer to a double to store the calculated potential energy.
variancePointer to a double to store the variance of the energy (currently unused, set to NULL).
boxThe simulation box vectors (3x3 matrix).

Implements eonc::Potential.

Definition at line 358 of file MetatomicPotential.cpp.

361 {
362 // Serialize concurrent calls -- PyTorch model inference on the same
363 // Module instance is not thread-safe
364 std::lock_guard<std::mutex> lock(inference_mutex_);
365
366 eonc::FPEHandler fpeh;
367 fpeh.eat_fpe();
368
369 if (!atomicNrs) {
370 throw std::runtime_error(
371 "[MetatomicPotential] `atomicNrs` must be provided.");
372 }
373
374 const bool use_rotation =
375 this->random_rotation_ || this->n_symmetry_rotations_ > 0;
376 // n_symmetry_rotations averages; random_rotation alone is one rotated eval
377 const long n_passes =
378 this->n_symmetry_rotations_ > 0 ? this->n_symmetry_rotations_ : 1;
379
380 auto f64_options =
381 torch::TensorOptions().dtype(torch::kFloat64).device(torch::kCPU);
382 std::vector<int32_t> types_vec(atomicNrs, atomicNrs + nAtoms);
383 auto atomic_types_cpu =
384 torch::tensor(types_vec, torch::TensorOptions().dtype(torch::kInt32));
385
386 double energy_acc = 0.0;
387 auto forces_acc = torch::zeros({nAtoms, 3}, f64_options);
388 bool variance_set = false;
389
390 for (long i_pass = 0; i_pass < n_passes; ++i_pass) {
391 torch::Tensor R = torch::eye(
392 3, torch::TensorOptions().dtype(this->dtype_).device(this->device_));
393 if (use_rotation) {
394 R = random_so3(this->device_, this->dtype_);
395 }
396 // R is applied to row vectors: pos' = pos @ R^T (equiv. R @ pos for cols)
397 auto R_cpu = R.to(torch::kCPU).to(torch::kFloat64);
398 auto R_T = R.transpose(0, 1);
399
400 auto pos_cpu = torch::from_blob(const_cast<double *>(positions),
401 {nAtoms, 3}, f64_options)
402 .clone();
403 auto cell_cpu =
404 torch::from_blob(const_cast<double *>(box), {3, 3}, f64_options)
405 .clone();
406 if (use_rotation) {
407 pos_cpu = pos_cpu.matmul(R_cpu.transpose(0, 1));
408 // Rotate cell vectors (rows) the same way
409 cell_cpu = cell_cpu.matmul(R_cpu.transpose(0, 1));
410 }
411
412 std::vector<double> pos_buf(static_cast<size_t>(nAtoms) * 3);
413 std::vector<double> cell_buf(9);
414 std::memcpy(pos_buf.data(), pos_cpu.contiguous().data_ptr<double>(),
415 pos_buf.size() * sizeof(double));
416 std::memcpy(cell_buf.data(), cell_cpu.contiguous().data_ptr<double>(),
417 9 * sizeof(double));
418
419 auto torch_positions =
420 torch::from_blob(pos_buf.data(), {nAtoms, 3}, f64_options)
421 .to(this->dtype_)
422 .to(this->device_)
423 .set_requires_grad(!this->non_conservative_);
424
425 auto torch_cell = torch::from_blob(cell_buf.data(), {3, 3}, f64_options)
426 .to(this->dtype_)
427 .to(this->device_);
428
429 auto cell_norms = torch::norm(torch_cell, 2, /*dim=*/1);
430 auto torch_pbc = cell_norms.abs() > 1e-9;
431 bool periodic[3] = {torch_pbc[0].item<bool>(), torch_pbc[1].item<bool>(),
432 torch_pbc[2].item<bool>()};
433
434 auto atomic_types = atomic_types_cpu.to(this->device_);
435
436 auto system = torch::make_intrusive<metatomic_torch::SystemHolder>(
437 atomic_types, torch_positions, torch_cell, torch_pbc);
438
439 for (const auto &request : this->nl_requests_) {
440 auto neighbors = this->computeNeighbors(request, nAtoms, pos_buf.data(),
441 cell_buf.data(), periodic);
442 metatomic_torch::register_autograd_neighbors(system, neighbors,
443 this->check_consistency_);
444 system->add_neighbor_list(request, neighbors);
445 }
446
447 torch::Tensor forces_tensor;
448 try {
449 auto ivalue_output = this->model_.forward({
450 std::vector<metatomic_torch::System>{system},
452 this->check_consistency_,
453 });
454 auto dict_output = ivalue_output.toGenericDict();
455 auto output_map = dict_output.at(this->energy_key_)
456 .toCustomClass<metatensor_torch::TensorMapHolder>();
457
458 if (this->uncertainty_threshold_ > 0 && i_pass == 0) {
459 try {
460 if (dict_output.contains(this->energy_uncertainty_key_)) {
461 auto uncertainty_map =
462 dict_output.at(this->energy_uncertainty_key_)
463 .toCustomClass<metatensor_torch::TensorMapHolder>();
464 auto uncertainty_block =
465 metatensor_torch::TensorMapHolder::block_by_id(uncertainty_map,
466 0);
467 auto flat_uncertainty =
468 uncertainty_block->values().reshape({-1}).to(torch::kCPU);
469 if (variance != nullptr && flat_uncertainty.numel() > 0) {
470 try {
471 *variance =
472 flat_uncertainty.to(torch::kFloat64).mean().item<double>();
473 variance_set = true;
474 } catch (...) {
475 QUILL_LOG_DEBUG(m_log,
476 "[MetatomicPotential] Failed to compute mean "
477 "uncertainty for variance.");
478 }
479 }
480 auto atoms_above_threshold =
481 flat_uncertainty > this->uncertainty_threshold_;
482 if (torch::any(atoms_above_threshold).item<bool>()) {
483 auto samples = uncertainty_block->samples();
484 auto atom_indices_all = samples->column("atom").to(torch::kCPU);
485 auto atom_indices_above =
486 atom_indices_all.index({atoms_above_threshold});
487 std::ostringstream ss;
488 ss << "atoms at index [";
489 auto n_report = std::min<int64_t>(10, atom_indices_above.size(0));
490 for (int64_t i = 0; i < n_report; ++i) {
491 if (i > 0)
492 ss << ", ";
493 ss << atom_indices_above[i].item<int32_t>();
494 }
495 ss << "]";
496 if (atom_indices_above.size(0) > n_report) {
497 ss << " and " << (atom_indices_above.size(0) - n_report)
498 << " more";
499 }
500 QUILL_LOG_WARNING(
501 m_log,
502 "[MetatomicPotential] The uncertainty on atomic energies for "
503 "{} are larger than the threshold of {}. (Key: {}) Be "
504 "careful "
505 "when analyzing the results, and consider retraining the "
506 "model to better describe these configurations.",
507 ss.str(), this->uncertainty_threshold_,
508 this->energy_uncertainty_key_);
509 }
510 }
511 } catch (const std::exception &e) {
512 QUILL_LOG_WARNING(m_log,
513 "[MetatomicPotential] Failed to check {}: {}",
514 this->energy_uncertainty_key_, e.what());
515 }
516 }
517
518 auto energy_block =
519 metatensor_torch::TensorMapHolder::block_by_id(output_map, 0);
520 auto energy_tensor = energy_block->values();
521 energy_acc += energy_tensor.sum().item<double>();
522
523 if (this->non_conservative_ && !this->nc_forces_key_.empty()) {
524 auto nc_map = dict_output.at(this->nc_forces_key_)
525 .toCustomClass<metatensor_torch::TensorMapHolder>();
526 auto nc_block =
527 metatensor_torch::TensorMapHolder::block_by_id(nc_map, 0);
528 auto nc_vals = nc_block->values();
529 if (nc_vals.numel() != nAtoms * 3) {
530 throw std::runtime_error("[MetatomicPotential] NC force block has " +
531 std::to_string(nc_vals.numel()) +
532 " values, expected " +
533 std::to_string(nAtoms * 3));
534 }
535 auto nc_samples = nc_block->samples();
536 if (nc_samples->size() > 0 && nc_samples->names().size() > 1) {
537 auto atom_col = nc_samples->column("atom").to(torch::kCPU);
538 if (atom_col.size(0) != nAtoms) {
539 throw std::runtime_error(
540 "[MetatomicPotential] NC force samples atom count mismatch");
541 }
542 }
543 forces_tensor =
544 nc_vals.reshape({nAtoms, 3}).to(torch::kCPU).to(torch::kFloat64);
545 } else {
546 energy_tensor.backward(torch::ones_like(energy_tensor));
547 auto positions_grad = system->positions().grad();
548 forces_tensor = (-positions_grad).to(torch::kCPU).to(torch::kFloat64);
549 }
550 } catch (const std::exception &e) {
551 QUILL_LOG_ERROR(m_log, "[MetatomicPotential] Model evaluation failed: {}",
552 e.what());
553 throw;
554 }
555
556 // Rotate forces back to original frame: F = F' @ R (since pos' = pos @
557 // R^T)
558 if (use_rotation) {
559 forces_tensor = forces_tensor.matmul(R_cpu);
560 }
561 forces_acc += forces_tensor;
562 }
563
564 const double inv_n = 1.0 / static_cast<double>(n_passes);
565 *energy = energy_acc * inv_n;
566 forces_acc = forces_acc * inv_n;
567 static_cast<void>(variance_set);
568
569 std::memcpy(forces, forces_acc.contiguous().data_ptr<double>(),
570 nAtoms * 3 * sizeof(double));
571
572 fpeh.restore_fpe();
573}
metatensor_torch::TensorBlock computeNeighbors(metatomic_torch::NeighborListOptions request, long nAtoms, const double *positions, const double *box, const bool periodic[3])
Computes neighbor list using the vesin library.

◆ forceBatch()

void MetatomicPotential::forceBatch ( long nSystems,
long nAtoms,
const double *const * positions,
const int *const * atomicNrs,
double *const * forces,
double * energies,
double * variances,
const double *const * boxes )
overridevirtual

Reimplemented from eonc::Potential.

Definition at line 670 of file MetatomicPotential.cpp.

675 {
676 if (nSystems > 1) {
677 try {
678 forceBatchNative(nSystems, nAtoms, positions, atomicNrs, forces, energies,
679 variances, boxes);
680 for (long s = 0; s < nSystems; s++)
682 return;
683 } catch (const std::exception &e) {
684 QUILL_LOG_WARNING(m_log,
685 "[MetatomicPotential] batched forward failed ({}); "
686 "falling back to sequential force()",
687 e.what());
688 }
689 }
690 for (long s = 0; s < nSystems; s++) {
691 double var = 0;
692 force(nAtoms, positions[s], atomicNrs[s], forces[s], &energies[s], &var,
693 boxes[s]);
694 if (variances)
695 variances[s] = var;
697 }
698}
void force(long nAtoms, const double *positions, const int *atomicNrs, double *forces, double *energy, double *variance, const double *box) override
Calculates the energy and forces for a given atomic configuration.
void forceBatchNative(long nSystems, long nAtoms, const double *const *positions, const int *const *atomicNrs, double *const *forces, double *energies, double *variances, const double *const *boxes)
void recordForceCall() noexcept
Charge one evaluated geometry to this potential and its owning registry.

◆ forceBatchNative()

void MetatomicPotential::forceBatchNative ( long nSystems,
long nAtoms,
const double *const * positions,
const int *const * atomicNrs,
double *const * forces,
double * energies,
double * variances,
const double *const * boxes )
private

Definition at line 700 of file MetatomicPotential.cpp.

705 {
706 std::lock_guard<std::mutex> lock(inference_mutex_);
707
708 eonc::FPEHandler fpeh;
709 fpeh.eat_fpe();
710
711 auto f64_options =
712 torch::TensorOptions().dtype(torch::kFloat64).device(torch::kCPU);
713
714 std::vector<metatomic_torch::System> systems;
715 std::vector<torch::Tensor> pos_tensors;
716 systems.reserve(static_cast<size_t>(nSystems));
717 pos_tensors.reserve(static_cast<size_t>(nSystems));
718
719 for (long s = 0; s < nSystems; s++) {
720 auto torch_positions = torch::from_blob(const_cast<double *>(positions[s]),
721 {nAtoms, 3}, f64_options)
722 .to(this->dtype_)
723 .to(this->device_)
724 .set_requires_grad(true);
725 pos_tensors.push_back(torch_positions);
726
727 auto torch_cell =
728 torch::from_blob(const_cast<double *>(boxes[s]), {3, 3}, f64_options)
729 .to(this->dtype_)
730 .to(this->device_);
731
732 auto cell_norms = torch::norm(torch_cell, 2, /*dim=*/1);
733 auto torch_pbc = cell_norms.abs() > 1e-9;
734 bool periodic[3] = {torch_pbc[0].item<bool>(), torch_pbc[1].item<bool>(),
735 torch_pbc[2].item<bool>()};
736
737 if (!atomicNrs[s]) {
738 throw std::runtime_error(
739 "[MetatomicPotential] `atomicNrs` must be provided.");
740 }
741 std::vector<int32_t> types_vec(atomicNrs[s], atomicNrs[s] + nAtoms);
742 auto atomic_types =
743 torch::tensor(types_vec, torch::TensorOptions().dtype(torch::kInt32))
744 .to(this->device_);
745
746 auto system = torch::make_intrusive<metatomic_torch::SystemHolder>(
747 atomic_types, torch_positions, torch_cell, torch_pbc);
748
749 // Compute and register neighbor lists for this system
750 for (const auto &request : this->nl_requests_) {
751 auto neighbors = this->computeNeighbors(request, nAtoms, positions[s],
752 boxes[s], periodic);
753 metatomic_torch::register_autograd_neighbors(system, neighbors,
754 this->check_consistency_);
755 system->add_neighbor_list(request, neighbors);
756 }
757
758 systems.push_back(system);
759 }
760
761 // Single batched forward pass
762 metatensor_torch::TensorMap output_map;
763 try {
764 auto ivalue_output = this->model_.forward({
765 systems,
767 this->check_consistency_,
768 });
769 auto dict_output = ivalue_output.toGenericDict();
770 output_map = dict_output.at(this->energy_key_)
771 .toCustomClass<metatensor_torch::TensorMapHolder>();
772 } catch (const std::exception &e) {
773 QUILL_LOG_ERROR(m_log,
774 "[MetatomicPotential] Batched model evaluation failed: {}",
775 e.what());
776 throw;
777 }
778
779 // Extract per-system energies from the output TensorMap.
780 // For per-atom output: samples have ["system", "atom"] dimensions.
781 // For system-level output: samples have ["system"] dimension.
782 // In both cases, sum over all non-system dimensions to get per-system energy.
783 auto energy_block =
784 metatensor_torch::TensorMapHolder::block_by_id(output_map, 0);
785 auto energy_values = energy_block->values();
786 auto samples = energy_block->samples();
787
788 // Check if this is per-atom or per-system output
789 bool per_atom = samples->size() > 0 && samples->names().size() > 1;
790
791 if (per_atom) {
792 // Per-atom output: sum energies by system index
793 auto system_col = samples->column("system").to(torch::kCPU);
794 auto flat_energies = energy_values.reshape({-1}).to(torch::kCPU);
795
796 // Sum per-system energies for output
797 for (long s = 0; s < nSystems; s++) {
798 auto mask = (system_col == s);
799 energies[s] =
800 flat_energies.index({mask}).sum().to(torch::kFloat64).item<double>();
801 }
802
803 // Backward: sum ALL energies, single backward call.
804 // Each system's positions.grad() gets only its own contribution
805 // because energy_i depends only on positions_i.
806 energy_values.sum().backward();
807 } else {
808 // System-level output: values shape is (nSystems, 1) or similar
809 auto cpu_energies = energy_values.to(torch::kCPU).to(torch::kFloat64);
810 for (long s = 0; s < nSystems; s++) {
811 energies[s] = cpu_energies[s].sum().item<double>();
812 }
813 energy_values.backward(torch::ones_like(energy_values));
814 }
815
816 // Extract per-system forces from position gradients
817 for (long s = 0; s < nSystems; s++) {
818 auto positions_grad = pos_tensors[s].grad();
819 auto forces_tensor = -positions_grad.to(torch::kCPU).to(torch::kFloat64);
820 std::memcpy(forces[s], forces_tensor.contiguous().data_ptr<double>(),
821 nAtoms * 3 * sizeof(double));
822 }
823
824 // Variances: not yet supported in batched path
825 if (variances) {
826 for (long s = 0; s < nSystems; s++) {
827 variances[s] = 0.0;
828 }
829 }
830
831 fpeh.restore_fpe();
832}
double sum(const double *x, std::size_t n)
Round-to-nearest-even value of the exact sum of x[i].

◆ isThreadSafe()

bool MetatomicPotential::isThreadSafe ( ) const
inlinenodiscardoverridevirtualnoexcept

Single shared instance, serialized via mutex.

Sequential evaluation through computePotential() ensures correct force counting, removeNetForce, and PotRegistry bookkeeping. JIT profiling is disabled so all calls on the same instance produce deterministic results.

Reimplemented from eonc::Potential.

Definition at line 156 of file MetatomicPotential.h.

156{ return false; }

◆ needsPerImageInstance()

bool MetatomicPotential::needsPerImageInstance ( ) const
inlinenodiscardoverridevirtualnoexcept

Whether NEB should create separate Potential instances per image for true parallel force evaluation.

When true, NEB calls makePotential() once per image instead of sharing one instance. Override in potentials that use internal mutexes (e.g. MetatomicPotential).

Reimplemented from eonc::Potential.

Definition at line 157 of file MetatomicPotential.h.

157 {
158 return false;
159 }

◆ supportsBatchEvaluation()

bool MetatomicPotential::supportsBatchEvaluation ( ) const
inlinenodiscardoverridevirtualnoexcept

Batched evaluation via single shared instance.

Processes each system sequentially through the same model (identical to N force() calls but bypasses Matter::computePotential overhead). Forces, energies, and forceCallCounter are handled correctly.

Reimplemented from eonc::Potential.

Definition at line 165 of file MetatomicPotential.h.

165 {
166 return true;
167 }

Member Data Documentation

◆ capabilities_

metatomic_torch::ModelCapabilities MetatomicPotential::capabilities_
private

Definition at line 70 of file MetatomicPotential.h.

◆ check_consistency_

bool MetatomicPotential::check_consistency_
private

Definition at line 77 of file MetatomicPotential.h.

◆ device_

torch::Device MetatomicPotential::device_
private

Definition at line 76 of file MetatomicPotential.h.

◆ device_type_

c10::DeviceType MetatomicPotential::device_type_
private

Definition at line 75 of file MetatomicPotential.h.

◆ dtype_

torch::ScalarType MetatomicPotential::dtype_
private

Definition at line 74 of file MetatomicPotential.h.

◆ energy_key_

std::string MetatomicPotential::energy_key_
private

Definition at line 79 of file MetatomicPotential.h.

◆ energy_uncertainty_key_

std::string MetatomicPotential::energy_uncertainty_key_
private

Definition at line 80 of file MetatomicPotential.h.

◆ evaluations_options_

metatomic_torch::ModelEvaluationOptions MetatomicPotential::evaluations_options_
private

Definition at line 72 of file MetatomicPotential.h.

◆ inference_mutex_

std::mutex MetatomicPotential::inference_mutex_
mutableprivate

Definition at line 181 of file MetatomicPotential.h.

◆ m_log

eonc::log::Scoped MetatomicPotential::m_log
private

Definition at line 66 of file MetatomicPotential.h.

◆ m_metatomic_opts

eonc::Parameters::metatomic_options_t MetatomicPotential::m_metatomic_opts
private

Definition at line 67 of file MetatomicPotential.h.

◆ model_

metatensor_torch::Module MetatomicPotential::model_
private

Definition at line 69 of file MetatomicPotential.h.

◆ n_symmetry_rotations_

long MetatomicPotential::n_symmetry_rotations_ {0}
private

Definition at line 84 of file MetatomicPotential.h.

84{0};

◆ nc_forces_key_

std::string MetatomicPotential::nc_forces_key_
private

Definition at line 81 of file MetatomicPotential.h.

◆ nl_requests_

std::vector<metatomic_torch::NeighborListOptions> MetatomicPotential::nl_requests_
private

Definition at line 71 of file MetatomicPotential.h.

◆ non_conservative_

bool MetatomicPotential::non_conservative_ {false}
private

Definition at line 82 of file MetatomicPotential.h.

82{false};

◆ random_rotation_

bool MetatomicPotential::random_rotation_ {false}
private

Definition at line 83 of file MetatomicPotential.h.

83{false};

◆ uncertainty_threshold_

double MetatomicPotential::uncertainty_threshold_ {-1.0}
private

Definition at line 87 of file MetatomicPotential.h.

87{-1.0};

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