File size: 73,248 Bytes
3ccaf5a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
"""Generate the headline figures and numerics table for the paper.

Design conventions follow what top-venue ML papers (NeurIPS, ICLR, Nature MI)
actually ship, not what matplotlib defaults give you. Specifically:

    - Base font 8pt, axis labels 9pt, tick labels 7pt, legend 7pt.
    - Tableau-10 muted palette for categorical series; Nature-muted for
      error-type stacks.
    - CI band alpha 0.08 with a 0.4-alpha 0.5pt edge, NOT the chunky 0.12
      fills that make overlapping series look like mud.
    - Solid fills + 0.8pt white edges on stacked bars. NO hatching.
    - No end-caps on forest-plot whiskers; 4pt filled-circle markers.
    - Zero reference line solid grey (#999999), not dashed.
    - Type-42 fonts so the typesetter can re-kern; Type-3 is an amateur tell.
    - NeurIPS widths: 3.25" single-column, 6.75" double-column.

Data consumed:
    results/metrics/{model}_{quant}_{bench}_run0_metrics.json   point estimates
    results/metrics/{model}_{quant}_{bench}_run0_ci.json        bootstrap CIs
    results/metrics/{model}_{quant}_{bench}_run0_sig.json       paired sig tests
"""

import argparse
import glob
import json
import os
import re
import sys
from collections import defaultdict
from typing import Dict, List, Optional, Tuple

import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))


# ---------------------------------------------------------------------------
# Global style (Q1-venue defaults)
# ---------------------------------------------------------------------------

mpl.rcParams.update({
    "font.family": "sans-serif",
    "font.sans-serif": ["Inter", "Helvetica Neue", "Arial", "DejaVu Sans"],
    "font.size": 8,
    "axes.titlesize": 9,
    "axes.titleweight": "regular",
    "axes.titlepad": 6,
    "axes.labelsize": 9,
    "axes.labelpad": 3,
    "xtick.labelsize": 7,
    "ytick.labelsize": 7,
    "legend.fontsize": 7,
    "legend.frameon": False,
    "figure.dpi": 200,
    "savefig.dpi": 400,
    "savefig.bbox": "tight",
    "pdf.fonttype": 42,
    "ps.fonttype": 42,
    "axes.linewidth": 0.6,
    "axes.edgecolor": "#333333",
    "axes.labelcolor": "#222222",
    "axes.titlecolor": "#222222",
    "xtick.color": "#333333",
    "ytick.color": "#333333",
    "xtick.major.width": 0.6,
    "ytick.major.width": 0.6,
    "xtick.major.size": 3,
    "ytick.major.size": 3,
    "xtick.major.pad": 2,
    "ytick.major.pad": 2,
    "axes.spines.top": False,
    "axes.spines.right": False,
    "grid.color": "#EAEAEA",
    "grid.linewidth": 0.5,
    "grid.linestyle": "-",
    "lines.linewidth": 1.3,
    "lines.solid_capstyle": "round",
    "patch.linewidth": 0.0,
    "hatch.linewidth": 0.0,          # we don't hatch
})


# Tableau-10 muted: a de-facto standard for categorical ML figures.
# Darker shade = base quantization, paired lighter shade = restored variant.
METHOD_COLOR = {
    "awq_w4":                 "#4E79A7",
    "awq_w4_restored":        "#A0CBE8",
    "gptq_w4":                "#E15759",
    "gptq_w4_restored":       "#FF9D9A",
    "bnb_nf4_w4":             "#59A14F",
    "bnb_nf4_w4_restored":    "#8CD17D",
}
METHOD_ORDER = ["awq_w4", "gptq_w4", "bnb_nf4_w4"]
METHOD_PRETTY = {"awq_w4": "AWQ w4", "gptq_w4": "GPTQ w4", "bnb_nf4_w4": "BnB NF4"}

# Nature-muted error-type palette — categorical-ish but visually calm.
ERROR_COLORS = {
    "conceptual":     "#264653",
    "methodological": "#2A9D8F",
    "executional":    "#E9C46A",
    "logical":        "#E76F51",
}
ERROR_TYPES = ["conceptual", "methodological", "executional", "logical"]

BENCHMARKS = ["gsm8k", "math500", "gpqa"]
BENCH_PRETTY = {"gsm8k": "GSM8K", "math500": "MATH-500", "gpqa": "GPQA-Diamond"}

GREY_REF = "#999999"   # zero/reference line
GREY_LIGHT = "#C7C7C7"
GREY_TEXT = "#555555"


# ---------------------------------------------------------------------------
# Data loading
# ---------------------------------------------------------------------------

def _benchmark_from_filename(fname: str) -> str:
    for bench in BENCHMARKS:
        if re.search(rf"_{bench}_run\d+_metrics\.json$", fname):
            return bench
    return "unknown"


def _parse_ci_name(fname: str, suffix: str):
    base = fname.replace(suffix, "")
    m = re.match(r"(.+?)_(awq_w\d+(?:_restored)?|gptq_w\d+(?:_restored)?|bnb_nf\d+_w\d+(?:_restored)?)_(\w+)_run\d+$", base)
    if not m:
        return None
    return m.group(1), m.group(2), m.group(3)


def load_all(metrics_dir: str) -> Dict[Tuple[str, str, str], dict]:
    data: Dict[Tuple[str, str, str], dict] = {}

    for f in glob.glob(os.path.join(metrics_dir, "*_metrics.json")):
        with open(f) as fp:
            d = json.load(fp)
        bench = _benchmark_from_filename(os.path.basename(f))
        model = d.get("model")
        quant = d.get("quantization")
        if model and quant:
            data.setdefault((model, quant, bench), {}).update(d)

    for f in glob.glob(os.path.join(metrics_dir, "*_ci.json")):
        parsed = _parse_ci_name(os.path.basename(f), "_ci.json")
        if not parsed:
            continue
        model, quant, bench = parsed
        if bench not in BENCHMARKS:
            continue
        with open(f) as fp:
            d = json.load(fp)
        data.setdefault((model, quant, bench), {})["ci"] = d

    for f in glob.glob(os.path.join(metrics_dir, "*_sig.json")):
        parsed = _parse_ci_name(os.path.basename(f), "_sig.json")
        if not parsed:
            continue
        model, quant, bench = parsed
        if bench not in BENCHMARKS:
            continue
        with open(f) as fp:
            d = json.load(fp)
        data.setdefault((model, quant, bench), {})["sig_vs_restored"] = d

    return data


def sig_mark(p: Optional[float]) -> str:
    """Single-asterisk convention; threshold documented in the legend footnote."""
    if p is None:
        return ""
    return "*" if p < 0.05 else ""


def sig_stars_tex(p: Optional[float]) -> str:
    """For LaTeX table only — three-tier stars since the table has room."""
    if p is None:
        return ""
    if p < 0.001:
        return "$^{***}$"
    if p < 0.01:
        return "$^{**}$"
    if p < 0.05:
        return "$^{*}$"
    return ""


# ---------------------------------------------------------------------------
# Fig 1 — SSR curves with CI bands
# ---------------------------------------------------------------------------

def fig_paper_1_ssr(data, primary_model: str, output_path: str):
    """Step-survival with 95% bootstrap CI bands. One panel per benchmark.

    Base = solid + filled CI band (alpha 0.08 with a 0.5pt edge at 0.35
    alpha — the edge keeps the band from dissolving into the other bands).
    Restored = dashed line only, no band (showing 6 bands would be mud).
    """
    fig, axes = plt.subplots(1, 3, figsize=(6.75, 2.15),
                             sharey=True, constrained_layout=True)

    for ax, bench in zip(axes, BENCHMARKS):
        max_d = 0
        for method in METHOD_ORDER:
            color = METHOD_COLOR[method]
            color_rest = METHOD_COLOR[method + "_restored"]

            base_entry = data.get((primary_model, method, bench)) or {}
            rest_entry = data.get((primary_model, method + "_restored", bench)) or {}

            # Base: line + CI band + edge
            ssr = base_entry.get("ssr_curve", [])
            if ssr:
                x = np.arange(len(ssr))
                max_d = max(max_d, len(ssr))
                ci = (base_entry.get("ci") or {}).get("ssr_curve_ci", {}) or {}
                lo = ci.get("ci_lo") or []
                hi = ci.get("ci_hi") or []
                if lo and hi:
                    lo_arr = np.array([np.nan if v is None else v for v in lo[: len(ssr)]])
                    hi_arr = np.array([np.nan if v is None else v for v in hi[: len(ssr)]])
                    valid = ~(np.isnan(lo_arr) | np.isnan(hi_arr))
                    if valid.any():
                        ax.fill_between(x[valid], lo_arr[valid], hi_arr[valid],
                                        color=color, alpha=0.08, linewidth=0, zorder=1)
                        ax.plot(x[valid], lo_arr[valid], color=color,
                                linewidth=0.5, alpha=0.35, zorder=2)
                        ax.plot(x[valid], hi_arr[valid], color=color,
                                linewidth=0.5, alpha=0.35, zorder=2)
                ax.plot(x, ssr, "-", color=color, linewidth=1.3,
                        label=METHOD_PRETTY[method], zorder=4)

            # Restored: dashed line only (keep the plot readable)
            ssr_r = rest_entry.get("ssr_curve", [])
            if ssr_r:
                xr = np.arange(len(ssr_r))
                max_d = max(max_d, len(ssr_r))
                ax.plot(xr, ssr_r, "--", color=color_rest, linewidth=1.1,
                        label=METHOD_PRETTY[method] + " (rest.)", zorder=3)

        ax.set_xlim(0, max(12, min(max_d, 25)))
        ax.set_ylim(0, 1.02)
        ax.set_xlabel("Reasoning step depth")
        ax.set_yticks([0, 0.25, 0.5, 0.75, 1.0])
        ax.yaxis.grid(True)
        ax.set_axisbelow(True)
        ax.text(0.98, 0.96, BENCH_PRETTY[bench], transform=ax.transAxes,
                ha="right", va="top", fontsize=7.5, color=GREY_TEXT)

    axes[0].set_ylabel("Step survival rate")

    handles, labels = axes[0].get_legend_handles_labels()
    seen = set()
    uniq = [(h, l) for h, l in zip(handles, labels) if not (l in seen or seen.add(l))]
    if uniq:
        h2, l2 = zip(*uniq)
        fig.legend(h2, l2, loc="lower center", ncol=min(6, len(l2)),
                   bbox_to_anchor=(0.5, -0.09),
                   columnspacing=1.6, handlelength=2.4, handletextpad=0.6)

    fig.savefig(output_path)
    plt.close(fig)
    print(f"  Paper fig 1 saved: {output_path}")


# ---------------------------------------------------------------------------
# Fig 2 — Error counts per 100 problems, stacked (one focus benchmark)
# ---------------------------------------------------------------------------

def fig_paper_2_error_mix(data, primary_model: str, primary_benchmark: str, output_path: str):
    """Single focused panel: errors per 100 problems for the primary
    (model, benchmark), stacked by error type, with quantized vs restored
    bars side-by-side for each method.

    White edges between stack segments (DeepMind/Anthropic style) — no hatching.
    Each pair carries a small Δ annotation showing the post-restoration change
    in total errors, so the reader can see direction at a glance even when
    bar heights look near-identical.
    """
    # Slightly wider canvas so the per-bar variant labels ("Quant.", "Rest.")
    # and the Δ annotations have room without crowding the method names.
    fig, ax = plt.subplots(figsize=(4.2, 2.9), constrained_layout=True)

    x = np.arange(len(METHOD_ORDER), dtype=float)
    width = 0.32
    positions = {
        "":           x - width / 2 - 0.02,
        "_restored":  x + width / 2 + 0.02,
    }

    max_total = 0.0
    totals_by = {}
    for suffix in ("", "_restored"):
        bottoms = np.zeros(len(METHOD_ORDER))
        totals = np.zeros(len(METHOD_ORDER))
        for e_idx, etype in enumerate(ERROR_TYPES):
            heights = []
            for method in METHOD_ORDER:
                q = method + suffix
                entry = data.get((primary_model, q, primary_benchmark)) or {}
                acc = entry.get("accuracy") or 0.0
                dist = entry.get("error_type_dist") or {}
                h = (1 - acc) * 100 * dist.get(etype, 0)
                heights.append(h)
            heights = np.array(heights)
            totals += heights
            ax.bar(positions[suffix], heights, width=width, bottom=bottoms,
                   color=ERROR_COLORS[etype], edgecolor="white", linewidth=0.8,
                   label=etype.capitalize() if suffix == "" else None)
            bottoms += heights
        totals_by[suffix] = totals
        max_total = max(max_total, totals.max())

    # Top-of-bar total labels — show one decimal so a 0.2-pp change isn't
    # rounded into invisibility (the previous "28 / 28" was misleading).
    for suffix in ("", "_restored"):
        for mi, t in enumerate(totals_by[suffix]):
            if t > 0:
                ax.text(positions[suffix][mi], t + max_total * 0.025,
                        f"{t:.1f}",
                        ha="center", va="bottom", fontsize=6.8,
                        color="#222222")

    # Δ annotation centered between each (Quant., Rest.) pair, sitting just
    # above the taller of the two bars. Green ↓ = restoration reduced errors;
    # red ↑ = restoration made it worse. The arrow encodes direction so the
    # reader doesn't have to compare two near-identical heights by eye.
    for mi in range(len(METHOD_ORDER)):
        q_total = totals_by[""][mi]
        r_total = totals_by["_restored"][mi]
        delta = r_total - q_total
        if abs(delta) < 1e-3:
            continue
        # Sit the badge above the column-pair, clear of the per-bar totals.
        y_badge = max(q_total, r_total) + max_total * 0.115
        improved = delta < 0
        arrow = "↓" if improved else "↑"
        color = "#2A9D74" if improved else "#C9534F"
        ax.text(x[mi], y_badge,
                f"{arrow} {abs(delta):.1f}",
                ha="center", va="bottom", fontsize=6.6,
                color=color, fontweight="bold")

    # Sub-label under each bar identifying the variant. Spelled out so the
    # figure is self-contained — "Q" / "R" alone forced the reader to chase
    # an off-figure key.
    for mi, method in enumerate(METHOD_ORDER):
        ax.text(positions[""][mi], -max_total * 0.04, "Quant.",
                ha="center", va="top", fontsize=6.4, color=GREY_TEXT)
        ax.text(positions["_restored"][mi], -max_total * 0.04, "Rest.",
                ha="center", va="top", fontsize=6.4, color=GREY_TEXT)

    ax.set_xticks(x)
    ax.set_xticklabels([METHOD_PRETTY[m] for m in METHOD_ORDER])
    # Extra pad so method labels sit clearly below the Quant./Rest. row.
    ax.tick_params(axis="x", which="major", pad=14)
    # Headroom for the Δ badge above the tallest bar.
    ax.set_ylim(0, max_total * 1.25 + 1)
    ax.set_ylabel("Errors per 100 problems")
    ax.yaxis.grid(True)
    ax.set_axisbelow(True)

    # Right-top panel tag (benchmark + model); keep it small and grey.
    ax.text(0.98, 0.97,
            f"{primary_model} · {BENCH_PRETTY[primary_benchmark]}",
            transform=ax.transAxes, ha="right", va="top",
            fontsize=7, color=GREY_TEXT)

    # Legend: error types beneath the x-axis labels.
    ax.legend(loc="upper center", bbox_to_anchor=(0.5, -0.18),
              ncol=4, handlelength=1.2, columnspacing=1.3, handletextpad=0.5,
              frameon=False)

    fig.savefig(output_path)
    plt.close(fig)
    print(f"  Paper fig 2 saved: {output_path}")


# ---------------------------------------------------------------------------
# Fig 3 — Forest plot of ΔAccuracy
# ---------------------------------------------------------------------------

def fig_paper_3_forest(data, models: List[str], output_path: str):
    """Forest plot: ΔAccuracy with 95% paired-bootstrap CI whiskers.

    One panel per benchmark. Row = (model, method). Marker = filled circle
    4pt, no end-caps on whiskers, zero line solid #999999, single asterisk
    at right of rows where p<.05 with a footnote explaining.
    """
    # Skip any model that has no (base, restored) paired-sig data in any
    # (method, benchmark) cell — otherwise those rows render as empty space
    # inside every panel and make the plot look broken.
    def _has_any_sig(model):
        for method in METHOD_ORDER:
            for bench in BENCHMARKS:
                sig = (data.get((model, method, bench)) or {}).get("sig_vs_restored") or {}
                if sig and sig.get("n_pairs", 0) > 0:
                    return True
        return False

    models = [m for m in models if _has_any_sig(m)]
    if not models:
        print("  [SKIP] fig 3: no paired sig data for any model")
        return

    rows: List[Tuple[str, str]] = [(m, q) for m in models for q in METHOD_ORDER]
    n_rows = len(rows)
    row_height = 0.32
    fig_h = row_height * n_rows + 1.1

    fig, axes = plt.subplots(1, 3, figsize=(6.75, fig_h),
                             sharex=True, sharey=True, constrained_layout=True)

    # Compute shared x range for symmetry about 0.
    all_bounds = []
    for (model, method) in rows:
        for bench in BENCHMARKS:
            sig = (data.get((model, method, bench)) or {}).get("sig_vs_restored") or {}
            if sig and sig.get("n_pairs", 0) > 0:
                lo = sig.get("delta_acc_ci_lo", 0) * 100
                hi = sig.get("delta_acc_ci_hi", 0) * 100
                all_bounds += [lo, hi]
    if all_bounds:
        bound = max(abs(min(all_bounds)), abs(max(all_bounds)))
        xlim = (-bound * 1.12 - 2, bound * 1.12 + 2)
    else:
        xlim = (-20, 20)

    for ax, bench in zip(axes, BENCHMARKS):
        ax.axvline(0, color=GREY_REF, linewidth=0.6, zorder=1)

        for row_idx, (model, method) in enumerate(rows):
            y = n_rows - 1 - row_idx
            entry = data.get((model, method, bench)) or {}
            sig = entry.get("sig_vs_restored") or {}
            if not sig or sig.get("n_pairs", 0) == 0:
                continue

            delta = sig.get("delta_acc_observed", 0) * 100
            lo = sig.get("delta_acc_ci_lo", delta / 100) * 100
            hi = sig.get("delta_acc_ci_hi", delta / 100) * 100
            p = sig.get("p_value")
            color = METHOD_COLOR[method]

            ax.plot([lo, hi], [y, y], color=color, linewidth=1.0, zorder=2, solid_capstyle="butt")
            ax.plot(delta, y, "o", markersize=4, color=color,
                    markeredgewidth=0, zorder=3)

            # Place the sig star just to the right of the CI whisker's high
            # end — visually attached to the data point rather than parked at
            # the panel edge.
            star = sig_mark(p)
            if star:
                ax.text(hi + (xlim[1] - xlim[0]) * 0.02, y, star,
                        va="center", ha="left",
                        fontsize=9, color=color, fontweight="bold")

        # Faint horizontal separators between model blocks.
        for i in range(1, len(models)):
            y_sep = n_rows - i * len(METHOD_ORDER) - 0.5
            ax.axhline(y_sep, color=GREY_LIGHT, linewidth=0.3, zorder=0)

        ax.set_yticks([n_rows - 1 - i for i in range(n_rows)])
        ax.set_yticklabels([METHOD_PRETTY[rows[i][1]] for i in range(n_rows)])
        ax.set_xlim(*xlim)
        ax.xaxis.grid(True)
        ax.set_axisbelow(True)
        ax.set_xlabel(r"$\Delta$Accuracy (pp)")
        # Corner benchmark tag
        ax.text(0.98, 1.0, BENCH_PRETTY[bench], transform=ax.transAxes,
                ha="right", va="bottom", fontsize=7.5, color=GREY_TEXT)

    # Model labels on the left, vertically centered on each model block.
    block = len(METHOD_ORDER)
    for i, model in enumerate(models):
        y_mid = n_rows - 1 - (i * block + (block - 1) / 2)
        axes[0].text(-0.46, y_mid, model,
                     transform=axes[0].get_yaxis_transform(),
                     ha="right", va="center", fontsize=8, color="#222222")

    # Bottom-left significance-key footnote.
    fig.text(0.02, -0.02, r"$*\,p<.05$ (paired bootstrap, 5000 iter.)",
             ha="left", va="top", fontsize=6.5, color=GREY_TEXT)

    fig.savefig(output_path)
    plt.close(fig)
    print(f"  Paper fig 3 saved: {output_path}")


# ---------------------------------------------------------------------------
# Table — LaTeX numerics
# ---------------------------------------------------------------------------

def table_paper_tex(data, models: List[str], output_path: str):
    def fmt_pct(x, ci=None):
        if x is None:
            return "--"
        s = f"{x * 100:.1f}"
        if ci and ci[0] is not None and ci[1] is not None:
            s += f"\\,[{ci[0] * 100:.1f},{ci[1] * 100:.1f}]"
        return s

    def fmt_f(x, ci=None, d=2):
        if x is None or x == float("inf"):
            return "--"
        s = f"{x:.{d}f}"
        if ci and ci[0] is not None and ci[1] is not None:
            s += f"\\,[{ci[0]:.{d}f},{ci[1]:.{d}f}]"
        return s

    def ci_pair(entry, field):
        ci = (entry.get("ci") or {}).get(field)
        if not ci:
            return None
        return ci.get("ci_lo"), ci.get("ci_hi")

    rows = []
    for model in models:
        for bench in BENCHMARKS:
            for method in METHOD_ORDER:
                base = data.get((model, method, bench)) or {}
                rest = data.get((model, method + "_restored", bench)) or {}
                if not base and not rest:
                    continue
                sig = base.get("sig_vs_restored") or {}
                p = sig.get("p_value")
                d_acc_obs = sig.get("delta_acc_observed")

                rows.append({
                    "model": model,
                    "bench": BENCH_PRETTY[bench],
                    "method": METHOD_PRETTY[method],
                    "acc_base": fmt_pct(base.get("accuracy"), ci_pair(base, "accuracy")),
                    "acc_rest": fmt_pct(rest.get("accuracy"), ci_pair(rest, "accuracy")),
                    "d_acc": ("--" if d_acc_obs is None
                              else f"{d_acc_obs * 100:+.1f}{sig_stars_tex(p)}"),
                    "ffs_base": fmt_f(base.get("avg_ffs"), ci_pair(base, "avg_ffs")),
                    "ffs_rest": fmt_f(rest.get("avg_ffs"), ci_pair(rest, "avg_ffs")),
                    "ecr_base": fmt_pct(base.get("ecr"), ci_pair(base, "ecr")),
                    "ecr_rest": fmt_pct(rest.get("ecr"), ci_pair(rest, "ecr")),
                })

    # Wrap the tabular in \resizebox so the table never overflows the text
    # width regardless of how many digits the CIs produce.
    header = (
        "\\begin{table}[t]\n"
        "\\centering\n"
        "\\caption{Per-(model, benchmark, method) results. Point estimates followed by 95\\% bootstrap CIs "
        "in brackets. Accuracy and ECR in \\%, FFS in step index. $\\Delta$Acc is restored~--~base accuracy "
        "(pp); paired-bootstrap significance: $^{*}p<.05$, $^{**}p<.01$, $^{***}p<.001$.}\n"
        "\\label{tab:main}\n"
        "\\resizebox{\\textwidth}{!}{%\n"
        "\\begin{tabular}{@{}lllcccccc@{}}\n"
        "\\toprule\n"
        "Model & Benchmark & Method "
        "& Acc$_\\mathrm{base}$ & Acc$_\\mathrm{rest}$ & $\\Delta$Acc "
        "& FFS$_\\mathrm{base}\\!\\to\\!\\mathrm{rest}$ "
        "& ECR$_\\mathrm{base}\\!\\to\\!\\mathrm{rest}$ \\\\\n"
        "\\midrule\n"
    )

    body_lines = []
    last_model = None
    last_bench = None
    for row in rows:
        model_cell = row["model"] if row["model"] != last_model else ""
        bench_cell = row["bench"] if (row["model"] != last_model or row["bench"] != last_bench) else ""
        if model_cell and last_model is not None:
            body_lines.append("\\addlinespace[2pt]")
        body_lines.append(
            f"{model_cell} & {bench_cell} & {row['method']} "
            f"& {row['acc_base']} & {row['acc_rest']} & {row['d_acc']} "
            f"& {row['ffs_base']}\\,$\\to$\\,{row['ffs_rest']} "
            f"& {row['ecr_base']}\\,$\\to$\\,{row['ecr_rest']} \\\\"
        )
        last_model = row["model"]
        last_bench = row["bench"]

    footer = "\\bottomrule\n\\end{tabular}%\n}\n\\end{table}\n"

    with open(output_path, "w") as f:
        f.write(header + "\n".join(body_lines) + "\n" + footer)
    print(f"  Paper table saved: {output_path}")


# ---------------------------------------------------------------------------
# Per-problem diagnosis loader (used by fig 4 and fig 5)
# ---------------------------------------------------------------------------

def _load_diagnosis(diagnosis_dir: str, model: str, quant: str, benchmark: str) -> List[dict]:
    path = os.path.join(diagnosis_dir, quant, model, f"{benchmark}_run0.jsonl")
    if not os.path.exists(path):
        return []
    out = []
    with open(path) as f:
        for line in f:
            out.append(json.loads(line))
    return out


def _first_failure_step(steps: List[dict]) -> Optional[int]:
    for s in steps:
        if s.get("is_correct") is False:
            return s.get("index")
    return None


def _load_segmented_fp16(segmented_dir: str, model: str, benchmark: str) -> List[dict]:
    path = os.path.join(segmented_dir, "fp16", model, f"{benchmark}_run0.jsonl")
    if not os.path.exists(path):
        return []
    out = []
    with open(path) as f:
        for line in f:
            out.append(json.loads(line))
    return out


# ---------------------------------------------------------------------------
# Fig 0 — Method schematic / pipeline diagram
# ---------------------------------------------------------------------------

def fig_paper_0_pipeline(output_path: str):
    """Method schematic — four coloured stage bands with mini visual
    metaphors (step-dot ribbons, a DTW alignment glyph, an error-type donut,
    metric badges) so the figure summarises the method without needing to
    read the body text.

    Stages:
        1. Generation     — FP16 + quantized CoTs
        2. Diagnosis      — DTW alignment, per-step scoring, step-level metrics
        3. Silver-bullet  — failures sampled across the 4 error types
        4. Restoration    — QLoRA on the quantized base → restored model
    """
    from matplotlib.patches import (FancyBboxPatch, FancyArrowPatch,
                                     Rectangle, Circle, Wedge)

    # Wider, slightly taller canvas so the new mini-visuals breathe.
    fig, ax = plt.subplots(figsize=(8.6, 4.5))
    ax.set_xlim(0, 100)
    ax.set_ylim(2, 74)
    ax.set_axis_off()

    # -------- Palette ------------------------------------------------------
    C_FP16   = METHOD_COLOR["awq_w4"]            # blue
    C_FP16_F = "#EAF0F7"
    C_QUANT  = METHOD_COLOR["gptq_w4"]           # red
    C_QUANT_F = "#FCEDEB"
    C_NEUTRAL  = "#555555"
    C_NEUTRAL_F = "#F3F3F3"
    C_OUT      = METHOD_COLOR["bnb_nf4_w4"]      # green
    C_OUT_F    = "#E8F4EE"
    C_GOOD     = "#5BA56F"                        # correct-step dot fill
    C_BAD      = "#D85C58"                        # failed-step dot fill

    # -------- Stage bands --------------------------------------------------
    # Each band gets a numbered pill at the top instead of a bare "1." text;
    # the pill reads as a stage badge and gives the diagram clearer rhythm.
    stage_bands = [
        ( 0, 27, "1", "Generation",           "#F5F8FC", C_FP16),
        (29, 56, "2", "Diagnosis",            "#F7F7F7", C_NEUTRAL),
        (58, 76, "3", "Silver-bullet",        "#FDF7F0", "#D77C1F"),
        (78, 100, "4", "Restoration",         "#EFF6EF", C_OUT),
    ]
    # Approximate width per character for label sizing so we can centre
    # the (badge + gap + label) group on each band.
    LABEL_FS = 9.5
    CHAR_W   = LABEL_FS * 0.085   # rough conversion from pt to data units
    BADGE_W  = 4.0
    BADGE_GAP = 1.6               # space between pill and label

    for x0, x1, num, label, fc, badge_c in stage_bands:
        ax.add_patch(Rectangle((x0, 4), x1 - x0, 64, linewidth=0,
                               facecolor=fc, zorder=0))
        # Stage badge: a coloured pill (number) + stage name. Centre the
        # whole group on the band so the number sits to the left of the
        # name with a clear gap, no overlap.
        cx = (x0 + x1) / 2
        label_w = len(label) * CHAR_W
        group_w = BADGE_W + BADGE_GAP + label_w
        pill_left = cx - group_w / 2
        ax.add_patch(FancyBboxPatch((pill_left, 69.5), BADGE_W, 3.6,
                                    boxstyle="round,pad=0.05,rounding_size=1.4",
                                    linewidth=0, facecolor=badge_c, zorder=2))
        ax.text(pill_left + BADGE_W / 2, 71.3, num,
                ha="center", va="center",
                fontsize=8.5, color="white", fontweight="bold", zorder=3)
        ax.text(pill_left + BADGE_W + BADGE_GAP, 71.3, label,
                ha="left", va="center",
                fontsize=LABEL_FS, color="#222", fontweight="bold", zorder=3)

    # -------- Helpers ------------------------------------------------------
    TITLE_OFFSET = 3.0
    SUB_TOP_GAP  = 7.5    # raised to clear two-line titles like "Restored\nquant. model"
    LINE_SPACING = 2.8

    def box(x, y, w, h, label, fc=C_NEUTRAL_F, ec=C_NEUTRAL,
            label_fs=8.5, sub_fs=6.8, sub_lines=None,
            label_y_frac=None):
        """Rounded box with top-anchored text. If label_y_frac is given the
        title sits at that fraction of the box height (used when there's a
        mini-visual taking up the lower portion of the box)."""
        p = FancyBboxPatch((x, y), w, h,
                           boxstyle="round,pad=0.02,rounding_size=0.7",
                           linewidth=1.0, edgecolor=ec, facecolor=fc, zorder=2)
        ax.add_patch(p)
        cx = x + w / 2
        y_top = y + h
        if label_y_frac is not None:
            ax.text(cx, y + h * label_y_frac, label,
                    ha="center", va="center",
                    fontsize=label_fs, color="#1A1A1A", zorder=3)
        elif sub_lines:
            ax.text(cx, y_top - TITLE_OFFSET, label, ha="center", va="center",
                    fontsize=label_fs, color="#1A1A1A", zorder=3)
            for i, line in enumerate(sub_lines):
                ax.text(cx, y_top - SUB_TOP_GAP - i * LINE_SPACING, line,
                        ha="center", va="center",
                        fontsize=sub_fs, color=GREY_TEXT, zorder=3)
        else:
            ax.text(cx, y + h / 2, label, ha="center", va="center",
                    fontsize=label_fs, color="#1A1A1A", zorder=3)
        return (x, y, w, h)

    def arrow(src_xy, dst_xy, label=None, rad=0.0, offset=0,
              lw=0.9, color="#444444"):
        a = FancyArrowPatch(src_xy, dst_xy,
                            arrowstyle="->,head_width=3,head_length=4",
                            connectionstyle=f"arc3,rad={rad}",
                            linewidth=lw, color=color, zorder=1,
                            shrinkA=2, shrinkB=2)
        ax.add_patch(a)
        if label:
            mx = (src_xy[0] + dst_xy[0]) / 2
            my = (src_xy[1] + dst_xy[1]) / 2 + offset
            ax.text(mx, my, label, ha="center", va="center",
                    fontsize=6.8, color="#333",
                    bbox=dict(boxstyle="round,pad=0.18",
                              fc="white", ec="none", alpha=0.85),
                    zorder=3)

    def step_dots(cx, cy, n, fail_idx=None, r=0.85, gap=2.4,
                  ok_color=C_GOOD, fail_color=C_BAD,
                  ok_alpha=0.9):
        """A horizontal ribbon of n step-dots centred on (cx, cy). Indices
        in `fail_idx` are drawn in fail_color (with a slightly larger ring)
        to mark erroneous steps."""
        fail_idx = set(fail_idx or [])
        total_w = (n - 1) * gap
        x0 = cx - total_w / 2
        for i in range(n):
            x = x0 + i * gap
            if i in fail_idx:
                ax.add_patch(Circle((x, cy), r * 1.15,
                                    facecolor=fail_color, edgecolor="white",
                                    linewidth=0.7, zorder=4))
            else:
                ax.add_patch(Circle((x, cy), r,
                                    facecolor=ok_color, edgecolor="white",
                                    linewidth=0.6, alpha=ok_alpha, zorder=4))

    # ------------------------------------------------------------------
    # Shared row geometry. Every stage's "top" content is anchored to
    # TOP_Y_TOP/TOP_Y_BOT and every "bottom" content to BOT_Y_TOP/BOT_Y_BOT
    # so the diagram has one clean horizontal rhythm instead of three.
    # ------------------------------------------------------------------
    TOP_Y_BOT = 44      # bottom of the top row
    TOP_Y_TOP = 60      # top of the top row    (height = 16)
    BOT_Y_BOT = 12      # bottom of the bottom row
    BOT_Y_TOP = 36      # top of the bottom row (height = 24, taller for richer content)
    ROW_H_TOP = TOP_Y_TOP - TOP_Y_BOT
    ROW_H_BOT = BOT_Y_TOP - BOT_Y_BOT

    # -------- Stage 1: Generation -----------------------------------------
    # FP16 reference path (top): model → CoT-with-blue-dots
    model_h = 11
    b_fp16_m = box(3, TOP_Y_BOT + (ROW_H_TOP - model_h) / 2, 9, model_h,
                   "FP16\nmodel",
                   fc=C_FP16_F, ec=C_FP16, label_y_frac=0.5)
    b_fp16_t = box(14, TOP_Y_BOT, 12, ROW_H_TOP, "Reference CoT",
                   fc=C_FP16_F, ec=C_FP16, label_y_frac=0.80)
    step_dots(b_fp16_t[0] + b_fp16_t[2] / 2, b_fp16_t[1] + 5.0, n=5,
              ok_color=C_FP16, ok_alpha=0.85)
    ax.text(b_fp16_t[0] + b_fp16_t[2] / 2, b_fp16_t[1] + 2.0,
            "all correct", ha="center", va="center",
            fontsize=6.3, color=GREY_TEXT, style="italic")
    arrow((b_fp16_m[0] + b_fp16_m[2], b_fp16_m[1] + b_fp16_m[3] / 2),
          (b_fp16_t[0], b_fp16_t[1] + b_fp16_t[3] / 2))

    # Quantized candidate path (bottom)
    b_q_m = box(3, BOT_Y_BOT + (ROW_H_BOT - model_h) / 2, 9, model_h,
                "Quantized\nmodel",
                fc=C_QUANT_F, ec=C_QUANT, label_y_frac=0.5)
    b_q_t = box(14, BOT_Y_BOT + (ROW_H_BOT - 16) / 2, 12, 16,
                "Candidate CoT",
                fc=C_QUANT_F, ec=C_QUANT, label_y_frac=0.80)
    # Failed dots get a contrasting white outline to read clearly even when
    # printed in greyscale or at small size.
    step_dots(b_q_t[0] + b_q_t[2] / 2, b_q_t[1] + 5.5, n=5,
              fail_idx={2, 4}, ok_color=C_QUANT, ok_alpha=0.40,
              fail_color=C_BAD)
    ax.text(b_q_t[0] + b_q_t[2] / 2, b_q_t[1] + 2.5,
            "AWQ / GPTQ / BnB", ha="center", va="center",
            fontsize=6.3, color=GREY_TEXT, style="italic")
    arrow((b_q_m[0] + b_q_m[2], b_q_m[1] + b_q_m[3] / 2),
          (b_q_t[0], b_q_t[1] + b_q_t[3] / 2))

    # -------- Stage 2: Diagnosis ------------------------------------------
    # DTW alignment box: top row, two rows of dots with pairing lines.
    b_align = box(31, TOP_Y_BOT, 24, ROW_H_TOP, "DTW step alignment",
                  fc=C_NEUTRAL_F, ec=C_NEUTRAL, label_y_frac=0.82)
    ax_cx = b_align[0] + b_align[2] / 2
    top_y = b_align[1] + 7.5
    bot_y = b_align[1] + 3.0
    ref_xs  = [ax_cx - 8 + i * 4 for i in range(5)]
    cand_xs = [ax_cx - 8 + i * 4 for i in range(5)]
    for x in ref_xs:
        ax.add_patch(Circle((x, top_y), 0.75, facecolor=C_FP16,
                            edgecolor="white", linewidth=0.5, zorder=4))
    for i, x in enumerate(cand_xs):
        col = C_BAD if i in (2, 4) else C_QUANT
        ax.add_patch(Circle((x, bot_y), 0.85, facecolor=col,
                            edgecolor="white", linewidth=0.5, zorder=4))
    # Pairing lines. One non-monotone pairing (ref-3 ↔ cand-2) demonstrates
    # warping; that's the whole reason DTW is used over index matching.
    pairings = [(0, 0), (1, 1), (2, 2), (3, 2), (4, 3), (4, 4)]
    for r_i, c_i in pairings:
        a = FancyArrowPatch((ref_xs[r_i], top_y - 0.7),
                            (cand_xs[c_i], bot_y + 0.7),
                            arrowstyle="-",
                            connectionstyle="arc3,rad=0.0",
                            linewidth=0.5, color="#888888", zorder=3,
                            shrinkA=0, shrinkB=0)
        ax.add_patch(a)

    # Per-step scoring box: bottom row, taller. Layout from top to bottom:
    #   1) title
    #   2) "is_correct + error_type" subtitle
    #   3) horizontal swatch+label legend (label below swatch — conventional)
    #   4) the FFS / ECR / SSR metric pills, anchored INSIDE the box (was
    #      floating below before)
    b_score = box(31, BOT_Y_BOT, 24, ROW_H_BOT, "Per-step scoring",
                  fc=C_NEUTRAL_F, ec=C_NEUTRAL, label_y_frac=0.88)
    sw_cx = b_score[0] + b_score[2] / 2
    ax.text(sw_cx, b_score[1] + ROW_H_BOT * 0.74,
            "is_correct  +  error_type", ha="center", va="center",
            fontsize=6.8, color=GREY_TEXT, style="italic")
    # Swatch row (chip on top, label below).
    swatch_y       = b_score[1] + ROW_H_BOT * 0.52
    swatch_label_y = b_score[1] + ROW_H_BOT * 0.40
    et_labels = ["concept.", "method.", "execut.", "logical"]
    sw_step = 5.4
    for i, et in enumerate(ERROR_TYPES):
        sx = sw_cx + (i - 1.5) * sw_step
        ax.add_patch(FancyBboxPatch((sx - 1.6, swatch_y - 1.1), 3.2, 2.2,
                                    boxstyle="round,pad=0.02,rounding_size=0.6",
                                    linewidth=0, facecolor=ERROR_COLORS[et],
                                    zorder=4))
        ax.text(sx, swatch_label_y, et_labels[i],
                ha="center", va="center",
                fontsize=6.0, color="#333", zorder=4)

    # Metric pills, ANCHORED inside the scoring box (no longer floating).
    # Small "yields →" tag on the left makes the relationship explicit.
    metric_y = b_score[1] + ROW_H_BOT * 0.18
    metric_h = 3.6
    metric_w = 4.8
    metric_gap = 1.2
    metric_specs = [("FFS", "#4E79A7"),
                    ("ECR", "#E15759"),
                    ("SSR", "#59A14F")]
    n_m = len(metric_specs)
    total_metric_w = n_m * metric_w + (n_m - 1) * metric_gap
    yields_w = 6.5
    group_left = sw_cx - (total_metric_w + yields_w) / 2 + yields_w
    ax.text(group_left - 1.0, metric_y, "yields →",
            ha="right", va="center", fontsize=6.5, color=GREY_TEXT,
            style="italic", zorder=4)
    for i, (name, col) in enumerate(metric_specs):
        sx = group_left + i * (metric_w + metric_gap) + metric_w / 2
        ax.add_patch(FancyBboxPatch((sx - metric_w / 2, metric_y - metric_h / 2),
                                    metric_w, metric_h,
                                    boxstyle="round,pad=0.05,rounding_size=1.4",
                                    linewidth=0, facecolor=col, alpha=0.92,
                                    zorder=4))
        ax.text(sx, metric_y, name, ha="center", va="center",
                fontsize=7.5, color="white", fontweight="bold", zorder=5)

    # Stage 1 → Stage 2 arrows.
    arrow((b_fp16_t[0] + b_fp16_t[2], b_fp16_t[1] + b_fp16_t[3] / 2),
          (b_align[0], b_align[1] + b_align[3] * 0.55),
          label="ref.", offset=1.5)
    arrow((b_q_t[0] + b_q_t[2], b_q_t[1] + b_q_t[3] / 2),
          (b_score[0], b_score[1] + b_score[3] * 0.65),
          label="cand.", offset=-1.5)
    # Internal alignment → scoring arrow (carries DTW pairs to the scorer).
    arrow((b_align[0] + b_align[2] / 2, b_align[1]),
          (b_score[0] + b_score[2] / 2, b_score[1] + b_score[3]),
          rad=0.0, label="pairs", offset=0)

    # -------- Stage 3: Silver-bullet construction -------------------------
    # A compact box centred in the band (between the two rows) — previous
    # version spanned the full band height which left ~28 units of empty
    # space. The 4-chip strip honestly conveys "stratified by error type"
    # without implying equal-quartile sampling (the donut+"4×" did).
    b_filter_x, b_filter_w = 60, 14
    b_filter_h = 30
    band_mid_y = (BOT_Y_BOT + TOP_Y_TOP) / 2
    b_filter_y = band_mid_y - b_filter_h / 2
    box(b_filter_x, b_filter_y, b_filter_w, b_filter_h, "Silver-bullet\ndataset",
        fc="#FFF2E5", ec="#D77C1F", label_y_frac=0.83)

    chip_y = b_filter_y + b_filter_h * 0.48
    chip_w = 2.4; chip_h = 2.4; chip_gap = 0.8
    chip_total_w = 4 * chip_w + 3 * chip_gap
    chip_left = b_filter_x + b_filter_w / 2 - chip_total_w / 2
    for i, et in enumerate(ERROR_TYPES):
        ax.add_patch(FancyBboxPatch((chip_left + i * (chip_w + chip_gap),
                                     chip_y - chip_h / 2),
                                    chip_w, chip_h,
                                    boxstyle="round,pad=0.02,rounding_size=0.6",
                                    linewidth=0,
                                    facecolor=ERROR_COLORS[et], zorder=4))
    ax.text(b_filter_x + b_filter_w / 2, chip_y + chip_h / 2 + 1.8,
            "stratified by", ha="center", va="center",
            fontsize=6.4, color=GREY_TEXT, style="italic")
    ax.text(b_filter_x + b_filter_w / 2, chip_y - chip_h / 2 - 1.8,
            "error type", ha="center", va="center",
            fontsize=6.4, color=GREY_TEXT, style="italic")
    ax.text(b_filter_x + b_filter_w / 2, b_filter_y + b_filter_h * 0.13,
            "$N\\!\\leq\\!500$ failed problems",
            ha="center", va="center",
            fontsize=6.5, color=GREY_TEXT)

    # Stage 2 → Stage 3: scoring box (bottom row) → silver-bullet (centre).
    # Source from the scoring box's upper-right; target the box's left
    # edge mid-height. Keeps the arrow in clear whitespace above the chips.
    arrow((b_score[0] + b_score[2], b_score[1] + b_score[3] * 0.78),
          (b_filter_x, b_filter_y + b_filter_h * 0.50),
          label="scored\nsteps", offset=0)

    # -------- Stage 4: Restoration ----------------------------------------
    # Top-row QLoRA box anchored to the same TOP row as Stage 1/2.
    b_qlora = box(79, TOP_Y_BOT, 19, ROW_H_TOP, "QLoRA fine-tune",
                  sub_lines=["rank 16,  $\\alpha\\!=\\!32$",
                             "on quantized base",
                             "$<\\!0.4\\%$ trainable"],
                  fc=C_OUT_F, ec=C_OUT)
    # The arrow itself enters the middle of the QLoRA box, but its mid-point
    # label is offset upward so it sits between the box top and the first
    # sub-line — otherwise the label crashed into the "<0.4% trainable"
    # text in the QLoRA box (same y-range, both rendered, looked merged).
    arrow((b_filter_x + b_filter_w, b_filter_y + b_filter_h * 0.65),
          (b_qlora[0], b_qlora[1] + b_qlora[3] * 0.5),
          label="train set", offset=7)

    # Bottom-row Restored model box anchored to the same BOT row.
    b_out = box(79, BOT_Y_BOT, 19, ROW_H_BOT, "Restored\nquant. model",
                sub_lines=["adapter merged,",
                           "re-quantized"],
                fc=C_OUT_F, ec=C_OUT)
    arrow((b_qlora[0] + b_qlora[2] / 2, b_qlora[1]),
          (b_out[0] + b_out[2] / 2, b_out[1] + b_out[3]),
          label="adapter", offset=0)

    fig.tight_layout()
    fig.savefig(output_path)
    plt.close(fig)
    print(f"  Paper fig 0 saved: {output_path}")


# ---------------------------------------------------------------------------
# Fig 4 — FFS distribution per method (base vs restored overlay)
# ---------------------------------------------------------------------------

def fig_paper_4_ffs_distribution(diagnosis_dir: str, primary_model: str,
                                 primary_benchmark: str, output_path: str):
    """3 small-multiple panels, one per quantization method. Each panel shows
    the FFS histogram — base (solid fill) vs restored (outlined) — for
    problems that failed. Bin edges chosen to resolve the dominant 0-5 range
    and then lump 6+."""
    # Slightly taller than before so the legend can sit under the
    # shared x-axis labels without colliding with them.
    fig, axes = plt.subplots(1, 3, figsize=(6.75, 2.55),
                             sharey=True, constrained_layout=False)
    fig.subplots_adjust(left=0.08, right=0.99, top=0.88, bottom=0.32,
                        wspace=0.12)

    # Wider buckets in the tail — the data is effectively zero beyond step 5,
    # so lumping 6+ into a single "6+" bucket avoids the overlapping multi-char
    # labels that "6-10 / 11-20 / 21+" produced at this figure width.
    bin_edges = np.array([0, 1, 2, 3, 4, 5, 6, 31])
    bin_labels = ["0", "1", "2", "3", "4", "5", "6+"]

    for ax, method in zip(axes, METHOD_ORDER):
        base_traces = _load_diagnosis(diagnosis_dir, primary_model, method, primary_benchmark)
        rest_traces = _load_diagnosis(diagnosis_dir, primary_model, method + "_restored", primary_benchmark)

        def ffs_vec(traces):
            vals = []
            for t in traces:
                f = _first_failure_step(t.get("steps", []) or [])
                if f is not None:
                    vals.append(f)
            return np.array(vals)

        base_ffs = ffs_vec(base_traces)
        rest_ffs = ffs_vec(rest_traces)

        base_h, _ = np.histogram(base_ffs, bins=bin_edges)
        rest_h, _ = np.histogram(rest_ffs, bins=bin_edges)

        x = np.arange(len(bin_labels))
        width = 0.38
        color = METHOD_COLOR[method]
        color_rest = METHOD_COLOR[method + "_restored"]

        ax.bar(x - width / 2, base_h, width=width, color=color,
               label="Quantized", edgecolor="white", linewidth=0.6)
        ax.bar(x + width / 2, rest_h, width=width, facecolor="none",
               edgecolor=color, linewidth=1.0, label="Restored")

        ax.set_xticks(x)
        ax.set_xticklabels(bin_labels)
        ax.yaxis.grid(True)
        ax.set_axisbelow(True)
        ax.set_xlabel("First failure step")
        ax.text(0.98, 0.96, METHOD_PRETTY[method], transform=ax.transAxes,
                ha="right", va="top", fontsize=7.5, color=GREY_TEXT)

    axes[0].set_ylabel("Failed problems")

    # Shared legend — anchored below the x-axis labels (there is now
    # explicit bottom padding via subplots_adjust) so it cannot overlap
    # the per-panel "First failure step" captions.
    handles = [
        plt.Rectangle((0, 0), 1, 1, facecolor=GREY_TEXT, edgecolor="white",
                      linewidth=0.6, label="Quantized"),
        plt.Rectangle((0, 0), 1, 1, facecolor="none", edgecolor=GREY_TEXT,
                      linewidth=1.0, label="Restored"),
    ]
    fig.legend(handles=handles, loc="lower center",
               bbox_to_anchor=(0.5, 0.02),
               ncol=2, handlelength=1.6, handletextpad=0.5, columnspacing=1.6,
               frameon=False)

    # Subtitle-style note at top-left
    fig.text(0.01, 0.95, f"{primary_model} · {BENCH_PRETTY[primary_benchmark]}",
             ha="left", va="bottom", fontsize=7, color=GREY_TEXT)

    fig.savefig(output_path)
    plt.close(fig)
    print(f"  Paper fig 4 saved: {output_path}")


# ---------------------------------------------------------------------------
# Fig 5 — Qualitative trace example (FP16 vs quantized, diagnosed)
# ---------------------------------------------------------------------------

def fig_paper_5_trace_example(diagnosis_dir: str, segmented_dir: str,
                              primary_model: str, primary_benchmark: str,
                              output_path: str,
                              method: str = "gptq_w4",
                              problem_id: str = "math500_12",
                              n_steps_to_show: int = 4):
    """Side-by-side diagnosed trace: FP16 reference (left) vs quantized
    candidate (right), with explicit visual encodings of the diagnosis the
    paper claims to produce:

        • per-step ✓ / ✗ status badges in the gutter
        • a "First Failure Step" callout band on the row of the very first
          quantized failure (FFS = the headline metric of the paper)
        • subtle horizontal alignment ribbons in the inter-column gap that
          echo the DTW pairing depicted in fig 0
        • error-type chip embedded in the failing box (same colour palette
          as figs 0/2/12, so the figure stays consistent across the paper)
    """
    import textwrap
    from matplotlib.patches import FancyBboxPatch as _FBPatch

    quant_traces = _load_diagnosis(diagnosis_dir, primary_model, method, primary_benchmark)
    fp16_traces  = _load_segmented_fp16(segmented_dir, primary_model, primary_benchmark)

    fp16 = next((t for t in fp16_traces  if t.get("problem_id") == problem_id), None)
    qnt  = next((t for t in quant_traces if t.get("problem_id") == problem_id), None)
    if not fp16 or not qnt:
        print(f"  [SKIP] Missing traces for {problem_id}")
        return

    # The segmented/diagnosis JSONLs don't carry the question text; pull it
    # from the inference output (which has the original prompt).
    def _load_question(quant_subdir: str) -> Optional[str]:
        path = os.path.join("results/inference", quant_subdir, primary_model,
                            f"{primary_benchmark}_run0.jsonl")
        if not os.path.exists(path):
            return None
        with open(path) as f:
            for line in f:
                row = json.loads(line)
                if row.get("problem_id") == problem_id:
                    return row.get("question") or row.get("problem_text")
        return None

    question_text = (_load_question("fp16") or _load_question(method) or "")

    fp16_steps = (fp16.get("steps") or [])[:n_steps_to_show]
    qnt_steps  = (qnt.get("steps")  or [])[:n_steps_to_show]

    # First-failure-step index (in the quantized trace). The visual callout
    # is anchored on the row that matches this step. None ⇒ no callout.
    ffs = _first_failure_step(qnt_steps)

    # ------------------------------------------------------------------
    # Pre-wrap both columns. Wrap width and line cap are both small enough
    # that the inter-column gap doesn't get squeezed (we now reserve a
    # 14%-wide gutter for the alignment ribbon + ✓/✗ badges).
    # ------------------------------------------------------------------
    # WRAP_W tuned for the new 7.4" canvas with 0.18-ratio gutter:
    # ~47 chars fit per line at 8pt. MAX_LINES=6 so a typical 240-260 char
    # step renders as full prose (no "[…]" marker) — earlier 5-line cap
    # produced bogus "[…]" tails on steps whose text would otherwise fit.
    WRAP_W   = 50
    MAX_LINES = 6

    def _prewrap(steps):
        out = []
        for s in steps:
            text = _truncate(s.get("text", ""), WRAP_W * MAX_LINES)
            lines = textwrap.wrap(text, width=WRAP_W) or [""]
            if len(lines) > MAX_LINES:
                lines = lines[:MAX_LINES]
                # End on whole-word boundary then append the ellipsis as a
                # separate visual marker, so it reads as "(continues)" not
                # as a typo.
                lines[-1] = lines[-1].rstrip() + " […]"
            out.append({"lines": lines, "s": s})
        return out

    wl = _prewrap(fp16_steps)
    wr = _prewrap(qnt_steps)
    n_rows = max(len(wl), len(wr))
    while len(wl) < n_rows: wl.append(None)
    while len(wr) < n_rows: wr.append(None)

    row_lines = [
        max((len(wl[i]["lines"]) if wl[i] else 0),
            (len(wr[i]["lines"]) if wr[i] else 0))
        for i in range(n_rows)
    ]
    row_units = [lc + 1.0 for lc in row_lines]
    total_units = sum(row_units) + (n_rows - 1) * 0.4

    LINE_INCH = 0.165
    CONTENT_IN = total_units * LINE_INCH
    if question_text:
        q_lines = max(1, min(4, len(textwrap.wrap(question_text, width=110))))
        HEADER_IN = 0.55 + 0.16 * q_lines
    else:
        HEADER_IN = 0.60
    FOOTER_IN = 0.32
    fig_h = HEADER_IN + CONTENT_IN + FOOTER_IN
    fig_w = 7.4   # +0.4" wider than the previous version to give the
                  # alignment-ribbon gutter and ✓/✗ badges proper breathing room

    fig = plt.figure(figsize=(fig_w, fig_h))
    top_frac    = 1.0 - HEADER_IN / fig_h
    bottom_frac = FOOTER_IN / fig_h

    # Three-column gridspec: [left text]  [centre gutter]  [right text].
    # The centre gutter axis hosts ✓/✗ status badges, the alignment ribbon
    # connecting paired rows, and the FFS callout marker — all live in the
    # same coordinate space so they line up perfectly with the rows.
    gs = fig.add_gridspec(1, 3,
                          width_ratios=[1.0, 0.18, 1.0],
                          wspace=0.0,
                          left=0.02, right=0.98,
                          top=top_frac, bottom=bottom_frac)
    ax_l = fig.add_subplot(gs[0, 0]); ax_l.set_axis_off()
    ax_g = fig.add_subplot(gs[0, 1]); ax_g.set_axis_off()
    ax_r = fig.add_subplot(gs[0, 2]); ax_r.set_axis_off()
    ax_g.set_xlim(0, 1); ax_g.set_ylim(0, 1)

    # ----- Problem header -------------------------------------------------
    if question_text:
        problem_wrap = textwrap.fill(_truncate(question_text, 320), width=110)
        fig.text(0.5, 1.0 - 0.10 / fig_h, problem_wrap,
                 ha="center", va="top", fontsize=7.5, color="#222222",
                 bbox=dict(boxstyle="round,pad=0.5", fc="#F4F6F9",
                           ec="#B7C1CE", lw=0.7))

    # ----- Column headers -------------------------------------------------
    ax_l.text(0.5, 1.015, "FP16 reference", transform=ax_l.transAxes,
              ha="center", va="bottom", fontsize=9,
              color=METHOD_COLOR["awq_w4"], fontweight="bold")
    ax_r.text(0.5, 1.015, f"{METHOD_PRETTY[method]} (quantized)",
              transform=ax_r.transAxes, ha="center", va="bottom",
              fontsize=9, color=METHOD_COLOR[method], fontweight="bold")
    # Gutter sub-header — spelled out instead of "diag." abbreviation, so
    # the figure stays self-explanatory to a reader who hasn't read §3 yet.
    ax_g.text(0.5, 1.015, "verdict", transform=ax_g.transAxes,
              ha="center", va="bottom", fontsize=7.5,
              color=GREY_TEXT, style="italic")

    # ----- Shared y-grid --------------------------------------------------
    y_top_axes = 0.985
    y_bot_axes = 0.015
    avail = y_top_axes - y_bot_axes
    unit  = avail / max(total_units, 1)

    row_y_top = []
    row_y_center = []
    row_y_bot = []
    y_cursor = y_top_axes
    for i in range(n_rows):
        block_h = row_units[i] * unit
        y_top = y_cursor
        y_cursor -= block_h
        y_center = (y_top + y_cursor) / 2 + unit * 0.20
        row_y_top.append(y_top)
        row_y_center.append(y_center)
        row_y_bot.append(y_cursor)
        if i < n_rows - 1:
            y_cursor -= 0.4 * unit

    # ------------------------------------------------------------------
    # Render each column. Step badges (the small numbered circle) sit in
    # the body axes' left margin; ✓ / ✗ status icons sit in the GUTTER
    # axis so they read as a per-row diagnosis verdict, independent of
    # either text column.
    # ------------------------------------------------------------------
    def render(ax, wrapped_rows, accent_color, is_quant):
        for i, w in enumerate(wrapped_rows):
            if w is None:
                continue
            y_center = row_y_center[i]
            is_correct = w["s"].get("is_correct", True)
            err_type   = w["s"].get("error_type") or ""
            is_fail    = is_quant and (is_correct is False)

            if is_fail:
                ec = ERROR_COLORS.get(err_type, "#E76F51")
                fc = "#FFF7F4"
                lw = 1.2
            else:
                ec = "#D6D9DD"
                fc = "#FAFBFC" if is_quant else "#F6FAF7"
                lw = 0.5

            # Numbered step badge in the column's left margin.
            ax.text(0.005, y_center, f"{i}",
                    transform=ax.transAxes, va="center", ha="left",
                    fontsize=8.5, color=accent_color, fontweight="bold",
                    bbox=dict(boxstyle="circle,pad=0.25",
                              fc="white", ec=accent_color, lw=0.9))

            # Step body.
            body = "\n".join(w["lines"])
            ax.text(0.07, y_center, body,
                    transform=ax.transAxes, va="center", ha="left",
                    fontsize=8, color="#222222",
                    bbox=dict(boxstyle="round,pad=0.5",
                              fc=fc, ec=ec, lw=lw))

            # Error-type chip inline at the bottom-right of the failing box.
            if is_fail and err_type:
                ax.text(0.985, y_center - (row_lines[i] * 0.5 - 0.5) * unit,
                        err_type,
                        transform=ax.transAxes, va="top", ha="right",
                        fontsize=6.5, color="white",
                        bbox=dict(boxstyle="round,pad=0.28",
                                  fc=ERROR_COLORS.get(err_type, "#E76F51"),
                                  ec="none"))

    render(ax_l, wl, METHOD_COLOR["awq_w4"], is_quant=False)
    render(ax_r, wr, METHOD_COLOR[method],   is_quant=True)

    # ------------------------------------------------------------------
    # Gutter visualisations: alignment ribbon + ✓ / ✗ status icons.
    # ------------------------------------------------------------------
    OK_COLOR   = "#3CA56F"
    FAIL_COLOR = "#D85C58"
    for i in range(n_rows):
        if wl[i] is None or wr[i] is None:
            continue
        yc = row_y_center[i]
        # Thin alignment ribbon spanning the gutter — echoes DTW pairing.
        ax_g.plot([0.05, 0.95], [yc, yc], color="#C6CCD3",
                  linewidth=0.6, zorder=1)

        # Per-row verdict from the quantized side (the FP16 trace is taken
        # as ground truth in this figure, so its ✓ is implicit).
        is_correct_q = wr[i]["s"].get("is_correct", True)
        is_fail_q    = is_correct_q is False
        glyph = "✗" if is_fail_q else "✓"
        gcol  = FAIL_COLOR if is_fail_q else OK_COLOR
        # White-ringed pill for the verdict, sized to read at a glance.
        ax_g.text(0.5, yc, glyph, transform=ax_g.transAxes,
                  ha="center", va="center",
                  fontsize=8.5, color="white", fontweight="bold",
                  bbox=dict(boxstyle="circle,pad=0.30",
                            fc=gcol, ec="white", lw=1.0),
                  zorder=4)

    # ------------------------------------------------------------------
    # First Failure Step callout. Anchored to the FFS row, sits in the
    # left-most margin of the figure (left of the FP16 column) and points
    # right toward the failing row. This is the central concept of the
    # paper, so we make it visually unmissable without disrupting layout.
    # ------------------------------------------------------------------
    if ffs is not None and 0 <= ffs < n_rows:
        yc = row_y_center[ffs]
        from matplotlib.patches import Rectangle as _Rect
        # Yellow-tinted band the full row width. Slightly stronger fill
        # (alpha 0.75 + thin amber edge) than the previous 0.55-alpha tint,
        # which read too faintly in print.
        band_h_axes = max(row_lines[ffs] * 0.55 * unit, 0.030)
        band_y_fig  = bottom_frac + (yc - band_h_axes / 2) * (top_frac - bottom_frac)
        band_h_fig  = band_h_axes * (top_frac - bottom_frac)
        fig.add_artist(_Rect((0.02, band_y_fig), 0.96, band_h_fig,
                             facecolor="#FFF1B5", edgecolor="#E5C46A",
                             linewidth=0.5, alpha=0.75, zorder=0))
        # FFS pill in the gutter axis itself (NOT the figure margin), so
        # it sits cleanly above the verdict pill of that row, doesn't
        # collide with the FP16 column's left edge, and inherits the
        # gutter's coordinate space so it tracks row layout exactly.
        ax_g.text(0.5, yc + band_h_axes * 0.55,
                  "first failure step",
                  transform=ax_g.transAxes,
                  ha="center", va="bottom",
                  fontsize=6.5, color="#7A5A0F", fontweight="bold",
                  bbox=dict(boxstyle="round,pad=0.30",
                            fc="#FFE066", ec="#D4A516", lw=0.6),
                  zorder=5)

    # ----- Footer caption -------------------------------------------------
    fig.text(0.02, FOOTER_IN / fig_h * 0.4,
             f"Problem: {problem_id}   ·   Model: {primary_model}   ·   "
             f"Method: {METHOD_PRETTY[method]}",
             ha="left", va="center", fontsize=6.8, color=GREY_TEXT)
    # Inline legend at the right side of the footer. Removed the FFS
    # entry because the visible "first failure step" yellow pill already
    # serves as its own legend, and listing a "░" pattern character that
    # didn't match the actual yellow-band marker was actively misleading.
    fig.text(0.98, FOOTER_IN / fig_h * 0.4,
             "✓ correct step    ✗ failed step",
             ha="right", va="center", fontsize=6.8, color=GREY_TEXT)

    fig.savefig(output_path)
    plt.close(fig)
    print(f"  Paper fig 5 saved: {output_path}")


def _truncate(s: str, n: int) -> str:
    s = (s or "").replace("\n", " ").strip()
    return s if len(s) <= n else s[:n - 1].rstrip() + "…"


# ---------------------------------------------------------------------------
# Fig 11 — Correlation between the novel metrics
# ---------------------------------------------------------------------------

def fig_paper_11_metric_correlation(data, output_path: str):
    """Pearson correlation between (Accuracy, FFS, ECR, avg_token_count)
    computed across all (model, benchmark, quant) cells. If all four were
    redundant the matrix would be near-perfect 1s; non-trivial off-diagonals
    justify the 3-metric framework as a strict extension of accuracy alone.
    """
    fields = ["accuracy", "avg_ffs", "median_ffs", "ecr"]
    labels = ["Accuracy", "Avg FFS", "Median FFS", "ECR"]

    rows = []
    for (model, quant, bench), entry in data.items():
        row = [entry.get(f) for f in fields]
        if any(v is None or (isinstance(v, float) and (v != v)) for v in row):
            continue
        rows.append(row)
    if not rows:
        print("  [SKIP] fig 11: no complete rows to correlate")
        return

    arr = np.array(rows, dtype=float)
    # Guard against fields that are all identical / all NaN (would nan out corr)
    corr = np.corrcoef(arr.T)

    fig, ax = plt.subplots(figsize=(3.5, 3.0), constrained_layout=True)
    im = ax.imshow(corr, cmap="RdBu_r", vmin=-1, vmax=1, aspect="auto")

    for i in range(len(fields)):
        for j in range(len(fields)):
            c = "white" if abs(corr[i, j]) > 0.6 else "#222"
            ax.text(j, i, f"{corr[i, j]:.2f}", ha="center", va="center",
                    fontsize=8, color=c)

    ax.set_xticks(range(len(fields)))
    ax.set_yticks(range(len(fields)))
    ax.set_xticklabels(labels, rotation=20, ha="right")
    ax.set_yticklabels(labels)

    cbar = plt.colorbar(im, ax=ax, fraction=0.046, pad=0.04,
                        ticks=[-1, -0.5, 0, 0.5, 1])
    cbar.ax.tick_params(labelsize=7)
    cbar.set_label("Pearson r", fontsize=8)

    ax.text(1.0, 1.05,
            f"N = {len(rows)} cells (model × benchmark × quant)",
            transform=ax.transAxes, ha="right", va="bottom",
            fontsize=7, color=GREY_TEXT)

    fig.savefig(output_path)
    plt.close(fig)
    print(f"  Paper fig 11 saved: {output_path}")


# ---------------------------------------------------------------------------
# Fig 12 — Error-type × step-depth heatmap
# ---------------------------------------------------------------------------

def fig_paper_12_error_x_depth(diagnosis_dir: str, primary_model: str,
                                primary_benchmark: str, output_path: str,
                                max_depth: int = 15):
    """For the primary (model, benchmark), pool failed steps from all three
    base quantization methods and build a heatmap P(error_type | depth).

    Reads: for each quant method's diagnosis jsonl, every step with
    `is_correct == False` gets counted at its `index` under its `error_type`.
    Rows are error types, columns are step depths 0..max_depth-1. Cells are
    fraction of errors at that depth that have this type (columns sum to 1).

    Per-step error-type labels: this figure is rendered from the LLM-judge
    re-classification (results/diagnosis_llm/) when available, matching the
    aggregate distribution reported in §5.4 and the convention announced in
    §3.5. Falls back to the rule-based diagnosis directory only if the
    LLM-judge directory is missing for the primary cell.
    """
    counts = np.zeros((len(ERROR_TYPES), max_depth), dtype=float)

    # Prefer LLM-judge labels for the primary cell; fall back to rule-based
    # diagnosis directory if no LLM-judge re-classification was run.
    llm_root = os.path.join(os.path.dirname(diagnosis_dir.rstrip("/")),
                            "diagnosis_llm")
    primary_dir = llm_root if os.path.isdir(llm_root) else diagnosis_dir

    for method in METHOD_ORDER:
        traces = _load_diagnosis(primary_dir, primary_model, method, primary_benchmark)
        for t in traces:
            for s in (t.get("steps") or []):
                if s.get("is_correct") is not False:
                    continue
                d = s.get("index", 0)
                et = s.get("error_type")
                if et in ERROR_TYPES and 0 <= d < max_depth:
                    counts[ERROR_TYPES.index(et), d] += 1

    col_sums = counts.sum(axis=0, keepdims=True)
    with np.errstate(invalid="ignore", divide="ignore"):
        prop = np.where(col_sums > 0, counts / col_sums, np.nan)

    fig, ax = plt.subplots(figsize=(6.75, 2.3), constrained_layout=True)
    im = ax.imshow(prop, cmap="YlOrRd", aspect="auto", vmin=0, vmax=1)

    ax.set_xticks(range(max_depth))
    ax.set_xticklabels(range(max_depth))
    ax.set_yticks(range(len(ERROR_TYPES)))
    ax.set_yticklabels([e.capitalize() for e in ERROR_TYPES])
    ax.set_xlabel("Step depth")

    for i in range(len(ERROR_TYPES)):
        for j in range(max_depth):
            v = prop[i, j]
            if np.isnan(v):
                continue
            c = "white" if v > 0.5 else "#222"
            ax.text(j, i, f"{v:.0%}" if v >= 0.05 else "",
                    ha="center", va="center", fontsize=6.5, color=c)

    # Per-column total count, annotated on top (how many errors are at that depth).
    col_totals = counts.sum(axis=0).astype(int)
    for j, n in enumerate(col_totals):
        ax.text(j, -0.8, str(n), ha="center", va="center", fontsize=6.3, color=GREY_TEXT)
    ax.text(-0.6, -0.8, "$n$=", ha="right", va="center", fontsize=6.3, color=GREY_TEXT)

    cbar = plt.colorbar(im, ax=ax, fraction=0.035, pad=0.02,
                        ticks=[0, 0.25, 0.5, 0.75, 1])
    cbar.ax.tick_params(labelsize=7)
    cbar.set_label("Fraction of errors at that depth", fontsize=7.5)

    # Metadata tag on the colorbar axis (empty space there) so it doesn't
    # collide with the "n=" counts row sitting at y = -0.8 inside this axes.
    cbar.ax.text(0.5, 1.06,
                 f"{primary_model} · {BENCH_PRETTY[primary_benchmark]}",
                 transform=cbar.ax.transAxes, ha="center", va="bottom",
                 fontsize=7.5, color=GREY_TEXT)

    fig.savefig(output_path)
    plt.close(fig)
    print(f"  Paper fig 12 saved: {output_path}")


# ---------------------------------------------------------------------------
# Fig 13 — Error-type reduction after restoration (slopegraph)
# ---------------------------------------------------------------------------

def fig_paper_13_error_reduction(data, primary_model: str,
                                  primary_benchmark: str, output_path: str):
    """Slopegraph: for each (method, error_type), draw a line from the
    pre-restoration error rate (per 100 problems) to the post-restoration
    rate. Lines that slope down = restoration reduced that error type;
    lines that slope up = restoration made it worse. Side-by-side panels
    per quantization method keep the reader from confusing families.
    """
    fig, axes = plt.subplots(1, len(METHOD_ORDER),
                              figsize=(6.75, 2.6), sharey=True,
                              constrained_layout=True)
    if len(METHOD_ORDER) == 1:
        axes = [axes]

    for ax, method in zip(axes, METHOD_ORDER):
        base = data.get((primary_model, method, primary_benchmark)) or {}
        rest = data.get((primary_model, method + "_restored", primary_benchmark)) or {}

        base_acc = base.get("accuracy") or 0.0
        rest_acc = rest.get("accuracy") or 0.0
        base_dist = base.get("error_type_dist") or {}
        rest_dist = rest.get("error_type_dist") or {}

        # Errors per 100 problems of each type, before vs after
        before = {e: (1 - base_acc) * 100 * base_dist.get(e, 0) for e in ERROR_TYPES}
        after  = {e: (1 - rest_acc) * 100 * rest_dist.get(e, 0) for e in ERROR_TYPES}

        y_max = max(list(before.values()) + list(after.values()) + [1])

        # Draw each error type's line
        for e in ERROR_TYPES:
            b, a = before[e], after[e]
            color = ERROR_COLORS[e]
            ax.plot([0, 1], [b, a], "-", color=color, linewidth=1.6, alpha=0.9, zorder=2)
            ax.scatter([0], [b], s=28, color=color, edgecolor="white",
                       linewidth=0.8, zorder=3)
            ax.scatter([1], [a], s=28, color=color, edgecolor="white",
                       linewidth=0.8, zorder=3)
            # Annotate on the restored side
            ax.annotate(f"{e[:5]} {a:.1f}", xy=(1, a), xytext=(4, 0),
                        textcoords="offset points", ha="left", va="center",
                        fontsize=6.5, color=color)

        ax.set_xticks([0, 1])
        ax.set_xticklabels(["Quantized", "Restored"])
        ax.set_xlim(-0.12, 1.5)
        ax.set_ylim(0, y_max * 1.15 + 1)
        ax.text(0.98, 0.97, METHOD_PRETTY[method], transform=ax.transAxes,
                ha="right", va="top", fontsize=7.5, color=GREY_TEXT)
        ax.yaxis.grid(True); ax.set_axisbelow(True)

    axes[0].set_ylabel("Errors per 100 problems")

    fig.savefig(output_path)
    plt.close(fig)
    print(f"  Paper fig 13 saved: {output_path}")


# ---------------------------------------------------------------------------
# Entrypoint
# ---------------------------------------------------------------------------

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--metrics", required=True)
    parser.add_argument("--diagnosis", default="results/diagnosis",
                        help="Diagnosis directory (for FFS dist. and trace example)")
    parser.add_argument("--segmented", default="results/segmented",
                        help="Segmented directory (for FP16 reference in trace example)")
    parser.add_argument("--output", required=True)
    parser.add_argument("--primary-model", default="r1-qwen-7b")
    parser.add_argument("--primary-benchmark", default="math500")
    parser.add_argument("--trace-method", default="gptq_w4",
                        help="Quant method featured in the qualitative trace figure")
    parser.add_argument("--trace-problem", default="math500_12",
                        help="Problem id featured in the qualitative trace figure")
    parser.add_argument("--models", nargs="*", default=None)
    args = parser.parse_args()

    os.makedirs(args.output, exist_ok=True)
    data = load_all(args.metrics)
    if not data:
        print(f"No metrics found in {args.metrics}")
        return

    all_models = sorted({m for (m, _, _) in data.keys()})
    models = args.models if args.models else all_models
    print(f"Primary model: {args.primary_model}   Models: {models}")

    fig_paper_0_pipeline(os.path.join(args.output, "fig_paper_0_pipeline.pdf"))
    fig_paper_1_ssr(data, args.primary_model,
                    os.path.join(args.output, "fig_paper_1_ssr.pdf"))
    fig_paper_2_error_mix(data, args.primary_model, args.primary_benchmark,
                          os.path.join(args.output, "fig_paper_2_error_mix.pdf"))
    fig_paper_3_forest(data, models,
                       os.path.join(args.output, "fig_paper_3_forest.pdf"))
    fig_paper_4_ffs_distribution(args.diagnosis, args.primary_model,
                                 args.primary_benchmark,
                                 os.path.join(args.output, "fig_paper_4_ffs_dist.pdf"))
    fig_paper_5_trace_example(args.diagnosis, args.segmented,
                              args.primary_model, args.primary_benchmark,
                              os.path.join(args.output, "fig_paper_5_trace_example.pdf"),
                              method=args.trace_method,
                              problem_id=args.trace_problem)
    fig_paper_11_metric_correlation(data,
                                    os.path.join(args.output, "fig_paper_11_metric_correlation.pdf"))
    fig_paper_12_error_x_depth(args.diagnosis, args.primary_model,
                               args.primary_benchmark,
                               os.path.join(args.output, "fig_paper_12_error_x_depth.pdf"))
    fig_paper_13_error_reduction(data, args.primary_model,
                                 args.primary_benchmark,
                                 os.path.join(args.output, "fig_paper_13_error_reduction.pdf"))
    table_paper_tex(data, models,
                    os.path.join(args.output, "table_paper.tex"))

    print(f"\nPaper artifacts written under {args.output}")


if __name__ == "__main__":
    main()