Mohamed Sana commited on
Commit
80b7c55
·
1 Parent(s): 7a56257

deploy open telecom llm leaderboard

Browse files
.gitattributes CHANGED
@@ -25,7 +25,6 @@
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
- *.tar filter=lfs diff=lfs merge=lfs -text
29
  *.tflite filter=lfs diff=lfs merge=lfs -text
30
  *.tgz filter=lfs diff=lfs merge=lfs -text
31
  *.wasm filter=lfs diff=lfs merge=lfs -text
@@ -33,3 +32,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* 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
 
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 CHANGED
@@ -1,12 +1,54 @@
1
  ---
2
- title: Open Telecom Llm Leaderboard
3
- emoji: 🚀
4
- colorFrom: yellow
5
- colorTo: yellow
6
  sdk: gradio
7
- sdk_version: 5.1.0
8
  app_file: app.py
9
- pinned: false
 
 
 
 
 
 
 
 
 
 
10
  ---
11
 
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: Open Telecom LLM Leaderboard
3
+ emoji: 🏆
4
+ colorFrom: green
5
+ colorTo: indigo
6
  sdk: gradio
7
+ sdk_version: 4.36.0
8
  app_file: app.py
9
+ pinned: true
10
+ license: apache-2.0
11
+ fullWidth: true
12
+ startup_duration_timeout: 1h
13
+ space_ci:
14
+ private: true
15
+ secrets:
16
+ - HF_TOKEN
17
+ tags:
18
+ - leaderboard
19
+ short_description: Track, rank and evaluate open Arabic LLMs and chatbots
20
  ---
21
 
22
+ # Start the configuration
23
+
24
+ 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).
25
+
26
+ Results files should have the following format and be stored as json files:
27
+ ```json
28
+ {
29
+ "config": {
30
+ "model_dtype": "torch.float16", # or torch.bfloat16 or 8bit or 4bit
31
+ "model_name": "path of the model on the hub: org/model",
32
+ "model_sha": "revision on the hub",
33
+ },
34
+ "results": {
35
+ "task_name": {
36
+ "metric_name": score,
37
+ },
38
+ "task_name2": {
39
+ "metric_name": score,
40
+ }
41
+ }
42
+ }
43
+ ```
44
+
45
+ Request files are created automatically by this tool.
46
+
47
+ 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.
48
+
49
+ # Code logic for more complex edits
50
+
51
+ You'll find
52
+ - the main table' columns names and properties in `src/display/utils.py`
53
+ - 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`
54
+ - the logic to allow or filter submissions in `src/submission/submit.py` and `src/submission/check_validity.py`
app.py ADDED
@@ -0,0 +1,353 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import pandas as pd
3
+ from apscheduler.schedulers.background import BackgroundScheduler
4
+ from huggingface_hub import snapshot_download
5
+ import os
6
+
7
+ os.environ['CURL_CA_BUNDLE'] = ''
8
+ os.environ['REQUESTS_CA_BUNDLE'] = ''
9
+
10
+
11
+ from src.about import (
12
+ CITATION_BUTTON_LABEL,
13
+ CITATION_BUTTON_TEXT,
14
+ EVALUATION_QUEUE_TEXT,
15
+ INTRODUCTION_TEXT,
16
+ LLM_BENCHMARKS_TEXT,
17
+ TITLE,
18
+ BOTTOM_LOGO,
19
+ )
20
+ from src.display.css_html_js import custom_css
21
+ from src.display.utils import (
22
+ BENCHMARK_COLS,
23
+ COLS,
24
+ EVAL_COLS,
25
+ EVAL_TYPES,
26
+ NUMERIC_INTERVALS,
27
+ TYPES,
28
+ AutoEvalColumn,
29
+ ModelType,
30
+ fields,
31
+ WeightType,
32
+ Precision
33
+ )
34
+ from src.envs import API, EVAL_REQUESTS_PATH, EVAL_RESULTS_PATH, QUEUE_REPO, REPO_ID, RESULTS_REPO, TOKEN
35
+ from src.populate import get_evaluation_queue_df, get_leaderboard_df
36
+ from src.submission.submit import add_new_eval
37
+
38
+
39
+ def restart_space():
40
+ API.restart_space(repo_id=REPO_ID)
41
+ pass
42
+
43
+ try:
44
+ print(EVAL_REQUESTS_PATH)
45
+ snapshot_download(
46
+ repo_id=QUEUE_REPO, local_dir=EVAL_REQUESTS_PATH, repo_type="dataset", tqdm_class=None, etag_timeout=30, token=TOKEN
47
+ )
48
+ except Exception:
49
+ restart_space()
50
+ try:
51
+ print(EVAL_RESULTS_PATH)
52
+ snapshot_download(
53
+ repo_id=RESULTS_REPO, local_dir=EVAL_RESULTS_PATH, repo_type="dataset", tqdm_class=None, etag_timeout=30, token=TOKEN
54
+ )
55
+ except Exception:
56
+ restart_space()
57
+
58
+
59
+ raw_data, original_df = get_leaderboard_df(EVAL_RESULTS_PATH, EVAL_REQUESTS_PATH, COLS, BENCHMARK_COLS)
60
+ leaderboard_df = original_df.copy()
61
+
62
+ (
63
+ finished_eval_queue_df,
64
+ running_eval_queue_df,
65
+ pending_eval_queue_df,
66
+ ) = get_evaluation_queue_df(EVAL_REQUESTS_PATH, EVAL_COLS)
67
+
68
+
69
+ # Searching and filtering
70
+ def update_table(
71
+ hidden_df: pd.DataFrame,
72
+ columns: list,
73
+ type_query: list,
74
+ precision_query: str,
75
+ size_query: list,
76
+ show_all: bool,
77
+ query: str,
78
+ ):
79
+ filtered_df = filter_models(hidden_df, type_query, size_query, precision_query, show_all)
80
+ filtered_df = filter_queries(query, filtered_df)
81
+ df = select_columns(filtered_df, columns)
82
+
83
+ # pdb.set_trace()
84
+ return df
85
+
86
+
87
+ def search_table(df: pd.DataFrame, query: str) -> pd.DataFrame:
88
+ return df[(df[AutoEvalColumn.model.name].str.contains(query, case=False))]
89
+
90
+
91
+ def select_columns(df: pd.DataFrame, columns: list) -> pd.DataFrame:
92
+ always_here_cols = [
93
+ AutoEvalColumn.model_type_symbol.name,
94
+ AutoEvalColumn.model.name,
95
+ ]
96
+ # We use COLS to maintain sorting
97
+ filtered_df = df[
98
+ always_here_cols + [c for c in COLS if c in df.columns and c in columns]
99
+ ]
100
+ return filtered_df
101
+
102
+
103
+ def filter_queries(query: str, filtered_df: pd.DataFrame) -> pd.DataFrame:
104
+ final_df = []
105
+ if query != "":
106
+ queries = [q.strip() for q in query.split(";")]
107
+ for _q in queries:
108
+ _q = _q.strip()
109
+ if _q != "":
110
+ temp_filtered_df = search_table(filtered_df, _q)
111
+ if len(temp_filtered_df) > 0:
112
+ final_df.append(temp_filtered_df)
113
+ if len(final_df) > 0:
114
+ filtered_df = pd.concat(final_df)
115
+ filtered_df = filtered_df.drop_duplicates(
116
+ subset=[AutoEvalColumn.model.name, AutoEvalColumn.precision.name, AutoEvalColumn.revision.name]
117
+ )
118
+
119
+ return filtered_df
120
+
121
+
122
+ def filter_models(
123
+ df: pd.DataFrame, type_query: list, size_query: list, precision_query: list, show_all: bool
124
+ ) -> pd.DataFrame:
125
+ # Show all models
126
+ if show_all:
127
+ filtered_df = df
128
+ else: # Show only still on the hub models
129
+ filtered_df = df[df[AutoEvalColumn.still_on_hub.name] == True]
130
+
131
+ type_emoji = [t[0] for t in type_query]
132
+ filtered_df = filtered_df.loc[df[AutoEvalColumn.model_type_symbol.name].isin(type_emoji)]
133
+ filtered_df = filtered_df.loc[df[AutoEvalColumn.precision.name].isin(precision_query + ["None"])]
134
+
135
+ numeric_interval = pd.IntervalIndex(sorted([NUMERIC_INTERVALS[s] for s in size_query]))
136
+ params_column = pd.to_numeric(df[AutoEvalColumn.params.name], errors="coerce")
137
+ mask = params_column.apply(lambda x: any(numeric_interval.contains(x)))
138
+ filtered_df = filtered_df.loc[mask]
139
+
140
+ return filtered_df
141
+
142
+
143
+ demo = gr.Blocks(css=custom_css)
144
+ with demo:
145
+ gr.HTML(TITLE)
146
+ gr.Markdown(INTRODUCTION_TEXT, elem_classes="markdown-text")
147
+
148
+ with gr.Tabs(elem_classes="tab-buttons") as tabs:
149
+ with gr.TabItem("🏅 LLM Leaderboard", elem_id="llm-benchmark-tab-table", id=0):
150
+ with gr.Row():
151
+ with gr.Column():
152
+ with gr.Row():
153
+ search_bar = gr.Textbox(
154
+ placeholder=" 🔍 Search for your model (separate multiple queries with `;`) and press ENTER...",
155
+ show_label=False,
156
+ elem_id="search-bar",
157
+ )
158
+ with gr.Row():
159
+ shown_columns = gr.CheckboxGroup(
160
+ choices=[
161
+ c.name
162
+ for c in fields(AutoEvalColumn)
163
+ if not c.hidden and not c.never_hidden
164
+ ],
165
+ value=[
166
+ c.name
167
+ for c in fields(AutoEvalColumn)
168
+ if c.displayed_by_default and not c.hidden and not c.never_hidden
169
+ ],
170
+ label="Select columns to show",
171
+ elem_id="column-select",
172
+ interactive=True,
173
+ )
174
+ with gr.Row():
175
+ show_all = gr.Checkbox(
176
+ value=True, label="Show gated/private/deleted models", interactive=True
177
+ )
178
+ with gr.Column(min_width=320):
179
+ #with gr.Box(elem_id="box-filter"):
180
+ filter_columns_type = gr.CheckboxGroup(
181
+ label="Model types",
182
+ choices=[t.to_str() for t in ModelType],
183
+ value=[t.to_str() for t in ModelType],
184
+ interactive=True,
185
+ elem_id="filter-columns-type",
186
+ )
187
+ filter_columns_precision = gr.CheckboxGroup(
188
+ label="Precision",
189
+ choices=[i.value.name for i in Precision],
190
+ value=[i.value.name for i in Precision],
191
+ interactive=True,
192
+ elem_id="filter-columns-precision",
193
+ )
194
+ filter_columns_size = gr.CheckboxGroup(
195
+ label="Model sizes (in billions of parameters)",
196
+ choices=list(NUMERIC_INTERVALS.keys()),
197
+ value=list(NUMERIC_INTERVALS.keys()),
198
+ interactive=True,
199
+ elem_id="filter-columns-size",
200
+ )
201
+
202
+ leaderboard_table = gr.components.Dataframe(
203
+ value=leaderboard_df[
204
+ [c.name for c in fields(AutoEvalColumn) if c.never_hidden]
205
+ + shown_columns.value
206
+ ],
207
+ headers=[c.name for c in fields(AutoEvalColumn) if c.never_hidden] + shown_columns.value,
208
+ datatype=TYPES,
209
+ elem_id="leaderboard-table",
210
+ interactive=False,
211
+ visible=True,
212
+ )
213
+
214
+ # Dummy leaderboard for handling the case when the user uses backspace key
215
+ hidden_leaderboard_table_for_search = gr.components.Dataframe(
216
+ value=original_df[COLS],
217
+ headers=COLS,
218
+ datatype=TYPES,
219
+ visible=False,
220
+ )
221
+ search_bar.submit(
222
+ update_table,
223
+ [
224
+ hidden_leaderboard_table_for_search,
225
+ shown_columns,
226
+ filter_columns_type,
227
+ filter_columns_precision,
228
+ filter_columns_size,
229
+ show_all,
230
+ search_bar,
231
+ ],
232
+ leaderboard_table,
233
+ )
234
+ for selector in [shown_columns, filter_columns_type, filter_columns_precision, filter_columns_size, show_all]:
235
+ selector.change(
236
+ update_table,
237
+ [
238
+ hidden_leaderboard_table_for_search,
239
+ shown_columns,
240
+ filter_columns_type,
241
+ filter_columns_precision,
242
+ filter_columns_size,
243
+ show_all,
244
+ search_bar,
245
+ ],
246
+ leaderboard_table,
247
+ queue=True,
248
+ )
249
+
250
+ with gr.TabItem("📝 About", elem_id="llm-benchmark-tab-table", id=2):
251
+ gr.Markdown(LLM_BENCHMARKS_TEXT, elem_classes="markdown-text")
252
+
253
+ with gr.TabItem("🚀 Submit here! ", elem_id="llm-benchmark-tab-table", id=3):
254
+ with gr.Column():
255
+ with gr.Row():
256
+ gr.Markdown(EVALUATION_QUEUE_TEXT, elem_classes="markdown-text")
257
+
258
+ with gr.Column():
259
+ with gr.Accordion(
260
+ f"✅ Finished Evaluations ({len(finished_eval_queue_df)})",
261
+ open=False,
262
+ ):
263
+ with gr.Row():
264
+ finished_eval_table = gr.components.Dataframe(
265
+ value=finished_eval_queue_df,
266
+ headers=EVAL_COLS,
267
+ datatype=EVAL_TYPES,
268
+ row_count=5,
269
+ )
270
+ # with gr.Accordion(
271
+ # f"🔄 Running Evaluation Queue ({len(running_eval_queue_df)})",
272
+ # open=False,
273
+ # ):
274
+ # with gr.Row():
275
+ # running_eval_table = gr.components.Dataframe(
276
+ # value=running_eval_queue_df,
277
+ # headers=EVAL_COLS,
278
+ # datatype=EVAL_TYPES,
279
+ # row_count=5,
280
+ # )
281
+ with gr.Accordion(
282
+ f"⏳ Pending Evaluation Queue ({len(pending_eval_queue_df)})",
283
+ open=False,
284
+ ):
285
+ with gr.Row():
286
+ pending_eval_table = gr.components.Dataframe(
287
+ value=pending_eval_queue_df,
288
+ headers=EVAL_COLS,
289
+ datatype=EVAL_TYPES,
290
+ row_count=5,
291
+ )
292
+ with gr.Row():
293
+ gr.Markdown("# ✉️✨ Submit your model here!", elem_classes="markdown-text")
294
+
295
+ with gr.Row():
296
+ with gr.Column():
297
+ model_name_textbox = gr.Textbox(label="Model name")
298
+ revision_name_textbox = gr.Textbox(label="Revision commit", placeholder="main")
299
+ model_type = gr.Dropdown(
300
+ choices=[t.to_str(" : ") for t in ModelType if t != ModelType.Unknown],
301
+ label="Model type",
302
+ multiselect=False,
303
+ value=None,
304
+ interactive=True,
305
+ )
306
+
307
+ with gr.Column():
308
+ precision = gr.Dropdown(
309
+ choices=[i.value.name for i in Precision if i != Precision.Unknown],
310
+ label="Precision",
311
+ multiselect=False,
312
+ value="float16",
313
+ interactive=True,
314
+ )
315
+ weight_type = gr.Dropdown(
316
+ choices=[i.value.name for i in WeightType],
317
+ label="Weights type",
318
+ multiselect=False,
319
+ value="Original",
320
+ interactive=True,
321
+ )
322
+ base_model_name_textbox = gr.Textbox(label="Base model (for delta or adapter weights)")
323
+
324
+ submit_button = gr.Button("Submit Eval")
325
+ submission_result = gr.Markdown()
326
+ submit_button.click(
327
+ add_new_eval,
328
+ [
329
+ model_name_textbox,
330
+ base_model_name_textbox,
331
+ revision_name_textbox,
332
+ precision,
333
+ weight_type,
334
+ model_type,
335
+ ],
336
+ submission_result,
337
+ )
338
+
339
+ with gr.Row():
340
+ with gr.Accordion("📙 Citation", open=False):
341
+ citation_button = gr.Textbox(
342
+ value=CITATION_BUTTON_TEXT,
343
+ label=CITATION_BUTTON_LABEL,
344
+ lines=20,
345
+ elem_id="citation-button",
346
+ show_copy_button=True,
347
+ )
348
+ gr.HTML(BOTTOM_LOGO)
349
+
350
+ scheduler = BackgroundScheduler()
351
+ scheduler.add_job(restart_space, "interval", seconds=3600)
352
+ scheduler.start()
353
+ 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,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ APScheduler==3.10.1
2
+ black==23.11.0
3
+ click==8.1.3
4
+ datasets==2.14.5
5
+ gradio
6
+ gradio_client
7
+ huggingface-hub>=0.18.0
8
+ matplotlib==3.7.1
9
+ numpy==1.24.2
10
+ pandas==2.0.0
11
+ python-dateutil==2.8.2
12
+ requests==2.28.2
13
+ tqdm==4.65.0
14
+ transformers==4.43.2
15
+ tokenizers>=0.15.0
16
+ accelerate==0.24.1
17
+ sentencepiece
src/about.py ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass
2
+ from enum import Enum
3
+
4
+ @dataclass
5
+ class Task:
6
+ benchmark: str
7
+ metric: str
8
+ col_name: str
9
+ desciption: str = None
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
+ tsg_avg = Task("3gpp|tsg:_average|0", "acc_norm", "TSG-AVG")
17
+ tsg_ran = Task("3gpp|tsg_ran:_average|0", "acc", "TSG-RAN")
18
+ tsg_sa = Task("3gpp|tsg_sa:_average|0", "acc", "TSG-SA")
19
+ tsg_ct = Task("3gpp|tsg_ct:_average|0", "acc", "TSG-CT")
20
+ tele_EQ = Task("tii|tele_EQ:_average|0", "cosine_similarity", "TELE-EQ")
21
+ tele_QnA = Task("huawei|tele_QnA:_average|0", "acc", "TELE-QnA")
22
+
23
+
24
+ NUM_FEWSHOT = 0 # Change with your few shot
25
+ # ---------------------------------------------------
26
+
27
+
28
+
29
+ # Your leaderboard name
30
+ TITLE = """<h1 align="left" id="space-title">Open Telecom LLM Leaderboard</h1>"""
31
+ # TITLE = """<img src="https://avatars.githubusercontent.com/u/148767883?v=4" style="width:15%;display:block;margin-left:auto;margin-right:auto;border-radius:15px;">"""
32
+
33
+ BOTTOM_LOGO = """<img src="https://avatars.githubusercontent.com/u/148767883?v=4" style="width:20%;display:block;margin-left:auto;margin-right:auto;border-radius:15px;">"""
34
+
35
+ # What does your leaderboard evaluate?
36
+ INTRODUCTION_TEXT = """
37
+ 🌐 The Open TELCOM LLM Leaderboard : Evaluate and compare the performance of Telecom Large Language Models (LLMs).
38
+
39
+
40
+ When you submit a model on the "Submit here!" page, it is automatically evaluated on a set of benchmarks.
41
+
42
+ The GPU used for evaluation is operated with the support of __[Huawei Technologies France](https://www.huawei.com/)__, __[Technology Innovation Institute (TII)](https://www.tii.ae/)__, and __[GSM Association (GSMA)](https://www.gsma.com/)__.
43
+
44
+ The datasets used for evaluation consist of datasets that are the `TeleQna` benchmark from [TeleQna](https://github.com/netop-team/TeleQnA) and `BENCHMARK` benchmark from [BENCHMARK_HUB](https://benchmarkwebsite.com) to assess reasoning, language understanding, commonsense, and more.
45
+
46
+ More details about the benchmarks and the evaluation process is provided on the “About” page.
47
+ """
48
+
49
+ # Which evaluations are you running? how can people reproduce what you have?
50
+ LLM_BENCHMARKS_TEXT = f"""
51
+ # Context
52
+
53
+ Large Language Models (LLMs) have the potential to revolutionize the Sixth Generation (6G) communication networks. However, current mainstream LLMs generally lack the specialized
54
+ knowledge in telecom domain. In this paper, for the first time, we propose a pipeline to adapt any general purpose LLMs to a telecom-specific LLMs. We collect and build telecom-specific pretrain dataset, instruction dataset, preference dataset to perform
55
+ continual pre-training, instruct tuning and alignment tuning respectively. Besides, due to the lack of widely accepted evaluation benchmarks in telecom domain, we extend existing evaluation benchmarks and proposed three new benchmarks, namely, Telecom Math Modeling, Telecom Open QnA and Telecom Code Tasks.
56
+
57
+ These new benchmarks provide a holistic evaluation of the capabilities of LLMs including math modeling, Open-Ended question answering, code generation, infilling, summarization and analysis in telecom domain.
58
+
59
+ ## Icons & Model types
60
+
61
+ 🟢 : `pretrained` or `continuously pretrained`
62
+
63
+ 🔶 : `fine-tuned on domain-specific datasets`
64
+
65
+ 💬 : `chat models (RLHF, DPO, ORPO, ...)`
66
+
67
+ 🤝 : `base merges and moerges`
68
+
69
+
70
+ If the icon is "?", it indicates that there is insufficient information about the model.
71
+ Please provide information about the model through an issue! 🤩
72
+
73
+ Note 1 : We reserve the right to correct any incorrect tags/icons after manual verification to ensure the accuracy and reliability of the leaderboard.
74
+
75
+ Note 2 ⚠️ : Some models might be widely discussed as subjects of caution by the community, implying that users should exercise restraint when using them. Models that have used the evaluation set for training to achieve a high leaderboard ranking, among others, may be selected as subjects of caution and might result in their deletion from the leaderboard.
76
+
77
+ ## How it works
78
+ 📈 We evaluate models using the impressive [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.
79
+ We have set up a benchmark using datasets:
80
+ - Telecom Math Modelling : Find more details [here](https://arxiv.org/pdf/2407.09424) - (provided by [TII](https://www.tii.ae/))
81
+ - Telecom Open QnA : Find more details [here](https://arxiv.org/abs/2310.15051) - (provided by [Huawei Technologies](https://huawei.com))
82
+ - Telecom Code Tasks : Find more details [here](https://arxiv.org/pdf/2407.09424) - (provided by [TII](https://www.tii.ae/))
83
+
84
+ 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.
85
+
86
+ Also, given the nature of the tasks, which include multiple-choice and yes/no questions, the leaderboard primarily uses normalized log likelihood accuracy `loglikelihood_acc_norm` for all tasks. This metric was chosen for its ability to provide a clear and fair measurement of model performance across different types of questions.
87
+
88
+
89
+ Please, consider reaching out to us through the discussions tab if you are working on benchmarks for Telecom LLMs and willing to see them on this leaderboard as well. Your benchmark might change the whole game for Telecom industry !
90
+
91
+ GPUs are provided by __[HuggingFace and GSMA](https://www.gsma.com/)__ for the evaluations.
92
+
93
+ ## Details and Logs
94
+ - Detailed numerical results in the `results` otellm dataset: https://huggingface.co/datasets/otellm/results
95
+ - Community queries and running status in the `requests` otellm dataset: https://huggingface.co/datasets/otellm/requests
96
+
97
+ ## More resources
98
+ If you still have questions, you can check our FAQ [here](https://huggingface.co/spaces/otellm/Open-Telcom-LLM-Leaderboard/discussions/1)!
99
+ """
100
+
101
+ EVALUATION_QUEUE_TEXT = """
102
+ ## Some good practices before submitting a model
103
+
104
+ ### 1) Make sure you can load your model and tokenizer using AutoClasses:
105
+
106
+ ```python
107
+ from transformers import AutoConfig, AutoModel, AutoTokenizer
108
+ config = AutoConfig.from_pretrained("your model name", revision=revision)
109
+ model = AutoModel.from_pretrained("your model name", revision=revision)
110
+ tokenizer = AutoTokenizer.from_pretrained("your model name", revision=revision)
111
+ ```
112
+ If this step fails, follow the error messages to debug your model before submitting it. It's likely your model has been improperly uploaded.
113
+
114
+ Note: make sure your model is public!
115
+ 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!
116
+
117
+ ### 2) Convert your model weights to [safetensors](https://huggingface.co/docs/safetensors/index)
118
+ 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`!
119
+
120
+ ### 3) Make sure your model has an open license!
121
+ This is a leaderboard for Open LLMs, and we'd love for as many people as possible to know they can use your model 🤗
122
+
123
+ ### 4) Fill up your model card
124
+ When we add extra information about models to the leaderboard, it will be automatically taken from the model card
125
+
126
+ ## In case of model failure
127
+ If your model is displayed in the `FAILED` category, its execution stopped.
128
+ Make sure you have followed the above steps first.
129
+ If everything is done, check you can launch the LightEval script on your model locally, using [this script](https://gist.github.com/alielfilali01/d486cfc962dca3ed4091b7c562a4377f).
130
+ """
131
+
132
+ CITATION_BUTTON_LABEL = "Copy the following snippet to cite these results"
133
+ CITATION_BUTTON_TEXT = r"""
134
+ @misc{Netop,
135
+ author = {xxxx, },
136
+ title = {Open Telco LLM Leaderboard},
137
+ year = {2024},
138
+ publisher = {Netop},
139
+ howpublished = "\url{https://huggingface.co/spaces/netop/Open-Telecom-LLM-Leaderboard}"
140
+ }
141
+
142
+ @article{maatouk2023teleqna,
143
+ title={Teleqna: A benchmark dataset to assess large language models telecommunications knowledge},
144
+ author={Maatouk, Ali and Ayed, Fadhel and Piovesan, Nicola and De Domenico, Antonio and Debbah, Merouane and Luo, Zhi-Quan},
145
+ journal={arXiv preprint arXiv:2310.15051},
146
+ year={2023}
147
+ }
148
+
149
+
150
+ @article{maatouk2024large,
151
+ title={Large language models for telecom: Forthcoming impact on the industry},
152
+ author={Maatouk, Ali and Piovesan, Nicola and Ayed, Fadhel and De Domenico, Antonio and Debbah, Merouane},
153
+ journal={IEEE Communications Magazine},
154
+ year={2024},
155
+ publisher={IEEE}
156
+ }
157
+
158
+ @article{zou2024telecomgpt,
159
+ title={TelecomGPT: A framework to build telecom-specfic large language models},
160
+ author={Zou, Hang and Zhao, Qiyang and Tian, Yu and Bariah, Lina and Bader, Faouzi and Lestable, Thierry and Debbah, Merouane},
161
+ journal={arXiv preprint arXiv:2407.09424},
162
+ year={2024}
163
+ }
164
+
165
+ @misc{lighteval,
166
+ author = {Fourrier, Clémentine and Habib, Nathan and Wolf, Thomas and Tunstall, Lewis},
167
+ title = {LightEval: A lightweight framework for LLM evaluation},
168
+ year = {2023},
169
+ version = {0.3.0},
170
+ url = {https://github.com/huggingface/lighteval}
171
+ }"""
src/display/css_html_js.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ custom_css = """
2
+
3
+ .markdown-text {
4
+ font-size: 16px !important;
5
+ }
6
+
7
+ #models-to-add-text {
8
+ font-size: 18px !important;
9
+ }
10
+
11
+ #citation-button span {
12
+ font-size: 16px !important;
13
+ }
14
+
15
+ #citation-button textarea {
16
+ font-size: 16px !important;
17
+ }
18
+
19
+ #citation-button > label > button {
20
+ margin: 6px;
21
+ transform: scale(1.3);
22
+ }
23
+
24
+ #leaderboard-table {
25
+ margin-top: 15px
26
+ }
27
+
28
+ #leaderboard-table-lite {
29
+ margin-top: 15px
30
+ }
31
+
32
+ #search-bar-table-box > div:first-child {
33
+ background: none;
34
+ border: none;
35
+ }
36
+
37
+ #search-bar {
38
+ padding: 0px;
39
+ }
40
+
41
+ /* Limit the width of the first AutoEvalColumn so that names don't expand too much */
42
+ 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,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass, make_dataclass, field
2
+ from enum import Enum
3
+
4
+ import pandas as pd
5
+
6
+ from src.about import Tasks
7
+ import pdb
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
+ # Prevent ValueError: mutable default <class 'className'> for field 'fieldName' is not allowed: use default_factory
26
+ def to_dataclass_field(c: ColumnContent):
27
+ return field(default_factory=lambda: c)
28
+
29
+
30
+ ## Leaderboard columns
31
+ auto_eval_column_dict = []
32
+ # Init
33
+ auto_eval_column_dict.append(["model_type_symbol", ColumnContent, to_dataclass_field(ColumnContent("T", "str", True, never_hidden=True))])
34
+ auto_eval_column_dict.append(["model", ColumnContent, to_dataclass_field(ColumnContent("Model", "markdown", True, never_hidden=True))])
35
+ #Scores
36
+ auto_eval_column_dict.append(["average", ColumnContent, to_dataclass_field(ColumnContent("Average ⬆️", "number", True))])
37
+ for task in Tasks:
38
+ auto_eval_column_dict.append([task.name, ColumnContent, to_dataclass_field(ColumnContent(task.value.col_name, "number", True))])
39
+ # Model information
40
+ auto_eval_column_dict.append(["model_type", ColumnContent, to_dataclass_field(ColumnContent("Type", "str", False))])
41
+ auto_eval_column_dict.append(["architecture", ColumnContent, to_dataclass_field(ColumnContent("Architecture", "str", False))])
42
+ auto_eval_column_dict.append(["weight_type", ColumnContent, to_dataclass_field(ColumnContent("Weight type", "str", False, True))])
43
+ auto_eval_column_dict.append(["precision", ColumnContent, to_dataclass_field(ColumnContent("Precision", "str", False))])
44
+ auto_eval_column_dict.append(["license", ColumnContent, to_dataclass_field(ColumnContent("Hub License", "str", False))])
45
+ auto_eval_column_dict.append(["params", ColumnContent, to_dataclass_field(ColumnContent("#Params (B)", "number", False))])
46
+ auto_eval_column_dict.append(["likes", ColumnContent, to_dataclass_field(ColumnContent("Hub ❤️", "number", False))])
47
+ auto_eval_column_dict.append(["still_on_hub", ColumnContent, to_dataclass_field(ColumnContent("Available on the hub", "bool", False))])
48
+ auto_eval_column_dict.append(["revision", ColumnContent, to_dataclass_field(ColumnContent("Model sha", "str", False, False))])
49
+
50
+ # We use make dataclass to dynamically fill the scores from Tasks
51
+ AutoEvalColumn = make_dataclass("AutoEvalColumn", auto_eval_column_dict, frozen=True)()
52
+
53
+ # pdb.set_trace()
54
+
55
+ ## For the queue columns in the submission tab
56
+ @dataclass(frozen=True)
57
+ class EvalQueueColumn: # Queue column
58
+ model = ColumnContent("model", "markdown", True)
59
+ revision = ColumnContent("revision", "str", True)
60
+ private = ColumnContent("private", "bool", True)
61
+ precision = ColumnContent("precision", "str", True)
62
+ weight_type = ColumnContent("weight_type", "str", "Original")
63
+ status = ColumnContent("status", "str", True)
64
+
65
+ ## All the model information that we might need
66
+ @dataclass
67
+ class ModelDetails:
68
+ name: str
69
+ display_name: str = ""
70
+ symbol: str = "" # emoji
71
+
72
+
73
+ class ModelType(Enum):
74
+ PT = ModelDetails(name="pretrained", symbol="🟢")
75
+ CPT = ModelDetails(name="continuously pretrained", symbol="🟩")
76
+ FT = ModelDetails(name="fine-tuned on domain-specific datasets", symbol="🔶")
77
+ chat = ModelDetails(name="chat models (RLHF, DPO, IFT, ...)", symbol="💬")
78
+ merges = ModelDetails(name="base merges and moerges", symbol="🤝")
79
+ Unknown = ModelDetails(name="", symbol="?")
80
+
81
+ def to_str(self, separator=" "):
82
+ return f"{self.value.symbol}{separator}{self.value.name}"
83
+
84
+ @staticmethod
85
+ def from_str(type):
86
+ if "pretrained" in type or "🟢" in type:
87
+ return ModelType.PT
88
+ if "continously pretrained" in type or "🟩" in type:
89
+ return ModelType.CPT
90
+ if "fine-tuned" in type or "🔶" in type:
91
+ return ModelType.FT
92
+ if any([k in type for k in ["instruction-tuned", "RL-tuned", "chat", "🟦", "⭕", "💬"]]):
93
+ return ModelType.chat
94
+ if "merges" in type or "🤝" in type:
95
+ return ModelType.merges
96
+ return ModelType.Unknown
97
+
98
+
99
+ class WeightType(Enum):
100
+ Adapter = ModelDetails("Adapter")
101
+ Original = ModelDetails("Original")
102
+ Delta = ModelDetails("Delta")
103
+
104
+ class Precision(Enum):
105
+ # float32 = ModelDetails("float32")
106
+ float16 = ModelDetails("float16")
107
+ bfloat16 = ModelDetails("bfloat16")
108
+ qt_8bit = ModelDetails("8bit")
109
+ qt_4bit = ModelDetails("4bit")
110
+ qt_GPTQ = ModelDetails("GPTQ")
111
+ Unknown = ModelDetails("?")
112
+
113
+ def from_str(precision):
114
+ # if precision in ["torch.float32", "float32"]:
115
+ # return Precision.float32
116
+ if precision in ["torch.float16", "float16"]:
117
+ return Precision.float16
118
+ if precision in ["torch.bfloat16", "bfloat16"]:
119
+ return Precision.bfloat16
120
+ if precision in ["8bit"]:
121
+ return Precision.qt_8bit
122
+ if precision in ["4bit"]:
123
+ return Precision.qt_4bit
124
+ if precision in ["GPTQ", "None"]:
125
+ return Precision.qt_GPTQ
126
+ return Precision.Unknown
127
+
128
+ # Column selection
129
+ COLS = [c.name for c in fields(AutoEvalColumn) if not c.hidden]
130
+ TYPES = [c.type for c in fields(AutoEvalColumn) if not c.hidden]
131
+ COLS_LITE = [c.name for c in fields(AutoEvalColumn) if c.displayed_by_default and not c.hidden]
132
+ TYPES_LITE = [c.type for c in fields(AutoEvalColumn) if c.displayed_by_default and not c.hidden]
133
+
134
+ EVAL_COLS = [c.name for c in fields(EvalQueueColumn)]
135
+ EVAL_TYPES = [c.type for c in fields(EvalQueueColumn)]
136
+
137
+ BENCHMARK_COLS = [t.value.col_name for t in Tasks]
138
+
139
+ NUMERIC_INTERVALS = {
140
+ "?": pd.Interval(-1, 0, closed="right"),
141
+ "~1.5": pd.Interval(0, 2, closed="right"),
142
+ "~3": pd.Interval(2, 4, closed="right"),
143
+ "~7": pd.Interval(4, 9, closed="right"),
144
+ "~13": pd.Interval(9, 20, closed="right"),
145
+ "~35": pd.Interval(20, 45, closed="right"),
146
+ "~60": pd.Interval(45, 70, closed="right"),
147
+ "70+": pd.Interval(70, 10000, closed="right"),
148
+ }
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("HF_TOKEN") # A read/write token for your org
8
+
9
+ OWNER = "otellm" # 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}/open-telecom-llm-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,198 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import glob
2
+ import json
3
+ import os
4
+ from dataclasses import dataclass
5
+
6
+ import dateutil
7
+ import numpy as np
8
+
9
+ from src.display.formatting import make_clickable_model
10
+ from src.display.utils import AutoEvalColumn, ModelType, Tasks, Precision, WeightType
11
+ from src.submission.check_validity import is_model_on_hub
12
+
13
+
14
+ @dataclass
15
+ class EvalResult:
16
+ """Represents one full evaluation. Built from a combination of the result and request file for a given run.
17
+ """
18
+ eval_name: str # org_model_precision (uid)
19
+ full_model: str # org/model (path on hub)
20
+ org: str
21
+ model: str
22
+ revision: str # commit hash, "" if main
23
+ results: dict
24
+ precision: Precision = Precision.Unknown
25
+ model_type: ModelType = ModelType.Unknown # Pretrained, fine tuned, ...
26
+ weight_type: WeightType = WeightType.Original # Original or Adapter
27
+ architecture: str = "Unknown"
28
+ license: str = "?"
29
+ likes: int = 0
30
+ num_params: int = 0
31
+ date: str = "" # submission date of request file
32
+ still_on_hub: bool = False
33
+
34
+ @classmethod
35
+ def init_from_json_file(self, json_filepath):
36
+ """Inits the result from the specific model result file"""
37
+ with open(json_filepath) as fp:
38
+ data = json.load(fp)
39
+
40
+ config = data.get("config_general")
41
+
42
+ # Precision
43
+ precision = Precision.from_str(config.get("model_dtype"))
44
+
45
+ # Get model and org
46
+ org_and_model = config.get("model_name", config.get("model_args", None))
47
+ org_and_model = org_and_model.split("/", 1)
48
+
49
+ if len(org_and_model) == 1:
50
+ org = None
51
+ model = org_and_model[0]
52
+ result_key = f"{model}_{precision.value.name}"
53
+ else:
54
+ org = org_and_model[0]
55
+ model = org_and_model[1]
56
+ result_key = f"{org}_{model}_{precision.value.name}"
57
+ full_model = "/".join(org_and_model)
58
+
59
+ still_on_hub, _, model_config = is_model_on_hub(
60
+ full_model, config.get("model_sha", "main"), trust_remote_code=True, test_tokenizer=False
61
+ )
62
+ architecture = "?"
63
+ if model_config is not None:
64
+ architectures = getattr(model_config, "architectures", None)
65
+ if architectures:
66
+ architecture = ";".join(architectures)
67
+
68
+ # Extract results available in this file (some results are split in several files)
69
+ results = {}
70
+ for task in Tasks:
71
+ task = task.value
72
+
73
+ # We average all scores of a given metric (not all metrics are present in all files)
74
+ accs = np.array([v.get(task.metric, None) for k, v in data["results"].items() if task.benchmark == k])
75
+ if accs.size == 0 or any([acc is None for acc in accs]):
76
+ continue
77
+
78
+ mean_acc = np.mean(accs) * 100.0
79
+ results[task.benchmark] = mean_acc
80
+
81
+ return self(
82
+ eval_name=result_key,
83
+ full_model=full_model,
84
+ org=org,
85
+ model=model,
86
+ results=results,
87
+ precision=precision,
88
+ revision= config.get("model_sha", ""),
89
+ still_on_hub=still_on_hub,
90
+ architecture=architecture
91
+ )
92
+
93
+ def update_with_request_file(self, requests_path):
94
+ """Finds the relevant request file for the current model and updates info with it"""
95
+ request_file = get_request_file_for_model(requests_path, self.full_model, self.precision.value.name)
96
+
97
+ try:
98
+ with open(request_file, "r") as f:
99
+ request = json.load(f)
100
+ self.model_type = ModelType.from_str(request.get("model_type", ""))
101
+ self.weight_type = WeightType[request.get("weight_type", "Original")]
102
+ self.license = request.get("license", "?")
103
+ self.likes = request.get("likes", 0)
104
+ self.num_params = request.get("params", 0)
105
+ self.date = request.get("submitted_time", "")
106
+ self.architecture = request.get("architectures", "Unknown") # delete later
107
+ self.status = request.get("status", "FAILED")
108
+ except Exception:
109
+ self.status = "FAILED"
110
+ print(f'Could not find request file for {self.org}/{self.model} with "precision:{self.precision.value.name},model_type:{self.model_type}",license:{self.license},status:{self.status}')
111
+
112
+ def to_dict(self):
113
+ """Converts the Eval Result to a dict compatible with our dataframe display"""
114
+ average = sum([v for v in self.results.values() if v is not None]) / len(Tasks)
115
+ data_dict = {
116
+ "eval_name": self.eval_name, # not a column, just a save name,
117
+ AutoEvalColumn.precision.name: self.precision.value.name,
118
+ AutoEvalColumn.model_type.name: self.model_type.value.name,
119
+ AutoEvalColumn.model_type_symbol.name: self.model_type.value.symbol,
120
+ AutoEvalColumn.weight_type.name: self.weight_type.value.name,
121
+ AutoEvalColumn.architecture.name: self.architecture,
122
+ AutoEvalColumn.model.name: make_clickable_model(self.full_model),
123
+ AutoEvalColumn.revision.name: self.revision,
124
+ AutoEvalColumn.average.name: average,
125
+ AutoEvalColumn.license.name: self.license,
126
+ AutoEvalColumn.likes.name: self.likes,
127
+ AutoEvalColumn.params.name: self.num_params,
128
+ AutoEvalColumn.still_on_hub.name: self.still_on_hub,
129
+ }
130
+
131
+ for task in Tasks:
132
+ data_dict[task.value.col_name] = self.results[task.value.benchmark]
133
+
134
+ return data_dict
135
+
136
+
137
+ def get_request_file_for_model(requests_path, model_name, precision):
138
+ """Selects the correct request file for a given model. Only keeps runs tagged as FINISHED"""
139
+ request_files = os.path.join(
140
+ requests_path,
141
+ f"{model_name}_eval_request_*.json",
142
+ )
143
+ request_files = glob.glob(request_files)
144
+
145
+ # Select correct request file (precision)
146
+ request_file = ""
147
+ request_files = sorted(request_files, reverse=True)
148
+ for tmp_request_file in request_files:
149
+ with open(tmp_request_file, "r") as f:
150
+ req_content = json.load(f)
151
+ if (
152
+ req_content["status"] in ["FINISHED"]
153
+ and req_content["precision"] == precision.split(".")[-1]
154
+ ):
155
+ request_file = tmp_request_file
156
+ return request_file
157
+
158
+
159
+ def get_raw_eval_results(results_path: str, requests_path: str) -> list[EvalResult]:
160
+ """From the path of the results folder root, extract all needed info for results"""
161
+ model_result_filepaths = []
162
+
163
+ for root, _, files in os.walk(results_path):
164
+ # We should only have json files in model results
165
+ if len(files) == 0 or any([not f.endswith(".json") for f in files]):
166
+ continue
167
+
168
+ # Sort the files by date
169
+ try:
170
+ files.sort(key=lambda x: x.removesuffix(".json").removeprefix("results_")[:-7])
171
+ except dateutil.parser._parser.ParserError:
172
+ files = [files[-1]]
173
+
174
+ for file in files:
175
+ model_result_filepaths.append(os.path.join(root, file))
176
+
177
+ eval_results = {}
178
+ for model_result_filepath in model_result_filepaths:
179
+ # Creation of result
180
+ eval_result = EvalResult.init_from_json_file(model_result_filepath)
181
+ eval_result.update_with_request_file(requests_path)
182
+
183
+ # Store results of same eval together
184
+ eval_name = eval_result.eval_name
185
+ if eval_name in eval_results.keys():
186
+ eval_results[eval_name].results.update({k: v for k, v in eval_result.results.items() if v is not None})
187
+ else:
188
+ eval_results[eval_name] = eval_result
189
+
190
+ results = []
191
+ for v in eval_results.values():
192
+ try:
193
+ v.to_dict() # we test if the dict version is complete
194
+ results.append(v)
195
+ except KeyError: # not all eval values present
196
+ continue
197
+
198
+ return results
src/populate.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+
4
+ import pandas as pd
5
+
6
+ from src.display.formatting import has_no_nan_values, make_clickable_model
7
+ from src.display.utils import AutoEvalColumn, EvalQueueColumn
8
+ from src.leaderboard.read_evals import get_raw_eval_results
9
+
10
+
11
+ def get_leaderboard_df(results_path: str, requests_path: str, cols: list, benchmark_cols: list) -> pd.DataFrame:
12
+ """Creates a dataframe from all the individual experiment results"""
13
+ raw_data = get_raw_eval_results(results_path, requests_path)
14
+ all_data_json = [v.to_dict() for v in raw_data]
15
+
16
+ df = pd.DataFrame.from_records(all_data_json)
17
+ df = df.sort_values(by=[AutoEvalColumn.average.name], ascending=False)
18
+ df = df[cols].round(decimals=2)
19
+
20
+ # filter out if any of the benchmarks have not been produced
21
+ df = df[has_no_nan_values(df, benchmark_cols)]
22
+ print("\nsrc/populate.py/get_leaderboard_df() : num of elements in leaderboard is :", len(df))
23
+
24
+ return raw_data, df
25
+
26
+
27
+ def get_evaluation_queue_df(save_path: str, cols: list) -> list[pd.DataFrame]:
28
+ entries = [entry for entry in os.listdir(save_path) if not entry.startswith(".")]
29
+ all_evals = []
30
+
31
+ for entry in entries:
32
+ if ".json" in entry:
33
+ file_path = os.path.join(save_path, entry)
34
+ try:
35
+ with open(file_path, encoding='utf-8') as fp:
36
+ data = json.load(fp)
37
+ except UnicodeDecodeError as e:
38
+ print(f"Unicode decoding error in {file_path}: {e}")
39
+ continue
40
+
41
+ data[EvalQueueColumn.model.name] = make_clickable_model(data["model"])
42
+ data[EvalQueueColumn.revision.name] = data.get("revision", "main")
43
+
44
+ all_evals.append(data)
45
+ elif ".md" not in entry:
46
+ # this is a folder
47
+ sub_entries = [e for e in os.listdir(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
+ try:
51
+ with open(file_path, encoding='utf-8') as fp:
52
+ data = json.load(fp)
53
+ except json.JSONDecodeError:
54
+ print(f"Error reading {file_path}")
55
+ continue
56
+ except UnicodeDecodeError as e:
57
+ print(f"Unicode decoding error in {file_path}: {e}")
58
+ continue
59
+
60
+ data[EvalQueueColumn.model.name] = make_clickable_model(data["model"])
61
+ data[EvalQueueColumn.revision.name] = data.get("revision", "main")
62
+ all_evals.append(data)
63
+
64
+ pending_list = [e for e in all_evals if e["status"] in ["PENDING", "RERUN"]]
65
+ running_list = [e for e in all_evals if e["status"] == "RUNNING"]
66
+ finished_list = [e for e in all_evals if e["status"].startswith("FINISHED") or e["status"] == "PENDING_NEW_EVAL"]
67
+ df_pending = pd.DataFrame.from_records(pending_list, columns=cols)
68
+ df_running = pd.DataFrame.from_records(running_list, columns=cols)
69
+ df_finished = pd.DataFrame.from_records(finished_list, columns=cols)
70
+ 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
+ )