先记住一句话

把 TensorRT 看成两套系统:昂贵且环境相关的 build system,以及低延迟、需显式管理 shape/memory/concurrency 的 runtime。

export/parse networkdefine profiles/precisionbenchmark tacticsserialize enginecreate context/bindings/streamenqueue + validate
Build phasenetwork + profiles
tactic search
Planengine
deserialize
Runtimeexecution context
set shapes/addresses
CUDA streamenqueue inference
Engine 固化 build 环境下的 tactics 与 profiles;runtime context 承载具体 shape 和并发状态。

1. Build→Run 全流程

Framework model / ONNX / Network Definition
  ↓ parse + shape/type inference + graph optimization
Builder + BuilderConfig + optimization profiles
  ↓ tactic search / timing cache / precision + format selection
Serialized Engine (plan)
  ↓ deserialize
Runtime + Engine + Execution Context + CUDA stream

builder 会融合 layers、消除常量、选择 kernels/tactics 并规划中间 memory。build 慢不等于 inference 慢;应离线构建并缓存可复现 artifacts。

2. Tactic selection

一个 layer 可能有多个来自 TensorRT、cuDNN、cuBLAS/cuBLASLt 或 plugin 的实现。builder 根据 shape、dtype、workspace 和实际 timing 选 tactic。timing noise 会影响选择;timing cache 可复用 profiling 结果,但必须尊重版本、设备和兼容性约束。

3. Engine 不是通用模型文件

serialized engine 含面向目标 GPU/software stack 的已编译执行计划,兼容范围由构建配置与 TensorRT 能力决定;不要把它当跨任意架构的 ONNX。官方还强调 engine 可能包含可执行代码/插件指针,应像原生二进制一样只反序列化可信来源。

4. Dynamic shapes 与 profiles

对 runtime dimensions,用 optimization profile 指定 MIN/OPT/MAX。builder 通常围绕 OPT shape 调优并保证范围内可运行;范围越宽,最优 tactic 空间可能更受限。多个 shape clusters 可建多个 profiles/engines,代价是 build time、engine size 和运维复杂度。

profile A: batch 1, short sequence
profile B: medium batch/sequence
profile C: long sequence fallback

5. Execution Context

engine 是只读的执行计划,context 保存一次执行流的动态状态、当前 profile/shapes 和 activation memory。并发请求通常用多个 contexts 和 streams;对象 thread-safety、profile ownership、workspace 生命周期与 input/output buffer 地址必须明确。

6. Memory 与 stream

host↔device copy 若要真正 async 通常需要 pinned host memory;用非默认 streams 和 events 构建依赖,可 overlap preprocessing、copy 与 inference。context 的 device memory、tensor buffers 和 stream 必须活到 enqueue 完成,过早复用会产生 silent corruption。

7. Precision 与 Q/DQ

FP16/BF16/FP8/INT8 等模式只有在硬件、layer 和 shape 有合适 kernel 时才提速。显式 Q/DQ graph 把量化边界与 scales 带入 TensorRT;mixed precision 允许敏感层保留高精度。必须比较端到端 task quality,不能只看 layer 输出或 engine build 成功。

8. Plugins

不支持的 op 可实现 TensorRT plugin,提供 format/type/shape 能力和 enqueue kernel。当前官方接口以 IPluginV3 为主。plugin 同时扩大 native-code trust boundary,也要自行承担 serialization、versioning、dynamic shapes、workspace、stream 与数值测试。

9. 用 trtexec 建 baseline

trtexec 可构建/加载 engine,设置 shapes、precision、streams 并报告 host latency、GPU compute time、throughput 和 enqueue time。它适合隔离 TensorRT engine 上限;真实应用还要加 preprocessing、copies、queueing、postprocessing 和并发调度。

10. 常见“没变快”原因

  • shape 太小,CPU enqueue/launch 主导;
  • dynamic profile 太宽或真实 shape 偏离 OPT;
  • layout conversions、unsupported ops 导致分段;
  • 量化插入大量 Q/DQ 或缺少目标精度 tactic;
  • 同步 copy/stream 使用错误;
  • 只优化 engine,应用瓶颈在前后处理。

11. 四个 TensorRT build/runtime 计算

例 1:profile 覆盖

Profile min/opt/max batch=[1,8,16]、sequence=[16,128,512]。请求 batch=12、seq=256 在范围内;batch=20 即使 tensor 内存足够也不匹配该 profile。

例 2:build amortization

Build 需 20 min=1200 s,engine 每 inference 比原方案省 4 ms;break-even requests=1200/0.004=300,000。生产长期服务可摊销,短实验未必。

例 3:context memory

Engine weights 2 GB 可被多个 contexts 共享,每 context activation workspace 600 MB。4 concurrent contexts 总约 2 GB+4×0.6 GB=4.4 GB,不含 I/O buffers。

例 4:tactic 与 end-to-end

某 layer 从 2 ms 降到 1 ms,但整网原 latency=10 ms,新 latency=9 ms,总 speedup=10/9=1.11×,不是 layer 的 2×。

常见误解:

TensorRT engine 不是安全的数据容器。它可能承载本机可执行逻辑;来自不可信来源的 plan/plugin 应视为供应链风险。

自测

1. engine 与 execution context 有什么区别?

engine 是优化后的只读执行计划;context 是一次/一路执行所需的动态 shape、profile、memory 等可变状态。

2. 为什么 optimization profile 的 OPT 很重要?

builder 会重点针对 OPT shape 选择和计时 tactics;真实 workload 若离它很远,性能可能不理想。

3. trtexec 快而服务慢说明什么?

engine 本身未必是瓶颈,应检查排队、batching、copies、前后处理、Python/CPU overhead 和并发资源管理。

官方资料

NVIDIA How TensorRT Works说明 build/runtime、tactics 与 engine 安全边界;Dynamic Shapes解释 optimization profiles;Benchmarking说明 trtexec metrics。