Program Listing for File NativeSpinPTExpt.h

Program Listing for File NativeSpinPTExpt.h#

↰ Return to documentation for file (source/api_cc/include/NativeSpinPTExpt.h)

// SPDX-License-Identifier: LGPL-3.0-or-later
#pragma once

#ifdef BUILD_PYTORCH
// The AOTInductor package loader header is absent on some platforms (e.g.
// macOS x86_64); the native-spin compact backend is compiled out there.
#if __has_include(<torch/csrc/inductor/aoti_package/model_package_loader.h>)
#define BUILD_PT_EXPT_NATIVE_SPIN 1
#else
#define BUILD_PT_EXPT_NATIVE_SPIN 0
#endif

#if BUILD_PT_EXPT_NATIVE_SPIN

#include <torch/torch.h>

#include <mutex>

#include "DeepSpin.h"

// Forward-declare to keep the private header out of the public one. Defined in
// commonPTExpt.h.
namespace deepmd::ptexpt {
class ChargeStateFold;
class GraphReplay;
struct HaloTensors;
}  // namespace deepmd::ptexpt

namespace torch::inductor {
class AOTIModelPackageLoader;
}

namespace deepmd {

struct GraphTensorPack;
struct CanonicalGraphTensorPack;

class NativeSpinPTExpt : public DeepSpinBackend {
 public:
  NativeSpinPTExpt();
  ~NativeSpinPTExpt() override;
  NativeSpinPTExpt(const std::string& model,
                   const int& gpu_rank = 0,
                   const std::string& file_content = "");
  void init(const std::string& model,
            const int& gpu_rank = 0,
            const std::string& file_content = "") override;

  double cutoff() const override {
    assert(inited);
    return rcut;
  };
  int numb_types() const override {
    assert(inited);
    return ntypes;
  };
  int numb_types_spin() const override {
    assert(inited);
    return ntypes_spin;
  };
  int dim_fparam() const override {
    assert(inited);
    return dfparam;
  };
  int dim_aparam() const override {
    assert(inited);
    return daparam;
  };
  int dim_chg_spin() const override {
    assert(inited);
    return settable_chgspin;
  };
  void set_charge_spin(const std::vector<double>& charge_spin) override;
  void get_type_map(std::string& type_map) override;
  bool is_aparam_nall() const override { return false; };
  bool has_default_fparam() const override {
    assert(inited);
    return has_default_fparam_;
  };
  std::vector<bool> get_use_spin() const override {
    assert(inited);
    return use_spin_;
  };

  void computew(std::vector<double>& ener,
                std::vector<double>& force,
                std::vector<double>& force_mag,
                std::vector<double>& virial,
                std::vector<double>& atom_energy,
                std::vector<double>& atom_virial,
                const std::vector<double>& coord,
                const std::vector<double>& spin,
                const std::vector<int>& atype,
                const std::vector<double>& box,
                const std::vector<double>& fparam,
                const std::vector<double>& aparam,
                const bool atomic) override;
  void computew(std::vector<double>& ener,
                std::vector<float>& force,
                std::vector<float>& force_mag,
                std::vector<float>& virial,
                std::vector<float>& atom_energy,
                std::vector<float>& atom_virial,
                const std::vector<float>& coord,
                const std::vector<float>& spin,
                const std::vector<int>& atype,
                const std::vector<float>& box,
                const std::vector<float>& fparam,
                const std::vector<float>& aparam,
                const bool atomic) override;
  void computew(std::vector<double>& ener,
                std::vector<double>& force,
                std::vector<double>& force_mag,
                std::vector<double>& virial,
                std::vector<double>& atom_energy,
                std::vector<double>& atom_virial,
                const std::vector<double>& coord,
                const std::vector<double>& spin,
                const std::vector<int>& atype,
                const std::vector<double>& box,
                const int nghost,
                const InputNlist& inlist,
                const int& ago,
                const std::vector<double>& fparam,
                const std::vector<double>& aparam,
                const bool atomic) override;
  void computew(std::vector<double>& ener,
                std::vector<float>& force,
                std::vector<float>& force_mag,
                std::vector<float>& virial,
                std::vector<float>& atom_energy,
                std::vector<float>& atom_virial,
                const std::vector<float>& coord,
                const std::vector<float>& spin,
                const std::vector<int>& atype,
                const std::vector<float>& box,
                const int nghost,
                const InputNlist& inlist,
                const int& ago,
                const std::vector<float>& fparam,
                const std::vector<float>& aparam,
                const bool atomic) override;

  // Charge/spin-aware overloads.  This backend serves the condition in force
  // rather than marshalling one per call, so a condition named here is
  // checked against that state and rejected when it names another; the
  // inherited defaults would drop it without a word.  An empty condition
  // selects the state in force.
  void computew(std::vector<double>& ener,
                std::vector<double>& force,
                std::vector<double>& force_mag,
                std::vector<double>& virial,
                std::vector<double>& atom_energy,
                std::vector<double>& atom_virial,
                const std::vector<double>& coord,
                const std::vector<double>& spin,
                const std::vector<int>& atype,
                const std::vector<double>& box,
                const std::vector<double>& fparam,
                const std::vector<double>& aparam,
                const std::vector<double>& charge_spin,
                const bool atomic) override;
  void computew(std::vector<double>& ener,
                std::vector<float>& force,
                std::vector<float>& force_mag,
                std::vector<float>& virial,
                std::vector<float>& atom_energy,
                std::vector<float>& atom_virial,
                const std::vector<float>& coord,
                const std::vector<float>& spin,
                const std::vector<int>& atype,
                const std::vector<float>& box,
                const std::vector<float>& fparam,
                const std::vector<float>& aparam,
                const std::vector<double>& charge_spin,
                const bool atomic) override;
  void computew(std::vector<double>& ener,
                std::vector<double>& force,
                std::vector<double>& force_mag,
                std::vector<double>& virial,
                std::vector<double>& atom_energy,
                std::vector<double>& atom_virial,
                const std::vector<double>& coord,
                const std::vector<double>& spin,
                const std::vector<int>& atype,
                const std::vector<double>& box,
                const int nghost,
                const InputNlist& inlist,
                const int& ago,
                const std::vector<double>& fparam,
                const std::vector<double>& aparam,
                const std::vector<double>& charge_spin,
                const bool atomic) override;
  void computew(std::vector<double>& ener,
                std::vector<float>& force,
                std::vector<float>& force_mag,
                std::vector<float>& virial,
                std::vector<float>& atom_energy,
                std::vector<float>& atom_virial,
                const std::vector<float>& coord,
                const std::vector<float>& spin,
                const std::vector<int>& atype,
                const std::vector<float>& box,
                const int nghost,
                const InputNlist& inlist,
                const int& ago,
                const std::vector<float>& fparam,
                const std::vector<float>& aparam,
                const std::vector<double>& charge_spin,
                const bool atomic) override;

  void compute_canonical_graph_gpu(double* d_atom_energy,
                                   double* d_force,
                                   double* d_force_mag,
                                   double* d_virial,
                                   double* d_atom_virial,
                                   const std::int64_t* d_atype,
                                   const void* d_source,
                                   DP_CanonicalIndexWidth index_width,
                                   const float* d_edge_vec,
                                   const std::int64_t* d_destination_row_ptr,
                                   const std::int64_t* d_source_row_ptr,
                                   const std::int64_t* d_source_order,
                                   const float* d_spin,
                                   void* world,
                                   const DP_HaloExchange* halo,
                                   const std::int64_t nloc,
                                   const std::int64_t nall_nodes,
                                   const std::int64_t edge_storage,
                                   void* stream) override;

  bool uses_canonical_graph_inference() const override;

  bool canonical_graph_requires_halo() const override;

  bool uses_native_spin_scheme() const override;

 private:
  template <typename VALUETYPE, typename ENERGYVTYPE>
  void compute(ENERGYVTYPE& ener,
               std::vector<VALUETYPE>& force,
               std::vector<VALUETYPE>& force_mag,
               std::vector<VALUETYPE>& virial,
               std::vector<VALUETYPE>& atom_energy,
               std::vector<VALUETYPE>& atom_virial,
               const std::vector<VALUETYPE>& coord,
               const std::vector<VALUETYPE>& spin,
               const std::vector<int>& atype,
               const int nghost,
               const InputNlist& lmp_list,
               const int& ago,
               const std::vector<VALUETYPE>& fparam,
               const std::vector<VALUETYPE>& aparam,
               const std::vector<double>& charge_spin,
               const bool atomic);
  template <typename VALUETYPE, typename ENERGYVTYPE>
  void compute(ENERGYVTYPE& ener,
               std::vector<VALUETYPE>& force,
               std::vector<VALUETYPE>& force_mag,
               std::vector<VALUETYPE>& virial,
               std::vector<VALUETYPE>& atom_energy,
               std::vector<VALUETYPE>& atom_virial,
               const std::vector<VALUETYPE>& coord,
               const std::vector<VALUETYPE>& spin,
               const std::vector<int>& atype,
               const std::vector<VALUETYPE>& box,
               const std::vector<VALUETYPE>& fparam,
               const std::vector<VALUETYPE>& aparam,
               const std::vector<double>& charge_spin,
               const bool atomic);

  bool reads_charge_spin_per_call() const { return dchgspin > 0; }

  template <typename VALUETYPE, typename ENERGYVTYPE>
  void compute_frame(ENERGYVTYPE& ener,
                     std::vector<VALUETYPE>& force,
                     std::vector<VALUETYPE>& force_mag,
                     std::vector<VALUETYPE>& virial,
                     std::vector<VALUETYPE>& atom_energy,
                     std::vector<VALUETYPE>& atom_virial,
                     const std::vector<VALUETYPE>& coord,
                     const std::vector<VALUETYPE>& spin,
                     const std::vector<int>& atype,
                     const std::vector<VALUETYPE>& box,
                     const std::vector<VALUETYPE>& fparam,
                     const std::vector<VALUETYPE>& aparam,
                     const std::vector<double>& charge_spin,
                     const bool atomic);

  std::vector<torch::Tensor> run_model_canonical(
      const CanonicalGraphTensorPack& graph,
      const torch::Tensor& spin,
      const void* world,
      const ptexpt::HaloTensors& halo);

  std::vector<torch::Tensor> run_model_graph(const GraphTensorPack& graph,
                                             const torch::Tensor& spin,
                                             const torch::Tensor& fparam,
                                             const torch::Tensor& aparam,
                                             const torch::Tensor& charge_spin);

  std::map<std::string, torch::Tensor> run_graph_payload(
      GraphTensorPack& graph,
      const std::int64_t node_count,
      const std::int64_t nloc,
      const torch::Tensor& spin,
      const std::vector<double>& fparam,
      const std::vector<double>& aparam,
      const std::vector<double>& charge_spin,
      const void* world = nullptr,
      const ptexpt::HaloTensors* halo = nullptr);

  void extract_outputs(std::map<std::string, torch::Tensor>& output_map,
                       const std::vector<torch::Tensor>& flat_outputs);

  void translate_error(std::function<void()> f);

  bool inited;
  // Every width below is a property of the loaded archive.  They read as zero
  // until ``init`` has run, so that a query on an uninitialised backend
  // answers "none" rather than whatever the allocation happened to hold.
  int ntypes = 0;
  int ntypes_spin = 0;
  int dfparam = 0;
  int daparam = 0;
  // Conditioning width of the compiled forward's argument list.  Zero for a
  // model that carries no condition, and also for a compressed one, whose
  // condition lives in frozen tables rather than in an input.  Every gate that
  // decides whether to hand the forward a condition tensor reads this.
  int dchgspin = 0;
  // Width of a charge state this model can be given; see ``dim_chg_spin()``.
  int settable_chgspin = 0;
  bool has_default_fparam_;
  std::vector<double> default_fparam_;
  // The condition served by every forward pass that is not given one
  // explicitly, initialised from the archive and replaced by
  // ``set_charge_spin``.
  std::vector<double> default_chg_spin_;
  std::vector<std::pair<double, double> > chg_spin_table_ranges_;
  double rcut;
  int gpu_id;
  bool gpu_enabled;
  // Which of the two schemas the loaded artifact declares: the compact
  // dual-CSR ABI when true, the general NeighborGraph ABI when false.
  bool canonical_abi_ = false;
  // Two-entry source CSR placeholders that decline the per-atom virial.
  at::Tensor source_row_placeholder_;
  at::Tensor source_order_placeholder_;
  // Edge-vector precision the NeighborGraph artifact was traced with, read
  // from the ``graph_edge_dtype`` metadata field. The compact ABI is float32
  // by definition and validates that at load.
  bool graph_edge_fp32_ = false;
  // Whether the descriptor reads intermediate features of neighbouring nodes,
  // which an extended-region graph cannot supply for a ghost node.
  bool has_message_passing_ = false;
  std::vector<bool> use_spin_;
  std::vector<std::string> type_map;
  std::vector<std::string> output_keys;  // sorted internal output key names
  // Device-resident (ntypes+1)^2 model-level pair-type keep table, uploaded
  // once in ``init`` from the ``pair_exclude_types`` metadata field. An
  // UNDEFINED tensor means no exclusion. Exclusion belongs to the graph build:
  // the ingestion seam applies it exactly once and the exported lower consumes
  // a pre-excluded payload.
  torch::Tensor pair_exclude_table_;
  // Cached LAMMPS skin topology, rebuilt whenever ``ago == 0``. The
  // model-cutoff edge set is recomputed from it on-device every step.
  NeighborListData nlist_data;
  std::vector<std::int64_t> mapping_;
  at::Tensor edge_index_tensor;      // node-space edges (folded or extended)
  at::Tensor edge_index_ext_tensor;  // extended-atom edges, for the geometry
  std::unique_ptr<torch::inductor::AOTIModelPackageLoader> loader;
  // CUDA-graph replay of repeated device-resident canonical evaluations,
  // declared after the loader so that the graph is released before the
  // constants it reads.
  std::unique_ptr<deepmd::ptexpt::GraphReplay> canonical_replay_;
  // Serializes the runs of the model, which runs on a single-threaded runner,
  // the device-resident entry point, whose replay of canonical evaluations
  // keeps its graph across calls, and the replacement of the constants. The
  // mutex is recursive because a replayed evaluation enters the runner again.
  std::recursive_mutex evaluation_mutex_;
  // The charge/spin condition a compressed descriptor folded into the
  // constants of its lower, re-runnable so that a condition chosen at runtime
  // can be served.  Null for an uncompressed model, which reads its condition
  // as an ordinary input and needs no rebuild.
  std::unique_ptr<deepmd::ptexpt::ChargeStateFold> charge_state_fold_;
};

}  // namespace deepmd

#endif  // BUILD_PT_EXPT_NATIVE_SPIN
#endif  // BUILD_PYTORCH