martinigoyanes commited on
Commit
883eeae
·
1 Parent(s): 5fc1f4b

initial commit

Browse files
.gitignore CHANGED
@@ -3,11 +3,14 @@ venv/
3
  __pycache__/
4
  .env
5
  .ipynb_checkpoints
6
- *ipynb
7
  .vscode/
 
8
 
9
  eval-queue/
10
  eval-results/
11
  eval-queue-bk/
12
  eval-results-bk/
13
  logs/
 
 
 
 
3
  __pycache__/
4
  .env
5
  .ipynb_checkpoints
 
6
  .vscode/
7
+ .idea
8
 
9
  eval-queue/
10
  eval-results/
11
  eval-queue-bk/
12
  eval-results-bk/
13
  logs/
14
+ data
15
+ contact_info.jsonl
16
+ .DS_Store
.pre-commit-config.yaml DELETED
@@ -1,53 +0,0 @@
1
- # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
2
- #
3
- # Licensed under the Apache License, Version 2.0 (the "License");
4
- # you may not use this file except in compliance with the License.
5
- # You may obtain a copy of the License at
6
- #
7
- # http://www.apache.org/licenses/LICENSE-2.0
8
- #
9
- # Unless required by applicable law or agreed to in writing, software
10
- # distributed under the License is distributed on an "AS IS" BASIS,
11
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- # See the License for the specific language governing permissions and
13
- # limitations under the License.
14
-
15
- default_language_version:
16
- python: python3
17
-
18
- ci:
19
- autofix_prs: true
20
- autoupdate_commit_msg: '[pre-commit.ci] pre-commit suggestions'
21
- autoupdate_schedule: quarterly
22
-
23
- repos:
24
- - repo: https://github.com/pre-commit/pre-commit-hooks
25
- rev: v4.3.0
26
- hooks:
27
- - id: check-yaml
28
- - id: check-case-conflict
29
- - id: detect-private-key
30
- - id: check-added-large-files
31
- args: ['--maxkb=1000']
32
- - id: requirements-txt-fixer
33
- - id: end-of-file-fixer
34
- - id: trailing-whitespace
35
-
36
- - repo: https://github.com/PyCQA/isort
37
- rev: 5.12.0
38
- hooks:
39
- - id: isort
40
- name: Format imports
41
-
42
- - repo: https://github.com/psf/black
43
- rev: 22.12.0
44
- hooks:
45
- - id: black
46
- name: Format code
47
- additional_dependencies: ['click==8.0.2']
48
-
49
- - repo: https://github.com/charliermarsh/ruff-pre-commit
50
- # Ruff version.
51
- rev: 'v0.0.267'
52
- hooks:
53
- - id: ruff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Makefile DELETED
@@ -1,13 +0,0 @@
1
- .PHONY: style format
2
-
3
-
4
- style:
5
- python -m black --line-length 119 .
6
- python -m isort .
7
- ruff check --fix .
8
-
9
-
10
- quality:
11
- python -m black --check --line-length 119 .
12
- python -m isort --check-only .
13
- ruff check .
 
 
 
 
 
 
 
 
 
 
 
 
 
 
README.md CHANGED
@@ -1,44 +1,20 @@
1
  ---
2
- title: Demo Leaderboard
3
- emoji: 🥇
4
- colorFrom: green
5
  colorTo: indigo
6
  sdk: gradio
7
  app_file: app.py
8
  pinned: true
9
  license: apache-2.0
 
 
10
  ---
11
 
12
- # Start the configuration
13
 
14
- Most of the variables to change for a default leaderboard are in `src/env.py` (replace the path for your leaderboard) and `src/about.py` (for tasks).
15
-
16
- Results files should have the following format and be stored as json files:
17
- ```json
18
- {
19
- "config": {
20
- "model_dtype": "torch.float16", # or torch.bfloat16 or 8bit or 4bit
21
- "model_name": "path of the model on the hub: org/model",
22
- "model_sha": "revision on the hub",
23
- },
24
- "results": {
25
- "task_name": {
26
- "metric_name": score,
27
- },
28
- "task_name2": {
29
- "metric_name": score,
30
- }
31
- }
32
- }
33
  ```
34
 
35
- Request files are created automatically by this tool.
36
-
37
- If you encounter problem on the space, don't hesitate to restart it to remove the create eval-queue, eval-queue-bk, eval-results and eval-results-bk created folder.
38
-
39
- # Code logic for more complex edits
40
-
41
- You'll find
42
- - the main table' columns names and properties in `src/display/utils.py`
43
- - the logic to read all results and request files, then convert them in dataframe lines, in `src/leaderboard/read_evals.py`, and `src/populate.py`
44
- - the logic to allow or filter submissions in `src/submission/submit.py` and `src/submission/check_validity.py`
 
1
  ---
2
+ title: Data Agents Benchmark Leaderboard
3
+ emoji: 🦾
4
+ colorFrom: yellow
5
  colorTo: indigo
6
  sdk: gradio
7
  app_file: app.py
8
  pinned: true
9
  license: apache-2.0
10
+ tags:
11
+ - leaderboard
12
  ---
13
 
14
+ to run
15
 
16
+ ```
17
+ gradio app.py
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
  ```
19
 
20
+ (assumes `HF_TOKEN` env var is set)
 
 
 
 
 
 
 
 
 
app.py CHANGED
@@ -1,204 +1,87 @@
 
1
  import gradio as gr
2
- from gradio_leaderboard import Leaderboard, ColumnFilter, SelectColumns
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
- 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
28
- from src.populate import get_evaluation_queue_df, get_leaderboard_df
29
- from src.submission.submit import add_new_eval
30
 
31
 
32
  def restart_space():
33
- API.restart_space(repo_id=REPO_ID)
34
-
35
- ### 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
- )
48
- except Exception:
49
- restart_space()
50
-
51
-
52
- LEADERBOARD_DF = get_leaderboard_df(EVAL_RESULTS_PATH, EVAL_REQUESTS_PATH, COLS, BENCHMARK_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):
193
- citation_button = gr.Textbox(
194
- value=CITATION_BUTTON_TEXT,
195
- label=CITATION_BUTTON_LABEL,
196
- lines=20,
197
- elem_id="citation-button",
198
- show_copy_button=True,
199
- )
200
 
201
- scheduler = BackgroundScheduler()
202
- scheduler.add_job(restart_space, "interval", seconds=1800)
203
- scheduler.start()
204
- demo.queue(default_concurrency_limit=40).launch()
 
1
+ import os
2
  import gradio as gr
 
 
 
 
3
 
4
+ from apscheduler.schedulers.background import BackgroundScheduler
5
+ from dabstep_benchmark.content import TITLE, INTRODUCTION_TEXT, SUBMISSION_TEXT, CITATION_BUTTON_TEXT, CITATION_BUTTON_LABEL
6
+ from dabstep_benchmark.leaderboard import *
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
 
8
 
9
  def restart_space():
10
+ HF_API.restart_space(repo_id=HF_LEADERBOARD)
11
+
12
+
13
+ if __name__ == "__main__":
14
+ os.makedirs("data/task_scores", exist_ok=True)
15
+ refresh(only_leaderboard=False)
16
+
17
+ demo = gr.Blocks()
18
+ with demo:
19
+ gr.Markdown(TITLE)
20
+ gr.Markdown(INTRODUCTION_TEXT, elem_classes="markdown-text")
21
+
22
+ leaderboard_table = gr.components.Dataframe(
23
+ value=generate_leaderboard_df(),
24
+ datatype=["markdown", "str", "str", "str", "markdown", "str", "str", "str"],
25
+ interactive=False,
26
+ column_widths=["20%"],
27
+ wrap=True,
28
+ )
29
+ # create a Gradio event listener that runs when the page is loaded to populate the dataframe
30
+ demo.load(lambda: generate_leaderboard_df(), None, leaderboard_table)
31
+
32
+ refresh_button = gr.Button("Refresh")
33
+ refresh_button.click(
34
+ refresh,
35
+ inputs=[
36
+ gr.Checkbox(value=True, visible=False)
37
+ ],
38
+ outputs=[
39
+ leaderboard_table,
40
+ ],
41
+ )
42
+ with gr.Row():
43
+ with gr.Accordion("📙 Citation", open=False):
44
+ citation_button = gr.Textbox(
45
+ value=CITATION_BUTTON_TEXT,
46
+ label=CITATION_BUTTON_LABEL,
47
+ lines=len(CITATION_BUTTON_TEXT.split("\n")),
48
+ elem_id="citation-button",
49
+ ) # .style(show_copy_button=True)
50
+
51
+ with gr.Accordion("Submit new agent answers for evaluation"):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
  with gr.Row():
53
+ gr.Markdown(SUBMISSION_TEXT, elem_classes="markdown-text")
 
54
  with gr.Row():
55
  with gr.Column():
56
+ split = gr.Radio(["all"], value="all", label="Split", visible=False)
57
+ agent_name_textbox = gr.Textbox(label="Agent name")
58
+ model_family_textbox = gr.Textbox(label="Model family")
59
+ system_prompt_textbox = gr.Textbox(label="System prompt example")
60
+ repo_url_textbox = gr.Textbox(label="Repo URL with agent code")
 
 
 
 
 
61
  with gr.Column():
62
+ organisation = gr.Textbox(label="Organisation")
63
+ mail = gr.Textbox(
64
+ label="Contact email (will be stored privately, & used if there is an issue with your submission)")
65
+ file_output = gr.File()
 
 
 
 
 
 
 
 
 
 
 
66
 
67
+ submit_button = gr.Button("Submit answers")
68
  submission_result = gr.Markdown()
69
  submit_button.click(
70
+ process_submission,
71
  [
72
+ split,
73
+ agent_name_textbox,
74
+ model_family_textbox,
75
+ repo_url_textbox,
76
+ file_output,
77
+ organisation,
78
+ mail
79
  ],
80
  submission_result,
81
  )
82
 
83
+ scheduler = BackgroundScheduler()
84
+ scheduler.add_job(restart_space, "interval", seconds=3600)
85
+ scheduler.start()
86
+ demo.launch(debug=True)
 
 
 
 
 
87
 
 
 
 
 
baseline/requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ -i https://pypi.org/simple
2
+ datasets
3
+ huggingface-hub
4
+ smolagents
5
+ litellm
6
+ tenacity
baseline/run.py ADDED
@@ -0,0 +1,194 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+
3
+ from opentelemetry import trace
4
+ from opentelemetry.sdk.trace import TracerProvider
5
+ from opentelemetry.sdk.trace.export import BatchSpanProcessor
6
+
7
+ from openinference.instrumentation.smolagents import SmolagentsInstrumentor
8
+ from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
9
+ from opentelemetry.sdk.trace.export import ConsoleSpanExporter, SimpleSpanProcessor
10
+
11
+ endpoint = "http://0.0.0.0:6006/v1/traces"
12
+ trace_provider = TracerProvider()
13
+ trace_provider.add_span_processor(SimpleSpanProcessor(OTLPSpanExporter(endpoint)))
14
+
15
+ SmolagentsInstrumentor().instrument(tracer_provider=trace_provider)
16
+
17
+ import argparse
18
+ import json
19
+ import logging
20
+ import os
21
+ import threading
22
+ import time
23
+ from concurrent.futures import ThreadPoolExecutor, as_completed
24
+ from pathlib import Path
25
+
26
+ import datasets
27
+ import pandas as pd
28
+ from data_agents_benchmark.utils import evaluate
29
+ from huggingface_hub import hf_hub_download
30
+ from smolagents import CodeAgent, LiteLLMModel
31
+ from smolagents.utils import console
32
+ from tenacity import retry, stop_after_attempt, wait_fixed, before_sleep_log, retry_if_exception_type, wait_exponential, wait_random
33
+ from tqdm import tqdm
34
+ import litellm
35
+
36
+
37
+ class TqdmLoggingHandler(logging.Handler):
38
+ def emit(self, record):
39
+ tqdm.write(self.format(record))
40
+
41
+ logging.basicConfig(level=logging.WARNING, handlers=[TqdmLoggingHandler()])
42
+ logger = logging.getLogger(__name__)
43
+
44
+ append_answer_lock = threading.Lock()
45
+ append_console_output_lock = threading.Lock()
46
+
47
+
48
+ def parse_args():
49
+ parser = argparse.ArgumentParser()
50
+ parser.add_argument("--concurrency", type=int, default=4)
51
+ parser.add_argument("--model-id", type=str, default="huggingface/meta-llama/Meta-Llama-3.1-70B-Instruct")
52
+ parser.add_argument("--max-tasks", type=int, default=-1)
53
+ parser.add_argument("--api-base", type=str, default=None)
54
+ parser.add_argument("--api-key", type=str, default=None)
55
+ parser.add_argument("--split", type=str, default="default", choices=["default", "dev"])
56
+ parser.add_argument("--timestamp", type=str, default=None)
57
+ return parser.parse_args()
58
+
59
+
60
+ def download_context(base_dir: str) -> str:
61
+ ctx_files = [
62
+ "data/context/acquirer_countries.csv",
63
+ "data/context/payments.csv",
64
+ "data/context/merchant_category_codes.csv",
65
+ "data/context/fees.json",
66
+ "data/context/merchant_data.json",
67
+ "data/context/manual.md",
68
+ "data/context/payments-readme.md"
69
+ ]
70
+ repo_id = "adyen/data-agents-benchmark"
71
+ for f in ctx_files:
72
+ hf_hub_download(repo_id, repo_type="dataset", filename=f, local_dir=base_dir, force_download=True)
73
+ return os.path.join(base_dir, Path(ctx_files[0]).parent)
74
+
75
+
76
+ def get_tasks_to_run(data, total: int, base_filename: Path):
77
+ import json
78
+ f = base_filename.parent / f"{base_filename.stem}_answers.jsonl"
79
+ done = set()
80
+ if f.exists():
81
+ with open(f, encoding="utf-8") as fh:
82
+ done = {json.loads(line)["task_id"] for line in fh if line.strip()}
83
+ return [data[i] for i in range(total) if str(data[i]["task_id"]) not in done]
84
+
85
+ def append_answer(entry: dict, jsonl_file: Path) -> None:
86
+ jsonl_file.parent.mkdir(parents=True, exist_ok=True)
87
+ with append_answer_lock, open(jsonl_file, "a", encoding="utf-8") as fp:
88
+ fp.write(json.dumps(entry) + "\n")
89
+
90
+
91
+ def append_console_output(captured_text: str, txt_file: Path) -> None:
92
+ txt_file.parent.mkdir(parents=True, exist_ok=True)
93
+ with append_console_output_lock, open(txt_file, "a", encoding="utf-8") as fp:
94
+ fp.write(captured_text + "\n")
95
+
96
+
97
+ class LiteLLMModelWithBackOff(LiteLLMModel):
98
+ @retry(
99
+ stop=stop_after_attempt(450),
100
+ wait=wait_exponential(min=1, max=120, exp_base=2, multiplier=1) + wait_random(0, 5),
101
+ before_sleep=before_sleep_log(logger, logging.WARNING),
102
+ retry=retry_if_exception_type((
103
+ litellm.Timeout,
104
+ litellm.RateLimitError,
105
+ litellm.APIConnectionError,
106
+ litellm.InternalServerError
107
+ ))
108
+ )
109
+ def __call__(self, *args, **kwargs):
110
+ return super().__call__(*args, **kwargs)
111
+
112
+ def create_code_agent(model_id: str, api_base=None, api_key=None, max_steps=10):
113
+ agent = CodeAgent(
114
+ tools=[],
115
+ model=LiteLLMModelWithBackOff(model_id=model_id, api_base=api_base, api_key=api_key),
116
+ additional_authorized_imports=["numpy", "pandas", "json", "csv", "glob", "markdown", "os"],
117
+ max_steps=max_steps,
118
+ )
119
+ def read_only_open(*a, **kw):
120
+ if (len(a) > 1 and isinstance(a[1], str) and a[1] != 'r') or kw.get('mode', 'r') != 'r':
121
+ raise Exception("Only mode='r' allowed for the function open")
122
+ return open(*a, **kw)
123
+
124
+ agent.python_executor.static_tools.update({"open": read_only_open})
125
+ return agent
126
+
127
+ def run_single_task(
128
+ task: dict,
129
+ model_id: str,
130
+ api_base: str,
131
+ api_key: str,
132
+ ctx_path: str,
133
+ base_filename: Path, # base file path WITHOUT suffix changes
134
+ is_dev_data: bool
135
+ ):
136
+ prompt = f"""You are an expert data analyst and you will answer factoid questions by referencing files in the data directory: `{ctx_path}`
137
+ Don't forget to reference any documentation in the data dir before answering a question.
138
+
139
+ Here is the question you need to answer: {task['question']}
140
+
141
+ Here are the guidelines you MUST follow when answering the question above: {task['guidelines']}
142
+
143
+ Before answering the question, reference any documentation in the data dir and leverage its information in your reasoning / planning.
144
+ """
145
+
146
+ agent = create_code_agent(model_id, api_base, api_key)
147
+ with console.capture() as capture:
148
+ answer = agent.run(prompt)
149
+
150
+
151
+ logger.warning(f"Task id: {task['task_id']}\tQuestion: {task['question']} Answer: {answer}\n{'=' * 50}")
152
+
153
+ answer_dict = {"task_id": str(task["task_id"]), "agent_answer": str(answer)}
154
+ answers_file = base_filename / "answers.jsonl"
155
+ logs_file = base_filename / "logs.txt"
156
+
157
+ if is_dev_data:
158
+ scores = evaluate(agent_answers=pd.DataFrame([answer_dict]), tasks_with_gt=pd.DataFrame([task]))
159
+ entry = {**answer_dict, "answer": task["answer"], "score": scores[0]["score"], "level": scores[0]["level"]}
160
+ append_answer(entry, answers_file)
161
+ else:
162
+ append_answer(answer_dict, answers_file)
163
+ append_console_output(capture.get(), logs_file)
164
+
165
+
166
+ def main():
167
+ args = parse_args()
168
+ logger.warning(f"Starting run with arguments: {args}")
169
+
170
+ ctx_path = download_context(str(Path().resolve()))
171
+
172
+ # We'll create a base filename with no special suffix, e.g. claude_123456789
173
+ runs_dir = Path().resolve() / "runs"
174
+ runs_dir.mkdir(parents=True, exist_ok=True)
175
+ timestamp = time.time() if not args.timestamp else args.timestamp
176
+ base_filename = runs_dir / f"{args.model_id.replace('/', '_').replace('.', '_')}/{args.split}/{int(timestamp)}"
177
+
178
+ # Load dataset with user-chosen split
179
+ data = datasets.load_dataset("adyen/data-agents-benchmark", name="tasks", split=args.split, download_mode='force_redownload')
180
+ total = len(data) if args.max_tasks < 0 else min(len(data), args.max_tasks)
181
+
182
+ tasks_to_run = get_tasks_to_run(data, total, base_filename)
183
+ with ThreadPoolExecutor(max_workers=args.concurrency) as exe:
184
+ futures = [
185
+ exe.submit(run_single_task, task, args.model_id, args.api_base, args.api_key, ctx_path, base_filename, (args.split == "dev"))
186
+ for task in tasks_to_run
187
+ ]
188
+ for f in tqdm(as_completed(futures), total=len(tasks_to_run), desc="Processing tasks"):
189
+ f.result()
190
+
191
+ logger.warning("All tasks processed.")
192
+
193
+ if __name__ == "__main__":
194
+ main()
dabstep_benchmark/__init__.py ADDED
File without changes
dabstep_benchmark/content.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ TITLE = """# 🏅 DABStep Leaderboard"""
2
+
3
+ INTRODUCTION_TEXT = """
4
+ The Data Agent Benchmark for Multi-step Reasoning (DABStep) is looking to measure and push the state-of-the-art in Data Analysis by LLMs.
5
+ The benchmark is composed of ~450 data analysis questions ([Dataset Link](https://huggingface.co/datasets/adyen/data-agents-benchmark)) centered around 1 or more documents that agents will have to understand and cross reference in order to answer correctly.
6
+
7
+ We have set up a notebook to quickly get an agent baseline using the free Huggingface Inference API: [Colab Notebook](https://colab.research.google.com/drive/1pXi5ffBFNJQ5nn1111SnIfjfKCOlunxu)
8
+ """
9
+
10
+ SUBMISSION_TEXT = """
11
+ ## Submissions
12
+ Scores are expressed as the percentage of correct answers.
13
+
14
+ Each question calls for an answer that is either a string (one or a few words), a number, or a comma separated list of strings or floats, unless specified otherwise. There is only one correct answer.
15
+ Hence, evaluation is done via quasi exact match between a model’s answer and the ground truth (up to some normalization that is tied to the “type” of the ground truth).
16
+
17
+
18
+ We expect submissions to be json-line files with the following format.
19
+ Mandatory fields are: `task_id` and `agent_answer`. However, `reasoning_trace` is optional:
20
+ ```
21
+ {"task_id": "task_id_1", "agent_answer": "Answer 1 from your agent", "reasoning_trace": "The different steps by which your model reached answer 1"}
22
+ {"task_id": "task_id_2", "agent_answer": "Answer 2 from your agent", "reasoning_trace": "The different steps by which your model reached answer 2"}
23
+ ```
24
+
25
+ Our scoring function can be found [here](https://huggingface.co/spaces/adyen/data-agents-benchmark/blob/main/data_agents_benchmark/evaluation/scorer.py).
26
+ """
27
+
28
+ CITATION_BUTTON_LABEL = "Copy the following snippet to cite these results"
29
+ CITATION_BUTTON_TEXT = r"""@misc{data_agents_benchmark_2025,
30
+ title={Data Agents Benchmark},
31
+ author={Martin Iglesias, Alex Egg, Friso Kingma},
32
+ year={2025},
33
+ month={January},
34
+ url={TBD}
35
+ }"""
dabstep_benchmark/evaluation/__init__.py ADDED
File without changes
dabstep_benchmark/evaluation/scorer.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ from typing import Union
3
+ import math
4
+ from difflib import SequenceMatcher
5
+
6
+ def is_numeric_with_commas(value: str) -> bool:
7
+ # Check if the string is a number with comma separators
8
+ return bool(re.match(r'^\$?(\d{1,3}(,\d{3})*(\.\d+)?|\.\d+)$', value.strip()))
9
+
10
+ def question_scorer(input1: str, input2: str) -> bool:
11
+ # Remove leading/trailing whitespace and convert to lowercase
12
+ input1 = input1.strip().lower()
13
+ input2 = input2.strip().lower()
14
+
15
+ # Check if inputs are numeric with commas
16
+ if is_numeric_with_commas(input1) or is_numeric_with_commas(input2):
17
+ num1 = extract_numeric(input1)
18
+ num2 = extract_numeric(input2)
19
+ return compare_numeric(num1, num2) if num1 is not None and num2 is not None else False
20
+
21
+ # Check for list match
22
+ if ';' in input1 or ';' in input2 or ',' in input1 or ',' in input2:
23
+ return compare_lists(input1, input2)
24
+
25
+ # Extract numeric values if present
26
+ num1 = extract_numeric(input1)
27
+ num2 = extract_numeric(input2)
28
+
29
+ # If both inputs have numeric values, compare them
30
+ if num1 is not None and num2 is not None:
31
+ return compare_numeric(num1, num2)
32
+
33
+ # Check for string match or subset
34
+ return compare_strings(input1, input2)
35
+
36
+ def extract_numeric(value: str) -> Union[float, None]:
37
+ # Remove commas and currency symbols from the value string
38
+ value = value.replace(',', '').replace('$', '')
39
+
40
+ # Extract the first occurrence of a numeric value (including percentages and leading decimal point)
41
+ match = re.search(r'(\d*\.\d+|\d+\.?\d*)%?', value)
42
+ if match:
43
+ num_str = match.group(1)
44
+
45
+ # @martini: now ground truths are expressed in % not in ratios anymore so no need for this
46
+ ## Handle percentages
47
+ # if '%' in value:
48
+ # try:
49
+ # return float(num_str) / 100
50
+ # except ValueError:
51
+ # return None
52
+ # else:
53
+ # try:
54
+ # return float(num_str)
55
+ # except ValueError:
56
+ # return None
57
+ try:
58
+ return float(num_str)
59
+ except ValueError:
60
+ return None
61
+ return None
62
+
63
+ def compare_numeric(num1: float, num2: float) -> bool:
64
+ # Check for exact equality first
65
+ if num1 == num2:
66
+ return True
67
+
68
+ # For percentages and small numbers, use a more lenient comparison
69
+ if num1 < 1 and num2 < 1:
70
+ return math.isclose(num1, num2, rel_tol=1e-2, abs_tol=1e-4)
71
+
72
+ # For larger numbers, use the original comparison method
73
+ dec_places1 = len(str(num1).split('.')[-1]) if '.' in str(num1) else 0
74
+ dec_places2 = len(str(num2).split('.')[-1]) if '.' in str(num2) else 0
75
+ round_to = min(dec_places1, dec_places2)
76
+ rounded1 = round(num1, round_to)
77
+ rounded2 = round(num2, round_to)
78
+
79
+ if rounded1 == rounded2:
80
+ return True
81
+
82
+ return math.isclose(num1, num2, rel_tol=1e-2, abs_tol=1e-2)
83
+
84
+ def compare_strings(str1: str, str2: str) -> bool:
85
+ # Remove all whitespace and punctuation
86
+ clean1 = re.sub(r'[^\w]', '', str1)
87
+ clean2 = re.sub(r'[^\w]', '', str2)
88
+
89
+ if clean1 == clean2:
90
+ return True
91
+
92
+ words1 = re.findall(r'\b\w+\b', str1.lower())
93
+ words2 = re.findall(r'\b\w+\b', str2.lower())
94
+
95
+ # Only do subset comparison if neither list is empty
96
+ if (len(words1) == 1 or len(words2) == 1) and words1 and words2:
97
+ return set(words1).issubset(set(words2)) or set(words2).issubset(set(words1))
98
+
99
+ # Debugging: Log similarity score
100
+ similarity = SequenceMatcher(None, str1, str2).ratio()
101
+
102
+ return similarity > 0.95
103
+
104
+ def compare_lists(list1: str, list2: str) -> bool:
105
+ # Normalize list representations by removing brackets
106
+ list1 = re.sub(r'^\[|\]$', '', list1.strip())
107
+ list2 = re.sub(r'^\[|\]$', '', list2.strip())
108
+
109
+ # Split the lists and remove whitespace
110
+ items1 = [item.strip() for item in re.split(r'[,;]', list1) if item.strip()]
111
+ items2 = [item.strip() for item in re.split(r'[,;]', list2) if item.strip()]
112
+
113
+ # Sort the items to handle different order
114
+ items1.sort()
115
+ items2.sort()
116
+
117
+ # Check if the lists are identical
118
+ if items1 == items2:
119
+ return True
120
+
121
+ # If lists are not identical, compare each item
122
+ if len(items1) != len(items2):
123
+ return False
124
+
125
+ for item1, item2 in zip(items1, items2):
126
+ if not question_scorer(item1, item2):
127
+ return False
128
+
129
+ return True
dabstep_benchmark/leaderboard.py ADDED
@@ -0,0 +1,310 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ import gradio as gr
3
+ import json
4
+ import datetime
5
+ from email.utils import parseaddr
6
+
7
+ import pandas as pd
8
+ from datasets import load_dataset
9
+ from huggingface_hub import HfApi
10
+
11
+ from dabstep_benchmark.utils import format_log, format_error, format_warning, is_valid_https_url, evaluate
12
+
13
+ OWNER = "adyen"
14
+
15
+ HF_API = HfApi()
16
+ HF_LEADERBOARD = f"{OWNER}/DABstep"
17
+ HF_DATASET_PATH = f"{OWNER}/DABstep"
18
+ HF_INTERNAL_DATASET_PATH = f"{OWNER}/DABstep-internal"
19
+ HF_DATASET_CONFIGS = [
20
+ "tasks",
21
+ "submissions",
22
+ "task_scores"
23
+ ]
24
+ DATASETS = {}
25
+
26
+ def refresh(only_leaderboard: bool = False):
27
+ if only_leaderboard:
28
+ for config_name in ["task_scores", "submissions"]:
29
+ DATASETS[f"{config_name}"] = load_dataset(
30
+ path=HF_DATASET_PATH,
31
+ name=config_name,
32
+ split="default",
33
+ )
34
+ print(f"Downloaded {HF_DATASET_PATH}/{config_name}")
35
+
36
+ else:
37
+ for config_name in HF_DATASET_CONFIGS:
38
+ DATASETS[f"{config_name}"] = load_dataset(
39
+ path=HF_DATASET_PATH,
40
+ name=config_name,
41
+ split="default",
42
+ )
43
+ print(f"Downloaded {HF_DATASET_PATH}/{config_name}")
44
+
45
+ DATASETS["internal_tasks"] = load_dataset(
46
+ path=HF_INTERNAL_DATASET_PATH,
47
+ name="tasks",
48
+ split="default",
49
+ )
50
+ print(f"Downloaded {HF_INTERNAL_DATASET_PATH}/tasks")
51
+ DATASETS["contact_info"] = load_dataset(
52
+ path=HF_INTERNAL_DATASET_PATH,
53
+ name="contact_info",
54
+ split="default",
55
+ )
56
+ print(f"Downloaded {HF_INTERNAL_DATASET_PATH}/contact_info")
57
+
58
+ return generate_leaderboard_df()
59
+
60
+
61
+ def validate_submission(submission_df: pd.DataFrame):
62
+ # mandatory_columns = ["agent_answer", "task_id", "num_steps"]
63
+ mandatory_columns = ["agent_answer", "task_id"]
64
+ expected_columns = [*mandatory_columns, "reasoning_trace"]
65
+
66
+ # Check for missing mandatory columns
67
+ missing_columns = [col for col in mandatory_columns if col not in submission_df.columns]
68
+ if missing_columns:
69
+ return format_error(f"Missing mandatory columns: {', '.join(missing_columns)}")
70
+
71
+ # Check for unexpected columns
72
+ unexpected_columns = [col for col in submission_df.columns if col not in expected_columns]
73
+ if unexpected_columns:
74
+ return format_error(f"Unexpected columns: {', '.join(unexpected_columns)}")
75
+
76
+ # Check for NaN values in any column
77
+ if submission_df.isnull().values.any():
78
+ return format_error("Submission contains NaN values. Please ensure no missing data.")
79
+
80
+ # Check if all columns are of string type
81
+ non_string_columns = [col for col in submission_df.columns if submission_df[col].dtype != 'object']
82
+ if non_string_columns:
83
+ return format_error(f"Columns with non-string data type: {', '.join(non_string_columns)}")
84
+
85
+ return None # No errors
86
+
87
+ def process_submission(
88
+ split: str,
89
+ agent_name: str,
90
+ model_family: str,
91
+ repo_url: str,
92
+ path_to_file: str,
93
+ organisation: str,
94
+ mail: str,
95
+ ):
96
+ if agent_name == "":
97
+ return format_warning("Please provide an agent name")
98
+ if organisation == "":
99
+ return format_warning("Please provide an organisation")
100
+ if mail == "":
101
+ return format_warning("Please provide an email")
102
+ if model_family == "":
103
+ return format_warning("Please provide a model family")
104
+
105
+ allowed_pattern = re.compile(r'^[a-zA-Z0-9 _.-]+$')
106
+ if not allowed_pattern.match(agent_name):
107
+ return format_warning(
108
+ f"{agent_name=} can only contain alphanumeric characters, spaces, dashes (-), and underscores (_)")
109
+
110
+ if not allowed_pattern.match(organisation):
111
+ return format_warning(
112
+ f"{organisation=} can only contain alphanumeric characters, spaces, dashes (-), and underscores (_)")
113
+
114
+
115
+ # very basic email parsing
116
+ _, parsed_mail = parseaddr(mail)
117
+ if not "@" in parsed_mail:
118
+ return format_warning("Please provide a valid email address.")
119
+
120
+ if repo_url != "" and not is_valid_https_url(repo_url):
121
+ return format_warning("If you provide a URL it must be a valid one. You can also leave it empty")
122
+
123
+ # submission file validation
124
+ if path_to_file == None:
125
+ return format_warning("Please attach a file.")
126
+ submission_path = path_to_file.name
127
+ try:
128
+ submission_df = pd.read_json(submission_path, lines=True, dtype=str)
129
+ validation_error = validate_submission(submission_df)
130
+ if validation_error:
131
+ return validation_error
132
+ except Exception as exc:
133
+ return format_error(f"Submission file is incorrectly formatted. Please fix it and resubmit your file. {str(exc)}")
134
+
135
+
136
+ print(f"Processing submission_id={organisation}-{agent_name}...")
137
+ gr.Info(f"Processing submission of {agent_name}...")
138
+ refresh(only_leaderboard=False)
139
+ submissions_df = DATASETS["submissions"].to_pandas()
140
+ contact_info_df = DATASETS["contact_info"].to_pandas()
141
+ internal_tasks_df = DATASETS["internal_tasks"].to_pandas()
142
+
143
+
144
+ # check if this agent already was submitted
145
+ submission_id = f"{organisation}-{agent_name}"
146
+ if submission_id in submissions_df['submission_id'].values:
147
+ return format_warning(f"This {submission_id} pair has been already submitted.")
148
+
149
+ # process submission
150
+ submission_df["submission_id"] = submission_id
151
+ submission_df["agent_name"] = agent_name
152
+ submission_df["model_family"] = model_family
153
+ submission_df["organisation"] = organisation
154
+ submission_df["repo_url"] = repo_url
155
+ submission_df["date"] = datetime.date.today().strftime("%d-%m-%Y")
156
+
157
+ # add empty reasoning trace if one is not provided to not break schema of datasets
158
+ if "reasoning_trace" not in submission_df.columns:
159
+ submission_df["reasoning_trace"] = ""
160
+
161
+ # overwrite submission
162
+ submission_df.to_json(submission_path, orient="records", lines=True)
163
+
164
+ try:
165
+ task_scores = evaluate(
166
+ agent_answers=submission_df,
167
+ tasks_with_gt=internal_tasks_df,
168
+ submission_id=submission_id
169
+ )
170
+ except KeyError as exc:
171
+ return format_error(str(exc))
172
+
173
+
174
+ # save submitted file once evaluation has run correctly
175
+ filename_id = f"v1__{organisation}-{agent_name}__{datetime.datetime.today().strftime('%d-%m-%Y')}"
176
+ path_in_repo = f"data/submissions/{filename_id}.jsonl"
177
+ HF_API.upload_file(
178
+ repo_id=HF_DATASET_PATH,
179
+ path_or_fileobj=submission_path,
180
+ path_in_repo=path_in_repo,
181
+ repo_type="dataset",
182
+ )
183
+ print(f"[submission_id={organisation}-{agent_name}] Pushed submission to {HF_DATASET_PATH}/{path_in_repo} !")
184
+
185
+ # write scores to disk
186
+ with open(f"data/task_scores/{filename_id}.jsonl", "w") as f:
187
+ for score in task_scores:
188
+ f.write(json.dumps(score) + "\n")
189
+
190
+ # upload scores to hub dataset
191
+ path_in_repo = f"data/task_scores/{filename_id}.jsonl"
192
+ HF_API.upload_file(
193
+ repo_id=HF_DATASET_PATH,
194
+ path_or_fileobj=f"data/task_scores/{filename_id}.jsonl",
195
+ path_in_repo=path_in_repo,
196
+ repo_type="dataset",
197
+ )
198
+ print(f"[submission_id={organisation}-{agent_name}] Pushed task_scores to {HF_DATASET_PATH}/{path_in_repo} !")
199
+
200
+ # if we already have this email dont save its metadata
201
+ if mail not in contact_info_df["mail"].values:
202
+ contact_info = {
203
+ "submission_id": submission_id,
204
+ "agent_name": agent_name,
205
+ "model_family": model_family,
206
+ "repo_url": repo_url,
207
+ "organisation": organisation,
208
+ "mail": mail,
209
+ "date": datetime.date.today().strftime("%d-%m-%Y"),
210
+ }
211
+ contact_info_df = pd.concat([contact_info_df, pd.DataFrame([contact_info])], ignore_index=True)
212
+ contact_info_df.to_json("contact_info.jsonl", orient="records", lines=True)
213
+
214
+ HF_API.upload_file(
215
+ repo_id=HF_INTERNAL_DATASET_PATH,
216
+ path_or_fileobj="contact_info.jsonl",
217
+ path_in_repo="contact_info.jsonl",
218
+ repo_type="dataset",
219
+ )
220
+ print(f"[submission_id={organisation}-{agent_name}] Pushed contact_info to {HF_INTERNAL_DATASET_PATH}/contact_info.jsonl !")
221
+
222
+
223
+ return format_log(
224
+ f"""
225
+ Agent {agent_name} submitted by {organisation} successfully.
226
+ Please refresh the leaderboard to see your score displayed.
227
+ """)
228
+
229
+ def generate_leaderboard_df() -> pd.DataFrame:
230
+ task_scores_df = DATASETS["task_scores"].to_pandas()
231
+ submissions_df = DATASETS["submissions"].to_pandas()
232
+
233
+ # get metadata of each submssion_id
234
+ submissions_df = (
235
+ submissions_df.groupby("submission_id")
236
+ .first()
237
+ .reset_index()[
238
+ [
239
+ "submission_id",
240
+ "agent_name",
241
+ "model_family",
242
+ "organisation",
243
+ "repo_url",
244
+ "date"
245
+ ]
246
+ ]
247
+ )
248
+
249
+ # make num_steps a number
250
+ # task_scores_df["num_steps"] = pd.to_numeric(task_scores_df["num_steps"], errors="coerce")
251
+
252
+ # group scores per submission
253
+ leaderboard_df = (
254
+ task_scores_df.groupby(["submission_id", "level"])
255
+ .agg(
256
+ avg_score=("score", "mean"),
257
+ # avg_num_steps=("num_steps", "mean")
258
+ )
259
+ .reset_index()
260
+ )
261
+
262
+ # reshape
263
+ # leaderboard_df = leaderboard_df.pivot(index="submission_id", columns="level", values=["avg_score", "avg_num_steps"])
264
+ leaderboard_df = leaderboard_df.pivot(index="submission_id", columns="level", values=["avg_score"])
265
+ leaderboard_df.columns = [f"{metric}_lvl_{level}" for metric, level in leaderboard_df.columns]
266
+ leaderboard_df = leaderboard_df.reset_index()
267
+
268
+ # leaderboard_df["overall_avg_steps"] = (
269
+ # leaderboard_df.get("avg_num_steps_lvl_1", 0) +
270
+ # leaderboard_df.get("avg_num_steps_lvl_2", 0) +
271
+ # leaderboard_df.get("avg_num_steps_lvl_3", 0)
272
+ # )
273
+ # leaderboard_df["overall_avg_steps"] = leaderboard_df["overall_avg_steps"] / 3
274
+
275
+ # join scores and submission metadata
276
+ leaderboard_df = pd.merge(submissions_df, leaderboard_df, on="submission_id", how="inner")
277
+
278
+ # renaming
279
+ col_map = {
280
+ "agent_name": "Agent",
281
+ "avg_score_lvl_easy": "Easy Level Accuracy (%)",
282
+ "avg_score_lvl_hard": "Hard Level Accuracy (%)",
283
+ # "overall_avg_steps": "Overall Avg Reasoning Steps",
284
+ # "avg_num_steps_lvl_1": "Level 1 Avg Reasoning Steps",
285
+ # "avg_num_steps_lvl_2": "Level 2 Avg Reasoning Steps",
286
+ # "avg_num_steps_lvl_3": "Level 3 Avg Reasoning Steps",
287
+ "organisation": "Organization",
288
+ "repo_url": "Repo URL",
289
+ "model_family": "Model Family",
290
+ "date": "Date"
291
+ }
292
+ col_order = [new_col_name for new_col_name in col_map.values()]
293
+ leaderboard_df.rename(columns=col_map, inplace=True)
294
+ df = leaderboard_df[col_order].copy()
295
+
296
+ # formatting
297
+ # convert scores to %
298
+ df["Easy Level Accuracy (%)"] = df["Easy Level Accuracy (%)"].apply(lambda x: round(x * 100, 2))
299
+ df["Hard Level Accuracy (%)"] = df["Hard Level Accuracy (%)"].apply(lambda x: round(x * 100, 2))
300
+
301
+ # make repo url clickable in markdown
302
+ df["Repo URL"] = df["Repo URL"].apply(lambda x: f"[Link]({x})" if x != "" else x)
303
+
304
+ # make agent name bold
305
+ df["Agent"] = df["Agent"].apply(lambda x: f"**{x}**")
306
+
307
+ # sort-by best score
308
+ df.sort_values(by="Hard Level Accuracy (%)", ascending=False, inplace=True)
309
+
310
+ return df
dabstep_benchmark/tests/__init__.py ADDED
File without changes
dabstep_benchmark/tests/test_scorer.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+ from ..evaluation.scorer import question_scorer
3
+
4
+ @pytest.mark.parametrize("input1, input2, expected", [
5
+ ("42", "42", True),
6
+ ("$42.00", "42", True),
7
+ ("43", "42", False),
8
+ ("10,765", "10765", True),
9
+ ("22520", "22520", True)
10
+ ])
11
+ def test_numeric_match(input1, input2, expected):
12
+ assert question_scorer(input1, input2) == expected
13
+
14
+ @pytest.mark.parametrize("input1, input2, expected", [
15
+ ("hello world", "Hello World", True),
16
+ (" sea gull ", "seagull", True),
17
+ ("hello", "world", False),
18
+ ("Other", "Other", True),
19
+ #("A. Netherlands", "B. Netherlands", False), #ignoring as outlier
20
+ ("", "Inditex", False),
21
+ (" ", "Inditex", False),
22
+ ("The average transaction amount is 91.85 EUR.", "91.852", True),
23
+ ("The top 2 merchants account for approx 59.96% of all transactions.", "0.5996", False),
24
+ ("Netherlands", "NL", False),
25
+ ("", "", True) # @martini
26
+ ])
27
+ def test_string_match(input1, input2, expected):
28
+ assert question_scorer(input1, input2) == expected
29
+
30
+ @pytest.mark.parametrize("input1, input2, expected", [
31
+ ("1, 2, 3", "1,2,3", True),
32
+ ("apple; banana; cherry", "apple;banana;cherry", True),
33
+ ("1, 2", "1, 2, 3", False),
34
+ ("apple; banana", "apple; banana; cherry", False),
35
+ ("uber, spotify, nike, netflix, inditex", "Nike, Netflix, Uber, Inditex, Spotify", True),
36
+ ("a, b, c", "['a', 'b', 'c']", True),
37
+ (
38
+ "C: 69.36, F: 77.90, B: 86.22, A: 87.79, D: 94.34, G: 115.23",
39
+ "[C: 69.36, F: 77.9, B: 86.22, A: 87.79, D: 94.34, G: 115.23]",
40
+ True
41
+ ),
42
+ (
43
+ "[BE: 85.3, IT: 93.82, FR: 98.57, NL: 99.87, LU: 111.42, SE: 114.36, ES: 134.41, GR: 169.92, ]",
44
+ "BE: 85.3, IT: 93.82, FR: 98.57, NL: 99.87, LU: 111.42, SE: 114.36, ES: 134.41, GR: 169.92",
45
+ True
46
+ )
47
+ ])
48
+ def test_list_match(input1, input2, expected):
49
+ assert question_scorer(input1, input2) == expected
50
+
51
+ @pytest.mark.parametrize("input1, input2, expected", [
52
+ ("42, hello", "42, hello", True),
53
+ ("42, world", "42, hello", False),
54
+ ])
55
+ def test_mixed_list_match(input1, input2, expected):
56
+ assert question_scorer(input1, input2) == expected
57
+
58
+ @pytest.mark.parametrize("input1, input2, expected", [
59
+ ("3.14", "3.1483", True),
60
+ ("3.14", "3.20", False),
61
+ ("1", "1.0", True),
62
+ ("1.0", "1", True),
63
+ ("0.731495413640441", "0.731495", True),
64
+ ("C", "C) both ip_address and email_address", True),
65
+ ("0.36706256984345176", "0.3670625698434518", True),
66
+ ("$0.10", "$0.10 per retry", True),
67
+ ("D", "D) Apples", True),
68
+ ("D", "A) Oranges", False),
69
+ ("25.0", "0.250", False) #input is not a percentage
70
+ ])
71
+ def test_approximate_numeric_match(input1, input2, expected):
72
+ assert question_scorer(input1, input2) == expected
73
+
74
+ @pytest.mark.parametrize("input1, input2, expected", [
75
+ ("73.15%", "73.1495", True),
76
+ ("42%", "42", True),
77
+ ("30%", "30.1", True),
78
+ ("25", "25%", True),
79
+ ("100%", "100", True),
80
+ ("0.1%", "0.1", True),
81
+ ("73%", "74", False), # This should fail as the difference is too large
82
+ ("90%", "89.99971063977545", True),
83
+ ("7.79%", "7.787407043027865", True)
84
+ # ("7.787407 %", "0.07787407043027865", True) #TODO FIX
85
+
86
+ ])
87
+ def test_percentages_match(input1, input2, expected):
88
+ assert question_scorer(input1, input2) == expected
89
+
90
+
dabstep_benchmark/utils.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ import pandas as pd
3
+ from dabstep_benchmark.evaluation.scorer import question_scorer
4
+
5
+
6
+ def format_error(msg):
7
+ return f"<p style='color: red; font-size: 20px; text-align: center;'>{msg}</p>"
8
+
9
+ def format_warning(msg):
10
+ return f"<p style='color: orange; font-size: 20px; text-align: center;'>{msg}</p>"
11
+
12
+ def format_log(msg):
13
+ return f"<p style='color: green; font-size: 20px; text-align: center;'>{msg}</p>"
14
+
15
+ def model_hyperlink(link, model_name):
16
+ return f'<a target="_blank" href="{link}" style="color: var(--link-text-color); text-decoration: underline;text-decoration-style: dotted;">{model_name}</a>'
17
+
18
+ def is_valid_https_url(url):
19
+ pattern = re.compile(
20
+ r'^https://' # URL must start with 'https://'
21
+ r'(?!10(?:\.\d{1,3}){3})' # Exclude private IP 10.x.x.x
22
+ r'(?!127(?:\.\d{1,3}){3})' # Exclude loopback IP 127.x.x.x
23
+ r'(?!169\.254(?:\.\d{1,3}){2})' # Exclude link-local IP 169.254.x.x
24
+ r'(?!192\.168(?:\.\d{1,3}){2})' # Exclude private IP 192.168.x.x
25
+ r'(?!172\.(?:1[6-9]|2[0-9]|3[0-1])(?:\.\d{1,3}){2})' # Exclude private IP 172.16.x.x - 172.31.x.x
26
+ r'(?:(?:[a-zA-Z0-9-]+\.)+[a-zA-Z]{2,})' # Match domain name
27
+ r'(?::\d{2,5})?' # Optional port
28
+ r'(?:/[^\s]*)?$', # Optional path
29
+ re.IGNORECASE
30
+ )
31
+ return re.match(pattern, url) is not None
32
+
33
+
34
+ def evaluate(agent_answers: pd.DataFrame, tasks_with_gt: pd.DataFrame, submission_id: str = ""):
35
+ task_scores = []
36
+ for index, row in tasks_with_gt.iterrows():
37
+ correct_answer = row["answer"]
38
+ level = str(row["level"])
39
+ task_id = str(row["task_id"])
40
+
41
+ if task_id not in agent_answers["task_id"].values:
42
+ raise KeyError(f"Task ID: {task_id} not found. Are you sure you submitted the correct file?")
43
+
44
+ agent_answer = agent_answers.loc[agent_answers.task_id == task_id, "agent_answer"].values[0]
45
+ # num_steps = agent_answers.loc[agent_answers.task_id == task_id, "num_steps"].values[0]
46
+ score = question_scorer(agent_answer, correct_answer)
47
+
48
+ task_scores.append(
49
+ {
50
+ "submission_id": submission_id,
51
+ "task_id": task_id,
52
+ "score": score,
53
+ "level": level,
54
+ "agent_answer": agent_answer,
55
+ # "num_steps": num_steps,
56
+ }
57
+ )
58
+
59
+ return task_scores
pyproject.toml DELETED
@@ -1,13 +0,0 @@
1
- [tool.ruff]
2
- # Enable pycodestyle (`E`) and Pyflakes (`F`) codes by default.
3
- select = ["E", "F"]
4
- ignore = ["E501"] # line too long (black is taking care of this)
5
- line-length = 119
6
- fixable = ["A", "B", "C", "D", "E", "F", "G", "I", "N", "Q", "S", "T", "W", "ANN", "ARG", "BLE", "COM", "DJ", "DTZ", "EM", "ERA", "EXE", "FBT", "ICN", "INP", "ISC", "NPY", "PD", "PGH", "PIE", "PL", "PT", "PTH", "PYI", "RET", "RSE", "RUF", "SIM", "SLF", "TCH", "TID", "TRY", "UP", "YTT"]
7
-
8
- [tool.isort]
9
- profile = "black"
10
- line_length = 119
11
-
12
- [tool.black]
13
- line-length = 119
 
 
 
 
 
 
 
 
 
 
 
 
 
 
requirements.txt CHANGED
@@ -1,16 +1,6 @@
1
- APScheduler
2
- black
3
  datasets
4
- gradio
5
- gradio[oauth]
6
- gradio_leaderboard==0.0.9
7
- gradio_client
8
- huggingface-hub>=0.18.0
9
- matplotlib
10
  numpy
11
- pandas
12
- python-dateutil
13
- tqdm
14
- transformers
15
- tokenizers>=0.15.0
16
- sentencepiece
 
 
 
1
  datasets
2
+ huggingface-hub
 
 
 
 
 
3
  numpy
4
+ fastapi==0.112.2
5
+ gradio==5.0.0b1
6
+ APScheduler
 
 
 
setup.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from setuptools import setup, find_packages
2
+
3
+ # Read dependencies from requirements.txt
4
+ def parse_requirements(filename):
5
+ not_needed_deps = [
6
+ "fastapi==0.112.2",
7
+ "gradio==5.0.0b1",
8
+ "APScheduler",
9
+ ]
10
+ dependencies = []
11
+ with open(filename) as f:
12
+ for line in f:
13
+ dep_name = line.strip()
14
+ if dep_name not in not_needed_deps:
15
+ dependencies.append(dep_name)
16
+ return dependencies
17
+
18
+ setup(
19
+ name="DABstep Benchmark",
20
+ version="0.1.0",
21
+ description="DABstep: Data Agent Benchmark for Multi-Step Reasoning",
22
+ long_description=open("README.md").read(),
23
+ long_description_content_type="text/markdown",
24
+ author="Martin Iglesias, Alex Egg, Andreu Mora, Friso Kingma, Leandro von Werra",
25
+ author_email="[email protected]",
26
+ packages=find_packages(include=["dabstep_benchmark", "dabstep_benchmark.*"]),
27
+ include_package_data=True,
28
+ install_requires=parse_requirements("requirements.txt"),
29
+ classifiers=[
30
+ "Programming Language :: Python :: 3",
31
+ "License :: OSI Approved :: MIT License",
32
+ "Operating System :: OS Independent",
33
+ ],
34
+ )
src/about.py DELETED
@@ -1,72 +0,0 @@
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("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
- """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/display/css_html_js.py DELETED
@@ -1,105 +0,0 @@
1
- custom_css = """
2
-
3
- .markdown-text {
4
- font-size: 16px !important;
5
- }
6
-
7
- #models-to-add-text {
8
- font-size: 18px !important;
9
- }
10
-
11
- #citation-button span {
12
- font-size: 16px !important;
13
- }
14
-
15
- #citation-button textarea {
16
- font-size: 16px !important;
17
- }
18
-
19
- #citation-button > label > button {
20
- margin: 6px;
21
- transform: scale(1.3);
22
- }
23
-
24
- #leaderboard-table {
25
- margin-top: 15px
26
- }
27
-
28
- #leaderboard-table-lite {
29
- margin-top: 15px
30
- }
31
-
32
- #search-bar-table-box > div:first-child {
33
- background: none;
34
- border: none;
35
- }
36
-
37
- #search-bar {
38
- padding: 0px;
39
- }
40
-
41
- /* Limit the width of the first AutoEvalColumn so that names don't expand too much */
42
- table td:first-child,
43
- table th:first-child {
44
- max-width: 400px;
45
- overflow: auto;
46
- white-space: nowrap;
47
- }
48
-
49
- .tab-buttons button {
50
- font-size: 20px;
51
- }
52
-
53
- #scale-logo {
54
- border-style: none !important;
55
- box-shadow: none;
56
- display: block;
57
- margin-left: auto;
58
- margin-right: auto;
59
- max-width: 600px;
60
- }
61
-
62
- #scale-logo .download {
63
- display: none;
64
- }
65
- #filter_type{
66
- border: 0;
67
- padding-left: 0;
68
- padding-top: 0;
69
- }
70
- #filter_type label {
71
- display: flex;
72
- }
73
- #filter_type label > span{
74
- margin-top: var(--spacing-lg);
75
- margin-right: 0.5em;
76
- }
77
- #filter_type label > .wrap{
78
- width: 103px;
79
- }
80
- #filter_type label > .wrap .wrap-inner{
81
- padding: 2px;
82
- }
83
- #filter_type label > .wrap .wrap-inner input{
84
- width: 1px
85
- }
86
- #filter-columns-type{
87
- border:0;
88
- padding:0.5;
89
- }
90
- #filter-columns-size{
91
- border:0;
92
- padding:0.5;
93
- }
94
- #box-filter > .form{
95
- border: 0
96
- }
97
- """
98
-
99
- get_window_url_params = """
100
- function(url_params) {
101
- const params = new URLSearchParams(window.location.search);
102
- url_params = Object.fromEntries(params);
103
- return url_params;
104
- }
105
- """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/display/formatting.py DELETED
@@ -1,27 +0,0 @@
1
- def model_hyperlink(link, model_name):
2
- return f'<a target="_blank" href="{link}" style="color: var(--link-text-color); text-decoration: underline;text-decoration-style: dotted;">{model_name}</a>'
3
-
4
-
5
- def make_clickable_model(model_name):
6
- link = f"https://huggingface.co/{model_name}"
7
- return model_hyperlink(link, model_name)
8
-
9
-
10
- def styled_error(error):
11
- return f"<p style='color: red; font-size: 20px; text-align: center;'>{error}</p>"
12
-
13
-
14
- def styled_warning(warn):
15
- return f"<p style='color: orange; font-size: 20px; text-align: center;'>{warn}</p>"
16
-
17
-
18
- def styled_message(message):
19
- return f"<p style='color: green; font-size: 20px; text-align: center;'>{message}</p>"
20
-
21
-
22
- def has_no_nan_values(df, columns):
23
- return df[columns].notna().all(axis=1)
24
-
25
-
26
- def has_nan_values(df, columns):
27
- return df[columns].isna().any(axis=1)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/display/utils.py DELETED
@@ -1,110 +0,0 @@
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
- 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)]
108
-
109
- BENCHMARK_COLS = [t.value.col_name for t in Tasks]
110
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/envs.py DELETED
@@ -1,25 +0,0 @@
1
- import os
2
-
3
- from huggingface_hub import HfApi
4
-
5
- # Info to change for your repository
6
- # ----------------------------------
7
- TOKEN = os.environ.get("HF_TOKEN") # A read/write token for your org
8
-
9
- OWNER = "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", ".")
18
-
19
- # Local caches
20
- EVAL_REQUESTS_PATH = os.path.join(CACHE_PATH, "eval-queue")
21
- EVAL_RESULTS_PATH = os.path.join(CACHE_PATH, "eval-results")
22
- EVAL_REQUESTS_PATH_BACKEND = os.path.join(CACHE_PATH, "eval-queue-bk")
23
- EVAL_RESULTS_PATH_BACKEND = os.path.join(CACHE_PATH, "eval-results-bk")
24
-
25
- API = HfApi(token=TOKEN)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/leaderboard/read_evals.py 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 DELETED
@@ -1,58 +0,0 @@
1
- import json
2
- import os
3
-
4
- import pandas as pd
5
-
6
- from src.display.formatting import has_no_nan_values, make_clickable_model
7
- from src.display.utils import AutoEvalColumn, EvalQueueColumn
8
- from src.leaderboard.read_evals import get_raw_eval_results
9
-
10
-
11
- def get_leaderboard_df(results_path: str, requests_path: str, cols: list, benchmark_cols: list) -> pd.DataFrame:
12
- """Creates a dataframe from all the individual experiment results"""
13
- raw_data = get_raw_eval_results(results_path, requests_path)
14
- all_data_json = [v.to_dict() for v in raw_data]
15
-
16
- df = pd.DataFrame.from_records(all_data_json)
17
- df = df.sort_values(by=[AutoEvalColumn.average.name], ascending=False)
18
- df = df[cols].round(decimals=2)
19
-
20
- # filter out if any of the benchmarks have not been produced
21
- df = df[has_no_nan_values(df, benchmark_cols)]
22
- return df
23
-
24
-
25
- def get_evaluation_queue_df(save_path: str, cols: list) -> list[pd.DataFrame]:
26
- """Creates the different dataframes for the evaluation queues requestes"""
27
- entries = [entry for entry in os.listdir(save_path) if not entry.startswith(".")]
28
- all_evals = []
29
-
30
- for entry in entries:
31
- if ".json" in entry:
32
- file_path = os.path.join(save_path, entry)
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 not e.startswith(".")]
43
- for sub_entry in sub_entries:
44
- file_path = os.path.join(save_path, entry, sub_entry)
45
- with open(file_path) as fp:
46
- data = json.load(fp)
47
-
48
- data[EvalQueueColumn.model.name] = make_clickable_model(data["model"])
49
- data[EvalQueueColumn.revision.name] = data.get("revision", "main")
50
- all_evals.append(data)
51
-
52
- pending_list = [e for e in all_evals if e["status"] in ["PENDING", "RERUN"]]
53
- running_list = [e for e in all_evals if e["status"] == "RUNNING"]
54
- finished_list = [e for e in all_evals if e["status"].startswith("FINISHED") or e["status"] == "PENDING_NEW_EVAL"]
55
- df_pending = pd.DataFrame.from_records(pending_list, columns=cols)
56
- df_running = pd.DataFrame.from_records(running_list, columns=cols)
57
- df_finished = pd.DataFrame.from_records(finished_list, columns=cols)
58
- return df_finished[cols], df_running[cols], df_pending[cols]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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=False, test_tokenizer=False) -> tuple[bool, str]:
35
- """Checks if the model model_name is on the hub, and whether it (and its tokenizer) can be loaded with AutoClasses."""
36
- try:
37
- config = AutoConfig.from_pretrained(model_name, revision=revision, trust_remote_code=trust_remote_code, token=token)
38
- if test_tokenizer:
39
- try:
40
- tk = AutoTokenizer.from_pretrained(model_name, revision=revision, trust_remote_code=trust_remote_code, token=token)
41
- except ValueError as e:
42
- return (
43
- False,
44
- f"uses a tokenizer which is not in a transformers release: {e}",
45
- None
46
- )
47
- except Exception as e:
48
- return (False, "'s tokenizer cannot be loaded. Is your tokenizer class in a stable transformers release, and correctly configured?", None)
49
- return True, None, config
50
-
51
- except ValueError:
52
- return (
53
- False,
54
- "needs to be launched with `trust_remote_code=True`. For safety reason, we do not allow these models to be automatically submitted to the leaderboard.",
55
- None
56
- )
57
-
58
- except Exception as e:
59
- return False, "was not found on hub!", None
60
-
61
-
62
- def get_model_size(model_info: ModelInfo, precision: str):
63
- """Gets the model size from the configuration, or the model name if the configuration does not contain the information."""
64
- try:
65
- model_size = round(model_info.safetensors["total"] / 1e9, 3)
66
- except (AttributeError, TypeError):
67
- return 0 # Unknown model sizes are indicated as 0, see NUMERIC_INTERVALS in app.py
68
-
69
- size_factor = 8 if (precision == "GPTQ" or "gptq" in model_info.modelId.lower()) else 1
70
- model_size = size_factor * model_size
71
- return model_size
72
-
73
- def get_model_arch(model_info: ModelInfo):
74
- """Gets the model architecture from the configuration"""
75
- return model_info.config.get("architectures", "Unknown")
76
-
77
- def already_submitted_models(requested_models_dir: str) -> set[str]:
78
- """Gather a list of already submitted models to avoid duplicates"""
79
- depth = 1
80
- file_names = []
81
- users_to_submission_dates = defaultdict(list)
82
-
83
- for root, _, files in os.walk(requested_models_dir):
84
- current_depth = root.count(os.sep) - requested_models_dir.count(os.sep)
85
- if current_depth == depth:
86
- for file in files:
87
- if not file.endswith(".json"):
88
- continue
89
- with open(os.path.join(root, file), "r") as f:
90
- info = json.load(f)
91
- file_names.append(f"{info['model']}_{info['revision']}_{info['precision']}")
92
-
93
- # Select organisation
94
- if info["model"].count("/") == 0 or "submitted_time" not in info:
95
- continue
96
- organisation, _ = info["model"].split("/")
97
- users_to_submission_dates[organisation].append(info["submitted_time"])
98
-
99
- return set(file_names), users_to_submission_dates
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/submission/submit.py 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
- )