test_rknn_ops.py 17 KB

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