# TensorRT_CPP **Repository Path**: Laxman/tensor-rt_-cpp ## Basic Information - **Project Name**: TensorRT_CPP - **Description**: TensorRT的简单封装 - **Primary Language**: C++ - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 2 - **Forks**: 0 - **Created**: 2022-08-23 - **Last Updated**: 2024-04-21 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # TensorRT 封装库 > 参考了大量的NV的TensorRT的例程,仅仅实现了基本的功能,不是最佳实现。 ## Engine类 加载网络,并提供运行网络的方法。 ### 1. build_engine 通过trt格式模型文件加载模型,或通过模型数据(可通过OnnxParser转换onnx模型获得)加载模型。 ```C++ bool build_engine(const std::string& file); bool build_engine(const std::shared_ptr& model); bool build_engine(const char* data, const std::size_t size); ``` ### 2. perpare 为推理准备运行环境。在执行`execute()`或者`execute_async()`之前调用。 ```C++ void perpare(); ``` ### 3. execute/execute_async 此函数将会将数据传输到GPU内存中,在调用GPU运行该模型,将运行结果拷贝到CPU内存中。其中,`execute`和`execute_async`的主要区别为`execute_async`使用DMA进行传输。 > **注意:** 首次调用前,一定要执行一次`perpare()` ```C++ void execute(); void execute_async(); ``` ### 4. get_engine 得到TensorRT原始的CudaEngine ```C++ std::shared_ptr get_engine(); ``` ### 5. get_buffer 获取模型的输入输出缓存 ```C++ std::shared_ptr& get_buffer(); ``` ## 使用trt模型进行推理 ```CPP #include "engine.h" // 对于输入1x1x3x3 输出1x9的模型执行推理 // 实际数据个数1x1x3x3=9 1x9=9 // 模型 9 => 9 int main() { weilin::Engine engine; engine.build_engine("test.trt"); // 通过读取trt模型文件导入模型 engine.perpate(); // 准备环境 // 向输入缓冲区填入输入 float* data = static_cast(engine.get_buffer()->get_host_buffer(0)); for (int i = 0; i < 9; i++) { *data = 2.0f; data++; } // 执行推理 engine.execute(); // 或 engine.execute_async(); // 向输出缓冲区获取数据 float* result = static_cast(engine.get_buffer()->get_host_buffer(1)); for (int i = 0; i < 9; i++) { std::cout << *result << " "; result++; } return 0; } ``` ## onnx模型转tensorRT模型 ```CPP #include "onnx_parser.h" int main() { using namespace weilin; OnnxParser parser; parser.parse("test.onnx"); // 输入onnx模型并尝试对模型进行转换 if (parser.is_parse_success()) { // 转换成功 parser.save_model("test.trt"); // 保存转换好的模型 // 或则直接使用转换好的模型 auto model = parser.get_model(); // 使用模型 ... } } ``` ## 依赖 - cuda - TensorRT - spdlog