diff --git a/models/adaptors/__init__.py b/models/adaptors/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/models/adaptors/__init__.py @@ -0,0 +1 @@ + diff --git a/models/adaptors/adaptors.py b/models/adaptors/adaptors.py new file mode 100644 index 0000000000000000000000000000000000000000..6e71dcf905edc8eb0582eae6fde4fcd7f29f39a5 --- /dev/null +++ b/models/adaptors/adaptors.py @@ -0,0 +1,363 @@ +from typing import Dict, List, Optional, Tuple + +import torch +import torch.nn.functional as F +from torch import Tensor, nn + +from utils.custom_types import DrivingExample + + +def compute_waypoint_loss( + prediction: Tensor, + label: Tensor, + loss_fn: str = "mse", + smooth_l1_beta: float = 1.0, +) -> Tensor: + """Per-sample waypoint loss averaged over waypoints; last dim is (x, y) or distance.""" + if loss_fn == "mse": + return F.mse_loss(prediction, label, reduction="none").sum(-1).mean(-1) + if loss_fn == "smooth_l1": + return F.smooth_l1_loss( + prediction, + label, + beta=smooth_l1_beta, + reduction="none", + ).sum(-1).mean(-1) + raise ValueError(f"waypoint_loss_fn must be 'mse' or 'smooth_l1', not {loss_fn!r}") + + +class NormZeroOne(nn.Module): + def __init__(self, min_max: Tuple[float, float]): + super().__init__() + self.register_buffer("min_max", torch.tensor(min_max, dtype=torch.float), persistent=False) + + def forward(self, x: Tensor) -> Tensor: + """Normalise tensor to [0, 1] using values from min_max""" + return (x - self.min_max[0]) / (self.min_max[1] - self.min_max[0]) + + +class WaypointInputAdaptor(nn.Module): + """ + Takes an input of shape [B, N, 2] and returns an output of shape [B, N, token_size] + Args: + token_size: feature dimension of output tensor. + hidden_size: hidden dimension used in Linear layers under the hood. + norm_layer: the `Module` to use to normalize the values of the input tensor. + """ + + def __init__( + self, token_size: int = 258, hidden_size: int = 64, norm_layer: Optional[nn.Module] = None + ): + super().__init__() + self.hidden_size = hidden_size + self.norm_layer = norm_layer + self.mlp = nn.Sequential(nn.Linear(2, hidden_size), nn.ReLU(True), nn.Linear(hidden_size, token_size)) + + def forward(self, x: Tensor) -> Tensor: + """ + Args: + x: Input with dims [B, N, 2] + + Returns: + Output with dims [B, N, token_size] + """ + if self.norm_layer is not None: + x = self.norm_layer(x) + x = self.mlp(x) + return x + + +class VectorInputAdaptor(nn.Module): + """ + Takes an input of shape [B, input_size] and returns an output of shape [B, 1, token_size] + Args: + input_size: Expected feature dimension of input tensor. + token_size: feature dimension of output tensor. + hidden_size: hidden dimension used in Linear layers under the hood. + norm_layer: the `Module` to use to normalize the values of the input tensor. + """ + + def __init__( + self, + input_size: int, + token_size: int = 258, + hidden_size: int = 64, + norm_layer: Optional[nn.Module] = None, + ): + super().__init__() + # store args + self.hidden_size = hidden_size + self.input_size = input_size + self.norm_layer = norm_layer + # networks + self.mlp = nn.Sequential(nn.Linear(input_size, hidden_size), nn.ReLU(True), nn.Linear(hidden_size, token_size)) + + def forward(self, x: Tensor) -> Tensor: + """ + Args: + x: Input with dims [B, input_size] + + Returns: + Output with dims [B, 1, token_size] + """ + if self.norm_layer is not None: + x = self.norm_layer(x) + x = self.mlp(x).unsqueeze(1) + return x + +class DrivingAdaptor(nn.Module): + def __init__(self, + hidden_size: int, + mlp_dim=256, + predict_route_as_wps=False, + speed_wps_mode=False, + waypoint_loss_fn: str = "mse", + smooth_l1_beta: float = 1.0, + latent_tokens: int = 0, + ): + super().__init__() + self.heads = {} + self.queries = {} + self.sizes = {} + self.order = [] + + self.speed_wps_mode = speed_wps_mode + self.predict_route_as_wps = predict_route_as_wps + self.waypoint_loss_fn = waypoint_loss_fn + self.smooth_l1_beta = smooth_l1_beta + + # Latent world-model queries: no prediction head, the LM hidden states + # at these positions are supervised through the world predictor. + # Placed first so route/speed queries can attend to them (causal LM). + self.num_latent_tokens = int(latent_tokens) + if self.num_latent_tokens > 0: + self.query_embeds_latent = nn.Parameter( + 0.02 * torch.randn((1, self.num_latent_tokens, hidden_size)) + ) + self.queries['latent'] = self.query_embeds_latent + self.sizes['latent'] = self.num_latent_tokens + self.order.append('latent') + + if predict_route_as_wps: + self.future_waypoints = 20 + self.query_embeds_wps = nn.Parameter(0.02 * torch.randn((1, self.future_waypoints, hidden_size))) + self.route_head = nn.Sequential( + nn.Linear(hidden_size, mlp_dim), nn.SiLU(True), nn.Linear(mlp_dim, 2, bias=False) + ) + + self.queries['route'] = self.query_embeds_wps + self.sizes['route'] = self.future_waypoints + self.heads["route"] = self.route_head + self.order.append('route') + + if speed_wps_mode == '2d': + dim = 2 + elif speed_wps_mode == '1d': + dim = 1 + else: + raise ValueError(f"speed_wps_mode must be '1d' or '2d', not {speed_wps_mode}") + self.future_speed_waypoints = 10 + self.query_embeds_speed = nn.Parameter(0.02 * torch.randn((1, self.future_speed_waypoints, hidden_size))) + self.speed_wps_head = nn.Sequential( + nn.Linear(hidden_size, mlp_dim), nn.SiLU(True), nn.Linear(mlp_dim, dim, bias=False) + ) + self.heads["speed_wps"] = self.speed_wps_head + self.queries['speed_wps'] = self.query_embeds_speed + self.sizes['speed_wps'] = self.future_speed_waypoints + self.order.append('speed_wps') + + def _head_input(self, input_type: str, features: Tensor) -> Tensor: + head_dtype = next(self.heads[input_type].parameters()).dtype + return features.to(dtype=head_dtype) + + + def forward(self, + driving_example: DrivingExample, + **kwargs + ) -> Dict[str, Tensor]: + + try: + driving_input = driving_example.driving_input + except AttributeError: + driving_input = driving_example + + b = driving_input.vehicle_speed.shape[0] + inputs = None + + for input_type in self.order: + query_embed = self.queries[input_type] + if inputs is None: + inputs = query_embed.expand(b, -1, -1) + else: + inputs = torch.cat((inputs, query_embed.expand(b, -1, -1)), dim=1) + + inputs_mask = torch.ones_like(inputs[:, :, 0], dtype=torch.bool) + + return {"inputs": inputs, "inputs_mask": inputs_mask} + + def get_predictions( + self, + features: Tensor + ) -> Dict: + + current_index = 0 + predictions = {} + for i, input_type in enumerate(self.order): + size = self.sizes[input_type] + if input_type not in self.heads: + # latent world-model queries have no prediction head + current_index += size + continue + + feature = self._head_input(input_type, features[:, current_index: current_index + size]) + prediction = self.heads[input_type](feature).cumsum(1) + + predictions[input_type] = prediction + current_index += size + + return predictions + + + def compute_loss( + self, adaptor_features: Tensor, _inputs: Dict[str, Tensor], example: DrivingExample + ) -> Dict[str, Tuple[Tensor, Tensor]]: + label = example.driving_label + assert label is not None + + if self.predict_route_as_wps: + label_route = label.route_adjusted + else: + label_route = None + + if self.speed_wps_mode == '2d': + label_speed_wps = label.waypoints[:, : self.future_speed_waypoints] + elif self.speed_wps_mode == '1d': + label_speed_wps = label.waypoints_1d + else: + label_speed_wps = None + + current_index = 0 + loss_dict = {} + for i, input_type in enumerate(self.order): + size = self.sizes[input_type] + if input_type not in self.heads: + # expose the raw LM features (e.g. latent world-model tokens) + # to the caller instead of applying a head/loss + loss_dict[f"{input_type}_features"] = adaptor_features[:, current_index: current_index + size] + current_index += size + continue + features_tmp = self._head_input(input_type, adaptor_features[:, current_index: current_index + size]) + label = locals()[f'label_{input_type}'] + + prediction = self.heads[input_type](features_tmp).cumsum(1) + loss = compute_waypoint_loss( + prediction, + label, + loss_fn=self.waypoint_loss_fn, + smooth_l1_beta=self.smooth_l1_beta, + ) + + loss_dict[f"{input_type}_loss"] = (loss, torch.ones_like(loss, dtype=torch.long)) + loss_dict[f"{input_type}_prediction"] = prediction + loss_dict[f"{input_type}_label"] = label + current_index += size + + return loss_dict + +class AdaptorList(nn.Module): + """ + Each adaptor is responsible for converting a driving example + to a sequence of tokens and computing the loss on the token outputs. + Adaptors are only used during training. + """ + + def __init__( + self, + driving: Optional[DrivingAdaptor] = None, + ): + super().__init__() + self.driving = driving + + @property + def adaptors(self): + dct: Dict[str, Adaptor] = {} + if self.driving is not None: + dct["driving"] = self.driving + return dct + + def forward(self, example: DrivingExample) -> Dict[str, Tensor]: + """ + Construct input embeddings for the given driving example. + """ + + input_dict: Dict[str, Tensor] = {} + inputs_list: List[Tensor] = [] + inputs_mask_list: List[Tensor] = [] + + for key, adaptor in self.adaptors.items(): + adaptor_input_dict = adaptor.forward(example) + inputs_list.append(adaptor_input_dict["inputs"]) + inputs_mask_list.append(adaptor_input_dict["inputs_mask"]) + input_dict.update({key + "_" + k: v for k, v in adaptor_input_dict.items()}) + + inputs = torch.cat(inputs_list, dim=1) + inputs_mask = torch.cat(inputs_mask_list, dim=1) + split_sizes = torch.as_tensor([x.size(1) for x in inputs_list]) + arange = torch.arange(inputs.size(0), device=inputs.device)[:, None] + + # Apply random permutation of modalities during training + rand_perm = torch.arange(inputs.size(1), device=inputs.device).expand(inputs.size(0), -1) + # Apply permutation to move invalid tokens to end of sequence + valid_perm = inputs_mask[arange, rand_perm].byte().argsort(dim=-1, descending=True, stable=True) + perm = rand_perm.gather(1, valid_perm) + + input_dict["inputs"] = inputs[arange, perm] + input_dict["inputs_mask"] = inputs_mask[arange, perm] + input_dict["perm"] = perm + input_dict["split_sizes"] = split_sizes + return input_dict + + def compute_loss( + self, features: Tensor, input_dict: Dict[str, Tensor], example: DrivingExample + ) -> Dict[str, Tuple[Tensor, Tensor]]: + """ + Distributes the output embeddings from the transformer to + the correct loss function and returns a dictionary of losses. + """ + + features_by_adaptor = self.split_outputs_by_adaptor(input_dict, features) + + loss_dict: Dict[str, Tuple[Tensor, Tensor]] = {} + + # Compute loss in each adaptor + loss_dict: Dict[str, Tuple[Tensor, Tensor]] = {} + for key, adaptor in self.adaptors.items(): + adaptor_input_dict = _gather_from_dict(input_dict, key + "_") + adaptor_features = features_by_adaptor[key] + losses = adaptor.compute_loss(adaptor_features, adaptor_input_dict, example) + loss_dict.update(losses) + + return loss_dict + + def split_outputs_by_adaptor(self, input_dict: Dict[str, Tensor], outputs: Tensor) -> Dict[str, Tensor]: + """ + Splits the output tensor into the correct output for each adaptor, according to the + split_sizes in the input_dict. + """ + # First reverse permutation + inv_perm = input_dict["perm"].argsort(-1) + arange = torch.arange(inv_perm.size(0), device=inv_perm.device)[:, None] + outputs = outputs[arange, inv_perm] + + # Now split output for each adaptor + split_sizes = [int(x) for x in input_dict["split_sizes"]] + outputs_list = list(outputs.split(split_sizes, dim=1)) + return {key: outputs_list[i] for i, key in enumerate(self.adaptors.keys())} + + +def _gather_from_dict(d: Dict[str, Tensor], prefix: str): + out: Dict[str, Tensor] = {} # dict comprehensions with if not supported + for k, v in d.items(): + if k.startswith(prefix): + out[k[len(prefix) :]] = v + return out diff --git a/models/detector.py b/models/detector.py new file mode 100644 index 0000000000000000000000000000000000000000..0b110cff95d4dca745f55e89ba6488d5c147ed34 --- /dev/null +++ b/models/detector.py @@ -0,0 +1,274 @@ +"""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 / 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 diff --git a/models/detector_metrics.py b/models/detector_metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..7365854b60bde27b06917839cfd9e2a050dda688 --- /dev/null +++ b/models/detector_metrics.py @@ -0,0 +1,135 @@ +"""Detection metrics in the terms of the tracker acceptance criteria (BEV, per range bin). + +Predictions are matched greedily by score to the nearest unmatched labelled box within +1.5 m + 5 % of its range. Recall is reported against two ground truths: "positive" (bank-visible +and hit by the lidar, what the detector is trained on) and "bank" (bank-visible only, what the +oracle stage-3 model was given). A false positive is a prediction within range that matches no +labelled box at all, so detections of uncertain/ignored boxes are not counted against it. +""" +import numpy as np + +from dataloader.detection_data import CAMERA_X, is_positive +from dataloader.detection_labels import ( + OBJ_BANK_VISIBLE, OBJ_CLASS, OBJ_SPEED, OBJ_X, OBJ_Y, OBJ_YAW, +) + +RANGE_BINS = ((0, 10), (10, 20), (20, 30), (30, 40), (40, 50)) +CLASS_NAMES = ("car", "walker", "static") + + +def match(pred_xy, pred_score, gt_xy, gt_range): + """Greedy score-ordered matching; returns gt index per prediction (-1 unmatched).""" + assigned = np.full(len(pred_xy), -1, dtype=np.int64) + if len(pred_xy) == 0 or len(gt_xy) == 0: + return assigned + dist = np.linalg.norm(pred_xy[:, None] - gt_xy[None], axis=-1) + gate = 1.5 + 0.05 * gt_range + taken = np.zeros(len(gt_xy), dtype=bool) + for p in np.argsort(-pred_score): + d = np.where(taken | (dist[p] > gate), np.inf, dist[p]) + g = int(np.argmin(d)) + if np.isfinite(d[g]): + assigned[p] = g + taken[g] = True + return assigned + + +class DetectionMetrics: + def __init__(self, max_range=50.0, thresholds=(0.2, 0.3, 0.4, 0.5)): + self.max_range = max_range + self.thresholds = thresholds + self.frames = 0 + self.gt = [] # per labelled box: range, class, positive, bank, speed, matched-at-threshold..., errors + self.fp = {t: 0 for t in thresholds} + self.errors = [] # matched positives at the 0.3 threshold: range, class, pos err, lon, lat, vel err, speed, yaw err + + def add(self, gt_rows, det): + """gt_rows [N, OBJ_DIM] numpy; det: decoded dict of tensors for one image.""" + self.frames += 1 + det = {k: v.detach().float().cpu().numpy() for k, v in det.items()} + gt_xy = gt_rows[:, [OBJ_X, OBJ_Y]].astype(np.float64) + gt_range = np.hypot(gt_xy[:, 0] - CAMERA_X, gt_xy[:, 1]) + pos = is_positive(gt_rows, self.max_range) + bank = (gt_rows[:, OBJ_BANK_VISIBLE] > 0.5) & (gt_range <= self.max_range) + pred_xy = np.stack((det["x"], det["y"]), -1).astype(np.float64) + pred_range = np.hypot(pred_xy[:, 0] - CAMERA_X, pred_xy[:, 1]) + matched = {} + for t in self.thresholds: + keep = det["score"] >= t + a = match(pred_xy[keep], det["score"][keep], gt_xy, gt_range) + hit = np.zeros(len(gt_rows), dtype=bool) + hit[a[a >= 0]] = True + matched[t] = hit + self.fp[t] += int(((a < 0) & (pred_range[keep] <= self.max_range)).sum()) + if t == 0.3: + idx = np.flatnonzero(keep) + for p, g in zip(idx[a >= 0], a[a >= 0]): + if not pos[g]: + continue + d = pred_xy[p] - gt_xy[g] + ray = gt_xy[g] - (CAMERA_X, 0.0) + ray /= max(np.linalg.norm(ray), 1e-6) + gv = gt_rows[g, OBJ_SPEED] * np.array((np.cos(gt_rows[g, OBJ_YAW]), np.sin(gt_rows[g, OBJ_YAW]))) + yaw_err = abs((det["yaw"][p] - gt_rows[g, OBJ_YAW] + np.pi) % (2 * np.pi) - np.pi) + self.errors.append((gt_range[g], gt_rows[g, OBJ_CLASS], np.linalg.norm(d), d @ ray, + abs(d[0] * -ray[1] + d[1] * ray[0]), + np.linalg.norm((det["vx"][p], det["vy"][p]) - gv), gt_rows[g, OBJ_SPEED], + yaw_err, det["depth_sigma"][p], int(det["cls"][p] == gt_rows[g, OBJ_CLASS]))) + for g in range(len(gt_rows)): + self.gt.append((gt_range[g], gt_rows[g, OBJ_CLASS], pos[g], bank[g], gt_rows[g, OBJ_SPEED], + *[matched[t][g] for t in self.thresholds])) + + def summary(self): + gt = np.asarray(self.gt, dtype=np.float64).reshape(-1, 5 + len(self.thresholds)) + err = np.asarray(self.errors, dtype=np.float64).reshape(-1, 10) + out = dict(frames=self.frames, fp_per_frame={t: self.fp[t] / max(self.frames, 1) for t in self.thresholds}) + k30 = 5 + self.thresholds.index(0.3) + for c, name in enumerate(CLASS_NAMES): + rows = {} + for lo, hi in RANGE_BINS: + sel = (gt[:, 1] == c) & (gt[:, 0] >= lo) & (gt[:, 0] < hi) + p, b = sel & (gt[:, 2] > 0), sel & (gt[:, 3] > 0) + e = err[(err[:, 1] == c) & (err[:, 0] >= lo) & (err[:, 0] < hi)] + rows[f"{lo}-{hi}"] = dict( + n_pos=int(p.sum()), recall_pos=float(gt[p, k30].mean()) if p.any() else None, + recall_bank=float(gt[b, k30].mean()) if b.any() else None, + pos_err_med=float(np.median(e[:, 2])) if len(e) else None, + pos_err_p90=float(np.percentile(e[:, 2], 90)) if len(e) else None, + lon_err_med=float(np.median(np.abs(e[:, 3]))) if len(e) else None, + lat_err_med=float(np.median(e[:, 4])) if len(e) else None, + vel_err_med=float(np.median(e[:, 5])) if len(e) else None, + cls_acc=float(e[:, 9].mean()) if len(e) else None) + p50 = (gt[:, 1] == c) & (gt[:, 2] > 0) + rows["recall_pos_0-50_by_threshold"] = { + t: float(gt[p50, 5 + i].mean()) if p50.any() else None for i, t in enumerate(self.thresholds)} + out[name] = rows + cars = err[err[:, 1] == 0] + if len(cars): + speed_bins = {} + for lo, hi in ((0, 0.5), (0.5, 5), (5, 10), (10, 20)): + s = cars[(cars[:, 6] >= lo) & (cars[:, 6] < hi)] + if len(s): + speed_bins[f"{lo}-{hi}"] = dict(n=len(s), vel_err_med=float(np.median(s[:, 5])), + vel_err_p90=float(np.percentile(s[:, 5], 90)), + yaw_err_med_deg=float(np.degrees(np.median(s[:, 7])))) + out["car_velocity_by_speed"] = speed_bins + return out + + +def format_summary(s): + lines = [f"frames {s['frames']} FP/frame " + " ".join(f"@{t}: {v:.3f}" for t, v in s["fp_per_frame"].items())] + for name in CLASS_NAMES: + lines.append(f"{name:7s} range n_pos rec_pos rec_bank err_med err_p90 lon lat vel_err cls_acc") + for key, r in s[name].items(): + if key.startswith("recall_pos_0-50"): + lines.append(" recall_pos 0-50 by threshold: " + " ".join( + f"@{t}: {v:.3f}" for t, v in r.items() if v is not None)) + continue + f = lambda v, w=6, p=2: (f"{v:{w}.{p}f}" if v is not None else " " * (w - 1) + "-") # noqa: E731 + lines.append(f" {key:6s} {r['n_pos']:6d} {f(r['recall_pos'], 6, 3)} {f(r['recall_bank'], 6, 3)} " + f"{f(r['pos_err_med'])} {f(r['pos_err_p90'])} {f(r['lon_err_med'], 5)} " + f"{f(r['lat_err_med'], 5)} {f(r['vel_err_med'])} {f(r['cls_acc'], 5)}") + for key, r in s.get("car_velocity_by_speed", {}).items(): + lines.append(f"car speed {key:7s} n={r['n']:6d} vel_err med {r['vel_err_med']:.2f} p90 {r['vel_err_p90']:.2f}" + f" yaw_err med {r['yaw_err_med_deg']:.1f} deg") + return "\n".join(lines) diff --git a/models/driving.py b/models/driving.py new file mode 100644 index 0000000000000000000000000000000000000000..29317296e5e75e2e18f4cabfb2678228d3c0c134 --- /dev/null +++ b/models/driving.py @@ -0,0 +1,1195 @@ +import pickle as pkl +import warnings +from pprint import PrettyPrinter +from typing import Optional, Tuple + +import pytorch_lightning as pl +import torch +from torch import Tensor, nn +from torchvision.models import ResNet18_Weights, resnet18 + +try: + from deepspeed.ops.adam import FusedAdam +except ModuleNotFoundError: + FusedAdam = None + +from models.adaptors.adaptors import ( + AdaptorList, DrivingAdaptor, VectorInputAdaptor, WaypointInputAdaptor +) +from models.utils import configure_params_groups, summarise_losses +from models.plan_consequence import ( + PlanConditionedConsequenceHead, + PooledPlanConsequenceHead, + aggregate_risk_logits, + binary_waypoint_loss, + clearance_waypoint_loss, + expand_scene_for_plans, + make_hard_negative_plans, + pairwise_ranking_loss, + relative_min_clearance_hinge, + trajectory_geometry_targets, + visible_obstacle_mask, +) +from models.world_predictor import ( + BlockCausalWorldPredictor, linear_world_weight, masked_world_l1 +) +from utils.custom_types import ( + DrivingExample, DrivingInput, DrivingLabel, ParamGroup, TrainingOutput +) + +pprint = PrettyPrinter().pprint + +class RouteEncode(nn.Module): + def __init__(self, out_channels: int, pretrained=True): + super().__init__() + self.backbone = resnet18(weights=ResNet18_Weights.IMAGENET1K_V1 if pretrained else None) + self.backbone.fc = nn.Linear(self.backbone.fc.in_features, out_channels) + + def forward(self, route): + x = route.to(self.backbone.fc.weight.dtype) / 128.0 - 1.0 + return self.backbone(x).unsqueeze(-2) # add token dim + +class NormZeroOne(nn.Module): + def __init__(self, min_max: Tuple[float, float]): + super().__init__() + self.register_buffer("min_max", torch.tensor(min_max, dtype=torch.float), persistent=False) + + def forward(self, x: Tensor) -> Tensor: + """Normalise tensor to [0, 1] using values from min_max""" + return (x - self.min_max[0]) / (self.min_max[1] - self.min_max[0]) + + +class DrivingModel(pl.LightningModule): + def __init__( + self, + vision_model: nn.Module, + language_model: nn.Module, + lr: float = 1e-4, + vision_lr: Optional[float] = None, + lm_lr: Optional[float] = None, + weight_decay: float = 0.1, + betas: Tuple[float, float] = (0.9, 0.999), + pct_start: float = 0.05, + enable_language=False, + route_as=True, + speed_as_input=True, + new_layer_norm_minmax=False, + predict_route_as_wps=False, + speed_wps_mode=False, + waypoint_loss_fn: str = "mse", + smooth_l1_beta: float = 1.0, + variant=None, + nav_p_both: float = 0.4, + nav_p_command: float = 0.4, + nav_p_tp: float = 0.2, + jepa=None, + consequence=None, + vision_freeze_steps: int = 0, + vision_ramp_steps: int = 0, + speed_dropout_p: float = 0.0, + ): + super().__init__() + + self.save_hyperparameters(ignore=["vision_model", "language_model"]) + self.vision_model = vision_model + self.language_model = language_model + self.lr = lr + self.vision_lr = vision_lr + # optional separate LR for the LM trunk (pretrained-init small trunks + # want a lower LR than freshly initialised adaptors/heads) + self.lm_lr = lm_lr + self.weight_decay = weight_decay + self.betas = betas + self.pct_start = pct_start + self.enable_language = enable_language + self.route_as = route_as + self.speed_as_input = speed_as_input + self.new_layer_norm_minmax = new_layer_norm_minmax + self.predict_route_as_wps = predict_route_as_wps + self.speed_wps_mode = speed_wps_mode + self.waypoint_loss_fn = waypoint_loss_fn + self.smooth_l1_beta = smooth_l1_beta + # three-state navigation dropout probabilities (both / command-only / tp-only) + self.nav_probs = (nav_p_both, nav_p_command, nav_p_tp) + # training: hide the ego-speed token from this fraction of samples, so the policy can also act from + # the scene alone (the agent masks it while stalled to escape the v = 0 attractor of the speed input) + self.speed_dropout_p = float(speed_dropout_p) + self.vision_freeze_steps = int(vision_freeze_steps) + self.vision_ramp_steps = int(vision_ramp_steps) + + self.all_predictions = {} + self.all_losses = {} + + # V-JEPA2 world-model supervision on latent action queries + self.use_world_loss = bool(jepa is not None and jepa.get("enabled", False)) + latent_tokens = 0 + if self.use_world_loss: + self.latent_steps = int(jepa.get("latent_steps", 3)) + self.latent_tokens_per_step = int(jepa.get("latent_tokens_per_step", 8)) + latent_tokens = self.latent_steps * self.latent_tokens_per_step + self.world_loss_weight = float(jepa.get("world_loss_weight", 0.1)) + self.world_loss_warmup_steps = int(jepa.get("world_loss_warmup_steps", 0)) + + driving = DrivingAdaptor( + self.language_model.hidden_size, + speed_wps_mode=speed_wps_mode, + predict_route_as_wps=predict_route_as_wps, + waypoint_loss_fn=waypoint_loss_fn, + smooth_l1_beta=smooth_l1_beta, + latent_tokens=latent_tokens, + ) + + self.adaptors = AdaptorList( + driving=driving, + ) + + self.world_predictor = None + if self.use_world_loss: + self.world_predictor = BlockCausalWorldPredictor( + action_dim=self.language_model.hidden_size, + predictor_dim=int(jepa.get("predictor_dim", 1024)), + target_dim=int(jepa.get("teacher_dim", 1024)), + depth=int(jepa.get("predictor_depth", 12)), + heads=int(jepa.get("predictor_heads", 8)), + mlp_ratio=float(jepa.get("predictor_mlp_ratio", 4.0)), + dropout=float(jepa.get("predictor_dropout", 0.0)), + num_blocks=self.latent_steps, + state_tokens=64, + action_tokens=self.latent_tokens_per_step, + ) + + # Explicit-plan consequence head. It is intentionally absent from + # forward(); only forward_loss invokes it during training/validation. + self.use_consequence_loss = bool( + consequence is not None and consequence.get("enabled", False) + ) + self.consequence_cfg = consequence or {} + self.consequence_head = None + # "pooled" = ConsDrive v2 head (BCE risk logits + ranking supervision); + # "cross_attn" = ConsDrive v4 head (clearance regression + L_avoid); + # "cross_attn_risk" = ConsDrive v6: v4's cross-attention architecture + # trained with v2's BCE + ranking supervision. + self.consequence_head_type = str( + self.consequence_cfg.get("head_type", "cross_attn") + ) + if self.consequence_head_type not in ("pooled", "cross_attn", "cross_attn_risk"): + raise ValueError( + "consequence.head_type must be 'pooled', 'cross_attn', or " + "'cross_attn_risk'" + ) + if self.use_consequence_loss: + if self.consequence_head_type == "pooled": + self.consequence_head = PooledPlanConsequenceHead( + scene_dim=self.language_model.hidden_size, + hidden_dim=int(self.consequence_cfg.get("hidden_dim", 256)), + plan_dim=int(self.consequence_cfg.get("plan_dim", 128)), + horizon=10, + route_points=20, + dropout=float(self.consequence_cfg.get("dropout", 0.1)), + ) + else: + self.consequence_head = PlanConditionedConsequenceHead( + scene_dim=self.language_model.hidden_size, + hidden_dim=int(self.consequence_cfg.get("hidden_dim", 256)), + plan_dim=int(self.consequence_cfg.get("plan_dim", 128)), + horizon=10, + route_points=20, + dropout=float(self.consequence_cfg.get("dropout", 0.1)), + attn_heads=int(self.consequence_cfg.get("attn_heads", 4)), + with_risk_head=(self.consequence_head_type == "cross_attn_risk"), + ) + + if self.speed_as_input: + if self.new_layer_norm_minmax: + min_max = (0.0, 110.0 / 3.6) + else: + min_max = (0.0, 64.0 / 3.6) + self.speed_encoder = VectorInputAdaptor( + input_size=1, + token_size=self.language_model.hidden_size, + hidden_size=256, + norm_layer=NormZeroOne(min_max=min_max), + ) + + if route_as in ('coords', 'target_point', 'command_tp'): + if self.new_layer_norm_minmax: + min_max = (-200.0, 200.0) + else: + min_max = (-32.0, 32.0) + self.route_encoder = WaypointInputAdaptor( + token_size=self.language_model.hidden_size, + hidden_size=256, + norm_layer=NormZeroOne(min_max=min_max), + ) + elif route_as == 'command': + self.route_encoder = None + else: + self.route_encoder = RouteEncode(self.language_model.hidden_size, pretrained=True) + + # Whether the vision encoder provides DeepStack features (Qwen3-VL) + self.use_deepstack = hasattr(self.vision_model, "num_deepstack_layers") + + self.language_projection = nn.Identity() + if self.vision_model.token_size != self.language_model.hidden_size: + self.language_projection = nn.Linear(self.vision_model.token_size, self.language_model.hidden_size, bias=False) + + + # action-only models (from-scratch LM) have no tokenizer + self.tok = getattr(self.language_model, "tokenizer", None) + if self.tok is not None: + self.bos_token_id = self.tok.bos_token_id + self.eos_token_id = self.tok.eos_token_id + self.pad_token_id = self.tok.pad_token_id + else: + self.bos_token_id = None + self.eos_token_id = None + self.pad_token_id = None + + def forward(self, + driving_input: DrivingInput, + prompt_ids: Optional[Tensor] = None, + return_context: bool = False): + """ + Samples a trajectory from the model. + + With ``return_context=True`` the LM vision-token sequence used by the + consequence head is returned so deployment-time plan scoring can reuse + the same backbone pass. + """ + self.speed_wps, self.route, self.target_speed = None, None, None + + # single forward pass same as during training so we can use the same function + inputs = self.adaptors(driving_input) + if return_context: + features, vision_tokens, vision_mask = self.forward_model( + driving_input, inputs["inputs"], return_context=True + ) + else: + features = self.forward_model(driving_input, inputs["inputs"]) + predictions = self.adaptors.driving.get_predictions(features) + + for k, v in predictions.items(): + if v is not None: + setattr(self, k, v) + + if return_context: + return self.speed_wps, self.route, vision_tokens, vision_mask + return self.speed_wps, self.route + + @staticmethod + def _pool_scene_context(vision_tokens: Tensor, vision_mask: Tensor) -> Tensor: + """Masked mean over LM vision-token outputs (the v2 scene feature).""" + mask = vision_mask.to( + device=vision_tokens.device, dtype=vision_tokens.dtype + ) + return (vision_tokens * mask.unsqueeze(-1)).sum(dim=1) / mask.sum( + dim=1, keepdim=True + ).clamp_min(1.0) + + def score_plan_risk( + self, + vision_tokens: Tensor, + vision_mask: Tensor, + route: Tensor, + speed_wps: Tensor, + ): + """Score candidate plans with the trained consequence head. + + Returns per-waypoint collision probabilities ``[B, 10]`` and signed + clearance estimates ``[B, 10]`` in metres. The pooled (v2) head + supervises calibrated risk logits directly; the cross-attention (v4) + head only regresses clearance, so its risk is a sigmoid squash. + """ + if self.consequence_head is None: + raise RuntimeError( + "score_plan_risk requires a checkpoint trained with the " + "consequence head enabled" + ) + if self.consequence_head_type == "pooled": + scene_context = self._pool_scene_context(vision_tokens, vision_mask) + output = self.consequence_head( + scene_context.float(), route.float(), speed_wps.float() + ) + return ( + torch.sigmoid(output.risk_logits.float()), + output.clearance.float(), + ) + output = self.consequence_head( + vision_tokens.float(), + vision_mask, + route.float(), + speed_wps.float(), + ) + if self.consequence_head_type == "cross_attn_risk": + return ( + torch.sigmoid(output.risk_logits.float()), + output.clearance.float(), + ) + tau = max(float(self.consequence_cfg.get("risk_temperature", 1.0)), 1e-6) + risk = torch.sigmoid(-output.clearance.float() / tau) + return risk, output.clearance.float() + + + def forward_model(self, + driving_input: DrivingInput, + adaptor_embeds: Tensor, + driving_labels: DrivingLabel = None, + return_context: bool = False, + ): + """ + Forward model conditioned on the given driving input. + """ + + vision_embeds, attention_mask, aux = self.get_fixed_input_embeds(driving_input) + + input_embeds = torch.cat((vision_embeds, adaptor_embeds), dim=1) + adaptor_attention_mask = torch.ones( + adaptor_embeds.shape[:2], + dtype=torch.long, + device=adaptor_embeds.device, + ) + if attention_mask is not None: + attention_mask = torch.cat((attention_mask, adaptor_attention_mask), dim=1) + # to dtype of language model + input_embeds = input_embeds.to( + dtype=self.language_model.model.dtype + ) + + lm_kwargs = {} + if self.use_deepstack: + total_len = input_embeds.size(1) + visual_pos_masks = torch.zeros( + input_embeds.shape[:2], dtype=torch.bool, device=input_embeds.device + ) + visual_pos_masks[:, : aux["vision_mask"].size(1)] = aux["vision_mask"] + # flatten deepstack features in batch-major order at valid vision positions + deepstack_visual_embeds = [ + feat[aux["vision_mask"]] for feat in aux["deepstack_embeds"] + ] + lm_kwargs["visual_pos_masks"] = visual_pos_masks + lm_kwargs["deepstack_visual_embeds"] = deepstack_visual_embeds + lm_kwargs["position_ids"] = self._build_mrope_position_ids( + aux["video_grid_thw"], total_len, input_embeds.device + ) + + outputs = self.language_model.forward( + input_embeds, + attention_mask=attention_mask, + **lm_kwargs, + ) + + vision_outputs, adaptor_outputs = outputs.split( + [outputs.size(1) - adaptor_embeds.size(1), adaptor_embeds.size(1)], dim=1 + ) + if return_context: + vision_mask = attention_mask[:, :vision_outputs.size(1)] + return adaptor_outputs, vision_outputs, vision_mask + return adaptor_outputs + + def _build_mrope_position_ids(self, video_grid_thw: Tensor, total_len: int, device) -> Tensor: + """ + Interleaved-MRoPE position ids [3, B, total_len] following Qwen3-VL's + get_rope_index: every temporal frame of the video is treated as its own + grid (t=1), text/extra tokens get sequential positions on all 3 axes. + """ + merge = self.vision_model.spatial_merge_size + position_ids = torch.zeros(3, video_grid_thw.shape[0], total_len, dtype=torch.long, device=device) + + for batch_idx in range(video_grid_thw.shape[0]): + grid_t, grid_h, grid_w = (int(x) for x in video_grid_thw[batch_idx]) + llm_h, llm_w = grid_h // merge, grid_w // merge + pos_list = [] + current_pos = 0 + for _ in range(grid_t): + t_grid, h_grid, w_grid = torch.meshgrid( + torch.zeros(1, dtype=torch.long, device=device), + torch.arange(llm_h, device=device), + torch.arange(llm_w, device=device), + indexing="ij", + ) + frame_pos = torch.stack([t_grid, h_grid, w_grid], dim=0).reshape(3, -1) + current_pos + pos_list.append(frame_pos) + current_pos += max(llm_h, llm_w) + vision_pos = torch.cat(pos_list, dim=1) + n_vision = vision_pos.size(1) + n_text = total_len - n_vision + text_pos = (torch.arange(n_text, device=device) + current_pos).view(1, -1).expand(3, -1) + position_ids[:, batch_idx] = torch.cat([vision_pos, text_pos], dim=1) + + return position_ids + + def get_fixed_input_embeds(self, driving_input: DrivingInput): + img = driving_input.camera_images #[:, 0, :, :, :] # only use the front camera + + aux = {} + if self.use_deepstack: + vision_embeds, vision_mask_bool, deepstack_embeds = self.vision_model.forward( + img, image_sizes=driving_input.image_sizes + ) + attention_mask = vision_mask_bool.to(device=vision_embeds.device, dtype=torch.long) + video_grid_thw = driving_input.image_sizes + if video_grid_thw.ndim == 3: + video_grid_thw = video_grid_thw.reshape(-1, 3) + aux["vision_mask"] = vision_mask_bool + aux["deepstack_embeds"] = [self.language_projection(f) for f in deepstack_embeds] + aux["video_grid_thw"] = video_grid_thw + else: + vision_embeds, vision_aux = self.vision_model.forward(img, image_sizes=driving_input.image_sizes) + if isinstance(vision_aux, torch.Tensor) and vision_aux.ndim == 2: + attention_mask = vision_aux.to(device=vision_embeds.device, dtype=torch.long) + else: + attention_mask = torch.ones( + vision_embeds.shape[:2], + dtype=torch.long, + device=vision_embeds.device, + ) + + # n_frames, n_tokens, channels = sizes + vision_embeds = self.language_projection(vision_embeds) + extra_embeds = [] + extra_attention_masks = [] + if self.speed_as_input: + vehicle_speed = driving_input.vehicle_speed + # a NaN speed means "unknown": the token is masked out of attention like a dropped nav token + speed_known = torch.isfinite(vehicle_speed).all(dim=-1) + speed = self.speed_encoder.forward(torch.nan_to_num(vehicle_speed, nan=0.0)) + if self.training and self.speed_dropout_p > 0: + speed_known = speed_known & (torch.rand(speed_known.shape, device=speed_known.device) + >= self.speed_dropout_p) + extra_embeds.append(speed.to(dtype=vision_embeds.dtype)) + extra_attention_masks.append( + speed_known.to(device=speed.device, dtype=torch.long).unsqueeze(1).expand(speed.shape[:2]) + ) + + if self.route_as == 'command_tp': + batch_size = vision_embeds.size(0) + device = vision_embeds.device + # target-point tokens [B, 2, C] + tp_embeds = self.route_encoder.forward(driving_input.map_route) + tp_mask = torch.ones(tp_embeds.shape[:2], dtype=torch.long, device=device) + # command tokens [B, Lc, C] + cmd_embeds, cmd_mask = self.encode_navigation_command( + driving_input.navigation_command, device=device + ) + # three-state conditional dropout during training: + # both (p0) / command-only (p1) / tp-only (p2); inference keeps both + if self.training: + p_both, p_cmd, _ = self.nav_probs + r = torch.rand(batch_size, device=device) + drop_tp = (r >= p_both) & (r < p_both + p_cmd) # command-only + drop_cmd = r >= p_both + p_cmd # tp-only + tp_mask = tp_mask * (~drop_tp).long().unsqueeze(1) + cmd_mask = cmd_mask * (~drop_cmd).long().unsqueeze(1) + extra_embeds.append(tp_embeds.to(dtype=vision_embeds.dtype)) + extra_attention_masks.append(tp_mask) + extra_embeds.append(cmd_embeds.to(dtype=vision_embeds.dtype)) + extra_attention_masks.append(cmd_mask) + elif self.route_as == 'command': + route, route_attention_mask = self.encode_navigation_command( + driving_input.navigation_command, + device=vision_embeds.device, + ) + extra_embeds.append(route.to(dtype=vision_embeds.dtype)) + extra_attention_masks.append(route_attention_mask) + else: + map_route = driving_input.map_route + route = self.route_encoder.forward(map_route) + extra_embeds.append(route.to(dtype=vision_embeds.dtype)) + extra_attention_masks.append( + torch.ones(route.shape[:2], dtype=torch.long, device=route.device) + ) + + # free-form instruction prompt (used by Action Dreaming samples) + prompt = getattr(driving_input, "prompt", None) + if prompt is not None and any(len(p) > 0 for p in prompt): + prompt_embeds, prompt_mask = self.encode_navigation_command( + ["" if p is None else p for p in prompt], + device=vision_embeds.device, + ) + extra_embeds.append(prompt_embeds.to(dtype=vision_embeds.dtype)) + extra_attention_masks.append(prompt_mask) + + input_embeds = torch.cat((vision_embeds, *extra_embeds), dim=1) + extra_attention_mask = torch.cat(extra_attention_masks, dim=1) + attention_mask = torch.cat((attention_mask, extra_attention_mask), dim=1) + + return input_embeds, attention_mask, aux + + def encode_navigation_command(self, commands, device): + embed_tokens = getattr(self.language_model, "embed_tokens", None) + if embed_tokens is None: + embed_tokens = getattr(self.language_model.model, "embed_tokens", None) + if embed_tokens is None: + raise ValueError("Text conditioning requires a language model with token embeddings.") + + commands = ["" if c is None else c for c in commands] + # tokenizer requires non-empty batch entries; empty strings yield zero-length rows, + # pad them with the pad token and mask everything out + tokens = self.language_model.tokenizer( + list(commands), + padding=True, + truncation=True, + return_tensors="pt", + ) + input_ids = tokens["input_ids"].to(device) + attention_mask = tokens["attention_mask"].to(device=device, dtype=torch.long) + if input_ids.numel() == 0: + pad_id = self.language_model.tokenizer.pad_token_id + input_ids = torch.full((len(commands), 1), pad_id, dtype=torch.long, device=device) + attention_mask = torch.zeros((len(commands), 1), dtype=torch.long, device=device) + embeds = embed_tokens(input_ids) + return embeds, attention_mask + + def forward_loss(self, example: DrivingExample, per_sample=False) -> TrainingOutput: + """ + Forward pass of the model for a driving input, followed by + computing the next token cross-entropy loss. + + Args: + driving_input: input to the vision encoder. + text_ids: Text ids tensor of shape [B, T]. These are input to the model and used in the loss. + text_mask: Text mask tensor of shape [B, T]. + """ + + adaptor_dict = self.adaptors(example) + adaptor_embeds = adaptor_dict["inputs"] + + if self.use_consequence_loss: + adaptor_outputs, vision_tokens, vision_mask = self.forward_model( + example.driving_input, + adaptor_embeds, + driving_labels=example.driving_label, + return_context=True, + ) + else: + adaptor_outputs = self.forward_model( + example.driving_input, + adaptor_embeds, + driving_labels=example.driving_label, + ) + vision_tokens = vision_mask = None + loss_dict = self.adaptors.compute_loss(adaptor_outputs, adaptor_dict, example) + latent_features = loss_dict.pop("latent_features", None) + + if self.use_consequence_loss: + route_prediction = loss_dict.get("route_prediction") + speed_prediction = loss_dict.get("speed_wps_prediction") + if route_prediction is None or speed_prediction is None: + raise ValueError( + "consequence loss requires predict_route_as_wps=True and " + "speed_wps_mode='2d'" + ) + loss_dict.update( + self.compute_consequence_losses( + vision_tokens, + vision_mask, + route_prediction, + speed_prediction, + example.driving_label, + ) + ) + + loss_dict_only_losses = {k:v for k, v in loss_dict.items() if k.endswith("loss")} + pred_labels = {k:v for k, v in loss_dict.items() if not k.endswith("loss")} + + if self.use_world_loss and latent_features is not None: + loss_dict_only_losses["world_loss"] = self.compute_world_loss( + latent_features, example.driving_label + ) + + if per_sample: + return loss_dict_only_losses, pred_labels + + return summarise_losses(loss_dict_only_losses) + + def compute_consequence_losses( + self, + vision_tokens: Tensor, + vision_mask: Tensor, + predicted_route: Tensor, + predicted_speed: Tensor, + label: DrivingLabel, + ): + """Dispatch to the head-specific consequence supervision.""" + if self.consequence_head is None or label.future_obstacles is None: + return {} + if self.consequence_head_type in ("pooled", "cross_attn_risk"): + return self._compute_consequence_losses_risk( + vision_tokens, vision_mask, predicted_route, predicted_speed, label + ) + return self._compute_consequence_losses_cross_attn( + vision_tokens, vision_mask, predicted_route, predicted_speed, label + ) + + def _make_consequence_head_call(self, vision_tokens: Tensor, vision_mask: Tensor): + """Uniform head invocation for the risk-supervised head variants. + + Returns ``head_call(routes, speeds, num_plans=1)``: candidate plans are + laid out batch-major ([b0p0..b0pK, b1p0..]), matching both the pooled + scene expansion and ``expand_scene_for_plans``. + """ + head = self.consequence_head + if self.consequence_head_type == "pooled": + scene_context = self._pool_scene_context(vision_tokens, vision_mask) + + def head_call(routes, speeds, num_plans: int = 1): + if num_plans == 1: + return head(scene_context, routes, speeds) + batch = scene_context.size(0) + expanded = ( + scene_context[:, None] + .expand(-1, num_plans, -1) + .reshape(batch * num_plans, -1) + ) + return head(expanded, routes, speeds) + + return head_call + + def head_call(routes, speeds, num_plans: int = 1): + if num_plans == 1: + return head(vision_tokens, vision_mask, routes, speeds) + tokens, mask = expand_scene_for_plans( + vision_tokens, vision_mask, num_plans + ) + return head(tokens, mask, routes, speeds) + + return head_call + + def _compute_consequence_losses_risk( + self, + vision_tokens: Tensor, + vision_mask: Tensor, + predicted_route: Tensor, + predicted_speed: Tensor, + label: DrivingLabel, + ): + """ConsDrive v2 supervision: BCE risk + clearance + hard-negative + ranking (+ Action Dreaming terms when dreamer labels exist). Shared + by the pooled (v2/v5) and cross_attn_risk (v6) heads.""" + cfg = self.consequence_cfg + head_call = self._make_consequence_head_call(vision_tokens, vision_mask) + + gt_route = label.route_adjusted + gt_speed = label.waypoints[:, :10] + predicted = head_call(predicted_route, predicted_speed) + ground_truth = head_call(gt_route, gt_speed) + batch_size = predicted_route.size(0) + device = predicted_route.device + + obstacles = label.future_obstacles.to(device=device) + obstacle_valid = label.future_obstacle_valid.to(device=device) + step_valid = label.future_obstacle_step_valid.to(device=device) + ego_radius = float(cfg.get("ego_radius", 0.9)) + max_clearance = float(cfg.get("max_clearance", 20.0)) + pred_risk_target, pred_clearance_target, geometry_valid = ( + trajectory_geometry_targets( + predicted_speed.detach(), + obstacles, + obstacle_valid, + step_valid, + ego_radius=ego_radius, + max_clearance=max_clearance, + ) + ) + + risk_pos_weight = float(cfg.get("risk_pos_weight", 1.0)) + risk_values, risk_counts = binary_waypoint_loss( + predicted.risk_logits, + pred_risk_target, + geometry_valid, + pos_weight=risk_pos_weight, + ) + clearance_values, clearance_counts = clearance_waypoint_loss( + predicted.clearance, + pred_clearance_target, + geometry_valid, + beta=float(cfg.get("clearance_beta", 1.0)), + ) + + # Dataset targets anchor the GT plan. They include exact future-box + # geometry when available and explicit hazard-only fallback otherwise. + gt_risk_values, gt_risk_counts = binary_waypoint_loss( + ground_truth.risk_logits, + label.consequence_risk_target.to(device=device), + label.consequence_risk_valid.to(device=device), + pos_weight=risk_pos_weight, + ) + gt_clearance_values, gt_clearance_counts = clearance_waypoint_loss( + ground_truth.clearance, + label.consequence_clearance_target.to(device=device), + label.consequence_clearance_valid.to(device=device), + beta=float(cfg.get("clearance_beta", 1.0)), + ) + + rank_values = predicted.risk_logits.float().sum(dim=1) * 0.0 + rank_counts = torch.zeros(batch_size, dtype=torch.long, device=device) + complete_geometry = step_valid.all(dim=1) + if bool(complete_geometry.any()): + rank_parts = [] + count_parts = [] + for base_route, base_speed, base_output in ( + (predicted_route, predicted_speed, predicted), + (gt_route, gt_speed, ground_truth), + ): + values, counts = self._consequence_ranking_for_plan( + head_call, + base_route, + base_speed, + base_output.risk_logits, + obstacles, + obstacle_valid, + step_valid, + ) + rank_parts.append(values) + count_parts.append(counts) + stacked_counts = torch.stack(count_parts, dim=1) + stacked_values = torch.stack(rank_parts, dim=1) + rank_counts = (stacked_counts.sum(dim=1) > 0).long() + rank_values = ( + (stacked_values * stacked_counts).sum(dim=1) + / stacked_counts.sum(dim=1).clamp_min(1) + ) + + # Action Dreaming safety terms are only defined when dreamer labels + # exist (use_dreamer=True); otherwise they contribute zero counts. + dream_values = predicted.risk_logits.float().sum(dim=1) * 0.0 + dream_counts = torch.zeros(batch_size, dtype=torch.long, device=device) + if ( + label.safe_to_execute is not None + and label.safe_to_execute_valid is not None + and label.is_dreamer is not None + ): + dream_valid = ( + label.safe_to_execute_valid.to(device=device) + & label.is_dreamer.to(device=device) + ) + dream_target = (~label.safe_to_execute.to(device=device)).float() + # The safety flag labels the selected Dreamer trajectory, not the + # model's still-imperfect prediction of that trajectory. + dream_logits = aggregate_risk_logits(ground_truth.risk_logits) + dream_loss = torch.nn.functional.binary_cross_entropy_with_logits( + dream_logits, dream_target, reduction="none" + ) + dream_values = dream_loss * dream_valid.float() + dream_counts = dream_valid.long() + + dream_pair_values = predicted.risk_logits.float().sum(dim=1) * 0.0 + dream_pair_counts = torch.zeros( + batch_size, dtype=torch.long, device=device + ) + if label.dream_pair_valid is not None: + pair_valid = label.dream_pair_valid.to(device=device, dtype=torch.bool) + if bool(pair_valid.any()): + safe_output = head_call( + label.dream_safe_route.to(device=device), + label.dream_safe_speed.to(device=device), + ) + unsafe_output = head_call( + label.dream_unsafe_route.to(device=device), + label.dream_unsafe_speed.to(device=device), + ) + dream_pair_values, dream_pair_counts = pairwise_ranking_loss( + safe_output.risk_logits, + unsafe_output.risk_logits[:, None], + pair_valid[:, None], + margin=float(cfg.get("negative_margin", 0.5)), + ) + + warmup_steps = int(cfg.get("warmup_steps", 0)) + if self.training and warmup_steps > 0 and getattr(self, "_trainer", None) is not None: + warmup = min((int(self.global_step) + 1) / warmup_steps, 1.0) + else: + warmup = 1.0 + global_weight = float(cfg.get("loss_weight", 0.1)) * warmup + + def weighted(values, name): + return values * global_weight * float(cfg.get(name, 1.0)) + + return { + "consequence_risk_loss": ( + weighted(risk_values, "risk_weight"), + risk_counts, + ), + "consequence_gt_risk_loss": ( + weighted(gt_risk_values, "risk_weight"), + gt_risk_counts, + ), + "consequence_clearance_loss": ( + weighted(clearance_values, "clearance_weight"), + clearance_counts, + ), + "consequence_gt_clearance_loss": ( + weighted(gt_clearance_values, "clearance_weight"), + gt_clearance_counts, + ), + "consequence_ranking_loss": ( + weighted(rank_values, "ranking_weight"), + rank_counts, + ), + "consequence_dream_safety_loss": ( + weighted(dream_values, "dream_weight"), + dream_counts, + ), + "consequence_dream_pair_ranking_loss": ( + weighted(dream_pair_values, "dream_pair_weight"), + dream_pair_counts, + ), + } + + def _consequence_ranking_for_plan( + self, + head_call, + base_route, + base_speed, + base_logits, + obstacles, + obstacle_valid, + step_valid, + ): + cfg = self.consequence_cfg + # `speed_scale` (scalar) is the legacy key kept for old configs; + # `negative_speed_scales` (list) takes precedence when present. + speed_scales = cfg.get("negative_speed_scales") + if speed_scales is None: + speed_scales = [float(cfg.get("speed_scale", 1.35))] + time_shifts = cfg.get("negative_time_shifts") or () + candidate_routes, candidate_speeds = make_hard_negative_plans( + base_route, + base_speed, + speed_scales=[float(s) for s in speed_scales], + lateral_offset=float(cfg.get("lateral_offset", 1.5)), + time_shifts=[int(s) for s in time_shifts], + ) + batch_size, candidates = candidate_routes.shape[:2] + flat_routes = candidate_routes.reshape(batch_size * candidates, 20, 2) + flat_speeds = candidate_speeds.reshape(batch_size * candidates, 10, 2) + candidate_output = head_call(flat_routes, flat_speeds, num_plans=candidates) + candidate_logits = candidate_output.risk_logits.reshape( + batch_size, candidates, 10 + ) + + base_risk, _, base_valid = trajectory_geometry_targets( + base_speed.detach(), + obstacles, + obstacle_valid, + step_valid, + ego_radius=float(cfg.get("ego_radius", 0.9)), + max_clearance=float(cfg.get("max_clearance", 20.0)), + ) + expanded_obstacles = obstacles[:, None].expand( + -1, candidates, -1, -1, -1 + ).reshape(batch_size * candidates, *obstacles.shape[1:]) + expanded_obstacle_valid = obstacle_valid[:, None].expand( + -1, candidates, -1, -1 + ).reshape(batch_size * candidates, *obstacle_valid.shape[1:]) + expanded_step_valid = step_valid[:, None].expand( + -1, candidates, -1 + ).reshape(batch_size * candidates, -1) + candidate_risk, _, candidate_valid = trajectory_geometry_targets( + flat_speeds.detach(), + expanded_obstacles, + expanded_obstacle_valid, + expanded_step_valid, + ego_radius=float(cfg.get("ego_radius", 0.9)), + max_clearance=float(cfg.get("max_clearance", 20.0)), + ) + candidate_risk = candidate_risk.reshape(batch_size, candidates, 10) + candidate_valid = candidate_valid.reshape(batch_size, candidates, 10) + proven_safe = base_valid.all(dim=1) & ~base_risk.bool().any(dim=1) + proven_unsafe = ( + candidate_valid.all(dim=2) & candidate_risk.bool().any(dim=2) + ) + ranking_valid = proven_safe[:, None] & proven_unsafe + return pairwise_ranking_loss( + base_logits, + candidate_logits, + ranking_valid, + margin=float(cfg.get("negative_margin", 0.5)), + ) + + def _compute_consequence_losses_cross_attn( + self, + vision_tokens: Tensor, + vision_mask: Tensor, + predicted_route: Tensor, + predicted_speed: Tensor, + label: DrivingLabel, + ): + """Avoidance hinge on the predicted plan plus one clearance head loss.""" + cfg = self.consequence_cfg + head = self.consequence_head + + gt_route = label.route_adjusted + gt_speed = label.waypoints[:, :10] + batch_size = predicted_route.size(0) + device = predicted_route.device + + obstacles = label.future_obstacles.to(device=device) + obstacle_valid = label.future_obstacle_valid.to(device=device) + step_valid = label.future_obstacle_step_valid.to(device=device) + ego_radius = float(cfg.get("ego_radius", 0.9)) + max_clearance = float(cfg.get("max_clearance", 20.0)) + geometry_kwargs = dict( + ego_radius=ego_radius, max_clearance=max_clearance + ) + + _, pred_clearance, pred_geom_valid = trajectory_geometry_targets( + predicted_speed, obstacles, obstacle_valid, step_valid, **geometry_kwargs + ) + _, gt_clearance, gt_geom_valid = trajectory_geometry_targets( + gt_speed, obstacles, obstacle_valid, step_valid, **geometry_kwargs + ) + avoid_values, avoid_counts = relative_min_clearance_hinge( + pred_clearance, gt_clearance, pred_geom_valid, gt_geom_valid + ) + + visible_valid = visible_obstacle_mask( + obstacles, + obstacle_valid, + max_range=float(cfg.get("visible_max_range", 40.0)), + min_x=float(cfg.get("visible_min_x", 0.0)), + ) + speed_scales = cfg.get("negative_speed_scales") + if speed_scales is None: + speed_scales = [0.7, 0.8, 0.9, 1.2, 1.5] + time_shifts = cfg.get("negative_time_shifts") or () + neg_routes, neg_speeds = make_hard_negative_plans( + gt_route, + gt_speed, + speed_scales=[float(s) for s in speed_scales], + lateral_offset=float(cfg.get("lateral_offset", 1.5)), + time_shifts=[int(s) for s in time_shifts], + ) + plan_routes = torch.cat( + (gt_route[:, None], predicted_route.detach()[:, None], neg_routes), + dim=1, + ) + plan_speeds = torch.cat( + (gt_speed[:, None], predicted_speed.detach()[:, None], neg_speeds), + dim=1, + ) + num_plans = plan_routes.size(1) + flat_routes = plan_routes.reshape(batch_size * num_plans, 20, 2) + flat_speeds = plan_speeds.reshape(batch_size * num_plans, 10, 2) + flat_tokens, flat_mask = expand_scene_for_plans( + vision_tokens, vision_mask, num_plans + ) + head_out = head(flat_tokens, flat_mask, flat_routes, flat_speeds) + + expanded_obstacles = obstacles[:, None].expand( + -1, num_plans, -1, -1, -1 + ).reshape(batch_size * num_plans, *obstacles.shape[1:]) + expanded_visible = visible_valid[:, None].expand( + -1, num_plans, -1, -1 + ).reshape(batch_size * num_plans, *visible_valid.shape[1:]) + expanded_step = step_valid[:, None].expand( + -1, num_plans, -1 + ).reshape(batch_size * num_plans, -1) + _, plan_clearance_target, plan_valid = trajectory_geometry_targets( + flat_speeds, + expanded_obstacles, + expanded_visible, + expanded_step, + **geometry_kwargs, + ) + plan_values, plan_counts = clearance_waypoint_loss( + head_out.clearance, + plan_clearance_target, + plan_valid, + beta=float(cfg.get("clearance_beta", 1.0)), + ) + plan_values = plan_values.view(batch_size, num_plans) + plan_counts = plan_counts.view(batch_size, num_plans) + plan_used = plan_counts > 0 + head_counts = plan_used.any(dim=1).long() + head_values = (plan_values * plan_used.to(dtype=plan_values.dtype)).sum( + dim=1 + ) / plan_used.to(dtype=plan_values.dtype).sum(dim=1).clamp_min(1) + + warmup_steps = int(cfg.get("warmup_steps", 0)) + if self.training and warmup_steps > 0 and getattr(self, "_trainer", None) is not None: + warmup = min((int(self.global_step) + 1) / warmup_steps, 1.0) + else: + # Tests / memory probe have no Trainer; use full weights so the + # measured graph matches a warmed-up training step. + warmup = 1.0 + avoid_weight = float(cfg.get("avoid_weight", 0.3)) * warmup + head_weight = float(cfg.get("head_weight", 0.1)) * warmup + + return { + "consequence_avoid_loss": (avoid_values * avoid_weight, avoid_counts), + "consequence_head_loss": (head_values * head_weight, head_counts), + } + + def compute_world_loss(self, latent_features: Tensor, label: DrivingLabel): + """L1 between the world predictor's next-state prediction (conditioned on + the LM's latent action tokens) and the cached V-JEPA2 future latents.""" + b = latent_features.size(0) + actions = latent_features.view( + b, self.latent_steps, self.latent_tokens_per_step, -1 + ) + future_states = getattr(label, "future_states", None) + wm_valid = getattr(label, "wm_valid", None) + raw_loss, valid_count = masked_world_l1( + self.world_predictor, actions, future_states, wm_valid + ) + beta = linear_world_weight( + self.global_step, self.world_loss_weight, self.world_loss_warmup_steps + ) if self.training else self.world_loss_weight + weighted = raw_loss * beta + self._world_metrics = { + "world_loss_raw": raw_loss.detach(), + "world_beta": beta, + "world_valid_count": float(valid_count), + } + return ( + weighted.reshape(1), + torch.ones(1, dtype=torch.long, device=weighted.device), + ) + + def training_step(self, batch: DrivingExample, _batch_idx: int = 0): + output = self.forward_loss(batch) + self.log_training_output(output, "train") + + # log the loss + self.log("train/loss", output.loss, on_step=True, on_epoch=True, prog_bar=True, logger=True) + self._log_world_metrics("train") + + return {"loss": output.loss, "outputs": output} + + def _log_world_metrics(self, mode: str): + metrics = getattr(self, "_world_metrics", None) + if metrics is None: + return + on_step = mode == "train" + for k, v in metrics.items(): + self.log( + f"{mode}_losses/{k}", v, + on_step=on_step, on_epoch=not on_step, sync_dist=False, logger=True, + ) + self._world_metrics = None + + def validation_step(self, batch: DrivingExample, _batch_idx: int = 0): + output = self.forward_loss(batch) + self.log_training_output(output, "val") + + # log the loss + self.log("val/loss", output.loss, on_step=False, on_epoch=True, prog_bar=True, logger=True) + self._log_world_metrics("val") + + return {"loss": output.loss, "outputs": output} + + def predict_step(self, batch: DrivingExample, _batch_idx: int = 0): + loss_dict, pred_labels = self.forward_loss(batch, per_sample=True) + + per_sample_losses = loss_dict['waypoints_loss'][0].detach().cpu().numpy() + predictions = pred_labels['waypoints_prediction'].detach().cpu().numpy() + labels = pred_labels['waypoints_label'].detach().cpu().numpy() + + for i in range(len(per_sample_losses)): + self.all_losses[batch.run_id[i]] = per_sample_losses[i] + self.all_predictions[batch.run_id[i]] = (per_sample_losses[i], predictions[i], labels[i]) + + return + + def on_predict_epoch_end(self) -> None: + + # sort by loss and save as pkl and json + # sorted_losses = sorted(self.all_losses.items(), key=lambda x: x[1]) + # with open("sorted_losses.json", "w") as f: + # json.dump(sorted_losses, f) + try: + with open("sorted_losses.pkl", "wb") as f: + pkl.dump(self.all_losses, f) + with open("all_predictions.pkl", "wb") as f: + pkl.dump(self.all_predictions, f) + except: + breakpoint() + + + def log_training_output(self, training_output: TrainingOutput, mode: str, dataset: Optional[str] = None): + losses = {k: n.detach() for k, n in training_output.loss_averages.items()} + counts = {k: n.detach().sum() for k, n in training_output.loss_counts.items()} + losses["loss"] = training_output.loss.detach() + counts["loss"] = 1 # loss is already averaged + for k, v in sorted(losses.items()): + log_key = f"{mode}_losses/{k}" + self.log(log_key, v, batch_size=counts[k], sync_dist=True, add_dataloader_idx=False) + + + def configure_optimizers(self): + + if self.lm_lr is not None: + # pretrained-init trunks get their own (lower) LR; the regexes must + # stay disjoint because configure_params_groups forbids overlap + param_groups = [ + ParamGroup(r"^language_model\..*", self.lm_lr, self.weight_decay), + ParamGroup(r"^(model|language_projection|adaptors|speed_encoder|route_encoder|world_predictor|consequence_head)\..*", self.lr, self.weight_decay), + ParamGroup(r"^vision_model\..*", self.vision_lr, self.weight_decay), + ] + else: + param_groups = [ + ParamGroup(r"^(model|language_model|language_projection|adaptors|speed_encoder|route_encoder|world_predictor|consequence_head)\..*", self.lr, self.weight_decay), + ParamGroup(r"^vision_model\..*", self.vision_lr, self.weight_decay), + ] + param_group_config = configure_params_groups(self, param_groups, verbose=False) + if isinstance(self.trainer.strategy, pl.strategies.DeepSpeedStrategy) and FusedAdam is not None: + try: + optimizer = FusedAdam(param_group_config, betas=self.betas) + except (ImportError, OSError, RuntimeError): + warnings.warn( + "FusedAdam could not be loaded; falling back to torch.optim.AdamW.", + stacklevel=2, + ) + optimizer = torch.optim.AdamW(param_group_config, betas=self.betas) + else: + optimizer = torch.optim.AdamW(param_group_config, betas=self.betas) + if self.trainer.max_steps == -1: + max_steps = self.trainer.estimated_stepping_batches + else: + max_steps = self.trainer.max_steps + + if self.vision_freeze_steps > 0 or self.vision_ramp_steps > 0: + scheduler = self._build_freeze_ramp_scheduler(optimizer, max_steps) + else: + lrs = [pg['lr'] for pg in optimizer.param_groups] + scheduler = torch.optim.lr_scheduler.OneCycleLR( + optimizer, max_lr=lrs, total_steps=max_steps, pct_start=self.pct_start + ) + return {"optimizer": optimizer, "lr_scheduler": {"scheduler": scheduler, "frequency": 1, "interval": "step"}} + + def _build_freeze_ramp_scheduler(self, optimizer, max_steps: int): + """Per-group LambdaLR: main groups get linear warmup + cosine decay; + vision groups stay at lr=0 for `vision_freeze_steps`, then ramp up + linearly over `vision_ramp_steps` and follow the same cosine envelope.""" + import math + + warmup_steps = max(1, int(self.pct_start * max_steps)) + freeze_steps = self.vision_freeze_steps + ramp_steps = max(1, self.vision_ramp_steps) + + def cosine_envelope(step: int) -> float: + if step < warmup_steps: + return 1.0 + progress = (step - warmup_steps) / max(1, max_steps - warmup_steps) + return 0.5 * (1.0 + math.cos(math.pi * min(progress, 1.0))) + + def main_lambda(step: int) -> float: + if step < warmup_steps: + return (step + 1) / warmup_steps + return cosine_envelope(step) + + def vision_lambda(step: int) -> float: + if step < freeze_steps: + return 0.0 + ramp = min((step - freeze_steps + 1) / ramp_steps, 1.0) + return ramp * cosine_envelope(step) + + vision_param_ids = {id(p) for p in self.vision_model.parameters()} + lambdas = [ + vision_lambda + if any(id(p) in vision_param_ids for p in group["params"]) + else main_lambda + for group in optimizer.param_groups + ] + return torch.optim.lr_scheduler.LambdaLR(optimizer, lr_lambda=lambdas) diff --git a/models/encoder/__init__.py b/models/encoder/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/models/encoder/__init__.py @@ -0,0 +1 @@ + diff --git a/models/encoder/dinov2_lora.py b/models/encoder/dinov2_lora.py new file mode 100644 index 0000000000000000000000000000000000000000..77c6b52574dde97fb3144aebf9a75b5a422a894e --- /dev/null +++ b/models/encoder/dinov2_lora.py @@ -0,0 +1,218 @@ +import math +from pathlib import Path +from typing import Optional, Sequence, Tuple + +import torch +from safetensors import safe_open +from torch import Tensor, nn +import torch.nn.functional as F +import timm + + +class LoRAQKV(nn.Module): + def __init__( + self, + qkv: nn.Linear, + rank: int, + use_layer_norm: bool = False, + use_qkv: bool = False, + ): + super().__init__() + self.qkv = qkv + self.dim = qkv.in_features + self.use_qkv = use_qkv + + self.linear_a_q = nn.Linear(self.dim, rank, bias=False) + self.linear_b_q = nn.Linear(rank, self.dim, bias=False) + self.linear_a_v = nn.Linear(self.dim, rank, bias=False) + self.linear_b_v = nn.Linear(rank, self.dim, bias=False) + + self.linear_a_k = nn.Linear(self.dim, rank, bias=False) if use_qkv else nn.Identity() + self.linear_b_k = nn.Linear(rank, self.dim, bias=False) if use_qkv else nn.Identity() + + self.layernorm_q = nn.LayerNorm(self.dim) if use_layer_norm else nn.Identity() + self.layernorm_v = nn.LayerNorm(self.dim) if use_layer_norm else nn.Identity() + self.layernorm_k = nn.LayerNorm(self.dim) if use_layer_norm and use_qkv else nn.Identity() + self.reset_parameters() + + def reset_parameters(self): + for module in (self.linear_a_q, self.linear_a_v, self.linear_a_k): + if isinstance(module, nn.Linear): + nn.init.kaiming_uniform_(module.weight, a=math.sqrt(5)) + for module in (self.linear_b_q, self.linear_b_v, self.linear_b_k): + if isinstance(module, nn.Linear): + nn.init.zeros_(module.weight) + + def forward(self, x: Tensor) -> Tensor: + qkv = self.qkv(x) + qkv[:, :, : self.dim] += self.linear_b_q(self.linear_a_q(self.layernorm_q(x))) + qkv[:, :, -self.dim :] += self.linear_b_v(self.linear_a_v(self.layernorm_v(x))) + if self.use_qkv: + qkv[:, :, self.dim : 2 * self.dim] += self.linear_b_k(self.linear_a_k(self.layernorm_k(x))) + return qkv + + +def _load_checkpoint(path: str): + path_obj = Path(path) + if not path_obj.exists(): + raise FileNotFoundError(f"DINOv2 checkpoint does not exist: {path}") + + try: + state_dict = {} + with safe_open(str(path_obj), framework="pt", device="cpu") as f: + for key in f.keys(): + state_dict[key] = f.get_tensor(key) + return state_dict + except Exception: + checkpoint = torch.load(path_obj, map_location="cpu") + if isinstance(checkpoint, dict): + for key in ("state_dict", "model", "teacher"): + if key in checkpoint and isinstance(checkpoint[key], dict): + checkpoint = checkpoint[key] + break + return checkpoint + + +class DinoV2LoRAEncoderModel(nn.Module): + """ + DINOv2 vision encoder following the DrivoR adaptation pattern: + frozen timm DINOv2 backbone + LoRA injected into attention q/v + trainable neck. + """ + + def __init__( + self, + model_name: str = "timm/vit_small_patch14_reg4_dinov2.lvd142m", + model_weights: Optional[str] = None, + embed_dim: int = 512, + image_size: Tuple[int, int] = (224, 224), + use_lora: bool = True, + lora_rank: int = 16, + lora_layers: Optional[Sequence[int]] = None, + lora_use_layer_norm: bool = False, + lora_use_qkv: bool = False, + finetune: bool = False, + num_register_tokens: int = 4, + use_feature_pooling: bool = False, + freeze: bool = False, + max_frames: int = 4, + max_cameras: int = 6, + use_global_img: bool = False, + ): + super().__init__() + self.token_size = embed_dim + self.image_size = tuple(image_size) + self.num_register_tokens = num_register_tokens + self.use_feature_pooling = use_feature_pooling + self.max_frames = max_frames + self.max_cameras = max_cameras + self.use_global_img = use_global_img + + self.model = timm.create_model( + model_name, + pretrained=False, + num_classes=0, + img_size=self.image_size, + ) + if model_weights: + state_dict = _load_checkpoint(model_weights) + missing, unexpected = self.model.load_state_dict(state_dict, strict=False) + if unexpected: + print(f"DINOv2 checkpoint unexpected keys: {unexpected[:10]}") + if missing: + print(f"DINOv2 checkpoint missing keys: {missing[:10]}") + + self.num_features = self.model.num_features + self.neck = nn.Linear(self.num_features, embed_dim) + self.temporal_encoding = nn.Parameter(0.02 * torch.randn(1, max_frames, 1, 1, embed_dim)) + self.camera_encoding = nn.Parameter(0.02 * torch.randn(1, 1, max_cameras, 1, embed_dim)) + + if use_lora: + self._freeze_backbone() + self._inject_lora(lora_rank, lora_layers, lora_use_layer_norm, lora_use_qkv) + elif finetune: + for param in self.model.parameters(): + param.requires_grad = True + else: + self._freeze_backbone() + + if freeze: + for param in self.parameters(): + param.requires_grad = False + + self.register_buffer( + "image_mean", + torch.tensor([0.485, 0.456, 0.406]).view(1, 3, 1, 1), + persistent=False, + ) + self.register_buffer( + "image_std", + torch.tensor([0.229, 0.224, 0.225]).view(1, 3, 1, 1), + persistent=False, + ) + + def _freeze_backbone(self): + for param in self.model.parameters(): + param.requires_grad = False + + def _inject_lora( + self, + rank: int, + layers: Optional[Sequence[int]], + use_layer_norm: bool, + use_qkv: bool, + ): + if rank <= 0: + return + selected_layers = set(layers) if layers is not None else set(range(len(self.model.blocks))) + for layer_idx, block in enumerate(self.model.blocks): + if layer_idx not in selected_layers: + continue + block.attn.qkv = LoRAQKV( + block.attn.qkv, + rank=rank, + use_layer_norm=use_layer_norm, + use_qkv=use_qkv, + ) + + def _select_tokens(self, tokens: Tensor) -> Tensor: + if self.use_feature_pooling: + return F.adaptive_avg_pool1d(tokens.transpose(1, 2), self.num_register_tokens).transpose(1, 2) + + reg_token = getattr(self.model, "reg_token", None) + if reg_token is not None: + start = 1 if getattr(self.model, "cls_token", None) is not None else 0 + end = start + self.num_register_tokens + return tokens[:, start:end] + return tokens[:, : self.num_register_tokens] + + def forward(self, pixel_values: Tensor, image_sizes: Optional[Tensor] = None) -> Tuple[Tensor, Tensor]: + if pixel_values.ndim != 6: + raise ValueError( + "DinoV2LoRAEncoderModel expects images shaped [B, T, N, C, H, W], " + f"got {tuple(pixel_values.shape)}." + ) + + batch_size, num_frames, num_cameras, channels, height, width = pixel_values.shape + if channels != 3: + raise ValueError(f"Expected RGB images with 3 channels, got {channels}.") + if num_frames > self.max_frames: + raise ValueError(f"num_frames={num_frames} exceeds max_frames={self.max_frames}.") + if num_cameras > self.max_cameras: + raise ValueError(f"num_cameras={num_cameras} exceeds max_cameras={self.max_cameras}.") + + x = pixel_values.reshape(batch_size * num_frames * num_cameras, channels, height, width) + x = x.to(device=self.neck.weight.device, dtype=self.neck.weight.dtype) + x = x / 255.0 + x = (x - self.image_mean.to(dtype=x.dtype)) / self.image_std.to(dtype=x.dtype) + if (height, width) != self.image_size: + x = F.interpolate(x, size=self.image_size, mode="bilinear", align_corners=False) + + tokens = self.model.forward_features(x) + tokens = self._select_tokens(tokens) + tokens = self.neck(tokens) + tokens = tokens.view(batch_size, num_frames, num_cameras, self.num_register_tokens, -1) + tokens = tokens + self.temporal_encoding[:, :num_frames].to(dtype=tokens.dtype) + tokens = tokens + self.camera_encoding[:, :, :num_cameras].to(dtype=tokens.dtype) + embeds = tokens.reshape(batch_size, num_frames * num_cameras * self.num_register_tokens, -1) + attention_mask = torch.ones(embeds.shape[:2], dtype=torch.long, device=embeds.device) + return embeds, attention_mask diff --git a/models/encoder/llavanext.py b/models/encoder/llavanext.py new file mode 100644 index 0000000000000000000000000000000000000000..3b1a81b69e2e27438e1acd63ab720dd49a7dd763 --- /dev/null +++ b/models/encoder/llavanext.py @@ -0,0 +1,107 @@ +import numpy as np +import torch +from torch import nn +from transformers import LlavaNextProcessor + +from models.encoder.llavanext_model import LingoLlavaNextModel + +class LLaVAnextEncoderModel(nn.Module): + def __init__(self, + variant: str, + embed_dim: int, + freeze: bool, + downsample_feature_grid_factor: int = 2, + use_global_img = False, + ): + + super().__init__() + self.num_cameras = 1 + self.num_frames = 1 + self.token_size = embed_dim + + self.downsample_feature_grid_factor = downsample_feature_grid_factor + + self.image_encoder = LingoLlavaNextModel.from_pretrained(variant) + self.image_encoder.use_global_img = use_global_img + self.image_encoder.config.image_grid_pinpoints = [[336,672]] # this is done to save memory otherwise it would use higehr res input dependen on how we cut the image + self.image_encoder.language_model = None + print("\033[91m" + "Using LLaVA pretraining for the image encoder" + "\033[0m") + + self.projection = nn.Linear(self.image_encoder.base_model.config.vision_config.intermediate_size, embed_dim) + # Embeddings: BS, N_FRAMES, N_CAMS, N_PATCHES, EMBED_DIM + self.temporal_encoding = nn.Parameter(0.02 * torch.randn(1, self.num_frames, 1, 1, embed_dim)) + self.camera_encoding = nn.Parameter(0.02 * torch.randn(1, 1, self.num_cameras, 1, embed_dim)) + + # freeze the paramaeters -> no gradient updates + if freeze: + for p in self.parameters(): + p.requires_grad = False + + # activate the projection layer + self.projection.weight.requires_grad = True + self.projection.bias.requires_grad = True + # self.positional_encoding.requires_grad = True + self.temporal_encoding.requires_grad = True + self.camera_encoding.requires_grad = True + + def forward( + self, + pixel_values: torch.Tensor, + image_sizes = None, + use_temporal_encoding: bool = True, + use_positional_encoding: bool = True, + use_camera_encoding: bool = True, + ) -> torch.Tensor: + + BS, num_frames, num_cams, num_patches, C, H, W = pixel_values.shape + + + patch_embeddings = self.image_encoder.forward_image(pixel_values=pixel_values, image_sizes=image_sizes, downsample_feature_grid_factor=self.downsample_feature_grid_factor) + patch_embeddings = self.projection(patch_embeddings) + patch_embeddings = patch_embeddings.view(-1, num_frames, num_cams, patch_embeddings.shape[-2], patch_embeddings.shape[-1]) + + input_sequence = patch_embeddings + _, _, _, n_tokens, channels = input_sequence.shape + + # temporal embeddings + if use_temporal_encoding: + input_sequence = input_sequence + self.temporal_encoding + # positional embeddings + # if use_positional_encoding: + # input_sequence = input_sequence + self.positional_encoding + # per camera embeddings + if use_camera_encoding: + input_sequence = input_sequence + self.camera_encoding + + embeds = input_sequence.view(BS, -1, channels) + + return embeds, (num_frames, n_tokens, channels) + + + +if __name__ == "__main__": + model = LLaVAnextEncoderModel( + variant="llava-hf/llava-v1.6-mistral-7b-hf", + debug=True, + embed_dim=256, + freeze=True, + ) + processor = LlavaNextProcessor.from_pretrained("llava-hf/llava-v1.6-mistral-7b-hf") + + # BS, N_FRAMES, N_CAMS, 3, H, W + # random vector between 0 and 1 + image = np.random.rand(2, 4, 2, 3, 512, 1024).astype(np.float32) + image = torch.tensor(image) + + # merge BS and N_FRAMES and N_CAMS + image = image.view(-1, 3, 512, 1024) + + inputs = processor.image_processor(image, return_tensors="pt").to("cuda:0") + # typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), typing.List[ForwardRef('PIL.Image.Image')], typing.List[numpy.ndarray], typing.List[ForwardRef('torch.Tensor')]] + + output = model(**inputs) + print(output[0].shape, output[1]) + + # output_image_shape = True + # output = model(image, output_image_shape) + # print(output.shape) \ No newline at end of file diff --git a/models/encoder/llavanext_model.py b/models/encoder/llavanext_model.py new file mode 100644 index 0000000000000000000000000000000000000000..e1d929731d548f2de2986bdd17a556fc54a1bc29 --- /dev/null +++ b/models/encoder/llavanext_model.py @@ -0,0 +1,150 @@ +import torch +from torch.nn import functional as F +from transformers import LlavaNextForConditionalGeneration +from transformers.models.llava_next.modeling_llava_next import ( + LlavaNextCausalLMOutputWithPast, + get_anyres_image_grid_shape, + unpad_image, +) +from typing import Optional, Tuple, Union + + +class LingoLlavaNextModel(LlavaNextForConditionalGeneration): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.use_global_img = None + + def forward_image( + self, + pixel_values: torch.FloatTensor = None, + image_sizes: Optional[torch.LongTensor] = None, + vision_feature_layer: Optional[int] = None, + vision_feature_select_strategy: Optional[str] = None, + downsample_feature_grid_factor: Optional[int] = None, + ) -> Union[Tuple, LlavaNextCausalLMOutputWithPast]: + r""" + Args: + labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): + Labels for computing the masked language modeling loss. Indices should either be in `[0, ..., + config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored + (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`. + + Returns: + + Example: + + ```python + >>> from PIL import Image + >>> import requests + >>> from transformers import AutoProcessor, LlavaNextForConditionalGeneration + + >>> model = LlavaNextForConditionalGeneration.from_pretrained("llava-hf/llava-v1.6-mistral-7b-hf") + >>> processor = AutoProcessor.from_pretrained("llava-hf/llava-v1.6-mistral-7b-hf") + + >>> prompt = "[INST] \nWhat is shown in this image? [/INST]" + >>> url = "https://www.ilankelman.org/stopsigns/australia.jpg" + >>> image = Image.open(requests.get(url, stream=True).raw) + + >>> inputs = processor(text=prompt, images=image, return_tensors="pt") + + >>> # Generate + >>> generate_ids = model.generate(**inputs, max_length=30) + >>> processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0] + "[INST] \nWhat is shown in this image? [/INST] The image appears to be a radar chart, which is a type of multi-dimensional plot (...)" + ```""" + + vision_feature_layer = ( + vision_feature_layer if vision_feature_layer is not None else self.config.vision_feature_layer + ) + vision_feature_select_strategy = ( + vision_feature_select_strategy + if vision_feature_select_strategy is not None + else self.config.vision_feature_select_strategy + ) + + if pixel_values is not None: + batch_size, num_frames, num_cams, num_patches, num_channels, height, width = pixel_values.shape + reshaped_pixel_values = pixel_values.reshape(batch_size *num_frames * num_cams * num_patches, num_channels, height, width) + image_features = self.vision_tower(pixel_values=reshaped_pixel_values, output_hidden_states=True) + + selected_image_feature = image_features.hidden_states[vision_feature_layer] + + if len(image_features.hidden_states[-1].shape) == 4: + selected_image_feature = image_features.hidden_states[-1] + # flatten + selected_image_feature = selected_image_feature.flatten(2,3) + # swap + selected_image_feature = selected_image_feature.transpose(1, 2) + + if vision_feature_select_strategy == "default": + selected_image_feature = selected_image_feature[:, 1:] # remove the CLS token + # (BS*num_patches), num_tokens->24x24=576, hidden_size=1024... -> 24 because we have 336 pixels and use patch size of 14 + elif vision_feature_select_strategy == "full": + selected_image_feature = selected_image_feature + # (BS*num_patches), num_tokens->24x24+1=577, hidden_size=1024 + + + image_features = self.multi_modal_projector(selected_image_feature) + + image_features = list(image_features.view(batch_size * num_frames * num_cams, num_patches, image_features.shape[-2], image_features.shape[-1])) + + # split up image_features for each of the individual images + # hence we get a list of image_features, each of shape (5, num_patches, hidden_size) + # if we assume each image has 5 image features (base image + 4 patches) + # split_sizes = [image.shape[0] for image in pixel_values] + + + # image_features = torch.split(image_features, split_sizes, dim=0) + + # NOTE we only support multimodal_patch_merge_type == "spatial_unpad" + height = width = self.config.vision_config.image_size // self.config.vision_config.patch_size + + new_image_features = [] + for image_idx, image_feature in enumerate(image_features): + if image_feature.shape[0] > 1: + # image_feature: + if self.use_global_img: + base_image_feature = image_feature[0] + image_feature = image_feature[1:] + + if height * width != image_feature.shape[1]: + raise ValueError("The number of patches is not consistent with the image size.") + num_patch_height, num_patch_width = get_anyres_image_grid_shape( + image_sizes[image_idx], + self.config.image_grid_pinpoints, + self.config.vision_config.image_size, + ) + image_feature = image_feature.view(num_patch_height, num_patch_width, height, width, -1) # torch.Size([1, 3, 24, 24, 4096]) or torch.Size([2, 2, 24, 24, 4096]) + image_feature = image_feature.permute(4, 0, 2, 1, 3).contiguous() # torch.Size([4096, 1, 24, 3, 24]) or torch.Size([4096, 2, 24, 2, 24]) + image_feature = image_feature.flatten(1, 2).flatten(2, 3) # torch.Size([4096, 24, 72]) or torch.Size([4096, 48, 48]) + image_feature = unpad_image(image_feature, image_sizes[image_idx]) + if downsample_feature_grid_factor is not None: + # average pooling to downsample the feature grid + image_feature = F.avg_pool2d( + image_feature.unsqueeze(0), downsample_feature_grid_factor + ).squeeze(0) # for 2: torch.Size([4096, 12, 32]) + if self.use_global_img: + base_image_feature = base_image_feature.view(1, height, width, -1) + base_image_feature = F.avg_pool2d(base_image_feature.permute(0, 3, 1, 2), downsample_feature_grid_factor).squeeze(0).permute(1, 2, 0) + base_image_feature = base_image_feature.flatten(0, 1) + image_feature = torch.cat( + ( + image_feature, + self.image_newline[:, None, None].expand(*image_feature.shape[:-1], 1), + ), + dim=-1, + ) + image_feature = image_feature.flatten(1, 2).transpose(0, 1) + if self.use_global_img: + image_feature = torch.cat((base_image_feature, image_feature), dim=0) + else: + image_feature = image_feature[0] + if downsample_feature_grid_factor is not None: + image_feature = image_feature.view(1, height, width, -1) + image_feature = F.avg_pool2d(image_feature.permute(0, 3, 1, 2), downsample_feature_grid_factor).squeeze(0).permute(1, 2, 0) + image_feature = image_feature.flatten(0, 1) + image_feature = torch.cat((image_feature, self.image_newline[None]), dim=0) + new_image_features.append(image_feature) + image_features = torch.stack(new_image_features, dim=0) + + return image_features diff --git a/models/encoder/qwen2_5_vl.py b/models/encoder/qwen2_5_vl.py new file mode 100644 index 0000000000000000000000000000000000000000..c3a35536199b305dbf7390baffb115eeba430ed3 --- /dev/null +++ b/models/encoder/qwen2_5_vl.py @@ -0,0 +1,94 @@ +from typing import Optional + +import torch +import torch.nn.functional as F +from torch import nn +from transformers import AutoConfig +from transformers.models.qwen2_5_vl.modeling_qwen2_5_vl import Qwen2_5_VisionTransformerPretrainedModel + +from models.qwen_utils import build_empty_module, load_prefixed_safetensors + + +class Qwen2_5VLEncoderModel(nn.Module): + def __init__( + self, + variant: str, + freeze: bool = False, + max_visual_tokens: Optional[int] = None, + local_files_only: bool = True, + use_global_img: bool = False, + torch_dtype: str = "bfloat16", + ): + super().__init__() + self.config = AutoConfig.from_pretrained(variant, local_files_only=local_files_only) + self.config.vision_config._attn_implementation = "flash_attention_2" + dtype = getattr(torch, torch_dtype) + self.image_encoder = build_empty_module( + Qwen2_5_VisionTransformerPretrainedModel, self.config.vision_config + ) + load_prefixed_safetensors(self.image_encoder, variant, "visual.", torch_dtype=dtype) + + self.token_size = self.config.vision_config.out_hidden_size + self.max_visual_tokens = max_visual_tokens + self.use_global_img = use_global_img + + if freeze: + for param in self.parameters(): + param.requires_grad = False + + def forward(self, pixel_values: torch.Tensor, image_sizes: torch.Tensor = None): + if image_sizes is None: + raise ValueError("Qwen2.5-VL vision encoder requires image_grid_thw in image_sizes.") + + if image_sizes.ndim == 3: + batch_size, images_per_sample, _ = image_sizes.shape + image_grid_thw = image_sizes.reshape(batch_size * images_per_sample, 3) + elif image_sizes.ndim == 2: + image_grid_thw = image_sizes + batch_size = image_grid_thw.shape[0] + images_per_sample = 1 + else: + raise ValueError(f"Unexpected image_sizes shape: {tuple(image_sizes.shape)}") + + device = next(self.image_encoder.parameters()).device + dtype = next(self.image_encoder.parameters()).dtype + pixel_values = pixel_values.to(device=device, dtype=dtype) + image_grid_thw = image_grid_thw.to(device=device) + + outputs = self.image_encoder(pixel_values, grid_thw=image_grid_thw) + # transformers 5.x: pooler_output is the post-merger output [N_merged, out_hidden_size] + # last_hidden_state is pre-merger [N_patches, hidden_size] — NOT what we want + if hasattr(outputs, 'pooler_output') and outputs.pooler_output is not None: + image_embeds = outputs.pooler_output + elif torch.is_tensor(outputs): + image_embeds = outputs + else: + image_embeds = outputs.last_hidden_state + + split_sizes = ( + image_grid_thw.prod(-1) // (self.image_encoder.spatial_merge_size ** 2) + ).tolist() + image_embeds = torch.split(image_embeds, [int(s) for s in split_sizes]) + + samples = [] + for sample_idx in range(batch_size): + start = sample_idx * images_per_sample + end = start + images_per_sample + sample_embeds = torch.cat(image_embeds[start:end], dim=0) + if self.max_visual_tokens is not None: + sample_embeds = sample_embeds[: self.max_visual_tokens] + samples.append(sample_embeds) + + max_tokens = max(sample.shape[0] for sample in samples) + padded_samples = [] + attention_masks = [] + for sample in samples: + pad_tokens = max_tokens - sample.shape[0] + if pad_tokens > 0: + sample = F.pad(sample, (0, 0, 0, pad_tokens)) + padded_samples.append(sample) + attention_masks.append( + torch.arange(max_tokens, device=sample.device) < (max_tokens - pad_tokens) + ) + + return torch.stack(padded_samples, dim=0), torch.stack(attention_masks, dim=0) diff --git a/models/encoder/qwen3_vl.py b/models/encoder/qwen3_vl.py new file mode 100644 index 0000000000000000000000000000000000000000..bd2ae1ff1d81d8415025080b63a69b92286f40a7 --- /dev/null +++ b/models/encoder/qwen3_vl.py @@ -0,0 +1,115 @@ +from typing import Optional + +import torch +import torch.nn.functional as F +from torch import nn +from transformers import AutoConfig +from transformers.models.qwen3_vl.modeling_qwen3_vl import Qwen3VLVisionModel + +from models.qwen_utils import build_empty_module, load_prefixed_safetensors +from utils.logging_project import rank_zero_print + + +class Qwen3VLEncoderModel(nn.Module): + """ + Qwen3-VL vision encoder in native video mode. + + Consumes video patches (pixel_values_videos) with video_grid_thw and returns: + - merged video token embeddings [B, N, out_hidden_size] + - attention mask [B, N] + - deepstack features: list of 3 tensors [B, N, out_hidden_size] + (from vision blocks 8/16/24, already projected by deepstack mergers) + """ + + def __init__( + self, + variant: str, + freeze: bool = False, + max_visual_tokens: Optional[int] = None, + local_files_only: bool = True, + use_global_img: bool = False, + torch_dtype: str = "bfloat16", + ): + super().__init__() + self.config = AutoConfig.from_pretrained(variant, local_files_only=local_files_only) + dtype = getattr(torch, torch_dtype) + self.config.vision_config._attn_implementation = "flash_attention_2" + self.config.vision_config.dtype = dtype + rank_zero_print("Loading Qwen3-VL vision encoder (meta init)...", flush=True) + self.image_encoder = build_empty_module(Qwen3VLVisionModel, self.config.vision_config) + rank_zero_print("Loading vision weights...", flush=True) + load_prefixed_safetensors(self.image_encoder, variant, "model.visual.", torch_dtype=dtype) + rank_zero_print("Vision encoder ready.", flush=True) + + self.token_size = self.config.vision_config.out_hidden_size + self.spatial_merge_size = self.config.vision_config.spatial_merge_size + self.num_deepstack_layers = len(self.config.vision_config.deepstack_visual_indexes) + self.max_visual_tokens = max_visual_tokens + self.use_global_img = use_global_img + + if freeze: + for param in self.parameters(): + param.requires_grad = False + + def forward(self, pixel_values: torch.Tensor, image_sizes: torch.Tensor = None): + """ + Args: + pixel_values: [total_patches, patch_dim] video patches from Qwen3VLVideoProcessor + (concatenated over the batch). + image_sizes: video_grid_thw. Either [B, 3] (one video per sample) or + [B, 1, 3]. + """ + if image_sizes is None: + raise ValueError("Qwen3-VL vision encoder requires video_grid_thw in image_sizes.") + + if image_sizes.ndim == 3: + video_grid_thw = image_sizes.reshape(-1, 3) + elif image_sizes.ndim == 2: + video_grid_thw = image_sizes + else: + raise ValueError(f"Unexpected image_sizes shape: {tuple(image_sizes.shape)}") + batch_size = video_grid_thw.shape[0] + + device = next(self.image_encoder.parameters()).device + dtype = next(self.image_encoder.parameters()).dtype + pixel_values = pixel_values.to(device=device, dtype=dtype) + video_grid_thw = video_grid_thw.to(device=device) + + outputs = self.image_encoder(pixel_values, grid_thw=video_grid_thw) + video_embeds = outputs.pooler_output # [total_merged_tokens, out_hidden_size] + deepstack_features = outputs.deepstack_features # list of [total_merged_tokens, out_hidden_size] + + split_sizes = ( + video_grid_thw.prod(-1) // (self.spatial_merge_size ** 2) + ).tolist() + split_sizes = [int(s) for s in split_sizes] + + video_embeds = torch.split(video_embeds, split_sizes) + deepstack_split = [torch.split(feat, split_sizes) for feat in deepstack_features] + + max_tokens = max(int(s) for s in split_sizes) + if self.max_visual_tokens is not None: + max_tokens = min(max_tokens, self.max_visual_tokens) + + padded_embeds = [] + padded_deepstack = [[] for _ in range(len(deepstack_features))] + attention_masks = [] + for sample_idx in range(batch_size): + sample = video_embeds[sample_idx][:max_tokens] + valid = sample.shape[0] + pad = max_tokens - valid + if pad > 0: + sample = F.pad(sample, (0, 0, 0, pad)) + padded_embeds.append(sample) + attention_masks.append(torch.arange(max_tokens, device=sample.device) < valid) + for layer_idx in range(len(deepstack_features)): + ds = deepstack_split[layer_idx][sample_idx][:max_tokens] + if pad > 0: + ds = F.pad(ds, (0, 0, 0, pad)) + padded_deepstack[layer_idx].append(ds) + + video_embeds = torch.stack(padded_embeds, dim=0) # [B, N, C] + attention_mask = torch.stack(attention_masks, dim=0) # [B, N] + deepstack_embeds = [torch.stack(layer, dim=0) for layer in padded_deepstack] # 3 x [B, N, C] + + return video_embeds, attention_mask, deepstack_embeds diff --git a/models/encoder/resnet.py b/models/encoder/resnet.py new file mode 100644 index 0000000000000000000000000000000000000000..88d6a71707f643d7255ccea759fbe75fffc383a1 --- /dev/null +++ b/models/encoder/resnet.py @@ -0,0 +1,106 @@ +import numpy as np +import torch +from torch import nn +from transformers import AutoModel, LlavaNextProcessor + +class ResnetEncoderModel(nn.Module): + def __init__(self, + variant: str, + embed_dim: int, + freeze: bool, + downsample_feature_grid_factor: int = 2, + use_global_img = False, + ): + + super().__init__() + self.num_cameras = 1 + self.num_frames = 1 + self.token_size = embed_dim + + self.downsample_feature_grid_factor = downsample_feature_grid_factor + + self.image_encoder = AutoModel.from_pretrained(variant) + + self.projection = nn.Linear(self.image_encoder.config.hidden_sizes[-1], embed_dim) + # Embeddings: BS, N_FRAMES, N_CAMS, N_PATCHES, EMBED_DIM + self.temporal_encoding = nn.Parameter(0.02 * torch.randn(1, self.num_frames, 1, 1, embed_dim)) + self.camera_encoding = nn.Parameter(0.02 * torch.randn(1, 1, self.num_cameras, 1, embed_dim)) + # self.positional_encoding = nn.Parameter(torch.zeros(1, 1, 1, tokens_per_frame, embed_dim)).to("cuda:0") + + # freeze the paramaeters -> no gradient updates + if freeze: + for p in self.parameters(): + p.requires_grad = False + + # activate the projection layer + self.projection.weight.requires_grad = True + self.projection.bias.requires_grad = True + # self.positional_encoding.requires_grad = True + self.temporal_encoding.requires_grad = True + self.camera_encoding.requires_grad = True + + def forward( + self, + pixel_values: torch.Tensor, + image_sizes = None, + use_temporal_encoding: bool = True, + use_positional_encoding: bool = True, + use_camera_encoding: bool = True, + ) -> torch.Tensor: + + BS, num_frames, num_cams, C, H, W = pixel_values.shape + + pixel_values = pixel_values.squeeze().view(1, C, H, W) + + + img_embeddings = self.image_encoder(pixel_values=pixel_values).last_hidden_state # torch.Size([4, 512, 12, 32]) + img_embeddings = img_embeddings.flatten(2,3).transpose(1, 2) # torch.Size([4, 384, 512]) + + img_embeddings = self.projection(img_embeddings) + img_embeddings = img_embeddings.view(-1, num_frames, num_cams, img_embeddings.shape[-2], img_embeddings.shape[-1]) + + input_sequence = img_embeddings + _, _, _, n_tokens, channels = input_sequence.shape + + # temporal embeddings + if use_temporal_encoding: + input_sequence = input_sequence + self.temporal_encoding + # positional embeddings + # if use_positional_encoding: + # input_sequence = input_sequence + self.positional_encoding + # per camera embeddings + if use_camera_encoding: + input_sequence = input_sequence + self.camera_encoding + + embeds = input_sequence.view(BS, -1, channels) + + return embeds, (num_frames, n_tokens, channels) + + + +if __name__ == "__main__": + model = ResnetEncoderModel( + variant="llava-hf/llava-v1.6-mistral-7b-hf", + debug=True, + embed_dim=256, + freeze=True, + ) + processor = LlavaNextProcessor.from_pretrained("llava-hf/llava-v1.6-mistral-7b-hf") + + # BS, N_FRAMES, N_CAMS, 3, H, W + # random vector between 0 and 1 + image = np.random.rand(2, 4, 2, 3, 512, 1024).astype(np.float32) + image = torch.tensor(image) + + # merge BS and N_FRAMES and N_CAMS + image = image.view(-1, 3, 512, 1024) + + inputs = processor.image_processor(image, return_tensors="pt").to("cuda:0") + # typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), typing.List[ForwardRef('PIL.Image.Image')], typing.List[numpy.ndarray], typing.List[ForwardRef('torch.Tensor')]] + + output = model(**inputs) + print(output[0].shape, output[1]) + + # output_image_shape = True + # output = model(image, output_image_shape) + # print(output.shape) \ No newline at end of file diff --git a/models/fastvlm.py b/models/fastvlm.py new file mode 100644 index 0000000000000000000000000000000000000000..59c8f35add63c7b3a0a04497fa74e945029c630b --- /dev/null +++ b/models/fastvlm.py @@ -0,0 +1,125 @@ +"""Adapters for Apple's official PyTorch FastVLM checkpoint. + +The vision tower, pretrained projector and Qwen2 trunk are loaded ONCE and +then assigned disjoint ownership. No replacement/random projector is used. +""" +import os +import sys +from pathlib import Path +import torch +import torch.nn.functional as F +from torch import nn + + +class FastVLMVisionAdapter(nn.Module): + def __init__(self, tower, projector, hidden_size, image_size=(448, 896), freeze=True): + super().__init__() + self.image_encoder, self.projector = tower, projector + self.token_size = hidden_size + self.image_size = tuple(image_size) + self.use_global_img = False + self.frozen = freeze + self.image_encoder.requires_grad_(not freeze) + if hasattr(self.image_encoder, 'tune_vision_tower'): + self.image_encoder.tune_vision_tower = not freeze + + def train(self, mode=True): + super().train(mode) + if self.frozen: + self.image_encoder.eval() + return self + + def forward(self, images, image_sizes=None): + if images.ndim == 6: + if images.shape[1:3] != (1, 1): + raise ValueError('FastVLM/PIM requires exactly ONE current front image') + images = images[:, 0, 0] + if images.ndim != 4 or images.shape[1] != 3: + raise ValueError('Expected RGB [B,3,H,W] or [B,1,1,3,H,W]') + # Both training and deployment supply raw RGB in [0,255]. MobileCLIP + # uses mean=0/std=1. Resize once, preserving the intended wide FOV. + images = F.interpolate(images.float() / 255., size=self.image_size, + mode='bilinear', align_corners=False, antialias=True) + parameter = next(self.image_encoder.parameters()) + images = images.to(device=parameter.device, dtype=parameter.dtype) + features = self.image_encoder(images) + features = self.projector(features.to(next(self.projector.parameters()).dtype)) + mask = torch.ones(features.shape[:2], device=features.device, dtype=torch.long) + return features, mask + + +class FastVLMLanguageAdapter(nn.Module): + def __init__(self, core, tokenizer, freeze=False, lora=True, lora_r=16, + lora_alpha=32, lora_dropout=0.05): + super().__init__() + self.model, self.tokenizer = core, tokenizer + self.hidden_size = core.config.hidden_size + self.vocab_size = core.config.vocab_size + if tokenizer.pad_token_id is None: + tokenizer.pad_token = tokenizer.eos_token + if freeze or lora: + self.model.requires_grad_(False) + if lora: + from peft import LoraConfig, get_peft_model + self.model = get_peft_model(self.model, LoraConfig( + r=lora_r, lora_alpha=lora_alpha, lora_dropout=lora_dropout, + target_modules=['q_proj', 'k_proj', 'v_proj', 'o_proj', + 'gate_proj', 'up_proj', 'down_proj'])) + + @property + def embed_tokens(self): + core = self.model.get_base_model() if hasattr(self.model, 'get_base_model') else self.model + return core.embed_tokens + + def forward(self, embeddings, attention_mask=None, **kwargs): + return self.model(inputs_embeds=embeddings, attention_mask=attention_mask, + use_cache=False, return_dict=True).last_hidden_state + + +def load_fastvlm(variant, source_path=None, torch_dtype='bfloat16', + local_files_only=True, freeze_vision=True, freeze_language=False, + lora=True, lora_r=16, lora_alpha=32, lora_dropout=0.05, + image_size=(448, 896), attn_implementation='sdpa'): + checkpoint = Path(variant).expanduser() + if local_files_only and not checkpoint.is_dir(): + raise FileNotFoundError(f'FastVLM checkpoint directory missing: {checkpoint}') + source_path = source_path or os.environ.get('FASTVLM_SOURCE') + if source_path: + source = Path(source_path).expanduser().resolve() + if not (source / 'llava/model/language_model/llava_qwen.py').is_file(): + raise FileNotFoundError(f'Not the official ml-fastvlm source tree: {source}') + sys.path.insert(0, str(source)) + try: + from llava.model.language_model.llava_qwen import LlavaQwen2ForCausalLM + from transformers import AutoTokenizer + except ImportError as exc: + raise ImportError('Install the official apple/ml-fastvlm source and set ' + 'FASTVLM_SOURCE; see docs/PIM.md for dependencies') from exc + dtype = getattr(torch, torch_dtype) + config = LlavaQwen2ForCausalLM.config_class.from_pretrained( + str(checkpoint), local_files_only=local_files_only) + # Construct the tower BEFORE loading its checkpoint tensors. Lazy loading + # afterwards would silently leave a newly initialised visual encoder. + config.unfreeze_mm_vision_tower = True + full, info = LlavaQwen2ForCausalLM.from_pretrained( + str(checkpoint), config=config, torch_dtype=dtype, + local_files_only=local_files_only, attn_implementation=attn_implementation, + output_loading_info=True) + missing = [k for k in info.get('missing_keys', []) + if 'vision_tower' in k or 'mm_projector' in k] + if missing: + raise RuntimeError(f'Checkpoint does not contain complete visual weights: {missing[:8]}') + core = full.get_model() + tower, projector = core.get_vision_tower(), core.mm_projector + if not getattr(tower, 'is_loaded', True): + raise RuntimeError('FastVLM vision tower was not constructed during checkpoint loading') + del core.vision_tower + del core.mm_projector + if hasattr(core, 'image_newline'): + del core.image_newline + tokenizer = AutoTokenizer.from_pretrained(str(checkpoint), local_files_only=local_files_only) + vision = FastVLMVisionAdapter(tower, projector, core.config.hidden_size, + image_size=image_size, freeze=freeze_vision) + language = FastVLMLanguageAdapter(core, tokenizer, freeze_language, lora, + lora_r, lora_alpha, lora_dropout) + return vision, language diff --git a/models/fastvlm_driving.py b/models/fastvlm_driving.py new file mode 100644 index 0000000000000000000000000000000000000000..e608f6d62732bb5d8ca1c46a76543b17b7bf7825 --- /dev/null +++ b/models/fastvlm_driving.py @@ -0,0 +1,74 @@ +"""Current-frame FastVLM driving model (FIVE-VLA stage 1: no memory, IID samples).""" +import math +from collections import defaultdict + +import torch +from torch import nn + +from models.driving import DrivingModel +from models.fastvlm import load_fastvlm + + +class FastVLMDrivingModel(DrivingModel): + def __init__(self, fastvlm=None, vision_bn_train=False, freeze_embeddings=True, + min_lr_ratio=0.05, vision_model=None, language_model=None, **kwargs): + if (vision_model is None) != (language_model is None): + raise ValueError('Provide both injected vision/language adapters, or neither') + if vision_model is None: + if fastvlm is None: + raise ValueError('FastVLM configuration is required') + vision_model, language_model = load_fastvlm(**dict(fastvlm)) + super().__init__(vision_model=vision_model, language_model=language_model, **kwargs) + if self.use_world_loss or self.use_consequence_loss or self.use_deepstack: + raise ValueError('FastVLMDrivingModel trains the plain route/speed heads only') + self.vision_bn_train = bool(vision_bn_train) + self.min_lr_ratio = float(min_lr_ratio) + # The CLIP projection head never receives gradients (DDP would reject it), + # and AdamW decay would shrink every row of the 151k-token embedding table. + for name, parameter in self.vision_model.named_parameters(): + if name.startswith('image_encoder.vision_tower.model.head.'): + parameter.requires_grad_(False) + if freeze_embeddings: + self.language_model.embed_tokens.requires_grad_(False) + + def train(self, mode=True): + super().train(mode) + if mode and not self.vision_bn_train: + for module in self.vision_model.modules(): + if isinstance(module, nn.modules.batchnorm._BatchNorm): + module.eval() + return self + + def configure_optimizers(self): + # Explicit groups: FastViTHD has bare layer_scale parameters that the + # legacy module-type whitelist in configure_params_groups rejects. + groups = defaultdict(list) + for name, parameter in self.named_parameters(): + if not parameter.requires_grad: + continue + if name.startswith('vision_model.'): + lr = self.vision_lr if self.vision_lr is not None else self.lr + elif name.startswith('language_model.'): + lr = self.lm_lr if self.lm_lr is not None else self.lr + else: + lr = self.lr + decay = parameter.ndim >= 2 and not any( + key in name for key in ('query_embeds', 'layer_scale')) + groups[(lr, decay)].append(parameter) + optimizer = torch.optim.AdamW( + [{'params': params, 'lr': lr, 'weight_decay': self.weight_decay if decay else 0.0} + for (lr, decay), params in groups.items()], + betas=self.betas) + total = max(1, int(self.trainer.estimated_stepping_batches)) + warmup = max(1, int(self.pct_start * total)) + floor = self.min_lr_ratio + + def schedule(step): + if step < warmup: + return (step + 1) / warmup + progress = min(1.0, (step - warmup) / max(1, total - warmup)) + return floor + (1.0 - floor) * 0.5 * (1.0 + math.cos(math.pi * progress)) + + scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, schedule) + return {'optimizer': optimizer, 'lr_scheduler': { + 'scheduler': scheduler, 'interval': 'step', 'frequency': 1}} diff --git a/models/fastvlm_object_driving.py b/models/fastvlm_object_driving.py new file mode 100644 index 0000000000000000000000000000000000000000..603f66ad7b4c1a52bef404d975748ef3854ca92e --- /dev/null +++ b/models/fastvlm_object_driving.py @@ -0,0 +1,194 @@ +"""Stage 3: FastVLM driving model with object-bank tokens and a per-object relation head. + +Object rows (dataloader.object_bank: position, heading, speed, size, class, visibility, time unseen) +enter the LM as extra tokens after the fixed inputs and before the action queries, through an MLP +whose last layer is zero-initialised so training starts from the stage-1 behaviour. The LM output at +each object token predicts the expert's relation to that object (ignore / follow / yield); the action +queries read those positions through causal attention. +""" +import torch +import torch.nn.functional as F +from torch import nn + +from dataloader.object_bank import DEFAULT_BANK, FEAT_DIM, RELATION_NAMES, RELATION_PAD +from models.fastvlm_driving import FastVLMDrivingModel +from models.utils import summarise_losses + + +class ObjectTokenAdaptor(nn.Module): + def __init__(self, feat_dim, token_size, hidden_size=256): + super().__init__() + self.type_embed = nn.Parameter(0.02 * torch.randn(1, 1, token_size)) + self.mlp = nn.Sequential(nn.Linear(feat_dim, hidden_size), nn.SiLU(True), + nn.Linear(hidden_size, token_size)) + nn.init.zeros_(self.mlp[-1].weight) + nn.init.zeros_(self.mlp[-1].bias) + + def forward(self, objects): + return self.type_embed + self.mlp(objects) + + +FEAT_SPEED, FEAT_VISIBLE, FEAT_UNSEEN, FEAT_AGE = 4, 10, 11, 12 +# 'full': every bank row; 'visible_only': rows currently in view (no memory of objects that left the +# view or got occluded); 'single_frame': visible_only without the quantities that need association +# over time (speed, time unseen, track age), i.e. what a per-frame detector provides. +FEATURE_MODES = ('full', 'visible_only', 'single_frame') + + +class FastVLMObjectDrivingModel(FastVLMDrivingModel): + uses_object_tokens = True + + def __init__(self, objects=None, **kwargs): + super().__init__(**kwargs) + cfg = dict(objects or {}) + self.object_bank_config = {key: cfg.get(key, value) for key, value in DEFAULT_BANK.items()} + self.max_objects = int(self.object_bank_config['max_objects']) + self.relation_loss_weight = float(cfg.get('relation_loss_weight', 0.3)) + self.object_dropout_p = float(cfg.get('object_dropout_p', 0.1)) + self.feature_mode = str(cfg.get('feature_mode', 'full')) + if self.feature_mode not in FEATURE_MODES: + raise ValueError(f'objects.feature_mode must be one of {FEATURE_MODES}, got {self.feature_mode}') + weights = cfg.get('relation_class_weights', [0.25, 1.0, 1.0]) + self.register_buffer('relation_class_weights', torch.tensor(list(weights), dtype=torch.float), + persistent=False) + hidden = self.language_model.hidden_size + self.object_encoder = ObjectTokenAdaptor(FEAT_DIM, hidden, int(cfg.get('hidden_size', 256))) + self.relation_head = nn.Sequential(nn.Linear(hidden, 256), nn.SiLU(True), + nn.Linear(256, len(RELATION_NAMES))) + self._object_outputs = None + self._object_mask = None + self._relation_stats = None + + # ------------------------------------------------------------------ inputs + def encode_objects(self, driving_input, batch_size, device): + objects = getattr(driving_input, 'objects', None) + mask = getattr(driving_input, 'object_mask', None) + if objects is None: + objects = torch.zeros(batch_size, self.max_objects, FEAT_DIM, device=device) + mask = torch.zeros(batch_size, self.max_objects, dtype=torch.bool, device=device) + objects = objects.to(device=device, dtype=torch.float32) + mask = mask.to(device=device, dtype=torch.bool) + if self.feature_mode != 'full': + mask = mask & (objects[..., FEAT_VISIBLE] > 0.5) + if self.feature_mode == 'single_frame': + objects = objects.clone() + objects[..., [FEAT_SPEED, FEAT_UNSEEN, FEAT_AGE]] = 0.0 + if self.training and self.object_dropout_p > 0: + keep = torch.rand(batch_size, device=device) >= self.object_dropout_p + mask = mask & keep[:, None] + tokens = self.object_encoder(objects) * mask.unsqueeze(-1).to(torch.float32) + return tokens, mask + + def forward_model(self, driving_input, adaptor_embeds, driving_labels=None, return_context=False): + fixed_embeds, attention_mask, _ = self.get_fixed_input_embeds(driving_input) + batch_size, device = fixed_embeds.size(0), fixed_embeds.device + object_embeds, object_mask = self.encode_objects(driving_input, batch_size, device) + dtype = self.language_model.model.dtype + input_embeds = torch.cat((fixed_embeds, object_embeds.to(fixed_embeds.dtype), adaptor_embeds), dim=1) + attention_mask = torch.cat(( + attention_mask, + object_mask.long(), + torch.ones(adaptor_embeds.shape[:2], dtype=torch.long, device=device), + ), dim=1) + outputs = self.language_model.forward(input_embeds.to(dtype=dtype), attention_mask=attention_mask) + n_fixed, n_obj = fixed_embeds.size(1), object_embeds.size(1) + fixed_outputs, object_outputs, adaptor_outputs = outputs.split( + [n_fixed, n_obj, adaptor_embeds.size(1)], dim=1) + self._object_outputs = object_outputs + self._object_mask = object_mask + if return_context: + return adaptor_outputs, fixed_outputs, attention_mask[:, :n_fixed] + return adaptor_outputs + + # ------------------------------------------------------------------ outputs + def relation_logits(self): + """[B, N, 3] relation logits for the object tokens of the last forward pass.""" + if self._object_outputs is None: + return None + return self.relation_head(self._object_outputs.float()) + + def _relation_loss(self, label): + target = getattr(label, 'object_relation', None) + if target is None or self._object_outputs is None: + return None + target = target.to(self._object_outputs.device).clone() + target[~self._object_mask] = RELATION_PAD # objects dropped in encode_objects carry no label + logits = self.relation_logits() + per_object = F.cross_entropy(logits.transpose(1, 2), target, weight=self.relation_class_weights, + ignore_index=RELATION_PAD, reduction='none') + labelled = (target != RELATION_PAD) + per_sample = per_object.sum(1) / labelled.sum(1).clamp_min(1) + counts = labelled.any(1).long() + with torch.no_grad(): + # Fixed-shape (correct, total) counts: row 0 = all labelled objects, rows 1.. = per class. + # Fixed shape matters under DDP: per-rank dicts with varying keys would desynchronise + # the epoch-end all-reduce. + pred = logits.argmax(-1) + stats = torch.zeros(len(RELATION_NAMES) + 1, 2, device=logits.device) + stats[0, 0] = (pred[labelled] == target[labelled]).sum() + stats[0, 1] = labelled.sum() + for cls in range(len(RELATION_NAMES)): + sel = labelled & (target == cls) + stats[cls + 1, 0] = (pred[sel] == cls).sum() + stats[cls + 1, 1] = sel.sum() + self._relation_stats = stats + return per_sample * self.relation_loss_weight, counts + + @staticmethod + def _stats_to_metrics(stats): + metrics = {} + if stats[0, 1] > 0: + metrics['relation_acc'] = stats[0, 0] / stats[0, 1] + for cls, name in enumerate(RELATION_NAMES): + if stats[cls + 1, 1] > 0: + metrics[f'relation_recall_{name}'] = stats[cls + 1, 0] / stats[cls + 1, 1] + return metrics + + @property + def _relation_metrics(self): + stats = getattr(self, '_relation_stats', None) + return None if stats is None else self._stats_to_metrics(stats) + + def forward_loss(self, example, per_sample=False): + adaptor_dict = self.adaptors(example) + adaptor_outputs = self.forward_model(example.driving_input, adaptor_dict['inputs'], + driving_labels=example.driving_label) + loss_dict = self.adaptors.compute_loss(adaptor_outputs, adaptor_dict, example) + loss_dict.pop('latent_features', None) + relation = self._relation_loss(example.driving_label) + if relation is not None: + loss_dict['relation_loss'] = relation + losses = {k: v for k, v in loss_dict.items() if k.endswith('loss')} + predictions = {k: v for k, v in loss_dict.items() if not k.endswith('loss')} + if per_sample: + return losses, predictions + return summarise_losses(losses) + + def training_step(self, batch, batch_idx=0): + out = super().training_step(batch, batch_idx) + stats = getattr(self, '_relation_stats', None) + self._relation_stats = None + if stats is not None: # per-rank step metrics, no collective involved + for key, value in self._stats_to_metrics(stats).items(): + self.log(f'train_metrics/{key}', value, on_step=True, on_epoch=False, sync_dist=False, logger=True) + return out + + def on_validation_epoch_start(self): + self._val_relation_stats = torch.zeros(len(RELATION_NAMES) + 1, 2, device=self.device) + + def validation_step(self, batch, batch_idx=0): + out = super().validation_step(batch, batch_idx) + stats = getattr(self, '_relation_stats', None) + self._relation_stats = None + if stats is not None: + self._val_relation_stats += stats + return out + + def on_validation_epoch_end(self): + stats = getattr(self, '_val_relation_stats', None) + if stats is None: + return + stats = self.trainer.strategy.reduce(stats, reduce_op='sum') # one fixed-shape all-reduce per rank + for key, value in self._stats_to_metrics(stats).items(): + self.log(f'val_metrics/{key}', value, on_step=False, on_epoch=True, sync_dist=False, logger=True) + self._val_relation_stats = None diff --git a/models/language_model/__init__.py b/models/language_model/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/models/language_model/__init__.py @@ -0,0 +1 @@ + diff --git a/models/language_model/llama.py b/models/language_model/llama.py new file mode 100644 index 0000000000000000000000000000000000000000..4ca4b435e1e70af8b3514784ade5f585371bf47c --- /dev/null +++ b/models/language_model/llama.py @@ -0,0 +1,194 @@ +import torch +from torch import Tensor, nn +from torch.nn import functional as F +from transformers import AutoTokenizer, LlamaConfig, LlamaModel +from typing import Any, Dict, Optional, Tuple + + +CONFIGS: Dict[str, Dict[str, Any]] = { + "debug": dict(num_hidden_layers=2, num_attention_heads=2, hidden_size=32, intermediate_size=64), + "legacy-tiny": dict(num_hidden_layers=8, num_attention_heads=16, hidden_size=2048, intermediate_size=4096), + # -- auto-regressive driving models -- + "tiny": dict(num_hidden_layers=12, num_attention_heads=8, hidden_size=512, intermediate_size=2048), # 50M + "x-small": dict(num_hidden_layers=14, num_attention_heads=8, hidden_size=1024, intermediate_size=4096), # 235M + "small": dict(num_hidden_layers=22, num_attention_heads=8, hidden_size=1024, intermediate_size=4096), # 369M + "medium": dict(num_hidden_layers=22, num_attention_heads=12, hidden_size=1536, intermediate_size=4096), # 623M + "large": dict(num_hidden_layers=22, num_attention_heads=16, hidden_size=2048, intermediate_size=5632), # 1.1B + # -- gaia world models -- + "gaia-large": dict(num_hidden_layers=22, num_attention_heads=16, hidden_size=1536, intermediate_size=4096), # 623M + # -- language models -- + "7B": dict(num_hidden_layers=32, num_attention_heads=32, hidden_size=4096, intermediate_size=11008), # 6476M + "13B": dict(num_hidden_layers=40, num_attention_heads=40, hidden_size=5120, intermediate_size=11008), + "70B": dict( + num_hidden_layers=80, num_attention_heads=64, hidden_size=8192, intermediate_size=28672, num_key_value_heads=8 + ), + "tiny-llama-1.1b": dict( # 969M + num_hidden_layers=22, num_attention_heads=32, hidden_size=2048, intermediate_size=5632, num_key_value_heads=4 + ), + "phi": dict( + num_hidden_layers=24, + num_attention_heads=32, + hidden_size=2048, + intermediate_size=8192, + partial_rotary_factor=0.5, + bias=True, + vocab_size=51200, + norm_type="layer_norm", + mlp_type="gelu_new", + parallel_attn_mlp=True, + ), +} + + +class Llama(nn.Module): + def __init__(self, variant: str, lora: bool = False): + super().__init__() + + config_overrides = CONFIGS[variant].copy() + + configuration = LlamaConfig(**config_overrides) + + # Initializing a model from the llama-7b style configuration + self.model = LlamaModel(configuration) + self.tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-hf") # Add huggingface token + self.model.embed_tokens = None + # self.model.base_model.embed_tokens = None + if self.tokenizer.pad_token is None: + self.tokenizer.pad_token = self.tokenizer.eos_token + + if lora: + from peft import get_peft_model + from peft import LoraConfig, TaskType + + peft_config = LoraConfig( + inference_mode=False, + r=16, + lora_alpha=32, + lora_dropout=0.1, + target_modules="all-linear" + ) + self.model = get_peft_model(self.model, peft_config) + self.model.print_trainable_parameters() + + self.vocab_size = self.model.config.vocab_size + self.hidden_size = self.model.config.hidden_size + self.max_position_embeddings = self.model.config.max_position_embeddings + + + def forward(self, + embeddings: Tensor, + attention_mask: Tensor = None, + return_dict: bool = True, + ) -> Tensor: + + outputs = self.model( + inputs_embeds=embeddings, + attention_mask=attention_mask, + output_hidden_states=True, + return_dict=return_dict + )#.last_hidden_state + outputs = outputs.hidden_states[-1] + + return outputs + + def sample_categorical( + self, + logits: Tensor, + temperature: float = 0.0, + top_k: Optional[int] = None, + top_p: Optional[float] = None, + restrict_tokens: Optional[Tuple[int, int]] = None, + ): + if restrict_tokens is not None: + logits[..., : restrict_tokens[0]] = -float("inf") + logits[..., restrict_tokens[0] + restrict_tokens[1] :] = -float("inf") + + if temperature <= 0.0: + return logits.argmax(dim=-1, keepdim=False) + + if top_k is not None: + v, _ = torch.topk(logits, min(top_k, logits.size(-1))) + pivot = v.select(-1, -1).unsqueeze(-1) + logits = torch.where(logits < pivot, -float("inf"), logits) + + temperature = max(temperature, 1e-9) + logits = logits / temperature + + if top_p is not None: + sorted_logits, sorted_indices = torch.sort(logits, descending=True, dim=-1) + cumulative_probs = torch.softmax(sorted_logits, dim=-1).cumsum(dim=-1) + # Shift the indices to the right to keep also the first token above the threshold + mask = (cumulative_probs > top_p).roll(shifts=1, dims=-1) + mask[..., 0] = False + logits[mask.gather(-1, sorted_indices.argsort(-1))] = -float("inf") + + return torch.multinomial(logits.softmax(dim=-1), 1).squeeze(-1) + + def greedy_sample( + self, + input_embeds: Tensor, + inputs_mask: Optional[Tensor] = None, + max_new_tokens: int = 100, + temperature: float = 0.0, + top_k: Optional[int] = None, + top_p: Optional[float] = None, + eos_token_id: Optional[int] = None, + cache_offset: int = 0, + input_embed_matrix: Optional[Tensor] = None, + logit_matrix: Optional[Tensor] = None, + restrict_tokens: Optional[Tuple[int, int]] = None, + ) -> Tuple[Tensor, int]: + + if input_embed_matrix is None: + if self.embed_tokens is None: + raise ValueError( + "No input embeddings available because the model doesn't define a vocab. " + "Please provide input_embed_matrix. " + ) + input_embed_matrix = self.embed_tokens.weight + if logit_matrix is None: + if self.lm_head is None: + raise ValueError( + "No logit matrix available because the model doesn't define a vocab. " + "Please provide logit_matrix. " + ) + logit_matrix = self.lm_head.weight + # We generate tokens up to the eos token id if provided. If not provided, we generate until the end. + # If no eos token id is provided, use -1 instead, so we will never stop generating until 'new_token'. + sampled_tokens = torch.empty((input_embeds.size(0), max_new_tokens), device=input_embeds.device, dtype=torch.long) + if eos_token_id is not None: + sampled_tokens.fill_(eos_token_id) + + # we start with all sequences left to complete + incomplete_seq_mask = torch.ones(input_embeds.size(0), dtype=torch.bool, device=input_embeds.device) + for i in range(max_new_tokens): + outputs = self.forward(embeddings=input_embeds) + last_hidden_state = outputs[:, -1] + + # sample the next token + logits = F.linear(last_hidden_state, logit_matrix) + next_token = self.sample_categorical( + logits, temperature=temperature, top_k=top_k, top_p=top_p, restrict_tokens=restrict_tokens + ) + x = F.embedding(next_token.unsqueeze(1), input_embed_matrix) + + input_embeds = torch.cat([input_embeds, x], dim=1) + attn_mask = None + + # only update sequences where we haven't predicted the eos token before + sampled_tokens[incomplete_seq_mask, i] = next_token[incomplete_seq_mask] + + if eos_token_id is not None: + # only update the mask of incomplete sequences and stop early if an eos token id is provided. + incomplete_seq_mask = sampled_tokens[:, i] != eos_token_id + if not incomplete_seq_mask.any(): + # finished all sequences, early exit + sampled_tokens = sampled_tokens[:, : i + 1] + break + + return sampled_tokens, input_embeds + + +if __name__ == "__main__": + model = Llama("x-small", False) + print(model) \ No newline at end of file diff --git a/models/language_model/qwen2_5_vl.py b/models/language_model/qwen2_5_vl.py new file mode 100644 index 0000000000000000000000000000000000000000..e0b9f2a0f03d5c895c9bbc13a882c5f9a916296f --- /dev/null +++ b/models/language_model/qwen2_5_vl.py @@ -0,0 +1,83 @@ +from typing import Optional + +import torch +from torch import Tensor, nn +from transformers import AutoConfig, AutoTokenizer +from transformers.models.qwen2_5_vl.modeling_qwen2_5_vl import Qwen2_5_VLTextModel + +from models.qwen_utils import build_empty_module, load_prefixed_safetensors + + +class Qwen2_5VLLanguageModel(nn.Module): + def __init__( + self, + variant: str, + freeze: bool = False, + lora: bool = False, + lora_r: int = 16, + lora_alpha: int = 32, + lora_dropout: float = 0.1, + local_files_only: bool = True, + torch_dtype: str = "bfloat16", + ): + super().__init__() + self.config = AutoConfig.from_pretrained(variant, local_files_only=local_files_only) + self.config.text_config._attn_implementation = "flash_attention_2" + dtype = getattr(torch, torch_dtype) + self.model = build_empty_module(Qwen2_5_VLTextModel, self.config.text_config) + load_prefixed_safetensors(self.model, variant, "model.", torch_dtype=dtype) + + self.tokenizer = AutoTokenizer.from_pretrained(variant, local_files_only=local_files_only) + if self.tokenizer.pad_token is None: + self.tokenizer.pad_token = self.tokenizer.eos_token + + self.vocab_size = self.model.config.vocab_size + self.hidden_size = self.model.config.hidden_size + self.max_position_embeddings = self.model.config.max_position_embeddings + + if freeze: + for param in self.model.parameters(): + param.requires_grad = False + + if lora: + from peft import LoraConfig, get_peft_model + + peft_config = LoraConfig( + inference_mode=False, + r=lora_r, + lora_alpha=lora_alpha, + lora_dropout=lora_dropout, + target_modules=[ + "q_proj", + "k_proj", + "v_proj", + "o_proj", + "gate_proj", + "up_proj", + "down_proj", + ], + ) + self.model = get_peft_model(self.model, peft_config) + self.model.print_trainable_parameters() + + def forward( + self, + embeddings: Tensor, + attention_mask: Optional[Tensor] = None, + return_dict: bool = True, + ) -> Tensor: + if attention_mask is None: + attention_mask = torch.ones( + embeddings.shape[:2], + dtype=torch.long, + device=embeddings.device, + ) + + outputs = self.model( + inputs_embeds=embeddings, + attention_mask=attention_mask, + use_cache=False, + output_hidden_states=False, + return_dict=return_dict, + ) + return outputs.last_hidden_state if return_dict else outputs[0] diff --git a/models/language_model/qwen3_vl.py b/models/language_model/qwen3_vl.py new file mode 100644 index 0000000000000000000000000000000000000000..4c7d443d3bb8a22bac575a1ea33c076b2c3e56b4 --- /dev/null +++ b/models/language_model/qwen3_vl.py @@ -0,0 +1,109 @@ +from typing import List, Optional + +import torch +from torch import Tensor, nn +from transformers import AutoConfig, AutoTokenizer +from transformers.models.qwen3_vl.modeling_qwen3_vl import Qwen3VLTextModel + +from models.qwen_utils import build_empty_module, load_prefixed_safetensors +from utils.logging_project import is_global_rank_zero, rank_zero_print + + +class Qwen3VLLanguageModel(nn.Module): + """ + Qwen3-VL text decoder with DeepStack support: visual features from + intermediate vision-encoder layers are added to the hidden states of the + first LLM layers at the visual token positions (deepstack_visual_embeds). + """ + + def __init__( + self, + variant: str, + freeze: bool = False, + lora: bool = False, + lora_r: int = 16, + lora_alpha: int = 32, + lora_dropout: float = 0.1, + local_files_only: bool = True, + torch_dtype: str = "bfloat16", + ): + super().__init__() + self.config = AutoConfig.from_pretrained(variant, local_files_only=local_files_only) + dtype = getattr(torch, torch_dtype) + self.config.text_config._attn_implementation = "flash_attention_2" + self.config.text_config.dtype = dtype + rank_zero_print("Loading Qwen3-VL language model (meta init)...", flush=True) + self.model = build_empty_module(Qwen3VLTextModel, self.config.text_config) + rank_zero_print("Loading language model weights...", flush=True) + load_prefixed_safetensors(self.model, variant, "model.language_model.", torch_dtype=dtype) + rank_zero_print("Language model weights ready.", flush=True) + + self.tokenizer = AutoTokenizer.from_pretrained(variant, local_files_only=local_files_only) + if self.tokenizer.pad_token is None: + self.tokenizer.pad_token = self.tokenizer.eos_token + + self.vocab_size = self.model.config.vocab_size + self.hidden_size = self.model.config.hidden_size + self.max_position_embeddings = self.model.config.max_position_embeddings + + if freeze: + for param in self.model.parameters(): + param.requires_grad = False + + if lora: + from peft import LoraConfig, get_peft_model + + rank_zero_print("Applying LoRA adapters...", flush=True) + peft_config = LoraConfig( + inference_mode=False, + r=lora_r, + lora_alpha=lora_alpha, + lora_dropout=lora_dropout, + target_modules=[ + "q_proj", + "k_proj", + "v_proj", + "o_proj", + "gate_proj", + "up_proj", + "down_proj", + ], + ) + self.model = get_peft_model(self.model, peft_config) + if is_global_rank_zero(): + self.model.print_trainable_parameters() + + @property + def embed_tokens(self): + model = self.model + # unwrap peft + if hasattr(model, "get_base_model"): + model = model.get_base_model() + return model.embed_tokens + + def forward( + self, + embeddings: Tensor, + attention_mask: Optional[Tensor] = None, + position_ids: Optional[Tensor] = None, + visual_pos_masks: Optional[Tensor] = None, + deepstack_visual_embeds: Optional[List[Tensor]] = None, + return_dict: bool = True, + ) -> Tensor: + if attention_mask is None: + attention_mask = torch.ones( + embeddings.shape[:2], + dtype=torch.long, + device=embeddings.device, + ) + + outputs = self.model( + inputs_embeds=embeddings, + attention_mask=attention_mask, + position_ids=position_ids, + visual_pos_masks=visual_pos_masks, + deepstack_visual_embeds=deepstack_visual_embeds, + use_cache=False, + return_dict=return_dict, + ) + return outputs.last_hidden_state if return_dict else outputs[0] diff --git a/models/language_model/qwen3_vl_scratch.py b/models/language_model/qwen3_vl_scratch.py new file mode 100644 index 0000000000000000000000000000000000000000..9416a3c76a04f80e1f40d1023f6b792bec7aa38c --- /dev/null +++ b/models/language_model/qwen3_vl_scratch.py @@ -0,0 +1,105 @@ +"""Randomly-initialised, shrunk Qwen3-VL text decoder ("small" preset). + +Same architecture family as `models.language_model.qwen3_vl.Qwen3VLLanguageModel` +(Interleaved-MRoPE, DeepStack injection) but built from a (possibly downsized) +config and trained from scratch instead of loading pretrained weights + LoRA. + +ConsDrive v4 keeps the 2B width (hidden 2048, 16 heads, FFN 6144) and only +shrinks depth (10 layers) so DeepStack features stay Identity-aligned. + +The model is action-only: there is no text input or output, so no tokenizer is +exposed (`tokenizer = None`) and the (tiny) token embedding table is frozen so +DeepSpeed never sees an unused trainable parameter. +""" + +from copy import deepcopy +from typing import List, Optional + +import torch +from torch import Tensor, nn +from transformers import AutoConfig +from transformers.models.qwen3_vl.modeling_qwen3_vl import Qwen3VLTextModel + +from utils.logging_project import rank_zero_print + + +class Qwen3VLScratchLanguageModel(nn.Module): + def __init__( + self, + variant: str, + hidden_size: int = 1024, + num_hidden_layers: int = 22, + num_attention_heads: int = 8, + num_key_value_heads: int = 8, + intermediate_size: int = 4096, + head_dim: int = 128, + vocab_size: int = 16, + local_files_only: bool = True, + torch_dtype: str = "bfloat16", + ): + super().__init__() + dtype = getattr(torch, torch_dtype) + + # Start from the pretrained text config so RoPE/MRoPE settings + # (rope_theta, mrope_section, interleaved) stay compatible with the + # position ids built in DrivingModel, then shrink the trunk. + base_config = AutoConfig.from_pretrained(variant, local_files_only=local_files_only) + text_config = deepcopy(base_config.text_config) + text_config.hidden_size = int(hidden_size) + text_config.num_hidden_layers = int(num_hidden_layers) + text_config.num_attention_heads = int(num_attention_heads) + text_config.num_key_value_heads = int(num_key_value_heads) + text_config.intermediate_size = int(intermediate_size) + text_config.head_dim = int(head_dim) + # Text tokens are never used; keep the embedding table symbolic. + text_config.vocab_size = int(vocab_size) + text_config.tie_word_embeddings = False + text_config._attn_implementation = "flash_attention_2" + text_config.dtype = dtype + self.config = text_config + + rank_zero_print( + f"Building from-scratch Qwen3-VL text model: {num_hidden_layers}L, " + f"hidden {hidden_size}, heads {num_attention_heads}/{num_key_value_heads}, " + f"ffn {intermediate_size}, head_dim {head_dim}", + flush=True, + ) + self.model = Qwen3VLTextModel(text_config).to(dtype) + # No text input exists in this setup; freeze embed_tokens so all + # trainable parameters participate in every backward pass. + self.model.embed_tokens.weight.requires_grad = False + + num_params = sum(p.numel() for p in self.model.parameters()) + rank_zero_print(f"Scratch LM parameters: {num_params / 1e6:.1f}M", flush=True) + + self.tokenizer = None + self.vocab_size = text_config.vocab_size + self.hidden_size = text_config.hidden_size + self.max_position_embeddings = text_config.max_position_embeddings + + def forward( + self, + embeddings: Tensor, + attention_mask: Optional[Tensor] = None, + position_ids: Optional[Tensor] = None, + visual_pos_masks: Optional[Tensor] = None, + deepstack_visual_embeds: Optional[List[Tensor]] = None, + return_dict: bool = True, + ) -> Tensor: + if attention_mask is None: + attention_mask = torch.ones( + embeddings.shape[:2], + dtype=torch.long, + device=embeddings.device, + ) + + outputs = self.model( + inputs_embeds=embeddings, + attention_mask=attention_mask, + position_ids=position_ids, + visual_pos_masks=visual_pos_masks, + deepstack_visual_embeds=deepstack_visual_embeds, + use_cache=False, + return_dict=return_dict, + ) + return outputs.last_hidden_state if return_dict else outputs[0] diff --git a/models/language_model/qwen3_vl_truncated.py b/models/language_model/qwen3_vl_truncated.py new file mode 100644 index 0000000000000000000000000000000000000000..8f5b16d025de84a54cef23bfeb5888e4880b9bbf --- /dev/null +++ b/models/language_model/qwen3_vl_truncated.py @@ -0,0 +1,124 @@ +"""Pretrained-initialised, depth-truncated Qwen3-VL text decoder. + +ConsDrive v5: same interface as `Qwen3VLScratchLanguageModel` (10-layer trunk, +hidden 2048, DeepStack + Interleaved-MRoPE) but every kept layer, the token +embedding table, and the final norm are loaded from the pretrained checkpoint +instead of random init. Keeping the pretrained embed_tokens (frozen) plus the +tokenizer restores the text pathway, so `command_tp_text` navigation works on +the small trunk (the digit/word embeddings carry their pretrained meaning). + +Parameter budget: 10 pretrained layers at 2B width are ~0.5B trainable; the +frozen full-vocab embedding table adds ~0.3B non-trainable lookup weights. +""" + +from copy import deepcopy +from typing import List, Optional + +import torch +from torch import Tensor, nn +from transformers import AutoConfig, AutoTokenizer +from transformers.models.qwen3_vl.modeling_qwen3_vl import Qwen3VLTextModel + +from models.qwen_utils import build_empty_module, load_prefixed_state_dict +from utils.logging_project import rank_zero_print + + +class Qwen3VLTruncatedLanguageModel(nn.Module): + def __init__( + self, + variant: str, + num_hidden_layers: int = 10, + freeze_embed: bool = True, + local_files_only: bool = True, + torch_dtype: str = "bfloat16", + ): + super().__init__() + dtype = getattr(torch, torch_dtype) + + base_config = AutoConfig.from_pretrained( + variant, local_files_only=local_files_only + ) + text_config = deepcopy(base_config.text_config) + text_config.num_hidden_layers = int(num_hidden_layers) + text_config._attn_implementation = "flash_attention_2" + text_config.dtype = dtype + self.config = text_config + + rank_zero_print( + f"Building truncated Qwen3-VL text model: first {num_hidden_layers} " + f"pretrained layers, hidden {text_config.hidden_size}", + flush=True, + ) + self.model = build_empty_module(Qwen3VLTextModel, text_config) + + # The checkpoint holds all 28 layers; keep only the keys our shrunk + # module actually has (layers 0..N-1, embed_tokens, final norm). + full_state = load_prefixed_state_dict(variant, "model.language_model.") + wanted = set(self.model.state_dict().keys()) + state = { + k: v.to(dtype) for k, v in full_state.items() if k in wanted + } + missing = wanted - state.keys() + if missing: + raise RuntimeError( + f"Truncated LM init incomplete; missing keys: {sorted(missing)[:10]}" + ) + self.model.load_state_dict(state, strict=True, assign=True) + del full_state, state + rank_zero_print("Truncated language model weights ready.", flush=True) + + self.tokenizer = AutoTokenizer.from_pretrained( + variant, local_files_only=local_files_only + ) + if self.tokenizer.pad_token is None: + self.tokenizer.pad_token = self.tokenizer.eos_token + + if freeze_embed: + # Digit/word embeddings keep their pretrained geometry; also spares + # DeepSpeed the ~0.3B-parameter embedding gradient. + self.model.embed_tokens.weight.requires_grad = False + + num_params = sum(p.numel() for p in self.model.parameters()) + num_trainable = sum( + p.numel() for p in self.model.parameters() if p.requires_grad + ) + rank_zero_print( + f"Truncated LM parameters: {num_params / 1e6:.1f}M total, " + f"{num_trainable / 1e6:.1f}M trainable", + flush=True, + ) + + self.vocab_size = text_config.vocab_size + self.hidden_size = text_config.hidden_size + self.max_position_embeddings = text_config.max_position_embeddings + + @property + def embed_tokens(self): + return self.model.embed_tokens + + def forward( + self, + embeddings: Tensor, + attention_mask: Optional[Tensor] = None, + position_ids: Optional[Tensor] = None, + visual_pos_masks: Optional[Tensor] = None, + deepstack_visual_embeds: Optional[List[Tensor]] = None, + return_dict: bool = True, + ) -> Tensor: + if attention_mask is None: + attention_mask = torch.ones( + embeddings.shape[:2], + dtype=torch.long, + device=embeddings.device, + ) + + outputs = self.model( + inputs_embeds=embeddings, + attention_mask=attention_mask, + position_ids=position_ids, + visual_pos_masks=visual_pos_masks, + deepstack_visual_embeds=deepstack_visual_embeds, + use_cache=False, + return_dict=return_dict, + ) + return outputs.last_hidden_state if return_dict else outputs[0] diff --git a/models/language_model/tiny_transformer.py b/models/language_model/tiny_transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..9b44476da78b9edbf0b8ddd241b85f2d47eb180a --- /dev/null +++ b/models/language_model/tiny_transformer.py @@ -0,0 +1,149 @@ +import string +from typing import Dict, List, Optional + +import torch +from torch import Tensor, nn + + +class CharacterCommandTokenizer: + def __init__(self, max_length: int = 96): + chars = string.ascii_lowercase + string.digits + " .,;:-_/[]()<>" + self.pad_token = "" + self.bos_token = "" + self.eos_token = "" + self.unk_token = "" + self.id_to_token = [self.pad_token, self.bos_token, self.eos_token, self.unk_token, *chars] + self.token_to_id = {token: idx for idx, token in enumerate(self.id_to_token)} + self.pad_token_id = self.token_to_id[self.pad_token] + self.bos_token_id = self.token_to_id[self.bos_token] + self.eos_token_id = self.token_to_id[self.eos_token] + self.unk_token_id = self.token_to_id[self.unk_token] + self.vocab_size = len(self.id_to_token) + self.max_length = max_length + + def _encode(self, text: str, max_length: int) -> List[int]: + ids = [self.bos_token_id] + ids.extend(self.token_to_id.get(ch, self.unk_token_id) for ch in text.lower()) + ids.append(self.eos_token_id) + return ids[:max_length] + + def __call__( + self, + texts, + padding: bool = True, + truncation: bool = True, + return_tensors: Optional[str] = None, + max_length: Optional[int] = None, + ) -> Dict[str, Tensor]: + if isinstance(texts, str): + texts = [texts] + max_length = max_length or self.max_length + encoded = [self._encode(text, max_length) for text in texts] + padded_length = max(len(ids) for ids in encoded) if padding else max_length + padded_length = min(padded_length, max_length) + + input_ids = [] + attention_mask = [] + for ids in encoded: + ids = ids[:padded_length] + pad_len = padded_length - len(ids) + input_ids.append(ids + [self.pad_token_id] * pad_len) + attention_mask.append([1] * len(ids) + [0] * pad_len) + + return { + "input_ids": torch.tensor(input_ids, dtype=torch.long), + "attention_mask": torch.tensor(attention_mask, dtype=torch.long), + } + + +class TinyCausalTransformerBackbone(nn.Module): + def __init__( + self, + vocab_size: int, + hidden_size: int = 512, + num_hidden_layers: int = 6, + num_attention_heads: int = 8, + intermediate_size: int = 2048, + max_position_embeddings: int = 4096, + dropout: float = 0.0, + ): + super().__init__() + self.embed_tokens = nn.Embedding(vocab_size, hidden_size) + self.position_embedding = nn.Embedding(max_position_embeddings, hidden_size) + encoder_layer = nn.TransformerEncoderLayer( + d_model=hidden_size, + nhead=num_attention_heads, + dim_feedforward=intermediate_size, + dropout=dropout, + activation="gelu", + batch_first=True, + norm_first=True, + ) + self.layers = nn.TransformerEncoder(encoder_layer, num_layers=num_hidden_layers) + self.norm = nn.LayerNorm(hidden_size) + self.max_position_embeddings = max_position_embeddings + + @property + def dtype(self): + return self.embed_tokens.weight.dtype + + def forward(self, inputs_embeds: Tensor, attention_mask: Optional[Tensor] = None) -> Tensor: + seq_len = inputs_embeds.shape[1] + if seq_len > self.max_position_embeddings: + raise ValueError( + f"Sequence length {seq_len} exceeds max_position_embeddings={self.max_position_embeddings}." + ) + + positions = torch.arange(seq_len, device=inputs_embeds.device) + x = inputs_embeds + self.position_embedding(positions).to(dtype=inputs_embeds.dtype).unsqueeze(0) + + causal_mask = torch.triu( + torch.ones(seq_len, seq_len, device=inputs_embeds.device, dtype=torch.bool), + diagonal=1, + ) + key_padding_mask = None + if attention_mask is not None: + key_padding_mask = attention_mask.to(device=inputs_embeds.device) == 0 + + x = self.layers(x, mask=causal_mask, src_key_padding_mask=key_padding_mask) + return self.norm(x) + + +class TinyTransformerLanguageModel(nn.Module): + def __init__( + self, + hidden_size: int = 512, + num_hidden_layers: int = 6, + num_attention_heads: int = 8, + intermediate_size: int = 2048, + max_position_embeddings: int = 4096, + tokenizer_max_length: int = 96, + dropout: float = 0.0, + freeze: bool = False, + ): + super().__init__() + self.tokenizer = CharacterCommandTokenizer(max_length=tokenizer_max_length) + self.model = TinyCausalTransformerBackbone( + vocab_size=self.tokenizer.vocab_size, + hidden_size=hidden_size, + num_hidden_layers=num_hidden_layers, + num_attention_heads=num_attention_heads, + intermediate_size=intermediate_size, + max_position_embeddings=max_position_embeddings, + dropout=dropout, + ) + self.vocab_size = self.tokenizer.vocab_size + self.hidden_size = hidden_size + self.max_position_embeddings = max_position_embeddings + + if freeze: + for param in self.parameters(): + param.requires_grad = False + + def forward( + self, + embeddings: Tensor, + attention_mask: Optional[Tensor] = None, + return_dict: bool = True, + ) -> Tensor: + return self.model(inputs_embeds=embeddings, attention_mask=attention_mask) diff --git a/models/pim.py b/models/pim.py new file mode 100644 index 0000000000000000000000000000000000000000..b4615d51dc237daa75f13dcef713677839120fe7 --- /dev/null +++ b/models/pim.py @@ -0,0 +1,139 @@ +"""Current-observation interaction memory, independent of the vision backbone. + +Version 1 uses supervised semantic slots, not object-ID tracking. Multiple +objects of one interaction type are aggregated. Labels never enter forward(). +""" +from dataclasses import dataclass +from typing import Optional +import torch +from torch import nn + +SLOT_NAMES = ( + 'crossing_vehicle', 'oncoming_vehicle', 'lead_vehicle', 'pedestrian', + 'cyclist', 'static_obstacle', 'traffic_control', 'other_interaction', +) + + +@dataclass +class InteractionState: + features: torch.Tensor + valid: torch.Tensor + last_observed: torch.Tensor + timestamp: torch.Tensor + observed_pose: Optional[torch.Tensor] = None + + def detach(self): + return InteractionState(self.features.detach(), self.valid.detach(), + self.last_observed.detach(), self.timestamp.detach(), + None if self.observed_pose is None else self.observed_pose.detach()) + + +class PersistentInteractionMemory(nn.Module): + """Unmatched semantic slots persist until current evidence predicts release. + + State belongs to one stream. Never register it as a learned parameter or + checkpoint buffer. Callers own state reset, route isolation and TBPTT. + """ + def __init__(self, hidden_size, slots=8, memory_dim=256, heads=4, + observation_threshold=0.5, release_threshold=0.9): + super().__init__() + if slots < 1 or heads < 1 or memory_dim % heads: + raise ValueError('Invalid memory slots or attention dimensions') + if not 0 < observation_threshold < 1 or not 0 < release_threshold < 1: + raise ValueError('Thresholds must lie in (0, 1)') + self.slots, self.memory_dim = slots, memory_dim + self.observation_threshold, self.release_threshold = observation_threshold, release_threshold + self.query_embeds_observation = nn.Parameter(torch.randn(1, slots, hidden_size) * .02) + self.observation_projection = nn.Linear(hidden_size, memory_dim) + self.visibility = nn.Linear(memory_dim, 1) + self.update_cell = nn.GRUCell(memory_dim, memory_dim) + self.release = nn.Sequential(nn.Linear(2 * memory_dim + 5, memory_dim), + nn.SiLU(), nn.Linear(memory_dim, 1)) + self.pending_head = nn.Linear(memory_dim, 1) + self.action_projection = nn.Linear(hidden_size, memory_dim) + self.metadata_projection = nn.Sequential(nn.Linear(5, memory_dim), nn.SiLU()) + self.reader = nn.MultiheadAttention(memory_dim, heads, batch_first=True) + self.output_projection = nn.Linear(memory_dim, hidden_size) + nn.init.zeros_(self.output_projection.weight) + nn.init.zeros_(self.output_projection.bias) + nn.init.constant_(self.release[-1].bias, -4.) + + def empty(self, batch_size, device, dtype=torch.float32): + return InteractionState( + torch.zeros(batch_size, self.slots, self.memory_dim, device=device, dtype=dtype), + torch.zeros(batch_size, self.slots, device=device, dtype=torch.bool), + torch.zeros(batch_size, self.slots, device=device), + torch.zeros(batch_size, device=device), + torch.zeros(batch_size, self.slots, 3, device=device)) + + def observation_queries(self, batch_size): + return self.query_embeds_observation.expand(batch_size, -1, -1) + + @staticmethod + def _metadata(timestamp, pose, last_observed, observed_pose): + age = (timestamp[:, None] - last_observed).clamp_min(0) + displacement = pose[:, None, :2] - observed_pose[..., :2] + yaw = observed_pose[..., 2] + c, s = yaw.cos(), yaw.sin() + dx = c * displacement[..., 0] + s * displacement[..., 1] + dy = -s * displacement[..., 0] + c * displacement[..., 1] + angle = pose[:, None, 2] - yaw + return torch.stack((torch.log1p(age), dx / 50., dy / 50., + angle.sin(), angle.cos()), -1), age + + def forward(self, observations, actions, timestamp, state=None, reset=None, + ego_pose=None, read_enabled=True): + z = self.observation_projection(observations) + b, n, d = z.shape + if n != self.slots: + raise ValueError('Observation count differs from slot count') + timestamp = timestamp.to(z.device, torch.float32).reshape(b) + ego_pose = (torch.zeros(b, 3, device=z.device) if ego_pose is None + else ego_pose.to(z.device, torch.float32).reshape(b, 3)) + if not torch.isfinite(timestamp).all() or not torch.isfinite(ego_pose).all(): + raise ValueError('Timestamp and ego pose must be finite') + initial = state is None + if initial: + state = self.empty(b, z.device, z.dtype) + if state.features.shape != z.shape: + raise ValueError('State batch/slot shape mismatch; reset the stream') + reset = (torch.zeros(b, dtype=torch.bool, device=z.device) if reset is None + else reset.to(z.device).bool().reshape(b)) + if ((timestamp < state.timestamp) & ~reset).any(): + raise ValueError('Non-monotonic stream timestamps require reset') + fresh = (timestamp > state.timestamp) | reset | initial + old_valid = state.valid & ~reset[:, None] + old = torch.where(old_valid[..., None], state.features, torch.zeros_like(state.features)) + old_pose = (ego_pose[:, None].expand(-1, n, -1) if state.observed_pose is None + else state.observed_pose) + old_time = torch.where(reset[:, None], timestamp[:, None], state.last_observed) + metadata_before, _ = self._metadata(timestamp, ego_pose, old_time, old_pose) + visibility_logits = self.visibility(z).squeeze(-1) + observed = (visibility_logits.sigmoid() >= self.observation_threshold) & fresh[:, None] + candidate = self.update_cell(z.reshape(-1, d), old.reshape(-1, d)).reshape(b, n, d) + features = torch.where(observed[..., None], candidate, old) + scene = z.mean(1, keepdim=True).expand(-1, n, -1) + # Current-only evidence and ego motion can support release; absence and + # elapsed time alone never deterministically clear a slot. + release_logits = self.release(torch.cat((old, scene, metadata_before.to(z.dtype)), -1)).squeeze(-1) + released = old_valid & fresh[:, None] & (release_logits.sigmoid() >= self.release_threshold) + valid = (old_valid | observed) & ~released + features = features * valid[..., None] + last_observed = torch.where(observed, timestamp[:, None], old_time) + observed_pose = torch.where(observed[..., None], ego_pose[:, None], old_pose) + metadata, age = self._metadata(timestamp, ego_pose, last_observed, observed_pose) + keys = features + self.metadata_projection(metadata.to(z.dtype)) + null = z.new_zeros(b, 1, d) + keys, values = torch.cat((keys, null), 1), torch.cat((features, null), 1) + mask = torch.cat((~valid, torch.zeros(b, 1, dtype=torch.bool, device=z.device)), 1) + read, _ = self.reader(self.action_projection(actions), keys, values, + key_padding_mask=mask, need_weights=False) + delta = self.output_projection(read) * valid.any(1)[:, None, None] + # read_enabled is an inference ablation, not a change in memory updates. + result = actions + delta * float(read_enabled) + new_state = InteractionState(features, valid, last_observed, timestamp, observed_pose) + diagnostics = dict(visibility_logits=visibility_logits, release_logits=release_logits, + pending_logits=self.pending_head(features).squeeze(-1), + observed=observed, released=released, age=age, + previous_valid=old_valid, valid=valid) + return result, new_state, diagnostics diff --git a/models/pim_driving.py b/models/pim_driving.py new file mode 100644 index 0000000000000000000000000000000000000000..9a815ee2901cc9130286eb04d4cdd2c032109608 --- /dev/null +++ b/models/pim_driving.py @@ -0,0 +1,176 @@ +"""Single-current-image FastVLM driving with explicit persistent interaction state.""" +from collections import defaultdict +import torch +from torch import nn +from models.driving import DrivingModel +from models.fastvlm import load_fastvlm +from models.pim import PersistentInteractionMemory +from models.pim_losses import interaction_losses +from models.utils import summarise_losses +from utils.pim_types import PIMStepOutput, PIMStreamBatch + + +class PIMDrivingModel(DrivingModel): + def __init__(self, fastvlm=None, pim=None, vision_model=None, language_model=None, **kwargs): + if (vision_model is None) != (language_model is None): + raise ValueError('Provide both injected vision/language adapters, or neither') + if vision_model is None: + if fastvlm is None: + raise ValueError('FastVLM configuration is required') + vision_model, language_model = load_fastvlm(**dict(fastvlm)) + super().__init__(vision_model=vision_model, language_model=language_model, **kwargs) + self.pim_cfg = dict(pim or {}) + self.pim_enabled = bool(self.pim_cfg.get('enabled', True)) + self.pim_read_enabled = True + self.pim = None + if self.pim_enabled: + self.pim = PersistentInteractionMemory( + language_model.hidden_size, + slots=int(self.pim_cfg.get('slots', 8)), + memory_dim=int(self.pim_cfg.get('memory_dim', 256)), + heads=int(self.pim_cfg.get('heads', 4)), + observation_threshold=float(self.pim_cfg.get('observation_threshold', .5)), + release_threshold=float(self.pim_cfg.get('release_threshold', .9))) + if self.use_world_loss: + raise ValueError('PIM first release does not combine world-latent supervision') + + def forward_step(self, driving_input, timestamp, ego_pose, state=None, reset=None): + images = driving_input.camera_images + if images.ndim == 6 and tuple(images.shape[1:3]) != (1, 1): + raise ValueError('PIM receives one current image; do not pass historical frames') + prefix, prefix_mask, _ = self.get_fixed_input_embeds(driving_input) + if self.use_deepstack: + raise ValueError('PIMDrivingModel expects FastVLM, not the Qwen3-VL video tower') + adaptor = self.adaptors(driving_input)['inputs'] + b, prefix_length = prefix.shape[:2] + parts = [prefix] + n_obs = 0 + if self.pim is not None: + observation_queries = self.pim.observation_queries(b).to(prefix.dtype) + n_obs = observation_queries.shape[1] + parts.append(observation_queries) + parts.append(adaptor.to(prefix.dtype)) + embeddings = torch.cat(parts, 1) + mask = torch.cat((prefix_mask, torch.ones( + b, n_obs + adaptor.shape[1], device=prefix.device, dtype=prefix_mask.dtype)), 1) + embeddings = embeddings.to(next(self.language_model.parameters()).dtype) + # One LM call; observation queries precede action queries. No ground-truth + # answer text, future waypoint or event target is in this sequence. + outputs = self.language_model(embeddings, attention_mask=mask) + actions = outputs[:, prefix_length + n_obs:] + diagnostics = {} + if self.pim is not None: + observations = outputs[:, prefix_length:prefix_length + n_obs] + actions, state, diagnostics = self.pim( + observations.to(self.pim.observation_projection.weight.dtype), + actions.to(self.pim.action_projection.weight.dtype), timestamp, + state=state, reset=reset, ego_pose=ego_pose, + read_enabled=self.pim_read_enabled) + predictions = self.adaptors.driving.get_predictions(actions) + return PIMStepOutput(predictions['speed_wps'], predictions['route'], state, + diagnostics, actions, outputs[:, :prefix_length], prefix_mask) + + def forward(self, driving_input, prompt_ids=None, return_context=False): + if self.pim_enabled: + raise RuntimeError('Use forward_step(input,timestamp,ego_pose,state) for PIM; ' + 'implicit state would leak across streams') + return super().forward(driving_input, prompt_ids, return_context) + + def forward_loss(self, example, per_sample=False): + if not isinstance(example, PIMStreamBatch): + if self.pim_enabled: + raise TypeError('PIM training requires PIMStreamBatch from PIMDataModule') + return super().forward_loss(example, per_sample) + t_steps = len(example.frames) + if t_steps == 0: + raise ValueError('Empty temporal stream') + burn_in = int(self.pim_cfg.get('burn_in', 0)) if self.pim_enabled else 0 + tbptt = int(self.pim_cfg.get('tbptt_steps', 4)) + if burn_in >= t_steps or tbptt < 1: + raise ValueError('burn_in must be smaller than stream length; tbptt_steps >= 1') + state = None # New sampled stream; never inherit a different minibatch. + collected = defaultdict(list) + predictions = {} + for t, frame in enumerate(example.frames): + if state is not None and t % tbptt == 0: + state = state.detach() + output = self.forward_step(frame.driving_input, example.timestamps[:, t], + example.ego_poses[:, t], state) + state = output.state + adaptor_dict = self.adaptors(frame) + losses = self.adaptors.compute_loss(output.action_features, adaptor_dict, frame) + predictions = {k: v for k, v in losses.items() if not k.endswith('loss')} + if t >= burn_in: + for name, pair in losses.items(): + if name.endswith('loss'): + collected[name].append(pair) + if self.use_consequence_loss: + extra = self.compute_consequence_losses( + output.scene_tokens, output.scene_mask, output.route, + output.speed_wps, frame.driving_label) + for name, pair in extra.items(): + collected[name].append(pair) + if self.pim_enabled: + targets = example.labels[t] + if targets is None and self.pim_cfg.get('require_labels', True): + raise ValueError('PIM lifecycle labels missing; see docs/PIM.md') + for name, pair in interaction_losses( + output.diagnostics, targets, + float(self.pim_cfg.get('event_loss_weight', .2))).items(): + collected[name].append(pair) + merged = {name: (torch.cat([p[0].reshape(-1) for p in pairs]), + torch.cat([p[1].reshape(-1) for p in pairs])) + for name, pairs in collected.items()} + return (merged, predictions) if per_sample else summarise_losses(merged) + + def _stream_step(self, batch, mode): + output = self.forward_loss(batch) + batch_size = (batch.timestamps.shape[0] if isinstance(batch, PIMStreamBatch) + else batch.driving_input.vehicle_speed.shape[0]) + for name, value in output.loss_averages.items(): + count = output.loss_counts[name].sum().detach().to(value.dtype) + totals = torch.stack((value.detach() * count, count)) + # All ranks must make the same logging decision for sparse labels. + if torch.distributed.is_available() and torch.distributed.is_initialized(): + torch.distributed.all_reduce(totals) + global_count = int(totals[1].item()) + if global_count: + self.log(f'{mode}_losses/{name}', totals[0] / totals[1], + batch_size=global_count, on_step=mode == 'train', + on_epoch=True, sync_dist=False) + self.log(f'{mode}/loss', output.loss, batch_size=batch_size, + on_step=mode == 'train', on_epoch=True, prog_bar=True) + return output.loss + + def training_step(self, batch, batch_idx=0): + return self._stream_step(batch, 'train') + + def validation_step(self, batch, batch_idx=0): + return self._stream_step(batch, 'val') + + def predict_step(self, batch, batch_idx=0): + output = self.forward_loss(batch) + return {k: v.detach().cpu() for k, v in output.loss_averages.items()} + + def configure_optimizers(self): + # Explicit groups cover new query, GRU and projection parameters and avoid + # assumptions in the legacy parameter-name whitelist. + groups = defaultdict(list) + for name, parameter in self.named_parameters(): + if not parameter.requires_grad: + continue + lr = self.lr + if name.startswith('vision_model.'): + lr = self.vision_lr if self.vision_lr is not None else self.lr + elif name.startswith('language_model.') and self.lm_lr is not None: + lr = self.lm_lr + decay = self.weight_decay if parameter.ndim > 1 and 'query_embeds' not in name else 0. + groups[(lr, decay)].append(parameter) + optimizer = torch.optim.AdamW([ + {'params': params, 'lr': lr, 'weight_decay': decay} + for (lr, decay), params in groups.items()], betas=self.betas) + steps = self.trainer.estimated_stepping_batches + scheduler = torch.optim.lr_scheduler.LambdaLR( + optimizer, lambda s: min(1., (s + 1) / max(1., self.pct_start * steps))) + return {'optimizer': optimizer, 'lr_scheduler': { + 'scheduler': scheduler, 'interval': 'step', 'frequency': 1}} diff --git a/models/pim_losses.py b/models/pim_losses.py new file mode 100644 index 0000000000000000000000000000000000000000..f0ed31aa0ade0f229a0026df06ecbf779ec26e32 --- /dev/null +++ b/models/pim_losses.py @@ -0,0 +1,32 @@ +"""Masked semantic lifecycle supervision. Targets NEVER condition policy forward.""" +import torch +import torch.nn.functional as F + + +def _bce(logits, target, valid, weight): + target = target.to(logits.device, logits.dtype) + valid = valid.to(logits.device).bool() + # Invalid/unknown targets are removed before BCE (also safe for NaN placeholders). + clean = torch.where(valid, target, torch.zeros_like(target)) + losses = F.binary_cross_entropy_with_logits(logits.float(), clean.float(), reduction='none') + return (torch.where(valid, losses, torch.zeros_like(losses)).sum(-1) * weight, + valid.sum(-1)) + + +def interaction_losses(diagnostics, targets, weight=0.2): + if targets is None: + return {} + losses = {'pim_observation_loss': _bce( + diagnostics['visibility_logits'], targets['observed'], + targets['observed_valid'], weight)} + # Only states already represented in memory can be supervised for release. + # Unknown is not "resolved"; release_valid must mark actual evidence labels. + old = diagnostics['previous_valid'] + losses['pim_release_loss'] = _bce( + diagnostics['release_logits'], targets['resolved'], + targets['resolved_valid'].to(old.device).bool() & old, weight) + represented = diagnostics['valid'] + losses['pim_pending_loss'] = _bce( + diagnostics['pending_logits'], targets['pending'], + targets['pending_valid'].to(represented.device).bool() & represented, weight) + return losses diff --git a/models/plan_consequence.py b/models/plan_consequence.py new file mode 100644 index 0000000000000000000000000000000000000000..dccbe64a84ddc8b25a673ababbef0b7840a0efd8 --- /dev/null +++ b/models/plan_consequence.py @@ -0,0 +1,519 @@ +"""Small training-only, plan-conditioned consequence model. + +Waypoint tokens attend to LM vision tokens (not a pooled scene vector) and +score an explicit metric plan. Privileged future boxes supervise clearance +and a relative avoidance hinge; they are never a model output. +""" + +import math +from typing import NamedTuple, Optional, Sequence, Tuple + +import torch +import torch.nn.functional as F +from torch import Tensor, nn + + +class ConsequenceOutput(NamedTuple): + clearance: Tensor # [B, 10], signed metres (negative means overlap) + + +class PooledConsequenceOutput(NamedTuple): + risk_logits: Tensor # [B, 10] + clearance: Tensor # [B, 10], signed metres (negative means overlap) + + +class PooledPlanConsequenceHead(nn.Module): + """ConsDrive v2 head: fuse a pooled scene vector with explicit plans. + + This is the exact architecture behind the v2 checkpoint whose speed + gating reached 91.1/91.33 DS on Bench2Drive: BCE-supervised risk logits + plus a clearance regression, both per waypoint. Kept alongside the + cross-attention head so v4 checkpoints stay loadable. + """ + + def __init__( + self, + scene_dim: int, + hidden_dim: int = 256, + plan_dim: int = 128, + horizon: int = 10, + route_points: int = 20, + dropout: float = 0.1, + ): + super().__init__() + self.horizon = int(horizon) + self.route_points = int(route_points) + + self.scene_encoder = nn.Sequential( + nn.LayerNorm(scene_dim), + nn.Linear(scene_dim, hidden_dim), + nn.SiLU(), + ) + self.route_encoder = nn.Sequential( + nn.Linear(4, plan_dim), + nn.SiLU(), + nn.Linear(plan_dim, plan_dim), + ) + # speed xy, speed delta xy, and route point xy at the same progress + self.step_encoder = nn.Sequential( + nn.Linear(6, plan_dim), + nn.SiLU(), + nn.Linear(plan_dim, plan_dim), + ) + self.fusion = nn.Sequential( + nn.LayerNorm(hidden_dim + 2 * plan_dim), + nn.Linear(hidden_dim + 2 * plan_dim, hidden_dim), + nn.SiLU(), + nn.Dropout(dropout), + nn.Linear(hidden_dim, hidden_dim), + nn.SiLU(), + ) + self.risk_head = nn.Linear(hidden_dim, 1) + self.clearance_head = nn.Linear(hidden_dim, 1) + + def forward( + self, + scene_feature: Tensor, + route: Tensor, + speed_trajectory: Tensor, + ) -> PooledConsequenceOutput: + if scene_feature.ndim != 2: + raise ValueError("scene_feature must have shape [B,C]") + if route.shape != (scene_feature.size(0), self.route_points, 2): + raise ValueError(f"route must have shape [B,{self.route_points},2]") + if speed_trajectory.shape != (scene_feature.size(0), self.horizon, 2): + raise ValueError(f"speed_trajectory must have shape [B,{self.horizon},2]") + dtype = self.scene_encoder[1].weight.dtype + scene_feature = scene_feature.to(dtype=dtype) + route = route.to(dtype=dtype) + speed_trajectory = speed_trajectory.to(dtype=dtype) + + route_delta = torch.diff( + route, dim=1, prepend=torch.zeros_like(route[:, :1]) + ) + route_tokens = self.route_encoder(torch.cat((route, route_delta), dim=-1)) + route_summary = route_tokens.mean(dim=1) + + route_indices = torch.linspace( + 0, + route.size(1) - 1, + speed_trajectory.size(1), + device=route.device, + ).round().long() + aligned_route = route.index_select(1, route_indices) + speed_delta = torch.diff( + speed_trajectory, + dim=1, + prepend=torch.zeros_like(speed_trajectory[:, :1]), + ) + step_tokens = self.step_encoder( + torch.cat((speed_trajectory, speed_delta, aligned_route), dim=-1) + ) + + scene = self.scene_encoder(scene_feature) + context = torch.cat( + ( + scene[:, None].expand(-1, self.horizon, -1), + route_summary[:, None].expand(-1, self.horizon, -1), + step_tokens, + ), + dim=-1, + ) + fused = self.fusion(context) + return PooledConsequenceOutput( + risk_logits=self.risk_head(fused).squeeze(-1), + clearance=self.clearance_head(fused).squeeze(-1), + ) + + +class PlanConditionedConsequenceHead(nn.Module): + """Cross-attend waypoint queries to vision tokens, then score the plan. + + Default output is clearance only (ConsDrive v4). With + ``with_risk_head=True`` (ConsDrive v6) an additional per-waypoint risk + logit is produced so the head can train with the v2 BCE + ranking + losses; the flag is off by default so v4 checkpoints keep loading. + """ + + def __init__( + self, + scene_dim: int, + hidden_dim: int = 256, + plan_dim: int = 128, + horizon: int = 10, + route_points: int = 20, + dropout: float = 0.1, + attn_heads: int = 4, + with_risk_head: bool = False, + ): + super().__init__() + self.horizon = int(horizon) + self.route_points = int(route_points) + heads = int(attn_heads) + if hidden_dim % heads != 0: + heads = 1 + self.attn_heads = heads + + self.vision_norm = nn.LayerNorm(scene_dim) + self.kv_proj = nn.Linear(scene_dim, hidden_dim) + self.route_encoder = nn.Sequential( + nn.Linear(4, plan_dim), + nn.SiLU(), + nn.Linear(plan_dim, plan_dim), + ) + # speed xy, speed delta xy, and route point xy at the same progress + self.step_encoder = nn.Sequential( + nn.Linear(6, plan_dim), + nn.SiLU(), + nn.Linear(plan_dim, plan_dim), + ) + self.query_proj = nn.Linear(2 * plan_dim, hidden_dim) + self.cross_attn = nn.MultiheadAttention( + hidden_dim, heads, dropout=dropout, batch_first=True + ) + self.fusion = nn.Sequential( + nn.LayerNorm(hidden_dim + 2 * plan_dim), + nn.Linear(hidden_dim + 2 * plan_dim, hidden_dim), + nn.SiLU(), + nn.Dropout(dropout), + nn.Linear(hidden_dim, hidden_dim), + nn.SiLU(), + ) + self.clearance_head = nn.Linear(hidden_dim, 1) + self.with_risk_head = bool(with_risk_head) + if self.with_risk_head: + self.risk_head = nn.Linear(hidden_dim, 1) + + def forward( + self, + vision_tokens: Tensor, + vision_mask: Tensor, + route: Tensor, + speed_trajectory: Tensor, + ): + _check_plan_shapes( + vision_tokens, route, speed_trajectory, self.route_points, self.horizon + ) + dtype = self.kv_proj.weight.dtype + vision_tokens = vision_tokens.to(dtype=dtype) + route = route.to(dtype=dtype) + speed_trajectory = speed_trajectory.to(dtype=dtype) + + route_delta = torch.diff( + route, dim=1, prepend=torch.zeros_like(route[:, :1]) + ) + route_tokens = self.route_encoder(torch.cat((route, route_delta), dim=-1)) + route_summary = route_tokens.mean(dim=1) + + route_indices = torch.linspace( + 0, + route.size(1) - 1, + speed_trajectory.size(1), + device=route.device, + ).round().long() + aligned_route = route.index_select(1, route_indices) + speed_delta = torch.diff( + speed_trajectory, + dim=1, + prepend=torch.zeros_like(speed_trajectory[:, :1]), + ) + step_tokens = self.step_encoder( + torch.cat((speed_trajectory, speed_delta, aligned_route), dim=-1) + ) + query = self.query_proj( + torch.cat( + ( + route_summary[:, None].expand(-1, self.horizon, -1), + step_tokens, + ), + dim=-1, + ) + ) + kv = self.kv_proj(self.vision_norm(vision_tokens)) + padding = ~vision_mask.to(device=vision_tokens.device, dtype=torch.bool) + if padding.size(1) != kv.size(1): + raise ValueError( + f"vision_mask length {padding.size(1)} != vision tokens {kv.size(1)}" + ) + all_pad = padding.all(dim=1) + if bool(all_pad.any()): + padding = padding.clone() + padding[all_pad, 0] = False + attn_out, _ = self.cross_attn( + query, kv, kv, key_padding_mask=padding, need_weights=False + ) + fused = self.fusion( + torch.cat( + ( + attn_out, + route_summary[:, None].expand(-1, self.horizon, -1), + step_tokens, + ), + dim=-1, + ) + ) + if self.with_risk_head: + return PooledConsequenceOutput( + risk_logits=self.risk_head(fused).squeeze(-1), + clearance=self.clearance_head(fused).squeeze(-1), + ) + return ConsequenceOutput(clearance=self.clearance_head(fused).squeeze(-1)) + + +def trajectory_geometry_targets( + trajectory: Tensor, + obstacles: Tensor, + obstacle_valid: Tensor, + step_valid: Tensor, + ego_radius: float = 0.9, + max_clearance: float = 20.0, +) -> Tuple[Tensor, Tensor, Tensor]: + """Compute point-to-oriented-box clearance for a candidate trajectory. + + Args: + trajectory: Candidate ego centres in the current ego frame, [B,H,2]. + obstacles: Future actor boxes in that same frame, [B,H,M,5], stored as + centre x/y, half extent x/y, and yaw. + obstacle_valid: Actor padding mask [B,H,M]. + step_valid: True only when that future box file was reliably loaded + [B,H]. A loaded frame with no actors is valid and has max clearance. + """ + if obstacles.ndim != 4 or obstacles.size(-1) != 5: + raise ValueError("obstacles must have shape [B,H,M,5]") + if trajectory.shape[:2] != obstacles.shape[:2]: + raise ValueError("trajectory and obstacle horizons must match") + + boxes = obstacles.to(device=trajectory.device, dtype=trajectory.dtype) + actor_mask = obstacle_valid.to(device=trajectory.device, dtype=torch.bool) + valid = step_valid.to(device=trajectory.device, dtype=torch.bool) + + delta = trajectory[:, :, None, :] - boxes[..., :2] + yaw = boxes[..., 4] + cos_yaw, sin_yaw = torch.cos(yaw), torch.sin(yaw) + local_x = cos_yaw * delta[..., 0] + sin_yaw * delta[..., 1] + local_y = -sin_yaw * delta[..., 0] + cos_yaw * delta[..., 1] + local = torch.stack((local_x, local_y), dim=-1) + + q = local.abs() - boxes[..., 2:4].clamp_min(0.0) + outside = torch.linalg.vector_norm(q.clamp_min(0.0), dim=-1) + inside = torch.minimum(q.amax(dim=-1), torch.zeros_like(outside)) + signed_clearance = outside + inside - float(ego_radius) + signed_clearance = signed_clearance.masked_fill(~actor_mask, float("inf")) + + has_actor = actor_mask.any(dim=-1) + clearance = signed_clearance.amin(dim=-1) + clearance = torch.where( + has_actor, + clearance.clamp(min=-float(max_clearance), max=float(max_clearance)), + torch.full_like(clearance, float(max_clearance)), + ) + risk = (clearance <= 0.0).to(dtype=trajectory.dtype) + return risk, clearance, valid + + +def visible_obstacle_mask( + obstacles: Tensor, + obstacle_valid: Tensor, + max_range: float = 40.0, + min_x: float = 0.0, +) -> Tensor: + """Keep actors ahead of ego and inside a distance cap (visibility proxy).""" + xy = obstacles[..., :2] + dist = torch.linalg.vector_norm(xy, dim=-1) + ahead = xy[..., 0] >= float(min_x) + near = dist <= float(max_range) + return obstacle_valid.to(dtype=torch.bool) & ahead & near + + +def relative_min_clearance_hinge( + pred_clearance: Tensor, + gt_clearance: Tensor, + pred_valid: Tensor, + gt_valid: Tensor, +) -> Tuple[Tensor, Tensor]: + """Penalise a predicted plan that is worse than the expert's worst gap.""" + pred_min, pred_has = _masked_min_clearance(pred_clearance, pred_valid) + gt_min, gt_has = _masked_min_clearance(gt_clearance, gt_valid) + valid = pred_has & gt_has + hinge = F.relu(gt_min - pred_min) + values = hinge * valid.to(dtype=hinge.dtype) + counts = valid.to(dtype=torch.long) + return values, counts + + +def _masked_min_clearance(clearance: Tensor, valid: Tensor) -> Tuple[Tensor, Tensor]: + valid = valid.to(device=clearance.device, dtype=torch.bool) + fill = torch.finfo(clearance.dtype).max + filled = clearance.masked_fill(~valid, fill) + min_c = filled.min(dim=-1).values + has = valid.any(dim=-1) + min_c = torch.where(has, min_c, torch.zeros_like(min_c)) + return min_c, has + + +def expand_scene_for_plans( + vision_tokens: Tensor, vision_mask: Tensor, num_plans: int +) -> Tuple[Tensor, Tensor]: + """Repeat a scene along a candidate-plan axis: [B,N,C] -> [B*P,N,C].""" + batch, tokens, channels = vision_tokens.shape + expanded_tokens = ( + vision_tokens[:, None] + .expand(batch, num_plans, tokens, channels) + .reshape(batch * num_plans, tokens, channels) + ) + expanded_mask = ( + vision_mask[:, None] + .expand(batch, num_plans, tokens) + .reshape(batch * num_plans, tokens) + ) + return expanded_tokens, expanded_mask + + +def time_advanced_trajectory(speed_trajectory: Tensor, shift_steps: int) -> Tensor: + """Traverse the same path but arrive ``shift_steps`` waypoints earlier. + + Waypoints are 0.2 s apart, so a shift of k puts the ego where it would + otherwise be k*0.2 s later - the classic "enter the conflict zone too + early" junction mistake. Beyond the original horizon the trajectory is + extrapolated with the final segment direction. + """ + horizon = speed_trajectory.size(1) + shift = int(shift_steps) + if shift <= 0: + return speed_trajectory + last_delta = speed_trajectory[:, -1:] - speed_trajectory[:, -2:-1] + indices = torch.arange(horizon, device=speed_trajectory.device) + shift + overshoot = (indices - (horizon - 1)).clamp_min(0) + indices = indices.clamp_max(horizon - 1) + shifted = speed_trajectory.index_select(1, indices) + return shifted + overshoot.view(1, horizon, 1).to( + dtype=speed_trajectory.dtype + ) * last_delta + + +def make_hard_negative_plans( + route: Tensor, + speed_trajectory: Tensor, + speed_scales: Sequence[float] = (1.35,), + lateral_offset: float = 1.5, + time_shifts: Sequence[int] = (), +) -> Tuple[Tensor, Tensor]: + """Create same-scene counterfactual candidates around a base plan. + + Candidates: one per entry in ``speed_scales`` (same path, faster), left + and right ``lateral_offset`` shifts, and one per entry in ``time_shifts`` + (same path, entered earlier; see ``time_advanced_trajectory``). + """ + batch, route_steps, _ = route.shape + horizon = speed_trajectory.size(1) + route_ramp = torch.linspace( + 0.0, 1.0, route_steps, device=route.device, dtype=route.dtype + ).view(1, route_steps, 1) + speed_ramp = torch.linspace( + 0.0, 1.0, horizon, device=route.device, dtype=route.dtype + ).view(1, horizon, 1) + lateral = route.new_tensor([0.0, float(lateral_offset)]).view(1, 1, 2) + + route_list = [] + speed_list = [] + for scale in speed_scales: + route_list.append(route) + speed_list.append(speed_trajectory * float(scale)) + route_list.append(route + route_ramp * lateral) + speed_list.append(speed_trajectory + speed_ramp * lateral) + route_list.append(route - route_ramp * lateral) + speed_list.append(speed_trajectory - speed_ramp * lateral) + for shift in time_shifts: + route_list.append(route) + speed_list.append(time_advanced_trajectory(speed_trajectory, shift)) + + routes = torch.stack(route_list, dim=1) + speeds = torch.stack(speed_list, dim=1) + candidates = len(speed_scales) + 2 + len(time_shifts) + assert routes.shape == (batch, candidates, route_steps, 2) + return routes, speeds + + +def masked_per_sample_mean( + values: Tensor, mask: Tensor +) -> Tuple[Tensor, Tensor]: + """Reduce waypoint/candidate values while preserving summarise_losses API.""" + mask = mask.to(device=values.device, dtype=torch.bool) + reduce_dims = tuple(range(1, values.ndim)) + counts = mask.sum(dim=reduce_dims) + totals = (values * mask.to(dtype=values.dtype)).sum(dim=reduce_dims) + means = totals / counts.clamp_min(1).to(dtype=values.dtype) + sample_valid = (counts > 0).to(dtype=torch.long) + return means, sample_valid + + +def pairwise_ranking_loss( + safe_logits: Tensor, + unsafe_logits: Tensor, + valid: Tensor, + margin: float, +) -> Tuple[Tensor, Tensor]: + """Rank aggregate risk of proven-unsafe candidates above a safe plan.""" + safe_score = torch.logsumexp(safe_logits.float(), dim=-1) - math.log( + safe_logits.size(-1) + ) + unsafe_score = torch.logsumexp(unsafe_logits.float(), dim=-1) - math.log( + unsafe_logits.size(-1) + ) + losses = F.relu(float(margin) + safe_score[:, None] - unsafe_score) + return masked_per_sample_mean(losses, valid) + + +def binary_waypoint_loss( + logits: Tensor, + targets: Tensor, + valid: Tensor, + pos_weight: Optional[float] = None, +) -> Tuple[Tensor, Tensor]: + weight = None + if pos_weight is not None and float(pos_weight) != 1.0: + weight = torch.tensor( + float(pos_weight), device=logits.device, dtype=torch.float32 + ) + losses = F.binary_cross_entropy_with_logits( + logits.float(), targets.to(device=logits.device, dtype=torch.float32), + reduction="none", + pos_weight=weight, + ) + return masked_per_sample_mean(losses, valid) + + +def clearance_waypoint_loss( + prediction: Tensor, + targets: Tensor, + valid: Tensor, + beta: float = 1.0, +) -> Tuple[Tensor, Tensor]: + losses = F.smooth_l1_loss( + prediction.float(), + targets.to(device=prediction.device, dtype=torch.float32), + beta=float(beta), + reduction="none", + ) + return masked_per_sample_mean(losses, valid) + + +def aggregate_risk_logits(risk_logits: Tensor) -> Tensor: + return torch.logsumexp(risk_logits.float(), dim=-1) - math.log( + risk_logits.size(-1) + ) + + +def _check_plan_shapes( + vision_tokens: Tensor, + route: Tensor, + speed_trajectory: Tensor, + route_points: int, + horizon: int, +) -> None: + if vision_tokens.ndim != 3: + raise ValueError("vision_tokens must have shape [B,N,C]") + if route.shape != (vision_tokens.size(0), route_points, 2): + raise ValueError(f"route must have shape [B,{route_points},2]") + if speed_trajectory.shape != (vision_tokens.size(0), horizon, 2): + raise ValueError(f"speed_trajectory must have shape [B,{horizon},2]") diff --git a/models/qwen_utils.py b/models/qwen_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..e54ee5f78fceb41f2b17a495bcd6ef43b9ece11f --- /dev/null +++ b/models/qwen_utils.py @@ -0,0 +1,80 @@ +import json +from pathlib import Path +from typing import Dict, TypeVar + +import torch +from accelerate import init_empty_weights +from safetensors import safe_open +from torch import nn + +ModuleT = TypeVar("ModuleT", bound=nn.Module) + + +def _shard_paths_for_prefix(model_dir: Path, prefix: str) -> list[Path]: + index_path = model_dir / "model.safetensors.index.json" + if index_path.exists(): + with open(index_path, encoding="utf-8") as f: + weight_map = json.load(f)["weight_map"] + + shard_names = sorted( + {shard_name for key, shard_name in weight_map.items() if key.startswith(prefix)} + ) + if not shard_names: + raise RuntimeError(f"No weights found for prefix {prefix!r} in {index_path}") + return [model_dir / shard_name for shard_name in shard_names] + + single_path = model_dir / "model.safetensors" + if single_path.exists(): + with safe_open(single_path, framework="pt", device="cpu") as shard: + if any(key.startswith(prefix) for key in shard.keys()): + return [single_path] + raise RuntimeError(f"No weights found for prefix {prefix!r} in {single_path}") + + raise FileNotFoundError( + f"Missing safetensors weights in {model_dir}: expected " + f"model.safetensors.index.json or model.safetensors" + ) + + +def load_prefixed_state_dict(model_path: str, prefix: str) -> Dict[str, torch.Tensor]: + model_dir = Path(model_path) + state_dict: Dict[str, torch.Tensor] = {} + for shard_path in _shard_paths_for_prefix(model_dir, prefix): + with safe_open(shard_path, framework="pt", device="cpu") as shard: + for key in shard.keys(): + if key.startswith(prefix): + state_dict[key[len(prefix) :]] = shard.get_tensor(key) + return state_dict + + +def build_empty_module(module_cls, config) -> ModuleT: + """Build module on meta device without random weight initialization.""" + with init_empty_weights(): + return module_cls._from_config(config) + + +def load_prefixed_safetensors( + module: nn.Module, + model_path: str, + prefix: str, + torch_dtype: torch.dtype | None = None, +) -> None: + state_dict = load_prefixed_state_dict(model_path, prefix) + if torch_dtype is not None: + state_dict = {key: value.to(torch_dtype) for key, value in state_dict.items()} + + missing, unexpected = module.load_state_dict(state_dict, strict=False, assign=True) + if missing or unexpected: + raise RuntimeError( + f"Failed loading Qwen weights for prefix {prefix!r}: " + f"missing={missing[:10]}, unexpected={unexpected[:10]}" + ) + + # Materialize any parameters that were not present in the checkpoint. + for name, param in module.named_parameters(): + if param.device.type == "meta": + raise RuntimeError(f"Parameter {name!r} remained on meta device after loading {prefix!r}") + + for name, buffer in module.named_buffers(): + if buffer.device.type == "meta": + raise RuntimeError(f"Buffer {name!r} remained on meta device after loading {prefix!r}") diff --git a/models/stream_petr.py b/models/stream_petr.py new file mode 100644 index 0000000000000000000000000000000000000000..ff7fab79cb19971416aba505a02eda38c5a4eba9 --- /dev/null +++ b/models/stream_petr.py @@ -0,0 +1,611 @@ +"""Stage 2 (v2): StreamPETR-style monocular 3D detector with object-query memory on the FastVLM vision tower. + +Image tokens are the FPN stride-8 features of FastViTHD (models/detector.py) with PETR's 3D position +embedding: every token is lifted along its camera ray to DEPTH_BINS depths, the points are normalised +to PC_RANGE and encoded by an MLP gated by the token's own features (PETRv2 feature-guided PE). A set of +learnable 3D reference points becomes object queries; the decoder layers attend to the image tokens and, +through hybrid self-attention, to a memory queue of the top-K queries of the last MEMORY_FRAMES frames. +Memory entries are aligned to the current frame with the ego motion and the objects' own velocity and +re-encoded by motion-aware layer normalisation (StreamPETR); the most recent K of them are propagated +into the current query set, so a track keeps its query across frames. + +Every query predicts class scores, the box centre as a sigmoid-space offset from its reference point, +log half extents, heading (sin, cos) and velocity in the ego frame, and Laplace scales for range and +velocity, so decoded detections have the fields of models.detector.decode and feed the same tracker. +Training uses Hungarian set matching with focal + L1 losses on every decoder layer plus denoising +queries (noised ground-truth boxes with a known assignment). +""" +import math + +import numpy as np +import torch +import torch.nn.functional as F +from scipy.optimize import linear_sum_assignment +from torch import nn + +from dataloader.detection_data import CAMERA_X, CAMERA_Z, FOCAL, GRID_H, GRID_W, IMAGE_H, IMAGE_W, STRIDE +from dataloader.detection_labels import ( + OBJ_BANK_VISIBLE, OBJ_CLASS, OBJ_HALF_H, OBJ_HALF_L, OBJ_HALF_W, OBJ_LIDAR_POINTS, OBJ_SPEED, OBJ_X, OBJ_Y, + OBJ_YAW, OBJ_Z, +) +from dataloader.object_bank import NUM_CLASSES +from models.detector import FASTVIT_STAGE_INDEX, FPN, build_fastvithd + +PC_RANGE = (-5.0, -50.0, -2.0, 60.0, 50.0, 4.0) # x_min, y_min, z_min, x_max, y_max, z_max (box frame, metres) +DEPTH_BINS, DEPTH_MIN, DEPTH_MAX = 64, 1.0, 61.0 +VEL_SCALE = 10.0 +# regression code: dx dy dz (sigmoid-space offsets), log half l w h, sin yaw, cos yaw, vx vy (/VEL_SCALE), +# log sigma range, log sigma vx, log sigma vy +CODE_DIM = 13 +BOX_DIM = 10 # target code: x y z, log half l w h, sin, cos, vx, vy +POSITIVE_RANGE = 50.0 # boxes the detector must find (as det_v1) +MATCH_RANGE = 55.0 # labelled boxes farther than this are neither matched nor negatives + + +# ------------------------------------------------------------------------------------------ helpers +def inverse_sigmoid(x, eps=1e-5): + x = x.clamp(eps, 1 - eps) + return torch.log(x / (1 - x)) + + +def normalize_xyz(xyz): + lo, hi = xyz.new_tensor(PC_RANGE[:3]), xyz.new_tensor(PC_RANGE[3:]) + return (xyz - lo) / (hi - lo) + + +def denormalize_xyz(n): + lo, hi = n.new_tensor(PC_RANGE[:3]), n.new_tensor(PC_RANGE[3:]) + return n * (hi - lo) + lo + + +def sine_embedding(pos, num_feats=128, temperature=10000.0): + """[..., D] in [0, 1] -> [..., D * num_feats] sine/cosine features.""" + pos = pos.float() * 2 * math.pi + dim_t = torch.arange(num_feats, dtype=torch.float32, device=pos.device) + dim_t = temperature ** (2 * torch.div(dim_t, 2, rounding_mode="floor") / num_feats) + out = [] + for i in range(pos.shape[-1]): + p = pos[..., i, None] / dim_t + out.append(torch.stack((p[..., 0::2].sin(), p[..., 1::2].cos()), -1).flatten(-2)) + return torch.cat(out, -1) + + +def mlp(dims, final_bias=None): + layers = [] + for i in range(len(dims) - 1): + layers.append(nn.Linear(dims[i], dims[i + 1])) + if i < len(dims) - 2: + layers.append(nn.ReLU(inplace=True)) + if final_bias is not None: + nn.init.constant_(layers[-1].bias, final_bias) + return nn.Sequential(*layers) + + +def camera_frustum_points(): + """Box-frame points [GRID_H * GRID_W, DEPTH_BINS, 3] of the stride-8 cell centres at LID depth bins.""" + u = (torch.arange(GRID_W, dtype=torch.float32) + 0.5) * STRIDE + v = (torch.arange(GRID_H, dtype=torch.float32) + 0.5) * STRIDE + i = torch.arange(DEPTH_BINS, dtype=torch.float32) + 0.5 + d = DEPTH_MIN + (DEPTH_MAX - DEPTH_MIN) * i * (i + 1) / (DEPTH_BINS * (DEPTH_BINS + 1)) + vv, uu = torch.meshgrid(v, u, indexing="ij") + uu, vv, d = uu.reshape(-1, 1), vv.reshape(-1, 1), d[None] + x = (d + CAMERA_X).expand(uu.shape[0], -1) + y = (uu - IMAGE_W / 2) * d / FOCAL + z = -(vv - IMAGE_H / 2) * d / FOCAL + CAMERA_Z + return torch.stack((x, y, z), -1) + + +def image_grid_uv(): + """Normalised (u, v) of the stride-8 cell centres [GRID_H * GRID_W, 2].""" + u = (torch.arange(GRID_W, dtype=torch.float32) + 0.5) / GRID_W + v = (torch.arange(GRID_H, dtype=torch.float32) + 0.5) / GRID_H + vv, uu = torch.meshgrid(v, u, indexing="ij") + return torch.stack((uu.reshape(-1), vv.reshape(-1)), -1) + + +def ego_from_world(w, pose): + """World points [..., 2] -> ego frame of pose [..., 3] (x, y, yaw); same convention as ego_motion.""" + c, s = torch.cos(pose[..., 2]), torch.sin(pose[..., 2]) + dx, dy = w[..., 0] - pose[..., 0], w[..., 1] - pose[..., 1] + return torch.stack((c * dx + s * dy, -s * dx + c * dy), -1) + + +def world_from_ego(p, pose): + c, s = torch.cos(pose[..., 2]), torch.sin(pose[..., 2]) + return torch.stack((c * p[..., 0] - s * p[..., 1] + pose[..., 0], s * p[..., 0] + c * p[..., 1] + pose[..., 1]), -1) + + +def rotate(v, angle): + c, s = torch.cos(angle), torch.sin(angle) + return torch.stack((c * v[..., 0] - s * v[..., 1], s * v[..., 0] + c * v[..., 1]), -1) + + +# ------------------------------------------------------------------------------------------ decoder +class DecoderLayer(nn.Module): + def __init__(self, d=256, heads=8, ffn=1024, dropout=0.0): + super().__init__() + self.heads = heads + self.self_attn = nn.MultiheadAttention(d, heads, dropout=dropout, batch_first=True) + self.cross_attn = nn.MultiheadAttention(d, heads, dropout=dropout, batch_first=True) + self.ffn = nn.Sequential(nn.Linear(d, ffn), nn.ReLU(inplace=True), nn.Dropout(dropout), nn.Linear(ffn, d)) + self.norm1, self.norm2, self.norm3 = nn.LayerNorm(d), nn.LayerNorm(d), nn.LayerNorm(d) + self.drop = nn.Dropout(dropout) + + def forward(self, q, q_pos, mem, mem_pos, attn_mask, img, img_pos): + """q [B, L, d] queries; mem [B, S_m, d] memory-only keys; attn_mask [B, L, L + S_m] (True = blocked).""" + k = torch.cat((q + q_pos, mem + mem_pos), 1) + v = torch.cat((q, mem), 1) + mask = attn_mask.repeat_interleave(self.heads, 0) + x = self.self_attn(q + q_pos, k, v, attn_mask=mask, need_weights=False)[0] + q = self.norm1(q + self.drop(x)) + x = self.cross_attn(q + q_pos, img + img_pos, img, need_weights=False)[0] + q = self.norm2(q + self.drop(x)) + return self.norm3(q + self.drop(self.ffn(q))) + + +class StreamPETR(nn.Module): + def __init__(self, init="pretrained/FastVLM-0.5B", embed=256, num_queries=400, num_propagated=128, + memory_frames=4, layers=6, dn_groups=3, dn_noise=(1.0, 1.0, 0.3), dn_label_noise=0.25, + freeze_backbone=False, fpn_channels=128): + """init: FastVLM checkpoint dir, a driving-model .ckpt, or a train_detector.py .pt (backbone + FPN).""" + super().__init__() + from_detector = init.endswith(".pt") + self.backbone = build_fastvithd("pretrained/FastVLM-0.5B" if from_detector else init) + self.freeze_backbone = bool(freeze_backbone) + if self.freeze_backbone: + self.backbone.requires_grad_(False) + self.fpn = FPN(fpn_channels) + if from_detector: + state = torch.load(init, map_location="cpu", weights_only=False)["model"] + self.backbone.load_state_dict({k[len("backbone."):]: v for k, v in state.items() if k.startswith("backbone.")}) + self.fpn.load_state_dict({k[len("fpn."):]: v for k, v in state.items() if k.startswith("fpn.")}) + self.embed, self.num_queries, self.num_propagated = embed, num_queries, num_propagated + self.memory_frames, self.dn_groups = memory_frames, dn_groups + self.dn_noise, self.dn_label_noise = dn_noise, dn_label_noise + + self.in_proj = nn.Conv2d(fpn_channels, embed, 1) + self.register_buffer("pe3d_input", inverse_sigmoid(normalize_xyz(camera_frustum_points())).flatten(1), + persistent=False) + self.register_buffer("pe2d_input", sine_embedding(image_grid_uv(), embed // 2), persistent=False) + self.pe3d = mlp([DEPTH_BINS * 3, embed * 4, embed]) + self.pe2d = mlp([embed, embed, embed]) + self.fpe = mlp([embed, embed, embed]) + self.reference_points = nn.Embedding(num_queries, 3) + nn.init.uniform_(self.reference_points.weight, 0.0, 1.0) + self.query_pos = mlp([embed // 2 * 3, embed, embed]) + self.dn_label_enc = nn.Embedding(NUM_CLASSES + 1, embed) + self.mln = mlp([5, embed, 2 * embed]) + self.mln_norm = nn.LayerNorm(embed, elementwise_affine=False) + self.layers = nn.ModuleList([DecoderLayer(embed) for _ in range(layers)]) + self.cls_heads = nn.ModuleList([mlp([embed, embed, embed, NUM_CLASSES], final_bias=-math.log(99.0)) + for _ in range(layers)]) + self.reg_heads = nn.ModuleList([mlp([embed, embed, embed, CODE_DIM]) for _ in range(layers)]) + for h in self.reg_heads: + nn.init.zeros_(h[-1].weight) + nn.init.zeros_(h[-1].bias) + self.memory = None + + # ------------------------------------------------------------------------------ image tokens + def backbone_features(self, images): + 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 image_tokens(self, images): + if self.freeze_backbone: + with torch.no_grad(): + feats = self.backbone_features(images) + else: + feats = self.backbone_features(images) + img = self.in_proj(self.fpn(feats)[8]).flatten(2).transpose(1, 2) # [B, N, embed] + pos = self.pe3d(self.pe3d_input)[None] * torch.sigmoid(self.fpe(img)) + self.pe2d(self.pe2d_input)[None] + return img, pos + + # ------------------------------------------------------------------------------ memory + def reset_memory(self, keep=None): + """Clear the memory queue: everything (keep None) or the batch elements where keep is False.""" + if keep is None or self.memory is None: + self.memory = None + return + keep = keep.to(self.memory["valid"].device) + for k, v in self.memory.items(): + self.memory[k] = torch.where(keep.view(-1, *([1] * (v.dim() - 1))), v, torch.zeros_like(v)) + + def _empty_memory(self, b, device): + n, d = self.memory_frames * self.num_propagated, self.embed + return dict(embed=torch.zeros(b, n, d, device=device), ref=torch.zeros(b, n, 3, device=device), + vel=torch.zeros(b, n, 2, device=device), pose=torch.zeros(b, n, 3, device=device), + time=torch.zeros(b, n, device=device), valid=torch.zeros(b, n, dtype=torch.bool, device=device)) + + def aligned_memory(self, pose, time): + """Memory entries moved into the current ego frame: (embed, pos, ref_norm, valid).""" + m = self.memory + pose_m = m["pose"] + pose_b = pose[:, None].expand_as(pose_m) + dt = (time[:, None] - m["time"]).clamp(min=0.0) + moved = m["ref"][..., :2] + m["vel"] * dt[..., None] + ref_xy = ego_from_world(world_from_ego(moved, pose_m), pose_b) + ref = torch.cat((ref_xy, m["ref"][..., 2:3]), -1) + rel_t = ego_from_world(pose_m[..., :2], pose_b) + dyaw = pose_m[..., 2] - pose[:, None, 2] + motion = torch.stack((rel_t[..., 0] / 10.0, rel_t[..., 1] / 10.0, torch.cos(dyaw), torch.sin(dyaw), dt), -1) + gamma, beta = self.mln(motion).chunk(2, -1) + embed = self.mln_norm(m["embed"]) * (1 + gamma) + beta + ref_norm = normalize_xyz(ref).clamp(0.0, 1.0) + pos = self.query_pos(sine_embedding(ref_norm, self.embed // 2)) + return embed, pos, ref_norm, m["valid"] + + @torch.no_grad() + def update_memory(self, embed, center, vel, score, valid, pose, time): + """Push the top-K current queries (by score) to the front of the memory queue.""" + k = self.num_propagated + top = score.masked_fill(~valid, -1.0).topk(k, dim=1).indices + g = lambda x: x.gather(1, top.unsqueeze(-1).expand(-1, -1, x.shape[-1])) # noqa: E731 + new = dict(embed=g(embed).float(), ref=g(center).float(), vel=g(vel).float(), + pose=pose[:, None].expand(-1, k, -1).float(), time=time[:, None].expand(-1, k).float(), + valid=valid.gather(1, top)) + for key in self.memory: + self.memory[key] = torch.cat((new[key], self.memory[key][:, :-k]), 1) + + # ------------------------------------------------------------------------------ denoising queries + def make_dn(self, gt_rows, gt_count, device): + """Noised copies of the positive ground-truth boxes: (embed, ref_norm, valid, group, gt_index). + + At least one (invalid, padded) query is always produced so the module graph is the same on + every rank.""" + b = gt_rows.shape[0] + pos = positive_mask(gt_rows, gt_count) + n_max = int(pos.sum(1).max().item()) + n_dn = max(self.dn_groups * n_max, 1) + ref = torch.full((b, n_dn, 3), 0.5, device=device) + label = torch.full((b, n_dn), NUM_CLASSES, dtype=torch.long, device=device) + valid = torch.zeros(b, n_dn, dtype=torch.bool, device=device) + group = torch.zeros(b, n_dn, dtype=torch.long, device=device) + gt_index = torch.zeros(b, n_dn, dtype=torch.long, device=device) + if n_max: + noise = gt_rows.new_tensor(self.dn_noise) + for i in range(b): + idx = pos[i].nonzero()[:, 0] + n = len(idx) + if n == 0: + continue + rows = gt_rows[i, idx] + for g in range(self.dn_groups): + sl = slice(g * n_max, g * n_max + n) + center = rows[:, [OBJ_X, OBJ_Y, OBJ_Z]] + (torch.rand(n, 3, device=device) * 2 - 1) * noise + lab = rows[:, OBJ_CLASS].long() + flip = torch.rand(n, device=device) < self.dn_label_noise + lab = torch.where(flip, torch.randint(0, NUM_CLASSES, (n,), device=device), lab) + ref[i, sl] = normalize_xyz(center).clamp(0.01, 0.99) + label[i, sl] = lab + valid[i, sl], group[i, sl], gt_index[i, sl] = True, g, idx + return self.dn_label_enc(label), ref, valid, group, gt_index + + # ------------------------------------------------------------------------------ forward + def forward(self, images, pose, time, gt_rows=None, gt_count=None): + """images uint8 [B, 3, H, W]; pose [B, 3] world (x, y, yaw); time [B] seconds; optional labels + [B, K, OBJ_DIM] / [B] switch denoising queries on. + + Call reset_memory() at the start of a sequence. Returns per-layer predictions for the query set + [dn | current | propagated] plus the index layout; the memory queue is updated as a side effect.""" + b, device = images.shape[0], images.device + img, img_pos = self.image_tokens(images) + img_pos = img_pos.to(img.dtype) + if self.memory is None or self.memory["embed"].shape[0] != b: + self.memory = self._empty_memory(b, device) + pose, time = pose.float(), time.float() + mem_embed, mem_pos, mem_ref, mem_valid = self.aligned_memory(pose, time) + k = self.num_propagated + prop_embed, prop_pos, prop_ref, prop_valid = mem_embed[:, :k], mem_pos[:, :k], mem_ref[:, :k], mem_valid[:, :k] + rest_embed, rest_pos, rest_valid = mem_embed[:, k:], mem_pos[:, k:], mem_valid[:, k:] + + cur_ref = self.reference_points.weight[None].expand(b, -1, -1) + cur_pos = self.query_pos(sine_embedding(cur_ref, self.embed // 2)) + cur_embed = torch.zeros_like(cur_pos) + + if gt_rows is not None: + dn_embed, dn_ref, dn_valid, dn_group, dn_gt = self.make_dn(gt_rows, gt_count, device) + dn_pos = self.query_pos(sine_embedding(dn_ref, self.embed // 2)) + q = torch.cat((dn_embed, cur_embed, prop_embed), 1) + q_pos = torch.cat((dn_pos, cur_pos, prop_pos), 1) + ref = torch.cat((dn_ref, cur_ref, prop_ref), 1) + n_dn = dn_embed.shape[1] + else: + dn_valid = dn_group = dn_gt = None + q = torch.cat((cur_embed, prop_embed), 1) + q_pos = torch.cat((cur_pos, prop_pos), 1) + ref = torch.cat((cur_ref, prop_ref), 1) + n_dn = 0 + n_cur, n_rest = self.num_queries, rest_embed.shape[1] + L = q.shape[1] + # self-attention keys are [dn | cur | prop | rest memory]; True blocks + key_valid = torch.cat((torch.ones(b, n_dn + n_cur, dtype=torch.bool, device=device), prop_valid, rest_valid), 1) + mask = ~key_valid[:, None, :].expand(-1, L, -1).clone() + if n_dn: + mask[:, n_dn:, :n_dn] = True # matching queries never see denoising queries + same = dn_group[:, :, None] == dn_group[:, None, :] + mask[:, :n_dn, :n_dn] |= ~same | ~dn_valid[:, None, :] + eye = torch.eye(L, dtype=torch.bool, device=device)[None] + mask[:, :, :L] &= ~eye # every query attends to itself (no empty rows) + + ref_logit = inverse_sigmoid(ref.float()) + q, q_pos = q.to(img.dtype), q_pos.to(img.dtype) + rest_embed, rest_pos = rest_embed.to(img.dtype), rest_pos.to(img.dtype) + outs = [] + for layer, cls_head, reg_head in zip(self.layers, self.cls_heads, self.reg_heads): + q = layer(q, q_pos, rest_embed, rest_pos, mask, img, img_pos) + reg = reg_head(q).float() + outs.append(dict(cls=cls_head(q).float(), center=denormalize_xyz(torch.sigmoid(ref_logit + reg[..., 0:3])), + log_size=reg[..., 3:6], sincos=reg[..., 6:8], vel=reg[..., 8:10] * VEL_SCALE, + log_sigma=reg[..., 10:13])) + valid = torch.cat((torch.ones(b, n_cur, dtype=torch.bool, device=device), prop_valid), 1) + last = outs[-1] + score = torch.sigmoid(last["cls"][:, n_dn:]).max(-1).values + self.update_memory(q[:, n_dn:].detach(), last["center"][:, n_dn:].detach(), last["vel"][:, n_dn:].detach(), + score.detach(), valid, pose, time) + return dict(layers=outs, n_dn=n_dn, n_cur=n_cur, n_prop=k, query_valid=valid, dn_valid=dn_valid, + dn_gt=dn_gt) + + +# ------------------------------------------------------------------------------------------ targets / loss +def positive_mask(rows, count): + """[B, K] boxes the detector must find: bank-visible, within 50 m of the camera, hit by the lidar.""" + present = torch.arange(rows.shape[1], device=rows.device)[None] < count[:, None] + rng = torch.hypot(rows[..., OBJ_X] - CAMERA_X, rows[..., OBJ_Y]) + return present & (rows[..., OBJ_BANK_VISIBLE] > 0.5) & (rng <= POSITIVE_RANGE) & (rows[..., OBJ_LIDAR_POINTS] >= 1) + + +def matchable_mask(rows, count): + present = torch.arange(rows.shape[1], device=rows.device)[None] < count[:, None] + rng = torch.hypot(rows[..., OBJ_X] - CAMERA_X, rows[..., OBJ_Y]) + return present & (rng <= MATCH_RANGE) + + +def box_code(rows): + """[..., OBJ_DIM] -> target code (centre xyz, log half extents, sin, cos, vx, vy) [..., BOX_DIM].""" + yaw, speed = rows[..., OBJ_YAW], rows[..., OBJ_SPEED] + return torch.cat((rows[..., [OBJ_X, OBJ_Y, OBJ_Z]], + torch.log(rows[..., [OBJ_HALF_L, OBJ_HALF_W, OBJ_HALF_H]].clamp(min=1e-3)), + torch.sin(yaw)[..., None], torch.cos(yaw)[..., None], + (speed * torch.cos(yaw))[..., None], (speed * torch.sin(yaw))[..., None]), -1) + + +def pred_code(layer, sl): + return torch.cat((layer["center"][:, sl], layer["log_size"][:, sl], layer["sincos"][:, sl], layer["vel"][:, sl]), -1) + + +def focal_cost(logits, gt_cls, alpha=0.25, gamma=2.0): + """[L, C] logits, [G] classes -> [L, G] classification matching cost.""" + p = torch.sigmoid(logits) + neg = (1 - alpha) * p ** gamma * (-(1 - p).clamp(min=1e-8).log()) + pos = alpha * (1 - p) ** gamma * (-p.clamp(min=1e-8).log()) + return pos[:, gt_cls] - neg[:, gt_cls] + + +def sigmoid_focal(logits, target_onehot, alpha=0.25, gamma=2.0): + p = torch.sigmoid(logits) + ce = F.binary_cross_entropy_with_logits(logits, target_onehot, reduction="none") + p_t = p * target_onehot + (1 - p) * (1 - target_onehot) + alpha_t = alpha * target_onehot + (1 - alpha) * (1 - target_onehot) + return alpha_t * ce * (1 - p_t) ** gamma + + +def laplace_scale_term(err, log_sigma): + """Trains only the scale (the mean is trained by the L1): err.detach() * exp(-s) + s.""" + log_sigma = log_sigma.clamp(-5.0, 5.0) + return err.detach() * torch.exp(-log_sigma) + log_sigma + + +@torch.no_grad() +def hungarian_all(layers, sl, query_valid, gt_code, gt_cls, w_cls, w_box): + """Assignments for every (layer, sample): list over layers of lists of (q_idx, g_idx) LongTensors (CPU). + + All cost matrices are moved to the CPU in one transfer.""" + b = query_valid.shape[0] + g_max = max([len(g) for g in gt_code] + [1]) + costs = [] + for layer in layers: + pc = pred_code(layer, sl)[..., :8] + cost = pc.new_full((b, pc.shape[1], g_max), 1e6) + for i in range(b): + if len(gt_code[i]): + c = w_cls * focal_cost(layer["cls"][i, sl], gt_cls[i]) + w_box * torch.cdist(pc[i], gt_code[i][:, :8], p=1) + cost[i, :, :len(gt_code[i])] = c.masked_fill(~query_valid[i][:, None], 1e6) + costs.append(cost) + costs = torch.stack(costs).cpu().numpy() + out = [] + for li in range(len(layers)): + pairs = [] + for i in range(b): + n = len(gt_code[i]) + if n == 0: + pairs.append((torch.zeros(0, dtype=torch.long), torch.zeros(0, dtype=torch.long))) + continue + r, c = linear_sum_assignment(costs[li, i, :, :n]) + pairs.append((torch.as_tensor(r, dtype=torch.long), torch.as_tensor(c, dtype=torch.long))) + out.append(pairs) + return out + + +def stream_petr_loss(out, gt_rows, gt_count, w_cls=2.0, w_box=0.25, w_vel=1.0, w_sigma=0.1, w_dn=1.0): + """Set loss over all decoder layers plus the denoising loss. gt_rows [B, K, OBJ_DIM] float, gt_count [B]. + + Queries matched to an uncertain labelled box (not bank-visible / no lidar point / beyond 50 m) get + no classification target and no negative pressure; boxes beyond MATCH_RANGE are not matched.""" + device = gt_rows.device + b = gt_rows.shape[0] + n_dn, n_cur, n_prop = out["n_dn"], out["n_cur"], out["n_prop"] + sl = slice(n_dn, n_dn + n_cur + n_prop) + qv = out["query_valid"] + match = matchable_mask(gt_rows, gt_count) + pos = positive_mask(gt_rows, gt_count) + gt_code = [box_code(gt_rows[i, match[i]]) for i in range(b)] + gt_cls = [gt_rows[i, match[i], OBJ_CLASS].long() for i in range(b)] + gt_pos = [pos[i, match[i]] for i in range(b)] + num_pos = max(float(pos.sum().item()), 1.0) + assignments = hungarian_all(out["layers"], sl, qv, gt_code, gt_cls, w_cls, w_box) + zero = gt_rows.new_zeros(()) + losses = dict(cls=zero, box=zero, vel=zero, sigma=zero, dn_cls=zero, dn_box=zero) + dv, dg = out["dn_valid"], out["dn_gt"] + if n_dn: + n_dn_valid = max(float(dv.sum().item()), 1.0) + gt_cls_all = gt_rows[..., OBJ_CLASS].long() + dn_target = torch.zeros(b, n_dn, NUM_CLASSES, device=device) + dn_target.scatter_(2, gt_cls_all.gather(1, dg)[..., None], 1.0) + dn_target = dn_target * dv[..., None] + dn_gt_code = box_code(gt_rows).gather(1, dg[..., None].expand(-1, -1, BOX_DIM)) + for layer, pairs in zip(out["layers"], assignments): + logits = layer["cls"][:, sl] + target = torch.zeros_like(logits) + weight = qv.float().clone() # 0 for invalid propagated queries + pc = pred_code(layer, sl) + ls = layer["log_sigma"][:, sl] + box_l = vel_l = sig_l = zero + for i, (r, c) in enumerate(pairs): + if len(r) == 0: + continue + r, c = r.to(device), c.to(device) + is_pos = gt_pos[i][c] + target[i, r[is_pos], gt_cls[i][c[is_pos]]] = 1.0 + weight[i, r[~is_pos]] = 0.0 + rp, cp = r[is_pos], c[is_pos] + if len(rp) == 0: + continue + p, g = pc[i, rp], gt_code[i][cp] + box_l = box_l + (p[:, :8] - g[:, :8]).abs().sum() + vel_err = (p[:, 8:10] - g[:, 8:10]).abs() + vel_l = vel_l + vel_err.sum() + rng_err = (torch.hypot(p[:, 0] - CAMERA_X, p[:, 1]) - torch.hypot(g[:, 0] - CAMERA_X, g[:, 1])).abs() + sig_l = sig_l + laplace_scale_term(rng_err, ls[i, rp, 0]).sum() \ + + laplace_scale_term(vel_err, ls[i, rp, 1:3]).sum() + losses["cls"] = losses["cls"] + (sigmoid_focal(logits, target) * weight[..., None]).sum() / num_pos + losses["box"] = losses["box"] + box_l / num_pos + losses["vel"] = losses["vel"] + vel_l / num_pos + losses["sigma"] = losses["sigma"] + sig_l / num_pos + if n_dn: + dn_logits = layer["cls"][:, :n_dn] + losses["dn_cls"] = losses["dn_cls"] + (sigmoid_focal(dn_logits, dn_target) * dv[..., None]).sum() / n_dn_valid + pd = pred_code(layer, slice(0, n_dn)) + err = (pd[..., :8] - dn_gt_code[..., :8]).abs().sum(-1) \ + + w_vel * (pd[..., 8:10] - dn_gt_code[..., 8:10]).abs().sum(-1) + losses["dn_box"] = losses["dn_box"] + (err * dv).sum() / n_dn_valid + losses["total"] = w_cls * losses["cls"] + w_box * losses["box"] + w_box * w_vel * losses["vel"] \ + + w_sigma * losses["sigma"] + w_dn * (w_cls * losses["dn_cls"] + w_box * losses["dn_box"]) + return losses + + +# ------------------------------------------------------------------------------------------ decoding +NMS_LATERAL = {0: 1.0, 1: 0.5, 2: 1.0} # per class: metres across the viewing ray +NMS_RANGE = {0: (1.5, 0.05), 1: (0.75, 0.025), 2: (1.5, 0.05)} # along the ray: a + b * range + + +@torch.no_grad() +def bev_nms(x, y, cls, score): + """Keep mask: a lower-scoring detection of the same class within NMS_LATERAL across and NMS_RANGE along + the viewing ray of a kept one is a duplicate (the set prediction occasionally puts a current and a + propagated query on the same object; their offsets are mostly along the ray, i.e. depth).""" + n = len(score) + keep = torch.ones(n, dtype=torch.bool, device=score.device) + if n < 2: + return keep + dx, dy = x - CAMERA_X, y + rng = torch.hypot(dx, dy) + ux, uy = dx / rng.clamp(min=1e-6), dy / rng.clamp(min=1e-6) + order = torch.argsort(score, descending=True) + x, y, cls, rng, ux, uy = x[order], y[order], cls[order], rng[order], ux[order], uy[order] + lat = torch.tensor([NMS_LATERAL[int(c)] for c in cls.tolist()], device=score.device) + along = torch.tensor([NMS_RANGE[int(c)][0] + NMS_RANGE[int(c)][1] * r for c, r in zip(cls.tolist(), rng.tolist())], + device=score.device) + ddx, ddy = x[None] - x[:, None], y[None] - y[:, None] # [i, j]: j relative to i + d_along = (ddx * ux[:, None] + ddy * uy[:, None]).abs() + d_lat = (-ddx * uy[:, None] + ddy * ux[:, None]).abs() + dup = (cls[None] == cls[:, None]) & (d_along <= along[:, None]) & (d_lat <= lat[:, None]) + kept = torch.ones(n, dtype=torch.bool, device=score.device) + for i in range(n): + if kept[i]: + kept &= ~(dup[i] & (torch.arange(n, device=score.device) > i)) + keep[order] = kept + return keep + + +@torch.no_grad() +def decode_stream(out, score_threshold=0.2, max_detections=64, nms=True): + """Last-layer predictions of the matching queries -> per-image dicts with the fields of detector.decode.""" + n_dn = out["n_dn"] + layer = out["layers"][-1] + cls = layer["cls"][:, n_dn:] + score_all = torch.sigmoid(cls).masked_fill(~out["query_valid"][..., None], 0.0) + scores, flat = score_all.flatten(1).topk(min(max_detections, score_all.shape[1] * score_all.shape[2]), dim=1) + q_idx, c_idx = flat // NUM_CLASSES, flat % NUM_CLASSES + results = [] + for i in range(cls.shape[0]): + keep = scores[i] >= score_threshold + if nms and int(keep.sum()) > 1: + q0 = q_idx[i][keep] + n_dn + c0 = layer["center"][i, q0] + sel = bev_nms(c0[:, 0], c0[:, 1], c_idx[i][keep], scores[i][keep]) + keep[keep.clone()] = sel + q = q_idx[i][keep] + n_dn + center = layer["center"][i, q] + sincos = layer["sincos"][i, q] + vel = layer["vel"][i, q] + yaw = torch.atan2(sincos[:, 0], sincos[:, 1]) + speed = torch.hypot(vel[:, 0], vel[:, 1]) + flip = (speed > 1.0) & (torch.cos(torch.atan2(vel[:, 1], vel[:, 0]) - yaw) < 0) + yaw = torch.where(flip, yaw + math.pi, yaw) + yaw = torch.atan2(torch.sin(yaw), torch.cos(yaw)) + ext = torch.exp(layer["log_size"][i, q].clamp(-4, 4)) + ls = layer["log_sigma"][i, q].clamp(-5, 5) + results.append(dict( + x=center[:, 0], y=center[:, 1], z=center[:, 2], yaw=yaw, speed=speed, vx=vel[:, 0], vy=vel[:, 1], + half_l=ext[:, 0], half_w=ext[:, 1], half_h=ext[:, 2], cls=c_idx[i][keep], score=scores[i][keep], + depth_sigma=torch.exp(ls[:, 0]), velocity_sigma=torch.exp(ls[:, 1:3]), + query=q_idx[i][keep], + )) + return results + + +def load_stream_petr(path, device): + """StreamPETR from a train_stream_petr.py checkpoint, in eval mode with an empty memory.""" + ckpt = torch.load(path, map_location="cpu", weights_only=False) + a = ckpt.get("args", {}) + model = StreamPETR(init="pretrained/FastVLM-0.5B", num_queries=a.get("num_queries", 400), + num_propagated=a.get("num_propagated", 128), memory_frames=a.get("memory_frames", 4), + layers=a.get("layers", 6), dn_groups=a.get("dn_groups", 3)) + model.load_state_dict(ckpt["model"]) + model.reset_memory() + return model.to(device).eval() + + +class StreamDetector: + """Online wrapper: one call per 4 Hz frame, memory carried across calls (reset() at route start).""" + + def __init__(self, model, device, score_threshold=0.2): + self.model, self.device, self.score_threshold = model, device, score_threshold + self.reset() + + def reset(self): + self.model.reset_memory() + + @torch.no_grad() + def step(self, image, pose, time): + """image uint8 [3, H, W] tensor or numpy HWC; pose (x, y, yaw) world; time seconds -> decode dict + of numpy arrays.""" + if isinstance(image, np.ndarray): + image = torch.from_numpy(np.ascontiguousarray(image)).permute(2, 0, 1) + image = image[None].to(self.device, non_blocking=True) + pose_t = torch.tensor(pose, dtype=torch.float32, device=self.device)[None] + time_t = torch.tensor([time], dtype=torch.float32, device=self.device) + with torch.autocast("cuda", dtype=torch.bfloat16): + out = self.model(image, pose_t, time_t) + det = decode_stream(out, self.score_threshold)[0] + return {k: v.float().cpu().numpy() for k, v in det.items()} diff --git a/models/utils.py b/models/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..a2e5d89dc0b48117574d98864e44ba09263a6fdf --- /dev/null +++ b/models/utils.py @@ -0,0 +1,200 @@ +import re +from typing import Dict, Optional, Sequence, Tuple + +import torch +from torch import Tensor, nn +from transformers.models.gemma.modeling_gemma import GemmaRMSNorm +from transformers.models.llama.modeling_llama import LlamaRMSNorm +from transformers.models.qwen2.modeling_qwen2 import Qwen2RMSNorm +try: + from transformers.models.qwen3_vl.modeling_qwen3_vl import Qwen3VLTextRMSNorm +except ImportError: + # FastVLM's official environment uses transformers 4.48 (no Qwen3-VL). + Qwen3VLTextRMSNorm = Qwen2RMSNorm + +from utils.custom_types import ParamGroup, TrainingOutput + + +def configure_params_groups(model: nn.Module, param_groups: Sequence[ParamGroup], verbose: bool = True): + # Partition the parameters into those that will and those that will not experience regularising weight decay + whitelist_weight_modules = ( + torch.nn.Linear, + torch.nn.Conv2d, + torch.nn.Conv3d, + torch.nn.MultiheadAttention, + torch.nn.GRU, + ) + blacklist_weight_modules = ( + LlamaRMSNorm, + GemmaRMSNorm, + Qwen2RMSNorm, + Qwen3VLTextRMSNorm, + torch.nn.GroupNorm, + torch.nn.LayerNorm, + torch.nn.BatchNorm2d, + torch.nn.Embedding, + torch.nn.SyncBatchNorm, + ) + + black_list_weight_names = ( + "latent", + "logit_scale", + "pos_enc", + 'image_newline', + 'class_embedding', + 'temporal_embedding', + "pos_embed", + "positional_encoding", + "temporal_encoding", + "camera_encoding", + "register_tokens", + "sink_token", + "egoposition_head", + "route_head", + "acceleration_head", + "curvature_rate_head", + "query_embeds", + # world predictor bare parameters (positional/type embeddings) + "state_type_embed", + "action_type_embed", + "spatial_embed", + "action_slot_embed", + "time_embed", + # transformers 5.x Qwen2.5-VL specific parameters + 'norm1.weight', + 'norm2.weight', + 'fc1.weight', + 'fc2.weight', + 'merger.ln_q.weight', + 'spatial_merge.weight', + ) + + decay_params = set() + no_decay_params = set() + not_trainable_params = set() + for mn, m in model.named_modules(): + for pn, p in m.named_parameters(): + + fpn = f"{mn}.{pn}" if mn else pn # full param name + if not p.requires_grad: + not_trainable_params.add(fpn) + continue + if pn.endswith('bias'): + # all biases will not be decayed + no_decay_params.add(fpn) + elif ( + pn.endswith('weight') + and isinstance(m, blacklist_weight_modules) + or any(x in fpn for x in black_list_weight_names) + ): + # weights of blacklist modules will NOT be weight decayed + no_decay_params.add(fpn) + elif pn.endswith('weight') and isinstance(m, whitelist_weight_modules): + # weights of whitelist modules will be weight decayed + decay_params.add(fpn) + + # validate that we considered every parameter + param_dict = {pn: p for pn, p in model.named_parameters()} + inter_params = decay_params & no_decay_params + union_params = decay_params | no_decay_params | not_trainable_params + assert len(inter_params) == 0, f"parameters {inter_params} made it into both decay/no_decay sets!" + assert len(param_dict.keys() - union_params) == 0, ( + f"parameters {param_dict.keys() - union_params} were not separated " + f"into either decay/no_decay/not_trainable set!" + ) + + union_params = set(not_trainable_params) + + # split decay/no decay params into separate param groups with different lr + out = [] + for pg in param_groups: + group_params_decay = sorted(k for k in decay_params if re.match(pg.pattern, k)) + group_params_no_decay = sorted(k for k in no_decay_params if re.match(pg.pattern, k)) + + inter_params = union_params.intersection(group_params_decay) + assert len(inter_params) == 0, f"decay parameters {inter_params} made it into multiple param groups" + inter_params = union_params.intersection(group_params_no_decay) + assert len(inter_params) == 0, f"no-decay parameters {inter_params} made it into multiple param groups" + + if pg.weight_decay <= 0.0: + group_params_no_decay = group_params_decay + group_params_no_decay + group_params_decay = [] + if verbose and rank_zero_only.rank == 0: + print(f"==== PARAM_GROUP {pg.pattern} ====") + for pn in group_params_decay: + print(f"(DECAY) {pn}") + for pn in group_params_no_decay: + print(f"(NO_DECAY) {pn}") + if len(group_params_decay) > 0: + out.append( + {'params': [param_dict[pn] for pn in group_params_decay], 'lr': pg.lr, 'weight_decay': pg.weight_decay} + ) + if len(group_params_no_decay) > 0: + out.append({'params': [param_dict[pn] for pn in group_params_no_decay], 'lr': pg.lr, 'weight_decay': 0.0}) + + union_params.update(group_params_decay) + union_params.update(group_params_no_decay) + + assert ( + len(param_dict.keys() - union_params) == 0 + ), f"parameters {param_dict.keys() - union_params} were not separated into any param groups!" + + return out + + +def normalize_imagenet(x): + """ + Normalize input images according to ImageNet standards. + Args: + x (tensor): input images + """ + x = x.copy() + x[:, 0] = ((x[:, 0] / 255.0) - 0.485) / 0.229 + x[:, 1] = ((x[:, 1] / 255.0) - 0.456) / 0.224 + x[:, 2] = ((x[:, 2] / 255.0) - 0.406) / 0.225 + return x + + +def summarise_losses( + loss_dict: Dict[str, Tuple[Tensor, Tensor]], weights: Optional[Dict[str, float]] = None +) -> TrainingOutput: + """ + Computes the total loss from a dictionary of losses and their counts. + + The loss dict should contain two tensor for each key: + - The loss value for each batch sample; shape [B]. + - The loss count for each batch sample; shape [B]. This is the number of items to average over, i.e. + number of tokens, number of cuboids etc. For the case where each batch sample has a loss, you + can set it to a ones tensor of shape [B]. + + Optionally, a weights dictionary can be provided to weight the losses. + + Args: + loss_dict: A dictionary of losses and their counts, for each batch sample. + weights: A dictionary of weights for each loss key. + + Returns: + A TrainingOutput object with the total loss and its components. + """ + + loss_values = {k: v for k, (v, _) in loss_dict.items()} + loss_counts = {k: n for k, (_, n) in loss_dict.items()} + # Clamp the denominator so the unselected `where` branch never divides by + # zero: `d(v/n)/dv = grad/n` is evaluated in backward even when the branch + # is masked out, and 0/0 poisons every upstream gradient with NaN. This + # triggers whenever a loss term has zero valid items in the whole batch + # (e.g. no dream pair / no complete future-box geometry). + loss_averages = { + k: torch.where(n.sum() > 0, v.sum() / n.sum().clamp_min(1), 0.0) + for k, (v, n) in loss_dict.items() + } + if weights is None: + loss = torch.stack(list(loss_averages.values())).sum() + else: + loss = torch.stack([weights.get(k, 1.0) * v for k, v in loss_averages.items()]).sum() + return TrainingOutput( + loss=loss, + loss_values=loss_values, + loss_counts=loss_counts, + loss_averages=loss_averages, + ) diff --git a/models/world_predictor.py b/models/world_predictor.py new file mode 100644 index 0000000000000000000000000000000000000000..4ee238e75e749d8baee00bc0625fc8111b56a654 --- /dev/null +++ b/models/world_predictor.py @@ -0,0 +1,227 @@ +"""Block-causal latent-action world predictor (ported from SimLingo-J1). + +Each temporal block contains 64 V-JEPA2 state tokens and 8 student latent +action tokens. Tokens within a block attend bidirectionally; a block can only +attend to itself and earlier blocks. The predictor is supervised to map +teacher-forced ``S[t]`` plus latent ``A[t]`` to ``S[t+1]``. +""" + +from __future__ import annotations + +from typing import Optional, Tuple + +import torch +import torch.nn.functional as F +from torch import Tensor, nn + + +def build_block_causal_mask( + num_blocks: int, state_tokens: int, action_tokens: int +) -> Tensor: + if min(num_blocks, state_tokens, action_tokens) <= 0: + raise ValueError("block mask dimensions must be positive") + block_size = state_tokens + action_tokens + block_ids = torch.arange(num_blocks).repeat_interleave(block_size) + # PyTorch boolean attention masks use True for forbidden pairs. + return block_ids.unsqueeze(0) > block_ids.unsqueeze(1) + + +def linear_world_weight(global_step: int, weight: float, warmup_steps: int) -> float: + """Weight for the optimizer update about to run (steps are zero-indexed).""" + + if warmup_steps <= 0: + return float(weight) + return float(weight) * min((int(global_step) + 1) / int(warmup_steps), 1.0) + + +class BlockCausalWorldPredictor(nn.Module): + """Predict ``S[t+1]`` from teacher-forced ``S[t]`` and latent ``A[t]``.""" + + def __init__( + self, + *, + action_dim: int, + predictor_dim: int = 1024, + target_dim: int = 1024, + depth: int = 12, + heads: int = 8, + mlp_ratio: float = 4.0, + dropout: float = 0.0, + num_blocks: int = 3, + state_tokens: int = 64, + action_tokens: int = 8, + ) -> None: + super().__init__() + if predictor_dim % heads: + raise ValueError("predictor_dim must be divisible by predictor_heads") + self.num_blocks = int(num_blocks) + self.state_tokens = int(state_tokens) + self.action_tokens = int(action_tokens) + self.state_projection = nn.Linear(target_dim, predictor_dim) + self.action_projection = nn.Linear(action_dim, predictor_dim) + self.state_type_embed = nn.Parameter(torch.zeros(1, 1, predictor_dim)) + self.action_type_embed = nn.Parameter(torch.zeros(1, 1, predictor_dim)) + self.spatial_embed = nn.Parameter( + 0.02 * torch.randn(1, state_tokens, predictor_dim) + ) + self.action_slot_embed = nn.Parameter( + 0.02 * torch.randn(1, action_tokens, predictor_dim) + ) + self.time_embed = nn.Parameter( + torch.zeros(1, num_blocks, 1, predictor_dim) + ) + layer = nn.TransformerEncoderLayer( + d_model=predictor_dim, + nhead=heads, + dim_feedforward=int(predictor_dim * mlp_ratio), + dropout=dropout, + activation="gelu", + batch_first=True, + norm_first=True, + ) + self.transformer = nn.TransformerEncoder( + layer, num_layers=depth, norm=nn.LayerNorm(predictor_dim) + ) + self.output_projection = nn.Linear(predictor_dim, target_dim) + self.register_buffer( + "attention_mask", + build_block_causal_mask(num_blocks, state_tokens, action_tokens), + persistent=False, + ) + + def forward(self, states: Tensor, actions: Tensor) -> Tensor: + expected_states = (self.num_blocks, self.state_tokens) + expected_actions = (self.num_blocks, self.action_tokens) + if states.ndim != 4 or tuple(states.shape[1:3]) != expected_states: + raise ValueError( + f"states must be [B,{self.num_blocks},{self.state_tokens},D], " + f"got {tuple(states.shape)}" + ) + if actions.ndim != 4 or tuple(actions.shape[1:3]) != expected_actions: + raise ValueError( + f"actions must be [B,{self.num_blocks},{self.action_tokens},D], " + f"got {tuple(actions.shape)}" + ) + param_dtype = self.state_projection.weight.dtype + state_tokens = self.state_projection(states.to(param_dtype)) + state_tokens = ( + state_tokens + + self.spatial_embed.unsqueeze(1) + + self.state_type_embed.unsqueeze(1) + + self.time_embed + ) + action_tokens = self.action_projection(actions.to(param_dtype)) + action_tokens = ( + action_tokens + + self.action_slot_embed.unsqueeze(1) + + self.action_type_embed.unsqueeze(1) + + self.time_embed + ) + blocks = torch.cat((state_tokens, action_tokens), dim=2) + encoded = self.transformer( + blocks.flatten(1, 2), mask=self.attention_mask, is_causal=False + ) + encoded = encoded.view( + states.size(0), self.num_blocks, self.state_tokens + self.action_tokens, -1 + ) + return self.output_projection(encoded[:, :, : self.state_tokens]) + + +def masked_world_l1( + predictor: BlockCausalWorldPredictor, + actions: Tensor, + future_states: Optional[Tensor], + valid: Optional[Tensor], +) -> Tuple[Tensor, int]: + """Globally-normalized L1 over valid samples only. + + Different distributed ranks may receive different numbers of valid targets + (shift-augmented samples are masked out). If at least one rank has a valid + future target, every rank must include the predictor in its autograd graph, + so ranks without a valid target execute a zero-weight dummy forward. This + keeps DeepSpeed/DDP gradient collectives aligned across ranks. When the + global batch contains no valid target the predictor is skipped entirely. + """ + + local_count = ( + int(valid.to(dtype=torch.long).sum().item()) + if future_states is not None and valid is not None + else 0 + ) + distributed = torch.distributed.is_available() and torch.distributed.is_initialized() + global_count_tensor = actions.new_tensor(local_count, dtype=torch.long) + if distributed: + torch.distributed.all_reduce( + global_count_tensor, op=torch.distributed.ReduceOp.SUM + ) + global_count = int(global_count_tensor.item()) + if global_count == 0: + return actions.new_zeros(()), 0 + + world_size = torch.distributed.get_world_size() if distributed else 1 + num_blocks = predictor.num_blocks + state_tokens = predictor.state_tokens + target_dim = predictor.state_projection.in_features + if future_states is not None and ( + future_states.ndim != 4 + or tuple(future_states.shape[1:]) + != (num_blocks + 1, state_tokens, target_dim) + ): + raise ValueError( + f"future_states must have shape [B,{num_blocks + 1},{state_tokens},{target_dim}], " + f"got {tuple(future_states.shape)}" + ) + if future_states is None: + predictor_states = actions.new_zeros( + (actions.size(0), num_blocks + 1, state_tokens, target_dim) + ) + local_valid = torch.zeros(actions.size(0), dtype=torch.bool, device=actions.device) + else: + predictor_states = future_states.detach() + local_valid = ( + valid.to(device=actions.device, dtype=torch.bool) + if valid is not None + else torch.zeros(actions.size(0), dtype=torch.bool, device=actions.device) + ) + + # Always use the full local microbatch. A rank-local selected subset gives + # DeepSpeed Stage 2 a different predictor execution shape on each rank and + # can stall reduction even when the same parameters are present. + predictions = predictor(predictor_states[:, :num_blocks], actions) + targets = predictor_states[:, 1:] + selected_predictions = predictions[local_valid] + selected_targets = targets[local_valid] + # DDP averages gradients across ranks. This scale makes that result equal + # to a mean over every valid element in the global batch, even when the + # rank-local valid counts differ. + error_sum = (selected_predictions - selected_targets.to(selected_predictions.dtype)).abs().float().sum() + elements_per_sample = targets[0].numel() + loss = error_sum * (float(world_size) / (global_count * elements_per_sample)) + return loss, global_count + + +def masked_world_l1_diagnostics( + predictor: BlockCausalWorldPredictor, + actions: Tensor, + future_states: Optional[Tensor], + valid: Optional[Tensor], +) -> Tuple[dict, int]: + """Validation-only correct/shuffled/reversed target comparison.""" + + if future_states is None or valid is None or not bool(valid.any()): + zero = actions.new_zeros(()) + return {"correct": zero, "shuffled": zero, "reversed": zero}, 0 + selected_actions = actions[valid] + selected_states = future_states[valid].detach() + predictions = predictor(selected_states[:, : predictor.num_blocks], selected_actions) + targets = selected_states[:, 1:].to(predictions.dtype) + if targets.size(0) > 1: + shuffled = targets.roll(1, dims=0) + else: + shuffled = targets.roll(1, dims=2) + losses = { + "correct": F.l1_loss(predictions, targets, reduction="mean"), + "shuffled": F.l1_loss(predictions, shuffled, reduction="mean"), + "reversed": F.l1_loss(predictions, targets.flip(1), reduction="mean"), + } + return losses, int(valid.sum().item()) diff --git a/original_scores.txt b/original_scores.txt new file mode 100644 index 0000000000000000000000000000000000000000..bf51aaf5b0ccf20c8fdca4b737e694d88cf14026 --- /dev/null +++ b/original_scores.txt @@ -0,0 +1,8 @@ +# Original closed-loop result on the source machine. +# Full per-route JSON files are intentionally not packed. + +eval_name: qwen3vl_2b_video_dream_consdrive_v2_gating_jump_thr010_s08_seed_42_tmux +checkpoint: outputs/qwen3vl_2b_video_dream_consdrive_seed_42/2026-08-09_13-10-02/checkpoints/last.ckpt +driving score: 91.32802589545453 +success rate: 0.7772727272727272 +eval num: 220 diff --git a/requirements-pim.txt b/requirements-pim.txt new file mode 100644 index 0000000000000000000000000000000000000000..d5e4d7a7e025e01fd22fd758469a3ce6c6d374bc --- /dev/null +++ b/requirements-pim.txt @@ -0,0 +1,23 @@ +# Separate environment from the legacy Qwen3-VL baseline. Python 3.10-3.12. +torch==2.6.0 +torchvision==0.21.0 +transformers==4.48.3 +peft==0.13.2 +timm==1.0.15 +pytorch-lightning==2.5.0 +torchmetrics==1.6.1 +hydra-core==1.3.2 +numpy==1.26.4 +opencv-python-headless==4.11.0.86 +imgaug==0.4.0 +ujson +line-profiler +scipy +Pillow +sentencepiece +einops +shortuuid +filterpy +pytest +# Install official ml-fastvlm dependencies as needed (see docs/PIM.md). +# CARLA 0.9.15 Python wheel must match your Python/OS; not installed here. diff --git a/scripts/analysis/ability_benchmark.py b/scripts/analysis/ability_benchmark.py new file mode 100644 index 0000000000000000000000000000000000000000..27203211e26be7a0852b0734b0380e42547cc52e --- /dev/null +++ b/scripts/analysis/ability_benchmark.py @@ -0,0 +1,178 @@ +"""Bench2Drive tools/ability_benchmark.py, connecting to an already running CARLA server (route planner built once per town).""" +import json +import carla +import argparse +import xml.etree.ElementTree as ET +from agents.navigation.global_route_planner import GlobalRoutePlanner +import os +import atexit +import subprocess +import time +import random + +Ability = { + "Overtaking":['Accident', 'AccidentTwoWays', 'ConstructionObstacle', 'ConstructionObstacleTwoWays', 'HazardAtSideLaneTwoWays', 'HazardAtSideLane', 'ParkedObstacleTwoWays', 'ParkedObstacle', 'VehicleOpensDoorTwoWays'], + "Merging": ['CrossingBicycleFlow', 'EnterActorFlow', 'HighwayExit', 'InterurbanActorFlow', 'HighwayCutIn', 'InterurbanAdvancedActorFlow', 'MergerIntoSlowTrafficV2', 'MergerIntoSlowTraffic', 'NonSignalizedJunctionLeftTurn', 'NonSignalizedJunctionRightTurn', 'NonSignalizedJunctionLeftTurnEnterFlow', 'ParkingExit', 'SequentialLaneChange', 'SignalizedJunctionLeftTurn', 'SignalizedJunctionRightTurn', 'SignalizedJunctionLeftTurnEnterFlow'], + "Emergency_Brake": ['BlockedIntersection', 'DynamicObjectCrossing', 'HardBreakRoute', 'OppositeVehicleTakingPriority', 'OppositeVehicleRunningRedLight', 'ParkingCutIn', 'PedestrianCrossing', 'ParkingCrossingPedestrian', 'StaticCutIn', 'VehicleTurningRoute', 'VehicleTurningRoutePedestrian', 'ControlLoss'], + "Give_Way": ['InvadingTurn', 'YieldToEmergencyVehicle'], + "Traffic_Signs": ['BlockedIntersection', 'OppositeVehicleTakingPriority', 'OppositeVehicleRunningRedLight', 'PedestrianCrossing', 'VehicleTurningRoute', 'VehicleTurningRoutePedestrian', 'EnterActorFlow', 'CrossingBicycleFlow', 'NonSignalizedJunctionLeftTurn', 'NonSignalizedJunctionRightTurn', 'NonSignalizedJunctionLeftTurnEnterFlow', 'OppositeVehicleTakingPriority', 'OppositeVehicleRunningRedLight', 'PedestrianCrossing', 'SignalizedJunctionLeftTurn', 'SignalizedJunctionRightTurn', 'SignalizedJunctionLeftTurnEnterFlow', 'T_Junction', 'VanillaNonSignalizedTurn', 'VanillaSignalizedTurnEncounterGreenLight', 'VanillaSignalizedTurnEncounterRedLight', 'VanillaNonSignalizedTurnEncounterStopsign', 'VehicleTurningRoute', 'VehicleTurningRoutePedestrian'] +} + +def get_infraction_status(record): + for infraction, value in record['infractions'].items(): + if infraction == "min_speed_infractions": + continue + elif len(value) > 0: + return True + return False + +def update_Ability(scenario_name, Ability_Statistic, status): + for ability, scenarios in Ability.items(): + if scenario_name in scenarios: + Ability_Statistic[ability][1] += 1 + if status: + Ability_Statistic[ability][0] += 1 + pass + +def update_Success(scenario_name, Success_Statistic, status): + if scenario_name not in Success_Statistic: + if status: + Success_Statistic[scenario_name] = [1, 1] + else: + Success_Statistic[scenario_name] = [0, 1] + else: + Success_Statistic[scenario_name][1] += 1 + if status: + Success_Statistic[scenario_name][0] += 1 + pass + +def get_position(xml_route): + waypoints_elem = xml_route.find('waypoints') + keypoints = waypoints_elem.findall('position') + return [carla.Location(float(pos.get('x')), float(pos.get('y')), float(pos.get('z'))) for pos in keypoints] + +def get_route_result(records, route_id): + for record in records: + record_route_id = record['route_id'].split('_')[1] + if route_id == record_route_id: + return record + return None + +def get_waypoint_route(locs, grp): + route = [] + for i in range(len(locs) - 1): + loc = locs[i] + loc_next = locs[i + 1] + interpolated_trace = grp.trace_route(loc, loc_next) + for wp, _ in interpolated_trace: + route.append(wp) + return route + +def main(args): + routes_file = args.file + result_file = args.result_file + Ability_Statistic = {} + crash_route_list = [] + for key in Ability: + Ability_Statistic[key] = [0, 0.] + Success_Statistic = {} + + with open(result_file, 'r') as f: + data = json.load(f) + records = data["_checkpoint"]["records"] + + tree = ET.parse(routes_file) + root = tree.getroot() + routes = root.findall('route') + sorted_routes = sorted(routes, key=lambda x: x.get('town')) + + client = carla.Client(args.host, args.port) + client.set_timeout(300) + + current_town = sorted_routes[0].get('town') + world = client.load_world(current_town) + carla_map = world.get_map() + grp = GlobalRoutePlanner(carla_map, 1.0) + for route in sorted_routes: + scenarios = route.find('scenarios') + scenario_name = scenarios.find('scenario').get("type") + route_id = route.get('id') + route_record = get_route_result(records, route_id) + if route_record is None: + crash_route_list.append((scenario_name, route_id)) + print('No result record of route', route_id, "in the result file") + continue + if route_record["status"] == 'Completed' or route_record["status"] == "Perfect": + if get_infraction_status(route_record): + record_success_status = False + else: + record_success_status = True + else: + record_success_status = False + update_Ability(scenario_name, Ability_Statistic, record_success_status) + update_Success(scenario_name, Success_Statistic, record_success_status) + # if scenario_name in Ability["Traffic_Signs"] and (scenario_name in Ability["Merging"] or scenario_name in Ability["Emergency_Brake"]): + # Only these three 'Ability's intersect + if scenario_name in Ability["Traffic_Signs"]: + # Only these three 'Ability's intersect + if route.get('town') != current_town: + current_town = route.get('town') + print("Loading the town:", current_town) + world = client.load_world(current_town) + print("successfully load the town:", current_town) + grp = GlobalRoutePlanner(world.get_map(), 1.0) + location_list = get_position(route) + waypoint_route = get_waypoint_route(location_list, grp) + count = 0 + for wp in waypoint_route: + count += 1 + if wp.is_junction: + break + if not wp.is_junction: + raise RuntimeError("This route does not contain any junction-waypoint!") + # +8 to ensure the ego pass the trigger volume + junction_completion = float(count+8) / float(len(waypoint_route)) + record_completion = route_record["scores"]["score_route"] / 100.0 + stop_infraction = route_record["infractions"]["stop_infraction"] + red_light_infraction = route_record["infractions"]["red_light"] + if record_completion > junction_completion and not stop_infraction and not red_light_infraction: + Ability_Statistic['Traffic_Signs'][0] += 1 + Ability_Statistic['Traffic_Signs'][1] += 1 + else: + Ability_Statistic['Traffic_Signs'][1] += 1 + else: + pass + + Ability_Res = {} + for ability, statis in Ability_Statistic.items(): + Ability_Res[ability] = float(statis[0])/float(statis[1]) + + for key, value in Ability_Res.items(): + print(key, ": ", value) + + Ability_Res['mean'] = sum(list(Ability_Res.values())) / 5 + Ability_Res['crashed'] = crash_route_list + with open(os.path.splitext(result_file)[0] + "_ability.json", 'w') as file: + json.dump(Ability_Res, file, indent=4) + + Success_Res = {} + Route_num = 0 + Succ_Route_num = 0 + for scenario, statis in Success_Statistic.items(): + Success_Res[scenario] = float(statis[0])/float(statis[1]) + Succ_Route_num += statis[0] + Route_num += statis[1] + assert len(crash_route_list) == 220 - float(Route_num) + print(f"Mean:{Ability_Res['mean']}") + print(f'Crashed Route num: {len(crash_route_list)}, Crashed Route ID: {crash_route_list}') + print('Finished!') + +if __name__=='__main__': + argparser = argparse.ArgumentParser(description=__doc__) + argparser.add_argument('-f', '--file', nargs=None, default="leaderboard/data/bench2drive220.xml", help='route file') + argparser.add_argument('-r', '--result_file', nargs=None, default="", help='result json file') + argparser.add_argument('-t', '--host', default='localhost', help='IP of the host server (default: localhost)') + argparser.add_argument('-p', '--port', type=int, default=2000, help='carla rpc port') + args = argparser.parse_args() + main(args) + \ No newline at end of file diff --git a/scripts/analysis/cf_batch.py b/scripts/analysis/cf_batch.py new file mode 100644 index 0000000000000000000000000000000000000000..cb6df52df60ca2d72c3bae393c1de93d0d5ad5e2 --- /dev/null +++ b/scripts/analysis/cf_batch.py @@ -0,0 +1,66 @@ +"""Run the creep counterfactual for every collision in a failure report. + +S1 (memoryless creep after a standstill): applies when the ego departed from a standstill <= 30 m before +the impact; simulate from the departure point at rest. +S2 (memory-gated creep): applies when the other actor had been inside the FOV during the last 15 s but was +out of view 1.5 s before impact; simulate from 20 m (arc length) before impact at the recorded speed. + +Usage: python cf_batch.py report.json NPZ_DIR extents.json out.json +""" +import json +import sys +from pathlib import Path + +import numpy as np + +from cf_creep import bystander_index, simulate + + +def start_20m_before(hero, t_c, dist=20.0): + seg = hero[hero[:, 0] <= t_c] + d = np.concatenate([[0], np.cumsum(np.hypot(np.diff(seg[::-1, 1]), np.diff(seg[::-1, 2])))]) + k = np.searchsorted(d, dist) + k = min(k, len(seg) - 1) + row = seg[::-1][k] + return float(row[0]), float(row[4]) + + +def main(): + report, npz_dir, extents, out = sys.argv[1:5] + report = json.load(open(report)) + extents = json.load(open(extents)) + results = [] + for e in report: + if e["success"] or not isinstance(e.get("collisions"), list): + continue + d = np.load(Path(npz_dir) / f"RouteScenario_{e['route']}_rep0.npz") + others = d["others"] + for c in e["collisions"]: + oid = c.get("other_id") + if oid is None or c["class"] == "static object / layout" or not np.any(others[:, 1] == oid): + continue + ext = extents.get(c["other_type"], (2.4, 1.0)) + bys = bystander_index(d, oid, extents) + row = {"route": e["route"], "scenario": e["scenario"], "t": c["t"], "other": c["other_type"], + "class": c["class"]} + try: + row["replay_actual"] = simulate(d, c["t"], oid, ext, c["t"] - 8.0, 0.0, replay_actual=True)["outcome"] + except Exception as ex: + row["replay_actual"] = f"error {ex!r}" + dep = c.get("departed_from_stop_s_before") + if dep is not None and c.get("dist_since_departure", 99) <= 30 and not c.get("stop_is_route_start", False): + t0 = c["t"] - dep + row["S1"] = {f"tau{tau}": simulate(d, c["t"], oid, ext, t0, 0.0, v_cap=3.0, tau=tau, bystanders=bys) + for tau in (0.5, 1.0, None)} + fov = c.get("in_fov_at", {}) + if c.get("fov_time_last15s", 0) > 0 and not fov.get("-1.5s", True): + t0, v0 = start_20m_before(d["hero"], c["t"]) + row["S2"] = {f"tau{tau}": simulate(d, c["t"], oid, ext, t0, v0, v_cap=3.0, tau=tau, bystanders=bys) + for tau in (0.5, 1.0, None)} + results.append(row) + json.dump(results, open(out, "w"), indent=1, default=float) + print(f"{len(results)} collisions simulated -> {out}") + + +if __name__ == "__main__": + main() diff --git a/scripts/analysis/cf_creep.py b/scripts/analysis/cf_creep.py new file mode 100644 index 0000000000000000000000000000000000000000..89d4c29ea4f9eb83b59102293f98469714b7dc1f --- /dev/null +++ b/scripts/analysis/cf_creep.py @@ -0,0 +1,288 @@ +"""Counterfactual 'visibility-aware creep' replay for a single recorded collision. + +The ego follows its recorded path geometry but with a new speed profile: from the start point it creeps at +<= v_cap and, being memoryless, starts braking `tau` seconds after any corner of the other actor's box enters +the 110 deg front-camera FOV. The other actor replays its recorded trajectory (constant-velocity +extrapolation after the real impact). If it was at rest and started moving after the start point, its +launch is re-timed to the moment the simulated ego reaches the position the real ego had at launch +(scenario actors are triggered by ego proximity). +""" +import json +import math + +import numpy as np + +from failure_report import CAM_BACK, EGO_EXTENT, HALF_FOV, corners, interp_state + +DT = 0.02 + + +def _axes(c): + return [(c[1][0] - c[0][0], c[1][1] - c[0][1]), (c[2][0] - c[0][0], c[2][1] - c[0][1])] + + +def boxes_overlap(a, b): + for axis in _axes(a) + _axes(b): + pa = [p[0] * axis[0] + p[1] * axis[1] for p in a] + pb = [p[0] * axis[0] + p[1] * axis[1] for p in b] + if max(pa) < min(pb) or max(pb) < min(pa): + return False + return True + + +def box(x, y, yaw, ext): + # corners() order: (-x,-y), (-x,+y), (+x,-y), (+x,+y) -> reorder to a polygon for SAT axes + c = corners(x, y, yaw, ext) + return [c[0], c[1], c[3], c[2]] + + +def visible(ego, oth, ext): + ex, ey, eyaw = ego + c, s = math.cos(math.radians(eyaw)), math.sin(math.radians(eyaw)) + cx, cy = ex - CAM_BACK * c, ey - CAM_BACK * s + for px, py in corners(*oth, ext): + lx = (px - cx) * c + (py - cy) * s + ly = -(px - cx) * s + (py - cy) * c + if lx > 0 and abs(math.atan2(ly, lx)) < HALF_FOV: + return True + return False + + +class Path: + def __init__(self, hero, t0, t1, extend=15.0): + seg = hero[(hero[:, 0] >= t0) & (hero[:, 0] <= t1)] + pts = [seg[0]] + for r in seg[1:]: + if math.hypot(r[1] - pts[-1][1], r[2] - pts[-1][2]) > 0.05: + pts.append(r) + pts = np.array(pts) + yaw = math.radians(pts[-1][3]) + ext = np.array([[0, pts[-1][1] + k * math.cos(yaw), pts[-1][2] + k * math.sin(yaw), pts[-1][3], 0] + for k in np.arange(0.5, extend, 0.5)]) + self.p = np.vstack([pts, ext]) if len(ext) else pts + d = np.hypot(np.diff(self.p[:, 1]), np.diff(self.p[:, 2])) + self.s = np.concatenate([[0], np.cumsum(d)]) + self.s_impact = self.s[len(pts) - 1] + self.t_of_s = (pts[:, 0], self.s[: len(pts)]) + + def pose(self, s): + s = float(np.clip(s, 0, self.s[-1])) + x = np.interp(s, self.s, self.p[:, 1]) + y = np.interp(s, self.s, self.p[:, 2]) + yaw = np.degrees(np.unwrap(np.radians(self.p[:, 3]))) + return x, y, float(np.interp(s, self.s, yaw)) + + def s_at_time(self, t): + return float(np.interp(t, *self.t_of_s)) + + +def other_pose_fn(tr, t_c): + pre = tr[tr[:, 0] <= t_c - 0.1] + last, prev = pre[-1], pre[max(0, len(pre) - 6)] + dt = max(last[0] - prev[0], 1e-3) + vx, vy = (last[1] - prev[1]) / dt, (last[2] - prev[2]) / dt + + def f(t): + if t <= last[0]: + return interp_state(pre, max(t, pre[0, 0])) + return last[1] + vx * (t - last[0]), last[2] + vy * (t - last[0]), last[3] + + return f, last[0] + + +def bystander_index(d, other_id, extents): + """Map 0.1 s time keys -> list of (box params) for every recorded actor except the collision partner.""" + actors = json.loads(str(d["actors"])) + idx = {} + for t, aid, x, y, yaw in d["others"]: + if aid == other_id: + continue + ext = extents.get(actors.get(str(int(aid)), ""), (2.4, 1.0)) + idx.setdefault(int(round(t * 10)), []).append((int(aid), x, y, yaw, ext)) + return idx + + +def simulate(d, t_c, other_id, ext_other, t_start, v0, v_cap=3.0, a_acc=2.0, a_brake=6.0, tau=0.5, + replay_actual=False, horizon=15.0, bystanders=None): + """tau=None means a blind creep (never brakes); `bystanders` from bystander_index() adds overlap + checks against all other recorded actors (replayed on the original clock).""" + hero = d["hero"] + others = d["others"] + tr = others[others[:, 1] == other_id][:, [0, 2, 3, 4]] + path = Path(hero, t_start, t_c) + opose, t_last = other_pose_fn(tr, t_c) + # Detect a triggered launch: at rest at t_start, moving later. + spd = np.hypot(np.diff(tr[:, 1]), np.diff(tr[:, 2])) / np.maximum(np.diff(tr[:, 0]), 1e-3) + moving = np.where((tr[1:, 0] > t_start) & (spd > 0.5))[0] + at_rest_start = len(tr) > 1 and tr[0, 0] <= t_start and np.all(spd[(tr[1:, 0] <= t_start) & (tr[1:, 0] > t_start - 1.0)] < 0.3) + t_launch = float(tr[moving[0] + 1, 0]) if (len(moving) and at_rest_start) else None + s_launch = path.s_at_time(t_launch) if t_launch is not None else None + + s, v, t = 0.0, v0, 0.0 + t_trig, t_seen, braking = None, None, False + first_seen = None + min_gap = None + while t < horizon: + if replay_actual: + s = path.s_at_time(t_start + t) if t_start + t <= t_c else path.s_impact + ego = path.pose(s) + if t_launch is not None: + if t_trig is None and s >= s_launch: + t_trig = t + t_o = t_launch + (t - t_trig) if t_trig is not None else t_launch - 1e-3 + else: + t_o = t_start + t + oth = opose(t_o) + if t_seen is None and visible(ego, oth, ext_other): + t_seen = t + first_seen = t if first_seen is None else first_seen + ego_box = box(*ego, EGO_EXTENT) + if boxes_overlap(ego_box, box(*oth, ext_other)): + return {"outcome": "collision", "triggered": t_launch is not None, "t": round(t, 2), "t_seen": first_seen, "s": round(s, 1), + "s_impact": round(path.s_impact, 1)} + if bystanders is not None and t_start + t < t_c + 3.0: + for aid, bx, by, byaw, bext in bystanders.get(int(round((t_start + t) * 10)), []): + if abs(bx - ego[0]) < 8 and abs(by - ego[1]) < 8 and boxes_overlap(ego_box, box(bx, by, byaw, bext)): + return {"outcome": "collision_with_other", "triggered": t_launch is not None, "other_id": aid, "t": round(t, 2), + "t_seen": first_seen} + gap = math.hypot(ego[0] - oth[0], ego[1] - oth[1]) + min_gap = gap if min_gap is None else min(min_gap, gap) + # Done once the other actor's motion has run past the extrapolation window, or we cleared the impact point. + if t_o > t_last + 5.0 or (s > path.s_impact + 8.0): + return {"outcome": "safe", "triggered": t_launch is not None, "t_seen": first_seen, "min_centre_gap": round(min_gap, 1)} + if not replay_actual: + if tau is not None and t_seen is not None and t >= t_seen + tau: + braking = True + if braking: + v = max(0.0, v - a_brake * DT) + # Resume once the other actor is no longer visible and has moved away. + if v == 0.0 and gap > 12.0 and not visible(ego, oth, ext_other): + braking, t_seen = False, None + elif v > v_cap: + v = max(v_cap, v - 3.0 * DT) + else: + v = min(v_cap, v + a_acc * DT) + s += v * DT + t += DT + return {"outcome": "timeout", "min_centre_gap": round(min_gap or -1, 1)} + + +def _bystander_tracks(d, other_id, extents): + actors = json.loads(str(d["actors"])) + others = d["others"] + tracks = {} + for aid in np.unique(others[:, 1]): + if aid == other_id: + continue + tr = others[others[:, 1] == aid][:, [0, 2, 3, 4]] + tracks[int(aid)] = (tr, extents.get(actors.get(str(int(aid)), ""), (2.4, 1.0))) + return tracks + + +def _track_pose(tr, t): + if t < tr[0, 0] or t > tr[-1, 0]: + return None + return interp_state(tr, t) + + +def simulate_reactive(d, t_c, other_id, ext_other, t_start, v0, extents, v_cap=3.0, a_acc=2.0, a_brake=6.0, + tau=0.5, t_pred=3.0, horizon=40.0, v_release=None, release_after=(4.0, 1.0)): + """Creep at <= v_cap and yield to every actor currently in the front-camera FOV whose constant-velocity + prediction (from its last 0.5 s of motion, no future knowledge) overlaps the ego's creep path within + t_pred seconds. Braking/resuming acts on the threat state from `tau` seconds earlier. Bystanders are + replayed on the recorded clock until the recording ends; the partner is extrapolated beyond that. + Note flow actors switch to reactive driving after any crash, so post-impact bystander motion is optimistic. + v_release: once the ego has crept release_after[0] m and seen no threat for release_after[1] s, the cap + is raised to v_release (threat checks stay active).""" + hero, others = d["hero"], d["others"] + tr = others[others[:, 1] == other_id][:, [0, 2, 3, 4]] + path = Path(hero, t_start, t_c) + opose, t_last = other_pose_fn(tr, t_c) + spd = np.hypot(np.diff(tr[:, 1]), np.diff(tr[:, 2])) / np.maximum(np.diff(tr[:, 0]), 1e-3) + moving = np.where((tr[1:, 0] > t_start) & (spd > 0.5))[0] + at_rest_start = len(tr) > 1 and tr[0, 0] <= t_start and np.all(spd[(tr[1:, 0] <= t_start) & (tr[1:, 0] > t_start - 1.0)] < 0.3) + t_launch = float(tr[moving[0] + 1, 0]) if (len(moving) and at_rest_start) else None + s_launch = path.s_at_time(t_launch) if t_launch is not None else None + tracks = _bystander_tracks(d, other_id, extents) + rec_end = float(hero[-1, 0]) + ego_ext = (EGO_EXTENT[0] + 0.5, EGO_EXTENT[1] + 0.3) + + s, v, t = 0.0, v0, 0.0 + cap = v_cap + t_trig = None + threat_hist = [] # (t, threat) + braking = False + first_threat, n_threat_actors = None, set() + while t < horizon: + ego = path.pose(s) + if t_launch is not None: + if t_trig is None and s >= s_launch: + t_trig = t + t_o = t_launch + (t - t_trig) if t_trig is not None else t_launch - 1e-3 + partner = lambda tt: opose(t_launch + (tt - t_trig) if t_trig is not None else t_launch - 1e-3) + else: + t_o = t_start + t + partner = lambda tt: opose(t_start + tt) + oth = opose(t_o) + ego_box = box(*ego, EGO_EXTENT) + if boxes_overlap(ego_box, box(*oth, ext_other)): + return {"outcome": "collision", "triggered": t_launch is not None, "t": round(t, 2), "s": round(s, 1), + "s_impact": round(path.s_impact, 1), "first_threat": first_threat} + tw = t_start + t + live = [] + for aid, (btr, bext) in (tracks.items() if tw <= rec_end else ()): + p = _track_pose(btr, tw) + if p is None or abs(p[0] - ego[0]) > 40 or abs(p[1] - ego[1]) > 40: + continue + live.append((aid, p, btr, bext)) + if abs(p[0] - ego[0]) < 8 and abs(p[1] - ego[1]) < 8 and boxes_overlap(ego_box, box(*p, bext)): + return {"outcome": "collision_with_other", "triggered": t_launch is not None, "with_id": aid, + "t": round(t, 2), "first_threat": first_threat} + info = {"triggered": t_launch is not None, "first_threat": first_threat, "t": round(t, 2), + "threat_actors": sorted(map(str, n_threat_actors)), "s": round(s, 1), "s_impact": round(path.s_impact, 1)} + if s > path.s_impact + 8.0: + return {"outcome": "passed" if tw <= rec_end else "passed_after_recording", **info} + if tw > rec_end and t_o > t_last + 5.0: + # Partner extrapolated well past the impact; recorded traffic ended without a conflict. + return {"outcome": "partner_avoided", **info} + + if int(round(t / DT)) % 5 == 0: + cand = [("partner", oth, partner(t - 0.5), ext_other)] + for aid, p, btr, bext in live: + q = _track_pose(btr, tw - 0.5) + cand.append((aid, p, q if q is not None else p, bext)) + threat = False + v_plan = max(v, cap) + for aid, p, q, ext in cand: + if not visible(ego, p, ext): + continue + vx, vy = (p[0] - q[0]) / 0.5, (p[1] - q[1]) / 0.5 + for k in np.arange(0.0, t_pred + 1e-6, 0.2): + ek = path.pose(s + v_plan * k) + if abs(p[0] + vx * k - ek[0]) > 10 or abs(p[1] + vy * k - ek[1]) > 10: + continue + if boxes_overlap(box(*ek, ego_ext), box(p[0] + vx * k, p[1] + vy * k, p[2], ext)): + threat = True + n_threat_actors.add(aid) + break + if threat: + break + if threat and first_threat is None: + first_threat = round(t, 2) + threat_hist.append((t, threat)) + delayed = [th for tt, th in threat_hist if tt <= t - (tau or 0.0)] + braking = bool(delayed[-1]) if delayed else False + if v_release is not None and cap == v_cap and s >= release_after[0]: + recent = [th for tt, th in threat_hist if tt >= t - release_after[1]] + if len(recent) >= int(release_after[1] / 0.1) and not any(recent): + cap = v_release + if braking: + v = max(0.0, v - a_brake * DT) + elif v > cap: + v = max(cap, v - 3.0 * DT) + else: + v = min(cap, v + a_acc * DT) + s += v * DT + t += DT + return {"outcome": "stuck", "first_threat": first_threat, "s": round(s, 1), "s_impact": round(path.s_impact, 1), + "threat_actors": sorted(map(str, n_threat_actors))} diff --git a/scripts/analysis/cf_reactive.py b/scripts/analysis/cf_reactive.py new file mode 100644 index 0000000000000000000000000000000000000000..ab95b83685b280a56fa1d459e48e8a2e8858e866 --- /dev/null +++ b/scripts/analysis/cf_reactive.py @@ -0,0 +1,50 @@ +"""Multi-actor reactive creep counterfactual for every collision in a failure report. + +S1 (memoryless creep after a junction standstill, not the route-start standstill): start at rest at the +departure point. S2 (memory-gated creep): start 20 m before impact at the recorded speed, applicable when +the partner had been seen during the last 15 s but was out of view 1.5 s before impact. + +Usage: python cf_reactive.py report.json NPZ_DIR extents.json out.json +""" +import json +import sys +from pathlib import Path + +import numpy as np + +from cf_batch import start_20m_before +from cf_creep import simulate_reactive + +GRID = [(3.0, 0.5), (3.0, 1.0), (2.0, 0.5), (2.0, 1.0)] + + +def main(): + report, npz_dir, extents, out = sys.argv[1:5] + report = json.load(open(report)) + extents = json.load(open(extents)) + results = [] + for e in report: + if e["success"] or not isinstance(e.get("collisions"), list): + continue + d = np.load(Path(npz_dir) / f"RouteScenario_{e['route']}_rep0.npz") + for c in e["collisions"]: + oid = c.get("other_id") + if oid is None or c["class"] == "static object / layout" or not np.any(d["others"][:, 1] == oid): + continue + ext = extents.get(c["other_type"], (2.4, 1.0)) + row = {"route": e["route"], "t": c["t"], "other_id": oid} + dep = c.get("departed_from_stop_s_before") + if dep is not None and c.get("dist_since_departure", 99) <= 30 and not c.get("stop_is_route_start", False): + row["S1"] = {f"v{v}_tau{tau}": simulate_reactive(d, c["t"], oid, ext, c["t"] - dep, 0.0, extents, v_cap=v, tau=tau) + for v, tau in GRID} + if c.get("fov_time_last15s", 0) > 0 and not c.get("in_fov_at", {}).get("-1.5s", True): + t0, v0 = start_20m_before(d["hero"], c["t"]) + row["S2"] = {f"v{v}_tau{tau}": simulate_reactive(d, c["t"], oid, ext, t0, v0, extents, v_cap=v, tau=tau) + for v, tau in GRID} + results.append(row) + json.dump(results, open(out, "w"), indent=1, default=float) + print(f"{len(results)} collisions -> {out}") + + +if __name__ == "__main__": + main() diff --git a/scripts/analysis/compare_reproduction.py b/scripts/analysis/compare_reproduction.py new file mode 100644 index 0000000000000000000000000000000000000000..664ddbdc83a587421e30ae56595f1dea5e41afc5 --- /dev/null +++ b/scripts/analysis/compare_reproduction.py @@ -0,0 +1,162 @@ +"""Original runs vs a reproduction (scripts/reproduce_pipeline.sh) of the best configuration. + +python scripts/analysis/compare_reproduction.py --tag repro1 (writes eval_results/Bench2Drive/reproduction_.txt) + +Training level: final validation loss of stage1 / speeddrop / tracker_sp and the last validation of the +detectors. Closed loop: Bench2Drive-220 driving score of the final model (sp_v1 detector at 4 Hz, no speed +mask) against the five original runs. The DS difference is judged against the simulator noise measured on the +original repeats (single-run sd ~0.6 DS on the fixed 220 routes): "within noise" when +|mean_repro - mean_orig| <= 1.96 * sqrt(sd^2/n_repro + sd^2/n_orig). Unfinished stages show as pending. +""" +import argparse +import csv +import json +import math +import re +from pathlib import Path + +import numpy as np + +B = Path("eval_results/Bench2Drive") +SINGLE_RUN_SD = 0.62 # per-route variance across the original repeats, routes fixed + +ORIG_TRAIN = {"stage1": "outputs/fastvlm_stage1/2026-10-31_14-19-40", + "speeddrop": "outputs/fastvlm_stage3_speeddrop/2026-11-02_06-08-03", + "tracker_sp": "outputs/fastvlm_stage3_tracker_sp/2026-11-03_16-38-38"} +ORIG_DET = {"det_v1": "outputs/detector/det_v1", "sp_v1": "outputs/stream_petr/sp_v1", + "sp_fold0": "outputs/stream_petr/sp_fold0of2", "sp_fold1": "outputs/stream_petr/sp_fold1of2"} +ORIG_EVALS = ["sp_ft_det4hz_nomask", "sp_ft_det4hz_nomask_repeat", "sp_ft_det4hz_nomask_run3", + "sp_ft_det4hz_nomask_run4", "sp_ft_det4hz_nomask_run5"] + + +def repro_paths(tag): + train = {"stage1": f"outputs/fastvlm_stage1/{tag}", "speeddrop": f"outputs/fastvlm_stage3_speeddrop/{tag}", + "tracker_sp": f"outputs/fastvlm_stage3_tracker_sp/{tag}"} + det = {"det_v1": f"outputs/detector/det_v1_{tag}", "sp_v1": f"outputs/stream_petr/sp_v1_{tag}", + "sp_fold0": f"outputs/stream_petr/sp_fold0of2_{tag}", "sp_fold1": f"outputs/stream_petr/sp_fold1of2_{tag}"} + evals = sorted(p.name for p in B.glob(f"{tag}_sp_ft_nomask_r*") if (p / "merged.json").exists()) + return train, det, evals + + +def final_val_loss(train_dir): + """Last val/loss, route and speed-waypoint losses from Lightning's metrics.csv.""" + p = Path(train_dir) / "logs" / "metrics.csv" + if not p.exists(): + return None + rows = [r for r in csv.DictReader(open(p)) if r.get("val/loss")] + if not rows: + return None + r = rows[-1] + return {k.split("/")[-1]: float(r[k]) for k in ("val/loss", "val_losses/route_loss", "val_losses/speed_wps_loss") if r.get(k)} + + +def train_hours(train_dir): + p = Path(train_dir) / "train.log" + if not p.exists(): + return None + # tqdm prints MM:SS under one hour and H:MM:SS above, and re-renders the bar many times near 100 %: + # take the largest elapsed time seen per epoch. + per_epoch = {} + for ep, a, b, c in re.findall(r"Epoch (\d+): 100%\|[^|]*\| \d+/\d+ \[(\d+):(\d+)(?::(\d+))?<", p.read_text(errors="ignore")): + secs = int(a) * 3600 + int(b) * 60 + int(c) if c else int(a) * 60 + int(b) + per_epoch[ep] = max(per_epoch.get(ep, 0), secs) + return sum(per_epoch.values()) / 3600 if per_epoch else None + + +def detector_val(det_dir): + vals = sorted(Path(det_dir).glob("val_*.json")) + if not vals: + return None + d = json.load(open(vals[-1])) + out = {"step": int(vals[-1].stem.split("_")[1]), "fp@0.3": d["fp_per_frame"].get("0.3")} + for cls in ("car", "walker"): + for rng in ("0-10", "20-30", "40-50"): + if rng in d.get(cls, {}): + out[f"{cls}_recall_{rng}"] = d[cls][rng].get("recall_pos") + for k, v in d.get("car_velocity_by_speed", {}).items(): + out[f"vel_med_{k}"] = v.get("vel_err_med") + return out + + +def fmt_metrics(d): + if d is None: + return "pending" + return " ".join(f"{k}={v:.3f}" if isinstance(v, float) else f"{k}={v}" for k, v in d.items() if v is not None) + + +def load_eval(name): + return {r["route_id"]: r for r in json.load(open(B / name / "merged.json"))["_checkpoint"]["records"]} + + +def success(r): + return r["status"] in ("Completed", "Perfect") and all( + len(v) == 0 for k, v in r["infractions"].items() if k != "min_speed_infractions") + + +def summarize(names): + runs = [load_eval(n) for n in names] + return dict(runs=runs, + ds=[np.mean([r["scores"]["score_composed"] for r in run.values()]) for run in runs], + sr=[100 * np.mean([success(r) for r in run.values()]) for run in runs], + col=[sum(len(r["infractions"].get("collisions_vehicle", [])) for r in run.values()) for run in runs], + stops=[sum(len(r["infractions"].get("scenario_timeouts", [])) + len(r["infractions"].get("route_timeout", [])) + for r in run.values()) for run in runs]) + + +def route_means(summary): + keys = sorted(summary["runs"][0]) + return keys, np.array([[run[k]["scores"]["score_composed"] for k in keys] for run in summary["runs"]]).mean(0) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--tag", default="repro1") + args = ap.parse_args() + rtrain, rdet, revals = repro_paths(args.tag) + L = [f"# Reproduction '{args.tag}' vs original runs (best configuration: speed-dropout stage 3 fine-tuned on " + "StreamPETR tracker banks, sp_v1 detector at 4 Hz, no speed mask)"] + + L += ["", "## Training: final validation loss (Lightning metrics.csv) and wall time", + f"{'stage':12s} {'':6s} {'val/loss':>9s} {'route':>8s} {'speed_wps':>10s} {'hours':>6s}"] + for stage in ("stage1", "speeddrop", "tracker_sp"): + for lab, d in (("orig", ORIG_TRAIN[stage]), ("repro", rtrain[stage])): + v, h = final_val_loss(d), train_hours(d) + if v is None: + L.append(f"{stage:12s} {lab:6s} {'pending':>9s}") + else: + L.append(f"{stage:12s} {lab:6s} {v.get('loss', float('nan')):9.4f} {v.get('route_loss', float('nan')):8.4f} " + f"{v.get('speed_wps_loss', float('nan')):10.4f} {h if h is not None else float('nan'):6.2f}") + + L += ["", "## Detectors: last validation (sp_*: frames with memory; recall = recall_pos; velocity error median, m/s)"] + for name in ("det_v1", "sp_v1", "sp_fold0", "sp_fold1"): + for lab, d in (("orig", ORIG_DET[name]), ("repro", rdet[name])): + L.append(f"{name:10s} {lab:6s} {fmt_metrics(detector_val(d))}") + + L += ["", f"## Closed loop, Bench2Drive-220 (single-run sd {SINGLE_RUN_SD} DS)", + f"{'':6s} {'n':>2s} {'DS per run':>36s} {'mean':>6s} {'SR':>6s} {'veh.col':>8s} {'timeouts':>9s}"] + o = summarize(ORIG_EVALS) + L.append(f"{'orig':6s} {len(ORIG_EVALS):2d} {' / '.join(f'{x:.2f}' for x in o['ds']):>36s} {np.mean(o['ds']):6.2f} " + f"{np.mean(o['sr']):6.2f} {np.mean(o['col']):8.1f} {np.mean(o['stops']):9.1f}") + if not revals: + L.append(f"{'repro':6s} 0 {'pending':>36s}") + else: + r = summarize(revals) + diff = np.mean(r["ds"]) - np.mean(o["ds"]) + band = 1.96 * SINGLE_RUN_SD * math.sqrt(1 / len(revals) + 1 / len(ORIG_EVALS)) + verdict = "within noise" if abs(diff) <= band else ("BETTER than original" if diff > 0 else "WORSE than original") + L.append(f"{'repro':6s} {len(revals):2d} {' / '.join(f'{x:.2f}' for x in r['ds']):>36s} {np.mean(r['ds']):6.2f} " + f"{np.mean(r['sr']):6.2f} {np.mean(r['col']):8.1f} {np.mean(r['stops']):9.1f}") + L.append(f"repro - orig = {diff:+.2f} DS, 95% noise band +/-{band:.2f} -> {verdict}") + keys, om = route_means(o) + _, rm = route_means(r) + big = np.argsort(-np.abs(rm - om))[:6] + L.append(f"per-route mean |diff| {np.mean(np.abs(rm - om)):.2f}; routes differing by >= 20 DS: {int((np.abs(rm - om) >= 20).sum())}; " + "largest: " + ", ".join(f"{keys[i].replace('RouteScenario_', '').replace('_rep0', '')} {rm[i] - om[i]:+.0f}" for i in big)) + + text = "\n".join(L) + print(text) + (B / f"reproduction_{args.tag}.txt").write_text(text + "\n") + + +if __name__ == "__main__": + main() diff --git a/scripts/analysis/compare_runs.py b/scripts/analysis/compare_runs.py new file mode 100644 index 0000000000000000000000000000000000000000..c5e34ae32c48b430a95f461b31ad270ad259ea9b --- /dev/null +++ b/scripts/analysis/compare_runs.py @@ -0,0 +1,111 @@ +"""Compare two Bench2Drive full-220 runs through their failure_report.py outputs. + +Every failed route gets one primary cause: the earliest collision (by its class and front-camera warning +time) or, without collisions, its non-collision infractions. Driving-score loss is (100 - route score) / 220. + +Usage: python compare_runs.py NAME_A REPORT_A NAME_B REPORT_B [--out OUT.json] +""" +import argparse +import collections +import json + +IGNORED = {"route_dev", "min_speed_infractions"} +VIS_LIMIT_S = 1.5 +LEAD = {"ego hits stationary vehicle", "ego hits vehicle ahead (same direction)"} + + +def primary_cause(e): + infr = sorted(k for k, v in e["infractions"].items() if v and k not in IGNORED) + colls = e["collisions"] if isinstance(e.get("collisions"), list) else [] + if colls: + c = min(colls, key=lambda c: c["t"]) + if c["class"] == "pedestrian": + return "pedestrian", c + if c["class"] == "static object / layout": + return "static object / layout", c + if c["class"] == "rear-ended by other": + return "rear threat", c + if c.get("warning_s", 99) < VIS_LIMIT_S: + return "visibility-limited (<1.5 s in FOV)", c + if c["class"] in LEAD: + return "lead / stationary vehicle", c + return "visible, not yielded (" + c["class"] + ")", c + if any(k.startswith("collisions") for k in infr): + return "collision without recorder match", None + if infr: + return "non-collision: " + "/".join(infr), None + if e["status"] != "Completed": + return "status: " + e["status"], None + return "deviation / min speed only", None + + +def summarize(report): + out = {} + for e in report: + cause, c = (None, None) if e["success"] else primary_cause(e) + out[e["route"]] = {"scenario": e["scenario"], "town": e["town"], "score": e["score"], "success": e["success"], + "status": e["status"], "cause": cause, + "first_collision": None if c is None else + {k: c.get(k) for k in ("t", "class", "other_type", "warning_s", "ego_speed", "other_speed")}} + return out + + +def group(cause): + if cause is None: + return None + return "visible, not yielded" if cause.startswith("visible, not yielded") else \ + "non-collision" if cause.startswith("non-collision") else cause + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("name_a"); ap.add_argument("report_a"); ap.add_argument("name_b"); ap.add_argument("report_b") + ap.add_argument("--out") + args = ap.parse_args() + A, B = (summarize(json.load(open(p))) for p in (args.report_a, args.report_b)) + na, nb = args.name_a, args.name_b + assert A.keys() == B.keys() + n = len(A) + + print(f"{'':28s}{na:>14s}{nb:>14s}") + for label, f in (("driving score", lambda S: sum(v["score"] for v in S.values()) / n), + ("success rate %", lambda S: 100 * sum(v["success"] for v in S.values()) / n), + ("DS loss on failed routes", lambda S: sum(100 - v["score"] for v in S.values() if not v["success"]) / n), + ("DS loss on successes", lambda S: sum(100 - v["score"] for v in S.values() if v["success"]) / n)): + print(f"{label:28s}{f(A):14.2f}{f(B):14.2f}") + + print("\nprimary cause of failure: count (DS loss)") + ca, cb = collections.Counter(), collections.Counter() + la, lb = collections.Counter(), collections.Counter() + for S, c, l in ((A, ca, la), (B, cb, lb)): + for v in S.values(): + if not v["success"]: + g = group(v["cause"]); c[g] += 1; l[g] += (100 - v["score"]) / n + for g in sorted(set(ca) | set(cb), key=lambda g: -(la[g] + lb[g])): + print(f" {g:38s}{ca[g]:4d} ({la[g]:5.2f}){cb[g]:6d} ({lb[g]:5.2f})") + + fa = {r for r, v in A.items() if not v["success"]} + fb = {r for r, v in B.items() if not v["success"]} + print(f"\nfailed in both: {len(fa & fb)} only {na}: {len(fa - fb)} only {nb}: {len(fb - fa)}") + for title, rs in ((f"newly failing in {na} (succeeded in {nb})", fa - fb), (f"fixed in {na} (failed in {nb})", fb - fa)): + print(f"\n{title}:") + for r in sorted(rs, key=lambda r: A[r]["scenario"]): + print(f" {r:>6s} {A[r]['scenario']:38s} {na}: {A[r]['score']:5.1f} {group(A[r]['cause']) or 'success'}" + f" {nb}: {B[r]['score']:5.1f} {group(B[r]['cause']) or 'success'}") + both_same = sum(group(A[r]["cause"]) == group(B[r]["cause"]) for r in fa & fb) + print(f"\nfailed in both with the same primary cause: {both_same}/{len(fa & fb)}") + + print("\nper scenario success (only scenarios that differ):") + sa, sb, tot = collections.Counter(), collections.Counter(), collections.Counter() + for r in A: + s = A[r]["scenario"]; tot[s] += 1; sa[s] += A[r]["success"]; sb[s] += B[r]["success"] + for s in sorted(tot, key=lambda s: sa[s] - sb[s]): + if sa[s] != sb[s]: + print(f" {s:42s}{sa[s]:3d}/{tot[s]:<3d}{sb[s]:6d}/{tot[s]:<3d}{sa[s] - sb[s]:+4d}") + + if args.out: + json.dump({na: A, nb: B}, open(args.out, "w"), indent=1) + + +if __name__ == "__main__": + main() diff --git a/scripts/analysis/compare_speed_mask.py b/scripts/analysis/compare_speed_mask.py new file mode 100644 index 0000000000000000000000000000000000000000..99453d7df255bafebe16ff5072524d715d43783a --- /dev/null +++ b/scripts/analysis/compare_speed_mask.py @@ -0,0 +1,140 @@ +"""Speed mask (SPEED_MASK_STALL_S=15) vs no mask on the StreamPETR stage-3 model, from repeated 220-route evals. + +python scripts/analysis/compare_speed_mask.py (run from the repo root; writes eval_results/Bench2Drive/speed_mask_summary.txt) + +Fixed-benchmark CIs treat the 220 routes as fixed and use only simulator noise: the variance of a run's DS is +estimated from the per-route variance across repeats (routes are simulated independently). Routes where the +mask never fired in any mask15 run ran identical inputs in both arms and serve as an A/A control. +""" +import glob +import json +import math +import re +from collections import Counter +from pathlib import Path + +import numpy as np + +B = Path("eval_results/Bench2Drive") +NOMASK = ["sp_ft_det4hz_nomask", "sp_ft_det4hz_nomask_repeat", "sp_ft_det4hz_nomask_run3", + "sp_ft_det4hz_nomask_run4", "sp_ft_det4hz_nomask_run5"] +MASK15 = ["sp_ft_det4hz_mask15", "sp_ft_det4hz_mask15_repeat", "sp_ft_det4hz_mask15_run3", + "sp_ft_det4hz_mask15_run4", "sp_ft_det4hz_mask15_run5"] +ORACLE = ["fastvlm_stage3_oracle_2026-11-01_07-40-56", "stage3_oracle_repeat_clean"] +DETV1 = ["tracker_ft_det4hz_mask15", "tracker_ft_det4hz_mask15_repeat"] +OBSTACLE = ("Construction", "StaticCutIn", "Accident", "HazardAtSideLane", "ParkedObstacle", "VehicleOpensDoor", + "MergerIntoSlowTraffic", "ParkingExit", "InvadingTurn") +INFRACTIONS = ["collisions_vehicle", "collisions_layout", "red_light", "stop_infraction", "route_dev", + "route_timeout", "scenario_timeouts", "outside_route_lanes"] + + +def route_key(route_id): + return route_id.replace("RouteScenario_", "").replace("_rep0", "") + + +def load(path): + return {route_key(r["route_id"]): r for r in json.load(open(path))["_checkpoint"]["records"]} + + +def success(r): + return r["status"] in ("Completed", "Perfect") and all( + len(v) == 0 for k, v in r["infractions"].items() if k != "min_speed_infractions") + + +def masked_steps(run): + steps = {} + for f in glob.glob(str(B / run / "logs" / "w*.log")): + route = None + for line in open(f, errors="ignore"): + m = re.search(r"Preparing RouteScenario_(\d+)", line) + if m: + route = m.group(1) + m = re.search(r"Speed-masked steps: (\d+)", line) + if m and route: + steps[route] = int(m.group(1)) + return steps + + +R = {n: load(B / n / "merged.json") for n in NOMASK + MASK15 + ORACLE + DETV1} +R["stage1"] = load("/tmp/s1_view/merged.json") +keys = sorted(R[NOMASK[0]], key=int) +scenario = {e["route"]: e["scenario"] for e in json.load(open(B / ORACLE[0] / "analysis" / "report.json"))} +X = {name: np.array([[R[n][k]["scores"]["score_composed"] for k in keys] for n in runs]) + for name, runs in (("nomask", NOMASK), ("mask15", MASK15), ("oracle", ORACLE), ("detv1", DETV1), + ("stage1", ["stage1"]))} +X["sp_all10"] = np.vstack([X["nomask"], X["mask15"]]) +lines = ["# Speed mask after 15 s standstill vs no mask; StreamPETR stage-3 fine-tune " + "(outputs/fastvlm_stage3_tracker_sp/2026-11-03_16-38-38), sp_v1 detector at 4 Hz, 5 x 220 routes per arm.", + f"{'run':28s} {'DS':>6s} {'SR':>6s} " + " ".join( + f"{k.replace('collisions_', 'col_')[:9]:>9s}" for k in INFRACTIONS) + " game_s timed_out"] +for n in NOMASK + MASK15: + recs = R[n].values() + tot = {k: sum(len(r["infractions"].get(k, [])) for r in recs) for k in INFRACTIONS} + lines.append(f"{n.replace('sp_ft_det4hz_', ''):28s} {np.mean([r['scores']['score_composed'] for r in recs]):6.2f} " + f"{sum(map(success, recs)) / 2.2:6.2f} " + " ".join(f"{tot[k]:9d}" for k in INFRACTIONS) + + f" {np.mean([r['meta']['duration_game'] for r in recs]):6.1f}" + + f" {sum(r['status'] == 'Failed - Agent timed out' for r in recs):9d}") + +single_sd = {n: math.sqrt(a.var(0, ddof=1).sum()) / 220 for n, a in X.items() if len(a) > 1} +single_sd["stage1"] = single_sd["sp_all10"] +lines += ["", "arm runs mean DS sd(run means) single-run sd from per-route variance"] +for n in ("nomask", "mask15", "sp_all10", "oracle", "detv1"): + rm = X[n].mean(1) + lines.append(f"{n:10s} {len(rm):5d} {rm.mean():8.2f} {rm.std(ddof=1):14.2f} {single_sd[n]:10.2f}") + + +def fixed(a, b): + m = X[a].mean() - X[b].mean() + se = math.sqrt(single_sd[a] ** 2 / len(X[a]) + single_sd[b] ** 2 / len(X[b])) + lines.append(f"{a:9s} - {b:7s} {m:+.2f} fixed-benchmark 95% CI [{m - 1.96 * se:+.2f},{m + 1.96 * se:+.2f}]") + + +lines.append("") +for a, b in (("mask15", "nomask"), ("sp_all10", "oracle"), ("sp_all10", "detv1"), ("sp_all10", "stage1"), + ("oracle", "detv1")): + fixed(a, b) + +steps = {n: masked_steps(n) for n in MASK15} +fired = {k for n in MASK15 for k, v in steps[n].items() if v > 0} +lines += ["", f"mask fired on {[sum(v > 0 for v in steps[n].values()) for n in MASK15]} routes per run " + f"({len(fired)} distinct); masked time per run " + f"{[round(sum(steps[n].values()) / 20) for n in MASK15]} s"] +diff = X["mask15"].mean(0) - X["nomask"].mean(0) +groups = {"A/A (never fired)": [i for i, k in enumerate(keys) if k not in fired], + "fired: junction / yield": [i for i, k in enumerate(keys) + if k in fired and not any(s in scenario[k] for s in OBSTACLE)], + "fired: obstacle bypass": [i for i, k in enumerate(keys) + if k in fired and any(s in scenario[k] for s in OBSTACLE)]} +rng = np.random.default_rng(0) +for name, ix in groups.items(): + a, b = X["mask15"][:, ix], X["nomask"][:, ix] + se = math.sqrt(a.var(0, ddof=1).sum() / len(a) + b.var(0, ddof=1).sum() / len(b)) / 220 + both = np.vstack([a, b]) + obs = abs(a.mean() - b.mean()) + perm = [abs(both[p[:5]].mean() - both[p[5:]].mean()) >= obs - 1e-9 + for p in (rng.permutation(10) for _ in range(20000))] + lines.append(f"{name:24s} n={len(ix):3d} nomask {b.mean():5.1f} mask15 {a.mean():5.1f} DS contribution " + f"{diff[ix].sum() / 220:+.2f} +/- {1.96 * se:.2f} run-label permutation p={np.mean(perm):.3f}") + +lines += ["", "routes with the largest mean difference (mask15 - nomask), scores per run:"] +order = np.argsort(diff) +for i in list(order[:8]) + list(order[-8:][::-1]): + k = keys[i] + lines.append(f" {k:>6} {scenario[k][:36]:36s} {diff[i]:+6.1f} nomask {X['nomask'][:, i].round().astype(int).tolist()}" + f" mask15 {X['mask15'][:, i].round().astype(int).tolist()}" + f" masked_s {[round(steps[n].get(k, 0) / 20) for n in MASK15]}") + +lines += ["", "per-scenario success over 5 runs (differences >= 3):"] +count = Counter() +for k in keys: + s = scenario[k] + count[s, "n"] += sum(success(R[n][k]) for n in NOMASK) + count[s, "m"] += sum(success(R[n][k]) for n in MASK15) + count[s, "r"] += 5 +for s in sorted({s for s, _ in count}, key=lambda s: count[s, "m"] - count[s, "n"]): + if abs(count[s, "m"] - count[s, "n"]) >= 3: + lines.append(f" {s:42s} nomask {count[s, 'n']:2d}/{count[s, 'r']} mask15 {count[s, 'm']:2d}/{count[s, 'r']}") + +text = "\n".join(lines) +print(text) +(B / "speed_mask_summary.txt").write_text(text + "\n") diff --git a/scripts/analysis/compare_stream_petr.py b/scripts/analysis/compare_stream_petr.py new file mode 100644 index 0000000000000000000000000000000000000000..acefc67910dbeb7eaab5b2507c2472cf0200dbf3 --- /dev/null +++ b/scripts/analysis/compare_stream_petr.py @@ -0,0 +1,99 @@ +"""Closed-loop comparison of the StreamPETR perception arms against det_v1 and the oracle (220 routes each). + +python scripts/analysis/compare_stream_petr.py (run from the repo root; writes eval_results/Bench2Drive/stream_petr_summary.txt) +""" +import json +import math +import statistics +from pathlib import Path + +from scipy import stats + +B = Path("eval_results/Bench2Drive") + + +def load(p): + return {r["route_id"]: r for r in json.load(open(p))["_checkpoint"]["records"]} + + +runs = { + "stage1": "/tmp/s1_view/merged.json", + "oracle_full": B / "fastvlm_stage3_oracle_2026-11-01_07-40-56/merged.json", + "oracle_repeat": B / "stage3_oracle_repeat_clean/merged.json", + "speeddrop_mask15 (oracle bank)": B / "speeddrop_mask15/merged.json", + "detv1_ft (coast2)": B / "tracker_ft_det4hz_mask15/merged.json", + "detv1_ft_repeat": B / "tracker_ft_det4hz_mask15_repeat/merged.json", + "sp_ft_mask15": B / "sp_ft_det4hz_mask15/merged.json", + "sp_ft_mask15_repeat": B / "sp_ft_det4hz_mask15_repeat/merged.json", + "detv1_ft + sp detector (zero-shot)": B / "tracker_ft_spdet4hz_mask15_zeroshot/merged.json", + "sp_ft_nomask": B / "sp_ft_det4hz_nomask/merged.json", + "sp_ft_nomask_repeat": B / "sp_ft_det4hz_nomask_repeat/merged.json", + "sp_ft_nomask_run3": B / "sp_ft_det4hz_nomask_run3/merged.json", + "sp_ft_nomask_run4": B / "sp_ft_det4hz_nomask_run4/merged.json", + "sp_ft_nomask_run5": B / "sp_ft_det4hz_nomask_run5/merged.json", + "sp_ft_mask15_run3": B / "sp_ft_det4hz_mask15_run3/merged.json", + "sp_ft_mask15_run4": B / "sp_ft_det4hz_mask15_run4/merged.json", + "sp_ft_mask15_run5": B / "sp_ft_det4hz_mask15_run5/merged.json", + "nodrop_sp_ft_nomask": B / "nodrop_sp_ft_det4hz_nomask_clean/merged.json", +} +MASK15 = ["sp_ft_mask15", "sp_ft_mask15_repeat", "sp_ft_mask15_run3", "sp_ft_mask15_run4", "sp_ft_mask15_run5"] +NOMASK = ["sp_ft_nomask", "sp_ft_nomask_repeat", "sp_ft_nomask_run3", "sp_ft_nomask_run4", "sp_ft_nomask_run5"] +R = {k: load(v) for k, v in runs.items()} +a, b = R["oracle_full"], R["oracle_repeat"] +ref = {k: (a[k]["scores"]["score_composed"] + b[k]["scores"]["score_composed"]) / 2 for k in a} +keys = ["collisions_vehicle", "collisions_pedestrian", "collisions_layout", "red_light", "stop_infraction", "route_dev", + "route_timeout", "scenario_timeouts", "vehicle_blocked"] +lines = ["# StreamPETR perception (sp_v1, 4 Hz, Kalman tracker coast 2 s) vs det_v1; stage 3 fine-tuned on cross-fitted " + "tracker banks. DS differences are paired against the mean of the two oracle runs (Wilcoxon, zsplit).", + f"{'run':36s} {'DS':>6s} {'SR':>6s} {'vs oracle':>18s} {'p':>6s} " + + " ".join(f"{k.replace('collisions_', 'col_').replace('_infractions', '')[:9]:>9s}" for k in keys) + " game_s"] + + +def sr(recs): + return sum(r["status"] in ("Completed", "Perfect") and all(len(v) == 0 for k2, v in r["infractions"].items() + if k2 != "min_speed_infractions") for r in recs.values()) / 220 * 100 + + +for n, recs in R.items(): + ds = [recs[k]["scores"]["score_composed"] for k in ref] + d = [recs[k]["scores"]["score_composed"] - ref[k] for k in ref] + m, se = statistics.mean(d), statistics.stdev(d) / math.sqrt(len(d)) + p = stats.wilcoxon(ds, [ref[k] for k in ref], zero_method="zsplit").pvalue + tot = {k: sum(len(r["infractions"].get(k, [])) for r in recs.values()) for k in keys} + gt = statistics.mean(r["meta"]["duration_game"] for r in recs.values()) + lines.append(f"{n:36s} {statistics.mean(ds):6.2f} {sr(recs):6.2f} {m:+6.2f} [{m - 1.96 * se:+5.2f},{m + 1.96 * se:+5.2f}] " + f"{p:6.3f} " + " ".join(f"{tot[k]:9d}" for k in keys) + f" {gt:6.1f}") +lines.append("") + + +def pooled(*names): + return {k: statistics.mean(R[n][k]["scores"]["score_composed"] for n in names) for k in ref} + + +def diff(nm, x, y): + d = [x[k] - y[k] for k in ref] + m, se = statistics.mean(d), statistics.stdev(d) / math.sqrt(len(d)) + p = stats.wilcoxon([x[k] for k in ref], [y[k] for k in ref], zero_method="zsplit").pvalue + lines.append(f"{nm:44s} {m:+.2f} [{m - 1.96 * se:+.2f},{m + 1.96 * se:+.2f}] p={p:.3f}") + + +P = dict(sp=pooled(*MASK15), detv1=pooled("detv1_ft (coast2)", "detv1_ft_repeat"), + oracle=ref, stage1=pooled("stage1"), zs=pooled("detv1_ft + sp detector (zero-shot)"), + nomask=pooled(*NOMASK), nodrop=pooled("nodrop_sp_ft_nomask"), + sdrop=pooled("speeddrop_mask15 (oracle bank)"), sp10=pooled(*MASK15, *NOMASK)) +for nm, x in (("sp_ft_mask15 x5", P["sp"]), ("detv1_ft x2", P["detv1"]), ("sp_ft_nomask x5", P["nomask"]), + ("sp_ft all 10 (mask15 x5 + nomask x5)", P["sp10"])): + lines.append(f"{nm}: mean DS {statistics.mean(x.values()):.2f}") +lines.append("route-paired Wilcoxon below (routes as the sampling unit); fixed-benchmark CIs: compare_speed_mask.py") +diff("sp_ft_mask15 x5 - oracle x2", P["sp"], P["oracle"]) +diff("sp_ft_mask15 x5 - detv1_ft x2", P["sp"], P["detv1"]) +diff("sp_ft_mask15 x5 - speeddrop_mask15 (oracle bank)", P["sp"], P["sdrop"]) +diff("detv1_ft + sp detector zero-shot - sp_ft_mask15 x5", P["zs"], P["sp"]) +diff("sp_ft_nomask x5 - sp_ft_mask15 x5", P["nomask"], P["sp"]) +diff("sp_ft all 10 - oracle x2", P["sp10"], P["oracle"]) +diff("sp_ft all 10 - detv1_ft x2", P["sp10"], P["detv1"]) +diff("sp_ft all 10 - stage1", P["sp10"], P["stage1"]) +diff("nodrop_sp_ft_nomask - sp_ft all 10", P["nodrop"], P["sp10"]) +text = "\n".join(lines) +print(text) +(B / "stream_petr_summary.txt").write_text(text + "\n") diff --git a/scripts/analysis/compare_tracker_finetune.py b/scripts/analysis/compare_tracker_finetune.py new file mode 100644 index 0000000000000000000000000000000000000000..ef9d8d4d969cb9d52595ffdc4912bf447833353f --- /dev/null +++ b/scripts/analysis/compare_tracker_finetune.py @@ -0,0 +1,44 @@ +import json, statistics, math +from scipy import stats +def load(p): return {r["route_id"]: r for r in json.load(open(p))["_checkpoint"]["records"]} +runs = { + "stage1": "/tmp/s1_view/merged.json", + "oracle_full": "fastvlm_stage3_oracle_2026-11-01_07-40-56/merged.json", + "oracle_repeat": "stage3_oracle_repeat_clean/merged.json", + "speeddrop_mask15 (oracle)": "speeddrop_mask15/merged.json", + "det_zeroshot_20hz (oracle ckpt)": "detector_zeroshot_v1/merged.json", + "speeddrop_zeroshot_det4hz": "speeddrop_det4hz_mask15_zeroshot/merged.json", + "ft_coast2": "tracker_ft_det4hz_mask15/merged.json", + "ft_coast2_repeat": "tracker_ft_det4hz_mask15_repeat/merged.json", + "ft_coast1": "tracker_ft_coast1_det4hz_mask15/merged.json", + "ft_coast1_repeat": "tracker_ft_coast1_det4hz_mask15_repeat/merged.json", + "ft_coast4": "tracker_ft_coast4_det4hz_mask15/merged.json", + "ft_coast4_repeat": "tracker_ft_coast4_det4hz_mask15_repeat/merged.json", +} +R = {k: load(v) for k, v in runs.items()} +a, b = R["oracle_full"], R["oracle_repeat"] +ref = {k: (a[k]["scores"]["score_composed"] + b[k]["scores"]["score_composed"]) / 2 for k in a} +keys = ["collisions_vehicle", "collisions_pedestrian", "collisions_layout", "red_light", "stop_infraction", "route_dev", "route_timeout", "scenario_timeouts", "vehicle_blocked"] +print(f"{'run':34s} {'DS':>6s} {'SR':>6s} {'vs oracle':>18s} {'p':>6s} " + " ".join(f"{k.replace('collisions_','col_').replace('_infractions','')[:9]:>9s}" for k in keys) + " game_s") +for n, recs in R.items(): + ds = [recs[k]["scores"]["score_composed"] for k in ref] + d = [recs[k]["scores"]["score_composed"] - ref[k] for k in ref] + m, se = statistics.mean(d), statistics.stdev(d) / math.sqrt(len(d)) + p = stats.wilcoxon(ds, [ref[k] for k in ref], zero_method="zsplit").pvalue + sr = sum(r["status"] in ("Completed", "Perfect") and all(len(v) == 0 for k2, v in r["infractions"].items() if k2 != "min_speed_infractions") for r in recs.values()) / 220 * 100 + tot = {k: sum(len(r["infractions"].get(k, [])) for r in recs.values()) for k in keys} + gt = statistics.mean(r["meta"]["duration_game"] for r in recs.values()) + print(f"{n:34s} {statistics.mean(ds):6.2f} {sr:6.2f} {m:+6.2f} [{m-1.96*se:+5.2f},{m+1.96*se:+5.2f}] {p:6.3f} " + " ".join(f"{tot[k]:9d}" for k in keys) + f" {gt:6.1f}") +print() +pooled = {} +for name, pair in (("coast1", ("ft_coast1", "ft_coast1_repeat")), ("coast2", ("ft_coast2", "ft_coast2_repeat")), ("coast4", ("ft_coast4", "ft_coast4_repeat"))): + x = {k: (R[pair[0]][k]["scores"]["score_composed"] + R[pair[1]][k]["scores"]["score_composed"]) / 2 for k in ref} + pooled[name] = x + d = [x[k] - ref[k] for k in ref] + m, se = statistics.mean(d), statistics.stdev(d) / math.sqrt(len(d)) + p = stats.wilcoxon([x[k] for k in ref], [ref[k] for k in ref], zero_method="zsplit").pvalue + col = sum(len(R[q][k]["infractions"]["collisions_vehicle"]) for q in pair for k in ref) / 2 + print(f"{name} x2 mean DS {statistics.mean(x.values()):6.2f} vs oracle mean {m:+.2f} [{m-1.96*se:+.2f},{m+1.96*se:+.2f}] p={p:.3f} vehicle collisions/run {col:.1f}") +for nm, x, y in (("coast1 - coast2", pooled["coast1"], pooled["coast2"]), ("coast4 - coast2", pooled["coast4"], pooled["coast2"]), ("coast2 - stage1", pooled["coast2"], {k: R["stage1"][k]["scores"]["score_composed"] for k in ref})): + d = [x[k] - y[k] for k in ref]; m, se = statistics.mean(d), statistics.stdev(d) / math.sqrt(len(d)) + print(f"{nm}: {m:+.2f} [{m-1.96*se:+.2f},{m+1.96*se:+.2f}] p={stats.wilcoxon([x[k] for k in ref], [y[k] for k in ref], zero_method='zsplit').pvalue:.3f}") diff --git a/scripts/analysis/compare_tracker_offline.py b/scripts/analysis/compare_tracker_offline.py new file mode 100644 index 0000000000000000000000000000000000000000..745fbd03b031e8c80995382fd04b6c1a3754e46f --- /dev/null +++ b/scripts/analysis/compare_tracker_offline.py @@ -0,0 +1,31 @@ +"""Side-by-side offline tracker metrics (scripts/eval_tracker_offline.py) of several detector runs. + +python scripts/analysis/compare_tracker_offline.py eval_results/tracker_offline/det_v1_val eval_results/tracker_offline/sp_v1_val +""" +import json +import sys +from pathlib import Path + +runs = [(Path(p).name, json.load(open(Path(p) / "tracker_metrics.json"))) for p in sys.argv[1:]] +names = [n for n, _ in runs] +w = max(12, max(len(n) for n in names) + 2) +print(f"{'':28s}" + "".join(f"{n:>{w}s}" for n in names)) +print(f"{'frames':28s}" + "".join(f"{d['frames']:>{w}d}" for _, d in runs)) +print(f"{'false tracks / s':28s}" + "".join(f"{d['false_tracks_per_s']:>{w}.3f}" for _, d in runs)) +print(f"{'id switches / 100 matches':28s}" + "".join(f"{d['id_switches_per_100_matches']:>{w}.2f}" for _, d in runs)) +for cls in ("car", "walker", "static"): + for key in ("recall_visible", "pos_err_med", "vel_err_med"): + for rb in ("0-10", "10-20", "20-30", "30-40", "40-50"): + vals = [d[cls][rb].get(key) for _, d in runs] + if all(v is None for v in vals): + continue + print(f"{cls + ' ' + key + ' ' + rb:28s}" + "".join(f"{v:>{w}.3f}" if v is not None else f"{'-':>{w}s}" + for v in vals)) +for sb in ("0-0.5", "0.5-5", "5-10", "10-20"): + for key in ("vel_err_med", "vel_err_rms"): + vals = [d["car_velocity_by_speed"].get(sb, {}).get(key) for _, d in runs] + print(f"{'car ' + sb + ' m/s ' + key:28s}" + "".join(f"{v:>{w}.3f}" if v is not None else f"{'-':>{w}s}" + for v in vals)) + tgt = runs[0][1]["car_velocity_by_speed"].get(sb, {}).get("target_sigma") + if tgt is not None: + print(f"{' (target sigma)':28s}{tgt:>{w}.3f}") diff --git a/scripts/analysis/extents.json b/scripts/analysis/extents.json new file mode 100644 index 0000000000000000000000000000000000000000..83c6f78d1fd681e2527be33ee20c0aa39ffee64d --- /dev/null +++ b/scripts/analysis/extents.json @@ -0,0 +1,370 @@ +{ +"vehicle.audi.a2": [ +1.853, +0.894 +], +"vehicle.citroen.c3": [ +1.994, +0.925 +], +"vehicle.chevrolet.impala": [ +2.679, +1.017 +], +"vehicle.dodge.charger_police_2020": [ +2.619, +0.965 +], +"vehicle.micro.microlino": [ +1.104, +0.74 +], +"vehicle.dodge.charger_police": [ +2.487, +1.019 +], +"vehicle.audi.tt": [ +2.091, +0.997 +], +"vehicle.jeep.wrangler_rubicon": [ +1.933, +0.953 +], +"vehicle.mercedes.coupe": [ +2.513, +1.076 +], +"vehicle.yamaha.yzf": [ +1.095, +0.433 +], +"vehicle.mercedes.coupe_2020": [ +2.337, +0.906 +], +"vehicle.harley-davidson.low_rider": [ +1.175, +0.383 +], +"vehicle.dodge.charger_2020": [ +2.504, +0.941 +], +"vehicle.ford.ambulance": [ +3.183, +1.176 +], +"vehicle.lincoln.mkz_2020": [ +2.446, +0.918 +], +"vehicle.mini.cooper_s_2021": [ +2.276, +1.049 +], +"vehicle.ford.crown": [ +2.683, +0.9 +], +"vehicle.toyota.prius": [ +2.257, +1.003 +], +"vehicle.carlamotors.european_hgv": [ +3.968, +1.446 +], +"vehicle.carlamotors.carlacola": [ +2.602, +1.313 +], +"vehicle.vespa.zx125": [ +0.909, +0.433 +], +"vehicle.nissan.patrol_2021": [ +2.783, +1.075 +], +"vehicle.mercedes.sprinter": [ +2.958, +0.994 +], +"vehicle.audi.etron": [ +2.428, +1.016 +], +"vehicle.seat.leon": [ +2.096, +0.908 +], +"vehicle.volkswagen.t2_2021": [ +2.221, +0.887 +], +"vehicle.tesla.cybertruck": [ +3.137, +1.195 +], +"vehicle.lincoln.mkz_2017": [ +2.451, +1.064 +], +"vehicle.carlamotors.firetruck": [ +4.234, +1.446 +], +"vehicle.ford.mustang": [ +2.359, +0.947 +], +"vehicle.volkswagen.t2": [ +2.24, +1.035 +], +"vehicle.mitsubishi.fusorosa": [ +5.136, +1.972 +], +"vehicle.tesla.model3": [ +2.396, +1.082 +], +"vehicle.diamondback.century": [ +0.828, +0.291 +], +"vehicle.gazelle.omafiets": [ +0.922, +0.33 +], +"vehicle.bmw.grandtourer": [ +2.306, +1.121 +], +"vehicle.bh.crossbike": [ +0.755, +0.433 +], +"vehicle.kawasaki.ninja": [ +1.022, +0.398 +], +"vehicle.nissan.patrol": [ +2.302, +0.966 +], +"vehicle.nissan.micra": [ +1.817, +0.923 +], +"vehicle.mini.cooper_s": [ +1.903, +0.985 +], +"walker.pedestrian.0013": [ +0.188, +0.188 +], +"walker.pedestrian.0027": [ +0.25, +0.25 +], +"walker.pedestrian.0008": [ +0.25, +0.25 +], +"walker.pedestrian.0006": [ +0.25, +0.25 +], +"walker.pedestrian.0035": [ +0.25, +0.25 +], +"walker.pedestrian.0001": [ +0.25, +0.25 +], +"walker.pedestrian.0002": [ +0.25, +0.25 +], +"walker.pedestrian.0004": [ +0.25, +0.25 +], +"walker.pedestrian.0011": [ +0.25, +0.25 +], +"walker.pedestrian.0037": [ +0.25, +0.25 +], +"walker.pedestrian.0005": [ +0.25, +0.25 +], +"walker.pedestrian.0009": [ +0.25, +0.25 +], +"walker.pedestrian.0010": [ +0.25, +0.25 +], +"walker.pedestrian.0026": [ +0.25, +0.25 +], +"walker.pedestrian.0014": [ +0.25, +0.25 +], +"walker.pedestrian.0045": [ +0.25, +0.25 +], +"walker.pedestrian.0015": [ +0.25, +0.25 +], +"walker.pedestrian.0016": [ +0.25, +0.25 +], +"walker.pedestrian.0038": [ +0.25, +0.25 +], +"walker.pedestrian.0041": [ +0.25, +0.25 +], +"walker.pedestrian.0043": [ +0.25, +0.25 +], +"walker.pedestrian.0042": [ +0.25, +0.25 +], +"walker.pedestrian.0044": [ +0.25, +0.25 +], +"walker.pedestrian.0020": [ +0.25, +0.25 +], +"walker.pedestrian.0039": [ +0.25, +0.25 +], +"walker.pedestrian.0022": [ +0.25, +0.25 +], +"walker.pedestrian.0046": [ +0.25, +0.25 +], +"walker.pedestrian.0017": [ +0.25, +0.25 +], +"walker.pedestrian.0034": [ +0.25, +0.25 +], +"walker.pedestrian.0040": [ +0.25, +0.25 +], +"walker.pedestrian.0003": [ +0.25, +0.25 +], +"walker.pedestrian.0051": [ +0.25, +0.25 +], +"walker.pedestrian.0047": [ +0.25, +0.25 +], +"walker.pedestrian.0048": [ +0.25, +0.25 +], +"walker.pedestrian.0049": [ +0.25, +0.25 +], +"walker.pedestrian.0050": [ +0.25, +0.25 +], +"walker.pedestrian.0031": [ +0.25, +0.25 +], +"walker.pedestrian.0028": [ +0.25, +0.25 +], +"walker.pedestrian.0033": [ +0.25, +0.25 +], +"walker.pedestrian.0030": [ +0.25, +0.25 +], +"walker.pedestrian.0007": [ +0.25, +0.25 +], +"walker.pedestrian.0036": [ +0.25, +0.25 +], +"walker.pedestrian.0029": [ +0.25, +0.25 +], +"walker.pedestrian.0012": [ +0.25, +0.25 +], +"walker.pedestrian.0025": [ +0.25, +0.25 +], +"walker.pedestrian.0024": [ +0.25, +0.25 +], +"walker.pedestrian.0021": [ +0.25, +0.25 +], +"walker.pedestrian.0019": [ +0.25, +0.25 +], +"walker.pedestrian.0023": [ +0.25, +0.25 +], +"walker.pedestrian.0032": [ +0.25, +0.25 +], +"walker.pedestrian.0018": [ +0.25, +0.25 +] +} \ No newline at end of file diff --git a/scripts/analysis/extract_failed.py b/scripts/analysis/extract_failed.py new file mode 100644 index 0000000000000000000000000000000000000000..9537ffa632a9aaf5c66125457e6cc715f38002a0 --- /dev/null +++ b/scripts/analysis/extract_failed.py @@ -0,0 +1,59 @@ +"""Extract recorder kinematics for every finished, failed route of a (possibly still running) eval. + +Usage: python extract_failed.py RESULT_ROOT --ports 2000,2010,... +""" +import argparse +import glob +import json +import subprocess +import sys +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path + +from failure_report import is_success + +HERE = Path(__file__).resolve().parent + + +def finished_records(root): + recs = {} + for f in glob.glob(f"{root}/bench2drive220_*.json"): + try: + data = json.load(open(f)) + except json.JSONDecodeError: + continue + for r in data.get("_checkpoint", {}).get("records", []): + if r.get("status") and r["status"] != "Started": + recs[r["route_id"]] = r + return recs + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("root") + ap.add_argument("--ports", default="2000") + args = ap.parse_args() + root = Path(args.root) + out_dir = root / "analysis" / "npz" + recs = finished_records(root) + todo = [] + for rid, r in recs.items(): + log = root / "recorder" / f"{rid}.log" + if not is_success(r) and log.exists() and not (out_dir / f"{rid}.npz").exists(): + todo.append(str(log)) + ports = [int(p) for p in args.ports.split(",")] + print(f"{len(recs)} finished, {len(todo)} failed logs to extract", flush=True) + chunks = [todo[k::len(ports)] for k in range(len(ports))] + + def run(k): + if not chunks[k]: + return + subprocess.run([sys.executable, str(HERE / "recorder_extract.py"), "--port", str(ports[k]), + "--out-dir", str(out_dir), *chunks[k]], check=False) + + with ThreadPoolExecutor(len(ports)) as ex: + list(ex.map(run, range(len(ports)))) + + +if __name__ == "__main__": + main() diff --git a/scripts/analysis/failure_report.py b/scripts/analysis/failure_report.py new file mode 100644 index 0000000000000000000000000000000000000000..be0a1013e37fe2cc925cc8a5187d8f7d96ee8d51 --- /dev/null +++ b/scripts/analysis/failure_report.py @@ -0,0 +1,235 @@ +"""Classify failed Bench2Drive routes and extract collision geometry from recorder kinematics. + +Usage: python failure_report.py --merged merged.json --routes bench2drive220.xml \ + --npz-dir DIR --extents extents.json --out report.json +""" +import argparse +import json +import math +import re +import xml.etree.ElementTree as ET +from pathlib import Path + +import carla +import numpy as np + +CARLA_MAPS = Path("/workspace/carla0915/CarlaUE4/Content/Carla/Maps") +HALF_FOV = math.radians(55.0) +CAM_BACK = 1.5 +EGO_EXTENT = (2.446, 0.918) +_maps = {} + + +def get_map(town): + if town not in _maps: + for p in (CARLA_MAPS / town / "OpenDrive" / f"{town}.xodr", CARLA_MAPS / "OpenDrive" / f"{town}.xodr"): + if p.exists(): + _maps[town] = carla.Map(town, p.read_text()) + break + return _maps[town] + + +def is_success(rec): + if rec["status"] not in ("Completed", "Perfect"): + return False + return all(not v or k == "min_speed_infractions" for k, v in rec["infractions"].items()) + + +def interp_state(traj, t): + """traj columns: t, x, y, yaw, (v). Returns x, y, yaw at time t.""" + i = int(np.clip(np.searchsorted(traj[:, 0], t), 1, len(traj) - 1)) + a, b = traj[i - 1], traj[i] + w = 0.0 if b[0] == a[0] else float(np.clip((t - a[0]) / (b[0] - a[0]), 0, 1)) + dyaw = (b[3] - a[3] + 180) % 360 - 180 + return a[1] + w * (b[1] - a[1]), a[2] + w * (b[2] - a[2]), a[3] + w * dyaw + + +def corners(x, y, yaw, ext): + c, s = math.cos(math.radians(yaw)), math.sin(math.radians(yaw)) + return [(x + lx * c - ly * s, y + lx * s + ly * c) for lx in (-ext[0], ext[0]) for ly in (-ext[1], ext[1])] + + +def in_fov(ego_pose, other_pose, ext): + ex, ey, eyaw = ego_pose + c, s = math.cos(math.radians(eyaw)), math.sin(math.radians(eyaw)) + cx, cy = ex - CAM_BACK * c, ey - CAM_BACK * s + for px, py in corners(*other_pose, ext): + lx = (px - cx) * c + (py - cy) * s + ly = -(px - cx) * s + (py - cy) * c + if lx > 0 and abs(math.atan2(ly, lx)) < HALF_FOV: + return True + return False + + +def to_ego_frame(ego_pose, p): + ex, ey, eyaw = ego_pose + c, s = math.cos(math.radians(eyaw)), math.sin(math.radians(eyaw)) + dx, dy = p[0] - ex, p[1] - ey + return dx * c + dy * s, -dx * s + dy * c + + +def speed_at(traj, t, dt=0.3): + a, b = interp_state(traj, t - dt), interp_state(traj, t) + return math.hypot(b[0] - a[0], b[1] - a[1]) / dt + + +def last_departure(hero, t_end, window=20.0): + """Last standstill (>=0.5 s below 0.1 m/s) that ended within `window` s before t_end.""" + v = np.convolve(hero[:, 4], np.ones(5) / 5, "same") + sel = np.where((hero[:, 0] > t_end - window) & (hero[:, 0] < t_end) & (v < 0.1))[0] + if not len(sel): + return None + k = sel[-1] + start = k + while start > 0 and v[start - 1] < 0.1: + start -= 1 + if hero[k, 0] - hero[start, 0] < 0.5: + return None + return {"t_stop": float(hero[start, 0]), "t_depart": float(hero[k, 0]), "x": float(hero[k, 1]), "y": float(hero[k, 2])} + + +def collision_features(d, town, extents, t_c, other_id): + hero = d["hero"] + actors = json.loads(str(d["actors"])) + otype = actors.get(str(int(other_id)), "?") + others = d["others"] + tr = others[others[:, 1] == other_id][:, [0, 2, 3, 4]] + feat = {"t": round(float(t_c), 2), "other_type": otype} + ego_c = interp_state(hero, t_c) + m = get_map(town) + wp = m.get_waypoint(carla.Location(x=ego_c[0], y=ego_c[1], z=0), project_to_road=True) + feat["ego_in_junction"] = bool(wp.is_junction) + feat["ego_speed"] = round(speed_at(hero, t_c - 0.1), 2) + dep = last_departure(hero, t_c) + if dep: + feat["departed_from_stop_s_before"] = round(t_c - dep["t_depart"], 2) + feat["stop_duration"] = round(dep["t_depart"] - dep["t_stop"], 2) + feat["dist_since_departure"] = round(float(np.linalg.norm(np.array(ego_c[:2]) - [dep["x"], dep["y"]])), 1) + loc = carla.Location(x=dep["x"], y=dep["y"], z=0) + wpd = m.get_waypoint(loc, project_to_road=True) + signs = wpd.get_landmarks(25.0, False) + feat["stop_reason"] = sorted({l.type for l in signs if l.type in ("206", "1000001")}) or None + if len(tr) < 2: + feat["other_track"] = "missing" + return feat + ext = extents.get(otype, (2.4, 1.0)) + t_pre = min(t_c - 0.1, tr[-1, 0]) + oth_c = interp_state(tr, t_pre) + lx, ly = to_ego_frame(ego_c, oth_c) + feat["other_rel_xy"] = (round(lx, 1), round(ly, 1)) + feat["rel_heading"] = round(((oth_c[2] - ego_c[2] + 180) % 360) - 180, 0) + feat["other_speed"] = round(speed_at(tr, t_pre), 2) if tr[0, 0] < t_pre - 0.3 else None + # Field-of-view history (geometry only, ignores occlusion and fog). + ts = tr[(tr[:, 0] >= t_c - 15) & (tr[:, 0] <= t_pre), 0] + vis = [(t, in_fov(interp_state(hero, t), interp_state(tr, t), ext)) for t in ts] + seen = [t for t, v in vis if v] + feat["first_tracked_s_before"] = round(t_c - float(tr[0, 0]), 1) + feat["in_fov_at"] = {f"-{k}s": bool(any(v for t, v in vis if abs(t - (t_c - k)) < 0.06)) for k in (0.5, 1.0, 1.5, 2.0, 3.0)} + feat["last_in_fov_s_before"] = round(t_c - max(seen), 2) if seen else None + feat["fov_time_last15s"] = round(0.1 * len(seen), 1) + # Warning time: start of the last uninterrupted in-FOV stretch before impact. + warn = None + for t, v in reversed(vis): + if not v: + break + warn = t + feat["warning_s"] = round(t_c - warn, 2) if warn is not None else 0.0 + if dep: + feat["stop_is_route_start"] = dep["t_stop"] < 1.0 + t_d = dep["t_depart"] + feat["in_fov_at_departure"] = bool(tr[0, 0] <= t_d and in_fov(interp_state(hero, t_d), interp_state(tr, t_d), ext)) + feat["tracked_at_departure"] = bool(tr[0, 0] <= t_d) + # Was the other actor parked and then started (scenario-triggered)? + sp = [speed_at(tr, t) for t in ts[ts > ts[0] + 0.3]] if len(ts) > 3 else [] + feat["other_started_from_rest"] = bool(sp and min(sp[: max(1, len(sp) // 2)]) < 0.3 and max(sp) > 3) + return feat + + +MSG_RE = re.compile(r"type=(\S+) and id=(\d+) at \(x=([-\d.]+), y=([-\d.]+)") + + +def collision_time(d, other_id, x, y): + """Recorder collision time with this actor if logged, else when the ego passed the reported location.""" + coll = d["collisions"] + hit = coll[coll[:, 1] == other_id] + if len(hit): + return float(hit[0, 0]) + hero = d["hero"] + dist = np.hypot(hero[:, 1] - x, hero[:, 2] - y) + close = np.where(dist < 1.0)[0] + return float(hero[close[0], 0] if len(close) else hero[np.argmin(dist), 0]) + + +def classify_collision(f): + lx, ly = f.get("other_rel_xy", (None, None)) + if lx is None: + return "unknown" + rh = abs(f.get("rel_heading", 0)) + if f["other_type"].startswith("walker."): + return "pedestrian" + if lx > 0 and f.get("other_speed") is not None and f["other_speed"] < 0.5: + return "ego hits stationary vehicle" + if lx < -1.5 and rh < 45: + return "rear-ended by other" + if lx > 1.5 and rh < 45: + return "ego hits vehicle ahead (same direction)" + if rh > 135 and abs(ly) < 3.0: + return "head-on" + if 45 <= rh <= 135 or (f.get("ego_in_junction") and rh > 30): + return "crossing" + return "side-swipe / lane change" + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--merged", required=True) + ap.add_argument("--routes", required=True) + ap.add_argument("--npz-dir", required=True) + ap.add_argument("--extents", required=True) + ap.add_argument("--out", required=True) + args = ap.parse_args() + extents = {k: tuple(v) for k, v in json.load(open(args.extents)).items()} + meta = {} + for r in ET.parse(args.routes).iter("route"): + meta[r.attrib["id"]] = {"town": r.attrib["town"], "scenario": [s.attrib["type"] for s in r.iter("scenario")][0]} + recs = json.load(open(args.merged))["_checkpoint"]["records"] + report = [] + for rec in recs: + rid = rec["route_id"].split("_")[1] + entry = {"route": rid, **meta[rid], "status": rec["status"], "score": rec["scores"]["score_composed"], + "success": is_success(rec), + "infractions": {k: v for k, v in rec["infractions"].items() if v and k != "min_speed_infractions"}} + if not entry["success"]: + npz = Path(args.npz_dir) / f"RouteScenario_{rid}_rep0.npz" + if npz.exists(): + d = np.load(npz, allow_pickle=False) + feats = [] + for kind in ("collisions_vehicle", "collisions_pedestrian", "collisions_layout"): + for msg in rec["infractions"].get(kind, []): + m = MSG_RE.search(msg) + if not m: + continue + otype, oid, cx, cy = m.group(1), int(m.group(2)), float(m.group(3)), float(m.group(4)) + t_c = collision_time(d, oid, cx, cy) + others = d["others"] + if kind != "collisions_layout" and np.any(others[:, 1] == oid): + f = collision_features(d, meta[rid]["town"], extents, t_c, oid) + f["class"] = classify_collision(f) + else: + f = {"t": round(t_c, 2), "other_type": otype, "class": "static object / layout", + "ego_speed": round(speed_at(d["hero"], t_c - 0.1), 2)} + f["kind"] = kind + f["other_id"] = oid + feats.append(f) + entry["collisions"] = feats + entry["duration"] = round(float(d["hero"][-1, 0]), 1) + else: + entry["collisions"] = "no recorder log" + report.append(entry) + json.dump(report, open(args.out, "w"), indent=1) + n_fail = sum(not e["success"] for e in report) + print(f"{len(report)} routes, {len(report) - n_fail} success, {n_fail} failed -> {args.out}") + + +if __name__ == "__main__": + main() diff --git a/scripts/analysis/fixability.py b/scripts/analysis/fixability.py new file mode 100644 index 0000000000000000000000000000000000000000..b1f3e61513315ddb9b28f2d59b84b18688431f06 --- /dev/null +++ b/scripts/analysis/fixability.py @@ -0,0 +1,95 @@ +"""Route-level fixability of failed routes under S1 (creep after a junction standstill) / S2 (memory-gated creep). + +A collision counts as visibility-limited when the partner was continuously in the front-camera FOV for +< 1.5 s before impact. It is fixed by a strategy when the multi-actor reactive replay (cf_reactive.py) +avoids the partner without hitting any recorded actor for every (v_cap, tau) setting. A route is fixable +when every infraction other than route deviation / min speed is a collision that is fixed, or that happens +after a fixed collision inside its replay window. Route deviation is ignored by request. + +Usage: python fixability.py ANALYSIS_DIR +""" +import collections +import json +import sys + +import numpy as np + +IGNORED = {"route_dev", "min_speed_infractions"} +COLLISIONS = {"collisions_vehicle", "collisions_pedestrian", "collisions_layout"} +AVOIDED = {"passed", "passed_after_recording", "partner_avoided"} +VIS_LIMIT_S = 1.5 +REAR_THREAT_SCENARIOS = {"ParkingExit"} + + +def verdict(sims): + if not sims: + return None + good = [v["outcome"] in AVOIDED for v in sims.values()] + return "fixed" if all(good) else ("fragile" if any(good) else "no") + + +def classify_route(e, cf, npz_dir): + infr = {k: len(v) for k, v in e["infractions"].items() if v and k not in IGNORED} + if not infr: + return "deviation only (ignored)", [] + if set(infr) - COLLISIONS - {"collisions_vehicle"}: + return "non-collision: " + "/".join(sorted(set(infr) - COLLISIONS)), [] + if e["scenario"] in REAR_THREAT_SCENARIOS: + return "not addressed: threat from behind", [] + rec_end = float(np.load(f"{npz_dir}/RouteScenario_{e['route']}_rep0.npz")["hero"][-1, 0]) + per, seen = [], set() + for c in sorted(e["collisions"], key=lambda c: c["t"]): + key = (c.get("other_id"), round(c["t"], 1)) + if key in seen: + continue + seen.add(key) + r = cf.get((e["route"], c.get("other_id"), round(c["t"], 2)), {}) + per.append({"t": c["t"], "class": c["class"], "other": c["other_type"], "warning_s": c.get("warning_s"), + "vis_limited": c["class"] != "static object / layout" and c.get("warning_s", 99) < VIS_LIMIT_S, + "S1": verdict(r.get("S1")), "S2": verdict(r.get("S2"))}) + first_fix = next((p for p in per if p["vis_limited"] and "fixed" in (p["S1"], p["S2"])), None) + for p in per: + if p["vis_limited"] and p["S1"] == "fixed": + p["status"] = "S1" + elif p["vis_limited"] and p["S2"] == "fixed": + p["status"] = "S2" + elif p["vis_limited"] and "fragile" in (p["S1"], p["S2"]): + p["status"] = "fragile" + elif first_fix and first_fix["t"] < p["t"] <= rec_end: + p["status"] = "covered" + else: + p["status"] = "no" + st = [p["status"] for p in per] + if all(s in ("S1", "covered") for s in st): + return "S1 fixes", per + if all(s in ("S1", "S2", "covered") for s in st): + return "S2 fixes", per + if all(s in ("S1", "S2", "covered", "fragile") for s in st): + return "S1/S2 fragile", per + p = per[st.index("no")] + if p["class"] == "static object / layout" or p["class"].startswith("ego hits"): + return "not addressed: ego hits lead/stationary/static object", per + if p["class"] == "pedestrian": + return "not addressed: pedestrian", per + if not p["vis_limited"]: + return f"not addressed: partner visible >= {VIS_LIMIT_S} s but not yielded to", per + return "not addressed: visibility-limited, creep does not help (lane change/merge/flow)", per + + +def main(): + adir = sys.argv[1] + report = json.load(open(f"{adir}/report.json")) + cf = {(r["route"], r["other_id"], round(r["t"], 2)): r for r in json.load(open(f"{adir}/cf_reactive.json"))} + out = collections.defaultdict(list) + for e in report: + if not e["success"]: + cat, per = classify_route(e, cf, f"{adir}/npz") + out[cat].append({"route": e["route"], "scenario": e["scenario"], "collisions": per}) + json.dump(out, open(f"{adir}/fixability.json", "w"), indent=1, default=float) + for k in sorted(out): + print(f"{len(out[k]):3d} {k}: {' '.join(r['route'] for r in out[k])}") + print(f"{sum(map(len, out.values()))} failed routes -> {adir}/fixability.json") + + +if __name__ == "__main__": + main() diff --git a/scripts/analysis/recorder_extract.py b/scripts/analysis/recorder_extract.py new file mode 100644 index 0000000000000000000000000000000000000000..cfbdd84b0a1a05020ac0c9d0af06e976f1277598 --- /dev/null +++ b/scripts/analysis/recorder_extract.py @@ -0,0 +1,124 @@ +"""Extract compact kinematics from CARLA recorder logs. + +Usage: python recorder_extract.py --port 2000 --out-dir DIR log1.log [log2.log ...] + +For each log writes DIR/.npz with + hero: (T, 5) t, x, y, yaw_deg, speed + hero_ctrl: (T, 4) t, steer, throttle, brake + collisions: (K, 2) t, other_id (only collisions involving the hero) + actors: JSON string {id: type_id} + others: (N, 5) t, id, x, y, yaw_deg (vehicles/walkers within 80 m of the hero, 10 Hz) +Positions are in metres (the recorder stores centimetres). +""" +import argparse +import json +import math +import re +from pathlib import Path + +import carla +import numpy as np + +FRAME_RE = re.compile(r"^Frame \d+ at ([\d.]+) seconds") +CREATE_RE = re.compile(r"^ Create (\d+): (\S+) \(\d+\) at") +ATTR_RE = re.compile(r"^\s+role_name = (\S+)") +POS_RE = re.compile(r"^ Id: (\d+) Location: \(([-+\d.e]+), ([-+\d.e]+), ([-+\d.e]+)\) Rotation: \(([-+\d.e]+), ([-+\d.e]+), ([-+\d.e]+)\)") +CTRL_RE = re.compile(r"^ Id: (\d+) Steering: ([-+\d.e]+) Throttle: ([-+\d.e]+) Brake: ([-+\d.e]+)") +COLL_RE = re.compile(r"^ Collision id \d+ between (\d+)(?: \((\w+)\))?\s+with (\d+)(?: \((\w+)\))?") +KEEP_PREFIX = ("vehicle.", "walker.") + + +def extract(text): + types, roles = {}, {} + hero = None + frames = [] + cur_create = None + t = None + pos, ctrl, colls = {}, {}, [] + for line in text.splitlines(): + m = FRAME_RE.match(line) + if m: + if t is not None: + frames.append((t, pos, ctrl)) + t, pos, ctrl, cur_create = float(m.group(1)), {}, {}, None + continue + if line.startswith(" Id: "): + m = POS_RE.match(line) + if m: + pos[int(m.group(1))] = (float(m.group(2)) / 100, float(m.group(3)) / 100, float(m.group(7))) + continue + m = CTRL_RE.match(line) + if m: + ctrl[int(m.group(1))] = (float(m.group(2)), float(m.group(3)), float(m.group(4))) + continue + m = CREATE_RE.match(line) + if m: + cur_create = int(m.group(1)) + types[cur_create] = m.group(2) + continue + m = ATTR_RE.match(line) + if m and cur_create is not None: + roles[cur_create] = m.group(1) + if m.group(1) == "hero" and types.get(cur_create, "").startswith("vehicle."): + hero = cur_create + continue + m = COLL_RE.match(line) + if m and t is not None: + a, b = int(m.group(1)), int(m.group(3)) + colls.append((t, a, b)) + if t is not None: + frames.append((t, pos, ctrl)) + + hero_rows, ctrl_rows, other_rows = [], [], [] + last = None + next_other_t = -1.0 + for t, pos, ctrl in frames: + if hero not in pos: + continue + x, y, yaw = pos[hero] + v = 0.0 if last is None or t <= last[0] else math.hypot(x - last[1], y - last[2]) / (t - last[0]) + hero_rows.append((t, x, y, yaw, v)) + last = (t, x, y) + if hero in ctrl: + ctrl_rows.append((t,) + ctrl[hero]) + if t >= next_other_t: + next_other_t = t + 0.1 - 1e-6 + for aid, (ax, ay, ayaw) in pos.items(): + if aid == hero or not types.get(aid, "").startswith(KEEP_PREFIX): + continue + if math.hypot(ax - x, ay - y) < 80.0: + other_rows.append((t, aid, ax, ay, ayaw)) + hero_colls = [(t, b if a == hero else a) for t, a, b in colls if hero in (a, b)] + return { + "hero": np.array(hero_rows, dtype=np.float64), + "hero_ctrl": np.array(ctrl_rows, dtype=np.float64).reshape(-1, 4), + "collisions": np.array(hero_colls, dtype=np.float64).reshape(-1, 2), + "others": np.array(other_rows, dtype=np.float64).reshape(-1, 5), + "actors": json.dumps({str(k): v for k, v in types.items()}), + "hero_id": hero, + } + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--port", type=int, default=2000) + ap.add_argument("--out-dir", required=True) + ap.add_argument("logs", nargs="+") + args = ap.parse_args() + out_dir = Path(args.out_dir) + out_dir.mkdir(parents=True, exist_ok=True) + client = carla.Client("localhost", args.port) + client.set_timeout(600.0) + for log in args.logs: + log = Path(log).resolve() + out = out_dir / (log.stem + ".npz") + if out.exists(): + continue + data = extract(client.show_recorder_file_info(str(log), True)) + np.savez_compressed(out, **data) + print(f"{log.stem}: hero={data['hero_id']} frames={len(data['hero'])} " + f"collisions={len(data['collisions'])} others={len(data['others'])}", flush=True) + + +if __name__ == "__main__": + main() diff --git a/scripts/analysis/recorder_traffic_lights.py b/scripts/analysis/recorder_traffic_lights.py new file mode 100644 index 0000000000000000000000000000000000000000..25fd1c8e5c465697b975ae723e202dc3abf9bfe4 --- /dev/null +++ b/scripts/analysis/recorder_traffic_lights.py @@ -0,0 +1,90 @@ +"""Extract traffic-light locations and state changes from CARLA recorder logs. + +Usage: python recorder_traffic_lights.py --port 2000 --out-dir DIR [--workers 4] log1.log [log2.log ...] + +For each log writes DIR/_tl.npz with + tl_ids: (L,) recorder actor ids of traffic lights + tl_locs: (L, 2) x, y in metres + changes: (C, 3) t, tl_id, state (state: 0 red, 1 yellow, 2 green, 3 off, 4 unknown; first row per light + is its state in the first recorded frame) +""" +import argparse +import re +from multiprocessing import Pool +from pathlib import Path + +import carla +import numpy as np + +FRAME_RE = re.compile(r"^Frame \d+ at ([\d.]+) seconds") +CREATE_RE = re.compile(r"^ Create (\d+): traffic\.traffic_light \(\d+\) at \(([-+\d.e]+), ([-+\d.e]+), ([-+\d.e]+)\)") +STATE_RE = re.compile(r"^ Id: (\d+) state: (\d+) frozen") + +PORT = None + + +def extract(text): + locs, last, changes = {}, {}, [] + t = None + for line in text.splitlines(): + if line.startswith("Frame "): + m = FRAME_RE.match(line) + if m: + t = float(m.group(1)) + continue + if line.startswith(" Id: ") and " state: " in line: + m = STATE_RE.match(line) + if m and t is not None: + tl, state = int(m.group(1)), int(m.group(2)) + if last.get(tl) != state: + last[tl] = state + changes.append((t, tl, state)) + continue + if line.startswith(" Create ") and "traffic_light" in line: + m = CREATE_RE.match(line) + if m: + locs[int(m.group(1))] = (float(m.group(2)) / 100, float(m.group(3)) / 100) + ids = np.array(sorted(locs), dtype=np.int64) + return { + "tl_ids": ids, + "tl_locs": np.array([locs[i] for i in ids], dtype=np.float64).reshape(-1, 2), + "changes": np.array(changes, dtype=np.float64).reshape(-1, 3), + } + + +def work(job): + log, out = job + client = carla.Client("localhost", PORT, worker_threads=2) + client.set_timeout(600.0) + data = extract(client.show_recorder_file_info(str(log), True)) + np.savez_compressed(out, **data) + return f"{log.stem}: {len(data['tl_ids'])} lights, {len(data['changes'])} state changes" + + +def init(port): + global PORT + PORT = port + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--port", type=int, default=2000) + ap.add_argument("--out-dir", required=True) + ap.add_argument("--workers", type=int, default=4) + ap.add_argument("logs", nargs="+") + args = ap.parse_args() + out_dir = Path(args.out_dir) + out_dir.mkdir(parents=True, exist_ok=True) + jobs = [] + for log in args.logs: + log = Path(log).resolve() + out = out_dir / f"{log.stem}_tl.npz" + if not out.exists(): + jobs.append((log, out)) + with Pool(args.workers, initializer=init, initargs=(args.port,)) as pool: + for msg in pool.imap_unordered(work, jobs): + print(msg, flush=True) + + +if __name__ == "__main__": + main() diff --git a/scripts/analysis/stall_reasons.py b/scripts/analysis/stall_reasons.py new file mode 100644 index 0000000000000000000000000000000000000000..4dd875a8aeb0f943fefcb1e4791be8baaa6207ed --- /dev/null +++ b/scripts/analysis/stall_reasons.py @@ -0,0 +1,172 @@ +"""Classify why the ego was standing still, from recorder kinematics + traffic-light states. + +Usage: python stall_reasons.py --merged merged.json --npz-dir DIR --tl-dir DIR --stoplines stoplines.json + --out stalls.json + +For every stop (speed < 0.1 m/s for >= MIN_STOP_S) the ego's actually driven path after the stop is taken as +the path it should have driven. Every 0.5 s of the stop is labelled + blocked a vehicle/walker is on that path (within 22 m) now or within the next 3 s (recorded future) + red_light a same-direction stop line on the path belongs to a red/yellow light + stop_sign the ego is inside a stop-sign trigger and has been stopped for < 4 s + free none of the above: nothing required the ego to wait +and the stop records how long it had been continuously free when the ego finally moved. +""" +import argparse +import json +import math + +import numpy as np + +MIN_STOP_S = 3.0 +STEP_S = 0.5 +PATH_LEN = 25.0 +CONFLICT_S = (2.5, 22.0) # arc length range from the ego centre (excludes vehicles behind) +LATERAL = {"vehicle": 2.0, "walker": 1.5} +LOOKAHEAD_S = 3.0 +STOP_SIGN_WAIT_S = 4.0 +CREEP_THROTTLE = 0.4 + + +def future_path(hero, i_end): + """Driven path from the stop position, resampled every 0.5 m; straight ahead if the ego never moved again.""" + x0, y0, yaw0 = hero[i_end, 1], hero[i_end, 2], math.radians(hero[i_end, 3]) + pts = [(x0, y0)] + dist = 0.0 + for x, y in hero[i_end + 1:, 1:3]: + step = math.hypot(x - pts[-1][0], y - pts[-1][1]) + if step < 0.25: + continue + pts.append((x, y)) + dist += step + if dist >= PATH_LEN: + break + if dist < 5.0: + pts = [(x0 + s * math.cos(yaw0), y0 + s * math.sin(yaw0)) for s in np.arange(0, PATH_LEN, 0.5)] + pts = np.array(pts) + seg = np.hypot(*np.diff(pts, axis=0).T) + s = np.concatenate([[0.0], np.cumsum(seg)]) + grid = np.arange(0.0, min(s[-1], PATH_LEN) + 1e-6, 0.5) + path = np.stack([np.interp(grid, s, pts[:, 0]), np.interp(grid, s, pts[:, 1])], axis=1) + heading = np.arctan2(*np.gradient(path, axis=0)[:, ::-1].T) if len(path) > 1 else np.array([yaw0]) + return path, grid, heading + + +def project(points, path, grid): + d = np.hypot(points[:, None, 0] - path[None, :, 0], points[:, None, 1] - path[None, :, 1]) + j = d.argmin(axis=1) + return d[np.arange(len(points)), j], grid[j], j + + +def tl_state_fn(tl): + changes = tl["changes"] + by_id = {} + for t, i, s in changes: + by_id.setdefault(int(i), []).append((t, int(s))) + + def state(tl_id, t): + seq = by_id.get(tl_id) + if not seq: + return 4 + k = np.searchsorted([c[0] for c in seq], t, side="right") - 1 + return seq[max(k, 0)][1] + + return state + + +def analyse_route(z, tl, lights, signs): + hero, ctrl, others = z["hero"], z["hero_ctrl"], z["others"] + types = json.loads(str(z["actors"])) + kinds = {int(k): ("walker" if v.startswith("walker.") else "vehicle") for k, v in types.items()} + t, v = hero[:, 0], hero[:, 4] + state = tl_state_fn(tl) + # recorder ids of the town's traffic lights (match by location) + rec_ids = tl["tl_ids"].astype(int) + rec_locs = tl["tl_locs"] + stop_lines = [] + for light in lights: + if len(rec_locs) == 0: + break + d = np.hypot(*(rec_locs - np.array(light["loc"])).T) + if d.min() < 1.0: + for x, y, yaw, _, _ in light["stops"]: + stop_lines.append((x, y, math.radians(yaw), int(rec_ids[d.argmin()]))) + stop_lines = np.array(stop_lines) if stop_lines else np.zeros((0, 4)) + signs = np.array(signs) if signs else np.zeros((0, 4)) + + stopped = v < 0.1 + edges = np.diff(np.concatenate([[0], stopped.astype(int), [0]])) + starts, ends = np.nonzero(edges == 1)[0], np.nonzero(edges == -1)[0] - 1 + moved_before = np.concatenate([[0.0], np.cumsum(np.hypot(*np.diff(hero[:, 1:3], axis=0).T))]) + out = [] + for i0, i1 in zip(starts, ends): + t0, t1 = max(t[i0], 2.5), t[i1] + if t1 - t0 < MIN_STOP_S: + continue + path, grid, heading = future_path(hero, i1) + # actors on the path now or within LOOKAHEAD_S + sel = (others[:, 0] >= t0) & (others[:, 0] <= t1 + LOOKAHEAD_S) + rows = others[sel] + conflict_t = np.zeros(0) + if len(rows): + d, s, _ = project(rows[:, 2:4], path, grid) + lat = np.array([LATERAL[kinds.get(int(i), "vehicle")] for i in rows[:, 1]]) + hit = (d < lat) & (s >= CONFLICT_S[0]) & (s <= CONFLICT_S[1]) + conflict_t = rows[hit, 0] + # same-direction stop lines on the path + lines = [] + if len(stop_lines): + d, s, j = project(stop_lines[:, :2], path, grid) + dyaw = np.abs((stop_lines[:, 2] - heading[j] + np.pi) % (2 * np.pi) - np.pi) + ok = (d < 2.5) & (s <= 20.0) & (dyaw < math.radians(45)) + lines = sorted({int(i) for i in stop_lines[ok, 3]}) + in_sign = bool(len(signs)) and bool(np.any( + np.hypot(signs[:, 0] - hero[i0, 1], signs[:, 1] - hero[i0, 2]) < np.maximum(signs[:, 2], signs[:, 3]) + 2.0)) + labels = [] + for ts in np.arange(t0, t1, STEP_S): + if np.any((conflict_t >= ts) & (conflict_t <= ts + LOOKAHEAD_S)): + labels.append("blocked") + elif any(state(i, ts) in (0, 1) for i in lines): + labels.append("red_light") + elif in_sign and ts - t0 < STOP_SIGN_WAIT_S: + labels.append("stop_sign") + else: + labels.append("free") + free_run = 0 + for lab in reversed(labels): + if lab != "free": + break + free_run += 1 + departed = i1 + 1 < len(hero) + dep_ctrl = ctrl[(ctrl[:, 0] > t1 - 0.1) & (ctrl[:, 0] < t1 + 0.8)] + creep = departed and t1 - t0 >= 39.0 and len(dep_ctrl) > 0 and np.any(np.abs(dep_ctrl[:, 2] - CREEP_THROTTLE) < 1e-3) + dep_conflict = bool(np.any((conflict_t >= t1) & (conflict_t <= t1 + LOOKAHEAD_S))) + counts = {k: labels.count(k) * STEP_S for k in ("blocked", "red_light", "stop_sign", "free")} + out.append(dict( + t0=round(float(t0), 2), t1=round(float(t1), 2), duration=round(float(t1 - t0), 2), + route_start=bool(moved_before[i0] < 1.0), ended=("creep" if creep else "policy" if departed else "route_end"), + first=labels[0], free_run_s=free_run * STEP_S, departed_into_conflict=dep_conflict, **counts)) + return out + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--merged", required=True) + ap.add_argument("--npz-dir", required=True) + ap.add_argument("--tl-dir", required=True) + ap.add_argument("--stoplines", required=True) + ap.add_argument("--out", required=True) + args = ap.parse_args() + towns = {r["route_id"]: r["town_name"] for r in json.load(open(args.merged))["_checkpoint"]["records"]} + stoplines = json.load(open(args.stoplines)) + result = {} + for rid, town in sorted(towns.items()): + z = np.load(f"{args.npz_dir}/{rid}.npz", allow_pickle=True) + tl = np.load(f"{args.tl_dir}/{rid}_tl.npz") + result[rid] = analyse_route(z, tl, stoplines.get(town, []), stoplines.get(f"{town}/stop_signs", [])) + json.dump(result, open(args.out, "w"), indent=1) + stops = [s for v in result.values() for s in v] + print(f"{len(stops)} stops >= {MIN_STOP_S}s in {len(result)} routes") + + +if __name__ == "__main__": + main() diff --git a/scripts/analysis/stall_summary.py b/scripts/analysis/stall_summary.py new file mode 100644 index 0000000000000000000000000000000000000000..d36348e2c4ce0d58a295716034f1a7d41c718c67 --- /dev/null +++ b/scripts/analysis/stall_summary.py @@ -0,0 +1,23 @@ +"""Summarise stall_reasons.py output for several runs. + +Usage: python stall_summary.py NAME=stalls.json [NAME=stalls.json ...] +""" +import json +import sys + +FREE_RUNS = (5, 10, 20) + +print(f"{'run':10s} {'stops':>5s} {'stopped_s':>9s} {'free_s':>7s} {'blocked_s':>9s} {'red_s':>6s} " + + " ".join(f"{'free>=' + str(k):>8s}" for k in FREE_RUNS) + + f" {'start_free>=5':>13s} {'creep':>5s} {'creep_free':>10s} {'creep_conf':>10s} {'end_stopped':>11s}") +for arg in sys.argv[1:]: + name, path = arg.split("=", 1) + stalls = json.load(open(path)) + stops = [s for v in stalls.values() for s in v] + creeps = [s for s in stops if s["ended"] == "creep"] + print(f"{name:10s} {len(stops):5d} {sum(s['duration'] for s in stops):9.0f} {sum(s['free'] for s in stops):7.0f} " + f"{sum(s['blocked'] for s in stops):9.0f} {sum(s['red_light'] for s in stops):6.0f} " + + " ".join(f"{sum(s['free_run_s'] >= k for s in stops):8d}" for k in FREE_RUNS) + + f" {sum(s['route_start'] and s['free_run_s'] >= 5 for s in stops):13d} {len(creeps):5d}" + f" {sum(s['free_run_s'] >= 5 for s in creeps):10d} {sum(s['departed_into_conflict'] for s in creeps):10d}" + f" {sum(s['ended'] == 'route_end' for s in stops):11d}") diff --git a/scripts/analysis/traffic_light_stoplines.py b/scripts/analysis/traffic_light_stoplines.py new file mode 100644 index 0000000000000000000000000000000000000000..6101313a8c8f97f085fd98c6d875b43b92d4ed67 --- /dev/null +++ b/scripts/analysis/traffic_light_stoplines.py @@ -0,0 +1,53 @@ +"""Dump traffic-light stop lines per town so recorder logs can be checked for red-light waits offline. + +Usage: python traffic_light_stoplines.py --port 2000 --out stoplines.json [--towns Town12 Town13 ...] +Writes {town: [{"loc": [x, y], "stops": [[x, y, yaw_deg, road_id, lane_id], ...]}, ...]}; "loc" is the +traffic-light actor location in metres, which matches the recorder's "Create ...: traffic.traffic_light". +Stop signs go to {town + "/stop_signs": [[x, y, extent_x, extent_y], ...]} (trigger-volume centre and +half extents in metres). +""" +import argparse +import json +import xml.etree.ElementTree as ET + +import carla + +ROUTES = "leaderboard/data/bench2drive220.xml" + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--port", type=int, default=2000) + ap.add_argument("--out", required=True) + ap.add_argument("--towns", nargs="*") + args = ap.parse_args() + towns = args.towns or sorted({r.get("town") for r in ET.parse(ROUTES).getroot().iter("route")}) + client = carla.Client("localhost", args.port, worker_threads=4) + client.set_timeout(600.0) + try: + out = json.load(open(args.out)) + except FileNotFoundError: + out = {} + for town in towns: + if town in out and f"{town}/stop_signs" in out: + continue + world = client.load_world(town) + lights = [] + for tl in world.get_actors().filter("traffic.traffic_light"): + loc = tl.get_location() + stops = [[w.transform.location.x, w.transform.location.y, w.transform.rotation.yaw, w.road_id, w.lane_id] + for w in tl.get_stop_waypoints()] + lights.append({"loc": [loc.x, loc.y], "stops": stops}) + signs = [] + for sign in world.get_actors().filter("traffic.stop"): + centre = sign.get_transform().transform(sign.trigger_volume.location) + signs.append([centre.x, centre.y, sign.trigger_volume.extent.x, sign.trigger_volume.extent.y]) + out[town] = lights + out[f"{town}/stop_signs"] = signs + json.dump(out, open(args.out, "w")) + print(f"{town}: {len(lights)} traffic lights, {sum(len(l['stops']) for l in lights)} stop lines, " + f"{len(signs)} stop signs", flush=True) + + +if __name__ == "__main__": + main() diff --git a/scripts/build_detection_labels.py b/scripts/build_detection_labels.py new file mode 100644 index 0000000000000000000000000000000000000000..cf862046ec553e50f70f4e3cbba6268f4a549d67 --- /dev/null +++ b/scripts/build_detection_labels.py @@ -0,0 +1,92 @@ +"""Build the stage-2 detection / traffic-control labels for every SimLingo route. + +Writes /detection_labels/<...>//labels.npz (layout in dataloader.detection_labels). + +Usage: python scripts/build_detection_labels.py [--data-root simlingo_data] [--workers 192] [--limit N] +""" +import argparse +import glob +import gzip +import os +import sys +import time +from multiprocessing import Pool +from pathlib import Path + +import numpy as np +import ujson + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +from dataloader.detection_labels import EGO_DIM, MAX_OBJECTS, OBJ_DIM, frame_labels # noqa: E402 + + +def output_path(route_dir, data_root): + rel = Path(route_dir).relative_to(Path(data_root) / "data") + return Path(data_root) / "detection_labels" / rel / "labels.npz" + + +def build_route(args): + route_dir, data_root = args + out = output_path(route_dir, data_root) + if out.exists(): + return route_dir, "skipped", None + box_files = sorted(glob.glob(f"{route_dir}/boxes/*.json.gz")) + if not box_files: + return route_dir, "no_boxes", None + objects = np.zeros((len(box_files), MAX_OBJECTS, OBJ_DIM), dtype=np.float32) + count = np.zeros(len(box_files), dtype=np.int16) + ego = np.zeros((len(box_files), EGO_DIM), dtype=np.float32) + try: + for f, box_file in enumerate(box_files): + frame = int(Path(box_file).name.split(".")[0]) + if frame != f: + return route_dir, f"error: non-contiguous frames at {frame}", None + with gzip.open(box_file, "rt") as fh: + boxes = ujson.load(fh) + with gzip.open(f"{route_dir}/measurements/{frame:04d}.json.gz", "rt") as fh: + measurement = ujson.load(fh) + rows, ego[f] = frame_labels(boxes, measurement) + objects[f, :len(rows)] = rows + count[f] = len(rows) + except Exception as exc: # keep the pool alive; report the route + return route_dir, f"error: {type(exc).__name__}: {exc}", None + out.parent.mkdir(parents=True, exist_ok=True) + tmp = out.with_suffix(".tmp.npz") + np.savez(tmp, objects=objects, count=count, ego=ego) + os.replace(tmp, out) + return route_dir, "built", (len(box_files), int(count.sum())) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--data-root", default="simlingo_data") + ap.add_argument("--workers", type=int, default=max(1, min(192, (os.cpu_count() or 2) - 8))) + ap.add_argument("--limit", type=int, default=0, help="only the first N routes (smoke test)") + args = ap.parse_args() + data_root = str(Path(args.data_root).resolve()) + routes = sorted(glob.glob(f"{data_root}/data/simlingo/*/*/*/Town*")) + if args.limit: + routes = routes[: args.limit] + print(f"{len(routes)} routes, {args.workers} workers", flush=True) + t0 = time.time() + frames = objects = 0 + status, errors = {}, [] + with Pool(args.workers) as pool: + for i, (route, state, stats) in enumerate(pool.imap_unordered( + build_route, [(r, data_root) for r in routes], chunksize=2), 1): + key = state.split(":")[0] + status[key] = status.get(key, 0) + 1 + if stats is not None: + frames += stats[0] + objects += stats[1] + if key == "error": + errors.append((route, state)) + if i % 1000 == 0 or i == len(routes): + print(f"[{i}/{len(routes)}] {time.time() - t0:.0f}s {status}", flush=True) + print(f"frames {frames}, labelled objects/frame {objects / max(frames, 1):.2f}", flush=True) + for route, state in errors[:20]: + print("ERROR", route, state) + + +if __name__ == "__main__": + main() diff --git a/scripts/build_object_bank.py b/scripts/build_object_bank.py new file mode 100644 index 0000000000000000000000000000000000000000..902e8c5c64ff61ab5d0671aed163d2152116569e --- /dev/null +++ b/scripts/build_object_bank.py @@ -0,0 +1,116 @@ +"""Build the FOV-limited object bank for every SimLingo route (stage-3 object tokens + relation labels). + +For each route the bank is replayed frame by frame over boxes/*.json.gz (4 Hz) and written to +/object_bank/simlingo/<...>//objects.npz with + raw [F, N, RAW_DIM] float16 object rows in the ego frame of that frame (see dataloader.object_bank) + ids [F, N] int32 CARLA actor id (negative: id-less static matched by position), 0 = padding + relation [F, N] int8 0 ignore / 1 follow / 2 yield, -100 padding + count [F] int16 + +Usage: python scripts/build_object_bank.py [--data-root simlingo_data] [--workers 192] [--limit N] +""" +import argparse +import glob +import gzip +import json +import os +import sys +import time +from multiprocessing import Pool +from pathlib import Path + +import numpy as np +import ujson + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +from dataloader.object_bank import ( # noqa: E402 + DEFAULT_BANK, RAW_DIM, ObjectBank, observations_from_simlingo_boxes, relation_labels, +) + +FRAME_DT = 0.25 # SimLingo logs are stored at 4 Hz + + +def output_path(route_dir, data_root): + rel = Path(route_dir).relative_to(Path(data_root) / "data") + return Path(data_root) / "object_bank" / rel / "objects.npz" + + +def build_route(args): + route_dir, data_root, bank_kwargs = args + out = output_path(route_dir, data_root) + if out.exists(): + return route_dir, "skipped", None + box_files = sorted(glob.glob(f"{route_dir}/boxes/*.json.gz")) + if not box_files: + return route_dir, "no_boxes", None + bank = ObjectBank(**bank_kwargs) + n = bank.max_objects + raw_all = np.zeros((len(box_files), n, RAW_DIM), dtype=np.float16) + ids_all = np.zeros((len(box_files), n), dtype=np.int32) + rel_all = np.full((len(box_files), n), -100, dtype=np.int8) + count_all = np.zeros(len(box_files), dtype=np.int16) + stats = np.zeros(4, dtype=np.int64) # frames, objects, follow, yield + try: + for f, box_file in enumerate(box_files): + frame = int(Path(box_file).name.split(".")[0]) + with gzip.open(box_file, "rt") as fh: + boxes = ujson.load(fh) + with gzip.open(f"{route_dir}/measurements/{frame:04d}.json.gz", "rt") as fh: + measurement = ujson.load(fh) + ego_matrix = np.asarray(measurement["ego_matrix"], dtype=np.float64) + observations = observations_from_simlingo_boxes(boxes, ego_matrix) + raw, ids, count = bank.step(frame * FRAME_DT, ego_matrix, observations) + labels = relation_labels(ids, count, measurement) + raw_all[f] = raw + ids_all[f] = ids + rel_all[f] = labels + count_all[f] = count + stats += (1, count, int((labels == 1).sum()), int((labels == 2).sum())) + except Exception as exc: # keep the pool alive; report the route + return route_dir, f"error: {type(exc).__name__}: {exc}", None + out.parent.mkdir(parents=True, exist_ok=True) + tmp = out.with_suffix(".tmp.npz") + np.savez(tmp, raw=raw_all, ids=ids_all, relation=rel_all, count=count_all, + frame_dt=np.float32(FRAME_DT), bank=np.array(json.dumps(bank_kwargs))) + os.replace(tmp, out) + return route_dir, "built", stats + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--data-root", default="simlingo_data") + ap.add_argument("--workers", type=int, default=max(1, min(192, (os.cpu_count() or 2) - 8))) + ap.add_argument("--limit", type=int, default=0, help="only the first N routes (smoke test)") + for key, value in DEFAULT_BANK.items(): + ap.add_argument(f"--{key.replace('_', '-')}", type=type(value), default=value) + args = ap.parse_args() + bank_kwargs = {key: getattr(args, key) for key in DEFAULT_BANK} + data_root = str(Path(args.data_root).resolve()) + routes = sorted(glob.glob(f"{data_root}/data/simlingo/*/*/*/Town*")) + if args.limit: + routes = routes[: args.limit] + print(f"{len(routes)} routes, {args.workers} workers, bank={bank_kwargs}", flush=True) + t0 = time.time() + totals = np.zeros(4, dtype=np.int64) + status = {} + errors = [] + with Pool(args.workers) as pool: + for i, (route, state, stats) in enumerate(pool.imap_unordered( + build_route, [(r, data_root, bank_kwargs) for r in routes], chunksize=2), 1): + key = state.split(":")[0] + status[key] = status.get(key, 0) + 1 + if stats is not None: + totals += stats + if key == "error": + errors.append((route, state)) + if i % 500 == 0 or i == len(routes): + print(f"[{i}/{len(routes)}] {time.time() - t0:.0f}s {status}", flush=True) + frames, objects, follow, yield_ = (int(v) for v in totals) + print(f"frames {frames}, objects/frame {objects / max(frames, 1):.2f}, " + f"follow labels {follow}, yield labels {yield_}", flush=True) + for route, state in errors[:20]: + print("ERROR", route, state) + + +if __name__ == "__main__": + main() diff --git a/scripts/chain_coast_ablation.sh b/scripts/chain_coast_ablation.sh new file mode 100644 index 0000000000000000000000000000000000000000..d047396a383ea127550af9313058985b68e8dc31 --- /dev/null +++ b/scripts/chain_coast_ablation.sh @@ -0,0 +1,107 @@ +#!/bin/bash +# Closed-loop coasting-horizon ablation: 1 s and 4 s arms next to the 2 s arm of chain_tracker_finetune.sh. +# 1. once the main chain has written its banks (detections cached in simlingo_data/tracker_dets), re-run +# the tracker on CPU with max_coast_s = 1 and 4 -> simlingo_data/tracker_bank_coast{1,4} +# 2. wait for the main chain's three evals to finish (kills a CARLA whose worker log is idle > 30 min so +# the evaluator's watchdog retries the route) +# 3. fine-tune stage 3 on each bank set (4 GPUs each, grad accumulation 2 -> global batch 128) +# 4. four 220-route evals, 6 slots each: coast1 x2, coast4 x2, TRACKER_COAST_S matching the banks +set -u +cd /workspace/code/ConsDrive_v2_eval +PY=/venv/fastvlm/bin/python +B=eval_results/Bench2Drive +MAIN_LOG=/tmp/chain_tracker_ft.log +log() { echo "[$(date '+%F %T')] $*"; } + +# ---------------------------------------------------------------- 1. banks from cached detections +until grep -q "fine-tune ->" $MAIN_LOG 2>/dev/null; do + grep -qE "failed|incomplete" $MAIN_LOG 2>/dev/null && { log "main chain failed"; exit 1; } + sleep 60 +done +n_det=$(find simlingo_data/tracker_dets -name dets.npz | wc -l) +log "cached detections: $n_det" +for c in 1 4; do + for s in $(seq 0 23); do + CUDA_VISIBLE_DEVICES= OMP_NUM_THREADS=1 $PY scripts/eval_tracker_offline.py --detector none \ + --out eval_results/tracker_offline/banks_coast$c --split all --shard $s/24 --reuse-detections \ + --write-banks --bank-folder tracker_bank_coast$c --max-coast-s $c --skip-existing \ + > eval_results/tracker_offline/banks_coast${c}_shard$s.log 2>&1 & + done + wait + n=$(find simlingo_data/tracker_bank_coast$c -name objects.npz | wc -l) + log "coast $c banks: $n / $n_det" + [ "$n" -eq "$n_det" ] || { log "coast $c bank coverage incomplete"; exit 1; } +done + +# ---------------------------------------------------------------- 2. wait for the main chain's evals +until grep -q "evals launched" $MAIN_LOG 2>/dev/null; do + grep -qE "failed|incomplete" $MAIN_LOG 2>/dev/null && { log "main chain failed"; exit 1; } + sleep 120 +done +MAIN_EVALS="tracker_ft_det4hz_mask15 tracker_ft_det4hz_mask15_repeat speeddrop_det4hz_mask15_zeroshot" +all_done() { + for r in $MAIN_EVALS; do + [ "$(grep -l WORKER_EXIT $B/$r/logs/w*.log 2>/dev/null | wc -l)" -ge 16 ] || return 1 + done +} +until all_done; do + now=$(date +%s) + for r in $MAIN_EVALS; do + for f in $B/$r/logs/w*.log; do + [ -f "$f" ] || continue + grep -q WORKER_EXIT "$f" && continue + if [ $((now - $(stat -c %Y "$f"))) -gt 1800 ]; then + w=$(basename "$f" .log) + port=$(grep -oE -- "--port [0-9]+" $B/$r/scripts/run_$w.sh | awk '{print $2}') + log "worker $r/$w idle > 30 min, killing CARLA on port $port" + pkill -9 -f "carla-rpc-port=$port( |$)" + touch "$f" + fi + done + done + sleep 300 +done +log "main chain evals finished" + +# ---------------------------------------------------------------- 3. fine-tunes (4 GPUs each, in parallel) +STAMP=$(date +%Y-%m-%d_%H-%M-%S) +declare -A FT +pids=() +for c in 1 4; do + FT[$c]=outputs/fastvlm_stage3_tracker_coast$c/$STAMP + gpus=$([ $c = 1 ] && echo 0,1,2,3 || echo 4,5,6,7) + CUDA_VISIBLE_DEVICES=$gpus TRACKER_BANK_FOLDER=tracker_bank_coast$c CONFIG_NAME=fastvlm_stage3_tracker \ + OUTPUT_DIR=${FT[$c]} bash scripts/run_train_fastvlm_stage3.sh \ + trainer.devices=4 +trainer.accumulate_grad_batches=2 > /dev/null 2>&1 & + pids+=($!) +done +rc=0 +for p in "${pids[@]}"; do wait $p || rc=1; done +for c in 1 4; do + ls ${FT[$c]}/checkpoints/epoch=*.ckpt > /dev/null 2>&1 || rc=1 + echo "TRAIN_EXIT=$rc" >> ${FT[$c]}/train.log +done +[ $rc -eq 0 ] || { log "a coast fine-tune failed"; exit 1; } +log "fine-tunes done: ${FT[1]} ${FT[4]}" + +# ---------------------------------------------------------------- 4. evals +DET=/workspace/code/ConsDrive_v2_eval/outputs/detector/det_v1/last.pt +slots() { # eval index k, slot count n (two workers per slot) + local k=$1 n=$2 s="" j + for ((j = 0; j < n; j++)); do s+="$(( (j + 2 * k) % 8 )):$(( (j + k) % 7 )) "; done + echo "${s% }" +} +launch() { # k run_dir name n_slots extra_env + RUN_DIR=$2 RESULT_ROOT=$B/$3 SLOTS="$(slots $1 $4)" TAG=$3 \ + PORT_BASE=$((20000 + 2000 * $1)) TM_PORT_BASE=$((30000 + 2000 * $1)) EXTRA_ENV="$5" \ + bash scripts/run_full220_fastvlm.sh +} +k=0 +for c in 1 4; do + for rep in "" _repeat; do + launch $k ${FT[$c]} tracker_ft_coast${c}_det4hz_mask15$rep 6 \ + "OBJECT_SOURCE=detector DETECTOR_CKPT=$DET DETECTOR_UPDATE_EVERY=5 SPEED_MASK_STALL_S=15 TRACKER_COAST_S=$c" + k=$((k + 1)) + done +done +log "coast evals launched" diff --git a/scripts/chain_stream_petr.sh b/scripts/chain_stream_petr.sh new file mode 100644 index 0000000000000000000000000000000000000000..991b72ac230bed7db467d06c4557791c1a78f056 --- /dev/null +++ b/scripts/chain_stream_petr.sh @@ -0,0 +1,93 @@ +#!/bin/bash +# StreamPETR perception pipeline, after outputs/stream_petr/sp_v1 (train_stream_petr.py, all routes) finishes: +# 1. offline detector + tracker eval of sp_v1 on the val routes and the 311-route train subset +# (eval_results/tracker_offline/sp_v1_{val,train}; compare with det_v1_{val,train}) +# 2. cross-fitting: two streaming detectors each trained without one half of the routes +# (outputs/stream_petr/sp_fold{0,1}of2, 4 GPUs each, steps from /tmp/sp_fold_steps) +# 3. tracker banks from the out-of-fold detector (simlingo_data/tracker_bank_sp, detections cached in +# tracker_dets_sp), 8 shards per fold +# 4. stage-3 fine-tune (config/fastvlm_stage3_tracker.yaml, TRACKER_BANK_FOLDER=tracker_bank_sp) +# 5. closed-loop 220-route evals: fine-tuned x2, plus the det_v1-bank fine-tuned model with the +# StreamPETR detector zero-shot; all OBJECT_SOURCE=detector DETECTOR_UPDATE_EVERY=5 SPEED_MASK_STALL_S=15 +set -u +cd /workspace/code/ConsDrive_v2_eval +PY=/venv/fastvlm/bin/python +log() { echo "[$(date '+%F %T')] $*"; } +SP=outputs/stream_petr +OUT=eval_results/tracker_offline + +until [ -f $SP/sp_v1/val_030000.json ] && ! pgrep -f "train_stream_petr.py --out $SP/sp_v1" > /dev/null; do sleep 60; done +log "sp_v1 training done" + +# 1. offline eval (GPU 0 and 1), concurrently with the fold trainings below +CUDA_VISIBLE_DEVICES=0 OMP_NUM_THREADS=4 $PY scripts/eval_tracker_offline.py --detector $SP/sp_v1/last.pt \ + --out $OUT/sp_v1_val --split val --decode-threads 6 > $OUT/sp_v1_val.log 2>&1 & +CUDA_VISIBLE_DEVICES=1 OMP_NUM_THREADS=4 $PY scripts/eval_tracker_offline.py --detector $SP/sp_v1/last.pt \ + --out $OUT/sp_v1_train --split train --sample-routes 311 --seed 0 --decode-threads 6 > $OUT/sp_v1_train.log 2>&1 & + +# 2. fold detectors +STEPS=$(cat /tmp/sp_fold_steps 2>/dev/null || echo 24000) +log "fold detectors: $STEPS steps each" +for k in 0 1; do + mkdir -p $SP/sp_fold${k}of2 + ( + CUDA_VISIBLE_DEVICES=$((4 * k)),$((4 * k + 1)),$((4 * k + 2)),$((4 * k + 3)) \ + $PY -m torch.distributed.run --nproc_per_node=4 --master_port=$((29620 + k)) train_stream_petr.py \ + --out $SP/sp_fold${k}of2 --holdout-fold $k/2 --steps $STEPS --val-every 4000 --batch 8 --workers 10 \ + > $SP/sp_fold${k}of2/train.log 2>&1 + echo "TRAIN_EXIT=$?" >> $SP/sp_fold${k}of2/train.log + ) & +done +wait +for k in 0 1; do + grep -q "TRAIN_EXIT=0" $SP/sp_fold${k}of2/train.log || { log "fold $k detector failed"; exit 1; } +done +log "fold detectors done; offline eval sp_v1: $(tail -n 1 $OUT/sp_v1_val.log)" + +# 3. banks +for k in 0 1; do + for s in 0 1 2 3 4 5 6 7; do + gpu=$((4 * k + s / 2)) + CUDA_VISIBLE_DEVICES=$gpu OMP_NUM_THREADS=4 $PY scripts/eval_tracker_offline.py \ + --detector $SP/sp_fold${k}of2/last.pt --out $OUT/banks_sp_fold$k --split all --fold $k/2 \ + --shard $s/8 --write-banks --bank-folder tracker_bank_sp --skip-existing --decode-threads 6 \ + --save-detections --detections-folder tracker_dets_sp \ + > $OUT/banks_sp_fold${k}_shard$s.log 2>&1 & + done +done +wait +n_bank=$(find simlingo_data/tracker_bank_sp -name objects.npz | wc -l) +n_oracle=$(find simlingo_data/object_bank -name objects.npz | wc -l) +log "tracker banks (sp): $n_bank / $n_oracle" +[ "$n_bank" -eq "$n_oracle" ] || { log "bank coverage incomplete"; exit 1; } + +# 4. fine-tune +FT=outputs/fastvlm_stage3_tracker_sp/$(date +%Y-%m-%d_%H-%M-%S) +echo "$FT" > /tmp/stage3_tracker_sp_outdir +log "fine-tune -> $FT" +TRACKER_BANK_FOLDER=tracker_bank_sp CONFIG_NAME=fastvlm_stage3_tracker OUTPUT_DIR=$FT \ + bash scripts/run_train_fastvlm_stage3.sh > /dev/null 2>&1 +rc=$? +echo "TRAIN_EXIT=$rc" >> $FT/train.log +[ $rc -eq 0 ] || { log "fine-tune failed ($rc)"; exit 1; } +log "fine-tune done: $(ls $FT/checkpoints)" + +# 5. closed-loop evals +DET=/workspace/code/ConsDrive_v2_eval/$SP/sp_v1/last.pt +ENV="OBJECT_SOURCE=detector DETECTOR_CKPT=$DET DETECTOR_UPDATE_EVERY=5 SPEED_MASK_STALL_S=15" +FT_DETV1=outputs/fastvlm_stage3_tracker/2026-11-02_17-25-27 +B=eval_results/Bench2Drive +slots() { # eval index k, slot count n (two workers per slot) + local k=$1 n=$2 s="" j + for ((j = 0; j < n; j++)); do s+="$(( (j + 2 * k) % 8 )):$(( (j + k) % 7 )) "; done + echo "${s% }" +} +launch() { # k run_dir name n_slots extra_env + RUN_DIR=$2 RESULT_ROOT=$B/$3 SLOTS="$(slots $1 $4)" TAG=$3 \ + PORT_BASE=$((20000 + 2000 * $1)) TM_PORT_BASE=$((30000 + 2000 * $1)) EXTRA_ENV="$5" \ + bash scripts/run_full220_fastvlm.sh +} +launch 0 $FT sp_ft_det4hz_mask15 8 "$ENV" +launch 1 $FT sp_ft_det4hz_mask15_repeat 8 "$ENV" +launch 2 $FT_DETV1 tracker_ft_spdet4hz_mask15_zeroshot 8 "$ENV" +log "evals launched" diff --git a/scripts/chain_stream_petr_ablation.sh b/scripts/chain_stream_petr_ablation.sh new file mode 100644 index 0000000000000000000000000000000000000000..f05c0fda7860f8e0928bad98ca0ab028e3a52ead --- /dev/null +++ b/scripts/chain_stream_petr_ablation.sh @@ -0,0 +1,77 @@ +#!/bin/bash +# Speed-dropout ablation on StreamPETR perception, appended to chain_stream_petr.sh: +# 1. wait for the main chain's three evals to finish (kills a CARLA whose worker log is idle > 30 min so +# the evaluator's watchdog retries the route) +# 2. fine-tune the *no-dropout* oracle stage-3 checkpoint on tracker_bank_sp for 1 epoch +# (speed_dropout_p = 0, otherwise the recipe of config/fastvlm_stage3_tracker.yaml) +# 3. two 220-route evals, 8 slots each, StreamPETR detector at 4 Hz, no speed mask: +# nodrop_sp_ft_det4hz_nomask - the fine-tune of step 2 +# sp_ft_det4hz_nomask - the main chain's speed-dropout fine-tune with SPEED_MASK_STALL_S unset +set -u +cd /workspace/code/ConsDrive_v2_eval +PY=/venv/fastvlm/bin/python +B=eval_results/Bench2Drive +MAIN_LOG=/tmp/chain_sp.log +log() { echo "[$(date '+%F %T')] $*"; } + +# ---------------------------------------------------------------- 1. wait for the main chain's evals +until grep -q "evals launched" $MAIN_LOG 2>/dev/null; do + grep -qE "failed|incomplete" $MAIN_LOG 2>/dev/null && { log "main chain failed"; exit 1; } + sleep 120 +done +FT_SP=$(cat /tmp/stage3_tracker_sp_outdir) +log "main chain evals launched; speed-dropout fine-tune: $FT_SP" +MAIN_EVALS="sp_ft_det4hz_mask15 sp_ft_det4hz_mask15_repeat tracker_ft_spdet4hz_mask15_zeroshot" +all_done() { + for r in $MAIN_EVALS; do + [ "$(grep -l WORKER_EXIT $B/$r/logs/w*.log 2>/dev/null | wc -l)" -ge 16 ] || return 1 + done +} +until all_done; do + now=$(date +%s) + for r in $MAIN_EVALS; do + for f in $B/$r/logs/w*.log; do + [ -f "$f" ] || continue + grep -q WORKER_EXIT "$f" && continue + if [ $((now - $(stat -c %Y "$f"))) -gt 1800 ]; then + w=$(basename "$f" .log) + port=$(grep -oE -- "--port [0-9]+" $B/$r/scripts/run_$w.sh | awk '{print $2}') + log "worker $r/$w idle > 30 min, killing CARLA on port $port" + pkill -9 -f "carla-rpc-port=$port( |$)" + touch "$f" + fi + done + done + sleep 300 +done +log "main chain evals finished" + +# ---------------------------------------------------------------- 2. no-dropout fine-tune on tracker_bank_sp +ORACLE=outputs/fastvlm_stage3_oracle/2026-11-01_07-40-56/checkpoints/epoch=002.ckpt +FT_ND=outputs/fastvlm_stage3_tracker_sp_nodrop/$(date +%Y-%m-%d_%H-%M-%S) +echo "$FT_ND" > /tmp/stage3_tracker_sp_nodrop_outdir +log "no-dropout fine-tune -> $FT_ND" +STAGE3_CHECKPOINT=$ORACLE TRACKER_BANK_FOLDER=tracker_bank_sp CONFIG_NAME=fastvlm_stage3_tracker OUTPUT_DIR=$FT_ND \ + bash scripts/run_train_fastvlm_stage3.sh model.speed_dropout_p=0 > /dev/null 2>&1 +rc=$? +ls $FT_ND/checkpoints/epoch=*.ckpt > /dev/null 2>&1 || rc=1 +echo "TRAIN_EXIT=$rc" >> $FT_ND/train.log +[ $rc -eq 0 ] || { log "no-dropout fine-tune failed ($rc)"; exit 1; } +log "no-dropout fine-tune done: $(ls $FT_ND/checkpoints)" + +# ---------------------------------------------------------------- 3. evals (no speed mask) +DET=/workspace/code/ConsDrive_v2_eval/outputs/stream_petr/sp_v1/last.pt +ENV="OBJECT_SOURCE=detector DETECTOR_CKPT=$DET DETECTOR_UPDATE_EVERY=5" +slots() { # eval index k, slot count n (two workers per slot) + local k=$1 n=$2 s="" j + for ((j = 0; j < n; j++)); do s+="$(( (j + 2 * k) % 8 )):$(( (j + k) % 7 )) "; done + echo "${s% }" +} +launch() { # k run_dir name n_slots extra_env + RUN_DIR=$2 RESULT_ROOT=$B/$3 SLOTS="$(slots $1 $4)" TAG=$3 \ + PORT_BASE=$((20000 + 2000 * $1)) TM_PORT_BASE=$((30000 + 2000 * $1)) EXTRA_ENV="$5" \ + bash scripts/run_full220_fastvlm.sh +} +launch 0 $FT_ND nodrop_sp_ft_det4hz_nomask 8 "$ENV" +launch 1 $FT_SP sp_ft_det4hz_nomask 8 "$ENV" +log "ablation evals launched" diff --git a/scripts/chain_tracker_finetune.sh b/scripts/chain_tracker_finetune.sh new file mode 100644 index 0000000000000000000000000000000000000000..26f3d7baefdd645b9ef07fc36a6308d4d6b3d6ad --- /dev/null +++ b/scripts/chain_tracker_finetune.sh @@ -0,0 +1,64 @@ +#!/bin/bash +# Cross-fitted tracker banks -> stage-3 fine-tune on them -> closed-loop evals with the 4 Hz det_v1 tracker. +# 1. wait for outputs/detector/det_fold{0,1}of2 (each trained without its fold's routes) +# 2. tracker banks: fold-k routes through the fold-k detector (8 shards per fold, 2 per GPU); the +# per-frame detections are cached in simlingo_data/tracker_dets so other tracker settings can be +# re-run on CPU (scripts/chain_coast_ablation.sh) +# 3. fine-tune config/fastvlm_stage3_tracker.yaml (from the speed-dropout stage-3 checkpoint) +# 4. three 220-route evals: fine-tuned x2 and the speed-dropout checkpoint zero-shot, all with +# OBJECT_SOURCE=detector (det_v1) DETECTOR_UPDATE_EVERY=5 SPEED_MASK_STALL_S=15 +set -u +cd /workspace/code/ConsDrive_v2_eval +PY=/venv/fastvlm/bin/python +log() { echo "[$(date '+%F %T')] $*"; } + +for k in 0 1; do + until grep -q "TRAIN_EXIT=" outputs/detector/det_fold${k}of2/train.log 2>/dev/null; do sleep 60; done + grep -q "TRAIN_EXIT=0" outputs/detector/det_fold${k}of2/train.log || { log "fold $k detector failed"; exit 1; } +done +log "fold detectors done" + +OUT=eval_results/tracker_offline +for k in 0 1; do + for s in 0 1 2 3 4 5 6 7; do + gpu=$((4 * k + s / 2)) + CUDA_VISIBLE_DEVICES=$gpu OMP_NUM_THREADS=4 $PY scripts/eval_tracker_offline.py \ + --detector outputs/detector/det_fold${k}of2/last.pt --out $OUT/banks_fold$k --split all --fold $k/2 \ + --shard $s/8 --write-banks --bank-folder tracker_bank --skip-existing --decode-threads 6 \ + --save-detections --detections-folder tracker_dets \ + > $OUT/banks_fold${k}_shard$s.log 2>&1 & + done +done +wait +n_bank=$(find simlingo_data/tracker_bank -name objects.npz | wc -l) +n_oracle=$(find simlingo_data/object_bank -name objects.npz | wc -l) +log "tracker banks: $n_bank / $n_oracle" +[ "$n_bank" -eq "$n_oracle" ] || { log "bank coverage incomplete"; exit 1; } + +FT=outputs/fastvlm_stage3_tracker/$(date +%Y-%m-%d_%H-%M-%S) +echo "$FT" > /tmp/stage3_tracker_outdir +log "fine-tune -> $FT" +CONFIG_NAME=fastvlm_stage3_tracker OUTPUT_DIR=$FT bash scripts/run_train_fastvlm_stage3.sh > /dev/null 2>&1 +rc=$? +echo "TRAIN_EXIT=$rc" >> $FT/train.log +[ $rc -eq 0 ] || { log "fine-tune failed ($rc)"; exit 1; } +log "fine-tune done: $(ls $FT/checkpoints)" + +SD=outputs/fastvlm_stage3_speeddrop/2026-11-02_06-08-03 +DET=/workspace/code/ConsDrive_v2_eval/outputs/detector/det_v1/last.pt +ENV="OBJECT_SOURCE=detector DETECTOR_CKPT=$DET DETECTOR_UPDATE_EVERY=5 SPEED_MASK_STALL_S=15" +B=eval_results/Bench2Drive +slots() { # eval index k, slot count n (two workers per slot) + local k=$1 n=$2 s="" j + for ((j = 0; j < n; j++)); do s+="$(( (j + 2 * k) % 8 )):$(( (j + k) % 7 )) "; done + echo "${s% }" +} +launch() { # k run_dir name n_slots extra_env + RUN_DIR=$2 RESULT_ROOT=$B/$3 SLOTS="$(slots $1 $4)" TAG=$3 \ + PORT_BASE=$((20000 + 2000 * $1)) TM_PORT_BASE=$((30000 + 2000 * $1)) EXTRA_ENV="$5" \ + bash scripts/run_full220_fastvlm.sh +} +launch 0 $FT tracker_ft_det4hz_mask15 8 "$ENV" +launch 1 $FT tracker_ft_det4hz_mask15_repeat 8 "$ENV" +launch 2 $SD speeddrop_det4hz_mask15_zeroshot 8 "$ENV" +log "evals launched" diff --git a/scripts/check_bench2drive_complete.py b/scripts/check_bench2drive_complete.py new file mode 100644 index 0000000000000000000000000000000000000000..70fc7d045733b9d893bf05b5e3bf8d679f92ef43 --- /dev/null +++ b/scripts/check_bench2drive_complete.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Return 0 when all Bench2Drive worker checkpoints in a result root are finished.""" + +import argparse +import json +import sys +from pathlib import Path + + +def load_json(path: Path): + try: + with open(path, encoding="utf-8") as handle: + return json.load(handle) + except (OSError, json.JSONDecodeError): + return None + + +def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument("result_root", type=Path) + parser.add_argument( + "--workers", + type=int, + default=8, + help="Expected number of bench2drive220_worker_*.json files.", + ) + args = parser.parse_args() + + result_root = args.result_root.expanduser().resolve() + worker_files = sorted(result_root.glob("bench2drive220_worker_*.json")) + if len(worker_files) < args.workers: + print( + f"waiting: found {len(worker_files)}/{args.workers} worker checkpoints", + file=sys.stderr, + ) + return 1 + + total_records = 0 + for worker_file in worker_files: + data = load_json(worker_file) + if not isinstance(data, dict): + print(f"waiting: invalid checkpoint {worker_file.name}", file=sys.stderr) + return 1 + if data.get("entry_status") != "Finished": + print( + f"waiting: {worker_file.name} entry_status={data.get('entry_status')}", + file=sys.stderr, + ) + return 1 + records = data.get("_checkpoint", {}).get("records", []) + total_records += len(records) + + print(f"complete: {len(worker_files)} workers, {total_records} route records") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/clean_carla.sh b/scripts/clean_carla.sh new file mode 100644 index 0000000000000000000000000000000000000000..bcc53f25c1efa73a995a30e892daf15b782a77fe --- /dev/null +++ b/scripts/clean_carla.sh @@ -0,0 +1,6 @@ +#!/bin/bash +killall -9 -r CarlaUE4-Linux +ps -ef | grep "carla-rpc-port" | awk '{print $2}' | xargs kill > /dev/null 2>&1 & +ps -ef | grep "run_evaluation" | awk '{print $2}' | xargs kill > /dev/null 2>&1 & +ps -ef | grep "leaderboard_evaluator" | awk '{print $2}' | xargs kill > /dev/null 2>&1 & +wait \ No newline at end of file diff --git a/scripts/eval_tracker_offline.py b/scripts/eval_tracker_offline.py new file mode 100644 index 0000000000000000000000000000000000000000..a3c1ec97a1e074bfe2b8844907c58cc52fa3ab7c --- /dev/null +++ b/scripts/eval_tracker_offline.py @@ -0,0 +1,385 @@ +"""Offline detector + tracker evaluation on whole SimLingo routes, against the oracle object bank. + +Runs models/detector.py frame by frame (4 Hz logs, consecutive frames as the two-frame input) and +team_code/tracker.py on the ground-truth ego pose, then compares the tracker's rows with the oracle +bank rows the stage-3 model was trained on (object_bank/.../objects.npz) in the tracker acceptance +terms: recall of visible bank objects per range bin, false tracks per second, position / speed / +heading errors and identity switches. Optionally writes the tracker rows per route in the bank +layout (--write-banks) for stage-3 fine-tuning on real perception; relation labels move from the +oracle bank to the matched tracks, unmatched tracks are labelled ignore. + +Usage: python scripts/eval_tracker_offline.py --detector outputs/detector//last.pt --out + [--split train|val|all] [--sample-routes N] [--shard K/N] [--write-banks [--bank-folder F]] + [--save-detections | --reuse-detections] (cache detections once, re-run the tracker on CPU) +""" +import argparse +import json +import sys +import time +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path + +import numpy as np +import torch +from scipy.optimize import linear_sum_assignment + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +from dataloader.detection_data import CAMERA_X, DetectionDataset, ego_motion, load_image, route_fold # noqa: E402 +from dataloader.detection_labels import EGO_X, EGO_Y, EGO_YAW, OBJ_X, OBJ_Y # noqa: E402 +from dataloader.object_bank import ( # noqa: E402 + RAW_CLASS, RAW_DIM, RAW_SPEED, RAW_VISIBLE, RAW_X, RAW_Y, RAW_YAW, RELATION_IGNORE, RELATION_PAD, +) +from models.detector import decode, load_detector # noqa: E402 +from team_code.tracker import Tracker, TrackerConfig, detections_to_world # noqa: E402 + +FRAME_DT = 0.25 +RANGE_BINS = ((0, 10), (10, 20), (20, 30), (30, 40), (40, 50)) + + +def run_route(model, route_dir, objects, count, ego, device, score_threshold, tracker_cfg, batch=32, pool=None): + """Detector outputs for every frame (pairs f-1, f), then the tracker over the sequence.""" + dets = detect_route(model, route_dir, len(count), ego, device, score_threshold, batch, pool) + return track_route(dets, ego, score_threshold, tracker_cfg) + + +@torch.no_grad() +def detect_route(model, route_dir, n, ego, device, score_threshold, batch=32, pool=None): + """Decoded detections (scores >= min(score_threshold, 0.2)) per frame; None for frame 0.""" + dets = [None] * n + for start in range(1, n, batch): + frames = list(range(start, min(n, start + batch))) + paths = [f"{route_dir}/rgb/{f:04d}.jpg" for f in range(start - 1, frames[-1] + 1)] + window = torch.stack(list(pool.map(load_image, paths)) if pool else [load_image(p) for p in paths]) + window = window.to(device) + img, prev = window[1:], window[:-1] + motion = torch.stack([torch.from_numpy(ego_motion(ego[f - 1], ego[f])) for f in frames]).to(device) + with torch.autocast("cuda", dtype=torch.bfloat16): + out, _ = model(img, prev, motion) + for f, d in zip(frames, decode(out, score_threshold=min(score_threshold, 0.2))): + dets[f] = {k: v.float().cpu().numpy() for k, v in d.items()} + return dets + + +@torch.no_grad() +def detect_routes_stream(model, route_dirs, lengths, egos, device, score_threshold, pool=None): + """Streaming detector (models/stream_petr.py) over several routes in lockstep: one image per route per + step, memory reset at the start; shorter routes are padded with their last frame. Returns per-route + detection lists (frame 0 included, as the detector needs no earlier frame).""" + from models.stream_petr import decode_stream + + b, n_max = len(route_dirs), max(lengths) + dets = [[None] * n for n in lengths] + model.reset_memory() + for f in range(n_max): + fs = [min(f, n - 1) for n in lengths] + paths = [f"{d}/rgb/{fi:04d}.jpg" for d, fi in zip(route_dirs, fs)] + images = torch.stack(list(pool.map(load_image, paths)) if pool else [load_image(p) for p in paths]).to(device) + pose = torch.tensor(np.stack([e[fi, [EGO_X, EGO_Y, EGO_YAW]] for e, fi in zip(egos, fs)]), + dtype=torch.float32, device=device) + time_t = torch.tensor([fi * FRAME_DT for fi in fs], dtype=torch.float32, device=device) + with torch.autocast("cuda", dtype=torch.bfloat16): + out = model(images, pose, time_t) + for i, d in enumerate(decode_stream(out, score_threshold=min(score_threshold, 0.2))): + if f < lengths[i]: + dets[i][f] = {k: v.float().cpu().numpy() for k, v in d.items() if k in DET_KEYS_ALL} + model.reset_memory() + return dets + + +def load_any_detector(path, device): + """(model, is_stream) for a train_detector.py or train_stream_petr.py checkpoint.""" + args = torch.load(path, map_location="cpu", weights_only=False).get("args", {}) + if "num_queries" in args: + from models.stream_petr import load_stream_petr + + return load_stream_petr(path, device), True + return load_detector(path, device), False + + +DET_KEYS = ("x", "y", "z", "yaw", "speed", "vx", "vy", "half_l", "half_w", "half_h", "cls", "score", "depth_sigma") +DET_KEYS_ALL = (*DET_KEYS, "velocity_sigma") + + +def save_detections(path, dets): + """Per-frame detections (detect_route output) -> one flat npz so the tracker can be re-run without the model.""" + frames = [f for f, d in enumerate(dets) if d is not None] + arrays = {k: np.concatenate([dets[f][k] for f in frames]) if frames else np.zeros(0) for k in DET_KEYS} + arrays["velocity_sigma"] = (np.concatenate([dets[f]["velocity_sigma"] for f in frames]) if frames + else np.zeros((0, 2))) + arrays["frame"] = np.concatenate([np.full(len(dets[f]["score"]), f, dtype=np.int32) for f in frames]) \ + if frames else np.zeros(0, dtype=np.int32) + path.parent.mkdir(parents=True, exist_ok=True) + tmp = path.with_suffix(".tmp.npz") + np.savez(tmp, n_frames=np.int32(len(dets)), **{k: v.astype(np.float32) if k != "frame" else v + for k, v in arrays.items()}) + tmp.rename(path) + + +def load_detections(path): + with np.load(path) as z: + n, frame = int(z["n_frames"]), z["frame"] + data = {k: z[k] for k in (*DET_KEYS, "velocity_sigma")} + dets = [None] * n + for f in range(n): + sel = frame == f + if f == 0 and not sel.any(): + continue # two-frame detector: no detections on a route's first frame + dets[f] = {k: v[sel] for k, v in data.items()} + return dets + + +def track_route(dets, ego, score_threshold, tracker_cfg): + """Tracker rows over a route from per-frame detections (detect_route).""" + n = len(dets) + tracker = Tracker(tracker_cfg) + rows = np.zeros((n, tracker_cfg.max_objects, RAW_DIM), dtype=np.float32) + ids = np.zeros((n, tracker_cfg.max_objects), dtype=np.int64) + counts = np.zeros(n, dtype=np.int16) + for f in range(n): + ego_xy, ego_yaw = ego[f, [EGO_X, EGO_Y]].astype(np.float64), float(ego[f, EGO_YAW]) + world = [] + if dets[f] is not None: + keep = dets[f]["score"] >= score_threshold + world = detections_to_world({k: v[keep] for k, v in dets[f].items()}, ego_xy, ego_yaw) + rows[f], ids[f], counts[f] = tracker.step(f * FRAME_DT, world, ego_xy, ego_yaw) + return rows, ids, counts + + +def match_rows(g_xy, p_xy): + """Bank row index -> tracker row index (-1 if unmatched), Hungarian within 1.5 m + 5% of range.""" + assigned = np.full(len(g_xy), -1) + if len(g_xy) and len(p_xy): + g_rng = np.hypot(g_xy[:, 0] - CAMERA_X, g_xy[:, 1]) + d = np.linalg.norm(g_xy[:, None] - p_xy[None], axis=-1) + cost = np.where(d <= (1.5 + 0.05 * g_rng)[:, None], d, 1e6) + r, c = linear_sum_assignment(cost) + keep = cost[r, c] < 1e5 + assigned[r[keep]] = c[keep] + return assigned + + +def transfer_relations(bank_raw, bank_rel, bank_count, trk_raw, trk_count): + """Relation labels for tracker rows: the label of the matched bank object, ignore for unmatched tracks.""" + rel = np.full(trk_raw.shape[:2], RELATION_PAD, dtype=np.int8) + for f in range(len(trk_count)): + rel[f, :trk_count[f]] = RELATION_IGNORE + g = bank_raw[f, :bank_count[f]].astype(np.float64) + p = trk_raw[f, :trk_count[f]].astype(np.float64) + assigned = match_rows(g[:, [RAW_X, RAW_Y]], p[:, [RAW_X, RAW_Y]]) + for i in np.nonzero(assigned >= 0)[0]: + rel[f, assigned[i]] = bank_rel[f, i] + return rel + + +class TrackMetrics: + """Tracker rows vs oracle bank rows, frame by frame.""" + + def __init__(self): + self.gt = [] # range, class, visible, matched, pos err, speed gt, speed err, yaw err + self.false_tracks = 0 + self.frames = 0 + self.id_switches = 0 + self.matched_pairs = 0 + + def add_route(self, bank_raw, bank_ids, bank_count, trk_raw, trk_count, trk_ids, labels, label_count): + last_track_of = {} + for f in range(len(bank_count)): + self.frames += 1 + g = bank_raw[f, :bank_count[f]].astype(np.float64) + p = trk_raw[f, :trk_count[f]].astype(np.float64) + g_xy, p_xy = g[:, [RAW_X, RAW_Y]], p[:, [RAW_X, RAW_Y]] + g_rng = np.hypot(g_xy[:, 0] - CAMERA_X, g_xy[:, 1]) + assigned = match_rows(g_xy, p_xy) + for i in range(len(g)): + j = assigned[i] + if j >= 0: + gv = g[i, RAW_SPEED] * np.array((np.cos(g[i, RAW_YAW]), np.sin(g[i, RAW_YAW]))) + pv = p[j, RAW_SPEED] * np.array((np.cos(p[j, RAW_YAW]), np.sin(p[j, RAW_YAW]))) + yaw_err = abs(np.angle(np.exp(1j * (p[j, RAW_YAW] - g[i, RAW_YAW])))) + self.gt.append((g_rng[i], g[i, RAW_CLASS], g[i, RAW_VISIBLE], 1.0, + np.linalg.norm(g_xy[i] - p_xy[j]), g[i, RAW_SPEED], np.linalg.norm(gv - pv), yaw_err)) + gid, tid = int(bank_ids[f, i]), int(trk_ids[f, j]) + if gid in last_track_of and last_track_of[gid] != tid: + self.id_switches += 1 + last_track_of[gid] = tid + self.matched_pairs += 1 + else: + self.gt.append((g_rng[i], g[i, RAW_CLASS], g[i, RAW_VISIBLE], 0.0, np.nan, g[i, RAW_SPEED], np.nan, np.nan)) + # false track: no labelled box at all (visible or not) near it + lab = labels[f, :label_count[f]] + l_xy = lab[:, [OBJ_X, OBJ_Y]].astype(np.float64) + for j in range(len(p)): + prng = np.hypot(p_xy[j, 0] - CAMERA_X, p_xy[j, 1]) + if prng > 50.0 or j in assigned: + continue + near_label = len(l_xy) and np.min(np.linalg.norm(l_xy - p_xy[j], axis=-1)) <= 1.5 + 0.05 * prng + near_bank = len(g_xy) and np.min(np.linalg.norm(g_xy - p_xy[j], axis=-1)) <= 1.5 + 0.05 * prng + if not near_label and not near_bank: + self.false_tracks += 1 + + def summary(self): + gt = np.asarray(self.gt, dtype=np.float64).reshape(-1, 8) + out = dict(frames=self.frames, seconds=self.frames * FRAME_DT, + false_tracks_per_s=self.false_tracks / max(self.frames * FRAME_DT, 1e-6), + id_switches_per_100_matches=100.0 * self.id_switches / max(self.matched_pairs, 1)) + for c, name in enumerate(("car", "walker", "static")): + rows = {} + for lo, hi in RANGE_BINS: + sel = (gt[:, 1] == c) & (gt[:, 0] >= lo) & (gt[:, 0] < hi) + vis, mem = sel & (gt[:, 2] > 0.5), sel & (gt[:, 2] <= 0.5) + m = vis & (gt[:, 3] > 0) + rows[f"{lo}-{hi}"] = dict( + n_visible=int(vis.sum()), recall_visible=float(gt[vis, 3].mean()) if vis.any() else None, + recall_memory=float(gt[mem, 3].mean()) if mem.any() else None, + pos_err_med=float(np.median(gt[m, 4])) if m.any() else None, + pos_err_p90=float(np.percentile(gt[m, 4], 90)) if m.any() else None, + vel_err_med=float(np.median(gt[m, 6])) if m.any() else None) + out[name] = rows + cars = gt[(gt[:, 1] == 0) & (gt[:, 2] > 0.5) & (gt[:, 3] > 0) & (gt[:, 0] < 50)] + speed = {} + for lo, hi in ((0, 0.5), (0.5, 5), (5, 10), (10, 20)): + s = cars[(cars[:, 5] >= lo) & (cars[:, 5] < hi)] + if len(s): + speed[f"{lo}-{hi}"] = dict(n=len(s), vel_err_med=float(np.median(s[:, 6])), + vel_err_rms=float(np.sqrt(np.mean(s[:, 6] ** 2))), + target_sigma=0.3 + 0.1 * 0.5 * (lo + hi), + yaw_err_med_deg=float(np.degrees(np.median(s[:, 7])))) + out["car_velocity_by_speed"] = speed + return out + + +def format_summary(s): + lines = [f"{s['frames']} frames ({s['seconds']:.0f} s) false tracks/s {s['false_tracks_per_s']:.3f} " + f"id switches / 100 matches {s['id_switches_per_100_matches']:.2f}"] + f = lambda v, p=3: f"{v:6.{p}f}" if v is not None else " -" # noqa: E731 + for name in ("car", "walker", "static"): + lines.append(f"{name:7s} range n_vis rec_vis rec_mem err_med err_p90 vel_err") + for key, r in s[name].items(): + lines.append(f" {key:5s} {r['n_visible']:6d} {f(r['recall_visible'])} {f(r['recall_memory'])} " + f"{f(r['pos_err_med'], 2)} {f(r['pos_err_p90'], 2)} {f(r['vel_err_med'], 2)}") + for key, r in s["car_velocity_by_speed"].items(): + lines.append(f"car speed {key:7s} n={r['n']:6d} vel_err med {r['vel_err_med']:.2f} rms {r['vel_err_rms']:.2f} " + f"(target sigma {r['target_sigma']:.2f}) yaw_err med {r['yaw_err_med_deg']:.1f} deg") + return "\n".join(lines) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--detector", required=True) + ap.add_argument("--out", required=True) + ap.add_argument("--split", default="val", help="train | val | all") + ap.add_argument("--max-routes", type=int, default=0) + ap.add_argument("--sample-routes", type=int, default=0, help="random subset of this many routes (seeded)") + ap.add_argument("--seed", type=int, default=0) + ap.add_argument("--shard", default="0/1", help="K/N: process every N-th route starting at K") + ap.add_argument("--fold", default=None, + help="K/N: only routes of cross-fitting fold K (pair with a detector trained with " + "--holdout-fold K/N)") + ap.add_argument("--score-threshold", type=float, default=0.3) + ap.add_argument("--max-coast-s", type=float, default=2.0) + ap.add_argument("--write-banks", action="store_true") + ap.add_argument("--bank-folder", default="tracker_bank") + ap.add_argument("--skip-existing", action="store_true", help="skip routes whose bank file already exists") + ap.add_argument("--decode-threads", type=int, default=8) + ap.add_argument("--stream-batch", type=int, default=8, help="routes run in lockstep by the streaming detector") + ap.add_argument("--detections-folder", default="tracker_dets") + ap.add_argument("--save-detections", action="store_true", + help="cache the per-frame detections next to the banks (//dets.npz)") + ap.add_argument("--reuse-detections", action="store_true", + help="tracker-only run from cached detections (CPU); routes without a cache are skipped") + args = ap.parse_args() + device = torch.device("cuda") if not args.reuse_detections else None + shard, num_shards = (int(v) for v in args.shard.split("/")) + out = Path(args.out) / (f"shard_{shard}_of_{num_shards}" if num_shards > 1 else "") + out.mkdir(parents=True, exist_ok=True) + splits = ("train", "val") if args.split == "all" else (args.split,) + datasets = [DetectionDataset(split=s) for s in splits] + data_root = datasets[0].data_root + routes = [r for d in datasets for r in d.routes] + if args.sample_routes: + pick = np.random.default_rng(args.seed).choice(len(routes), size=min(args.sample_routes, len(routes)), + replace=False) + routes = [routes[i] for i in sorted(pick)] + if args.fold: + fold, num_folds = (int(v) for v in args.fold.split("/")) + routes = [r for r in routes + if route_fold(str(Path(r[0]).relative_to(data_root / "data")), num_folds) == fold] + routes = routes[: args.max_routes] if args.max_routes else routes + routes = routes[shard::num_shards] + model, is_stream = load_any_detector(args.detector, device) if not args.reuse_detections else (None, False) + cfg = TrackerConfig(max_coast_s=args.max_coast_s) + metrics = TrackMetrics() + pool = ThreadPoolExecutor(args.decode_threads) if args.decode_threads > 1 else None + t0 = time.time() + missing_cache = 0 + pending = [] # streaming detector: (index, route_dir, n, ego) of routes waiting for a lockstep batch + stream_dets = {} + + def flush_pending(): + if pending: + out_dets = detect_routes_stream(model, [p[1] for p in pending], [p[2] for p in pending], + [p[3] for p in pending], device, args.score_threshold, pool) + stream_dets.update({p[0]: d for p, d in zip(pending, out_dets)}) + pending.clear() + + for i, (route_dir, label_file) in enumerate(routes): + rel = Path(route_dir).relative_to(data_root / "data") + bank_file = data_root / "object_bank" / rel / "objects.npz" + dst = data_root / args.bank_folder / rel / "objects.npz" + det_file = data_root / args.detections_folder / rel / "dets.npz" + if not bank_file.exists() or (args.skip_existing and dst.exists()): + continue + if args.reuse_detections and not det_file.exists(): + missing_cache += 1 + continue + with np.load(label_file) as z: + labels, label_count, ego = z["objects"], z["count"], z["ego"] + with np.load(bank_file) as z: + bank_raw, bank_ids, bank_rel, bank_count = z["raw"], z["ids"], z["relation"], z["count"] + if args.reuse_detections: + dets = load_detections(det_file) + elif is_stream: + # detections for this route come from the lockstep batch it belongs to (routes are processed + # in order, so the batch is flushed as soon as this route's turn comes) + if i not in stream_dets: + j = i + while j < len(routes) and len(pending) < args.stream_batch: + rd, lf = routes[j] + rj = Path(rd).relative_to(data_root / "data") + bj, dj = data_root / "object_bank" / rj / "objects.npz", data_root / args.bank_folder / rj / "objects.npz" + if bj.exists() and not (args.skip_existing and dj.exists()): + with np.load(lf) as z: + ej, nj = z["ego"], len(z["count"]) + pending.append((j, rd, nj, ej)) + j += 1 + flush_pending() + dets = stream_dets.pop(i) + if args.save_detections: + save_detections(det_file, dets) + else: + dets = detect_route(model, route_dir, len(label_count), ego, device, args.score_threshold, pool=pool) + if args.save_detections: + save_detections(det_file, dets) + rows, ids, counts = track_route(dets, ego, args.score_threshold, cfg) + metrics.add_route(bank_raw, bank_ids, bank_count, rows, counts, ids, labels, label_count) + if args.write_banks: + relation = transfer_relations(bank_raw, bank_rel, bank_count, rows, counts) + dst.parent.mkdir(parents=True, exist_ok=True) + tmp = dst.with_suffix(".tmp.npz") + np.savez(tmp, raw=rows.astype(np.float16), ids=ids.astype(np.int32), relation=relation, count=counts, + frame_dt=np.float32(FRAME_DT), detector=np.array(str(args.detector))) + tmp.rename(dst) + if (i + 1) % 20 == 0 or i + 1 == len(routes): + print(f"[{i + 1}/{len(routes)}] {time.time() - t0:.0f}s", flush=True) + if missing_cache: + print(f"WARNING: {missing_cache} routes skipped, no cached detections", flush=True) + summary = metrics.summary() + summary["args"] = vars(args) + (out / "tracker_metrics.json").write_text(json.dumps(summary, indent=1)) + text = format_summary(summary) + (out / "tracker_metrics.txt").write_text(text + "\n") + print(text) + + +if __name__ == "__main__": + main() diff --git a/scripts/monitor_bench2drive.py b/scripts/monitor_bench2drive.py new file mode 100644 index 0000000000000000000000000000000000000000..cb4d4a544e574f5c6fb1860d949ba230725962fc --- /dev/null +++ b/scripts/monitor_bench2drive.py @@ -0,0 +1,86 @@ +#!/usr/bin/env python3 +"""Print a compact status table for parallel Bench2Drive workers.""" + +import argparse +import json +from pathlib import Path + + +RETRYABLE_STATUSES = { + "Started", + "Failed - Simulation crashed", + "Failed - Agent crashed", +} + + +def load_json(path): + try: + with open(path, encoding="utf-8") as file_handle: + return json.load(file_handle) + except (OSError, json.JSONDecodeError): + return None + + +def retry_state_path(result_file): + worker_label = result_file.stem.removeprefix("bench2drive220_") + return result_file.parent / f"retry_state_{worker_label}.json" + + +def worker_status(result_file): + data = load_json(result_file) + if not isinstance(data, dict): + return f"{result_file.stem:<52} waiting for a valid checkpoint" + + checkpoint = data.get("_checkpoint", {}) + progress = checkpoint.get("progress", ["?", "?"]) + records = checkpoint.get("records", []) + completed = progress[0] if len(progress) == 2 else "?" + total = progress[1] if len(progress) == 2 else "?" + + current = next( + ( + record + for record in records + if isinstance(record, dict) and record.get("status") in RETRYABLE_STATUSES + ), + None, + ) + last_record = records[-1] if records and isinstance(records[-1], dict) else {} + display_record = current or last_record + route_id = display_record.get("route_id", "-") + status = display_record.get("status", "-") + skipped = sum( + 1 + for record in records + if isinstance(record, dict) and record.get("status") == "Failed - Retry limit exceeded" + ) + + retries = 0 + retry_data = load_json(retry_state_path(result_file)) + if current and isinstance(retry_data, dict): + route_state = retry_data.get("routes", {}).get(route_id, {}) + retries = route_state.get("retries", 0) + + return ( + f"{result_file.stem:<52} " + f"progress={completed}/{total} entry={data.get('entry_status', '-'):<8} " + f"route={route_id:<28} retries={retries} skipped={skipped} status={status}" + ) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("result_root", type=Path) + args = parser.parse_args() + + result_files = sorted(args.result_root.glob("bench2drive220_worker_*.json")) + print(f"Bench2Drive results: {args.result_root}") + if not result_files: + print("Waiting for worker checkpoints...") + return + for result_file in result_files: + print(worker_status(result_file)) + + +if __name__ == "__main__": + main() diff --git a/scripts/pim_labels.py b/scripts/pim_labels.py new file mode 100644 index 0000000000000000000000000000000000000000..df1ca8b7248369f9adf12efa98810ee3177803af --- /dev/null +++ b/scripts/pim_labels.py @@ -0,0 +1,44 @@ +"""Validate/export reviewed PIM JSONL. Does not infer labels from object disappearance.""" +import argparse +import json +import sys +from pathlib import Path +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +from dataloader.pim_annotations import parse_annotation + + +def main(): + p=argparse.ArgumentParser(description=__doc__) + p.add_argument('jsonl',type=Path) + p.add_argument('--output-root',type=Path) + p.add_argument('--validate-only',action='store_true') + args=p.parse_args() + if not args.validate_only and args.output_root is None: + p.error('--output-root is required when exporting') + records=[]; seen=set() + for line_no,line in enumerate(args.jsonl.read_text().splitlines(),1): + if not line.strip(): continue + row=json.loads(line); route=Path(row['route']); frame=row['frame'] + if route.is_absolute() or '..' in route.parts or not route.parts: + raise ValueError(f'Line {line_no}: route must be relative to the data root') + if type(frame) is not int or frame<0: + raise ValueError(f'Line {line_no}: frame must be a nonnegative integer') + key=(str(route),frame) + if key in seen: raise ValueError(f'Line {line_no}: duplicate {key}') + seen.add(key) + payload={k:v for k,v in row.items() if k not in ('route','frame')} + parse_annotation(payload) + records.append((route,frame,payload)) + # Validate the whole input before writing any sidecars. + if not args.validate_only: + destinations=[args.output_root/route/'pim'/f'{frame:04d}.json' + for route,frame,_ in records] + if any(path.exists() for path in destinations): + raise FileExistsError('Export would replace existing labels; use a new output root') + for path,(_,_,payload) in zip(destinations,records): + path.parent.mkdir(parents=True,exist_ok=True) + path.write_text(json.dumps(payload,ensure_ascii=False,indent=2)+'\n') + print(f'Validated {len(records)} frames; exported={not args.validate_only}') + + +if __name__=='__main__': main() diff --git a/scripts/reproduce_pipeline.sh b/scripts/reproduce_pipeline.sh new file mode 100644 index 0000000000000000000000000000000000000000..caaa0f8e7611eff2bd349702e27d9be68d9d3abd --- /dev/null +++ b/scripts/reproduce_pipeline.sh @@ -0,0 +1,231 @@ +#!/bin/bash +# Retrain the best configuration from pretrained/FastVLM-0.5B and re-evaluate it on Bench2Drive-220: +# speed-dropout stage 3 fine-tuned on cross-fitted StreamPETR tracker banks, closed loop with the sp_v1 +# detector at 4 Hz and no speed mask (eval_results/Bench2Drive/sp_ft_det4hz_nomask*, 92.50 / 89.99 / 91.15 / +# 91.86 / 92.01, mean 91.50). Only the stages this model depends on are trained; same configs, seeds, step +# counts and global batch sizes as the original runs, output paths carry a tag. Every stage is skipped when +# its done-marker exists, so the script can be re-launched after a crash and continues where it stopped. +# +# nohup bash scripts/reproduce_pipeline.sh > /tmp/repro.log 2>&1 & +# tail -f outputs/repro_/chain.log +# +# Stages (wall time from the original runs on 8x RTX PRO 6000; all 8 GPUs unless noted): +# stage1 : train_fastvlm.py config/fastvlm_stage1.yaml, 6 epochs ~4 h +# speeddrop : stage 3 oracle config + model.speed_dropout_p=0.3, 3 epochs, init stage1 epoch 5 ~2 h +# det_v1 : train_detector.py, 30k steps (backbone init for the streaming detector) ~4.5 h +# sp_v1 : train_stream_petr.py, 30k steps, init det_v1 (the closed-loop detector) ~7 h +# folds : sp_fold0of2 / sp_fold1of2, 30k steps each, 4 GPUs each in parallel ~6.5 h +# banks : tracker banks of all routes from the out-of-fold detector, 16 shards ~2.5 h +# tracker_sp: stage 3 fine-tune on the banks, 1 epoch, init speeddrop epoch 2 ~40 min +# eval : N_EVAL_REPEATS x 220 routes, OBJECT_SOURCE=detector DETECTOR_UPDATE_EVERY=5, no mask ~1 h +# Total about 28 h. +# +# Knobs (environment): +# REPRO_TAG=repro1 suffix of every output dir (outputs//, outputs/stream_petr/sp_v1_, ...) +# N_EVAL_REPEATS=2 concurrent 220-route evals of the final model (single-run sd ~0.6 DS; 2 -> se 0.45) +# PRUNE_CHECKPOINTS=1 keep only the final epoch checkpoint of each Lightning stage (saves ~30 GB) +# SPEEDDROP_OVERRIDES="" original run used "trainer.devices=4 +trainer.accumulate_grad_batches=2" (same global +# batch 128, 2x slower); default trains on 8 GPUs without accumulation +# SEED=42 DET_SEED=0 Lightning seed / torchrun trainer seed (the originals) +# MIN_FREE_GB=60 abort at start when /workspace has less free space (new footprint is ~30 GB) +# FORCE=1 start even if other trainings / evals are running +# Afterwards: python scripts/analysis/compare_reproduction.py --tag +set -u +cd /workspace/code/ConsDrive_v2_eval +PY=/venv/fastvlm/bin/python +REPO=/workspace/code/ConsDrive_v2_eval + +TAG=${REPRO_TAG:-repro1} +N_EVAL_REPEATS=${N_EVAL_REPEATS:-2} +PRUNE_CHECKPOINTS=${PRUNE_CHECKPOINTS:-1} +SPEEDDROP_OVERRIDES=${SPEEDDROP_OVERRIDES:-""} +SEED=${SEED:-42} +DET_SEED=${DET_SEED:-0} +MIN_FREE_GB=${MIN_FREE_GB:-60} + +STATE=outputs/repro_$TAG +mkdir -p $STATE eval_results/tracker_offline eval_results/Bench2Drive +LOG=$STATE/chain.log +log() { echo "[$(date '+%F %T')] $*" | tee -a $LOG; } +die() { log "FATAL: $*"; exit 1; } +free_gb() { df -BG --output=avail /workspace | tail -n 1 | tr -dc '0-9'; } +require_disk() { [ "$(free_gb)" -ge "$1" ] || die "only $(free_gb) GB free on /workspace, need $1 GB"; } + +# ------------------------------------------------------------------ paths +STAGE1=outputs/fastvlm_stage1/$TAG +SPEEDDROP=outputs/fastvlm_stage3_speeddrop/$TAG +TRACKER_SP=outputs/fastvlm_stage3_tracker_sp/$TAG +DET_V1=outputs/detector/det_v1_$TAG +SP_V1=outputs/stream_petr/sp_v1_$TAG +SP_FOLD=outputs/stream_petr/sp_fold%dof2_$TAG +BANK_FOLDER=tracker_bank_sp_$TAG +DETS_FOLDER=tracker_dets_sp_$TAG +OFFLINE=eval_results/tracker_offline +B=eval_results/Bench2Drive + +export FASTVLM_SOURCE=${FASTVLM_SOURCE:-/workspace/code/ml-fastvlm} +export FASTVLM_CHECKPOINT=${FASTVLM_CHECKPOINT:-$REPO/pretrained/FastVLM-0.5B} +# Dataloader workers otherwise size BLAS/OpenCV pools to all 256 cores (pid limit, see run_train_fastvlm_stage3.sh). +export OMP_NUM_THREADS=1 MKL_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1 OPENCV_FOR_THREADS_NUM=1 + +# ------------------------------------------------------------------ preflight +if [ "${FORCE:-0}" != "1" ]; then + if pgrep -f "train_fastvlm.py|train_stream_petr.py|train_detector.py|eval_tracker_offline.py" > /dev/null \ + || tmux ls 2>/dev/null | grep -q '^b2d220_'; then + die "other trainings or evals are running (pgrep / tmux ls); finish them first or set FORCE=1" + fi +fi +require_disk "$MIN_FREE_GB" +[ -d pretrained/FastVLM-0.5B ] || die "pretrained/FastVLM-0.5B missing" +[ -d simlingo_data/object_bank ] || die "simlingo_data/object_bank missing (scripts/build_object_bank.py)" +[ -d simlingo_data/detection_labels ] || die "simlingo_data/detection_labels missing (scripts/build_detection_labels.py)" +N_ORACLE_BANKS=$(find simlingo_data/object_bank -name objects.npz | wc -l) +log "reproduction '$TAG': $N_EVAL_REPEATS final evals, $(free_gb) GB free, $N_ORACLE_BANKS oracle banks" +cat > $STATE/config.env </dev/null || echo none) +EOF + +# ------------------------------------------------------------------ Lightning stages (train_fastvlm.py) +# train_lightning NAME OUT_DIR WRAPPER EPOCHS [env assignments...] -- [hydra overrides...] +train_lightning() { + local name=$1 out=$2 wrapper=$3 epochs=$4; shift 4 + local envs=() overrides=() + while [ $# -gt 0 ] && [ "$1" != "--" ]; do envs+=("$1"); shift; done + [ $# -gt 0 ] && shift + overrides=("$@") + local final; final=$(printf '%s/checkpoints/epoch=%03d.ckpt' "$out" $((epochs - 1))) + if [ -f $out/REPRO_DONE ]; then log "$name: done ($final)"; return 0; fi + mkdir -p $out + if [ -f $out/checkpoints/last.ckpt ] && [ ! -f "$final" ]; then + log "$name: resuming from $out/checkpoints/last.ckpt" + overrides+=("resume_checkpoint=$REPO/$out/checkpoints/last.ckpt") + fi + log "$name: training -> $out (${overrides[*]:-no overrides})" + env "${envs[@]}" OUTPUT_DIR=$out bash $wrapper "seed=$SEED" "${overrides[@]}" > /dev/null 2>&1 + local rc=$? + echo "TRAIN_EXIT=$rc" >> $out/train.log + [ $rc -eq 0 ] && [ -f "$final" ] || die "$name failed (exit $rc, final checkpoint $([ -f "$final" ] && echo present || echo missing)); see $out/train.log" + if [ "$PRUNE_CHECKPOINTS" = "1" ]; then + find $out/checkpoints -name '*.ckpt' ! -name "$(basename "$final")" -delete + log "$name: pruned checkpoints, kept $(basename "$final")" + fi + grep -o "val/loss=[0-9.]*" $out/train.log | tail -n 1 | sed "s/^/$name final /" | tee -a $LOG + date > $out/REPRO_DONE +} + +# ------------------------------------------------------------------ torchrun stages (detector / StreamPETR) +# train_torchrun NAME OUT_DIR GPUS MASTER_PORT STEPS SCRIPT [args...] +train_torchrun() { + local name=$1 out=$2 gpus=$3 port=$4 steps=$5 script=$6; shift 6 + local final; final=$(printf '%s/val_%06d.json' "$out" "$steps") + if [ -f $out/REPRO_DONE ]; then log "$name: done"; return 0; fi + mkdir -p $out + local extra=() + if [ -f $out/last.pt ] && [ ! -f "$final" ]; then + if [ "$script" = train_stream_petr.py ]; then + log "$name: resuming from $out/last.pt"; extra=(--resume $out/last.pt) + else # train_detector.py has no --resume: start over cleanly + log "$name: incomplete run found, restarting from scratch" + rm -f $out/last.pt $out/val_*.json $out/log.jsonl $out/args.json + fi + fi + local nproc; nproc=$(echo "$gpus" | tr ',' '\n' | wc -l) + log "$name: training -> $out on GPUs $gpus ($steps steps)" + CUDA_VISIBLE_DEVICES=$gpus $PY -m torch.distributed.run --nproc_per_node=$nproc --master_port=$port \ + $script --out $out "$@" "${extra[@]}" >> $out/train.log 2>&1 + local rc=$? + echo "TRAIN_EXIT=$rc" >> $out/train.log + [ $rc -eq 0 ] && [ -f "$final" ] || die "$name failed (exit $rc); see $out/train.log" + date > $out/REPRO_DONE +} + +# ================================================================== 1. stage 1 -> speed-dropout stage 3 +train_lightning stage1 $STAGE1 scripts/run_train_fastvlm_stage1.sh 6 -- +STAGE1_CKPT=$REPO/$STAGE1/checkpoints/epoch=005.ckpt +# shellcheck disable=SC2086 +train_lightning speeddrop $SPEEDDROP scripts/run_train_fastvlm_stage3.sh 3 \ + CONFIG_NAME=fastvlm_stage3_oracle STAGE1_CHECKPOINT=$STAGE1_CKPT -- +model.speed_dropout_p=0.3 $SPEEDDROP_OVERRIDES + +# ================================================================== 2. perception: det_v1 -> sp_v1 -> folds -> banks +train_torchrun det_v1 $DET_V1 0,1,2,3,4,5,6,7 29610 30000 train_detector.py \ + --init pretrained/FastVLM-0.5B --batch 16 --workers 12 --steps 30000 --warmup 500 --lr 4e-4 --backbone-lr 4e-5 \ + --walker-weight 5 --val-every 3000 --val-samples 4000 --seed $DET_SEED +train_torchrun sp_v1 $SP_V1 0,1,2,3,4,5,6,7 29612 30000 train_stream_petr.py \ + --init $DET_V1/last.pt --steps 30000 --val-every 2000 --batch 8 --workers 10 --seed $DET_SEED +for k in 0 1; do + train_torchrun sp_fold$k "$(printf "$SP_FOLD" $k)" "$((4 * k)),$((4 * k + 1)),$((4 * k + 2)),$((4 * k + 3))" $((29620 + k)) 30000 \ + train_stream_petr.py --init $DET_V1/last.pt --holdout-fold $k/2 --steps 30000 --val-every 4000 --batch 8 --workers 10 --seed $DET_SEED & + pids[$k]=$! +done +wait ${pids[0]} || die "sp_fold0 failed" +wait ${pids[1]} || die "sp_fold1 failed" + +if [ -f $STATE/banks.done ]; then + log "banks: done" +else + log "tracker banks -> simlingo_data/$BANK_FOLDER (16 shards, fold-k routes through the fold-k detector)" + for k in 0 1; do + for s in 0 1 2 3 4 5 6 7; do + CUDA_VISIBLE_DEVICES=$((4 * k + s / 2)) OMP_NUM_THREADS=4 $PY scripts/eval_tracker_offline.py \ + --detector "$(printf "$SP_FOLD" $k)/last.pt" --out $OFFLINE/banks_sp_${TAG}_fold$k --split all --fold $k/2 \ + --shard $s/8 --write-banks --bank-folder $BANK_FOLDER --skip-existing --decode-threads 6 \ + --save-detections --detections-folder $DETS_FOLDER > $OFFLINE/banks_sp_${TAG}_fold${k}_shard$s.log 2>&1 & + done + done + wait + n_bank=$(find simlingo_data/$BANK_FOLDER -name objects.npz | wc -l) + log "tracker banks: $n_bank / $N_ORACLE_BANKS" + [ "$n_bank" -eq "$N_ORACLE_BANKS" ] || die "bank coverage incomplete (re-run the script: --skip-existing resumes)" + date > $STATE/banks.done +fi + +# ================================================================== 3. final fine-tune +train_lightning tracker_sp $TRACKER_SP scripts/run_train_fastvlm_stage3.sh 1 \ + CONFIG_NAME=fastvlm_stage3_tracker STAGE3_CHECKPOINT=$REPO/$SPEEDDROP/checkpoints/epoch=002.ckpt TRACKER_BANK_FOLDER=$BANK_FOLDER -- + +# ================================================================== 4. closed-loop evals of the final model +slots() { # eval index k, slot count n (two workers per slot); same GPU/CARLA rotation as the original chains + local k=$1 n=$2 s="" j + for ((j = 0; j < n; j++)); do s+="$(( (j + 2 * k) % 8 )):$(( (j + k) % 7 )) "; done + echo "${s% }" +} +ds_of() { $PY -c "import json; d=json.load(open('$1/merged.json')); print(f\"DS {d['driving score']:.2f} SR {d['success rate']*100:.2f} n={d['eval num']}\")" 2>/dev/null; } +merge_eval() { # merge a finished run (all 16 workers exited); returns 1 while it is still incomplete + local dir=$1 + [ -f $dir/merged.json ] && return 0 + [ "$(cat $dir/logs/w*.log 2>/dev/null | grep -c WORKER_EXIT)" -ge 16 ] || return 1 + $PY merge_route_json.py -f $dir > /dev/null 2>&1 && [ -f $dir/merged.json ] +} +report_eval() { + local dir=$1 + local bad; bad=$(grep -l "out of memory\|can't start new thread\|Retry limit exceeded" $dir/logs/w*.log 2>/dev/null | wc -l) + log "eval $(basename $dir): $(ds_of $dir)$([ "$bad" -gt 0 ] && echo " WARNING: $bad worker logs with OOM / thread / retry-limit failures, check before trusting")" +} +DET_ENV="OBJECT_SOURCE=detector DETECTOR_CKPT=$REPO/$SP_V1/last.pt DETECTOR_UPDATE_EVERY=5" +if tmux ls 2>/dev/null | grep -q "^b2d220_${TAG}_"; then # evals of a previous launch still running (FORCE=1) + log "waiting for running evals of '$TAG'" + while tmux ls 2>/dev/null | grep -q "^b2d220_${TAG}_"; do sleep 60; done +fi +require_disk 10 +launched=0 +for ((k = 1; k <= N_EVAL_REPEATS; k++)); do + dir=$B/${TAG}_sp_ft_nomask_r$k + if merge_eval $dir; then log "eval ${TAG}_sp_ft_nomask_r$k: done ($(ds_of $dir))"; continue; fi + rm -rf $dir + RUN_DIR=$TRACKER_SP RESULT_ROOT=$dir SLOTS="$(slots $((k - 1)) 8)" TAG=${TAG}_sp_ft_nomask_r$k TRAJ_VIZ=0 \ + PORT_BASE=$((20000 + 2000 * (k - 1))) TM_PORT_BASE=$((30000 + 2000 * (k - 1))) EXTRA_ENV="$DET_ENV" \ + bash scripts/run_full220_fastvlm.sh >> $LOG 2>&1 || die "could not launch eval ${TAG}_sp_ft_nomask_r$k" + log "eval ${TAG}_sp_ft_nomask_r$k launched (16 workers)" + launched=$((launched + 1)) +done +if [ $launched -gt 0 ]; then + while tmux ls 2>/dev/null | grep -q "^b2d220_${TAG}_"; do sleep 60; done + for ((k = 1; k <= N_EVAL_REPEATS; k++)); do + dir=$B/${TAG}_sp_ft_nomask_r$k + if merge_eval $dir; then report_eval $dir; else log "eval $(basename $dir): incomplete (fewer than 16 WORKER_EXIT lines), re-run the script"; fi + done +fi + +log "all stages done; comparison:" +$PY scripts/analysis/compare_reproduction.py --tag $TAG 2>&1 | tee -a $LOG diff --git a/scripts/run_bench2drive_tmux.sh b/scripts/run_bench2drive_tmux.sh new file mode 100644 index 0000000000000000000000000000000000000000..523e4e1136b82a1486091ad72f886446f9d2dad2 --- /dev/null +++ b/scripts/run_bench2drive_tmux.sh @@ -0,0 +1,209 @@ +#!/usr/bin/env bash +set -euo pipefail + +export CARLA_ROOT="${CARLA_ROOT:-/public/ZLCODE/carla}" + +SESSION_NAME="${SESSION_NAME:-b2d_eval}" +CONDA_ENV="${CONDA_ENV:-drivevla}" +CONDA_SH="${CONDA_SH:-$HOME/miniconda3/etc/profile.d/conda.sh}" +CHECKPOINT="${CHECKPOINT:-outputs/register_tp_small_seed_42/checkpoints/last.ckpt}" +ROUTES="${ROUTES:-leaderboard/data/bench2drive220.xml}" +RESULT_ROOT="${RESULT_ROOT:-eval_results/Bench2Drive/register_tp_small_seed_42_tmux}" +GPUS="${GPUS:-0,1,2,3,4,5,6,7}" +CARLA_GPU_RANKS="${CARLA_GPU_RANKS:-${CARLA_GPUS:-$GPUS}}" +WORKERS="${WORKERS:-8}" +BASE_PORT="${BASE_PORT:-20000}" +BASE_TM_PORT="${BASE_TM_PORT:-30000}" +PORT_STRIDE="${PORT_STRIDE:-50}" +TRAFFIC_MANAGER_SEED="${TRAFFIC_MANAGER_SEED:-1}" +TIMEOUT="${TIMEOUT:-600}" +MAX_ROUTE_RETRIES="${MAX_ROUTE_RETRIES:-3}" +RETRY_WAIT="${RETRY_WAIT:-15}" +CARLA_DEATH_GRACE="${CARLA_DEATH_GRACE:-90}" +REPETITIONS="${REPETITIONS:-1}" +AGENT_FILE="${AGENT_FILE:-team_code/agent_drivevla.py}" +CARLA_ROOT_ARG=() +CONFIG_ARG=() +OVERWRITE_ARG=() +VISUALIZE_ARG=() +GATING_ARG=() +SHADOW_ARG=() + +if [[ -n "${CARLA_ROOT:-}" ]]; then + CARLA_ROOT_ARG=(--carla-root "$CARLA_ROOT") +fi + +if [[ -n "${CONFIG:-}" ]]; then + CONFIG_ARG=(--config "$CONFIG") +fi + +if [[ "${OVERWRITE:-0}" == "1" || "${OVERWRITE:-}" == "true" ]]; then + OVERWRITE_ARG=(--overwrite) +fi + +if [[ "${VISUALIZE_TRAJECTORIES:-0}" == "1" || "${VISUALIZE_TRAJECTORIES:-}" == "true" ]]; then + VISUALIZE_ARG=(--visualize-trajectories) +fi + +if [[ "${CONSEQUENCE_GATING:-0}" == "1" || "${CONSEQUENCE_GATING:-}" == "true" ]]; then + GATING_ARG=(--consequence-gating) + if [[ -n "${GATING_ALGORITHM:-}" ]]; then + GATING_ARG+=(--gating-algorithm "$GATING_ALGORITHM") + fi + if [[ -n "${GATING_RISK_THRESHOLD:-}" ]]; then + GATING_ARG+=(--gating-risk-threshold "$GATING_RISK_THRESHOLD") + fi + if [[ -n "${GATING_SPEED_SCALES:-}" ]]; then + GATING_ARG+=(--gating-speed-scales "$GATING_SPEED_SCALES") + fi + if [[ -n "${GATING_AGGREGATE:-}" ]]; then + GATING_ARG+=(--gating-aggregate "$GATING_AGGREGATE") + fi + if [[ -n "${GATING_HYSTERESIS_DOWN:-}" ]]; then + GATING_ARG+=(--gating-hysteresis-down-steps "$GATING_HYSTERESIS_DOWN") + fi + if [[ -n "${GATING_HYSTERESIS_UP:-}" ]]; then + GATING_ARG+=(--gating-hysteresis-up-steps "$GATING_HYSTERESIS_UP") + fi + if [[ -n "${GATING_MIN_SPEED:-}" ]]; then + GATING_ARG+=(--gating-min-speed "$GATING_MIN_SPEED") + fi +fi + +if [[ "${RISK_SHADOW_LOG:-0}" == "1" || "${RISK_SHADOW_LOG:-}" == "true" ]]; then + SHADOW_ARG=(--risk-shadow-log) +fi + +REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +cd "$REPO_ROOT" + +if ! command -v tmux >/dev/null 2>&1; then + echo "tmux is not installed or not on PATH." >&2 + exit 1 +fi + +if [[ ! -f "$CONDA_SH" ]]; then + echo "Cannot find conda activation script: $CONDA_SH" >&2 + echo "Set CONDA_SH=/path/to/conda.sh or edit scripts/run_bench2drive_tmux.sh" >&2 + exit 1 +fi + +IFS=',' read -r -a GPU_ARRAY <<< "$GPUS" +if (( WORKERS > ${#GPU_ARRAY[@]} )); then + echo "WORKERS=$WORKERS exceeds number of GPUS in GPUS=$GPUS" >&2 + exit 1 +fi +IFS=',' read -r -a CARLA_GPU_ARRAY <<< "$CARLA_GPU_RANKS" +if (( WORKERS > ${#CARLA_GPU_ARRAY[@]} )); then + echo "WORKERS=$WORKERS exceeds number of CARLA_GPU_RANKS in CARLA_GPU_RANKS=$CARLA_GPU_RANKS" >&2 + exit 1 +fi + +if tmux has-session -t "$SESSION_NAME" 2>/dev/null; then + echo "tmux session '$SESSION_NAME' already exists. Attach with: tmux attach -t $SESSION_NAME" >&2 + exit 1 +fi + +mkdir -p "$RESULT_ROOT/logs" + +mapfile -t ROUTE_SUBSETS < <( + python - "$ROUTES" "$WORKERS" <<'PY' +import sys +import xml.etree.ElementTree as ET + +routes_file = sys.argv[1] +workers = int(sys.argv[2]) +route_ids = [route.attrib["id"] for route in ET.parse(routes_file).iter("route")] +chunks = [[] for _ in range(workers)] +for idx, route_id in enumerate(route_ids): + chunks[idx % workers].append(route_id) +for chunk in chunks: + print(",".join(chunk)) +PY +) + +tmux new-session -d -s "$SESSION_NAME" -n monitor +tmux set-option -t "$SESSION_NAME" remain-on-exit on +tmux send-keys -t "$SESSION_NAME:monitor" \ + "source '$CONDA_SH' && conda activate '$CONDA_ENV' && cd '$REPO_ROOT' && echo 'Bench2Drive tmux session: $SESSION_NAME' && echo 'Conda env: $CONDA_ENV' && echo 'Logs: $RESULT_ROOT/logs' && watch -n 10 \"python scripts/monitor_bench2drive.py '$RESULT_ROOT'\"" C-m + +for ((worker=0; worker "$launcher_script" + chmod +x "$launcher_script" + + tmux new-window -t "$SESSION_NAME" -n "$worker_name" + tmux send-keys -t "$SESSION_NAME:$worker_name" \ + "set -o pipefail && mkdir -p '$RESULT_ROOT' '$RESULT_ROOT/logs' && echo 'conda env: $CONDA_ENV' | tee -a '$log_path' && which python | tee -a '$log_path' && python -V | tee -a '$log_path' && echo \"CUDA_VISIBLE_DEVICES=\$CUDA_VISIBLE_DEVICES CARLA_GPU_RANK=$carla_gpu_rank CARLA_GRAPHICSADAPTER=$carla_graphicsadapter OMP_NUM_THREADS=\$OMP_NUM_THREADS MAX_ROUTE_RETRIES=$MAX_ROUTE_RETRIES\" | tee -a '$log_path' && echo 'launcher: $launcher_script' | tee -a '$log_path' && cat '$launcher_script' | tee -a '$log_path' && bash '$launcher_script' 2>&1 | tee -a '$log_path'; worker_status=\${PIPESTATUS[0]}; echo \"WORKER_EXIT=\$worker_status\" | tee -a '$log_path'; exit \$worker_status" C-m + + echo "worker=$worker cuda_gpu=$gpu carla_gpu_rank=$carla_gpu_rank graphicsadapter=$carla_graphicsadapter routes=$(awk -F',' '{print NF}' <<< "$subset") port=$port tm_port=$tm_port result=$result_file launcher=$launcher_script log=$log_path" +done + +echo +echo "Started tmux session: $SESSION_NAME" +echo "Conda env: $CONDA_ENV" +echo "Attach: tmux attach -t $SESSION_NAME" +echo "List windows: tmux list-windows -t $SESSION_NAME" +echo "Kill all workers: tmux kill-session -t $SESSION_NAME" diff --git a/scripts/run_consdrive_v2_eval.sh b/scripts/run_consdrive_v2_eval.sh new file mode 100644 index 0000000000000000000000000000000000000000..a9083946dfd1627d7804d24263ebc695db1eea41 --- /dev/null +++ b/scripts/run_consdrive_v2_eval.sh @@ -0,0 +1,142 @@ +#!/usr/bin/env bash +# Reproduce ConsDrive v2 Bench2Drive-220 eval: +# qwen3vl_2b_video_dream_consdrive_v2_gating_jump_thr010_s08_seed_42_tmux +# +# Original machine: DS=91.33, SR=77.73%, 220/220 routes. +# Weights are the Aug 9 run named qwen3vl_2b_video_dream_consdrive_seed_42 +# (no separate "v2" checkpoint directory). Gating uses the jump controller +# (CLI name: v3) with threshold=0.10 and scales=1.0,0.9,0.8. +# +# Required on the target machine: +# CARLA_ROOT CARLA 0.9.15 tree (CarlaUE4.sh + PythonAPI) +# conda env drivevla, or CONDA_ENV / CONDA_SH overrides +# tmux +# +# Usage: +# export CARLA_ROOT=/path/to/carla0915 +# bash scripts/run_consdrive_v2_eval.sh + +set -euo pipefail + +REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +cd "$REPO_ROOT" + +RUN_DIR="${RUN_DIR:-outputs/qwen3vl_2b_video_dream_consdrive_seed_42/2026-08-09_13-10-02}" +CHECKPOINT="${CHECKPOINT:-$RUN_DIR/checkpoints/last.ckpt}" +HYDRA_CONFIG="${HYDRA_CONFIG:-$RUN_DIR/.hydra/config.yaml}" +CONFIG="${CONFIG:-$RUN_DIR/eval_config.yaml}" +QWEN3VL_MODEL="${QWEN3VL_MODEL:-$REPO_ROOT/pretrained/Qwen3-VL-2B-Instruct}" + +CONDA_ENV="${CONDA_ENV:-drivevla}" +PYTHON="${PYTHON:-$HOME/miniconda3/envs/${CONDA_ENV}/bin/python}" +WORKERS="${WORKERS:-8}" +GPUS="${GPUS:-0,1,2,3,4,5,6,7}" +POLL_INTERVAL_SEC="${POLL_INTERVAL_SEC:-120}" + +export AGENT_FILE="team_code/agent_drivevla.py" +: "${CARLA_ROOT:?Set CARLA_ROOT to your CARLA 0.9.15 installation}" + +if [[ ! -e "$CHECKPOINT" ]]; then + echo "CHECKPOINT does not exist: $CHECKPOINT" >&2 + exit 1 +fi +if [[ ! -d "$QWEN3VL_MODEL" ]]; then + echo "Qwen3-VL model directory does not exist: $QWEN3VL_MODEL" >&2 + exit 1 +fi + +"$PYTHON" - "$HYDRA_CONFIG" "$CONFIG" "$QWEN3VL_MODEL" <<'PY' +import sys +from pathlib import Path + +from omegaconf import OmegaConf + +src, dst, qwen = sys.argv[1], sys.argv[2], sys.argv[3] +cfg = OmegaConf.load(src) +qwen = str(Path(qwen).expanduser().resolve()) +cfg.model.vision_model.variant = qwen +cfg.model.language_model.variant = qwen +if OmegaConf.select(cfg, "model.consequence") is not None: + cfg.model.consequence.head_type = "pooled" +Path(dst).parent.mkdir(parents=True, exist_ok=True) +OmegaConf.save(cfg, dst) +print(f"Wrote {dst} with variant={qwen}") +PY + +P1_ROOT="${P1_ROOT:-eval_results/Bench2Drive/qwen3vl_2b_video_dream_consdrive_v2_gating_jump_thr010_s08_seed_42_tmux}" +P1_SESSION="${P1_SESSION:-b2d_consdrive_v2_gating_jump}" + +GATING_ALGORITHM="${GATING_ALGORITHM:-v3}" +GATING_RISK_THRESHOLD="${GATING_RISK_THRESHOLD:-0.10}" +GATING_SPEED_SCALES="${GATING_SPEED_SCALES:-1.0,0.9,0.8}" +GATING_AGGREGATE="${GATING_AGGREGATE:-max}" +GATING_HYSTERESIS_DOWN="${GATING_HYSTERESIS_DOWN:-3}" +GATING_HYSTERESIS_UP="${GATING_HYSTERESIS_UP:-5}" +GATING_MIN_SPEED="${GATING_MIN_SPEED:-1.5}" + +wait_for_eval() { + local label="$1" + local result_root="$2" + local session="$3" + echo + echo "=== Waiting for $label (session=$session, root=$result_root) ===" + while true; do + if "$PYTHON" scripts/check_bench2drive_complete.py "$result_root" --workers "$WORKERS"; then + break + fi + sleep "$POLL_INTERVAL_SEC" + done + if tmux has-session -t "$session" 2>/dev/null; then + echo "Killing tmux session $session" + tmux kill-session -t "$session" + fi + "$PYTHON" merge_route_json.py -f "$result_root" + echo "Merged: $result_root/merged.json" +} + +if tmux has-session -t "$P1_SESSION" 2>/dev/null; then + echo "tmux session $P1_SESSION already exists. Kill it first." >&2 + exit 1 +fi + +echo "=== ConsDrive v2 gating-jump eval ===" +echo " REPO_ROOT=$REPO_ROOT" +echo " CARLA_ROOT=$CARLA_ROOT" +echo " CHECKPOINT=$CHECKPOINT" +echo " CONFIG=$CONFIG" +echo " QWEN3VL_MODEL=$QWEN3VL_MODEL" +echo " GATING_ALGORITHM=$GATING_ALGORITHM" +echo " GATING_RISK_THRESHOLD=$GATING_RISK_THRESHOLD" +echo " GATING_SPEED_SCALES=$GATING_SPEED_SCALES" +echo " GATING_AGGREGATE=$GATING_AGGREGATE" +echo + +SESSION_NAME="$P1_SESSION" \ + CHECKPOINT="$CHECKPOINT" \ + CONFIG="$CONFIG" \ + RESULT_ROOT="$P1_ROOT" \ + WORKERS="$WORKERS" \ + GPUS="$GPUS" \ + CONSEQUENCE_GATING=1 \ + GATING_ALGORITHM="$GATING_ALGORITHM" \ + GATING_RISK_THRESHOLD="$GATING_RISK_THRESHOLD" \ + GATING_SPEED_SCALES="$GATING_SPEED_SCALES" \ + GATING_AGGREGATE="$GATING_AGGREGATE" \ + GATING_HYSTERESIS_DOWN="$GATING_HYSTERESIS_DOWN" \ + GATING_HYSTERESIS_UP="$GATING_HYSTERESIS_UP" \ + GATING_MIN_SPEED="$GATING_MIN_SPEED" \ + bash scripts/run_bench2drive_tmux.sh + +if [[ "${NO_WAIT:-0}" == "1" ]]; then + echo + echo "NO_WAIT=1: workers are running in tmux session $P1_SESSION" + echo "Monitor: python scripts/monitor_bench2drive.py $P1_ROOT" + echo "Merge: python merge_route_json.py -f $P1_ROOT" + exit 0 +fi + +wait_for_eval "v2_gating_jump" "$P1_ROOT" "$P1_SESSION" +echo +echo "=== Done ===" +echo "Merged: $P1_ROOT/merged.json" +echo "Reference (original machine): driving score 91.33, success rate 0.777, eval num 220" diff --git a/scripts/run_full220_fastvlm.sh b/scripts/run_full220_fastvlm.sh new file mode 100644 index 0000000000000000000000000000000000000000..39ca76e12177752fe88b635a69403470dd4627cb --- /dev/null +++ b/scripts/run_full220_fastvlm.sh @@ -0,0 +1,84 @@ +#!/usr/bin/env bash +# Bench2Drive-220 eval of a FastVLM stage-1 checkpoint on this 8-GPU box. +# No consequence gating; stuck creep and CARLA recorder are kept so results and +# failure_report.py analyses are comparable with consdrive_v2_full. +# CARLA's -graphicsadapter=N is GPU N here, but the leaderboard maps --gpu-rank=k to adapter k+1, +# so GPU 1 cannot host CARLA: its workers run the model on GPU 1 and CARLA on GPU 0. +# +# RUN_DIR=outputs/fastvlm_stage1/ bash scripts/run_full220_fastvlm.sh +# Optional: CHECKPOINT (default: last epoch checkpoint), RESULT_ROOT, +# ROUTE_IDS=2127,2084 (restrict routes), SLOTS="0:0 1:0" (model_gpu:carla_gpu_rank), +# EXTRA_ENV="VAR=value ..." (exported in every worker), and for concurrent evals a distinct +# TAG (tmux session prefix) plus PORT_BASE / TM_PORT_BASE at least 100 * (number of SLOTS) +# apart (two workers per slot, 50 ports per worker). +# TRAJ_VIZ=0 disables the trajectory visualisation frames (~12 GB per 220-route run; the +# recorder logs used by scripts/analysis are kept). +set -euo pipefail + +REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +cd "$REPO_ROOT" +PY=/venv/fastvlm/bin/python +: "${RUN_DIR:?Set RUN_DIR to the stage-1 output directory}" +CHECKPOINT="${CHECKPOINT:-$(ls "$RUN_DIR"/checkpoints/epoch=*.ckpt | sort | tail -1)}" +RESULT_ROOT="${RESULT_ROOT:-eval_results/Bench2Drive/fastvlm_stage1_$(basename "$RUN_DIR")}" +ROUTES=leaderboard/data/bench2drive220.xml +export CARLA_ROOT=/workspace/carla0915 +export FASTVLM_SOURCE="${FASTVLM_SOURCE:-/workspace/code/ml-fastvlm}" +export FASTVLM_CHECKPOINT="${FASTVLM_CHECKPOINT:-$REPO_ROOT/pretrained/FastVLM-0.5B}" + +# model_gpu:carla_gpu_rank, two workers per entry. +read -r -a SLOTS <<< "${SLOTS:-0:0 1:0 2:1 3:2 4:3 5:4 6:5 7:6}" +WORKERS=$(( ${#SLOTS[@]} * 2 )) +PORT_BASE="${PORT_BASE:-20000}" +TM_PORT_BASE="${TM_PORT_BASE:-30000}" +TAG="${TAG:-fastvlm}" + +mkdir -p "$RESULT_ROOT/logs" "$RESULT_ROOT/scripts" +echo "checkpoint=$CHECKPOINT" > "$RESULT_ROOT/eval_source.txt" +mapfile -t SUBSETS < <($PY - "$ROUTES" "$WORKERS" "${ROUTE_IDS:-}" <<'PY' +import sys +import xml.etree.ElementTree as ET +ids = [r.attrib["id"] for r in ET.parse(sys.argv[1]).iter("route")] +if sys.argv[3]: + wanted = set(sys.argv[3].split(",")) + ids = [i for i in ids if i in wanted] +w = int(sys.argv[2]) +for k in range(w): + print(",".join(ids[k::w])) +PY +) + +launched=0 +for ((w = 0; w < WORKERS; w++)); do + [ -n "${SUBSETS[$w]:-}" ] || continue + slot=${SLOTS[$((w / 2))]} + gpu=${slot%%:*} + rank=${slot##*:} + label=$(printf 'w%02d_g%d_cr%d' "$w" "$gpu" "$rank") + viz_args="" + [ "${TRAJ_VIZ:-1}" = "0" ] || viz_args="--visualize-trajectories --trajectory-viz-frequency 5 --trajectory-viz-dir $RESULT_ROOT/trajectory_viz/${label}" + launcher="$RESULT_ROOT/scripts/run_${label}.sh" + cat > "$launcher" < '$RESULT_ROOT/logs/${label}.log' 2>&1; echo WORKER_EXIT=\$? >> '$RESULT_ROOT/logs/${label}.log'" + launched=$((launched + 1)) + sleep 3 +done +echo "launched $launched workers; logs in $RESULT_ROOT/logs" diff --git a/scripts/run_full220_local.sh b/scripts/run_full220_local.sh new file mode 100644 index 0000000000000000000000000000000000000000..39c29775f8a4e3fc03167a0cddc565ef8fe87ba6 --- /dev/null +++ b/scripts/run_full220_local.sh @@ -0,0 +1,61 @@ +#!/usr/bin/env bash +# Full Bench2Drive-220 eval of the ConsDrive v2 checkpoint on this 8-GPU box (no conda). +# CARLA's -graphicsadapter=N is GPU N here, but the leaderboard maps --gpu-rank=k to adapter k+1, +# so GPU 1 cannot host CARLA: its workers run the model on GPU 1 and CARLA on GPU 0. +set -euo pipefail + +REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +cd "$REPO_ROOT" +PY=/venv/consdrive/bin/python +RUN_DIR=outputs/qwen3vl_2b_video_dream_consdrive_seed_42/2026-08-09_13-10-02 +RESULT_ROOT="${RESULT_ROOT:-eval_results/Bench2Drive/consdrive_v2_full}" +ROUTES=leaderboard/data/bench2drive220.xml +export CARLA_ROOT=/workspace/carla0915 + +# model_gpu:carla_gpu_rank, two workers per entry. +SLOTS=(0:0 1:0 2:1 3:2 4:3 5:4 6:5 7:6) +WORKERS=$(( ${#SLOTS[@]} * 2 )) + +mkdir -p "$RESULT_ROOT/logs" "$RESULT_ROOT/scripts" +mapfile -t SUBSETS < <($PY - "$ROUTES" "$WORKERS" <<'PY' +import sys +import xml.etree.ElementTree as ET +ids = [r.attrib["id"] for r in ET.parse(sys.argv[1]).iter("route")] +w = int(sys.argv[2]) +for k in range(w): + print(",".join(ids[k::w])) +PY +) + +for ((w = 0; w < WORKERS; w++)); do + slot=${SLOTS[$((w / 2))]} + gpu=${slot%%:*} + rank=${slot##*:} + label=$(printf 'w%02d_g%d_cr%d' "$w" "$gpu" "$rank") + launcher="$RESULT_ROOT/scripts/run_${label}.sh" + cat > "$launcher" < '$RESULT_ROOT/logs/${label}.log' 2>&1; echo WORKER_EXIT=\$? >> '$RESULT_ROOT/logs/${label}.log'" + sleep 3 +done +echo "launched $WORKERS workers; logs in $RESULT_ROOT/logs" diff --git a/scripts/run_train_fastvlm_stage1.sh b/scripts/run_train_fastvlm_stage1.sh new file mode 100644 index 0000000000000000000000000000000000000000..8b260ac91b1f79c86ee2bb29886a9de736632b24 --- /dev/null +++ b/scripts/run_train_fastvlm_stage1.sh @@ -0,0 +1,17 @@ +#!/bin/bash +# Stage 1: current-frame FastVLM driving model (FIVE-VLA without memory), 8-GPU DDP. +# Extra Hydra overrides are forwarded, e.g. trainer.max_epochs=8 seed=1. +set -euo pipefail +cd "$(dirname "$0")/.." + +PYTHON="${PYTHON:-/venv/fastvlm/bin/python}" +REPO="$(pwd)" + +export FASTVLM_SOURCE="${FASTVLM_SOURCE:-/workspace/code/ml-fastvlm}" +export FASTVLM_CHECKPOINT="${FASTVLM_CHECKPOINT:-$REPO/pretrained/FastVLM-0.5B}" +export OMP_NUM_THREADS=1 +export MKL_NUM_THREADS=1 + +OUTPUT_DIR="${OUTPUT_DIR:-outputs/fastvlm_stage1/$(date +%Y-%m-%d_%H-%M-%S)}" +mkdir -p "$OUTPUT_DIR" +"$PYTHON" train_fastvlm.py output_dir="$OUTPUT_DIR" "$@" 2>&1 | tee -a "$OUTPUT_DIR/train.log" diff --git a/scripts/run_train_fastvlm_stage3.sh b/scripts/run_train_fastvlm_stage3.sh new file mode 100644 index 0000000000000000000000000000000000000000..b9b573a20a8ec700e78a5be36edc6ea2fce9e92f --- /dev/null +++ b/scripts/run_train_fastvlm_stage3.sh @@ -0,0 +1,25 @@ +#!/bin/bash +# Stage 3 (oracle object bank): stage-1 FastVLM + object tokens + relation head, 8-GPU DDP. +# Requires simlingo_data/object_bank (scripts/build_object_bank.py) and a stage-1 checkpoint +# (STAGE1_CHECKPOINT or the default in config/fastvlm_stage3_oracle.yaml). +# Extra Hydra overrides are forwarded, e.g. trainer.max_epochs=2 model.objects.relation_loss_weight=0.5. +set -euo pipefail +cd "$(dirname "$0")/.." + +PYTHON="${PYTHON:-/venv/fastvlm/bin/python}" +REPO="$(pwd)" + +export FASTVLM_SOURCE="${FASTVLM_SOURCE:-/workspace/code/ml-fastvlm}" +export FASTVLM_CHECKPOINT="${FASTVLM_CHECKPOINT:-$REPO/pretrained/FastVLM-0.5B}" +export OMP_NUM_THREADS=1 +export MKL_NUM_THREADS=1 +# OpenCV/OpenBLAS otherwise size their pools to all 256 cores in each of the 128 dataloader workers, +# which exhausts the container's pid limit when CARLA evals run at the same time. +export OPENBLAS_NUM_THREADS=1 +export OPENCV_FOR_THREADS_NUM=1 + +# CONFIG_NAME=fastvlm_stage3_tracker fine-tunes on the tracker banks instead +CONFIG_NAME="${CONFIG_NAME:-fastvlm_stage3_oracle}" +OUTPUT_DIR="${OUTPUT_DIR:-outputs/${CONFIG_NAME}/$(date +%Y-%m-%d_%H-%M-%S)}" +mkdir -p "$OUTPUT_DIR" +"$PYTHON" train_fastvlm.py --config-name "$CONFIG_NAME" output_dir="$OUTPUT_DIR" "$@" 2>&1 | tee -a "$OUTPUT_DIR/train.log" diff --git a/scripts/run_train_qwen3vl_video_dream_consdrive.sh b/scripts/run_train_qwen3vl_video_dream_consdrive.sh new file mode 100644 index 0000000000000000000000000000000000000000..39f8ac171ad03f11b5cb3576d2caae8fa3c78112 --- /dev/null +++ b/scripts/run_train_qwen3vl_video_dream_consdrive.sh @@ -0,0 +1,12 @@ +#!/bin/bash +# Train Dream with the training-only plan-conditioned consequence objective. +# The consequence head is not executed by the deployment forward path. +set -eu +cd "$(dirname "$0")/.." + +PYTHON="${PYTHON:-/home/zl/miniconda3/envs/drivevla/bin/python}" + +export OMP_NUM_THREADS=1 +export MKL_NUM_THREADS=1 + +exec "$PYTHON" train.py experiment=qwen3vl_video_dream_consdrive "$@" diff --git a/scripts/watch_stage1_then_eval.sh b/scripts/watch_stage1_then_eval.sh new file mode 100644 index 0000000000000000000000000000000000000000..40612736d6e762653878df67ade4244a36702066 --- /dev/null +++ b/scripts/watch_stage1_then_eval.sh @@ -0,0 +1,21 @@ +#!/usr/bin/env bash +# Wait for a stage-1 training tmux session to exit, then start the Bench2Drive-220 +# eval on its final epoch checkpoint. Does nothing if that checkpoint is missing. +# RUN_DIR=outputs/fastvlm_stage1/ bash scripts/watch_stage1_then_eval.sh +set -euo pipefail +cd "$(dirname "${BASH_SOURCE[0]}")/.." +: "${RUN_DIR:?Set RUN_DIR to the stage-1 output directory}" +SESSION="${SESSION:-fastvlm_stage1}" +EPOCHS="${EPOCHS:-6}" + +while tmux has-session -t "$SESSION" 2>/dev/null; do sleep 60; done +while pgrep -f "train_fastvlm.py output_dir=$RUN_DIR" > /dev/null; do sleep 10; done + +final=$(printf '%s/checkpoints/epoch=%03d.ckpt' "$RUN_DIR" $((EPOCHS - 1))) +if [ ! -f "$final" ]; then + echo "$(date) training did not finish: $final missing; eval not started" + exit 1 +fi +while tmux ls 2>/dev/null | grep -q '^b2d220_fastvlm_'; do sleep 30; done +echo "$(date) training finished; evaluating $final" +RUN_DIR="$RUN_DIR" CHECKPOINT="$final" bash scripts/run_full220_fastvlm.sh diff --git a/team_code/__init__.py b/team_code/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/team_code/__init__.py @@ -0,0 +1 @@ + diff --git a/team_code/agent_drivevla.py b/team_code/agent_drivevla.py new file mode 100644 index 0000000000000000000000000000000000000000..5e0b497b588bf27a5edf7b2fb18c42b7f046e026 --- /dev/null +++ b/team_code/agent_drivevla.py @@ -0,0 +1,1310 @@ +import json +import math +import os +import sys +from collections import Counter, deque +from copy import deepcopy +from pathlib import Path + +REPO_ROOT = Path(__file__).resolve().parents[1] +if str(REPO_ROOT) not in sys.path: + sys.path.insert(0, str(REPO_ROOT)) +else: + sys.path.insert(0, sys.path.pop(sys.path.index(str(REPO_ROOT)))) + +loaded_utils = sys.modules.get("utils") +if loaded_utils is not None: + loaded_utils_file = getattr(loaded_utils, "__file__", None) + try: + is_repo_utils = loaded_utils_file is not None and Path(loaded_utils_file).resolve().relative_to(REPO_ROOT) + except ValueError: + is_repo_utils = False + if not is_repo_utils: + del sys.modules["utils"] + +import cv2 +import hydra +import numpy as np +import torch +from filterpy.kalman import MerweScaledSigmaPoints +from filterpy.kalman import UnscentedKalmanFilter as UKF +from omegaconf import OmegaConf +from PIL import Image, ImageDraw +from scipy.interpolate import PchipInterpolator + +import carla +from leaderboard.autoagents import autonomous_agent +from srunner.scenariomanager.carla_data_provider import CarlaDataProvider + +from config import register_configs # noqa: F401 +from utils.custom_types import DrivingInput +from utils.image_enhancing import histogram_equalization +from utils.navigation_text import format_target_waypoint_text +from utils.projection import get_camera_extrinsics, get_camera_intrinsics, project_points + + +USE_UKF = True # Filter GNSS/compass with an Unscented Kalman Filter (same setup as SimLingo) + + +def get_entry_point(): + return "DriveVLABench2DriveAgent" + + +class PIDController: + def __init__(self, k_p=1.0, k_i=0.0, k_d=0.0, n=20): + self.k_p = k_p + self.k_i = k_i + self.k_d = k_d + self._window = deque([0.0 for _ in range(n)], maxlen=n) + self._saved_window = deepcopy(self._window) + + def step(self, error): + self._window.append(float(error)) + integral = sum(self._window) / len(self._window) + derivative = 0.0 if len(self._window) < 2 else self._window[-1] - self._window[-2] + return self.k_p * error + self.k_i * integral + self.k_d * derivative + + def save(self): + self._saved_window = deepcopy(self._window) + + def load(self): + self._window = deepcopy(self._saved_window) + + +class LateralPIDController: + def __init__( + self, + k_p=3.118357247806046, + k_d=1.3782508892109167, + k_i=0.6406067986034124, + speed_scale=0.9755321901954155, + speed_offset=1.9152884533402488, + n=6, + ): + self.k_p = k_p + self.k_d = k_d + self.k_i = k_i + self.speed_scale = speed_scale + self.speed_offset = speed_offset + self.n = n + self._window = [] + + def step(self, route_np, current_speed): + if route_np.shape[0] == 0: + return 0.0 + + current_speed_kph = current_speed * 3.6 + lookahead = int(min(np.clip(self.speed_scale * current_speed_kph + self.speed_offset, 24, 105), route_np.shape[0] - 1)) + desired_heading_vec = route_np[lookahead] + yaw_path = np.arctan2(desired_heading_vec[1], desired_heading_vec[0]) + heading_error = yaw_path % (2 * np.pi) + heading_error = heading_error if heading_error < np.pi else heading_error - 2 * np.pi + heading_error = heading_error * 180.0 / np.pi / 90.0 + + self._window.append(heading_error) + self._window = self._window[-self.n :] + derivative = 0.0 if len(self._window) == 1 else self._window[-1] - self._window[-2] + integral = np.mean(self._window) + return np.clip(self.k_p * heading_error + self.k_d * derivative + self.k_i * integral, -1.0, 1.0).item() + + +class RoutePlanner: + def __init__(self, min_distance, max_distance, lat_ref=0.0, lon_ref=0.0): + self.route = deque() + self.route_distances = deque() + self.min_distance = min_distance + self.max_distance = max_distance + self.lat_ref = lat_ref + self.lon_ref = lon_ref + + def convert_gps_to_carla(self, gps): + earth_radius_equa = 6378137.0 + lat, lon, z = gps + scale = math.cos(self.lat_ref * math.pi / 180.0) + my = math.log(math.tan((lat + 90) * math.pi / 360.0)) * (earth_radius_equa * scale) + mx = (lon * (math.pi * earth_radius_equa * scale)) / 180.0 + y = scale * earth_radius_equa * math.log(math.tan((90.0 + self.lat_ref) * math.pi / 360.0)) - my + x = mx - scale * self.lon_ref * math.pi * earth_radius_equa / 180.0 + return np.array([x, y, z]) + + def set_route(self, global_plan, gps=False): + self.route.clear() + self.route_distances.clear() + + for pos, cmd in global_plan: + if gps: + pos = self.convert_gps_to_carla(np.array([pos["lat"], pos["lon"], pos["z"]])) + else: + pos = np.array([pos.location.x, pos.location.y, pos.location.z]) + self.route.append((pos, cmd)) + + self.route_distances.append(0.0) + for i in range(1, len(self.route)): + diff = self.route[i][0] - self.route[i - 1][0] + self.route_distances.append(float((diff[0] ** 2 + diff[1] ** 2) ** 0.5)) + + def run_step(self, gps): + if len(self.route) <= 2: + return self.route + + to_pop = 0 + farthest_in_range = -np.inf + cumulative_distance = 0.0 + for i in range(1, len(self.route)): + if cumulative_distance > self.max_distance: + break + cumulative_distance += self.route_distances[i] + diff = self.route[i][0] - gps + distance = float((diff[0] ** 2 + diff[1] ** 2) ** 0.5) + if farthest_in_range < distance <= self.min_distance: + farthest_in_range = distance + to_pop = i + + for _ in range(to_pop): + if len(self.route) > 2: + self.route.popleft() + self.route_distances.popleft() + return self.route + + +class DriveVLABench2DriveAgent(autonomous_agent.AutonomousAgent): + def setup(self, path_to_conf_file, route_index=None): + self.track = autonomous_agent.Track.SENSORS + self.step = -1 + self.initialized = False + self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + self.control = carla.VehicleControl(steer=0.0, throttle=0.0, brake=1.0) + + self.agent_cfg = self._load_agent_config(path_to_conf_file) + self.checkpoint_path = Path(self.agent_cfg["checkpoint"]).expanduser().resolve() + self.cfg = self._load_hydra_config(self.agent_cfg.get("config"), self.checkpoint_path) + self.route_as = self.agent_cfg.get("route_as") or OmegaConf.select(self.cfg, "data_module.route_as") or "target_point" + # TP-in-text must match training; old checkpoints lack the flag -> off. + self.command_tp_text = bool(OmegaConf.select(self.cfg, "data_module.command_tp_text")) + + self.processor = None + self._configure_processor() + + if self.cfg.model.vision_model is not None: + self.cfg.model.vision_model.use_global_img = self.cfg.data_module.use_global_img + self.model = hydra.utils.instantiate(self.cfg.model, route_as=self.route_as) + state_dict = self._load_state_dict(self.checkpoint_path) + self.model.load_state_dict(state_dict, strict=True) + self.model.to(self.device).eval() + self._setup_object_source() + self._setup_consequence_gating() + self._setup_risk_shadow_log(route_index) + + self.speed_controller = PIDController(k_p=1.75, k_i=1.0, k_d=2.0, n=20) + self.turn_controller = LateralPIDController() + self.stuck_detector = 0 + self.force_move = 0 + self.last_command = 4 + self.last_command_tmp = 4 + self.commands = deque([4, 4], maxlen=2) + self.target_point_prev = np.array([1e5, 1e5]) + + self.carla_frame_rate = 1.0 / 20.0 + self.carla_fps = 20 + + # GNSS/compass filtering, ported from SimLingo's agent (bicycle-model UKF). + # Only the filtered position is used; heading stays raw compass. + self.use_ukf = bool(self.agent_cfg.get("use_ukf", USE_UKF)) + if self.use_ukf: + self.ukf_points = MerweScaledSigmaPoints(n=4, alpha=0.00001, beta=2, kappa=0, subtract=residual_state_x) + self.ukf = UKF( + dim_x=4, + dim_z=4, + fx=bicycle_model_forward, + hx=measurement_function_hx, + dt=self.carla_frame_rate, + points=self.ukf_points, + x_mean_fn=state_mean, + z_mean_fn=measurement_mean, + residual_x=residual_state_x, + residual_z=residual_measurement_h, + ) + # State noise, same as measurement because we initialize with the first measurement later + self.ukf.P = np.diag([0.5, 0.5, 0.000001, 0.000001]) + # Measurement noise + self.ukf.R = np.diag([0.5, 0.5, 0.000000000000001, 0.000000000000001]) + self.ukf.Q = np.diag([0.0001, 0.0001, 0.001, 0.001]) # Model noise + self.filter_initialized = False + self.data_save_freq = 5 + self.wp_dilation = 1 + self.initial_frames_delay = int(2.0 / self.carla_frame_rate) + self.stuck_threshold = 800 + self.creep_duration = 15 + self.creep_throttle = 0.4 + self._setup_creep_gate() + # Learned restart (needs a checkpoint trained with speed_dropout_p > 0): after SPEED_MASK_STALL_S at + # standstill the speed token is hidden, so the policy decides from the scene whether to go, until the + # ego exceeds SPEED_MASK_RELEASE m/s. + mask_s = os.environ.get("SPEED_MASK_STALL_S") + self.speed_mask_steps = int(float(mask_s) * self.carla_fps) if mask_s else None + self.speed_mask_release = float(os.environ.get("SPEED_MASK_RELEASE", "2.0")) + self.speed_masked = False + self.speed_mask_count = 0 + if self.speed_mask_steps is not None: + print(f"Speed mask while stalled: after {mask_s}s, release above {self.speed_mask_release} m/s", flush=True) + + # temporal input: training frames are stored at carla_fps / data_save_freq + # (4 Hz -> 0.25 s apart); keep a buffer of raw frames and pick + # hist_len frames with the same spacing at inference time + self.hist_len = int(OmegaConf.select(self.cfg, "data_module.hist_len") or 1) + self.frame_stride = self.data_save_freq # sim frames between model frames + buffer_len = (self.hist_len - 1) * self.frame_stride + 1 + self.frame_buffer = deque(maxlen=buffer_len) + if route_index is None and "+" in str(path_to_conf_file): + # The leaderboard appends "+____