Ruslan commited on
Commit
55ece2a
·
1 Parent(s): 35cc04d

Clone Leaderboard

Browse files
app.py CHANGED
@@ -9,8 +9,10 @@ from src.about import (
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 (
@@ -21,7 +23,6 @@ from src.display.utils import (
21
  AutoEvalColumn,
22
  ModelType,
23
  fields,
24
- WeightType,
25
  Precision
26
  )
27
  from src.envs import API, EVAL_REQUESTS_PATH, EVAL_RESULTS_PATH, QUEUE_REPO, REPO_ID, RESULTS_REPO, TOKEN
@@ -34,14 +35,12 @@ def restart_space():
34
 
35
  ### Space initialisation
36
  try:
37
- print(EVAL_REQUESTS_PATH)
38
  snapshot_download(
39
  repo_id=QUEUE_REPO, local_dir=EVAL_REQUESTS_PATH, repo_type="dataset", tqdm_class=None, etag_timeout=30, token=TOKEN
40
  )
41
  except Exception:
42
  restart_space()
43
  try:
44
- print(EVAL_RESULTS_PATH)
45
  snapshot_download(
46
  repo_id=RESULTS_REPO, local_dir=EVAL_RESULTS_PATH, repo_type="dataset", tqdm_class=None, etag_timeout=30, token=TOKEN
47
  )
@@ -53,140 +52,160 @@ LEADERBOARD_DF = get_leaderboard_df(EVAL_RESULTS_PATH, EVAL_REQUESTS_PATH, COLS,
53
 
54
  (
55
  finished_eval_queue_df,
56
- running_eval_queue_df,
57
  pending_eval_queue_df,
58
  ) = get_evaluation_queue_df(EVAL_REQUESTS_PATH, EVAL_COLS)
59
 
60
  def init_leaderboard(dataframe):
61
  if dataframe is None or dataframe.empty:
62
  raise ValueError("Leaderboard DataFrame is empty or None.")
63
- return Leaderboard(
64
- value=dataframe,
65
- datatype=[c.type for c in fields(AutoEvalColumn)],
66
- select_columns=SelectColumns(
67
- default_selection=[c.name for c in fields(AutoEvalColumn) if c.displayed_by_default],
68
- cant_deselect=[c.name for c in fields(AutoEvalColumn) if c.never_hidden],
69
- label="Select Columns to Display:",
70
- ),
71
- search_columns=[AutoEvalColumn.model.name, AutoEvalColumn.license.name],
72
- hide_columns=[c.name for c in fields(AutoEvalColumn) if c.hidden],
73
- filter_columns=[
74
- ColumnFilter(AutoEvalColumn.model_type.name, type="checkboxgroup", label="Model types"),
75
- ColumnFilter(AutoEvalColumn.precision.name, type="checkboxgroup", label="Precision"),
76
- ColumnFilter(
77
- AutoEvalColumn.params.name,
78
- type="slider",
79
- min=0.01,
80
- max=150,
81
- label="Select the number of parameters (B)",
82
- ),
83
- ColumnFilter(
84
- AutoEvalColumn.still_on_hub.name, type="boolean", label="Deleted/incomplete", default=True
85
- ),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
  ],
87
- bool_checkboxgroup_label="Hide models",
88
- interactive=False,
89
  )
90
 
91
-
92
  demo = gr.Blocks(css=custom_css)
93
  with demo:
94
  gr.HTML(TITLE)
95
  gr.Markdown(INTRODUCTION_TEXT, elem_classes="markdown-text")
96
 
97
  with gr.Tabs(elem_classes="tab-buttons") as tabs:
98
- with gr.TabItem("🏅 LLM Benchmark", elem_id="llm-benchmark-tab-table", id=0):
99
- leaderboard = init_leaderboard(LEADERBOARD_DF)
100
 
101
- with gr.TabItem("📝 About", elem_id="llm-benchmark-tab-table", id=2):
102
- gr.Markdown(LLM_BENCHMARKS_TEXT, elem_classes="markdown-text")
103
 
104
- with gr.TabItem("🚀 Submit here! ", elem_id="llm-benchmark-tab-table", id=3):
105
- with gr.Column():
106
- with gr.Row():
107
- gr.Markdown(EVALUATION_QUEUE_TEXT, elem_classes="markdown-text")
108
-
109
- with gr.Column():
110
- with gr.Accordion(
111
- f"✅ Finished Evaluations ({len(finished_eval_queue_df)})",
112
- open=False,
113
- ):
114
- with gr.Row():
115
- finished_eval_table = gr.components.Dataframe(
116
- value=finished_eval_queue_df,
117
- headers=EVAL_COLS,
118
- datatype=EVAL_TYPES,
119
- row_count=5,
120
- )
121
- with gr.Accordion(
122
- f"🔄 Running Evaluation Queue ({len(running_eval_queue_df)})",
123
- open=False,
124
- ):
125
- with gr.Row():
126
- running_eval_table = gr.components.Dataframe(
127
- value=running_eval_queue_df,
128
- headers=EVAL_COLS,
129
- datatype=EVAL_TYPES,
130
- row_count=5,
131
- )
132
-
133
- with gr.Accordion(
134
- f"⏳ Pending Evaluation Queue ({len(pending_eval_queue_df)})",
135
- open=False,
136
- ):
137
- with gr.Row():
138
- pending_eval_table = gr.components.Dataframe(
139
- value=pending_eval_queue_df,
140
- headers=EVAL_COLS,
141
- datatype=EVAL_TYPES,
142
- row_count=5,
143
- )
144
- with gr.Row():
145
- gr.Markdown("# ✉️✨ Submit your model here!", elem_classes="markdown-text")
146
-
147
- with gr.Row():
148
- with gr.Column():
149
- model_name_textbox = gr.Textbox(label="Model name")
150
- revision_name_textbox = gr.Textbox(label="Revision commit", placeholder="main")
151
- model_type = gr.Dropdown(
152
- choices=[t.to_str(" : ") for t in ModelType if t != ModelType.Unknown],
153
- label="Model type",
154
- multiselect=False,
155
- value=None,
156
- interactive=True,
157
- )
158
-
159
- with gr.Column():
160
- precision = gr.Dropdown(
161
- choices=[i.value.name for i in Precision if i != Precision.Unknown],
162
- label="Precision",
163
- multiselect=False,
164
- value="float16",
165
- interactive=True,
166
- )
167
- weight_type = gr.Dropdown(
168
- choices=[i.value.name for i in WeightType],
169
- label="Weights type",
170
- multiselect=False,
171
- value="Original",
172
- interactive=True,
173
- )
174
- base_model_name_textbox = gr.Textbox(label="Base model (for delta or adapter weights)")
175
-
176
- submit_button = gr.Button("Submit Eval")
177
- submission_result = gr.Markdown()
178
- submit_button.click(
179
- add_new_eval,
180
- [
181
- model_name_textbox,
182
- base_model_name_textbox,
183
- revision_name_textbox,
184
- precision,
185
- weight_type,
186
- model_type,
187
- ],
188
- submission_result,
189
- )
190
 
191
  with gr.Row():
192
  with gr.Accordion("📙 Citation", open=False):
@@ -201,4 +220,4 @@ with demo:
201
  scheduler = BackgroundScheduler()
202
  scheduler.add_job(restart_space, "interval", seconds=1800)
203
  scheduler.start()
204
- demo.queue(default_concurrency_limit=40).launch()
 
9
  CITATION_BUTTON_TEXT,
10
  EVALUATION_QUEUE_TEXT,
11
  INTRODUCTION_TEXT,
12
+ ABOUT_TEXT,
13
  TITLE,
14
+ Training_Dataset,
15
+ Testing_Type
16
  )
17
  from src.display.css_html_js import custom_css
18
  from src.display.utils import (
 
23
  AutoEvalColumn,
24
  ModelType,
25
  fields,
 
26
  Precision
27
  )
28
  from src.envs import API, EVAL_REQUESTS_PATH, EVAL_RESULTS_PATH, QUEUE_REPO, REPO_ID, RESULTS_REPO, TOKEN
 
35
 
36
  ### Space initialisation
37
  try:
 
38
  snapshot_download(
39
  repo_id=QUEUE_REPO, local_dir=EVAL_REQUESTS_PATH, repo_type="dataset", tqdm_class=None, etag_timeout=30, token=TOKEN
40
  )
41
  except Exception:
42
  restart_space()
43
  try:
 
44
  snapshot_download(
45
  repo_id=RESULTS_REPO, local_dir=EVAL_RESULTS_PATH, repo_type="dataset", tqdm_class=None, etag_timeout=30, token=TOKEN
46
  )
 
52
 
53
  (
54
  finished_eval_queue_df,
 
55
  pending_eval_queue_df,
56
  ) = get_evaluation_queue_df(EVAL_REQUESTS_PATH, EVAL_COLS)
57
 
58
  def init_leaderboard(dataframe):
59
  if dataframe is None or dataframe.empty:
60
  raise ValueError("Leaderboard DataFrame is empty or None.")
61
+
62
+ with gr.Tabs(elem_classes="leaderboard-tabs") as leaderboard_tabs:
63
+ for testing_type in Testing_Type:
64
+ with gr.TabItem("Average Scores" if testing_type.value == "avg" else testing_type.name, elem_id=f"{testing_type.value}_Leaderboard"):
65
+ if testing_type.value == "avg":
66
+ gr.Markdown("The scores presented in this tab are averaged scores across all datasets.")
67
+
68
+ try:
69
+ leaderboard = Leaderboard(
70
+ value=dataframe[dataframe["Testing Type"] == testing_type.name],
71
+ datatype=[c.type for c in fields(AutoEvalColumn)],
72
+ select_columns=SelectColumns(
73
+ default_selection=[c.name for c in fields(AutoEvalColumn) if c.displayed_by_default],
74
+ cant_deselect=[c.name for c in fields(AutoEvalColumn) if c.never_hidden],
75
+ label="Select Columns to Display:",
76
+ ),
77
+ search_columns=[AutoEvalColumn.model_name.name],
78
+ hide_columns=[c.name for c in fields(AutoEvalColumn) if c.hidden],
79
+ filter_columns=[
80
+ ColumnFilter(AutoEvalColumn.precision.name, type="checkboxgroup", label="Precision"),
81
+ ColumnFilter(AutoEvalColumn.training_dataset_type.name, type="checkboxgroup", label="Training Dataset"),
82
+ ColumnFilter(
83
+ AutoEvalColumn.model_parameters.name,
84
+ type="slider",
85
+ min=0,
86
+ max=10000,
87
+ default=["0", "100"],
88
+ label="Select the number of parameters (M)",
89
+ ),
90
+ ],
91
+ bool_checkboxgroup_label="Hide Models",
92
+ interactive=False,
93
+ )
94
+ except:
95
+ gr.Markdown("There are no submissions for this testing type yet.")
96
+
97
+ def init_submissions():
98
+ with gr.Column():
99
+ with gr.Row():
100
+ gr.Markdown(EVALUATION_QUEUE_TEXT, elem_classes="markdown-text")
101
+
102
+ with gr.Column():
103
+ with gr.Accordion(
104
+ f"✅ Finished Evaluations ({len(finished_eval_queue_df)})",
105
+ open=False,
106
+ ):
107
+ with gr.Row():
108
+ finished_eval_table = gr.components.Dataframe(
109
+ value=finished_eval_queue_df,
110
+ headers=EVAL_COLS,
111
+ datatype=EVAL_TYPES,
112
+ row_count=5,
113
+ )
114
+
115
+ with gr.Accordion(
116
+ f"⏳ Pending Evaluation Queue ({len(pending_eval_queue_df)})",
117
+ open=False,
118
+ ):
119
+ with gr.Row():
120
+ pending_eval_table = gr.components.Dataframe(
121
+ value=pending_eval_queue_df,
122
+ headers=EVAL_COLS,
123
+ datatype=EVAL_TYPES,
124
+ row_count=5,
125
+ )
126
+
127
+ with gr.Row():
128
+ gr.Markdown("# ✉️✨ Submit your model here!", elem_classes="markdown-text")
129
+
130
+ with gr.Row():
131
+ with gr.Column():
132
+ model_name_textbox = gr.Textbox(label="Model name")
133
+ model_link_textbox = gr.Textbox(label="Link to Model")
134
+ model_backbone_textbox = gr.Dropdown(
135
+ choices=["Original"],
136
+ label="Model Backbone",
137
+ value="Original",
138
+ allow_custom_value=True,
139
+ )
140
+
141
+ model_parameter_number = gr.Number(label="Model Parameter Count (M)", precision=1, minimum=0)
142
+
143
+ precision = gr.Dropdown(
144
+ choices=[i.name for i in Precision],
145
+ label="Precision",
146
+ multiselect=False,
147
+ value="float32",
148
+ interactive=True,
149
+ )
150
+ paper_name_textbox = gr.Textbox(label="Paper Name")
151
+ paper_link_textbox = gr.Textbox(label="Link To Paper")
152
+
153
+
154
+ with gr.Column():
155
+ training_dataset = gr.Dropdown(
156
+ choices=[i.value for i in Training_Dataset if i.value != Training_Dataset.Other.value],
157
+ label="Training Dataset",
158
+ multiselect=False,
159
+ value=Training_Dataset.XCL.value,
160
+ interactive=True,
161
+ allow_custom_value=True,
162
+ )
163
+ testing_type = gr.Dropdown(
164
+ choices=[i.name for i in Testing_Type],
165
+ label="Tested on",
166
+ multiselect=False,
167
+ value=Testing_Type.AVG.name,
168
+ interactive=True,
169
+ )
170
+ cmap_value = gr.Number(label="cmAP Performance", precision=2, minimum=0.00, maximum=1.00, step=0.01)
171
+ auroc_value = gr.Number(label="AUROC Performance", precision=2, minimum=0.00, maximum=1.00, step=0.01)
172
+ t1acc_value = gr.Number(label="T1-Acc Performance", precision=2, minimum=0.00, maximum=1.00, step=0.01)
173
+
174
+ submit_button = gr.Button("Submit Eval")
175
+ submission_result = gr.Markdown()
176
+ submit_button.click(
177
+ fn=add_new_eval,
178
+ inputs=[
179
+ model_name_textbox,
180
+ model_link_textbox,
181
+ model_backbone_textbox,
182
+ precision,
183
+ model_parameter_number,
184
+ paper_name_textbox,
185
+ paper_link_textbox,
186
+ training_dataset,
187
+ testing_type,
188
+ cmap_value,
189
+ auroc_value,
190
+ t1acc_value,
191
  ],
192
+ outputs=submission_result,
 
193
  )
194
 
 
195
  demo = gr.Blocks(css=custom_css)
196
  with demo:
197
  gr.HTML(TITLE)
198
  gr.Markdown(INTRODUCTION_TEXT, elem_classes="markdown-text")
199
 
200
  with gr.Tabs(elem_classes="tab-buttons") as tabs:
201
+ with gr.TabItem("🏅 Leaderboard", elem_id="leaderboard-tab-table", id=0):
202
+ init_leaderboard(LEADERBOARD_DF)
203
 
204
+ with gr.TabItem("📝 About", elem_id="leaderboard-tab-table", id=2):
205
+ gr.Markdown(ABOUT_TEXT, elem_classes="markdown-text")
206
 
207
+ with gr.TabItem("🚀 Submit here! ", elem_id="leaderboard-tab-table", id=3):
208
+ init_submissions()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
209
 
210
  with gr.Row():
211
  with gr.Accordion("📙 Citation", open=False):
 
220
  scheduler = BackgroundScheduler()
221
  scheduler.add_job(restart_space, "interval", seconds=1800)
222
  scheduler.start()
223
+ demo.launch()
src/about.py CHANGED
@@ -1,9 +1,51 @@
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
 
@@ -11,62 +53,45 @@ class Task:
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("anli_r1", "acc", "ANLI")
16
- task1 = Task("logiqa", "acc_norm", "LogiQA")
 
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">Demo leaderboard</h1>"""
25
 
26
  # What does your leaderboard evaluate?
27
  INTRODUCTION_TEXT = """
28
- Intro text
29
  """
30
 
31
  # Which evaluations are you running? how can people reproduce what you have?
32
- LLM_BENCHMARKS_TEXT = f"""
33
- ## How it works
34
-
35
- ## Reproducibility
36
- To reproduce our results, here is the commands you can run:
37
-
 
 
38
  """
39
 
40
  EVALUATION_QUEUE_TEXT = """
41
- ## Some good practices before submitting a model
42
-
43
- ### 1) Make sure you can load your model and tokenizer using AutoClasses:
44
- ```python
45
- from transformers import AutoConfig, AutoModel, AutoTokenizer
46
- config = AutoConfig.from_pretrained("your model name", revision=revision)
47
- model = AutoModel.from_pretrained("your model name", revision=revision)
48
- tokenizer = AutoTokenizer.from_pretrained("your model name", revision=revision)
49
- ```
50
- If this step fails, follow the error messages to debug your model before submitting it. It's likely your model has been improperly uploaded.
51
 
52
- Note: make sure your model is public!
53
- 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!
54
 
55
- ### 2) Convert your model weights to [safetensors](https://huggingface.co/docs/safetensors/index)
56
- 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`!
57
-
58
- ### 3) Make sure your model has an open license!
59
- This is a leaderboard for Open LLMs, and we'd love for as many people as possible to know they can use your model 🤗
60
-
61
- ### 4) Fill up your model card
62
- When we add extra information about models to the leaderboard, it will be automatically taken from the model card
63
-
64
- ## In case of model failure
65
- If your model is displayed in the `FAILED` category, its execution stopped.
66
- Make sure you have followed the above steps first.
67
- If everything is done, check you can launch the EleutherAIHarness on your model locally, using the above command without modifications (you can add `--limit` to limit the number of examples per task).
68
  """
69
 
70
  CITATION_BUTTON_LABEL = "Copy the following snippet to cite these results"
71
- CITATION_BUTTON_TEXT = r"""
72
- """
 
1
  from dataclasses import dataclass
2
  from enum import Enum
3
 
4
+ class Model_Backbone(Enum):
5
+ Original = "Original"
6
+ Other = "Other"
7
+
8
+ def from_str(model_backbone: str):
9
+ if model_backbone == Model_Backbone.Original.value:
10
+ return Model_Backbone.Original
11
+ return Model_Backbone.Other
12
+
13
+ @classmethod
14
+ def format_for_leaderboard(cls, model_backbone: str):
15
+ return (cls.from_str(model_backbone), model_backbone)
16
+
17
+ class Training_Dataset(Enum):
18
+ XCL = "BirdSet (XCL)"
19
+ XCM = "BirdSet (XCM)"
20
+ Dedicated = "BirdSet (Dedicated)"
21
+ Other = "other"
22
+
23
+ def from_str(training_dataset: str):
24
+ if training_dataset in [Training_Dataset.Dedicated.value, Training_Dataset.Dedicated.name, "BirdSet - Dedicated", "dt", "DT"]:
25
+ return Training_Dataset.Dedicated
26
+ if training_dataset in [Training_Dataset.XCM.value, Training_Dataset.XCM.name, "BirdSet - XCM", "mt", "MT"]:
27
+ return Training_Dataset.XCM
28
+ if training_dataset in [Training_Dataset.XCL.value, Training_Dataset.XCL.name, "BirdSet - XCL", "lt", "LT"]:
29
+ return Training_Dataset.XCL
30
+ return Training_Dataset.Other
31
+
32
+ @classmethod
33
+ def format_for_leaderboard(cls, training_dataset: str):
34
+ return (cls.from_str(training_dataset), training_dataset)
35
+
36
+ class Testing_Type(Enum):
37
+ AVG = "avg"
38
+ PER = "per"
39
+ NES = "nes"
40
+ UHH = "uhh"
41
+ HSN = "hsn"
42
+ NBP = "nbp"
43
+ SSW = "ssw"
44
+ SNE = "sne"
45
+
46
+
47
  @dataclass
48
  class Task:
 
49
  metric: str
50
  col_name: str
51
 
 
53
  # Select your tasks here
54
  # ---------------------------------------------------
55
  class Tasks(Enum):
56
+ # metric_key in the json file, name to display in the leaderboard
57
+ cmap = Task("cmap", "cmAP")
58
+ auroc = Task("auroc", "AUROC")
59
+ t1acc = Task("t1-acc", "T1-Acc")
60
 
61
+ NUM_FEWSHOT = 0
62
  # ---------------------------------------------------
63
 
64
 
65
 
66
  # Your leaderboard name
67
+ TITLE = """<h1 align="center" id="space-title">BirdSet Leaderboard</h1>"""
68
 
69
  # What does your leaderboard evaluate?
70
  INTRODUCTION_TEXT = """
71
+ This leaderboard accompanies the [BirdSet Dataset Collection](https://huggingface.co/datasets/DBD-research-group/BirdSet). You can find out more about BirdSet in the \"About\" Tab.
72
  """
73
 
74
  # Which evaluations are you running? how can people reproduce what you have?
75
+ ABOUT_TEXT = f"""
76
+ ## What is BirdSet
77
+ Deep learning models have emerged as a powerful tool in avian bioacoustics to assess environmental health.
78
+ To maximize the potential of cost-effective and minimal-invasive passive acoustic monitoring (PAM), models must analyze bird vocalizations across a wide range of species and environmental conditions.
79
+ However, data fragmentation challenges a evaluation of generalization performance.
80
+ Therefore, we introduce the BirdSet dataset, comprising approximately 520,000 global bird recordings for training and over 400 hours PAM recordings for testing in a multi-label classification setting.
81
+
82
+ You can find the datasets on [Huggingface](https://huggingface.co/datasets/DBD-research-group/BirdSet) and the code on [Github](https://github.com/DBD-research-group/BirdSet).
83
  """
84
 
85
  EVALUATION_QUEUE_TEXT = """
86
+ ## How to Submit a Model
87
+ First you need to evaluate your model on the BirdSet dataset.
88
+ Then you can enter your evaluation information and submit a request.
89
+ We will then check your request and approve it if everything is alright.
 
 
 
 
 
 
90
 
91
+ Please make sure that you model is publicly available so that we can check you results.
 
92
 
93
+ If you want to submit an average over all datasets then choose \"AVG\" as \"Tested on\".
 
 
 
 
 
 
 
 
 
 
 
 
94
  """
95
 
96
  CITATION_BUTTON_LABEL = "Copy the following snippet to cite these results"
97
+ CITATION_BUTTON_TEXT = r""""""
 
src/display/formatting.py CHANGED
@@ -1,10 +1,10 @@
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):
 
1
+ def make_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 make_hyperlink(link, model_name)
8
 
9
 
10
  def styled_error(error):
src/display/utils.py CHANGED
@@ -23,22 +23,23 @@ class ColumnContent:
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)
@@ -46,11 +47,10 @@ AutoEvalColumn = make_dataclass("AutoEvalColumn", auto_eval_column_dict, frozen=
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
@@ -66,7 +66,7 @@ class ModelType(Enum):
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}"
@@ -81,27 +81,19 @@ class ModelType(Enum):
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
- Unknown = ModelDetails("?")
95
 
96
  def from_str(precision):
97
- if precision in ["torch.float16", "float16"]:
98
- return Precision.float16
99
- if precision in ["torch.bfloat16", "bfloat16"]:
100
- return Precision.bfloat16
101
- return Precision.Unknown
102
 
103
  # Column selection
104
- COLS = [c.name for c in fields(AutoEvalColumn) if not c.hidden]
105
 
106
  EVAL_COLS = [c.name for c in fields(EvalQueueColumn)]
107
  EVAL_TYPES = [c.type for c in fields(EvalQueueColumn)]
 
23
  ## Leaderboard columns
24
  auto_eval_column_dict = []
25
  # Init
26
+ #auto_eval_column_dict.append(["model_type_symbol", ColumnContent, ColumnContent("T", "markdown", True, never_hidden=True)])
27
+ auto_eval_column_dict.append(["model_name", ColumnContent, ColumnContent("Model Name", "markdown", True, never_hidden=True)])
28
+ auto_eval_column_dict.append(["paper", ColumnContent, ColumnContent("Paper", "markdown", False)])
29
+ auto_eval_column_dict.append(["training_dataset_type", ColumnContent, ColumnContent("Training Dataset Type", "markdown", False, hidden=True)])
30
+ auto_eval_column_dict.append(["training_dataset", ColumnContent, ColumnContent("Training Dataset", "markdown", True, never_hidden=True)])
31
  #Scores
 
32
  for task in Tasks:
33
  auto_eval_column_dict.append([task.name, ColumnContent, ColumnContent(task.value.col_name, "number", True)])
34
  # Model information
35
+ #auto_eval_column_dict.append(["model_type", ColumnContent, ColumnContent("Type", "markdown", False)])
36
+ auto_eval_column_dict.append(["model_backbone_type", ColumnContent, ColumnContent("Model Backbone Type", "markdown", False, hidden=True)])
37
+ auto_eval_column_dict.append(["model_backbone", ColumnContent, ColumnContent("Model Backbone", "str", True)])
38
+ auto_eval_column_dict.append(["precision", ColumnContent, ColumnContent("Precision", "markdown", False)])
39
+ auto_eval_column_dict.append(["model_parameters", ColumnContent, ColumnContent("Parameter Count", "markdown", False)])
40
+ auto_eval_column_dict.append(["model_link", ColumnContent, ColumnContent("Link To Model", "markdown", True)])
41
+ auto_eval_column_dict.append(["testing_type", ColumnContent, ColumnContent("Testing Type", "str", False, hidden=True)])
42
+
 
43
 
44
  # We use make dataclass to dynamically fill the scores from Tasks
45
  AutoEvalColumn = make_dataclass("AutoEvalColumn", auto_eval_column_dict, frozen=True)
 
47
  ## For the queue columns in the submission tab
48
  @dataclass(frozen=True)
49
  class EvalQueueColumn: # Queue column
50
+ model = ColumnContent("model", "str", True)
 
 
51
  precision = ColumnContent("precision", "str", True)
52
+ training_dataset = ColumnContent("training_dataset", "str", True)
53
+ testing_type = ColumnContent("testing_type", "str", True)
54
  status = ColumnContent("status", "str", True)
55
 
56
  ## All the model information that we might need
 
66
  FT = ModelDetails(name="fine-tuned", symbol="🔶")
67
  IFT = ModelDetails(name="instruction-tuned", symbol="⭕")
68
  RL = ModelDetails(name="RL-tuned", symbol="🟦")
69
+ Other = ModelDetails(name="Other", symbol="?")
70
 
71
  def to_str(self, separator=" "):
72
  return f"{self.value.symbol}{separator}{self.value.name}"
 
81
  return ModelType.RL
82
  if "instruction-tuned" in type or "⭕" in type:
83
  return ModelType.IFT
84
+ return ModelType.Other
 
 
 
 
 
85
 
86
  class Precision(Enum):
87
+ float32 = "float32"
88
+ Other = "Other"
 
89
 
90
  def from_str(precision):
91
+ if precision in ["torch.float32", "float32"]:
92
+ return Precision.float32
93
+ return Precision.Other
 
 
94
 
95
  # Column selection
96
+ COLS = [c.name for c in fields(AutoEvalColumn)]
97
 
98
  EVAL_COLS = [c.name for c in fields(EvalQueueColumn)]
99
  EVAL_TYPES = [c.type for c in fields(EvalQueueColumn)]
src/envs.py CHANGED
@@ -6,12 +6,12 @@ from huggingface_hub import HfApi
6
  # ----------------------------------
7
  TOKEN = os.environ.get("HF_TOKEN") # A read/write token for your org
8
 
9
- OWNER = "demo-leaderboard-backend" # Change to your org - don't forget to create a results and request dataset, with the correct format!
10
  # ----------------------------------
11
 
12
- REPO_ID = f"{OWNER}/leaderboard"
13
- QUEUE_REPO = f"{OWNER}/requests"
14
- RESULTS_REPO = f"{OWNER}/results"
15
 
16
  # If you setup a cache later, just change HF_HOME
17
  CACHE_PATH=os.getenv("HF_HOME", ".")
 
6
  # ----------------------------------
7
  TOKEN = os.environ.get("HF_TOKEN") # A read/write token for your org
8
 
9
+ OWNER = "DBD-research-group" # 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}/BirdSet-Leaderboard"
13
+ QUEUE_REPO = f"{OWNER}/Leaderboard-Requests"
14
+ RESULTS_REPO = f"{OWNER}/Leaderboard-Results"
15
 
16
  # If you setup a cache later, just change HF_HOME
17
  CACHE_PATH=os.getenv("HF_HOME", ".")
src/leaderboard/read_evals.py CHANGED
@@ -7,30 +7,31 @@ from dataclasses import dataclass
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):
@@ -40,118 +41,96 @@ class EvalResult:
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]:
@@ -163,12 +142,6 @@ def get_raw_eval_results(results_path: str, requests_path: str) -> list[EvalResu
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
 
@@ -178,12 +151,8 @@ def get_raw_eval_results(results_path: str, requests_path: str) -> list[EvalResu
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():
@@ -192,5 +161,5 @@ def get_raw_eval_results(results_path: str, requests_path: str) -> list[EvalResu
192
  results.append(v)
193
  except KeyError: # not all eval values present
194
  continue
195
-
196
  return results
 
7
  import dateutil
8
  import numpy as np
9
 
10
+ from src.display.formatting import make_hyperlink
11
+ from src.display.utils import AutoEvalColumn, ModelType, Tasks, Precision
12
+ from src.about import Model_Backbone, Training_Dataset, Testing_Type
13
 
14
 
15
  @dataclass
16
  class EvalResult:
 
17
  """
18
+ Represents one full evaluation. Built from a combination of the result and request file for a given run.
19
+ """
20
+ eval_name: str # model_training_testing_precision (identifier for evaluations)
21
+ model_name: str
22
+ training_dataset_type: Training_Dataset
23
+ training_dataset: str
24
+ testing_type: Testing_Type
25
  results: dict
26
+ paper_name: str = ""
27
+ model_link: str = ""
28
+ paper_link: str = ""
29
+ model_backbone_type: Model_Backbone = Model_Backbone.Other
30
+ model_backbone: str = ""
31
+ precision: Precision = Precision.Other
32
+ model_parameters: float = 0
33
+ model_type: ModelType = ModelType.Other # Pretrained, fine tuned, ...
34
  date: str = "" # submission date of request file
 
35
 
36
  @classmethod
37
  def init_from_json_file(self, json_filepath):
 
41
 
42
  config = data.get("config")
43
 
44
+ # Extract evaluation config
45
+ model_name = config["model_name"]
46
+ training_dataset_type = Training_Dataset.from_str(config["training_dataset"])
47
+ if training_dataset_type.name != Training_Dataset.Other.name:
48
+ training_dataset = training_dataset_type.value
 
 
 
 
 
 
49
  else:
50
+ training_dataset = config["training_dataset"]
51
+ testing_type = Testing_Type(config["testing_type"])
52
+ precision = Precision.from_str(config.get("model_dtype"))
53
+ eval_name = model_name + precision.value + training_dataset + testing_type.value
 
 
 
 
 
 
 
 
 
54
 
55
+ # Extract results
56
  results = {}
57
  for task in Tasks:
58
  task = task.value
59
+ results[task.metric] = data["results"].get(task.metric, -1)
 
 
 
 
 
 
 
60
 
61
  return self(
62
+ eval_name=eval_name,
63
+ model_name=model_name,
64
+ training_dataset_type=training_dataset_type,
65
+ training_dataset=training_dataset,
66
+ testing_type=testing_type,
67
+ precision=precision,
68
  results=results,
 
 
 
 
69
  )
70
 
71
  def update_with_request_file(self, requests_path):
72
  """Finds the relevant request file for the current model and updates info with it"""
73
+ if self.training_dataset_type.name != Training_Dataset.Other.name:
74
+ training_dataset_request = self.training_dataset_type.name
75
+ else:
76
+ training_dataset_request = self.training_dataset
77
+ training_dataset_request = "_".join(training_dataset_request.split())
78
+ request_file = get_request_file_for_model(requests_path, self.model_name, self.precision.value, training_dataset_request, self.testing_type.value)
79
 
80
  try:
81
  with open(request_file, "r") as f:
82
  request = json.load(f)
83
+ self.model_parameters = request.get("model_parameters", 0)
84
+ self.model_link = request.get("model_link", "None")
85
+ self.model_backbone = request.get("model_backbone", "Unknown")
86
+ self.model_backbone_type = Model_Backbone.from_str(self.model_backbone)
87
+ self.paper_name = request.get("paper_name", "None")
88
+ self.paper_link = request.get("paper_link", "None")
89
  self.model_type = ModelType.from_str(request.get("model_type", ""))
 
 
 
 
90
  self.date = request.get("submitted_time", "")
91
  except Exception:
92
+ print(f"Could not find request file for {self.model_name} with precision {self.precision.value}, training dataset {self.training_dataset} and testing type {self.testing_type.value}")
93
 
94
  def to_dict(self):
95
  """Converts the Eval Result to a dict compatible with our dataframe display"""
 
96
  data_dict = {
97
  "eval_name": self.eval_name, # not a column, just a save name,
98
+ AutoEvalColumn.precision.name: self.precision.value,
99
+ AutoEvalColumn.model_parameters.name: self.model_parameters,
100
+ AutoEvalColumn.model_name.name: self.model_name,
101
+ AutoEvalColumn.paper.name: make_hyperlink(self.paper_link, self.paper_name) if self.paper_link.startswith("http") else self.paper_name,
102
+ AutoEvalColumn.model_backbone_type.name: self.model_backbone_type.value,
103
+ AutoEvalColumn.model_backbone.name: self.model_backbone,
104
+ AutoEvalColumn.training_dataset_type.name: self.training_dataset_type.value,
105
+ AutoEvalColumn.training_dataset.name: self.training_dataset,
106
+ AutoEvalColumn.testing_type.name: self.testing_type.name,
107
+ AutoEvalColumn.model_link.name: self.model_link
 
 
108
  }
109
 
110
  for task in Tasks:
111
+ data_dict[task.value.col_name] = self.results[task.value.metric]
112
 
113
  return data_dict
114
 
115
 
116
+ def get_request_file_for_model(requests_path, model_name, precision, training_dataset, testing_type):
117
+ """Selects the correct request file for a given model if it's marked as FINISHED"""
118
+ request_filename = os.path.join(
119
  requests_path,
120
+ model_name,
121
+ f"{model_name}_eval_request_{precision}_{training_dataset}_{testing_type}.json",
122
  )
123
+
124
+ # check for request file
125
+ try:
126
+ with open(request_filename, "r") as file:
127
+ req_content = json.load(file)
128
+ if req_content["status"] not in ["FINISHED"]:
129
+ return None
130
+ except OSError:
131
+ return None
132
+
133
+ return request_filename
 
 
 
134
 
135
 
136
  def get_raw_eval_results(results_path: str, requests_path: str) -> list[EvalResult]:
 
142
  if len(files) == 0 or any([not f.endswith(".json") for f in files]):
143
  continue
144
 
 
 
 
 
 
 
145
  for file in files:
146
  model_result_filepaths.append(os.path.join(root, file))
147
 
 
151
  eval_result = EvalResult.init_from_json_file(model_result_filepath)
152
  eval_result.update_with_request_file(requests_path)
153
 
 
154
  eval_name = eval_result.eval_name
155
+ eval_results[eval_name] = eval_result
 
 
 
156
 
157
  results = []
158
  for v in eval_results.values():
 
161
  results.append(v)
162
  except KeyError: # not all eval values present
163
  continue
164
+
165
  return results
src/populate.py CHANGED
@@ -5,6 +5,7 @@ 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
 
@@ -14,11 +15,11 @@ def get_leaderboard_df(results_path: str, requests_path: str, cols: list, benchm
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
  return df
23
 
24
 
@@ -33,27 +34,28 @@ def get_evaluation_queue_df(save_path: str, cols: list) -> list[pd.DataFrame]:
33
  with open(file_path) as fp:
34
  data = json.load(fp)
35
 
36
- data[EvalQueueColumn.model.name] = make_clickable_model(data["model"])
37
- data[EvalQueueColumn.revision.name] = data.get("revision", "main")
 
 
38
 
39
  all_evals.append(data)
40
  elif ".md" not in entry:
41
  # this is a folder
42
- #sub_entries = [e for e in os.listdir(f"{save_path}/{entry}") if os.isfile(e) and not e.startswith(".")]
43
- sub_entries = []
44
  for sub_entry in sub_entries:
45
  file_path = os.path.join(save_path, entry, sub_entry)
46
  with open(file_path) as fp:
47
  data = json.load(fp)
48
 
49
- data[EvalQueueColumn.model.name] = make_clickable_model(data["model"])
50
- data[EvalQueueColumn.revision.name] = data.get("revision", "main")
 
 
51
  all_evals.append(data)
52
 
53
  pending_list = [e for e in all_evals if e["status"] in ["PENDING", "RERUN"]]
54
- running_list = [e for e in all_evals if e["status"] == "RUNNING"]
55
- finished_list = [e for e in all_evals if e["status"].startswith("FINISHED") or e["status"] == "PENDING_NEW_EVAL"]
56
  df_pending = pd.DataFrame.from_records(pending_list, columns=cols)
57
- df_running = pd.DataFrame.from_records(running_list, columns=cols)
58
  df_finished = pd.DataFrame.from_records(finished_list, columns=cols)
59
- return df_finished[cols], df_running[cols], df_pending[cols]
 
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.about import Tasks, Training_Dataset
9
  from src.leaderboard.read_evals import get_raw_eval_results
10
 
11
 
 
15
  all_data_json = [v.to_dict() for v in raw_data]
16
 
17
  df = pd.DataFrame.from_records(all_data_json)
 
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
+ df = df.sort_values(by=[Tasks.auroc.value.col_name, Tasks.cmap.value.col_name, Tasks.t1acc.value.col_name], ascending=False)
23
  return df
24
 
25
 
 
34
  with open(file_path) as fp:
35
  data = json.load(fp)
36
 
37
+ data[EvalQueueColumn.model.name] = data["model_name"]
38
+ data[EvalQueueColumn.precision.name] = data.get("precision", "other")
39
+ data[EvalQueueColumn.training_dataset.name] = Training_Dataset.from_str(data.get("training_dataset", "other")).value
40
+ data[EvalQueueColumn.testing_type.name] = data["testing_type"]
41
 
42
  all_evals.append(data)
43
  elif ".md" not in entry:
44
  # this is a folder
45
+ sub_entries = [e for e in os.listdir(f"{save_path}/{entry}") if not e.startswith(".")]
 
46
  for sub_entry in sub_entries:
47
  file_path = os.path.join(save_path, entry, sub_entry)
48
  with open(file_path) as fp:
49
  data = json.load(fp)
50
 
51
+ data[EvalQueueColumn.model.name] = data["model_name"]
52
+ data[EvalQueueColumn.precision.name] = data.get("precision", "other")
53
+ data[EvalQueueColumn.training_dataset.name] = Training_Dataset.from_str(data.get("training_dataset", "None"))
54
+ data[EvalQueueColumn.testing_type.name] = data["testing_type"]
55
  all_evals.append(data)
56
 
57
  pending_list = [e for e in all_evals if e["status"] in ["PENDING", "RERUN"]]
58
+ finished_list = [e for e in all_evals if e["status"].startswith("FINISHED")]
 
59
  df_pending = pd.DataFrame.from_records(pending_list, columns=cols)
 
60
  df_finished = pd.DataFrame.from_records(finished_list, columns=cols)
61
+ return df_finished[cols], df_pending[cols]
src/submission/check_validity.py CHANGED
@@ -1,84 +1,10 @@
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)
@@ -88,12 +14,6 @@ def already_submitted_models(requested_models_dir: str) -> set[str]:
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
 
1
  import json
2
  import os
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
 
4
  def already_submitted_models(requested_models_dir: str) -> set[str]:
5
  """Gather a list of already submitted models to avoid duplicates"""
6
  depth = 1
7
  file_names = []
 
8
 
9
  for root, _, files in os.walk(requested_models_dir):
10
  current_depth = root.count(os.sep) - requested_models_dir.count(os.sep)
 
14
  continue
15
  with open(os.path.join(root, file), "r") as f:
16
  info = json.load(f)
17
+ file_names.append(f"{info['model_name']}_{info['training_dataset']}_{info['testing_type']}_{info['precision']}")
 
 
 
 
 
 
18
 
19
+ return set(file_names)
src/submission/submit.py CHANGED
@@ -4,112 +4,91 @@ 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)
@@ -117,3 +96,5 @@ def add_new_eval(
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
  )
 
 
 
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 already_submitted_models
8
+ from src.about import Training_Dataset
9
+
 
 
 
10
 
11
  REQUESTED_MODELS = None
 
12
 
13
  def add_new_eval(
14
+ model_name : str = None,
15
+ model_link : str = None,
16
+ model_backbone : str = "Unknown",
17
+ precision : str = None,
18
+ model_parameters: float = 0,
19
+ paper_name: str = "None",
20
+ paper_link: str = "None",
21
+ training_dataset: str = "",
22
+ testing_type : str = None,
23
+ cmap_value : float = 0,
24
+ auroc_value : float = 0,
25
+ t1acc_value : float = 0,
26
  ):
27
+
28
  global REQUESTED_MODELS
 
29
  if not REQUESTED_MODELS:
30
+ REQUESTED_MODELS = already_submitted_models(EVAL_REQUESTS_PATH)
31
 
32
+ if model_name is None or model_name == "":
33
+ return styled_error("Please enter a model name")
34
+
35
+ if model_link is None or model_link == "":
36
+ return styled_error("Please provide a link to your model")
37
 
 
38
  current_time = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
39
 
40
+ training_dataset_type = Training_Dataset.from_str(training_dataset)
41
+ if training_dataset_type.name != Training_Dataset.Other.name:
42
+ training_dataset = training_dataset_type.name
 
 
 
 
 
 
 
 
 
43
 
44
+ training_dataset = "_".join(training_dataset.split())
45
+ model_name = "_".join(model_name.split())
46
+ testing_type = testing_type.lower()
 
47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
  print("Adding new eval")
49
 
50
  eval_entry = {
51
+ "model_name": model_name,
52
+ "model_link": model_link,
53
+ "model_backbone": model_backbone,
54
  "precision": precision,
55
+ "model_parameters": model_parameters,
56
+ "paper_name": paper_name,
57
+ "paper_link": paper_link,
58
  "status": "PENDING",
59
  "submitted_time": current_time,
60
+ "training_dataset": training_dataset,
61
+ "testing_type": testing_type,
62
+ "claimed_cmap": cmap_value,
63
+ "claimed_auroc": auroc_value,
64
+ "claimed_t1acc": t1acc_value
65
  }
66
 
67
+ if f"{model_name}_{training_dataset}_{testing_type}_{precision}" in REQUESTED_MODELS:
 
68
  return styled_warning("This model has been already submitted.")
69
 
70
  print("Creating eval file")
71
+ try:
72
+ OUT_DIR = f"{EVAL_REQUESTS_PATH}/{model_name}"
73
+ os.makedirs(OUT_DIR, exist_ok=True)
74
+ out_path = f"{OUT_DIR}/{model_name}_eval_request_{precision}_{training_dataset}_{testing_type}.json"
75
 
76
+ with open(out_path, "w") as f:
77
+ f.write(json.dumps(eval_entry))
78
+ except:
79
+ return styled_error("There was an error while creating your request. Make sure there are no \"/\" in your model name.")
80
 
81
  print("Uploading eval file")
82
+ try:
83
+ API.upload_file(
84
+ path_or_fileobj=out_path,
85
+ path_in_repo=out_path.split("eval-queue/")[1],
86
+ repo_id=QUEUE_REPO,
87
+ repo_type="dataset",
88
+ commit_message=f"Add {model_name}_{training_dataset}_{testing_type} to eval queue",
89
+ )
90
+ except:
91
+ return styled_error("There was an error while uploading your request.")
92
 
93
  # Remove the local file
94
  os.remove(out_path)
 
96
  return styled_message(
97
  "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."
98
  )
99
+
100
+