File size: 60,780 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
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
import json
import math
import os
import sys
from collections import Counter, deque
from copy import deepcopy
from pathlib import Path

REPO_ROOT = Path(__file__).resolve().parents[1]
if str(REPO_ROOT) not in sys.path:
    sys.path.insert(0, str(REPO_ROOT))
else:
    sys.path.insert(0, sys.path.pop(sys.path.index(str(REPO_ROOT))))

loaded_utils = sys.modules.get("utils")
if loaded_utils is not None:
    loaded_utils_file = getattr(loaded_utils, "__file__", None)
    try:
        is_repo_utils = loaded_utils_file is not None and Path(loaded_utils_file).resolve().relative_to(REPO_ROOT)
    except ValueError:
        is_repo_utils = False
    if not is_repo_utils:
        del sys.modules["utils"]

import cv2
import hydra
import numpy as np
import torch
from filterpy.kalman import MerweScaledSigmaPoints
from filterpy.kalman import UnscentedKalmanFilter as UKF
from omegaconf import OmegaConf
from PIL import Image, ImageDraw
from scipy.interpolate import PchipInterpolator

import carla
from leaderboard.autoagents import autonomous_agent
from srunner.scenariomanager.carla_data_provider import CarlaDataProvider

from config import register_configs  # noqa: F401
from utils.custom_types import DrivingInput
from utils.image_enhancing import histogram_equalization
from utils.navigation_text import format_target_waypoint_text
from utils.projection import get_camera_extrinsics, get_camera_intrinsics, project_points


USE_UKF = True  # Filter GNSS/compass with an Unscented Kalman Filter (same setup as SimLingo)


def get_entry_point():
    return "DriveVLABench2DriveAgent"


class PIDController:
    def __init__(self, k_p=1.0, k_i=0.0, k_d=0.0, n=20):
        self.k_p = k_p
        self.k_i = k_i
        self.k_d = k_d
        self._window = deque([0.0 for _ in range(n)], maxlen=n)
        self._saved_window = deepcopy(self._window)

    def step(self, error):
        self._window.append(float(error))
        integral = sum(self._window) / len(self._window)
        derivative = 0.0 if len(self._window) < 2 else self._window[-1] - self._window[-2]
        return self.k_p * error + self.k_i * integral + self.k_d * derivative

    def save(self):
        self._saved_window = deepcopy(self._window)

    def load(self):
        self._window = deepcopy(self._saved_window)


class LateralPIDController:
    def __init__(
        self,
        k_p=3.118357247806046,
        k_d=1.3782508892109167,
        k_i=0.6406067986034124,
        speed_scale=0.9755321901954155,
        speed_offset=1.9152884533402488,
        n=6,
    ):
        self.k_p = k_p
        self.k_d = k_d
        self.k_i = k_i
        self.speed_scale = speed_scale
        self.speed_offset = speed_offset
        self.n = n
        self._window = []

    def step(self, route_np, current_speed):
        if route_np.shape[0] == 0:
            return 0.0

        current_speed_kph = current_speed * 3.6
        lookahead = int(min(np.clip(self.speed_scale * current_speed_kph + self.speed_offset, 24, 105), route_np.shape[0] - 1))
        desired_heading_vec = route_np[lookahead]
        yaw_path = np.arctan2(desired_heading_vec[1], desired_heading_vec[0])
        heading_error = yaw_path % (2 * np.pi)
        heading_error = heading_error if heading_error < np.pi else heading_error - 2 * np.pi
        heading_error = heading_error * 180.0 / np.pi / 90.0

        self._window.append(heading_error)
        self._window = self._window[-self.n :]
        derivative = 0.0 if len(self._window) == 1 else self._window[-1] - self._window[-2]
        integral = np.mean(self._window)
        return np.clip(self.k_p * heading_error + self.k_d * derivative + self.k_i * integral, -1.0, 1.0).item()


class RoutePlanner:
    def __init__(self, min_distance, max_distance, lat_ref=0.0, lon_ref=0.0):
        self.route = deque()
        self.route_distances = deque()
        self.min_distance = min_distance
        self.max_distance = max_distance
        self.lat_ref = lat_ref
        self.lon_ref = lon_ref

    def convert_gps_to_carla(self, gps):
        earth_radius_equa = 6378137.0
        lat, lon, z = gps
        scale = math.cos(self.lat_ref * math.pi / 180.0)
        my = math.log(math.tan((lat + 90) * math.pi / 360.0)) * (earth_radius_equa * scale)
        mx = (lon * (math.pi * earth_radius_equa * scale)) / 180.0
        y = scale * earth_radius_equa * math.log(math.tan((90.0 + self.lat_ref) * math.pi / 360.0)) - my
        x = mx - scale * self.lon_ref * math.pi * earth_radius_equa / 180.0
        return np.array([x, y, z])

    def set_route(self, global_plan, gps=False):
        self.route.clear()
        self.route_distances.clear()

        for pos, cmd in global_plan:
            if gps:
                pos = self.convert_gps_to_carla(np.array([pos["lat"], pos["lon"], pos["z"]]))
            else:
                pos = np.array([pos.location.x, pos.location.y, pos.location.z])
            self.route.append((pos, cmd))

        self.route_distances.append(0.0)
        for i in range(1, len(self.route)):
            diff = self.route[i][0] - self.route[i - 1][0]
            self.route_distances.append(float((diff[0] ** 2 + diff[1] ** 2) ** 0.5))

    def run_step(self, gps):
        if len(self.route) <= 2:
            return self.route

        to_pop = 0
        farthest_in_range = -np.inf
        cumulative_distance = 0.0
        for i in range(1, len(self.route)):
            if cumulative_distance > self.max_distance:
                break
            cumulative_distance += self.route_distances[i]
            diff = self.route[i][0] - gps
            distance = float((diff[0] ** 2 + diff[1] ** 2) ** 0.5)
            if farthest_in_range < distance <= self.min_distance:
                farthest_in_range = distance
                to_pop = i

        for _ in range(to_pop):
            if len(self.route) > 2:
                self.route.popleft()
                self.route_distances.popleft()
        return self.route


class DriveVLABench2DriveAgent(autonomous_agent.AutonomousAgent):
    def setup(self, path_to_conf_file, route_index=None):
        self.track = autonomous_agent.Track.SENSORS
        self.step = -1
        self.initialized = False
        self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
        self.control = carla.VehicleControl(steer=0.0, throttle=0.0, brake=1.0)

        self.agent_cfg = self._load_agent_config(path_to_conf_file)
        self.checkpoint_path = Path(self.agent_cfg["checkpoint"]).expanduser().resolve()
        self.cfg = self._load_hydra_config(self.agent_cfg.get("config"), self.checkpoint_path)
        self.route_as = self.agent_cfg.get("route_as") or OmegaConf.select(self.cfg, "data_module.route_as") or "target_point"
        # TP-in-text must match training; old checkpoints lack the flag -> off.
        self.command_tp_text = bool(OmegaConf.select(self.cfg, "data_module.command_tp_text"))

        self.processor = None
        self._configure_processor()

        if self.cfg.model.vision_model is not None:
            self.cfg.model.vision_model.use_global_img = self.cfg.data_module.use_global_img
        self.model = hydra.utils.instantiate(self.cfg.model, route_as=self.route_as)
        state_dict = self._load_state_dict(self.checkpoint_path)
        self.model.load_state_dict(state_dict, strict=True)
        self.model.to(self.device).eval()
        self._setup_object_source()
        self._setup_consequence_gating()
        self._setup_risk_shadow_log(route_index)

        self.speed_controller = PIDController(k_p=1.75, k_i=1.0, k_d=2.0, n=20)
        self.turn_controller = LateralPIDController()
        self.stuck_detector = 0
        self.force_move = 0
        self.last_command = 4
        self.last_command_tmp = 4
        self.commands = deque([4, 4], maxlen=2)
        self.target_point_prev = np.array([1e5, 1e5])

        self.carla_frame_rate = 1.0 / 20.0
        self.carla_fps = 20

        # GNSS/compass filtering, ported from SimLingo's agent (bicycle-model UKF).
        # Only the filtered position is used; heading stays raw compass.
        self.use_ukf = bool(self.agent_cfg.get("use_ukf", USE_UKF))
        if self.use_ukf:
            self.ukf_points = MerweScaledSigmaPoints(n=4, alpha=0.00001, beta=2, kappa=0, subtract=residual_state_x)
            self.ukf = UKF(
                dim_x=4,
                dim_z=4,
                fx=bicycle_model_forward,
                hx=measurement_function_hx,
                dt=self.carla_frame_rate,
                points=self.ukf_points,
                x_mean_fn=state_mean,
                z_mean_fn=measurement_mean,
                residual_x=residual_state_x,
                residual_z=residual_measurement_h,
            )
            # State noise, same as measurement because we initialize with the first measurement later
            self.ukf.P = np.diag([0.5, 0.5, 0.000001, 0.000001])
            # Measurement noise
            self.ukf.R = np.diag([0.5, 0.5, 0.000000000000001, 0.000000000000001])
            self.ukf.Q = np.diag([0.0001, 0.0001, 0.001, 0.001])  # Model noise
            self.filter_initialized = False
        self.data_save_freq = 5
        self.wp_dilation = 1
        self.initial_frames_delay = int(2.0 / self.carla_frame_rate)
        self.stuck_threshold = 800
        self.creep_duration = 15
        self.creep_throttle = 0.4
        self._setup_creep_gate()
        # Learned restart (needs a checkpoint trained with speed_dropout_p > 0): after SPEED_MASK_STALL_S at
        # standstill the speed token is hidden, so the policy decides from the scene whether to go, until the
        # ego exceeds SPEED_MASK_RELEASE m/s.
        mask_s = os.environ.get("SPEED_MASK_STALL_S")
        self.speed_mask_steps = int(float(mask_s) * self.carla_fps) if mask_s else None
        self.speed_mask_release = float(os.environ.get("SPEED_MASK_RELEASE", "2.0"))
        self.speed_masked = False
        self.speed_mask_count = 0
        if self.speed_mask_steps is not None:
            print(f"Speed mask while stalled: after {mask_s}s, release above {self.speed_mask_release} m/s", flush=True)

        # temporal input: training frames are stored at carla_fps / data_save_freq
        # (4 Hz -> 0.25 s apart); keep a buffer of raw frames and pick
        # hist_len frames with the same spacing at inference time
        self.hist_len = int(OmegaConf.select(self.cfg, "data_module.hist_len") or 1)
        self.frame_stride = self.data_save_freq  # sim frames between model frames
        buffer_len = (self.hist_len - 1) * self.frame_stride + 1
        self.frame_buffer = deque(maxlen=buffer_len)
        if route_index is None and "+" in str(path_to_conf_file):
            # The leaderboard appends "+<route>_<town>_<scenario>_<weather>_<time>" to the config path.
            route_index = str(path_to_conf_file).split("+", 1)[1] or None
        self._route_index = route_index
        self._setup_trajectory_viz(route_index)

    def _setup_object_source(self):
        """Stage-3 object tokens. Checkpoints trained with the oracle bank read privileged CARLA
        state through team_code/oracle_objects.py (upper-bound experiment, not a sensor agent)."""
        self.object_source = None
        self._viz_objects = None
        self._shadow_oracle = self._object_compare = None
        if not getattr(self.model, "uses_object_tokens", False):
            return
        bank_cfg = dict(getattr(self.model, "object_bank_config", {}))
        bank_cfg.update(self.agent_cfg.get("object_bank") or {})
        # OBJECT_SOURCE=detector: sensor-only rows from the stage-2 detector + tracker (DETECTOR_CKPT)
        source = os.environ.get("OBJECT_SOURCE", "oracle")
        if source == "detector":
            from team_code.detector_objects import make_object_source

            checkpoint = os.environ["DETECTOR_CKPT"]
            self.object_source = make_object_source(  # two-frame or streaming detector, by checkpoint type
                checkpoint, bank_cfg, self.device,
                score_threshold=float(os.environ.get("DETECTOR_SCORE", "0.3")),
                tracker_kwargs={"max_coast_s": float(os.environ.get("TRACKER_COAST_S", "2.0"))},
                # 5 = detector + tracker at 4 Hz like the offline tracker banks a fine-tuned stage 3 saw
                update_every=int(os.environ.get("DETECTOR_UPDATE_EVERY", "1")))
            print(f"Detector object source enabled: {checkpoint}, bank={bank_cfg}", flush=True)
            self._object_dump_dir = os.environ.get("OBJECT_DUMP_DIR")
            self._object_dump = []
            # OBJECT_COMPARE_DIR=<dir>: score the tracker rows against a shadow oracle bank (never fed to the model)
            self._object_compare_dir = os.environ.get("OBJECT_COMPARE_DIR")
            if self._object_compare_dir:
                from team_code.object_compare import ShadowComparison
                from team_code.oracle_objects import OracleObjectSource

                self._shadow_oracle = OracleObjectSource(bank_cfg)
                self._object_compare = ShadowComparison(max_range=float(bank_cfg.get("max_range", 50.0)))
            return
        if source != "oracle":
            raise ValueError(f"OBJECT_SOURCE must be oracle or detector, got {source}")
        from team_code.oracle_objects import OracleObjectSource

        if os.environ.get("ORACLE_MAX_UNSEEN_S"):  # ablation: how long lost tracks are coasted
            bank_cfg["max_unseen_s"] = float(os.environ["ORACLE_MAX_UNSEEN_S"])
        noise = None
        noise_preset = os.environ.get("ORACLE_NOISE")  # ablation: corrupt observations like a camera tracker
        if noise_preset:
            from team_code.oracle_noise import TrackerNoise

            noise = TrackerNoise(noise_preset, seed=int(os.environ.get("ORACLE_NOISE_SEED", "0")))
        self.object_source = OracleObjectSource(bank_cfg, noise=noise)
        print(f"Oracle object bank enabled (privileged CARLA state): {bank_cfg}, "
              f"feature_mode={getattr(self.model, 'feature_mode', 'full')}, noise={noise_preset or 'none'}", flush=True)
        # Debug: OBJECT_DUMP_DIR=<dir> saves the raw model inputs/outputs of every 5th step per route
        # (rgb, speed, target point, command, object rows) so stalls can be replayed offline.
        self._object_dump_dir = os.environ.get("OBJECT_DUMP_DIR")
        self._object_dump = []

    def _record_object_dump(self, driving_input, speed, raw, ids, count, pred_speed_wps, pred_route, timestamp):
        if not self._object_dump_dir or self.step % 5:
            return
        self._object_dump.append(dict(
            step=self.step, t=float(timestamp), rgb=self._viz_rgb.copy(), speed=float(speed),
            target_point=driving_input.target_point[0].cpu().numpy(),
            map_route=driving_input.map_route[0].cpu().numpy(), command=driving_input.navigation_command[0],
            raw=raw.copy(), ids=ids.copy(), count=int(count),
            pred_speed_wps=pred_speed_wps[0].cpu().numpy() if pred_speed_wps is not None else None,
            pred_route=pred_route[0].cpu().numpy() if pred_route is not None else None,
            relation=torch.softmax(self.model.relation_logits()[0].float(), -1).cpu().numpy()
            if hasattr(self.model, "relation_logits") and self.model.relation_logits() is not None else None,
        ))

    def _flush_object_dump(self):
        if not self._object_dump_dir or not self._object_dump:
            return
        import pickle
        Path(self._object_dump_dir).mkdir(parents=True, exist_ok=True)
        name = self._route_name()
        with open(Path(self._object_dump_dir) / f"{name}.pkl", "wb") as f:
            pickle.dump(self._object_dump, f)
        print(f"object dump: {len(self._object_dump)} steps -> {self._object_dump_dir}/{name}.pkl", flush=True)
        self._object_dump = []

    def _route_name(self):
        if getattr(self, "_route_index", None):
            return str(self._route_index)
        return self.save_path_img.parent.name if self.save_path_img is not None else f"route_pid{os.getpid()}_{self.step}"

    def _flush_object_compare(self):
        if self._object_compare is None or not self._object_compare.frames:
            return
        path = Path(self._object_compare_dir) / f"{self._route_name()}.npz"
        self._object_compare.save(path)
        print(f"Object compare ({self._object_compare.frames} frames): {self._object_compare.brief()} -> {path}", flush=True)
        self._object_compare = None

    def _setup_consequence_gating(self):
        """Optional inference-time speed gating with the consequence head.

        The backbone still runs exactly once per step; only the small MLP head
        is evaluated on a handful of speed-scaled candidates, and the fastest
        candidate whose predicted collision risk stays under the threshold is
        executed. The route is never modified.
        """
        gating_cfg = self.agent_cfg.get("consequence_gating") or {}
        self.consequence_gating = bool(gating_cfg.get("enabled"))
        if not self.consequence_gating:
            return
        if getattr(self.model, "consequence_head", None) is None:
            print(
                "WARNING: consequence_gating requested but the checkpoint has "
                "no consequence head; gating disabled.",
                flush=True,
            )
            self.consequence_gating = False
            return

        scales = [float(s) for s in gating_cfg.get("speed_scales", [1.0, 0.85, 0.7, 0.5])]
        if 1.0 not in scales:
            scales.append(1.0)
        # fastest first: selection walks the list and keeps the first safe one
        self.gating_speed_scales = sorted(set(scales), reverse=True)
        self.gating_risk_threshold = float(gating_cfg.get("risk_threshold", 0.5))
        self.gating_aggregate = str(gating_cfg.get("aggregate", "max"))
        if self.gating_aggregate not in ("max", "mean"):
            raise ValueError("consequence_gating.aggregate must be 'max' or 'mean'")
        self.gating_hysteresis_down_steps = max(
            int(gating_cfg.get("hysteresis_down_steps", 3)), 1
        )
        self.gating_hysteresis_up_steps = max(
            int(gating_cfg.get("hysteresis_up_steps", 5)), 1
        )
        self.gating_min_speed = float(gating_cfg.get("min_speed", 1.5))

        # "v2": one-step hysteresis (the controller that scored 91.10 on ConsDrive v2).
        # "v3": jump-to-safe; opt-in only, not the default.
        self.gating_algorithm = str(gating_cfg.get("algorithm", "v2"))
        if self.gating_algorithm not in ("v2", "v3"):
            raise ValueError("consequence_gating.algorithm must be 'v2' or 'v3'")
        
        self.gating_stats = {round(s, 4): 0 for s in self.gating_speed_scales}
        self.gating_low_speed_skips = 0
        self._gating_scale_idx = 0
        self._gating_hysteresis_counter = 0
        
        # v2-specific state: tracks consecutive safe/unsafe steps for gradual adjustment
        self._gating_safe_streak = 0
        self._gating_unsafe_streak = 0
        
        print(
            f"Consequence speed gating enabled (algorithm={self.gating_algorithm}): "
            f"scales={self.gating_speed_scales}, "
            f"risk_threshold={self.gating_risk_threshold}, aggregate={self.gating_aggregate}, "
            f"hysteresis_down={self.gating_hysteresis_down_steps}, "
            f"hysteresis_up={self.gating_hysteresis_up_steps}, "
            f"min_speed={self.gating_min_speed} m/s",
            flush=True,
        )

    def _setup_risk_shadow_log(self, route_index):
        """Record the risk head's scores on the executed plan without acting.

        Meant for no-gating runs: risk heads trained with different BCE
        pos_weight calibrations put their probability mass at different
        levels, so a gating threshold tuned on one checkpoint is meaningless
        on the next.  Shadow logging measures the closed-loop risk
        distribution so the threshold can be picked from data
        (scripts/pick_gating_threshold.py).
        """
        shadow_cfg = self.agent_cfg.get("risk_shadow_log") or {}
        self.risk_shadow_log = bool(shadow_cfg.get("enabled")) and (
            getattr(self.model, "consequence_head", None) is not None
        )
        if not self.risk_shadow_log:
            return
        output_dir = Path(shadow_cfg.get("output_dir", "risk_shadow")).expanduser()
        if not output_dir.is_absolute():
            output_dir = REPO_ROOT / output_dir
        output_dir.mkdir(parents=True, exist_ok=True)
        # One evaluator process runs many routes and calls setup() once per
        # route without a route_index, so a per-process sequence number is
        # needed to keep one shadow file per route.
        cls = type(self)
        cls._shadow_seq = getattr(cls, "_shadow_seq", 0) + 1
        suffix = str(route_index) if route_index is not None else f"pid{os.getpid()}"
        self._shadow_output_path = output_dir / f"route_{suffix}_{cls._shadow_seq:03d}.json"
        self._shadow_risk_mean = []
        self._shadow_risk_max = []
        print(f"Risk shadow logging enabled -> {self._shadow_output_path}", flush=True)

    def _record_risk_shadow(self, vision_tokens, vision_mask, pred_route, pred_speed_wps):
        route = pred_route.float()
        speed_wps = pred_speed_wps.float()
        if route.ndim != 3 or route.shape[1:] != (20, 2) or speed_wps.shape[1:] != (10, 2):
            return
        with torch.no_grad():
            risk_probs, _ = self.model.score_plan_risk(
                vision_tokens.float(), vision_mask, route, speed_wps
            )
        self._shadow_risk_mean.append(float(risk_probs.mean()))
        self._shadow_risk_max.append(float(risk_probs.max()))

    def _expand_vision_scene(self, vision_tokens, vision_mask, batch):
        tokens = vision_tokens.float()
        mask = vision_mask
        if tokens.size(0) == 1 and batch > 1:
            tokens = tokens.expand(batch, -1, -1)
            mask = mask.expand(batch, -1)
        elif tokens.size(0) != batch:
            repeat = batch // tokens.size(0)
            tokens = tokens.repeat(repeat, 1, 1)
            mask = mask.repeat(repeat, 1)
        return tokens, mask

    def _gate_speed_with_consequence(self, vision_tokens, vision_mask, pred_route, pred_speed_wps):
        """Dispatch to the selected gating algorithm version."""
        if self.gating_algorithm == "v2":
            return self._gate_speed_with_consequence_v2(
                vision_tokens, vision_mask, pred_route, pred_speed_wps
            )
        return self._gate_speed_with_consequence_v3(
            vision_tokens, vision_mask, pred_route, pred_speed_wps
        )

    def _gate_speed_with_consequence_v2(self, vision_tokens, vision_mask, pred_route, pred_speed_wps):
        """One-step hysteresis: N consecutive unsafe steps to drop one tier,
        M consecutive safe steps to rise one tier, and only if the faster
        neighbor itself is also under the threshold.
        """
        route = pred_route.float()
        speed_wps = pred_speed_wps.float()
        if route.ndim != 3 or route.shape[1:] != (20, 2) or speed_wps.shape[1:] != (10, 2):
            return pred_speed_wps

        scales = self.gating_speed_scales
        candidates = torch.cat([speed_wps * scale for scale in scales], dim=0)
        tokens, mask = self._expand_vision_scene(vision_tokens, vision_mask, len(scales))
        routes = route.expand(len(scales), -1, -1)
        with torch.no_grad():
            risk_probs, _ = self.model.score_plan_risk(tokens, mask, routes, candidates)
        if self.gating_aggregate == "mean":
            aggregated = risk_probs.mean(dim=1)
        else:
            aggregated = risk_probs.max(dim=1).values

        current_idx = int(self._gating_scale_idx)
        current_risk = float(aggregated[current_idx])
        threshold = self.gating_risk_threshold

        if current_risk > threshold:
            self._gating_unsafe_streak += 1
            self._gating_safe_streak = 0
            if (
                self._gating_unsafe_streak >= self.gating_hysteresis_down_steps
                and current_idx < len(scales) - 1
            ):
                current_idx += 1
                self._gating_unsafe_streak = 0
                self._gating_safe_streak = 0
        else:
            self._gating_safe_streak += 1
            self._gating_unsafe_streak = 0
            if (
                self._gating_safe_streak >= self.gating_hysteresis_up_steps
                and current_idx > 0
                and float(aggregated[current_idx - 1]) <= threshold
            ):
                current_idx -= 1
                self._gating_safe_streak = 0
                self._gating_unsafe_streak = 0

        self._gating_scale_idx = current_idx
        self.gating_stats[round(scales[current_idx], 4)] += 1
        return speed_wps * scales[current_idx]

    def _gate_speed_with_consequence_v3(self, vision_tokens, vision_mask, pred_route, pred_speed_wps):
        """V3 algorithm: jump-to-safe candidate selection.
        
        Evaluates all speed candidates and selects the fastest one whose risk
        is below threshold, allowing direct jumps to safe speeds when high risk
        is detected. Uses hysteresis on the final selected scale.
        """
        route = pred_route.float()
        speed_wps = pred_speed_wps.float()
        if route.ndim != 3 or route.shape[1:] != (20, 2) or speed_wps.shape[1:] != (10, 2):
            return pred_speed_wps

        scales = self.gating_speed_scales
        candidates = torch.cat([speed_wps * scale for scale in scales], dim=0)
        tokens, mask = self._expand_vision_scene(vision_tokens, vision_mask, len(scales))
        routes = route.expand(len(scales), -1, -1)
        
        with torch.no_grad():
            risk_probs, _ = self.model.score_plan_risk(tokens, mask, routes, candidates)
        
        if self.gating_aggregate == "mean":
            aggregated = risk_probs.mean(dim=1)
        else:
            aggregated = risk_probs.max(dim=1).values

        threshold = self.gating_risk_threshold
        current_idx = int(self._gating_scale_idx)
        
        # Find the fastest safe candidate (smallest index with risk <= threshold)
        best_idx = None
        for idx in range(len(scales)):
            if float(aggregated[idx]) <= threshold:
                best_idx = idx
                break
        
        # If no candidate is safe, use the slowest one
        if best_idx is None:
            best_idx = len(scales) - 1
        
        # Apply hysteresis: only change if the new target is confirmed for enough steps
        if best_idx == current_idx:
            # Already at target, reset counter
            self._gating_hysteresis_counter = 0
        elif best_idx > current_idx:
            # Want to slow down (higher index = slower)
            self._gating_hysteresis_counter += 1
            if self._gating_hysteresis_counter >= self.gating_hysteresis_down_steps:
                current_idx = best_idx
                self._gating_hysteresis_counter = 0
        else:
            # Want to speed up (lower index = faster)
            self._gating_hysteresis_counter -= 1
            if self._gating_hysteresis_counter <= -self.gating_hysteresis_up_steps:
                current_idx = best_idx
                self._gating_hysteresis_counter = 0

        self._gating_scale_idx = current_idx
        self.gating_stats[round(scales[current_idx], 4)] += 1
        return speed_wps * scales[current_idx]

    def _setup_trajectory_viz(self, route_index):
        viz_cfg = self.agent_cfg.get("trajectory_viz") or {}
        self.trajectory_viz_enabled = bool(viz_cfg.get("enabled"))
        self.trajectory_viz_frequency = max(int(viz_cfg.get("frequency", 1)), 1)
        self.save_path_img = None
        if not self.trajectory_viz_enabled:
            return

        output_dir = Path(viz_cfg.get("output_dir", "trajectory_viz")).expanduser()
        if not output_dir.is_absolute():
            output_dir = REPO_ROOT / output_dir
        route_suffix = str(route_index) if route_index is not None else "route"
        self.save_path_img = output_dir / route_suffix / "images"
        self.save_path_img.mkdir(parents=True, exist_ok=True)

    def sensors(self):
        return [
            {
                "type": "sensor.camera.rgb",
                "x": -1.5,
                "y": 0.0,
                "z": 2.0,
                "roll": 0.0,
                "pitch": 0.0,
                "yaw": 0.0,
                "width": 1024,
                "height": 512,
                "fov": 110,
                "id": "rgb_0",
            },
            {
                "type": "sensor.other.imu",
                "x": 0.0,
                "y": 0.0,
                "z": 0.0,
                "roll": 0.0,
                "pitch": 0.0,
                "yaw": 0.0,
                "sensor_tick": self.carla_frame_rate,
                "id": "imu",
            },
            {
                "type": "sensor.other.gnss",
                "x": 0.0,
                "y": 0.0,
                "z": 0.0,
                "roll": 0.0,
                "pitch": 0.0,
                "yaw": 0.0,
                "sensor_tick": 0.01,
                "id": "gps",
            },
            {"type": "sensor.speedometer", "reading_frequency": self.carla_fps, "id": "speed"},
        ]

    def _init(self):
        self.lat_ref, self.lon_ref = self._estimate_gps_reference()
        self._route_planner = RoutePlanner(7.5, 50.0, self.lat_ref, self.lon_ref)
        self._route_planner.set_route(self._global_plan, gps=True)
        self.initialized = True

    @torch.inference_mode()
    def run_step(self, input_data, timestamp, sensors=None):
        self.step += 1
        if not self.initialized:
            self._init()
            return self.control

        driving_input, speed = self._build_model_input(input_data, timestamp)
        if self.speed_mask_steps is not None:
            if self.stuck_detector > self.speed_mask_steps:
                self.speed_masked = True
            elif speed > self.speed_mask_release:
                self.speed_masked = False
            if self.speed_masked:
                driving_input = driving_input._replace(
                    vehicle_speed=torch.full_like(driving_input.vehicle_speed, float("nan")))
                self.speed_mask_count += 1
        # Vision/LM run in bf16 (training config); adaptors like language_projection
        # may stay fp32 — match training with autocast instead of raw fp32 inference.
        with torch.autocast(
            device_type=self.device.type,
            dtype=torch.bfloat16,
            enabled=self.device.type == "cuda",
        ):
            if self.consequence_gating or getattr(self, "risk_shadow_log", False):
                pred_speed_wps, pred_route, vision_tokens, vision_mask = self._predict_trajectory(
                    driving_input, return_context=True
                )
            else:
                pred_speed_wps, pred_route = self._predict_trajectory(driving_input)
                vision_tokens = vision_mask = None
        pred_speed_wps = pred_speed_wps.float() if pred_speed_wps is not None else None
        pred_route = pred_route.float() if pred_route is not None else pred_speed_wps

        if (
            self.consequence_gating
            and vision_tokens is not None
            and pred_speed_wps is not None
            and pred_route is not None
            and speed >= self.gating_min_speed
        ):
            pred_speed_wps = self._gate_speed_with_consequence(
                vision_tokens, vision_mask, pred_route, pred_speed_wps
            )
        elif self.consequence_gating and speed < self.gating_min_speed:
            self.gating_low_speed_skips += 1

        if (
            getattr(self, "risk_shadow_log", False)
            and vision_tokens is not None
            and pred_route is not None
            and pred_speed_wps is not None
        ):
            self._record_risk_shadow(
                vision_tokens, vision_mask, pred_route, pred_speed_wps
            )

        self._maybe_save_trajectory_viz(pred_route, pred_speed_wps)
        if self.object_source is not None:
            self._record_object_dump(driving_input, speed, *self._last_object_rows, pred_speed_wps, pred_route, timestamp)

        steer, throttle, brake = self._control_pid(pred_route, speed, pred_speed_wps)

        if speed < 0.1:
            self.stuck_detector += 1
        else:
            self.stuck_detector = 0
        if self._allow_creep() and self.force_move == 0:
            trigger = None
            if self.creep_gate_steps is not None and self.stuck_detector > self.creep_gate_steps \
                    and self._creep_path_free(pred_route):
                trigger = "gated"
            elif self.stuck_detector > self.stuck_threshold and self.creep_fallback == "ungated":
                trigger = "fallback"
            if trigger is not None:
                self.force_move = self.creep_duration
                self.creep_stats[trigger] += 1
        if self._allow_creep() and self.force_move > 0:
            throttle = max(self.creep_throttle, throttle)
            brake = False
            self.force_move -= 1

        control = carla.VehicleControl(steer=float(steer), throttle=float(throttle), brake=float(brake))
        self.control = carla.VehicleControl(steer=0.0, throttle=0.0, brake=1.0) if self.step < self.initial_frames_delay else control
        return self.control

    def _predict_trajectory(self, driving_input, return_context=False):
        return self.model(driving_input, return_context=return_context)

    def _allow_creep(self):
        return True

    def _setup_creep_gate(self):
        """Optional early restart from a stall when the predicted path is free (team_code/creep_gate.py).

        CREEP_GATE_WAIT_S enables it after that many seconds at standstill. CREEP_GATE_TL=oracle (default)
        holds at red/yellow lights using the privileged light state, standing in for a light head that a
        deployable agent would need; none skips the light check. CREEP_FALLBACK=ungated keeps the blind
        creep after stuck_threshold steps, none drops it.
        """
        wait_s = os.environ.get("CREEP_GATE_WAIT_S")
        self.creep_gate_steps = int(float(wait_s) * self.carla_fps) if wait_s else None
        self.creep_gate_tl = os.environ.get("CREEP_GATE_TL", "oracle")
        self.creep_fallback = os.environ.get("CREEP_FALLBACK", "ungated")
        if self.creep_gate_tl not in ("oracle", "none") or self.creep_fallback not in ("ungated", "none"):
            raise ValueError(f"bad creep gate config: tl={self.creep_gate_tl} fallback={self.creep_fallback}")
        self.creep_stats = Counter()
        self._creep_gate_cache = (-1, False)
        if self.creep_gate_steps is not None:
            if self.object_source is None:
                raise RuntimeError("CREEP_GATE_WAIT_S needs an object source (object-token checkpoint)")
            print(f"Creep gate enabled: wait={wait_s}s tl={self.creep_gate_tl} fallback={self.creep_fallback}",
                  flush=True)

    def _creep_path_free(self, pred_route):
        """Re-evaluated every 0.5 s while stalled; the light lookup walks the map."""
        if self.step - self._creep_gate_cache[0] < 10:
            return self._creep_gate_cache[1]
        free = False
        rows = getattr(self, "_last_object_rows", None)
        if pred_route is not None and rows is not None:
            from team_code.creep_gate import path_conflicts

            raw, _, count = rows
            route = pred_route[0].detach().float().cpu().numpy()
            free = not path_conflicts(raw[:count], route).any()
            if free and self.creep_gate_tl == "oracle" and self._ego_light_red():
                free = False
                self.creep_stats["held_red"] += 1
            elif not free:
                self.creep_stats["held_objects"] += 1
        self._creep_gate_cache = (self.step, free)
        return free

    def _ego_light_red(self, max_distance=15.0):
        hero = CarlaDataProvider.get_hero_actor()
        if hero is None:
            return False
        light = hero.get_traffic_light()
        if light is None:
            light = CarlaDataProvider.get_next_traffic_light(hero, use_cached_location=False)
            if light is not None:
                trigger = light.get_transform().transform(light.trigger_volume.location)
                if trigger.distance(hero.get_location()) > max_distance:
                    light = None
        return light is not None and light.get_state() in (carla.TrafficLightState.Red, carla.TrafficLightState.Yellow)

    def _build_model_input(self, input_data, timestamp=0.0):
        rgb = input_data["rgb_0"][1][:, :, :3]
        _, compressed = cv2.imencode(".jpg", rgb)
        rgb = cv2.imdecode(compressed, cv2.IMREAD_UNCHANGED)
        rgb = cv2.cvtColor(rgb, cv2.COLOR_BGR2RGB)
        rgb_full = rgb
        if bool(OmegaConf.select(self.cfg, "data_module.image_enhancing")):
            rgb = histogram_equalization(rgb)
        if bool(OmegaConf.select(self.cfg, "data_module.cut_bottom_quarter")) or bool(OmegaConf.select(self.cfg, "data_module.img_shift_augmentation")):
            rgb = rgb[: int(rgb.shape[0] - (rgb.shape[0] * 4.8) // 16), :, :]

        self.frame_buffer.append(rgb)
        self._viz_rgb = rgb.copy()
        frames = self._temporal_frames()

        image = np.stack([np.transpose(f, (2, 0, 1)) for f in frames], axis=0)[None, :, None, ...]  # [1, T, 1, C, H, W]
        images_pixel, image_sizes = self._process_image(image)

        gps_pos = self._route_planner.convert_gps_to_carla(input_data["gps"][1])
        compass = preprocess_compass(input_data["imu"][1][-1])
        speed = float(input_data["speed"][1]["speed"])

        if self.use_ukf:
            if not self.filter_initialized:
                self.ukf.x = np.array([gps_pos[0], gps_pos[1], normalize_angle(compass), speed])
                self.filter_initialized = True
            self.ukf.predict(steer=self.control.steer, throttle=self.control.throttle, brake=self.control.brake)
            self.ukf.update(np.array([gps_pos[0], gps_pos[1], normalize_angle(compass), speed]))
            ego_position = self.ukf.x[0:2]
        else:
            ego_position = gps_pos[:2]

        self._current_ego_pose = [float(ego_position[0]), float(ego_position[1]), float(compass)]
        self._current_image_id = input_data["rgb_0"][0]
        waypoint_route = self._route_planner.run_step(np.append(ego_position, gps_pos[2]))
        target_point, far_command = self._route_item(waypoint_route, 1)
        next_target_point, next_far_command = self._route_item(waypoint_route, 2)

        far_command_value = command_value(far_command)
        next_far_command_value = command_value(next_far_command)
        if self.last_command_tmp != far_command_value:
            self.last_command = self.last_command_tmp
        self.last_command_tmp = far_command_value

        if not np.allclose(target_point[:2], self.target_point_prev):
            self.target_point_prev = target_point[:2].copy()
            self.commands.append(far_command_value)

        ego_target_point = inverse_conversion_2d(target_point[:2], ego_position, compass)
        ego_next_target_point = inverse_conversion_2d(next_target_point[:2], ego_position, compass)
        self._viz_target_points = np.stack([ego_target_point, ego_next_target_point], axis=0)
        map_route, navigation_command = self._navigation_input(
            ego_target_point,
            ego_next_target_point,
            far_command_value,
            next_far_command_value,
        )

        objects = object_mask = None
        if self.object_source is not None:
            if getattr(self.object_source, "needs_sensors", False):
                feats, mask, raw, ids, count = self.object_source.step(timestamp, rgb_full, ego_position[:2], compass, speed)
                if self._shadow_oracle is not None:
                    _, _, oracle_raw, _, oracle_count = self._shadow_oracle.step(timestamp)
                    if self.step % 5 == 0:
                        self._object_compare.add(oracle_raw, oracle_count, raw, count)
            else:
                feats, mask, raw, ids, count = self.object_source.step(timestamp)
            objects = torch.from_numpy(feats).unsqueeze(0).to(self.device)
            object_mask = torch.from_numpy(mask).unsqueeze(0).to(self.device)
            self._viz_objects = (raw[:count].copy(), ids[:count].copy())
            self._last_object_rows = (raw, ids, count)

        channels, height, width = image.shape[3:]
        driving_input = DrivingInput(
            camera_images=images_pixel.to(self.device),
            image_sizes=image_sizes.to(self.device) if image_sizes is not None else None,
            camera_intrinsics=get_camera_intrinsics(width, height, 110).unsqueeze(0).unsqueeze(0).to(self.device),
            camera_extrinsics=get_camera_extrinsics().unsqueeze(0).unsqueeze(0).to(self.device),
            vehicle_speed=torch.tensor([[speed]], dtype=torch.float32, device=self.device),
            map_route=map_route.to(self.device),
            target_point=torch.tensor([ego_target_point], dtype=torch.float32, device=self.device),
            navigation_command=[navigation_command],
            prompt=[""],
            objects=objects,
            object_mask=object_mask,
        )
        return driving_input, speed

    def _draw_objects(self, draw, camera_intrinsics):
        """Object-bank rows as BEV boxes projected to the ground plane, coloured by the relation head."""
        from dataloader.object_bank import RAW_LENGTH, RAW_VISIBLE, RAW_WIDTH, RAW_X, RAW_Y, RAW_YAW

        raw, ids = self._viz_objects
        if len(raw) == 0:
            return
        probs = None
        logits = self.model.relation_logits() if hasattr(self.model, "relation_logits") else None
        if logits is not None:
            probs = torch.softmax(logits[0, : len(raw)].float(), dim=-1).cpu().numpy()
        colours = {0: (200, 200, 200), 1: (0, 255, 0), 2: (255, 0, 0)}
        for k, row in enumerate(raw):
            x, y, yaw, l, w = row[RAW_X], row[RAW_Y], row[RAW_YAW], row[RAW_LENGTH], row[RAW_WIDTH]
            c, s = np.cos(yaw), np.sin(yaw)
            corners = np.array([
                [x + c * l - s * w, y + s * l + c * w], [x + c * l + s * w, y + s * l - c * w],
                [x - c * l + s * w, y - s * l - c * w], [x - c * l - s * w, y - s * l + c * w],
            ])
            if (corners[:, 0] + 1.5 <= 0.5).any():
                continue
            points = project_points(corners, camera_intrinsics)
            relation = int(np.argmax(probs[k])) if probs is not None else 0
            colour = colours[relation]
            if row[RAW_VISIBLE] < 0.5:  # remembered, not currently visible
                colour = tuple(int(v * 0.5) for v in colour)
            for a, b in zip(points, np.roll(points, 1, axis=0)):
                draw.line([tuple(a), tuple(b)], fill=colour, width=2)
            label = f"{int(ids[k])}"
            if probs is not None:
                label += f" f{probs[k][1]:.2f} y{probs[k][2]:.2f}"
            draw.text(tuple(points[0]), label, fill=colour)

    def _maybe_save_trajectory_viz(self, pred_route, pred_speed_wps):
        if not self.trajectory_viz_enabled or self.save_path_img is None:
            return
        if self.step % self.trajectory_viz_frequency != 0:
            return
        if not hasattr(self, "_viz_rgb"):
            return

        image = Image.fromarray(self._viz_rgb)
        draw = ImageDraw.Draw(image)
        height, width = self._viz_rgb.shape[:2]
        camera_intrinsics = np.asarray(get_camera_intrinsics(width, height, 110))

        if hasattr(self, "_viz_target_points") and self._viz_target_points is not None:
            for points_2d in project_points(self._viz_target_points, camera_intrinsics):
                x, y = points_2d
                draw.ellipse((x - 4, y - 4, x + 4, y + 4), fill=(0, 0, 255, 255))

        if pred_route is not None:
            for points_2d in project_points(pred_route[0].detach().cpu().numpy(), camera_intrinsics):
                x, y = points_2d
                draw.ellipse((x - 3, y - 3, x + 3, y + 3), fill=(255, 0, 0, 255))

        if pred_speed_wps is not None:
            for points_2d in project_points(pred_speed_wps[0].detach().cpu().numpy(), camera_intrinsics):
                x, y = points_2d
                draw.ellipse((x - 2, y - 2, x + 2, y + 2), fill=(0, 255, 0, 255))

        if self._viz_objects is not None:
            self._draw_objects(draw, camera_intrinsics)

        image.save(self.save_path_img / f"{self.step:06d}.png")

    def _temporal_frames(self):
        """Pick hist_len frames spaced frame_stride sim-frames apart (newest last)."""
        frames = []
        n = len(self.frame_buffer)
        for i in range(self.hist_len - 1, -1, -1):
            idx = n - 1 - i * self.frame_stride
            idx = max(idx, 0)
            frames.append(self.frame_buffer[idx])
        return frames

    def _process_image(self, image):
        encoder = OmegaConf.select(self.cfg, "data_module.encoder")
        # Convert list of numpy arrays to single numpy array before creating tensor
        batch = torch.from_numpy(np.array(image))
        batch_size, time_steps, num_cameras, channels, height, width = batch.shape

        if encoder == "llavanext":
            images = list(batch.view(batch_size * time_steps * num_cameras, channels, height, width))
            processed = self.processor.image_processor(images, return_tensors="pt", image_grid_pinpoints=[[336, 672]])
            images_pixel = processed["pixel_values"]
            if not bool(OmegaConf.select(self.cfg, "data_module.use_global_img")):
                images_pixel = images_pixel[:, 1:]
            num_patches = images_pixel.shape[1]
            images_pixel = images_pixel.view(batch_size, time_steps, num_cameras, num_patches, channels, images_pixel.shape[3], images_pixel.shape[4])
            return images_pixel, processed["image_sizes"]

        if encoder == "qwen2_5_vl":
            images = batch.view(batch_size * time_steps * num_cameras, channels, height, width).numpy()
            image_list = [np.transpose(x, (1, 2, 0)).astype(np.uint8) for x in images]
            processed = self.processor.image_processor(image_list, return_tensors="pt")
            image_sizes = processed["image_grid_thw"].view(batch_size, time_steps * num_cameras, 3)
            return processed["pixel_values"], image_sizes

        if encoder == "qwen3_vl":
            # native video mode: T front-camera frames form one clip
            video = batch[0, :, 0].to(torch.uint8)  # [T, C, H, W]
            processed = self.processor.video_processor(
                videos=[video],
                do_sample_frames=False,
                return_tensors="pt",
            )
            return processed["pixel_values_videos"], processed["video_grid_thw"]  # [1, 3]

        return batch.half(), None

    def _navigation_input(self, target_point, next_target_point, command, next_command):
        if self.route_as == "command":
            return torch.zeros((1, 2, 2), dtype=torch.float32), self._command_string(target_point, command, next_command)
        if self.route_as == "command_tp":
            route = np.stack([target_point, next_target_point], axis=0)
            command_str = self._command_string(target_point, command, next_command)
            if self.command_tp_text:
                command_str += format_target_waypoint_text(target_point, next_target_point)
            return torch.tensor(route, dtype=torch.float32).unsqueeze(0), command_str
        if self.route_as == "coords":
            route = np.stack([target_point, next_target_point], axis=0)
            return torch.tensor(route, dtype=torch.float32).unsqueeze(0), ""
        route = np.stack([target_point, next_target_point], axis=0)
        return torch.tensor(route, dtype=torch.float32).unsqueeze(0), ""

    def _command_string(self, target_point, command, next_command):
        command_map = {
            1: "go left at the next intersection",
            2: "go right at the next intersection",
            3: "go straight at the next intersection",
            4: "follow the road",
            5: "do a lane change to the left",
            6: "do a lane change to the right",
        }
        command_text = command_map.get(command, "follow the road")
        next_text = command_map.get(next_command, command_text)
        if self.last_command in (1, 2, 3) and command == 4:
            next_text = command_text
            command_text = command_map.get(self.last_command, command_text)
        next_suffix = f" then {next_text}" if command_text != next_text else ""
        if command == 4:
            return f"Command: {command_text}{next_suffix}."
        distance = int(np.linalg.norm(target_point))
        return f"Command: {command_text} in {distance} meter{next_suffix}."

    def _control_pid(self, route_waypoints, velocity, speed_waypoints):
        if route_waypoints is None or speed_waypoints is None:
            return 0.0, 0.0, True

        route_np = route_waypoints[0].detach().cpu().numpy()
        speed_np = speed_waypoints[0].detach().cpu().numpy()

        one_second = int(self.carla_fps // (self.wp_dilation * self.data_save_freq))
        half_second = one_second // 2
        if speed_np.shape[-1] == 1:
            desired_speed = float(max(speed_np[one_second - 2, 0] - speed_np[half_second - 2, 0], 0.0) * 2.0)
        else:
            desired_speed = float(np.linalg.norm(speed_np[half_second - 2] - speed_np[one_second - 2]) * 2.0)

        brake = desired_speed < 0.4 or (desired_speed > 1e-5 and velocity / desired_speed > 1.1)
        delta = np.clip(desired_speed - velocity, 0.0, 1.0)
        throttle = np.clip(self.speed_controller.step(delta), 0.0, 1.0)
        throttle = 0.0 if brake else throttle

        route_interp = interpolate_waypoints(route_np.squeeze())
        steer = round(float(np.clip(self.turn_controller.step(route_interp, velocity), -1.0, 1.0)), 3)
        return steer, throttle, brake

    def _route_item(self, route, index):
        if len(route) > index:
            return route[index]
        return route[-1]

    def _estimate_gps_reference(self):
        try:
            locx = self._global_plan_world_coord[0][0].location.x
            locy = self._global_plan_world_coord[0][0].location.y
            lon = self._global_plan[0][0]["lon"]
            lat = self._global_plan[0][0]["lat"]
            earth_radius_equa = 6378137.0

            def equations(variables):
                x, y = variables
                eq1 = lon * math.cos(x * math.pi / 180.0) - (locx * x * 180.0) / (math.pi * earth_radius_equa) - math.cos(x * math.pi / 180.0) * y
                eq2 = (
                    math.log(math.tan((lat + 90.0) * math.pi / 360.0)) * earth_radius_equa * math.cos(x * math.pi / 180.0)
                    + locy
                    - math.cos(x * math.pi / 180.0) * earth_radius_equa * math.log(math.tan((90.0 + x) * math.pi / 360.0))
                )
                return [eq1, eq2]

            from scipy.optimize import fsolve

            solution = fsolve(equations, [0.0, 0.0])
            return float(solution[0]), float(solution[1])
        except Exception as exc:
            print(f"Could not estimate GPS reference, falling back to zero: {exc}", flush=True)
            return 0.0, 0.0

    def _configure_processor(self):
        encoder = OmegaConf.select(self.cfg, "data_module.encoder")
        variant = OmegaConf.select(self.cfg, "model.vision_model.variant")
        if encoder == "llavanext":
            from transformers import LlavaNextProcessor

            self.processor = LlavaNextProcessor.from_pretrained(variant)
        elif encoder == "qwen2_5_vl":
            from transformers import AutoProcessor

            self.processor = AutoProcessor.from_pretrained(variant, local_files_only=os.path.exists(str(variant)), use_fast=False)
        elif encoder == "qwen3_vl":
            from transformers import AutoProcessor

            self.processor = AutoProcessor.from_pretrained(variant, local_files_only=os.path.exists(str(variant)))

    def _load_agent_config(self, path_to_conf_file):
        if path_to_conf_file is None:
            raise ValueError("Bench2Drive agent-config must point to a checkpoint or JSON config.")

        config_text = str(path_to_conf_file)
        if "+" in config_text and not Path(config_text).exists():
            config_text = config_text.split("+", 1)[0]

        path = Path(config_text).expanduser()
        if path.suffix == ".json":
            with open(path, "r", encoding="utf-8") as f:
                cfg = json.load(f)
            if "checkpoint" not in cfg:
                raise ValueError(f"Agent config JSON {path} must contain a 'checkpoint' field.")
            return cfg
        return {"checkpoint": str(path)}

    def _load_hydra_config(self, explicit_config, checkpoint_path):
        if explicit_config:
            return OmegaConf.load(Path(explicit_config).expanduser())

        for candidate in [checkpoint_path if checkpoint_path.is_dir() else checkpoint_path.parent, *checkpoint_path.parents]:
            hydra_config = candidate / ".hydra" / "config.yaml"
            if hydra_config.exists():
                return OmegaConf.load(hydra_config)

        config_dir = Path(__file__).resolve().parents[1] / "config"
        with hydra.initialize_config_dir(version_base="1.1", config_dir=str(config_dir)):
            return hydra.compose(config_name="config")

    def _load_state_dict(self, checkpoint_path):
        if checkpoint_path.is_dir():
            model_state_path = checkpoint_path / "checkpoint" / "mp_rank_00_model_states.pt"
            if model_state_path.exists():
                checkpoint = torch.load(model_state_path, map_location="cpu", weights_only=False)
                module_state = checkpoint.get("module") if isinstance(checkpoint, dict) else None
                if isinstance(module_state, dict):
                    return {remove_prefix(k, "model."): v for k, v in module_state.items()}

            try:
                from deepspeed.utils.zero_to_fp32 import get_fp32_state_dict_from_zero_checkpoint

                return get_fp32_state_dict_from_zero_checkpoint(str(checkpoint_path))
            except Exception as exc:
                raise RuntimeError(f"Failed to load DeepSpeed checkpoint directory {checkpoint_path}: {exc}") from exc

        checkpoint = torch.load(checkpoint_path, map_location="cpu", weights_only=False)
        for key in ("state_dict", "module", "model"):
            if isinstance(checkpoint, dict) and key in checkpoint and isinstance(checkpoint[key], dict):
                checkpoint = checkpoint[key]
                break
        return {remove_prefix(k, "model."): v for k, v in checkpoint.items()}

    def destroy(self, results=None):
        if getattr(self, "creep_stats", None):
            print(f"Creep stats (steps for held_*): {dict(self.creep_stats)}", flush=True)
        if getattr(self, "speed_mask_steps", None) is not None:
            print(f"Speed-masked steps: {self.speed_mask_count}", flush=True)
        if getattr(self, "risk_shadow_log", False) and getattr(self, "_shadow_risk_mean", None):
            payload = {
                "steps": len(self._shadow_risk_mean),
                "risk_mean": [round(v, 5) for v in self._shadow_risk_mean],
                "risk_max": [round(v, 5) for v in self._shadow_risk_max],
            }
            try:
                with open(self._shadow_output_path, "w") as handle:
                    json.dump(payload, handle)
                arr = np.asarray(self._shadow_risk_mean)
                p50, p90, p95, p99 = np.percentile(arr, [50, 90, 95, 99])
                print(
                    f"Risk shadow ({len(arr)} steps, mean-agg): "
                    f"p50={p50:.4f} p90={p90:.4f} p95={p95:.4f} p99={p99:.4f} "
                    f"-> {self._shadow_output_path}",
                    flush=True,
                )
            except Exception as exc:
                print(f"WARNING: failed to write risk shadow log: {exc}", flush=True)
        if getattr(self, "consequence_gating", False) and getattr(self, "gating_stats", None):
            total = sum(self.gating_stats.values())
            if total:
                summary = ", ".join(
                    f"x{scale}: {count} ({100.0 * count / total:.1f}%)"
                    for scale, count in sorted(self.gating_stats.items(), reverse=True)
                )
                print(f"Consequence gating decisions over {total} steps: {summary}", flush=True)
            skips = int(getattr(self, "gating_low_speed_skips", 0))
            if skips:
                print(
                    f"Consequence gating skipped {skips} steps below "
                    f"{self.gating_min_speed} m/s",
                    flush=True,
                )
        if getattr(self, "object_source", None) is not None:
            self._flush_object_dump()
            self._flush_object_compare()
            self.object_source.reset()
        if hasattr(self, "model"):
            del self.model
        torch.cuda.empty_cache()


def command_value(command):
    return int(command.value) if hasattr(command, "value") else int(command)


def remove_prefix(value, prefix):
    return value[len(prefix) :] if value.startswith(prefix) else value


def normalize_angle(x):
    x = x % (2 * np.pi)
    if x > np.pi:
        x -= 2 * np.pi
    return x


def preprocess_compass(compass):
    if math.isnan(compass):
        compass = 0.0
    return normalize_angle(compass - np.deg2rad(90.0))


def inverse_conversion_2d(point, translation, yaw):
    rotation_matrix = np.array([[np.cos(yaw), -np.sin(yaw)], [np.sin(yaw), np.cos(yaw)]])
    return rotation_matrix.T @ (point - translation)


# UKF helper functions (ported from SimLingo's team_code/agent_simlingo.py)
def bicycle_model_forward(x, dt, steer, throttle, brake):
    # Kinematic bicycle model. Numbers are the tuned parameters from World on Rails.
    front_wb = -0.090769015
    rear_wb = 1.4178275

    steer_gain = 0.36848336
    brake_accel = -4.952399
    throt_accel = 0.5633837

    locs_0 = x[0]
    locs_1 = x[1]
    yaw = x[2]
    speed = x[3]

    accel = brake_accel if brake else throt_accel * throttle
    wheel = steer_gain * steer

    beta = math.atan(rear_wb / (front_wb + rear_wb) * math.tan(wheel))
    next_locs_0 = locs_0.item() + speed * math.cos(yaw + beta) * dt
    next_locs_1 = locs_1.item() + speed * math.sin(yaw + beta) * dt
    next_yaws = yaw + speed / rear_wb * math.sin(beta) * dt
    next_speed = max(speed + accel * dt, 0.0)

    return np.array([next_locs_0, next_locs_1, next_yaws, next_speed])


def measurement_function_hx(vehicle_state):
    """Measurement space equals state space: 0: pos_x, 1: pos_y, 2: rotation, 3: speed."""
    return vehicle_state


def state_mean(state, wm):
    """Average orientations via atan2 of the weighted sin/cos means."""
    x = np.zeros(4)
    sum_sin = np.sum(np.dot(np.sin(state[:, 2]), wm))
    sum_cos = np.sum(np.dot(np.cos(state[:, 2]), wm))
    x[0] = np.sum(np.dot(state[:, 0], wm))
    x[1] = np.sum(np.dot(state[:, 1], wm))
    x[2] = math.atan2(sum_sin, sum_cos)
    x[3] = np.sum(np.dot(state[:, 3], wm))
    return x


def measurement_mean(state, wm):
    return state_mean(state, wm)


def residual_state_x(a, b):
    y = a - b
    y[2] = normalize_angle(y[2])
    return y


def residual_measurement_h(a, b):
    y = a - b
    y[2] = normalize_angle(y[2])
    return y


def interpolate_waypoints(waypoints):
    waypoints = np.asarray(waypoints, dtype=np.float32)
    if waypoints.ndim == 1:
        waypoints = waypoints.reshape(-1, 2)
    waypoints = np.concatenate((np.zeros_like(waypoints[:1]), waypoints))
    shift = np.roll(waypoints, 1, axis=0)
    shift[0] = shift[1]
    dists = np.linalg.norm(waypoints - shift, axis=1)
    dists = np.cumsum(dists)
    dists += np.arange(0, len(dists)) * 1e-4
    interp = PchipInterpolator(dists, waypoints, axis=0)
    x = np.arange(0.1, dists[-1], 0.1)
    interp_points = interp(x)
    if interp_points.shape[0] == 0:
        interp_points = waypoints[None, -1]
    return interp_points