| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486 |
- # -*- coding: utf-8 -*-
- """量「NPU 时间占比」并按口径判定 PASS/FAIL(在 RK3576 / RK3588 板卡上跑)。
- 为什么不能只报一个百分比
- ------------------------
- 「NPU 加速比例 ≥70%」有两种口径,混在一起就永远验收不清楚:
- * **口径 A(整链时间占比)**:``npu_ms / 单帧端到端耗时``。解码、letterbox、色彩转换、
- 后处理(解码输出 + NMS)都算分母,只有真正跑在 NPU 上的那段算分子;
- * **口径 B(模型链占比)**:``npu_ms / (preproc_ms + npu_ms + postproc_ms)``,只统计
- "模型这条链路",用来判断模型本身有没有被 CPU 打断。
- 两者都测,结论才不会被"分母怎么算"扯皮。判定用口径 A(更严),同时打印 B 供定位。
- 用法(板卡上)::
- python scripts/rknpu_ratio.py --config configs/rk3588-rtsp.json --check
- python scripts/rknpu_ratio.py --config configs/rk3588-rtsp.json --video samples/crane.mp4 \
- --frames 200 --target 0.70 --json runs/npu_ratio.json
- # 与生产同语义(后台线程解码)+ 配对 fps 门禁
- python scripts/rknpu_ratio.py --config configs/rk3588-rtsp.json --video samples/crane.mp4 \
- --producer --min-fps 12 --target 0.70
- 说明
- ----
- * 只在 ``run.backend=rknn`` 时有意义:``edge`` / ``evidence-v2`` / ``mock`` 是纯 CPU 经典 CV,
- ``npu_ms`` 恒为 0,脚本会直接判 FAIL(这正是当前交付路径的真实状态);
- * ``--extra-ms`` 用来补上没被计时的固定开销(决策 / 投票 / Modbus 发布,通常 0.1~0.3 ms);
- * NPU 硬件占用率取自 ``/sys/kernel/debug/rknpu/load``(或 devfreq),读不到时报 ``null``
- 而不是 0,避免「没采到」被当成「占用为 0」。
- 三个会让结论失真的坑(脚本会主动提示,别忽略)
- ----------------------------------------------
- 1. **取帧方式**:默认串行 ``cap.read()``,解码时间计入分母(偏保守)。生产用
- :class:`~portcv.io.capture.FrameGrabber` 在**后台线程**解码,加 ``--producer`` 复现生产语义;
- 此时等帧时间单列为 ``wait_ms``,不进口径 A 的分母(那段墙上时间 NPU 本可以跑别的帧);
- 2. **``run.max_fps``**:主循环每帧后主动 sleep,wall-clock 占比会被限速稀释 →
- 验收请用 ``max_fps=0`` 的配置,否则分母里混了「故意闲下来」的时间;
- 3. **``plc.gating``**:按需识别时空档期完全不推理,一天里的 wall-clock 占比接近 0 →
- 本脚本只代表「正在推理的帧」,门禁必须写明这个前提(或验收时关 gating)。
- 为避免「把比例调好看」而不是「真的变快」,建议配对 ``--min-fps`` 一起判定:
- 占比达标 **且** 实测 fps 达标才算 PASS。
- """
- from __future__ import annotations
- import argparse
- import json
- import os
- import statistics
- import sys
- import time
- from typing import Dict, List, Optional, Sequence
- sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
- from portcv.config import load_config # noqa: E402
- from portcv.detect import build_detector # noqa: E402
- from portcv.detect.rknn_backend import ( # noqa: E402
- detect_board,
- detect_npu_cores,
- read_npu_load,
- resolve_core_mask,
- )
- __all__ = ["SAMPLE_KEYS", "format_report", "main", "measure", "summarize"]
- #: 每帧采样的字段(``decode_ms`` / ``wait_ms`` / ``period_ms`` 由本脚本测,其余取自检测器的 stage_ms)
- SAMPLE_KEYS = (
- "decode_ms",
- "wait_ms",
- "period_ms",
- "preproc_ms",
- "npu_ms",
- "postproc_ms",
- "npu_load",
- )
- def _mean(values: Sequence[float]) -> float:
- return float(statistics.fmean(values)) if values else 0.0
- def _p95(values: Sequence[float]) -> float:
- """最近秩 P95(样本少时退化为最大值),避免引入 numpy 依赖。"""
- if not values:
- return 0.0
- ordered = sorted(float(v) for v in values)
- index = min(len(ordered) - 1, int(round(0.95 * (len(ordered) - 1))))
- return float(ordered[index])
- def summarize(
- samples: List[Dict[str, float]],
- target: float = 0.70,
- extra_ms: float = 0.0,
- min_fps: float = 0.0,
- ) -> Dict[str, object]:
- """把逐帧采样汇总成两个口径的占比 + 判定结果。
- 每帧采样字段见 :data:`SAMPLE_KEYS`;``npu_load`` 允许缺失或为 ``None``。
- ``wait_ms`` 只在 ``--producer`` 模式出现(后台线程解码时的等帧时间):
- **不进口径 A 的分母**——那段时间 NPU 本可以接着跑下一帧,串行取帧才会把它算进去;
- 单列成 ``ratio_wall`` 供「整段值守时间」参考。
- ``min_fps > 0`` 时启用配对门禁:占比达标 **且** 实测 fps 达标,``pass`` 才为真。
- 这是为了防止「故意把 max_fps 调低 / 把分母做大」把比例做漂亮。
- """
- if not samples:
- raise ValueError("没有采样数据(frames=0?)")
- decode = _mean([float(s.get("decode_ms", 0.0)) for s in samples])
- wait = _mean([float(s.get("wait_ms", 0.0)) for s in samples])
- preproc = _mean([float(s.get("preproc_ms", 0.0)) for s in samples])
- npu = _mean([float(s.get("npu_ms", 0.0)) for s in samples])
- postproc = _mean([float(s.get("postproc_ms", 0.0)) for s in samples])
- loads = [float(s["npu_load"]) for s in samples if s.get("npu_load") is not None]
- periods = [
- float(s.get("period_ms", 0.0) or 0.0)
- for s in samples
- if float(s.get("period_ms", 0.0) or 0.0) > 0.0
- ]
- extra = max(0.0, float(extra_ms))
- total_a = decode + preproc + npu + postproc + extra
- total_b = preproc + npu + postproc
- total_wall = total_a + wait
- ratio_a = (npu / total_a) if total_a > 0 else 0.0
- ratio_b = (npu / total_b) if total_b > 0 else 0.0
- ratio_wall = (npu / total_wall) if total_wall > 0 else 0.0
- fps = (1000.0 / _mean(periods)) if periods else 0.0
- fps_ok = True if float(min_fps) <= 0.0 else bool(fps >= float(min_fps))
- return {
- "frames": len(samples),
- "target": float(target),
- "extra_ms": extra,
- "fps": round(fps, 2),
- "min_fps": float(min_fps),
- "mean_ms": {
- "decode": round(decode, 3),
- "wait": round(wait, 3),
- "preproc": round(preproc, 3),
- "npu": round(npu, 3),
- "postproc": round(postproc, 3),
- "total_a": round(total_a, 3),
- "total_b": round(total_b, 3),
- "total_wall": round(total_wall, 3),
- },
- "p95_ms": {
- "npu": round(_p95([float(s.get("npu_ms", 0.0)) for s in samples]), 3),
- "preproc": round(_p95([float(s.get("preproc_ms", 0.0)) for s in samples]), 3),
- "postproc": round(_p95([float(s.get("postproc_ms", 0.0)) for s in samples]), 3),
- "decode": round(_p95([float(s.get("decode_ms", 0.0)) for s in samples]), 3),
- },
- "npu_load": {
- "mean": round(_mean(loads), 4) if loads else None,
- "max": round(max(loads), 4) if loads else None,
- "samples": len(loads),
- },
- "ratio_a": round(ratio_a, 4),
- "ratio_b": round(ratio_b, 4),
- "ratio_wall": round(ratio_wall, 4),
- "pass_a": bool(ratio_a >= float(target)),
- "pass_b": bool(ratio_b >= float(target)),
- "pass_fps": bool(fps_ok),
- "pass": bool(ratio_a >= float(target) and fps_ok),
- }
- def _config_warnings(cfg, producer: bool = False) -> List[str]:
- """列出会让口径失真的配置项(打印给人看,不改配置)。
- 这些提示比数字本身重要:同样的板子,``max_fps`` 或 ``gating`` 一开一关,
- 口径 A 能差出一倍,最后变成「谁选的配置谁赢」的口水仗。
- """
- notes: List[str] = []
- if bool(cfg.get_path("plc.gating", False)):
- notes.append(
- "plc.gating=true:生产上只在 PLC 请求后的窗口内推理,wall-clock 占比会被空档期稀释;"
- "本报告只代表「正在推理的帧」,门禁必须写明这个前提"
- )
- max_fps = float(cfg.get_path("run.max_fps", 0.0) or 0.0)
- if max_fps > 0.0:
- notes.append(
- "run.max_fps=%.1f 会在每帧后主动 sleep:验收口径A 请用 max_fps=0 的配置,"
- "否则分母里混了「故意闲下来」的时间" % max_fps
- )
- if not producer:
- notes.append(
- "当前是串行取帧模式,decode 计入分母(偏保守);生产用 FrameGrabber 后台解码,"
- "可加 --producer 复现生产语义"
- )
- return notes
- def _hint(summary: Dict[str, object]) -> str:
- """指出把占比压下去的主要环节(按平均耗时排序)。"""
- mean_ms = summary.get("mean_ms", {})
- assert isinstance(mean_ms, dict)
- stages = [(float(mean_ms.get(key, 0.0)), key) for key in ("decode", "preproc", "postproc", "npu")]
- stages.sort(reverse=True)
- biggest_ms, biggest = stages[0]
- if biggest == "npu":
- return "耗时最大的是 NPU 本身:说明模型偏重/输入分辨率偏高,可换更小模型或降输入尺寸"
- return "耗时最大的是 %s(%.2f ms):把它搬到硬件/向量化,占比才会上去" % (biggest, biggest_ms)
- def format_report(summary: Dict[str, object]) -> str:
- """把 :func:`summarize` 的结果排成人读的报告(同时是验收证据的正文)。"""
- mean_ms = summary["mean_ms"]
- p95 = summary["p95_ms"]
- load = summary["npu_load"]
- assert isinstance(mean_ms, dict) and isinstance(p95, dict) and isinstance(load, dict)
- if load["mean"] is None:
- load_text = "无法读取(非 RK 板或没挂 debugfs)"
- else:
- load_text = "平均 %.0f%% / 峰值 %.0f%%(%d 次采样)" % (
- float(load["mean"]) * 100.0,
- float(load["max"]) * 100.0,
- int(load["samples"]),
- )
- lines = [
- "== NPU 时间占比 ==",
- "帧数 %d / 目标 %.0f%% / 额外开销 %.2f ms"
- % (summary["frames"], float(summary["target"]) * 100.0, float(summary["extra_ms"])),
- "平均耗时(ms): decode %.2f | preproc %.2f | npu %.2f | postproc %.2f"
- % (mean_ms["decode"], mean_ms["preproc"], mean_ms["npu"], mean_ms["postproc"]),
- "P95 耗时(ms): decode %.2f | preproc %.2f | npu %.2f | postproc %.2f"
- % (p95["decode"], p95["preproc"], p95["npu"], p95["postproc"]),
- "单帧总耗时(ms): 口径A %.2f | 口径B %.2f" % (mean_ms["total_a"], mean_ms["total_b"]),
- "口径A(整链) npu/总耗时 = %.1f%% → %s"
- % (float(summary["ratio_a"]) * 100.0, "PASS" if summary["pass_a"] else "FAIL"),
- "口径B(模型链)npu/模型链 = %.1f%% → %s"
- % (float(summary["ratio_b"]) * 100.0, "PASS" if summary["pass_b"] else "FAIL"),
- "NPU 硬件占用率: %s" % load_text,
- (
- "实测吞吐: %.1f fps(等帧 %.2f ms/帧,仅 --producer 统计,不进口径A 分母)"
- % (float(summary.get("fps", 0.0)), float(mean_ms.get("wait", 0.0)))
- if float(summary.get("fps", 0.0)) > 0.0
- else "实测吞吐: 未采样(没有 period_ms:旧版采样或手工构造的数据)"
- ),
- "参考口径Wall(npu/含等帧墙钟)= %.1f%%" % (float(summary.get("ratio_wall", 0.0)) * 100.0),
- "诊断: %s" % _hint(summary),
- ]
- if float(summary.get("min_fps", 0.0)) > 0.0:
- lines.append(
- "配对门禁: 需 %.1f fps,实测 %.1f fps → %s"
- % (
- float(summary["min_fps"]),
- float(summary.get("fps", 0.0)),
- "满足" if summary.get("pass_fps") else "不满足(占比再高也不能算达标)",
- )
- )
- return "\n".join(lines)
- def _fresh_frame(grabber, seen: int, timeout: float = 5.0):
- """等一帧 ``frame_id`` 比 ``seen`` 更新的帧;返回 ``(frame, 等待秒数)``,超时返回 ``(None, 秒数)``。"""
- start = time.perf_counter()
- deadline = start + timeout
- while time.perf_counter() < deadline:
- frame = grabber.latest
- if frame is not None and frame.frame_id > seen:
- return frame, time.perf_counter() - start
- time.sleep(0.002)
- return None, time.perf_counter() - start
- def measure(
- cfg,
- frames: int,
- video: str = "",
- warmup: int = 3,
- producer: bool = False,
- ) -> List[Dict[str, float]]:
- """跑真实帧并采样逐阶段耗时;返回逐帧采样列表。
- * ``producer=False``(默认):串行 ``cap.read()``,``decode_ms`` 计入分母 —— **保守口径**,
- 适合当门禁,因为它假设最坏情况(解码与推理完全不重叠);
- * ``producer=True``:用 :class:`~portcv.io.capture.FrameGrabber` 后台线程取帧(与生产一致),
- 解码与推理并行,只把等帧时间记进 ``wait_ms``,**不进口径 A 分母**。
- 给了 ``video`` 时一律按本地文件打开(``source_type=file``、关掉 GStreamer 管线),
- 避免拿现场 ``rtsp`` 配置去读本地片段时打不开。
- """
- from portcv.io.capture import FrameGrabber, open_capture
- detector = build_detector(cfg)
- source = video or str(cfg.get_path("source.uri", "samples/demo.mp4"))
- samples: List[Dict[str, float]] = []
- total = max(1, int(frames))
- warmup_n = max(0, int(warmup))
- def record(stages: Dict[str, float], decode_ms: float, wait_ms: float, period_ms: float) -> None:
- samples.append(
- {
- "decode_ms": decode_ms,
- "wait_ms": wait_ms,
- "period_ms": period_ms,
- "preproc_ms": float(stages.get("preproc", 0.0)),
- "npu_ms": float(stages.get("npu", 0.0)),
- "postproc_ms": float(stages.get("postproc", 0.0)),
- "npu_load": read_npu_load(),
- }
- )
- prev_t: Optional[float] = None
- if producer:
- grabber = FrameGrabber(cfg)
- if video:
- grabber.uri = video
- grabber.source_type = "file"
- grabber.use_gst = False
- grabber.start()
- if not grabber.opened:
- grabber.stop()
- raise RuntimeError(
- "打不开视频源: %s(source.type=%s,检查路径 / RTSP 地址)"
- % (grabber.uri, grabber.source_type)
- )
- seen = 0
- try:
- for _ in range(warmup_n):
- frame, _wait = _fresh_frame(grabber, seen)
- if frame is None:
- break
- seen = frame.frame_id
- detector.infer(frame.image)
- while len(samples) < total:
- frame, wait_s = _fresh_frame(grabber, seen)
- if frame is None:
- break
- seen = frame.frame_id
- started = time.perf_counter()
- detector.infer(frame.image)
- stages = getattr(detector, "stage_ms", None) or {}
- period_ms = 0.0 if prev_t is None else (started - prev_t) * 1000.0
- prev_t = started
- record(stages, 0.0, wait_s * 1000.0, period_ms)
- finally:
- grabber.stop()
- detector.close()
- else:
- cap = open_capture(source, use_gst=bool(cfg.get_path("source.use_gst", False)))
- if not cap.isOpened():
- raise RuntimeError("打不开视频源: %s" % source)
- try:
- for _ in range(warmup_n):
- ok, frame = cap.read()
- if not ok or frame is None:
- break
- detector.infer(frame)
- while len(samples) < total:
- start = time.perf_counter()
- ok, frame = cap.read()
- grabbed = time.perf_counter()
- if not ok or frame is None:
- break
- detector.infer(frame)
- stages = getattr(detector, "stage_ms", None) or {}
- period_ms = 0.0 if prev_t is None else (start - prev_t) * 1000.0
- prev_t = start
- record(stages, (grabbed - start) * 1000.0, 0.0, period_ms)
- finally:
- cap.release()
- detector.close()
- if not samples:
- raise RuntimeError("没有取到任何帧(检查 --video / source.uri)")
- return samples
- def check_env(cfg) -> int:
- """打印运行环境就绪度(不需要模型也能跑,现场排查第一条命令)。"""
- import importlib.util
- backend = str(cfg.get_path("run.backend", "mock"))
- model = str(cfg.get_path("model.rknn_path", ""))
- board = detect_board()
- cores = detect_npu_cores(board)
- core = str(cfg.get_path("model.rknn_core", "auto"))
- mask, note = resolve_core_mask(core, cores)
- load = read_npu_load()
- has_lite = importlib.util.find_spec("rknnlite") is not None
- rows = [
- ("run.backend", backend, backend.lower() == "rknn"),
- ("板型", board or "未识别", bool(board)),
- ("NPU core 数", str(cores or "未知"), cores > 0),
- ("core_mask", "%s → %d%s" % (core, mask, "(已收敛)" if note else ""), not note),
- ("RKNN 模型", model if os.path.isfile(model) else "%s(不存在)" % model, os.path.isfile(model)),
- ("rknnlite", "已安装" if has_lite else "未安装", has_lite),
- (
- "NPU 负载节点",
- "可读 %.0f%%" % (float(load) * 100.0) if load is not None else "不可读",
- load is not None,
- ),
- ]
- print("== 环境检查 ==")
- for name, value, ok in rows:
- print(" [%s] %-14s %s" % ("OK" if ok else "缺失", name, value))
- if note:
- print(" 提示: %s" % note)
- notes = _config_warnings(cfg, producer=True)
- if notes:
- print("== 口径提示 ==")
- for item in notes:
- print(" * %s" % item)
- blockers = [name for name, _, ok in rows if not ok]
- if blockers:
- print("结论: 还不能测(缺 %s)" % "、".join(blockers))
- return 1
- print("结论: 环境就绪,可以开始测量")
- return 0
- def main(argv: Optional[Sequence[str]] = None) -> int:
- parser = argparse.ArgumentParser(description="量 NPU 时间占比(Rockchip RKNPU2 板卡)")
- parser.add_argument("--config", required=True, help="配置文件(需 run.backend=rknn)")
- parser.add_argument("--video", default="", help="覆盖 source.uri,建议用现场片段保证可重复")
- parser.add_argument("--frames", type=int, default=100, help="测量帧数(预热不计入)")
- parser.add_argument("--warmup", type=int, default=3, help="预热帧数")
- parser.add_argument("--target", type=float, default=0.70, help="达标线(默认 0.70)")
- parser.add_argument(
- "--extra-ms",
- dest="extra_ms",
- type=float,
- default=0.0,
- help="补上未计时的固定开销(决策/投票/Modbus 发布),单位 ms",
- )
- parser.add_argument("--json", default="", help="结果写成 json(验收证据)")
- parser.add_argument(
- "--producer",
- action="store_true",
- help="用 FrameGrabber 后台线程取帧(与生产一致:解码与推理并行,decode 不进口径A 分母)",
- )
- parser.add_argument(
- "--min-fps",
- dest="min_fps",
- type=float,
- default=0.0,
- help="配对门禁:除占比外还要求实测 fps ≥ 该值(0=不检查)",
- )
- parser.add_argument("--check", action="store_true", help="只检查环境,不跑推理")
- args = parser.parse_args(argv)
- cfg = load_config(args.config)
- if args.check:
- return check_env(cfg)
- warnings = _config_warnings(cfg, producer=bool(args.producer))
- for item in warnings:
- print("提示: %s" % item)
- samples = measure(cfg, args.frames, args.video, args.warmup, producer=bool(args.producer))
- summary = summarize(samples, args.target, args.extra_ms, args.min_fps)
- summary["producer"] = bool(args.producer)
- summary["warnings"] = warnings
- print(format_report(summary))
- if args.json:
- target = os.path.abspath(args.json)
- os.makedirs(os.path.dirname(target) or ".", exist_ok=True)
- with open(target, "w", encoding="utf-8") as fh:
- json.dump(
- {"config": args.config, "video": args.video, "summary": summary},
- fh,
- ensure_ascii=False,
- indent=2,
- )
- print("已写出:%s" % target)
- return 0 if summary["pass"] else 1
- if __name__ == "__main__":
- sys.exit(main())
|