Program Listing for File commonPT.h

Program Listing for File commonPT.h#

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

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

#ifdef BUILD_PYTORCH
#include <torch/torch.h>
#include <torch/version.h>

#include <algorithm>
#include <cstdint>
#include <limits>
#include <map>
#include <set>
#include <sstream>
#include <string>
#include <type_traits>
#include <utility>
#include <vector>

#include "canonical_graph.h"
#include "common.h"
#include "neighbor_list.h"

namespace deepmd {

inline void build_comm_dict(torch::Dict<std::string, torch::Tensor>& comm_dict,
                            const InputNlist& lmp_list,
                            int** sendlist,
                            int* sendnum,
                            int* recvnum) {
  int nswap = lmp_list.nswap;
  auto int32_option =
      torch::TensorOptions().device(torch::kCPU).dtype(torch::kInt32);
  auto int64_option =
      torch::TensorOptions().device(torch::kCPU).dtype(torch::kInt64);

  torch::Tensor sendlist_tensor =
      torch::from_blob(static_cast<void*>(sendlist), {nswap}, int64_option);
  torch::Tensor sendnum_tensor =
      torch::from_blob(sendnum, {nswap}, int32_option);
  torch::Tensor recvnum_tensor =
      torch::from_blob(recvnum, {nswap}, int32_option);
  torch::Tensor sendproc_tensor =
      torch::from_blob(lmp_list.sendproc, {nswap}, int32_option);
  torch::Tensor recvproc_tensor =
      torch::from_blob(lmp_list.recvproc, {nswap}, int32_option);

  torch::Tensor communicator_tensor;
  static std::int64_t null_communicator = 0;
  if (lmp_list.world == nullptr) {
    communicator_tensor =
        torch::from_blob(&null_communicator, {1}, torch::kInt64);
  } else {
    communicator_tensor =
        torch::from_blob(const_cast<void*>(lmp_list.world), {1}, torch::kInt64);
  }

  comm_dict.insert_or_assign("send_list", sendlist_tensor);
  comm_dict.insert_or_assign("send_proc", sendproc_tensor);
  comm_dict.insert_or_assign("recv_proc", recvproc_tensor);
  comm_dict.insert_or_assign("send_num", sendnum_tensor);
  comm_dict.insert_or_assign("recv_num", recvnum_tensor);
  comm_dict.insert_or_assign("communicator", communicator_tensor);
}

inline void build_comm_dict_with_virtual_atoms(
    torch::Dict<std::string, torch::Tensor>& comm_dict,
    const InputNlist& lmp_list,
    const std::vector<int>& fwd_map,
    std::vector<std::vector<int>>& remapped_sendlist,
    std::vector<int*>& remapped_sendlist_ptrs,
    std::vector<int>& remapped_sendnum,
    std::vector<int>& remapped_recvnum) {
  remap_comm_sendlist(remapped_sendlist, remapped_sendnum, remapped_recvnum,
                      lmp_list, fwd_map);
  int nswap = lmp_list.nswap;
  remapped_sendlist_ptrs.resize(nswap);
  for (int s = 0; s < nswap; ++s) {
    remapped_sendlist_ptrs[s] = remapped_sendlist[s].data();
  }
  build_comm_dict(comm_dict, lmp_list, remapped_sendlist_ptrs.data(),
                  remapped_sendnum.data(), remapped_recvnum.data());
}

inline torch::Tensor createNlistTensor(
    const std::vector<std::vector<int>>& data, int min_nnei = 0) {
  int nloc = static_cast<int>(data.size());
  int nnei = min_nnei;
  for (int ii = 0; ii < nloc; ++ii) {
    nnei = std::max(nnei, static_cast<int>(data[ii].size()));
  }
  std::vector<int> flat_data(static_cast<size_t>(nloc) * nnei, -1);
  for (int ii = 0; ii < nloc; ++ii) {
    for (size_t jj = 0; jj < data[ii].size(); ++jj) {
      flat_data[static_cast<size_t>(ii) * nnei + jj] = data[ii][jj];
    }
  }
  torch::Tensor flat_tensor = torch::tensor(flat_data, torch::kInt32);
  return flat_tensor.view({1, nloc, nnei});
}

struct EdgeTensorPack {
  torch::Tensor edge_index;
  torch::Tensor edge_vec;
  torch::Tensor edge_index_ext;
  torch::Tensor edge_mask;
};

template <typename VALUETYPE>
inline EdgeTensorPack createEdgeTensors(
    const std::vector<std::vector<int>>& nlist,
    const std::vector<VALUETYPE>& coord,
    const std::vector<std::int64_t>& mapping,
    const int nloc,
    const int nall,
    const torch::Device& device,
    const bool with_geometry = true,
    const std::vector<int>* row_centers = nullptr,
    const bool fold_to_local = true) {
  // Folding reads an owner for every extended atom, so a mapping shorter than
  // that is a caller error rather than a degraded input: indexing it would be
  // out of bounds, and the out-of-range owners it appears to yield would drop
  // the corresponding edges one by one, leaving a quietly incomplete graph.
  if (fold_to_local && mapping.size() < static_cast<size_t>(nall)) {
    throw deepmd::deepmd_exception(
        "folding ghost neighbours onto their local owners needs an owner for "
        "each of the " +
        std::to_string(nall) + " extended atoms, but the mapping holds " +
        std::to_string(mapping.size()) +
        "; under LAMMPS this is what 'atom_modify map yes' supplies");
  }
  std::vector<std::int64_t> src;
  std::vector<std::int64_t> dst;
  std::vector<std::int64_t> src_ext;
  std::vector<std::int64_t> dst_ext;
  std::vector<VALUETYPE> edge_vec;
  size_t reserve_size = with_geometry ? 2 : 0;
  for (const auto& row : nlist) {
    reserve_size += row.size();
  }
  src.reserve(reserve_size);
  dst.reserve(reserve_size);
  src_ext.reserve(reserve_size);
  dst_ext.reserve(reserve_size);
  if (with_geometry) {
    edge_vec.reserve(reserve_size * 3);
  }

  // Real edges: use row_centers when LAMMPS has compacted away empty rows.
  for (int ii = 0; ii < static_cast<int>(nlist.size()); ++ii) {
    if (row_centers != nullptr &&
        static_cast<size_t>(ii) >= row_centers->size()) {
      continue;
    }
    const int center =
        row_centers == nullptr ? ii : (*row_centers)[static_cast<size_t>(ii)];
    if (center < 0 || center >= nloc || center >= nall) {
      continue;
    }
    const size_t center_offset = static_cast<size_t>(center) * 3;
    for (const int jj : nlist[ii]) {
      if (jj < 0 || jj >= nall) {
        continue;
      }
      // edge_index source: the local owner (folded) for single-domain message
      // passing, or the extended atom itself for the multi-rank with-comm
      // convention where ghost features are exchanged across ranks.
      std::int64_t src_node;
      if (fold_to_local) {
        const std::int64_t src_local = mapping[static_cast<size_t>(jj)];
        // Folding is single-domain, where every extended atom has an owner
        // among the local ones. An owner outside that range therefore marks a
        // mapping that was never filled, not a neighbour to skip: skipping
        // would discard every ghost edge and leave a graph that is quietly
        // missing the whole halo.
        if (src_local < 0 || src_local >= nloc) {
          throw deepmd::deepmd_exception(
              "extended atom " + std::to_string(jj) + " of " +
              std::to_string(nall) + " maps to owner " +
              std::to_string(src_local) + ", which is not one of the " +
              std::to_string(nloc) +
              " local atoms; under LAMMPS an owner for every extended atom is "
              "what 'atom_modify map yes' supplies");
        }
        src_node = src_local;
      } else {
        src_node = jj;
      }
      const size_t neighbor_offset = static_cast<size_t>(jj) * 3;
      const VALUETYPE dx = coord[neighbor_offset] - coord[center_offset];
      const VALUETYPE dy =
          coord[neighbor_offset + 1] - coord[center_offset + 1];
      const VALUETYPE dz =
          coord[neighbor_offset + 2] - coord[center_offset + 2];
      const VALUETYPE rr = dx * dx + dy * dy + dz * dz;
      if (rr <= static_cast<VALUETYPE>(1e-10)) {
        continue;
      }
      src.push_back(src_node);
      dst.push_back(center);
      src_ext.push_back(jj);
      dst_ext.push_back(center);
      if (with_geometry) {
        edge_vec.push_back(dx);
        edge_vec.push_back(dy);
        edge_vec.push_back(dz);
      }
    }
  }

  const size_t real_edges = src.size();
  if (with_geometry) {
    // Dummy edges keep exported edge tensors non-empty without affecting
    // output.
    for (int ii = 0; ii < 2; ++ii) {
      src.push_back(0);
      dst.push_back(0);
      src_ext.push_back(0);
      dst_ext.push_back(0);
      edge_vec.push_back(0);
      edge_vec.push_back(0);
      edge_vec.push_back(0);
    }
  }
  const size_t nedge = src.size();
  std::vector<std::int64_t> edge_index(2 * nedge);
  std::vector<std::int64_t> edge_index_ext(2 * nedge);
  // Materialize local-owner and extended scatter index spaces side by side.
  for (size_t ii = 0; ii < nedge; ++ii) {
    edge_index[ii] = src[ii];
    edge_index[nedge + ii] = dst[ii];
    edge_index_ext[ii] = src_ext[ii];
    edge_index_ext[nedge + ii] = dst_ext[ii];
  }

  auto int_options = torch::TensorOptions().dtype(torch::kInt64);
  EdgeTensorPack pack;
  if (nedge == 0) {
    pack.edge_index = torch::empty({2, 0}, int_options).to(device);
    pack.edge_index_ext = torch::empty({2, 0}, int_options).to(device);
  } else {
    pack.edge_index =
        torch::from_blob(edge_index.data(),
                         {2, static_cast<std::int64_t>(nedge)}, int_options)
            .clone()
            .to(device);
    pack.edge_index_ext =
        torch::from_blob(edge_index_ext.data(),
                         {2, static_cast<std::int64_t>(nedge)}, int_options)
            .clone()
            .to(device);
  }
  if (with_geometry) {
    pack.edge_vec =
        torch::from_blob(
            edge_vec.data(), {static_cast<std::int64_t>(nedge), 3},
            torch::TensorOptions().dtype(std::is_same<VALUETYPE, float>::value
                                             ? torch::kFloat32
                                             : torch::kFloat64))
            .clone()
            .to(device);
    std::vector<std::uint8_t> edge_mask(nedge, 0);
    std::fill(edge_mask.begin(), edge_mask.begin() + real_edges,
              static_cast<std::uint8_t>(1));
    pack.edge_mask =
        torch::from_blob(edge_mask.data(), {static_cast<std::int64_t>(nedge)},
                         torch::TensorOptions().dtype(torch::kUInt8))
            .clone()
            .to(torch::kBool)
            .to(device);
  }
  return pack;
}

inline EdgeTensorPack compactEdgeTensors(const torch::Tensor& edge_index,
                                         const torch::Tensor& edge_index_ext,
                                         const torch::Tensor& coord,
                                         const double rcut) {
  const auto coord_flat = coord.reshape({-1, 3});
  const auto src_ext = edge_index_ext.select(0, 0);
  const auto dst_ext = edge_index_ext.select(0, 1);
  const auto edge_vec_all =
      coord_flat.index_select(0, src_ext) - coord_flat.index_select(0, dst_ext);
  const auto rr = (edge_vec_all * edge_vec_all).sum(1);
  const auto keep = (rr > 1e-10) & (rr <= rcut * rcut);
  const auto real_idx = torch::nonzero(keep).reshape({-1});

  EdgeTensorPack pack;
  const auto real_edge_index = edge_index.index_select(1, real_idx);
  const auto real_edge_index_ext = edge_index_ext.index_select(1, real_idx);
  const auto real_edge_vec = edge_vec_all.index_select(0, real_idx);

  const auto dummy_index = torch::zeros({2, 2}, edge_index.options());
  const auto dummy_vec = torch::zeros({2, 3}, edge_vec_all.options());
  pack.edge_index = torch::cat({real_edge_index, dummy_index}, 1);
  pack.edge_index_ext = torch::cat({real_edge_index_ext, dummy_index}, 1);
  pack.edge_vec = torch::cat({real_edge_vec, dummy_vec}, 0);

  const auto real_mask = torch::ones(
      {real_idx.size(0)},
      torch::TensorOptions().dtype(torch::kBool).device(coord.device()));
  const auto dummy_mask = torch::zeros({2}, real_mask.options());
  pack.edge_mask = torch::cat({real_mask, dummy_mask}, 0);
  return pack;
}

struct GraphTensorPack {
  torch::Tensor atype;
  torch::Tensor n_node;
  torch::Tensor n_local;
  torch::Tensor edge_index;
  torch::Tensor edge_vec;
  torch::Tensor edge_mask;
  torch::Tensor destination_order;
  torch::Tensor destination_row_ptr;
  torch::Tensor source_order;
  torch::Tensor source_row_ptr;
};

struct CanonicalGraphTensorPack {
  torch::Tensor atype;
  torch::Tensor n_node;
  torch::Tensor n_local;
  torch::Tensor source;
  torch::Tensor edge_vec;
  torch::Tensor destination_row_ptr;
  torch::Tensor source_row_ptr;
  torch::Tensor source_order;
};

inline torch::Tensor canonicalIndexBytes(const torch::Tensor& index) {
  auto shape = index.sizes().vec();
  shape.push_back(index.element_size());
  return index.view(torch::kUInt8).view(shape);
}

inline CanonicalGraphTensorPack compactCanonicalGraph(
    const GraphTensorPack& graph) {
  const std::int64_t edge_count =
      graph.destination_row_ptr.select(0, graph.destination_row_ptr.size(0) - 1)
          .item<std::int64_t>();
  const std::int64_t storage_count = std::max<std::int64_t>(edge_count, 2);
  const auto index_type =
      canonical_index_width(graph.atype.size(0)) == DP_CANONICAL_INDEX32
          ? torch::kInt32
          : torch::kInt64;
  auto source = torch::zeros({storage_count},
                             graph.edge_index.options().dtype(index_type));
  auto edge_vec = torch::zeros({storage_count, 3},
                               graph.edge_vec.options().dtype(torch::kFloat32));
  auto source_order = torch::arange(
      storage_count, graph.edge_index.options().dtype(torch::kInt64));
  if (edge_count > 0) {
    source.slice(0, 0, edge_count)
        .copy_(graph.edge_index.select(0, 0)
                   .slice(0, 0, edge_count)
                   .to(index_type));
    edge_vec.slice(0, 0, edge_count)
        .copy_(graph.edge_vec.slice(0, 0, edge_count).to(torch::kFloat32));
    source_order.slice(0, 0, edge_count)
        .copy_(graph.source_order.slice(0, 0, edge_count));
  }
  return {graph.atype,
          graph.n_node,
          graph.n_local,
          source,
          edge_vec,
          graph.destination_row_ptr,
          graph.source_row_ptr,
          source_order};
}

inline void groupEdgesByNode(const std::int64_t* key,
                             const bool* mask,
                             const std::int64_t edge_count,
                             const std::int64_t node_count,
                             torch::Tensor& row_ptr,
                             torch::Tensor& order) {
  const auto options = torch::TensorOptions().dtype(torch::kInt64);
  row_ptr = torch::empty({node_count + 1}, options);
  order = torch::empty({edge_count}, options);
  std::vector<std::int64_t> cursor(node_count + 2, 0);
  for (std::int64_t edge = 0; edge < edge_count; ++edge) {
    const std::int64_t bucket =
        (mask == nullptr || mask[edge]) ? key[edge] : node_count;
    ++cursor[bucket + 1];
  }
  for (std::int64_t bucket = 0; bucket < node_count + 1; ++bucket) {
    cursor[bucket + 1] += cursor[bucket];
  }
  std::int64_t* row_data = row_ptr.data_ptr<std::int64_t>();
  std::copy(cursor.begin(), cursor.begin() + node_count + 1, row_data);
  std::int64_t* order_data = order.data_ptr<std::int64_t>();
  for (std::int64_t edge = 0; edge < edge_count; ++edge) {
    const std::int64_t bucket =
        (mask == nullptr || mask[edge]) ? key[edge] : node_count;
    order_data[cursor[bucket]++] = edge;
  }
}

inline void buildGraphCSRWithTensorOps(GraphTensorPack& pack,
                                       const std::int64_t node_count,
                                       const bool destination_sorted) {
  const auto index = pack.edge_index.to(torch::kInt64).contiguous();
  const auto mask = pack.edge_mask.to(torch::kBool).contiguous();
  const auto real_index = torch::nonzero(mask).reshape({-1});
  const auto padding_index =
      torch::nonzero(torch::logical_not(mask)).reshape({-1});
  const auto real_destination = index.select(0, 1).index_select(0, real_index);
  const auto real_source = index.select(0, 0).index_select(0, real_index);
  const auto destination_counts =
      torch::bincount(real_destination, {}, node_count);
  const auto source_counts = torch::bincount(real_source, {}, node_count);
  const auto zero = torch::zeros({1}, destination_counts.options());
  pack.destination_row_ptr =
      torch::cat({zero, torch::cumsum(destination_counts, 0)})
          .to(torch::kInt64)
          .contiguous();
  pack.source_row_ptr = torch::cat({zero, torch::cumsum(source_counts, 0)})
                            .to(torch::kInt64)
                            .contiguous();
  if (destination_sorted) {
    pack.destination_order = torch::arange(index.size(1), real_index.options());
  } else {
    const auto real_destination_order =
        torch::argsort(real_destination, 0, false);
    pack.destination_order =
        torch::cat(
            {real_index.index_select(0, real_destination_order), padding_index})
            .contiguous();
  }
  const auto real_source_order = torch::argsort(real_source, 0, false);
  pack.source_order =
      torch::cat({real_index.index_select(0, real_source_order), padding_index})
          .contiguous();
}

inline void buildGraphCSR(GraphTensorPack& pack,
                          const std::int64_t node_count,
                          const bool destination_sorted = false) {
  if (!pack.edge_index.device().is_cpu()) {
    buildGraphCSRWithTensorOps(pack, node_count, destination_sorted);
    return;
  }
  const auto index = pack.edge_index.to(torch::kInt64).contiguous();
  const auto mask = pack.edge_mask.to(torch::kBool).contiguous();
  const std::int64_t edge_count = index.size(1);
  const bool* mask_data = mask.const_data_ptr<bool>();
  torch::Tensor destination_order;
  groupEdgesByNode(index.const_data_ptr<std::int64_t>() + edge_count, mask_data,
                   edge_count, node_count, pack.destination_row_ptr,
                   destination_order);
  groupEdgesByNode(index.const_data_ptr<std::int64_t>(), mask_data, edge_count,
                   node_count, pack.source_row_ptr, pack.source_order);
  pack.destination_order =
      destination_sorted
          ? torch::arange(edge_count,
                          torch::TensorOptions().dtype(torch::kInt64))
          : destination_order;
}

inline void buildGraphCSR(GraphTensorPack& pack) {
  buildGraphCSR(pack, pack.atype.size(0));
}

inline void canonicalizeGraphPayload(GraphTensorPack& pack,
                                     const std::int64_t node_count) {
  if (!pack.edge_index.device().is_cpu()) {
    const auto destination = pack.edge_index.select(0, 1);
    const auto padding_node = torch::full_like(destination, node_count);
    const auto destination_key =
        torch::where(pack.edge_mask, destination, padding_node);
    const auto order =
        torch::argsort(destination_key, /*stable=*/true, 0, false);
    pack.edge_index = pack.edge_index.index_select(1, order).contiguous();
    pack.edge_vec = pack.edge_vec.index_select(0, order).contiguous();
    pack.edge_mask = pack.edge_mask.index_select(0, order).contiguous();
    buildGraphCSR(pack, node_count, /*destination_sorted=*/true);
    return;
  }
  const auto index = pack.edge_index.to(torch::kInt64).contiguous();
  const auto mask = pack.edge_mask.to(torch::kBool).contiguous();
  const std::int64_t edge_count = index.size(1);
  torch::Tensor row_ptr;
  torch::Tensor order;
  groupEdgesByNode(index.const_data_ptr<std::int64_t>() + edge_count,
                   mask.const_data_ptr<bool>(), edge_count, node_count, row_ptr,
                   order);
  pack.edge_index = pack.edge_index.index_select(1, order).contiguous();
  pack.edge_vec = pack.edge_vec.index_select(0, order).contiguous();
  pack.edge_mask = pack.edge_mask.index_select(0, order).contiguous();
  buildGraphCSR(pack, node_count, /*destination_sorted=*/true);
}

template <typename VALUETYPE>
inline GraphTensorPack buildGraphTensors(
    const std::vector<std::vector<int>>& nlist,
    const std::vector<VALUETYPE>& coord,
    const std::vector<int>& atype_ext,
    const std::vector<std::int64_t>& mapping,
    const int nloc,
    const int nall,
    const double rcut,
    const torch::Device& device,
    const std::vector<int>* row_centers = nullptr,
    const bool fold_to_local = true) {
  auto int_options = torch::TensorOptions().dtype(torch::kInt64);

  // 1. Cached-style topology only (no geometry): when fold_to_local=true,
  //    edge_index folds ghost neighbours onto their local owners (single-rank);
  //    when false, edge_index indexes the extended atoms directly (multi-rank).
  //    edge_index_ext always keeps extended indices for the on-device geometry
  //    recompute.
  const EdgeTensorPack topology =
      createEdgeTensors(nlist, coord, mapping, nloc, nall, device,
                        /*with_geometry=*/false, row_centers, fold_to_local);

  // 2. Recompute geometry from the current coords on-device, filter by rcut and
  //    append the two masked dummy edges.  The model is compiled for float64
  //    inputs, so build the coord tensor as float64 to match the edge path.
  std::vector<double> coord_d(coord.begin(), coord.end());
  at::Tensor coord_tensor =
      torch::from_blob(coord_d.data(), {static_cast<std::int64_t>(nall), 3},
                       torch::TensorOptions().dtype(torch::kFloat64))
          .clone()
          .to(device);
  const EdgeTensorPack edges = compactEdgeTensors(
      topology.edge_index, topology.edge_index_ext, coord_tensor, rcut);

  GraphTensorPack pack;
  pack.edge_index = edges.edge_index;  // (2, E): local-folded or extended
  pack.edge_vec = edges.edge_vec;      // (E, 3) neighbour - center
  pack.edge_mask = edges.edge_mask;    // (E,) bool
  // Single-rank: N == nloc (ghosts folded onto owners).  Multi-rank: N == nall
  // (ghosts are distinct nodes whose features come from their real halo types).
  const std::int64_t n_node_count = fold_to_local ? nloc : nall;
  pack.n_node = torch::full({1}, n_node_count, int_options).to(device);
  pack.n_local = torch::full({1}, nloc, int_options).to(device);
  // Node types from the extended types (NOT atype[mapping]): the local slice
  // for single-rank, the full extended set (incl. real halo types) for
  // multi-rank.
  std::vector<std::int64_t> atype_nodes(atype_ext.begin(),
                                        atype_ext.begin() + n_node_count);
  pack.atype = torch::from_blob(atype_nodes.data(), {n_node_count}, int_options)
                   .clone()
                   .to(device);
  return pack;
}

inline at::Tensor extend_graph_aparam(const at::Tensor& aparam_tensor,
                                      std::int64_t n_node_count,
                                      std::int64_t nlocal,
                                      std::int64_t daparam) {
  if (daparam <= 0) {
    return aparam_tensor;  // model has no aparam input; passed through empty
  }
  if (aparam_tensor.numel() == 0) {
    if (nlocal > 0) {
      throw deepmd::deepmd_exception(
          "aparam is required (dim_aparam=" + std::to_string(daparam) +
          ") but no values were provided on a rank owning " +
          std::to_string(nlocal) + " atoms.");
    }
    // ghost-only rank: there are no owned rows to supply; zeros are inert
    // under the owned-node mask but the artifact needs the full node axis.
    return torch::zeros({n_node_count, daparam}, aparam_tensor.options());
  }
  if (aparam_tensor.numel() != nlocal * daparam) {
    throw deepmd::deepmd_exception(
        "aparam holds " + std::to_string(aparam_tensor.numel()) +
        " values but the graph route expects nlocal * dim_aparam = " +
        std::to_string(nlocal) + " * " + std::to_string(daparam) + ".");
  }
  at::Tensor owned = aparam_tensor.reshape({nlocal, daparam});
  if (nlocal == n_node_count) {
    return owned;  // single-rank / folded graph: nothing to pad
  }
  at::Tensor padded =
      torch::zeros({n_node_count, daparam}, aparam_tensor.options());
  padded.slice(0, 0, nlocal).copy_(owned);
  return padded;
}

inline void check_graph_aparam_flat(const at::Tensor& aparam,
                                    std::int64_t daparam,
                                    const char* where) {
  if (daparam <= 0) {
    return;
  }
  if (aparam.dim() != 2 || aparam.size(1) != daparam) {
    std::ostringstream oss;
    oss << where
        << ": graph-route aparam must be flat (N, daparam) on the node axis "
           "(produce it with extend_graph_aparam); got a rank-"
        << aparam.dim() << " tensor of shape " << aparam.sizes()
        << " for daparam = " << daparam << ".";
    throw deepmd::deepmd_exception(oss.str());
  }
}

inline torch::Tensor applyPairExclusion(const torch::Tensor& edge_index,
                                        const torch::Tensor& edge_mask,
                                        const torch::Tensor& atype,
                                        const torch::Tensor& type_mask_table,
                                        const int ntypes) {
  if (!type_mask_table.defined()) {
    return edge_mask;
  }
  const auto src = edge_index.index({0});  // (E,) neighbour
  const auto dst = edge_index.index({1});  // (E,) center
  const auto src_t = atype.index_select(0, src);
  const auto dst_t = atype.index_select(0, dst);
  // type_ij = atype[dst] * (ntypes + 1) + atype[src]  (matches Python)
  const auto type_ij = dst_t * (ntypes + 1) + src_t;
  const auto keep = type_mask_table.index_select(0, type_ij).to(torch::kBool);
  return torch::logical_and(edge_mask, keep);
}

inline torch::Tensor applyPairExclusionNlist(
    const torch::Tensor& nlist,
    const torch::Tensor& atype_ext,
    const torch::Tensor& type_mask_table,
    const int ntypes) {
  if (!type_mask_table.defined()) {
    return nlist;
  }
  const std::int64_t nf = nlist.size(0);
  const std::int64_t nloc = nlist.size(1);
  const std::int64_t nnei = nlist.size(2);
  const std::int64_t nall = atype_ext.size(1);
  // center types: first nloc extended atoms.  type_i = atype * (ntypes + 1).
  const auto type_i = atype_ext.slice(1, 0, nloc) * (ntypes + 1);  // (nf, nloc)
  // append virtual atom of type ntypes; map -1 neighbours to it.
  const auto ae = torch::cat(
      {atype_ext, torch::full({nf, 1}, ntypes, atype_ext.options())}, 1);
  const auto nlist_for_type =
      torch::where(nlist == -1, torch::full_like(nlist, nall), nlist);
  const auto type_j = torch::gather(
      ae.unsqueeze(1).expand({nf, nloc, nall + 1}), 2, nlist_for_type);
  // type_ij = type_i * (ntypes + 1) + type_j  (matches Python: type_i already
  // scaled above; here just add the neighbour type).
  const auto type_ij = type_i.unsqueeze(2) + type_j;  // (nf, nloc, nnei)
  const auto keep = type_mask_table.index_select(0, type_ij.reshape({-1}))
                        .reshape({nf, nloc, nnei});
  return torch::where(keep == 1, nlist, torch::full_like(nlist, -1));
}

inline void remap_graph_outputs_to_dense_keys(
    std::map<std::string, torch::Tensor>& output_map,
    const std::int64_t nloc,
    const std::int64_t nall,
    const bool atomic,
    const bool single_rank = true) {
  if (!single_rank) {
    throw deepmd::deepmd_exception(
        "remap_graph_outputs_to_dense_keys requires single-rank graph input");
  }
  using torch::indexing::Slice;
  const std::int64_t nf = 1;
  const auto& energy_pub = output_map.at("energy");  // (nf, 1)
  const auto& force_pub = output_map.at("force");    // (N, 3), N == nloc
  const auto& virial_pub = output_map.at("virial");  // (nf, 9)

  output_map["energy_redu"] = energy_pub.reshape({nf, 1});
  output_map["energy_derv_c_redu"] = virial_pub.reshape({nf, 1, 9});

  // Local force -> (nf, nall, 1, 3) with zero ghost rows.
  auto force_full = torch::zeros({nf, nall, 1, 3}, force_pub.options());
  force_full.index_put_({0, Slice(0, nloc), 0}, force_pub);
  output_map["energy_derv_r"] = force_full;

  if (atomic) {
    const auto& atom_energy_pub = output_map.at("atom_energy");  // (N, 1)
    const auto& atom_virial_pub = output_map.at("atom_virial");  // (N, 9)
    output_map["energy"] = atom_energy_pub.reshape({nf, nloc, 1});
    auto atom_virial_full =
        torch::zeros({nf, nall, 1, 9}, atom_virial_pub.options());
    atom_virial_full.index_put_({0, Slice(0, nloc), 0}, atom_virial_pub);
    output_map["energy_derv_c"] = atom_virial_full;
  }
}

inline void flatten_canonical_atom_virial(
    std::map<std::string, torch::Tensor>& output_map) {
  const auto entry = output_map.find("atom_virial");
  if (entry == output_map.end()) {
    return;
  }
  entry->second = entry->second.reshape({entry->second.size(0), 9});
}

inline void remap_graph_spin_outputs_to_dense_keys(
    std::map<std::string, torch::Tensor>& output_map,
    const std::int64_t nloc,
    const std::int64_t nall,
    const bool atomic) {
  using torch::indexing::Slice;
  const std::int64_t nf = 1;
  remap_graph_outputs_to_dense_keys(output_map, nloc, nall, atomic,
                                    /*single_rank=*/true);
  const auto& force_mag_pub = output_map.at("force_mag");  // (N, 3)
  auto force_mag_full = torch::zeros({nf, nall, 1, 3}, force_mag_pub.options());
  force_mag_full.index_put_({0, Slice(0, nloc), 0}, force_mag_pub);
  output_map["energy_derv_r_mag"] = force_mag_full;
}

inline void remap_graph_outputs_to_dense_keys_extended(
    std::map<std::string, torch::Tensor>& output_map,
    const std::int64_t nloc,
    const std::int64_t nall,
    const bool atomic) {
  using torch::indexing::Slice;
  const std::int64_t nf = 1;
  const auto& atom_energy_pub = output_map.at("atom_energy");  // (N==nall, 1)
  const auto& force_pub = output_map.at("force");    // (N==nall, 3) extended
  const auto& virial_pub = output_map.at("virial");  // (nf, 9)

  // Owned energy = sum over LOCAL atoms only; ghost nodes carry bias-only
  // energy belonging to other ranks.
  output_map["energy_redu"] =
      atom_energy_pub.index({Slice(0, nloc)}).sum().reshape({nf, 1});
  output_map["energy_derv_c_redu"] = virial_pub.reshape({nf, 1, 9});
  // Extended force: ghost rows stay distinct for LAMMPS reverse-comm fold-back.
  output_map["energy_derv_r"] = force_pub.reshape({nf, nall, 1, 3});

  if (atomic) {
    const auto& atom_virial_pub = output_map.at("atom_virial");  // (N==nall, 9)
    output_map["energy"] =
        atom_energy_pub.index({Slice(0, nloc)}).reshape({nf, nloc, 1});
    output_map["energy_derv_c"] = atom_virial_pub.reshape({nf, nall, 1, 9});
  }
}

inline void remap_graph_spin_outputs_to_dense_keys_extended(
    std::map<std::string, torch::Tensor>& output_map,
    const std::int64_t nloc,
    const std::int64_t nall,
    const bool atomic) {
  const std::int64_t nf = 1;
  remap_graph_outputs_to_dense_keys_extended(output_map, nloc, nall, atomic);
  const auto& force_mag_pub = output_map.at("force_mag");  // (N==nall, 3)
  output_map["energy_derv_r_mag"] = force_mag_pub.reshape({nf, nall, 1, 3});
}

}  // namespace deepmd

#endif  // BUILD_PYTORCH