potsawee commited on
Commit
5102800
0 Parent(s):

init commit

Browse files
.gitattributes ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tflite filter=lfs diff=lfs merge=lfs -text
29
+ *.tgz filter=lfs diff=lfs merge=lfs -text
30
+ *.wasm filter=lfs diff=lfs merge=lfs -text
31
+ *.xz filter=lfs diff=lfs merge=lfs -text
32
+ *.zip filter=lfs diff=lfs merge=lfs -text
33
+ *.zst filter=lfs diff=lfs merge=lfs -text
34
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
35
+ scale-hf-logo.png filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ auto_evals/
2
+ venv/
3
+ __pycache__/
4
+ .env
5
+ .ipynb_checkpoints
6
+ *ipynb
7
+ .vscode/
8
+
9
+ eval-queue/
10
+ eval-results/
11
+ eval-queue-bk/
12
+ eval-results-bk/
13
+ logs/
.pre-commit-config.yaml ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ default_language_version:
16
+ python: python3
17
+
18
+ ci:
19
+ autofix_prs: true
20
+ autoupdate_commit_msg: '[pre-commit.ci] pre-commit suggestions'
21
+ autoupdate_schedule: quarterly
22
+
23
+ repos:
24
+ - repo: https://github.com/pre-commit/pre-commit-hooks
25
+ rev: v4.3.0
26
+ hooks:
27
+ - id: check-yaml
28
+ - id: check-case-conflict
29
+ - id: detect-private-key
30
+ - id: check-added-large-files
31
+ args: ['--maxkb=1000']
32
+ - id: requirements-txt-fixer
33
+ - id: end-of-file-fixer
34
+ - id: trailing-whitespace
35
+
36
+ - repo: https://github.com/PyCQA/isort
37
+ rev: 5.12.0
38
+ hooks:
39
+ - id: isort
40
+ name: Format imports
41
+
42
+ - repo: https://github.com/psf/black
43
+ rev: 22.12.0
44
+ hooks:
45
+ - id: black
46
+ name: Format code
47
+ additional_dependencies: ['click==8.0.2']
48
+
49
+ - repo: https://github.com/charliermarsh/ruff-pre-commit
50
+ # Ruff version.
51
+ rev: 'v0.0.267'
52
+ hooks:
53
+ - id: ruff
Makefile ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .PHONY: style format
2
+
3
+
4
+ style:
5
+ python -m black --line-length 119 .
6
+ python -m isort .
7
+ ruff check --fix .
8
+
9
+
10
+ quality:
11
+ python -m black --check --line-length 119 .
12
+ python -m isort --check-only .
13
+ ruff check .
README.md ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Leaderboard
3
+ emoji: 🥇
4
+ colorFrom: green
5
+ colorTo: indigo
6
+ sdk: gradio
7
+ sdk_version: 4.4.0
8
+ app_file: app.py
9
+ pinned: true
10
+ license: apache-2.0
11
+ ---
12
+
13
+ # Start the configuration
14
+
15
+ 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).
16
+
17
+ Results files should have the following format and be stored as json files:
18
+ ```json
19
+ {
20
+ "config": {
21
+ "model_dtype": "torch.float16", # or torch.bfloat16 or 8bit or 4bit
22
+ "model_name": "path of the model on the hub: org/model",
23
+ "model_sha": "revision on the hub",
24
+ },
25
+ "results": {
26
+ "task_name": {
27
+ "metric_name": score,
28
+ },
29
+ "task_name2": {
30
+ "metric_name": score,
31
+ }
32
+ }
33
+ }
34
+ ```
35
+
36
+ Request files are created automatically by this tool.
37
+
38
+ 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.
39
+
40
+ # Code logic for more complex edits
41
+
42
+ You'll find
43
+ - the main table' columns names and properties in `src/display/utils.py`
44
+ - 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`
45
+ - teh logic to allow or filter submissions in `src/submission/submit.py` and `src/submission/check_validity.py`
app.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import subprocess
2
+ import gradio as gr
3
+ from apscheduler.schedulers.background import BackgroundScheduler
4
+ from huggingface_hub import snapshot_download
5
+
6
+ from src.pages.about import show_about_page
7
+ from src.pages.submit import show_submit_page
8
+ from src.pages.result_table import show_result_page
9
+ from src.about import (
10
+ CITATION_BUTTON_LABEL,
11
+ CITATION_BUTTON_TEXT,
12
+ INTRODUCTION_TEXT,
13
+ TITLE,
14
+ )
15
+ from src.display.css_html_js import custom_css
16
+ from src.envs import API, EVAL_REQUESTS_PATH, EVAL_RESULTS_PATH, QUEUE_REPO, REPO_ID, RESULTS_REPO, TOKEN
17
+
18
+
19
+
20
+ def restart_space():
21
+ API.restart_space(repo_id=REPO_ID)
22
+
23
+ try:
24
+ print(EVAL_REQUESTS_PATH)
25
+ snapshot_download(
26
+ repo_id=QUEUE_REPO, local_dir=EVAL_REQUESTS_PATH, repo_type="dataset", tqdm_class=None, etag_timeout=30, token=TOKEN
27
+ )
28
+ except Exception:
29
+ restart_space()
30
+ try:
31
+ print(EVAL_RESULTS_PATH)
32
+ snapshot_download(
33
+ repo_id=RESULTS_REPO, local_dir=EVAL_RESULTS_PATH, repo_type="dataset", tqdm_class=None, etag_timeout=30, token=TOKEN
34
+ )
35
+ except Exception:
36
+ restart_space()
37
+
38
+
39
+ demo = gr.Blocks(css=custom_css)
40
+ with demo:
41
+ gr.HTML(TITLE)
42
+ gr.Markdown(INTRODUCTION_TEXT, elem_classes="markdown-text")
43
+
44
+ with gr.Tabs(elem_classes="tab-buttons") as tabs:
45
+ show_result_page(root_path='VH', title='🎆 Visual Hallucination Benchmark', index=0)
46
+ show_result_page(root_path='AVH-visual', title='📺 AVHalluBench Visual', index=1)
47
+ show_result_page(root_path='AVH-audio', title='🔈 AVHalluBench Audio', index=2)
48
+ show_about_page(index=3)
49
+ show_submit_page(index=4)
50
+
51
+ with gr.Row():
52
+ with gr.Accordion("📙 Citation", open=False):
53
+ citation_button = gr.Textbox(
54
+ value=CITATION_BUTTON_TEXT,
55
+ label=CITATION_BUTTON_LABEL,
56
+ lines=8,
57
+ elem_id="citation-button",
58
+ show_copy_button=True,
59
+ )
60
+
61
+ scheduler = BackgroundScheduler()
62
+ scheduler.add_job(restart_space, "interval", seconds=1800)
63
+ scheduler.start()
64
+ demo.queue(default_concurrency_limit=40).launch()
pyproject.toml ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [tool.ruff]
2
+ # Enable pycodestyle (`E`) and Pyflakes (`F`) codes by default.
3
+ select = ["E", "F"]
4
+ ignore = ["E501"] # line too long (black is taking care of this)
5
+ line-length = 119
6
+ fixable = ["A", "B", "C", "D", "E", "F", "G", "I", "N", "Q", "S", "T", "W", "ANN", "ARG", "BLE", "COM", "DJ", "DTZ", "EM", "ERA", "EXE", "FBT", "ICN", "INP", "ISC", "NPY", "PD", "PGH", "PIE", "PL", "PT", "PTH", "PYI", "RET", "RSE", "RUF", "SIM", "SLF", "TCH", "TID", "TRY", "UP", "YTT"]
7
+
8
+ [tool.isort]
9
+ profile = "black"
10
+ line_length = 119
11
+
12
+ [tool.black]
13
+ line-length = 119
requirements.txt ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ APScheduler==3.10.1
2
+ black==23.11.0
3
+ click==8.1.3
4
+ gradio==4.26.0
5
+ gradio_client==0.15.1
6
+ huggingface-hub>=0.18.0
7
+ numpy==1.24.2
8
+ pandas==2.0.0
9
+ requests==2.28.2
10
+ tqdm==4.65.0
11
+ transformers==4.35.2
12
+ python-dotenv
src/about.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass
2
+ from enum import Enum
3
+
4
+
5
+
6
+ NUM_FEWSHOT = 0 # Change with your few shot
7
+ # ---------------------------------------------------
8
+
9
+ TITLE = """<h1 align="center" id="space-title">AV Hallucination Leaderboard</h1>"""
10
+
11
+ INTRODUCTION_TEXT = """
12
+ """
13
+
14
+ LLM_BENCHMARKS_TEXT = f"""
15
+ TODO write about page here
16
+ """
17
+
18
+ EVALUATION_QUEUE_TEXT = """
19
+ TODO Write this
20
+ """
21
+
22
+ CITATION_BUTTON_LABEL = "Copy the following snippet to cite these results"
23
+ CITATION_BUTTON_TEXT = r"""@misc{sun2024crosscheckgpt,
24
+ title={CrossCheckGPT: Universal Hallucination Ranking for Multimodal Foundation Models},
25
+ author={Guangzhi Sun and Potsawee Manakul and Adian Liusie and Kunat Pipatanakul and Chao Zhang and Phil Woodland and Mark Gales},
26
+ year={2024},
27
+ eprint={2405.13684},
28
+ archivePrefix={arXiv},
29
+ primaryClass={cs.CL}
30
+ }"""
src/display/css_html_js.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ custom_css = """
2
+
3
+ .markdown-text {
4
+ font-size: 16px !important;
5
+ }
6
+
7
+ #models-to-add-text {
8
+ font-size: 18px !important;
9
+ }
10
+
11
+ #citation-button span {
12
+ font-size: 16px !important;
13
+ }
14
+
15
+ #citation-button textarea {
16
+ font-size: 16px !important;
17
+ }
18
+
19
+ #citation-button > label > button {
20
+ margin: 6px;
21
+ transform: scale(1.3);
22
+ }
23
+
24
+ #leaderboard-table {
25
+ margin-top: 15px
26
+ }
27
+
28
+ #leaderboard-table-lite {
29
+ margin-top: 15px
30
+ }
31
+
32
+ #search-bar-table-box > div:first-child {
33
+ background: none;
34
+ border: none;
35
+ }
36
+
37
+ #search-bar {
38
+ padding: 0px;
39
+ }
40
+
41
+ /* Limit the width of the first AutoEvalColumn so that names don't expand too much */
42
+ table td:first-child,
43
+ table th:first-child {
44
+ max-width: 400px;
45
+ overflow: auto;
46
+ white-space: nowrap;
47
+ }
48
+
49
+ .tab-buttons button {
50
+ font-size: 20px;
51
+ }
52
+
53
+ #scale-logo {
54
+ border-style: none !important;
55
+ box-shadow: none;
56
+ display: block;
57
+ margin-left: auto;
58
+ margin-right: auto;
59
+ max-width: 600px;
60
+ }
61
+
62
+ #scale-logo .download {
63
+ display: none;
64
+ }
65
+ #filter_type{
66
+ border: 0;
67
+ padding-left: 0;
68
+ padding-top: 0;
69
+ }
70
+ #filter_type label {
71
+ display: flex;
72
+ }
73
+ #filter_type label > span{
74
+ margin-top: var(--spacing-lg);
75
+ margin-right: 0.5em;
76
+ }
77
+ #filter_type label > .wrap{
78
+ width: 103px;
79
+ }
80
+ #filter_type label > .wrap .wrap-inner{
81
+ padding: 2px;
82
+ }
83
+ #filter_type label > .wrap .wrap-inner input{
84
+ width: 1px
85
+ }
86
+ #filter-columns-type{
87
+ border:0;
88
+ padding:0.5;
89
+ }
90
+ #filter-columns-size{
91
+ border:0;
92
+ padding:0.5;
93
+ }
94
+ #box-filter > .form{
95
+ border: 0
96
+ }
97
+ """
98
+
99
+ get_window_url_params = """
100
+ function(url_params) {
101
+ const params = new URLSearchParams(window.location.search);
102
+ url_params = Object.fromEntries(params);
103
+ return url_params;
104
+ }
105
+ """
src/display/formatting.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 styled_error(error):
6
+ return f"<p style='color: red; font-size: 20px; text-align: center;'>{error}</p>"
7
+
8
+
9
+ def styled_warning(warn):
10
+ return f"<p style='color: orange; font-size: 20px; text-align: center;'>{warn}</p>"
11
+
12
+
13
+ def styled_message(message):
14
+ return f"<p style='color: green; font-size: 20px; text-align: center;'>{message}</p>"
15
+
16
+
17
+ def has_no_nan_values(df, columns):
18
+ return df[columns].notna().all(axis=1)
19
+
20
+
21
+ def has_nan_values(df, columns):
22
+ return df[columns].isna().any(axis=1)
src/display/utils.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass, make_dataclass
2
+ import pandas as pd
3
+
4
+
5
+ def fields(raw_class):
6
+ return [v for k, v in raw_class.__dict__.items() if k[:2] != "__" and k[-2:] != "__"]
7
+
8
+
9
+ # These classes are for user facing column names,
10
+ # to avoid having to change them all around the code
11
+ # when a modif is needed
12
+ @dataclass
13
+ class ColumnContent:
14
+ name: str
15
+ type: str
16
+ displayed_by_default: bool
17
+ hidden: bool = False
18
+ never_hidden: bool = False
19
+
20
+ ## Leaderboard columns
21
+ auto_eval_column_dict = []
22
+ # Init
23
+ auto_eval_column_dict.append(["model", ColumnContent, ColumnContent("Model", "markdown", True, never_hidden=True)])
24
+
25
+ # We use make dataclass to dynamically fill the scores from Tasks
26
+ AutoEvalColumn = make_dataclass("AutoEvalColumn", auto_eval_column_dict, frozen=True)
27
+
28
+ ## For the queue columns in the submission tab
29
+ @dataclass(frozen=True)
30
+ class EvalQueueColumn: # Queue column
31
+ model = ColumnContent("model", "markdown", True)
32
+ revision = ColumnContent("revision", "str", True)
33
+ private = ColumnContent("private", "bool", True)
34
+ status = ColumnContent("status", "str", True)
35
+
36
+ ## All the model information that we might need
37
+ @dataclass
38
+ class ModelDetails:
39
+ name: str
40
+ display_name: str = ""
41
+ symbol: str = "" # emoji
42
+
43
+
44
+ # Column selection
45
+ COLS_LITE = [c.name for c in fields(AutoEvalColumn) if c.displayed_by_default and not c.hidden]
46
+ TYPES_LITE = [c.type for c in fields(AutoEvalColumn) if c.displayed_by_default and not c.hidden]
47
+
48
+ EVAL_COLS = [c.name for c in fields(EvalQueueColumn)]
49
+ EVAL_TYPES = [c.type for c in fields(EvalQueueColumn)]
50
+
51
+ NUMERIC_INTERVALS = {
52
+ "?": pd.Interval(-1, 0, closed="right"),
53
+ "~1.5": pd.Interval(0, 2, closed="right"),
54
+ "~3": pd.Interval(2, 4, closed="right"),
55
+ "~7": pd.Interval(4, 9, closed="right"),
56
+ "~13": pd.Interval(9, 20, closed="right"),
57
+ "~35": pd.Interval(20, 45, closed="right"),
58
+ "~60": pd.Interval(45, 70, closed="right"),
59
+ "70+": pd.Interval(70, 10000, closed="right"),
60
+ }
src/envs.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from dotenv import load_dotenv
3
+ load_dotenv()
4
+ from huggingface_hub import HfApi
5
+
6
+ # Info to change for your repository
7
+ # ----------------------------------
8
+ TOKEN = os.environ.get("TOKEN") # A read/write token for your org
9
+
10
+ OWNER = "scb10x" # Change to your org - don't forget to create a results and request dataset, with the correct format!
11
+ # ----------------------------------
12
+
13
+ REPO_ID = f"{OWNER}/leaderboard"
14
+ QUEUE_REPO = f"{OWNER}/av_hallucination_requests"
15
+ RESULTS_REPO = f"{OWNER}/av_hallucination_results"
16
+
17
+ # If you setup a cache later, just change HF_HOME
18
+ CACHE_PATH=os.getenv("HF_HOME", ".")
19
+
20
+ # Local caches
21
+ EVAL_REQUESTS_PATH = os.path.join(CACHE_PATH, "eval-queue")
22
+ EVAL_RESULTS_PATH = os.path.join(CACHE_PATH, "eval-results")
23
+ EVAL_REQUESTS_PATH_BACKEND = os.path.join(CACHE_PATH, "eval-queue-bk")
24
+ EVAL_RESULTS_PATH_BACKEND = os.path.join(CACHE_PATH, "eval-results-bk")
25
+
26
+ API = HfApi(token=TOKEN)
src/leaderboard/read_evals.py ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import glob
2
+ import json
3
+ import os
4
+ from dataclasses import dataclass
5
+ import dateutil
6
+
7
+ from src.display.formatting import model_hyperlink
8
+ from src.display.utils import AutoEvalColumn
9
+
10
+
11
+ @dataclass
12
+ class EvalResult:
13
+ """Represents one full evaluation. Built from a combination of the result and request file for a given run.
14
+ """
15
+ eval_name: str # org_model (uid)
16
+ full_model: str # org/model (path on hub)
17
+ org: str
18
+ model: str
19
+ results: dict
20
+ model_link: str = ""
21
+ date: str = "" # submission date of request file
22
+
23
+ @classmethod
24
+ def init_from_json_file(self, json_filepath):
25
+ """Inits the result from the specific model result file"""
26
+ with open(json_filepath) as fp:
27
+ data = json.load(fp)
28
+
29
+ config = data.get("config")
30
+
31
+
32
+ # Get model and org
33
+ org_and_model = config.get("model_name", config.get("model_args", None))
34
+ org_and_model = org_and_model.split("/", 1)
35
+
36
+ if len(org_and_model) == 1:
37
+ org = None
38
+ model = org_and_model[0]
39
+ result_key = f"{model}"
40
+ else:
41
+ org = org_and_model[0]
42
+ model = org_and_model[1]
43
+ result_key = f"{org}_{model}"
44
+ full_model = "/".join(org_and_model)
45
+ model_link = config.get('model_link', '')
46
+
47
+ # Extract results available in this file (some results are split in several files)
48
+ results = {}
49
+
50
+ for k, v in data["results"].items():
51
+ results[k] = v[k]
52
+ print('results', results)
53
+ return self(
54
+ eval_name=result_key,
55
+ full_model=full_model,
56
+ model_link=model_link,
57
+ org=org,
58
+ model=model,
59
+ results=results,
60
+ )
61
+
62
+ def update_with_request_file(self, requests_path):
63
+ """Finds the relevant request file for the current model and updates info with it"""
64
+ request_file = get_request_file_for_model(requests_path, self.full_model)
65
+
66
+ try:
67
+ with open(request_file, "r") as f:
68
+ request = json.load(f)
69
+ self.date = request.get("submitted_time", "")
70
+ except Exception:
71
+ print(f"Could not find request file for {self.org}/{self.model}")
72
+
73
+ def to_dict(self):
74
+ """Converts the Eval Result to a dict compatible with our dataframe display"""
75
+ data_dict = {
76
+ AutoEvalColumn.model.name: model_hyperlink(self.model_link, self.full_model),
77
+ }
78
+
79
+ for key in self.results.keys():
80
+ try:
81
+ data_dict[key] = float(self.results[key])
82
+ except ValueError:
83
+ data_dict[key] = self.results[key]
84
+
85
+ return data_dict
86
+
87
+
88
+ def get_request_file_for_model(requests_path, model_name):
89
+ """Selects the correct request file for a given model. Only keeps runs tagged as FINISHED"""
90
+ request_files = os.path.join(
91
+ requests_path,
92
+ f"{model_name}_eval_request_*.json",
93
+ )
94
+ request_files = glob.glob(request_files)
95
+
96
+ request_file = ""
97
+ request_files = sorted(request_files, reverse=True)
98
+ for tmp_request_file in request_files:
99
+ with open(tmp_request_file, "r") as f:
100
+ req_content = json.load(f)
101
+ if (
102
+ req_content["status"] in ["FINISHED"]
103
+ ):
104
+ request_file = tmp_request_file
105
+ return request_file
106
+
107
+
108
+ def get_raw_eval_results(results_path: str) -> list[EvalResult]:
109
+ """From the path of the results folder root, extract all needed info for results"""
110
+ model_result_filepaths = []
111
+
112
+ for root, _, files in os.walk(results_path):
113
+ # We should only have json files in model results
114
+ if len(files) == 0 or any([not f.endswith(".json") for f in files]):
115
+ continue
116
+
117
+ # Sort the files by date
118
+ try:
119
+ files.sort(key=lambda x: x.removesuffix(".json").removeprefix("results_")[:-7])
120
+ except dateutil.parser._parser.ParserError:
121
+ files = [files[-1]]
122
+
123
+ for file in files:
124
+ model_result_filepaths.append(os.path.join(root, file))
125
+
126
+ eval_results = {}
127
+ for model_result_filepath in model_result_filepaths:
128
+ # Creation of result
129
+ eval_result = EvalResult.init_from_json_file(model_result_filepath)
130
+
131
+ # Store results of same eval together
132
+ eval_name = eval_result.eval_name
133
+ if eval_name in eval_results.keys():
134
+ eval_results[eval_name].results.update({k: v for k, v in eval_result.results.items() if v is not None})
135
+ else:
136
+ eval_results[eval_name] = eval_result
137
+
138
+ results = []
139
+ for v in eval_results.values():
140
+ try:
141
+ v.to_dict() # we test if the dict version is complete
142
+ results.append(v)
143
+ except KeyError: # not all eval values present
144
+ continue
145
+ return results
src/pages/about.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+
3
+ from src.about import LLM_BENCHMARKS_TEXT
4
+
5
+ def show_about_page(index: int):
6
+ with gr.TabItem("📝 About", elem_id="llm-benchmark-tab-table", id=index):
7
+ gr.Markdown(LLM_BENCHMARKS_TEXT, elem_classes="markdown-text")
src/pages/result_table.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import pandas as pd
3
+ from src.envs import EVAL_RESULTS_PATH
4
+ from src.populate import get_leaderboard_df
5
+ from src.display.utils import (
6
+ AutoEvalColumn,
7
+ )
8
+
9
+ def update_table(
10
+ hidden_df: pd.DataFrame,
11
+ query: str,
12
+ ):
13
+ filtered_df = filter_queries(query, hidden_df)
14
+ return filtered_df
15
+
16
+
17
+ def search_table(df: pd.DataFrame, query: str) -> pd.DataFrame:
18
+ return df[(df[AutoEvalColumn.model.name].str.contains(query, case=False))]
19
+
20
+
21
+ def filter_queries(query: str, filtered_df: pd.DataFrame) -> pd.DataFrame:
22
+ final_df = []
23
+ if query != "":
24
+ queries = [q.strip() for q in query.split(";")]
25
+ for _q in queries:
26
+ _q = _q.strip()
27
+ if _q != "":
28
+ temp_filtered_df = search_table(filtered_df, _q)
29
+ if len(temp_filtered_df) > 0:
30
+ final_df.append(temp_filtered_df)
31
+ if len(final_df) > 0:
32
+ filtered_df = pd.concat(final_df)
33
+ filtered_df = filtered_df.drop_duplicates(
34
+ subset=[AutoEvalColumn.model.name, ]
35
+ )
36
+
37
+ return filtered_df
38
+
39
+
40
+
41
+ def show_result_page(root_path: str, title: str, index: int):
42
+ raw_data, original_df = get_leaderboard_df(EVAL_RESULTS_PATH + f'/{root_path}')
43
+ leaderboard_df = original_df.copy()
44
+ number_of_field = list(leaderboard_df.keys())
45
+ with gr.TabItem(title, elem_id="llm-benchmark-tab-table", id=index):
46
+ with gr.Row():
47
+ with gr.Column():
48
+ with gr.Row():
49
+ search_bar = gr.Textbox(
50
+ placeholder=" 🔍 Search for your model (separate multiple queries with `;`) and press ENTER...",
51
+ show_label=False,
52
+ elem_id="search-bar",
53
+ )
54
+
55
+
56
+ leaderboard_table = gr.components.Dataframe(
57
+ value=leaderboard_df,
58
+ headers=list(leaderboard_df.keys()),
59
+ datatype=['markdown'],
60
+ elem_id="leaderboard-table",
61
+ column_widths=(['20%'] if len(number_of_field) > 6 else [str((1.5 / (len(number_of_field))) * 100) + '%']) * len(number_of_field),
62
+ min_width=180,
63
+ interactive=False,
64
+ visible=True,
65
+ wrap=True
66
+ )
67
+
68
+
69
+ # Dummy leaderboard for handling the case when the user uses backspace key
70
+ hidden_leaderboard_table = gr.components.Dataframe(
71
+ value=original_df,
72
+ headers=list(original_df.keys()),
73
+ interactive=False,
74
+ visible=False,
75
+ )
76
+
77
+ search_bar.submit(
78
+ update_table,
79
+ [
80
+ hidden_leaderboard_table,
81
+ search_bar,
82
+ ],
83
+ leaderboard_table,
84
+ )
src/pages/submit.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from src.display.utils import EVAL_COLS, EVAL_TYPES
2
+ from src.envs import EVAL_REQUESTS_PATH
3
+ from src.populate import get_evaluation_queue_df
4
+ from src.about import EVALUATION_QUEUE_TEXT
5
+ from src.submission.submit import add_new_eval
6
+ import gradio as gr
7
+
8
+ def show_submit_page(index: int):
9
+ (
10
+ finished_eval_queue_df,
11
+ running_eval_queue_df,
12
+ pending_eval_queue_df,
13
+ ) = get_evaluation_queue_df(EVAL_REQUESTS_PATH, EVAL_COLS)
14
+ with gr.TabItem("🚀 Submit here! ", elem_id="llm-benchmark-tab-table", id=index):
15
+ with gr.Column():
16
+ with gr.Row():
17
+ gr.Markdown(EVALUATION_QUEUE_TEXT, elem_classes="markdown-text")
18
+
19
+ with gr.Column():
20
+ with gr.Accordion(
21
+ f"✅ Finished Evaluations ({len(finished_eval_queue_df)})",
22
+ open=False,
23
+ ):
24
+ with gr.Row():
25
+ finished_eval_table = gr.components.Dataframe(
26
+ value=finished_eval_queue_df,
27
+ headers=EVAL_COLS,
28
+ datatype=EVAL_TYPES,
29
+ row_count=5,
30
+ )
31
+
32
+ with gr.Accordion(
33
+ f"⏳ Pending Evaluation Queue ({len(pending_eval_queue_df)})",
34
+ open=False,
35
+ ):
36
+ with gr.Row():
37
+ pending_eval_table = gr.components.Dataframe(
38
+ value=pending_eval_queue_df,
39
+ headers=EVAL_COLS,
40
+ datatype=EVAL_TYPES,
41
+ row_count=5,
42
+ )
43
+ with gr.Row():
44
+ gr.Markdown("# ✉️✨ Submit your model here!", elem_classes="markdown-text")
45
+
46
+ with gr.Row():
47
+ with gr.Column():
48
+ model_name_textbox = gr.Textbox(label="Model name")
49
+ # TODO
50
+ # add more field here
51
+
52
+ submit_button = gr.Button("Submit Eval")
53
+ submission_result = gr.Markdown()
54
+ submit_button.click(
55
+ add_new_eval,
56
+ [
57
+ model_name_textbox,
58
+ ],
59
+ submission_result,
60
+ )
src/populate.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+
4
+ import pandas as pd
5
+
6
+ from src.display.utils import EvalQueueColumn
7
+ from src.leaderboard.read_evals import get_raw_eval_results
8
+
9
+
10
+ def get_leaderboard_df(results_path: str) -> pd.DataFrame:
11
+ """Creates a dataframe from all the individual experiment results"""
12
+ raw_data = get_raw_eval_results(results_path)
13
+ all_data_json = [v.to_dict() for v in raw_data]
14
+
15
+ df = pd.DataFrame.from_records(all_data_json)
16
+ df = df.round(decimals=2)
17
+ return raw_data, df
18
+
19
+
20
+ def get_evaluation_queue_df(save_path: str, cols: list) -> list[pd.DataFrame]:
21
+ """Creates the different dataframes for the evaluation queues requestes"""
22
+ entries = [entry for entry in os.listdir(save_path) if not entry.startswith(".")]
23
+ all_evals = []
24
+
25
+ for entry in entries:
26
+ if ".json" in entry:
27
+ file_path = os.path.join(save_path, entry)
28
+ with open(file_path) as fp:
29
+ data = json.load(fp)
30
+
31
+ data[EvalQueueColumn.revision.name] = data.get("revision", "main")
32
+
33
+ all_evals.append(data)
34
+ elif ".md" not in entry:
35
+ # this is a folder
36
+ sub_entries = [e for e in os.listdir(f"{save_path}/{entry}") if not e.startswith(".")]
37
+ for sub_entry in sub_entries:
38
+ file_path = os.path.join(save_path, entry, sub_entry)
39
+ with open(file_path) as fp:
40
+ data = json.load(fp)
41
+ data[EvalQueueColumn.revision.name] = data.get("revision", "main")
42
+ all_evals.append(data)
43
+
44
+ pending_list = [e for e in all_evals if e["status"] in ["PENDING", "RERUN"]]
45
+ running_list = [e for e in all_evals if e["status"] == "RUNNING"]
46
+ finished_list = [e for e in all_evals if e["status"].startswith("FINISHED") or e["status"] == "PENDING_NEW_EVAL"]
47
+ df_pending = pd.DataFrame.from_records(pending_list, columns=cols)
48
+ df_running = pd.DataFrame.from_records(running_list, columns=cols)
49
+ df_finished = pd.DataFrame.from_records(finished_list, columns=cols)
50
+ return df_finished[cols], df_running[cols], df_pending[cols]
src/submission/check_validity.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ from collections import defaultdict
4
+
5
+ import huggingface_hub
6
+ from huggingface_hub import ModelCard
7
+ from huggingface_hub.hf_api import ModelInfo
8
+ from transformers import AutoConfig
9
+ from transformers.models.auto.tokenization_auto import AutoTokenizer
10
+
11
+ def check_model_card(repo_id: str) -> tuple[bool, str]:
12
+ """Checks if the model card and license exist and have been filled"""
13
+ try:
14
+ card = ModelCard.load(repo_id)
15
+ except huggingface_hub.utils.EntryNotFoundError:
16
+ return False, "Please add a model card to your model to explain how you trained/fine-tuned it."
17
+
18
+ # Enforce card content
19
+ if len(card.text) < 200:
20
+ return False, "Please add a description to your model card, it is too short."
21
+
22
+ return True, ""
23
+
24
+ def is_model_on_hub(model_name: str, revision: str, token: str = None, trust_remote_code=False, test_tokenizer=False) -> tuple[bool, str]:
25
+ """Checks if the model model_name is on the hub, and whether it (and its tokenizer) can be loaded with AutoClasses."""
26
+ try:
27
+ config = AutoConfig.from_pretrained(model_name, revision=revision, trust_remote_code=trust_remote_code, token=token)
28
+ if test_tokenizer:
29
+ try:
30
+ tk = AutoTokenizer.from_pretrained(model_name, revision=revision, trust_remote_code=trust_remote_code, token=token)
31
+ except ValueError as e:
32
+ return (
33
+ False,
34
+ f"uses a tokenizer which is not in a transformers release: {e}",
35
+ None
36
+ )
37
+ except Exception as e:
38
+ return (False, "'s tokenizer cannot be loaded. Is your tokenizer class in a stable transformers release, and correctly configured?", None)
39
+ return True, None, config
40
+
41
+ except ValueError:
42
+ return (
43
+ False,
44
+ "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.",
45
+ None
46
+ )
47
+
48
+ except Exception as e:
49
+ return False, "was not found on hub!", None
50
+
51
+
52
+ def get_model_size(model_info: ModelInfo):
53
+ """Gets the model size from the configuration, or the model name if the configuration does not contain the information."""
54
+ try:
55
+ model_size = round(model_info.safetensors["total"] / 1e9, 3)
56
+ except (AttributeError, TypeError):
57
+ return 0 # Unknown model sizes are indicated as 0, see NUMERIC_INTERVALS in app.py
58
+
59
+ model_size = 1 * model_size
60
+ return model_size
61
+
62
+ def already_submitted_models(requested_models_dir: str) -> set[str]:
63
+ """Gather a list of already submitted models to avoid duplicates"""
64
+ depth = 1
65
+ file_names = []
66
+ users_to_submission_dates = defaultdict(list)
67
+
68
+ for root, _, files in os.walk(requested_models_dir):
69
+ current_depth = root.count(os.sep) - requested_models_dir.count(os.sep)
70
+ if current_depth == depth:
71
+ for file in files:
72
+ if not file.endswith(".json"):
73
+ continue
74
+ with open(os.path.join(root, file), "r") as f:
75
+ info = json.load(f)
76
+ file_names.append(f"{info['model']}_{info['revision']}")
77
+
78
+ # Select organisation
79
+ if info["model"].count("/") == 0 or "submitted_time" not in info:
80
+ continue
81
+ organisation, _ = info["model"].split("/")
82
+ users_to_submission_dates[organisation].append(info["submitted_time"])
83
+
84
+ return set(file_names), users_to_submission_dates
src/submission/submit.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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, QUEUE_REPO
7
+ from src.submission.check_validity import (
8
+ already_submitted_models,
9
+ check_model_card,
10
+ )
11
+
12
+ REQUESTED_MODELS = None
13
+ USERS_TO_SUBMISSION_DATES = None
14
+
15
+ def add_new_eval(
16
+ model: str,
17
+ ):
18
+ global REQUESTED_MODELS
19
+ global USERS_TO_SUBMISSION_DATES
20
+ if not REQUESTED_MODELS:
21
+ REQUESTED_MODELS, USERS_TO_SUBMISSION_DATES = already_submitted_models(EVAL_REQUESTS_PATH)
22
+
23
+ user_name = ""
24
+ model_path = model
25
+ if "/" in model:
26
+ user_name = model.split("/")[0]
27
+ model_path = model.split("/")[1]
28
+
29
+ current_time = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
30
+
31
+ revision = "main"
32
+
33
+
34
+ # Is the model info correctly filled?
35
+ try:
36
+ model_info = API.model_info(repo_id=model, revision=revision)
37
+ except Exception:
38
+ return styled_error("Could not get your model information. Please fill it up properly.")
39
+
40
+
41
+ modelcard_OK, error_msg = check_model_card(model)
42
+ if not modelcard_OK:
43
+ return styled_error(error_msg)
44
+
45
+ # Seems good, creating the eval
46
+ print("Adding new eval")
47
+
48
+ eval_entry = {
49
+ "model": model,
50
+ "revision": revision,
51
+ "status": "PENDING",
52
+ "submitted_time": current_time,
53
+ "private": False,
54
+ }
55
+
56
+ # Check for duplicate submission
57
+ if f"{model}_{revision}" in REQUESTED_MODELS:
58
+ return styled_warning("This model has been already submitted.")
59
+
60
+ print("Creating eval file")
61
+ OUT_DIR = f"{EVAL_REQUESTS_PATH}/{user_name}"
62
+ os.makedirs(OUT_DIR, exist_ok=True)
63
+ out_path = f"{OUT_DIR}/{model_path}_eval_request_False.json"
64
+
65
+ with open(out_path, "w") as f:
66
+ f.write(json.dumps(eval_entry))
67
+
68
+ print("Uploading eval file")
69
+ API.upload_file(
70
+ path_or_fileobj=out_path,
71
+ path_in_repo=out_path.split("eval-queue/")[1],
72
+ repo_id=QUEUE_REPO,
73
+ repo_type="dataset",
74
+ commit_message=f"Add {model} to eval queue",
75
+ )
76
+
77
+ # Remove the local file
78
+ os.remove(out_path)
79
+
80
+ return styled_message(
81
+ "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."
82
+ )