(libtorch) How to save model in MNIST cpp example?


(Heng Ding) #1

I’m running mnist example and try to save trained model to disk:

torch::save(model, "model.pt")   # save model using torch::save

Then got error as:

In file included from /home/christding/env/libtorch/include/torch/csrc/api/include/torch/all.h:8:0,
                 from /home/christding/env/libtorch/include/torch/csrc/api/include/torch/torch.h:3,
                 from /home/christding/Desktop/workspace/TorchLearning/C++/mnist-custom/src/mnist.cpp:1:
/home/christding/env/libtorch/include/torch/csrc/api/include/torch/serialize.h: In instantiation of ‘void torch::save(const Value&, SaveToArgs&& ...) [with Value = Net; SaveToArgs = {const char (&)[9]}]’:
/home/christding/Desktop/workspace/TorchLearning/C++/mnist-custom/src/mnist.cpp:171:32:   required from here
/home/christding/env/libtorch/include/torch/csrc/api/include/torch/serialize.h:39:11: error: no match for ‘operator<<’ (operand types are ‘torch::serialize::OutputArchive’ and ‘const Net’)
   archive << value;
   ~~~~~~~~^~~~~~~~
... 
...

make[2]: *** [CMakeFiles/mnist.dir/src/mnist.cpp.o] Error 1
make[1]: *** [CMakeFiles/mnist.dir/all] Error 2
make: *** [all] Error 2

Does anyone know how to serialize the trained model?


(Heng Ding) #2

Solved by myself. To save the trained model, we need to create a torch::serialize::OutputArchive object like follows:

string model_path = "model.pt";
serialize::OutputArchive output_archive;
model.save(output_archive);
output_archive.save_to(model_path);

(Carsten Ditzel) #3

that seems like an overcomplicated way oO