使用 onnxruntime-gpu 推理时,如何开启 TensorRT 后端并设置 INT8 校准?

解读

在国内工业界,把 PyTorch 训练好的模型通过 ONNX 导出、再用 onnxruntime-gpu 做线上推理,是“研究→生产”最主流的一条闭环。TensorRT 作为 NVIDIA 官方加速库,在 Ampere/Ada 架构 GPU 上能带来 3~7× 的吞吐提升;INT8 量化又是 TensorRT 的“杀手锏”,能把显存和延迟再压一半。因此“能不能把 TensorRT 开起来,并把 INT8 校准做对”几乎成了 CV/NLP 方向面试的“必答题”。面试官问这道题,想确认三件事:

  1. 你对 ONNX 生态工具链(onnxruntime-gpu、TensorRT、校准表)是否真正跑通过,而不是只看过文档;
  2. 你知道 INT8 校准的“数据代表集”怎么准备、怎么保证分布一致;
  3. 你能把“开启后端”与“设置校准”这两个阶段拆清楚,且能把关键 API 拼出来。

知识点

  1. onnxruntime-gpu 的 ExecutionProvider 注册顺序决定优先级,TensorRT 必须放在 CUDA 之前。
  2. SessionOptions 里与 TensorRT 相关的 key 近 20 个,国内最常问到的 6 组:
    • trt_engine_cache_enable / trt_engine_cache_path
    • trt_int8_enable
    • trt_int8_calibration_table_name
    • trt_int8_use_native_calibration_table
    • trt_max_workspace_size
    • trt_builder_optimization_level
  3. INT8 模式分“有校准表”和“无校准表”两条路:
    • 有校准表:先跑 CalibrationDataReader 生成 cache,第二次加载 cache 直接推理;
    • 无校准表:onnxruntime-gpu ≥1.16 支持 trt_int8_use_native_calibration_table=0,内部用动态量化,但精度往往掉 1–2%,不推荐上线。
  4. CalibrationDataReader 必须实现 get_next() → {"input_name": np.array(batch)},且数据预处理方式必须与训练阶段逐字节对齐(RGB/BGR、mean/std、resize 插值方式)。
  5. 国内大厂上线规范:
    • 校准集 ≥500 张或 5% 训练集,覆盖长尾场景;
    • 校准 batch_size 取 8/16,显存占用 <50%;
    • 同一模型版本校准表文件“谁生成谁负责”,文件名带 md5(onnx) 前 8 位,防止混用。
  6. 常见坑:
    • 驱动 ≤11.4 时 TensorRT 8.5 以上会加载失败;
    • 混用 conda 的 cudatoolkit 与系统 libcuda.so 导致 “TRT 6” 报错;
    • 动态 shape 模型忘了加 trt_profile_min_shapes / max_shapes,校准阶段直接崩溃。

答案

下面给出一条在 Ubuntu 20.04 + NVIDIA 驱动 525 + CUDA 11.8 + TensorRT 8.6 + onnxruntime-gpu 1.17 环境下调通的最小可复现流程,完全对应面试“手写代码”环节。

import onnxruntime as ort
import numpy as np
from tqdm import tqdm

# 1. 准备校准数据读取器
class CalibReader:
    def __init__(self, data_loader, input_name="input"):
        self.loader = data_loader          # torch.utils.data.DataLoader
        self.input_name = input_name
        self.enum = iter(self.loader)

    def get_next(self):
        try:
            batch, _ = next(self.enum)     # 不需要 label
            # 关键:预处理必须与训练阶段完全一致
            batch = batch.numpy() if hasattr(batch, "numpy") else batch
            return {self.input_name: batch}
        except StopIteration:
            return None

# 2. 生成 INT8 校准表(只做一次)
def build_calibration_table(onnx_path, calib_loader, cache_file="model.calibration"):
    providers = [
        ("TensorrtExecutionProvider", {
            "device_id": 0,
            "trt_max_workspace_size": 2 << 30,          # 2 GB
            "trt_fp16_enable": False,
            "trt_int8_enable": True,
            "trt_engine_cache_enable": False,           # 第一次不要缓存
            "trt_int8_calibration_table_name": cache_file,
            "trt_int8_use_native_calibration_table": 1  # 必须 1
        }),
        "CUDAExecutionProvider"
    ]
    sess = ort.InferenceSession(onnx_path, providers=providers)
    # 绑定 CalibrationDataReader
    calib = CalibReader(calib_loader)
    # 运行 dummy 推理,触发校准
    for _ in tqdm(range(len(calib_loader)), desc="Calibrating"):
        d = calib.get_next()
        if d is None:
            break
        _ = sess.run(None, d)
    print("Calibration table saved to", cache_file)

# 3. 正式推理阶段加载校准表
def create_int8_session(onnx_path, cache_file="model.calibration"):
    providers = [
        ("TensorrtExecutionProvider", {
            "device_id": 0,
            "trt_max_workspace_size": 2 << 30,
            "trt_fp16_enable": False,
            "trt_int8_enable": True,
            "trt_engine_cache_enable": True,
            "trt_engine_cache_path": "./trt_cache",
            "trt_int8_calibration_table_name": cache_file,
            "trt_int8_use_native_calibration_table": 1
        }),
        "CUDAExecutionProvider"
    ]
    sess = ort.InferenceSession(onnx_path, providers=providers)
    return sess

# 4. 使用示例
# build_calibration_table("model.onnx", calib_loader)
# sess = create_int8_session("model.onnx")
# output = sess.run(None, {"input": np.random.randn(32,3,224,224).astype(np.float32)})

要点回顾:

  • 第一次运行 build_calibration_table 会在当前目录生成 model.calibration;
  • 第二次及以后直接 create_int8_session,TensorRT 会读取校准表并生成 .engine 缓存,重启进程不再重新校准;
  • 若 ONNX 模型含动态维度,务必在 providers 字典里再补 trt_profile_min_shapes、trt_profile_max_shapes、trt_profile_opt_shapes,否则校准阶段会抛 Profile::kINVALID 异常。

拓展思考

  1. 如果面试官追问“校准表跨 GPU 架构是否可复用”,应回答:
    “同一 TensorRT 主版本(如 8.6.x)且 CUDA 计算能力相同(如 8.6/8.9 都算 sm_89)可以复用;跨大版本或跨架构(Ampere→Ada)必须重新校准,否则精度不可控。”
  2. 若被问到“INT8 掉精度如何回退”,可给出“混合精度”策略:
    “先开 trt_fp16_enable=True + trt_int8_enable=True,TensorRT 会自动把敏感层回退到 FP16;若仍不满足,再手动把指定节点标记为 FP16,方法是在 ONNX 里插入 quantization_annotation 把该层 scale=1/zero_point=0 标记为无效,TensorRT 会识别为 FP16。”
  3. 针对国内部署合规,可以补充:
    “上线前需通过 MLPerf 或自研压测脚本,在 99.9% 延迟 P99 指标下对比 FP32 下降不超过 1%;同时校准集需保存 30 天,方便监管回溯。”