TensorRT学习笔记之ONNX转engine




#include <iostream>
#include "NvInfer.h"
#include "NvOnnxParser.h"
 
// 函数定义,用于创建TensorRT的引擎
nvinfer1::ICudaEngine* createEngine(const std::string& onnxModelFile) {
    // 创建builder
    nvinfer1::IBuilder* builder = nvinfer1::createInferBuilder(nvinfer1::ILogger::Severity::kWARNING);
    nvinfer1::IBuilderConfig* config = builder->createBuilderConfig();
 
    // 创建解析器
    auto parser = nvonnxparser::createParser(*builder, ::gLogger.getTRTLogger());
    const auto explicitBatch = 1U << static_cast<uint32_t>(nvinfer1::NetworkDefinitionCreationFlag::kEXPLICIT_BATCH);
    nvinfer1::INetworkDefinition* network = builder->createNetworkV2(explicitBatch);
 
    // 解析ONNX模型文件
    parser->parseFromFile(onnxModelFile.c_str(), static_cast<int>(nvinfer1::NetworkDefinitionCreationFlag::kEXPLICIT_BATCH));
 
    // 序列化网络
    builder->setMaxBatchSize(32);
    config->setMaxWorkspaceSize(1 << 20);
    nvinfer1::ICudaEngine* engine = builder->buildEngineWithConfig(*network, *config);
 
    // 清理资源
    parser->destroy();
    network->destroy();
    config->destroy();
    builder->destroy();
 
    return engine;
}
 
int main() {
    const std::string onnxModelFile = "model.onnx"; // 替换为你的ONNX模型文件路径
    nvinfer1::ICudaEngine* engine = createEngine(onnxModelFile);
 
    if (engine == nullptr) {
        std::cerr << "Engine could not be created." << std::endl;
        return -1;
    }
 
    // 保存引擎到文件
    std::ofstream planFile("model.plan", std::ios::binary);
    if (!planFile) {
        std::cerr << "Could not open plan output file for writing." << std::endl;
        return -1;
    }
    engine->serialize(planFile);
    planFile.close();
 
    // 释放资源
    engine->destroy();
    std::cout << "Engine has been created and saved to disk." << std::endl;
 
    return 0;
}

这段代码展示了如何使用TensorRT的C++ API将ONNX模型转换为TensorRT引擎,并将引擎序列化到一个文件中。代码中包含了创建TensorRT构建器、解析器和网络的步骤,并设置了构建引擎所需的配置。最后,引擎被序列化并保存到了文件系统中,同时释放了所有被创建的TensorRT资源。

gin
最后修改于:2024年08月15日 13:56

评论已关闭

推荐阅读

Vue中使用mind-map实现在线思维导图
2024年08月04日
VUE
Web前端最全Vue实现免密登录跳转的方式_vue怎么样不登录返回首页,最强技术实现
2024年08月04日
VUE
vue3 项目搭建教程(基于create-vue,vite,Vite + Vue)
2024年08月04日
VUE
Vue-颜色选择器实现方案——>Vue-Color( 实战*1+ Demo*7)
2024年08月04日
VUE
Vue项目卡顿慢加载?这些优化技巧告诉你!_vue数据多渲染卡顿
2024年08月04日
VUE
vue中的keep-alive详解与应用场景
2024年08月04日
VUE
Vue、React实现excel导出功能(三种实现方式保姆级讲解)
2024年08月04日
vue-office/docx插件实现docx文件预览
2024年08月04日
VUE
java调用js文件的两种方法(支持V8引擎)
2024年08月04日
JavaScript:解决计算精度问题/mathjs/bignumber.js/big.js/decimal.js
2024年08月04日
两周从爬虫小白变大神 _yjs_js_security_passport
2024年08月04日
JS笔记(对象、函数、数组)
2024年08月04日
Markdown.js:强大的纯JavaScript Markdown解析器
2024年08月04日
Vue项目:js模拟点击a标签下载文件并重命名,URL文件地址下载方法、请求接口下载文件方法总结。
2024年08月04日
vue 父组件怎么获取子组件里面的data数据
2024年08月04日
VUE
个人开发实现AI套壳网站快速搭建(Vue+elementUI+SpringBoot)
2024年08月04日
el-table 表格封装并改造实现单元格可编辑
2024年08月04日
none
nodejs环境下创建vue项目、SSH密钥登陆!!!
2024年08月04日
vue+quill+element-ui实现视频、图片上传及缩放保姆级教程,轻松使用富文本
2024年08月04日
【three.js】22. Imported Models导入模型
2024年08月04日