File size: 68,624 Bytes
296ef60
 
 
 
 
 
 
 
0164c03
 
 
296ef60
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0164c03
 
 
 
 
 
 
 
8c15ebd
 
296ef60
 
 
 
 
 
 
0164c03
 
 
 
 
8c15ebd
 
0164c03
 
 
 
 
 
 
 
 
 
 
296ef60
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0164c03
 
 
 
 
 
8c15ebd
 
0164c03
 
 
 
 
 
 
 
 
 
 
296ef60
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20aeae0
 
 
296ef60
20aeae0
296ef60
 
 
 
 
0164c03
 
296ef60
 
 
 
 
 
 
 
 
 
 
 
20aeae0
 
296ef60
 
 
 
 
 
0164c03
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c15ebd
0164c03
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
296ef60
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0164c03
 
 
 
 
 
296ef60
 
0164c03
296ef60
 
 
 
 
 
 
 
 
 
 
 
 
0164c03
 
 
 
 
 
296ef60
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0164c03
296ef60
 
 
 
 
 
 
 
 
0164c03
296ef60
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5518b36
 
 
 
 
 
296ef60
5518b36
296ef60
5518b36
 
 
 
 
 
296ef60
5518b36
 
 
 
 
 
 
 
 
 
 
 
 
 
296ef60
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5518b36
 
 
 
0164c03
296ef60
 
5518b36
0164c03
296ef60
5518b36
 
296ef60
5518b36
 
 
 
 
 
 
 
 
 
 
 
 
 
296ef60
 
 
 
5518b36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
296ef60
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0164c03
 
 
 
 
 
 
296ef60
 
 
 
 
 
 
 
 
 
 
 
5518b36
 
 
 
296ef60
 
 
5518b36
 
296ef60
 
 
 
 
 
 
 
0164c03
296ef60
 
 
 
 
 
0164c03
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c15ebd
 
 
 
0164c03
 
 
 
296ef60
 
 
 
 
 
 
 
5518b36
 
296ef60
 
5518b36
 
296ef60
5518b36
 
 
296ef60
 
0164c03
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
296ef60
 
 
0164c03
 
 
296ef60
 
 
0164c03
 
296ef60
 
 
 
 
 
 
0164c03
 
 
 
 
 
296ef60
 
 
 
 
0164c03
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c15ebd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0164c03
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c15ebd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0164c03
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
296ef60
 
 
 
 
 
 
 
 
 
8fa472f
 
 
 
296ef60
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5518b36
296ef60
5518b36
 
296ef60
 
 
 
 
5518b36
 
296ef60
 
0164c03
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c15ebd
 
 
 
 
 
 
0164c03
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
296ef60
 
 
 
b045445
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8fa472f
 
b045445
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8fa472f
b045445
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8fa472f
 
 
 
 
 
 
 
 
 
b045445
 
296ef60
 
 
 
 
 
 
 
 
0164c03
 
 
 
8c15ebd
 
0164c03
 
 
 
 
 
 
 
 
 
 
296ef60
 
 
0164c03
 
 
296ef60
 
 
0164c03
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
296ef60
 
0164c03
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b045445
0164c03
 
 
 
 
 
296ef60
 
0164c03
 
 
 
296ef60
0164c03
 
296ef60
 
 
 
 
 
0164c03
 
 
296ef60
8fa472f
0164c03
296ef60
 
 
0164c03
296ef60
0164c03
 
296ef60
0164c03
 
 
 
296ef60
 
5518b36
0164c03
5518b36
296ef60
0164c03
296ef60
 
 
 
 
 
 
 
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
"""
Every number, table and figure in the Jev benchmark paper, regenerated from saved outputs.
No API calls, no model training.

    uv run --no-project --with numpy --with scikit-learn --with matplotlib --with huggingface_hub \\
        --with datasets python papers/jev_benchmark/analysis.py

Inputs: verification/jev_benchmark_artifacts/ (Jev responses and LR predictions), the comparators'
saved validation logits on the HF Hub, verification/semif_benchmark_artifacts/ (SemIf, an open
reproduction of the interface; each variant is included when its full-validation file exists), and the
canonical splits (utils/data_utils.py).
Outputs: papers/jev_benchmark/numbers.json and papers/jev_benchmark/figures/*.pdf.

Metric conventions (stated in the paper, section "Evaluation protocol"):
  * Macro F1: per-class F1 = 2TP / (2TP + FP + FN), each count over ALL evaluation examples, averaged
    over the classes that have at least one true example in the (re)sample. On the full validation
    split all 113 classes have support, so the point estimate is macro F1 over the fixed 113 labels.
  * Head/mid/tail F1: the same per-class F1 values (counted over all examples), averaged over the
    classes in each frequency group. These decompose overall macro F1 exactly (asserted below).
    The earlier "conditional" variant (only the group's own examples) is kept as a diagnostic.
  * Bootstrap: paired; the same resampled example indices are used for every system. 10,000
    ordinary resamples; sensitivity: fixed 113 labels (absent classes score 0), and a
    class-stratified bootstrap (5,000) that keeps every class's support fixed.
"""

import hashlib
import json
import re
import sys
from pathlib import Path

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
from sklearn.metrics import f1_score

# Two layouts: the build repository (default) or a public release directory (--release DIR), where
# every system's validation predictions are read from predictions/val_predictions_all_systems.npz.
RELEASE = Path(sys.argv[sys.argv.index("--release") + 1]).resolve() if "--release" in sys.argv else None
ROOT = RELEASE if RELEASE else Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT))
ART = (RELEASE / "results") if RELEASE else ROOT / "verification" / "jev_benchmark_artifacts"
SEMIF = (RELEASE / "results" / "semif") if RELEASE else ROOT / "verification" / "semif_benchmark_artifacts"
GLM_DIR = (RELEASE / "results" / "glm") if RELEASE else ROOT / "verification" / "glm_benchmark_artifacts"
SEMIF_FILES = {"SemIf bracket": "semif-qwen3.5-4b_bracket_val_probs.npz",
               "SemIf bracket + definitions": "semif-qwen3.5-4b_bracket_v1_val_probs.npz",
               "SemIf one-vs-rest": "semif-qwen3.5-4b_ovr_val_probs.npz"}
OPEN_FILES = {k: SEMIF / v for k, v in SEMIF_FILES.items()}
OPEN_FILES["GLM-5.3 (generative)"] = ROOT / "verification" / "glm_benchmark_artifacts" / "glm-5.3_val_probs.npz"
OPEN_FILES["GLM-5.3, 20 retrieved examples"] = ROOT / "verification" / "glm_benchmark_artifacts" / "glm-5.3_fewshot20_val_probs.npz"
OPEN_FILES["GLM-5.3, labels of 20 retrieved complaints"] = ROOT / "verification" / "glm_benchmark_artifacts" / "glm-5.3_shortlist20_val_probs.npz"   # ablation: labels only, no texts
NO_PROBS = {"GLM-5.3 (generative)", "GLM-5.3, 20 retrieved examples", "GLM-5.3, labels of 20 retrieved complaints", "1-nearest-neighbour"}   # generated label only: no distribution, so no ECE / risk-coverage
OUT = (RELEASE / "results") if RELEASE else Path(__file__).resolve().parent
FIG = OUT / "figures"
FIG.mkdir(parents=True, exist_ok=True)
LABELS = json.loads((ROOT / "data" / "label_list.json").read_text())
SYSTEM_KEYS = {  # name in the paper -> key prefix in the combined predictions file
    "Jev zero-shot": "jev_bare", "Jev + form instruction": "jev_form_instruction",
    "Jev + form instruction + definitions": "jev_form_instruction_definitions",
    "SemIf bracket": "semif_bracket", "SemIf bracket + definitions": "semif_bracket_definitions",
    "SemIf one-vs-rest": "semif_ovr",
    "GLM-5.3 (generative)": "glm53",
    "GLM-5.3, 20 retrieved examples": "glm53_fewshot20",
    "20-nearest-neighbour vote": "knn20_vote",
    "GLM-5.3, labels of 20 retrieved complaints": "glm53_shortlist20",
    "1-nearest-neighbour": "knn1",
    "TF-IDF (20k)": "sub20k_tfidf",
    "Jev probabilities (20k)": "sub20k_jev",
    "SemIf probabilities (20k)": "sub20k_semif",
    "TF-IDF + Jev (20k)": "sub20k_tfidf_jev",
    "TF-IDF + SemIf (20k)": "sub20k_tfidf_semif",

    "LR on sentence embeddings": "lr_emb", "TF-IDF + embeddings + LR": "tfidf_emb_lr",
    "TF-IDF + Jev top choice": "ctrl_onehot_jev",
    "TF-IDF + label-name similarity": "ctrl_labelsim",
    "TF-IDF + stacked embedding probabilities": "ctrl_oof_emb",

    "LR on Jev probs": "lr_jev", "TF-IDF + LR": "tfidf_lr", "TF-IDF + Jev + LR": "tfidf_jev_lr",
    "ModernBERT-base (vanilla)": "modernbert_base_vanilla", "ModernBERT-base (distilled)": "modernbert_base_distilled",
    "ModernBERT-large": "modernbert_large", "Qwen3-32B + LoRA": "qwen3_32b_lora"}
K = len(LABELS)
SEED = 42
B_ORD, B_STRAT, B_RC = 10_000, 5_000, 2_000

# Evaluation status (reviewer taxonomy, extended with our own development history):
#   A  no validation-based selection, and validation results did not inform development
#   B  indirect: validation results or a validation-selected model influenced development
#   C  direct: checkpoint, temperature or threshold selected on validation
STATUS = {
    "Jev zero-shot": "A",
    "Jev + form instruction": "B",
    "Jev + form instruction + definitions": "B",
    "SemIf bracket": "A",
    "SemIf bracket + definitions": "B",   # same definitions as Jev's, written after a validation look
    "SemIf one-vs-rest": "A",
    "GLM-5.3 (generative)": "A",
    "GLM-5.3, 20 retrieved examples": "A",
    "20-nearest-neighbour vote": "A",
    "GLM-5.3, labels of 20 retrieved complaints": "A",
    "1-nearest-neighbour": "A",
    "TF-IDF (20k)": "B",
    "Jev probabilities (20k)": "B",
    "SemIf probabilities (20k)": "B",
    "TF-IDF + Jev (20k)": "B",
    "TF-IDF + SemIf (20k)": "B",

    "LR on sentence embeddings": "B", "TF-IDF + embeddings + LR": "B",   # grids extended after earlier passes
    "TF-IDF + Jev top choice": "B",
    "TF-IDF + label-name similarity": "B",
    "TF-IDF + stacked embedding probabilities": "B",

    "LR on Jev probs": "A",
    "TF-IDF + LR": "B",
    "TF-IDF + Jev + LR": "B",
    "ModernBERT-base (vanilla)": "A",
    "ModernBERT-base (distilled)": "B",
    "ModernBERT-large": "C",
    "Qwen3-32B + LoRA": "C",
}

# Validated categorical slots (dataviz reference palette, light) + text/grid tokens
BLUE, ORANGE, AQUA = "#2a78d6", "#eb6834", "#1baf7a"
INK, INK2, MUTED, GRID, NEUTRAL = "#0b0b0b", "#52514e", "#898781", "#e1e0d9", "#b8b7ae"
plt.rcParams.update({
    "font.family": "serif", "font.size": 9, "axes.edgecolor": MUTED, "axes.labelcolor": INK2,
    "xtick.color": INK2, "ytick.color": INK2, "axes.spines.top": False, "axes.spines.right": False,
    "axes.grid": True, "grid.color": GRID, "grid.linewidth": 0.6, "axes.axisbelow": True,
    "savefig.bbox": "tight", "savefig.dpi": 300,
})


# --------------------------------------------------------------------------------------------
# Loading
# --------------------------------------------------------------------------------------------
def softmax(z):
    z = z - z.max(-1, keepdims=True)
    e = np.exp(z)
    return e / e.sum(-1, keepdims=True)


def hub_npz(repo, fname):
    from huggingface_hub import hf_hub_download
    return np.load(hf_hub_download(repo, fname), allow_pickle=True)


def jsonl_by_idx(path, key):
    out = {}
    for line in open(path):
        r = json.loads(line)
        out[r[key]] = r
    return out


def load_jev_variant(path, key, n):
    c = jsonl_by_idx(path, key)
    assert sorted(c) == list(range(n)), f"{path.name}: incomplete"
    # Jev reports probabilities and confidence to two decimals; round away float artifacts from JSON
    # (e.g. 0.41000000000000003) so ties are identical in every layout
    probs = np.round(np.array([c[i]["probs"] for i in range(n)]), 2)
    choice = np.array([LABELS.index(c[i]["choice"]) for i in range(n)])
    conf = np.round(np.array([c[i]["confidence"] for i in range(n)]), 2)
    return choice, probs, conf


def load_systems_release():
    d = np.load(RELEASE / "predictions" / "val_predictions_all_systems.npz")
    systems = {nm: (d[f"{k}_preds"].astype(int), d[f"{k}_probs"]) for nm, k in SYSTEM_KEYS.items()
               if f"{k}_preds" in d.files}
    conf = {nm: d[f"{SYSTEM_KEYS[nm]}_confidence"] for nm in
            ("Jev zero-shot", "Jev + form instruction", "Jev + form instruction + definitions")}
    return d["labels"].astype(int), d["tiers"].astype(str), systems, conf, None


def load_systems():
    if RELEASE:
        return load_systems_release()
    jz = np.load(ART / "jev-1.13.0_val_probs.npz")
    y = jz["labels"].astype(int)
    n = len(y)
    systems, conf = {}, {}
    systems["Jev zero-shot"] = (jz["preds"].astype(int), np.round(jz["probs"], 2))
    conf["Jev zero-shot"] = np.round(jz["confidence"], 2)
    for name, f in [("Jev + form instruction", "jev-1.13.0_v1instr_val_responses.jsonl"),
                    ("Jev + form instruction + definitions", "jev-1.13.0_v1_val_responses.jsonl")]:
        if (ART / f).exists():
            p, pr, c = load_jev_variant(ART / f, "idx", n)
            systems[name] = (p, pr)
            conf[name] = c
    for name, f in OPEN_FILES.items():
        if f.exists():
            d = np.load(f)
            assert (d["labels"] == y).all(), f"{name}: label order mismatch"
            assert np.allclose(d["probs"].sum(-1), 1)
            preds = d["raw_preds"].astype(int) if "raw_preds" in d.files else d["preds"].astype(int)
            systems[name] = (np.where(preds < 0, K, preds), d["probs"].astype(np.float64))
    sub_path = ART / "semif_features_fit20000_val_probs.npz"   # verification/semif_features.py (20k fit subsample)
    if sub_path.exists():
        sd = np.load(sub_path)
        assert (sd["labels"] == y).all()
        for name, key in [('TF-IDF (20k)', 'tfidf'), ('Jev probabilities (20k)', 'jev'), ('SemIf probabilities (20k)', 'semif'), ('TF-IDF + Jev (20k)', 'tfidf_jev'), ('TF-IDF + SemIf (20k)', 'tfidf_semif')]:
            systems[name] = (sd[key].argmax(-1), sd[key])
    knn_path = ART / "knn_vote_val_probs.npz"   # verification/knn_vote.py: few-shot retrieval without the LLM
    if knn_path.exists():
        kd = np.load(knn_path)
        assert (kd["labels"] == y).all()
        systems["20-nearest-neighbour vote"] = (kd["preds"].astype(int), kd["probs"].astype(np.float64))
        systems["1-nearest-neighbour"] = (kd["nn1"].astype(int), np.eye(K)[kd["nn1"].astype(int)])   # label only
    emb_path = ART / "embedding_control_val_probs.npz"   # features control (verification/embedding_control.py)
    if emb_path.exists():
        e = np.load(emb_path)
        assert (e["labels"] == y).all()
        for name, key in [("LR on sentence embeddings", "emb"), ("TF-IDF + embeddings + LR", "tfidf_emb")]:
            systems[name] = (e[key].argmax(-1), e[key])
    ctrl_v2, ctrl_v1 = ART / "controls_v2_val_probs.npz", ART / "controls_val_probs.npz"
    if ctrl_v2.exists():   # verification/features_controls_v2.py (v1 kept for the record)
        c, spec = np.load(ctrl_v2), [("TF-IDF + Jev top choice", "onehot_choice"), ("TF-IDF + label-name similarity", "labelsim"),
                                     ("TF-IDF + stacked embedding probabilities", "oof_emb_insplit")]
    elif ctrl_v1.exists():
        c, spec = np.load(ctrl_v1), [("TF-IDF + Jev top choice", "onehot_jev"), ("TF-IDF + label-name similarity", "labelsim"),
                                     ("TF-IDF + stacked embedding probabilities", "oof_emb")]
    if ctrl_v2.exists() or ctrl_v1.exists():
        assert (c["labels"] == y).all()
        for name, key in spec:
            systems[name] = (c[key].argmax(-1), c[key])
    lr = np.load(ART / "jev-1.13.0_features_val_probs.npz")
    assert (lr["labels"] == y).all()
    for name, key in [("LR on Jev probs", "jev"), ("TF-IDF + LR", "tfidf"), ("TF-IDF + Jev + LR", "tfidf_jev")]:
        systems[name] = (lr[key].argmax(-1), lr[key])
    tiers = None
    comps = [("ModernBERT-base (vanilla)", "earino/ecbs5200-week6-vanilla-baseline", "val_predictions.npz"),
             ("ModernBERT-base (distilled)", "earino/ecbs5200-week6-distilled-student", "val_predictions.npz"),
             ("ModernBERT-large", "earino/ecbs5200-modernbert-large-control-train-test", "val_logits_best.npz"),
             ("Qwen3-32B + LoRA", "earino/ecbs5200-qwen3-32b-phase1-v4-teacher-canonical",
              "val_logits_canonical_final.npz")]
    for name, repo, f in comps:
        d = hub_npz(repo, f)
        assert (d["labels"] == y).all(), f"{name}: label order mismatch"
        pr = softmax(d["logits"].astype(np.float64))
        # Alignment check at the prediction level, not only the aggregate metric
        assert (pr.argmax(-1) == d["preds"]).mean() > 0.999, f"{name}: preds disagree with logits"
        systems[name] = (pr.argmax(-1), pr)
        t = d["tiers"] if "tiers" in d.files else d["val_tiers"]
        tiers = np.asarray(t).astype(str) if tiers is None else tiers
        assert (np.asarray(t).astype(str) == tiers).all()
    return y, tiers, systems, conf, comps


# --------------------------------------------------------------------------------------------
# Metrics (weighted counts so the same code serves point estimates and bootstraps)
# --------------------------------------------------------------------------------------------
def cnt(p):
    """Predicted counts per class; an out-of-taxonomy prediction (value K, an unmatched generated answer) is a
    wrong answer that is a false positive for no class."""
    return np.bincount(p, minlength=K + 1)[:K]


def class_f1(y, p, w):
    tp = np.bincount(y, weights=w * (p == y), minlength=K)
    pred = np.bincount(p, weights=w, minlength=K + 1)[:K]
    true = np.bincount(y, weights=w, minlength=K)
    denom = pred + true
    f1 = np.divide(2 * tp, denom, out=np.zeros(K), where=denom > 0)
    return f1, true


def macro(f1, true, mask=None, fixed=False):
    sel = np.ones(K, bool) if fixed else (true > 0)
    if mask is not None:
        sel = sel & mask
    return f1[sel].mean() if sel.any() else np.nan


def ece(y, probs, preds=None, bins=15):
    """Top-label ECE for the reported prediction: its assigned probability against its correctness. For Jev the
    reported prediction is the returned choice; for SemIf the bracket winner (both can differ from the argmax)."""
    preds = probs.argmax(-1) if preds is None else preds
    conf = probs[np.arange(len(preds)), preds]
    correct = preds == y
    edges = np.linspace(0, 1, bins + 1)
    total = 0.0
    for lo, hi in zip(edges[:-1], edges[1:]):
        m = (conf > lo) & (conf <= hi)
        if m.any():
            total += m.mean() * abs(correct[m].mean() - conf[m].mean())
    return total


def conditional_tier_f1(y, p, tiers, tier, tier_classes):
    m = tiers == tier
    return f1_score(y[m], p[m], labels=tier_classes, average="macro", zero_division=0)


# --------------------------------------------------------------------------------------------
# Analyses
# --------------------------------------------------------------------------------------------
def point_metrics(y, tiers, systems, tier_mask, tier_classes):
    out = {}
    ones = np.ones(len(y))
    for name, (p, pr) in systems.items():
        f1, true = class_f1(y, p, ones)
        assert np.isclose(macro(f1, true), f1_score(y, p, labels=np.arange(K), average="macro", zero_division=0))
        tier_vals = {t: macro(f1, true, tier_mask[t]) for t in ("head", "mid", "tail")}
        # Unconditional tier F1 decomposes overall macro F1 exactly
        recon = sum(tier_mask[t].sum() * tier_vals[t] for t in tier_vals) / K
        assert np.isclose(recon, macro(f1, true)), name
        out[name] = {
            "status": STATUS[name], "accuracy": float((p == y).mean()), "macro_f1": float(macro(f1, true)),
            **{f"{t}_f1": float(v) for t, v in tier_vals.items()},
            **{f"{t}_f1_conditional": float(conditional_tier_f1(y, p, tiers, t, tier_classes[t]))
               for t in ("head", "mid", "tail")},
            "zero_f1_classes": int((f1 == 0).sum()), "top_label_ece": None if name in NO_PROBS else float(ece(y, pr, p)),
            "distinct_labels_predicted": int(len(np.unique(p))),
        }
    return out


def bootstrap(y, systems, tier_mask, kind, B, fixed=False):
    """[B, S] macro F1 and [B, S, 3] tier F1 from paired resamples."""
    rng = np.random.default_rng(SEED)
    n = len(y)
    names = list(systems)
    by_class = [np.where(y == c)[0] for c in range(K)]
    mac = np.empty((B, len(names)))
    tier = np.empty((B, len(names), 3))
    for b in range(B):
        if kind == "ordinary":
            w = np.bincount(rng.integers(0, n, n), minlength=n).astype(float)
        else:  # class-stratified: resample within each class, supports fixed
            w = np.zeros(n)
            for idx in by_class:
                if len(idx):
                    np.add.at(w, idx[rng.integers(0, len(idx), len(idx))], 1.0)
        for s, name in enumerate(names):
            f1, true = class_f1(y, systems[name][0], w)
            mac[b, s] = macro(f1, true, fixed=fixed)
            for t_i, t in enumerate(("head", "mid", "tail")):
                tier[b, s, t_i] = macro(f1, true, tier_mask[t], fixed=fixed)
    return names, mac, tier


def ci(a):
    lo, hi = np.nanpercentile(a, [2.5, 97.5])
    return [float(lo), float(hi)]


def risk_coverage(y, p, score, tail_mask_ex, targets=(0.1, 0.25, 0.5)):
    """Tie-aware selective risk. Operating points are score thresholds: an example is answered when its
    score is >= t, so tied examples are always kept or dropped together and only attainable coverages are
    reported. For each target coverage c, t is the highest threshold whose coverage is >= c on the full
    split. Intervals: the same fixed threshold t is applied to each bootstrap resample (B_RC resamples),
    so they describe the error of that threshold rule; its coverage varies across resamples."""
    n = len(y)
    err = (p != y)
    order = np.argsort(-score, kind="stable")
    s_sorted, e_sorted, t_sorted = score[order], err[order], tail_mask_ex[order]
    ends = np.r_[np.nonzero(np.diff(s_sorted) != 0)[0], n - 1]      # last row of each tie group
    cov = (ends + 1) / n
    risk = np.cumsum(e_sorted)[ends] / (ends + 1)
    sizes = np.diff(np.r_[-1, ends])
    aurc = float((sizes * risk).sum() / n)                           # each row weighted by its group's risk
    rng = np.random.default_rng(SEED)
    boots = [rng.integers(0, n, n) for _ in range(B_RC)]
    pts = {}
    for c in targets:
        g = int(np.argmax(cov >= c))
        t = float(s_sorted[ends[g]])
        keep = score >= t
        be = [err[idx][score[idx] >= t].mean() for idx in boots]
        pts[str(c)] = {"threshold": t, "coverage": float(keep.mean()), "n_answered": int(keep.sum()),
                       "error_rate": float(err[keep].mean()), "ci95": ci(be),
                       "tail_share_retained": float(tail_mask_ex[keep].mean()),
                       "tail_recall_retained": float(tail_mask_ex[keep].sum() / max(1, tail_mask_ex.sum()))}
    uniq, counts = np.unique(score, return_counts=True)
    return {"aurc": aurc, "points": pts, "distinct_scores": int(len(uniq)), "largest_tie": int(counts.max()),
            "curve": (cov, risk)}


def latest_year(text):
    ys = [int(m) for m in re.findall(r"(?<![\d$])(199\d|20[01]\d)(?!\d)(?!\.\d)", text)]
    return max(ys) if ys else None


# Candidate old/new wording pairs; each is kept only if the year test on training data supports it
CANDIDATE_PAIRS = [
    ("Credit reporting company's investigation",
     "Problem with a credit reporting company's investigation into an existing problem"),
    ("Disclosure verification of debt", "Written notification about debt"),
    ("Improper contact or sharing of info", "Threatened to contact someone or share information improperly"),
    ("Taking/threatening an illegal action", "Took or threatened to take negative or legal action"),
    ("Loan modification,collection,foreclosure", "Struggling to pay your mortgage"),
    ("Loan servicing, payments, escrow account", "Trouble during payment process"),
    ("Application, originator, mortgage broker", "Applying for a mortgage or refinancing an existing mortgage"),
    ("Settlement process and costs", "Closing on a mortgage"),
    ("Can't repay my loan", "Struggling to pay your loan"),
]


def year_test(train_texts, train_y):
    rows, kept = [], []
    years = [latest_year(t) for t in train_texts]
    for old, new in CANDIDATE_PAIRS:
        stats = {}
        for lab in (old, new):
            ys = [yr for yr, l in zip(years, train_y) if l == LABELS.index(lab) and yr is not None]
            n_lab = int((train_y == LABELS.index(lab)).sum())
            stats[lab] = {"n": n_lab, "with_year": len(ys),
                          "share_le_2016": float(np.mean([v <= 2016 for v in ys])) if ys else float("nan"),
                          "share_ge_2017": float(np.mean([v >= 2017 for v in ys])) if ys else float("nan")}
        ok = (stats[old]["share_le_2016"] >= 0.85 and stats[new]["share_ge_2017"] >= 0.5
              and stats[old]["with_year"] >= 20 and stats[new]["with_year"] >= 20)
        rows.append({"old": old, "new": new, **{f"old_{k}": v for k, v in stats[old].items()},
                     **{f"new_{k}": v for k, v in stats[new].items()}, "kept": bool(ok)})
        if ok:
            kept.append((old, new))
    return rows, kept


def merged_sensitivity(y, systems, pairs, names_for_gap):
    """Two rescoring procedures for merged historical labels:
      remap:     map each system's existing predicted label and the true label into the merged set
      aggregate: sum each system's probabilities within every merged class, then take the argmax
    Neither is equivalent to training or querying with the merged taxonomy from the start."""
    to = np.arange(K + 1)   # index K = out-of-taxonomy prediction (unmatched generated answer), kept as is
    for old, new in pairs:
        to[LABELS.index(old)] = LABELS.index(new)
    M = np.zeros((K, K))
    M[np.arange(K), to[:K]] = 1.0
    ym = to[y]
    present = np.zeros(K, bool)
    present[np.unique(ym)] = True
    n = len(y)

    def merged_preds(name, how):
        p, pr = systems[name]
        return to[p] if how == "remap" else (pr @ M).argmax(-1)

    def mf1(pred, w):
        f1, true = class_f1(ym, pred, w)
        return macro(f1, true, mask=present, fixed=True)

    res = {name: {how: {"macro_f1_merged": float(mf1(merged_preds(name, how), np.ones(n))),
                        "accuracy_merged": float((merged_preds(name, how) == ym).mean())}
                  for how in ("remap", "aggregate")} for name in systems}
    rng = np.random.default_rng(SEED)
    boots = [np.bincount(rng.integers(0, n, n), minlength=n).astype(float) for _ in range(2000)]
    gaps = {}
    for a, b in names_for_gap:
        pa, pb = systems[a][0], systems[b][0]
        fa, ta = class_f1(y, pa, np.ones(n)); fb, tb = class_f1(y, pb, np.ones(n))
        pt_o = macro(fa, ta, fixed=True) - macro(fb, tb, fixed=True)
        d_orig = []
        for w in boots:
            fa, ta = class_f1(y, pa, w); fb, tb = class_f1(y, pb, w)
            d_orig.append(macro(fa, ta, fixed=True) - macro(fb, tb, fixed=True))
        d_orig = np.array(d_orig)
        rec = {"delta_original": float(pt_o)}
        for how in ("remap", "aggregate"):
            ma, mb = merged_preds(a, how), merged_preds(b, how)
            pt_m = mf1(ma, np.ones(n)) - mf1(mb, np.ones(n))
            d_m = np.array([mf1(ma, w) - mf1(mb, w) for w in boots])
            rec[how] = {"delta_merged": float(pt_m), "change_in_gap": float(pt_m - pt_o),
                        "change_ci95": ci(d_m - d_orig)}
        gaps[f"{a} || {b}"] = rec
    return {"classes_after_merge": int(present.sum()), "systems": res, "gaps": gaps}


def near_duplicates(val_texts, fit_texts, y_val, y_fit):
    from sklearn.feature_extraction.text import TfidfVectorizer
    norm = lambda t: re.sub(r"\s+", " ", t.lower()).strip()
    fit_hash = {}
    for i, t in enumerate(fit_texts):
        fit_hash.setdefault(hashlib.sha256(norm(t).encode()).hexdigest(), []).append(i)
    exact = [i for i, t in enumerate(val_texts) if hashlib.sha256(norm(t).encode()).hexdigest() in fit_hash]
    vec = TfidfVectorizer(max_features=50000, sublinear_tf=True, ngram_range=(1, 2)).fit(fit_texts)
    F, V = vec.transform(fit_texts), vec.transform(val_texts)
    best, arg = np.zeros(len(val_texts)), np.zeros(len(val_texts), int)
    for s in range(0, V.shape[0], 500):
        sims = (V[s:s + 500] @ F.T).toarray()
        best[s:s + 500] = sims.max(1)
        arg[s:s + 500] = sims.argmax(1)
    out = {"exact_duplicates": len(exact),
           "exact_same_label": int(sum(y_fit[fit_hash[hashlib.sha256(norm(val_texts[i]).encode()).hexdigest()][0]]
                                       == y_val[i] for i in exact))}
    for thr in (0.95, 0.9, 0.8):
        m = best >= thr
        out[f"nn_cosine_ge_{thr}"] = int(m.sum())
        out[f"nn_cosine_ge_{thr}_same_label"] = int((y_fit[arg[m]] == y_val[m]).sum())
    return out, best


def main():
    from utils.data_utils import load_course_data
    y, tiers, systems, conf, comps = load_systems()
    order = list(SYSTEM_KEYS)
    systems = {nm: systems[nm] for nm in order if nm in systems}

    def pscore(nm):
        """Probability each system assigns to its own reported prediction (score for selective prediction)."""
        pr, pd = systems[nm][1], systems[nm][0]
        return pr[np.arange(len(pd)), np.minimum(pd, K - 1)]
    n = len(y)
    names = list(systems)
    class_tier = {c: tiers[y == c][0] for c in range(K)}
    tier_mask = {t: np.array([class_tier[c] == t for c in range(K)]) for t in ("head", "mid", "tail")}
    tier_classes = {t: [c for c in range(K) if class_tier[c] == t] for t in ("head", "mid", "tail")}
    numbers = {"n_val": n, "classes": K, "tier_classes": {t: len(v) for t, v in tier_classes.items()},
               "tier_examples": {t: int((tiers == t).sum()) for t in ("head", "mid", "tail")},
               "singleton_classes_val": int((np.bincount(y, minlength=K) == 1).sum())}

    print("Point metrics...")
    numbers["point"] = point_metrics(y, tiers, systems, tier_mask, tier_classes)

    # Primary: fixed 113-label macro F1 (a class absent from a resample scores 0 for every system).
    # Sensitivities: averaging over classes with support in the resample, and a class-stratified bootstrap.
    print(f"Bootstraps: fixed-label x{B_ORD}, support-based x{B_ORD}, class-stratified x{B_STRAT}...")
    _, mac_f, tier_f = bootstrap(y, systems, tier_mask, "ordinary", B_ORD, fixed=True)
    _, mac_o, tier_o = bootstrap(y, systems, tier_mask, "ordinary", B_ORD)
    _, mac_s, tier_s = bootstrap(y, systems, tier_mask, "stratified", B_STRAT)
    for s, name in enumerate(names):
        numbers["point"][name]["macro_f1_ci95"] = ci(mac_f[:, s])
        numbers["point"][name]["tail_f1_ci95"] = ci(tier_f[:, s, 2])

    pairs = [
        ("Jev zero-shot", "ModernBERT-base (vanilla)"), ("Jev zero-shot", "ModernBERT-base (distilled)"),
        ("Jev zero-shot", "ModernBERT-large"), ("Jev zero-shot", "Qwen3-32B + LoRA"),
        ("Jev zero-shot", "TF-IDF + LR"),
        ("Jev + form instruction", "Jev zero-shot"),
        ("Jev + form instruction + definitions", "Jev zero-shot"),
        ("Jev + form instruction + definitions", "Jev + form instruction"),
        ("SemIf bracket + definitions", "Jev zero-shot"),
        ("Jev + form instruction + definitions", "ModernBERT-base (vanilla)"),
        ("Jev + form instruction + definitions", "Qwen3-32B + LoRA"),
        ("LR on Jev probs", "Jev zero-shot"), ("LR on Jev probs", "TF-IDF + LR"),
        ("TF-IDF + Jev + LR", "TF-IDF + LR"),
        ("TF-IDF + Jev + LR", "ModernBERT-base (vanilla)"), ("TF-IDF + Jev + LR", "ModernBERT-base (distilled)"),
        ("TF-IDF + Jev + LR", "ModernBERT-large"), ("TF-IDF + Jev + LR", "Qwen3-32B + LoRA"),
        ("SemIf bracket", "Jev zero-shot"), ("SemIf bracket", "TF-IDF + LR"),
        ("SemIf bracket", "ModernBERT-base (vanilla)"), ("SemIf bracket", "Qwen3-32B + LoRA"),
        ("SemIf bracket + definitions", "SemIf bracket"),
        ("SemIf bracket + definitions", "Jev + form instruction + definitions"),
        ("SemIf one-vs-rest", "SemIf bracket"), ("SemIf one-vs-rest", "Jev zero-shot"),
        ("TF-IDF + embeddings + LR", "TF-IDF + LR"), ("TF-IDF + Jev + LR", "TF-IDF + embeddings + LR"),
        ("LR on sentence embeddings", "LR on Jev probs"),
        ("TF-IDF + Jev top choice", "TF-IDF + LR"), ("TF-IDF + Jev + LR", "TF-IDF + Jev top choice"),
        ("TF-IDF + label-name similarity", "TF-IDF + LR"), ("TF-IDF + Jev + LR", "TF-IDF + label-name similarity"),
        ("TF-IDF + stacked embedding probabilities", "TF-IDF + LR"),
        ("TF-IDF + Jev + LR", "TF-IDF + stacked embedding probabilities"),
        ("TF-IDF + LR", "Jev + form instruction + definitions"), ("TF-IDF + LR", "GLM-5.3 (generative)"),
        ("ModernBERT-base (vanilla)", "TF-IDF + LR"), ("Qwen3-32B + LoRA", "TF-IDF + LR"),
        ("ModernBERT-base (vanilla)", "TF-IDF + Jev + LR"),
        ("GLM-5.3 (generative)", "SemIf bracket + definitions"),
        ("GLM-5.3, 20 retrieved examples", "GLM-5.3 (generative)"), ("GLM-5.3, 20 retrieved examples", "TF-IDF + LR"),
        ("GLM-5.3, 20 retrieved examples", "20-nearest-neighbour vote"), ("20-nearest-neighbour vote", "TF-IDF + LR"),
        ("TF-IDF + SemIf (20k)", "TF-IDF (20k)"), ("TF-IDF + Jev (20k)", "TF-IDF (20k)"),
        ("TF-IDF + Jev (20k)", "TF-IDF + SemIf (20k)"), ("SemIf probabilities (20k)", "Jev probabilities (20k)"),
        ("GLM-5.3, 20 retrieved examples", "Jev + form instruction + definitions"),
        ("GLM-5.3, 20 retrieved examples", "ModernBERT-base (vanilla)"),
        ("GLM-5.3, 20 retrieved examples", "1-nearest-neighbour"), ("1-nearest-neighbour", "20-nearest-neighbour vote"),
        ("GLM-5.3, labels of 20 retrieved complaints", "GLM-5.3 (generative)"), ("GLM-5.3, 20 retrieved examples", "GLM-5.3, labels of 20 retrieved complaints"),
        ("GLM-5.3, labels of 20 retrieved complaints", "20-nearest-neighbour vote"),
        ("GLM-5.3, 20 retrieved examples", "TF-IDF + label-name similarity"),
        ("GLM-5.3 (generative)", "Jev zero-shot"), ("GLM-5.3 (generative)", "Jev + form instruction + definitions"),
        ("GLM-5.3 (generative)", "SemIf bracket"), ("GLM-5.3 (generative)", "TF-IDF + LR"),
        ("GLM-5.3 (generative)", "ModernBERT-base (vanilla)"), ("GLM-5.3 (generative)", "Qwen3-32B + LoRA"),
    ]
    pairs = [(a, b) for a, b in pairs if a in systems and b in systems]
    idx = {nm: i for i, nm in enumerate(names)}
    numbers["paired"] = {}
    for a, b in pairs:
        i, j = idx[a], idx[b]
        pt = numbers["point"][a]["macro_f1"] - numbers["point"][b]["macro_f1"]
        rec = {"delta": pt,
               "ci95": ci(mac_f[:, i] - mac_f[:, j]),
               "ci95_support_based": ci(mac_o[:, i] - mac_o[:, j]),
               "ci95_class_stratified": ci(mac_s[:, i] - mac_s[:, j]),
               "tail_delta": numbers["point"][a]["tail_f1"] - numbers["point"][b]["tail_f1"],
               "tail_ci95": ci(tier_f[:, i, 2] - tier_f[:, j, 2]),
               "tail_ci95_support_based": ci(tier_o[:, i, 2] - tier_o[:, j, 2]),
               "tail_ci95_class_stratified": ci(tier_s[:, i, 2] - tier_s[:, j, 2])}
        rec["excludes_zero"] = bool(rec["ci95"][0] > 0 or rec["ci95"][1] < 0)
        tails = [rec["tail_ci95"], rec["tail_ci95_support_based"], rec["tail_ci95_class_stratified"]]
        rec["tail_conclusion_agrees_across_conventions"] = len({(lo > 0) - (hi < 0) for lo, hi in tails}) == 1
        numbers["paired"][f"{a} || {b}"] = rec

    # Paired accuracy differences (same resampling scheme, B_ORD resamples)
    rng_a = np.random.default_rng(SEED)
    boots_a = [rng_a.integers(0, n, n) for _ in range(B_ORD)]
    correct_by = {nm: (systems[nm][0] == y).astype(float) for nm in names}
    for a, b in pairs:
        d = correct_by[a] - correct_by[b]
        bs = np.array([d[i].mean() for i in boots_a])
        numbers["paired"][f"{a} || {b}"].update(acc_delta=float(d.mean()), acc_ci95=ci(bs))

    # Exact decomposition of Δ macro F1 into head/mid/tail parts: (classes in group / K) x Δ group F1
    frac = {t: tier_mask[t].sum() / K for t in ("head", "mid", "tail")}
    numbers["decomposition"] = {}
    for a, b in pairs:
        i, j = idx[a], idx[b]
        rec = {}
        for t_i, t in enumerate(("head", "mid", "tail")):
            pt = frac[t] * (numbers["point"][a][f"{t}_f1"] - numbers["point"][b][f"{t}_f1"])
            rec[t] = {"part": float(pt), "ci95": ci(frac[t] * (tier_f[:, i, t_i] - tier_f[:, j, t_i]))}
        rec["total"] = numbers["paired"][f"{a} || {b}"]["delta"]
        assert np.isclose(sum(rec[t]["part"] for t in ("head", "mid", "tail")), rec["total"])
        numbers["decomposition"][f"{a} || {b}"] = rec

    # Proper scoring rules on the full distribution (systems that return one); NLL floored at 1e-6
    numbers["scoring"] = {}
    for nm in names:
        if nm in NO_PROBS:
            continue
        pr = systems[nm][1]
        pt = np.clip(pr[np.arange(n), y], 1e-6, 1)
        onehot = np.zeros_like(pr); onehot[np.arange(n), y] = 1
        numbers["scoring"][nm] = {"nll_floor_1e-6": float(-np.log(pt).mean()),
                                  "brier": float(((pr - onehot) ** 2).sum(-1).mean()),
                                  "p_true_is_zero": float((pr[np.arange(n), y] == 0).mean())}

    # Over-prediction profile: log((predicted+1)/(true+1)) per class; correlation between systems
    true_c = np.bincount(y, minlength=K)
    prof = {nm: np.log((cnt(systems[nm][0]) + 1) / (true_c + 1)) for nm in names}
    # Net of label frequency: residuals of each profile after regressing on log(true count + 1)
    lf = np.log(true_c + 1)
    Xf = np.c_[np.ones(K), lf]
    resid = {nm: prof[nm] - Xf @ np.linalg.lstsq(Xf, prof[nm], rcond=None)[0] for nm in names}
    numbers["overprediction_correlation_net_of_frequency"] = {
        ref: {nm: float(np.corrcoef(resid[ref], resid[nm])[0, 1]) for nm in names if nm != ref}
        for ref in ("Jev zero-shot", "SemIf bracket", "GLM-5.3 (generative)", "Qwen3-32B + LoRA") if ref in resid}
    numbers["overprediction_vs_log_frequency"] = {nm: float(np.corrcoef(prof[nm], lf)[0, 1]) for nm in names}
    numbers["overprediction_correlation"] = {
        ref: {nm: float(np.corrcoef(prof[ref], prof[nm])[0, 1]) for nm in names if nm != ref}
        for ref in ("Jev zero-shot", "SemIf bracket", "GLM-5.3 (generative)", "Qwen3-32B + LoRA") if ref in prof}
    numbers["predicted_counts"] = {nm: {LABELS[c]: int(v) for c, v in enumerate(cnt(systems[nm][0]))}
                                   for nm in names}
    numbers["top_overpredicted"] = {nm: [LABELS[c] for c in np.argsort(-(cnt(systems[nm][0]) - true_c))[:8]]
                                    for nm in names}

    # Most-confident-10% subset by top probability: error and tail share, every system with a distribution
    numbers["confident_decile"] = {}
    for nm in names:
        if nm in NO_PROBS:
            continue
        top = pscore(nm)
        thr = np.quantile(top, 0.9)
        keep = top >= thr
        numbers["confident_decile"][nm] = {"coverage": float(keep.mean()),
                                           "error": float((systems[nm][0][keep] != y[keep]).mean()),
                                           "tail_share": float((tiers[keep] == "tail").mean()),
                                           "distinct_top_prob_values": int(len(np.unique(top)))}

    print("Risk-coverage...")
    tail_ex = tiers == "tail"
    rc_specs = [("Jev zero-shot", "confidence", conf["Jev zero-shot"]),
                ("Jev zero-shot", "top probability", pscore("Jev zero-shot")),
                ("TF-IDF + Jev + LR", "top probability", pscore("TF-IDF + Jev + LR")),
                ("Qwen3-32B + LoRA", "top probability", pscore("Qwen3-32B + LoRA"))]
    if "Jev + form instruction + definitions" in conf:
        rc_specs.insert(2, ("Jev + form instruction + definitions", "confidence",
                            conf["Jev + form instruction + definitions"]))
    if "SemIf bracket" in systems:
        rc_specs.append(("SemIf bracket", "top probability", pscore("SemIf bracket")))
    rc = {}
    for name, sname, score in rc_specs:
        r = risk_coverage(y, systems[name][0], score, tail_ex)
        rc[f"{name} | {sname}"] = r
    numbers["risk_coverage"] = {k: {kk: vv for kk, vv in v.items() if kk != "curve"} for k, v in rc.items()}
    cz = conf["Jev zero-shot"]
    correct = systems["Jev zero-shot"][0] == y
    tp = pscore("Jev zero-shot")
    correct_jev = systems["Jev zero-shot"][0] == y
    numbers["jev_top_probability_buckets"] = {
        f"[{lo},{hi})": {"n": int(((tp >= lo) & (tp < hi)).sum()),
                         "accuracy": float(correct_jev[(tp >= lo) & (tp < hi)].mean())}
        for lo, hi in [(0.9, 1.01), (0.5, 0.9), (0.0, 0.5)] if ((tp >= lo) & (tp < hi)).any()}
    numbers["jev_confidence_buckets"] = {
        f"[{lo},{hi})": {"n": int(((cz >= lo) & (cz < hi)).sum()),
                         "accuracy": float(correct[(cz >= lo) & (cz < hi)].mean())}
        for lo, hi in [(0.9, 1.01), (0.5, 0.9), (0.0, 0.5)]}

    # Open reproduction: agreement with Jev, composed-probability buckets, predicted counts for the
    # error-concentration table, and the labels each system over-predicts most
    numbers["semif"] = {}
    for name in [nm for nm in OPEN_FILES if nm in systems and nm not in NO_PROBS]:
        p, pr = systems[name]
        top = pr[np.arange(len(p)), p]
        corr = p == y
        numbers["semif"][name] = {
            "agreement_with_jev_zero_shot": float((p == systems["Jev zero-shot"][0]).mean()),
            "top_probability_buckets": {
                f"[{lo},{hi})": {"share": float(((top >= lo) & (top < hi)).mean()),
                                 "accuracy": float(corr[(top >= lo) & (top < hi)].mean())}
                for lo, hi in [(0.9, 1.01), (0.5, 0.9), (0.0, 0.5)]},
            "predicted_counts": {LABELS[c]: int(v) for c, v in enumerate(cnt(p))},
            "most_overpredicted": [{"label": LABELS[c], "predicted": int(cnt(p)[c]),
                                    "true": int(np.bincount(y, minlength=K)[c])}
                                   for c in np.argsort(-(cnt(p) - np.bincount(y, minlength=K)))[:5]],
        }
    numbers["semif_diagnostics"] = {}
    for nm, f in [("SemIf bracket", "semif-qwen3.5-4b_bracket_results_full.json"),
                  ("SemIf bracket + definitions", "semif-qwen3.5-4b_bracket_v1_results_full.json"),
                  ("SemIf one-vs-rest", "semif-qwen3.5-4b_ovr_results_full.json")]:
        if (SEMIF / f).exists():
            r = json.loads((SEMIF / f).read_text())
            numbers["semif_diagnostics"][nm] = {**r["semif_diag"], "ops": r["semif_ops"]}
    # Robustness of the bracket to the seeded grouping of labels (seed 42 is the reported one)
    seed_preds = {}
    for seed, f in [(42, "semif-qwen3.5-4b_bracket_val_probs.npz"), (7, "semif-qwen3.5-4b_bracket_g7_val_probs.npz"),
                    (123, "semif-qwen3.5-4b_bracket_g123_val_probs.npz")]:
        if (SEMIF / f).exists():
            d = np.load(SEMIF / f)
            assert (d["labels"] == y).all()
            pp = (d["raw_preds"] if "raw_preds" in d.files else d["preds"]).astype(int)
            seed_preds[seed] = np.where(pp < 0, K, pp)
    if len(seed_preds) == 3:
        ones_s = np.ones(n)
        numbers["semif_grouping_seeds"] = {
            str(sd): {"accuracy": float((pp == y).mean()), "macro_f1": float(macro(*class_f1(y, pp, ones_s), fixed=True))}
            for sd, pp in seed_preds.items()}
        a, b, c = seed_preds[42], seed_preds[7], seed_preds[123]
        numbers["semif_grouping_seeds"]["all_three_agree"] = float(((a == b) & (b == c)).mean())
    glm_resp = GLM_DIR / "glm-5.3_val_responses.jsonl"
    if glm_resp.exists():
        sys.path.insert(0, str(ROOT / "verification"))
        import re as _re
        norm = {_re.sub(r"[^a-z0-9]", "", l.lower()): i for i, l in enumerate(LABELS)}
        exact = fallback = none = 0
        for line in glm_resp.read_text().splitlines():
            a = json.loads(line)["answer"]
            first = a.strip().strip('"\'`').splitlines()[0] if a.strip() else ""
            key = _re.sub(r"[^a-z0-9]", "", _re.sub(r"^[-*\d.\s)]+", "", first).lower())
            if key in norm:
                exact += 1
            elif json.loads(line)["label_idx"] is not None:
                fallback += 1
            else:
                none += 1
        numbers["glm_matching"] = {"exact_after_normalization": exact, "substring_fallback": fallback, "unmatched": none}
    numbers["glm_tokens"] = {}
    for tag in ["glm-5.3", "glm-5.3_fewshot20", "glm-5.3_shortlist20"]:
        fr = GLM_DIR / f"{tag}_val_responses.jsonl"
        if not fr.exists():
            continue
        final = [json.loads(l) for l in fr.read_text().splitlines()]
        tr = GLM_DIR / f"{tag}_val_responses_truncated_first_attempt.jsonl"
        first = [json.loads(l) for l in tr.read_text().splitlines()] if tr.exists() else []
        nf = len(final)
        numbers["glm_tokens"][tag] = {
            "n": nf, "retried": len(first),
            "input_mean_final": float(np.mean([r["input_tokens"] for r in final])),
            "output_mean_final": float(np.mean([r["output_tokens"] for r in final])),
            "input_mean_incl_retries": float((sum(r["input_tokens"] for r in final) + sum(r["input_tokens"] for r in first)) / nf),
            "output_mean_incl_retries": float((sum(r["output_tokens"] for r in final) + sum(r["output_tokens"] for r in first)) / nf),
            "retried_final_output_max": int(max([r["output_tokens"] for r in final if r.get("max_tokens", 0) > 16384], default=0)),
            "retried_final_output_over_2000": int(sum(r["output_tokens"] > 2000 for r in final if r.get("max_tokens", 0) > 16384)),
            "latency_p50_s": float(np.median([r["latency_s"] for r in final])),
            "latency_p95_s": float(np.percentile([r["latency_s"] for r in final], 95))}
    ctrl_res = ART / "controls_results.json"
    if ctrl_res.exists():
        cr = json.loads(ctrl_res.read_text())
        numbers["logit_adjustment"] = cr["logit_adjustment"]
        numbers["learning_curve"] = cr["learning_curve"]
    ctrl2 = ART / "controls_v2_results.json"
    if ctrl2.exists():
        c2 = json.loads(ctrl2.read_text())
        agg = {}
        for r in c2["learning_curve_nested"]:
            agg.setdefault((r["model"], r["n"]), []).append(r)
        numbers["learning_curve_nested"] = [
            {"model": m, "n": nn, "seeds": len(rs),
             **{f"{k}_{st}": float(fn([r[k] for r in rs])) for k in ("accuracy", "macro_f1")
                for st, fn in (("mean", np.mean), ("min", np.min), ("max", np.max))}}
            for (m, nn), rs in sorted(agg.items())]
        numbers["controls_v2_selected"] = c2["selected"]
        numbers["returned_choice_differs_from_argmax"] = c2["returned_choice_differs_from_argmax"]
        numbers["controls_selected"] = cr["selected"]
    numbers["true_counts"] = {LABELS[c]: int(v) for c, v in enumerate(np.bincount(y, minlength=K))}
    numbers["jev_predicted_counts"] = {nm: {LABELS[c]: int(v) for c, v in enumerate(cnt(systems[nm][0]))}
                                       for nm in ("Jev zero-shot", "Jev + form instruction + definitions") if nm in systems}

    print("Merged-label sensitivity (year test on training data)...")
    train_ds, val_ds, test_ds = load_course_data()
    yr_rows, kept = year_test(list(train_ds["text"]), np.array(train_ds["label"]))
    numbers["year_test"] = yr_rows
    gap_pairs = [("Jev zero-shot", "Qwen3-32B + LoRA"), ("Jev zero-shot", "ModernBERT-base (vanilla)"),
                 ("TF-IDF + Jev + LR", "Qwen3-32B + LoRA")]
    numbers["merged"] = {"pairs_merged": kept, **merged_sensitivity(y, systems, kept, gap_pairs)}

    print("Near-duplicate audit...")
    val_texts = list(val_ds["text"])
    if RELEASE:   # the public dataset is loaded by the course loader; confirm it yields exactly the released rows
        want = np.load(RELEASE / "predictions" / "val_predictions_all_systems.npz")["text_sha256"]
        got = np.array([hashlib.sha256(t.encode()).hexdigest() for t in val_texts])
        assert (want == got).all(), f"{(want != got).sum()} evaluation texts differ from the released hashes"
    fit_texts = list(train_ds["text"]) + list(test_ds["text"])
    y_fit = np.concatenate([train_ds["label"], test_ds["label"]])
    nd, best = near_duplicates(val_texts, fit_texts, y, y_fit)
    numbers["near_duplicates"] = nd

    print("Deduplicated re-analysis (validation examples with a fit-set neighbour at cosine >= 0.9 removed)...")
    keep = best < 0.9
    yk = y[keep]
    sys_k = {nm: (p[keep], pr[keep]) for nm, (p, pr) in systems.items()}
    ded = {"n_kept": int(keep.sum()), "classes_with_support": int(len(np.unique(yk))), "point": {}, "paired": {}}
    ones = np.ones(len(yk))
    for nm, (p, pr) in sys_k.items():
        f1, true = class_f1(yk, p, ones)
        ded["point"][nm] = {"accuracy": float((p == yk).mean()), "macro_f1": float(macro(f1, true)),
                            "tail_f1": float(macro(f1, true, tier_mask["tail"]))}
    _, mac_k, tier_k = bootstrap(yk, sys_k, tier_mask, "ordinary", B_ORD, fixed=True)
    idx_k = {nm: i for i, nm in enumerate(sys_k)}
    for s_i, nm in enumerate(sys_k):
        ded["point"][nm]["macro_f1_ci95"] = ci(mac_k[:, s_i])
    for a, b in pairs:
        i, j = idx_k[a], idx_k[b]
        ded["paired"][f"{a} || {b}"] = {
            "delta": ded["point"][a]["macro_f1"] - ded["point"][b]["macro_f1"],
            "ci95": ci(mac_k[:, i] - mac_k[:, j]),
            "tail_delta": ded["point"][a]["tail_f1"] - ded["point"][b]["tail_f1"],
            "tail_ci95": ci(tier_k[:, i, 2] - tier_k[:, j, 2]),
            "delta_full_val": numbers["paired"][f"{a} || {b}"]["delta"]}
    numbers["deduplicated"] = ded

    print("Cluster bootstrap over repeated narratives (sensitivity)...")
    normt = [re.sub(r"\s+", " ", t.lower()).strip() for t in val_texts]
    _, cl = np.unique(normt, return_inverse=True)
    n_cl = cl.max() + 1
    rng_c = np.random.default_rng(SEED)
    names_c = list(systems)
    idx_c = {nm: i for i, nm in enumerate(names_c)}
    mac_c = np.empty((2000, len(names_c)))
    for b in range(2000):
        w = np.bincount(rng_c.integers(0, n_cl, n_cl), minlength=n_cl)[cl].astype(float)
        for si, nm in enumerate(names_c):
            f1, true = class_f1(y, systems[nm][0], w)
            mac_c[b, si] = macro(f1, true, fixed=True)
    numbers["cluster_bootstrap"] = {"distinct_narratives": int(n_cl), "resamples": 2000}

    # Retrieval few-shot: how much the 20 retrieved examples narrow the question (same neighbours as the prompt)
    nb_path = ART / "retrieval_neighbours_val.npz"   # the 20 fit-set neighbours of each evaluation complaint
    if not nb_path.exists() and (ART / "embeddings_mpnet_fit.npz").exists():
        E_fit = np.load(ART / "embeddings_mpnet_fit.npz")["emb"]; E_val = np.load(ART / "embeddings_mpnet_val.npz")["emb"]
        nb_idx, nb_sim = np.empty((n, 20), np.int32), np.empty((n, 20), np.float32)
        for st in range(0, n, 500):
            S = E_val[st:st + 500] @ E_fit.T
            top = np.argpartition(-S, 20, axis=1)[:, :20]
            nb_idx[st:st + 500], nb_sim[st:st + 500] = top, np.take_along_axis(S, top, 1)
        np.savez_compressed(nb_path, idx=nb_idx, sim=nb_sim)
    if "GLM-5.3, 20 retrieved examples" in systems and nb_path.exists():
        nb = np.load(nb_path); nb_idx, nb_sim = nb["idx"], nb["sim"]
        g = systems["GLM-5.3, 20 retrieved examples"][0]
        n_lab, in_set, g_in, top1 = np.empty(n), np.zeros(n, bool), np.zeros(n, bool), np.empty(n)
        for i in range(n):
            labs = set(y_fit[nb_idx[i]].tolist())
            n_lab[i] = len(labs); in_set[i] = y[i] in labs; g_in[i] = g[i] in labs; top1[i] = nb_sim[i].max()
        ok = g == y
        numbers["retrieval_shortlist"] = {
            "distinct_labels_mean": float(n_lab.mean()), "distinct_labels_median": float(np.median(n_lab)),
            "true_label_in_retrieved_set": float(in_set.mean()), "answer_in_retrieved_set": float(g_in.mean()),
            "accuracy_if_true_in_set": float(ok[in_set].mean()), "accuracy_if_true_not_in_set": float(ok[~in_set].mean()),
            "near_exact_neighbour_share": float((top1 >= 0.99).mean()),
            "accuracy_near_exact": float(ok[top1 >= 0.99].mean()), "accuracy_otherwise": float(ok[top1 < 0.99].mean())}
        if "GLM-5.3, labels of 20 retrieved complaints" in systems:   # same neighbours, labels only: how far the candidate list alone goes
            gs = systems["GLM-5.3, labels of 20 retrieved complaints"][0]; oks = gs == y
            g_in_s = np.array([gs[i] in set(y_fit[nb_idx[i]].tolist()) for i in range(n)])
            numbers["retrieval_shortlist"]["labels_only"] = {
                "answer_in_retrieved_set": float(g_in_s.mean()), "accuracy_if_true_in_set": float(oks[in_set].mean()),
                "accuracy_if_true_not_in_set": float(oks[~in_set].mean()),
                "accuracy_near_exact": float(oks[top1 >= 0.99].mean()), "accuracy_otherwise": float(oks[top1 < 0.99].mean())}
    for a, b in pairs:
        numbers["paired"][f"{a} || {b}"]["ci95_cluster"] = ci(mac_c[:, idx_c[a]] - mac_c[:, idx_c[b]])

    print("Label-mapping sensitivity (evaluation rows whose raw label was mapped to a narrower label)...")
    from datasets import load_dataset
    from utils import data_utils as du
    raw = load_dataset(du.DATASET_NAME)["train"].select(json.loads((ROOT / "data" / "val_indices.json").read_text()))
    raw_labels = [r for r in raw[du.LABEL_COLUMN] if du._apply_merge(r) in du._VALID_CLASSES]
    assert len(raw_labels) == n
    SUSPECT = {"Balance transfer", "Cash advance", "Managing, opening, or closing account"}
    keep_m = np.array([r not in SUSPECT for r in raw_labels])
    ym = y[keep_m]
    sys_m = {nm: (pp[keep_m], pr[keep_m]) for nm, (pp, pr) in systems.items()}
    _, mac_m, _ = bootstrap(ym, sys_m, tier_mask, "ordinary", 2000, fixed=True)
    idx_m = {nm: i for i, nm in enumerate(sys_m)}
    ones_m = np.ones(len(ym))
    msens = {"rows_removed": int((~keep_m).sum()), "point": {}, "paired": {}}
    for nm, (pp, _) in sys_m.items():
        f1, true = class_f1(ym, pp, ones_m)
        msens["point"][nm] = {"accuracy": float((pp == ym).mean()), "macro_f1": float(macro(f1, true, fixed=True))}
    for a, b in pairs:
        msens["paired"][f"{a} || {b}"] = {"delta": msens["point"][a]["macro_f1"] - msens["point"][b]["macro_f1"],
                                          "ci95": ci(mac_m[:, idx_m[a]] - mac_m[:, idx_m[b]])}
    numbers["mapping_sensitivity"] = msens
    numbers["row_alignment"] = {
        "val_text_sha256_first5": [hashlib.sha256(t.encode()).hexdigest()[:16] for t in val_texts[:5]],
        "all_prediction_arrays_length": n}

    # ---------------------------------------------------------------------------------------------
    # Figures quoted in the paper's text that are simple functions of the results above, or facts
    # about the data, so that every number in the text traces to this file (paper/number_trace.csv).
    # ---------------------------------------------------------------------------------------------
    P_, D_, DEC_ = numbers["point"], numbers["paired"], numbers["decomposition"]
    derived = {}
    raw_all = load_dataset(du.DATASET_NAME)
    raw_labels_all = [r for split in raw_all for r in raw_all[split][du.LABEL_COLUMN]]
    mapping = json.loads((ROOT / "data" / "label_merge_mapping.json").read_text())
    merged_labels = {du._apply_merge(r) for r in raw_labels_all}
    derived["data"] = {
        "raw_labels": len(set(raw_labels_all)), "mapping_entries": len([k for k in mapping if not k.startswith("_")]),
        "labels_after_mapping": len(merged_labels), "classes_kept": K,
        "n_train": int(len(train_ds)), "n_test_folded_in": int(len(test_ds)), "n_fit": int(len(fit_texts)),
        "max_words_any_narrative": int(max(len(t.split()) for t in fit_texts + val_texts)),
        "majority_class_share_val": float(np.bincount(y, minlength=K).max() / n),
        "tail_share_val": float((tiers == "tail").mean()),
        "selection_slice_size": int(round(0.1 * len(fit_texts))),
        "selection_train_size": int(len(fit_texts) - round(0.1 * len(fit_texts)))}
    try:   # share of complaints longer than the fine-tuned models' 128-token limit (ModernBERT tokenizer)
        from tokenizers import Tokenizer
        from huggingface_hub import hf_hub_download
        tok = Tokenizer.from_file(hf_hub_download("answerdotai/ModernBERT-base", "tokenizer.json",
                                                   revision="8949b909ec900327062f0ebf497f51aef5e6f0c8"))
        lens_fit = np.array([len(e.ids) for e in tok.encode_batch(fit_texts)])
        lens_val = np.array([len(e.ids) for e in tok.encode_batch(val_texts)])
        derived["data"]["share_over_128_tokens_fit"] = float((lens_fit > 128).mean())
        derived["data"]["share_over_128_tokens_val"] = float((lens_val > 128).mean())
        derived["data"]["share_over_128_tokens_all"] = float((np.concatenate([lens_fit, lens_val]) > 128).mean())
    except ImportError:
        pass
    jz = P_["Jev zero-shot"]["accuracy"]
    derived["jev_accuracy_above_majority_points"] = 100 * (jz - derived["data"]["majority_class_share_val"])
    dq = DEC_["Jev zero-shot || Qwen3-32B + LoRA"]
    derived["jev_qwen_gap_share_head_mid"] = (dq["head"]["part"] + dq["mid"]["part"]) / (
        dq["head"]["part"] + dq["mid"]["part"] + dq["tail"]["part"])
    tc = numbers["true_counts"]["Identity theft/Fraud/Embezzlement"]
    pc = numbers["predicted_counts"]
    derived["identity_theft_overprediction_ratio"] = {
        nm: pc[nm]["Identity theft/Fraud/Embezzlement"] / tc for nm in
        ("Jev zero-shot", "SemIf bracket", "GLM-5.3 (generative)")}
    buckets = numbers["jev_top_probability_buckets"]
    sb = numbers["semif"]["SemIf bracket"]["top_probability_buckets"]["[0.9,1.01)"]
    derived["score_0_9_or_more"] = {
        "Jev zero-shot": {"share": buckets["[0.9,1.01)"]["n"] / n, "error": 1 - buckets["[0.9,1.01)"]["accuracy"]},
        "SemIf bracket": {"share": sb["share"], "error": 1 - sb["accuracy"]}}
    cj = conf["Jev zero-shot"]; okj = systems["Jev zero-shot"][0] == y
    errs = [1 - okj[cj >= t].mean() for t in np.unique(cj)]
    derived["jev_confidence"] = {"lowest_error_any_threshold": float(min(errs)), "n_at_1_0": int((cj >= 1.0).sum()),
                                 "share_at_1_0": float((cj >= 1.0).mean()),
                                 "accuracy_at_1_0": float(okj[cj >= 1.0].mean())}
    dj = DEC_["TF-IDF + Jev + LR || TF-IDF + LR"]
    derived["tfidf_jev_gain_tail_share"] = dj["tail"]["part"] / D_["TF-IDF + Jev + LR || TF-IDF + LR"]["delta"]
    SLn = "GLM-5.3, labels of 20 retrieved complaints"
    if SLn in P_:
        full = D_["GLM-5.3, 20 retrieved examples || GLM-5.3 (generative)"]
        part = D_[f"{SLn} || GLM-5.3 (generative)"]
        derived["retrieval_gain_share_from_labels_only"] = {
            "macro_f1": part["delta"] / full["delta"], "accuracy": part["acc_delta"] / full["acc_delta"]}
    derived["glm_unmatched"] = {}
    for tag in ["glm-5.3", "glm-5.3_fewshot20", "glm-5.3_shortlist20"]:
        fr = GLM_DIR / f"{tag}_val_responses.jsonl"
        if fr.exists():
            rows = [json.loads(l) for l in fr.read_text().splitlines()]
            derived["glm_unmatched"][tag] = sum(r["label_idx"] is None for r in rows)
    for tag in ["glm-5.3", "glm-5.3_fewshot20", "glm-5.3_shortlist20"]:
        if tag in numbers.get("glm_tokens", {}):
            numbers["glm_tokens"][tag]["retried_share"] = numbers["glm_tokens"][tag]["retried"] / n
    d64 = GLM_DIR / "discarded_maxtok64_traindev_responses.jsonl"
    if d64.exists():
        rows = [json.loads(l) for l in d64.read_text().splitlines()]
        derived["glm_budget_64_training_check"] = {"n": len(rows), "empty": sum(not r["answer"].strip() for r in rows)}
    # Filtered-subset changes (full split minus filtered subset), summarised as the paper states them
    dp = numbers["deduplicated"]["point"]
    drop = {nm: P_[nm]["macro_f1"] - dp[nm]["macro_f1"] for nm in P_ if nm in dp}
    text_trained = ["TF-IDF + LR", "TF-IDF + Jev + LR", "TF-IDF + embeddings + LR", "TF-IDF + Jev top choice",
                    "TF-IDF + label-name similarity", "TF-IDF + stacked embedding probabilities",
                    "ModernBERT-base (vanilla)", "ModernBERT-base (distilled)", "ModernBERT-large", "Qwen3-32B + LoRA"]
    unaffected = ["Jev zero-shot", "Jev + form instruction", "Jev + form instruction + definitions", "SemIf bracket",
                  "SemIf bracket + definitions", "SemIf one-vs-rest", "GLM-5.3 (generative)", "LR on Jev probs",
                  "LR on sentence embeddings"]
    derived["filtered_drop"] = {
        "text_trained_min": min(drop[k] for k in text_trained if k in drop),
        "text_trained_max": max(drop[k] for k in text_trained if k in drop),
        "zero_shot_and_single_block_max_abs": max(abs(drop[k]) for k in unaffected if k in drop),
        "by_system": drop}
    derived["exact_duplicate_share_val"] = numbers["near_duplicates"]["exact_duplicates"] / n
    derived["near_duplicate_share_val"] = numbers["near_duplicates"]["nn_cosine_ge_0.9"] / n
    for crit in (ROOT / "criteria" / "v1.json", ROOT / "verification" / "jev_criteria" / "v1.json"):
        if crit.exists():
            derived["definitions_count"] = len(json.loads(crit.read_text())["criteria"])
            break
    pass1 = ART / "embedding_control_val_probs_pass1.npz"   # first-pass grid of the embedding control
    if pass1.exists():
        e1 = np.load(pass1)
        f1_, true_ = class_f1(y, e1["tfidf_emb"].argmax(-1), np.ones(n))
        derived["tfidf_embeddings_first_pass_macro_f1"] = float(macro(f1_, true_, fixed=True))
    for tag in list(numbers.get("glm_tokens", {})):
        g = numbers["glm_tokens"][tag]
        fr = [json.loads(l) for l in (GLM_DIR / f"{tag}_val_responses.jsonl").read_text().splitlines()]
        g["retried_final_output_under_2000"] = int(sum(r["output_tokens"] < 2000 for r in fr if r.get("max_tokens", 0) > 16384))
    if nb_path.exists():
        derived["retrieval_neighbours_per_complaint"] = int(np.load(nb_path)["idx"].shape[1])
    derived["semif_groups"] = {"n_groups": 8, "sizes": sorted({len(g) for g in np.array_split(np.arange(K), 8)})}
    ft = ["ModernBERT-base (vanilla)", "ModernBERT-base (distilled)", "ModernBERT-large", "Qwen3-32B + LoRA"]
    derived["confident_decile_fine_tuned_tail_below_split"] = sum(
        numbers["confident_decile"][m]["tail_share"] < derived["data"]["tail_share_val"] for m in ft)
    derived["merged_pairs"] = len(numbers["merged"]["pairs_merged"]) if "merged" in numbers else None
    derived["merge_candidates"] = len(numbers.get("year_test", []))
    numbers["paper_derived"] = derived

    make_figures(numbers, rc, systems, y)
    (OUT / "numbers.json").write_text(json.dumps(numbers, indent=2, default=float))
    print(f"Wrote {OUT / 'numbers.json'}")


# --------------------------------------------------------------------------------------------
# Figures
# --------------------------------------------------------------------------------------------
FAMILY = {"Jev zero-shot": "zero", "Jev + form instruction": "zero", "Jev + form instruction + definitions": "zero",
          "SemIf bracket": "open", "SemIf bracket + definitions": "open", "SemIf one-vs-rest": "open",
          "GLM-5.3 (generative)": "llm",
          "GLM-5.3, 20 retrieved examples": "llm",
          "20-nearest-neighbour vote": "linear",
          "GLM-5.3, labels of 20 retrieved complaints": "llm",
          "1-nearest-neighbour": "linear",
          "TF-IDF (20k)": "linear",
          "Jev probabilities (20k)": "linear",
          "SemIf probabilities (20k)": "linear",
          "TF-IDF + Jev (20k)": "linear",
          "TF-IDF + SemIf (20k)": "linear",

          "LR on sentence embeddings": "linear", "TF-IDF + embeddings + LR": "linear",
          "TF-IDF + Jev top choice": "linear",
          "TF-IDF + label-name similarity": "linear",
          "TF-IDF + stacked embedding probabilities": "linear",

          "LR on Jev probs": "linear", "TF-IDF + LR": "linear", "TF-IDF + Jev + LR": "linear",
          "ModernBERT-base (vanilla)": "ft", "ModernBERT-base (distilled)": "ft", "ModernBERT-large": "ft",
          "Qwen3-32B + LoRA": "ft"}
PURPLE = "#7a5cd6"   # fourth categorical slot
GRAY = "#6b6a65"
COLOR = {"zero": ORANGE, "open": PURPLE, "llm": GRAY, "linear": AQUA, "ft": BLUE}


def make_figures(numbers, rc, systems, y):
    # Figure 1: over-prediction profiles. Per class, log((predicted + 1) / (true + 1)); each panel plots one
    # system against Jev's bare-label profile. Zero-shot readers of label names line up with Jev; supervised
    # models do not.
    true_c = np.bincount(y, minlength=K)
    prof = lambda nm: np.log((cnt(systems[nm][0]) + 1) / (true_c + 1))
    panels = [(nm, col) for nm, col in [("SemIf bracket", PURPLE), ("GLM-5.3 (generative)", GRAY),
                                        ("Qwen3-32B + LoRA", BLUE)] if nm in systems]
    titles = {"SemIf bracket": "SemIf (Qwen3.5-4B), zero-shot", "GLM-5.3 (generative)": "GLM-5.3, zero-shot",
              "Qwen3-32B + LoRA": "Qwen3-32B + LoRA, fine-tuned"}
    fig, axes = plt.subplots(1, len(panels), figsize=(6.6, 2.35), sharex=True, sharey=True)
    xj = prof("Jev zero-shot")
    size = 6 + 40 * np.sqrt(true_c / true_c.max())
    idt = LABELS.index("Identity theft/Fraud/Embezzlement")
    for ax, (nm, col) in zip(np.atleast_1d(axes), panels):
        yy = prof(nm)
        ax.axhline(0, color=GRID, lw=0.8, zorder=1); ax.axvline(0, color=GRID, lw=0.8, zorder=1)
        ax.scatter(xj, yy, s=size, color=col, alpha=0.55, edgecolor="white", linewidth=0.4, zorder=2)
        ax.scatter([xj[idt]], [yy[idt]], s=size[idt] + 10, facecolor="none", edgecolor=INK, linewidth=0.9, zorder=3)
        r = np.corrcoef(xj, yy)[0, 1]
        ax.set_title(f"{titles[nm]}\n$r = {r:.2f}$", fontsize=7.5, color=INK)
        ax.set_xlabel("Jev (bare labels)", fontsize=7.5)
        ax.grid(False)
    np.atleast_1d(axes)[0].set_ylabel("log over-prediction ratio", fontsize=7.5)
    fig.savefig(FIG / "overprediction.pdf")
    plt.close(fig)

    # Figure: learning curve (verification/features_controls.py), zero-shot systems as horizontal references
    if numbers.get("learning_curve_nested"):
        full = {"tfidf": "TF-IDF + LR", "tfidf+jev": "TF-IDF + Jev + LR", "tfidf+sim": "TF-IDF + label-name similarity"}
        lc = []
        for r in numbers["learning_curve_nested"]:
            lc.append({"model": r["model"], "n": r["n"], "accuracy": r["accuracy_mean"], "macro_f1": r["macro_f1_mean"],
                       "lo": {"accuracy": r["accuracy_min"], "macro_f1": r["macro_f1_min"]},
                       "hi": {"accuracy": r["accuracy_max"], "macro_f1": r["macro_f1_max"]}})
        for m, nm in full.items():
            if nm in numbers["point"]:
                v = numbers["point"][nm]
                lc.append({"model": m, "n": 79278, "accuracy": v["accuracy"], "macro_f1": v["macro_f1"]})
        fig, axes = plt.subplots(1, 2, figsize=(6.6, 2.6))
        styles = {"tfidf": (AQUA, "-", "o", "TF-IDF"), "tfidf+jev": (ORANGE, (0, (4, 2)), "s", "TF-IDF + Jev probabilities"),
                  "tfidf+sim": (BLUE, (0, (1, 1.5)), "^", "TF-IDF + label-name similarity")}
        refs = [("GLM-5.3, 20 retrieved examples", GRAY, "GLM-5.3, 20 examples"),
                ("GLM-5.3 (generative)", GRAY, "GLM-5.3"), ("Jev + form instruction + definitions", ORANGE, "Jev + definitions"),
                ("Jev zero-shot", ORANGE, "Jev, bare labels"), ("SemIf bracket", PURPLE, "SemIf, bare labels")]
        for ax, metric, lab in [(axes[0], "accuracy", "Accuracy"), (axes[1], "macro_f1", "Macro F1")]:
            for nm, col, rl in refs:
                if nm in numbers["point"]:
                    v = numbers["point"][nm][metric]
                    ax.axhline(v, color=col, lw=0.9, ls=(0, (2, 2)) if "definitions" in nm or "SemIf" in nm else "-", alpha=0.8)
                    if metric == "macro_f1":
                        ax.text(80000, v, " " + rl, fontsize=6, color=col, va="center")
            for kind, (col, ls, mk, name) in styles.items():
                rs = sorted((r for r in lc if r["model"] == kind), key=lambda r: r["n"])
                ax.plot([r["n"] for r in rs], [r[metric] for r in rs], color=col, ls=ls, marker=mk, markersize=4, lw=1.6, label=name)
                for r in rs:
                    if "lo" in r:
                        ax.plot([r["n"], r["n"]], [r["lo"][metric], r["hi"][metric]], color=col, lw=0.8)
            ax.set_xscale("log"); ax.set_xlabel("Labelled training complaints"); ax.set_ylabel(lab)
            ax.set_xticks([500, 2000, 8000, 20000, 79278]); ax.set_xticklabels(["500", "2k", "8k", "20k", "79k"])
        axes[0].legend(loc="lower right", frameon=False, fontsize=6.3)
        fig.savefig(FIG / "learning_curve.pdf")
        plt.close(fig)

    # Figure 2: reliability diagram (top-label) for systems that return a distribution
    fig, ax = plt.subplots(figsize=(3.4, 3.2))
    ax.plot([0, 1], [0, 1], color=MUTED, lw=1, zorder=1)
    for name, col, marker in [("Jev zero-shot", ORANGE, "o"), ("SemIf bracket", PURPLE, "D"),
                              ("LR on Jev probs", AQUA, "s"), ("Qwen3-32B + LoRA", BLUE, "^")]:
        if name not in systems:
            continue
        pr = systems[name][1]
        pred = systems[name][0]
        cf, cr = pr[np.arange(len(pred)), pred], pred == y
        edges = np.linspace(0, 1, 16)
        xs, ys = [], []
        for lo, hi in zip(edges[:-1], edges[1:]):
            m = (cf > lo) & (cf <= hi)
            if m.sum() >= 30:
                xs.append(cf[m].mean()); ys.append(cr[m].mean())
        ax.plot(xs, ys, color=col, lw=2, marker=marker, markersize=4.5, markeredgecolor="white",
                markeredgewidth=0.8, zorder=3, label={"Jev zero-shot": "Jev, bare labels", "SemIf bracket": "SemIf, bare labels",
                                                      "LR on Jev probs": "LR on Jev probabilities"}.get(name, name))
    ax.set_xlim(0, 1); ax.set_ylim(0, 1); ax.set_aspect("equal")
    ax.set_xlabel("Mean score of the reported prediction"); ax.set_ylabel("Accuracy")
    ax.legend(loc="upper left", frameon=False, fontsize=7)
    fig.savefig(FIG / "reliability.pdf")
    plt.close(fig)

    # Figure 2 (right): risk-coverage
    fig, ax = plt.subplots(figsize=(5.0, 3.1))
    styles = {"Jev zero-shot | confidence": (ORANGE, "-", "Jev, ranked by confidence score"),
              "Jev zero-shot | top probability": (ORANGE, (0, (4, 2)), "Jev, ranked by top probability"),
              "Jev + form instruction + definitions | confidence": (ORANGE, (0, (1, 1.5)),
                                                                   "Jev + definitions, confidence score"),
              "SemIf bracket | top probability": (PURPLE, "-", "SemIf, composed top probability"),
              "TF-IDF + Jev + LR | top probability": (AQUA, "-", "TF-IDF + Jev probabilities"),
              "Qwen3-32B + LoRA | top probability": (BLUE, "-", "Qwen3-32B + LoRA")}
    for key, r in rc.items():
        col, ls, lab = styles[key]
        c_, r_ = r["curve"]
        m = c_ >= 0.01
        ax.plot(c_[m], r_[m], color=col, ls=ls, lw=1.8, label=lab)
    ax.set_xlim(0, 1); ax.set_ylim(0, 1.0)
    ax.set_xlabel("Coverage (share answered, most confident first)")
    ax.set_ylabel("Error rate among answered")
    ax.legend(loc="upper left", frameon=False, fontsize=6.8)
    fig.savefig(FIG / "risk_coverage.pdf")
    plt.close(fig)


if __name__ == "__main__":
    main()