changh95's picture
tt-model push meteor-2-p150 (container)
0f131e7 verified
Raw History Blame Contribute Delete
10.2 kB
# SPDX-License-Identifier: Apache-2.0
"""Python API: METEOR 2 (TIER IV, AutowareFoundation/meteor2 v1.0) on one Tenstorrent Blackhole p150.
from tt_meteor2 import METEOR2, load_sample
with METEOR2.from_pretrained(variant="gather") as model: # weights -> HF cache, device open, traces captured
out = model(**load_sample("code/tt_meteor2/samples/synthetic_8cam.json"))
print(out.to_dict()) # the same JSON as POST /predict
``variant`` (load time, env ``METEOR2_VARIANT``) is the released form: ``gather`` (the exact geometric lift; K and
T_cam_ego are inputs, any rig) or ``npu`` (the lift as fixed low-rank maps; TIER IV's DRS rig only). Both share the
host code; the device graph is ``tt.model.TtMeteor2`` traced by ``tt.runner.Meteor2Device``.
Inputs per call (``host.inputs``): ``images`` (the 8 cameras, 16:9, any size), ``calibration`` (per camera
intrinsics + ``T_ref_from_camera``; required by ``gather``), ``ego_speed`` (m/s) and optionally ``acc``, ``ego_hist``
[32], ``route`` [13] as METEOR 2's graph defines them (zeros when absent). Runtime params: the box score threshold
and top-k, the occupancy display gates, ``heads`` (compact debug arrays in the JSON). One frame: host prep (resize,
space-to-depth into the upload buffer; the lift tables only when the rig changes) -> one traced frame (5 MB read) ->
host peak decode in fp32 -> a second small trace gathers the box rows -> ego MLPs on the host (fp32).
"""
from __future__ import annotations
from typing import Any, Dict, Optional
import numpy as np
from . import io as tio
from .device import DEVICE_DEFAULTS
from .host.outputs import Meteor2Output
from .reference import config as C
from .ttaw.api_base import ModelBase
from .ttaw.knobs import Knob, Knobs
__all__ = ["METEOR2", "Output", "KNOBS", "load_sample"]
Output = Meteor2Output
KNOBS = Knobs("METEOR2", [
Knob("CONV", "HiFi4+fp32+l1acc", "precision of every kxk / 1x1 feature conv (ttaw Precision spec)"),
Knob("HEAD_CONV", "HiFi4+fp32+l1acc:w=float32", "precision of the output heads (box rows, lane, occupancy)"),
Knob("LIFT_CAMS", 3, "Gather form: most cameras that see one BEV point (4 bilinear taps each); a rig above it "
"is refused with a 400"),
Knob("PAINT_SLOTS", 3, "Gather form: most cameras that paint one BEV point"),
Knob("HOST_THREADS", 8, "threads of the per-camera host preparation (resize + space-to-depth)"),
Knob("RESIZE", "fast", "camera upscale to 1152x648: fast = OpenCV's uint8 bicubic (0.2 ms per camera); exact = "
"upstream's float rule rounded to uint8 (4 ms; differs from fast by 1 grey level on 0.016 % "
"of the pixels)", choices=("fast", "exact")),
Knob("CONV_L1", "table", "kxk conv placement: table = tt.model.PLACEMENT (ttnn's L1 path for the BEV maps and the "
"small image stages, measured 3-5x faster); none = the DRAM-sliced path everywhere",
choices=("table", "none")),
])
def load_sample(path: Any) -> Dict[str, Any]:
"""``model(**load_sample("samples/<name>.json"))``: cameras + calibration + ego inputs."""
import json
from pathlib import Path
p = Path(path)
spec = json.loads(p.read_text())
calib = dict(spec.get("calibration") or {})
if "preset" in calib:
calib = tio.resolve_calibration(calib, p.parent.parent / "calib")
images = {name: str((p.parent / rel).resolve()) for name, rel in spec["images"].items()}
out = {"images": images, "calibration": calib, "ego_speed": float(spec.get("ego_speed", 0.0))}
for k in ("acc", "ego_hist", "route"):
if k in spec:
out[k] = spec[k]
return out
class METEOR2(ModelBase):
"""METEOR 2 on one Blackhole p150. Create it with :meth:`from_pretrained`."""
MODEL_NAME = "meteor-2-p150"
ENV_PREFIX = "METEOR2"
DEFAULT_REPO = C.WEIGHTS_REPO
DEFAULT_TAG = "v1.0"
DEFAULT_REVISION = C.WEIGHTS_REVISION
ALLOW_PATTERNS = ["meteor2_gather.onnx", "meteor2_npu.onnx", "meteor2_gather.param.yaml", "meteor2_npu.param.yaml",
"LICENSE", "SHA256SUMS"]
WEIGHTS_LICENSE = "Apache-2.0 (AutowareFoundation/meteor2 model card)"
VARIANTS = ["gather", "npu"]
DEFAULT_VARIANT = "gather"
INPUT_KIND = "multicam"
CAMERA_ORDER = C.CAMERAS
REQUIRE_CALIBRATION = False # the NPU form has its rig in the weights; the Gather form checks it itself
LABELS = ["vehicle", "pedestrian"]
RUNTIME_PARAMS = {
"box_threshold": (float, 0.0, 1.0, 0.30),
"box_topk": (int, 1, 64, 64),
"occ_gate": (float, 0.0, 1.0, 0.55),
"occ_gate_strict": (float, 0.0, 1.0, 0.92),
"heads": (bool, None, None, False),
}
EXTRA_INPUTS = ("ego_speed", "acc", "ego_hist", "route")
DEVICE_DEFAULTS = DEVICE_DEFAULTS
# ---- hooks -----------------------------------------------------------------------------------------------
def _build(self) -> None:
from concurrent.futures import ThreadPoolExecutor
from .host.ego import EgoHead
from .reference.weights import Meteor2Weights
from .tt.model import S2D_H, S2D_W
from .tt.runner import Meteor2Device
params = {k.upper(): v for k, v in getattr(self, "compile_params", {}).items() if k.upper() in KNOBS.knobs}
self.knobs = KNOBS.read(**params)
self.w = Meteor2Weights(self.weights_path / C.ONNX_FILES[self.variant])
if self.w.form != self.variant:
raise ValueError(f"{C.ONNX_FILES[self.variant]} is the {self.w.form} form")
self.ego_head = EgoHead(self.w)
self.dev = Meteor2Device(self.device, self.w, conv_precision=str(self.knobs.CONV),
head_precision=str(self.knobs.HEAD_CONV), lift_cams=int(self.knobs.LIFT_CAMS),
paint_slots=int(self.knobs.PAINT_SLOTS), conv_l1=str(self.knobs.CONV_L1))
self.runner = self.dev.runner
self.pool = ThreadPoolExecutor(int(self.knobs.HOST_THREADS))
self.buffer = np.empty((1, 1, C.N_CAM * S2D_H * S2D_W, 12), np.uint8)
self._tables: Dict[str, Any] = {}
if self.variant == "gather":
self._pts = self.w.bev_points()
self._zfill = self.w.paint_z_fill()
def _warm_one(self, variant: Any) -> None:
self.runner.capture()
def _lift_tables(self, K: np.ndarray, T: np.ndarray):
from .host.calib import lift_tables, rig_key
key = rig_key(K, T)
if key not in self._tables:
if len(self._tables) >= 8:
self._tables.pop(next(iter(self._tables)))
self._tables[key] = lift_tables(K, T, self._pts, self._zfill)
return self._tables[key]
def _prepare(self, points: Any = None, *, images: Any = None, calibration: Any = None, stream: Any = None,
ego_speed: Any = None, acc: Any = None, ego_hist: Any = None, route: Any = None,
**_: Any) -> Dict[str, Any]:
from .host.inputs import prepare_request
if points is not None:
raise tio.InputError("this model takes the eight camera images (+ calibration, ego inputs), not points")
frame = prepare_request(images, calibration, ego_speed=ego_speed, acc=acc, ego_hist=ego_hist, route=route,
need_calibration=self.variant == "gather", buffer=self.buffer, pool=self.pool,
calib_dir=getattr(self, "calib_dir", None), resize=str(self.knobs.RESIZE))
tables = self._lift_tables(frame.K, frame.T_cam_ego) if self.variant == "gather" else None
return {"frame": frame, "tables": tables}
def _forward(self, prepared: Dict[str, Any]) -> Any:
if prepared["tables"] is not None:
self.dev.set_calibration(prepared["tables"])
return self.dev.frame(prepared["frame"].img)
def _postprocess(self, raw: Any, prepared: Dict[str, Any], params: Dict[str, Any]) -> Output:
from .host.postprocess import decode_rows, find_peaks
f = prepared["frame"]
hm = np.stack([raw["hm0"].reshape(-1), raw["hm1"].reshape(-1)]).reshape(2, C.BEV_H, C.BEV_W)
peaks = find_peaks(hm, float(params["box_threshold"]), int(params["box_topk"]))
rows = self.dev.gather([p[1] for p in peaks]) if peaks else np.zeros((0, 64), np.float32)
boxes = decode_rows(peaks, rows)
eg = self.ego_head(raw["ego_pool"].reshape(-1, 128)[:20], raw["kin_pool"].reshape(-1, 16)[:160], f.v0, f.acc,
f.ego_hist, f.route)
lane = raw["lane"].reshape(-1)[: C.LANE_H * C.LANE_W].reshape(C.LANE_H, C.LANE_W).astype(np.uint8)
code = raw["occ_cls"].reshape(C.OCC_H, C.OCC_W, C.OCC_Z).transpose(2, 0, 1).astype(np.uint8)
occ_cls = code % 10 # most likely non-free class
occ_argmax = np.where(code >= 10, 0, occ_cls).astype(np.uint8) # argmax over all 10 classes
occ_p = raw["occ_p"].reshape(C.OCC_H, C.OCC_W, C.OCC_Z).transpose(2, 0, 1).astype(np.float32)
meta = dict(f.meta)
if prepared["tables"] is not None:
meta["rig_key"] = prepared["tables"].key
return Meteor2Output(boxes, eg["ego"][0], eg["ego_path_6s"][0], eg["tl"][0], lane, occ_cls, occ_p, occ_argmax,
occ_gate=float(params["occ_gate"]), occ_gate_strict=float(params["occ_gate_strict"]),
form=self.variant, heads=bool(params["heads"]), model=self.MODEL_NAME, meta=meta)
def _release(self) -> None:
runner = getattr(self, "runner", None)
if runner is not None:
runner.release()
pool = getattr(self, "pool", None)
if pool is not None:
pool.shutdown(wait=False)
def extra_info(self) -> Dict[str, Any]:
info: Dict[str, Any] = {"form": self.variant}
if hasattr(self, "knobs"):
info["knobs"] = self.knobs.as_dict()
if getattr(self, "dev", None) is not None:
info["device_graph"] = self.dev.describe()
return info