File size: 60,669 Bytes
a56d4d4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Robustness analyses for VIPBench (camera-ready version).

The script reruns, from the released files alone, the analyses that were added during the
NeurIPS 2026 review. Every quantity is computed for each of the eleven models. The summary
statistics that depend on the model set (rank correlations and checks of the group order)
are then reported twice, once for the ten models of the submitted paper and once for all
eleven models.

Run `benchmark_analysis.ipynb` first. It writes `cache/ssl_bestlayer_cosims.pkl`, which holds
the nested best-layer cosine similarities of the SSL models and Whisper.

Sections:
  A  learned similarity probes                      (Reviewer 2XGW, W1 and Q2)
  B  ranking on genuine speech only                 (Reviewer 2XGW, Q1)
  C  nested Task 2 thresholds                       (Reviewer 2XGW, W4)
  D  ranking stability under speaker resampling     (Reviewer 2XGW, W2)
  E  listener consistency                           (Reviewer 2XGW, W3 and Q3)
  F  Task 3 permutation tests and symmetrized matrix (Reviewer CSNB, W3 and Q3)
  G  unfamiliar and familiar trials                 (Reviewers mUiR and tEip, area chair)
  H  VoxCeleb identity overlap                      (Reviewer mUiR, area chair)
  I  reliability and alignment by stimulus type     (Reviewers mUiR and tEip, area chair)
  J  vote downsampling                              (Reviewer tEip, W3)
  K  equal weight for each stimulus type            (Reviewer tEip, Q3)
  L  listener questionnaire and participation       (Reviewer tEip, W1)
  M  CosyVoice 2 extension subset                   (Reviewers 2XGW and CSNB)

Usage:
    python3 robustness_analyses.py                 # all sections
    python3 robustness_analyses.py --sections D,G  # selected sections
"""
import argparse
import os
import pickle
import re
import unicodedata
import warnings
from pathlib import Path

import numpy as np
import pandas as pd
from scipy.stats import pearsonr, rankdata, spearmanr
from sklearn.decomposition import PCA
from sklearn.linear_model import RidgeCV
from sklearn.metrics import accuracy_score, roc_auc_score, roc_curve

warnings.filterwarnings("ignore")

CODE = Path(__file__).resolve().parent
ROOT = Path(os.environ.get("VIPBENCH_ROOT", CODE.parent))
DATA = ROOT / "data"
EXT = DATA / "experiment2"
MAIN_CACHE = CODE / "cache"
CACHE = MAIN_CACHE / "robustness"
CACHE.mkdir(parents=True, exist_ok=True)
SEED = 42

SUPERVISED_10 = ["resemblyzer", "ecapa_tdnn", "titanet", "rawnet3", "xvector"]
NEW_MODELS = ["wespeaker_resnet34_lm"]
SSL = ["wavlm", "wav2vec2", "xlsr", "hubert"]
WHISPER = "whisper"
MODEL_SETS = {
    "ten": SUPERVISED_10 + SSL + [WHISPER],
    "eleven": SUPERVISED_10 + NEW_MODELS + SSL + [WHISPER],
}
ALL_MODELS = MODEL_SETS["eleven"]
SUPERVISED = SUPERVISED_10 + NEW_MODELS
LAYERED = SSL + [WHISPER]
DISPLAY = {"rawnet3": "RawNet3", "ecapa_tdnn": "ECAPA-TDNN", "titanet": "TitaNet",
           "resemblyzer": "resemblyzer", "xvector": "x-vector", "wav2vec2": "wav2vec 2.0",
           "hubert": "HuBERT", "wavlm": "WavLM", "whisper": "Whisper", "xlsr": "XLS-R",
           "wespeaker_resnet34_lm": "WeSpeaker"}


def cached(key, fn, desc=""):
    f = CACHE / f"{key}.pkl"
    if f.exists():
        with open(f, "rb") as fh:
            return pickle.load(fh)
    print(f"  [computing {key}{': ' + desc if desc else ''}]", flush=True)
    res = fn()
    with open(f, "wb") as fh:
        pickle.dump(res, fh)
    return res


def group_of(m):
    return "supervised" if m in SUPERVISED else ("ssl" if m in SSL else "whisper")


def group_order_holds(vals, models):
    """True when every supervised model is above every SSL model, and every SSL model is
    above Whisper."""
    sup = [vals[m] for m in models if m in SUPERVISED]
    ssl = [vals[m] for m in models if m in SSL]
    return bool(min(sup) > max(ssl) and min(ssl) > vals[WHISPER])


def rank_corr(a, b, models):
    return spearmanr([a[m] for m in models], [b[m] for m in models])[0]


# --------------------------------------------------------------------------------------
# Setup: pair table, cosine similarities, folds
# --------------------------------------------------------------------------------------
print("Loading the released tables and embeddings...", flush=True)
responses = pd.read_csv(DATA / "participant_responses.csv", low_memory=False)
stimuli = pd.read_csv(DATA / "stimuli.csv")
speakers = pd.read_csv(DATA / "speakers.csv")

agg = responses.groupby("stimuli_id").agg(n_responses=("answer", "count"),
                                          n_same=("answer", "sum")).reset_index()
agg["p_same"] = agg["n_same"] / agg["n_responses"]

df = stimuli[["id", "stimuli_type", "reference", "comparison", "voice_clone",
              "correct_answer", "scale"]].copy()
df["p_same_full"] = df["id"].map(agg.set_index("stimuli_id")["p_same"])
df["n_resp_full"] = df["id"].map(agg.set_index("stimuli_id")["n_responses"])
df["majority_full"] = (df["p_same_full"] > 0.5).astype(int)
assert len(df) == 9800, len(df)

embeddings = {}
for name in ALL_MODELS:
    z = np.load(DATA / "embeddings" / f"{name}.npz", allow_pickle=True)
    embeddings[name] = {k: z[k] for k in z.files}

for name, emb in embeddings.items():
    ref_keys = [f"{r}R" for r in df["reference"]]
    sims = np.full(len(df), np.nan)
    for i, (rk, sk) in enumerate(zip(ref_keys, df["id"])):
        if rk in emb and sk in emb:
            a, b = emb[rk], emb[sk]
            sims[i] = (a @ b) / ((np.linalg.norm(a) * np.linalg.norm(b)) + 1e-10)
    df[f"{name}_cosim"] = sims

# Gender-balanced speaker folds, built exactly as in the main notebook
_all_spk = sorted(df["reference"].unique())
_male = [s for s in _all_spk if s.startswith("M")]
_female = [s for s in _all_spk if s.startswith("F")]
_rng = np.random.default_rng(SEED)
_rng.shuffle(_male)
_rng.shuffle(_female)
CV_FOLDS = [[] for _ in range(10)]
for i, s in enumerate(_male):
    CV_FOLDS[i % 10].append(s)
for i, s in enumerate(_female):
    CV_FOLDS[i % 10].append(s)

_bl = MAIN_CACHE / "ssl_bestlayer_cosims.pkl"
if not _bl.exists():
    raise SystemExit(f"{_bl} is missing. Run benchmark_analysis.ipynb first.")
with open(_bl, "rb") as fh:
    ssl_bestlayer = pickle.load(fh)
best_layer_per_fold = {}
for m, d_ in ssl_bestlayer.items():
    df[f"{m}_cosim_lastlayer"] = df[f"{m}_cosim"]
    df[f"{m}_cosim"] = d_["best_cosim"]
    best_layer_per_fold[m] = d_["selected_layers"]
MODAL_LAYER = {m: int(pd.Series(v).mode()[0]) for m, v in best_layer_per_fold.items()}


def comp_speaker(row):
    if row["stimuli_type"] in (1, 2, 3):
        return row["reference"]
    if row["stimuli_type"] in (4, 5):
        return str(row["comparison"])
    return str(row["id"]).split("_")[2][:3]


df["comp_speaker"] = df.apply(comp_speaker, axis=1)

task1_r = {}
for m in ALL_MODELS:
    v = df.dropna(subset=[f"{m}_cosim", "p_same_full"])
    task1_r[m] = pearsonr(v[f"{m}_cosim"], v["p_same_full"])[0]
task1_n = {m: int(df[[f"{m}_cosim", "p_same_full"]].dropna().shape[0]) for m in ALL_MODELS}
assert abs(task1_r["resemblyzer"] - 0.656) < 0.005 and abs(task1_r["ecapa_tdnn"] - 0.646) < 0.005
print("Task 1 r:", {DISPLAY[m]: round(task1_r[m], 3) for m in ALL_MODELS})
print("Pairs with a score:", {DISPLAY[m]: task1_n[m] for m in ALL_MODELS if task1_n[m] != 9800} or "9,800 for every model")
print("Selected layers (mode over folds):", MODAL_LAYER, flush=True)

R = {"task1_r": task1_r, "task1_n": task1_n, "modal_layer": MODAL_LAYER}


def per_set(fn):
    """Evaluate a summary function for the ten-model and the eleven-model set."""
    return {tag: fn(models) for tag, models in MODEL_SETS.items()}


# --------------------------------------------------------------------------------------
# A. Learned similarity probes
# --------------------------------------------------------------------------------------
ALPHAS = np.logspace(-2, 3, 12)


def _pair_features(m):
    """Reference and comparison embeddings aligned to the rows of df. SSL models and Whisper
    use the layer selected in each fold, and supervised models use their native embedding."""
    n = len(df)
    ref_keys = [f"{r}R" for r in df["reference"]]
    if m in SUPERVISED:
        emb = embeddings[m]
        dim = next(iter(emb.values())).shape[0]
        ref = np.full((n, dim), np.nan)
        comp = np.full((n, dim), np.nan)
        for i, (rk, sk) in enumerate(zip(ref_keys, df["id"])):
            if rk in emb and sk in emb:
                ref[i] = emb[rk]
                comp[i] = emb[sk]
        return {None: (ref, comp)}
    z = np.load(DATA / "embeddings" / "layers" / f"{m}.npz", allow_pickle=True)
    layers = sorted(set(best_layer_per_fold[m]))
    dim = z[z.files[0]].shape[1]
    out = {L: (np.full((n, dim), np.nan), np.full((n, dim), np.nan)) for L in layers}
    cache_clip = {}
    for i, (rk, sk) in enumerate(zip(ref_keys, df["id"])):
        if rk not in cache_clip:
            cache_clip[rk] = z[rk]
        e_r, e_s = cache_clip[rk], z[sk]
        for L in layers:
            out[L][0][i] = e_r[L]
            out[L][1][i] = e_s[L]
    return out


def _probe_model(m):
    y = df["p_same_full"].values
    spk = df["reference"].values
    feats = _pair_features(m)
    pred_quad = np.full(len(df), np.nan)
    pred_pair = np.full(len(df), np.nan)
    for k, fold in enumerate(CV_FOLDS):
        L = None if m in SUPERVISED else best_layer_per_fold[m][k]
        ref, comp = feats[L]
        valid = ~np.isnan(y) & ~np.isnan(ref).any(1) & ~np.isnan(comp).any(1)
        te = np.isin(spk, fold) & valid
        tr = ~np.isin(spk, fold) & valid
        rn = ref / (np.linalg.norm(ref, axis=1, keepdims=True) + 1e-10)
        cn = comp / (np.linalg.norm(comp, axis=1, keepdims=True) + 1e-10)
        # Probe 1: full quadratic form on the first 50 principal components of the differences
        diffs = rn - cn
        pca = PCA(n_components=50, random_state=SEED).fit(diffs[tr])
        dtr, dte = pca.transform(diffs[tr]), pca.transform(diffs[te])
        iu = np.triu_indices(50)
        qtr = np.einsum("ni,nj->nij", dtr, dtr)[:, iu[0], iu[1]]
        qte = np.einsum("ni,nj->nij", dte, dte)[:, iu[0], iu[1]]
        pred_quad[te] = RidgeCV(alphas=ALPHAS).fit(qtr, y[tr]).predict(qte)
        # Probe 2: ridge regression on [|e1 - e2|, e1 * e2]
        ptr = np.hstack([np.abs(rn[tr] - cn[tr]), rn[tr] * cn[tr]])
        pte = np.hstack([np.abs(rn[te] - cn[te]), rn[te] * cn[te]])
        pred_pair[te] = RidgeCV(alphas=ALPHAS).fit(ptr, y[tr]).predict(pte)
    vq = ~np.isnan(pred_quad) & ~np.isnan(y)
    vp = ~np.isnan(pred_pair) & ~np.isnan(y)
    return {"r_quad": pearsonr(pred_quad[vq], y[vq])[0],
            "r_pair": pearsonr(pred_pair[vp], y[vp])[0]}


def section_A():
    print("\n=== A. Learned similarity probes ===", flush=True)
    res = {m: cached(f"probe_{m}", lambda m=m: _probe_model(m), "nested probes") for m in ALL_MODELS}
    tab = pd.DataFrame([{"model": DISPLAY[m], "cosine r": task1_r[m],
                         "quadratic r": res[m]["r_quad"], "pair-feature r": res[m]["r_pair"]}
                        for m in ALL_MODELS])
    print(tab.round(3).to_string(index=False))

    def summ(models):
        out = {}
        for key, lab in (("r_quad", "quadratic"), ("r_pair", "pair-feature")):
            vals = {m: res[m][key] for m in models}
            sup = [vals[m] for m in models if m in SUPERVISED]
            ssl = [vals[m] for m in models if m in SSL]
            out[lab] = {"rho_vs_cosine": rank_corr(task1_r, vals, models),
                        "group_order": group_order_holds(vals, models),
                        "min_sup_minus_max_ssl": min(sup) - max(ssl),
                        "mean_sup_minus_mean_ssl": float(np.mean(sup) - np.mean(ssl))}
        sup = [task1_r[m] for m in models if m in SUPERVISED]
        ssl = [task1_r[m] for m in models if m in SSL]
        out["cosine"] = {"min_sup_minus_max_ssl": min(sup) - max(ssl),
                         "mean_sup_minus_mean_ssl": float(np.mean(sup) - np.mean(ssl))}
        return out
    s = per_set(summ)
    for tag in MODEL_SETS:
        print(f"  [{tag}] " + "; ".join(
            f"{lab}: rho vs cosine {s[tag][lab]['rho_vs_cosine']:.3f}, group order {s[tag][lab]['group_order']}, "
            f"gap min/mean {s[tag][lab]['min_sup_minus_max_ssl']:.3f}/{s[tag][lab]['mean_sup_minus_mean_ssl']:.3f}"
            for lab in ("quadratic", "pair-feature"))
            + f"; cosine gap min/mean {s[tag]['cosine']['min_sup_minus_max_ssl']:.3f}/"
              f"{s[tag]['cosine']['mean_sup_minus_mean_ssl']:.3f}")
    R["probes"] = {"per_model": res, "table": tab, "summary": s}


# --------------------------------------------------------------------------------------
# B. Ranking on genuine speech only (Types 1, 2, 4)
# --------------------------------------------------------------------------------------
def section_B():
    print("\n=== B. Ranking on genuine speech only (Types 1, 2, 4) ===")
    real = df[df["stimuli_type"].isin([1, 2, 4])]
    real_r = {m: pearsonr(*real.dropna(subset=[f"{m}_cosim"])[[f"{m}_cosim", "p_same_full"]].values.T)[0]
              for m in ALL_MODELS}
    t25 = df[df["stimuli_type"].isin([2, 3, 4, 5])]
    t25_r = {m: pearsonr(*t25.dropna(subset=[f"{m}_cosim"])[[f"{m}_cosim", "p_same_full"]].values.T)[0]
             for m in ALL_MODELS}
    tab = pd.DataFrame([{"model": DISPLAY[m], "full r": task1_r[m], "genuine-only r": real_r[m],
                         "Types 2-5 r": t25_r[m]} for m in ALL_MODELS])
    print(tab.round(3).to_string(index=False))
    s = per_set(lambda models: {"rho": rank_corr(task1_r, real_r, models),
                                "group_order": group_order_holds(real_r, models)})
    for tag in MODEL_SETS:
        print(f"  [{tag}] rank correlation with the full ranking {s[tag]['rho']:.3f}; "
              f"group order {s[tag]['group_order']}")
    R["real_only"] = {"r": real_r, "types25_r": t25_r, "table": tab, "summary": s}


# --------------------------------------------------------------------------------------
# C. Nested Task 2 thresholds and the human baseline
# --------------------------------------------------------------------------------------
def human_accuracy():
    pv = responses.groupby("stimuli_id")["answer"].agg(["count", "sum"]).rename(
        columns={"count": "n_total", "sum": "n_same"})
    rj = responses.join(pv, on="stimuli_id")
    rj["n_minus"] = rj["n_total"] - 1
    rj["n_same_minus"] = rj["n_same"] - rj["answer"]
    rj = rj[rj["n_minus"] >= 1]
    rj["loo_majority"] = np.where(rj["n_same_minus"] > rj["n_minus"] / 2, 1,
                                  np.where(rj["n_same_minus"] < rj["n_minus"] / 2, 0, np.nan))
    rj = rj.dropna(subset=["loo_majority"])
    rj["hit"] = (rj["answer"] == rj["loo_majority"]).astype(int)
    per_part = rj.groupby("user_id").agg(acc=("hit", "mean"), n=("hit", "count"))
    trial_counts = responses.groupby("user_id").size()
    eligible = trial_counts[trial_counts >= 10].index
    return per_part.loc[per_part.index.intersection(eligible), "acc"], trial_counts


def section_C():
    print("\n=== C. Nested Task 2 thresholds ===")
    df_binary = df[(df["p_same_full"] != 0.5) & df["p_same_full"].notna()].copy()
    human_acc, _ = human_accuracy()
    print(f"  listeners with at least 10 trials: {len(human_acc)}, mean {human_acc.mean():.3f}, "
          f"median {human_acc.median():.3f}, SD {human_acc.std():.3f}, "
          f"range {human_acc.min():.2f} to {human_acc.max():.2f}")
    rows = []
    for m in ALL_MODELS:
        v = df_binary.dropna(subset=[f"{m}_cosim"])
        yv = v["majority_full"].values
        sv = v[f"{m}_cosim"].values
        spkv = v["reference"].values
        fpr, tpr, thr = roc_curve(yv, sv)
        acc_full = accuracy_score(yv, sv >= thr[np.argmax(tpr - fpr)])
        pred = np.full(len(v), np.nan)
        for fold in CV_FOLDS:
            te = np.isin(spkv, fold)
            tr = ~te
            fpr, tpr, thr = roc_curve(yv[tr], sv[tr])
            pred[te] = (sv[te] >= thr[np.argmax(tpr - fpr)]).astype(float)
        ok = ~np.isnan(pred)
        acc_nest = accuracy_score(yv[ok], pred[ok])
        rows.append({"model": DISPLAY[m], "key": m, "acc full": acc_full, "acc nested": acc_nest,
                     "delta acc": acc_nest - acc_full,
                     "pct full": 100 * (human_acc < acc_full).mean(),
                     "pct nested": 100 * (human_acc < acc_nest).mean()})
    tab = pd.DataFrame(rows)
    tab["delta pct"] = tab["pct nested"] - tab["pct full"]
    print(tab.drop(columns="key").round(3).to_string(index=False))

    def summ(models):
        t = tab[tab["key"].isin(models)].set_index("key")
        # A reversal is a pair of models whose order flips. A tie in one of the two orders is
        # not a reversal.
        reversals = [(DISPLAY[a], DISPLAY[b]) for i, a in enumerate(models) for b in models[i + 1:]
                     if (t.loc[a, "acc full"] - t.loc[b, "acc full"]) * (t.loc[a, "acc nested"] - t.loc[b, "acc nested"]) < 0]
        ties = [(DISPLAY[a], DISPLAY[b]) for i, a in enumerate(models) for b in models[i + 1:]
                if t.loc[a, "acc full"] == t.loc[b, "acc full"] or t.loc[a, "acc nested"] == t.loc[b, "acc nested"]]
        return {"max_abs_delta_acc": float(t["delta acc"].abs().max()),
                "max_abs_delta_pct": float(t["delta pct"].abs().max()),
                "reversals": reversals, "ties": ties}
    s = per_set(summ)
    for tag in MODEL_SETS:
        print(f"  [{tag}] largest accuracy change {s[tag]['max_abs_delta_acc']:.3f}; largest percentile "
              f"change {s[tag]['max_abs_delta_pct']:.1f} points; pairs whose order reverses {s[tag]['reversals']}; "
              f"tied pairs {s[tag]['ties']}")
    R["nested_thresholds"] = {"table": tab, "summary": s,
                              "human": {"n": int(len(human_acc)), "mean": float(human_acc.mean()),
                                        "median": float(human_acc.median()), "sd": float(human_acc.std()),
                                        "min": float(human_acc.min()), "max": float(human_acc.max())}}


# --------------------------------------------------------------------------------------
# D. Ranking stability under speaker resampling
# --------------------------------------------------------------------------------------
def _speaker_boot():
    rngb = np.random.default_rng(SEED + 1)
    spk_idx = {s: df.index[df["reference"] == s].values for s in _all_spk}
    y = df["p_same_full"].values
    cos_mat = np.column_stack([df[f"{m}_cosim"].values for m in ALL_MODELS])
    out = np.zeros((1000, len(ALL_MODELS)))
    for b in range(1000):
        spks = rngb.choice(_all_spk, size=len(_all_spk), replace=True)
        idx = np.concatenate([spk_idx[s] for s in spks])
        yv = y[idx]
        cm = cos_mat[idx]
        ok = ~np.isnan(yv)
        for j in range(len(ALL_MODELS)):
            v = ok & ~np.isnan(cm[:, j])
            out[b, j] = pearsonr(cm[v, j], yv[v])[0]
    return {"models": list(ALL_MODELS), "r": out}


def section_D():
    print("\n=== D. Ranking stability under speaker resampling (1,000 resamples) ===", flush=True)
    boot = cached("speaker_bootstrap_r", _speaker_boot, "resampling the 100 reference speakers")
    bm = pd.DataFrame(boot["r"], columns=boot["models"])

    def summ(models):
        sub = bm[models]
        ranks = sub.rank(axis=1, ascending=False)
        top1 = sub.idxmax(axis=1).value_counts(normalize=True).to_dict()
        sup = [m for m in models if m in SUPERVISED]
        ssl = [m for m in models if m in SSL]
        order_ok = ((sub[sup].min(axis=1) > sub[ssl].max(axis=1))
                    & (sub[ssl].min(axis=1) > sub[WHISPER])).mean()
        rows = [{"model": DISPLAY[m], "mean rank": ranks[m].mean(),
                 "rank 2.5%": np.percentile(ranks[m], 2.5), "rank 97.5%": np.percentile(ranks[m], 97.5),
                 "r 2.5%": np.percentile(sub[m], 2.5), "r 97.5%": np.percentile(sub[m], 97.5)}
                for m in models]
        pair = {}
        for a, b in (("resemblyzer", "ecapa_tdnn"), ("resemblyzer", "titanet"), ("ecapa_tdnn", "titanet")):
            d = sub[a] - sub[b]
            pair[f"{a}>{b}"] = {"p_greater": float((d > 0).mean()),
                                "diff_ci": [float(np.percentile(d, 2.5)), float(np.percentile(d, 97.5))]}
        # Pairwise test under speaker resampling, with Benjamini-Hochberg correction
        pvals, names = [], []
        for i, a in enumerate(models):
            for b in models[i + 1:]:
                d = sub[a] - sub[b]
                pvals.append(2 * min((d <= 0).mean(), (d >= 0).mean()))
                names.append((a, b))
        order = np.argsort(pvals)
        q = np.empty(len(pvals))
        prev = 1.0
        for rank, i in list(enumerate(order))[::-1]:
            prev = min(prev, pvals[i] * len(pvals) / (rank + 1))
            q[i] = prev
        nonsig = [(DISPLAY[a], DISPLAY[b], round(float(qq), 3)) for (a, b), qq in zip(names, q) if qq >= 0.05]
        return {"top1": {DISPLAY[k]: float(v) for k, v in top1.items()},
                "group_order_fraction": float(order_ok), "table": pd.DataFrame(rows), "pairs": pair,
                "cluster_pairwise": {"n_tests": len(pvals), "n_signif": int((q < 0.05).sum()),
                                     "not_significant": nonsig}}
    s = per_set(summ)
    for tag in MODEL_SETS:
        print(f"  [{tag}] group order holds in {100 * s[tag]['group_order_fraction']:.1f}% of resamples; "
              f"first place: " + ", ".join(f"{k} {100 * v:.1f}%" for k, v in s[tag]["top1"].items()))
        print(s[tag]["table"].round(2).to_string(index=False))
        print(f"  [{tag}] P(resemblyzer above ECAPA-TDNN) = {s[tag]['pairs']['resemblyzer>ecapa_tdnn']['p_greater']:.3f}, "
              f"difference interval {np.round(s[tag]['pairs']['resemblyzer>ecapa_tdnn']['diff_ci'], 3)}")
        cp = s[tag]["cluster_pairwise"]
        print(f"  [{tag}] pairwise test with speakers resampled: {cp['n_signif']} of {cp['n_tests']} pairs "
              f"differ at BH q < 0.05; not significant: {cp['not_significant']}")
    R["speaker_bootstrap"] = s


# --------------------------------------------------------------------------------------
# E. Listener consistency (does not depend on the models)
# --------------------------------------------------------------------------------------
def section_E():
    print("\n=== E. Listener consistency ===", flush=True)
    human_acc, trial_counts = human_accuracy()
    repeats = int(responses.duplicated(subset=["user_id", "stimuli_id"]).sum())
    print(f"  repeated (listener, pair) combinations: {repeats}")

    resp_b = responses.merge(df[["id", "p_same_full"]], left_on="stimuli_id", right_on="id")
    resp_b["bias"] = resp_b["answer"] - resp_b["p_same_full"]
    rng_f = np.random.default_rng(SEED + 2)
    eligible30 = trial_counts[trial_counts >= 30].index
    half = {"h1": {}, "h2": {}}
    for uid, g in resp_b[resp_b["user_id"].isin(eligible30)].groupby("user_id"):
        perm = rng_f.permutation(len(g))
        half["h1"][uid] = g.iloc[perm[:len(g) // 2]]["bias"].mean()
        half["h2"][uid] = g.iloc[perm[len(g) // 2:]]["bias"].mean()
    hb = pd.DataFrame(half).dropna()
    r_hb = pearsonr(hb["h1"], hb["h2"])[0]
    print(f"  response tendency, split-half r = {r_hb:.3f} over {len(hb)} listeners with at least 30 trials "
          f"(Spearman-Brown {2 * r_hb / (1 + r_hb):.3f})")

    t1 = responses[responses["stimuli_type"] == 1]
    t1_counts = t1.groupby("user_id").size()
    t1_elig = t1_counts[t1_counts >= 5].index
    t1_err = 1 - t1[t1["user_id"].isin(t1_elig)].groupby("user_id")["answer"].mean()
    print(f"  same-recording pairs: {100 * (1 - t1['answer'].mean()):.1f}% of judgments are 'different'; "
          f"median listener error {100 * t1_err.median():.1f}% over {len(t1_err)} listeners with at least 5 such trials")

    def _duo():
        t6r = responses[responses["stimuli_type"] == 6].copy()
        parts = t6r["stimuli_id"].str.split("_", expand=True)
        t6r["ref3"] = parts[1].str[:3]
        t6r["comp3"] = parts[2].str[:3]
        t6r["comp_ver"] = parts[2].str[3:]
        t6r["mscale"] = parts[3].astype(int)
        t6r = t6r[t6r["ref3"] != t6r["comp3"]]
        tot = responses.groupby("stimuli_id")["answer"].agg(["sum", "count"])
        rows = []
        for key, gg in t6r.groupby(["user_id", "ref3", "comp3", "mscale"]):
            if len(gg) != 2 or gg["comp_ver"].nunique() != 2:
                continue
            (s1, a1), (s2, a2) = zip(gg["stimuli_id"], gg["answer"])
            p1 = (tot.loc[s1, "sum"] - a1) / (tot.loc[s1, "count"] - 1)
            p2 = (tot.loc[s2, "sum"] - a2) / (tot.loc[s2, "count"] - 1)
            rows.append({"user_id": key[0], "mscale": key[3], "agree": int(a1 == a2),
                         "base": p1 * p2 + (1 - p1) * (1 - p2)})
        d = pd.DataFrame(rows)
        rngd = np.random.default_rng(SEED)
        uids = d["user_id"].unique()
        byu = {u: d[d["user_id"] == u] for u in uids}
        ex = []
        for _ in range(2000):
            smp = rngd.choice(uids, size=len(uids), replace=True)
            dd = pd.concat([byu[u] for u in smp])
            ex.append(dd["agree"].mean() - dd["base"].mean())
        return d, np.percentile(ex, [2.5, 97.5])
    duo, duo_ci = cached("duo_consistency", _duo, "matched morph pairs judged by one listener")
    mid = duo[(duo.mscale > 20) & (duo.mscale < 80)]
    print(f"  matched morph pairs: {len(duo)} from {duo.user_id.nunique()} listeners; agreement "
          f"{duo.agree.mean():.3f} vs {duo.base.mean():.3f} for two independent listeners; "
          f"difference {duo.agree.mean() - duo.base.mean():+.3f}, 95% interval [{duo_ci[0]:+.3f}, {duo_ci[1]:+.3f}]")
    print(f"  scales 21 to 79 only: n = {len(mid)}, agreement {mid.agree.mean():.3f} vs {mid.base.mean():.3f}")
    R["listener_consistency"] = {
        "repeats": repeats, "split_half_r": float(r_hb), "n_listeners_30": int(len(hb)),
        "t1_error_median": float(t1_err.median()), "t1_n_listeners": int(len(t1_err)),
        "t1_different_rate": float(1 - t1["answer"].mean()),
        "duo": {"n": int(len(duo)), "n_listeners": int(duo.user_id.nunique()),
                "agree": float(duo.agree.mean()), "base": float(duo.base.mean()),
                "ci": [float(duo_ci[0]), float(duo_ci[1])], "mid_n": int(len(mid)),
                "mid_agree": float(mid.agree.mean()), "mid_base": float(mid.base.mean())}}


# --------------------------------------------------------------------------------------
# F. Task 3 matrix: two permutation tests, directional and symmetrized
# --------------------------------------------------------------------------------------
def shuffle_test(x, y, n_perm=5000, seed=SEED):
    """Spearman rho, with a p-value from shuffling the model values freely (the notebook's test)."""
    rng_m = np.random.default_rng(seed)
    observed, _ = spearmanr(x, y)
    y_perm = y.copy()
    null = np.zeros(n_perm)
    for i in range(n_perm):
        rng_m.shuffle(y_perm)
        null[i], _ = spearmanr(x, y_perm)
    return observed, (np.abs(null) >= np.abs(observed)).mean()


def speaker_cells(pairs):
    """The groups of speakers that are compared with each other (20 cells of five speakers)."""
    spk = sorted(set(a for a, _ in pairs) | set(b for _, b in pairs))
    parent = {s: s for s in spk}

    def find(x):
        while parent[x] != x:
            parent[x] = parent[parent[x]]
            x = parent[x]
        return x
    for a, b in pairs:
        parent[find(a)] = find(b)
    cells = {}
    for s in spk:
        cells.setdefault(find(s), []).append(s)
    return list(cells.values())


def speaker_permutations(keys, cells, symmetric, n_perm=5000, seed=SEED + 1):
    """Index arrays for a test that permutes the speakers instead of the values.

    Each permutation exchanges whole cells and the speakers inside each cell. It relabels the
    reference speaker and the comparison speaker in the same way, so that all entries of a
    speaker move together."""
    index = {k: i for i, k in enumerate(keys)}
    rng_p = np.random.default_rng(seed)
    out = np.zeros((n_perm, len(keys)), dtype=int)
    for k in range(n_perm):
        relabel = {}
        order = rng_p.permutation(len(cells))
        for ci, members in enumerate(cells):
            target = cells[order[ci]]
            p = rng_p.permutation(len(target))
            for i, s in enumerate(members):
                relabel[s] = target[p[i]]
        if symmetric:
            out[k] = [index[tuple(sorted((relabel[a], relabel[b])))] for a, b in keys]
        else:
            out[k] = [index[(relabel[a], relabel[b])] for a, b in keys]
    return out


def speaker_test(x, y, perms):
    """Spearman rho of x and y, with a p-value from the speaker permutations of y."""
    rx = rankdata(x)
    observed = np.corrcoef(rx, rankdata(y))[0, 1]
    null = np.array([np.corrcoef(rx, rankdata(y[ix]))[0, 1] for ix in perms])
    return observed, (np.abs(null) >= abs(observed)).mean()


def section_F():
    print("\n=== F. Task 3 matrix, two permutation tests, directional and symmetrized ===", flush=True)
    rdm = (df[(df["reference"] != df["comparison"]) & df["stimuli_type"].isin([4, 5])]
           .groupby(["reference", "comparison"])
           .agg({"p_same_full": "mean", **{f"{m}_cosim": "mean" for m in ALL_MODELS}})
           .reset_index())
    assert len(rdm) == 400, len(rdm)
    rdm["ukey"] = [tuple(sorted([a, b])) for a, b in zip(rdm["reference"], rdm["comparison"])]
    rdm_sym = rdm.groupby("ukey").agg({"p_same_full": "mean",
                                       **{f"{m}_cosim": "mean" for m in ALL_MODELS}})
    keys_dir = list(zip(rdm["reference"], rdm["comparison"]))
    keys_sym = list(rdm_sym.index)
    cells = speaker_cells(keys_dir)
    assert len(cells) == 20 and all(len(c) == 5 for c in cells), [len(c) for c in cells]
    perm_dir = speaker_permutations(keys_dir, cells, symmetric=False)
    perm_sym = speaker_permutations(keys_sym, cells, symmetric=True)

    def _one(m):
        h_d, v_d = 1 - rdm["p_same_full"].values, 1 - rdm[f"{m}_cosim"].values
        h_s, v_s = 1 - rdm_sym["p_same_full"].values, 1 - rdm_sym[f"{m}_cosim"].values
        rho_d, p_d = shuffle_test(h_d, v_d)
        rho_s, p_s = shuffle_test(h_s, v_s)
        _, p_d_spk = speaker_test(h_d, v_d, perm_dir)
        _, p_s_spk = speaker_test(h_s, v_s, perm_sym)
        return {"rho_dir": rho_d, "p_dir": p_d, "p_dir_speakers": p_d_spk,
                "rho_sym": rho_s, "p_sym": p_s, "p_sym_speakers": p_s_spk}
    res = {m: cached(f"task3_tests_{m}", lambda m=m: _one(m), "Task 3 permutation tests") for m in ALL_MODELS}
    tab = pd.DataFrame([{"model": DISPLAY[m], "key": m,
                         "rho directional": res[m]["rho_dir"],
                         "p shuffle (dir)": res[m]["p_dir"],
                         "p speakers (dir)": res[m]["p_dir_speakers"],
                         "rho symmetrized": res[m]["rho_sym"],
                         "p shuffle (sym)": res[m]["p_sym"],
                         "p speakers (sym)": res[m]["p_sym_speakers"]} for m in ALL_MODELS])
    print(f"  directional entries {len(rdm)}, symmetrized entries {len(rdm_sym)}, speaker cells {len(cells)}")
    print("  'shuffle' shuffles the model values freely, as in the notebook. 'speakers' permutes the")
    print("  speakers within and between cells, so that all entries of a speaker move together.")
    print(tab.drop(columns="key").round(3).to_string(index=False))

    def summ(models):
        t = tab[tab["key"].isin(models)]
        return {"ordering_rho": spearmanr(t["rho directional"], t["rho symmetrized"])[0],
                "max_abs_change": float((t["rho directional"] - t["rho symmetrized"]).abs().max()),
                "max_p_sym": float(t["p shuffle (sym)"].max()),
                "max_p_sym_speakers": float(t["p speakers (sym)"].max()),
                "rank_dir": t.sort_values("rho directional", ascending=False)["model"].tolist()}
    s = per_set(summ)
    for tag in MODEL_SETS:
        print(f"  [{tag}] rank correlation between the two orderings {s[tag]['ordering_rho']:.3f}; largest change "
              f"{s[tag]['max_abs_change']:.3f}; largest p on the symmetrized matrix "
              f"{s[tag]['max_p_sym']:.3f} (shuffle) and {s[tag]['max_p_sym_speakers']:.3f} (speakers)")
        print(f"  [{tag}] directional order: {s[tag]['rank_dir']}")
    R["rdm"] = {"table": tab, "summary": s}

# --------------------------------------------------------------------------------------
# G. Unfamiliar and familiar trials
# --------------------------------------------------------------------------------------
def _split_half(resp, n_splits=100):
    rng = np.random.default_rng(SEED)
    uids = np.array(sorted(resp["user_id"].unique()))
    rs = []
    for _ in range(n_splits):
        perm = rng.permutation(uids)
        h1, h2 = set(perm[:len(perm) // 2]), set(perm[len(perm) // 2:])
        r1 = resp[resp["user_id"].isin(h1)].groupby("stimuli_id")["answer"].mean()
        r2 = resp[resp["user_id"].isin(h2)].groupby("stimuli_id")["answer"].mean()
        common = r1.index.intersection(r2.index)
        rs.append(pearsonr(r1[common], r2[common])[0])
    sh = float(np.mean(rs))
    return sh, 2 * sh / (1 + sh)


def section_G():
    print("\n=== G. Unfamiliar and familiar trials ===", flush=True)
    unfam = responses[responses["know_speaker"] == 0]
    fam = responses[responses["know_speaker"] == 1]
    agg_u = unfam.groupby("stimuli_id")["answer"].agg(["count", "sum"])
    agg_f = fam.groupby("stimuli_id")["answer"].agg(["count", "sum"])
    df["p_same_unfam"] = df["id"].map(agg_u["sum"] / agg_u["count"])
    df["n_unfam"] = df["id"].map(agg_u["count"])
    df["p_same_fam"] = df["id"].map(agg_f["sum"] / agg_f["count"])
    df["n_fam"] = df["id"].map(agg_f["count"])
    df["maj_full"] = np.where(df["p_same_full"] > 0.5, 1, np.where(df["p_same_full"] < 0.5, 0, np.nan))
    df["maj_unfam"] = np.where(df["p_same_unfam"] > 0.5, 1, np.where(df["p_same_unfam"] < 0.5, 0, np.nan))
    print(f"  unfamiliar judgments {len(unfam):,} ({len(unfam) / len(responses):.1%}), median votes per pair "
          f"{df['n_unfam'].median():.0f}; familiar judgments {len(fam):,}, pairs with at least 3 familiar votes "
          f"{int((df['n_fam'] >= 3).sum())}; tied pairs full {int(df['p_same_full'].eq(0.5).sum())}, "
          f"unfamiliar {int(df['p_same_unfam'].eq(0.5).sum())}")
    rows = []
    for m in ALL_MODELS:
        c = f"{m}_cosim"
        v1 = df.dropna(subset=[c, "p_same_unfam"])
        vf = df.dropna(subset=[c, "maj_full"])
        vu = df.dropna(subset=[c, "maj_unfam"])
        vfam = df.dropna(subset=[c, "p_same_fam"])
        vfam3 = vfam[vfam["n_fam"] >= 3]
        rows.append({"model": DISPLAY[m], "key": m, "T1 r full": task1_r[m],
                     "T1 r unfam": pearsonr(v1[c], v1["p_same_unfam"])[0],
                     "T2 AUC full": roc_auc_score(vf["maj_full"], vf[c]),
                     "T2 AUC unfam": roc_auc_score(vu["maj_unfam"], vu[c]),
                     "T1 r fam": pearsonr(vfam[c], vfam["p_same_fam"])[0],
                     "T1 r fam>=3": pearsonr(vfam3[c], vfam3["p_same_fam"])[0]})
    tab = pd.DataFrame(rows)
    tab["AUC delta"] = tab["T2 AUC unfam"] - tab["T2 AUC full"]
    tab["r delta"] = tab["T1 r unfam"] - tab["T1 r full"]
    print(tab.drop(columns="key").round(3).to_string(index=False))
    sh_u, sb_u = cached("unfam_ceiling", lambda: _split_half(unfam), "split-half ceiling, unfamiliar trials")
    sh_a, sb_a = cached("full_ceiling", lambda: _split_half(responses), "split-half ceiling, all trials")
    print(f"  ceiling on unfamiliar trials {sb_u:.3f}; ceiling on all trials with the same procedure {sb_a:.3f}")

    def summ(models):
        t = tab[tab["key"].isin(models)].set_index("key")
        best_u = t["T1 r unfam"].max()
        best_f = t["T1 r full"].max()
        return {"rho_r": spearmanr(t["T1 r full"], t["T1 r unfam"])[0],
                "rho_auc": spearmanr(t["T2 AUC full"], t["T2 AUC unfam"])[0],
                "rho_fam": spearmanr(t["T1 r full"], t["T1 r fam"])[0],
                "rho_fam3": spearmanr(t["T1 r full"], t["T1 r fam>=3"])[0],
                "max_r_drop": float(-t["r delta"].min()), "auc_drop_range": [float(-t["AUC delta"].max()), float(-t["AUC delta"].min())],
                "group_order_unfam": group_order_holds(t["T1 r unfam"].to_dict(), models),
                "group_order_fam3": group_order_holds(t["T1 r fam>=3"].to_dict(), models),
                "best_unfam": DISPLAY[t["T1 r unfam"].idxmax()], "best_fam3": DISPLAY[t["T1 r fam>=3"].idxmax()],
                "norm_unfam": float(best_u ** 2 / sb_u), "norm_full": float(best_f ** 2 / sb_a)}
    s = per_set(summ)
    for tag in MODEL_SETS:
        x = s[tag]
        print(f"  [{tag}] rank correlation full vs unfamiliar: Task 1 {x['rho_r']:.3f}, Task 2 AUC {x['rho_auc']:.3f}; "
              f"largest r drop {x['max_r_drop']:.3f}; AUC drop {x['auc_drop_range'][0]:.3f} to {x['auc_drop_range'][1]:.3f}; "
              f"best model reaches {100 * x['norm_unfam']:.0f}% of the unfamiliar ceiling vs {100 * x['norm_full']:.0f}%")
        print(f"  [{tag}] familiar trials: rank correlation {x['rho_fam']:.3f} (all), {x['rho_fam3']:.3f} (at least 3 votes); "
              f"best model on familiar (at least 3 votes) {x['best_fam3']}; group order unfamiliar {x['group_order_unfam']}, "
              f"familiar {x['group_order_fam3']}")
    R["familiarity"] = {"table": tab, "ceiling_unfam": sb_u, "ceiling_full": sb_a, "summary": s,
                        "n_unfam": int(len(unfam)), "n_fam": int(len(fam)),
                        "pairs_fam3": int((df["n_fam"] >= 3).sum())}


# --------------------------------------------------------------------------------------
# H. VoxCeleb identity overlap
# --------------------------------------------------------------------------------------
def norm_name(s):
    s = unicodedata.normalize("NFKD", str(s))
    s = "".join(c for c in s if not unicodedata.combining(c))
    s = re.sub(r"[._\-]+", " ", s.lower())
    s = re.sub(r"[^a-z ]", "", s)
    return re.sub(r"\s+", " ", s).strip()


def voxceleb_overlap_ids(vox_dir):
    """Match the 100 speaker names against the VoxCeleb1 and VoxCeleb2 identity lists. The
    lists are not part of the release. `vox_dir` must hold vox1_meta.csv, vox2_meta.csv, and
    the VGGFace2 identity_meta.csv from the VoxCeleb website."""
    vox_dir = Path(vox_dir)
    spk = speakers.copy()
    spk["norm"] = spk["name"].map(norm_name)
    vox1 = pd.read_csv(vox_dir / "vox1_meta.csv", sep="\t")
    vox1.columns = [c.strip() for c in vox1.columns]
    vox1_names = set(vox1["VGGFace1 ID"].map(norm_name))
    vox2 = pd.read_csv(vox_dir / "vox2_meta.csv", encoding="utf-8-sig")
    vox2.columns = [c.strip() for c in vox2.columns]
    vgg = pd.read_csv(vox_dir / "vggface2_identity_meta.csv", skipinitialspace=True,
                      quotechar='"', on_bad_lines="skip")
    vgg.columns = [c.strip() for c in vgg.columns]
    vgg["Class_ID"] = vgg["Class_ID"].str.strip()
    vgg_name = dict(zip(vgg["Class_ID"], vgg["Name"].map(norm_name)))
    vox2_names = {vgg_name[i] for i in set(vox2["VGGFace2 ID"].str.strip()) if i in vgg_name}
    spk["in_vox1"] = spk["norm"].isin(vox1_names)
    spk["in_vox2"] = spk["norm"].isin(vox2_names)
    return spk.loc[spk["in_vox1"] | spk["in_vox2"], ["id", "name", "in_vox1", "in_vox2"]]


def section_H(vox_dir):
    print("\n=== H. VoxCeleb identity overlap ===")
    listfile = CODE / "voxceleb_overlap.csv"
    if vox_dir and Path(vox_dir).exists():
        ov = voxceleb_overlap_ids(vox_dir)
        ov.to_csv(listfile, index=False)
        print(f"  matched {len(ov)} of 100 speakers by name and wrote {listfile.name}")
    elif listfile.exists():
        ov = pd.read_csv(listfile)
        print(f"  read {len(ov)} overlapping speakers from {listfile.name}")
    else:
        print("  skipped: no VoxCeleb identity lists and no voxceleb_overlap.csv")
        return
    vox_set = set(ov["id"])
    clean = ~df["reference"].isin(vox_set) & ~df["comp_speaker"].isin(vox_set)
    rows = []
    for m in ALL_MODELS:
        v = df.dropna(subset=[f"{m}_cosim", "p_same_full"])
        c = clean.loc[v.index]
        rows.append({"model": DISPLAY[m], "key": m, "r full": task1_r[m],
                     "r non-overlap": pearsonr(*v[c][[f"{m}_cosim", "p_same_full"]].values.T)[0],
                     "r overlap-involved": pearsonr(*v[~c][[f"{m}_cosim", "p_same_full"]].values.T)[0]})
    tab = pd.DataFrame(rows)
    print(f"  pairs with both speakers outside VoxCeleb: {int(clean.sum())}")
    print(tab.drop(columns="key").round(3).to_string(index=False))

    def summ(models):
        t = tab[tab["key"].isin(models)].set_index("key")
        sup = [m for m in models if m in SUPERVISED]
        ssl = [m for m in models if m in SSL]
        return {"rho": spearmanr(t["r full"], t["r non-overlap"])[0],
                "gap_clean": float(t.loc[sup, "r non-overlap"].mean() - t.loc[ssl, "r non-overlap"].mean()),
                "gap_overlap": float(t.loc[sup, "r overlap-involved"].mean() - t.loc[ssl, "r overlap-involved"].mean()),
                "gap_full": float(t.loc[sup, "r full"].mean() - t.loc[ssl, "r full"].mean()),
                "group_order": group_order_holds(t["r non-overlap"].to_dict(), models),
                "best_clean": DISPLAY[t["r non-overlap"].idxmax()]}
    s = per_set(summ)
    for tag in MODEL_SETS:
        x = s[tag]
        print(f"  [{tag}] rank correlation with the full ranking {x['rho']:.3f}; mean gap supervised minus SSL "
              f"{x['gap_clean']:.3f} (outside VoxCeleb), {x['gap_overlap']:.3f} (pairs with a VoxCeleb speaker), "
              f"{x['gap_full']:.3f} (all pairs); group order {x['group_order']}; best model {x['best_clean']}")
    R["voxceleb"] = {"overlap": ov, "n_clean_pairs": int(clean.sum()), "table": tab, "summary": s}


# --------------------------------------------------------------------------------------
# I. Reliability and alignment by stimulus type
# --------------------------------------------------------------------------------------
def section_I():
    print("\n=== I. Reliability and alignment by stimulus type ===", flush=True)

    def _per_type():
        rng = np.random.default_rng(SEED)
        uids = np.array(sorted(responses["user_id"].unique()))
        type_of = stimuli.set_index("id")["stimuli_type"]
        acc = {t: [] for t in [1, 2, 3, 4, 5, 6]}
        for _ in range(100):
            perm = rng.permutation(uids)
            h1, h2 = set(perm[:len(perm) // 2]), set(perm[len(perm) // 2:])
            r1 = responses[responses["user_id"].isin(h1)].groupby("stimuli_id")["answer"].mean()
            r2 = responses[responses["user_id"].isin(h2)].groupby("stimuli_id")["answer"].mean()
            common = r1.index.intersection(r2.index)
            tt = type_of.reindex(common)
            for t in acc:
                ids = common[tt.values == t]
                if len(ids) > 20:
                    acc[t].append(pearsonr(r1[ids], r2[ids])[0])
        return {t: (np.mean(v), 2 * np.mean(v) / (1 + np.mean(v))) for t, v in acc.items()}
    type_ceil = cached("per_type_ceiling", _per_type, "split-half reliability within each stimulus type")
    votes = responses.groupby("stimuli_id").size()
    df["_votes"] = df["id"].map(votes)
    ceil = pd.DataFrame([{"type": t, "pairs": int((df["stimuli_type"] == t).sum()),
                          "mean votes/pair": df.loc[df["stimuli_type"] == t, "_votes"].mean(),
                          "P(same) mean": df.loc[df["stimuli_type"] == t, "p_same_full"].mean(),
                          "P(same) SD": df.loc[df["stimuli_type"] == t, "p_same_full"].std(),
                          "split-half r": type_ceil[t][0], "Spearman-Brown": type_ceil[t][1]}
                         for t in [1, 2, 3, 4, 5, 6]])
    print(ceil.round(3).to_string(index=False))
    type_r = {m: {} for m in ALL_MODELS}
    for m in ALL_MODELS:
        for t in [1, 2, 3, 4, 5, 6]:
            v = df[df["stimuli_type"] == t].dropna(subset=[f"{m}_cosim", "p_same_full"])
            type_r[m][t] = pearsonr(v[f"{m}_cosim"], v["p_same_full"])[0]
    tr = pd.DataFrame([{"model": DISPLAY[m], **{f"T{t}": type_r[m][t] for t in [1, 2, 3, 4, 5, 6]}}
                       for m in ALL_MODELS])
    print(tr.round(3).to_string(index=False))
    R["by_type"] = {"ceilings": ceil, "type_r": type_r, "table": tr}
    return type_r


# --------------------------------------------------------------------------------------
# J. Vote downsampling
# --------------------------------------------------------------------------------------
def section_J():
    print("\n=== J. Vote downsampling (Types 1, 2, 4 reduced to 10 votes per pair, 20 draws) ===", flush=True)

    def _ds():
        rng = np.random.default_rng(SEED)
        real_ids = set(df.loc[df["stimuli_type"].isin([1, 2, 4]), "id"])
        votes_by_pair = {sid: g["answer"].to_numpy()
                         for sid, g in responses.groupby("stimuli_id") if sid in real_ids}
        base = df["p_same_full"].copy()
        per_model = {m: [] for m in ALL_MODELS}
        for _ in range(20):
            ds_map = {sid: rng.choice(v, size=min(10, len(v)), replace=False).mean()
                      for sid, v in votes_by_pair.items()}
            target = df["id"].map(ds_map).fillna(base)
            for m in ALL_MODELS:
                v = ~df[f"{m}_cosim"].isna() & ~target.isna()
                per_model[m].append(pearsonr(df.loc[v, f"{m}_cosim"], target[v])[0])
        return per_model
    per_model = cached("downsample_r", _ds, "20 draws")
    tab = pd.DataFrame([{"model": DISPLAY[m], "r full votes": task1_r[m], "mean": np.mean(per_model[m]),
                         "min": np.min(per_model[m]), "max": np.max(per_model[m])} for m in ALL_MODELS])
    print(tab.round(3).to_string(index=False))

    def summ(models):
        rhos = [spearmanr([task1_r[m] for m in models], [per_model[m][k] for m in models])[0] for k in range(20)]
        mean_ds = {m: float(np.mean(per_model[m])) for m in models}
        srt = sorted(models, key=lambda m: -task1_r[m])
        overlap = any(np.max(per_model[b]) >= np.min(per_model[a]) for a, b in zip(srt[:-1], srt[1:]))
        return {"rho_min": float(np.min(rhos)), "rho_mean": float(np.mean(rhos)),
                "n_identical": int(np.sum(np.isclose(rhos, 1.0))),
                "group_order": group_order_holds(mean_ds, models), "adjacent_ranges_overlap": bool(overlap),
                "max_range": float(max(np.max(per_model[m]) - np.min(per_model[m]) for m in models))}
    s = per_set(summ)
    for tag in MODEL_SETS:
        x = s[tag]
        print(f"  [{tag}] rank correlation with the full ranking: min {x['rho_min']:.3f}, mean {x['rho_mean']:.3f}, "
              f"identical in {x['n_identical']} of 20 draws; group order {x['group_order']}; "
              f"ranges of adjacent models overlap {x['adjacent_ranges_overlap']}; largest range {x['max_range']:.4f}")
    R["downsample"] = {"per_model": per_model, "table": tab, "summary": s}


# --------------------------------------------------------------------------------------
# K. Equal weight for each stimulus type
# --------------------------------------------------------------------------------------
def section_K(type_r):
    print("\n=== K. Equal weight for each stimulus type ===")
    eq6 = {m: float(np.mean([type_r[m][t] for t in [1, 2, 3, 4, 5, 6]])) for m in ALL_MODELS}
    eq5 = {m: float(np.mean([type_r[m][t] for t in [2, 3, 4, 5, 6]])) for m in ALL_MODELS}

    def summ(models):
        t = pd.DataFrame({"model": [DISPLAY[m] for m in models], "pooled r": [task1_r[m] for m in models],
                          "equal T1-6": [eq6[m] for m in models], "equal T2-6": [eq5[m] for m in models]})
        for c in ["pooled r", "equal T1-6", "equal T2-6"]:
            t["rk " + c] = t[c].rank(ascending=False).astype(int)
        return {"table": t, "rho_T1_6": spearmanr(t["pooled r"], t["equal T1-6"])[0],
                "rho_T2_6": spearmanr(t["pooled r"], t["equal T2-6"])[0],
                "group_order_T1_6": group_order_holds(eq6, models),
                "group_order_T2_6": group_order_holds(eq5, models)}
    s = per_set(summ)
    for tag in MODEL_SETS:
        x = s[tag]
        print(x["table"].round(3).to_string(index=False))
        print(f"  [{tag}] rank correlation with the pooled ranking: {x['rho_T1_6']:.3f} (Types 1 to 6), "
              f"{x['rho_T2_6']:.3f} (Types 2 to 6); group order {x['group_order_T1_6']} / {x['group_order_T2_6']}")
    R["equal_weight"] = {"eq6": eq6, "eq5": eq5, "summary": s}


# --------------------------------------------------------------------------------------
# L. Listener questionnaire and participation
# --------------------------------------------------------------------------------------
def section_L():
    print("\n=== L. Listener questionnaire and participation ===")
    cols = [c for c in ["age", "gender", "first_language", "hearing"] if c in responses.columns]
    per_p = responses.sort_values("user_id").groupby("user_id")[cols].first()
    out = {"n_listeners": int(len(per_p)), "n_answered": int(per_p["gender"].notna().sum())}
    print(f"  listeners {out['n_listeners']}, with a questionnaire {out['n_answered']}")
    for c in cols:
        out[c] = per_p[c].value_counts(dropna=False).sort_index().to_dict()
        print(f"  {c}: {out[c]}")
    if "hearing" in cols:
        h = per_p["hearing"].dropna()
        out["hearing_good_or_better"] = float((h >= 3).mean())
        print(f"  hearing good or better: {100 * out['hearing_good_or_better']:.1f}% of {len(h)}")
    tc = responses.groupby("user_id").size()
    out["trials_per_listener"] = {"median": float(tc.median()), "min": int(tc.min()), "max": int(tc.max()),
                                  "n_at_least_10": int((tc >= 10).sum())}
    print(f"  trials per listener: median {tc.median():.0f}, range {tc.min()} to {tc.max()}; "
          f"{(tc >= 10).sum()} listeners have at least 10 trials")

    # Share of the judgments that come from the most active listeners, and the Task 1
    # ranking when their judgments are removed.
    srt = tc.sort_values(ascending=False, kind="stable")
    out["share_of_most_active"] = {k: float(srt.head(k).sum() / len(responses)) for k in (10, 20, 100)}
    print("  share of all judgments from the most active listeners: "
          + ", ".join(f"top {k} {100 * v:.1f}%" for k, v in out["share_of_most_active"].items()))
    without = {}
    for k in (10, 20):
        keep = responses[~responses["user_id"].isin(set(srt.head(k).index))]
        votes = keep.groupby("stimuli_id")["answer"].agg(["mean", "size"])
        target = df["id"].map(votes["mean"])
        r = {}
        for m in ALL_MODELS:
            v = df[f"{m}_cosim"].notna() & target.notna()
            r[m] = pearsonr(df.loc[v, f"{m}_cosim"], target[v])[0]
        without[k] = {"r": r, "n_judgments": int(len(keep)), "n_pairs": int(target.notna().sum()),
                      "median_votes": float(votes["size"].median()), "min_votes": int(votes["size"].min())}
        print(f"  without the {k} most active listeners: {len(keep):,} judgments, {without[k]['n_pairs']:,} pairs "
              f"with a judgment, median {without[k]['median_votes']:.0f} and minimum {without[k]['min_votes']} per pair")
        print("    Task 1 r: " + ", ".join(f"{DISPLAY[m]} {r[m]:.3f}" for m in ALL_MODELS))

    def summ(models):
        full_order = sorted(models, key=lambda m: -task1_r[m])
        return {k: {"rho": float(rank_corr(task1_r, without[k]["r"], models)),
                    "identical": full_order == sorted(models, key=lambda m: -without[k]["r"][m]),
                    "group_order": group_order_holds(without[k]["r"], models)} for k in without}
    s = per_set(summ)
    for tag in MODEL_SETS:
        for k in without:
            x = s[tag][k]
            print(f"  [{tag}] without the {k} most active listeners: rank correlation with the full ranking "
                  f"{x['rho']:.3f}, identical ranking {x['identical']}, group order {x['group_order']}")
    out["without_most_active"] = {"per_k": without, "summary": s}
    R["questionnaire"] = out


# --------------------------------------------------------------------------------------
# M. CosyVoice 2 extension subset
# --------------------------------------------------------------------------------------
def ols2(x, y):
    b1, b0 = np.polyfit(x, y, 1)
    return b0, b1


def section_M(real_only):
    print("\n=== M. CosyVoice 2 extension subset (frozen models) ===", flush=True)
    pairs = pd.read_csv(EXT / "pairs.csv")
    pairs = pairs[pairs["analysed"]].sort_values(["claimed_speaker_id", "suffix"]).reset_index(drop=True)
    resp = pd.read_csv(EXT / "responses.csv")
    resp["same"] = resp["choice"].isin([3, 4]).astype(int)
    votes = resp.groupby("stimulus_id")["same"].agg(["mean", "count"])
    pairs["p_same"] = pairs["stimulus_id"].map(votes["mean"])
    pairs["n_votes"] = pairs["stimulus_id"].map(votes["count"])
    n_list = resp[resp.stimulus_id.isin(pairs.stimulus_id)].listener_id.nunique()
    print(f"  {len(pairs)} analysed pairs, {int(pairs.n_votes.sum())} ratings, {n_list} listeners, "
          f"median {pairs.n_votes.median():.0f} per pair (range {int(pairs.n_votes.min())} to {int(pairs.n_votes.max())})")

    def cos(a, b):
        return float(a @ b / ((np.linalg.norm(a) * np.linalg.norm(b)) + 1e-10))
    for m in ALL_MODELS:
        if m in LAYERED:
            emb = np.load(EXT / "embeddings" / "layers" / f"{m}.npz")
            L = MODAL_LAYER[m]
            get = lambda k, e=emb, L=L: e[k][L]
        else:
            emb = np.load(EXT / "embeddings" / f"{m}.npz")
            get = lambda k, e=emb: e[k]
        pairs[f"{m}_cosim"] = [cos(get(r.comparison_clip_id), get(f"{r.claimed_speaker_id}R"))
                               for r in pairs.itertuples()]
    ext_r = {m: pearsonr(pairs[f"{m}_cosim"], pairs["p_same"])[0] for m in ALL_MODELS}
    spk_list = sorted(pairs["claimed_speaker_id"].unique())

    def _boot():
        rngb = np.random.default_rng(SEED)
        out = np.full((2000, len(ALL_MODELS)), np.nan)
        for b in range(2000):
            spks = rngb.choice(spk_list, size=len(spk_list), replace=True)
            idx = np.concatenate([pairs.index[pairs["claimed_speaker_id"] == s].values for s in spks])
            sub = pairs.loc[idx]
            for j, m in enumerate(ALL_MODELS):
                if sub[f"{m}_cosim"].std() >= 1e-10 and sub["p_same"].std() >= 1e-10:
                    out[b, j] = pearsonr(sub[f"{m}_cosim"], sub["p_same"])[0]
        return out
    boot = pd.DataFrame(cached("extension_boot_r", _boot, "resampling the 10 speakers"), columns=ALL_MODELS)

    real_suf, clone_suf = ["_02", "_07"], ["_03", "_04", "_05", "_06"]
    e_real = pairs[pairs["suffix"].isin(real_suf)]
    e_syn = pairs[pairs["suffix"].isin(clone_suf)]

    def ext_stats(sub_r, sub_s, col):
        b0, b1 = ols2(sub_r[col].values, sub_r["p_same"].values)
        y = sub_s["p_same"].values
        sst = ((y - y.mean()) ** 2).sum()
        r2_t = 1 - ((y - (b0 + b1 * sub_s[col].values)) ** 2).sum() / sst
        b0s, b1s = ols2(sub_s[col].values, y)
        return r2_t, b1 / b1s, b1 - b1s

    def _t4boot():
        rngb = np.random.default_rng(SEED)
        out = {m: {"ratio": [], "transfer": []} for m in ALL_MODELS}
        for _ in range(2000):
            spks = rngb.choice(spk_list, size=len(spk_list), replace=True)
            ir = np.concatenate([e_real.index[e_real["claimed_speaker_id"] == s].values for s in spks])
            isv = np.concatenate([e_syn.index[e_syn["claimed_speaker_id"] == s].values for s in spks])
            sub_r, sub_s = pairs.loc[ir], pairs.loc[isv]
            for m in ALL_MODELS:
                try:
                    r2t, ratio, _ = ext_stats(sub_r, sub_s, f"{m}_cosim")
                except Exception:
                    r2t, ratio = np.nan, np.nan
                out[m]["ratio"].append(ratio)
                out[m]["transfer"].append(r2t)
        return out
    t4b = cached("extension_task4_boot", _t4boot, "slope ratio on the extension subset")

    rows = []
    for m in ALL_MODELS:
        lo, hi = np.nanpercentile(boot[m], [2.5, 97.5])
        r2t, ratio, _ = ext_stats(e_real, e_syn, f"{m}_cosim")
        br = np.array(t4b[m]["ratio"], dtype=float)
        br = br[np.isfinite(br)]
        rows.append({"model": DISPLAY[m], "key": m, "main r": task1_r[m],
                     "main r (Types 2-5)": real_only["types25_r"][m], "extension r": ext_r[m],
                     "ci lo": lo, "ci hi": hi, "slope ratio": ratio,
                     "ratio lo": np.percentile(br, 2.5), "ratio hi": np.percentile(br, 97.5),
                     "P(ratio>1)": float((br > 1).mean()), "R2 transfer": r2t})
    tab = pd.DataFrame(rows)
    print(tab.drop(columns="key").round(3).to_string(index=False))

    def summ(models):
        sub = boot[models]
        sup = [m for m in models if m in SUPERVISED]
        ssl = [m for m in models if m in SSL]
        order_frac = ((sub[sup].min(axis=1) > sub[ssl].max(axis=1)) & (sub[ssl].min(axis=1) > sub[WHISPER])).mean()
        # The rebuttal used a weaker check for this number, where only the best SSL model
        # has to be above Whisper. It is kept so the rebuttal value can be reproduced.
        order_frac_weak = ((sub[sup].min(axis=1) > sub[ssl].max(axis=1)) & (sub[ssl].max(axis=1) > sub[WHISPER])).mean()
        brho = [spearmanr([task1_r[m] for m in models], row.values)[0] for _, row in sub.iterrows()]
        t = tab[tab["key"].isin(models)]
        return {"rho_full": rank_corr(task1_r, ext_r, models),
                "rho_t25": rank_corr(real_only["types25_r"], ext_r, models),
                "group_order_point": group_order_holds(ext_r, models),
                "group_order_fraction": float(order_frac),
                "group_order_fraction_weak": float(order_frac_weak),
                "rho_boot": [float(np.nanmedian(brho)), float(np.nanpercentile(brho, 2.5)), float(np.nanpercentile(brho, 97.5))],
                "n_ratio_above_1": int((t["slope ratio"] > 1).sum()), "n_models": int(len(t)),
                "sup_ratio_above_1": int((t[t["key"].isin(sup)]["slope ratio"] > 1).sum()), "n_sup": len(sup)}
    s = per_set(summ)
    for tag in MODEL_SETS:
        x = s[tag]
        print(f"  [{tag}] rank correlation with the main benchmark {x['rho_full']:.3f} (all types), {x['rho_t25']:.3f} "
              f"(Types 2 to 5); bootstrap median {x['rho_boot'][0]:.3f}, interval [{x['rho_boot'][1]:.3f}, {x['rho_boot'][2]:.3f}]; "
              f"group order on point estimates {x['group_order_point']}, in {100 * x['group_order_fraction']:.1f}% of resamples; "
              f"slope ratio above 1 for {x['sup_ratio_above_1']} of {x['n_sup']} supervised models and "
              f"{x['n_ratio_above_1']} of {x['n_models']} models")
    R["extension"] = {"table": tab, "ext_r": ext_r, "summary": s, "n_pairs": int(len(pairs)),
                      "n_ratings": int(pairs.n_votes.sum()), "n_listeners": int(n_list)}


# --------------------------------------------------------------------------------------
def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--sections", default="A,B,C,D,E,F,G,H,I,J,K,L,M")
    ap.add_argument("--voxceleb-dir", default=os.environ.get("VOXCELEB_META_DIR", ""),
                    help="folder with vox1_meta.csv, vox2_meta.csv, vggface2_identity_meta.csv")
    args = ap.parse_args()
    want = set(args.sections.split(","))
    type_r = None
    if "A" in want: section_A()
    if "B" in want or "M" in want: section_B()
    if "C" in want: section_C()
    if "D" in want: section_D()
    if "E" in want: section_E()
    if "F" in want: section_F()
    if "G" in want: section_G()
    if "H" in want: section_H(args.voxceleb_dir)
    if "I" in want or "K" in want: type_r = section_I()
    if "J" in want: section_J()
    if "K" in want: section_K(type_r)
    if "L" in want: section_L()
    if "M" in want: section_M(R["real_only"])
    out = CACHE / "robustness_results.pkl"
    prev = {}
    if out.exists():
        with open(out, "rb") as fh:
            prev = pickle.load(fh)
    prev.update(R)
    with open(out, "wb") as fh:
        pickle.dump(prev, fh)
    print(f"\nSaved {out}")


if __name__ == "__main__":
    main()