changh95's picture
tt-model push auto_e2e-p150 (container)
31ffdfe verified
Raw History Blame Contribute Delete
11.4 kB
# SPDX-License-Identifier: Apache-2.0
"""The AutoE2E BEV encoder rewritten in the order the device computes it (torch, fp32), checked against upstream.
Upstream (``Model/model_components/view_fusion/bevformer_v2_t1.py``) per frame: 6 x (t1 self-attention -> LN ->
multi-scale spatial cross-attention -> LN -> FFN -> LN), then the BEV cells no camera sees are zeroed. The port form
changes only the schedule, not the math:
- **layer 0's self-attention is a constant**: its inputs are the learned ``bev_queries`` and the learned row / column
position embeddings, so ``LN0(TSA0(bev_queries))`` is computed once (:attr:`PortForm.layer0`);
- **host geometry**: the reference points (4 pillar heights per BEV cell) projected into every camera, their
visibility mask and the per-camera lists of visible cells (``rows[c]``: cells with any visible pillar point) come
from the 3 x 4 matrices alone (:func:`reference_points`, :func:`rebatch`);
- **SCA rebatched**: the sampling offsets and attention weights are computed once per cell (upstream recomputes them
per camera) and the sampling runs only on the visible (cell, camera) rows (24.7 % of 6 x 60,000 on the golden
sample); the per-cell sum over cameras and the division by the camera count follow;
- **TSA as one 8-point attention per head**: upstream's two queue entries sample the same value map (t1: the current
BEV twice) with their own 4 offsets and a softmax per entry, then average; that is 8 points per head with weights
``0.5 * softmax`` per group of 4.
Sampling positions are pixel coordinates ``px = loc * size - 0.5`` (``align_corners=False``), the convention of the
device kernel; :func:`bilinear` is the zero-padded bilinear sample at those positions.
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import Dict, List, Sequence, Tuple
import torch
import torch.nn.functional as F
BEV_H, BEV_W = 300, 200
Q = BEV_H * BEV_W
E = 256
HEADS = 8
HEAD_DIM = 32
LEVELS = 4
POINTS = 8
PILLARS = 4
TSA_POINTS = 4
PC_RANGE = (-60.0, -60.0, -5.0, 120.0, 60.0, 3.0)
DEPTH_EPS = 1e-5
LN_EPS = 1e-5
def reference_points_3d() -> torch.Tensor:
"""``[Q, 4, 4]`` homogeneous ego points of the BEV pillars (``_init_reference_points`` + ``_ego_reference_homo``)."""
rows = (torch.arange(BEV_H, dtype=torch.float32) + 0.5) / BEV_H
cols = (torch.arange(BEV_W, dtype=torch.float32) + 0.5) / BEV_W
hts = (torch.arange(PILLARS, dtype=torch.float32) + 0.5) / PILLARS
gr, gc, gz = torch.meshgrid(rows, cols, hts, indexing="ij")
ref = torch.stack([1.0 - gr, 1.0 - gc, gz], dim=-1).reshape(Q, PILLARS, 3)
r = PC_RANGE
ref[..., 0] = ref[..., 0] * (r[3] - r[0]) + r[0]
ref[..., 1] = ref[..., 1] * (r[4] - r[1]) + r[1]
ref[..., 2] = ref[..., 2] * (r[5] - r[2]) + r[2]
return torch.cat([ref, torch.ones(Q, PILLARS, 1)], dim=-1)
def reference_points(P: torch.Tensor, size: int) -> Tuple[torch.Tensor, torch.Tensor]:
"""``P`` ``[V, 3, 4]`` (ego -> pixels of the ``size`` x ``size`` model input) -> (``uv`` ``[V, Q, 4, 2]`` in
[0, 1] units of the image, ``mask`` ``[V, Q, 4]``): upstream ``PinholeProjection`` + ``_finalize_linear``."""
pts = reference_points_3d().reshape(-1, 4)
proj = torch.einsum("vij,mj->vmi", P.float(), pts)
depth = proj[..., 2]
uv = proj[..., :2] / depth.clamp(min=DEPTH_EPS).unsqueeze(-1) / torch.tensor([float(size), float(size)])
mask = (depth > DEPTH_EPS) & (uv[..., 0] >= 0) & (uv[..., 0] <= 1) & (uv[..., 1] >= 0) & (uv[..., 1] <= 1)
V = P.shape[0]
return uv.reshape(V, Q, PILLARS, 2), mask.reshape(V, Q, PILLARS)
def rebatch(mask: torch.Tensor) -> List[torch.Tensor]:
"""Per camera the BEV cells with any visible pillar point (upstream's ``visible``), ascending."""
return [torch.nonzero(mask[v].any(-1)).flatten() for v in range(mask.shape[0])]
def bilinear(value: torch.Tensor, px: torch.Tensor, py: torch.Tensor) -> torch.Tensor:
"""Zero-padded bilinear sample: ``value`` ``[N, C, h, w]``, pixel coordinates ``px, py`` ``[N, R, P]`` ->
``[N, R, P, C]`` (identical to ``grid_sample(align_corners=False)`` at ``g = (2 px + 1) / w - 1``)."""
n, c, h, w = value.shape
gx = (2.0 * px + 1.0) / w - 1.0
gy = (2.0 * py + 1.0) / h - 1.0
out = F.grid_sample(value, torch.stack([gx, gy], -1), mode="bilinear", padding_mode="zeros", align_corners=False)
return out.permute(0, 2, 3, 1)
def _lin(x, m):
return F.linear(x, m.weight, m.bias)
@dataclass
class FrameTrace:
"""Optional per-layer intermediates of :meth:`PortForm.frame` (for the device stage checks)."""
layers: List[Dict[str, torch.Tensor]]
class PortForm:
"""The BEV encoder of a loaded upstream ``AutoE2E`` model in port form (``model.Reactive_E2E``)."""
def __init__(self, model):
r = model.Reactive_E2E
self.vf = vf = r.FeatureFusion.view_fusion
self.layers = list(vf.layers)
self.level_emb = vf.level_embeddings.detach().float()
self.camera_emb = vf.camera_embeddings.detach().float()
rows = vf.row_embed.weight.detach()[:, None, :].expand(BEV_H, BEV_W, -1)
cols = vf.col_embed.weight.detach()[None, :, :].expand(BEV_H, BEV_W, -1)
self.position = torch.cat([rows, cols], dim=-1).reshape(Q, E).float()
self.queries = vf.bev_queries.weight.detach().float()
with torch.no_grad():
self.layer0 = self._ln(self.layers[0].norms[0], self.tsa(self.layers[0].self_attention, self.queries))
# ------------------------------------------------------------------ blocks
@staticmethod
def _ln(norm, x):
return F.layer_norm(x, (E,), norm.weight, norm.bias, LN_EPS)
def tsa(self, att, query: torch.Tensor) -> torch.Tensor:
"""t1 self-attention as 8 points per head (2 queue entries x 4) on one value map; returns ``query + out``."""
value = _lin(query, att.value_proj).reshape(BEV_H, BEV_W, HEADS, HEAD_DIM).permute(2, 3, 0, 1)
pin = torch.cat([query, query + self.position], dim=-1)
off = _lin(pin, att.sampling_offsets).reshape(Q, HEADS, 2 * TSA_POINTS, 2)
logit = _lin(pin, att.attention_weights).reshape(Q, HEADS, 2, TSA_POINTS)
w = 0.5 * logit.softmax(-1).reshape(Q, HEADS, 2 * TSA_POINTS)
rr = (torch.arange(BEV_H, dtype=torch.float32) + 0.5) / BEV_H
cc = (torch.arange(BEV_W, dtype=torch.float32) + 0.5) / BEV_W
gr, gc = torch.meshgrid(rr, cc, indexing="ij")
ref = torch.stack([gc, gr], -1).reshape(Q, 1, 1, 2)
loc = ref + off / torch.tensor([float(BEV_W), float(BEV_H)]) # [Q, H, 8, 2] in [0, 1]
px = (loc[..., 0] * BEV_W - 0.5).permute(1, 0, 2)
py = (loc[..., 1] * BEV_H - 0.5).permute(1, 0, 2)
s = bilinear(value, px, py) # [H, Q, 8, 32]
out = (s * w.permute(1, 0, 2).unsqueeze(-1)).sum(2).permute(1, 0, 2).reshape(Q, E)
return query + _lin(out, att.output_proj)
def value_maps(self, att, feats: Sequence[torch.Tensor], cams: Sequence[int], *, delta_only=False):
"""Per level ``[V * H, 32, h, w]`` value maps (map ``v * H + head``) of the SCA value projection."""
out = []
for lvl, f in enumerate(feats):
x = f.float().permute(0, 2, 3, 1) # [V, h, w, 256]
if delta_only:
x = F.linear(x, att.value_proj.weight)
else:
x = x + self.level_emb[lvl] + self.camera_emb[list(cams)].reshape(-1, 1, 1, E)
x = _lin(x, att.value_proj)
v, h, w, _ = x.shape
out.append(x.reshape(v, h, w, HEADS, HEAD_DIM).permute(0, 3, 4, 1, 2).reshape(v * HEADS, HEAD_DIM, h, w))
return out
def sca_attend(self, att, query, maps, uv, rows) -> Tuple[torch.Tensor, torch.Tensor]:
"""Rebatched SCA: (per-cell sum over the seeing cameras ``[Q, 256]``, camera count ``[Q]``)."""
off = _lin(query, att.sampling_offsets).reshape(Q, HEADS, LEVELS, POINTS, 2)
w = _lin(query, att.attention_weights).reshape(Q, HEADS, LEVELS * POINTS).softmax(-1)
w = w.reshape(Q, HEADS, LEVELS, POINTS)
anchors = torch.arange(POINTS) % PILLARS
acc = torch.zeros(Q, E)
cnt = torch.zeros(Q)
for v, idx in enumerate(rows):
if idx.numel() == 0:
continue
ref = uv[v, idx][:, anchors] # [R, 8, 2]
o = torch.zeros(idx.numel(), HEADS, HEAD_DIM)
for lvl, m in enumerate(maps):
h, wd = m.shape[-2:]
loc = ref[:, None] + off[idx, :, lvl] / torch.tensor([float(wd), float(h)]) # [R, H, 8, 2]
px = (loc[..., 0] * wd - 0.5).permute(1, 0, 2)
py = (loc[..., 1] * h - 0.5).permute(1, 0, 2)
s = bilinear(m[v * HEADS:(v + 1) * HEADS], px, py) # [H, R, 8, 32]
o = o + (s * w[idx, :, lvl].permute(1, 0, 2).unsqueeze(-1)).sum(2).permute(1, 0, 2)
acc[idx] += o.reshape(-1, E)
cnt[idx] += 1.0
return acc, cnt
def frame(self, feats: Sequence[torch.Tensor], P: torch.Tensor, *, size: int = 512, trace: bool = False):
"""One BEV frame: FPN levels ``[6, 256, h, w]`` x 4 and ``P`` ``[6, 3, 4]`` -> ``[Q, 256]`` (zeroed where no
camera sees the cell) and the optional trace."""
uv, mask = reference_points(P, size)
rows = rebatch(mask)
cams = list(range(P.shape[0]))
tr = []
query = self.layer0
for i, layer in enumerate(self.layers):
if i > 0:
query = self._ln(layer.norms[0], self.tsa(layer.self_attention, query))
maps = self.value_maps(layer.cross_attention, feats, cams)
acc, cnt = self.sca_attend(layer.cross_attention, query, maps, uv, rows)
attended = acc / cnt.clamp_min(1.0).unsqueeze(-1)
query = self._ln(layer.norms[1], query + _lin(attended, layer.cross_attention.output_proj))
ffn = layer.ffn
query = self._ln(layer.norms[2], query + _lin(F.relu(_lin(query, ffn[0])), ffn[3]))
if trace:
tr.append({"query": query.clone()})
observed = mask.any(-1).any(0)
out = query * observed.unsqueeze(-1).float()
return (out, FrameTrace(tr)) if trace else out
def front(self, bev: torch.Tensor, feats: Sequence[torch.Tensor], P_front: torch.Tensor) -> torch.Tensor:
"""``fuse_front_camera``: the 1024 px front FPN through the content-only cross-attention, gated residual."""
vf = self.vf
att = vf.front_cross_attention
uv, mask = reference_points(P_front, 1024)
rows = rebatch(mask)
maps = self.value_maps(att, feats, [vf.front_camera_index], delta_only=True)
maps = [m for m in maps]
# camera embedding of the front camera is unused under delta_only (the value is W x only)
acc, cnt = self.sca_attend(att, bev, maps, uv, rows)
attended = F.linear(acc / cnt.clamp_min(1.0).unsqueeze(-1), att.output_proj.weight)
norm = self.layers[-1].norms[1]
residual = self._ln(norm, bev + attended) - self._ln(norm, bev)
residual = residual * mask.any(-1).any(0).unsqueeze(-1).float()
gate = torch.tanh(vf.front_residual_gate.detach().float())
return bev + gate * residual