Wwwduojin commited on
Commit
3b8aea5
1 Parent(s): 32008f3

Upload 24 files

Browse files
src DELETED
File without changes
src/__pycache__/envs.cpython-310.pyc ADDED
Binary file (1.21 kB). View file
 
src/__pycache__/populate.cpython-310.pyc ADDED
Binary file (2.92 kB). View file
 
src/display/__pycache__/about.cpython-310.pyc ADDED
Binary file (18.2 kB). View file
 
src/display/__pycache__/css_html_js.cpython-310.pyc ADDED
Binary file (2.19 kB). View file
 
src/display/__pycache__/formatting.cpython-310.pyc ADDED
Binary file (1.91 kB). View file
 
src/display/__pycache__/utils.cpython-310.pyc ADDED
Binary file (6.39 kB). View file
 
src/display/about.py ADDED
@@ -0,0 +1,224 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from src.display.utils import ModelType
2
+
3
+ TITLE = """<h1 align="center" id="space-title">🏅 Open MLLM Leaderboard</h1>"""
4
+
5
+ INTRODUCTION_TEXT = """
6
+ 📏 The 📈 Open MLLM Leaderboard aims to track, rank and evaluate open MLLMs and chatbots.
7
+ 🥳 Submit a model for automated evaluation on the ⚖️ GPU cluster on the "Submit" page!
8
+ """
9
+
10
+ LLM_BENCHMARKS_TEXT = f"""
11
+ # Context
12
+ With the plethora of large language models (LLMs) and chatbots being released week upon week, often with grandiose claims of their performance, it can be hard to filter out the genuine progress that is being made by the open-source community and which model is the current state of the art.
13
+ ## How it works
14
+ 📈 We evaluate models on 7 key benchmarks using the <a href="https://github.com/EleutherAI/lm-evaluation-harness" target="_blank"> Eleuther AI Language Model Evaluation Harness </a>, a unified framework to test generative language models on a large number of different evaluation tasks.
15
+ - <a href="https://arxiv.org/abs/1803.05457" target="_blank"> AI2 Reasoning Challenge </a> (25-shot) - a set of grade-school science questions.
16
+ - <a href="https://arxiv.org/abs/1905.07830" target="_blank"> HellaSwag </a> (10-shot) - a test of commonsense inference, which is easy for humans (~95%) but challenging for SOTA models.
17
+ - <a href="https://arxiv.org/abs/2009.03300" target="_blank"> MMLU </a> (5-shot) - a test to measure a text model's multitask accuracy. The test covers 57 tasks including elementary mathematics, US history, computer science, law, and more.
18
+ - <a href="https://arxiv.org/abs/2109.07958" target="_blank"> TruthfulQA </a> (0-shot) - a test to measure a model's propensity to reproduce falsehoods commonly found online. Note: TruthfulQA in the Harness is actually a minima a 6-shots task, as it is prepended by 6 examples systematically, even when launched using 0 for the number of few-shot examples.
19
+ - <a href="https://arxiv.org/abs/1907.10641" target="_blank"> Winogrande </a> (5-shot) - an adversarial and difficult Winograd benchmark at scale, for commonsense reasoning.
20
+ - <a href="https://arxiv.org/abs/2110.14168" target="_blank"> GSM8k </a> (5-shot) - diverse grade school math word problems to measure a model's ability to solve multi-step mathematical reasoning problems.
21
+ For all these evaluations, a higher score is a better score.
22
+ We chose these benchmarks as they test a variety of reasoning and general knowledge across a wide variety of fields in 0-shot and few-shot settings.
23
+ ## Details and logs
24
+ You can find:
25
+ - detailed numerical results in the `results` Hugging Face dataset: https://huggingface.co/datasets/open-llm-leaderboard/results
26
+ - details on the input/outputs for the models in the `details` of each model, that you can access by clicking the 📄 emoji after the model name
27
+ - community queries and running status in the `requests` Hugging Face dataset: https://huggingface.co/datasets/open-llm-leaderboard/requests
28
+ ## Reproducibility
29
+ To reproduce our results, here is the commands you can run, using [this version](https://github.com/EleutherAI/lm-evaluation-harness/tree/b281b0921b636bc36ad05c0b0b0763bd6dd43463) of the Eleuther AI Harness:
30
+ `python main.py --model=hf-causal-experimental --model_args="pretrained=<your_model>,use_accelerate=True,revision=<your_model_revision>"`
31
+ ` --tasks=<task_list> --num_fewshot=<n_few_shot> --batch_size=1 --output_path=<output_path>`
32
+ The total batch size we get for models which fit on one A100 node is 8 (8 GPUs * 1). If you don't use parallelism, adapt your batch size to fit.
33
+ *You can expect results to vary slightly for different batch sizes because of padding.*
34
+ The tasks and few shots parameters are:
35
+ - ARC: 25-shot, *arc-challenge* (`acc_norm`)
36
+ - HellaSwag: 10-shot, *hellaswag* (`acc_norm`)
37
+ - TruthfulQA: 0-shot, *truthfulqa-mc* (`mc2`)
38
+ - MMLU: 5-shot, *hendrycksTest-abstract_algebra,hendrycksTest-anatomy,hendrycksTest-astronomy,hendrycksTest-business_ethics,hendrycksTest-clinical_knowledge,hendrycksTest-college_biology,hendrycksTest-college_chemistry,hendrycksTest-college_computer_science,hendrycksTest-college_mathematics,hendrycksTest-college_medicine,hendrycksTest-college_physics,hendrycksTest-computer_security,hendrycksTest-conceptual_physics,hendrycksTest-econometrics,hendrycksTest-electrical_engineering,hendrycksTest-elementary_mathematics,hendrycksTest-formal_logic,hendrycksTest-global_facts,hendrycksTest-high_school_biology,hendrycksTest-high_school_chemistry,hendrycksTest-high_school_computer_science,hendrycksTest-high_school_european_history,hendrycksTest-high_school_geography,hendrycksTest-high_school_government_and_politics,hendrycksTest-high_school_macroeconomics,hendrycksTest-high_school_mathematics,hendrycksTest-high_school_microeconomics,hendrycksTest-high_school_physics,hendrycksTest-high_school_psychology,hendrycksTest-high_school_statistics,hendrycksTest-high_school_us_history,hendrycksTest-high_school_world_history,hendrycksTest-human_aging,hendrycksTest-human_sexuality,hendrycksTest-international_law,hendrycksTest-jurisprudence,hendrycksTest-logical_fallacies,hendrycksTest-machine_learning,hendrycksTest-management,hendrycksTest-marketing,hendrycksTest-medical_genetics,hendrycksTest-miscellaneous,hendrycksTest-moral_disputes,hendrycksTest-moral_scenarios,hendrycksTest-nutrition,hendrycksTest-philosophy,hendrycksTest-prehistory,hendrycksTest-professional_accounting,hendrycksTest-professional_law,hendrycksTest-professional_medicine,hendrycksTest-professional_psychology,hendrycksTest-public_relations,hendrycksTest-security_studies,hendrycksTest-sociology,hendrycksTest-us_foreign_policy,hendrycksTest-virology,hendrycksTest-world_religions* (average of all the results `acc`)
39
+ - Winogrande: 5-shot, *winogrande* (`acc`)
40
+ - GSM8k: 5-shot, *gsm8k* (`acc`)
41
+ Side note on the baseline scores:
42
+ - for log-likelihood evaluation, we select the random baseline
43
+ - for GSM8K, we select the score obtained in the paper after finetuning a 6B model on the full GSM8K training set for 50 epochs
44
+ ## Icons
45
+ - {ModelType.PT.to_str(" : ")} model: new, base models, trained on a given corpora
46
+ - {ModelType.FT.to_str(" : ")} model: pretrained models finetuned on more data
47
+ Specific fine-tune subcategories (more adapted to chat):
48
+ - {ModelType.IFT.to_str(" : ")} model: instruction fine-tunes, which are model fine-tuned specifically on datasets of task instruction
49
+ - {ModelType.RL.to_str(" : ")} model: reinforcement fine-tunes, which usually change the model loss a bit with an added policy.
50
+ If there is no icon, we have not uploaded the information on the model yet, feel free to open an issue with the model information!
51
+ "Flagged" indicates that this model has been flagged by the community, and should probably be ignored! Clicking the link will redirect you to the discussion about the model.
52
+ ## Quantization
53
+ To get more information about quantization, see:
54
+ - 8 bits: [blog post](https://huggingface.co/blog/hf-bitsandbytes-integration), [paper](https://arxiv.org/abs/2208.07339)
55
+ - 4 bits: [blog post](https://huggingface.co/blog/4bit-transformers-bitsandbytes), [paper](https://arxiv.org/abs/2305.14314)
56
+ ## Useful links
57
+ - [Community resources](https://huggingface.co/spaces/HuggingFaceH4/open_llm_leaderboard/discussions/174)
58
+ - [Collection of best models](https://huggingface.co/collections/open-llm-leaderboard/llm-leaderboard-best-models-652d6c7965a4619fb5c27a03)
59
+ """
60
+
61
+ FAQ_TEXT = """
62
+ ---------------------------
63
+ # FAQ
64
+ Below are some common questions - if this FAQ does not answer you, feel free to create a new issue, and we'll take care of it as soon as we can!
65
+ ## 1) Submitting a model
66
+ My model requires `trust_remote_code=True`, can I submit it?
67
+ - *We only support models that have been integrated in a stable version of the `transformers` library for automatic submission, as we don't want to run possibly unsage code on our cluster.*
68
+ What about models of type X?
69
+ - *We only support models that have been integrated in a stable version of the `transformers` library for automatic submission.*
70
+ How can I follow when my model is launched?
71
+ - *You can look for its request file [here](https://huggingface.co/datasets/open-llm-leaderboard/requests) and follow the status evolution, or directly in the queues above the submit form.*
72
+ My model disappeared from all the queues, what happened?
73
+ - *A model disappearing from all the queues usually means that there has been a failure. You can check if that is the case by looking for your model [here](https://huggingface.co/datasets/open-llm-leaderboard/requests).*
74
+ What causes an evaluation failure?
75
+ - *Most of the failures we get come from problems in the submissions (corrupted files, config problems, wrong parameters selected for eval ...), so we'll be grateful if you first make sure you have followed the steps in `About`. However, from time to time, we have failures on our side (hardware/node failures, problem with an update of our backend, connectivity problem ending up in the results not being saved, ...).*
76
+ How can I report an evaluation failure?
77
+ - *As we store the logs for all models, feel free to create an issue, **where you link to the requests file of your model** (look for it [here](https://huggingface.co/datasets/open-llm-leaderboard/requests/tree/main)), so we can investigate! If the model failed due to a problem on our side, we'll relaunch it right away!*
78
+ *Note: Please do not re-upload your model under a different name, it will not help*
79
+ ## 2) Model results
80
+ What kind of information can I find?
81
+ - *Let's imagine you are interested in the Yi-34B results. You have access to 3 different information categories:*
82
+ - *The [request file](https://huggingface.co/datasets/open-llm-leaderboard/requests/blob/main/01-ai/Yi-34B_eval_request_False_bfloat16_Original.json): it gives you information about the status of the evaluation*
83
+ - *The [aggregated results folder](https://huggingface.co/datasets/open-llm-leaderboard/results/tree/main/01-ai/Yi-34B): it gives you aggregated scores, per experimental run*
84
+ - *The [details dataset](https://huggingface.co/datasets/open-llm-leaderboard/details_01-ai__Yi-34B/tree/main): it gives you the full details (scores and examples for each task and a given model)*
85
+ Why do models appear several times in the leaderboard?
86
+ - *We run evaluations with user selected precision and model commit. Sometimes, users submit specific models at different commits and at different precisions (for example, in float16 and 4bit to see how quantization affects performance). You should be able to verify this by displaying the `precision` and `model sha` columns in the display. If, however, you see models appearing several time with the same precision and hash commit, this is not normal.*
87
+ What is this concept of "flagging"?
88
+ - *This mechanism allows user to report models that have unfair performance on the leaderboard. This contains several categories: exceedingly good results on the leaderboard because the model was (maybe accidentally) trained on the evaluation data, models that are copy of other models not atrributed properly, etc.*
89
+ My model has been flagged improperly, what can I do?
90
+ - *Every flagged model has a discussion associated with it - feel free to plead your case there, and we'll see what to do together with the community.*
91
+ ## 3) Editing a submission
92
+ I upgraded my model and want to re-submit, how can I do that?
93
+ - *Please open an issue with the precise name of your model, and we'll remove your model from the leaderboard so you can resubmit. You can also resubmit directly with the new commit hash!*
94
+ I need to rename my model, how can I do that?
95
+ - *You can use @Weyaxi 's [super cool tool](https://huggingface.co/spaces/Weyaxi/open-llm-leaderboard-renamer) to request model name changes, then open a discussion where you link to the created pull request, and we'll check them and merge them as needed.*
96
+ ## 4) Other
97
+ Why don't you display closed source model scores?
98
+ - *This is a leaderboard for Open models, both for philosophical reasons (openness is cool) and for practical reasons: we want to ensure that the results we display are accurate and reproducible, but 1) commercial closed models can change their API thus rendering any scoring at a given time incorrect 2) we re-run everything on our cluster to ensure all models are run on the same setup and you can't do that for these models.*
99
+ I have an issue about accessing the leaderboard through the Gradio API
100
+ - *Since this is not the recommended way to access the leaderboard, we won't provide support for this, but you can look at tools provided by the community for inspiration!*
101
+ """
102
+
103
+
104
+ EVALUATION_QUEUE_TEXT = """
105
+ # Evaluation Queue for the 🤗 Open LLM Leaderboard
106
+ Models added here will be automatically evaluated on the 🤗 cluster.
107
+ ## First steps before submitting a model
108
+ ### 1) Make sure you can load your model and tokenizer using AutoClasses:
109
+ ```python
110
+ from transformers import AutoConfig, AutoModel, AutoTokenizer
111
+ config = AutoConfig.from_pretrained("your model name", revision=revision)
112
+ model = AutoModel.from_pretrained("your model name", revision=revision)
113
+ tokenizer = AutoTokenizer.from_pretrained("your model name", revision=revision)
114
+ ```
115
+ If this step fails, follow the error messages to debug your model before submitting it. It's likely your model has been improperly uploaded.
116
+ Note: make sure your model is public!
117
+ 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!
118
+ ### 2) Convert your model weights to [safetensors](https://huggingface.co/docs/safetensors/index)
119
+ 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`!
120
+ ### 3) Make sure your model has an open license!
121
+ This is a leaderboard for Open LLMs, and we'd love for as many people as possible to know they can use your model 🤗
122
+ ### 4) Fill up your model card
123
+ When we add extra information about models to the leaderboard, it will be automatically taken from the model card
124
+ ## In case of model failure
125
+ If your model is displayed in the `FAILED` category, its execution stopped.
126
+ Make sure you have followed the above steps first.
127
+ 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).
128
+ """
129
+
130
+ CITATION_BUTTON_LABEL = "Copy the following snippet to cite these results"
131
+ CITATION_BUTTON_TEXT = r"""
132
+ @misc{open-llm-leaderboard,
133
+ author = {Edward Beeching and Clémentine Fourrier and Nathan Habib and Sheon Han and Nathan Lambert and Nazneen Rajani and Omar Sanseviero and Lewis Tunstall and Thomas Wolf},
134
+ title = {Open LLM Leaderboard},
135
+ year = {2023},
136
+ publisher = {Hugging Face},
137
+ howpublished = "\url{https://huggingface.co/spaces/HuggingFaceH4/open_llm_leaderboard}"
138
+ }
139
+ @software{eval-harness,
140
+ author = {Gao, Leo and
141
+ Tow, Jonathan and
142
+ Biderman, Stella and
143
+ Black, Sid and
144
+ DiPofi, Anthony and
145
+ Foster, Charles and
146
+ Golding, Laurence and
147
+ Hsu, Jeffrey and
148
+ McDonell, Kyle and
149
+ Muennighoff, Niklas and
150
+ Phang, Jason and
151
+ Reynolds, Laria and
152
+ Tang, Eric and
153
+ Thite, Anish and
154
+ Wang, Ben and
155
+ Wang, Kevin and
156
+ Zou, Andy},
157
+ title = {A framework for few-shot language model evaluation},
158
+ month = sep,
159
+ year = 2021,
160
+ publisher = {Zenodo},
161
+ version = {v0.0.1},
162
+ doi = {10.5281/zenodo.5371628},
163
+ url = {https://doi.org/10.5281/zenodo.5371628}
164
+ }
165
+ @misc{clark2018think,
166
+ title={Think you have Solved Question Answering? Try ARC, the AI2 Reasoning Challenge},
167
+ author={Peter Clark and Isaac Cowhey and Oren Etzioni and Tushar Khot and Ashish Sabharwal and Carissa Schoenick and Oyvind Tafjord},
168
+ year={2018},
169
+ eprint={1803.05457},
170
+ archivePrefix={arXiv},
171
+ primaryClass={cs.AI}
172
+ }
173
+ @misc{zellers2019hellaswag,
174
+ title={HellaSwag: Can a Machine Really Finish Your Sentence?},
175
+ author={Rowan Zellers and Ari Holtzman and Yonatan Bisk and Ali Farhadi and Yejin Choi},
176
+ year={2019},
177
+ eprint={1905.07830},
178
+ archivePrefix={arXiv},
179
+ primaryClass={cs.CL}
180
+ }
181
+ @misc{hendrycks2021measuring,
182
+ title={Measuring Massive Multitask Language Understanding},
183
+ author={Dan Hendrycks and Collin Burns and Steven Basart and Andy Zou and Mantas Mazeika and Dawn Song and Jacob Steinhardt},
184
+ year={2021},
185
+ eprint={2009.03300},
186
+ archivePrefix={arXiv},
187
+ primaryClass={cs.CY}
188
+ }
189
+ @misc{lin2022truthfulqa,
190
+ title={TruthfulQA: Measuring How Models Mimic Human Falsehoods},
191
+ author={Stephanie Lin and Jacob Hilton and Owain Evans},
192
+ year={2022},
193
+ eprint={2109.07958},
194
+ archivePrefix={arXiv},
195
+ primaryClass={cs.CL}
196
+ }
197
+ @misc{DBLP:journals/corr/abs-1907-10641,
198
+ title={{WINOGRANDE:} An Adversarial Winograd Schema Challenge at Scale},
199
+ author={Keisuke Sakaguchi and Ronan Le Bras and Chandra Bhagavatula and Yejin Choi},
200
+ year={2019},
201
+ eprint={1907.10641},
202
+ archivePrefix={arXiv},
203
+ primaryClass={cs.CL}
204
+ }
205
+ @misc{DBLP:journals/corr/abs-2110-14168,
206
+ title={Training Verifiers to Solve Math Word Problems},
207
+ author={Karl Cobbe and
208
+ Vineet Kosaraju and
209
+ Mohammad Bavarian and
210
+ Mark Chen and
211
+ Heewoo Jun and
212
+ Lukasz Kaiser and
213
+ Matthias Plappert and
214
+ Jerry Tworek and
215
+ Jacob Hilton and
216
+ Reiichiro Nakano and
217
+ Christopher Hesse and
218
+ John Schulman},
219
+ year={2021},
220
+ eprint={2110.14168},
221
+ archivePrefix={arXiv},
222
+ primaryClass={cs.CL}
223
+ }
224
+ """
src/display/css_html_js.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ @Project -> File :leaderboard -> css_html_js.py
4
+ @Author : Www多金
5
+ @Date :2023/12/12 16:01
6
+ @Desc : study Mechine Learning
7
+ """
8
+ custom_css = """
9
+ .markdown-text {
10
+ font-size: 16px !important;
11
+ }
12
+ #models-to-add-text {
13
+ font-size: 18px !important;
14
+ }
15
+ #citation-button span {
16
+ font-size: 16px !important;
17
+ }
18
+ #citation-button textarea {
19
+ font-size: 16px !important;
20
+ }
21
+ #citation-button > label > button {
22
+ margin: 6px;
23
+ transform: scale(1.3);
24
+ }
25
+ #leaderboard-table {
26
+ margin-top: 15px
27
+ }
28
+ #leaderboard-table-lite {
29
+ margin-top: 15px
30
+ }
31
+ #search-bar-table-box > div:first-child {
32
+ background: none;
33
+ border: none;
34
+ }
35
+
36
+ #search-bar {
37
+ padding: 0px;
38
+ }
39
+ /* Hides the final AutoEvalColumn */
40
+ #llm-benchmark-tab-table table td:last-child,
41
+ #llm-benchmark-tab-table table th:last-child {
42
+ display: none;
43
+ }
44
+ /* Limit the width of the first AutoEvalColumn so that names don't expand too much */
45
+ table td:first-child,
46
+ table th:first-child {
47
+ max-width: 400px;
48
+ overflow: auto;
49
+ white-space: nowrap;
50
+ }
51
+ .tab-buttons button {
52
+ font-size: 20px;
53
+ }
54
+ #scale-logo {
55
+ border-style: none !important;
56
+ box-shadow: none;
57
+ display: block;
58
+ margin-left: auto;
59
+ margin-right: auto;
60
+ max-width: 600px;
61
+ }
62
+ #scale-logo .download {
63
+ display: none;
64
+ }
65
+ #filter_type{
66
+ border: 0;
67
+ padding-left: 0;
68
+ padding-top: 0;
69
+ }
70
+ #filter_type label {
71
+ display: flex;
72
+ }
73
+ #filter_type label > span{
74
+ margin-top: var(--spacing-lg);
75
+ margin-right: 0.5em;
76
+ }
77
+ #filter_type label > .wrap{
78
+ width: 103px;
79
+ }
80
+ #filter_type label > .wrap .wrap-inner{
81
+ padding: 2px;
82
+ }
83
+ #filter_type label > .wrap .wrap-inner input{
84
+ width: 1px
85
+ }
86
+ #filter-columns-type{
87
+ border:0;
88
+ padding:0.5;
89
+ }
90
+ #filter-columns-size{
91
+ border:0;
92
+ padding:0.5;
93
+ }
94
+ #box-filter > .form{
95
+ border: 0
96
+ }
97
+ """
98
+
99
+ get_window_url_params = """
100
+ function(url_params) {
101
+ const params = new URLSearchParams(window.location.search);
102
+ url_params = Object.fromEntries(params);
103
+ return url_params;
104
+ }
105
+ """
src/display/formatting.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ @Project -> File :leaderboard -> formatting.py
4
+ @Author : Www多金
5
+ @Date :2023/12/12 16:39
6
+ @Desc : study Mechine Learning
7
+ """
8
+ import os
9
+ from datetime import datetime, timezone
10
+
11
+ from huggingface_hub import HfApi
12
+ from huggingface_hub.hf_api import ModelInfo
13
+
14
+
15
+ API = HfApi()
16
+
17
+ def model_hyperlink(link, model_name):
18
+ return f'<a target="_blank" href="{link}" style="color: var(--link-text-color); text-decoration: underline;text-decoration-style: dotted;">{model_name}</a>'
19
+
20
+
21
+ def make_clickable_model(model_name):
22
+ link = f"https://huggingface.co/{model_name}"
23
+
24
+ details_model_name = model_name.replace("/", "__")
25
+ details_link = f"https://huggingface.co/datasets/open-llm-leaderboard/details_{details_model_name}"
26
+
27
+ return model_hyperlink(link, model_name) + " " + model_hyperlink(details_link, "📑")
28
+
29
+
30
+ def styled_error(error):
31
+ return f"<p style='color: red; font-size: 20px; text-align: center;'>{error}</p>"
32
+
33
+
34
+ def styled_warning(warn):
35
+ return f"<p style='color: orange; font-size: 20px; text-align: center;'>{warn}</p>"
36
+
37
+
38
+ def styled_message(message):
39
+ return f"<p style='color: green; font-size: 20px; text-align: center;'>{message}</p>"
40
+
41
+
42
+ def has_no_nan_values(df, columns):
43
+ return df[columns].notna().all(axis=1)
44
+
45
+
46
+ def has_nan_values(df, columns):
47
+ return df[columns].isna().any(axis=1)
src/display/utils.py ADDED
@@ -0,0 +1,198 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ @Project -> File :leaderboard -> utils.py
4
+ @Author : Www多金
5
+ @Date :2023/12/12 16:00
6
+ @Desc : study Mechine Learning
7
+ """
8
+ from dataclasses import dataclass, make_dataclass
9
+ from enum import Enum
10
+
11
+ import pandas as pd
12
+
13
+
14
+ def fields(raw_class):
15
+ return [v for k, v in raw_class.__dict__.items() if k[:2] != "__" and k[-2:] != "__"]
16
+
17
+
18
+ @dataclass
19
+ class Task:
20
+ benchmark: str
21
+ metric: str
22
+ col_name: str
23
+
24
+
25
+ class Tasks(Enum):
26
+ arc = Task("arc:challenge", "acc_norm", "ARC")
27
+ hellaswag = Task("hellaswag", "acc_norm", "HellaSwag")
28
+ mmlu = Task("hendrycksTest", "acc", "MMLU")
29
+ truthfulqa = Task("truthfulqa:mc", "mc2", "TruthfulQA")
30
+ winogrande = Task("winogrande", "acc", "Winogrande")
31
+ gsm8k = Task("gsm8k", "acc", "GSM8K")
32
+
33
+
34
+ # These classes are for user facing column names,
35
+ # to avoid having to change them all around the code
36
+ # when a modif is needed
37
+ @dataclass
38
+ class ColumnContent:
39
+ name: str
40
+ type: str
41
+ displayed_by_default: bool
42
+ hidden: bool = False
43
+ never_hidden: bool = False
44
+ dummy: bool = False
45
+
46
+
47
+ auto_eval_column_dict = []
48
+ # Init
49
+ auto_eval_column_dict.append(["model_type_symbol", ColumnContent, ColumnContent("T", "str", True, never_hidden=True)])
50
+ auto_eval_column_dict.append(["model", ColumnContent, ColumnContent("Model", "markdown", True, never_hidden=True)])
51
+ # Scores
52
+ auto_eval_column_dict.append(["average", ColumnContent, ColumnContent("Average ⬆️", "number", True)])
53
+ for task in Tasks:
54
+ auto_eval_column_dict.append([task.name, ColumnContent, ColumnContent(task.value.col_name, "number", True)])
55
+ # Model information
56
+ auto_eval_column_dict.append(["model_type", ColumnContent, ColumnContent("Type", "str", False)])
57
+ auto_eval_column_dict.append(["architecture", ColumnContent, ColumnContent("Architecture", "str", False)])
58
+ auto_eval_column_dict.append(["weight_type", ColumnContent, ColumnContent("Weight type", "str", False, True)])
59
+ auto_eval_column_dict.append(["precision", ColumnContent, ColumnContent("Precision", "str", False)])
60
+ auto_eval_column_dict.append(["license", ColumnContent, ColumnContent("Hub License", "str", False)])
61
+ auto_eval_column_dict.append(["params", ColumnContent, ColumnContent("#Params (B)", "number", False)])
62
+ auto_eval_column_dict.append(["likes", ColumnContent, ColumnContent("Hub ❤️", "number", False)])
63
+ auto_eval_column_dict.append(["still_on_hub", ColumnContent, ColumnContent("Available on the hub", "bool", False)])
64
+ auto_eval_column_dict.append(["revision", ColumnContent, ColumnContent("Model sha", "str", False, False)])
65
+ # Dummy column for the search bar (hidden by the custom CSS)
66
+ auto_eval_column_dict.append(["dummy", ColumnContent, ColumnContent("model_name_for_query", "str", False, dummy=True)])
67
+
68
+ # We use make dataclass to dynamically fill the scores from Tasks
69
+ AutoEvalColumn = make_dataclass("AutoEvalColumn", auto_eval_column_dict, frozen=True)
70
+
71
+
72
+ @dataclass(frozen=True)
73
+ class EvalQueueColumn: # Queue column
74
+ model = ColumnContent("model", "markdown", True)
75
+ revision = ColumnContent("revision", "str", True)
76
+ private = ColumnContent("private", "bool", True)
77
+ precision = ColumnContent("precision", "str", True)
78
+ weight_type = ColumnContent("weight_type", "str", "Original")
79
+ status = ColumnContent("status", "str", True)
80
+
81
+
82
+ baseline_row = {
83
+ AutoEvalColumn.model.name: "<p>Baseline</p>",
84
+ AutoEvalColumn.revision.name: "N/A",
85
+ AutoEvalColumn.precision.name: None,
86
+ AutoEvalColumn.average.name: 31.0,
87
+ AutoEvalColumn.arc.name: 25.0,
88
+ AutoEvalColumn.hellaswag.name: 25.0,
89
+ AutoEvalColumn.mmlu.name: 25.0,
90
+ AutoEvalColumn.truthfulqa.name: 25.0,
91
+ AutoEvalColumn.winogrande.name: 50.0,
92
+ AutoEvalColumn.gsm8k.name: 0.21,
93
+ AutoEvalColumn.dummy.name: "baseline",
94
+ AutoEvalColumn.model_type.name: "",
95
+ }
96
+
97
+ # Average ⬆️ human baseline is 0.897 (source: averaging human baselines below)
98
+ # ARC human baseline is 0.80 (source: https://lab42.global/arc/)
99
+ # HellaSwag human baseline is 0.95 (source: https://deepgram.com/learn/hellaswag-llm-benchmark-guide)
100
+ # MMLU human baseline is 0.898 (source: https://openreview.net/forum?id=d7KBjmI3GmQ)
101
+ # TruthfulQA human baseline is 0.94(source: https://arxiv.org/pdf/2109.07958.pdf)
102
+ # Winogrande: https://leaderboard.allenai.org/winogrande/submissions/public
103
+ # GSM8K: paper
104
+ # Define the human baselines
105
+ human_baseline_row = {
106
+ AutoEvalColumn.model.name: "<p>Human performance</p>",
107
+ AutoEvalColumn.revision.name: "N/A",
108
+ AutoEvalColumn.precision.name: None,
109
+ AutoEvalColumn.average.name: 92.75,
110
+ AutoEvalColumn.arc.name: 80.0,
111
+ AutoEvalColumn.hellaswag.name: 95.0,
112
+ AutoEvalColumn.mmlu.name: 89.8,
113
+ AutoEvalColumn.truthfulqa.name: 94.0,
114
+ AutoEvalColumn.winogrande.name: 94.0,
115
+ AutoEvalColumn.gsm8k.name: 100,
116
+ AutoEvalColumn.dummy.name: "human_baseline",
117
+ AutoEvalColumn.model_type.name: "",
118
+ }
119
+
120
+
121
+ @dataclass
122
+ class ModelDetails:
123
+ name: str
124
+ symbol: str = "" # emoji, only for the model type
125
+
126
+
127
+ class ModelType(Enum):
128
+ PT = ModelDetails(name="pretrained", symbol="🟢")
129
+ FT = ModelDetails(name="fine-tuned", symbol="🔶")
130
+ IFT = ModelDetails(name="instruction-tuned", symbol="⭕")
131
+ RL = ModelDetails(name="RL-tuned", symbol="🟦")
132
+ Unknown = ModelDetails(name="", symbol="?")
133
+
134
+ def to_str(self, separator=" "):
135
+ return f"{self.value.symbol}{separator}{self.value.name}"
136
+
137
+ @staticmethod
138
+ def from_str(type):
139
+ if "fine-tuned" in type or "🔶" in type:
140
+ return ModelType.FT
141
+ if "pretrained" in type or "🟢" in type:
142
+ return ModelType.PT
143
+ if "RL-tuned" in type or "🟦" in type:
144
+ return ModelType.RL
145
+ if "instruction-tuned" in type or "⭕" in type:
146
+ return ModelType.IFT
147
+ return ModelType.Unknown
148
+
149
+
150
+ class WeightType(Enum):
151
+ Adapter = ModelDetails("Adapter")
152
+ Original = ModelDetails("Original")
153
+ Delta = ModelDetails("Delta")
154
+
155
+
156
+ class Precision(Enum):
157
+ float16 = ModelDetails("float16")
158
+ bfloat16 = ModelDetails("bfloat16")
159
+ qt_8bit = ModelDetails("8bit")
160
+ qt_4bit = ModelDetails("4bit")
161
+ qt_GPTQ = ModelDetails("GPTQ")
162
+ Unknown = ModelDetails("?")
163
+
164
+ def from_str(precision):
165
+ if precision in ["torch.float16", "float16"]:
166
+ return Precision.float16
167
+ if precision in ["torch.bfloat16", "bfloat16"]:
168
+ return Precision.bfloat16
169
+ if precision in ["8bit"]:
170
+ return Precision.qt_8bit
171
+ if precision in ["4bit"]:
172
+ return Precision.qt_4bit
173
+ if precision in ["GPTQ", "None"]:
174
+ return Precision.qt_GPTQ
175
+ return Precision.Unknown
176
+
177
+
178
+ # Column selection
179
+ COLS = [c.name for c in fields(AutoEvalColumn) if not c.hidden]
180
+ TYPES = [c.type for c in fields(AutoEvalColumn) if not c.hidden]
181
+ COLS_LITE = [c.name for c in fields(AutoEvalColumn) if c.displayed_by_default and not c.hidden]
182
+ TYPES_LITE = [c.type for c in fields(AutoEvalColumn) if c.displayed_by_default and not c.hidden]
183
+
184
+ EVAL_COLS = [c.name for c in fields(EvalQueueColumn)]
185
+ EVAL_TYPES = [c.type for c in fields(EvalQueueColumn)]
186
+
187
+ BENCHMARK_COLS = [t.value.col_name for t in Tasks]
188
+
189
+ NUMERIC_INTERVALS = {
190
+ "?": pd.Interval(-1, 0, closed="right"),
191
+ "~1.5": pd.Interval(0, 2, closed="right"),
192
+ "~3": pd.Interval(2, 4, closed="right"),
193
+ "~7": pd.Interval(4, 9, closed="right"),
194
+ "~13": pd.Interval(9, 20, closed="right"),
195
+ "~35": pd.Interval(20, 45, closed="right"),
196
+ "~60": pd.Interval(45, 70, closed="right"),
197
+ "70+": pd.Interval(70, 10000, closed="right"),
198
+ }
src/envs.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ @Project -> File :leaderboard -> envs.py
4
+ @Author : Www多金
5
+ @Date :2023/12/12 16:42
6
+ @Desc : study Mechine Learning
7
+ """
8
+ import os
9
+
10
+ from huggingface_hub import HfApi
11
+
12
+ # clone / pull the lmeh eval data
13
+ H4_TOKEN = os.environ.get("H4_TOKEN", None)
14
+
15
+ REPO_ID = "HuggingFaceH4/open_llm_leaderboard"
16
+ QUEUE_REPO = "open-llm-leaderboard/requests"
17
+ RESULTS_REPO = "open-llm-leaderboard/results"
18
+
19
+ PRIVATE_QUEUE_REPO = "open-llm-leaderboard/private-requests"
20
+ PRIVATE_RESULTS_REPO = "open-llm-leaderboard/private-results"
21
+
22
+ IS_PUBLIC = bool(os.environ.get("IS_PUBLIC", True))
23
+
24
+ CACHE_PATH=os.getenv("HF_HOME", ".")
25
+
26
+ EVAL_REQUESTS_PATH = os.path.join(CACHE_PATH, "eval-queue")
27
+ EVAL_RESULTS_PATH = os.path.join(CACHE_PATH, "eval-results")
28
+
29
+ EVAL_REQUESTS_PATH_PRIVATE = "eval-queue-private"
30
+ EVAL_RESULTS_PATH_PRIVATE = "eval-results-private"
31
+
32
+ PATH_TO_COLLECTION = "open-llm-leaderboard/llm-leaderboard-best-models-652d6c7965a4619fb5c27a03"
33
+
34
+ # Rate limit variables
35
+ RATE_LIMIT_PERIOD = 7
36
+ RATE_LIMIT_QUOTA = 5
37
+ HAS_HIGHER_RATE_LIMIT = ["TheBloke"]
38
+
39
+ API = HfApi(token=H4_TOKEN)
src/leaderboard/__pycache__/filter_models.cpython-310.pyc ADDED
Binary file (2.45 kB). View file
 
src/leaderboard/__pycache__/read_evals.cpython-310.pyc ADDED
Binary file (6.71 kB). View file
 
src/leaderboard/filter_models.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ @Project -> File :leaderboard -> filter_models.py
4
+ @Author : Www多金
5
+ @Date :2023/12/12 16:40
6
+ @Desc : study Mechine Learning
7
+ """
8
+ from src.display.formatting import model_hyperlink
9
+ from src.display.utils import AutoEvalColumn
10
+
11
+ # Models which have been flagged by users as being problematic for a reason or another
12
+ # (Model name to forum discussion link)
13
+ FLAGGED_MODELS = {
14
+ "Voicelab/trurl-2-13b": "https://huggingface.co/spaces/HuggingFaceH4/open_llm_leaderboard/discussions/202",
15
+ "deepnight-research/llama-2-70B-inst": "https://huggingface.co/spaces/HuggingFaceH4/open_llm_leaderboard/discussions/207",
16
+ "Aspik101/trurl-2-13b-pl-instruct_unload": "https://huggingface.co/spaces/HuggingFaceH4/open_llm_leaderboard/discussions/213",
17
+ "Fredithefish/ReasonixPajama-3B-HF": "https://huggingface.co/spaces/HuggingFaceH4/open_llm_leaderboard/discussions/236",
18
+ "TigerResearch/tigerbot-7b-sft-v1": "https://huggingface.co/spaces/HuggingFaceH4/open_llm_leaderboard/discussions/237",
19
+ "gaodrew/gaodrew-gorgonzola-13b": "https://huggingface.co/spaces/HuggingFaceH4/open_llm_leaderboard/discussions/215",
20
+ "AIDC-ai-business/Marcoroni-70B": "https://huggingface.co/spaces/HuggingFaceH4/open_llm_leaderboard/discussions/287",
21
+ "AIDC-ai-business/Marcoroni-13B": "https://huggingface.co/spaces/HuggingFaceH4/open_llm_leaderboard/discussions/287",
22
+ "AIDC-ai-business/Marcoroni-7B": "https://huggingface.co/spaces/HuggingFaceH4/open_llm_leaderboard/discussions/287",
23
+ "TigerResearch/tigerbot-70b-chat-v4-4k": "https://huggingface.co/spaces/HuggingFaceH4/open_llm_leaderboard/discussions/438",
24
+ "TigerResearch/tigerbot-70b-chat-v2": "https://huggingface.co/spaces/HuggingFaceH4/open_llm_leaderboard/discussions/438",
25
+ }
26
+
27
+ # Models which have been requested by orgs to not be submitted on the leaderboard
28
+ DO_NOT_SUBMIT_MODELS = [
29
+ "Voicelab/trurl-2-13b", # trained on MMLU
30
+ "TigerResearch/tigerbot-70b-chat", # per authors request
31
+ "TigerResearch/tigerbot-70b-chat-v2", # per authors request
32
+ "TigerResearch/tigerbot-70b-chat-v4-4k", # per authors request
33
+ ]
34
+
35
+
36
+ def flag_models(leaderboard_data: list[dict]):
37
+ for model_data in leaderboard_data:
38
+ if model_data["model_name_for_query"] in FLAGGED_MODELS:
39
+ issue_num = FLAGGED_MODELS[model_data["model_name_for_query"]].split("/")[-1]
40
+ issue_link = model_hyperlink(
41
+ FLAGGED_MODELS[model_data["model_name_for_query"]],
42
+ f"See discussion #{issue_num}",
43
+ )
44
+ model_data[
45
+ AutoEvalColumn.model.name
46
+ ] = f"{model_data[AutoEvalColumn.model.name]} has been flagged! {issue_link}"
47
+
48
+
49
+ def remove_forbidden_models(leaderboard_data: list[dict]):
50
+ indices_to_remove = []
51
+ for ix, model in enumerate(leaderboard_data):
52
+ if model["model_name_for_query"] in DO_NOT_SUBMIT_MODELS:
53
+ indices_to_remove.append(ix)
54
+
55
+ for ix in reversed(indices_to_remove):
56
+ leaderboard_data.pop(ix)
57
+ return leaderboard_data
58
+
59
+
60
+ def filter_models(leaderboard_data: list[dict]):
61
+ leaderboard_data = remove_forbidden_models(leaderboard_data)
62
+ flag_models(leaderboard_data)
src/leaderboard/read_evals.py ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ @Project -> File :leaderboard -> read_evals.py
4
+ @Author : Www多金
5
+ @Date :2023/12/12 16:40
6
+ @Desc : study Mechine Learning
7
+ """
8
+ import glob
9
+ import json
10
+ import math
11
+ import os
12
+ from dataclasses import dataclass
13
+
14
+ import dateutil
15
+ # from datetime import datetime
16
+ # from transformers import AutoConfig
17
+ import numpy as np
18
+
19
+ from src.display.formatting import make_clickable_model
20
+ from src.display.utils import AutoEvalColumn, ModelType, Tasks, Precision, WeightType
21
+ from src.submission.check_validity import is_model_on_hub
22
+
23
+
24
+ @dataclass
25
+ class EvalResult:
26
+ # Also see src.display.utils.AutoEvalColumn for what will be displayed.
27
+ eval_name: str # org_model_precision (uid)
28
+ full_model: str # org/model (path on hub)
29
+ org: str
30
+ model: str
31
+ revision: str # commit hash, "" if main
32
+ results: dict
33
+ precision: Precision = Precision.Unknown
34
+ model_type: ModelType = ModelType.Unknown # Pretrained, fine tuned, ...
35
+ weight_type: WeightType = WeightType.Original # Original or Adapter
36
+ architecture: str = "Unknown" # From config file
37
+ license: str = "?"
38
+ likes: int = 0
39
+ num_params: int = 0
40
+ date: str = "" # submission date of request file
41
+ still_on_hub: bool = False
42
+
43
+ @classmethod
44
+ def init_from_json_file(self, json_filepath):
45
+ """Inits the result from the specific model result file"""
46
+ with open(json_filepath) as fp:
47
+ data = json.load(fp)
48
+
49
+ # We manage the legacy config format
50
+ config = data.get("config", data.get("config_general", None))
51
+
52
+ # Precision
53
+ precision = Precision.from_str(config.get("model_dtype"))
54
+
55
+ # Get model and org
56
+ org_and_model = config.get("model_name", config.get("model_args", None))
57
+ org_and_model = org_and_model.split("/", 1)
58
+
59
+ if len(org_and_model) == 1:
60
+ org = None
61
+ model = org_and_model[0]
62
+ result_key = f"{model}_{precision.value.name}"
63
+ else:
64
+ org = org_and_model[0]
65
+ model = org_and_model[1]
66
+ result_key = f"{org}_{model}_{precision.value.name}"
67
+ full_model = "/".join(org_and_model)
68
+
69
+ still_on_hub, error, model_config = is_model_on_hub(
70
+ full_model, config.get("model_sha", "main"), trust_remote_code=True, test_tokenizer=False
71
+ )
72
+ architecture = "?"
73
+ if model_config is not None:
74
+ architectures = getattr(model_config, "architectures", None)
75
+ if architectures:
76
+ architecture = ";".join(architectures)
77
+
78
+ # Extract results available in this file (some results are split in several files)
79
+ results = {}
80
+ for task in Tasks:
81
+ task = task.value
82
+ # We skip old mmlu entries
83
+ wrong_mmlu_version = False
84
+ if task.benchmark == "hendrycksTest":
85
+ for mmlu_k in ["harness|hendrycksTest-abstract_algebra|5", "hendrycksTest-abstract_algebra"]:
86
+ if mmlu_k in data["versions"] and data["versions"][mmlu_k] == 0:
87
+ wrong_mmlu_version = True
88
+
89
+ if wrong_mmlu_version:
90
+ continue
91
+
92
+ # Some truthfulQA values are NaNs
93
+ if task.benchmark == "truthfulqa:mc" and "harness|truthfulqa:mc|0" in data["results"]:
94
+ if math.isnan(float(data["results"]["harness|truthfulqa:mc|0"][task.metric])):
95
+ results[task.benchmark] = 0.0
96
+ continue
97
+
98
+ # We average all scores of a given metric (mostly for mmlu)
99
+ accs = np.array([v.get(task.metric, None) for k, v in data["results"].items() if task.benchmark in k])
100
+ if accs.size == 0 or any([acc is None for acc in accs]):
101
+ continue
102
+
103
+ mean_acc = np.mean(accs) * 100.0
104
+ results[task.benchmark] = mean_acc
105
+
106
+ return self(
107
+ eval_name=result_key,
108
+ full_model=full_model,
109
+ org=org,
110
+ model=model,
111
+ results=results,
112
+ precision=precision,
113
+ revision= config.get("model_sha", ""),
114
+ still_on_hub=still_on_hub,
115
+ architecture=architecture
116
+ )
117
+
118
+ def update_with_request_file(self, requests_path):
119
+ """Finds the relevant request file for the current model and updates info with it"""
120
+ request_file = get_request_file_for_model(requests_path, self.full_model, self.precision.value.name)
121
+
122
+ try:
123
+ with open(request_file, "r") as f:
124
+ request = json.load(f)
125
+ self.model_type = ModelType.from_str(request.get("model_type", ""))
126
+ self.weight_type = WeightType[request.get("weight_type", "Original")]
127
+ self.license = request.get("license", "?")
128
+ self.likes = request.get("likes", 0)
129
+ self.num_params = request.get("params", 0)
130
+ self.date = request.get("submitted_time", "")
131
+ except Exception:
132
+ print(f"Could not find request file for {self.org}/{self.model}")
133
+
134
+ def to_dict(self):
135
+ """Converts the Eval Result to a dict compatible with our dataframe display"""
136
+ average = sum([v for v in self.results.values() if v is not None]) / len(Tasks)
137
+ data_dict = {
138
+ "eval_name": self.eval_name, # not a column, just a save name,
139
+ AutoEvalColumn.precision.name: self.precision.value.name,
140
+ AutoEvalColumn.model_type.name: self.model_type.value.name,
141
+ AutoEvalColumn.model_type_symbol.name: self.model_type.value.symbol,
142
+ AutoEvalColumn.weight_type.name: self.weight_type.value.name,
143
+ AutoEvalColumn.architecture.name: self.architecture,
144
+ AutoEvalColumn.model.name: make_clickable_model(self.full_model),
145
+ AutoEvalColumn.dummy.name: self.full_model,
146
+ AutoEvalColumn.revision.name: self.revision,
147
+ AutoEvalColumn.average.name: average,
148
+ AutoEvalColumn.license.name: self.license,
149
+ AutoEvalColumn.likes.name: self.likes,
150
+ AutoEvalColumn.params.name: self.num_params,
151
+ AutoEvalColumn.still_on_hub.name: self.still_on_hub,
152
+ }
153
+
154
+ for task in Tasks:
155
+ data_dict[task.value.col_name] = self.results[task.value.benchmark]
156
+
157
+ return data_dict
158
+
159
+
160
+ def get_request_file_for_model(requests_path, model_name, precision):
161
+ """Selects the correct request file for a given model. Only keeps runs tagged as FINISHED"""
162
+ request_files = os.path.join(
163
+ requests_path,
164
+ f"{model_name}_eval_request_*.json",
165
+ )
166
+ request_files = glob.glob(request_files)
167
+
168
+ # Select correct request file (precision)
169
+ request_file = ""
170
+ request_files = sorted(request_files, reverse=True)
171
+ for tmp_request_file in request_files:
172
+ with open(tmp_request_file, "r") as f:
173
+ req_content = json.load(f)
174
+ if (
175
+ req_content["status"] in ["FINISHED"]
176
+ and req_content["precision"] == precision.split(".")[-1]
177
+ ):
178
+ request_file = tmp_request_file
179
+ return request_file
180
+
181
+
182
+ def get_raw_eval_results(results_path: str, requests_path: str) -> list[EvalResult]:
183
+ """From the path of the results folder root, extract all needed info for results"""
184
+ model_result_filepaths = []
185
+
186
+ for root, _, files in os.walk(results_path):
187
+ # We should only have json files in model results
188
+ if len(files) == 0 or any([not f.endswith(".json") for f in files]):
189
+ continue
190
+
191
+ # Sort the files by date
192
+ try:
193
+ files.sort(key=lambda x: x.removesuffix(".json").removeprefix("results_")[:-7])
194
+ except dateutil.parser._parser.ParserError:
195
+ files = [files[-1]]
196
+
197
+ for file in files:
198
+ model_result_filepaths.append(os.path.join(root, file))
199
+
200
+ eval_results = {}
201
+ for model_result_filepath in model_result_filepaths:
202
+ # Creation of result
203
+ eval_result = EvalResult.init_from_json_file(model_result_filepath)
204
+ eval_result.update_with_request_file(requests_path)
205
+
206
+ # Store results of same eval together
207
+ eval_name = eval_result.eval_name
208
+ if eval_name in eval_results.keys():
209
+ eval_results[eval_name].results.update({k: v for k, v in eval_result.results.items() if v is not None})
210
+ else:
211
+ eval_results[eval_name] = eval_result
212
+
213
+ results = []
214
+ for v in eval_results.values():
215
+ try:
216
+ v.to_dict() # we test if the dict version is complete
217
+ results.append(v)
218
+ except KeyError: # not all eval values present
219
+ continue
220
+
221
+ return results
src/populate.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ @Project -> File :leaderboard -> populate.py
4
+ @Author : Www多金
5
+ @Date :2023/12/12 16:39
6
+ @Desc : study Mechine Learning
7
+ """
8
+ import json
9
+ import os
10
+
11
+ import pandas as pd
12
+
13
+ from src.display.formatting import has_no_nan_values, make_clickable_model
14
+ from src.display.utils import AutoEvalColumn, EvalQueueColumn, baseline_row
15
+ from src.leaderboard.filter_models import filter_models
16
+ from src.leaderboard.read_evals import get_raw_eval_results
17
+
18
+
19
+ def get_leaderboard_df(results_path: str, requests_path: str, cols: list, benchmark_cols: list) -> pd.DataFrame:
20
+ raw_data = get_raw_eval_results(results_path, requests_path)
21
+ all_data_json = [v.to_dict() for v in raw_data]
22
+ all_data_json.append(baseline_row)
23
+ filter_models(all_data_json)
24
+
25
+ df = pd.DataFrame.from_records(all_data_json)
26
+ df = df.sort_values(by=[AutoEvalColumn.average.name], ascending=False)
27
+ df = df[cols].round(decimals=2)
28
+
29
+ # filter out if any of the benchmarks have not been produced
30
+ df = df[has_no_nan_values(df, benchmark_cols)]
31
+ return raw_data, df
32
+
33
+
34
+ def get_evaluation_queue_df(save_path: str, cols: list) -> list[pd.DataFrame]:
35
+ entries = [entry for entry in os.listdir(save_path) if not entry.startswith(".")]
36
+ all_evals = []
37
+
38
+ for entry in entries:
39
+ if ".json" in entry:
40
+ file_path = os.path.join(save_path, entry)
41
+ with open(file_path) as fp:
42
+ data = json.load(fp)
43
+
44
+ data[EvalQueueColumn.model.name] = make_clickable_model(data["model"])
45
+ data[EvalQueueColumn.revision.name] = data.get("revision", "main")
46
+
47
+ all_evals.append(data)
48
+ elif ".md" not in entry:
49
+ # this is a folder
50
+ sub_entries = [e for e in os.listdir(f"{save_path}/{entry}") if not e.startswith(".")]
51
+ for sub_entry in sub_entries:
52
+ file_path = os.path.join(save_path, entry, sub_entry)
53
+ with open(file_path) as fp:
54
+ data = json.load(fp)
55
+
56
+ data[EvalQueueColumn.model.name] = make_clickable_model(data["model"])
57
+ data[EvalQueueColumn.revision.name] = data.get("revision", "main")
58
+ all_evals.append(data)
59
+
60
+ pending_list = [e for e in all_evals if e["status"] in ["PENDING", "RERUN"]]
61
+ running_list = [e for e in all_evals if e["status"] == "RUNNING"]
62
+ finished_list = [e for e in all_evals if e["status"].startswith("FINISHED") or e["status"] == "PENDING_NEW_EVAL"]
63
+ df_pending = pd.DataFrame.from_records(pending_list, columns=cols)
64
+ df_running = pd.DataFrame.from_records(running_list, columns=cols)
65
+ df_finished = pd.DataFrame.from_records(finished_list, columns=cols)
66
+ return df_finished[cols], df_running[cols], df_pending[cols]
src/submission/__pycache__/check_validity.cpython-310.pyc ADDED
Binary file (4.87 kB). View file
 
src/submission/__pycache__/submit.cpython-310.pyc ADDED
Binary file (3.38 kB). View file
 
src/submission/check_validity.py ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ @Project -> File :leaderboard -> check_validity.py
4
+ @Author : Www多金
5
+ @Date :2023/12/12 16:41
6
+ @Desc : study Mechine Learning
7
+ """
8
+ import json
9
+ import os
10
+ import re
11
+ from collections import defaultdict
12
+ from datetime import datetime, timedelta, timezone
13
+
14
+ import huggingface_hub
15
+ from huggingface_hub import ModelCard
16
+ from huggingface_hub.hf_api import ModelInfo
17
+ from transformers import AutoConfig, AutoTokenizer
18
+ from transformers.models.auto.tokenization_auto import tokenizer_class_from_name, get_tokenizer_config
19
+
20
+ from src.envs import HAS_HIGHER_RATE_LIMIT
21
+
22
+
23
+ # ht to @Wauplin, thank you for the snippet!
24
+ # See https://huggingface.co/spaces/HuggingFaceH4/open_llm_leaderboard/discussions/317
25
+ def check_model_card(repo_id: str) -> tuple[bool, str]:
26
+ # Returns operation status, and error message
27
+ try:
28
+ card = ModelCard.load(repo_id)
29
+ except huggingface_hub.utils.EntryNotFoundError:
30
+ return False, "Please add a model card to your model to explain how you trained/fine-tuned it."
31
+
32
+ # Enforce license metadata
33
+ if card.data.license is None:
34
+ if not ("license_name" in card.data and "license_link" in card.data):
35
+ return False, (
36
+ "License not found. Please add a license to your model card using the `license` metadata or a"
37
+ " `license_name`/`license_link` pair."
38
+ )
39
+
40
+ # Enforce card content
41
+ if len(card.text) < 200:
42
+ return False, "Please add a description to your model card, it is too short."
43
+
44
+ return True, ""
45
+
46
+
47
+ def is_model_on_hub(model_name: str, revision: str, token: str = None, trust_remote_code=False, test_tokenizer=False) -> tuple[bool, str]:
48
+ try:
49
+ config = AutoConfig.from_pretrained(model_name, revision=revision, trust_remote_code=trust_remote_code, token=token)
50
+ if test_tokenizer:
51
+ try:
52
+ tk = AutoTokenizer.from_pretrained(model_name, revision=revision, trust_remote_code=trust_remote_code, token=token)
53
+ except ValueError as e:
54
+ return (
55
+ False,
56
+ f"uses a tokenizer which is not in a transformers release: {e}",
57
+ None
58
+ )
59
+ except Exception as e:
60
+ return (False, "'s tokenizer cannot be loaded. Is your tokenizer class in a stable transformers release, and correctly configured?", None)
61
+ return True, None, config
62
+
63
+ except ValueError:
64
+ return (
65
+ False,
66
+ "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.",
67
+ None
68
+ )
69
+
70
+ except Exception as e:
71
+ return False, "was not found on hub!", None
72
+
73
+
74
+ def get_model_size(model_info: ModelInfo, precision: str):
75
+ size_pattern = size_pattern = re.compile(r"(\d\.)?\d+(b|m)")
76
+ try:
77
+ model_size = round(model_info.safetensors["total"] / 1e9, 3)
78
+ except (AttributeError, TypeError ):
79
+ try:
80
+ size_match = re.search(size_pattern, model_info.modelId.lower())
81
+ model_size = size_match.group(0)
82
+ model_size = round(float(model_size[:-1]) if model_size[-1] == "b" else float(model_size[:-1]) / 1e3, 3)
83
+ except AttributeError:
84
+ return 0 # Unknown model sizes are indicated as 0, see NUMERIC_INTERVALS in app.py
85
+
86
+ size_factor = 8 if (precision == "GPTQ" or "gptq" in model_info.modelId.lower()) else 1
87
+ model_size = size_factor * model_size
88
+ return model_size
89
+
90
+ def get_model_arch(model_info: ModelInfo):
91
+ return model_info.config.get("architectures", "Unknown")
92
+
93
+ def user_submission_permission(org_or_user, users_to_submission_dates, rate_limit_period, rate_limit_quota):
94
+ if org_or_user not in users_to_submission_dates:
95
+ return True, ""
96
+ submission_dates = sorted(users_to_submission_dates[org_or_user])
97
+
98
+ time_limit = (datetime.now(timezone.utc) - timedelta(days=rate_limit_period)).strftime("%Y-%m-%dT%H:%M:%SZ")
99
+ submissions_after_timelimit = [d for d in submission_dates if d > time_limit]
100
+
101
+ num_models_submitted_in_period = len(submissions_after_timelimit)
102
+ if org_or_user in HAS_HIGHER_RATE_LIMIT:
103
+ rate_limit_quota = 2 * rate_limit_quota
104
+
105
+ if num_models_submitted_in_period > rate_limit_quota:
106
+ error_msg = f"Organisation or user `{org_or_user}`"
107
+ error_msg += f"already has {num_models_submitted_in_period} model requests submitted to the leaderboard "
108
+ error_msg += f"in the last {rate_limit_period} days.\n"
109
+ error_msg += (
110
+ "Please wait a couple of days before resubmitting, so that everybody can enjoy using the leaderboard 🤗"
111
+ )
112
+ return False, error_msg
113
+ return True, ""
114
+
115
+
116
+ def already_submitted_models(requested_models_dir: str) -> set[str]:
117
+ depth = 1
118
+ file_names = []
119
+ users_to_submission_dates = defaultdict(list)
120
+
121
+ for root, _, files in os.walk(requested_models_dir):
122
+ current_depth = root.count(os.sep) - requested_models_dir.count(os.sep)
123
+ if current_depth == depth:
124
+ for file in files:
125
+ if not file.endswith(".json"):
126
+ continue
127
+ with open(os.path.join(root, file), "r") as f:
128
+ info = json.load(f)
129
+ file_names.append(f"{info['model']}_{info['revision']}_{info['precision']}")
130
+
131
+ # Select organisation
132
+ if info["model"].count("/") == 0 or "submitted_time" not in info:
133
+ continue
134
+ organisation, _ = info["model"].split("/")
135
+ users_to_submission_dates[organisation].append(info["submitted_time"])
136
+
137
+ return set(file_names), users_to_submission_dates
src/submission/submit.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ @Project -> File :leaderboard -> submit.py
4
+ @Author : Www多金
5
+ @Date :2023/12/12 16:50
6
+ @Desc : study Mechine Learning
7
+ """
8
+ import json
9
+ import os
10
+ from datetime import datetime, timezone
11
+
12
+ from src.display.formatting import styled_error, styled_message, styled_warning
13
+ from src.envs import API, EVAL_REQUESTS_PATH, H4_TOKEN, QUEUE_REPO, RATE_LIMIT_PERIOD, RATE_LIMIT_QUOTA
14
+ from src.leaderboard.filter_models import DO_NOT_SUBMIT_MODELS
15
+ from src.submission.check_validity import (
16
+ already_submitted_models,
17
+ check_model_card,
18
+ get_model_size,
19
+ is_model_on_hub,
20
+ user_submission_permission,
21
+ )
22
+
23
+ REQUESTED_MODELS = None
24
+ USERS_TO_SUBMISSION_DATES = None
25
+
26
+ def add_new_eval(
27
+ model: str,
28
+ base_model: str,
29
+ revision: str,
30
+ precision: str,
31
+ private: bool,
32
+ weight_type: str,
33
+ model_type: str,
34
+ ):
35
+ global REQUESTED_MODELS
36
+ global USERS_TO_SUBMISSION_DATES
37
+ if not REQUESTED_MODELS:
38
+ REQUESTED_MODELS, USERS_TO_SUBMISSION_DATES = already_submitted_models(EVAL_REQUESTS_PATH)
39
+
40
+ user_name = ""
41
+ model_path = model
42
+ if "/" in model:
43
+ user_name = model.split("/")[0]
44
+ model_path = model.split("/")[1]
45
+
46
+ precision = precision.split(" ")[0]
47
+ current_time = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
48
+
49
+ if model_type is None or model_type == "":
50
+ return styled_error("Please select a model type.")
51
+
52
+ # Is the user rate limited?
53
+ if user_name != "":
54
+ user_can_submit, error_msg = user_submission_permission(
55
+ user_name, USERS_TO_SUBMISSION_DATES, RATE_LIMIT_PERIOD, RATE_LIMIT_QUOTA
56
+ )
57
+ if not user_can_submit:
58
+ return styled_error(error_msg)
59
+
60
+ # Did the model authors forbid its submission to the leaderboard?
61
+ if model in DO_NOT_SUBMIT_MODELS or base_model in DO_NOT_SUBMIT_MODELS:
62
+ return styled_warning("Model authors have requested that their model be not submitted on the leaderboard.")
63
+
64
+ # Does the model actually exist?
65
+ if revision == "":
66
+ revision = "main"
67
+
68
+ # Is the model on the hub?
69
+ if weight_type in ["Delta", "Adapter"]:
70
+ base_model_on_hub, error, _ = is_model_on_hub(model_name=base_model, revision=revision, token=H4_TOKEN, test_tokenizer=True)
71
+ if not base_model_on_hub:
72
+ return styled_error(f'Base model "{base_model}" {error}')
73
+
74
+ if not weight_type == "Adapter":
75
+ model_on_hub, error, _ = is_model_on_hub(model_name=model, revision=revision, test_tokenizer=True)
76
+ if not model_on_hub:
77
+ return styled_error(f'Model "{model}" {error}')
78
+
79
+ # Is the model info correctly filled?
80
+ try:
81
+ model_info = API.model_info(repo_id=model, revision=revision)
82
+ except Exception:
83
+ return styled_error("Could not get your model information. Please fill it up properly.")
84
+
85
+ model_size = get_model_size(model_info=model_info, precision=precision)
86
+
87
+ # Were the model card and license filled?
88
+ try:
89
+ license = model_info.cardData["license"]
90
+ except Exception:
91
+ return styled_error("Please select a license for your model")
92
+
93
+ modelcard_OK, error_msg = check_model_card(model)
94
+ if not modelcard_OK:
95
+ return styled_error(error_msg)
96
+
97
+ # Seems good, creating the eval
98
+ print("Adding new eval")
99
+
100
+ eval_entry = {
101
+ "model": model,
102
+ "base_model": base_model,
103
+ "revision": revision,
104
+ "private": private,
105
+ "precision": precision,
106
+ "weight_type": weight_type,
107
+ "status": "PENDING",
108
+ "submitted_time": current_time,
109
+ "model_type": model_type,
110
+ "likes": model_info.likes,
111
+ "params": model_size,
112
+ "license": license,
113
+ }
114
+
115
+ # Check for duplicate submission
116
+ if f"{model}_{revision}_{precision}" in REQUESTED_MODELS:
117
+ return styled_warning("This model has been already submitted.")
118
+
119
+ print("Creating eval file")
120
+ OUT_DIR = f"{EVAL_REQUESTS_PATH}/{user_name}"
121
+ os.makedirs(OUT_DIR, exist_ok=True)
122
+ out_path = f"{OUT_DIR}/{model_path}_eval_request_{private}_{precision}_{weight_type}.json"
123
+
124
+ with open(out_path, "w") as f:
125
+ f.write(json.dumps(eval_entry))
126
+
127
+ print("Uploading eval file")
128
+ API.upload_file(
129
+ path_or_fileobj=out_path,
130
+ path_in_repo=out_path.split("eval-queue/")[1],
131
+ repo_id=QUEUE_REPO,
132
+ repo_type="dataset",
133
+ commit_message=f"Add {model} to eval queue",
134
+ )
135
+
136
+ # Remove the local file
137
+ os.remove(out_path)
138
+
139
+ return styled_message(
140
+ "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."
141
+ )
src/tools/__pycache__/collections.cpython-310.pyc ADDED
Binary file (2.72 kB). View file
 
src/tools/__pycache__/plots.cpython-310.pyc ADDED
Binary file (4.6 kB). View file
 
src/tools/collections.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ @Project -> File :leaderboard -> collections.py
4
+ @Author : Www多金
5
+ @Date :2023/12/12 16:50
6
+ @Desc : study Mechine Learning
7
+ """
8
+ import os
9
+
10
+ import pandas as pd
11
+ from huggingface_hub import add_collection_item, delete_collection_item, get_collection, update_collection_item
12
+ from huggingface_hub.utils._errors import HfHubHTTPError
13
+ from pandas import DataFrame
14
+
15
+ from src.display.utils import AutoEvalColumn, ModelType
16
+ from src.envs import H4_TOKEN, PATH_TO_COLLECTION
17
+
18
+ # Specific intervals for the collections
19
+ intervals = {
20
+ "1B": pd.Interval(0, 1.5, closed="right"),
21
+ "3B": pd.Interval(2.5, 3.5, closed="neither"),
22
+ "7B": pd.Interval(6, 8, closed="neither"),
23
+ "13B": pd.Interval(10, 14, closed="neither"),
24
+ "30B": pd.Interval(25, 35, closed="neither"),
25
+ "65B": pd.Interval(60, 70, closed="neither"),
26
+ }
27
+
28
+
29
+ def update_collections(df: DataFrame):
30
+ """This function updates the Open LLM Leaderboard model collection with the latest best models for
31
+ each size category and type.
32
+ """
33
+ collection = get_collection(collection_slug=PATH_TO_COLLECTION, token=H4_TOKEN)
34
+ params_column = pd.to_numeric(df[AutoEvalColumn.params.name], errors="coerce")
35
+
36
+ cur_best_models = []
37
+
38
+ ix = 0
39
+ for type in ModelType:
40
+ if type.value.name == "":
41
+ continue
42
+ for size in intervals:
43
+ # We filter the df to gather the relevant models
44
+ type_emoji = [t[0] for t in type.value.symbol]
45
+ filtered_df = df[df[AutoEvalColumn.model_type_symbol.name].isin(type_emoji)]
46
+
47
+ numeric_interval = pd.IntervalIndex([intervals[size]])
48
+ mask = params_column.apply(lambda x: any(numeric_interval.contains(x)))
49
+ filtered_df = filtered_df.loc[mask]
50
+
51
+ best_models = list(
52
+ filtered_df.sort_values(AutoEvalColumn.average.name, ascending=False)[AutoEvalColumn.dummy.name]
53
+ )
54
+ print(type.value.symbol, size, best_models[:10])
55
+
56
+ # We add them one by one to the leaderboard
57
+ for model in best_models:
58
+ ix += 1
59
+ cur_len_collection = len(collection.items)
60
+ try:
61
+ collection = add_collection_item(
62
+ PATH_TO_COLLECTION,
63
+ item_id=model,
64
+ item_type="model",
65
+ exists_ok=True,
66
+ note=f"Best {type.to_str(' ')} model of around {size} on the leaderboard today!",
67
+ token=H4_TOKEN,
68
+ )
69
+ if (
70
+ len(collection.items) > cur_len_collection
71
+ ): # we added an item - we make sure its position is correct
72
+ item_object_id = collection.items[-1].item_object_id
73
+ update_collection_item(
74
+ collection_slug=PATH_TO_COLLECTION, item_object_id=item_object_id, position=ix
75
+ )
76
+ cur_len_collection = len(collection.items)
77
+ cur_best_models.append(model)
78
+ break
79
+ except HfHubHTTPError:
80
+ continue
81
+
82
+ collection = get_collection(PATH_TO_COLLECTION, token=H4_TOKEN)
83
+ for item in collection.items:
84
+ if item.item_id not in cur_best_models:
85
+ try:
86
+ delete_collection_item(
87
+ collection_slug=PATH_TO_COLLECTION, item_object_id=item.item_object_id, token=H4_TOKEN
88
+ )
89
+ except HfHubHTTPError:
90
+ continue
src/tools/plots.py ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ @Project -> File :leaderboard -> plots.py
4
+ @Author : Www多金
5
+ @Date :2023/12/12 16:51
6
+ @Desc : study Mechine Learning
7
+ """
8
+ import pandas as pd
9
+ import numpy as np
10
+ import plotly.express as px
11
+ from plotly.graph_objs import Figure
12
+
13
+ from src.leaderboard.filter_models import FLAGGED_MODELS
14
+ from src.display.utils import human_baseline_row as HUMAN_BASELINE, AutoEvalColumn, Tasks, Task, BENCHMARK_COLS
15
+ from src.leaderboard.read_evals import EvalResult
16
+
17
+
18
+
19
+ def create_scores_df(raw_data: list[EvalResult]) -> pd.DataFrame:
20
+ """
21
+ Generates a DataFrame containing the maximum scores until each date.
22
+ :param results_df: A DataFrame containing result information including metric scores and dates.
23
+ :return: A new DataFrame containing the maximum scores until each date for every metric.
24
+ """
25
+ # Step 1: Ensure 'date' is in datetime format and sort the DataFrame by it
26
+ results_df = pd.DataFrame(raw_data)
27
+ #results_df["date"] = pd.to_datetime(results_df["date"], format="mixed", utc=True)
28
+ results_df.sort_values(by="date", inplace=True)
29
+
30
+ # Step 2: Initialize the scores dictionary
31
+ scores = {k: [] for k in BENCHMARK_COLS + [AutoEvalColumn.average.name]}
32
+
33
+ # Step 3: Iterate over the rows of the DataFrame and update the scores dictionary
34
+ for task in [t.value for t in Tasks] + [Task("Average", "avg", AutoEvalColumn.average.name)]:
35
+ current_max = 0
36
+ last_date = ""
37
+ column = task.col_name
38
+ for _, row in results_df.iterrows():
39
+ current_model = row["full_model"]
40
+ if current_model in FLAGGED_MODELS:
41
+ continue
42
+
43
+ current_date = row["date"]
44
+ if task.benchmark == "Average":
45
+ current_score = np.mean(list(row["results"].values()))
46
+ else:
47
+ current_score = row["results"][task.benchmark]
48
+
49
+ if current_score > current_max:
50
+ if current_date == last_date and len(scores[column]) > 0:
51
+ scores[column][-1] = {"model": current_model, "date": current_date, "score": current_score}
52
+ else:
53
+ scores[column].append({"model": current_model, "date": current_date, "score": current_score})
54
+ current_max = current_score
55
+ last_date = current_date
56
+
57
+ # Step 4: Return all dictionaries as DataFrames
58
+ return {k: pd.DataFrame(v) for k, v in scores.items()}
59
+
60
+
61
+ def create_plot_df(scores_df: dict[str: pd.DataFrame]) -> pd.DataFrame:
62
+ """
63
+ Transforms the scores DataFrame into a new format suitable for plotting.
64
+ :param scores_df: A DataFrame containing metric scores and dates.
65
+ :return: A new DataFrame reshaped for plotting purposes.
66
+ """
67
+ # Initialize the list to store DataFrames
68
+ dfs = []
69
+
70
+ # Iterate over the cols and create a new DataFrame for each column
71
+ for col in BENCHMARK_COLS + [AutoEvalColumn.average.name]:
72
+ d = scores_df[col].reset_index(drop=True)
73
+ d["task"] = col
74
+ dfs.append(d)
75
+
76
+ # Concatenate all the created DataFrames
77
+ concat_df = pd.concat(dfs, ignore_index=True)
78
+
79
+ # Sort values by 'date'
80
+ concat_df.sort_values(by="date", inplace=True)
81
+ concat_df.reset_index(drop=True, inplace=True)
82
+ return concat_df
83
+
84
+
85
+ def create_metric_plot_obj(
86
+ df: pd.DataFrame, metrics: list[str], title: str
87
+ ) -> Figure:
88
+ """
89
+ Create a Plotly figure object with lines representing different metrics
90
+ and horizontal dotted lines representing human baselines.
91
+ :param df: The DataFrame containing the metric values, names, and dates.
92
+ :param metrics: A list of strings representing the names of the metrics
93
+ to be included in the plot.
94
+ :param title: A string representing the title of the plot.
95
+ :return: A Plotly figure object with lines representing metrics and
96
+ horizontal dotted lines representing human baselines.
97
+ """
98
+
99
+ # Filter the DataFrame based on the specified metrics
100
+ df = df[df["task"].isin(metrics)]
101
+
102
+ # Filter the human baselines based on the specified metrics
103
+ filtered_human_baselines = {k: v for k, v in HUMAN_BASELINE.items() if k in metrics}
104
+
105
+ # Create a line figure using plotly express with specified markers and custom data
106
+ fig = px.line(
107
+ df,
108
+ x="date",
109
+ y="score",
110
+ color="task",
111
+ markers=True,
112
+ custom_data=["task", "score", "model"],
113
+ title=title,
114
+ )
115
+
116
+ # Update hovertemplate for better hover interaction experience
117
+ fig.update_traces(
118
+ hovertemplate="<br>".join(
119
+ [
120
+ "Model Name: %{customdata[2]}",
121
+ "Metric Name: %{customdata[0]}",
122
+ "Date: %{x}",
123
+ "Metric Value: %{y}",
124
+ ]
125
+ )
126
+ )
127
+
128
+ # Update the range of the y-axis
129
+ fig.update_layout(yaxis_range=[0, 100])
130
+
131
+ # Create a dictionary to hold the color mapping for each metric
132
+ metric_color_mapping = {}
133
+
134
+ # Map each metric name to its color in the figure
135
+ for trace in fig.data:
136
+ metric_color_mapping[trace.name] = trace.line.color
137
+
138
+ # Iterate over filtered human baselines and add horizontal lines to the figure
139
+ for metric, value in filtered_human_baselines.items():
140
+ color = metric_color_mapping.get(metric, "blue") # Retrieve color from mapping; default to blue if not found
141
+ location = "top left" if metric == "HellaSwag" else "bottom left" # Set annotation position
142
+ # Add horizontal line with matched color and positioned annotation
143
+ fig.add_hline(
144
+ y=value,
145
+ line_dash="dot",
146
+ annotation_text=f"{metric} human baseline",
147
+ annotation_position=location,
148
+ annotation_font_size=10,
149
+ annotation_font_color=color,
150
+ line_color=color,
151
+ )
152
+
153
+ return fig
154
+
155
+
156
+ # Example Usage:
157
+ # human_baselines dictionary is defined.
158
+ # chart = create_metric_plot_obj(scores_df, ["ARC", "HellaSwag", "MMLU", "TruthfulQA"], human_baselines, "Graph Title")