13#include <ATen/ops/ones_like.h>
16#include "neml2/misc/assertions.h"
28 auto options = Model::expected_options();
29 options.add<std::vector<VariableName>>(
"inputs",
"The input variables for the neural network");
30 options.add<std::vector<VariableName>>(
"outputs",
31 "The (scaled) output variables for the neural network");
32 options.add<std::string>(
"file_path",
"The path to the neural network file");
34 options.set<
bool>(
"jit",
false);
35 options.suppress(
"jit");
41 _file_path(
Moose::DataFileUtils::getPath(options.get<
std::string>(
"file_path"))),
42 _surrogate(
std::make_unique<torch::jit::script::Module>(torch::jit::load(_file_path.path)))
45 for (
const auto & fv : options.get<std::vector<VariableName>>(
"inputs"))
46 _inputs.push_back(&declare_input_variable<Scalar>(fv));
47 for (
const auto & fv : options.get<std::vector<VariableName>>(
"outputs"))
48 _outputs.push_back(&declare_output_variable<Scalar>(fv));
56 if (options.has_device())
59 if (options.has_dtype())
60 _surrogate->to(torch::Dtype(caffe2::typeMetaToScalarType(options.dtype())));
66 std::vector<const VariableBase *> inputs;
67 for (
size_t i = 0; i <
_inputs.size(); ++i)
70 for (
size_t i = 0; i <
_outputs.size(); ++i)
79 std::vector<at::Tensor>
values;
80 auto first_batch_dim =
_inputs[0]->batch_dim();
81 for (
size_t i = 0; i <
_inputs.size(); ++i)
84 neml_assert(
_inputs[i]->batch_dim() == first_batch_dim);
88 auto x = Tensor(torch::transpose(torch::vstack(at::ArrayRef<at::Tensor>(
95 auto temp =
_surrogate->forward({x}).toTensor().squeeze();
97 (temp.dim() == 1) ? temp.view({temp.size(0), 1}).transpose(0, 1) : temp.transpose(0, 1);
99 for (
size_t i = 0; i <
_outputs.size(); ++i)
std::array< Real, 2 > values
Evaluate a pretrained libtorch model in .pt format, such as a neural network.
LibtorchModel(const OptionSet &options)
virtual void request_AD() override
virtual void to(const torch::TensorOptions &options) override
Override the base implementation to additionally send the model loaded from torch script to different...
std::vector< const Variable< Scalar > * > _inputs
std::unique_ptr< torch::jit::script::Module > _surrogate
We need to use a pointer here because forward is not const qualified.
virtual void set_value(bool out, bool dout_din, bool d2out_din2) override
static OptionSet expected_options()
std::vector< Variable< Scalar > * > _outputs
MOOSE now contains C++17 code, so give a reasonable error message stating what the user can do to add...
register_NEML2_object(LibtorchModel)