pytorch 模型部署之Libtorch

Python端生成pt模型文件

python 复制代码
net.load(model_path)
net.eval()
net.to("cuda")

example_input = torch.rand(1, 3, 240, 320).to("cuda")
traced_model = torch.jit.trace(net, example_input)
traced_model.save("model.pt")


output = traced_model(example_input)
# 输出查看是否与c++输出一致。
print(len(output))

C++ 端进行调用

c++环境配置
libtorch常用API

cpp 复制代码
#include <torch/script.h>
#include <torch/torch.h>

#include <iostream>

int main() {
	std::cout <<"cuda::is_available():" << torch::cuda::is_available() << std::endl;
    torch::Tensor tensor = torch::rand({2, 3}).to(at::kCUDA);
    std::cout << tensor << std::endl;
 
       torch::jit::script::Module module;
     
        module = torch::jit::load("/home/yang/Documents/demo/opencv/model.pt");
    

       // 创建一个示例输入
       std::vector<torch::jit::IValue> inputs;
       inputs.push_back(torch::rand({1, 3, 240, 320}).to(at::kCUDA));

       // 运行模型
      // at::Tensor output = module.forward(inputs).toTensor();
        //auto output = module.forward(inputs).toTensorList();
        auto out = module.forward(inputs);
 
        auto tpl = out.toTuple();

        auto out_ct_hm = tpl->elements()[0].toTensor();
        out_ct_hm.print();
        auto out_wh = tpl->elements()[1].toTensor();
        out_wh.print();


       // 打印输出
       //std::cout << output << "\n";

}

可能出错的问题

  1. terminate called after throwing an instance of 'c10::Error'
    what(): open file failed, file path: model.pt (FileAdapter at .../.../caffe2/serialize/file_adapter.cc:11)。 模型路径有问题,使用绝对路径解决。
  2. 'c10::Error' what(): isTensor() INTERNAL ASSERT FAILED。
    很明显,模型的输出应该不是一个 Tensor,可能是一个列表或者元组什么的
相关推荐
乐迪信息33 分钟前
乐迪信息:目标检测算法+AI摄像机:煤矿全场景识别方案
人工智能·物联网·算法·目标检测·目标跟踪·语音识别
学术小白人3 小时前
【EI会议征稿通知】2026年智能感知与自主控制国际学术会议(IPAC 2026)
人工智能·物联网·数据分析·区块链·能源
HyperAI超神经3 小时前
在线教程丨 David Baker 团队开源 RFdiffusion3,实现全原子蛋白质设计的生成式突破
人工智能·深度学习·学习·机器学习·ai·cpu·gpu
ASKED_20196 小时前
End-To-End之于推荐: Meta GRs & HSTU 生成式推荐革命之作
人工智能
liulanba6 小时前
AI Agent技术完整指南 第一部分:基础理论
数据库·人工智能·oracle
自动化代码美学6 小时前
【AI白皮书】AI应用运行时
人工智能
小CC吃豆子6 小时前
openGauss :核心定位 + 核心优势 + 适用场景
人工智能
一瞬祈望6 小时前
⭐ 深度学习入门体系(第 7 篇): 什么是损失函数?
人工智能·深度学习·cnn·损失函数
徐小夕@趣谈前端6 小时前
15k star的开源项目 Next AI Draw.io:AI 加持下的图表绘制工具
人工智能·开源·draw.io
优爱蛋白6 小时前
MMP-9(20-469) His Tag 蛋白:高活性可溶性催化结构域的研究工具
人工智能·健康医疗