Trace modules in C++ not in pytorch

hi, I want to train/test and generate jit::script structure totally in C++ code.
simply, I want to trace modules implemented in totally libtorch C++.
Always torch provides save script in python and load script in C++. But, I want to use script in C++ directly from modules same namespace C++. is it possible?

I declared a class for all definitions of Network, and composed a register module and each forward function. Both training and testing work fine.
I would like to convert it into a script form made directly from this class Model, not a .pt file made from Pytorch.
In Python, I can pass the network through the trace function to figure out the structure, but libtorch c++ doesnā€™t seem to provide such a function.

The Model class I use can be accessed through a function like Model->named_modules().
However, I couldnā€™t find a function like ā€˜trace functionā€™ or a way to convert it to torch::jit:script:Module form.

Any example code that might help?

You can do it with torch::jit::tracer::trace.
I donā€™t have a clean example but hereā€™s an overview of what we do in the R bindings:

Stack inputs_ = *reinterpret_cast<Stack*>(inputs);
auto module_ = reinterpret_cast<torch::jit::script::Module*>(module);
auto name_ = from_raw::string(name);

std::function<std::string(const torch::autograd::Variable&)> var_fn =
      [](const torch::autograd::Variable& x) { return ""; };

  auto traced =
      torch::jit::tracer::trace(inputs_, fn_, var_fn, strict, false, module_);
1 Like

Could you give an example in more detail? Iā€™m facing the same problem and canā€™t get it to work.

On what header file is torch::jit::tracer::trace located?

These are the relevant imports:

1 Like