在 libtorch 中使用 forward 的非法指令(核心转储)

Illegal instruction (core dumped) using forward in libtorch

我正在尝试使用 libtorch 将 Python 中的模型加载到 C++ 中并加以使用。该程序编译正确,但我在输入上使用转发得到非法指令(核心转储)。

这是代码:

void test(vector<module_type>& model){
    //pseudo input
    vector<torch::jit::IValue> inputs;
    inputs.push_back(torch::ones({1, 3, 224, 224}));
    //ERROR IS HERE
    at::Tensor output = model[0].forward(inputs).toTensor();
    cout << output << endl;
}

int main(int argc, char *argv[]) {

    if (argc == 2){
        cout << argv[1] << endl;
    }
    else {
        cerr << "no path of model is given" << endl;
        return -1;
    }
    // test
    module_type module = torch::jit::load(argv[1]);
    vector<module_type> modul;
    modul.push_back(module);
    test(modul);

}

CMake:

cmake_minimum_required(VERSION 3.0 FATAL_ERROR)
project(main)

find_package(Torch REQUIRED)

add_executable(main main.cpp)
target_link_libraries(main "${TORCH_LIBRARIES}")
set_property(TARGET main PROPERTY CXX_STANDARD 11)

1) torch::jit::load return 类型是 std::shared_ptr<torch::jit::script::Module>,所以你的代码应该是 at::Tensor output = model[0]->forward(inputs).toTensor();

2) 可能由于某种原因,您的 Python 模型导出失败,但如果没有看到您使用的实际 python 代码,很难判断。要查看有多少方法可用,请尝试:

auto module = torch::jit::load(argv[1]);
size_t number_of_methods = module->get_methods().size();

基本上,如果 number_of_methods 为 0,您就会遇到问题:序列化对象不包含任何方法(问题来自您的 python 代码)。否则,forward方法应该可用。