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)