test_model_graph.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. """``portcv.model_graph`` 的单元测试:ONNX 图里插「BGR→RGB 通道反转」节点。
  2. 为什么值得测:
  3. 1. 这是 ``model.input_format=bgr_uint8``(唯一零拷贝路径)的**前提**——节点少插一次,
  4. 板子上的颜色就是错的,而且往往只是掉几个点,现场发现不了;
  5. 2. 插节点要重定向**所有**消费者,漏一个就有一支分支吃错颜色;
  6. 3. 重复执行必须是 no-op(转换流水线可能跑两遍),否则通道会被反两次;
  7. 4. ``scripts/onnx_to_rknn.py`` 必须在「配置写 bgr_uint8 但模型没反通道」时**先拦住**,
  8. 而不是转完才发现颜色错了。
  9. 需要 ``onnx``(可选依赖);没装时整组跳过。
  10. """
  11. import contextlib
  12. import importlib.util
  13. import io
  14. import json
  15. import os
  16. import tempfile
  17. import unittest
  18. import numpy as np
  19. try: # onnx 是可选依赖,没有就跳过整组
  20. import onnx # noqa: F401
  21. from onnx import TensorProto, helper, numpy_helper
  22. HAVE_ONNX = True
  23. except ImportError: # pragma: no cover - 只在没装 onnx 的环境
  24. HAVE_ONNX = False
  25. from portcv.model_graph import (
  26. BGR_IDX_TENSOR,
  27. has_channel_reversal,
  28. insert_channel_reversal,
  29. verify_reversal,
  30. )
  31. ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  32. def load_script(name: str):
  33. """按路径加载 ``scripts/<name>.py``(scripts 不是包,沿用 test_rknn_ops 的写法)。"""
  34. path = os.path.join(ROOT, "scripts", name + ".py")
  35. spec = importlib.util.spec_from_file_location(name, path)
  36. module = importlib.util.module_from_spec(spec)
  37. spec.loader.exec_module(module)
  38. return module
  39. def build_model(nhwc: bool = False, channels: int = 3):
  40. """迷你模型:**两个消费者**共用输入,便于验证「所有消费者都被重定向」。
  41. ``y = (x * w) + (x + b)``:每个通道有各自的系数,通道顺序一变结果立刻不同。
  42. """
  43. shape = [1, 4, 5, channels] if nhwc else [1, channels, 4, 5]
  44. param_shape = [1, 1, 1, channels] if nhwc else [1, channels, 1, 1]
  45. x = helper.make_tensor_value_info("images", TensorProto.FLOAT, shape)
  46. y = helper.make_tensor_value_info("output0", TensorProto.FLOAT, shape)
  47. scale = np.arange(1, channels + 1, dtype=np.float32).reshape(param_shape)
  48. shift = np.arange(1, channels + 1, dtype=np.float32).reshape(param_shape)
  49. graph = helper.make_graph(
  50. [
  51. helper.make_node("Mul", ["images", "w"], ["scaled"]),
  52. helper.make_node("Add", ["images", "b"], ["shifted"]),
  53. helper.make_node("Add", ["scaled", "shifted"], ["output0"]),
  54. ],
  55. "tiny_rgb_model",
  56. [x],
  57. [y],
  58. [numpy_helper.from_array(scale, "w"), numpy_helper.from_array(shift, "b")],
  59. )
  60. model = helper.make_model(graph, opset_imports=[helper.make_opsetid("", 13)])
  61. model.ir_version = 8
  62. onnx.checker.check_model(model)
  63. return model
  64. def build_shape_model(dims):
  65. """按给定输入维度造一个单节点模型(用来测维度报错分支)。"""
  66. x = helper.make_tensor_value_info("images", TensorProto.FLOAT, dims)
  67. y = helper.make_tensor_value_info("output0", TensorProto.FLOAT, None)
  68. w = numpy_helper.from_array(np.ones([1], dtype=np.float32), "w")
  69. graph = helper.make_graph(
  70. [helper.make_node("Mul", ["images", "w"], ["output0"])], "shape_model", [x], [y], [w]
  71. )
  72. return helper.make_model(graph, opset_imports=[helper.make_opsetid("", 13)])
  73. @unittest.skipUnless(HAVE_ONNX, "需要 onnx:pip install onnx")
  74. class InsertReversalTests(unittest.TestCase):
  75. def test_gather_is_inserted_first_and_redirects_every_consumer(self):
  76. model = build_model()
  77. info = insert_channel_reversal(model)
  78. self.assertTrue(info["inserted"])
  79. self.assertEqual(info["axis"], 1) # NCHW → 通道轴 1
  80. self.assertEqual(info["consumers"], 2) # Mul 和 Add 两个消费者
  81. self.assertEqual(model.graph.node[0].op_type, "Gather")
  82. self.assertEqual(info["output"], model.graph.node[0].output[0])
  83. self.assertTrue(any(init.name == BGR_IDX_TENSOR for init in model.graph.initializer))
  84. # 原来的两个消费者都改成吃反通道后的张量,输入本身没人直接用了
  85. for node in list(model.graph.node)[1:]:
  86. self.assertNotIn("images", list(node.input))
  87. onnx.checker.check_model(model)
  88. def test_second_insert_is_noop(self):
  89. model = build_model()
  90. first = insert_channel_reversal(model)
  91. node_count = len(model.graph.node)
  92. second = insert_channel_reversal(model)
  93. self.assertTrue(first["inserted"])
  94. self.assertFalse(second["inserted"])
  95. self.assertEqual(len(model.graph.node), node_count) # 不会反两次
  96. def test_nhwc_model_gets_axis_3(self):
  97. model = build_model(nhwc=True)
  98. info = insert_channel_reversal(model)
  99. self.assertEqual(info["axis"], 3)
  100. def test_has_channel_reversal_flips_after_insert(self):
  101. model = build_model()
  102. self.assertFalse(has_channel_reversal(model))
  103. insert_channel_reversal(model)
  104. self.assertTrue(has_channel_reversal(model))
  105. def test_unknown_input_name_raises(self):
  106. with self.assertRaises(ValueError):
  107. insert_channel_reversal(build_model(), input_name="pixel_values")
  108. def test_rank_three_input_raises(self):
  109. with self.assertRaises(ValueError):
  110. insert_channel_reversal(build_shape_model([1, 3, 4]))
  111. def test_dynamic_channel_raises_with_actionable_message(self):
  112. with self.assertRaises(ValueError) as ctx:
  113. insert_channel_reversal(build_shape_model(["N", "C", 4, 5]))
  114. self.assertIn("3 通道", str(ctx.exception))
  115. def test_control_flow_subgraph_reference_raises(self):
  116. """If/Loop 子图里引用输入时,只改主图会漏,必须报错让人手工处理。"""
  117. shape = [1, 3, 4, 5]
  118. out = helper.make_tensor_value_info("branch_out", TensorProto.FLOAT, shape)
  119. branches = [
  120. helper.make_graph(
  121. [helper.make_node("Identity", ["images"], ["branch_out"])], name, [], [out]
  122. )
  123. for name in ("then_branch", "else_branch")
  124. ]
  125. graph = helper.make_graph(
  126. [
  127. helper.make_node(
  128. "If",
  129. ["cond"],
  130. ["picked"],
  131. then_branch=branches[0],
  132. else_branch=branches[1],
  133. ),
  134. helper.make_node("Identity", ["picked"], ["output0"]),
  135. ],
  136. "control_flow",
  137. [helper.make_tensor_value_info("images", TensorProto.FLOAT, shape)],
  138. [helper.make_tensor_value_info("output0", TensorProto.FLOAT, shape)],
  139. [numpy_helper.from_array(np.array(True, dtype=np.bool_), "cond")],
  140. )
  141. model = helper.make_model(graph, opset_imports=[helper.make_opsetid("", 13)])
  142. with self.assertRaises(ValueError) as ctx:
  143. insert_channel_reversal(model)
  144. self.assertIn("子图", str(ctx.exception))
  145. @unittest.skipUnless(HAVE_ONNX, "需要 onnx:pip install onnx")
  146. class VerifyReversalTests(unittest.TestCase):
  147. def test_bgr_input_is_equivalent_to_rgb_input(self):
  148. before = build_model()
  149. after = build_model()
  150. insert_channel_reversal(after)
  151. result = verify_reversal(before, after)
  152. self.assertTrue(result["ok"])
  153. self.assertLess(result["max_abs_diff"], 1e-6)
  154. # 不反通道时结果必须真的不同,否则这个节点是白插的
  155. self.assertGreater(result["diff_without_reversal"], 1e-3)
  156. def test_nhwc_verification_uses_last_axis(self):
  157. before = build_model(nhwc=True)
  158. after = build_model(nhwc=True)
  159. insert_channel_reversal(after)
  160. result = verify_reversal(before, after)
  161. self.assertTrue(result["ok"])
  162. self.assertEqual(result["axis"], 3)
  163. @unittest.skipUnless(HAVE_ONNX, "需要 onnx:pip install onnx")
  164. class ConvertGateTests(unittest.TestCase):
  165. """``scripts/onnx_to_rknn.py`` 的闸门:配置写 ``bgr_uint8`` 就得有反通道节点。"""
  166. def setUp(self):
  167. self._tmp = tempfile.TemporaryDirectory()
  168. self.addCleanup(self._tmp.cleanup)
  169. self.dir = self._tmp.name
  170. with contextlib.redirect_stdout(io.StringIO()):
  171. self.script = load_script("onnx_to_rknn")
  172. def _save(self, name: str, model) -> str:
  173. path = os.path.join(self.dir, name)
  174. onnx.save(model, path)
  175. return path
  176. def _config(self, input_format: str = "bgr_uint8") -> str:
  177. path = os.path.join(self.dir, "cfg.json")
  178. with open(path, "w", encoding="utf-8") as fh:
  179. json.dump(
  180. {
  181. "run": {"backend": "rknn"},
  182. "model": {
  183. "input_format": input_format,
  184. "input_size": [640, 640],
  185. "rknn_path": os.path.join(self.dir, "model.rknn"),
  186. },
  187. },
  188. fh,
  189. )
  190. return path
  191. def test_missing_node_raises_with_fix_command(self):
  192. path = self._save("plain.onnx", build_model())
  193. with self.assertRaises(RuntimeError) as ctx:
  194. with contextlib.redirect_stdout(io.StringIO()):
  195. self.script.check_bgr_input(path)
  196. message = str(ctx.exception)
  197. self.assertIn("onnx_bgr_input.py", message) # 报错里直接给修复命令
  198. self.assertIn("bgr_uint8", message)
  199. def test_inserted_node_passes(self):
  200. model = build_model()
  201. insert_channel_reversal(model)
  202. path = self._save("bgr.onnx", model)
  203. with contextlib.redirect_stdout(io.StringIO()):
  204. self.assertIsNone(self.script.check_bgr_input(path)) # 不抛异常
  205. def test_main_stops_before_rknn_toolkit(self):
  206. """闸门必须在 ``convert()`` 之前触发,否则没装 rknn-toolkit2 时会报成另一个错。"""
  207. onnx_path = self._save("plain.onnx", build_model())
  208. cfg = self._config()
  209. with self.assertRaises(RuntimeError) as ctx:
  210. with contextlib.redirect_stdout(io.StringIO()):
  211. self.script.main(["--onnx", onnx_path, "--config", cfg, "--no-quantize"])
  212. self.assertIn("反通道节点", str(ctx.exception))
  213. self.assertNotIn("rknn-toolkit2", str(ctx.exception))