Download code/tt_meteor2/host/postprocess.py from changh95/METEOR-2-p150: direct link, hf CLI and curl.
- Browser
- Download file 7.25 kB
-
https://huggingface.co/changh95/METEOR-2-p150/resolve/main/code/tt_meteor2/host/postprocess.py
- Command line
-
hf download hf://changh95/METEOR-2-p150/code/tt_meteor2/host/postprocess.py
-
curl -L -o postprocess.py https://huggingface.co/changh95/METEOR-2-p150/resolve/main/code/tt_meteor2/host/postprocess.py
7.25 kB
| # SPDX-License-Identifier: Apache-2.0 | |
| """Host decoding of METEOR 2's BEV outputs (numpy, float32 / float64), shared by the device path and the CPU reference. | |
| Boxes (model card, ``param.yaml``): a box is a 5 x 5 local maximum of sigmoid(hm) at or above ``score`` (0.30), at | |
| most ``topk`` (64) per class, highest first; centre x = 80 - (row + reg0) 0.4, y = 50 - (col + reg1) 0.4 (ego frame, | |
| x forward, y left), size exp(reg2), exp(reg3), yaw = 0.5 atan2(reg4, reg5) (sin 2y / cos 2y: the box axis, front and | |
| back are not resolved), plus sigmoid(stationary) and the 3-mode 3 s future of ``traj`` (3 x 6 x 2 offsets in metres | |
| in the ego frame + 3 mode logits). Lanes: argmax of the 9 classes on 800 x 500 at 0.2 m. Occupancy: per (z, row, | |
| col) the most likely non-free class and 1 - p(free); occupied when 1 - p(free) > 0.55 (vegetation, building > 0.92). | |
| """ | |
| from __future__ import annotations | |
| from dataclasses import dataclass | |
| from typing import Dict, List, Optional, Tuple | |
| import numpy as np | |
| from ..reference import config as C | |
| __all__ = ["BOX_CLASSES", "LANE_CLASSES", "OCC_CLASSES", "find_peaks", "decode_rows", "Boxes", "occ_occupied", | |
| "sigmoid", "max5"] | |
| BOX_CLASSES = ("vehicle", "pedestrian") | |
| LANE_CLASSES = None # names are not published in v1.0's param.yaml; ids 0..8 | |
| OCC_CLASSES = ("free", "obstacle", "vehicle", "two_wheeler", "pedestrian", "road", "sidewalk", "vegetation", | |
| "building", "pole_sign") | |
| BOX_RES, BOX_X0, BOX_Y0 = 0.4, 80.0, 50.0 | |
| SCORE, TOPK = 0.30, 64 | |
| OCC_GATE, OCC_GATE_STRICT, OCC_STRICT = 0.55, 0.92, (7, 8) | |
| def sigmoid(x): | |
| x = np.asarray(x, np.float64) | |
| return 1.0 / (1.0 + np.exp(-x)) | |
| def max5(a: np.ndarray) -> np.ndarray: | |
| """5 x 5 max filter of a 2D array (borders padded with -inf), as two separable 5-tap passes (max is separable: | |
| the same values as the 25-shift form).""" | |
| h, w = a.shape | |
| p = np.full((h, w + 4), -np.inf) | |
| p[:, 2:-2] = a | |
| row = p[:, 0:w].copy() | |
| for dx in range(1, 5): | |
| np.maximum(row, p[:, dx:dx + w], out=row) | |
| q = np.full((h + 4, w), -np.inf) | |
| q[2:-2] = row | |
| out = q[0:h].copy() | |
| for dy in range(1, 5): | |
| np.maximum(out, q[dy:dy + h], out=out) | |
| return out | |
| def find_peaks(hm: np.ndarray, score: float = SCORE, topk: int = TOPK) -> List[Tuple[int, int, float]]: | |
| """hm logits [400, 250, 2] (or [2, 400, 250] with ``channels_first``-shaped input detected) -> [(class, cell, | |
| score)] per class highest first (stable order on ties, as the CPU reference).""" | |
| hm = np.asarray(hm, np.float32) | |
| if hm.shape[-1] == 2 and hm.shape[0] != 2: | |
| hm = np.moveaxis(hm.reshape(C.BEV_H, C.BEV_W, 2), -1, 0) | |
| hm = hm.reshape(2, C.BEV_H, C.BEV_W) | |
| out = [] | |
| for c in range(2): | |
| s = sigmoid(hm[c]) | |
| peak = (s >= max5(s)) & (s >= score) | |
| r, q = np.nonzero(peak) | |
| order = np.argsort(-s[r, q], kind="stable")[:topk] | |
| out += [(c, int(r[i]) * C.BEV_W + int(q[i]), float(s[r[i], q[i]])) for i in order] | |
| return out | |
| class Boxes: | |
| """N boxes: ``cls`` [N] int, ``score`` [N], ``xy`` [N, 2] (ego, m), ``lw`` [N, 2], ``yaw`` [N] (rad, box axis), | |
| ``p_stationary`` [N], ``risk`` [N] (logit at the centre cell), ``futures`` [N, 3, 6, 2] (m, ego frame), | |
| ``mode_logits`` [N, 3], ``cell`` [N] (BEV cell index).""" | |
| cls: np.ndarray | |
| score: np.ndarray | |
| xy: np.ndarray | |
| lw: np.ndarray | |
| yaw: np.ndarray | |
| p_stationary: np.ndarray | |
| risk: np.ndarray | |
| futures: np.ndarray | |
| mode_logits: np.ndarray | |
| cell: np.ndarray | |
| def __len__(self) -> int: | |
| return int(self.cls.size) | |
| def as_rows(self) -> np.ndarray: | |
| """[N, 8]: class, score, x, y, length, width, yaw, p_stationary (tt-autoware's ``meteor2_lib`` layout).""" | |
| return np.concatenate([self.cls[:, None], self.score[:, None], self.xy, self.lw, self.yaw[:, None], | |
| self.p_stationary[:, None]], 1).astype(np.float32) | |
| def decode_rows(peaks: List[Tuple[int, int, float]], rows: np.ndarray) -> Boxes: | |
| """peaks from :func:`find_peaks`, rows [N, >= 49] fp32 in ``tt.model.ROW_COLUMNS`` order (hm 0:2, reg 2:8, | |
| stationary 8, risk 9, traj 10:49) of the same cells -> :class:`Boxes`.""" | |
| n = len(peaks) | |
| rows = np.asarray(rows, np.float64).reshape(n, -1) | |
| cls = np.array([p[0] for p in peaks], np.int64) | |
| cell = np.array([p[1] for p in peaks], np.int64) | |
| score = np.array([p[2] for p in peaks], np.float64) | |
| r, q = cell // C.BEV_W, cell % C.BEV_W | |
| reg = rows[:, 2:8] | |
| x = BOX_X0 - (r + reg[:, 0]) * BOX_RES | |
| y = BOX_Y0 - (q + reg[:, 1]) * BOX_RES | |
| yaw = 0.5 * np.arctan2(reg[:, 4], reg[:, 5]) | |
| traj = rows[:, 10:49] | |
| f = np.float32 | |
| return Boxes(cls, score.astype(f), np.stack([x, y], 1).astype(f), np.exp(reg[:, 2:4]).astype(f), | |
| yaw.astype(f), sigmoid(rows[:, 8]).astype(f), rows[:, 9].astype(f), | |
| traj[:, :36].reshape(n, 3, 6, 2).astype(f), traj[:, 36:39].astype(f), cell) | |
| def decode_dense(hm: np.ndarray, reg: np.ndarray, stationary: np.ndarray, risk: np.ndarray, traj: np.ndarray, | |
| score: float = SCORE, topk: int = TOPK) -> Boxes: | |
| """The same decoding from the dense graph outputs (NCHW [1, C, 400, 250]: the CPU reference / ONNX).""" | |
| peaks = find_peaks(np.asarray(hm).reshape(2, C.BEV_H, C.BEV_W), score, topk) | |
| dense = np.concatenate([np.asarray(a, np.float32).reshape(-1, C.BEV_H * C.BEV_W) | |
| for a in (hm, reg, stationary, risk, traj)], 0).T # [100000, 49] | |
| return decode_rows(peaks, dense[[p[1] for p in peaks]]) | |
| def occ_occupied(cls: np.ndarray, p_occ: np.ndarray) -> np.ndarray: | |
| """Display mask per (cell, z): 1 - p(free) above 0.55, above 0.92 for vegetation / building.""" | |
| cls = np.asarray(cls) | |
| thr = np.where(np.isin(cls, OCC_STRICT), OCC_GATE_STRICT, OCC_GATE) | |
| return np.asarray(p_occ) > thr | |
| def occ_from_logits(occ_logit: np.ndarray) -> Tuple[np.ndarray, np.ndarray]: | |
| """[1, 10, 16, 200, 200] logits (CPU reference) -> (most likely non-free class, 1 - p(free)), [16, 200, 200].""" | |
| lg = np.asarray(occ_logit, np.float64)[0] | |
| m = lg.max(0) | |
| e = np.exp(lg - m) | |
| p_free = e[0] / e.sum(0) | |
| return lg[1:].argmax(0) + 1, 1.0 - p_free | |
| def match_boxes(a: Boxes, b: Boxes, radius: Tuple[float, float] = (3.0, 1.5)) -> Dict[str, float]: | |
| """Greedy match per class, highest score of ``a`` first, centres within ``radius`` (vehicle, pedestrian).""" | |
| matched, dist = 0, [] | |
| for c, rad in enumerate(radius): | |
| ia = np.nonzero(a.cls == c)[0] | |
| ib = np.nonzero(b.cls == c)[0] | |
| free = np.ones(ib.size, bool) | |
| for i in ia[np.argsort(-a.score[ia], kind="stable")]: | |
| if not free.any(): | |
| break | |
| d = np.linalg.norm(b.xy[ib] - a.xy[i], axis=1) | |
| d[~free] = np.inf | |
| j = int(np.argmin(d)) | |
| if d[j] <= rad: | |
| free[j] = False | |
| matched += 1 | |
| dist.append(float(d[j])) | |
| return {"matched": matched, "n_a": len(a), "n_b": len(b), "recall_b": matched / max(len(b), 1), | |
| "precision_a": matched / max(len(a), 1), "centre_m": float(np.mean(dist)) if dist else float("nan")} | |