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,可能是一个列表或者元组什么的
相关推荐
计算机小手2 分钟前
使用 llama.cpp 在本地高效运行大语言模型,支持 Docker 一键启动,兼容CPU与GPU
人工智能·经验分享·docker·语言模型·开源软件
短视频矩阵源码定制3 分钟前
矩阵系统哪个好?2025年全方位选型指南与品牌深度解析
java·人工智能·矩阵·架构·aigc
java1234_小锋8 分钟前
[免费]基于Python的Flask酒店客房管理系统【论文+源码+SQL脚本】
开发语言·人工智能·python·flask·酒店客房
hakuii20 分钟前
SVD分解后的各个矩阵的深层理解
人工智能·机器学习·矩阵
这张生成的图像能检测吗39 分钟前
(论文速读)基于图像堆栈的低频超宽带SAR叶簇隐蔽目标变化检测
图像处理·人工智能·深度学习·机器学习·信号处理·雷达·变化检测
leijiwen1 小时前
城市本地生活实体零售可信数据空间 RWA 平台方案
人工智能·生活·零售
L-ololois1 小时前
【AI产品】一键比较GPT-5、Claude 4、Gemini 2.5、Deepseek多chatbot
人工智能·gpt
2401_841495641 小时前
【自然语言处理】生成式语言模型GPT复现详细技术方案
人工智能·python·gpt·深度学习·语言模型·自然语言处理·transformer
Elastic 中国社区官方博客1 小时前
如何使用 Ollama 在本地设置和运行 GPT-OSS
人工智能·gpt·elasticsearch·搜索引擎·ai·语言模型
FreeBuf_1 小时前
PortGPT:研究人员如何教会AI自动回移植安全补丁
人工智能