-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy path_plotter_combined.py
More file actions
2708 lines (2424 loc) · 97.8 KB
/
Copy path_plotter_combined.py
File metadata and controls
2708 lines (2424 loc) · 97.8 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 json
import os
import re
from typing import Any, Dict, List
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from matplotlib.lines import Line2D
from benchmarks._plotter_helper import (
compute_avg_latency_score,
compute_cache_hit_rate_cumulative_list,
compute_cache_hit_rate_score,
compute_error_rate_cumulative_list,
compute_error_rate_score,
compute_false_positive_rate_score,
compute_precision_score,
compute_recall_score,
convert_to_dataframe_from_json_file,
)
def __calculate_mean_and_ci_from_runs(
per_run_values: List[float],
z: float = 1.96,
clamp_min: float | None = None,
clamp_max: float | None = None,
):
"""Calculates mean and confidence interval from a list of per-run metric values."""
if not per_run_values:
return 0.0, 0.0, 0.0
if len(per_run_values) == 1:
mean_val = per_run_values[0]
# Apply clamping even for single value if specified
if clamp_min is not None:
mean_val = max(clamp_min, mean_val)
if clamp_max is not None:
mean_val = min(clamp_max, mean_val)
return mean_val, mean_val, mean_val
mean_val = np.mean(per_run_values)
std_dev = np.std(per_run_values, ddof=1)
sem = std_dev / np.sqrt(len(per_run_values))
ci_low = mean_val - z * sem
ci_up = mean_val + z * sem
if clamp_min is not None:
ci_low = max(clamp_min, ci_low)
mean_val = max(
clamp_min, mean_val
) # Ensure mean is also clamped if interval is
if clamp_max is not None:
ci_up = min(clamp_max, ci_up)
mean_val = min(
clamp_max, mean_val
) # Ensure mean is also clamped if interval is
# Ensure CI bounds don't cross after clamping if mean was outside clamp range initially
if clamp_min is not None and clamp_max is not None:
mean_val = max(clamp_min, min(clamp_max, mean_val))
ci_low = max(clamp_min, min(clamp_max, ci_low))
ci_up = max(clamp_min, min(clamp_max, ci_up))
if (
ci_low > ci_up
): # if clamping pushed lower bound above upper bound (e.g. very wide CI outside narrow clamp)
ci_low = ci_up = mean_val
return mean_val, ci_low, ci_up
def __collect_run_dirs_by_prefix_and_key(
results_dir_path: str, dir_prefix_to_match: str
):
"""
Collects full paths to run directories based on a prefix and extracts a normalized key.
The key is typically a threshold or delta value formatted as a string.
Example: results_dir_path contains "gptcache_0.8_run_1", "gptcache_0.8_run_2".
If dir_prefix_to_match is "gptcache_", it will map {"0.8": [path_to_run1, path_to_run2]}.
"""
mapping: Dict[str, List[str]] = {}
if not os.path.exists(results_dir_path):
return mapping
for dir_name in os.listdir(results_dir_path):
full_dir_path = os.path.join(results_dir_path, dir_name)
if not dir_name.startswith(dir_prefix_to_match) or not os.path.isdir(
full_dir_path
):
continue
name_part_after_prefix = dir_name[
len(dir_prefix_to_match) :
] # e.g., "0.8", "0.01_run_1"
# Attempt to match a floating point number at the beginning of the remaining part.
# This should capture values like "0.8", "0.01", "0.955" etc.
# It handles cases like "0.8_run_1" by only taking "0.8".
match = re.match(r"([0-9]+\.?[0-9]*|[0-9]*\.?[0-9]+)", name_part_after_prefix)
if match:
key_str_from_dir = match.group(1)
try:
float_val = float(key_str_from_dir)
# Normalize the string representation to match keys from data_frames
# e.g., 0.8 -> "0.8", 0.0 -> "0", 0.010 -> "0.01"
normalized_key_str = f"{float_val:.3f}".rstrip("0").rstrip(".")
if not normalized_key_str and float_val == 0: # Handles 0.0 becoming ""
normalized_key_str = "0"
elif (
not normalized_key_str and "." in key_str_from_dir
): # e.g. if input was "0."
normalized_key_str = key_str_from_dir.rstrip("0").rstrip(".")
if not normalized_key_str:
normalized_key_str = "0"
mapping.setdefault(normalized_key_str, []).append(full_dir_path)
except ValueError:
# print(f"Warning: Could not parse float from '{key_str_from_dir}' in dir '{dir_name}'")
continue
# else:
# print(f"Warning: No numeric key found in '{name_part_after_prefix}' for dir '{dir_name}'")
return mapping
def __draw_confidence_series(
x_means: List[float],
y_means: List[float],
x_lower_errors: List[float],
x_upper_errors: List[float],
y_lower_errors: List[float],
y_upper_errors: List[float],
is_multi_run: List[bool],
color: str,
label: str,
marker_size: int,
line_style: str = "-",
line_width: int = 3,
error_bar_alpha: float = 0.6,
error_bar_capsize: int = 4,
error_bar_elinewidth: float = 1.5,
):
"""Plots a series with optional confidence interval error bars."""
if not x_means:
return
plt.plot(
x_means,
y_means,
line_style,
color=color,
linewidth=line_width,
label=label,
zorder=3,
)
for i in range(len(x_means)):
xm, ym = x_means[i], y_means[i]
is_multi = is_multi_run[i]
current_marker_size = 5 if is_multi else marker_size
plt.plot(xm, ym, "o", color=color, markersize=current_marker_size, zorder=10)
if is_multi:
# Prepare error lists for errorbar, ensuring they are 2xN arrays
# xerr should be [[lower_errors], [upper_errors]]
current_x_err = None
if (
x_lower_errors[i] > 1e-9 or x_upper_errors[i] > 1e-9
): # Check for non-zero error
current_x_err = [[x_lower_errors[i]], [x_upper_errors[i]]]
current_y_err = None
if y_lower_errors[i] > 1e-9 or y_upper_errors[i] > 1e-9:
current_y_err = [[y_lower_errors[i]], [y_upper_errors[i]]]
if current_x_err or current_y_err: # Only plot if there is some error
plt.errorbar(
xm,
ym,
xerr=current_x_err,
yerr=current_y_err,
fmt="none",
ecolor=color,
elinewidth=error_bar_elinewidth,
capsize=error_bar_capsize,
alpha=error_bar_alpha,
zorder=5,
)
# Aggregation functions for different metrics
def __aggregate_stats_for_roc(run_dirs: List[str], keep_split: int, z: float = 1.96):
per_run_tpr_values = []
per_run_fpr_values = []
if not run_dirs:
return 0.0, 0.0, 0.0, 0.0, 0.0, 0.0
for rd_path in run_dirs:
run_total_tp = 0
run_total_fn = 0
run_total_fp = 0
run_total_tn = 0
has_data_for_run = False
for file_name in os.listdir(rd_path):
if file_name.startswith("results_") and file_name.endswith(".json"):
file_path = os.path.join(rd_path, file_name)
try:
with open(file_path, "r", encoding="utf-8") as f:
data = json.load(f)
df, _, _ = convert_to_dataframe_from_json_file(
json_data=data, keep_split=keep_split
)
run_total_tp += np.sum(df["tp_list"])
run_total_fn += np.sum(df["fn_list"])
run_total_fp += np.sum(df["fp_list"])
run_total_tn += np.sum(df["tn_list"])
has_data_for_run = True
except Exception:
# print(f"Warning: Error reading/processing {file_path} in __aggregate_stats_for_roc: {e}")
continue
if has_data_for_run:
current_run_tpr = (
run_total_tp / (run_total_tp + run_total_fn)
if (run_total_tp + run_total_fn) > 0
else 0.0
)
current_run_fpr = (
run_total_fp / (run_total_fp + run_total_tn)
if (run_total_fp + run_total_tn) > 0
else 0.0
)
per_run_tpr_values.append(current_run_tpr)
per_run_fpr_values.append(current_run_fpr)
# Calculate mean and CI for TPR
tpr_mean, tpr_ci_low, tpr_ci_up = __calculate_mean_and_ci_from_runs(
per_run_tpr_values, z, clamp_min=0.0, clamp_max=1.0
)
# Calculate mean and CI for FPR
fpr_mean, fpr_ci_low, fpr_ci_up = __calculate_mean_and_ci_from_runs(
per_run_fpr_values, z, clamp_min=0.0, clamp_max=1.0
)
return tpr_mean, tpr_ci_low, tpr_ci_up, fpr_mean, fpr_ci_low, fpr_ci_up
def __aggregate_stats_for_latency_error(run_dirs: List[str], z: float = 1.96):
per_run_error_rate_values = []
per_run_avg_latency_values = []
if not run_dirs:
return 0.0, 0.0, 0.0, 0.0, 0.0, 0.0
for rd_path in run_dirs:
run_total_fp = 0
run_num_samples_for_fp = 0
run_total_latency = 0.0
run_num_latency_samples = 0
has_data_for_run = False
for file_name in os.listdir(rd_path):
if file_name.startswith("results_") and file_name.endswith(".json"):
file_path = os.path.join(rd_path, file_name)
try:
with open(file_path, "r", encoding="utf-8") as f:
data = json.load(f)
df, _, _ = convert_to_dataframe_from_json_file(data)
run_total_fp += np.sum(df["fp_list"])
run_num_samples_for_fp += len(df["fp_list"])
run_total_latency += np.sum(df["latency_vectorq_list"])
run_num_latency_samples += len(df["latency_vectorq_list"])
has_data_for_run = True
except Exception:
# print(f"Warning: Error reading/processing {file_path} in __aggregate_stats_for_latency_error: {e}")
continue
if has_data_for_run:
if run_num_samples_for_fp > 0:
current_run_error_rate = run_total_fp / run_num_samples_for_fp
per_run_error_rate_values.append(current_run_error_rate)
if run_num_latency_samples > 0:
current_run_avg_latency = run_total_latency / run_num_latency_samples
per_run_avg_latency_values.append(current_run_avg_latency)
# Calculate mean and CI for Error Rate
err_mean, err_ci_low, err_ci_up = __calculate_mean_and_ci_from_runs(
per_run_error_rate_values, z, clamp_min=0.0, clamp_max=1.0
)
# Calculate mean and CI for Latency
lat_mean, lat_ci_low, lat_ci_up = __calculate_mean_and_ci_from_runs(
per_run_avg_latency_values, z, clamp_min=0.0
)
return err_mean, err_ci_low, err_ci_up, lat_mean, lat_ci_low, lat_ci_up
def __aggregate_stats_for_cache_hit_error_rate(run_dirs: List[str], z: float = 1.96):
per_run_cache_hit_rate_values = []
per_run_error_rate_values = []
if not run_dirs:
return {
"cache_hit_rate_mean": 0.0,
"cache_hit_rate_ci_low": 0.0,
"cache_hit_rate_ci_up": 0.0,
"error_rate_mean": 0.0,
"error_rate_ci_low": 0.0,
"error_rate_ci_up": 0.0,
}
for rd_path in run_dirs:
run_total_samples_ch = 0
run_total_cache_hits = 0
run_total_samples_er = 0
run_total_fp = 0
has_data_for_run = False
for file_name in os.listdir(rd_path):
if file_name.startswith("results_") and file_name.endswith(".json"):
file_path = os.path.join(rd_path, file_name)
try:
with open(file_path, "r", encoding="utf-8") as f:
data = json.load(f)
df, _, _ = convert_to_dataframe_from_json_file(data)
run_total_samples_ch += len(
df["cache_hit_list"]
) # Or len(df) if more appropriate
run_total_cache_hits += int(np.sum(df["cache_hit_list"]))
run_total_samples_er += len(df["fp_list"]) # Or len(df)
run_total_fp += int(np.sum(df["fp_list"]))
has_data_for_run = True
except Exception:
# print(f"Warning: Error reading/processing {file_path} in __aggregate_stats_for_cache_hit_error_rate: {e}")
continue
if has_data_for_run:
if run_total_samples_ch > 0:
current_run_ch_rate = run_total_cache_hits / run_total_samples_ch
per_run_cache_hit_rate_values.append(current_run_ch_rate)
if run_total_samples_er > 0:
current_run_er_rate = run_total_fp / run_total_samples_er
per_run_error_rate_values.append(current_run_er_rate)
# Calculate mean and CI for Cache Hit Rate
ch_mean, ch_ci_low, ch_ci_up = __calculate_mean_and_ci_from_runs(
per_run_cache_hit_rate_values, z, clamp_min=0.0, clamp_max=1.0
)
# Calculate mean and CI for Error Rate
er_mean, er_ci_low, er_ci_up = __calculate_mean_and_ci_from_runs(
per_run_error_rate_values, z, clamp_min=0.0, clamp_max=1.0
)
return {
"cache_hit_rate_mean": ch_mean,
"cache_hit_rate_ci_low": ch_ci_low,
"cache_hit_rate_ci_up": ch_ci_up,
"error_rate_mean": er_mean,
"error_rate_ci_low": er_ci_low,
"error_rate_ci_up": er_ci_up,
}
# End of new helper functions
def __get_result_files(results_dir: str):
if not os.path.exists(results_dir):
print(f"No results found in {results_dir}")
return [], [], [], [], [], [], []
gptcache_files: List[str] = []
vcache_local_files: List[str] = []
vcache_global_files: List[str] = []
berkeley_embedding_files: List[str] = []
vcache_berkeley_embedding_files: List[str] = []
sigmoid_probability_files: List[str] = []
sigmoid_only_files: List[str] = []
for d in os.listdir(results_dir):
# Process GPTCache (static threshold) directories
if (d.startswith("gptcache_") or d.startswith("static_")) and os.path.isdir(
os.path.join(results_dir, d)
):
dir_path: str = os.path.join(results_dir, d)
for file in os.listdir(dir_path):
if file.startswith("results_") and file.endswith(".json"):
gptcache_files.append(os.path.join(dir_path, file))
# Process vCache local directories
elif (
d.startswith("vcache_local_") or d.startswith("vectorq_local_")
) and os.path.isdir(os.path.join(results_dir, d)):
dir_path: str = os.path.join(results_dir, d)
for file in os.listdir(dir_path):
if file.startswith("results_") and file.endswith(".json"):
vcache_local_files.append(os.path.join(dir_path, file))
# Process vCache global directories
elif (
d.startswith("vcache_global_") or d.startswith("vectorq_global_")
) and os.path.isdir(os.path.join(results_dir, d)):
dir_path: str = os.path.join(results_dir, d)
for file in os.listdir(dir_path):
if file.startswith("results_") and file.endswith(".json"):
vcache_global_files.append(os.path.join(dir_path, file))
# Process Fine-tuned Embedding directories
elif d.startswith("berkeley_embedding_") and os.path.isdir(
os.path.join(results_dir, d)
):
dir_path: str = os.path.join(results_dir, d)
for file in os.listdir(dir_path):
if file.startswith("results_") and file.endswith(".json"):
berkeley_embedding_files.append(os.path.join(dir_path, file))
# Process vCache Fine-tuned Embedding directories
elif d.startswith("vcache_berkeley_embedding_") and os.path.isdir(
os.path.join(results_dir, d)
):
dir_path: str = os.path.join(results_dir, d)
for file in os.listdir(dir_path):
if file.startswith("results_") and file.endswith(".json"):
vcache_berkeley_embedding_files.append(os.path.join(dir_path, file))
# Process Sigmoid Probability directories
elif d.startswith("sigmoid_probability_") and os.path.isdir(
os.path.join(results_dir, d)
):
dir_path: str = os.path.join(results_dir, d)
for file in os.listdir(dir_path):
if file.startswith("results_") and file.endswith(".json"):
sigmoid_probability_files.append(os.path.join(dir_path, file))
# Process Sigmoid Only directories
elif d.startswith("sigmoid_only_") and os.path.isdir(
os.path.join(results_dir, d)
):
dir_path: str = os.path.join(results_dir, d)
for file in os.listdir(dir_path):
if file.startswith("results_") and file.endswith(".json"):
sigmoid_only_files.append(os.path.join(dir_path, file))
return (
gptcache_files,
vcache_local_files,
vcache_global_files,
berkeley_embedding_files,
vcache_berkeley_embedding_files,
sigmoid_probability_files,
sigmoid_only_files,
)
def generate_combined_plots(
dataset: str,
embedding_model_name: str,
llm_model_name: str,
results_dir: str,
timestamp: str,
font_size: int,
keep_split: int = 100,
):
results_dir: str = (
f"{results_dir}/{dataset}/{embedding_model_name}/{llm_model_name}/"
)
(
gptcache_files,
vcache_local_files,
vcache_global_files,
berkeley_embedding_files,
vcache_berkeley_embedding_files,
sigmoid_probability_files,
sigmoid_only_files,
) = __get_result_files(results_dir)
if (
not gptcache_files
and not vcache_local_files
and not vcache_global_files
and not berkeley_embedding_files
and not vcache_berkeley_embedding_files
and not sigmoid_probability_files
and not sigmoid_only_files
):
print(
f"No folders found for {dataset}, {embedding_model_name}, {llm_model_name}\n"
f"in {results_dir}"
)
return
chopped_index = None
############################################################
### Baseline: GPTCache
gptcache_data_frames: Dict[float, pd.DataFrame] = {}
for gptcache_file_path in gptcache_files:
try:
with open(gptcache_file_path, "r") as f:
data: Any = json.load(f)
dataframe, _, chopped_index = convert_to_dataframe_from_json_file(
json_data=data, keep_split=keep_split
)
threshold: float = data["config"]["threshold"]
gptcache_data_frames[threshold] = dataframe
chopped_index = chopped_index
except Exception as e:
print(f"Error loading {gptcache_file_path}: {e}")
continue
############################################################
### Baseline: vCache Local
vcache_local_data_frames: Dict[float, pd.DataFrame] = {}
for vcache_local_file_path in vcache_local_files:
try:
with open(vcache_local_file_path, "r") as f:
data: Any = json.load(f)
dataframe, _, chopped_index = convert_to_dataframe_from_json_file(
json_data=data, keep_split=keep_split
)
delta: float = data["config"]["delta"]
vcache_local_data_frames[delta] = dataframe
chopped_index = chopped_index
except Exception as e:
print(f"Error loading {vcache_local_file_path}: {e}")
continue
############################################################
### Baseline: vCache Global
vcache_global_data_frames: Dict[float, pd.DataFrame] = {}
for vcache_global_file_path in vcache_global_files:
with open(vcache_global_file_path, "r") as f:
try:
data: Any = json.load(f)
dataframe, _, chopped_index = convert_to_dataframe_from_json_file(
json_data=data, keep_split=keep_split
)
delta: float = data["config"]["delta"]
vcache_global_data_frames[delta] = dataframe
chopped_index = chopped_index
except Exception as e:
print(f"Error loading {vcache_global_file_path}: {e}")
continue
############################################################
### Baseline: Fine-tuned Embedding
berkeley_embedding_data_frames: Dict[float, pd.DataFrame] = {}
for berkeley_embedding_file_path in berkeley_embedding_files:
with open(berkeley_embedding_file_path, "r") as f:
try:
data: Any = json.load(f)
dataframe, _, chopped_index = convert_to_dataframe_from_json_file(
json_data=data, keep_split=keep_split
)
threshold: float = data["config"]["threshold"]
berkeley_embedding_data_frames[threshold] = dataframe
chopped_index = chopped_index
except Exception as e:
print(f"Error loading {berkeley_embedding_file_path}: {e}")
continue
############################################################
### vCache + Fine-tuned Embedding
vcache_berkeley_embedding_data_frames: Dict[float, pd.DataFrame] = {}
for vcache_berkeley_embedding_file_path in vcache_berkeley_embedding_files:
with open(vcache_berkeley_embedding_file_path, "r") as f:
try:
data: Any = json.load(f)
dataframe, _, chopped_index = convert_to_dataframe_from_json_file(
json_data=data, keep_split=keep_split
)
delta: float = data["config"]["delta"]
vcache_berkeley_embedding_data_frames[delta] = dataframe
chopped_index = chopped_index
except Exception as e:
print(f"Error loading {vcache_berkeley_embedding_file_path}: {e}")
continue
############################################################
### Sigmoid Probability
sigmoid_probability_data_frames: Dict[float, pd.DataFrame] = {}
for sigmoid_probability_file_path in sigmoid_probability_files:
with open(sigmoid_probability_file_path, "r") as f:
try:
data: Any = json.load(f)
dataframe, _, chopped_index = convert_to_dataframe_from_json_file(
json_data=data, keep_split=keep_split
)
delta: float = data["config"]["delta"]
sigmoid_probability_data_frames[delta] = dataframe
chopped_index = chopped_index
except Exception as e:
print(f"Error loading {sigmoid_probability_file_path}: {e}")
continue
############################################################
### Sigmoid Only
sigmoid_only_data_frames: Dict[float, pd.DataFrame] = {}
for sigmoid_only_file_path in sigmoid_only_files:
with open(sigmoid_only_file_path, "r") as f:
try:
data: Any = json.load(f)
dataframe, _, chopped_index = convert_to_dataframe_from_json_file(
json_data=data, keep_split=keep_split
)
delta: float = data["config"]["delta"]
sigmoid_only_data_frames[delta] = dataframe
chopped_index = chopped_index
except Exception as e:
print(f"Error loading {sigmoid_only_file_path}: {e}")
continue
if chopped_index is None:
print(
f"No data found for {dataset}, {embedding_model_name}, {llm_model_name} in {results_dir}"
)
return
__plot_legend(
gptcache_data_frames=gptcache_data_frames,
vcache_local_data_frames=vcache_local_data_frames,
vcache_global_data_frames=vcache_global_data_frames,
berkeley_embedding_data_frames=berkeley_embedding_data_frames,
vcache_berkeley_embedding_data_frames=vcache_berkeley_embedding_data_frames,
sigmoid_probability_data_frames=sigmoid_probability_data_frames,
sigmoid_only_data_frames=sigmoid_only_data_frames,
results_dir=results_dir,
timestamp=timestamp,
font_size=font_size,
)
try:
__plot_roc(
gptcache_data_frames=gptcache_data_frames,
vcache_local_data_frames=vcache_local_data_frames,
vcache_global_data_frames=vcache_global_data_frames,
berkeley_embedding_data_frames=berkeley_embedding_data_frames,
vcache_berkeley_embedding_data_frames=vcache_berkeley_embedding_data_frames,
results_dir=results_dir,
timestamp=timestamp,
font_size=font_size,
keep_split=keep_split,
chopped_index=chopped_index,
)
except Exception as e:
print(f"Error plotting ROC: {e}")
try:
__plot_precision_vs_recall(
gptcache_data_frames=gptcache_data_frames,
vcache_local_data_frames=vcache_local_data_frames,
vcache_global_data_frames=vcache_global_data_frames,
berkeley_embedding_data_frames=berkeley_embedding_data_frames,
vcache_berkeley_embedding_data_frames=vcache_berkeley_embedding_data_frames,
results_dir=results_dir,
timestamp=timestamp,
font_size=font_size,
chopped_index=chopped_index,
)
except Exception as e:
print(f"Error plotting precision vs recall: {e}")
try:
__plot_avg_latency_vs_error_rate(
gptcache_data_frames=gptcache_data_frames,
vcache_local_data_frames=vcache_local_data_frames,
vcache_global_data_frames=vcache_global_data_frames,
berkeley_embedding_data_frames=berkeley_embedding_data_frames,
vcache_berkeley_embedding_data_frames=vcache_berkeley_embedding_data_frames,
sigmoid_probability_data_frames=sigmoid_probability_data_frames,
sigmoid_only_data_frames=sigmoid_only_data_frames,
results_dir=results_dir,
timestamp=timestamp,
font_size=font_size,
chopped_index=chopped_index,
)
except Exception as e:
print(f"Error plotting avg latency vs error rate: {e}")
try:
__plot_cache_hit_vs_error_rate(
gptcache_data_frames=gptcache_data_frames,
vcache_local_data_frames=vcache_local_data_frames,
vcache_global_data_frames=vcache_global_data_frames,
berkeley_embedding_data_frames=berkeley_embedding_data_frames,
vcache_berkeley_embedding_data_frames=vcache_berkeley_embedding_data_frames,
sigmoid_probability_data_frames=sigmoid_probability_data_frames,
sigmoid_only_data_frames=sigmoid_only_data_frames,
results_dir=results_dir,
timestamp=timestamp,
font_size=font_size,
chopped_index=chopped_index,
)
except Exception as e:
print(f"Error plotting cache hit vs error rate: {e}")
try:
__plot_cache_hit_vs_error_rate_vs_sample_size(
gptcache_data_frames=gptcache_data_frames,
vcache_local_data_frames=vcache_local_data_frames,
vcache_global_data_frames=vcache_global_data_frames,
berkeley_embedding_data_frames=berkeley_embedding_data_frames,
vcache_berkeley_embedding_data_frames=vcache_berkeley_embedding_data_frames,
results_dir=results_dir,
timestamp=timestamp,
font_size=font_size,
keep_split=keep_split,
chopped_index=chopped_index,
)
except Exception as e:
print(f"Error plotting cache hit vs error rate vs sample size: {e}")
try:
__plot_delta_accuracy(
vcache_local_data_frames=vcache_local_data_frames,
vcache_global_data_frames=vcache_global_data_frames,
vcache_berkeley_embedding_data_frames=vcache_berkeley_embedding_data_frames,
results_dir=results_dir,
timestamp=timestamp,
font_size=font_size,
chopped_index=chopped_index,
)
except Exception as e:
print(f"Error plotting delta accuracy: {e}")
def __plot_legend(
gptcache_data_frames: Dict[float, pd.DataFrame],
vcache_local_data_frames: Dict[float, pd.DataFrame],
vcache_global_data_frames: Dict[float, pd.DataFrame],
berkeley_embedding_data_frames: Dict[float, pd.DataFrame],
vcache_berkeley_embedding_data_frames: Dict[float, pd.DataFrame],
sigmoid_probability_data_frames: Dict[float, pd.DataFrame],
sigmoid_only_data_frames: Dict[float, pd.DataFrame],
results_dir: str,
timestamp: str,
font_size: int,
):
figlegend = plt.figure(figsize=(12, 1.5))
ax = figlegend.add_subplot(111)
ax.axis("off")
lines = []
labels = []
if gptcache_data_frames:
lines.append(
Line2D(
[0],
[0],
color="#C23B48",
linewidth=3,
linestyle="-",
marker="o",
markersize=8,
)
)
labels.append("GPTCache")
if vcache_local_data_frames:
lines.append(
Line2D(
[0],
[0],
color="#37A9EC",
linewidth=3,
linestyle="-",
marker="o",
markersize=8,
)
)
labels.append("vCache")
if vcache_global_data_frames:
lines.append(
Line2D(
[0],
[0],
color="#8CBE94",
linewidth=3,
linestyle="-",
marker="o",
markersize=8,
)
)
labels.append("vCache (Ablation)")
if vcache_berkeley_embedding_data_frames:
lines.append(
Line2D(
[0],
[0],
color="#EDBE24",
linewidth=3,
linestyle="-",
marker="o",
markersize=8,
)
)
labels.append("vCache + Fine-tuned Embedding")
if berkeley_embedding_data_frames:
lines.append(
Line2D(
[0],
[0],
color="#3B686A",
linewidth=3,
linestyle="-",
marker="o",
markersize=8,
)
)
labels.append("Fine-tuned Embedding")
if sigmoid_probability_data_frames:
lines.append(
Line2D(
[0],
[0],
color="#89D572",
linewidth=3,
linestyle="-",
marker="o",
markersize=8,
)
)
labels.append("Sigmoid Probability")
if sigmoid_only_data_frames:
lines.append(
Line2D(
[0],
[0],
color="#E2A043",
linewidth=3,
linestyle="-",
marker="o",
markersize=8,
)
)
labels.append("Sigmoid Only")
ax.legend(lines, labels, loc="center", ncol=2, fontsize=font_size, frameon=False)
legend_filename = results_dir + "/legend.pdf"
figlegend.savefig(
legend_filename, format="pdf", bbox_inches="tight", transparent=True
)
plt.close(figlegend)
lines.append(Line2D([0], [0], color="grey", linewidth=3, linestyle="--", alpha=0.7))
labels.append("Random Classifier")
lines.append(Line2D([0], [0], color="grey", linewidth=3, linestyle="-"))
labels.append("No Cache")
ax.legend(lines, labels, loc="center", ncol=3, fontsize=font_size, frameon=False)
legend_filename = results_dir + "/legend_w_rnd_class.pdf"
figlegend.savefig(
legend_filename, format="pdf", bbox_inches="tight", transparent=True
)
plt.close(figlegend)
def __plot_roc(
gptcache_data_frames: Dict[float, pd.DataFrame],
vcache_local_data_frames: Dict[float, pd.DataFrame],
vcache_global_data_frames: Dict[float, pd.DataFrame],
berkeley_embedding_data_frames: Dict[float, pd.DataFrame],
vcache_berkeley_embedding_data_frames: Dict[float, pd.DataFrame],
results_dir: str,
timestamp: str,
font_size: int,
keep_split: int,
chopped_index: int,
):
plt.figure(figsize=(12, 10))
# Collect all run directories once
# base_results_dir = os.path.dirname(results_dir.rstrip('/')) # Get parent of timestamped dir if any
# Or, if results_dir is the one containing gptcache_X.Y folders:
# base_results_dir = results_dir # This should be correct based on how results_dir is constructed
gptcache_run_dirs_map = __collect_run_dirs_by_prefix_and_key(
results_dir, "gptcache_"
)
vcache_local_run_dirs_map = __collect_run_dirs_by_prefix_and_key(
results_dir, "vcache_local_"
)
vcache_global_run_dirs_map = __collect_run_dirs_by_prefix_and_key(
results_dir, "vcache_global_"
)
berkeley_embedding_run_dirs_map = __collect_run_dirs_by_prefix_and_key(
results_dir, "berkeley_embedding_"
)
vcache_berkeley_embedding_run_dirs_map = __collect_run_dirs_by_prefix_and_key(
results_dir, "vcache_berkeley_embedding_"
)
plt.plot(
[0, 1],
[0, 1],
"--",
color="grey",
alpha=0.7,
linewidth=3,
label="Random Classifier",
)
# Helper to prepare data for a series
def prepare_roc_series_data(data_frames, run_dirs_map_for_series, keep_split: int):
thresholds_or_deltas = sorted(data_frames.keys())
tpr_means, fpr_means = [], []
tpr_low_err, tpr_up_err = [], []
fpr_low_err, fpr_up_err = [], []
is_multi = []
for key_val in thresholds_or_deltas:
key_str = f"{key_val:.3f}".rstrip("0").rstrip(".")
if not key_str and key_val == 0:
key_str = "0"
current_run_dirs = run_dirs_map_for_series.get(key_str, [])
if len(current_run_dirs) > 1: # Multi-run
tpr_m, tpr_l, tpr_u, fpr_m, fpr_l, fpr_u = __aggregate_stats_for_roc(
run_dirs=current_run_dirs, keep_split=keep_split
)
tpr_means.append(tpr_m)
fpr_means.append(fpr_m)
tpr_low_err.append(tpr_m - tpr_l)
tpr_up_err.append(tpr_u - tpr_m)
fpr_low_err.append(fpr_m - fpr_l)
fpr_up_err.append(fpr_u - fpr_m)
is_multi.append(True)
elif (
data_frames
): # Single run (or fallback to single file if no dirs found but df exists)
df = data_frames[key_val]
tpr_m = compute_recall_score(tp=df["tp_list"], fn=df["fn_list"])
fpr_m = compute_false_positive_rate_score(
fp=df["fp_list"], tn=df["tn_list"]
)
tpr_means.append(tpr_m)
fpr_means.append(fpr_m)
tpr_low_err.append(0)
tpr_up_err.append(0)
fpr_low_err.append(0)
fpr_up_err.append(0)
is_multi.append(False)
# Ensure errors are non-negative
tpr_low_err = [max(0, err) for err in tpr_low_err]
tpr_up_err = [max(0, err) for err in tpr_up_err]
fpr_low_err = [max(0, err) for err in fpr_low_err]
fpr_up_err = [max(0, err) for err in fpr_up_err]
return (
fpr_means,
tpr_means,
fpr_low_err,
fpr_up_err,
tpr_low_err,
tpr_up_err,
is_multi,
)
############################################################
### Baseline: GPTCache
if gptcache_data_frames:
gpt_fpr, gpt_tpr, gpt_fpr_le, gpt_fpr_ue, gpt_tpr_le, gpt_tpr_ue, gpt_multi = (
prepare_roc_series_data(
data_frames=gptcache_data_frames,
run_dirs_map_for_series=gptcache_run_dirs_map,
keep_split=keep_split,
)
)
__draw_confidence_series(
gpt_fpr,
gpt_tpr,
gpt_fpr_le,
gpt_fpr_ue,
gpt_tpr_le,