LCOV - code coverage report
Current view: top level - src - torch_c_api.cpp (source / functions) Coverage Total Hit
Test: CP2K Regtests (git:1be8651) Lines: 76.9 % 546 420
Test Date: 2026-11-24 01:22:08 Functions: 87.3 % 71 62

            Line data    Source code
       1              : /*----------------------------------------------------------------------------*/
       2              : /*  CP2K: A general program to perform molecular dynamics simulations         */
       3              : /*  Copyright 2000-2026 CP2K developers group <https://cp2k.org>              */
       4              : /*                                                                            */
       5              : /*  SPDX-License-Identifier: GPL-2.0-or-later                                 */
       6              : /*----------------------------------------------------------------------------*/
       7              : 
       8              : #if defined(__LIBTORCH)
       9              : 
      10              : #include <ATen/Parallel.h>
      11              : #if defined(__LIBTORCH_CUDA)
      12              : #include <ATen/cuda/CUDAContextLight.h>
      13              : #include <c10/cuda/CUDAAllocatorConfig.h>
      14              : #endif
      15              : #include <c10/core/DeviceGuard.h>
      16              : #include <torch/csrc/api/include/torch/cuda.h>
      17              : #include <torch/csrc/autograd/autograd.h>
      18              : #include <torch/csrc/jit/passes/freeze_module.h>
      19              : #include <torch/csrc/jit/passes/inliner.h>
      20              : #include <torch/csrc/jit/passes/subgraph_rewrite.h>
      21              : #include <torch/csrc/jit/runtime/graph_executor.h>
      22              : #include <torch/script.h>
      23              : 
      24              : #include "offload/offload_library.h"
      25              : 
      26              : #if defined(__OPENBLAS)
      27              : #include <cblas.h>
      28              : #endif
      29              : 
      30              : #include "base/cp_assert.h"
      31              : 
      32              : #include <cfenv>
      33              : #include <climits>
      34              : #include <cstdlib>
      35              : #include <cstring>
      36              : #include <mutex>
      37              : #include <optional>
      38              : #include <string>
      39              : #include <unordered_map>
      40              : #include <unordered_set>
      41              : #include <vector>
      42              : 
      43              : #if defined(__OPENBLAS)
      44              : // PyTorch's oneMKL batch ABI is not compatible with OpenBLAS's same-named
      45              : // entry points. Expand grouped GEMMs into the portable CBLAS interface.
      46              : extern "C" void
      47         3888 : cblas_sgemm_batch(const CBLAS_ORDER order, const CBLAS_TRANSPOSE *trans_a,
      48              :                   const CBLAS_TRANSPOSE *trans_b, const int *m, const int *n,
      49              :                   const int *k, const float *alpha, const float **a,
      50              :                   const int *lda, const float **b, const int *ldb,
      51              :                   const float *beta, float **c, const int *ldc,
      52              :                   const int group_count, const int *group_size) {
      53         3888 :   int offset = 0;
      54         7776 :   for (int group = 0; group < group_count; ++group) {
      55        84888 :     for (int operation = 0; operation < group_size[group]; ++operation) {
      56        81000 :       const int index = offset + operation;
      57        81000 :       cblas_sgemm(order, trans_a[group], trans_b[group], m[group], n[group],
      58        81000 :                   k[group], alpha[group], a[index], lda[group], b[index],
      59        81000 :                   ldb[group], beta[group], c[index], ldc[group]);
      60              :     }
      61         3888 :     offset += group_size[group];
      62              :   }
      63         3888 : }
      64              : 
      65              : extern "C" void
      66        18900 : cblas_dgemm_batch(const CBLAS_ORDER order, const CBLAS_TRANSPOSE *trans_a,
      67              :                   const CBLAS_TRANSPOSE *trans_b, const int *m, const int *n,
      68              :                   const int *k, const double *alpha, const double **a,
      69              :                   const int *lda, const double **b, const int *ldb,
      70              :                   const double *beta, double **c, const int *ldc,
      71              :                   const int group_count, const int *group_size) {
      72        18900 :   int offset = 0;
      73        37800 :   for (int group = 0; group < group_count; ++group) {
      74       327030 :     for (int operation = 0; operation < group_size[group]; ++operation) {
      75       308130 :       const int index = offset + operation;
      76       308130 :       cblas_dgemm(order, trans_a[group], trans_b[group], m[group], n[group],
      77       308130 :                   k[group], alpha[group], a[index], lda[group], b[index],
      78       308130 :                   ldb[group], beta[group], c[index], ldc[group]);
      79              :     }
      80        18900 :     offset += group_size[group];
      81              :   }
      82        18900 : }
      83              : #endif
      84              : 
      85              : typedef torch::Tensor torch_c_tensor_t;
      86              : typedef c10::Dict<std::string, torch::Tensor> torch_c_dict_t;
      87              : typedef torch::jit::Module torch_c_model_t;
      88              : 
      89              : class TorchFloatingPointMaskGuard {
      90              : public:
      91          429 :   TorchFloatingPointMaskGuard() : active_(std::feholdexcept(&env_) == 0) {}
      92          429 :   ~TorchFloatingPointMaskGuard() {
      93          429 :     if (active_) {
      94          429 :       std::feclearexcept(FE_ALL_EXCEPT);
      95          429 :       std::fesetenv(&env_);
      96              :     }
      97          429 :   }
      98              : 
      99              : private:
     100              :   std::fenv_t env_;
     101              :   bool active_;
     102              : };
     103              : 
     104              : /*******************************************************************************
     105              :  * \brief Internal helper for selecting the CUDA device when available.
     106              :  * \author Ole Schuett
     107              :  ******************************************************************************/
     108              : static bool use_cuda_if_available = true;
     109              : 
     110            0 : static void enable_expandable_cuda_segments_if_unconfigured() {
     111              : #if defined(__LIBTORCH_CUDA)
     112              :   static const bool initialized = []() {
     113              :     const char *legacy_config = std::getenv("PYTORCH_CUDA_ALLOC_CONF");
     114              :     const char *config = std::getenv("PYTORCH_ALLOC_CONF");
     115              :     if ((legacy_config == nullptr || legacy_config[0] == '\0') &&
     116              :         (config == nullptr || config[0] == '\0')) {
     117              :       c10::cuda::CUDACachingAllocator::setAllocatorSettings(
     118              :           "expandable_segments:True");
     119              :     }
     120              :     return true;
     121              :   }();
     122              :   (void)initialized;
     123              : #endif
     124            0 : }
     125              : 
     126           54 : static bool get_positive_int_env(const char *name, int &value) {
     127           54 :   const char *raw = std::getenv(name);
     128           54 :   if (raw == nullptr || raw[0] == '\0') {
     129              :     return false;
     130              :   }
     131            0 :   char *end = nullptr;
     132            0 :   const long parsed = std::strtol(raw, &end, 10);
     133            0 :   if (end == raw || *end != '\0' || parsed <= 0 || parsed > INT_MAX) {
     134              :     return false;
     135              :   }
     136            0 :   value = static_cast<int>(parsed);
     137            0 :   return true;
     138              : }
     139              : 
     140        12466 : static void initialize_torch_threads_from_env() {
     141        12466 :   static bool initialized = false;
     142        12466 :   if (initialized) {
     143        12439 :     return;
     144              :   }
     145           27 :   initialized = true;
     146              : 
     147           27 :   int num_threads = 0;
     148           27 :   if (get_positive_int_env("CP2K_TORCH_NUM_THREADS", num_threads)) {
     149            0 :     at::set_num_threads(num_threads);
     150              :   }
     151           27 :   if (get_positive_int_env("CP2K_TORCH_NUM_INTEROP_THREADS", num_threads)) {
     152            0 :     at::set_num_interop_threads(num_threads);
     153              :   }
     154              : }
     155              : 
     156         9732 : static torch::Device get_device() {
     157         9732 :   initialize_torch_threads_from_env();
     158         9732 :   if (!use_cuda_if_available || !torch::cuda::is_available()) {
     159         9732 :     return torch::kCPU;
     160              :   }
     161            0 :   enable_expandable_cuda_segments_if_unconfigured();
     162            0 :   const auto device_count = torch::cuda::device_count();
     163            0 :   if (device_count <= 0) {
     164            0 :     return torch::kCPU;
     165              :   }
     166            0 :   const int chosen_device = offload_get_chosen_device();
     167            0 :   const int device = (chosen_device >= 0) ? chosen_device : 0;
     168            0 :   cp_assert(device < device_count);
     169            0 :   return torch::Device(torch::kCUDA, device);
     170              : }
     171              : 
     172         9732 : static torch::Device get_device_with_guard(c10::OptionalDeviceGuard &guard) {
     173         9732 :   const auto device = get_device();
     174         9732 :   if (device.is_cuda()) {
     175            0 :     guard.reset_device(device);
     176              :   }
     177         9732 :   return device;
     178              : }
     179              : 
     180          338 : static bool use_batched_gradient_readback(const torch::Tensor &tensor) {
     181              : #if defined(__LIBTORCH_CUDA)
     182              :   return tensor.is_cuda() &&
     183              :          at::cuda::getDeviceProperties(tensor.device().index())->integrated;
     184              : #else
     185          338 :   (void)tensor;
     186          338 :   return false;
     187              : #endif
     188              : }
     189              : 
     190           35 : static void set_jit_fusion_strategy() {
     191              :   // JIT Fusion strategy optimization, hardcode dynamic 10, see also
     192              :   // https://github.com/mir-group/pair_nequip_allegro.git
     193           35 :   torch::jit::FusionStrategy strategy = {
     194           35 :       {torch::jit::FusionBehavior::DYNAMIC, 10}};
     195           70 :   torch::jit::setFusionStrategy(strategy);
     196           35 : }
     197              : 
     198           78 : static void copy_string_to_c_buffer(const std::string &source, char **content,
     199              :                                     int *length) {
     200           78 :   *length = source.length();
     201           78 :   *content = (char *)malloc(source.length() + 1); // +1 for null terminator
     202           78 :   strcpy(*content, source.c_str());
     203           78 : }
     204              : 
     205           35 : static bool can_load_directly_to_device(const torch::Device &device) {
     206           35 :   return !device.is_cuda() || device.index() == 0 ||
     207            0 :          torch::cuda::device_count() == 1;
     208              : }
     209              : 
     210           35 : static torch::jit::Module load_module_for_device(
     211              :     const char *filename, const torch::Device &device,
     212              :     std::unordered_map<std::string, std::string> *extra_files = nullptr,
     213              :     const bool load_on_cpu = false) {
     214           35 :   if (!load_on_cpu && can_load_directly_to_device(device)) {
     215           35 :     if (extra_files != nullptr) {
     216           38 :       return torch::jit::load(filename, device, *extra_files);
     217              :     }
     218           32 :     return torch::jit::load(filename, device);
     219              :   }
     220            0 :   auto model = (extra_files != nullptr)
     221            0 :                    ? torch::jit::load(filename, torch::kCPU, *extra_files)
     222            0 :                    : torch::jit::load(filename, torch::kCPU);
     223            0 :   model.to(device);
     224            0 :   return model;
     225            0 : }
     226              : 
     227            0 : static void remap_device_constants(torch::jit::Block *block,
     228              :                                    const torch::Device &device) {
     229            0 :   for (torch::jit::Node *node : block->nodes()) {
     230            0 :     if (node->kind() == torch::jit::prim::Constant &&
     231            0 :         node->outputs().size() == 1 &&
     232            0 :         node->output()->type()->kind() == c10::TypeKind::DeviceObjType &&
     233            0 :         node->hasAttribute(torch::jit::attr::value) &&
     234            0 :         node->kindOf(torch::jit::attr::value) == torch::jit::AttributeKind::s) {
     235            0 :       node->s_(torch::jit::attr::value, device.str());
     236              :     }
     237            0 :     bool has_tensor_input = false;
     238            0 :     for (const torch::jit::Value *input : node->inputs()) {
     239            0 :       has_tensor_input |= input->type()->kind() == c10::TypeKind::TensorType;
     240              :     }
     241            0 :     const auto *schema = node->maybeSchema();
     242            0 :     if (!has_tensor_input && schema != nullptr) {
     243              :       const auto &arguments = schema->arguments();
     244            0 :       for (size_t i = 0; i < arguments.size() && i < node->inputs().size();
     245              :            ++i) {
     246            0 :         const auto input_value = torch::jit::toIValue(node->input(i));
     247            0 :         if (arguments[i].name() == "device" && input_value.has_value() &&
     248            0 :             input_value->isNone()) {
     249            0 :           torch::jit::WithInsertPoint insertion_guard(node);
     250            0 :           auto *device_value =
     251            0 :               node->owningGraph()->insertConstant(torch::jit::IValue(device));
     252            0 :           node->replaceInput(i, device_value);
     253            0 :         }
     254            0 :       }
     255              :     }
     256            0 :     for (torch::jit::Block *nested_block : node->blocks()) {
     257            0 :       remap_device_constants(nested_block, device);
     258              :     }
     259              :   }
     260            0 : }
     261              : 
     262            0 : static void remap_model_device_constants(torch::jit::Module &model,
     263              :                                          const torch::Device &device) {
     264            0 :   for (const auto &attribute : model.named_attributes(false)) {
     265            0 :     const auto &value = attribute.value;
     266            0 :     if (value.isTensor()) {
     267            0 :       model.setattr(attribute.name, value.toTensor().to(device));
     268            0 :     } else if (value.isTensorList()) {
     269            0 :       auto tensors = value.toTensorList();
     270            0 :       for (size_t i = 0; i < tensors.size(); ++i) {
     271            0 :         tensors.set(i, tensors.get(i).to(device));
     272              :       }
     273            0 :       model.setattr(attribute.name, tensors);
     274            0 :     }
     275            0 :   }
     276            0 :   for (const auto &method : model.get_methods()) {
     277            0 :     remap_device_constants(method.graph()->block(), device);
     278            0 :   }
     279            0 :   for (auto child : model.children()) {
     280            0 :     remap_model_device_constants(child, device);
     281            0 :   }
     282            0 : }
     283              : 
     284         4978 : static void promote_float32_constants(torch::jit::Block *block) {
     285       193021 :   for (torch::jit::Node *node : block->nodes()) {
     286       225682 :     if (node->kind() == torch::jit::prim::Constant &&
     287       221502 :         node->hasAttribute(torch::jit::attr::value) &&
     288        33459 :         node->kindOf(torch::jit::attr::value) == torch::jit::AttributeKind::t) {
     289         2014 :       const auto tensor = node->t(torch::jit::attr::value);
     290         2014 :       if (tensor.defined() && tensor.scalar_type() == torch::kFloat32) {
     291            0 :         const auto promoted = tensor.to(torch::kFloat64);
     292            0 :         node->t_(torch::jit::attr::value, promoted);
     293            0 :         node->output()->setType(c10::TensorType::create(promoted));
     294            0 :       }
     295         2014 :     }
     296       188043 :     const auto *schema = node->maybeSchema();
     297       188043 :     if (schema != nullptr) {
     298              :       const auto &arguments = schema->arguments();
     299       480472 :       for (size_t i = 0; i < arguments.size() && i < node->inputs().size();
     300              :            ++i) {
     301       202901 :         const auto value = torch::jit::toIValue(node->input(i));
     302       202901 :         if (arguments[i].name() == "dtype" && value.has_value() &&
     303       208012 :             value->isInt() &&
     304         2090 :             value->toInt() == static_cast<int64_t>(torch::kFloat32)) {
     305              :           // A dtype constant can also be used as a dimension or an index.
     306              :           // Replace this edge only; leave other uses and integer tensors
     307              :           // intact.
     308         1368 :           torch::jit::WithInsertPoint insertion_guard(node);
     309         1368 :           auto *dtype = node->owningGraph()->insertConstant(
     310         2736 :               static_cast<int64_t>(torch::kFloat64));
     311         1368 :           node->replaceInput(i, dtype);
     312         1368 :         }
     313       202901 :       }
     314              :     }
     315       188043 :     for (torch::jit::Block *nested : node->blocks()) {
     316            0 :       promote_float32_constants(nested);
     317              :     }
     318              :   }
     319         4978 : }
     320              : 
     321         3249 : static void promote_model_float32(torch::jit::Module &model) {
     322        15561 :   for (const auto &attribute : model.named_attributes(false)) {
     323        12312 :     const auto &value = attribute.value;
     324        14896 :     if (value.isTensor() && value.toTensor().defined() &&
     325         2584 :         value.toTensor().scalar_type() == torch::kFloat32) {
     326         4674 :       model.setattr(attribute.name, value.toTensor().to(torch::kFloat64));
     327         9975 :     } else if (value.isTensorList()) {
     328            0 :       auto tensors = value.toTensorList();
     329            0 :       for (size_t i = 0; i < tensors.size(); ++i) {
     330            0 :         if (tensors.get(i).defined() &&
     331            0 :             tensors.get(i).scalar_type() == torch::kFloat32) {
     332            0 :           tensors.set(i, tensors.get(i).to(torch::kFloat64));
     333              :         }
     334              :       }
     335            0 :       model.setattr(attribute.name, tensors);
     336            0 :     }
     337        15561 :   }
     338         8227 :   for (const auto &method : model.get_methods()) {
     339         4978 :     torch::jit::Inline(*method.graph());
     340         9956 :     promote_float32_constants(method.graph()->block());
     341         3249 :   }
     342         9709 :   for (auto child : model.children()) {
     343         3230 :     promote_model_float32(child);
     344         6479 :   }
     345         3249 : }
     346              : 
     347            0 : static void initialize_cuda_linalg(const torch::Device &device) {
     348            0 :   static std::once_flag flag;
     349            0 :   std::call_once(flag, [&]() {
     350            0 :     const auto options =
     351            0 :         torch::TensorOptions().dtype(torch::kFloat32).device(device);
     352            0 :     static_cast<void>(at::linalg_eigh(torch::eye(1, options)));
     353            0 :   });
     354            0 : }
     355              : 
     356              : /*******************************************************************************
     357              :  * \brief Internal helper for creating a Torch tensor from an array.
     358              :  * \author Ole Schuett
     359              :  ******************************************************************************/
     360         2734 : static torch_c_tensor_t *tensor_from_array(const torch::Dtype dtype,
     361              :                                            const bool req_grad, const int ndims,
     362              :                                            const int64_t sizes[],
     363              :                                            void *source) {
     364         2734 :   initialize_torch_threads_from_env();
     365         2734 :   const auto opts = torch::TensorOptions().dtype(dtype).requires_grad(req_grad);
     366         2734 :   const auto sizes_ref = c10::IntArrayRef(sizes, ndims);
     367         2734 :   return new torch_c_tensor_t(torch::from_blob(source, sizes_ref, opts));
     368              : }
     369              : 
     370          318 : static bool tensor_matches(const torch_c_tensor_t *tensor,
     371              :                            const torch::Dtype dtype,
     372              :                            const torch::Device &device, const int ndims,
     373              :                            const int64_t sizes[]) {
     374          372 :   if (tensor == nullptr || !tensor->defined() ||
     375          690 :       tensor->scalar_type() != dtype || tensor->device() != device ||
     376          186 :       tensor->ndimension() != ndims) {
     377          132 :     return false;
     378              :   }
     379          620 :   for (int i = 0; i < ndims; i++) {
     380          434 :     if (tensor->size(i) != sizes[i]) {
     381              :       return false;
     382              :     }
     383              :   }
     384          186 :   return tensor->is_contiguous();
     385              : }
     386              : 
     387          318 : static bool reset_tensor_from_array_double(torch_c_tensor_t **tensor,
     388              :                                            const bool req_grad, const int ndims,
     389              :                                            const int64_t sizes[],
     390              :                                            double source[]) {
     391          318 :   c10::OptionalDeviceGuard guard;
     392          318 :   const auto device = get_device_with_guard(guard);
     393          318 :   const auto sizes_ref = c10::IntArrayRef(sizes, ndims);
     394          318 :   const bool reallocated =
     395          318 :       !tensor_matches(*tensor, torch::kFloat64, device, ndims, sizes);
     396          318 :   if (reallocated) {
     397          132 :     delete (*tensor);
     398          132 :     const auto opts =
     399          132 :         torch::TensorOptions().dtype(torch::kFloat64).device(device);
     400          264 :     *tensor = new torch_c_tensor_t(torch::empty(sizes_ref, opts).detach());
     401              :   }
     402          318 :   const auto source_tensor = torch::from_blob(
     403          318 :       source, sizes_ref, torch::TensorOptions().dtype(torch::kFloat64));
     404          318 :   {
     405          318 :     torch::NoGradGuard no_grad;
     406          318 :     (*tensor)->copy_(source_tensor);
     407          318 :     (*tensor)->mutable_grad() = torch::Tensor();
     408            0 :   }
     409          318 :   (*tensor)->set_requires_grad(req_grad);
     410          318 :   return reallocated;
     411          318 : }
     412              : 
     413              : /*******************************************************************************
     414              :  * \brief Internal helper for getting the data_ptr and sizes of a Torch tensor.
     415              :  * \author Ole Schuett
     416              :  ******************************************************************************/
     417         1354 : static void *get_data_ptr(const torch_c_tensor_t *tensor,
     418              :                           const torch::Dtype dtype, const int ndims,
     419              :                           int64_t sizes[]) {
     420         1354 :   cp_assert(tensor->scalar_type() == dtype);
     421         1354 :   cp_assert(tensor->ndimension() == ndims);
     422         4326 :   for (int i = 0; i < ndims; i++) {
     423         2972 :     sizes[i] = tensor->size(i);
     424              :   }
     425              : 
     426         1354 :   cp_assert(tensor->is_contiguous());
     427         1354 :   return tensor->data_ptr();
     428              : };
     429              : 
     430              : #ifdef __cplusplus
     431              : extern "C" {
     432              : #endif
     433              : 
     434              : /*******************************************************************************
     435              :  * \brief Creates a Torch tensor from an array of int32s.
     436              :  *        The passed array has to outlive the tensor!
     437              :  * \author Ole Schuett
     438              :  ******************************************************************************/
     439            0 : void torch_c_tensor_from_array_int32(torch_c_tensor_t **tensor,
     440              :                                      const bool req_grad, const int ndims,
     441              :                                      const int64_t sizes[], int32_t source[]) {
     442            0 :   *tensor = tensor_from_array(torch::kInt32, req_grad, ndims, sizes, source);
     443            0 : }
     444              : 
     445              : /*******************************************************************************
     446              :  * \brief Creates a Torch tensor from an array of floats.
     447              :  *        The passed array has to outlive the tensor!
     448              :  * \author Ole Schuett
     449              :  ******************************************************************************/
     450           66 : void torch_c_tensor_from_array_float(torch_c_tensor_t **tensor,
     451              :                                      const bool req_grad, const int ndims,
     452              :                                      const int64_t sizes[], float source[]) {
     453           66 :   *tensor = tensor_from_array(torch::kFloat32, req_grad, ndims, sizes, source);
     454           66 : }
     455              : 
     456              : /*******************************************************************************
     457              :  * \brief Creates a Torch tensor from an array of int64s.
     458              :  *        The passed array has to outlive the tensor!
     459              :  * \author Ole Schuett
     460              :  ******************************************************************************/
     461          786 : void torch_c_tensor_from_array_int64(torch_c_tensor_t **tensor,
     462              :                                      const bool req_grad, const int ndims,
     463              :                                      const int64_t sizes[], int64_t source[]) {
     464          786 :   *tensor = tensor_from_array(torch::kInt64, req_grad, ndims, sizes, source);
     465          786 : }
     466              : 
     467              : /*******************************************************************************
     468              :  * \brief Creates a Torch tensor from an array of doubles.
     469              :  *        The passed array has to outlive the tensor!
     470              :  * \author Ole Schuett
     471              :  ******************************************************************************/
     472         1882 : void torch_c_tensor_from_array_double(torch_c_tensor_t **tensor,
     473              :                                       const bool req_grad, const int ndims,
     474              :                                       const int64_t sizes[], double source[]) {
     475         1882 :   *tensor = tensor_from_array(torch::kFloat64, req_grad, ndims, sizes, source);
     476         1882 : }
     477              : 
     478              : /*******************************************************************************
     479              :  * \brief Releases a string returned from the Torch C API.
     480              :  ******************************************************************************/
     481           78 : void torch_c_free_string(char *content) { free(content); }
     482              : 
     483              : /*******************************************************************************
     484              :  * \brief Reuses or creates a device tensor and reports reallocation.
     485              :  ******************************************************************************/
     486          318 : bool torch_c_tensor_reset_from_array_double_status(torch_c_tensor_t **tensor,
     487              :                                                    const bool req_grad,
     488              :                                                    const int ndims,
     489              :                                                    const int64_t sizes[],
     490              :                                                    double source[]) {
     491          318 :   return reset_tensor_from_array_double(tensor, req_grad, ndims, sizes, source);
     492              : }
     493              : 
     494              : /*******************************************************************************
     495              :  * \brief Creates an expanded tensor view along one singleton dimension.
     496              :  ******************************************************************************/
     497          102 : void torch_c_tensor_expand_dim(const torch_c_tensor_t *tensor,
     498              :                                const int64_t dim, const int64_t size,
     499              :                                torch_c_tensor_t **result) {
     500          102 :   c10::OptionalDeviceGuard guard;
     501          102 :   get_device_with_guard(guard);
     502          102 :   cp_assert(*result == NULL);
     503          102 :   cp_assert(dim >= 0);
     504          102 :   cp_assert(dim < tensor->dim());
     505          102 :   std::vector<int64_t> sizes(tensor->sizes().begin(), tensor->sizes().end());
     506          102 :   cp_assert(sizes[dim] == 1);
     507          102 :   sizes[dim] = size;
     508          102 :   *result = new torch_c_tensor_t(tensor->expand(sizes));
     509          102 : }
     510              : 
     511              : /*******************************************************************************
     512              :  * \brief Creates a tensor view narrowed along one dimension.
     513              :  ******************************************************************************/
     514         1888 : void torch_c_tensor_narrow(const torch_c_tensor_t *tensor, const int64_t dim,
     515              :                            const int64_t start_index, const int64_t length,
     516              :                            torch_c_tensor_t **result) {
     517         1888 :   c10::OptionalDeviceGuard guard;
     518         1888 :   const auto device = get_device_with_guard(guard);
     519         1888 :   cp_assert(*result == NULL);
     520         1888 :   cp_assert(dim >= 0);
     521         1888 :   cp_assert(start_index >= 0);
     522         1888 :   cp_assert(length >= 0);
     523         1888 :   cp_assert(dim < tensor->ndimension());
     524         1888 :   cp_assert(start_index + length <= tensor->size(dim));
     525         3776 :   *result =
     526         1888 :       new torch_c_tensor_t(tensor->narrow(dim, start_index, length).to(device));
     527         1888 : }
     528              : 
     529              : /*******************************************************************************
     530              :  * \brief Returns the data_ptr and sizes of a Torch tensor of int32s.
     531              :  *        The returned pointer is only valide during the tensor's live time!
     532              :  * \author Ole Schuett
     533              :  ******************************************************************************/
     534            0 : void torch_c_tensor_data_ptr_int32(const torch_c_tensor_t *tensor,
     535              :                                    const int ndims, int64_t sizes[],
     536              :                                    int32_t **data_ptr) {
     537            0 :   *data_ptr = (int32_t *)get_data_ptr(tensor, torch::kInt32, ndims, sizes);
     538            0 : }
     539              : 
     540              : /*******************************************************************************
     541              :  * \brief Returns the data_ptr and sizes of a Torch tensor of floats.
     542              :  *        The returned pointer is only valide during the tensor's lifetime!
     543              :  * \author Ole Schuett
     544              :  ******************************************************************************/
     545           66 : void torch_c_tensor_data_ptr_float(const torch_c_tensor_t *tensor,
     546              :                                    const int ndims, int64_t sizes[],
     547              :                                    float **data_ptr) {
     548           66 :   *data_ptr = (float *)get_data_ptr(tensor, torch::kFloat32, ndims, sizes);
     549           66 : }
     550              : 
     551              : /*******************************************************************************
     552              :  * \brief Returns the data_ptr and sizes of a Torch tensor of int64s.
     553              :  *        The returned pointer is only valide during the tensor's live time!
     554              :  * \author Ole Schuett
     555              :  ******************************************************************************/
     556            0 : void torch_c_tensor_data_ptr_int64(const torch_c_tensor_t *tensor,
     557              :                                    const int ndims, int64_t sizes[],
     558              :                                    int64_t **data_ptr) {
     559            0 :   *data_ptr = (int64_t *)get_data_ptr(tensor, torch::kInt64, ndims, sizes);
     560            0 : }
     561              : 
     562              : /*******************************************************************************
     563              :  * \brief Returns the data_ptr and sizes of a Torch tensor of doubles.
     564              :  *        The returned pointer is only valide during the tensor's live time!
     565              :  * \author Ole Schuett
     566              :  ******************************************************************************/
     567         1288 : void torch_c_tensor_data_ptr_double(const torch_c_tensor_t *tensor,
     568              :                                     const int ndims, int64_t sizes[],
     569              :                                     double **data_ptr) {
     570         1288 :   *data_ptr = (double *)get_data_ptr(tensor, torch::kFloat64, ndims, sizes);
     571         1288 : }
     572              : 
     573              : /*******************************************************************************
     574              :  * \brief Runs autograd on a Torch tensor.
     575              :  * \author Ole Schuett
     576              :  ******************************************************************************/
     577            6 : void torch_c_tensor_backward(const torch_c_tensor_t *tensor,
     578              :                              const torch_c_tensor_t *outer_grad) {
     579            6 :   TorchFloatingPointMaskGuard fpe_guard;
     580            6 :   c10::OptionalDeviceGuard guard;
     581            6 :   get_device_with_guard(guard);
     582            6 :   tensor->backward(*outer_grad);
     583            6 : }
     584              : 
     585              : /*******************************************************************************
     586              :  * \brief Apply a scalar tensor's Hessian to directions of its independent
     587              :  * inputs.
     588              :  ******************************************************************************/
     589            2 : void torch_c_tensor_hessian_vector(const torch_c_tensor_t *tensor,
     590              :                                    const int count,
     591              :                                    const torch_c_tensor_t *const inputs[],
     592              :                                    const torch_c_tensor_t *const directions[],
     593              :                                    torch_c_tensor_t *responses[],
     594              :                                    const bool to_host, int *status) {
     595            2 :   *status = 0;
     596            8 :   for (int i = 0; i < count; i++)
     597            6 :     responses[i] = nullptr;
     598            2 :   try {
     599            2 :     TorchFloatingPointMaskGuard fpe_guard;
     600            2 :     c10::OptionalDeviceGuard guard;
     601            2 :     get_device_with_guard(guard);
     602            2 :     TORCH_CHECK(
     603              :         count > 0 && tensor->numel() == 1,
     604            2 :         "Hessian-vector evaluation requires a scalar and input tensors");
     605            2 :     std::vector<torch::Tensor> variables;
     606            2 :     std::vector<torch::Tensor> active_variables;
     607            2 :     std::vector<torch::Tensor> active_directions;
     608            8 :     for (int i = 0; i < count; i++) {
     609            6 :       TORCH_CHECK(inputs[i]->requires_grad() &&
     610              :                       inputs[i]->sizes() == directions[i]->sizes() &&
     611              :                       inputs[i]->device() == directions[i]->device(),
     612              :                   "Hessian-vector inputs and directions must have matching "
     613            6 :                   "shapes and devices");
     614            6 :       variables.push_back(*inputs[i]);
     615            6 :       if (directions[i]->count_nonzero().item<int64_t>() != 0) {
     616            6 :         active_variables.push_back(*inputs[i]);
     617            6 :         active_directions.push_back(directions[i]->detach());
     618              :       }
     619              :     }
     620            2 :     std::vector<torch::Tensor> first(active_variables.size());
     621            2 :     if (tensor->requires_grad() && !active_variables.empty()) {
     622            8 :       first = torch::autograd::grad({*tensor}, active_variables, {}, true, true,
     623            2 :                                     true);
     624              :     }
     625            2 :     torch::Tensor contraction;
     626            8 :     for (size_t i = 0; i < first.size(); i++) {
     627            6 :       if (first[i].defined() && first[i].requires_grad()) {
     628           12 :         auto term = (first[i] * active_directions[i]).sum();
     629            8 :         contraction = contraction.defined() ? contraction + term : term;
     630            6 :       }
     631              :     }
     632            2 :     std::vector<torch::Tensor> second(count);
     633            2 :     if (contraction.defined()) {
     634              :       // Retain all mixed responses, even for inputs with a zero direction.
     635            8 :       second = torch::autograd::grad({contraction}, variables, {}, false, false,
     636            2 :                                      true);
     637              :     }
     638            8 :     for (int i = 0; i < count; i++) {
     639            6 :       auto response = second[i].defined() ? second[i].detach()
     640            0 :                                           : torch::zeros_like(*inputs[i]);
     641           12 :       responses[i] = new torch_c_tensor_t(to_host ? response.cpu().contiguous()
     642           12 :                                                   : response);
     643            6 :     }
     644            2 :   } catch (const std::exception &error) {
     645            0 :     fprintf(stderr, "Torch Hessian evaluation failed: %s\n", error.what());
     646            0 :     for (int i = 0; i < count; i++) {
     647            0 :       delete responses[i];
     648            0 :       responses[i] = nullptr;
     649              :     }
     650            0 :     *status = 1;
     651            0 :   }
     652           10 : }
     653              : 
     654              : /*******************************************************************************
     655              :  * \brief Runs autograd on a scalar Torch tensor.
     656              :  ******************************************************************************/
     657          340 : void torch_c_tensor_backward_scalar(const torch_c_tensor_t *tensor) {
     658          340 :   TorchFloatingPointMaskGuard fpe_guard;
     659          340 :   c10::OptionalDeviceGuard guard;
     660          340 :   get_device_with_guard(guard);
     661          680 :   tensor->backward();
     662          340 : }
     663              : 
     664              : /*******************************************************************************
     665              :  * \brief Moves a tensor to the active device and makes it an autograd leaf.
     666              :  ******************************************************************************/
     667         2472 : void torch_c_tensor_to_device_leaf(torch_c_tensor_t **tensor,
     668              :                                    const bool req_grad) {
     669         2472 :   c10::OptionalDeviceGuard guard;
     670         2472 :   const auto device = get_device_with_guard(guard);
     671         4944 :   auto moved = (*tensor)->to(device).detach();
     672         2472 :   moved.set_requires_grad(req_grad);
     673         4944 :   delete (*tensor);
     674         4944 :   *tensor = new torch_c_tensor_t(moved);
     675         2472 : }
     676              : 
     677              : /*******************************************************************************
     678              :  * \brief Select whether Torch wrappers should use CUDA when available.
     679              :  ******************************************************************************/
     680          724 : void torch_c_use_cuda(const bool use_cuda) { use_cuda_if_available = use_cuda; }
     681              : 
     682              : /*******************************************************************************
     683              :  * \brief Returns whether Torch wrappers currently select CUDA when available.
     684              :  ******************************************************************************/
     685          360 : bool torch_c_get_use_cuda() { return use_cuda_if_available; }
     686              : 
     687              : /*******************************************************************************
     688              :  * \brief Returns the gradient of a Torch tensor which was computed by autograd.
     689              :  * \author Ole Schuett
     690              :  ******************************************************************************/
     691          256 : void torch_c_tensor_grad(const torch_c_tensor_t *tensor,
     692              :                          torch_c_tensor_t **grad) {
     693          256 :   c10::OptionalDeviceGuard guard;
     694          256 :   get_device_with_guard(guard);
     695          256 :   const torch::Tensor maybe_grad = tensor->grad();
     696          256 :   cp_assert(maybe_grad.defined());
     697          512 :   torch::Tensor host_grad = maybe_grad.detach().cpu().contiguous();
     698          256 :   if (maybe_grad.is_cpu()) {
     699          256 :     host_grad = host_grad.clone();
     700              :   }
     701          256 :   *grad = new torch_c_tensor_t(std::move(host_grad));
     702          256 : }
     703              : 
     704              : /*******************************************************************************
     705              :  * \brief Copies three autograd gradients to CPU memory.
     706              :  ******************************************************************************/
     707          338 : void torch_c_tensor_grad_batch3(const torch_c_tensor_t *tensor1,
     708              :                                 const torch_c_tensor_t *tensor2,
     709              :                                 const torch_c_tensor_t *tensor3,
     710              :                                 torch_c_tensor_t **grad1,
     711              :                                 torch_c_tensor_t **grad2,
     712              :                                 torch_c_tensor_t **grad3) {
     713          338 :   c10::OptionalDeviceGuard guard;
     714          338 :   const auto device = get_device_with_guard(guard);
     715          338 :   cp_assert(*grad1 == nullptr && *grad2 == nullptr && *grad3 == nullptr);
     716              : 
     717          338 :   const torch::Tensor source1 = tensor1->grad();
     718          338 :   const torch::Tensor source2 = tensor2->grad();
     719          338 :   const torch::Tensor source3 = tensor3->grad();
     720          338 :   cp_assert(source1.defined() && source2.defined() && source3.defined());
     721          338 :   cp_assert(source1.device() == source2.device());
     722          338 :   cp_assert(source1.device() == source3.device());
     723          338 :   if (use_batched_gradient_readback(source1)) {
     724            0 :     auto host1 =
     725              :         torch::empty(source1.sizes(),
     726            0 :                      source1.options().device(torch::kCPU).pinned_memory(true));
     727            0 :     auto host2 =
     728              :         torch::empty(source2.sizes(),
     729            0 :                      source2.options().device(torch::kCPU).pinned_memory(true));
     730            0 :     auto host3 =
     731              :         torch::empty(source3.sizes(),
     732            0 :                      source3.options().device(torch::kCPU).pinned_memory(true));
     733            0 :     host1.copy_(source1, true);
     734            0 :     host2.copy_(source2, true);
     735            0 :     host3.copy_(source3, true);
     736            0 :     torch::cuda::synchronize(device.index());
     737            0 :     *grad1 = new torch_c_tensor_t(std::move(host1));
     738            0 :     *grad2 = new torch_c_tensor_t(std::move(host2));
     739            0 :     *grad3 = new torch_c_tensor_t(std::move(host3));
     740            0 :   } else {
     741              :     // Materialize independent host buffers instead of aliasing gradients owned
     742              :     // by the autograd graph when they are already contiguous CPU tensors.
     743          338 :     *grad1 = new torch_c_tensor_t(source1.detach().cpu().contiguous().clone());
     744          338 :     *grad2 = new torch_c_tensor_t(source2.detach().cpu().contiguous().clone());
     745          338 :     *grad3 = new torch_c_tensor_t(source3.detach().cpu().contiguous().clone());
     746              :   }
     747          338 : }
     748              : 
     749              : /*******************************************************************************
     750              :  * \brief Releases a Torch tensor and all its ressources.
     751              :  * \author Ole Schuett
     752              :  ******************************************************************************/
     753        13784 : void torch_c_tensor_release(torch_c_tensor_t *tensor) { delete (tensor); }
     754              : 
     755              : /*******************************************************************************
     756              :  * \brief Creates an empty Torch dictionary.
     757              :  * \author Ole Schuett
     758              :  ******************************************************************************/
     759          416 : void torch_c_dict_create(torch_c_dict_t **dict_out) {
     760          416 :   cp_assert(*dict_out == NULL);
     761          416 :   *dict_out = new c10::Dict<std::string, torch::Tensor>();
     762          416 : }
     763              : 
     764              : /*******************************************************************************
     765              :  * \brief Clones a Torch dictionary.
     766              :  ******************************************************************************/
     767           38 : void torch_c_dict_clone(const torch_c_dict_t *dict, torch_c_dict_t **dict_out) {
     768           38 :   cp_assert(*dict_out == NULL);
     769           38 :   torch_c_dict_t *clone = new c10::Dict<std::string, torch::Tensor>();
     770          228 :   for (const auto &entry : *dict) {
     771          190 :     clone->insert(entry.key(), entry.value());
     772              :   }
     773           38 :   *dict_out = clone;
     774           38 : }
     775              : 
     776              : /*******************************************************************************
     777              :  * \brief Inserts a Torch tensor into a Torch dictionary.
     778              :  * \author Ole Schuett
     779              :  ******************************************************************************/
     780         2860 : void torch_c_dict_insert(const torch_c_dict_t *dict, const char *key,
     781              :                          const torch_c_tensor_t *tensor) {
     782         2860 :   c10::OptionalDeviceGuard guard;
     783         2860 :   const auto device = get_device_with_guard(guard);
     784         5720 :   dict->insert(key, tensor->to(device));
     785         2860 : }
     786              : 
     787              : /*******************************************************************************
     788              :  * \brief Retrieves a Torch tensor from a Torch dictionary.
     789              :  * \author Ole Schuett
     790              :  ******************************************************************************/
     791           76 : void torch_c_dict_get(const torch_c_dict_t *dict, const char *key,
     792              :                       torch_c_tensor_t **tensor) {
     793           76 :   cp_assert(dict->contains(key));
     794           76 :   *tensor = new torch_c_tensor_t(dict->at(key).cpu().contiguous());
     795           76 : }
     796              : 
     797              : /*******************************************************************************
     798              :  * \brief Releases a Torch dictionary and all its ressources.
     799              :  * \author Ole Schuett
     800              :  ******************************************************************************/
     801          908 : void torch_c_dict_release(torch_c_dict_t *dict) { delete (dict); }
     802              : 
     803              : /*******************************************************************************
     804              :  * \brief Loads a Torch model from given "*.pth" file.
     805              :  *        In Torch lingo models are called modules.
     806              :  * \author Ole Schuett
     807              :  ******************************************************************************/
     808           16 : void torch_c_model_load(torch_c_model_t **model_out, const char *filename) {
     809           16 :   cp_assert(*model_out == NULL);
     810           16 :   c10::OptionalDeviceGuard guard;
     811           16 :   const auto device = get_device_with_guard(guard);
     812           16 :   set_jit_fusion_strategy();
     813           16 :   torch::jit::Module *model = new torch::jit::Module();
     814           16 :   *model = load_module_for_device(filename, device);
     815           16 :   model->eval(); // Set inference behavior for modules such as dropout.
     816           16 :   *model_out = model;
     817           16 : }
     818              : 
     819              : /*******************************************************************************
     820              :  * \brief Loads a Torch model and reads two metadata entries.
     821              :  ******************************************************************************/
     822           19 : void torch_c_model_load_with_metadata(torch_c_model_t **model_out,
     823              :                                       const char *filename, const char *key1,
     824              :                                       const char *key2, char **content1,
     825              :                                       int *length1, char **content2,
     826              :                                       int *length2) {
     827           19 :   cp_assert(*model_out == NULL);
     828           19 :   c10::OptionalDeviceGuard guard;
     829           19 :   const auto device = get_device_with_guard(guard);
     830           19 :   std::unordered_map<std::string, std::string> extra_files = {{key1, ""},
     831           76 :                                                               {key2, ""}};
     832           19 :   set_jit_fusion_strategy();
     833           19 :   torch::jit::Module *model = new torch::jit::Module();
     834              :   // Deduplicate Skala constants on CPU without repeated CUDA synchronization.
     835           19 :   *model =
     836           19 :       load_module_for_device(filename, device, &extra_files, device.is_cuda());
     837           19 :   model->eval(); // Set inference behavior for modules such as dropout.
     838           19 :   *model_out = model;
     839           38 :   copy_string_to_c_buffer(extra_files[key1], content1, length1);
     840           38 :   copy_string_to_c_buffer(extra_files[key2], content2, length2);
     841           38 : }
     842              : 
     843              : /*******************************************************************************
     844              :  * \brief Maps serialized TorchScript device constants to the active device.
     845              :  ******************************************************************************/
     846           27 : void torch_c_model_remap_device_constants(torch_c_model_t *model) {
     847           27 :   c10::OptionalDeviceGuard guard;
     848           27 :   const auto device = get_device_with_guard(guard);
     849           27 :   if (device.is_cuda()) {
     850            0 :     remap_model_device_constants(*model, device);
     851            0 :     initialize_cuda_linalg(device);
     852              :   }
     853           27 : }
     854              : 
     855              : /*******************************************************************************
     856              :  * \brief Promote float32 model state and explicit numerical casts to float64.
     857              :  *        Trained values are retained exactly; integer/index operations are
     858              :  * kept.
     859              :  ******************************************************************************/
     860           19 : void torch_c_model_promote_float32(torch_c_model_t *model) {
     861           19 :   TorchFloatingPointMaskGuard fpe_guard;
     862           19 :   torch::NoGradGuard no_grad;
     863           19 :   promote_model_float32(*model);
     864           19 : }
     865              : 
     866              : /*******************************************************************************
     867              :  * \brief Prepare a model for higher input derivatives.
     868              :  ******************************************************************************/
     869            2 : void torch_c_model_prepare_higher_derivatives(torch_c_model_t *model) {
     870              :   // Preserve parameter values while avoiding fp32 cancellation and saturated
     871              :   // SiLU backward in higher input derivatives.
     872            2 :   torch_c_model_promote_float32(model);
     873            2 :   torch::jit::SubgraphRewriter rewriter;
     874            2 :   rewriter.RegisterRewritePattern(
     875            4 :       "graph(%x):\n %y = aten::silu(%x)\n return (%y)", R"IR(
     876              : graph(%x):
     877              :   %s = aten::sigmoid(%x)
     878              :   %y = aten::mul(%x, %s)
     879              :   return (%y))IR");
     880            2 :   std::unordered_set<torch::jit::Graph *> prepared;
     881          686 :   for (const auto &module : model->modules()) {
     882          866 :     for (const auto &method : module.get_methods()) {
     883          524 :       auto graph = method.graph();
     884          524 :       if (prepared.insert(graph.get()).second) {
     885         1048 :         rewriter.runOnGraph(graph);
     886              :       }
     887          866 :     }
     888          344 :   }
     889            4 : }
     890              : 
     891              : /*******************************************************************************
     892              :  * \brief Disables gradients for inference-only model parameters.
     893              :  ******************************************************************************/
     894           19 : void torch_c_model_disable_parameter_gradients(torch_c_model_t *model) {
     895           19 :   torch::NoGradGuard no_grad;
     896         1539 :   for (auto parameter : model->parameters()) {
     897         3040 :     parameter.set_requires_grad(false);
     898         1539 :   }
     899           19 : }
     900              : 
     901              : /*******************************************************************************
     902              :  * \brief Evaluates the given Torch model.
     903              :  * \author Ole Schuett
     904              :  ******************************************************************************/
     905           62 : void torch_c_model_forward(torch_c_model_t *model, const torch_c_dict_t *inputs,
     906              :                            torch_c_dict_t *outputs) {
     907              : 
     908           62 :   TorchFloatingPointMaskGuard fpe_guard;
     909           62 :   c10::OptionalDeviceGuard guard;
     910           62 :   get_device_with_guard(guard);
     911          310 :   auto untyped_output = model->forward({*inputs}).toGenericDict();
     912           62 :   outputs->clear();
     913          232 :   for (const auto &entry : untyped_output) {
     914          170 :     outputs->insert(entry.key().toStringView(), entry.value().toTensor());
     915              :   }
     916          186 : }
     917              : 
     918              : /*******************************************************************************
     919              :  * \brief Evaluates a TorchScript model method expecting argument "mol".
     920              :  ******************************************************************************/
     921          342 : void torch_c_model_forward_mol_tensor(torch_c_model_t *model,
     922              :                                       const char *method_name,
     923              :                                       const torch_c_dict_t *inputs,
     924              :                                       torch_c_tensor_t **output) {
     925              : 
     926          342 :   c10::OptionalDeviceGuard guard;
     927          342 :   const auto device = get_device_with_guard(guard);
     928              :   // Avoid repeated TorchScript profiling of the frozen Skala model on CUDA.
     929          342 :   std::optional<torch::jit::GraphOptimizerEnabledGuard> graph_optimization;
     930          342 :   if (device.is_cuda()) {
     931            0 :     graph_optimization.emplace(false);
     932              :   }
     933          342 :   cp_assert(*output == NULL);
     934          342 :   *output = new torch_c_tensor_t(
     935         1710 :       model->get_method(method_name)({*inputs}).toTensor());
     936         1026 : }
     937              : 
     938              : /*******************************************************************************
     939              :  * \brief Returns the weighted sum of two Torch tensors.
     940              :  ******************************************************************************/
     941          342 : void torch_c_tensor_weighted_sum(const torch_c_tensor_t *values,
     942              :                                  const torch_c_tensor_t *weights,
     943              :                                  torch_c_tensor_t **result) {
     944          342 :   c10::OptionalDeviceGuard guard;
     945          342 :   get_device_with_guard(guard);
     946          342 :   const auto weights_on_device = weights->to(values->device());
     947          684 :   *result = new torch_c_tensor_t((*values * weights_on_device).sum());
     948          342 : }
     949              : 
     950              : /*******************************************************************************
     951              :  * \brief Returns a scalar double value from a Torch tensor.
     952              :  ******************************************************************************/
     953          342 : double torch_c_tensor_item_double(const torch_c_tensor_t *tensor) {
     954          342 :   c10::OptionalDeviceGuard guard;
     955          342 :   get_device_with_guard(guard);
     956          342 :   return tensor->item<double>();
     957          342 : }
     958              : 
     959              : /*******************************************************************************
     960              :  * \brief Releases a Torch model and all its ressources.
     961              :  * \author Ole Schuett
     962              :  ******************************************************************************/
     963           35 : void torch_c_model_release(torch_c_model_t *model) { delete (model); }
     964              : 
     965              : /*******************************************************************************
     966              :  * \brief Reads metadata entry from given "*.pth" file.
     967              :  *        In Torch lingo they are called extra files.
     968              :  *        The returned char array has to be deallocated by caller!
     969              :  * \author Ole Schuett
     970              :  ******************************************************************************/
     971           40 : void torch_c_model_read_metadata(const char *filename, const char *key,
     972              :                                  char **content, int *length) {
     973              : 
     974          120 :   std::unordered_map<std::string, std::string> extra_files = {{key, ""}};
     975           40 :   torch::jit::load(filename, torch::kCPU, extra_files);
     976           80 :   const std::string &content_str = extra_files[key];
     977           40 :   copy_string_to_c_buffer(content_str, content, length);
     978           80 : }
     979              : 
     980              : /*******************************************************************************
     981              :  * \brief Returns true iff the Torch CUDA backend is available.
     982              :  * \author Ole Schuett
     983              :  ******************************************************************************/
     984            2 : bool torch_c_cuda_is_available() { return torch::cuda::is_available(); }
     985              : 
     986              : /*******************************************************************************
     987              :  * \brief Return the number of CUDA devices visible to Torch.
     988              :  ******************************************************************************/
     989            0 : int torch_c_cuda_device_count() {
     990            0 :   return torch::cuda::is_available() ? torch::cuda::device_count() : 0;
     991              : }
     992              : 
     993              : /*******************************************************************************
     994              :  * \brief Set whether to allow TF32.
     995              :  *        Needed due to changes in defaults from pytorch 1.7 to 1.11 to >=1.12
     996              :  *        See https://pytorch.org/docs/stable/notes/cuda.html
     997              :  * \author Gabriele Tocci
     998              :  ******************************************************************************/
     999            6 : void torch_c_allow_tf32(const bool allow_tf32) {
    1000              : 
    1001            6 :   at::globalContext().setAllowTF32CuBLAS(allow_tf32);
    1002            6 :   at::globalContext().setAllowTF32CuDNN(allow_tf32);
    1003            6 : }
    1004              : 
    1005              : /******************************************************************************
    1006              :  * \brief Freeze the Torch model: generic optimization that speeds up model.
    1007              :  *        See https://pytorch.org/docs/stable/generated/torch.jit.freeze.html
    1008              :  * \author Gabriele Tocci
    1009              :  ******************************************************************************/
    1010            6 : void torch_c_model_freeze(torch_c_model_t *model) {
    1011              : 
    1012            6 :   *model = torch::jit::freeze(*model);
    1013            6 : }
    1014              : 
    1015              : /******************************************************************************
    1016              :  * \brief Freeze a Torch model while preserving one exported method.
    1017              :  ******************************************************************************/
    1018           19 : void torch_c_model_freeze_preserving_method(torch_c_model_t *model,
    1019              :                                             const char *method_name) {
    1020              : 
    1021           38 :   const std::vector<std::string> preserved_methods = {method_name};
    1022           19 :   torch::jit::freeze_module_inplace(model, preserved_methods);
    1023           38 : }
    1024              : 
    1025              : /*******************************************************************************
    1026              :  * \brief Retrieves an int64 attribute. Must be called before model freeze.
    1027              :  * \author Ole Schuett
    1028              :  ******************************************************************************/
    1029           40 : void torch_c_model_get_attr_int64(const torch_c_model_t *model, const char *key,
    1030              :                                   int64_t *dest) {
    1031           40 :   *dest = model->attr(key).toInt();
    1032           40 : }
    1033              : 
    1034              : /*******************************************************************************
    1035              :  * \brief Retrieves a double attribute. Must be called before model freeze.
    1036              :  * \author Ole Schuett
    1037              :  ******************************************************************************/
    1038            8 : void torch_c_model_get_attr_double(const torch_c_model_t *model,
    1039              :                                    const char *key, double *dest) {
    1040            8 :   *dest = model->attr(key).toDouble();
    1041            8 : }
    1042              : 
    1043              : /*******************************************************************************
    1044              :  * \brief Retrieves a string attribute. Must be called before model freeze.
    1045              :  * \author Ole Schuett
    1046              :  ******************************************************************************/
    1047           16 : void torch_c_model_get_attr_string(const torch_c_model_t *model,
    1048              :                                    const char *key, char *dest) {
    1049           16 :   const std::string &str = model->attr(key).toStringRef();
    1050           16 :   cp_assert(str.size() < 80); // default_string_length
    1051          144 :   for (int i = 0; i < str.size(); i++) {
    1052          128 :     dest[i] = str[i];
    1053              :   }
    1054           16 : }
    1055              : 
    1056              : /*******************************************************************************
    1057              :  * \brief Retrieves a list attribute's size. Must be called before model freeze.
    1058              :  * \author Ole Schuett
    1059              :  ******************************************************************************/
    1060            8 : void torch_c_model_get_attr_list_size(const torch_c_model_t *model,
    1061              :                                       const char *key, int *size) {
    1062            8 :   *size = model->attr(key).toList().size();
    1063            8 : }
    1064              : 
    1065              : /*******************************************************************************
    1066              :  * \brief Retrieves a single item from a string list attribute.
    1067              :  * \author Ole Schuett
    1068              :  ******************************************************************************/
    1069           16 : void torch_c_model_get_attr_strlist(const torch_c_model_t *model,
    1070              :                                     const char *key, const int index,
    1071              :                                     char *dest) {
    1072           32 :   const auto list = model->attr(key).toList();
    1073           16 :   const std::string &str = list[index].toStringRef();
    1074           16 :   cp_assert(str.size() < 80); // default_string_length
    1075           32 :   for (int i = 0; i < str.size(); i++) {
    1076           16 :     dest[i] = str[i];
    1077              :   }
    1078           16 : }
    1079              : 
    1080              : #ifdef __cplusplus
    1081              : }
    1082              : #endif
    1083              : 
    1084              : #endif // defined(__LIBTORCH)
    1085              : 
    1086              : // EOF
        

Generated by: LCOV version 2.0-1