# SPDX-License-Identifier: Apache-2.0 """VisionPilot networks on the p150 as captured traces (ttaw ``TraceRunner``). One ``TraceRunner`` holds every network loaded on the device, one trace variant each (``capture()`` warms all variants before capturing any: a program compiled after a capture could overwrite another trace's buffers, ttaw API section 3). ``NetRunner`` is the one-network case. Input: each network image as uint8 4 x 4 space-to-depth cells ``[1, 1, Hc*Wc, 48]`` (``stem.pack_s2d4``; 0.85 ms to upload instead of 13 ms for one 3-byte row per pixel). Inside the trace: one typecast to bf16 (exact for 0..255), the plan with its stem rewritten for cells (``stem.rewrite_stem``: the input scaling is folded into the first convolution), then the cut tensors packed into one float32 readback (cuts of at most 32 channels are transposed to ``[C, H*W]`` first, so their packed rows are long). The host tail (``Plan.run_tail``) turns them into the network outputs exactly as the ONNX file defines them. """ from __future__ import annotations import time from typing import Any, Dict, Mapping, Optional, Tuple import numpy as np from ..graph import Graph from ..models import NetworkSpec from ..plan import Plan from ..stem import pack_s2d4, rewrite_stem from ..ttaw.ops.conv import FeatureMap from ..ttaw.trace import TraceRunner, pack_outputs from .backend import TtBackend SMALL_CUT = 32 class _Net: def __init__(self, device: Any, spec: NetworkSpec, graph: Graph, backend: TtBackend): self.spec = spec self.graph = graph self.plan = Plan(graph, spec) self.image_hw = {name: tuple(graph.shape(name)[2:]) for name in spec.inputs} a, b = spec.channel_affine() rewrite_stem(self.plan, a, b) self.backend = backend self.cells = {name: self.plan.meta[name][1:3] for name in spec.inputs} # streams (AutoDrive): frame t's curr-branch boundary tensors are frame t+1's prev-branch ones self.branches = self.plan.branches() def state_key(self, i: int) -> str: return f"{self.spec.name}/prev_feat{i}" def _feed(self, ctx, name): import ttnn hc, wc = self.cells[name] return FeatureMap(ttnn.typecast(ctx[self.input_key(name)], ttnn.bfloat16), 1, hc, wc, 48) def forward_prime(self, ctx): """Frame 1 of a stream: the curr branch only, its boundary tensors into the states.""" br = self.branches curr_in = self.spec.inputs[1] out = self.plan.run(self.backend, {curr_in: self._feed(ctx, curr_in)}, steps=br["curr"], outputs=[c for _, c in br["boundary"]]) for i, (_, c) in enumerate(br["boundary"]): ctx.write_state(self.state_key(i), out[c].tensor) return out[br["boundary"][0][1]].tensor def forward_stream(self, ctx): """Frame t > 1: the curr branch, the head on (state = frame t-1's boundary, frame t's), the states updated.""" br = self.branches curr_in = self.spec.inputs[1] feeds = {curr_in: self._feed(ctx, curr_in)} for i, (p, _) in enumerate(br["boundary"]): _, h, w, c = self.plan.meta[p] feeds[p] = FeatureMap(ctx[self.state_key(i)], 1, h, w, c) out = self.plan.run(self.backend, feeds, steps=br["curr"] + br["head"], outputs=list(self.spec.cut) + [c for _, c in br["boundary"]]) packed = self._pack(out) for i, (_, c) in enumerate(br["boundary"]): ctx.write_state(self.state_key(i), out[c].tensor) return packed def input_key(self, name: str) -> str: return f"{self.spec.name}/{name}" def forward(self, ctx): feeds = {name: self._feed(ctx, name) for name in self.cells} return self._pack(self.plan.run(self.backend, feeds)) def _pack(self, cut): import ttnn out = {} for c in self.spec.cut: t = cut[c].tensor if self.plan.meta[c][3] <= SMALL_CUT: t = ttnn.transpose(t, -2, -1) # [1, 1, H*W, C] -> [1, 1, C, H*W] out[c] = t return pack_outputs(out, dtype="float32") def device_inputs(self, images_rgb: Mapping[str, np.ndarray], only=None) -> Dict[str, np.ndarray]: out = {} for name, (h, w) in self.image_hw.items(): if only is not None and name not in only: continue img = images_rgb[name] if img.shape != (h, w, 3) or img.dtype != np.uint8: raise ValueError(f"{name}: expected uint8 ({h}, {w}, 3), got {img.dtype} {img.shape}") out[self.input_key(name)] = pack_s2d4(img).reshape(1, 1, -1, 48) return out def unpack(self, packed: Mapping[str, np.ndarray]) -> Dict[str, np.ndarray]: out = {} for c in self.spec.cut: _, hh, ww, cc = self.plan.meta[c] a = np.asarray(packed[c], np.float32) if cc <= SMALL_CUT: a = a.reshape(-1, a.shape[-1])[:cc, : hh * ww].T else: a = a.reshape(-1, a.shape[-1])[: hh * ww, :cc] out[c] = np.ascontiguousarray(a.reshape(hh, ww, cc).transpose(2, 0, 1)[None]) return out class MultiNetRunner: """Several networks on one device: one TraceRunner, one variant per network (named by ``spec.name``).""" def __init__(self, device: Any, nets: Mapping[str, Tuple[NetworkSpec, Graph]], *, num_command_queues: int = 1, weight_terms: int = 1, conv_precision: Optional[str] = None): import ttnn self.device = device kw = {} if conv_precision is None else {"conv_precision": conv_precision} self.nets: Dict[str, _Net] = {} self.runner = TraceRunner(device, num_command_queues=num_command_queues, name="visionpilot") for key, (spec, graph) in nets.items(): net = _Net(device, spec, graph, TtBackend(device, weight_terms=weight_terms, **kw)) self.nets[key] = net for name, (hc, wc) in net.cells.items(): self.runner.add_input(net.input_key(name), shape=(1, 1, hc * wc, 48), dtype="uint8", layout=ttnn.ROW_MAJOR_LAYOUT) self.runner.add_variant(key, net.forward) if net.branches is not None: for i, (p, _) in enumerate(net.branches["boundary"]): _, h, w, c = net.plan.meta[p] self.runner.add_state(net.state_key(i), shape=(1, 1, h * w, c), dtype="bfloat16", layout=ttnn.TILE_LAYOUT) self.runner.add_variant(f"{key}/prime", net.forward_prime) self.runner.add_variant(f"{key}/stream", net.forward_stream) self.timings: Dict[str, float] = {} def capture(self) -> None: t0 = time.perf_counter() self.runner.capture() self.timings["capture_s"] = time.perf_counter() - t0 def run_device(self, key: str, images_rgb: Mapping[str, np.ndarray]) -> Dict[str, np.ndarray]: """``images_rgb[input name]``: uint8 ``(512, 1024, 3)`` RGB network image -> the cut tensors (NCHW).""" net = self.nets[key] packed = self.runner(key, inputs=net.device_inputs(images_rgb)) return net.unpack(packed) def __call__(self, key: str, images_rgb: Mapping[str, np.ndarray]) -> Dict[str, np.ndarray]: return self.nets[key].plan.run_tail(self.run_device(key, images_rgb)) def stream(self, key: str, image_rgb: np.ndarray, *, fresh: bool) -> Optional[Dict[str, np.ndarray]]: """One frame of a stream of a two-frame network (AutoDrive): ``fresh`` (the first frame) primes the state and returns None (VisionPilot returns nothing on its first frame too); later frames return the outputs of (previous frame, this frame), with one backbone pass per frame.""" net = self.nets[key] if net.branches is None: raise ValueError(f"{key} has no stream form") curr_in = net.spec.inputs[1] inputs = net.device_inputs({curr_in: image_rgb}, only=(curr_in,)) if fresh: self.runner.run(f"{key}/prime", inputs=inputs) return None packed = self.runner(f"{key}/stream", inputs=inputs) return net.plan.run_tail(net.unpack(packed)) def release(self) -> None: self.runner.release() class NetRunner: """One network: ``NetRunner(device, spec, graph)``; ``capture()``, ``run_device(images)``, ``__call__``.""" def __init__(self, device: Any, spec: NetworkSpec, graph: Graph, **kw: Any): self.multi = MultiNetRunner(device, {spec.name: (spec, graph)}, **kw) self.key = spec.name self.spec = spec self.plan = self.multi.nets[self.key].plan self.runner = self.multi.runner self.timings = self.multi.timings def capture(self) -> None: self.multi.capture() def run_device(self, images_rgb: Mapping[str, np.ndarray]) -> Dict[str, np.ndarray]: return self.multi.run_device(self.key, images_rgb) def __call__(self, images_rgb: Mapping[str, np.ndarray]) -> Dict[str, np.ndarray]: return self.multi(self.key, images_rgb) @property def streams(self) -> bool: return self.multi.nets[self.key].branches is not None def stream(self, image_rgb: np.ndarray, *, fresh: bool) -> Optional[Dict[str, np.ndarray]]: return self.multi.stream(self.key, image_rgb, fresh=fresh) def release(self) -> None: self.multi.release()