trt_backend.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. """Jetson TensorRT 后端(pycuda 直跑 .plan 引擎)。
  2. * 生产环境更推荐 DeepStream(``deploy/deepstream``),它自带零拷贝、多路解码和
  3. nvinfer 批处理;
  4. * 这个后端适合"单路相机 + 自己做状态机"的简洁部署,也用于和 DeepStream 对比精度;
  5. * 兼容 TensorRT 8(``get_binding_*``)与 TensorRT 10(``get_tensor_*`` / ``execute_async_v3``)。
  6. 引擎构建请用 ``scripts/build_trt.py``(在 Jetson 上执行,必须与设备版本一致)。
  7. """
  8. from __future__ import annotations
  9. import os
  10. from typing import Dict, List, Optional
  11. import numpy as np
  12. from ..config import Config
  13. from ..schema import Box
  14. from .base import Detector
  15. from .postproc import decode_yolo_output
  16. from .preproc import letterbox, to_blob
  17. __all__ = ["TensorRtDetector"]
  18. class TensorRtDetector(Detector):
  19. name = "tensorrt"
  20. def __init__(self, cfg: Config) -> None:
  21. super().__init__(cfg)
  22. self.engine_path: str = str(cfg.get_path("model.engine_path", ""))
  23. self.engine = None
  24. self.context = None
  25. self.stream = None
  26. self._cuda = None
  27. self._trt = None
  28. self._tensors: List[Dict[str, object]] = []
  29. # ------------------------------------------------------------ 加载
  30. def load(self) -> None:
  31. if self.context is not None:
  32. return
  33. if not os.path.isfile(self.engine_path):
  34. raise FileNotFoundError(
  35. "TensorRT 引擎不存在: %s(先在 Jetson 上执行 scripts/build_trt.py)" % self.engine_path
  36. )
  37. try:
  38. import tensorrt as trt # type: ignore
  39. import pycuda.driver as cuda # type: ignore
  40. except ImportError as exc: # pragma: no cover
  41. raise RuntimeError(
  42. "使用 tensorrt 后端需要 JetPack 自带的 tensorrt 与 pip 安装的 pycuda;"
  43. "若不想管理这些依赖,请改用 DeepStream 或 onnx 后端"
  44. ) from exc
  45. cuda.init()
  46. self._cuda = cuda
  47. self._trt = trt
  48. self.stream = cuda.Stream()
  49. with open(self.engine_path, "rb") as fh:
  50. runtime = trt.Runtime(trt.Logger(trt.Logger.WARNING))
  51. self.engine = runtime.deserialize_cuda_engine(fh.read())
  52. if self.engine is None:
  53. raise RuntimeError("反序列化 TensorRT 引擎失败(引擎与当前 TensorRT 版本不匹配?)")
  54. self.context = self.engine.create_execution_context()
  55. self._allocate()
  56. def _allocate(self) -> None:
  57. cuda = self._cuda
  58. trt = self._trt
  59. assert cuda is not None and trt is not None and self.engine is not None
  60. modern = hasattr(self.engine, "num_io_tensors") # TRT >= 10
  61. count = self.engine.num_io_tensors if modern else self.engine.num_bindings
  62. for index in range(count):
  63. if modern:
  64. name = self.engine.get_tensor_name(index)
  65. is_input = str(self.engine.get_tensor_mode(name)) == "TensorIOMode.INPUT"
  66. shape = tuple(int(v) for v in self.engine.get_tensor_shape(name))
  67. dtype = trt.nptype(self.engine.get_tensor_dtype(name))
  68. else:
  69. name = self.engine.get_binding_name(index)
  70. is_input = bool(self.engine.binding_is_input(index))
  71. shape = tuple(int(v) for v in self.engine.get_binding_shape(index))
  72. dtype = trt.nptype(self.engine.get_binding_dtype(index))
  73. if is_input:
  74. # 网络输入通常是 NCHW,H/W 可能为 -1(动态 shape),这里按配置固定
  75. height, width = self.input_size[1], self.input_size[0]
  76. shape = (1, 3, height, width)
  77. if modern:
  78. self.context.set_input_shape(name, shape)
  79. else:
  80. self.context.set_binding_shape(index, shape)
  81. size = int(np.prod(shape))
  82. host = cuda.pagelocked_empty(size, dtype)
  83. device = cuda.mem_alloc(host.nbytes)
  84. self._tensors.append(
  85. {
  86. "name": name,
  87. "is_input": is_input,
  88. "shape": shape,
  89. "dtype": dtype,
  90. "host": host,
  91. "device": device,
  92. "index": index,
  93. }
  94. )
  95. # ------------------------------------------------------------ 推理
  96. def infer(self, frame: np.ndarray) -> List[Box]:
  97. if self.context is None:
  98. self.load()
  99. cuda = self._cuda
  100. assert cuda is not None and self.context is not None and self.stream is not None
  101. height, width = frame.shape[:2]
  102. padded, ratio, pad = letterbox(frame, self.input_size)
  103. blob = to_blob(padded, self.input_format).astype(np.float32, copy=False)
  104. for item in self._tensors:
  105. if item["is_input"]:
  106. host = item["host"]
  107. np.copyto(host, blob.reshape(-1))
  108. cuda.memcpy_htod_async(item["device"], host, self.stream)
  109. if hasattr(self.context, "execute_async_v3"):
  110. for item in self._tensors:
  111. self.context.set_tensor_address(item["name"], int(item["device"]))
  112. self.context.execute_async_v3(stream_handle=self.stream.handle)
  113. else: # TensorRT 8
  114. bindings = [int(item["device"]) for item in self._tensors]
  115. self.context.execute_async_v2(bindings=bindings, stream_handle=self.stream.handle)
  116. for item in self._tensors:
  117. if not item["is_input"]:
  118. cuda.memcpy_dtoh_async(item["host"], item["device"], self.stream)
  119. self.stream.synchronize()
  120. outputs: List[np.ndarray] = []
  121. for item in self._tensors:
  122. if not item["is_input"]:
  123. outputs.append(np.array(item["host"]).reshape(tuple(item["shape"])))
  124. raw = self.pick_output(outputs)
  125. if raw is None:
  126. return []
  127. return decode_yolo_output(
  128. raw,
  129. labels=self.labels,
  130. conf_thres=self.conf,
  131. iou_thres=self.iou,
  132. max_det=self.max_det,
  133. nms_free=self.nms_free,
  134. ratio=ratio,
  135. pad=pad,
  136. image_size=(width, height),
  137. )
  138. # ------------------------------------------------------------ 释放
  139. def close(self) -> None:
  140. for item in self._tensors:
  141. try:
  142. item["device"].free()
  143. except Exception: # pragma: no cover - 释放失败不影响退出
  144. pass
  145. self._tensors = []
  146. self.context = None
  147. self.engine = None
  148. self.stream = None
  149. def describe(self) -> Dict[str, object]:
  150. info = super().describe()
  151. info.update({"engine_path": self.engine_path})
  152. return info