ONNX模型结构转文本格式

深度学习端侧推理框架核心元素:
模型结构定义及存储
tensor的定义
内存分配算法
多线程计算

onnx框架的模型结构利用protobuf库定义模型元素及保存模型结构,以下借助protobuf的API将onnx模型由二进制转为文本格式,文本格式可以清楚的查看onnx模型都有哪些字段和内容,配合对应的proto文件帮助更深刻理解模型结构。

  1. 下载onnx.proto文件, 注释最后一行,因为使用protobuf-lite会少很多实用接口。
// For using protobuf-lite
//option optimize_for = LITE_RUNTIME;

  1. 生成.cc和.h文件
protoc -I ./ --cpp_out=./ onnx.proto
  1. 编译转换代码
g++ convert2text.cpp onnx.pb.cc -o convert2text-lprotobuf
#include <iostream>
#include <fstream>
#include "onnx.pb.h"
#include "google/protobuf/text_format.h"
#include "google/protobuf/io/coded_stream.h"
#include "google/protobuf/io/zero_copy_stream_impl.h"
#include <sstream>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

using google::protobuf::Message;
using google::protobuf::io::FileOutputStream;

void WriteProtoToTextFile(const Message& proto, const char* filename)
{
    int fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
    if (fd < 0) {
        return;
    }
    FileOutputStream* output = new FileOutputStream(fd);
    google::protobuf::TextFormat::Print(proto, output);
    delete output;
    close(fd);
}

int main(int argc, char* argv[])
{
    onnx::ModelProto oriModelProto;
    {
        std::fstream input(argv[1], std::ios::in | std::ios::binary);
        if (!oriModelProto.ParseFromIstream(&input)) {
            std::cerr <<"failed to parse onnx modelproto"<<std::endl;
            return -1;
        }
    }
    WriteProtoToTextFile(oriModelProto, argv[2]);
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值