-
Notifications
You must be signed in to change notification settings - Fork 7
/
new_plots.py
1758 lines (1447 loc) · 66.1 KB
/
new_plots.py
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 numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from pathlib import Path
from typing import Dict, List, Tuple, NamedTuple, Set
from clusters import question_w_clusters, wordcel_questions, shape_rotator_questions
from question_list import questions
from collections import defaultdict
from model_list import lmsys_scores, release_dates, model_scales, model_prices
from scipy import stats
import adjustText
from datetime import datetime, timedelta
import matplotlib.dates as mdates
import csv
import pandas as pd
import textwrap
# Define company colors
COMPANY_COLORS = {
'openai': '#74AA9C', # OpenAI green
'meta-llama': '#044EAB', # Meta blue
'anthropic': '#D4C5B9', # Anthropic beige
'google': '#669DF7', # Google blue
'x-ai': '#000000', # X black
'mistralai': '#F54E42' # Mistral red
}
# Add these constants at the top with other constants
PAPER_FONT_SIZE = 12 # Base font size for paper
PAPER_TITLE_SIZE = 14 # Title font size
PAPER_LABEL_SIZE = 10 # Label font size for bars/points
FIGURE_WIDTH = 10 # Standard figure width for paper
FIGURE_HEIGHT = 6 # Base figure height (will be adjusted based on content)
def _set_paper_style():
"""Configure plot style for academic paper presentation."""
plt.style.use('seaborn-v0_8-paper')
plt.rcParams.update({
'font.size': PAPER_FONT_SIZE,
'axes.labelsize': PAPER_FONT_SIZE,
'axes.titlesize': PAPER_TITLE_SIZE,
'xtick.labelsize': PAPER_FONT_SIZE,
'ytick.labelsize': PAPER_FONT_SIZE,
'legend.fontsize': PAPER_FONT_SIZE,
'figure.titlesize': PAPER_TITLE_SIZE,
'figure.dpi': 300,
'savefig.dpi': 300,
'savefig.bbox': 'tight',
'savefig.pad_inches': 0.1
})
class ModelMetrics(NamedTuple):
embedding_total: float
coherence_total: float
valid_answers: int
def load_results(file_path: str) -> dict:
"""Load results from JSON file."""
with open(file_path, 'r') as f:
return json.load(f)
def calculate_metrics(results: dict,
min_embedding_threshold: float = 0.15,
min_coherence_threshold: float = 15.0) -> Dict[str, Dict[str, ModelMetrics]]:
"""Calculate metrics for each model at each temperature setting."""
metrics = {}
for model_name, temp_data in results['models'].items():
metrics[model_name] = {}
for temp, questions in temp_data.items():
embedding_total = 0
coherence_total = 0
valid_answers = 0
for question, answers in questions.items():
for answer in answers:
if (answer['embedding_dissimilarity_score'] >= min_embedding_threshold and
answer['coherence_score'] >= min_coherence_threshold):
embedding_total += answer['embedding_dissimilarity_score']
coherence_total += answer['coherence_score'] / 100 # Divide coherence by 100
valid_answers += 1
metrics[model_name][temp] = ModelMetrics(
embedding_total=embedding_total,
coherence_total=coherence_total,
valid_answers=valid_answers
)
return metrics
def plot_metric(metrics: Dict[str, Dict[str, ModelMetrics]],
metric_name: str,
metric_getter,
output_dir: str,
figure_name: str,
ylabel: str,
format_value=lambda x: f"{x:.2f}",
paper_ready=True,
color_by_company=True
) -> None:
"""Create a vertical bar plot for the specified metric, sorted by value."""
_set_paper_style()
models = list(metrics.keys())
temps = list(metrics[models[0]].keys())
# Calculate max value for each model for ranking
max_values = {model: max(metric_getter(temp_metrics)
for temp_metrics in temp_data.values())
for model, temp_data in metrics.items()}
# Sort models by their max values
sorted_models = sorted(models, key=lambda x: max_values[x], reverse=True)
# Set up the plot with adjusted dimensions
plt.figure(figsize=(FIGURE_WIDTH, max(FIGURE_HEIGHT * 1.2, len(models) * 0.4)))
# Calculate bar positions
bar_width = 0.8 / len(temps)
positions_base = np.arange(len(models))
# Create bars for each temperature
for i, temp in enumerate(temps):
positions = positions_base + i * bar_width
values = [metric_getter(metrics[model][temp]) for model in sorted_models]
if color_by_company:
# Create bars with company-specific colors
for pos, val, model in zip(positions, values, sorted_models):
company = model.split('/')[0]
bar = plt.bar(pos, val, bar_width,
color=COMPANY_COLORS[company],
alpha=0.8)
# Add value label
plt.text(pos, val + max(values) * 0.01, # Slight offset above bar
format_value(val),
ha='center',
va='bottom',
rotation=45,
fontsize=PAPER_LABEL_SIZE)
else:
# Create bars with default coloring
container = plt.bar(positions, values, bar_width,
label=f'Temperature {temp}' if not paper_ready else None,
alpha=0.8)
# Add value labels
for rect, val in zip(container, values):
plt.text(rect.get_x() + rect.get_width()/2, val + max(values) * 0.01,
format_value(val),
ha='center',
va='bottom',
rotation=45,
fontsize=PAPER_LABEL_SIZE)
# Customize the plot
plt.xlabel('Models')
plt.ylabel(ylabel)
if paper_ready:
plt.title(f'{metric_name} by Model')
else:
plt.title(f'{metric_name} by Model and Temperature\n(Filtered for embedding ≥ 0.15 and coherence ≥ 15)')
# Position model names
plt.xticks(positions_base + (bar_width * (len(temps) - 1)) / 2,
[m.split('/')[-1] for m in sorted_models],
rotation=45,
ha='right')
# Add legend
if color_by_company:
# Add company color legend
legend_elements = [plt.Rectangle((0,0),1,1, facecolor=color, label=company)
for company, color in COMPANY_COLORS.items()]
plt.legend(handles=legend_elements,
bbox_to_anchor=(1.05, 1),
loc='upper left')
elif not paper_ready:
plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')
# Add grid and adjust layout
plt.grid(True, alpha=0.3, axis='y')
plt.tight_layout()
# Ensure there's enough space at the top for labels
plt.margins(y=0.15)
# Save the plot
plt.savefig(Path(output_dir) / figure_name, dpi=300, bbox_inches='tight')
plt.close()
def analyze_benchmark(file_path: str,
output_dir: str = 'plots',
min_embedding_threshold: float = 0.15,
min_coherence_threshold: float = 15.0) -> Dict[str, Dict[str, ModelMetrics]]:
"""Main function to analyze benchmark results and generate plots."""
results = load_results(file_path)
metrics = calculate_metrics(
results,
min_embedding_threshold=min_embedding_threshold,
min_coherence_threshold=min_coherence_threshold
)
Path(output_dir).mkdir(parents=True, exist_ok=True)
# Add this line to generate the new results plot
plot_results(metrics, output_dir)
# Rest of your existing plot generations...
plot_metric(
metrics,
"Total Embedding Dissimilarity",
lambda x: x.embedding_total,
output_dir,
'embedding_scores.png',
'Total Embedding Dissimilarity Score',
lambda x: f"{x:.2f}"
)
# ... (rest of the function remains the same)
#####
def get_cluster_questions(cluster: str, questions_data: List[dict]) -> Set[str]:
"""Get all questions belonging to a specific cluster."""
return {q['question'] for q in questions_data if cluster in q['clusters']}
def calculate_cluster_metrics(results: dict,
cluster_questions: Set[str],
min_embedding_threshold: float = 0.15,
min_coherence_threshold: float = 15.0) -> Dict[str, Dict[str, ModelMetrics]]:
"""Calculate metrics for each model at each temperature setting for specific cluster questions."""
metrics = {}
for model_name, temp_data in results['models'].items():
metrics[model_name] = {}
for temp, questions in temp_data.items():
embedding_total = 0
coherence_total = 0
valid_answers = 0
# Only process questions that belong to the cluster
for question in cluster_questions:
if question in questions:
for answer in questions[question]:
if (answer['embedding_dissimilarity_score'] >= min_embedding_threshold and
answer['coherence_score'] >= min_coherence_threshold):
embedding_total += answer['embedding_dissimilarity_score']
coherence_total += answer['coherence_score'] / 100
valid_answers += 1
metrics[model_name][temp] = ModelMetrics(
embedding_total=embedding_total,
coherence_total=coherence_total,
valid_answers=valid_answers
)
return metrics
def plot_cluster_metrics(results: dict,
questions_data: List[dict],
clusters: List[str],
output_dir: str = 'plots',
min_embedding_threshold: float = 0.15,
min_coherence_threshold: float = 15.0) -> None:
"""Generate plots for each cluster."""
# Create cluster-specific directory
cluster_dir = Path(output_dir) / 'clusters'
cluster_dir.mkdir(parents=True, exist_ok=True)
# Process each cluster
for cluster in clusters:
print(f"Processing cluster: {cluster}")
# Get questions for this cluster
cluster_questions = get_cluster_questions(cluster, questions_data)
# Skip if no questions in cluster
if not cluster_questions:
print(f"No questions found for cluster: {cluster}")
continue
# Calculate metrics for this cluster
metrics = calculate_cluster_metrics(
results,
cluster_questions,
min_embedding_threshold,
min_coherence_threshold
)
# Create cluster-specific subdirectory
cluster_subdir = cluster_dir / cluster.lower().replace(' ', '_')
cluster_subdir.mkdir(parents=True, exist_ok=True)
# Generate the three plots for this cluster
plot_metric(
metrics,
f"Total Embedding Dissimilarity - {cluster}",
lambda x: x.embedding_total,
cluster_subdir,
'embedding_scores.png',
'Total Embedding Dissimilarity Score',
lambda x: f"{x:.2f}"
)
plot_metric(
metrics,
f"Total Coherence Score - {cluster}",
lambda x: x.coherence_total,
cluster_subdir,
'coherence_scores.png',
'Total Coherence Score',
lambda x: f"{x:.2f}"
)
plot_metric(
metrics,
f"Number of Valid Responses - {cluster}",
lambda x: x.valid_answers,
cluster_subdir,
'valid_responses.png',
'Number of Valid Responses',
lambda x: f"{int(x)}"
)
def analyze_clusters(results_file: str,
questions_data: List[dict], # Now takes Python list directly
output_dir: str = 'plots',
min_embedding_threshold: float = 0.15,
min_coherence_threshold: float = 15.0) -> None:
"""Main function to analyze benchmark results by clusters."""
# Load results
with open(results_file, 'r') as f:
results = json.load(f)
# Extract unique clusters
clusters = set()
for question in questions_data:
clusters.update(question['clusters'])
clusters = sorted(list(clusters))
# Generate plots for each cluster
plot_cluster_metrics(
results,
questions_data,
clusters,
output_dir,
min_embedding_threshold,
min_coherence_threshold
)
print("\nCluster analysis complete. Plots have been generated in the 'plots/clusters' directory.")
#####
def get_company_from_model(model_name: str) -> str:
"""Extract company name from model name."""
return model_name.split('/')[0]
def get_best_models_per_cluster(results: dict,
questions_data: List[dict],
min_embedding_threshold: float = 0.15,
min_coherence_threshold: float = 15.0) -> Dict[str, Dict[str, Tuple[str, float]]]:
"""
For each cluster, find the best performing model for each metric.
Scores are averaged by the number of questions in each cluster.
Returns dict[cluster][metric] = (model_name, average_score)
"""
# Get unique clusters and count questions per cluster
clusters = set()
cluster_question_counts = defaultdict(int)
for question in questions_data:
for cluster in question['clusters']:
clusters.add(cluster)
cluster_question_counts[cluster] += 1
# Initialize results storage
best_performers = {cluster: {} for cluster in clusters}
# Process each cluster
for cluster in clusters:
# Get questions for this cluster
cluster_questions = {q['question'] for q in questions_data if cluster in q['clusters']}
num_questions = cluster_question_counts[cluster]
# Initialize metric tracking for this cluster
metrics = defaultdict(lambda: defaultdict(float))
# Calculate metrics for each model
for model_name, temp_data in results['models'].items():
for temp, questions in temp_data.items():
embedding_total = 0
coherence_total = 0
valid_answers = 0
for question in cluster_questions:
if question in questions:
for answer in questions[question]:
if (answer['embedding_dissimilarity_score'] >= min_embedding_threshold and
answer['coherence_score'] >= min_coherence_threshold):
embedding_total += answer['embedding_dissimilarity_score']
coherence_total += answer['coherence_score'] / 100
valid_answers += 1
# Average scores by number of questions in cluster
avg_embedding = embedding_total / num_questions if num_questions > 0 else 0
avg_coherence = coherence_total / num_questions if num_questions > 0 else 0
avg_answers = valid_answers / num_questions if num_questions > 0 else 0
# Update best scores if this temperature setting is better
metrics['embedding'][model_name] = max(metrics['embedding'][model_name], avg_embedding)
metrics['coherence'][model_name] = max(metrics['coherence'][model_name], avg_coherence)
metrics['answers'][model_name] = max(metrics['answers'][model_name], avg_answers)
# Find best model for each metric
for metric_name, model_scores in metrics.items():
if model_scores:
best_model = max(model_scores.items(), key=lambda x: x[1])
best_performers[cluster][metric_name] = best_model
return best_performers
def plot_best_performers(best_performers: Dict[str, Dict[str, Tuple[str, float]]],
metric: str,
output_dir: str = 'plots',
title_suffix: str = '') -> None:
"""Create a horizontal bar plot for best performers in a specific metric."""
# Prepare data
clusters = list(best_performers.keys())
models = [best_performers[cluster][metric][0] if metric in best_performers[cluster] else None for cluster in clusters]
scores = [best_performers[cluster][metric][1] if metric in best_performers[cluster] else 0 for cluster in clusters]
# Sort by score
sorted_indices = np.argsort(scores)
clusters = [clusters[i] for i in sorted_indices]
models = [models[i] for i in sorted_indices]
scores = [scores[i] for i in sorted_indices]
# Create figure
plt.figure(figsize=(12, max(8, len(clusters) * 0.4)))
# Create bars
bars = plt.barh(range(len(clusters)), scores, height=0.7)
# Color bars by company and add model names
for idx, (bar, model) in enumerate(zip(bars, models)):
if model:
company = get_company_from_model(model)
bar.set_color(COMPANY_COLORS[company])
# Add model name inside bar
model_name = model.split('/')[-1] # Get just the model name part
x_pos = bar.get_width() * 0.02 # Small offset from start of bar
plt.text(x_pos, idx, f"{model_name} ({scores[idx]:.2f})",
va='center', fontsize=8, color='black')
# Customize plot
plt.ylabel('Clusters')
xlabel = {
'embedding': 'Average Embedding Dissimilarity Score per Question',
'coherence': 'Average Coherence Score per Question',
'answers': 'Average Valid Responses per Question'
}[metric]
plt.xlabel(xlabel)
plt.title(f'Best Performing Models by {xlabel}{title_suffix}')
plt.yticks(range(len(clusters)), [c.replace(' and ', '\n& ') for c in clusters], fontsize=8)
# Add legend for companies
legend_elements = [plt.Rectangle((0,0),1,1, facecolor=color, label=company)
for company, color in COMPANY_COLORS.items()]
plt.legend(handles=legend_elements, loc='center left', bbox_to_anchor=(1, 0.5))
# Save plot
plt.tight_layout()
plt.savefig(Path(output_dir) / f'best_{metric}_per_cluster_averaged.png',
dpi=300, bbox_inches='tight')
plt.close()
def analyze_best_performers(results_file: str,
questions_data: List[dict],
output_dir: str = 'plots') -> None:
"""Generate best performer analysis and plots."""
# Load results
with open(results_file, 'r') as f:
results = json.load(f)
# Get best performers
best_performers = get_best_models_per_cluster(
results,
questions_data,
min_embedding_threshold=0.15,
min_coherence_threshold=15.0
)
# Create output directory
Path(output_dir).mkdir(parents=True, exist_ok=True)
# Generate plots for each metric
for metric in ['embedding', 'coherence', 'answers']:
plot_best_performers(best_performers, metric, output_dir)
return best_performers
#####
def normalize_text(text: str) -> str:
"""Normalize text for comparison by removing extra spaces and hyphens."""
return text.lower().replace('-', ' ').replace(' ', ' ').strip()
def get_best_models_per_question(results: dict,
questions_data: List[dict],
min_embedding_threshold: float = 0.15,
min_coherence_threshold: float = 15.0) -> Dict[str, Dict[int, Tuple[str, float]]]:
"""
For each metric, find the best performing model for each question.
Scores are summed across all valid answers for each model-question pair.
Returns dict[metric][question_num] = (model_name, score)
"""
# Initialize storage
best_scores = {
'embedding': {},
'coherence': {},
'answers': {}
}
# Create normalized question map
question_map = {normalize_text(q['question']): q['number'] for q in questions_data}
# First, calculate total scores for each model-question pair
model_scores = defaultdict(lambda: defaultdict(lambda: defaultdict(float)))
for model_name, temp_data in results['models'].items():
for temp, questions in temp_data.items():
for question, answers in questions.items():
normalized_q = normalize_text(question)
if normalized_q not in question_map:
print(f"Warning: Could not find matching question for: {question}")
continue
q_num = question_map[normalized_q]
# Initialize scores for this model-temp-question combination
embedding_total = 0
coherence_total = 0
valid_count = 0
# Sum up scores across all valid answers
for answer in answers:
if (answer['embedding_dissimilarity_score'] >= min_embedding_threshold and
answer['coherence_score'] >= min_coherence_threshold):
embedding_total += answer['embedding_dissimilarity_score']
coherence_total += answer['coherence_score'] / 100
valid_count += 1
# Update scores if this temperature setting gives better results
current_embedding = model_scores['embedding'][model_name][q_num]
current_coherence = model_scores['coherence'][model_name][q_num]
current_answers = model_scores['answers'][model_name][q_num]
model_scores['embedding'][model_name][q_num] = max(current_embedding, embedding_total)
model_scores['coherence'][model_name][q_num] = max(current_coherence, coherence_total)
model_scores['answers'][model_name][q_num] = max(current_answers, valid_count)
# Now find the best model for each question
for metric in ['embedding', 'coherence', 'answers']:
for q_num in question_map.values():
best_score = -float('inf')
best_model = None
for model_name in results['models'].keys():
score = model_scores[metric][model_name][q_num]
if score > best_score:
best_score = score
best_model = model_name
if best_model is not None:
best_scores[metric][q_num] = (best_model, best_score)
return best_scores
def wrap_text(text: str, width: int = 15) -> str:
"""Wrap text to specified width, preserving words."""
words = text.replace(' and ', '\n& ').split()
lines = []
current_line = []
current_length = 0
for word in words:
if current_length + len(word) + 1 <= width:
current_line.append(word)
current_length += len(word) + 1
else:
if current_line:
lines.append(' '.join(current_line))
current_line = [word]
current_length = len(word)
if current_line:
lines.append(' '.join(current_line))
return '\n'.join(lines)
def plot_question_performance(best_scores: Dict[str, Dict[int, Tuple[str, float]]],
questions_data: List[dict],
metric: str,
output_dir: str = 'plots',
show_question_numbers: bool = True) -> None:
"""Create a hierarchical horizontal bar plot for question-level performance."""
# Group questions by cluster
cluster_questions = defaultdict(list)
for q in questions_data:
for cluster in q['clusters']:
cluster_questions[cluster].append(q['number'])
# Sort and organize data
organized_data = []
y_labels = []
scores = []
models = []
for cluster in sorted(cluster_questions.keys()):
questions = cluster_questions[cluster]
# Sort questions by their best score within cluster
sorted_questions = sorted(
questions,
key=lambda q: best_scores[metric][q][1] if q in best_scores[metric] else -float('inf'),
reverse=True
)
# Add cluster label as placeholder
organized_data.append((cluster, None, None))
# Add questions
for q in sorted_questions:
if q in best_scores[metric]:
organized_data.append((None, q, best_scores[metric][q]))
# Create figure with GridSpec for better control
fig = plt.figure(figsize=(12, max(8, len(organized_data) * 0.3)))
gs = fig.add_gridspec(1, 2, width_ratios=[2, 15], wspace=0.01) # Increased width ratio for labels
# Create two axes: one for labels, one for the main plot
ax_labels = fig.add_subplot(gs[0])
ax_main = fig.add_subplot(gs[1])
# Process data and create bars
current_y = 0
y_positions = []
cluster_positions = []
cluster_heights = []
for item in organized_data:
cluster, q_num, score_data = item
if cluster: # This is a cluster label
cluster_positions.append(current_y)
current_y += 0.5 # Add some space before first question
else: # This is a question
y_positions.append(current_y)
model, score = score_data
scores.append(score)
models.append(model)
current_y += 1
# Calculate cluster heights
for i in range(len(cluster_positions)):
if i < len(cluster_positions) - 1:
cluster_heights.append(cluster_positions[i+1] - cluster_positions[i] - 0.5)
else:
cluster_heights.append(current_y - cluster_positions[i] - 0.5)
# Plot bars
bars = ax_main.barh(y_positions, scores, height=0.7)
# Color bars and add labels
for idx, (bar, model) in enumerate(zip(bars, models)):
company = model.split('/')[0]
bar.set_color(COMPANY_COLORS[company])
# Add model name inside bar
model_name = model.split('/')[-1]
x_pos = bar.get_width() * 0.02
ax_main.text(x_pos, y_positions[idx], f"{model_name} ({scores[idx]:.2f})",
va='center', fontsize=6, color='black')
# Add cluster labels and backgrounds
for cluster_y, height, (cluster, _, _) in zip(cluster_positions, cluster_heights,
[x for x in organized_data if x[0]]):
# Add wrapped cluster label
wrapped_cluster = wrap_text(cluster)
ax_labels.text(0.8, cluster_y + height/2, wrapped_cluster,
ha='right', va='center',
fontsize=8, fontweight='bold',
linespacing=0.9)
# Add alternating background
ax_main.axhspan(cluster_y, cluster_y + height,
color='gray' if cluster_positions.index(cluster_y) % 2 == 0 else 'white',
alpha=0.1)
# Add question numbers on the left
question_positions = []
question_labels = []
for item in organized_data:
if not item[0]: # This is a question
question_positions.append(y_positions[len(question_labels)])
# question_labels.append(f"Q{item[1]}")
question_labels.append(" ")
ax_labels.set_ylim(ax_main.get_ylim())
ax_labels.set_xlim(-1, 1)
# Set y-tick labels for questions
ax_labels.set_yticks(question_positions)
ax_labels.set_yticklabels(question_labels, fontsize=8)
# Move question numbers to the far left
ax_labels.set_yticklabels(question_labels, fontsize=8)
for tick in ax_labels.yaxis.get_major_ticks():
tick.set_pad(-20) # Adjust the padding to move numbers closer to the left edge
tick.tick1line.set_visible(False) # Hide the tick marks
tick.tick2line.set_visible(False) # Hide the tick marks on the other side
# Customize axes
ax_labels.set_xticks([])
ax_labels.spines['right'].set_visible(False)
ax_labels.spines['top'].set_visible(False)
ax_labels.spines['bottom'].set_visible(False)
ax_labels.spines['left'].set_visible(False)
ax_main.set_yticks([])
# Set title and labels
xlabel = {
'embedding': 'Total Embedding Dissimilarity Score',
'coherence': 'Total Coherence Score',
'answers': 'Number of Valid Responses'
}[metric]
ax_main.set_xlabel(xlabel)
fig.suptitle(f'Best Performance by Question\nGrouped by Cluster, Ordered by {xlabel}',
y=1.02)
# Add legend for companies
legend_elements = [plt.Rectangle((0,0),1,1, facecolor=color, label=company)
for company, color in COMPANY_COLORS.items()]
ax_main.legend(handles=legend_elements,
loc='upper center',
bbox_to_anchor=(0.5, 1.15),
ncol=len(COMPANY_COLORS))
# Save plot
plt.savefig(Path(output_dir) / f'question_level_{metric}.png',
dpi=300, bbox_inches='tight')
plt.close()
def analyze_question_performance(results_file: str,
questions_data: List[dict],
output_dir: str = 'plots') -> None:
"""Generate question-level analysis and plots."""
# Load results
with open(results_file, 'r') as f:
results = json.load(f)
# Get best performers for each question
best_scores = get_best_models_per_question(
results,
questions_data,
min_embedding_threshold=0.15,
min_coherence_threshold=15.0
)
# Create output directory
Path(output_dir).mkdir(parents=True, exist_ok=True)
# Generate plots for each metric
for metric in ['embedding', 'coherence', 'answers']:
plot_question_performance(best_scores, questions_data, metric, output_dir)
return best_scores
#####
def get_max_scores(results: dict,
min_embedding_threshold: float = 0.15,
min_coherence_threshold: float = 15.0) -> Dict[str, Dict[str, float]]:
"""
Calculate maximum scores for each model across temperatures.
"""
max_scores = defaultdict(lambda: {'embedding': 0, 'coherence': 0, 'answers': 0})
for model_name, temp_data in results['models'].items():
for temp, questions in temp_data.items():
embedding_total = 0
coherence_total = 0
valid_answers = 0
for answers in questions.values():
for answer in answers:
if (answer['embedding_dissimilarity_score'] >= min_embedding_threshold and
answer['coherence_score'] >= min_coherence_threshold):
embedding_total += answer['embedding_dissimilarity_score']
coherence_total += answer['coherence_score'] / 100
valid_answers += 1
# Update maximum scores
max_scores[model_name]['embedding'] = max(max_scores[model_name]['embedding'],
embedding_total)
max_scores[model_name]['coherence'] = max(max_scores[model_name]['coherence'],
coherence_total)
max_scores[model_name]['answers'] = max(max_scores[model_name]['answers'],
valid_answers)
return max_scores
def _create_styled_label(ax, x, y, text: str, color: str, offset_x: float = 0.005) -> plt.Text:
"""Create a consistently styled text label with background."""
# Calculate offset based on axis scale type
if isinstance(x, datetime):
date_range = (ax.get_xlim()[1] - ax.get_xlim()[0])
x_offset = timedelta(days=date_range * offset_x)
else:
x_offset = x * 0.005 if x > 0 else 0.005
# Create ultra-soft background color with same alpha as scatter points
rgba_color = plt.matplotlib.colors.to_rgba(color, alpha=0.2) # Match scatter point alpha
text_obj = ax.text(x + x_offset, y, text,
fontsize=11,
bbox=dict(
facecolor=rgba_color,
alpha=0.3, # Reduced transparency for label background
edgecolor='none',
boxstyle='round,pad=0.4,rounding_size=0.4',
linewidth=0
),
horizontalalignment='left',
verticalalignment='center',
zorder=100)
text_obj.point_coords = (x, y)
return text_obj
def _adjust_labels(texts, ax):
"""Helper function to adjust label positions using adjustText with minimal movement."""
adjustText.adjust_text(
texts,
ax=ax,
force_points=(0.01, 0.01), # Keep minimal force between points and texts
force_text=(0.05, 0.05), # Keep very small force between texts
expand_points=(0.5, 0.5), # Keep minimal point expansion
expand_text=(0.5, 0.5), # Keep minimal text expansion
arrowprops=dict(
arrowstyle='-',
color='gray',
alpha=0.5, # Restored original alpha
lw=0.5 # Restored original line width
),
avoid_self=True,
avoid_points=True,
min_arrow_dist=1.0, # Keep minimal arrow distance
autoalign=False,
only_move={'points': 'xy',
'text': 'xy',
'objects': 'xy'},
text_from_point=(0, 0),
save_steps=False,
drag_enable=False
)
def create_timeline_plots(results: dict,
release_dates: List[dict],
output_dir: str = 'plots') -> None:
"""
Create scatter plots showing score evolution over time with log scale.
"""
# Get maximum scores for each model
max_scores = get_max_scores(results)
# Convert release dates to dict and datetime objects
release_dict = {item['model']: datetime.strptime(item['release_date'], '%Y-%m-%d')
for item in release_dates}
# Create scatter plot
plt.figure(figsize=(15, 8))
# Collect data points
plot_data = []
for model, scores in max_scores.items():
if model in release_dict:
plot_data.append({
'model': model,
'answers': scores['answers'], # Focus on number of answers
'date': release_dict[model],
'company': model.split('/')[0]
})
# Get date range
dates = [d['date'] for d in plot_data]
min_date = min(dates)
max_date = max(dates)
# Add padding to date range (10% on each side)
date_range = (max_date - min_date).days
padding = timedelta(days=int(date_range * 0.1))
plt.xlim(min_date - padding, max_date + padding)
# Plot points with fill color
for data in plot_data:
plt.scatter(data['date'], data['answers'],
color=COMPANY_COLORS[data['company']],
alpha=0.2, # Match label background alpha
s=100,
edgecolor=COMPANY_COLORS[data['company']],
linewidth=1,
zorder=10)
# Add labels with background - directly next to points
for data in plot_data:
model_name = data['model'].split('/')[-1]
_create_styled_label(plt.gca(),
data['date'],
data['answers'],
model_name,
COMPANY_COLORS[data['company']])
# Set log scale for y-axis
plt.yscale('log')
# Customize plot
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m'))
plt.gca().xaxis.set_major_locator(mdates.MonthLocator())
# Rotate and align the tick labels so they look better
plt.gcf().autofmt_xdate()
plt.xlabel('Release Date')
plt.ylabel('Number of Valid Answers (log scale)')
plt.title('Model Performance Evolution Over Time')
# Add legend for companies
legend_elements = [plt.Line2D([0], [0], marker='o', color='w',
markerfacecolor=color, label=company, markersize=10)
for company, color in COMPANY_COLORS.items()]
plt.legend(handles=legend_elements, loc='center left', bbox_to_anchor=(1, 0.5))
# Add grid
plt.grid(True, alpha=0.3)
# Save plot
plt.tight_layout()
plt.savefig(Path(output_dir) / 'model_timeline.png',
dpi=300, bbox_inches='tight')
plt.close()
def create_parameter_plots(results: dict,
model_scales: List[dict],
output_dir: str = 'plots') -> None:
"""Create scatter plots comparing performance versus parameter count for Llama models."""
max_scores = get_max_scores(results)
scale_dict = {item['model']: item['parameters'] for item in model_scales}
fig, ax = plt.subplots(figsize=(15, 8))
# Collect and sort data points by parameter count
plot_data = []
for model, scores in max_scores.items():
if model in scale_dict:
plot_data.append({
'model': model,
'answers': scores['answers'],
'parameters': scale_dict[model],
'company': model.split('/')[0]
})
# Sort by parameter count to help with label placement
plot_data.sort(key=lambda x: x['parameters'])