alozowski HF Staff commited on
Commit
0203fca
·
1 Parent(s): 2934174

Refactor leaderboard_space/utils.py and integrate dark mode support

Browse files
yourbench_space/leaderboard_space/utils.py CHANGED
@@ -1,94 +1,114 @@
1
  import json
2
- from typing import Tuple
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
  def aggregate_results() -> list:
11
- """From the path of outputs and model list, extracts the current scores and stores them in a list of dicts with model, score, time as keys"""
12
  all_results = []
13
- for org_model in MODELS:
14
  try:
15
- path = f"{ORG_NAME}/details_{org_model.replace('/', '__')}_private"
16
- ds = load_dataset(path, "results", split="latest")
17
- config = json.loads(ds["config_general"][0])
18
- results = json.loads(ds["results"][0])
19
-
20
- # Model data
21
- org, model = org_model.split("/")
22
-
23
- cur_result = {"Org": org, "Model": model, "Duration (s)": config["end_time"] - config["start_time"]}
24
-
25
- # Extract the task from the JSON data
26
- for k_metric, v_dict in results.items():
27
- if k_metric != "all":
28
- for k, v in v_dict.items():
29
- cur_result[f"{k}({k_metric})"] = v
30
- all_results.append(cur_result)
 
 
 
 
 
 
 
 
 
 
 
 
31
  except Exception as e:
32
- print(f"Error processing {org_model} {ORG_NAME}: {e}")
 
 
 
 
33
  return all_results
34
 
35
 
36
- def extract_dataviz() -> Tuple[list, list]:
37
- """From the path of outputs and model list, extracts from the details the worst samples, best samples"""
38
- all_samples = {}
39
- for org_model in MODELS:
 
40
  try:
41
- path = f"{ORG_NAME}/details_{org_model.replace('/', '__')}_private"
42
- ds = load_dataset(path, f"custom_{TASK.replace('/', '_')}_0", split="latest")
 
43
 
44
- for ix, row in enumerate(ds):
45
  prompt = row["full_prompt"]
46
  gold = row.get("gold", "")
47
- if isinstance(gold, list):
48
- gold = gold[0] if gold else ""
49
  score = list(row["metrics"].values())[0]
50
  predictions = row.get("predictions", [])
51
  prediction = predictions[0] if predictions else ""
52
 
53
- # We store flattened samples in a dict
54
- # ix -> ix, prompt, gold, model_score for each model, model_prediction for each model
55
- # then 2 lists: model_scores and models, to aggreg more easily
56
- if ix not in all_samples:
57
- all_samples[ix] = {
58
- "ix": ix,
59
  "prompt": prompt,
60
- "gold": gold[0] if isinstance(gold, list) else gold,
61
- # A bit redundant, but put in their own boxes for simplicity of access later
62
  "model_scores": [],
63
  "models": [],
64
  }
65
- if org_model not in all_samples[ix]["models"]:
66
- all_samples[ix][f"{org_model}_score"] = row["metrics"]
67
- all_samples[ix][f"{org_model}_prediction"] = prediction
68
- all_samples[ix]["model_scores"].append(score)
69
- all_samples[ix]["models"].append(org_model)
 
70
 
71
  except Exception as e:
72
- print(f"Error processing {org_model}: {e}")
73
 
74
- full_samples = sorted(all_samples.values(), key=lambda r: r["ix"])
75
 
76
- hard_samples = sorted(
77
- [sample for sample in all_samples.values() if sum(sample["model_scores"]) == 0], key=lambda r: r["ix"]
78
- )
79
- easy_samples = sorted(
80
- [sample for sample in all_samples.values() if sum(sample["model_scores"]) == len(sample["model_scores"])],
81
- key=lambda r: r["ix"],
82
- )
83
- return easy_samples, hard_samples, full_samples
84
 
 
85
 
86
- def samples_to_box_display(samples: list, example_index: int = 0):
87
- """Adapted from Nathan's code in https://huggingface.co/spaces/SaylorTwift/OpenEvalsModelDetails/"""
88
- if len(samples) == 0:
 
 
 
 
89
  return "No samples in this category!"
90
- outputs = []
91
  sample = samples[example_index]
 
 
92
  for model in sample["models"]:
93
  try:
94
  outputs.append({
@@ -104,20 +124,86 @@ def samples_to_box_display(samples: list, example_index: int = 0):
104
  if not outputs:
105
  return "No results found for the selected combination."
106
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
107
  # Create HTML output with all models
108
- html_output = "<div style='max-width: 800px; margin: 0 auto;'>\n\n"
109
 
110
  # Show gold answer at the top with distinct styling
111
  if outputs:
112
- html_output += "<div style='background: #e6f3e6; padding: 20px; border-radius: 10px; margin-bottom: 20px;'>\n"
113
  html_output += "<h3 style='margin-top: 0;'>Ground Truth</h3>\n"
114
  html_output += "<div style='overflow-x: auto; max-width: 100%;'>\n"
115
- html_output += f"<pre style='white-space: pre-wrap; word-wrap: break-word; margin: 0;'><code>{outputs[0]['Gold']}</code></pre>\n"
116
  html_output += "</div>\n"
117
  html_output += "</div>\n"
118
 
119
  for output in outputs:
120
- html_output += "<div style='background: #f5f5f5; padding: 20px; margin-bottom: 20px; border-radius: 10px;'>\n"
121
  html_output += f"<h2 style='margin-top: 0;'>{output['Model']}</h2>\n"
122
 
123
  # Format metrics as a clean table
@@ -131,7 +217,7 @@ def samples_to_box_display(samples: list, example_index: int = 0):
131
  for key, value in metrics.items():
132
  if isinstance(value, float):
133
  value = f"{value:.3f}"
134
- html_output += f"<tr><td style='padding: 5px; border-bottom: 1px solid #ddd;'><strong>{key}</strong></td><td style='padding: 5px; border-bottom: 1px solid #ddd;'>{value}</td></tr>\n"
135
  html_output += "</table>\n"
136
  html_output += "</div>\n"
137
  html_output += "</details>\n\n"
@@ -139,7 +225,7 @@ def samples_to_box_display(samples: list, example_index: int = 0):
139
  # Handle prompt formatting with better styling
140
  html_output += "<details style='margin-bottom: 15px;'>\n"
141
  html_output += "<summary><h3 style='display: inline; margin: 0;'>Prompt</h3></summary>\n"
142
- html_output += "<div style='background: #ffffff; padding: 15px; border-radius: 5px; margin-top: 10px;'>\n"
143
 
144
  prompt_text = output["Prompt"]
145
  if isinstance(prompt_text, list):
@@ -149,21 +235,21 @@ def samples_to_box_display(samples: list, example_index: int = 0):
149
  html_output += "<div style='margin-bottom: 10px;'>\n"
150
  html_output += f"<strong>{role}:</strong>\n"
151
  html_output += "<div style='overflow-x: auto;'>\n"
152
- html_output += f"<pre style='white-space: pre-wrap; word-wrap: break-word; margin: 5px 0;'><code>{msg['content']}</code></pre>\n"
153
  html_output += "</div>\n"
154
  html_output += "</div>\n"
155
  else:
156
  html_output += "<div style='margin-bottom: 10px;'>\n"
157
  html_output += "<div style='overflow-x: auto;'>\n"
158
- html_output += f"<pre style='white-space: pre-wrap; word-wrap: break-word; margin: 5px 0;'><code>{json.dumps(msg, indent=2)}</code></pre>\n"
159
  html_output += "</div>\n"
160
  html_output += "</div>\n"
161
  else:
162
  html_output += "<div style='overflow-x: auto;'>\n"
163
  if isinstance(prompt_text, dict) and "content" in prompt_text:
164
- html_output += f"<pre style='white-space: pre-wrap; word-wrap: break-word; margin: 5px 0;'><code>{prompt_text['content']}</code></pre>\n"
165
  else:
166
- html_output += f"<pre style='white-space: pre-wrap; word-wrap: break-word; margin: 5px 0;'><code>{prompt_text}</code></pre>\n"
167
  html_output += "</div>\n"
168
 
169
  html_output += "</div>\n"
@@ -174,11 +260,11 @@ def samples_to_box_display(samples: list, example_index: int = 0):
174
  html_output += "<summary><h3 style='display: inline; margin: 0;'>Prediction</h3>"
175
  # Add word count in a muted style
176
  word_count = len(output["Prediction"].split())
177
- html_output += f"<span style='color: #666; font-size: 0.8em; margin-left: 10px;'>({word_count} words)</span>"
178
  html_output += "</summary>\n"
179
- html_output += "<div style='background: #ffffff; padding: 15px; border-radius: 5px; margin-top: 10px;'>\n"
180
  html_output += "<div style='overflow-x: auto;'>\n"
181
- html_output += f"<pre style='white-space: pre-wrap; word-wrap: break-word; margin: 0;'><code>{output['Prediction']}</code></pre>\n"
182
  html_output += "</div>\n"
183
  html_output += "</div>\n"
184
  html_output += "</details>\n"
@@ -188,25 +274,37 @@ def samples_to_box_display(samples: list, example_index: int = 0):
188
  return html_output
189
 
190
 
191
- def run_pipeline(samples_ix: int = 0):
 
192
  results = aggregate_results()
193
- best_samples, worst_samples, all_samples = extract_dataviz()
 
194
  return (
195
  gr.Dataframe(Dataset.from_list(results).to_pandas(), visible=True),
196
  gr.HTML(
197
- samples_to_box_display(best_samples, samples_ix), label="Easiest samples (always found)", visible=True
 
 
 
 
 
 
 
198
  ),
199
  gr.HTML(
200
- samples_to_box_display(worst_samples, samples_ix), label="Hardest samples (always failed)", visible=True
 
 
201
  ),
202
- gr.HTML(samples_to_box_display(all_samples, samples_ix), label="All samples", visible=True),
203
  )
204
 
205
 
206
- def update_examples(samples_ix: int = 0):
207
- best_samples, worst_samples, all_samples = extract_dataviz()
 
 
208
  return (
209
- samples_to_box_display(best_samples, samples_ix),
210
- samples_to_box_display(worst_samples, samples_ix),
211
  samples_to_box_display(all_samples, samples_ix),
212
- )
 
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
+ KNOWN_METRIC_LABELS = {
10
+ "accuracy": "Accuracy",
11
+ "accuracy_stderr": "Accuracy (stderr)",
12
+ }
13
 
14
  def aggregate_results() -> list:
15
+ """Extract scores for each model and return list of result dictionaries."""
16
  all_results = []
17
+ for model_path in MODELS:
18
  try:
19
+ path = f"{ORG_NAME}/details_{model_path.replace('/', '__')}_private"
20
+ dataset = load_dataset(path, "results", split="latest")
21
+ config = json.loads(dataset["config_general"][0])
22
+ results = json.loads(dataset["results"][0])
23
+
24
+ _, model = model_path.split("/")
25
+ duration = round(config["end_time"] - config["start_time"], 2)
26
+
27
+ result = {
28
+ "Model": model,
29
+ "Duration (s)": duration,
30
+ }
31
+
32
+ for metric, metric_values in results.items():
33
+ if metric == "all":
34
+ continue
35
+
36
+ for raw_metric_name, metric_value in metric_values.items():
37
+ base_name = raw_metric_name.split("(")[0].strip()
38
+ pretty_label = KNOWN_METRIC_LABELS.get(base_name, raw_metric_name)
39
+
40
+ if isinstance(metric_value, float):
41
+ metric_value = round(metric_value, 3)
42
+
43
+ result[pretty_label] = metric_value
44
+
45
+ all_results.append(result)
46
+
47
  except Exception as e:
48
+ print(f"Error processing {model_path} {ORG_NAME}: {e}")
49
+
50
+ # Sort final result by Accuracy
51
+ all_results.sort(key=lambda r: r.get("Accuracy", 0), reverse=True)
52
+
53
  return all_results
54
 
55
 
56
+ def extract_dataviz() -> tuple[list[dict[str, Any]], list[dict[str, Any]], list[dict[str, Any]]]:
57
+ """Extract best, worst, and all samples for visualization"""
58
+ sample_index_map = {}
59
+
60
+ for model_path in MODELS:
61
  try:
62
+ dataset_path = f"{ORG_NAME}/details_{model_path.replace('/', '__')}_private"
63
+ split_name = f"custom_{TASK.replace('/', '_')}_0"
64
+ dataset = load_dataset(dataset_path, split_name, split="latest")
65
 
66
+ for idx, row in enumerate(dataset):
67
  prompt = row["full_prompt"]
68
  gold = row.get("gold", "")
69
+ gold = gold[0] if isinstance(gold, list) and gold else gold
 
70
  score = list(row["metrics"].values())[0]
71
  predictions = row.get("predictions", [])
72
  prediction = predictions[0] if predictions else ""
73
 
74
+ if idx not in sample_index_map:
75
+ sample_index_map[idx] = {
76
+ "ix": idx,
 
 
 
77
  "prompt": prompt,
78
+ "gold": gold,
 
79
  "model_scores": [],
80
  "models": [],
81
  }
82
+
83
+ if model_path not in sample_index_map[idx]["models"]:
84
+ sample_index_map[idx][f"{model_path}_score"] = row["metrics"]
85
+ sample_index_map[idx][f"{model_path}_prediction"] = prediction
86
+ sample_index_map[idx]["model_scores"].append(score)
87
+ sample_index_map[idx]["models"].append(model_path)
88
 
89
  except Exception as e:
90
+ print(f"Error processing {model_path}: {e}")
91
 
92
+ all_samples = sorted(sample_index_map.values(), key=lambda r: r["ix"])
93
 
94
+ hard_samples = [sample for sample in all_samples if sum(sample["model_scores"]) == 0]
95
+
96
+ easy_samples = [sample for sample in all_samples if sum(sample["model_scores"]) == len(sample["model_scores"])]
 
 
 
 
 
97
 
98
+ return easy_samples, hard_samples, all_samples
99
 
100
+
101
+ def samples_to_box_display(samples: list[dict[str, Any]], example_index: int = 0) -> str:
102
+ """
103
+ Adapted from Nathan's code https://huggingface.co/spaces/SaylorTwift/OpenEvalsModelDetails/
104
+ Support both light and dark themes
105
+ """
106
+ if not samples:
107
  return "No samples in this category!"
108
+
109
  sample = samples[example_index]
110
+ outputs = []
111
+
112
  for model in sample["models"]:
113
  try:
114
  outputs.append({
 
124
  if not outputs:
125
  return "No results found for the selected combination."
126
 
127
+ # CSS for theme compatibility
128
+ css = """
129
+ <style>
130
+ :root {
131
+ --primary-bg: #f5f5f5;
132
+ --secondary-bg: #ffffff;
133
+ --gold-bg: #e6f3e6;
134
+ --text-color: #333333;
135
+ --border-color: #ddd;
136
+ }
137
+
138
+ @media (prefers-color-scheme: dark) {
139
+ :root {
140
+ --primary-bg: #2a2a2a;
141
+ --secondary-bg: #333333;
142
+ --gold-bg: #2a3a2a;
143
+ --text-color: #e0e0e0;
144
+ --border-color: #555;
145
+ }
146
+ }
147
+
148
+ .box-container {
149
+ max-width: 800px;
150
+ margin: 0 auto;
151
+ color: var(--text-color);
152
+ }
153
+
154
+ .gold-box {
155
+ background: var(--gold-bg);
156
+ padding: 20px;
157
+ border-radius: 10px;
158
+ margin-bottom: 20px;
159
+ }
160
+
161
+ .model-box {
162
+ background: var(--primary-bg);
163
+ padding: 20px;
164
+ margin-bottom: 20px;
165
+ border-radius: 10px;
166
+ }
167
+
168
+ .content-section {
169
+ background: var(--secondary-bg);
170
+ padding: 15px;
171
+ border-radius: 5px;
172
+ margin-top: 10px;
173
+ }
174
+
175
+ .metric-row {
176
+ padding: 5px;
177
+ border-bottom: 1px solid var(--border-color);
178
+ }
179
+
180
+ h2, h3 {
181
+ color: var(--text-color);
182
+ }
183
+
184
+ pre, code {
185
+ white-space: pre-wrap;
186
+ word-wrap: break-word;
187
+ margin: 0;
188
+ color: var(--text-color);
189
+ }
190
+ </style>
191
+ """
192
+
193
  # Create HTML output with all models
194
+ html_output = f"{css}<div class='box-container'>\n\n"
195
 
196
  # Show gold answer at the top with distinct styling
197
  if outputs:
198
+ html_output += "<div class='gold-box'>\n"
199
  html_output += "<h3 style='margin-top: 0;'>Ground Truth</h3>\n"
200
  html_output += "<div style='overflow-x: auto; max-width: 100%;'>\n"
201
+ html_output += f"<pre><code>{outputs[0]['Gold']}</code></pre>\n"
202
  html_output += "</div>\n"
203
  html_output += "</div>\n"
204
 
205
  for output in outputs:
206
+ html_output += "<div class='model-box'>\n"
207
  html_output += f"<h2 style='margin-top: 0;'>{output['Model']}</h2>\n"
208
 
209
  # Format metrics as a clean table
 
217
  for key, value in metrics.items():
218
  if isinstance(value, float):
219
  value = f"{value:.3f}"
220
+ html_output += f"<tr class='metric-row'><td><strong>{key}</strong></td><td>{value}</td></tr>\n"
221
  html_output += "</table>\n"
222
  html_output += "</div>\n"
223
  html_output += "</details>\n\n"
 
225
  # Handle prompt formatting with better styling
226
  html_output += "<details style='margin-bottom: 15px;'>\n"
227
  html_output += "<summary><h3 style='display: inline; margin: 0;'>Prompt</h3></summary>\n"
228
+ html_output += "<div class='content-section'>\n"
229
 
230
  prompt_text = output["Prompt"]
231
  if isinstance(prompt_text, list):
 
235
  html_output += "<div style='margin-bottom: 10px;'>\n"
236
  html_output += f"<strong>{role}:</strong>\n"
237
  html_output += "<div style='overflow-x: auto;'>\n"
238
+ html_output += f"<pre><code>{msg['content']}</code></pre>\n"
239
  html_output += "</div>\n"
240
  html_output += "</div>\n"
241
  else:
242
  html_output += "<div style='margin-bottom: 10px;'>\n"
243
  html_output += "<div style='overflow-x: auto;'>\n"
244
+ html_output += f"<pre><code>{json.dumps(msg, indent=2)}</code></pre>\n"
245
  html_output += "</div>\n"
246
  html_output += "</div>\n"
247
  else:
248
  html_output += "<div style='overflow-x: auto;'>\n"
249
  if isinstance(prompt_text, dict) and "content" in prompt_text:
250
+ html_output += f"<pre><code>{prompt_text['content']}</code></pre>\n"
251
  else:
252
+ html_output += f"<pre><code>{prompt_text}</code></pre>\n"
253
  html_output += "</div>\n"
254
 
255
  html_output += "</div>\n"
 
260
  html_output += "<summary><h3 style='display: inline; margin: 0;'>Prediction</h3>"
261
  # Add word count in a muted style
262
  word_count = len(output["Prediction"].split())
263
+ html_output += f"<span style='color: inherit; opacity: 0.7; font-size: 0.8em; margin-left: 10px;'>({word_count} words)</span>"
264
  html_output += "</summary>\n"
265
+ html_output += "<div class='content-section'>\n"
266
  html_output += "<div style='overflow-x: auto;'>\n"
267
+ html_output += f"<pre><code>{output['Prediction']}</code></pre>\n"
268
  html_output += "</div>\n"
269
  html_output += "</div>\n"
270
  html_output += "</details>\n"
 
274
  return html_output
275
 
276
 
277
+ def run_pipeline(samples_ix: int = 0) -> tuple[Any, Any, Any, Any]:
278
+ """Run evaluation pipeline and return results for display"""
279
  results = aggregate_results()
280
+ easy_samples, hard_samples, all_samples = extract_dataviz()
281
+
282
  return (
283
  gr.Dataframe(Dataset.from_list(results).to_pandas(), visible=True),
284
  gr.HTML(
285
+ samples_to_box_display(easy_samples, samples_ix),
286
+ label="Easiest samples (always found)",
287
+ visible=True,
288
+ ),
289
+ gr.HTML(
290
+ samples_to_box_display(hard_samples, samples_ix),
291
+ label="Hardest samples (always failed)",
292
+ visible=True,
293
  ),
294
  gr.HTML(
295
+ samples_to_box_display(all_samples, samples_ix),
296
+ label="All samples",
297
+ visible=True,
298
  ),
 
299
  )
300
 
301
 
302
+ def update_examples(samples_ix: int = 0) -> tuple[str, str, str]:
303
+ """Return HTML strings for easy, hard, and all samples"""
304
+ easy_samples, hard_samples, all_samples = extract_dataviz()
305
+
306
  return (
307
+ samples_to_box_display(easy_samples, samples_ix),
308
+ samples_to_box_display(hard_samples, samples_ix),
309
  samples_to_box_display(all_samples, samples_ix),
310
+ )