-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunctions.py
More file actions
1973 lines (1702 loc) · 82.5 KB
/
Copy pathfunctions.py
File metadata and controls
1973 lines (1702 loc) · 82.5 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
import re
import time
import numpy as np
from threadpoolctl import threadpool_limits
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor, as_completed
import qutip as qt
import pandas as pd
import seaborn as sns
import sklearn as sk
import scipy as sp
import scipy.cluster.hierarchy as spc
import matplotlib.pyplot as plt
import matplotlib.colors as colors
from qutip import Bloch, basis
from sklearn.metrics.pairwise import cosine_similarity
from sklearn.decomposition import PCA
from datasets import load_dataset
from tqdm import tqdm
import pickle, os
import gzip
from sklearn.metrics import roc_auc_score
from scipy.stats import entropy
import hdbscan
import numpy as np
from scipy.optimize import linear_sum_assignment
from sklearn.metrics import pairwise_distances
from webencodings import lookup
model_names = {'phi_4': 'Phi 4', 'phi_4_mini': 'Phi 4 Mini', 'llama4_maverick': 'Llama4 Maverick'}
dataset_names = {'TriviaQA': 'TriviaQA', 'OpenNQ': 'Natural Questions'}
DATASET_TO_NAME = {
'TriviaQA': 'TriviaQA',
'OpenNQ': 'Natural Questions',
}
ALL_TEMPS = np.logspace(np.log10(0.1), np.log10(3.0), num=20) #Linear search space over sampling temperatures for the Lamb et al. sampling temperature calibration baseline
def plot_risk_TS_curves(results, file_name=None, font_size=10, figsize=(10, 4), n_size=300):
results = pd.DataFrame(results)
datasets = ['TriviaQA', 'OpenNQ']
models = ['phi_4_mini', 'phi_4', 'llama4_maverick']
n_rows = len(datasets)
n_cols = len(models)
fig, axes = plt.subplots(n_rows, n_cols, figsize=figsize)
for dataset_id, dataset in enumerate(datasets):
for model_id, model in enumerate(models):
selected_instances = results[(results['model']==model)&(results['dataset']==dataset)].reset_index(drop=True)
temps = np.array(selected_instances['temps'][0])
#temps = np.round(1/temps, 2)
risks = np.array(selected_instances['risks'][0])
risks_stds = np.array(selected_instances['risks_stds'][0])
risks_ub = risks + risks_stds/n_size
risks_lb = risks - risks_stds/n_size
entropies = np.array(selected_instances['avg_entropies'][0])
entropies_stds = np.array(selected_instances['avg_entropies_stds'][0])
entropies_ub = entropies + entropies_stds/n_size
entropies_lb = entropies - entropies_stds/n_size
axes[dataset_id][model_id].axvline(x=1, color='grey', linestyle='--', linewidth=2)
axes[dataset_id][model_id].plot(temps, risks, color='red', linewidth=2, label='Risk')
axes[dataset_id][model_id].fill_between(
temps, risks_lb, risks_ub, alpha=0.2, color='red'
)
axes[dataset_id][model_id].plot(temps, entropies, color='blue', linewidth=2, label='Average \n Entropy')
axes[dataset_id][model_id].fill_between(
temps, entropies_lb, entropies_ub, alpha=0.2, color='blue'
)
axes[dataset_id][model_id].set_xscale("log")
if dataset_id < 1:
axes[dataset_id][model_id].set_title(model_names[model])
axes[dataset_id][model_id].set_xticks([], [])
if model_id==2:
# top right subfigure
axes[dataset_id][model_id].legend(bbox_to_anchor=(1.05, 1))
else:
axes[dataset_id][model_id].set_xticks([0.5, 1.0, 2.0, 4.0], [0.5, 1.0, 2.0, 4.0])
if dataset_id==len(datasets)-1:
axes[dataset_id][model_id].set_xlabel('Temperature', fontsize=font_size)
if model_id < 1:
axes[dataset_id][model_id].set_ylabel(dataset_names[dataset], fontsize=font_size)
# plt.xticks(fontsize=font_size)
# plt.yticks(fontsize=font_size)
plt.tight_layout()
if file_name is not None:
plt.savefig('figures/'+file_name, dpi=300, bbox_inches="tight")
plt.show();
def balanced_kmeans(corr, k, random_state=0):
"""
Balanced clustering into k equal-sized clusters
from a correlation matrix using Hungarian assignment.
"""
np.random.seed(random_state)
N = corr.shape[0]
assert N % k == 0, "N must be divisible by k for equal clusters"
cluster_size = N // k
# Use correlation distance
dist = 1 - corr
# Initialize k random centers
centers = np.random.choice(N, k, replace=False)
for _ in range(10): # a few refinement iterations
# Compute distances to cluster centers
D = dist[:, centers] # shape (N, k)
# Expand cost matrix to enforce equal cluster sizes
cost = np.repeat(D, cluster_size, axis=1) # (N, k*cluster_size)
# Solve assignment
row_ind, col_ind = linear_sum_assignment(cost)
assignments = col_ind // cluster_size
# Update centers as mean of assigned points (like k-means)
new_centers = []
for c in range(k):
idx = np.where(assignments == c)[0]
# compute centroid in correlation space
sub_corr = corr[np.ix_(idx, idx)]
center = idx[np.argmax(np.sum(sub_corr, axis=1))]
new_centers.append(center)
centers = new_centers
return assignments
# # Example
# np.random.seed(0)
# N = 2000
# X = np.random.randn(100, N)
# corr = np.corrcoef(X, rowvar=False)
# labels = balanced_kmeans(corr, k=4)
# print("Cluster labels:", labels)
# print("Cluster sizes:", np.bincount(labels))
def load_data(dataset, answer_model, split, embedding_model='all_mpnet_base_v2', baseline = False, baseline_temperature_index=0):
"""
Available datasets:
- TriviaQA
- OpenNQ
Available answer models:
- phi_4
- phi_4_mini
- llama4_maverick
Possible splits:
- validation
- test
Note: Validation dataset has 100 answers per question. Test has only 20 answers per question.
"""
# Added block to correctly fetch baseline data
if baseline:
log_dir = 'baseline_logs'
temperature_str = f'-t{baseline_temperature_index}'
else:
log_dir = 'logs'
temperature_str = ''
if dataset not in ['TriviaQA', 'OpenNQ']:
raise ValueError(f"Dataset {dataset} not recognized. Only 'TriviaQA' and 'OpenNQ' are supported.")
#Get ground truth data
if split not in ['validation', 'test']:
raise ValueError("split must be 'validation' or 'test'")
elif split == 'test':
dataset = dataset + '_2k'
dataset_path = f'data/eval/{dataset}.json'
dataset_df = pd.read_json(dataset_path)
if split == 'test': #If we want the test set, we take the 2k set and remove the overlapping points between it and the validation set
base_dataset = dataset.replace('_2k', '')
base_path = f'data/eval/{base_dataset}.json'
base_df = pd.read_json(base_path)
base_ids = set(base_df['datapoint_id'])
dataset_df = dataset_df[~dataset_df['datapoint_id'].isin(base_ids)].reset_index(drop=True)
#Get answer embeddings
pickle_path = f'data/{log_dir}/{dataset}/no_ensembling/no_model-variations/{answer_model}-embeddings{temperature_str}-{embedding_model}.pkl.gz'
with gzip.open(pickle_path, 'rb') as f:
embedding_data = pickle.load(f)
dataset_df = dataset_df.merge(embedding_data, on='question_id', how='left')
if not baseline:
#Get answer correctness (fuzzy and model/judge-based labels, one per question)
standard_answers_path = f'data/logs/{dataset}/standard_answers/{answer_model}-answers.json'
standard_df = pd.read_json(standard_answers_path)
standard_df = standard_df.drop(columns=['generated_answer'])
# some embedding pickles already carry fuzzy_correctness; drop before merge to avoid _x/_y suffix collision
conflict_cols = [c for c in standard_df.columns if c != 'question_id' and c in dataset_df.columns]
if conflict_cols:
dataset_df = dataset_df.drop(columns=conflict_cols)
dataset_df = dataset_df.merge(standard_df, on='question_id', how='left')
#Get ground truth embeddings
gt_pickle_path = f'data/logs/{dataset}/gt-embeddings-{embedding_model}.pkl.gz'
with gzip.open(gt_pickle_path, 'rb') as f:
gt_embeddings_data = pickle.load(f)
gt_embeddings_data_df = pd.DataFrame(gt_embeddings_data)
gt_embeddings_data_df['gt_embedding'] = gt_embeddings_data_df['embedding']
gt_embeddings_data_df= gt_embeddings_data_df[['question_id', 'gt_embedding']]
dataset_df = dataset_df.merge(gt_embeddings_data_df, on='question_id', how = 'left')
return dataset_df
def cross_entropy_loss(EV_decomp, target_vec, eps=1e-10):
eigenvals, eigenvecs = EV_decomp #np.linalg.eigh(psd_matrix)
eigenvals = np.maximum(eigenvals, eps)
log_matrix = eigenvecs @ np.diag(np.log(eigenvals)) @ eigenvecs.T
return (-1) * target_vec.T @ log_matrix @ target_vec
def kernel_score(psd_matrix, target_vec):
matrix_length = np.linalg.norm(psd_matrix, 'fro')**2
cross_term = target_vec.T @ psd_matrix @ target_vec
return matrix_length - 2*cross_term
# Load GloVe embeddings (e.g., glove.6B.100d.txt)
def load_glove_embeddings(filepath):
embeddings = {}
with open(filepath, 'r', encoding='utf8') as f:
for line in f:
values = line.split()
word = values[0]
vec = np.array(values[1:], dtype='float32')
embeddings[word] = vec
return embeddings
# Preprocess text (simple tokenization)
def tokenize(text):
return re.findall(r'\b\w+\b', text.lower())
def argsort_based_on_max_EV(eigenvals, eigenvecs):
eigenvals_max = eigenvals.copy()
eigenvals_max[eigenvals < np.max(eigenvals)] = 0
reduced_gram_matrix = eigenvecs @ np.diag(eigenvals_max) @ eigenvecs.T
reduced_probs = np.diag(reduced_gram_matrix)
ranks = np.argsort(reduced_probs)
return ranks[::-1]
# Average word embeddings for a sentence
def sentence_embedding(sentence, glove):
tokens = tokenize(sentence)
vectors = [glove[word] for word in tokens if word in glove]
if not vectors:
return np.zeros(100) # Fallback for unknown tokens
return np.mean(vectors, axis=0)
def normalise_rows(data):
return data / np.linalg.norm(data, axis=1, keepdims=True)
def spectral_decomp_gram_matrix(vec):
vec = vec.astype(np.float32)
gram_matrix = vec @ vec.T/vec.shape[0]
eigenvals, eigenvecs = np.linalg.eigh(gram_matrix)
# eigenvalues are expected to be normalised
eigenvals = np.clip(eigenvals, 0, 1)
return eigenvals, eigenvecs
def TS_EV(eigenvals, temp=1): #Now temperature is inversed to match the standard temperature definition.
eigenvals = np.abs(eigenvals)
try:
scaled_EVs = eigenvals**(1/temp) / np.sum(eigenvals**(1/temp))
return scaled_EVs
except ZeroDivisionError:
print(eigenvals)
print(temp)
#print(eigenvals**(1/temp))
return np.ones_like(eigenvals)/len(eigenvals)
def TS_matrix(psd_matrix, temp=1):
eigenvals, eigenvecs = np.linalg.eigh(psd_matrix)
eigenvals = np.clip(eigenvals, 0, 1)
scaled_EVs = TS_EV(eigenvals, temp=temp)
return scaled_EVs, eigenvecs
def plot_eigenvals(eigenvals, file_name=None, font_size=12, figsize=(6,6)):
outcomes = ['#{}'.format(i+1) for i, _ in enumerate(eigenvals)]
# Create a bar plot
plt.figure(figsize=figsize)
colors = ['red'] + ['blue'] * (len(outcomes) - 1)
plt.bar(outcomes, eigenvals[::-1], color=colors)
# Add labels and title
plt.xlabel('Latent Outcome', fontsize=font_size+4)
plt.ylabel('Probability', fontsize=font_size+4)
plt.xticks(fontsize=font_size)
plt.yticks(fontsize=font_size)
ax = plt.gca()
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
if file_name is not None:
plt.savefig('figures/'+file_name, dpi=300, bbox_inches="tight")
plt.show();
def plot_bloch(data, color_gradient=None, view=None, file_name=None, point_size=100, font_size=15, figsize=(6,6)):
"""
data shape: (3, n_samples)
color_gradient: (n_samples,)
view: (2,)
"""
# Instantiate the Bloch sphere
b = Bloch()
x = (basis(2,0)+(1+0j)*basis(2,1)).unit()
y = (basis(2,0)+(0+1j)*basis(2,1)).unit()
z = (basis(2,0)+(0+0j)*basis(2,1)).unit()
b.add_states([x,y,z])
if color_gradient is not None:
norm = colors.Normalize(vmin=np.min(color_gradient), vmax=np.max(color_gradient))
cmap = plt.get_cmap('coolwarm')
mapped_colors = cmap(norm(color_gradient))
b.point_color = mapped_colors
b.add_points(data, 'm')
else:
b.add_points(data)
if view is not None:
b.view = view
b.zlabel = ["", ""]
b.xlabel = ["", ""]
b.ylabel = ["", ""]
b.point_size = [point_size]
b.vector_color = ["black", "black", "black"]
b.font_size = font_size
b.fig = plt.figure(figsize=figsize)
# ax = b.axes
# ax.set_ylabel("Dim 3", labelpad=20)
# ax.yaxis.set_label_coords(-0.2, 0.5)
if file_name is not None:
b.render()
b.fig.savefig('figures/'+file_name, dpi=300, bbox_inches="tight")
else:
b.show()
def sim_estimator(emb_answers):
n_val = emb_answers.shape[0]
n_reps = 1000
results = []
for n_subset in tqdm([5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75][::-1]):
for seed in np.arange(n_reps):
np.random.seed(seed)
row_indices = np.random.choice(n_val, size=n_subset, replace=False)
sampled_embs = emb_answers[row_indices]
sampled_embs = normalise_rows(sampled_embs)
eigenvals, _ = spectral_decomp_gram_matrix(sampled_embs)
results += [{
'seed': seed.item(),
'n_size': n_subset,
'max EV': eigenvals[-1].item(),
}]
return pd.DataFrame(results)
def ECE_conf_bin(
confs,
pred_covs,
target_embs,
n_bins: int = 15,
num_clusters: int = 1,
strategy: str = "uniform", # "uniform" or "quantile" (aka "adaptive")
min_n = 2,
):
"""
Compute Expected Calibration Error (ECE).
Parameters
----------
confs_clusters : array-like, shape (N,2)
Predicted confidences with clusters.
labels : array-like, shape (N, D)
True embeddings.
n_bins : int, optional (default=15)
Number of bins for calibration.
strategy : {"uniform", "quantile"}, optional (default="uniform")
- "uniform": equal-width bins over [0,1].
- "quantile": bins chosen by quantiles of confidence (adaptive binning).
Returns
-------
ece : float
Expected Calibration Error using L1 distance: sum_b ( (|acc_b - conf_b|) * (n_b / N) ).
details : dict
Useful per-bin details:
{
"bin_edges": np.ndarray, shape (B+1,),
"bin_count": np.ndarray, shape (B,),
"avg_conf": np.ndarray, shape (B,),
"avg_acc": np.ndarray, shape (B,)
}
"""
if num_clusters > 1:
cov_corr_matrix = pairwise_matrix_cos(pred_covs)
clusters = get_clusters(cov_corr_matrix, num_clusters)
else:
clusters = np.repeat(0, confs.shape[0])
target_embs = normalise_rows(target_embs)
N = confs.shape[0]
# Build bin edges
if strategy == "uniform":
edges = np.linspace(0.0, 1.0, n_bins + 1)
elif strategy in ("quantile", "adaptive"):
# Quantile edges; ensure coverage of [0,1]
q = np.linspace(0.0, 1.0, n_bins + 1)
edges = np.quantile(confs, q)
edges = np.unique(edges) # guard against repeated edges if conf has ties
# Guarantee exact bounds
edges[0] = 0.0
edges[-1] = 1.0
else:
raise ValueError("strategy must be 'uniform' or 'quantile' (alias: 'adaptive').")
# Assign each sample to a bin: digitize with right-closed bins except the last
# np.digitize returns indices in [0, len(edges)-1]; we use edges[1:-1] as split points -> [0, B-1]
bin_ids = np.digitize(confs, edges[1:-1], right=True)
# Per-bin counts and sums
B = len(edges) - 1
bin_count = np.bincount(bin_ids, minlength=B)
sum_conf = np.bincount(bin_ids, weights=confs, minlength=B)
max_EVs = np.zeros((B, 2))
for bin_id in np.unique(bin_ids):
for cluster_id in np.unique(clusters):
mask = (bin_ids==bin_id) & (clusters==cluster_id)
# ignore all target EVs based on less than min_n instances
if np.sum(mask) >= min_n:
selected_embs = target_embs[mask]
eigenvals, _ = spectral_decomp_gram_matrix(selected_embs)
max_EVs[bin_id, 0] += eigenvals[-1].item()
max_EVs[bin_id, 1] += 1
# avoid div by 0
max_EVs = max_EVs[:,0] / np.maximum(max_EVs[:,1], 1)
nonzero = bin_count > 0
avg_conf = np.zeros(B, dtype=float)
avg_conf[nonzero] = sum_conf[nonzero] / bin_count[nonzero]
weights = bin_count.astype(float) / float(N)
ece = np.sum(weights * np.abs(max_EVs - avg_conf))
return ece, {
"bin_edges": edges,
"bin_count": bin_count,
"avg_conf": avg_conf, #Average model confidence within bin
"max_EVs": max_EVs, #Target max EV within bin
}
def get_max_EV(emb_matrix):
"""
emb_matrix shape (samples x dimension)
return: scalar max EV
"""
emb_matrix = normalise_rows(emb_matrix)
eigenvals, _ = spectral_decomp_gram_matrix(emb_matrix)
return eigenvals[-1].item()
def dataset_to_confs_targets(dataset, temp=None):
df_wide = dataset.pivot(index='question_id', columns='answer_id', values='embedding')
cols = df_wide.keys()
df_wide['emb_matrix'] = df_wide.apply(lambda row: np.vstack([row[c] for c in cols]), axis=1)
df_wide['emb_matrix'] = df_wide.apply(lambda row: normalise_rows(row['emb_matrix']), axis=1)
df_wide['EVs'] = df_wide.apply(lambda row: spectral_decomp_gram_matrix(row['emb_matrix'])[0], axis=1)
if temp is not None:
df_wide['EVs'] = df_wide.apply(lambda row: TS_EV(row['EVs'], temp=temp), axis=1)
df_wide['max_EV'] = df_wide.apply(lambda row: row['EVs'][-1].item(), axis=1)
confs = df_wide['max_EV']
n_uniques = np.unique(dataset['question_id']).shape[0]
reps = dataset.shape[0] // n_uniques
target_embs = dataset['gt_embedding'].iloc[::reps]
target_embs = np.stack(target_embs.to_numpy())
return confs, target_embs
def dataset_to_evs_uncertainties(dataset, temp=None):
df_wide = dataset.pivot(index='question_id', columns='answer_id', values='embedding')
cols = df_wide.keys()
n_answers = len(cols)
df_wide['emb_matrix'] = df_wide.apply(lambda row: np.vstack([row[c] for c in cols]), axis=1)
df_wide['emb_matrix'] = df_wide.apply(lambda row: normalise_rows(row['emb_matrix']), axis=1)
df_wide['emb_list'] = df_wide.apply(lambda row: [row[c]/np.linalg.norm(row[c]) for c in cols], axis=1)
df_wide['EVs'] = df_wide.apply(lambda row: spectral_decomp_gram_matrix(row['emb_matrix'])[0], axis=1)
df_wide['EVects'] = df_wide.apply(lambda row: spectral_decomp_gram_matrix(row['emb_matrix'])[1], axis=1)
if temp is not None:
df_wide['EVs'] = df_wide.apply(lambda row: TS_EV(row['EVs'], temp=temp), axis=1)
df_wide['max_EV'] = df_wide.apply(lambda row: row['EVs'][-1].item(), axis=1)
df_wide['VNE'] = df_wide.apply(lambda row: entropy(row['EVs']), axis=1)
def compute_pke_from_eigenvalues_eigenvectors(eigenvals, eigenvecs):
n=len(eigenvals)
matrix = eigenvecs @ np.diag(eigenvals) @ eigenvecs.T
return float((matrix.diagonal().sum() - matrix.sum())/(n*(n-1)))
df_wide['PKE'] = df_wide.apply(lambda row: compute_pke_from_eigenvalues_eigenvectors(row['EVs'], row['EVects']), axis=1)
df_wide['question_id'] = df_wide.index.map(int)
df_wide = df_wide.reset_index(drop=True).sort_values('question_id', ascending=True).reset_index(drop=True)
df_evs = df_wide[['question_id', 'EVs', 'max_EV', 'VNE', 'PKE']]
return df_evs, n_answers
def emb_to_cov_matrix(emb_matrix):
emb_matrix = normalise_rows(emb_matrix.astype(np.float32))
cov_matrix = emb_matrix.T @ emb_matrix/emb_matrix.shape[0]
return cov_matrix
def _compute_one_temp(ev_decomps, target_embs, fuzzy_correctness, temp):
ts_ev_decomps = [(TS_EV(ev[0], temp=temp), ev[1]) for ev in ev_decomps]
xent_losses = np.array([cross_entropy_loss(ts_ev, t_emb) for ts_ev, t_emb in zip(ts_ev_decomps, target_embs)])
entropies = np.array([entropy(ts_ev[0]) for ts_ev in ts_ev_decomps])
confs = np.array([ts_ev[0][-1].item() for ts_ev in ts_ev_decomps])
return {
'risk': xent_losses.mean(),
'risk_std': xent_losses.std(),
'avg_entropy': entropies.mean(),
'avg_entropy_std': entropies.std(),
'ev_auroc': roc_auc_score(fuzzy_correctness, confs),
'ent_auroc': roc_auc_score(fuzzy_correctness, -entropies),
}
def dataset_to_risks(dataset, temps, progress_bar=None):
df_wide = dataset.pivot(index='question_id', columns='answer_id', values='embedding')
cols = df_wide.keys()
n_uniques = np.unique(dataset['question_id']).shape[0]
reps = dataset.shape[0] // n_uniques
df_wide['emb_matrix'] = df_wide.apply(lambda row: np.vstack([row[c] for c in cols]), axis=1)
df_wide['pred_matrix'] = df_wide.apply(lambda row: emb_to_cov_matrix(row['emb_matrix']), axis=1)
df_wide['EV_decomp'] = df_wide.apply(lambda row: np.linalg.eigh(row['pred_matrix']), axis=1)
target_embs = dataset['gt_embedding'].iloc[::reps].reset_index(drop=True).tolist()
df_wide['target_embs'] = target_embs
fuzzy_correctness = dataset['fuzzy_correctness'].iloc[::reps].to_numpy()
ev_decomps = df_wide['EV_decomp'].tolist()
results = {
'risks': [None] * len(temps),
'risks_stds': [None] * len(temps),
'ev_aurocs': [None] * len(temps),
'ent_aurocs': [None] * len(temps),
'avg_entropies': [None] * len(temps),
'avg_entropies_stds': [None] * len(temps),
}
for i, temp in enumerate(temps):
r = _compute_one_temp(ev_decomps, target_embs, fuzzy_correctness, temp)
results['risks'][i] = r['risk']
results['risks_stds'][i] = r['risk_std']
results['avg_entropies'][i] = r['avg_entropy']
results['avg_entropies_stds'][i] = r['avg_entropy_std']
results['ev_aurocs'][i] = r['ev_auroc']
results['ent_aurocs'][i] = r['ent_auroc']
if progress_bar is not None:
progress_bar.update(1)
return results
def dataset_to_cov_matrix(dataset):
df_wide = dataset.pivot(index='question_id', columns='answer_id', values='embedding')
cols = df_wide.keys()
df_wide['emb_matrix'] = df_wide.apply(lambda row: np.vstack([row[c] for c in cols]), axis=1)
pred_matrix = np.array(df_wide.apply(lambda row: emb_to_cov_matrix(row['emb_matrix']), axis=1))
pred_matrix = np.stack(pred_matrix)
return pred_matrix
def load_all_settings(datasets, models, split):
data = {}
for dataset_id, dataset in enumerate(datasets):
data[dataset] = {}
for model_id, model in enumerate(models):
dataframe = load_data(dataset, model, split='validation')
data[dataset][model] = dataframe
return data
def get_clusters(corr_matrix, num_clusters, min_cluster_size=None): #min_n here does not really work.
pdist = spc.distance.pdist(corr_matrix) #Compute pairwise euclidian distances between cosine similarity vectors: Similar similarity vectors <-> both matrices correlate similarly to all other matrices <-> low distance
linkage = spc.linkage(pdist, method='average')
if num_clusters is None:
idx = spc.fcluster(linkage, 0.5 * pdist.max(), criterion='distance')
else:
idx = spc.fcluster(linkage, criterion='maxclust', t=num_clusters)
return idx
def _compute_TS_pair(dataset, model, temps, embedding_model):
dataframe = load_data(dataset, model, split='validation', embedding_model=embedding_model)
risks_dict = dataset_to_risks(dataframe, temps, progress_bar=None)
risks_dict['temps'] = temps
risks_dict['model'] = model
risks_dict['dataset'] = dataset
return risks_dict
def compute_TS_curves(datasets, models, temps, embedding_model='all_mpnet_base_v2', save_results='results/TS_results.json'):
pairs = [(dataset, model) for dataset in datasets for model in models]
results = []
_log(f"compute_TS_curves [{embedding_model}]: {len(pairs)} pairs, {len(temps)} temps")
t0 = time.perf_counter()
n_workers = len(pairs)
blas_threads = max(1, (os.cpu_count() or 1) // n_workers)
_log(f" [{embedding_model}] using {n_workers} workers × {blas_threads} BLAS threads")
with ProcessPoolExecutor(max_workers=n_workers, initializer=_init_worker, initargs=(blas_threads,)) as executor:
futures = {
executor.submit(_compute_TS_pair, dataset, model, temps, embedding_model): (dataset, model)
for dataset, model in pairs
}
with tqdm(total=len(pairs), desc='dataset/model pairs') as pbar:
for future in as_completed(futures):
result = future.result()
results.append(result)
_log(f" [{embedding_model}] finished {result['dataset']}/{result['model']} ({time.perf_counter()-t0:.1f}s elapsed)")
pbar.update(1)
_log(f"compute_TS_curves [{embedding_model}] done in {time.perf_counter()-t0:.1f}s")
if save_results:
pd.DataFrame(results).to_json(save_results)
return results
def plot_auroc_TS_curves(results, unc_type='EV', file_name=None, figsize=(10, 4)):
results = pd.DataFrame(results)
datasets = ['TriviaQA', 'OpenNQ']
models = ['phi_4_mini', 'phi_4', 'llama4_maverick']
n_rows = len(datasets)
n_cols = len(models)
fig, axes = plt.subplots(n_rows, n_cols, figsize=figsize)
for dataset_id, dataset in enumerate(datasets):
for model_id, model in enumerate(models):
selected_instances = results[(results['model']==model)&(results['dataset']==dataset)].reset_index(drop=True)
temps = selected_instances['temps'][0]
if unc_type=='EV':
aurocs = selected_instances['ev_aurocs'][0]
axes[dataset_id][model_id].plot(temps, aurocs, color='blue', linewidth=2)
elif unc_type=='ENT':
aurocs = selected_instances['ent_aurocs'][0]
axes[dataset_id][model_id].plot(temps, aurocs, color='blue', linewidth=2)
axes[dataset_id][model_id].set_xscale("log")
if dataset_id < 1:
axes[dataset_id][model_id].set_title(model)
if dataset_id==len(datasets)-1:
axes[dataset_id][model_id].set_xlabel('Temperature')
if model_id < 1:
axes[dataset_id][model_id].set_ylabel(DATASET_TO_NAME[dataset])
plt.tight_layout()
if file_name is not None:
plt.savefig('figures/'+file_name, dpi=300, bbox_inches="tight")
plt.show();
def matrix_cos_sim(A, B):
"""only used for unit testing the next function"""
AB_prod = np.trace(A @ B)
l2_A = np.sqrt(np.trace(A@A))
l2_B = np.sqrt(np.trace(B@B))
return AB_prod / (l2_A * l2_B)
# # unit test
# A = np.array([[0., 1., 3.], [1., 0., 2.], [3., 2., 0.]])
# B = np.array([[1., 1., 0.], [1., 1., 2.], [0., 2., 1.]])
# D = np.array([A,B])
# sim1 = matrix_cos_sim(A,B)
# sim2 = pairwise_matrix_cos(D)
# print(sim1, sim2)
def pairwise_matrix_cos(mats):
N = mats.shape[0]
# Reshape matrices into vectors of length (m*n)
vecs = mats.reshape(N, -1) # shape (N, m*n)
# Pairwise Frobenius inner products = Gram matrix
G = vecs @ vecs.T
# Norms of each matrix (Frobenius norm)
norms = np.linalg.norm(vecs, axis=1)
# Normalized Frobenius inner product (cosine similarity)
cosine_sim = G / np.outer(norms, norms)
return cosine_sim
from sklearn.cluster import AgglomerativeClustering
from sklearn.metrics.pairwise import cosine_similarity
def cluster_by_cosine_similarity(embeddings, n_clusters=5):
"""
Cluster data instances based on cosine similarity.
Parameters
----------
embeddings : ndarray, shape (N, D)
Rows are data instances, columns are embedding dimensions.
n_clusters : int
Desired number of clusters.
Returns
-------
labels : ndarray, shape (N,)
Cluster assignment for each instance.
similarity_matrix : ndarray, shape (N, N)
Pairwise cosine similarity matrix.
"""
embeddings = np.asarray(embeddings)
# Compute cosine similarity matrix
sim_matrix = cosine_similarity(embeddings)
# Convert similarity to distance (AgglomerativeClustering uses distance)
dist_matrix = 1.0 - sim_matrix
# Use "metric" instead of "affinity" in new versions
clustering = AgglomerativeClustering(
n_clusters=n_clusters,
metric="precomputed",
linkage="average"
)
labels = clustering.fit_predict(dist_matrix)
return labels, sim_matrix
# # -------------------
# # Example usage:
# # Suppose we have 6 samples with 3D embeddings
# embeddings = np.random.randn(6, 3)
# labels, sim = cluster_by_cosine_similarity(embeddings, n_clusters=2)
# print("Cluster labels:", labels)
# print("Cosine similarity matrix:\n", sim)
# from functions import dataset_to_confs_targets, dataset_to_cov_matrix, pairwise_matrix_cos, get_clusters, balanced_kmeans
def ECE_conf_bin_alt(
confs,
pred_covs,
target_embs,
n_bins: int = 15,
num_clusters: int = 10,
min_n = 5,
cluster_func=get_clusters
):
"""
Compute Expected Calibration Error (ECE).
Parameters
----------
confs_clusters : array-like, shape (N,2)
Predicted confidences with clusters.
labels : array-like, shape (N, D)
True embeddings.
n_bins : int, optional (default=15)
Number of bins for calibration.
Returns
-------
ece : float
Expected Calibration Error using L1 distance: sum_b ( (|acc_b - conf_b|) * (n_b / N) ).
details : dict
Useful per-bin details:
{
"bin_edges": np.ndarray, shape (B+1,),
"bin_count": np.ndarray, shape (B,),
"avg_conf": np.ndarray, shape (B,),
"avg_acc": np.ndarray, shape (B,)
}
"""
target_embs = normalise_rows(target_embs)
N = confs.shape[0]
# Quantile edges; ensure coverage of [0,1]
q = np.linspace(0.0, 1.0, n_bins + 1)
edges = np.quantile(confs, q)
edges = np.unique(edges) # guard against repeated edges if conf has ties
# Guarantee exact bounds
edges[0] = 0.0
edges[-1] = 1.0
# Assign each sample to a bin: digitize with right-closed bins except the last
# np.digitize returns indices in [0, len(edges)-1]; we use edges[1:-1] as split points -> [0, B-1]
bin_ids = np.digitize(confs, edges[1:-1], right=True)
# Per-bin counts and sums
B = len(edges) - 1
bin_count = np.bincount(bin_ids, minlength=B)
sum_conf = np.bincount(bin_ids, weights=confs, minlength=B)
max_EVs = np.zeros((B, 2))
for bin_id in np.unique(bin_ids): #Bin then cluster
bin_covs = pred_covs[bin_ids==bin_id]
bin_confs = confs[bin_ids==bin_id]
bin_targets = target_embs[bin_ids==bin_id]
cov_corr_matrix = pairwise_matrix_cos(bin_covs)
clusters = cluster_func(cov_corr_matrix, num_clusters, min_n)
for cluster_id in np.unique(clusters):
if np.sum(clusters==cluster_id) >= min_n: #If cluster does not have enough instances, ignore
selected_targets = bin_targets[clusters==cluster_id]
eigenvals, _ = spectral_decomp_gram_matrix(selected_targets)
max_EVs[bin_id, 0] += eigenvals[-1].item() #Running sum of max EVs
max_EVs[bin_id, 1] += 1 #Running number of clusters considered within bin
# avoid div by 0
max_EVs = max_EVs[:,0] / np.maximum(max_EVs[:,1], 1) #Bins with no clusters considered will have max_EV=0 (this usually doesn't happen with quantile binning, but depends also on the clustering algorithm)
nonzero = bin_count > 0
avg_conf = np.zeros(B, dtype=float)
avg_conf[nonzero] = sum_conf[nonzero] / bin_count[nonzero] #Average model confidence within bin
weights = bin_count.astype(float) / float(N)
ece = np.sum(weights * np.abs(max_EVs - avg_conf))
return ece, {
"bin_edges": edges,
"bin_count": bin_count,
"avg_conf": avg_conf, #Average model confidence within bin
"max_EVs": max_EVs, #Target max EV within bin
}
def plot_single_rel_diag(confs, max_EVs, freq, ece_results, figsize=(2.5, 2), font_size=10, title=None, file_name='rel_diagram_bincluster_trivia_phi4mini.png'):
fig, axes = plt.subplots(1, 1, figsize=figsize)
plot_rel_diag(confs, max_EVs, freq, ece_results, axes, bin_type='bin2cluster', legend=False)
plt.xlabel('Predicted eigenvalue', fontsize=font_size)
plt.ylabel('Target eigenvalue', fontsize=font_size)
plt.xticks(fontsize=font_size)
plt.yticks(fontsize=font_size)
plt.title(title)
plt.tight_layout()
plt.savefig('figures/'+file_name, dpi=300, bbox_inches="tight")
plt.show();
def get_hdbscan_cluster(corr, num_cluster, min_cluster_size):
# Convert to distance matrix
corr = np.minimum(corr, 1)
dist = np.sqrt(4 * (1 - corr))
dist = dist.astype(np.float64)
# Run HDBSCAN (minimum cluster size = 3)
clusterer = hdbscan.HDBSCAN(min_cluster_size=min_cluster_size, metric='precomputed')
labels = clusterer.fit_predict(dist)
return labels
def _init_worker(num_threads=1):
threadpool_limits(num_threads)
def _log(msg):
print(f"[{time.strftime('%H:%M:%S')}] {msg}", flush=True)
def _preprocess_pair(dataset, model, TS_dict, split, embedding_model, correctness_type):
dataframe = load_data(dataset, model, split=split, embedding_model=embedding_model)
df_wide = dataframe.pivot(index='question_id', columns='answer_id', values='embedding')
cols = df_wide.keys()
n_uniques = np.unique(dataframe['question_id']).shape[0]
reps = dataframe.shape[0] // n_uniques
df_wide['emb_matrix'] = df_wide.apply(lambda row: np.vstack([row[c] for c in cols]), axis=1)
df_wide['pred_matrix'] = df_wide.apply(lambda row: emb_to_cov_matrix(row['emb_matrix']), axis=1)
df_wide['EV_decomp'] = df_wide.apply(lambda row: np.linalg.eigh(row['pred_matrix']), axis=1)
if correctness_type == 'fuzzy_correctness':
if 'fuzzy_correctness_y' in dataframe.keys():
correctness_key = 'fuzzy_correctness_y'
elif 'fuzzy_correctness' in dataframe.keys():
correctness_key = 'fuzzy_correctness'
elif correctness_type == 'model_correctness':
correctness_key = 'model_correctness'
else:
raise ValueError("correctness_type must be 'fuzzy_correctness' or 'model_correctness'")
correctness = dataframe[correctness_key].iloc[::reps].to_numpy()
target_embs = dataframe['gt_embedding'].iloc[::reps]
df_wide['target_embs'] = target_embs.reset_index(drop=True)
temp = TS_dict[dataset][model] if TS_dict is not None else None
df_wide['TS_EV_decomp'] = df_wide.apply(
lambda row: (TS_EV(row['EV_decomp'][0], temp=temp), row['EV_decomp'][1]), axis=1
)
df_wide['entropy'] = df_wide.apply(lambda row: entropy(np.maximum(row['EV_decomp'][0], 0)), axis=1)
df_wide['TS_entropy'] = df_wide.apply(
lambda row: entropy(np.maximum(row['TS_EV_decomp'][0], 0)), axis=1
)
confs = df_wide.apply(lambda row: row['EV_decomp'][0][-1].item(), axis=1).to_numpy()
TS_confs = df_wide.apply(lambda row: row['TS_EV_decomp'][0][-1].item(), axis=1).to_numpy()
ents = (-1) * df_wide['entropy'].to_numpy()
TS_ents = (-1) * df_wide['TS_entropy'].to_numpy()
return dataset, model, correctness, confs, TS_confs, ents, TS_ents
def _auroc_one_seed(dataset, model, seed, correctness, confs, TS_confs, ents, TS_ents):
np.random.seed(seed)
sample_idx = np.random.choice(confs.shape[0], size=confs.shape[0], replace=True)
sampled_corrects = correctness[sample_idx]
return {
'dataset': dataset, 'model': model, 'seed': seed,
'ev_auroc': roc_auc_score(sampled_corrects, confs[sample_idx]),
'TS_ev_auroc': roc_auc_score(sampled_corrects, TS_confs[sample_idx]),
'ent_auroc': roc_auc_score(sampled_corrects, ents[sample_idx]),
'TS_ent_auroc': roc_auc_score(sampled_corrects, TS_ents[sample_idx]),
}
def auroc_experiments(datasets, models, TS_dict, n_bootstrap, split='test', embedding_model='all_mpnet_base_v2', correctness_type='fuzzy_correctness'):
pairs = [(dataset, model) for dataset in datasets for model in models]
total_tasks = len(pairs) * n_bootstrap
_log(f"auroc_experiments: {len(pairs)} pairs, {n_bootstrap} bootstrap seeds, split={split}")
t_total = time.perf_counter()
with ProcessPoolExecutor(max_workers=len(pairs), initializer=_init_worker) as executor:
# Phase 1: preprocess all (dataset, model) pairs in parallel
_log(f"Phase 1 start — preprocessing {len(pairs)} pairs in parallel")
t1 = time.perf_counter()
prep_futures = {
executor.submit(_preprocess_pair, dataset, model, TS_dict, split, embedding_model, correctness_type): (dataset, model)
for dataset, model in pairs
}
preprocessed = {}
with tqdm(total=len(pairs), desc='preprocessing pairs') as pbar:
for future in as_completed(prep_futures):
dataset, model, correctness, confs, TS_confs, ents, TS_ents = future.result()
preprocessed[(dataset, model)] = (correctness, confs, TS_confs, ents, TS_ents)
_log(f" finished {dataset}/{model} ({time.perf_counter()-t1:.1f}s elapsed)")
pbar.update(1)
_log(f"Phase 1 done in {time.perf_counter()-t1:.1f}s")
# Phase 2: run all (pair, seed) combinations in parallel
_log(f"Phase 2 start — {total_tasks} bootstrap tasks ({len(pairs)} pairs × {n_bootstrap} seeds)")
t2 = time.perf_counter()
seed_futures = [
executor.submit(_auroc_one_seed, dataset, model, seed, *preprocessed[(dataset, model)])
for dataset, model in pairs
for seed in range(n_bootstrap)
]
results = []
with tqdm(total=total_tasks, desc='bootstrap seeds') as pbar:
for future in as_completed(seed_futures):
results.append(future.result())
pbar.update(1)
_log(f"Phase 2 done in {time.perf_counter()-t2:.1f}s")
_log(f"Total time: {time.perf_counter()-t_total:.1f}s")
return pd.DataFrame(results)
def compute_rel_diag(dataset, model, temp, bin_type='uniform', min_n=2, num_clusters=1,
num_bins=15, split='test', embedding_model='all_mpnet_base_v2', baseline = False, baseline_temperature_index=0):
dataframe = load_data(dataset, model, split=split, embedding_model=embedding_model, baseline=baseline, baseline_temperature_index=baseline_temperature_index)
confs, target_embs = dataset_to_confs_targets(dataframe, temp=temp)
cov_mats = dataset_to_cov_matrix(dataframe)
if bin_type=='bin2cluster':
ece_result = ECE_conf_bin_alt(
confs, cov_mats, target_embs, min_n=min_n, num_clusters=num_clusters, n_bins=num_bins,
cluster_func=get_clusters
)
counts = ece_result[1]['bin_count']
elif bin_type=='bin2hdbscan':
ece_result = ECE_conf_bin_alt(
confs, cov_mats, target_embs, min_n=min_n, num_clusters=num_clusters, n_bins=num_bins,
cluster_func=get_hdbscan_cluster
)
counts = ece_result[1]['bin_count']
else:
ece_result = ECE_conf_bin(
confs, cov_mats, target_embs, strategy=bin_type, min_n=min_n, num_clusters=num_clusters,
n_bins=num_bins
)
counts = ece_result[1]['bin_count']
confs = ece_result[1]['avg_conf']
max_EVs = ece_result[1]['max_EVs']
max_EVs[counts<min_n] = None
freq = counts/counts.sum()
freq[counts<min_n] = None
return confs, max_EVs, freq, ece_result
def plot_rel_diag(confs, max_EVs, freq, ece_result, plot_axis, legend, bin_type='uniform'):
plot_axis.plot(confs, max_EVs, marker='o', label="Target Max EV", color='red')
if bin_type=='uniform' or bin_type=='cluster':
plot_axis.plot(confs, freq, marker='o', label="Bin Freq.", color='orange')
plot_axis.plot([0, 1], [0, 1], linestyle='--', color='gray', label="Perfectly calibrated")
plot_axis.set_xlabel("")
plot_axis.set_ylabel("")
plot_axis.grid(True)
plot_axis.text(
0.05, 0.95, f'ECE:{ece_result[0]:.2f}', transform=plot_axis.transAxes, ha="left", va="top",
)
if legend:
plot_axis.legend(loc="center left", bbox_to_anchor=(1, 0.5))
def get_rel_diag(
dataset, model, temp, plot_axis, legend, bin_type='uniform', min_n=2, num_clusters=1,
num_bins=15, embedding_model='all_mpnet_base_v2'
):
confs, max_EVs, freq, ece_result = compute_rel_diag(
dataset=dataset, model=model, temp=temp, bin_type=bin_type,
min_n=min_n, num_clusters=num_clusters, num_bins=num_bins, embedding_model=embedding_model
)