-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.py
More file actions
2154 lines (1915 loc) · 75.9 KB
/
app.py
File metadata and controls
2154 lines (1915 loc) · 75.9 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 streamlit as st
import subprocess
import json
import os
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
import sys
import io
import zipfile
import plotly.io as pio
import tempfile
import time
import signal
import datetime
from collections import deque
from urllib.parse import quote, unquote
from xml.sax.saxutils import escape
PLOTLY_DOWNLOAD_CONFIG = {
"toImageButtonOptions": {
"format": "png",
"height": 800,
"width": 1400,
"scale": 2,
}
}
PLOTLY_MMLU_DOWNLOAD_CONFIG = {
"toImageButtonOptions": {
"format": "png",
"height": 1200,
"width": 2400,
"scale": 3,
}
}
EVAL_RESULTS_FALLBACKS = {
"arc_challenge": {
"dataset_id": "allenai/ai2_arc",
"task_id": "ARC-Challenge",
"metric_name": "acc_norm",
},
"gpqa_diamond_zeroshot": {
"dataset_id": "Idavidrein/gpqa",
"task_id": "gpqa_diamond",
"metric_name": "acc",
},
"gsm8k": {
"dataset_id": "openai/gsm8k",
"task_id": "main",
"metric_name": "exact_match",
},
"hellaswag": {
"dataset_id": "Rowan/hellaswag",
"task_id": "default",
"metric_name": "acc_norm",
},
"humaneval": {
"dataset_id": "openai/openai_humaneval",
"task_id": "openai_humaneval",
"metric_name": "pass@1",
},
"ifeval": {
"dataset_id": "google/IFEval",
"task_id": "ifeval",
"metric_name": "prompt_level_strict_acc",
},
"mmlu": {
"dataset_id": "cais/mmlu",
"task_id": "default",
"metric_name": "acc",
},
"truthfulqa_mc2": {
"dataset_id": "truthfulqa/truthful_qa",
"task_id": "multiple_choice",
"metric_name": "mc2 acc",
},
"winogrande": {
"dataset_id": "allenai/winogrande",
"task_id": "winogrande_xl",
"metric_name": "acc",
},
}
CHAT_TEMPLATE_UNSAFE_BENCHMARKS = {
"arc_challenge",
"gpqa_diamond_zeroshot",
"hellaswag",
"mmlu",
"truthfulqa_mc2",
"winogrande",
}
def parse_json_object_input(value, field_name):
if value is None:
return None
value = str(value).strip()
if not value:
return None
try:
parsed = json.loads(value)
except json.JSONDecodeError as exc:
raise ValueError(f"{field_name} must be valid JSON: {exc.msg}") from exc
if not isinstance(parsed, dict):
raise ValueError(f"{field_name} must be a JSON object")
return parsed
def benchmark_supports_chat_template(benchmark):
return benchmark not in CHAT_TEMPLATE_UNSAFE_BENCHMARKS
def get_effective_chat_template_settings(benchmark):
requested = bool(apply_chat_template)
enabled = requested and benchmark_supports_chat_template(benchmark)
disabled_reason = "task_incompatible" if requested and not enabled else None
return enabled, disabled_reason
st.set_page_config(page_title="TeichAI Benchmark Suite", layout="wide")
st.title("TeichAI Model Benchmark Suite")
results_placeholder = st.empty()
native_windows = sys.platform.startswith("win")
# --- Sidebar Configuration ---
st.sidebar.header("Configuration")
# Model Selection
default_model = "TeichAI/Qwen3-4B-Thinking-2507-Gemini-2.5-Flash-Distill"
models_input = st.sidebar.text_area(
"Models (one per line)", value=default_model, height=100
)
models = [m.strip() for m in models_input.split("\n") if m.strip()]
# Benchmark (lm_eval task) Selection
benchmarks = st.sidebar.multiselect(
"Benchmarks",
[
"gpqa_diamond_zeroshot",
"gsm8k",
"winogrande",
"arc_challenge",
"hellaswag",
"truthfulqa_mc2",
"mmlu",
"ifeval",
"humaneval",
],
default=["gpqa_diamond_zeroshot"],
)
# DeepEval
run_deepeval = st.sidebar.checkbox("Run DeepEval (Qualitative Metrics)", value=False)
if run_deepeval and not os.getenv("OPENROUTER_API_KEY"):
st.sidebar.warning("OPENROUTER_API_KEY not set. DeepEval may fail.")
# HuggingFace Token (for private models)
with st.sidebar.expander("HuggingFace Token"):
hf_token = st.text_input(
"HF Token",
type="password",
help="Enter your HuggingFace token to access private/gated models. "
"Get one at https://huggingface.co/settings/tokens",
)
if hf_token:
st.success("Token provided")
# Settings
backend_options = ["hf"] if native_windows else ["hf", "vllm"]
backend = st.sidebar.selectbox(
"Inference Backend",
backend_options,
index=0,
help="'hf' = HuggingFace Transformers (works everywhere). "
"'vllm' = vLLM (Linux/WSL only, much faster for generation tasks like ifeval/humaneval).",
)
if native_windows:
st.sidebar.info(
"Native Windows detected: `vllm` is disabled in the UI. Use `hf` or run the suite under Linux/WSL for `vllm`."
)
quantization = st.sidebar.selectbox(
"Quantization",
["4bit", "8bit", "none"],
index=2,
help="Use `none` for the most trustworthy and leaderboard-comparable results. Low-bit quantization is mainly a speed/memory tradeoff.",
)
if quantization != "none":
st.sidebar.warning(
"Low-bit quantization can materially change benchmark scores. Use `none` if you care about fair comparison."
)
vllm_max_model_len_default = int(os.getenv("VLLM_MAX_MODEL_LEN", "8192"))
vllm_max_model_len = st.sidebar.number_input(
"vLLM Max Context Length",
min_value=512,
max_value=262144,
value=vllm_max_model_len_default,
step=512,
disabled=backend != "vllm",
help="Sets vLLM max_model_len to limit KV cache memory."
" Only applies to vLLM backend.",
)
allow_code_eval = st.sidebar.checkbox(
"Allow code execution (Humaneval/code_eval)",
value=False,
disabled="humaneval" not in benchmarks,
help=(
"Required for Humaneval/code_eval. Runs untrusted model code; "
"enable only in a sandboxed environment."
),
)
apply_chat_template = st.sidebar.checkbox(
"Apply chat template",
value=True,
help="Recommended for instruct/chat models to format prompts correctly.",
)
chat_template_kwargs_input = st.sidebar.text_area(
"Chat template kwargs (JSON)",
value="",
height=80,
disabled=not apply_chat_template,
help='Optional JSON object passed into the model chat template, e.g. {"enable_thinking": true}.',
)
chat_template_kwargs = None
chat_template_kwargs_error = None
if apply_chat_template:
try:
chat_template_kwargs = parse_json_object_input(
chat_template_kwargs_input,
"Chat template kwargs",
)
except ValueError as exc:
chat_template_kwargs_error = str(exc)
if chat_template_kwargs_input.strip():
st.sidebar.error(chat_template_kwargs_error)
if apply_chat_template:
incompatible_chat_template_benchmarks = [
benchmark for benchmark in benchmarks if not benchmark_supports_chat_template(benchmark)
]
if incompatible_chat_template_benchmarks:
st.sidebar.warning(
"Chat template will be auto-disabled for "
f"{', '.join(incompatible_chat_template_benchmarks)} because assistant-prefill/reasoning prefixes can corrupt multiple-choice likelihood benchmarking."
)
overwrite_saved = st.sidebar.checkbox("Overwrite saved results", value=False)
fewshot_mode = st.sidebar.selectbox(
"Few-shot",
["Task default (recommended)", "Zero-shot (0)", "Custom"],
index=0,
)
if fewshot_mode == "Zero-shot (0)":
num_fewshot = 0
elif fewshot_mode == "Custom":
num_fewshot = st.sidebar.number_input("num_fewshot", min_value=0, value=5)
else:
num_fewshot = None
override_gen_kwargs = st.sidebar.checkbox(
"Override generation settings (advanced)",
value=False,
)
# Sampling Parameters
with st.sidebar.expander("Sampling Parameters"):
do_sample = st.checkbox(
"Enable sampling (not recommended for reproducible benchmarks)",
value=False,
disabled=not override_gen_kwargs,
)
temperature = st.slider(
"Temperature",
0.0,
2.0,
0.0,
)
top_p = st.slider(
"Top P",
0.0,
1.0,
1.0,
)
top_k = st.number_input(
"Top K",
value=0,
min_value=0,
)
repetition_penalty = st.slider(
"Repetition Penalty",
1.0,
2.0,
1.0,
)
batch_size = st.number_input("Batch size (lm_eval)", min_value=1, value=1)
if override_gen_kwargs:
st.sidebar.warning(
"Manual generation overrides make runs harder to compare across models and across reruns."
)
if do_sample:
st.sidebar.error(
"Sampling is enabled. This run is experimental and should not be treated as a stable benchmark result."
)
# Run / View Controls
view_saved_only = st.sidebar.checkbox(
"View saved results only (no new runs)", value=False
)
run_clicked = st.sidebar.button("Run Benchmarks", type="primary")
def is_valid_lm_eval_payload(data):
if not isinstance(data, dict):
return False
lm_data = data.get("lm_eval")
if not isinstance(lm_data, dict):
return False
lm_results = lm_data.get("results")
return isinstance(lm_results, dict) and bool(lm_results)
def get_model_filename_keys(model):
model_text = str(model)
keys = [quote(model_text, safe="")]
legacy_key = model_text.replace("/", "_")
if legacy_key not in keys:
keys.append(legacy_key)
return keys
def get_cache_path(model, benchmark):
return os.path.join(
"saved_results", f"results_{get_model_filename_keys(model)[0]}_{benchmark}.json"
)
def get_cache_path_candidates(model, benchmark):
return [
os.path.join("saved_results", f"results_{key}_{benchmark}.json")
for key in get_model_filename_keys(model)
]
def get_raw_result_path(model, benchmark):
return os.path.join(
"saved_results",
f"results_raw_{get_model_filename_keys(model)[0]}_{benchmark}.json",
)
def get_deepeval_result_path_candidates(model, benchmark):
candidates = [
os.path.join("saved_results", f"results_raw_{key}_{benchmark}_deepeval.json")
for key in get_model_filename_keys(model)
]
candidates.extend(
f"results_{key}_{benchmark}_deepeval.json"
for key in get_model_filename_keys(model)
)
return list(dict.fromkeys(candidates))
def load_json_file(path):
with open(path, "r") as f:
return json.load(f)
def unpack_result_payload(payload):
if isinstance(payload, dict) and "data" in payload:
return payload.get("config"), payload.get("data")
return None, payload
def coerce_scalar(value):
if isinstance(value, (bool, int, float)) or value is None:
return value
if isinstance(value, str):
text = value.strip()
lowered = text.lower()
if lowered == "true":
return True
if lowered == "false":
return False
if lowered in {"none", "null"}:
return None
try:
if all(ch not in lowered for ch in [".", "e"]):
return int(text)
except ValueError:
pass
try:
return float(text)
except ValueError:
return text
return value
def parse_model_args(model_args):
if isinstance(model_args, dict):
return dict(model_args)
if not isinstance(model_args, str):
return {}
parsed = {}
for item in model_args.split(","):
if "=" not in item:
continue
key, value = item.split("=", 1)
parsed[key.strip()] = coerce_scalar(value.strip())
return parsed
def is_probably_chat_model(model_name):
lowered = str(model_name).lower()
return any(token in lowered for token in ["instruct", "chat", "assistant", "reasoning"])
def load_saved_run_config(model, benchmark):
for candidate in get_cache_path_candidates(model, benchmark):
if not os.path.exists(candidate):
continue
try:
candidate_config, candidate_data = unpack_result_payload(load_json_file(candidate))
except Exception:
continue
if isinstance(candidate_config, dict) and is_valid_lm_eval_payload(candidate_data):
return candidate_config
return None
def extract_run_diagnostics(model, benchmark, data, saved_config=None):
lm_data = data.get("lm_eval", {}) if isinstance(data, dict) else {}
lm_config = lm_data.get("config", {}) if isinstance(lm_data, dict) else {}
if not isinstance(lm_config, dict):
lm_config = {}
saved_config = saved_config if isinstance(saved_config, dict) else {}
model_args = parse_model_args(lm_config.get("model_args"))
gen_kwargs = lm_config.get("gen_kwargs")
if not isinstance(gen_kwargs, dict):
gen_kwargs = {}
backend_name = saved_config.get("backend") or lm_config.get("model") or "-"
quantization_name = saved_config.get("quantization")
if not quantization_name:
if model_args.get("load_in_4bit") is True:
quantization_name = "4bit"
elif model_args.get("load_in_8bit") is True:
quantization_name = "8bit"
elif model_args.get("quantization") == "bitsandbytes":
quantization_name = "low-bit"
else:
quantization_name = "none"
override_generation = bool(saved_config.get("override_gen_kwargs")) or bool(gen_kwargs)
if override_generation:
sampling_enabled = bool(saved_config.get("do_sample")) if saved_config else bool(gen_kwargs.get("do_sample"))
temperature_value = saved_config.get("temperature") if saved_config else gen_kwargs.get("temperature")
top_p_value = saved_config.get("top_p") if saved_config else gen_kwargs.get("top_p")
top_k_value = saved_config.get("top_k") if saved_config else gen_kwargs.get("top_k")
repetition_penalty_value = saved_config.get("repetition_penalty") if saved_config else gen_kwargs.get("repetition_penalty")
else:
sampling_enabled = False
temperature_value = None
top_p_value = None
top_k_value = None
repetition_penalty_value = None
apply_chat_template_value = saved_config.get("apply_chat_template")
chat_template_disabled_reason = saved_config.get("chat_template_disabled_reason")
if apply_chat_template_value is None:
if "chat_template_args" in model_args or "enable_thinking" in model_args:
apply_chat_template_value = True
thinking_value = None
chat_template_kwargs_value = saved_config.get("chat_template_kwargs")
if isinstance(chat_template_kwargs_value, dict):
thinking_value = chat_template_kwargs_value.get("enable_thinking")
if thinking_value is None:
chat_template_args_value = model_args.get("chat_template_args")
if isinstance(chat_template_args_value, dict):
thinking_value = chat_template_args_value.get("enable_thinking")
if thinking_value is None:
thinking_value = model_args.get("enable_thinking")
limit_value = lm_config.get("limit")
limit_display = "full" if limit_value is None else str(limit_value)
fewshot_value = saved_config.get("num_fewshot")
fewshot_display = "task default" if fewshot_value is None else str(fewshot_value)
batch_size_value = saved_config.get("batch_size", lm_config.get("batch_size", "-"))
precision_value = model_args.get("dtype") or lm_config.get("model_dtype") or "-"
device_value = lm_config.get("device") or "-"
seed_parts = [
lm_config.get("random_seed"),
lm_config.get("numpy_seed"),
lm_config.get("torch_seed"),
]
seed_values = [str(seed) for seed in seed_parts if seed is not None]
seeds_display = ", ".join(seed_values) if seed_values else "-"
notes = []
if limit_value is not None:
notes.append(f"partial dataset (limit={limit_display})")
if quantization_name in {"4bit", "8bit", "low-bit"}:
notes.append(f"{quantization_name} quantization")
if sampling_enabled:
notes.append("sampling enabled")
if fewshot_value is not None:
notes.append(f"few-shot override={fewshot_display}")
if (
apply_chat_template_value is False
and is_probably_chat_model(model)
and chat_template_disabled_reason != "task_incompatible"
):
notes.append("chat template disabled")
comparable = not notes
if apply_chat_template_value is True:
chat_template_display = "On"
elif chat_template_disabled_reason == "task_incompatible":
chat_template_display = "Auto-disabled"
elif apply_chat_template_value is False:
chat_template_display = "Off"
else:
chat_template_display = "Unknown"
if thinking_value is True:
thinking_display = "On"
elif thinking_value is False:
thinking_display = "Off"
else:
thinking_display = "-"
return {
"Model": model,
"Benchmark": benchmark,
"Comparable": "Yes" if comparable else "No",
"Backend": backend_name,
"Quantization": quantization_name,
"Sampling": "On" if sampling_enabled else "Off",
"Temperature": "-" if temperature_value is None else str(temperature_value),
"Top P": "-" if top_p_value is None else str(top_p_value),
"Top K": "-" if top_k_value is None else str(top_k_value),
"Repetition Penalty": "-" if repetition_penalty_value is None else str(repetition_penalty_value),
"Few-shot": fewshot_display,
"Limit": limit_display,
"Chat Template": chat_template_display,
"Thinking": thinking_display,
"Batch Size": str(batch_size_value),
"Precision": str(precision_value),
"Device": str(device_value),
"Seeds": seeds_display,
"Notes": "; ".join(notes) if notes else "None detected",
}
def build_result_entry(model, benchmark, data, saved_config=None):
score, total_questions, total_correct = summarize_results(model, benchmark, data)
diagnostics = extract_run_diagnostics(model, benchmark, data, saved_config=saved_config)
return {
"Model": model,
"Benchmark": benchmark,
"Score": score,
"Total Questions": int(total_questions),
"Total Correct": int(total_correct),
"Comparable": diagnostics["Comparable"],
"Notes": diagnostics["Notes"],
"Run Config": saved_config,
"Run Diagnostics": diagnostics,
"Details": data,
}
def render_results(results_data):
if not results_data:
return
st.divider()
st.header("Results Comparison")
df = pd.DataFrame(results_data)
all_models = sorted(df["Model"].unique())
all_benchmarks = sorted(df["Benchmark"].unique())
selected_models = st.multiselect(
"Models to display",
options=all_models,
default=all_models,
key="results_filter_models",
)
selected_benchmarks = st.multiselect(
"Benchmarks to display",
options=all_benchmarks,
default=all_benchmarks,
key="results_filter_benchmarks",
)
st.session_state.selected_models_for_mmlu = selected_models
filtered_df = df[
df["Model"].isin(selected_models) & df["Benchmark"].isin(selected_benchmarks)
]
if filtered_df.empty:
st.info("No data for current selection.")
return
filtered_results = [
item
for item in results_data
if item["Model"] in selected_models and item["Benchmark"] in selected_benchmarks
]
diagnostics_df = pd.DataFrame(
[item.get("Run Diagnostics", {}) for item in filtered_results]
)
provenance_columns = [
"Model",
"Benchmark",
"Comparable",
"Backend",
"Quantization",
"Sampling",
"Temperature",
"Few-shot",
"Limit",
"Chat Template",
"Thinking",
"Batch Size",
"Precision",
"Device",
"Seeds",
"Notes",
]
provenance_export_df = (
diagnostics_df[provenance_columns].copy() if not diagnostics_df.empty else pd.DataFrame()
)
long_form_df = pd.DataFrame(
[
{
"Model": item["Model"],
"Benchmark": item["Benchmark"],
"Score": item["Score"],
"Total Questions": item["Total Questions"],
"Total Correct": item["Total Correct"],
"Comparable": (item.get("Run Diagnostics") or {}).get("Comparable", "Unknown"),
"Backend": (item.get("Run Diagnostics") or {}).get("Backend", "-"),
"Quantization": (item.get("Run Diagnostics") or {}).get("Quantization", "-"),
"Sampling": (item.get("Run Diagnostics") or {}).get("Sampling", "-"),
"Chat Template": (item.get("Run Diagnostics") or {}).get("Chat Template", "-"),
"Limit": (item.get("Run Diagnostics") or {}).get("Limit", "-"),
"Notes": (item.get("Run Diagnostics") or {}).get("Notes", "-"),
}
for item in filtered_results
]
)
if not diagnostics_df.empty:
displayed_runs = int(len(diagnostics_df))
comparable_runs = int((diagnostics_df["Comparable"] == "Yes").sum())
experimental_runs = displayed_runs - comparable_runs
partial_runs = int((diagnostics_df["Limit"] != "full").sum())
metric_cols = st.columns(4)
metric_cols[0].metric("Displayed runs", displayed_runs)
metric_cols[1].metric("Comparable runs", comparable_runs)
metric_cols[2].metric("Experimental runs", experimental_runs)
metric_cols[3].metric("Partial runs", partial_runs)
if experimental_runs:
st.warning(
"Some displayed results were produced under settings that make direct comparison unreliable. Check the run provenance table before trusting rank order."
)
st.subheader("Run Provenance")
st.caption(
"These fields are extracted from saved run configs and lm_eval output so you can see what was actually run."
)
st.dataframe(provenance_export_df, use_container_width=True)
score_matrix = (
filtered_df.pivot_table(
index="Benchmark", columns="Model", values="Score", aggfunc="mean"
)
.reindex(columns=selected_models)
.sort_index()
)
def _highlight_row_winners(row):
valid = row.dropna()
if valid.empty:
return ["" for _ in row]
winner = valid.max()
return [
"background-color: #dcfce7; color: #166534; font-weight: 700;"
if pd.notna(v) and v == winner
else ""
for v in row
]
def _highlight_outcome_row(row):
outcome = row.get("Outcome")
if outcome == "Primary model ahead":
style = "background-color: #dcfce7; color: #111827;"
elif outcome == "Comparison models ahead":
style = "background-color: #fee2e2; color: #111827;"
elif outcome == "Tie":
style = "background-color: #fef3c7; color: #111827;"
else:
style = ""
return [style for _ in row]
def _highlight_delta_column(values):
styles = []
for value in values:
if pd.isna(value):
styles.append("")
elif float(value) > 0:
styles.append("color: #166534; font-weight: 700;")
elif float(value) < 0:
styles.append("color: #991b1b; font-weight: 700;")
else:
styles.append("color: #92400e; font-weight: 700;")
return styles
def _score_to_text(v):
return "-" if pd.isna(v) else f"{float(v):.3f}"
def _score_to_md(v, is_winner):
if pd.isna(v):
return "-"
value = f"{float(v):.3f}"
return f"**{value}**" if is_winner else value
def _safe_to_markdown(table_df):
try:
return table_df.to_markdown(index=False)
except ImportError:
return table_df.to_csv(index=False)
matrix_md_rows = []
for benchmark_name, row in score_matrix.iterrows():
valid = row.dropna()
winner_score = valid.max() if not valid.empty else None
row_data = {"Benchmark": benchmark_name}
for model_name in score_matrix.columns:
value = row[model_name]
is_winner = pd.notna(value) and winner_score is not None and value == winner_score
row_data[model_name] = _score_to_md(value, is_winner)
matrix_md_rows.append(row_data)
score_matrix_md_df = pd.DataFrame(matrix_md_rows)
st.subheader("Head-to-Head Score Matrix")
st.caption(
"Rows are benchmarks, columns are models. Best score in each row is highlighted."
)
st.dataframe(
score_matrix.style.format("{:.3f}", na_rep="-").apply(
_highlight_row_winners, axis=1
),
use_container_width=True,
)
with st.expander("View matrix in markdown format"):
st.markdown(_safe_to_markdown(score_matrix_md_df))
st.subheader("Head-to-head model comparison")
st.caption(
"Choose the primary model first, then add the comparison models you want to measure it against."
)
base_model = st.selectbox(
"Primary model",
options=selected_models,
index=0,
key="base_model_select",
)
compare_options = [m for m in selected_models if m != base_model]
compare_models = st.multiselect(
"Comparison models",
options=compare_options,
default=compare_options,
key="compare_models_select",
)
comparison_summary_df = pd.DataFrame()
benchmark_outcome_df = pd.DataFrame()
key_takeaways = []
if compare_models and base_model in score_matrix.columns:
summary_rows = []
for model_name in compare_models:
if model_name not in score_matrix.columns:
continue
pair = score_matrix[[base_model, model_name]].dropna()
if pair.empty:
continue
base_wins = int((pair[base_model] > pair[model_name]).sum())
base_losses = int((pair[base_model] < pair[model_name]).sum())
ties = int((pair[base_model] == pair[model_name]).sum())
avg_delta = float((pair[base_model] - pair[model_name]).mean())
summary_rows.append(
{
"Comparison Model": model_name,
"Benchmarks Compared": int(len(pair)),
"Primary Model Wins": base_wins,
"Primary Model Losses": base_losses,
"Ties": ties,
"Avg Score Gap (Primary - Comparison)": avg_delta,
}
)
if summary_rows:
comparison_summary_df = pd.DataFrame(summary_rows).sort_values(
"Avg Score Gap (Primary - Comparison)", ascending=False
)
outcome_rows = []
for benchmark_name, row in score_matrix.iterrows():
base_score = row.get(base_model)
if pd.isna(base_score):
continue
competitor_scores = row[compare_models].dropna()
if competitor_scores.empty:
continue
best_competitor = competitor_scores.idxmax()
best_competitor_score = float(competitor_scores.max())
delta = float(base_score - best_competitor_score)
if delta > 0:
outcome = "Primary model ahead"
elif delta < 0:
outcome = "Comparison models ahead"
else:
outcome = "Tie"
outcome_rows.append(
{
"Benchmark": benchmark_name,
"Primary Model Score": float(base_score),
"Best Comparison Model": best_competitor,
"Best Comparison Score": best_competitor_score,
"Score Gap (Primary - Best Comparison)": delta,
"Outcome": outcome,
}
)
if outcome_rows:
benchmark_outcome_df = pd.DataFrame(outcome_rows).sort_values("Benchmark")
if not benchmark_outcome_df.empty:
wins = int((benchmark_outcome_df["Outcome"] == "Primary model ahead").sum())
losses = int((benchmark_outcome_df["Outcome"] == "Comparison models ahead").sum())
ties = int((benchmark_outcome_df["Outcome"] == "Tie").sum())
key_takeaways.append(
f"Primary model ({base_model}): {wins} wins, {losses} losses, {ties} ties across selected benchmarks."
)
if not comparison_summary_df.empty:
strongest = comparison_summary_df.iloc[-1]
weakest = comparison_summary_df.iloc[0]
key_takeaways.append(
f"Hardest comparison model: {strongest['Comparison Model']} (Avg Δ={strongest['Avg Score Gap (Primary - Comparison)']:.3f})."
)
key_takeaways.append(
f"Easiest comparison model: {weakest['Comparison Model']} (Avg Δ={weakest['Avg Score Gap (Primary - Comparison)']:.3f})."
)
if not benchmark_outcome_df.empty:
st.subheader("Benchmark-by-benchmark comparison")
st.dataframe(
benchmark_outcome_df.style.format(
{
"Primary Model Score": "{:.3f}",
"Best Comparison Score": "{:.3f}",
"Score Gap (Primary - Best Comparison)": "{:.3f}",
}
).apply(_highlight_outcome_row, axis=1).apply(
_highlight_delta_column,
subset=["Score Gap (Primary - Best Comparison)"],
axis=0,
),
use_container_width=True,
)
if not comparison_summary_df.empty:
st.subheader("Comparison summary")
st.dataframe(
comparison_summary_df.style.format(
{"Avg Score Gap (Primary - Comparison)": "{:.3f}"}
).apply(
_highlight_delta_column,
subset=["Avg Score Gap (Primary - Comparison)"],
axis=0,
),
use_container_width=True,
)
if key_takeaways:
st.subheader("Quick Read")
for line in key_takeaways:
st.markdown(f"- {line}")
# Bar Chart
fig = px.bar(
filtered_df,
x="Model",
y="Score",
color="Benchmark",
barmode="group",
title="Benchmark Results",
text_auto=".2f",
)
fig.update_layout(
yaxis=dict(range=[0, 1], fixedrange=True),
legend=dict(
orientation="h",
yanchor="bottom",
y=1.02,
xanchor="center",
x=0.5,
),
margin=dict(t=80, b=120, l=60, r=60),
)
st.plotly_chart(
fig,
use_container_width=True,
key="results_bar_chart",
config=PLOTLY_DOWNLOAD_CONFIG,
)
with st.expander("View long-form rows"):
st.dataframe(
long_form_df,
use_container_width=True,
)
# Raw Data Expander (full, unfiltered data)
with st.expander("View Raw Results"):
st.json(results_data)
# Export to Markdown / ZIP / PDF (filtered view)
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
display_timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
md_content = "# Benchmark Results Report\n\n"
md_content += f"**Date:** {display_timestamp}\n\n"
md_content += "## Scope\n"
md_content += f"- **Displayed models:** {', '.join(selected_models)}\n"
md_content += f"- **Displayed benchmarks:** {', '.join(selected_benchmarks)}\n"
md_content += f"- **Primary comparison model:** {base_model}\n"
if not diagnostics_df.empty:
md_content += f"- **Comparable runs:** {comparable_runs}/{displayed_runs}\n"
md_content += f"- **Experimental runs:** {experimental_runs}\n"
md_content += f"- **Partial runs:** {partial_runs}\n"
md_content += "\n"
if not provenance_export_df.empty:
md_content += "## Run Provenance\n\n"
md_content += _safe_to_markdown(provenance_export_df)
md_content += "\n\n"
md_content += "## Head-to-Head Score Matrix\n\n"
md_content += _safe_to_markdown(score_matrix_md_df)
if not benchmark_outcome_df.empty:
md_content += "\n\n## Benchmark-by-benchmark comparison\n\n"
benchmark_outcome_export = benchmark_outcome_df.copy()
md_content += _safe_to_markdown(benchmark_outcome_export)
if not comparison_summary_df.empty:
md_content += "\n\n## Comparison summary\n\n"
md_content += _safe_to_markdown(comparison_summary_df)
if key_takeaways:
md_content += "\n\n## Quick Read\n\n"
for line in key_takeaways:
md_content += f"- {line}\n"
md_content += "\n\n## Full Row Data\n\n"
md_content += _safe_to_markdown(long_form_df)
mmlu_filtered = None
mmlu_subject_results = st.session_state.get("mmlu_subject_results")
if mmlu_subject_results:
mmlu_df = pd.DataFrame(mmlu_subject_results)
mmlu_df["Subject"] = mmlu_df["Benchmark"].apply(
lambda b: (
b[len("mmlu_") :] if isinstance(b, str) and b.startswith("mmlu_") else b
)
)
mmlu_filtered = mmlu_df[mmlu_df["Model"].isin(selected_models)]
if not mmlu_filtered.empty:
md_content += "\n\n## MMLU Subject Breakdown\n\n"
md_content += (
'\n\n'
)
mmlu_export = mmlu_filtered[
[
"Model",
"Subject",