Andrea Seveso commited on
Commit
e5ee086
·
0 Parent(s):

initial code

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,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: INVALSIbenchmark
3
+ emoji: 🥇
4
+ colorFrom: green
5
+ colorTo: indigo
6
+ sdk: gradio
7
+ app_file: app.py
8
+ pinned: true
9
+ license: apache-2.0
10
+ ---
11
+
12
+ # Start the configuration
13
+
14
+ Most of the variables to change for a default leaderboard are in `src/env.py` (replace the path for your leaderboard) and `src/about.py` (for tasks).
15
+
16
+ Results files should have the following format and be stored as json files:
17
+ ```json
18
+ {
19
+ "config": {
20
+ "model_dtype": "torch.float16", # or torch.bfloat16 or 8bit or 4bit
21
+ "model_name": "path of the model on the hub: org/model",
22
+ "model_sha": "revision on the hub",
23
+ },
24
+ "results": {
25
+ "task_name": {
26
+ "metric_name": score,
27
+ },
28
+ "task_name2": {
29
+ "metric_name": score,
30
+ }
31
+ }
32
+ }
33
+ ```
34
+
35
+ Request files are created automatically by this tool.
36
+
37
+ If you encounter problem on the space, don't hesitate to restart it to remove the create eval-queue, eval-queue-bk, eval-results and eval-results-bk created folder.
38
+
39
+ # Code logic for more complex edits
40
+
41
+ You'll find
42
+ - the main table' columns names and properties in `src/display/utils.py`
43
+ - the logic to read all results and request files, then convert them in dataframe lines, in `src/leaderboard/read_evals.py`, and `src/populate.py`
44
+ - teh logic to allow or filter submissions in `src/submission/submit.py` and `src/submission/check_validity.py`
app.py ADDED
@@ -0,0 +1,327 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import subprocess
2
+ import gradio as gr
3
+ import pandas as pd
4
+ from apscheduler.schedulers.background import BackgroundScheduler
5
+ from huggingface_hub import snapshot_download
6
+
7
+ from src.about import (
8
+ CITATION_BUTTON_LABEL,
9
+ CITATION_BUTTON_TEXT,
10
+ EVALUATION_QUEUE_TEXT,
11
+ INTRODUCTION_TEXT,
12
+ LLM_BENCHMARKS_TEXT,
13
+ TITLE,
14
+ EVALUATION_QUEUE_TEXT,
15
+ )
16
+ from src.display.css_html_js import custom_css
17
+ from src.display.utils import (
18
+ BENCHMARK_COLS,
19
+ COLS,
20
+ EVAL_COLS,
21
+ SIZE_INTERVALS,
22
+ TYPES,
23
+ AutoEvalColumn,
24
+ ModelType,
25
+ fields,
26
+ )
27
+ from src.envs import API, EVAL_REQUESTS_PATH, EVAL_RESULTS_PATH, QUEUE_REPO, REPO_ID, RESULTS_REPO, TOKEN
28
+ from src.populate import get_evaluation_queue_df, get_leaderboard_df
29
+ from src.submission.submit import add_new_eval
30
+
31
+
32
+ def restart_space():
33
+ API.restart_space(repo_id=REPO_ID)
34
+
35
+
36
+ try:
37
+ print(EVAL_REQUESTS_PATH)
38
+ snapshot_download(
39
+ repo_id=QUEUE_REPO, local_dir=EVAL_REQUESTS_PATH, repo_type="dataset", tqdm_class=None, etag_timeout=30, token=TOKEN
40
+ )
41
+ except Exception:
42
+ restart_space()
43
+ try:
44
+ print(EVAL_RESULTS_PATH)
45
+ snapshot_download(
46
+ repo_id=RESULTS_REPO, local_dir=EVAL_RESULTS_PATH, repo_type="dataset", tqdm_class=None, etag_timeout=30, token=TOKEN
47
+ )
48
+ except Exception:
49
+ restart_space()
50
+
51
+
52
+ raw_data, original_df = get_leaderboard_df(
53
+ EVAL_RESULTS_PATH, EVAL_REQUESTS_PATH, COLS, BENCHMARK_COLS)
54
+ leaderboard_df = original_df.copy()
55
+
56
+ (
57
+ finished_eval_queue_df,
58
+ running_eval_queue_df,
59
+ pending_eval_queue_df,
60
+ ) = get_evaluation_queue_df(EVAL_REQUESTS_PATH, EVAL_COLS)
61
+
62
+
63
+ # Searching and filtering
64
+ def update_table(
65
+ hidden_df: pd.DataFrame,
66
+ columns: list,
67
+ type_query: list,
68
+ size_query: list,
69
+ query: str,
70
+ ):
71
+ filtered_df = filter_models(
72
+ hidden_df, type_query, size_query)
73
+ filtered_df = filter_queries(query, filtered_df)
74
+ df = select_columns(filtered_df, columns)
75
+ return df
76
+
77
+
78
+ def search_table(df: pd.DataFrame, query: str) -> pd.DataFrame:
79
+ return df[(df[AutoEvalColumn.model.name].str.contains(query, case=False))]
80
+
81
+
82
+ def select_columns(df: pd.DataFrame, columns: list) -> pd.DataFrame:
83
+ always_here_cols = [
84
+ AutoEvalColumn.model_type_symbol.name,
85
+ AutoEvalColumn.model.name,
86
+ ]
87
+ # We use COLS to maintain sorting
88
+ filtered_df = df[
89
+ always_here_cols +
90
+ [c for c in COLS if c in df.columns and c in columns]
91
+ ]
92
+ return filtered_df
93
+
94
+
95
+ def filter_queries(query: str, filtered_df: pd.DataFrame) -> pd.DataFrame:
96
+ final_df = []
97
+ if query != "":
98
+ queries = [q.strip() for q in query.split(";")]
99
+ for _q in queries:
100
+ _q = _q.strip()
101
+ if _q != "":
102
+ temp_filtered_df = search_table(filtered_df, _q)
103
+ if len(temp_filtered_df) > 0:
104
+ final_df.append(temp_filtered_df)
105
+ if len(final_df) > 0:
106
+ filtered_df = pd.concat(final_df)
107
+ filtered_df = filtered_df.drop_duplicates(
108
+ subset=[AutoEvalColumn.model.name]
109
+ )
110
+
111
+ return filtered_df
112
+
113
+
114
+ def filter_models(
115
+ df: pd.DataFrame, type_query: list, size_query: list,
116
+ ) -> pd.DataFrame:
117
+
118
+ filtered_df = df
119
+
120
+ type_emoji = [t[0] for t in type_query]
121
+ filtered_df = filtered_df.loc[df[AutoEvalColumn.model_type_symbol.name].isin(
122
+ type_emoji)]
123
+
124
+ filtered_df = filtered_df.loc[df[AutoEvalColumn.params.name].isin(
125
+ size_query)]
126
+
127
+ return filtered_df
128
+
129
+
130
+ demo = gr.Blocks(css=custom_css)
131
+ with demo:
132
+ gr.HTML(TITLE)
133
+ gr.Markdown(INTRODUCTION_TEXT, elem_classes="markdown-text")
134
+
135
+ with gr.Tabs(elem_classes="tab-buttons") as tabs:
136
+ with gr.TabItem("🏅 LLM Benchmark", elem_id="llm-benchmark-tab-table", id=0):
137
+ with gr.Row():
138
+ with gr.Column():
139
+ with gr.Row():
140
+ search_bar = gr.Textbox(
141
+ placeholder=" 🔍 Search for your model (separate multiple queries with `;`) and press ENTER...",
142
+ show_label=False,
143
+ elem_id="search-bar",
144
+ )
145
+ with gr.Row():
146
+ shown_columns = gr.CheckboxGroup(
147
+ choices=[
148
+ c.name
149
+ for c in fields(AutoEvalColumn)
150
+ if not c.hidden and not c.never_hidden
151
+ ],
152
+ value=[
153
+ c.name
154
+ for c in fields(AutoEvalColumn)
155
+ if c.displayed_by_default and not c.hidden and not c.never_hidden
156
+ ],
157
+ label="Select columns to show",
158
+ elem_id="column-select",
159
+ interactive=True,
160
+ )
161
+ with gr.Column(min_width=320):
162
+ # with gr.Box(elem_id="box-filter"):
163
+ filter_columns_type = gr.CheckboxGroup(
164
+ label="Model types",
165
+ choices=[t.to_str() for t in ModelType],
166
+ value=[t.to_str() for t in ModelType],
167
+ interactive=True,
168
+ elem_id="filter-columns-type",
169
+ )
170
+ filter_columns_size = gr.CheckboxGroup(
171
+ label="Model sizes",
172
+ choices=list(SIZE_INTERVALS),
173
+ value=list(SIZE_INTERVALS),
174
+ interactive=True,
175
+ elem_id="filter-columns-size",
176
+ )
177
+
178
+ leaderboard_table = gr.components.Dataframe(
179
+ value=leaderboard_df[
180
+ [c.name for c in fields(AutoEvalColumn) if c.never_hidden]
181
+ + shown_columns.value
182
+ ],
183
+ headers=[c.name for c in fields(
184
+ AutoEvalColumn) if c.never_hidden] + shown_columns.value,
185
+ datatype=TYPES,
186
+ elem_id="leaderboard-table",
187
+ interactive=False,
188
+ visible=True,
189
+ )
190
+
191
+ # Dummy leaderboard for handling the case when the user uses backspace key
192
+ hidden_leaderboard_table_for_search = gr.components.Dataframe(
193
+ value=original_df[COLS],
194
+ headers=COLS,
195
+ datatype=TYPES,
196
+ visible=False,
197
+ )
198
+ search_bar.submit(
199
+ update_table,
200
+ [
201
+ hidden_leaderboard_table_for_search,
202
+ shown_columns,
203
+ filter_columns_type,
204
+ filter_columns_size,
205
+ search_bar,
206
+ ],
207
+ leaderboard_table,
208
+ )
209
+ for selector in [shown_columns, filter_columns_type, filter_columns_size]:
210
+ selector.change(
211
+ update_table,
212
+ [
213
+ hidden_leaderboard_table_for_search,
214
+ shown_columns,
215
+ filter_columns_type,
216
+ filter_columns_size,
217
+ search_bar,
218
+ ],
219
+ leaderboard_table,
220
+ queue=True,
221
+ )
222
+
223
+ with gr.TabItem("📝 About", elem_id="llm-benchmark-tab-table", id=2):
224
+ gr.Markdown(LLM_BENCHMARKS_TEXT, elem_classes="markdown-text")
225
+
226
+ with gr.TabItem("🚀 Submit here! ", elem_id="llm-benchmark-tab-table", id=3):
227
+ with gr.Column():
228
+ with gr.Row():
229
+ gr.Markdown(EVALUATION_QUEUE_TEXT,
230
+ elem_classes="markdown-text")
231
+
232
+ # with gr.Column():
233
+ # with gr.Accordion(
234
+ # f"✅ Finished Evaluations ({len(finished_eval_queue_df)})",
235
+ # open=False,
236
+ # ):
237
+ # with gr.Row():
238
+ # finished_eval_table = gr.components.Dataframe(
239
+ # value=finished_eval_queue_df,
240
+ # headers=EVAL_COLS,
241
+ # datatype=EVAL_TYPES,
242
+ # row_count=5,
243
+ # )
244
+ # with gr.Accordion(
245
+ # f"🔄 Running Evaluation Queue ({len(running_eval_queue_df)})",
246
+ # open=False,
247
+ # ):
248
+ # with gr.Row():
249
+ # running_eval_table = gr.components.Dataframe(
250
+ # value=running_eval_queue_df,
251
+ # headers=EVAL_COLS,
252
+ # datatype=EVAL_TYPES,
253
+ # row_count=5,
254
+ # )
255
+
256
+ # with gr.Accordion(
257
+ # f"⏳ Pending Evaluation Queue ({len(pending_eval_queue_df)})",
258
+ # open=False,
259
+ # ):
260
+ # with gr.Row():
261
+ # pending_eval_table = gr.components.Dataframe(
262
+ # value=pending_eval_queue_df,
263
+ # headers=EVAL_COLS,
264
+ # datatype=EVAL_TYPES,
265
+ # row_count=5,
266
+ # )
267
+ # with gr.Row():
268
+ # gr.Markdown("# ✉️✨ Submit your model here!", elem_classes="markdown-text")
269
+
270
+ # with gr.Row():
271
+ # with gr.Column():
272
+ # model_name_textbox = gr.Textbox(label="Model name")
273
+ # revision_name_textbox = gr.Textbox(label="Revision commit", placeholder="main")
274
+ # model_type = gr.Dropdown(
275
+ # choices=[t.to_str(" : ") for t in ModelType if t != ModelType.Unknown],
276
+ # label="Model type",
277
+ # multiselect=False,
278
+ # value=None,
279
+ # interactive=True,
280
+ # )
281
+
282
+ # with gr.Column():
283
+ # precision = gr.Dropdown(
284
+ # choices=[i.value.name for i in Precision if i != Precision.Unknown],
285
+ # label="Precision",
286
+ # multiselect=False,
287
+ # value="float16",
288
+ # interactive=True,
289
+ # )
290
+ # weight_type = gr.Dropdown(
291
+ # choices=[i.value.name for i in WeightType],
292
+ # label="Weights type",
293
+ # multiselect=False,
294
+ # value="Original",
295
+ # interactive=True,
296
+ # )
297
+ # base_model_name_textbox = gr.Textbox(label="Base model (for delta or adapter weights)")
298
+
299
+ # submit_button = gr.Button("Submit Eval")
300
+ # submission_result = gr.Markdown()
301
+ # submit_button.click(
302
+ # add_new_eval,
303
+ # [
304
+ # model_name_textbox,
305
+ # base_model_name_textbox,
306
+ # revision_name_textbox,
307
+ # precision,
308
+ # weight_type,
309
+ # model_type,
310
+ # ],
311
+ # submission_result,
312
+ # )
313
+
314
+ with gr.Row():
315
+ with gr.Accordion("📙 Citation", open=False):
316
+ citation_button = gr.Textbox(
317
+ value=CITATION_BUTTON_TEXT,
318
+ label=CITATION_BUTTON_LABEL,
319
+ lines=20,
320
+ elem_id="citation-button",
321
+ show_copy_button=True,
322
+ )
323
+
324
+ scheduler = BackgroundScheduler()
325
+ scheduler.add_job(restart_space, "interval", seconds=1800)
326
+ scheduler.start()
327
+ 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,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ APScheduler
2
+ black
3
+ click
4
+ datasets
5
+ gradio
6
+ gradio_client
7
+ huggingface-hub>=0.18.0
8
+ matplotlib
9
+ numpy
10
+ pandas
11
+ python-dateutil
12
+ requests
13
+ tqdm
14
+ transformers
15
+ tokenizers>=0.15.0
16
+ git+https://github.com/EleutherAI/lm-evaluation-harness.git@b281b0921b636bc36ad05c0b0b0763bd6dd43463#egg=lm-eval
17
+ accelerate
18
+ sentencepiece
src/about.py ADDED
@@ -0,0 +1,242 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # Select your tasks here
13
+ # ---------------------------------------------------
14
+ class Tasks(Enum):
15
+ # task_key in the json file, metric_key in the json file, name to display in the leaderboard
16
+ task0 = Task("main", "acc", "Overall")
17
+
18
+
19
+ NUM_FEWSHOT = 0 # Change with your few shot
20
+ # ---------------------------------------------------
21
+
22
+
23
+ # Your leaderboard name
24
+ TITLE = """<h1 align="center" id="space-title">👩‍🏫Invalsi Leaderboard
25
+ <img src="https://huggingface.co/spaces/Crisp-Unimib/INVALSIbenchmark/resolve/main/src/logo-crisp-eng-retina.png" height="800" width="150" style="vertical-align: middle;">
26
+ </h1>"""
27
+
28
+ # What does your leaderboard evaluate?
29
+ INTRODUCTION_TEXT = """
30
+ Welcome into <a href="https://crispresearch.it/"><b>CRISP Bicocca</b></a> Invalsi Leaderboard page!
31
+ On this page you will find the Invalsi Leaderboard: The Invalsi tests are tests prepared by the Invalsi Institute, administered to primary and secondary school students to assess their knowledge about mathematics and the Italian language.
32
+
33
+ We structured a benchmark for assessing Italian capabilities of both open and close source Large Language Models, using 10 Invalsi tests, including all different grades of difficulty. (Paper Link)
34
+ """
35
+
36
+ # Which evaluations are you running? how can people reproduce what you have?
37
+ LLM_BENCHMARKS_TEXT = f"""
38
+ ## INVALSI Benchmark
39
+
40
+ ### Data Collection
41
+ We have collected from public sources 58 unique tests, divided into 141 unique units, with 2114 questions and 2808 unique items. Some questions are subdivided into multiple items, each requiring a specific answer.
42
+ The data has been gathered from the <a href="https://www.gestinv.it/Index.aspx"><b>Gestinv</b></a> database.
43
+ Questions' formatting is sometimes not adequately structured for LLM evaluation; for instance, it is sometimes impossible to automatically transcribe the questions into structured fields, necessitating further inspection of images and PDFs. For this reason, we also collected corresponding PDF files and images. Manual inspection was required to ensure accuracy. In cases where questions involved graphical elements, we modified them into an appropriate multiple-choice format. For example, if the task required a student to find and underscore a word, we reformulated the question to allow selection from multiple choices. Similarly, if the task involved drawing a line between two groups of concepts—a common task for younger students—we rephrased it to involve choosing the correct association from given options. Generally, we aimed to adapt the questions to a format that allows the model to select the correct answer from a pool of choices if it aligns with the original type of question.
44
+
45
+
46
+ ### Dataset Characteristics
47
+
48
+ <ul>
49
+ <li> We have selected <b>10 tests</b> comprising <b>31 unique units</b>, <b>409 questions</b>, and <b>625 items</b> from the above data. A test comprises <b>two or more different units</b>; each question can have more than one item to answer. The sample of tests has been chosen by manual inspection, aiming to include different grades and years and avoiding those with questions that require inspecting an image or contained questions that would be hard to reformulate for language model comprehension. <br> <br>
50
+ <table style="font-size: 18px; border-collapse: collapse; width: 60%; margin: auto; border: 1px solid black;">
51
+ <caption style="caption-side: top; text-align: center; font-weight: bold;">
52
+ Distribution of tests, questions and items by educational grade.
53
+ </caption>
54
+ <thead>
55
+ <tr style="background-color: #f2f2f2;">
56
+ <th style="border: 1px solid black; padding: 8px; text-align: left;">School Grade</th>
57
+ <th style="border: 1px solid black; padding: 8px; text-align: left;"># Tests</th>
58
+ <th style="border: 1px solid black; padding: 8px; text-align: left;"># Questions</th>
59
+ <th style="border: 1px solid black; padding: 8px; text-align: left;"># Items</th>
60
+ </tr>
61
+ </thead>
62
+ <tbody>
63
+ <tr>
64
+ <td style="border: 1px solid black; padding: 8px; text-align: left;">2nd Grade (Primary School)</td>
65
+ <td style="border: 1px solid black; padding: 8px; text-align: left;">2</td>
66
+ <td style="border: 1px solid black; padding: 8px; text-align: left;">34</td>
67
+ <td style="border: 1px solid black; padding: 8px; text-align: left;">72</td>
68
+ </tr>
69
+ <tr>
70
+ <td style="border: 1px solid black; padding: 8px; text-align: left;">5th Grade (Primary School)</td>
71
+ <td style="border: 1px solid black; padding: 8px; text-align: left;">2</td>
72
+ <td style="border: 1px solid black; padding: 8px; text-align: left;">75</td>
73
+ <td style="border: 1px solid black; padding: 8px; text-align: left;">117</td>
74
+ </tr>
75
+ <tr>
76
+ <td style="border: 1px solid black; padding: 8px; text-align: left;">6th Grade (Middle School)</td>
77
+ <td style="border: 1px solid black; padding: 8px; text-align: left;">1</td>
78
+ <td style="border: 1px solid black; padding: 8px; text-align: left;">87</td>
79
+ <td style="border: 1px solid black; padding: 8px; text-align: left;">118</td>
80
+ </tr>
81
+ <tr>
82
+ <td style="border: 1px solid black; padding: 8px; text-align: left;">8th Grade (Middle School)</td>
83
+ <td style="border: 1px solid black; padding: 8px; text-align: left;">2</td>
84
+ <td style="border: 1px solid black; padding: 8px; text-align: left;">86</td>
85
+ <td style="border: 1px solid black; padding: 8px; text-align: left;">88</td>
86
+ </tr>
87
+ <tr>
88
+ <td style="border: 1px solid black; padding: 8px; text-align: left;">10th Grade (High School)</td>
89
+ <td style="border: 1px solid black; padding: 8px; text-align: left;">2</td>
90
+ <td style="border: 1px solid black; padding: 8px; text-align: left;">77</td>
91
+ <td style="border: 1px solid black; padding: 8px; text-align: left;">139</td>
92
+ </tr>
93
+ <tr>
94
+ <td style="border: 1px solid black; padding: 8px; text-align: left;">13th Grade (High School)</td>
95
+ <td style="border: 1px solid black; padding: 8px; text-align: left;">1</td>
96
+ <td style="border: 1px solid black; padding: 8px; text-align: left;">50</td>
97
+ <td style="border: 1px solid black; padding: 8px; text-align: left;">91</td>
98
+ </tr>
99
+ </tbody>
100
+ </table>
101
+ </li>
102
+ <br> <br>
103
+ <li> Each question in the benchmark is labelled with the specific <b>lexical macro area</b> it aims to assess <br> <br>
104
+
105
+ <table style="font-size: 18px; border-collapse: collapse; width: 80%; margin: auto; border: 1px solid black;">
106
+ <caption style="caption-side: top; text-align: center; font-weight: bold;">
107
+ Distribution of questions by section and macro area.
108
+ </caption>
109
+ <thead>
110
+ <tr style="background-color: #f2f2f2;">
111
+ <th style="border: 1px solid black; padding: 8px; text-align: left;">Section</th>
112
+ <th style="border: 1px solid black; padding: 8px; text-align: left; width: 3.5cm;">Macro Area</th>
113
+ <th style="border: 1px solid black; padding: 8px; text-align: right;"># Questions</th>
114
+ </tr>
115
+ </thead>
116
+ <tbody>
117
+ <tr>
118
+ <td rowspan="3" style="border: 1px solid black; padding: 8px; text-align: left; width: 1.3cm;">Text comprehension</td>
119
+ <td style="border: 1px solid black; padding: 8px; text-align: left;">Reconstruct the meaning of the text, locally or globally</td>
120
+ <td style="border: 1px solid black; padding: 8px; text-align: right;">179 (43.8%)</td>
121
+ </tr>
122
+ <tr>
123
+ <td style="border: 1px solid black; padding: 8px; text-align: left;">Locate and identify information within the text</td>
124
+ <td style="border: 1px solid black; padding: 8px; text-align: right;">108 (26.4%)</td>
125
+ </tr>
126
+ <tr>
127
+ <td style="border: 1px solid black; padding: 8px; text-align: left;">Reflect on the content or form of the text, <br> locally or globally, and evaluate them</td>
128
+ <td style="border: 1px solid black; padding: 8px; text-align: right;">33 (8.1%)</td>
129
+ </tr>
130
+ <tr>
131
+ <td rowspan="6" style="border: 1px solid black; padding: 8px; text-align: left; width: 1.3cm;">Reflection on the language</td>
132
+ <td style="border: 1px solid black; padding: 8px; text-align: left;">Lexicon and semantics</td>
133
+ <td style="border: 1px solid black; padding: 8px; text-align: right;">29 (7.1%)</td>
134
+ </tr>
135
+ <tr>
136
+ <td style="border: 1px solid black; padding: 8px; text-align: left;">Morphology</td>
137
+ <td style="border: 1px solid black; padding: 8px; text-align: right;">24 (5.9%)</td>
138
+ </tr>
139
+ <tr>
140
+ <td style="border: 1px solid black; padding: 8px; text-align: left;">Syntax</td>
141
+ <td style="border: 1px solid black; padding: 8px; text-align: right;">19 (4.6%)</td>
142
+ </tr>
143
+ <tr>
144
+ <td style="border: 1px solid black; padding: 8px; text-align: left;">Word formation</td>
145
+ <td style="border: 1px solid black; padding: 8px; text-align: right;">7 (1.7%)</td>
146
+ </tr>
147
+ <tr>
148
+ <td style="border: 1px solid black; padding: 8px; text-align: left;">Textuality and pragmatics</td>
149
+ <td style="border: 1px solid black; padding: 8px; text-align: right;">6 (1.5%)</td>
150
+ </tr>
151
+ <tr>
152
+ <td style="border: 1px solid black; padding: 8px; text-align: left;">Spelling</td>
153
+ <td style="border: 1px solid black; padding: 8px; text-align: right;">4 (1.0%)</td>
154
+ </tr>
155
+ </tbody>
156
+ </table>
157
+
158
+ </li>
159
+ <br> <br>
160
+
161
+ <li> The questions come in five distinct formats <br> <br>
162
+ <table style="width: 90%; margin: auto; border-collapse: collapse; font-size: 18px; border: 1px solid black;">
163
+ <caption style="caption-side: top; text-align: center; font-weight: bold;">
164
+ Combined Legend of Question Types and Distribution by Format
165
+ </caption>
166
+ <thead>
167
+ <tr style="background-color: #f2f2f2;">
168
+ <th style="border: 1px solid black; padding: 10px; text-align: center;">Question Type</th>
169
+ <th style="border: 1px solid black; padding: 10px; text-align: center;">Description</th>
170
+ <th style="border: 1px solid black; padding: 10px; text-align: center;"># Questions</th>
171
+ <th style="border: 1px solid black; padding: 10px; text-align: center;"># Items</th>
172
+ </tr>
173
+ </thead>
174
+ <tbody>
175
+ <tr>
176
+ <td style="border: 1px solid black; padding: 10px; text-align: left;"><i>Multiple Choice (MC)</i></td>
177
+ <td style="border: 1px solid black; padding: 10px; text-align: left;">Composed of a question with several answer options, among which only one is correct. The most common question format.</td>
178
+ <td style="border: 1px solid black; padding: 10px; text-align: left;">334 (81.7%)</td>
179
+ <td style="border: 1px solid black; padding: 10px; text-align: left;">340</td>
180
+ </tr>
181
+ <tr>
182
+ <td style="border: 1px solid black; padding: 10px; text-align: left;"><i>Multiple Complex Choice (MCC)</i></td>
183
+ <td style="border: 1px solid black; padding: 10px; text-align: left;">Composed of input questions and multiple items to answer. Requires all items to be correctly answered.</td>
184
+ <td style="border: 1px solid black; padding: 10px; text-align: left;">38 (9.3%)</td>
185
+ <td style="border: 1px solid black; padding: 10px; text-align: left;">228</td>
186
+ </tr>
187
+ <tr>
188
+ <td style="border: 1px solid black; padding: 10px; text-align: left;"><i>Unique Response (RU)</i></td>
189
+ <td style="border: 1px solid black; padding: 10px; text-align: left;">Open-ended questions with only one correct answer, sometimes allowing limited variants.</td>
190
+ <td style="border: 1px solid black; padding: 10px; text-align: left;">33 (8.1%)</td>
191
+ <td style="border: 1px solid black; padding: 10px; text-align: left;">50</td>
192
+ </tr>
193
+ <tr>
194
+ <td style="border: 1px solid black; padding: 10px; text-align: left;"><i>Short Response (RB)</i></td>
195
+ <td style="border: 1px solid black; padding: 10px; text-align: left;">Specific sub-type of RU questions requiring a single identifying word as the answer.</td>
196
+ <td style="border: 1px solid black; padding: 10px; text-align: left;">1 (0.2%)</td>
197
+ <td style="border: 1px solid black; padding: 10px; text-align: left;">1</td>
198
+ </tr>
199
+ <tr>
200
+ <td style="border: 1px solid black; padding: 10px; text-align: left;"><i>Cloze (CL)</i></td>
201
+ <td style="border: 1px solid black; padding: 10px; text-align: left;">Text with missing words to be filled in, can be open-ended or closed-ended.</td>
202
+ <td style="border: 1px solid black; padding: 10px; text-align: left;">3 (0.7%)</td>
203
+ <td style="border: 1px solid black; padding: 10px; text-align: left;">6</td>
204
+ </tr>
205
+ </tbody>
206
+ </table>
207
+ </il>
208
+
209
+ </ul>
210
+
211
+
212
+ """
213
+
214
+ EVALUATION_QUEUE_TEXT = """
215
+ ## Evaluation Form
216
+
217
+ Please submit your model for evaluation by filling out the form located [here](https://forms.gle/tkbJME4SS9LF8XTK7).
218
+
219
+ ## Some good practices before submitting a model
220
+
221
+ ### 1) Make sure you can load your model and tokenizer using AutoClasses:
222
+ ```python
223
+ from transformers import AutoConfig, AutoModel, AutoTokenizer
224
+ config = AutoConfig.from_pretrained("your model name", revision=revision)
225
+ model = AutoModel.from_pretrained("your model name", revision=revision)
226
+ tokenizer = AutoTokenizer.from_pretrained("your model name", revision=revision)
227
+ ```
228
+ If this step fails, follow the error messages to debug your model before submitting it. It's likely your model has been improperly uploaded.
229
+
230
+ Note: make sure your model is public!
231
+ 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!
232
+
233
+ ### 2) Convert your model weights to [safetensors](https://huggingface.co/docs/safetensors/index)
234
+ 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`!
235
+
236
+ ### 3) Make sure your model has an open license!
237
+ This is a leaderboard for Open LLMs, and we'd love for as many people as possible to know they can use your model 🤗
238
+ """
239
+
240
+ CITATION_BUTTON_LABEL = "Copy the following snippet to cite these results"
241
+ CITATION_BUTTON_TEXT = r"""
242
+ """
src/display/css_html_js.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ custom_css = """
2
+
3
+ .markdown-text {
4
+ font-size: 18px !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
+ table td:first-child,
43
+ table th:first-child {
44
+ max-width: 400px;
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 ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
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
+
24
+
25
+ # Leaderboard columns
26
+ auto_eval_column_dict = []
27
+ # Init
28
+ auto_eval_column_dict.append(["model_type_symbol", ColumnContent, ColumnContent(
29
+ "T", "str", False, never_hidden=True)])
30
+ auto_eval_column_dict.append(["model", ColumnContent, ColumnContent(
31
+ "Model", "markdown", False, never_hidden=True)])
32
+ auto_eval_column_dict.append(
33
+ ["params", ColumnContent, ColumnContent("Model Size", "str", False, False)])
34
+ # Scores
35
+ # auto_eval_column_dict.append(["average", ColumnContent, ColumnContent("Average ⬆️", "number", True)])
36
+ for task in Tasks:
37
+ auto_eval_column_dict.append(
38
+ [task.name, ColumnContent, ColumnContent(task.value.col_name, "number", True)])
39
+ # Model information
40
+ auto_eval_column_dict.append(
41
+ ["model_type", ColumnContent, ColumnContent("Type", "str", False, True)])
42
+ auto_eval_column_dict.append(
43
+ ["architecture", ColumnContent, ColumnContent("Architecture", "str", False, True)])
44
+ auto_eval_column_dict.append(
45
+ ["weight_type", ColumnContent, ColumnContent("Weight type", "str", False, True)])
46
+ auto_eval_column_dict.append(
47
+ ["precision", ColumnContent, ColumnContent("Precision", "str", False, True)])
48
+ auto_eval_column_dict.append(
49
+ ["license", ColumnContent, ColumnContent("Hub License", "str", False, True)])
50
+ auto_eval_column_dict.append(
51
+ ["likes", ColumnContent, ColumnContent("Hub ❤️", "number", False, True)])
52
+ auto_eval_column_dict.append(["still_on_hub", ColumnContent, ColumnContent(
53
+ "Available on the hub", "bool", False, True)])
54
+ auto_eval_column_dict.append(
55
+ ["revision", ColumnContent, ColumnContent("Model sha", "str", False, True)])
56
+
57
+ # We use make dataclass to dynamically fill the scores from Tasks
58
+ AutoEvalColumn = make_dataclass(
59
+ "AutoEvalColumn", auto_eval_column_dict, frozen=True)
60
+
61
+ # For the queue columns in the submission tab
62
+
63
+
64
+ @dataclass(frozen=True)
65
+ class EvalQueueColumn: # Queue column
66
+ model = ColumnContent("model", "markdown", True)
67
+ revision = ColumnContent("revision", "str", True)
68
+ private = ColumnContent("private", "bool", True)
69
+ precision = ColumnContent("precision", "str", True)
70
+ weight_type = ColumnContent("weight_type", "str", "Original")
71
+ status = ColumnContent("status", "str", True)
72
+
73
+ # All the model information that we might need
74
+
75
+
76
+ @dataclass
77
+ class ModelDetails:
78
+ name: str
79
+ display_name: str = ""
80
+ symbol: str = "" # emoji
81
+
82
+
83
+ class ModelType(Enum):
84
+ open = ModelDetails(name="Open", symbol="🟢")
85
+ # FT = ModelDetails(name="fine-tuned", symbol="🔶")
86
+ close = ModelDetails(name="Closed", symbol="⭕")
87
+ # RL = ModelDetails(name="RL-tuned", symbol="🟦")
88
+ Unknown = ModelDetails(name="", symbol="?")
89
+
90
+ def to_str(self, separator=" "):
91
+ return f"{self.value.symbol}{separator}{self.value.name}"
92
+
93
+ @staticmethod
94
+ def from_str(type):
95
+ # if "fine-tuned" in type or "🔶" in type:
96
+ # return ModelType.FT
97
+ if "Open" in type or "🟢" in type:
98
+ return ModelType.open
99
+ # if "RL-tuned" in type or "🟦" in type:
100
+ # return ModelType.RL
101
+ if "Closed" in type or "⭕" in type:
102
+ return ModelType.close
103
+ return ModelType.Unknown
104
+
105
+
106
+ class WeightType(Enum):
107
+ Adapter = ModelDetails("Adapter")
108
+ Original = ModelDetails("Original")
109
+ Delta = ModelDetails("Delta")
110
+
111
+
112
+ class Precision(Enum):
113
+ float16 = ModelDetails("float16")
114
+ bfloat16 = ModelDetails("bfloat16")
115
+ float32 = ModelDetails("float32")
116
+ # qt_8bit = ModelDetails("8bit")
117
+ # qt_4bit = ModelDetails("4bit")
118
+ # qt_GPTQ = ModelDetails("GPTQ")
119
+ Unknown = ModelDetails("?")
120
+
121
+ def from_str(precision):
122
+ if precision in ["torch.float16", "float16"]:
123
+ return Precision.float16
124
+ if precision in ["torch.bfloat16", "bfloat16"]:
125
+ return Precision.bfloat16
126
+ if precision in ["float32"]:
127
+ return Precision.float32
128
+ # if precision in ["8bit"]:
129
+ # return Precision.qt_8bit
130
+ # if precision in ["4bit"]:
131
+ # return Precision.qt_4bit
132
+ # if precision in ["GPTQ", "None"]:
133
+ # return Precision.qt_GPTQ
134
+ return Precision.Unknown
135
+
136
+
137
+ # Column selection
138
+ COLS = [c.name for c in fields(AutoEvalColumn) if not c.hidden]
139
+ TYPES = [c.type for c in fields(AutoEvalColumn) if not c.hidden]
140
+ COLS_LITE = [c.name for c in fields(
141
+ AutoEvalColumn) if c.displayed_by_default and not c.hidden]
142
+ TYPES_LITE = [c.type for c in fields(
143
+ AutoEvalColumn) if c.displayed_by_default and not c.hidden]
144
+
145
+ EVAL_COLS = [c.name for c in fields(EvalQueueColumn)]
146
+ EVAL_TYPES = [c.type for c in fields(EvalQueueColumn)]
147
+
148
+ BENCHMARK_COLS = [t.value.col_name for t in Tasks]
149
+
150
+ NUMERIC_INTERVALS = {
151
+ "?": pd.Interval(-1, 0, closed="right"),
152
+ "~1.5": pd.Interval(0, 2, closed="right"),
153
+ "~3": pd.Interval(2, 4, closed="right"),
154
+ "~7": pd.Interval(4, 9, closed="right"),
155
+ "~13": pd.Interval(9, 20, closed="right"),
156
+ "~35": pd.Interval(20, 45, closed="right"),
157
+ "~60": pd.Interval(45, 70, closed="right"),
158
+ "70+": pd.Interval(70, 10000, closed="right"),
159
+ }
160
+
161
+ SIZE_INTERVALS = [
162
+ 'Small',
163
+ 'Medium',
164
+ 'Large',
165
+ ]
src/envs.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ from huggingface_hub import HfApi
4
+
5
+ # Info to change for your repository
6
+ # ----------------------------------
7
+ TOKEN = os.environ.get("autoBenchInvalsi") # A read/write token for your org
8
+
9
+ OWNER = "Crisp-Unimib" # 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 ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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(
48
+ "model_name", config.get("model_args", None))
49
+ org_and_model = org_and_model.split("/", 1)
50
+
51
+ if len(org_and_model) == 1:
52
+ org = None
53
+ model = org_and_model[0]
54
+ result_key = f"{model}_{precision.value.name}"
55
+ else:
56
+ org = org_and_model[0]
57
+ model = org_and_model[1]
58
+ result_key = f"{org}_{model}_{precision.value.name}"
59
+ full_model = "/".join(org_and_model)
60
+
61
+ still_on_hub, _, model_config = is_model_on_hub(
62
+ full_model, config.get("model_sha", "main"), trust_remote_code=True, test_tokenizer=False
63
+ )
64
+ architecture = "?"
65
+ if model_config is not None:
66
+ architectures = getattr(model_config, "architectures", None)
67
+ if architectures:
68
+ architecture = ";".join(architectures)
69
+
70
+ # Extract results available in this file (some results are split in several files)
71
+ results = {}
72
+ for task in Tasks:
73
+ task = task.value
74
+
75
+ # We average all scores of a given metric (not all metrics are present in all files)
76
+ accs = np.array([v.get(task.metric, None)
77
+ for k, v in data["results"].items() if task.benchmark == k])
78
+ if accs.size == 0 or any([acc is None for acc in accs]):
79
+ continue
80
+
81
+ mean_acc = np.mean(accs) * 100.0
82
+ results[task.benchmark] = mean_acc
83
+
84
+ return self(
85
+ eval_name=result_key,
86
+ full_model=full_model,
87
+ org=org,
88
+ model=model,
89
+ results=results,
90
+ precision=precision,
91
+ revision=config.get("model_sha", ""),
92
+ still_on_hub=still_on_hub,
93
+ architecture=architecture
94
+ )
95
+
96
+ def update_with_request_file(self, requests_path):
97
+ """Finds the relevant request file for the current model and updates info with it"""
98
+ request_file = get_request_file_for_model(
99
+ requests_path, self.full_model, self.precision.value.name)
100
+
101
+ try:
102
+ with open(request_file, "r") as f:
103
+ request = json.load(f)
104
+ self.model_type = ModelType.from_str(request.get("model_type", ""))
105
+ self.weight_type = WeightType[request.get(
106
+ "weight_type", "Original")]
107
+ self.license = request.get("license", "?")
108
+ self.likes = request.get("likes", 0)
109
+ self.num_params = request.get("params", 0)
110
+ self.date = request.get("submitted_time", "")
111
+ except Exception:
112
+ print(
113
+ f"Could not find request file for {self.org}/{self.model} with precision {self.precision.value.name}")
114
+
115
+ def to_dict(self):
116
+ """Converts the Eval Result to a dict compatible with our dataframe display"""
117
+ # average = sum([v for v in self.results.values() if v is not None]) / len(Tasks)
118
+ data_dict = {
119
+ "eval_name": self.eval_name, # not a column, just a save name,
120
+ AutoEvalColumn.precision.name: self.precision.value.name,
121
+ AutoEvalColumn.model_type.name: self.model_type.value.name,
122
+ AutoEvalColumn.model_type_symbol.name: self.model_type.value.symbol,
123
+ AutoEvalColumn.weight_type.name: self.weight_type.value.name,
124
+ AutoEvalColumn.architecture.name: self.architecture,
125
+ AutoEvalColumn.model.name: make_clickable_model(self.full_model) if self.model_type.value.name == "Open" else self.full_model,
126
+ AutoEvalColumn.revision.name: self.revision,
127
+ # AutoEvalColumn.average.name: average,
128
+ AutoEvalColumn.license.name: self.license,
129
+ AutoEvalColumn.likes.name: self.likes,
130
+ AutoEvalColumn.params.name: self.num_params,
131
+ AutoEvalColumn.still_on_hub.name: self.still_on_hub,
132
+ }
133
+
134
+ for task in Tasks:
135
+ data_dict[task.value.col_name] = self.results[task.value.benchmark]
136
+
137
+ return data_dict
138
+
139
+
140
+ def get_request_file_for_model(requests_path, model_name, precision):
141
+ """Selects the correct request file for a given model. Only keeps runs tagged as FINISHED"""
142
+ request_files = os.path.join(
143
+ requests_path,
144
+ f"{model_name}_eval_request_*.json",
145
+ )
146
+ request_files = glob.glob(request_files)
147
+
148
+ # Select correct request file (precision)
149
+ request_file = ""
150
+ request_files = sorted(request_files, reverse=True)
151
+ for tmp_request_file in request_files:
152
+ with open(tmp_request_file, "r") as f:
153
+ req_content = json.load(f)
154
+ if (
155
+ req_content["status"] in ["FINISHED"]
156
+ # and req_content["precision"] == precision.split(".")[-1]
157
+ ):
158
+ request_file = tmp_request_file
159
+ return request_file
160
+
161
+
162
+ def get_raw_eval_results(results_path: str, requests_path: str) -> list[EvalResult]:
163
+ """From the path of the results folder root, extract all needed info for results"""
164
+ model_result_filepaths = []
165
+
166
+ for root, _, files in os.walk(results_path):
167
+ # We should only have json files in model results
168
+ if len(files) == 0 or any([not f.endswith(".json") for f in files]):
169
+ continue
170
+
171
+ # Sort the files by date
172
+ try:
173
+ files.sort(key=lambda x: x.removesuffix(
174
+ ".json").removeprefix("results_")[:-7])
175
+ except dateutil.parser._parser.ParserError:
176
+ files = [files[-1]]
177
+
178
+ for file in files:
179
+ model_result_filepaths.append(os.path.join(root, file))
180
+
181
+ eval_results = {}
182
+ for model_result_filepath in model_result_filepaths:
183
+ # Creation of result
184
+ eval_result = EvalResult.init_from_json_file(model_result_filepath)
185
+ eval_result.update_with_request_file(requests_path)
186
+
187
+ # Store results of same eval together
188
+ eval_name = eval_result.eval_name
189
+ if eval_name in eval_results.keys():
190
+ eval_results[eval_name].results.update(
191
+ {k: v for k, v in eval_result.results.items() if v is not None})
192
+ else:
193
+ eval_results[eval_name] = eval_result
194
+
195
+ results = []
196
+ for v in eval_results.values():
197
+ try:
198
+ v.to_dict() # we test if the dict version is complete
199
+ results.append(v)
200
+ except KeyError: # not all eval values present
201
+ continue
202
+
203
+ return results
src/logo-crisp-eng-retina.png ADDED
src/populate.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ print(df.columns)
18
+ # df = df.sort_values(by=[AutoEvalColumn.average.name], ascending=False)
19
+ df = df.sort_values(by=["Overall"], ascending=False)
20
+ df = df[cols].round(decimals=2)
21
+
22
+ # filter out if any of the benchmarks have not been produced
23
+ df = df[has_no_nan_values(df, benchmark_cols)]
24
+ return raw_data, df
25
+
26
+
27
+ def get_evaluation_queue_df(save_path: str, cols: list) -> list[pd.DataFrame]:
28
+ """Creates the different dataframes for the evaluation queues requestes"""
29
+ entries = [entry for entry in os.listdir(
30
+ save_path) if not entry.startswith(".")]
31
+ all_evals = []
32
+
33
+ for entry in entries:
34
+ if ".json" in entry:
35
+ file_path = os.path.join(save_path, entry)
36
+ with open(file_path) as fp:
37
+ data = json.load(fp)
38
+
39
+ data[EvalQueueColumn.model.name] = make_clickable_model(
40
+ data["model"])
41
+ data[EvalQueueColumn.revision.name] = data.get("revision", "main")
42
+
43
+ all_evals.append(data)
44
+ elif ".md" not in entry:
45
+ # this is a folder
46
+ sub_entries = [e for e in os.listdir(
47
+ f"{save_path}/{entry}") if not e.startswith(".")]
48
+ for sub_entry in sub_entries:
49
+ file_path = os.path.join(save_path, entry, sub_entry)
50
+ with open(file_path) as fp:
51
+ data = json.load(fp)
52
+
53
+ data[EvalQueueColumn.model.name] = make_clickable_model(
54
+ data["model"])
55
+ data[EvalQueueColumn.revision.name] = data.get(
56
+ "revision", "main")
57
+ all_evals.append(data)
58
+
59
+ pending_list = [e for e in all_evals if e["status"]
60
+ in ["PENDING", "RERUN"]]
61
+ running_list = [e for e in all_evals if e["status"] == "RUNNING"]
62
+ finished_list = [e for e in all_evals if e["status"].startswith(
63
+ "FINISHED") or e["status"] == "PENDING_NEW_EVAL"]
64
+ df_pending = pd.DataFrame.from_records(pending_list, columns=cols)
65
+ df_running = pd.DataFrame.from_records(running_list, columns=cols)
66
+ df_finished = pd.DataFrame.from_records(finished_list, columns=cols)
67
+ return df_finished[cols], df_running[cols], df_pending[cols]
src/submission/check_validity.py ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ )