test_rknn_ops.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  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_rk3576_devfreq_raw_is_not_trusted(self):
  95. """RK3576 板端 devfreq 实际是 ``100@950000000Hz``,空闲也报 100 → 不许解析成功。
  96. 同一时刻 debugfs 是 ``Core0: 0%, Core1: 0%``(实测 2026-11-16,NPU driver v0.9.8)。
  97. 这条测试是**防回归**用的:谁要是把 ``(\\d+)@\\d+Hz`` 也认了,status 里的 NPU 占用率
  98. 就会在空跑时恒为 100%,把「驱动 idle 统计没生效」伪装成满负荷。
  99. """
  100. self.assertIsNone(parse_npu_load("100@950000000Hz\n"))
  101. def test_unparsable_returns_none_not_zero(self):
  102. self.assertIsNone(parse_npu_load(""))
  103. self.assertIsNone(parse_npu_load("nonsense"))
  104. self.assertIsNone(read_npu_load("C:/definitely/missing/npu/load"))
  105. class ToBlobTests(unittest.TestCase):
  106. def test_bgr_uint8_is_zero_copy(self):
  107. image = np.zeros((8, 8, 3), dtype=np.uint8)
  108. blob = to_blob(image, "bgr_uint8")
  109. self.assertEqual(blob.shape, (1, 8, 8, 3))
  110. self.assertTrue(np.shares_memory(blob, image))
  111. def test_rgb_uint8_flips_channels(self):
  112. image = np.zeros((2, 2, 3), dtype=np.uint8)
  113. image[..., 0] = 10 # B
  114. image[..., 2] = 200 # R
  115. blob = to_blob(image, "rgb_uint8")
  116. self.assertEqual(int(blob[0, 0, 0, 0]), 200)
  117. self.assertEqual(int(blob[0, 0, 0, 2]), 10)
  118. def test_rgb_float_is_nchw(self):
  119. blob = to_blob(np.full((4, 6, 3), 255, dtype=np.uint8), "rgb_float")
  120. self.assertEqual(blob.shape, (1, 3, 4, 6))
  121. self.assertEqual(blob.dtype, np.float32)
  122. self.assertAlmostEqual(float(blob[0, 0, 0, 0]), 1.0)
  123. def test_unknown_format_raises(self):
  124. with self.assertRaises(ValueError):
  125. to_blob(np.zeros((2, 2, 3), dtype=np.uint8), "yuv420")
  126. def _scalar_xywh(raw, labels, conf, ratio, pad, image_size):
  127. """重构前的标量实现(参照物):逐框调用 ``unletterbox_box``。"""
  128. arr = np.asarray(raw, dtype=np.float32)
  129. while arr.ndim > 2:
  130. arr = arr[0]
  131. nc = len(labels)
  132. # 与 _as_2d 一致:导出常见 (C, N) 布局,需要转置成 (N, C)
  133. if arr.shape[1] not in (4 + nc, 5 + nc, 6) and arr.shape[0] in (4 + nc, 5 + nc, 6):
  134. arr = arr.T
  135. arr = np.ascontiguousarray(arr)
  136. cls_scores = arr[:, 4 : 4 + nc]
  137. cls_ids = np.argmax(cls_scores, axis=1)
  138. scores = cls_scores[np.arange(len(cls_ids)), cls_ids]
  139. rows = []
  140. for i in range(len(arr)):
  141. if scores[i] < conf:
  142. continue
  143. x1 = float(arr[i, 0] - arr[i, 2] / 2.0)
  144. y1 = float(arr[i, 1] - arr[i, 3] / 2.0)
  145. x2 = float(arr[i, 0] + arr[i, 2] / 2.0)
  146. y2 = float(arr[i, 1] + arr[i, 3] / 2.0)
  147. rx1, ry1, rx2, ry2 = unletterbox_box(x1, y1, x2, y2, ratio, pad, image_size)
  148. if rx2 - rx1 < 1 or ry2 - ry1 < 1:
  149. continue
  150. rows.append((rx1, ry1, rx2, ry2, float(scores[i]), int(cls_ids[i])))
  151. return rows
  152. class VectorizedDecodeTests(unittest.TestCase):
  153. def setUp(self):
  154. rng = np.random.default_rng(7)
  155. n = 40
  156. arr = np.zeros((1, 4 + len(LABELS), n), dtype=np.float32)
  157. arr[0, 0] = rng.uniform(0.0, 220.0, n) # cx
  158. arr[0, 1] = rng.uniform(0.0, 160.0, n) # cy
  159. arr[0, 2] = rng.uniform(1.0, 120.0, n) # w
  160. arr[0, 3] = rng.uniform(1.0, 120.0, n) # h
  161. arr[0, 4] = rng.uniform(0.0, 1.0, n)
  162. arr[0, 5] = rng.uniform(0.0, 1.0, n)
  163. arr[0, 6] = rng.uniform(0.0, 1.0, n)
  164. self.raw = np.ascontiguousarray(arr)
  165. self.ratio = 0.5
  166. self.pad = (12.0, 30.0)
  167. self.size = (640, 480)
  168. def _decode(self):
  169. return decode_yolo_output(
  170. self.raw,
  171. labels=LABELS,
  172. conf_thres=0.2,
  173. iou_thres=0.5,
  174. max_det=100,
  175. ratio=self.ratio,
  176. pad=self.pad,
  177. image_size=self.size,
  178. apply_nms=False,
  179. )
  180. def test_matches_scalar_reference(self):
  181. expected = _scalar_xywh(self.raw, LABELS, 0.2, self.ratio, self.pad, self.size)
  182. got = self._decode()
  183. self.assertEqual(len(got), len(expected))
  184. for box, row in zip(got, expected):
  185. self.assertAlmostEqual(box.x1, row[0], places=6)
  186. self.assertAlmostEqual(box.y1, row[1], places=6)
  187. self.assertAlmostEqual(box.x2, row[2], places=6)
  188. self.assertAlmostEqual(box.y2, row[3], places=6)
  189. self.assertAlmostEqual(box.score, row[4], places=6)
  190. self.assertEqual(box.class_id, row[5])
  191. self.assertEqual(box.class_name, LABELS[row[5]])
  192. def test_coords_are_clipped_to_image(self):
  193. for box in self._decode():
  194. self.assertGreaterEqual(box.x1, 0.0)
  195. self.assertLessEqual(box.x2, float(self.size[0]))
  196. self.assertGreaterEqual(box.y1, 0.0)
  197. self.assertLessEqual(box.y2, float(self.size[1]))
  198. def test_nms_free_path_matches_scalar(self):
  199. rows = np.array(
  200. [
  201. [10.0, 20.0, 110.0, 120.0, 0.9, 0.0],
  202. [10.0, 20.0, 110.0, 120.0, 0.1, 0.0], # 低于 conf
  203. [5.0, 5.0, 5.4, 5.4, 0.8, 1.0], # 还原后 < 1 px → 丢弃
  204. ],
  205. dtype=np.float32,
  206. )
  207. got = decode_yolo_output(
  208. rows[None],
  209. labels=LABELS,
  210. conf_thres=0.35,
  211. ratio=1.0,
  212. pad=(0.0, 0.0),
  213. image_size=(640, 480),
  214. nms_free=True,
  215. )
  216. self.assertEqual(len(got), 1)
  217. self.assertAlmostEqual(got[0].x1, 10.0, places=5)
  218. self.assertEqual(got[0].class_name, "container")
  219. class _StubRuntime:
  220. """假 rknnlite runtime:记录调用参数,返回固定的检测头张量。"""
  221. def __init__(self, outputs):
  222. self.outputs = outputs
  223. self.calls = []
  224. self.released = False
  225. def inference(self, inputs=None, data_format=None):
  226. self.calls.append({"data_format": data_format, "shape": inputs[0].shape})
  227. return self.outputs
  228. def release(self):
  229. self.released = True
  230. class RknnDetectorTests(unittest.TestCase):
  231. def _cfg(self, input_format):
  232. return Config(
  233. {
  234. "run": {"backend": "rknn"},
  235. "model": {"input_format": input_format, "input_size": [64, 64], "labels": LABELS},
  236. }
  237. )
  238. def _detector(self, input_format):
  239. outputs = [np.zeros((1, 4 + len(LABELS), 5), dtype=np.float32)]
  240. stub = _StubRuntime(outputs)
  241. detector = RknnDetector(self._cfg(input_format))
  242. detector.rknn = stub # 绕过 load(),避免依赖 rknnlite
  243. return detector, stub
  244. def test_uint8_input_declares_nhwc(self):
  245. detector, stub = self._detector("bgr_uint8")
  246. boxes = detector.infer(np.zeros((48, 64, 3), dtype=np.uint8))
  247. self.assertEqual(boxes, [])
  248. self.assertEqual(stub.calls[0]["data_format"], "nhwc")
  249. self.assertEqual(tuple(stub.calls[0]["shape"]), (1, 64, 64, 3))
  250. def test_float_input_declares_nchw(self):
  251. detector, stub = self._detector("rgb_float")
  252. detector.infer(np.zeros((48, 64, 3), dtype=np.uint8))
  253. # to_blob(rgb_float) 给的是 NCHW;rknnlite 不给 data_format 时会自己猜布局,猜错
  254. # **不报错**(RK3576 实测 cos 1.000000 → 0.986824,5 个真框 → 13 个假框),
  255. # 所以必须显式声明。
  256. self.assertEqual(stub.calls[0]["data_format"], "nchw")
  257. self.assertEqual(tuple(stub.calls[0]["shape"]), (1, 3, 64, 64))
  258. def test_stage_timings_and_describe(self):
  259. detector, _ = self._detector("bgr_uint8")
  260. detector.infer(np.zeros((48, 64, 3), dtype=np.uint8))
  261. self.assertEqual(set(detector.stage_ms), {"preproc", "npu", "postproc"})
  262. info = detector.describe()
  263. self.assertIn("stage_ms", info)
  264. self.assertIn("core_mask", info)
  265. self.assertEqual(info["npu_cores"], detect_npu_cores(detector.board))
  266. def test_close_releases_runtime(self):
  267. detector, stub = self._detector("bgr_uint8")
  268. detector.close()
  269. self.assertTrue(stub.released)
  270. self.assertIsNone(detector.rknn)
  271. class ModelChainRatioTests(unittest.TestCase):
  272. """口径 B 的实时版本:``describe()`` / status 用它,脚本用 ``ratio_b``,两者必须同义。"""
  273. def test_ratio_is_npu_over_model_chain(self):
  274. self.assertAlmostEqual(
  275. model_chain_ratio({"preproc": 2.0, "npu": 10.0, "postproc": 3.0}),
  276. 10.0 / 15.0,
  277. places=6,
  278. )
  279. def test_missing_or_zero_stage_returns_none(self):
  280. self.assertIsNone(model_chain_ratio(None))
  281. self.assertIsNone(model_chain_ratio({}))
  282. self.assertIsNone(model_chain_ratio({"preproc": 0.0, "npu": 0.0, "postproc": 0.0}))
  283. class RatioSummaryTests(unittest.TestCase):
  284. def setUp(self):
  285. self.mod = load_ratio_script()
  286. def _samples(self, npu, preproc=2.0, postproc=3.0, decode=5.0, load=0.5):
  287. return [
  288. {
  289. "decode_ms": decode,
  290. "preproc_ms": preproc,
  291. "npu_ms": npu,
  292. "postproc_ms": postproc,
  293. "npu_load": load,
  294. }
  295. for _ in range(10)
  296. ]
  297. def test_two_ratios_differ_by_decode(self):
  298. summary = self.mod.summarize(self._samples(10.0), target=0.70)
  299. self.assertAlmostEqual(summary["ratio_a"], 0.5, places=4) # 10 / (5+2+10+3)
  300. self.assertAlmostEqual(summary["ratio_b"], 10.0 / 15.0, places=4)
  301. self.assertFalse(summary["pass_a"])
  302. self.assertFalse(summary["pass_b"])
  303. def test_target_is_respected(self):
  304. summary = self.mod.summarize(self._samples(10.0), target=0.49)
  305. self.assertTrue(summary["pass_a"])
  306. def test_zero_npu_means_zero_ratio(self):
  307. summary = self.mod.summarize(self._samples(0.0), target=0.70)
  308. self.assertEqual(summary["ratio_a"], 0.0)
  309. self.assertFalse(summary["pass_a"])
  310. def test_extra_ms_lowers_ratio(self):
  311. base = self.mod.summarize(self._samples(10.0), target=0.70)
  312. with_extra = self.mod.summarize(self._samples(10.0), target=0.70, extra_ms=10.0)
  313. self.assertLess(with_extra["ratio_a"], base["ratio_a"])
  314. def test_missing_load_reported_as_null(self):
  315. summary = self.mod.summarize(self._samples(10.0, load=None), target=0.70)
  316. self.assertIsNone(summary["npu_load"]["mean"])
  317. self.assertIn("无法读取", self.mod.format_report(summary))
  318. def test_report_mentions_both_metrics(self):
  319. text = self.mod.format_report(self.mod.summarize(self._samples(10.0), target=0.70))
  320. self.assertIn("口径A", text)
  321. self.assertIn("口径B", text)
  322. self.assertIn("FAIL", text)
  323. def _producer_samples(self, npu=12.0, preproc=2.0, postproc=1.0, wait=20.0, period=35.0):
  324. """``--producer`` 模式的采样:decode=0,等帧单列 ``wait_ms``,模型链固定 15 ms。"""
  325. return [
  326. {
  327. "decode_ms": 0.0,
  328. "wait_ms": wait,
  329. "period_ms": period,
  330. "preproc_ms": preproc,
  331. "npu_ms": npu,
  332. "postproc_ms": postproc,
  333. "npu_load": 0.5,
  334. }
  335. for _ in range(10)
  336. ]
  337. def test_producer_wait_is_not_in_ratio_a(self):
  338. summary = self.mod.summarize(self._producer_samples(), target=0.70)
  339. self.assertAlmostEqual(summary["ratio_a"], 12.0 / 15.0, places=4)
  340. # 等帧 20 ms 只进 wall 口径:12 / (15 + 20)
  341. self.assertAlmostEqual(summary["ratio_wall"], 12.0 / 35.0, places=4)
  342. def test_min_fps_gate_blocks_pass(self):
  343. strict = self.mod.summarize(
  344. self._producer_samples(period=100.0), target=0.70, min_fps=12.0
  345. )
  346. self.assertAlmostEqual(strict["fps"], 10.0, places=2)
  347. self.assertTrue(strict["pass_a"]) # 占比本身达标
  348. self.assertFalse(strict["pass_fps"]) # 但吞吐不达标
  349. self.assertFalse(strict["pass"])
  350. relaxed = self.mod.summarize(self._producer_samples(period=100.0), target=0.70)
  351. self.assertTrue(relaxed["pass"])
  352. def test_config_warnings_flag_the_three_traps(self):
  353. cfg = Config({"run": {"max_fps": 15.0}, "plc": {"gating": True}})
  354. text = "\n".join(self.mod._config_warnings(cfg))
  355. self.assertIn("gating", text)
  356. self.assertIn("max_fps", text)
  357. self.assertIn("--producer", text)
  358. # producer=True 时不再提示串行取帧
  359. no_serial = "\n".join(self.mod._config_warnings(cfg, producer=True))
  360. self.assertNotIn("--producer", no_serial)
  361. def test_empty_samples_raise(self):
  362. with self.assertRaises(ValueError):
  363. self.mod.summarize([], target=0.70)
  364. if __name__ == "__main__":
  365. unittest.main()