Download code/tt_centerpoint/reference/config.py from changh95/centerpoint-p150: direct link, hf CLI and curl.
- Browser
- Download file 15.5 kB
-
https://huggingface.co/changh95/centerpoint-p150/resolve/main/code/tt_centerpoint/reference/config.py
- Command line
-
hf download hf://changh95/centerpoint-p150/code/tt_centerpoint/reference/config.py
-
curl -L -o config.py https://huggingface.co/changh95/centerpoint-p150/resolve/main/code/tt_centerpoint/reference/config.py
15.5 kB
| # SPDX-License-Identifier: Apache-2.0 | |
| """The Autoware ``lidar_centerpoint`` parameters this port reproduces, and its compile-time constants. | |
| Sources (autoware_universe main ``9ceaccf``, ``perception/autoware_lidar_centerpoint`` = ``CP/``; weights | |
| ``AutowareFoundation/lidar_centerpoint@v4.1`` = commit ``494c8171``, research/centerpoint/SPEC.md section 2): | |
| - per variant, from the weights repo: ``<variant>/ml_package.param.yaml`` (class names, range, voxel size, | |
| ``downsample_factor`` 1 base / 2 tiny, ``max_voxel_size``, encoder features, thresholds) and | |
| ``<variant>/detection_class_remapper.param.yaml`` (the 8x8 area remapper matrices); | |
| - node-wide, :data:`COMMON_PARAMS` = ``CP/config/centerpoint_common.param.yaml`` (identical to the full-stack copy in | |
| autoware_perception_config, S:centerpoint:38); | |
| - hard-coded in the node: :data:`MAX_POINTS_PER_PILLAR`, :data:`ENCODER_OUT_FEATURES` (``centerpoint_config.hpp``). | |
| Every validation the node does on these files is repeated here (version >= v4.1, ascending distance bins, one | |
| yaw-norm threshold per class, thresholds outside [0, 1) -> 0, circle-NMS distance <= 0 -> 1.5 m). ``yaml`` is | |
| imported when a file is read, never at module import. | |
| """ | |
| from __future__ import annotations | |
| import re | |
| from dataclasses import dataclass, field, replace | |
| from pathlib import Path | |
| from typing import Any, Dict, Mapping, Optional, Tuple | |
| import numpy as np | |
| from ..ttaw.decode import CenterHeadDecodeConfig | |
| from ..ttaw.nms import ClassRemapper | |
| from ..ttaw.voxelize import PillarGridSpec | |
| __all__ = [ | |
| "VARIANTS", "DEFAULT_VARIANT", "COMMON_PARAMS", "MAX_POINTS_PER_PILLAR", "ENCODER_OUT_FEATURES", "SHUFFLE_SEED", | |
| "HEAD_NAMES", "ENCODER_ONNX", "HEAD_ONNX", "CLASS_NAMES", "CenterPointConfig", "variant_dir", | |
| ] | |
| VARIANTS = ("base", "tiny") # S:centerpoint:39-46 (sigma and short_range are out of scope) | |
| DEFAULT_VARIANT = "base" # Autoware's default LiDAR detector (S:centerpoint:31-37) | |
| MIN_VERSION = (4, 1) # CP/include/.../ml_package_version.hpp:24-25 | |
| # CP/config/centerpoint_common.param.yaml:1-19 | |
| COMMON_PARAMS: Dict[str, Any] = { | |
| "cloud_capacity": 2_000_000, | |
| "circle_nms_dist_threshold": 0.5, | |
| "iou_nms_search_distance_2d": 10.0, | |
| "iou_nms_threshold": 0.1, | |
| "world_frame_id": "map", | |
| "num_past_frames": 1, | |
| } | |
| MAX_POINTS_PER_PILLAR = 32 # CP/include/.../centerpoint_config.hpp:111; preprocess_kernel.cu:41 (COMPILE) | |
| ENCODER_OUT_FEATURES = 32 # centerpoint_config.hpp:127 (COMPILE) | |
| SHUFFLE_SEED = 0 # PLAN.md D1: fixed seeded permutation before the first-32 rule (S:centerpoint:389) | |
| DROP_ZERO_POINTS = True # (0, 0, 0) rows are missing returns of organized clouds (research reference rule) | |
| HEAD_NAMES = ("heatmap", "reg", "height", "dim", "rot", "vel") # output order, CP/lib/centerpoint_trt.cpp:137-150 | |
| # class_names of both v4.1 ml_packages (base, tiny): the names the per-class runtime parameters accept (validated | |
| # before the device runs); the decode itself always uses the yaml's own list (CenterPointConfig.class_names) | |
| CLASS_NAMES = ("CAR", "TRUCK", "BUS", "BICYCLE", "PEDESTRIAN") | |
| ENCODER_ONNX = "pts_voxel_encoder.onnx" # ml_package.param.yaml encoder_onnx_path | |
| HEAD_ONNX = "pts_backbone_neck_head.onnx" # ml_package.param.yaml head_onnx_path | |
| def variant_dir(weights_dir: Any, variant: str) -> Path: | |
| """``<weights_dir>/<variant>`` (the HF repo layout), or ``weights_dir`` itself when it already is a variant | |
| directory (holds ``ml_package.param.yaml``).""" | |
| root = Path(weights_dir) | |
| if (root / "ml_package.param.yaml").is_file(): | |
| return root | |
| d = root / variant | |
| if not (d / "ml_package.param.yaml").is_file(): | |
| raise FileNotFoundError(f"no {variant}/ml_package.param.yaml under {root}") | |
| return d | |
| def _ros_params(path: Path) -> Dict[str, Any]: | |
| import yaml | |
| with open(path) as f: | |
| doc = yaml.safe_load(f) | |
| try: | |
| return doc["/**"]["ros__parameters"] | |
| except (KeyError, TypeError): | |
| raise ValueError(f"{path}: not a ROS 2 parameter file (no /**: ros__parameters)") from None | |
| def _check_version(version: str) -> None: | |
| m = re.fullmatch(r"v?(\d+)\.(\d+)(?:\.\d+)?", str(version).strip()) | |
| if not m or (int(m.group(1)), int(m.group(2))) < MIN_VERSION or int(m.group(1)) != MIN_VERSION[0]: | |
| raise ValueError(f"ml_package version {version!r} is not supported (need v{MIN_VERSION[0]}.x >= " | |
| f"v{MIN_VERSION[0]}.{MIN_VERSION[1]})") | |
| class CenterPointConfig: | |
| """One variant's parameters (COMPILE values marked in PORT_LOG.md's parameter table).""" | |
| variant: str | |
| version: str | |
| class_names: Tuple[str, ...] | |
| point_feature_size: int | |
| max_voxel_size: int | |
| point_cloud_range: Tuple[float, ...] | |
| voxel_size: Tuple[float, ...] | |
| downsample_factor: int | |
| encoder_in_feature_size: int | |
| has_variance: bool | |
| has_twist: bool | |
| yaw_norm_thresholds: Tuple[float, ...] | |
| distance_bin_upper_limits: Tuple[float, ...] | |
| score_thresholds: np.ndarray # (bins, classes), [bin][class] as node.cpp:129-167 | |
| remap_lists: Tuple[tuple, tuple, tuple] = field(repr=False, default=((), (), ())) | |
| common: Mapping[str, Any] = field(default_factory=lambda: dict(COMMON_PARAMS)) | |
| model_dir: Optional[str] = None | |
| # ---- construction -------------------------------------------------------------------------------------- | |
| def from_model_dir(cls, model_dir: Any, variant: Optional[str] = None, | |
| common: Optional[Mapping[str, Any]] = None) -> "CenterPointConfig": | |
| """Read ``ml_package.param.yaml`` and ``detection_class_remapper.param.yaml`` of a variant directory | |
| (``<weights>/base`` or ``<weights>/tiny``).""" | |
| d = Path(model_dir) | |
| p = _ros_params(d / "ml_package.param.yaml") | |
| _check_version(p.get("version", "")) | |
| mp = p["model_params"] | |
| names = tuple(mp["class_names"]) | |
| dst = mp["detection_score_thresholds"] | |
| bins = tuple(float(v) for v in dst["distance_bin_upper_limits"]) | |
| scores = dst["min_confidence_scores"] | |
| missing = [c for c in names if c not in scores] | |
| if missing: | |
| raise ValueError(f"min_confidence_scores lacks {missing}") | |
| for c in names: | |
| if len(scores[c]) != len(bins): | |
| raise ValueError(f"min_confidence_scores.{c} must have one value per distance bin") | |
| thr = np.array([[float(scores[c][b]) for c in names] for b in range(len(bins))], dtype=np.float32) | |
| q = _ros_params(d / str(p.get("class_remapper_param_path", "detection_class_remapper.param.yaml"))) | |
| remap = (tuple(int(v) for v in q["allow_remapping_by_area_matrix"]), | |
| tuple(float(v) for v in q["min_area_matrix"]), tuple(float(v) for v in q["max_area_matrix"])) | |
| name = variant or d.name | |
| cfg = cls(variant=name, version=str(p.get("version")), class_names=names, | |
| point_feature_size=int(mp["point_feature_size"]), max_voxel_size=int(mp["max_voxel_size"]), | |
| point_cloud_range=tuple(float(v) for v in mp["point_cloud_range"]), | |
| voxel_size=tuple(float(v) for v in mp["voxel_size"]), | |
| downsample_factor=int(mp["downsample_factor"]), | |
| encoder_in_feature_size=int(mp["encoder_in_feature_size"]), has_variance=bool(mp["has_variance"]), | |
| has_twist=bool(mp["has_twist"]), | |
| yaw_norm_thresholds=tuple(float(v) for v in mp["yaw_norm_thresholds"]), | |
| distance_bin_upper_limits=bins, score_thresholds=thr, remap_lists=remap, | |
| common={**COMMON_PARAMS, **dict(common or {})}, model_dir=str(d)) | |
| cfg.validate() | |
| return cfg | |
| def from_weights(cls, weights_dir: Any, variant: str = DEFAULT_VARIANT, | |
| common: Optional[Mapping[str, Any]] = None) -> "CenterPointConfig": | |
| if variant not in VARIANTS: | |
| raise ValueError(f"variant={variant!r}: expected one of {VARIANTS}") | |
| return cls.from_model_dir(variant_dir(weights_dir, variant), variant, common) | |
| def validate(self) -> None: | |
| if len(self.point_cloud_range) != 6 or len(self.voxel_size) != 3: | |
| raise ValueError("point_cloud_range needs 6 values and voxel_size 3") | |
| if self.point_feature_size not in (4, 5): | |
| raise ValueError("point_feature_size must be 4 (x, y, z, time_lag) or 5 (+ intensity)") | |
| if self.encoder_in_feature_size not in (9, 10, 11): | |
| raise ValueError("encoder_in_feature_size must be 9, 10 or 11") | |
| if self.has_variance: | |
| raise ValueError("has_variance (CenterPoint-sigma) is out of scope for this port") | |
| if self.grid_x % self.downsample_factor or self.grid_y % self.downsample_factor: | |
| raise ValueError("grid size is not divisible by downsample_factor") | |
| self.decode_config() # bins ascending, one yaw threshold per class, threshold shape | |
| # ---- derived values ------------------------------------------------------------------------------------ | |
| def grid_spec(self) -> PillarGridSpec: | |
| r = self.point_cloud_range | |
| return PillarGridSpec(range_min=tuple(r[:3]), range_max=tuple(r[3:]), voxel_size=tuple(self.voxel_size), | |
| max_points_per_pillar=MAX_POINTS_PER_PILLAR, max_pillars=self.max_voxel_size, | |
| order="flipped_x") | |
| def grid_x(self) -> int: | |
| return self.grid_spec.grid_x | |
| def grid_y(self) -> int: | |
| return self.grid_spec.grid_y | |
| def down_grid_x(self) -> int: | |
| return self.grid_x // self.downsample_factor | |
| def down_grid_y(self) -> int: | |
| return self.grid_y // self.downsample_factor | |
| def head_channels(self) -> Dict[str, int]: | |
| """Output channels per head (``centerpoint_config.hpp:58-65``; sigma would double the regressions).""" | |
| return {"heatmap": len(self.class_names), "reg": 2, "height": 1, "dim": 3, "rot": 2, "vel": 2} | |
| def circle_nms_dist_threshold(self) -> float: | |
| """``centerpoint_config.hpp:83-85,139``: values <= 0 fall back to 1.5 m.""" | |
| v = float(self.common["circle_nms_dist_threshold"]) | |
| return v if v > 0 else 1.5 | |
| def remapper(self) -> ClassRemapper: | |
| return ClassRemapper.from_lists(*self.remap_lists) | |
| def decode_config(self, score_threshold: Optional[float] = None, *, | |
| score_thresholds: Optional[Mapping[str, Any]] = None, | |
| distance_bin_upper_limits: Optional[Any] = None, | |
| yaw_norm_thresholds: Optional[Mapping[str, float]] = None) -> CenterHeadDecodeConfig: | |
| """The decoder parameters, with the runtime overrides of the RT-host knobs (PLAN.md 2.3; all None = the | |
| ml_package values, the exact pre-knob path): | |
| - ``score_threshold``: one value for every class and distance bin; | |
| - ``score_thresholds``: per class name, on top of that: a number (every bin) or one value per distance bin; | |
| - ``distance_bin_upper_limits``: the bin limits (ascending, as many as the ml_package has); | |
| - ``yaw_norm_thresholds``: per class name, the rotation-head norm gate. | |
| Thresholds outside [0, 1) are coerced to 0 as Autoware does (``CenterHeadDecodeConfig.create``); an unknown | |
| class name, a wrong number of values or descending bins raise ``ValueError``.""" | |
| cfg = CenterHeadDecodeConfig.create( | |
| class_names=self.class_names, voxel_size_xy=self.voxel_size[:2], range_min_xy=self.point_cloud_range[:2], | |
| downsample_factor=self.downsample_factor, distance_bin_upper_limits=self.distance_bin_upper_limits, | |
| score_thresholds=self.score_thresholds, yaw_norm_thresholds=self.yaw_norm_thresholds, | |
| has_variance=self.has_variance, has_twist=self.has_twist) | |
| cfg = cfg.with_score_threshold(score_threshold) | |
| if not score_thresholds and distance_bin_upper_limits is None and not yaw_norm_thresholds: | |
| return cfg | |
| names = list(self.class_names) | |
| def index(name: str) -> int: | |
| if name not in names: | |
| raise ValueError(f"unknown class {name!r}; this model's classes are {names}") | |
| return names.index(name) | |
| bins = cfg.distance_bin_upper_limits | |
| if distance_bin_upper_limits is not None: | |
| bins = tuple(float(v) for v in distance_bin_upper_limits) | |
| if len(bins) != len(cfg.distance_bin_upper_limits): | |
| raise ValueError(f"distance_bin_upper_limits needs {len(cfg.distance_bin_upper_limits)} values (the " | |
| f"ml_package's bins), got {len(bins)}") | |
| thr = np.array(cfg.score_thresholds, dtype=np.float32) # (bins, classes) | |
| for name, value in (score_thresholds or {}).items(): | |
| v = np.asarray(value, dtype=np.float32) | |
| if v.ndim == 0: | |
| thr[:, index(name)] = v | |
| elif v.shape == (thr.shape[0],): | |
| thr[:, index(name)] = v | |
| else: | |
| raise ValueError(f"score_thresholds[{name!r}]: one number or {thr.shape[0]} values (one per distance " | |
| f"bin), got {v.shape[0] if v.ndim == 1 else v.shape}") | |
| yaw = np.array(cfg.yaw_norm_thresholds, dtype=np.float64) | |
| for name, value in (yaw_norm_thresholds or {}).items(): | |
| yaw[index(name)] = float(value) | |
| return CenterHeadDecodeConfig.create( | |
| class_names=self.class_names, voxel_size_xy=self.voxel_size[:2], range_min_xy=self.point_cloud_range[:2], | |
| downsample_factor=self.downsample_factor, distance_bin_upper_limits=bins, score_thresholds=thr, | |
| yaw_norm_thresholds=yaw, has_variance=self.has_variance, has_twist=self.has_twist) | |
| def z_range(self) -> Tuple[float, float]: | |
| """The z filter of ``point_cloud_range`` ([z_min, z_max) in base_link; the runtime ``z_range`` may narrow it).""" | |
| return float(self.point_cloud_range[2]), float(self.point_cloud_range[5]) | |
| def with_common(self, **overrides: Any) -> "CenterPointConfig": | |
| return replace(self, common={**dict(self.common), **overrides}) | |
| def describe(self) -> Dict[str, Any]: | |
| """JSON-able summary (``model.info``, golden metadata).""" | |
| return {"variant": self.variant, "version": self.version, "class_names": list(self.class_names), | |
| "point_cloud_range": list(self.point_cloud_range), "voxel_size": list(self.voxel_size), | |
| "grid": [self.grid_x, self.grid_y], "head_grid": [self.down_grid_x, self.down_grid_y], | |
| "downsample_factor": self.downsample_factor, "max_voxel_size": self.max_voxel_size, | |
| "max_points_per_pillar": MAX_POINTS_PER_PILLAR, "encoder_in_feature_size": self.encoder_in_feature_size, | |
| "point_feature_size": self.point_feature_size, "has_twist": self.has_twist, | |
| "yaw_norm_thresholds": list(self.yaw_norm_thresholds), | |
| "distance_bin_upper_limits": list(self.distance_bin_upper_limits), | |
| "score_thresholds": self.score_thresholds.tolist(), "shuffle_seed": SHUFFLE_SEED, | |
| "common": {k: v for k, v in self.common.items()}} | |