changh95's picture
tt-model push auto_e2e-p150 (container)
ce1bce6 verified
Raw History Blame Contribute Delete
11.6 kB
# SPDX-License-Identifier: Apache-2.0
"""AutoE2E as captured traces on one p150 (ttaw ``TraceRunner``), stateful like upstream's camera-FPN cache.
State: a ring of the FPN pyramids (4 levels, 6 views) of the last 7 frames on the 500 ms grid, slot 0 the oldest.
Variants:
- ``push``: the image branch on ``cams`` (6 x 512 px) and the ring shifted by one with the new pyramid in slot 6 (the
prime of a stream: its 7 history frames, oldest first);
- ``step``: the image branch on ``cams`` and on the 1024 px ``front``; the 8 BEV frames (ring slots 0-6 with
geometry 0-6, the new pyramid with geometry 7); the front fusion; T8; the map fusion with ``nav`` (the host
navigation BEV); the ring shifted with the new pyramid. Output: the fused BEV ``[Q, 256]``.
Per-step inputs written by the host before a replay: ``cams`` / ``front`` (the backbone input, ``tt.image.
backbone_input``, bf16 ROW_MAJOR), the geometry of the 8 frames and of the front (``host.geometry``), ``nav``.
Streams (the KITScenes evaluator's 5 lanes, or several sensors): the ring has ``banks`` copies, switched with
:meth:`AutoE2EDevice.select`.
"""
from __future__ import annotations
from typing import Any, Dict, List, Optional, Sequence
import numpy as np
from ..host.geometry import FAR, K_CAMS, R_CAP, CmGeometry, FrameGeometry, level_sizes, use_cm, use_front_cm
from ..reference.port_form import E, Q
from ..ttaw.ops.conv import FeatureMap
from ..ttaw.trace import TraceRunner, pack_outputs
from .encoder import TtBevEncoder
from .fusion import FRONT_CAP, TtFrontFusion, TtMapFusion
from .image import TtImageBranch, state_dict_of
from .t8 import TtT8
SIZES = level_sizes(512)
DEVICE_DEFAULTS = {"trace_region_size": 768 << 20, "l1_small_size": 32768, "num_command_queues": 1}
def _geo_names(tag: str, k_cams: int) -> List[str]:
return [f"{tag}.sca_index", f"{tag}.base", f"{tag}.seg", f"{tag}.scale", f"{tag}.observed"] + \
[f"{tag}.gather{i}" for i in range(k_cams)]
def geometry_inputs(tag: str, geo) -> Dict[str, np.ndarray]:
"""Host arrays of one frame's geometry under the runner's input names."""
if isinstance(geo, CmGeometry):
return {f"{tag}.table": geo.table.reshape(1, 1, Q, 32)} # observed: from the table's count on the device
r = geo.base.shape[0]
out = {f"{tag}.sca_index": geo.sca_index.astype(np.uint32),
f"{tag}.base": geo.base.reshape(1, 1, r, -1).astype(np.float32),
f"{tag}.seg": geo.seg.astype(np.uint32),
f"{tag}.scale": geo.scale.reshape(1, 1, Q, 1).astype(np.float32),
f"{tag}.observed": geo.observed.reshape(1, 1, Q, 1).astype(np.float32)}
for i in range(geo.gather.shape[0]):
out[f"{tag}.gather{i}"] = geo.gather[i:i + 1].astype(np.uint32)
return out
class AutoE2EDevice:
def __init__(self, device: Any, tree: Any, *, banks: int = 0):
import ttnn
self.device = device
state = state_dict_of(tree)
self.img = TtImageBranch(state)
self.enc = TtBevEncoder(device, tree)
self.front = TtFrontFusion(device, tree)
self.t8 = TtT8(state)
self.mfuse = TtMapFusion(device, state)
self.banks = int(banks)
R = self.runner = TraceRunner(device, num_command_queues=1, name="autoe2e")
RM, TL = ttnn.ROW_MAJOR_LAYOUT, ttnn.TILE_LAYOUT
# images as one row per image row (a 3-byte row per pixel is a slow host -> device copy: 39 ms for the 6
# views), reshaped to pixel rows on the device; nav row-major, tilized on the device
R.add_input("cams", shape=(1, 1, 6 * 512, 512 * 3), dtype="bfloat16", layout=RM)
R.add_input("front", shape=(1, 1, 1024, 1024 * 3), dtype="bfloat16", layout=RM)
R.add_input("nav", shape=(1, 1, Q, E), dtype="bfloat16", layout=RM)
# one tile read back by the variants whose results stay on the device (push, step_a)
R.add_input("ok", np.zeros((1, 1, 32, 32), np.float32), dtype="float32", layout=TL)
self.cm = self.enc.cm
for k in range(8):
if self.cm:
self._add_cm_geometry(f"f{k}")
else:
self._add_geometry(f"f{k}", R_CAP, K_CAMS, 6)
if use_front_cm():
self._add_cm_geometry("front")
else:
self._add_geometry("front", FRONT_CAP, 1, 1)
for s in range(7):
for l, (h, w) in enumerate(SIZES):
R.add_state(self._ring(s, l), shape=(1, 1, 6 * h * w, E), dtype="bfloat16", layout=TL,
banks=self.banks)
# the step in two traces: step_a (images, the 8 BEV frames, the front fusion, T8 -> state image_bev) and
# step_b (the map fusion with nav): the host computes the navigation BEV while step_a runs
R.add_state("image_bev", shape=(1, 1, Q, E), dtype="bfloat16", layout=TL)
R.add_variant("push", self._push)
R.add_variant("step_a", self._step_a)
R.add_variant("step_b", self._step_b)
# ------------------------------------------------------------------ registration
@staticmethod
def _ring(s: int, l: int) -> str:
return f"ring{s}.l{l}"
def _add_geometry(self, tag: str, cap: int, k_cams: int, ncam: int) -> None:
import ttnn
R = self.runner
RM, TL = ttnn.ROW_MAJOR_LAYOUT, ttnn.TILE_LAYOUT
seg = np.zeros((1, 1, 1, 16), np.uint32)
seg[0, 0, 0, :8] = cap // 32
R.add_input(f"{tag}.sca_index", np.full((1, cap), Q, np.uint32), dtype="uint32", layout=RM)
R.add_input(f"{tag}.base", np.full((1, 1, cap, 64), FAR, np.float32), dtype="float32", layout=TL)
R.add_input(f"{tag}.seg", seg, dtype="uint32", layout=RM)
R.add_input(f"{tag}.scale", np.ones((1, 1, Q, 1), np.float32), dtype="float32", layout=TL)
R.add_input(f"{tag}.observed", np.zeros((1, 1, Q, 1), np.float32), dtype="bfloat16", layout=TL)
for i in range(k_cams):
R.add_input(f"{tag}.gather{i}", np.full((1, Q), cap, np.uint32), dtype="uint32", layout=RM)
self._ncam = getattr(self, "_ncam", {})
self._ncam[tag] = (ncam, k_cams)
def _add_cm_geometry(self, tag: str) -> None:
import ttnn
table = np.zeros((1, 1, Q, 32), np.int32)
table[..., 16:18] = -1
self.runner.add_input(f"{tag}.table", table, dtype="int32", layout=ttnn.TILE_LAYOUT)
self._ncam = getattr(self, "_ncam", {})
self._ncam[tag] = None
def _geo(self, ctx, tag: str) -> Dict[str, Any]:
if self._ncam[tag] is None:
return {"table": ctx[f"{tag}.table"]}
ncam, k = self._ncam[tag]
return {"sca_index": ctx[f"{tag}.sca_index"], "base": ctx[f"{tag}.base"], "seg": ctx[f"{tag}.seg"],
"scale": ctx[f"{tag}.scale"], "observed": ctx[f"{tag}.observed"],
"gather": [ctx[f"{tag}.gather{i}"] for i in range(k)], "nseg": ncam}
# ------------------------------------------------------------------ traced functions
def _pyramid(self, x, n, size) -> List[Any]:
import ttnn
shape = (1, 1, n * size * size, 3)
px = x if tuple(x.shape) == shape else ttnn.reshape(x, shape) # image rows -> pixel rows (a copy)
outs = self.img(FeatureMap(px, n, size, size, 3))
if px is not x:
ttnn.deallocate(px)
res = []
for o in outs:
shape = (1, 1, n * o.height * o.width, E)
res.append(o.tensor if tuple(o.tensor.shape) == shape else ttnn.reshape(o.tensor, shape))
return res
def _shift(self, ctx, new: Sequence[Any]) -> None:
for s in range(6):
for l in range(4):
ctx.write_state(self._ring(s, l), ctx[self._ring(s + 1, l)])
for l in range(4):
ctx.write_state(self._ring(6, l), new[l])
def _push(self, ctx):
import ttnn
fpn = self._pyramid(ctx["cams"], 6, 512)
self._shift(ctx, fpn)
for t in fpn:
ttnn.deallocate(t)
return pack_outputs({"ok": ctx["ok"]}, dtype="float32") # a dummy output (the ring is the result)
def _step_a(self, ctx):
import ttnn
fpn = self._pyramid(ctx["cams"], 6, 512)
ffront = self._pyramid(ctx["front"], 1, 1024)
bevs = [self.enc.frame([ctx[self._ring(s, l)] for l in range(4)], self._geo(ctx, f"f{s}")) for s in range(7)]
cur = self.enc.frame(fpn, self._geo(ctx, "f7"))
curf = self.front(cur, ffront, self._geo(ctx, "front"))
ttnn.deallocate(cur)
for t in ffront:
ttnn.deallocate(t)
image_bev = self.t8(bevs + [curf])
for t in bevs + [curf]:
ttnn.deallocate(t)
ctx.write_state("image_bev", image_bev)
ttnn.deallocate(image_bev)
self._shift(ctx, fpn)
for t in fpn:
ttnn.deallocate(t)
return pack_outputs({"ok": ctx["ok"]}, dtype="float32") # a dummy output (the state is the result)
def _step_b(self, ctx):
import ttnn
nav = ttnn.to_layout(ctx["nav"], ttnn.TILE_LAYOUT, memory_config=ttnn.DRAM_MEMORY_CONFIG)
fused = self.mfuse(ctx["image_bev"], nav)
ttnn.deallocate(nav)
return pack_outputs({"fused": fused}, dtype="bfloat16") # the fused BEV is bf16: the same values, half the read
# ------------------------------------------------------------------ host API
def capture(self) -> None:
self.runner.capture()
def select(self, bank: int, previous: Optional[int] = None) -> None:
"""Switch the ring to stream ``bank`` (saving the current ring into ``previous`` first)."""
for s in range(7):
for l in range(4):
if previous is not None:
self.runner.save_state(self._ring(s, l), previous)
self.runner.load_state(self._ring(s, l), bank)
def push(self, cams_input: np.ndarray) -> None:
"""``cams_input`` [6, 512, 512, 3] float32 (``backbone_input``) into the ring (history prime)."""
self.runner("push", inputs={"cams": cams_input.reshape(1, 1, 6 * 512, 512 * 3)})
def step(self, cams_input: np.ndarray, front_input: np.ndarray, geos: Sequence[Any],
geo_front: FrameGeometry, nav_rows: np.ndarray) -> np.ndarray:
"""One step -> the fused BEV ``[Q, 256]`` float32 (for the host planner). ``nav_rows`` ``[Q, 256]``: numpy, or a
torch bf16 tensor (no conversion on this thread: ``api`` converts it on its host pool)."""
self.step_begin(cams_input, front_input, geos, geo_front)
return self.step_end(nav_rows)
def step_begin(self, cams_input: np.ndarray, front_input: np.ndarray, geos: Sequence[Any],
geo_front: FrameGeometry) -> None:
"""Upload the frame and start step_a (non-blocking): the host is free until :meth:`step_end`."""
inputs = {"cams": cams_input.reshape(1, 1, 6 * 512, 512 * 3),
"front": front_input.reshape(1, 1, 1024, 1024 * 3)}
for k, g in enumerate(geos):
inputs.update(geometry_inputs(f"f{k}", g))
inputs.update(geometry_inputs("front", geo_front))
self.runner.run("step_a", inputs=inputs)
def step_end(self, nav_rows: Any) -> np.ndarray:
"""The map fusion with the navigation BEV ``[Q, 256]`` (numpy or torch bf16) -> the fused BEV ``[Q, 256]``."""
out = self.runner("step_b", inputs={"nav": nav_rows.reshape(1, 1, Q, E)})
return np.asarray(out["fused"], np.float32).reshape(Q, E)
def release(self) -> None:
self.runner.release()