Ubuntu20.04+vscode的libtorch环境配置(跑起来测试demo)
初学,网上资料五花八门,又多又乱,查了很久资料才跑通,记录一下防止自己老年痴呆…
1.在pytorch官网找到libtorch,下载压缩文件,解压获得源码
2.使用pytorch训练模型(前面可以都不看,就看模型怎么保存的)
if __name__ == '__main__':
# 训练好的模型
model = torch.load('model/best_model.pth')
# 必须使用torch.jit.trace来处理模型,第一个参数就是训练好的模型,第二个参数是规定的输入维度!!这里将会对cpp中的输入维度有所限制
traced_script_module = torch.jit.trace(model, torch.rand(1, 10, 1))
traced_script_module.save('model/best_model.pt')
# print(model)
test()
3.准备好自己用pytorch训练好的模型,设置预先规定好的输入维度信息
#include <torch/script.h> // One-stop header.
#include <iostream>
#include <memory>
int main() {
// Deserialize the ScriptModule from a file using torch::jit::load().
//std::shared_ptr<torch::jit::script::Module> module =
// torch::jit::load("E:/HM_DL/torch_test/traced_resnet_model.pt");
using torch::jit::script::Module;
Module module =
torch::jit::load("/home/coshe/PycharmProjects/LSTM_Test/model/best_model.pt");
std::cout << "ok\n";
// Create a vector of inputs.
std::vector<torch::jit::IValue> inputs;
//在这里构造输入的维度,例如这里之前有规定输入维度为[1, 10, 1]
inputs.push_back(torch::rand({1, 10, 1}));
// Execute the model and turn its output into a tensor.
std::cout << "inputs: " << std::endl;
std::cout << inputs << std::endl;
at::Tensor output = module.forward(inputs).toTensor();
std::cout << output << '\n';
// while (1)
// ;
}
如果有强迫症(比如我)受不了头文件<torch/script.h>
爆红,可以在vscode的c_cpp_properties.json
中手动写入头文件路径,什么?你找不到?快捷键Ctrl+
p,然后输入一个’>’,回车就是了,然后配置如下
{
"configurations": [
{
"name": "Linux",
"includePath": [
"${workspaceFolder}/**",
"/home/coshe/下载/libtorch/include"
],
"defines": [],
"compilerPath": "/usr/bin/clang",
"cStandard": "c11",
"cppStandard": "c++14",
"intelliSenseMode": "linux-clang-x64"
}
],
"version": 4
}
就把"includePath里面加一个libtorch的include路径就ok了"
4.CMakeLists.txt的编写
cmake_minimum_required(VERSION 3.0 FATAL_ERROR)
project(example)
# 改成自己的相应的目录
set(Torch_DIR /home/coshe/下载/libtorch/share/cmake/Torch)
find_package(Torch REQUIRED)
# message(STATUS "Pytorch status:")
# message(STATUS " libraries: ${TORCH_LIBRARIES}")
# message(STATUS "OpenCV library status:")
add_executable(example example-app.cpp)
target_link_libraries(example ${TORCH_LIBRARIES})
set_property(TARGET example PROPERTY CXX_STANDARD 14)
然后就是
# 编译
mkdir build && cd ./build
cmake ..
make -j8
# 运行
./example
发现成功了,输出如下:
coshe@coshe-pc:~/文档/torch-cpp/libtorch_test/build$ ./example
ok
inputs:
(1,.,.) =
0.4012
0.3990
0.4569
0.0698
0.1218
0.2944
0.6884
0.9574
0.9151
0.4877
[ CPUFloatType{1,10,1} ]
0.9934
[ CPUFloatType{1,1} ]