File size: 5,601 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 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 | #!/usr/bin/env python3
# SPDX-License-Identifier: Apache-2.0
"""The TIER IV demo scenes through the Python API on the p150 (bin/devrun), in the format of tt-autoware's CPU
reference run (``scripts/autoware/meteor2_ref.py``), so ``meteor2_ref.py --compare <cpu outputs> <these outputs>``
measures the device against the fp32 network frame by frame.
bin/devrun python scripts/eval_scenes.py --variant gather --route none recorded --out /logs/eval_gather
Inputs are built exactly as the CPU run builds them (``/ttaw_scripts/meteor2_lib.py`` + ``meteor2_ref.py``): the
768x432 JPEGs are sent as they are (the model upscales them), K at 768x432, T_ref_from_camera = the scene's
T_ego_cam, v0, causal acc, the 0.5 s ego history and the route of the driven path (or none). Writes
``outputs/<variant>_<route>/<scene>_<frame>.npz`` (ego, ego_path_6s, tl, boxes, lane, occ), ``rows.jsonl`` (path
errors vs the recorded drive, timing_ms) and ``summary.json``.
"""
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__)), ".."))
sys.path.insert(0, "/ttaw_scripts")
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--variant", default="gather")
ap.add_argument("--scenes", nargs="+", default=["valday", "arterial_day"])
ap.add_argument("--route", nargs="+", default=["none"])
ap.add_argument("--frames", type=int, default=0)
ap.add_argument("--scenes-root", default="/scenes")
ap.add_argument("--out", required=True)
a = ap.parse_args()
import cv2
import meteor2_lib as M2
import meteor2_ref as R
from tt_meteor2 import METEOR2
model = METEOR2.from_pretrained(variant=a.variant, weights_dir=os.environ.get("METEOR2_WEIGHTS_DIR", "/weights"))
os.makedirs(a.out, exist_ok=True)
rows = []
rowf = open(os.path.join(a.out, "rows.jsonl"), "w")
for sc in a.scenes:
path = R.scene_dir(a.scenes_root, sc)
man, em, K, T, dt, (w0, h0), s = R.load_scene(path)
cams = man["cams"]
calib = {"cameras": {c: {"intrinsics": np.asarray(cams[c]["K"], np.float64).tolist(),
"T_ref_from_camera": np.asarray(cams[c]["T_ego_cam"], np.float64).tolist()}
for c in M2.METEOR2_CAMERAS}}
frames = man["frames"][: a.frames] if a.frames else man["frames"]
pose = np.asarray(em["pose"], np.float64)
for fr in frames:
fi = int(fr["frame"])
images = {c: cv2.imread(os.path.join(path, fr["imgs"][c]), cv2.IMREAD_COLOR)[:, :, ::-1].copy()
for c in M2.METEOR2_CAMERAS}
hist = M2.ego_hist(pose, fi, dt)
hist_rows = int(np.any(hist.reshape(8, 4) != 0, axis=1).sum())
gt3 = np.asarray(em["wp"][fi], np.float64) if bool(em.get("valid", np.ones(len(pose)))[fi]) else np.full((6, 2), np.nan)
gt6 = M2.future_path(pose, fi, dt, 12)
for rm in a.route:
t0 = time.perf_counter()
out = model(images=images, calibration=calib, ego_speed=float(em["v0"][fi]),
acc=float(M2.causal_acc(em["v0"], fi, dt)), ego_hist=hist,
route=M2.route_input(pose, fi, rm == "recorded"))
wall = (time.perf_counter() - t0) * 1e3
eg = M2.decode_ego(out.ego)
p6 = np.asarray(out.ego_path_6s, np.float32)
best = eg["best"]
ade3, fde3, _ = M2.path_errors(eg["paths"][best], gt3)
minade3 = min(M2.path_errors(eg["paths"][k], gt3)[0] for k in range(3))
ade6, fde6, n6 = M2.path_errors(p6[best], gt6)
boxes = out.boxes.as_rows()
d = os.path.join(a.out, "outputs", f"{a.variant}_{rm}")
os.makedirs(d, exist_ok=True)
np.savez_compressed(os.path.join(d, f"{sc}_{fi:04d}.npz"), ego=out.ego[None], ego_path_6s=p6[None],
tl=out.tl[None], boxes=boxes, lane=out.lane, occ=out.occ_argmax)
row = {"scene": sc, "frame": fi, "form": a.variant, "route": rm, "hist_rows": hist_rows,
"cpu_ms": round(wall, 1), "ade3": ade3, "fde3": fde3, "minade3": minade3, "ade6": ade6 if n6 == 12 else None, "fde6": fde6 if n6 == 12 else None,
"best": best, "tl": M2.TL_CLASSES[int(np.argmax(out.tl))],
"n_vehicle": int((boxes[:, 0] == 0).sum()), "n_vru": int((boxes[:, 0] == 1).sum()),
"wall_ms": round(wall, 1), "timing_ms": {k: round(v, 2) for k, v in out.timing_ms.items()}}
rows.append(row)
rowf.write(json.dumps(row) + "\n")
rowf.flush()
print(f"[eval] {sc} {fi:4d} {rows[-1]['wall_ms']:.0f} ms ade3 {rows[-1]['ade3']:.2f}", flush=True)
rowf.close()
summary = {"full_history": R.summarize(rows, [a.variant], a.route, True), "all_frames": R.summarize(rows, [a.variant], a.route)}
t = {}
for k in ("preprocess", "device", "postprocess", "total"):
v = np.asarray([r["timing_ms"][k] for r in rows[1:]])
t[k] = {"median": float(np.median(v)), "p90": float(np.percentile(v, 90)), "max": float(v.max())}
summary["timing_ms"] = t
summary["info"] = {k: model.info.get(k) for k in ("device", "weights", "variant")}
json.dump(summary, open(os.path.join(a.out, "summary.json"), "w"), indent=1, default=str)
print(json.dumps(t), flush=True)
model.close()
if __name__ == "__main__":
main()
|