-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathrun_paper_figures.py
More file actions
2307 lines (2027 loc) · 90.2 KB
/
Copy pathrun_paper_figures.py
File metadata and controls
2307 lines (2027 loc) · 90.2 KB
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
"""Generate all paper-ready tables and figures from probe results.
Outputs
-------
- paper/figures/auc_summary_barplot.pdf : Main paper figure — best-layer AUC per model & dataset
- paper/figures/<run_id>/<probe>_auc_heatmap.pdf
- paper/figures/<run_id>/<probe>_auc_heatmap_step.pdf
- paper/figures/<run_id>/<probe>_layer_auc.pdf
- paper/figures/<run_id>/<probe>_lookahead[_suffix].pdf
- paper/figures/<run_id>/<probe>_tool_nll_layer<N>[_suffix].pdf
- paper/auc_table.tex : AUC table (appendix)
- paper/calibration_table.tex : ECE + Brier table (appendix)
- paper/figures/transfer_barplot.pdf : Cross-dataset transfer figure
- paper/transfer_table.tex : Cross-dataset transfer table (appendix)
- paper/figures/manifest.json : Figure index for the dashboard
"""
import argparse
import json
import math
import sys
from pathlib import Path
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import matplotlib.colors as mcolors
import numpy as np
import torch
from matplotlib.ticker import MaxNLocator
sys.path.insert(0, str(Path(__file__).parent))
from paper import style as _style
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _load(results_dir: Path, run_id: str, probe: str) -> dict | None:
p = results_dir / run_id / probe / "results.pt"
if not p.exists():
return None
return torch.load(p, weights_only=False)
def _weighted_mean(results_for_layer, field: str) -> float:
total_n, total_w = 0, 0.0
for r in results_for_layer:
n = r.n_test if hasattr(r, "n_test") else r["n_test"]
v = getattr(r, field) if hasattr(r, field) else r[field]
if v is None:
continue
total_w += v * n
total_n += n
return total_w / total_n if total_n > 0 else float("nan")
def _best_layer_mean(all_results: dict, field: str) -> float:
best = float("nan")
for layer_results in all_results.values():
m = _weighted_mean(layer_results, field)
if math.isnan(best) or m > best:
best = m
return best
def _layer_means(all_results: dict, field: str, layers: list[int]) -> dict[int, float]:
return {l: _weighted_mean(all_results.get(l, []), field) for l in layers}
def _auc_grid(all_results: dict, layers: list[int], n_bins: int = 10) -> tuple[np.ndarray, int]:
all_bins = [r.bin_idx if hasattr(r, "bin_idx") else r["bin_idx"]
for lr in all_results.values() for r in lr]
min_b = min(all_bins) if all_bins else 0
eff_bins = max(max(all_bins) - min_b + 1, n_bins) if all_bins and min_b == 0 else (max(all_bins) - min_b + 1 if all_bins else n_bins)
grid = np.full((len(layers), eff_bins), np.nan)
for li, layer in enumerate(layers):
for r in all_results.get(layer, []):
b = r.bin_idx if hasattr(r, "bin_idx") else r["bin_idx"]
v = r.test_auc if hasattr(r, "test_auc") else r["test_auc"]
idx = b - min_b
if 0 <= idx < eff_bins:
grid[li, idx] = v
return grid, eff_bins
# ---------------------------------------------------------------------------
# Labels
# ---------------------------------------------------------------------------
PROBE_LABELS = {
"currently_compiles": _style.PROPERTY_LABELS["syntactic"],
"currently_correct": _style.PROPERTY_LABELS["semantic"],
"currently_reduces_failing": _style.PROPERTY_LABELS["reduced"],
"currently_has_regressions": _style.PROPERTY_LABELS["regressions"],
"will_resolve": "Will resolve",
}
PROBE_TO_PROPERTY = {
"currently_compiles": "syntactic",
"currently_correct": "semantic",
"currently_reduces_failing": "reduced",
"currently_has_regressions": "regressions",
}
PROBE_LABELS_TEX = {
"currently_compiles": r"\Syntactic{}",
"currently_correct": r"\Semantic{}",
"currently_reduces_failing": r"\RedFail{}",
"currently_has_regressions": r"\Regressions{}",
"will_resolve": "Will resolve",
}
# Map hparams.json probe-label strings (old and canonical) to LaTeX macros
_HPARAM_LABEL_TEX = {
"Syntactic correctness": r"\Syntactic{}",
"Semantic correctness": r"\Semantic{}",
"Reduces failures": r"\RedFail{}",
"Has regressions": r"\Regressions{}",
"Syntactic Correctness": r"\Syntactic{}",
"Semantic Correctness": r"\Semantic{}",
"Reduced Failing Tests": r"\RedFail{}",
"Introduced Regressions": r"\Regressions{}",
}
MODEL_LABELS = {
"laguna_xs2_full": "Laguna-XS.2",
"laguna_xs2_pro_full": "Laguna-XS.2",
"qwen36_35b_a3b_full": "Qwen3.6-35B-A3B",
"qwen36_35b_a3b_pro_full": "Qwen3.6-35B-A3B",
}
_MODEL_KEYS = list(MODEL_LABELS.keys())
DATASET_LABELS = {
"Verified": "SWE-Bench-Verified",
"Pro": "SWE-Bench-Pro",
}
def _prop_tick_label(probe: str) -> str:
"""Return a wrapped tick label with glyph on first line; label in uppercase (small-caps proxy)."""
label = PROBE_LABELS.get(probe, probe).upper()
prop = PROBE_TO_PROPERTY.get(probe)
glyph = _style.PROPERTY_GLYPHS[prop] if prop else ""
words = label.split()
first_line = f"{glyph} {words[0]}" if glyph else words[0]
return first_line + ("\n" + "\n".join(words[1:]) if len(words) > 1 else "")
def _apply_title(ax, probe: str, model_str: str = "", dataset_label: str = "", fontsize: float | None = None) -> None:
"""Set a split axes title:
- property glyph + label: property color, uppercase (small-caps proxy)
- model / benchmark: black, monospace font, slightly smaller
The two parts are separate annotate objects so their colors don't mix.
"""
label = PROBE_LABELS.get(probe, probe).upper()
prop = PROBE_TO_PROPERTY.get(probe)
glyph = _style.PROPERTY_GLYPHS.get(prop, "")
prop_color = _style.PROPERTY_COLORS[prop] if prop else "black"
prop_text = f"{glyph} {label}" if glyph else label
ts = fontsize if fontsize is not None else float(plt.rcParams.get("axes.titlesize", 11))
ss = max(ts * 0.82, 7.0)
ax.set_title("") # suppress the built-in title slot
full_ds = DATASET_LABELS.get(dataset_label, dataset_label)
parts = [s for s in [model_str, full_ds] if s]
if parts:
subtitle = " — ".join(parts)
# subtitle: lower of the two (just above the axes border)
ax.annotate(subtitle,
xy=(0.5, 1.0), xycoords="axes fraction",
xytext=(0, 3), textcoords="offset points",
ha="center", va="bottom",
fontsize=ss, family="monospace", color="black",
annotation_clip=False)
# property label: above the subtitle
ax.annotate(prop_text,
xy=(0.5, 1.0), xycoords="axes fraction",
xytext=(0, 3 + ss * 1.35), textcoords="offset points",
ha="center", va="bottom",
fontsize=ts, fontweight="bold", color=prop_color,
annotation_clip=False)
else:
ax.annotate(prop_text,
xy=(0.5, 1.0), xycoords="axes fraction",
xytext=(0, 6), textcoords="offset points",
ha="center", va="bottom",
fontsize=ts, fontweight="bold", color=prop_color,
annotation_clip=False)
def _model_key(run_id: str) -> str:
"""Strip run-suffix to get the canonical MODEL_LABELS key."""
for key in _MODEL_KEYS:
if run_id == key or run_id.startswith(key + "_"):
return key
return run_id
def _layer_label(layer: int) -> int:
"""Convert 0-indexed transformer layer to 1-indexed display label."""
return layer + 1
# ---------------------------------------------------------------------------
# Test-set size annotation helpers
# ---------------------------------------------------------------------------
def _n_test_from_results(all_res: dict) -> int:
"""Return total n_test for one probe/run by summing across bins in the first layer."""
for layer_results in all_res.values():
if layer_results:
return sum(
r.n_test if hasattr(r, "n_test") else r.get("n_test", 0)
for r in layer_results
)
return 0
def _fmt_n(n: int) -> str:
"""Format a hidden-state count as e.g. '488k' or '4.7M' (no units)."""
if n <= 0:
return ""
return f"{n/1e3:.0f}k" if n < 1e6 else f"{n/1e6:.1f}M"
def _annotate_n_test(ax, n: int) -> None:
"""Small grey n= annotation in the bottom-right corner of ax."""
s = _fmt_n(n)
if not s:
return
ax.annotate(f"n = {s} $h_t$",
xy=(1, 0), xycoords="axes fraction",
xytext=(-4, 4), textcoords="offset points",
ha="right", va="bottom", fontsize=7, color="#999999",
annotation_clip=False)
# ---------------------------------------------------------------------------
# AUC summary barplot (main paper figure)
# ---------------------------------------------------------------------------
def plot_generalization_barplot(
verified_results_dir: Path,
pro_results_dir: Path,
verified_run_ids: list[str],
pro_run_ids: list[str],
model_labels: list[str],
probes: list[str],
layers: list[int],
figures_dir: Path,
verified_pooled_run_ids: list[str] | None = None,
pro_pooled_run_ids: list[str] | None = None,
) -> None:
"""Grouped barplot: best-layer AUC per probe × model × dataset."""
# Build series list: (color_key, label, results_dir, effective_run_id)
series = []
for i, (model_id, model_label) in enumerate(zip(verified_run_ids, model_labels)):
model_key = "laguna" if "laguna" in model_id else "qwen"
v_run = (verified_pooled_run_ids or verified_run_ids)[i]
_pro_list = pro_pooled_run_ids or pro_run_ids
p_run = _pro_list[i] if pro_run_ids and i < len(_pro_list) else None
series.append((f"{model_key}_verified", f"{model_label} (Verified)",
verified_results_dir, v_run))
series.append((f"{model_key}_pro", f"{model_label} (Pro)",
pro_results_dir, p_run))
n_series = len(series)
bar_width = 0.15
offsets = np.linspace(-(n_series - 1) / 2, (n_series - 1) / 2, n_series) * bar_width
x = np.arange(len(probes))
fig, ax = plt.subplots(figsize=(_style.FULL_WIDTH, _style.FIG_HEIGHT_BAR))
legend_handles = []
for i, (color_key, label, res_dir, run_id) in enumerate(series):
dataset = "pro" if color_key.endswith("_pro") else "verified"
color = _style.COLORS[color_key]
hatch = _style.HATCH[dataset]
model_key = color_key.replace("_pro", "").replace("_verified", "")
ec = _style.COLORS[f"{model_key}_verified"] # dark shade for hatch visibility
rendered = False
for pi, probe in enumerate(probes):
all_res = _load(res_dir, run_id, probe) if run_id else None
if all_res is None:
continue
v = _best_layer_mean(all_res, "test_auc")
if math.isnan(v):
continue
ax.bar(x[pi] + offsets[i], v, width=bar_width,
color=color, hatch=hatch, edgecolor=ec, linewidth=0.6, zorder=3)
rendered = True
if rendered:
legend_handles.append(mpatches.Patch(
facecolor=color, hatch=hatch, edgecolor=ec, linewidth=0.6, label=label,
))
ax.axhline(0.5, linestyle="--", color=_style.COLORS["baseline"],
linewidth=1.0, zorder=2)
legend_handles.append(plt.Line2D(
[0], [0], linestyle="--", color=_style.COLORS["baseline"],
linewidth=1.0, label="Random (0.5)",
))
ax.set_xticks(x)
ax.set_xticklabels([_prop_tick_label(p) for p in probes], fontsize=8.5)
for tick, p in zip(ax.get_xticklabels(), probes):
prop = PROBE_TO_PROPERTY.get(p)
if prop:
tick.set_color(_style.PROPERTY_COLORS[prop])
ax.set_ylabel("Best-layer AUC")
ax.set_ylim(0.45, 1.0)
ax.legend(handles=legend_handles, ncol=2, loc="upper right")
figures_dir.mkdir(parents=True, exist_ok=True)
out = figures_dir / "auc_summary_barplot.pdf"
fig.savefig(out)
plt.close(fig)
print(f" [fig] {out}")
# ---------------------------------------------------------------------------
# AUC table
# ---------------------------------------------------------------------------
def build_auc_table(
results_dir: Path,
probes: list[str],
model_run_ids: list[str],
shuffled_run_ids: list[str],
layers: list[int],
pooled_run_ids: list[str] | None = None,
pro_results_dir: Path | None = None,
pro_run_ids: list[str] | None = None,
pro_shuffled_run_ids: list[str] | None = None,
pro_pooled_run_ids: list[str] | None = None,
) -> str:
n_layer_cols = len(layers)
col_spec = "l" + "c" * n_layer_cols + "c"
layer_header = " & ".join(str(_layer_label(l)) for l in layers)
n_cols = 1 + n_layer_cols + 1
lines = [
r"\begin{table*}[t]",
r"\centering",
r"\caption{AUC per probe, model, and benchmark across transformer layers."
r" \textbf{Bold} marks the best layer per row."
r" \emph{Shuffled} uses label-permuted data as a sanity baseline.}",
r"\label{tab:auc_roc}",
rf"\begin{{tabular}}{{{col_spec}}}",
r"\toprule",
rf" & \multicolumn{{{n_layer_cols}}}{{c}}{{AUC $\uparrow$}} & Shuffled \\",
rf"\cmidrule(lr){{2-{1 + n_layer_cols}}}",
"Probe & " + layer_header + r" & (best layer) \\",
r"\midrule",
]
def _probe_rows(res_dir: Path, probe_run_id: str, shuf_id: str | None) -> list[str]:
rows = []
for probe in probes:
all_res = _load(res_dir, probe_run_id, probe)
shuf_res = _load(res_dir, shuf_id, probe) if shuf_id else None
tex_lbl = PROBE_LABELS_TEX.get(probe, probe)
if all_res is None:
rows.append(
f"{tex_lbl} & "
+ " & ".join(["—"] * n_layer_cols) + " & — \\\\"
)
continue
layer_aucs = _layer_means(all_res, "test_auc", layers)
shuf_auc = _best_layer_mean(shuf_res, "test_auc") if shuf_res else float("nan")
best_in_row = max(
(v for v in layer_aucs.values() if not math.isnan(v)),
default=float("nan"),
)
cells = []
for l in layers:
v = layer_aucs.get(l, float("nan"))
if math.isnan(v):
cells.append("—")
elif not math.isnan(best_in_row) and abs(v - best_in_row) < 1e-9:
cells.append(rf"\textbf{{{v:.3f}}}")
else:
cells.append(f"{v:.3f}")
shuf_str = f"{shuf_auc:.3f}" if not math.isnan(shuf_auc) else "—"
rows.append(
f"{tex_lbl} & "
+ " & ".join(cells) + f" & {shuf_str} \\\\"
)
return rows
def _dataset_block(
dataset_label: str,
res_dir: Path,
run_ids: list[str],
shuf_ids: list[str] | None,
probe_run_ids: list[str],
) -> list[str]:
if shuf_ids is None:
shuf_ids = [None] * len(run_ids)
block = [
rf"\multicolumn{{{n_cols}}}{{l}}{{\textsc{{{dataset_label}}}}} \\",
r"\addlinespace[2pt]",
]
for run_id, shuf_id, probe_run_id in zip(run_ids, shuf_ids, probe_run_ids):
model_label = MODEL_LABELS.get(_model_key(run_id), run_id)
block.append(
rf"\multicolumn{{{n_cols}}}{{l}}{{\quad\textit{{{model_label}}}}} \\"
)
block += _probe_rows(res_dir, probe_run_id, shuf_id)
block.append(r"\addlinespace[3pt]")
return block
lines += _dataset_block(
"SWE-bench Verified",
results_dir,
model_run_ids,
shuffled_run_ids,
pooled_run_ids or model_run_ids,
)
if pro_results_dir and pro_run_ids:
while lines and lines[-1] == r"\addlinespace[3pt]":
lines.pop()
lines.append(r"\midrule")
lines += _dataset_block(
"SWE-bench Pro",
pro_results_dir,
pro_run_ids,
pro_shuffled_run_ids,
pro_pooled_run_ids or pro_run_ids,
)
while lines and lines[-1] == r"\addlinespace[3pt]":
lines.pop()
lines += [r"\bottomrule", r"\end{tabular}", r"\end{table*}"]
return "\n".join(lines)
# ---------------------------------------------------------------------------
# Calibration table
# ---------------------------------------------------------------------------
def build_calibration_table(
results_dir: Path,
probes: list[str],
model_run_ids: list[str],
layers: list[int],
pooled_run_ids: list[str] | None = None,
pro_results_dir: Path | None = None,
pro_run_ids: list[str] | None = None,
pro_pooled_run_ids: list[str] | None = None,
) -> str:
col_spec = "l" + "cc" * len(layers)
layer_header = " & ".join(rf"\multicolumn{{2}}{{c}}{{Layer {_layer_label(l)}}}" for l in layers)
sub_header = " & ".join([r"ECE $\downarrow$ & Brier $\downarrow$"] * len(layers))
n_metric_cols = len(layers) * 2
n_cols = 1 + n_metric_cols
lines = [
r"\begin{table*}[t]",
r"\centering",
r"\caption{Calibration metrics (ECE and Brier score) per probe across layers."
r" Lower is better for both metrics.}",
r"\label{tab:calibration}",
rf"\begin{{tabular}}{{{col_spec}}}",
r"\toprule",
rf"Probe & {layer_header} \\",
rf"\cmidrule(lr){{2-{1 + n_metric_cols}}}",
rf"& {sub_header} \\",
r"\midrule",
]
def _probe_rows(res_dir: Path, probe_run_id: str) -> list[str]:
rows = []
for probe in probes:
all_res = _load(res_dir, probe_run_id, probe)
tex_lbl = PROBE_LABELS_TEX.get(probe, probe)
if all_res is None:
rows.append(
f"{tex_lbl} & "
+ " & ".join(["— & —"] * len(layers)) + r" \\"
)
continue
cells = []
for l in layers:
ece = _weighted_mean(all_res.get(l, []), "test_ece")
brier = _weighted_mean(all_res.get(l, []), "test_brier")
cells.append(
f"{'—' if math.isnan(ece) else f'{ece:.3f}'}"
f" & {'—' if math.isnan(brier) else f'{brier:.3f}'}"
)
rows.append(
f"{tex_lbl} & " + " & ".join(cells) + r" \\"
)
return rows
def _dataset_block(
dataset_label: str,
res_dir: Path,
run_ids: list[str],
probe_run_ids: list[str],
) -> list[str]:
block = [
rf"\multicolumn{{{n_cols}}}{{l}}{{\textsc{{{dataset_label}}}}} \\",
r"\addlinespace[2pt]",
]
for run_id, probe_run_id in zip(run_ids, probe_run_ids):
model_label = MODEL_LABELS.get(_model_key(run_id), run_id)
block.append(
rf"\multicolumn{{{n_cols}}}{{l}}{{\quad\textit{{{model_label}}}}} \\"
)
block += _probe_rows(res_dir, probe_run_id)
block.append(r"\addlinespace[3pt]")
return block
lines += _dataset_block(
"SWE-bench Verified",
results_dir,
model_run_ids,
pooled_run_ids or model_run_ids,
)
if pro_results_dir and pro_run_ids:
while lines and lines[-1] == r"\addlinespace[3pt]":
lines.pop()
lines.append(r"\midrule")
lines += _dataset_block(
"SWE-bench Pro",
pro_results_dir,
pro_run_ids,
pro_pooled_run_ids or pro_run_ids,
)
while lines and lines[-1] == r"\addlinespace[3pt]":
lines.pop()
lines += [r"\bottomrule", r"\end{tabular}", r"\end{table*}"]
return "\n".join(lines)
# ---------------------------------------------------------------------------
# Hyperparameter table
# ---------------------------------------------------------------------------
def _sci_notation(v: float) -> str:
"""Format a float as LaTeX scientific notation: $X.XX \\times 10^{N}$."""
exp = math.floor(math.log10(abs(v)))
mantissa = v / 10 ** exp
return rf"${mantissa:.2f} \times 10^{{{exp}}}$"
def build_hparam_table(
hparams: dict,
model_labels: list[str],
dataset_labels: list[str],
output_path: Path,
) -> None:
"""Write a LaTeX table of chosen probe hyperparameters to output_path.
hparams format:
{dataset_label: {model_label: hp_entry | None}}
where hp_entry is either:
{lr, weight_decay, batch_size, patience} — one set shared across probes
{probe_label: {lr, weight_decay, batch_size, patience}, ...} — per-probe
{probe_label: {layer_str: {lr, weight_decay, batch_size, patience}, ...}, ...} — per-probe per-layer
Per-probe per-layer entries are collapsed to per-probe for display using the middle layer.
"""
def _hp_cells(hp: dict) -> str:
return (
f"{_sci_notation(hp['lr'])} & {_sci_notation(hp['weight_decay'])} "
f"& {hp['batch_size']} & {hp['patience']}"
)
def _is_per_layer(entry: dict) -> bool:
"""True when entry values are dicts of layer→hp (per-probe per-layer)."""
first = next(iter(entry.values()), None)
if not isinstance(first, dict):
return False
first_inner = next(iter(first.values()), None)
return isinstance(first_inner, dict)
def _collapse_layers(entry: dict) -> dict:
"""Collapse per-probe per-layer dict to per-probe by picking the middle layer."""
result = {}
for probe_label, layer_hps in entry.items():
layers_sorted = sorted(layer_hps.keys(), key=lambda x: int(x))
mid = layers_sorted[len(layers_sorted) // 2]
result[probe_label] = layer_hps[mid]
return result
def _is_per_probe(entry) -> bool:
if entry is None:
return False
if _is_per_layer(entry):
return True
return isinstance(next(iter(entry.values())), dict)
def _resolve_hp(entry) -> dict:
"""Return a per-probe dict, collapsing layers if needed."""
if _is_per_layer(entry):
return _collapse_layers(entry)
return entry
# Count total rows to size multirow for the dataset column
def _n_rows_for_dataset(dataset_label: str) -> int:
dataset_hparams = hparams.get(dataset_label, {})
total = 0
for model_label in model_labels:
hp = dataset_hparams.get(model_label)
if _is_per_probe(hp):
total += len(_resolve_hp(hp))
else:
total += 1
return total
# Determine if we need a Probe column (any dataset has per-probe entries)
need_probe_col = any(
_is_per_probe(hparams.get(ds, {}).get(m))
for ds in dataset_labels
for m in model_labels
)
col_spec = "lllrrrr" if need_probe_col else "llrrrr"
header_row = (
r"Dataset & Model & Probe & Learning rate & Weight decay & Batch size & Patience \\"
if need_probe_col else
r"Dataset & Model & Learning rate & Weight decay & Batch size & Patience \\"
)
lines = [
r"\begin{table}[t]",
r"\centering",
(
r"\caption{Chosen hyperparameters for each model and benchmark, "
r"selected by 20-trial random search maximising mean validation AUC. "
r"Sweeps were run independently per probe and per layer; "
r"table shows the middle probed layer as representative.}"
),
r"\label{tab:probe-hparams}",
rf"\begin{{tabular}}{{{col_spec}}}",
r"\toprule",
header_row,
r"\midrule",
]
for di, dataset_label in enumerate(dataset_labels):
dataset_hparams = hparams.get(dataset_label, {})
n_ds_rows = _n_rows_for_dataset(dataset_label)
ds_multirow = rf"\multirow{{{n_ds_rows}}}{{*}}{{\textsc{{{dataset_label}}}}}"
ds_printed = False
for model_label in model_labels:
hp = dataset_hparams.get(model_label)
ds_cell = ds_multirow if not ds_printed else ""
if _is_per_probe(hp):
resolved = _resolve_hp(hp)
probe_labels = list(resolved.keys())
n_probe_rows = len(probe_labels)
model_multirow = rf"\multirow{{{n_probe_rows}}}{{*}}{{{model_label}}}"
for pi, probe_label in enumerate(probe_labels):
probe_hp = resolved[probe_label]
model_cell = model_multirow if pi == 0 else ""
d_cell = ds_cell if pi == 0 else ""
tex_probe = _HPARAM_LABEL_TEX.get(probe_label, probe_label)
if need_probe_col:
lines.append(
f"{d_cell} & {model_cell} & {tex_probe} & {_hp_cells(probe_hp)} \\\\"
)
ds_printed = True
else:
cells = _hp_cells(hp) if hp is not None else "— & — & — & —"
if need_probe_col:
lines.append(f"{ds_cell} & {model_label} & & {cells} \\\\")
else:
lines.append(f"{ds_cell} & {model_label} & {cells} \\\\")
ds_printed = True
if di < len(dataset_labels) - 1:
lines.append(r"\midrule")
lines += [
r"\bottomrule",
r"\end{tabular}",
r"\end{table}",
]
output_path.write_text("\n".join(lines) + "\n")
print(f" [tex] {output_path}")
# ---------------------------------------------------------------------------
# Transfer barplot
# ---------------------------------------------------------------------------
def plot_transfer_barplot(
verified_results_dir: Path,
pro_results_dir: Path,
probes: list[str],
figures_dir: Path,
model_labels: list[str],
verified_pooled_run_ids: list[str],
pro_pooled_run_ids: list[str],
verified_to_pro_run_ids: list[str],
pro_to_verified_run_ids: list[str],
) -> None:
"""Grouped barplot: in-dist vs transfer AUC (best layer) per probe, one subplot per model."""
def _best(res_dir: Path, run_id: str, probe: str) -> float:
res = _load(res_dir, run_id, probe)
return _best_layer_mean(res, "test_auc") if res is not None else float("nan")
n_models = len(model_labels)
bar_width = 0.14
pair_gap = 0.02
group_gap = 0.08
pair_w = bar_width * 2 + pair_gap
total = 2 * pair_w + group_gap
left = -(total / 2)
offsets = {
"indist_v": left,
"vp": left + bar_width + pair_gap,
"indist_p": left + pair_w + group_gap,
"pv": left + pair_w + group_gap + bar_width + pair_gap,
}
fig, axes = plt.subplots(n_models, 1,
figsize=(_style.FULL_WIDTH, _style.FIG_HEIGHT_BAR * n_models),
squeeze=False)
x = np.arange(len(probes))
for row, (model_label, v_pooled, p_pooled, vp_id, pv_id) in enumerate(zip(
model_labels, verified_pooled_run_ids, pro_pooled_run_ids,
verified_to_pro_run_ids, pro_to_verified_run_ids,
)):
ax = axes[row, 0]
model_slug = "laguna" if "laguna" in v_pooled else "qwen"
color_v = _style.COLORS[f"{model_slug}_verified"]
color_p = _style.COLORS[f"{model_slug}_pro"]
gray = "#BDBDBD"
gray_p = "#9E9E9E"
for pi, probe in enumerate(probes):
v_auc = _best(verified_results_dir, v_pooled, probe)
p_auc = _best(pro_results_dir, p_pooled, probe)
vp_auc = _best(pro_results_dir, vp_id, probe)
pv_auc = _best(verified_results_dir, pv_id, probe)
for val, offset, color, ec in [
(v_auc, offsets["indist_v"], gray, "#9E9E9E"),
(vp_auc, offsets["vp"], color_v, color_v),
(p_auc, offsets["indist_p"], gray_p, "#757575"),
(pv_auc, offsets["pv"], color_p, color_p),
]:
if not math.isnan(val):
ax.bar(x[pi] + offset, val, width=bar_width,
color=color, edgecolor=ec, linewidth=0.6, zorder=3)
ax.axhline(0.5, linestyle="--", color=_style.COLORS["baseline"],
linewidth=1.0, zorder=2)
legend_handles = [
mpatches.Patch(facecolor=gray, edgecolor="#9E9E9E", linewidth=0.6, label="In-dist (Verified)"),
mpatches.Patch(facecolor=color_v, edgecolor=color_v, linewidth=0.6, label="Verified → Pro"),
mpatches.Patch(facecolor=gray_p, edgecolor="#757575", linewidth=0.6, label="In-dist (Pro)"),
mpatches.Patch(facecolor=color_p, edgecolor=color_p, linewidth=0.6, label="Pro → Verified"),
plt.Line2D([0], [0], linestyle="--", color=_style.COLORS["baseline"],
linewidth=1.0, label="Random (0.5)"),
]
ax.set_xticks(x)
ax.set_xticklabels([_prop_tick_label(p) for p in probes], fontsize=8.5)
for tick, p in zip(ax.get_xticklabels(), probes):
prop = PROBE_TO_PROPERTY.get(p)
if prop:
tick.set_color(_style.PROPERTY_COLORS[prop])
ax.set_ylabel("Best-layer AUC")
ax.set_ylim(0.45, 1.0)
ax.set_title(model_label)
ax.legend(handles=legend_handles, ncol=3, loc="upper right")
fig.tight_layout()
figures_dir.mkdir(parents=True, exist_ok=True)
out = figures_dir / "transfer_barplot.pdf"
fig.savefig(out, bbox_inches="tight")
plt.close(fig)
print(f" [fig] {out}")
# ---------------------------------------------------------------------------
# Transfer table
# ---------------------------------------------------------------------------
def build_transfer_table(
verified_results_dir: Path,
pro_results_dir: Path,
probes: list[str],
layers: list[int],
model_labels: list[str],
verified_pooled_run_ids: list[str],
pro_pooled_run_ids: list[str],
verified_to_pro_run_ids: list[str],
pro_to_verified_run_ids: list[str],
) -> str:
n_layer_cols = len(layers)
col_spec = "l" + "c" * n_layer_cols
layer_header = " & ".join(f"Layer {_layer_label(l)}" for l in layers)
multi_model = len(model_labels) > 1
def _fmt_delta(delta: float) -> str:
sign = "+" if delta >= 0 else "-"
color = r"green!50!black" if delta >= 0 else r"red!70!black"
return rf"{{\scriptsize \textcolor{{{color}}}{{${sign}{abs(delta):.3f}$}}}}"
def _get_aucs(res_dir: Path, run_id: str, probe: str) -> dict[int, float]:
res = _load(res_dir, run_id, probe)
if res is None:
return {l: float("nan") for l in layers}
return {l: _weighted_mean(res.get(l, []), "test_auc") for l in layers}
def _ref_cell(v: float) -> str:
return rf"\textcolor{{gray}}{{\small {v:.3f}}}" if not math.isnan(v) else "—"
def _transfer_cell(transfer_v: float, ref_v: float) -> str:
if math.isnan(transfer_v):
return "—"
delta = transfer_v - ref_v if not math.isnan(ref_v) else float("nan")
delta_str = _fmt_delta(delta) if not math.isnan(delta) else ""
return rf"{transfer_v:.3f}\,{delta_str}"
lines = [
r"\begin{table*}[t]",
r"\centering",
r"\caption{Cross-dataset transfer AUC. "
r"Gray rows show in-distribution reference performance. "
r"Transfer rows show AUC when probe weights trained on one dataset are "
r"evaluated on the other; the subscript shows the delta relative to the "
r"in-distribution baseline on the \emph{same} evaluation set.}",
r"\label{tab:transfer}",
rf"\begin{{tabular}}{{{col_spec}}}",
r"\toprule",
rf" & {layer_header} \\",
r"\midrule",
]
for probe in probes:
probe_label = PROBE_LABELS_TEX.get(probe, probe)
lines.append(
rf"\multicolumn{{{1 + n_layer_cols}}}{{l}}{{\textit{{{probe_label}}}}} \\"
)
for model_label, v_pooled, p_pooled, vp_id, pv_id in zip(
model_labels, verified_pooled_run_ids, pro_pooled_run_ids,
verified_to_pro_run_ids, pro_to_verified_run_ids,
):
indent = r"\qquad{}" if multi_model else r"\quad{}"
if multi_model:
lines.append(
rf"\quad{{}}\textit{{{model_label}}} \\"
)
v_aucs = _get_aucs(verified_results_dir, v_pooled, probe)
p_aucs = _get_aucs(pro_results_dir, p_pooled, probe)
vp_aucs = _get_aucs(pro_results_dir, vp_id, probe)
pv_aucs = _get_aucs(verified_results_dir, pv_id, probe)
lines.append(
indent + r"\textcolor{gray}{\small In-dist (Verified)} & "
+ " & ".join(_ref_cell(v_aucs[l]) for l in layers) + r" \\"
)
lines.append(
indent + r"\textcolor{gray}{\small In-dist (Pro)} & "
+ " & ".join(_ref_cell(p_aucs[l]) for l in layers) + r" \\"
)
lines.append(
indent + r"Verified $\rightarrow$ Pro & "
+ " & ".join(_transfer_cell(vp_aucs[l], p_aucs[l]) for l in layers) + r" \\"
)
lines.append(
indent + r"Pro $\rightarrow$ Verified & "
+ " & ".join(_transfer_cell(pv_aucs[l], v_aucs[l]) for l in layers) + r" \\"
)
lines.append(r"\midrule")
lines[-1] = r"\bottomrule"
lines += [r"\end{tabular}", r"\end{table*}"]
return "\n".join(lines)
# ---------------------------------------------------------------------------
# AUC heatmap
# ---------------------------------------------------------------------------
def plot_auc_heatmap(
results_dir: Path,
run_id: str,
probe: str,
layers: list[int],
figures_dir: Path,
n_bins: int = 10,
x_label: str = "Relative position bin",
suffix: str = "",
dataset_label: str = "",
) -> None:
all_res = _load(results_dir, run_id, probe)
if all_res is None:
print(f" [skip] {run_id}/{probe} — no results.pt")
return
grid, eff_bins = _auc_grid(all_res, layers, n_bins)
out_dir = figures_dir / run_id
out_dir.mkdir(parents=True, exist_ok=True)
fig, ax = plt.subplots(figsize=(_style.FULL_WIDTH, _style.FIG_HEIGHT_HEAT))
ax.grid(False) # override global rcParam — grid lines bleed over heatmap cells
norm = mcolors.Normalize(vmin=_style.HEATMAP_VMIN, vmax=_style.HEATMAP_VMAX)
# pcolormesh gives crisp cell edges with no interpolation artefacts
im = ax.pcolormesh(grid, cmap=_style.HEATMAP_CMAP, norm=norm,
linewidth=0.5, edgecolors="white")
ax.set_xticks([i + 0.5 for i in range(eff_bins)])
ax.set_xticklabels(
[f"{i/eff_bins:.1f}–{(i+1)/eff_bins:.1f}" for i in range(eff_bins)],
rotation=40, ha="right",
)
ax.set_yticks([i + 0.5 for i in range(len(layers))])
ax.set_yticklabels([f"Layer {_layer_label(l)}" for l in layers])
ax.set_xlabel(x_label)
ax.set_ylabel("Layer")
ax.tick_params(length=0) # hide tick marks — cells are already delimited
model_key = _model_key(run_id)
model_str = MODEL_LABELS.get(model_key, model_key)
_apply_title(ax, probe, model_str, dataset_label)
cb = plt.colorbar(im, ax=ax, label="AUC")
cb.set_ticks([0.5, 0.625, 0.75, 0.875, 1.0])
cb.ax.tick_params(labelsize=8)
mid = (_style.HEATMAP_VMIN + _style.HEATMAP_VMAX) / 2
for li in range(len(layers)):
for bi in range(eff_bins):
v = grid[li, bi]
if not math.isnan(v):
ax.text(bi + 0.5, li + 0.5, f"{v:.2f}", ha="center", va="center",
fontsize=6.5, color="white" if v > mid else "black")
_annotate_n_test(ax, _n_test_from_results(all_res))
fname = f"{probe}_auc_heatmap{suffix}.pdf"
fig.savefig(out_dir / fname)
plt.close(fig)
print(f" [fig] {out_dir / fname}")
# ---------------------------------------------------------------------------
# Layer AUC line plot
# ---------------------------------------------------------------------------
def plot_layer_auc(
results_dir: Path,
run_ids: list[str],
run_labels: list[str],
probe: str,
layers: list[int],
figures_dir: Path,
out_run_id: str,
extra_series: list[tuple[Path, str, str]] | None = None,
) -> None:
out_dir = figures_dir / out_run_id
out_dir.mkdir(parents=True, exist_ok=True)
prop_key = PROBE_TO_PROPERTY.get(probe)
prop_marker = _style.PROPERTY_MARKERS[prop_key] if prop_key else "o"
fig, ax = plt.subplots(figsize=(_style.FULL_WIDTH, _style.FIG_HEIGHT_LINE))
for run_id, label in zip(run_ids, run_labels):
all_res = _load(results_dir, run_id, probe)
if all_res is None:
continue
layer_aucs = _layer_means(all_res, "test_auc", layers)
xs = [l for l in layers if not math.isnan(layer_aucs.get(l, float("nan")))]
ys = [layer_aucs[l] for l in xs]
is_shuffled = "shuffled" in run_id
is_qwen = "qwen" in run_id
if is_shuffled:
color = _style.COLORS["shuffled"]
ls, marker, ms, alpha = "--", None, 0, 0.7
elif is_qwen:
color = _style.COLORS["qwen_verified"]
ls, marker, ms, alpha = "-", prop_marker, 5, 1.0
else:
color = _style.COLORS["laguna_verified"]
ls, marker, ms, alpha = "-", prop_marker, 5, 1.0
ax.plot(xs, ys, linestyle=ls, marker=marker, markersize=ms,
color=color, alpha=alpha, label=label, linewidth=1.4)