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

标签 c++ 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返回类型是 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 方法应该可用。

关于c++ - 在 libtorch 中使用 forward 的非法指令(核心转储),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57306441/

相关文章:

c++ - c++语言/getdate()中如何定义一个表示时间值的值?

c++ - 如何将着色器应用于特定对象

c++ - 在c中访问越界数组

c++ - Pytorch/ATen C++ 中切片张量的等价

pytorch - 运行 TRTorch 示例时为 "error while loading shared libraries: libnvinfer.so.7: cannot open shared object file: No such file or directory"

python - 如何将 PyTorch 张量转换为 C++ torch::Tensor,反之亦然?

c++ - 串口未读取完整传输

c++ - 从 C 程序调用 C++ DLL 时,当我尝试访问 DLL 中的调用参数指针时它崩溃了

opencv - LibTorch C++和Eigen之间的数据传输

c++ - libtorch (PyTorch C++) 奇怪的类语法