File size: 9,978 Bytes
7d7fddc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
# SPDX-License-Identifier: Apache-2.0
"""The three networks on KITScenes frames on the p150 against the onnxruntime fp32 reference (run under bin/devrun):

    python -m tt_visionpilot.tests.dev_kitscenes --frames /weights/kitscenes_frames --ref /weights/kitscenes_ref \
        [--scenes ...] [--json OUT]

The three traces share one device (captured once each). Per frame the network images are made exactly as
``tools/kitscenes_ref.py`` makes them (same OpenCV 4.11): AutoSteer / AutoSpeed from the virtual front camera,
AutoDrive from the 50 deg crop, as (frame i-1, frame i) pairs. Metrics per scene:

- AutoSteer: |xp - xp_ref| (xp is a fraction of the image width: x 1024 gives network pixels) and |h - h_ref|;
- AutoSpeed: VisionPilot's decoded detections matched greedily per frame (same class, IoU >= 0.5): recall,
  precision, IoU of the matches, |score - score_ref|; unmatched ones listed with their raw probability (a raw
  probability near VisionPilot's effective threshold 0.405 can fall on either side);
- AutoDrive: |dist - dist_ref| (x 150 m), |curv - curv_ref| (x 0.21 1/m), |sigmoid(flag) - sigmoid(flag_ref)| and
  the agreement of the presence decision (probability >= 0.5);
- device time per frame of each network (upload + replay + read).
"""
from __future__ import annotations

import argparse
import json
import time
from pathlib import Path

import numpy as np

from ..graph import Graph
from ..host.prep import front_image, warped_image
from ..models import NETWORKS
from ..outputs import autospeed_decode


def iou(a, b) -> float:
    ix = max(0.0, min(a[2], b[2]) - max(a[0], b[0]))
    iy = max(0.0, min(a[3], b[3]) - max(a[1], b[1]))
    inter = ix * iy
    return inter / ((a[2] - a[0]) * (a[3] - a[1]) + (b[2] - b[0]) * (b[3] - b[1]) - inter + 1e-9)


def stats(v) -> dict:
    v = np.asarray([x for x in v if np.isfinite(x)], np.float64)
    if v.size == 0:
        return {"n": 0}
    return {"n": int(v.size), "median": float(np.median(v)), "p95": float(np.percentile(v, 95)),
            "p99": float(np.percentile(v, 99)), "max": float(v.max()), "mean": float(v.mean())}


def main(argv=None) -> int:
    import cv2

    from ..tt.runner import MultiNetRunner
    from ..ttaw.device import close_device, describe_device, open_device

    ap = argparse.ArgumentParser()
    ap.add_argument("--frames", default="/weights/kitscenes_frames")
    ap.add_argument("--ref", default="/weights/kitscenes_ref")
    ap.add_argument("--port", default="/weights/port")
    ap.add_argument("--scenes", nargs="*", default=None)
    ap.add_argument("--json", default=None)
    ap.add_argument("--save", default=None, help="directory for the device outputs per scene (npz)")
    args = ap.parse_args(argv)
    dev = open_device(0, dispatch="eth", num_command_queues=1, l1_small_size=32768, trace_region_size=192 << 20,
                      allow_fallback=False)
    print(json.dumps(describe_device(dev)))
    multi = None
    report = {}
    try:
        multi = MultiNetRunner(dev, {n: (NETWORKS[n], Graph(Path(args.port) / "folded" / f"{n}.onnx"))
                                     for n in ("autosteer", "autospeed", "autodrive")})
        multi.capture()
        print("capture", multi.timings)
        runners = {n: (lambda imgs, n=n: multi(n, imgs)) for n in multi.nets}
        scenes = args.scenes or sorted(p.stem for p in Path(args.ref).glob("*.npz"))
        for scene in scenes:
            meta = json.loads((Path(args.frames) / scene / "frames.json").read_text())
            ref = np.load(Path(args.ref) / f"{scene}.npz")
            H = ref["homography"]
            st = {"xp_px": [], "h_abs": [], "dist_m": [], "curv_per_m": [], "flag_p": [], "flag_agree": [],
                  "iou": [], "score_abs": [], "t_steer": [], "t_speed": [], "t_drive": [], "t_drive_stream": [],
                  "stream_vs_full": []}
            det_tp = det_ref = det_tt = 0
            unmatched = []
            prev = None
            saved = {"xp": [], "h": [], "dist": [], "curv": [], "flag": [], "dets": []}
            for k, f in enumerate(meta["frames"]):
                bgr = cv2.imread(str(Path(args.frames) / scene / f["file"]), cv2.IMREAD_COLOR)
                rgb = np.ascontiguousarray(bgr[..., ::-1])
                img, _ = front_image(rgb)
                t = time.perf_counter()
                o = runners["autosteer"]({"input": img})
                st["t_steer"].append((time.perf_counter() - t) * 1e3)
                xp, hv = o["lane_value"].ravel(), o["height"].ravel()
                st["xp_px"] += list(np.abs(xp - ref["xp"][k]) * 1024.0)
                st["h_abs"] += list(np.abs(hv - ref["h"][k]))
                t = time.perf_counter()
                o = runners["autospeed"]({"input": img})
                st["t_speed"].append((time.perf_counter() - t) * 1e3)
                b, s, c, p = autospeed_decode(o["output"])
                sel = ref["det_frame"] == f["index"]
                rb, rs, rc, rp = ref["det_box"][sel], ref["det_score"][sel], ref["det_cls"][sel], ref["det_pmax"][sel]
                det_ref += len(rs)
                det_tt += len(s)
                used = set()
                for i in range(len(s)):
                    best, bj = 0.0, -1
                    for j in range(len(rs)):
                        if j in used or rc[j] != c[i]:
                            continue
                        v = iou(b[i], rb[j])
                        if v > best:
                            best, bj = v, j
                    if bj >= 0 and best >= 0.5:
                        used.add(bj)
                        det_tp += 1
                        st["iou"].append(best)
                        st["score_abs"].append(abs(float(s[i]) - float(rs[bj])))
                    else:
                        unmatched.append({"frame": f["index"], "side": "tt", "pmax": float(p[i].max()),
                                          "score": float(s[i])})
                for j in range(len(rs)):
                    if j not in used:
                        unmatched.append({"frame": f["index"], "side": "ref", "pmax": float(rp[j]),
                                          "score": float(rs[j])})
                warped = warped_image(rgb, H)
                t = time.perf_counter()
                so = multi.stream("autodrive", warped, fresh=prev is None)
                st["t_drive_stream"].append((time.perf_counter() - t) * 1e3)
                if prev is not None:
                    t = time.perf_counter()
                    o = runners["autodrive"]({"image_prev": prev, "image_curr": warped})
                    st["t_drive"].append((time.perf_counter() - t) * 1e3)
                    d, cv_, fl = (float(o[n].ravel()[0]) for n in ("distance", "curvature", "flag_logit"))
                    st["stream_vs_full"].append(max(abs(float(so[n].ravel()[0]) - float(o[n].ravel()[0]))
                                                    for n in ("distance", "curvature", "flag_logit")))
                    st["dist_m"].append(abs(d - ref["dist"][k]) * 150.0)
                    st["curv_per_m"].append(abs(cv_ - ref["curv"][k]) * 0.21)
                    pt, pr = 1 / (1 + np.exp(-fl)), 1 / (1 + np.exp(-ref["flag"][k]))
                    st["flag_p"].append(abs(pt - pr))
                    st["flag_agree"].append(float((pt >= 0.5) == (pr >= 0.5)))
                    saved["dist"].append(d)
                    saved["curv"].append(cv_)
                    saved["flag"].append(fl)
                prev = warped
                saved["xp"].append(xp)
                saved["h"].append(hv)
                saved["dets"].append([(float(x1), float(y1), float(x2), float(y2), float(sc), int(cl))
                                      for (x1, y1, x2, y2), sc, cl in zip(b, s, c)])
            rep = {k: stats(v) for k, v in st.items() if k != "flag_agree"}
            rep["flag_agreement"] = float(np.mean(st["flag_agree"])) if st["flag_agree"] else None
            rep["autospeed"] = {"ref": det_ref, "tt": det_tt, "matched": det_tp,
                                "recall": det_tp / max(det_ref, 1), "precision": det_tp / max(det_tt, 1),
                                "unmatched": unmatched[:40]}
            rep["frames"] = len(meta["frames"])
            report[scene] = rep
            print(f"== {scene}: {rep['frames']} frames | steer xp px median {rep['xp_px'].get('median', 0):.3f} "
                  f"p99 {rep['xp_px'].get('p99', 0):.3f} max {rep['xp_px'].get('max', 0):.3f} | speed recall "
                  f"{rep['autospeed']['recall']:.4f} precision {rep['autospeed']['precision']:.4f} "
                  f"({det_tp}/{det_ref}/{det_tt}) | drive dist m median {rep['dist_m'].get('median', 0):.3f} "
                  f"p99 {rep['dist_m'].get('p99', 0):.3f}, curv 1/m p99 {rep['curv_per_m'].get('p99', 0):.2e}, flag p "
                  f"p99 {rep['flag_p'].get('p99', 0):.4f}, presence agree {rep['flag_agreement']} | ms steer "
                  f"{rep['t_steer'].get('median', 0):.2f} speed {rep['t_speed'].get('median', 0):.2f} drive "
                  f"{rep['t_drive'].get('median', 0):.2f} (stream {rep['t_drive_stream'].get('median', 0):.2f}, max |stream - full| "
                  f"{rep['stream_vs_full'].get('max', 0):.3g})")
            if args.save:
                Path(args.save).mkdir(parents=True, exist_ok=True)
                np.savez_compressed(Path(args.save) / f"{scene}.npz", xp=np.asarray(saved["xp"]),
                                    h=np.asarray(saved["h"]), dist=np.asarray(saved["dist"]),
                                    curv=np.asarray(saved["curv"]), flag=np.asarray(saved["flag"]),
                                    dets=np.asarray(json.dumps(saved["dets"])))
    finally:
        if multi is not None:
            multi.release()
        close_device(dev)
    if args.json:
        Path(args.json).write_text(json.dumps(report, indent=1))
    return 0


if __name__ == "__main__":
    raise SystemExit(main())