|
|
@@ -0,0 +1,266 @@
|
|
|
+"""ONNX ↔ RKNN 数值一致性校验(在**板子**上跑:同一进程里两个引擎各推一次)。
|
|
|
+
|
|
|
+为什么需要它
|
|
|
+------------
|
|
|
+``rknn.build()`` 返回 0、``rknnlite.inference()`` 也不报错,**都不代表模型算对了**。
|
|
|
+本项目踩过一次真实故障:rknn-toolkit2 2.5.0 编 YOLOv8 检测头(DFL 1×1 conv)先崩,
|
|
|
+按它的提示禁用 ``seperate_conv_rs_split`` 后编译通过,但产出的 ``.rknn`` 输出与输入几乎无关
|
|
|
+(黑图/实拍图结果雷同、类别行整行常数),现场只表现为「框全错」,没有数值证据很难定位。
|
|
|
+换成 2.3.2 后同一份 ONNX 的 cos = 1.000000。
|
|
|
+
|
|
|
+所以**每次转换后**都跑一遍本脚本:同一张图分别喂 ONNX(onnxruntime) 与 RKNN(rknnlite),
|
|
|
+比较张量余弦相似度、top-K anchor 重合度、以及解码后的框(数量/坐标/IoU)。
|
|
|
+
|
|
|
+用法
|
|
|
+----
|
|
|
+.. code-block:: bash
|
|
|
+
|
|
|
+ # 板子上(rknnlite 与 onnxruntime 都可导入)
|
|
|
+ python scripts/verify_rknn.py --onnx weights/demo/yolov8n.onnx \
|
|
|
+ --rknn weights/demo/yolov8n.rknn --image samples/bus.jpg \
|
|
|
+ --config configs/demo-yolov8n.json
|
|
|
+
|
|
|
+ # 只比张量、不解码(模型不是 YOLO 检测头时)
|
|
|
+ python scripts/verify_rknn.py --onnx a.onnx --rknn a.rknn --image x.jpg --no-decode
|
|
|
+
|
|
|
+退出码:``0`` 通过;``1`` 数值不达标;``2`` 环境/文件缺失(缺 rknnlite、onnxruntime 等)。
|
|
|
+"""
|
|
|
+
|
|
|
+from __future__ import annotations
|
|
|
+
|
|
|
+import argparse
|
|
|
+import os
|
|
|
+import sys
|
|
|
+from typing import List, Optional, Sequence, Tuple
|
|
|
+
|
|
|
+import numpy as np
|
|
|
+
|
|
|
+REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
|
+sys.path.insert(0, REPO)
|
|
|
+
|
|
|
+__all__ = ["canonical", "cosine", "match_boxes", "main"]
|
|
|
+
|
|
|
+
|
|
|
+def _force_utf8() -> None:
|
|
|
+ """Windows/重定向下中文输出不崩(与其它脚本一致)。"""
|
|
|
+
|
|
|
+ for stream in (sys.stdout, sys.stderr):
|
|
|
+ try:
|
|
|
+ stream.reconfigure(encoding="utf-8", errors="replace")
|
|
|
+ except Exception: # pragma: no cover - 老 Python / 被重定向的流
|
|
|
+ pass
|
|
|
+
|
|
|
+
|
|
|
+def cosine(a: np.ndarray, b: np.ndarray) -> float:
|
|
|
+ """展平后的余弦相似度;任一侧全 0 时返回 0(而不是 NaN)。"""
|
|
|
+
|
|
|
+ x = np.asarray(a, dtype=np.float64).ravel()
|
|
|
+ y = np.asarray(b, dtype=np.float64).ravel()
|
|
|
+ if x.size != y.size:
|
|
|
+ raise ValueError("张量元素数不一致: %d vs %d" % (x.size, y.size))
|
|
|
+ nx = float(np.linalg.norm(x))
|
|
|
+ ny = float(np.linalg.norm(y))
|
|
|
+ if nx <= 0.0 or ny <= 0.0:
|
|
|
+ return 0.0
|
|
|
+ return float(x @ y / (nx * ny))
|
|
|
+
|
|
|
+
|
|
|
+def canonical(raw: np.ndarray, nc: int) -> np.ndarray:
|
|
|
+ """把检测头张量统一成 ``(N, 4+nc)``(列 = xywh + 类别分数),忽略 batch 维。"""
|
|
|
+
|
|
|
+ arr = np.asarray(raw, dtype=np.float32)
|
|
|
+ while arr.ndim > 2:
|
|
|
+ arr = arr[0]
|
|
|
+ if arr.ndim == 1:
|
|
|
+ arr = arr[None]
|
|
|
+ cols = int(arr.shape[1])
|
|
|
+ if cols != 4 + nc and int(arr.shape[0]) == 4 + nc:
|
|
|
+ arr = arr.T
|
|
|
+ return np.ascontiguousarray(arr)
|
|
|
+
|
|
|
+
|
|
|
+def match_boxes(ref: Sequence[object], got: Sequence[object]) -> Tuple[int, float]:
|
|
|
+ """同类贪心匹配:返回 ``(匹配数, 平均 IoU)``;类别不同算不匹配。"""
|
|
|
+
|
|
|
+ used = [False] * len(got)
|
|
|
+ ious: List[float] = []
|
|
|
+ for a in ref:
|
|
|
+ best, best_idx = 0.0, -1
|
|
|
+ for idx, b in enumerate(got):
|
|
|
+ if used[idx] or getattr(a, "class_id", -1) != getattr(b, "class_id", -2):
|
|
|
+ continue
|
|
|
+ ix1, iy1 = max(a.x1, b.x1), max(a.y1, b.y1)
|
|
|
+ ix2, iy2 = min(a.x2, b.x2), min(a.y2, b.y2)
|
|
|
+ inter = max(0.0, ix2 - ix1) * max(0.0, iy2 - iy1)
|
|
|
+ union = a.width * a.height + b.width * b.height - inter
|
|
|
+ iou = (inter / union) if union > 0 else 0.0
|
|
|
+ if iou > best:
|
|
|
+ best, best_idx = iou, idx
|
|
|
+ if best_idx >= 0 and best > 0.0:
|
|
|
+ used[best_idx] = True
|
|
|
+ ious.append(best)
|
|
|
+ return len(ious), (float(sum(ious) / len(ious)) if ious else 0.0)
|
|
|
+
|
|
|
+
|
|
|
+def _check_files(args) -> Optional[int]:
|
|
|
+ for path, what in ((args.onnx, "ONNX"), (args.rknn, "RKNN"), (args.image, "图片")):
|
|
|
+ if not os.path.isfile(path):
|
|
|
+ print("✗ %s 不存在: %s" % (what, path))
|
|
|
+ return 2
|
|
|
+ if args.config and not os.path.isfile(args.config):
|
|
|
+ print("✗ 配置文件不存在: %s" % args.config)
|
|
|
+ return 2
|
|
|
+ return None
|
|
|
+
|
|
|
+
|
|
|
+def _build_parser() -> argparse.ArgumentParser:
|
|
|
+ parser = argparse.ArgumentParser(description="ONNX ↔ RKNN 数值一致性校验")
|
|
|
+ parser.add_argument("--onnx", required=True, help="参考 ONNX(onnxruntime 推理)")
|
|
|
+ parser.add_argument("--rknn", required=True, help="待校验的 .rknn(rknnlite 推理)")
|
|
|
+ parser.add_argument("--image", required=True, help="一张真实图片(建议现场截图)")
|
|
|
+ parser.add_argument("--config", default=None, help="取 model.labels / input_size / input_format")
|
|
|
+ parser.add_argument(
|
|
|
+ "--input-format",
|
|
|
+ dest="input_format",
|
|
|
+ default=None,
|
|
|
+ help="rknn 输入格式:rgb_uint8(默认,FP16/INT8 归一化模型)| rgb_float | bgr_uint8",
|
|
|
+ )
|
|
|
+ parser.add_argument("--size", type=int, default=0, help="输入边长(默认取配置或 640)")
|
|
|
+ parser.add_argument("--conf", type=float, default=0.35, help="解码置信度阈值")
|
|
|
+ parser.add_argument("--iou", type=float, default=0.5, help="解码 NMS 阈值")
|
|
|
+ parser.add_argument("--min-cos", dest="min_cos", type=float, default=0.99,
|
|
|
+ help="判定通过的整体/类别余弦相似度下限")
|
|
|
+ parser.add_argument("--min-iou", dest="min_iou", type=float, default=0.9,
|
|
|
+ help="判定通过的解码框平均 IoU 下限")
|
|
|
+ parser.add_argument("--topk", type=int, default=50, help="比较 top-K anchor 的 K")
|
|
|
+ parser.add_argument("--no-decode", dest="decode", action="store_false",
|
|
|
+ help="只比张量,不解码框(非检测头模型用)")
|
|
|
+ parser.add_argument("--dump", default=None, help="把两个张量存成 .npy 到该目录(排查用)")
|
|
|
+ return parser
|
|
|
+
|
|
|
+
|
|
|
+def main(argv=None) -> int:
|
|
|
+ _force_utf8()
|
|
|
+ args = _build_parser().parse_args(argv)
|
|
|
+ bad = _check_files(args)
|
|
|
+ if bad is not None:
|
|
|
+ return bad
|
|
|
+
|
|
|
+ try:
|
|
|
+ import cv2
|
|
|
+ import onnxruntime as ort
|
|
|
+ except ImportError as exc:
|
|
|
+ print("✗ 需要 opencv + onnxruntime: %s" % exc)
|
|
|
+ return 2
|
|
|
+ try:
|
|
|
+ from rknnlite.api import RKNNLite # type: ignore
|
|
|
+ except ImportError as exc:
|
|
|
+ print("✗ 需要 rknnlite(只在 RK 板子上有): %s" % exc)
|
|
|
+ return 2
|
|
|
+
|
|
|
+ from portcv.config import load_config
|
|
|
+ from portcv.detect.preproc import letterbox, to_blob
|
|
|
+
|
|
|
+ cfg = load_config(args.config) if args.config else None
|
|
|
+ size = int(args.size) or 640
|
|
|
+ if cfg is not None and not args.size:
|
|
|
+ cfg_size = list(cfg.input_size or [])
|
|
|
+ if len(cfg_size) == 2:
|
|
|
+ size = int(cfg_size[0])
|
|
|
+ labels = list(cfg.labels or []) if cfg is not None else []
|
|
|
+ default_fmt = cfg.get_path("model.input_format", "rgb_uint8") if cfg is not None else "rgb_uint8"
|
|
|
+ input_format = str(args.input_format or default_fmt).lower()
|
|
|
+
|
|
|
+ image = cv2.imread(args.image)
|
|
|
+ if image is None:
|
|
|
+ print("✗ 图片读不出来: %s" % args.image)
|
|
|
+ return 2
|
|
|
+ height, width = image.shape[:2]
|
|
|
+ padded, ratio, pad = letterbox(image, (size, size))
|
|
|
+
|
|
|
+ # --- ONNX 参考(NCHW float,与 OnnxDetector 口径一致) ------------------
|
|
|
+ sess = ort.InferenceSession(args.onnx, providers=["CPUExecutionProvider"])
|
|
|
+ ref_raw = sess.run(None, {sess.get_inputs()[0].name: to_blob(padded, "rgb_float")})[0]
|
|
|
+
|
|
|
+ # --- RKNN 待测(布局必须显式声明:不给 data_format 会被当成 NHWC) ------
|
|
|
+ lite = RKNNLite(verbose=False)
|
|
|
+ if lite.load_rknn(args.rknn) != 0:
|
|
|
+ print("✗ load_rknn 失败(板子 librknnrt 与模型版本不匹配?): %s" % args.rknn)
|
|
|
+ return 2
|
|
|
+ if lite.init_runtime() != 0:
|
|
|
+ print("✗ init_runtime 失败: %s" % args.rknn)
|
|
|
+ return 2
|
|
|
+ fmt = "nhwc" if input_format.endswith("uint8") else "nchw"
|
|
|
+ try:
|
|
|
+ got_raw = lite.inference(inputs=[to_blob(padded, input_format)], data_format=fmt)[0]
|
|
|
+ finally:
|
|
|
+ lite.release()
|
|
|
+
|
|
|
+ return _report(args, ref_raw, got_raw, labels, ratio, pad, (width, height), input_format, fmt)
|
|
|
+
|
|
|
+
|
|
|
+def _report(args, ref_raw, got_raw, labels, ratio, pad, image_size, input_format, fmt) -> int:
|
|
|
+ ref_arr = np.asarray(ref_raw, dtype=np.float32)
|
|
|
+ got_arr = np.asarray(got_raw, dtype=np.float32)
|
|
|
+ nc = len(labels)
|
|
|
+ if not nc and ref_arr.ndim >= 2 and ref_arr.shape[1] < ref_arr.shape[-1]:
|
|
|
+ # 没有标签时从形状反推: (1, 4+nc, N)
|
|
|
+ nc = max(0, int(ref_arr.shape[1]) - 4)
|
|
|
+ ref2 = canonical(ref_arr, nc)
|
|
|
+ got2 = canonical(got_arr, nc)
|
|
|
+
|
|
|
+ print("ONNX 输出 %s | RKNN 输出 %s → 归一化 %s" % (ref_arr.shape, got_arr.shape, ref2.shape))
|
|
|
+ print("输入:%s %dx%d(letterbox ratio=%.4f pad=%s)→ %s / %s"
|
|
|
+ % (os.path.basename(args.image), image_size[0], image_size[1],
|
|
|
+ ratio, pad, input_format, fmt))
|
|
|
+ print("数值范围:ONNX [%.3f, %.3f] | RKNN [%.3f, %.3f]"
|
|
|
+ % (ref2.min(), ref2.max(), got2.min(), got2.max()))
|
|
|
+
|
|
|
+ all_cos = cosine(ref2, got2)
|
|
|
+ box_cos = cosine(ref2[:, :4], got2[:, :4])
|
|
|
+ cls_cos = cosine(ref2[:, 4:], got2[:, 4:]) if ref2.shape[1] > 4 else 1.0
|
|
|
+ k = max(1, min(int(args.topk), ref2.shape[0]))
|
|
|
+ if ref2.shape[1] > 4:
|
|
|
+ ref_top = set(int(v) for v in np.argsort(-ref2[:, 4:].max(axis=1))[:k])
|
|
|
+ got_top = set(int(v) for v in np.argsort(-got2[:, 4:].max(axis=1))[:k])
|
|
|
+ overlap = len(ref_top & got_top)
|
|
|
+ else:
|
|
|
+ overlap = k
|
|
|
+
|
|
|
+ print("余弦相似度:整体 %.6f | 框(前 4 行) %.6f | 类别 %.6f" % (all_cos, box_cos, cls_cos))
|
|
|
+ print("top-%d anchor 重合:%d/%d" % (k, overlap, k))
|
|
|
+ if args.dump:
|
|
|
+ os.makedirs(args.dump, exist_ok=True)
|
|
|
+ np.save(os.path.join(args.dump, "onnx.npy"), ref2)
|
|
|
+ np.save(os.path.join(args.dump, "rknn.npy"), got2)
|
|
|
+ print("张量已存到 %s(onnx.npy / rknn.npy)" % args.dump)
|
|
|
+
|
|
|
+ ok = all_cos >= args.min_cos and cls_cos >= args.min_cos
|
|
|
+ if args.decode and labels and ref2.shape[1] == 4 + len(labels):
|
|
|
+ from portcv.detect.postproc import decode_yolo_output
|
|
|
+
|
|
|
+ kwargs = dict(labels=labels, conf_thres=args.conf, iou_thres=args.iou, max_det=300,
|
|
|
+ nms_free=False, ratio=ratio, pad=pad, image_size=image_size)
|
|
|
+ ref_boxes = decode_yolo_output(ref2, **kwargs)
|
|
|
+ got_boxes = decode_yolo_output(got2, **kwargs)
|
|
|
+ matched, mean_iou = match_boxes(ref_boxes, got_boxes)
|
|
|
+ print("解码框:ONNX %d 个 | RKNN %d 个 | 同类匹配 %d 个,平均 IoU %.4f"
|
|
|
+ % (len(ref_boxes), len(got_boxes), matched, mean_iou))
|
|
|
+ for box in sorted(got_boxes, key=lambda b: -b.score)[:5]:
|
|
|
+ print(" RKNN %-12s %.3f [%.0f,%.0f,%.0f,%.0f]"
|
|
|
+ % (box.class_name, box.score, box.x1, box.y1, box.x2, box.y2))
|
|
|
+ if ref_boxes:
|
|
|
+ ok = ok and matched >= max(1, len(ref_boxes) // 2) and mean_iou >= args.min_iou
|
|
|
+ elif got_boxes:
|
|
|
+ ok = False
|
|
|
+
|
|
|
+ if ok:
|
|
|
+ print("✓ PASS(cos ≥ %.4f,框对得上)" % args.min_cos)
|
|
|
+ return 0
|
|
|
+ print("✗ FAIL:先确认 toolkit 版本(YOLOv8 用 rknn-toolkit2 2.3.2)、"
|
|
|
+ "input_format 与 mean/std 是否匹配,再重新转换。")
|
|
|
+ return 1
|
|
|
+
|
|
|
+
|
|
|
+if __name__ == "__main__": # pragma: no cover
|
|
|
+ sys.exit(main())
|