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

时间:2019-08-01 09:57:32

标签: c++ libtorch

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

这是代码:

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 个答案:

答案 0 :(得分:0)

1)torch::jit::load的返回类型为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代码)。否则,前进方法应该可用。