-
Notifications
You must be signed in to change notification settings - Fork 672
Expand file tree
/
Copy pathvisualize_results.py
More file actions
1536 lines (1294 loc) · 61.4 KB
/
visualize_results.py
File metadata and controls
1536 lines (1294 loc) · 61.4 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 logging, glob, re, ast, os
import pytz
import sys
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from pathlib import Path
from plotly.subplots import make_subplots
from jinja2 import Template
from collections import Counter
from datetime import datetime
from scipy import stats
from utils import run_inference, report_summary_template, convert_scientific_to_decimal
# Configuration constants
TIMESTAMP = datetime.now().strftime("%Y%m%d_%H%M%S")
# Analysis constants
MIN_RECORDS_FOR_ANALYSIS = 1000
MIN_RECORDS_FOR_HISTOGRAM = 2000
EPSILON_DIVISION = 0.001 # Small value to prevent division by zero
VALUE_RATIO_MULTIPLIER = 10
# Statistical constants
PERCENTILES = [0.50, 0.90, 0.95, 0.99]
NORMAL_DISTRIBUTION_RANGE_MULTIPLIER = 0.5
NORMAL_DISTRIBUTION_POINTS = 100
# Visualization constants
COEFFICIENT_VARIATION_THRESHOLD = 0.3 # CV < 30% indicates good consistency
GRID_OPACITY = 0.3
COMPOSITE_SCORE_WEIGHTS = {
'latency': 0.5,
'cost': 0.5
}
# Performance thresholds
PERFORMANCE_THRESHOLDS = {
'success_rate': {'good': 0.95, 'medium': 0.85},
# 'avg_latency': {'good': 1.5, 'medium': 2},
'avg_cost': {'good': 0.5, 'medium': 1.0},
'avg_otps': {'good': 100, 'medium': 35},
}
# LLM inference settings
INFERENCE_MAX_TOKENS = 750
INFERENCE_TEMPERATURE = 0.3
INFERENCE_REGION = 'us-west-2'
# Get project root directory
PROJECT_ROOT = Path(os.path.abspath(os.path.dirname(os.path.dirname(__file__))))
# Setup logger
logger = logging.getLogger(__name__)
log_dir = PROJECT_ROOT / "logs"
os.makedirs(log_dir, exist_ok=True)
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
# filename=log_dir / f"visualize_results_{TIMESTAMP}.log",
filemode='a'
)
logger.info(f"Starting visualization with project root: {PROJECT_ROOT}")
# Load HTML template with absolute path
template_path = PROJECT_ROOT / "assets" / "html_template.txt"
try:
with open(template_path, 'r') as file:
HTML_TEMPLATE = file.read()
logger.info(f"Loaded HTML template from {template_path}")
except FileNotFoundError:
logger.error(f"HTML template not found at {template_path}")
HTML_TEMPLATE = """<!DOCTYPE html>
<html>
<head><title>LLM Benchmark Report</title></head>
<body><h1>LLM Benchmark Report</h1><p>Template not found, using fallback.</p></body>
</html>"""
def extract_model_name(model_id):
"""Extract clean model name from ID."""
if '.' in model_id:
parts = model_id.split('.')
if len(parts) == 3:
model_name = parts[-1].split(':')[0].split('-v')[0]
else:
model_name = parts[-2] + '.' + parts[-1]
return model_name
return model_id.split(':')[0]
def parse_json_string(json_str):
try:
if isinstance(json_str, list):
json_str = json_str[0]
# Use ast.literal_eval to safely evaluate the string as a Python literal
# This handles the single-quoted JSON-like strings
dict_data = ast.literal_eval(json_str)
return dict_data
except Exception as e:
# Return error information if parsing fails
return {"error": str(e)}
def load_data(directory, evaluation_names=None):
"""Load and prepare benchmark data.
Args:
directory: Directory containing CSV files
evaluation_names: Optional list of evaluation names to filter by
"""
# Ensure directory is a Path object
directory = Path(directory)
logger.info(f"Looking for CSV files in: {directory}")
# Load CSV files
all_files = glob.glob(str(directory / "invocations_*.csv"))
if not all_files:
logger.error(f"No invocation CSVs found in {directory}")
raise FileNotFoundError(f"No invocation CSVs found in {directory}")
# Filter files by evaluation names if specified
if evaluation_names:
files = []
for file_path in all_files:
file_name = Path(file_path).name
# Check if any evaluation name is in the filename
if any(eval_name in file_name for eval_name in evaluation_names):
files.append(file_path)
if not files:
logger.warning(f"No CSV files found matching evaluations: {evaluation_names}")
logger.info(f"Available files: {[Path(f).name for f in all_files]}")
raise FileNotFoundError(f"No CSV files found for evaluations: {evaluation_names}")
logger.info(f"Filtered to {len(files)} CSV files matching evaluations {evaluation_names}: {[Path(f).name for f in files]}")
else:
files = all_files
logger.info(f"Found {len(files)} CSV files (no filter applied): {[Path(f).name for f in files]}")
dataframes = []
for f in files:
try:
logger.info(f"Reading file: {f}")
df_file = pd.read_csv(f)
logger.info(f"Read {len(df_file)} rows from {f}")
dataframes.append(df_file)
except Exception as e:
logger.error(f"Error reading {f}: {str(e)}")
continue
if not dataframes:
logger.error("No valid data found in any CSV files")
raise ValueError("No valid data found in any CSV files")
df = pd.concat(dataframes, ignore_index=True)
logger.info(f"Combined data has {len(df)} rows")
# Clean and prepare data (optimized with method chaining)
df = (df[df['api_call_status'] == 'Success']
.reset_index(drop=True)
.assign(model_name=lambda x: x['model_id'].apply(extract_model_name)))
parsed_dicts = df['performance_metrics'].apply(parse_json_string)
del df['performance_metrics']
# Convert the Series of dictionaries to a DataFrame
unpacked_findings = pd.DataFrame(list(parsed_dicts))
df = pd.concat([df, unpacked_findings], axis=1)
df['task_success'] = df['judge_success']
# Calculate tokens per second
df['OTPS'] = df['output_tokens'] / (df['time_to_last_byte'] + EPSILON_DIVISION)
judge_scores = pd.DataFrame(df['judge_scores'].to_dict()).transpose()
# Identify numeric index values
numeric_index_mask = pd.to_numeric(judge_scores.index, errors='coerce').notna()
# Filter and process judge scores (optimized with method chaining)
judge_scores_df = (judge_scores[numeric_index_mask]
.reset_index(drop=True)
.assign(mean_scores=lambda x: x.mean(axis=1)))
df = pd.concat([df, judge_scores_df], axis=1)
# ── Cost summary ───────────────────────────────────────────────────────────
cost_stats = (
df.groupby(["model_name"])["response_cost"]
.agg(avg_cost="mean", total_cost="sum", num_invocations="count")
)
# ── Latency percentiles (50/90/95/99) ──────────────────────────────────────
latency_stats = (
df.groupby(["model_name"])["time_to_last_byte"]
.quantile(PERCENTILES) # returns MultiIndex
.unstack(level=-1) # percentiles → columns
)
latency_stats.columns = [f"p{int(q*100)}" for q in latency_stats.columns]
# ── Combine both sets of metrics ──────────────────────────────────────────
summary = cost_stats.join(latency_stats)
# Optional: forecast spend per model/profile (30-day projection)
summary["monthly_forecast"] = (
summary["avg_cost"]
* (summary["num_invocations"] / df.shape[0])
* 30
)
df = pd.concat([df, summary], axis=1)
return df
def calculate_metrics_by_model_task(df):
"""Calculate detailed metrics for each model-task combination."""
# Group by model and task
metrics = df.groupby(['model_name', 'task_types']).agg({
'task_success': ['mean', 'count'],
'time_to_first_byte': ['mean', 'min', 'max'],
'time_to_last_byte': ['mean', 'min', 'max'],
'OTPS': ['mean', 'min', 'max'],
'response_cost': ['mean', 'sum'],
'output_tokens': ['mean', 'sum'],
'input_tokens': ['mean', 'sum']
})
# Flatten multi-level column index
metrics.columns = ['_'.join(col).strip() for col in metrics.columns.values]
# Rename columns for clarity
metrics = metrics.rename(columns={
'task_success_mean': 'success_rate',
'task_success_count': 'sample_count',
'time_to_first_byte_mean': 'avg_ttft',
'time_to_last_byte_mean': 'avg_latency',
'OTPS_mean': 'avg_otps',
'response_cost_mean': 'avg_cost',
'output_tokens_mean': 'avg_output_tokens',
'input_tokens_mean': 'avg_input_tokens'
})
max_raw_ratio = metrics['success_rate'].max() / (metrics['avg_cost'].min() + EPSILON_DIVISION)
metrics['value_ratio'] = VALUE_RATIO_MULTIPLIER * (metrics['success_rate'] / (metrics['avg_cost'] + EPSILON_DIVISION)) / max_raw_ratio
return metrics.reset_index()
def calculate_latency_metrics(df):
"""Calculate aggregated latency metrics by model."""
latency = df.groupby(['model_name']).agg({
'time_to_first_byte': ['mean', 'min', 'max', 'std'],
'time_to_last_byte': ['mean', 'min', 'max', 'std'],
'OTPS': ['mean', 'min', 'max', 'std']
})
# Flatten multi-level column index
latency.columns = ['_'.join(col).strip() for col in latency.columns.values]
# Rename columns for clarity
latency = latency.rename(columns={
'time_to_first_byte_mean': 'avg_ttft',
'time_to_last_byte_mean': 'avg_latency',
'OTPS_mean': 'avg_otps'
})
return latency.reset_index()
def calculate_cost_metrics(df):
"""Calculate aggregated cost metrics by model."""
cost = df.groupby(['model_name']).agg({
'response_cost': ['mean', 'min', 'max', 'sum'],
'input_tokens': ['mean', 'sum'],
'output_tokens': ['mean', 'sum']
})
# Flatten multi-level column index
cost.columns = ['_'.join(col).strip() for col in cost.columns.values]
# Rename columns for clarity
cost = cost.rename(columns={
'response_cost_mean': 'avg_cost',
'response_cost_sum': 'total_cost',
'input_tokens_mean': 'avg_input_tokens',
'output_tokens_mean': 'avg_output_tokens'
})
return cost.reset_index()
def create_normal_distribution_histogram(df,
key='time_to_first_byte',
label='Time to First Token (seconds)'):
"""
Creates overlapping histogram plots with normal distribution curves for time_to_first_byte by model.
Only creates the plot if there are more than 2000 records available.
Args:
df: DataFrame containing the benchmark data
label: label for the histogram plot
key: data column to create the histogram plot
Returns:
Plotly figure or None if insufficient data
"""
min_vals = MIN_RECORDS_FOR_ANALYSIS
# Check if we have enough data
# Check if we have enough data
value_counts = df['model_name'].value_counts()
# Get values that appear more than 2000 times
frequent_values = value_counts[value_counts > min_vals].index
# Filter the dataframe to only include rows where the column value is in our frequent_values list
df_match = df[df['model_name'].isin(frequent_values)]
if df_match.empty:
logger.info(f"Insufficient data for {label} Distribution by Model histogram: {len(df)} records (need >{MIN_RECORDS_FOR_HISTOGRAM})")
return None
# Filter out any null values
df_clean = df_match[df_match[key].notna()].copy()
if df_clean.empty:
return ["No valid time_to_first_byte data found"]
logger.info(f"Creating {label} Distribution by Model histogram with {len(df)} records")
# Create figure
fig = go.Figure()
# Get unique models and assign colors
unique_models = df_clean['model_name'].unique()
colors = px.colors.qualitative.Set1[:len(unique_models)]
# Create histogram and normal distribution for each model
for i, model in enumerate(unique_models):
model_data = df_clean[df_clean['model_name'] == model][key]
if len(model_data) < 10: # Skip models with too few data points
continue
# Calculate statistics for normal distribution
mean = model_data.mean()
std = model_data.std()
# Add histogram
fig.add_trace(go.Histogram(
x=model_data,
name=f'{model} (n={len(model_data)})',
opacity=0.6,
marker_color=colors[i % len(colors)],
histnorm='probability density', # Normalize to match normal curve
nbinsx=50,
showlegend=True
))
# Generate points for normal distribution curve
x_range = np.linspace(
model_data.min() - NORMAL_DISTRIBUTION_RANGE_MULTIPLIER * std,
model_data.max() + NORMAL_DISTRIBUTION_RANGE_MULTIPLIER * std,
NORMAL_DISTRIBUTION_POINTS
)
normal_curve = stats.norm.pdf(x_range, mean, std)
# Add normal distribution curve
fig.add_trace(go.Scatter(
x=x_range,
y=normal_curve,
mode='lines',
name=f'{model} Normal (μ={mean:.3f}, σ={std:.3f})',
line=dict(
color=colors[i % len(colors)],
width=2,
dash='dash'
),
opacity=0.8,
showlegend=True
))
# Update layout
fig.update_layout(
template="plotly_dark",
paper_bgcolor="#1e1e1e",
plot_bgcolor="#2d2d2d",
title={
'text': f'{label} Distribution by Model<br><sub>Histograms with Normal Distribution Overlays</sub>',
'x': 0.5,
'xanchor': 'center'
},
xaxis_title=label,
yaxis_title='Probability Density',
barmode='overlay', # Allow histograms to overlap
legend=dict(
orientation="v",
yanchor="top",
y=1,
xanchor="left",
x=1.02
),
height=800,
margin=dict(r=250) # Extra margin for legend
)
# Update x and y axes
fig.update_xaxes(showgrid=True, gridwidth=1, gridcolor=f'rgba(128,128,128,{GRID_OPACITY})')
fig.update_yaxes(showgrid=True, gridwidth=1, gridcolor=f'rgba(128,128,128,{GRID_OPACITY})')
return fig
def create_visualizations(df, model_task_metrics, latency_metrics, cost_metrics):
"""Create visualizations for the report."""
visualizations = {}
latency_metrics_round = latency_metrics
average_cost_round = latency_metrics_round.round({'avg_ttft': 4})
# 1. TTFT Comparison
ttft_fig = px.bar(
average_cost_round.sort_values('avg_ttft'),
template="plotly_dark", # Use the built-in dark template as a base
x='model_name',
y='avg_ttft',
labels={'model_name': 'Model', 'avg_ttft': 'Time to First Token (Secs)'},
title='Time to First Token by Model',
color='avg_ttft',
color_continuous_scale='Viridis_r' # Reversed so lower is better (green)
)
# Improve overall chart visibility
ttft_fig.update_layout(
paper_bgcolor="#1e1e1e",
plot_bgcolor="#2d2d2d", # Slightly lighter than paper for contrast
)
visualizations['ttft_comparison'] = ttft_fig
tokens_per_sec_round = latency_metrics
tokens_per_sec_round = tokens_per_sec_round.round({'avg_otps': 2})
# 2. OTPS Comparison
otps_fig = px.bar(
tokens_per_sec_round.sort_values('avg_otps', ascending=False),
template="plotly_dark", # Use the built-in dark template as a base
x='model_name',
y='avg_otps',
error_y=tokens_per_sec_round['OTPS_std'],
labels={'model_name': 'Model', 'avg_otps': 'Tokens/sec'},
title='Output Tokens Per Second by Model',
color='avg_otps',
color_continuous_scale='Viridis'
)
# Improve overall chart visibility
otps_fig.update_layout(
paper_bgcolor="#1e1e1e",
plot_bgcolor="#2d2d2d", # Slightly lighter than paper for contrast
)
visualizations['otps_comparison'] = otps_fig
average_cost_round = (cost_metrics
.sort_values('avg_cost')
.round({'avg_cost': 5}))
# 3. Cost Comparison
cost_fig = px.bar(
average_cost_round.sort_values('avg_cost'),
template="plotly_dark", # Use the built-in dark template as a base
x='model_name',
y='avg_cost',
labels={'model_name': 'Model', 'avg_cost': 'Cost per Response (USD)'},
title='Using μ (Micro) Symbol for Small Numbers',
color='avg_cost',
color_continuous_scale='Viridis_r' # Reversed so lower is better (green)
)
# Improve overall chart visibility
cost_fig.update_layout(
paper_bgcolor="#1e1e1e",
plot_bgcolor="#2d2d2d", # Slightly lighter than paper for contrast
)
visualizations['cost_comparison'] = cost_fig
# 5. Task-Model Success Rate Heatmap
# Pivot to create model vs task matrix
pivot_success = pd.pivot_table(
model_task_metrics,
values='success_rate',
index='model_name',
columns='task_types',
aggfunc='mean'
).infer_objects(copy=False).fillna(0)
heatmap_fig = px.imshow(
pivot_success,
template="plotly_dark", # Use the built-in dark template as a base
labels={'x': 'Task Type', 'y': 'Model', 'color': 'Success Rate'},
title='Success Rate by Model and Task Type',
color_continuous_scale='Earth', #'Viridis',
text_auto='.2f',
aspect='auto'
)
# Improve overall chart visibility
heatmap_fig.update_layout(
paper_bgcolor="#1e1e1e",
plot_bgcolor="#2d2d2d", # Slightly lighter than paper for contrast
)
visualizations['model_task_heatmap'] = heatmap_fig
model_task_metrics_round = model_task_metrics
average_cost_round = model_task_metrics_round.round({'avg_otps': 2, 'value_ratio': 2})
# 6. Model-Task Bubble Chart
bubble_fig = px.scatter(
average_cost_round,
template="plotly_dark", # Keep the dark template for the base layout
x='avg_latency',
y='success_rate',
size='avg_otps',
color='avg_cost',
facet_col='task_types',
facet_col_wrap=3,
hover_data=['model_name', 'value_ratio'],
labels={
'avg_latency': 'Latency (Secs)',
'success_rate': 'Success Rate',
'avg_cost': 'Cost (USD)',
'avg_otps': 'Tokens/sec'
},
title='Model Performance by Task Type',
color_continuous_scale='Earth', # Use a brighter color scale
opacity=0.85 # Slightly increase transparency for better contrast
)
# Additional customizations to improve visibility
bubble_fig.update_traces(
marker=dict(
line=dict(width=1, color="rgba(255, 255, 255, 0.3)") # Add subtle white outline
)
)
# You can also brighten the color bar
bubble_fig.update_layout(
coloraxis_colorbar=dict(
title_font_color="#ffffff",
tickfont_color="#ffffff",
)
)
# Make facet titles more visible
bubble_fig.for_each_annotation(lambda a: a.update(font=dict(color="#90caf9", size=12)))
# Improve overall chart visibility
bubble_fig.update_layout(
paper_bgcolor="#1e1e1e",
plot_bgcolor="#2d2d2d", # Slightly lighter than paper for contrast
font=dict(color="#e0e0e0"),
title_font=dict(color="#90caf9", size=18)
)
visualizations['model_task_bubble'] = bubble_fig
# 7. Error Analysis
if 'judge_explanation' in df.columns:
fails = df[df['task_success'] == False].copy()
if not fails.empty:
fails['error'] = fails['judge_explanation'].fillna("Unknown").replace("", "Unknown")
# Extract error categories using regex
fails['error_category'] = fails['error'].apply(
lambda x: '<br>'.join(list(set(re.findall(r'[A-Za-z-]+', str(x))))) if pd.notnull(x) else "Unknown"
)
counts = fails.groupby(['model_name', 'task_types', 'error_category']).size().reset_index(name='count')
# counts['error_category'] = counts['error_category']
# if counts
error_fig = px.treemap(
counts,
template="plotly_dark", # Use the built-in dark template as a base
path=['task_types', 'model_name', 'error_category'],
values='count',
title='Error Analysis by Task, Model, and Error Type',
color='count',
color_continuous_scale='Reds'
)
error_fig.update_traces(
hovertemplate='<br>Error Judgment: %{label}<br>Count: %{value:.0f}<br>Model: %{parent}<extra></extra>'
)
# Improve overall chart visibility
error_fig.update_layout(
paper_bgcolor="#1e1e1e",
plot_bgcolor="#2d2d2d", # Slightly lighter than paper for contrast
)
visualizations['error_analysis'] = error_fig.to_html(full_html=False)
else:
visualizations['error_analysis'] = '<div id="not-found">No Errors found in the Evaluation</div>'
else:
visualizations['error_analysis'] = '<div id="not-found">No Jury Evaluation Found</div>'
# Add this inside create_visualizations() function
# Extract judge scores from the DataFrame
df['parsed_scores'] = df['judge_scores'].apply(extract_judge_scores)
# Create one radar chart per model (combining all tasks)
radar_charts = {}
# Get all unique models and categories
unique_models = df['model_name'].dropna().unique()
all_categories = set()
# First, collect all categories across all data
for _, row in df.iterrows():
if pd.notnull(row.get('parsed_scores')):
score_dict = row['parsed_scores']
for key in score_dict:
if key.startswith('AVG_'):
category = key.replace('AVG_', '')
all_categories.add(category)
all_categories = sorted(list(all_categories))
# Create one chart per model with all tasks
for model in unique_models:
# Filter data for this model
model_data = df[df['model_name'] == model]
if model_data.empty:
continue
# Get all tasks for this model
tasks = model_data['task_types'].unique()
# Create figure for this model
fig = go.Figure()
# Add one trace per task
for task in tasks:
task_data = model_data[model_data['task_types'] == task]
# Extract scores for this task
scores_dicts = task_data['parsed_scores'].dropna().tolist()
if not scores_dicts:
continue
# Calculate average scores for each category
avg_scores = {}
for score_dict in scores_dicts:
for key, value in score_dict.items():
if key.startswith('AVG_'):
category = key.replace('AVG_', '')
if category not in avg_scores:
avg_scores[category] = []
avg_scores[category].append(value)
# Fill in values for each category
values = []
for category in all_categories:
scores = avg_scores.get(category, [])
if scores:
values.append(sum(scores) / len(scores))
else:
values.append(0)
# Add trace for this task
fig.add_trace(go.Scatterpolar(
r=values + [values[0]], # Close the polygon
theta=all_categories + [all_categories[0]], # Close the polygon
fill='toself',
name=task,
opacity=0.7
))
# Update layout
fig.update_layout(
template="plotly_dark", # Use the built-in dark template as a base
paper_bgcolor="#1e1e1e",
plot_bgcolor="#2d2d2d", # Slightly lighter than paper for contrast
polar=dict(
radialaxis=dict(
visible=True,
range=[0, 5] # Assuming scores are on a 0-5 scale
)
),
title=f"Eval Scores Across All Tasks",
showlegend=True,
legend=dict(
orientation="h",
yanchor="bottom",
y=-0.2,
xanchor="center",
x=0.5
),
height=500,
width=850,
margin=dict(l=20, r=20, b=80, t=50) # Added bottom margin for legend
)
# Store the chart
radar_charts[model] = fig
visualizations['judge_score_radars'] = radar_charts
# 8. Task-specific charts
task_charts = {}
for task in df['task_types'].unique():
task_data = model_task_metrics[model_task_metrics['task_types'] == task]
if not task_data.empty:
# Create subplot with 2x2 grid
fig = make_subplots(
rows=2, cols=2,
subplot_titles=("Success Rate", "Latency (Secs)", 'Cost per Response (USD)<br><span style="font-size: 12px;">Using μ (Micro) Symbol for Small Numbers</span>', "Tokens per Second")
)
# Sort data for each subplot (using method chaining for efficiency)
by_success = task_data.sort_values('success_rate', ascending=False)
by_latency = task_data.sort_values('avg_latency')
by_cost = task_data.sort_values('avg_cost')
by_otps = task_data.sort_values('avg_otps', ascending=False)
# Add traces for each subplot
fig.add_trace(
go.Bar(x=by_success['model_name'], y=by_success['success_rate'], marker_color='green'),
row=1, col=1
)
fig.add_trace(
go.Bar(x=by_latency['model_name'], y=by_latency['avg_latency'], marker_color='orange'),
row=1, col=2
)
fig.add_trace(
go.Bar(x=by_cost['model_name'], y=by_cost['avg_cost'], marker_color='red'),
row=2, col=1
)
fig.add_trace(
go.Bar(x=by_otps['model_name'], y=by_otps['avg_otps'], marker_color='blue'),
row=2, col=2
)
fig.update_layout(
height=725,
title_text=f"Performance Metrics for {task}",
showlegend=False,
template="plotly_dark",
paper_bgcolor="#1e1e1e",
plot_bgcolor="#2d2d2d", # Slightly lighter than paper for contrast
)
task_charts[task] = fig
visualizations['task_charts'] = task_charts
visualizations['integrated_analysis_tables'], analysis_df = create_integrated_analysis_table(model_task_metrics)
visualizations['regional_performance'] = create_regional_performance_analysis(df)
# Add TTFB histogram with normal distribution (only if sufficient data)
ttfb_histogram = create_normal_distribution_histogram(df)
if ttfb_histogram is not None:
visualizations['ttfb_histogram'] = ttfb_histogram
accuracy_histogram = create_normal_distribution_histogram(df, key='mean_scores', label='Accuracy Distribution by Model')
if accuracy_histogram is not None:
visualizations['accuracy_histogram'] = accuracy_histogram
return visualizations
def generate_task_findings(df, model_task_metrics):
"""Generate key findings for each task type."""
task_findings = {}
for task in df['task_types'].unique():
task_data = model_task_metrics[model_task_metrics['task_types'] == task]
findings = []
if not task_data.empty:
# Best accuracy model
best_acc_idx = task_data['success_rate'].idxmax()
best_acc = task_data.loc[best_acc_idx]
findings.append(f"{best_acc['model_name']} had the highest success rate ({best_acc['success_rate']:.1%})")
# Best speed model
best_speed_idx = task_data['avg_latency'].idxmin()
best_speed = task_data.loc[best_speed_idx]
findings.append(
f"{best_speed['model_name']} was the fastest with {best_speed['avg_latency']:.2f}s average latency")
# Best throughput model
best_otps_idx = task_data['avg_otps'].idxmax()
best_otps = task_data.loc[best_otps_idx]
findings.append(
f"{best_otps['model_name']} had the highest throughput ({best_otps['avg_otps']:.1f} tokens/sec)")
# Best value model
best_value_idx = task_data['value_ratio'].idxmax()
best_value = task_data.loc[best_value_idx]
findings.append(
f"{best_value['model_name']} offered the best value (success/cost ratio: {best_value['value_ratio']:.2f})")
# Average success rate
avg_success = task_data['success_rate'].mean()
findings.append(f"Average success rate for this task was {avg_success:.1%}")
# Error analysis
fails = df[(df['task_types'] == task) & (df['task_success'] == False)]
if not fails.empty and 'judge_explanation' in fails.columns:
# Extract common error patterns
error_patterns = []
unique_explanations = fails['judge_explanation'].dropna()
all_errors = unique_explanations.apply(lambda x: [i for i in x.split(';') if i != '']).tolist()
[error_patterns.extend(exp) for exp in all_errors]
if error_patterns:
common_errors = Counter(error_patterns).most_common(2)
errors_text = ", ".join([f"{err[0]} ({err[1]} occurrences)" for err in common_errors])
findings.append(f"Most common errors: {errors_text}")
task_findings[task] = findings
return task_findings
def generate_task_recommendations(model_task_metrics):
"""Generate task-specific model recommendations."""
recommendations = []
for task in model_task_metrics['task_types'].unique():
task_data = model_task_metrics[model_task_metrics['task_types'] == task]
if not task_data.empty:
# Find best models by different metrics
best_suc = task_data['success_rate'].max()
best_acc_model = '<br>'.join(task_data[task_data['success_rate'] == best_suc]['model_name'].tolist())
best_lat = task_data['avg_latency'].min()
best_speed_model = '<br>'.join(task_data[task_data['avg_latency'] == best_lat]['model_name'].tolist())
best_value = task_data['value_ratio'].max()
best_value_model = '<br>'.join(task_data[task_data['value_ratio'] == best_value]['model_name'].tolist())
# Create recommendation entry
recommendations.append({
'task': task,
'best_accuracy_model': best_acc_model,
'accuracy': f"{best_suc:.1%}",
'best_speed_model': best_speed_model,
'speed': f"{best_lat:.2f}s",
'best_value_model': best_value_model,
'value': f"{best_value:.2f}"
})
return sorted(recommendations, key=lambda x: x['task'])
def generate_histogram_findings(df, key='time_to_first_byte', label='Time to First Token'):
"""
Generate key findings for the TTFB histogram analysis.
Returns either meaningful findings or a message about insufficient data.
Args:
df: DataFrame containing the benchmark data
key: Key used to measure
label: Label used to label the findings
Returns:
List of finding strings or single message about insufficient data
"""
min_records = MIN_RECORDS_FOR_ANALYSIS
# Check if we have enough data
value_counts = df['model_name'].value_counts()
# Get values that appear more than 2000 times
frequent_values = value_counts[value_counts > min_records].index
# Filter the dataframe to only include rows where the column value is in our frequent_values list
df_match = df[df['model_name'].isin(frequent_values)]
if df_match.empty:
return [f"Not enough data to perform measurements (need at minimum over {MIN_RECORDS_FOR_HISTOGRAM} measurements per model)"]
# Filter out any null values
df_clean = df_match[df_match[key].notna()].copy()
if df_clean.empty:
return [f"No valid {key} data found"]
findings = []
for model in df_clean['model_name'].unique().tolist():
df_model = df_clean[df_clean['model_name'] == model]
# Overall statistics
overall_mean = df_model[key].mean()
overall_std = df_model[key].std()
findings.append(f"Model <b>{model}</b> {label}: μ={overall_mean:.3f}s, σ={overall_std:.3f}s across {len(df_model)} measurements")
# Model-specific analysis (optimized with method chaining)
model_stats = (df_clean.groupby('model_name')[key]
.agg(['mean', 'std', 'count'])
.reset_index()
.query(f'count >= {min_records}')) # Only models with sufficient data
if not model_stats.empty:
# Fastest model (lowest mean)
fastest_model = model_stats.loc[model_stats['mean'].idxmin()]
findings.append(f"Highest achieving model: <b>{fastest_model['model_name']}</b> with {fastest_model['mean']:.3f}s average {label}")
# Most consistent model (lowest standard deviation)
most_consistent = model_stats.loc[model_stats['std'].idxmin()]
findings.append(f"Most consistent model: <b>{most_consistent['model_name']}</b> with {most_consistent['std']:.3f}s standard deviation")
# Model with highest variability
most_variable = model_stats.loc[model_stats['std'].idxmax()]
findings.append(f"Most variable model (fat-tails): <b>{most_variable['model_name']}</b> with {most_variable['std']:.3f}s standard deviation")
# Distribution characteristics
# Check for normality using coefficient of variation
model_stats['cv'] = model_stats['std'] / model_stats['mean'] # Coefficient of variation
# Models with good normal distribution characteristics (low CV)
well_distributed = model_stats[model_stats['cv'] < COEFFICIENT_VARIATION_THRESHOLD] # CV < 30% indicates good consistency
if not well_distributed.empty:
best_distributed = well_distributed.loc[well_distributed['cv'].idxmin()]
findings.append(f"Best distribution characteristics: <b>{best_distributed['model_name']}</b> (Coefficient of Variation/CV={best_distributed['cv']:.2f})")
# Performance spread analysis
fastest_mean = model_stats['mean'].min()
slowest_mean = model_stats['mean'].max()
performance_spread = ((slowest_mean - fastest_mean) / fastest_mean) * 100
findings.append(f"Performance spread: {performance_spread:.1f}% difference between best and worst achieving models")
for model in df_clean['model_name'].unique().tolist():
# Outlier detection
df_model = df_clean[df_clean['model_name'] == model]
q1 = df_model[key].quantile(0.25)
q3 = df_model[key].quantile(0.75)
iqr = q3 - q1
outlier_threshold = q3 + 1.5 * iqr
outliers = df_model[df_model[key] > outlier_threshold]
if not outliers.empty:
outlier_pct = (len(outliers) / len(df_clean)) * 100
findings.append(f"Outliers for <b>{model}</b>: {len(outliers)} measurements ({outlier_pct:.1f}%) exceed {outlier_threshold:.3f}s")
return findings
def create_html_report(output_dir, timestamp, evaluation_names=None):
"""Generate HTML benchmark report with task-specific analysis.
Args:
output_dir: Directory containing CSV files and where report will be saved
timestamp: Timestamp for report filename
evaluation_names: Optional list of evaluation names to filter by
"""
# Ensure output_dir is an absolute path
if isinstance(output_dir, str):
if not os.path.isabs(output_dir):
output_dir = PROJECT_ROOT / output_dir
output_dir = Path(output_dir)
output_dir = Path(output_dir).resolve()
output_dir.mkdir(parents=True, exist_ok=True)
logger.info(f"Using output directory: {output_dir}")
# Use log directory from project root
log_dir = PROJECT_ROOT / "logs"
os.makedirs(log_dir, exist_ok=True)
report_log_file = log_dir / f"report_generation-{timestamp}.log"
logger.info(f"Report generation logs will be saved to: {report_log_file}")
# Load and process data
if evaluation_names:
logger.info(f"Loading and processing data for evaluations: {evaluation_names}")
else:
logger.info("Loading and processing data for all evaluations...")
try:
df = load_data(output_dir, evaluation_names)
evaluation_info = f" for evaluations {evaluation_names}" if evaluation_names else " (all evaluations)"
logger.info(f"Loaded data with {len(df)} records from {output_dir}{evaluation_info}")
except Exception as e:
logger.error(f"Error loading data: {str(e)}")
raise
# Calculate metrics
logger.info("Calculating model-task metrics...")
model_task_metrics = calculate_metrics_by_model_task(df)
logger.info("Calculating latency metrics...")
latency_metrics = calculate_latency_metrics(df)
logger.info("Calculating cost metrics...")
cost_metrics = calculate_cost_metrics(df)
# Create visualizations
logger.info("Creating visualizations...")
visualizations = create_visualizations(df, model_task_metrics, latency_metrics, cost_metrics)
# Generate findings and recommendations
logger.info("Generating task findings...")
task_findings = generate_task_findings(df, model_task_metrics)
logger.info("Generating recommendations...")
task_recommendations = generate_task_recommendations(model_task_metrics)
task_level_analysis = '# Task Level Analysis:\n'
# Prepare task analysis data for template
task_analysis = []
for task, chart in visualizations['task_charts'].items():
task_level_analysis += f'# Task Name: {task}\n\n'