Download code/tt_autoe2e/host/geometry.py from changh95/auto_e2e-p150: direct link, hf CLI and curl.
- Browser
- Download file 8.58 kB
-
https://huggingface.co/changh95/auto_e2e-p150/resolve/main/code/tt_autoe2e/host/geometry.py
- Command line
-
hf download hf://changh95/auto_e2e-p150/code/tt_autoe2e/host/geometry.py
-
curl -L -o geometry.py https://huggingface.co/changh95/auto_e2e-p150/resolve/main/code/tt_autoe2e/host/geometry.py
8.58 kB
| # SPDX-License-Identifier: Apache-2.0 | |
| """Host geometry of one BEV frame for the device encoder: everything that depends only on the 3 x 4 matrices. | |
| The rebatched cross-attention runs on ``R_CAP`` rows: per camera the BEV cells it sees (any of the 4 pillar points | |
| visible: upstream's ``visible``), in ascending cell order, each camera's segment padded to a multiple of 32 rows, | |
| the segments back to back, padding rows after the last one. Per frame the host builds: | |
| - ``sca_index`` ``[1, R_CAP]`` uint32: the cell of each row (``Q``, the zero row of the gather table, on padding); | |
| - ``base`` ``[R_CAP, 64]`` float32: per level l and point p (anchor ``p % 4``) the anchor's pixel position in Q16.16 | |
| units, ``(uv * size_l - 0.5) * 2^16`` in columns ``l * 16 + 2p + (x, y)`` (the level's columns of the merged | |
| sampling projection; padding rows far outside every map, so they sample zeros); | |
| - ``seg`` ``[1, 1, 1, 16]`` uint32: the cumulative block ends of the camera segments (the kernel's runtime table); | |
| - ``gather`` ``[K, Q]`` uint32: per cell the rows of the cameras that see it (``R_CAP``, the zero row, when fewer than | |
| K cameras do): the scatter-add over cameras as K gathers; | |
| - ``scale`` ``[Q, 1]`` float32: ``1 / max(count, 1)``; ``observed`` ``[Q, 1]``: 1 where any camera sees the cell. | |
| Positions come from upstream's float32 ``uv`` (``reference/port_form.reference_points``). | |
| """ | |
| from __future__ import annotations | |
| from dataclasses import dataclass | |
| from typing import List, Sequence, Tuple | |
| import numpy as np | |
| from ..reference.port_form import PILLARS, POINTS, LEVELS, Q, reference_points | |
| R_CAP = 98_304 # rows (3072 blocks of 32): ~88.6k visible rows per KITScenes frame + padding | |
| K_CAMS = 3 # cameras per cell the scatter supports (KITScenes: at most 2) | |
| FAR = -float(1 << 27) # Q16.16 of pixel -2048: all four corners outside any map | |
| def level_sizes(image: int) -> List[Tuple[int, int]]: | |
| """FPN level (h, w) of a square ``image`` input: strides 8, 16, 32, 64.""" | |
| return [(image // s, image // s) for s in (8, 16, 32, 64)] | |
| class FrameGeometry: | |
| sca_index: np.ndarray | |
| base: np.ndarray | |
| seg: np.ndarray | |
| seg_rows: List[int] | |
| gather: np.ndarray | |
| scale: np.ndarray | |
| observed: np.ndarray | |
| visible_rows: List[int] | |
| def frame_geometry(P: np.ndarray, image: int = 512, *, r_cap: int = R_CAP, k_cams: int = K_CAMS) -> FrameGeometry: | |
| """``P`` ``[V, 3, 4]`` (ego -> pixels of the ``image`` x ``image`` model input) -> :class:`FrameGeometry`. | |
| Vectorized over the cameras' rows in float32: the level sizes are powers of two, so ``uv * size`` is exact and | |
| ``(uv * size - 0.5) * 2^16`` rounds once, like the float64 computation cast to float32 (``tests/host_geometry`` | |
| checks the two bit for bit).""" | |
| import torch | |
| uv, mask = reference_points(torch.as_tensor(np.asarray(P, np.float32)), image) | |
| uv = uv.numpy() # [V, Q, 4, 2] float32 | |
| vis = mask.numpy().any(-1) # [V, Q] | |
| V = vis.shape[0] | |
| if V > 8: | |
| raise ValueError("frame_geometry: at most 8 cameras") | |
| rows = [np.flatnonzero(vis[v]) for v in range(V)] | |
| counts = [len(r) for r in rows] | |
| seg_rows = [int(-(-n // 32) * 32) for n in counts] | |
| total = sum(seg_rows) | |
| if total > r_cap: | |
| raise ValueError(f"frame_geometry: {total} rebatched rows exceed the capacity {r_cap}") | |
| sizes = level_sizes(image) | |
| wh = np.array([[w, h] for h, w in sizes], np.float32) # [L, 2] | |
| if any(int(x) & (int(x) - 1) for x in wh.ravel()): | |
| raise ValueError(f"frame_geometry: level sizes {sizes} are not powers of two") | |
| starts = np.concatenate([[0], np.cumsum(seg_rows)[:-1]]).astype(np.int64) | |
| cam = np.repeat(np.arange(V), counts) | |
| cell = np.concatenate(rows) if V else np.zeros(0, np.int64) | |
| dst = np.concatenate([s + np.arange(n) for s, n in zip(starts, counts)]) if V else np.zeros(0, np.int64) | |
| a = uv[cam, cell][:, np.arange(POINTS) % PILLARS] # [N, 8, 2] | |
| blk = (a[:, None] * wh[None, :, None, :] - np.float32(0.5)) * np.float32(65536.0) # [N, L, 8, 2] | |
| base = np.full((r_cap, LEVELS * 16), FAR, np.float32) | |
| base[dst] = blk.reshape(len(dst), LEVELS * 16) | |
| sca_index = np.full((1, r_cap), Q, np.uint32) | |
| sca_index[0, dst] = cell | |
| cams_of = np.zeros(Q, np.int64) | |
| gather = np.full((k_cams, Q), r_cap, np.uint32) | |
| ends = np.zeros((1, 1, 1, 16), np.uint32) | |
| for v, r in enumerate(rows): | |
| slot = cams_of[r] | |
| if len(r) and slot.max() >= k_cams: | |
| raise ValueError(f"frame_geometry: a cell is seen by more than {k_cams} cameras") | |
| gather[slot, r] = np.arange(starts[v], starts[v] + len(r), dtype=np.uint32) | |
| cams_of[r] += 1 | |
| ends[0, 0, 0, v] = (starts[v] + seg_rows[v]) // 32 | |
| ends[0, 0, 0, V:8] = r_cap // 32 | |
| # the last segment owns the padding blocks after it (its rows there are padding: cell Q, FAR positions) | |
| ends[0, 0, 0, V - 1] = r_cap // 32 | |
| cnt = cams_of.astype(np.float32) | |
| scale = (1.0 / np.maximum(cnt, 1.0)).reshape(Q, 1).astype(np.float32) | |
| observed = (cnt > 0).astype(np.float32).reshape(Q, 1) | |
| return FrameGeometry(sca_index, base, ends, seg_rows, gather, scale, observed, counts) | |
| CM_SLOTS = 2 # cameras per cell of the cell-major cross-attention (KITScenes / the synthetic rig: at most 2) | |
| class CmGeometry: | |
| """The cell-major cross-attention's per-frame geometry (``tt/msda_cm.py``): ``table`` ``[Q, 32]`` int32 (per slot | |
| k the 4 anchors as ``round(uv * 2^(16 + smax))`` in columns ``8 k + 2 a + (x, y)``, the camera in ``16 + k`` (-1: | |
| none), the count in 18), ``observed`` ``[Q, 1]`` float32 (1 where a camera sees the cell), ``counts`` per camera.""" | |
| table: np.ndarray | |
| observed: np.ndarray | |
| visible_rows: List[int] | |
| def cm_geometry(P: np.ndarray, image: int = 512, *, slots: int = CM_SLOTS) -> CmGeometry: | |
| """``P`` ``[V, 3, 4]`` -> :class:`CmGeometry`. Slot k of a cell is its k-th visible camera (ascending camera order, | |
| the order of upstream's sum over the cameras). Anchors far outside are clamped to |uv| <= 64 (still outside every | |
| map: their points read nothing). Raises if a cell is seen by more than ``slots`` cameras (the rebatched path | |
| handles up to ``K_CAMS``).""" | |
| import torch | |
| uv, mask = reference_points(torch.as_tensor(np.asarray(P, np.float32)), image) | |
| uv = uv.numpy() # [V, Q, 4, 2] float32 | |
| vis = mask.numpy().any(-1) # [V, Q] | |
| cnt = vis.sum(0) | |
| if cnt.max(initial=0) > slots: | |
| raise ValueError(f"cm_geometry: a cell is seen by {int(cnt.max())} cameras (> {slots} slots)") | |
| smax = int(round(np.log2(level_sizes(image)[0][1]))) | |
| scale = float(1 << (16 + smax)) | |
| table = np.zeros((Q, 32), np.int32) | |
| table[:, 16:16 + slots] = -1 | |
| slot = np.cumsum(vis, axis=0) - 1 # [V, Q]: the slot of a visible (camera, cell) | |
| for v in range(vis.shape[0]): | |
| cells = np.flatnonzero(vis[v]) | |
| if not len(cells): | |
| continue | |
| u = np.round(np.clip(uv[v, cells].astype(np.float64), -64.0, 64.0) * scale).astype(np.int64) # [n, 4, 2] | |
| k = slot[v, cells] | |
| for s in range(slots): | |
| sel = k == s | |
| table[cells[sel], 8 * s:8 * s + 8] = u[sel].reshape(-1, 8).astype(np.int32) | |
| table[cells[sel], 16 + s] = v | |
| table[:, 18] = cnt | |
| observed = (cnt > 0).astype(np.float32).reshape(Q, 1) | |
| return CmGeometry(table, observed, [int(x) for x in vis.sum(1)]) | |
| def use_cm() -> bool: | |
| """The BEV frames' cross-attention form: cell-major (``tt/msda_cm.py``, default) or rebatched (``AE_CM=0``).""" | |
| import os | |
| return os.environ.get("AE_CM", "1") != "0" | |
| def bev_geometry(P: np.ndarray, image: int = 512): | |
| """The geometry of one BEV frame for the encoder's form: :class:`CmGeometry` (cell-major) or | |
| :class:`FrameGeometry` (rebatched).""" | |
| return cm_geometry(P, image) if use_cm() else frame_geometry(P, image) | |
| def tsa_base() -> np.ndarray: | |
| """``[Q, 128]`` float32 Q16.16: the t1 self-attention's reference (the cell centre) in pixels of the 300 x 200 | |
| value map, ``x = column``, ``y = row``, for the 8 points of the 16 head blocks (columns ``j * 8 + 2p + (x, y)``).""" | |
| from ..reference.port_form import BEV_H, BEV_W | |
| r, c = np.divmod(np.arange(Q), BEV_W) | |
| xy = np.stack([c, r], -1).astype(np.float64) * 65536.0 # [Q, 2] | |
| return np.tile(xy, (1, 64)).astype(np.float32) | |