alozowski HF Staff commited on
Commit
d8b2714
·
verified ·
1 Parent(s): 4ec8b01

Upload folder using huggingface_hub

Browse files
Files changed (5) hide show
  1. __pycache__/env.cpython-312.pyc +0 -0
  2. app.py +26 -0
  3. env.py +17 -0
  4. requirements.txt +2 -0
  5. utils.py +312 -0
__pycache__/env.cpython-312.pyc ADDED
Binary file (701 Bytes). View file
 
app.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from env import TASK
2
+ from utils import run_pipeline, update_examples
3
+
4
+ import gradio as gr
5
+
6
+
7
+ with gr.Blocks(
8
+ title="YourBench Leaderboard",
9
+ css="button { margin: 0 10px; padding: 5px 15px; }",
10
+ ) as app:
11
+ # DISPLAY TABLE AND ANALYSIS
12
+ title = gr.Markdown(f"YourBench auto-Leaderboard for {TASK}")
13
+ leaderboard = gr.DataFrame(label="Results", interactive=False)
14
+ samples_ix = gr.Number(label="Example Index", value=0, step=1, info="Navigate through different examples")
15
+ with gr.Tab("Hardest samples"):
16
+ hard_samples = gr.HTML()
17
+ with gr.Tab("Easiest samples"):
18
+ easy_samples = gr.HTML()
19
+ with gr.Tab("All samples"):
20
+ all_samples = gr.HTML()
21
+
22
+ samples_ix.change(update_examples, samples_ix, [easy_samples, hard_samples, all_samples])
23
+
24
+ app.load(run_pipeline, [samples_ix], [leaderboard, easy_samples, hard_samples, all_samples])
25
+
26
+ app.launch()
env.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+
4
+ INIT_MODELS = [
5
+ # 70B
6
+ ("Qwen/Qwen2.5-72B-Instruct", "novita"),
7
+ ("meta-llama/Llama-3.3-70B-Instruct", "novita"),
8
+ ("deepseek-ai/DeepSeek-R1-Distill-Llama-70B", "novita"),
9
+ # 20 to 30B
10
+ ("Qwen/QwQ-32B", "novita"),
11
+ ("mistralai/Mistral-Small-24B-Instruct-2501", "together"),
12
+ ]
13
+ MODELS = [m[0] for m in INIT_MODELS]
14
+ TASK = os.getenv("TASK")
15
+ # With storage
16
+ HF_TOKEN = os.getenv("HF_TOKEN")
17
+ ORG_NAME = os.getenv("ORG_NAME")
requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ datasets
2
+ huggingface_hub
utils.py ADDED
@@ -0,0 +1,312 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from typing import Any
3
+
4
+ from env import TASK, MODELS, ORG_NAME
5
+
6
+ import gradio as gr
7
+ from datasets import Dataset, load_dataset
8
+
9
+
10
+ KNOWN_METRIC_LABELS = {
11
+ "accuracy": "Accuracy",
12
+ "accuracy_stderr": "Accuracy (stderr)",
13
+ }
14
+
15
+
16
+ def aggregate_results() -> list:
17
+ """Extract scores for each model and return list of result dictionaries."""
18
+ all_results = []
19
+ for model_path in MODELS:
20
+ try:
21
+ path = f"{ORG_NAME}/details_{model_path.replace('/', '__')}_private"
22
+ dataset = load_dataset(path, "results", split="latest")
23
+ config = json.loads(dataset["config_general"][0])
24
+ results = json.loads(dataset["results"][0])
25
+
26
+ _, model = model_path.split("/")
27
+ duration = round(config["end_time"] - config["start_time"], 2)
28
+
29
+ result = {
30
+ "Model": model,
31
+ "Duration (s)": duration,
32
+ }
33
+
34
+ for metric, metric_values in results.items():
35
+ if metric == "all":
36
+ continue
37
+
38
+ for raw_metric_name, metric_value in metric_values.items():
39
+ base_name = raw_metric_name.split("(")[0].strip()
40
+ pretty_label = KNOWN_METRIC_LABELS.get(base_name, raw_metric_name)
41
+
42
+ if isinstance(metric_value, float):
43
+ metric_value = round(metric_value, 3)
44
+
45
+ result[pretty_label] = metric_value
46
+
47
+ all_results.append(result)
48
+
49
+ except Exception as e:
50
+ print(f"Error processing {model_path} {ORG_NAME}: {e}")
51
+
52
+ # Sort final result by Accuracy
53
+ all_results.sort(key=lambda r: r.get("Accuracy", 0), reverse=True)
54
+
55
+ return all_results
56
+
57
+
58
+ def extract_dataviz() -> tuple[list[dict[str, Any]], list[dict[str, Any]], list[dict[str, Any]]]:
59
+ """Extract best, worst, and all samples for visualization"""
60
+ sample_index_map = {}
61
+
62
+ for model_path in MODELS:
63
+ try:
64
+ dataset_path = f"{ORG_NAME}/details_{model_path.replace('/', '__')}_private"
65
+ split_name = f"custom_{TASK.replace('/', '_')}_0"
66
+ dataset = load_dataset(dataset_path, split_name, split="latest")
67
+
68
+ for idx, row in enumerate(dataset):
69
+ prompt = row["full_prompt"]
70
+ gold = row.get("gold", "")
71
+ gold = gold[0] if isinstance(gold, list) and gold else gold
72
+ score = list(row["metrics"].values())[0]
73
+ predictions = row.get("predictions", [])
74
+ prediction = predictions[0] if predictions else ""
75
+
76
+ if idx not in sample_index_map:
77
+ sample_index_map[idx] = {
78
+ "ix": idx,
79
+ "prompt": prompt,
80
+ "gold": gold,
81
+ "model_scores": [],
82
+ "models": [],
83
+ }
84
+
85
+ if model_path not in sample_index_map[idx]["models"]:
86
+ sample_index_map[idx][f"{model_path}_score"] = row["metrics"]
87
+ sample_index_map[idx][f"{model_path}_prediction"] = prediction
88
+ sample_index_map[idx]["model_scores"].append(score)
89
+ sample_index_map[idx]["models"].append(model_path)
90
+
91
+ except Exception as e:
92
+ print(f"Error processing {model_path}: {e}")
93
+
94
+ all_samples = sorted(sample_index_map.values(), key=lambda r: r["ix"])
95
+
96
+ hard_samples = [sample for sample in all_samples if sum(sample["model_scores"]) == 0]
97
+
98
+ easy_samples = [sample for sample in all_samples if sum(sample["model_scores"]) == len(sample["model_scores"])]
99
+
100
+ return easy_samples, hard_samples, all_samples
101
+
102
+
103
+ def samples_to_box_display(samples: list[dict[str, Any]], example_index: int = 0) -> str:
104
+ """
105
+ Adapted from Nathan's code https://huggingface.co/spaces/SaylorTwift/OpenEvalsModelDetails/
106
+ Support both light and dark themes
107
+ """
108
+ if not samples:
109
+ return "No samples in this category!"
110
+
111
+ sample = samples[example_index]
112
+ outputs = []
113
+
114
+ for model in sample["models"]:
115
+ try:
116
+ outputs.append({
117
+ "Model": model,
118
+ "Prediction": sample[f"{model}_prediction"],
119
+ "Prompt": sample["prompt"],
120
+ "Metrics": sample[f"{model}_score"],
121
+ "Gold": sample["gold"],
122
+ })
123
+ except (KeyError, IndexError):
124
+ continue
125
+
126
+ if not outputs:
127
+ return "No results found for the selected combination."
128
+
129
+ # CSS for theme compatibility
130
+ css = """
131
+ <style>
132
+ :root {
133
+ --primary-bg: #f5f5f5;
134
+ --secondary-bg: #ffffff;
135
+ --gold-bg: #e6f3e6;
136
+ --text-color: #333333;
137
+ --border-color: #ddd;
138
+ }
139
+
140
+ @media (prefers-color-scheme: dark) {
141
+ :root {
142
+ --primary-bg: #2a2a2a;
143
+ --secondary-bg: #333333;
144
+ --gold-bg: #2a3a2a;
145
+ --text-color: #e0e0e0;
146
+ --border-color: #555;
147
+ }
148
+ }
149
+
150
+ .box-container {
151
+ max-width: 800px;
152
+ margin: 0 auto;
153
+ color: var(--text-color);
154
+ }
155
+
156
+ .gold-box {
157
+ background: var(--gold-bg);
158
+ padding: 20px;
159
+ border-radius: 10px;
160
+ margin-bottom: 20px;
161
+ }
162
+
163
+ .model-box {
164
+ background: var(--primary-bg);
165
+ padding: 20px;
166
+ margin-bottom: 20px;
167
+ border-radius: 10px;
168
+ }
169
+
170
+ .content-section {
171
+ background: var(--secondary-bg);
172
+ padding: 15px;
173
+ border-radius: 5px;
174
+ margin-top: 10px;
175
+ }
176
+
177
+ .metric-row {
178
+ padding: 5px;
179
+ border-bottom: 1px solid var(--border-color);
180
+ }
181
+
182
+ h2, h3 {
183
+ color: var(--text-color);
184
+ }
185
+
186
+ pre, code {
187
+ white-space: pre-wrap;
188
+ word-wrap: break-word;
189
+ margin: 0;
190
+ color: var(--text-color);
191
+ }
192
+ </style>
193
+ """
194
+
195
+ # Create HTML output with all models
196
+ html_output = f"{css}<div class='box-container'>\n\n"
197
+
198
+ # Show gold answer at the top with distinct styling
199
+ if outputs:
200
+ html_output += "<div class='gold-box'>\n"
201
+ html_output += "<h3 style='margin-top: 0;'>Ground Truth</h3>\n"
202
+ html_output += "<div style='overflow-x: auto; max-width: 100%;'>\n"
203
+ html_output += f"<pre><code>{outputs[0]['Gold']}</code></pre>\n"
204
+ html_output += "</div>\n"
205
+ html_output += "</div>\n"
206
+
207
+ for output in outputs:
208
+ html_output += "<div class='model-box'>\n"
209
+ html_output += f"<h2 style='margin-top: 0;'>{output['Model']}</h2>\n"
210
+
211
+ # Format metrics as a clean table
212
+ html_output += "<details open style='margin-bottom: 15px;'>\n"
213
+ html_output += "<summary><h3 style='display: inline; margin: 0;'>Metrics</h3></summary>\n"
214
+ metrics = output["Metrics"]
215
+ if isinstance(metrics, str):
216
+ metrics = eval(metrics)
217
+ html_output += "<div style='overflow-x: auto;'>\n"
218
+ html_output += "<table style='width: 100%; margin: 10px 0; border-collapse: collapse;'>\n"
219
+ for key, value in metrics.items():
220
+ if isinstance(value, float):
221
+ value = f"{value:.3f}"
222
+ html_output += f"<tr class='metric-row'><td><strong>{key}</strong></td><td>{value}</td></tr>\n"
223
+ html_output += "</table>\n"
224
+ html_output += "</div>\n"
225
+ html_output += "</details>\n\n"
226
+
227
+ # Handle prompt formatting with better styling
228
+ html_output += "<details style='margin-bottom: 15px;'>\n"
229
+ html_output += "<summary><h3 style='display: inline; margin: 0;'>Prompt</h3></summary>\n"
230
+ html_output += "<div class='content-section'>\n"
231
+
232
+ prompt_text = output["Prompt"]
233
+ if isinstance(prompt_text, list):
234
+ for i, msg in enumerate(prompt_text):
235
+ if isinstance(msg, dict) and "content" in msg:
236
+ role = msg.get("role", "message").title()
237
+ html_output += "<div style='margin-bottom: 10px;'>\n"
238
+ html_output += f"<strong>{role}:</strong>\n"
239
+ html_output += "<div style='overflow-x: auto;'>\n"
240
+ html_output += f"<pre><code>{msg['content']}</code></pre>\n"
241
+ html_output += "</div>\n"
242
+ html_output += "</div>\n"
243
+ else:
244
+ html_output += "<div style='margin-bottom: 10px;'>\n"
245
+ html_output += "<div style='overflow-x: auto;'>\n"
246
+ html_output += f"<pre><code>{json.dumps(msg, indent=2)}</code></pre>\n"
247
+ html_output += "</div>\n"
248
+ html_output += "</div>\n"
249
+ else:
250
+ html_output += "<div style='overflow-x: auto;'>\n"
251
+ if isinstance(prompt_text, dict) and "content" in prompt_text:
252
+ html_output += f"<pre><code>{prompt_text['content']}</code></pre>\n"
253
+ else:
254
+ html_output += f"<pre><code>{prompt_text}</code></pre>\n"
255
+ html_output += "</div>\n"
256
+
257
+ html_output += "</div>\n"
258
+ html_output += "</details>\n\n"
259
+
260
+ # Style prediction output - now in a collapsible section
261
+ html_output += "<details open style='margin-bottom: 15px;'>\n"
262
+ html_output += "<summary><h3 style='display: inline; margin: 0;'>Prediction</h3>"
263
+ # Add word count in a muted style
264
+ word_count = len(output["Prediction"].split())
265
+ html_output += f"<span style='color: inherit; opacity: 0.7; font-size: 0.8em; margin-left: 10px;'>({word_count} words)</span>"
266
+ html_output += "</summary>\n"
267
+ html_output += "<div class='content-section'>\n"
268
+ html_output += "<div style='overflow-x: auto;'>\n"
269
+ html_output += f"<pre><code>{output['Prediction']}</code></pre>\n"
270
+ html_output += "</div>\n"
271
+ html_output += "</div>\n"
272
+ html_output += "</details>\n"
273
+ html_output += "</div>\n\n"
274
+
275
+ html_output += "</div>"
276
+ return html_output
277
+
278
+
279
+ def run_pipeline(samples_ix: int = 0) -> tuple[Any, Any, Any, Any]:
280
+ """Run evaluation pipeline and return results for display"""
281
+ results = aggregate_results()
282
+ easy_samples, hard_samples, all_samples = extract_dataviz()
283
+
284
+ return (
285
+ gr.Dataframe(Dataset.from_list(results).to_pandas(), visible=True),
286
+ gr.HTML(
287
+ samples_to_box_display(easy_samples, samples_ix),
288
+ label="Easiest samples (always found)",
289
+ visible=True,
290
+ ),
291
+ gr.HTML(
292
+ samples_to_box_display(hard_samples, samples_ix),
293
+ label="Hardest samples (always failed)",
294
+ visible=True,
295
+ ),
296
+ gr.HTML(
297
+ samples_to_box_display(all_samples, samples_ix),
298
+ label="All samples",
299
+ visible=True,
300
+ ),
301
+ )
302
+
303
+
304
+ def update_examples(samples_ix: int = 0) -> tuple[str, str, str]:
305
+ """Return HTML strings for easy, hard, and all samples"""
306
+ easy_samples, hard_samples, all_samples = extract_dataviz()
307
+
308
+ return (
309
+ samples_to_box_display(easy_samples, samples_ix),
310
+ samples_to_box_display(hard_samples, samples_ix),
311
+ samples_to_box_display(all_samples, samples_ix),
312
+ )