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.
361 {
362
363
365
366 eonc::FPEHandler fpeh;
368
369 if (!atomicNrs) {
370 throw std::runtime_error(
371 "[MetatomicPotential] `atomicNrs` must be provided.");
372 }
373
374 const bool use_rotation =
376
377 const long n_passes =
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) {
395 }
396
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
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)
424
425 auto torch_cell = torch::from_blob(cell_buf.data(), {3, 3}, f64_options)
428
429 auto cell_norms = torch::norm(torch_cell, 2, 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
441 cell_buf.data(), periodic);
442 metatomic_torch::register_autograd_neighbors(system, neighbors,
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},
453 });
454 auto dict_output = ivalue_output.toGenericDict();
455 auto output_map = dict_output.at(this->
energy_key_)
456 .toCustomClass<metatensor_torch::TensorMapHolder>();
457
459 try {
460 if (dict_output.contains(this->energy_uncertainty_key_)) {
461 auto uncertainty_map =
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 =
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(
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 {}: {}",
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
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
557
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
573}