Hi, I was trying to explore how to train the mnist model in C++, save the model, and having another C++ to load the file and use it as inference system.
I tried the methods in (libtorch) How to save model in MNIST cpp example?,
- Using original mnist.cpp, add 3 lines of codes to save the model:
torch::serialize::OutputArchive output_archive; model.save(output_archive); output_archive.save_to("model.pt");
- Change the Net by NetImpl as suggested, and save the mode with:
with both, I am able to compile and run the code and save the model, however, when I am trying to load the model from another C++ file, I get the error of “‘ScriptModule’ object has no attribute ‘forward’”
To simplified the testing, I tried to load the model in Python:
- Load with torch.load
import torch # load by torch.load model = torch.load('model.pt') ## Error loading ## RuntimeError: model_impl.pt is a zip archive (did you mean to use torch.jit.load()?)
- Load by torch.jit.load
# Loaded successfully, but... model = torch.jit.load('model.pt') model.eval() # Python output ScriptModule( (conv1): ScriptModule() (conv2): ScriptModule() (conv2_drop): ScriptModule() (fc1): ScriptModule() (fc2): ScriptModule() ) # When try to have a forward pass, I get the following error. output = model(torch.ones(1, 1, 28, 28)) ## Error : AttributeError: 'ScriptModule' object has no attribute 'forward'
Apologize if I’ve miss anything else.