METEOR-2-p150 / code /scripts /dev_v0.py
changh95's picture
tt-model push meteor-2-p150 (container)
0f131e7 verified
Raw History Blame Contribute Delete
7.48 kB
#!/usr/bin/env python3
# SPDX-License-Identifier: Apache-2.0
"""Device bring-up check of ``TtMeteor2`` (eager, taps): every stage vs the fp32 CPU goldens (run under bin/devrun).
bin/devrun python scripts/dev_v0.py --form gather --name valday_0040 [--taps all|none|a,b] [--runs 2]
Prints per-tap / per-output PCC and max |error|, the task-level agreement (lane / occupancy argmax, BEV peak boxes,
ego paths), the eager forward time of each run, and writes /logs/dev_v0_<form>_<name>.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__)), ".."))
def stats(t, r):
from tt_meteor2.ttaw.metrics import pcc
t = np.asarray(t, np.float64)
r = np.asarray(r, np.float64)
return {"pcc": float(pcc(t, r)), "max_abs": float(np.abs(t - r).max()), "ref_absmax": float(np.abs(r).max())}
def rows_to_nchw(a, n, h, w, c):
return np.asarray(a, np.float32).reshape(-1, a.shape[-1])[: n * h * w, :c].reshape(n, h, w, c).transpose(0, 3, 1, 2)
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--form", default="gather")
ap.add_argument("--name", default="valday_0040")
ap.add_argument("--taps", default="all")
ap.add_argument("--runs", type=int, default=2)
ap.add_argument("--conv", default=None)
ap.add_argument("--l1", default="table", choices=("none", "table"))
ap.add_argument("--stem", default="s2d", choices=("s2d", "direct"))
a = ap.parse_args()
import torch
import ttnn
from tt_meteor2.host.calib import lift_tables
from tt_meteor2.host.ego import EgoHead
from tt_meteor2.reference import config as C
from tt_meteor2.reference.weights import Meteor2Weights
from tt_meteor2.tt.model import TtMeteor2, image_input
from tt_meteor2.ttaw.device import close_device, describe_device, open_device
from tt_meteor2.ttaw.ops.conv import FeatureMap, fmap_to_numpy
z = dict(np.load(f"/data/inputs/{a.name}.npz"))
gold = np.load(f"/data/goldens/{a.form}/{a.name}.npz")
w = Meteor2Weights(f"/weights/{C.ONNX_FILES[a.form]}")
report = {"form": a.form, "name": a.name}
t0 = time.time()
dev = open_device(0, dispatch="eth", l1_small_size=32768, trace_region_size=256 << 20)
report["device"] = describe_device(dev)
try:
kw = {"conv_precision": a.conv} if a.conv else {}
model = TtMeteor2(dev, w, **dict(kw, stem=a.stem, conv_l1=a.l1))
if a.form == "gather":
tables = lift_tables(z["K"][0], z["T_cam_ego"][0], w.bev_points(), w.paint_z_fill())
model.set_calibration(tables)
report["tables"] = tables.describe()
head = EgoHead(w)
x_host, geo = model.host_input(z["imgs"])
want = None if a.taps == "none" else (None if a.taps == "all" else set(a.taps.split(",")))
times = []
for run in range(a.runs):
x = ttnn.from_torch(x_host, dtype=ttnn.bfloat16, layout=ttnn.ROW_MAJOR_LAYOUT, device=dev,
memory_config=ttnn.DRAM_MEMORY_CONFIG)
taps = {} if (run == 0 and a.taps != "none") else None
ttnn.synchronize_device(dev)
t = time.time()
out = model.forward(FeatureMap(x, *geo), taps)
ttnn.synchronize_device(dev)
times.append((time.time() - t) * 1e3)
print(f"run {run}: forward {times[-1]:.1f} ms (eager{', taps' if taps is not None else ''})", flush=True)
if run == 0:
host = {k: ttnn.to_torch(v).float().numpy() for k, v in out.items()}
if taps is not None:
for k, fm in taps.items():
if want is not None and k not in want:
continue
if ("tap." + k) not in gold.files:
continue
g = gold["tap." + k]
if hasattr(fm, "batch"):
v = fmap_to_numpy(fm)
else: # lift.polar [8, 64 b, 288, 64 c] RM
v = ttnn.to_torch(fm).float().numpy().transpose(0, 3, 1, 2) * 0.5 # 0.5 folded into 1/count
report["tap:" + k] = stats(v.reshape(g.shape), g)
print(f" tap {k:12s} pcc {report['tap:' + k]['pcc']:.6f} max_abs {report['tap:' + k]['max_abs']:.3e}"
f" (ref {report['tap:' + k]['ref_absmax']:.3g})", flush=True)
for v in out.values():
ttnn.deallocate(v)
ttnn.deallocate(x)
report["forward_ms"] = times
# outputs vs goldens
rows = host["rows"].reshape(-1, 64)[: C.BEV_CELLS]
dense = rows.reshape(C.BEV_H, C.BEV_W, 64).transpose(2, 0, 1)[None]
o = {"hm": dense[:, 0:2], "reg": dense[:, 2:8], "stationary": dense[:, 8:9], "risk": dense[:, 9:10],
"traj": dense[:, 10:49]}
eg = head(host["ego_pool"].reshape(-1, 128)[:20], host["kin_pool"].reshape(-1, 16)[:160], z["v0"], z["acc"],
z["ego_hist"], z["route"])
o.update({k: eg[k] for k in ("ego", "tl", "ego_path_6s")})
for k, v in o.items():
g = gold["out." + k]
report["out:" + k] = stats(v.reshape(g.shape), g)
print(f" out {k:12s} pcc {report['out:' + k]['pcc']:.6f} max_abs {report['out:' + k]['max_abs']:.3e}"
f" (ref {report['out:' + k]['ref_absmax']:.3g})", flush=True)
from tt_meteor2.host.postprocess import decode_dense, match_boxes, occ_from_logits, occ_occupied
lane = host["lane"].reshape(-1)[: C.LANE_H * C.LANE_W].reshape(C.LANE_H, C.LANE_W)
report["lane_argmax_agree"] = float((lane == gold["out.lane_logit"][0].argmax(0)).mean())
rcls, rp = occ_from_logits(gold["out.occ_logit"])
dcls = host["occ_cls"].reshape(-1, 32)[: C.OCC_H * C.OCC_W, :16].reshape(C.OCC_H, C.OCC_W, 16).transpose(2, 0, 1) % 10
dp = host["occ_p"].reshape(-1, 32)[: C.OCC_H * C.OCC_W, :16].reshape(C.OCC_H, C.OCC_W, 16).transpose(2, 0, 1)
report["occ_argmax_agree"] = float((occ_occupied(dcls, dp) == occ_occupied(rcls, rp)).mean())
bd = decode_dense(o["hm"], o["reg"], o["stationary"], o["risk"], o["traj"])
br = decode_dense(gold["out.hm"], gold["out.reg"], gold["out.stationary"], gold["out.risk"], gold["out.traj"])
report["boxes"] = match_boxes(bd, br)
print(" boxes", report["boxes"], flush=True)
report["tl_same"] = bool(np.argmax(o["tl"]) == np.argmax(gold["out.tl"]))
ge = gold["out.ego_path_6s"][0]
report["ego_path_6s_mean_m"] = float(np.linalg.norm(o["ego_path_6s"][0] - ge, axis=-1).mean())
hm_t = 1 / (1 + np.exp(-o["hm"]))
hm_r = 1 / (1 + np.exp(-gold["out.hm"]))
report["hm_sigmoid_max_abs"] = float(np.abs(hm_t - hm_r).max())
print(" lane argmax", report["lane_argmax_agree"], "occ mask agree", report["occ_argmax_agree"], "tl same",
report["tl_same"], "ego path 6s mean dist m", round(report["ego_path_6s_mean_m"], 4),
"hm sigmoid max abs", round(report["hm_sigmoid_max_abs"], 4), flush=True)
finally:
close_device(dev)
report["total_s"] = time.time() - t0
json.dump(report, open(f"/logs/dev_v0_{a.form}_{a.name}.json", "w"), indent=1)
if __name__ == "__main__":
main()