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,可能是一个列表或者元组什么的
相关推荐
飞哥数智坊8 小时前
从CodeBuddy翻车到MasterGo救场,我的小程序UI终于焕然一新
人工智能
AKAMAI10 小时前
跳过复杂环节:Akamai应用平台让Kubernetes生产就绪——现已正式发布
人工智能·云原生·云计算
databook12 小时前
Manim实现闪光轨迹特效
后端·python·动效
新智元12 小时前
阿里王牌 Agent 横扫 SOTA,全栈开源力压 OpenAI!博士级难题一键搞定
人工智能·openai
新智元12 小时前
刚刚,OpenAI/Gemini 共斩 ICPC 2025 金牌!OpenAI 满分碾压横扫全场
人工智能·openai
机器之心12 小时前
OneSearch,揭开快手电商搜索「一步到位」的秘技
人工智能·openai
阿里云大数据AI技术12 小时前
2025云栖大会·大数据AI参会攻略请查收!
大数据·人工智能
Juchecar13 小时前
解惑:NumPy 中 ndarray.ndim 到底是什么?
python
YourKing13 小时前
yolov11n.onnx格式模型转换与图像推理
人工智能
sans_13 小时前
NCCL的用户缓冲区注册
人工智能