Spaces:
Running on Zero

File size: 57,907 Bytes
32769b9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python
"""Step 3: selective answering under sensor degradation (paper/PLAN.md §10.8;
docs/pilot_artifacts/2026-10-29/joint_jobs/STEP3_SELECTIVE_SPEC.md, author decisions of 30 October).

Every arm continues j1 (camera + LiDAR + radar tokens) on one stream and may answer "insufficient evidence".
Targets are defined from the input the model receives (the oracle), never from annotations alone:
  - motion of an object without a valid return in the input: abstain unless its prior cell's best constant answer is
    right more than half the time (uniform motion weighting; tools/multisensor_selective_tables.json);
  - an addressed question whose identifier is missing (box dropout may drop the queried object): the same rule per
    question type;
  - motion of an object with returns: abstain when the Bayes posterior of the most likely class (or the probability
    that the measured median is within 1 m/s, for velocity), given the noisy median, the clean moving fraction and
    the noise level, is below tau = 0.5.
Selection questions (sel/s4/m3) are recomputed on the degraded input and stay answerable.

Arms (`train --arm`): r_sel (GRPO, +1 right / 0 abstain / -1 wrong), r_task (abstention scored -1), s_oracle (SFT on
the oracle targets), s_plain (SFT on the annotated answers everywhere); warm-up arms warm_abstain / warm_plain (25
steps; 10% random abstention targets / annotated targets) if the smoke finds j1 never abstains.

Phases: stream (CPU) | counts (CPU) | smoke | train | evaluate | tune.
"""
from __future__ import annotations

import argparse
from collections import Counter, defaultdict
from datetime import datetime, timezone
import functools
import hashlib
import json
import math
import os
from pathlib import Path
import random
import sys
import time

ROOT = Path(__file__).resolve().parents[1]
sys.path[:0] = [str(ROOT), str(ROOT / "src"), str(ROOT / "tools")]

import torch  # noqa: E402

from mmcrfm_utonia.data import readout_ladder as ladder  # noqa: E402
from mmcrfm_utonia.data.multisensor.object_radar import rows_radar_channels  # noqa: E402
from tools import multisensor_readout_ladder as tool  # noqa: E402

SEED = 20261030
ABSTAIN = "insufficient evidence"
SUFFIX = " If the available sensor evidence cannot determine the answer, answer 'insufficient evidence'."
TAU = 0.5
MARGINAL = 0.45          # cells or posteriors in (0.45, 0.5] are marginal: the reward barely separates the actions
ARMS = ("r_sel", "r_task", "s_oracle", "s_plain")
WARM_ARMS = ("warm_abstain", "warm_plain")
ABSTAIN_REWARD = dict(r_sel=0.0, r_task=-1.0)
SHARES = dict(m1=0.20, m2=0.20, m3=0.10, sel=0.10, s4=0.10, r1b=0.15, addr=0.15)
UNSUPPORTED_SHARE = 0.25  # of m1/m2 training questions (evaluation: 180 of 780)
DEGRADE_P = 0.5
TRAIN_DEGRADATIONS = (("radar_removed", None), ("radar_object_dropout", 0.5), ("radar_doppler_noise", 0.5),
                      ("radar_doppler_noise", 1.0), ("lidar_box_dropout_any", 0.3), ("lidar_content_dropout", 0.5),
                      ("camera_dark_blur", None))
# Stream v2 (author, 30 Oct, decided from case counts before any outcome): the evidence-removing conditions get a
# larger sampling weight so the stream holds about three times as many clear abstention cases (v1: 78 of 2,000).
EVIDENCE_REMOVING = {"radar_removed", "radar_object_dropout:0.5", "lidar_box_dropout_any:0.3",
                     "radar_doppler_noise:1"}
EVAL_DEGRADATIONS = (("radar_removed", None), ("radar_object_dropout", 0.5), ("radar_object_dropout", 0.25),
                     ("radar_doppler_noise", 0.5), ("radar_doppler_noise", 1.0), ("radar_doppler_noise", 2.0),
                     ("lidar_box_dropout_any", 0.3), ("radar_sensor_dropout", None))
HELD_OUT = {"radar_object_dropout:0.25", "radar_doppler_noise:2.0", "radar_sensor_dropout"}
EDITS = ("doppler_heading_flip", "doppler_zero", "relabel")
EVAL_LIMITS = dict(motion=300, other=150, edit=150)   # records per set and non-clean condition (clean: all)
WARM_STEPS = 25
MODALITIES = ("camera", "lidar")   # j1's interface


def now():
    return datetime.now(timezone.utc).isoformat(timespec="seconds")


def condition_name(name, param):
    return name if param is None else f"{name}:{param:g}"


def rng_for(*parts):
    return random.Random(":".join(str(p) for p in (SEED, *parts)))


# ------------------------------------------------------------------ prompts
_LIST_VARIANTS = (  # variant B: the abstention phrase among the listed answers (smoke decides whether it is used)
    (ladder.ATTRIBUTE_ASK["class"], ladder.ATTRIBUTE_ASK["class"].removesuffix(".") + ", insufficient evidence."),
    ("left, right, or rear (more than 150 degrees from ego forward).",
     "left, right, rear (more than 150 degrees from ego forward), or insufficient evidence."),
    ("Answer with one word: approaching, receding, or neither.",
     "Answer with one of: approaching, receding, neither, or insufficient evidence."),
)


def step3_question(question, variant="A"):
    """The question with the step-3 instruction; variant B also lists the abstention phrase where the
    question lists its allowed answers."""
    if variant == "B":
        for old, new in _LIST_VARIANTS:
            question = question.replace(old, new)
    return question + SUFFIX


def is_abstention(text):
    return ladder.normalize_answer(text).startswith(ABSTAIN)


# ------------------------------------------------------------------ oracle tables
class Tables:
    """tools/multisensor_selective_tables.json: prior cells (uniform motion weighting) and Doppler posteriors."""

    def __init__(self, path):
        self.path = Path(path)
        self.data = json.loads(self.path.read_text())
        self.sha256 = hashlib.sha256(self.path.read_bytes()).hexdigest()
        self.cells = self.data["radarless"]["cells"]
        self.bands = self.data["range_bands_m"]
        self.refined = set(self.data["refined_categories"])
        self.edges = self.data["doppler"]["median_edges"]

    def band(self, range_m):
        return max(i for i, edge in enumerate(self.bands) if range_m >= edge)

    def radarless(self, obj, attribute):
        """(best-constant rate, cell key) of a motion question about an object without a valid return."""
        key = obj["category"]
        if key in self.refined:
            sub = f"{key}|{self.band(obj['range_m'])}|{ladder.sector_of(obj['bearing_deg'])}"
            if sub in self.cells:
                key = sub
        cell = self.cells.get(key)
        if cell is None:  # a category never seen without returns: no prior, abstain
            return 0.0, key
        return float(cell[attribute][1]), key

    def missing_box(self, rung, attribute):
        return float(self.data["missing_box"][f"{rung}/{attribute}"][1])

    def doppler(self, sigma, median, moving, attribute):
        """P(the best answer is right) for an object with returns: the largest class posterior (motion) or
        P(|truth - measured median| <= 1 m/s) (velocity), given the noisy median, moving fraction and sigma."""
        table = self.data["doppler"]["sigma"][f"{float(sigma):.1f}"]
        i = sum(1 for e in self.edges if median >= e)
        j = 0 if moving <= 0 else 1 if moving < 0.5 else 2
        sparse = table["mass"][i][j] < 20
        if attribute == "motion":
            post = table["motion_posterior_marginal"][i] if sparse else table["motion_posterior"][i][j]
            return float(max(post))
        return float(table["velocity_within_1_marginal"][i] if sparse else table["velocity_within_1"][i][j])


def stratum(p):
    """Abstention strata by the probability the best answer is right: clear (<= 0.45) or marginal (<= 0.5)."""
    return "answerable" if p > TAU else "marginal" if p > MARGINAL else "clear"


# ------------------------------------------------------------------ degradations of the supplied rows
def zero_radar(rows, layout, index):
    out = torch.as_tensor(rows).clone()
    out[index, layout.radar_start:layout.xyz_start] = 0
    return out


def sensor_dropped(rows, layout, raw, frame, generator):
    """The rows' radar channels recomputed without one radar sensor's returns (held-out evaluation): the dropped
    sensor is drawn among those with returns in this keyframe."""
    frames = torch.as_tensor(raw["radar_frame_ids"]).long()
    sensors = torch.as_tensor(raw["radar_sensor_id"]).long()
    present = sorted(set(sensors[frames == int(frame)].tolist()))
    if not present:
        return torch.as_tensor(rows).clone(), None
    dropped = present[int(torch.randint(len(present), (1,), generator=generator))]
    keep = sensors != dropped
    rows = torch.as_tensor(rows).clone()
    channels = rows_radar_channels(rows[:, layout.geometry_start:layout.geometry_start + 5], rows[:, layout.xyz_start:],
                                   torch.full((len(rows),), int(frame)), torch.as_tensor(raw["radar_points"])[keep],
                                   frames[keep], torch.as_tensor(raw["radar_point_valid_mask"]).bool()[keep])
    rows[:, layout.radar_start:layout.xyz_start] = channels.to(rows.dtype)
    return rows, int(dropped)


def degrade(rows, ids, supplied, name, param, seed, layout, raw, frame, single):
    """(rows, ids, supplied objects, camera condition, info) after one degradation of the supplied rows."""
    gen = torch.Generator().manual_seed(int(seed))
    rows, ids, supplied, camera, info = torch.as_tensor(rows).clone(), ids, list(supplied), None, {}
    if name in (None, "clean"):
        pass
    elif name == "radar_removed":
        rows = ladder.radar_removed(rows, layout)
    elif name == "radar_object_dropout":
        hit = (torch.rand(len(rows), generator=gen) < float(param)).nonzero().flatten().tolist()
        rows = zero_radar(rows, layout, hit) if hit else rows
        info["radar_dropped_rows"] = hit
    elif name == "radar_doppler_noise":
        rows = ladder.doppler_noised(rows, layout, float(param), gen)
    elif name == "radar_sensor_dropout":
        rows, info["dropped_sensor"] = sensor_dropped(rows, layout, raw, frame, gen)
    elif name == "lidar_box_dropout_any":
        if single:
            raise ValueError("box dropout needs a multi-object question")
        draws = torch.rand(len(rows), generator=gen)
        keep = [i for i in range(len(rows)) if bool(draws[i] >= float(param))] or [0][:len(rows)]
        rows, supplied = rows[keep], [supplied[i] for i in keep]
        ids = None if ids is None else [ids[i] for i in keep]
    elif name == "lidar_content_dropout":
        rows = ladder.content_dropped(rows, layout, float(param), gen)
    elif name == "camera_dark_blur":
        camera = "dark_blur_v1"
    else:
        raise ValueError(f"unknown degradation {name!r}")
    return rows, ids, supplied, camera, info


def draw_degradation(rung, r, degrade_p, weight):
    """(name, param) of one entry: degraded with probability ``degrade_p``, the condition drawn among those applicable
    to the rung with ``weight`` for the evidence-removing ones and 1 for the others."""
    if r.random() >= degrade_p:
        return "clean", None
    options = applicable(rung, TRAIN_DEGRADATIONS)
    weights = [weight if condition_name(*o) in EVIDENCE_REMOVING else 1.0 for o in options]
    return r.choices(options, weights)[0]


def applicable(rung, degradations):
    """The degradations a rung can take: box dropout needs several objects; radar degradations matter for motion
    and m3 only (elsewhere they are left out rather than drawn as no-ops)."""
    out = []
    for name, param in degradations:
        if name == "lidar_box_dropout_any" and rung in ("r1b", "m1"):
            continue
        if name.startswith("radar") and rung not in ("m1", "m2", "m3"):
            continue
        out.append((name, param))
    return tuple(out)


# ------------------------------------------------------------------ one sample: input, truth and oracle target
def base(source, record):
    """(raw, supplied objects aligned with rows, rows, identifiers) of a record, clean."""
    raw = source.raw(record["scene_token"])
    features, _ = ladder.scene_rows(raw)
    objects = source.objects(record["scene_token"], record["keyframe"])
    if record["rung"] in ("r1b", "m1"):
        target = objects[record["keep_rank"]]
        return raw, [target], features[[target["row"]]], None
    return raw, objects, features[[o["row"] for o in objects]], list(record["object_ids"])


def sample(source, tables, record, degradation=("clean", None, 0), variant="A"):
    """The step-3 sample of a record under (name, param, seed): dict(item=..., truth, oracle, p_right, stratum,
    abstain_source, attribute, ...) or None when the question is undefined on the degraded input.

    ``truth`` is the annotated answer (motion and addressed questions keep it even when the input no longer supports
    it: that is the reward's reference); ``oracle`` is "insufficient evidence" where the input-defined rule says so.
    """
    name, param, seed = degradation
    rung, attribute = record["rung"], record.get("attribute", "range")
    frame = int(record["keyframe"])
    raw, supplied, rows, ids = base(source, record)
    rows, ids, supplied, camera, info = degrade(rows, ids, supplied, name, param, seed, source.layout, raw, frame,
                                                rung in ("r1b", "m1"))
    layout = source.layout
    seen = ladder.frame_objects(rows, torch.full((len(rows),), frame), frame, layout, tool.K)
    for o in seen:  # annotated labels travel with their rows
        o.update(motion=supplied[o["row"]].get("motion"), gt_radial=supplied[o["row"]].get("gt_radial"),
                 rank=o["rank"])
    truth, p_right, source_kind = record["answer"], 1.0, None
    label = (lambda o: ids[o["row"]])
    if rung in ("sel", "s4"):
        hit = ladder.nearest(seen, record.get("category", "any"), record["sector"])
        truth = "none" if hit is None else f"obj{label(hit)}, {hit['range_m']:.1f} m"
    elif rung == "m3":
        status, hit = ladder.nearest_approaching(seen, record["sector"])
        if status != "ok":
            return None
        truth = "none" if hit is None else f"obj{label(hit)}, {hit['range_m']:.1f} m"
    elif rung in ("addr", "m2") and record["identifier"] not in ids:
        p_right, source_kind = tables.missing_box(rung, attribute), "missing_box"
    elif rung in ("m1", "m2"):
        target = seen[0] if rung == "m1" else next(o for o in seen if label(o) == record["identifier"])
        if not target["answerable"]:
            p_right, cell = tables.radarless(target, attribute)
            had_returns = bool(supplied[target["row"]].get("answerable"))
            source_kind = f"radarless:{name}" if had_returns else "radarless:natural"
            info["cell"] = cell
        else:
            sigma = float(param) if name == "radar_doppler_noise" else 0.0
            radar = rows[target["row"], layout.radar_start:layout.xyz_start]
            p_right = tables.doppler(sigma, float(radar[2]), float(radar[4]), attribute)
            source_kind = f"doppler:{sigma:g}"
    oracle = truth if p_right > TAU else ABSTAIN
    question = step3_question(record["question"], variant)
    return dict(record=record, rows=rows, ids=ids, camera=camera, raw=raw, frame=frame, question=question,
                truth=truth, oracle=oracle, p_right=round(float(p_right), 4), stratum=stratum(p_right),
                abstain_source=source_kind if oracle == ABSTAIN else None, evidence_source=source_kind,
                attribute=attribute, condition=condition_name(name, param), info=info)


def item_of(source, s, answer):
    """The model input of a sample with ``answer`` as its supervised target."""
    extra = {}
    if s["ids"]:
        extra["object_ids"] = s["ids"]
    if s["camera"]:
        extra["camera_condition"] = s["camera"]
    return ladder.item_from_rows(source.dataset, s["raw"], s["frame"], s["rows"], s["question"], answer,
                                 extra=extra or None, modalities=MODALITIES)


def edit_sample(source, record, edit, variant="A"):
    """An edit of the ladder's evaluation (doppler_heading_flip, doppler_zero, relabel): input and implied answer
    from SceneSource, with the step-3 instruction. Edits are answerable by construction."""
    shown = dict(record, question=step3_question(record["question"], variant))
    if record["rung"] in ("m1", "m2", "m3"):
        item, expected, _ = source.motion_item(shown, edit)
    elif edit == "relabel":
        item, expected = source.item(shown, relabel=True)
    else:
        return None
    if item is None:
        return None
    return dict(record=record, item=item, truth=expected, oracle=expected, p_right=1.0, stratum="answerable",
                abstain_source=None, evidence_source=f"edit:{edit}", attribute=record.get("attribute", "range"),
                condition=edit, info={})


# ------------------------------------------------------------------ pools and the stream
def unsupported_motion_pools(source, sets):
    """m1/m2 questions about objects without a valid return, on the training frames (the ladder's training sets
    hold answerable objects only)."""
    frames = sorted({(r["scene_token"], r["keyframe"]) for r in sets["m1_train"]})
    pools = dict(m1=[], m2=[])
    for scene, frame in frames:
        objects = source.objects(scene, frame)
        for rung, addressed in (("m1", False), ("m2", True)):
            pools[rung] += [r for r in ladder.motion_records(scene, frame, objects, tool.SEED, addressed)
                            if not r["answerable"]]
    return pools


def uniform_motion_draw(pool, n, rng):
    """n records, uniform over the three motion classes, then uniform within a class (with replacement)."""
    by = defaultdict(list)
    for r in pool:
        by[r["motion"]].append(r)
    classes = sorted(by)
    return [rng.choice(by[rng.choice(classes)]) for _ in range(n)]


def build_stream(sets, unsupported, steps, batch_size, degrade_p=DEGRADE_P, weight=1.0):
    """The ordered (record, degradation) entries every arm reads (it never depends on the arm)."""
    need = steps * batch_size
    counts = {k: int(v * need) for k, v in SHARES.items()}
    counts["addr"] += need - sum(counts.values())
    rng = rng_for("stream")
    order = []
    for rung in ("m1", "m2"):
        n_unsupported = int(round(UNSUPPORTED_SHARE * counts[rung]))
        order += uniform_motion_draw(sets[f"{rung}_train"], counts[rung] - n_unsupported, rng)
        order += uniform_motion_draw(unsupported[rung], n_unsupported, rng)
    for rung in ("m3", "sel", "s4"):
        order += tool.cycled_sample(sets[f"{rung}_train"], counts[rung], lambda r: 1.0, SEED + len(rung))
    for rung in ("r1b", "addr"):
        pool = sets[f"{rung}_train"]
        order += tool.cycled_sample(pool, counts[rung], tool.class_balanced_weight(pool), SEED + 7 * len(rung))
    rng.shuffle(order)
    entries = []
    for position, record in enumerate(order):
        r = rng_for("degrade", position)
        name, param = draw_degradation(record["rung"], r, degrade_p, weight)
        entries.append(dict(position=position, step=position // batch_size + 1, rung=record["rung"],
                            record=record, degradation=[name, param, r.getrandbits(31)]))
    return entries


def held_out(sets, stream, n_scenes, salt, exclude=()):
    """Training scenes outside the stream for the warm-up and the threshold tuning; when fewer than half the wanted
    scenes exist, training keyframes outside the stream. Returns (kind, keys): scenes or [scene, keyframe] pairs."""
    used = {e["record"]["scene_token"] for e in stream}
    scenes = sorted({r["scene_token"] for r in sets["m1_train"]} - used - {k for k in exclude if isinstance(k, str)})
    if len(scenes) >= n_scenes // 2:
        rng_for(salt).shuffle(scenes)
        return "scenes", scenes[:n_scenes]
    used_frames = {(e["record"]["scene_token"], e["record"]["keyframe"]) for e in stream}
    frames = sorted({(r["scene_token"], r["keyframe"]) for r in sets["m1_train"]} - used_frames
                    - {tuple(k) for k in exclude if not isinstance(k, str)})
    rng_for(salt).shuffle(frames)
    return "keyframes", [list(f) for f in frames[:8 * n_scenes]]


def side_records(sets, unsupported, held, n, salt, answerable_only):
    """Questions on held-out training scenes or keyframes (``held_out``), uniform motion weighting, rungs by SHARES."""
    kind, keys = held
    keep = set(keys) if kind == "scenes" else {tuple(k) for k in keys}
    inside = (lambda r: r["scene_token"] in keep) if kind == "scenes" else \
        (lambda r: (r["scene_token"], r["keyframe"]) in keep)
    rng = rng_for(salt)
    out = []
    for rung, share in SHARES.items():
        pool = [r for r in sets[f"{rung}_train"] if inside(r)]
        if rung in ("m1", "m2") and not answerable_only:
            pool += [r for r in unsupported[rung] if inside(r)]
        if not pool:
            continue
        k = max(1, int(round(share * n)))
        out += uniform_motion_draw(pool, k, rng) if rung in ("m1", "m2") else [rng.choice(pool) for _ in range(k)]
    rng.shuffle(out)
    return out[:n]


def stream_phase(options):
    sets, plan = tool.load_sets(options.run_root)
    import infer
    args = infer.resolve_inference_settings(options.config, {}, False)
    source = tool.SceneSource(args, "train", radar=True, motion_labels=sets["motion_labels"])
    cache = options.output_dir / "unsupported_pools.json"
    if cache.exists():  # the pools depend on the data only; cached to iterate on the condition weights
        unsupported = json.loads(cache.read_text())
    else:
        unsupported = unsupported_motion_pools(source, sets)
        options.output_dir.mkdir(parents=True, exist_ok=True)
        tool.write_json(cache, unsupported)
    stream = build_stream(sets, unsupported, options.max_steps, options.batch_size, options.degrade_p,
                          options.evidence_weight)
    warm_held = held_out(sets, stream, 40, "warm")
    tune_held = held_out(sets, stream, 60, "tune", exclude=warm_held[1])
    warm = side_records(sets, unsupported, warm_held, WARM_STEPS * options.batch_size, "warm-records", True)
    tune = side_records(sets, unsupported, tune_held, options.tune_n, "tune-records", False)
    tune_entries = []
    for k, record in enumerate(tune):
        r = rng_for("tune-degrade", k)
        name, param = draw_degradation(record["rung"], r, options.degrade_p, options.evidence_weight)  # the stream's mix
        tune_entries.append(dict(position=k, rung=record["rung"], record=record,
                                 degradation=[name, param, r.getrandbits(31)]))
    warm_rng = rng_for("warm-targets")
    warm_entries = [dict(position=k, rung=r["rung"], record=r, degradation=["clean", None, 0],
                         abstain_target=warm_rng.random() < 0.10) for k, r in enumerate(warm)]
    out = dict(created_at=now(), seed=SEED, steps=options.max_steps, batch_size=options.batch_size,
               shares=SHARES, unsupported_share=UNSUPPORTED_SHARE, degrade_p=options.degrade_p,
               evidence_removing=sorted(EVIDENCE_REMOVING), evidence_weight=options.evidence_weight,
               train_degradations=TRAIN_DEGRADATIONS, plan_record_sha256=plan["record_sha256"],
               unsupported_pool_sizes={k: len(v) for k, v in unsupported.items()},
               warm_held=warm_held, tune_held=tune_held, entries=stream, warm=warm_entries, tune=tune_entries)
    options.output_dir.mkdir(parents=True, exist_ok=True)
    tool.write_json(options.output_dir / options.stream_name, out)
    print(json.dumps(dict(entries=len(stream), warm=len(warm_entries), tune=len(tune_entries),
                          warm_held=[warm_held[0], len(warm_held[1])], tune_held=[tune_held[0], len(tune_held[1])],
                          unsupported=out["unsupported_pool_sizes"],
                          sha256=tool.file_sha256(options.output_dir / options.stream_name))), flush=True)


def load_stream(path, expected_sha256=None):
    digest = tool.file_sha256(Path(path))
    if expected_sha256 and digest != expected_sha256:
        raise SystemExit(f"stream {digest} differs from the pinned {expected_sha256}")
    return json.loads(Path(path).read_text()), digest


# ------------------------------------------------------------------ counts (CPU)
def eval_plan(sets):
    """(set, record, condition, degradation) of the step-3 evaluation; seeds fixed per record and condition."""
    out = []
    for name in ("r1b_eval", "addr_eval", "sel_eval", "s4_eval", "m1_eval", "m2_eval", "m3_eval"):
        records = sets[name]
        rung = name.removesuffix("_eval")
        for record in records:
            out.append((name, record, "clean", ("clean", None, 0)))
        limit = EVAL_LIMITS["motion" if rung in ("m1", "m2", "m3") else "other"]
        for deg, param in applicable(rung, EVAL_DEGRADATIONS):
            cond = condition_name(deg, param)
            for record in records[:limit]:
                seed = int(hashlib.sha256(f"{SEED}:{cond}:{record['id']}".encode()).hexdigest()[:8], 16)
                out.append((name, record, cond, (deg, param, seed)))
        for edit in EDITS:
            if edit == "relabel" and rung not in ("addr", "sel", "s4", "m2", "m3"):
                continue
            if edit != "relabel" and rung not in ("m1", "m2", "m3"):
                continue
            for record in records[:EVAL_LIMITS["edit"] if edit == "relabel" else len(records)]:
                out.append((name, record, edit, None))
    return out


def counts_phase(options):
    """Oracle-abstain counts per source: in the stream and per evaluation condition (author's check)."""
    import infer
    sets, _ = tool.load_sets(options.run_root)
    args = infer.resolve_inference_settings(options.config, {}, False)
    tables = Tables(options.tables)
    stream, digest = load_stream(options.stream)
    train_source = tool.SceneSource(args, "train", radar=True, motion_labels=sets["motion_labels"])
    report = dict(stream_sha256=digest, tables_sha256=tables.sha256, stream={}, evaluation={})
    tally = Counter()
    for e in stream["entries"]:
        s = sample(train_source, tables, e["record"], tuple(e["degradation"]))
        key = "undefined" if s is None else (f"abstain|{s['abstain_source']}|{s['stratum']}" if s["oracle"] == ABSTAIN
                                             else f"answer|{s['evidence_source']}")
        tally[key] += 1
    report["stream"] = dict(sorted(tally.items()))
    clear = sum(v for k, v in tally.items() if k.endswith("|clear"))
    marginal = sum(v for k, v in tally.items() if k.endswith("|marginal"))
    report["stream_totals"] = dict(entries=len(stream["entries"]), clear=clear, marginal=marginal)
    print(json.dumps(report["stream_totals"]), flush=True)
    if options.stream_only:
        options.output_dir.mkdir(parents=True, exist_ok=True)
        tool.write_json(options.output_dir / f"oracle_counts_{Path(options.stream).stem}.json", report)
        return
    val_source = tool.SceneSource(args, "val", radar=True, motion_labels=sets["motion_labels"])
    per = defaultdict(Counter)
    for name, record, cond, deg in eval_plan(sets):
        if deg is None:
            continue  # edits are answerable by construction
        s = sample(val_source, tables, record, deg)
        key = "undefined" if s is None else (f"abstain|{s['abstain_source']}|{s['stratum']}" if s["oracle"] == ABSTAIN
                                             else "answer")
        per[f"{name}|{cond}"][key] += 1
    report["evaluation"] = {k: dict(v) for k, v in sorted(per.items())}
    options.output_dir.mkdir(parents=True, exist_ok=True)
    tool.write_json(options.output_dir / "oracle_counts.json", report)
    print(json.dumps(report["stream"], indent=1), flush=True)


# ------------------------------------------------------------------ model
def load_model(options, checkpoint, train):
    model, processor, collator, args, _ = tool.load(options, checkpoint, train=train, radar=True)
    spec = getattr(model, "ladder_spec", {})
    if not spec.get("camera") or spec.get("measured_text") or model.ladder_class_branch is None \
            or model.ladder_radar_branch is None:
        raise ValueError("step 3 continues j1: camera, class branch and radar branch, no measured text")
    if not train and options.radar_guard:
        print(f"RADAR prefix guard on {guard_radar_prefix(model)} projector(s)", flush=True)
    return model, processor, collator, args


def guard_radar_prefix(model):
    """Generation only: run the raw-RADAR prefix with key buckets as long as the batch's largest frame (in 128s).

    The prefix projector buckets each frame's returns into max_points_per_frame key slots, a cap sized for LiDAR
    (16,384 in E2) while a RADAR frame has a few hundred returns at most: at batch 16 the buckets alone are ~5e9
    values, the 20 GiB allocations behind both failures below. Padded slots are masked out of the attention, so
    buckets as long as the largest frame keep every return; rounded up to a multiple of 128 slots they give the same
    prefix bit for bit (RTX 5090, torch 2.7, bf16 autocast; on CPU, buckets shorter than 16 slots differ in the last
    bit). A batch whose largest frame needs the cap keeps the projector's own path.
    - E2 (raw RADAR on): arm T's evaluations ran out of memory there at batch 16 (vast.ai, 31 Oct and 1 Nov).
    - Step 3 feeds RADAR through the per-object branch, so every item's raw-return tensor is empty; the model then
      passes ONE zero return per item, marked valid, in frame 0 (_forward_sensor_readout), so the buckets are 128
      slots. On LRZ (torch 2.11, H100) the attention over the full buckets hit an illegal memory access: 7 of 7 full
      evaluations, on the addressed box-dropout questions at batch 16 (31 Oct, 1 Nov). The first step-3 guard
      (1cee8f3) acted only on empty or all-padded batches, so it never engaged there.
    Without a return (a direct caller): one slot per frame, attended with PyTorch's plain (math) kernel.
    Training is unchanged.
    """
    from torch.nn.attention import SDPBackend, sdpa_kernel

    from mmcrfm_utonia.radar_projector import RadarPerFrameMultiQueryProjector

    def guarded(projector, point_features, point_key_padding_mask=None, frame_ids=None):
        forward = type(projector).forward
        slots, frames = projector.config.max_points_per_frame, projector.config.max_frames
        if frame_ids is None:
            return forward(projector, point_features, point_key_padding_mask, frame_ids)
        need = 0
        if point_features.shape[1]:   # returns in the batch's largest frame, as the projector buckets them
            valid = torch.ones_like(frame_ids, dtype=torch.long) if point_key_padding_mask is None \
                else (~point_key_padding_mask.bool()).long()
            ids = frame_ids.long().clamp(0, frames - 1)
            need = int(torch.zeros(ids.shape[0], frames, dtype=torch.long, device=ids.device)
                       .scatter_add_(1, ids, valid).max())
        bucket = -(-need // 128) * 128   # whole 128s (bit-identical, above); 0 without a return
        if bucket >= slots:
            return forward(projector, point_features, point_key_padding_mask, frame_ids)
        projector.config.max_points_per_frame = bucket or 1
        try:
            if need:
                return forward(projector, point_features, point_key_padding_mask, frame_ids)
            with sdpa_kernel(SDPBackend.MATH):
                return forward(projector, point_features, point_key_padding_mask, frame_ids)
        finally:
            projector.config.max_points_per_frame = slots

    projectors = [m for m in model.modules() if isinstance(m, RadarPerFrameMultiQueryProjector)]
    for projector in projectors:
        projector.forward = functools.partial(guarded, projector)
    return len(projectors)


def optimizer_groups(model, lora_lr, projector_lr):
    tool.enable_prefix_training(model, lora=True)
    groups = [dict(params=[p for n, p in model.named_parameters() if p.requires_grad and "pc_prefix" in n],
                   lr=projector_lr, name="pc_prefix"),
              dict(params=[p for n, p in model.named_parameters() if p.requires_grad and "pc_prefix" not in n],
                   lr=lora_lr, name="lora")]
    for name in ("class", "radar"):
        branch = getattr(model, f"ladder_{name}_branch")
        branch.requires_grad_(True)
        groups.append(dict(params=list(branch.parameters()), lr=projector_lr, name=f"{name}_branch"))
    if len({id(p) for g in groups for p in g["params"]}) != sum(len(g["params"]) for g in groups):
        raise ValueError("a parameter sits in two optimizer groups")
    return groups


def selective_reward(text, truth, attribute, abstain_value):
    from tools.multisensor_ladder_reward import answer_right
    if is_abstention(text):
        return float(abstain_value)
    return 1.0 if answer_right(text, truth, attribute) else -1.0


# ------------------------------------------------------------------ training
def train(options):
    from transformers import GenerationConfig, set_seed

    import infer
    from mmcrfm_utonia.multisensor_reward import group_relative_advantages, reinforce_loss
    from tools.multisensor_ladder_reward import completion_tokens, well_formed, with_completions
    from tools.multisensor_reward_training import on_device, score_completion, sft_loss

    tool.require_device("step-3 training")
    started = time.monotonic()
    set_seed(SEED)
    sets, _ = tool.load_sets(options.run_root)
    stream, digest = load_stream(options.stream, options.stream_sha256)
    tables = Tables(options.tables)
    arm = options.arm
    if arm in WARM_ARMS:
        entries, steps = stream["warm"], WARM_STEPS
    else:
        entries, steps = stream["entries"], options.max_steps
    model, processor, collator, args = load_model(options, options.warm_checkpoint, train=True)
    groups = optimizer_groups(model, options.lr, options.projector_lr)
    optimizer = torch.optim.AdamW([{k: v for k, v in g.items() if k != "name"} for g in groups], weight_decay=0.0)
    warm = max(1, options.warmup_steps)
    scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, lambda s: min(1.0, (s + 1) / warm))
    source = tool.SceneSource(args, "train", radar=True, motion_labels=sets["motion_labels"], camera=True)
    tokenizer = processor.tokenizer
    suppressed = sorted(set(tokenizer.all_special_ids) - {tokenizer.eos_token_id})
    model._reward_suppressed_token_ids = suppressed
    generation = GenerationConfig(do_sample=True, temperature=1.0, top_p=1.0, top_k=0,
                                  max_new_tokens=options.max_new_tokens, use_cache=True, suppress_tokens=suppressed,
                                  eos_token_id=tokenizer.eos_token_id, pad_token_id=tokenizer.pad_token_id)
    eos_ids = {tokenizer.eos_token_id}
    result = dict(arm=arm, warm_checkpoint=str(options.warm_checkpoint), radar_channels=model.ladder_radar,
                  radar_zeroed=model.ladder_radar_zeroed, spec=dict(model.ladder_spec), stream_sha256=digest,
                  tables_sha256=tables.sha256, lr=options.lr, projector_lr=options.projector_lr,
                  batch_size=options.batch_size, group_size=options.group_size, planned_steps=steps,
                  variant=options.variant, started_at=now())
    print(json.dumps(dict(event="step3_training_ready", **result)), flush=True)
    options.output_dir.mkdir(parents=True, exist_ok=True)
    tally = Counter()
    step = 0
    with (options.output_dir / "metrics.jsonl").open("x") as metrics:
        for step in range(1, steps + 1):
            if step > 1 and time.monotonic() - started >= options.max_seconds:
                step -= 1
                break
            batch_entries = entries[(step - 1) * options.batch_size:step * options.batch_size]
            built = []
            for e in batch_entries:
                s = sample(source, tables, e["record"], tuple(e["degradation"]), options.variant)
                if s is None:
                    tally["undefined"] += 1
                    continue
                if arm == "warm_abstain":
                    s["target"] = ABSTAIN if e["abstain_target"] else s["truth"]
                elif arm in ("warm_plain", "s_plain"):
                    s["target"] = s["truth"]
                elif arm == "s_oracle":
                    s["target"] = s["oracle"]
                else:
                    s["target"] = s["truth"]
                tally[f"oracle:{'abstain' if s['oracle'] == ABSTAIN else 'answer'}"] += 1
                built.append(s)
            optimizer.zero_grad(set_to_none=True)
            log = dict(step=step, examples=len(built))
            if arm in ("s_oracle", "s_plain") or arm in WARM_ARMS:
                log["loss"] = 0.0
                for start in range(0, len(built), options.chunk):
                    part = built[start:start + options.chunk]
                    batch = on_device(collator([item_of(source, s, s["target"]) for s in part]), model.device)
                    loss = sft_loss(model, batch) * (len(part) / len(built))
                    if not torch.isfinite(loss):
                        raise ValueError("nonfinite SFT loss")
                    loss.backward()
                    log["loss"] += float(loss.detach())
                log["abstain_targets"] = sum(s["target"] == ABSTAIN for s in built)
            else:
                abstain_value = ABSTAIN_REWARD[arm]
                total, zero_groups, step_rewards, abstained, malformed = 0.0, 0, [], 0, 0
                for s in built:
                    prompt, _ = collator.encode_prompts([item_of(source, s, s["truth"])] * options.group_size)
                    prompt = on_device(prompt, model.device)
                    model.eval()
                    with torch.no_grad(), infer.generation_autocast(model):
                        generated = model.generate(**prompt, generation_config=generation)
                    length = prompt["input_ids"].shape[1]
                    completions = [completion_tokens(row, length, eos_ids) for row in generated]
                    texts = [tokenizer.decode([t for t in c if t not in eos_ids], skip_special_tokens=True).strip()
                             for c in completions]
                    rewards = torch.tensor([selective_reward(t, s["truth"], s["attribute"], abstain_value)
                                            for t in texts])
                    abstained += sum(is_abstention(t) for t in texts)
                    malformed += sum(not is_abstention(t) and not well_formed(t, s["attribute"]) for t in texts)
                    step_rewards += rewards.tolist()
                    if float(rewards.std()) == 0.0:
                        zero_groups += 1
                    advantages = group_relative_advantages(rewards.unsqueeze(0))[0].to(model.device)
                    model.train()
                    batch, mask = with_completions(prompt, completions, tokenizer.pad_token_id)
                    mean_logp = score_completion(model, batch, mask)
                    sequence_logp = mean_logp * torch.tensor([len(c) for c in completions], device=mean_logp.device)
                    loss = reinforce_loss(sequence_logp, advantages) / max(1, len(built))
                    if not torch.isfinite(loss):
                        raise ValueError("nonfinite policy loss")
                    loss.backward()
                    total += float(loss.detach())
                    del batch, mask, prompt, generated
                log.update(rl_loss=total, mean_reward=sum(step_rewards) / max(1, len(step_rewards)),
                           zero_variance_groups=zero_groups, sampled_abstention=abstained / max(1, len(step_rewards)),
                           sampled_malformed=malformed / max(1, len(step_rewards)))
            params = [p for g in groups for p in g["params"]]
            if any(p.grad is not None for p in params):
                log["grad_norm"] = float(torch.nn.utils.clip_grad_norm_(params, 1.0, error_if_nonfinite=True))
                optimizer.step()
            scheduler.step()
            log["seconds"] = time.monotonic() - started
            metrics.write(json.dumps(log) + "\n")
            metrics.flush()
            if step % 10 == 0 or step == 1:
                print(json.dumps(log), flush=True)
            if options.save_every and step % options.save_every == 0 and step != steps:
                tool.save(model, processor, options.output_dir / f"checkpoint-{step}", dict(step=step, **result))
    if step < 1:
        raise RuntimeError("no update completed")
    result.update(chunk=options.chunk, optimizer_steps=step, stopped_by="max_steps" if step == steps else "walltime_budget",
                  seconds=time.monotonic() - started, tally=dict(tally), spec=dict(model.ladder_spec))
    final = options.output_dir / f"checkpoint-{step}"
    if not final.exists():
        tool.save(model, processor, final, dict(step=step, **result))
    (options.output_dir / "final").symlink_to(final.name, target_is_directory=True)
    tool.write_json(options.output_dir / "result.json", result)
    return result


# ------------------------------------------------------------------ evaluation
@torch.inference_mode()
def answer_rows(model, processor, collator, items, batch_size, abstain_id):
    """Greedy answers with first-token statistics: P(abstention first token), the top first token's probability,
    the top probability among the other tokens."""
    import infer
    tok = processor.tokenizer
    out = []
    for start in range(0, len(items), batch_size):
        batch, _ = collator.encode_prompts(items[start:start + batch_size])
        batch = {k: v.to(model.device) if isinstance(v, torch.Tensor) else v for k, v in batch.items()}
        with infer.generation_autocast(model):
            generated = model.generate(**batch, max_new_tokens=16, do_sample=False, pad_token_id=tok.pad_token_id,
                                       eos_token_id=tok.eos_token_id, return_dict_in_generate=True,
                                       output_logits=True)
        probs = generated.logits[0].detach().float().softmax(-1).cpu()
        texts = tok.batch_decode(generated.sequences[:, batch["input_ids"].shape[1]:], skip_special_tokens=True)
        for text, p in zip(texts, probs):
            p_abstain = float(p[abstain_id])
            others = p.clone()
            others[abstain_id] = 0
            out.append(dict(prediction=text.strip(), p_abstain_first=round(p_abstain, 6),
                            p_top_first=round(float(p.max()), 6), p_top_other_first=round(float(others.max()), 6)))
    return out


@torch.inference_mode()
def forced_answers(model, processor, collator, items, batch_size, abstain_id):
    """Greedy answers with the abstention first token suppressed (forced-answer accuracy)."""
    import infer
    tok = processor.tokenizer
    out = []
    for start in range(0, len(items), batch_size):
        batch, _ = collator.encode_prompts(items[start:start + batch_size])
        batch = {k: v.to(model.device) if isinstance(v, torch.Tensor) else v for k, v in batch.items()}
        with infer.generation_autocast(model):
            generated = model.generate(**batch, max_new_tokens=16, do_sample=False, pad_token_id=tok.pad_token_id,
                                       eos_token_id=tok.eos_token_id, suppress_tokens=[abstain_id])
        out += [t.strip() for t in tok.batch_decode(generated[:, batch["input_ids"].shape[1]:],
                                                    skip_special_tokens=True)]
    return out


def abstain_token(tokenizer):
    ids = tokenizer("<|im_start|>assistant\n" + ABSTAIN, add_special_tokens=False)["input_ids"]
    base_ids = tokenizer("<|im_start|>assistant\n", add_special_tokens=False)["input_ids"]
    return ids[len(base_ids)]


def score_row(row, s):
    from tools.multisensor_ladder_reward import answer_right
    abstained = is_abstention(row["prediction"])
    right = (not abstained) and answer_right(row["prediction"], s["truth"], s["attribute"])
    row.update(abstained=abstained, correct=right, selective_reward=0.0 if abstained else (1.0 if right else -1.0),
               follows_oracle=(abstained if s["oracle"] == ABSTAIN else right))
    return row


def evaluate(options):
    import infer
    tool.require_device("step-3 evaluation")
    sets, plan = tool.load_sets(options.run_root)
    tables = Tables(options.tables)
    model, processor, collator, args = load_model(options, options.checkpoint, train=False)
    model.eval()
    abstain_id = abstain_token(processor.tokenizer)
    source = tool.SceneSource(args, "val", radar=True, motion_labels=sets["motion_labels"], camera=True)
    options.output_dir.mkdir(parents=True, exist_ok=True)
    summary = dict(checkpoint=str(options.checkpoint), training=tool.training_provenance(options.checkpoint),
                   tables_sha256=tables.sha256, plan_record_sha256=plan["record_sha256"], variant=options.variant,
                   abstain_token_id=abstain_id, started_at=now(), files={})
    plan_rows = eval_plan(sets)
    if options.only:
        missing = set(options.only) - {f"{p[0]}|{p[2]}" for p in plan_rows}
        if missing:
            raise ValueError(f"--only names no evaluation group: {sorted(missing)}")
        plan_rows = [p for p in plan_rows if f"{p[0]}|{p[2]}" in options.only]
    if options.limit:
        seen = Counter()
        plan_rows = [p for p in plan_rows if seen.update([(p[0], p[2])]) or seen[(p[0], p[2])] <= options.limit]
    grouped = defaultdict(list)
    for name, record, cond, deg in plan_rows:
        grouped[(name, cond)].append((record, deg))
    for (name, cond), entries in grouped.items():
        built = []
        for record, deg in entries:
            if deg is None:
                s = edit_sample(source, record, cond, options.variant)
                if s is not None:
                    built.append((s, s["item"]))
            else:
                s = sample(source, tables, record, deg, options.variant)
                if s is not None:
                    built.append((s, item_of(source, s, s["truth"])))
        rows = answer_rows(model, processor, collator, [b[1] for b in built], options.batch_size, abstain_id)
        abstained = [k for k, r in enumerate(rows) if is_abstention(r["prediction"])]
        forced = forced_answers(model, processor, collator, [built[k][1] for k in abstained], options.batch_size,
                                abstain_id) if abstained else []
        from tools.multisensor_ladder_reward import answer_right
        for k, text in zip(abstained, forced):
            rows[k].update(forced_prediction=text,
                           forced_correct=answer_right(text, built[k][0]["truth"], built[k][0]["attribute"]))
        path = options.output_dir / f"{name}__{cond.replace(':', '_')}.jsonl"
        with path.open("x") as handle:
            for (s, _), row in zip(built, rows):
                row = score_row(dict(id=s["record"]["id"], set=name, condition=cond, attribute=s["attribute"],
                                     truth=s["truth"], oracle=s["oracle"], p_right=s["p_right"],
                                     stratum=s["stratum"], abstain_source=s["abstain_source"],
                                     evidence_source=s["evidence_source"], held_out=cond in HELD_OUT,
                                     motion=s["record"].get("motion"), category=s["record"].get("category"),
                                     **row), s)
                handle.write(json.dumps(row) + "\n")
        summary["files"][path.name] = len(rows)
        print(json.dumps({f"{name}|{cond}": dict(n=len(rows), abstained=len(abstained))}), flush=True)
    summary["completed_at"] = now()
    tool.write_json(options.output_dir / "summary.json", summary)


def tune(options):
    """First-token statistics of a checkpoint on the tuning questions (training scenes outside the stream), for
    choosing S-plain's and R-task's abstention threshold."""
    tool.require_device("step-3 tuning")
    sets, _ = tool.load_sets(options.run_root)
    tables = Tables(options.tables)
    stream, digest = load_stream(options.stream, options.stream_sha256)
    model, processor, collator, args = load_model(options, options.checkpoint, train=False)
    model.eval()
    abstain_id = abstain_token(processor.tokenizer)
    source = tool.SceneSource(args, "train", radar=True, motion_labels=sets["motion_labels"], camera=True)
    built = []
    for e in stream["tune"]:
        s = sample(source, tables, e["record"], tuple(e["degradation"]), options.variant)
        if s is not None:
            built.append((s, item_of(source, s, s["truth"])))
    rows = answer_rows(model, processor, collator, [b[1] for b in built], options.batch_size, abstain_id)
    options.output_dir.mkdir(parents=True, exist_ok=True)
    with (options.output_dir / "tune.jsonl").open("x") as handle:
        for (s, _), row in zip(built, rows):
            row = score_row(dict(id=s["record"]["id"], condition=s["condition"], attribute=s["attribute"],
                                 truth=s["truth"], oracle=s["oracle"], stratum=s["stratum"], **row), s)
            handle.write(json.dumps(row) + "\n")
    tool.write_json(options.output_dir / "summary.json", dict(checkpoint=str(options.checkpoint), stream_sha256=digest,
                                                            n=len(rows), completed_at=now()))


# ------------------------------------------------------------------ smoke
def smoke(options):
    """j1's sampled abstention rate under the step-3 prompt (variants A and B) on clear-stratum, marginal and
    answerable questions, with the malformed share."""
    import infer
    from transformers import GenerationConfig

    tool.require_device("step-3 smoke")
    sets, _ = tool.load_sets(options.run_root)
    stream, digest = load_stream(options.stream, options.stream_sha256)
    tables = Tables(options.tables)
    model, processor, collator, args = load_model(options, options.warm_checkpoint, train=False)
    model.eval()
    tok = processor.tokenizer
    source = tool.SceneSource(args, "train", radar=True, motion_labels=sets["motion_labels"], camera=True)
    generation = GenerationConfig(do_sample=True, temperature=1.0, top_p=1.0, top_k=0, max_new_tokens=16,
                                  suppress_tokens=sorted(set(tok.all_special_ids) - {tok.eos_token_id}),
                                  eos_token_id=tok.eos_token_id, pad_token_id=tok.pad_token_id)
    from tools.multisensor_ladder_reward import well_formed
    kinds = ("clear", "marginal", "answerable")  # the warm-up is decided on the clear stratum (author, 30 Oct)
    picked = defaultdict(list)
    for e in stream["entries"]:
        s = sample(source, tables, e["record"], tuple(e["degradation"]))
        if s is None:
            continue
        kind = s["stratum"] if s["oracle"] == ABSTAIN else "answerable"
        if len(picked[kind]) < options.smoke_questions:
            picked[kind].append(e)
        if all(len(picked[k]) >= options.smoke_questions for k in kinds):
            break
    report = dict(stream_sha256=digest, questions={k: len(v) for k, v in picked.items()}, variants={})
    options.output_dir.mkdir(parents=True, exist_ok=True)
    log = (options.output_dir / "abstention_questions.jsonl").open("x")
    for variant in ("A", "B"):
        rates = {}
        for kind, entries in picked.items():
            sampled = greedy = malformed = 0
            for e in entries:
                s = sample(source, tables, e["record"], tuple(e["degradation"]), variant)
                item = item_of(source, s, s["truth"])
                on = lambda b: {k: v.to(model.device) if isinstance(v, torch.Tensor) else v for k, v in b.items()}
                prompt = on(collator.encode_prompts([item] * options.group_size)[0])
                with torch.no_grad(), infer.generation_autocast(model):
                    generated = model.generate(**prompt, generation_config=generation)
                texts = [t.strip() for t in tok.batch_decode(generated[:, prompt["input_ids"].shape[1]:],
                                                             skip_special_tokens=True)]
                sampled += sum(is_abstention(t) for t in texts)
                malformed += sum(not is_abstention(t) and not well_formed(t, s["attribute"]) for t in texts)
                single = on(collator.encode_prompts([item])[0])  # pixel values are flattened: never slice a batch
                with torch.no_grad(), infer.generation_autocast(model):
                    g = model.generate(**single, max_new_tokens=16, do_sample=False,
                                       pad_token_id=tok.pad_token_id, eos_token_id=tok.eos_token_id)
                greedy_text = tok.decode(g[0, single["input_ids"].shape[1]:], skip_special_tokens=True).strip()
                greedy += is_abstention(greedy_text)
                log.write(json.dumps(dict(variant=variant, kind=kind, id=e["record"]["id"], condition=s["condition"],
                                          attribute=s["attribute"], truth=s["truth"], oracle=s["oracle"],
                                          sampled=texts, greedy=greedy_text)) + "\n")
            n = len(entries) * options.group_size
            rates[kind] = dict(sampled=sampled / n, greedy=greedy / len(entries), malformed=malformed / n)
        report["variants"][variant] = rates
        print(json.dumps({variant: rates}), flush=True)
    log.close()
    clear = {v: r["clear"]["sampled"] for v, r in report["variants"].items()}
    report["sampled_abstention_clear"] = clear
    report["variant_b_clears"] = clear["A"] < 0.05 <= clear["B"]
    report["warm_up_triggers"] = clear["A"] < 0.05 and not report["variant_b_clears"]
    from tools.multisensor_ladder_reward import release_memory
    del model
    release_memory()
    options.output_dir.mkdir(parents=True, exist_ok=True)
    tool.write_json(options.output_dir / "abstention_smoke.json", report)
    print(json.dumps(report), flush=True)
    # The arms' updates run as separate processes (the launcher's smoke phase): one model per process, as in
    # production; sequential arms in one process ran out of GPU memory (LRZ 5888431).


# ------------------------------------------------------------------ CLI
def parse_args(argv=None):
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument("phase", choices=("stream", "counts", "smoke", "train", "evaluate", "tune"))
    parser.add_argument("--config", required=True, type=Path)
    parser.add_argument("--run-root", required=True, type=Path)
    parser.add_argument("--output-dir", required=True, type=Path)
    parser.add_argument("--tables", type=Path, default=ROOT / "tools" / "multisensor_selective_tables.json")
    parser.add_argument("--stream", type=Path)
    parser.add_argument("--stream-sha256")
    parser.add_argument("--warm-checkpoint", type=Path)
    parser.add_argument("--checkpoint", type=Path)
    parser.add_argument("--arm", choices=(*ARMS, *WARM_ARMS))
    parser.add_argument("--variant", choices=("A", "B"), default="A")
    parser.add_argument("--max-steps", type=int, default=250)
    parser.add_argument("--batch-size", type=int, default=8)
    parser.add_argument("--group-size", type=int, default=8)
    parser.add_argument("--chunk", type=int, default=8, help="SFT examples per forward pass")
    parser.add_argument("--lr", type=float, default=1e-5)
    parser.add_argument("--projector-lr", type=float, default=2e-5)
    parser.add_argument("--warmup-steps", type=int, default=30)
    parser.add_argument("--max-new-tokens", type=int, default=16)
    parser.add_argument("--max-seconds", type=float, default=1e9)
    parser.add_argument("--save-every", type=int, default=50)
    parser.add_argument("--limit", type=int, help="evaluate: first N records per set and condition (smoke)")
    parser.add_argument("--only", nargs="+", metavar="SET|CONDITION", help="evaluate: these groups only (checks)")
    parser.add_argument("--no-radar-guard", dest="radar_guard", action="store_false",
                        help="generation without guard_radar_prefix (the check that reproduces the LRZ crash)")
    parser.add_argument("--tune-n", type=int, default=1200)
    parser.add_argument("--degrade-p", type=float, default=DEGRADE_P, help="stream: share of degraded entries")
    parser.add_argument("--evidence-weight", type=float, default=1.0,
                        help="stream: sampling weight of the evidence-removing conditions (others 1)")
    parser.add_argument("--stream-name", default="stream.json", help="stream: output file name")
    parser.add_argument("--stream-only", action="store_true", help="counts: the stream only")
    parser.add_argument("--smoke-questions", type=int, default=24, help="smoke: questions per kind")
    options = parser.parse_args(argv)
    need = dict(stream=(), counts=("stream",), smoke=("stream", "warm_checkpoint"),
                train=("stream", "warm_checkpoint", "arm"), evaluate=("checkpoint",), tune=("stream", "checkpoint"))
    missing = [n for n in need[options.phase] if getattr(options, n) is None]
    if missing:
        parser.error(f"{options.phase} requires: " + ", ".join("--" + m.replace("_", "-") for m in missing))
    return options


def main(argv=None):
    options = parse_args(argv)
    torch.set_num_threads(int(os.environ.get("OMP_NUM_THREADS", "1")))
    dict(stream=stream_phase, counts=counts_phase, smoke=smoke, train=train, evaluate=evaluate,
         tune=tune)[options.phase](options)


if __name__ == "__main__":
    main()