ConsDrive / models /detector.py
ZenoNing's picture
Upload ConsDrive v2 source (part 2)
314ecfb verified
Raw History Blame Contribute Delete
13.1 kB
"""Stage 2: two-frame monocular 3D detector on the FastVLM vision tower (FastViTHD).
CenterNet-style head at stride 8 on an FPN over the FastViTHD stages (stride 8/16/32/64). Per class
heatmap peaks give the projected 3D box centre; the same cell regresses the sub-pixel offset, the
camera-frame depth (Laplace NLL, so every detection carries a depth uncertainty for the tracker),
log half extents and the allocentric heading. A motion branch correlates the current features with
those of the frame 0.25 s earlier (local cost volumes at stride 16 and 32, conditioned on the ego
motion) and regresses the object's velocity in the current ego frame, also with an uncertainty.
Decoded detections are rows in the object-bank convention (dataloader.object_bank): x forward,
y right, heading and speed along the heading, half extents, class.
"""
import math
import os
import sys
import torch
import torch.nn.functional as F
from torch import nn
from dataloader.detection_data import (
CAMERA_X, CAMERA_Z, FOCAL, GRID_H, GRID_W, IMAGE_H, IMAGE_W, STRIDE, T_COS, T_LOG_DEPTH, T_LOG_H, T_LOG_L,
T_LOG_W, T_OFF_U, T_OFF_V, T_SIN, T_VX, T_VY,
)
from dataloader.object_bank import NUM_CLASSES
# index in FastViT.network after which the stride-8/16/32/64 stage outputs are taken
FASTVIT_STAGE_INDEX = {8: 2, 16: 4, 32: 7, 64: 10}
FASTVIT_CHANNELS = {8: 192, 16: 384, 32: 768, 64: 1536}
FASTVLM_PREFIX = "model.vision_tower.vision_tower.model."
LIGHTNING_PREFIX = "vision_model.image_encoder.vision_tower.model."
def build_fastvithd(init="pretrained/FastVLM-0.5B", source=None):
"""FastViTHD with weights from a FastVLM checkpoint directory or a driving-model .ckpt."""
source = source or os.environ.get("FASTVLM_SOURCE", "/workspace/code/ml-fastvlm")
if source not in sys.path:
sys.path.insert(0, source)
from llava.model.multimodal_encoder.mobileclip.mci import fastvithd
model = fastvithd()
if os.path.isdir(init):
from safetensors.torch import load_file
state = load_file(os.path.join(init, "model.safetensors"))
prefix = FASTVLM_PREFIX
else:
state = torch.load(init, map_location="cpu", weights_only=False)["state_dict"]
prefix = LIGHTNING_PREFIX
state = {k[len(prefix):]: v.float() for k, v in state.items()
if k.startswith(prefix) and not k[len(prefix):].startswith(("conv_exp.", "head."))}
missing, unexpected = model.load_state_dict(state, strict=False)
missing = [k for k in missing if not k.startswith(("conv_exp.", "head."))]
if missing or unexpected:
raise RuntimeError(f"FastViTHD weights from {init}: missing {missing[:5]}, unexpected {unexpected[:5]}")
# the classification tail is never used
model.conv_exp, model.head = nn.Identity(), nn.Identity()
return model
def conv_block(cin, cout, k=3, dilation=1):
return nn.Sequential(nn.Conv2d(cin, cout, k, padding=dilation * (k // 2), dilation=dilation, bias=False),
nn.GroupNorm(16, cout), nn.ReLU(inplace=True))
class FPN(nn.Module):
def __init__(self, channels=128):
super().__init__()
self.lateral = nn.ModuleDict({str(s): nn.Conv2d(c, channels, 1) for s, c in FASTVIT_CHANNELS.items()})
self.smooth = nn.ModuleDict({str(s): conv_block(channels, channels) for s in FASTVIT_CHANNELS})
def forward(self, feats):
out, top = {}, None
for s in sorted(FASTVIT_CHANNELS, reverse=True):
x = self.lateral[str(s)](feats[s])
if top is not None:
x = x + F.interpolate(top, size=x.shape[-2:], mode="bilinear", align_corners=False)
top = self.smooth[str(s)](x)
out[s] = top
return out
def local_correlation(a, b, radius):
"""Cost volume <a(p), b(p + d)> / sqrt(C) for |d|_inf <= radius: [B, (2r+1)^2, H, W]."""
_, c, h, w = a.shape
k = 2 * radius + 1
b = F.unfold(F.pad(b, (radius,) * 4), kernel_size=k).view(a.shape[0], c, k * k, h, w)
return (a.unsqueeze(2) * b).sum(1) / math.sqrt(c)
def head(cin, cout, hidden=128, bias=0.0):
layer = nn.Conv2d(hidden, cout, 1)
nn.init.constant_(layer.bias, bias)
return nn.Sequential(conv_block(cin, hidden), conv_block(hidden, hidden), layer)
def ray_grid(device):
"""Per-cell viewing-ray slopes (right, up) at stride 8: [1, 2, GRID_H, GRID_W]."""
u = (torch.arange(GRID_W, device=device) + 0.5) * STRIDE
v = (torch.arange(GRID_H, device=device) + 0.5) * STRIDE
ru = ((u - IMAGE_W / 2) / FOCAL)[None].expand(GRID_H, GRID_W)
rv = (-(v - IMAGE_H / 2) / FOCAL)[:, None].expand(GRID_H, GRID_W)
return torch.stack((ru, rv))[None]
class TwoFrameDetector(nn.Module):
# outputs per cell
OUT_OFFSET, OUT_DEPTH, OUT_SIZE, OUT_ORIENT, OUT_VEL = 2, 2, 3, 2, 4
def __init__(self, init="pretrained/FastVLM-0.5B", channels=128, corr_radius=4, freeze_backbone=False):
super().__init__()
self.backbone = build_fastvithd(init)
self.freeze_backbone = bool(freeze_backbone)
if self.freeze_backbone:
self.backbone.requires_grad_(False)
self.fpn = FPN(channels)
self.corr_radius = corr_radius
n_corr = (2 * corr_radius + 1) ** 2
c_app = channels + 2
self.heatmap = head(c_app, NUM_CLASSES, bias=-2.19)
self.box = head(c_app, self.OUT_OFFSET + self.OUT_DEPTH + self.OUT_SIZE + self.OUT_ORIENT)
# motion: cost volumes at stride 16 and 32 + current features + ego motion, upsampled to stride 8
self.motion16 = nn.Sequential(conv_block(2 * n_corr + channels + 4, channels),
conv_block(channels, channels, dilation=2), conv_block(channels, channels))
self.velocity = head(2 * channels + 2 + 4, self.OUT_VEL)
def backbone_features(self, images):
"""uint8 [B, 3, H, W] (any size, 2:1) -> FPN levels {stride: [B, C, h, w]}."""
x = F.interpolate(images.float() / 255.0, size=(IMAGE_H, IMAGE_W), mode="bilinear",
align_corners=False, antialias=True)
x = self.backbone.patch_embed(x)
feats = {}
for i, block in enumerate(self.backbone.network):
x = block(x)
for s, idx in FASTVIT_STAGE_INDEX.items():
if idx == i:
feats[s] = x
if i >= FASTVIT_STAGE_INDEX[64]:
break
return feats
def forward(self, image, image_prev=None, ego_motion=None, prev_pyramid=None):
"""Returns (outputs dict at stride 8, current FPN pyramid for reuse as the next prev_pyramid)."""
if self.freeze_backbone:
with torch.no_grad():
feats = self.backbone_features(image)
else:
feats = self.backbone_features(image)
pyramid = self.fpn(feats)
if prev_pyramid is None:
with torch.no_grad():
prev_pyramid = self.fpn(self.backbone_features(image_prev))
b = image.shape[0]
rays = ray_grid(image.device).expand(b, -1, -1, -1).to(pyramid[8].dtype)
app = torch.cat((pyramid[8], rays), 1)
ego = torch.stack((ego_motion[:, 0] / 5.0, ego_motion[:, 1] / 2.0, ego_motion[:, 2] * 5.0,
ego_motion[:, 3] / 10.0), 1).to(app.dtype)
r = self.corr_radius
c16 = local_correlation(pyramid[16], prev_pyramid[16], r)
c32 = F.interpolate(local_correlation(pyramid[32], prev_pyramid[32], r), size=c16.shape[-2:],
mode="bilinear", align_corners=False)
ego16 = ego[:, :, None, None].expand(-1, -1, *c16.shape[-2:])
m16 = self.motion16(torch.cat((c16, c32, pyramid[16], ego16), 1))
m8 = F.interpolate(m16, size=app.shape[-2:], mode="bilinear", align_corners=False)
ego8 = ego[:, :, None, None].expand(-1, -1, *app.shape[-2:])
box = self.box(app)
out = dict(
heatmap=self.heatmap(app),
offset=box[:, 0:2],
depth=box[:, 2:4], # log depth, log scale
size=box[:, 4:7],
orient=box[:, 7:9],
velocity=self.velocity(torch.cat((pyramid[8], m8, rays, ego8), 1)), # vx, vy, log scale x/y
)
return out, pyramid
def load_detector(path, device):
"""TwoFrameDetector from a train_detector.py checkpoint, in eval mode."""
ckpt = torch.load(path, map_location="cpu", weights_only=False)
args = ckpt.get("args", {})
model = TwoFrameDetector(init=args.get("init", "pretrained/FastVLM-0.5B"),
freeze_backbone=args.get("freeze_backbone", False))
model.load_state_dict(ckpt["model"])
return model.to(device).eval()
# ---------------------------------------------------------------------------------------- losses
def focal_loss(logits, target, ignore):
pred = torch.sigmoid(logits.float()).clamp(1e-4, 1 - 1e-4)
pos = target.eq(1).float()
neg = (1 - pos) * (ignore[:, None] < 0.3).float()
pos_loss = torch.log(pred) * (1 - pred) ** 2 * pos
neg_loss = torch.log(1 - pred) * pred ** 2 * (1 - target) ** 4 * neg
n = pos.sum().clamp(min=1.0)
return -(pos_loss.sum() + neg_loss.sum()) / n
def gather(feature, index):
"""[B, C, H, W], [B, K] -> [B, K, C]"""
b, c = feature.shape[:2]
return feature.view(b, c, -1).gather(2, index[:, None].expand(-1, c, -1)).transpose(1, 2).float()
def l1_and_scale(pred, log_scale, target):
"""L1 on the mean plus a Laplace NLL that only trains the scale. With a plain NLL the rare hard
targets (moving objects among mostly parked ones) get an inflated scale instead of a mean."""
log_scale = log_scale.clamp(-5.0, 5.0)
err = (pred - target).abs()
return err + err.detach() * torch.exp(-log_scale) + log_scale
def detection_loss(out, batch, weights=None):
w = dict(heatmap=1.0, offset=1.0, depth=1.0, size=0.5, orient=0.5, velocity=0.5)
w.update(weights or {})
mask = batch["mask"]
n = mask.sum().clamp(min=1.0)
index, target = batch["index"], batch["target"]
off, dep = gather(out["offset"], index), gather(out["depth"], index)
size, ori, vel = gather(out["size"], index), gather(out["orient"], index), gather(out["velocity"], index)
m = mask[..., None]
losses = dict(
heatmap=focal_loss(out["heatmap"], batch["heatmap"], batch["ignore"]),
offset=((off - target[..., [T_OFF_U, T_OFF_V]]).abs() * m).sum() / n,
depth=(l1_and_scale(dep[..., 0], dep[..., 1], target[..., T_LOG_DEPTH]) * mask).sum() / n,
size=((size - target[..., [T_LOG_L, T_LOG_W, T_LOG_H]]).abs() * m).sum() / n,
orient=((ori - target[..., [T_SIN, T_COS]]).abs() * m).sum() / n,
velocity=(l1_and_scale(vel[..., 0:2], vel[..., 2:4], target[..., [T_VX, T_VY]]) * m).sum() / n,
)
losses["total"] = sum(w[k] * v for k, v in losses.items())
return losses
# ---------------------------------------------------------------------------------------- decoding
@torch.no_grad()
def decode(out, score_threshold=0.3, max_detections=64):
"""Detections per image: list of dicts of tensors (x, y, z, yaw, speed, vx, vy, half extents, class,
score, depth_sigma, velocity_sigma) in the ego frame of the current image."""
heat = torch.sigmoid(out["heatmap"].float())
peaks = heat * (F.max_pool2d(heat, 3, stride=1, padding=1) == heat).float()
b, c, h, w = peaks.shape
scores, flat = peaks.view(b, -1).topk(max_detections)
cls = flat // (h * w)
cell = flat % (h * w)
iy, ix = (cell // w).float(), (cell % w).float()
results = []
for i in range(b):
keep = scores[i] >= score_threshold
idx = cell[i][keep][None]
off = gather(out["offset"][i:i + 1], idx)[0]
dep = gather(out["depth"][i:i + 1], idx)[0]
size = gather(out["size"][i:i + 1], idx)[0]
ori = gather(out["orient"][i:i + 1], idx)[0]
vel = gather(out["velocity"][i:i + 1], idx)[0]
u = (ix[i][keep] + off[:, 0]) * STRIDE
v = (iy[i][keep] + off[:, 1]) * STRIDE
depth = torch.exp(dep[:, 0])
yc = (u - IMAGE_W / 2) * depth / FOCAL
zc = -(v - IMAGE_H / 2) * depth / FOCAL
alpha = torch.atan2(ori[:, 0], ori[:, 1])
yaw = alpha + torch.atan2(yc, depth)
vx, vy = vel[:, 0], vel[:, 1]
speed = torch.hypot(vx, vy)
# heading from appearance is ambiguous front/back; trust the motion when the object moves
moving_dir = torch.atan2(vy, vx)
flip = (speed > 1.0) & (torch.cos(moving_dir - yaw) < 0)
yaw = torch.where(flip, yaw + math.pi, yaw)
yaw = torch.atan2(torch.sin(yaw), torch.cos(yaw))
ext = torch.exp(size)
results.append(dict(
x=depth + CAMERA_X, y=yc, z=zc + CAMERA_Z, yaw=yaw, speed=speed, vx=vx, vy=vy,
half_l=ext[:, 0], half_w=ext[:, 1], half_h=ext[:, 2], cls=cls[i][keep], score=scores[i][keep],
depth_sigma=torch.exp(dep[:, 1].clamp(-5, 5)) * depth, # Laplace scale of log depth -> metres
velocity_sigma=torch.exp(vel[:, 2:4].clamp(-5, 5)),
))
return results