Download code/tt_meteor2/reference/model.py from changh95/METEOR-2-p150: direct link, hf CLI and curl.
- Browser
- Download file 22.1 kB
-
https://huggingface.co/changh95/METEOR-2-p150/resolve/main/code/tt_meteor2/reference/model.py
- Command line
-
hf download hf://changh95/METEOR-2-p150/code/tt_meteor2/reference/model.py
-
curl -L -o model.py https://huggingface.co/changh95/METEOR-2-p150/resolve/main/code/tt_meteor2/reference/model.py
22.1 kB
| # SPDX-License-Identifier: Apache-2.0 | |
| """Pure-PyTorch fp32 re-implementation of ``meteor2_gather.onnx`` and ``meteor2_npu.onnx`` with per-module taps. | |
| Written from the released graphs (``reference.weights`` reads every parameter and constant from its ONNX node; no | |
| upstream code is imported). The arithmetic keeps the graph's operation order where it decides a rounding or a | |
| discrete choice (the lift projection, its validity tests and the paint pixel rounding). Shape glue disappears. | |
| ``Meteor2Net.forward`` returns the 14 graph outputs with the ONNX names and shapes; ``taps`` records the | |
| intermediates below (names shared with ``reference.ort.ORT_TAPS``, the device gates and the goldens). | |
| Graph (both forms; ``N`` = 8 cameras, image 648 x 1152, features 162 x 288, BEV 400 x 250): | |
| ================== ====================== =================================================================== | |
| tap shape meaning | |
| ================== ====================== =================================================================== | |
| ``img.input`` [8, 3, 648, 1152] (uint8 / 255 - mean) / std | |
| ``img.c1`` [8, 64, 162, 288] stem 7x7 s2 + ReLU + maxpool 3x3 s2 + 2 BasicBlocks (ResNet-18 layer1) | |
| ``img.c2..c4`` [8, 128..512, ...] ResNet-18 layers 2..4 (81 x 144, 41 x 72, 21 x 36) | |
| ``img.fpn`` [8, 128, 162, 288] lat4..lat1 + nearest top-down (21x36 -> 41x72 -> 81x144) + smooth | |
| 3x3 ReLU + nearest x2 + lat1, then the f_x residual block (ReLU) | |
| ``seg2d.logits`` [8, 21, 162, 288] 1x1 head (also an output) | |
| ``ctx`` [8, 64, 162, 288] ctx (3x3 96 ReLU + 1x1 64) + 1x1(softmax(seg2d)) + pp_mix residual | |
| block (no final ReLU) | |
| ``depth.logits`` [8, 64, 162, 288] depth.0 3x3 96 ReLU, depth_x residual (ReLU), depth.1 1x1 64 | |
| ``depth.prob`` [8, 64, 162, 288] softmax over the 64 log-spaced bins (fp32) | |
| ``paint.feat`` [8, 32, 162, 288] paint 1x1 64 -> 32 ReLU on ``img.c1`` | |
| ``lift.polar`` [8, 64, 64, 288] 0.5 * sum over image rows of ctx x prob, per camera and column: | |
| [cam, ctx channel, depth bin, column] | |
| ``lift.bev`` [1, 64, 400, 250] Gather: bilinear (column, bin) sample of every BEV ground point | |
| in every camera, mean over the cameras that see it. | |
| NPU: the block low-rank map of ``lift.polar`` (``reference.lowrank``) | |
| ``paint.bev`` [1, 32, 400, 250] Gather: nearest image pixel of every ground point, mean over | |
| cameras. NPU: the block low-rank map of ``paint.feat`` | |
| ``bev.b0`` [1, 64, 400, 250] b0: 3x3 ReLU + residual block | |
| ``bev.b1`` [1, 128, 200, 125] b1: 3x3 s2 ReLU + 3 residual blocks (dilation 1, 2, 4) | |
| ``bev.fuse`` [1, 96, 400, 250] b0 + nearest x2(up_lat(b1)) -> fuse 3x3 ReLU + residual block | |
| ``det.feat`` [1, 96, 400, 250] det 3x3 ReLU + 2 residual blocks (dilation 1, 2) | |
| ``lane.up`` [1, 48, 800, 500] nearest x2(lane.0 + seg_x0) + gipm_proj(nearest x2(paint.bev)) | |
| ``ego.flat`` [1, 2560] ego_stem (2 x 3x3 s2 ReLU on b1) + avgpool 10x8 -> 128 x 5 x 4 | |
| ``ego.kin_in`` [1, 3, 3132] per 3 s candidate: shared ego context + its path / 10, score, route | |
| ``occ.feat`` [1, 128, 200, 200] occ stem + mid block (+ the occ_mid2 residual pair, Gather form only) | |
| on fuse rows 100:300, cols 25:225 | |
| ================== ====================== =================================================================== | |
| """ | |
| from __future__ import annotations | |
| from typing import Any, Dict, Mapping, Optional | |
| import numpy as np | |
| from . import config as C | |
| from .lowrank import LowRankLift, parse_lowrank | |
| from .weights import Meteor2Weights | |
| __all__ = ["Meteor2Net", "nearest_index", "lift_geometry", "paint_geometry"] | |
| def _torch(): | |
| import torch | |
| import torch.nn.functional as F | |
| return torch, F | |
| def nearest_index(n_in: int, n_out: int) -> np.ndarray: | |
| """ONNX Resize nearest / asymmetric / floor source index per output index (scale = out / in, float32).""" | |
| scale = np.float32(n_out) / np.float32(n_in) | |
| idx = np.floor(np.arange(n_out, dtype=np.float32) / scale).astype(np.int64) | |
| return np.minimum(idx, n_in - 1) | |
| def _f32(x) -> np.ndarray: | |
| return np.asarray(x, np.float32) | |
| def lift_geometry(K: np.ndarray, T_cam_ego: np.ndarray, pts: np.ndarray) -> Dict[str, np.ndarray]: | |
| """Gather-form lift geometry, float32 in the graph's operation order. | |
| K [8, 3, 3], T_cam_ego [8, 4, 4] (ego -> camera optical), pts [4, P] -> col, bin [8, P] (feature-plane column and | |
| depth-bin coordinates), valid [8, P] bool, z [8, P]. | |
| """ | |
| K, T, pts = _f32(K), _f32(T_cam_ego), _f32(pts) | |
| cam = np.einsum("nij,jp->nip", T, pts).astype(np.float32) # /MatMul_1: [8, 4, P] | |
| x, z = cam[:, 0], cam[:, 2] | |
| s = np.float32(np.float32(1.0) / np.float32(C.IMG_W)) * np.float32(C.IMG_W) # /Reciprocal * 1152 | |
| fx = (K[:, 0, 0] * s)[:, None] | |
| cx = (K[:, 0, 2] * s)[:, None] | |
| zc = np.maximum(z, np.float32(C.Z_MIN)) # /Clip | |
| u = (fx * x) / zc + cx # /Mul_5, /Div_2, /Add_4 | |
| col = (u + np.float32(0.5)) / np.float32(C.FEAT_STRIDE) - np.float32(0.5) | |
| b = (np.log(zc) - np.float32(C.LOG_Z0)) / np.float32(C.LOG_DZ) # /Log, /Sub_2, /Div_4 | |
| valid = (z > np.float32(C.Z_MIN)) & (col >= 0) & (col <= np.float32(C.FEAT_W - 1)) & (b >= 0) \ | |
| & (b <= np.float32(C.N_BINS - 1)) | |
| return {"col": col.astype(np.float32), "bin": b.astype(np.float32), "valid": valid, "z": z} | |
| def paint_geometry(K: np.ndarray, T_cam_ego: np.ndarray, pts: np.ndarray, z_fill: np.ndarray) -> Dict[str, np.ndarray]: | |
| """Gather-form paint geometry: rounded feature pixel (rc, rr) [8, P] int and valid [8, P] bool.""" | |
| K, T, pts = _f32(K), _f32(T_cam_ego), _f32(pts) | |
| cam = np.einsum("nij,jp->nip", T, pts).astype(np.float32) # /MatMul_2 | |
| x, y, z = cam[:, 0], cam[:, 1], cam[:, 2] | |
| sw = np.float32(np.float32(1.0) / np.float32(C.IMG_W)) * np.float32(C.IMG_W) | |
| sh = np.float32(np.float32(1.0) / np.float32(C.IMG_H)) * np.float32(C.IMG_H) | |
| front = z > np.float32(C.Z_MIN) | |
| zq = np.where(front, z, _f32(z_fill)) # /Where_2 | |
| u = ((K[:, 0, 0:1] * sw) * x) / zq + K[:, 0, 2:3] * sw # /Mul_11, /Mul_12, /Div_8, /Add_6 | |
| v = ((K[:, 1, 1:2] * sh) * y) / zq + K[:, 1, 2:3] * sh | |
| cu = (u + np.float32(0.5)) / np.float32(C.FEAT_STRIDE) - np.float32(0.5) | |
| cv = (v + np.float32(0.5)) / np.float32(C.FEAT_STRIDE) - np.float32(0.5) | |
| rc = np.rint(cu) # ONNX Round: half to even (= np.rint) | |
| rr = np.rint(cv) | |
| valid = front & (rc >= 0) & (rc < C.FEAT_W) & (rr >= 0) & (rr < C.FEAT_H) | |
| return {"rc": rc.astype(np.int64), "rr": rr.astype(np.int64), "valid": valid} | |
| class Meteor2Net: | |
| """fp32 CPU reference of one form. ``Meteor2Net(Meteor2Weights(path))``; call with the graph's inputs.""" | |
| def __init__(self, weights: Meteor2Weights): | |
| torch, _ = _torch() | |
| self.w = weights | |
| self.form = weights.form | |
| self._t: Dict[str, Any] = {} | |
| if self.form == "gather": | |
| self.pts = weights.bev_points() | |
| self.z_fill = weights.paint_z_fill() | |
| self.vt: Optional[LowRankLift] = None | |
| self.gvt: Optional[LowRankLift] = None | |
| else: | |
| self.vt = parse_lowrank(weights.onnx, "/vt_lr/") | |
| self.gvt = parse_lowrank(weights.onnx, "/gvt_lr/") | |
| for k in weights.upsample_kernels(): | |
| if not np.all(k == 1.0): | |
| raise ValueError("NPU ConvTranspose upsample is not nearest x2 (weights != 1)") | |
| self.has_occ_mid2 = weights.has_node("/occ_mid2/occ_mid2.0/a/a.0/Conv") | |
| ph, pw = weights.kin_pool() | |
| a, b = weights.path_mats() | |
| self.kin_ph, self.kin_pw = torch.from_numpy(ph.copy()), torch.from_numpy(pw.copy()) | |
| self.path_a, self.path_b = torch.from_numpy(a.copy()), torch.from_numpy(b.copy()) | |
| self._idx = {} | |
| # ------------------------------------------------------------------ layers | |
| def _param(self, key, make): | |
| if key not in self._t: | |
| self._t[key] = make() | |
| return self._t[key] | |
| def conv(self, module: str, x): | |
| torch, F = _torch() | |
| p = self.w.conv(module) | |
| wt = self._param(("cw", module), lambda: torch.from_numpy(np.array(p.weight, np.float32))) | |
| bt = self._param(("cb", module), lambda: None if p.bias is None else torch.from_numpy(np.array(p.bias, np.float32))) | |
| t, l, bo, r = p.pads | |
| if t != bo or l != r: | |
| x = F.pad(x, (l, r, t, bo)) | |
| pad = 0 | |
| else: | |
| pad = (t, l) | |
| return F.conv2d(x, wt, bt, stride=tuple(p.strides), padding=pad, dilation=tuple(p.dilations), groups=p.group) | |
| def gemm(self, module: str, x): | |
| torch, _ = _torch() | |
| w, b = self.w.gemm(module) | |
| wt = self._param(("gw", module), lambda: torch.from_numpy(w.copy())) | |
| bt = self._param(("gb", module), lambda: torch.from_numpy(b.copy())) | |
| return x @ wt.T + bt | |
| def linear(self, module: str, x): | |
| torch, _ = _torch() | |
| w, b = self.w.linear(module) | |
| wt = self._param(("lw", module), lambda: torch.from_numpy(w.copy())) | |
| bt = self._param(("lb", module), lambda: torch.from_numpy(b.copy())) | |
| return x @ wt + bt | |
| def resblock(self, prefix: str, x, relu_out: bool = True): | |
| torch, _ = _torch() | |
| a = torch.relu(self.conv(f"{prefix}/a/a.0", x)) | |
| y = x + self.conv(f"{prefix}/b/b.0", a) | |
| return torch.relu(y) if relu_out else y | |
| def basic(self, prefix: str, x, downsample: bool): | |
| torch, _ = _torch() | |
| h = torch.relu(self.conv(f"{prefix}/conv1", x)) | |
| h = self.conv(f"{prefix}/conv2", h) | |
| idt = self.conv(f"{prefix}/downsample/downsample.0", x) if downsample else x | |
| return torch.relu(h + idt) | |
| def resize_nearest(self, x, size): | |
| torch, _ = _torch() | |
| h, w = x.shape[-2:] | |
| key = (h, w) + tuple(size) | |
| if key not in self._idx: | |
| self._idx[key] = (torch.from_numpy(nearest_index(h, size[0])), torch.from_numpy(nearest_index(w, size[1]))) | |
| ih, iw = self._idx[key] | |
| return x.index_select(-2, ih).index_select(-1, iw) | |
| # ------------------------------------------------------------------ stages | |
| def image(self, imgs_u8, taps: Dict[str, Any]): | |
| torch, F = _torch() | |
| x = imgs_u8.reshape(C.N_CAM, 3, C.IMG_H, C.IMG_W).to(torch.float32) | |
| mean = torch.tensor(C.IMAGENET_MEAN, dtype=torch.float32).view(1, 3, 1, 1) | |
| std = torch.tensor(C.IMAGENET_STD, dtype=torch.float32).view(1, 3, 1, 1) | |
| x = ((x / 255.0) - mean) / std | |
| taps["img.input"] = x | |
| s = torch.relu(self.conv("stem/stem.0", x)) | |
| s = F.max_pool2d(s, 3, 2, 1) | |
| s = self.basic("stem/stem.4/stem.4.0", s, False) | |
| c1 = self.basic("stem/stem.4/stem.4.1", s, False) | |
| c2 = self.basic("l2/l2.1", self.basic("l2/l2.0", c1, True), False) | |
| c3 = self.basic("l3/l3.1", self.basic("l3/l3.0", c2, True), False) | |
| c4 = self.basic("l4/l4.1", self.basic("l4/l4.0", c3, True), False) | |
| taps.update({"img.c1": c1, "img.c2": c2, "img.c3": c3, "img.c4": c4}) | |
| p3 = self.conv("lat3", c3) + self.resize_nearest(self.conv("lat4", c4), c3.shape[-2:]) | |
| p2 = self.conv("lat2", c2) + self.resize_nearest(p3, c2.shape[-2:]) | |
| sm = torch.relu(self.conv("smooth/smooth.0", p2)) | |
| p1 = self.resize_nearest(sm, c1.shape[-2:]) + self.conv("lat1", c1) | |
| fx = self.resblock("f_x", p1) | |
| taps["img.fpn"] = fx | |
| return c1, fx | |
| def heads2d(self, c1, fx, taps): | |
| torch, _ = _torch() | |
| seg = self.conv("seg2d", fx) | |
| ctx = self.conv("ctx/ctx.1", torch.relu(self.conv("ctx/ctx.0/ctx.0.0", fx))) | |
| ctx = ctx + self.conv("", torch.softmax(seg, dim=1)) | |
| ctx = self.resblock("pp_mix", ctx, relu_out=False) | |
| d = torch.relu(self.conv("depth.0/depth.0.0", fx)) | |
| d = self.resblock("depth_x", d) | |
| dl = self.conv("depth.1", d) | |
| prob = torch.softmax(dl, dim=1) | |
| paint = torch.relu(self.conv("paint/paint.0", c1)) | |
| taps.update({"seg2d.logits": seg, "ctx": ctx, "depth.logits": dl, "depth.prob": prob, "paint.feat": paint}) | |
| return seg, ctx, dl, prob, paint | |
| def polar(self, ctx, prob): | |
| torch, _ = _torch() | |
| # /MatMul over the image rows per (camera, column): [8, 288, 64c, 162] @ [8, 288, 162, 64b] -> [8, 64c, 64b, 288] | |
| m = torch.matmul(ctx.permute(0, 3, 1, 2), prob.permute(0, 3, 2, 1)) * 0.5 | |
| return m.permute(0, 2, 3, 1).contiguous() | |
| def lift_gather(self, polar, K, T, taps): | |
| torch, F = _torch() | |
| g = lift_geometry(K, T, self.pts) | |
| col = g["col"] / np.float32(C.FEAT_W - 1) * np.float32(2.0) - np.float32(1.0) | |
| bn = g["bin"] / np.float32(C.N_BINS - 1) * np.float32(2.0) - np.float32(1.0) | |
| grid = torch.from_numpy(np.stack([col, bn], -1)[:, :, None, :].astype(np.float32)) | |
| s = F.grid_sample(polar, grid, mode="bilinear", padding_mode="zeros", align_corners=True)[..., 0] | |
| valid = torch.from_numpy(g["valid"].astype(np.float32)) | |
| num = (s * valid[:, None, :]).sum(0) | |
| den = torch.clamp(valid.sum(0), min=1.0) | |
| taps["lift.valid"] = valid | |
| return (num / den).reshape(1, C.C_CTX, C.BEV_H, C.BEV_W) | |
| def paint_gather(self, paint, K, T, taps): | |
| torch, F = _torch() | |
| g = paint_geometry(K, T, self.pts, self.z_fill) | |
| gx = g["rc"].astype(np.float32) / np.float32(C.FEAT_W - 1) * np.float32(2.0) - np.float32(1.0) | |
| gy = g["rr"].astype(np.float32) / np.float32(C.FEAT_H - 1) * np.float32(2.0) - np.float32(1.0) | |
| grid = torch.from_numpy(np.stack([gx, gy], -1)[:, :, None, :].astype(np.float32)) | |
| s = F.grid_sample(paint, grid, mode="nearest", padding_mode="zeros", align_corners=True)[..., 0] | |
| valid = torch.from_numpy(g["valid"].astype(np.float32)) | |
| num = (s * valid[:, None, :]).sum(0) | |
| den = torch.clamp(valid.sum(0), min=1.0) | |
| taps["paint.valid"] = valid | |
| return (num / den).reshape(1, C.C_PAINT, C.BEV_H, C.BEV_W) | |
| def lift_lowrank(self, lift: LowRankLift, x): | |
| """x [N, C, H, W] -> [1, C, 400, 250] with the parsed block terms (fp32 matmuls, the graph's order).""" | |
| torch, _ = _torch() | |
| key = ("lr", lift.prefix) | |
| if key not in self._t: | |
| self._t[key] = [[(t.cam, t.rows, t.cols, torch.from_numpy(t.u), torch.from_numpy(t.v)) for t in b] | |
| for b in lift.blocks] | |
| c = x.shape[1] | |
| bh, bw = lift.block | |
| gh, gw = lift.grid | |
| blocks = [] | |
| for terms in self._t[key]: | |
| acc = None | |
| for cam, rows, cols, u, v in terms: | |
| s = x[cam, :, rows[0]:rows[1], cols[0]:cols[1]].reshape(1, c, -1) | |
| y = (s @ u) @ v | |
| acc = y if acc is None else acc + y | |
| blocks.append(acc) | |
| st = torch.cat(blocks, 0).reshape(1, gh, gw, c, bh, bw) | |
| return st.permute(0, 3, 1, 4, 2, 5).reshape(1, c, gh * bh, gw * bw) | |
| def bev(self, lift, paint_bev, v0, acc, ego_hist, route, taps): | |
| torch, F = _torch() | |
| out: Dict[str, Any] = {} | |
| b0 = torch.relu(self.conv("b0/b0.0/b0.0.0", lift)) | |
| b0 = self.resblock("b0/b0.1", b0) | |
| b1 = torch.relu(self.conv("b1/b1.0/b1.0.0", b0)) | |
| for k in (1, 2, 3): | |
| b1 = self.resblock(f"b1/b1.{k}", b1) | |
| up = self.resize_nearest(self.conv("up_lat", b1), b0.shape[-2:]) | |
| f = torch.relu(self.conv("fuse/fuse.0/fuse.0.0", b0 + up)) | |
| fuse = self.resblock("fuse/fuse.1", f) | |
| taps.update({"bev.b0": b0, "bev.b1": b1, "bev.fuse": fuse}) | |
| # detection | |
| d = torch.relu(self.conv("det/det.0/det.0.0", fuse)) | |
| d = self.resblock("det/det.2", self.resblock("det/det.1", d)) | |
| taps["det.feat"] = d | |
| out["hm"] = self.conv("hm", fuse) + self.conv("hm_x", d) | |
| out["reg"] = self.conv("reg", fuse) + self.conv("reg_x", d) | |
| out["stationary"] = self.conv("stationary", fuse) | |
| out["risk"] = self.conv("risk", fuse) | |
| out["traj"] = self.conv("traj/traj.1", torch.relu(self.conv("traj/traj.0/traj.0.0", fuse))) | |
| # lanes | |
| l0 = self.resblock("seg_x0", torch.relu(self.conv("lane.0/lane.0.0", fuse))) | |
| lane_hw = (C.LANE_H, C.LANE_W) | |
| pu = self.resize_nearest(paint_bev, lane_hw) | |
| g = self.conv("gipm_proj/gipm_proj.1", torch.relu(self.conv("gipm_proj/gipm_proj.0/gipm_proj.0.0", pu))) | |
| a13 = self.resize_nearest(l0, lane_hw) + g | |
| taps["lane.up"] = a13 | |
| s = self.resblock("seg_x1", torch.relu(self.conv("seg_up/seg_up.0", a13))) | |
| out["lane_logit"] = self.conv("lane.2", a13) + self.conv("seg_o", s) | |
| # ego / traffic light | |
| e = torch.relu(self.conv("ego_stem/ego_stem.0/ego_stem.0.0", b1)) | |
| e = torch.relu(self.conv("ego_stem/ego_stem.1/ego_stem.1.0", e)) | |
| e = F.avg_pool2d(e, (10, 8), (10, 8)) | |
| flat = e.reshape(1, -1) | |
| taps["ego.flat"] = flat | |
| out["tl"] = self.gemm("tl", flat) | |
| v0t = torch.as_tensor(np.asarray(v0, np.float32).reshape(1, 1)) | |
| cat6 = torch.cat([flat, v0t], 1) | |
| eh = torch.as_tensor(np.asarray(ego_hist, np.float32).reshape(1, C.EGO_HIST)) | |
| h = self.gemm("ego_mlp.0", cat6) + self.gemm( | |
| "ae_hist_mlp/ae_hist_mlp.2", torch.relu(self.gemm("ae_hist_mlp/ae_hist_mlp.0", eh))) | |
| h = torch.relu(h) | |
| ego = self.gemm("ego_mlp.2", h) | |
| out["ego"] = ego | |
| tok = self.conv("ego_kin_bevtok", b1) # [1, 16, 200, 125] | |
| tok = torch.matmul(torch.matmul(self.kin_ph, tok), self.kin_pw) # [1, 16, 16, 10] | |
| bp = torch.relu(self.gemm("ego_kin_bevproj/ego_kin_bevproj.0", tok.reshape(1, -1))) | |
| bp = torch.relu(self.gemm("ego_kin_bevproj/ego_kin_bevproj.2", bp)) | |
| acct = torch.as_tensor(np.asarray(acc, np.float32).reshape(1, 1)) / 3.0 | |
| cat7 = torch.cat([cat6, h, eh, acct, bp], 1) # [1, 3106] | |
| traj12 = ego[:, 0:36].reshape(1, 3, 12) | |
| score = ego[:, 36:39].reshape(1, 3, 1) | |
| rt = torch.as_tensor(np.asarray(route, np.float32).reshape(1, 1, C.ROUTE)).expand(1, 3, C.ROUTE) | |
| kin_in = torch.cat([cat7[:, None, :].expand(1, 3, cat7.shape[1]), traj12 / 10.0, score, rt], 2) | |
| taps["ego.kin_in"] = kin_in | |
| k = torch.relu(self.linear("ego_kin/ego_kin.0", kin_in)) | |
| k = torch.relu(self.linear("ego_kin/ego_kin.2", k)) | |
| k = self.linear("ego_kin/ego_kin.4", k) # [1, 3, 26] | |
| gate = float(np.float32(np.asarray(v0, np.float32).reshape(-1)[0]) >= np.float32(C.V_GATE)) | |
| tail = torch.matmul(traj12, self.path_a) + gate * torch.matmul(k[:, :, 0:12], self.path_b) | |
| out["ego_path_6s"] = torch.cat([traj12.reshape(1, 3, 6, 2), tail.reshape(1, 3, 6, 2)], 2) | |
| # occupancy | |
| c = fuse[:, :, C.OCC_ROWS[0]:C.OCC_ROWS[1], C.OCC_COLS[0]:C.OCC_COLS[1]] | |
| o = torch.relu(self.conv("occ_stem/occ_stem.0", c)) | |
| m = self.conv("occ_mid/occ_mid.1", torch.relu(self.conv("occ_mid/occ_mid.0/occ_mid.0.0", o))) | |
| o = torch.relu(o + m) | |
| if self.has_occ_mid2: # Gather form only: two more residual blocks | |
| o = self.resblock("occ_mid2/occ_mid2.1", self.resblock("occ_mid2/occ_mid2.0", o)) | |
| taps["occ.feat"] = o | |
| out["occ_logit"] = self.conv("occ_head", o).reshape(1, C.N_OCC_CLASSES, C.OCC_Z, C.OCC_H, C.OCC_W) | |
| return out | |
| # ------------------------------------------------------------------ whole graph | |
| def forward(self, imgs, K=None, T_cam_ego=None, v0=0.0, acc=0.0, ego_hist=None, route=None, | |
| taps: Optional[Dict[str, Any]] = None, numpy_out: bool = True) -> Dict[str, Any]: | |
| torch, _ = _torch() | |
| taps = {} if taps is None else taps | |
| ego_hist = np.zeros(C.EGO_HIST, np.float32) if ego_hist is None else ego_hist | |
| route = np.zeros(C.ROUTE, np.float32) if route is None else route | |
| with torch.no_grad(): | |
| imgs_t = torch.as_tensor(np.asarray(imgs, np.uint8)) | |
| c1, fx = self.image(imgs_t, taps) | |
| seg, ctx, dl, prob, paint = self.heads2d(c1, fx, taps) | |
| polar = self.polar(ctx, prob) | |
| taps["lift.polar"] = polar | |
| if self.form == "gather": | |
| if K is None or T_cam_ego is None: | |
| raise ValueError("the gather form needs K and T_cam_ego") | |
| K8 = np.asarray(K, np.float32).reshape(C.N_CAM, 3, 3) | |
| T8 = np.asarray(T_cam_ego, np.float32).reshape(C.N_CAM, 4, 4) | |
| lift = self.lift_gather(polar, K8, T8, taps) | |
| pbev = self.paint_gather(paint, K8, T8, taps) | |
| else: | |
| lift = self.lift_lowrank(self.vt, polar) | |
| pbev = self.lift_lowrank(self.gvt, paint) | |
| taps["lift.bev"] = lift | |
| taps["paint.bev"] = pbev | |
| out = self.bev(lift, pbev, v0, acc, ego_hist, route, taps) | |
| out["depth_logit"] = dl.reshape(1, C.N_CAM, C.N_BINS, C.FEAT_H, C.FEAT_W) | |
| out["seg2d_logit"] = seg.reshape(1, C.N_CAM, C.C_SEG2D, C.FEAT_H, C.FEAT_W) | |
| out["hm2d"] = self.conv("hm2d", fx).reshape(1, C.N_CAM, 10, C.FEAT_H, C.FEAT_W) | |
| out["reg2d"] = self.conv("reg2d", fx).reshape(1, C.N_CAM, 4, C.FEAT_H, C.FEAT_W) | |
| if numpy_out: | |
| out = {k: v.numpy() for k, v in out.items()} | |
| return {k: out[k] for k in C.OUTPUT_NAMES} | |
| __call__ = forward | |