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,可能是一个列表或者元组什么的
相关推荐
攻城狮7号25 分钟前
腾讯混元翻译模型Hunyuan-MT-7B开源,先前拿了30个冠军
人工智能·hunyuan-mt-7b·腾讯混元翻译模型·30个冠军
zezexihaha31 分钟前
从“帮写文案”到“管生活”:个人AI工具的边界在哪?
人工智能
算家云34 分钟前
nano banana官方最强Prompt模板来了!六大场景模板详解
人工智能·谷歌·ai大模型·算家云·ai生图·租算力,到算家云·nano banana 提示词
暴躁的大熊35 分钟前
AI助力决策:告别生活与工作中的纠结,明析抉择引领明智选择
人工智能
Gyoku Mint40 分钟前
提示词工程(Prompt Engineering)的崛起——为什么“会写Prompt”成了新技能?
人工智能·pytorch·深度学习·神经网络·语言模型·自然语言处理·nlp
honder试试43 分钟前
焊接自动化测试平台图像处理分析-模型训练推理
开发语言·python
梁小憨憨1 小时前
zotero扩容
人工智能·笔记
大数据张老师1 小时前
AI架构师的思维方式与架构设计原则
人工智能·架构师·ai架构·后端架构
心本无晴.1 小时前
Python进程,线程
python·进程
AKAMAI1 小时前
Entity Digital Sports 降低成本并快速扩展
人工智能·云计算