test_rknn_ops.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. """RKNN 部署相关单元测试(**不需要** RK 板卡 / rknnlite / 模型文件)。
  2. 覆盖四块新增/改动:
  3. 1. ``model.rknn_core`` 在单核板(RK3576)上被收敛为 auto,而不是让 ``init_runtime`` 报错;
  4. 2. NPU 负载节点解析(debugfs 多核 / devfreq 两种真实格式);
  5. 3. 后处理向量化与标量版**逐框等价**(重构不许改行为);
  6. 4. ``scripts/rknpu_ratio.py`` 的两个口径汇总与判定。
  7. """
  8. import importlib.util
  9. import os
  10. import unittest
  11. import numpy as np
  12. from portcv.config import Config
  13. from portcv.detect.postproc import decode_yolo_output
  14. from portcv.detect.preproc import to_blob, unletterbox_box
  15. from portcv.detect.rknn_backend import (
  16. RknnDetector,
  17. detect_npu_cores,
  18. model_chain_ratio,
  19. parse_npu_load,
  20. read_npu_load,
  21. resolve_core_mask,
  22. )
  23. ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  24. LABELS = ["container", "bed", "flatbed"]
  25. def load_ratio_script():
  26. """按路径加载 ``scripts/rknpu_ratio.py``(scripts 不是包)。"""
  27. path = os.path.join(ROOT, "scripts", "rknpu_ratio.py")
  28. spec = importlib.util.spec_from_file_location("rknpu_ratio", path)
  29. module = importlib.util.module_from_spec(spec)
  30. assert spec.loader is not None
  31. spec.loader.exec_module(module)
  32. return module
  33. class CoreMaskTests(unittest.TestCase):
  34. def test_auto_and_single_core_pass_through(self):
  35. self.assertEqual(resolve_core_mask("auto", 3), (0, ""))
  36. self.assertEqual(resolve_core_mask("0", 3), (1, ""))
  37. self.assertEqual(resolve_core_mask("1", 1), (2, ""))
  38. def test_multi_core_config_on_rk3588_is_kept(self):
  39. self.assertEqual(resolve_core_mask("0_1_2", 3), (7, ""))
  40. def test_multi_core_config_on_rk3576_is_clamped(self):
  41. mask, note = resolve_core_mask("0_1_2", 1)
  42. self.assertEqual(mask, 0)
  43. self.assertIn("NPU core", note)
  44. self.assertIn("auto", note)
  45. def test_unknown_board_does_not_clamp(self):
  46. self.assertEqual(resolve_core_mask("0_1_2", 0), (7, ""))
  47. def test_unknown_value_raises(self):
  48. with self.assertRaises(ValueError):
  49. resolve_core_mask("3", 3)
  50. def test_board_to_core_count(self):
  51. self.assertEqual(detect_npu_cores("rockchip,rk3576-wxd-a576"), 1)
  52. self.assertEqual(detect_npu_cores("rk3588"), 3)
  53. self.assertEqual(detect_npu_cores("rk3568"), 1)
  54. self.assertEqual(detect_npu_cores(""), 0)
  55. self.assertEqual(detect_npu_cores("some-other-soc"), 0)
  56. class NpuLoadTests(unittest.TestCase):
  57. def test_debugfs_multi_core_takes_busiest(self):
  58. text = "NPU load: Core0: 37%, Core1: 0%, Core2: 5%,"
  59. self.assertAlmostEqual(parse_npu_load(text), 0.37)
  60. def test_devfreq_format(self):
  61. self.assertAlmostEqual(parse_npu_load("load=42@1000000000Hz"), 0.42)
  62. def test_unparsable_returns_none_not_zero(self):
  63. self.assertIsNone(parse_npu_load(""))
  64. self.assertIsNone(parse_npu_load("nonsense"))
  65. self.assertIsNone(read_npu_load("C:/definitely/missing/npu/load"))
  66. class ToBlobTests(unittest.TestCase):
  67. def test_bgr_uint8_is_zero_copy(self):
  68. image = np.zeros((8, 8, 3), dtype=np.uint8)
  69. blob = to_blob(image, "bgr_uint8")
  70. self.assertEqual(blob.shape, (1, 8, 8, 3))
  71. self.assertTrue(np.shares_memory(blob, image))
  72. def test_rgb_uint8_flips_channels(self):
  73. image = np.zeros((2, 2, 3), dtype=np.uint8)
  74. image[..., 0] = 10 # B
  75. image[..., 2] = 200 # R
  76. blob = to_blob(image, "rgb_uint8")
  77. self.assertEqual(int(blob[0, 0, 0, 0]), 200)
  78. self.assertEqual(int(blob[0, 0, 0, 2]), 10)
  79. def test_rgb_float_is_nchw(self):
  80. blob = to_blob(np.full((4, 6, 3), 255, dtype=np.uint8), "rgb_float")
  81. self.assertEqual(blob.shape, (1, 3, 4, 6))
  82. self.assertEqual(blob.dtype, np.float32)
  83. self.assertAlmostEqual(float(blob[0, 0, 0, 0]), 1.0)
  84. def test_unknown_format_raises(self):
  85. with self.assertRaises(ValueError):
  86. to_blob(np.zeros((2, 2, 3), dtype=np.uint8), "yuv420")
  87. def _scalar_xywh(raw, labels, conf, ratio, pad, image_size):
  88. """重构前的标量实现(参照物):逐框调用 ``unletterbox_box``。"""
  89. arr = np.asarray(raw, dtype=np.float32)
  90. while arr.ndim > 2:
  91. arr = arr[0]
  92. nc = len(labels)
  93. # 与 _as_2d 一致:导出常见 (C, N) 布局,需要转置成 (N, C)
  94. if arr.shape[1] not in (4 + nc, 5 + nc, 6) and arr.shape[0] in (4 + nc, 5 + nc, 6):
  95. arr = arr.T
  96. arr = np.ascontiguousarray(arr)
  97. cls_scores = arr[:, 4 : 4 + nc]
  98. cls_ids = np.argmax(cls_scores, axis=1)
  99. scores = cls_scores[np.arange(len(cls_ids)), cls_ids]
  100. rows = []
  101. for i in range(len(arr)):
  102. if scores[i] < conf:
  103. continue
  104. x1 = float(arr[i, 0] - arr[i, 2] / 2.0)
  105. y1 = float(arr[i, 1] - arr[i, 3] / 2.0)
  106. x2 = float(arr[i, 0] + arr[i, 2] / 2.0)
  107. y2 = float(arr[i, 1] + arr[i, 3] / 2.0)
  108. rx1, ry1, rx2, ry2 = unletterbox_box(x1, y1, x2, y2, ratio, pad, image_size)
  109. if rx2 - rx1 < 1 or ry2 - ry1 < 1:
  110. continue
  111. rows.append((rx1, ry1, rx2, ry2, float(scores[i]), int(cls_ids[i])))
  112. return rows
  113. class VectorizedDecodeTests(unittest.TestCase):
  114. def setUp(self):
  115. rng = np.random.default_rng(7)
  116. n = 40
  117. arr = np.zeros((1, 4 + len(LABELS), n), dtype=np.float32)
  118. arr[0, 0] = rng.uniform(0.0, 220.0, n) # cx
  119. arr[0, 1] = rng.uniform(0.0, 160.0, n) # cy
  120. arr[0, 2] = rng.uniform(1.0, 120.0, n) # w
  121. arr[0, 3] = rng.uniform(1.0, 120.0, n) # h
  122. arr[0, 4] = rng.uniform(0.0, 1.0, n)
  123. arr[0, 5] = rng.uniform(0.0, 1.0, n)
  124. arr[0, 6] = rng.uniform(0.0, 1.0, n)
  125. self.raw = np.ascontiguousarray(arr)
  126. self.ratio = 0.5
  127. self.pad = (12.0, 30.0)
  128. self.size = (640, 480)
  129. def _decode(self):
  130. return decode_yolo_output(
  131. self.raw,
  132. labels=LABELS,
  133. conf_thres=0.2,
  134. iou_thres=0.5,
  135. max_det=100,
  136. ratio=self.ratio,
  137. pad=self.pad,
  138. image_size=self.size,
  139. apply_nms=False,
  140. )
  141. def test_matches_scalar_reference(self):
  142. expected = _scalar_xywh(self.raw, LABELS, 0.2, self.ratio, self.pad, self.size)
  143. got = self._decode()
  144. self.assertEqual(len(got), len(expected))
  145. for box, row in zip(got, expected):
  146. self.assertAlmostEqual(box.x1, row[0], places=6)
  147. self.assertAlmostEqual(box.y1, row[1], places=6)
  148. self.assertAlmostEqual(box.x2, row[2], places=6)
  149. self.assertAlmostEqual(box.y2, row[3], places=6)
  150. self.assertAlmostEqual(box.score, row[4], places=6)
  151. self.assertEqual(box.class_id, row[5])
  152. self.assertEqual(box.class_name, LABELS[row[5]])
  153. def test_coords_are_clipped_to_image(self):
  154. for box in self._decode():
  155. self.assertGreaterEqual(box.x1, 0.0)
  156. self.assertLessEqual(box.x2, float(self.size[0]))
  157. self.assertGreaterEqual(box.y1, 0.0)
  158. self.assertLessEqual(box.y2, float(self.size[1]))
  159. def test_nms_free_path_matches_scalar(self):
  160. rows = np.array(
  161. [
  162. [10.0, 20.0, 110.0, 120.0, 0.9, 0.0],
  163. [10.0, 20.0, 110.0, 120.0, 0.1, 0.0], # 低于 conf
  164. [5.0, 5.0, 5.4, 5.4, 0.8, 1.0], # 还原后 < 1 px → 丢弃
  165. ],
  166. dtype=np.float32,
  167. )
  168. got = decode_yolo_output(
  169. rows[None],
  170. labels=LABELS,
  171. conf_thres=0.35,
  172. ratio=1.0,
  173. pad=(0.0, 0.0),
  174. image_size=(640, 480),
  175. nms_free=True,
  176. )
  177. self.assertEqual(len(got), 1)
  178. self.assertAlmostEqual(got[0].x1, 10.0, places=5)
  179. self.assertEqual(got[0].class_name, "container")
  180. class _StubRuntime:
  181. """假 rknnlite runtime:记录调用参数,返回固定的检测头张量。"""
  182. def __init__(self, outputs):
  183. self.outputs = outputs
  184. self.calls = []
  185. self.released = False
  186. def inference(self, inputs=None, data_format=None):
  187. self.calls.append({"data_format": data_format, "shape": inputs[0].shape})
  188. return self.outputs
  189. def release(self):
  190. self.released = True
  191. class RknnDetectorTests(unittest.TestCase):
  192. def _cfg(self, input_format):
  193. return Config(
  194. {
  195. "run": {"backend": "rknn"},
  196. "model": {"input_format": input_format, "input_size": [64, 64], "labels": LABELS},
  197. }
  198. )
  199. def _detector(self, input_format):
  200. outputs = [np.zeros((1, 4 + len(LABELS), 5), dtype=np.float32)]
  201. stub = _StubRuntime(outputs)
  202. detector = RknnDetector(self._cfg(input_format))
  203. detector.rknn = stub # 绕过 load(),避免依赖 rknnlite
  204. return detector, stub
  205. def test_uint8_input_declares_nhwc(self):
  206. detector, stub = self._detector("bgr_uint8")
  207. boxes = detector.infer(np.zeros((48, 64, 3), dtype=np.uint8))
  208. self.assertEqual(boxes, [])
  209. self.assertEqual(stub.calls[0]["data_format"], "nhwc")
  210. self.assertEqual(tuple(stub.calls[0]["shape"]), (1, 64, 64, 3))
  211. def test_float_input_does_not_force_nhwc(self):
  212. detector, stub = self._detector("rgb_float")
  213. detector.infer(np.zeros((48, 64, 3), dtype=np.uint8))
  214. self.assertIsNone(stub.calls[0]["data_format"])
  215. self.assertEqual(tuple(stub.calls[0]["shape"]), (1, 3, 64, 64))
  216. def test_stage_timings_and_describe(self):
  217. detector, _ = self._detector("bgr_uint8")
  218. detector.infer(np.zeros((48, 64, 3), dtype=np.uint8))
  219. self.assertEqual(set(detector.stage_ms), {"preproc", "npu", "postproc"})
  220. info = detector.describe()
  221. self.assertIn("stage_ms", info)
  222. self.assertIn("core_mask", info)
  223. self.assertEqual(info["npu_cores"], detect_npu_cores(detector.board))
  224. def test_close_releases_runtime(self):
  225. detector, stub = self._detector("bgr_uint8")
  226. detector.close()
  227. self.assertTrue(stub.released)
  228. self.assertIsNone(detector.rknn)
  229. class ModelChainRatioTests(unittest.TestCase):
  230. """口径 B 的实时版本:``describe()`` / status 用它,脚本用 ``ratio_b``,两者必须同义。"""
  231. def test_ratio_is_npu_over_model_chain(self):
  232. self.assertAlmostEqual(
  233. model_chain_ratio({"preproc": 2.0, "npu": 10.0, "postproc": 3.0}),
  234. 10.0 / 15.0,
  235. places=6,
  236. )
  237. def test_missing_or_zero_stage_returns_none(self):
  238. self.assertIsNone(model_chain_ratio(None))
  239. self.assertIsNone(model_chain_ratio({}))
  240. self.assertIsNone(model_chain_ratio({"preproc": 0.0, "npu": 0.0, "postproc": 0.0}))
  241. class RatioSummaryTests(unittest.TestCase):
  242. def setUp(self):
  243. self.mod = load_ratio_script()
  244. def _samples(self, npu, preproc=2.0, postproc=3.0, decode=5.0, load=0.5):
  245. return [
  246. {
  247. "decode_ms": decode,
  248. "preproc_ms": preproc,
  249. "npu_ms": npu,
  250. "postproc_ms": postproc,
  251. "npu_load": load,
  252. }
  253. for _ in range(10)
  254. ]
  255. def test_two_ratios_differ_by_decode(self):
  256. summary = self.mod.summarize(self._samples(10.0), target=0.70)
  257. self.assertAlmostEqual(summary["ratio_a"], 0.5, places=4) # 10 / (5+2+10+3)
  258. self.assertAlmostEqual(summary["ratio_b"], 10.0 / 15.0, places=4)
  259. self.assertFalse(summary["pass_a"])
  260. self.assertFalse(summary["pass_b"])
  261. def test_target_is_respected(self):
  262. summary = self.mod.summarize(self._samples(10.0), target=0.49)
  263. self.assertTrue(summary["pass_a"])
  264. def test_zero_npu_means_zero_ratio(self):
  265. summary = self.mod.summarize(self._samples(0.0), target=0.70)
  266. self.assertEqual(summary["ratio_a"], 0.0)
  267. self.assertFalse(summary["pass_a"])
  268. def test_extra_ms_lowers_ratio(self):
  269. base = self.mod.summarize(self._samples(10.0), target=0.70)
  270. with_extra = self.mod.summarize(self._samples(10.0), target=0.70, extra_ms=10.0)
  271. self.assertLess(with_extra["ratio_a"], base["ratio_a"])
  272. def test_missing_load_reported_as_null(self):
  273. summary = self.mod.summarize(self._samples(10.0, load=None), target=0.70)
  274. self.assertIsNone(summary["npu_load"]["mean"])
  275. self.assertIn("无法读取", self.mod.format_report(summary))
  276. def test_report_mentions_both_metrics(self):
  277. text = self.mod.format_report(self.mod.summarize(self._samples(10.0), target=0.70))
  278. self.assertIn("口径A", text)
  279. self.assertIn("口径B", text)
  280. self.assertIn("FAIL", text)
  281. def _producer_samples(self, npu=12.0, preproc=2.0, postproc=1.0, wait=20.0, period=35.0):
  282. """``--producer`` 模式的采样:decode=0,等帧单列 ``wait_ms``,模型链固定 15 ms。"""
  283. return [
  284. {
  285. "decode_ms": 0.0,
  286. "wait_ms": wait,
  287. "period_ms": period,
  288. "preproc_ms": preproc,
  289. "npu_ms": npu,
  290. "postproc_ms": postproc,
  291. "npu_load": 0.5,
  292. }
  293. for _ in range(10)
  294. ]
  295. def test_producer_wait_is_not_in_ratio_a(self):
  296. summary = self.mod.summarize(self._producer_samples(), target=0.70)
  297. self.assertAlmostEqual(summary["ratio_a"], 12.0 / 15.0, places=4)
  298. # 等帧 20 ms 只进 wall 口径:12 / (15 + 20)
  299. self.assertAlmostEqual(summary["ratio_wall"], 12.0 / 35.0, places=4)
  300. def test_min_fps_gate_blocks_pass(self):
  301. strict = self.mod.summarize(
  302. self._producer_samples(period=100.0), target=0.70, min_fps=12.0
  303. )
  304. self.assertAlmostEqual(strict["fps"], 10.0, places=2)
  305. self.assertTrue(strict["pass_a"]) # 占比本身达标
  306. self.assertFalse(strict["pass_fps"]) # 但吞吐不达标
  307. self.assertFalse(strict["pass"])
  308. relaxed = self.mod.summarize(self._producer_samples(period=100.0), target=0.70)
  309. self.assertTrue(relaxed["pass"])
  310. def test_config_warnings_flag_the_three_traps(self):
  311. cfg = Config({"run": {"max_fps": 15.0}, "plc": {"gating": True}})
  312. text = "\n".join(self.mod._config_warnings(cfg))
  313. self.assertIn("gating", text)
  314. self.assertIn("max_fps", text)
  315. self.assertIn("--producer", text)
  316. # producer=True 时不再提示串行取帧
  317. no_serial = "\n".join(self.mod._config_warnings(cfg, producer=True))
  318. self.assertNotIn("--producer", no_serial)
  319. def test_empty_samples_raise(self):
  320. with self.assertRaises(ValueError):
  321. self.mod.summarize([], target=0.70)
  322. if __name__ == "__main__":
  323. unittest.main()