changh95's picture
tt-model push auto_e2e-p150 (container)
7b01b36 verified
Raw History Blame Contribute Delete
7.54 kB
# SPDX-License-Identifier: Apache-2.0
"""Where a step's time goes (bin/devrun): eager blocks before capture, then the traced call split into host
conversion, host -> device copies, replay and readback, per input group.
bin/devrun python -m tt_autoe2e.tests.dev_prof [--out /logs/prof/dev_prof.json] [--no-eager]
Eager part (each block synchronized): the image branch on the 6 views and on the 1024 px front, one BEV frame
(with the encoder's block profile), the front fusion, T8 on 8 BEVs, the map fusion. Traced part (golden sample,
ring primed with its 7 history frames): the step's inputs as ``AutoE2EDevice.step`` builds them.
"""
from __future__ import annotations
import argparse
import glob
import json
import os
import time
from collections import defaultdict
import numpy as np
CKPT = "/ae2e/881e6a8367746da1eaae044a68077d0e7ce6fc1b/models/kitscenes-epoch-5/checkpoint.pt"
def group_of(name: str) -> str:
if "." in name:
tag, field = name.split(".", 1)
return "geo." + "".join(c for c in field if not c.isdigit())
return name
def main(argv=None) -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--out", default="/logs/prof/dev_prof.json")
ap.add_argument("--no-eager", action="store_true")
args = ap.parse_args(argv)
import torch
import ttnn
from ..host import head as H
from ..host.geometry import bev_geometry, frame_geometry
from ..reference.port_form import E, Q
from ..reference.tree import load_tree
from ..tt.fusion import FRONT_CAP
from ..tt.image import backbone_input, state_dict_of
from ..tt.runner import DEVICE_DEFAULTS, AutoE2EDevice, geometry_inputs
from ..ttaw.device import DeviceConfig, close_device
from ..ttaw.ops.conv import FeatureMap
from ..ttaw.trace import to_host_tensor
torch.set_num_threads(8)
g = np.load(glob.glob("/ae2e/ref/autoe2e_kitscenes_epoch5_*f000045.npz")[0])
tree = load_tree(CKPT)
state = state_dict_of(tree)
Ps = [g["camera_history_projection_matrix"][0, k] for k in range(7)] + [g["camera_projection_matrix"][0]]
t = time.perf_counter()
geos = [bev_geometry(P, 512) for P in Ps]
gf = frame_geometry(g["front_camera_projection_matrix"][0], 1024, r_cap=FRONT_CAP, k_cams=1)
res = {"host_geometry_9_s": time.perf_counter() - t}
t = time.perf_counter()
nav, _ = H.navigation(state, g["map_context"][0], g["route_mask"][0], bool(g["map_valid"][0]),
bool(g["route_valid"][0]))
res["host_navigation_s"] = time.perf_counter() - t
cams = backbone_input(g["camera_tiles"][0])
front = backbone_input(g["front_camera_tile"])
nav_rows = np.ascontiguousarray(nav.reshape(256, -1).T)
dev = DeviceConfig(**DEVICE_DEFAULTS).open()
sync = lambda: ttnn.synchronize_device(dev)
try:
m = AutoE2EDevice(dev, tree)
if not args.no_eager:
eg = {}
def timed(name, fn, reps=2):
out = fn() # warm (program cache)
sync()
best = 1e9
for _ in range(reps):
if isinstance(out, list):
for o in out:
ttnn.deallocate(o)
else:
ttnn.deallocate(out)
t0 = time.perf_counter()
out = fn()
sync()
best = min(best, time.perf_counter() - t0)
eg[name] = round(best * 1e3, 2)
return out
up_rm = lambda a: ttnn.from_torch(torch.from_numpy(np.ascontiguousarray(a, np.float32)),
dtype=ttnn.bfloat16, layout=ttnn.ROW_MAJOR_LAYOUT, device=dev)
xc = up_rm(cams.reshape(1, 1, 6 * 512, 512 * 3))
xf = up_rm(front.reshape(1, 1, 1024, 1024 * 3))
fpn = timed("image_6x512", lambda: m._pyramid(xc, 6, 512))
ffr = timed("image_front_1024", lambda: m._pyramid(xf, 1, 1024))
gd = m.enc.upload_geometry(geos[7])
gdf = m.enc.upload_geometry(gf)
bev = timed("bev_frame", lambda: m.enc.frame(fpn, gd))
m.enc.prof = {}
o = m.enc.frame(fpn, gd)
sync()
ttnn.deallocate(o)
eg["bev_frame_blocks"] = {k: round(v * 1e3, 2) for k, v in sorted(m.enc.prof.items(), key=lambda kv: -kv[1])}
m.enc.prof = None
curf = timed("front_fusion", lambda: m.front(bev, ffr, gdf))
t8 = timed("t8", lambda: m.t8([bev] * 7 + [curf]))
navd = ttnn.from_torch(torch.from_numpy(nav_rows.reshape(1, 1, Q, E)), dtype=ttnn.bfloat16,
layout=ttnn.TILE_LAYOUT, device=dev)
fused = timed("map_fusion", lambda: m.mfuse(t8, navd))
for x in fpn + ffr + [bev, curf, t8, navd, fused, xc, xf]:
ttnn.deallocate(x)
res["eager_ms"] = eg
print(json.dumps(eg, indent=1), flush=True)
t = time.perf_counter()
m.capture()
res["capture_s"] = time.perf_counter() - t
for k in range(7):
m.push(backbone_input(g["camera_history_tiles"][0, k]))
sync()
R = m.runner
inputs = {"cams": cams.reshape(1, 1, 6 * 512, 512 * 3), "front": front.reshape(1, 1, 1024, 1024 * 3),
"nav": nav_rows.reshape(1, 1, Q, E)}
for k, gg in enumerate(geos):
inputs.update(geometry_inputs(f"f{k}", gg))
inputs.update(geometry_inputs("front", gf))
m.step(cams, front, geos, gf, nav_rows) # warm
conv, h2d, nbytes = defaultdict(float), defaultdict(float), defaultdict(int)
for name, value in inputs.items():
slot = R._slot(name, "input")
t0 = time.perf_counter()
host = to_host_tensor(value, slot.dtype, slot.layout, shape=slot.shape)
t1 = time.perf_counter()
ttnn.copy_host_to_device_tensor(host, slot.buffers[0], cq_id=0)
sync()
t2 = time.perf_counter()
grp = group_of(name)
conv[grp] += (t1 - t0) * 1e3
h2d[grp] += (t2 - t1) * 1e3
nbytes[grp] += int(np.asarray(value).nbytes)
res["inputs_ms"] = {k: {"convert": round(conv[k], 2), "h2d": round(h2d[k], 2), "MB": round(nbytes[k] / 1e6, 2)}
for k in sorted(conv, key=lambda k: -(conv[k] + h2d[k]))}
res["inputs_total_ms"] = round(sum(conv.values()) + sum(h2d.values()), 1)
tm = defaultdict(list)
for _ in range(3):
t0 = time.perf_counter()
ups = R._collect_uploads(inputs, None)
t1 = time.perf_counter()
R._enqueue_uploads(ups)
sync()
t2 = time.perf_counter()
R.run("step_a")
R.run("step_b")
sync()
t3 = time.perf_counter()
R.read("step_b")
t4 = time.perf_counter()
for k, v in (("convert", t1 - t0), ("h2d", t2 - t1), ("replay", t3 - t2), ("read", t4 - t3)):
tm[k].append(v * 1e3)
res["traced_ms"] = {k: round(float(np.median(v)), 1) for k, v in tm.items()}
m.release()
finally:
close_device(dev)
print(json.dumps(res, indent=1))
os.makedirs(os.path.dirname(args.out), exist_ok=True)
with open(args.out, "w") as f:
json.dump(res, f, indent=1)
return 0
if __name__ == "__main__":
raise SystemExit(main())