Refactor Gradio app to enhance data management, improve user interface with modern styling, and implement comprehensive error handling. Remove deprecated files and streamline configuration for better maintainability.
Browse files- .gitignore +40 -9
- .pre-commit-config.yaml +0 -53
- Makefile +0 -13
- README.md +42 -68
- app.py +379 -78
- app_e.py +0 -115
- app_ex.py +0 -204
- config.py +126 -8
- data_manager.py +201 -58
- pyproject.toml +0 -13
- requirements.txt +6 -15
- src/about.py +0 -72
- src/display/css_html_js.py +0 -105
- src/display/formatting.py +0 -27
- src/display/utils.py +0 -110
- src/envs.py +0 -25
- src/leaderboard/read_evals.py +0 -196
- src/populate.py +0 -58
- src/submission/check_validity.py +0 -99
- src/submission/submit.py +0 -119
- utils.py +455 -50
.gitignore
CHANGED
@@ -1,13 +1,44 @@
|
|
1 |
-
|
2 |
-
venv/
|
3 |
__pycache__/
|
4 |
-
|
5 |
-
.
|
6 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
7 |
.vscode/
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
8 |
|
9 |
-
|
10 |
-
eval-results/
|
11 |
-
eval-queue-bk/
|
12 |
-
eval-results-bk/
|
13 |
logs/
|
|
|
|
1 |
+
# Python
|
|
|
2 |
__pycache__/
|
3 |
+
*.py[cod]
|
4 |
+
*$py.class
|
5 |
+
*.so
|
6 |
+
.Python
|
7 |
+
build/
|
8 |
+
develop-eggs/
|
9 |
+
dist/
|
10 |
+
downloads/
|
11 |
+
eggs/
|
12 |
+
.eggs/
|
13 |
+
lib/
|
14 |
+
lib64/
|
15 |
+
parts/
|
16 |
+
sdist/
|
17 |
+
var/
|
18 |
+
wheels/
|
19 |
+
*.egg-info/
|
20 |
+
.installed.cfg
|
21 |
+
*.egg
|
22 |
+
|
23 |
+
# Virtual environments
|
24 |
+
venv/
|
25 |
+
env/
|
26 |
+
ENV/
|
27 |
+
|
28 |
+
# IDE
|
29 |
.vscode/
|
30 |
+
.idea/
|
31 |
+
*.swp
|
32 |
+
*.swo
|
33 |
+
|
34 |
+
# Jupyter
|
35 |
+
.ipynb_checkpoints
|
36 |
+
*.ipynb
|
37 |
+
|
38 |
+
# Environment variables
|
39 |
+
.env
|
40 |
+
.env.local
|
41 |
|
42 |
+
# Logs
|
|
|
|
|
|
|
43 |
logs/
|
44 |
+
*.log
|
.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
@@ -12,16 +12,17 @@ short_description: Leaderboard showcasing Turkish MMLU dataset results.
|
|
12 |
|
13 |
# 🏆 Turkish MMLU Leaderboard
|
14 |
|
15 |
-
A web application for exploring
|
16 |
|
17 |
-
## Features
|
18 |
|
19 |
-
- 📊 Interactive
|
20 |
-
- 🔍
|
21 |
-
- 📈 Visualize section-wise performance
|
22 |
-
- ➕ Submit new models for evaluation
|
|
|
23 |
|
24 |
-
##
|
25 |
|
26 |
### Prerequisites
|
27 |
|
@@ -31,95 +32,68 @@ A web application for exploring, evaluating, and comparing AI model performance
|
|
31 |
### Installation
|
32 |
|
33 |
1. Clone the repository:
|
|
|
34 |
```bash
|
35 |
git clone https://github.com/yourusername/turkish_mmlu_leaderboard.git
|
36 |
cd turkish_mmlu_leaderboard
|
37 |
```
|
38 |
|
39 |
2. Install dependencies:
|
|
|
40 |
```bash
|
41 |
pip install -r requirements.txt
|
42 |
```
|
43 |
|
44 |
3. Run the application:
|
|
|
45 |
```bash
|
46 |
python app.py
|
47 |
```
|
48 |
|
49 |
-
4. Open your browser and navigate to `http://
|
50 |
-
|
51 |
-
## Deploying to Hugging Face Spaces
|
52 |
-
|
53 |
-
### Option 1: Using the Hugging Face UI
|
54 |
|
55 |
-
|
56 |
-
2. Click "Create a new Space"
|
57 |
-
3. Select "Gradio" as the SDK
|
58 |
-
4. Upload your files or connect to your GitHub repository
|
59 |
-
5. The Space will automatically build and deploy
|
60 |
|
61 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
62 |
|
63 |
-
|
64 |
-
2. Select "Docker" as the SDK
|
65 |
-
3. Upload your files including the Dockerfile
|
66 |
-
4. The Space will build and deploy using your Dockerfile
|
67 |
|
68 |
-
|
69 |
|
70 |
-
|
|
|
|
|
71 |
|
72 |
-
|
73 |
-
2. Increase the timeout values in `config.py`
|
74 |
-
3. Make sure your datasets are accessible from Hugging Face Spaces
|
75 |
-
4. Consider using smaller datasets or pre-caching data
|
76 |
|
77 |
-
|
78 |
|
79 |
-
|
|
|
|
|
80 |
|
81 |
-
|
82 |
-
- `UIConfig`: Customize the UI appearance
|
83 |
-
- `ModelConfig`: Define model-related options
|
84 |
|
85 |
-
|
86 |
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
This project is licensed under the MIT License - see the LICENSE file for details.
|
92 |
-
|
93 |
-
# Start the configuration
|
94 |
-
|
95 |
-
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).
|
96 |
-
|
97 |
-
Results files should have the following format and be stored as json files:
|
98 |
-
```json
|
99 |
-
{
|
100 |
-
"config": {
|
101 |
-
"model_dtype": "torch.float16", # or torch.bfloat16 or 8bit or 4bit
|
102 |
-
"model_name": "path of the model on the hub: org/model",
|
103 |
-
"model_sha": "revision on the hub",
|
104 |
-
},
|
105 |
-
"results": {
|
106 |
-
"task_name": {
|
107 |
-
"metric_name": score,
|
108 |
-
},
|
109 |
-
"task_name2": {
|
110 |
-
"metric_name": score,
|
111 |
-
}
|
112 |
-
}
|
113 |
-
}
|
114 |
```
|
115 |
|
116 |
-
|
117 |
|
118 |
-
|
119 |
|
120 |
-
|
121 |
|
122 |
-
|
123 |
-
- the main table' columns names and properties in `src/display/utils.py`
|
124 |
-
- 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`
|
125 |
-
- the logic to allow or filter submissions in `src/submission/submit.py` and `src/submission/check_validity.py`
|
|
|
12 |
|
13 |
# 🏆 Turkish MMLU Leaderboard
|
14 |
|
15 |
+
A clean, modern web application for exploring and comparing AI model performance on the Turkish Massive Multitask Language Understanding (MMLU) benchmark.
|
16 |
|
17 |
+
## ✨ Features
|
18 |
|
19 |
+
- 📊 **Interactive Leaderboard**: Filter and sort models by family, quantization, and performance
|
20 |
+
- 🔍 **Model Responses Browser**: Browse through all 6,200 questions and model answers with pagination
|
21 |
+
- 📈 **Performance Analytics**: Visualize section-wise performance with interactive charts
|
22 |
+
- ➕ **Model Submission**: Submit new models for evaluation
|
23 |
+
- 🎨 **Clean UI**: Modern, responsive design with beautiful styling
|
24 |
|
25 |
+
## 🚀 Quick Start
|
26 |
|
27 |
### Prerequisites
|
28 |
|
|
|
32 |
### Installation
|
33 |
|
34 |
1. Clone the repository:
|
35 |
+
|
36 |
```bash
|
37 |
git clone https://github.com/yourusername/turkish_mmlu_leaderboard.git
|
38 |
cd turkish_mmlu_leaderboard
|
39 |
```
|
40 |
|
41 |
2. Install dependencies:
|
42 |
+
|
43 |
```bash
|
44 |
pip install -r requirements.txt
|
45 |
```
|
46 |
|
47 |
3. Run the application:
|
48 |
+
|
49 |
```bash
|
50 |
python app.py
|
51 |
```
|
52 |
|
53 |
+
4. Open your browser and navigate to `http://localhost:7860`
|
|
|
|
|
|
|
|
|
54 |
|
55 |
+
## 📁 Project Structure
|
|
|
|
|
|
|
|
|
56 |
|
57 |
+
```
|
58 |
+
turkish_mmlu_leaderboard/
|
59 |
+
├── app.py # Main Gradio application
|
60 |
+
├── config.py # Configuration settings
|
61 |
+
├── data_manager.py # Data loading and caching
|
62 |
+
├── utils.py # Utility functions for search and validation
|
63 |
+
├── requirements.txt # Python dependencies
|
64 |
+
├── Dockerfile # Docker configuration
|
65 |
+
└── README.md # This file
|
66 |
+
```
|
67 |
|
68 |
+
## 🔧 Configuration
|
|
|
|
|
|
|
69 |
|
70 |
+
The application can be configured by modifying `config.py`:
|
71 |
|
72 |
+
- **DatasetConfig**: Dataset paths, cache settings, refresh intervals
|
73 |
+
- **UIConfig**: UI appearance and styling
|
74 |
+
- **ModelConfig**: Model-related options and validation
|
75 |
|
76 |
+
## 📊 Data Sources
|
|
|
|
|
|
|
77 |
|
78 |
+
The leaderboard loads data from three Hugging Face datasets:
|
79 |
|
80 |
+
- **Leaderboard Data**: Model rankings and scores
|
81 |
+
- **Model Responses**: Individual model answers to questions
|
82 |
+
- **Section Results**: Performance breakdown by subject areas
|
83 |
|
84 |
+
## 🐳 Docker Deployment
|
|
|
|
|
85 |
|
86 |
+
Build and run with Docker:
|
87 |
|
88 |
+
```bash
|
89 |
+
docker build -t turkish-mmlu-leaderboard .
|
90 |
+
docker run -p 7860:7860 turkish-mmlu-leaderboard
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
91 |
```
|
92 |
|
93 |
+
## 🤝 Contributing
|
94 |
|
95 |
+
Contributions are welcome! Please feel free to submit a Pull Request.
|
96 |
|
97 |
+
## 📄 License
|
98 |
|
99 |
+
This project is licensed under the CC-BY-NC-4.0 License.
|
|
|
|
|
|
app.py
CHANGED
@@ -1,109 +1,402 @@
|
|
1 |
-
import gradio as gr
|
2 |
-
from apscheduler.schedulers.background import BackgroundScheduler
|
3 |
-
from typing import Optional
|
4 |
import logging
|
5 |
import sys
|
6 |
import time
|
|
|
|
|
|
|
|
|
|
|
|
|
7 |
|
8 |
from config import CONFIG
|
9 |
from data_manager import data_manager
|
10 |
-
from utils import
|
11 |
|
12 |
logging.basicConfig(level=logging.INFO)
|
13 |
logger = logging.getLogger(__name__)
|
14 |
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
37 |
|
38 |
-
#
|
39 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
40 |
|
41 |
-
with gr.Blocks(css=
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
46 |
# Leaderboard Tab
|
47 |
with gr.TabItem("📊 Leaderboard"):
|
|
|
|
|
48 |
with gr.Row():
|
49 |
family_filter = gr.Dropdown(
|
50 |
-
choices=
|
51 |
label="Filter by Family",
|
52 |
-
|
53 |
)
|
54 |
quantization_filter = gr.Dropdown(
|
55 |
-
choices=
|
56 |
-
label="Filter by Quantization
|
|
|
57 |
)
|
|
|
58 |
|
59 |
-
filter_btn = gr.Button("Apply Filters", variant="primary")
|
60 |
leaderboard_table = gr.DataFrame(
|
61 |
-
value=
|
62 |
-
interactive=False
|
|
|
63 |
)
|
64 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
65 |
filter_btn.click(
|
66 |
-
|
67 |
inputs=[family_filter, quantization_filter],
|
68 |
outputs=leaderboard_table
|
69 |
)
|
70 |
-
|
71 |
# Model Responses Tab
|
72 |
with gr.TabItem("🔍 Model Responses"):
|
|
|
|
|
|
|
73 |
with gr.Row():
|
74 |
model_dropdown = gr.Dropdown(
|
75 |
-
choices=
|
76 |
-
label="Select Model"
|
|
|
77 |
)
|
78 |
query_input = gr.Textbox(
|
79 |
-
label="Search Query",
|
80 |
-
placeholder="Enter search
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
81 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
82 |
|
83 |
-
|
84 |
-
|
85 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
86 |
search_btn.click(
|
87 |
-
|
88 |
-
inputs=[query_input, model_dropdown],
|
89 |
-
outputs=responses_table
|
90 |
)
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
97 |
# Submit Model Tab
|
98 |
with gr.TabItem("➕ Submit Model"):
|
99 |
-
gr.Markdown("### Submit Your Model
|
|
|
100 |
|
101 |
-
with gr.
|
102 |
-
|
103 |
-
|
104 |
-
|
|
|
105 |
|
106 |
-
with gr.
|
107 |
precision = gr.Dropdown(
|
108 |
choices=CONFIG["model"].precision_options,
|
109 |
label="Precision",
|
@@ -121,25 +414,36 @@ def create_app() -> gr.Blocks:
|
|
121 |
)
|
122 |
|
123 |
submit_btn = gr.Button("Submit Model", variant="primary")
|
124 |
-
submission_output = gr.
|
125 |
|
126 |
def handle_submission(*args):
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
|
|
|
|
|
|
|
|
131 |
|
132 |
submit_btn.click(
|
133 |
handle_submission,
|
134 |
inputs=[model_name, base_model, revision, precision, weight_type, model_type],
|
135 |
outputs=submission_output
|
136 |
)
|
137 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
138 |
return app
|
139 |
|
140 |
def main():
|
141 |
try:
|
142 |
-
# Initialize scheduler
|
143 |
scheduler = BackgroundScheduler()
|
144 |
scheduler.add_job(
|
145 |
data_manager.refresh_datasets,
|
@@ -149,19 +453,16 @@ def main():
|
|
149 |
scheduler.start()
|
150 |
|
151 |
# Create and launch app
|
152 |
-
app =
|
153 |
-
app.queue(
|
154 |
-
|
155 |
-
server_name="0.0.0.0", # Use 0.0.0.0 to listen on all interfaces
|
156 |
server_port=7860,
|
157 |
share=False,
|
158 |
-
|
159 |
-
show_error=True,
|
160 |
-
max_threads=40
|
161 |
)
|
162 |
except Exception as e:
|
163 |
logger.error(f"Error starting application: {e}")
|
164 |
sys.exit(1)
|
165 |
|
166 |
if __name__ == "__main__":
|
167 |
-
main()
|
|
|
|
|
|
|
|
|
1 |
import logging
|
2 |
import sys
|
3 |
import time
|
4 |
+
from typing import Optional
|
5 |
+
|
6 |
+
import gradio as gr
|
7 |
+
import plotly.express as px
|
8 |
+
import plotly.graph_objects as go
|
9 |
+
from apscheduler.schedulers.background import BackgroundScheduler
|
10 |
|
11 |
from config import CONFIG
|
12 |
from data_manager import data_manager
|
13 |
+
from utils import search_responses, validate_model_submission
|
14 |
|
15 |
logging.basicConfig(level=logging.INFO)
|
16 |
logger = logging.getLogger(__name__)
|
17 |
|
18 |
+
# Clean, minimal CSS
|
19 |
+
CLEAN_CSS = """
|
20 |
+
.gradio-container {
|
21 |
+
max-width: 1200px !important;
|
22 |
+
margin: 0 auto !important;
|
23 |
+
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif !important;
|
24 |
+
}
|
25 |
+
|
26 |
+
.main-header {
|
27 |
+
text-align: center;
|
28 |
+
background: linear-gradient(135deg, #4f46e5 0%, #7c3aed 100%);
|
29 |
+
color: white;
|
30 |
+
padding: 2rem;
|
31 |
+
border-radius: 12px;
|
32 |
+
margin-bottom: 2rem;
|
33 |
+
box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
|
34 |
+
}
|
35 |
+
|
36 |
+
.main-header h1 {
|
37 |
+
font-size: 2.5rem !important;
|
38 |
+
font-weight: 700 !important;
|
39 |
+
margin-bottom: 0.5rem !important;
|
40 |
+
}
|
41 |
+
|
42 |
+
.main-header p {
|
43 |
+
font-size: 1.1rem !important;
|
44 |
+
opacity: 0.9;
|
45 |
+
}
|
46 |
+
|
47 |
+
.status-info {
|
48 |
+
background: #f8fafc;
|
49 |
+
border: 1px solid #e2e8f0;
|
50 |
+
border-radius: 8px;
|
51 |
+
padding: 1rem;
|
52 |
+
margin: 1rem 0;
|
53 |
+
font-size: 0.9rem;
|
54 |
+
color: #475569;
|
55 |
+
}
|
56 |
+
|
57 |
+
.gr-button {
|
58 |
+
border-radius: 8px !important;
|
59 |
+
font-weight: 500 !important;
|
60 |
+
}
|
61 |
+
|
62 |
+
.gr-dataframe {
|
63 |
+
border-radius: 8px !important;
|
64 |
+
border: 1px solid #e2e8f0 !important;
|
65 |
+
}
|
66 |
+
"""
|
67 |
+
|
68 |
+
def create_simple_plot():
|
69 |
+
"""Create a simple, clean plot."""
|
70 |
+
try:
|
71 |
+
df = data_manager.section_results_data
|
72 |
+
|
73 |
+
if df.empty:
|
74 |
+
fig = go.Figure()
|
75 |
+
fig.add_annotation(
|
76 |
+
text="No data available",
|
77 |
+
xref="paper", yref="paper",
|
78 |
+
x=0.5, y=0.5, xanchor='center', yanchor='middle',
|
79 |
+
showarrow=False,
|
80 |
+
font=dict(size=16, color="gray")
|
81 |
+
)
|
82 |
+
fig.update_layout(
|
83 |
+
title="Section Performance",
|
84 |
+
height=400,
|
85 |
+
plot_bgcolor='white'
|
86 |
+
)
|
87 |
+
return fig
|
88 |
+
|
89 |
+
# Simple bar chart
|
90 |
+
numeric_cols = df.select_dtypes(include=['number']).columns
|
91 |
+
if len(numeric_cols) > 0:
|
92 |
+
avg_scores = df[numeric_cols].mean()
|
93 |
+
|
94 |
+
fig = go.Figure(data=[
|
95 |
+
go.Bar(
|
96 |
+
x=avg_scores.index,
|
97 |
+
y=avg_scores.values,
|
98 |
+
marker_color='#4f46e5',
|
99 |
+
text=[f'{v:.1f}%' for v in avg_scores.values],
|
100 |
+
textposition='auto',
|
101 |
+
)
|
102 |
+
])
|
103 |
+
|
104 |
+
fig.update_layout(
|
105 |
+
title="Average Section Performance",
|
106 |
+
xaxis_title="Sections",
|
107 |
+
yaxis_title="Accuracy (%)",
|
108 |
+
height=400,
|
109 |
+
plot_bgcolor='white',
|
110 |
+
paper_bgcolor='white'
|
111 |
+
)
|
112 |
+
|
113 |
+
return fig
|
114 |
+
|
115 |
+
except Exception as e:
|
116 |
+
logger.error(f"Error creating plot: {e}")
|
117 |
+
fig = go.Figure()
|
118 |
+
fig.add_annotation(
|
119 |
+
text=f"Error: {str(e)}",
|
120 |
+
xref="paper", yref="paper",
|
121 |
+
x=0.5, y=0.5, xanchor='center', yanchor='middle',
|
122 |
+
showarrow=False,
|
123 |
+
font=dict(size=14, color="red")
|
124 |
+
)
|
125 |
+
fig.update_layout(title="Section Performance", height=400)
|
126 |
+
return fig
|
127 |
+
|
128 |
+
def create_clean_app():
|
129 |
+
"""Create a clean, simple Gradio app."""
|
130 |
|
131 |
+
# Get basic data info
|
132 |
+
try:
|
133 |
+
leaderboard_data = data_manager.leaderboard_data
|
134 |
+
responses_data = data_manager.responses_data
|
135 |
+
|
136 |
+
# Get available models for responses
|
137 |
+
available_models = []
|
138 |
+
if not responses_data.empty:
|
139 |
+
available_models = [col.replace("_cevap", "") for col in responses_data.columns if col.endswith("_cevap")]
|
140 |
+
|
141 |
+
data_status = f"✅ Loaded: {len(leaderboard_data)} leaderboard entries, {len(responses_data)} responses, {len(available_models)} models"
|
142 |
+
except Exception as e:
|
143 |
+
data_status = f"⚠️ Data loading issue: {str(e)}"
|
144 |
+
available_models = []
|
145 |
|
146 |
+
with gr.Blocks(css=CLEAN_CSS, title="Turkish MMLU Leaderboard") as app:
|
147 |
+
|
148 |
+
# Header
|
149 |
+
gr.HTML(f"""
|
150 |
+
<div class="main-header">
|
151 |
+
<h1>🏆 Turkish MMLU Leaderboard</h1>
|
152 |
+
<p>Comprehensive evaluation of AI models on Turkish language tasks</p>
|
153 |
+
</div>
|
154 |
+
""")
|
155 |
+
|
156 |
+
# Status
|
157 |
+
gr.HTML(f'<div class="status-info">{data_status}</div>')
|
158 |
+
|
159 |
+
with gr.Tabs():
|
160 |
+
|
161 |
# Leaderboard Tab
|
162 |
with gr.TabItem("📊 Leaderboard"):
|
163 |
+
gr.Markdown("### Model Performance Rankings")
|
164 |
+
|
165 |
with gr.Row():
|
166 |
family_filter = gr.Dropdown(
|
167 |
+
choices=["All"] + (leaderboard_data["family"].unique().tolist() if not leaderboard_data.empty else []),
|
168 |
label="Filter by Family",
|
169 |
+
value="All"
|
170 |
)
|
171 |
quantization_filter = gr.Dropdown(
|
172 |
+
choices=["All"] + (leaderboard_data["quantization_level"].unique().tolist() if not leaderboard_data.empty else []),
|
173 |
+
label="Filter by Quantization",
|
174 |
+
value="All"
|
175 |
)
|
176 |
+
filter_btn = gr.Button("Apply Filters", variant="primary")
|
177 |
|
|
|
178 |
leaderboard_table = gr.DataFrame(
|
179 |
+
value=leaderboard_data,
|
180 |
+
interactive=False,
|
181 |
+
wrap=True
|
182 |
)
|
183 |
|
184 |
+
def simple_filter(family, quantization):
|
185 |
+
try:
|
186 |
+
df = data_manager.leaderboard_data.copy()
|
187 |
+
if df.empty:
|
188 |
+
return df
|
189 |
+
|
190 |
+
if family and family != "All":
|
191 |
+
df = df[df["family"] == family]
|
192 |
+
if quantization and quantization != "All":
|
193 |
+
df = df[df["quantization_level"] == quantization]
|
194 |
+
|
195 |
+
if "score" in df.columns:
|
196 |
+
df = df.sort_values("score", ascending=False)
|
197 |
+
|
198 |
+
return df
|
199 |
+
except Exception as e:
|
200 |
+
logger.error(f"Filter error: {e}")
|
201 |
+
return data_manager.leaderboard_data
|
202 |
+
|
203 |
filter_btn.click(
|
204 |
+
simple_filter,
|
205 |
inputs=[family_filter, quantization_filter],
|
206 |
outputs=leaderboard_table
|
207 |
)
|
208 |
+
|
209 |
# Model Responses Tab
|
210 |
with gr.TabItem("🔍 Model Responses"):
|
211 |
+
gr.Markdown("### Browse Model Responses")
|
212 |
+
gr.Markdown("**Browse all 6,200 questions and model answers, or search for specific content.**")
|
213 |
+
|
214 |
with gr.Row():
|
215 |
model_dropdown = gr.Dropdown(
|
216 |
+
choices=available_models,
|
217 |
+
label="Select Model (Optional - leave empty to see all models)",
|
218 |
+
scale=2
|
219 |
)
|
220 |
query_input = gr.Textbox(
|
221 |
+
label="Search Query (Optional - leave empty to see all questions)",
|
222 |
+
placeholder="Enter keywords to search, or leave empty to browse all...",
|
223 |
+
scale=2
|
224 |
+
)
|
225 |
+
search_btn = gr.Button("Search/Browse", variant="primary", scale=1)
|
226 |
+
|
227 |
+
with gr.Row():
|
228 |
+
show_all_btn = gr.Button("📋 Show All Questions", variant="secondary")
|
229 |
+
refresh_btn = gr.Button("🔄 Refresh Models", variant="secondary")
|
230 |
+
page_size_dropdown = gr.Dropdown(
|
231 |
+
choices=[25, 50, 100, 200],
|
232 |
+
value=50,
|
233 |
+
label="Items per page",
|
234 |
+
scale=1
|
235 |
+
)
|
236 |
+
|
237 |
+
# Pagination controls
|
238 |
+
with gr.Row():
|
239 |
+
prev_btn = gr.Button("⬅️ Previous", variant="secondary", scale=1)
|
240 |
+
page_info = gr.HTML("<div style='text-align: center; padding: 10px;'>Page 1 of 124 (6,200 questions)</div>")
|
241 |
+
next_btn = gr.Button("Next ➡️", variant="secondary", scale=1)
|
242 |
+
|
243 |
+
with gr.Row():
|
244 |
+
page_input = gr.Number(
|
245 |
+
label="Go to page",
|
246 |
+
value=1,
|
247 |
+
minimum=1,
|
248 |
+
step=1,
|
249 |
+
scale=1
|
250 |
)
|
251 |
+
go_page_btn = gr.Button("Go", variant="secondary", scale=1)
|
252 |
+
|
253 |
+
gr.Markdown("💡 **Tip**: Use pagination to browse through all 6,200 questions! Leave both fields empty to see all model responses.")
|
254 |
+
|
255 |
+
# Initialize with some responses data
|
256 |
+
try:
|
257 |
+
from utils import get_all_responses, get_pagination_info
|
258 |
+
initial_responses = get_all_responses(model=None, page=1, page_size=50)
|
259 |
+
initial_page_info = get_pagination_info(page=1, page_size=50)
|
260 |
+
initial_page_html = f"<div style='text-align: center; padding: 12px; background: linear-gradient(135deg, #e0f2fe 0%, #f3e5f5 100%); border: 1px solid #b3e5fc; border-radius: 10px; color: #1565c0; font-weight: 500; box-shadow: 0 2px 4px rgba(0,0,0,0.1);'>📄 Page {initial_page_info['current_page']} of {initial_page_info['total_pages']} • Showing {initial_page_info['start_idx']}-{initial_page_info['end_idx']} of {initial_page_info['total_rows']} questions</div>"
|
261 |
+
except Exception as e:
|
262 |
+
logger.error(f"Error loading initial responses: {e}")
|
263 |
+
initial_responses = pd.DataFrame({"ℹ️ Info": ["Click 'Show All Questions' to load responses"]})
|
264 |
+
initial_page_html = "<div style='text-align: center; padding: 10px;'>Page 1 of 1 (0 items)</div>"
|
265 |
+
|
266 |
+
responses_table = gr.DataFrame(value=initial_responses, wrap=True)
|
267 |
+
|
268 |
+
# State variables for pagination
|
269 |
+
current_page = gr.State(1)
|
270 |
+
current_query = gr.State("")
|
271 |
+
current_model = gr.State("")
|
272 |
+
current_page_size = gr.State(50)
|
273 |
|
274 |
+
# Update page info display with improved styling
|
275 |
+
page_info.value = initial_page_html
|
276 |
|
277 |
+
def refresh_models():
|
278 |
+
try:
|
279 |
+
responses_data = data_manager.responses_data
|
280 |
+
if not responses_data.empty:
|
281 |
+
models = [col.replace("_cevap", "") for col in responses_data.columns if col.endswith("_cevap")]
|
282 |
+
return gr.Dropdown(choices=models, value=None)
|
283 |
+
return gr.Dropdown(choices=[], value=None)
|
284 |
+
except Exception as e:
|
285 |
+
logger.error(f"Refresh error: {e}")
|
286 |
+
return gr.Dropdown(choices=[], value=None)
|
287 |
+
|
288 |
+
def show_all_responses(page_size):
|
289 |
+
"""Show all responses without any filters"""
|
290 |
+
from utils import get_all_responses, get_pagination_info
|
291 |
+
responses = get_all_responses(model=None, page=1, page_size=page_size)
|
292 |
+
page_info_data = get_pagination_info(page=1, page_size=page_size)
|
293 |
+
page_html = f"<div style='text-align: center; padding: 12px; background: linear-gradient(135deg, #e0f2fe 0%, #f3e5f5 100%); border: 1px solid #b3e5fc; border-radius: 10px; color: #1565c0; font-weight: 500; box-shadow: 0 2px 4px rgba(0,0,0,0.1);'>📄 Page {page_info_data['current_page']} of {page_info_data['total_pages']} • Showing {page_info_data['start_idx']}-{page_info_data['end_idx']} of {page_info_data['total_rows']} questions</div>"
|
294 |
+
return responses, page_html, 1, "", "", page_size
|
295 |
+
|
296 |
+
def search_with_pagination(query, model, page, page_size):
|
297 |
+
"""Search with pagination support"""
|
298 |
+
from utils import get_pagination_info, search_responses
|
299 |
+
responses = search_responses(query, model, page, page_size)
|
300 |
+
|
301 |
+
# Get pagination info
|
302 |
+
if query and query.strip():
|
303 |
+
# For search results, we need to calculate based on search results
|
304 |
+
page_html = f"<div style='text-align: center; padding: 12px; background: linear-gradient(135deg, #fff3cd 0%, #ffeaa7 100%); border: 1px solid #fdcb6e; border-radius: 10px; color: #d63031; font-weight: 500; box-shadow: 0 2px 4px rgba(0,0,0,0.1);'>🔍 Search results for '{query}' • Page {page}</div>"
|
305 |
+
else:
|
306 |
+
page_info_data = get_pagination_info(page, page_size)
|
307 |
+
page_html = f"<div style='text-align: center; padding: 12px; background: linear-gradient(135deg, #e0f2fe 0%, #f3e5f5 100%); border: 1px solid #b3e5fc; border-radius: 10px; color: #1565c0; font-weight: 500; box-shadow: 0 2px 4px rgba(0,0,0,0.1);'>📄 Page {page_info_data['current_page']} of {page_info_data['total_pages']} • Showing {page_info_data['start_idx']}-{page_info_data['end_idx']} of {page_info_data['total_rows']} questions</div>"
|
308 |
+
|
309 |
+
return responses, page_html, page, query, model, page_size
|
310 |
+
|
311 |
+
def go_to_page(page_num, query, model, page_size):
|
312 |
+
"""Go to specific page"""
|
313 |
+
page_num = max(1, int(page_num)) if page_num else 1
|
314 |
+
return search_with_pagination(query, model, page_num, page_size)
|
315 |
+
|
316 |
+
def next_page(current_page_val, query, model, page_size):
|
317 |
+
"""Go to next page"""
|
318 |
+
from utils import get_pagination_info
|
319 |
+
page_info_data = get_pagination_info(current_page_val, page_size)
|
320 |
+
if page_info_data['has_next']:
|
321 |
+
return search_with_pagination(query, model, current_page_val + 1, page_size)
|
322 |
+
return search_with_pagination(query, model, current_page_val, page_size)
|
323 |
+
|
324 |
+
def prev_page(current_page_val, query, model, page_size):
|
325 |
+
"""Go to previous page"""
|
326 |
+
if current_page_val > 1:
|
327 |
+
return search_with_pagination(query, model, current_page_val - 1, page_size)
|
328 |
+
return search_with_pagination(query, model, current_page_val, page_size)
|
329 |
+
|
330 |
+
def change_page_size(new_page_size, query, model):
|
331 |
+
"""Change page size and reset to page 1"""
|
332 |
+
return search_with_pagination(query, model, 1, new_page_size)
|
333 |
+
|
334 |
+
# Event handlers
|
335 |
search_btn.click(
|
336 |
+
search_with_pagination,
|
337 |
+
inputs=[query_input, model_dropdown, current_page, current_page_size],
|
338 |
+
outputs=[responses_table, page_info, current_page, current_query, current_model, current_page_size]
|
339 |
)
|
340 |
+
|
341 |
+
show_all_btn.click(
|
342 |
+
show_all_responses,
|
343 |
+
inputs=[current_page_size],
|
344 |
+
outputs=[responses_table, page_info, current_page, current_query, current_model, current_page_size]
|
345 |
+
)
|
346 |
+
|
347 |
+
next_btn.click(
|
348 |
+
next_page,
|
349 |
+
inputs=[current_page, current_query, current_model, current_page_size],
|
350 |
+
outputs=[responses_table, page_info, current_page, current_query, current_model, current_page_size]
|
351 |
+
)
|
352 |
+
|
353 |
+
prev_btn.click(
|
354 |
+
prev_page,
|
355 |
+
inputs=[current_page, current_query, current_model, current_page_size],
|
356 |
+
outputs=[responses_table, page_info, current_page, current_query, current_model, current_page_size]
|
357 |
+
)
|
358 |
+
|
359 |
+
go_page_btn.click(
|
360 |
+
go_to_page,
|
361 |
+
inputs=[page_input, current_query, current_model, current_page_size],
|
362 |
+
outputs=[responses_table, page_info, current_page, current_query, current_model, current_page_size]
|
363 |
+
)
|
364 |
+
|
365 |
+
page_size_dropdown.change(
|
366 |
+
change_page_size,
|
367 |
+
inputs=[page_size_dropdown, current_query, current_model],
|
368 |
+
outputs=[responses_table, page_info, current_page, current_query, current_model, current_page_size]
|
369 |
+
)
|
370 |
+
|
371 |
+
refresh_btn.click(
|
372 |
+
refresh_models,
|
373 |
+
outputs=model_dropdown
|
374 |
+
)
|
375 |
+
|
376 |
+
# Analytics Tab
|
377 |
+
with gr.TabItem("📈 Analytics"):
|
378 |
+
gr.Markdown("### Performance Analytics")
|
379 |
+
|
380 |
+
plot_output = gr.Plot(value=create_simple_plot())
|
381 |
+
|
382 |
+
gr.Markdown("### Section Results")
|
383 |
+
section_table = gr.DataFrame(
|
384 |
+
value=data_manager.section_results_data,
|
385 |
+
wrap=True
|
386 |
+
)
|
387 |
+
|
388 |
# Submit Model Tab
|
389 |
with gr.TabItem("➕ Submit Model"):
|
390 |
+
gr.Markdown("### Submit Your Model")
|
391 |
+
gr.Markdown("Add your model to the leaderboard for evaluation.")
|
392 |
|
393 |
+
with gr.Row():
|
394 |
+
with gr.Column():
|
395 |
+
model_name = gr.Textbox(label="Model Name", placeholder="Enter model name")
|
396 |
+
base_model = gr.Textbox(label="Base Model", placeholder="Enter base model")
|
397 |
+
revision = gr.Textbox(label="Revision", value="main")
|
398 |
|
399 |
+
with gr.Column():
|
400 |
precision = gr.Dropdown(
|
401 |
choices=CONFIG["model"].precision_options,
|
402 |
label="Precision",
|
|
|
414 |
)
|
415 |
|
416 |
submit_btn = gr.Button("Submit Model", variant="primary")
|
417 |
+
submission_output = gr.HTML()
|
418 |
|
419 |
def handle_submission(*args):
|
420 |
+
try:
|
421 |
+
is_valid, message = validate_model_submission(*args)
|
422 |
+
if is_valid:
|
423 |
+
return f'<div style="color: green; padding: 10px; border: 1px solid green; border-radius: 5px;">✅ {message}</div>'
|
424 |
+
else:
|
425 |
+
return f'<div style="color: red; padding: 10px; border: 1px solid red; border-radius: 5px;">❌ {message}</div>'
|
426 |
+
except Exception as e:
|
427 |
+
return f'<div style="color: red; padding: 10px; border: 1px solid red; border-radius: 5px;">❌ Error: {str(e)}</div>'
|
428 |
|
429 |
submit_btn.click(
|
430 |
handle_submission,
|
431 |
inputs=[model_name, base_model, revision, precision, weight_type, model_type],
|
432 |
outputs=submission_output
|
433 |
)
|
434 |
+
|
435 |
+
# Footer
|
436 |
+
gr.HTML("""
|
437 |
+
<div style="text-align: center; padding: 20px; color: #64748b; border-top: 1px solid #e2e8f0; margin-top: 40px;">
|
438 |
+
<p>🏆 Turkish MMLU Leaderboard • Built with Gradio</p>
|
439 |
+
</div>
|
440 |
+
""")
|
441 |
+
|
442 |
return app
|
443 |
|
444 |
def main():
|
445 |
try:
|
446 |
+
# Initialize scheduler
|
447 |
scheduler = BackgroundScheduler()
|
448 |
scheduler.add_job(
|
449 |
data_manager.refresh_datasets,
|
|
|
453 |
scheduler.start()
|
454 |
|
455 |
# Create and launch app
|
456 |
+
app = create_clean_app()
|
457 |
+
app.queue().launch(
|
458 |
+
server_name="0.0.0.0",
|
|
|
459 |
server_port=7860,
|
460 |
share=False,
|
461 |
+
show_error=True
|
|
|
|
|
462 |
)
|
463 |
except Exception as e:
|
464 |
logger.error(f"Error starting application: {e}")
|
465 |
sys.exit(1)
|
466 |
|
467 |
if __name__ == "__main__":
|
468 |
+
main()
|
app_e.py
DELETED
@@ -1,115 +0,0 @@
|
|
1 |
-
import gradio as gr
|
2 |
-
from apscheduler.schedulers.background import BackgroundScheduler
|
3 |
-
from huggingface_hub import snapshot_download
|
4 |
-
import pandas as pd
|
5 |
-
import matplotlib.pyplot as plt
|
6 |
-
|
7 |
-
# Dataset paths
|
8 |
-
LEADERBOARD_PATH = "hf://datasets/alibayram/yapay_zeka_turkce_mmlu_liderlik_tablosu/data/train-00000-of-00001.parquet"
|
9 |
-
RESPONSES_PATH = "hf://datasets/alibayram/yapay_zeka_turkce_mmlu_model_cevaplari/data/train-00000-of-00001.parquet"
|
10 |
-
SECTION_RESULTS_PATH = "hf://datasets/alibayram/yapay_zeka_turkce_mmlu_bolum_sonuclari/data/train-00000-of-00001.parquet"
|
11 |
-
|
12 |
-
# Load datasets
|
13 |
-
try:
|
14 |
-
leaderboard_data = pd.read_parquet(LEADERBOARD_PATH)
|
15 |
-
model_responses_data = pd.read_parquet(RESPONSES_PATH)
|
16 |
-
section_results_data = pd.read_parquet(SECTION_RESULTS_PATH)
|
17 |
-
except Exception as e:
|
18 |
-
print(f"Error loading datasets: {e}")
|
19 |
-
raise
|
20 |
-
|
21 |
-
# Helper functions
|
22 |
-
def filter_leaderboard(family=None, quantization_level=None):
|
23 |
-
df = leaderboard_data.copy()
|
24 |
-
if family:
|
25 |
-
df = df[df["family"] == family]
|
26 |
-
if quantization_level:
|
27 |
-
df = df[df["quantization_level"] == quantization_level]
|
28 |
-
return df
|
29 |
-
|
30 |
-
def search_responses(query, model):
|
31 |
-
filtered = model_responses_data[model_responses_data["bolum"].str.contains(query, case=False)]
|
32 |
-
selected_columns = ["bolum", "soru", "cevap", model + "_cevap"]
|
33 |
-
return filtered[selected_columns]
|
34 |
-
|
35 |
-
def plot_section_results():
|
36 |
-
fig, ax = plt.subplots(figsize=(10, 6))
|
37 |
-
avg_scores = section_results_data.mean(numeric_only=True)
|
38 |
-
avg_scores.plot(kind="bar", ax=ax)
|
39 |
-
ax.set_title("Average Section-Wise Performance")
|
40 |
-
ax.set_ylabel("Accuracy (%)")
|
41 |
-
ax.set_xlabel("Sections")
|
42 |
-
return fig # Return the figure object
|
43 |
-
|
44 |
-
def add_new_model(model_name, base_model, revision, precision, weight_type, model_type):
|
45 |
-
# Simulated model submission logic
|
46 |
-
return f"Model '{model_name}' submitted successfully!"
|
47 |
-
|
48 |
-
# Gradio app structure
|
49 |
-
with gr.Blocks(css=".container { max-width: 1200px; margin: auto; }") as app:
|
50 |
-
gr.HTML("<h1>🏆 Turkish MMLU Leaderboard</h1>")
|
51 |
-
gr.Markdown("Explore, evaluate, and compare AI model performance.")
|
52 |
-
|
53 |
-
with gr.Tabs() as tabs:
|
54 |
-
# Leaderboard Tab
|
55 |
-
with gr.TabItem("Leaderboard"):
|
56 |
-
family_filter = gr.Dropdown(
|
57 |
-
choices=leaderboard_data["family"].unique().tolist(), label="Filter by Family", multiselect=False
|
58 |
-
)
|
59 |
-
quantization_filter = gr.Dropdown(
|
60 |
-
choices=leaderboard_data["quantization_level"].unique().tolist(), label="Filter by Quantization Level"
|
61 |
-
)
|
62 |
-
leaderboard_table = gr.DataFrame(leaderboard_data)
|
63 |
-
gr.Button("Apply Filters").click(
|
64 |
-
filter_leaderboard, inputs=[family_filter, quantization_filter], outputs=leaderboard_table
|
65 |
-
)
|
66 |
-
|
67 |
-
# Model Responses Tab
|
68 |
-
with gr.TabItem("Model Responses"):
|
69 |
-
model_dropdown = gr.Dropdown(
|
70 |
-
choices=leaderboard_data["model"].unique().tolist(), label="Select Model"
|
71 |
-
)
|
72 |
-
query_input = gr.Textbox(label="Search Query")
|
73 |
-
responses_table = gr.DataFrame()
|
74 |
-
gr.Button("Search").click(
|
75 |
-
search_responses, inputs=[query_input, model_dropdown], outputs=responses_table
|
76 |
-
)
|
77 |
-
|
78 |
-
# Section Results Tab
|
79 |
-
with gr.TabItem("Section Results"):
|
80 |
-
gr.Plot(plot_section_results)
|
81 |
-
gr.DataFrame(section_results_data)
|
82 |
-
|
83 |
-
# Submit Model Tab
|
84 |
-
with gr.TabItem("Submit Model"):
|
85 |
-
gr.Markdown("### Submit Your Model for Evaluation")
|
86 |
-
model_name = gr.Textbox(label="Model Name")
|
87 |
-
base_model = gr.Textbox(label="Base Model")
|
88 |
-
revision = gr.Textbox(label="Revision", placeholder="main")
|
89 |
-
precision = gr.Dropdown(
|
90 |
-
choices=["float16", "int8", "bfloat16", "float32"], label="Precision", value="float16"
|
91 |
-
)
|
92 |
-
weight_type = gr.Dropdown(
|
93 |
-
choices=["Original", "Delta", "Adapter"], label="Weight Type", value="Original"
|
94 |
-
)
|
95 |
-
model_type = gr.Dropdown(
|
96 |
-
choices=["Transformer", "RNN", "GPT", "Other"], label="Model Type", value="Transformer"
|
97 |
-
)
|
98 |
-
submit_button = gr.Button("Submit")
|
99 |
-
submission_output = gr.Markdown()
|
100 |
-
submit_button.click(
|
101 |
-
add_new_model,
|
102 |
-
inputs=[model_name, base_model, revision, precision, weight_type, model_type],
|
103 |
-
outputs=submission_output,
|
104 |
-
)
|
105 |
-
|
106 |
-
# Scheduler for refreshing datasets
|
107 |
-
scheduler = BackgroundScheduler()
|
108 |
-
scheduler.add_job(
|
109 |
-
lambda: snapshot_download(repo_id="alibayram", repo_type="dataset", local_dir="cache"),
|
110 |
-
"interval", seconds=1800
|
111 |
-
)
|
112 |
-
scheduler.start()
|
113 |
-
|
114 |
-
# Launch app
|
115 |
-
app.queue(default_concurrency_limit=40).launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
app_ex.py
DELETED
@@ -1,204 +0,0 @@
|
|
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()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
config.py
CHANGED
@@ -1,6 +1,7 @@
|
|
1 |
from dataclasses import dataclass
|
2 |
from typing import Dict, List
|
3 |
|
|
|
4 |
@dataclass
|
5 |
class DatasetConfig:
|
6 |
leaderboard_path: str = "hf://datasets/alibayram/yapay_zeka_turkce_mmlu_liderlik_tablosu/data/train-00000-of-00001.parquet"
|
@@ -15,22 +16,139 @@ class DatasetConfig:
|
|
15 |
@dataclass
|
16 |
class UIConfig:
|
17 |
title: str = "🏆 Turkish MMLU Leaderboard"
|
18 |
-
description: str = "Explore, evaluate, and compare AI model performance."
|
19 |
-
theme: str = "
|
20 |
css: str = """
|
21 |
-
|
22 |
-
.
|
23 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
24 |
"""
|
25 |
|
26 |
@dataclass
|
27 |
class ModelConfig:
|
28 |
-
precision_options: List[str] = ("float16", "int8", "bfloat16", "float32")
|
29 |
-
weight_types: List[str] = ("Original", "Delta", "Adapter")
|
30 |
-
model_types: List[str] = ("Transformer", "RNN", "GPT", "Other")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
31 |
|
32 |
CONFIG = {
|
33 |
"dataset": DatasetConfig(),
|
34 |
"ui": UIConfig(),
|
35 |
"model": ModelConfig(),
|
|
|
|
|
36 |
}
|
|
|
1 |
from dataclasses import dataclass
|
2 |
from typing import Dict, List
|
3 |
|
4 |
+
|
5 |
@dataclass
|
6 |
class DatasetConfig:
|
7 |
leaderboard_path: str = "hf://datasets/alibayram/yapay_zeka_turkce_mmlu_liderlik_tablosu/data/train-00000-of-00001.parquet"
|
|
|
16 |
@dataclass
|
17 |
class UIConfig:
|
18 |
title: str = "🏆 Turkish MMLU Leaderboard"
|
19 |
+
description: str = "Explore, evaluate, and compare AI model performance on Turkish language tasks."
|
20 |
+
theme: str = "soft"
|
21 |
css: str = """
|
22 |
+
/* Enhanced Modern UI Styles */
|
23 |
+
.gradio-container {
|
24 |
+
max-width: 1400px !important;
|
25 |
+
margin: 0 auto !important;
|
26 |
+
padding: 20px !important;
|
27 |
+
font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif !important;
|
28 |
+
}
|
29 |
+
|
30 |
+
/* Header Enhancement */
|
31 |
+
.main-header {
|
32 |
+
text-align: center;
|
33 |
+
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
34 |
+
color: white;
|
35 |
+
padding: 40px 20px;
|
36 |
+
border-radius: 20px;
|
37 |
+
margin-bottom: 30px;
|
38 |
+
box-shadow: 0 10px 30px rgba(0,0,0,0.1);
|
39 |
+
}
|
40 |
+
|
41 |
+
/* Button Enhancements */
|
42 |
+
.gr-button {
|
43 |
+
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important;
|
44 |
+
border: none !important;
|
45 |
+
border-radius: 10px !important;
|
46 |
+
padding: 12px 24px !important;
|
47 |
+
font-weight: 600 !important;
|
48 |
+
color: white !important;
|
49 |
+
box-shadow: 0 5px 15px rgba(102, 126, 234, 0.3) !important;
|
50 |
+
transition: all 0.3s ease !important;
|
51 |
+
}
|
52 |
+
|
53 |
+
.gr-button:hover {
|
54 |
+
transform: translateY(-2px) !important;
|
55 |
+
box-shadow: 0 8px 25px rgba(102, 126, 234, 0.4) !important;
|
56 |
+
}
|
57 |
+
|
58 |
+
/* Table Enhancements */
|
59 |
+
.gr-dataframe {
|
60 |
+
border-radius: 15px !important;
|
61 |
+
overflow: hidden !important;
|
62 |
+
box-shadow: 0 5px 20px rgba(0,0,0,0.08) !important;
|
63 |
+
border: 1px solid #f0f0f0 !important;
|
64 |
+
}
|
65 |
+
|
66 |
+
.gr-dataframe th {
|
67 |
+
background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%) !important;
|
68 |
+
color: #495057 !important;
|
69 |
+
font-weight: 600 !important;
|
70 |
+
padding: 15px 12px !important;
|
71 |
+
}
|
72 |
+
|
73 |
+
.gr-dataframe tr:hover {
|
74 |
+
background-color: #f8f9ff !important;
|
75 |
+
}
|
76 |
+
|
77 |
+
/* Card Styles */
|
78 |
+
.card {
|
79 |
+
background: white;
|
80 |
+
border-radius: 15px;
|
81 |
+
padding: 25px;
|
82 |
+
box-shadow: 0 5px 20px rgba(0,0,0,0.08);
|
83 |
+
border: 1px solid #f0f0f0;
|
84 |
+
margin-bottom: 20px;
|
85 |
+
}
|
86 |
+
|
87 |
+
/* Status Messages */
|
88 |
+
.success-message {
|
89 |
+
background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
|
90 |
+
color: white;
|
91 |
+
padding: 15px 20px;
|
92 |
+
border-radius: 10px;
|
93 |
+
margin: 10px 0;
|
94 |
+
font-weight: 500;
|
95 |
+
}
|
96 |
+
|
97 |
+
.error-message {
|
98 |
+
background: linear-gradient(135deg, #dc3545 0%, #fd7e14 100%);
|
99 |
+
color: white;
|
100 |
+
padding: 15px 20px;
|
101 |
+
border-radius: 10px;
|
102 |
+
margin: 10px 0;
|
103 |
+
font-weight: 500;
|
104 |
+
}
|
105 |
+
|
106 |
+
/* Responsive Design */
|
107 |
+
@media (max-width: 768px) {
|
108 |
+
.gradio-container {
|
109 |
+
padding: 10px !important;
|
110 |
+
}
|
111 |
+
|
112 |
+
.main-header h1 {
|
113 |
+
font-size: 2rem !important;
|
114 |
+
}
|
115 |
+
|
116 |
+
.card {
|
117 |
+
padding: 15px;
|
118 |
+
}
|
119 |
+
}
|
120 |
"""
|
121 |
|
122 |
@dataclass
|
123 |
class ModelConfig:
|
124 |
+
precision_options: List[str] = ("float16", "int8", "bfloat16", "float32", "int4")
|
125 |
+
weight_types: List[str] = ("Original", "Delta", "Adapter", "LoRA", "QLoRA")
|
126 |
+
model_types: List[str] = ("Transformer", "RNN", "GPT", "BERT", "T5", "Other")
|
127 |
+
|
128 |
+
@dataclass
|
129 |
+
class AppConfig:
|
130 |
+
"""Enhanced app configuration"""
|
131 |
+
server_name: str = "0.0.0.0"
|
132 |
+
server_port: int = 7860
|
133 |
+
share: bool = False
|
134 |
+
debug: bool = False
|
135 |
+
show_error: bool = True
|
136 |
+
max_threads: int = 40
|
137 |
+
default_concurrency_limit: int = 40
|
138 |
+
enable_queue: bool = True
|
139 |
+
|
140 |
+
@dataclass
|
141 |
+
class PerformanceConfig:
|
142 |
+
"""Performance and caching configuration"""
|
143 |
+
enable_caching: bool = True
|
144 |
+
cache_timeout: int = 3600 # 1 hour
|
145 |
+
max_cache_size: int = 100 # MB
|
146 |
+
enable_compression: bool = True
|
147 |
|
148 |
CONFIG = {
|
149 |
"dataset": DatasetConfig(),
|
150 |
"ui": UIConfig(),
|
151 |
"model": ModelConfig(),
|
152 |
+
"app": AppConfig(),
|
153 |
+
"performance": PerformanceConfig(),
|
154 |
}
|
data_manager.py
CHANGED
@@ -1,13 +1,17 @@
|
|
1 |
-
from typing import Optional, Dict
|
2 |
-
import pandas as pd
|
3 |
-
from functools import lru_cache
|
4 |
-
from huggingface_hub import snapshot_download
|
5 |
import logging
|
6 |
-
import time
|
7 |
import os
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
8 |
import requests
|
|
|
9 |
from requests.adapters import HTTPAdapter
|
10 |
from urllib3.util.retry import Retry
|
|
|
11 |
from config import CONFIG
|
12 |
|
13 |
logging.basicConfig(level=logging.INFO)
|
@@ -41,102 +45,241 @@ class DataManager:
|
|
41 |
self._responses_data: Optional[pd.DataFrame] = None
|
42 |
self._section_results_data: Optional[pd.DataFrame] = None
|
43 |
self._session = create_retry_session()
|
44 |
-
self._max_retries =
|
45 |
-
self._retry_delay =
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
46 |
|
47 |
-
def _load_dataset(self, path: str) -> pd.DataFrame:
|
48 |
-
"""Load dataset with
|
|
|
|
|
|
|
|
|
|
|
|
|
49 |
attempts = 0
|
50 |
last_error = None
|
51 |
|
52 |
while attempts < self._max_retries:
|
53 |
try:
|
54 |
-
logger.info(f"
|
55 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
56 |
except Exception as e:
|
57 |
last_error = e
|
58 |
-
logger.warning(f"Error loading dataset from {path}: {e}. Retrying in {self._retry_delay} seconds...")
|
59 |
attempts += 1
|
60 |
-
|
|
|
|
|
|
|
|
|
|
|
61 |
|
62 |
# If we get here, all attempts failed
|
63 |
logger.error(f"Failed to load dataset after {self._max_retries} attempts: {last_error}")
|
64 |
|
65 |
-
# Return
|
66 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
67 |
return self._create_fallback_leaderboard()
|
68 |
-
elif "responses" in path:
|
69 |
return self._create_fallback_responses()
|
70 |
-
elif "
|
71 |
return self._create_fallback_section_results()
|
72 |
else:
|
73 |
-
return pd.DataFrame()
|
74 |
|
75 |
def _create_fallback_leaderboard(self) -> pd.DataFrame:
|
76 |
-
"""Create a fallback leaderboard dataframe
|
77 |
logger.info("Creating fallback leaderboard data")
|
78 |
return pd.DataFrame({
|
79 |
-
"model": ["
|
80 |
-
"family": ["
|
81 |
-
"quantization_level": ["None"],
|
82 |
-
"score": [
|
83 |
-
"timestamp": [pd.Timestamp.now()]
|
|
|
|
|
84 |
})
|
85 |
|
86 |
def _create_fallback_responses(self) -> pd.DataFrame:
|
87 |
-
"""Create a fallback responses dataframe
|
88 |
logger.info("Creating fallback responses data")
|
89 |
return pd.DataFrame({
|
90 |
-
"bolum": ["
|
91 |
-
"soru": [
|
92 |
-
|
93 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
94 |
})
|
95 |
|
96 |
def _create_fallback_section_results(self) -> pd.DataFrame:
|
97 |
-
"""Create a fallback section results dataframe
|
98 |
logger.info("Creating fallback section results data")
|
99 |
return pd.DataFrame({
|
100 |
-
"section": ["
|
101 |
-
"
|
|
|
|
|
|
|
|
|
102 |
})
|
103 |
|
104 |
def refresh_datasets(self) -> None:
|
105 |
-
"""Refresh all datasets from source."""
|
106 |
-
|
107 |
-
logger.info("
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
122 |
|
123 |
@property
|
124 |
def leaderboard_data(self) -> pd.DataFrame:
|
125 |
-
|
126 |
-
|
127 |
-
|
|
|
|
|
|
|
|
|
|
|
128 |
|
129 |
@property
|
130 |
def responses_data(self) -> pd.DataFrame:
|
131 |
-
|
132 |
-
|
133 |
-
|
|
|
|
|
|
|
|
|
|
|
134 |
|
135 |
@property
|
136 |
def section_results_data(self) -> pd.DataFrame:
|
137 |
-
|
138 |
-
|
139 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
140 |
|
141 |
# Global instance
|
142 |
data_manager = DataManager()
|
|
|
|
|
|
|
|
|
|
|
1 |
import logging
|
|
|
2 |
import os
|
3 |
+
import threading
|
4 |
+
import time
|
5 |
+
from datetime import datetime, timedelta
|
6 |
+
from functools import lru_cache
|
7 |
+
from typing import Dict, Optional
|
8 |
+
|
9 |
+
import pandas as pd
|
10 |
import requests
|
11 |
+
from huggingface_hub import snapshot_download
|
12 |
from requests.adapters import HTTPAdapter
|
13 |
from urllib3.util.retry import Retry
|
14 |
+
|
15 |
from config import CONFIG
|
16 |
|
17 |
logging.basicConfig(level=logging.INFO)
|
|
|
45 |
self._responses_data: Optional[pd.DataFrame] = None
|
46 |
self._section_results_data: Optional[pd.DataFrame] = None
|
47 |
self._session = create_retry_session()
|
48 |
+
self._max_retries = CONFIG["dataset"].max_retries
|
49 |
+
self._retry_delay = CONFIG["dataset"].retry_delay
|
50 |
+
self._cache_timestamps = {}
|
51 |
+
self._data_lock = threading.Lock()
|
52 |
+
self._last_refresh_attempt = None
|
53 |
+
self._refresh_in_progress = False
|
54 |
+
|
55 |
+
def _is_cache_valid(self, data_type: str) -> bool:
|
56 |
+
"""Check if cached data is still valid based on timestamp."""
|
57 |
+
if data_type not in self._cache_timestamps:
|
58 |
+
return False
|
59 |
+
|
60 |
+
cache_time = self._cache_timestamps[data_type]
|
61 |
+
cache_timeout = CONFIG["performance"].cache_timeout
|
62 |
+
return (datetime.now() - cache_time).seconds < cache_timeout
|
63 |
+
|
64 |
+
def _update_cache_timestamp(self, data_type: str):
|
65 |
+
"""Update the cache timestamp for a data type."""
|
66 |
+
self._cache_timestamps[data_type] = datetime.now()
|
67 |
|
68 |
+
def _load_dataset(self, path: str, data_type: str = "unknown") -> pd.DataFrame:
|
69 |
+
"""Load dataset with enhanced error handling and caching."""
|
70 |
+
|
71 |
+
# Check cache validity first
|
72 |
+
if self._is_cache_valid(data_type):
|
73 |
+
logger.info(f"Using cached data for {data_type}")
|
74 |
+
return getattr(self, f"_{data_type}_data", pd.DataFrame())
|
75 |
+
|
76 |
attempts = 0
|
77 |
last_error = None
|
78 |
|
79 |
while attempts < self._max_retries:
|
80 |
try:
|
81 |
+
logger.info(f"Loading dataset from {path} (attempt {attempts+1}/{self._max_retries})")
|
82 |
+
|
83 |
+
# Add timeout and better error handling
|
84 |
+
df = pd.read_parquet(path, engine='pyarrow')
|
85 |
+
|
86 |
+
if df.empty:
|
87 |
+
logger.warning(f"Dataset from {path} is empty")
|
88 |
+
else:
|
89 |
+
logger.info(f"Successfully loaded {len(df)} rows from {path}")
|
90 |
+
self._update_cache_timestamp(data_type)
|
91 |
+
|
92 |
+
return df
|
93 |
+
|
94 |
except Exception as e:
|
95 |
last_error = e
|
|
|
96 |
attempts += 1
|
97 |
+
logger.warning(f"Error loading dataset from {path}: {e}")
|
98 |
+
|
99 |
+
if attempts < self._max_retries:
|
100 |
+
wait_time = self._retry_delay * (2 ** (attempts - 1)) # Exponential backoff
|
101 |
+
logger.info(f"Retrying in {wait_time} seconds...")
|
102 |
+
time.sleep(wait_time)
|
103 |
|
104 |
# If we get here, all attempts failed
|
105 |
logger.error(f"Failed to load dataset after {self._max_retries} attempts: {last_error}")
|
106 |
|
107 |
+
# Return appropriate fallback dataframe
|
108 |
+
return self._create_fallback_data(data_type, path)
|
109 |
+
|
110 |
+
def _create_fallback_data(self, data_type: str, path: str) -> pd.DataFrame:
|
111 |
+
"""Create fallback data based on the data type."""
|
112 |
+
logger.info(f"Creating fallback data for {data_type}")
|
113 |
+
|
114 |
+
if "leaderboard" in path.lower() or data_type == "leaderboard":
|
115 |
return self._create_fallback_leaderboard()
|
116 |
+
elif "responses" in path.lower() or data_type == "responses":
|
117 |
return self._create_fallback_responses()
|
118 |
+
elif "section" in path.lower() or data_type == "section_results":
|
119 |
return self._create_fallback_section_results()
|
120 |
else:
|
121 |
+
return pd.DataFrame({"error": ["Unknown data type"], "message": [f"Failed to load {path}"]})
|
122 |
|
123 |
def _create_fallback_leaderboard(self) -> pd.DataFrame:
|
124 |
+
"""Create a comprehensive fallback leaderboard dataframe."""
|
125 |
logger.info("Creating fallback leaderboard data")
|
126 |
return pd.DataFrame({
|
127 |
+
"model": ["GPT-4-Turbo", "Claude-3-Opus", "Gemini-Pro", "Llama-2-70B", "Mistral-7B"],
|
128 |
+
"family": ["OpenAI", "Anthropic", "Google", "Meta", "Mistral"],
|
129 |
+
"quantization_level": ["None", "None", "None", "float16", "int8"],
|
130 |
+
"score": [85.2, 83.7, 81.4, 78.9, 75.3],
|
131 |
+
"timestamp": [pd.Timestamp.now()] * 5,
|
132 |
+
"parameters": ["1.76T", "Unknown", "Unknown", "70B", "7B"],
|
133 |
+
"license": ["Proprietary", "Proprietary", "Proprietary", "Custom", "Apache 2.0"]
|
134 |
})
|
135 |
|
136 |
def _create_fallback_responses(self) -> pd.DataFrame:
|
137 |
+
"""Create a comprehensive fallback responses dataframe."""
|
138 |
logger.info("Creating fallback responses data")
|
139 |
return pd.DataFrame({
|
140 |
+
"bolum": ["Matematik", "Tarih", "Coğrafya", "Edebiyat", "Fen"],
|
141 |
+
"soru": [
|
142 |
+
"2 + 2 kaçtır?",
|
143 |
+
"Osmanlı İmparatorluğu ne zaman kuruldu?",
|
144 |
+
"Türkiye'nin başkenti neresidir?",
|
145 |
+
"Yunus Emre hangi dönemde yaşamıştır?",
|
146 |
+
"Suyun kimyasal formülü nedir?"
|
147 |
+
],
|
148 |
+
"cevap": ["4", "1299", "Ankara", "13-14. yüzyıl", "H2O"],
|
149 |
+
"GPT-4-Turbo_cevap": ["4", "1299", "Ankara", "13-14. yüzyıl", "H2O"],
|
150 |
+
"Claude-3-Opus_cevap": ["4", "1299 civarı", "Ankara", "13-14. yüzyıl", "H2O"],
|
151 |
+
"Gemini-Pro_cevap": ["4", "1299", "Ankara", "13. ve 14. yüzyıl", "H2O"]
|
152 |
})
|
153 |
|
154 |
def _create_fallback_section_results(self) -> pd.DataFrame:
|
155 |
+
"""Create a comprehensive fallback section results dataframe."""
|
156 |
logger.info("Creating fallback section results data")
|
157 |
return pd.DataFrame({
|
158 |
+
"section": ["Matematik", "Tarih", "Coğrafya", "Edebiyat", "Fen", "Felsefe", "Sosyoloji"],
|
159 |
+
"GPT-4-Turbo": [88.5, 85.2, 82.7, 89.1, 86.3, 83.8, 81.4],
|
160 |
+
"Claude-3-Opus": [86.2, 87.1, 80.5, 88.7, 84.9, 85.2, 82.1],
|
161 |
+
"Gemini-Pro": [84.7, 83.6, 81.2, 86.4, 85.1, 82.3, 80.8],
|
162 |
+
"Llama-2-70B": [82.1, 80.4, 78.9, 83.2, 81.7, 79.6, 77.3],
|
163 |
+
"Mistral-7B": [79.3, 77.8, 76.2, 80.1, 78.5, 76.9, 74.6]
|
164 |
})
|
165 |
|
166 |
def refresh_datasets(self) -> None:
|
167 |
+
"""Refresh all datasets from source with thread safety."""
|
168 |
+
if self._refresh_in_progress:
|
169 |
+
logger.info("Refresh already in progress, skipping...")
|
170 |
+
return
|
171 |
+
|
172 |
+
with self._data_lock:
|
173 |
+
try:
|
174 |
+
self._refresh_in_progress = True
|
175 |
+
self._last_refresh_attempt = datetime.now()
|
176 |
+
|
177 |
+
logger.info("Starting comprehensive dataset refresh...")
|
178 |
+
|
179 |
+
# Create cache directory if it doesn't exist
|
180 |
+
os.makedirs(CONFIG["dataset"].cache_dir, exist_ok=True)
|
181 |
+
|
182 |
+
# Download latest data
|
183 |
+
snapshot_download(
|
184 |
+
repo_id="alibayram",
|
185 |
+
repo_type="dataset",
|
186 |
+
local_dir=CONFIG["dataset"].cache_dir,
|
187 |
+
max_retries=CONFIG["dataset"].max_retries,
|
188 |
+
retry_delay_seconds=CONFIG["dataset"].retry_delay
|
189 |
+
)
|
190 |
+
|
191 |
+
# Clear cached data to force reload
|
192 |
+
self._leaderboard_data = None
|
193 |
+
self._responses_data = None
|
194 |
+
self._section_results_data = None
|
195 |
+
self._cache_timestamps.clear()
|
196 |
+
|
197 |
+
logger.info("Datasets refreshed successfully")
|
198 |
+
|
199 |
+
except Exception as e:
|
200 |
+
logger.error(f"Error refreshing datasets: {e}")
|
201 |
+
# Don't clear cache on error, keep existing data
|
202 |
+
|
203 |
+
finally:
|
204 |
+
self._refresh_in_progress = False
|
205 |
+
|
206 |
+
def get_refresh_status(self) -> Dict[str, any]:
|
207 |
+
"""Get the status of the last refresh attempt."""
|
208 |
+
return {
|
209 |
+
"last_attempt": self._last_refresh_attempt.isoformat() if self._last_refresh_attempt else None,
|
210 |
+
"in_progress": self._refresh_in_progress,
|
211 |
+
"cache_timestamps": {k: v.isoformat() for k, v in self._cache_timestamps.items()}
|
212 |
+
}
|
213 |
|
214 |
@property
|
215 |
def leaderboard_data(self) -> pd.DataFrame:
|
216 |
+
"""Get leaderboard data with thread safety and caching."""
|
217 |
+
with self._data_lock:
|
218 |
+
if self._leaderboard_data is None or not self._is_cache_valid("leaderboard"):
|
219 |
+
self._leaderboard_data = self._load_dataset(
|
220 |
+
CONFIG["dataset"].leaderboard_path,
|
221 |
+
"leaderboard"
|
222 |
+
)
|
223 |
+
return self._leaderboard_data.copy() if self._leaderboard_data is not None else pd.DataFrame()
|
224 |
|
225 |
@property
|
226 |
def responses_data(self) -> pd.DataFrame:
|
227 |
+
"""Get responses data with thread safety and caching."""
|
228 |
+
with self._data_lock:
|
229 |
+
if self._responses_data is None or not self._is_cache_valid("responses"):
|
230 |
+
self._responses_data = self._load_dataset(
|
231 |
+
CONFIG["dataset"].responses_path,
|
232 |
+
"responses"
|
233 |
+
)
|
234 |
+
return self._responses_data.copy() if self._responses_data is not None else pd.DataFrame()
|
235 |
|
236 |
@property
|
237 |
def section_results_data(self) -> pd.DataFrame:
|
238 |
+
"""Get section results data with thread safety and caching."""
|
239 |
+
with self._data_lock:
|
240 |
+
if self._section_results_data is None or not self._is_cache_valid("section_results"):
|
241 |
+
self._section_results_data = self._load_dataset(
|
242 |
+
CONFIG["dataset"].section_results_path,
|
243 |
+
"section_results"
|
244 |
+
)
|
245 |
+
return self._section_results_data.copy() if self._section_results_data is not None else pd.DataFrame()
|
246 |
+
|
247 |
+
def get_data_summary(self) -> Dict[str, any]:
|
248 |
+
"""Get a comprehensive summary of all loaded data."""
|
249 |
+
try:
|
250 |
+
summary = {
|
251 |
+
"leaderboard": {
|
252 |
+
"rows": len(self.leaderboard_data),
|
253 |
+
"columns": list(self.leaderboard_data.columns) if not self.leaderboard_data.empty else [],
|
254 |
+
"families": self.leaderboard_data["family"].nunique() if "family" in self.leaderboard_data.columns else 0,
|
255 |
+
"models": self.leaderboard_data["model"].nunique() if "model" in self.leaderboard_data.columns else 0
|
256 |
+
},
|
257 |
+
"responses": {
|
258 |
+
"rows": len(self.responses_data),
|
259 |
+
"columns": list(self.responses_data.columns) if not self.responses_data.empty else [],
|
260 |
+
"sections": self.responses_data["bolum"].nunique() if "bolum" in self.responses_data.columns else 0
|
261 |
+
},
|
262 |
+
"section_results": {
|
263 |
+
"rows": len(self.section_results_data),
|
264 |
+
"columns": list(self.section_results_data.columns) if not self.section_results_data.empty else [],
|
265 |
+
"sections": len([col for col in self.section_results_data.columns if col != "section"]) if not self.section_results_data.empty else 0
|
266 |
+
},
|
267 |
+
"cache_status": self.get_refresh_status(),
|
268 |
+
"last_updated": datetime.now().isoformat()
|
269 |
+
}
|
270 |
+
return summary
|
271 |
+
except Exception as e:
|
272 |
+
logger.error(f"Error generating data summary: {e}")
|
273 |
+
return {"error": str(e)}
|
274 |
+
|
275 |
+
def clear_cache(self):
|
276 |
+
"""Clear all cached data and force reload on next access."""
|
277 |
+
with self._data_lock:
|
278 |
+
self._leaderboard_data = None
|
279 |
+
self._responses_data = None
|
280 |
+
self._section_results_data = None
|
281 |
+
self._cache_timestamps.clear()
|
282 |
+
logger.info("All cached data cleared")
|
283 |
|
284 |
# Global instance
|
285 |
data_manager = DataManager()
|
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,7 @@
|
|
1 |
-
|
2 |
-
|
3 |
-
|
4 |
-
|
5 |
-
gradio[oauth]
|
6 |
-
gradio_leaderboard==0.0.13
|
7 |
-
gradio_client
|
8 |
huggingface-hub>=0.18.0
|
9 |
-
|
10 |
-
|
11 |
-
pandas
|
12 |
-
python-dateutil
|
13 |
-
tqdm
|
14 |
-
transformers
|
15 |
-
tokenizers>=0.15.0
|
16 |
-
sentencepiece
|
|
|
1 |
+
gradio>=4.0.0
|
2 |
+
pandas>=1.5.0
|
3 |
+
plotly>=5.0.0
|
4 |
+
APScheduler>=3.9.0
|
|
|
|
|
|
|
5 |
huggingface-hub>=0.18.0
|
6 |
+
requests>=2.28.0
|
7 |
+
urllib3>=1.26.0
|
|
|
|
|
|
|
|
|
|
|
|
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 |
-
#leaderboard-table td:nth-child(2),
|
43 |
-
#leaderboard-table th:nth-child(2) {
|
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 os.path.isfile(e) and 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 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
utils.py
CHANGED
@@ -1,16 +1,22 @@
|
|
1 |
-
from typing import Optional, Dict
|
2 |
-
import pandas as pd
|
3 |
-
import matplotlib.pyplot as plt
|
4 |
import logging
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
5 |
from data_manager import data_manager
|
6 |
|
7 |
logger = logging.getLogger(__name__)
|
8 |
|
|
|
9 |
def filter_leaderboard(
|
10 |
family: Optional[str] = None,
|
11 |
quantization_level: Optional[str] = None
|
12 |
) -> pd.DataFrame:
|
13 |
-
"""Filter leaderboard data based on criteria."""
|
14 |
try:
|
15 |
df = data_manager.leaderboard_data.copy()
|
16 |
|
@@ -18,79 +24,375 @@ def filter_leaderboard(
|
|
18 |
logger.warning("Leaderboard data is empty, returning empty DataFrame")
|
19 |
return pd.DataFrame()
|
20 |
|
21 |
-
|
|
|
22 |
df = df[df["family"] == family]
|
23 |
-
if quantization_level:
|
24 |
df = df[df["quantization_level"] == quantization_level]
|
25 |
|
26 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
27 |
except Exception as e:
|
28 |
logger.error(f"Error filtering leaderboard: {e}")
|
29 |
return pd.DataFrame()
|
30 |
|
31 |
-
def
|
32 |
-
"""
|
33 |
try:
|
34 |
-
|
35 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
36 |
|
37 |
df = data_manager.responses_data
|
38 |
|
39 |
if df.empty:
|
40 |
logger.warning("Responses data is empty, returning empty DataFrame")
|
41 |
-
return pd.DataFrame()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
42 |
|
43 |
# Check if model column exists
|
44 |
model_column = f"{model}_cevap"
|
45 |
if model_column not in df.columns:
|
|
|
46 |
logger.warning(f"Model column '{model_column}' not found in responses data")
|
47 |
-
return pd.DataFrame({
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
48 |
|
49 |
-
|
50 |
-
|
51 |
-
|
|
|
52 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
53 |
selected_columns = ["bolum", "soru", "cevap", model_column]
|
54 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
55 |
except Exception as e:
|
56 |
logger.error(f"Error searching responses: {e}")
|
57 |
-
return pd.DataFrame({
|
|
|
|
|
|
|
|
|
|
|
58 |
|
59 |
-
def
|
60 |
-
"""
|
61 |
try:
|
62 |
df = data_manager.section_results_data
|
63 |
|
64 |
if df.empty:
|
65 |
-
|
66 |
-
fig
|
67 |
-
|
68 |
-
|
69 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
70 |
return fig
|
71 |
|
72 |
-
|
73 |
-
|
|
|
74 |
|
75 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
76 |
|
77 |
-
#
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
|
|
|
|
|
|
83 |
|
84 |
-
|
85 |
-
|
86 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
87 |
|
88 |
return fig
|
|
|
89 |
except Exception as e:
|
90 |
-
logger.error(f"Error
|
91 |
-
fig
|
92 |
-
|
93 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
94 |
return fig
|
95 |
|
96 |
def validate_model_submission(
|
@@ -100,18 +402,121 @@ def validate_model_submission(
|
|
100 |
precision: str,
|
101 |
weight_type: str,
|
102 |
model_type: str
|
103 |
-
) ->
|
104 |
-
"""
|
105 |
try:
|
106 |
-
|
107 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
108 |
|
109 |
-
# Check if
|
110 |
if not data_manager.leaderboard_data.empty:
|
111 |
-
|
112 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
113 |
|
114 |
-
return True, "Validation successful"
|
115 |
except Exception as e:
|
116 |
logger.error(f"Error validating model submission: {e}")
|
117 |
-
return False, f"Validation error: {str(e)}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import logging
|
2 |
+
import time
|
3 |
+
from functools import lru_cache
|
4 |
+
from typing import Dict, List, Optional, Tuple
|
5 |
+
|
6 |
+
import pandas as pd
|
7 |
+
import plotly.express as px
|
8 |
+
import plotly.graph_objects as go
|
9 |
+
|
10 |
from data_manager import data_manager
|
11 |
|
12 |
logger = logging.getLogger(__name__)
|
13 |
|
14 |
+
@lru_cache(maxsize=128)
|
15 |
def filter_leaderboard(
|
16 |
family: Optional[str] = None,
|
17 |
quantization_level: Optional[str] = None
|
18 |
) -> pd.DataFrame:
|
19 |
+
"""Filter leaderboard data based on criteria with caching."""
|
20 |
try:
|
21 |
df = data_manager.leaderboard_data.copy()
|
22 |
|
|
|
24 |
logger.warning("Leaderboard data is empty, returning empty DataFrame")
|
25 |
return pd.DataFrame()
|
26 |
|
27 |
+
# Apply filters
|
28 |
+
if family and family != "All":
|
29 |
df = df[df["family"] == family]
|
30 |
+
if quantization_level and quantization_level != "All":
|
31 |
df = df[df["quantization_level"] == quantization_level]
|
32 |
|
33 |
+
# Sort by score if available
|
34 |
+
if "score" in df.columns:
|
35 |
+
df = df.sort_values("score", ascending=False)
|
36 |
+
|
37 |
+
# Add ranking
|
38 |
+
if not df.empty and "score" in df.columns:
|
39 |
+
df = df.reset_index(drop=True)
|
40 |
+
df.insert(0, "Rank", range(1, len(df) + 1))
|
41 |
+
|
42 |
+
return df
|
43 |
except Exception as e:
|
44 |
logger.error(f"Error filtering leaderboard: {e}")
|
45 |
return pd.DataFrame()
|
46 |
|
47 |
+
def get_all_responses(model: str = None, page: int = 1, page_size: int = 50) -> pd.DataFrame:
|
48 |
+
"""Get all model responses for browsing without search query with pagination."""
|
49 |
try:
|
50 |
+
df = data_manager.responses_data
|
51 |
+
|
52 |
+
if df.empty:
|
53 |
+
logger.warning("Responses data is empty, returning empty DataFrame")
|
54 |
+
return pd.DataFrame({"ℹ️ Info": ["No response data available. Please check data loading."]})
|
55 |
+
|
56 |
+
# Debug: Show available columns
|
57 |
+
logger.info(f"Available columns in responses data: {list(df.columns)}")
|
58 |
+
|
59 |
+
# Check if required columns exist
|
60 |
+
required_columns = ["bolum", "soru", "cevap"]
|
61 |
+
missing_columns = [col for col in required_columns if col not in df.columns]
|
62 |
+
if missing_columns:
|
63 |
+
return pd.DataFrame({
|
64 |
+
"❌ Error": [f"Missing required columns: {', '.join(missing_columns)}"],
|
65 |
+
"Available Columns": [", ".join(df.columns.tolist())]
|
66 |
+
})
|
67 |
+
|
68 |
+
# Get all available models
|
69 |
+
available_models = [col.replace("_cevap", "") for col in df.columns if col.endswith("_cevap")]
|
70 |
+
|
71 |
+
if not available_models:
|
72 |
+
return pd.DataFrame({
|
73 |
+
"ℹ️ Info": ["No model response columns found."],
|
74 |
+
"Available Columns": [", ".join(df.columns.tolist())]
|
75 |
+
})
|
76 |
+
|
77 |
+
# Calculate pagination
|
78 |
+
total_rows = len(df)
|
79 |
+
start_idx = (page - 1) * page_size
|
80 |
+
end_idx = start_idx + page_size
|
81 |
+
|
82 |
+
# Validate page number
|
83 |
+
if start_idx >= total_rows:
|
84 |
+
return pd.DataFrame({
|
85 |
+
"ℹ️ Info": [f"Page {page} is out of range. Total pages: {(total_rows + page_size - 1) // page_size}"]
|
86 |
+
})
|
87 |
+
|
88 |
+
# Get the data slice for current page
|
89 |
+
df_page = df.iloc[start_idx:end_idx].copy()
|
90 |
+
|
91 |
+
# If no specific model selected, show responses for all models
|
92 |
+
if not model or model.strip() == "":
|
93 |
+
# Select relevant columns
|
94 |
+
display_columns = ["bolum", "soru", "cevap"] + [f"{m}_cevap" for m in available_models if f"{m}_cevap" in df_page.columns]
|
95 |
+
result_df = df_page[display_columns]
|
96 |
+
|
97 |
+
# Rename columns for better display
|
98 |
+
column_mapping = {
|
99 |
+
"bolum": "📚 Section",
|
100 |
+
"soru": "❓ Question",
|
101 |
+
"cevap": "✅ Correct Answer"
|
102 |
+
}
|
103 |
+
|
104 |
+
for model_name in available_models:
|
105 |
+
model_col = f"{model_name}_cevap"
|
106 |
+
if model_col in result_df.columns:
|
107 |
+
column_mapping[model_col] = f"🤖 {model_name}"
|
108 |
+
|
109 |
+
result_df = result_df.rename(columns=column_mapping)
|
110 |
+
|
111 |
+
else:
|
112 |
+
# Show responses for specific model
|
113 |
+
model_column = f"{model}_cevap"
|
114 |
+
if model_column not in df.columns:
|
115 |
+
return pd.DataFrame({
|
116 |
+
"❌ Error": [f"Model '{model}' responses not found."],
|
117 |
+
"🤖 Available Models": [", ".join(available_models[:10]) + ("..." if len(available_models) > 10 else "")],
|
118 |
+
"💡 Tip": ["Please select a model from the dropdown that has response data."]
|
119 |
+
})
|
120 |
+
|
121 |
+
# Select and prepare columns for display
|
122 |
+
selected_columns = ["bolum", "soru", "cevap", model_column]
|
123 |
+
result_df = df_page[selected_columns]
|
124 |
+
|
125 |
+
# Rename columns for better display
|
126 |
+
result_df = result_df.rename(columns={
|
127 |
+
"bolum": "📚 Section",
|
128 |
+
"soru": "❓ Question",
|
129 |
+
"cevap": "✅ Correct Answer",
|
130 |
+
model_column: f"🤖 {model} Response"
|
131 |
+
})
|
132 |
+
|
133 |
+
# Handle missing values
|
134 |
+
result_df = result_df.fillna("N/A")
|
135 |
+
|
136 |
+
# Add global question numbers (not just page numbers)
|
137 |
+
global_question_numbers = range(start_idx + 1, start_idx + len(result_df) + 1)
|
138 |
+
result_df.insert(0, "📝 Question #", global_question_numbers)
|
139 |
+
|
140 |
+
return result_df
|
141 |
+
|
142 |
+
except Exception as e:
|
143 |
+
logger.error(f"Error getting all responses: {e}")
|
144 |
+
return pd.DataFrame({
|
145 |
+
"❌ Error": [f"Error loading responses: {str(e)}"],
|
146 |
+
"🔧 Debug Info": [f"Model: '{model}', Page: {page}"]
|
147 |
+
})
|
148 |
+
|
149 |
+
def get_pagination_info(page: int = 1, page_size: int = 50) -> dict:
|
150 |
+
"""Get pagination information for the responses data."""
|
151 |
+
try:
|
152 |
+
df = data_manager.responses_data
|
153 |
+
total_rows = len(df)
|
154 |
+
total_pages = (total_rows + page_size - 1) // page_size
|
155 |
+
|
156 |
+
start_idx = (page - 1) * page_size + 1
|
157 |
+
end_idx = min(page * page_size, total_rows)
|
158 |
+
|
159 |
+
return {
|
160 |
+
"current_page": page,
|
161 |
+
"total_pages": total_pages,
|
162 |
+
"total_rows": total_rows,
|
163 |
+
"page_size": page_size,
|
164 |
+
"start_idx": start_idx,
|
165 |
+
"end_idx": end_idx,
|
166 |
+
"has_prev": page > 1,
|
167 |
+
"has_next": page < total_pages
|
168 |
+
}
|
169 |
+
except Exception as e:
|
170 |
+
logger.error(f"Error getting pagination info: {e}")
|
171 |
+
return {
|
172 |
+
"current_page": 1,
|
173 |
+
"total_pages": 1,
|
174 |
+
"total_rows": 0,
|
175 |
+
"page_size": page_size,
|
176 |
+
"start_idx": 1,
|
177 |
+
"end_idx": 0,
|
178 |
+
"has_prev": False,
|
179 |
+
"has_next": False
|
180 |
+
}
|
181 |
+
|
182 |
+
def search_responses(query: str, model: str, page: int = 1, page_size: int = 50) -> pd.DataFrame:
|
183 |
+
"""Search model responses based on query with enhanced functionality."""
|
184 |
+
try:
|
185 |
+
# If no query provided, show all responses
|
186 |
+
if not query or not query.strip():
|
187 |
+
return get_all_responses(model, page, page_size)
|
188 |
+
|
189 |
+
if not model or not model.strip():
|
190 |
+
return pd.DataFrame({"ℹ️ Info": ["Please select a model from the dropdown."]})
|
191 |
+
|
192 |
+
query = query.strip()
|
193 |
+
model = model.strip()
|
194 |
|
195 |
df = data_manager.responses_data
|
196 |
|
197 |
if df.empty:
|
198 |
logger.warning("Responses data is empty, returning empty DataFrame")
|
199 |
+
return pd.DataFrame({"ℹ️ Info": ["No response data available. Please check data loading."]})
|
200 |
+
|
201 |
+
# Debug: Show available columns
|
202 |
+
logger.info(f"Available columns in responses data: {list(df.columns)}")
|
203 |
+
|
204 |
+
# Check if required columns exist
|
205 |
+
required_columns = ["bolum", "soru", "cevap"]
|
206 |
+
missing_columns = [col for col in required_columns if col not in df.columns]
|
207 |
+
if missing_columns:
|
208 |
+
return pd.DataFrame({
|
209 |
+
"❌ Error": [f"Missing required columns: {', '.join(missing_columns)}"],
|
210 |
+
"Available Columns": [", ".join(df.columns.tolist())]
|
211 |
+
})
|
212 |
|
213 |
# Check if model column exists
|
214 |
model_column = f"{model}_cevap"
|
215 |
if model_column not in df.columns:
|
216 |
+
available_models = [col.replace("_cevap", "") for col in df.columns if col.endswith("_cevap")]
|
217 |
logger.warning(f"Model column '{model_column}' not found in responses data")
|
218 |
+
return pd.DataFrame({
|
219 |
+
"❌ Error": [f"Model '{model}' responses not found."],
|
220 |
+
"🤖 Available Models": [", ".join(available_models[:10]) + ("..." if len(available_models) > 10 else "")],
|
221 |
+
"💡 Tip": ["Please select a model from the dropdown that has response data."]
|
222 |
+
})
|
223 |
+
|
224 |
+
# Enhanced search - search in multiple columns with better error handling
|
225 |
+
try:
|
226 |
+
search_mask = pd.Series([False] * len(df))
|
227 |
+
|
228 |
+
# Search in each column separately to handle potential issues
|
229 |
+
if "bolum" in df.columns:
|
230 |
+
search_mask |= df["bolum"].astype(str).str.contains(query, case=False, na=False)
|
231 |
+
|
232 |
+
if "soru" in df.columns:
|
233 |
+
search_mask |= df["soru"].astype(str).str.contains(query, case=False, na=False)
|
234 |
+
|
235 |
+
if "cevap" in df.columns:
|
236 |
+
search_mask |= df["cevap"].astype(str).str.contains(query, case=False, na=False)
|
237 |
+
|
238 |
+
if model_column in df.columns:
|
239 |
+
search_mask |= df[model_column].astype(str).str.contains(query, case=False, na=False)
|
240 |
+
|
241 |
+
except Exception as search_error:
|
242 |
+
logger.error(f"Error in search operation: {search_error}")
|
243 |
+
return pd.DataFrame({"❌ Error": [f"Search operation failed: {str(search_error)}"]})
|
244 |
+
|
245 |
+
filtered = df[search_mask]
|
246 |
+
|
247 |
+
if filtered.empty:
|
248 |
+
return pd.DataFrame({
|
249 |
+
"ℹ️ Info": [f"No results found for '{query}' in model '{model}' responses."],
|
250 |
+
"💡 Suggestion": ["Try different search terms or check if the model has response data."]
|
251 |
+
})
|
252 |
|
253 |
+
# Apply pagination to search results
|
254 |
+
total_results = len(filtered)
|
255 |
+
start_idx = (page - 1) * page_size
|
256 |
+
end_idx = start_idx + page_size
|
257 |
|
258 |
+
# Validate page number for search results
|
259 |
+
if start_idx >= total_results:
|
260 |
+
total_pages = (total_results + page_size - 1) // page_size
|
261 |
+
return pd.DataFrame({
|
262 |
+
"ℹ️ Info": [f"Search page {page} is out of range. Total search pages: {total_pages}"],
|
263 |
+
"🔍 Search Results": [f"Found {total_results} matches for '{query}'"]
|
264 |
+
})
|
265 |
+
|
266 |
+
# Get the search results slice for current page
|
267 |
+
filtered_page = filtered.iloc[start_idx:end_idx].copy()
|
268 |
+
|
269 |
+
# Select and prepare columns for display
|
270 |
selected_columns = ["bolum", "soru", "cevap", model_column]
|
271 |
+
result = filtered_page[selected_columns].copy()
|
272 |
+
|
273 |
+
# Handle missing values
|
274 |
+
result = result.fillna("N/A")
|
275 |
+
|
276 |
+
# Rename columns for better display
|
277 |
+
result = result.rename(columns={
|
278 |
+
"bolum": "📚 Section",
|
279 |
+
"soru": "❓ Question",
|
280 |
+
"cevap": "✅ Correct Answer",
|
281 |
+
model_column: f"🤖 {model} Response"
|
282 |
+
})
|
283 |
+
|
284 |
+
# Add global match numbers (not just page numbers)
|
285 |
+
global_match_numbers = range(start_idx + 1, start_idx + len(result) + 1)
|
286 |
+
result.insert(0, "🔍 Match #", global_match_numbers)
|
287 |
+
|
288 |
+
logger.info(f"Showing search results {start_idx + 1}-{start_idx + len(result)} out of {total_results} total matches")
|
289 |
+
|
290 |
+
return result
|
291 |
+
|
292 |
except Exception as e:
|
293 |
logger.error(f"Error searching responses: {e}")
|
294 |
+
return pd.DataFrame({
|
295 |
+
"❌ Error": [f"Search error: {str(e)}"],
|
296 |
+
"🔧 Debug Info": [f"Query: '{query}', Model: '{model}'"]
|
297 |
+
})
|
298 |
+
|
299 |
+
|
300 |
|
301 |
+
def create_plotly_section_results() -> go.Figure:
|
302 |
+
"""Create an interactive Plotly chart for section results."""
|
303 |
try:
|
304 |
df = data_manager.section_results_data
|
305 |
|
306 |
if df.empty:
|
307 |
+
fig = go.Figure()
|
308 |
+
fig.add_annotation(
|
309 |
+
text="📊 No data available",
|
310 |
+
xref="paper", yref="paper",
|
311 |
+
x=0.5, y=0.5, xanchor='center', yanchor='middle',
|
312 |
+
showarrow=False,
|
313 |
+
font=dict(size=18, color="gray")
|
314 |
+
)
|
315 |
+
fig.update_layout(
|
316 |
+
title="Section-Wise Performance",
|
317 |
+
height=500,
|
318 |
+
plot_bgcolor='white'
|
319 |
+
)
|
320 |
return fig
|
321 |
|
322 |
+
# Calculate average scores
|
323 |
+
numeric_cols = df.select_dtypes(include=['number']).columns
|
324 |
+
avg_scores = df[numeric_cols].mean()
|
325 |
|
326 |
+
# Create interactive bar chart
|
327 |
+
fig = go.Figure(data=[
|
328 |
+
go.Bar(
|
329 |
+
x=avg_scores.index,
|
330 |
+
y=avg_scores.values,
|
331 |
+
marker=dict(
|
332 |
+
color=avg_scores.values,
|
333 |
+
colorscale='Viridis',
|
334 |
+
showscale=True,
|
335 |
+
colorbar=dict(title="Score (%)", titleside="right")
|
336 |
+
),
|
337 |
+
text=[f'{v:.1f}%' for v in avg_scores.values],
|
338 |
+
textposition='auto',
|
339 |
+
textfont=dict(size=12, color='white'),
|
340 |
+
hovertemplate='<b>%{x}</b><br>Score: %{y:.1f}%<br><extra></extra>',
|
341 |
+
name="Section Scores"
|
342 |
+
)
|
343 |
+
])
|
344 |
|
345 |
+
# Add average line
|
346 |
+
mean_score = avg_scores.mean()
|
347 |
+
fig.add_hline(
|
348 |
+
y=mean_score,
|
349 |
+
line_dash="dash",
|
350 |
+
line_color="red",
|
351 |
+
annotation_text=f"Average: {mean_score:.1f}%",
|
352 |
+
annotation_position="top right"
|
353 |
+
)
|
354 |
|
355 |
+
fig.update_layout(
|
356 |
+
title=dict(
|
357 |
+
text="📊 Average Section-Wise Performance",
|
358 |
+
x=0.5,
|
359 |
+
font=dict(size=24, color='#2c3e50')
|
360 |
+
),
|
361 |
+
xaxis=dict(
|
362 |
+
title="Sections",
|
363 |
+
titlefont=dict(size=16),
|
364 |
+
tickangle=45,
|
365 |
+
gridcolor='#f0f0f0'
|
366 |
+
),
|
367 |
+
yaxis=dict(
|
368 |
+
title="Accuracy (%)",
|
369 |
+
titlefont=dict(size=16),
|
370 |
+
gridcolor='#f0f0f0'
|
371 |
+
),
|
372 |
+
plot_bgcolor='white',
|
373 |
+
paper_bgcolor='white',
|
374 |
+
height=600,
|
375 |
+
margin=dict(t=100, b=120, l=80, r=80),
|
376 |
+
showlegend=False
|
377 |
+
)
|
378 |
|
379 |
return fig
|
380 |
+
|
381 |
except Exception as e:
|
382 |
+
logger.error(f"Error creating Plotly section results: {e}")
|
383 |
+
fig = go.Figure()
|
384 |
+
fig.add_annotation(
|
385 |
+
text=f"❌ Error generating plot: {str(e)}",
|
386 |
+
xref="paper", yref="paper",
|
387 |
+
x=0.5, y=0.5, xanchor='center', yanchor='middle',
|
388 |
+
showarrow=False,
|
389 |
+
font=dict(size=14, color="red")
|
390 |
+
)
|
391 |
+
fig.update_layout(
|
392 |
+
title="Section-Wise Performance",
|
393 |
+
height=500,
|
394 |
+
plot_bgcolor='white'
|
395 |
+
)
|
396 |
return fig
|
397 |
|
398 |
def validate_model_submission(
|
|
|
402 |
precision: str,
|
403 |
weight_type: str,
|
404 |
model_type: str
|
405 |
+
) -> Tuple[bool, str]:
|
406 |
+
"""Enhanced model submission validation with detailed checks."""
|
407 |
try:
|
408 |
+
# Basic required field validation
|
409 |
+
if not model_name or not model_name.strip():
|
410 |
+
return False, "Model name is required and cannot be empty."
|
411 |
+
|
412 |
+
if not base_model or not base_model.strip():
|
413 |
+
return False, "Base model is required and cannot be empty."
|
414 |
+
|
415 |
+
# Model name validation
|
416 |
+
model_name = model_name.strip()
|
417 |
+
if len(model_name) < 3:
|
418 |
+
return False, "Model name must be at least 3 characters long."
|
419 |
+
|
420 |
+
if len(model_name) > 100:
|
421 |
+
return False, "Model name must be less than 100 characters."
|
422 |
+
|
423 |
+
# Check for invalid characters
|
424 |
+
invalid_chars = ['<', '>', ':', '"', '|', '?', '*', '\\', '/']
|
425 |
+
if any(char in model_name for char in invalid_chars):
|
426 |
+
return False, f"Model name contains invalid characters: {', '.join(invalid_chars)}"
|
427 |
|
428 |
+
# Check if model already exists
|
429 |
if not data_manager.leaderboard_data.empty:
|
430 |
+
existing_models = data_manager.leaderboard_data["model"].values
|
431 |
+
if model_name in existing_models:
|
432 |
+
return False, f"Model name '{model_name}' already exists. Please choose a unique name."
|
433 |
+
|
434 |
+
# Base model validation
|
435 |
+
base_model = base_model.strip()
|
436 |
+
if len(base_model) < 3:
|
437 |
+
return False, "Base model name must be at least 3 characters long."
|
438 |
+
|
439 |
+
# Revision validation
|
440 |
+
if revision and len(revision.strip()) == 0:
|
441 |
+
return False, "Revision cannot be empty if provided."
|
442 |
+
|
443 |
+
# Validate precision, weight_type, and model_type are from allowed options
|
444 |
+
from config import CONFIG
|
445 |
+
|
446 |
+
if precision not in CONFIG["model"].precision_options:
|
447 |
+
return False, f"Invalid precision. Must be one of: {', '.join(CONFIG['model'].precision_options)}"
|
448 |
+
|
449 |
+
if weight_type not in CONFIG["model"].weight_types:
|
450 |
+
return False, f"Invalid weight type. Must be one of: {', '.join(CONFIG['model'].weight_types)}"
|
451 |
+
|
452 |
+
if model_type not in CONFIG["model"].model_types:
|
453 |
+
return False, f"Invalid model type. Must be one of: {', '.join(CONFIG['model'].model_types)}"
|
454 |
+
|
455 |
+
return True, "✅ All validation checks passed! Your model submission looks good."
|
456 |
|
|
|
457 |
except Exception as e:
|
458 |
logger.error(f"Error validating model submission: {e}")
|
459 |
+
return False, f"Validation error: {str(e)}"
|
460 |
+
|
461 |
+
def get_leaderboard_stats() -> Dict[str, any]:
|
462 |
+
"""Get comprehensive statistics about the leaderboard."""
|
463 |
+
try:
|
464 |
+
df = data_manager.leaderboard_data
|
465 |
+
|
466 |
+
if df.empty:
|
467 |
+
return {
|
468 |
+
"total_models": 0,
|
469 |
+
"total_families": 0,
|
470 |
+
"avg_score": 0,
|
471 |
+
"top_score": 0,
|
472 |
+
"last_updated": "No data"
|
473 |
+
}
|
474 |
+
|
475 |
+
stats = {
|
476 |
+
"total_models": len(df),
|
477 |
+
"total_families": df["family"].nunique() if "family" in df.columns else 0,
|
478 |
+
"avg_score": df["score"].mean() if "score" in df.columns else 0,
|
479 |
+
"top_score": df["score"].max() if "score" in df.columns else 0,
|
480 |
+
"last_updated": time.strftime("%Y-%m-%d %H:%M:%S")
|
481 |
+
}
|
482 |
+
|
483 |
+
return stats
|
484 |
+
|
485 |
+
except Exception as e:
|
486 |
+
logger.error(f"Error getting leaderboard stats: {e}")
|
487 |
+
return {
|
488 |
+
"total_models": 0,
|
489 |
+
"total_families": 0,
|
490 |
+
"avg_score": 0,
|
491 |
+
"top_score": 0,
|
492 |
+
"last_updated": "Error"
|
493 |
+
}
|
494 |
+
|
495 |
+
def format_dataframe_for_display(df: pd.DataFrame, max_rows: int = 100) -> pd.DataFrame:
|
496 |
+
"""Format DataFrame for better display in Gradio."""
|
497 |
+
try:
|
498 |
+
if df.empty:
|
499 |
+
return df
|
500 |
+
|
501 |
+
# Limit rows for performance
|
502 |
+
if len(df) > max_rows:
|
503 |
+
df = df.head(max_rows)
|
504 |
+
|
505 |
+
# Round numeric columns
|
506 |
+
numeric_columns = df.select_dtypes(include=['float64', 'float32']).columns
|
507 |
+
for col in numeric_columns:
|
508 |
+
df[col] = df[col].round(2)
|
509 |
+
|
510 |
+
# Truncate long text fields
|
511 |
+
text_columns = df.select_dtypes(include=['object']).columns
|
512 |
+
for col in text_columns:
|
513 |
+
if col in df.columns:
|
514 |
+
df[col] = df[col].astype(str).apply(
|
515 |
+
lambda x: x[:100] + "..." if len(str(x)) > 100 else x
|
516 |
+
)
|
517 |
+
|
518 |
+
return df
|
519 |
+
|
520 |
+
except Exception as e:
|
521 |
+
logger.error(f"Error formatting DataFrame: {e}")
|
522 |
+
return df
|