VS配置LibTorch环境并调用CUDA运行torchscript模型


本文环境: win10 + vs2019 + opencv 4
最新环境:LibTorch:libtorch-win-shared-with-deps-1.6.0+cu101


导出 TorchScript 模型

有两种方式,可以自己试一下,而且很多开源模型已经提供了转换脚本,可以参考

  • torch.jit.trace
  • torch.jit.script

还是很简单的:

    # Input
    img = torch.zeros((batch_size, 3, img_size[0], img_size[1])) 
    # Load PyTorch model
    model = torch.load("module.pt", map_location=torch.device('cpu'))['model'].float()
    model.eval()
    model.model[-1].export = True  # set Detect() layer export=True
    y = model(img)  
    # TorchScript export
    try:
        print('\nStarting TorchScript export with torch %s...' % torch.__version__)
        ts = torch.jit.trace(model, img)
        ts.save("module.torchscript")
        print('TorchScript export success, saved as %s' % f)
    except Exception as e:
        print('TorchScript export failure: %s' % e)

环境配置

配置OpenCV属性表

添加目录:
在这里插入图片描述
链接器中加入:
在这里插入图片描述

配置LibTorch属性表

下载release版本 850.25M:官网 。配置LibTorch,和OpenCV一个套路,属性表 我上传了

我下载了一夜,分享出来方便大家 -.-
最新版本 1.5.1 2020/07
天翼网盘:libtorch-win-shared-with-deps-1.5.1.zip (访问码:4sns)

添加【两个】包含目录:
在这里插入图片描述

库目录还是lib
在这里插入图片描述

在输入链接器的时候,由于lib文件比较多,可以通过脚本命令快速得到文件名,然后复制进去就可以了,非常好用。

dir /b *.lib > a.txt

也可以直接复制?

asmjit.lib
c10.lib
c10_cuda.lib
caffe2_detectron_ops_gpu.lib
caffe2_module_test_dynamic.lib
caffe2_nvrtc.lib
clog.lib
cpuinfo.lib
dnnl.lib
fbgemm.lib
libprotobuf-lite.lib
libprotobuf.lib
libprotoc.lib
mkldnn.lib
torch.lib
torch_cpu.lib
torch_cuda.lib

添加环境变量

在这里插入图片描述

示例代码

网上很多代码是测试版本的,接口已经改了。这里是最新的 2020/07

#include "opencv2/opencv.hpp"
#include "torch/script.h"

using namespace std;

torch::jit::script::Module load_model(string model_path)
{
    torch::jit::script::Module module;
    try {
        module = torch::jit::load(model_path);
    }
    catch (const c10::Error & e) {
        std::cerr << "error loading the model\n";
        exit(-1);
    }
    std::cout << "ok\n";
    return module;
}

int main() {
    // 加载模型
    auto module = load_model("modules/yolov5s_dmf.torchscript");

    // 读入图像
    cv::Mat img = cv::imread("test.jpg");
    assert(not img.empty());

    // 转换数据格式
    cv::cvtColor(img, img, cv::COLOR_BGR2RGB);
    cv::Mat img_float;
    img.convertTo(img_float, CV_32F, 1.0 / 255);
    cv::resize(img_float, img_float, cv::Size(640, 640));
    auto img_tensor = torch::from_blob(img_float.data, { 1, 3, 640, 640 }, torch::kFloat32);
    std::vector<torch::jit::IValue> inputs;
    inputs.emplace_back(img_tensor);
    //inputs.push_back(torch::ones({ 1, 3, 448, 640 }));

    // 预测
    at::Tensor output = module.forward(inputs).toTensor();
    std::cout << output.slice(/*dim=*/1, /*start=*/0, /*end=*/5) << '\n';

    return 0;
}

添加CUDA支持

经过上述配置,其实运行的还是cpu环境,是调不起来CUDA的。可以自行测试:

torch::DeviceType device_type;
if (torch::cuda::is_available()) {
    device_type = torch::kCUDA;
    cout << "enable CUDA ...";
} else {
    device_type = torch::kCPU;
}
device = torch::Device(device_type);
this->model.to(device);
this->model.eval();
std::cout << "done.\n";

需要新加命令行/INCLUDE:?warp_size@cuda@at@@YAHXZ,目前版本 libtorch-win-shared-with-deps-1.6.0+cu101,亲测可用。
在这里插入图片描述

总结和参考

网上的许多文章已经过期,LibTorch已经发布了稳定的1.6+版本,还是建议参看英文的官方教程。

  • 2
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
注:本文将以 YOLOv5 为例,介绍如何使用 LibTorchTorch TensorRT 对 TorchScript 模型进行加速推理。本文默认读者已经熟悉 YOLOv5 和 TorchScript 的相关知识。 1. 准备工作 在开始之前,需要先安装以下工具: - PyTorch - LibTorch - Torch TensorRT 其中,PyTorch 是用于训练 YOLOv5 模型的框架,而 LibTorchTorch TensorRT 则是用于加速推理的工具。在安装完这些工具之后,需要将训练好的 YOLOv5 模型转换为 TorchScript 格式。 2. 将 YOLOv5 模型转换为 TorchScript 格式 将训练好的 YOLOv5 模型转换为 TorchScript 格式的方法有很多种,这里给出一种比较简单的方法: ```python import torch from models.experimental import attempt_load from utils.general import set_logging from torch.utils.mobile_optimizer import optimize_for_mobile def export_torchscript(weights, img_size, device='cpu'): set_logging() model = attempt_load(weights, map_location=device) img = torch.zeros((1, 3, img_size, img_size), device=device) model.eval() traced_script_module = torch.jit.trace(model, img) traced_script_module_optimized = optimize_for_mobile(traced_script_module) traced_script_module_optimized.save("yolov5s.torchscript.pt") export_torchscript(weights='yolov5s.pt', img_size=640, device='cpu') ``` 在这个函数中,我们首先加载训练好的 YOLOv5 模型,然后使用 torch.jit.trace 将模型转换为 TorchScript 格式。接着,我们使用 torch.utils.mobile_optimizer.optimize_for_mobile 对模型进行优化,最后将优化后的模型保存到磁盘上。 3. 加载 TorchScript 模型C++ 中加载 TorchScript 模型需要使用 LibTorch,下面是加载模型的代码: ```cpp #include <torch/script.h> // One-stop header. int main(int argc, const char* argv[]) { // Load the model. torch::jit::script::Module module; try { // Deserialize the ScriptModule from a file using torch::jit::load(). module = torch::jit::load("yolov5s.torchscript.pt"); } catch (const c10::Error& e) { std::cerr << "error loading the model\n"; return -1; } return 0; } ``` 在这个代码中,我们使用 torch::jit::load 函数加载 TorchScript 模型。如果加载失败,将输出错误信息并返回 -1,否则返回 0。 4. 使用 Torch TensorRT 进行推理 为了加速 TorchScript 模型的推理,我们可以使用 Torch TensorRT。下面是使用 Torch TensorRT 进行推理的代码: ```cpp #include <torch/script.h> // One-stop header. #include <iostream> #include <memory> #include <vector> #include <chrono> #include <NvInferRuntime.h> int main(int argc, const char* argv[]) { // Load the model. torch::jit::script::Module module; try { // Deserialize the ScriptModule from a file using torch::jit::load(). module = torch::jit::load("yolov5s.torchscript.pt"); } catch (const c10::Error& e) { std::cerr << "error loading the model\n"; return -1; } // Create a TensorRT engine from the TorchScript module. nvinfer1::IRuntime* runtime = nvinfer1::createInferRuntime(gLogger); nvinfer1::ICudaEngine* engine = createCudaEngine(module, runtime, batchSize, kINPUT_BLOB_NAME, kOUTPUT_BLOB_NAME, maxWorkspaceSize); if (!engine) { std::cerr << "error creating the engine\n"; return -1; } // Create a TensorRT execution context. nvinfer1::IExecutionContext* context = engine->createExecutionContext(); if (!context) { std::cerr << "error creating the context\n"; return -1; } // Prepare inputs and outputs. std::vector<float> inputData(batchSize * inputSize * inputSize * 3); std::vector<float> outputData(batchSize * outputSize * outputSize * (5 + numClasses)); void* buffers[] = {inputData.data(), outputData.data()}; // Run inference. auto start = std::chrono::high_resolution_clock::now(); context->execute(batchSize, buffers); auto end = std::chrono::high_resolution_clock::now(); std::chrono::duration<double, std::milli> elapsed = end - start; std::cout << "elapsed time: " << elapsed.count() << " ms\n"; // Release resources. context->destroy(); engine->destroy(); runtime->destroy(); return 0; } ``` 在这个代码中,我们首先使用 createCudaEngine 函数将 TorchScript 模型转换为 TensorRT engine。接着,我们创建 TensorRT execution context,准备输入和输出数据,并调用 context->execute 进行推理。最后,我们释放资源。 5. 总结 本文介绍了如何使用 LibTorchTorch TensorRT 对 TorchScript 模型进行加速推理。在实际应用中,我们可以根据自己的需求对代码进行修改和优化,以达到更好的性能和效果。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值