ZenoNing commited on
Commit
314ecfb
·
verified ·
1 Parent(s): 3e56913

Upload ConsDrive v2 source (part 2)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. models/adaptors/__init__.py +1 -0
  2. models/adaptors/adaptors.py +363 -0
  3. models/detector.py +274 -0
  4. models/detector_metrics.py +135 -0
  5. models/driving.py +1195 -0
  6. models/encoder/__init__.py +1 -0
  7. models/encoder/dinov2_lora.py +218 -0
  8. models/encoder/llavanext.py +107 -0
  9. models/encoder/llavanext_model.py +150 -0
  10. models/encoder/qwen2_5_vl.py +94 -0
  11. models/encoder/qwen3_vl.py +115 -0
  12. models/encoder/resnet.py +106 -0
  13. models/fastvlm.py +125 -0
  14. models/fastvlm_driving.py +74 -0
  15. models/fastvlm_object_driving.py +194 -0
  16. models/language_model/__init__.py +1 -0
  17. models/language_model/llama.py +194 -0
  18. models/language_model/qwen2_5_vl.py +83 -0
  19. models/language_model/qwen3_vl.py +109 -0
  20. models/language_model/qwen3_vl_scratch.py +105 -0
  21. models/language_model/qwen3_vl_truncated.py +124 -0
  22. models/language_model/tiny_transformer.py +149 -0
  23. models/pim.py +139 -0
  24. models/pim_driving.py +176 -0
  25. models/pim_losses.py +32 -0
  26. models/plan_consequence.py +519 -0
  27. models/qwen_utils.py +80 -0
  28. models/stream_petr.py +611 -0
  29. models/utils.py +200 -0
  30. models/world_predictor.py +227 -0
  31. original_scores.txt +8 -0
  32. requirements-pim.txt +23 -0
  33. scripts/analysis/ability_benchmark.py +178 -0
  34. scripts/analysis/cf_batch.py +66 -0
  35. scripts/analysis/cf_creep.py +288 -0
  36. scripts/analysis/cf_reactive.py +50 -0
  37. scripts/analysis/compare_reproduction.py +162 -0
  38. scripts/analysis/compare_runs.py +111 -0
  39. scripts/analysis/compare_speed_mask.py +140 -0
  40. scripts/analysis/compare_stream_petr.py +99 -0
  41. scripts/analysis/compare_tracker_finetune.py +44 -0
  42. scripts/analysis/compare_tracker_offline.py +31 -0
  43. scripts/analysis/extents.json +370 -0
  44. scripts/analysis/extract_failed.py +59 -0
  45. scripts/analysis/failure_report.py +235 -0
  46. scripts/analysis/fixability.py +95 -0
  47. scripts/analysis/recorder_extract.py +124 -0
  48. scripts/analysis/recorder_traffic_lights.py +90 -0
  49. scripts/analysis/stall_reasons.py +172 -0
  50. scripts/analysis/stall_summary.py +23 -0
models/adaptors/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+
models/adaptors/adaptors.py ADDED
@@ -0,0 +1,363 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Dict, List, Optional, Tuple
2
+
3
+ import torch
4
+ import torch.nn.functional as F
5
+ from torch import Tensor, nn
6
+
7
+ from utils.custom_types import DrivingExample
8
+
9
+
10
+ def compute_waypoint_loss(
11
+ prediction: Tensor,
12
+ label: Tensor,
13
+ loss_fn: str = "mse",
14
+ smooth_l1_beta: float = 1.0,
15
+ ) -> Tensor:
16
+ """Per-sample waypoint loss averaged over waypoints; last dim is (x, y) or distance."""
17
+ if loss_fn == "mse":
18
+ return F.mse_loss(prediction, label, reduction="none").sum(-1).mean(-1)
19
+ if loss_fn == "smooth_l1":
20
+ return F.smooth_l1_loss(
21
+ prediction,
22
+ label,
23
+ beta=smooth_l1_beta,
24
+ reduction="none",
25
+ ).sum(-1).mean(-1)
26
+ raise ValueError(f"waypoint_loss_fn must be 'mse' or 'smooth_l1', not {loss_fn!r}")
27
+
28
+
29
+ class NormZeroOne(nn.Module):
30
+ def __init__(self, min_max: Tuple[float, float]):
31
+ super().__init__()
32
+ self.register_buffer("min_max", torch.tensor(min_max, dtype=torch.float), persistent=False)
33
+
34
+ def forward(self, x: Tensor) -> Tensor:
35
+ """Normalise tensor to [0, 1] using values from min_max"""
36
+ return (x - self.min_max[0]) / (self.min_max[1] - self.min_max[0])
37
+
38
+
39
+ class WaypointInputAdaptor(nn.Module):
40
+ """
41
+ Takes an input of shape [B, N, 2] and returns an output of shape [B, N, token_size]
42
+ Args:
43
+ token_size: feature dimension of output tensor.
44
+ hidden_size: hidden dimension used in Linear layers under the hood.
45
+ norm_layer: the `Module` to use to normalize the values of the input tensor.
46
+ """
47
+
48
+ def __init__(
49
+ self, token_size: int = 258, hidden_size: int = 64, norm_layer: Optional[nn.Module] = None
50
+ ):
51
+ super().__init__()
52
+ self.hidden_size = hidden_size
53
+ self.norm_layer = norm_layer
54
+ self.mlp = nn.Sequential(nn.Linear(2, hidden_size), nn.ReLU(True), nn.Linear(hidden_size, token_size))
55
+
56
+ def forward(self, x: Tensor) -> Tensor:
57
+ """
58
+ Args:
59
+ x: Input with dims [B, N, 2]
60
+
61
+ Returns:
62
+ Output with dims [B, N, token_size]
63
+ """
64
+ if self.norm_layer is not None:
65
+ x = self.norm_layer(x)
66
+ x = self.mlp(x)
67
+ return x
68
+
69
+
70
+ class VectorInputAdaptor(nn.Module):
71
+ """
72
+ Takes an input of shape [B, input_size] and returns an output of shape [B, 1, token_size]
73
+ Args:
74
+ input_size: Expected feature dimension of input tensor.
75
+ token_size: feature dimension of output tensor.
76
+ hidden_size: hidden dimension used in Linear layers under the hood.
77
+ norm_layer: the `Module` to use to normalize the values of the input tensor.
78
+ """
79
+
80
+ def __init__(
81
+ self,
82
+ input_size: int,
83
+ token_size: int = 258,
84
+ hidden_size: int = 64,
85
+ norm_layer: Optional[nn.Module] = None,
86
+ ):
87
+ super().__init__()
88
+ # store args
89
+ self.hidden_size = hidden_size
90
+ self.input_size = input_size
91
+ self.norm_layer = norm_layer
92
+ # networks
93
+ self.mlp = nn.Sequential(nn.Linear(input_size, hidden_size), nn.ReLU(True), nn.Linear(hidden_size, token_size))
94
+
95
+ def forward(self, x: Tensor) -> Tensor:
96
+ """
97
+ Args:
98
+ x: Input with dims [B, input_size]
99
+
100
+ Returns:
101
+ Output with dims [B, 1, token_size]
102
+ """
103
+ if self.norm_layer is not None:
104
+ x = self.norm_layer(x)
105
+ x = self.mlp(x).unsqueeze(1)
106
+ return x
107
+
108
+ class DrivingAdaptor(nn.Module):
109
+ def __init__(self,
110
+ hidden_size: int,
111
+ mlp_dim=256,
112
+ predict_route_as_wps=False,
113
+ speed_wps_mode=False,
114
+ waypoint_loss_fn: str = "mse",
115
+ smooth_l1_beta: float = 1.0,
116
+ latent_tokens: int = 0,
117
+ ):
118
+ super().__init__()
119
+ self.heads = {}
120
+ self.queries = {}
121
+ self.sizes = {}
122
+ self.order = []
123
+
124
+ self.speed_wps_mode = speed_wps_mode
125
+ self.predict_route_as_wps = predict_route_as_wps
126
+ self.waypoint_loss_fn = waypoint_loss_fn
127
+ self.smooth_l1_beta = smooth_l1_beta
128
+
129
+ # Latent world-model queries: no prediction head, the LM hidden states
130
+ # at these positions are supervised through the world predictor.
131
+ # Placed first so route/speed queries can attend to them (causal LM).
132
+ self.num_latent_tokens = int(latent_tokens)
133
+ if self.num_latent_tokens > 0:
134
+ self.query_embeds_latent = nn.Parameter(
135
+ 0.02 * torch.randn((1, self.num_latent_tokens, hidden_size))
136
+ )
137
+ self.queries['latent'] = self.query_embeds_latent
138
+ self.sizes['latent'] = self.num_latent_tokens
139
+ self.order.append('latent')
140
+
141
+ if predict_route_as_wps:
142
+ self.future_waypoints = 20
143
+ self.query_embeds_wps = nn.Parameter(0.02 * torch.randn((1, self.future_waypoints, hidden_size)))
144
+ self.route_head = nn.Sequential(
145
+ nn.Linear(hidden_size, mlp_dim), nn.SiLU(True), nn.Linear(mlp_dim, 2, bias=False)
146
+ )
147
+
148
+ self.queries['route'] = self.query_embeds_wps
149
+ self.sizes['route'] = self.future_waypoints
150
+ self.heads["route"] = self.route_head
151
+ self.order.append('route')
152
+
153
+ if speed_wps_mode == '2d':
154
+ dim = 2
155
+ elif speed_wps_mode == '1d':
156
+ dim = 1
157
+ else:
158
+ raise ValueError(f"speed_wps_mode must be '1d' or '2d', not {speed_wps_mode}")
159
+ self.future_speed_waypoints = 10
160
+ self.query_embeds_speed = nn.Parameter(0.02 * torch.randn((1, self.future_speed_waypoints, hidden_size)))
161
+ self.speed_wps_head = nn.Sequential(
162
+ nn.Linear(hidden_size, mlp_dim), nn.SiLU(True), nn.Linear(mlp_dim, dim, bias=False)
163
+ )
164
+ self.heads["speed_wps"] = self.speed_wps_head
165
+ self.queries['speed_wps'] = self.query_embeds_speed
166
+ self.sizes['speed_wps'] = self.future_speed_waypoints
167
+ self.order.append('speed_wps')
168
+
169
+ def _head_input(self, input_type: str, features: Tensor) -> Tensor:
170
+ head_dtype = next(self.heads[input_type].parameters()).dtype
171
+ return features.to(dtype=head_dtype)
172
+
173
+
174
+ def forward(self,
175
+ driving_example: DrivingExample,
176
+ **kwargs
177
+ ) -> Dict[str, Tensor]:
178
+
179
+ try:
180
+ driving_input = driving_example.driving_input
181
+ except AttributeError:
182
+ driving_input = driving_example
183
+
184
+ b = driving_input.vehicle_speed.shape[0]
185
+ inputs = None
186
+
187
+ for input_type in self.order:
188
+ query_embed = self.queries[input_type]
189
+ if inputs is None:
190
+ inputs = query_embed.expand(b, -1, -1)
191
+ else:
192
+ inputs = torch.cat((inputs, query_embed.expand(b, -1, -1)), dim=1)
193
+
194
+ inputs_mask = torch.ones_like(inputs[:, :, 0], dtype=torch.bool)
195
+
196
+ return {"inputs": inputs, "inputs_mask": inputs_mask}
197
+
198
+ def get_predictions(
199
+ self,
200
+ features: Tensor
201
+ ) -> Dict:
202
+
203
+ current_index = 0
204
+ predictions = {}
205
+ for i, input_type in enumerate(self.order):
206
+ size = self.sizes[input_type]
207
+ if input_type not in self.heads:
208
+ # latent world-model queries have no prediction head
209
+ current_index += size
210
+ continue
211
+
212
+ feature = self._head_input(input_type, features[:, current_index: current_index + size])
213
+ prediction = self.heads[input_type](feature).cumsum(1)
214
+
215
+ predictions[input_type] = prediction
216
+ current_index += size
217
+
218
+ return predictions
219
+
220
+
221
+ def compute_loss(
222
+ self, adaptor_features: Tensor, _inputs: Dict[str, Tensor], example: DrivingExample
223
+ ) -> Dict[str, Tuple[Tensor, Tensor]]:
224
+ label = example.driving_label
225
+ assert label is not None
226
+
227
+ if self.predict_route_as_wps:
228
+ label_route = label.route_adjusted
229
+ else:
230
+ label_route = None
231
+
232
+ if self.speed_wps_mode == '2d':
233
+ label_speed_wps = label.waypoints[:, : self.future_speed_waypoints]
234
+ elif self.speed_wps_mode == '1d':
235
+ label_speed_wps = label.waypoints_1d
236
+ else:
237
+ label_speed_wps = None
238
+
239
+ current_index = 0
240
+ loss_dict = {}
241
+ for i, input_type in enumerate(self.order):
242
+ size = self.sizes[input_type]
243
+ if input_type not in self.heads:
244
+ # expose the raw LM features (e.g. latent world-model tokens)
245
+ # to the caller instead of applying a head/loss
246
+ loss_dict[f"{input_type}_features"] = adaptor_features[:, current_index: current_index + size]
247
+ current_index += size
248
+ continue
249
+ features_tmp = self._head_input(input_type, adaptor_features[:, current_index: current_index + size])
250
+ label = locals()[f'label_{input_type}']
251
+
252
+ prediction = self.heads[input_type](features_tmp).cumsum(1)
253
+ loss = compute_waypoint_loss(
254
+ prediction,
255
+ label,
256
+ loss_fn=self.waypoint_loss_fn,
257
+ smooth_l1_beta=self.smooth_l1_beta,
258
+ )
259
+
260
+ loss_dict[f"{input_type}_loss"] = (loss, torch.ones_like(loss, dtype=torch.long))
261
+ loss_dict[f"{input_type}_prediction"] = prediction
262
+ loss_dict[f"{input_type}_label"] = label
263
+ current_index += size
264
+
265
+ return loss_dict
266
+
267
+ class AdaptorList(nn.Module):
268
+ """
269
+ Each adaptor is responsible for converting a driving example
270
+ to a sequence of tokens and computing the loss on the token outputs.
271
+ Adaptors are only used during training.
272
+ """
273
+
274
+ def __init__(
275
+ self,
276
+ driving: Optional[DrivingAdaptor] = None,
277
+ ):
278
+ super().__init__()
279
+ self.driving = driving
280
+
281
+ @property
282
+ def adaptors(self):
283
+ dct: Dict[str, Adaptor] = {}
284
+ if self.driving is not None:
285
+ dct["driving"] = self.driving
286
+ return dct
287
+
288
+ def forward(self, example: DrivingExample) -> Dict[str, Tensor]:
289
+ """
290
+ Construct input embeddings for the given driving example.
291
+ """
292
+
293
+ input_dict: Dict[str, Tensor] = {}
294
+ inputs_list: List[Tensor] = []
295
+ inputs_mask_list: List[Tensor] = []
296
+
297
+ for key, adaptor in self.adaptors.items():
298
+ adaptor_input_dict = adaptor.forward(example)
299
+ inputs_list.append(adaptor_input_dict["inputs"])
300
+ inputs_mask_list.append(adaptor_input_dict["inputs_mask"])
301
+ input_dict.update({key + "_" + k: v for k, v in adaptor_input_dict.items()})
302
+
303
+ inputs = torch.cat(inputs_list, dim=1)
304
+ inputs_mask = torch.cat(inputs_mask_list, dim=1)
305
+ split_sizes = torch.as_tensor([x.size(1) for x in inputs_list])
306
+ arange = torch.arange(inputs.size(0), device=inputs.device)[:, None]
307
+
308
+ # Apply random permutation of modalities during training
309
+ rand_perm = torch.arange(inputs.size(1), device=inputs.device).expand(inputs.size(0), -1)
310
+ # Apply permutation to move invalid tokens to end of sequence
311
+ valid_perm = inputs_mask[arange, rand_perm].byte().argsort(dim=-1, descending=True, stable=True)
312
+ perm = rand_perm.gather(1, valid_perm)
313
+
314
+ input_dict["inputs"] = inputs[arange, perm]
315
+ input_dict["inputs_mask"] = inputs_mask[arange, perm]
316
+ input_dict["perm"] = perm
317
+ input_dict["split_sizes"] = split_sizes
318
+ return input_dict
319
+
320
+ def compute_loss(
321
+ self, features: Tensor, input_dict: Dict[str, Tensor], example: DrivingExample
322
+ ) -> Dict[str, Tuple[Tensor, Tensor]]:
323
+ """
324
+ Distributes the output embeddings from the transformer to
325
+ the correct loss function and returns a dictionary of losses.
326
+ """
327
+
328
+ features_by_adaptor = self.split_outputs_by_adaptor(input_dict, features)
329
+
330
+ loss_dict: Dict[str, Tuple[Tensor, Tensor]] = {}
331
+
332
+ # Compute loss in each adaptor
333
+ loss_dict: Dict[str, Tuple[Tensor, Tensor]] = {}
334
+ for key, adaptor in self.adaptors.items():
335
+ adaptor_input_dict = _gather_from_dict(input_dict, key + "_")
336
+ adaptor_features = features_by_adaptor[key]
337
+ losses = adaptor.compute_loss(adaptor_features, adaptor_input_dict, example)
338
+ loss_dict.update(losses)
339
+
340
+ return loss_dict
341
+
342
+ def split_outputs_by_adaptor(self, input_dict: Dict[str, Tensor], outputs: Tensor) -> Dict[str, Tensor]:
343
+ """
344
+ Splits the output tensor into the correct output for each adaptor, according to the
345
+ split_sizes in the input_dict.
346
+ """
347
+ # First reverse permutation
348
+ inv_perm = input_dict["perm"].argsort(-1)
349
+ arange = torch.arange(inv_perm.size(0), device=inv_perm.device)[:, None]
350
+ outputs = outputs[arange, inv_perm]
351
+
352
+ # Now split output for each adaptor
353
+ split_sizes = [int(x) for x in input_dict["split_sizes"]]
354
+ outputs_list = list(outputs.split(split_sizes, dim=1))
355
+ return {key: outputs_list[i] for i, key in enumerate(self.adaptors.keys())}
356
+
357
+
358
+ def _gather_from_dict(d: Dict[str, Tensor], prefix: str):
359
+ out: Dict[str, Tensor] = {} # dict comprehensions with if not supported
360
+ for k, v in d.items():
361
+ if k.startswith(prefix):
362
+ out[k[len(prefix) :]] = v
363
+ return out
models/detector.py ADDED
@@ -0,0 +1,274 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Stage 2: two-frame monocular 3D detector on the FastVLM vision tower (FastViTHD).
2
+
3
+ CenterNet-style head at stride 8 on an FPN over the FastViTHD stages (stride 8/16/32/64). Per class
4
+ heatmap peaks give the projected 3D box centre; the same cell regresses the sub-pixel offset, the
5
+ camera-frame depth (Laplace NLL, so every detection carries a depth uncertainty for the tracker),
6
+ log half extents and the allocentric heading. A motion branch correlates the current features with
7
+ those of the frame 0.25 s earlier (local cost volumes at stride 16 and 32, conditioned on the ego
8
+ motion) and regresses the object's velocity in the current ego frame, also with an uncertainty.
9
+
10
+ Decoded detections are rows in the object-bank convention (dataloader.object_bank): x forward,
11
+ y right, heading and speed along the heading, half extents, class.
12
+ """
13
+ import math
14
+ import os
15
+ import sys
16
+
17
+ import torch
18
+ import torch.nn.functional as F
19
+ from torch import nn
20
+
21
+ from dataloader.detection_data import (
22
+ 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,
23
+ T_LOG_W, T_OFF_U, T_OFF_V, T_SIN, T_VX, T_VY,
24
+ )
25
+ from dataloader.object_bank import NUM_CLASSES
26
+
27
+ # index in FastViT.network after which the stride-8/16/32/64 stage outputs are taken
28
+ FASTVIT_STAGE_INDEX = {8: 2, 16: 4, 32: 7, 64: 10}
29
+ FASTVIT_CHANNELS = {8: 192, 16: 384, 32: 768, 64: 1536}
30
+ FASTVLM_PREFIX = "model.vision_tower.vision_tower.model."
31
+ LIGHTNING_PREFIX = "vision_model.image_encoder.vision_tower.model."
32
+
33
+
34
+ def build_fastvithd(init="pretrained/FastVLM-0.5B", source=None):
35
+ """FastViTHD with weights from a FastVLM checkpoint directory or a driving-model .ckpt."""
36
+ source = source or os.environ.get("FASTVLM_SOURCE", "/workspace/code/ml-fastvlm")
37
+ if source not in sys.path:
38
+ sys.path.insert(0, source)
39
+ from llava.model.multimodal_encoder.mobileclip.mci import fastvithd
40
+ model = fastvithd()
41
+ if os.path.isdir(init):
42
+ from safetensors.torch import load_file
43
+ state = load_file(os.path.join(init, "model.safetensors"))
44
+ prefix = FASTVLM_PREFIX
45
+ else:
46
+ state = torch.load(init, map_location="cpu", weights_only=False)["state_dict"]
47
+ prefix = LIGHTNING_PREFIX
48
+ state = {k[len(prefix):]: v.float() for k, v in state.items()
49
+ if k.startswith(prefix) and not k[len(prefix):].startswith(("conv_exp.", "head."))}
50
+ missing, unexpected = model.load_state_dict(state, strict=False)
51
+ missing = [k for k in missing if not k.startswith(("conv_exp.", "head."))]
52
+ if missing or unexpected:
53
+ raise RuntimeError(f"FastViTHD weights from {init}: missing {missing[:5]}, unexpected {unexpected[:5]}")
54
+ # the classification tail is never used
55
+ model.conv_exp, model.head = nn.Identity(), nn.Identity()
56
+ return model
57
+
58
+
59
+ def conv_block(cin, cout, k=3, dilation=1):
60
+ return nn.Sequential(nn.Conv2d(cin, cout, k, padding=dilation * (k // 2), dilation=dilation, bias=False),
61
+ nn.GroupNorm(16, cout), nn.ReLU(inplace=True))
62
+
63
+
64
+ class FPN(nn.Module):
65
+ def __init__(self, channels=128):
66
+ super().__init__()
67
+ self.lateral = nn.ModuleDict({str(s): nn.Conv2d(c, channels, 1) for s, c in FASTVIT_CHANNELS.items()})
68
+ self.smooth = nn.ModuleDict({str(s): conv_block(channels, channels) for s in FASTVIT_CHANNELS})
69
+
70
+ def forward(self, feats):
71
+ out, top = {}, None
72
+ for s in sorted(FASTVIT_CHANNELS, reverse=True):
73
+ x = self.lateral[str(s)](feats[s])
74
+ if top is not None:
75
+ x = x + F.interpolate(top, size=x.shape[-2:], mode="bilinear", align_corners=False)
76
+ top = self.smooth[str(s)](x)
77
+ out[s] = top
78
+ return out
79
+
80
+
81
+ def local_correlation(a, b, radius):
82
+ """Cost volume <a(p), b(p + d)> / sqrt(C) for |d|_inf <= radius: [B, (2r+1)^2, H, W]."""
83
+ _, c, h, w = a.shape
84
+ k = 2 * radius + 1
85
+ b = F.unfold(F.pad(b, (radius,) * 4), kernel_size=k).view(a.shape[0], c, k * k, h, w)
86
+ return (a.unsqueeze(2) * b).sum(1) / math.sqrt(c)
87
+
88
+
89
+ def head(cin, cout, hidden=128, bias=0.0):
90
+ layer = nn.Conv2d(hidden, cout, 1)
91
+ nn.init.constant_(layer.bias, bias)
92
+ return nn.Sequential(conv_block(cin, hidden), conv_block(hidden, hidden), layer)
93
+
94
+
95
+ def ray_grid(device):
96
+ """Per-cell viewing-ray slopes (right, up) at stride 8: [1, 2, GRID_H, GRID_W]."""
97
+ u = (torch.arange(GRID_W, device=device) + 0.5) * STRIDE
98
+ v = (torch.arange(GRID_H, device=device) + 0.5) * STRIDE
99
+ ru = ((u - IMAGE_W / 2) / FOCAL)[None].expand(GRID_H, GRID_W)
100
+ rv = (-(v - IMAGE_H / 2) / FOCAL)[:, None].expand(GRID_H, GRID_W)
101
+ return torch.stack((ru, rv))[None]
102
+
103
+
104
+ class TwoFrameDetector(nn.Module):
105
+ # outputs per cell
106
+ OUT_OFFSET, OUT_DEPTH, OUT_SIZE, OUT_ORIENT, OUT_VEL = 2, 2, 3, 2, 4
107
+
108
+ def __init__(self, init="pretrained/FastVLM-0.5B", channels=128, corr_radius=4, freeze_backbone=False):
109
+ super().__init__()
110
+ self.backbone = build_fastvithd(init)
111
+ self.freeze_backbone = bool(freeze_backbone)
112
+ if self.freeze_backbone:
113
+ self.backbone.requires_grad_(False)
114
+ self.fpn = FPN(channels)
115
+ self.corr_radius = corr_radius
116
+ n_corr = (2 * corr_radius + 1) ** 2
117
+ c_app = channels + 2
118
+ self.heatmap = head(c_app, NUM_CLASSES, bias=-2.19)
119
+ self.box = head(c_app, self.OUT_OFFSET + self.OUT_DEPTH + self.OUT_SIZE + self.OUT_ORIENT)
120
+ # motion: cost volumes at stride 16 and 32 + current features + ego motion, upsampled to stride 8
121
+ self.motion16 = nn.Sequential(conv_block(2 * n_corr + channels + 4, channels),
122
+ conv_block(channels, channels, dilation=2), conv_block(channels, channels))
123
+ self.velocity = head(2 * channels + 2 + 4, self.OUT_VEL)
124
+
125
+ def backbone_features(self, images):
126
+ """uint8 [B, 3, H, W] (any size, 2:1) -> FPN levels {stride: [B, C, h, w]}."""
127
+ x = F.interpolate(images.float() / 255.0, size=(IMAGE_H, IMAGE_W), mode="bilinear",
128
+ align_corners=False, antialias=True)
129
+ x = self.backbone.patch_embed(x)
130
+ feats = {}
131
+ for i, block in enumerate(self.backbone.network):
132
+ x = block(x)
133
+ for s, idx in FASTVIT_STAGE_INDEX.items():
134
+ if idx == i:
135
+ feats[s] = x
136
+ if i >= FASTVIT_STAGE_INDEX[64]:
137
+ break
138
+ return feats
139
+
140
+ def forward(self, image, image_prev=None, ego_motion=None, prev_pyramid=None):
141
+ """Returns (outputs dict at stride 8, current FPN pyramid for reuse as the next prev_pyramid)."""
142
+ if self.freeze_backbone:
143
+ with torch.no_grad():
144
+ feats = self.backbone_features(image)
145
+ else:
146
+ feats = self.backbone_features(image)
147
+ pyramid = self.fpn(feats)
148
+ if prev_pyramid is None:
149
+ with torch.no_grad():
150
+ prev_pyramid = self.fpn(self.backbone_features(image_prev))
151
+ b = image.shape[0]
152
+ rays = ray_grid(image.device).expand(b, -1, -1, -1).to(pyramid[8].dtype)
153
+ app = torch.cat((pyramid[8], rays), 1)
154
+ ego = torch.stack((ego_motion[:, 0] / 5.0, ego_motion[:, 1] / 2.0, ego_motion[:, 2] * 5.0,
155
+ ego_motion[:, 3] / 10.0), 1).to(app.dtype)
156
+ r = self.corr_radius
157
+ c16 = local_correlation(pyramid[16], prev_pyramid[16], r)
158
+ c32 = F.interpolate(local_correlation(pyramid[32], prev_pyramid[32], r), size=c16.shape[-2:],
159
+ mode="bilinear", align_corners=False)
160
+ ego16 = ego[:, :, None, None].expand(-1, -1, *c16.shape[-2:])
161
+ m16 = self.motion16(torch.cat((c16, c32, pyramid[16], ego16), 1))
162
+ m8 = F.interpolate(m16, size=app.shape[-2:], mode="bilinear", align_corners=False)
163
+ ego8 = ego[:, :, None, None].expand(-1, -1, *app.shape[-2:])
164
+ box = self.box(app)
165
+ out = dict(
166
+ heatmap=self.heatmap(app),
167
+ offset=box[:, 0:2],
168
+ depth=box[:, 2:4], # log depth, log scale
169
+ size=box[:, 4:7],
170
+ orient=box[:, 7:9],
171
+ velocity=self.velocity(torch.cat((pyramid[8], m8, rays, ego8), 1)), # vx, vy, log scale x/y
172
+ )
173
+ return out, pyramid
174
+
175
+
176
+ def load_detector(path, device):
177
+ """TwoFrameDetector from a train_detector.py checkpoint, in eval mode."""
178
+ ckpt = torch.load(path, map_location="cpu", weights_only=False)
179
+ args = ckpt.get("args", {})
180
+ model = TwoFrameDetector(init=args.get("init", "pretrained/FastVLM-0.5B"),
181
+ freeze_backbone=args.get("freeze_backbone", False))
182
+ model.load_state_dict(ckpt["model"])
183
+ return model.to(device).eval()
184
+
185
+
186
+ # ---------------------------------------------------------------------------------------- losses
187
+ def focal_loss(logits, target, ignore):
188
+ pred = torch.sigmoid(logits.float()).clamp(1e-4, 1 - 1e-4)
189
+ pos = target.eq(1).float()
190
+ neg = (1 - pos) * (ignore[:, None] < 0.3).float()
191
+ pos_loss = torch.log(pred) * (1 - pred) ** 2 * pos
192
+ neg_loss = torch.log(1 - pred) * pred ** 2 * (1 - target) ** 4 * neg
193
+ n = pos.sum().clamp(min=1.0)
194
+ return -(pos_loss.sum() + neg_loss.sum()) / n
195
+
196
+
197
+ def gather(feature, index):
198
+ """[B, C, H, W], [B, K] -> [B, K, C]"""
199
+ b, c = feature.shape[:2]
200
+ return feature.view(b, c, -1).gather(2, index[:, None].expand(-1, c, -1)).transpose(1, 2).float()
201
+
202
+
203
+ def l1_and_scale(pred, log_scale, target):
204
+ """L1 on the mean plus a Laplace NLL that only trains the scale. With a plain NLL the rare hard
205
+ targets (moving objects among mostly parked ones) get an inflated scale instead of a mean."""
206
+ log_scale = log_scale.clamp(-5.0, 5.0)
207
+ err = (pred - target).abs()
208
+ return err + err.detach() * torch.exp(-log_scale) + log_scale
209
+
210
+
211
+ def detection_loss(out, batch, weights=None):
212
+ w = dict(heatmap=1.0, offset=1.0, depth=1.0, size=0.5, orient=0.5, velocity=0.5)
213
+ w.update(weights or {})
214
+ mask = batch["mask"]
215
+ n = mask.sum().clamp(min=1.0)
216
+ index, target = batch["index"], batch["target"]
217
+ off, dep = gather(out["offset"], index), gather(out["depth"], index)
218
+ size, ori, vel = gather(out["size"], index), gather(out["orient"], index), gather(out["velocity"], index)
219
+ m = mask[..., None]
220
+ losses = dict(
221
+ heatmap=focal_loss(out["heatmap"], batch["heatmap"], batch["ignore"]),
222
+ offset=((off - target[..., [T_OFF_U, T_OFF_V]]).abs() * m).sum() / n,
223
+ depth=(l1_and_scale(dep[..., 0], dep[..., 1], target[..., T_LOG_DEPTH]) * mask).sum() / n,
224
+ size=((size - target[..., [T_LOG_L, T_LOG_W, T_LOG_H]]).abs() * m).sum() / n,
225
+ orient=((ori - target[..., [T_SIN, T_COS]]).abs() * m).sum() / n,
226
+ velocity=(l1_and_scale(vel[..., 0:2], vel[..., 2:4], target[..., [T_VX, T_VY]]) * m).sum() / n,
227
+ )
228
+ losses["total"] = sum(w[k] * v for k, v in losses.items())
229
+ return losses
230
+
231
+
232
+ # ---------------------------------------------------------------------------------------- decoding
233
+ @torch.no_grad()
234
+ def decode(out, score_threshold=0.3, max_detections=64):
235
+ """Detections per image: list of dicts of tensors (x, y, z, yaw, speed, vx, vy, half extents, class,
236
+ score, depth_sigma, velocity_sigma) in the ego frame of the current image."""
237
+ heat = torch.sigmoid(out["heatmap"].float())
238
+ peaks = heat * (F.max_pool2d(heat, 3, stride=1, padding=1) == heat).float()
239
+ b, c, h, w = peaks.shape
240
+ scores, flat = peaks.view(b, -1).topk(max_detections)
241
+ cls = flat // (h * w)
242
+ cell = flat % (h * w)
243
+ iy, ix = (cell // w).float(), (cell % w).float()
244
+ results = []
245
+ for i in range(b):
246
+ keep = scores[i] >= score_threshold
247
+ idx = cell[i][keep][None]
248
+ off = gather(out["offset"][i:i + 1], idx)[0]
249
+ dep = gather(out["depth"][i:i + 1], idx)[0]
250
+ size = gather(out["size"][i:i + 1], idx)[0]
251
+ ori = gather(out["orient"][i:i + 1], idx)[0]
252
+ vel = gather(out["velocity"][i:i + 1], idx)[0]
253
+ u = (ix[i][keep] + off[:, 0]) * STRIDE
254
+ v = (iy[i][keep] + off[:, 1]) * STRIDE
255
+ depth = torch.exp(dep[:, 0])
256
+ yc = (u - IMAGE_W / 2) * depth / FOCAL
257
+ zc = -(v - IMAGE_H / 2) * depth / FOCAL
258
+ alpha = torch.atan2(ori[:, 0], ori[:, 1])
259
+ yaw = alpha + torch.atan2(yc, depth)
260
+ vx, vy = vel[:, 0], vel[:, 1]
261
+ speed = torch.hypot(vx, vy)
262
+ # heading from appearance is ambiguous front/back; trust the motion when the object moves
263
+ moving_dir = torch.atan2(vy, vx)
264
+ flip = (speed > 1.0) & (torch.cos(moving_dir - yaw) < 0)
265
+ yaw = torch.where(flip, yaw + math.pi, yaw)
266
+ yaw = torch.atan2(torch.sin(yaw), torch.cos(yaw))
267
+ ext = torch.exp(size)
268
+ results.append(dict(
269
+ x=depth + CAMERA_X, y=yc, z=zc + CAMERA_Z, yaw=yaw, speed=speed, vx=vx, vy=vy,
270
+ half_l=ext[:, 0], half_w=ext[:, 1], half_h=ext[:, 2], cls=cls[i][keep], score=scores[i][keep],
271
+ depth_sigma=torch.exp(dep[:, 1].clamp(-5, 5)) * depth, # Laplace scale of log depth -> metres
272
+ velocity_sigma=torch.exp(vel[:, 2:4].clamp(-5, 5)),
273
+ ))
274
+ return results
models/detector_metrics.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Detection metrics in the terms of the tracker acceptance criteria (BEV, per range bin).
2
+
3
+ Predictions are matched greedily by score to the nearest unmatched labelled box within
4
+ 1.5 m + 5 % of its range. Recall is reported against two ground truths: "positive" (bank-visible
5
+ and hit by the lidar, what the detector is trained on) and "bank" (bank-visible only, what the
6
+ oracle stage-3 model was given). A false positive is a prediction within range that matches no
7
+ labelled box at all, so detections of uncertain/ignored boxes are not counted against it.
8
+ """
9
+ import numpy as np
10
+
11
+ from dataloader.detection_data import CAMERA_X, is_positive
12
+ from dataloader.detection_labels import (
13
+ OBJ_BANK_VISIBLE, OBJ_CLASS, OBJ_SPEED, OBJ_X, OBJ_Y, OBJ_YAW,
14
+ )
15
+
16
+ RANGE_BINS = ((0, 10), (10, 20), (20, 30), (30, 40), (40, 50))
17
+ CLASS_NAMES = ("car", "walker", "static")
18
+
19
+
20
+ def match(pred_xy, pred_score, gt_xy, gt_range):
21
+ """Greedy score-ordered matching; returns gt index per prediction (-1 unmatched)."""
22
+ assigned = np.full(len(pred_xy), -1, dtype=np.int64)
23
+ if len(pred_xy) == 0 or len(gt_xy) == 0:
24
+ return assigned
25
+ dist = np.linalg.norm(pred_xy[:, None] - gt_xy[None], axis=-1)
26
+ gate = 1.5 + 0.05 * gt_range
27
+ taken = np.zeros(len(gt_xy), dtype=bool)
28
+ for p in np.argsort(-pred_score):
29
+ d = np.where(taken | (dist[p] > gate), np.inf, dist[p])
30
+ g = int(np.argmin(d))
31
+ if np.isfinite(d[g]):
32
+ assigned[p] = g
33
+ taken[g] = True
34
+ return assigned
35
+
36
+
37
+ class DetectionMetrics:
38
+ def __init__(self, max_range=50.0, thresholds=(0.2, 0.3, 0.4, 0.5)):
39
+ self.max_range = max_range
40
+ self.thresholds = thresholds
41
+ self.frames = 0
42
+ self.gt = [] # per labelled box: range, class, positive, bank, speed, matched-at-threshold..., errors
43
+ self.fp = {t: 0 for t in thresholds}
44
+ self.errors = [] # matched positives at the 0.3 threshold: range, class, pos err, lon, lat, vel err, speed, yaw err
45
+
46
+ def add(self, gt_rows, det):
47
+ """gt_rows [N, OBJ_DIM] numpy; det: decoded dict of tensors for one image."""
48
+ self.frames += 1
49
+ det = {k: v.detach().float().cpu().numpy() for k, v in det.items()}
50
+ gt_xy = gt_rows[:, [OBJ_X, OBJ_Y]].astype(np.float64)
51
+ gt_range = np.hypot(gt_xy[:, 0] - CAMERA_X, gt_xy[:, 1])
52
+ pos = is_positive(gt_rows, self.max_range)
53
+ bank = (gt_rows[:, OBJ_BANK_VISIBLE] > 0.5) & (gt_range <= self.max_range)
54
+ pred_xy = np.stack((det["x"], det["y"]), -1).astype(np.float64)
55
+ pred_range = np.hypot(pred_xy[:, 0] - CAMERA_X, pred_xy[:, 1])
56
+ matched = {}
57
+ for t in self.thresholds:
58
+ keep = det["score"] >= t
59
+ a = match(pred_xy[keep], det["score"][keep], gt_xy, gt_range)
60
+ hit = np.zeros(len(gt_rows), dtype=bool)
61
+ hit[a[a >= 0]] = True
62
+ matched[t] = hit
63
+ self.fp[t] += int(((a < 0) & (pred_range[keep] <= self.max_range)).sum())
64
+ if t == 0.3:
65
+ idx = np.flatnonzero(keep)
66
+ for p, g in zip(idx[a >= 0], a[a >= 0]):
67
+ if not pos[g]:
68
+ continue
69
+ d = pred_xy[p] - gt_xy[g]
70
+ ray = gt_xy[g] - (CAMERA_X, 0.0)
71
+ ray /= max(np.linalg.norm(ray), 1e-6)
72
+ gv = gt_rows[g, OBJ_SPEED] * np.array((np.cos(gt_rows[g, OBJ_YAW]), np.sin(gt_rows[g, OBJ_YAW])))
73
+ yaw_err = abs((det["yaw"][p] - gt_rows[g, OBJ_YAW] + np.pi) % (2 * np.pi) - np.pi)
74
+ self.errors.append((gt_range[g], gt_rows[g, OBJ_CLASS], np.linalg.norm(d), d @ ray,
75
+ abs(d[0] * -ray[1] + d[1] * ray[0]),
76
+ np.linalg.norm((det["vx"][p], det["vy"][p]) - gv), gt_rows[g, OBJ_SPEED],
77
+ yaw_err, det["depth_sigma"][p], int(det["cls"][p] == gt_rows[g, OBJ_CLASS])))
78
+ for g in range(len(gt_rows)):
79
+ self.gt.append((gt_range[g], gt_rows[g, OBJ_CLASS], pos[g], bank[g], gt_rows[g, OBJ_SPEED],
80
+ *[matched[t][g] for t in self.thresholds]))
81
+
82
+ def summary(self):
83
+ gt = np.asarray(self.gt, dtype=np.float64).reshape(-1, 5 + len(self.thresholds))
84
+ err = np.asarray(self.errors, dtype=np.float64).reshape(-1, 10)
85
+ out = dict(frames=self.frames, fp_per_frame={t: self.fp[t] / max(self.frames, 1) for t in self.thresholds})
86
+ k30 = 5 + self.thresholds.index(0.3)
87
+ for c, name in enumerate(CLASS_NAMES):
88
+ rows = {}
89
+ for lo, hi in RANGE_BINS:
90
+ sel = (gt[:, 1] == c) & (gt[:, 0] >= lo) & (gt[:, 0] < hi)
91
+ p, b = sel & (gt[:, 2] > 0), sel & (gt[:, 3] > 0)
92
+ e = err[(err[:, 1] == c) & (err[:, 0] >= lo) & (err[:, 0] < hi)]
93
+ rows[f"{lo}-{hi}"] = dict(
94
+ n_pos=int(p.sum()), recall_pos=float(gt[p, k30].mean()) if p.any() else None,
95
+ recall_bank=float(gt[b, k30].mean()) if b.any() else None,
96
+ pos_err_med=float(np.median(e[:, 2])) if len(e) else None,
97
+ pos_err_p90=float(np.percentile(e[:, 2], 90)) if len(e) else None,
98
+ lon_err_med=float(np.median(np.abs(e[:, 3]))) if len(e) else None,
99
+ lat_err_med=float(np.median(e[:, 4])) if len(e) else None,
100
+ vel_err_med=float(np.median(e[:, 5])) if len(e) else None,
101
+ cls_acc=float(e[:, 9].mean()) if len(e) else None)
102
+ p50 = (gt[:, 1] == c) & (gt[:, 2] > 0)
103
+ rows["recall_pos_0-50_by_threshold"] = {
104
+ t: float(gt[p50, 5 + i].mean()) if p50.any() else None for i, t in enumerate(self.thresholds)}
105
+ out[name] = rows
106
+ cars = err[err[:, 1] == 0]
107
+ if len(cars):
108
+ speed_bins = {}
109
+ for lo, hi in ((0, 0.5), (0.5, 5), (5, 10), (10, 20)):
110
+ s = cars[(cars[:, 6] >= lo) & (cars[:, 6] < hi)]
111
+ if len(s):
112
+ speed_bins[f"{lo}-{hi}"] = dict(n=len(s), vel_err_med=float(np.median(s[:, 5])),
113
+ vel_err_p90=float(np.percentile(s[:, 5], 90)),
114
+ yaw_err_med_deg=float(np.degrees(np.median(s[:, 7]))))
115
+ out["car_velocity_by_speed"] = speed_bins
116
+ return out
117
+
118
+
119
+ def format_summary(s):
120
+ lines = [f"frames {s['frames']} FP/frame " + " ".join(f"@{t}: {v:.3f}" for t, v in s["fp_per_frame"].items())]
121
+ for name in CLASS_NAMES:
122
+ lines.append(f"{name:7s} range n_pos rec_pos rec_bank err_med err_p90 lon lat vel_err cls_acc")
123
+ for key, r in s[name].items():
124
+ if key.startswith("recall_pos_0-50"):
125
+ lines.append(" recall_pos 0-50 by threshold: " + " ".join(
126
+ f"@{t}: {v:.3f}" for t, v in r.items() if v is not None))
127
+ continue
128
+ f = lambda v, w=6, p=2: (f"{v:{w}.{p}f}" if v is not None else " " * (w - 1) + "-") # noqa: E731
129
+ lines.append(f" {key:6s} {r['n_pos']:6d} {f(r['recall_pos'], 6, 3)} {f(r['recall_bank'], 6, 3)} "
130
+ f"{f(r['pos_err_med'])} {f(r['pos_err_p90'])} {f(r['lon_err_med'], 5)} "
131
+ f"{f(r['lat_err_med'], 5)} {f(r['vel_err_med'])} {f(r['cls_acc'], 5)}")
132
+ for key, r in s.get("car_velocity_by_speed", {}).items():
133
+ 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}"
134
+ f" yaw_err med {r['yaw_err_med_deg']:.1f} deg")
135
+ return "\n".join(lines)
models/driving.py ADDED
@@ -0,0 +1,1195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pickle as pkl
2
+ import warnings
3
+ from pprint import PrettyPrinter
4
+ from typing import Optional, Tuple
5
+
6
+ import pytorch_lightning as pl
7
+ import torch
8
+ from torch import Tensor, nn
9
+ from torchvision.models import ResNet18_Weights, resnet18
10
+
11
+ try:
12
+ from deepspeed.ops.adam import FusedAdam
13
+ except ModuleNotFoundError:
14
+ FusedAdam = None
15
+
16
+ from models.adaptors.adaptors import (
17
+ AdaptorList, DrivingAdaptor, VectorInputAdaptor, WaypointInputAdaptor
18
+ )
19
+ from models.utils import configure_params_groups, summarise_losses
20
+ from models.plan_consequence import (
21
+ PlanConditionedConsequenceHead,
22
+ PooledPlanConsequenceHead,
23
+ aggregate_risk_logits,
24
+ binary_waypoint_loss,
25
+ clearance_waypoint_loss,
26
+ expand_scene_for_plans,
27
+ make_hard_negative_plans,
28
+ pairwise_ranking_loss,
29
+ relative_min_clearance_hinge,
30
+ trajectory_geometry_targets,
31
+ visible_obstacle_mask,
32
+ )
33
+ from models.world_predictor import (
34
+ BlockCausalWorldPredictor, linear_world_weight, masked_world_l1
35
+ )
36
+ from utils.custom_types import (
37
+ DrivingExample, DrivingInput, DrivingLabel, ParamGroup, TrainingOutput
38
+ )
39
+
40
+ pprint = PrettyPrinter().pprint
41
+
42
+ class RouteEncode(nn.Module):
43
+ def __init__(self, out_channels: int, pretrained=True):
44
+ super().__init__()
45
+ self.backbone = resnet18(weights=ResNet18_Weights.IMAGENET1K_V1 if pretrained else None)
46
+ self.backbone.fc = nn.Linear(self.backbone.fc.in_features, out_channels)
47
+
48
+ def forward(self, route):
49
+ x = route.to(self.backbone.fc.weight.dtype) / 128.0 - 1.0
50
+ return self.backbone(x).unsqueeze(-2) # add token dim
51
+
52
+ class NormZeroOne(nn.Module):
53
+ def __init__(self, min_max: Tuple[float, float]):
54
+ super().__init__()
55
+ self.register_buffer("min_max", torch.tensor(min_max, dtype=torch.float), persistent=False)
56
+
57
+ def forward(self, x: Tensor) -> Tensor:
58
+ """Normalise tensor to [0, 1] using values from min_max"""
59
+ return (x - self.min_max[0]) / (self.min_max[1] - self.min_max[0])
60
+
61
+
62
+ class DrivingModel(pl.LightningModule):
63
+ def __init__(
64
+ self,
65
+ vision_model: nn.Module,
66
+ language_model: nn.Module,
67
+ lr: float = 1e-4,
68
+ vision_lr: Optional[float] = None,
69
+ lm_lr: Optional[float] = None,
70
+ weight_decay: float = 0.1,
71
+ betas: Tuple[float, float] = (0.9, 0.999),
72
+ pct_start: float = 0.05,
73
+ enable_language=False,
74
+ route_as=True,
75
+ speed_as_input=True,
76
+ new_layer_norm_minmax=False,
77
+ predict_route_as_wps=False,
78
+ speed_wps_mode=False,
79
+ waypoint_loss_fn: str = "mse",
80
+ smooth_l1_beta: float = 1.0,
81
+ variant=None,
82
+ nav_p_both: float = 0.4,
83
+ nav_p_command: float = 0.4,
84
+ nav_p_tp: float = 0.2,
85
+ jepa=None,
86
+ consequence=None,
87
+ vision_freeze_steps: int = 0,
88
+ vision_ramp_steps: int = 0,
89
+ speed_dropout_p: float = 0.0,
90
+ ):
91
+ super().__init__()
92
+
93
+ self.save_hyperparameters(ignore=["vision_model", "language_model"])
94
+ self.vision_model = vision_model
95
+ self.language_model = language_model
96
+ self.lr = lr
97
+ self.vision_lr = vision_lr
98
+ # optional separate LR for the LM trunk (pretrained-init small trunks
99
+ # want a lower LR than freshly initialised adaptors/heads)
100
+ self.lm_lr = lm_lr
101
+ self.weight_decay = weight_decay
102
+ self.betas = betas
103
+ self.pct_start = pct_start
104
+ self.enable_language = enable_language
105
+ self.route_as = route_as
106
+ self.speed_as_input = speed_as_input
107
+ self.new_layer_norm_minmax = new_layer_norm_minmax
108
+ self.predict_route_as_wps = predict_route_as_wps
109
+ self.speed_wps_mode = speed_wps_mode
110
+ self.waypoint_loss_fn = waypoint_loss_fn
111
+ self.smooth_l1_beta = smooth_l1_beta
112
+ # three-state navigation dropout probabilities (both / command-only / tp-only)
113
+ self.nav_probs = (nav_p_both, nav_p_command, nav_p_tp)
114
+ # training: hide the ego-speed token from this fraction of samples, so the policy can also act from
115
+ # the scene alone (the agent masks it while stalled to escape the v = 0 attractor of the speed input)
116
+ self.speed_dropout_p = float(speed_dropout_p)
117
+ self.vision_freeze_steps = int(vision_freeze_steps)
118
+ self.vision_ramp_steps = int(vision_ramp_steps)
119
+
120
+ self.all_predictions = {}
121
+ self.all_losses = {}
122
+
123
+ # V-JEPA2 world-model supervision on latent action queries
124
+ self.use_world_loss = bool(jepa is not None and jepa.get("enabled", False))
125
+ latent_tokens = 0
126
+ if self.use_world_loss:
127
+ self.latent_steps = int(jepa.get("latent_steps", 3))
128
+ self.latent_tokens_per_step = int(jepa.get("latent_tokens_per_step", 8))
129
+ latent_tokens = self.latent_steps * self.latent_tokens_per_step
130
+ self.world_loss_weight = float(jepa.get("world_loss_weight", 0.1))
131
+ self.world_loss_warmup_steps = int(jepa.get("world_loss_warmup_steps", 0))
132
+
133
+ driving = DrivingAdaptor(
134
+ self.language_model.hidden_size,
135
+ speed_wps_mode=speed_wps_mode,
136
+ predict_route_as_wps=predict_route_as_wps,
137
+ waypoint_loss_fn=waypoint_loss_fn,
138
+ smooth_l1_beta=smooth_l1_beta,
139
+ latent_tokens=latent_tokens,
140
+ )
141
+
142
+ self.adaptors = AdaptorList(
143
+ driving=driving,
144
+ )
145
+
146
+ self.world_predictor = None
147
+ if self.use_world_loss:
148
+ self.world_predictor = BlockCausalWorldPredictor(
149
+ action_dim=self.language_model.hidden_size,
150
+ predictor_dim=int(jepa.get("predictor_dim", 1024)),
151
+ target_dim=int(jepa.get("teacher_dim", 1024)),
152
+ depth=int(jepa.get("predictor_depth", 12)),
153
+ heads=int(jepa.get("predictor_heads", 8)),
154
+ mlp_ratio=float(jepa.get("predictor_mlp_ratio", 4.0)),
155
+ dropout=float(jepa.get("predictor_dropout", 0.0)),
156
+ num_blocks=self.latent_steps,
157
+ state_tokens=64,
158
+ action_tokens=self.latent_tokens_per_step,
159
+ )
160
+
161
+ # Explicit-plan consequence head. It is intentionally absent from
162
+ # forward(); only forward_loss invokes it during training/validation.
163
+ self.use_consequence_loss = bool(
164
+ consequence is not None and consequence.get("enabled", False)
165
+ )
166
+ self.consequence_cfg = consequence or {}
167
+ self.consequence_head = None
168
+ # "pooled" = ConsDrive v2 head (BCE risk logits + ranking supervision);
169
+ # "cross_attn" = ConsDrive v4 head (clearance regression + L_avoid);
170
+ # "cross_attn_risk" = ConsDrive v6: v4's cross-attention architecture
171
+ # trained with v2's BCE + ranking supervision.
172
+ self.consequence_head_type = str(
173
+ self.consequence_cfg.get("head_type", "cross_attn")
174
+ )
175
+ if self.consequence_head_type not in ("pooled", "cross_attn", "cross_attn_risk"):
176
+ raise ValueError(
177
+ "consequence.head_type must be 'pooled', 'cross_attn', or "
178
+ "'cross_attn_risk'"
179
+ )
180
+ if self.use_consequence_loss:
181
+ if self.consequence_head_type == "pooled":
182
+ self.consequence_head = PooledPlanConsequenceHead(
183
+ scene_dim=self.language_model.hidden_size,
184
+ hidden_dim=int(self.consequence_cfg.get("hidden_dim", 256)),
185
+ plan_dim=int(self.consequence_cfg.get("plan_dim", 128)),
186
+ horizon=10,
187
+ route_points=20,
188
+ dropout=float(self.consequence_cfg.get("dropout", 0.1)),
189
+ )
190
+ else:
191
+ self.consequence_head = PlanConditionedConsequenceHead(
192
+ scene_dim=self.language_model.hidden_size,
193
+ hidden_dim=int(self.consequence_cfg.get("hidden_dim", 256)),
194
+ plan_dim=int(self.consequence_cfg.get("plan_dim", 128)),
195
+ horizon=10,
196
+ route_points=20,
197
+ dropout=float(self.consequence_cfg.get("dropout", 0.1)),
198
+ attn_heads=int(self.consequence_cfg.get("attn_heads", 4)),
199
+ with_risk_head=(self.consequence_head_type == "cross_attn_risk"),
200
+ )
201
+
202
+ if self.speed_as_input:
203
+ if self.new_layer_norm_minmax:
204
+ min_max = (0.0, 110.0 / 3.6)
205
+ else:
206
+ min_max = (0.0, 64.0 / 3.6)
207
+ self.speed_encoder = VectorInputAdaptor(
208
+ input_size=1,
209
+ token_size=self.language_model.hidden_size,
210
+ hidden_size=256,
211
+ norm_layer=NormZeroOne(min_max=min_max),
212
+ )
213
+
214
+ if route_as in ('coords', 'target_point', 'command_tp'):
215
+ if self.new_layer_norm_minmax:
216
+ min_max = (-200.0, 200.0)
217
+ else:
218
+ min_max = (-32.0, 32.0)
219
+ self.route_encoder = WaypointInputAdaptor(
220
+ token_size=self.language_model.hidden_size,
221
+ hidden_size=256,
222
+ norm_layer=NormZeroOne(min_max=min_max),
223
+ )
224
+ elif route_as == 'command':
225
+ self.route_encoder = None
226
+ else:
227
+ self.route_encoder = RouteEncode(self.language_model.hidden_size, pretrained=True)
228
+
229
+ # Whether the vision encoder provides DeepStack features (Qwen3-VL)
230
+ self.use_deepstack = hasattr(self.vision_model, "num_deepstack_layers")
231
+
232
+ self.language_projection = nn.Identity()
233
+ if self.vision_model.token_size != self.language_model.hidden_size:
234
+ self.language_projection = nn.Linear(self.vision_model.token_size, self.language_model.hidden_size, bias=False)
235
+
236
+
237
+ # action-only models (from-scratch LM) have no tokenizer
238
+ self.tok = getattr(self.language_model, "tokenizer", None)
239
+ if self.tok is not None:
240
+ self.bos_token_id = self.tok.bos_token_id
241
+ self.eos_token_id = self.tok.eos_token_id
242
+ self.pad_token_id = self.tok.pad_token_id
243
+ else:
244
+ self.bos_token_id = None
245
+ self.eos_token_id = None
246
+ self.pad_token_id = None
247
+
248
+ def forward(self,
249
+ driving_input: DrivingInput,
250
+ prompt_ids: Optional[Tensor] = None,
251
+ return_context: bool = False):
252
+ """
253
+ Samples a trajectory from the model.
254
+
255
+ With ``return_context=True`` the LM vision-token sequence used by the
256
+ consequence head is returned so deployment-time plan scoring can reuse
257
+ the same backbone pass.
258
+ """
259
+ self.speed_wps, self.route, self.target_speed = None, None, None
260
+
261
+ # single forward pass same as during training so we can use the same function
262
+ inputs = self.adaptors(driving_input)
263
+ if return_context:
264
+ features, vision_tokens, vision_mask = self.forward_model(
265
+ driving_input, inputs["inputs"], return_context=True
266
+ )
267
+ else:
268
+ features = self.forward_model(driving_input, inputs["inputs"])
269
+ predictions = self.adaptors.driving.get_predictions(features)
270
+
271
+ for k, v in predictions.items():
272
+ if v is not None:
273
+ setattr(self, k, v)
274
+
275
+ if return_context:
276
+ return self.speed_wps, self.route, vision_tokens, vision_mask
277
+ return self.speed_wps, self.route
278
+
279
+ @staticmethod
280
+ def _pool_scene_context(vision_tokens: Tensor, vision_mask: Tensor) -> Tensor:
281
+ """Masked mean over LM vision-token outputs (the v2 scene feature)."""
282
+ mask = vision_mask.to(
283
+ device=vision_tokens.device, dtype=vision_tokens.dtype
284
+ )
285
+ return (vision_tokens * mask.unsqueeze(-1)).sum(dim=1) / mask.sum(
286
+ dim=1, keepdim=True
287
+ ).clamp_min(1.0)
288
+
289
+ def score_plan_risk(
290
+ self,
291
+ vision_tokens: Tensor,
292
+ vision_mask: Tensor,
293
+ route: Tensor,
294
+ speed_wps: Tensor,
295
+ ):
296
+ """Score candidate plans with the trained consequence head.
297
+
298
+ Returns per-waypoint collision probabilities ``[B, 10]`` and signed
299
+ clearance estimates ``[B, 10]`` in metres. The pooled (v2) head
300
+ supervises calibrated risk logits directly; the cross-attention (v4)
301
+ head only regresses clearance, so its risk is a sigmoid squash.
302
+ """
303
+ if self.consequence_head is None:
304
+ raise RuntimeError(
305
+ "score_plan_risk requires a checkpoint trained with the "
306
+ "consequence head enabled"
307
+ )
308
+ if self.consequence_head_type == "pooled":
309
+ scene_context = self._pool_scene_context(vision_tokens, vision_mask)
310
+ output = self.consequence_head(
311
+ scene_context.float(), route.float(), speed_wps.float()
312
+ )
313
+ return (
314
+ torch.sigmoid(output.risk_logits.float()),
315
+ output.clearance.float(),
316
+ )
317
+ output = self.consequence_head(
318
+ vision_tokens.float(),
319
+ vision_mask,
320
+ route.float(),
321
+ speed_wps.float(),
322
+ )
323
+ if self.consequence_head_type == "cross_attn_risk":
324
+ return (
325
+ torch.sigmoid(output.risk_logits.float()),
326
+ output.clearance.float(),
327
+ )
328
+ tau = max(float(self.consequence_cfg.get("risk_temperature", 1.0)), 1e-6)
329
+ risk = torch.sigmoid(-output.clearance.float() / tau)
330
+ return risk, output.clearance.float()
331
+
332
+
333
+ def forward_model(self,
334
+ driving_input: DrivingInput,
335
+ adaptor_embeds: Tensor,
336
+ driving_labels: DrivingLabel = None,
337
+ return_context: bool = False,
338
+ ):
339
+ """
340
+ Forward model conditioned on the given driving input.
341
+ """
342
+
343
+ vision_embeds, attention_mask, aux = self.get_fixed_input_embeds(driving_input)
344
+
345
+ input_embeds = torch.cat((vision_embeds, adaptor_embeds), dim=1)
346
+ adaptor_attention_mask = torch.ones(
347
+ adaptor_embeds.shape[:2],
348
+ dtype=torch.long,
349
+ device=adaptor_embeds.device,
350
+ )
351
+ if attention_mask is not None:
352
+ attention_mask = torch.cat((attention_mask, adaptor_attention_mask), dim=1)
353
+ # to dtype of language model
354
+ input_embeds = input_embeds.to(
355
+ dtype=self.language_model.model.dtype
356
+ )
357
+
358
+ lm_kwargs = {}
359
+ if self.use_deepstack:
360
+ total_len = input_embeds.size(1)
361
+ visual_pos_masks = torch.zeros(
362
+ input_embeds.shape[:2], dtype=torch.bool, device=input_embeds.device
363
+ )
364
+ visual_pos_masks[:, : aux["vision_mask"].size(1)] = aux["vision_mask"]
365
+ # flatten deepstack features in batch-major order at valid vision positions
366
+ deepstack_visual_embeds = [
367
+ feat[aux["vision_mask"]] for feat in aux["deepstack_embeds"]
368
+ ]
369
+ lm_kwargs["visual_pos_masks"] = visual_pos_masks
370
+ lm_kwargs["deepstack_visual_embeds"] = deepstack_visual_embeds
371
+ lm_kwargs["position_ids"] = self._build_mrope_position_ids(
372
+ aux["video_grid_thw"], total_len, input_embeds.device
373
+ )
374
+
375
+ outputs = self.language_model.forward(
376
+ input_embeds,
377
+ attention_mask=attention_mask,
378
+ **lm_kwargs,
379
+ )
380
+
381
+ vision_outputs, adaptor_outputs = outputs.split(
382
+ [outputs.size(1) - adaptor_embeds.size(1), adaptor_embeds.size(1)], dim=1
383
+ )
384
+ if return_context:
385
+ vision_mask = attention_mask[:, :vision_outputs.size(1)]
386
+ return adaptor_outputs, vision_outputs, vision_mask
387
+ return adaptor_outputs
388
+
389
+ def _build_mrope_position_ids(self, video_grid_thw: Tensor, total_len: int, device) -> Tensor:
390
+ """
391
+ Interleaved-MRoPE position ids [3, B, total_len] following Qwen3-VL's
392
+ get_rope_index: every temporal frame of the video is treated as its own
393
+ grid (t=1), text/extra tokens get sequential positions on all 3 axes.
394
+ """
395
+ merge = self.vision_model.spatial_merge_size
396
+ position_ids = torch.zeros(3, video_grid_thw.shape[0], total_len, dtype=torch.long, device=device)
397
+
398
+ for batch_idx in range(video_grid_thw.shape[0]):
399
+ grid_t, grid_h, grid_w = (int(x) for x in video_grid_thw[batch_idx])
400
+ llm_h, llm_w = grid_h // merge, grid_w // merge
401
+ pos_list = []
402
+ current_pos = 0
403
+ for _ in range(grid_t):
404
+ t_grid, h_grid, w_grid = torch.meshgrid(
405
+ torch.zeros(1, dtype=torch.long, device=device),
406
+ torch.arange(llm_h, device=device),
407
+ torch.arange(llm_w, device=device),
408
+ indexing="ij",
409
+ )
410
+ frame_pos = torch.stack([t_grid, h_grid, w_grid], dim=0).reshape(3, -1) + current_pos
411
+ pos_list.append(frame_pos)
412
+ current_pos += max(llm_h, llm_w)
413
+ vision_pos = torch.cat(pos_list, dim=1)
414
+ n_vision = vision_pos.size(1)
415
+ n_text = total_len - n_vision
416
+ text_pos = (torch.arange(n_text, device=device) + current_pos).view(1, -1).expand(3, -1)
417
+ position_ids[:, batch_idx] = torch.cat([vision_pos, text_pos], dim=1)
418
+
419
+ return position_ids
420
+
421
+ def get_fixed_input_embeds(self, driving_input: DrivingInput):
422
+ img = driving_input.camera_images #[:, 0, :, :, :] # only use the front camera
423
+
424
+ aux = {}
425
+ if self.use_deepstack:
426
+ vision_embeds, vision_mask_bool, deepstack_embeds = self.vision_model.forward(
427
+ img, image_sizes=driving_input.image_sizes
428
+ )
429
+ attention_mask = vision_mask_bool.to(device=vision_embeds.device, dtype=torch.long)
430
+ video_grid_thw = driving_input.image_sizes
431
+ if video_grid_thw.ndim == 3:
432
+ video_grid_thw = video_grid_thw.reshape(-1, 3)
433
+ aux["vision_mask"] = vision_mask_bool
434
+ aux["deepstack_embeds"] = [self.language_projection(f) for f in deepstack_embeds]
435
+ aux["video_grid_thw"] = video_grid_thw
436
+ else:
437
+ vision_embeds, vision_aux = self.vision_model.forward(img, image_sizes=driving_input.image_sizes)
438
+ if isinstance(vision_aux, torch.Tensor) and vision_aux.ndim == 2:
439
+ attention_mask = vision_aux.to(device=vision_embeds.device, dtype=torch.long)
440
+ else:
441
+ attention_mask = torch.ones(
442
+ vision_embeds.shape[:2],
443
+ dtype=torch.long,
444
+ device=vision_embeds.device,
445
+ )
446
+
447
+ # n_frames, n_tokens, channels = sizes
448
+ vision_embeds = self.language_projection(vision_embeds)
449
+ extra_embeds = []
450
+ extra_attention_masks = []
451
+ if self.speed_as_input:
452
+ vehicle_speed = driving_input.vehicle_speed
453
+ # a NaN speed means "unknown": the token is masked out of attention like a dropped nav token
454
+ speed_known = torch.isfinite(vehicle_speed).all(dim=-1)
455
+ speed = self.speed_encoder.forward(torch.nan_to_num(vehicle_speed, nan=0.0))
456
+ if self.training and self.speed_dropout_p > 0:
457
+ speed_known = speed_known & (torch.rand(speed_known.shape, device=speed_known.device)
458
+ >= self.speed_dropout_p)
459
+ extra_embeds.append(speed.to(dtype=vision_embeds.dtype))
460
+ extra_attention_masks.append(
461
+ speed_known.to(device=speed.device, dtype=torch.long).unsqueeze(1).expand(speed.shape[:2])
462
+ )
463
+
464
+ if self.route_as == 'command_tp':
465
+ batch_size = vision_embeds.size(0)
466
+ device = vision_embeds.device
467
+ # target-point tokens [B, 2, C]
468
+ tp_embeds = self.route_encoder.forward(driving_input.map_route)
469
+ tp_mask = torch.ones(tp_embeds.shape[:2], dtype=torch.long, device=device)
470
+ # command tokens [B, Lc, C]
471
+ cmd_embeds, cmd_mask = self.encode_navigation_command(
472
+ driving_input.navigation_command, device=device
473
+ )
474
+ # three-state conditional dropout during training:
475
+ # both (p0) / command-only (p1) / tp-only (p2); inference keeps both
476
+ if self.training:
477
+ p_both, p_cmd, _ = self.nav_probs
478
+ r = torch.rand(batch_size, device=device)
479
+ drop_tp = (r >= p_both) & (r < p_both + p_cmd) # command-only
480
+ drop_cmd = r >= p_both + p_cmd # tp-only
481
+ tp_mask = tp_mask * (~drop_tp).long().unsqueeze(1)
482
+ cmd_mask = cmd_mask * (~drop_cmd).long().unsqueeze(1)
483
+ extra_embeds.append(tp_embeds.to(dtype=vision_embeds.dtype))
484
+ extra_attention_masks.append(tp_mask)
485
+ extra_embeds.append(cmd_embeds.to(dtype=vision_embeds.dtype))
486
+ extra_attention_masks.append(cmd_mask)
487
+ elif self.route_as == 'command':
488
+ route, route_attention_mask = self.encode_navigation_command(
489
+ driving_input.navigation_command,
490
+ device=vision_embeds.device,
491
+ )
492
+ extra_embeds.append(route.to(dtype=vision_embeds.dtype))
493
+ extra_attention_masks.append(route_attention_mask)
494
+ else:
495
+ map_route = driving_input.map_route
496
+ route = self.route_encoder.forward(map_route)
497
+ extra_embeds.append(route.to(dtype=vision_embeds.dtype))
498
+ extra_attention_masks.append(
499
+ torch.ones(route.shape[:2], dtype=torch.long, device=route.device)
500
+ )
501
+
502
+ # free-form instruction prompt (used by Action Dreaming samples)
503
+ prompt = getattr(driving_input, "prompt", None)
504
+ if prompt is not None and any(len(p) > 0 for p in prompt):
505
+ prompt_embeds, prompt_mask = self.encode_navigation_command(
506
+ ["" if p is None else p for p in prompt],
507
+ device=vision_embeds.device,
508
+ )
509
+ extra_embeds.append(prompt_embeds.to(dtype=vision_embeds.dtype))
510
+ extra_attention_masks.append(prompt_mask)
511
+
512
+ input_embeds = torch.cat((vision_embeds, *extra_embeds), dim=1)
513
+ extra_attention_mask = torch.cat(extra_attention_masks, dim=1)
514
+ attention_mask = torch.cat((attention_mask, extra_attention_mask), dim=1)
515
+
516
+ return input_embeds, attention_mask, aux
517
+
518
+ def encode_navigation_command(self, commands, device):
519
+ embed_tokens = getattr(self.language_model, "embed_tokens", None)
520
+ if embed_tokens is None:
521
+ embed_tokens = getattr(self.language_model.model, "embed_tokens", None)
522
+ if embed_tokens is None:
523
+ raise ValueError("Text conditioning requires a language model with token embeddings.")
524
+
525
+ commands = ["" if c is None else c for c in commands]
526
+ # tokenizer requires non-empty batch entries; empty strings yield zero-length rows,
527
+ # pad them with the pad token and mask everything out
528
+ tokens = self.language_model.tokenizer(
529
+ list(commands),
530
+ padding=True,
531
+ truncation=True,
532
+ return_tensors="pt",
533
+ )
534
+ input_ids = tokens["input_ids"].to(device)
535
+ attention_mask = tokens["attention_mask"].to(device=device, dtype=torch.long)
536
+ if input_ids.numel() == 0:
537
+ pad_id = self.language_model.tokenizer.pad_token_id
538
+ input_ids = torch.full((len(commands), 1), pad_id, dtype=torch.long, device=device)
539
+ attention_mask = torch.zeros((len(commands), 1), dtype=torch.long, device=device)
540
+ embeds = embed_tokens(input_ids)
541
+ return embeds, attention_mask
542
+
543
+ def forward_loss(self, example: DrivingExample, per_sample=False) -> TrainingOutput:
544
+ """
545
+ Forward pass of the model for a driving input, followed by
546
+ computing the next token cross-entropy loss.
547
+
548
+ Args:
549
+ driving_input: input to the vision encoder.
550
+ text_ids: Text ids tensor of shape [B, T]. These are input to the model and used in the loss.
551
+ text_mask: Text mask tensor of shape [B, T].
552
+ """
553
+
554
+ adaptor_dict = self.adaptors(example)
555
+ adaptor_embeds = adaptor_dict["inputs"]
556
+
557
+ if self.use_consequence_loss:
558
+ adaptor_outputs, vision_tokens, vision_mask = self.forward_model(
559
+ example.driving_input,
560
+ adaptor_embeds,
561
+ driving_labels=example.driving_label,
562
+ return_context=True,
563
+ )
564
+ else:
565
+ adaptor_outputs = self.forward_model(
566
+ example.driving_input,
567
+ adaptor_embeds,
568
+ driving_labels=example.driving_label,
569
+ )
570
+ vision_tokens = vision_mask = None
571
+ loss_dict = self.adaptors.compute_loss(adaptor_outputs, adaptor_dict, example)
572
+ latent_features = loss_dict.pop("latent_features", None)
573
+
574
+ if self.use_consequence_loss:
575
+ route_prediction = loss_dict.get("route_prediction")
576
+ speed_prediction = loss_dict.get("speed_wps_prediction")
577
+ if route_prediction is None or speed_prediction is None:
578
+ raise ValueError(
579
+ "consequence loss requires predict_route_as_wps=True and "
580
+ "speed_wps_mode='2d'"
581
+ )
582
+ loss_dict.update(
583
+ self.compute_consequence_losses(
584
+ vision_tokens,
585
+ vision_mask,
586
+ route_prediction,
587
+ speed_prediction,
588
+ example.driving_label,
589
+ )
590
+ )
591
+
592
+ loss_dict_only_losses = {k:v for k, v in loss_dict.items() if k.endswith("loss")}
593
+ pred_labels = {k:v for k, v in loss_dict.items() if not k.endswith("loss")}
594
+
595
+ if self.use_world_loss and latent_features is not None:
596
+ loss_dict_only_losses["world_loss"] = self.compute_world_loss(
597
+ latent_features, example.driving_label
598
+ )
599
+
600
+ if per_sample:
601
+ return loss_dict_only_losses, pred_labels
602
+
603
+ return summarise_losses(loss_dict_only_losses)
604
+
605
+ def compute_consequence_losses(
606
+ self,
607
+ vision_tokens: Tensor,
608
+ vision_mask: Tensor,
609
+ predicted_route: Tensor,
610
+ predicted_speed: Tensor,
611
+ label: DrivingLabel,
612
+ ):
613
+ """Dispatch to the head-specific consequence supervision."""
614
+ if self.consequence_head is None or label.future_obstacles is None:
615
+ return {}
616
+ if self.consequence_head_type in ("pooled", "cross_attn_risk"):
617
+ return self._compute_consequence_losses_risk(
618
+ vision_tokens, vision_mask, predicted_route, predicted_speed, label
619
+ )
620
+ return self._compute_consequence_losses_cross_attn(
621
+ vision_tokens, vision_mask, predicted_route, predicted_speed, label
622
+ )
623
+
624
+ def _make_consequence_head_call(self, vision_tokens: Tensor, vision_mask: Tensor):
625
+ """Uniform head invocation for the risk-supervised head variants.
626
+
627
+ Returns ``head_call(routes, speeds, num_plans=1)``: candidate plans are
628
+ laid out batch-major ([b0p0..b0pK, b1p0..]), matching both the pooled
629
+ scene expansion and ``expand_scene_for_plans``.
630
+ """
631
+ head = self.consequence_head
632
+ if self.consequence_head_type == "pooled":
633
+ scene_context = self._pool_scene_context(vision_tokens, vision_mask)
634
+
635
+ def head_call(routes, speeds, num_plans: int = 1):
636
+ if num_plans == 1:
637
+ return head(scene_context, routes, speeds)
638
+ batch = scene_context.size(0)
639
+ expanded = (
640
+ scene_context[:, None]
641
+ .expand(-1, num_plans, -1)
642
+ .reshape(batch * num_plans, -1)
643
+ )
644
+ return head(expanded, routes, speeds)
645
+
646
+ return head_call
647
+
648
+ def head_call(routes, speeds, num_plans: int = 1):
649
+ if num_plans == 1:
650
+ return head(vision_tokens, vision_mask, routes, speeds)
651
+ tokens, mask = expand_scene_for_plans(
652
+ vision_tokens, vision_mask, num_plans
653
+ )
654
+ return head(tokens, mask, routes, speeds)
655
+
656
+ return head_call
657
+
658
+ def _compute_consequence_losses_risk(
659
+ self,
660
+ vision_tokens: Tensor,
661
+ vision_mask: Tensor,
662
+ predicted_route: Tensor,
663
+ predicted_speed: Tensor,
664
+ label: DrivingLabel,
665
+ ):
666
+ """ConsDrive v2 supervision: BCE risk + clearance + hard-negative
667
+ ranking (+ Action Dreaming terms when dreamer labels exist). Shared
668
+ by the pooled (v2/v5) and cross_attn_risk (v6) heads."""
669
+ cfg = self.consequence_cfg
670
+ head_call = self._make_consequence_head_call(vision_tokens, vision_mask)
671
+
672
+ gt_route = label.route_adjusted
673
+ gt_speed = label.waypoints[:, :10]
674
+ predicted = head_call(predicted_route, predicted_speed)
675
+ ground_truth = head_call(gt_route, gt_speed)
676
+ batch_size = predicted_route.size(0)
677
+ device = predicted_route.device
678
+
679
+ obstacles = label.future_obstacles.to(device=device)
680
+ obstacle_valid = label.future_obstacle_valid.to(device=device)
681
+ step_valid = label.future_obstacle_step_valid.to(device=device)
682
+ ego_radius = float(cfg.get("ego_radius", 0.9))
683
+ max_clearance = float(cfg.get("max_clearance", 20.0))
684
+ pred_risk_target, pred_clearance_target, geometry_valid = (
685
+ trajectory_geometry_targets(
686
+ predicted_speed.detach(),
687
+ obstacles,
688
+ obstacle_valid,
689
+ step_valid,
690
+ ego_radius=ego_radius,
691
+ max_clearance=max_clearance,
692
+ )
693
+ )
694
+
695
+ risk_pos_weight = float(cfg.get("risk_pos_weight", 1.0))
696
+ risk_values, risk_counts = binary_waypoint_loss(
697
+ predicted.risk_logits,
698
+ pred_risk_target,
699
+ geometry_valid,
700
+ pos_weight=risk_pos_weight,
701
+ )
702
+ clearance_values, clearance_counts = clearance_waypoint_loss(
703
+ predicted.clearance,
704
+ pred_clearance_target,
705
+ geometry_valid,
706
+ beta=float(cfg.get("clearance_beta", 1.0)),
707
+ )
708
+
709
+ # Dataset targets anchor the GT plan. They include exact future-box
710
+ # geometry when available and explicit hazard-only fallback otherwise.
711
+ gt_risk_values, gt_risk_counts = binary_waypoint_loss(
712
+ ground_truth.risk_logits,
713
+ label.consequence_risk_target.to(device=device),
714
+ label.consequence_risk_valid.to(device=device),
715
+ pos_weight=risk_pos_weight,
716
+ )
717
+ gt_clearance_values, gt_clearance_counts = clearance_waypoint_loss(
718
+ ground_truth.clearance,
719
+ label.consequence_clearance_target.to(device=device),
720
+ label.consequence_clearance_valid.to(device=device),
721
+ beta=float(cfg.get("clearance_beta", 1.0)),
722
+ )
723
+
724
+ rank_values = predicted.risk_logits.float().sum(dim=1) * 0.0
725
+ rank_counts = torch.zeros(batch_size, dtype=torch.long, device=device)
726
+ complete_geometry = step_valid.all(dim=1)
727
+ if bool(complete_geometry.any()):
728
+ rank_parts = []
729
+ count_parts = []
730
+ for base_route, base_speed, base_output in (
731
+ (predicted_route, predicted_speed, predicted),
732
+ (gt_route, gt_speed, ground_truth),
733
+ ):
734
+ values, counts = self._consequence_ranking_for_plan(
735
+ head_call,
736
+ base_route,
737
+ base_speed,
738
+ base_output.risk_logits,
739
+ obstacles,
740
+ obstacle_valid,
741
+ step_valid,
742
+ )
743
+ rank_parts.append(values)
744
+ count_parts.append(counts)
745
+ stacked_counts = torch.stack(count_parts, dim=1)
746
+ stacked_values = torch.stack(rank_parts, dim=1)
747
+ rank_counts = (stacked_counts.sum(dim=1) > 0).long()
748
+ rank_values = (
749
+ (stacked_values * stacked_counts).sum(dim=1)
750
+ / stacked_counts.sum(dim=1).clamp_min(1)
751
+ )
752
+
753
+ # Action Dreaming safety terms are only defined when dreamer labels
754
+ # exist (use_dreamer=True); otherwise they contribute zero counts.
755
+ dream_values = predicted.risk_logits.float().sum(dim=1) * 0.0
756
+ dream_counts = torch.zeros(batch_size, dtype=torch.long, device=device)
757
+ if (
758
+ label.safe_to_execute is not None
759
+ and label.safe_to_execute_valid is not None
760
+ and label.is_dreamer is not None
761
+ ):
762
+ dream_valid = (
763
+ label.safe_to_execute_valid.to(device=device)
764
+ & label.is_dreamer.to(device=device)
765
+ )
766
+ dream_target = (~label.safe_to_execute.to(device=device)).float()
767
+ # The safety flag labels the selected Dreamer trajectory, not the
768
+ # model's still-imperfect prediction of that trajectory.
769
+ dream_logits = aggregate_risk_logits(ground_truth.risk_logits)
770
+ dream_loss = torch.nn.functional.binary_cross_entropy_with_logits(
771
+ dream_logits, dream_target, reduction="none"
772
+ )
773
+ dream_values = dream_loss * dream_valid.float()
774
+ dream_counts = dream_valid.long()
775
+
776
+ dream_pair_values = predicted.risk_logits.float().sum(dim=1) * 0.0
777
+ dream_pair_counts = torch.zeros(
778
+ batch_size, dtype=torch.long, device=device
779
+ )
780
+ if label.dream_pair_valid is not None:
781
+ pair_valid = label.dream_pair_valid.to(device=device, dtype=torch.bool)
782
+ if bool(pair_valid.any()):
783
+ safe_output = head_call(
784
+ label.dream_safe_route.to(device=device),
785
+ label.dream_safe_speed.to(device=device),
786
+ )
787
+ unsafe_output = head_call(
788
+ label.dream_unsafe_route.to(device=device),
789
+ label.dream_unsafe_speed.to(device=device),
790
+ )
791
+ dream_pair_values, dream_pair_counts = pairwise_ranking_loss(
792
+ safe_output.risk_logits,
793
+ unsafe_output.risk_logits[:, None],
794
+ pair_valid[:, None],
795
+ margin=float(cfg.get("negative_margin", 0.5)),
796
+ )
797
+
798
+ warmup_steps = int(cfg.get("warmup_steps", 0))
799
+ if self.training and warmup_steps > 0 and getattr(self, "_trainer", None) is not None:
800
+ warmup = min((int(self.global_step) + 1) / warmup_steps, 1.0)
801
+ else:
802
+ warmup = 1.0
803
+ global_weight = float(cfg.get("loss_weight", 0.1)) * warmup
804
+
805
+ def weighted(values, name):
806
+ return values * global_weight * float(cfg.get(name, 1.0))
807
+
808
+ return {
809
+ "consequence_risk_loss": (
810
+ weighted(risk_values, "risk_weight"),
811
+ risk_counts,
812
+ ),
813
+ "consequence_gt_risk_loss": (
814
+ weighted(gt_risk_values, "risk_weight"),
815
+ gt_risk_counts,
816
+ ),
817
+ "consequence_clearance_loss": (
818
+ weighted(clearance_values, "clearance_weight"),
819
+ clearance_counts,
820
+ ),
821
+ "consequence_gt_clearance_loss": (
822
+ weighted(gt_clearance_values, "clearance_weight"),
823
+ gt_clearance_counts,
824
+ ),
825
+ "consequence_ranking_loss": (
826
+ weighted(rank_values, "ranking_weight"),
827
+ rank_counts,
828
+ ),
829
+ "consequence_dream_safety_loss": (
830
+ weighted(dream_values, "dream_weight"),
831
+ dream_counts,
832
+ ),
833
+ "consequence_dream_pair_ranking_loss": (
834
+ weighted(dream_pair_values, "dream_pair_weight"),
835
+ dream_pair_counts,
836
+ ),
837
+ }
838
+
839
+ def _consequence_ranking_for_plan(
840
+ self,
841
+ head_call,
842
+ base_route,
843
+ base_speed,
844
+ base_logits,
845
+ obstacles,
846
+ obstacle_valid,
847
+ step_valid,
848
+ ):
849
+ cfg = self.consequence_cfg
850
+ # `speed_scale` (scalar) is the legacy key kept for old configs;
851
+ # `negative_speed_scales` (list) takes precedence when present.
852
+ speed_scales = cfg.get("negative_speed_scales")
853
+ if speed_scales is None:
854
+ speed_scales = [float(cfg.get("speed_scale", 1.35))]
855
+ time_shifts = cfg.get("negative_time_shifts") or ()
856
+ candidate_routes, candidate_speeds = make_hard_negative_plans(
857
+ base_route,
858
+ base_speed,
859
+ speed_scales=[float(s) for s in speed_scales],
860
+ lateral_offset=float(cfg.get("lateral_offset", 1.5)),
861
+ time_shifts=[int(s) for s in time_shifts],
862
+ )
863
+ batch_size, candidates = candidate_routes.shape[:2]
864
+ flat_routes = candidate_routes.reshape(batch_size * candidates, 20, 2)
865
+ flat_speeds = candidate_speeds.reshape(batch_size * candidates, 10, 2)
866
+ candidate_output = head_call(flat_routes, flat_speeds, num_plans=candidates)
867
+ candidate_logits = candidate_output.risk_logits.reshape(
868
+ batch_size, candidates, 10
869
+ )
870
+
871
+ base_risk, _, base_valid = trajectory_geometry_targets(
872
+ base_speed.detach(),
873
+ obstacles,
874
+ obstacle_valid,
875
+ step_valid,
876
+ ego_radius=float(cfg.get("ego_radius", 0.9)),
877
+ max_clearance=float(cfg.get("max_clearance", 20.0)),
878
+ )
879
+ expanded_obstacles = obstacles[:, None].expand(
880
+ -1, candidates, -1, -1, -1
881
+ ).reshape(batch_size * candidates, *obstacles.shape[1:])
882
+ expanded_obstacle_valid = obstacle_valid[:, None].expand(
883
+ -1, candidates, -1, -1
884
+ ).reshape(batch_size * candidates, *obstacle_valid.shape[1:])
885
+ expanded_step_valid = step_valid[:, None].expand(
886
+ -1, candidates, -1
887
+ ).reshape(batch_size * candidates, -1)
888
+ candidate_risk, _, candidate_valid = trajectory_geometry_targets(
889
+ flat_speeds.detach(),
890
+ expanded_obstacles,
891
+ expanded_obstacle_valid,
892
+ expanded_step_valid,
893
+ ego_radius=float(cfg.get("ego_radius", 0.9)),
894
+ max_clearance=float(cfg.get("max_clearance", 20.0)),
895
+ )
896
+ candidate_risk = candidate_risk.reshape(batch_size, candidates, 10)
897
+ candidate_valid = candidate_valid.reshape(batch_size, candidates, 10)
898
+ proven_safe = base_valid.all(dim=1) & ~base_risk.bool().any(dim=1)
899
+ proven_unsafe = (
900
+ candidate_valid.all(dim=2) & candidate_risk.bool().any(dim=2)
901
+ )
902
+ ranking_valid = proven_safe[:, None] & proven_unsafe
903
+ return pairwise_ranking_loss(
904
+ base_logits,
905
+ candidate_logits,
906
+ ranking_valid,
907
+ margin=float(cfg.get("negative_margin", 0.5)),
908
+ )
909
+
910
+ def _compute_consequence_losses_cross_attn(
911
+ self,
912
+ vision_tokens: Tensor,
913
+ vision_mask: Tensor,
914
+ predicted_route: Tensor,
915
+ predicted_speed: Tensor,
916
+ label: DrivingLabel,
917
+ ):
918
+ """Avoidance hinge on the predicted plan plus one clearance head loss."""
919
+ cfg = self.consequence_cfg
920
+ head = self.consequence_head
921
+
922
+ gt_route = label.route_adjusted
923
+ gt_speed = label.waypoints[:, :10]
924
+ batch_size = predicted_route.size(0)
925
+ device = predicted_route.device
926
+
927
+ obstacles = label.future_obstacles.to(device=device)
928
+ obstacle_valid = label.future_obstacle_valid.to(device=device)
929
+ step_valid = label.future_obstacle_step_valid.to(device=device)
930
+ ego_radius = float(cfg.get("ego_radius", 0.9))
931
+ max_clearance = float(cfg.get("max_clearance", 20.0))
932
+ geometry_kwargs = dict(
933
+ ego_radius=ego_radius, max_clearance=max_clearance
934
+ )
935
+
936
+ _, pred_clearance, pred_geom_valid = trajectory_geometry_targets(
937
+ predicted_speed, obstacles, obstacle_valid, step_valid, **geometry_kwargs
938
+ )
939
+ _, gt_clearance, gt_geom_valid = trajectory_geometry_targets(
940
+ gt_speed, obstacles, obstacle_valid, step_valid, **geometry_kwargs
941
+ )
942
+ avoid_values, avoid_counts = relative_min_clearance_hinge(
943
+ pred_clearance, gt_clearance, pred_geom_valid, gt_geom_valid
944
+ )
945
+
946
+ visible_valid = visible_obstacle_mask(
947
+ obstacles,
948
+ obstacle_valid,
949
+ max_range=float(cfg.get("visible_max_range", 40.0)),
950
+ min_x=float(cfg.get("visible_min_x", 0.0)),
951
+ )
952
+ speed_scales = cfg.get("negative_speed_scales")
953
+ if speed_scales is None:
954
+ speed_scales = [0.7, 0.8, 0.9, 1.2, 1.5]
955
+ time_shifts = cfg.get("negative_time_shifts") or ()
956
+ neg_routes, neg_speeds = make_hard_negative_plans(
957
+ gt_route,
958
+ gt_speed,
959
+ speed_scales=[float(s) for s in speed_scales],
960
+ lateral_offset=float(cfg.get("lateral_offset", 1.5)),
961
+ time_shifts=[int(s) for s in time_shifts],
962
+ )
963
+ plan_routes = torch.cat(
964
+ (gt_route[:, None], predicted_route.detach()[:, None], neg_routes),
965
+ dim=1,
966
+ )
967
+ plan_speeds = torch.cat(
968
+ (gt_speed[:, None], predicted_speed.detach()[:, None], neg_speeds),
969
+ dim=1,
970
+ )
971
+ num_plans = plan_routes.size(1)
972
+ flat_routes = plan_routes.reshape(batch_size * num_plans, 20, 2)
973
+ flat_speeds = plan_speeds.reshape(batch_size * num_plans, 10, 2)
974
+ flat_tokens, flat_mask = expand_scene_for_plans(
975
+ vision_tokens, vision_mask, num_plans
976
+ )
977
+ head_out = head(flat_tokens, flat_mask, flat_routes, flat_speeds)
978
+
979
+ expanded_obstacles = obstacles[:, None].expand(
980
+ -1, num_plans, -1, -1, -1
981
+ ).reshape(batch_size * num_plans, *obstacles.shape[1:])
982
+ expanded_visible = visible_valid[:, None].expand(
983
+ -1, num_plans, -1, -1
984
+ ).reshape(batch_size * num_plans, *visible_valid.shape[1:])
985
+ expanded_step = step_valid[:, None].expand(
986
+ -1, num_plans, -1
987
+ ).reshape(batch_size * num_plans, -1)
988
+ _, plan_clearance_target, plan_valid = trajectory_geometry_targets(
989
+ flat_speeds,
990
+ expanded_obstacles,
991
+ expanded_visible,
992
+ expanded_step,
993
+ **geometry_kwargs,
994
+ )
995
+ plan_values, plan_counts = clearance_waypoint_loss(
996
+ head_out.clearance,
997
+ plan_clearance_target,
998
+ plan_valid,
999
+ beta=float(cfg.get("clearance_beta", 1.0)),
1000
+ )
1001
+ plan_values = plan_values.view(batch_size, num_plans)
1002
+ plan_counts = plan_counts.view(batch_size, num_plans)
1003
+ plan_used = plan_counts > 0
1004
+ head_counts = plan_used.any(dim=1).long()
1005
+ head_values = (plan_values * plan_used.to(dtype=plan_values.dtype)).sum(
1006
+ dim=1
1007
+ ) / plan_used.to(dtype=plan_values.dtype).sum(dim=1).clamp_min(1)
1008
+
1009
+ warmup_steps = int(cfg.get("warmup_steps", 0))
1010
+ if self.training and warmup_steps > 0 and getattr(self, "_trainer", None) is not None:
1011
+ warmup = min((int(self.global_step) + 1) / warmup_steps, 1.0)
1012
+ else:
1013
+ # Tests / memory probe have no Trainer; use full weights so the
1014
+ # measured graph matches a warmed-up training step.
1015
+ warmup = 1.0
1016
+ avoid_weight = float(cfg.get("avoid_weight", 0.3)) * warmup
1017
+ head_weight = float(cfg.get("head_weight", 0.1)) * warmup
1018
+
1019
+ return {
1020
+ "consequence_avoid_loss": (avoid_values * avoid_weight, avoid_counts),
1021
+ "consequence_head_loss": (head_values * head_weight, head_counts),
1022
+ }
1023
+
1024
+ def compute_world_loss(self, latent_features: Tensor, label: DrivingLabel):
1025
+ """L1 between the world predictor's next-state prediction (conditioned on
1026
+ the LM's latent action tokens) and the cached V-JEPA2 future latents."""
1027
+ b = latent_features.size(0)
1028
+ actions = latent_features.view(
1029
+ b, self.latent_steps, self.latent_tokens_per_step, -1
1030
+ )
1031
+ future_states = getattr(label, "future_states", None)
1032
+ wm_valid = getattr(label, "wm_valid", None)
1033
+ raw_loss, valid_count = masked_world_l1(
1034
+ self.world_predictor, actions, future_states, wm_valid
1035
+ )
1036
+ beta = linear_world_weight(
1037
+ self.global_step, self.world_loss_weight, self.world_loss_warmup_steps
1038
+ ) if self.training else self.world_loss_weight
1039
+ weighted = raw_loss * beta
1040
+ self._world_metrics = {
1041
+ "world_loss_raw": raw_loss.detach(),
1042
+ "world_beta": beta,
1043
+ "world_valid_count": float(valid_count),
1044
+ }
1045
+ return (
1046
+ weighted.reshape(1),
1047
+ torch.ones(1, dtype=torch.long, device=weighted.device),
1048
+ )
1049
+
1050
+ def training_step(self, batch: DrivingExample, _batch_idx: int = 0):
1051
+ output = self.forward_loss(batch)
1052
+ self.log_training_output(output, "train")
1053
+
1054
+ # log the loss
1055
+ self.log("train/loss", output.loss, on_step=True, on_epoch=True, prog_bar=True, logger=True)
1056
+ self._log_world_metrics("train")
1057
+
1058
+ return {"loss": output.loss, "outputs": output}
1059
+
1060
+ def _log_world_metrics(self, mode: str):
1061
+ metrics = getattr(self, "_world_metrics", None)
1062
+ if metrics is None:
1063
+ return
1064
+ on_step = mode == "train"
1065
+ for k, v in metrics.items():
1066
+ self.log(
1067
+ f"{mode}_losses/{k}", v,
1068
+ on_step=on_step, on_epoch=not on_step, sync_dist=False, logger=True,
1069
+ )
1070
+ self._world_metrics = None
1071
+
1072
+ def validation_step(self, batch: DrivingExample, _batch_idx: int = 0):
1073
+ output = self.forward_loss(batch)
1074
+ self.log_training_output(output, "val")
1075
+
1076
+ # log the loss
1077
+ self.log("val/loss", output.loss, on_step=False, on_epoch=True, prog_bar=True, logger=True)
1078
+ self._log_world_metrics("val")
1079
+
1080
+ return {"loss": output.loss, "outputs": output}
1081
+
1082
+ def predict_step(self, batch: DrivingExample, _batch_idx: int = 0):
1083
+ loss_dict, pred_labels = self.forward_loss(batch, per_sample=True)
1084
+
1085
+ per_sample_losses = loss_dict['waypoints_loss'][0].detach().cpu().numpy()
1086
+ predictions = pred_labels['waypoints_prediction'].detach().cpu().numpy()
1087
+ labels = pred_labels['waypoints_label'].detach().cpu().numpy()
1088
+
1089
+ for i in range(len(per_sample_losses)):
1090
+ self.all_losses[batch.run_id[i]] = per_sample_losses[i]
1091
+ self.all_predictions[batch.run_id[i]] = (per_sample_losses[i], predictions[i], labels[i])
1092
+
1093
+ return
1094
+
1095
+ def on_predict_epoch_end(self) -> None:
1096
+
1097
+ # sort by loss and save as pkl and json
1098
+ # sorted_losses = sorted(self.all_losses.items(), key=lambda x: x[1])
1099
+ # with open("sorted_losses.json", "w") as f:
1100
+ # json.dump(sorted_losses, f)
1101
+ try:
1102
+ with open("sorted_losses.pkl", "wb") as f:
1103
+ pkl.dump(self.all_losses, f)
1104
+ with open("all_predictions.pkl", "wb") as f:
1105
+ pkl.dump(self.all_predictions, f)
1106
+ except:
1107
+ breakpoint()
1108
+
1109
+
1110
+ def log_training_output(self, training_output: TrainingOutput, mode: str, dataset: Optional[str] = None):
1111
+ losses = {k: n.detach() for k, n in training_output.loss_averages.items()}
1112
+ counts = {k: n.detach().sum() for k, n in training_output.loss_counts.items()}
1113
+ losses["loss"] = training_output.loss.detach()
1114
+ counts["loss"] = 1 # loss is already averaged
1115
+ for k, v in sorted(losses.items()):
1116
+ log_key = f"{mode}_losses/{k}"
1117
+ self.log(log_key, v, batch_size=counts[k], sync_dist=True, add_dataloader_idx=False)
1118
+
1119
+
1120
+ def configure_optimizers(self):
1121
+
1122
+ if self.lm_lr is not None:
1123
+ # pretrained-init trunks get their own (lower) LR; the regexes must
1124
+ # stay disjoint because configure_params_groups forbids overlap
1125
+ param_groups = [
1126
+ ParamGroup(r"^language_model\..*", self.lm_lr, self.weight_decay),
1127
+ ParamGroup(r"^(model|language_projection|adaptors|speed_encoder|route_encoder|world_predictor|consequence_head)\..*", self.lr, self.weight_decay),
1128
+ ParamGroup(r"^vision_model\..*", self.vision_lr, self.weight_decay),
1129
+ ]
1130
+ else:
1131
+ param_groups = [
1132
+ ParamGroup(r"^(model|language_model|language_projection|adaptors|speed_encoder|route_encoder|world_predictor|consequence_head)\..*", self.lr, self.weight_decay),
1133
+ ParamGroup(r"^vision_model\..*", self.vision_lr, self.weight_decay),
1134
+ ]
1135
+ param_group_config = configure_params_groups(self, param_groups, verbose=False)
1136
+ if isinstance(self.trainer.strategy, pl.strategies.DeepSpeedStrategy) and FusedAdam is not None:
1137
+ try:
1138
+ optimizer = FusedAdam(param_group_config, betas=self.betas)
1139
+ except (ImportError, OSError, RuntimeError):
1140
+ warnings.warn(
1141
+ "FusedAdam could not be loaded; falling back to torch.optim.AdamW.",
1142
+ stacklevel=2,
1143
+ )
1144
+ optimizer = torch.optim.AdamW(param_group_config, betas=self.betas)
1145
+ else:
1146
+ optimizer = torch.optim.AdamW(param_group_config, betas=self.betas)
1147
+ if self.trainer.max_steps == -1:
1148
+ max_steps = self.trainer.estimated_stepping_batches
1149
+ else:
1150
+ max_steps = self.trainer.max_steps
1151
+
1152
+ if self.vision_freeze_steps > 0 or self.vision_ramp_steps > 0:
1153
+ scheduler = self._build_freeze_ramp_scheduler(optimizer, max_steps)
1154
+ else:
1155
+ lrs = [pg['lr'] for pg in optimizer.param_groups]
1156
+ scheduler = torch.optim.lr_scheduler.OneCycleLR(
1157
+ optimizer, max_lr=lrs, total_steps=max_steps, pct_start=self.pct_start
1158
+ )
1159
+ return {"optimizer": optimizer, "lr_scheduler": {"scheduler": scheduler, "frequency": 1, "interval": "step"}}
1160
+
1161
+ def _build_freeze_ramp_scheduler(self, optimizer, max_steps: int):
1162
+ """Per-group LambdaLR: main groups get linear warmup + cosine decay;
1163
+ vision groups stay at lr=0 for `vision_freeze_steps`, then ramp up
1164
+ linearly over `vision_ramp_steps` and follow the same cosine envelope."""
1165
+ import math
1166
+
1167
+ warmup_steps = max(1, int(self.pct_start * max_steps))
1168
+ freeze_steps = self.vision_freeze_steps
1169
+ ramp_steps = max(1, self.vision_ramp_steps)
1170
+
1171
+ def cosine_envelope(step: int) -> float:
1172
+ if step < warmup_steps:
1173
+ return 1.0
1174
+ progress = (step - warmup_steps) / max(1, max_steps - warmup_steps)
1175
+ return 0.5 * (1.0 + math.cos(math.pi * min(progress, 1.0)))
1176
+
1177
+ def main_lambda(step: int) -> float:
1178
+ if step < warmup_steps:
1179
+ return (step + 1) / warmup_steps
1180
+ return cosine_envelope(step)
1181
+
1182
+ def vision_lambda(step: int) -> float:
1183
+ if step < freeze_steps:
1184
+ return 0.0
1185
+ ramp = min((step - freeze_steps + 1) / ramp_steps, 1.0)
1186
+ return ramp * cosine_envelope(step)
1187
+
1188
+ vision_param_ids = {id(p) for p in self.vision_model.parameters()}
1189
+ lambdas = [
1190
+ vision_lambda
1191
+ if any(id(p) in vision_param_ids for p in group["params"])
1192
+ else main_lambda
1193
+ for group in optimizer.param_groups
1194
+ ]
1195
+ return torch.optim.lr_scheduler.LambdaLR(optimizer, lr_lambda=lambdas)
models/encoder/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+
models/encoder/dinov2_lora.py ADDED
@@ -0,0 +1,218 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from pathlib import Path
3
+ from typing import Optional, Sequence, Tuple
4
+
5
+ import torch
6
+ from safetensors import safe_open
7
+ from torch import Tensor, nn
8
+ import torch.nn.functional as F
9
+ import timm
10
+
11
+
12
+ class LoRAQKV(nn.Module):
13
+ def __init__(
14
+ self,
15
+ qkv: nn.Linear,
16
+ rank: int,
17
+ use_layer_norm: bool = False,
18
+ use_qkv: bool = False,
19
+ ):
20
+ super().__init__()
21
+ self.qkv = qkv
22
+ self.dim = qkv.in_features
23
+ self.use_qkv = use_qkv
24
+
25
+ self.linear_a_q = nn.Linear(self.dim, rank, bias=False)
26
+ self.linear_b_q = nn.Linear(rank, self.dim, bias=False)
27
+ self.linear_a_v = nn.Linear(self.dim, rank, bias=False)
28
+ self.linear_b_v = nn.Linear(rank, self.dim, bias=False)
29
+
30
+ self.linear_a_k = nn.Linear(self.dim, rank, bias=False) if use_qkv else nn.Identity()
31
+ self.linear_b_k = nn.Linear(rank, self.dim, bias=False) if use_qkv else nn.Identity()
32
+
33
+ self.layernorm_q = nn.LayerNorm(self.dim) if use_layer_norm else nn.Identity()
34
+ self.layernorm_v = nn.LayerNorm(self.dim) if use_layer_norm else nn.Identity()
35
+ self.layernorm_k = nn.LayerNorm(self.dim) if use_layer_norm and use_qkv else nn.Identity()
36
+ self.reset_parameters()
37
+
38
+ def reset_parameters(self):
39
+ for module in (self.linear_a_q, self.linear_a_v, self.linear_a_k):
40
+ if isinstance(module, nn.Linear):
41
+ nn.init.kaiming_uniform_(module.weight, a=math.sqrt(5))
42
+ for module in (self.linear_b_q, self.linear_b_v, self.linear_b_k):
43
+ if isinstance(module, nn.Linear):
44
+ nn.init.zeros_(module.weight)
45
+
46
+ def forward(self, x: Tensor) -> Tensor:
47
+ qkv = self.qkv(x)
48
+ qkv[:, :, : self.dim] += self.linear_b_q(self.linear_a_q(self.layernorm_q(x)))
49
+ qkv[:, :, -self.dim :] += self.linear_b_v(self.linear_a_v(self.layernorm_v(x)))
50
+ if self.use_qkv:
51
+ qkv[:, :, self.dim : 2 * self.dim] += self.linear_b_k(self.linear_a_k(self.layernorm_k(x)))
52
+ return qkv
53
+
54
+
55
+ def _load_checkpoint(path: str):
56
+ path_obj = Path(path)
57
+ if not path_obj.exists():
58
+ raise FileNotFoundError(f"DINOv2 checkpoint does not exist: {path}")
59
+
60
+ try:
61
+ state_dict = {}
62
+ with safe_open(str(path_obj), framework="pt", device="cpu") as f:
63
+ for key in f.keys():
64
+ state_dict[key] = f.get_tensor(key)
65
+ return state_dict
66
+ except Exception:
67
+ checkpoint = torch.load(path_obj, map_location="cpu")
68
+ if isinstance(checkpoint, dict):
69
+ for key in ("state_dict", "model", "teacher"):
70
+ if key in checkpoint and isinstance(checkpoint[key], dict):
71
+ checkpoint = checkpoint[key]
72
+ break
73
+ return checkpoint
74
+
75
+
76
+ class DinoV2LoRAEncoderModel(nn.Module):
77
+ """
78
+ DINOv2 vision encoder following the DrivoR adaptation pattern:
79
+ frozen timm DINOv2 backbone + LoRA injected into attention q/v + trainable neck.
80
+ """
81
+
82
+ def __init__(
83
+ self,
84
+ model_name: str = "timm/vit_small_patch14_reg4_dinov2.lvd142m",
85
+ model_weights: Optional[str] = None,
86
+ embed_dim: int = 512,
87
+ image_size: Tuple[int, int] = (224, 224),
88
+ use_lora: bool = True,
89
+ lora_rank: int = 16,
90
+ lora_layers: Optional[Sequence[int]] = None,
91
+ lora_use_layer_norm: bool = False,
92
+ lora_use_qkv: bool = False,
93
+ finetune: bool = False,
94
+ num_register_tokens: int = 4,
95
+ use_feature_pooling: bool = False,
96
+ freeze: bool = False,
97
+ max_frames: int = 4,
98
+ max_cameras: int = 6,
99
+ use_global_img: bool = False,
100
+ ):
101
+ super().__init__()
102
+ self.token_size = embed_dim
103
+ self.image_size = tuple(image_size)
104
+ self.num_register_tokens = num_register_tokens
105
+ self.use_feature_pooling = use_feature_pooling
106
+ self.max_frames = max_frames
107
+ self.max_cameras = max_cameras
108
+ self.use_global_img = use_global_img
109
+
110
+ self.model = timm.create_model(
111
+ model_name,
112
+ pretrained=False,
113
+ num_classes=0,
114
+ img_size=self.image_size,
115
+ )
116
+ if model_weights:
117
+ state_dict = _load_checkpoint(model_weights)
118
+ missing, unexpected = self.model.load_state_dict(state_dict, strict=False)
119
+ if unexpected:
120
+ print(f"DINOv2 checkpoint unexpected keys: {unexpected[:10]}")
121
+ if missing:
122
+ print(f"DINOv2 checkpoint missing keys: {missing[:10]}")
123
+
124
+ self.num_features = self.model.num_features
125
+ self.neck = nn.Linear(self.num_features, embed_dim)
126
+ self.temporal_encoding = nn.Parameter(0.02 * torch.randn(1, max_frames, 1, 1, embed_dim))
127
+ self.camera_encoding = nn.Parameter(0.02 * torch.randn(1, 1, max_cameras, 1, embed_dim))
128
+
129
+ if use_lora:
130
+ self._freeze_backbone()
131
+ self._inject_lora(lora_rank, lora_layers, lora_use_layer_norm, lora_use_qkv)
132
+ elif finetune:
133
+ for param in self.model.parameters():
134
+ param.requires_grad = True
135
+ else:
136
+ self._freeze_backbone()
137
+
138
+ if freeze:
139
+ for param in self.parameters():
140
+ param.requires_grad = False
141
+
142
+ self.register_buffer(
143
+ "image_mean",
144
+ torch.tensor([0.485, 0.456, 0.406]).view(1, 3, 1, 1),
145
+ persistent=False,
146
+ )
147
+ self.register_buffer(
148
+ "image_std",
149
+ torch.tensor([0.229, 0.224, 0.225]).view(1, 3, 1, 1),
150
+ persistent=False,
151
+ )
152
+
153
+ def _freeze_backbone(self):
154
+ for param in self.model.parameters():
155
+ param.requires_grad = False
156
+
157
+ def _inject_lora(
158
+ self,
159
+ rank: int,
160
+ layers: Optional[Sequence[int]],
161
+ use_layer_norm: bool,
162
+ use_qkv: bool,
163
+ ):
164
+ if rank <= 0:
165
+ return
166
+ selected_layers = set(layers) if layers is not None else set(range(len(self.model.blocks)))
167
+ for layer_idx, block in enumerate(self.model.blocks):
168
+ if layer_idx not in selected_layers:
169
+ continue
170
+ block.attn.qkv = LoRAQKV(
171
+ block.attn.qkv,
172
+ rank=rank,
173
+ use_layer_norm=use_layer_norm,
174
+ use_qkv=use_qkv,
175
+ )
176
+
177
+ def _select_tokens(self, tokens: Tensor) -> Tensor:
178
+ if self.use_feature_pooling:
179
+ return F.adaptive_avg_pool1d(tokens.transpose(1, 2), self.num_register_tokens).transpose(1, 2)
180
+
181
+ reg_token = getattr(self.model, "reg_token", None)
182
+ if reg_token is not None:
183
+ start = 1 if getattr(self.model, "cls_token", None) is not None else 0
184
+ end = start + self.num_register_tokens
185
+ return tokens[:, start:end]
186
+ return tokens[:, : self.num_register_tokens]
187
+
188
+ def forward(self, pixel_values: Tensor, image_sizes: Optional[Tensor] = None) -> Tuple[Tensor, Tensor]:
189
+ if pixel_values.ndim != 6:
190
+ raise ValueError(
191
+ "DinoV2LoRAEncoderModel expects images shaped [B, T, N, C, H, W], "
192
+ f"got {tuple(pixel_values.shape)}."
193
+ )
194
+
195
+ batch_size, num_frames, num_cameras, channels, height, width = pixel_values.shape
196
+ if channels != 3:
197
+ raise ValueError(f"Expected RGB images with 3 channels, got {channels}.")
198
+ if num_frames > self.max_frames:
199
+ raise ValueError(f"num_frames={num_frames} exceeds max_frames={self.max_frames}.")
200
+ if num_cameras > self.max_cameras:
201
+ raise ValueError(f"num_cameras={num_cameras} exceeds max_cameras={self.max_cameras}.")
202
+
203
+ x = pixel_values.reshape(batch_size * num_frames * num_cameras, channels, height, width)
204
+ x = x.to(device=self.neck.weight.device, dtype=self.neck.weight.dtype)
205
+ x = x / 255.0
206
+ x = (x - self.image_mean.to(dtype=x.dtype)) / self.image_std.to(dtype=x.dtype)
207
+ if (height, width) != self.image_size:
208
+ x = F.interpolate(x, size=self.image_size, mode="bilinear", align_corners=False)
209
+
210
+ tokens = self.model.forward_features(x)
211
+ tokens = self._select_tokens(tokens)
212
+ tokens = self.neck(tokens)
213
+ tokens = tokens.view(batch_size, num_frames, num_cameras, self.num_register_tokens, -1)
214
+ tokens = tokens + self.temporal_encoding[:, :num_frames].to(dtype=tokens.dtype)
215
+ tokens = tokens + self.camera_encoding[:, :, :num_cameras].to(dtype=tokens.dtype)
216
+ embeds = tokens.reshape(batch_size, num_frames * num_cameras * self.num_register_tokens, -1)
217
+ attention_mask = torch.ones(embeds.shape[:2], dtype=torch.long, device=embeds.device)
218
+ return embeds, attention_mask
models/encoder/llavanext.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import torch
3
+ from torch import nn
4
+ from transformers import LlavaNextProcessor
5
+
6
+ from models.encoder.llavanext_model import LingoLlavaNextModel
7
+
8
+ class LLaVAnextEncoderModel(nn.Module):
9
+ def __init__(self,
10
+ variant: str,
11
+ embed_dim: int,
12
+ freeze: bool,
13
+ downsample_feature_grid_factor: int = 2,
14
+ use_global_img = False,
15
+ ):
16
+
17
+ super().__init__()
18
+ self.num_cameras = 1
19
+ self.num_frames = 1
20
+ self.token_size = embed_dim
21
+
22
+ self.downsample_feature_grid_factor = downsample_feature_grid_factor
23
+
24
+ self.image_encoder = LingoLlavaNextModel.from_pretrained(variant)
25
+ self.image_encoder.use_global_img = use_global_img
26
+ 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
27
+ self.image_encoder.language_model = None
28
+ print("\033[91m" + "Using LLaVA pretraining for the image encoder" + "\033[0m")
29
+
30
+ self.projection = nn.Linear(self.image_encoder.base_model.config.vision_config.intermediate_size, embed_dim)
31
+ # Embeddings: BS, N_FRAMES, N_CAMS, N_PATCHES, EMBED_DIM
32
+ self.temporal_encoding = nn.Parameter(0.02 * torch.randn(1, self.num_frames, 1, 1, embed_dim))
33
+ self.camera_encoding = nn.Parameter(0.02 * torch.randn(1, 1, self.num_cameras, 1, embed_dim))
34
+
35
+ # freeze the paramaeters -> no gradient updates
36
+ if freeze:
37
+ for p in self.parameters():
38
+ p.requires_grad = False
39
+
40
+ # activate the projection layer
41
+ self.projection.weight.requires_grad = True
42
+ self.projection.bias.requires_grad = True
43
+ # self.positional_encoding.requires_grad = True
44
+ self.temporal_encoding.requires_grad = True
45
+ self.camera_encoding.requires_grad = True
46
+
47
+ def forward(
48
+ self,
49
+ pixel_values: torch.Tensor,
50
+ image_sizes = None,
51
+ use_temporal_encoding: bool = True,
52
+ use_positional_encoding: bool = True,
53
+ use_camera_encoding: bool = True,
54
+ ) -> torch.Tensor:
55
+
56
+ BS, num_frames, num_cams, num_patches, C, H, W = pixel_values.shape
57
+
58
+
59
+ patch_embeddings = self.image_encoder.forward_image(pixel_values=pixel_values, image_sizes=image_sizes, downsample_feature_grid_factor=self.downsample_feature_grid_factor)
60
+ patch_embeddings = self.projection(patch_embeddings)
61
+ patch_embeddings = patch_embeddings.view(-1, num_frames, num_cams, patch_embeddings.shape[-2], patch_embeddings.shape[-1])
62
+
63
+ input_sequence = patch_embeddings
64
+ _, _, _, n_tokens, channels = input_sequence.shape
65
+
66
+ # temporal embeddings
67
+ if use_temporal_encoding:
68
+ input_sequence = input_sequence + self.temporal_encoding
69
+ # positional embeddings
70
+ # if use_positional_encoding:
71
+ # input_sequence = input_sequence + self.positional_encoding
72
+ # per camera embeddings
73
+ if use_camera_encoding:
74
+ input_sequence = input_sequence + self.camera_encoding
75
+
76
+ embeds = input_sequence.view(BS, -1, channels)
77
+
78
+ return embeds, (num_frames, n_tokens, channels)
79
+
80
+
81
+
82
+ if __name__ == "__main__":
83
+ model = LLaVAnextEncoderModel(
84
+ variant="llava-hf/llava-v1.6-mistral-7b-hf",
85
+ debug=True,
86
+ embed_dim=256,
87
+ freeze=True,
88
+ )
89
+ processor = LlavaNextProcessor.from_pretrained("llava-hf/llava-v1.6-mistral-7b-hf")
90
+
91
+ # BS, N_FRAMES, N_CAMS, 3, H, W
92
+ # random vector between 0 and 1
93
+ image = np.random.rand(2, 4, 2, 3, 512, 1024).astype(np.float32)
94
+ image = torch.tensor(image)
95
+
96
+ # merge BS and N_FRAMES and N_CAMS
97
+ image = image.view(-1, 3, 512, 1024)
98
+
99
+ inputs = processor.image_processor(image, return_tensors="pt").to("cuda:0")
100
+ # 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')]]
101
+
102
+ output = model(**inputs)
103
+ print(output[0].shape, output[1])
104
+
105
+ # output_image_shape = True
106
+ # output = model(image, output_image_shape)
107
+ # print(output.shape)
models/encoder/llavanext_model.py ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch.nn import functional as F
3
+ from transformers import LlavaNextForConditionalGeneration
4
+ from transformers.models.llava_next.modeling_llava_next import (
5
+ LlavaNextCausalLMOutputWithPast,
6
+ get_anyres_image_grid_shape,
7
+ unpad_image,
8
+ )
9
+ from typing import Optional, Tuple, Union
10
+
11
+
12
+ class LingoLlavaNextModel(LlavaNextForConditionalGeneration):
13
+ def __init__(self, *args, **kwargs):
14
+ super().__init__(*args, **kwargs)
15
+ self.use_global_img = None
16
+
17
+ def forward_image(
18
+ self,
19
+ pixel_values: torch.FloatTensor = None,
20
+ image_sizes: Optional[torch.LongTensor] = None,
21
+ vision_feature_layer: Optional[int] = None,
22
+ vision_feature_select_strategy: Optional[str] = None,
23
+ downsample_feature_grid_factor: Optional[int] = None,
24
+ ) -> Union[Tuple, LlavaNextCausalLMOutputWithPast]:
25
+ r"""
26
+ Args:
27
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
28
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
29
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
30
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
31
+
32
+ Returns:
33
+
34
+ Example:
35
+
36
+ ```python
37
+ >>> from PIL import Image
38
+ >>> import requests
39
+ >>> from transformers import AutoProcessor, LlavaNextForConditionalGeneration
40
+
41
+ >>> model = LlavaNextForConditionalGeneration.from_pretrained("llava-hf/llava-v1.6-mistral-7b-hf")
42
+ >>> processor = AutoProcessor.from_pretrained("llava-hf/llava-v1.6-mistral-7b-hf")
43
+
44
+ >>> prompt = "[INST] <image>\nWhat is shown in this image? [/INST]"
45
+ >>> url = "https://www.ilankelman.org/stopsigns/australia.jpg"
46
+ >>> image = Image.open(requests.get(url, stream=True).raw)
47
+
48
+ >>> inputs = processor(text=prompt, images=image, return_tensors="pt")
49
+
50
+ >>> # Generate
51
+ >>> generate_ids = model.generate(**inputs, max_length=30)
52
+ >>> processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
53
+ "[INST] \nWhat is shown in this image? [/INST] The image appears to be a radar chart, which is a type of multi-dimensional plot (...)"
54
+ ```"""
55
+
56
+ vision_feature_layer = (
57
+ vision_feature_layer if vision_feature_layer is not None else self.config.vision_feature_layer
58
+ )
59
+ vision_feature_select_strategy = (
60
+ vision_feature_select_strategy
61
+ if vision_feature_select_strategy is not None
62
+ else self.config.vision_feature_select_strategy
63
+ )
64
+
65
+ if pixel_values is not None:
66
+ batch_size, num_frames, num_cams, num_patches, num_channels, height, width = pixel_values.shape
67
+ reshaped_pixel_values = pixel_values.reshape(batch_size *num_frames * num_cams * num_patches, num_channels, height, width)
68
+ image_features = self.vision_tower(pixel_values=reshaped_pixel_values, output_hidden_states=True)
69
+
70
+ selected_image_feature = image_features.hidden_states[vision_feature_layer]
71
+
72
+ if len(image_features.hidden_states[-1].shape) == 4:
73
+ selected_image_feature = image_features.hidden_states[-1]
74
+ # flatten
75
+ selected_image_feature = selected_image_feature.flatten(2,3)
76
+ # swap
77
+ selected_image_feature = selected_image_feature.transpose(1, 2)
78
+
79
+ if vision_feature_select_strategy == "default":
80
+ selected_image_feature = selected_image_feature[:, 1:] # remove the CLS token
81
+ # (BS*num_patches), num_tokens->24x24=576, hidden_size=1024... -> 24 because we have 336 pixels and use patch size of 14
82
+ elif vision_feature_select_strategy == "full":
83
+ selected_image_feature = selected_image_feature
84
+ # (BS*num_patches), num_tokens->24x24+1=577, hidden_size=1024
85
+
86
+
87
+ image_features = self.multi_modal_projector(selected_image_feature)
88
+
89
+ image_features = list(image_features.view(batch_size * num_frames * num_cams, num_patches, image_features.shape[-2], image_features.shape[-1]))
90
+
91
+ # split up image_features for each of the individual images
92
+ # hence we get a list of image_features, each of shape (5, num_patches, hidden_size)
93
+ # if we assume each image has 5 image features (base image + 4 patches)
94
+ # split_sizes = [image.shape[0] for image in pixel_values]
95
+
96
+
97
+ # image_features = torch.split(image_features, split_sizes, dim=0)
98
+
99
+ # NOTE we only support multimodal_patch_merge_type == "spatial_unpad"
100
+ height = width = self.config.vision_config.image_size // self.config.vision_config.patch_size
101
+
102
+ new_image_features = []
103
+ for image_idx, image_feature in enumerate(image_features):
104
+ if image_feature.shape[0] > 1:
105
+ # image_feature:
106
+ if self.use_global_img:
107
+ base_image_feature = image_feature[0]
108
+ image_feature = image_feature[1:]
109
+
110
+ if height * width != image_feature.shape[1]:
111
+ raise ValueError("The number of patches is not consistent with the image size.")
112
+ num_patch_height, num_patch_width = get_anyres_image_grid_shape(
113
+ image_sizes[image_idx],
114
+ self.config.image_grid_pinpoints,
115
+ self.config.vision_config.image_size,
116
+ )
117
+ 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])
118
+ 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])
119
+ image_feature = image_feature.flatten(1, 2).flatten(2, 3) # torch.Size([4096, 24, 72]) or torch.Size([4096, 48, 48])
120
+ image_feature = unpad_image(image_feature, image_sizes[image_idx])
121
+ if downsample_feature_grid_factor is not None:
122
+ # average pooling to downsample the feature grid
123
+ image_feature = F.avg_pool2d(
124
+ image_feature.unsqueeze(0), downsample_feature_grid_factor
125
+ ).squeeze(0) # for 2: torch.Size([4096, 12, 32])
126
+ if self.use_global_img:
127
+ base_image_feature = base_image_feature.view(1, height, width, -1)
128
+ base_image_feature = F.avg_pool2d(base_image_feature.permute(0, 3, 1, 2), downsample_feature_grid_factor).squeeze(0).permute(1, 2, 0)
129
+ base_image_feature = base_image_feature.flatten(0, 1)
130
+ image_feature = torch.cat(
131
+ (
132
+ image_feature,
133
+ self.image_newline[:, None, None].expand(*image_feature.shape[:-1], 1),
134
+ ),
135
+ dim=-1,
136
+ )
137
+ image_feature = image_feature.flatten(1, 2).transpose(0, 1)
138
+ if self.use_global_img:
139
+ image_feature = torch.cat((base_image_feature, image_feature), dim=0)
140
+ else:
141
+ image_feature = image_feature[0]
142
+ if downsample_feature_grid_factor is not None:
143
+ image_feature = image_feature.view(1, height, width, -1)
144
+ image_feature = F.avg_pool2d(image_feature.permute(0, 3, 1, 2), downsample_feature_grid_factor).squeeze(0).permute(1, 2, 0)
145
+ image_feature = image_feature.flatten(0, 1)
146
+ image_feature = torch.cat((image_feature, self.image_newline[None]), dim=0)
147
+ new_image_features.append(image_feature)
148
+ image_features = torch.stack(new_image_features, dim=0)
149
+
150
+ return image_features
models/encoder/qwen2_5_vl.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional
2
+
3
+ import torch
4
+ import torch.nn.functional as F
5
+ from torch import nn
6
+ from transformers import AutoConfig
7
+ from transformers.models.qwen2_5_vl.modeling_qwen2_5_vl import Qwen2_5_VisionTransformerPretrainedModel
8
+
9
+ from models.qwen_utils import build_empty_module, load_prefixed_safetensors
10
+
11
+
12
+ class Qwen2_5VLEncoderModel(nn.Module):
13
+ def __init__(
14
+ self,
15
+ variant: str,
16
+ freeze: bool = False,
17
+ max_visual_tokens: Optional[int] = None,
18
+ local_files_only: bool = True,
19
+ use_global_img: bool = False,
20
+ torch_dtype: str = "bfloat16",
21
+ ):
22
+ super().__init__()
23
+ self.config = AutoConfig.from_pretrained(variant, local_files_only=local_files_only)
24
+ self.config.vision_config._attn_implementation = "flash_attention_2"
25
+ dtype = getattr(torch, torch_dtype)
26
+ self.image_encoder = build_empty_module(
27
+ Qwen2_5_VisionTransformerPretrainedModel, self.config.vision_config
28
+ )
29
+ load_prefixed_safetensors(self.image_encoder, variant, "visual.", torch_dtype=dtype)
30
+
31
+ self.token_size = self.config.vision_config.out_hidden_size
32
+ self.max_visual_tokens = max_visual_tokens
33
+ self.use_global_img = use_global_img
34
+
35
+ if freeze:
36
+ for param in self.parameters():
37
+ param.requires_grad = False
38
+
39
+ def forward(self, pixel_values: torch.Tensor, image_sizes: torch.Tensor = None):
40
+ if image_sizes is None:
41
+ raise ValueError("Qwen2.5-VL vision encoder requires image_grid_thw in image_sizes.")
42
+
43
+ if image_sizes.ndim == 3:
44
+ batch_size, images_per_sample, _ = image_sizes.shape
45
+ image_grid_thw = image_sizes.reshape(batch_size * images_per_sample, 3)
46
+ elif image_sizes.ndim == 2:
47
+ image_grid_thw = image_sizes
48
+ batch_size = image_grid_thw.shape[0]
49
+ images_per_sample = 1
50
+ else:
51
+ raise ValueError(f"Unexpected image_sizes shape: {tuple(image_sizes.shape)}")
52
+
53
+ device = next(self.image_encoder.parameters()).device
54
+ dtype = next(self.image_encoder.parameters()).dtype
55
+ pixel_values = pixel_values.to(device=device, dtype=dtype)
56
+ image_grid_thw = image_grid_thw.to(device=device)
57
+
58
+ outputs = self.image_encoder(pixel_values, grid_thw=image_grid_thw)
59
+ # transformers 5.x: pooler_output is the post-merger output [N_merged, out_hidden_size]
60
+ # last_hidden_state is pre-merger [N_patches, hidden_size] — NOT what we want
61
+ if hasattr(outputs, 'pooler_output') and outputs.pooler_output is not None:
62
+ image_embeds = outputs.pooler_output
63
+ elif torch.is_tensor(outputs):
64
+ image_embeds = outputs
65
+ else:
66
+ image_embeds = outputs.last_hidden_state
67
+
68
+ split_sizes = (
69
+ image_grid_thw.prod(-1) // (self.image_encoder.spatial_merge_size ** 2)
70
+ ).tolist()
71
+ image_embeds = torch.split(image_embeds, [int(s) for s in split_sizes])
72
+
73
+ samples = []
74
+ for sample_idx in range(batch_size):
75
+ start = sample_idx * images_per_sample
76
+ end = start + images_per_sample
77
+ sample_embeds = torch.cat(image_embeds[start:end], dim=0)
78
+ if self.max_visual_tokens is not None:
79
+ sample_embeds = sample_embeds[: self.max_visual_tokens]
80
+ samples.append(sample_embeds)
81
+
82
+ max_tokens = max(sample.shape[0] for sample in samples)
83
+ padded_samples = []
84
+ attention_masks = []
85
+ for sample in samples:
86
+ pad_tokens = max_tokens - sample.shape[0]
87
+ if pad_tokens > 0:
88
+ sample = F.pad(sample, (0, 0, 0, pad_tokens))
89
+ padded_samples.append(sample)
90
+ attention_masks.append(
91
+ torch.arange(max_tokens, device=sample.device) < (max_tokens - pad_tokens)
92
+ )
93
+
94
+ return torch.stack(padded_samples, dim=0), torch.stack(attention_masks, dim=0)
models/encoder/qwen3_vl.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional
2
+
3
+ import torch
4
+ import torch.nn.functional as F
5
+ from torch import nn
6
+ from transformers import AutoConfig
7
+ from transformers.models.qwen3_vl.modeling_qwen3_vl import Qwen3VLVisionModel
8
+
9
+ from models.qwen_utils import build_empty_module, load_prefixed_safetensors
10
+ from utils.logging_project import rank_zero_print
11
+
12
+
13
+ class Qwen3VLEncoderModel(nn.Module):
14
+ """
15
+ Qwen3-VL vision encoder in native video mode.
16
+
17
+ Consumes video patches (pixel_values_videos) with video_grid_thw and returns:
18
+ - merged video token embeddings [B, N, out_hidden_size]
19
+ - attention mask [B, N]
20
+ - deepstack features: list of 3 tensors [B, N, out_hidden_size]
21
+ (from vision blocks 8/16/24, already projected by deepstack mergers)
22
+ """
23
+
24
+ def __init__(
25
+ self,
26
+ variant: str,
27
+ freeze: bool = False,
28
+ max_visual_tokens: Optional[int] = None,
29
+ local_files_only: bool = True,
30
+ use_global_img: bool = False,
31
+ torch_dtype: str = "bfloat16",
32
+ ):
33
+ super().__init__()
34
+ self.config = AutoConfig.from_pretrained(variant, local_files_only=local_files_only)
35
+ dtype = getattr(torch, torch_dtype)
36
+ self.config.vision_config._attn_implementation = "flash_attention_2"
37
+ self.config.vision_config.dtype = dtype
38
+ rank_zero_print("Loading Qwen3-VL vision encoder (meta init)...", flush=True)
39
+ self.image_encoder = build_empty_module(Qwen3VLVisionModel, self.config.vision_config)
40
+ rank_zero_print("Loading vision weights...", flush=True)
41
+ load_prefixed_safetensors(self.image_encoder, variant, "model.visual.", torch_dtype=dtype)
42
+ rank_zero_print("Vision encoder ready.", flush=True)
43
+
44
+ self.token_size = self.config.vision_config.out_hidden_size
45
+ self.spatial_merge_size = self.config.vision_config.spatial_merge_size
46
+ self.num_deepstack_layers = len(self.config.vision_config.deepstack_visual_indexes)
47
+ self.max_visual_tokens = max_visual_tokens
48
+ self.use_global_img = use_global_img
49
+
50
+ if freeze:
51
+ for param in self.parameters():
52
+ param.requires_grad = False
53
+
54
+ def forward(self, pixel_values: torch.Tensor, image_sizes: torch.Tensor = None):
55
+ """
56
+ Args:
57
+ pixel_values: [total_patches, patch_dim] video patches from Qwen3VLVideoProcessor
58
+ (concatenated over the batch).
59
+ image_sizes: video_grid_thw. Either [B, 3] (one video per sample) or
60
+ [B, 1, 3].
61
+ """
62
+ if image_sizes is None:
63
+ raise ValueError("Qwen3-VL vision encoder requires video_grid_thw in image_sizes.")
64
+
65
+ if image_sizes.ndim == 3:
66
+ video_grid_thw = image_sizes.reshape(-1, 3)
67
+ elif image_sizes.ndim == 2:
68
+ video_grid_thw = image_sizes
69
+ else:
70
+ raise ValueError(f"Unexpected image_sizes shape: {tuple(image_sizes.shape)}")
71
+ batch_size = video_grid_thw.shape[0]
72
+
73
+ device = next(self.image_encoder.parameters()).device
74
+ dtype = next(self.image_encoder.parameters()).dtype
75
+ pixel_values = pixel_values.to(device=device, dtype=dtype)
76
+ video_grid_thw = video_grid_thw.to(device=device)
77
+
78
+ outputs = self.image_encoder(pixel_values, grid_thw=video_grid_thw)
79
+ video_embeds = outputs.pooler_output # [total_merged_tokens, out_hidden_size]
80
+ deepstack_features = outputs.deepstack_features # list of [total_merged_tokens, out_hidden_size]
81
+
82
+ split_sizes = (
83
+ video_grid_thw.prod(-1) // (self.spatial_merge_size ** 2)
84
+ ).tolist()
85
+ split_sizes = [int(s) for s in split_sizes]
86
+
87
+ video_embeds = torch.split(video_embeds, split_sizes)
88
+ deepstack_split = [torch.split(feat, split_sizes) for feat in deepstack_features]
89
+
90
+ max_tokens = max(int(s) for s in split_sizes)
91
+ if self.max_visual_tokens is not None:
92
+ max_tokens = min(max_tokens, self.max_visual_tokens)
93
+
94
+ padded_embeds = []
95
+ padded_deepstack = [[] for _ in range(len(deepstack_features))]
96
+ attention_masks = []
97
+ for sample_idx in range(batch_size):
98
+ sample = video_embeds[sample_idx][:max_tokens]
99
+ valid = sample.shape[0]
100
+ pad = max_tokens - valid
101
+ if pad > 0:
102
+ sample = F.pad(sample, (0, 0, 0, pad))
103
+ padded_embeds.append(sample)
104
+ attention_masks.append(torch.arange(max_tokens, device=sample.device) < valid)
105
+ for layer_idx in range(len(deepstack_features)):
106
+ ds = deepstack_split[layer_idx][sample_idx][:max_tokens]
107
+ if pad > 0:
108
+ ds = F.pad(ds, (0, 0, 0, pad))
109
+ padded_deepstack[layer_idx].append(ds)
110
+
111
+ video_embeds = torch.stack(padded_embeds, dim=0) # [B, N, C]
112
+ attention_mask = torch.stack(attention_masks, dim=0) # [B, N]
113
+ deepstack_embeds = [torch.stack(layer, dim=0) for layer in padded_deepstack] # 3 x [B, N, C]
114
+
115
+ return video_embeds, attention_mask, deepstack_embeds
models/encoder/resnet.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import torch
3
+ from torch import nn
4
+ from transformers import AutoModel, LlavaNextProcessor
5
+
6
+ class ResnetEncoderModel(nn.Module):
7
+ def __init__(self,
8
+ variant: str,
9
+ embed_dim: int,
10
+ freeze: bool,
11
+ downsample_feature_grid_factor: int = 2,
12
+ use_global_img = False,
13
+ ):
14
+
15
+ super().__init__()
16
+ self.num_cameras = 1
17
+ self.num_frames = 1
18
+ self.token_size = embed_dim
19
+
20
+ self.downsample_feature_grid_factor = downsample_feature_grid_factor
21
+
22
+ self.image_encoder = AutoModel.from_pretrained(variant)
23
+
24
+ self.projection = nn.Linear(self.image_encoder.config.hidden_sizes[-1], embed_dim)
25
+ # Embeddings: BS, N_FRAMES, N_CAMS, N_PATCHES, EMBED_DIM
26
+ self.temporal_encoding = nn.Parameter(0.02 * torch.randn(1, self.num_frames, 1, 1, embed_dim))
27
+ self.camera_encoding = nn.Parameter(0.02 * torch.randn(1, 1, self.num_cameras, 1, embed_dim))
28
+ # self.positional_encoding = nn.Parameter(torch.zeros(1, 1, 1, tokens_per_frame, embed_dim)).to("cuda:0")
29
+
30
+ # freeze the paramaeters -> no gradient updates
31
+ if freeze:
32
+ for p in self.parameters():
33
+ p.requires_grad = False
34
+
35
+ # activate the projection layer
36
+ self.projection.weight.requires_grad = True
37
+ self.projection.bias.requires_grad = True
38
+ # self.positional_encoding.requires_grad = True
39
+ self.temporal_encoding.requires_grad = True
40
+ self.camera_encoding.requires_grad = True
41
+
42
+ def forward(
43
+ self,
44
+ pixel_values: torch.Tensor,
45
+ image_sizes = None,
46
+ use_temporal_encoding: bool = True,
47
+ use_positional_encoding: bool = True,
48
+ use_camera_encoding: bool = True,
49
+ ) -> torch.Tensor:
50
+
51
+ BS, num_frames, num_cams, C, H, W = pixel_values.shape
52
+
53
+ pixel_values = pixel_values.squeeze().view(1, C, H, W)
54
+
55
+
56
+ img_embeddings = self.image_encoder(pixel_values=pixel_values).last_hidden_state # torch.Size([4, 512, 12, 32])
57
+ img_embeddings = img_embeddings.flatten(2,3).transpose(1, 2) # torch.Size([4, 384, 512])
58
+
59
+ img_embeddings = self.projection(img_embeddings)
60
+ img_embeddings = img_embeddings.view(-1, num_frames, num_cams, img_embeddings.shape[-2], img_embeddings.shape[-1])
61
+
62
+ input_sequence = img_embeddings
63
+ _, _, _, n_tokens, channels = input_sequence.shape
64
+
65
+ # temporal embeddings
66
+ if use_temporal_encoding:
67
+ input_sequence = input_sequence + self.temporal_encoding
68
+ # positional embeddings
69
+ # if use_positional_encoding:
70
+ # input_sequence = input_sequence + self.positional_encoding
71
+ # per camera embeddings
72
+ if use_camera_encoding:
73
+ input_sequence = input_sequence + self.camera_encoding
74
+
75
+ embeds = input_sequence.view(BS, -1, channels)
76
+
77
+ return embeds, (num_frames, n_tokens, channels)
78
+
79
+
80
+
81
+ if __name__ == "__main__":
82
+ model = ResnetEncoderModel(
83
+ variant="llava-hf/llava-v1.6-mistral-7b-hf",
84
+ debug=True,
85
+ embed_dim=256,
86
+ freeze=True,
87
+ )
88
+ processor = LlavaNextProcessor.from_pretrained("llava-hf/llava-v1.6-mistral-7b-hf")
89
+
90
+ # BS, N_FRAMES, N_CAMS, 3, H, W
91
+ # random vector between 0 and 1
92
+ image = np.random.rand(2, 4, 2, 3, 512, 1024).astype(np.float32)
93
+ image = torch.tensor(image)
94
+
95
+ # merge BS and N_FRAMES and N_CAMS
96
+ image = image.view(-1, 3, 512, 1024)
97
+
98
+ inputs = processor.image_processor(image, return_tensors="pt").to("cuda:0")
99
+ # 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')]]
100
+
101
+ output = model(**inputs)
102
+ print(output[0].shape, output[1])
103
+
104
+ # output_image_shape = True
105
+ # output = model(image, output_image_shape)
106
+ # print(output.shape)
models/fastvlm.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Adapters for Apple's official PyTorch FastVLM checkpoint.
2
+
3
+ The vision tower, pretrained projector and Qwen2 trunk are loaded ONCE and
4
+ then assigned disjoint ownership. No replacement/random projector is used.
5
+ """
6
+ import os
7
+ import sys
8
+ from pathlib import Path
9
+ import torch
10
+ import torch.nn.functional as F
11
+ from torch import nn
12
+
13
+
14
+ class FastVLMVisionAdapter(nn.Module):
15
+ def __init__(self, tower, projector, hidden_size, image_size=(448, 896), freeze=True):
16
+ super().__init__()
17
+ self.image_encoder, self.projector = tower, projector
18
+ self.token_size = hidden_size
19
+ self.image_size = tuple(image_size)
20
+ self.use_global_img = False
21
+ self.frozen = freeze
22
+ self.image_encoder.requires_grad_(not freeze)
23
+ if hasattr(self.image_encoder, 'tune_vision_tower'):
24
+ self.image_encoder.tune_vision_tower = not freeze
25
+
26
+ def train(self, mode=True):
27
+ super().train(mode)
28
+ if self.frozen:
29
+ self.image_encoder.eval()
30
+ return self
31
+
32
+ def forward(self, images, image_sizes=None):
33
+ if images.ndim == 6:
34
+ if images.shape[1:3] != (1, 1):
35
+ raise ValueError('FastVLM/PIM requires exactly ONE current front image')
36
+ images = images[:, 0, 0]
37
+ if images.ndim != 4 or images.shape[1] != 3:
38
+ raise ValueError('Expected RGB [B,3,H,W] or [B,1,1,3,H,W]')
39
+ # Both training and deployment supply raw RGB in [0,255]. MobileCLIP
40
+ # uses mean=0/std=1. Resize once, preserving the intended wide FOV.
41
+ images = F.interpolate(images.float() / 255., size=self.image_size,
42
+ mode='bilinear', align_corners=False, antialias=True)
43
+ parameter = next(self.image_encoder.parameters())
44
+ images = images.to(device=parameter.device, dtype=parameter.dtype)
45
+ features = self.image_encoder(images)
46
+ features = self.projector(features.to(next(self.projector.parameters()).dtype))
47
+ mask = torch.ones(features.shape[:2], device=features.device, dtype=torch.long)
48
+ return features, mask
49
+
50
+
51
+ class FastVLMLanguageAdapter(nn.Module):
52
+ def __init__(self, core, tokenizer, freeze=False, lora=True, lora_r=16,
53
+ lora_alpha=32, lora_dropout=0.05):
54
+ super().__init__()
55
+ self.model, self.tokenizer = core, tokenizer
56
+ self.hidden_size = core.config.hidden_size
57
+ self.vocab_size = core.config.vocab_size
58
+ if tokenizer.pad_token_id is None:
59
+ tokenizer.pad_token = tokenizer.eos_token
60
+ if freeze or lora:
61
+ self.model.requires_grad_(False)
62
+ if lora:
63
+ from peft import LoraConfig, get_peft_model
64
+ self.model = get_peft_model(self.model, LoraConfig(
65
+ r=lora_r, lora_alpha=lora_alpha, lora_dropout=lora_dropout,
66
+ target_modules=['q_proj', 'k_proj', 'v_proj', 'o_proj',
67
+ 'gate_proj', 'up_proj', 'down_proj']))
68
+
69
+ @property
70
+ def embed_tokens(self):
71
+ core = self.model.get_base_model() if hasattr(self.model, 'get_base_model') else self.model
72
+ return core.embed_tokens
73
+
74
+ def forward(self, embeddings, attention_mask=None, **kwargs):
75
+ return self.model(inputs_embeds=embeddings, attention_mask=attention_mask,
76
+ use_cache=False, return_dict=True).last_hidden_state
77
+
78
+
79
+ def load_fastvlm(variant, source_path=None, torch_dtype='bfloat16',
80
+ local_files_only=True, freeze_vision=True, freeze_language=False,
81
+ lora=True, lora_r=16, lora_alpha=32, lora_dropout=0.05,
82
+ image_size=(448, 896), attn_implementation='sdpa'):
83
+ checkpoint = Path(variant).expanduser()
84
+ if local_files_only and not checkpoint.is_dir():
85
+ raise FileNotFoundError(f'FastVLM checkpoint directory missing: {checkpoint}')
86
+ source_path = source_path or os.environ.get('FASTVLM_SOURCE')
87
+ if source_path:
88
+ source = Path(source_path).expanduser().resolve()
89
+ if not (source / 'llava/model/language_model/llava_qwen.py').is_file():
90
+ raise FileNotFoundError(f'Not the official ml-fastvlm source tree: {source}')
91
+ sys.path.insert(0, str(source))
92
+ try:
93
+ from llava.model.language_model.llava_qwen import LlavaQwen2ForCausalLM
94
+ from transformers import AutoTokenizer
95
+ except ImportError as exc:
96
+ raise ImportError('Install the official apple/ml-fastvlm source and set '
97
+ 'FASTVLM_SOURCE; see docs/PIM.md for dependencies') from exc
98
+ dtype = getattr(torch, torch_dtype)
99
+ config = LlavaQwen2ForCausalLM.config_class.from_pretrained(
100
+ str(checkpoint), local_files_only=local_files_only)
101
+ # Construct the tower BEFORE loading its checkpoint tensors. Lazy loading
102
+ # afterwards would silently leave a newly initialised visual encoder.
103
+ config.unfreeze_mm_vision_tower = True
104
+ full, info = LlavaQwen2ForCausalLM.from_pretrained(
105
+ str(checkpoint), config=config, torch_dtype=dtype,
106
+ local_files_only=local_files_only, attn_implementation=attn_implementation,
107
+ output_loading_info=True)
108
+ missing = [k for k in info.get('missing_keys', [])
109
+ if 'vision_tower' in k or 'mm_projector' in k]
110
+ if missing:
111
+ raise RuntimeError(f'Checkpoint does not contain complete visual weights: {missing[:8]}')
112
+ core = full.get_model()
113
+ tower, projector = core.get_vision_tower(), core.mm_projector
114
+ if not getattr(tower, 'is_loaded', True):
115
+ raise RuntimeError('FastVLM vision tower was not constructed during checkpoint loading')
116
+ del core.vision_tower
117
+ del core.mm_projector
118
+ if hasattr(core, 'image_newline'):
119
+ del core.image_newline
120
+ tokenizer = AutoTokenizer.from_pretrained(str(checkpoint), local_files_only=local_files_only)
121
+ vision = FastVLMVisionAdapter(tower, projector, core.config.hidden_size,
122
+ image_size=image_size, freeze=freeze_vision)
123
+ language = FastVLMLanguageAdapter(core, tokenizer, freeze_language, lora,
124
+ lora_r, lora_alpha, lora_dropout)
125
+ return vision, language
models/fastvlm_driving.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Current-frame FastVLM driving model (FIVE-VLA stage 1: no memory, IID samples)."""
2
+ import math
3
+ from collections import defaultdict
4
+
5
+ import torch
6
+ from torch import nn
7
+
8
+ from models.driving import DrivingModel
9
+ from models.fastvlm import load_fastvlm
10
+
11
+
12
+ class FastVLMDrivingModel(DrivingModel):
13
+ def __init__(self, fastvlm=None, vision_bn_train=False, freeze_embeddings=True,
14
+ min_lr_ratio=0.05, vision_model=None, language_model=None, **kwargs):
15
+ if (vision_model is None) != (language_model is None):
16
+ raise ValueError('Provide both injected vision/language adapters, or neither')
17
+ if vision_model is None:
18
+ if fastvlm is None:
19
+ raise ValueError('FastVLM configuration is required')
20
+ vision_model, language_model = load_fastvlm(**dict(fastvlm))
21
+ super().__init__(vision_model=vision_model, language_model=language_model, **kwargs)
22
+ if self.use_world_loss or self.use_consequence_loss or self.use_deepstack:
23
+ raise ValueError('FastVLMDrivingModel trains the plain route/speed heads only')
24
+ self.vision_bn_train = bool(vision_bn_train)
25
+ self.min_lr_ratio = float(min_lr_ratio)
26
+ # The CLIP projection head never receives gradients (DDP would reject it),
27
+ # and AdamW decay would shrink every row of the 151k-token embedding table.
28
+ for name, parameter in self.vision_model.named_parameters():
29
+ if name.startswith('image_encoder.vision_tower.model.head.'):
30
+ parameter.requires_grad_(False)
31
+ if freeze_embeddings:
32
+ self.language_model.embed_tokens.requires_grad_(False)
33
+
34
+ def train(self, mode=True):
35
+ super().train(mode)
36
+ if mode and not self.vision_bn_train:
37
+ for module in self.vision_model.modules():
38
+ if isinstance(module, nn.modules.batchnorm._BatchNorm):
39
+ module.eval()
40
+ return self
41
+
42
+ def configure_optimizers(self):
43
+ # Explicit groups: FastViTHD has bare layer_scale parameters that the
44
+ # legacy module-type whitelist in configure_params_groups rejects.
45
+ groups = defaultdict(list)
46
+ for name, parameter in self.named_parameters():
47
+ if not parameter.requires_grad:
48
+ continue
49
+ if name.startswith('vision_model.'):
50
+ lr = self.vision_lr if self.vision_lr is not None else self.lr
51
+ elif name.startswith('language_model.'):
52
+ lr = self.lm_lr if self.lm_lr is not None else self.lr
53
+ else:
54
+ lr = self.lr
55
+ decay = parameter.ndim >= 2 and not any(
56
+ key in name for key in ('query_embeds', 'layer_scale'))
57
+ groups[(lr, decay)].append(parameter)
58
+ optimizer = torch.optim.AdamW(
59
+ [{'params': params, 'lr': lr, 'weight_decay': self.weight_decay if decay else 0.0}
60
+ for (lr, decay), params in groups.items()],
61
+ betas=self.betas)
62
+ total = max(1, int(self.trainer.estimated_stepping_batches))
63
+ warmup = max(1, int(self.pct_start * total))
64
+ floor = self.min_lr_ratio
65
+
66
+ def schedule(step):
67
+ if step < warmup:
68
+ return (step + 1) / warmup
69
+ progress = min(1.0, (step - warmup) / max(1, total - warmup))
70
+ return floor + (1.0 - floor) * 0.5 * (1.0 + math.cos(math.pi * progress))
71
+
72
+ scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, schedule)
73
+ return {'optimizer': optimizer, 'lr_scheduler': {
74
+ 'scheduler': scheduler, 'interval': 'step', 'frequency': 1}}
models/fastvlm_object_driving.py ADDED
@@ -0,0 +1,194 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Stage 3: FastVLM driving model with object-bank tokens and a per-object relation head.
2
+
3
+ Object rows (dataloader.object_bank: position, heading, speed, size, class, visibility, time unseen)
4
+ enter the LM as extra tokens after the fixed inputs and before the action queries, through an MLP
5
+ whose last layer is zero-initialised so training starts from the stage-1 behaviour. The LM output at
6
+ each object token predicts the expert's relation to that object (ignore / follow / yield); the action
7
+ queries read those positions through causal attention.
8
+ """
9
+ import torch
10
+ import torch.nn.functional as F
11
+ from torch import nn
12
+
13
+ from dataloader.object_bank import DEFAULT_BANK, FEAT_DIM, RELATION_NAMES, RELATION_PAD
14
+ from models.fastvlm_driving import FastVLMDrivingModel
15
+ from models.utils import summarise_losses
16
+
17
+
18
+ class ObjectTokenAdaptor(nn.Module):
19
+ def __init__(self, feat_dim, token_size, hidden_size=256):
20
+ super().__init__()
21
+ self.type_embed = nn.Parameter(0.02 * torch.randn(1, 1, token_size))
22
+ self.mlp = nn.Sequential(nn.Linear(feat_dim, hidden_size), nn.SiLU(True),
23
+ nn.Linear(hidden_size, token_size))
24
+ nn.init.zeros_(self.mlp[-1].weight)
25
+ nn.init.zeros_(self.mlp[-1].bias)
26
+
27
+ def forward(self, objects):
28
+ return self.type_embed + self.mlp(objects)
29
+
30
+
31
+ FEAT_SPEED, FEAT_VISIBLE, FEAT_UNSEEN, FEAT_AGE = 4, 10, 11, 12
32
+ # 'full': every bank row; 'visible_only': rows currently in view (no memory of objects that left the
33
+ # view or got occluded); 'single_frame': visible_only without the quantities that need association
34
+ # over time (speed, time unseen, track age), i.e. what a per-frame detector provides.
35
+ FEATURE_MODES = ('full', 'visible_only', 'single_frame')
36
+
37
+
38
+ class FastVLMObjectDrivingModel(FastVLMDrivingModel):
39
+ uses_object_tokens = True
40
+
41
+ def __init__(self, objects=None, **kwargs):
42
+ super().__init__(**kwargs)
43
+ cfg = dict(objects or {})
44
+ self.object_bank_config = {key: cfg.get(key, value) for key, value in DEFAULT_BANK.items()}
45
+ self.max_objects = int(self.object_bank_config['max_objects'])
46
+ self.relation_loss_weight = float(cfg.get('relation_loss_weight', 0.3))
47
+ self.object_dropout_p = float(cfg.get('object_dropout_p', 0.1))
48
+ self.feature_mode = str(cfg.get('feature_mode', 'full'))
49
+ if self.feature_mode not in FEATURE_MODES:
50
+ raise ValueError(f'objects.feature_mode must be one of {FEATURE_MODES}, got {self.feature_mode}')
51
+ weights = cfg.get('relation_class_weights', [0.25, 1.0, 1.0])
52
+ self.register_buffer('relation_class_weights', torch.tensor(list(weights), dtype=torch.float),
53
+ persistent=False)
54
+ hidden = self.language_model.hidden_size
55
+ self.object_encoder = ObjectTokenAdaptor(FEAT_DIM, hidden, int(cfg.get('hidden_size', 256)))
56
+ self.relation_head = nn.Sequential(nn.Linear(hidden, 256), nn.SiLU(True),
57
+ nn.Linear(256, len(RELATION_NAMES)))
58
+ self._object_outputs = None
59
+ self._object_mask = None
60
+ self._relation_stats = None
61
+
62
+ # ------------------------------------------------------------------ inputs
63
+ def encode_objects(self, driving_input, batch_size, device):
64
+ objects = getattr(driving_input, 'objects', None)
65
+ mask = getattr(driving_input, 'object_mask', None)
66
+ if objects is None:
67
+ objects = torch.zeros(batch_size, self.max_objects, FEAT_DIM, device=device)
68
+ mask = torch.zeros(batch_size, self.max_objects, dtype=torch.bool, device=device)
69
+ objects = objects.to(device=device, dtype=torch.float32)
70
+ mask = mask.to(device=device, dtype=torch.bool)
71
+ if self.feature_mode != 'full':
72
+ mask = mask & (objects[..., FEAT_VISIBLE] > 0.5)
73
+ if self.feature_mode == 'single_frame':
74
+ objects = objects.clone()
75
+ objects[..., [FEAT_SPEED, FEAT_UNSEEN, FEAT_AGE]] = 0.0
76
+ if self.training and self.object_dropout_p > 0:
77
+ keep = torch.rand(batch_size, device=device) >= self.object_dropout_p
78
+ mask = mask & keep[:, None]
79
+ tokens = self.object_encoder(objects) * mask.unsqueeze(-1).to(torch.float32)
80
+ return tokens, mask
81
+
82
+ def forward_model(self, driving_input, adaptor_embeds, driving_labels=None, return_context=False):
83
+ fixed_embeds, attention_mask, _ = self.get_fixed_input_embeds(driving_input)
84
+ batch_size, device = fixed_embeds.size(0), fixed_embeds.device
85
+ object_embeds, object_mask = self.encode_objects(driving_input, batch_size, device)
86
+ dtype = self.language_model.model.dtype
87
+ input_embeds = torch.cat((fixed_embeds, object_embeds.to(fixed_embeds.dtype), adaptor_embeds), dim=1)
88
+ attention_mask = torch.cat((
89
+ attention_mask,
90
+ object_mask.long(),
91
+ torch.ones(adaptor_embeds.shape[:2], dtype=torch.long, device=device),
92
+ ), dim=1)
93
+ outputs = self.language_model.forward(input_embeds.to(dtype=dtype), attention_mask=attention_mask)
94
+ n_fixed, n_obj = fixed_embeds.size(1), object_embeds.size(1)
95
+ fixed_outputs, object_outputs, adaptor_outputs = outputs.split(
96
+ [n_fixed, n_obj, adaptor_embeds.size(1)], dim=1)
97
+ self._object_outputs = object_outputs
98
+ self._object_mask = object_mask
99
+ if return_context:
100
+ return adaptor_outputs, fixed_outputs, attention_mask[:, :n_fixed]
101
+ return adaptor_outputs
102
+
103
+ # ------------------------------------------------------------------ outputs
104
+ def relation_logits(self):
105
+ """[B, N, 3] relation logits for the object tokens of the last forward pass."""
106
+ if self._object_outputs is None:
107
+ return None
108
+ return self.relation_head(self._object_outputs.float())
109
+
110
+ def _relation_loss(self, label):
111
+ target = getattr(label, 'object_relation', None)
112
+ if target is None or self._object_outputs is None:
113
+ return None
114
+ target = target.to(self._object_outputs.device).clone()
115
+ target[~self._object_mask] = RELATION_PAD # objects dropped in encode_objects carry no label
116
+ logits = self.relation_logits()
117
+ per_object = F.cross_entropy(logits.transpose(1, 2), target, weight=self.relation_class_weights,
118
+ ignore_index=RELATION_PAD, reduction='none')
119
+ labelled = (target != RELATION_PAD)
120
+ per_sample = per_object.sum(1) / labelled.sum(1).clamp_min(1)
121
+ counts = labelled.any(1).long()
122
+ with torch.no_grad():
123
+ # Fixed-shape (correct, total) counts: row 0 = all labelled objects, rows 1.. = per class.
124
+ # Fixed shape matters under DDP: per-rank dicts with varying keys would desynchronise
125
+ # the epoch-end all-reduce.
126
+ pred = logits.argmax(-1)
127
+ stats = torch.zeros(len(RELATION_NAMES) + 1, 2, device=logits.device)
128
+ stats[0, 0] = (pred[labelled] == target[labelled]).sum()
129
+ stats[0, 1] = labelled.sum()
130
+ for cls in range(len(RELATION_NAMES)):
131
+ sel = labelled & (target == cls)
132
+ stats[cls + 1, 0] = (pred[sel] == cls).sum()
133
+ stats[cls + 1, 1] = sel.sum()
134
+ self._relation_stats = stats
135
+ return per_sample * self.relation_loss_weight, counts
136
+
137
+ @staticmethod
138
+ def _stats_to_metrics(stats):
139
+ metrics = {}
140
+ if stats[0, 1] > 0:
141
+ metrics['relation_acc'] = stats[0, 0] / stats[0, 1]
142
+ for cls, name in enumerate(RELATION_NAMES):
143
+ if stats[cls + 1, 1] > 0:
144
+ metrics[f'relation_recall_{name}'] = stats[cls + 1, 0] / stats[cls + 1, 1]
145
+ return metrics
146
+
147
+ @property
148
+ def _relation_metrics(self):
149
+ stats = getattr(self, '_relation_stats', None)
150
+ return None if stats is None else self._stats_to_metrics(stats)
151
+
152
+ def forward_loss(self, example, per_sample=False):
153
+ adaptor_dict = self.adaptors(example)
154
+ adaptor_outputs = self.forward_model(example.driving_input, adaptor_dict['inputs'],
155
+ driving_labels=example.driving_label)
156
+ loss_dict = self.adaptors.compute_loss(adaptor_outputs, adaptor_dict, example)
157
+ loss_dict.pop('latent_features', None)
158
+ relation = self._relation_loss(example.driving_label)
159
+ if relation is not None:
160
+ loss_dict['relation_loss'] = relation
161
+ losses = {k: v for k, v in loss_dict.items() if k.endswith('loss')}
162
+ predictions = {k: v for k, v in loss_dict.items() if not k.endswith('loss')}
163
+ if per_sample:
164
+ return losses, predictions
165
+ return summarise_losses(losses)
166
+
167
+ def training_step(self, batch, batch_idx=0):
168
+ out = super().training_step(batch, batch_idx)
169
+ stats = getattr(self, '_relation_stats', None)
170
+ self._relation_stats = None
171
+ if stats is not None: # per-rank step metrics, no collective involved
172
+ for key, value in self._stats_to_metrics(stats).items():
173
+ self.log(f'train_metrics/{key}', value, on_step=True, on_epoch=False, sync_dist=False, logger=True)
174
+ return out
175
+
176
+ def on_validation_epoch_start(self):
177
+ self._val_relation_stats = torch.zeros(len(RELATION_NAMES) + 1, 2, device=self.device)
178
+
179
+ def validation_step(self, batch, batch_idx=0):
180
+ out = super().validation_step(batch, batch_idx)
181
+ stats = getattr(self, '_relation_stats', None)
182
+ self._relation_stats = None
183
+ if stats is not None:
184
+ self._val_relation_stats += stats
185
+ return out
186
+
187
+ def on_validation_epoch_end(self):
188
+ stats = getattr(self, '_val_relation_stats', None)
189
+ if stats is None:
190
+ return
191
+ stats = self.trainer.strategy.reduce(stats, reduce_op='sum') # one fixed-shape all-reduce per rank
192
+ for key, value in self._stats_to_metrics(stats).items():
193
+ self.log(f'val_metrics/{key}', value, on_step=False, on_epoch=True, sync_dist=False, logger=True)
194
+ self._val_relation_stats = None
models/language_model/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+
models/language_model/llama.py ADDED
@@ -0,0 +1,194 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch import Tensor, nn
3
+ from torch.nn import functional as F
4
+ from transformers import AutoTokenizer, LlamaConfig, LlamaModel
5
+ from typing import Any, Dict, Optional, Tuple
6
+
7
+
8
+ CONFIGS: Dict[str, Dict[str, Any]] = {
9
+ "debug": dict(num_hidden_layers=2, num_attention_heads=2, hidden_size=32, intermediate_size=64),
10
+ "legacy-tiny": dict(num_hidden_layers=8, num_attention_heads=16, hidden_size=2048, intermediate_size=4096),
11
+ # -- auto-regressive driving models --
12
+ "tiny": dict(num_hidden_layers=12, num_attention_heads=8, hidden_size=512, intermediate_size=2048), # 50M
13
+ "x-small": dict(num_hidden_layers=14, num_attention_heads=8, hidden_size=1024, intermediate_size=4096), # 235M
14
+ "small": dict(num_hidden_layers=22, num_attention_heads=8, hidden_size=1024, intermediate_size=4096), # 369M
15
+ "medium": dict(num_hidden_layers=22, num_attention_heads=12, hidden_size=1536, intermediate_size=4096), # 623M
16
+ "large": dict(num_hidden_layers=22, num_attention_heads=16, hidden_size=2048, intermediate_size=5632), # 1.1B
17
+ # -- gaia world models --
18
+ "gaia-large": dict(num_hidden_layers=22, num_attention_heads=16, hidden_size=1536, intermediate_size=4096), # 623M
19
+ # -- language models --
20
+ "7B": dict(num_hidden_layers=32, num_attention_heads=32, hidden_size=4096, intermediate_size=11008), # 6476M
21
+ "13B": dict(num_hidden_layers=40, num_attention_heads=40, hidden_size=5120, intermediate_size=11008),
22
+ "70B": dict(
23
+ num_hidden_layers=80, num_attention_heads=64, hidden_size=8192, intermediate_size=28672, num_key_value_heads=8
24
+ ),
25
+ "tiny-llama-1.1b": dict( # 969M
26
+ num_hidden_layers=22, num_attention_heads=32, hidden_size=2048, intermediate_size=5632, num_key_value_heads=4
27
+ ),
28
+ "phi": dict(
29
+ num_hidden_layers=24,
30
+ num_attention_heads=32,
31
+ hidden_size=2048,
32
+ intermediate_size=8192,
33
+ partial_rotary_factor=0.5,
34
+ bias=True,
35
+ vocab_size=51200,
36
+ norm_type="layer_norm",
37
+ mlp_type="gelu_new",
38
+ parallel_attn_mlp=True,
39
+ ),
40
+ }
41
+
42
+
43
+ class Llama(nn.Module):
44
+ def __init__(self, variant: str, lora: bool = False):
45
+ super().__init__()
46
+
47
+ config_overrides = CONFIGS[variant].copy()
48
+
49
+ configuration = LlamaConfig(**config_overrides)
50
+
51
+ # Initializing a model from the llama-7b style configuration
52
+ self.model = LlamaModel(configuration)
53
+ self.tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-hf") # Add huggingface token
54
+ self.model.embed_tokens = None
55
+ # self.model.base_model.embed_tokens = None
56
+ if self.tokenizer.pad_token is None:
57
+ self.tokenizer.pad_token = self.tokenizer.eos_token
58
+
59
+ if lora:
60
+ from peft import get_peft_model
61
+ from peft import LoraConfig, TaskType
62
+
63
+ peft_config = LoraConfig(
64
+ inference_mode=False,
65
+ r=16,
66
+ lora_alpha=32,
67
+ lora_dropout=0.1,
68
+ target_modules="all-linear"
69
+ )
70
+ self.model = get_peft_model(self.model, peft_config)
71
+ self.model.print_trainable_parameters()
72
+
73
+ self.vocab_size = self.model.config.vocab_size
74
+ self.hidden_size = self.model.config.hidden_size
75
+ self.max_position_embeddings = self.model.config.max_position_embeddings
76
+
77
+
78
+ def forward(self,
79
+ embeddings: Tensor,
80
+ attention_mask: Tensor = None,
81
+ return_dict: bool = True,
82
+ ) -> Tensor:
83
+
84
+ outputs = self.model(
85
+ inputs_embeds=embeddings,
86
+ attention_mask=attention_mask,
87
+ output_hidden_states=True,
88
+ return_dict=return_dict
89
+ )#.last_hidden_state
90
+ outputs = outputs.hidden_states[-1]
91
+
92
+ return outputs
93
+
94
+ def sample_categorical(
95
+ self,
96
+ logits: Tensor,
97
+ temperature: float = 0.0,
98
+ top_k: Optional[int] = None,
99
+ top_p: Optional[float] = None,
100
+ restrict_tokens: Optional[Tuple[int, int]] = None,
101
+ ):
102
+ if restrict_tokens is not None:
103
+ logits[..., : restrict_tokens[0]] = -float("inf")
104
+ logits[..., restrict_tokens[0] + restrict_tokens[1] :] = -float("inf")
105
+
106
+ if temperature <= 0.0:
107
+ return logits.argmax(dim=-1, keepdim=False)
108
+
109
+ if top_k is not None:
110
+ v, _ = torch.topk(logits, min(top_k, logits.size(-1)))
111
+ pivot = v.select(-1, -1).unsqueeze(-1)
112
+ logits = torch.where(logits < pivot, -float("inf"), logits)
113
+
114
+ temperature = max(temperature, 1e-9)
115
+ logits = logits / temperature
116
+
117
+ if top_p is not None:
118
+ sorted_logits, sorted_indices = torch.sort(logits, descending=True, dim=-1)
119
+ cumulative_probs = torch.softmax(sorted_logits, dim=-1).cumsum(dim=-1)
120
+ # Shift the indices to the right to keep also the first token above the threshold
121
+ mask = (cumulative_probs > top_p).roll(shifts=1, dims=-1)
122
+ mask[..., 0] = False
123
+ logits[mask.gather(-1, sorted_indices.argsort(-1))] = -float("inf")
124
+
125
+ return torch.multinomial(logits.softmax(dim=-1), 1).squeeze(-1)
126
+
127
+ def greedy_sample(
128
+ self,
129
+ input_embeds: Tensor,
130
+ inputs_mask: Optional[Tensor] = None,
131
+ max_new_tokens: int = 100,
132
+ temperature: float = 0.0,
133
+ top_k: Optional[int] = None,
134
+ top_p: Optional[float] = None,
135
+ eos_token_id: Optional[int] = None,
136
+ cache_offset: int = 0,
137
+ input_embed_matrix: Optional[Tensor] = None,
138
+ logit_matrix: Optional[Tensor] = None,
139
+ restrict_tokens: Optional[Tuple[int, int]] = None,
140
+ ) -> Tuple[Tensor, int]:
141
+
142
+ if input_embed_matrix is None:
143
+ if self.embed_tokens is None:
144
+ raise ValueError(
145
+ "No input embeddings available because the model doesn't define a vocab. "
146
+ "Please provide input_embed_matrix. "
147
+ )
148
+ input_embed_matrix = self.embed_tokens.weight
149
+ if logit_matrix is None:
150
+ if self.lm_head is None:
151
+ raise ValueError(
152
+ "No logit matrix available because the model doesn't define a vocab. "
153
+ "Please provide logit_matrix. "
154
+ )
155
+ logit_matrix = self.lm_head.weight
156
+ # We generate tokens up to the eos token id if provided. If not provided, we generate until the end.
157
+ # If no eos token id is provided, use -1 instead, so we will never stop generating until 'new_token'.
158
+ sampled_tokens = torch.empty((input_embeds.size(0), max_new_tokens), device=input_embeds.device, dtype=torch.long)
159
+ if eos_token_id is not None:
160
+ sampled_tokens.fill_(eos_token_id)
161
+
162
+ # we start with all sequences left to complete
163
+ incomplete_seq_mask = torch.ones(input_embeds.size(0), dtype=torch.bool, device=input_embeds.device)
164
+ for i in range(max_new_tokens):
165
+ outputs = self.forward(embeddings=input_embeds)
166
+ last_hidden_state = outputs[:, -1]
167
+
168
+ # sample the next token
169
+ logits = F.linear(last_hidden_state, logit_matrix)
170
+ next_token = self.sample_categorical(
171
+ logits, temperature=temperature, top_k=top_k, top_p=top_p, restrict_tokens=restrict_tokens
172
+ )
173
+ x = F.embedding(next_token.unsqueeze(1), input_embed_matrix)
174
+
175
+ input_embeds = torch.cat([input_embeds, x], dim=1)
176
+ attn_mask = None
177
+
178
+ # only update sequences where we haven't predicted the eos token before
179
+ sampled_tokens[incomplete_seq_mask, i] = next_token[incomplete_seq_mask]
180
+
181
+ if eos_token_id is not None:
182
+ # only update the mask of incomplete sequences and stop early if an eos token id is provided.
183
+ incomplete_seq_mask = sampled_tokens[:, i] != eos_token_id
184
+ if not incomplete_seq_mask.any():
185
+ # finished all sequences, early exit
186
+ sampled_tokens = sampled_tokens[:, : i + 1]
187
+ break
188
+
189
+ return sampled_tokens, input_embeds
190
+
191
+
192
+ if __name__ == "__main__":
193
+ model = Llama("x-small", False)
194
+ print(model)
models/language_model/qwen2_5_vl.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional
2
+
3
+ import torch
4
+ from torch import Tensor, nn
5
+ from transformers import AutoConfig, AutoTokenizer
6
+ from transformers.models.qwen2_5_vl.modeling_qwen2_5_vl import Qwen2_5_VLTextModel
7
+
8
+ from models.qwen_utils import build_empty_module, load_prefixed_safetensors
9
+
10
+
11
+ class Qwen2_5VLLanguageModel(nn.Module):
12
+ def __init__(
13
+ self,
14
+ variant: str,
15
+ freeze: bool = False,
16
+ lora: bool = False,
17
+ lora_r: int = 16,
18
+ lora_alpha: int = 32,
19
+ lora_dropout: float = 0.1,
20
+ local_files_only: bool = True,
21
+ torch_dtype: str = "bfloat16",
22
+ ):
23
+ super().__init__()
24
+ self.config = AutoConfig.from_pretrained(variant, local_files_only=local_files_only)
25
+ self.config.text_config._attn_implementation = "flash_attention_2"
26
+ dtype = getattr(torch, torch_dtype)
27
+ self.model = build_empty_module(Qwen2_5_VLTextModel, self.config.text_config)
28
+ load_prefixed_safetensors(self.model, variant, "model.", torch_dtype=dtype)
29
+
30
+ self.tokenizer = AutoTokenizer.from_pretrained(variant, local_files_only=local_files_only)
31
+ if self.tokenizer.pad_token is None:
32
+ self.tokenizer.pad_token = self.tokenizer.eos_token
33
+
34
+ self.vocab_size = self.model.config.vocab_size
35
+ self.hidden_size = self.model.config.hidden_size
36
+ self.max_position_embeddings = self.model.config.max_position_embeddings
37
+
38
+ if freeze:
39
+ for param in self.model.parameters():
40
+ param.requires_grad = False
41
+
42
+ if lora:
43
+ from peft import LoraConfig, get_peft_model
44
+
45
+ peft_config = LoraConfig(
46
+ inference_mode=False,
47
+ r=lora_r,
48
+ lora_alpha=lora_alpha,
49
+ lora_dropout=lora_dropout,
50
+ target_modules=[
51
+ "q_proj",
52
+ "k_proj",
53
+ "v_proj",
54
+ "o_proj",
55
+ "gate_proj",
56
+ "up_proj",
57
+ "down_proj",
58
+ ],
59
+ )
60
+ self.model = get_peft_model(self.model, peft_config)
61
+ self.model.print_trainable_parameters()
62
+
63
+ def forward(
64
+ self,
65
+ embeddings: Tensor,
66
+ attention_mask: Optional[Tensor] = None,
67
+ return_dict: bool = True,
68
+ ) -> Tensor:
69
+ if attention_mask is None:
70
+ attention_mask = torch.ones(
71
+ embeddings.shape[:2],
72
+ dtype=torch.long,
73
+ device=embeddings.device,
74
+ )
75
+
76
+ outputs = self.model(
77
+ inputs_embeds=embeddings,
78
+ attention_mask=attention_mask,
79
+ use_cache=False,
80
+ output_hidden_states=False,
81
+ return_dict=return_dict,
82
+ )
83
+ return outputs.last_hidden_state if return_dict else outputs[0]
models/language_model/qwen3_vl.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List, Optional
2
+
3
+ import torch
4
+ from torch import Tensor, nn
5
+ from transformers import AutoConfig, AutoTokenizer
6
+ from transformers.models.qwen3_vl.modeling_qwen3_vl import Qwen3VLTextModel
7
+
8
+ from models.qwen_utils import build_empty_module, load_prefixed_safetensors
9
+ from utils.logging_project import is_global_rank_zero, rank_zero_print
10
+
11
+
12
+ class Qwen3VLLanguageModel(nn.Module):
13
+ """
14
+ Qwen3-VL text decoder with DeepStack support: visual features from
15
+ intermediate vision-encoder layers are added to the hidden states of the
16
+ first LLM layers at the visual token positions (deepstack_visual_embeds).
17
+ """
18
+
19
+ def __init__(
20
+ self,
21
+ variant: str,
22
+ freeze: bool = False,
23
+ lora: bool = False,
24
+ lora_r: int = 16,
25
+ lora_alpha: int = 32,
26
+ lora_dropout: float = 0.1,
27
+ local_files_only: bool = True,
28
+ torch_dtype: str = "bfloat16",
29
+ ):
30
+ super().__init__()
31
+ self.config = AutoConfig.from_pretrained(variant, local_files_only=local_files_only)
32
+ dtype = getattr(torch, torch_dtype)
33
+ self.config.text_config._attn_implementation = "flash_attention_2"
34
+ self.config.text_config.dtype = dtype
35
+ rank_zero_print("Loading Qwen3-VL language model (meta init)...", flush=True)
36
+ self.model = build_empty_module(Qwen3VLTextModel, self.config.text_config)
37
+ rank_zero_print("Loading language model weights...", flush=True)
38
+ load_prefixed_safetensors(self.model, variant, "model.language_model.", torch_dtype=dtype)
39
+ rank_zero_print("Language model weights ready.", flush=True)
40
+
41
+ self.tokenizer = AutoTokenizer.from_pretrained(variant, local_files_only=local_files_only)
42
+ if self.tokenizer.pad_token is None:
43
+ self.tokenizer.pad_token = self.tokenizer.eos_token
44
+
45
+ self.vocab_size = self.model.config.vocab_size
46
+ self.hidden_size = self.model.config.hidden_size
47
+ self.max_position_embeddings = self.model.config.max_position_embeddings
48
+
49
+ if freeze:
50
+ for param in self.model.parameters():
51
+ param.requires_grad = False
52
+
53
+ if lora:
54
+ from peft import LoraConfig, get_peft_model
55
+
56
+ rank_zero_print("Applying LoRA adapters...", flush=True)
57
+ peft_config = LoraConfig(
58
+ inference_mode=False,
59
+ r=lora_r,
60
+ lora_alpha=lora_alpha,
61
+ lora_dropout=lora_dropout,
62
+ target_modules=[
63
+ "q_proj",
64
+ "k_proj",
65
+ "v_proj",
66
+ "o_proj",
67
+ "gate_proj",
68
+ "up_proj",
69
+ "down_proj",
70
+ ],
71
+ )
72
+ self.model = get_peft_model(self.model, peft_config)
73
+ if is_global_rank_zero():
74
+ self.model.print_trainable_parameters()
75
+
76
+ @property
77
+ def embed_tokens(self):
78
+ model = self.model
79
+ # unwrap peft
80
+ if hasattr(model, "get_base_model"):
81
+ model = model.get_base_model()
82
+ return model.embed_tokens
83
+
84
+ def forward(
85
+ self,
86
+ embeddings: Tensor,
87
+ attention_mask: Optional[Tensor] = None,
88
+ position_ids: Optional[Tensor] = None,
89
+ visual_pos_masks: Optional[Tensor] = None,
90
+ deepstack_visual_embeds: Optional[List[Tensor]] = None,
91
+ return_dict: bool = True,
92
+ ) -> Tensor:
93
+ if attention_mask is None:
94
+ attention_mask = torch.ones(
95
+ embeddings.shape[:2],
96
+ dtype=torch.long,
97
+ device=embeddings.device,
98
+ )
99
+
100
+ outputs = self.model(
101
+ inputs_embeds=embeddings,
102
+ attention_mask=attention_mask,
103
+ position_ids=position_ids,
104
+ visual_pos_masks=visual_pos_masks,
105
+ deepstack_visual_embeds=deepstack_visual_embeds,
106
+ use_cache=False,
107
+ return_dict=return_dict,
108
+ )
109
+ return outputs.last_hidden_state if return_dict else outputs[0]
models/language_model/qwen3_vl_scratch.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Randomly-initialised, shrunk Qwen3-VL text decoder ("small" preset).
2
+
3
+ Same architecture family as `models.language_model.qwen3_vl.Qwen3VLLanguageModel`
4
+ (Interleaved-MRoPE, DeepStack injection) but built from a (possibly downsized)
5
+ config and trained from scratch instead of loading pretrained weights + LoRA.
6
+
7
+ ConsDrive v4 keeps the 2B width (hidden 2048, 16 heads, FFN 6144) and only
8
+ shrinks depth (10 layers) so DeepStack features stay Identity-aligned.
9
+
10
+ The model is action-only: there is no text input or output, so no tokenizer is
11
+ exposed (`tokenizer = None`) and the (tiny) token embedding table is frozen so
12
+ DeepSpeed never sees an unused trainable parameter.
13
+ """
14
+
15
+ from copy import deepcopy
16
+ from typing import List, Optional
17
+
18
+ import torch
19
+ from torch import Tensor, nn
20
+ from transformers import AutoConfig
21
+ from transformers.models.qwen3_vl.modeling_qwen3_vl import Qwen3VLTextModel
22
+
23
+ from utils.logging_project import rank_zero_print
24
+
25
+
26
+ class Qwen3VLScratchLanguageModel(nn.Module):
27
+ def __init__(
28
+ self,
29
+ variant: str,
30
+ hidden_size: int = 1024,
31
+ num_hidden_layers: int = 22,
32
+ num_attention_heads: int = 8,
33
+ num_key_value_heads: int = 8,
34
+ intermediate_size: int = 4096,
35
+ head_dim: int = 128,
36
+ vocab_size: int = 16,
37
+ local_files_only: bool = True,
38
+ torch_dtype: str = "bfloat16",
39
+ ):
40
+ super().__init__()
41
+ dtype = getattr(torch, torch_dtype)
42
+
43
+ # Start from the pretrained text config so RoPE/MRoPE settings
44
+ # (rope_theta, mrope_section, interleaved) stay compatible with the
45
+ # position ids built in DrivingModel, then shrink the trunk.
46
+ base_config = AutoConfig.from_pretrained(variant, local_files_only=local_files_only)
47
+ text_config = deepcopy(base_config.text_config)
48
+ text_config.hidden_size = int(hidden_size)
49
+ text_config.num_hidden_layers = int(num_hidden_layers)
50
+ text_config.num_attention_heads = int(num_attention_heads)
51
+ text_config.num_key_value_heads = int(num_key_value_heads)
52
+ text_config.intermediate_size = int(intermediate_size)
53
+ text_config.head_dim = int(head_dim)
54
+ # Text tokens are never used; keep the embedding table symbolic.
55
+ text_config.vocab_size = int(vocab_size)
56
+ text_config.tie_word_embeddings = False
57
+ text_config._attn_implementation = "flash_attention_2"
58
+ text_config.dtype = dtype
59
+ self.config = text_config
60
+
61
+ rank_zero_print(
62
+ f"Building from-scratch Qwen3-VL text model: {num_hidden_layers}L, "
63
+ f"hidden {hidden_size}, heads {num_attention_heads}/{num_key_value_heads}, "
64
+ f"ffn {intermediate_size}, head_dim {head_dim}",
65
+ flush=True,
66
+ )
67
+ self.model = Qwen3VLTextModel(text_config).to(dtype)
68
+ # No text input exists in this setup; freeze embed_tokens so all
69
+ # trainable parameters participate in every backward pass.
70
+ self.model.embed_tokens.weight.requires_grad = False
71
+
72
+ num_params = sum(p.numel() for p in self.model.parameters())
73
+ rank_zero_print(f"Scratch LM parameters: {num_params / 1e6:.1f}M", flush=True)
74
+
75
+ self.tokenizer = None
76
+ self.vocab_size = text_config.vocab_size
77
+ self.hidden_size = text_config.hidden_size
78
+ self.max_position_embeddings = text_config.max_position_embeddings
79
+
80
+ def forward(
81
+ self,
82
+ embeddings: Tensor,
83
+ attention_mask: Optional[Tensor] = None,
84
+ position_ids: Optional[Tensor] = None,
85
+ visual_pos_masks: Optional[Tensor] = None,
86
+ deepstack_visual_embeds: Optional[List[Tensor]] = None,
87
+ return_dict: bool = True,
88
+ ) -> Tensor:
89
+ if attention_mask is None:
90
+ attention_mask = torch.ones(
91
+ embeddings.shape[:2],
92
+ dtype=torch.long,
93
+ device=embeddings.device,
94
+ )
95
+
96
+ outputs = self.model(
97
+ inputs_embeds=embeddings,
98
+ attention_mask=attention_mask,
99
+ position_ids=position_ids,
100
+ visual_pos_masks=visual_pos_masks,
101
+ deepstack_visual_embeds=deepstack_visual_embeds,
102
+ use_cache=False,
103
+ return_dict=return_dict,
104
+ )
105
+ return outputs.last_hidden_state if return_dict else outputs[0]
models/language_model/qwen3_vl_truncated.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Pretrained-initialised, depth-truncated Qwen3-VL text decoder.
2
+
3
+ ConsDrive v5: same interface as `Qwen3VLScratchLanguageModel` (10-layer trunk,
4
+ hidden 2048, DeepStack + Interleaved-MRoPE) but every kept layer, the token
5
+ embedding table, and the final norm are loaded from the pretrained checkpoint
6
+ instead of random init. Keeping the pretrained embed_tokens (frozen) plus the
7
+ tokenizer restores the text pathway, so `command_tp_text` navigation works on
8
+ the small trunk (the digit/word embeddings carry their pretrained meaning).
9
+
10
+ Parameter budget: 10 pretrained layers at 2B width are ~0.5B trainable; the
11
+ frozen full-vocab embedding table adds ~0.3B non-trainable lookup weights.
12
+ """
13
+
14
+ from copy import deepcopy
15
+ from typing import List, Optional
16
+
17
+ import torch
18
+ from torch import Tensor, nn
19
+ from transformers import AutoConfig, AutoTokenizer
20
+ from transformers.models.qwen3_vl.modeling_qwen3_vl import Qwen3VLTextModel
21
+
22
+ from models.qwen_utils import build_empty_module, load_prefixed_state_dict
23
+ from utils.logging_project import rank_zero_print
24
+
25
+
26
+ class Qwen3VLTruncatedLanguageModel(nn.Module):
27
+ def __init__(
28
+ self,
29
+ variant: str,
30
+ num_hidden_layers: int = 10,
31
+ freeze_embed: bool = True,
32
+ local_files_only: bool = True,
33
+ torch_dtype: str = "bfloat16",
34
+ ):
35
+ super().__init__()
36
+ dtype = getattr(torch, torch_dtype)
37
+
38
+ base_config = AutoConfig.from_pretrained(
39
+ variant, local_files_only=local_files_only
40
+ )
41
+ text_config = deepcopy(base_config.text_config)
42
+ text_config.num_hidden_layers = int(num_hidden_layers)
43
+ text_config._attn_implementation = "flash_attention_2"
44
+ text_config.dtype = dtype
45
+ self.config = text_config
46
+
47
+ rank_zero_print(
48
+ f"Building truncated Qwen3-VL text model: first {num_hidden_layers} "
49
+ f"pretrained layers, hidden {text_config.hidden_size}",
50
+ flush=True,
51
+ )
52
+ self.model = build_empty_module(Qwen3VLTextModel, text_config)
53
+
54
+ # The checkpoint holds all 28 layers; keep only the keys our shrunk
55
+ # module actually has (layers 0..N-1, embed_tokens, final norm).
56
+ full_state = load_prefixed_state_dict(variant, "model.language_model.")
57
+ wanted = set(self.model.state_dict().keys())
58
+ state = {
59
+ k: v.to(dtype) for k, v in full_state.items() if k in wanted
60
+ }
61
+ missing = wanted - state.keys()
62
+ if missing:
63
+ raise RuntimeError(
64
+ f"Truncated LM init incomplete; missing keys: {sorted(missing)[:10]}"
65
+ )
66
+ self.model.load_state_dict(state, strict=True, assign=True)
67
+ del full_state, state
68
+ rank_zero_print("Truncated language model weights ready.", flush=True)
69
+
70
+ self.tokenizer = AutoTokenizer.from_pretrained(
71
+ variant, local_files_only=local_files_only
72
+ )
73
+ if self.tokenizer.pad_token is None:
74
+ self.tokenizer.pad_token = self.tokenizer.eos_token
75
+
76
+ if freeze_embed:
77
+ # Digit/word embeddings keep their pretrained geometry; also spares
78
+ # DeepSpeed the ~0.3B-parameter embedding gradient.
79
+ self.model.embed_tokens.weight.requires_grad = False
80
+
81
+ num_params = sum(p.numel() for p in self.model.parameters())
82
+ num_trainable = sum(
83
+ p.numel() for p in self.model.parameters() if p.requires_grad
84
+ )
85
+ rank_zero_print(
86
+ f"Truncated LM parameters: {num_params / 1e6:.1f}M total, "
87
+ f"{num_trainable / 1e6:.1f}M trainable",
88
+ flush=True,
89
+ )
90
+
91
+ self.vocab_size = text_config.vocab_size
92
+ self.hidden_size = text_config.hidden_size
93
+ self.max_position_embeddings = text_config.max_position_embeddings
94
+
95
+ @property
96
+ def embed_tokens(self):
97
+ return self.model.embed_tokens
98
+
99
+ def forward(
100
+ self,
101
+ embeddings: Tensor,
102
+ attention_mask: Optional[Tensor] = None,
103
+ position_ids: Optional[Tensor] = None,
104
+ visual_pos_masks: Optional[Tensor] = None,
105
+ deepstack_visual_embeds: Optional[List[Tensor]] = None,
106
+ return_dict: bool = True,
107
+ ) -> Tensor:
108
+ if attention_mask is None:
109
+ attention_mask = torch.ones(
110
+ embeddings.shape[:2],
111
+ dtype=torch.long,
112
+ device=embeddings.device,
113
+ )
114
+
115
+ outputs = self.model(
116
+ inputs_embeds=embeddings,
117
+ attention_mask=attention_mask,
118
+ position_ids=position_ids,
119
+ visual_pos_masks=visual_pos_masks,
120
+ deepstack_visual_embeds=deepstack_visual_embeds,
121
+ use_cache=False,
122
+ return_dict=return_dict,
123
+ )
124
+ return outputs.last_hidden_state if return_dict else outputs[0]
models/language_model/tiny_transformer.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import string
2
+ from typing import Dict, List, Optional
3
+
4
+ import torch
5
+ from torch import Tensor, nn
6
+
7
+
8
+ class CharacterCommandTokenizer:
9
+ def __init__(self, max_length: int = 96):
10
+ chars = string.ascii_lowercase + string.digits + " .,;:-_/[]()<>"
11
+ self.pad_token = "<pad>"
12
+ self.bos_token = "<bos>"
13
+ self.eos_token = "<eos>"
14
+ self.unk_token = "<unk>"
15
+ self.id_to_token = [self.pad_token, self.bos_token, self.eos_token, self.unk_token, *chars]
16
+ self.token_to_id = {token: idx for idx, token in enumerate(self.id_to_token)}
17
+ self.pad_token_id = self.token_to_id[self.pad_token]
18
+ self.bos_token_id = self.token_to_id[self.bos_token]
19
+ self.eos_token_id = self.token_to_id[self.eos_token]
20
+ self.unk_token_id = self.token_to_id[self.unk_token]
21
+ self.vocab_size = len(self.id_to_token)
22
+ self.max_length = max_length
23
+
24
+ def _encode(self, text: str, max_length: int) -> List[int]:
25
+ ids = [self.bos_token_id]
26
+ ids.extend(self.token_to_id.get(ch, self.unk_token_id) for ch in text.lower())
27
+ ids.append(self.eos_token_id)
28
+ return ids[:max_length]
29
+
30
+ def __call__(
31
+ self,
32
+ texts,
33
+ padding: bool = True,
34
+ truncation: bool = True,
35
+ return_tensors: Optional[str] = None,
36
+ max_length: Optional[int] = None,
37
+ ) -> Dict[str, Tensor]:
38
+ if isinstance(texts, str):
39
+ texts = [texts]
40
+ max_length = max_length or self.max_length
41
+ encoded = [self._encode(text, max_length) for text in texts]
42
+ padded_length = max(len(ids) for ids in encoded) if padding else max_length
43
+ padded_length = min(padded_length, max_length)
44
+
45
+ input_ids = []
46
+ attention_mask = []
47
+ for ids in encoded:
48
+ ids = ids[:padded_length]
49
+ pad_len = padded_length - len(ids)
50
+ input_ids.append(ids + [self.pad_token_id] * pad_len)
51
+ attention_mask.append([1] * len(ids) + [0] * pad_len)
52
+
53
+ return {
54
+ "input_ids": torch.tensor(input_ids, dtype=torch.long),
55
+ "attention_mask": torch.tensor(attention_mask, dtype=torch.long),
56
+ }
57
+
58
+
59
+ class TinyCausalTransformerBackbone(nn.Module):
60
+ def __init__(
61
+ self,
62
+ vocab_size: int,
63
+ hidden_size: int = 512,
64
+ num_hidden_layers: int = 6,
65
+ num_attention_heads: int = 8,
66
+ intermediate_size: int = 2048,
67
+ max_position_embeddings: int = 4096,
68
+ dropout: float = 0.0,
69
+ ):
70
+ super().__init__()
71
+ self.embed_tokens = nn.Embedding(vocab_size, hidden_size)
72
+ self.position_embedding = nn.Embedding(max_position_embeddings, hidden_size)
73
+ encoder_layer = nn.TransformerEncoderLayer(
74
+ d_model=hidden_size,
75
+ nhead=num_attention_heads,
76
+ dim_feedforward=intermediate_size,
77
+ dropout=dropout,
78
+ activation="gelu",
79
+ batch_first=True,
80
+ norm_first=True,
81
+ )
82
+ self.layers = nn.TransformerEncoder(encoder_layer, num_layers=num_hidden_layers)
83
+ self.norm = nn.LayerNorm(hidden_size)
84
+ self.max_position_embeddings = max_position_embeddings
85
+
86
+ @property
87
+ def dtype(self):
88
+ return self.embed_tokens.weight.dtype
89
+
90
+ def forward(self, inputs_embeds: Tensor, attention_mask: Optional[Tensor] = None) -> Tensor:
91
+ seq_len = inputs_embeds.shape[1]
92
+ if seq_len > self.max_position_embeddings:
93
+ raise ValueError(
94
+ f"Sequence length {seq_len} exceeds max_position_embeddings={self.max_position_embeddings}."
95
+ )
96
+
97
+ positions = torch.arange(seq_len, device=inputs_embeds.device)
98
+ x = inputs_embeds + self.position_embedding(positions).to(dtype=inputs_embeds.dtype).unsqueeze(0)
99
+
100
+ causal_mask = torch.triu(
101
+ torch.ones(seq_len, seq_len, device=inputs_embeds.device, dtype=torch.bool),
102
+ diagonal=1,
103
+ )
104
+ key_padding_mask = None
105
+ if attention_mask is not None:
106
+ key_padding_mask = attention_mask.to(device=inputs_embeds.device) == 0
107
+
108
+ x = self.layers(x, mask=causal_mask, src_key_padding_mask=key_padding_mask)
109
+ return self.norm(x)
110
+
111
+
112
+ class TinyTransformerLanguageModel(nn.Module):
113
+ def __init__(
114
+ self,
115
+ hidden_size: int = 512,
116
+ num_hidden_layers: int = 6,
117
+ num_attention_heads: int = 8,
118
+ intermediate_size: int = 2048,
119
+ max_position_embeddings: int = 4096,
120
+ tokenizer_max_length: int = 96,
121
+ dropout: float = 0.0,
122
+ freeze: bool = False,
123
+ ):
124
+ super().__init__()
125
+ self.tokenizer = CharacterCommandTokenizer(max_length=tokenizer_max_length)
126
+ self.model = TinyCausalTransformerBackbone(
127
+ vocab_size=self.tokenizer.vocab_size,
128
+ hidden_size=hidden_size,
129
+ num_hidden_layers=num_hidden_layers,
130
+ num_attention_heads=num_attention_heads,
131
+ intermediate_size=intermediate_size,
132
+ max_position_embeddings=max_position_embeddings,
133
+ dropout=dropout,
134
+ )
135
+ self.vocab_size = self.tokenizer.vocab_size
136
+ self.hidden_size = hidden_size
137
+ self.max_position_embeddings = max_position_embeddings
138
+
139
+ if freeze:
140
+ for param in self.parameters():
141
+ param.requires_grad = False
142
+
143
+ def forward(
144
+ self,
145
+ embeddings: Tensor,
146
+ attention_mask: Optional[Tensor] = None,
147
+ return_dict: bool = True,
148
+ ) -> Tensor:
149
+ return self.model(inputs_embeds=embeddings, attention_mask=attention_mask)
models/pim.py ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Current-observation interaction memory, independent of the vision backbone.
2
+
3
+ Version 1 uses supervised semantic slots, not object-ID tracking. Multiple
4
+ objects of one interaction type are aggregated. Labels never enter forward().
5
+ """
6
+ from dataclasses import dataclass
7
+ from typing import Optional
8
+ import torch
9
+ from torch import nn
10
+
11
+ SLOT_NAMES = (
12
+ 'crossing_vehicle', 'oncoming_vehicle', 'lead_vehicle', 'pedestrian',
13
+ 'cyclist', 'static_obstacle', 'traffic_control', 'other_interaction',
14
+ )
15
+
16
+
17
+ @dataclass
18
+ class InteractionState:
19
+ features: torch.Tensor
20
+ valid: torch.Tensor
21
+ last_observed: torch.Tensor
22
+ timestamp: torch.Tensor
23
+ observed_pose: Optional[torch.Tensor] = None
24
+
25
+ def detach(self):
26
+ return InteractionState(self.features.detach(), self.valid.detach(),
27
+ self.last_observed.detach(), self.timestamp.detach(),
28
+ None if self.observed_pose is None else self.observed_pose.detach())
29
+
30
+
31
+ class PersistentInteractionMemory(nn.Module):
32
+ """Unmatched semantic slots persist until current evidence predicts release.
33
+
34
+ State belongs to one stream. Never register it as a learned parameter or
35
+ checkpoint buffer. Callers own state reset, route isolation and TBPTT.
36
+ """
37
+ def __init__(self, hidden_size, slots=8, memory_dim=256, heads=4,
38
+ observation_threshold=0.5, release_threshold=0.9):
39
+ super().__init__()
40
+ if slots < 1 or heads < 1 or memory_dim % heads:
41
+ raise ValueError('Invalid memory slots or attention dimensions')
42
+ if not 0 < observation_threshold < 1 or not 0 < release_threshold < 1:
43
+ raise ValueError('Thresholds must lie in (0, 1)')
44
+ self.slots, self.memory_dim = slots, memory_dim
45
+ self.observation_threshold, self.release_threshold = observation_threshold, release_threshold
46
+ self.query_embeds_observation = nn.Parameter(torch.randn(1, slots, hidden_size) * .02)
47
+ self.observation_projection = nn.Linear(hidden_size, memory_dim)
48
+ self.visibility = nn.Linear(memory_dim, 1)
49
+ self.update_cell = nn.GRUCell(memory_dim, memory_dim)
50
+ self.release = nn.Sequential(nn.Linear(2 * memory_dim + 5, memory_dim),
51
+ nn.SiLU(), nn.Linear(memory_dim, 1))
52
+ self.pending_head = nn.Linear(memory_dim, 1)
53
+ self.action_projection = nn.Linear(hidden_size, memory_dim)
54
+ self.metadata_projection = nn.Sequential(nn.Linear(5, memory_dim), nn.SiLU())
55
+ self.reader = nn.MultiheadAttention(memory_dim, heads, batch_first=True)
56
+ self.output_projection = nn.Linear(memory_dim, hidden_size)
57
+ nn.init.zeros_(self.output_projection.weight)
58
+ nn.init.zeros_(self.output_projection.bias)
59
+ nn.init.constant_(self.release[-1].bias, -4.)
60
+
61
+ def empty(self, batch_size, device, dtype=torch.float32):
62
+ return InteractionState(
63
+ torch.zeros(batch_size, self.slots, self.memory_dim, device=device, dtype=dtype),
64
+ torch.zeros(batch_size, self.slots, device=device, dtype=torch.bool),
65
+ torch.zeros(batch_size, self.slots, device=device),
66
+ torch.zeros(batch_size, device=device),
67
+ torch.zeros(batch_size, self.slots, 3, device=device))
68
+
69
+ def observation_queries(self, batch_size):
70
+ return self.query_embeds_observation.expand(batch_size, -1, -1)
71
+
72
+ @staticmethod
73
+ def _metadata(timestamp, pose, last_observed, observed_pose):
74
+ age = (timestamp[:, None] - last_observed).clamp_min(0)
75
+ displacement = pose[:, None, :2] - observed_pose[..., :2]
76
+ yaw = observed_pose[..., 2]
77
+ c, s = yaw.cos(), yaw.sin()
78
+ dx = c * displacement[..., 0] + s * displacement[..., 1]
79
+ dy = -s * displacement[..., 0] + c * displacement[..., 1]
80
+ angle = pose[:, None, 2] - yaw
81
+ return torch.stack((torch.log1p(age), dx / 50., dy / 50.,
82
+ angle.sin(), angle.cos()), -1), age
83
+
84
+ def forward(self, observations, actions, timestamp, state=None, reset=None,
85
+ ego_pose=None, read_enabled=True):
86
+ z = self.observation_projection(observations)
87
+ b, n, d = z.shape
88
+ if n != self.slots:
89
+ raise ValueError('Observation count differs from slot count')
90
+ timestamp = timestamp.to(z.device, torch.float32).reshape(b)
91
+ ego_pose = (torch.zeros(b, 3, device=z.device) if ego_pose is None
92
+ else ego_pose.to(z.device, torch.float32).reshape(b, 3))
93
+ if not torch.isfinite(timestamp).all() or not torch.isfinite(ego_pose).all():
94
+ raise ValueError('Timestamp and ego pose must be finite')
95
+ initial = state is None
96
+ if initial:
97
+ state = self.empty(b, z.device, z.dtype)
98
+ if state.features.shape != z.shape:
99
+ raise ValueError('State batch/slot shape mismatch; reset the stream')
100
+ reset = (torch.zeros(b, dtype=torch.bool, device=z.device) if reset is None
101
+ else reset.to(z.device).bool().reshape(b))
102
+ if ((timestamp < state.timestamp) & ~reset).any():
103
+ raise ValueError('Non-monotonic stream timestamps require reset')
104
+ fresh = (timestamp > state.timestamp) | reset | initial
105
+ old_valid = state.valid & ~reset[:, None]
106
+ old = torch.where(old_valid[..., None], state.features, torch.zeros_like(state.features))
107
+ old_pose = (ego_pose[:, None].expand(-1, n, -1) if state.observed_pose is None
108
+ else state.observed_pose)
109
+ old_time = torch.where(reset[:, None], timestamp[:, None], state.last_observed)
110
+ metadata_before, _ = self._metadata(timestamp, ego_pose, old_time, old_pose)
111
+ visibility_logits = self.visibility(z).squeeze(-1)
112
+ observed = (visibility_logits.sigmoid() >= self.observation_threshold) & fresh[:, None]
113
+ candidate = self.update_cell(z.reshape(-1, d), old.reshape(-1, d)).reshape(b, n, d)
114
+ features = torch.where(observed[..., None], candidate, old)
115
+ scene = z.mean(1, keepdim=True).expand(-1, n, -1)
116
+ # Current-only evidence and ego motion can support release; absence and
117
+ # elapsed time alone never deterministically clear a slot.
118
+ release_logits = self.release(torch.cat((old, scene, metadata_before.to(z.dtype)), -1)).squeeze(-1)
119
+ released = old_valid & fresh[:, None] & (release_logits.sigmoid() >= self.release_threshold)
120
+ valid = (old_valid | observed) & ~released
121
+ features = features * valid[..., None]
122
+ last_observed = torch.where(observed, timestamp[:, None], old_time)
123
+ observed_pose = torch.where(observed[..., None], ego_pose[:, None], old_pose)
124
+ metadata, age = self._metadata(timestamp, ego_pose, last_observed, observed_pose)
125
+ keys = features + self.metadata_projection(metadata.to(z.dtype))
126
+ null = z.new_zeros(b, 1, d)
127
+ keys, values = torch.cat((keys, null), 1), torch.cat((features, null), 1)
128
+ mask = torch.cat((~valid, torch.zeros(b, 1, dtype=torch.bool, device=z.device)), 1)
129
+ read, _ = self.reader(self.action_projection(actions), keys, values,
130
+ key_padding_mask=mask, need_weights=False)
131
+ delta = self.output_projection(read) * valid.any(1)[:, None, None]
132
+ # read_enabled is an inference ablation, not a change in memory updates.
133
+ result = actions + delta * float(read_enabled)
134
+ new_state = InteractionState(features, valid, last_observed, timestamp, observed_pose)
135
+ diagnostics = dict(visibility_logits=visibility_logits, release_logits=release_logits,
136
+ pending_logits=self.pending_head(features).squeeze(-1),
137
+ observed=observed, released=released, age=age,
138
+ previous_valid=old_valid, valid=valid)
139
+ return result, new_state, diagnostics
models/pim_driving.py ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Single-current-image FastVLM driving with explicit persistent interaction state."""
2
+ from collections import defaultdict
3
+ import torch
4
+ from torch import nn
5
+ from models.driving import DrivingModel
6
+ from models.fastvlm import load_fastvlm
7
+ from models.pim import PersistentInteractionMemory
8
+ from models.pim_losses import interaction_losses
9
+ from models.utils import summarise_losses
10
+ from utils.pim_types import PIMStepOutput, PIMStreamBatch
11
+
12
+
13
+ class PIMDrivingModel(DrivingModel):
14
+ def __init__(self, fastvlm=None, pim=None, vision_model=None, language_model=None, **kwargs):
15
+ if (vision_model is None) != (language_model is None):
16
+ raise ValueError('Provide both injected vision/language adapters, or neither')
17
+ if vision_model is None:
18
+ if fastvlm is None:
19
+ raise ValueError('FastVLM configuration is required')
20
+ vision_model, language_model = load_fastvlm(**dict(fastvlm))
21
+ super().__init__(vision_model=vision_model, language_model=language_model, **kwargs)
22
+ self.pim_cfg = dict(pim or {})
23
+ self.pim_enabled = bool(self.pim_cfg.get('enabled', True))
24
+ self.pim_read_enabled = True
25
+ self.pim = None
26
+ if self.pim_enabled:
27
+ self.pim = PersistentInteractionMemory(
28
+ language_model.hidden_size,
29
+ slots=int(self.pim_cfg.get('slots', 8)),
30
+ memory_dim=int(self.pim_cfg.get('memory_dim', 256)),
31
+ heads=int(self.pim_cfg.get('heads', 4)),
32
+ observation_threshold=float(self.pim_cfg.get('observation_threshold', .5)),
33
+ release_threshold=float(self.pim_cfg.get('release_threshold', .9)))
34
+ if self.use_world_loss:
35
+ raise ValueError('PIM first release does not combine world-latent supervision')
36
+
37
+ def forward_step(self, driving_input, timestamp, ego_pose, state=None, reset=None):
38
+ images = driving_input.camera_images
39
+ if images.ndim == 6 and tuple(images.shape[1:3]) != (1, 1):
40
+ raise ValueError('PIM receives one current image; do not pass historical frames')
41
+ prefix, prefix_mask, _ = self.get_fixed_input_embeds(driving_input)
42
+ if self.use_deepstack:
43
+ raise ValueError('PIMDrivingModel expects FastVLM, not the Qwen3-VL video tower')
44
+ adaptor = self.adaptors(driving_input)['inputs']
45
+ b, prefix_length = prefix.shape[:2]
46
+ parts = [prefix]
47
+ n_obs = 0
48
+ if self.pim is not None:
49
+ observation_queries = self.pim.observation_queries(b).to(prefix.dtype)
50
+ n_obs = observation_queries.shape[1]
51
+ parts.append(observation_queries)
52
+ parts.append(adaptor.to(prefix.dtype))
53
+ embeddings = torch.cat(parts, 1)
54
+ mask = torch.cat((prefix_mask, torch.ones(
55
+ b, n_obs + adaptor.shape[1], device=prefix.device, dtype=prefix_mask.dtype)), 1)
56
+ embeddings = embeddings.to(next(self.language_model.parameters()).dtype)
57
+ # One LM call; observation queries precede action queries. No ground-truth
58
+ # answer text, future waypoint or event target is in this sequence.
59
+ outputs = self.language_model(embeddings, attention_mask=mask)
60
+ actions = outputs[:, prefix_length + n_obs:]
61
+ diagnostics = {}
62
+ if self.pim is not None:
63
+ observations = outputs[:, prefix_length:prefix_length + n_obs]
64
+ actions, state, diagnostics = self.pim(
65
+ observations.to(self.pim.observation_projection.weight.dtype),
66
+ actions.to(self.pim.action_projection.weight.dtype), timestamp,
67
+ state=state, reset=reset, ego_pose=ego_pose,
68
+ read_enabled=self.pim_read_enabled)
69
+ predictions = self.adaptors.driving.get_predictions(actions)
70
+ return PIMStepOutput(predictions['speed_wps'], predictions['route'], state,
71
+ diagnostics, actions, outputs[:, :prefix_length], prefix_mask)
72
+
73
+ def forward(self, driving_input, prompt_ids=None, return_context=False):
74
+ if self.pim_enabled:
75
+ raise RuntimeError('Use forward_step(input,timestamp,ego_pose,state) for PIM; '
76
+ 'implicit state would leak across streams')
77
+ return super().forward(driving_input, prompt_ids, return_context)
78
+
79
+ def forward_loss(self, example, per_sample=False):
80
+ if not isinstance(example, PIMStreamBatch):
81
+ if self.pim_enabled:
82
+ raise TypeError('PIM training requires PIMStreamBatch from PIMDataModule')
83
+ return super().forward_loss(example, per_sample)
84
+ t_steps = len(example.frames)
85
+ if t_steps == 0:
86
+ raise ValueError('Empty temporal stream')
87
+ burn_in = int(self.pim_cfg.get('burn_in', 0)) if self.pim_enabled else 0
88
+ tbptt = int(self.pim_cfg.get('tbptt_steps', 4))
89
+ if burn_in >= t_steps or tbptt < 1:
90
+ raise ValueError('burn_in must be smaller than stream length; tbptt_steps >= 1')
91
+ state = None # New sampled stream; never inherit a different minibatch.
92
+ collected = defaultdict(list)
93
+ predictions = {}
94
+ for t, frame in enumerate(example.frames):
95
+ if state is not None and t % tbptt == 0:
96
+ state = state.detach()
97
+ output = self.forward_step(frame.driving_input, example.timestamps[:, t],
98
+ example.ego_poses[:, t], state)
99
+ state = output.state
100
+ adaptor_dict = self.adaptors(frame)
101
+ losses = self.adaptors.compute_loss(output.action_features, adaptor_dict, frame)
102
+ predictions = {k: v for k, v in losses.items() if not k.endswith('loss')}
103
+ if t >= burn_in:
104
+ for name, pair in losses.items():
105
+ if name.endswith('loss'):
106
+ collected[name].append(pair)
107
+ if self.use_consequence_loss:
108
+ extra = self.compute_consequence_losses(
109
+ output.scene_tokens, output.scene_mask, output.route,
110
+ output.speed_wps, frame.driving_label)
111
+ for name, pair in extra.items():
112
+ collected[name].append(pair)
113
+ if self.pim_enabled:
114
+ targets = example.labels[t]
115
+ if targets is None and self.pim_cfg.get('require_labels', True):
116
+ raise ValueError('PIM lifecycle labels missing; see docs/PIM.md')
117
+ for name, pair in interaction_losses(
118
+ output.diagnostics, targets,
119
+ float(self.pim_cfg.get('event_loss_weight', .2))).items():
120
+ collected[name].append(pair)
121
+ merged = {name: (torch.cat([p[0].reshape(-1) for p in pairs]),
122
+ torch.cat([p[1].reshape(-1) for p in pairs]))
123
+ for name, pairs in collected.items()}
124
+ return (merged, predictions) if per_sample else summarise_losses(merged)
125
+
126
+ def _stream_step(self, batch, mode):
127
+ output = self.forward_loss(batch)
128
+ batch_size = (batch.timestamps.shape[0] if isinstance(batch, PIMStreamBatch)
129
+ else batch.driving_input.vehicle_speed.shape[0])
130
+ for name, value in output.loss_averages.items():
131
+ count = output.loss_counts[name].sum().detach().to(value.dtype)
132
+ totals = torch.stack((value.detach() * count, count))
133
+ # All ranks must make the same logging decision for sparse labels.
134
+ if torch.distributed.is_available() and torch.distributed.is_initialized():
135
+ torch.distributed.all_reduce(totals)
136
+ global_count = int(totals[1].item())
137
+ if global_count:
138
+ self.log(f'{mode}_losses/{name}', totals[0] / totals[1],
139
+ batch_size=global_count, on_step=mode == 'train',
140
+ on_epoch=True, sync_dist=False)
141
+ self.log(f'{mode}/loss', output.loss, batch_size=batch_size,
142
+ on_step=mode == 'train', on_epoch=True, prog_bar=True)
143
+ return output.loss
144
+
145
+ def training_step(self, batch, batch_idx=0):
146
+ return self._stream_step(batch, 'train')
147
+
148
+ def validation_step(self, batch, batch_idx=0):
149
+ return self._stream_step(batch, 'val')
150
+
151
+ def predict_step(self, batch, batch_idx=0):
152
+ output = self.forward_loss(batch)
153
+ return {k: v.detach().cpu() for k, v in output.loss_averages.items()}
154
+
155
+ def configure_optimizers(self):
156
+ # Explicit groups cover new query, GRU and projection parameters and avoid
157
+ # assumptions in the legacy parameter-name whitelist.
158
+ groups = defaultdict(list)
159
+ for name, parameter in self.named_parameters():
160
+ if not parameter.requires_grad:
161
+ continue
162
+ lr = self.lr
163
+ if name.startswith('vision_model.'):
164
+ lr = self.vision_lr if self.vision_lr is not None else self.lr
165
+ elif name.startswith('language_model.') and self.lm_lr is not None:
166
+ lr = self.lm_lr
167
+ decay = self.weight_decay if parameter.ndim > 1 and 'query_embeds' not in name else 0.
168
+ groups[(lr, decay)].append(parameter)
169
+ optimizer = torch.optim.AdamW([
170
+ {'params': params, 'lr': lr, 'weight_decay': decay}
171
+ for (lr, decay), params in groups.items()], betas=self.betas)
172
+ steps = self.trainer.estimated_stepping_batches
173
+ scheduler = torch.optim.lr_scheduler.LambdaLR(
174
+ optimizer, lambda s: min(1., (s + 1) / max(1., self.pct_start * steps)))
175
+ return {'optimizer': optimizer, 'lr_scheduler': {
176
+ 'scheduler': scheduler, 'interval': 'step', 'frequency': 1}}
models/pim_losses.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Masked semantic lifecycle supervision. Targets NEVER condition policy forward."""
2
+ import torch
3
+ import torch.nn.functional as F
4
+
5
+
6
+ def _bce(logits, target, valid, weight):
7
+ target = target.to(logits.device, logits.dtype)
8
+ valid = valid.to(logits.device).bool()
9
+ # Invalid/unknown targets are removed before BCE (also safe for NaN placeholders).
10
+ clean = torch.where(valid, target, torch.zeros_like(target))
11
+ losses = F.binary_cross_entropy_with_logits(logits.float(), clean.float(), reduction='none')
12
+ return (torch.where(valid, losses, torch.zeros_like(losses)).sum(-1) * weight,
13
+ valid.sum(-1))
14
+
15
+
16
+ def interaction_losses(diagnostics, targets, weight=0.2):
17
+ if targets is None:
18
+ return {}
19
+ losses = {'pim_observation_loss': _bce(
20
+ diagnostics['visibility_logits'], targets['observed'],
21
+ targets['observed_valid'], weight)}
22
+ # Only states already represented in memory can be supervised for release.
23
+ # Unknown is not "resolved"; release_valid must mark actual evidence labels.
24
+ old = diagnostics['previous_valid']
25
+ losses['pim_release_loss'] = _bce(
26
+ diagnostics['release_logits'], targets['resolved'],
27
+ targets['resolved_valid'].to(old.device).bool() & old, weight)
28
+ represented = diagnostics['valid']
29
+ losses['pim_pending_loss'] = _bce(
30
+ diagnostics['pending_logits'], targets['pending'],
31
+ targets['pending_valid'].to(represented.device).bool() & represented, weight)
32
+ return losses
models/plan_consequence.py ADDED
@@ -0,0 +1,519 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Small training-only, plan-conditioned consequence model.
2
+
3
+ Waypoint tokens attend to LM vision tokens (not a pooled scene vector) and
4
+ score an explicit metric plan. Privileged future boxes supervise clearance
5
+ and a relative avoidance hinge; they are never a model output.
6
+ """
7
+
8
+ import math
9
+ from typing import NamedTuple, Optional, Sequence, Tuple
10
+
11
+ import torch
12
+ import torch.nn.functional as F
13
+ from torch import Tensor, nn
14
+
15
+
16
+ class ConsequenceOutput(NamedTuple):
17
+ clearance: Tensor # [B, 10], signed metres (negative means overlap)
18
+
19
+
20
+ class PooledConsequenceOutput(NamedTuple):
21
+ risk_logits: Tensor # [B, 10]
22
+ clearance: Tensor # [B, 10], signed metres (negative means overlap)
23
+
24
+
25
+ class PooledPlanConsequenceHead(nn.Module):
26
+ """ConsDrive v2 head: fuse a pooled scene vector with explicit plans.
27
+
28
+ This is the exact architecture behind the v2 checkpoint whose speed
29
+ gating reached 91.1/91.33 DS on Bench2Drive: BCE-supervised risk logits
30
+ plus a clearance regression, both per waypoint. Kept alongside the
31
+ cross-attention head so v4 checkpoints stay loadable.
32
+ """
33
+
34
+ def __init__(
35
+ self,
36
+ scene_dim: int,
37
+ hidden_dim: int = 256,
38
+ plan_dim: int = 128,
39
+ horizon: int = 10,
40
+ route_points: int = 20,
41
+ dropout: float = 0.1,
42
+ ):
43
+ super().__init__()
44
+ self.horizon = int(horizon)
45
+ self.route_points = int(route_points)
46
+
47
+ self.scene_encoder = nn.Sequential(
48
+ nn.LayerNorm(scene_dim),
49
+ nn.Linear(scene_dim, hidden_dim),
50
+ nn.SiLU(),
51
+ )
52
+ self.route_encoder = nn.Sequential(
53
+ nn.Linear(4, plan_dim),
54
+ nn.SiLU(),
55
+ nn.Linear(plan_dim, plan_dim),
56
+ )
57
+ # speed xy, speed delta xy, and route point xy at the same progress
58
+ self.step_encoder = nn.Sequential(
59
+ nn.Linear(6, plan_dim),
60
+ nn.SiLU(),
61
+ nn.Linear(plan_dim, plan_dim),
62
+ )
63
+ self.fusion = nn.Sequential(
64
+ nn.LayerNorm(hidden_dim + 2 * plan_dim),
65
+ nn.Linear(hidden_dim + 2 * plan_dim, hidden_dim),
66
+ nn.SiLU(),
67
+ nn.Dropout(dropout),
68
+ nn.Linear(hidden_dim, hidden_dim),
69
+ nn.SiLU(),
70
+ )
71
+ self.risk_head = nn.Linear(hidden_dim, 1)
72
+ self.clearance_head = nn.Linear(hidden_dim, 1)
73
+
74
+ def forward(
75
+ self,
76
+ scene_feature: Tensor,
77
+ route: Tensor,
78
+ speed_trajectory: Tensor,
79
+ ) -> PooledConsequenceOutput:
80
+ if scene_feature.ndim != 2:
81
+ raise ValueError("scene_feature must have shape [B,C]")
82
+ if route.shape != (scene_feature.size(0), self.route_points, 2):
83
+ raise ValueError(f"route must have shape [B,{self.route_points},2]")
84
+ if speed_trajectory.shape != (scene_feature.size(0), self.horizon, 2):
85
+ raise ValueError(f"speed_trajectory must have shape [B,{self.horizon},2]")
86
+ dtype = self.scene_encoder[1].weight.dtype
87
+ scene_feature = scene_feature.to(dtype=dtype)
88
+ route = route.to(dtype=dtype)
89
+ speed_trajectory = speed_trajectory.to(dtype=dtype)
90
+
91
+ route_delta = torch.diff(
92
+ route, dim=1, prepend=torch.zeros_like(route[:, :1])
93
+ )
94
+ route_tokens = self.route_encoder(torch.cat((route, route_delta), dim=-1))
95
+ route_summary = route_tokens.mean(dim=1)
96
+
97
+ route_indices = torch.linspace(
98
+ 0,
99
+ route.size(1) - 1,
100
+ speed_trajectory.size(1),
101
+ device=route.device,
102
+ ).round().long()
103
+ aligned_route = route.index_select(1, route_indices)
104
+ speed_delta = torch.diff(
105
+ speed_trajectory,
106
+ dim=1,
107
+ prepend=torch.zeros_like(speed_trajectory[:, :1]),
108
+ )
109
+ step_tokens = self.step_encoder(
110
+ torch.cat((speed_trajectory, speed_delta, aligned_route), dim=-1)
111
+ )
112
+
113
+ scene = self.scene_encoder(scene_feature)
114
+ context = torch.cat(
115
+ (
116
+ scene[:, None].expand(-1, self.horizon, -1),
117
+ route_summary[:, None].expand(-1, self.horizon, -1),
118
+ step_tokens,
119
+ ),
120
+ dim=-1,
121
+ )
122
+ fused = self.fusion(context)
123
+ return PooledConsequenceOutput(
124
+ risk_logits=self.risk_head(fused).squeeze(-1),
125
+ clearance=self.clearance_head(fused).squeeze(-1),
126
+ )
127
+
128
+
129
+ class PlanConditionedConsequenceHead(nn.Module):
130
+ """Cross-attend waypoint queries to vision tokens, then score the plan.
131
+
132
+ Default output is clearance only (ConsDrive v4). With
133
+ ``with_risk_head=True`` (ConsDrive v6) an additional per-waypoint risk
134
+ logit is produced so the head can train with the v2 BCE + ranking
135
+ losses; the flag is off by default so v4 checkpoints keep loading.
136
+ """
137
+
138
+ def __init__(
139
+ self,
140
+ scene_dim: int,
141
+ hidden_dim: int = 256,
142
+ plan_dim: int = 128,
143
+ horizon: int = 10,
144
+ route_points: int = 20,
145
+ dropout: float = 0.1,
146
+ attn_heads: int = 4,
147
+ with_risk_head: bool = False,
148
+ ):
149
+ super().__init__()
150
+ self.horizon = int(horizon)
151
+ self.route_points = int(route_points)
152
+ heads = int(attn_heads)
153
+ if hidden_dim % heads != 0:
154
+ heads = 1
155
+ self.attn_heads = heads
156
+
157
+ self.vision_norm = nn.LayerNorm(scene_dim)
158
+ self.kv_proj = nn.Linear(scene_dim, hidden_dim)
159
+ self.route_encoder = nn.Sequential(
160
+ nn.Linear(4, plan_dim),
161
+ nn.SiLU(),
162
+ nn.Linear(plan_dim, plan_dim),
163
+ )
164
+ # speed xy, speed delta xy, and route point xy at the same progress
165
+ self.step_encoder = nn.Sequential(
166
+ nn.Linear(6, plan_dim),
167
+ nn.SiLU(),
168
+ nn.Linear(plan_dim, plan_dim),
169
+ )
170
+ self.query_proj = nn.Linear(2 * plan_dim, hidden_dim)
171
+ self.cross_attn = nn.MultiheadAttention(
172
+ hidden_dim, heads, dropout=dropout, batch_first=True
173
+ )
174
+ self.fusion = nn.Sequential(
175
+ nn.LayerNorm(hidden_dim + 2 * plan_dim),
176
+ nn.Linear(hidden_dim + 2 * plan_dim, hidden_dim),
177
+ nn.SiLU(),
178
+ nn.Dropout(dropout),
179
+ nn.Linear(hidden_dim, hidden_dim),
180
+ nn.SiLU(),
181
+ )
182
+ self.clearance_head = nn.Linear(hidden_dim, 1)
183
+ self.with_risk_head = bool(with_risk_head)
184
+ if self.with_risk_head:
185
+ self.risk_head = nn.Linear(hidden_dim, 1)
186
+
187
+ def forward(
188
+ self,
189
+ vision_tokens: Tensor,
190
+ vision_mask: Tensor,
191
+ route: Tensor,
192
+ speed_trajectory: Tensor,
193
+ ):
194
+ _check_plan_shapes(
195
+ vision_tokens, route, speed_trajectory, self.route_points, self.horizon
196
+ )
197
+ dtype = self.kv_proj.weight.dtype
198
+ vision_tokens = vision_tokens.to(dtype=dtype)
199
+ route = route.to(dtype=dtype)
200
+ speed_trajectory = speed_trajectory.to(dtype=dtype)
201
+
202
+ route_delta = torch.diff(
203
+ route, dim=1, prepend=torch.zeros_like(route[:, :1])
204
+ )
205
+ route_tokens = self.route_encoder(torch.cat((route, route_delta), dim=-1))
206
+ route_summary = route_tokens.mean(dim=1)
207
+
208
+ route_indices = torch.linspace(
209
+ 0,
210
+ route.size(1) - 1,
211
+ speed_trajectory.size(1),
212
+ device=route.device,
213
+ ).round().long()
214
+ aligned_route = route.index_select(1, route_indices)
215
+ speed_delta = torch.diff(
216
+ speed_trajectory,
217
+ dim=1,
218
+ prepend=torch.zeros_like(speed_trajectory[:, :1]),
219
+ )
220
+ step_tokens = self.step_encoder(
221
+ torch.cat((speed_trajectory, speed_delta, aligned_route), dim=-1)
222
+ )
223
+ query = self.query_proj(
224
+ torch.cat(
225
+ (
226
+ route_summary[:, None].expand(-1, self.horizon, -1),
227
+ step_tokens,
228
+ ),
229
+ dim=-1,
230
+ )
231
+ )
232
+ kv = self.kv_proj(self.vision_norm(vision_tokens))
233
+ padding = ~vision_mask.to(device=vision_tokens.device, dtype=torch.bool)
234
+ if padding.size(1) != kv.size(1):
235
+ raise ValueError(
236
+ f"vision_mask length {padding.size(1)} != vision tokens {kv.size(1)}"
237
+ )
238
+ all_pad = padding.all(dim=1)
239
+ if bool(all_pad.any()):
240
+ padding = padding.clone()
241
+ padding[all_pad, 0] = False
242
+ attn_out, _ = self.cross_attn(
243
+ query, kv, kv, key_padding_mask=padding, need_weights=False
244
+ )
245
+ fused = self.fusion(
246
+ torch.cat(
247
+ (
248
+ attn_out,
249
+ route_summary[:, None].expand(-1, self.horizon, -1),
250
+ step_tokens,
251
+ ),
252
+ dim=-1,
253
+ )
254
+ )
255
+ if self.with_risk_head:
256
+ return PooledConsequenceOutput(
257
+ risk_logits=self.risk_head(fused).squeeze(-1),
258
+ clearance=self.clearance_head(fused).squeeze(-1),
259
+ )
260
+ return ConsequenceOutput(clearance=self.clearance_head(fused).squeeze(-1))
261
+
262
+
263
+ def trajectory_geometry_targets(
264
+ trajectory: Tensor,
265
+ obstacles: Tensor,
266
+ obstacle_valid: Tensor,
267
+ step_valid: Tensor,
268
+ ego_radius: float = 0.9,
269
+ max_clearance: float = 20.0,
270
+ ) -> Tuple[Tensor, Tensor, Tensor]:
271
+ """Compute point-to-oriented-box clearance for a candidate trajectory.
272
+
273
+ Args:
274
+ trajectory: Candidate ego centres in the current ego frame, [B,H,2].
275
+ obstacles: Future actor boxes in that same frame, [B,H,M,5], stored as
276
+ centre x/y, half extent x/y, and yaw.
277
+ obstacle_valid: Actor padding mask [B,H,M].
278
+ step_valid: True only when that future box file was reliably loaded
279
+ [B,H]. A loaded frame with no actors is valid and has max clearance.
280
+ """
281
+ if obstacles.ndim != 4 or obstacles.size(-1) != 5:
282
+ raise ValueError("obstacles must have shape [B,H,M,5]")
283
+ if trajectory.shape[:2] != obstacles.shape[:2]:
284
+ raise ValueError("trajectory and obstacle horizons must match")
285
+
286
+ boxes = obstacles.to(device=trajectory.device, dtype=trajectory.dtype)
287
+ actor_mask = obstacle_valid.to(device=trajectory.device, dtype=torch.bool)
288
+ valid = step_valid.to(device=trajectory.device, dtype=torch.bool)
289
+
290
+ delta = trajectory[:, :, None, :] - boxes[..., :2]
291
+ yaw = boxes[..., 4]
292
+ cos_yaw, sin_yaw = torch.cos(yaw), torch.sin(yaw)
293
+ local_x = cos_yaw * delta[..., 0] + sin_yaw * delta[..., 1]
294
+ local_y = -sin_yaw * delta[..., 0] + cos_yaw * delta[..., 1]
295
+ local = torch.stack((local_x, local_y), dim=-1)
296
+
297
+ q = local.abs() - boxes[..., 2:4].clamp_min(0.0)
298
+ outside = torch.linalg.vector_norm(q.clamp_min(0.0), dim=-1)
299
+ inside = torch.minimum(q.amax(dim=-1), torch.zeros_like(outside))
300
+ signed_clearance = outside + inside - float(ego_radius)
301
+ signed_clearance = signed_clearance.masked_fill(~actor_mask, float("inf"))
302
+
303
+ has_actor = actor_mask.any(dim=-1)
304
+ clearance = signed_clearance.amin(dim=-1)
305
+ clearance = torch.where(
306
+ has_actor,
307
+ clearance.clamp(min=-float(max_clearance), max=float(max_clearance)),
308
+ torch.full_like(clearance, float(max_clearance)),
309
+ )
310
+ risk = (clearance <= 0.0).to(dtype=trajectory.dtype)
311
+ return risk, clearance, valid
312
+
313
+
314
+ def visible_obstacle_mask(
315
+ obstacles: Tensor,
316
+ obstacle_valid: Tensor,
317
+ max_range: float = 40.0,
318
+ min_x: float = 0.0,
319
+ ) -> Tensor:
320
+ """Keep actors ahead of ego and inside a distance cap (visibility proxy)."""
321
+ xy = obstacles[..., :2]
322
+ dist = torch.linalg.vector_norm(xy, dim=-1)
323
+ ahead = xy[..., 0] >= float(min_x)
324
+ near = dist <= float(max_range)
325
+ return obstacle_valid.to(dtype=torch.bool) & ahead & near
326
+
327
+
328
+ def relative_min_clearance_hinge(
329
+ pred_clearance: Tensor,
330
+ gt_clearance: Tensor,
331
+ pred_valid: Tensor,
332
+ gt_valid: Tensor,
333
+ ) -> Tuple[Tensor, Tensor]:
334
+ """Penalise a predicted plan that is worse than the expert's worst gap."""
335
+ pred_min, pred_has = _masked_min_clearance(pred_clearance, pred_valid)
336
+ gt_min, gt_has = _masked_min_clearance(gt_clearance, gt_valid)
337
+ valid = pred_has & gt_has
338
+ hinge = F.relu(gt_min - pred_min)
339
+ values = hinge * valid.to(dtype=hinge.dtype)
340
+ counts = valid.to(dtype=torch.long)
341
+ return values, counts
342
+
343
+
344
+ def _masked_min_clearance(clearance: Tensor, valid: Tensor) -> Tuple[Tensor, Tensor]:
345
+ valid = valid.to(device=clearance.device, dtype=torch.bool)
346
+ fill = torch.finfo(clearance.dtype).max
347
+ filled = clearance.masked_fill(~valid, fill)
348
+ min_c = filled.min(dim=-1).values
349
+ has = valid.any(dim=-1)
350
+ min_c = torch.where(has, min_c, torch.zeros_like(min_c))
351
+ return min_c, has
352
+
353
+
354
+ def expand_scene_for_plans(
355
+ vision_tokens: Tensor, vision_mask: Tensor, num_plans: int
356
+ ) -> Tuple[Tensor, Tensor]:
357
+ """Repeat a scene along a candidate-plan axis: [B,N,C] -> [B*P,N,C]."""
358
+ batch, tokens, channels = vision_tokens.shape
359
+ expanded_tokens = (
360
+ vision_tokens[:, None]
361
+ .expand(batch, num_plans, tokens, channels)
362
+ .reshape(batch * num_plans, tokens, channels)
363
+ )
364
+ expanded_mask = (
365
+ vision_mask[:, None]
366
+ .expand(batch, num_plans, tokens)
367
+ .reshape(batch * num_plans, tokens)
368
+ )
369
+ return expanded_tokens, expanded_mask
370
+
371
+
372
+ def time_advanced_trajectory(speed_trajectory: Tensor, shift_steps: int) -> Tensor:
373
+ """Traverse the same path but arrive ``shift_steps`` waypoints earlier.
374
+
375
+ Waypoints are 0.2 s apart, so a shift of k puts the ego where it would
376
+ otherwise be k*0.2 s later - the classic "enter the conflict zone too
377
+ early" junction mistake. Beyond the original horizon the trajectory is
378
+ extrapolated with the final segment direction.
379
+ """
380
+ horizon = speed_trajectory.size(1)
381
+ shift = int(shift_steps)
382
+ if shift <= 0:
383
+ return speed_trajectory
384
+ last_delta = speed_trajectory[:, -1:] - speed_trajectory[:, -2:-1]
385
+ indices = torch.arange(horizon, device=speed_trajectory.device) + shift
386
+ overshoot = (indices - (horizon - 1)).clamp_min(0)
387
+ indices = indices.clamp_max(horizon - 1)
388
+ shifted = speed_trajectory.index_select(1, indices)
389
+ return shifted + overshoot.view(1, horizon, 1).to(
390
+ dtype=speed_trajectory.dtype
391
+ ) * last_delta
392
+
393
+
394
+ def make_hard_negative_plans(
395
+ route: Tensor,
396
+ speed_trajectory: Tensor,
397
+ speed_scales: Sequence[float] = (1.35,),
398
+ lateral_offset: float = 1.5,
399
+ time_shifts: Sequence[int] = (),
400
+ ) -> Tuple[Tensor, Tensor]:
401
+ """Create same-scene counterfactual candidates around a base plan.
402
+
403
+ Candidates: one per entry in ``speed_scales`` (same path, faster), left
404
+ and right ``lateral_offset`` shifts, and one per entry in ``time_shifts``
405
+ (same path, entered earlier; see ``time_advanced_trajectory``).
406
+ """
407
+ batch, route_steps, _ = route.shape
408
+ horizon = speed_trajectory.size(1)
409
+ route_ramp = torch.linspace(
410
+ 0.0, 1.0, route_steps, device=route.device, dtype=route.dtype
411
+ ).view(1, route_steps, 1)
412
+ speed_ramp = torch.linspace(
413
+ 0.0, 1.0, horizon, device=route.device, dtype=route.dtype
414
+ ).view(1, horizon, 1)
415
+ lateral = route.new_tensor([0.0, float(lateral_offset)]).view(1, 1, 2)
416
+
417
+ route_list = []
418
+ speed_list = []
419
+ for scale in speed_scales:
420
+ route_list.append(route)
421
+ speed_list.append(speed_trajectory * float(scale))
422
+ route_list.append(route + route_ramp * lateral)
423
+ speed_list.append(speed_trajectory + speed_ramp * lateral)
424
+ route_list.append(route - route_ramp * lateral)
425
+ speed_list.append(speed_trajectory - speed_ramp * lateral)
426
+ for shift in time_shifts:
427
+ route_list.append(route)
428
+ speed_list.append(time_advanced_trajectory(speed_trajectory, shift))
429
+
430
+ routes = torch.stack(route_list, dim=1)
431
+ speeds = torch.stack(speed_list, dim=1)
432
+ candidates = len(speed_scales) + 2 + len(time_shifts)
433
+ assert routes.shape == (batch, candidates, route_steps, 2)
434
+ return routes, speeds
435
+
436
+
437
+ def masked_per_sample_mean(
438
+ values: Tensor, mask: Tensor
439
+ ) -> Tuple[Tensor, Tensor]:
440
+ """Reduce waypoint/candidate values while preserving summarise_losses API."""
441
+ mask = mask.to(device=values.device, dtype=torch.bool)
442
+ reduce_dims = tuple(range(1, values.ndim))
443
+ counts = mask.sum(dim=reduce_dims)
444
+ totals = (values * mask.to(dtype=values.dtype)).sum(dim=reduce_dims)
445
+ means = totals / counts.clamp_min(1).to(dtype=values.dtype)
446
+ sample_valid = (counts > 0).to(dtype=torch.long)
447
+ return means, sample_valid
448
+
449
+
450
+ def pairwise_ranking_loss(
451
+ safe_logits: Tensor,
452
+ unsafe_logits: Tensor,
453
+ valid: Tensor,
454
+ margin: float,
455
+ ) -> Tuple[Tensor, Tensor]:
456
+ """Rank aggregate risk of proven-unsafe candidates above a safe plan."""
457
+ safe_score = torch.logsumexp(safe_logits.float(), dim=-1) - math.log(
458
+ safe_logits.size(-1)
459
+ )
460
+ unsafe_score = torch.logsumexp(unsafe_logits.float(), dim=-1) - math.log(
461
+ unsafe_logits.size(-1)
462
+ )
463
+ losses = F.relu(float(margin) + safe_score[:, None] - unsafe_score)
464
+ return masked_per_sample_mean(losses, valid)
465
+
466
+
467
+ def binary_waypoint_loss(
468
+ logits: Tensor,
469
+ targets: Tensor,
470
+ valid: Tensor,
471
+ pos_weight: Optional[float] = None,
472
+ ) -> Tuple[Tensor, Tensor]:
473
+ weight = None
474
+ if pos_weight is not None and float(pos_weight) != 1.0:
475
+ weight = torch.tensor(
476
+ float(pos_weight), device=logits.device, dtype=torch.float32
477
+ )
478
+ losses = F.binary_cross_entropy_with_logits(
479
+ logits.float(), targets.to(device=logits.device, dtype=torch.float32),
480
+ reduction="none",
481
+ pos_weight=weight,
482
+ )
483
+ return masked_per_sample_mean(losses, valid)
484
+
485
+
486
+ def clearance_waypoint_loss(
487
+ prediction: Tensor,
488
+ targets: Tensor,
489
+ valid: Tensor,
490
+ beta: float = 1.0,
491
+ ) -> Tuple[Tensor, Tensor]:
492
+ losses = F.smooth_l1_loss(
493
+ prediction.float(),
494
+ targets.to(device=prediction.device, dtype=torch.float32),
495
+ beta=float(beta),
496
+ reduction="none",
497
+ )
498
+ return masked_per_sample_mean(losses, valid)
499
+
500
+
501
+ def aggregate_risk_logits(risk_logits: Tensor) -> Tensor:
502
+ return torch.logsumexp(risk_logits.float(), dim=-1) - math.log(
503
+ risk_logits.size(-1)
504
+ )
505
+
506
+
507
+ def _check_plan_shapes(
508
+ vision_tokens: Tensor,
509
+ route: Tensor,
510
+ speed_trajectory: Tensor,
511
+ route_points: int,
512
+ horizon: int,
513
+ ) -> None:
514
+ if vision_tokens.ndim != 3:
515
+ raise ValueError("vision_tokens must have shape [B,N,C]")
516
+ if route.shape != (vision_tokens.size(0), route_points, 2):
517
+ raise ValueError(f"route must have shape [B,{route_points},2]")
518
+ if speed_trajectory.shape != (vision_tokens.size(0), horizon, 2):
519
+ raise ValueError(f"speed_trajectory must have shape [B,{horizon},2]")
models/qwen_utils.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from pathlib import Path
3
+ from typing import Dict, TypeVar
4
+
5
+ import torch
6
+ from accelerate import init_empty_weights
7
+ from safetensors import safe_open
8
+ from torch import nn
9
+
10
+ ModuleT = TypeVar("ModuleT", bound=nn.Module)
11
+
12
+
13
+ def _shard_paths_for_prefix(model_dir: Path, prefix: str) -> list[Path]:
14
+ index_path = model_dir / "model.safetensors.index.json"
15
+ if index_path.exists():
16
+ with open(index_path, encoding="utf-8") as f:
17
+ weight_map = json.load(f)["weight_map"]
18
+
19
+ shard_names = sorted(
20
+ {shard_name for key, shard_name in weight_map.items() if key.startswith(prefix)}
21
+ )
22
+ if not shard_names:
23
+ raise RuntimeError(f"No weights found for prefix {prefix!r} in {index_path}")
24
+ return [model_dir / shard_name for shard_name in shard_names]
25
+
26
+ single_path = model_dir / "model.safetensors"
27
+ if single_path.exists():
28
+ with safe_open(single_path, framework="pt", device="cpu") as shard:
29
+ if any(key.startswith(prefix) for key in shard.keys()):
30
+ return [single_path]
31
+ raise RuntimeError(f"No weights found for prefix {prefix!r} in {single_path}")
32
+
33
+ raise FileNotFoundError(
34
+ f"Missing safetensors weights in {model_dir}: expected "
35
+ f"model.safetensors.index.json or model.safetensors"
36
+ )
37
+
38
+
39
+ def load_prefixed_state_dict(model_path: str, prefix: str) -> Dict[str, torch.Tensor]:
40
+ model_dir = Path(model_path)
41
+ state_dict: Dict[str, torch.Tensor] = {}
42
+ for shard_path in _shard_paths_for_prefix(model_dir, prefix):
43
+ with safe_open(shard_path, framework="pt", device="cpu") as shard:
44
+ for key in shard.keys():
45
+ if key.startswith(prefix):
46
+ state_dict[key[len(prefix) :]] = shard.get_tensor(key)
47
+ return state_dict
48
+
49
+
50
+ def build_empty_module(module_cls, config) -> ModuleT:
51
+ """Build module on meta device without random weight initialization."""
52
+ with init_empty_weights():
53
+ return module_cls._from_config(config)
54
+
55
+
56
+ def load_prefixed_safetensors(
57
+ module: nn.Module,
58
+ model_path: str,
59
+ prefix: str,
60
+ torch_dtype: torch.dtype | None = None,
61
+ ) -> None:
62
+ state_dict = load_prefixed_state_dict(model_path, prefix)
63
+ if torch_dtype is not None:
64
+ state_dict = {key: value.to(torch_dtype) for key, value in state_dict.items()}
65
+
66
+ missing, unexpected = module.load_state_dict(state_dict, strict=False, assign=True)
67
+ if missing or unexpected:
68
+ raise RuntimeError(
69
+ f"Failed loading Qwen weights for prefix {prefix!r}: "
70
+ f"missing={missing[:10]}, unexpected={unexpected[:10]}"
71
+ )
72
+
73
+ # Materialize any parameters that were not present in the checkpoint.
74
+ for name, param in module.named_parameters():
75
+ if param.device.type == "meta":
76
+ raise RuntimeError(f"Parameter {name!r} remained on meta device after loading {prefix!r}")
77
+
78
+ for name, buffer in module.named_buffers():
79
+ if buffer.device.type == "meta":
80
+ raise RuntimeError(f"Buffer {name!r} remained on meta device after loading {prefix!r}")
models/stream_petr.py ADDED
@@ -0,0 +1,611 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Stage 2 (v2): StreamPETR-style monocular 3D detector with object-query memory on the FastVLM vision tower.
2
+
3
+ Image tokens are the FPN stride-8 features of FastViTHD (models/detector.py) with PETR's 3D position
4
+ embedding: every token is lifted along its camera ray to DEPTH_BINS depths, the points are normalised
5
+ to PC_RANGE and encoded by an MLP gated by the token's own features (PETRv2 feature-guided PE). A set of
6
+ learnable 3D reference points becomes object queries; the decoder layers attend to the image tokens and,
7
+ through hybrid self-attention, to a memory queue of the top-K queries of the last MEMORY_FRAMES frames.
8
+ Memory entries are aligned to the current frame with the ego motion and the objects' own velocity and
9
+ re-encoded by motion-aware layer normalisation (StreamPETR); the most recent K of them are propagated
10
+ into the current query set, so a track keeps its query across frames.
11
+
12
+ Every query predicts class scores, the box centre as a sigmoid-space offset from its reference point,
13
+ log half extents, heading (sin, cos) and velocity in the ego frame, and Laplace scales for range and
14
+ velocity, so decoded detections have the fields of models.detector.decode and feed the same tracker.
15
+ Training uses Hungarian set matching with focal + L1 losses on every decoder layer plus denoising
16
+ queries (noised ground-truth boxes with a known assignment).
17
+ """
18
+ import math
19
+
20
+ import numpy as np
21
+ import torch
22
+ import torch.nn.functional as F
23
+ from scipy.optimize import linear_sum_assignment
24
+ from torch import nn
25
+
26
+ from dataloader.detection_data import CAMERA_X, CAMERA_Z, FOCAL, GRID_H, GRID_W, IMAGE_H, IMAGE_W, STRIDE
27
+ from dataloader.detection_labels import (
28
+ OBJ_BANK_VISIBLE, OBJ_CLASS, OBJ_HALF_H, OBJ_HALF_L, OBJ_HALF_W, OBJ_LIDAR_POINTS, OBJ_SPEED, OBJ_X, OBJ_Y,
29
+ OBJ_YAW, OBJ_Z,
30
+ )
31
+ from dataloader.object_bank import NUM_CLASSES
32
+ from models.detector import FASTVIT_STAGE_INDEX, FPN, build_fastvithd
33
+
34
+ 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)
35
+ DEPTH_BINS, DEPTH_MIN, DEPTH_MAX = 64, 1.0, 61.0
36
+ VEL_SCALE = 10.0
37
+ # regression code: dx dy dz (sigmoid-space offsets), log half l w h, sin yaw, cos yaw, vx vy (/VEL_SCALE),
38
+ # log sigma range, log sigma vx, log sigma vy
39
+ CODE_DIM = 13
40
+ BOX_DIM = 10 # target code: x y z, log half l w h, sin, cos, vx, vy
41
+ POSITIVE_RANGE = 50.0 # boxes the detector must find (as det_v1)
42
+ MATCH_RANGE = 55.0 # labelled boxes farther than this are neither matched nor negatives
43
+
44
+
45
+ # ------------------------------------------------------------------------------------------ helpers
46
+ def inverse_sigmoid(x, eps=1e-5):
47
+ x = x.clamp(eps, 1 - eps)
48
+ return torch.log(x / (1 - x))
49
+
50
+
51
+ def normalize_xyz(xyz):
52
+ lo, hi = xyz.new_tensor(PC_RANGE[:3]), xyz.new_tensor(PC_RANGE[3:])
53
+ return (xyz - lo) / (hi - lo)
54
+
55
+
56
+ def denormalize_xyz(n):
57
+ lo, hi = n.new_tensor(PC_RANGE[:3]), n.new_tensor(PC_RANGE[3:])
58
+ return n * (hi - lo) + lo
59
+
60
+
61
+ def sine_embedding(pos, num_feats=128, temperature=10000.0):
62
+ """[..., D] in [0, 1] -> [..., D * num_feats] sine/cosine features."""
63
+ pos = pos.float() * 2 * math.pi
64
+ dim_t = torch.arange(num_feats, dtype=torch.float32, device=pos.device)
65
+ dim_t = temperature ** (2 * torch.div(dim_t, 2, rounding_mode="floor") / num_feats)
66
+ out = []
67
+ for i in range(pos.shape[-1]):
68
+ p = pos[..., i, None] / dim_t
69
+ out.append(torch.stack((p[..., 0::2].sin(), p[..., 1::2].cos()), -1).flatten(-2))
70
+ return torch.cat(out, -1)
71
+
72
+
73
+ def mlp(dims, final_bias=None):
74
+ layers = []
75
+ for i in range(len(dims) - 1):
76
+ layers.append(nn.Linear(dims[i], dims[i + 1]))
77
+ if i < len(dims) - 2:
78
+ layers.append(nn.ReLU(inplace=True))
79
+ if final_bias is not None:
80
+ nn.init.constant_(layers[-1].bias, final_bias)
81
+ return nn.Sequential(*layers)
82
+
83
+
84
+ def camera_frustum_points():
85
+ """Box-frame points [GRID_H * GRID_W, DEPTH_BINS, 3] of the stride-8 cell centres at LID depth bins."""
86
+ u = (torch.arange(GRID_W, dtype=torch.float32) + 0.5) * STRIDE
87
+ v = (torch.arange(GRID_H, dtype=torch.float32) + 0.5) * STRIDE
88
+ i = torch.arange(DEPTH_BINS, dtype=torch.float32) + 0.5
89
+ d = DEPTH_MIN + (DEPTH_MAX - DEPTH_MIN) * i * (i + 1) / (DEPTH_BINS * (DEPTH_BINS + 1))
90
+ vv, uu = torch.meshgrid(v, u, indexing="ij")
91
+ uu, vv, d = uu.reshape(-1, 1), vv.reshape(-1, 1), d[None]
92
+ x = (d + CAMERA_X).expand(uu.shape[0], -1)
93
+ y = (uu - IMAGE_W / 2) * d / FOCAL
94
+ z = -(vv - IMAGE_H / 2) * d / FOCAL + CAMERA_Z
95
+ return torch.stack((x, y, z), -1)
96
+
97
+
98
+ def image_grid_uv():
99
+ """Normalised (u, v) of the stride-8 cell centres [GRID_H * GRID_W, 2]."""
100
+ u = (torch.arange(GRID_W, dtype=torch.float32) + 0.5) / GRID_W
101
+ v = (torch.arange(GRID_H, dtype=torch.float32) + 0.5) / GRID_H
102
+ vv, uu = torch.meshgrid(v, u, indexing="ij")
103
+ return torch.stack((uu.reshape(-1), vv.reshape(-1)), -1)
104
+
105
+
106
+ def ego_from_world(w, pose):
107
+ """World points [..., 2] -> ego frame of pose [..., 3] (x, y, yaw); same convention as ego_motion."""
108
+ c, s = torch.cos(pose[..., 2]), torch.sin(pose[..., 2])
109
+ dx, dy = w[..., 0] - pose[..., 0], w[..., 1] - pose[..., 1]
110
+ return torch.stack((c * dx + s * dy, -s * dx + c * dy), -1)
111
+
112
+
113
+ def world_from_ego(p, pose):
114
+ c, s = torch.cos(pose[..., 2]), torch.sin(pose[..., 2])
115
+ return torch.stack((c * p[..., 0] - s * p[..., 1] + pose[..., 0], s * p[..., 0] + c * p[..., 1] + pose[..., 1]), -1)
116
+
117
+
118
+ def rotate(v, angle):
119
+ c, s = torch.cos(angle), torch.sin(angle)
120
+ return torch.stack((c * v[..., 0] - s * v[..., 1], s * v[..., 0] + c * v[..., 1]), -1)
121
+
122
+
123
+ # ------------------------------------------------------------------------------------------ decoder
124
+ class DecoderLayer(nn.Module):
125
+ def __init__(self, d=256, heads=8, ffn=1024, dropout=0.0):
126
+ super().__init__()
127
+ self.heads = heads
128
+ self.self_attn = nn.MultiheadAttention(d, heads, dropout=dropout, batch_first=True)
129
+ self.cross_attn = nn.MultiheadAttention(d, heads, dropout=dropout, batch_first=True)
130
+ self.ffn = nn.Sequential(nn.Linear(d, ffn), nn.ReLU(inplace=True), nn.Dropout(dropout), nn.Linear(ffn, d))
131
+ self.norm1, self.norm2, self.norm3 = nn.LayerNorm(d), nn.LayerNorm(d), nn.LayerNorm(d)
132
+ self.drop = nn.Dropout(dropout)
133
+
134
+ def forward(self, q, q_pos, mem, mem_pos, attn_mask, img, img_pos):
135
+ """q [B, L, d] queries; mem [B, S_m, d] memory-only keys; attn_mask [B, L, L + S_m] (True = blocked)."""
136
+ k = torch.cat((q + q_pos, mem + mem_pos), 1)
137
+ v = torch.cat((q, mem), 1)
138
+ mask = attn_mask.repeat_interleave(self.heads, 0)
139
+ x = self.self_attn(q + q_pos, k, v, attn_mask=mask, need_weights=False)[0]
140
+ q = self.norm1(q + self.drop(x))
141
+ x = self.cross_attn(q + q_pos, img + img_pos, img, need_weights=False)[0]
142
+ q = self.norm2(q + self.drop(x))
143
+ return self.norm3(q + self.drop(self.ffn(q)))
144
+
145
+
146
+ class StreamPETR(nn.Module):
147
+ def __init__(self, init="pretrained/FastVLM-0.5B", embed=256, num_queries=400, num_propagated=128,
148
+ memory_frames=4, layers=6, dn_groups=3, dn_noise=(1.0, 1.0, 0.3), dn_label_noise=0.25,
149
+ freeze_backbone=False, fpn_channels=128):
150
+ """init: FastVLM checkpoint dir, a driving-model .ckpt, or a train_detector.py .pt (backbone + FPN)."""
151
+ super().__init__()
152
+ from_detector = init.endswith(".pt")
153
+ self.backbone = build_fastvithd("pretrained/FastVLM-0.5B" if from_detector else init)
154
+ self.freeze_backbone = bool(freeze_backbone)
155
+ if self.freeze_backbone:
156
+ self.backbone.requires_grad_(False)
157
+ self.fpn = FPN(fpn_channels)
158
+ if from_detector:
159
+ state = torch.load(init, map_location="cpu", weights_only=False)["model"]
160
+ self.backbone.load_state_dict({k[len("backbone."):]: v for k, v in state.items() if k.startswith("backbone.")})
161
+ self.fpn.load_state_dict({k[len("fpn."):]: v for k, v in state.items() if k.startswith("fpn.")})
162
+ self.embed, self.num_queries, self.num_propagated = embed, num_queries, num_propagated
163
+ self.memory_frames, self.dn_groups = memory_frames, dn_groups
164
+ self.dn_noise, self.dn_label_noise = dn_noise, dn_label_noise
165
+
166
+ self.in_proj = nn.Conv2d(fpn_channels, embed, 1)
167
+ self.register_buffer("pe3d_input", inverse_sigmoid(normalize_xyz(camera_frustum_points())).flatten(1),
168
+ persistent=False)
169
+ self.register_buffer("pe2d_input", sine_embedding(image_grid_uv(), embed // 2), persistent=False)
170
+ self.pe3d = mlp([DEPTH_BINS * 3, embed * 4, embed])
171
+ self.pe2d = mlp([embed, embed, embed])
172
+ self.fpe = mlp([embed, embed, embed])
173
+ self.reference_points = nn.Embedding(num_queries, 3)
174
+ nn.init.uniform_(self.reference_points.weight, 0.0, 1.0)
175
+ self.query_pos = mlp([embed // 2 * 3, embed, embed])
176
+ self.dn_label_enc = nn.Embedding(NUM_CLASSES + 1, embed)
177
+ self.mln = mlp([5, embed, 2 * embed])
178
+ self.mln_norm = nn.LayerNorm(embed, elementwise_affine=False)
179
+ self.layers = nn.ModuleList([DecoderLayer(embed) for _ in range(layers)])
180
+ self.cls_heads = nn.ModuleList([mlp([embed, embed, embed, NUM_CLASSES], final_bias=-math.log(99.0))
181
+ for _ in range(layers)])
182
+ self.reg_heads = nn.ModuleList([mlp([embed, embed, embed, CODE_DIM]) for _ in range(layers)])
183
+ for h in self.reg_heads:
184
+ nn.init.zeros_(h[-1].weight)
185
+ nn.init.zeros_(h[-1].bias)
186
+ self.memory = None
187
+
188
+ # ------------------------------------------------------------------------------ image tokens
189
+ def backbone_features(self, images):
190
+ x = F.interpolate(images.float() / 255.0, size=(IMAGE_H, IMAGE_W), mode="bilinear",
191
+ align_corners=False, antialias=True)
192
+ x = self.backbone.patch_embed(x)
193
+ feats = {}
194
+ for i, block in enumerate(self.backbone.network):
195
+ x = block(x)
196
+ for s, idx in FASTVIT_STAGE_INDEX.items():
197
+ if idx == i:
198
+ feats[s] = x
199
+ if i >= FASTVIT_STAGE_INDEX[64]:
200
+ break
201
+ return feats
202
+
203
+ def image_tokens(self, images):
204
+ if self.freeze_backbone:
205
+ with torch.no_grad():
206
+ feats = self.backbone_features(images)
207
+ else:
208
+ feats = self.backbone_features(images)
209
+ img = self.in_proj(self.fpn(feats)[8]).flatten(2).transpose(1, 2) # [B, N, embed]
210
+ pos = self.pe3d(self.pe3d_input)[None] * torch.sigmoid(self.fpe(img)) + self.pe2d(self.pe2d_input)[None]
211
+ return img, pos
212
+
213
+ # ------------------------------------------------------------------------------ memory
214
+ def reset_memory(self, keep=None):
215
+ """Clear the memory queue: everything (keep None) or the batch elements where keep is False."""
216
+ if keep is None or self.memory is None:
217
+ self.memory = None
218
+ return
219
+ keep = keep.to(self.memory["valid"].device)
220
+ for k, v in self.memory.items():
221
+ self.memory[k] = torch.where(keep.view(-1, *([1] * (v.dim() - 1))), v, torch.zeros_like(v))
222
+
223
+ def _empty_memory(self, b, device):
224
+ n, d = self.memory_frames * self.num_propagated, self.embed
225
+ return dict(embed=torch.zeros(b, n, d, device=device), ref=torch.zeros(b, n, 3, device=device),
226
+ vel=torch.zeros(b, n, 2, device=device), pose=torch.zeros(b, n, 3, device=device),
227
+ time=torch.zeros(b, n, device=device), valid=torch.zeros(b, n, dtype=torch.bool, device=device))
228
+
229
+ def aligned_memory(self, pose, time):
230
+ """Memory entries moved into the current ego frame: (embed, pos, ref_norm, valid)."""
231
+ m = self.memory
232
+ pose_m = m["pose"]
233
+ pose_b = pose[:, None].expand_as(pose_m)
234
+ dt = (time[:, None] - m["time"]).clamp(min=0.0)
235
+ moved = m["ref"][..., :2] + m["vel"] * dt[..., None]
236
+ ref_xy = ego_from_world(world_from_ego(moved, pose_m), pose_b)
237
+ ref = torch.cat((ref_xy, m["ref"][..., 2:3]), -1)
238
+ rel_t = ego_from_world(pose_m[..., :2], pose_b)
239
+ dyaw = pose_m[..., 2] - pose[:, None, 2]
240
+ motion = torch.stack((rel_t[..., 0] / 10.0, rel_t[..., 1] / 10.0, torch.cos(dyaw), torch.sin(dyaw), dt), -1)
241
+ gamma, beta = self.mln(motion).chunk(2, -1)
242
+ embed = self.mln_norm(m["embed"]) * (1 + gamma) + beta
243
+ ref_norm = normalize_xyz(ref).clamp(0.0, 1.0)
244
+ pos = self.query_pos(sine_embedding(ref_norm, self.embed // 2))
245
+ return embed, pos, ref_norm, m["valid"]
246
+
247
+ @torch.no_grad()
248
+ def update_memory(self, embed, center, vel, score, valid, pose, time):
249
+ """Push the top-K current queries (by score) to the front of the memory queue."""
250
+ k = self.num_propagated
251
+ top = score.masked_fill(~valid, -1.0).topk(k, dim=1).indices
252
+ g = lambda x: x.gather(1, top.unsqueeze(-1).expand(-1, -1, x.shape[-1])) # noqa: E731
253
+ new = dict(embed=g(embed).float(), ref=g(center).float(), vel=g(vel).float(),
254
+ pose=pose[:, None].expand(-1, k, -1).float(), time=time[:, None].expand(-1, k).float(),
255
+ valid=valid.gather(1, top))
256
+ for key in self.memory:
257
+ self.memory[key] = torch.cat((new[key], self.memory[key][:, :-k]), 1)
258
+
259
+ # ------------------------------------------------------------------------------ denoising queries
260
+ def make_dn(self, gt_rows, gt_count, device):
261
+ """Noised copies of the positive ground-truth boxes: (embed, ref_norm, valid, group, gt_index).
262
+
263
+ At least one (invalid, padded) query is always produced so the module graph is the same on
264
+ every rank."""
265
+ b = gt_rows.shape[0]
266
+ pos = positive_mask(gt_rows, gt_count)
267
+ n_max = int(pos.sum(1).max().item())
268
+ n_dn = max(self.dn_groups * n_max, 1)
269
+ ref = torch.full((b, n_dn, 3), 0.5, device=device)
270
+ label = torch.full((b, n_dn), NUM_CLASSES, dtype=torch.long, device=device)
271
+ valid = torch.zeros(b, n_dn, dtype=torch.bool, device=device)
272
+ group = torch.zeros(b, n_dn, dtype=torch.long, device=device)
273
+ gt_index = torch.zeros(b, n_dn, dtype=torch.long, device=device)
274
+ if n_max:
275
+ noise = gt_rows.new_tensor(self.dn_noise)
276
+ for i in range(b):
277
+ idx = pos[i].nonzero()[:, 0]
278
+ n = len(idx)
279
+ if n == 0:
280
+ continue
281
+ rows = gt_rows[i, idx]
282
+ for g in range(self.dn_groups):
283
+ sl = slice(g * n_max, g * n_max + n)
284
+ center = rows[:, [OBJ_X, OBJ_Y, OBJ_Z]] + (torch.rand(n, 3, device=device) * 2 - 1) * noise
285
+ lab = rows[:, OBJ_CLASS].long()
286
+ flip = torch.rand(n, device=device) < self.dn_label_noise
287
+ lab = torch.where(flip, torch.randint(0, NUM_CLASSES, (n,), device=device), lab)
288
+ ref[i, sl] = normalize_xyz(center).clamp(0.01, 0.99)
289
+ label[i, sl] = lab
290
+ valid[i, sl], group[i, sl], gt_index[i, sl] = True, g, idx
291
+ return self.dn_label_enc(label), ref, valid, group, gt_index
292
+
293
+ # ------------------------------------------------------------------------------ forward
294
+ def forward(self, images, pose, time, gt_rows=None, gt_count=None):
295
+ """images uint8 [B, 3, H, W]; pose [B, 3] world (x, y, yaw); time [B] seconds; optional labels
296
+ [B, K, OBJ_DIM] / [B] switch denoising queries on.
297
+
298
+ Call reset_memory() at the start of a sequence. Returns per-layer predictions for the query set
299
+ [dn | current | propagated] plus the index layout; the memory queue is updated as a side effect."""
300
+ b, device = images.shape[0], images.device
301
+ img, img_pos = self.image_tokens(images)
302
+ img_pos = img_pos.to(img.dtype)
303
+ if self.memory is None or self.memory["embed"].shape[0] != b:
304
+ self.memory = self._empty_memory(b, device)
305
+ pose, time = pose.float(), time.float()
306
+ mem_embed, mem_pos, mem_ref, mem_valid = self.aligned_memory(pose, time)
307
+ k = self.num_propagated
308
+ prop_embed, prop_pos, prop_ref, prop_valid = mem_embed[:, :k], mem_pos[:, :k], mem_ref[:, :k], mem_valid[:, :k]
309
+ rest_embed, rest_pos, rest_valid = mem_embed[:, k:], mem_pos[:, k:], mem_valid[:, k:]
310
+
311
+ cur_ref = self.reference_points.weight[None].expand(b, -1, -1)
312
+ cur_pos = self.query_pos(sine_embedding(cur_ref, self.embed // 2))
313
+ cur_embed = torch.zeros_like(cur_pos)
314
+
315
+ if gt_rows is not None:
316
+ dn_embed, dn_ref, dn_valid, dn_group, dn_gt = self.make_dn(gt_rows, gt_count, device)
317
+ dn_pos = self.query_pos(sine_embedding(dn_ref, self.embed // 2))
318
+ q = torch.cat((dn_embed, cur_embed, prop_embed), 1)
319
+ q_pos = torch.cat((dn_pos, cur_pos, prop_pos), 1)
320
+ ref = torch.cat((dn_ref, cur_ref, prop_ref), 1)
321
+ n_dn = dn_embed.shape[1]
322
+ else:
323
+ dn_valid = dn_group = dn_gt = None
324
+ q = torch.cat((cur_embed, prop_embed), 1)
325
+ q_pos = torch.cat((cur_pos, prop_pos), 1)
326
+ ref = torch.cat((cur_ref, prop_ref), 1)
327
+ n_dn = 0
328
+ n_cur, n_rest = self.num_queries, rest_embed.shape[1]
329
+ L = q.shape[1]
330
+ # self-attention keys are [dn | cur | prop | rest memory]; True blocks
331
+ key_valid = torch.cat((torch.ones(b, n_dn + n_cur, dtype=torch.bool, device=device), prop_valid, rest_valid), 1)
332
+ mask = ~key_valid[:, None, :].expand(-1, L, -1).clone()
333
+ if n_dn:
334
+ mask[:, n_dn:, :n_dn] = True # matching queries never see denoising queries
335
+ same = dn_group[:, :, None] == dn_group[:, None, :]
336
+ mask[:, :n_dn, :n_dn] |= ~same | ~dn_valid[:, None, :]
337
+ eye = torch.eye(L, dtype=torch.bool, device=device)[None]
338
+ mask[:, :, :L] &= ~eye # every query attends to itself (no empty rows)
339
+
340
+ ref_logit = inverse_sigmoid(ref.float())
341
+ q, q_pos = q.to(img.dtype), q_pos.to(img.dtype)
342
+ rest_embed, rest_pos = rest_embed.to(img.dtype), rest_pos.to(img.dtype)
343
+ outs = []
344
+ for layer, cls_head, reg_head in zip(self.layers, self.cls_heads, self.reg_heads):
345
+ q = layer(q, q_pos, rest_embed, rest_pos, mask, img, img_pos)
346
+ reg = reg_head(q).float()
347
+ outs.append(dict(cls=cls_head(q).float(), center=denormalize_xyz(torch.sigmoid(ref_logit + reg[..., 0:3])),
348
+ log_size=reg[..., 3:6], sincos=reg[..., 6:8], vel=reg[..., 8:10] * VEL_SCALE,
349
+ log_sigma=reg[..., 10:13]))
350
+ valid = torch.cat((torch.ones(b, n_cur, dtype=torch.bool, device=device), prop_valid), 1)
351
+ last = outs[-1]
352
+ score = torch.sigmoid(last["cls"][:, n_dn:]).max(-1).values
353
+ self.update_memory(q[:, n_dn:].detach(), last["center"][:, n_dn:].detach(), last["vel"][:, n_dn:].detach(),
354
+ score.detach(), valid, pose, time)
355
+ return dict(layers=outs, n_dn=n_dn, n_cur=n_cur, n_prop=k, query_valid=valid, dn_valid=dn_valid,
356
+ dn_gt=dn_gt)
357
+
358
+
359
+ # ------------------------------------------------------------------------------------------ targets / loss
360
+ def positive_mask(rows, count):
361
+ """[B, K] boxes the detector must find: bank-visible, within 50 m of the camera, hit by the lidar."""
362
+ present = torch.arange(rows.shape[1], device=rows.device)[None] < count[:, None]
363
+ rng = torch.hypot(rows[..., OBJ_X] - CAMERA_X, rows[..., OBJ_Y])
364
+ return present & (rows[..., OBJ_BANK_VISIBLE] > 0.5) & (rng <= POSITIVE_RANGE) & (rows[..., OBJ_LIDAR_POINTS] >= 1)
365
+
366
+
367
+ def matchable_mask(rows, count):
368
+ present = torch.arange(rows.shape[1], device=rows.device)[None] < count[:, None]
369
+ rng = torch.hypot(rows[..., OBJ_X] - CAMERA_X, rows[..., OBJ_Y])
370
+ return present & (rng <= MATCH_RANGE)
371
+
372
+
373
+ def box_code(rows):
374
+ """[..., OBJ_DIM] -> target code (centre xyz, log half extents, sin, cos, vx, vy) [..., BOX_DIM]."""
375
+ yaw, speed = rows[..., OBJ_YAW], rows[..., OBJ_SPEED]
376
+ return torch.cat((rows[..., [OBJ_X, OBJ_Y, OBJ_Z]],
377
+ torch.log(rows[..., [OBJ_HALF_L, OBJ_HALF_W, OBJ_HALF_H]].clamp(min=1e-3)),
378
+ torch.sin(yaw)[..., None], torch.cos(yaw)[..., None],
379
+ (speed * torch.cos(yaw))[..., None], (speed * torch.sin(yaw))[..., None]), -1)
380
+
381
+
382
+ def pred_code(layer, sl):
383
+ return torch.cat((layer["center"][:, sl], layer["log_size"][:, sl], layer["sincos"][:, sl], layer["vel"][:, sl]), -1)
384
+
385
+
386
+ def focal_cost(logits, gt_cls, alpha=0.25, gamma=2.0):
387
+ """[L, C] logits, [G] classes -> [L, G] classification matching cost."""
388
+ p = torch.sigmoid(logits)
389
+ neg = (1 - alpha) * p ** gamma * (-(1 - p).clamp(min=1e-8).log())
390
+ pos = alpha * (1 - p) ** gamma * (-p.clamp(min=1e-8).log())
391
+ return pos[:, gt_cls] - neg[:, gt_cls]
392
+
393
+
394
+ def sigmoid_focal(logits, target_onehot, alpha=0.25, gamma=2.0):
395
+ p = torch.sigmoid(logits)
396
+ ce = F.binary_cross_entropy_with_logits(logits, target_onehot, reduction="none")
397
+ p_t = p * target_onehot + (1 - p) * (1 - target_onehot)
398
+ alpha_t = alpha * target_onehot + (1 - alpha) * (1 - target_onehot)
399
+ return alpha_t * ce * (1 - p_t) ** gamma
400
+
401
+
402
+ def laplace_scale_term(err, log_sigma):
403
+ """Trains only the scale (the mean is trained by the L1): err.detach() * exp(-s) + s."""
404
+ log_sigma = log_sigma.clamp(-5.0, 5.0)
405
+ return err.detach() * torch.exp(-log_sigma) + log_sigma
406
+
407
+
408
+ @torch.no_grad()
409
+ def hungarian_all(layers, sl, query_valid, gt_code, gt_cls, w_cls, w_box):
410
+ """Assignments for every (layer, sample): list over layers of lists of (q_idx, g_idx) LongTensors (CPU).
411
+
412
+ All cost matrices are moved to the CPU in one transfer."""
413
+ b = query_valid.shape[0]
414
+ g_max = max([len(g) for g in gt_code] + [1])
415
+ costs = []
416
+ for layer in layers:
417
+ pc = pred_code(layer, sl)[..., :8]
418
+ cost = pc.new_full((b, pc.shape[1], g_max), 1e6)
419
+ for i in range(b):
420
+ if len(gt_code[i]):
421
+ c = w_cls * focal_cost(layer["cls"][i, sl], gt_cls[i]) + w_box * torch.cdist(pc[i], gt_code[i][:, :8], p=1)
422
+ cost[i, :, :len(gt_code[i])] = c.masked_fill(~query_valid[i][:, None], 1e6)
423
+ costs.append(cost)
424
+ costs = torch.stack(costs).cpu().numpy()
425
+ out = []
426
+ for li in range(len(layers)):
427
+ pairs = []
428
+ for i in range(b):
429
+ n = len(gt_code[i])
430
+ if n == 0:
431
+ pairs.append((torch.zeros(0, dtype=torch.long), torch.zeros(0, dtype=torch.long)))
432
+ continue
433
+ r, c = linear_sum_assignment(costs[li, i, :, :n])
434
+ pairs.append((torch.as_tensor(r, dtype=torch.long), torch.as_tensor(c, dtype=torch.long)))
435
+ out.append(pairs)
436
+ return out
437
+
438
+
439
+ 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):
440
+ """Set loss over all decoder layers plus the denoising loss. gt_rows [B, K, OBJ_DIM] float, gt_count [B].
441
+
442
+ Queries matched to an uncertain labelled box (not bank-visible / no lidar point / beyond 50 m) get
443
+ no classification target and no negative pressure; boxes beyond MATCH_RANGE are not matched."""
444
+ device = gt_rows.device
445
+ b = gt_rows.shape[0]
446
+ n_dn, n_cur, n_prop = out["n_dn"], out["n_cur"], out["n_prop"]
447
+ sl = slice(n_dn, n_dn + n_cur + n_prop)
448
+ qv = out["query_valid"]
449
+ match = matchable_mask(gt_rows, gt_count)
450
+ pos = positive_mask(gt_rows, gt_count)
451
+ gt_code = [box_code(gt_rows[i, match[i]]) for i in range(b)]
452
+ gt_cls = [gt_rows[i, match[i], OBJ_CLASS].long() for i in range(b)]
453
+ gt_pos = [pos[i, match[i]] for i in range(b)]
454
+ num_pos = max(float(pos.sum().item()), 1.0)
455
+ assignments = hungarian_all(out["layers"], sl, qv, gt_code, gt_cls, w_cls, w_box)
456
+ zero = gt_rows.new_zeros(())
457
+ losses = dict(cls=zero, box=zero, vel=zero, sigma=zero, dn_cls=zero, dn_box=zero)
458
+ dv, dg = out["dn_valid"], out["dn_gt"]
459
+ if n_dn:
460
+ n_dn_valid = max(float(dv.sum().item()), 1.0)
461
+ gt_cls_all = gt_rows[..., OBJ_CLASS].long()
462
+ dn_target = torch.zeros(b, n_dn, NUM_CLASSES, device=device)
463
+ dn_target.scatter_(2, gt_cls_all.gather(1, dg)[..., None], 1.0)
464
+ dn_target = dn_target * dv[..., None]
465
+ dn_gt_code = box_code(gt_rows).gather(1, dg[..., None].expand(-1, -1, BOX_DIM))
466
+ for layer, pairs in zip(out["layers"], assignments):
467
+ logits = layer["cls"][:, sl]
468
+ target = torch.zeros_like(logits)
469
+ weight = qv.float().clone() # 0 for invalid propagated queries
470
+ pc = pred_code(layer, sl)
471
+ ls = layer["log_sigma"][:, sl]
472
+ box_l = vel_l = sig_l = zero
473
+ for i, (r, c) in enumerate(pairs):
474
+ if len(r) == 0:
475
+ continue
476
+ r, c = r.to(device), c.to(device)
477
+ is_pos = gt_pos[i][c]
478
+ target[i, r[is_pos], gt_cls[i][c[is_pos]]] = 1.0
479
+ weight[i, r[~is_pos]] = 0.0
480
+ rp, cp = r[is_pos], c[is_pos]
481
+ if len(rp) == 0:
482
+ continue
483
+ p, g = pc[i, rp], gt_code[i][cp]
484
+ box_l = box_l + (p[:, :8] - g[:, :8]).abs().sum()
485
+ vel_err = (p[:, 8:10] - g[:, 8:10]).abs()
486
+ vel_l = vel_l + vel_err.sum()
487
+ rng_err = (torch.hypot(p[:, 0] - CAMERA_X, p[:, 1]) - torch.hypot(g[:, 0] - CAMERA_X, g[:, 1])).abs()
488
+ sig_l = sig_l + laplace_scale_term(rng_err, ls[i, rp, 0]).sum() \
489
+ + laplace_scale_term(vel_err, ls[i, rp, 1:3]).sum()
490
+ losses["cls"] = losses["cls"] + (sigmoid_focal(logits, target) * weight[..., None]).sum() / num_pos
491
+ losses["box"] = losses["box"] + box_l / num_pos
492
+ losses["vel"] = losses["vel"] + vel_l / num_pos
493
+ losses["sigma"] = losses["sigma"] + sig_l / num_pos
494
+ if n_dn:
495
+ dn_logits = layer["cls"][:, :n_dn]
496
+ losses["dn_cls"] = losses["dn_cls"] + (sigmoid_focal(dn_logits, dn_target) * dv[..., None]).sum() / n_dn_valid
497
+ pd = pred_code(layer, slice(0, n_dn))
498
+ err = (pd[..., :8] - dn_gt_code[..., :8]).abs().sum(-1) \
499
+ + w_vel * (pd[..., 8:10] - dn_gt_code[..., 8:10]).abs().sum(-1)
500
+ losses["dn_box"] = losses["dn_box"] + (err * dv).sum() / n_dn_valid
501
+ losses["total"] = w_cls * losses["cls"] + w_box * losses["box"] + w_box * w_vel * losses["vel"] \
502
+ + w_sigma * losses["sigma"] + w_dn * (w_cls * losses["dn_cls"] + w_box * losses["dn_box"])
503
+ return losses
504
+
505
+
506
+ # ------------------------------------------------------------------------------------------ decoding
507
+ NMS_LATERAL = {0: 1.0, 1: 0.5, 2: 1.0} # per class: metres across the viewing ray
508
+ NMS_RANGE = {0: (1.5, 0.05), 1: (0.75, 0.025), 2: (1.5, 0.05)} # along the ray: a + b * range
509
+
510
+
511
+ @torch.no_grad()
512
+ def bev_nms(x, y, cls, score):
513
+ """Keep mask: a lower-scoring detection of the same class within NMS_LATERAL across and NMS_RANGE along
514
+ the viewing ray of a kept one is a duplicate (the set prediction occasionally puts a current and a
515
+ propagated query on the same object; their offsets are mostly along the ray, i.e. depth)."""
516
+ n = len(score)
517
+ keep = torch.ones(n, dtype=torch.bool, device=score.device)
518
+ if n < 2:
519
+ return keep
520
+ dx, dy = x - CAMERA_X, y
521
+ rng = torch.hypot(dx, dy)
522
+ ux, uy = dx / rng.clamp(min=1e-6), dy / rng.clamp(min=1e-6)
523
+ order = torch.argsort(score, descending=True)
524
+ x, y, cls, rng, ux, uy = x[order], y[order], cls[order], rng[order], ux[order], uy[order]
525
+ lat = torch.tensor([NMS_LATERAL[int(c)] for c in cls.tolist()], device=score.device)
526
+ along = torch.tensor([NMS_RANGE[int(c)][0] + NMS_RANGE[int(c)][1] * r for c, r in zip(cls.tolist(), rng.tolist())],
527
+ device=score.device)
528
+ ddx, ddy = x[None] - x[:, None], y[None] - y[:, None] # [i, j]: j relative to i
529
+ d_along = (ddx * ux[:, None] + ddy * uy[:, None]).abs()
530
+ d_lat = (-ddx * uy[:, None] + ddy * ux[:, None]).abs()
531
+ dup = (cls[None] == cls[:, None]) & (d_along <= along[:, None]) & (d_lat <= lat[:, None])
532
+ kept = torch.ones(n, dtype=torch.bool, device=score.device)
533
+ for i in range(n):
534
+ if kept[i]:
535
+ kept &= ~(dup[i] & (torch.arange(n, device=score.device) > i))
536
+ keep[order] = kept
537
+ return keep
538
+
539
+
540
+ @torch.no_grad()
541
+ def decode_stream(out, score_threshold=0.2, max_detections=64, nms=True):
542
+ """Last-layer predictions of the matching queries -> per-image dicts with the fields of detector.decode."""
543
+ n_dn = out["n_dn"]
544
+ layer = out["layers"][-1]
545
+ cls = layer["cls"][:, n_dn:]
546
+ score_all = torch.sigmoid(cls).masked_fill(~out["query_valid"][..., None], 0.0)
547
+ scores, flat = score_all.flatten(1).topk(min(max_detections, score_all.shape[1] * score_all.shape[2]), dim=1)
548
+ q_idx, c_idx = flat // NUM_CLASSES, flat % NUM_CLASSES
549
+ results = []
550
+ for i in range(cls.shape[0]):
551
+ keep = scores[i] >= score_threshold
552
+ if nms and int(keep.sum()) > 1:
553
+ q0 = q_idx[i][keep] + n_dn
554
+ c0 = layer["center"][i, q0]
555
+ sel = bev_nms(c0[:, 0], c0[:, 1], c_idx[i][keep], scores[i][keep])
556
+ keep[keep.clone()] = sel
557
+ q = q_idx[i][keep] + n_dn
558
+ center = layer["center"][i, q]
559
+ sincos = layer["sincos"][i, q]
560
+ vel = layer["vel"][i, q]
561
+ yaw = torch.atan2(sincos[:, 0], sincos[:, 1])
562
+ speed = torch.hypot(vel[:, 0], vel[:, 1])
563
+ flip = (speed > 1.0) & (torch.cos(torch.atan2(vel[:, 1], vel[:, 0]) - yaw) < 0)
564
+ yaw = torch.where(flip, yaw + math.pi, yaw)
565
+ yaw = torch.atan2(torch.sin(yaw), torch.cos(yaw))
566
+ ext = torch.exp(layer["log_size"][i, q].clamp(-4, 4))
567
+ ls = layer["log_sigma"][i, q].clamp(-5, 5)
568
+ results.append(dict(
569
+ x=center[:, 0], y=center[:, 1], z=center[:, 2], yaw=yaw, speed=speed, vx=vel[:, 0], vy=vel[:, 1],
570
+ half_l=ext[:, 0], half_w=ext[:, 1], half_h=ext[:, 2], cls=c_idx[i][keep], score=scores[i][keep],
571
+ depth_sigma=torch.exp(ls[:, 0]), velocity_sigma=torch.exp(ls[:, 1:3]),
572
+ query=q_idx[i][keep],
573
+ ))
574
+ return results
575
+
576
+
577
+ def load_stream_petr(path, device):
578
+ """StreamPETR from a train_stream_petr.py checkpoint, in eval mode with an empty memory."""
579
+ ckpt = torch.load(path, map_location="cpu", weights_only=False)
580
+ a = ckpt.get("args", {})
581
+ model = StreamPETR(init="pretrained/FastVLM-0.5B", num_queries=a.get("num_queries", 400),
582
+ num_propagated=a.get("num_propagated", 128), memory_frames=a.get("memory_frames", 4),
583
+ layers=a.get("layers", 6), dn_groups=a.get("dn_groups", 3))
584
+ model.load_state_dict(ckpt["model"])
585
+ model.reset_memory()
586
+ return model.to(device).eval()
587
+
588
+
589
+ class StreamDetector:
590
+ """Online wrapper: one call per 4 Hz frame, memory carried across calls (reset() at route start)."""
591
+
592
+ def __init__(self, model, device, score_threshold=0.2):
593
+ self.model, self.device, self.score_threshold = model, device, score_threshold
594
+ self.reset()
595
+
596
+ def reset(self):
597
+ self.model.reset_memory()
598
+
599
+ @torch.no_grad()
600
+ def step(self, image, pose, time):
601
+ """image uint8 [3, H, W] tensor or numpy HWC; pose (x, y, yaw) world; time seconds -> decode dict
602
+ of numpy arrays."""
603
+ if isinstance(image, np.ndarray):
604
+ image = torch.from_numpy(np.ascontiguousarray(image)).permute(2, 0, 1)
605
+ image = image[None].to(self.device, non_blocking=True)
606
+ pose_t = torch.tensor(pose, dtype=torch.float32, device=self.device)[None]
607
+ time_t = torch.tensor([time], dtype=torch.float32, device=self.device)
608
+ with torch.autocast("cuda", dtype=torch.bfloat16):
609
+ out = self.model(image, pose_t, time_t)
610
+ det = decode_stream(out, self.score_threshold)[0]
611
+ return {k: v.float().cpu().numpy() for k, v in det.items()}
models/utils.py ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ from typing import Dict, Optional, Sequence, Tuple
3
+
4
+ import torch
5
+ from torch import Tensor, nn
6
+ from transformers.models.gemma.modeling_gemma import GemmaRMSNorm
7
+ from transformers.models.llama.modeling_llama import LlamaRMSNorm
8
+ from transformers.models.qwen2.modeling_qwen2 import Qwen2RMSNorm
9
+ try:
10
+ from transformers.models.qwen3_vl.modeling_qwen3_vl import Qwen3VLTextRMSNorm
11
+ except ImportError:
12
+ # FastVLM's official environment uses transformers 4.48 (no Qwen3-VL).
13
+ Qwen3VLTextRMSNorm = Qwen2RMSNorm
14
+
15
+ from utils.custom_types import ParamGroup, TrainingOutput
16
+
17
+
18
+ def configure_params_groups(model: nn.Module, param_groups: Sequence[ParamGroup], verbose: bool = True):
19
+ # Partition the parameters into those that will and those that will not experience regularising weight decay
20
+ whitelist_weight_modules = (
21
+ torch.nn.Linear,
22
+ torch.nn.Conv2d,
23
+ torch.nn.Conv3d,
24
+ torch.nn.MultiheadAttention,
25
+ torch.nn.GRU,
26
+ )
27
+ blacklist_weight_modules = (
28
+ LlamaRMSNorm,
29
+ GemmaRMSNorm,
30
+ Qwen2RMSNorm,
31
+ Qwen3VLTextRMSNorm,
32
+ torch.nn.GroupNorm,
33
+ torch.nn.LayerNorm,
34
+ torch.nn.BatchNorm2d,
35
+ torch.nn.Embedding,
36
+ torch.nn.SyncBatchNorm,
37
+ )
38
+
39
+ black_list_weight_names = (
40
+ "latent",
41
+ "logit_scale",
42
+ "pos_enc",
43
+ 'image_newline',
44
+ 'class_embedding',
45
+ 'temporal_embedding',
46
+ "pos_embed",
47
+ "positional_encoding",
48
+ "temporal_encoding",
49
+ "camera_encoding",
50
+ "register_tokens",
51
+ "sink_token",
52
+ "egoposition_head",
53
+ "route_head",
54
+ "acceleration_head",
55
+ "curvature_rate_head",
56
+ "query_embeds",
57
+ # world predictor bare parameters (positional/type embeddings)
58
+ "state_type_embed",
59
+ "action_type_embed",
60
+ "spatial_embed",
61
+ "action_slot_embed",
62
+ "time_embed",
63
+ # transformers 5.x Qwen2.5-VL specific parameters
64
+ 'norm1.weight',
65
+ 'norm2.weight',
66
+ 'fc1.weight',
67
+ 'fc2.weight',
68
+ 'merger.ln_q.weight',
69
+ 'spatial_merge.weight',
70
+ )
71
+
72
+ decay_params = set()
73
+ no_decay_params = set()
74
+ not_trainable_params = set()
75
+ for mn, m in model.named_modules():
76
+ for pn, p in m.named_parameters():
77
+
78
+ fpn = f"{mn}.{pn}" if mn else pn # full param name
79
+ if not p.requires_grad:
80
+ not_trainable_params.add(fpn)
81
+ continue
82
+ if pn.endswith('bias'):
83
+ # all biases will not be decayed
84
+ no_decay_params.add(fpn)
85
+ elif (
86
+ pn.endswith('weight')
87
+ and isinstance(m, blacklist_weight_modules)
88
+ or any(x in fpn for x in black_list_weight_names)
89
+ ):
90
+ # weights of blacklist modules will NOT be weight decayed
91
+ no_decay_params.add(fpn)
92
+ elif pn.endswith('weight') and isinstance(m, whitelist_weight_modules):
93
+ # weights of whitelist modules will be weight decayed
94
+ decay_params.add(fpn)
95
+
96
+ # validate that we considered every parameter
97
+ param_dict = {pn: p for pn, p in model.named_parameters()}
98
+ inter_params = decay_params & no_decay_params
99
+ union_params = decay_params | no_decay_params | not_trainable_params
100
+ assert len(inter_params) == 0, f"parameters {inter_params} made it into both decay/no_decay sets!"
101
+ assert len(param_dict.keys() - union_params) == 0, (
102
+ f"parameters {param_dict.keys() - union_params} were not separated "
103
+ f"into either decay/no_decay/not_trainable set!"
104
+ )
105
+
106
+ union_params = set(not_trainable_params)
107
+
108
+ # split decay/no decay params into separate param groups with different lr
109
+ out = []
110
+ for pg in param_groups:
111
+ group_params_decay = sorted(k for k in decay_params if re.match(pg.pattern, k))
112
+ group_params_no_decay = sorted(k for k in no_decay_params if re.match(pg.pattern, k))
113
+
114
+ inter_params = union_params.intersection(group_params_decay)
115
+ assert len(inter_params) == 0, f"decay parameters {inter_params} made it into multiple param groups"
116
+ inter_params = union_params.intersection(group_params_no_decay)
117
+ assert len(inter_params) == 0, f"no-decay parameters {inter_params} made it into multiple param groups"
118
+
119
+ if pg.weight_decay <= 0.0:
120
+ group_params_no_decay = group_params_decay + group_params_no_decay
121
+ group_params_decay = []
122
+ if verbose and rank_zero_only.rank == 0:
123
+ print(f"==== PARAM_GROUP {pg.pattern} ====")
124
+ for pn in group_params_decay:
125
+ print(f"(DECAY) {pn}")
126
+ for pn in group_params_no_decay:
127
+ print(f"(NO_DECAY) {pn}")
128
+ if len(group_params_decay) > 0:
129
+ out.append(
130
+ {'params': [param_dict[pn] for pn in group_params_decay], 'lr': pg.lr, 'weight_decay': pg.weight_decay}
131
+ )
132
+ if len(group_params_no_decay) > 0:
133
+ out.append({'params': [param_dict[pn] for pn in group_params_no_decay], 'lr': pg.lr, 'weight_decay': 0.0})
134
+
135
+ union_params.update(group_params_decay)
136
+ union_params.update(group_params_no_decay)
137
+
138
+ assert (
139
+ len(param_dict.keys() - union_params) == 0
140
+ ), f"parameters {param_dict.keys() - union_params} were not separated into any param groups!"
141
+
142
+ return out
143
+
144
+
145
+ def normalize_imagenet(x):
146
+ """
147
+ Normalize input images according to ImageNet standards.
148
+ Args:
149
+ x (tensor): input images
150
+ """
151
+ x = x.copy()
152
+ x[:, 0] = ((x[:, 0] / 255.0) - 0.485) / 0.229
153
+ x[:, 1] = ((x[:, 1] / 255.0) - 0.456) / 0.224
154
+ x[:, 2] = ((x[:, 2] / 255.0) - 0.406) / 0.225
155
+ return x
156
+
157
+
158
+ def summarise_losses(
159
+ loss_dict: Dict[str, Tuple[Tensor, Tensor]], weights: Optional[Dict[str, float]] = None
160
+ ) -> TrainingOutput:
161
+ """
162
+ Computes the total loss from a dictionary of losses and their counts.
163
+
164
+ The loss dict should contain two tensor for each key:
165
+ - The loss value for each batch sample; shape [B].
166
+ - The loss count for each batch sample; shape [B]. This is the number of items to average over, i.e.
167
+ number of tokens, number of cuboids etc. For the case where each batch sample has a loss, you
168
+ can set it to a ones tensor of shape [B].
169
+
170
+ Optionally, a weights dictionary can be provided to weight the losses.
171
+
172
+ Args:
173
+ loss_dict: A dictionary of losses and their counts, for each batch sample.
174
+ weights: A dictionary of weights for each loss key.
175
+
176
+ Returns:
177
+ A TrainingOutput object with the total loss and its components.
178
+ """
179
+
180
+ loss_values = {k: v for k, (v, _) in loss_dict.items()}
181
+ loss_counts = {k: n for k, (_, n) in loss_dict.items()}
182
+ # Clamp the denominator so the unselected `where` branch never divides by
183
+ # zero: `d(v/n)/dv = grad/n` is evaluated in backward even when the branch
184
+ # is masked out, and 0/0 poisons every upstream gradient with NaN. This
185
+ # triggers whenever a loss term has zero valid items in the whole batch
186
+ # (e.g. no dream pair / no complete future-box geometry).
187
+ loss_averages = {
188
+ k: torch.where(n.sum() > 0, v.sum() / n.sum().clamp_min(1), 0.0)
189
+ for k, (v, n) in loss_dict.items()
190
+ }
191
+ if weights is None:
192
+ loss = torch.stack(list(loss_averages.values())).sum()
193
+ else:
194
+ loss = torch.stack([weights.get(k, 1.0) * v for k, v in loss_averages.items()]).sum()
195
+ return TrainingOutput(
196
+ loss=loss,
197
+ loss_values=loss_values,
198
+ loss_counts=loss_counts,
199
+ loss_averages=loss_averages,
200
+ )
models/world_predictor.py ADDED
@@ -0,0 +1,227 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Block-causal latent-action world predictor (ported from SimLingo-J1).
2
+
3
+ Each temporal block contains 64 V-JEPA2 state tokens and 8 student latent
4
+ action tokens. Tokens within a block attend bidirectionally; a block can only
5
+ attend to itself and earlier blocks. The predictor is supervised to map
6
+ teacher-forced ``S[t]`` plus latent ``A[t]`` to ``S[t+1]``.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from typing import Optional, Tuple
12
+
13
+ import torch
14
+ import torch.nn.functional as F
15
+ from torch import Tensor, nn
16
+
17
+
18
+ def build_block_causal_mask(
19
+ num_blocks: int, state_tokens: int, action_tokens: int
20
+ ) -> Tensor:
21
+ if min(num_blocks, state_tokens, action_tokens) <= 0:
22
+ raise ValueError("block mask dimensions must be positive")
23
+ block_size = state_tokens + action_tokens
24
+ block_ids = torch.arange(num_blocks).repeat_interleave(block_size)
25
+ # PyTorch boolean attention masks use True for forbidden pairs.
26
+ return block_ids.unsqueeze(0) > block_ids.unsqueeze(1)
27
+
28
+
29
+ def linear_world_weight(global_step: int, weight: float, warmup_steps: int) -> float:
30
+ """Weight for the optimizer update about to run (steps are zero-indexed)."""
31
+
32
+ if warmup_steps <= 0:
33
+ return float(weight)
34
+ return float(weight) * min((int(global_step) + 1) / int(warmup_steps), 1.0)
35
+
36
+
37
+ class BlockCausalWorldPredictor(nn.Module):
38
+ """Predict ``S[t+1]`` from teacher-forced ``S[t]`` and latent ``A[t]``."""
39
+
40
+ def __init__(
41
+ self,
42
+ *,
43
+ action_dim: int,
44
+ predictor_dim: int = 1024,
45
+ target_dim: int = 1024,
46
+ depth: int = 12,
47
+ heads: int = 8,
48
+ mlp_ratio: float = 4.0,
49
+ dropout: float = 0.0,
50
+ num_blocks: int = 3,
51
+ state_tokens: int = 64,
52
+ action_tokens: int = 8,
53
+ ) -> None:
54
+ super().__init__()
55
+ if predictor_dim % heads:
56
+ raise ValueError("predictor_dim must be divisible by predictor_heads")
57
+ self.num_blocks = int(num_blocks)
58
+ self.state_tokens = int(state_tokens)
59
+ self.action_tokens = int(action_tokens)
60
+ self.state_projection = nn.Linear(target_dim, predictor_dim)
61
+ self.action_projection = nn.Linear(action_dim, predictor_dim)
62
+ self.state_type_embed = nn.Parameter(torch.zeros(1, 1, predictor_dim))
63
+ self.action_type_embed = nn.Parameter(torch.zeros(1, 1, predictor_dim))
64
+ self.spatial_embed = nn.Parameter(
65
+ 0.02 * torch.randn(1, state_tokens, predictor_dim)
66
+ )
67
+ self.action_slot_embed = nn.Parameter(
68
+ 0.02 * torch.randn(1, action_tokens, predictor_dim)
69
+ )
70
+ self.time_embed = nn.Parameter(
71
+ torch.zeros(1, num_blocks, 1, predictor_dim)
72
+ )
73
+ layer = nn.TransformerEncoderLayer(
74
+ d_model=predictor_dim,
75
+ nhead=heads,
76
+ dim_feedforward=int(predictor_dim * mlp_ratio),
77
+ dropout=dropout,
78
+ activation="gelu",
79
+ batch_first=True,
80
+ norm_first=True,
81
+ )
82
+ self.transformer = nn.TransformerEncoder(
83
+ layer, num_layers=depth, norm=nn.LayerNorm(predictor_dim)
84
+ )
85
+ self.output_projection = nn.Linear(predictor_dim, target_dim)
86
+ self.register_buffer(
87
+ "attention_mask",
88
+ build_block_causal_mask(num_blocks, state_tokens, action_tokens),
89
+ persistent=False,
90
+ )
91
+
92
+ def forward(self, states: Tensor, actions: Tensor) -> Tensor:
93
+ expected_states = (self.num_blocks, self.state_tokens)
94
+ expected_actions = (self.num_blocks, self.action_tokens)
95
+ if states.ndim != 4 or tuple(states.shape[1:3]) != expected_states:
96
+ raise ValueError(
97
+ f"states must be [B,{self.num_blocks},{self.state_tokens},D], "
98
+ f"got {tuple(states.shape)}"
99
+ )
100
+ if actions.ndim != 4 or tuple(actions.shape[1:3]) != expected_actions:
101
+ raise ValueError(
102
+ f"actions must be [B,{self.num_blocks},{self.action_tokens},D], "
103
+ f"got {tuple(actions.shape)}"
104
+ )
105
+ param_dtype = self.state_projection.weight.dtype
106
+ state_tokens = self.state_projection(states.to(param_dtype))
107
+ state_tokens = (
108
+ state_tokens
109
+ + self.spatial_embed.unsqueeze(1)
110
+ + self.state_type_embed.unsqueeze(1)
111
+ + self.time_embed
112
+ )
113
+ action_tokens = self.action_projection(actions.to(param_dtype))
114
+ action_tokens = (
115
+ action_tokens
116
+ + self.action_slot_embed.unsqueeze(1)
117
+ + self.action_type_embed.unsqueeze(1)
118
+ + self.time_embed
119
+ )
120
+ blocks = torch.cat((state_tokens, action_tokens), dim=2)
121
+ encoded = self.transformer(
122
+ blocks.flatten(1, 2), mask=self.attention_mask, is_causal=False
123
+ )
124
+ encoded = encoded.view(
125
+ states.size(0), self.num_blocks, self.state_tokens + self.action_tokens, -1
126
+ )
127
+ return self.output_projection(encoded[:, :, : self.state_tokens])
128
+
129
+
130
+ def masked_world_l1(
131
+ predictor: BlockCausalWorldPredictor,
132
+ actions: Tensor,
133
+ future_states: Optional[Tensor],
134
+ valid: Optional[Tensor],
135
+ ) -> Tuple[Tensor, int]:
136
+ """Globally-normalized L1 over valid samples only.
137
+
138
+ Different distributed ranks may receive different numbers of valid targets
139
+ (shift-augmented samples are masked out). If at least one rank has a valid
140
+ future target, every rank must include the predictor in its autograd graph,
141
+ so ranks without a valid target execute a zero-weight dummy forward. This
142
+ keeps DeepSpeed/DDP gradient collectives aligned across ranks. When the
143
+ global batch contains no valid target the predictor is skipped entirely.
144
+ """
145
+
146
+ local_count = (
147
+ int(valid.to(dtype=torch.long).sum().item())
148
+ if future_states is not None and valid is not None
149
+ else 0
150
+ )
151
+ distributed = torch.distributed.is_available() and torch.distributed.is_initialized()
152
+ global_count_tensor = actions.new_tensor(local_count, dtype=torch.long)
153
+ if distributed:
154
+ torch.distributed.all_reduce(
155
+ global_count_tensor, op=torch.distributed.ReduceOp.SUM
156
+ )
157
+ global_count = int(global_count_tensor.item())
158
+ if global_count == 0:
159
+ return actions.new_zeros(()), 0
160
+
161
+ world_size = torch.distributed.get_world_size() if distributed else 1
162
+ num_blocks = predictor.num_blocks
163
+ state_tokens = predictor.state_tokens
164
+ target_dim = predictor.state_projection.in_features
165
+ if future_states is not None and (
166
+ future_states.ndim != 4
167
+ or tuple(future_states.shape[1:])
168
+ != (num_blocks + 1, state_tokens, target_dim)
169
+ ):
170
+ raise ValueError(
171
+ f"future_states must have shape [B,{num_blocks + 1},{state_tokens},{target_dim}], "
172
+ f"got {tuple(future_states.shape)}"
173
+ )
174
+ if future_states is None:
175
+ predictor_states = actions.new_zeros(
176
+ (actions.size(0), num_blocks + 1, state_tokens, target_dim)
177
+ )
178
+ local_valid = torch.zeros(actions.size(0), dtype=torch.bool, device=actions.device)
179
+ else:
180
+ predictor_states = future_states.detach()
181
+ local_valid = (
182
+ valid.to(device=actions.device, dtype=torch.bool)
183
+ if valid is not None
184
+ else torch.zeros(actions.size(0), dtype=torch.bool, device=actions.device)
185
+ )
186
+
187
+ # Always use the full local microbatch. A rank-local selected subset gives
188
+ # DeepSpeed Stage 2 a different predictor execution shape on each rank and
189
+ # can stall reduction even when the same parameters are present.
190
+ predictions = predictor(predictor_states[:, :num_blocks], actions)
191
+ targets = predictor_states[:, 1:]
192
+ selected_predictions = predictions[local_valid]
193
+ selected_targets = targets[local_valid]
194
+ # DDP averages gradients across ranks. This scale makes that result equal
195
+ # to a mean over every valid element in the global batch, even when the
196
+ # rank-local valid counts differ.
197
+ error_sum = (selected_predictions - selected_targets.to(selected_predictions.dtype)).abs().float().sum()
198
+ elements_per_sample = targets[0].numel()
199
+ loss = error_sum * (float(world_size) / (global_count * elements_per_sample))
200
+ return loss, global_count
201
+
202
+
203
+ def masked_world_l1_diagnostics(
204
+ predictor: BlockCausalWorldPredictor,
205
+ actions: Tensor,
206
+ future_states: Optional[Tensor],
207
+ valid: Optional[Tensor],
208
+ ) -> Tuple[dict, int]:
209
+ """Validation-only correct/shuffled/reversed target comparison."""
210
+
211
+ if future_states is None or valid is None or not bool(valid.any()):
212
+ zero = actions.new_zeros(())
213
+ return {"correct": zero, "shuffled": zero, "reversed": zero}, 0
214
+ selected_actions = actions[valid]
215
+ selected_states = future_states[valid].detach()
216
+ predictions = predictor(selected_states[:, : predictor.num_blocks], selected_actions)
217
+ targets = selected_states[:, 1:].to(predictions.dtype)
218
+ if targets.size(0) > 1:
219
+ shuffled = targets.roll(1, dims=0)
220
+ else:
221
+ shuffled = targets.roll(1, dims=2)
222
+ losses = {
223
+ "correct": F.l1_loss(predictions, targets, reduction="mean"),
224
+ "shuffled": F.l1_loss(predictions, shuffled, reduction="mean"),
225
+ "reversed": F.l1_loss(predictions, targets.flip(1), reduction="mean"),
226
+ }
227
+ return losses, int(valid.sum().item())
original_scores.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ # Original closed-loop result on the source machine.
2
+ # Full per-route JSON files are intentionally not packed.
3
+
4
+ eval_name: qwen3vl_2b_video_dream_consdrive_v2_gating_jump_thr010_s08_seed_42_tmux
5
+ checkpoint: outputs/qwen3vl_2b_video_dream_consdrive_seed_42/2026-08-09_13-10-02/checkpoints/last.ckpt
6
+ driving score: 91.32802589545453
7
+ success rate: 0.7772727272727272
8
+ eval num: 220
requirements-pim.txt ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Separate environment from the legacy Qwen3-VL baseline. Python 3.10-3.12.
2
+ torch==2.6.0
3
+ torchvision==0.21.0
4
+ transformers==4.48.3
5
+ peft==0.13.2
6
+ timm==1.0.15
7
+ pytorch-lightning==2.5.0
8
+ torchmetrics==1.6.1
9
+ hydra-core==1.3.2
10
+ numpy==1.26.4
11
+ opencv-python-headless==4.11.0.86
12
+ imgaug==0.4.0
13
+ ujson
14
+ line-profiler
15
+ scipy
16
+ Pillow
17
+ sentencepiece
18
+ einops
19
+ shortuuid
20
+ filterpy
21
+ pytest
22
+ # Install official ml-fastvlm dependencies as needed (see docs/PIM.md).
23
+ # CARLA 0.9.15 Python wheel must match your Python/OS; not installed here.
scripts/analysis/ability_benchmark.py ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Bench2Drive tools/ability_benchmark.py, connecting to an already running CARLA server (route planner built once per town)."""
2
+ import json
3
+ import carla
4
+ import argparse
5
+ import xml.etree.ElementTree as ET
6
+ from agents.navigation.global_route_planner import GlobalRoutePlanner
7
+ import os
8
+ import atexit
9
+ import subprocess
10
+ import time
11
+ import random
12
+
13
+ Ability = {
14
+ "Overtaking":['Accident', 'AccidentTwoWays', 'ConstructionObstacle', 'ConstructionObstacleTwoWays', 'HazardAtSideLaneTwoWays', 'HazardAtSideLane', 'ParkedObstacleTwoWays', 'ParkedObstacle', 'VehicleOpensDoorTwoWays'],
15
+ "Merging": ['CrossingBicycleFlow', 'EnterActorFlow', 'HighwayExit', 'InterurbanActorFlow', 'HighwayCutIn', 'InterurbanAdvancedActorFlow', 'MergerIntoSlowTrafficV2', 'MergerIntoSlowTraffic', 'NonSignalizedJunctionLeftTurn', 'NonSignalizedJunctionRightTurn', 'NonSignalizedJunctionLeftTurnEnterFlow', 'ParkingExit', 'SequentialLaneChange', 'SignalizedJunctionLeftTurn', 'SignalizedJunctionRightTurn', 'SignalizedJunctionLeftTurnEnterFlow'],
16
+ "Emergency_Brake": ['BlockedIntersection', 'DynamicObjectCrossing', 'HardBreakRoute', 'OppositeVehicleTakingPriority', 'OppositeVehicleRunningRedLight', 'ParkingCutIn', 'PedestrianCrossing', 'ParkingCrossingPedestrian', 'StaticCutIn', 'VehicleTurningRoute', 'VehicleTurningRoutePedestrian', 'ControlLoss'],
17
+ "Give_Way": ['InvadingTurn', 'YieldToEmergencyVehicle'],
18
+ "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']
19
+ }
20
+
21
+ def get_infraction_status(record):
22
+ for infraction, value in record['infractions'].items():
23
+ if infraction == "min_speed_infractions":
24
+ continue
25
+ elif len(value) > 0:
26
+ return True
27
+ return False
28
+
29
+ def update_Ability(scenario_name, Ability_Statistic, status):
30
+ for ability, scenarios in Ability.items():
31
+ if scenario_name in scenarios:
32
+ Ability_Statistic[ability][1] += 1
33
+ if status:
34
+ Ability_Statistic[ability][0] += 1
35
+ pass
36
+
37
+ def update_Success(scenario_name, Success_Statistic, status):
38
+ if scenario_name not in Success_Statistic:
39
+ if status:
40
+ Success_Statistic[scenario_name] = [1, 1]
41
+ else:
42
+ Success_Statistic[scenario_name] = [0, 1]
43
+ else:
44
+ Success_Statistic[scenario_name][1] += 1
45
+ if status:
46
+ Success_Statistic[scenario_name][0] += 1
47
+ pass
48
+
49
+ def get_position(xml_route):
50
+ waypoints_elem = xml_route.find('waypoints')
51
+ keypoints = waypoints_elem.findall('position')
52
+ return [carla.Location(float(pos.get('x')), float(pos.get('y')), float(pos.get('z'))) for pos in keypoints]
53
+
54
+ def get_route_result(records, route_id):
55
+ for record in records:
56
+ record_route_id = record['route_id'].split('_')[1]
57
+ if route_id == record_route_id:
58
+ return record
59
+ return None
60
+
61
+ def get_waypoint_route(locs, grp):
62
+ route = []
63
+ for i in range(len(locs) - 1):
64
+ loc = locs[i]
65
+ loc_next = locs[i + 1]
66
+ interpolated_trace = grp.trace_route(loc, loc_next)
67
+ for wp, _ in interpolated_trace:
68
+ route.append(wp)
69
+ return route
70
+
71
+ def main(args):
72
+ routes_file = args.file
73
+ result_file = args.result_file
74
+ Ability_Statistic = {}
75
+ crash_route_list = []
76
+ for key in Ability:
77
+ Ability_Statistic[key] = [0, 0.]
78
+ Success_Statistic = {}
79
+
80
+ with open(result_file, 'r') as f:
81
+ data = json.load(f)
82
+ records = data["_checkpoint"]["records"]
83
+
84
+ tree = ET.parse(routes_file)
85
+ root = tree.getroot()
86
+ routes = root.findall('route')
87
+ sorted_routes = sorted(routes, key=lambda x: x.get('town'))
88
+
89
+ client = carla.Client(args.host, args.port)
90
+ client.set_timeout(300)
91
+
92
+ current_town = sorted_routes[0].get('town')
93
+ world = client.load_world(current_town)
94
+ carla_map = world.get_map()
95
+ grp = GlobalRoutePlanner(carla_map, 1.0)
96
+ for route in sorted_routes:
97
+ scenarios = route.find('scenarios')
98
+ scenario_name = scenarios.find('scenario').get("type")
99
+ route_id = route.get('id')
100
+ route_record = get_route_result(records, route_id)
101
+ if route_record is None:
102
+ crash_route_list.append((scenario_name, route_id))
103
+ print('No result record of route', route_id, "in the result file")
104
+ continue
105
+ if route_record["status"] == 'Completed' or route_record["status"] == "Perfect":
106
+ if get_infraction_status(route_record):
107
+ record_success_status = False
108
+ else:
109
+ record_success_status = True
110
+ else:
111
+ record_success_status = False
112
+ update_Ability(scenario_name, Ability_Statistic, record_success_status)
113
+ update_Success(scenario_name, Success_Statistic, record_success_status)
114
+ # if scenario_name in Ability["Traffic_Signs"] and (scenario_name in Ability["Merging"] or scenario_name in Ability["Emergency_Brake"]):
115
+ # Only these three 'Ability's intersect
116
+ if scenario_name in Ability["Traffic_Signs"]:
117
+ # Only these three 'Ability's intersect
118
+ if route.get('town') != current_town:
119
+ current_town = route.get('town')
120
+ print("Loading the town:", current_town)
121
+ world = client.load_world(current_town)
122
+ print("successfully load the town:", current_town)
123
+ grp = GlobalRoutePlanner(world.get_map(), 1.0)
124
+ location_list = get_position(route)
125
+ waypoint_route = get_waypoint_route(location_list, grp)
126
+ count = 0
127
+ for wp in waypoint_route:
128
+ count += 1
129
+ if wp.is_junction:
130
+ break
131
+ if not wp.is_junction:
132
+ raise RuntimeError("This route does not contain any junction-waypoint!")
133
+ # +8 to ensure the ego pass the trigger volume
134
+ junction_completion = float(count+8) / float(len(waypoint_route))
135
+ record_completion = route_record["scores"]["score_route"] / 100.0
136
+ stop_infraction = route_record["infractions"]["stop_infraction"]
137
+ red_light_infraction = route_record["infractions"]["red_light"]
138
+ if record_completion > junction_completion and not stop_infraction and not red_light_infraction:
139
+ Ability_Statistic['Traffic_Signs'][0] += 1
140
+ Ability_Statistic['Traffic_Signs'][1] += 1
141
+ else:
142
+ Ability_Statistic['Traffic_Signs'][1] += 1
143
+ else:
144
+ pass
145
+
146
+ Ability_Res = {}
147
+ for ability, statis in Ability_Statistic.items():
148
+ Ability_Res[ability] = float(statis[0])/float(statis[1])
149
+
150
+ for key, value in Ability_Res.items():
151
+ print(key, ": ", value)
152
+
153
+ Ability_Res['mean'] = sum(list(Ability_Res.values())) / 5
154
+ Ability_Res['crashed'] = crash_route_list
155
+ with open(os.path.splitext(result_file)[0] + "_ability.json", 'w') as file:
156
+ json.dump(Ability_Res, file, indent=4)
157
+
158
+ Success_Res = {}
159
+ Route_num = 0
160
+ Succ_Route_num = 0
161
+ for scenario, statis in Success_Statistic.items():
162
+ Success_Res[scenario] = float(statis[0])/float(statis[1])
163
+ Succ_Route_num += statis[0]
164
+ Route_num += statis[1]
165
+ assert len(crash_route_list) == 220 - float(Route_num)
166
+ print(f"Mean:{Ability_Res['mean']}")
167
+ print(f'Crashed Route num: {len(crash_route_list)}, Crashed Route ID: {crash_route_list}')
168
+ print('Finished!')
169
+
170
+ if __name__=='__main__':
171
+ argparser = argparse.ArgumentParser(description=__doc__)
172
+ argparser.add_argument('-f', '--file', nargs=None, default="leaderboard/data/bench2drive220.xml", help='route file')
173
+ argparser.add_argument('-r', '--result_file', nargs=None, default="", help='result json file')
174
+ argparser.add_argument('-t', '--host', default='localhost', help='IP of the host server (default: localhost)')
175
+ argparser.add_argument('-p', '--port', type=int, default=2000, help='carla rpc port')
176
+ args = argparser.parse_args()
177
+ main(args)
178
+
scripts/analysis/cf_batch.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Run the creep counterfactual for every collision in a failure report.
2
+
3
+ S1 (memoryless creep after a standstill): applies when the ego departed from a standstill <= 30 m before
4
+ the impact; simulate from the departure point at rest.
5
+ S2 (memory-gated creep): applies when the other actor had been inside the FOV during the last 15 s but was
6
+ out of view 1.5 s before impact; simulate from 20 m (arc length) before impact at the recorded speed.
7
+
8
+ Usage: python cf_batch.py report.json NPZ_DIR extents.json out.json
9
+ """
10
+ import json
11
+ import sys
12
+ from pathlib import Path
13
+
14
+ import numpy as np
15
+
16
+ from cf_creep import bystander_index, simulate
17
+
18
+
19
+ def start_20m_before(hero, t_c, dist=20.0):
20
+ seg = hero[hero[:, 0] <= t_c]
21
+ d = np.concatenate([[0], np.cumsum(np.hypot(np.diff(seg[::-1, 1]), np.diff(seg[::-1, 2])))])
22
+ k = np.searchsorted(d, dist)
23
+ k = min(k, len(seg) - 1)
24
+ row = seg[::-1][k]
25
+ return float(row[0]), float(row[4])
26
+
27
+
28
+ def main():
29
+ report, npz_dir, extents, out = sys.argv[1:5]
30
+ report = json.load(open(report))
31
+ extents = json.load(open(extents))
32
+ results = []
33
+ for e in report:
34
+ if e["success"] or not isinstance(e.get("collisions"), list):
35
+ continue
36
+ d = np.load(Path(npz_dir) / f"RouteScenario_{e['route']}_rep0.npz")
37
+ others = d["others"]
38
+ for c in e["collisions"]:
39
+ oid = c.get("other_id")
40
+ if oid is None or c["class"] == "static object / layout" or not np.any(others[:, 1] == oid):
41
+ continue
42
+ ext = extents.get(c["other_type"], (2.4, 1.0))
43
+ bys = bystander_index(d, oid, extents)
44
+ row = {"route": e["route"], "scenario": e["scenario"], "t": c["t"], "other": c["other_type"],
45
+ "class": c["class"]}
46
+ try:
47
+ row["replay_actual"] = simulate(d, c["t"], oid, ext, c["t"] - 8.0, 0.0, replay_actual=True)["outcome"]
48
+ except Exception as ex:
49
+ row["replay_actual"] = f"error {ex!r}"
50
+ dep = c.get("departed_from_stop_s_before")
51
+ if dep is not None and c.get("dist_since_departure", 99) <= 30 and not c.get("stop_is_route_start", False):
52
+ t0 = c["t"] - dep
53
+ row["S1"] = {f"tau{tau}": simulate(d, c["t"], oid, ext, t0, 0.0, v_cap=3.0, tau=tau, bystanders=bys)
54
+ for tau in (0.5, 1.0, None)}
55
+ fov = c.get("in_fov_at", {})
56
+ if c.get("fov_time_last15s", 0) > 0 and not fov.get("-1.5s", True):
57
+ t0, v0 = start_20m_before(d["hero"], c["t"])
58
+ row["S2"] = {f"tau{tau}": simulate(d, c["t"], oid, ext, t0, v0, v_cap=3.0, tau=tau, bystanders=bys)
59
+ for tau in (0.5, 1.0, None)}
60
+ results.append(row)
61
+ json.dump(results, open(out, "w"), indent=1, default=float)
62
+ print(f"{len(results)} collisions simulated -> {out}")
63
+
64
+
65
+ if __name__ == "__main__":
66
+ main()
scripts/analysis/cf_creep.py ADDED
@@ -0,0 +1,288 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Counterfactual 'visibility-aware creep' replay for a single recorded collision.
2
+
3
+ The ego follows its recorded path geometry but with a new speed profile: from the start point it creeps at
4
+ <= v_cap and, being memoryless, starts braking `tau` seconds after any corner of the other actor's box enters
5
+ the 110 deg front-camera FOV. The other actor replays its recorded trajectory (constant-velocity
6
+ extrapolation after the real impact). If it was at rest and started moving after the start point, its
7
+ launch is re-timed to the moment the simulated ego reaches the position the real ego had at launch
8
+ (scenario actors are triggered by ego proximity).
9
+ """
10
+ import json
11
+ import math
12
+
13
+ import numpy as np
14
+
15
+ from failure_report import CAM_BACK, EGO_EXTENT, HALF_FOV, corners, interp_state
16
+
17
+ DT = 0.02
18
+
19
+
20
+ def _axes(c):
21
+ 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])]
22
+
23
+
24
+ def boxes_overlap(a, b):
25
+ for axis in _axes(a) + _axes(b):
26
+ pa = [p[0] * axis[0] + p[1] * axis[1] for p in a]
27
+ pb = [p[0] * axis[0] + p[1] * axis[1] for p in b]
28
+ if max(pa) < min(pb) or max(pb) < min(pa):
29
+ return False
30
+ return True
31
+
32
+
33
+ def box(x, y, yaw, ext):
34
+ # corners() order: (-x,-y), (-x,+y), (+x,-y), (+x,+y) -> reorder to a polygon for SAT axes
35
+ c = corners(x, y, yaw, ext)
36
+ return [c[0], c[1], c[3], c[2]]
37
+
38
+
39
+ def visible(ego, oth, ext):
40
+ ex, ey, eyaw = ego
41
+ c, s = math.cos(math.radians(eyaw)), math.sin(math.radians(eyaw))
42
+ cx, cy = ex - CAM_BACK * c, ey - CAM_BACK * s
43
+ for px, py in corners(*oth, ext):
44
+ lx = (px - cx) * c + (py - cy) * s
45
+ ly = -(px - cx) * s + (py - cy) * c
46
+ if lx > 0 and abs(math.atan2(ly, lx)) < HALF_FOV:
47
+ return True
48
+ return False
49
+
50
+
51
+ class Path:
52
+ def __init__(self, hero, t0, t1, extend=15.0):
53
+ seg = hero[(hero[:, 0] >= t0) & (hero[:, 0] <= t1)]
54
+ pts = [seg[0]]
55
+ for r in seg[1:]:
56
+ if math.hypot(r[1] - pts[-1][1], r[2] - pts[-1][2]) > 0.05:
57
+ pts.append(r)
58
+ pts = np.array(pts)
59
+ yaw = math.radians(pts[-1][3])
60
+ ext = np.array([[0, pts[-1][1] + k * math.cos(yaw), pts[-1][2] + k * math.sin(yaw), pts[-1][3], 0]
61
+ for k in np.arange(0.5, extend, 0.5)])
62
+ self.p = np.vstack([pts, ext]) if len(ext) else pts
63
+ d = np.hypot(np.diff(self.p[:, 1]), np.diff(self.p[:, 2]))
64
+ self.s = np.concatenate([[0], np.cumsum(d)])
65
+ self.s_impact = self.s[len(pts) - 1]
66
+ self.t_of_s = (pts[:, 0], self.s[: len(pts)])
67
+
68
+ def pose(self, s):
69
+ s = float(np.clip(s, 0, self.s[-1]))
70
+ x = np.interp(s, self.s, self.p[:, 1])
71
+ y = np.interp(s, self.s, self.p[:, 2])
72
+ yaw = np.degrees(np.unwrap(np.radians(self.p[:, 3])))
73
+ return x, y, float(np.interp(s, self.s, yaw))
74
+
75
+ def s_at_time(self, t):
76
+ return float(np.interp(t, *self.t_of_s))
77
+
78
+
79
+ def other_pose_fn(tr, t_c):
80
+ pre = tr[tr[:, 0] <= t_c - 0.1]
81
+ last, prev = pre[-1], pre[max(0, len(pre) - 6)]
82
+ dt = max(last[0] - prev[0], 1e-3)
83
+ vx, vy = (last[1] - prev[1]) / dt, (last[2] - prev[2]) / dt
84
+
85
+ def f(t):
86
+ if t <= last[0]:
87
+ return interp_state(pre, max(t, pre[0, 0]))
88
+ return last[1] + vx * (t - last[0]), last[2] + vy * (t - last[0]), last[3]
89
+
90
+ return f, last[0]
91
+
92
+
93
+ def bystander_index(d, other_id, extents):
94
+ """Map 0.1 s time keys -> list of (box params) for every recorded actor except the collision partner."""
95
+ actors = json.loads(str(d["actors"]))
96
+ idx = {}
97
+ for t, aid, x, y, yaw in d["others"]:
98
+ if aid == other_id:
99
+ continue
100
+ ext = extents.get(actors.get(str(int(aid)), ""), (2.4, 1.0))
101
+ idx.setdefault(int(round(t * 10)), []).append((int(aid), x, y, yaw, ext))
102
+ return idx
103
+
104
+
105
+ 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,
106
+ replay_actual=False, horizon=15.0, bystanders=None):
107
+ """tau=None means a blind creep (never brakes); `bystanders` from bystander_index() adds overlap
108
+ checks against all other recorded actors (replayed on the original clock)."""
109
+ hero = d["hero"]
110
+ others = d["others"]
111
+ tr = others[others[:, 1] == other_id][:, [0, 2, 3, 4]]
112
+ path = Path(hero, t_start, t_c)
113
+ opose, t_last = other_pose_fn(tr, t_c)
114
+ # Detect a triggered launch: at rest at t_start, moving later.
115
+ spd = np.hypot(np.diff(tr[:, 1]), np.diff(tr[:, 2])) / np.maximum(np.diff(tr[:, 0]), 1e-3)
116
+ moving = np.where((tr[1:, 0] > t_start) & (spd > 0.5))[0]
117
+ 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)
118
+ t_launch = float(tr[moving[0] + 1, 0]) if (len(moving) and at_rest_start) else None
119
+ s_launch = path.s_at_time(t_launch) if t_launch is not None else None
120
+
121
+ s, v, t = 0.0, v0, 0.0
122
+ t_trig, t_seen, braking = None, None, False
123
+ first_seen = None
124
+ min_gap = None
125
+ while t < horizon:
126
+ if replay_actual:
127
+ s = path.s_at_time(t_start + t) if t_start + t <= t_c else path.s_impact
128
+ ego = path.pose(s)
129
+ if t_launch is not None:
130
+ if t_trig is None and s >= s_launch:
131
+ t_trig = t
132
+ t_o = t_launch + (t - t_trig) if t_trig is not None else t_launch - 1e-3
133
+ else:
134
+ t_o = t_start + t
135
+ oth = opose(t_o)
136
+ if t_seen is None and visible(ego, oth, ext_other):
137
+ t_seen = t
138
+ first_seen = t if first_seen is None else first_seen
139
+ ego_box = box(*ego, EGO_EXTENT)
140
+ if boxes_overlap(ego_box, box(*oth, ext_other)):
141
+ return {"outcome": "collision", "triggered": t_launch is not None, "t": round(t, 2), "t_seen": first_seen, "s": round(s, 1),
142
+ "s_impact": round(path.s_impact, 1)}
143
+ if bystanders is not None and t_start + t < t_c + 3.0:
144
+ for aid, bx, by, byaw, bext in bystanders.get(int(round((t_start + t) * 10)), []):
145
+ if abs(bx - ego[0]) < 8 and abs(by - ego[1]) < 8 and boxes_overlap(ego_box, box(bx, by, byaw, bext)):
146
+ return {"outcome": "collision_with_other", "triggered": t_launch is not None, "other_id": aid, "t": round(t, 2),
147
+ "t_seen": first_seen}
148
+ gap = math.hypot(ego[0] - oth[0], ego[1] - oth[1])
149
+ min_gap = gap if min_gap is None else min(min_gap, gap)
150
+ # Done once the other actor's motion has run past the extrapolation window, or we cleared the impact point.
151
+ if t_o > t_last + 5.0 or (s > path.s_impact + 8.0):
152
+ return {"outcome": "safe", "triggered": t_launch is not None, "t_seen": first_seen, "min_centre_gap": round(min_gap, 1)}
153
+ if not replay_actual:
154
+ if tau is not None and t_seen is not None and t >= t_seen + tau:
155
+ braking = True
156
+ if braking:
157
+ v = max(0.0, v - a_brake * DT)
158
+ # Resume once the other actor is no longer visible and has moved away.
159
+ if v == 0.0 and gap > 12.0 and not visible(ego, oth, ext_other):
160
+ braking, t_seen = False, None
161
+ elif v > v_cap:
162
+ v = max(v_cap, v - 3.0 * DT)
163
+ else:
164
+ v = min(v_cap, v + a_acc * DT)
165
+ s += v * DT
166
+ t += DT
167
+ return {"outcome": "timeout", "min_centre_gap": round(min_gap or -1, 1)}
168
+
169
+
170
+ def _bystander_tracks(d, other_id, extents):
171
+ actors = json.loads(str(d["actors"]))
172
+ others = d["others"]
173
+ tracks = {}
174
+ for aid in np.unique(others[:, 1]):
175
+ if aid == other_id:
176
+ continue
177
+ tr = others[others[:, 1] == aid][:, [0, 2, 3, 4]]
178
+ tracks[int(aid)] = (tr, extents.get(actors.get(str(int(aid)), ""), (2.4, 1.0)))
179
+ return tracks
180
+
181
+
182
+ def _track_pose(tr, t):
183
+ if t < tr[0, 0] or t > tr[-1, 0]:
184
+ return None
185
+ return interp_state(tr, t)
186
+
187
+
188
+ 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,
189
+ tau=0.5, t_pred=3.0, horizon=40.0, v_release=None, release_after=(4.0, 1.0)):
190
+ """Creep at <= v_cap and yield to every actor currently in the front-camera FOV whose constant-velocity
191
+ prediction (from its last 0.5 s of motion, no future knowledge) overlaps the ego's creep path within
192
+ t_pred seconds. Braking/resuming acts on the threat state from `tau` seconds earlier. Bystanders are
193
+ replayed on the recorded clock until the recording ends; the partner is extrapolated beyond that.
194
+ Note flow actors switch to reactive driving after any crash, so post-impact bystander motion is optimistic.
195
+ v_release: once the ego has crept release_after[0] m and seen no threat for release_after[1] s, the cap
196
+ is raised to v_release (threat checks stay active)."""
197
+ hero, others = d["hero"], d["others"]
198
+ tr = others[others[:, 1] == other_id][:, [0, 2, 3, 4]]
199
+ path = Path(hero, t_start, t_c)
200
+ opose, t_last = other_pose_fn(tr, t_c)
201
+ spd = np.hypot(np.diff(tr[:, 1]), np.diff(tr[:, 2])) / np.maximum(np.diff(tr[:, 0]), 1e-3)
202
+ moving = np.where((tr[1:, 0] > t_start) & (spd > 0.5))[0]
203
+ 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)
204
+ t_launch = float(tr[moving[0] + 1, 0]) if (len(moving) and at_rest_start) else None
205
+ s_launch = path.s_at_time(t_launch) if t_launch is not None else None
206
+ tracks = _bystander_tracks(d, other_id, extents)
207
+ rec_end = float(hero[-1, 0])
208
+ ego_ext = (EGO_EXTENT[0] + 0.5, EGO_EXTENT[1] + 0.3)
209
+
210
+ s, v, t = 0.0, v0, 0.0
211
+ cap = v_cap
212
+ t_trig = None
213
+ threat_hist = [] # (t, threat)
214
+ braking = False
215
+ first_threat, n_threat_actors = None, set()
216
+ while t < horizon:
217
+ ego = path.pose(s)
218
+ if t_launch is not None:
219
+ if t_trig is None and s >= s_launch:
220
+ t_trig = t
221
+ t_o = t_launch + (t - t_trig) if t_trig is not None else t_launch - 1e-3
222
+ partner = lambda tt: opose(t_launch + (tt - t_trig) if t_trig is not None else t_launch - 1e-3)
223
+ else:
224
+ t_o = t_start + t
225
+ partner = lambda tt: opose(t_start + tt)
226
+ oth = opose(t_o)
227
+ ego_box = box(*ego, EGO_EXTENT)
228
+ if boxes_overlap(ego_box, box(*oth, ext_other)):
229
+ return {"outcome": "collision", "triggered": t_launch is not None, "t": round(t, 2), "s": round(s, 1),
230
+ "s_impact": round(path.s_impact, 1), "first_threat": first_threat}
231
+ tw = t_start + t
232
+ live = []
233
+ for aid, (btr, bext) in (tracks.items() if tw <= rec_end else ()):
234
+ p = _track_pose(btr, tw)
235
+ if p is None or abs(p[0] - ego[0]) > 40 or abs(p[1] - ego[1]) > 40:
236
+ continue
237
+ live.append((aid, p, btr, bext))
238
+ if abs(p[0] - ego[0]) < 8 and abs(p[1] - ego[1]) < 8 and boxes_overlap(ego_box, box(*p, bext)):
239
+ return {"outcome": "collision_with_other", "triggered": t_launch is not None, "with_id": aid,
240
+ "t": round(t, 2), "first_threat": first_threat}
241
+ info = {"triggered": t_launch is not None, "first_threat": first_threat, "t": round(t, 2),
242
+ "threat_actors": sorted(map(str, n_threat_actors)), "s": round(s, 1), "s_impact": round(path.s_impact, 1)}
243
+ if s > path.s_impact + 8.0:
244
+ return {"outcome": "passed" if tw <= rec_end else "passed_after_recording", **info}
245
+ if tw > rec_end and t_o > t_last + 5.0:
246
+ # Partner extrapolated well past the impact; recorded traffic ended without a conflict.
247
+ return {"outcome": "partner_avoided", **info}
248
+
249
+ if int(round(t / DT)) % 5 == 0:
250
+ cand = [("partner", oth, partner(t - 0.5), ext_other)]
251
+ for aid, p, btr, bext in live:
252
+ q = _track_pose(btr, tw - 0.5)
253
+ cand.append((aid, p, q if q is not None else p, bext))
254
+ threat = False
255
+ v_plan = max(v, cap)
256
+ for aid, p, q, ext in cand:
257
+ if not visible(ego, p, ext):
258
+ continue
259
+ vx, vy = (p[0] - q[0]) / 0.5, (p[1] - q[1]) / 0.5
260
+ for k in np.arange(0.0, t_pred + 1e-6, 0.2):
261
+ ek = path.pose(s + v_plan * k)
262
+ if abs(p[0] + vx * k - ek[0]) > 10 or abs(p[1] + vy * k - ek[1]) > 10:
263
+ continue
264
+ if boxes_overlap(box(*ek, ego_ext), box(p[0] + vx * k, p[1] + vy * k, p[2], ext)):
265
+ threat = True
266
+ n_threat_actors.add(aid)
267
+ break
268
+ if threat:
269
+ break
270
+ if threat and first_threat is None:
271
+ first_threat = round(t, 2)
272
+ threat_hist.append((t, threat))
273
+ delayed = [th for tt, th in threat_hist if tt <= t - (tau or 0.0)]
274
+ braking = bool(delayed[-1]) if delayed else False
275
+ if v_release is not None and cap == v_cap and s >= release_after[0]:
276
+ recent = [th for tt, th in threat_hist if tt >= t - release_after[1]]
277
+ if len(recent) >= int(release_after[1] / 0.1) and not any(recent):
278
+ cap = v_release
279
+ if braking:
280
+ v = max(0.0, v - a_brake * DT)
281
+ elif v > cap:
282
+ v = max(cap, v - 3.0 * DT)
283
+ else:
284
+ v = min(cap, v + a_acc * DT)
285
+ s += v * DT
286
+ t += DT
287
+ return {"outcome": "stuck", "first_threat": first_threat, "s": round(s, 1), "s_impact": round(path.s_impact, 1),
288
+ "threat_actors": sorted(map(str, n_threat_actors))}
scripts/analysis/cf_reactive.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Multi-actor reactive creep counterfactual for every collision in a failure report.
2
+
3
+ S1 (memoryless creep after a junction standstill, not the route-start standstill): start at rest at the
4
+ departure point. S2 (memory-gated creep): start 20 m before impact at the recorded speed, applicable when
5
+ the partner had been seen during the last 15 s but was out of view 1.5 s before impact.
6
+
7
+ Usage: python cf_reactive.py report.json NPZ_DIR extents.json out.json
8
+ """
9
+ import json
10
+ import sys
11
+ from pathlib import Path
12
+
13
+ import numpy as np
14
+
15
+ from cf_batch import start_20m_before
16
+ from cf_creep import simulate_reactive
17
+
18
+ GRID = [(3.0, 0.5), (3.0, 1.0), (2.0, 0.5), (2.0, 1.0)]
19
+
20
+
21
+ def main():
22
+ report, npz_dir, extents, out = sys.argv[1:5]
23
+ report = json.load(open(report))
24
+ extents = json.load(open(extents))
25
+ results = []
26
+ for e in report:
27
+ if e["success"] or not isinstance(e.get("collisions"), list):
28
+ continue
29
+ d = np.load(Path(npz_dir) / f"RouteScenario_{e['route']}_rep0.npz")
30
+ for c in e["collisions"]:
31
+ oid = c.get("other_id")
32
+ if oid is None or c["class"] == "static object / layout" or not np.any(d["others"][:, 1] == oid):
33
+ continue
34
+ ext = extents.get(c["other_type"], (2.4, 1.0))
35
+ row = {"route": e["route"], "t": c["t"], "other_id": oid}
36
+ dep = c.get("departed_from_stop_s_before")
37
+ if dep is not None and c.get("dist_since_departure", 99) <= 30 and not c.get("stop_is_route_start", False):
38
+ 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)
39
+ for v, tau in GRID}
40
+ if c.get("fov_time_last15s", 0) > 0 and not c.get("in_fov_at", {}).get("-1.5s", True):
41
+ t0, v0 = start_20m_before(d["hero"], c["t"])
42
+ row["S2"] = {f"v{v}_tau{tau}": simulate_reactive(d, c["t"], oid, ext, t0, v0, extents, v_cap=v, tau=tau)
43
+ for v, tau in GRID}
44
+ results.append(row)
45
+ json.dump(results, open(out, "w"), indent=1, default=float)
46
+ print(f"{len(results)} collisions -> {out}")
47
+
48
+
49
+ if __name__ == "__main__":
50
+ main()
scripts/analysis/compare_reproduction.py ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Original runs vs a reproduction (scripts/reproduce_pipeline.sh) of the best configuration.
2
+
3
+ python scripts/analysis/compare_reproduction.py --tag repro1 (writes eval_results/Bench2Drive/reproduction_<tag>.txt)
4
+
5
+ Training level: final validation loss of stage1 / speeddrop / tracker_sp and the last validation of the
6
+ detectors. Closed loop: Bench2Drive-220 driving score of the final model (sp_v1 detector at 4 Hz, no speed
7
+ mask) against the five original runs. The DS difference is judged against the simulator noise measured on the
8
+ original repeats (single-run sd ~0.6 DS on the fixed 220 routes): "within noise" when
9
+ |mean_repro - mean_orig| <= 1.96 * sqrt(sd^2/n_repro + sd^2/n_orig). Unfinished stages show as pending.
10
+ """
11
+ import argparse
12
+ import csv
13
+ import json
14
+ import math
15
+ import re
16
+ from pathlib import Path
17
+
18
+ import numpy as np
19
+
20
+ B = Path("eval_results/Bench2Drive")
21
+ SINGLE_RUN_SD = 0.62 # per-route variance across the original repeats, routes fixed
22
+
23
+ ORIG_TRAIN = {"stage1": "outputs/fastvlm_stage1/2026-10-31_14-19-40",
24
+ "speeddrop": "outputs/fastvlm_stage3_speeddrop/2026-11-02_06-08-03",
25
+ "tracker_sp": "outputs/fastvlm_stage3_tracker_sp/2026-11-03_16-38-38"}
26
+ ORIG_DET = {"det_v1": "outputs/detector/det_v1", "sp_v1": "outputs/stream_petr/sp_v1",
27
+ "sp_fold0": "outputs/stream_petr/sp_fold0of2", "sp_fold1": "outputs/stream_petr/sp_fold1of2"}
28
+ ORIG_EVALS = ["sp_ft_det4hz_nomask", "sp_ft_det4hz_nomask_repeat", "sp_ft_det4hz_nomask_run3",
29
+ "sp_ft_det4hz_nomask_run4", "sp_ft_det4hz_nomask_run5"]
30
+
31
+
32
+ def repro_paths(tag):
33
+ train = {"stage1": f"outputs/fastvlm_stage1/{tag}", "speeddrop": f"outputs/fastvlm_stage3_speeddrop/{tag}",
34
+ "tracker_sp": f"outputs/fastvlm_stage3_tracker_sp/{tag}"}
35
+ det = {"det_v1": f"outputs/detector/det_v1_{tag}", "sp_v1": f"outputs/stream_petr/sp_v1_{tag}",
36
+ "sp_fold0": f"outputs/stream_petr/sp_fold0of2_{tag}", "sp_fold1": f"outputs/stream_petr/sp_fold1of2_{tag}"}
37
+ evals = sorted(p.name for p in B.glob(f"{tag}_sp_ft_nomask_r*") if (p / "merged.json").exists())
38
+ return train, det, evals
39
+
40
+
41
+ def final_val_loss(train_dir):
42
+ """Last val/loss, route and speed-waypoint losses from Lightning's metrics.csv."""
43
+ p = Path(train_dir) / "logs" / "metrics.csv"
44
+ if not p.exists():
45
+ return None
46
+ rows = [r for r in csv.DictReader(open(p)) if r.get("val/loss")]
47
+ if not rows:
48
+ return None
49
+ r = rows[-1]
50
+ 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)}
51
+
52
+
53
+ def train_hours(train_dir):
54
+ p = Path(train_dir) / "train.log"
55
+ if not p.exists():
56
+ return None
57
+ # tqdm prints MM:SS under one hour and H:MM:SS above, and re-renders the bar many times near 100 %:
58
+ # take the largest elapsed time seen per epoch.
59
+ per_epoch = {}
60
+ for ep, a, b, c in re.findall(r"Epoch (\d+): 100%\|[^|]*\| \d+/\d+ \[(\d+):(\d+)(?::(\d+))?<", p.read_text(errors="ignore")):
61
+ secs = int(a) * 3600 + int(b) * 60 + int(c) if c else int(a) * 60 + int(b)
62
+ per_epoch[ep] = max(per_epoch.get(ep, 0), secs)
63
+ return sum(per_epoch.values()) / 3600 if per_epoch else None
64
+
65
+
66
+ def detector_val(det_dir):
67
+ vals = sorted(Path(det_dir).glob("val_*.json"))
68
+ if not vals:
69
+ return None
70
+ d = json.load(open(vals[-1]))
71
+ out = {"step": int(vals[-1].stem.split("_")[1]), "fp@0.3": d["fp_per_frame"].get("0.3")}
72
+ for cls in ("car", "walker"):
73
+ for rng in ("0-10", "20-30", "40-50"):
74
+ if rng in d.get(cls, {}):
75
+ out[f"{cls}_recall_{rng}"] = d[cls][rng].get("recall_pos")
76
+ for k, v in d.get("car_velocity_by_speed", {}).items():
77
+ out[f"vel_med_{k}"] = v.get("vel_err_med")
78
+ return out
79
+
80
+
81
+ def fmt_metrics(d):
82
+ if d is None:
83
+ return "pending"
84
+ 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)
85
+
86
+
87
+ def load_eval(name):
88
+ return {r["route_id"]: r for r in json.load(open(B / name / "merged.json"))["_checkpoint"]["records"]}
89
+
90
+
91
+ def success(r):
92
+ return r["status"] in ("Completed", "Perfect") and all(
93
+ len(v) == 0 for k, v in r["infractions"].items() if k != "min_speed_infractions")
94
+
95
+
96
+ def summarize(names):
97
+ runs = [load_eval(n) for n in names]
98
+ return dict(runs=runs,
99
+ ds=[np.mean([r["scores"]["score_composed"] for r in run.values()]) for run in runs],
100
+ sr=[100 * np.mean([success(r) for r in run.values()]) for run in runs],
101
+ col=[sum(len(r["infractions"].get("collisions_vehicle", [])) for r in run.values()) for run in runs],
102
+ stops=[sum(len(r["infractions"].get("scenario_timeouts", [])) + len(r["infractions"].get("route_timeout", []))
103
+ for r in run.values()) for run in runs])
104
+
105
+
106
+ def route_means(summary):
107
+ keys = sorted(summary["runs"][0])
108
+ return keys, np.array([[run[k]["scores"]["score_composed"] for k in keys] for run in summary["runs"]]).mean(0)
109
+
110
+
111
+ def main():
112
+ ap = argparse.ArgumentParser()
113
+ ap.add_argument("--tag", default="repro1")
114
+ args = ap.parse_args()
115
+ rtrain, rdet, revals = repro_paths(args.tag)
116
+ L = [f"# Reproduction '{args.tag}' vs original runs (best configuration: speed-dropout stage 3 fine-tuned on "
117
+ "StreamPETR tracker banks, sp_v1 detector at 4 Hz, no speed mask)"]
118
+
119
+ L += ["", "## Training: final validation loss (Lightning metrics.csv) and wall time",
120
+ f"{'stage':12s} {'':6s} {'val/loss':>9s} {'route':>8s} {'speed_wps':>10s} {'hours':>6s}"]
121
+ for stage in ("stage1", "speeddrop", "tracker_sp"):
122
+ for lab, d in (("orig", ORIG_TRAIN[stage]), ("repro", rtrain[stage])):
123
+ v, h = final_val_loss(d), train_hours(d)
124
+ if v is None:
125
+ L.append(f"{stage:12s} {lab:6s} {'pending':>9s}")
126
+ else:
127
+ L.append(f"{stage:12s} {lab:6s} {v.get('loss', float('nan')):9.4f} {v.get('route_loss', float('nan')):8.4f} "
128
+ f"{v.get('speed_wps_loss', float('nan')):10.4f} {h if h is not None else float('nan'):6.2f}")
129
+
130
+ L += ["", "## Detectors: last validation (sp_*: frames with memory; recall = recall_pos; velocity error median, m/s)"]
131
+ for name in ("det_v1", "sp_v1", "sp_fold0", "sp_fold1"):
132
+ for lab, d in (("orig", ORIG_DET[name]), ("repro", rdet[name])):
133
+ L.append(f"{name:10s} {lab:6s} {fmt_metrics(detector_val(d))}")
134
+
135
+ L += ["", f"## Closed loop, Bench2Drive-220 (single-run sd {SINGLE_RUN_SD} DS)",
136
+ f"{'':6s} {'n':>2s} {'DS per run':>36s} {'mean':>6s} {'SR':>6s} {'veh.col':>8s} {'timeouts':>9s}"]
137
+ o = summarize(ORIG_EVALS)
138
+ 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} "
139
+ f"{np.mean(o['sr']):6.2f} {np.mean(o['col']):8.1f} {np.mean(o['stops']):9.1f}")
140
+ if not revals:
141
+ L.append(f"{'repro':6s} 0 {'pending':>36s}")
142
+ else:
143
+ r = summarize(revals)
144
+ diff = np.mean(r["ds"]) - np.mean(o["ds"])
145
+ band = 1.96 * SINGLE_RUN_SD * math.sqrt(1 / len(revals) + 1 / len(ORIG_EVALS))
146
+ verdict = "within noise" if abs(diff) <= band else ("BETTER than original" if diff > 0 else "WORSE than original")
147
+ L.append(f"{'repro':6s} {len(revals):2d} {' / '.join(f'{x:.2f}' for x in r['ds']):>36s} {np.mean(r['ds']):6.2f} "
148
+ f"{np.mean(r['sr']):6.2f} {np.mean(r['col']):8.1f} {np.mean(r['stops']):9.1f}")
149
+ L.append(f"repro - orig = {diff:+.2f} DS, 95% noise band +/-{band:.2f} -> {verdict}")
150
+ keys, om = route_means(o)
151
+ _, rm = route_means(r)
152
+ big = np.argsort(-np.abs(rm - om))[:6]
153
+ 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())}; "
154
+ "largest: " + ", ".join(f"{keys[i].replace('RouteScenario_', '').replace('_rep0', '')} {rm[i] - om[i]:+.0f}" for i in big))
155
+
156
+ text = "\n".join(L)
157
+ print(text)
158
+ (B / f"reproduction_{args.tag}.txt").write_text(text + "\n")
159
+
160
+
161
+ if __name__ == "__main__":
162
+ main()
scripts/analysis/compare_runs.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Compare two Bench2Drive full-220 runs through their failure_report.py outputs.
2
+
3
+ Every failed route gets one primary cause: the earliest collision (by its class and front-camera warning
4
+ time) or, without collisions, its non-collision infractions. Driving-score loss is (100 - route score) / 220.
5
+
6
+ Usage: python compare_runs.py NAME_A REPORT_A NAME_B REPORT_B [--out OUT.json]
7
+ """
8
+ import argparse
9
+ import collections
10
+ import json
11
+
12
+ IGNORED = {"route_dev", "min_speed_infractions"}
13
+ VIS_LIMIT_S = 1.5
14
+ LEAD = {"ego hits stationary vehicle", "ego hits vehicle ahead (same direction)"}
15
+
16
+
17
+ def primary_cause(e):
18
+ infr = sorted(k for k, v in e["infractions"].items() if v and k not in IGNORED)
19
+ colls = e["collisions"] if isinstance(e.get("collisions"), list) else []
20
+ if colls:
21
+ c = min(colls, key=lambda c: c["t"])
22
+ if c["class"] == "pedestrian":
23
+ return "pedestrian", c
24
+ if c["class"] == "static object / layout":
25
+ return "static object / layout", c
26
+ if c["class"] == "rear-ended by other":
27
+ return "rear threat", c
28
+ if c.get("warning_s", 99) < VIS_LIMIT_S:
29
+ return "visibility-limited (<1.5 s in FOV)", c
30
+ if c["class"] in LEAD:
31
+ return "lead / stationary vehicle", c
32
+ return "visible, not yielded (" + c["class"] + ")", c
33
+ if any(k.startswith("collisions") for k in infr):
34
+ return "collision without recorder match", None
35
+ if infr:
36
+ return "non-collision: " + "/".join(infr), None
37
+ if e["status"] != "Completed":
38
+ return "status: " + e["status"], None
39
+ return "deviation / min speed only", None
40
+
41
+
42
+ def summarize(report):
43
+ out = {}
44
+ for e in report:
45
+ cause, c = (None, None) if e["success"] else primary_cause(e)
46
+ out[e["route"]] = {"scenario": e["scenario"], "town": e["town"], "score": e["score"], "success": e["success"],
47
+ "status": e["status"], "cause": cause,
48
+ "first_collision": None if c is None else
49
+ {k: c.get(k) for k in ("t", "class", "other_type", "warning_s", "ego_speed", "other_speed")}}
50
+ return out
51
+
52
+
53
+ def group(cause):
54
+ if cause is None:
55
+ return None
56
+ return "visible, not yielded" if cause.startswith("visible, not yielded") else \
57
+ "non-collision" if cause.startswith("non-collision") else cause
58
+
59
+
60
+ def main():
61
+ ap = argparse.ArgumentParser()
62
+ ap.add_argument("name_a"); ap.add_argument("report_a"); ap.add_argument("name_b"); ap.add_argument("report_b")
63
+ ap.add_argument("--out")
64
+ args = ap.parse_args()
65
+ A, B = (summarize(json.load(open(p))) for p in (args.report_a, args.report_b))
66
+ na, nb = args.name_a, args.name_b
67
+ assert A.keys() == B.keys()
68
+ n = len(A)
69
+
70
+ print(f"{'':28s}{na:>14s}{nb:>14s}")
71
+ for label, f in (("driving score", lambda S: sum(v["score"] for v in S.values()) / n),
72
+ ("success rate %", lambda S: 100 * sum(v["success"] for v in S.values()) / n),
73
+ ("DS loss on failed routes", lambda S: sum(100 - v["score"] for v in S.values() if not v["success"]) / n),
74
+ ("DS loss on successes", lambda S: sum(100 - v["score"] for v in S.values() if v["success"]) / n)):
75
+ print(f"{label:28s}{f(A):14.2f}{f(B):14.2f}")
76
+
77
+ print("\nprimary cause of failure: count (DS loss)")
78
+ ca, cb = collections.Counter(), collections.Counter()
79
+ la, lb = collections.Counter(), collections.Counter()
80
+ for S, c, l in ((A, ca, la), (B, cb, lb)):
81
+ for v in S.values():
82
+ if not v["success"]:
83
+ g = group(v["cause"]); c[g] += 1; l[g] += (100 - v["score"]) / n
84
+ for g in sorted(set(ca) | set(cb), key=lambda g: -(la[g] + lb[g])):
85
+ print(f" {g:38s}{ca[g]:4d} ({la[g]:5.2f}){cb[g]:6d} ({lb[g]:5.2f})")
86
+
87
+ fa = {r for r, v in A.items() if not v["success"]}
88
+ fb = {r for r, v in B.items() if not v["success"]}
89
+ print(f"\nfailed in both: {len(fa & fb)} only {na}: {len(fa - fb)} only {nb}: {len(fb - fa)}")
90
+ for title, rs in ((f"newly failing in {na} (succeeded in {nb})", fa - fb), (f"fixed in {na} (failed in {nb})", fb - fa)):
91
+ print(f"\n{title}:")
92
+ for r in sorted(rs, key=lambda r: A[r]["scenario"]):
93
+ print(f" {r:>6s} {A[r]['scenario']:38s} {na}: {A[r]['score']:5.1f} {group(A[r]['cause']) or 'success'}"
94
+ f" {nb}: {B[r]['score']:5.1f} {group(B[r]['cause']) or 'success'}")
95
+ both_same = sum(group(A[r]["cause"]) == group(B[r]["cause"]) for r in fa & fb)
96
+ print(f"\nfailed in both with the same primary cause: {both_same}/{len(fa & fb)}")
97
+
98
+ print("\nper scenario success (only scenarios that differ):")
99
+ sa, sb, tot = collections.Counter(), collections.Counter(), collections.Counter()
100
+ for r in A:
101
+ s = A[r]["scenario"]; tot[s] += 1; sa[s] += A[r]["success"]; sb[s] += B[r]["success"]
102
+ for s in sorted(tot, key=lambda s: sa[s] - sb[s]):
103
+ if sa[s] != sb[s]:
104
+ print(f" {s:42s}{sa[s]:3d}/{tot[s]:<3d}{sb[s]:6d}/{tot[s]:<3d}{sa[s] - sb[s]:+4d}")
105
+
106
+ if args.out:
107
+ json.dump({na: A, nb: B}, open(args.out, "w"), indent=1)
108
+
109
+
110
+ if __name__ == "__main__":
111
+ main()
scripts/analysis/compare_speed_mask.py ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Speed mask (SPEED_MASK_STALL_S=15) vs no mask on the StreamPETR stage-3 model, from repeated 220-route evals.
2
+
3
+ python scripts/analysis/compare_speed_mask.py (run from the repo root; writes eval_results/Bench2Drive/speed_mask_summary.txt)
4
+
5
+ Fixed-benchmark CIs treat the 220 routes as fixed and use only simulator noise: the variance of a run's DS is
6
+ estimated from the per-route variance across repeats (routes are simulated independently). Routes where the
7
+ mask never fired in any mask15 run ran identical inputs in both arms and serve as an A/A control.
8
+ """
9
+ import glob
10
+ import json
11
+ import math
12
+ import re
13
+ from collections import Counter
14
+ from pathlib import Path
15
+
16
+ import numpy as np
17
+
18
+ B = Path("eval_results/Bench2Drive")
19
+ NOMASK = ["sp_ft_det4hz_nomask", "sp_ft_det4hz_nomask_repeat", "sp_ft_det4hz_nomask_run3",
20
+ "sp_ft_det4hz_nomask_run4", "sp_ft_det4hz_nomask_run5"]
21
+ MASK15 = ["sp_ft_det4hz_mask15", "sp_ft_det4hz_mask15_repeat", "sp_ft_det4hz_mask15_run3",
22
+ "sp_ft_det4hz_mask15_run4", "sp_ft_det4hz_mask15_run5"]
23
+ ORACLE = ["fastvlm_stage3_oracle_2026-11-01_07-40-56", "stage3_oracle_repeat_clean"]
24
+ DETV1 = ["tracker_ft_det4hz_mask15", "tracker_ft_det4hz_mask15_repeat"]
25
+ OBSTACLE = ("Construction", "StaticCutIn", "Accident", "HazardAtSideLane", "ParkedObstacle", "VehicleOpensDoor",
26
+ "MergerIntoSlowTraffic", "ParkingExit", "InvadingTurn")
27
+ INFRACTIONS = ["collisions_vehicle", "collisions_layout", "red_light", "stop_infraction", "route_dev",
28
+ "route_timeout", "scenario_timeouts", "outside_route_lanes"]
29
+
30
+
31
+ def route_key(route_id):
32
+ return route_id.replace("RouteScenario_", "").replace("_rep0", "")
33
+
34
+
35
+ def load(path):
36
+ return {route_key(r["route_id"]): r for r in json.load(open(path))["_checkpoint"]["records"]}
37
+
38
+
39
+ def success(r):
40
+ return r["status"] in ("Completed", "Perfect") and all(
41
+ len(v) == 0 for k, v in r["infractions"].items() if k != "min_speed_infractions")
42
+
43
+
44
+ def masked_steps(run):
45
+ steps = {}
46
+ for f in glob.glob(str(B / run / "logs" / "w*.log")):
47
+ route = None
48
+ for line in open(f, errors="ignore"):
49
+ m = re.search(r"Preparing RouteScenario_(\d+)", line)
50
+ if m:
51
+ route = m.group(1)
52
+ m = re.search(r"Speed-masked steps: (\d+)", line)
53
+ if m and route:
54
+ steps[route] = int(m.group(1))
55
+ return steps
56
+
57
+
58
+ R = {n: load(B / n / "merged.json") for n in NOMASK + MASK15 + ORACLE + DETV1}
59
+ R["stage1"] = load("/tmp/s1_view/merged.json")
60
+ keys = sorted(R[NOMASK[0]], key=int)
61
+ scenario = {e["route"]: e["scenario"] for e in json.load(open(B / ORACLE[0] / "analysis" / "report.json"))}
62
+ X = {name: np.array([[R[n][k]["scores"]["score_composed"] for k in keys] for n in runs])
63
+ for name, runs in (("nomask", NOMASK), ("mask15", MASK15), ("oracle", ORACLE), ("detv1", DETV1),
64
+ ("stage1", ["stage1"]))}
65
+ X["sp_all10"] = np.vstack([X["nomask"], X["mask15"]])
66
+ lines = ["# Speed mask after 15 s standstill vs no mask; StreamPETR stage-3 fine-tune "
67
+ "(outputs/fastvlm_stage3_tracker_sp/2026-11-03_16-38-38), sp_v1 detector at 4 Hz, 5 x 220 routes per arm.",
68
+ f"{'run':28s} {'DS':>6s} {'SR':>6s} " + " ".join(
69
+ f"{k.replace('collisions_', 'col_')[:9]:>9s}" for k in INFRACTIONS) + " game_s timed_out"]
70
+ for n in NOMASK + MASK15:
71
+ recs = R[n].values()
72
+ tot = {k: sum(len(r["infractions"].get(k, [])) for r in recs) for k in INFRACTIONS}
73
+ lines.append(f"{n.replace('sp_ft_det4hz_', ''):28s} {np.mean([r['scores']['score_composed'] for r in recs]):6.2f} "
74
+ f"{sum(map(success, recs)) / 2.2:6.2f} " + " ".join(f"{tot[k]:9d}" for k in INFRACTIONS)
75
+ + f" {np.mean([r['meta']['duration_game'] for r in recs]):6.1f}"
76
+ + f" {sum(r['status'] == 'Failed - Agent timed out' for r in recs):9d}")
77
+
78
+ single_sd = {n: math.sqrt(a.var(0, ddof=1).sum()) / 220 for n, a in X.items() if len(a) > 1}
79
+ single_sd["stage1"] = single_sd["sp_all10"]
80
+ lines += ["", "arm runs mean DS sd(run means) single-run sd from per-route variance"]
81
+ for n in ("nomask", "mask15", "sp_all10", "oracle", "detv1"):
82
+ rm = X[n].mean(1)
83
+ lines.append(f"{n:10s} {len(rm):5d} {rm.mean():8.2f} {rm.std(ddof=1):14.2f} {single_sd[n]:10.2f}")
84
+
85
+
86
+ def fixed(a, b):
87
+ m = X[a].mean() - X[b].mean()
88
+ se = math.sqrt(single_sd[a] ** 2 / len(X[a]) + single_sd[b] ** 2 / len(X[b]))
89
+ lines.append(f"{a:9s} - {b:7s} {m:+.2f} fixed-benchmark 95% CI [{m - 1.96 * se:+.2f},{m + 1.96 * se:+.2f}]")
90
+
91
+
92
+ lines.append("")
93
+ for a, b in (("mask15", "nomask"), ("sp_all10", "oracle"), ("sp_all10", "detv1"), ("sp_all10", "stage1"),
94
+ ("oracle", "detv1")):
95
+ fixed(a, b)
96
+
97
+ steps = {n: masked_steps(n) for n in MASK15}
98
+ fired = {k for n in MASK15 for k, v in steps[n].items() if v > 0}
99
+ lines += ["", f"mask fired on {[sum(v > 0 for v in steps[n].values()) for n in MASK15]} routes per run "
100
+ f"({len(fired)} distinct); masked time per run "
101
+ f"{[round(sum(steps[n].values()) / 20) for n in MASK15]} s"]
102
+ diff = X["mask15"].mean(0) - X["nomask"].mean(0)
103
+ groups = {"A/A (never fired)": [i for i, k in enumerate(keys) if k not in fired],
104
+ "fired: junction / yield": [i for i, k in enumerate(keys)
105
+ if k in fired and not any(s in scenario[k] for s in OBSTACLE)],
106
+ "fired: obstacle bypass": [i for i, k in enumerate(keys)
107
+ if k in fired and any(s in scenario[k] for s in OBSTACLE)]}
108
+ rng = np.random.default_rng(0)
109
+ for name, ix in groups.items():
110
+ a, b = X["mask15"][:, ix], X["nomask"][:, ix]
111
+ se = math.sqrt(a.var(0, ddof=1).sum() / len(a) + b.var(0, ddof=1).sum() / len(b)) / 220
112
+ both = np.vstack([a, b])
113
+ obs = abs(a.mean() - b.mean())
114
+ perm = [abs(both[p[:5]].mean() - both[p[5:]].mean()) >= obs - 1e-9
115
+ for p in (rng.permutation(10) for _ in range(20000))]
116
+ lines.append(f"{name:24s} n={len(ix):3d} nomask {b.mean():5.1f} mask15 {a.mean():5.1f} DS contribution "
117
+ f"{diff[ix].sum() / 220:+.2f} +/- {1.96 * se:.2f} run-label permutation p={np.mean(perm):.3f}")
118
+
119
+ lines += ["", "routes with the largest mean difference (mask15 - nomask), scores per run:"]
120
+ order = np.argsort(diff)
121
+ for i in list(order[:8]) + list(order[-8:][::-1]):
122
+ k = keys[i]
123
+ lines.append(f" {k:>6} {scenario[k][:36]:36s} {diff[i]:+6.1f} nomask {X['nomask'][:, i].round().astype(int).tolist()}"
124
+ f" mask15 {X['mask15'][:, i].round().astype(int).tolist()}"
125
+ f" masked_s {[round(steps[n].get(k, 0) / 20) for n in MASK15]}")
126
+
127
+ lines += ["", "per-scenario success over 5 runs (differences >= 3):"]
128
+ count = Counter()
129
+ for k in keys:
130
+ s = scenario[k]
131
+ count[s, "n"] += sum(success(R[n][k]) for n in NOMASK)
132
+ count[s, "m"] += sum(success(R[n][k]) for n in MASK15)
133
+ count[s, "r"] += 5
134
+ for s in sorted({s for s, _ in count}, key=lambda s: count[s, "m"] - count[s, "n"]):
135
+ if abs(count[s, "m"] - count[s, "n"]) >= 3:
136
+ lines.append(f" {s:42s} nomask {count[s, 'n']:2d}/{count[s, 'r']} mask15 {count[s, 'm']:2d}/{count[s, 'r']}")
137
+
138
+ text = "\n".join(lines)
139
+ print(text)
140
+ (B / "speed_mask_summary.txt").write_text(text + "\n")
scripts/analysis/compare_stream_petr.py ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Closed-loop comparison of the StreamPETR perception arms against det_v1 and the oracle (220 routes each).
2
+
3
+ python scripts/analysis/compare_stream_petr.py (run from the repo root; writes eval_results/Bench2Drive/stream_petr_summary.txt)
4
+ """
5
+ import json
6
+ import math
7
+ import statistics
8
+ from pathlib import Path
9
+
10
+ from scipy import stats
11
+
12
+ B = Path("eval_results/Bench2Drive")
13
+
14
+
15
+ def load(p):
16
+ return {r["route_id"]: r for r in json.load(open(p))["_checkpoint"]["records"]}
17
+
18
+
19
+ runs = {
20
+ "stage1": "/tmp/s1_view/merged.json",
21
+ "oracle_full": B / "fastvlm_stage3_oracle_2026-11-01_07-40-56/merged.json",
22
+ "oracle_repeat": B / "stage3_oracle_repeat_clean/merged.json",
23
+ "speeddrop_mask15 (oracle bank)": B / "speeddrop_mask15/merged.json",
24
+ "detv1_ft (coast2)": B / "tracker_ft_det4hz_mask15/merged.json",
25
+ "detv1_ft_repeat": B / "tracker_ft_det4hz_mask15_repeat/merged.json",
26
+ "sp_ft_mask15": B / "sp_ft_det4hz_mask15/merged.json",
27
+ "sp_ft_mask15_repeat": B / "sp_ft_det4hz_mask15_repeat/merged.json",
28
+ "detv1_ft + sp detector (zero-shot)": B / "tracker_ft_spdet4hz_mask15_zeroshot/merged.json",
29
+ "sp_ft_nomask": B / "sp_ft_det4hz_nomask/merged.json",
30
+ "sp_ft_nomask_repeat": B / "sp_ft_det4hz_nomask_repeat/merged.json",
31
+ "sp_ft_nomask_run3": B / "sp_ft_det4hz_nomask_run3/merged.json",
32
+ "sp_ft_nomask_run4": B / "sp_ft_det4hz_nomask_run4/merged.json",
33
+ "sp_ft_nomask_run5": B / "sp_ft_det4hz_nomask_run5/merged.json",
34
+ "sp_ft_mask15_run3": B / "sp_ft_det4hz_mask15_run3/merged.json",
35
+ "sp_ft_mask15_run4": B / "sp_ft_det4hz_mask15_run4/merged.json",
36
+ "sp_ft_mask15_run5": B / "sp_ft_det4hz_mask15_run5/merged.json",
37
+ "nodrop_sp_ft_nomask": B / "nodrop_sp_ft_det4hz_nomask_clean/merged.json",
38
+ }
39
+ MASK15 = ["sp_ft_mask15", "sp_ft_mask15_repeat", "sp_ft_mask15_run3", "sp_ft_mask15_run4", "sp_ft_mask15_run5"]
40
+ NOMASK = ["sp_ft_nomask", "sp_ft_nomask_repeat", "sp_ft_nomask_run3", "sp_ft_nomask_run4", "sp_ft_nomask_run5"]
41
+ R = {k: load(v) for k, v in runs.items()}
42
+ a, b = R["oracle_full"], R["oracle_repeat"]
43
+ ref = {k: (a[k]["scores"]["score_composed"] + b[k]["scores"]["score_composed"]) / 2 for k in a}
44
+ keys = ["collisions_vehicle", "collisions_pedestrian", "collisions_layout", "red_light", "stop_infraction", "route_dev",
45
+ "route_timeout", "scenario_timeouts", "vehicle_blocked"]
46
+ lines = ["# StreamPETR perception (sp_v1, 4 Hz, Kalman tracker coast 2 s) vs det_v1; stage 3 fine-tuned on cross-fitted "
47
+ "tracker banks. DS differences are paired against the mean of the two oracle runs (Wilcoxon, zsplit).",
48
+ f"{'run':36s} {'DS':>6s} {'SR':>6s} {'vs oracle':>18s} {'p':>6s} "
49
+ + " ".join(f"{k.replace('collisions_', 'col_').replace('_infractions', '')[:9]:>9s}" for k in keys) + " game_s"]
50
+
51
+
52
+ def sr(recs):
53
+ return sum(r["status"] in ("Completed", "Perfect") and all(len(v) == 0 for k2, v in r["infractions"].items()
54
+ if k2 != "min_speed_infractions") for r in recs.values()) / 220 * 100
55
+
56
+
57
+ for n, recs in R.items():
58
+ ds = [recs[k]["scores"]["score_composed"] for k in ref]
59
+ d = [recs[k]["scores"]["score_composed"] - ref[k] for k in ref]
60
+ m, se = statistics.mean(d), statistics.stdev(d) / math.sqrt(len(d))
61
+ p = stats.wilcoxon(ds, [ref[k] for k in ref], zero_method="zsplit").pvalue
62
+ tot = {k: sum(len(r["infractions"].get(k, [])) for r in recs.values()) for k in keys}
63
+ gt = statistics.mean(r["meta"]["duration_game"] for r in recs.values())
64
+ 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}] "
65
+ f"{p:6.3f} " + " ".join(f"{tot[k]:9d}" for k in keys) + f" {gt:6.1f}")
66
+ lines.append("")
67
+
68
+
69
+ def pooled(*names):
70
+ return {k: statistics.mean(R[n][k]["scores"]["score_composed"] for n in names) for k in ref}
71
+
72
+
73
+ def diff(nm, x, y):
74
+ d = [x[k] - y[k] for k in ref]
75
+ m, se = statistics.mean(d), statistics.stdev(d) / math.sqrt(len(d))
76
+ p = stats.wilcoxon([x[k] for k in ref], [y[k] for k in ref], zero_method="zsplit").pvalue
77
+ lines.append(f"{nm:44s} {m:+.2f} [{m - 1.96 * se:+.2f},{m + 1.96 * se:+.2f}] p={p:.3f}")
78
+
79
+
80
+ P = dict(sp=pooled(*MASK15), detv1=pooled("detv1_ft (coast2)", "detv1_ft_repeat"),
81
+ oracle=ref, stage1=pooled("stage1"), zs=pooled("detv1_ft + sp detector (zero-shot)"),
82
+ nomask=pooled(*NOMASK), nodrop=pooled("nodrop_sp_ft_nomask"),
83
+ sdrop=pooled("speeddrop_mask15 (oracle bank)"), sp10=pooled(*MASK15, *NOMASK))
84
+ for nm, x in (("sp_ft_mask15 x5", P["sp"]), ("detv1_ft x2", P["detv1"]), ("sp_ft_nomask x5", P["nomask"]),
85
+ ("sp_ft all 10 (mask15 x5 + nomask x5)", P["sp10"])):
86
+ lines.append(f"{nm}: mean DS {statistics.mean(x.values()):.2f}")
87
+ lines.append("route-paired Wilcoxon below (routes as the sampling unit); fixed-benchmark CIs: compare_speed_mask.py")
88
+ diff("sp_ft_mask15 x5 - oracle x2", P["sp"], P["oracle"])
89
+ diff("sp_ft_mask15 x5 - detv1_ft x2", P["sp"], P["detv1"])
90
+ diff("sp_ft_mask15 x5 - speeddrop_mask15 (oracle bank)", P["sp"], P["sdrop"])
91
+ diff("detv1_ft + sp detector zero-shot - sp_ft_mask15 x5", P["zs"], P["sp"])
92
+ diff("sp_ft_nomask x5 - sp_ft_mask15 x5", P["nomask"], P["sp"])
93
+ diff("sp_ft all 10 - oracle x2", P["sp10"], P["oracle"])
94
+ diff("sp_ft all 10 - detv1_ft x2", P["sp10"], P["detv1"])
95
+ diff("sp_ft all 10 - stage1", P["sp10"], P["stage1"])
96
+ diff("nodrop_sp_ft_nomask - sp_ft all 10", P["nodrop"], P["sp10"])
97
+ text = "\n".join(lines)
98
+ print(text)
99
+ (B / "stream_petr_summary.txt").write_text(text + "\n")
scripts/analysis/compare_tracker_finetune.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json, statistics, math
2
+ from scipy import stats
3
+ def load(p): return {r["route_id"]: r for r in json.load(open(p))["_checkpoint"]["records"]}
4
+ runs = {
5
+ "stage1": "/tmp/s1_view/merged.json",
6
+ "oracle_full": "fastvlm_stage3_oracle_2026-11-01_07-40-56/merged.json",
7
+ "oracle_repeat": "stage3_oracle_repeat_clean/merged.json",
8
+ "speeddrop_mask15 (oracle)": "speeddrop_mask15/merged.json",
9
+ "det_zeroshot_20hz (oracle ckpt)": "detector_zeroshot_v1/merged.json",
10
+ "speeddrop_zeroshot_det4hz": "speeddrop_det4hz_mask15_zeroshot/merged.json",
11
+ "ft_coast2": "tracker_ft_det4hz_mask15/merged.json",
12
+ "ft_coast2_repeat": "tracker_ft_det4hz_mask15_repeat/merged.json",
13
+ "ft_coast1": "tracker_ft_coast1_det4hz_mask15/merged.json",
14
+ "ft_coast1_repeat": "tracker_ft_coast1_det4hz_mask15_repeat/merged.json",
15
+ "ft_coast4": "tracker_ft_coast4_det4hz_mask15/merged.json",
16
+ "ft_coast4_repeat": "tracker_ft_coast4_det4hz_mask15_repeat/merged.json",
17
+ }
18
+ R = {k: load(v) for k, v in runs.items()}
19
+ a, b = R["oracle_full"], R["oracle_repeat"]
20
+ ref = {k: (a[k]["scores"]["score_composed"] + b[k]["scores"]["score_composed"]) / 2 for k in a}
21
+ keys = ["collisions_vehicle", "collisions_pedestrian", "collisions_layout", "red_light", "stop_infraction", "route_dev", "route_timeout", "scenario_timeouts", "vehicle_blocked"]
22
+ 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")
23
+ for n, recs in R.items():
24
+ ds = [recs[k]["scores"]["score_composed"] for k in ref]
25
+ d = [recs[k]["scores"]["score_composed"] - ref[k] for k in ref]
26
+ m, se = statistics.mean(d), statistics.stdev(d) / math.sqrt(len(d))
27
+ p = stats.wilcoxon(ds, [ref[k] for k in ref], zero_method="zsplit").pvalue
28
+ 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
29
+ tot = {k: sum(len(r["infractions"].get(k, [])) for r in recs.values()) for k in keys}
30
+ gt = statistics.mean(r["meta"]["duration_game"] for r in recs.values())
31
+ 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}")
32
+ print()
33
+ pooled = {}
34
+ for name, pair in (("coast1", ("ft_coast1", "ft_coast1_repeat")), ("coast2", ("ft_coast2", "ft_coast2_repeat")), ("coast4", ("ft_coast4", "ft_coast4_repeat"))):
35
+ x = {k: (R[pair[0]][k]["scores"]["score_composed"] + R[pair[1]][k]["scores"]["score_composed"]) / 2 for k in ref}
36
+ pooled[name] = x
37
+ d = [x[k] - ref[k] for k in ref]
38
+ m, se = statistics.mean(d), statistics.stdev(d) / math.sqrt(len(d))
39
+ p = stats.wilcoxon([x[k] for k in ref], [ref[k] for k in ref], zero_method="zsplit").pvalue
40
+ col = sum(len(R[q][k]["infractions"]["collisions_vehicle"]) for q in pair for k in ref) / 2
41
+ 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}")
42
+ 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})):
43
+ d = [x[k] - y[k] for k in ref]; m, se = statistics.mean(d), statistics.stdev(d) / math.sqrt(len(d))
44
+ 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}")
scripts/analysis/compare_tracker_offline.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Side-by-side offline tracker metrics (scripts/eval_tracker_offline.py) of several detector runs.
2
+
3
+ python scripts/analysis/compare_tracker_offline.py eval_results/tracker_offline/det_v1_val eval_results/tracker_offline/sp_v1_val
4
+ """
5
+ import json
6
+ import sys
7
+ from pathlib import Path
8
+
9
+ runs = [(Path(p).name, json.load(open(Path(p) / "tracker_metrics.json"))) for p in sys.argv[1:]]
10
+ names = [n for n, _ in runs]
11
+ w = max(12, max(len(n) for n in names) + 2)
12
+ print(f"{'':28s}" + "".join(f"{n:>{w}s}" for n in names))
13
+ print(f"{'frames':28s}" + "".join(f"{d['frames']:>{w}d}" for _, d in runs))
14
+ print(f"{'false tracks / s':28s}" + "".join(f"{d['false_tracks_per_s']:>{w}.3f}" for _, d in runs))
15
+ print(f"{'id switches / 100 matches':28s}" + "".join(f"{d['id_switches_per_100_matches']:>{w}.2f}" for _, d in runs))
16
+ for cls in ("car", "walker", "static"):
17
+ for key in ("recall_visible", "pos_err_med", "vel_err_med"):
18
+ for rb in ("0-10", "10-20", "20-30", "30-40", "40-50"):
19
+ vals = [d[cls][rb].get(key) for _, d in runs]
20
+ if all(v is None for v in vals):
21
+ continue
22
+ print(f"{cls + ' ' + key + ' ' + rb:28s}" + "".join(f"{v:>{w}.3f}" if v is not None else f"{'-':>{w}s}"
23
+ for v in vals))
24
+ for sb in ("0-0.5", "0.5-5", "5-10", "10-20"):
25
+ for key in ("vel_err_med", "vel_err_rms"):
26
+ vals = [d["car_velocity_by_speed"].get(sb, {}).get(key) for _, d in runs]
27
+ print(f"{'car ' + sb + ' m/s ' + key:28s}" + "".join(f"{v:>{w}.3f}" if v is not None else f"{'-':>{w}s}"
28
+ for v in vals))
29
+ tgt = runs[0][1]["car_velocity_by_speed"].get(sb, {}).get("target_sigma")
30
+ if tgt is not None:
31
+ print(f"{' (target sigma)':28s}{tgt:>{w}.3f}")
scripts/analysis/extents.json ADDED
@@ -0,0 +1,370 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "vehicle.audi.a2": [
3
+ 1.853,
4
+ 0.894
5
+ ],
6
+ "vehicle.citroen.c3": [
7
+ 1.994,
8
+ 0.925
9
+ ],
10
+ "vehicle.chevrolet.impala": [
11
+ 2.679,
12
+ 1.017
13
+ ],
14
+ "vehicle.dodge.charger_police_2020": [
15
+ 2.619,
16
+ 0.965
17
+ ],
18
+ "vehicle.micro.microlino": [
19
+ 1.104,
20
+ 0.74
21
+ ],
22
+ "vehicle.dodge.charger_police": [
23
+ 2.487,
24
+ 1.019
25
+ ],
26
+ "vehicle.audi.tt": [
27
+ 2.091,
28
+ 0.997
29
+ ],
30
+ "vehicle.jeep.wrangler_rubicon": [
31
+ 1.933,
32
+ 0.953
33
+ ],
34
+ "vehicle.mercedes.coupe": [
35
+ 2.513,
36
+ 1.076
37
+ ],
38
+ "vehicle.yamaha.yzf": [
39
+ 1.095,
40
+ 0.433
41
+ ],
42
+ "vehicle.mercedes.coupe_2020": [
43
+ 2.337,
44
+ 0.906
45
+ ],
46
+ "vehicle.harley-davidson.low_rider": [
47
+ 1.175,
48
+ 0.383
49
+ ],
50
+ "vehicle.dodge.charger_2020": [
51
+ 2.504,
52
+ 0.941
53
+ ],
54
+ "vehicle.ford.ambulance": [
55
+ 3.183,
56
+ 1.176
57
+ ],
58
+ "vehicle.lincoln.mkz_2020": [
59
+ 2.446,
60
+ 0.918
61
+ ],
62
+ "vehicle.mini.cooper_s_2021": [
63
+ 2.276,
64
+ 1.049
65
+ ],
66
+ "vehicle.ford.crown": [
67
+ 2.683,
68
+ 0.9
69
+ ],
70
+ "vehicle.toyota.prius": [
71
+ 2.257,
72
+ 1.003
73
+ ],
74
+ "vehicle.carlamotors.european_hgv": [
75
+ 3.968,
76
+ 1.446
77
+ ],
78
+ "vehicle.carlamotors.carlacola": [
79
+ 2.602,
80
+ 1.313
81
+ ],
82
+ "vehicle.vespa.zx125": [
83
+ 0.909,
84
+ 0.433
85
+ ],
86
+ "vehicle.nissan.patrol_2021": [
87
+ 2.783,
88
+ 1.075
89
+ ],
90
+ "vehicle.mercedes.sprinter": [
91
+ 2.958,
92
+ 0.994
93
+ ],
94
+ "vehicle.audi.etron": [
95
+ 2.428,
96
+ 1.016
97
+ ],
98
+ "vehicle.seat.leon": [
99
+ 2.096,
100
+ 0.908
101
+ ],
102
+ "vehicle.volkswagen.t2_2021": [
103
+ 2.221,
104
+ 0.887
105
+ ],
106
+ "vehicle.tesla.cybertruck": [
107
+ 3.137,
108
+ 1.195
109
+ ],
110
+ "vehicle.lincoln.mkz_2017": [
111
+ 2.451,
112
+ 1.064
113
+ ],
114
+ "vehicle.carlamotors.firetruck": [
115
+ 4.234,
116
+ 1.446
117
+ ],
118
+ "vehicle.ford.mustang": [
119
+ 2.359,
120
+ 0.947
121
+ ],
122
+ "vehicle.volkswagen.t2": [
123
+ 2.24,
124
+ 1.035
125
+ ],
126
+ "vehicle.mitsubishi.fusorosa": [
127
+ 5.136,
128
+ 1.972
129
+ ],
130
+ "vehicle.tesla.model3": [
131
+ 2.396,
132
+ 1.082
133
+ ],
134
+ "vehicle.diamondback.century": [
135
+ 0.828,
136
+ 0.291
137
+ ],
138
+ "vehicle.gazelle.omafiets": [
139
+ 0.922,
140
+ 0.33
141
+ ],
142
+ "vehicle.bmw.grandtourer": [
143
+ 2.306,
144
+ 1.121
145
+ ],
146
+ "vehicle.bh.crossbike": [
147
+ 0.755,
148
+ 0.433
149
+ ],
150
+ "vehicle.kawasaki.ninja": [
151
+ 1.022,
152
+ 0.398
153
+ ],
154
+ "vehicle.nissan.patrol": [
155
+ 2.302,
156
+ 0.966
157
+ ],
158
+ "vehicle.nissan.micra": [
159
+ 1.817,
160
+ 0.923
161
+ ],
162
+ "vehicle.mini.cooper_s": [
163
+ 1.903,
164
+ 0.985
165
+ ],
166
+ "walker.pedestrian.0013": [
167
+ 0.188,
168
+ 0.188
169
+ ],
170
+ "walker.pedestrian.0027": [
171
+ 0.25,
172
+ 0.25
173
+ ],
174
+ "walker.pedestrian.0008": [
175
+ 0.25,
176
+ 0.25
177
+ ],
178
+ "walker.pedestrian.0006": [
179
+ 0.25,
180
+ 0.25
181
+ ],
182
+ "walker.pedestrian.0035": [
183
+ 0.25,
184
+ 0.25
185
+ ],
186
+ "walker.pedestrian.0001": [
187
+ 0.25,
188
+ 0.25
189
+ ],
190
+ "walker.pedestrian.0002": [
191
+ 0.25,
192
+ 0.25
193
+ ],
194
+ "walker.pedestrian.0004": [
195
+ 0.25,
196
+ 0.25
197
+ ],
198
+ "walker.pedestrian.0011": [
199
+ 0.25,
200
+ 0.25
201
+ ],
202
+ "walker.pedestrian.0037": [
203
+ 0.25,
204
+ 0.25
205
+ ],
206
+ "walker.pedestrian.0005": [
207
+ 0.25,
208
+ 0.25
209
+ ],
210
+ "walker.pedestrian.0009": [
211
+ 0.25,
212
+ 0.25
213
+ ],
214
+ "walker.pedestrian.0010": [
215
+ 0.25,
216
+ 0.25
217
+ ],
218
+ "walker.pedestrian.0026": [
219
+ 0.25,
220
+ 0.25
221
+ ],
222
+ "walker.pedestrian.0014": [
223
+ 0.25,
224
+ 0.25
225
+ ],
226
+ "walker.pedestrian.0045": [
227
+ 0.25,
228
+ 0.25
229
+ ],
230
+ "walker.pedestrian.0015": [
231
+ 0.25,
232
+ 0.25
233
+ ],
234
+ "walker.pedestrian.0016": [
235
+ 0.25,
236
+ 0.25
237
+ ],
238
+ "walker.pedestrian.0038": [
239
+ 0.25,
240
+ 0.25
241
+ ],
242
+ "walker.pedestrian.0041": [
243
+ 0.25,
244
+ 0.25
245
+ ],
246
+ "walker.pedestrian.0043": [
247
+ 0.25,
248
+ 0.25
249
+ ],
250
+ "walker.pedestrian.0042": [
251
+ 0.25,
252
+ 0.25
253
+ ],
254
+ "walker.pedestrian.0044": [
255
+ 0.25,
256
+ 0.25
257
+ ],
258
+ "walker.pedestrian.0020": [
259
+ 0.25,
260
+ 0.25
261
+ ],
262
+ "walker.pedestrian.0039": [
263
+ 0.25,
264
+ 0.25
265
+ ],
266
+ "walker.pedestrian.0022": [
267
+ 0.25,
268
+ 0.25
269
+ ],
270
+ "walker.pedestrian.0046": [
271
+ 0.25,
272
+ 0.25
273
+ ],
274
+ "walker.pedestrian.0017": [
275
+ 0.25,
276
+ 0.25
277
+ ],
278
+ "walker.pedestrian.0034": [
279
+ 0.25,
280
+ 0.25
281
+ ],
282
+ "walker.pedestrian.0040": [
283
+ 0.25,
284
+ 0.25
285
+ ],
286
+ "walker.pedestrian.0003": [
287
+ 0.25,
288
+ 0.25
289
+ ],
290
+ "walker.pedestrian.0051": [
291
+ 0.25,
292
+ 0.25
293
+ ],
294
+ "walker.pedestrian.0047": [
295
+ 0.25,
296
+ 0.25
297
+ ],
298
+ "walker.pedestrian.0048": [
299
+ 0.25,
300
+ 0.25
301
+ ],
302
+ "walker.pedestrian.0049": [
303
+ 0.25,
304
+ 0.25
305
+ ],
306
+ "walker.pedestrian.0050": [
307
+ 0.25,
308
+ 0.25
309
+ ],
310
+ "walker.pedestrian.0031": [
311
+ 0.25,
312
+ 0.25
313
+ ],
314
+ "walker.pedestrian.0028": [
315
+ 0.25,
316
+ 0.25
317
+ ],
318
+ "walker.pedestrian.0033": [
319
+ 0.25,
320
+ 0.25
321
+ ],
322
+ "walker.pedestrian.0030": [
323
+ 0.25,
324
+ 0.25
325
+ ],
326
+ "walker.pedestrian.0007": [
327
+ 0.25,
328
+ 0.25
329
+ ],
330
+ "walker.pedestrian.0036": [
331
+ 0.25,
332
+ 0.25
333
+ ],
334
+ "walker.pedestrian.0029": [
335
+ 0.25,
336
+ 0.25
337
+ ],
338
+ "walker.pedestrian.0012": [
339
+ 0.25,
340
+ 0.25
341
+ ],
342
+ "walker.pedestrian.0025": [
343
+ 0.25,
344
+ 0.25
345
+ ],
346
+ "walker.pedestrian.0024": [
347
+ 0.25,
348
+ 0.25
349
+ ],
350
+ "walker.pedestrian.0021": [
351
+ 0.25,
352
+ 0.25
353
+ ],
354
+ "walker.pedestrian.0019": [
355
+ 0.25,
356
+ 0.25
357
+ ],
358
+ "walker.pedestrian.0023": [
359
+ 0.25,
360
+ 0.25
361
+ ],
362
+ "walker.pedestrian.0032": [
363
+ 0.25,
364
+ 0.25
365
+ ],
366
+ "walker.pedestrian.0018": [
367
+ 0.25,
368
+ 0.25
369
+ ]
370
+ }
scripts/analysis/extract_failed.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Extract recorder kinematics for every finished, failed route of a (possibly still running) eval.
2
+
3
+ Usage: python extract_failed.py RESULT_ROOT --ports 2000,2010,...
4
+ """
5
+ import argparse
6
+ import glob
7
+ import json
8
+ import subprocess
9
+ import sys
10
+ from concurrent.futures import ThreadPoolExecutor
11
+ from pathlib import Path
12
+
13
+ from failure_report import is_success
14
+
15
+ HERE = Path(__file__).resolve().parent
16
+
17
+
18
+ def finished_records(root):
19
+ recs = {}
20
+ for f in glob.glob(f"{root}/bench2drive220_*.json"):
21
+ try:
22
+ data = json.load(open(f))
23
+ except json.JSONDecodeError:
24
+ continue
25
+ for r in data.get("_checkpoint", {}).get("records", []):
26
+ if r.get("status") and r["status"] != "Started":
27
+ recs[r["route_id"]] = r
28
+ return recs
29
+
30
+
31
+ def main():
32
+ ap = argparse.ArgumentParser()
33
+ ap.add_argument("root")
34
+ ap.add_argument("--ports", default="2000")
35
+ args = ap.parse_args()
36
+ root = Path(args.root)
37
+ out_dir = root / "analysis" / "npz"
38
+ recs = finished_records(root)
39
+ todo = []
40
+ for rid, r in recs.items():
41
+ log = root / "recorder" / f"{rid}.log"
42
+ if not is_success(r) and log.exists() and not (out_dir / f"{rid}.npz").exists():
43
+ todo.append(str(log))
44
+ ports = [int(p) for p in args.ports.split(",")]
45
+ print(f"{len(recs)} finished, {len(todo)} failed logs to extract", flush=True)
46
+ chunks = [todo[k::len(ports)] for k in range(len(ports))]
47
+
48
+ def run(k):
49
+ if not chunks[k]:
50
+ return
51
+ subprocess.run([sys.executable, str(HERE / "recorder_extract.py"), "--port", str(ports[k]),
52
+ "--out-dir", str(out_dir), *chunks[k]], check=False)
53
+
54
+ with ThreadPoolExecutor(len(ports)) as ex:
55
+ list(ex.map(run, range(len(ports))))
56
+
57
+
58
+ if __name__ == "__main__":
59
+ main()
scripts/analysis/failure_report.py ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Classify failed Bench2Drive routes and extract collision geometry from recorder kinematics.
2
+
3
+ Usage: python failure_report.py --merged merged.json --routes bench2drive220.xml \
4
+ --npz-dir DIR --extents extents.json --out report.json
5
+ """
6
+ import argparse
7
+ import json
8
+ import math
9
+ import re
10
+ import xml.etree.ElementTree as ET
11
+ from pathlib import Path
12
+
13
+ import carla
14
+ import numpy as np
15
+
16
+ CARLA_MAPS = Path("/workspace/carla0915/CarlaUE4/Content/Carla/Maps")
17
+ HALF_FOV = math.radians(55.0)
18
+ CAM_BACK = 1.5
19
+ EGO_EXTENT = (2.446, 0.918)
20
+ _maps = {}
21
+
22
+
23
+ def get_map(town):
24
+ if town not in _maps:
25
+ for p in (CARLA_MAPS / town / "OpenDrive" / f"{town}.xodr", CARLA_MAPS / "OpenDrive" / f"{town}.xodr"):
26
+ if p.exists():
27
+ _maps[town] = carla.Map(town, p.read_text())
28
+ break
29
+ return _maps[town]
30
+
31
+
32
+ def is_success(rec):
33
+ if rec["status"] not in ("Completed", "Perfect"):
34
+ return False
35
+ return all(not v or k == "min_speed_infractions" for k, v in rec["infractions"].items())
36
+
37
+
38
+ def interp_state(traj, t):
39
+ """traj columns: t, x, y, yaw, (v). Returns x, y, yaw at time t."""
40
+ i = int(np.clip(np.searchsorted(traj[:, 0], t), 1, len(traj) - 1))
41
+ a, b = traj[i - 1], traj[i]
42
+ w = 0.0 if b[0] == a[0] else float(np.clip((t - a[0]) / (b[0] - a[0]), 0, 1))
43
+ dyaw = (b[3] - a[3] + 180) % 360 - 180
44
+ return a[1] + w * (b[1] - a[1]), a[2] + w * (b[2] - a[2]), a[3] + w * dyaw
45
+
46
+
47
+ def corners(x, y, yaw, ext):
48
+ c, s = math.cos(math.radians(yaw)), math.sin(math.radians(yaw))
49
+ 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])]
50
+
51
+
52
+ def in_fov(ego_pose, other_pose, ext):
53
+ ex, ey, eyaw = ego_pose
54
+ c, s = math.cos(math.radians(eyaw)), math.sin(math.radians(eyaw))
55
+ cx, cy = ex - CAM_BACK * c, ey - CAM_BACK * s
56
+ for px, py in corners(*other_pose, ext):
57
+ lx = (px - cx) * c + (py - cy) * s
58
+ ly = -(px - cx) * s + (py - cy) * c
59
+ if lx > 0 and abs(math.atan2(ly, lx)) < HALF_FOV:
60
+ return True
61
+ return False
62
+
63
+
64
+ def to_ego_frame(ego_pose, p):
65
+ ex, ey, eyaw = ego_pose
66
+ c, s = math.cos(math.radians(eyaw)), math.sin(math.radians(eyaw))
67
+ dx, dy = p[0] - ex, p[1] - ey
68
+ return dx * c + dy * s, -dx * s + dy * c
69
+
70
+
71
+ def speed_at(traj, t, dt=0.3):
72
+ a, b = interp_state(traj, t - dt), interp_state(traj, t)
73
+ return math.hypot(b[0] - a[0], b[1] - a[1]) / dt
74
+
75
+
76
+ def last_departure(hero, t_end, window=20.0):
77
+ """Last standstill (>=0.5 s below 0.1 m/s) that ended within `window` s before t_end."""
78
+ v = np.convolve(hero[:, 4], np.ones(5) / 5, "same")
79
+ sel = np.where((hero[:, 0] > t_end - window) & (hero[:, 0] < t_end) & (v < 0.1))[0]
80
+ if not len(sel):
81
+ return None
82
+ k = sel[-1]
83
+ start = k
84
+ while start > 0 and v[start - 1] < 0.1:
85
+ start -= 1
86
+ if hero[k, 0] - hero[start, 0] < 0.5:
87
+ return None
88
+ return {"t_stop": float(hero[start, 0]), "t_depart": float(hero[k, 0]), "x": float(hero[k, 1]), "y": float(hero[k, 2])}
89
+
90
+
91
+ def collision_features(d, town, extents, t_c, other_id):
92
+ hero = d["hero"]
93
+ actors = json.loads(str(d["actors"]))
94
+ otype = actors.get(str(int(other_id)), "?")
95
+ others = d["others"]
96
+ tr = others[others[:, 1] == other_id][:, [0, 2, 3, 4]]
97
+ feat = {"t": round(float(t_c), 2), "other_type": otype}
98
+ ego_c = interp_state(hero, t_c)
99
+ m = get_map(town)
100
+ wp = m.get_waypoint(carla.Location(x=ego_c[0], y=ego_c[1], z=0), project_to_road=True)
101
+ feat["ego_in_junction"] = bool(wp.is_junction)
102
+ feat["ego_speed"] = round(speed_at(hero, t_c - 0.1), 2)
103
+ dep = last_departure(hero, t_c)
104
+ if dep:
105
+ feat["departed_from_stop_s_before"] = round(t_c - dep["t_depart"], 2)
106
+ feat["stop_duration"] = round(dep["t_depart"] - dep["t_stop"], 2)
107
+ feat["dist_since_departure"] = round(float(np.linalg.norm(np.array(ego_c[:2]) - [dep["x"], dep["y"]])), 1)
108
+ loc = carla.Location(x=dep["x"], y=dep["y"], z=0)
109
+ wpd = m.get_waypoint(loc, project_to_road=True)
110
+ signs = wpd.get_landmarks(25.0, False)
111
+ feat["stop_reason"] = sorted({l.type for l in signs if l.type in ("206", "1000001")}) or None
112
+ if len(tr) < 2:
113
+ feat["other_track"] = "missing"
114
+ return feat
115
+ ext = extents.get(otype, (2.4, 1.0))
116
+ t_pre = min(t_c - 0.1, tr[-1, 0])
117
+ oth_c = interp_state(tr, t_pre)
118
+ lx, ly = to_ego_frame(ego_c, oth_c)
119
+ feat["other_rel_xy"] = (round(lx, 1), round(ly, 1))
120
+ feat["rel_heading"] = round(((oth_c[2] - ego_c[2] + 180) % 360) - 180, 0)
121
+ feat["other_speed"] = round(speed_at(tr, t_pre), 2) if tr[0, 0] < t_pre - 0.3 else None
122
+ # Field-of-view history (geometry only, ignores occlusion and fog).
123
+ ts = tr[(tr[:, 0] >= t_c - 15) & (tr[:, 0] <= t_pre), 0]
124
+ vis = [(t, in_fov(interp_state(hero, t), interp_state(tr, t), ext)) for t in ts]
125
+ seen = [t for t, v in vis if v]
126
+ feat["first_tracked_s_before"] = round(t_c - float(tr[0, 0]), 1)
127
+ 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)}
128
+ feat["last_in_fov_s_before"] = round(t_c - max(seen), 2) if seen else None
129
+ feat["fov_time_last15s"] = round(0.1 * len(seen), 1)
130
+ # Warning time: start of the last uninterrupted in-FOV stretch before impact.
131
+ warn = None
132
+ for t, v in reversed(vis):
133
+ if not v:
134
+ break
135
+ warn = t
136
+ feat["warning_s"] = round(t_c - warn, 2) if warn is not None else 0.0
137
+ if dep:
138
+ feat["stop_is_route_start"] = dep["t_stop"] < 1.0
139
+ t_d = dep["t_depart"]
140
+ 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))
141
+ feat["tracked_at_departure"] = bool(tr[0, 0] <= t_d)
142
+ # Was the other actor parked and then started (scenario-triggered)?
143
+ sp = [speed_at(tr, t) for t in ts[ts > ts[0] + 0.3]] if len(ts) > 3 else []
144
+ feat["other_started_from_rest"] = bool(sp and min(sp[: max(1, len(sp) // 2)]) < 0.3 and max(sp) > 3)
145
+ return feat
146
+
147
+
148
+ MSG_RE = re.compile(r"type=(\S+) and id=(\d+) at \(x=([-\d.]+), y=([-\d.]+)")
149
+
150
+
151
+ def collision_time(d, other_id, x, y):
152
+ """Recorder collision time with this actor if logged, else when the ego passed the reported location."""
153
+ coll = d["collisions"]
154
+ hit = coll[coll[:, 1] == other_id]
155
+ if len(hit):
156
+ return float(hit[0, 0])
157
+ hero = d["hero"]
158
+ dist = np.hypot(hero[:, 1] - x, hero[:, 2] - y)
159
+ close = np.where(dist < 1.0)[0]
160
+ return float(hero[close[0], 0] if len(close) else hero[np.argmin(dist), 0])
161
+
162
+
163
+ def classify_collision(f):
164
+ lx, ly = f.get("other_rel_xy", (None, None))
165
+ if lx is None:
166
+ return "unknown"
167
+ rh = abs(f.get("rel_heading", 0))
168
+ if f["other_type"].startswith("walker."):
169
+ return "pedestrian"
170
+ if lx > 0 and f.get("other_speed") is not None and f["other_speed"] < 0.5:
171
+ return "ego hits stationary vehicle"
172
+ if lx < -1.5 and rh < 45:
173
+ return "rear-ended by other"
174
+ if lx > 1.5 and rh < 45:
175
+ return "ego hits vehicle ahead (same direction)"
176
+ if rh > 135 and abs(ly) < 3.0:
177
+ return "head-on"
178
+ if 45 <= rh <= 135 or (f.get("ego_in_junction") and rh > 30):
179
+ return "crossing"
180
+ return "side-swipe / lane change"
181
+
182
+
183
+ def main():
184
+ ap = argparse.ArgumentParser()
185
+ ap.add_argument("--merged", required=True)
186
+ ap.add_argument("--routes", required=True)
187
+ ap.add_argument("--npz-dir", required=True)
188
+ ap.add_argument("--extents", required=True)
189
+ ap.add_argument("--out", required=True)
190
+ args = ap.parse_args()
191
+ extents = {k: tuple(v) for k, v in json.load(open(args.extents)).items()}
192
+ meta = {}
193
+ for r in ET.parse(args.routes).iter("route"):
194
+ meta[r.attrib["id"]] = {"town": r.attrib["town"], "scenario": [s.attrib["type"] for s in r.iter("scenario")][0]}
195
+ recs = json.load(open(args.merged))["_checkpoint"]["records"]
196
+ report = []
197
+ for rec in recs:
198
+ rid = rec["route_id"].split("_")[1]
199
+ entry = {"route": rid, **meta[rid], "status": rec["status"], "score": rec["scores"]["score_composed"],
200
+ "success": is_success(rec),
201
+ "infractions": {k: v for k, v in rec["infractions"].items() if v and k != "min_speed_infractions"}}
202
+ if not entry["success"]:
203
+ npz = Path(args.npz_dir) / f"RouteScenario_{rid}_rep0.npz"
204
+ if npz.exists():
205
+ d = np.load(npz, allow_pickle=False)
206
+ feats = []
207
+ for kind in ("collisions_vehicle", "collisions_pedestrian", "collisions_layout"):
208
+ for msg in rec["infractions"].get(kind, []):
209
+ m = MSG_RE.search(msg)
210
+ if not m:
211
+ continue
212
+ otype, oid, cx, cy = m.group(1), int(m.group(2)), float(m.group(3)), float(m.group(4))
213
+ t_c = collision_time(d, oid, cx, cy)
214
+ others = d["others"]
215
+ if kind != "collisions_layout" and np.any(others[:, 1] == oid):
216
+ f = collision_features(d, meta[rid]["town"], extents, t_c, oid)
217
+ f["class"] = classify_collision(f)
218
+ else:
219
+ f = {"t": round(t_c, 2), "other_type": otype, "class": "static object / layout",
220
+ "ego_speed": round(speed_at(d["hero"], t_c - 0.1), 2)}
221
+ f["kind"] = kind
222
+ f["other_id"] = oid
223
+ feats.append(f)
224
+ entry["collisions"] = feats
225
+ entry["duration"] = round(float(d["hero"][-1, 0]), 1)
226
+ else:
227
+ entry["collisions"] = "no recorder log"
228
+ report.append(entry)
229
+ json.dump(report, open(args.out, "w"), indent=1)
230
+ n_fail = sum(not e["success"] for e in report)
231
+ print(f"{len(report)} routes, {len(report) - n_fail} success, {n_fail} failed -> {args.out}")
232
+
233
+
234
+ if __name__ == "__main__":
235
+ main()
scripts/analysis/fixability.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Route-level fixability of failed routes under S1 (creep after a junction standstill) / S2 (memory-gated creep).
2
+
3
+ A collision counts as visibility-limited when the partner was continuously in the front-camera FOV for
4
+ < 1.5 s before impact. It is fixed by a strategy when the multi-actor reactive replay (cf_reactive.py)
5
+ avoids the partner without hitting any recorded actor for every (v_cap, tau) setting. A route is fixable
6
+ when every infraction other than route deviation / min speed is a collision that is fixed, or that happens
7
+ after a fixed collision inside its replay window. Route deviation is ignored by request.
8
+
9
+ Usage: python fixability.py ANALYSIS_DIR
10
+ """
11
+ import collections
12
+ import json
13
+ import sys
14
+
15
+ import numpy as np
16
+
17
+ IGNORED = {"route_dev", "min_speed_infractions"}
18
+ COLLISIONS = {"collisions_vehicle", "collisions_pedestrian", "collisions_layout"}
19
+ AVOIDED = {"passed", "passed_after_recording", "partner_avoided"}
20
+ VIS_LIMIT_S = 1.5
21
+ REAR_THREAT_SCENARIOS = {"ParkingExit"}
22
+
23
+
24
+ def verdict(sims):
25
+ if not sims:
26
+ return None
27
+ good = [v["outcome"] in AVOIDED for v in sims.values()]
28
+ return "fixed" if all(good) else ("fragile" if any(good) else "no")
29
+
30
+
31
+ def classify_route(e, cf, npz_dir):
32
+ infr = {k: len(v) for k, v in e["infractions"].items() if v and k not in IGNORED}
33
+ if not infr:
34
+ return "deviation only (ignored)", []
35
+ if set(infr) - COLLISIONS - {"collisions_vehicle"}:
36
+ return "non-collision: " + "/".join(sorted(set(infr) - COLLISIONS)), []
37
+ if e["scenario"] in REAR_THREAT_SCENARIOS:
38
+ return "not addressed: threat from behind", []
39
+ rec_end = float(np.load(f"{npz_dir}/RouteScenario_{e['route']}_rep0.npz")["hero"][-1, 0])
40
+ per, seen = [], set()
41
+ for c in sorted(e["collisions"], key=lambda c: c["t"]):
42
+ key = (c.get("other_id"), round(c["t"], 1))
43
+ if key in seen:
44
+ continue
45
+ seen.add(key)
46
+ r = cf.get((e["route"], c.get("other_id"), round(c["t"], 2)), {})
47
+ per.append({"t": c["t"], "class": c["class"], "other": c["other_type"], "warning_s": c.get("warning_s"),
48
+ "vis_limited": c["class"] != "static object / layout" and c.get("warning_s", 99) < VIS_LIMIT_S,
49
+ "S1": verdict(r.get("S1")), "S2": verdict(r.get("S2"))})
50
+ first_fix = next((p for p in per if p["vis_limited"] and "fixed" in (p["S1"], p["S2"])), None)
51
+ for p in per:
52
+ if p["vis_limited"] and p["S1"] == "fixed":
53
+ p["status"] = "S1"
54
+ elif p["vis_limited"] and p["S2"] == "fixed":
55
+ p["status"] = "S2"
56
+ elif p["vis_limited"] and "fragile" in (p["S1"], p["S2"]):
57
+ p["status"] = "fragile"
58
+ elif first_fix and first_fix["t"] < p["t"] <= rec_end:
59
+ p["status"] = "covered"
60
+ else:
61
+ p["status"] = "no"
62
+ st = [p["status"] for p in per]
63
+ if all(s in ("S1", "covered") for s in st):
64
+ return "S1 fixes", per
65
+ if all(s in ("S1", "S2", "covered") for s in st):
66
+ return "S2 fixes", per
67
+ if all(s in ("S1", "S2", "covered", "fragile") for s in st):
68
+ return "S1/S2 fragile", per
69
+ p = per[st.index("no")]
70
+ if p["class"] == "static object / layout" or p["class"].startswith("ego hits"):
71
+ return "not addressed: ego hits lead/stationary/static object", per
72
+ if p["class"] == "pedestrian":
73
+ return "not addressed: pedestrian", per
74
+ if not p["vis_limited"]:
75
+ return f"not addressed: partner visible >= {VIS_LIMIT_S} s but not yielded to", per
76
+ return "not addressed: visibility-limited, creep does not help (lane change/merge/flow)", per
77
+
78
+
79
+ def main():
80
+ adir = sys.argv[1]
81
+ report = json.load(open(f"{adir}/report.json"))
82
+ cf = {(r["route"], r["other_id"], round(r["t"], 2)): r for r in json.load(open(f"{adir}/cf_reactive.json"))}
83
+ out = collections.defaultdict(list)
84
+ for e in report:
85
+ if not e["success"]:
86
+ cat, per = classify_route(e, cf, f"{adir}/npz")
87
+ out[cat].append({"route": e["route"], "scenario": e["scenario"], "collisions": per})
88
+ json.dump(out, open(f"{adir}/fixability.json", "w"), indent=1, default=float)
89
+ for k in sorted(out):
90
+ print(f"{len(out[k]):3d} {k}: {' '.join(r['route'] for r in out[k])}")
91
+ print(f"{sum(map(len, out.values()))} failed routes -> {adir}/fixability.json")
92
+
93
+
94
+ if __name__ == "__main__":
95
+ main()
scripts/analysis/recorder_extract.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Extract compact kinematics from CARLA recorder logs.
2
+
3
+ Usage: python recorder_extract.py --port 2000 --out-dir DIR log1.log [log2.log ...]
4
+
5
+ For each log writes DIR/<log stem>.npz with
6
+ hero: (T, 5) t, x, y, yaw_deg, speed
7
+ hero_ctrl: (T, 4) t, steer, throttle, brake
8
+ collisions: (K, 2) t, other_id (only collisions involving the hero)
9
+ actors: JSON string {id: type_id}
10
+ others: (N, 5) t, id, x, y, yaw_deg (vehicles/walkers within 80 m of the hero, 10 Hz)
11
+ Positions are in metres (the recorder stores centimetres).
12
+ """
13
+ import argparse
14
+ import json
15
+ import math
16
+ import re
17
+ from pathlib import Path
18
+
19
+ import carla
20
+ import numpy as np
21
+
22
+ FRAME_RE = re.compile(r"^Frame \d+ at ([\d.]+) seconds")
23
+ CREATE_RE = re.compile(r"^ Create (\d+): (\S+) \(\d+\) at")
24
+ ATTR_RE = re.compile(r"^\s+role_name = (\S+)")
25
+ POS_RE = re.compile(r"^ Id: (\d+) Location: \(([-+\d.e]+), ([-+\d.e]+), ([-+\d.e]+)\) Rotation: \(([-+\d.e]+), ([-+\d.e]+), ([-+\d.e]+)\)")
26
+ CTRL_RE = re.compile(r"^ Id: (\d+) Steering: ([-+\d.e]+) Throttle: ([-+\d.e]+) Brake: ([-+\d.e]+)")
27
+ COLL_RE = re.compile(r"^ Collision id \d+ between (\d+)(?: \((\w+)\))?\s+with (\d+)(?: \((\w+)\))?")
28
+ KEEP_PREFIX = ("vehicle.", "walker.")
29
+
30
+
31
+ def extract(text):
32
+ types, roles = {}, {}
33
+ hero = None
34
+ frames = []
35
+ cur_create = None
36
+ t = None
37
+ pos, ctrl, colls = {}, {}, []
38
+ for line in text.splitlines():
39
+ m = FRAME_RE.match(line)
40
+ if m:
41
+ if t is not None:
42
+ frames.append((t, pos, ctrl))
43
+ t, pos, ctrl, cur_create = float(m.group(1)), {}, {}, None
44
+ continue
45
+ if line.startswith(" Id: "):
46
+ m = POS_RE.match(line)
47
+ if m:
48
+ pos[int(m.group(1))] = (float(m.group(2)) / 100, float(m.group(3)) / 100, float(m.group(7)))
49
+ continue
50
+ m = CTRL_RE.match(line)
51
+ if m:
52
+ ctrl[int(m.group(1))] = (float(m.group(2)), float(m.group(3)), float(m.group(4)))
53
+ continue
54
+ m = CREATE_RE.match(line)
55
+ if m:
56
+ cur_create = int(m.group(1))
57
+ types[cur_create] = m.group(2)
58
+ continue
59
+ m = ATTR_RE.match(line)
60
+ if m and cur_create is not None:
61
+ roles[cur_create] = m.group(1)
62
+ if m.group(1) == "hero" and types.get(cur_create, "").startswith("vehicle."):
63
+ hero = cur_create
64
+ continue
65
+ m = COLL_RE.match(line)
66
+ if m and t is not None:
67
+ a, b = int(m.group(1)), int(m.group(3))
68
+ colls.append((t, a, b))
69
+ if t is not None:
70
+ frames.append((t, pos, ctrl))
71
+
72
+ hero_rows, ctrl_rows, other_rows = [], [], []
73
+ last = None
74
+ next_other_t = -1.0
75
+ for t, pos, ctrl in frames:
76
+ if hero not in pos:
77
+ continue
78
+ x, y, yaw = pos[hero]
79
+ v = 0.0 if last is None or t <= last[0] else math.hypot(x - last[1], y - last[2]) / (t - last[0])
80
+ hero_rows.append((t, x, y, yaw, v))
81
+ last = (t, x, y)
82
+ if hero in ctrl:
83
+ ctrl_rows.append((t,) + ctrl[hero])
84
+ if t >= next_other_t:
85
+ next_other_t = t + 0.1 - 1e-6
86
+ for aid, (ax, ay, ayaw) in pos.items():
87
+ if aid == hero or not types.get(aid, "").startswith(KEEP_PREFIX):
88
+ continue
89
+ if math.hypot(ax - x, ay - y) < 80.0:
90
+ other_rows.append((t, aid, ax, ay, ayaw))
91
+ hero_colls = [(t, b if a == hero else a) for t, a, b in colls if hero in (a, b)]
92
+ return {
93
+ "hero": np.array(hero_rows, dtype=np.float64),
94
+ "hero_ctrl": np.array(ctrl_rows, dtype=np.float64).reshape(-1, 4),
95
+ "collisions": np.array(hero_colls, dtype=np.float64).reshape(-1, 2),
96
+ "others": np.array(other_rows, dtype=np.float64).reshape(-1, 5),
97
+ "actors": json.dumps({str(k): v for k, v in types.items()}),
98
+ "hero_id": hero,
99
+ }
100
+
101
+
102
+ def main():
103
+ ap = argparse.ArgumentParser()
104
+ ap.add_argument("--port", type=int, default=2000)
105
+ ap.add_argument("--out-dir", required=True)
106
+ ap.add_argument("logs", nargs="+")
107
+ args = ap.parse_args()
108
+ out_dir = Path(args.out_dir)
109
+ out_dir.mkdir(parents=True, exist_ok=True)
110
+ client = carla.Client("localhost", args.port)
111
+ client.set_timeout(600.0)
112
+ for log in args.logs:
113
+ log = Path(log).resolve()
114
+ out = out_dir / (log.stem + ".npz")
115
+ if out.exists():
116
+ continue
117
+ data = extract(client.show_recorder_file_info(str(log), True))
118
+ np.savez_compressed(out, **data)
119
+ print(f"{log.stem}: hero={data['hero_id']} frames={len(data['hero'])} "
120
+ f"collisions={len(data['collisions'])} others={len(data['others'])}", flush=True)
121
+
122
+
123
+ if __name__ == "__main__":
124
+ main()
scripts/analysis/recorder_traffic_lights.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Extract traffic-light locations and state changes from CARLA recorder logs.
2
+
3
+ Usage: python recorder_traffic_lights.py --port 2000 --out-dir DIR [--workers 4] log1.log [log2.log ...]
4
+
5
+ For each log writes DIR/<log stem>_tl.npz with
6
+ tl_ids: (L,) recorder actor ids of traffic lights
7
+ tl_locs: (L, 2) x, y in metres
8
+ changes: (C, 3) t, tl_id, state (state: 0 red, 1 yellow, 2 green, 3 off, 4 unknown; first row per light
9
+ is its state in the first recorded frame)
10
+ """
11
+ import argparse
12
+ import re
13
+ from multiprocessing import Pool
14
+ from pathlib import Path
15
+
16
+ import carla
17
+ import numpy as np
18
+
19
+ FRAME_RE = re.compile(r"^Frame \d+ at ([\d.]+) seconds")
20
+ CREATE_RE = re.compile(r"^ Create (\d+): traffic\.traffic_light \(\d+\) at \(([-+\d.e]+), ([-+\d.e]+), ([-+\d.e]+)\)")
21
+ STATE_RE = re.compile(r"^ Id: (\d+) state: (\d+) frozen")
22
+
23
+ PORT = None
24
+
25
+
26
+ def extract(text):
27
+ locs, last, changes = {}, {}, []
28
+ t = None
29
+ for line in text.splitlines():
30
+ if line.startswith("Frame "):
31
+ m = FRAME_RE.match(line)
32
+ if m:
33
+ t = float(m.group(1))
34
+ continue
35
+ if line.startswith(" Id: ") and " state: " in line:
36
+ m = STATE_RE.match(line)
37
+ if m and t is not None:
38
+ tl, state = int(m.group(1)), int(m.group(2))
39
+ if last.get(tl) != state:
40
+ last[tl] = state
41
+ changes.append((t, tl, state))
42
+ continue
43
+ if line.startswith(" Create ") and "traffic_light" in line:
44
+ m = CREATE_RE.match(line)
45
+ if m:
46
+ locs[int(m.group(1))] = (float(m.group(2)) / 100, float(m.group(3)) / 100)
47
+ ids = np.array(sorted(locs), dtype=np.int64)
48
+ return {
49
+ "tl_ids": ids,
50
+ "tl_locs": np.array([locs[i] for i in ids], dtype=np.float64).reshape(-1, 2),
51
+ "changes": np.array(changes, dtype=np.float64).reshape(-1, 3),
52
+ }
53
+
54
+
55
+ def work(job):
56
+ log, out = job
57
+ client = carla.Client("localhost", PORT, worker_threads=2)
58
+ client.set_timeout(600.0)
59
+ data = extract(client.show_recorder_file_info(str(log), True))
60
+ np.savez_compressed(out, **data)
61
+ return f"{log.stem}: {len(data['tl_ids'])} lights, {len(data['changes'])} state changes"
62
+
63
+
64
+ def init(port):
65
+ global PORT
66
+ PORT = port
67
+
68
+
69
+ def main():
70
+ ap = argparse.ArgumentParser()
71
+ ap.add_argument("--port", type=int, default=2000)
72
+ ap.add_argument("--out-dir", required=True)
73
+ ap.add_argument("--workers", type=int, default=4)
74
+ ap.add_argument("logs", nargs="+")
75
+ args = ap.parse_args()
76
+ out_dir = Path(args.out_dir)
77
+ out_dir.mkdir(parents=True, exist_ok=True)
78
+ jobs = []
79
+ for log in args.logs:
80
+ log = Path(log).resolve()
81
+ out = out_dir / f"{log.stem}_tl.npz"
82
+ if not out.exists():
83
+ jobs.append((log, out))
84
+ with Pool(args.workers, initializer=init, initargs=(args.port,)) as pool:
85
+ for msg in pool.imap_unordered(work, jobs):
86
+ print(msg, flush=True)
87
+
88
+
89
+ if __name__ == "__main__":
90
+ main()
scripts/analysis/stall_reasons.py ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Classify why the ego was standing still, from recorder kinematics + traffic-light states.
2
+
3
+ Usage: python stall_reasons.py --merged merged.json --npz-dir DIR --tl-dir DIR --stoplines stoplines.json
4
+ --out stalls.json
5
+
6
+ For every stop (speed < 0.1 m/s for >= MIN_STOP_S) the ego's actually driven path after the stop is taken as
7
+ the path it should have driven. Every 0.5 s of the stop is labelled
8
+ blocked a vehicle/walker is on that path (within 22 m) now or within the next 3 s (recorded future)
9
+ red_light a same-direction stop line on the path belongs to a red/yellow light
10
+ stop_sign the ego is inside a stop-sign trigger and has been stopped for < 4 s
11
+ free none of the above: nothing required the ego to wait
12
+ and the stop records how long it had been continuously free when the ego finally moved.
13
+ """
14
+ import argparse
15
+ import json
16
+ import math
17
+
18
+ import numpy as np
19
+
20
+ MIN_STOP_S = 3.0
21
+ STEP_S = 0.5
22
+ PATH_LEN = 25.0
23
+ CONFLICT_S = (2.5, 22.0) # arc length range from the ego centre (excludes vehicles behind)
24
+ LATERAL = {"vehicle": 2.0, "walker": 1.5}
25
+ LOOKAHEAD_S = 3.0
26
+ STOP_SIGN_WAIT_S = 4.0
27
+ CREEP_THROTTLE = 0.4
28
+
29
+
30
+ def future_path(hero, i_end):
31
+ """Driven path from the stop position, resampled every 0.5 m; straight ahead if the ego never moved again."""
32
+ x0, y0, yaw0 = hero[i_end, 1], hero[i_end, 2], math.radians(hero[i_end, 3])
33
+ pts = [(x0, y0)]
34
+ dist = 0.0
35
+ for x, y in hero[i_end + 1:, 1:3]:
36
+ step = math.hypot(x - pts[-1][0], y - pts[-1][1])
37
+ if step < 0.25:
38
+ continue
39
+ pts.append((x, y))
40
+ dist += step
41
+ if dist >= PATH_LEN:
42
+ break
43
+ if dist < 5.0:
44
+ pts = [(x0 + s * math.cos(yaw0), y0 + s * math.sin(yaw0)) for s in np.arange(0, PATH_LEN, 0.5)]
45
+ pts = np.array(pts)
46
+ seg = np.hypot(*np.diff(pts, axis=0).T)
47
+ s = np.concatenate([[0.0], np.cumsum(seg)])
48
+ grid = np.arange(0.0, min(s[-1], PATH_LEN) + 1e-6, 0.5)
49
+ path = np.stack([np.interp(grid, s, pts[:, 0]), np.interp(grid, s, pts[:, 1])], axis=1)
50
+ heading = np.arctan2(*np.gradient(path, axis=0)[:, ::-1].T) if len(path) > 1 else np.array([yaw0])
51
+ return path, grid, heading
52
+
53
+
54
+ def project(points, path, grid):
55
+ d = np.hypot(points[:, None, 0] - path[None, :, 0], points[:, None, 1] - path[None, :, 1])
56
+ j = d.argmin(axis=1)
57
+ return d[np.arange(len(points)), j], grid[j], j
58
+
59
+
60
+ def tl_state_fn(tl):
61
+ changes = tl["changes"]
62
+ by_id = {}
63
+ for t, i, s in changes:
64
+ by_id.setdefault(int(i), []).append((t, int(s)))
65
+
66
+ def state(tl_id, t):
67
+ seq = by_id.get(tl_id)
68
+ if not seq:
69
+ return 4
70
+ k = np.searchsorted([c[0] for c in seq], t, side="right") - 1
71
+ return seq[max(k, 0)][1]
72
+
73
+ return state
74
+
75
+
76
+ def analyse_route(z, tl, lights, signs):
77
+ hero, ctrl, others = z["hero"], z["hero_ctrl"], z["others"]
78
+ types = json.loads(str(z["actors"]))
79
+ kinds = {int(k): ("walker" if v.startswith("walker.") else "vehicle") for k, v in types.items()}
80
+ t, v = hero[:, 0], hero[:, 4]
81
+ state = tl_state_fn(tl)
82
+ # recorder ids of the town's traffic lights (match by location)
83
+ rec_ids = tl["tl_ids"].astype(int)
84
+ rec_locs = tl["tl_locs"]
85
+ stop_lines = []
86
+ for light in lights:
87
+ if len(rec_locs) == 0:
88
+ break
89
+ d = np.hypot(*(rec_locs - np.array(light["loc"])).T)
90
+ if d.min() < 1.0:
91
+ for x, y, yaw, _, _ in light["stops"]:
92
+ stop_lines.append((x, y, math.radians(yaw), int(rec_ids[d.argmin()])))
93
+ stop_lines = np.array(stop_lines) if stop_lines else np.zeros((0, 4))
94
+ signs = np.array(signs) if signs else np.zeros((0, 4))
95
+
96
+ stopped = v < 0.1
97
+ edges = np.diff(np.concatenate([[0], stopped.astype(int), [0]]))
98
+ starts, ends = np.nonzero(edges == 1)[0], np.nonzero(edges == -1)[0] - 1
99
+ moved_before = np.concatenate([[0.0], np.cumsum(np.hypot(*np.diff(hero[:, 1:3], axis=0).T))])
100
+ out = []
101
+ for i0, i1 in zip(starts, ends):
102
+ t0, t1 = max(t[i0], 2.5), t[i1]
103
+ if t1 - t0 < MIN_STOP_S:
104
+ continue
105
+ path, grid, heading = future_path(hero, i1)
106
+ # actors on the path now or within LOOKAHEAD_S
107
+ sel = (others[:, 0] >= t0) & (others[:, 0] <= t1 + LOOKAHEAD_S)
108
+ rows = others[sel]
109
+ conflict_t = np.zeros(0)
110
+ if len(rows):
111
+ d, s, _ = project(rows[:, 2:4], path, grid)
112
+ lat = np.array([LATERAL[kinds.get(int(i), "vehicle")] for i in rows[:, 1]])
113
+ hit = (d < lat) & (s >= CONFLICT_S[0]) & (s <= CONFLICT_S[1])
114
+ conflict_t = rows[hit, 0]
115
+ # same-direction stop lines on the path
116
+ lines = []
117
+ if len(stop_lines):
118
+ d, s, j = project(stop_lines[:, :2], path, grid)
119
+ dyaw = np.abs((stop_lines[:, 2] - heading[j] + np.pi) % (2 * np.pi) - np.pi)
120
+ ok = (d < 2.5) & (s <= 20.0) & (dyaw < math.radians(45))
121
+ lines = sorted({int(i) for i in stop_lines[ok, 3]})
122
+ in_sign = bool(len(signs)) and bool(np.any(
123
+ np.hypot(signs[:, 0] - hero[i0, 1], signs[:, 1] - hero[i0, 2]) < np.maximum(signs[:, 2], signs[:, 3]) + 2.0))
124
+ labels = []
125
+ for ts in np.arange(t0, t1, STEP_S):
126
+ if np.any((conflict_t >= ts) & (conflict_t <= ts + LOOKAHEAD_S)):
127
+ labels.append("blocked")
128
+ elif any(state(i, ts) in (0, 1) for i in lines):
129
+ labels.append("red_light")
130
+ elif in_sign and ts - t0 < STOP_SIGN_WAIT_S:
131
+ labels.append("stop_sign")
132
+ else:
133
+ labels.append("free")
134
+ free_run = 0
135
+ for lab in reversed(labels):
136
+ if lab != "free":
137
+ break
138
+ free_run += 1
139
+ departed = i1 + 1 < len(hero)
140
+ dep_ctrl = ctrl[(ctrl[:, 0] > t1 - 0.1) & (ctrl[:, 0] < t1 + 0.8)]
141
+ creep = departed and t1 - t0 >= 39.0 and len(dep_ctrl) > 0 and np.any(np.abs(dep_ctrl[:, 2] - CREEP_THROTTLE) < 1e-3)
142
+ dep_conflict = bool(np.any((conflict_t >= t1) & (conflict_t <= t1 + LOOKAHEAD_S)))
143
+ counts = {k: labels.count(k) * STEP_S for k in ("blocked", "red_light", "stop_sign", "free")}
144
+ out.append(dict(
145
+ t0=round(float(t0), 2), t1=round(float(t1), 2), duration=round(float(t1 - t0), 2),
146
+ route_start=bool(moved_before[i0] < 1.0), ended=("creep" if creep else "policy" if departed else "route_end"),
147
+ first=labels[0], free_run_s=free_run * STEP_S, departed_into_conflict=dep_conflict, **counts))
148
+ return out
149
+
150
+
151
+ def main():
152
+ ap = argparse.ArgumentParser()
153
+ ap.add_argument("--merged", required=True)
154
+ ap.add_argument("--npz-dir", required=True)
155
+ ap.add_argument("--tl-dir", required=True)
156
+ ap.add_argument("--stoplines", required=True)
157
+ ap.add_argument("--out", required=True)
158
+ args = ap.parse_args()
159
+ towns = {r["route_id"]: r["town_name"] for r in json.load(open(args.merged))["_checkpoint"]["records"]}
160
+ stoplines = json.load(open(args.stoplines))
161
+ result = {}
162
+ for rid, town in sorted(towns.items()):
163
+ z = np.load(f"{args.npz_dir}/{rid}.npz", allow_pickle=True)
164
+ tl = np.load(f"{args.tl_dir}/{rid}_tl.npz")
165
+ result[rid] = analyse_route(z, tl, stoplines.get(town, []), stoplines.get(f"{town}/stop_signs", []))
166
+ json.dump(result, open(args.out, "w"), indent=1)
167
+ stops = [s for v in result.values() for s in v]
168
+ print(f"{len(stops)} stops >= {MIN_STOP_S}s in {len(result)} routes")
169
+
170
+
171
+ if __name__ == "__main__":
172
+ main()
scripts/analysis/stall_summary.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Summarise stall_reasons.py output for several runs.
2
+
3
+ Usage: python stall_summary.py NAME=stalls.json [NAME=stalls.json ...]
4
+ """
5
+ import json
6
+ import sys
7
+
8
+ FREE_RUNS = (5, 10, 20)
9
+
10
+ print(f"{'run':10s} {'stops':>5s} {'stopped_s':>9s} {'free_s':>7s} {'blocked_s':>9s} {'red_s':>6s} "
11
+ + " ".join(f"{'free>=' + str(k):>8s}" for k in FREE_RUNS)
12
+ + f" {'start_free>=5':>13s} {'creep':>5s} {'creep_free':>10s} {'creep_conf':>10s} {'end_stopped':>11s}")
13
+ for arg in sys.argv[1:]:
14
+ name, path = arg.split("=", 1)
15
+ stalls = json.load(open(path))
16
+ stops = [s for v in stalls.values() for s in v]
17
+ creeps = [s for s in stops if s["ended"] == "creep"]
18
+ 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} "
19
+ f"{sum(s['blocked'] for s in stops):9.0f} {sum(s['red_light'] for s in stops):6.0f} "
20
+ + " ".join(f"{sum(s['free_run_s'] >= k for s in stops):8d}" for k in FREE_RUNS)
21
+ + f" {sum(s['route_start'] and s['free_run_s'] >= 5 for s in stops):13d} {len(creeps):5d}"
22
+ f" {sum(s['free_run_s'] >= 5 for s in creeps):10d} {sum(s['departed_into_conflict'] for s in creeps):10d}"
23
+ f" {sum(s['ended'] == 'route_end' for s in stops):11d}")