tensorrt-cpp-api

cyrusbehrMIT更新放缓

一套 TensorRT C++ API 实战教程,演示如何用 C++ 加载 ONNX 模型并构建高性能推理引擎,适合想在工程里落地 GPU 推理的开发者。

TensorRT C++ API Tutorial

暂无版本812star105fork同步于 2026-11-07 07:30 UTC

怎么上手

由 README 提炼,执行前请确认
cmake -S . -B build -DTRT_CPP_API_BUILD_PREPROC=ON
cmake --build build -j$(nproc)
cmake --install build --prefix /opt/trtcpp
硬件要求按 README 说明

需要 NVIDIA GPU 和 CUDA 12,TensorRT ≥ 10 由系统或外部提供;README 未给出具体显存要求,性能数据基于 RTX 3080 Laptop GPU。

需要 CUDA
下载:源码 zip·GitHub Releases(安装包)本站不镜像安装包

项目说明

由 README 自动翻译提炼

把 ONNX 模型编译成 TensorRT 引擎并跑 CNN 推理的现代 C++ 库,带可选 Python 绑定

一套 TensorRT C++ API 实战教程,演示如何用 C++ 加载 ONNX 模型并构建高性能推理引擎,适合想在工程里落地 GPU 推理的开发者。

核心能力

  • 按 ONNX 哈希、构建选项、TensorRT 版本和 GPU UUID 缓存引擎
  • 支持动态形状的 min/opt/max 优化配置
  • 用 EnginePool 租借执行上下文做多流并发推理
  • 公开头文件不暴露 TensorRT 和 OpenCV 类型
  • 可选融合预处理 CUDA kernel 完成 letterbox 到 NCHW 转换

容易踩的坑

TensorRT 和 CUDA 需自行安装,用 tarball 版 TensorRT 时要加 -DTensorRT_DIR=;示例模型需先运行 examples/download_models.sh 下载;仅支持 Linux、CUDA 12、TensorRT ≥ 10 和 CNN 视觉模型,Windows 与 LLM 不在范围内。

内容由模型根据 README 生成,可能不完整或不准确,以官方文档为准。看原文 README

最近发版

0 个版本

暂无 release 数据(可能没有发版,或尚未同步)。

用户点评

登录用户的真实使用记录,可按版本和硬件筛选
共 0 条

    还没有人点评。第一个说出真实体验的人最有价值。

    README 原文

    未翻译

    Stargazers Issues LinkedIn


    tensorrt_cpp_api turns an ONNX model into a cached, optimized TensorRT engine and runs it with a small, leak-free API: name-keyed tensors at the boundary, caller-owned CUDA streams, explicit host/device transfers, and a Status/Result<T> error model — no exceptions, no OpenCV or TensorRT types in the public headers. It targets TensorRT ≥ 10 (built to the TensorRT 11 surface), CUDA 12, C++20, Linux.

    #include <tensorrt_cpp_api/all.h>
    using namespace trtcpp;
    
    int main() {
        // Build an FP16 engine from ONNX, or load it from the on-disk cache if one is already current.
        BuildOptions opt;
        opt.precision = Precision::kFp16;
        opt.engineCacheDir = "engines";
        auto engine = EngineBuilder{}.buildAndLoad("model.onnx", opt);
        if (!engine) {
            std::fprintf(stderr, "%s\n", engine.status().message().c_str());
            return 1;
        }
    
        Stream stream;  // owns a CUDA stream — or Stream::wrap(existingHandle) to use yours
        auto input = Tensor::allocate(DType::kFloat32, Shape{1, 3, 640, 640}, Device::kCuda).value();
        // ... fill `input` (e.g. via the fused preproc kernel) ...
    
        auto output = engine->inferSingle({{engine->inputNames().front(), input.view()}}, stream);
        if (!output) return 1;
    
        auto host = output->toHost(stream).value();   // explicit D2H + sync; never implicit
        std::span<const float> scores = host.as<float>().value();
        // ... post-process `scores` ...
    }
    

    Features

    • Engine cache that's actually safe. Build-or-load keyed by ONNX content hash + build options
      • TensorRT version + GPU UUID, with a JSON sidecar and atomic writes. A stale cache (changed model, options, driver, or GPU) is detected and rebuilt instead of silently misused.
    • Dynamic shapes, done right. Per-input min/opt/max optimization profiles; -1-aware Shape; one optimization profile per execution context for concurrent dynamic-shape inference.
    • Concurrency. EnginePool leases execution contexts for multi-stream inference; every call runs on a caller-provided Stream. The engine is thread-compatible; the pool is thread-safe.
    • No leaky abstractions. No nvinfer1, OpenCV, or spdlog types in any public header (PImpl + version-gated, generated build_config.h). Consumers need TensorRT at runtime, not compile time.
    • Quantization without surprises. Precision::kFp16 / kInt8Qdq / kFp8 …; precision is version-aware and never a silent no-op (it errors clearly when a mode isn't achievable).
    • Optional fused preprocessing (tensorrt_cpp_api::preproc): one CUDA kernel does letterbox-resize → BGR↔RGB → per-channel normalize → HWC→NCHW → cast, no intermediate buffers.
    • Optional zero-copy Python bindings (trtcpp): feed CuPy / PyTorch / Numba GPU arrays in and get them back via __cuda_array_interface__ / DLPack — no host round-trips, GIL released during inference. See examples/python.
    • Installable. cmake --install produces a find_package(tensorrt_cpp_api)-consumable package.

    Performance

    Single-stream inference latency on an RTX 3080 Laptop GPU (preallocated, zero-copy enqueue loop — examples/benchmark), TensorRT 10:

    ModelPrecisionLatencyThroughput
    YOLOv8nFP161.07 ms937 inf/s
    YOLOv8nFP322.00 ms499 inf/s
    MobileNetV2FP160.31 ms3199 inf/s

    Inference time is TensorRT-bound — it is the enqueueV3 cost of the engine itself, so the wrapper adds no measurable inference overhead. The library's work is everything around that call: zero-copy name-keyed IO with no per-call allocations or nested-vector copies, a stream-ordered allocator, and the no-throw Status/Result API. The Python bindings run the same path within ~13% of C++ (examples/python/benchmark_parity.py).

    Install

    TensorRT and CUDA are system/externally provided. In brief:

    cmake -S . -B build -DTRT_CPP_API_BUILD_PREPROC=ON        # add -DTensorRT_DIR=<root> for a tarball
    cmake --build build -j$(nproc)
    cmake --install build --prefix /opt/trtcpp
    

    Then in a downstream project:

    find_package(tensorrt_cpp_api REQUIRED)
    target_link_libraries(myapp PRIVATE tensorrt_cpp_api::tensorrt_cpp_api tensorrt_cpp_api::preproc)
    

    Python: pip install . (builds the trtcpp wheel via scikit-build-core). Full details — apt vs tarball TensorRT, build options, Python — are in docs/install.md.

    Examples

    examples/ has four runnable reference programs, each consuming the installed package: classification (ImageNet top-5), detection (YOLOv8n + NMS), segmentation (DeepLabV3), and a zero-copy Python demo with a C++/Python perf-parity benchmark. examples/download_models.sh fetches the models.

    Documentation

    Sister projects

    This library is the inference backend for YOLOv8-TensorRT-CPP and YOLOv9-TensorRT-CPP (object detection, segmentation, pose).

    Scope

    Linux, CUDA 12, TensorRT ≥ 10, CNN-style vision models. Windows and LLM/transformer-specific features are out of scope.

    Contributing

    Issues and PRs welcome. Install the hooks with pre-commit install (clang-format + cmake-format); CI runs the build, the CPU test suite, sanitizers, and a Python wheel build. If this project helps you, a ⭐ is appreciated — connect on LinkedIn.

    Contributors

    This project follows the all-contributors specification.

    License

    See LICENSE. Version history is in CHANGELOG.md.