METEOR-2-p150 / code /scripts /dev_trace.py
changh95's picture
tt-model push meteor-2-p150 (container)
0f131e7 verified
Raw History Blame Contribute Delete
5.23 kB
#!/usr/bin/env python3
# SPDX-License-Identifier: Apache-2.0
"""Trace the whole ``TtMeteor2.forward`` once and time replays + readback (run under bin/devrun).
bin/devrun python scripts/dev_trace.py --form gather --name valday_0040 [--iters 20]
"""
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 main():
ap = argparse.ArgumentParser()
ap.add_argument("--form", default="gather")
ap.add_argument("--name", default="valday_0040")
ap.add_argument("--iters", type=int, default=20)
ap.add_argument("--conv", default=None)
ap.add_argument("--stem", default="s2d", choices=("s2d", "direct"))
ap.add_argument("--profile", action="store_true", help="signpost one replay for tracy")
a = ap.parse_args()
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, open_device
from tt_meteor2.ttaw.ops.conv import FeatureMap
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]}")
rep = {"form": a.form, "name": a.name}
dev = open_device(0, dispatch="eth", l1_small_size=32768, trace_region_size=128 << 20)
try:
model = TtMeteor2(dev, w, **(dict({"conv_precision": a.conv} if a.conv else {}, stem=a.stem)))
if a.form == "gather":
model.set_calibration(lift_tables(z["K"][0], z["T_cam_ego"][0], w.bev_points(), w.paint_z_fill()))
xt, geo = model.host_input(z["imgs"])
xh = ttnn.from_torch(xt, dtype=ttnn.bfloat16, layout=ttnn.ROW_MAJOR_LAYOUT)
x = ttnn.allocate_tensor_on_device(xh.shape, ttnn.bfloat16, ttnn.ROW_MAJOR_LAYOUT, dev, ttnn.DRAM_MEMORY_CONFIG)
ttnn.copy_host_to_device_tensor(xh, x)
fm = FeatureMap(x, *geo)
for i in range(2):
t = time.time()
out = model.forward(fm)
ttnn.synchronize_device(dev)
print(f"warm-up {i}: {(time.time() - t) * 1e3:.1f} ms", flush=True)
for v in out.values():
ttnn.deallocate(v)
t = time.time()
tid = ttnn.begin_trace_capture(dev, cq_id=0)
out = model.forward(fm)
ttnn.end_trace_capture(dev, tid, cq_id=0)
ttnn.synchronize_device(dev)
rep["capture_ms"] = (time.time() - t) * 1e3
print(f"captured in {rep['capture_ms']:.0f} ms", flush=True)
rt, rd = [], []
for i in range(a.iters):
ttnn.copy_host_to_device_tensor(xh, x)
ttnn.synchronize_device(dev)
t = time.time()
ttnn.execute_trace(dev, tid, cq_id=0, blocking=False)
ttnn.synchronize_device(dev)
rt.append((time.time() - t) * 1e3)
t = time.time()
host = {k: ttnn.to_torch(v) for k, v in out.items()}
rd.append((time.time() - t) * 1e3)
rep["replay_ms"] = {"median": float(np.median(rt)), "min": float(np.min(rt)), "max": float(np.max(rt))}
rep["readback_ms"] = {"median": float(np.median(rd)), "min": float(np.min(rd))}
rep["readback_bytes"] = {k: int(v.numel() * v.element_size()) for k, v in host.items()}
print("replay ms", rep["replay_ms"], "readback ms", rep["readback_ms"], flush=True)
print("readback MB", {k: round(b / 2 ** 20, 1) for k, b in rep["readback_bytes"].items()}, flush=True)
# b2b replays
t = time.time()
for i in range(a.iters):
ttnn.execute_trace(dev, tid, cq_id=0, blocking=False)
ttnn.synchronize_device(dev)
rep["b2b_ms"] = (time.time() - t) * 1e3 / a.iters
print(f"back-to-back replay {rep['b2b_ms']:.1f} ms", flush=True)
# traced result == goldens (sanity)
h = {k: v.float().numpy() for k, v in host.items()}
lane = h["lane"].reshape(-1, 9)[: C.LANE_H * C.LANE_W].reshape(C.LANE_H, C.LANE_W, 9).argmax(-1)
rep["lane_argmax_agree"] = float((lane == gold["out.lane_logit"][0].argmax(0)).mean())
eg = EgoHead(w)(h["ego_pool"].reshape(-1, 128)[:20], h["kin_pool"].reshape(-1, 16)[:160], z["v0"], z["acc"],
z["ego_hist"], z["route"])
rep["ego_path_6s_mean_m"] = float(np.linalg.norm(eg["ego_path_6s"][0] - gold["out.ego_path_6s"][0], axis=-1).mean())
print("traced: lane argmax", rep["lane_argmax_agree"], "ego path 6s mean dist", rep["ego_path_6s_mean_m"])
if a.profile:
from tt_meteor2.ttaw.profiling import signpost
signpost("trace")
ttnn.execute_trace(dev, tid, cq_id=0, blocking=False)
ttnn.synchronize_device(dev)
signpost("trace_end")
ttnn.ReadDeviceProfiler(dev)
ttnn.release_trace(dev, tid)
finally:
close_device(dev)
json.dump(rep, open(f"/logs/dev_trace_{a.form}_{a.name}.json", "w"), indent=1)
if __name__ == "__main__":
main()