File size: 5,420 Bytes
2230fab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
# SPDX-License-Identifier: Apache-2.0
"""Render the p150 output on the shipped sample next to the stored fp32 CPU reference (the card's ``media/``).

    # on the device (one serve profile after the other), from the repo root:
    bin/devrun -t 900 -- python code/scripts/make_demo.py --out-dir media --json-dir <dir>
    # from stored outputs (no device):
    python code/scripts/make_demo.py --tt-json base=<dir>/test_pcd.base.tt.json --tt-json tiny=<...> --out-dir media

For every variant: ``CenterPoint.from_pretrained(variant=...)`` (ETH dispatch, 12x10, the traced graph) runs the input
through the Python API, which returns exactly what ``POST /predict`` returns; the output is matched with the stored
CPU reference ``<stem>.<variant>.reference.json`` next to the input by the rule of the accuracy gates (same label,
BEV centre distance <= 0.5 m, ``ttaw.metrics.match_detections``) and drawn over it as a bird's-eye view
(``tt_centerpoint.viz.render_bev``: p150 boxes in colour, reference boxes as light outlines, unmatched boxes ringed and
tagged) to ``<out-dir>/<stem>_<variant>_tt_vs_cpu.png``. ``--json-dir`` keeps the p150 bodies.
"""
from __future__ import annotations

import argparse
import json
import sys
from pathlib import Path

import numpy as np

HERE = Path(__file__).resolve().parent
CODE = HERE.parent
if str(CODE) not in sys.path:
    sys.path.insert(0, str(CODE))

from tt_centerpoint.ttaw.metrics import match_detections  # noqa: E402
from tt_centerpoint.viz import load_xyz, render_bev  # noqa: E402

SAMPLE = CODE / "tt_centerpoint" / "samples" / "test_pcd.npz"
TITLES = {"base": "CenterPoint (base)", "tiny": "CenterPoint-tiny"}


def rows(dets):
    boxes = np.array([d["center"] + d["size"] + [d["yaw"]] for d in dets], np.float32).reshape(-1, 7)
    return boxes, np.array([d["label_id"] for d in dets], np.int64), np.array([d["score"] for d in dets], np.float32)


def agreement(tt: dict, ref: dict) -> dict:
    m = match_detections(*rows(tt["detections"]), *rows(ref["detections"]), max_dist=0.5)
    out = m.to_dict()
    out.update(dev=len(tt["detections"]), ref=len(ref["detections"]),
               max_score_err=float(max(m.score_errors, default=0.0)))
    return out


def run_device(path: Path, variant: str, device_id: int) -> dict:
    from tt_centerpoint import CenterPoint

    with CenterPoint.from_pretrained(device_id=device_id, variant=variant) as model:
        out = model(str(path))
        body = out.to_dict()
        body["device"] = model.info.get("device")
    return body


def main(argv=None) -> int:
    ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
    ap.add_argument("--input", type=Path, default=SAMPLE)
    ap.add_argument("--variants", default="base,tiny")
    ap.add_argument("--out-dir", type=Path, default=CODE.parent / "media")
    ap.add_argument("--json-dir", type=Path, help="write the p150 output bodies here")
    ap.add_argument("--tt-json", action="append", default=[], help="VARIANT=FILE: a stored p150 body (no device)")
    ap.add_argument("--device-id", type=int, default=0)
    ap.add_argument("--width", type=int, default=450, help="panel width in pixels")
    a = ap.parse_args(argv)
    stored = dict(item.split("=", 1) for item in a.tt_json)
    points = load_xyz(a.input)
    a.out_dir.mkdir(parents=True, exist_ok=True)
    bodies, refs = {}, {}
    for v in a.variants.split(","):
        ref_path = a.input.with_name(f"{a.input.stem}.{v}.reference.json")
        refs[v] = json.loads(ref_path.read_text())
        bodies[v] = json.loads(Path(stored[v]).read_text()) if v in stored else run_device(a.input, v, a.device_id)
        if a.json_dir:
            a.json_dir.mkdir(parents=True, exist_ok=True)
            (a.json_dir / f"{a.input.stem}.{v}.tt.json").write_text(json.dumps(bodies[v], indent=1))
    every = [d for v in bodies for d in bodies[v]["detections"] + refs[v]["detections"]]
    xs = [d["center"][0] for d in every] + [-10.0, 20.0]
    ys = [d["center"][1] for d in every] + [-15.0, 15.0]
    x_range = (max(min(xs) - 6.0, -76.8), min(max(xs) + 6.0, 76.8))
    y_range = (max(min(ys) - 6.0, -76.8), min(max(ys) + 6.0, 76.8))
    for v, body in bodies.items():
        ag = agreement(body, refs[v])
        dev = body.get("device") or {}
        where = f"dispatch {dev.get('dispatch', 'eth')}, grid {dev.get('grid', '12x10')}"
        lines = [f"p150 ({where}) vs the fp32 CPU reference of the same network: {ag['matched']} of {ag['ref']} "
                 f"reference detections matched (same label, centres <= 0.5 m), {ag['dev']} on the p150; max |score "
                 f"difference| of matched pairs {ag['max_score_err']:.4f}.",
                 f"Input: {a.input.name} (Autoware's test.pcd, Apache-2.0), one sweep, "
                 f"{body['meta'].get('num_points', len(points))} points, {body['meta']['num_pillars']} pillars. "
                 "Forward up, rings every 10 m."]
        img = render_bev(points, body["detections"], reference=refs[v]["detections"],
                         title=f"{TITLES.get(v, v)} on one Blackhole p150 vs fp32 CPU reference",
                         lines=lines, x_range=x_range, y_range=y_range, width=a.width)
        out = a.out_dir / f"{a.input.stem}_{v}_tt_vs_cpu.png"
        img.save(out, optimize=True)
        print(f"{out}: {json.dumps(ag)}")
    return 0


if __name__ == "__main__":
    sys.exit(main())