Correct way to save a sub-struct of torch::nn::Module in LibTorch

I am trying to figure what the proper way to save a substruct of torch::nn::Module.

The following snippet:

#include <torch/torch.h>
#include <iostream>

using namespace std;

struct example_module:torch::nn::Module {
	example_module() {
		first_l = register_module("conv1", torch::nn::Conv2d(3, 3, 1));
	}
	torch::nn::Conv2d first_l = nullptr;
};

int main() {
	string save_fp = "/localmodel";
	example_module model = example_module();
	torch::save(model, save_fp);
}

Gives me a compilation error:

1>C:\Libtorch\libtorch-win-shared-with-deps-debug-1.10.2+cu113\libtorch\include\torch\csrc\api\include\torch/serialize.h(44,1): error C2679: binary ‘<<’: no operator found which takes a right-hand operand of type ‘const Value’ (or there is no acceptable conversion)
1> with
1> [
1> Value=example_module
1> ]
1>C:\Libtorch\libtorch-win-shared-with-deps-debug-1.10.2+cu113\libtorch\include\torch\csrc\api\include\torch/serialize/tensor.h(7,34): message : could be ‘torch::serialize::OutputArchive &torch::operator <<(torch::serialize::OutputArchive &,const at::Tensor &)’
1>C:\Libtorch\libtorch-win-shared-with-deps-debug-1.10.2+cu113\libtorch\include\c10/util/logging_is_not_google_glog.h(232,22): message : or ‘std::ostream &std::operator <<(std::ostream &,const std::nullptr_t &)’ [found using argument-dependent lookup]
1>C:\Libtorch\libtorch-win-shared-with-deps-debug-1.10.2+cu113\libtorch\include\torch\csrc\api\include\torch/nn/module.h(556,34): message : or ‘std::ostream &torch::nn::operator <<(std::ostream &,const torch::nn::Module &)’ [found using argument-dependent lookup]
1>C:\Libtorch\libtorch-win-shared-with-deps-debug-1.10.2+cu113\libtorch\include\torch\csrc\api\include\torch/nn/module.h(605,37): message : or ‘torch::serialize::OutputArchive &torch::nn::operator <<(torch::serialize::OutputArchive &,const std::shared_ptrtorch::nn::Module &)’ [found using argument-dependent lookup]
1>C:\Libtorch\libtorch-win-shared-with-deps-debug-1.10.2+cu113\libtorch\include\torch\csrc\api\include\torch/serialize.h(44,1): message : while trying to match the argument list ‘(torch::serialize::OutputArchive, const Value)’
1> with
1> [
1> Value=example_module
1> ]
1>sample_module.cpp(16): message : see reference to function template instantiation ‘void torch::save<example_module,std::string&>(const Value &,std::string &)’ being compiled
1> with
1> [
1> Value=example_module
1> ]
1>Done building project “TorchProjectExample.vcxproj” – FAILED.
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

What am I doing wrong?

1 Like

please try

//wrong
struct example_module:torch::nn::Module

//right
struct example_module:public torch::nn::Module