File size: 14,158 Bytes
2230fab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
# SPDX-License-Identifier: Apache-2.0
"""The two deployed ONNX graphs of AutowareFoundation/lidar_centerpoint@v4.1 read as DATA, the way the TT port reads
them: the vendored ``ttaw.weights.OnnxWeights`` (initializers addressed by the node that consumes them; nothing is
executed), the module structure recovered from the graph topology, BatchNorm folded in float64 with one rounding.

The v4.1 exports (opset 11, PyTorch 1.9) have unnamed nodes, so ``OnnxWeights`` calls them ``<OpType>_<index>``
(``Conv_0``, ``ConvTranspose_37``, ...). Nothing here hard-codes those indices: the structure is found from the
graph (S:centerpoint:213-257) and checked against the expected SECOND / SECONDFPN / CenterHead layout:

- encoder (``pts_voxel_encoder.onnx``): ``MatMul -> Transpose -> BatchNormalization(eps 1e-3) -> Transpose -> Relu``,
  ``ReduceMax`` over the 32 slots, ``Concat[h, tile(max)]``, the same again, ``ReduceMax``. BN folds into each MatMul
  (``W' = W * s``, ``b' = beta - mean * s``), which is what the port's ``ttnn.linear`` weights are;
- head (``pts_backbone_neck_head.onnx``): the three block outputs are the inputs of the three deblocks feeding the
  single ``Concat``; each block is the Conv(+ReLU) chain from the previous block output (or ``spatial_features``).
  Backbone convs and deblock0 (1x1) already carry the exporter's BN fold (biases present); deblock1 / deblock2 are
  ``ConvTranspose`` (no bias) + ``BatchNormalization`` + ReLU and are folded here
  (``ttaw.weights.fold_bn_conv_transpose``), so every layer is one conv + bias (+ ReLU). The shared conv consumes the
  concat; every graph output (``heatmap`` ... ``vel``) is a 1x1 conv fed by a 1x1 conv + ReLU on the shared output.

Every :class:`Layer` records the ONNX tensor that holds the same value as its tap, so the ONNX Runtime golden can
expose matching intermediates (``reference/ort.py``).
"""
from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path
from typing import Any, Dict, List, Optional, Sequence, Tuple

import numpy as np

from ..ttaw.weights import OnnxWeights, fold_bn_linear
from .config import ENCODER_ONNX, HEAD_NAMES, HEAD_ONNX, variant_dir

__all__ = ["Layer", "EncoderParams", "HeadParams", "CenterPointWeights", "load_encoder", "load_head", "load_weights"]


@dataclass(frozen=True)
class Layer:
    """One conv layer, BN folded: ``y = relu?(conv(x, weight) + bias)``."""

    name: str                 # tap name ("backbone.block0.conv0", "neck.deblock2", "head.heatmap.hidden", ...)
    kind: str                 # "conv" | "conv_transpose"
    weight: np.ndarray        # float32: conv [Cout, Cin, k, k]; conv_transpose [Cin, Cout, k, k]
    bias: np.ndarray          # float32 [Cout]
    stride: int
    padding: int
    relu: bool
    onnx_node: str            # the Conv / ConvTranspose node
    onnx_output: str          # ONNX tensor equal to this layer's output (after the ReLU when there is one)
    bn_node: Optional[str] = None   # BatchNormalization folded into this layer here (None: none / exporter-folded)

    @property
    def kernel(self) -> int:
        return int(self.weight.shape[-1])

    @property
    def in_channels(self) -> int:
        return int(self.weight.shape[1] if self.kind == "conv" else self.weight.shape[0])

    @property
    def out_channels(self) -> int:
        return int(self.weight.shape[0] if self.kind == "conv" else self.weight.shape[1])


@dataclass(frozen=True)
class EncoderParams:
    """PillarFeatureNet (``feat_channels=[32, 32]``) with BN folded. ``w*`` are ``[in, out]``. Layer 1 consumes
    ``concat[h, tile(max_slots h)]``: rows 0-15 of ``w1`` act on ``h`` (``w1a``), rows 16-31 on the max (``w1b``)."""

    w0: np.ndarray            # (9, 16) float32
    b0: np.ndarray            # (16,)
    w1: np.ndarray            # (32, 32)
    b1: np.ndarray            # (32,)
    nodes: Dict[str, str]
    onnx_taps: Dict[str, str]  # tap name -> ONNX tensor

    @property
    def w1a(self) -> np.ndarray:
        return self.w1[: self.w0.shape[1]]

    @property
    def w1b(self) -> np.ndarray:
        return self.w1[self.w0.shape[1]:]


@dataclass(frozen=True)
class HeadParams:
    blocks: Tuple[Tuple[Layer, ...], ...]          # SECOND: 3 blocks of 3x3 convs
    deblocks: Tuple[Layer, ...]                    # SECONDFPN: conv 1x1, convT k2 s2, convT k4 s4 (BN folded)
    shared: Layer                                  # shared conv 3x3 384 -> 64
    heads: Tuple[Tuple[str, Layer, Layer], ...]    # (output name, hidden 1x1 64 -> 64 + ReLU, final 1x1 64 -> C)
    input_name: str

    def layers(self) -> List[Layer]:
        out = [layer for block in self.blocks for layer in block] + list(self.deblocks) + [self.shared]
        for _, hidden, final in self.heads:
            out += [hidden, final]
        return out

    def onnx_taps(self) -> Dict[str, str]:
        """Tap name -> ONNX tensor of the module outputs (blocks, deblocks, shared conv, heads) and of every layer."""
        taps = {f"backbone.block{i}": block[-1].onnx_output for i, block in enumerate(self.blocks)}
        taps.update({layer.name: layer.onnx_output for layer in self.layers()})
        return taps

    @property
    def head_channels(self) -> Dict[str, int]:
        return {name: final.out_channels for name, _, final in self.heads}


@dataclass(frozen=True)
class CenterPointWeights:
    variant: str
    encoder: EncoderParams
    head: HeadParams
    encoder_sha256: str
    head_sha256: str
    model_dir: str


# ------------------------------------------------------------------------------------------------- helpers

def _single(found: Sequence[Any], what: str) -> Any:
    if len(found) != 1:
        raise ValueError(f"expected exactly one {what}, found {len(found)}")
    return found[0]


def _consumer(w: OnnxWeights, tensor: str, op_type: str, through: Sequence[str] = ()) -> Any:
    """The single ``op_type`` consumer of ``tensor``, looking through single-consumer ``through`` ops."""
    node = _single(w.consumers(tensor), f"consumer of {tensor!r}")
    while node.op_type in through:
        node = _single(w.consumers(node.outputs[0]), f"consumer of {node.outputs[0]!r}")
    if node.op_type != op_type:
        raise ValueError(f"{tensor!r} feeds {node.name} ({node.op_type}), expected {op_type}")
    return node


def _producer(w: OnnxWeights, tensor: str, op_type: str) -> Any:
    node = w.producer(tensor)
    if node is None or node.op_type != op_type:
        raise ValueError(f"{tensor!r} is produced by {getattr(node, 'op_type', None)}, expected {op_type}")
    return node


def _conv_layer(w: OnnxWeights, name: str, conv_node: Any, out_tensor: str, relu: bool) -> Layer:
    c = w.conv(conv_node.name)
    k = c.kernel_shape
    if c.group != 1 or c.dilations != (1, 1) or len(set(c.strides)) != 1 or len(set(c.pads)) != 1 or k[0] != k[1]:
        raise ValueError(f"{conv_node.name}: unexpected attributes {c}")
    bias = np.zeros(c.weight.shape[0], np.float32) if c.bias is None else np.asarray(c.bias, np.float32)
    return Layer(name, "conv", np.asarray(c.weight, np.float32), bias, int(c.strides[0]), int(c.pads[0]), relu,
                 conv_node.name, out_tensor)


# ------------------------------------------------------------------------------------------------- encoder

def load_encoder(path: Any) -> EncoderParams:
    """``pts_voxel_encoder.onnx`` -> folded PFN weights (module docstring)."""
    w = OnnxWeights(path)
    mats = w.nodes("MatMul")
    if len(mats) != 2:
        raise ValueError(f"{Path(path).name}: expected 2 MatMul (PFN layers), found {len(mats)}")
    folded, nodes, relu_out = [], {}, []
    for i, mm in enumerate(mats):
        wt = np.asarray(w.matmul_weight(mm.name), np.float64)                # [in, out]
        bn = _consumer(w, mm.outputs[0], "BatchNormalization", through=("Transpose",))
        relu = _consumer(w, bn.outputs[0], "Relu", through=("Transpose",))
        wf, bf = fold_bn_linear(wt, None, w.batchnorm(bn.name), layout="in_out")
        folded.append((wf.astype(np.float32), bf.astype(np.float32)))
        nodes.update({f"matmul{i}": mm.name, f"bn{i}": bn.name})
        relu_out.append(relu.outputs[0])
    concat = w.consumer_of(relu_out[0], "Concat")              # layer-0 ReLU feeds its ReduceMax and the Concat
    pooled = w.consumer_of(relu_out[0], "ReduceMax")
    if (concat.inputs[0] != relu_out[0] or int(concat.attrs.get("axis", -1)) != 2
            or list(pooled.attrs.get("axes", [])) != [1]):
        raise ValueError("PFN layer 1 input is not concat[h, tile(max over slots h)] on the feature axis")
    if _producer(w, w.output_names[0], "ReduceMax").inputs[0] != relu_out[1]:
        raise ValueError("encoder output is not the max over layer 1")
    (w0, b0), (w1, b1) = folded
    if w0.shape[1] * 2 != w1.shape[0]:
        raise ValueError(f"PFN shapes {w0.shape} / {w1.shape} do not match concat[h, max]")
    return EncoderParams(w0, b0, w1, b1, nodes, {"pfn.layer0": relu_out[0], "pfn": w.output_names[0]})


# ---------------------------------------------------------------------------------------------------- head

def _chain_back(w: OnnxWeights, out_tensor: str, stop_tensor: str, block: int) -> List[Layer]:
    """Conv+Relu layers from ``stop_tensor`` to ``out_tensor`` (a Relu output), in forward order."""
    layers: List[Layer] = []
    t = out_tensor
    while t != stop_tensor:
        relu = _producer(w, t, "Relu")
        conv = _producer(w, relu.inputs[0], "Conv")
        layers.append((conv, relu.outputs[0]))
        t = conv.inputs[0]
        if len(layers) > 64:
            raise ValueError("runaway block chain")
    return [_conv_layer(w, f"backbone.block{block}.conv{j}", conv, out, True)
            for j, (conv, out) in enumerate(reversed(layers))]


def load_head(path: Any) -> HeadParams:
    """``pts_backbone_neck_head.onnx`` -> SECOND / SECONDFPN / CenterHead layers with BN folded (module docstring)."""
    w = OnnxWeights(path)
    input_name = _single(list(w.input_names), "graph input")
    concat = _single(w.nodes("Concat"), "Concat (neck)")
    deblocks, block_outs = [], []
    for i, t in enumerate(concat.inputs):
        relu = _producer(w, t, "Relu")
        src = w.producer(relu.inputs[0])
        if src.op_type == "Conv":                                   # deblock0: 1x1 conv, exporter-folded BN
            layer = _conv_layer(w, f"neck.deblock{i}", src, relu.outputs[0], True)
            block_outs.append(src.inputs[0])
        elif src.op_type == "BatchNormalization":                   # deblock1/2: ConvTranspose + BN, folded here
            convt = _producer(w, src.inputs[0], "ConvTranspose")
            c = w.conv(convt.name)
            if c.group != 1 or c.kernel_shape != tuple(c.strides) or any(c.pads) or c.output_padding not in ((), (0, 0)):
                raise ValueError(f"{convt.name}: expected ConvTranspose with kernel == stride, no padding: {c}")
            wf, bf = w.fold_conv_bn(convt.name, src.name)
            layer = Layer(f"neck.deblock{i}", "conv_transpose", wf.astype(np.float32), bf.astype(np.float32),
                          int(c.strides[0]), 0, True, convt.name, relu.outputs[0], bn_node=src.name)
            block_outs.append(convt.inputs[0])
        else:
            raise ValueError(f"concat input {i} comes from {src.op_type}")
        deblocks.append(layer)
    blocks, prev = [], input_name
    for i, out in enumerate(block_outs):
        blocks.append(tuple(_chain_back(w, out, prev, i)))
        prev = out
    shared_conv = _consumer(w, concat.outputs[0], "Conv")
    shared_relu = _consumer(w, shared_conv.outputs[0], "Relu")
    shared = _conv_layer(w, "head.shared", shared_conv, shared_relu.outputs[0], True)
    heads = []
    for name in w.output_names:
        final = _producer(w, name, "Conv")
        relu = _producer(w, final.inputs[0], "Relu")
        hidden = _producer(w, relu.inputs[0], "Conv")
        if hidden.inputs[0] != shared_relu.outputs[0]:
            raise ValueError(f"head {name!r} is not fed by the shared conv")
        heads.append((name, _conv_layer(w, f"head.{name}.hidden", hidden, relu.outputs[0], True),
                      _conv_layer(w, f"head.{name}", final, name, False)))
    if tuple(n for n, _, _ in heads) != HEAD_NAMES:
        raise ValueError(f"head outputs {[n for n, _, _ in heads]} != {HEAD_NAMES}")
    params = HeadParams(tuple(blocks), tuple(deblocks), shared, tuple(heads), input_name)
    _check_head(params)
    return params


def _check_head(h: HeadParams) -> None:
    """The SECOND / SECONDFPN / CenterHead layout of S:centerpoint:246-257 (base and tiny differ only in the first
    stride)."""
    sizes = [len(b) for b in h.blocks]
    if sizes != [4, 6, 6]:
        raise ValueError(f"backbone blocks have {sizes} convs, expected [4, 6, 6]")
    for b in h.blocks:
        if any(layer.kernel != 3 or layer.padding != 1 for layer in b) or any(layer.stride != 1 for layer in b[1:]):
            raise ValueError("backbone blocks must be 3x3 convs, stride 1 after the first")
    if [b[0].stride for b in h.blocks][1:] != [2, 2] or h.blocks[0][0].stride not in (1, 2):
        raise ValueError("block strides must be [1|2, 2, 2]")
    d = h.deblocks
    if [(x.kind, x.kernel, x.stride) for x in d] != [("conv", 1, 1), ("conv_transpose", 2, 2),
                                                     ("conv_transpose", 4, 4)]:
        raise ValueError(f"unexpected deblocks {[(x.kind, x.kernel, x.stride) for x in d]}")
    if h.shared.kernel != 3 or h.shared.in_channels != sum(x.out_channels for x in d):
        raise ValueError("shared conv must be 3x3 over the concatenated deblocks")


def load_weights(weights_dir: Any, variant: str) -> CenterPointWeights:
    """Both graphs of one variant (``<weights_dir>/<variant>/`` or a variant directory)."""
    d = variant_dir(weights_dir, variant)
    enc_path, head_path = d / ENCODER_ONNX, d / HEAD_ONNX
    enc, head = load_encoder(enc_path), load_head(head_path)
    from ..ttaw.weights import file_sha256

    return CenterPointWeights(variant, enc, head, file_sha256(enc_path), file_sha256(head_path), str(d))