Yu (Hope) Hou commited on
Commit
2d3610f
·
1 Parent(s): 3759572

update the leaderboard for qanta 2025

Browse files
README.md CHANGED
@@ -1,6 +1,6 @@
1
  ---
2
  title: Grounded Qa Leaderboard
3
- emoji: 🦀
4
  colorFrom: gray
5
  colorTo: indigo
6
  sdk: gradio
 
1
  ---
2
  title: Grounded Qa Leaderboard
3
+ emoji: 👻
4
  colorFrom: gray
5
  colorTo: indigo
6
  sdk: gradio
app.py CHANGED
@@ -1,46 +1,23 @@
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
  )
15
  from src.display.css_html_js import custom_css
16
  from src.display.utils import (
17
- BENCHMARK_COLS,
18
- COLS,
19
- EVAL_COLS,
20
- EVAL_TYPES,
21
- NUMERIC_INTERVALS,
22
- TYPES,
23
- AutoEvalColumn,
24
- ModelType,
25
  fields,
26
- WeightType,
27
- Precision
28
  )
29
- from src.envs import API, EVAL_REQUESTS_PATH, EVAL_RESULTS_PATH, QUEUE_REPO, REPO_ID, RESULTS_REPO, TOKEN
30
- from src.populate import get_evaluation_queue_df, get_leaderboard_df
31
- from src.submission.submit import add_new_eval
32
 
33
 
34
  def restart_space():
35
  API.restart_space(repo_id=REPO_ID)
36
 
37
- try:
38
- print(EVAL_REQUESTS_PATH)
39
- snapshot_download(
40
- repo_id=QUEUE_REPO, local_dir=EVAL_REQUESTS_PATH, repo_type="dataset", tqdm_class=None, etag_timeout=30, token=TOKEN
41
- )
42
- except Exception:
43
- restart_space()
44
  try:
45
  print(EVAL_RESULTS_PATH)
46
  snapshot_download(
@@ -49,90 +26,9 @@ try:
49
  except Exception:
50
  restart_space()
51
 
52
-
53
- raw_data, original_df = get_leaderboard_df(EVAL_RESULTS_PATH, EVAL_REQUESTS_PATH, COLS, BENCHMARK_COLS)
54
  leaderboard_df = original_df.copy()
55
 
56
- (
57
- finished_eval_queue_df,
58
- running_eval_queue_df,
59
- pending_eval_queue_df,
60
- failed_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)
@@ -140,222 +36,17 @@ with demo:
140
 
141
  with gr.Tabs(elem_classes="tab-buttons") as tabs:
142
  with gr.TabItem("🏅 System", 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
-
264
- with gr.Accordion(
265
- f"❌ Failed Evaluations ({len(failed_eval_queue_df)})",
266
- open=False,
267
- ):
268
- with gr.Row():
269
- finished_eval_table = gr.components.Dataframe(
270
- value=failed_eval_queue_df,
271
- headers=EVAL_COLS,
272
- datatype=EVAL_TYPES,
273
- row_count=5,
274
- )
275
-
276
- with gr.Accordion(
277
- f"🔄 Running Evaluation Queue ({len(running_eval_queue_df)})",
278
- open=False,
279
- ):
280
- with gr.Row():
281
- running_eval_table = gr.components.Dataframe(
282
- value=running_eval_queue_df,
283
- headers=EVAL_COLS,
284
- datatype=EVAL_TYPES,
285
- row_count=5,
286
- )
287
-
288
- with gr.Accordion(
289
- f"⏳ Pending Evaluation Queue ({len(pending_eval_queue_df)})",
290
- open=False,
291
- ):
292
- with gr.Row():
293
- pending_eval_table = gr.components.Dataframe(
294
- value=pending_eval_queue_df,
295
- headers=EVAL_COLS,
296
- datatype=EVAL_TYPES,
297
- row_count=5,
298
- )
299
- with gr.Row():
300
- gr.Markdown("# ✉️✨ Submit your model here!", elem_classes="markdown-text")
301
-
302
- with gr.Row():
303
- with gr.Column():
304
- model_name_textbox = gr.Textbox(label="QA model name")
305
- revision_name_textbox = gr.Textbox(label="Revision commit", placeholder="main")
306
- model_type = gr.Dropdown(
307
- choices=[t.to_str(" : ") for t in ModelType if t != ModelType.Unknown],
308
- label="Model type",
309
- multiselect=False,
310
- value=None,
311
- interactive=True,
312
- )
313
-
314
- with gr.Column():
315
- precision = gr.Dropdown(
316
- choices=[i.value.name for i in Precision if i != Precision.Unknown],
317
- label="Precision",
318
- multiselect=False,
319
- value="float16",
320
- interactive=True,
321
- )
322
- # weight_type = gr.Dropdown(
323
- # choices=[i.value.name for i in WeightType],
324
- # label="Weights type",
325
- # multiselect=False,
326
- # value="Original",
327
- # interactive=True,
328
- # )
329
- weight_type = gr.Textbox(label="Retrieved dataset name")
330
- # TODO: default fake weight_type for now
331
- # weight_type = "none"
332
- base_model_name_textbox = gr.Textbox(label="Retriever model name")
333
-
334
- submit_button = gr.Button("Submit Eval")
335
- submission_result = gr.Markdown()
336
- submit_button.click(
337
- add_new_eval,
338
- [
339
- model_name_textbox,
340
- base_model_name_textbox,
341
- revision_name_textbox,
342
- precision,
343
- weight_type,
344
- model_type,
345
- ],
346
- submission_result,
347
- )
348
-
349
- # with gr.Row():
350
- # with gr.Accordion("📙 More about the task", open=False):
351
- # citation_button = gr.Textbox(
352
- # value=CITATION_BUTTON_TEXT,
353
- # label=CITATION_BUTTON_LABEL,
354
- # lines=20,
355
- # elem_id="citation-button",
356
- # show_copy_button=True,
357
- # )
358
-
359
  scheduler = BackgroundScheduler()
360
  scheduler.add_job(restart_space, "interval", seconds=1800)
361
  scheduler.start()
 
 
1
  import gradio as gr
 
2
  from apscheduler.schedulers.background import BackgroundScheduler
3
  from huggingface_hub import snapshot_download
4
 
5
  from src.about import (
 
 
 
6
  INTRODUCTION_TEXT,
 
7
  TITLE,
8
  )
9
  from src.display.css_html_js import custom_css
10
  from src.display.utils import (
11
+ NewAutoEvalColumn,
 
 
 
 
 
 
 
12
  fields,
 
 
13
  )
14
+ from src.envs import API, EVAL_RESULTS_PATH, REPO_ID, RESULTS_REPO, TOKEN
15
+ from src.populate import get_new_leaderboard_df
 
16
 
17
 
18
  def restart_space():
19
  API.restart_space(repo_id=REPO_ID)
20
 
 
 
 
 
 
 
 
21
  try:
22
  print(EVAL_RESULTS_PATH)
23
  snapshot_download(
 
26
  except Exception:
27
  restart_space()
28
 
29
+ original_df = get_new_leaderboard_df(EVAL_RESULTS_PATH)
 
30
  leaderboard_df = original_df.copy()
31
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
  demo = gr.Blocks(css=custom_css)
33
  with demo:
34
  gr.HTML(TITLE)
 
36
 
37
  with gr.Tabs(elem_classes="tab-buttons") as tabs:
38
  with gr.TabItem("🏅 System", elem_id="llm-benchmark-tab-table", id=0):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
  leaderboard_table = gr.components.Dataframe(
40
  value=leaderboard_df[
41
+ ["model", "buzz_accuracy", "win_rate_human", "win_rate_model"]
 
42
  ],
43
+ headers=[c.name for c in fields(NewAutoEvalColumn)],
44
+ datatype=[c.type for c in fields(NewAutoEvalColumn)],
45
  elem_id="leaderboard-table",
46
  interactive=False,
47
  visible=True,
48
  )
49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
  scheduler = BackgroundScheduler()
51
  scheduler.add_job(restart_space, "interval", seconds=1800)
52
  scheduler.start()
src/about.py CHANGED
@@ -1,25 +1,3 @@
1
- from dataclasses import dataclass
2
- from enum import Enum
3
-
4
- @dataclass
5
- class Task:
6
- benchmark: str
7
- metric: str
8
- col_name: str
9
-
10
-
11
- # Select your tasks here
12
- # ---------------------------------------------------
13
- class Tasks(Enum):
14
- # task_key in the json file, metric_key in the json file, name to display in the leaderboard
15
- # task0 = Task("trickme", "acc", "Accuracy")
16
- task1 = Task("trickme", "avg_confidence", "Buzz Confidence")
17
-
18
- NUM_FEWSHOT = 0 # Change with your few shot
19
- # ---------------------------------------------------
20
-
21
-
22
-
23
  # Your leaderboard name
24
  TITLE = """<h1 align="center" id="space-title">Adversarial Calibration QA Leaderboard</h1>"""
25
 
@@ -27,98 +5,3 @@ TITLE = """<h1 align="center" id="space-title">Adversarial Calibration QA Leader
27
  INTRODUCTION_TEXT = """
28
  Build an open-domain QA system that can answer any question posed by humans! For more: https://sites.google.com/view/qanta/home
29
  """
30
-
31
- # Which evaluations are you running? how can people reproduce what you have?
32
- LLM_BENCHMARKS_TEXT = """
33
- ## QA variants
34
-
35
- ### Generative QA
36
- This type of QA system aims to generate an answer to a given question directly.
37
-
38
- #### Input
39
- (1) `question` string
40
-
41
- ```
42
- E.g. qa_pipe(question)
43
- ```
44
-
45
- #### Output
46
- Return in a JSON format: (1) `guess` string, (2) `confidence` score which should be a float number representing the probability (0-1) of your guess.
47
-
48
- ```
49
- E.g. {'guess': 'Apple', 'confidence': 0.02}
50
- ```
51
-
52
- Reminder: Feel free to check the tutorial provided to see how you could calculate the probability of the generated tokens!
53
-
54
- ### Extractive QA
55
- This type of QA system aims to extract an answer span from a context passage for a given question.
56
-
57
- #### Input
58
- (1) `question` string, and (2) `context` string
59
-
60
- ```
61
- E.g. qa_pipe(question=question, context=context)
62
- ```
63
-
64
- #### Output
65
- Return in a JSON format: (1) `guess` string, (2) `confidence` score which should be a float number representing the probability (0-1) of your guess.
66
-
67
- ```
68
- E.g. {'guess': 'Apple', 'confidence': 0.02}
69
- ```
70
-
71
- Reminder: If you are playing around with an extractive QA model already, HF QA models output the `score` already, so you only need to wrap the `score` to `confidence`.
72
-
73
- ## Evaluation Metric
74
- In our Adversarial Calibration QA task, we evaluate the QA model's reliability of their performance by measuring their calibration estimates where we consider the confidence of guess confidence values. To understand this concept better, we adopt the concept of "buzz" in Trivia Quiz, where buzz happens whenever the player is confident enough to predict the correct guess in the middle of a question. This also applies to our measurement of model calibration as we focus whether the model prediction probability matches its prediction accuracy. Our evaluation metric, `Average Expected Buzz`, quantifies the expected buzz confidence estimation.
75
-
76
- ## FAQ
77
- What if my system type is not specified here or not supported yet?
78
- - Please send us an email so we could check how we adapt the leaderboard for your purpose. Thanks!
79
-
80
- I don't understand where I could start to build a QA system for submission.
81
- - Please check our submission tutorials. From there, you could fine-tune or do anything above the base models.
82
-
83
- I want to use API-based QA systems for submission, like GPT4. What should I do?
84
- - We don't support API-based models now but you could train your model with the GPT cache we provided: https://github.com/Pinafore/nlp-hw/tree/master/models.
85
-
86
- I have no ideas why my model is not working. Could you help me?
87
- - Yes! After you model submission is evaluated, you could check the first few example details with how scores are calculated [here](https://huggingface.co/datasets/umdclip/qanta_leaderboard_logs)!
88
- """
89
-
90
- EVALUATION_QUEUE_TEXT = """
91
- **Step 1: Make sure it could work locally**
92
-
93
- After you have a QA system uploaded to HuggingFace (with license specified), please check with the following example code to see if your pipe could return the guess and confidence score in a **JSON** format.
94
-
95
- ```
96
- from transformers import pipeline
97
- qa_pipe = pipeline(model="...", trust_remote_code=True)
98
-
99
- # If it is a Generative QA pipeline
100
- qa_pipe(“Where is UMD?”)
101
-
102
- # If it is a Extractive QA pipeline
103
- qa_pipe(question=“Where is UMD?”, context=”UMD is in Maryland.”)
104
- ```
105
-
106
- **Step 2: Fill in the submission form**
107
-
108
- (1) Fill in the `QA model name`
109
-
110
- (2) Fill in the `Revision commit`: if you leave it empty, by default it will be `main`.
111
-
112
- (3) Fill in the `Model type`
113
-
114
- (4) `Precision` by default is `float16`. You could update it as needed.
115
-
116
- (5) You could leave the `Retrieved dataset name` and `Retriever model` fields empty as we provide context for your extractive QA model. Let us know if you want to use your own context or retriver via an email!
117
-
118
- Here is a tutorial on how you could make pipe wrappers for submissions: [Colab](https://colab.research.google.com/drive/1bCt2870SdY6tI4uE3JPG8_3nLmNJXX6_?usp=sharing)
119
- """
120
-
121
- CITATION_BUTTON_LABEL = "Copy the following link to check more details"
122
- CITATION_BUTTON_TEXT = r"""
123
- https://sites.google.com/view/qanta/home
124
- """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  # Your leaderboard name
2
  TITLE = """<h1 align="center" id="space-title">Adversarial Calibration QA Leaderboard</h1>"""
3
 
 
5
  INTRODUCTION_TEXT = """
6
  Build an open-domain QA system that can answer any question posed by humans! For more: https://sites.google.com/view/qanta/home
7
  """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/display/utils.py CHANGED
@@ -1,135 +1,17 @@
1
  from dataclasses import dataclass, make_dataclass
2
- from enum import Enum
3
-
4
- import pandas as pd
5
-
6
- from src.about import Tasks
7
 
8
  def fields(raw_class):
9
  return [v for k, v in raw_class.__dict__.items() if k[:2] != "__" and k[-2:] != "__"]
10
 
11
-
12
- # These classes are for user facing column names,
13
- # to avoid having to change them all around the code
14
- # when a modif is needed
15
  @dataclass
16
- class ColumnContent:
17
  name: str
18
  type: str
19
- displayed_by_default: bool
20
- hidden: bool = False
21
- never_hidden: bool = False
22
-
23
- ## Leaderboard columns
24
- auto_eval_column_dict = []
25
- # Init
26
- auto_eval_column_dict.append(["model_type_symbol", ColumnContent, ColumnContent("T", "str", True, never_hidden=True)])
27
- auto_eval_column_dict.append(["model", ColumnContent, ColumnContent("Model", "markdown", True, never_hidden=True)])
28
- #Scores
29
- # auto_eval_column_dict.append(["average", ColumnContent, ColumnContent("Average ⬆️", "number", True)])
30
- for task in Tasks:
31
- auto_eval_column_dict.append([task.name, ColumnContent, ColumnContent(task.value.col_name, "number", True)])
32
- # Model information
33
- auto_eval_column_dict.append(["model_type", ColumnContent, ColumnContent("Type", "str", False)])
34
- auto_eval_column_dict.append(["architecture", ColumnContent, ColumnContent("Architecture", "str", False)])
35
- auto_eval_column_dict.append(["weight_type", ColumnContent, ColumnContent("Weight type", "str", False, True)])
36
- auto_eval_column_dict.append(["precision", ColumnContent, ColumnContent("Precision", "str", False)])
37
- auto_eval_column_dict.append(["license", ColumnContent, ColumnContent("Hub License", "str", False)])
38
- auto_eval_column_dict.append(["params", ColumnContent, ColumnContent("#Params (B)", "number", False)])
39
- auto_eval_column_dict.append(["likes", ColumnContent, ColumnContent("Hub ❤️", "number", False)])
40
- auto_eval_column_dict.append(["still_on_hub", ColumnContent, ColumnContent("Available on the hub", "bool", False)])
41
- auto_eval_column_dict.append(["revision", ColumnContent, ColumnContent("Model sha", "str", False, False)])
42
-
43
- # We use make dataclass to dynamically fill the scores from Tasks
44
- AutoEvalColumn = make_dataclass("AutoEvalColumn", auto_eval_column_dict, frozen=True)
45
-
46
- ## For the queue columns in the submission tab
47
- @dataclass(frozen=True)
48
- class EvalQueueColumn: # Queue column
49
- model = ColumnContent("model", "markdown", True)
50
- revision = ColumnContent("revision", "str", True)
51
- private = ColumnContent("private", "bool", True)
52
- precision = ColumnContent("precision", "str", True)
53
- weight_type = ColumnContent("weight_type", "str", "Original")
54
- status = ColumnContent("status", "str", True)
55
-
56
- ## All the model information that we might need
57
- @dataclass
58
- class ModelDetails:
59
- name: str
60
- display_name: str = ""
61
- symbol: str = "" # emoji
62
-
63
-
64
- class ModelType(Enum):
65
- PT = ModelDetails(name="pretrained", symbol="🟢")
66
- FT = ModelDetails(name="fine-tuned", symbol="🔶")
67
- IFT = ModelDetails(name="instruction-tuned", symbol="⭕")
68
- RL = ModelDetails(name="RL-tuned", symbol="🟦")
69
- Unknown = ModelDetails(name="", symbol="?")
70
-
71
- def to_str(self, separator=" "):
72
- return f"{self.value.symbol}{separator}{self.value.name}"
73
-
74
- @staticmethod
75
- def from_str(type):
76
- if "fine-tuned" in type or "🔶" in type:
77
- return ModelType.FT
78
- if "pretrained" in type or "🟢" in type:
79
- return ModelType.PT
80
- if "RL-tuned" in type or "🟦" in type:
81
- return ModelType.RL
82
- if "instruction-tuned" in type or "⭕" in type:
83
- return ModelType.IFT
84
- return ModelType.Unknown
85
-
86
- class WeightType(Enum):
87
- Adapter = ModelDetails("Adapter")
88
- Original = ModelDetails("Original")
89
- Delta = ModelDetails("Delta")
90
-
91
- class Precision(Enum):
92
- float16 = ModelDetails("float16")
93
- bfloat16 = ModelDetails("bfloat16")
94
- float32 = ModelDetails("float32")
95
- #qt_8bit = ModelDetails("8bit")
96
- #qt_4bit = ModelDetails("4bit")
97
- #qt_GPTQ = ModelDetails("GPTQ")
98
- Unknown = ModelDetails("?")
99
-
100
- def from_str(precision):
101
- if precision in ["torch.float16", "float16"]:
102
- return Precision.float16
103
- if precision in ["torch.bfloat16", "bfloat16"]:
104
- return Precision.bfloat16
105
- if precision in ["float32"]:
106
- return Precision.float32
107
- #if precision in ["8bit"]:
108
- # return Precision.qt_8bit
109
- #if precision in ["4bit"]:
110
- # return Precision.qt_4bit
111
- #if precision in ["GPTQ", "None"]:
112
- # return Precision.qt_GPTQ
113
- return Precision.Unknown
114
-
115
- # Column selection
116
- COLS = [c.name for c in fields(AutoEvalColumn) if not c.hidden]
117
- TYPES = [c.type for c in fields(AutoEvalColumn) if not c.hidden]
118
- COLS_LITE = [c.name for c in fields(AutoEvalColumn) if c.displayed_by_default and not c.hidden]
119
- TYPES_LITE = [c.type for c in fields(AutoEvalColumn) if c.displayed_by_default and not c.hidden]
120
-
121
- EVAL_COLS = [c.name for c in fields(EvalQueueColumn)]
122
- EVAL_TYPES = [c.type for c in fields(EvalQueueColumn)]
123
 
124
- BENCHMARK_COLS = [t.value.col_name for t in Tasks]
 
 
 
 
125
 
126
- NUMERIC_INTERVALS = {
127
- "?": pd.Interval(-1, 0, closed="right"),
128
- "~1.5": pd.Interval(0, 2, closed="right"),
129
- "~3": pd.Interval(2, 4, closed="right"),
130
- "~7": pd.Interval(4, 9, closed="right"),
131
- "~13": pd.Interval(9, 20, closed="right"),
132
- "~35": pd.Interval(20, 45, closed="right"),
133
- "~60": pd.Interval(45, 70, closed="right"),
134
- "70+": pd.Interval(70, 10000, closed="right"),
135
- }
 
1
  from dataclasses import dataclass, make_dataclass
 
 
 
 
 
2
 
3
  def fields(raw_class):
4
  return [v for k, v in raw_class.__dict__.items() if k[:2] != "__" and k[-2:] != "__"]
5
 
 
 
 
 
6
  @dataclass
7
+ class NewColumnContent:
8
  name: str
9
  type: str
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
 
11
+ new_auto_eval_column_dict = []
12
+ new_auto_eval_column_dict.append(["model", NewColumnContent, NewColumnContent("Model", "markdown")])
13
+ new_auto_eval_column_dict.append(["buzz_accuracy", NewColumnContent, NewColumnContent("Buzz Accuracy ⬆️", "number")])
14
+ new_auto_eval_column_dict.append(["win_rate_human", NewColumnContent, NewColumnContent("Win Rate (Human Teams)", "number")])
15
+ new_auto_eval_column_dict.append(["win_rate_model", NewColumnContent, NewColumnContent("Win Rate (Model Teams)", "number")])
16
 
17
+ NewAutoEvalColumn = make_dataclass("NewAutoEvalColumn", new_auto_eval_column_dict, frozen=True)
 
 
 
 
 
 
 
 
 
src/envs.py CHANGED
@@ -10,16 +10,13 @@ OWNER = "umdclip" # Change to your org - don't forget to create a results and re
10
  # ----------------------------------
11
 
12
  REPO_ID = f"{OWNER}/grounded_qa_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)
 
10
  # ----------------------------------
11
 
12
  REPO_ID = f"{OWNER}/grounded_qa_leaderboard"
13
+ RESULTS_REPO = f"{OWNER}/model-results"
 
14
 
15
  # If you setup a cache later, just change HF_HOME
16
  CACHE_PATH=os.getenv("HF_HOME", ".")
17
 
18
  # Local caches
 
19
  EVAL_RESULTS_PATH = os.path.join(CACHE_PATH, "eval-results")
 
20
  EVAL_RESULTS_PATH_BACKEND = os.path.join(CACHE_PATH, "eval-results-bk")
21
 
22
  API = HfApi(token=TOKEN)
src/leaderboard/read_evals.py DELETED
@@ -1,196 +0,0 @@
1
- import glob
2
- import json
3
- import math
4
- import os
5
- from dataclasses import dataclass
6
-
7
- import dateutil
8
- import numpy as np
9
-
10
- from src.display.formatting import make_clickable_model
11
- from src.display.utils import AutoEvalColumn, ModelType, Tasks, Precision, WeightType
12
- from src.submission.check_validity import is_model_on_hub
13
-
14
-
15
- @dataclass
16
- class EvalResult:
17
- """Represents one full evaluation. Built from a combination of the result and request file for a given run.
18
- """
19
- eval_name: str # org_model_precision (uid)
20
- full_model: str # org/model (path on hub)
21
- org: str
22
- model: str
23
- revision: str # commit hash, "" if main
24
- results: dict
25
- precision: Precision = Precision.Unknown
26
- model_type: ModelType = ModelType.Unknown # Pretrained, fine tuned, ...
27
- weight_type: WeightType = WeightType.Original # Original or Adapter
28
- architecture: str = "Unknown"
29
- license: str = "?"
30
- likes: int = 0
31
- num_params: int = 0
32
- date: str = "" # submission date of request file
33
- still_on_hub: bool = False
34
-
35
- @classmethod
36
- def init_from_json_file(self, json_filepath):
37
- """Inits the result from the specific model result file"""
38
- with open(json_filepath) as fp:
39
- data = json.load(fp)
40
-
41
- config = data.get("config")
42
-
43
- # Precision
44
- precision = Precision.from_str(config.get("model_dtype"))
45
-
46
- # Get model and org
47
- org_and_model = config.get("model_name", config.get("model_args", None))
48
- org_and_model = org_and_model.split("/", 1)
49
-
50
- if len(org_and_model) == 1:
51
- org = None
52
- model = org_and_model[0]
53
- result_key = f"{model}_{precision.value.name}"
54
- else:
55
- org = org_and_model[0]
56
- model = org_and_model[1]
57
- result_key = f"{org}_{model}_{precision.value.name}"
58
- full_model = "/".join(org_and_model)
59
-
60
- still_on_hub, _, model_config = is_model_on_hub(
61
- full_model, config.get("model_sha", "main"), trust_remote_code=True, test_tokenizer=False
62
- )
63
- architecture = "?"
64
- if model_config is not None:
65
- architectures = getattr(model_config, "architectures", None)
66
- if architectures:
67
- architecture = ";".join(architectures)
68
-
69
- # Extract results available in this file (some results are split in several files)
70
- results = {}
71
- for task in Tasks:
72
- task = task.value
73
-
74
- # We average all scores of a given metric (not all metrics are present in all files)
75
- accs = np.array([v.get(task.metric, None) for k, v in data["results"].items() if task.benchmark == k])
76
- if accs.size == 0 or any([acc is None for acc in accs]):
77
- continue
78
-
79
- mean_acc = np.mean(accs) * 100.0
80
- results[task.benchmark] = mean_acc
81
-
82
- return self(
83
- eval_name=result_key,
84
- full_model=full_model,
85
- org=org,
86
- model=model,
87
- results=results,
88
- precision=precision,
89
- revision= config.get("model_sha", ""),
90
- still_on_hub=still_on_hub,
91
- architecture=architecture
92
- )
93
-
94
- def update_with_request_file(self, requests_path):
95
- """Finds the relevant request file for the current model and updates info with it"""
96
- request_file = get_request_file_for_model(requests_path, self.full_model, self.precision.value.name)
97
-
98
- try:
99
- with open(request_file, "r") as f:
100
- request = json.load(f)
101
- self.model_type = ModelType.from_str(request.get("model_type", ""))
102
- self.weight_type = WeightType[request.get("weight_type", "Original")]
103
- self.license = request.get("license", "?")
104
- self.likes = request.get("likes", 0)
105
- self.num_params = request.get("params", 0)
106
- self.date = request.get("submitted_time", "")
107
- except Exception:
108
- print(f"Could not find request file for {self.org}/{self.model} with precision {self.precision.value.name}")
109
-
110
- def to_dict(self):
111
- """Converts the Eval Result to a dict compatible with our dataframe display"""
112
- average = sum([v for v in self.results.values() if v is not None]) / len(Tasks)
113
- data_dict = {
114
- "eval_name": self.eval_name, # not a column, just a save name,
115
- AutoEvalColumn.precision.name: self.precision.value.name,
116
- AutoEvalColumn.model_type.name: self.model_type.value.name,
117
- AutoEvalColumn.model_type_symbol.name: self.model_type.value.symbol,
118
- AutoEvalColumn.weight_type.name: self.weight_type.value.name,
119
- AutoEvalColumn.architecture.name: self.architecture,
120
- AutoEvalColumn.model.name: make_clickable_model(self.full_model),
121
- AutoEvalColumn.revision.name: self.revision,
122
- # AutoEvalColumn.average.name: average,
123
- AutoEvalColumn.license.name: self.license,
124
- AutoEvalColumn.likes.name: self.likes,
125
- AutoEvalColumn.params.name: self.num_params,
126
- AutoEvalColumn.still_on_hub.name: self.still_on_hub,
127
- }
128
-
129
- for task in Tasks:
130
- data_dict[task.value.col_name] = self.results[task.value.benchmark]
131
-
132
- return data_dict
133
-
134
-
135
- def get_request_file_for_model(requests_path, model_name, precision):
136
- """Selects the correct request file for a given model. Only keeps runs tagged as FINISHED"""
137
- request_files = os.path.join(
138
- requests_path,
139
- f"{model_name}_eval_request_*.json",
140
- )
141
- request_files = glob.glob(request_files)
142
-
143
- # Select correct request file (precision)
144
- request_file = ""
145
- request_files = sorted(request_files, reverse=True)
146
- for tmp_request_file in request_files:
147
- with open(tmp_request_file, "r") as f:
148
- req_content = json.load(f)
149
- if (
150
- req_content["status"] in ["FINISHED"]
151
- and req_content["precision"] == precision.split(".")[-1]
152
- ):
153
- request_file = tmp_request_file
154
- return request_file
155
-
156
-
157
- def get_raw_eval_results(results_path: str, requests_path: str) -> list[EvalResult]:
158
- """From the path of the results folder root, extract all needed info for results"""
159
- model_result_filepaths = []
160
-
161
- for root, _, files in os.walk(results_path):
162
- # We should only have json files in model results
163
- if len(files) == 0 or any([not f.endswith(".json") for f in files]):
164
- continue
165
-
166
- # Sort the files by date
167
- try:
168
- files.sort(key=lambda x: x.removesuffix(".json").removeprefix("results_")[:-7])
169
- except dateutil.parser._parser.ParserError:
170
- files = [files[-1]]
171
-
172
- for file in files:
173
- model_result_filepaths.append(os.path.join(root, file))
174
-
175
- eval_results = {}
176
- for model_result_filepath in model_result_filepaths:
177
- # Creation of result
178
- eval_result = EvalResult.init_from_json_file(model_result_filepath)
179
- eval_result.update_with_request_file(requests_path)
180
-
181
- # Store results of same eval together
182
- eval_name = eval_result.eval_name
183
- if eval_name in eval_results.keys():
184
- eval_results[eval_name].results.update({k: v for k, v in eval_result.results.items() if v is not None})
185
- else:
186
- eval_results[eval_name] = eval_result
187
-
188
- results = []
189
- for v in eval_results.values():
190
- try:
191
- v.to_dict() # we test if the dict version is complete
192
- results.append(v)
193
- except KeyError: # not all eval values present
194
- continue
195
-
196
- return results
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/populate.py CHANGED
@@ -3,60 +3,29 @@ 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
- # TODO: decide how to sort the leaderboard
18
- # df = df.sort_values(by=[AutoEvalColumn.average.name], ascending=False)
19
- df = df.sort_values(by=[AutoEvalColumn.model.name], ascending=False)
20
- df = df[cols].round(decimals=2)
21
-
22
- # filter out if any of the benchmarks have not been produced
23
- df = df[has_no_nan_values(df, benchmark_cols)]
24
- return raw_data, df
25
-
26
-
27
- def get_evaluation_queue_df(save_path: str, cols: list) -> list[pd.DataFrame]:
28
- """Creates the different dataframes for the evaluation queues requestes"""
29
- entries = [entry for entry in os.listdir(save_path) if not entry.startswith(".")]
30
- all_evals = []
31
-
32
- for entry in entries:
33
- if ".json" in entry:
34
- file_path = os.path.join(save_path, entry)
35
- with open(file_path) as fp:
36
- data = json.load(fp)
37
-
38
- data[EvalQueueColumn.model.name] = make_clickable_model(data["model"])
39
- data[EvalQueueColumn.revision.name] = data.get("revision", "main")
40
-
41
- all_evals.append(data)
42
- elif ".md" not in entry:
43
- # this is a folder
44
- sub_entries = [e for e in os.listdir(f"{save_path}/{entry}") if not e.startswith(".")]
45
- for sub_entry in sub_entries:
46
- file_path = os.path.join(save_path, entry, sub_entry)
47
- with open(file_path) as fp:
48
- data = json.load(fp)
49
-
50
- data[EvalQueueColumn.model.name] = make_clickable_model(data["model"])
51
- data[EvalQueueColumn.revision.name] = data.get("revision", "main")
52
- all_evals.append(data)
53
-
54
- pending_list = [e for e in all_evals if e["status"] in ["PENDING", "RERUN"]]
55
- failed_list = [e for e in all_evals if e["status"] == "FAILED"]
56
- running_list = [e for e in all_evals if e["status"] == "RUNNING"]
57
- finished_list = [e for e in all_evals if e["status"].startswith("FINISHED") or e["status"] == "PENDING_NEW_EVAL"]
58
- df_pending = pd.DataFrame.from_records(pending_list, columns=cols)
59
- df_running = pd.DataFrame.from_records(running_list, columns=cols)
60
- df_finished = pd.DataFrame.from_records(finished_list, columns=cols)
61
- df_failed = pd.DataFrame.from_records(failed_list, columns=cols)
62
- return df_finished[cols], df_running[cols], df_pending[cols], df_failed[cols]
 
3
 
4
  import pandas as pd
5
 
6
+ def get_new_leaderboard_df(results_path: str) -> pd.DataFrame:
7
+ model_result_filepaths = []
8
+ for root, _, files in os.walk(results_path):
9
+ if len(files) == 0 or any([not f.endswith(".json") for f in files]):
10
+ continue
11
+ for file in files:
12
+ model_result_filepaths.append(os.path.join(root, file))
13
+
14
+ eval_results = {
15
+ 'model': [],
16
+ 'buzz_accuracy': [],
17
+ 'win_rate_human': [],
18
+ 'win_rate_model': []
19
+ }
20
+ for model_result_filepath in model_result_filepaths:
21
+ with open(model_result_filepath, "r") as fin:
22
+ model_result = json.load(fin)
23
+ model_id = model_result["model_id"]
24
+ buzz_accuracy = model_result["buzz_accuracy"]
25
+ win_rate_human = model_result["win_rate_human"]
26
+ win_rate_model = model_result["win_rate_model"]
27
+ eval_results['model'].append(model_id)
28
+ eval_results['buzz_accuracy'].append(buzz_accuracy)
29
+ eval_results['win_rate_human'].append(win_rate_human)
30
+ eval_results['win_rate_model'].append(win_rate_model)
31
+ return pd.DataFrame(eval_results)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/submission/check_validity.py DELETED
@@ -1,99 +0,0 @@
1
- import json
2
- import os
3
- import re
4
- from collections import defaultdict
5
- from datetime import datetime, timedelta, timezone
6
-
7
- import huggingface_hub
8
- from huggingface_hub import ModelCard
9
- from huggingface_hub.hf_api import ModelInfo
10
- from transformers import AutoConfig
11
- from transformers.models.auto.tokenization_auto import AutoTokenizer
12
-
13
- def check_model_card(repo_id: str) -> tuple[bool, str]:
14
- """Checks if the model card and license exist and have been filled"""
15
- try:
16
- card = ModelCard.load(repo_id)
17
- except huggingface_hub.utils.EntryNotFoundError:
18
- return False, "Please add a model card to your model to explain how you trained/fine-tuned it."
19
-
20
- # Enforce license metadata
21
- if card.data.license is None:
22
- if not ("license_name" in card.data and "license_link" in card.data):
23
- return False, (
24
- "License not found. Please add a license to your model card using the `license` metadata or a"
25
- " `license_name`/`license_link` pair."
26
- )
27
-
28
- # Enforce card content
29
- if len(card.text) < 200:
30
- return False, "Please add a description to your model card, it is too short."
31
-
32
- return True, ""
33
-
34
- def is_model_on_hub(model_name: str, revision: str, token: str = None, trust_remote_code=True, test_tokenizer=False) -> tuple[bool, str]:
35
- """Checks if the model model_name is on the hub, and whether it (and its tokenizer) can be loaded with AutoClasses."""
36
- try:
37
- config = AutoConfig.from_pretrained(model_name, revision=revision, trust_remote_code=trust_remote_code, token=token)
38
- if test_tokenizer:
39
- try:
40
- tk = AutoTokenizer.from_pretrained(model_name, revision=revision, trust_remote_code=trust_remote_code, token=token)
41
- except ValueError as e:
42
- return (
43
- False,
44
- f"uses a tokenizer which is not in a transformers release: {e}",
45
- None
46
- )
47
- except Exception as e:
48
- return (False, "'s tokenizer cannot be loaded. Is your tokenizer class in a stable transformers release, and correctly configured?", None)
49
- return True, None, config
50
-
51
- except ValueError:
52
- return (
53
- False,
54
- "needs to be launched with `trust_remote_code=True`. For safety reason, we do not allow these models to be automatically submitted to the leaderboard.",
55
- None
56
- )
57
-
58
- except Exception as e:
59
- return False, "was not found on hub!", None
60
-
61
-
62
- def get_model_size(model_info: ModelInfo, precision: str):
63
- """Gets the model size from the configuration, or the model name if the configuration does not contain the information."""
64
- try:
65
- model_size = round(model_info.safetensors["total"] / 1e9, 3)
66
- except (AttributeError, TypeError):
67
- return 0 # Unknown model sizes are indicated as 0, see NUMERIC_INTERVALS in app.py
68
-
69
- size_factor = 8 if (precision == "GPTQ" or "gptq" in model_info.modelId.lower()) else 1
70
- model_size = size_factor * model_size
71
- return model_size
72
-
73
- def get_model_arch(model_info: ModelInfo):
74
- """Gets the model architecture from the configuration"""
75
- return model_info.config.get("architectures", "Unknown")
76
-
77
- def already_submitted_models(requested_models_dir: str) -> set[str]:
78
- """Gather a list of already submitted models to avoid duplicates"""
79
- depth = 1
80
- file_names = []
81
- users_to_submission_dates = defaultdict(list)
82
-
83
- for root, _, files in os.walk(requested_models_dir):
84
- current_depth = root.count(os.sep) - requested_models_dir.count(os.sep)
85
- if current_depth == depth:
86
- for file in files:
87
- if not file.endswith(".json"):
88
- continue
89
- with open(os.path.join(root, file), "r") as f:
90
- info = json.load(f)
91
- file_names.append(f"{info['model']}_{info['revision']}_{info['precision']}")
92
-
93
- # Select organisation
94
- if info["model"].count("/") == 0 or "submitted_time" not in info:
95
- continue
96
- organisation, _ = info["model"].split("/")
97
- users_to_submission_dates[organisation].append(info["submitted_time"])
98
-
99
- return set(file_names), users_to_submission_dates
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/submission/submit.py DELETED
@@ -1,119 +0,0 @@
1
- import json
2
- import os
3
- from datetime import datetime, timezone
4
-
5
- from src.display.formatting import styled_error, styled_message, styled_warning
6
- from src.envs import API, EVAL_REQUESTS_PATH, TOKEN, QUEUE_REPO
7
- from src.submission.check_validity import (
8
- already_submitted_models,
9
- check_model_card,
10
- get_model_size,
11
- is_model_on_hub,
12
- )
13
-
14
- REQUESTED_MODELS = None
15
- USERS_TO_SUBMISSION_DATES = None
16
-
17
- def add_new_eval(
18
- model: str,
19
- base_model: str,
20
- revision: str,
21
- precision: str,
22
- weight_type: str,
23
- model_type: str,
24
- ):
25
- global REQUESTED_MODELS
26
- global USERS_TO_SUBMISSION_DATES
27
- if not REQUESTED_MODELS:
28
- REQUESTED_MODELS, USERS_TO_SUBMISSION_DATES = already_submitted_models(EVAL_REQUESTS_PATH)
29
-
30
- user_name = ""
31
- model_path = model
32
- if "/" in model:
33
- user_name = model.split("/")[0]
34
- model_path = model.split("/")[1]
35
-
36
- precision = precision.split(" ")[0]
37
- current_time = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
38
-
39
- if model_type is None or model_type == "":
40
- return styled_error("Please select a model type.")
41
-
42
- # Does the model actually exist?
43
- if revision == "":
44
- revision = "main"
45
-
46
- # Is the model on the hub?
47
- # if weight_type in ["Delta", "Adapter"]:
48
- # base_model_on_hub, error, _ = is_model_on_hub(model_name=base_model, revision=revision, token=TOKEN, test_tokenizer=True)
49
- # if not base_model_on_hub:
50
- # return styled_error(f'Base model "{base_model}" {error}')
51
-
52
- # if not weight_type == "Adapter":
53
- # model_on_hub, error, _ = is_model_on_hub(model_name=model, revision=revision, token=TOKEN, test_tokenizer=True)
54
- # if not model_on_hub:
55
- # return styled_error(f'Model "{model}" {error}')
56
-
57
- # Is the model info correctly filled?
58
- try:
59
- model_info = API.model_info(repo_id=model, revision=revision)
60
- except Exception:
61
- return styled_error("Could not get your model information. Please fill it up properly.")
62
-
63
- model_size = get_model_size(model_info=model_info, precision=precision)
64
-
65
- # Were the model card and license filled?
66
- try:
67
- license = model_info.cardData["license"]
68
- except Exception:
69
- return styled_error("Please select a license for your model")
70
-
71
- modelcard_OK, error_msg = check_model_card(model)
72
- if not modelcard_OK:
73
- return styled_error(error_msg)
74
-
75
- # Seems good, creating the eval
76
- print("Adding new eval")
77
-
78
- eval_entry = {
79
- "model": model,
80
- "base_model": base_model,
81
- "revision": revision,
82
- "precision": precision,
83
- "weight_type": weight_type,
84
- "status": "PENDING",
85
- "submitted_time": current_time,
86
- "model_type": model_type,
87
- "likes": model_info.likes,
88
- "params": model_size,
89
- "license": license,
90
- "private": False,
91
- }
92
-
93
- # Check for duplicate submission
94
- if f"{model}_{revision}_{precision}" in REQUESTED_MODELS:
95
- return styled_warning("This model has been already submitted.")
96
-
97
- print("Creating eval file")
98
- OUT_DIR = f"{EVAL_REQUESTS_PATH}/{user_name}"
99
- os.makedirs(OUT_DIR, exist_ok=True)
100
- out_path = f"{OUT_DIR}/{model_path}_eval_request_False_{precision}_{weight_type}.json"
101
-
102
- with open(out_path, "w") as f:
103
- f.write(json.dumps(eval_entry))
104
-
105
- print("Uploading eval file")
106
- API.upload_file(
107
- path_or_fileobj=out_path,
108
- path_in_repo=out_path.split("eval-queue/")[1],
109
- repo_id=QUEUE_REPO,
110
- repo_type="dataset",
111
- commit_message=f"Add {model} to eval queue",
112
- )
113
-
114
- # Remove the local file
115
- os.remove(out_path)
116
-
117
- return styled_message(
118
- "Your request has been submitted to the evaluation queue!\nPlease wait for up to an hour for the model to show in the PENDING list."
119
- )