File size: 19,343 Bytes
314ecfb | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 | """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]")
|