changh95's picture
tt-model push centerpoint-p150 (container)
18c340c verified
Raw History Blame Contribute Delete
16 kB
# SPDX-License-Identifier: Apache-2.0
"""Host pre-processing of CenterPoint with Autoware's semantics (research/centerpoint/SPEC.md section 3; PLAN.md 2.3),
shared by the device path and the CPU reference so both see **identical** voxel tensors (S:centerpoint:381).
Input contract (the cloud is in the model frame, Autoware's ``base_link``; only x, y, z are used,
``point_feature_size: 4``):
1. ``points`` with a ``time_lag`` column: an already densified cloud (what Autoware's ``PointCloudDensification``
hands to the voxelizer), used as is;
2. ``points`` (+ optional ``sweeps=[{"points", "time_lag_s", "T_current_from_sweep"}]``): client-side
densification; each past sweep goes through the float32 sweep kernel (``ttaw.pointcloud.densify_sweeps``);
3. ``points`` + ``stream={"id", "timestamp_s", "T_world_from_ego", "reset"}``: server-side densification, Autoware's
state machine per stream id (``num_past_frames: 1``, cold start, no age limit, capacity drops whole sweeps;
``ttaw.pointcloud.SweepDensifier``). A missing pose is Autoware's TF failure: the frame is refused (HTTP 400)
and not cached;
4. ``points`` alone: one sweep, ``time_lag = 0`` (Autoware with ``num_past_frames: 0``).
Then (``ttaw.voxelize``): rows with a non-finite x / y / z (dropped at decode by ``ttaw.io.PointCloud``) or all-zero
x, y, z (organized-cloud fillers) never enter; a fixed seeded permutation (seed 0, PLAN.md D1) replaces Autoware's
time-seeded shuffle; Autoware's half-open range test (``point_cloud_range``; the per-request ``z_range`` knob may
narrow its z extent, an RT-host parameter of PLAN.md 2.3: the pillars are full columns, so no device shape changes);
the first 32 points of every 0.32 m cell; pillar ids in flipped-x cell order, at most 40,000 (overflow keeps the
front-most pillars and is reported); the 9 decorated features of ``generateFeatures_kernel``.
Device inputs built here (PLAN.md 2.3): the ``(40000, 32, 9)`` float32 encoder input and the gather index of the
canvas (C19: every cell ``iy * 480 + ix`` -> its pillar row, or row 40,000, an explicit zero row).
"""
from __future__ import annotations
from dataclasses import dataclass, field, replace
from typing import Any, Dict, Mapping, Optional, Sequence, Tuple
import numpy as np
from .. import io as tio
from ..reference.config import DROP_ZERO_POINTS, SHUFFLE_SEED, CenterPointConfig
from ..ttaw.geometry import as_transform
from ..ttaw.pointcloud import StreamDensifiers, densify_sweeps, nonzero_rows
from ..ttaw.voxelize import PillarGridSpec, PillarSet, assign_pillars, canvas_gather_index, decorate_pillar_features
from .postprocess import validate_z_range
__all__ = ["Prepared", "CenterPointPreprocessor", "TIME_LAG_FIELD"]
TIME_LAG_FIELD = "time_lag" # a column with this name marks a pre-densified cloud (seconds)
@dataclass
class Prepared:
"""One frame, ready for the device or the CPU reference."""
points: np.ndarray # (N, 4) float32 x, y, z, time_lag: the cloud handed to the voxelizer
pillars: PillarSet
features: Optional[np.ndarray] # (max_voxel_size, 32, F) float32 encoder input; None = decorated on first use
canvas_index: np.ndarray # (grid_y * grid_x,) uint32: cell -> pillar row; max_voxel_size = zero row
frame_id: str = "base_link"
densify: Dict[str, Any] = field(default_factory=dict)
z_range: Optional[Tuple[float, float]] = None # the per-request z filter, when it differs from the model's
spec: Optional[PillarGridSpec] = None # the grid of this frame (needed by a deferred decoration)
encoder_in_feature_size: int = 9
@property
def features_ready(self) -> bool:
"""The float32 encoder input exists (False: deferred, e.g. decorated straight into the staging rows)."""
return self._features is not None
@property
def num_pillars(self) -> int:
return self.pillars.num_pillars
@property
def coords(self) -> np.ndarray:
return self.pillars.coords
def stats(self) -> Dict[str, Any]:
"""Pillar statistics, Autoware's diagnostic ``is_num_pillars_within_range`` (false from
``num_pillars >= max_voxel_size`` on, i.e. also at exactly 40,000 pillars: ``centerpoint_trt.cpp:202``) and
the densification info."""
s = self.pillars.stats()
s["is_num_pillars_within_range"] = bool(self.pillars.num_pillars_total < self.pillars.points.shape[0])
s["densify"] = self.densify
if self.z_range is not None:
s["z_range"] = list(self.z_range)
return s
def _get_features(self: Prepared) -> np.ndarray:
"""The (max_voxel_size, 32, F) float32 encoder input, decorated on first access when it was deferred (the numpy
oracle ``decorate_pillar_features``: the CPU reference and the tests always see the same tensor)."""
if self._features is None:
if self.spec is None:
raise ValueError("Prepared: deferred features need the grid spec")
self._features = decorate_pillar_features(self.pillars, self.spec,
encoder_in_feature_size=self.encoder_in_feature_size)
return self._features
def _set_features(self: Prepared, value: Optional[np.ndarray]) -> None:
object.__setattr__(self, "_features", value)
Prepared.features = property(_get_features, _set_features) # the dataclass __init__ assigns through it
def _cloud(source: Any, what: str) -> tio.PointCloud:
if source is None:
raise tio.InputError(f"{what} is missing")
return tio.load_points(source)
def _xyz(cloud: tio.PointCloud) -> np.ndarray:
xyz = cloud.select(("x", "y", "z")) if {"x", "y", "z"} <= set(cloud.fields) else cloud.points[:, :3]
return np.ascontiguousarray(xyz, dtype=np.float32)
def _clean(xyz: np.ndarray, drop_zero: bool) -> np.ndarray:
return xyz[nonzero_rows(xyz)] if drop_zero else xyz
class CenterPointPreprocessor:
"""Stateful only through the per-stream densification caches (``stream`` inputs)."""
def __init__(self, config: CenterPointConfig, *, shuffle_seed: Optional[int] = SHUFFLE_SEED,
max_streams: int = 16, drop_zero_points: bool = DROP_ZERO_POINTS, voxelizer: str = "numpy",
decorate: str = "numpy", densify: str = "numpy"):
if config.point_feature_size != 4:
raise ValueError("this port implements point_feature_size 4 (x, y, z, time_lag)")
self.config = config
self.spec = config.grid_spec
self.shuffle_seed = shuffle_seed
self.drop_zero_points = drop_zero_points
if voxelizer not in ("numba2", "numba", "numpy") or decorate not in ("numba", "numpy") \
or densify not in ("numba", "numpy"):
raise ValueError("voxelizer must be 'numba2', 'numba' or 'numpy'; decorate / densify 'numba' or 'numpy'")
# "numba": the compiled twins of host/fast.py (bit-identical; numpy when numba is missing). decorate="numba"
# defers the float32 encoder input: FrameStaging decorates straight into its bf16 rows (OPT_PLAN.md H1)
self.voxelizer = voxelizer
self.decorate = decorate
self.densify = densify # "numba" (R10 H7): select + nonzero_rows + copy in one pass (host/fast.py)
self.streams = StreamDensifiers(num_past_frames=int(config.common["num_past_frames"]),
cloud_capacity=int(config.common["cloud_capacity"]), max_streams=max_streams)
# ---------------------------------------------------------------------------------------- densification
def densified_points(self, points: Any = None, *, sweeps: Optional[Sequence[Mapping[str, Any]]] = None,
stream: Optional[Mapping[str, Any]] = None) -> Tuple[np.ndarray, Dict[str, Any], str]:
"""The (N, 4) float32 cloud (x, y, z, time_lag) of one request, its densification info and frame id."""
cloud = _cloud(points, "this model needs 'points'")
frame_id = cloud.frame_id
capacity = int(self.config.common["cloud_capacity"])
if TIME_LAG_FIELD in cloud.fields: # 1. pre-densified
if sweeps or stream is not None:
raise tio.InputError("a cloud with a 'time_lag' column is already densified: do not send 'sweeps' "
"or 'stream' with it")
pts = self._fast_select(cloud, ("x", "y", "z", TIME_LAG_FIELD), 4)
if pts is None:
pts = cloud.select(("x", "y", "z", TIME_LAG_FIELD))
if self.drop_zero_points:
pts = pts[nonzero_rows(pts)]
if not np.isfinite(pts[:, 3]).all():
raise tio.InputError("time_lag holds non-finite values")
return np.ascontiguousarray(pts), {"mode": "pre-densified", "num_points": int(len(pts))}, frame_id
if not sweeps and stream is None and self.densify == "numba": # 4. single sweep, one pass
pts = self._fast_single(cloud)
if pts is not None:
return pts, {"mode": "single", "num_points": int(len(pts))}, frame_id
xyz = _clean(_xyz(cloud), self.drop_zero_points)
if sweeps and stream is not None:
raise tio.InputError("give 'sweeps' (client-side densification) or 'stream' (server-side), not both")
if sweeps: # 2. client-side
past = []
for i, s in enumerate(sweeps):
if not isinstance(s, Mapping):
raise tio.InputError(f"sweeps[{i}] must be an object {{points, time_lag_s, T_current_from_sweep}}")
try:
lag = float(s.get("time_lag_s", 0.0))
except (TypeError, ValueError):
lag = float("nan")
if not np.isfinite(lag):
raise tio.InputError(f"sweeps[{i}].time_lag_s must be finite")
T = s.get("T_current_from_sweep")
T = None if T is None else as_transform(T, field=f"sweeps[{i}].T_current_from_sweep")
past.append((_clean(_xyz(_cloud(s.get("points"), f"sweeps[{i}].points")), self.drop_zero_points),
lag, T))
pts, info = densify_sweeps(xyz, past, cloud_capacity=capacity)
return pts, {"mode": "sweeps", **info.to_dict()}, frame_id
if stream is not None: # 3. server-side, per stream id
if not isinstance(stream, Mapping):
raise tio.InputError("stream must be an object {id, timestamp_s, T_world_from_ego, reset}")
sid = str(stream.get("id", "default"))
try:
stamp = float(stream["timestamp_s"])
except (KeyError, TypeError, ValueError):
stamp = float("nan")
if not np.isfinite(stamp):
raise tio.InputError("stream.timestamp_s (seconds) is required for server-side densification")
T = stream.get("T_world_from_ego")
T = None if T is None else as_transform(T, field="stream.T_world_from_ego")
d = self.streams.get(sid, reset=bool(stream.get("reset", False)))
if not d.enqueue(xyz, stamp, T):
raise tio.InputError(
f"stream.T_world_from_ego is required with num_past_frames={d.num_past_frames}: Autoware skips "
"a frame without its map->base_link transform and does not cache it (nor did this request)")
pts, info = d.sweep_points(point_feature_size=4)
return pts, {"mode": "stream", "stream_id": sid, **info.to_dict()}, frame_id
pts = np.zeros((len(xyz), 4), np.float32) # 4. single sweep
pts[:, :3] = xyz
return pts, {"mode": "single", "num_points": int(len(pts))}, frame_id
def _fast_select(self, cloud: tio.PointCloud, names: Tuple[str, ...], width: int) -> Optional[np.ndarray]:
"""``HOST_DENSIFY=numba``: ``cloud.select(names)`` (zero-padded to ``width`` columns) without the rows
``nonzero_rows`` drops, in one pass (``host/fast.select_nonzero``, bit-identical); None = use numpy."""
if self.densify != "numba" or not {"x", "y", "z", *names} <= set(cloud.fields):
return None
from . import fast
f = cloud.fields
return fast.select_nonzero(cloud.points, tuple(f.index(n) for n in names),
tuple(f.index(n) for n in ("x", "y", "z")), width=width,
drop_zero=self.drop_zero_points)
def _fast_single(self, cloud: tio.PointCloud) -> Optional[np.ndarray]:
return self._fast_select(cloud, ("x", "y", "z"), 4)
# ------------------------------------------------------------------------------------------ voxelization
def z_range_spec(self, z_range: Optional[Any]) -> Tuple[PillarGridSpec, Optional[Tuple[float, float]]]:
"""The grid spec of a request: the model's, or its z extent narrowed to ``z_range`` (validated with
:func:`validate_z_range` against the model's range). Only Autoware's range test reads z: the pillars are
full columns (voxel z = the whole range), the cell index and the decoration use x / y only. Returns the spec
and the effective z range when it differs from the model's (else None)."""
z = validate_z_range(z_range, self.config.z_range)
if z is None or z == self.config.z_range:
return self.spec, None
mn, mx = self.spec.range_min, self.spec.range_max
return replace(self.spec, range_min=(mn[0], mn[1], z[0]), range_max=(mx[0], mx[1], z[1])), z
def voxelize(self, points4: np.ndarray, *, z_range: Optional[Any] = None, defer_features: bool = False
) -> Tuple[PillarSet, Optional[np.ndarray], np.ndarray]:
"""(N, 4) cloud -> pillars, (max_voxel_size, 32, 9) encoder input (None with ``defer_features``), canvas
gather index."""
spec, _ = self.z_range_spec(z_range)
if self.voxelizer in ("numba", "numba2"):
from . import fast
pillars = fast.assign_pillars(points4, spec, shuffle_seed=self.shuffle_seed,
version=2 if self.voxelizer == "numba2" else 1)
else:
pillars = assign_pillars(points4, spec, shuffle_seed=self.shuffle_seed)
features = None if defer_features else decorate_pillar_features(
pillars, spec, encoder_in_feature_size=self.config.encoder_in_feature_size)
index = canvas_gather_index(pillars.coords, pillars.num_pillars, spec, sentinel=spec.max_pillars)
return pillars, features, index
def __call__(self, points: Any = None, *, sweeps: Optional[Sequence[Mapping[str, Any]]] = None,
stream: Optional[Mapping[str, Any]] = None, z_range: Optional[Any] = None) -> Prepared:
_, z = self.z_range_spec(z_range) # a bad z_range is a 400 before densification touches a stream
pts, info, frame_id = self.densified_points(points, sweeps=sweeps, stream=stream)
pillars, features, index = self.voxelize(pts, z_range=z, defer_features=self.decorate == "numba")
spec, _ = self.z_range_spec(z)
return Prepared(points=pts, pillars=pillars, features=features, canvas_index=index, frame_id=frame_id,
densify=info, z_range=z, spec=spec,
encoder_in_feature_size=self.config.encoder_in_feature_size)
def describe(self) -> Dict[str, Any]:
return {"shuffle_seed": self.shuffle_seed, "drop_zero_points": self.drop_zero_points,
"voxelizer": self.voxelizer, "decorate": self.decorate, "densify": self.densify,
"z_range": list(self.config.z_range), "streams": self.streams.describe()}