rknpu_ratio.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  1. # -*- coding: utf-8 -*-
  2. """量「NPU 时间占比」并按口径判定 PASS/FAIL(在 RK3576 / RK3588 板卡上跑)。
  3. 为什么不能只报一个百分比
  4. ------------------------
  5. 「NPU 加速比例 ≥70%」有两种口径,混在一起就永远验收不清楚:
  6. * **口径 A(整链时间占比)**:``npu_ms / 单帧端到端耗时``。解码、letterbox、色彩转换、
  7. 后处理(解码输出 + NMS)都算分母,只有真正跑在 NPU 上的那段算分子;
  8. * **口径 B(模型链占比)**:``npu_ms / (preproc_ms + npu_ms + postproc_ms)``,只统计
  9. "模型这条链路",用来判断模型本身有没有被 CPU 打断。
  10. 两者都测,结论才不会被"分母怎么算"扯皮。判定用口径 A(更严),同时打印 B 供定位。
  11. 用法(板卡上)::
  12. python scripts/rknpu_ratio.py --config configs/rk3588-rtsp.json --check
  13. python scripts/rknpu_ratio.py --config configs/rk3588-rtsp.json --video samples/crane.mp4 \
  14. --frames 200 --target 0.70 --json runs/npu_ratio.json
  15. # 与生产同语义(后台线程解码)+ 配对 fps 门禁
  16. python scripts/rknpu_ratio.py --config configs/rk3588-rtsp.json --video samples/crane.mp4 \
  17. --producer --min-fps 12 --target 0.70
  18. 说明
  19. ----
  20. * 只在 ``run.backend=rknn`` 时有意义:``edge`` / ``evidence-v2`` / ``mock`` 是纯 CPU 经典 CV,
  21. ``npu_ms`` 恒为 0,脚本会直接判 FAIL(这正是当前交付路径的真实状态);
  22. * ``--extra-ms`` 用来补上没被计时的固定开销(决策 / 投票 / Modbus 发布,通常 0.1~0.3 ms);
  23. * NPU 硬件占用率取自 ``/sys/kernel/debug/rknpu/load``(或 devfreq),读不到时报 ``null``
  24. 而不是 0,避免「没采到」被当成「占用为 0」。
  25. 三个会让结论失真的坑(脚本会主动提示,别忽略)
  26. ----------------------------------------------
  27. 1. **取帧方式**:默认串行 ``cap.read()``,解码时间计入分母(偏保守)。生产用
  28. :class:`~portcv.io.capture.FrameGrabber` 在**后台线程**解码,加 ``--producer`` 复现生产语义;
  29. 此时等帧时间单列为 ``wait_ms``,不进口径 A 的分母(那段墙上时间 NPU 本可以跑别的帧);
  30. 2. **``run.max_fps``**:主循环每帧后主动 sleep,wall-clock 占比会被限速稀释 →
  31. 验收请用 ``max_fps=0`` 的配置,否则分母里混了「故意闲下来」的时间;
  32. 3. **``plc.gating``**:按需识别时空档期完全不推理,一天里的 wall-clock 占比接近 0 →
  33. 本脚本只代表「正在推理的帧」,门禁必须写明这个前提(或验收时关 gating)。
  34. 为避免「把比例调好看」而不是「真的变快」,建议配对 ``--min-fps`` 一起判定:
  35. 占比达标 **且** 实测 fps 达标才算 PASS。
  36. """
  37. from __future__ import annotations
  38. import argparse
  39. import json
  40. import os
  41. import statistics
  42. import sys
  43. import time
  44. from typing import Dict, List, Optional, Sequence
  45. sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
  46. from portcv.config import load_config # noqa: E402
  47. from portcv.detect import build_detector # noqa: E402
  48. from portcv.detect.rknn_backend import ( # noqa: E402
  49. detect_board,
  50. detect_npu_cores,
  51. read_npu_load,
  52. resolve_core_mask,
  53. )
  54. __all__ = ["SAMPLE_KEYS", "format_report", "main", "measure", "summarize"]
  55. #: 每帧采样的字段(``decode_ms`` / ``wait_ms`` / ``period_ms`` 由本脚本测,其余取自检测器的 stage_ms)
  56. SAMPLE_KEYS = (
  57. "decode_ms",
  58. "wait_ms",
  59. "period_ms",
  60. "preproc_ms",
  61. "npu_ms",
  62. "postproc_ms",
  63. "npu_load",
  64. )
  65. def _mean(values: Sequence[float]) -> float:
  66. return float(statistics.fmean(values)) if values else 0.0
  67. def _p95(values: Sequence[float]) -> float:
  68. """最近秩 P95(样本少时退化为最大值),避免引入 numpy 依赖。"""
  69. if not values:
  70. return 0.0
  71. ordered = sorted(float(v) for v in values)
  72. index = min(len(ordered) - 1, int(round(0.95 * (len(ordered) - 1))))
  73. return float(ordered[index])
  74. def summarize(
  75. samples: List[Dict[str, float]],
  76. target: float = 0.70,
  77. extra_ms: float = 0.0,
  78. min_fps: float = 0.0,
  79. ) -> Dict[str, object]:
  80. """把逐帧采样汇总成两个口径的占比 + 判定结果。
  81. 每帧采样字段见 :data:`SAMPLE_KEYS`;``npu_load`` 允许缺失或为 ``None``。
  82. ``wait_ms`` 只在 ``--producer`` 模式出现(后台线程解码时的等帧时间):
  83. **不进口径 A 的分母**——那段时间 NPU 本可以接着跑下一帧,串行取帧才会把它算进去;
  84. 单列成 ``ratio_wall`` 供「整段值守时间」参考。
  85. ``min_fps > 0`` 时启用配对门禁:占比达标 **且** 实测 fps 达标,``pass`` 才为真。
  86. 这是为了防止「故意把 max_fps 调低 / 把分母做大」把比例做漂亮。
  87. """
  88. if not samples:
  89. raise ValueError("没有采样数据(frames=0?)")
  90. decode = _mean([float(s.get("decode_ms", 0.0)) for s in samples])
  91. wait = _mean([float(s.get("wait_ms", 0.0)) for s in samples])
  92. preproc = _mean([float(s.get("preproc_ms", 0.0)) for s in samples])
  93. npu = _mean([float(s.get("npu_ms", 0.0)) for s in samples])
  94. postproc = _mean([float(s.get("postproc_ms", 0.0)) for s in samples])
  95. loads = [float(s["npu_load"]) for s in samples if s.get("npu_load") is not None]
  96. periods = [
  97. float(s.get("period_ms", 0.0) or 0.0)
  98. for s in samples
  99. if float(s.get("period_ms", 0.0) or 0.0) > 0.0
  100. ]
  101. extra = max(0.0, float(extra_ms))
  102. total_a = decode + preproc + npu + postproc + extra
  103. total_b = preproc + npu + postproc
  104. total_wall = total_a + wait
  105. ratio_a = (npu / total_a) if total_a > 0 else 0.0
  106. ratio_b = (npu / total_b) if total_b > 0 else 0.0
  107. ratio_wall = (npu / total_wall) if total_wall > 0 else 0.0
  108. fps = (1000.0 / _mean(periods)) if periods else 0.0
  109. fps_ok = True if float(min_fps) <= 0.0 else bool(fps >= float(min_fps))
  110. return {
  111. "frames": len(samples),
  112. "target": float(target),
  113. "extra_ms": extra,
  114. "fps": round(fps, 2),
  115. "min_fps": float(min_fps),
  116. "mean_ms": {
  117. "decode": round(decode, 3),
  118. "wait": round(wait, 3),
  119. "preproc": round(preproc, 3),
  120. "npu": round(npu, 3),
  121. "postproc": round(postproc, 3),
  122. "total_a": round(total_a, 3),
  123. "total_b": round(total_b, 3),
  124. "total_wall": round(total_wall, 3),
  125. },
  126. "p95_ms": {
  127. "npu": round(_p95([float(s.get("npu_ms", 0.0)) for s in samples]), 3),
  128. "preproc": round(_p95([float(s.get("preproc_ms", 0.0)) for s in samples]), 3),
  129. "postproc": round(_p95([float(s.get("postproc_ms", 0.0)) for s in samples]), 3),
  130. "decode": round(_p95([float(s.get("decode_ms", 0.0)) for s in samples]), 3),
  131. },
  132. "npu_load": {
  133. "mean": round(_mean(loads), 4) if loads else None,
  134. "max": round(max(loads), 4) if loads else None,
  135. "samples": len(loads),
  136. },
  137. "ratio_a": round(ratio_a, 4),
  138. "ratio_b": round(ratio_b, 4),
  139. "ratio_wall": round(ratio_wall, 4),
  140. "pass_a": bool(ratio_a >= float(target)),
  141. "pass_b": bool(ratio_b >= float(target)),
  142. "pass_fps": bool(fps_ok),
  143. "pass": bool(ratio_a >= float(target) and fps_ok),
  144. }
  145. def _config_warnings(cfg, producer: bool = False) -> List[str]:
  146. """列出会让口径失真的配置项(打印给人看,不改配置)。
  147. 这些提示比数字本身重要:同样的板子,``max_fps`` 或 ``gating`` 一开一关,
  148. 口径 A 能差出一倍,最后变成「谁选的配置谁赢」的口水仗。
  149. """
  150. notes: List[str] = []
  151. if bool(cfg.get_path("plc.gating", False)):
  152. notes.append(
  153. "plc.gating=true:生产上只在 PLC 请求后的窗口内推理,wall-clock 占比会被空档期稀释;"
  154. "本报告只代表「正在推理的帧」,门禁必须写明这个前提"
  155. )
  156. max_fps = float(cfg.get_path("run.max_fps", 0.0) or 0.0)
  157. if max_fps > 0.0:
  158. notes.append(
  159. "run.max_fps=%.1f 会在每帧后主动 sleep:验收口径A 请用 max_fps=0 的配置,"
  160. "否则分母里混了「故意闲下来」的时间" % max_fps
  161. )
  162. if not producer:
  163. notes.append(
  164. "当前是串行取帧模式,decode 计入分母(偏保守);生产用 FrameGrabber 后台解码,"
  165. "可加 --producer 复现生产语义"
  166. )
  167. return notes
  168. def _hint(summary: Dict[str, object]) -> str:
  169. """指出把占比压下去的主要环节(按平均耗时排序)。"""
  170. mean_ms = summary.get("mean_ms", {})
  171. assert isinstance(mean_ms, dict)
  172. stages = [(float(mean_ms.get(key, 0.0)), key) for key in ("decode", "preproc", "postproc", "npu")]
  173. stages.sort(reverse=True)
  174. biggest_ms, biggest = stages[0]
  175. if biggest == "npu":
  176. return "耗时最大的是 NPU 本身:说明模型偏重/输入分辨率偏高,可换更小模型或降输入尺寸"
  177. return "耗时最大的是 %s(%.2f ms):把它搬到硬件/向量化,占比才会上去" % (biggest, biggest_ms)
  178. def format_report(summary: Dict[str, object]) -> str:
  179. """把 :func:`summarize` 的结果排成人读的报告(同时是验收证据的正文)。"""
  180. mean_ms = summary["mean_ms"]
  181. p95 = summary["p95_ms"]
  182. load = summary["npu_load"]
  183. assert isinstance(mean_ms, dict) and isinstance(p95, dict) and isinstance(load, dict)
  184. if load["mean"] is None:
  185. load_text = "无法读取(非 RK 板或没挂 debugfs)"
  186. else:
  187. load_text = "平均 %.0f%% / 峰值 %.0f%%(%d 次采样)" % (
  188. float(load["mean"]) * 100.0,
  189. float(load["max"]) * 100.0,
  190. int(load["samples"]),
  191. )
  192. lines = [
  193. "== NPU 时间占比 ==",
  194. "帧数 %d / 目标 %.0f%% / 额外开销 %.2f ms"
  195. % (summary["frames"], float(summary["target"]) * 100.0, float(summary["extra_ms"])),
  196. "平均耗时(ms): decode %.2f | preproc %.2f | npu %.2f | postproc %.2f"
  197. % (mean_ms["decode"], mean_ms["preproc"], mean_ms["npu"], mean_ms["postproc"]),
  198. "P95 耗时(ms): decode %.2f | preproc %.2f | npu %.2f | postproc %.2f"
  199. % (p95["decode"], p95["preproc"], p95["npu"], p95["postproc"]),
  200. "单帧总耗时(ms): 口径A %.2f | 口径B %.2f" % (mean_ms["total_a"], mean_ms["total_b"]),
  201. "口径A(整链) npu/总耗时 = %.1f%% → %s"
  202. % (float(summary["ratio_a"]) * 100.0, "PASS" if summary["pass_a"] else "FAIL"),
  203. "口径B(模型链)npu/模型链 = %.1f%% → %s"
  204. % (float(summary["ratio_b"]) * 100.0, "PASS" if summary["pass_b"] else "FAIL"),
  205. "NPU 硬件占用率: %s" % load_text,
  206. (
  207. "实测吞吐: %.1f fps(等帧 %.2f ms/帧,仅 --producer 统计,不进口径A 分母)"
  208. % (float(summary.get("fps", 0.0)), float(mean_ms.get("wait", 0.0)))
  209. if float(summary.get("fps", 0.0)) > 0.0
  210. else "实测吞吐: 未采样(没有 period_ms:旧版采样或手工构造的数据)"
  211. ),
  212. "参考口径Wall(npu/含等帧墙钟)= %.1f%%" % (float(summary.get("ratio_wall", 0.0)) * 100.0),
  213. "诊断: %s" % _hint(summary),
  214. ]
  215. if float(summary.get("min_fps", 0.0)) > 0.0:
  216. lines.append(
  217. "配对门禁: 需 %.1f fps,实测 %.1f fps → %s"
  218. % (
  219. float(summary["min_fps"]),
  220. float(summary.get("fps", 0.0)),
  221. "满足" if summary.get("pass_fps") else "不满足(占比再高也不能算达标)",
  222. )
  223. )
  224. return "\n".join(lines)
  225. def _fresh_frame(grabber, seen: int, timeout: float = 5.0):
  226. """等一帧 ``frame_id`` 比 ``seen`` 更新的帧;返回 ``(frame, 等待秒数)``,超时返回 ``(None, 秒数)``。"""
  227. start = time.perf_counter()
  228. deadline = start + timeout
  229. while time.perf_counter() < deadline:
  230. frame = grabber.latest
  231. if frame is not None and frame.frame_id > seen:
  232. return frame, time.perf_counter() - start
  233. time.sleep(0.002)
  234. return None, time.perf_counter() - start
  235. def measure(
  236. cfg,
  237. frames: int,
  238. video: str = "",
  239. warmup: int = 3,
  240. producer: bool = False,
  241. ) -> List[Dict[str, float]]:
  242. """跑真实帧并采样逐阶段耗时;返回逐帧采样列表。
  243. * ``producer=False``(默认):串行 ``cap.read()``,``decode_ms`` 计入分母 —— **保守口径**,
  244. 适合当门禁,因为它假设最坏情况(解码与推理完全不重叠);
  245. * ``producer=True``:用 :class:`~portcv.io.capture.FrameGrabber` 后台线程取帧(与生产一致),
  246. 解码与推理并行,只把等帧时间记进 ``wait_ms``,**不进口径 A 分母**。
  247. 给了 ``video`` 时一律按本地文件打开(``source_type=file``、关掉 GStreamer 管线),
  248. 避免拿现场 ``rtsp`` 配置去读本地片段时打不开。
  249. """
  250. from portcv.io.capture import FrameGrabber, open_capture
  251. detector = build_detector(cfg)
  252. source = video or str(cfg.get_path("source.uri", "samples/demo.mp4"))
  253. samples: List[Dict[str, float]] = []
  254. total = max(1, int(frames))
  255. warmup_n = max(0, int(warmup))
  256. def record(stages: Dict[str, float], decode_ms: float, wait_ms: float, period_ms: float) -> None:
  257. samples.append(
  258. {
  259. "decode_ms": decode_ms,
  260. "wait_ms": wait_ms,
  261. "period_ms": period_ms,
  262. "preproc_ms": float(stages.get("preproc", 0.0)),
  263. "npu_ms": float(stages.get("npu", 0.0)),
  264. "postproc_ms": float(stages.get("postproc", 0.0)),
  265. "npu_load": read_npu_load(),
  266. }
  267. )
  268. prev_t: Optional[float] = None
  269. if producer:
  270. grabber = FrameGrabber(cfg)
  271. if video:
  272. grabber.uri = video
  273. grabber.source_type = "file"
  274. grabber.use_gst = False
  275. grabber.start()
  276. if not grabber.opened:
  277. grabber.stop()
  278. raise RuntimeError(
  279. "打不开视频源: %s(source.type=%s,检查路径 / RTSP 地址)"
  280. % (grabber.uri, grabber.source_type)
  281. )
  282. seen = 0
  283. try:
  284. for _ in range(warmup_n):
  285. frame, _wait = _fresh_frame(grabber, seen)
  286. if frame is None:
  287. break
  288. seen = frame.frame_id
  289. detector.infer(frame.image)
  290. while len(samples) < total:
  291. frame, wait_s = _fresh_frame(grabber, seen)
  292. if frame is None:
  293. break
  294. seen = frame.frame_id
  295. started = time.perf_counter()
  296. detector.infer(frame.image)
  297. stages = getattr(detector, "stage_ms", None) or {}
  298. period_ms = 0.0 if prev_t is None else (started - prev_t) * 1000.0
  299. prev_t = started
  300. record(stages, 0.0, wait_s * 1000.0, period_ms)
  301. finally:
  302. grabber.stop()
  303. detector.close()
  304. else:
  305. cap = open_capture(source, use_gst=bool(cfg.get_path("source.use_gst", False)))
  306. if not cap.isOpened():
  307. raise RuntimeError("打不开视频源: %s" % source)
  308. try:
  309. for _ in range(warmup_n):
  310. ok, frame = cap.read()
  311. if not ok or frame is None:
  312. break
  313. detector.infer(frame)
  314. while len(samples) < total:
  315. start = time.perf_counter()
  316. ok, frame = cap.read()
  317. grabbed = time.perf_counter()
  318. if not ok or frame is None:
  319. break
  320. detector.infer(frame)
  321. stages = getattr(detector, "stage_ms", None) or {}
  322. period_ms = 0.0 if prev_t is None else (start - prev_t) * 1000.0
  323. prev_t = start
  324. record(stages, (grabbed - start) * 1000.0, 0.0, period_ms)
  325. finally:
  326. cap.release()
  327. detector.close()
  328. if not samples:
  329. raise RuntimeError("没有取到任何帧(检查 --video / source.uri)")
  330. return samples
  331. def check_env(cfg) -> int:
  332. """打印运行环境就绪度(不需要模型也能跑,现场排查第一条命令)。"""
  333. import importlib.util
  334. backend = str(cfg.get_path("run.backend", "mock"))
  335. model = str(cfg.get_path("model.rknn_path", ""))
  336. board = detect_board()
  337. cores = detect_npu_cores(board)
  338. core = str(cfg.get_path("model.rknn_core", "auto"))
  339. mask, note = resolve_core_mask(core, cores)
  340. load = read_npu_load()
  341. has_lite = importlib.util.find_spec("rknnlite") is not None
  342. rows = [
  343. ("run.backend", backend, backend.lower() == "rknn"),
  344. ("板型", board or "未识别", bool(board)),
  345. ("NPU core 数", str(cores or "未知"), cores > 0),
  346. ("core_mask", "%s → %d%s" % (core, mask, "(已收敛)" if note else ""), not note),
  347. ("RKNN 模型", model if os.path.isfile(model) else "%s(不存在)" % model, os.path.isfile(model)),
  348. ("rknnlite", "已安装" if has_lite else "未安装", has_lite),
  349. (
  350. "NPU 负载节点",
  351. "可读 %.0f%%" % (float(load) * 100.0) if load is not None else "不可读",
  352. load is not None,
  353. ),
  354. ]
  355. print("== 环境检查 ==")
  356. for name, value, ok in rows:
  357. print(" [%s] %-14s %s" % ("OK" if ok else "缺失", name, value))
  358. if note:
  359. print(" 提示: %s" % note)
  360. notes = _config_warnings(cfg, producer=True)
  361. if notes:
  362. print("== 口径提示 ==")
  363. for item in notes:
  364. print(" * %s" % item)
  365. blockers = [name for name, _, ok in rows if not ok]
  366. if blockers:
  367. print("结论: 还不能测(缺 %s)" % "、".join(blockers))
  368. return 1
  369. print("结论: 环境就绪,可以开始测量")
  370. return 0
  371. def main(argv: Optional[Sequence[str]] = None) -> int:
  372. parser = argparse.ArgumentParser(description="量 NPU 时间占比(Rockchip RKNPU2 板卡)")
  373. parser.add_argument("--config", required=True, help="配置文件(需 run.backend=rknn)")
  374. parser.add_argument("--video", default="", help="覆盖 source.uri,建议用现场片段保证可重复")
  375. parser.add_argument("--frames", type=int, default=100, help="测量帧数(预热不计入)")
  376. parser.add_argument("--warmup", type=int, default=3, help="预热帧数")
  377. parser.add_argument("--target", type=float, default=0.70, help="达标线(默认 0.70)")
  378. parser.add_argument(
  379. "--extra-ms",
  380. dest="extra_ms",
  381. type=float,
  382. default=0.0,
  383. help="补上未计时的固定开销(决策/投票/Modbus 发布),单位 ms",
  384. )
  385. parser.add_argument("--json", default="", help="结果写成 json(验收证据)")
  386. parser.add_argument(
  387. "--producer",
  388. action="store_true",
  389. help="用 FrameGrabber 后台线程取帧(与生产一致:解码与推理并行,decode 不进口径A 分母)",
  390. )
  391. parser.add_argument(
  392. "--min-fps",
  393. dest="min_fps",
  394. type=float,
  395. default=0.0,
  396. help="配对门禁:除占比外还要求实测 fps ≥ 该值(0=不检查)",
  397. )
  398. parser.add_argument("--check", action="store_true", help="只检查环境,不跑推理")
  399. args = parser.parse_args(argv)
  400. cfg = load_config(args.config)
  401. if args.check:
  402. return check_env(cfg)
  403. warnings = _config_warnings(cfg, producer=bool(args.producer))
  404. for item in warnings:
  405. print("提示: %s" % item)
  406. samples = measure(cfg, args.frames, args.video, args.warmup, producer=bool(args.producer))
  407. summary = summarize(samples, args.target, args.extra_ms, args.min_fps)
  408. summary["producer"] = bool(args.producer)
  409. summary["warnings"] = warnings
  410. print(format_report(summary))
  411. if args.json:
  412. target = os.path.abspath(args.json)
  413. os.makedirs(os.path.dirname(target) or ".", exist_ok=True)
  414. with open(target, "w", encoding="utf-8") as fh:
  415. json.dump(
  416. {"config": args.config, "video": args.video, "summary": summary},
  417. fh,
  418. ensure_ascii=False,
  419. indent=2,
  420. )
  421. print("已写出:%s" % target)
  422. return 0 if summary["pass"] else 1
  423. if __name__ == "__main__":
  424. sys.exit(main())