changh95's picture
tt-model push auto_drive-p150 (container)
c147de1 verified
Raw History Blame Contribute Delete
6.78 kB
# SPDX-License-Identifier: Apache-2.0
"""End-to-end check of the Python API on the p150 (run under bin/devrun):
python -m tt_visionpilot.tests.dev_api [--nets autosteer autospeed autodrive] [--json OUT]
Each class through ``from_pretrained`` (local weights under /weights/pkg/<net>, the published files with their
pre-folded twins), called on raw sample frames (/weights/samples) through VisionPilot's pre-processing; the outputs
are compared with the fp32 numpy interpreter of the folded graph on the same network image (in this container, so
the OpenCV resize is the same one), decoded the same way.
"""
from __future__ import annotations
import argparse
import json
import time
from pathlib import Path
import numpy as np
from ..graph import Graph
from ..host import onnx_numpy
from ..host.prep import center_crop_homography, front_image, warped_image
from ..models import IMAGENET_MEAN, IMAGENET_STD, NETWORKS
from ..outputs import autospeed_decode
def net_input(rgb: np.ndarray, imagenet: bool) -> np.ndarray:
x = rgb.astype(np.float32) * np.float32(1.0 / 255.0)
if imagenet:
x = (x - np.asarray(IMAGENET_MEAN, np.float32)) / np.asarray(IMAGENET_STD, np.float32)
return np.ascontiguousarray(x.transpose(2, 0, 1)[None])
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 main(argv=None) -> int:
from ..api import MODELS
from ..ttaw.io import load_image
ap = argparse.ArgumentParser()
ap.add_argument("--nets", nargs="*", default=list(NETWORKS))
ap.add_argument("--root", default="/weights")
ap.add_argument("--iters", type=int, default=30)
ap.add_argument("--json", default=None)
args = ap.parse_args(argv)
root = Path(args.root)
samples = sorted((root / "samples").glob("*"))
rep = {}
for name in args.nets:
cls = MODELS[name]
t0 = time.perf_counter()
model = cls.from_pretrained(weights_dir=str(root / "pkg" / name))
boot = time.perf_counter() - t0
g = Graph(Path(model.weights_path) / Path(cls.WEIGHTS_FILE).parent / "folded" / Path(cls.WEIGHTS_FILE).name)
res = []
try:
for k, path in enumerate(samples):
rgb = load_image(str(path))
if name == "autodrive":
nxt = load_image(str(samples[(k + 1) % len(samples)]))
if nxt.shape != rgb.shape:
continue # a pair needs two frames of one camera
H = center_crop_homography(rgb.shape[1], rgb.shape[0], 60.0) if rgb.shape[:2] != (512, 1024) \
else None
imgs = [{"camera": "prev", "image": rgb}, {"camera": "curr", "image": nxt}]
out = model(images=imgs, homography=None if H is None else H.ravel().tolist())
feeds = {"image_prev": net_input(warped_image(rgb, H), True),
"image_curr": net_input(warped_image(nxt, H), True)}
env = onnx_numpy.run(g, feeds)
ref = {"dist": float(env["distance"].ravel()[0]), "curv": float(env["curvature"].ravel()[0]),
"flag": float(env["flag_logit"].ravel()[0])}
got = {"dist": out.dist_normalized, "curv": out.curvature_raw, "flag": out.flag_logit}
res.append({"sample": path.name, "got": got, "ref": ref,
"abs_err": {kk: abs(got[kk] - ref[kk]) for kk in got}, "timing_ms": out.timing_ms})
else:
out = model(images=[{"camera": "front", "image": rgb}])
img, _ = front_image(rgb)
env = onnx_numpy.run(g, {"input": net_input(img, False)})
if name == "autosteer":
rx, rh = env["lane_value"].ravel(), env["height"].ravel()
res.append({"sample": path.name,
"xp_rel_l2": float(np.linalg.norm(out.xp - rx) / np.linalg.norm(rx)),
"xp_max_abs": float(np.abs(out.xp - rx).max()),
"h_rel_l2": float(np.linalg.norm(out.h_vector - rh) / np.linalg.norm(rh)),
"timing_ms": out.timing_ms})
else:
rb, rs, rc, _ = autospeed_decode(env["output"])
matched = 0
used = set()
for b, c in zip(out.boxes, out.class_ids):
for j, (bb, cc) in enumerate(zip(rb, rc)):
if j not in used and cc == c and iou(b, bb) >= 0.9:
used.add(j)
matched += 1
break
res.append({"sample": path.name, "n_tt": int(len(out.scores)), "n_ref": int(len(rs)),
"matched_iou90": matched, "timing_ms": out.timing_ms,
"scores_tt": out.scores[:5].tolist(), "scores_ref": rs[:5].tolist()})
print(name, json.dumps(res[-1], default=float)[:400])
# timing of a steady stream of calls on the first sample
rgb = load_image(str(samples[0]))
call = (lambda: model(images=[{"camera": "prev", "image": rgb}, {"camera": "curr", "image": rgb}])) \
if name == "autodrive" and rgb.shape[:2] == (512, 1024) else \
(lambda: model(images=[{"camera": "front", "image": rgb}])) if name != "autodrive" else None
ts = []
if call is not None:
for _ in range(args.iters):
t = time.perf_counter()
o = call()
ts.append((time.perf_counter() - t) * 1e3)
rep[name] = {"boot_s": boot, "samples": res, "info": model.info.get("extra", None) or {},
"call_ms_median": float(np.median(ts)) if ts else None,
"call_ms_p90": float(np.percentile(ts, 90)) if ts else None,
"last_timing_ms": o.timing_ms if ts else None}
print(f"== {name}: boot {boot:.1f} s, call median {rep[name]['call_ms_median']} ms, "
f"p90 {rep[name]['call_ms_p90']}, timing {rep[name]['last_timing_ms']}")
finally:
model.close()
if args.json:
Path(args.json).write_text(json.dumps(rep, indent=1, default=float))
return 0
if __name__ == "__main__":
raise SystemExit(main())