"""Jetson TensorRT 后端(pycuda 直跑 .plan 引擎)。 * 生产环境更推荐 DeepStream(``deploy/deepstream``),它自带零拷贝、多路解码和 nvinfer 批处理; * 这个后端适合"单路相机 + 自己做状态机"的简洁部署,也用于和 DeepStream 对比精度; * 兼容 TensorRT 8(``get_binding_*``)与 TensorRT 10(``get_tensor_*`` / ``execute_async_v3``)。 引擎构建请用 ``scripts/build_trt.py``(在 Jetson 上执行,必须与设备版本一致)。 """ from __future__ import annotations import os from typing import Dict, List, Optional import numpy as np from ..config import Config from ..schema import Box from .base import Detector from .postproc import decode_yolo_output from .preproc import letterbox, to_blob __all__ = ["TensorRtDetector"] class TensorRtDetector(Detector): name = "tensorrt" def __init__(self, cfg: Config) -> None: super().__init__(cfg) self.engine_path: str = str(cfg.get_path("model.engine_path", "")) self.engine = None self.context = None self.stream = None self._cuda = None self._trt = None self._tensors: List[Dict[str, object]] = [] # ------------------------------------------------------------ 加载 def load(self) -> None: if self.context is not None: return if not os.path.isfile(self.engine_path): raise FileNotFoundError( "TensorRT 引擎不存在: %s(先在 Jetson 上执行 scripts/build_trt.py)" % self.engine_path ) try: import tensorrt as trt # type: ignore import pycuda.driver as cuda # type: ignore except ImportError as exc: # pragma: no cover raise RuntimeError( "使用 tensorrt 后端需要 JetPack 自带的 tensorrt 与 pip 安装的 pycuda;" "若不想管理这些依赖,请改用 DeepStream 或 onnx 后端" ) from exc cuda.init() self._cuda = cuda self._trt = trt self.stream = cuda.Stream() with open(self.engine_path, "rb") as fh: runtime = trt.Runtime(trt.Logger(trt.Logger.WARNING)) self.engine = runtime.deserialize_cuda_engine(fh.read()) if self.engine is None: raise RuntimeError("反序列化 TensorRT 引擎失败(引擎与当前 TensorRT 版本不匹配?)") self.context = self.engine.create_execution_context() self._allocate() def _allocate(self) -> None: cuda = self._cuda trt = self._trt assert cuda is not None and trt is not None and self.engine is not None modern = hasattr(self.engine, "num_io_tensors") # TRT >= 10 count = self.engine.num_io_tensors if modern else self.engine.num_bindings for index in range(count): if modern: name = self.engine.get_tensor_name(index) is_input = str(self.engine.get_tensor_mode(name)) == "TensorIOMode.INPUT" shape = tuple(int(v) for v in self.engine.get_tensor_shape(name)) dtype = trt.nptype(self.engine.get_tensor_dtype(name)) else: name = self.engine.get_binding_name(index) is_input = bool(self.engine.binding_is_input(index)) shape = tuple(int(v) for v in self.engine.get_binding_shape(index)) dtype = trt.nptype(self.engine.get_binding_dtype(index)) if is_input: # 网络输入通常是 NCHW,H/W 可能为 -1(动态 shape),这里按配置固定 height, width = self.input_size[1], self.input_size[0] shape = (1, 3, height, width) if modern: self.context.set_input_shape(name, shape) else: self.context.set_binding_shape(index, shape) size = int(np.prod(shape)) host = cuda.pagelocked_empty(size, dtype) device = cuda.mem_alloc(host.nbytes) self._tensors.append( { "name": name, "is_input": is_input, "shape": shape, "dtype": dtype, "host": host, "device": device, "index": index, } ) # ------------------------------------------------------------ 推理 def infer(self, frame: np.ndarray) -> List[Box]: if self.context is None: self.load() cuda = self._cuda assert cuda is not None and self.context is not None and self.stream is not None height, width = frame.shape[:2] padded, ratio, pad = letterbox(frame, self.input_size) blob = to_blob(padded, self.input_format).astype(np.float32, copy=False) for item in self._tensors: if item["is_input"]: host = item["host"] np.copyto(host, blob.reshape(-1)) cuda.memcpy_htod_async(item["device"], host, self.stream) if hasattr(self.context, "execute_async_v3"): for item in self._tensors: self.context.set_tensor_address(item["name"], int(item["device"])) self.context.execute_async_v3(stream_handle=self.stream.handle) else: # TensorRT 8 bindings = [int(item["device"]) for item in self._tensors] self.context.execute_async_v2(bindings=bindings, stream_handle=self.stream.handle) for item in self._tensors: if not item["is_input"]: cuda.memcpy_dtoh_async(item["host"], item["device"], self.stream) self.stream.synchronize() outputs: List[np.ndarray] = [] for item in self._tensors: if not item["is_input"]: outputs.append(np.array(item["host"]).reshape(tuple(item["shape"]))) raw = self.pick_output(outputs) if raw is None: return [] return decode_yolo_output( raw, labels=self.labels, conf_thres=self.conf, iou_thres=self.iou, max_det=self.max_det, nms_free=self.nms_free, ratio=ratio, pad=pad, image_size=(width, height), ) # ------------------------------------------------------------ 释放 def close(self) -> None: for item in self._tensors: try: item["device"].free() except Exception: # pragma: no cover - 释放失败不影响退出 pass self._tensors = [] self.context = None self.engine = None self.stream = None def describe(self) -> Dict[str, object]: info = super().describe() info.update({"engine_path": self.engine_path}) return info