"""RKNN 部署相关单元测试(**不需要** RK 板卡 / rknnlite / 模型文件)。 覆盖四块新增/改动: 1. ``model.rknn_core`` 在核数不足的板子上被收敛为 auto,而不是让 ``init_runtime`` 报错; 2. NPU 负载节点解析(debugfs 多核 / devfreq 两种真实格式)+ core 数实测(debugfs); 3. 后处理向量化与标量版**逐框等价**(重构不许改行为); 4. ``scripts/rknpu_ratio.py`` 的两个口径汇总与判定。 """ import importlib.util import os import tempfile import unittest import numpy as np from portcv.config import Config from portcv.detect.postproc import decode_yolo_output from portcv.detect.preproc import to_blob, unletterbox_box from portcv.detect.rknn_backend import ( RknnDetector, detect_npu_cores, detect_npu_cores_live, model_chain_ratio, parse_npu_load, read_npu_load, resolve_core_mask, ) ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) LABELS = ["container", "bed", "flatbed"] def load_ratio_script(): """按路径加载 ``scripts/rknpu_ratio.py``(scripts 不是包)。""" path = os.path.join(ROOT, "scripts", "rknpu_ratio.py") spec = importlib.util.spec_from_file_location("rknpu_ratio", path) module = importlib.util.module_from_spec(spec) assert spec.loader is not None spec.loader.exec_module(module) return module class CoreMaskTests(unittest.TestCase): def test_auto_and_single_core_pass_through(self): self.assertEqual(resolve_core_mask("auto", 3), (0, "")) self.assertEqual(resolve_core_mask("0", 3), (1, "")) self.assertEqual(resolve_core_mask("1", 2), (2, "")) def test_core_index_beyond_board_is_clamped(self): # 单核板上配 core1:核数没超(1 个),但 core1 不存在 mask, note = resolve_core_mask("1", 1) self.assertEqual(mask, 0) self.assertIn("core 1", note) def test_multi_core_config_on_rk3588_is_kept(self): self.assertEqual(resolve_core_mask("0_1_2", 3), (7, "")) def test_multi_core_config_on_single_core_board_is_clamped(self): mask, note = resolve_core_mask("0_1_2", 1) self.assertEqual(mask, 0) self.assertIn("NPU core", note) self.assertIn("auto", note) def test_rk3576_dual_core_keeps_two_core_mask(self): # RK3576 是 2 核(rk3576_npu_irqs = npu0_irq + npu1_irq,板端 load 打印 Core0/Core1): # 0_1 必须原样保留;0_2 / 0_1_2 引用了不存在的 core2,才该收敛 self.assertEqual(resolve_core_mask("0_1", 2), (3, "")) self.assertEqual(resolve_core_mask("0_2", 2)[0], 0) self.assertIn("core 0/2", resolve_core_mask("0_2", 2)[1]) self.assertIn("auto", resolve_core_mask("0_1_2", 2)[1]) def test_unknown_board_does_not_clamp(self): self.assertEqual(resolve_core_mask("0_1_2", 0), (7, "")) def test_unknown_value_raises(self): with self.assertRaises(ValueError): resolve_core_mask("3", 3) def test_board_to_core_count(self): # RK3576 双核:内核 rknpu_drv.c 的 rk3576_npu_irqs[] 注册了 npu0_irq + npu1_irq self.assertEqual(detect_npu_cores("rockchip,rk3576-wxd-a576"), 2) self.assertEqual(detect_npu_cores("rk3588"), 3) self.assertEqual(detect_npu_cores("rk3568"), 1) self.assertEqual(detect_npu_cores(""), 0) self.assertEqual(detect_npu_cores("some-other-soc"), 0) class NpuCoreProbeTests(unittest.TestCase): """NPU core 数优先从 debugfs 实测(板端 dump 见 docs/deployment.md)。""" def _write(self, text): fd, path = tempfile.mkstemp(suffix=".load") with os.fdopen(fd, "w", encoding="utf-8") as fh: fh.write(text) self.addCleanup(os.unlink, path) return path def test_rk3576_real_dump_counts_two_cores(self): path = self._write("NPU load: Core0: 0%, Core1: 0%,") self.assertEqual(detect_npu_cores_live([path]), 2) def test_rk3588_real_dump_counts_three_cores(self): path = self._write("NPU load: Core0: 37%, Core1: 0%, Core2: 5%,") self.assertEqual(detect_npu_cores_live([path]), 3) def test_missing_or_odd_text_returns_zero(self): self.assertEqual(detect_npu_cores_live([os.path.join(tempfile.gettempdir(), "nope.load")]), 0) self.assertEqual(detect_npu_cores_live([self._write("load=42@1000000000Hz")]), 0) class NpuLoadTests(unittest.TestCase): def test_debugfs_multi_core_takes_busiest(self): text = "NPU load: Core0: 37%, Core1: 0%, Core2: 5%," self.assertAlmostEqual(parse_npu_load(text), 0.37) def test_devfreq_format(self): self.assertAlmostEqual(parse_npu_load("load=42@1000000000Hz"), 0.42) def test_rk3576_devfreq_raw_is_not_trusted(self): """RK3576 板端 devfreq 实际是 ``100@950000000Hz``,空闲也报 100 → 不许解析成功。 同一时刻 debugfs 是 ``Core0: 0%, Core1: 0%``(实测 2026-11-16,NPU driver v0.9.8)。 这条测试是**防回归**用的:谁要是把 ``(\\d+)@\\d+Hz`` 也认了,status 里的 NPU 占用率 就会在空跑时恒为 100%,把「驱动 idle 统计没生效」伪装成满负荷。 """ self.assertIsNone(parse_npu_load("100@950000000Hz\n")) def test_unparsable_returns_none_not_zero(self): self.assertIsNone(parse_npu_load("")) self.assertIsNone(parse_npu_load("nonsense")) self.assertIsNone(read_npu_load("C:/definitely/missing/npu/load")) class ToBlobTests(unittest.TestCase): def test_bgr_uint8_is_zero_copy(self): image = np.zeros((8, 8, 3), dtype=np.uint8) blob = to_blob(image, "bgr_uint8") self.assertEqual(blob.shape, (1, 8, 8, 3)) self.assertTrue(np.shares_memory(blob, image)) def test_rgb_uint8_flips_channels(self): image = np.zeros((2, 2, 3), dtype=np.uint8) image[..., 0] = 10 # B image[..., 2] = 200 # R blob = to_blob(image, "rgb_uint8") self.assertEqual(int(blob[0, 0, 0, 0]), 200) self.assertEqual(int(blob[0, 0, 0, 2]), 10) def test_rgb_float_is_nchw(self): blob = to_blob(np.full((4, 6, 3), 255, dtype=np.uint8), "rgb_float") self.assertEqual(blob.shape, (1, 3, 4, 6)) self.assertEqual(blob.dtype, np.float32) self.assertAlmostEqual(float(blob[0, 0, 0, 0]), 1.0) def test_unknown_format_raises(self): with self.assertRaises(ValueError): to_blob(np.zeros((2, 2, 3), dtype=np.uint8), "yuv420") def _scalar_xywh(raw, labels, conf, ratio, pad, image_size): """重构前的标量实现(参照物):逐框调用 ``unletterbox_box``。""" arr = np.asarray(raw, dtype=np.float32) while arr.ndim > 2: arr = arr[0] nc = len(labels) # 与 _as_2d 一致:导出常见 (C, N) 布局,需要转置成 (N, C) if arr.shape[1] not in (4 + nc, 5 + nc, 6) and arr.shape[0] in (4 + nc, 5 + nc, 6): arr = arr.T arr = np.ascontiguousarray(arr) cls_scores = arr[:, 4 : 4 + nc] cls_ids = np.argmax(cls_scores, axis=1) scores = cls_scores[np.arange(len(cls_ids)), cls_ids] rows = [] for i in range(len(arr)): if scores[i] < conf: continue x1 = float(arr[i, 0] - arr[i, 2] / 2.0) y1 = float(arr[i, 1] - arr[i, 3] / 2.0) x2 = float(arr[i, 0] + arr[i, 2] / 2.0) y2 = float(arr[i, 1] + arr[i, 3] / 2.0) rx1, ry1, rx2, ry2 = unletterbox_box(x1, y1, x2, y2, ratio, pad, image_size) if rx2 - rx1 < 1 or ry2 - ry1 < 1: continue rows.append((rx1, ry1, rx2, ry2, float(scores[i]), int(cls_ids[i]))) return rows class VectorizedDecodeTests(unittest.TestCase): def setUp(self): rng = np.random.default_rng(7) n = 40 arr = np.zeros((1, 4 + len(LABELS), n), dtype=np.float32) arr[0, 0] = rng.uniform(0.0, 220.0, n) # cx arr[0, 1] = rng.uniform(0.0, 160.0, n) # cy arr[0, 2] = rng.uniform(1.0, 120.0, n) # w arr[0, 3] = rng.uniform(1.0, 120.0, n) # h arr[0, 4] = rng.uniform(0.0, 1.0, n) arr[0, 5] = rng.uniform(0.0, 1.0, n) arr[0, 6] = rng.uniform(0.0, 1.0, n) self.raw = np.ascontiguousarray(arr) self.ratio = 0.5 self.pad = (12.0, 30.0) self.size = (640, 480) def _decode(self): return decode_yolo_output( self.raw, labels=LABELS, conf_thres=0.2, iou_thres=0.5, max_det=100, ratio=self.ratio, pad=self.pad, image_size=self.size, apply_nms=False, ) def test_matches_scalar_reference(self): expected = _scalar_xywh(self.raw, LABELS, 0.2, self.ratio, self.pad, self.size) got = self._decode() self.assertEqual(len(got), len(expected)) for box, row in zip(got, expected): self.assertAlmostEqual(box.x1, row[0], places=6) self.assertAlmostEqual(box.y1, row[1], places=6) self.assertAlmostEqual(box.x2, row[2], places=6) self.assertAlmostEqual(box.y2, row[3], places=6) self.assertAlmostEqual(box.score, row[4], places=6) self.assertEqual(box.class_id, row[5]) self.assertEqual(box.class_name, LABELS[row[5]]) def test_coords_are_clipped_to_image(self): for box in self._decode(): self.assertGreaterEqual(box.x1, 0.0) self.assertLessEqual(box.x2, float(self.size[0])) self.assertGreaterEqual(box.y1, 0.0) self.assertLessEqual(box.y2, float(self.size[1])) def test_nms_free_path_matches_scalar(self): rows = np.array( [ [10.0, 20.0, 110.0, 120.0, 0.9, 0.0], [10.0, 20.0, 110.0, 120.0, 0.1, 0.0], # 低于 conf [5.0, 5.0, 5.4, 5.4, 0.8, 1.0], # 还原后 < 1 px → 丢弃 ], dtype=np.float32, ) got = decode_yolo_output( rows[None], labels=LABELS, conf_thres=0.35, ratio=1.0, pad=(0.0, 0.0), image_size=(640, 480), nms_free=True, ) self.assertEqual(len(got), 1) self.assertAlmostEqual(got[0].x1, 10.0, places=5) self.assertEqual(got[0].class_name, "container") class _StubRuntime: """假 rknnlite runtime:记录调用参数,返回固定的检测头张量。""" def __init__(self, outputs): self.outputs = outputs self.calls = [] self.released = False def inference(self, inputs=None, data_format=None): self.calls.append({"data_format": data_format, "shape": inputs[0].shape}) return self.outputs def release(self): self.released = True class RknnDetectorTests(unittest.TestCase): def _cfg(self, input_format): return Config( { "run": {"backend": "rknn"}, "model": {"input_format": input_format, "input_size": [64, 64], "labels": LABELS}, } ) def _detector(self, input_format): outputs = [np.zeros((1, 4 + len(LABELS), 5), dtype=np.float32)] stub = _StubRuntime(outputs) detector = RknnDetector(self._cfg(input_format)) detector.rknn = stub # 绕过 load(),避免依赖 rknnlite return detector, stub def test_uint8_input_declares_nhwc(self): detector, stub = self._detector("bgr_uint8") boxes = detector.infer(np.zeros((48, 64, 3), dtype=np.uint8)) self.assertEqual(boxes, []) self.assertEqual(stub.calls[0]["data_format"], "nhwc") self.assertEqual(tuple(stub.calls[0]["shape"]), (1, 64, 64, 3)) def test_float_input_declares_nchw(self): detector, stub = self._detector("rgb_float") detector.infer(np.zeros((48, 64, 3), dtype=np.uint8)) # to_blob(rgb_float) 给的是 NCHW;rknnlite 不给 data_format 时会自己猜布局,猜错 # **不报错**(RK3576 实测 cos 1.000000 → 0.986824,5 个真框 → 13 个假框), # 所以必须显式声明。 self.assertEqual(stub.calls[0]["data_format"], "nchw") self.assertEqual(tuple(stub.calls[0]["shape"]), (1, 3, 64, 64)) def test_stage_timings_and_describe(self): detector, _ = self._detector("bgr_uint8") detector.infer(np.zeros((48, 64, 3), dtype=np.uint8)) self.assertEqual(set(detector.stage_ms), {"preproc", "npu", "postproc"}) info = detector.describe() self.assertIn("stage_ms", info) self.assertIn("core_mask", info) self.assertEqual(info["npu_cores"], detect_npu_cores(detector.board)) def test_close_releases_runtime(self): detector, stub = self._detector("bgr_uint8") detector.close() self.assertTrue(stub.released) self.assertIsNone(detector.rknn) class ModelChainRatioTests(unittest.TestCase): """口径 B 的实时版本:``describe()`` / status 用它,脚本用 ``ratio_b``,两者必须同义。""" def test_ratio_is_npu_over_model_chain(self): self.assertAlmostEqual( model_chain_ratio({"preproc": 2.0, "npu": 10.0, "postproc": 3.0}), 10.0 / 15.0, places=6, ) def test_missing_or_zero_stage_returns_none(self): self.assertIsNone(model_chain_ratio(None)) self.assertIsNone(model_chain_ratio({})) self.assertIsNone(model_chain_ratio({"preproc": 0.0, "npu": 0.0, "postproc": 0.0})) class RatioSummaryTests(unittest.TestCase): def setUp(self): self.mod = load_ratio_script() def _samples(self, npu, preproc=2.0, postproc=3.0, decode=5.0, load=0.5): return [ { "decode_ms": decode, "preproc_ms": preproc, "npu_ms": npu, "postproc_ms": postproc, "npu_load": load, } for _ in range(10) ] def test_two_ratios_differ_by_decode(self): summary = self.mod.summarize(self._samples(10.0), target=0.70) self.assertAlmostEqual(summary["ratio_a"], 0.5, places=4) # 10 / (5+2+10+3) self.assertAlmostEqual(summary["ratio_b"], 10.0 / 15.0, places=4) self.assertFalse(summary["pass_a"]) self.assertFalse(summary["pass_b"]) def test_target_is_respected(self): summary = self.mod.summarize(self._samples(10.0), target=0.49) self.assertTrue(summary["pass_a"]) def test_zero_npu_means_zero_ratio(self): summary = self.mod.summarize(self._samples(0.0), target=0.70) self.assertEqual(summary["ratio_a"], 0.0) self.assertFalse(summary["pass_a"]) def test_extra_ms_lowers_ratio(self): base = self.mod.summarize(self._samples(10.0), target=0.70) with_extra = self.mod.summarize(self._samples(10.0), target=0.70, extra_ms=10.0) self.assertLess(with_extra["ratio_a"], base["ratio_a"]) def test_missing_load_reported_as_null(self): summary = self.mod.summarize(self._samples(10.0, load=None), target=0.70) self.assertIsNone(summary["npu_load"]["mean"]) self.assertIn("无法读取", self.mod.format_report(summary)) def test_report_mentions_both_metrics(self): text = self.mod.format_report(self.mod.summarize(self._samples(10.0), target=0.70)) self.assertIn("口径A", text) self.assertIn("口径B", text) self.assertIn("FAIL", text) def _producer_samples(self, npu=12.0, preproc=2.0, postproc=1.0, wait=20.0, period=35.0): """``--producer`` 模式的采样:decode=0,等帧单列 ``wait_ms``,模型链固定 15 ms。""" return [ { "decode_ms": 0.0, "wait_ms": wait, "period_ms": period, "preproc_ms": preproc, "npu_ms": npu, "postproc_ms": postproc, "npu_load": 0.5, } for _ in range(10) ] def test_producer_wait_is_not_in_ratio_a(self): summary = self.mod.summarize(self._producer_samples(), target=0.70) self.assertAlmostEqual(summary["ratio_a"], 12.0 / 15.0, places=4) # 等帧 20 ms 只进 wall 口径:12 / (15 + 20) self.assertAlmostEqual(summary["ratio_wall"], 12.0 / 35.0, places=4) def test_min_fps_gate_blocks_pass(self): strict = self.mod.summarize( self._producer_samples(period=100.0), target=0.70, min_fps=12.0 ) self.assertAlmostEqual(strict["fps"], 10.0, places=2) self.assertTrue(strict["pass_a"]) # 占比本身达标 self.assertFalse(strict["pass_fps"]) # 但吞吐不达标 self.assertFalse(strict["pass"]) relaxed = self.mod.summarize(self._producer_samples(period=100.0), target=0.70) self.assertTrue(relaxed["pass"]) def test_config_warnings_flag_the_three_traps(self): cfg = Config({"run": {"max_fps": 15.0}, "plc": {"gating": True}}) text = "\n".join(self.mod._config_warnings(cfg)) self.assertIn("gating", text) self.assertIn("max_fps", text) self.assertIn("--producer", text) # producer=True 时不再提示串行取帧 no_serial = "\n".join(self.mod._config_warnings(cfg, producer=True)) self.assertNotIn("--producer", no_serial) def test_empty_samples_raise(self): with self.assertRaises(ValueError): self.mod.summarize([], target=0.70) if __name__ == "__main__": unittest.main()