File size: 4,303 Bytes
7b01b36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# SPDX-License-Identifier: Apache-2.0
"""``host.geometry.frame_geometry`` (vectorized float32) against the original per-camera float64 loop, bit for bit,
on the golden sample's 8 frames and its 1024 px front, plus timing (host only, no device).

    bin/devrun --no-device python -m tt_autoe2e.tests.host_geometry
"""
from __future__ import annotations

import glob
import json
import time

import numpy as np

from ..host import geometry as G
from ..reference.port_form import LEVELS, PILLARS, POINTS, Q, reference_points


def frame_geometry_loop(P: np.ndarray, image: int = 512, *, r_cap: int = G.R_CAP, k_cams: int = G.K_CAMS) -> G.FrameGeometry:
    """``P`` ``[V, 3, 4]`` (ego -> pixels of the ``image`` x ``image`` model input) -> :class:`FrameGeometry`."""
    import torch

    uv, mask = reference_points(torch.as_tensor(np.asarray(P, np.float32)), image)
    uv = uv.numpy().astype(np.float64)                     # [V, Q, 4, 2]
    vis = mask.numpy().any(-1)                             # [V, Q]
    V = vis.shape[0]
    rows = [np.nonzero(vis[v])[0] for v in range(V)]
    seg_rows = [int(-(-len(r) // 32) * 32) for r in rows]
    total = sum(seg_rows)
    if total > r_cap:
        raise ValueError(f"frame_geometry: {total} rebatched rows exceed the capacity {r_cap}")
    if V > 8:
        raise ValueError("frame_geometry: at most 8 cameras")
    sca_index = np.full((1, r_cap), Q, np.uint32)
    base = np.full((r_cap, LEVELS * 16), G.FAR, np.float32)
    cams_of = np.zeros(Q, np.int64)
    gather = np.full((k_cams, Q), r_cap, np.uint32)
    anchors = np.arange(POINTS) % PILLARS
    sizes = G.level_sizes(image)
    start = 0
    ends = np.zeros((1, 1, 1, 16), np.uint32)
    for v, r in enumerate(rows):
        n = len(r)
        sca_index[0, start:start + n] = r
        a = uv[v, r][:, anchors]                           # [n, 8, 2]
        for lvl, (h, w) in enumerate(sizes):
            px = (a[..., 0] * w - 0.5) * 65536.0
            py = (a[..., 1] * h - 0.5) * 65536.0
            blk = np.stack([px, py], -1).reshape(n, 16)
            base[start:start + n, lvl * 16:(lvl + 1) * 16] = blk.astype(np.float32)
        slot = cams_of[r]
        if n 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(start, start + n, dtype=np.uint32)
        cams_of[r] += 1
        start += seg_rows[v]
        ends[0, 0, 0, v] = start // 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 G.FrameGeometry(sca_index, base, ends, seg_rows, gather, scale, observed, [int(len(r)) for r in rows])



def main() -> int:
    g = np.load(glob.glob("/ae2e/ref/autoe2e_kitscenes_epoch5_*f000045.npz")[0])
    cases = [(g["camera_history_projection_matrix"][0, k], 512, {}) for k in range(7)]
    cases += [(g["camera_projection_matrix"][0], 512, {}),
              (g["front_camera_projection_matrix"][0], 1024, {"r_cap": 40_960, "k_cams": 1})]
    res = {"cases": len(cases), "mismatch": []}
    t_new = t_old = 0.0
    for i, (P, size, kw) in enumerate(cases):
        t = time.perf_counter(); a = G.frame_geometry(P, size, **kw); t_new += time.perf_counter() - t
        t = time.perf_counter(); b = frame_geometry_loop(P, size, **kw); t_old += time.perf_counter() - t
        for f in ("sca_index", "base", "seg", "gather", "scale", "observed"):
            x, y = getattr(a, f), getattr(b, f)
            if x.shape != y.shape or x.dtype != y.dtype or x.tobytes() != y.tobytes():
                res["mismatch"].append([i, f])
        if a.seg_rows != b.seg_rows or a.visible_rows != b.visible_rows:
            res["mismatch"].append([i, "rows"])
    res["ms_per_frame"] = {"vectorized": round(t_new / len(cases) * 1e3, 1), "loop": round(t_old / len(cases) * 1e3, 1)}
    res["verdict"] = "PASS" if not res["mismatch"] else "FAIL"
    print(json.dumps(res, indent=1))
    return 0 if not res["mismatch"] else 1


if __name__ == "__main__":
    raise SystemExit(main())