changh95's picture
tt-model push centerpoint-p150 (container)
2230fab verified
Raw History Blame Contribute Delete
8.2 kB
# SPDX-License-Identifier: Apache-2.0
"""fp32 PyTorch re-implementation of the deployed CenterPoint network, module by module, with taps.
Built from :mod:`.weights` (the ONNX initializers addressed by node, BN folded where the TT port folds it), it
reproduces the two deployed graphs (S:centerpoint:205-257):
- ``pfn``: PillarFeatureNet, ``h = relu(x @ W0' + b0')``, ``m = max over ALL 32 slots of h`` (zero-padded slots
included: their rows are ``relu(b0')``, S:centerpoint:221-223), ``y = relu(concat[h, m] @ W1' + b1')``,
``max over the 32 slots`` -> (P, 32). It runs on the kept pillars only: the deployed encoder runs on all 40,000
rows, but rows past ``num_pillars`` are never scattered;
- ``scatter``: ``canvas[0, c, iy, ix] = pfn[p, c]`` (``scatter_kernel.cu``), a zero (1, 32, 480, 480) canvas;
- ``backbone``: SECOND, 3 blocks of 3x3 convs + ReLU (strides [1, 2, 2]; tiny [2, 2, 2]);
- ``neck``: SECONDFPN deblocks (1x1 conv, ConvTranspose k2 s2, ConvTranspose k4 s4, BN folded) + ReLU, concat;
- ``head``: shared 3x3 conv 384 -> 64 + ReLU, then six heads (1x1 64 -> 64 + ReLU, 1x1 64 -> C).
It computes the deployed graph literally (concat, then one conv); the TT-friendly equivalent forms the port uses
(split PFN layer 1, K-split shared conv, merged heads, ConvTranspose as linear + depth-to-space, gather-form
scatter) are in :mod:`.rewrites` and proven equal to these modules by ``tests/test_reference_rewrites_host.py``.
Taps (``ttaw.golden.TapRegistry``; stable names, used by the device PCC gates): ``pfn.layer0`` (P, 32, 16),
``pfn`` (P, 32), ``canvas`` (1, 32, H, W), ``backbone.block{0,1,2}`` (+ ``.conv{j}``), ``neck.deblock{0,1,2}``,
``head.shared``, ``head.<name>.hidden``, ``head.<name>`` for heatmap, reg, height, dim, rot, vel. Values are
recorded as float32 numpy, batch axis kept (``(1, C, H, W)``).
torch is imported lazily (``import tt_centerpoint.reference`` stays light); the module runs where ttnn is absent.
"""
from __future__ import annotations
from typing import Any, Dict, List, Optional
import numpy as np
from ..ttaw.golden import NULL_TAPS, TapRegistry
from .weights import CenterPointWeights
__all__ = ["CenterPointTorch", "MODULE_TAPS"]
# the module-output taps (golden files and device gates); per-layer taps are opt-in (include patterns)
MODULE_TAPS = ("pfn", "canvas", "backbone.block0", "backbone.block1", "backbone.block2", "neck.deblock0",
"neck.deblock1", "neck.deblock2", "head.shared", "head.heatmap", "head.reg", "head.height", "head.dim",
"head.rot", "head.vel")
def _torch():
import torch
return torch
def _tap(taps: TapRegistry, name: str, value):
"""Record a torch tensor as a float32 numpy copy (never through ``ttaw.tensors.to_numpy``, which would import
ttnn) and return it unchanged."""
if taps.enabled and taps.wants(name):
taps.tap(name, value.detach().cpu().numpy().astype(np.float32, copy=True))
return value
class CenterPointTorch:
"""The fp32 reference network of one variant. ``threads`` caps torch's intra-op threads (shared host: <= 4)."""
def __init__(self, weights: CenterPointWeights, *, threads: Optional[int] = None, device: str = "cpu"):
torch = _torch()
if threads is not None:
torch.set_num_threads(int(threads))
self.weights = weights
self.variant = weights.variant
t = lambda a: torch.from_numpy(np.array(a, dtype=np.float32, copy=True)).to(device) # noqa: E731
enc = weights.encoder
self.w0, self.b0, self.w1, self.b1 = t(enc.w0), t(enc.b0), t(enc.w1), t(enc.b1)
self._layers: Dict[str, tuple] = {}
for layer in weights.head.layers():
self._layers[layer.name] = (layer, t(layer.weight), t(layer.bias))
self.device = device
# ------------------------------------------------------------------------------------------- modules
def pfn(self, features: Any, taps: TapRegistry = NULL_TAPS):
"""(P, 32, F) decorated pillar features -> (P, 32) pillar features (``pillar_features`` squeezed)."""
torch = _torch()
x = torch.as_tensor(np.asarray(features, dtype=np.float32), device=self.device)
h = torch.relu(torch.matmul(x, self.w0) + self.b0) # (P, 32, 16)
_tap(taps, "pfn.layer0", h)
m = h.amax(dim=1, keepdim=True) # max over all 32 slots
y = torch.relu(torch.matmul(torch.cat([h, m.expand_as(h)], dim=2), self.w1) + self.b1)
return _tap(taps, "pfn", y.amax(dim=1))
def scatter(self, pillar_features: Any, coords: np.ndarray, num_pillars: int, grid_x: int, grid_y: int,
taps: TapRegistry = NULL_TAPS):
"""``scatterFeatures_kernel``: (P, 32) -> (1, 32, grid_y, grid_x) zero canvas with ``canvas[c, iy, ix]``."""
torch = _torch()
pf = torch.as_tensor(pillar_features, device=self.device)[:num_pillars]
canvas = torch.zeros((1, pf.shape[1], grid_y, grid_x), dtype=torch.float32, device=self.device)
c = torch.as_tensor(np.asarray(coords)[:num_pillars].astype(np.int64), device=self.device)
canvas[0, :, c[:, 1], c[:, 2]] = pf.T
return _tap(taps, "canvas", canvas)
def layer(self, name: str, x):
torch = _torch()
F = torch.nn.functional
layer, w, b = self._layers[name]
if layer.kind == "conv":
y = F.conv2d(x, w, b, stride=layer.stride, padding=layer.padding)
else:
y = F.conv_transpose2d(x, w, b, stride=layer.stride, padding=layer.padding)
return torch.relu(y) if layer.relu else y
def backbone(self, canvas, taps: TapRegistry = NULL_TAPS) -> List[Any]:
outs = []
x = canvas
for i, block in enumerate(self.weights.head.blocks):
for layer in block:
x = _tap(taps, layer.name, self.layer(layer.name, x))
outs.append(_tap(taps, f"backbone.block{i}", x))
return outs
def neck(self, blocks: List[Any], taps: TapRegistry = NULL_TAPS) -> List[Any]:
return [_tap(taps, layer.name, self.layer(layer.name, x))
for layer, x in zip(self.weights.head.deblocks, blocks)]
def head(self, deblocks: List[Any], taps: TapRegistry = NULL_TAPS) -> Dict[str, Any]:
torch = _torch()
shared = _tap(taps, "head.shared", self.layer("head.shared", torch.cat(deblocks, dim=1)))
out = {}
for name, hidden, final in self.weights.head.heads:
h = _tap(taps, hidden.name, self.layer(hidden.name, shared))
out[name] = _tap(taps, final.name, self.layer(final.name, h))
return out
# --------------------------------------------------------------------------------------------- whole
def forward(self, features: np.ndarray, coords: np.ndarray, num_pillars: int, grid_x: int, grid_y: int, *,
taps: TapRegistry = NULL_TAPS) -> Dict[str, np.ndarray]:
"""Decorated pillars (only the first ``num_pillars`` rows are used) -> the six head maps as float32 numpy
``(C, H, W)`` (batch axis dropped)."""
torch = _torch()
with torch.no_grad():
pf = self.pfn(np.asarray(features)[:num_pillars], taps)
canvas = self.scatter(pf, coords, num_pillars, grid_x, grid_y, taps)
heads = self.head(self.neck(self.backbone(canvas, taps), taps), taps)
return {k: v[0].cpu().numpy().astype(np.float32) for k, v in heads.items()}
def describe(self) -> Dict[str, Any]:
h = self.weights.head
return {"variant": self.variant, "encoder_sha256": self.weights.encoder_sha256,
"head_sha256": self.weights.head_sha256,
"blocks": [[(lay.in_channels, lay.out_channels, lay.stride) for lay in b] for b in h.blocks],
"deblocks": [(lay.kind, lay.in_channels, lay.out_channels, lay.stride) for lay in h.deblocks],
"head_channels": h.head_channels}
def layer_names(weights: CenterPointWeights) -> List[str]:
"""Every per-layer tap name (backbone convs, deblocks, shared, head hidden / final)."""
return [layer.name for layer in weights.head.layers()]