1、头文件包含问题
前面练习libtorch调用时除了包含路径和库文件外,在源文件中一般包含头文件:
#include <torch/script.h>
然后在调用下面一行代码时总是提示函数未定义或者不存在,后来才知道少包含了一个头文件。
torch::cuda::is_avaliable();
使用上面这一句时需要包含头文件:
#include <torch/torch.h>
于是下面这些函数都可以找到了。
void test_libtorch_version() {
std::cout << "cuDNN : " << torch::cuda::cudnn_is_available() << std::endl;
std::cout << "CUDA : " << torch::cuda::is_available() << std::endl;
std::cout << "Device count : " << torch::cuda::device_count() << std::endl;
}
2、属性设置问题(GPU)
在封装c++ 接口或者测试程序时,这样写编译不会报错,执行时会在加载模型时报错,。
torch::DeviceType device_type;
device_type = torch::kCUDA;
torch::Device device(device_type);
torch::jit::script::Module module = torch::jit::load(model_path, device);//
解决办法:参考:libtorch1.6 GPU版本无法使用的问题
我是用的是libtorch1.5.1,该方法同样适用。
下面是解决办法原文:
在官网中下载libtorch1.6 GPU版本,如果在VS中只添加inclue和lib的路径,编译的过程或编译好执行的过程很有可能出现错误。当然,如果是使用cmake来构建工程,是可以正常编译和执行。
出现错误的解决方法:
1)使用VS2017及以上版本;
2)windows上装的cuda版本需要与下载的libtorch的cuda版本相对应;
3)在“属性 --> 链接器 --> 命令行 --> 其他选项”中添加:
/INCLUDE:?warp_size@cuda@at@@YAHXZ
3、GPU/CPU模型
加载CPU模型使用下面的代码,模型是同一个,只是加载时的参数不同
torch::DeviceType device_type;
device_type = torch::kCPU;
torch::Device device(device_type);
torch::jit::script::Module module = torch::jit::load(model_path, device);//
加载GPU模型
torch::DeviceType device_type;
device_type = torch::kCUDA;
torch::Device device(device_type);
torch::jit::script::Module module = torch::jit::load(model_path, device);//