bevfusion-p150 / code /tt_bevfusion /host /postprocess.py
changh95's picture
tt-model push bevfusion-p150 (container)
5528e28 verified
Raw History Blame Contribute Delete
13.4 kB
# SPDX-License-Identifier: Apache-2.0
"""Host post-processing of BEVFusion-L with Autoware's semantics (research/bevfusion/SPEC.md section 5): the three
network outputs (``bbox_pred`` (10, K), ``score`` (K,), ``label_pred`` (K,): from the device readback or the CPU
reference) -> Autoware ``DetectedObjects``-equivalent detections.
Order of operations (``PKG/lib/postprocess/postprocess_kernel.cu:29-108,185-256``, ``circle_nms_kernel.cu:41-157``,
``PKG/src/bevfusion_node.cpp:310-322``):
1. :func:`decode_bevfusion` (``generateBoxes3D_kernel``, float32, every proposal): ``yaw_norm = sqrtf(sin^2 + cos^2)``
(rows 6, 7); ``score = 0`` unless ``yaw_norm >= yaw_norm_thresholds[label]``; ``x = bbox[0] * 8 * 0.17 +
(-122.4)``, ``y`` likewise (float32, left to right); the distance bin = the first ``i`` with ``x^2 + y^2 <
limit_i^2`` (none: score 0); ``score < thresholds[bin, label]`` -> 0; ``z = bbox[2]`` (gravity centre),
``length / width / height = expf(bbox[3:6])``, ``yaw = atan2f(sin, cos)``, ``vx, vy = bbox[8:10]``;
2. sort by descending score (cub radix ``SortPairsDescending``: stable, ties keep proposal order); nothing if the best
score is 0; circle NMS 0.5 m, class-agnostic, where a kept box also suppresses every later box of score 0 -- the
zero-score boxes all sort last and the first box is kept, so this equals dropping them before the NMS
(``ttaw.nms.circle_nms`` on the positive scores);
3. ``box3DToDetectedObject`` (``PKG/lib/ros_utils.cpp:30-61``): ``getSemanticType`` labels (CAR=1, TRUCK=2, BUS=3,
BICYCLE=6, PEDESTRIAN=7; TRAFFIC_CONE / BARRIER -> HAZARD, unused at v2.0), ``existence_probability = score``,
the **network yaw unchanged**, dimensions (length, width, height), ``orientation_availability`` SIGN_UNKNOWN for
car-like labels; the decoded velocity is not published;
4. IoU-BEV NMS (``perception_utils::IouBevNms::apply(objects)``, ``sort=false``; ``ttaw.nms.iou_bev_nms``);
5. the area class remapper of the weights repo (CAR -> TRUCK for 12.1-36 m^2, CAR / TRUCK / BUS -> TRAILER for
36-999.999 m^2; ``ttaw.nms.ClassRemapper``).
:data:`RUNTIME_PARAMS` are the per-request knobs (RT-host class, PLAN.md 0.4) with Autoware's defaults
(``bevfusion_lidar.param.yaml``). ``score_threshold`` sets every class and distance bin (the shipped yaml has 0.10
everywhere); the yaw-norm thresholds and distance bins stay the yaml's. numpy only.
"""
from __future__ import annotations
import math
from typing import Any, Dict, Mapping, Optional, Sequence, Tuple
import numpy as np
from ..reference.config import NODE_PARAMS, NUM_BOX_VALUES, BEVFusionConfig
from ..ttaw.decode import (AUTOWARE_LABELS, LABEL_IDS, SIGN_UNKNOWN, UNAVAILABLE, DecodedBoxes, DetectedObjects,
is_car_like)
from ..ttaw.nms import circle_nms, iou_bev_nms
from ..ttaw.outputs import Detections3D
__all__ = ["RUNTIME_PARAMS", "LABELS", "OUTPUT_NAMES", "BEVFusionPostprocessor", "decode_bevfusion",
"semantic_label", "to_detected_objects", "sort_stable_desc"]
LABELS = AUTOWARE_LABELS # output label_id = autoware_perception_msgs ObjectClassification value
OUTPUT_NAMES = ("bbox_pred", "score", "label_pred")
# name -> (type, min, max, default); defaults are Autoware's (bevfusion_lidar.param.yaml)
RUNTIME_PARAMS: Dict[str, Tuple[type, Any, Any, Any]] = {
# every class and distance bin; a score below it is dropped ('<', postprocess_kernel.cu:83); outside [0, 1) -> 0
"score_threshold": (float, 0.0, 1.0, NODE_PARAMS["min_confidence_score"]),
# strict '<' on the squared distance; <= 0 keeps 0.5 m (bevfusion_config.hpp:148-150)
"circle_nms_dist_threshold": (float, 0.0, 10.0, NODE_PARAMS["circle_nms_dist_threshold"]),
"iou_nms_threshold": (float, 0.0, 1.0, NODE_PARAMS["iou_nms_threshold"]),
"iou_nms_search_distance_2d": (float, 0.0, 200.0, NODE_PARAMS["iou_nms_search_distance_2d"]),
"remap_classes": (bool, None, None, True),
# not an Autoware knob (Autoware has no cap): keep the N best after NMS; None = all
"max_detections": (int, 1, None, None),
}
# PKG/lib/ros_utils.cpp:63-86 getSemanticType (HAZARD has no ObjectClassification value in this label table; the v2.0
# weights have no TRAFFIC_CONE / BARRIER class)
_SEMANTIC = {"CAR": "CAR", "TRUCK": "TRUCK", "BUS": "BUS", "TRAILER": "TRAILER", "MOTORCYCLE": "MOTORCYCLE",
"BICYCLE": "BICYCLE", "PEDESTRIAN": "PEDESTRIAN"}
def semantic_label(class_name: str) -> int:
"""``getSemanticType``: class name -> ObjectClassification label; anything else -> UNKNOWN."""
if class_name in ("TRAFFIC_CONE", "BARRIER"):
raise ValueError(f"{class_name} maps to HAZARD, which the v2.0 weights never produce (no label id here)")
return LABEL_IDS[_SEMANTIC.get(class_name, "UNKNOWN")]
def _outputs(raw: Mapping[str, Any]) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
box = np.asarray(raw["bbox_pred"], dtype=np.float32)
score = np.asarray(raw["score"], dtype=np.float32).reshape(-1)
label = np.asarray(raw["label_pred"]).reshape(-1)
if box.ndim == 3 and box.shape[0] == 1:
box = box[0]
if box.ndim != 2 or box.shape[0] != NUM_BOX_VALUES or box.shape[1] != score.size or label.size != score.size:
raise ValueError(f"expected bbox_pred (10, K), score (K,), label_pred (K,); got {box.shape}, {score.shape}, "
f"{label.shape}")
return box, score, label.astype(np.int64)
def decode_bevfusion(raw: Mapping[str, Any], cfg: BEVFusionConfig, *, score_threshold: Optional[float] = None
) -> DecodedBoxes:
"""``generateBoxes3D_kernel`` for every proposal -> ``ttaw.decode.DecodedBoxes`` in proposal order (``cell``
holds the proposal index; ``score`` is 0 for every proposal the kernel zeroes)."""
box, score_in, label = _outputs(raw)
K = score_in.size
f32 = np.float32
ncls = len(cfg.class_names)
if K and (label.min() < 0 or label.max() >= ncls):
raise ValueError(f"label_pred outside [0, {ncls})")
s, c = box[6], box[7]
yaw_norm = np.sqrt(s * s + c * c).astype(np.float32)
score = np.where(yaw_norm >= cfg.yaw_norm_thresholds[label], score_in, f32(0.0)).astype(np.float32)
k = f32(cfg.out_size_factor)
x = ((box[0] * k) * f32(cfg.voxel_size[0]) + f32(cfg.point_cloud_range[0])).astype(np.float32)
y = ((box[1] * k) * f32(cfg.voxel_size[1]) + f32(cfg.point_cloud_range[1])).astype(np.float32)
r2 = (x * x + y * y).astype(np.float32)
bins = cfg.distance_bins_sq
inside = r2[:, None] < bins[None, :]
has_bin = inside.any(axis=1)
b = np.argmax(inside, axis=1) # first bin with r2 < limit^2
thr = cfg.score_thresholds(score_threshold)[b, label]
score = np.where(has_bin & ~(score < thr), score, f32(0.0)).astype(np.float32)
with np.errstate(over="ignore"):
return DecodedBoxes(cell=np.arange(K, dtype=np.int64), label=label.astype(np.int32), score=score, x=x, y=y,
z=box[2].astype(np.float32), length=np.exp(box[3]).astype(np.float32),
width=np.exp(box[4]).astype(np.float32), height=np.exp(box[5]).astype(np.float32),
yaw=np.arctan2(s, c).astype(np.float32), vel_x=box[8].copy(), vel_y=box[9].copy())
def sort_stable_desc(boxes: DecodedBoxes) -> DecodedBoxes:
"""cub ``SortPairsDescending`` over the scores: a stable sort (ties keep proposal order)."""
return boxes.take(np.argsort(-boxes.score, kind="stable"))
def to_detected_objects(boxes: DecodedBoxes, class_names: Sequence[str]) -> DetectedObjects:
"""``box3DToDetectedObject`` of autoware_bevfusion for every row: no yaw conversion, no twist."""
table = np.array([semantic_label(n) for n in class_names], dtype=np.uint8)
lab = np.asarray(boxes.label, dtype=np.int64)
label = table[lab].astype(np.uint8)
orient = np.where(is_car_like(label), SIGN_UNKNOWN, UNAVAILABLE).astype(np.uint8)
return DetectedObjects(label=label, existence_probability=np.asarray(boxes.score, np.float32),
x=boxes.x.copy(), y=boxes.y.copy(), z=boxes.z.copy(), yaw=boxes.yaw.copy(),
length=boxes.length.copy(), width=boxes.width.copy(), height=boxes.height.copy(),
orientation_availability=orient, source_index=np.arange(len(boxes), dtype=np.int64),
label_before_remap=label.copy(),
extra={"proposal": np.asarray(boxes.cell, np.int64),
"velocity": np.stack([boxes.vel_x, boxes.vel_y], 1).astype(np.float32)})
class BEVFusionPostprocessor:
"""Stateless; ``params`` are validated ``RUNTIME_PARAMS`` values (missing keys take the defaults)."""
def __init__(self, config: BEVFusionConfig, *, nms: str = "numpy"):
if nms not in ("numpy", "numba"):
raise ValueError("nms must be 'numpy' or 'numba'")
self.config = config
self.remapper = config.remapper
# "numba" (OPT_PLAN H5, BEVFUSION_HOST_NMS): host/fast.circle_nms / iou_bev_nms, compiled twins with the same
# keep lists; the ttaw.nms numpy oracles stay the reference
self.nms = nms
if nms == "numba":
from . import fast
self._circle_nms, self._iou_bev_nms = fast.circle_nms, fast.iou_bev_nms
else:
self._circle_nms, self._iou_bev_nms = circle_nms, iou_bev_nms
def objects(self, raw: Mapping[str, Any], params: Optional[Mapping[str, Any]] = None
) -> Tuple[DetectedObjects, Dict[str, int]]:
p = {k: v[3] for k, v in RUNTIME_PARAMS.items()}
p.update(params or {})
cfg = self.config
decoded = decode_bevfusion(raw, cfg, score_threshold=p["score_threshold"])
boxes = sort_stable_desc(decoded)
n_pos = int(np.count_nonzero(boxes.score > 0))
if n_pos == 0: # highest score 0: no detections (postprocess_kernel.cu:209)
boxes = boxes.take(np.zeros(0, np.int64))
else:
boxes = boxes.take(np.arange(n_pos)) # score-0 boxes: suppressed by the first kept box
keep = self._circle_nms(boxes.x, boxes.y, cfg.sanitized_circle_nms(p["circle_nms_dist_threshold"]))
objs = to_detected_objects(boxes.take(keep), cfg.class_names)
n_circle = len(objs)
search, iou = float(p["iou_nms_search_distance_2d"]), float(p["iou_nms_threshold"])
if not (math.isfinite(search) and search >= 0.0 and math.isfinite(iou) and 0.0 <= iou <= 1.0):
raise ValueError("IouBevNms parameters out of range") # validate_params already refuses these
objs = objs.take(self._iou_bev_nms(objs.x, objs.y, objs.length, objs.width, objs.yaw, objs.label,
search_distance_2d=search, iou_threshold=iou))
if p["remap_classes"]:
objs.label = self.remapper.apply(objs.label, objs.length, objs.width)
counts = {"proposals": int(len(decoded)), "after_threshold": n_pos, "after_circle_nms": n_circle,
"after_iou_nms": int(len(objs))}
if p["max_detections"] is not None and len(objs) > int(p["max_detections"]):
objs = objs.take(np.arange(int(p["max_detections"])))
return objs, counts
def to_output(self, objs: DetectedObjects, *, model: str, frame_id: str = "base_link",
meta: Optional[Dict[str, Any]] = None) -> Detections3D:
"""``ttaw.outputs.Detections3D`` (the ``/predict`` body): boxes (x, y, z, length, width, height, yaw),
``existence_probability`` as the score, ObjectClassification label ids; ``meta`` gets the per-object
orientation availability, the pre-remap labels and the proposal index (aligned with the score-sorted
detections). The decoded velocity is not returned (Autoware does not publish it)."""
order = np.argsort(-objs.existence_probability, kind="stable") # already sorted: kept for alignment
objs = objs.take(order)
m = dict(meta or {})
m["orientation_availability"] = objs.orientation_availability.tolist()
m["label_before_remap"] = [LABELS[int(v)] for v in objs.label_before_remap]
m["proposal"] = objs.extra["proposal"].tolist()
return Detections3D(objs.boxes_xyzlwh_yaw(), objs.existence_probability, objs.label.astype(np.int32),
labels=LABELS, model=model, frame_id=frame_id, meta=m)
def empty(self, *, model: str, frame_id: str = "base_link", meta: Optional[Dict[str, Any]] = None) -> Detections3D:
"""The output of a frame Autoware skips (no voxel): no objects."""
m = dict(meta or {})
m.update({"orientation_availability": [], "label_before_remap": [], "proposal": []})
return Detections3D(np.zeros((0, 7), np.float32), np.zeros(0, np.float32), np.zeros(0, np.int32),
labels=LABELS, model=model, frame_id=frame_id, meta=m)
def __call__(self, raw: Mapping[str, Any], params: Optional[Mapping[str, Any]] = None, *, model: str,
frame_id: str = "base_link", meta: Optional[Dict[str, Any]] = None) -> Detections3D:
objs, counts = self.objects(raw, params)
return self.to_output(objs, model=model, frame_id=frame_id, meta={**(meta or {}), "counts": counts})