File size: 52,036 Bytes
314ecfb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
import pickle as pkl
import warnings
from pprint import PrettyPrinter
from typing import Optional, Tuple

import pytorch_lightning as pl
import torch
from torch import Tensor, nn
from torchvision.models import ResNet18_Weights, resnet18

try:
    from deepspeed.ops.adam import FusedAdam
except ModuleNotFoundError:
    FusedAdam = None

from models.adaptors.adaptors import (
    AdaptorList, DrivingAdaptor, VectorInputAdaptor, WaypointInputAdaptor
)
from models.utils import configure_params_groups, summarise_losses
from models.plan_consequence import (
    PlanConditionedConsequenceHead,
    PooledPlanConsequenceHead,
    aggregate_risk_logits,
    binary_waypoint_loss,
    clearance_waypoint_loss,
    expand_scene_for_plans,
    make_hard_negative_plans,
    pairwise_ranking_loss,
    relative_min_clearance_hinge,
    trajectory_geometry_targets,
    visible_obstacle_mask,
)
from models.world_predictor import (
    BlockCausalWorldPredictor, linear_world_weight, masked_world_l1
)
from utils.custom_types import (
    DrivingExample, DrivingInput, DrivingLabel, ParamGroup, TrainingOutput
)

pprint = PrettyPrinter().pprint

class RouteEncode(nn.Module):
    def __init__(self, out_channels: int, pretrained=True):
        super().__init__()
        self.backbone = resnet18(weights=ResNet18_Weights.IMAGENET1K_V1 if pretrained else None)
        self.backbone.fc = nn.Linear(self.backbone.fc.in_features, out_channels)

    def forward(self, route):
        x = route.to(self.backbone.fc.weight.dtype) / 128.0 - 1.0
        return self.backbone(x).unsqueeze(-2)  # add token dim

class NormZeroOne(nn.Module):
    def __init__(self, min_max: Tuple[float, float]):
        super().__init__()
        self.register_buffer("min_max", torch.tensor(min_max, dtype=torch.float), persistent=False)

    def forward(self, x: Tensor) -> Tensor:
        """Normalise tensor to [0, 1] using values from min_max"""
        return (x - self.min_max[0]) / (self.min_max[1] - self.min_max[0])


class DrivingModel(pl.LightningModule):
    def __init__(
        self,
        vision_model: nn.Module,
        language_model: nn.Module,
        lr: float = 1e-4,
        vision_lr: Optional[float] = None,
        lm_lr: Optional[float] = None,
        weight_decay: float = 0.1,
        betas: Tuple[float, float] = (0.9, 0.999),
        pct_start: float = 0.05,
        enable_language=False,
        route_as=True,
        speed_as_input=True,
        new_layer_norm_minmax=False,
        predict_route_as_wps=False,
        speed_wps_mode=False,
        waypoint_loss_fn: str = "mse",
        smooth_l1_beta: float = 1.0,
        variant=None,
        nav_p_both: float = 0.4,
        nav_p_command: float = 0.4,
        nav_p_tp: float = 0.2,
        jepa=None,
        consequence=None,
        vision_freeze_steps: int = 0,
        vision_ramp_steps: int = 0,
        speed_dropout_p: float = 0.0,
    ):
        super().__init__()

        self.save_hyperparameters(ignore=["vision_model", "language_model"])
        self.vision_model = vision_model
        self.language_model = language_model
        self.lr = lr
        self.vision_lr = vision_lr
        # optional separate LR for the LM trunk (pretrained-init small trunks
        # want a lower LR than freshly initialised adaptors/heads)
        self.lm_lr = lm_lr
        self.weight_decay = weight_decay
        self.betas = betas
        self.pct_start = pct_start
        self.enable_language = enable_language
        self.route_as = route_as
        self.speed_as_input = speed_as_input
        self.new_layer_norm_minmax = new_layer_norm_minmax
        self.predict_route_as_wps = predict_route_as_wps
        self.speed_wps_mode = speed_wps_mode
        self.waypoint_loss_fn = waypoint_loss_fn
        self.smooth_l1_beta = smooth_l1_beta
        # three-state navigation dropout probabilities (both / command-only / tp-only)
        self.nav_probs = (nav_p_both, nav_p_command, nav_p_tp)
        # training: hide the ego-speed token from this fraction of samples, so the policy can also act from
        # the scene alone (the agent masks it while stalled to escape the v = 0 attractor of the speed input)
        self.speed_dropout_p = float(speed_dropout_p)
        self.vision_freeze_steps = int(vision_freeze_steps)
        self.vision_ramp_steps = int(vision_ramp_steps)

        self.all_predictions = {}
        self.all_losses = {}

        # V-JEPA2 world-model supervision on latent action queries
        self.use_world_loss = bool(jepa is not None and jepa.get("enabled", False))
        latent_tokens = 0
        if self.use_world_loss:
            self.latent_steps = int(jepa.get("latent_steps", 3))
            self.latent_tokens_per_step = int(jepa.get("latent_tokens_per_step", 8))
            latent_tokens = self.latent_steps * self.latent_tokens_per_step
            self.world_loss_weight = float(jepa.get("world_loss_weight", 0.1))
            self.world_loss_warmup_steps = int(jepa.get("world_loss_warmup_steps", 0))

        driving = DrivingAdaptor(
            self.language_model.hidden_size, 
            speed_wps_mode=speed_wps_mode,
            predict_route_as_wps=predict_route_as_wps,
            waypoint_loss_fn=waypoint_loss_fn,
            smooth_l1_beta=smooth_l1_beta,
            latent_tokens=latent_tokens,
        )
        
        self.adaptors = AdaptorList(
            driving=driving,
        )

        self.world_predictor = None
        if self.use_world_loss:
            self.world_predictor = BlockCausalWorldPredictor(
                action_dim=self.language_model.hidden_size,
                predictor_dim=int(jepa.get("predictor_dim", 1024)),
                target_dim=int(jepa.get("teacher_dim", 1024)),
                depth=int(jepa.get("predictor_depth", 12)),
                heads=int(jepa.get("predictor_heads", 8)),
                mlp_ratio=float(jepa.get("predictor_mlp_ratio", 4.0)),
                dropout=float(jepa.get("predictor_dropout", 0.0)),
                num_blocks=self.latent_steps,
                state_tokens=64,
                action_tokens=self.latent_tokens_per_step,
            )

        # Explicit-plan consequence head.  It is intentionally absent from
        # forward(); only forward_loss invokes it during training/validation.
        self.use_consequence_loss = bool(
            consequence is not None and consequence.get("enabled", False)
        )
        self.consequence_cfg = consequence or {}
        self.consequence_head = None
        # "pooled" = ConsDrive v2 head (BCE risk logits + ranking supervision);
        # "cross_attn" = ConsDrive v4 head (clearance regression + L_avoid);
        # "cross_attn_risk" = ConsDrive v6: v4's cross-attention architecture
        # trained with v2's BCE + ranking supervision.
        self.consequence_head_type = str(
            self.consequence_cfg.get("head_type", "cross_attn")
        )
        if self.consequence_head_type not in ("pooled", "cross_attn", "cross_attn_risk"):
            raise ValueError(
                "consequence.head_type must be 'pooled', 'cross_attn', or "
                "'cross_attn_risk'"
            )
        if self.use_consequence_loss:
            if self.consequence_head_type == "pooled":
                self.consequence_head = PooledPlanConsequenceHead(
                    scene_dim=self.language_model.hidden_size,
                    hidden_dim=int(self.consequence_cfg.get("hidden_dim", 256)),
                    plan_dim=int(self.consequence_cfg.get("plan_dim", 128)),
                    horizon=10,
                    route_points=20,
                    dropout=float(self.consequence_cfg.get("dropout", 0.1)),
                )
            else:
                self.consequence_head = PlanConditionedConsequenceHead(
                    scene_dim=self.language_model.hidden_size,
                    hidden_dim=int(self.consequence_cfg.get("hidden_dim", 256)),
                    plan_dim=int(self.consequence_cfg.get("plan_dim", 128)),
                    horizon=10,
                    route_points=20,
                    dropout=float(self.consequence_cfg.get("dropout", 0.1)),
                    attn_heads=int(self.consequence_cfg.get("attn_heads", 4)),
                    with_risk_head=(self.consequence_head_type == "cross_attn_risk"),
                )

        if self.speed_as_input:
            if self.new_layer_norm_minmax:
                min_max = (0.0, 110.0 / 3.6)
            else:
                min_max = (0.0, 64.0 / 3.6)
            self.speed_encoder = VectorInputAdaptor(
                input_size=1,
                token_size=self.language_model.hidden_size,
                hidden_size=256,
                norm_layer=NormZeroOne(min_max=min_max),
            )

        if route_as in ('coords', 'target_point', 'command_tp'):
            if self.new_layer_norm_minmax:
                min_max = (-200.0, 200.0)
            else:
                min_max = (-32.0, 32.0)
            self.route_encoder = WaypointInputAdaptor(
                token_size=self.language_model.hidden_size,
                hidden_size=256,
                norm_layer=NormZeroOne(min_max=min_max),
            )
        elif route_as == 'command':
            self.route_encoder = None
        else:
            self.route_encoder = RouteEncode(self.language_model.hidden_size, pretrained=True)

        # Whether the vision encoder provides DeepStack features (Qwen3-VL)
        self.use_deepstack = hasattr(self.vision_model, "num_deepstack_layers")

        self.language_projection = nn.Identity()
        if self.vision_model.token_size != self.language_model.hidden_size:
            self.language_projection = nn.Linear(self.vision_model.token_size, self.language_model.hidden_size, bias=False)


        # action-only models (from-scratch LM) have no tokenizer
        self.tok = getattr(self.language_model, "tokenizer", None)
        if self.tok is not None:
            self.bos_token_id = self.tok.bos_token_id
            self.eos_token_id = self.tok.eos_token_id
            self.pad_token_id = self.tok.pad_token_id
        else:
            self.bos_token_id = None
            self.eos_token_id = None
            self.pad_token_id = None

    def forward(self,
        driving_input: DrivingInput,
        prompt_ids: Optional[Tensor] = None,
        return_context: bool = False):
        """
        Samples a trajectory from the model.

        With ``return_context=True`` the LM vision-token sequence used by the
        consequence head is returned so deployment-time plan scoring can reuse
        the same backbone pass.
        """
        self.speed_wps, self.route, self.target_speed = None, None, None

        # single forward pass same as during training so we can use the same function
        inputs = self.adaptors(driving_input)
        if return_context:
            features, vision_tokens, vision_mask = self.forward_model(
                driving_input, inputs["inputs"], return_context=True
            )
        else:
            features = self.forward_model(driving_input, inputs["inputs"])
        predictions = self.adaptors.driving.get_predictions(features)

        for k, v in predictions.items():
            if v is not None:
                setattr(self, k, v)

        if return_context:
            return self.speed_wps, self.route, vision_tokens, vision_mask
        return self.speed_wps, self.route

    @staticmethod
    def _pool_scene_context(vision_tokens: Tensor, vision_mask: Tensor) -> Tensor:
        """Masked mean over LM vision-token outputs (the v2 scene feature)."""
        mask = vision_mask.to(
            device=vision_tokens.device, dtype=vision_tokens.dtype
        )
        return (vision_tokens * mask.unsqueeze(-1)).sum(dim=1) / mask.sum(
            dim=1, keepdim=True
        ).clamp_min(1.0)

    def score_plan_risk(
        self,
        vision_tokens: Tensor,
        vision_mask: Tensor,
        route: Tensor,
        speed_wps: Tensor,
    ):
        """Score candidate plans with the trained consequence head.

        Returns per-waypoint collision probabilities ``[B, 10]`` and signed
        clearance estimates ``[B, 10]`` in metres.  The pooled (v2) head
        supervises calibrated risk logits directly; the cross-attention (v4)
        head only regresses clearance, so its risk is a sigmoid squash.
        """
        if self.consequence_head is None:
            raise RuntimeError(
                "score_plan_risk requires a checkpoint trained with the "
                "consequence head enabled"
            )
        if self.consequence_head_type == "pooled":
            scene_context = self._pool_scene_context(vision_tokens, vision_mask)
            output = self.consequence_head(
                scene_context.float(), route.float(), speed_wps.float()
            )
            return (
                torch.sigmoid(output.risk_logits.float()),
                output.clearance.float(),
            )
        output = self.consequence_head(
            vision_tokens.float(),
            vision_mask,
            route.float(),
            speed_wps.float(),
        )
        if self.consequence_head_type == "cross_attn_risk":
            return (
                torch.sigmoid(output.risk_logits.float()),
                output.clearance.float(),
            )
        tau = max(float(self.consequence_cfg.get("risk_temperature", 1.0)), 1e-6)
        risk = torch.sigmoid(-output.clearance.float() / tau)
        return risk, output.clearance.float()


    def forward_model(self, 
                      driving_input: DrivingInput, 
                      adaptor_embeds: Tensor, 
                      driving_labels: DrivingLabel = None,
                      return_context: bool = False,
                      ):
        """
        Forward model conditioned on the given driving input.
        """

        vision_embeds, attention_mask, aux = self.get_fixed_input_embeds(driving_input)

        input_embeds = torch.cat((vision_embeds, adaptor_embeds), dim=1)
        adaptor_attention_mask = torch.ones(
            adaptor_embeds.shape[:2],
            dtype=torch.long,
            device=adaptor_embeds.device,
        )
        if attention_mask is not None:
            attention_mask = torch.cat((attention_mask, adaptor_attention_mask), dim=1)
        # to dtype of language model
        input_embeds = input_embeds.to(
            dtype=self.language_model.model.dtype
        )

        lm_kwargs = {}
        if self.use_deepstack:
            total_len = input_embeds.size(1)
            visual_pos_masks = torch.zeros(
                input_embeds.shape[:2], dtype=torch.bool, device=input_embeds.device
            )
            visual_pos_masks[:, : aux["vision_mask"].size(1)] = aux["vision_mask"]
            # flatten deepstack features in batch-major order at valid vision positions
            deepstack_visual_embeds = [
                feat[aux["vision_mask"]] for feat in aux["deepstack_embeds"]
            ]
            lm_kwargs["visual_pos_masks"] = visual_pos_masks
            lm_kwargs["deepstack_visual_embeds"] = deepstack_visual_embeds
            lm_kwargs["position_ids"] = self._build_mrope_position_ids(
                aux["video_grid_thw"], total_len, input_embeds.device
            )

        outputs = self.language_model.forward(
            input_embeds,
            attention_mask=attention_mask,
            **lm_kwargs,
        )

        vision_outputs, adaptor_outputs = outputs.split(
            [outputs.size(1) - adaptor_embeds.size(1), adaptor_embeds.size(1)], dim=1
        )
        if return_context:
            vision_mask = attention_mask[:, :vision_outputs.size(1)]
            return adaptor_outputs, vision_outputs, vision_mask
        return adaptor_outputs

    def _build_mrope_position_ids(self, video_grid_thw: Tensor, total_len: int, device) -> Tensor:
        """
        Interleaved-MRoPE position ids [3, B, total_len] following Qwen3-VL's
        get_rope_index: every temporal frame of the video is treated as its own
        grid (t=1), text/extra tokens get sequential positions on all 3 axes.
        """
        merge = self.vision_model.spatial_merge_size
        position_ids = torch.zeros(3, video_grid_thw.shape[0], total_len, dtype=torch.long, device=device)

        for batch_idx in range(video_grid_thw.shape[0]):
            grid_t, grid_h, grid_w = (int(x) for x in video_grid_thw[batch_idx])
            llm_h, llm_w = grid_h // merge, grid_w // merge
            pos_list = []
            current_pos = 0
            for _ in range(grid_t):
                t_grid, h_grid, w_grid = torch.meshgrid(
                    torch.zeros(1, dtype=torch.long, device=device),
                    torch.arange(llm_h, device=device),
                    torch.arange(llm_w, device=device),
                    indexing="ij",
                )
                frame_pos = torch.stack([t_grid, h_grid, w_grid], dim=0).reshape(3, -1) + current_pos
                pos_list.append(frame_pos)
                current_pos += max(llm_h, llm_w)
            vision_pos = torch.cat(pos_list, dim=1)
            n_vision = vision_pos.size(1)
            n_text = total_len - n_vision
            text_pos = (torch.arange(n_text, device=device) + current_pos).view(1, -1).expand(3, -1)
            position_ids[:, batch_idx] = torch.cat([vision_pos, text_pos], dim=1)

        return position_ids

    def get_fixed_input_embeds(self, driving_input: DrivingInput):
        img = driving_input.camera_images #[:, 0, :, :, :] # only use the front camera

        aux = {}
        if self.use_deepstack:
            vision_embeds, vision_mask_bool, deepstack_embeds = self.vision_model.forward(
                img, image_sizes=driving_input.image_sizes
            )
            attention_mask = vision_mask_bool.to(device=vision_embeds.device, dtype=torch.long)
            video_grid_thw = driving_input.image_sizes
            if video_grid_thw.ndim == 3:
                video_grid_thw = video_grid_thw.reshape(-1, 3)
            aux["vision_mask"] = vision_mask_bool
            aux["deepstack_embeds"] = [self.language_projection(f) for f in deepstack_embeds]
            aux["video_grid_thw"] = video_grid_thw
        else:
            vision_embeds, vision_aux = self.vision_model.forward(img, image_sizes=driving_input.image_sizes)
            if isinstance(vision_aux, torch.Tensor) and vision_aux.ndim == 2:
                attention_mask = vision_aux.to(device=vision_embeds.device, dtype=torch.long)
            else:
                attention_mask = torch.ones(
                    vision_embeds.shape[:2],
                    dtype=torch.long,
                    device=vision_embeds.device,
                )

        # n_frames, n_tokens, channels = sizes
        vision_embeds = self.language_projection(vision_embeds)
        extra_embeds = []
        extra_attention_masks = []
        if self.speed_as_input:
            vehicle_speed = driving_input.vehicle_speed
            # a NaN speed means "unknown": the token is masked out of attention like a dropped nav token
            speed_known = torch.isfinite(vehicle_speed).all(dim=-1)
            speed = self.speed_encoder.forward(torch.nan_to_num(vehicle_speed, nan=0.0))
            if self.training and self.speed_dropout_p > 0:
                speed_known = speed_known & (torch.rand(speed_known.shape, device=speed_known.device)
                                             >= self.speed_dropout_p)
            extra_embeds.append(speed.to(dtype=vision_embeds.dtype))
            extra_attention_masks.append(
                speed_known.to(device=speed.device, dtype=torch.long).unsqueeze(1).expand(speed.shape[:2])
            )

        if self.route_as == 'command_tp':
            batch_size = vision_embeds.size(0)
            device = vision_embeds.device
            # target-point tokens [B, 2, C]
            tp_embeds = self.route_encoder.forward(driving_input.map_route)
            tp_mask = torch.ones(tp_embeds.shape[:2], dtype=torch.long, device=device)
            # command tokens [B, Lc, C]
            cmd_embeds, cmd_mask = self.encode_navigation_command(
                driving_input.navigation_command, device=device
            )
            # three-state conditional dropout during training:
            # both (p0) / command-only (p1) / tp-only (p2); inference keeps both
            if self.training:
                p_both, p_cmd, _ = self.nav_probs
                r = torch.rand(batch_size, device=device)
                drop_tp = (r >= p_both) & (r < p_both + p_cmd)   # command-only
                drop_cmd = r >= p_both + p_cmd                   # tp-only
                tp_mask = tp_mask * (~drop_tp).long().unsqueeze(1)
                cmd_mask = cmd_mask * (~drop_cmd).long().unsqueeze(1)
            extra_embeds.append(tp_embeds.to(dtype=vision_embeds.dtype))
            extra_attention_masks.append(tp_mask)
            extra_embeds.append(cmd_embeds.to(dtype=vision_embeds.dtype))
            extra_attention_masks.append(cmd_mask)
        elif self.route_as == 'command':
            route, route_attention_mask = self.encode_navigation_command(
                driving_input.navigation_command,
                device=vision_embeds.device,
            )
            extra_embeds.append(route.to(dtype=vision_embeds.dtype))
            extra_attention_masks.append(route_attention_mask)
        else:
            map_route = driving_input.map_route
            route = self.route_encoder.forward(map_route)
            extra_embeds.append(route.to(dtype=vision_embeds.dtype))
            extra_attention_masks.append(
                torch.ones(route.shape[:2], dtype=torch.long, device=route.device)
            )

        # free-form instruction prompt (used by Action Dreaming samples)
        prompt = getattr(driving_input, "prompt", None)
        if prompt is not None and any(len(p) > 0 for p in prompt):
            prompt_embeds, prompt_mask = self.encode_navigation_command(
                ["" if p is None else p for p in prompt],
                device=vision_embeds.device,
            )
            extra_embeds.append(prompt_embeds.to(dtype=vision_embeds.dtype))
            extra_attention_masks.append(prompt_mask)

        input_embeds = torch.cat((vision_embeds, *extra_embeds), dim=1)
        extra_attention_mask = torch.cat(extra_attention_masks, dim=1)
        attention_mask = torch.cat((attention_mask, extra_attention_mask), dim=1)

        return input_embeds, attention_mask, aux

    def encode_navigation_command(self, commands, device):
        embed_tokens = getattr(self.language_model, "embed_tokens", None)
        if embed_tokens is None:
            embed_tokens = getattr(self.language_model.model, "embed_tokens", None)
        if embed_tokens is None:
            raise ValueError("Text conditioning requires a language model with token embeddings.")

        commands = ["" if c is None else c for c in commands]
        # tokenizer requires non-empty batch entries; empty strings yield zero-length rows,
        # pad them with the pad token and mask everything out
        tokens = self.language_model.tokenizer(
            list(commands),
            padding=True,
            truncation=True,
            return_tensors="pt",
        )
        input_ids = tokens["input_ids"].to(device)
        attention_mask = tokens["attention_mask"].to(device=device, dtype=torch.long)
        if input_ids.numel() == 0:
            pad_id = self.language_model.tokenizer.pad_token_id
            input_ids = torch.full((len(commands), 1), pad_id, dtype=torch.long, device=device)
            attention_mask = torch.zeros((len(commands), 1), dtype=torch.long, device=device)
        embeds = embed_tokens(input_ids)
        return embeds, attention_mask

    def forward_loss(self, example: DrivingExample, per_sample=False) -> TrainingOutput:
        """
        Forward pass of the model for a driving input, followed by
        computing the next token cross-entropy loss.

        Args:
            driving_input: input to the vision encoder.
            text_ids: Text ids tensor of shape [B, T]. These are input to the model and used in the loss.
            text_mask: Text mask tensor of shape [B, T].
        """

        adaptor_dict = self.adaptors(example)
        adaptor_embeds = adaptor_dict["inputs"]

        if self.use_consequence_loss:
            adaptor_outputs, vision_tokens, vision_mask = self.forward_model(
                example.driving_input,
                adaptor_embeds,
                driving_labels=example.driving_label,
                return_context=True,
            )
        else:
            adaptor_outputs = self.forward_model(
                example.driving_input,
                adaptor_embeds,
                driving_labels=example.driving_label,
            )
            vision_tokens = vision_mask = None
        loss_dict = self.adaptors.compute_loss(adaptor_outputs, adaptor_dict, example)
        latent_features = loss_dict.pop("latent_features", None)

        if self.use_consequence_loss:
            route_prediction = loss_dict.get("route_prediction")
            speed_prediction = loss_dict.get("speed_wps_prediction")
            if route_prediction is None or speed_prediction is None:
                raise ValueError(
                    "consequence loss requires predict_route_as_wps=True and "
                    "speed_wps_mode='2d'"
                )
            loss_dict.update(
                self.compute_consequence_losses(
                    vision_tokens,
                    vision_mask,
                    route_prediction,
                    speed_prediction,
                    example.driving_label,
                )
            )

        loss_dict_only_losses = {k:v for k, v in loss_dict.items() if k.endswith("loss")}
        pred_labels = {k:v for k, v in loss_dict.items() if not k.endswith("loss")}

        if self.use_world_loss and latent_features is not None:
            loss_dict_only_losses["world_loss"] = self.compute_world_loss(
                latent_features, example.driving_label
            )

        if per_sample:
            return loss_dict_only_losses, pred_labels

        return summarise_losses(loss_dict_only_losses)

    def compute_consequence_losses(
        self,
        vision_tokens: Tensor,
        vision_mask: Tensor,
        predicted_route: Tensor,
        predicted_speed: Tensor,
        label: DrivingLabel,
    ):
        """Dispatch to the head-specific consequence supervision."""
        if self.consequence_head is None or label.future_obstacles is None:
            return {}
        if self.consequence_head_type in ("pooled", "cross_attn_risk"):
            return self._compute_consequence_losses_risk(
                vision_tokens, vision_mask, predicted_route, predicted_speed, label
            )
        return self._compute_consequence_losses_cross_attn(
            vision_tokens, vision_mask, predicted_route, predicted_speed, label
        )

    def _make_consequence_head_call(self, vision_tokens: Tensor, vision_mask: Tensor):
        """Uniform head invocation for the risk-supervised head variants.

        Returns ``head_call(routes, speeds, num_plans=1)``: candidate plans are
        laid out batch-major ([b0p0..b0pK, b1p0..]), matching both the pooled
        scene expansion and ``expand_scene_for_plans``.
        """
        head = self.consequence_head
        if self.consequence_head_type == "pooled":
            scene_context = self._pool_scene_context(vision_tokens, vision_mask)

            def head_call(routes, speeds, num_plans: int = 1):
                if num_plans == 1:
                    return head(scene_context, routes, speeds)
                batch = scene_context.size(0)
                expanded = (
                    scene_context[:, None]
                    .expand(-1, num_plans, -1)
                    .reshape(batch * num_plans, -1)
                )
                return head(expanded, routes, speeds)

            return head_call

        def head_call(routes, speeds, num_plans: int = 1):
            if num_plans == 1:
                return head(vision_tokens, vision_mask, routes, speeds)
            tokens, mask = expand_scene_for_plans(
                vision_tokens, vision_mask, num_plans
            )
            return head(tokens, mask, routes, speeds)

        return head_call

    def _compute_consequence_losses_risk(
        self,
        vision_tokens: Tensor,
        vision_mask: Tensor,
        predicted_route: Tensor,
        predicted_speed: Tensor,
        label: DrivingLabel,
    ):
        """ConsDrive v2 supervision: BCE risk + clearance + hard-negative
        ranking (+ Action Dreaming terms when dreamer labels exist).  Shared
        by the pooled (v2/v5) and cross_attn_risk (v6) heads."""
        cfg = self.consequence_cfg
        head_call = self._make_consequence_head_call(vision_tokens, vision_mask)

        gt_route = label.route_adjusted
        gt_speed = label.waypoints[:, :10]
        predicted = head_call(predicted_route, predicted_speed)
        ground_truth = head_call(gt_route, gt_speed)
        batch_size = predicted_route.size(0)
        device = predicted_route.device

        obstacles = label.future_obstacles.to(device=device)
        obstacle_valid = label.future_obstacle_valid.to(device=device)
        step_valid = label.future_obstacle_step_valid.to(device=device)
        ego_radius = float(cfg.get("ego_radius", 0.9))
        max_clearance = float(cfg.get("max_clearance", 20.0))
        pred_risk_target, pred_clearance_target, geometry_valid = (
            trajectory_geometry_targets(
                predicted_speed.detach(),
                obstacles,
                obstacle_valid,
                step_valid,
                ego_radius=ego_radius,
                max_clearance=max_clearance,
            )
        )

        risk_pos_weight = float(cfg.get("risk_pos_weight", 1.0))
        risk_values, risk_counts = binary_waypoint_loss(
            predicted.risk_logits,
            pred_risk_target,
            geometry_valid,
            pos_weight=risk_pos_weight,
        )
        clearance_values, clearance_counts = clearance_waypoint_loss(
            predicted.clearance,
            pred_clearance_target,
            geometry_valid,
            beta=float(cfg.get("clearance_beta", 1.0)),
        )

        # Dataset targets anchor the GT plan.  They include exact future-box
        # geometry when available and explicit hazard-only fallback otherwise.
        gt_risk_values, gt_risk_counts = binary_waypoint_loss(
            ground_truth.risk_logits,
            label.consequence_risk_target.to(device=device),
            label.consequence_risk_valid.to(device=device),
            pos_weight=risk_pos_weight,
        )
        gt_clearance_values, gt_clearance_counts = clearance_waypoint_loss(
            ground_truth.clearance,
            label.consequence_clearance_target.to(device=device),
            label.consequence_clearance_valid.to(device=device),
            beta=float(cfg.get("clearance_beta", 1.0)),
        )

        rank_values = predicted.risk_logits.float().sum(dim=1) * 0.0
        rank_counts = torch.zeros(batch_size, dtype=torch.long, device=device)
        complete_geometry = step_valid.all(dim=1)
        if bool(complete_geometry.any()):
            rank_parts = []
            count_parts = []
            for base_route, base_speed, base_output in (
                (predicted_route, predicted_speed, predicted),
                (gt_route, gt_speed, ground_truth),
            ):
                values, counts = self._consequence_ranking_for_plan(
                    head_call,
                    base_route,
                    base_speed,
                    base_output.risk_logits,
                    obstacles,
                    obstacle_valid,
                    step_valid,
                )
                rank_parts.append(values)
                count_parts.append(counts)
            stacked_counts = torch.stack(count_parts, dim=1)
            stacked_values = torch.stack(rank_parts, dim=1)
            rank_counts = (stacked_counts.sum(dim=1) > 0).long()
            rank_values = (
                (stacked_values * stacked_counts).sum(dim=1)
                / stacked_counts.sum(dim=1).clamp_min(1)
            )

        # Action Dreaming safety terms are only defined when dreamer labels
        # exist (use_dreamer=True); otherwise they contribute zero counts.
        dream_values = predicted.risk_logits.float().sum(dim=1) * 0.0
        dream_counts = torch.zeros(batch_size, dtype=torch.long, device=device)
        if (
            label.safe_to_execute is not None
            and label.safe_to_execute_valid is not None
            and label.is_dreamer is not None
        ):
            dream_valid = (
                label.safe_to_execute_valid.to(device=device)
                & label.is_dreamer.to(device=device)
            )
            dream_target = (~label.safe_to_execute.to(device=device)).float()
            # The safety flag labels the selected Dreamer trajectory, not the
            # model's still-imperfect prediction of that trajectory.
            dream_logits = aggregate_risk_logits(ground_truth.risk_logits)
            dream_loss = torch.nn.functional.binary_cross_entropy_with_logits(
                dream_logits, dream_target, reduction="none"
            )
            dream_values = dream_loss * dream_valid.float()
            dream_counts = dream_valid.long()

        dream_pair_values = predicted.risk_logits.float().sum(dim=1) * 0.0
        dream_pair_counts = torch.zeros(
            batch_size, dtype=torch.long, device=device
        )
        if label.dream_pair_valid is not None:
            pair_valid = label.dream_pair_valid.to(device=device, dtype=torch.bool)
            if bool(pair_valid.any()):
                safe_output = head_call(
                    label.dream_safe_route.to(device=device),
                    label.dream_safe_speed.to(device=device),
                )
                unsafe_output = head_call(
                    label.dream_unsafe_route.to(device=device),
                    label.dream_unsafe_speed.to(device=device),
                )
                dream_pair_values, dream_pair_counts = pairwise_ranking_loss(
                    safe_output.risk_logits,
                    unsafe_output.risk_logits[:, None],
                    pair_valid[:, None],
                    margin=float(cfg.get("negative_margin", 0.5)),
                )

        warmup_steps = int(cfg.get("warmup_steps", 0))
        if self.training and warmup_steps > 0 and getattr(self, "_trainer", None) is not None:
            warmup = min((int(self.global_step) + 1) / warmup_steps, 1.0)
        else:
            warmup = 1.0
        global_weight = float(cfg.get("loss_weight", 0.1)) * warmup

        def weighted(values, name):
            return values * global_weight * float(cfg.get(name, 1.0))

        return {
            "consequence_risk_loss": (
                weighted(risk_values, "risk_weight"),
                risk_counts,
            ),
            "consequence_gt_risk_loss": (
                weighted(gt_risk_values, "risk_weight"),
                gt_risk_counts,
            ),
            "consequence_clearance_loss": (
                weighted(clearance_values, "clearance_weight"),
                clearance_counts,
            ),
            "consequence_gt_clearance_loss": (
                weighted(gt_clearance_values, "clearance_weight"),
                gt_clearance_counts,
            ),
            "consequence_ranking_loss": (
                weighted(rank_values, "ranking_weight"),
                rank_counts,
            ),
            "consequence_dream_safety_loss": (
                weighted(dream_values, "dream_weight"),
                dream_counts,
            ),
            "consequence_dream_pair_ranking_loss": (
                weighted(dream_pair_values, "dream_pair_weight"),
                dream_pair_counts,
            ),
        }

    def _consequence_ranking_for_plan(
        self,
        head_call,
        base_route,
        base_speed,
        base_logits,
        obstacles,
        obstacle_valid,
        step_valid,
    ):
        cfg = self.consequence_cfg
        # `speed_scale` (scalar) is the legacy key kept for old configs;
        # `negative_speed_scales` (list) takes precedence when present.
        speed_scales = cfg.get("negative_speed_scales")
        if speed_scales is None:
            speed_scales = [float(cfg.get("speed_scale", 1.35))]
        time_shifts = cfg.get("negative_time_shifts") or ()
        candidate_routes, candidate_speeds = make_hard_negative_plans(
            base_route,
            base_speed,
            speed_scales=[float(s) for s in speed_scales],
            lateral_offset=float(cfg.get("lateral_offset", 1.5)),
            time_shifts=[int(s) for s in time_shifts],
        )
        batch_size, candidates = candidate_routes.shape[:2]
        flat_routes = candidate_routes.reshape(batch_size * candidates, 20, 2)
        flat_speeds = candidate_speeds.reshape(batch_size * candidates, 10, 2)
        candidate_output = head_call(flat_routes, flat_speeds, num_plans=candidates)
        candidate_logits = candidate_output.risk_logits.reshape(
            batch_size, candidates, 10
        )

        base_risk, _, base_valid = trajectory_geometry_targets(
            base_speed.detach(),
            obstacles,
            obstacle_valid,
            step_valid,
            ego_radius=float(cfg.get("ego_radius", 0.9)),
            max_clearance=float(cfg.get("max_clearance", 20.0)),
        )
        expanded_obstacles = obstacles[:, None].expand(
            -1, candidates, -1, -1, -1
        ).reshape(batch_size * candidates, *obstacles.shape[1:])
        expanded_obstacle_valid = obstacle_valid[:, None].expand(
            -1, candidates, -1, -1
        ).reshape(batch_size * candidates, *obstacle_valid.shape[1:])
        expanded_step_valid = step_valid[:, None].expand(
            -1, candidates, -1
        ).reshape(batch_size * candidates, -1)
        candidate_risk, _, candidate_valid = trajectory_geometry_targets(
            flat_speeds.detach(),
            expanded_obstacles,
            expanded_obstacle_valid,
            expanded_step_valid,
            ego_radius=float(cfg.get("ego_radius", 0.9)),
            max_clearance=float(cfg.get("max_clearance", 20.0)),
        )
        candidate_risk = candidate_risk.reshape(batch_size, candidates, 10)
        candidate_valid = candidate_valid.reshape(batch_size, candidates, 10)
        proven_safe = base_valid.all(dim=1) & ~base_risk.bool().any(dim=1)
        proven_unsafe = (
            candidate_valid.all(dim=2) & candidate_risk.bool().any(dim=2)
        )
        ranking_valid = proven_safe[:, None] & proven_unsafe
        return pairwise_ranking_loss(
            base_logits,
            candidate_logits,
            ranking_valid,
            margin=float(cfg.get("negative_margin", 0.5)),
        )

    def _compute_consequence_losses_cross_attn(
        self,
        vision_tokens: Tensor,
        vision_mask: Tensor,
        predicted_route: Tensor,
        predicted_speed: Tensor,
        label: DrivingLabel,
    ):
        """Avoidance hinge on the predicted plan plus one clearance head loss."""
        cfg = self.consequence_cfg
        head = self.consequence_head

        gt_route = label.route_adjusted
        gt_speed = label.waypoints[:, :10]
        batch_size = predicted_route.size(0)
        device = predicted_route.device

        obstacles = label.future_obstacles.to(device=device)
        obstacle_valid = label.future_obstacle_valid.to(device=device)
        step_valid = label.future_obstacle_step_valid.to(device=device)
        ego_radius = float(cfg.get("ego_radius", 0.9))
        max_clearance = float(cfg.get("max_clearance", 20.0))
        geometry_kwargs = dict(
            ego_radius=ego_radius, max_clearance=max_clearance
        )

        _, pred_clearance, pred_geom_valid = trajectory_geometry_targets(
            predicted_speed, obstacles, obstacle_valid, step_valid, **geometry_kwargs
        )
        _, gt_clearance, gt_geom_valid = trajectory_geometry_targets(
            gt_speed, obstacles, obstacle_valid, step_valid, **geometry_kwargs
        )
        avoid_values, avoid_counts = relative_min_clearance_hinge(
            pred_clearance, gt_clearance, pred_geom_valid, gt_geom_valid
        )

        visible_valid = visible_obstacle_mask(
            obstacles,
            obstacle_valid,
            max_range=float(cfg.get("visible_max_range", 40.0)),
            min_x=float(cfg.get("visible_min_x", 0.0)),
        )
        speed_scales = cfg.get("negative_speed_scales")
        if speed_scales is None:
            speed_scales = [0.7, 0.8, 0.9, 1.2, 1.5]
        time_shifts = cfg.get("negative_time_shifts") or ()
        neg_routes, neg_speeds = make_hard_negative_plans(
            gt_route,
            gt_speed,
            speed_scales=[float(s) for s in speed_scales],
            lateral_offset=float(cfg.get("lateral_offset", 1.5)),
            time_shifts=[int(s) for s in time_shifts],
        )
        plan_routes = torch.cat(
            (gt_route[:, None], predicted_route.detach()[:, None], neg_routes),
            dim=1,
        )
        plan_speeds = torch.cat(
            (gt_speed[:, None], predicted_speed.detach()[:, None], neg_speeds),
            dim=1,
        )
        num_plans = plan_routes.size(1)
        flat_routes = plan_routes.reshape(batch_size * num_plans, 20, 2)
        flat_speeds = plan_speeds.reshape(batch_size * num_plans, 10, 2)
        flat_tokens, flat_mask = expand_scene_for_plans(
            vision_tokens, vision_mask, num_plans
        )
        head_out = head(flat_tokens, flat_mask, flat_routes, flat_speeds)

        expanded_obstacles = obstacles[:, None].expand(
            -1, num_plans, -1, -1, -1
        ).reshape(batch_size * num_plans, *obstacles.shape[1:])
        expanded_visible = visible_valid[:, None].expand(
            -1, num_plans, -1, -1
        ).reshape(batch_size * num_plans, *visible_valid.shape[1:])
        expanded_step = step_valid[:, None].expand(
            -1, num_plans, -1
        ).reshape(batch_size * num_plans, -1)
        _, plan_clearance_target, plan_valid = trajectory_geometry_targets(
            flat_speeds,
            expanded_obstacles,
            expanded_visible,
            expanded_step,
            **geometry_kwargs,
        )
        plan_values, plan_counts = clearance_waypoint_loss(
            head_out.clearance,
            plan_clearance_target,
            plan_valid,
            beta=float(cfg.get("clearance_beta", 1.0)),
        )
        plan_values = plan_values.view(batch_size, num_plans)
        plan_counts = plan_counts.view(batch_size, num_plans)
        plan_used = plan_counts > 0
        head_counts = plan_used.any(dim=1).long()
        head_values = (plan_values * plan_used.to(dtype=plan_values.dtype)).sum(
            dim=1
        ) / plan_used.to(dtype=plan_values.dtype).sum(dim=1).clamp_min(1)

        warmup_steps = int(cfg.get("warmup_steps", 0))
        if self.training and warmup_steps > 0 and getattr(self, "_trainer", None) is not None:
            warmup = min((int(self.global_step) + 1) / warmup_steps, 1.0)
        else:
            # Tests / memory probe have no Trainer; use full weights so the
            # measured graph matches a warmed-up training step.
            warmup = 1.0
        avoid_weight = float(cfg.get("avoid_weight", 0.3)) * warmup
        head_weight = float(cfg.get("head_weight", 0.1)) * warmup

        return {
            "consequence_avoid_loss": (avoid_values * avoid_weight, avoid_counts),
            "consequence_head_loss": (head_values * head_weight, head_counts),
        }

    def compute_world_loss(self, latent_features: Tensor, label: DrivingLabel):
        """L1 between the world predictor's next-state prediction (conditioned on
        the LM's latent action tokens) and the cached V-JEPA2 future latents."""
        b = latent_features.size(0)
        actions = latent_features.view(
            b, self.latent_steps, self.latent_tokens_per_step, -1
        )
        future_states = getattr(label, "future_states", None)
        wm_valid = getattr(label, "wm_valid", None)
        raw_loss, valid_count = masked_world_l1(
            self.world_predictor, actions, future_states, wm_valid
        )
        beta = linear_world_weight(
            self.global_step, self.world_loss_weight, self.world_loss_warmup_steps
        ) if self.training else self.world_loss_weight
        weighted = raw_loss * beta
        self._world_metrics = {
            "world_loss_raw": raw_loss.detach(),
            "world_beta": beta,
            "world_valid_count": float(valid_count),
        }
        return (
            weighted.reshape(1),
            torch.ones(1, dtype=torch.long, device=weighted.device),
        )

    def training_step(self, batch: DrivingExample, _batch_idx: int = 0):
        output = self.forward_loss(batch)
        self.log_training_output(output, "train")

        # log the loss
        self.log("train/loss", output.loss, on_step=True, on_epoch=True, prog_bar=True, logger=True)
        self._log_world_metrics("train")

        return {"loss": output.loss, "outputs": output}

    def _log_world_metrics(self, mode: str):
        metrics = getattr(self, "_world_metrics", None)
        if metrics is None:
            return
        on_step = mode == "train"
        for k, v in metrics.items():
            self.log(
                f"{mode}_losses/{k}", v,
                on_step=on_step, on_epoch=not on_step, sync_dist=False, logger=True,
            )
        self._world_metrics = None

    def validation_step(self, batch: DrivingExample, _batch_idx: int = 0):
        output = self.forward_loss(batch)
        self.log_training_output(output, "val")

        # log the loss
        self.log("val/loss", output.loss, on_step=False, on_epoch=True, prog_bar=True, logger=True)
        self._log_world_metrics("val")

        return {"loss": output.loss, "outputs": output}

    def predict_step(self, batch: DrivingExample, _batch_idx: int = 0):
        loss_dict, pred_labels = self.forward_loss(batch, per_sample=True)

        per_sample_losses = loss_dict['waypoints_loss'][0].detach().cpu().numpy()
        predictions = pred_labels['waypoints_prediction'].detach().cpu().numpy()
        labels = pred_labels['waypoints_label'].detach().cpu().numpy()

        for i in range(len(per_sample_losses)):
            self.all_losses[batch.run_id[i]] = per_sample_losses[i]
            self.all_predictions[batch.run_id[i]] = (per_sample_losses[i], predictions[i], labels[i])

        return

    def on_predict_epoch_end(self) -> None:

        # sort by loss and save as pkl and json
        # sorted_losses = sorted(self.all_losses.items(), key=lambda x: x[1])
        # with open("sorted_losses.json", "w") as f:
        #     json.dump(sorted_losses, f)
        try:
            with open("sorted_losses.pkl", "wb") as f:
                pkl.dump(self.all_losses, f)
            with open("all_predictions.pkl", "wb") as f:
                pkl.dump(self.all_predictions, f)
        except:
            breakpoint()


    def log_training_output(self, training_output: TrainingOutput, mode: str, dataset: Optional[str] = None):
        losses = {k: n.detach() for k, n in training_output.loss_averages.items()}
        counts = {k: n.detach().sum() for k, n in training_output.loss_counts.items()}
        losses["loss"] = training_output.loss.detach()
        counts["loss"] = 1  # loss is already averaged
        for k, v in sorted(losses.items()):
            log_key = f"{mode}_losses/{k}"
            self.log(log_key, v, batch_size=counts[k], sync_dist=True, add_dataloader_idx=False)


    def configure_optimizers(self):

        if self.lm_lr is not None:
            # pretrained-init trunks get their own (lower) LR; the regexes must
            # stay disjoint because configure_params_groups forbids overlap
            param_groups = [
                ParamGroup(r"^language_model\..*", self.lm_lr, self.weight_decay),
                ParamGroup(r"^(model|language_projection|adaptors|speed_encoder|route_encoder|world_predictor|consequence_head)\..*", self.lr, self.weight_decay),
                ParamGroup(r"^vision_model\..*", self.vision_lr, self.weight_decay),
            ]
        else:
            param_groups = [
                ParamGroup(r"^(model|language_model|language_projection|adaptors|speed_encoder|route_encoder|world_predictor|consequence_head)\..*", self.lr, self.weight_decay),
                ParamGroup(r"^vision_model\..*", self.vision_lr, self.weight_decay),
            ]
        param_group_config = configure_params_groups(self, param_groups, verbose=False)
        if isinstance(self.trainer.strategy, pl.strategies.DeepSpeedStrategy) and FusedAdam is not None:
            try:
                optimizer = FusedAdam(param_group_config, betas=self.betas)
            except (ImportError, OSError, RuntimeError):
                warnings.warn(
                    "FusedAdam could not be loaded; falling back to torch.optim.AdamW.",
                    stacklevel=2,
                )
                optimizer = torch.optim.AdamW(param_group_config, betas=self.betas)
        else:
            optimizer = torch.optim.AdamW(param_group_config, betas=self.betas)
        if self.trainer.max_steps == -1:
            max_steps = self.trainer.estimated_stepping_batches
        else:
            max_steps = self.trainer.max_steps

        if self.vision_freeze_steps > 0 or self.vision_ramp_steps > 0:
            scheduler = self._build_freeze_ramp_scheduler(optimizer, max_steps)
        else:
            lrs = [pg['lr'] for pg in optimizer.param_groups]
            scheduler = torch.optim.lr_scheduler.OneCycleLR(
                optimizer, max_lr=lrs, total_steps=max_steps, pct_start=self.pct_start
            )
        return {"optimizer": optimizer, "lr_scheduler": {"scheduler": scheduler, "frequency": 1, "interval": "step"}}

    def _build_freeze_ramp_scheduler(self, optimizer, max_steps: int):
        """Per-group LambdaLR: main groups get linear warmup + cosine decay;
        vision groups stay at lr=0 for `vision_freeze_steps`, then ramp up
        linearly over `vision_ramp_steps` and follow the same cosine envelope."""
        import math

        warmup_steps = max(1, int(self.pct_start * max_steps))
        freeze_steps = self.vision_freeze_steps
        ramp_steps = max(1, self.vision_ramp_steps)

        def cosine_envelope(step: int) -> float:
            if step < warmup_steps:
                return 1.0
            progress = (step - warmup_steps) / max(1, max_steps - warmup_steps)
            return 0.5 * (1.0 + math.cos(math.pi * min(progress, 1.0)))

        def main_lambda(step: int) -> float:
            if step < warmup_steps:
                return (step + 1) / warmup_steps
            return cosine_envelope(step)

        def vision_lambda(step: int) -> float:
            if step < freeze_steps:
                return 0.0
            ramp = min((step - freeze_steps + 1) / ramp_steps, 1.0)
            return ramp * cosine_envelope(step)

        vision_param_ids = {id(p) for p in self.vision_model.parameters()}
        lambdas = [
            vision_lambda
            if any(id(p) in vision_param_ids for p in group["params"])
            else main_lambda
            for group in optimizer.param_groups
        ]
        return torch.optim.lr_scheduler.LambdaLR(optimizer, lr_lambda=lambdas)