File size: 3,176 Bytes
0f131e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
# SPDX-License-Identifier: Apache-2.0
"""Torch fp32 reference vs ONNX Runtime on input npz files: per-output and per-tap error stats (host only)."""
import argparse
import json
import os
import sys
import time

import numpy as np

sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
from tt_meteor2.reference import config as C  # noqa: E402
from tt_meteor2.reference.model import Meteor2Net  # noqa: E402
from tt_meteor2.reference.ort import ORT_TAPS, OrtOracle  # noqa: E402
from tt_meteor2.reference.weights import Meteor2Weights  # noqa: E402
from tt_meteor2.ttaw.metrics import pcc  # noqa: E402


def stats(a, b):
    a = np.asarray(a, np.float64)
    b = np.asarray(b, np.float64)
    d = np.abs(a - b)
    return {"pcc": float(pcc(a, b)), "max_abs": float(d.max()), "ref_absmax": float(np.abs(b).max())}


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--model-dir", default=os.path.expanduser(f"~/data/tt-autoware/meteor2/{C.WEIGHTS_REVISION}"))
    ap.add_argument("--form", choices=C.FORMS, required=True)
    ap.add_argument("--threads", type=int, default=8)
    ap.add_argument("--json")
    ap.add_argument("inputs", nargs="+")
    a = ap.parse_args()
    import torch
    torch.set_num_threads(a.threads)
    path = os.path.join(a.model_dir, C.ONNX_FILES[a.form])
    net = Meteor2Net(Meteor2Weights(path))
    ort = OrtOracle(path, a.form, taps=ORT_TAPS[a.form].keys(), threads=a.threads)
    report = {}
    for f in a.inputs:
        z = dict(np.load(f))
        kw = {k: z[k] for k in ("imgs", "K", "T_cam_ego", "v0", "acc", "ego_hist", "route")}
        t = time.time()
        o_ort = ort.run(ort.feeds(**kw))
        t_ort = time.time() - t
        taps = {}
        t = time.time()
        o_ref = net(**kw, taps=taps)
        t_ref = time.time() - t
        r = {"ort_s": round(t_ort, 2), "ref_s": round(t_ref, 2)}
        for k in C.OUTPUT_NAMES:
            r[k] = stats(o_ref[k], o_ort[k])
        for k in ORT_TAPS[a.form]:
            v = taps[k].numpy() if hasattr(taps[k], "numpy") else taps[k]
            r["tap:" + k] = stats(v.reshape(o_ort[k].shape), o_ort[k])
        # decisions
        r["lane_argmax_agree"] = float((o_ref["lane_logit"].argmax(1) == o_ort["lane_logit"].argmax(1)).mean())
        r["occ_argmax_agree"] = float((o_ref["occ_logit"].argmax(1) == o_ort["occ_logit"].argmax(1)).mean())
        r["tl_same"] = bool(o_ref["tl"].argmax() == o_ort["tl"].argmax())
        report[os.path.basename(f)] = r
        worst = sorted(((k, v["pcc"], v["max_abs"]) for k, v in r.items() if isinstance(v, dict)), key=lambda x: x[1])[:6]
        print(os.path.basename(f), a.form, f"ort {t_ort:.1f}s ref {t_ref:.1f}s", "lane", r["lane_argmax_agree"],
              "occ", r["occ_argmax_agree"], "tl", r["tl_same"])
        for k, p, m in worst:
            print(f"   {k:22s} pcc {p:.9f} max_abs {m:.3e}")
        for k in ("ego", "ego_path_6s", "tl"):
            print(f"   {k:22s} max_abs {r[k]['max_abs']:.3e} (ref absmax {r[k]['ref_absmax']:.3g})")
    if a.json:
        json.dump(report, open(a.json, "w"), indent=1)


if __name__ == "__main__":
    main()