Mihail Yonchev commited on
Commit
131edb5
0 Parent(s):

feat: add board

Browse files
.gitattributes ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tflite filter=lfs diff=lfs merge=lfs -text
29
+ *.tgz filter=lfs diff=lfs merge=lfs -text
30
+ *.wasm filter=lfs diff=lfs merge=lfs -text
31
+ *.xz filter=lfs diff=lfs merge=lfs -text
32
+ *.zip filter=lfs diff=lfs merge=lfs -text
33
+ *.zst filter=lfs diff=lfs merge=lfs -text
34
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
35
+ scale-hf-logo.png filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ auto_evals/
2
+ venv/
3
+ __pycache__/
4
+ .env
5
+ .ipynb_checkpoints
6
+ *ipynb
7
+ .vscode/
8
+
9
+ eval-queue/
10
+ eval-results/
11
+ eval-queue-bk/
12
+ eval-results-bk/
13
+ logs/
.pre-commit-config.yaml ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ default_language_version:
16
+ python: python3
17
+
18
+ ci:
19
+ autofix_prs: true
20
+ autoupdate_commit_msg: '[pre-commit.ci] pre-commit suggestions'
21
+ autoupdate_schedule: quarterly
22
+
23
+ repos:
24
+ - repo: https://github.com/pre-commit/pre-commit-hooks
25
+ rev: v4.3.0
26
+ hooks:
27
+ - id: check-yaml
28
+ - id: check-case-conflict
29
+ - id: detect-private-key
30
+ - id: check-added-large-files
31
+ args: ['--maxkb=1000']
32
+ - id: requirements-txt-fixer
33
+ - id: end-of-file-fixer
34
+ - id: trailing-whitespace
35
+
36
+ - repo: https://github.com/PyCQA/isort
37
+ rev: 5.12.0
38
+ hooks:
39
+ - id: isort
40
+ name: Format imports
41
+
42
+ - repo: https://github.com/psf/black
43
+ rev: 22.12.0
44
+ hooks:
45
+ - id: black
46
+ name: Format code
47
+ additional_dependencies: ['click==8.0.2']
48
+
49
+ - repo: https://github.com/charliermarsh/ruff-pre-commit
50
+ # Ruff version.
51
+ rev: 'v0.0.267'
52
+ hooks:
53
+ - id: ruff
Makefile ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .PHONY: style format
2
+
3
+
4
+ style:
5
+ python -m black --line-length 119 .
6
+ python -m isort .
7
+ ruff check --fix .
8
+
9
+
10
+ quality:
11
+ python -m black --check --line-length 119 .
12
+ python -m isort --check-only .
13
+ ruff check .
README.md ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: EU AI Act Compliance Leaderboard
3
+ emoji: 🥇
4
+ colorFrom: green
5
+ colorTo: indigo
6
+ sdk: gradio
7
+ sdk_version: 4.37.1
8
+ app_file: app.py
9
+ pinned: true
10
+ license: apache-2.0
11
+ tags:
12
+ - leaderboard
13
+ ---
14
+
15
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
16
+
17
+ Most of the variables to change for a default leaderboard are in env (replace the path for your leaderboard) and src/display/about.
18
+
19
+ Results files should have the following format:
20
+
21
+ ```
22
+ {
23
+ "config": {
24
+ "model_dtype": "torch.float16", # or torch.bfloat16 or 8bit or 4bit
25
+ "model_name": "path of the model on the hub: org/model",
26
+ "model_sha": "revision on the hub",
27
+ },
28
+ "results": {
29
+ "task_name": {
30
+ "metric_name": score,
31
+ },
32
+ "task_name2": {
33
+ "metric_name": score,
34
+ }
35
+ }
36
+ }
37
+ ```
38
+
39
+ Request files are created automatically by this tool.
app.py ADDED
@@ -0,0 +1,325 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import pandas as pd
3
+ from apscheduler.schedulers.background import BackgroundScheduler
4
+ from huggingface_hub import snapshot_download
5
+
6
+ from src.display.about import (
7
+ CITATION_BUTTON_LABEL,
8
+ CITATION_BUTTON_TEXT,
9
+ EVALUATION_QUEUE_TEXT,
10
+ INTRODUCTION_TEXT,
11
+ LLM_BENCHMARKS_TEXT,
12
+ TITLE,
13
+ )
14
+ from src.display.css_html_js import custom_css
15
+ from src.display.utils import (
16
+ BENCHMARK_COLS,
17
+ COLS,
18
+ EVAL_COLS,
19
+ EVAL_TYPES,
20
+ NUMERIC_INTERVALS,
21
+ TYPES,
22
+ AutoEvalColumn,
23
+ ModelType,
24
+ fields,
25
+ WeightType,
26
+ Precision
27
+ )
28
+ from src.envs import API, EVAL_REQUESTS_PATH, EVAL_RESULTS_PATH, TOKEN, QUEUE_REPO, REPO_ID, RESULTS_REPO
29
+ from src.populate import get_evaluation_queue_df, get_leaderboard_df
30
+ from src.submission.submit import add_new_eval
31
+ import time
32
+ import requests
33
+
34
+
35
+ def restart_space():
36
+ restart = False
37
+ while not restart:
38
+ try:
39
+ API.restart_space(repo_id=REPO_ID, token=TOKEN)
40
+ except requests.exceptions.ConnectionError as e:
41
+ print("Restart failed. Re-trying...")
42
+ time.sleep(30)
43
+ continue
44
+ restart = True
45
+
46
+
47
+ try:
48
+ print(EVAL_REQUESTS_PATH)
49
+ snapshot_download(
50
+ repo_id=QUEUE_REPO, local_dir=EVAL_REQUESTS_PATH, repo_type="dataset", tqdm_class=None, etag_timeout=30
51
+ )
52
+ except Exception:
53
+ restart_space()
54
+ try:
55
+ print(EVAL_RESULTS_PATH)
56
+ snapshot_download(
57
+ repo_id=RESULTS_REPO, local_dir=EVAL_RESULTS_PATH, repo_type="dataset", tqdm_class=None, etag_timeout=30
58
+ )
59
+ except Exception:
60
+ restart_space()
61
+
62
+ raw_data, original_df = get_leaderboard_df(EVAL_RESULTS_PATH, EVAL_REQUESTS_PATH, COLS, BENCHMARK_COLS)
63
+ leaderboard_df = original_df.copy()
64
+
65
+ (
66
+ finished_eval_queue_df,
67
+ pending_eval_queue_df,
68
+ ) = get_evaluation_queue_df(EVAL_REQUESTS_PATH, EVAL_COLS)
69
+
70
+
71
+ # Searching and filtering
72
+ def update_table(
73
+ hidden_df: pd.DataFrame,
74
+ columns: list,
75
+ type_query: list,
76
+ # precision_query: str,
77
+ # size_query: list,
78
+ query: str,
79
+ ):
80
+ filtered_df = filter_models(hidden_df, type_query)
81
+ filtered_df = filter_queries(query, filtered_df)
82
+ df = select_columns(filtered_df, columns)
83
+ return df
84
+
85
+
86
+ def search_table(df: pd.DataFrame, query: str) -> pd.DataFrame:
87
+ return df[(df[AutoEvalColumn.dummy.name].str.contains(query, case=False))]
88
+
89
+
90
+ def select_columns(df: pd.DataFrame, columns: list) -> pd.DataFrame:
91
+ always_here_cols = [
92
+ AutoEvalColumn.model_type_symbol.name,
93
+ AutoEvalColumn.model.name,
94
+ ]
95
+ # We use COLS to maintain sorting
96
+ filtered_df = df[
97
+ always_here_cols + [c for c in COLS if c in df.columns and c in columns] + [AutoEvalColumn.dummy.name]
98
+ ]
99
+ return filtered_df
100
+
101
+
102
+ def filter_queries(query: str, filtered_df: pd.DataFrame) -> pd.DataFrame:
103
+ final_df = []
104
+ if query != "":
105
+ queries = [q.strip() for q in query.split(";")]
106
+ for _q in queries:
107
+ _q = _q.strip()
108
+ if _q != "":
109
+ temp_filtered_df = search_table(filtered_df, _q)
110
+ if len(temp_filtered_df) > 0:
111
+ final_df.append(temp_filtered_df)
112
+ if len(final_df) > 0:
113
+ filtered_df = pd.concat(final_df)
114
+ filtered_df = filtered_df.drop_duplicates(
115
+ subset=[AutoEvalColumn.model.name, AutoEvalColumn.precision.name, AutoEvalColumn.revision.name]
116
+ )
117
+
118
+ return filtered_df
119
+
120
+
121
+ def filter_models(
122
+ df: pd.DataFrame, type_query: list
123
+ ) -> pd.DataFrame:
124
+ # Show all models
125
+ # if show_deleted:
126
+ filtered_df = df
127
+ # else: # Show only still on the hub models
128
+ # filtered_df = df[df[AutoEvalColumn.still_on_hub.name] == True]
129
+
130
+ type_emoji = [t[0] for t in type_query]
131
+ filtered_df = filtered_df.loc[df[AutoEvalColumn.model_type_symbol.name].isin(type_emoji)]
132
+ # filtered_df = filtered_df.loc[df[AutoEvalColumn.precision.name].isin(precision_query + ["None"])]
133
+
134
+ # numeric_interval = pd.IntervalIndex(sorted([NUMERIC_INTERVALS[s] for s in size_query]))
135
+ # params_column = pd.to_numeric(df[AutoEvalColumn.params.name], errors="coerce")
136
+ # mask = params_column.apply(lambda x: any(numeric_interval.contains(x)))
137
+ # filtered_df = filtered_df.loc[mask]
138
+
139
+ return filtered_df
140
+
141
+
142
+ demo = gr.Blocks(css=custom_css)
143
+ with demo:
144
+ gr.HTML(TITLE)
145
+ gr.Markdown(INTRODUCTION_TEXT, elem_classes="markdown-text")
146
+
147
+ with gr.Tabs(elem_classes="tab-buttons") as tabs:
148
+ with gr.TabItem("🏅 Results", elem_id="llm-benchmark-tab-table", id=0):
149
+ with gr.Row():
150
+ with gr.Column():
151
+ with gr.Row():
152
+ search_bar = gr.Textbox(
153
+ placeholder=" 🔍 Search for your model (separate multiple queries with `;`) and press ENTER...",
154
+ show_label=False,
155
+ elem_id="search-bar",
156
+ )
157
+ with gr.Row():
158
+ shown_columns = gr.CheckboxGroup(
159
+ choices=[
160
+ c.name
161
+ for c in fields(AutoEvalColumn)
162
+ if not c.hidden and not c.never_hidden and not c.dummy
163
+ ],
164
+ value=[
165
+ c.name
166
+ for c in fields(AutoEvalColumn)
167
+ if c.displayed_by_default and not c.hidden and not c.never_hidden
168
+ ],
169
+ label="Select columns to show",
170
+ elem_id="column-select",
171
+ interactive=True,
172
+ )
173
+ with gr.Column(min_width=250):
174
+ # with gr.Box(elem_id="box-filter"):
175
+ filter_columns_type = gr.CheckboxGroup(
176
+ label="Model types",
177
+ choices=[t.to_str() for t in ModelType],
178
+ value=[t.to_str() for t in ModelType],
179
+ interactive=True,
180
+ elem_id="filter-columns-type",
181
+ )
182
+ # filter_columns_precision = gr.CheckboxGroup(
183
+ # label="Precision",
184
+ # choices=[i.value.name for i in Precision],
185
+ # value=[i.value.name for i in Precision],
186
+ # interactive=True,
187
+ # elem_id="filter-columns-precision",
188
+ # )
189
+ # filter_columns_size = gr.CheckboxGroup(
190
+ # label="Model sizes (in billions of parameters)",
191
+ # choices=list(NUMERIC_INTERVALS.keys()),
192
+ # value=list(NUMERIC_INTERVALS.keys()),
193
+ # interactive=True,
194
+ # elem_id="filter-columns-size",
195
+ # )
196
+
197
+ leaderboard_table = gr.components.Dataframe(
198
+ value=leaderboard_df[
199
+ [c.name for c in fields(AutoEvalColumn) if c.never_hidden]
200
+ + shown_columns.value
201
+ ],
202
+ headers=[c.name for c in fields(AutoEvalColumn) if c.never_hidden] + shown_columns.value,
203
+ datatype=TYPES,
204
+ elem_id="leaderboard-table",
205
+ interactive=False,
206
+ visible=True,
207
+ column_widths=["2%", "20%", "10%", "10%", "12%"]
208
+ )
209
+
210
+ # Dummy leaderboard for handling the case when the user uses backspace key
211
+ hidden_leaderboard_table_for_search = gr.components.Dataframe(
212
+ value=original_df[COLS],
213
+ headers=COLS,
214
+ datatype=TYPES,
215
+ visible=False,
216
+ )
217
+ search_bar.submit(
218
+ update_table,
219
+ [
220
+ hidden_leaderboard_table_for_search,
221
+ shown_columns,
222
+ filter_columns_type,
223
+ # filter_columns_precision,
224
+ # filter_columns_size,
225
+ search_bar,
226
+ ],
227
+ leaderboard_table,
228
+ )
229
+ for selector in [shown_columns, filter_columns_type,
230
+ ]:
231
+ selector.change(
232
+ update_table,
233
+ [
234
+ hidden_leaderboard_table_for_search,
235
+ shown_columns,
236
+ filter_columns_type,
237
+ # filter_columns_precision,
238
+ # filter_columns_size,
239
+ # deleted_models_visibility,
240
+ search_bar,
241
+ ],
242
+ leaderboard_table,
243
+ queue=True,
244
+ )
245
+
246
+ with gr.TabItem("🚀 Request evaluation ", elem_id="llm-benchmark-tab-table", id=3):
247
+ with gr.Column():
248
+ with gr.Row():
249
+ gr.Markdown(EVALUATION_QUEUE_TEXT, elem_classes="markdown-text")
250
+
251
+ with gr.Column():
252
+ with gr.Accordion(
253
+ f"Completed Evaluations ({len(finished_eval_queue_df)}) ✅",
254
+ open=False,
255
+ ):
256
+ with gr.Row():
257
+ finished_eval_table = gr.components.Dataframe(
258
+ value=finished_eval_queue_df,
259
+ headers=EVAL_COLS,
260
+ datatype=EVAL_TYPES,
261
+ row_count=5,
262
+ )
263
+
264
+
265
+ with gr.Row():
266
+ gr.Markdown("👇 Request an evaluation here", elem_classes="markdown-text")
267
+
268
+ with gr.Row():
269
+ with gr.Column():
270
+ model_name_textbox = gr.Textbox(label="Model name")
271
+ # revision_name_textbox = gr.Textbox(label="Revision commit", placeholder="main")
272
+ # model_type = gr.Dropdown(
273
+ # choices=[t.to_str(" : ") for t in ModelType if t != ModelType.Unknown],
274
+ # label="Model type",
275
+ # multiselect=False,
276
+ # value=None,
277
+ # interactive=True,
278
+ # )
279
+
280
+ # with gr.Column():
281
+ # precision = gr.Dropdown(
282
+ # choices=[i.value.name for i in Precision if i != Precision.Unknown],
283
+ # label="Precision",
284
+ # multiselect=False,
285
+ # value="float16",
286
+ # interactive=True,
287
+ # # )
288
+ # weight_type = gr.Dropdown(
289
+ # choices=[i.value.name for i in WeightType],
290
+ # label="Weights type",
291
+ # multiselect=False,
292
+ # value="Original",
293
+ # interactive=True,
294
+ # )
295
+ # base_model_name_textbox = gr.Textbox(label="Base model (for delta or adapter weights)")
296
+
297
+ submit_button = gr.Button("Submit for evaluation")
298
+ submission_result = gr.Markdown()
299
+ submit_button.click(
300
+ add_new_eval,
301
+ [
302
+ model_name_textbox,
303
+ # base_model_name_textbox,
304
+ # revision_name_textbox,
305
+ # precision,
306
+ # weight_type,
307
+ # model_type,
308
+ ],
309
+ submission_result,
310
+ )
311
+
312
+ with gr.Row():
313
+ with gr.Accordion("📙 Citation", open=False):
314
+ citation_button = gr.Textbox(
315
+ value=CITATION_BUTTON_TEXT,
316
+ label=CITATION_BUTTON_LABEL,
317
+ lines=20,
318
+ elem_id="citation-button",
319
+ show_copy_button=True,
320
+ )
321
+
322
+ scheduler = BackgroundScheduler()
323
+ scheduler.add_job(restart_space, "interval", seconds=1800)
324
+ scheduler.start()
325
+ demo.queue(default_concurrency_limit=40).launch()
pyproject.toml ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [tool.ruff]
2
+ # Enable pycodestyle (`E`) and Pyflakes (`F`) codes by default.
3
+ select = ["E", "F"]
4
+ ignore = ["E501"] # line too long (black is taking care of this)
5
+ line-length = 119
6
+ fixable = ["A", "B", "C", "D", "E", "F", "G", "I", "N", "Q", "S", "T", "W", "ANN", "ARG", "BLE", "COM", "DJ", "DTZ", "EM", "ERA", "EXE", "FBT", "ICN", "INP", "ISC", "NPY", "PD", "PGH", "PIE", "PL", "PT", "PTH", "PYI", "RET", "RSE", "RUF", "SIM", "SLF", "TCH", "TID", "TRY", "UP", "YTT"]
7
+
8
+ [tool.isort]
9
+ profile = "black"
10
+ line_length = 119
11
+
12
+ [tool.black]
13
+ line-length = 119
requirements.txt ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ APScheduler==3.10.1
2
+ black==23.11.0
3
+ click==8.1.3
4
+ datasets==2.14.5
5
+ gradio==4.4.0
6
+ gradio_client==0.7.0
7
+ huggingface-hub>=0.18.0
8
+ matplotlib==3.7.1
9
+ numpy==1.24.2
10
+ pandas==2.0.0
11
+ python-dateutil==2.8.2
12
+ requests==2.28.2
13
+ tqdm==4.65.0
14
+ transformers==4.35.2
15
+ tokenizers>=0.15.0
scripts/create_request_file.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ import pprint
4
+ import re
5
+ from datetime import datetime, timezone
6
+
7
+ import click
8
+ from colorama import Fore
9
+ from huggingface_hub import HfApi, snapshot_download
10
+
11
+ EVAL_REQUESTS_PATH = "requests"
12
+ QUEUE_REPO = "latticeflow/requests"
13
+
14
+ precisions = ("float16", "bfloat16", "8bit (LLM.int8)", "4bit (QLoRA / FP4)", "GPTQ")
15
+ model_types = ("pretrained", "fine-tuned", "RL-tuned", "instruction-tuned")
16
+ # weight_types = ("Original", "Delta", "Adapter")
17
+
18
+
19
+ def get_model_size(model_info, precision: str):
20
+ size_pattern = size_pattern = re.compile(r"(\d\.)?\d+(b|m)")
21
+ try:
22
+ model_size = round(model_info.safetensors["total"] / 1e9, 3)
23
+ except (AttributeError, TypeError):
24
+ try:
25
+ size_match = re.search(size_pattern, model_info.modelId.lower())
26
+ model_size = size_match.group(0)
27
+ model_size = round(float(model_size[:-1]) if model_size[-1] == "b" else float(model_size[:-1]) / 1e3, 3)
28
+ except AttributeError:
29
+ return None # Unknown model sizes are indicated as 0, see NUMERIC_INTERVALS in app.py
30
+
31
+ size_factor = 8 if (precision == "GPTQ" or "gptq" in model_info.modelId.lower()) else 1
32
+ model_size = size_factor * model_size
33
+ return model_size
34
+
35
+
36
+ def main():
37
+ api = HfApi()
38
+ current_time = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
39
+ snapshot_download(repo_id=QUEUE_REPO, revision="main", local_dir=EVAL_REQUESTS_PATH, repo_type="dataset")
40
+
41
+ model_name = click.prompt("Enter model name")
42
+ revision = click.prompt("Enter revision", default="main")
43
+ precision = click.prompt("Enter precision", default="float16", type=click.Choice(precisions))
44
+ model_type = click.prompt("Enter model type", type=click.Choice(model_types))
45
+ # weight_type = click.prompt("Enter weight type", default="Original", type=click.Choice(weight_types))
46
+ base_model = click.prompt("Enter base model", default="")
47
+ status = click.prompt("Enter status", default="FINISHED")
48
+
49
+ try:
50
+ model_info = api.model_info(repo_id=model_name, revision=revision)
51
+ except Exception as e:
52
+ print(f"{Fore.RED}Could not find model info for {model_name} on the Hub\n{e}{Fore.RESET}")
53
+ return 1
54
+
55
+ model_size = get_model_size(model_info=model_info, precision=precision)
56
+
57
+ try:
58
+ license = model_info.cardData["license"]
59
+ except Exception:
60
+ license = "?"
61
+
62
+ eval_entry = {
63
+ "model": model_name,
64
+ "base_model": base_model,
65
+ "revision": revision,
66
+ "precision": precision,
67
+ # "weight_type": weight_type,
68
+ "status": status,
69
+ "submitted_time": current_time,
70
+ "model_type": model_type,
71
+ "likes": model_info.likes,
72
+ "params": model_size,
73
+ "license": license,
74
+ }
75
+
76
+ user_name = ""
77
+ model_path = model_name
78
+ if "/" in model_name:
79
+ user_name = model_name.split("/")[0]
80
+ model_path = model_name.split("/")[1]
81
+
82
+ pprint.pprint(eval_entry)
83
+
84
+ if click.confirm("Do you want to continue? This request file will be pushed to the hub"):
85
+ click.echo("continuing...")
86
+
87
+ out_dir = f"{EVAL_REQUESTS_PATH}/{user_name}"
88
+ os.makedirs(out_dir, exist_ok=True)
89
+ out_path = f"{out_dir}/{model_path}_eval_request.json"
90
+
91
+ with open(out_path, "w") as f:
92
+ f.write(json.dumps(eval_entry))
93
+
94
+ api.upload_file(
95
+ path_or_fileobj=out_path,
96
+ path_in_repo=out_path.split(f"{EVAL_REQUESTS_PATH}/")[1],
97
+ repo_id=QUEUE_REPO,
98
+ repo_type="dataset",
99
+ commit_message=f"Add {model_name} to eval queue",
100
+ )
101
+ else:
102
+ click.echo("aborting...")
103
+
104
+
105
+ if __name__ == "__main__":
106
+ main()
src/display/about.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass
2
+ from enum import Enum
3
+
4
+
5
+ @dataclass
6
+ class Task:
7
+ benchmark: str
8
+ metric: str
9
+ col_name: str
10
+
11
+
12
+ # Init: to update with your specific keys
13
+ class Tasks(Enum):
14
+ task0 = Task("bbq", "aggregate_score", "Prejudiced Answers: BBQ")
15
+ task1 = Task("bold", "aggregate_score", "Biased Completions: BOLD")
16
+ task2 = Task("toxicity", "aggregate_score", "Toxic Completions of Benign Text: RealToxicityPrompts")
17
+ task3 = Task("toxicity_advbench", "aggregate_score", "Following Harmful Instructions: AdvBench")
18
+ task4 = Task("forecasting_consistency", "aggregate_score", "Monotonicity Checks: Forecasting Consistency")
19
+ task5 = Task("self_check_consistency", "aggregate_score", "Self-Check Consistency")
20
+ task6 = Task("boolq_contrast_robustness", "aggregate_score", "BoolQ Contrast Set")
21
+ task7 = Task("imdb_contrast_robustness", "aggregate_score", "IMDB Contrast Set")
22
+ task8 = Task("calibration_big_bench", "aggregate_score", "Logit Calibration: BIG-Bench")
23
+ task9 = Task("calibration_big_bench_i_know", "aggregate_score", "Self-Assessment: TriviaQA")
24
+ task10 = Task("decoding_trust", "aggregate_score", "Income Fairness: DecodingTrust")
25
+ task11 = Task("hellaswag", "aggregate_score", "Common Sense Reasoning: HellaSwag")
26
+ task12 = Task("human_eval", "aggregate_score", "Coding: HumanEval")
27
+ task13 = Task("instruction_goal_hijacking", "aggregate_score", "Goal Hijacking and Prompt Leakage: TensorTrust")
28
+ task14 = Task("multiturn_goal_hijacking", "aggregate_score", "Rule Following: LLM RuLES")
29
+ task15 = Task("reddit_bias", "aggregate_score", "Representation Bias: RedditBias")
30
+ task16 = Task("truthful_qa_mc2", "aggregate_score", "Truthfulness: TruthfulQA MC2")
31
+ task17 = Task("mmlu", "aggregate_score", "General Knowledge: MMLU")
32
+ task18 = Task("ai2_reasoning", "aggregate_score", "Reasoning: AI2 Reasoning Challenge")
33
+ task19 = Task("human_deception", "aggregate_score", "Denying Human Presence")
34
+ task20 = Task("memorization", "aggregate_score", "Copyrighted Material Memorization")
35
+ task21 = Task("privacy", "aggregate_score", "PII Extraction by Association")
36
+ task22 = Task("fairllm", "aggregate_score", "Recommendation Consistency: FaiRLLM")
37
+ task23 = Task("mmlu_robustness", "aggregate_score", "MMLU: Robustness")
38
+ task24 = Task("training_data_suitability", "aggregate_score", "Training Data Suitability")
39
+ task25 = Task("watermarking", "aggregate_score", "Watermark Reliability & Robustness")
40
+
41
+
42
+
43
+
44
+ # Your leaderboard name
45
+ TITLE = """<h1 align="center" id="space-title">COMPL-AI is an open-source compliance-centered evaluation framework for Generative AI models</h1>"""
46
+
47
+ # What does your leaderboard evaluate?
48
+ INTRODUCTION_TEXT = """<p style="font-size: 16px;">COMPL-AI is an open-source compliance-centered evaluation framework for Generative AI models. It includes the ability to evaluate the regulatory technical requirements on a benchmarking suite containing 27 SOTA LLM benchmarks. The benchmark suite and technical interpretations are both open-source and open to community contributions. For more information, please visit <a href="https://compl-ai.org" target="_blank">compl-ai.org</a>.</p>"""
49
+
50
+ # Which evaluations are you running? how can people reproduce what you have?
51
+ LLM_BENCHMARKS_TEXT = f"""
52
+ """
53
+
54
+ EVALUATION_QUEUE_TEXT = """
55
+ """
56
+
57
+ CITATION_BUTTON_LABEL = "Copy the following snippet to cite these results"
58
+ CITATION_BUTTON_TEXT = r"""
59
+ @article{complai24,
60
+ title={COMPL-AI Framework: A Technical Interpretation and LLM Benchmarking Suite for the EU Artificial Intelligence Act},
61
+ author={Philipp Guldimann and Alexander Spiridonov and Robin Staab and Nikola Jovanovi\'{c} and Mark Vero and Velko Vechev and Anna Gueorguieva and Mislav Balunovi\'{c} and Nikola Konstantinov and Pavol Bielik and Petar Tsankov and Martin Vechev},
62
+ year={2024},
63
+ eprint={2410.07959},
64
+ primaryClass={cs.CL},
65
+ url={https://arxiv.org/abs/2410.07959},
66
+ }
67
+ """
src/display/css_html_js.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ custom_css = """
2
+ /* Hides the final AutoEvalColumn */
3
+ #llm-benchmark-tab-table table td:last-child,
4
+ #llm-benchmark-tab-table table th:last-child {
5
+ display: none;
6
+ }
7
+ /* Limit the width of the first AutoEvalColumn so that names don't expand too much */
8
+ table td:first-child,
9
+ table th:first-child {
10
+ max-width: none; /* Remove any max-width or set it to a higher value */
11
+ overflow: visible; /* Set overflow to visible to ensure the content is not hidden */
12
+ white-space: normal; /* Allow the text to wrap */
13
+ }
14
+
15
+ table {
16
+ table-layout: auto; /* Change from fixed to auto if necessary */
17
+ overflow-x: auto; /* Enable horizontal scrolling if the table is too wide */
18
+ display: block; /* Set display to block for table to behave like a block element */
19
+ }
20
+
21
+ /* Full width space */
22
+ .gradio-container {
23
+ max-width: 95%!important;
24
+ }
25
+
26
+ /* Text style and margins */
27
+ .markdown-text {
28
+ font-size: 16px !important;
29
+ }
30
+ #models-to-add-text {
31
+ font-size: 18px !important;
32
+ }
33
+ #citation-button span {
34
+ font-size: 16px !important;
35
+ }
36
+ #citation-button textarea {
37
+ font-size: 16px !important;
38
+ }
39
+ #citation-button > label > button {
40
+ margin: 6px;
41
+ transform: scale(1.3);
42
+ }
43
+ #search-bar-table-box > div:first-child {
44
+ background: none;
45
+ border: none;
46
+ }
47
+
48
+ #search-bar {
49
+ padding: 0px;
50
+ }
51
+ .tab-buttons button {
52
+ font-size: 20px;
53
+ }
54
+
55
+ /* Filters style */
56
+ #filter_type{
57
+ border: 0;
58
+ padding-left: 0;
59
+ padding-top: 0;
60
+ }
61
+ #filter_type label {
62
+ display: flex;
63
+ }
64
+ #filter_type label > span{
65
+ margin-top: var(--spacing-lg);
66
+ margin-right: 0.5em;
67
+ }
68
+ #filter_type label > .wrap{
69
+ width: 103px;
70
+ }
71
+ #filter_type label > .wrap .wrap-inner{
72
+ padding: 2px;
73
+ }
74
+ #filter_type label > .wrap .wrap-inner input{
75
+ width: 1px;
76
+ }
77
+ #filter-columns-type{
78
+ border:0;
79
+ padding:0.5;
80
+ }
81
+ #filter-columns-size{
82
+ border:0;
83
+ padding:0.5;
84
+ }
85
+ #box-filter > .form{
86
+ border: 0
87
+ }
88
+
89
+ """
90
+
91
+ get_window_url_params = """
92
+ function(url_params) {
93
+ const params = new URLSearchParams(window.location.search);
94
+ url_params = Object.fromEntries(params);
95
+ return url_params;
96
+ }
97
+ """
src/display/formatting.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from datetime import datetime, timezone
3
+
4
+ from huggingface_hub import HfApi
5
+ from huggingface_hub.hf_api import ModelInfo
6
+
7
+
8
+ API = HfApi()
9
+
10
+ def model_hyperlink(link, model_name):
11
+ return f'<a target="_blank" href="{link}" style="color: var(--link-text-color); text-decoration: underline;text-decoration-style: dotted;">{model_name}</a>'
12
+
13
+
14
+ def make_clickable_model(model_name, model_type):
15
+ if not model_type or model_type == "closed":
16
+ return model_name
17
+ # print(model_type, 'model type')
18
+ link = f"https://huggingface.co/{model_name}"
19
+ return model_hyperlink(link, model_name)
20
+
21
+
22
+ def styled_error(error):
23
+ return f"<p style='color: red; font-size: 20px; text-align: center;'>{error}</p>"
24
+
25
+
26
+ def styled_warning(warn):
27
+ return f"<p style='color: orange; font-size: 20px; text-align: center;'>{warn}</p>"
28
+
29
+
30
+ def styled_message(message):
31
+ return f"<p style='color: green; font-size: 20px; text-align: center;'>{message}</p>"
32
+
33
+
34
+ def has_no_nan_values(df, columns):
35
+ return df[columns].notna().all(axis=1)
36
+
37
+
38
+ def has_nan_values(df, columns):
39
+ return df[columns].isna().any(axis=1)
src/display/utils.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass, make_dataclass
2
+ from enum import Enum
3
+
4
+ import pandas as pd
5
+
6
+ from src.display.about import Tasks
7
+
8
+
9
+ def fields(raw_class):
10
+ return [v for k, v in raw_class.__dict__.items() if k[:2] != "__" and k[-2:] != "__"]
11
+
12
+
13
+ # These classes are for user facing column names,
14
+ # to avoid having to change them all around the code
15
+ # when a modif is needed
16
+ @dataclass
17
+ class ColumnContent:
18
+ name: str
19
+ type: str
20
+ displayed_by_default: bool
21
+ hidden: bool = False
22
+ never_hidden: bool = False
23
+ dummy: bool = False
24
+
25
+
26
+ ## Leaderboard columns
27
+ auto_eval_column_dict = [["model_type_symbol", ColumnContent, ColumnContent("T", "str", True, never_hidden=True)],
28
+ ["model", ColumnContent, ColumnContent("Model", "markdown", True, never_hidden=True)]]
29
+ # Init
30
+ # Scores
31
+ for task in Tasks:
32
+ auto_eval_column_dict.append([task.name, ColumnContent, ColumnContent(task.value.col_name, "number", True)])
33
+ # Model information
34
+ auto_eval_column_dict.append(["model_type", ColumnContent, ColumnContent("Type", "str", False)])
35
+ # auto_eval_column_dict.append(["architecture", ColumnContent, ColumnContent("Architecture", "str", False)])
36
+ # auto_eval_column_dict.append(["weight_type", ColumnContent, ColumnContent("Weight type", "str", False, True)])
37
+ # auto_eval_column_dict.append(["precision", ColumnContent, ColumnContent("Precision", "str", False)])
38
+ # auto_eval_column_dict.append(["license", ColumnContent, ColumnContent("Hub License", "str", False, dummy=True)])
39
+ # auto_eval_column_dict.append(["params", ColumnContent, ColumnContent("Params (B)", "number", False)])
40
+
41
+ # auto_eval_column_dict.append(["likes", ColumnContent, ColumnContent("Hub ❤️", "number", False, dummy=True)])
42
+ auto_eval_column_dict.append(["still_on_hub", ColumnContent, ColumnContent("Available on the hub", "bool", False, dummy=True)])
43
+ # auto_eval_column_dict.append(["revision", ColumnContent, ColumnContent("Model sha", "str", False, False, dummy=True)])
44
+ # Dummy column for the search bar (hidden by the custom CSS)
45
+ auto_eval_column_dict.append(["dummy", ColumnContent, ColumnContent("model_name_for_query", "str", False, dummy=True)])
46
+
47
+ # We use make dataclass to dynamically fill the scores from Tasks
48
+ AutoEvalColumn = make_dataclass("AutoEvalColumn", auto_eval_column_dict, frozen=True)
49
+
50
+
51
+ # For the queue columns in the submission tab
52
+ @dataclass(frozen=True)
53
+ class EvalQueueColumn: # Queue column
54
+ model = ColumnContent("model", "markdown", True)
55
+ revision = ColumnContent("revision", "str", True)
56
+ # private = ColumnContent("private", "bool", True)
57
+ # precision = ColumnContent("precision", "str", True)
58
+ # weight_type = ColumnContent("weight_type", "str", "Original")
59
+ status = ColumnContent("status", "str", True)
60
+
61
+
62
+ # All the model information that we might need
63
+ @dataclass
64
+ class ModelDetails:
65
+ name: str
66
+ display_name: str = ""
67
+ symbol: str = "" # emoji
68
+
69
+
70
+ class ModelType(Enum):
71
+ OPEN = ModelDetails(name="Publicly Available", symbol="🟢")
72
+ Unknown = ModelDetails(name="Private", symbol="🔒")
73
+
74
+ def to_str(self, separator=" "):
75
+ return f"{self.value.symbol}{separator}{self.value.name}"
76
+
77
+ @staticmethod
78
+ def from_str(type):
79
+ if "open" in type or "🟢" in type:
80
+ return ModelType.OPEN
81
+ return ModelType.Unknown
82
+
83
+
84
+ class WeightType(Enum):
85
+ Adapter = ModelDetails("Adapter")
86
+ Original = ModelDetails("Original")
87
+ Delta = ModelDetails("Delta")
88
+
89
+
90
+ class Precision(Enum):
91
+ float16 = ModelDetails("float16")
92
+ bfloat16 = ModelDetails("bfloat16")
93
+
94
+ qt_gptq_3bit = ModelDetails("GPTQ-3bit")
95
+ qt_gptq_4bit = ModelDetails("GPTQ-4bit")
96
+ qt_gptq_8bit = ModelDetails("GPTQ-8bit")
97
+ qt_awq_3bit = ModelDetails("AWQ-3bit")
98
+ qt_awq_4bit = ModelDetails("AWQ-4bit")
99
+ qt_awq_8bit = ModelDetails("AWQ-8bit")
100
+
101
+ Unknown = ModelDetails("🔒")
102
+
103
+ def from_str(precision):
104
+ if precision in ["torch.float16", "float16"]:
105
+ return Precision.float16
106
+ if precision in ["torch.bfloat16", "bfloat16"]:
107
+ return Precision.bfloat16
108
+ if precision in ["GPTQ-3bit"]:
109
+ return Precision.qt_gptq_3bit
110
+ if precision in ["GPTQ-4bit"]:
111
+ return Precision.qt_gptq_4bit
112
+ if precision in ["GPTQ-8bit"]:
113
+ return Precision.qt_gptq_8bit
114
+ if precision in ["AWQ-3bit"]:
115
+ return Precision.qt_awq_3bit
116
+ if precision in ["AWQ-4bit"]:
117
+ return Precision.qt_awq_4bit
118
+ if precision in ["AWQ-8bit"]:
119
+ return Precision.qt_awq_8bit
120
+ return Precision.Unknown
121
+
122
+
123
+ # Column selection
124
+ COLS = [c.name for c in fields(AutoEvalColumn) if not c.hidden]
125
+ TYPES = [c.type for c in fields(AutoEvalColumn) if not c.hidden]
126
+ COLS_LITE = [c.name for c in fields(AutoEvalColumn) if c.displayed_by_default and not c.hidden]
127
+ TYPES_LITE = [c.type for c in fields(AutoEvalColumn) if c.displayed_by_default and not c.hidden]
128
+
129
+ EVAL_COLS = [c.name for c in fields(EvalQueueColumn)]
130
+ EVAL_TYPES = [c.type for c in fields(EvalQueueColumn)]
131
+
132
+ BENCHMARK_COLS = [t.value.col_name for t in Tasks]
133
+
134
+ NUMERIC_INTERVALS = {
135
+ "🔒": pd.Interval(-1, 0, closed="right"),
136
+ "~1.5": pd.Interval(0, 2, closed="right"),
137
+ "~3": pd.Interval(2, 4, closed="right"),
138
+ "~7": pd.Interval(4, 9, closed="right"),
139
+ "~13": pd.Interval(9, 20, closed="right"),
140
+ "~35": pd.Interval(20, 45, closed="right"),
141
+ "~60": pd.Interval(45, 70, closed="right"),
142
+ "70+": pd.Interval(70, 10000, closed="right"),
143
+ }
src/envs.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ from huggingface_hub import HfApi
4
+
5
+ # clone / pull the lmeh eval data
6
+ TOKEN = os.environ.get("TOKEN", None)
7
+
8
+ OWNER = "latticeflow"
9
+ REPO_ID = f"{OWNER}/compl-ai-board"
10
+ QUEUE_REPO = f"{OWNER}/requests"
11
+ RESULTS_REPO = f"{OWNER}/results"
12
+
13
+ CACHE_PATH = os.getenv("HF_HOME", ".")
14
+
15
+ # Local caches
16
+ EVAL_REQUESTS_PATH = os.path.join(CACHE_PATH, "requests")
17
+ EVAL_RESULTS_PATH = os.path.join(CACHE_PATH, "results")
18
+
19
+ API = HfApi(token=TOKEN)
src/leaderboard/read_evals.py ADDED
@@ -0,0 +1,223 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ eval_name: str # org_model_precision (uid)
18
+ full_model: str # org/model (path on hub)
19
+ org: str
20
+ model: str
21
+ revision: str # commit hash, "" if main
22
+ results: dict
23
+ precision: Precision = Precision.Unknown
24
+ model_type: ModelType = ModelType.Unknown # Pretrained, fine tuned, ...
25
+ weight_type: WeightType = WeightType.Original # Original or Adapter
26
+ architecture: str = "Unknown"
27
+ license: str = "?"
28
+ likes: int = 0
29
+ num_params: int = 0
30
+ date: str = "" # submission date of request file
31
+ still_on_hub: bool = False
32
+
33
+ @classmethod
34
+ def init_from_json_file(self, json_filepath):
35
+ """Inits the result from the specific model result file"""
36
+ with open(json_filepath) as fp:
37
+ data = json.load(fp)
38
+
39
+ config = data.get("config")
40
+ print(json_filepath)
41
+ # Precision
42
+ # precision = Precision.from_str(config.get("model_dtype"))
43
+
44
+ # Get model and org
45
+ org_and_model = config.get("model_name", config.get("model_args", None))
46
+ org_and_model = org_and_model.split("/", 1)
47
+
48
+ if len(org_and_model) == 1:
49
+ org = None
50
+ model = org_and_model[0]
51
+ result_key = f"{model}"
52
+ else:
53
+ org = org_and_model[0]
54
+ model = org_and_model[1]
55
+ result_key = f"{org}_{model}"
56
+ full_model = "/".join(org_and_model)
57
+
58
+ still_on_hub, _, model_config = is_model_on_hub(
59
+ full_model, config.get("model_sha", "main"), trust_remote_code=True, test_tokenizer=False
60
+ )
61
+ architecture = "?"
62
+ if model_config is not None:
63
+ architectures = getattr(model_config, "architectures", None)
64
+ if architectures:
65
+ architecture = ";".join(architectures)
66
+
67
+ # Extract results available in this file (some results are split in several files)
68
+ results = {}
69
+ for task in Tasks:
70
+ task = task.value
71
+
72
+ # We average all scores of a given metric (not all metrics are present in all files)
73
+
74
+ accs = np.array([v.get(task.metric, None) for k, v in data["results"].items() if task.benchmark == k])
75
+ if accs.size == 0 or any([acc is None for acc in accs]):
76
+ print('skip', full_model)
77
+ results[task.benchmark] = None
78
+ continue
79
+
80
+ print(task)
81
+ print(accs)
82
+ mean_acc = np.mean(accs) # * 100.0
83
+ results[task.benchmark] = round(mean_acc, 2)
84
+
85
+
86
+ return self(
87
+ eval_name=result_key,
88
+ full_model=full_model,
89
+ org=org,
90
+ model=model,
91
+ results=results,
92
+ # precision=precision,
93
+ revision=config.get("model_sha", ""),
94
+ still_on_hub=still_on_hub,
95
+ architecture=architecture
96
+ )
97
+
98
+ def update_with_request_file(self, requests_path):
99
+ """Finds the relevant request file for the current model and updates info with it"""
100
+ request_file = get_request_file_for_model(
101
+ requests_path, self.full_model, self.revision
102
+ )
103
+
104
+ try:
105
+ with open(request_file, "r") as f:
106
+ request = json.load(f)
107
+ print(f"Read Request from {request_file}")
108
+ print(request)
109
+ # self.model_type = ModelType.from_str("open" if "/" in self.full_model and "openai" not in self.full_model else "closed")
110
+ # self.model_type = ModelType.from_str("open" if self.still_on_hub else "closed")
111
+ self.model_type = ModelType.from_str("open" if "/" in self.full_model and "openai" not in self.full_model else "closed")
112
+ self.weight_type = WeightType[request.get("weight_type", "Original")]
113
+ self.license = request.get("license", "?")
114
+ self.likes = request.get("likes", 0)
115
+ self.num_params = request.get("params", None)
116
+ self.date = request.get("submitted_time", "")
117
+ except Exception as e:
118
+ print(e)
119
+ self.model_type = ModelType.from_str("open" if "/" in self.full_model and "openai" not in self.full_model else "closed")
120
+ print(f"Could not find request file ({requests_path}) for {self.org}/{self.model}")
121
+
122
+ def to_dict(self):
123
+ """Converts the Eval Result to a dict compatible with our dataframe display"""
124
+ # average = sum([v for v in self.results.values() if v is not None]) / len(Tasks)
125
+ data_dict = {
126
+ "eval_name": self.eval_name, # not a column, just a save name,
127
+ # AutoEvalColumn.precision.name: self.precision.value.name,
128
+ AutoEvalColumn.model_type.name: self.model_type.value.name,
129
+ AutoEvalColumn.model_type_symbol.name: self.model_type.value.symbol,
130
+ # AutoEvalColumn.weight_type.name: self.weight_type.value.name,
131
+ # AutoEvalColumn.architecture.name: self.architecture,
132
+ AutoEvalColumn.model.name: make_clickable_model(self.full_model, self.model_type.value.name),
133
+ AutoEvalColumn.dummy.name: self.full_model,
134
+ # AutoEvalColumn.
135
+ # revision.name: self.revision,
136
+ # AutoEvalColumn.average.name: average,
137
+ # AutoEvalColumn.license.name: self.license,
138
+ # AutoEvalColumn.likes.name: self.likes,
139
+ # AutoEvalColumn.params.name: self.num_params,
140
+ AutoEvalColumn.still_on_hub.name: self.still_on_hub,
141
+ }
142
+
143
+ for task in Tasks:
144
+ data_dict[task.value.col_name] = self.results[task.value.benchmark] or "N/A"
145
+
146
+ return data_dict
147
+
148
+
149
+ def get_request_file_for_model(requests_path, model_name, revision=""):
150
+ """Selects the correct request file for a given model. Only keeps runs tagged as FINISHED"""
151
+
152
+ request_files = os.path.join(
153
+ requests_path,
154
+ f"**/request_{model_name}*_eval_request*.json"
155
+ )
156
+ print(f"Looking up request file(s) with pattern {request_files}")
157
+ request_files = glob.glob(request_files, recursive=True)
158
+ print(f"Found request file(s) {request_files}")
159
+
160
+ # Select correct request file (precision)
161
+ request_file = ""
162
+ request_files = sorted(request_files, reverse=True)
163
+ for tmp_request_file in request_files:
164
+ with open(tmp_request_file, "r") as f:
165
+ req_content = json.load(f)
166
+ # print("Precision", req_content["precision"])
167
+ if (
168
+ req_content["status"] in ["FINISHED"]
169
+ # and req_content["precision"] == precision.split(".")[-1]
170
+ ):
171
+ request_file = tmp_request_file
172
+ print(f"Selected {request_file} for model metadata")
173
+ return request_file
174
+
175
+
176
+ def get_raw_eval_results(results_path: str, requests_path: str) -> list[EvalResult]:
177
+ """From the path of the results folder root, extract all needed info for results"""
178
+ model_result_filepaths = []
179
+
180
+ for root, _, files in os.walk(results_path):
181
+ # We should only have json files in model results
182
+ if len(files) == 0 or any([not f.endswith(".json") for f in files]):
183
+ continue
184
+
185
+ # Sort the files by date
186
+ try:
187
+ files.sort(key=lambda x: x.removesuffix(".json").removeprefix("results_")[:-7])
188
+ except dateutil.parser._parser.ParserError:
189
+ files = [files[-1]]
190
+
191
+ for file in files:
192
+ model_result_filepaths.append(os.path.join(root, file))
193
+
194
+ eval_results = {}
195
+ for model_result_filepath in model_result_filepaths:
196
+ # Creation of result
197
+ eval_result = EvalResult.init_from_json_file(model_result_filepath)
198
+ print()
199
+ print('eval result')
200
+ print(eval_result)
201
+ print()
202
+ eval_result.update_with_request_file(requests_path)
203
+
204
+ # Store results of same eval together
205
+ eval_name = eval_result.eval_name
206
+ if eval_name in eval_results.keys():
207
+ eval_results[eval_name].results.update({k: v for k, v in eval_result.results.items() if v is not None})
208
+ else:
209
+ eval_results[eval_name] = eval_result
210
+
211
+ results = []
212
+
213
+ for v in eval_results.values():
214
+ try:
215
+ print()
216
+ print(v)
217
+ print()
218
+ v.to_dict() # we test if the dict version is complete
219
+ results.append(v)
220
+ except KeyError: # not all eval values present
221
+ continue
222
+
223
+ return results
src/populate.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ raw_data = get_raw_eval_results(results_path, requests_path)
13
+ all_data_json = [v.to_dict() for v in raw_data]
14
+ print(all_data_json)
15
+ df = pd.DataFrame.from_records(all_data_json)
16
+ # df = df.sort_values(by=[AutoEvalColumn.average.name], ascending=False)
17
+ df = df[cols].round(decimals=2)
18
+
19
+ # filter out if any of the benchmarks have not been produced
20
+ # df = df[has_no_nan_values(df, benchmark_cols)] TODO: NAN?
21
+ return raw_data, df
22
+
23
+
24
+ def get_evaluation_queue_df(save_path: str, cols: list) -> list[pd.DataFrame]:
25
+ entries = [entry for entry in os.listdir(save_path) if not entry.startswith(".")]
26
+ all_evals = []
27
+
28
+ for entry in entries:
29
+ if ".json" in entry:
30
+ file_path = os.path.join(save_path, entry)
31
+ with open(file_path) as fp:
32
+ data = json.load(fp)
33
+
34
+ data[EvalQueueColumn.model.name] = make_clickable_model(data["model"], data["model_type"])
35
+ data[EvalQueueColumn.revision.name] = data.get("revision", "main")
36
+
37
+ all_evals.append(data)
38
+ elif ".md" not in entry:
39
+ # this is a folder
40
+ sub_entries = [e for e in os.listdir(f"{save_path}/{entry}") if not e.startswith(".")]
41
+ for sub_entry in sub_entries:
42
+ file_path = os.path.join(save_path, entry, sub_entry)
43
+ print(file_path)
44
+ with open(file_path) as fp:
45
+ data = json.load(fp)
46
+
47
+ data[EvalQueueColumn.model.name] = make_clickable_model(data["model"], data["model_type"])
48
+ data[EvalQueueColumn.revision.name] = data.get("revision", "main")
49
+ all_evals.append(data)
50
+
51
+ pending_list = [e for e in all_evals if e["status"] in ["PENDING", "RERUN"]]
52
+ finished_list = [e for e in all_evals if e["status"].startswith("FINISHED") or e["status"] == "PENDING_NEW_EVAL"]
53
+ df_pending = pd.DataFrame.from_records(pending_list, columns=cols)
54
+ df_finished = pd.DataFrame.from_records(finished_list, columns=cols)
55
+ return df_finished[cols], df_pending[cols]
src/submission/check_validity.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 tokenizer_class_from_name, get_tokenizer_config
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
+
35
+ def is_model_on_hub(model_name: str, revision: str, token: str = None, trust_remote_code=False, test_tokenizer=False) -> tuple[bool, str]:
36
+ """Makes sure the model is on the hub, and uses a valid configuration (in the latest transformers version)"""
37
+ try:
38
+ config = AutoConfig.from_pretrained(model_name, revision=revision, trust_remote_code=trust_remote_code, token=token)
39
+ if test_tokenizer:
40
+ tokenizer_config = get_tokenizer_config(model_name)
41
+ if tokenizer_config is not None:
42
+ tokenizer_class_candidate = tokenizer_config.get("tokenizer_class", None)
43
+ else:
44
+ tokenizer_class_candidate = config.tokenizer_class
45
+
46
+
47
+ tokenizer_class = tokenizer_class_from_name(tokenizer_class_candidate)
48
+ if tokenizer_class is None:
49
+ return (
50
+ False,
51
+ f"uses {tokenizer_class_candidate}, which is not in a transformers release, therefore not supported at the moment.",
52
+ None
53
+ )
54
+ return True, None, config
55
+
56
+ except ValueError:
57
+ return (
58
+ False,
59
+ "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.",
60
+ None
61
+ )
62
+
63
+ except Exception as e:
64
+ return False, "was not found on hub!", None
65
+
66
+
67
+ def get_model_size(model_info: ModelInfo, precision: str = ""):
68
+ """Gets the model size from the configuration, or the model name if the configuration does not contain the information."""
69
+ try:
70
+ model_size = round(model_info.safetensors["total"] / 1e9, 3)
71
+ except (AttributeError, TypeError):
72
+ return 0 # Unknown model sizes are indicated as 0, see NUMERIC_INTERVALS in app.py
73
+
74
+ size_factor = 8 if (precision == "GPTQ" or "gptq" in model_info.modelId.lower()) else 1
75
+ model_size = size_factor * model_size
76
+ return model_size
77
+
78
+ def get_model_arch(model_info: ModelInfo):
79
+ """Gets the model architecture from the configuration"""
80
+ return model_info.config.get("architectures", "Unknown")
81
+
82
+ def already_submitted_models(requested_models_dir: str) -> set[str]:
83
+ depth = 1
84
+ file_names = []
85
+ users_to_submission_dates = defaultdict(list)
86
+
87
+ for root, _, files in os.walk(requested_models_dir):
88
+ current_depth = root.count(os.sep) - requested_models_dir.count(os.sep)
89
+ if current_depth == depth:
90
+ for file in files:
91
+ if not file.endswith(".json"):
92
+ continue
93
+ with open(os.path.join(root, file), "r") as f:
94
+ info = json.load(f)
95
+ file_names.append(f"{info['model']}_{info['revision']}")
96
+
97
+ # Select organisation
98
+ if info["model"].count("/") == 0 or "submitted_time" not in info:
99
+ continue
100
+ organisation, _ = info["model"].split("/")
101
+ users_to_submission_dates[organisation].append(info["submitted_time"])
102
+
103
+ return set(file_names), users_to_submission_dates
src/submission/submit.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
18
+ def add_new_eval(
19
+ model: str,
20
+ base_model: str,
21
+ revision: str,
22
+ # weight_type: str,
23
+ ):
24
+ global REQUESTED_MODELS
25
+ global USERS_TO_SUBMISSION_DATES
26
+ if not REQUESTED_MODELS:
27
+ REQUESTED_MODELS, USERS_TO_SUBMISSION_DATES = already_submitted_models(EVAL_REQUESTS_PATH)
28
+
29
+ user_name = ""
30
+ model_path = model
31
+ if "/" in model:
32
+ user_name = model.split("/")[0]
33
+ model_path = model.split("/")[1]
34
+
35
+ current_time = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
36
+
37
+ # if model_type is None or model_type == "":
38
+ # return styled_error("Please select a model type.")
39
+
40
+ # Does the model actually exist?
41
+ if revision == "":
42
+ revision = "main"
43
+
44
+ # Is the model on the hub?
45
+ # if weight_type in ["Delta", "Adapter"]:
46
+ # base_model_on_hub, error, _ = is_model_on_hub(model_name=base_model, revision=revision, token=TOKEN,
47
+ # test_tokenizer=True)
48
+ # if not base_model_on_hub:
49
+ # return styled_error(f'Base model "{base_model}" {error}')
50
+
51
+ # if not weight_type == "Adapter":
52
+ # model_on_hub, error, _ = is_model_on_hub(model_name=model, revision=revision, test_tokenizer=True)
53
+ # if not model_on_hub:
54
+ # return styled_error(f'Model "{model}" {error}')
55
+
56
+ # Is the model info correctly filled?
57
+ try:
58
+ model_info = API.model_info(repo_id=model, revision=revision)
59
+ except Exception:
60
+ return styled_error("Could not get your model information. Please fill it up properly.")
61
+
62
+ model_size = get_model_size(model_info=model_info)
63
+
64
+ # Were the model card and license filled?
65
+ try:
66
+ license = model_info.cardData["license"]
67
+ except Exception:
68
+ return styled_error("Please select a license for your model")
69
+
70
+ modelcard_OK, error_msg = check_model_card(model)
71
+ if not modelcard_OK:
72
+ return styled_error(error_msg)
73
+
74
+ # Seems good, creating the eval
75
+ print("Adding new eval")
76
+
77
+ eval_entry = {
78
+ "model": model,
79
+ "revision": "main",
80
+ "status": "PENDING",
81
+ "model_type": "open",
82
+ "submitted_time": current_time,
83
+ "params": model_size,
84
+ "license": license,
85
+ }
86
+
87
+ # Check for duplicate submission
88
+ if f"{model}_{revision}" in REQUESTED_MODELS:
89
+ return styled_warning("This model has been already submitted.")
90
+
91
+ print("Creating eval file")
92
+ OUT_DIR = f"{EVAL_REQUESTS_PATH}/{user_name}"
93
+ os.makedirs(OUT_DIR, exist_ok=True)
94
+ out_path = f"{OUT_DIR}/{model_path}_eval_request.json"
95
+
96
+ with open(out_path, "w") as f:
97
+ f.write(json.dumps(eval_entry))
98
+
99
+ print("Uploading eval file")
100
+ API.upload_file(
101
+ path_or_fileobj=out_path,
102
+ path_in_repo=out_path.split("requests/")[1],
103
+ repo_id=QUEUE_REPO,
104
+ repo_type="dataset",
105
+ commit_message=f"Add {model} to eval queue",
106
+ )
107
+
108
+ # Remove the local file
109
+ os.remove(out_path)
110
+
111
+ return styled_message(
112
+ "Your model request has been submitted successfully. Please allow some time for the evaluation to complete. Note that, in some cases, it may take more than 24 hours for a single model to finish processing. We appreciate your patience."
113
+ )