File size: 6,812 Bytes
31ffdfe 7b01b36 31ffdfe 7b01b36 31ffdfe | 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 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 | # SPDX-License-Identifier: Apache-2.0
"""One full AutoE2E step on the device (stateless: all 8 frames from the images) vs the upstream fp32 golden
(bin/devrun).
bin/devrun python -m tt_autoe2e.tests.dev_step [--out /logs/step/dev_step.json]
Device: image branch on the 7 history frames and the current frame (6 x 512 px) and the 1024 px front, the 8 BEV
frames, the front fusion, T8, the map fusion. Host: the geometry of every frame, the navigation encoder, the GRU
planner, the rollout. Compared per stage with the recon intermediates, then the controls and the trajectory.
"""
from __future__ import annotations
import argparse
import glob
import json
import os
import time
import numpy as np
CKPT = "/ae2e/881e6a8367746da1eaae044a68077d0e7ce6fc1b/models/kitscenes-epoch-5/checkpoint.pt"
def stats(a, b):
a = np.asarray(a, np.float64).ravel()
b = np.asarray(b, np.float64).ravel()
return {"rel_l2": float(np.linalg.norm(a - b) / max(np.linalg.norm(b), 1e-30)),
"pcc": float(np.corrcoef(a, b)[0, 1]), "max_abs": float(np.abs(a - b).max())}
def main(argv=None) -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--out", default="/logs/step/dev_step.json")
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 Q
from ..reference.tree import load_tree
from ..tt.encoder import TtBevEncoder
from ..tt.fusion import FRONT_CAP, TtFrontFusion, TtMapFusion
from ..tt.image import TtImageBranch, backbone_input, state_dict_of
from ..tt.t8 import TtT8
from ..ttaw.device import DeviceConfig, close_device
from ..ttaw.ops.conv import FeatureMap
torch.set_num_threads(8)
gpath = glob.glob("/ae2e/ref/autoe2e_kitscenes_epoch5_*f000045.npz")[0]
g = np.load(gpath)
it = np.load(gpath.replace(".npz", "_intermediates.npz"))
tree = load_tree(CKPT)
state = state_dict_of(tree)
res = {"stages": {}, "time_s": {}}
T = res["time_s"]
t = time.perf_counter()
Ps = [g["camera_history_projection_matrix"][0, k] for k in range(7)] + [g["camera_projection_matrix"][0]]
geos = [bev_geometry(P, 512) for P in Ps]
gfront = frame_geometry(g["front_camera_projection_matrix"][0], 1024, r_cap=FRONT_CAP, k_cams=1)
T["host_geometry"] = 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]))
T["host_navigation"] = time.perf_counter() - t
dev = DeviceConfig(trace_region_size=64 << 20).open()
try:
img, enc = TtImageBranch(state), TtBevEncoder(dev, tree)
front, t8, mfuse = TtFrontFusion(dev, tree), TtT8(state), TtMapFusion(dev, state)
def image(tiles):
x = backbone_input(tiles)
n, h, w, _ = x.shape
tt = ttnn.from_torch(torch.from_numpy(x.reshape(1, 1, n * h * w, 3)), dtype=ttnn.bfloat16,
layout=ttnn.ROW_MAJOR_LAYOUT, device=dev)
outs = img(FeatureMap(tt, n, h, w, 3))
ttnn.deallocate(tt)
return [o.tensor if tuple(o.tensor.shape) == (1, 1, n * o.height * o.width, 256)
else ttnn.reshape(o.tensor, (1, 1, n * o.height * o.width, 256)) for o in outs]
def run(record):
ts = {}
t0 = time.perf_counter()
frames = [image(g["camera_history_tiles"][0, k]) for k in range(7)] + [image(g["camera_tiles"][0])]
ffront = image(g["front_camera_tile"])
ttnn.synchronize_device(dev)
ts["dev_images"] = time.perf_counter() - t0
t0 = time.perf_counter()
bevs = []
for k in range(8):
gd = enc.upload_geometry(geos[k])
bevs.append(enc.frame(frames[k], gd))
for x in frames[k]:
ttnn.deallocate(x)
ttnn.synchronize_device(dev)
ts["dev_encoder_8_frames"] = time.perf_counter() - t0
t0 = time.perf_counter()
gf = enc.upload_geometry(gfront)
cur = front(bevs[7], ffront, gf)
if record:
d = lambda x: ttnn.to_torch(x).float().numpy().reshape(Q, 256)
hist = it["frame_bev_history"][0]
res["stages"]["bev_history"] = [stats(d(bevs[k]), hist[k].reshape(256, Q).T) for k in range(7)]
res["stages"]["bev_current"] = stats(d(bevs[7]), it["frame_bev_current_base"][0].reshape(256, Q).T)
res["stages"]["bev_current_front"] = stats(d(cur), it["frame_bev_current_with_front"][0].reshape(256, Q).T)
ttnn.deallocate(bevs[7])
bevs[7] = cur
image_bev = t8(bevs)
navd = ttnn.from_torch(torch.from_numpy(np.ascontiguousarray(nav.reshape(256, Q).T).reshape(1, 1, Q, 256)),
dtype=ttnn.bfloat16, layout=ttnn.TILE_LAYOUT, device=dev)
fused = mfuse(image_bev, navd)
fz = ttnn.to_torch(fused).float().numpy().reshape(Q, 256)
ts["dev_front_t8_fusion"] = time.perf_counter() - t0
if record:
d = lambda x: ttnn.to_torch(x).float().numpy().reshape(Q, 256)
res["stages"]["image_bev_t8"] = stats(d(image_bev), it["image_bev_t8"][0].reshape(256, Q).T)
res["stages"]["fused_bev"] = stats(fz, it["fused_bev"][0].reshape(256, Q).T)
for x in bevs + [image_bev, navd, fused] + ffront:
ttnn.deallocate(x)
t0 = time.perf_counter()
ctrl = H.planner(state, fz, H.normalize_egomotion(g["egomotion_history"][0]))
ts["host_planner"] = time.perf_counter() - t0
return ctrl, ts
ctrl, _ = run(True)
_, T2 = run(False)
T.update(T2)
finally:
close_device(dev)
ref = g["controls"][0]
res["controls"] = stats(ctrl, ref)
v0 = float(g["initial_speed_mps"][0])
xy, _, _ = H.rollout(ctrl, v0)
xr, _, _ = H.rollout(ref, v0)
res["trajectory_diff_m"] = {f"{s}s": float(np.linalg.norm(xy[n - 1] - xr[n - 1])) for s, n in ((1, 10), (3, 30), (5, 50))}
tgt, valid = g["target_trajectory_xy_m"][0], g["target_trajectory_valid"][0].astype(bool)
err = np.linalg.norm(xy - tgt, axis=-1)
res["ade_vs_log_m"] = {f"{s}s": float(err[:n][valid[:n]].mean()) for s, n in ((1, 10), (3, 30), (5, 50))}
res["controls_first5"] = ctrl[:5].tolist()
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())
|