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,可能是一个列表或者元组什么的
相关推荐
Liudef06几秒前
FLUX.1-Kontext 高效训练 LoRA:释放大语言模型定制化潜能的完整指南
人工智能·语言模型·自然语言处理·ai作画·aigc
静心问道2 分钟前
大型语言模型中的自动化思维链提示
人工智能·语言模型·大模型
万千思绪11 分钟前
【PyCharm 2025.1.2配置debug】
ide·python·pycharm
众链网络29 分钟前
你的Prompt还有很大提升
人工智能·prompt·ai写作·ai工具·ai智能体
汀沿河31 分钟前
2 大模型高效参数微调;prompt tunning
人工智能·深度学习·prompt
路溪非溪38 分钟前
机器学习之线性回归
人工智能·机器学习·线性回归
微风粼粼2 小时前
程序员在线接单
java·jvm·后端·python·eclipse·tomcat·dubbo
搞笑的秀儿2 小时前
信息新技术
大数据·人工智能·物联网·云计算·区块链
云天徽上2 小时前
【PaddleOCR】OCR表格识别数据集介绍,包含PubTabNet、好未来表格识别、WTW中文场景表格等数据,持续更新中......
python·ocr·文字识别·表格识别·paddleocr·pp-ocrv5
阿里云大数据AI技术2 小时前
OpenSearch 视频 RAG 实践
数据库·人工智能·llm