"""``portcv.model_graph`` 的单元测试:ONNX 图里插「BGR→RGB 通道反转」节点。 为什么值得测: 1. 这是 ``model.input_format=bgr_uint8``(唯一零拷贝路径)的**前提**——节点少插一次, 板子上的颜色就是错的,而且往往只是掉几个点,现场发现不了; 2. 插节点要重定向**所有**消费者,漏一个就有一支分支吃错颜色; 3. 重复执行必须是 no-op(转换流水线可能跑两遍),否则通道会被反两次; 4. ``scripts/onnx_to_rknn.py`` 必须在「配置写 bgr_uint8 但模型没反通道」时**先拦住**, 而不是转完才发现颜色错了。 需要 ``onnx``(可选依赖);没装时整组跳过。 """ import contextlib import importlib.util import io import json import os import tempfile import unittest import numpy as np try: # onnx 是可选依赖,没有就跳过整组 import onnx # noqa: F401 from onnx import TensorProto, helper, numpy_helper HAVE_ONNX = True except ImportError: # pragma: no cover - 只在没装 onnx 的环境 HAVE_ONNX = False from portcv.model_graph import ( BGR_IDX_TENSOR, has_channel_reversal, insert_channel_reversal, verify_reversal, ) ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) def load_script(name: str): """按路径加载 ``scripts/.py``(scripts 不是包,沿用 test_rknn_ops 的写法)。""" path = os.path.join(ROOT, "scripts", name + ".py") spec = importlib.util.spec_from_file_location(name, path) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) return module def build_model(nhwc: bool = False, channels: int = 3): """迷你模型:**两个消费者**共用输入,便于验证「所有消费者都被重定向」。 ``y = (x * w) + (x + b)``:每个通道有各自的系数,通道顺序一变结果立刻不同。 """ shape = [1, 4, 5, channels] if nhwc else [1, channels, 4, 5] param_shape = [1, 1, 1, channels] if nhwc else [1, channels, 1, 1] x = helper.make_tensor_value_info("images", TensorProto.FLOAT, shape) y = helper.make_tensor_value_info("output0", TensorProto.FLOAT, shape) scale = np.arange(1, channels + 1, dtype=np.float32).reshape(param_shape) shift = np.arange(1, channels + 1, dtype=np.float32).reshape(param_shape) graph = helper.make_graph( [ helper.make_node("Mul", ["images", "w"], ["scaled"]), helper.make_node("Add", ["images", "b"], ["shifted"]), helper.make_node("Add", ["scaled", "shifted"], ["output0"]), ], "tiny_rgb_model", [x], [y], [numpy_helper.from_array(scale, "w"), numpy_helper.from_array(shift, "b")], ) model = helper.make_model(graph, opset_imports=[helper.make_opsetid("", 13)]) model.ir_version = 8 onnx.checker.check_model(model) return model def build_shape_model(dims): """按给定输入维度造一个单节点模型(用来测维度报错分支)。""" x = helper.make_tensor_value_info("images", TensorProto.FLOAT, dims) y = helper.make_tensor_value_info("output0", TensorProto.FLOAT, None) w = numpy_helper.from_array(np.ones([1], dtype=np.float32), "w") graph = helper.make_graph( [helper.make_node("Mul", ["images", "w"], ["output0"])], "shape_model", [x], [y], [w] ) return helper.make_model(graph, opset_imports=[helper.make_opsetid("", 13)]) @unittest.skipUnless(HAVE_ONNX, "需要 onnx:pip install onnx") class InsertReversalTests(unittest.TestCase): def test_gather_is_inserted_first_and_redirects_every_consumer(self): model = build_model() info = insert_channel_reversal(model) self.assertTrue(info["inserted"]) self.assertEqual(info["axis"], 1) # NCHW → 通道轴 1 self.assertEqual(info["consumers"], 2) # Mul 和 Add 两个消费者 self.assertEqual(model.graph.node[0].op_type, "Gather") self.assertEqual(info["output"], model.graph.node[0].output[0]) self.assertTrue(any(init.name == BGR_IDX_TENSOR for init in model.graph.initializer)) # 原来的两个消费者都改成吃反通道后的张量,输入本身没人直接用了 for node in list(model.graph.node)[1:]: self.assertNotIn("images", list(node.input)) onnx.checker.check_model(model) def test_second_insert_is_noop(self): model = build_model() first = insert_channel_reversal(model) node_count = len(model.graph.node) second = insert_channel_reversal(model) self.assertTrue(first["inserted"]) self.assertFalse(second["inserted"]) self.assertEqual(len(model.graph.node), node_count) # 不会反两次 def test_nhwc_model_gets_axis_3(self): model = build_model(nhwc=True) info = insert_channel_reversal(model) self.assertEqual(info["axis"], 3) def test_has_channel_reversal_flips_after_insert(self): model = build_model() self.assertFalse(has_channel_reversal(model)) insert_channel_reversal(model) self.assertTrue(has_channel_reversal(model)) def test_unknown_input_name_raises(self): with self.assertRaises(ValueError): insert_channel_reversal(build_model(), input_name="pixel_values") def test_rank_three_input_raises(self): with self.assertRaises(ValueError): insert_channel_reversal(build_shape_model([1, 3, 4])) def test_dynamic_channel_raises_with_actionable_message(self): with self.assertRaises(ValueError) as ctx: insert_channel_reversal(build_shape_model(["N", "C", 4, 5])) self.assertIn("3 通道", str(ctx.exception)) def test_control_flow_subgraph_reference_raises(self): """If/Loop 子图里引用输入时,只改主图会漏,必须报错让人手工处理。""" shape = [1, 3, 4, 5] out = helper.make_tensor_value_info("branch_out", TensorProto.FLOAT, shape) branches = [ helper.make_graph( [helper.make_node("Identity", ["images"], ["branch_out"])], name, [], [out] ) for name in ("then_branch", "else_branch") ] graph = helper.make_graph( [ helper.make_node( "If", ["cond"], ["picked"], then_branch=branches[0], else_branch=branches[1], ), helper.make_node("Identity", ["picked"], ["output0"]), ], "control_flow", [helper.make_tensor_value_info("images", TensorProto.FLOAT, shape)], [helper.make_tensor_value_info("output0", TensorProto.FLOAT, shape)], [numpy_helper.from_array(np.array(True, dtype=np.bool_), "cond")], ) model = helper.make_model(graph, opset_imports=[helper.make_opsetid("", 13)]) with self.assertRaises(ValueError) as ctx: insert_channel_reversal(model) self.assertIn("子图", str(ctx.exception)) @unittest.skipUnless(HAVE_ONNX, "需要 onnx:pip install onnx") class VerifyReversalTests(unittest.TestCase): def test_bgr_input_is_equivalent_to_rgb_input(self): before = build_model() after = build_model() insert_channel_reversal(after) result = verify_reversal(before, after) self.assertTrue(result["ok"]) self.assertLess(result["max_abs_diff"], 1e-6) # 不反通道时结果必须真的不同,否则这个节点是白插的 self.assertGreater(result["diff_without_reversal"], 1e-3) def test_nhwc_verification_uses_last_axis(self): before = build_model(nhwc=True) after = build_model(nhwc=True) insert_channel_reversal(after) result = verify_reversal(before, after) self.assertTrue(result["ok"]) self.assertEqual(result["axis"], 3) @unittest.skipUnless(HAVE_ONNX, "需要 onnx:pip install onnx") class ConvertGateTests(unittest.TestCase): """``scripts/onnx_to_rknn.py`` 的闸门:配置写 ``bgr_uint8`` 就得有反通道节点。""" def setUp(self): self._tmp = tempfile.TemporaryDirectory() self.addCleanup(self._tmp.cleanup) self.dir = self._tmp.name with contextlib.redirect_stdout(io.StringIO()): self.script = load_script("onnx_to_rknn") def _save(self, name: str, model) -> str: path = os.path.join(self.dir, name) onnx.save(model, path) return path def _config(self, input_format: str = "bgr_uint8") -> str: path = os.path.join(self.dir, "cfg.json") with open(path, "w", encoding="utf-8") as fh: json.dump( { "run": {"backend": "rknn"}, "model": { "input_format": input_format, "input_size": [640, 640], "rknn_path": os.path.join(self.dir, "model.rknn"), }, }, fh, ) return path def test_missing_node_raises_with_fix_command(self): path = self._save("plain.onnx", build_model()) with self.assertRaises(RuntimeError) as ctx: with contextlib.redirect_stdout(io.StringIO()): self.script.check_bgr_input(path) message = str(ctx.exception) self.assertIn("onnx_bgr_input.py", message) # 报错里直接给修复命令 self.assertIn("bgr_uint8", message) def test_inserted_node_passes(self): model = build_model() insert_channel_reversal(model) path = self._save("bgr.onnx", model) with contextlib.redirect_stdout(io.StringIO()): self.assertIsNone(self.script.check_bgr_input(path)) # 不抛异常 def test_main_stops_before_rknn_toolkit(self): """闸门必须在 ``convert()`` 之前触发,否则没装 rknn-toolkit2 时会报成另一个错。""" onnx_path = self._save("plain.onnx", build_model()) cfg = self._config() with self.assertRaises(RuntimeError) as ctx: with contextlib.redirect_stdout(io.StringIO()): self.script.main(["--onnx", onnx_path, "--config", cfg, "--no-quantize"]) self.assertIn("反通道节点", str(ctx.exception)) self.assertNotIn("rknn-toolkit2", str(ctx.exception))