Loading...
Searching...
No Matches
MetatomicPotential.cpp
Go to the documentation of this file.
1/*
2** This file is part of eOn.
3**
4** SPDX-License-Identifier: BSD-3-Clause
5**
6** Copyright (c) 2010--present, eOn Development Team
7** All rights reserved.
8**
9** Repo:
10** https://github.com/TheochemUI/eOn
11*/
13#include "eon/Parameters.h"
14#include "eon/fpe_handler.h"
15#include "vesin.h"
16
17#include <torch/csrc/jit/runtime/graph_executor.h>
18
19#include <cstdint>
20#include <memory>
21#include <random>
22#include <sstream>
23#include <string>
24#include <vector>
25
26namespace {
27
28// metatensor-torch 0.10.3 Module::to() walks every attribute when
29// `_mts_buffer_names` is missing. Exported PET-MAD stores mixed dicts as
30// ordinary attrs; empty containers count as non-metatensor and throw.
31// Weights already moved. Swallow only that mixed-dict error. Do not
32// register `_mts_buffer_names` on scripted modules (JIT slot assert).
33bool is_mixed_mts_to_error(const c10::Error &e) {
34 const std::string w = e.what_without_backtrace();
35 return w.find("metatensor and non-metatensor") != std::string::npos;
36}
37
38void move_atomistic_model(metatensor_torch::Module &model,
39 torch::Device device) {
40 try {
41 model.to(device);
42 } catch (const c10::Error &e) {
43 if (!is_mixed_mts_to_error(e)) {
44 throw;
45 }
46 }
47}
48
49} // namespace
50
51static torch::optional<std::string> normalize_variant(const std::string &s) {
52 if (s.empty() || s == "off")
53 return torch::nullopt;
54 return s;
55}
56
58 : MetatomicPotential(params.metatomic_options(),
59 params.main_options().randomSeed) {}
60
62 const eonc::Parameters::metatomic_options_t &opts, long random_seed)
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
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
221 this->evaluations_options_ =
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).
253 this->energy_uncertainty_key_ =
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.",
259 this->energy_uncertainty_key_);
260 throw std::runtime_error(
261 "Missing explicit energy_uncertainty_output in metatomic model: " +
262 this->energy_uncertainty_key_);
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 = {})",
289 this->energy_uncertainty_key_,
290 this->uncertainty_threshold_);
291 } else {
292 QUILL_LOG_DEBUG(m_log,
293 "[MetatomicPotential] Model provides '{}' "
294 "but sample_kind is not \"atom\"; skipping uncertainty "
295 "checks.",
296 this->energy_uncertainty_key_);
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}
307
328
329std::shared_ptr<eonc::Potential> MetatomicPotential::clonePotential() const {
330 return std::shared_ptr<eonc::Potential>(
331 new MetatomicPotential(*this, CloneTag{}));
332}
333
334// --- helpers for random / symmetry rotations (#287, #292) ---
335
336namespace {
337
338// Uniform random rotation in SO(3) via QR of a Gaussian matrix with positive
339// determinant (Arvo / Shoemake style, sufficient for stochastic averaging).
340torch::Tensor random_so3(torch::Device device, torch::ScalarType dtype) {
341 auto A =
342 torch::randn({3, 3}, torch::TensorOptions().dtype(dtype).device(device));
343 auto qr = torch::linalg_qr(A);
344 auto Q = std::get<0>(qr);
345 auto R = std::get<1>(qr);
346 auto d = torch::sign(torch::diagonal(R));
347 Q = Q * d.unsqueeze(0);
348 if (torch::det(Q).item<double>() < 0) {
349 Q.select(1, 0).mul_(-1);
350 }
351 return Q;
352}
353
354} // namespace
355
356// --- MetatomicPotential::force ---
357
358void MetatomicPotential::force(long nAtoms, const double *positions,
359 const int *atomicNrs, double *forces,
360 double *energy, double *variance,
361 const double *box) {
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}
574
575// --- MetatomicPotential::computeNeighbors (helper) ---
576
577metatensor_torch::TensorBlock MetatomicPotential::computeNeighbors(
578 metatomic_torch::NeighborListOptions request, long nAtoms,
579 const double *positions, const double *box, const bool periodic[3]) {
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}
663
664// --- MetatomicPotential::forceBatch ---
665// Processes N systems sequentially through the same model instance.
666// Numerically identical to N individual force() calls. The single-instance
667// design avoids JIT profiling divergence and N model copies. True batched
668// model.forward({sys0..sysN}) is a future optimization (see #if 0 block below).
669
670void MetatomicPotential::forceBatch(long nSystems, long nAtoms,
671 const double *const *positions,
672 const int *const *atomicNrs,
673 double *const *forces, double *energies,
674 double *variances,
675 const double *const *boxes) {
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}
699
700void MetatomicPotential::forceBatchNative(long nSystems, long nAtoms,
701 const double *const *positions,
702 const int *const *atomicNrs,
703 double *const *forces,
704 double *energies, double *variances,
705 const double *const *boxes) {
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}
static torch::optional< std::string > normalize_variant(const std::string &s)
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)
std::vector< metatomic_torch::NeighborListOptions > nl_requests_
metatomic_torch::ModelEvaluationOptions evaluations_options_
eonc::log::Scoped m_log
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
metatomic_torch::ModelCapabilities capabilities_
EON_MTA_POT_API MetatomicPotential(const eonc::Parameters &params)
Constructor for the MetatomicPotential.
std::string energy_uncertainty_key_
eonc::Parameters::metatomic_options_t m_metatomic_opts
c10::DeviceType device_type_
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.
std::shared_ptr< eonc::Potential > clonePotential() const override
Independent instance that does not reload from disk.
metatensor_torch::Module model_
torch::ScalarType dtype_
eonc::metatomic_options_t metatomic_options_t
Definition Parameters.h:77
void recordForceCall() noexcept
Charge one evaluated geometry to this potential and its owning registry.
Potential(PotType a_ptype)
Production default: construction-scope registry, else PotRegistry::get().
RAII resource manager for the ARTn C library with global synchronization.