alielfilali01 commited on
Commit
5233c22
Β·
verified Β·
1 Parent(s): 5b86e0e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +899 -320
app.py CHANGED
@@ -1,346 +1,925 @@
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
- BOTTOM_LOGO,
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
- EVAL_TYPES,
22
- NUMERIC_INTERVALS,
23
- TYPES,
24
- AutoEvalColumn,
25
- ModelType,
26
- fields,
27
- WeightType,
28
- Precision
29
- )
30
- from src.envs import API, EVAL_REQUESTS_PATH, EVAL_RESULTS_PATH, QUEUE_REPO, REPO_ID, RESULTS_REPO, TOKEN
31
- from src.populate import get_evaluation_queue_df, get_leaderboard_df
32
- from src.submission.submit import add_new_eval
33
 
 
 
 
34
 
35
- def restart_space():
36
- API.restart_space(repo_id=REPO_ID)
 
 
37
 
38
- try:
39
- print(EVAL_REQUESTS_PATH)
40
- snapshot_download(
41
- repo_id=QUEUE_REPO, local_dir=EVAL_REQUESTS_PATH, repo_type="dataset", tqdm_class=None, etag_timeout=30, token=TOKEN
42
- )
43
- except Exception:
44
- restart_space()
45
- try:
46
- print(EVAL_RESULTS_PATH)
47
- snapshot_download(
48
- repo_id=RESULTS_REPO, local_dir=EVAL_RESULTS_PATH, repo_type="dataset", tqdm_class=None, etag_timeout=30, token=TOKEN
49
- )
50
- except Exception:
51
- restart_space()
52
-
53
-
54
- raw_data, original_df = get_leaderboard_df(EVAL_RESULTS_PATH, EVAL_REQUESTS_PATH, COLS, BENCHMARK_COLS)
55
- leaderboard_df = original_df.copy()
56
-
57
- (
58
- finished_eval_queue_df,
59
- running_eval_queue_df,
60
- pending_eval_queue_df,
61
- ) = get_evaluation_queue_df(EVAL_REQUESTS_PATH, EVAL_COLS)
62
-
63
-
64
- # Searching and filtering
65
- def update_table(
66
- hidden_df: pd.DataFrame,
67
- columns: list,
68
- type_query: list,
69
- precision_query: str,
70
- size_query: list,
71
- show_deleted: bool,
72
- query: str,
73
- ):
74
- filtered_df = filter_models(hidden_df, type_query, size_query, precision_query, show_deleted)
75
- filtered_df = filter_queries(query, filtered_df)
76
- df = select_columns(filtered_df, columns)
77
- return df
 
 
 
 
 
 
 
 
 
 
78
 
 
79
 
80
- def search_table(df: pd.DataFrame, query: str) -> pd.DataFrame:
81
- return df[(df[AutoEvalColumn.model.name].str.contains(query, case=False))]
82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83
 
84
- def select_columns(df: pd.DataFrame, columns: list) -> pd.DataFrame:
85
- always_here_cols = [
86
- AutoEvalColumn.model_type_symbol.name,
87
- AutoEvalColumn.model.name,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88
  ]
89
- # We use COLS to maintain sorting
90
- filtered_df = df[
91
- always_here_cols + [c for c in COLS if c in df.columns and c in columns]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92
  ]
93
- return filtered_df
94
-
95
-
96
- def filter_queries(query: str, filtered_df: pd.DataFrame) -> pd.DataFrame:
97
- final_df = []
98
- if query != "":
99
- queries = [q.strip() for q in query.split(";")]
100
- for _q in queries:
101
- _q = _q.strip()
102
- if _q != "":
103
- temp_filtered_df = search_table(filtered_df, _q)
104
- if len(temp_filtered_df) > 0:
105
- final_df.append(temp_filtered_df)
106
- if len(final_df) > 0:
107
- filtered_df = pd.concat(final_df)
108
- filtered_df = filtered_df.drop_duplicates(
109
- subset=[AutoEvalColumn.model.name, AutoEvalColumn.precision.name, AutoEvalColumn.revision.name]
110
- )
111
 
112
- return filtered_df
113
-
114
-
115
- def filter_models(
116
- df: pd.DataFrame, type_query: list, size_query: list, precision_query: list, show_deleted: bool
117
- ) -> pd.DataFrame:
118
- # Show all models
119
- if show_deleted:
120
- filtered_df = df
121
- else: # Show only still on the hub models
122
- filtered_df = df[df[AutoEvalColumn.still_on_hub.name] == True]
123
-
124
- type_emoji = [t[0] for t in type_query]
125
- filtered_df = filtered_df.loc[df[AutoEvalColumn.model_type_symbol.name].isin(type_emoji)]
126
- filtered_df = filtered_df.loc[df[AutoEvalColumn.precision.name].isin(precision_query + ["None"])]
127
-
128
- numeric_interval = pd.IntervalIndex(sorted([NUMERIC_INTERVALS[s] for s in size_query]))
129
- params_column = pd.to_numeric(df[AutoEvalColumn.params.name], errors="coerce")
130
- mask = params_column.apply(lambda x: any(numeric_interval.contains(x)))
131
- filtered_df = filtered_df.loc[mask]
132
-
133
- return filtered_df
134
-
135
-
136
- demo = gr.Blocks(css=custom_css)
137
- with demo:
138
- gr.HTML(TITLE)
139
- gr.Markdown(INTRODUCTION_TEXT, elem_classes="markdown-text")
140
-
141
- with gr.Tabs(elem_classes="tab-buttons") as tabs:
142
- with gr.TabItem("πŸ… LLM Leaderboard", elem_id="llm-benchmark-tab-table", id=0):
143
- with gr.Row():
144
- with gr.Column():
145
- with gr.Row():
146
- search_bar = gr.Textbox(
147
- placeholder=" πŸ” Search for your model (separate multiple queries with `;`) and press ENTER...",
148
- show_label=False,
149
- elem_id="search-bar",
150
- )
151
- with gr.Row():
152
- shown_columns = gr.CheckboxGroup(
153
- choices=[
154
- c.name
155
- for c in fields(AutoEvalColumn)
156
- if not c.hidden and not c.never_hidden
157
- ],
158
- value=[
159
- c.name
160
- for c in fields(AutoEvalColumn)
161
- if c.displayed_by_default and not c.hidden and not c.never_hidden
162
- ],
163
- label="Select columns to show",
164
- elem_id="column-select",
165
- interactive=True,
166
- )
167
- with gr.Row():
168
- deleted_models_visibility = gr.Checkbox(
169
- value=False, label="Show gated/private/deleted models", interactive=True
170
- )
171
- with gr.Column(min_width=320):
172
- #with gr.Box(elem_id="box-filter"):
173
- filter_columns_type = gr.CheckboxGroup(
174
- label="Model types",
175
- choices=[t.to_str() for t in ModelType],
176
- value=[t.to_str() for t in ModelType],
177
- interactive=True,
178
- elem_id="filter-columns-type",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
179
  )
180
- filter_columns_precision = gr.CheckboxGroup(
181
- label="Precision",
182
- choices=[i.value.name for i in Precision],
183
- value=[i.value.name for i in Precision],
184
- interactive=True,
185
- elem_id="filter-columns-precision",
186
  )
187
- filter_columns_size = gr.CheckboxGroup(
188
- label="Model sizes (in billions of parameters)",
189
- choices=list(NUMERIC_INTERVALS.keys()),
190
- value=list(NUMERIC_INTERVALS.keys()),
191
- interactive=True,
192
- elem_id="filter-columns-size",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
193
  )
194
 
195
- leaderboard_table = gr.components.Dataframe(
196
- value=leaderboard_df[
197
- [c.name for c in fields(AutoEvalColumn) if c.never_hidden]
198
- + shown_columns.value
199
- ],
200
- headers=[c.name for c in fields(AutoEvalColumn) if c.never_hidden] + shown_columns.value,
201
- datatype=TYPES,
202
- elem_id="leaderboard-table",
203
- interactive=False,
204
- visible=True,
205
- )
206
-
207
- # Dummy leaderboard for handling the case when the user uses backspace key
208
- hidden_leaderboard_table_for_search = gr.components.Dataframe(
209
- value=original_df[COLS],
210
- headers=COLS,
211
- datatype=TYPES,
212
- visible=False,
213
- )
214
- search_bar.submit(
215
- update_table,
216
- [
217
- hidden_leaderboard_table_for_search,
218
- shown_columns,
219
- filter_columns_type,
220
- filter_columns_precision,
221
- filter_columns_size,
222
- deleted_models_visibility,
223
- search_bar,
224
- ],
225
- leaderboard_table,
226
- )
227
- for selector in [shown_columns, filter_columns_type, filter_columns_precision, filter_columns_size, deleted_models_visibility]:
228
- selector.change(
229
- update_table,
230
- [
231
- hidden_leaderboard_table_for_search,
232
- shown_columns,
233
- filter_columns_type,
234
- filter_columns_precision,
235
- filter_columns_size,
236
- deleted_models_visibility,
237
- search_bar,
238
- ],
239
- leaderboard_table,
240
- queue=True,
241
  )
242
 
243
- with gr.TabItem("πŸ“ About", elem_id="llm-benchmark-tab-table", id=2):
244
- gr.Markdown(LLM_BENCHMARKS_TEXT, elem_classes="markdown-text")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
245
 
246
- with gr.TabItem("πŸš€ Submit here! ", 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"βœ… Finished 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
- # with gr.Accordion(
264
- # f"πŸ”„ Running Evaluation Queue ({len(running_eval_queue_df)})",
265
- # open=False,
266
- # ):
267
- # with gr.Row():
268
- # running_eval_table = gr.components.Dataframe(
269
- # value=running_eval_queue_df,
270
- # headers=EVAL_COLS,
271
- # datatype=EVAL_TYPES,
272
- # row_count=5,
273
- # )
274
- with gr.Accordion(
275
- f"⏳ Pending Evaluation Queue ({len(pending_eval_queue_df)})",
276
- open=False,
277
- ):
278
- with gr.Row():
279
- pending_eval_table = gr.components.Dataframe(
280
- value=pending_eval_queue_df,
281
- headers=EVAL_COLS,
282
- datatype=EVAL_TYPES,
283
- row_count=5,
284
- )
285
- with gr.Row():
286
- gr.Markdown("# βœ‰οΈβœ¨ Submit your model here!", elem_classes="markdown-text")
287
-
288
- with gr.Row():
289
- with gr.Column():
290
- model_name_textbox = gr.Textbox(label="Model name")
291
- revision_name_textbox = gr.Textbox(label="Revision commit", placeholder="main")
292
- model_type = gr.Dropdown(
293
- choices=[t.to_str(" : ") for t in ModelType if t != ModelType.Unknown],
294
- label="Model type",
295
- multiselect=False,
296
- value=None,
297
- interactive=True,
298
  )
299
-
300
- with gr.Column():
301
- precision = gr.Dropdown(
302
- choices=[i.value.name for i in Precision if i != Precision.Unknown],
303
- label="Precision",
304
- multiselect=False,
305
- value="float16",
306
- interactive=True,
 
 
 
 
307
  )
308
- weight_type = gr.Dropdown(
309
- choices=[i.value.name for i in WeightType],
310
- label="Weights type",
311
- multiselect=False,
312
  value="Original",
313
- interactive=True,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
314
  )
315
- base_model_name_textbox = gr.Textbox(label="Base model (for delta or adapter weights)")
316
-
317
- submit_button = gr.Button("Submit Eval")
318
- submission_result = gr.Markdown()
319
- submit_button.click(
320
- add_new_eval,
321
- [
322
- model_name_textbox,
323
- base_model_name_textbox,
324
- revision_name_textbox,
325
- precision,
326
- weight_type,
327
- model_type,
328
- ],
329
- submission_result,
330
- )
331
 
332
- with gr.Row():
333
- with gr.Accordion("πŸ“™ Citation", open=False):
334
- citation_button = gr.Textbox(
335
- value=CITATION_BUTTON_TEXT,
336
- label=CITATION_BUTTON_LABEL,
337
- lines=20,
338
- elem_id="citation-button",
339
- show_copy_button=True,
340
- )
341
- gr.HTML(BOTTOM_LOGO)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
342
 
343
- scheduler = BackgroundScheduler()
344
- scheduler.add_job(restart_space, "interval", seconds=1800)
345
- scheduler.start()
346
- demo.queue(default_concurrency_limit=40).launch()
 
1
+ import os
2
+ import json
3
+ import numpy as np
4
  import pandas as pd
5
+ import gradio as gr
6
+ from datetime import datetime, timedelta
7
+ from huggingface_hub.hf_api import ModelInfo
8
+ from transformers import AutoConfig, AutoTokenizer
9
+ from huggingface_hub import HfApi, hf_hub_download, ModelCard
10
  from apscheduler.schedulers.background import BackgroundScheduler
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
 
12
+ ################################################################################
13
+ # GLOBALS & CONSTANTS
14
+ ################################################################################
15
 
16
+ OWNER = "OALL"
17
+ REPO_ID = f"{OWNER}/Open-Arabic-LLM-Leaderboard-v2-exp"
18
+ RESULTS_REPO_ID = f"{OWNER}/v2_results"
19
+ REQUESTS_REPO_ID = f"{OWNER}/requests_v2"
20
 
21
+ # Global HF API instance (set once)
22
+ hf_api_token = os.environ.get('HF_API_TOKEN', None)
23
+ API = HfApi(token=hf_api_token)
24
+
25
+ TASKS = [
26
+ ("community|alghafa:_average|0", "acc_norm", "AlGhafa"),
27
+ ("community|arabic_mmlu:_average|0", "acc_norm", "ArabicMMLU"),
28
+ ("community|arabic_exams|0", "acc_norm", "EXAMS"),
29
+ ("community|madinah_qa:_average|0", "acc_norm", "MadinahQA"),
30
+ ("community|aratrust:_average|0", "acc_norm", "AraTrust"),
31
+ ("community|alrage_qa|0", "llm_as_judge", "ALRAGE"),
32
+ ("community|arabic_mmlu_ht:_average|0", "acc_norm", "ArbMMLU-HT"),
33
+ ]
34
+
35
+ MODEL_TYPE_TO_EMOJI = {
36
+ "🟒 : pretrained": "🟒",
37
+ "🟩 : continuously pretrained": "🟩",
38
+ "πŸ’¬ : chat models (RLHF, DPO, IFT, ...)": "πŸ’¬",
39
+ "πŸ”Ά : fine-tuned on domain-specific datasets": "πŸ”Ά",
40
+ "🀝 : base merges and merges": "🀝",
41
+ "Missing": "?",
42
+ }
43
+
44
+ HEADER = """
45
+ <img src="https://raw.githubusercontent.com/alielfilali01/OALL-assets/main/TITLE.png" style="width:30%;display:block;margin-left:auto;margin-right:auto;border-radius:15px;">
46
+ """
47
+
48
+ BOTTOM_LOGO = """<img src="https://raw.githubusercontent.com/alielfilali01/OALL-assets/main/BOTTOM.png" style="width:50%;display:block;margin-left:auto;margin-right:auto;border-radius:15px;">"""
49
+
50
+ SUBMISSION_TEXT = """
51
+ # Submit Your Model for Evaluation 🌴
52
+
53
+ **The Open Arabic LLM Leaderboard** aims to help you evaluate and compare the performance of Arabic Large Language Models.
54
+
55
+ When you submit a model on this page, it is automatically evaluated on a set of arabic native benchmarks ([find here](https://github.com/huggingface/lighteval/blob/main/examples/tasks/OALL_v2_tasks.txt)) with one additional human-translated version of [MMLU](https://arxiv.org/abs/2009.03300).
56
+
57
+ The GPU used for evaluation is operated with the support of __[Technology Innovation Institute (TII)](https://www.tii.ae/)__.
58
+
59
+ More details about the benchmarks and the evaluation process is provided on the β€œAbout” section below.
60
+ """
61
+
62
+ ABOUT_SECTION = """
63
+ ## About
64
+
65
+ While outstanding LLM models are being released competitively, most of them are centered on English and are familiar with the English cultural sphere. We operate the Open Arabic LLM Leaderboard (OALL), to evaluate models that reflect the characteristics of the Arabic language, culture and heritage. Through this, we hope that users can conveniently use the leaderboard, participate, and contribute to the advancement of research in the Arab region πŸ”₯.
66
+
67
+ ### Icons & Model types
68
+ 🟒 : `pretrained`
69
+
70
+ 🟩 : `continuously pretrained`
71
 
72
+ πŸ’¬ : `chat models (RLHF, DPO, IFT, ...)`
73
 
74
+ πŸ”Ά : `fine-tuned on domain-specific datasets`
 
75
 
76
+ 🀝 : `base merges and moerges`
77
+
78
+ ### Notes:
79
+ - We reserve the right to correct any incorrect tags or icons after manual verification to ensure the accuracy and reliability of the leaderboard. This helps maintain the integrity and trustworthiness of the platform.
80
+ - Some models may be flagged as β€œSubjects of Caution” by the community. These models might have used the evaluation set for training, attempted to manipulate rankings, or raised ethical concerns. Models deemed as such may face restricted visibility or removal from the leaderboard. Users are advised to exercise discretion when interpreting rankings.
81
+ - The leaderboard automatically hides models that were submitted, evaluated, and subsequently made private or gated post-evaluation. This platform is designed for **β€œopen”** models that benefit the wider community. If you intend to restrict your model’s accessibility after using the leaderboard’s resources or exploit the platform solely for personal gains, please refrain from submitting. Violators may face bans on their usernames and/or organization IDs from future submissions.
82
+ - The leaderboard no longer accepts models in **float32** precision except under special circumstances. If you are the developer of a float32 model and believe it deserves inclusion, please reach out to us.
83
+ - To ensure fair and equitable access to leaderboard resources, all usernames and organization IDs are limited to **5 submissions per week**. This policy minimizes spamming, encourages thoughtful participation, and allows everyone in the community to benefit from the platform.
84
+
85
+ By adhering to these guidelines, we aim to foster a fair, collaborative, and transparent environment for evaluating and advancing open models for the arabic/arabic-interested communities.
86
+
87
+ ### How it works
88
+
89
+ πŸ“ˆ We evaluate models using [LightEval](https://github.com/huggingface/lighteval), a unified and straightforward framework from the HuggingFace Eval Team to test and assess causal language models on a large number of different evaluation tasks.
90
+
91
+ To ensure a fair and unbiased assessment of the models' true capabilities, all evaluations are conducted in zero-shot settings `0-shots`. This approach eliminates any potential advantage from task-specific fine-tuning, providing a clear indication of how well the models can generalize to new tasks.
92
+
93
+ Also, given the nature of the tasks, which include multiple-choice questions, the leaderboard primarily uses normalized log likelihood accuracy `loglikelihood_acc_norm` for all tasks.
94
+
95
+ Please, consider reaching out to us through the discussions tab if you are working on benchmarks for Arabic LLMs and willing to see them on this leaderboard as well. Your benchmark might change the whole game for Arabic models !
96
+
97
+ ### Details and Logs
98
+ - Detailed numerical results in the `results` OALL dataset: https://huggingface.co/datasets/OALL/v2_results
99
+ - Community queries and running status in the `requests` OALL dataset: https://huggingface.co/datasets/OALL/requests_v2
100
+
101
+ ### More resources
102
+ If you still have questions, you can check our FAQ [here](https://huggingface.co/spaces/OALL/Open-Arabic-LLM-Leaderboard/discussions/15)!
103
+
104
+ """
105
+
106
+ CITATION_BUTTON_LABEL = """
107
+ Copy the following snippet to cite these results
108
+ """
109
+
110
+ CITATION_BUTTON_TEXT = """
111
+ @misc{OALL-2,
112
+ author = {El Filali, Ali and ALOUI, Manel and Husaain, Tarique and Alzubaidi, Ahmed and Boussaha, Basma El Amel and Cojocaru, Ruxandra and Fourrier, ClΓ©mentine and Habib, Nathan and Hacid, Hakim},
113
+ title = {Open Arabic LLM Leaderboard 2},
114
+ year = {2025},
115
+ publisher = {OALL},
116
+ howpublished = {https://huggingface.co/spaces/OALL/Open-Arabic-LLM-Leaderboard}
117
+ }
118
+ """
119
+
120
+ ################################################################################
121
+ # UTILITY & HELPER FUNCTIONS
122
+ ################################################################################
123
+
124
+ def model_hyperlink(model_name):
125
+ link = f"https://huggingface.co/{model_name}"
126
+ # return f'<a target="_blank" href="{link}" style="color: var(--link-text-color); text-decoration: underline;text-decoration-style: dotted;">{model_name}</a>'
127
+ # return f'[{model_name}]({link})' # WHYYYYYYYY It is not working !!!???
128
+ return f"{model_name}"
129
+
130
+ def restart_space():
131
+ """Restart the Gradio space periodically."""
132
+ API.restart_space(repo_id=REPO_ID)
133
 
134
+ def unify_precision(raw_precision: str) -> str:
135
+ """
136
+ Map raw precision strings (e.g. 'torch.float16', 'fp16', 'float16')
137
+ to canonical forms: 'float16', 'float32', 'bfloat16', '8bit', '4bit', 'Missing'.
138
+ """
139
+ if not raw_precision or raw_precision.lower() in ["missing", "unk", "none"]:
140
+ return "Missing"
141
+ p = raw_precision.lower()
142
+ if p in ["torch.float16", "float16", "fp16"]:
143
+ return "float16"
144
+ if p in ["torch.float32", "float32", "fp32"]:
145
+ return "float32"
146
+ if p in ["torch.bfloat16", "bfloat16", "bf16"]:
147
+ return "bfloat16"
148
+ if p == "8bit":
149
+ return "8bit"
150
+ if p == "4bit":
151
+ return "4bit"
152
+ return "Missing"
153
+
154
+ def load_requests(status_folder: str) -> pd.DataFrame:
155
+ """
156
+ Load all .json requests from REQUESTS_REPO_ID, filtering by 'status' == status_folder.
157
+ """
158
+ df_out = []
159
+ try:
160
+ files_info = API.list_repo_files(
161
+ repo_id=REQUESTS_REPO_ID,
162
+ repo_type="dataset",
163
+ token=hf_api_token
164
+ )
165
+ json_files = [f for f in files_info if f.endswith(".json")]
166
+ except Exception as e:
167
+ print(f"Error listing files in {REQUESTS_REPO_ID}: {e}")
168
+ return pd.DataFrame()
169
+
170
+ for path in json_files:
171
+ try:
172
+ local_path = hf_hub_download(
173
+ repo_id=REQUESTS_REPO_ID,
174
+ filename=path,
175
+ repo_type="dataset",
176
+ token=hf_api_token
177
+ )
178
+ with open(local_path, "r", encoding="utf-8") as f:
179
+ req = json.load(f)
180
+ except Exception as e:
181
+ print(f"Error loading {path}: {e}")
182
+ continue
183
+
184
+ if str(req.get("status", "")).strip().lower() == status_folder.lower():
185
+ df_out.append(req)
186
+
187
+ return pd.DataFrame(df_out)
188
+
189
+ def load_all_requests() -> pd.DataFrame:
190
+ """
191
+ Load *all* requests from the dataset (pending, finished, failed, etc.).
192
+ Returns a single DataFrame with columns from all requests.
193
+ """
194
+ df_out = []
195
+ try:
196
+ files_info = API.list_repo_files(
197
+ repo_id=REQUESTS_REPO_ID,
198
+ repo_type="dataset",
199
+ token=hf_api_token
200
+ )
201
+ json_files = [f for f in files_info if f.endswith(".json")]
202
+ except Exception as e:
203
+ print(f"Error listing files in {REQUESTS_REPO_ID}: {e}")
204
+ return pd.DataFrame()
205
+
206
+ for path in json_files:
207
+ try:
208
+ local_path = hf_hub_download(
209
+ repo_id=REQUESTS_REPO_ID,
210
+ filename=path,
211
+ repo_type="dataset",
212
+ token=hf_api_token
213
+ )
214
+ with open(local_path, "r", encoding="utf-8") as f:
215
+ req = json.load(f)
216
+ df_out.append(req)
217
+ except Exception as e:
218
+ print(f"Error loading {path}: {e}")
219
+ continue
220
+
221
+ return pd.DataFrame(df_out)
222
+
223
+ def already_in_queue(df_pending: pd.DataFrame, model_name: str, revision: str, precision: str) -> bool:
224
+ """
225
+ Check if (model, revision, precision) is already in the 'pending' queue.
226
+ """
227
+ if df_pending.empty:
228
+ return False
229
+ matched = df_pending[
230
+ (df_pending["model"] == model_name)
231
+ & (df_pending["revision"] == revision)
232
+ & (df_pending["precision"] == unify_precision(precision))
233
  ]
234
+ return not matched.empty
235
+
236
+ def get_model_size(model_info: ModelInfo, precision: str) -> float:
237
+ """
238
+ Return approximate model parameter size in billions, if safetensors info is available.
239
+ Return 0 if unknown.
240
+ For GPTQ, we do a small multiplier to reflect the extra bits, etc.
241
+ """
242
+ try:
243
+ param_bytes = model_info.safetensors.get("total", 0)
244
+ model_size = round(param_bytes / 1e9, 3)
245
+ except (AttributeError, TypeError):
246
+ return 0.0
247
+
248
+ if "gptq" in model_info.modelId.lower():
249
+ return model_size * 8
250
+ return model_size
251
+
252
+ def parse_datetime(dt_str: str) -> datetime:
253
+ """
254
+ Safely parse an ISO datetime string into a Python datetime object.
255
+ """
256
+ try:
257
+ return datetime.fromisoformat(dt_str.replace("Z", ""))
258
+ except Exception:
259
+ return datetime.min
260
+
261
+ ################################################################################
262
+ # SCOREBOARD LOADING & DISPLAY
263
+ ################################################################################
264
+
265
+ def load_scoreboard() -> pd.DataFrame:
266
+ """
267
+ 1) Reads JSON "results_*.json" from RESULTS_REPO_ID to collect scores.
268
+ 2) Combines with "finished" requests data for license, revision, etc.
269
+ 3) Removes any model that is no longer public or accessible.
270
+ 4) Returns a DataFrame ready for display & filtering.
271
+
272
+ Only models with finished evaluations are kept.
273
+ """
274
+ # Step A: Get scoreboard files from the results dataset
275
+ try:
276
+ files_info = API.list_repo_files(
277
+ repo_id=RESULTS_REPO_ID,
278
+ repo_type="dataset",
279
+ token=hf_api_token
280
+ )
281
+ except Exception as e:
282
+ print(f"Error listing scoreboard files in {RESULTS_REPO_ID}: {e}")
283
+ return pd.DataFrame()
284
+
285
+ candidate_json_paths = [
286
+ path for path in files_info
287
+ if path.endswith(".json") and len(path.split("/")) == 3 and path.split("/")[2].startswith("results_")
288
  ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
289
 
290
+ rows = []
291
+ # Step B: Read each scoreboard file
292
+ for file_path in candidate_json_paths:
293
+ try:
294
+ local_file = hf_hub_download(
295
+ repo_id=RESULTS_REPO_ID,
296
+ filename=file_path,
297
+ repo_type="dataset",
298
+ token=hf_api_token
299
+ )
300
+ with open(local_file, "r", encoding="utf-8") as f:
301
+ data = json.load(f)
302
+ except Exception as e:
303
+ print(f"Error loading scoreboard file {file_path}: {e}")
304
+ continue
305
+
306
+ config_general = data.get("config_general", {})
307
+ results_block = data.get("results", {})
308
+
309
+ model_name = config_general.get("model_name", "UNK")
310
+ scoreboard_precision = unify_precision(config_general.get("model_dtype", "Missing"))
311
+ # To be consistent with submission logic:
312
+ if scoreboard_precision == "Missing":
313
+ scoreboard_precision = "UNK"
314
+ scoreboard_model_type = config_general.get("model_type", "Missing")
315
+
316
+ row_dict = {
317
+ "Model Name": model_name,
318
+ "Revision": "Missing", # We'll fill from requests
319
+ "License": "Missing", # We'll fill from requests
320
+ "Precision": scoreboard_precision,
321
+ "Full Type": scoreboard_model_type,
322
+ "Model Size": 0.0, # We'll fill from requests
323
+ "Hub ❀️": 0, # We'll fill from requests
324
+ }
325
+
326
+ # Fill tasks
327
+ for (task_key, metric_field, display_name) in TASKS:
328
+ val = np.nan
329
+ if task_key in results_block:
330
+ subd = results_block[task_key]
331
+ if isinstance(subd, dict) and metric_field in subd:
332
+ val = subd[metric_field]
333
+ row_dict[display_name] = val
334
+
335
+ rows.append(row_dict)
336
+
337
+ df = pd.DataFrame(rows)
338
+ if df.empty:
339
+ base_cols = [
340
+ "Model Name","Revision","License",
341
+ "Precision","Full Type","Model Size","Hub ❀️"
342
+ ]
343
+ task_names = [t[2] for t in TASKS]
344
+ return pd.DataFrame(columns=base_cols + task_names)
345
+
346
+ # Step C: Convert tasks to numeric & multiply by 100
347
+ task_cols = [t[2] for t in TASKS if t[2] in df.columns]
348
+ df[task_cols] = df[task_cols].apply(pd.to_numeric, errors="coerce")
349
+ for c in task_cols:
350
+ df[c] = (df[c] * 100).round(2)
351
+
352
+ # Step D: Compute average
353
+ if task_cols:
354
+ df["Average ⬆️"] = df[task_cols].mean(axis=1).round(2)
355
+ else:
356
+ df["Average ⬆️"] = np.nan
357
+
358
+ # Step E: Overwrite scoreboard data with "finished" requests (except for Precision)
359
+ df_finished = load_requests("finished")
360
+ if not df_finished.empty:
361
+ df_finished["precision"] = df_finished["precision"].apply(unify_precision)
362
+ df_finished["license"] = df_finished["license"].apply(
363
+ lambda x: ", ".join(x) if isinstance(x, list) else str(x)
364
+ )
365
+ df_finished["model_type"] = df_finished["model_type"].apply(
366
+ lambda x: ", ".join(x) if isinstance(x, list) else str(x)
367
+ )
368
+
369
+ # Group by model name and precision to correctly distinguish multiple submissions
370
+ dff_grouped = df_finished.groupby(["model", "precision"], as_index=False).last()
371
+
372
+ request_map = {}
373
+ for _, row_ in dff_grouped.iterrows():
374
+ key = f"{row_['model']}__{row_['precision']}"
375
+ request_map[key] = {
376
+ "license": row_["license"],
377
+ "revision": row_["revision"],
378
+ "precision": row_["precision"],
379
+ "model_type":row_["model_type"],
380
+ "params": row_["params"],
381
+ "likes": row_["likes"]
382
+ }
383
+
384
+ def apply_request_info(row_):
385
+ key = f"{row_['Model Name']}__{row_['Precision']}"
386
+ if key in request_map:
387
+ row_["License"] = request_map[key]["license"]
388
+ row_["Revision"] = request_map[key]["revision"]
389
+ # Do NOT update "Precision": keep the value from the results file.
390
+ row_["Full Type"] = request_map[key]["model_type"]
391
+ row_["Model Size"] = request_map[key]["params"]
392
+ row_["Hub ❀️"] = request_map[key]["likes"]
393
+ return row_
394
+
395
+ df = df.apply(apply_request_info, axis=1)
396
+
397
+ # Step E2: Remove rows that do not have finished request info (i.e. Revision is still "Missing")
398
+ df = df[df["Revision"] != "Missing"]
399
+
400
+ # Step F: Remove any model not public
401
+ remove_idx = []
402
+ for idx, row in df.iterrows():
403
+ model_name = row["Model Name"]
404
+ if model_name == "UNK":
405
+ remove_idx.append(idx)
406
+ continue
407
+ try:
408
+ API.model_info(model_name)
409
+ except Exception:
410
+ remove_idx.append(idx)
411
+ df.drop(remove_idx, inplace=True)
412
+ df.reset_index(drop=True, inplace=True)
413
+
414
+ # Step G: Sort scoreboard
415
+ df = df.sort_values(by="Average ⬆️", ascending=False).reset_index(drop=True)
416
+
417
+ # Step H: Insert ranking & create a "Model Size Filter" for slider usage
418
+ df.insert(0, "Rank", range(1, len(df) + 1))
419
+ df["Model Size Filter"] = df["Model Size"]
420
+
421
+ # Step I: Short label for the model type
422
+ def map_type_to_emoji(full_str):
423
+ if not isinstance(full_str, str):
424
+ return "Missing"
425
+ return MODEL_TYPE_TO_EMOJI.get(full_str.strip(), full_str.strip())
426
+ df["T"] = df["Full Type"].apply(map_type_to_emoji)
427
+
428
+ # At this point, convert "Model Name" to a clickable link
429
+ df["Model Name"] = df["Model Name"].apply(model_hyperlink)
430
+
431
+ # Reorder columns
432
+ final_cols = ["Rank", "T", "Model Name", "Average ⬆️"] + task_cols
433
+ remainder = ["Model Size", "Hub ❀️", "License", "Precision", "Revision", "Model Size Filter", "Full Type"]
434
+ for rc in remainder:
435
+ if rc not in final_cols and rc in df.columns:
436
+ final_cols.append(rc)
437
+
438
+ return df[final_cols]
439
+
440
+ ################################################################################
441
+ # SUBMISSION LOGIC
442
+ ################################################################################
443
+
444
+ def check_model_card(repo_id: str) -> (bool, str):
445
+ """Check if model card is present, has a license, and is not too short."""
446
+ try:
447
+ card = ModelCard.load(repo_id)
448
+ except Exception:
449
+ return (False, "No model card found. Please add a README.md describing your model and license.")
450
+ if card.data.license is None and not ("license_name" in card.data and "license_link" in card.data):
451
+ return (False, "No license metadata found in the model card.")
452
+ if len(card.text) < 200:
453
+ return (False, "Model card is too short (<200 chars). Please add more details.")
454
+ return (True, "")
455
+
456
+ def is_model_on_hub(model_name, revision, token=None, trust_remote_code=False, test_tokenizer=True):
457
+ """Check if the model & tokenizer can be loaded from the Hub."""
458
+ try:
459
+ config = AutoConfig.from_pretrained(
460
+ model_name,
461
+ revision=revision,
462
+ trust_remote_code=trust_remote_code,
463
+ token=token
464
+ )
465
+ except ValueError:
466
+ return (False, "requires `trust_remote_code=True`. Not automatically allowed.", None)
467
+ except Exception as e:
468
+ return (False, f"not loadable from hub: {str(e)}", None)
469
+
470
+ if test_tokenizer:
471
+ try:
472
+ _ = AutoTokenizer.from_pretrained(
473
+ model_name,
474
+ revision=revision,
475
+ trust_remote_code=trust_remote_code,
476
+ token=token
477
+ )
478
+ except Exception as e:
479
+ return (False, f"tokenizer not loadable: {str(e)}", None)
480
+
481
+ return (True, "", config)
482
+
483
+ def check_org_threshold(org_name: str) -> (bool, str):
484
+ """
485
+ Each org can only submit 5 models in the last 7 days.
486
+ Return (True, "") if allowed. Otherwise, (False, "error message").
487
+ """
488
+ df_all = load_all_requests()
489
+ if df_all.empty:
490
+ return (True, "")
491
+
492
+ def get_org(m):
493
+ try:
494
+ return m.split("/")[0]
495
+ except:
496
+ return m
497
+
498
+ df_all["org_name"] = df_all["model"].apply(get_org)
499
+ df_org = df_all[df_all["org_name"] == org_name].copy()
500
+ if df_org.empty:
501
+ return (True, "")
502
+
503
+ df_org["datetime"] = df_org["submitted_time"].apply(parse_datetime)
504
+ df_org.dropna(subset=["datetime"], inplace=True)
505
+
506
+ now = datetime.utcnow()
507
+ week_ago = now - timedelta(days=7)
508
+ df_recent = df_org[df_org["datetime"] >= week_ago]
509
+
510
+ if len(df_recent) >= 5:
511
+ df_recent_sorted = df_recent.sort_values(by="datetime")
512
+ earliest = df_recent_sorted.iloc[0]["datetime"]
513
+ next_ok = earliest + timedelta(days=7)
514
+ msg_next = next_ok.isoformat(timespec="seconds") + "Z"
515
+ return (
516
+ False,
517
+ f"Your org '{org_name}' has reached the 5-submissions-per-week limit. You can submit again after {msg_next}."
518
+ )
519
+ return (True, "")
520
+
521
+ def submit_model(
522
+ model_name: str,
523
+ base_model: str,
524
+ revision: str,
525
+ precision: str,
526
+ weight_type: str,
527
+ model_type: str,
528
+ chat_template: str
529
+ ):
530
+ # -------------------------------------------------------------------------
531
+ # 0) Strip inputs to avoid trailing or leading spaces
532
+ # -------------------------------------------------------------------------
533
+ model_name = model_name.strip()
534
+ base_model = base_model.strip()
535
+ revision = revision.strip()
536
+ precision = precision.strip()
537
+
538
+ if not model_name:
539
+ return "**Error**: Model name cannot be empty (use 'org/model')."
540
+ if not revision:
541
+ revision = "main"
542
+
543
+ # 1) Check model card
544
+ card_ok, card_msg = check_model_card(model_name)
545
+ if not card_ok:
546
+ return f"**Error**: {card_msg}"
547
+
548
+ # 2) If adapter/delta, check base_model
549
+ if weight_type.lower() in ["adapter", "delta"]:
550
+ if not base_model:
551
+ return "**Error**: For adapter/delta, you must provide a valid `base_model`."
552
+ ok_base, base_err, _ = is_model_on_hub(base_model, revision, hf_api_token, test_tokenizer=True)
553
+ if not ok_base:
554
+ return f"**Error**: Base model '{base_model}' {base_err}"
555
+ else:
556
+ ok_model, model_err, _ = is_model_on_hub(model_name, revision, hf_api_token, test_tokenizer=True)
557
+ if not ok_model:
558
+ return f"**Error**: Model '{model_name}' {model_err}"
559
+
560
+ # 3) Retrieve ModelInfo
561
+ try:
562
+ info = API.model_info(model_name, revision=revision, token=hf_api_token)
563
+ except Exception as e:
564
+ return f"**Error**: Could not fetch model info. {str(e)}"
565
+
566
+ model_license = info.card_data.license
567
+ model_likes = info.likes or 0
568
+ model_private = bool(getattr(info, "private", False))
569
+
570
+ # 4) Check duplicates
571
+ df_pending = load_requests("pending")
572
+ df_finished = load_requests("finished")
573
+
574
+ if already_in_queue(df_finished, model_name, revision, precision):
575
+ return f"**Warning**: '{model_name}' with (rev='{revision}', prec='{precision}') has already been evaluated (status FINISHED)."
576
+ elif already_in_queue(df_pending, model_name, revision, precision):
577
+ return f"**Warning**: '{model_name}' with (rev='{revision}', prec='{precision}') is already in PENDING."
578
+
579
+ # 5) Check threshold
580
+ try:
581
+ org = model_name.split("/")[0]
582
+ except:
583
+ org = model_name
584
+ under_threshold, message = check_org_threshold(org)
585
+ if not under_threshold:
586
+ return f"**Error**: {message}"
587
+
588
+ precision_final = unify_precision(precision)
589
+ if precision_final == "Missing":
590
+ precision_final = "UNK"
591
+
592
+ model_params = get_model_size(model_info=info, precision=precision)
593
+ current_time = datetime.utcnow().isoformat() + "Z"
594
+ # Convert chat_template input to boolean: True if "Yes", False if "No"
595
+ chat_template_bool = True if chat_template.strip().lower() == "yes" else False
596
+
597
+ submission = {
598
+ "model": model_name,
599
+ "base_model": base_model.strip(),
600
+ "revision": revision,
601
+ "precision": precision_final,
602
+ "weight_type": weight_type,
603
+ "status": "PENDING",
604
+ "submitted_time": current_time,
605
+ "model_type": model_type,
606
+ "likes": model_likes,
607
+ "params": model_params,
608
+ "license": model_license,
609
+ "private": model_private,
610
+ "job_id": None,
611
+ "job_start_time": None,
612
+ "chat_template": chat_template_bool
613
+ }
614
+
615
+ # Must be "org/repo"
616
+ try:
617
+ org_, repo_id = model_name.split("/")
618
+ except ValueError:
619
+ return "**Error**: Please specify model as 'org/model'. Note that `org` can be `username` as well."
620
+
621
+ private_str = "True" if model_private else "False"
622
+ file_path_in_repo = f"{org_}/{repo_id}_eval_request_{private_str}_{precision_final}_{weight_type}.json"
623
+
624
+ # 6) Upload submission
625
+ try:
626
+ API.upload_file(
627
+ path_or_fileobj=json.dumps(submission, indent=2).encode("utf-8"),
628
+ path_in_repo=file_path_in_repo,
629
+ repo_id=REQUESTS_REPO_ID,
630
+ repo_type="dataset",
631
+ token=hf_api_token,
632
+ commit_message=f"Add {model_name} to eval queue"
633
+ )
634
+ except Exception as e:
635
+ return f"**Error**: Could not upload to '{REQUESTS_REPO_ID}': {str(e)}"
636
+
637
+ return f"**Success**: Model '{model_name}' submitted for evaluation!"
638
+
639
+ ################################################################################
640
+ # MAIN GRADIO APP
641
+ ################################################################################
642
+
643
+ def main():
644
+ # Periodically restart the Space (e.g., every 30 minutes)
645
+ scheduler = BackgroundScheduler()
646
+ scheduler.add_job(restart_space, "interval", hours=1)
647
+ scheduler.start()
648
+
649
+ df_tasks = load_scoreboard()
650
+
651
+ # Prepare filter choices from 'finished' requests
652
+ df_finished = load_requests("finished")
653
+ if not df_finished.empty:
654
+ df_finished["precision"] = df_finished["precision"].apply(unify_precision)
655
+ df_finished["license"] = df_finished["license"].apply(
656
+ lambda x: ", ".join(x) if isinstance(x, list) else str(x)
657
+ )
658
+ df_finished["model_type"] = df_finished["model_type"].apply(
659
+ lambda x: ", ".join(x) if isinstance(x, list) else str(x)
660
+ )
661
+
662
+ precision_options = sorted(df_finished["precision"].dropna().unique().tolist())
663
+ license_options = sorted(df_finished["license"].dropna().unique().tolist())
664
+ model_type_opts = sorted(df_finished["model_type"].dropna().unique().tolist())
665
+
666
+ for lst in [precision_options, license_options, model_type_opts]:
667
+ if "Missing" not in lst:
668
+ lst.append("Missing")
669
+ else:
670
+ precision_options = ["float16", "bfloat16", "8bit", "4bit", "Missing"]
671
+ license_options = ["Missing"]
672
+ model_type_opts = ["Missing"]
673
+
674
+ if not df_tasks.empty:
675
+ min_model_size = int(df_tasks["Model Size Filter"].min())
676
+ max_model_size = int(df_tasks["Model Size Filter"].max())
677
+ else:
678
+ min_model_size, max_model_size = 0, 1000
679
+
680
+ all_columns = df_tasks.columns.tolist() if not df_tasks.empty else []
681
+ # We don't want to show "Model Size Filter" or "Full Type" directly
682
+ hidden_cols = {"Model Size Filter", "Full Type"}
683
+ for h in hidden_cols:
684
+ if h in all_columns:
685
+ all_columns.remove(h)
686
+
687
+ task_cols = [t[2] for t in TASKS if t[2] in df_tasks.columns]
688
+ default_cols = ["Rank", "T", "Model Name", "Average ⬆️"] + task_cols
689
+ default_cols = [c for c in default_cols if c in all_columns]
690
+
691
+ with gr.Blocks() as demo:
692
+ gr.HTML(HEADER)
693
+ with gr.Tabs():
694
+ ####################################################################
695
+ # TAB 1: LLM Leaderboard
696
+ ####################################################################
697
+ with gr.Tab("πŸ… LLM Leaderboard"):
698
+ with gr.Row():
699
+ search_box = gr.Textbox(
700
+ label="Search",
701
+ placeholder="Search for models...",
702
+ interactive=True
703
  )
704
+ with gr.Row():
705
+ col_selector = gr.CheckboxGroup(
706
+ choices=all_columns,
707
+ value=default_cols,
708
+ label="Select columns to display"
 
709
  )
710
+ t_filter = gr.CheckboxGroup(
711
+ choices=model_type_opts,
712
+ value=model_type_opts.copy(),
713
+ label="Filter by Model Type"
714
+ )
715
+ with gr.Row():
716
+ license_filter = gr.CheckboxGroup(
717
+ choices=license_options,
718
+ value=license_options.copy(),
719
+ label="Filter by License"
720
+ )
721
+ precision_filter = gr.CheckboxGroup(
722
+ choices=precision_options,
723
+ value=precision_options.copy(),
724
+ label="Filter by Precision"
725
+ )
726
+ with gr.Row():
727
+ size_min_slider = gr.Slider(
728
+ minimum=min_model_size,
729
+ maximum=max_model_size,
730
+ value=min_model_size,
731
+ step=1,
732
+ label="Minimum Model Size (params)",
733
+ interactive=True
734
+ )
735
+ size_max_slider = gr.Slider(
736
+ minimum=min_model_size,
737
+ maximum=max_model_size,
738
+ value=max_model_size,
739
+ step=1,
740
+ label="Maximum Model Size (params)",
741
+ interactive=True
742
  )
743
 
744
+ leaderboard = gr.Dataframe(
745
+ value=df_tasks[default_cols] if not df_tasks.empty else pd.DataFrame(columns=default_cols),
746
+ interactive=False
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
747
  )
748
 
749
+ def filter_by_full_type(dff, selected_full_types):
750
+ incl_missing = "Missing" in selected_full_types
751
+ if incl_missing:
752
+ return dff[
753
+ (dff["Full Type"].isin(selected_full_types))
754
+ | (dff["Full Type"].isna())
755
+ | (dff["Full Type"] == "")
756
+ | (dff["Full Type"] == "Missing")
757
+ ]
758
+ else:
759
+ return dff[dff["Full Type"].isin(selected_full_types)]
760
+
761
+ def filter_leaderboard(
762
+ search_query,
763
+ selected_cols,
764
+ t_filter_values,
765
+ lic_filter_values,
766
+ prec_filter_values,
767
+ min_sz,
768
+ max_sz
769
+ ):
770
+ dff = df_tasks.copy()
771
+ # 1) Filter by size
772
+ if min_sz > max_sz:
773
+ min_sz, max_sz = max_sz, min_sz
774
+ dff = dff[(dff["Model Size Filter"] >= min_sz+1) & (dff["Model Size Filter"] <= max_sz+1)]
775
+ # 2) Search by name
776
+ dff["plain_name"] = dff["Model Name"].str.replace(r'<.*?>', '', regex=True)
777
+ if search_query:
778
+ dff = dff[dff["plain_name"].str.contains(search_query, case=False, na=False)]
779
+ # 3) Filter by model type
780
+ if t_filter_values:
781
+ dff = filter_by_full_type(dff, t_filter_values)
782
+ # 4) Filter by license
783
+ if lic_filter_values:
784
+ incl_missing = "Missing" in lic_filter_values
785
+ chosen = [l for l in lic_filter_values if l != "Missing"]
786
+ if incl_missing:
787
+ dff = dff[
788
+ dff["License"].isin(chosen)
789
+ | (dff["License"] == "Missing")
790
+ | (dff["License"].isna())
791
+ ]
792
+ else:
793
+ dff = dff[dff["License"].isin(chosen)]
794
+ # 5) Filter by precision
795
+ if prec_filter_values:
796
+ incl_missing = "Missing" in prec_filter_values
797
+ chosen = [p for p in prec_filter_values if p != "Missing"]
798
+ if incl_missing:
799
+ dff = dff[
800
+ dff["Precision"].isin(chosen)
801
+ | (dff["Precision"].isna())
802
+ | (dff["Precision"] == "Missing")
803
+ | (dff["Precision"] == "UNK")
804
+ ]
805
+ else:
806
+ dff = dff[dff["Precision"].isin(chosen)]
807
+
808
+ dff.drop(columns=["plain_name"], inplace=True, errors="ignore")
809
+ final_cols = [col for col in dff.columns if col in selected_cols]
810
+ return dff[final_cols]
811
+
812
+ filter_inputs = [
813
+ search_box, col_selector, t_filter,
814
+ license_filter, precision_filter,
815
+ size_min_slider, size_max_slider
816
+ ]
817
+ search_box.submit(filter_leaderboard, inputs=filter_inputs, outputs=leaderboard)
818
+ for comp in filter_inputs:
819
+ comp.change(filter_leaderboard, inputs=filter_inputs, outputs=leaderboard)
820
+
821
+ ####################################################################
822
+ # TAB 2: Submit here
823
+ ####################################################################
824
+ with gr.Tab("πŸš€ Submit here!"):
825
+ gr.Markdown(SUBMISSION_TEXT)
826
 
 
 
827
  with gr.Row():
828
+ model_name_box = gr.Textbox(
829
+ label="Model Name",
830
+ placeholder="myorg/mymodel",
831
+ interactive=True
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
832
  )
833
+ revision_box = gr.Textbox(
834
+ label="Revision Commit",
835
+ placeholder="main",
836
+ value="main",
837
+ interactive=True
838
+ )
839
+ with gr.Row():
840
+ model_type_box = gr.Dropdown(
841
+ label="Model Type",
842
+ choices=list(MODEL_TYPE_TO_EMOJI.keys()),
843
+ value="πŸ’¬ : chat models (RLHF, DPO, IFT, ...)",
844
+ interactive=True
845
  )
846
+ weight_type_box = gr.Dropdown(
847
+ label="Weight Type",
848
+ choices=["Original", "Adapter", "Delta"],
 
849
  value="Original",
850
+ interactive=True
851
+ )
852
+ with gr.Row():
853
+ precision_box = gr.Dropdown(
854
+ label="Precision",
855
+ choices=["float16", "bfloat16", "8bit", "4bit"],
856
+ value="bfloat16",
857
+ interactive=True
858
+ )
859
+ base_model_box = gr.Textbox(
860
+ label="Base Model (if adapter or delta weights)",
861
+ placeholder="(Optional) e.g. myorg/base-model",
862
+ interactive=True
863
+ )
864
+ with gr.Row():
865
+ chat_template_box = gr.Radio(
866
+ label="Evaluate using chat-template?",
867
+ choices=["Yes", "No"],
868
+ value="No",
869
+ interactive=True
870
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
871
 
872
+ submit_btn = gr.Button("Submit Model")
873
+ submit_out = gr.Markdown()
874
+
875
+ submit_btn.click(
876
+ fn=submit_model,
877
+ inputs=[model_name_box, base_model_box, revision_box, precision_box, weight_type_box, model_type_box, chat_template_box],
878
+ outputs=submit_out
879
+ )
880
+
881
+ df_pending = load_requests("pending")
882
+ df_running = load_requests("running")
883
+ df_finished2= load_requests("finished")
884
+ df_failed = load_requests("failed")
885
+
886
+ gr.Markdown("## Evaluation Status")
887
+ with gr.Accordion(f"Pending Evaluations ({len(df_pending)})", open=False):
888
+ if not df_pending.empty:
889
+ gr.Dataframe(df_pending)
890
+ else:
891
+ gr.Markdown("No pending evaluations.")
892
+ with gr.Accordion(f"Running Evaluations ({len(df_running)})", open=False):
893
+ if not df_running.empty:
894
+ gr.Dataframe(df_running)
895
+ else:
896
+ gr.Markdown("No running evaluations.")
897
+ with gr.Accordion(f"Finished Evaluations ({len(df_finished2)})", open=False):
898
+ if not df_finished2.empty:
899
+ gr.Dataframe(df_finished2)
900
+ else:
901
+ gr.Markdown("No finished evaluations.")
902
+ with gr.Accordion(f"Failed Evaluations ({len(df_failed)})", open=False):
903
+ if not df_failed.empty:
904
+ gr.Dataframe(df_failed)
905
+ else:
906
+ gr.Markdown("No failed evaluations.")
907
+
908
+ gr.Markdown(ABOUT_SECTION)
909
+
910
+ with gr.Row():
911
+ with gr.Accordion("πŸ“™ Citation", open=False):
912
+ citation_box = gr.Textbox(
913
+ value=CITATION_BUTTON_TEXT,
914
+ label=CITATION_BUTTON_LABEL,
915
+ lines=20,
916
+ elem_id="citation-button",
917
+ show_copy_button=True
918
+ )
919
+
920
+ gr.HTML(BOTTOM_LOGO)
921
+
922
+ demo.queue(default_concurrency_limit=40).launch()
923
 
924
+ if __name__ == "__main__":
925
+ main()