参考博客:
https://towardsdatascience.com/setting-up-a-c-project-in-visual-studio-2019-with-libtorch-1-6-ad8a0e49e82c
Libtorch + vs 2019安装及配置
libtorch 1.6下载链接
Windows CPU Only C++ Release Version
启动一个C++空项目
选择x64,release
项目配置
- 项目右键选择并打开属性
- 添加包含目录
D:\libtorch\libtorch\include
D:\libtorch\libtorch\include\torch\csrc\api\include
目录的地址按照自己的libtorch解压地址修改
- 语言设置
设置为否
- 附加库目录
D:\libtorch\libtorch\lib
-
指定额外的依赖项
- CPU Version: torch_cpu.lib, c10.lib, torch.lib
- GPU Version: torch.lib, torch_cuda.lib, caffe2_nvrtc.lib, c10.lib, c10_cuda.lib, torch_cpu.lib, -INCLUDE:?warp_size@cuda@at@@YAHXZ (https://github.com/pytorch/pytorch/issues/31611#issuecomment-594383154)
- 将lib里面所有的dll文件复制到exe目录
dll目录:
D:\libtorch\libtorch\lib
目标目录(项目编译的目录,其中包含exe文件):
D:\CPPV2\Project1\x64\Release
- 添加测试文件
#include <torch/torch.h>
#include <iostream>
int main() {
torch::Tensor tensor = torch::eye(3);
std::cout << tensor << std::endl;
}
- ctrl+F5运行代码
将pytorch模型转换为TorchScript
注意torch.jit.trace操作要在cpu上进行,即模型在cpu上训练
cd到Project.exe文件,把pt后缀的模型拷贝到这个文件夹
运行需要exe文件和.pt文件,命令行执行:
Project1.exe grownet.pt 1 1 1 1 1 1 1 1 1 0 0 1 1