Spaces:
Running
Running
Commit
·
88c98d4
1
Parent(s):
6a914d5
sorry this git history is v messy
Browse files- .gitignore +2 -0
- README.md +7 -5
- app.py +190 -194
- src/about.py +0 -72
- src/constants.py +43 -30
- src/css.py +3 -3
- src/display/css_html_js.py +0 -105
- src/display/formatting.py +0 -27
- src/display/utils.py +0 -110
- src/envs.py +0 -25
- src/leaderboard/read_evals.py +0 -196
- src/md.py +17 -5
- src/plt.py +18 -16
- src/populate.py +0 -58
- src/submission/check_validity.py +0 -99
- src/submission/submit.py +0 -119
- src/utils.py +20 -18
.gitignore
CHANGED
@@ -11,3 +11,5 @@ eval-results/
|
|
11 |
eval-queue-bk/
|
12 |
eval-results-bk/
|
13 |
logs/
|
|
|
|
|
|
11 |
eval-queue-bk/
|
12 |
eval-results-bk/
|
13 |
logs/
|
14 |
+
.gradio/
|
15 |
+
.evals/
|
README.md
CHANGED
@@ -1,13 +1,15 @@
|
|
1 |
---
|
2 |
-
title: Reward Bench
|
3 |
-
emoji:
|
4 |
-
colorFrom:
|
5 |
-
colorTo:
|
6 |
sdk: gradio
|
|
|
7 |
app_file: app.py
|
8 |
pinned: true
|
9 |
license: apache-2.0
|
10 |
-
|
|
|
11 |
---
|
12 |
|
13 |
# Start the configuration
|
|
|
1 |
---
|
2 |
+
title: Reward Bench Leaderboard
|
3 |
+
emoji: 📐
|
4 |
+
colorFrom: pink
|
5 |
+
colorTo: blue
|
6 |
sdk: gradio
|
7 |
+
sdk_version: 5.30.0
|
8 |
app_file: app.py
|
9 |
pinned: true
|
10 |
license: apache-2.0
|
11 |
+
tags:
|
12 |
+
- leaderboard
|
13 |
---
|
14 |
|
15 |
# Start the configuration
|
app.py
CHANGED
@@ -1,14 +1,15 @@
|
|
1 |
-
import gradio as gr
|
2 |
import os
|
3 |
-
from
|
4 |
-
|
|
|
|
|
5 |
from datasets import load_dataset
|
6 |
-
from
|
7 |
-
|
8 |
-
from src.
|
9 |
-
from src.constants import subset_mapping, length_categories, example_counts
|
10 |
from src.css import custom_css
|
11 |
-
|
|
|
12 |
|
13 |
api = HfApi()
|
14 |
|
@@ -18,40 +19,44 @@ evals_repo = "allenai/reward-bench-v2-results"
|
|
18 |
eval_set_repo = "allenai/reward-bench-v2-v0"
|
19 |
repo_dir_rewardbench = "./evals/rewardbench/"
|
20 |
|
|
|
21 |
def restart_space():
|
22 |
api.restart_space(repo_id="allenai/reward-bench-v2", token=COLLAB_TOKEN)
|
23 |
|
|
|
24 |
print("Pulling evaluation results")
|
25 |
repo = snapshot_download(
|
26 |
local_dir=repo_dir_rewardbench,
|
27 |
ignore_patterns=["pref-sets-scores/*", "eval-set-scores/*"],
|
28 |
repo_id=evals_repo,
|
29 |
use_auth_token=COLLAB_TOKEN,
|
30 |
-
tqdm_class=None,
|
31 |
etag_timeout=30,
|
32 |
repo_type="dataset",
|
33 |
)
|
34 |
|
|
|
35 |
def avg_over_rewardbench_v2(dataframe_core):
|
36 |
-
domain_cols = [
|
37 |
-
domain_weights=[0,1,1,1,1,1]
|
38 |
new_df = dataframe_core.copy()
|
39 |
|
40 |
# for main subsets, keys in subset_mapping, take the weighted avg by example_counts and store for the models
|
41 |
# Get the domain data and handle missing values
|
42 |
domain_data = new_df[domain_cols].values
|
43 |
masked_data = np.ma.masked_array(domain_data, np.isnan(domain_data))
|
44 |
-
|
45 |
# Calculate weighted average
|
46 |
average = np.ma.average(masked_data, axis=1, weights=domain_weights)
|
47 |
new_df["average"] = average.filled(np.nan)
|
48 |
-
|
49 |
# Rearrange columns for consistent output
|
50 |
keep_columns = ["model", "model_type", "average"] + domain_cols
|
51 |
new_df = new_df[keep_columns]
|
52 |
-
|
53 |
return new_df
|
54 |
|
|
|
55 |
def avg_over_rewardbench(dataframe_core, dataframe_prefs):
|
56 |
"""
|
57 |
Averages over the subsets alpacaeval, mt-bench, llmbar, refusals, hep and returns dataframe with only these columns.
|
@@ -69,13 +74,19 @@ def avg_over_rewardbench(dataframe_core, dataframe_prefs):
|
|
69 |
# for main subsets, keys in subset_mapping, take the weighted avg by example_counts and store for the models
|
70 |
for subset, sub_subsets in subset_mapping.items():
|
71 |
subset_cols = [col for col in new_df.columns if col in sub_subsets]
|
72 |
-
sub_data = new_df[subset_cols].values
|
73 |
-
sub_counts = [example_counts[s] for s in subset_cols]
|
74 |
-
new_df[subset] = np.average(sub_data, axis=1, weights=sub_counts)
|
75 |
# new_df[subset] = np.round(np.nanmean(new_df[subset_cols].values, axis=1), 2)
|
76 |
|
77 |
data_cols = list(subset_mapping.keys())
|
78 |
-
keep_columns =
|
|
|
|
|
|
|
|
|
|
|
|
|
79 |
# keep_columns = ["model", "average"] + subsets
|
80 |
new_df = new_df[keep_columns]
|
81 |
|
@@ -97,7 +108,7 @@ def avg_over_rewardbench(dataframe_core, dataframe_prefs):
|
|
97 |
# new_df.at[i, "Prior Sets (0.5 weight)"] = dataframe_prefs[dataframe_prefs["model"] == model]["Prior Sets (0.5 weight)"].values[0]
|
98 |
else:
|
99 |
values.append(np.nan)
|
100 |
-
|
101 |
new_df["Prior Sets (0.5 weight)"] = values
|
102 |
|
103 |
# add total average
|
@@ -114,6 +125,7 @@ def avg_over_rewardbench(dataframe_core, dataframe_prefs):
|
|
114 |
new_df = new_df[keep_columns]
|
115 |
return new_df
|
116 |
|
|
|
117 |
def expand_subsets(dataframe):
|
118 |
# TODO need to modify data/ script to do this
|
119 |
pass
|
@@ -125,7 +137,7 @@ def length_bias_check(dataframe):
|
|
125 |
Then, take the average of the three buckets as "average"
|
126 |
"""
|
127 |
new_df = dataframe.copy()
|
128 |
-
existing_subsets = new_df.columns[3:]
|
129 |
final_subsets = ["Length Bias", "Neutral", "Terse Bias"]
|
130 |
# new data is empty list dict for each final subset
|
131 |
new_data = {s: [] for s in final_subsets}
|
@@ -154,17 +166,17 @@ def length_bias_check(dataframe):
|
|
154 |
return new_df
|
155 |
|
156 |
|
157 |
-
|
158 |
-
rewardbench_data = load_all_data(repo_dir_rewardbench, subdir="eval-set").sort_values(by='average', ascending=False)
|
159 |
# rewardbench_data_length = length_bias_check(rewardbench_data).sort_values(by='Terse Bias', ascending=False)
|
160 |
# prefs_data = load_all_data(repo_dir_rewardbench, subdir="pref-sets").sort_values(by='average', ascending=False)
|
161 |
# prefs_data_sub = expand_subsets(prefs_data).sort_values(by='average', ascending=False)
|
162 |
|
163 |
-
rewardbench_data_avg = avg_over_rewardbench_v2(rewardbench_data).sort_values(by=
|
|
|
164 |
|
165 |
def prep_df(df):
|
166 |
# add column to 0th entry with count (column name itself empty)
|
167 |
-
df.insert(0,
|
168 |
|
169 |
# replace "model" with "Model" and "model_type" with "Model Type" and "average" with "Average"
|
170 |
df = df.rename(columns={"model": "Model", "model_type": "Model Type", "average": "Average"})
|
@@ -173,33 +185,36 @@ def prep_df(df):
|
|
173 |
if "Model Type" in df.columns:
|
174 |
# get model_types that have generative in them
|
175 |
mask = df["Model Type"].str.contains("generative", case=False, na=False)
|
176 |
-
|
177 |
# set these values to "Generative"
|
178 |
df.loc[mask, "Model Type"] = "Generative"
|
179 |
|
180 |
return df
|
181 |
|
|
|
182 |
# add count column to all dataframes
|
183 |
rewardbench_data = prep_df(rewardbench_data)
|
184 |
rewardbench_data_avg = prep_df(rewardbench_data_avg).rename(columns={"Average": "Score"})
|
185 |
# adjust weight of this average to 50% for Prior Sets (0.5 weight), 1 for others
|
186 |
|
187 |
# rewardbench_data_length = prep_df(rewardbench_data_length)
|
188 |
-
#prefs_data = prep_df(prefs_data)
|
189 |
|
190 |
col_types_rewardbench = ["number"] + ["markdown"] + ["str"] + ["number"] * (len(rewardbench_data.columns) - 1)
|
191 |
-
col_types_rewardbench_avg = ["number"] + ["markdown"]+ ["str"] + ["number"] * (len(rewardbench_data_avg.columns) - 1)
|
192 |
-
#cols_rewardbench_data_length = ["markdown"] + ["number"] * (len(rewardbench_data_length.columns) - 1)
|
193 |
-
#col_types_prefs = ["number"] + ["markdown"] + ["number"] * (len(prefs_data.columns) - 1)
|
194 |
## col_types_prefs_sub = ["markdown"] + ["number"] * (len(prefs_data_sub.columns) - 1)
|
195 |
|
196 |
# for showing random samples
|
197 |
eval_set = load_dataset(eval_set_repo, use_auth_token=COLLAB_TOKEN, split="test")
|
|
|
|
|
198 |
def random_sample(r: gr.Request, subset):
|
199 |
if subset is None or subset == []:
|
200 |
sample_index = np.random.randint(0, len(eval_set) - 1)
|
201 |
sample = eval_set[sample_index]
|
202 |
-
else:
|
203 |
if isinstance(subset, str):
|
204 |
subset = [subset]
|
205 |
# filter down dataset to only include the subset(s)
|
@@ -207,9 +222,10 @@ def random_sample(r: gr.Request, subset):
|
|
207 |
sample_index = np.random.randint(0, len(eval_set_filtered) - 1)
|
208 |
sample = eval_set_filtered[sample_index]
|
209 |
|
210 |
-
markdown_text =
|
211 |
return markdown_text
|
212 |
|
|
|
213 |
subsets = eval_set.unique("subset")
|
214 |
|
215 |
color_map = {
|
@@ -218,6 +234,8 @@ color_map = {
|
|
218 |
"Seq. Classifier": "#ffcd75",
|
219 |
"DPO": "#75809c",
|
220 |
}
|
|
|
|
|
221 |
def color_model_type_column(df, color_map):
|
222 |
"""
|
223 |
Apply color to the 'Model Type' column of the DataFrame based on a given color mapping.
|
@@ -229,17 +247,19 @@ def color_model_type_column(df, color_map):
|
|
229 |
Returns:
|
230 |
pd.Styler: The styled DataFrame.
|
231 |
"""
|
|
|
232 |
# Function to apply color based on the model type
|
233 |
def apply_color(val):
|
234 |
color = color_map.get(val, "default") # Default color if not specified in color_map
|
235 |
-
return f
|
236 |
-
|
237 |
# Format for different columns
|
238 |
-
format_dict = {col: "{:.1f}" for col in df.columns if col not in [
|
239 |
-
format_dict[
|
240 |
-
format_dict[
|
|
|
|
|
241 |
|
242 |
-
return df.style.applymap(apply_color, subset=['Model Type']).format(format_dict, na_rep='')
|
243 |
|
244 |
def regex_table(dataframe, regex, filter_button, style=True):
|
245 |
"""
|
@@ -248,18 +268,18 @@ def regex_table(dataframe, regex, filter_button, style=True):
|
|
248 |
# Split regex statement by comma and trim whitespace around regexes
|
249 |
regex_list = [x.strip() for x in regex.split(",")]
|
250 |
# Join the list into a single regex pattern with '|' acting as OR
|
251 |
-
combined_regex =
|
252 |
|
253 |
# remove internal ai2 data
|
254 |
dataframe = dataframe[~dataframe["Model"].str.contains("ai2", case=False, na=False)]
|
255 |
-
|
256 |
# if filter_button, remove all rows with "ai2" in the model name
|
257 |
update_scores = False
|
258 |
if isinstance(filter_button, list) or isinstance(filter_button, str):
|
259 |
-
if "Prior Sets" not in filter_button and
|
260 |
update_scores = True
|
261 |
# remove the column "Prior Sets (0.5 weight)" from the outputted table
|
262 |
-
dataframe = dataframe.drop(columns=[
|
263 |
if "Seq. Classifiers" not in filter_button:
|
264 |
dataframe = dataframe[~dataframe["Model Type"].str.contains("Seq. Classifier", case=False, na=False)]
|
265 |
if "DPO" not in filter_button:
|
@@ -277,12 +297,12 @@ def regex_table(dataframe, regex, filter_button, style=True):
|
|
277 |
# if "Prior Sets (0.5 weight)" in data.columns:
|
278 |
# data["Prior Sets (0.5 weight)"] = np.nan
|
279 |
# sort array by Score column
|
280 |
-
data = data.sort_values(by=
|
281 |
|
282 |
data.reset_index(drop=True, inplace=True)
|
283 |
|
284 |
# replace column '' with count/rank
|
285 |
-
data[
|
286 |
|
287 |
# if Score exists, round to 2 decimals
|
288 |
if "Score" in data.columns:
|
@@ -293,7 +313,7 @@ def regex_table(dataframe, regex, filter_button, style=True):
|
|
293 |
for col in data.columns:
|
294 |
if col not in ["", "Model", "Model Type", "Score", "Average"]:
|
295 |
# replace any data[col].values == '' with np.nan
|
296 |
-
data[col] = data[col].replace(
|
297 |
data[col] = np.round(np.array(data[col].values).astype(float), 1)
|
298 |
if style:
|
299 |
# apply color
|
@@ -301,156 +321,145 @@ def regex_table(dataframe, regex, filter_button, style=True):
|
|
301 |
|
302 |
return data
|
303 |
|
|
|
304 |
# import ipdb; ipdb.set_trace()
|
305 |
|
306 |
-
total_models = len(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
307 |
|
308 |
-
with gr.Blocks(css=custom_css) as app:
|
309 |
# create tabs for the app, moving the current table to one titled "rewardbench" and the benchmark_text to a tab called "About"
|
310 |
with gr.Row():
|
311 |
with gr.Column(scale=6):
|
312 |
-
gr.Markdown(TOP_TEXT
|
313 |
-
with gr.Column(scale=4):
|
314 |
-
|
315 |
-
|
316 |
-
|
317 |
-
|
318 |
-
|
319 |
-
|
320 |
-
|
321 |
-
|
322 |
-
|
323 |
-
search_1 = gr.Textbox(label="Model Search (delimit with , )",
|
324 |
-
placeholder="Model Search (delimit with , )",
|
325 |
-
show_label=False)
|
326 |
-
model_types_1 = gr.CheckboxGroup(["Seq. Classifiers", "DPO", "Custom Classifiers", "Generative", "Prior Sets"],
|
327 |
-
value=["Seq. Classifiers", "DPO", "Custom Classifiers", "Generative"],
|
328 |
-
label="Model Types",
|
329 |
-
show_label=False,
|
330 |
-
# info="Which model types to include.",
|
331 |
-
)
|
332 |
-
with gr.Row():
|
333 |
-
# reference data
|
334 |
-
rewardbench_table_hidden = gr.Dataframe(
|
335 |
-
rewardbench_data_avg.values,
|
336 |
-
datatype=col_types_rewardbench_avg,
|
337 |
-
headers=rewardbench_data_avg.columns.tolist(),
|
338 |
-
visible=False,
|
339 |
-
)
|
340 |
-
rewardbench_table = gr.Dataframe(
|
341 |
-
regex_table(rewardbench_data_avg.copy(), "", ["Seq. Classifiers", "DPO", "Custom Classifiers", "Generative"]),
|
342 |
-
datatype=col_types_rewardbench_avg,
|
343 |
-
headers=rewardbench_data_avg.columns.tolist(),
|
344 |
-
elem_id="rewardbench_dataframe_avg",
|
345 |
-
# height=1000,
|
346 |
-
)
|
347 |
-
|
348 |
-
with gr.TabItem("🔍 RewardBench - Detailed"):
|
349 |
with gr.Row():
|
350 |
-
|
351 |
-
|
352 |
-
|
353 |
-
|
354 |
-
|
355 |
-
|
356 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
357 |
with gr.Row():
|
358 |
-
|
359 |
-
rewardbench_table_detailed_hidden = gr.Dataframe(
|
360 |
-
rewardbench_data.values,
|
361 |
-
datatype=col_types_rewardbench,
|
362 |
-
headers=rewardbench_data.columns.tolist(),
|
363 |
-
visible=False,
|
364 |
-
)
|
365 |
-
rewardbench_table_detailed = gr.Dataframe(
|
366 |
-
regex_table(rewardbench_data.copy(), "", ["Seq. Classifiers", "DPO", "Generative", "Custom Classifiers"]),
|
367 |
-
datatype=col_types_rewardbench,
|
368 |
-
headers=rewardbench_data.columns.tolist(),
|
369 |
-
elem_id="rewardbench_dataframe",
|
370 |
-
# height=1000,
|
371 |
-
)
|
372 |
-
# with gr.TabItem("rewardbench Eval Set - Length Bias"):
|
373 |
-
# with gr.Row():
|
374 |
-
# # backup
|
375 |
-
# rewardbench_table_len_hidden = gr.Dataframe(
|
376 |
-
# rewardbench_data_length.values,
|
377 |
-
# datatype=cols_rewardbench_data_length,
|
378 |
-
# headers=rewardbench_data_length.columns.tolist(),
|
379 |
-
# visible=False,
|
380 |
-
# )
|
381 |
-
# rewardbench_table_len = gr.Dataframe(
|
382 |
-
# regex_table(rewardbench_data_length.copy(), "", False).values,
|
383 |
-
# datatype=cols_rewardbench_data_length,
|
384 |
-
# headers=rewardbench_data_length.columns.tolist(),
|
385 |
-
# elem_id="rewardbench_dataframe_length",
|
386 |
-
# height=1000,
|
387 |
-
# )
|
388 |
-
# with gr.TabItem("Prior Test Sets"):
|
389 |
-
# with gr.Row():
|
390 |
-
# search_3 = gr.Textbox(label="Model Search (delimit with , )", show_label=False, placeholder="Model Search (delimit with , )")
|
391 |
-
# model_types_3 = gr.CheckboxGroup(["Seq. Classifiers", "DPO", "Custom Classifiers", "Generative"],
|
392 |
-
# value=["Seq. Classifiers", "DPO", "Custom Classifiers"],
|
393 |
-
# label="Model Types",
|
394 |
-
# show_label=False,
|
395 |
-
# # info="Which model types to include.",
|
396 |
-
# )
|
397 |
-
# with gr.Row():
|
398 |
-
# PREF_SET_TEXT = """
|
399 |
-
# For more information, see the [dataset](https://huggingface.co/datasets/allenai/pref-test-sets). Only the subsets Anthropic Helpful, Anthropic HHH, Stanford SHP, and OpenAI's Summarize data are used in the leaderboard ranking.
|
400 |
-
# """
|
401 |
-
# gr.Markdown(PREF_SET_TEXT)
|
402 |
-
# with gr.Row():
|
403 |
-
# # backup
|
404 |
-
# pref_sets_table_hidden = gr.Dataframe(
|
405 |
-
# prefs_data.values,
|
406 |
-
# datatype=col_types_prefs,
|
407 |
-
# headers=prefs_data.columns.tolist(),
|
408 |
-
# visible=False,
|
409 |
-
# )
|
410 |
-
# pref_sets_table = gr.Dataframe(
|
411 |
-
# regex_table(prefs_data.copy(), "", ["Seq. Classifiers", "DPO", "Custom Classifiers"]),
|
412 |
-
# datatype=col_types_prefs,
|
413 |
-
# headers=prefs_data.columns.tolist(),
|
414 |
-
# elem_id="prefs_dataframe",
|
415 |
-
# # height=1000,
|
416 |
-
# )
|
417 |
-
|
418 |
-
|
419 |
-
with gr.TabItem("About"):
|
420 |
-
with gr.Row():
|
421 |
-
gr.Markdown(ABOUT_TEXT)
|
422 |
-
|
423 |
-
with gr.TabItem("Dataset Viewer"):
|
424 |
-
with gr.Row():
|
425 |
-
# loads one sample
|
426 |
-
gr.Markdown("""## Random Dataset Sample Viewer
|
427 |
-
Warning, refusals, XSTest, and donotanswer datasets have sensitive content.""")
|
428 |
-
subset_selector = gr.Dropdown(subsets, label="Subset", value=None, multiselect=True)
|
429 |
-
button = gr.Button("Show Random Sample")
|
430 |
-
|
431 |
-
with gr.Row():
|
432 |
-
sample_display = gr.Markdown("{sampled data loads here}")
|
433 |
-
|
434 |
-
button.click(fn=random_sample, inputs=[subset_selector], outputs=[sample_display])
|
435 |
-
# removed plot because not pretty enough
|
436 |
-
# with gr.TabItem("Model Correlation"):
|
437 |
-
# with gr.Row():
|
438 |
-
# plot = plot_avg_correlation(rewardbench_data_avg, prefs_data)
|
439 |
-
# gr.Plot(plot)
|
440 |
|
441 |
search_1.change(regex_table, inputs=[rewardbench_table_hidden, search_1, model_types_1], outputs=rewardbench_table)
|
442 |
-
search_2.change(regex_table, inputs=[rewardbench_table_detailed_hidden, search_2, model_types_2], outputs=rewardbench_table_detailed)
|
443 |
-
|
444 |
-
|
445 |
-
|
446 |
-
|
447 |
-
model_types_2.change(regex_table, inputs=[rewardbench_table_detailed_hidden, search_2, model_types_2], outputs=rewardbench_table_detailed)
|
448 |
-
# model_types_3.change(regex_table, inputs=[pref_sets_table_hidden, search_3, model_types_3], outputs=pref_sets_table)
|
449 |
|
450 |
with gr.Row():
|
451 |
with gr.Accordion("📚 Citation", open=False):
|
452 |
citation_button = gr.Textbox(
|
453 |
-
value=r"""@misc{
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
454 |
title={RewardBench: Evaluating Reward Models for Language Modeling},
|
455 |
author={Lambert, Nathan and Pyatkin, Valentina and Morrison, Jacob and Miranda, LJ and Lin, Bill Yuchen and Chandu, Khyathi and Dziri, Nouha and Kumar, Sachin and Zick, Tom and Choi, Yejin and Smith, Noah A. and Hajishirzi, Hannaneh},
|
456 |
year={2024},
|
@@ -461,18 +470,5 @@ Warning, refusals, XSTest, and donotanswer datasets have sensitive content.""")
|
|
461 |
elem_id="citation-button",
|
462 |
show_copy_button=True,
|
463 |
)
|
464 |
-
# Load data when app starts, TODO make this used somewhere...
|
465 |
-
# def load_data_on_start():
|
466 |
-
# data_rewardbench = load_all_data(repo_dir_rewardbench)
|
467 |
-
# rewardbench_table.update(data_rewardbench)
|
468 |
-
|
469 |
-
# data_rewardbench_avg = avg_over_rewardbench(repo_dir_rewardbench)
|
470 |
-
# rewardbench_table.update(data_rewardbench_avg)
|
471 |
-
|
472 |
-
# data_prefs = load_all_data(repo_dir_prefs)
|
473 |
-
# pref_sets_table.update(data_prefs)
|
474 |
|
475 |
-
|
476 |
-
scheduler.add_job(restart_space, "interval", seconds=10800) # restarted every 3h
|
477 |
-
scheduler.start()
|
478 |
-
app.launch(allowed_paths=['src/']) # had .queue() before launch before... not sure if that's necessary
|
|
|
|
|
1 |
import os
|
2 |
+
from pathlib import Path
|
3 |
+
|
4 |
+
import gradio as gr
|
5 |
+
import numpy as np
|
6 |
from datasets import load_dataset
|
7 |
+
from huggingface_hub import HfApi, snapshot_download
|
8 |
+
|
9 |
+
from src.constants import example_counts, length_categories, subset_mapping
|
|
|
10 |
from src.css import custom_css
|
11 |
+
from src.md import *
|
12 |
+
from src.utils import load_all_data
|
13 |
|
14 |
api = HfApi()
|
15 |
|
|
|
19 |
eval_set_repo = "allenai/reward-bench-v2-v0"
|
20 |
repo_dir_rewardbench = "./evals/rewardbench/"
|
21 |
|
22 |
+
|
23 |
def restart_space():
|
24 |
api.restart_space(repo_id="allenai/reward-bench-v2", token=COLLAB_TOKEN)
|
25 |
|
26 |
+
|
27 |
print("Pulling evaluation results")
|
28 |
repo = snapshot_download(
|
29 |
local_dir=repo_dir_rewardbench,
|
30 |
ignore_patterns=["pref-sets-scores/*", "eval-set-scores/*"],
|
31 |
repo_id=evals_repo,
|
32 |
use_auth_token=COLLAB_TOKEN,
|
33 |
+
tqdm_class=None,
|
34 |
etag_timeout=30,
|
35 |
repo_type="dataset",
|
36 |
)
|
37 |
|
38 |
+
|
39 |
def avg_over_rewardbench_v2(dataframe_core):
|
40 |
+
domain_cols = ["chat", "factuality", "safety", "math", "precise if", "ties"]
|
41 |
+
domain_weights = [0, 1, 1, 1, 1, 1]
|
42 |
new_df = dataframe_core.copy()
|
43 |
|
44 |
# for main subsets, keys in subset_mapping, take the weighted avg by example_counts and store for the models
|
45 |
# Get the domain data and handle missing values
|
46 |
domain_data = new_df[domain_cols].values
|
47 |
masked_data = np.ma.masked_array(domain_data, np.isnan(domain_data))
|
48 |
+
|
49 |
# Calculate weighted average
|
50 |
average = np.ma.average(masked_data, axis=1, weights=domain_weights)
|
51 |
new_df["average"] = average.filled(np.nan)
|
52 |
+
|
53 |
# Rearrange columns for consistent output
|
54 |
keep_columns = ["model", "model_type", "average"] + domain_cols
|
55 |
new_df = new_df[keep_columns]
|
56 |
+
|
57 |
return new_df
|
58 |
|
59 |
+
|
60 |
def avg_over_rewardbench(dataframe_core, dataframe_prefs):
|
61 |
"""
|
62 |
Averages over the subsets alpacaeval, mt-bench, llmbar, refusals, hep and returns dataframe with only these columns.
|
|
|
74 |
# for main subsets, keys in subset_mapping, take the weighted avg by example_counts and store for the models
|
75 |
for subset, sub_subsets in subset_mapping.items():
|
76 |
subset_cols = [col for col in new_df.columns if col in sub_subsets]
|
77 |
+
sub_data = new_df[subset_cols].values # take the relevant column values
|
78 |
+
sub_counts = [example_counts[s] for s in subset_cols] # take the example counts
|
79 |
+
new_df[subset] = np.average(sub_data, axis=1, weights=sub_counts) # take the weighted average
|
80 |
# new_df[subset] = np.round(np.nanmean(new_df[subset_cols].values, axis=1), 2)
|
81 |
|
82 |
data_cols = list(subset_mapping.keys())
|
83 |
+
keep_columns = (
|
84 |
+
[
|
85 |
+
"model",
|
86 |
+
]
|
87 |
+
+ ["model_type"]
|
88 |
+
+ data_cols
|
89 |
+
)
|
90 |
# keep_columns = ["model", "average"] + subsets
|
91 |
new_df = new_df[keep_columns]
|
92 |
|
|
|
108 |
# new_df.at[i, "Prior Sets (0.5 weight)"] = dataframe_prefs[dataframe_prefs["model"] == model]["Prior Sets (0.5 weight)"].values[0]
|
109 |
else:
|
110 |
values.append(np.nan)
|
111 |
+
|
112 |
new_df["Prior Sets (0.5 weight)"] = values
|
113 |
|
114 |
# add total average
|
|
|
125 |
new_df = new_df[keep_columns]
|
126 |
return new_df
|
127 |
|
128 |
+
|
129 |
def expand_subsets(dataframe):
|
130 |
# TODO need to modify data/ script to do this
|
131 |
pass
|
|
|
137 |
Then, take the average of the three buckets as "average"
|
138 |
"""
|
139 |
new_df = dataframe.copy()
|
140 |
+
existing_subsets = new_df.columns[3:] # model, model_type, average
|
141 |
final_subsets = ["Length Bias", "Neutral", "Terse Bias"]
|
142 |
# new data is empty list dict for each final subset
|
143 |
new_data = {s: [] for s in final_subsets}
|
|
|
166 |
return new_df
|
167 |
|
168 |
|
169 |
+
rewardbench_data = load_all_data(repo_dir_rewardbench, subdir="eval-set").sort_values(by="average", ascending=False)
|
|
|
170 |
# rewardbench_data_length = length_bias_check(rewardbench_data).sort_values(by='Terse Bias', ascending=False)
|
171 |
# prefs_data = load_all_data(repo_dir_rewardbench, subdir="pref-sets").sort_values(by='average', ascending=False)
|
172 |
# prefs_data_sub = expand_subsets(prefs_data).sort_values(by='average', ascending=False)
|
173 |
|
174 |
+
rewardbench_data_avg = avg_over_rewardbench_v2(rewardbench_data).sort_values(by="average", ascending=False)
|
175 |
+
|
176 |
|
177 |
def prep_df(df):
|
178 |
# add column to 0th entry with count (column name itself empty)
|
179 |
+
df.insert(0, "", range(1, 1 + len(df)))
|
180 |
|
181 |
# replace "model" with "Model" and "model_type" with "Model Type" and "average" with "Average"
|
182 |
df = df.rename(columns={"model": "Model", "model_type": "Model Type", "average": "Average"})
|
|
|
185 |
if "Model Type" in df.columns:
|
186 |
# get model_types that have generative in them
|
187 |
mask = df["Model Type"].str.contains("generative", case=False, na=False)
|
188 |
+
|
189 |
# set these values to "Generative"
|
190 |
df.loc[mask, "Model Type"] = "Generative"
|
191 |
|
192 |
return df
|
193 |
|
194 |
+
|
195 |
# add count column to all dataframes
|
196 |
rewardbench_data = prep_df(rewardbench_data)
|
197 |
rewardbench_data_avg = prep_df(rewardbench_data_avg).rename(columns={"Average": "Score"})
|
198 |
# adjust weight of this average to 50% for Prior Sets (0.5 weight), 1 for others
|
199 |
|
200 |
# rewardbench_data_length = prep_df(rewardbench_data_length)
|
201 |
+
# prefs_data = prep_df(prefs_data)
|
202 |
|
203 |
col_types_rewardbench = ["number"] + ["markdown"] + ["str"] + ["number"] * (len(rewardbench_data.columns) - 1)
|
204 |
+
col_types_rewardbench_avg = ["number"] + ["markdown"] + ["str"] + ["number"] * (len(rewardbench_data_avg.columns) - 1)
|
205 |
+
# cols_rewardbench_data_length = ["markdown"] + ["number"] * (len(rewardbench_data_length.columns) - 1)
|
206 |
+
# col_types_prefs = ["number"] + ["markdown"] + ["number"] * (len(prefs_data.columns) - 1)
|
207 |
## col_types_prefs_sub = ["markdown"] + ["number"] * (len(prefs_data_sub.columns) - 1)
|
208 |
|
209 |
# for showing random samples
|
210 |
eval_set = load_dataset(eval_set_repo, use_auth_token=COLLAB_TOKEN, split="test")
|
211 |
+
|
212 |
+
|
213 |
def random_sample(r: gr.Request, subset):
|
214 |
if subset is None or subset == []:
|
215 |
sample_index = np.random.randint(0, len(eval_set) - 1)
|
216 |
sample = eval_set[sample_index]
|
217 |
+
else: # filter by subsets (can be list)
|
218 |
if isinstance(subset, str):
|
219 |
subset = [subset]
|
220 |
# filter down dataset to only include the subset(s)
|
|
|
222 |
sample_index = np.random.randint(0, len(eval_set_filtered) - 1)
|
223 |
sample = eval_set_filtered[sample_index]
|
224 |
|
225 |
+
markdown_text = "\n\n".join([f"**{key}**:\n\n{value}" for key, value in sample.items()])
|
226 |
return markdown_text
|
227 |
|
228 |
+
|
229 |
subsets = eval_set.unique("subset")
|
230 |
|
231 |
color_map = {
|
|
|
234 |
"Seq. Classifier": "#ffcd75",
|
235 |
"DPO": "#75809c",
|
236 |
}
|
237 |
+
|
238 |
+
|
239 |
def color_model_type_column(df, color_map):
|
240 |
"""
|
241 |
Apply color to the 'Model Type' column of the DataFrame based on a given color mapping.
|
|
|
247 |
Returns:
|
248 |
pd.Styler: The styled DataFrame.
|
249 |
"""
|
250 |
+
|
251 |
# Function to apply color based on the model type
|
252 |
def apply_color(val):
|
253 |
color = color_map.get(val, "default") # Default color if not specified in color_map
|
254 |
+
return f"background-color: {color}"
|
255 |
+
|
256 |
# Format for different columns
|
257 |
+
format_dict = {col: "{:.1f}" for col in df.columns if col not in ["Average", "Model", "Model Type"]}
|
258 |
+
format_dict["Average"] = "{:.2f}"
|
259 |
+
format_dict[""] = "{:d}"
|
260 |
+
|
261 |
+
return df.style.applymap(apply_color, subset=["Model Type"]).format(format_dict, na_rep="")
|
262 |
|
|
|
263 |
|
264 |
def regex_table(dataframe, regex, filter_button, style=True):
|
265 |
"""
|
|
|
268 |
# Split regex statement by comma and trim whitespace around regexes
|
269 |
regex_list = [x.strip() for x in regex.split(",")]
|
270 |
# Join the list into a single regex pattern with '|' acting as OR
|
271 |
+
combined_regex = "|".join(regex_list)
|
272 |
|
273 |
# remove internal ai2 data
|
274 |
dataframe = dataframe[~dataframe["Model"].str.contains("ai2", case=False, na=False)]
|
275 |
+
|
276 |
# if filter_button, remove all rows with "ai2" in the model name
|
277 |
update_scores = False
|
278 |
if isinstance(filter_button, list) or isinstance(filter_button, str):
|
279 |
+
if "Prior Sets" not in filter_button and "Prior Sets (0.5 weight)" in dataframe.columns:
|
280 |
update_scores = True
|
281 |
# remove the column "Prior Sets (0.5 weight)" from the outputted table
|
282 |
+
dataframe = dataframe.drop(columns=["Prior Sets (0.5 weight)"])
|
283 |
if "Seq. Classifiers" not in filter_button:
|
284 |
dataframe = dataframe[~dataframe["Model Type"].str.contains("Seq. Classifier", case=False, na=False)]
|
285 |
if "DPO" not in filter_button:
|
|
|
297 |
# if "Prior Sets (0.5 weight)" in data.columns:
|
298 |
# data["Prior Sets (0.5 weight)"] = np.nan
|
299 |
# sort array by Score column
|
300 |
+
data = data.sort_values(by="Score", ascending=False)
|
301 |
|
302 |
data.reset_index(drop=True, inplace=True)
|
303 |
|
304 |
# replace column '' with count/rank
|
305 |
+
data[""] = np.arange(1, 1 + len(data))
|
306 |
|
307 |
# if Score exists, round to 2 decimals
|
308 |
if "Score" in data.columns:
|
|
|
313 |
for col in data.columns:
|
314 |
if col not in ["", "Model", "Model Type", "Score", "Average"]:
|
315 |
# replace any data[col].values == '' with np.nan
|
316 |
+
data[col] = data[col].replace("", np.nan)
|
317 |
data[col] = np.round(np.array(data[col].values).astype(float), 1)
|
318 |
if style:
|
319 |
# apply color
|
|
|
321 |
|
322 |
return data
|
323 |
|
324 |
+
|
325 |
# import ipdb; ipdb.set_trace()
|
326 |
|
327 |
+
total_models = len(
|
328 |
+
regex_table(
|
329 |
+
rewardbench_data_avg.copy(), "", ["Seq. Classifiers", "DPO", "Custom Classifiers", "Generative"], style=False
|
330 |
+
).values
|
331 |
+
)
|
332 |
+
assets = Path("src").resolve() # absolute dir with the image
|
333 |
+
|
334 |
+
# Using a string for a predefined color
|
335 |
+
theme = gr.themes.Default(primary_hue="blue")
|
336 |
|
337 |
+
with gr.Blocks(theme=theme, css=custom_css) as app:
|
338 |
# create tabs for the app, moving the current table to one titled "rewardbench" and the benchmark_text to a tab called "About"
|
339 |
with gr.Row():
|
340 |
with gr.Column(scale=6):
|
341 |
+
gr.Markdown(TOP_TEXT)
|
342 |
+
# with gr.Column(scale=4):
|
343 |
+
# # search = gr.Textbox(label="Model Search (delimit with , )", placeholder="Regex search for a model")
|
344 |
+
# # filter_button = gr.Checkbox(label="Include AI2 training runs (or type ai2 above).", interactive=True)
|
345 |
+
# # img = gr.Image(value="https://private-user-images.githubusercontent.com/10695622/310698241-24ed272a-0844-451f-b414-fde57478703e.png", width=500)
|
346 |
+
# gr.Markdown("""
|
347 |
+
# 
|
348 |
+
# """)
|
349 |
+
|
350 |
+
with gr.Tabs(elem_id="outer-tabs", elem_classes="tabs-big") as tabs_big:
|
351 |
+
with gr.TabItem("🏆 RewardBench 2", scale=1.5):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
352 |
with gr.Row():
|
353 |
+
with gr.Column(scale=7):
|
354 |
+
gr.Markdown(CAPTION_V2.format(str(total_models)))
|
355 |
+
with gr.Column(scale=3):
|
356 |
+
# search = gr.Textbox(label="Model Search (delimit with , )", placeholder="Regex search for a model")
|
357 |
+
# filter_button = gr.Checkbox(label="Include AI2 training runs (or type ai2 above).", interactive=True)
|
358 |
+
# img = gr.Image(value="https://private-user-images.githubusercontent.com/10695622/310698241-24ed272a-0844-451f-b414-fde57478703e.png", width=500)
|
359 |
+
gr.Markdown(
|
360 |
+
"""
|
361 |
+

|
362 |
+
"""
|
363 |
+
)
|
364 |
+
with gr.Tabs(elem_id="inner-tabs", elem_classes="tabs-small") as tabs:
|
365 |
+
with gr.TabItem("Leaderboard"):
|
366 |
+
with gr.Row():
|
367 |
+
search_1 = gr.Textbox(
|
368 |
+
label="Model Search (delimit with , )",
|
369 |
+
placeholder="Model Search (delimit with , )",
|
370 |
+
show_label=False,
|
371 |
+
)
|
372 |
+
model_types_1 = gr.CheckboxGroup(
|
373 |
+
["Seq. Classifiers", "DPO", "Custom Classifiers", "Generative"],
|
374 |
+
value=["Seq. Classifiers", "Custom Classifiers", "Generative"],
|
375 |
+
label="Model Types",
|
376 |
+
show_label=False,
|
377 |
+
# info="Which model types to include.",
|
378 |
+
)
|
379 |
+
with gr.Row():
|
380 |
+
# reference data
|
381 |
+
rewardbench_table_hidden = gr.Dataframe(
|
382 |
+
rewardbench_data_avg.values,
|
383 |
+
datatype=col_types_rewardbench_avg,
|
384 |
+
headers=rewardbench_data_avg.columns.tolist(),
|
385 |
+
visible=False,
|
386 |
+
)
|
387 |
+
rewardbench_table = gr.Dataframe(
|
388 |
+
regex_table(
|
389 |
+
rewardbench_data_avg.copy(),
|
390 |
+
"",
|
391 |
+
["Seq. Classifiers", "Custom Classifiers", "Generative"],
|
392 |
+
),
|
393 |
+
datatype=col_types_rewardbench_avg,
|
394 |
+
headers=rewardbench_data_avg.columns.tolist(),
|
395 |
+
elem_id="rewardbench_dataframe_avg",
|
396 |
+
max_height=800, # 800 px ≈ ~25 rows on default row-height
|
397 |
+
)
|
398 |
+
|
399 |
+
# removed because the data does not have sub-domains
|
400 |
+
# with gr.TabItem("Detailed"):
|
401 |
+
# with gr.Row():
|
402 |
+
# search_2 = gr.Textbox(label="Model Search (delimit with , )", show_label=False, placeholder="Model Search (delimit with , )")
|
403 |
+
# model_types_2 = gr.CheckboxGroup(["Seq. Classifiers", "DPO", "Custom Classifiers", "Generative"],
|
404 |
+
# value=["Seq. Classifiers", "DPO", "Generative", "Custom Classifiers"],
|
405 |
+
# label="Model Types",
|
406 |
+
# show_label=False,
|
407 |
+
# # info="Which model types to include."
|
408 |
+
# )
|
409 |
+
# with gr.Row():
|
410 |
+
# # ref data
|
411 |
+
# rewardbench_table_detailed_hidden = gr.Dataframe(
|
412 |
+
# rewardbench_data.values,
|
413 |
+
# datatype=col_types_rewardbench,
|
414 |
+
# headers=rewardbench_data.columns.tolist(),
|
415 |
+
# visible=False,
|
416 |
+
# )
|
417 |
+
# rewardbench_table_detailed = gr.Dataframe(
|
418 |
+
# regex_table(rewardbench_data.copy(), "", ["Seq. Classifiers", "DPO", "Generative", "Custom Classifiers"]),
|
419 |
+
# datatype=col_types_rewardbench,
|
420 |
+
# headers=rewardbench_data.columns.tolist(),
|
421 |
+
# elem_id="rewardbench_dataframe",
|
422 |
+
# # height=1000,
|
423 |
+
# )
|
424 |
+
|
425 |
+
with gr.TabItem("About"):
|
426 |
+
with gr.Row():
|
427 |
+
gr.Markdown(ABOUT_TEXT_V2)
|
428 |
+
|
429 |
+
with gr.TabItem("Dataset Viewer"):
|
430 |
+
with gr.Row():
|
431 |
+
# loads one sample
|
432 |
+
gr.Markdown("""## Random Dataset Sample Viewer""")
|
433 |
+
subset_selector = gr.Dropdown(subsets, label="Subset", value=None, multiselect=True)
|
434 |
+
button = gr.Button("Show Random Sample")
|
435 |
+
|
436 |
+
with gr.Row():
|
437 |
+
sample_display = gr.Markdown("{sampled data loads here}")
|
438 |
+
|
439 |
+
button.click(fn=random_sample, inputs=[subset_selector], outputs=[sample_display])
|
440 |
+
with gr.TabItem("RewardBench", scale=1.5):
|
441 |
with gr.Row():
|
442 |
+
gr.Markdown(CAPTION_V1.format(str(total_models)))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
443 |
|
444 |
search_1.change(regex_table, inputs=[rewardbench_table_hidden, search_1, model_types_1], outputs=rewardbench_table)
|
445 |
+
# search_2.change(regex_table, inputs=[rewardbench_table_detailed_hidden, search_2, model_types_2], outputs=rewardbench_table_detailed)
|
446 |
+
|
447 |
+
model_types_1.change(
|
448 |
+
regex_table, inputs=[rewardbench_table_hidden, search_1, model_types_1], outputs=rewardbench_table
|
449 |
+
)
|
450 |
+
# model_types_2.change(regex_table, inputs=[rewardbench_table_detailed_hidden, search_2, model_types_2], outputs=rewardbench_table_detailed)
|
|
|
451 |
|
452 |
with gr.Row():
|
453 |
with gr.Accordion("📚 Citation", open=False):
|
454 |
citation_button = gr.Textbox(
|
455 |
+
value=r"""@misc{RewardBench2,
|
456 |
+
title={RewardBench 2: Advancing Reward Model Evaluation},
|
457 |
+
author={Malik, Saumya and Pyatkin, Valentina and Land, Sander and Morrison, Jacob and Smith, Noah A. and Hajishirzi, Hannaneh and Lambert, Nathan},
|
458 |
+
year={2024},
|
459 |
+
howpublished={\url{https://huggingface.co/spaces/allenai/reward-bench-2}},
|
460 |
+
}
|
461 |
+
|
462 |
+
@misc{RewardBench,
|
463 |
title={RewardBench: Evaluating Reward Models for Language Modeling},
|
464 |
author={Lambert, Nathan and Pyatkin, Valentina and Morrison, Jacob and Miranda, LJ and Lin, Bill Yuchen and Chandu, Khyathi and Dziri, Nouha and Kumar, Sachin and Zick, Tom and Choi, Yejin and Smith, Noah A. and Hajishirzi, Hannaneh},
|
465 |
year={2024},
|
|
|
470 |
elem_id="citation-button",
|
471 |
show_copy_button=True,
|
472 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
473 |
|
474 |
+
app.launch(allowed_paths=[str(assets)]) # had .queue() before launch before... not sure if that's necessary
|
|
|
|
|
|
src/about.py
DELETED
@@ -1,72 +0,0 @@
|
|
1 |
-
from dataclasses import dataclass
|
2 |
-
from enum import Enum
|
3 |
-
|
4 |
-
@dataclass
|
5 |
-
class Task:
|
6 |
-
benchmark: str
|
7 |
-
metric: str
|
8 |
-
col_name: str
|
9 |
-
|
10 |
-
|
11 |
-
# Select your tasks here
|
12 |
-
# ---------------------------------------------------
|
13 |
-
class Tasks(Enum):
|
14 |
-
# task_key in the json file, metric_key in the json file, name to display in the leaderboard
|
15 |
-
task0 = Task("anli_r1", "acc", "ANLI")
|
16 |
-
task1 = Task("logiqa", "acc_norm", "LogiQA")
|
17 |
-
|
18 |
-
NUM_FEWSHOT = 0 # Change with your few shot
|
19 |
-
# ---------------------------------------------------
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
# Your leaderboard name
|
24 |
-
TITLE = """<h1 align="center" id="space-title">Demo leaderboard</h1>"""
|
25 |
-
|
26 |
-
# What does your leaderboard evaluate?
|
27 |
-
INTRODUCTION_TEXT = """
|
28 |
-
Intro text
|
29 |
-
"""
|
30 |
-
|
31 |
-
# Which evaluations are you running? how can people reproduce what you have?
|
32 |
-
LLM_BENCHMARKS_TEXT = f"""
|
33 |
-
## How it works
|
34 |
-
|
35 |
-
## Reproducibility
|
36 |
-
To reproduce our results, here is the commands you can run:
|
37 |
-
|
38 |
-
"""
|
39 |
-
|
40 |
-
EVALUATION_QUEUE_TEXT = """
|
41 |
-
## Some good practices before submitting a model
|
42 |
-
|
43 |
-
### 1) Make sure you can load your model and tokenizer using AutoClasses:
|
44 |
-
```python
|
45 |
-
from transformers import AutoConfig, AutoModel, AutoTokenizer
|
46 |
-
config = AutoConfig.from_pretrained("your model name", revision=revision)
|
47 |
-
model = AutoModel.from_pretrained("your model name", revision=revision)
|
48 |
-
tokenizer = AutoTokenizer.from_pretrained("your model name", revision=revision)
|
49 |
-
```
|
50 |
-
If this step fails, follow the error messages to debug your model before submitting it. It's likely your model has been improperly uploaded.
|
51 |
-
|
52 |
-
Note: make sure your model is public!
|
53 |
-
Note: if your model needs `use_remote_code=True`, we do not support this option yet but we are working on adding it, stay posted!
|
54 |
-
|
55 |
-
### 2) Convert your model weights to [safetensors](https://huggingface.co/docs/safetensors/index)
|
56 |
-
It's a new format for storing weights which is safer and faster to load and use. It will also allow us to add the number of parameters of your model to the `Extended Viewer`!
|
57 |
-
|
58 |
-
### 3) Make sure your model has an open license!
|
59 |
-
This is a leaderboard for Open LLMs, and we'd love for as many people as possible to know they can use your model 🤗
|
60 |
-
|
61 |
-
### 4) Fill up your model card
|
62 |
-
When we add extra information about models to the leaderboard, it will be automatically taken from the model card
|
63 |
-
|
64 |
-
## In case of model failure
|
65 |
-
If your model is displayed in the `FAILED` category, its execution stopped.
|
66 |
-
Make sure you have followed the above steps first.
|
67 |
-
If everything is done, check you can launch the EleutherAIHarness on your model locally, using the above command without modifications (you can add `--limit` to limit the number of examples per task).
|
68 |
-
"""
|
69 |
-
|
70 |
-
CITATION_BUTTON_LABEL = "Copy the following snippet to cite these results"
|
71 |
-
CITATION_BUTTON_TEXT = r"""
|
72 |
-
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
src/constants.py
CHANGED
@@ -1,28 +1,28 @@
|
|
1 |
# reference for length bias categories
|
2 |
length_categories = {
|
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 |
example_counts = {
|
@@ -32,7 +32,7 @@ example_counts = {
|
|
32 |
"mt-bench-easy": 28,
|
33 |
"mt-bench-med": 40,
|
34 |
"mt-bench-hard": 37,
|
35 |
-
"math-prm": 984,
|
36 |
"refusals-dangerous": 100,
|
37 |
"refusals-offensive": 100,
|
38 |
"llmbar-natural": 100,
|
@@ -41,20 +41,33 @@ example_counts = {
|
|
41 |
"llmbar-adver-GPTOut": 47,
|
42 |
"llmbar-adver-manual": 46,
|
43 |
"xstest-should-refuse": 154,
|
44 |
-
"xstest-should-respond": 250,
|
45 |
"donotanswer": 136,
|
46 |
"hep-cpp": 164,
|
47 |
"hep-go": 164,
|
48 |
"hep-java": 164,
|
49 |
"hep-js": 164,
|
50 |
"hep-python": 164,
|
51 |
-
"hep-rust": 164
|
52 |
}
|
53 |
|
54 |
# note, this order should match the dataframe.
|
55 |
subset_mapping = {
|
56 |
-
"Chat": [
|
57 |
-
"Chat Hard": [
|
58 |
-
|
59 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
60 |
}
|
|
|
1 |
# reference for length bias categories
|
2 |
length_categories = {
|
3 |
+
"alpacaeval-easy": "True",
|
4 |
+
"alpacaeval-hard": "True",
|
5 |
+
"alpacaeval-length": "Neutral",
|
6 |
+
"donotanswer": "False",
|
7 |
+
"hep-cpp": "Neutral",
|
8 |
+
"hep-go": "Neutral",
|
9 |
+
"hep-java": "Neutral",
|
10 |
+
"hep-js": "Neutral",
|
11 |
+
"hep-python": "Neutral",
|
12 |
+
"hep-rust": "Neutral",
|
13 |
+
"llmbar-adver-GPTInst": "False",
|
14 |
+
"llmbar-adver-GPTOut": "Neutral",
|
15 |
+
"llmbar-adver-manual": "False",
|
16 |
+
"llmbar-adver-neighbor": "False",
|
17 |
+
"llmbar-natural": "Neutral",
|
18 |
+
"math-prm": "Neutral",
|
19 |
+
"mt-bench-easy": "False",
|
20 |
+
"mt-bench-hard": "False",
|
21 |
+
"mt-bench-med": "Neutral",
|
22 |
+
"refusals-dangerous": "False",
|
23 |
+
"refusals-offensive": "False",
|
24 |
+
"xstest-should-refuse": "False",
|
25 |
+
"xstest-should-respond": "True",
|
26 |
}
|
27 |
|
28 |
example_counts = {
|
|
|
32 |
"mt-bench-easy": 28,
|
33 |
"mt-bench-med": 40,
|
34 |
"mt-bench-hard": 37,
|
35 |
+
"math-prm": 984, # actual length 447, upweighting to be equal to code
|
36 |
"refusals-dangerous": 100,
|
37 |
"refusals-offensive": 100,
|
38 |
"llmbar-natural": 100,
|
|
|
41 |
"llmbar-adver-GPTOut": 47,
|
42 |
"llmbar-adver-manual": 46,
|
43 |
"xstest-should-refuse": 154,
|
44 |
+
"xstest-should-respond": 250, # Note, refuse and respond were accidentally swapped until 9 Sept 2024
|
45 |
"donotanswer": 136,
|
46 |
"hep-cpp": 164,
|
47 |
"hep-go": 164,
|
48 |
"hep-java": 164,
|
49 |
"hep-js": 164,
|
50 |
"hep-python": 164,
|
51 |
+
"hep-rust": 164,
|
52 |
}
|
53 |
|
54 |
# note, this order should match the dataframe.
|
55 |
subset_mapping = {
|
56 |
+
"Chat": ["alpacaeval-easy", "alpacaeval-hard", "alpacaeval-length", "mt-bench-easy", "mt-bench-med"],
|
57 |
+
"Chat Hard": [
|
58 |
+
"llmbar-adver-GPTInst",
|
59 |
+
"llmbar-adver-GPTOut",
|
60 |
+
"llmbar-adver-manual",
|
61 |
+
"llmbar-adver-neighbor",
|
62 |
+
"llmbar-natural",
|
63 |
+
"mt-bench-hard",
|
64 |
+
],
|
65 |
+
"Safety": [
|
66 |
+
"donotanswer",
|
67 |
+
"refusals-dangerous",
|
68 |
+
"refusals-offensive",
|
69 |
+
"xstest-should-refuse",
|
70 |
+
"xstest-should-respond",
|
71 |
+
],
|
72 |
+
"Reasoning": ["hep-cpp", "hep-go", "hep-java", "hep-js", "hep-python", "hep-rust", "math-prm"],
|
73 |
}
|
src/css.py
CHANGED
@@ -1,3 +1,4 @@
|
|
|
|
1 |
custom_css = """
|
2 |
|
3 |
/* Full width space */
|
@@ -11,12 +12,11 @@ custom_css = """
|
|
11 |
}
|
12 |
|
13 |
.tab-buttons button {
|
14 |
-
font-size:
|
15 |
}
|
16 |
|
17 |
h1 {
|
18 |
font-size: 32px !important;
|
19 |
margin-top: 0px !important;
|
20 |
}
|
21 |
-
|
22 |
-
"""
|
|
|
1 |
+
ACCENT = "#245ED4" # OLMo Blue. Not currently used.
|
2 |
custom_css = """
|
3 |
|
4 |
/* Full width space */
|
|
|
12 |
}
|
13 |
|
14 |
.tab-buttons button {
|
15 |
+
font-size: 30px;
|
16 |
}
|
17 |
|
18 |
h1 {
|
19 |
font-size: 32px !important;
|
20 |
margin-top: 0px !important;
|
21 |
}
|
22 |
+
"""
|
|
src/display/css_html_js.py
DELETED
@@ -1,105 +0,0 @@
|
|
1 |
-
custom_css = """
|
2 |
-
|
3 |
-
.markdown-text {
|
4 |
-
font-size: 16px !important;
|
5 |
-
}
|
6 |
-
|
7 |
-
#models-to-add-text {
|
8 |
-
font-size: 18px !important;
|
9 |
-
}
|
10 |
-
|
11 |
-
#citation-button span {
|
12 |
-
font-size: 16px !important;
|
13 |
-
}
|
14 |
-
|
15 |
-
#citation-button textarea {
|
16 |
-
font-size: 16px !important;
|
17 |
-
}
|
18 |
-
|
19 |
-
#citation-button > label > button {
|
20 |
-
margin: 6px;
|
21 |
-
transform: scale(1.3);
|
22 |
-
}
|
23 |
-
|
24 |
-
#leaderboard-table {
|
25 |
-
margin-top: 15px
|
26 |
-
}
|
27 |
-
|
28 |
-
#leaderboard-table-lite {
|
29 |
-
margin-top: 15px
|
30 |
-
}
|
31 |
-
|
32 |
-
#search-bar-table-box > div:first-child {
|
33 |
-
background: none;
|
34 |
-
border: none;
|
35 |
-
}
|
36 |
-
|
37 |
-
#search-bar {
|
38 |
-
padding: 0px;
|
39 |
-
}
|
40 |
-
|
41 |
-
/* Limit the width of the first AutoEvalColumn so that names don't expand too much */
|
42 |
-
#leaderboard-table td:nth-child(2),
|
43 |
-
#leaderboard-table th:nth-child(2) {
|
44 |
-
max-width: 600px;
|
45 |
-
overflow: auto;
|
46 |
-
white-space: nowrap;
|
47 |
-
}
|
48 |
-
|
49 |
-
.tab-buttons button {
|
50 |
-
font-size: 20px;
|
51 |
-
}
|
52 |
-
|
53 |
-
#scale-logo {
|
54 |
-
border-style: none !important;
|
55 |
-
box-shadow: none;
|
56 |
-
display: block;
|
57 |
-
margin-left: auto;
|
58 |
-
margin-right: auto;
|
59 |
-
max-width: 600px;
|
60 |
-
}
|
61 |
-
|
62 |
-
#scale-logo .download {
|
63 |
-
display: none;
|
64 |
-
}
|
65 |
-
#filter_type{
|
66 |
-
border: 0;
|
67 |
-
padding-left: 0;
|
68 |
-
padding-top: 0;
|
69 |
-
}
|
70 |
-
#filter_type label {
|
71 |
-
display: flex;
|
72 |
-
}
|
73 |
-
#filter_type label > span{
|
74 |
-
margin-top: var(--spacing-lg);
|
75 |
-
margin-right: 0.5em;
|
76 |
-
}
|
77 |
-
#filter_type label > .wrap{
|
78 |
-
width: 103px;
|
79 |
-
}
|
80 |
-
#filter_type label > .wrap .wrap-inner{
|
81 |
-
padding: 2px;
|
82 |
-
}
|
83 |
-
#filter_type label > .wrap .wrap-inner input{
|
84 |
-
width: 1px
|
85 |
-
}
|
86 |
-
#filter-columns-type{
|
87 |
-
border:0;
|
88 |
-
padding:0.5;
|
89 |
-
}
|
90 |
-
#filter-columns-size{
|
91 |
-
border:0;
|
92 |
-
padding:0.5;
|
93 |
-
}
|
94 |
-
#box-filter > .form{
|
95 |
-
border: 0
|
96 |
-
}
|
97 |
-
"""
|
98 |
-
|
99 |
-
get_window_url_params = """
|
100 |
-
function(url_params) {
|
101 |
-
const params = new URLSearchParams(window.location.search);
|
102 |
-
url_params = Object.fromEntries(params);
|
103 |
-
return url_params;
|
104 |
-
}
|
105 |
-
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
src/display/formatting.py
DELETED
@@ -1,27 +0,0 @@
|
|
1 |
-
def model_hyperlink(link, model_name):
|
2 |
-
return f'<a target="_blank" href="{link}" style="color: var(--link-text-color); text-decoration: underline;text-decoration-style: dotted;">{model_name}</a>'
|
3 |
-
|
4 |
-
|
5 |
-
def make_clickable_model(model_name):
|
6 |
-
link = f"https://huggingface.co/{model_name}"
|
7 |
-
return model_hyperlink(link, model_name)
|
8 |
-
|
9 |
-
|
10 |
-
def styled_error(error):
|
11 |
-
return f"<p style='color: red; font-size: 20px; text-align: center;'>{error}</p>"
|
12 |
-
|
13 |
-
|
14 |
-
def styled_warning(warn):
|
15 |
-
return f"<p style='color: orange; font-size: 20px; text-align: center;'>{warn}</p>"
|
16 |
-
|
17 |
-
|
18 |
-
def styled_message(message):
|
19 |
-
return f"<p style='color: green; font-size: 20px; text-align: center;'>{message}</p>"
|
20 |
-
|
21 |
-
|
22 |
-
def has_no_nan_values(df, columns):
|
23 |
-
return df[columns].notna().all(axis=1)
|
24 |
-
|
25 |
-
|
26 |
-
def has_nan_values(df, columns):
|
27 |
-
return df[columns].isna().any(axis=1)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
src/display/utils.py
DELETED
@@ -1,110 +0,0 @@
|
|
1 |
-
from dataclasses import dataclass, make_dataclass
|
2 |
-
from enum import Enum
|
3 |
-
|
4 |
-
import pandas as pd
|
5 |
-
|
6 |
-
from src.about import Tasks
|
7 |
-
|
8 |
-
def fields(raw_class):
|
9 |
-
return [v for k, v in raw_class.__dict__.items() if k[:2] != "__" and k[-2:] != "__"]
|
10 |
-
|
11 |
-
|
12 |
-
# These classes are for user facing column names,
|
13 |
-
# to avoid having to change them all around the code
|
14 |
-
# when a modif is needed
|
15 |
-
@dataclass
|
16 |
-
class ColumnContent:
|
17 |
-
name: str
|
18 |
-
type: str
|
19 |
-
displayed_by_default: bool
|
20 |
-
hidden: bool = False
|
21 |
-
never_hidden: bool = False
|
22 |
-
|
23 |
-
## Leaderboard columns
|
24 |
-
auto_eval_column_dict = []
|
25 |
-
# Init
|
26 |
-
auto_eval_column_dict.append(["model_type_symbol", ColumnContent, ColumnContent("T", "str", True, never_hidden=True)])
|
27 |
-
auto_eval_column_dict.append(["model", ColumnContent, ColumnContent("Model", "markdown", True, never_hidden=True)])
|
28 |
-
#Scores
|
29 |
-
auto_eval_column_dict.append(["average", ColumnContent, ColumnContent("Average ⬆️", "number", True)])
|
30 |
-
for task in Tasks:
|
31 |
-
auto_eval_column_dict.append([task.name, ColumnContent, ColumnContent(task.value.col_name, "number", True)])
|
32 |
-
# Model information
|
33 |
-
auto_eval_column_dict.append(["model_type", ColumnContent, ColumnContent("Type", "str", False)])
|
34 |
-
auto_eval_column_dict.append(["architecture", ColumnContent, ColumnContent("Architecture", "str", False)])
|
35 |
-
auto_eval_column_dict.append(["weight_type", ColumnContent, ColumnContent("Weight type", "str", False, True)])
|
36 |
-
auto_eval_column_dict.append(["precision", ColumnContent, ColumnContent("Precision", "str", False)])
|
37 |
-
auto_eval_column_dict.append(["license", ColumnContent, ColumnContent("Hub License", "str", False)])
|
38 |
-
auto_eval_column_dict.append(["params", ColumnContent, ColumnContent("#Params (B)", "number", False)])
|
39 |
-
auto_eval_column_dict.append(["likes", ColumnContent, ColumnContent("Hub ❤️", "number", False)])
|
40 |
-
auto_eval_column_dict.append(["still_on_hub", ColumnContent, ColumnContent("Available on the hub", "bool", False)])
|
41 |
-
auto_eval_column_dict.append(["revision", ColumnContent, ColumnContent("Model sha", "str", False, False)])
|
42 |
-
|
43 |
-
# We use make dataclass to dynamically fill the scores from Tasks
|
44 |
-
AutoEvalColumn = make_dataclass("AutoEvalColumn", auto_eval_column_dict, frozen=True)
|
45 |
-
|
46 |
-
## For the queue columns in the submission tab
|
47 |
-
@dataclass(frozen=True)
|
48 |
-
class EvalQueueColumn: # Queue column
|
49 |
-
model = ColumnContent("model", "markdown", True)
|
50 |
-
revision = ColumnContent("revision", "str", True)
|
51 |
-
private = ColumnContent("private", "bool", True)
|
52 |
-
precision = ColumnContent("precision", "str", True)
|
53 |
-
weight_type = ColumnContent("weight_type", "str", "Original")
|
54 |
-
status = ColumnContent("status", "str", True)
|
55 |
-
|
56 |
-
## All the model information that we might need
|
57 |
-
@dataclass
|
58 |
-
class ModelDetails:
|
59 |
-
name: str
|
60 |
-
display_name: str = ""
|
61 |
-
symbol: str = "" # emoji
|
62 |
-
|
63 |
-
|
64 |
-
class ModelType(Enum):
|
65 |
-
PT = ModelDetails(name="pretrained", symbol="🟢")
|
66 |
-
FT = ModelDetails(name="fine-tuned", symbol="🔶")
|
67 |
-
IFT = ModelDetails(name="instruction-tuned", symbol="⭕")
|
68 |
-
RL = ModelDetails(name="RL-tuned", symbol="🟦")
|
69 |
-
Unknown = ModelDetails(name="", symbol="?")
|
70 |
-
|
71 |
-
def to_str(self, separator=" "):
|
72 |
-
return f"{self.value.symbol}{separator}{self.value.name}"
|
73 |
-
|
74 |
-
@staticmethod
|
75 |
-
def from_str(type):
|
76 |
-
if "fine-tuned" in type or "🔶" in type:
|
77 |
-
return ModelType.FT
|
78 |
-
if "pretrained" in type or "🟢" in type:
|
79 |
-
return ModelType.PT
|
80 |
-
if "RL-tuned" in type or "🟦" in type:
|
81 |
-
return ModelType.RL
|
82 |
-
if "instruction-tuned" in type or "⭕" in type:
|
83 |
-
return ModelType.IFT
|
84 |
-
return ModelType.Unknown
|
85 |
-
|
86 |
-
class WeightType(Enum):
|
87 |
-
Adapter = ModelDetails("Adapter")
|
88 |
-
Original = ModelDetails("Original")
|
89 |
-
Delta = ModelDetails("Delta")
|
90 |
-
|
91 |
-
class Precision(Enum):
|
92 |
-
float16 = ModelDetails("float16")
|
93 |
-
bfloat16 = ModelDetails("bfloat16")
|
94 |
-
Unknown = ModelDetails("?")
|
95 |
-
|
96 |
-
def from_str(precision):
|
97 |
-
if precision in ["torch.float16", "float16"]:
|
98 |
-
return Precision.float16
|
99 |
-
if precision in ["torch.bfloat16", "bfloat16"]:
|
100 |
-
return Precision.bfloat16
|
101 |
-
return Precision.Unknown
|
102 |
-
|
103 |
-
# Column selection
|
104 |
-
COLS = [c.name for c in fields(AutoEvalColumn) if not c.hidden]
|
105 |
-
|
106 |
-
EVAL_COLS = [c.name for c in fields(EvalQueueColumn)]
|
107 |
-
EVAL_TYPES = [c.type for c in fields(EvalQueueColumn)]
|
108 |
-
|
109 |
-
BENCHMARK_COLS = [t.value.col_name for t in Tasks]
|
110 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
src/envs.py
DELETED
@@ -1,25 +0,0 @@
|
|
1 |
-
import os
|
2 |
-
|
3 |
-
from huggingface_hub import HfApi
|
4 |
-
|
5 |
-
# Info to change for your repository
|
6 |
-
# ----------------------------------
|
7 |
-
TOKEN = os.environ.get("HF_TOKEN") # A read/write token for your org
|
8 |
-
|
9 |
-
OWNER = "demo-leaderboard-backend" # Change to your org - don't forget to create a results and request dataset, with the correct format!
|
10 |
-
# ----------------------------------
|
11 |
-
|
12 |
-
REPO_ID = f"{OWNER}/leaderboard"
|
13 |
-
QUEUE_REPO = f"{OWNER}/requests"
|
14 |
-
RESULTS_REPO = f"{OWNER}/results"
|
15 |
-
|
16 |
-
# If you setup a cache later, just change HF_HOME
|
17 |
-
CACHE_PATH=os.getenv("HF_HOME", ".")
|
18 |
-
|
19 |
-
# Local caches
|
20 |
-
EVAL_REQUESTS_PATH = os.path.join(CACHE_PATH, "eval-queue")
|
21 |
-
EVAL_RESULTS_PATH = os.path.join(CACHE_PATH, "eval-results")
|
22 |
-
EVAL_REQUESTS_PATH_BACKEND = os.path.join(CACHE_PATH, "eval-queue-bk")
|
23 |
-
EVAL_RESULTS_PATH_BACKEND = os.path.join(CACHE_PATH, "eval-results-bk")
|
24 |
-
|
25 |
-
API = HfApi(token=TOKEN)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
src/leaderboard/read_evals.py
DELETED
@@ -1,196 +0,0 @@
|
|
1 |
-
import glob
|
2 |
-
import json
|
3 |
-
import math
|
4 |
-
import os
|
5 |
-
from dataclasses import dataclass
|
6 |
-
|
7 |
-
import dateutil
|
8 |
-
import numpy as np
|
9 |
-
|
10 |
-
from src.display.formatting import make_clickable_model
|
11 |
-
from src.display.utils import AutoEvalColumn, ModelType, Tasks, Precision, WeightType
|
12 |
-
from src.submission.check_validity import is_model_on_hub
|
13 |
-
|
14 |
-
|
15 |
-
@dataclass
|
16 |
-
class EvalResult:
|
17 |
-
"""Represents one full evaluation. Built from a combination of the result and request file for a given run.
|
18 |
-
"""
|
19 |
-
eval_name: str # org_model_precision (uid)
|
20 |
-
full_model: str # org/model (path on hub)
|
21 |
-
org: str
|
22 |
-
model: str
|
23 |
-
revision: str # commit hash, "" if main
|
24 |
-
results: dict
|
25 |
-
precision: Precision = Precision.Unknown
|
26 |
-
model_type: ModelType = ModelType.Unknown # Pretrained, fine tuned, ...
|
27 |
-
weight_type: WeightType = WeightType.Original # Original or Adapter
|
28 |
-
architecture: str = "Unknown"
|
29 |
-
license: str = "?"
|
30 |
-
likes: int = 0
|
31 |
-
num_params: int = 0
|
32 |
-
date: str = "" # submission date of request file
|
33 |
-
still_on_hub: bool = False
|
34 |
-
|
35 |
-
@classmethod
|
36 |
-
def init_from_json_file(self, json_filepath):
|
37 |
-
"""Inits the result from the specific model result file"""
|
38 |
-
with open(json_filepath) as fp:
|
39 |
-
data = json.load(fp)
|
40 |
-
|
41 |
-
config = data.get("config")
|
42 |
-
|
43 |
-
# Precision
|
44 |
-
precision = Precision.from_str(config.get("model_dtype"))
|
45 |
-
|
46 |
-
# Get model and org
|
47 |
-
org_and_model = config.get("model_name", config.get("model_args", None))
|
48 |
-
org_and_model = org_and_model.split("/", 1)
|
49 |
-
|
50 |
-
if len(org_and_model) == 1:
|
51 |
-
org = None
|
52 |
-
model = org_and_model[0]
|
53 |
-
result_key = f"{model}_{precision.value.name}"
|
54 |
-
else:
|
55 |
-
org = org_and_model[0]
|
56 |
-
model = org_and_model[1]
|
57 |
-
result_key = f"{org}_{model}_{precision.value.name}"
|
58 |
-
full_model = "/".join(org_and_model)
|
59 |
-
|
60 |
-
still_on_hub, _, model_config = is_model_on_hub(
|
61 |
-
full_model, config.get("model_sha", "main"), trust_remote_code=True, test_tokenizer=False
|
62 |
-
)
|
63 |
-
architecture = "?"
|
64 |
-
if model_config is not None:
|
65 |
-
architectures = getattr(model_config, "architectures", None)
|
66 |
-
if architectures:
|
67 |
-
architecture = ";".join(architectures)
|
68 |
-
|
69 |
-
# Extract results available in this file (some results are split in several files)
|
70 |
-
results = {}
|
71 |
-
for task in Tasks:
|
72 |
-
task = task.value
|
73 |
-
|
74 |
-
# We average all scores of a given metric (not all metrics are present in all files)
|
75 |
-
accs = np.array([v.get(task.metric, None) for k, v in data["results"].items() if task.benchmark == k])
|
76 |
-
if accs.size == 0 or any([acc is None for acc in accs]):
|
77 |
-
continue
|
78 |
-
|
79 |
-
mean_acc = np.mean(accs) * 100.0
|
80 |
-
results[task.benchmark] = mean_acc
|
81 |
-
|
82 |
-
return self(
|
83 |
-
eval_name=result_key,
|
84 |
-
full_model=full_model,
|
85 |
-
org=org,
|
86 |
-
model=model,
|
87 |
-
results=results,
|
88 |
-
precision=precision,
|
89 |
-
revision= config.get("model_sha", ""),
|
90 |
-
still_on_hub=still_on_hub,
|
91 |
-
architecture=architecture
|
92 |
-
)
|
93 |
-
|
94 |
-
def update_with_request_file(self, requests_path):
|
95 |
-
"""Finds the relevant request file for the current model and updates info with it"""
|
96 |
-
request_file = get_request_file_for_model(requests_path, self.full_model, self.precision.value.name)
|
97 |
-
|
98 |
-
try:
|
99 |
-
with open(request_file, "r") as f:
|
100 |
-
request = json.load(f)
|
101 |
-
self.model_type = ModelType.from_str(request.get("model_type", ""))
|
102 |
-
self.weight_type = WeightType[request.get("weight_type", "Original")]
|
103 |
-
self.license = request.get("license", "?")
|
104 |
-
self.likes = request.get("likes", 0)
|
105 |
-
self.num_params = request.get("params", 0)
|
106 |
-
self.date = request.get("submitted_time", "")
|
107 |
-
except Exception:
|
108 |
-
print(f"Could not find request file for {self.org}/{self.model} with precision {self.precision.value.name}")
|
109 |
-
|
110 |
-
def to_dict(self):
|
111 |
-
"""Converts the Eval Result to a dict compatible with our dataframe display"""
|
112 |
-
average = sum([v for v in self.results.values() if v is not None]) / len(Tasks)
|
113 |
-
data_dict = {
|
114 |
-
"eval_name": self.eval_name, # not a column, just a save name,
|
115 |
-
AutoEvalColumn.precision.name: self.precision.value.name,
|
116 |
-
AutoEvalColumn.model_type.name: self.model_type.value.name,
|
117 |
-
AutoEvalColumn.model_type_symbol.name: self.model_type.value.symbol,
|
118 |
-
AutoEvalColumn.weight_type.name: self.weight_type.value.name,
|
119 |
-
AutoEvalColumn.architecture.name: self.architecture,
|
120 |
-
AutoEvalColumn.model.name: make_clickable_model(self.full_model),
|
121 |
-
AutoEvalColumn.revision.name: self.revision,
|
122 |
-
AutoEvalColumn.average.name: average,
|
123 |
-
AutoEvalColumn.license.name: self.license,
|
124 |
-
AutoEvalColumn.likes.name: self.likes,
|
125 |
-
AutoEvalColumn.params.name: self.num_params,
|
126 |
-
AutoEvalColumn.still_on_hub.name: self.still_on_hub,
|
127 |
-
}
|
128 |
-
|
129 |
-
for task in Tasks:
|
130 |
-
data_dict[task.value.col_name] = self.results[task.value.benchmark]
|
131 |
-
|
132 |
-
return data_dict
|
133 |
-
|
134 |
-
|
135 |
-
def get_request_file_for_model(requests_path, model_name, precision):
|
136 |
-
"""Selects the correct request file for a given model. Only keeps runs tagged as FINISHED"""
|
137 |
-
request_files = os.path.join(
|
138 |
-
requests_path,
|
139 |
-
f"{model_name}_eval_request_*.json",
|
140 |
-
)
|
141 |
-
request_files = glob.glob(request_files)
|
142 |
-
|
143 |
-
# Select correct request file (precision)
|
144 |
-
request_file = ""
|
145 |
-
request_files = sorted(request_files, reverse=True)
|
146 |
-
for tmp_request_file in request_files:
|
147 |
-
with open(tmp_request_file, "r") as f:
|
148 |
-
req_content = json.load(f)
|
149 |
-
if (
|
150 |
-
req_content["status"] in ["FINISHED"]
|
151 |
-
and req_content["precision"] == precision.split(".")[-1]
|
152 |
-
):
|
153 |
-
request_file = tmp_request_file
|
154 |
-
return request_file
|
155 |
-
|
156 |
-
|
157 |
-
def get_raw_eval_results(results_path: str, requests_path: str) -> list[EvalResult]:
|
158 |
-
"""From the path of the results folder root, extract all needed info for results"""
|
159 |
-
model_result_filepaths = []
|
160 |
-
|
161 |
-
for root, _, files in os.walk(results_path):
|
162 |
-
# We should only have json files in model results
|
163 |
-
if len(files) == 0 or any([not f.endswith(".json") for f in files]):
|
164 |
-
continue
|
165 |
-
|
166 |
-
# Sort the files by date
|
167 |
-
try:
|
168 |
-
files.sort(key=lambda x: x.removesuffix(".json").removeprefix("results_")[:-7])
|
169 |
-
except dateutil.parser._parser.ParserError:
|
170 |
-
files = [files[-1]]
|
171 |
-
|
172 |
-
for file in files:
|
173 |
-
model_result_filepaths.append(os.path.join(root, file))
|
174 |
-
|
175 |
-
eval_results = {}
|
176 |
-
for model_result_filepath in model_result_filepaths:
|
177 |
-
# Creation of result
|
178 |
-
eval_result = EvalResult.init_from_json_file(model_result_filepath)
|
179 |
-
eval_result.update_with_request_file(requests_path)
|
180 |
-
|
181 |
-
# Store results of same eval together
|
182 |
-
eval_name = eval_result.eval_name
|
183 |
-
if eval_name in eval_results.keys():
|
184 |
-
eval_results[eval_name].results.update({k: v for k, v in eval_result.results.items() if v is not None})
|
185 |
-
else:
|
186 |
-
eval_results[eval_name] = eval_result
|
187 |
-
|
188 |
-
results = []
|
189 |
-
for v in eval_results.values():
|
190 |
-
try:
|
191 |
-
v.to_dict() # we test if the dict version is complete
|
192 |
-
results.append(v)
|
193 |
-
except KeyError: # not all eval values present
|
194 |
-
continue
|
195 |
-
|
196 |
-
return results
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
src/md.py
CHANGED
@@ -1,7 +1,10 @@
|
|
1 |
from datetime import datetime
|
|
|
2 |
import pytz
|
3 |
|
4 |
-
|
|
|
|
|
5 |
We compute the win percentage for a reward model on hand curated chosen-rejected pairs for each prompt.
|
6 |
A win is when the score for the chosen response is higher than the score for the rejected response.
|
7 |
|
@@ -96,11 +99,20 @@ For more details, see the [dataset](https://huggingface.co/datasets/allenai/rewa
|
|
96 |
"""
|
97 |
|
98 |
# Get Pacific time zone (handles PST/PDT automatically)
|
99 |
-
pacific_tz = pytz.timezone(
|
100 |
current_time = datetime.now(pacific_tz).strftime("%H:%M %Z, %d %b %Y")
|
101 |
|
102 |
-
TOP_TEXT =
|
103 |
### Evaluating the capabilities, safety, and pitfalls of reward models
|
104 |
-
|
|
|
|
|
105 |
|
106 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
from datetime import datetime
|
2 |
+
|
3 |
import pytz
|
4 |
|
5 |
+
ABOUT_TEXT_V2 = """TODO"""
|
6 |
+
|
7 |
+
ABOUT_TEXT_V1 = """
|
8 |
We compute the win percentage for a reward model on hand curated chosen-rejected pairs for each prompt.
|
9 |
A win is when the score for the chosen response is higher than the score for the rejected response.
|
10 |
|
|
|
99 |
"""
|
100 |
|
101 |
# Get Pacific time zone (handles PST/PDT automatically)
|
102 |
+
pacific_tz = pytz.timezone("America/Los_Angeles")
|
103 |
current_time = datetime.now(pacific_tz).strftime("%H:%M %Z, %d %b %Y")
|
104 |
|
105 |
+
TOP_TEXT = """# RewardBench: Evaluating Reward Models
|
106 |
### Evaluating the capabilities, safety, and pitfalls of reward models
|
107 |
+
"""
|
108 |
+
|
109 |
+
CAPTION_V2 = f"""The *new version* of RewardBench that is based on unseen human data and designed to be substantially more difficult!
|
110 |
|
111 |
+
[Code](https://github.com/allenai/reward-bench) | [Eval. Dataset](https://huggingface.co/datasets/allenai/reward-bench-v2-v0) | [Prior Test Sets](https://huggingface.co/datasets/allenai/pref-test-sets) | [Results](https://huggingface.co/datasets/allenai/reward-bench-v2-results) | [Paper (TODO)](TODO) | Total models: {{}} | Last restart (PST): {current_time}"""
|
112 |
+
|
113 |
+
CAPTION_V1 = """The original RewardBench -- the first reward model evaluation.
|
114 |
+
|
115 |
+
**Note**: This leaderboard is frozen and will not be updated. The final version of the evaluation results are available [here](TODO).
|
116 |
+
|
117 |
+
⚠️ Many of the top models were trained on unintentionally contaminated, AI-generated data, for more information, see this [gist](https://gist.github.com/natolambert/1aed306000c13e0e8c5bc17c1a5dd300).
|
118 |
+
"""
|
src/plt.py
CHANGED
@@ -1,53 +1,55 @@
|
|
1 |
import matplotlib.pyplot as plt
|
2 |
import pandas as pd
|
|
|
3 |
from .utils import undo_hyperlink
|
4 |
|
|
|
5 |
def plot_avg_correlation(df1, df2):
|
6 |
"""
|
7 |
Plots the "average" column for each unique model that appears in both dataframes.
|
8 |
-
|
9 |
Parameters:
|
10 |
- df1: pandas DataFrame containing columns "model" and "average".
|
11 |
- df2: pandas DataFrame containing columns "model" and "average".
|
12 |
"""
|
13 |
# Identify the unique models that appear in both DataFrames
|
14 |
-
common_models = pd.Series(list(set(df1[
|
15 |
-
|
16 |
# Set up the plot
|
17 |
plt.figure(figsize=(13, 6), constrained_layout=True)
|
18 |
|
19 |
-
# axes from 0 to 1 for x and y
|
20 |
plt.xlim(0.475, 0.8)
|
21 |
plt.ylim(0.475, 0.8)
|
22 |
|
23 |
# larger font (16)
|
24 |
-
plt.rcParams.update({
|
25 |
# plt.subplots_adjust(left=0.1, right=0.9, top=0.9, bottom=0.1)
|
26 |
# plt.tight_layout()
|
27 |
# plt.margins(0,0)
|
28 |
|
29 |
for model in common_models:
|
30 |
# Filter data for the current model
|
31 |
-
df1_model_data = df1[df1[
|
32 |
-
df2_model_data = df2[df2[
|
33 |
-
|
34 |
# Plotting
|
35 |
plt.scatter(df1_model_data, df2_model_data, label=model)
|
36 |
m_name = undo_hyperlink(model)
|
37 |
if m_name == "No text found":
|
38 |
m_name = "Random"
|
39 |
-
# Add text above each point like
|
40 |
# plt.text(x[i] + 0.1, y[i] + 0.1, label, ha='left', va='bottom')
|
41 |
-
plt.text(
|
|
|
|
|
42 |
|
43 |
# add correlation line to scatter plot
|
44 |
# first, compute correlation
|
45 |
-
corr = df1[
|
46 |
# add correlation line based on corr
|
47 |
-
|
48 |
-
|
49 |
|
50 |
-
plt.xlabel(
|
51 |
-
plt.ylabel(
|
52 |
# plt.legend(title='Model', bbox_to_anchor=(1.05, 1), loc='upper left')
|
53 |
-
return plt
|
|
|
1 |
import matplotlib.pyplot as plt
|
2 |
import pandas as pd
|
3 |
+
|
4 |
from .utils import undo_hyperlink
|
5 |
|
6 |
+
|
7 |
def plot_avg_correlation(df1, df2):
|
8 |
"""
|
9 |
Plots the "average" column for each unique model that appears in both dataframes.
|
10 |
+
|
11 |
Parameters:
|
12 |
- df1: pandas DataFrame containing columns "model" and "average".
|
13 |
- df2: pandas DataFrame containing columns "model" and "average".
|
14 |
"""
|
15 |
# Identify the unique models that appear in both DataFrames
|
16 |
+
common_models = pd.Series(list(set(df1["model"]) & set(df2["model"])))
|
17 |
+
|
18 |
# Set up the plot
|
19 |
plt.figure(figsize=(13, 6), constrained_layout=True)
|
20 |
|
21 |
+
# axes from 0 to 1 for x and y
|
22 |
plt.xlim(0.475, 0.8)
|
23 |
plt.ylim(0.475, 0.8)
|
24 |
|
25 |
# larger font (16)
|
26 |
+
plt.rcParams.update({"font.size": 12, "axes.labelsize": 14, "axes.titlesize": 14})
|
27 |
# plt.subplots_adjust(left=0.1, right=0.9, top=0.9, bottom=0.1)
|
28 |
# plt.tight_layout()
|
29 |
# plt.margins(0,0)
|
30 |
|
31 |
for model in common_models:
|
32 |
# Filter data for the current model
|
33 |
+
df1_model_data = df1[df1["model"] == model]["average"].values
|
34 |
+
df2_model_data = df2[df2["model"] == model]["average"].values
|
35 |
+
|
36 |
# Plotting
|
37 |
plt.scatter(df1_model_data, df2_model_data, label=model)
|
38 |
m_name = undo_hyperlink(model)
|
39 |
if m_name == "No text found":
|
40 |
m_name = "Random"
|
41 |
+
# Add text above each point like
|
42 |
# plt.text(x[i] + 0.1, y[i] + 0.1, label, ha='left', va='bottom')
|
43 |
+
plt.text(
|
44 |
+
df1_model_data - 0.005, df2_model_data, m_name, horizontalalignment="right", verticalalignment="center"
|
45 |
+
)
|
46 |
|
47 |
# add correlation line to scatter plot
|
48 |
# first, compute correlation
|
49 |
+
corr = df1["average"].corr(df2["average"])
|
50 |
# add correlation line based on corr
|
|
|
|
|
51 |
|
52 |
+
plt.xlabel("HERM Eval. Set Avg.", fontsize=16)
|
53 |
+
plt.ylabel("Pref. Test Sets Avg.", fontsize=16)
|
54 |
# plt.legend(title='Model', bbox_to_anchor=(1.05, 1), loc='upper left')
|
55 |
+
return plt
|
src/populate.py
DELETED
@@ -1,58 +0,0 @@
|
|
1 |
-
import json
|
2 |
-
import os
|
3 |
-
|
4 |
-
import pandas as pd
|
5 |
-
|
6 |
-
from src.display.formatting import has_no_nan_values, make_clickable_model
|
7 |
-
from src.display.utils import AutoEvalColumn, EvalQueueColumn
|
8 |
-
from src.leaderboard.read_evals import get_raw_eval_results
|
9 |
-
|
10 |
-
|
11 |
-
def get_leaderboard_df(results_path: str, requests_path: str, cols: list, benchmark_cols: list) -> pd.DataFrame:
|
12 |
-
"""Creates a dataframe from all the individual experiment results"""
|
13 |
-
raw_data = get_raw_eval_results(results_path, requests_path)
|
14 |
-
all_data_json = [v.to_dict() for v in raw_data]
|
15 |
-
|
16 |
-
df = pd.DataFrame.from_records(all_data_json)
|
17 |
-
df = df.sort_values(by=[AutoEvalColumn.average.name], ascending=False)
|
18 |
-
df = df[cols].round(decimals=2)
|
19 |
-
|
20 |
-
# filter out if any of the benchmarks have not been produced
|
21 |
-
df = df[has_no_nan_values(df, benchmark_cols)]
|
22 |
-
return df
|
23 |
-
|
24 |
-
|
25 |
-
def get_evaluation_queue_df(save_path: str, cols: list) -> list[pd.DataFrame]:
|
26 |
-
"""Creates the different dataframes for the evaluation queues requestes"""
|
27 |
-
entries = [entry for entry in os.listdir(save_path) if not entry.startswith(".")]
|
28 |
-
all_evals = []
|
29 |
-
|
30 |
-
for entry in entries:
|
31 |
-
if ".json" in entry:
|
32 |
-
file_path = os.path.join(save_path, entry)
|
33 |
-
with open(file_path) as fp:
|
34 |
-
data = json.load(fp)
|
35 |
-
|
36 |
-
data[EvalQueueColumn.model.name] = make_clickable_model(data["model"])
|
37 |
-
data[EvalQueueColumn.revision.name] = data.get("revision", "main")
|
38 |
-
|
39 |
-
all_evals.append(data)
|
40 |
-
elif ".md" not in entry:
|
41 |
-
# this is a folder
|
42 |
-
sub_entries = [e for e in os.listdir(f"{save_path}/{entry}") if os.path.isfile(e) and not e.startswith(".")]
|
43 |
-
for sub_entry in sub_entries:
|
44 |
-
file_path = os.path.join(save_path, entry, sub_entry)
|
45 |
-
with open(file_path) as fp:
|
46 |
-
data = json.load(fp)
|
47 |
-
|
48 |
-
data[EvalQueueColumn.model.name] = make_clickable_model(data["model"])
|
49 |
-
data[EvalQueueColumn.revision.name] = data.get("revision", "main")
|
50 |
-
all_evals.append(data)
|
51 |
-
|
52 |
-
pending_list = [e for e in all_evals if e["status"] in ["PENDING", "RERUN"]]
|
53 |
-
running_list = [e for e in all_evals if e["status"] == "RUNNING"]
|
54 |
-
finished_list = [e for e in all_evals if e["status"].startswith("FINISHED") or e["status"] == "PENDING_NEW_EVAL"]
|
55 |
-
df_pending = pd.DataFrame.from_records(pending_list, columns=cols)
|
56 |
-
df_running = pd.DataFrame.from_records(running_list, columns=cols)
|
57 |
-
df_finished = pd.DataFrame.from_records(finished_list, columns=cols)
|
58 |
-
return df_finished[cols], df_running[cols], df_pending[cols]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
src/submission/check_validity.py
DELETED
@@ -1,99 +0,0 @@
|
|
1 |
-
import json
|
2 |
-
import os
|
3 |
-
import re
|
4 |
-
from collections import defaultdict
|
5 |
-
from datetime import datetime, timedelta, timezone
|
6 |
-
|
7 |
-
import huggingface_hub
|
8 |
-
from huggingface_hub import ModelCard
|
9 |
-
from huggingface_hub.hf_api import ModelInfo
|
10 |
-
from transformers import AutoConfig
|
11 |
-
from transformers.models.auto.tokenization_auto import AutoTokenizer
|
12 |
-
|
13 |
-
def check_model_card(repo_id: str) -> tuple[bool, str]:
|
14 |
-
"""Checks if the model card and license exist and have been filled"""
|
15 |
-
try:
|
16 |
-
card = ModelCard.load(repo_id)
|
17 |
-
except huggingface_hub.utils.EntryNotFoundError:
|
18 |
-
return False, "Please add a model card to your model to explain how you trained/fine-tuned it."
|
19 |
-
|
20 |
-
# Enforce license metadata
|
21 |
-
if card.data.license is None:
|
22 |
-
if not ("license_name" in card.data and "license_link" in card.data):
|
23 |
-
return False, (
|
24 |
-
"License not found. Please add a license to your model card using the `license` metadata or a"
|
25 |
-
" `license_name`/`license_link` pair."
|
26 |
-
)
|
27 |
-
|
28 |
-
# Enforce card content
|
29 |
-
if len(card.text) < 200:
|
30 |
-
return False, "Please add a description to your model card, it is too short."
|
31 |
-
|
32 |
-
return True, ""
|
33 |
-
|
34 |
-
def is_model_on_hub(model_name: str, revision: str, token: str = None, trust_remote_code=False, test_tokenizer=False) -> tuple[bool, str]:
|
35 |
-
"""Checks if the model model_name is on the hub, and whether it (and its tokenizer) can be loaded with AutoClasses."""
|
36 |
-
try:
|
37 |
-
config = AutoConfig.from_pretrained(model_name, revision=revision, trust_remote_code=trust_remote_code, token=token)
|
38 |
-
if test_tokenizer:
|
39 |
-
try:
|
40 |
-
tk = AutoTokenizer.from_pretrained(model_name, revision=revision, trust_remote_code=trust_remote_code, token=token)
|
41 |
-
except ValueError as e:
|
42 |
-
return (
|
43 |
-
False,
|
44 |
-
f"uses a tokenizer which is not in a transformers release: {e}",
|
45 |
-
None
|
46 |
-
)
|
47 |
-
except Exception as e:
|
48 |
-
return (False, "'s tokenizer cannot be loaded. Is your tokenizer class in a stable transformers release, and correctly configured?", None)
|
49 |
-
return True, None, config
|
50 |
-
|
51 |
-
except ValueError:
|
52 |
-
return (
|
53 |
-
False,
|
54 |
-
"needs to be launched with `trust_remote_code=True`. For safety reason, we do not allow these models to be automatically submitted to the leaderboard.",
|
55 |
-
None
|
56 |
-
)
|
57 |
-
|
58 |
-
except Exception as e:
|
59 |
-
return False, "was not found on hub!", None
|
60 |
-
|
61 |
-
|
62 |
-
def get_model_size(model_info: ModelInfo, precision: str):
|
63 |
-
"""Gets the model size from the configuration, or the model name if the configuration does not contain the information."""
|
64 |
-
try:
|
65 |
-
model_size = round(model_info.safetensors["total"] / 1e9, 3)
|
66 |
-
except (AttributeError, TypeError):
|
67 |
-
return 0 # Unknown model sizes are indicated as 0, see NUMERIC_INTERVALS in app.py
|
68 |
-
|
69 |
-
size_factor = 8 if (precision == "GPTQ" or "gptq" in model_info.modelId.lower()) else 1
|
70 |
-
model_size = size_factor * model_size
|
71 |
-
return model_size
|
72 |
-
|
73 |
-
def get_model_arch(model_info: ModelInfo):
|
74 |
-
"""Gets the model architecture from the configuration"""
|
75 |
-
return model_info.config.get("architectures", "Unknown")
|
76 |
-
|
77 |
-
def already_submitted_models(requested_models_dir: str) -> set[str]:
|
78 |
-
"""Gather a list of already submitted models to avoid duplicates"""
|
79 |
-
depth = 1
|
80 |
-
file_names = []
|
81 |
-
users_to_submission_dates = defaultdict(list)
|
82 |
-
|
83 |
-
for root, _, files in os.walk(requested_models_dir):
|
84 |
-
current_depth = root.count(os.sep) - requested_models_dir.count(os.sep)
|
85 |
-
if current_depth == depth:
|
86 |
-
for file in files:
|
87 |
-
if not file.endswith(".json"):
|
88 |
-
continue
|
89 |
-
with open(os.path.join(root, file), "r") as f:
|
90 |
-
info = json.load(f)
|
91 |
-
file_names.append(f"{info['model']}_{info['revision']}_{info['precision']}")
|
92 |
-
|
93 |
-
# Select organisation
|
94 |
-
if info["model"].count("/") == 0 or "submitted_time" not in info:
|
95 |
-
continue
|
96 |
-
organisation, _ = info["model"].split("/")
|
97 |
-
users_to_submission_dates[organisation].append(info["submitted_time"])
|
98 |
-
|
99 |
-
return set(file_names), users_to_submission_dates
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
src/submission/submit.py
DELETED
@@ -1,119 +0,0 @@
|
|
1 |
-
import json
|
2 |
-
import os
|
3 |
-
from datetime import datetime, timezone
|
4 |
-
|
5 |
-
from src.display.formatting import styled_error, styled_message, styled_warning
|
6 |
-
from src.envs import API, EVAL_REQUESTS_PATH, TOKEN, QUEUE_REPO
|
7 |
-
from src.submission.check_validity import (
|
8 |
-
already_submitted_models,
|
9 |
-
check_model_card,
|
10 |
-
get_model_size,
|
11 |
-
is_model_on_hub,
|
12 |
-
)
|
13 |
-
|
14 |
-
REQUESTED_MODELS = None
|
15 |
-
USERS_TO_SUBMISSION_DATES = None
|
16 |
-
|
17 |
-
def add_new_eval(
|
18 |
-
model: str,
|
19 |
-
base_model: str,
|
20 |
-
revision: str,
|
21 |
-
precision: str,
|
22 |
-
weight_type: str,
|
23 |
-
model_type: str,
|
24 |
-
):
|
25 |
-
global REQUESTED_MODELS
|
26 |
-
global USERS_TO_SUBMISSION_DATES
|
27 |
-
if not REQUESTED_MODELS:
|
28 |
-
REQUESTED_MODELS, USERS_TO_SUBMISSION_DATES = already_submitted_models(EVAL_REQUESTS_PATH)
|
29 |
-
|
30 |
-
user_name = ""
|
31 |
-
model_path = model
|
32 |
-
if "/" in model:
|
33 |
-
user_name = model.split("/")[0]
|
34 |
-
model_path = model.split("/")[1]
|
35 |
-
|
36 |
-
precision = precision.split(" ")[0]
|
37 |
-
current_time = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
38 |
-
|
39 |
-
if model_type is None or model_type == "":
|
40 |
-
return styled_error("Please select a model type.")
|
41 |
-
|
42 |
-
# Does the model actually exist?
|
43 |
-
if revision == "":
|
44 |
-
revision = "main"
|
45 |
-
|
46 |
-
# Is the model on the hub?
|
47 |
-
if weight_type in ["Delta", "Adapter"]:
|
48 |
-
base_model_on_hub, error, _ = is_model_on_hub(model_name=base_model, revision=revision, token=TOKEN, test_tokenizer=True)
|
49 |
-
if not base_model_on_hub:
|
50 |
-
return styled_error(f'Base model "{base_model}" {error}')
|
51 |
-
|
52 |
-
if not weight_type == "Adapter":
|
53 |
-
model_on_hub, error, _ = is_model_on_hub(model_name=model, revision=revision, token=TOKEN, test_tokenizer=True)
|
54 |
-
if not model_on_hub:
|
55 |
-
return styled_error(f'Model "{model}" {error}')
|
56 |
-
|
57 |
-
# Is the model info correctly filled?
|
58 |
-
try:
|
59 |
-
model_info = API.model_info(repo_id=model, revision=revision)
|
60 |
-
except Exception:
|
61 |
-
return styled_error("Could not get your model information. Please fill it up properly.")
|
62 |
-
|
63 |
-
model_size = get_model_size(model_info=model_info, precision=precision)
|
64 |
-
|
65 |
-
# Were the model card and license filled?
|
66 |
-
try:
|
67 |
-
license = model_info.cardData["license"]
|
68 |
-
except Exception:
|
69 |
-
return styled_error("Please select a license for your model")
|
70 |
-
|
71 |
-
modelcard_OK, error_msg = check_model_card(model)
|
72 |
-
if not modelcard_OK:
|
73 |
-
return styled_error(error_msg)
|
74 |
-
|
75 |
-
# Seems good, creating the eval
|
76 |
-
print("Adding new eval")
|
77 |
-
|
78 |
-
eval_entry = {
|
79 |
-
"model": model,
|
80 |
-
"base_model": base_model,
|
81 |
-
"revision": revision,
|
82 |
-
"precision": precision,
|
83 |
-
"weight_type": weight_type,
|
84 |
-
"status": "PENDING",
|
85 |
-
"submitted_time": current_time,
|
86 |
-
"model_type": model_type,
|
87 |
-
"likes": model_info.likes,
|
88 |
-
"params": model_size,
|
89 |
-
"license": license,
|
90 |
-
"private": False,
|
91 |
-
}
|
92 |
-
|
93 |
-
# Check for duplicate submission
|
94 |
-
if f"{model}_{revision}_{precision}" in REQUESTED_MODELS:
|
95 |
-
return styled_warning("This model has been already submitted.")
|
96 |
-
|
97 |
-
print("Creating eval file")
|
98 |
-
OUT_DIR = f"{EVAL_REQUESTS_PATH}/{user_name}"
|
99 |
-
os.makedirs(OUT_DIR, exist_ok=True)
|
100 |
-
out_path = f"{OUT_DIR}/{model_path}_eval_request_False_{precision}_{weight_type}.json"
|
101 |
-
|
102 |
-
with open(out_path, "w") as f:
|
103 |
-
f.write(json.dumps(eval_entry))
|
104 |
-
|
105 |
-
print("Uploading eval file")
|
106 |
-
API.upload_file(
|
107 |
-
path_or_fileobj=out_path,
|
108 |
-
path_in_repo=out_path.split("eval-queue/")[1],
|
109 |
-
repo_id=QUEUE_REPO,
|
110 |
-
repo_type="dataset",
|
111 |
-
commit_message=f"Add {model} to eval queue",
|
112 |
-
)
|
113 |
-
|
114 |
-
# Remove the local file
|
115 |
-
os.remove(out_path)
|
116 |
-
|
117 |
-
return styled_message(
|
118 |
-
"Your request has been submitted to the evaluation queue!\nPlease wait for up to an hour for the model to show in the PENDING list."
|
119 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
src/utils.py
CHANGED
@@ -1,9 +1,10 @@
|
|
1 |
-
import pandas as pd
|
2 |
-
from pathlib import Path
|
3 |
-
from datasets import load_dataset
|
4 |
-
import numpy as np
|
5 |
import os
|
6 |
import re
|
|
|
|
|
|
|
|
|
|
|
7 |
|
8 |
UNVERIFIED_MODELS = [
|
9 |
"nvidia/Nemotron-4-340B-Reward",
|
@@ -35,9 +36,10 @@ CONTAMINATED_MODELS = [
|
|
35 |
"SF-Foundation/TextEval-Llama3.1-70B",
|
36 |
"ZiyiYe/Con-J-Qwen2-7B",
|
37 |
"Ray2333/Gemma-2B-rewardmodel-ft",
|
38 |
-
"Ray2333/GRM-Gemma-2B-rewardmodel-ft"
|
39 |
]
|
40 |
|
|
|
41 |
# From Open LLM Leaderboard
|
42 |
def model_hyperlink(link, model_name):
|
43 |
# if model_name is above 50 characters, return first 47 characters and "..."
|
@@ -63,9 +65,10 @@ def model_hyperlink(link, model_name):
|
|
63 |
output += " ⚠️"
|
64 |
return output
|
65 |
|
|
|
66 |
def undo_hyperlink(html_string):
|
67 |
# Regex pattern to match content inside > and <
|
68 |
-
pattern = r
|
69 |
match = re.search(pattern, html_string)
|
70 |
if match:
|
71 |
# Extract the matched text and remove leading '>' and trailing '<'
|
@@ -75,7 +78,7 @@ def undo_hyperlink(html_string):
|
|
75 |
|
76 |
|
77 |
# Define a function to fetch and process data
|
78 |
-
def load_all_data(data_repo, subdir:str, subsubsets=False):
|
79 |
dir = Path(data_repo)
|
80 |
data_dir = dir / subdir
|
81 |
orgs = [d for d in os.listdir(data_dir) if os.path.isdir(os.path.join(data_dir, d))]
|
@@ -93,21 +96,20 @@ def load_all_data(data_repo, subdir:str, subsubsets=False): # use HF api to p
|
|
93 |
|
94 |
# load all json data in the list models_results one by one to avoid not having the same entries
|
95 |
for model in models_results:
|
96 |
-
model_data = load_dataset("json", data_files=data_repo + subdir+ "/" + model, split="train")
|
97 |
df2 = pd.DataFrame(model_data)
|
98 |
# add to df
|
99 |
df = pd.concat([df2, df])
|
100 |
|
101 |
-
|
102 |
# remove chat_template comlumn
|
103 |
df = df.drop(columns=["chat_template"])
|
104 |
|
105 |
# sort columns alphabetically
|
106 |
df = df.reindex(sorted(df.columns), axis=1)
|
107 |
-
|
108 |
# move column "model" to the front
|
109 |
cols = list(df.columns)
|
110 |
-
cols.insert(0, cols.pop(cols.index(
|
111 |
df = df.loc[:, cols]
|
112 |
|
113 |
# select all columns except "model"
|
@@ -123,7 +125,7 @@ def load_all_data(data_repo, subdir:str, subsubsets=False): # use HF api to p
|
|
123 |
if "model_beaker" in cols:
|
124 |
cols.remove("model_beaker")
|
125 |
df = df.drop(columns=["model_beaker"])
|
126 |
-
|
127 |
# remove column xstest (outdated data)
|
128 |
# if xstest is a column
|
129 |
if "xstest" in cols:
|
@@ -148,24 +150,24 @@ def load_all_data(data_repo, subdir:str, subsubsets=False): # use HF api to p
|
|
148 |
df = df.drop(columns=["pku_safer"])
|
149 |
cols.remove("pku_safer")
|
150 |
|
151 |
-
# convert to score
|
152 |
-
df[cols] =
|
153 |
-
avg = np.nanmean(df[cols].values,axis=1)
|
154 |
# add average column
|
155 |
df["average"] = avg
|
156 |
-
|
157 |
# apply model_hyperlink function to column "model"
|
158 |
df["model"] = df["model"].apply(lambda x: model_hyperlink(f"https://huggingface.co/{x}", x))
|
159 |
|
160 |
# move average column to the second
|
161 |
cols = list(df.columns)
|
162 |
-
cols.insert(1, cols.pop(cols.index(
|
163 |
df = df.loc[:, cols]
|
164 |
|
165 |
# move model_type column to first
|
166 |
if "model_type" in cols:
|
167 |
cols = list(df.columns)
|
168 |
-
cols.insert(1, cols.pop(cols.index(
|
169 |
df = df.loc[:, cols]
|
170 |
|
171 |
# remove models with DPO Ref. Free as type (future work)
|
|
|
|
|
|
|
|
|
|
|
1 |
import os
|
2 |
import re
|
3 |
+
from pathlib import Path
|
4 |
+
|
5 |
+
import numpy as np
|
6 |
+
import pandas as pd
|
7 |
+
from datasets import load_dataset
|
8 |
|
9 |
UNVERIFIED_MODELS = [
|
10 |
"nvidia/Nemotron-4-340B-Reward",
|
|
|
36 |
"SF-Foundation/TextEval-Llama3.1-70B",
|
37 |
"ZiyiYe/Con-J-Qwen2-7B",
|
38 |
"Ray2333/Gemma-2B-rewardmodel-ft",
|
39 |
+
"Ray2333/GRM-Gemma-2B-rewardmodel-ft",
|
40 |
]
|
41 |
|
42 |
+
|
43 |
# From Open LLM Leaderboard
|
44 |
def model_hyperlink(link, model_name):
|
45 |
# if model_name is above 50 characters, return first 47 characters and "..."
|
|
|
65 |
output += " ⚠️"
|
66 |
return output
|
67 |
|
68 |
+
|
69 |
def undo_hyperlink(html_string):
|
70 |
# Regex pattern to match content inside > and <
|
71 |
+
pattern = r">[^<]+<"
|
72 |
match = re.search(pattern, html_string)
|
73 |
if match:
|
74 |
# Extract the matched text and remove leading '>' and trailing '<'
|
|
|
78 |
|
79 |
|
80 |
# Define a function to fetch and process data
|
81 |
+
def load_all_data(data_repo, subdir: str, subsubsets=False): # use HF api to pull the git repo
|
82 |
dir = Path(data_repo)
|
83 |
data_dir = dir / subdir
|
84 |
orgs = [d for d in os.listdir(data_dir) if os.path.isdir(os.path.join(data_dir, d))]
|
|
|
96 |
|
97 |
# load all json data in the list models_results one by one to avoid not having the same entries
|
98 |
for model in models_results:
|
99 |
+
model_data = load_dataset("json", data_files=data_repo + subdir + "/" + model, split="train")
|
100 |
df2 = pd.DataFrame(model_data)
|
101 |
# add to df
|
102 |
df = pd.concat([df2, df])
|
103 |
|
|
|
104 |
# remove chat_template comlumn
|
105 |
df = df.drop(columns=["chat_template"])
|
106 |
|
107 |
# sort columns alphabetically
|
108 |
df = df.reindex(sorted(df.columns), axis=1)
|
109 |
+
|
110 |
# move column "model" to the front
|
111 |
cols = list(df.columns)
|
112 |
+
cols.insert(0, cols.pop(cols.index("model")))
|
113 |
df = df.loc[:, cols]
|
114 |
|
115 |
# select all columns except "model"
|
|
|
125 |
if "model_beaker" in cols:
|
126 |
cols.remove("model_beaker")
|
127 |
df = df.drop(columns=["model_beaker"])
|
128 |
+
|
129 |
# remove column xstest (outdated data)
|
130 |
# if xstest is a column
|
131 |
if "xstest" in cols:
|
|
|
150 |
df = df.drop(columns=["pku_safer"])
|
151 |
cols.remove("pku_safer")
|
152 |
|
153 |
+
# convert to score
|
154 |
+
df[cols] = df[cols] * 100
|
155 |
+
avg = np.nanmean(df[cols].values, axis=1)
|
156 |
# add average column
|
157 |
df["average"] = avg
|
158 |
+
|
159 |
# apply model_hyperlink function to column "model"
|
160 |
df["model"] = df["model"].apply(lambda x: model_hyperlink(f"https://huggingface.co/{x}", x))
|
161 |
|
162 |
# move average column to the second
|
163 |
cols = list(df.columns)
|
164 |
+
cols.insert(1, cols.pop(cols.index("average")))
|
165 |
df = df.loc[:, cols]
|
166 |
|
167 |
# move model_type column to first
|
168 |
if "model_type" in cols:
|
169 |
cols = list(df.columns)
|
170 |
+
cols.insert(1, cols.pop(cols.index("model_type")))
|
171 |
df = df.loc[:, cols]
|
172 |
|
173 |
# remove models with DPO Ref. Free as type (future work)
|