Download models/plan_consequence.py from ZenoNing/ConsDrive: direct link, hf CLI and curl.
- Browser
- Download file 19.3 kB
-
https://huggingface.co/ZenoNing/ConsDrive/resolve/main/models/plan_consequence.py
- Command line
-
hf download hf://ZenoNing/ConsDrive/models/plan_consequence.py
-
curl -L -o plan_consequence.py https://huggingface.co/ZenoNing/ConsDrive/resolve/main/models/plan_consequence.py
19.3 kB
| """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]") | |