changh95's picture
tt-model push centerpoint-p150 (container)
18c340c verified
Raw History Blame Contribute Delete
14.1 kB
# SPDX-License-Identifier: Apache-2.0
"""Python API: CenterPoint (Autoware lidar_centerpoint) on one Tenstorrent Blackhole p150.
from tt_centerpoint import CenterPoint
with CenterPoint.from_pretrained(device_id=0) as model: # weights -> HF cache, device open, traces captured
out = model("code/tt_centerpoint/samples/test_pcd.npz") # see PYTHON.md for every input form
print(out.to_dict()) # the same JSON as POST /predict
The contract shared by every bundle of the Autoware collection is the vendored ``ttaw.api_base.ModelBase``
(BUNDLE_CONVENTIONS.md section 8): ``from_pretrained`` resolves the pinned weights before it claims the chip, opens it
(ETH dispatch, 12x10), builds the graph and captures every trace variant in ``warmup_variants``, so the first call is
as fast as the later ones; calls are serialised by a lock (one chip, batch 1) and fill ``timing_ms``; ``close()`` is
idempotent, also runs at interpreter exit, and closes the chip only if the model opened it. The HTTP server
(``tt_centerpoint.server.app``) calls this class, so ``/predict`` and ``model(...)`` agree bit for bit.
This module holds the identity of the port and its hooks: host pre- and post-processing ported from Autoware live in
``tt_centerpoint.host`` (shared with the CPU reference ``tt_centerpoint.reference``, so device and reference see
identical voxel tensors), the ttnn graph in ``tt_centerpoint.tt`` (run by a ``ttaw.trace.TraceRunner``).
Importing it has no side effects: import ttnn / torch inside the hooks, never at module level.
Inputs (``points``, plus optional ``sweeps`` or ``stream``; host/preprocess.py has the full contract):
- a cloud in ``base_link`` with fields x, y, z (intensity is ignored: Autoware's ``point_feature_size`` is 4);
- a column named ``time_lag`` marks an already densified cloud (Autoware's 2-sweep input), used as is;
- ``sweeps=[{"points", "time_lag_s", "T_current_from_sweep"}]``: past sweeps densified on the host;
- ``stream={"id", "timestamp_s", "T_world_from_ego", "reset"}``: Autoware's stateful densification per stream id
(``num_past_frames: 1``), a missing pose refuses the frame without caching it (Autoware's TF failure).
Output: ``Detections3D`` with Autoware ``DetectedObjects`` semantics: ObjectClassification label ids (``LABELS``),
``existence_probability`` as the score, ``yaw_ros = -yaw_net - pi/2``, (length, width, height); ``meta`` holds the
pillar counts (overflow above 40,000 pillars), the per-stage detection counts and the per-object orientation
availability.
Per-request knobs (host only, PLAN.md 2.3 RT-host; defaults = Autoware's ml_package / node values): the scalar
``RUNTIME_PARAMS`` (``score_threshold``, the NMS distances, ``remap_classes``, ``max_detections``), the structured ones
(``score_thresholds`` per class and distance bin, ``distance_bin_upper_limits``, ``yaw_norm_thresholds`` per class)
and the pre-processing ``z_range`` (which narrows the z filter). Over HTTP all of them go in ``params``; in Python
they are keyword arguments of the call. :meth:`CenterPoint.validate_params` checks them before the device runs.
"""
from __future__ import annotations
from typing import Any, Dict, Optional
from . import io as tio
from .device import DEVICE_DEFAULTS
from .host.postprocess import (LABELS, RUNTIME_PARAMS, STRUCTURED_PARAMS, CenterPointPostprocessor,
validate_structured_params, validate_z_range)
from .host.preprocess import CenterPointPreprocessor, Prepared
from .reference.config import DEFAULT_VARIANT, VARIANTS, CenterPointConfig
from .ttaw.api_base import ModelBase
from .ttaw.outputs import Detections3D
__all__ = ["CenterPoint", "Output"]
# The result class of this model (ttaw.outputs: Detections3D, Detections2D, Segmentation3D, Mask2D, Trajectory).
Output = Detections3D
class CenterPoint(ModelBase):
"""CenterPoint (Autoware lidar_centerpoint) on one Blackhole p150. Create it with :meth:`from_pretrained`."""
MODEL_NAME = "centerpoint-p150"
ENV_PREFIX = "CENTERPOINT" # prefix of the environment knobs (SERVING.md section 3.4)
DEFAULT_REPO = "AutowareFoundation/lidar_centerpoint"
DEFAULT_TAG = "v4.1" # the Autoware ansible artifacts pin
# the commit DEFAULT_TAG points to (pinned: tags can move)
DEFAULT_REVISION = "494c8171def40bd36cc2feb323e0a5acbfab132b"
ALLOW_PATTERNS = ["base/*", "tiny/*"]
VARIANTS = VARIANTS # load-time (serve profiles base / tiny): selects the weights files and the trace shapes
DEFAULT_VARIANT = DEFAULT_VARIANT
INPUT_KIND = "lidar" # lidar | camera | multicam | lidar+multicam | planner
CAMERA_ORDER = () # multicam models: the fixed camera order of the network
POINT_FIELDS = tio.DEFAULT_POINT_FIELDS # default column names of an unnamed (N, 4) array
# output labels: autoware_perception_msgs ObjectClassification (label_id = the message value); the network's
# five heatmap classes (CAR, TRUCK, BUS, BICYCLE, PEDESTRIAN) map onto them, the remapper adds TRAILER
LABELS = list(LABELS)
# Per-request knobs (host post-processing only; defaults are Autoware's): host/postprocess.py
RUNTIME_PARAMS = RUNTIME_PARAMS
# z_range is a host PRE-processing knob (the z filter of the voxelizer), so it travels like an extra input to
# _prepare; over HTTP it is sent in params like every other knob (validate_params passes it on)
EXTRA_INPUTS = ("z_range",)
DEVICE_DEFAULTS = DEVICE_DEFAULTS # validated open parameters (device.py)
@classmethod
def validate_params(cls, params: Optional[Dict[str, Any]]) -> Dict[str, Any]:
"""``ModelBase.validate_params`` for the scalar knobs, plus the structured ones (``score_thresholds``,
``distance_bin_upper_limits``, ``yaw_norm_thresholds``: ``host.postprocess.validate_structured_params``) and
``z_range`` (kept in the result only when given). Client mistakes raise ``io.InputError`` (HTTP 400) before
the device runs; idempotent like the base method (the server validates, then ``model(**params)`` again)."""
params = dict(params or {})
structured = {k: params.pop(k) for k in list(params) if k in STRUCTURED_PARAMS}
z_range = params.pop("z_range", None)
out = super().validate_params(params)
out.update(validate_structured_params(structured))
if z_range is not None:
out["z_range"] = list(validate_z_range(z_range))
return out
def host_params(self) -> Dict[str, Any]:
"""The effective defaults of every per-request knob for this variant (``/info`` ``host_params``): what a
request gets when it sets nothing."""
cfg = self.config
names = list(cfg.class_names)
out = {k: v[3] for k, v in self.RUNTIME_PARAMS.items()}
out.update({
"score_thresholds": {c: [float(v) for v in cfg.score_thresholds[:, i]] for i, c in enumerate(names)},
"distance_bin_upper_limits": [float(v) for v in cfg.distance_bin_upper_limits],
"yaw_norm_thresholds": {c: float(v) for c, v in zip(names, cfg.yaw_norm_thresholds)},
"z_range": list(cfg.z_range),
})
return out
# ---- port-specific hooks (called by ModelBase; keep host work out of _forward) ---------------------------
def _build(self) -> None:
"""Host side (config of the variant, pre- / post-processors), then the ttnn graph of ``tt_centerpoint.tt``
(``TtCenterPoint``: PFN, gather-form scatter, SECOND, SECONDFPN, CenterHead) as the ``"default"`` variant
of a ``ttaw.trace.TraceRunner`` with two persistent inputs (no capture here; ``_warm_one`` captures), plus
one variant ``p<capacity>`` with its own features input per ``CENTERPOINT_PFN_BUCKETS`` capacity."""
from .reference.weights import load_weights
from .tt.model import FrameStaging, TtCenterPoint, build_runner, default_policy
self._build_host()
self.graph = TtCenterPoint(self.device, load_weights(self.weights_path, self.variant), self.config,
policy=default_policy())
self.runner = build_runner(self.graph, variants=("default",), name=f"{self.MODEL_NAME}/{self.variant}")
# persistent host buffers of the two inputs (written in place per frame, uploaded as they are)
self.staging = FrameStaging(self.graph, decorate=self.knobs.HOST_DECORATE,
sparse=self.knobs.HOST_STAGING == "sparse")
def _build_host(self, *, max_streams: int = 16) -> None:
"""The host half of ``_build`` (no device): usable alone by host tests and tools."""
from .knobs import KNOBS
self.knobs = KNOBS.read()
self.config = CenterPointConfig.from_weights(self.weights_path, self.variant)
self.pre = CenterPointPreprocessor(self.config, max_streams=max_streams,
voxelizer=self.knobs.HOST_VOXELIZER, decorate=self.knobs.HOST_DECORATE,
densify=self.knobs.HOST_DENSIFY)
self.post = CenterPointPostprocessor(self.config, nms=self.knobs.HOST_NMS)
k = self.knobs
if "numba" in (k.HOST_VOXELIZER, k.HOST_DECORATE, k.HOST_NMS, k.HOST_DENSIFY) \
or k.HOST_VOXELIZER == "numba2" or k.HOST_DECODE == "rows":
from .host import fast
fast.PREFILTER_U64 = k.HOST_PREFILTER == "u64"
fast.warm_up() # JIT at load, not in the first request
def _warm_one(self, variant: Dict[str, Any]) -> None:
"""Warm up and capture the traces of one entry of ``default_warmup_variants()``. ``TraceRunner.capture``
runs every pending variant eagerly (kernel JIT, program cache) before any capture, then captures with
program-cache misses forbidden; it is idempotent."""
self.runner.capture()
def _prepare(self, points: Any = None, *, sweeps: Optional[Any] = None, stream: Optional[Any] = None,
images: Any = None, calibration: Any = None, inputs: Any = None, z_range: Optional[Any] = None,
**_: Any) -> Prepared:
"""Host pre-processing (``host/preprocess.py``): densification, deterministic voxelization (``z_range``
narrows the z filter), the encoder tensor and the canvas gather index. Client mistakes raise
``tio.InputError`` (HTTP 400)."""
if points is None:
raise tio.InputError("this model needs 'points'")
if images or inputs is not None:
raise tio.InputError("CenterPoint takes a point cloud only (no 'images' / 'inputs')")
return self.pre(points, sweeps=sweeps, stream=stream, z_range=z_range)
def _forward(self, prepared: Prepared) -> Any:
"""Upload the frame's encoder input and canvas index into the persistent device inputs, replay the trace,
read the packed head tensor back (one D2H) and unpack it into the six head maps ``{name: (C, H, W)}``.
Runs under the model lock."""
inputs = self.staging.write(prepared)
variant = self.staging.variant # PFN_BUCKETS (R7): the smallest pillar capacity of the frame
if self.knobs.HOST_DECODE == "rows": # OPT_PLAN.md H3: decode on the rows, no unpack
from .host.postprocess import HeadRows
if self.knobs.HOST_READBACK == "tiled": # the TILE bytes as read back: no host untilize
out = self.runner.run(variant, inputs=inputs)
rb = getattr(self, "_readback", False)
if rb is False:
from .tt.model import TiledReadback
rb = self._readback = TiledReadback.create(out, self.device)
if rb is not None:
return HeadRows(None, self.graph.head.slices, *self.graph.head_grid, tiled=rb.read(out),
n_cols=rb.n_cols)
return HeadRows(self.runner.read(variant), self.graph.head.slices, *self.graph.head_grid)
return HeadRows(self.runner(variant, inputs=inputs), self.graph.head.slices, *self.graph.head_grid)
rows = self.runner(variant, inputs=inputs)
return self.graph.unpack(rows)
def _postprocess(self, raw: Any, prepared: Prepared, params: Dict[str, Any]) -> Output:
"""Host post-processing (``host/postprocess.py``): decode, circle NMS, ROS conversion, IoU-BEV NMS, class
remapper -> ``Detections3D``; ``raw`` = the six head maps ``{name: (C, H, W)}``, or the head rows as read back
(``host.postprocess.HeadRows``, ``CENTERPOINT_HOST_DECODE=rows``: candidate cells only, identical output)."""
meta = {"variant": self.variant, **prepared.stats()}
return self.post(raw, params, model=self.MODEL_NAME, frame_id=prepared.frame_id, meta=meta)
def _release(self) -> None:
"""Release the traces, persistent tensors and device weights; also called when ``from_pretrained`` fails
half-way (tolerates a partial build)."""
self._readback = False
runner = getattr(self, "runner", None)
if runner is not None:
runner.release()
self.runner = None
graph = getattr(self, "graph", None)
if graph is not None:
graph.release()
self.graph = None
def extra_info(self) -> Dict[str, Any]:
"""Additions to ``model.info`` and ``/info``: the variant config, the host state and the runner."""
info: Dict[str, Any] = {}
if getattr(self, "config", None) is not None:
info["config"] = self.config.describe()
info["host_params"] = self.host_params()
if getattr(self, "knobs", None) is not None:
info["knobs"] = self.knobs.as_dict()
if getattr(self, "pre", None) is not None:
info["preprocess"] = self.pre.describe()
runner = getattr(self, "runner", None)
if runner is not None:
info["trace"] = runner.describe()
graph = getattr(self, "graph", None)
if graph is not None:
info["graph"] = graph.describe()
return info