File size: 5,629 Bytes
0f131e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
# SPDX-License-Identifier: Apache-2.0
"""Weights and graph constants of a METEOR 2 ONNX file, read as data (the graph is never executed here).

``Meteor2Weights(path)`` wraps the vendored ``ttaw.weights.OnnxWeights``: convolutions by module path
(``"l2/l2.0/conv1"``), Gemm / MatMul weights, and the non-learned constants the graph computes with (the 100,000 BEV
ground points of the lift, the ego-kin pooling matrices, the 6 s path matrices). Batch norms are already folded
into the convs of the released graphs (no BatchNormalization node), so every conv is a plain ``ConvParams``.
"""
from __future__ import annotations

from pathlib import Path
from typing import Dict, Union

import numpy as np

from ..ttaw.weights import ConvParams, OnnxWeights

PathLike = Union[str, Path]

__all__ = ["Meteor2Weights", "detect_form"]


def detect_form(w: OnnxWeights) -> str:
    """``gather`` (K and T_cam_ego are graph inputs) or ``npu`` (the rig is inside the weights)."""
    return "gather" if "K" in w.input_names else "npu"


class Meteor2Weights:
    """All parameters of one form, by module name. ``form`` is detected from the graph inputs."""

    def __init__(self, path: PathLike):
        self.path = Path(path)
        self.onnx = OnnxWeights(self.path)
        self.form = detect_form(self.onnx)
        self._conv_cache: Dict[str, ConvParams] = {}

    @property
    def sha256(self) -> str:
        return self.onnx.sha256

    def has_node(self, name: str) -> bool:
        try:
            self.onnx.node(name)
            return True
        except KeyError:
            return False

    # ------------------------------------------------------------------ convs / dense layers
    def conv(self, module: str) -> ConvParams:
        """``module`` without the leading slash and without ``/Conv`` (``"stem/stem.0"``, ``"seg2d"``, ``""`` for the
        anonymous seg-softmax projection ``/Conv``)."""
        name = f"/{module}/Conv" if module else "/Conv"
        if name not in self._conv_cache:
            self._conv_cache[name] = self.onnx.conv(name)
        return self._conv_cache[name]

    def gemm(self, module: str):
        """(weight [out, in] float32, bias [out] float32) of ``/<module>/Gemm`` (transB=1 in this graph)."""
        g = self.onnx.gemm(f"/{module}/Gemm")
        w = np.asarray(g.weight, np.float32)
        if not g.trans_b:
            w = w.T
        if g.alpha != 1.0 or g.beta != 1.0:
            raise ValueError(f"/{module}/Gemm has alpha {g.alpha} beta {g.beta}")
        return np.ascontiguousarray(w), np.asarray(g.bias, np.float32)

    def linear(self, module: str):
        """(weight [in, out], bias [out]) of a MatMul + Add pair (``ego_kin/ego_kin.k``)."""
        w = self.onnx.matmul_weight(f"/{module}/MatMul")
        b = self.onnx.param(f"/{module}/Add", 0)
        return np.asarray(w, np.float32), np.asarray(b, np.float32)

    # ------------------------------------------------------------------ graph constants
    # Node names differ between the two forms (the NPU graph numbers its top-level nodes differently), so the
    # constants are found by structure: the consuming op and the constant's shape.
    def _const_inputs(self, op_type: str, shape) -> list:
        """[(node, slot, array)] of every ``op_type`` node with a constant input of ``shape``, in graph order."""
        out = []
        for n in self.onnx.nodes(op_type):
            for i, t in enumerate(n.inputs):
                if t and self.onnx.has(t):
                    a = self.onnx.array(t)
                    if tuple(a.shape) == tuple(shape):
                        out.append((n, i, a))
        return out

    def bev_points(self) -> np.ndarray:
        """Gather form: [4, 100000] homogeneous ego points of the lift (x, y, z, 1) in BEV row-major order."""
        found = self._const_inputs("Expand", (1, 4, 100000))
        if len(found) != 2 or not np.array_equal(found[0][2], found[1][2]):
            raise ValueError(f"expected the two identical lift point sets, found {len(found)}")
        return np.asarray(found[0][2], np.float32).reshape(4, -1)

    def paint_z_fill(self) -> np.ndarray:
        """Gather form: [8, 100000], the depth the paint projection divides by where z <= 1.5 (Where else-branch)."""
        found = self._const_inputs("Where", (8, 100000))
        if len(found) != 1:
            raise ValueError(f"expected one paint Where constant, found {len(found)}")
        return np.asarray(found[0][2], np.float32)

    def kin_pool(self):
        """(P_h [16, 200], P_w [125, 10]): the ego-kin token pooling over the 200 x 125 BEV map."""
        h = self._const_inputs("MatMul", (16, 200))
        w = self._const_inputs("MatMul", (125, 10))
        if len(h) != 1 or len(w) != 1 or h[0][1] != 0 or w[0][1] != 1:
            raise ValueError("ego-kin pooling matrices not found")
        return np.asarray(h[0][2], np.float32), np.asarray(w[0][2], np.float32)

    def path_mats(self):
        """(A [12, 12], B [12, 12]): ego_path_6s tail = traj3s @ A + gate * kin12 @ B (graph order: A first)."""
        found = self._const_inputs("MatMul", (12, 12))
        if len(found) != 2 or any(f[1] != 1 for f in found):
            raise ValueError(f"expected two 12x12 path matrices, found {len(found)}")
        return np.asarray(found[0][2], np.float32), np.asarray(found[1][2], np.float32)

    def upsample_kernels(self) -> list:
        """NPU form: the depthwise ConvTranspose 2x2 stride-2 constants, in graph order (all ones = nearest x2)."""
        return [np.asarray(self.onnx.param(n.name, 1), np.float32) for n in self.onnx.nodes("ConvTranspose")]