chivier commited on
Commit
e6c97c0
1 Parent(s): bb32fa1

sync from github

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. backend-cli.py +1 -0
  2. open-moe-llm-leaderboard-gh/.gitignore +0 -166
  3. open-moe-llm-leaderboard-gh/Dockerfile +0 -8
  4. open-moe-llm-leaderboard-gh/Makefile +0 -13
  5. open-moe-llm-leaderboard-gh/README.md +0 -85
  6. open-moe-llm-leaderboard-gh/app.py +0 -495
  7. open-moe-llm-leaderboard-gh/backend-cli.py +0 -539
  8. open-moe-llm-leaderboard-gh/cli/analysis-cli.py +0 -353
  9. open-moe-llm-leaderboard-gh/cli/averitec-upload-cli.py +0 -14
  10. open-moe-llm-leaderboard-gh/cli/beta-cli.py +0 -77
  11. open-moe-llm-leaderboard-gh/cli/completed-cli.py +0 -136
  12. open-moe-llm-leaderboard-gh/cli/create_request_file.py +0 -107
  13. open-moe-llm-leaderboard-gh/cli/eval-cli.py +0 -96
  14. open-moe-llm-leaderboard-gh/cli/fever-upload-cli.py +0 -70
  15. open-moe-llm-leaderboard-gh/cli/fix-requests-cli.py +0 -54
  16. open-moe-llm-leaderboard-gh/cli/halueval-upload-cli.py +0 -72
  17. open-moe-llm-leaderboard-gh/cli/isp-upload-cli.py +0 -20
  18. open-moe-llm-leaderboard-gh/cli/nqswap-upload-cli.py +0 -8
  19. open-moe-llm-leaderboard-gh/cli/shroom-upload-cli.py +0 -34
  20. open-moe-llm-leaderboard-gh/cli/submit-cli.py +0 -194
  21. open-moe-llm-leaderboard-gh/cli/sync-open-llm-cli.py +0 -109
  22. open-moe-llm-leaderboard-gh/cli/truefalse-upload-cli.py +0 -15
  23. open-moe-llm-leaderboard-gh/pyproject.toml +0 -13
  24. open-moe-llm-leaderboard-gh/requirements.txt +0 -34
  25. open-moe-llm-leaderboard-gh/snippets/xsum.yaml +0 -49
  26. open-moe-llm-leaderboard-gh/src/backend/envs.py +0 -68
  27. open-moe-llm-leaderboard-gh/src/backend/hflm_with_measurement.py +0 -592
  28. open-moe-llm-leaderboard-gh/src/backend/huggingface_generate_until.py +0 -60
  29. open-moe-llm-leaderboard-gh/src/backend/manage_requests.py +0 -134
  30. open-moe-llm-leaderboard-gh/src/backend/moe_infinity.py +0 -124
  31. open-moe-llm-leaderboard-gh/src/backend/run_eval_suite.py +0 -130
  32. open-moe-llm-leaderboard-gh/src/backend/sort_queue.py +0 -28
  33. open-moe-llm-leaderboard-gh/src/backend/tasks/__init__.py +0 -7
  34. open-moe-llm-leaderboard-gh/src/backend/tasks/cnndm/README.md +0 -54
  35. open-moe-llm-leaderboard-gh/src/backend/tasks/cnndm/cnndm.yaml +0 -2
  36. open-moe-llm-leaderboard-gh/src/backend/tasks/cnndm/cnndm_v2.yaml +0 -2
  37. open-moe-llm-leaderboard-gh/src/backend/tasks/cnndm/task.py +0 -218
  38. open-moe-llm-leaderboard-gh/src/backend/tasks/cnndm/task_v2.py +0 -231
  39. open-moe-llm-leaderboard-gh/src/backend/tasks/faithdial/faithdial.yaml +0 -14
  40. open-moe-llm-leaderboard-gh/src/backend/tasks/faithdial/faithdial_v2.yaml +0 -14
  41. open-moe-llm-leaderboard-gh/src/backend/tasks/faithdial/utils.py +0 -20
  42. open-moe-llm-leaderboard-gh/src/backend/tasks/fever/fever10.yaml +0 -16
  43. open-moe-llm-leaderboard-gh/src/backend/tasks/fever/fever11.yaml +0 -16
  44. open-moe-llm-leaderboard-gh/src/backend/tasks/gsm8k/gsm8k-custom.yaml +0 -47
  45. open-moe-llm-leaderboard-gh/src/backend/tasks/halueval/halueval_dialogue.yaml +0 -29
  46. open-moe-llm-leaderboard-gh/src/backend/tasks/halueval/halueval_qa.yaml +0 -29
  47. open-moe-llm-leaderboard-gh/src/backend/tasks/halueval/halueval_summarization.yaml +0 -29
  48. open-moe-llm-leaderboard-gh/src/backend/tasks/halueval/utils.py +0 -154
  49. open-moe-llm-leaderboard-gh/src/backend/tasks/measurement_task_utils.py +0 -69
  50. open-moe-llm-leaderboard-gh/src/backend/tasks/memo-trap/memo-trap.yaml +0 -19
backend-cli.py CHANGED
@@ -473,6 +473,7 @@ if __name__ == "__main__":
473
  precisions = args.precision.split(",")
474
  print(f"debug_model_names: {debug_model_names}, debug_task_name: {debug_task_name}, precisions: {precisions}")
475
  task_lst = TASKS_HARNESS.copy()
 
476
  for precision in precisions:
477
  for debug_model_name in debug_model_names:
478
  for task in task_lst:
 
473
  precisions = args.precision.split(",")
474
  print(f"debug_model_names: {debug_model_names}, debug_task_name: {debug_task_name}, precisions: {precisions}")
475
  task_lst = TASKS_HARNESS.copy()
476
+ RESULTS_REPO = DEBUG_RESULTS_REPO
477
  for precision in precisions:
478
  for debug_model_name in debug_model_names:
479
  for task in task_lst:
open-moe-llm-leaderboard-gh/.gitignore DELETED
@@ -1,166 +0,0 @@
1
- # LM eval
2
- eval-queue-bk/
3
- eval-results-bk/
4
- eval-queue/
5
- eval-results/
6
-
7
- # Byte-compiled / optimized / DLL files
8
- __pycache__/
9
- *.py[cod]
10
- *$py.class
11
-
12
- # C extensions
13
- *.so
14
-
15
- # Distribution / packaging
16
- .Python
17
- build/
18
- develop-eggs/
19
- dist/
20
- downloads/
21
- eggs/
22
- .eggs/
23
- lib/
24
- lib64/
25
- parts/
26
- sdist/
27
- var/
28
- wheels/
29
- share/python-wheels/
30
- *.egg-info/
31
- .installed.cfg
32
- *.egg
33
- MANIFEST
34
-
35
- # PyInstaller
36
- # Usually these files are written by a python script from a template
37
- # before PyInstaller builds the exe, so as to inject date/other infos into it.
38
- *.manifest
39
- *.spec
40
-
41
- # Installer logs
42
- pip-log.txt
43
- pip-delete-this-directory.txt
44
-
45
- # Unit test / coverage reports
46
- htmlcov/
47
- .tox/
48
- .nox/
49
- .coverage
50
- .coverage.*
51
- .cache
52
- nosetests.xml
53
- coverage.xml
54
- *.cover
55
- *.py,cover
56
- .hypothesis/
57
- .pytest_cache/
58
- cover/
59
-
60
- # Translations
61
- *.mo
62
- *.pot
63
-
64
- # Django stuff:
65
- *.log
66
- local_settings.py
67
- db.sqlite3
68
- db.sqlite3-journal
69
-
70
- # Flask stuff:
71
- instance/
72
- .webassets-cache
73
-
74
- # Scrapy stuff:
75
- .scrapy
76
-
77
- # Sphinx documentation
78
- docs/_build/
79
-
80
- # PyBuilder
81
- .pybuilder/
82
- target/
83
-
84
- # Jupyter Notebook
85
- .ipynb_checkpoints
86
-
87
- # IPython
88
- profile_default/
89
- ipython_config.py
90
-
91
- # pyenv
92
- # For a library or package, you might want to ignore these files since the code is
93
- # intended to run in multiple environments; otherwise, check them in:
94
- # .python-version
95
-
96
- # pipenv
97
- # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
98
- # However, in case of collaboration, if having platform-specific dependencies or dependencies
99
- # having no cross-platform support, pipenv may install dependencies that don't work, or not
100
- # install all needed dependencies.
101
- #Pipfile.lock
102
-
103
- # poetry
104
- # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
105
- # This is especially recommended for binary packages to ensure reproducibility, and is more
106
- # commonly ignored for libraries.
107
- # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
108
- #poetry.lock
109
-
110
- # pdm
111
- # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
112
- #pdm.lock
113
- # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
114
- # in version control.
115
- # https://pdm.fming.dev/#use-with-ide
116
- .pdm.toml
117
-
118
- # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
119
- __pypackages__/
120
-
121
- # Celery stuff
122
- celerybeat-schedule
123
- celerybeat.pid
124
-
125
- # SageMath parsed files
126
- *.sage.py
127
-
128
- # Environments
129
- .env
130
- .venv
131
- env/
132
- venv/
133
- ENV/
134
- env.bak/
135
- venv.bak/
136
-
137
- # Spyder project settings
138
- .spyderproject
139
- .spyproject
140
-
141
- # Rope project settings
142
- .ropeproject
143
-
144
- # mkdocs documentation
145
- /site
146
-
147
- # mypy
148
- .mypy_cache/
149
- .dmypy.json
150
- dmypy.json
151
-
152
- # Pyre type checker
153
- .pyre/
154
-
155
- # pytype static type analyzer
156
- .pytype/
157
-
158
- # Cython debug symbols
159
- cython_debug/
160
-
161
- # PyCharm
162
- # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
163
- # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
164
- # and can be added to the global gitignore or merged into this file. For a more nuclear
165
- # option (not recommended) you can uncomment the following to ignore the entire idea folder.
166
- #.idea/
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
open-moe-llm-leaderboard-gh/Dockerfile DELETED
@@ -1,8 +0,0 @@
1
- # Use specific python image
2
- FROM registry.hf.space/sparse-generative-ai-open-moe-llm-leaderboard:latest
3
-
4
- RUN pip install -i https://test.pypi.org/simple/ --extra-index-url https://pypi.org/simple/ moe-infinity --no-cache-dir
5
- # To fix pydantic version
6
- RUN pip install pydantic==2.6.4 --no-cache-dir
7
- # To fix selfcheck (selfchatgpt) dataset missing
8
- RUN python -m spacy download en
 
 
 
 
 
 
 
 
 
open-moe-llm-leaderboard-gh/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 .
 
 
 
 
 
 
 
 
 
 
 
 
 
 
open-moe-llm-leaderboard-gh/README.md DELETED
@@ -1,85 +0,0 @@
1
- ---
2
- title: OPEN-MOE-LLM-LEADERBOARD
3
- emoji: 🔥
4
- colorFrom: green
5
- colorTo: indigo
6
- sdk: gradio
7
- sdk_version: 4.9.0
8
- app_file: app.py
9
- pinned: true
10
- license: apache-2.0
11
- fullWidth: true
12
- tags:
13
- - leaderboard
14
- ---
15
-
16
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
17
-
18
- # Contributing to Open-MOE-LLM-Leaderboard
19
-
20
- Thank you for your interest in contributing to the Open-MOE-LLM-Leaderboard project! We welcome contributions from everyone. Below you'll find guidance on how to set up your development environment, understand our architecture, and contribute effectively. If you have any questions or wish to discuss your contributions, please reach out to Yao Fu via email at [[email protected]](mailto:[email protected]).
21
-
22
- ## What We're Looking For in Contributions
23
-
24
- We are looking for contributions in several key areas to enhance the Open-MOE-LLM-Leaderboard project:
25
-
26
- 1. **General Bug Fixes/Reports**: We welcome reports of any bugs found in the frontend interface or backend, as well as fixes for these issues.
27
-
28
- 2. **Adding New Tasks (Benchmark Datasets)**: If you have ideas for new benchmark datasets that could be added, your contributions would be greatly appreciated.
29
-
30
- 3. **Supporting New Inference Frameworks**: Expanding our project to support new inference frameworks is crucial for our growth. If you can contribute in this area, please reach out.
31
-
32
- 4. **Testing More Models**: To make our leaderboard as comprehensive as possible, we need to test a wide range of models. Contributions in this area are highly valuable.
33
-
34
- Documentation is currently of lower priority, but if you have thoughts or suggestions, please feel free to raise them.
35
-
36
- Your contributions are crucial to the success and improvement of the Open-MOE-LLM-Leaderboard project. We look forward to collaborating with you.
37
-
38
-
39
- ## Development Setup
40
-
41
- To start contributing, set up your development environment as follows:
42
-
43
- ```bash
44
- conda create -n leaderboard python=3.10
45
- conda activate leaderboard
46
- pip install -r requirements.txt
47
- pip install -i https://test.pypi.org/simple/ --extra-index-url https://pypi.org/simple/ moe-infinity
48
- pip install pydantic==2.6.4 # Resolves a dependency conflict with moe-infinity
49
- python -m spacy download en # Required for selfcheckgpt
50
- ```
51
-
52
- ## Architecture Overview
53
-
54
- The Open-MOE-LLM-Leaderboard project uses the following architecture:
55
-
56
- - **User Interface (Gradio)** ->upload-> **HuggingFace Dataset (Request)** ->download-> **Backend GPU Server** ->upload-> **HuggingFace Dataset (Result)** ->download-> **User Interface (Gradio)**
57
-
58
- In brief:
59
- 1. Users submit model benchmarking requests through the Gradio interface ([app.py](./app.py)). These requests are then recorded in a HuggingFace dataset ([sparse-generative-ai/requests](https://huggingface.co/datasets/sparse-generative-ai/requests)).
60
- 2. The backend ([backend-cli.py](./backend-cli.py)), running on a GPU server, processes these requests, performs the benchmarking tasks, and uploads the results to another HuggingFace dataset ([sparse-generative-ai/results](https://huggingface.co/datasets/sparse-generative-ai/results)).
61
- 3. Finally, the Gradio interface retrieves and displays these results to the users.
62
-
63
- ## Running the Gradio Interface
64
-
65
- To launch the Gradio interface, execute:
66
-
67
- ```bash
68
- python app.py
69
- ```
70
-
71
- Then, open your browser and navigate to http://127.0.0.1:7860.
72
-
73
- ## Running the Backend
74
-
75
- To start the backend process, use:
76
-
77
- ```bash
78
- python backend-cli.py --debug
79
- ```
80
-
81
- For additional details, please consult the [backend-cli.py](./backend-cli.py) script.
82
-
83
- ---
84
-
85
- We look forward to your contributions and are here to help guide you through the process. Thank you for supporting the Open-MOE-LLM-Leaderboard project!
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
open-moe-llm-leaderboard-gh/app.py DELETED
@@ -1,495 +0,0 @@
1
- #!/usr/bin/env python
2
- import os
3
- import datetime
4
- import socket
5
- import base64
6
- from threading import Thread
7
-
8
- import gradio as gr
9
- import pandas as pd
10
- import time
11
- from apscheduler.schedulers.background import BackgroundScheduler
12
-
13
- from huggingface_hub import snapshot_download
14
-
15
- from src.display.about import (
16
- CITATION_BUTTON_LABEL,
17
- CITATION_BUTTON_TEXT,
18
- EVALUATION_QUEUE_TEXT,
19
- INTRODUCTION_TEXT,
20
- LLM_BENCHMARKS_TEXT,
21
- LLM_BENCHMARKS_DETAILS,
22
- FAQ_TEXT,
23
- TITLE,
24
- ACKNOWLEDGEMENT_TEXT,
25
- )
26
-
27
- from src.display.css_html_js import custom_css
28
-
29
- from src.display.utils import (
30
- BENCHMARK_COLS,
31
- COLS,
32
- EVAL_COLS,
33
- EVAL_TYPES,
34
- TYPES,
35
- AutoEvalColumn,
36
- ModelType,
37
- InferenceFramework,
38
- fields,
39
- WeightType,
40
- Precision,
41
- GPUType
42
- )
43
-
44
- from src.envs import API, EVAL_REQUESTS_PATH, EVAL_RESULTS_PATH, H4_TOKEN, IS_PUBLIC, \
45
- QUEUE_REPO, REPO_ID, RESULTS_REPO, DEBUG_QUEUE_REPO, DEBUG_RESULTS_REPO
46
- from src.populate import get_evaluation_queue_df, get_leaderboard_df
47
- from src.submission.submit import add_new_eval
48
- from src.utils import get_dataset_summary_table
49
-
50
- def get_args():
51
- import argparse
52
-
53
- parser = argparse.ArgumentParser(description="Run the LLM Leaderboard")
54
- parser.add_argument("--debug", action="store_true", help="Run in debug mode")
55
- return parser.parse_args()
56
-
57
- args = get_args()
58
- if args.debug:
59
- print("Running in debug mode")
60
- QUEUE_REPO = DEBUG_QUEUE_REPO
61
- RESULTS_REPO = DEBUG_RESULTS_REPO
62
-
63
- def ui_snapshot_download(repo_id, local_dir, repo_type, tqdm_class, etag_timeout):
64
- try:
65
- print(local_dir)
66
- snapshot_download(
67
- repo_id=repo_id, local_dir=local_dir, repo_type=repo_type, tqdm_class=tqdm_class, etag_timeout=etag_timeout
68
- )
69
- except Exception as e:
70
- restart_space()
71
-
72
-
73
- def restart_space():
74
- API.restart_space(repo_id=REPO_ID, token=H4_TOKEN)
75
-
76
-
77
- def init_space():
78
- dataset_df = get_dataset_summary_table(file_path="blog/Hallucination-Leaderboard-Summary.csv")
79
-
80
- if socket.gethostname() not in {"neuromancer"}:
81
- # sync model_type with open-llm-leaderboard
82
- ui_snapshot_download(
83
- repo_id=QUEUE_REPO, local_dir=EVAL_REQUESTS_PATH, repo_type="dataset", tqdm_class=None, etag_timeout=30
84
- )
85
- ui_snapshot_download(
86
- repo_id=RESULTS_REPO, local_dir=EVAL_RESULTS_PATH, repo_type="dataset", tqdm_class=None, etag_timeout=30
87
- )
88
- raw_data, original_df = get_leaderboard_df(EVAL_RESULTS_PATH, EVAL_REQUESTS_PATH, "", COLS, BENCHMARK_COLS)
89
-
90
- finished_eval_queue_df, running_eval_queue_df, pending_eval_queue_df = get_evaluation_queue_df(
91
- EVAL_REQUESTS_PATH, EVAL_COLS
92
- )
93
- return dataset_df, original_df, finished_eval_queue_df, running_eval_queue_df, pending_eval_queue_df
94
-
95
-
96
- def add_benchmark_columns(shown_columns):
97
- benchmark_columns = []
98
- for benchmark in BENCHMARK_COLS:
99
- if benchmark in shown_columns:
100
- for c in COLS:
101
- if benchmark in c and benchmark != c:
102
- benchmark_columns.append(c)
103
- return benchmark_columns
104
-
105
-
106
- # Searching and filtering
107
- def update_table(
108
- hidden_df: pd.DataFrame, columns: list, type_query: list, precision_query: list, size_query: list, query: str
109
- ):
110
- filtered_df = filter_models(hidden_df, type_query, size_query, precision_query)
111
- filtered_df = filter_queries(query, filtered_df)
112
- benchmark_columns = add_benchmark_columns(columns)
113
- df = select_columns(filtered_df, columns + benchmark_columns)
114
- return df
115
-
116
-
117
- def search_table(df: pd.DataFrame, query: str) -> pd.DataFrame:
118
- return df[(df[AutoEvalColumn.dummy.name].str.contains(query, case=False))]
119
-
120
-
121
- def select_columns(df: pd.DataFrame, columns: list) -> pd.DataFrame:
122
- # always_here_cols = [AutoEvalColumn.model_type_symbol.name, AutoEvalColumn.model.name]
123
-
124
- always_here_cols = [c.name for c in fields(AutoEvalColumn) if c.never_hidden]
125
- dummy_col = [AutoEvalColumn.dummy.name]
126
-
127
- # We use COLS to maintain sorting
128
- filtered_df = df[
129
- # always_here_cols + [c for c in COLS if c in df.columns and c in columns] + [AutoEvalColumn.dummy.name]
130
- always_here_cols
131
- + [c for c in COLS if c in df.columns and c in columns]
132
- + dummy_col
133
- ]
134
- return filtered_df
135
-
136
-
137
- def filter_queries(query: str, filtered_df: pd.DataFrame):
138
- final_df = []
139
- if query != "":
140
- queries = [q.strip() for q in query.split(";")]
141
- for _q in queries:
142
- _q = _q.strip()
143
- if _q != "":
144
- temp_filtered_df = search_table(filtered_df, _q)
145
- if len(temp_filtered_df) > 0:
146
- final_df.append(temp_filtered_df)
147
- if len(final_df) > 0:
148
- filtered_df = pd.concat(final_df)
149
- subset = [AutoEvalColumn.model.name, AutoEvalColumn.precision.name, AutoEvalColumn.revision.name]
150
- filtered_df = filtered_df.drop_duplicates(subset=subset)
151
- return filtered_df
152
-
153
-
154
- def filter_models(df: pd.DataFrame, type_query: list, size_query: list, precision_query: list) -> pd.DataFrame:
155
- # Show all models
156
- filtered_df = df
157
-
158
- type_emoji = [t[0] for t in type_query]
159
- filtered_df = filtered_df.loc[df[AutoEvalColumn.model_type_symbol.name].isin(type_emoji)]
160
- filtered_df = filtered_df.loc[df[AutoEvalColumn.precision.name].isin(precision_query + ["None"])]
161
-
162
- # numeric_interval = pd.IntervalIndex(sorted([NUMERIC_INTERVALS[s] for s in size_query]))
163
- # params_column = pd.to_numeric(df[AutoEvalColumn.params.name], errors="coerce")
164
- # mask = params_column.apply(lambda x: any(numeric_interval.contains(x)))
165
- # filtered_df = filtered_df.loc[mask]
166
-
167
- return filtered_df
168
-
169
- shown_columns = None
170
- dataset_df, original_df, finished_eval_queue_df, running_eval_queue_df, pending_eval_queue_df = init_space()
171
- leaderboard_df = original_df.copy()
172
-
173
- # def update_leaderboard_table():
174
- # global leaderboard_df, shown_columns
175
- # print("Updating leaderboard table")
176
- # return leaderboard_df[
177
- # [c.name for c in fields(AutoEvalColumn) if c.never_hidden]
178
- # + shown_columns.value
179
- # + [AutoEvalColumn.dummy.name]
180
- # ] if not leaderboard_df.empty else leaderboard_df
181
-
182
-
183
- # def update_hidden_leaderboard_table():
184
- # global original_df
185
- # return original_df[COLS] if original_df.empty is False else original_df
186
-
187
- # def update_dataset_table():
188
- # global dataset_df
189
- # return dataset_df
190
-
191
- # def update_finish_table():
192
- # global finished_eval_queue_df
193
- # return finished_eval_queue_df
194
-
195
- # def update_running_table():
196
- # global running_eval_queue_df
197
- # return running_eval_queue_df
198
-
199
- # def update_pending_table():
200
- # global pending_eval_queue_df
201
- # return pending_eval_queue_df
202
-
203
- # def update_finish_num():
204
- # global finished_eval_queue_df
205
- # return len(finished_eval_queue_df)
206
-
207
- # def update_running_num():
208
- # global running_eval_queue_df
209
- # return len(running_eval_queue_df)
210
-
211
- # def update_pending_num():
212
- # global pending_eval_queue_df
213
- # return len(pending_eval_queue_df)
214
-
215
- # triggered only once at startup => read query parameter if it exists
216
- def load_query(request: gr.Request):
217
- query = request.query_params.get("query") or ""
218
- return query
219
-
220
-
221
- def get_image_html(url, image_path):
222
- with open(image_path, "rb") as image_file:
223
- encoded_string = base64.b64encode(image_file.read()).decode()
224
- return f'<a href="{url}" target="_blank"><img src="data:image/jpg;base64,{encoded_string}" alt="NetMind.AI Logo" style="width:100pt;"></a>'
225
-
226
-
227
- # Prepare the HTML content with the image
228
- image_html = get_image_html("https://netmind.ai/home", "./src/display/imgs/Netmind.AI_LOGO.jpg")
229
-
230
-
231
- demo = gr.Blocks(css=custom_css)
232
- with demo:
233
- gr.HTML(TITLE)
234
- gr.Markdown(INTRODUCTION_TEXT, elem_classes="markdown-text")
235
- gr.HTML(ACKNOWLEDGEMENT_TEXT.format(image_html=image_html))
236
-
237
- with gr.Tabs(elem_classes="tab-buttons") as tabs:
238
- with gr.TabItem("open-moe-llm-leaderboard", elem_id="llm-benchmark-tab-table", id=0):
239
- with gr.Row():
240
- with gr.Column():
241
- with gr.Row():
242
- search_bar = gr.Textbox(
243
- placeholder=" 🔍 Model search (separate multiple queries with `;`)",
244
- show_label=False,
245
- elem_id="search-bar"
246
- )
247
- with gr.Row():
248
- shown_columns = gr.CheckboxGroup(
249
- choices=[
250
- c.name
251
- for c in fields(AutoEvalColumn)
252
- if not c.hidden and not c.never_hidden and not c.dummy
253
- ],
254
- value=[
255
- c.name
256
- for c in fields(AutoEvalColumn)
257
- if c.displayed_by_default and not c.hidden and not c.never_hidden
258
- ],
259
- label="Select columns to show",
260
- elem_id="column-select",
261
- interactive=True,
262
- )
263
-
264
- with gr.Column(min_width=320):
265
- filter_columns_size = gr.CheckboxGroup(
266
- label="Inference frameworks",
267
- choices=[t.to_str() for t in InferenceFramework],
268
- value=[t.to_str() for t in InferenceFramework],
269
- interactive=True,
270
- elem_id="filter-columns-size",
271
- )
272
-
273
- filter_columns_type = gr.CheckboxGroup(
274
- label="Model types",
275
- choices=[t.to_str() for t in ModelType],
276
- value=[t.to_str() for t in ModelType],
277
- interactive=True,
278
- elem_id="filter-columns-type",
279
- )
280
-
281
- filter_columns_precision = gr.CheckboxGroup(
282
- label="Precision",
283
- choices=[i.value.name for i in Precision],
284
- value=[i.value.name for i in Precision],
285
- interactive=True,
286
- elem_id="filter-columns-precision",
287
- )
288
-
289
- # filter_columns_size = gr.CheckboxGroup(
290
- # label="Model sizes (in billions of parameters)",
291
- # choices=list(NUMERIC_INTERVALS.keys()),
292
- # value=list(NUMERIC_INTERVALS.keys()),
293
- # interactive=True,
294
- # elem_id="filter-columns-size",
295
- # )
296
-
297
- # breakpoint()
298
- benchmark_columns = add_benchmark_columns(shown_columns.value)
299
- leaderboard_table = gr.components.Dataframe(
300
- value=(
301
- leaderboard_df[
302
- [c.name for c in fields(AutoEvalColumn) if c.never_hidden]
303
- + shown_columns.value
304
- + benchmark_columns
305
- + [AutoEvalColumn.dummy.name]
306
- ]
307
- if leaderboard_df.empty is False
308
- else leaderboard_df
309
- ),
310
- headers=[c.name for c in fields(AutoEvalColumn) if c.never_hidden] + shown_columns.value + benchmark_columns,
311
- datatype=TYPES,
312
- elem_id="leaderboard-table",
313
- interactive=False,
314
- visible=True,
315
- ) # column_widths=["2%", "20%"]
316
-
317
- # Dummy leaderboard for handling the case when the user uses backspace key
318
- hidden_leaderboard_table_for_search = gr.components.Dataframe(
319
- value=original_df[COLS] if original_df.empty is False else original_df,
320
- headers=COLS,
321
- datatype=TYPES,
322
- visible=False,
323
- )
324
-
325
- search_bar.submit(
326
- update_table,
327
- [
328
- hidden_leaderboard_table_for_search,
329
- shown_columns,
330
- filter_columns_type,
331
- filter_columns_precision,
332
- filter_columns_size,
333
- search_bar,
334
- ],
335
- leaderboard_table
336
- )
337
-
338
- # Check query parameter once at startup and update search bar
339
- demo.load(load_query, inputs=[], outputs=[search_bar])
340
-
341
- for selector in [shown_columns, filter_columns_type, filter_columns_precision, filter_columns_size]:
342
- selector.change(
343
- update_table,
344
- [
345
- hidden_leaderboard_table_for_search,
346
- shown_columns,
347
- filter_columns_type,
348
- filter_columns_precision,
349
- filter_columns_size,
350
- search_bar,
351
- ],
352
- leaderboard_table,
353
- queue=True,
354
- )
355
-
356
- with gr.TabItem("About", elem_id="llm-benchmark-tab-table", id=2):
357
- gr.Markdown(LLM_BENCHMARKS_TEXT, elem_classes="markdown-text")
358
-
359
- dataset_table = gr.components.Dataframe(
360
- value=dataset_df,
361
- headers=list(dataset_df.columns),
362
- datatype=["str", "markdown", "str", "str", "str"],
363
- elem_id="dataset-table",
364
- interactive=False,
365
- visible=True,
366
- column_widths=["15%", "20%"],
367
- )
368
-
369
- gr.Markdown(LLM_BENCHMARKS_DETAILS, elem_classes="markdown-text")
370
- gr.Markdown(FAQ_TEXT, elem_classes="markdown-text")
371
-
372
- with gr.TabItem("Submit a model ", elem_id="llm-benchmark-tab-table", id=3):
373
- with gr.Column():
374
- with gr.Row():
375
- gr.Markdown(EVALUATION_QUEUE_TEXT, elem_classes="markdown-text")
376
-
377
- with gr.Column():
378
- with gr.Accordion(f"✅ Finished Evaluations ({len(finished_eval_queue_df)})", open=False):
379
- with gr.Row():
380
- finished_eval_table = gr.components.Dataframe(
381
- value=finished_eval_queue_df, headers=EVAL_COLS, datatype=EVAL_TYPES, row_count=5
382
- )
383
-
384
- with gr.Accordion(f"🔄 Running Evaluation Queue ({len(running_eval_queue_df)})", open=False):
385
- with gr.Row():
386
- running_eval_table = gr.components.Dataframe(
387
- value=running_eval_queue_df, headers=EVAL_COLS, datatype=EVAL_TYPES, row_count=5
388
- )
389
-
390
- with gr.Accordion(f"⏳ Scheduled Evaluation Queue ({len(pending_eval_queue_df)})", open=False):
391
- with gr.Row():
392
- pending_eval_table = gr.components.Dataframe(
393
- value=pending_eval_queue_df, headers=EVAL_COLS, datatype=EVAL_TYPES, row_count=5
394
- )
395
-
396
- with gr.Row():
397
- gr.Markdown("# Submit your model here", elem_classes="markdown-text")
398
-
399
- with gr.Row():
400
- inference_framework = gr.Dropdown(
401
- choices=[t.to_str() for t in InferenceFramework],
402
- label="Inference framework",
403
- multiselect=False,
404
- value=None,
405
- interactive=True,
406
- )
407
-
408
- gpu_type = gr.Dropdown(
409
- choices=[t.to_str() for t in GPUType],
410
- label="GPU type",
411
- multiselect=False,
412
- value="NVIDIA-A100-PCIe-80GB",
413
- interactive=True,
414
- )
415
-
416
-
417
- with gr.Row():
418
- with gr.Column():
419
- model_name_textbox = gr.Textbox(label="Model name")
420
- revision_name_textbox = gr.Textbox(label="Revision commit", placeholder="main")
421
- private = gr.Checkbox(False, label="Private", visible=not IS_PUBLIC)
422
- model_type = gr.Dropdown(
423
- choices=[t.to_str(" : ") for t in ModelType if t != ModelType.Unknown],
424
- label="Model type",
425
- multiselect=False,
426
- value=None,
427
- interactive=True,
428
- )
429
-
430
- with gr.Column():
431
- precision = gr.Dropdown(
432
- choices=[i.value.name for i in Precision if i != Precision.Unknown],
433
- label="Precision",
434
- multiselect=False,
435
- value="float32",
436
- interactive=True,
437
- )
438
-
439
- weight_type = gr.Dropdown(
440
- choices=[i.value.name for i in WeightType],
441
- label="Weights type",
442
- multiselect=False,
443
- value="Original",
444
- interactive=True,
445
- )
446
-
447
- base_model_name_textbox = gr.Textbox(label="Base model (for delta or adapter weights)")
448
-
449
- submit_button = gr.Button("Submit Eval")
450
- submission_result = gr.Markdown()
451
- debug = gr.Checkbox(value=args.debug, label="Debug", visible=False)
452
- submit_button.click(
453
- add_new_eval,
454
- [
455
- model_name_textbox,
456
- base_model_name_textbox,
457
- revision_name_textbox,
458
- precision,
459
- private,
460
- weight_type,
461
- model_type,
462
- inference_framework,
463
- debug,
464
- gpu_type
465
- ],
466
- submission_result,
467
- )
468
-
469
- with gr.Row():
470
- with gr.Accordion("Citing this leaderboard", open=False):
471
- citation_button = gr.Textbox(
472
- value=CITATION_BUTTON_TEXT,
473
- label=CITATION_BUTTON_LABEL,
474
- lines=20,
475
- elem_id="citation-button",
476
- show_copy_button=True,
477
- )
478
-
479
- scheduler = BackgroundScheduler()
480
-
481
- scheduler.add_job(restart_space, "interval", hours=6)
482
-
483
- def launch_backend():
484
- import subprocess
485
- from src.backend.envs import DEVICE
486
-
487
- if DEVICE not in {"cpu"}:
488
- _ = subprocess.run(["python", "backend-cli.py"])
489
-
490
- # Thread(target=periodic_init, daemon=True).start()
491
- # scheduler.add_job(launch_backend, "interval", seconds=120)
492
- if __name__ == "__main__":
493
- scheduler.start()
494
- demo.queue(default_concurrency_limit=40).launch()
495
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
open-moe-llm-leaderboard-gh/backend-cli.py DELETED
@@ -1,539 +0,0 @@
1
- #!/usr/bin/env python
2
-
3
- import os
4
- import json
5
- import argparse
6
-
7
- import socket
8
- import random
9
- import threading
10
- from datetime import datetime
11
-
12
- from src.backend.run_eval_suite import run_evaluation
13
- from src.backend.manage_requests import check_completed_evals, get_eval_requests, set_eval_request
14
- from src.backend.sort_queue import sort_models_by_priority
15
- from src.backend.envs import Tasks, EVAL_REQUESTS_PATH_BACKEND, EVAL_RESULTS_PATH_BACKEND, DEVICE, Task
16
- from src.backend.manage_requests import EvalRequest
17
- from src.leaderboard.read_evals import EvalResult
18
-
19
- from src.envs import QUEUE_REPO, RESULTS_REPO, API, DEBUG_QUEUE_REPO, DEBUG_RESULTS_REPO
20
- from src.utils import my_snapshot_download, analyze_gpu_stats, parse_nvidia_smi, monitor_gpus, get_gpu_details
21
-
22
- from src.leaderboard.read_evals import get_raw_eval_results
23
-
24
- from typing import Optional
25
- import GPUtil
26
- import time
27
-
28
- import pprint
29
- import logging
30
-
31
- from lm_eval.filters.extraction import RegexFilter
32
-
33
-
34
- # Configure the root logger
35
- logging.basicConfig(
36
- format="%(asctime)s,%(msecs)03d %(levelname)-8s [%(filename)s:%(lineno)d] %(message)s",
37
- datefmt="%Y-%m-%d:%H:%M:%S",
38
- level=logging.WARNING,
39
- )
40
-
41
- # Get the 'lm-eval' logger from the third-party library
42
- eval_logger = logging.getLogger("lm-eval")
43
-
44
- # Explicitly set the level for 'lm-eval' logger to WARNING
45
- eval_logger.setLevel(logging.WARNING)
46
-
47
- def tuple_input_decorator(func):
48
- def wrapper(self, resps, docs):
49
- stripped_resps = [[resp_data[0] for resp_data in group] for group in resps]
50
-
51
- filtered_resps = func(self, stripped_resps, docs)
52
-
53
- combined_resps = []
54
- for original_group, new_group in zip(resps, filtered_resps):
55
- combined_group = [(new_resp,) + rest_of_data[1:] for new_resp, rest_of_data in zip(new_group, original_group)]
56
- combined_resps.append(combined_group)
57
-
58
- return combined_resps
59
- return wrapper
60
-
61
-
62
- def my_set_eval_request(api, eval_request, set_to_status, hf_repo, local_dir):
63
- for i in range(10):
64
- try:
65
- set_eval_request(
66
- api=api, eval_request=eval_request, set_to_status=set_to_status, hf_repo=hf_repo, local_dir=local_dir
67
- )
68
- return
69
- except Exception as e:
70
- print(f"Error setting eval request to {set_to_status}: {e}. Retrying in 60 seconds")
71
- time.sleep(60)
72
- return
73
-
74
-
75
- logging.getLogger("openai").setLevel(logging.WARNING)
76
-
77
- logging.basicConfig(level=logging.ERROR)
78
- pp = pprint.PrettyPrinter(width=80)
79
-
80
- PENDING_STATUS = "PENDING"
81
- RUNNING_STATUS = "RUNNING"
82
- FINISHED_STATUS = "FINISHED"
83
- FAILED_STATUS = "FAILED"
84
-
85
- TASKS_HARNESS = [task.value for task in Tasks]
86
-
87
-
88
- my_snapshot_download(
89
- repo_id=RESULTS_REPO, revision="main", local_dir=EVAL_RESULTS_PATH_BACKEND, repo_type="dataset", max_workers=60
90
- )
91
- my_snapshot_download(
92
- repo_id=QUEUE_REPO, revision="main", local_dir=EVAL_REQUESTS_PATH_BACKEND, repo_type="dataset", max_workers=60
93
- )
94
-
95
-
96
- def sanity_checks():
97
- print(f"Device: {DEVICE}")
98
-
99
- # pull the eval dataset from the hub and parse any eval requests
100
- # check completed evals and set them to finished
101
- my_snapshot_download(
102
- repo_id=QUEUE_REPO, revision="main", local_dir=EVAL_REQUESTS_PATH_BACKEND, repo_type="dataset", max_workers=60
103
- )
104
- check_completed_evals(
105
- api=API,
106
- checked_status=RUNNING_STATUS,
107
- completed_status=FINISHED_STATUS,
108
- failed_status=FAILED_STATUS,
109
- hf_repo=QUEUE_REPO,
110
- local_dir=EVAL_REQUESTS_PATH_BACKEND,
111
- hf_repo_results=RESULTS_REPO,
112
- local_dir_results=EVAL_RESULTS_PATH_BACKEND,
113
- )
114
- return
115
-
116
-
117
- def request_to_result_name(request: EvalRequest) -> str:
118
- # Request: EvalRequest(model='meta-llama/Llama-2-13b-hf', private=False, status='FINISHED',
119
- # json_filepath='./eval-queue-bk/meta-llama/Llama-2-13b-hf_eval_request_False_False_False.json',
120
- # weight_type='Original', model_type='pretrained', precision='float32', base_model='', revision='main',
121
- # submitted_time='2023-09-09T10:52:17Z', likes=389, params=13.016, license='?')
122
- #
123
- # EvalResult(eval_name='meta-llama_Llama-2-13b-hf_float32', full_model='meta-llama/Llama-2-13b-hf',
124
- # org='meta-llama', model='Llama-2-13b-hf', revision='main',
125
- # results={'nq_open': 33.739612188365655, 'triviaqa': 74.12505572893447},
126
- # precision=<Precision.float32: ModelDetails(name='float32', symbol='')>,
127
- # model_type=<ModelType.PT: ModelDetails(name='pretrained', symbol='🟢')>,
128
- # weight_type=<WeightType.Original: ModelDetails(name='Original', symbol='')>,
129
- # architecture='LlamaForCausalLM', license='?', likes=389, num_params=13.016, date='2023-09-09T10:52:17Z', still_on_hub=True)
130
- #
131
- org_and_model = request.model.split("/", 1)
132
- if len(org_and_model) == 1:
133
- model = org_and_model[0]
134
- res = f"{model}_{request.precision}"
135
- else:
136
- org = org_and_model[0]
137
- model = org_and_model[1]
138
- res = f"{org}_{model}_{request.precision}"
139
- return res
140
-
141
-
142
- def process_evaluation(task: Task, eval_request: EvalRequest, limit: Optional[int] = None) -> dict:
143
- batch_size = 1
144
- batch_size = eval_request.batch_size
145
-
146
- init_gpu_info = analyze_gpu_stats(parse_nvidia_smi())
147
- # if init_gpu_info['Mem(M)'] > 500:
148
- # assert False, f"This machine is not empty: {init_gpu_info}"
149
- gpu_stats_list = []
150
- stop_event = threading.Event()
151
- monitor_thread = threading.Thread(target=monitor_gpus, args=(stop_event, 5, gpu_stats_list))
152
- monitor_thread.start()
153
-
154
- original_apply = RegexFilter.apply
155
- if task.benchmark in ["gsm8k", "gsm8k_cot", "gsm8k_cot_self_consistency", "gsm8k_custom"]:
156
- RegexFilter.apply = tuple_input_decorator(RegexFilter.apply)
157
- else:
158
- RegexFilter.apply = original_apply
159
-
160
- try:
161
- results = run_evaluation(
162
- eval_request=eval_request,
163
- task_names=[task.benchmark],
164
- num_fewshot=task.num_fewshot,
165
- batch_size=batch_size,
166
- device=DEVICE,
167
- use_cache=None,
168
- limit=limit,
169
- )
170
- except RuntimeError as e:
171
- if "No executable batch size found" in str(e):
172
- batch_size = 1
173
- results = run_evaluation(
174
- eval_request=eval_request,
175
- task_names=[task.benchmark],
176
- num_fewshot=task.num_fewshot,
177
- batch_size=batch_size,
178
- device=DEVICE,
179
- use_cache=None,
180
- limit=limit,
181
- )
182
- else:
183
- raise
184
-
185
- # print("RESULTS", results)
186
- stop_event.set()
187
- monitor_thread.join()
188
- gpu_info = analyze_gpu_stats(gpu_stats_list)
189
- for task_name in results['results'].keys():
190
- for key, value in gpu_info.items():
191
- if "GPU" not in key:
192
- results['results'][task_name][f"{key},none"] = int(value)
193
- else:
194
- results['results'][task_name][f"{key},none"] = value
195
-
196
- results['results'][task_name]['batch_size,none'] = batch_size
197
- results['results'][task_name]['precision,none'] = eval_request.precision
198
- print(f"gpu_stats_list: {gpu_stats_list}")
199
- print("GPU Usage:", gpu_info)
200
-
201
- dumped = json.dumps(results, indent=2, default=lambda o: "<not serializable>")
202
- # print(dumped)
203
-
204
- output_path = os.path.join(
205
- EVAL_RESULTS_PATH_BACKEND, *eval_request.model.split("/"), f"results_{datetime.now()}.json"
206
- )
207
- os.makedirs(os.path.dirname(output_path), exist_ok=True)
208
- with open(output_path, "w") as f:
209
- f.write(dumped)
210
-
211
- my_snapshot_download(
212
- repo_id=RESULTS_REPO, revision="main", local_dir=EVAL_RESULTS_PATH_BACKEND, repo_type="dataset", max_workers=60
213
- )
214
- API.upload_file(
215
- path_or_fileobj=output_path,
216
- path_in_repo=f"{eval_request.model}/results_{datetime.now()}.json",
217
- repo_id=RESULTS_REPO,
218
- repo_type="dataset",
219
- )
220
-
221
- RegexFilter.apply = original_apply
222
- return results
223
-
224
-
225
- def process_finished_requests(thr: int, hard_task_lst: Optional[list[str]] = None) -> bool:
226
- sanity_checks()
227
-
228
- current_finished_status = [FINISHED_STATUS, FAILED_STATUS]
229
-
230
- # Get all eval request that are FINISHED, if you want to run other evals, change this parameter
231
- eval_requests: list[EvalRequest] = get_eval_requests(
232
- job_status=current_finished_status, hf_repo=QUEUE_REPO, local_dir=EVAL_REQUESTS_PATH_BACKEND
233
- )
234
- # Sort the evals by priority (first submitted, first run)
235
- eval_requests: list[EvalRequest] = sort_models_by_priority(api=API, models=eval_requests)
236
-
237
- random.shuffle(eval_requests)
238
-
239
- eval_results: list[EvalResult] = get_raw_eval_results(EVAL_RESULTS_PATH_BACKEND, EVAL_REQUESTS_PATH_BACKEND)
240
-
241
- result_name_to_request = {request_to_result_name(r): r for r in eval_requests}
242
- result_name_to_result = {r.eval_name: r for r in eval_results}
243
-
244
- for eval_request in eval_requests:
245
- if eval_request.likes >= thr:
246
- result_name: str = request_to_result_name(eval_request)
247
-
248
- # Check the corresponding result
249
- eval_result: Optional[EvalResult] = (
250
- result_name_to_result[result_name] if result_name in result_name_to_result else None
251
- )
252
-
253
- # breakpoint()
254
-
255
- task_lst = TASKS_HARNESS.copy()
256
- random.shuffle(task_lst)
257
-
258
- # Iterate over tasks and, if we do not have results for a task, run the relevant evaluations
259
- for task in task_lst:
260
- task_name = task.benchmark
261
-
262
- do_run_task = False
263
- if hard_task_lst is None or any(ss in task_name for ss in hard_task_lst):
264
- do_run_task = True
265
-
266
- if (eval_result is None or task_name not in eval_result.results) and do_run_task:
267
- eval_request: EvalRequest = result_name_to_request[result_name]
268
-
269
- my_snapshot_download(
270
- repo_id=QUEUE_REPO,
271
- revision="main",
272
- local_dir=EVAL_REQUESTS_PATH_BACKEND,
273
- repo_type="dataset",
274
- max_workers=60,
275
- )
276
- my_set_eval_request(
277
- api=API,
278
- eval_request=eval_request,
279
- set_to_status=RUNNING_STATUS,
280
- hf_repo=QUEUE_REPO,
281
- local_dir=EVAL_REQUESTS_PATH_BACKEND,
282
- )
283
-
284
- results = process_evaluation(task, eval_request)
285
-
286
- my_snapshot_download(
287
- repo_id=QUEUE_REPO,
288
- revision="main",
289
- local_dir=EVAL_REQUESTS_PATH_BACKEND,
290
- repo_type="dataset",
291
- max_workers=60,
292
- )
293
- my_set_eval_request(
294
- api=API,
295
- eval_request=eval_request,
296
- set_to_status=FINISHED_STATUS,
297
- hf_repo=QUEUE_REPO,
298
- local_dir=EVAL_REQUESTS_PATH_BACKEND,
299
- )
300
-
301
- return True
302
-
303
- return False
304
-
305
-
306
- def maybe_refresh_results(thr: int, hard_task_lst: Optional[list[str]] = None) -> bool:
307
- sanity_checks()
308
-
309
- current_finished_status = [PENDING_STATUS, FINISHED_STATUS, FAILED_STATUS]
310
-
311
- # Get all eval request that are FINISHED, if you want to run other evals, change this parameter
312
- eval_requests: list[EvalRequest] = get_eval_requests(
313
- job_status=current_finished_status, hf_repo=QUEUE_REPO, local_dir=EVAL_REQUESTS_PATH_BACKEND
314
- )
315
- # Sort the evals by priority (first submitted, first run)
316
- eval_requests: list[EvalRequest] = sort_models_by_priority(api=API, models=eval_requests)
317
-
318
- random.shuffle(eval_requests)
319
-
320
- eval_results: list[EvalResult] = get_raw_eval_results(EVAL_RESULTS_PATH_BACKEND, EVAL_REQUESTS_PATH_BACKEND)
321
-
322
- result_name_to_request = {request_to_result_name(r): r for r in eval_requests}
323
- result_name_to_result = {r.eval_name: r for r in eval_results}
324
-
325
- for eval_request in eval_requests:
326
- if eval_request.likes >= thr:
327
- result_name: str = request_to_result_name(eval_request)
328
-
329
- # Check the corresponding result
330
- eval_result: Optional[EvalResult] = (
331
- result_name_to_result[result_name] if result_name in result_name_to_result else None
332
- )
333
-
334
- task_lst = TASKS_HARNESS.copy()
335
- random.shuffle(task_lst)
336
-
337
- # Iterate over tasks and, if we do not have results for a task, run the relevant evaluations
338
- for task in task_lst:
339
- task_name = task.benchmark
340
-
341
- do_run_task = False
342
- if hard_task_lst is None or any(ss in task_name for ss in hard_task_lst):
343
- do_run_task = True
344
-
345
- task_lst = ["nq", "trivia", "tqa", "self"]
346
- if (
347
- eval_result is None
348
- or do_run_task
349
- or task_name not in eval_result.results
350
- or any(ss in task_name for ss in task_lst)
351
- ):
352
- eval_request: EvalRequest = result_name_to_request[result_name]
353
-
354
- my_snapshot_download(
355
- repo_id=QUEUE_REPO,
356
- revision="main",
357
- local_dir=EVAL_REQUESTS_PATH_BACKEND,
358
- repo_type="dataset",
359
- max_workers=60,
360
- )
361
- my_set_eval_request(
362
- api=API,
363
- eval_request=eval_request,
364
- set_to_status=RUNNING_STATUS,
365
- hf_repo=QUEUE_REPO,
366
- local_dir=EVAL_REQUESTS_PATH_BACKEND,
367
- )
368
-
369
- results = process_evaluation(task, eval_request)
370
-
371
- my_snapshot_download(
372
- repo_id=QUEUE_REPO,
373
- revision="main",
374
- local_dir=EVAL_REQUESTS_PATH_BACKEND,
375
- repo_type="dataset",
376
- max_workers=60,
377
- )
378
- my_set_eval_request(
379
- api=API,
380
- eval_request=eval_request,
381
- set_to_status=FINISHED_STATUS,
382
- hf_repo=QUEUE_REPO,
383
- local_dir=EVAL_REQUESTS_PATH_BACKEND,
384
- )
385
-
386
- return True
387
-
388
- return False
389
-
390
- def process_pending_requests() -> bool:
391
- sanity_checks()
392
- print("Processing pending requests")
393
- current_pending_status = [PENDING_STATUS]
394
-
395
- # Get all eval request that are PENDING, if you want to run other evals, change this parameter
396
- eval_requests = get_eval_requests(
397
- job_status=current_pending_status, hf_repo=QUEUE_REPO, local_dir=EVAL_REQUESTS_PATH_BACKEND
398
- )
399
- # Sort the evals by priority (first submitted, first run)
400
- eval_requests = sort_models_by_priority(api=API, models=eval_requests)
401
-
402
- random.shuffle(eval_requests)
403
-
404
- print(f"Found {len(eval_requests)} {','.join(current_pending_status)} eval requests")
405
-
406
- if len(eval_requests) == 0:
407
- return False
408
-
409
- eval_request = eval_requests[0]
410
- pp.pprint(eval_request)
411
-
412
- gpu_type = eval_request.gpu_type
413
- curr_gpu_type = get_gpu_details()
414
- if gpu_type != curr_gpu_type:
415
- print(f"GPU type mismatch: {gpu_type} vs {curr_gpu_type}")
416
- return False
417
-
418
- my_snapshot_download(
419
- repo_id=QUEUE_REPO, revision="main", local_dir=EVAL_REQUESTS_PATH_BACKEND, repo_type="dataset", max_workers=60
420
- )
421
- my_set_eval_request(
422
- api=API,
423
- eval_request=eval_request,
424
- set_to_status=RUNNING_STATUS,
425
- hf_repo=QUEUE_REPO,
426
- local_dir=EVAL_REQUESTS_PATH_BACKEND,
427
- )
428
-
429
- task_lst = TASKS_HARNESS.copy()
430
- random.shuffle(task_lst)
431
-
432
- for task in task_lst:
433
- results = process_evaluation(task, eval_request)
434
-
435
- my_snapshot_download(
436
- repo_id=QUEUE_REPO, revision="main", local_dir=EVAL_REQUESTS_PATH_BACKEND, repo_type="dataset", max_workers=60
437
- )
438
- my_set_eval_request(
439
- api=API,
440
- eval_request=eval_request,
441
- set_to_status=FINISHED_STATUS,
442
- hf_repo=QUEUE_REPO,
443
- local_dir=EVAL_REQUESTS_PATH_BACKEND,
444
- )
445
-
446
- return True
447
-
448
-
449
- def get_args():
450
- parser = argparse.ArgumentParser(description="Run the backend")
451
- parser.add_argument("--debug", action="store_true", help="Run in debug mode")
452
- # debug parameters
453
- parser.add_argument("--task", type=str, default="selfcheckgpt,mmlu, gsm8k", help="Task to debug")
454
- parser.add_argument("--model", type=str, default="mistralai/Mixtral-8x7B-Instruct-v0.1,mistralai/Mixtral-8x7B-v0.1", help="Model to debug")
455
- parser.add_argument("--precision", type=str, default="float32,float16,8bit,4bit", help="Precision to debug")
456
- parser.add_argument("--inference-framework", type=str, default="hf-chat", help="Inference framework to debug")
457
- parser.add_argument("--limit", type=int, default=None, help="Limit for the number of samples")
458
- parser.add_argument("--gpu-type", type=str, default="NVIDIA-A100-PCIe-80GB",
459
- help="GPU type. NVIDIA-A100-PCIe-80GB; NVIDIA-RTX-A5000-24GB; NVIDIA-H100-PCIe-80GB")
460
- parser.add_argument("--debug_repo", action="store_true", help="Use debug repo")
461
- return parser.parse_args()
462
-
463
-
464
- if __name__ == "__main__":
465
- args = get_args()
466
- local_debug = args.debug
467
- # debug specific task by ping
468
- if local_debug and not args.debug_repo:
469
- # debug_model_names = [args.model] # Use model from arguments
470
- # debug_task_name = [args.task] # Use task from arguments
471
- debug_model_names = args.model.split(",")
472
- debug_task_name = args.task.split(",")
473
- precisions = args.precision.split(",")
474
- print(f"debug_model_names: {debug_model_names}, debug_task_name: {debug_task_name}, precisions: {precisions}")
475
- task_lst = TASKS_HARNESS.copy()
476
- RESULTS_REPO = DEBUG_RESULTS_REPO
477
- for precision in precisions:
478
- for debug_model_name in debug_model_names:
479
- for task in task_lst:
480
- task_name = task.benchmark
481
- if task_name not in debug_task_name:
482
- continue
483
- # try:
484
- eval_request = EvalRequest(
485
- model=debug_model_name,
486
- private=False,
487
- status="",
488
- json_filepath="",
489
- precision=precision, # Use precision from arguments
490
- inference_framework=args.inference_framework, # Use inference framework from arguments
491
- gpu_type=args.gpu_type
492
- )
493
- curr_gpu_type = get_gpu_details()
494
- if eval_request.gpu_type != curr_gpu_type:
495
- print(f"GPU type mismatch: {eval_request.gpu_type} vs {curr_gpu_type}")
496
- raise Exception("GPU type mismatch")
497
- results = process_evaluation(task, eval_request, limit=args.limit)
498
- # except Exception as e:
499
- # print(f"debug running error: {e}")
500
- elif local_debug and args.debug_repo:
501
- QUEUE_REPO = DEBUG_QUEUE_REPO
502
- RESULTS_REPO = DEBUG_RESULTS_REPO
503
- while True:
504
- res = False
505
- # if random.randint(0, 10) == 0:
506
- res = process_pending_requests()
507
- print(f"waiting for 60 seconds")
508
- time.sleep(60)
509
- # if res is False:
510
- # if random.randint(0, 5) == 0:
511
- # res = maybe_refresh_results(100)
512
- # else:
513
- # res = process_finished_requests(100)
514
- # time.sleep(60)
515
- # if res is False:
516
- # if random.randint(0, 5) == 0:
517
- # res = maybe_refresh_results(0)
518
- # else:
519
- # res = process_finished_requests(0)
520
- elif not local_debug and not args.debug_repo:
521
- while True:
522
- res = False
523
- # if random.randint(0, 10) == 0:
524
- res = process_pending_requests()
525
- print(f"waiting for 60 seconds")
526
- time.sleep(60)
527
- # if res is False:
528
- # if random.randint(0, 5) == 0:
529
- # res = maybe_refresh_results(100)
530
- # else:
531
- # res = process_finished_requests(100)
532
- # time.sleep(60)
533
- # if res is False:
534
- # if random.randint(0, 5) == 0:
535
- # res = maybe_refresh_results(0)
536
- # else:
537
- # res = process_finished_requests(0)
538
- else:
539
- raise Exception("Cannot use debug_repo without local debug flag")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
open-moe-llm-leaderboard-gh/cli/analysis-cli.py DELETED
@@ -1,353 +0,0 @@
1
- #!/usr/bin/env python3
2
-
3
- import os
4
- import sys
5
- import json
6
- import pickle
7
-
8
- import numpy as np
9
-
10
- import pandas as pd
11
- import seaborn as sns
12
- import matplotlib.pyplot as plt
13
-
14
- from scipy.cluster.hierarchy import linkage
15
-
16
- from src.backend.envs import Tasks, EVAL_REQUESTS_PATH_BACKEND, EVAL_RESULTS_PATH_BACKEND, DEVICE, LIMIT, Task
17
-
18
- from src.envs import QUEUE_REPO, RESULTS_REPO, API
19
- from src.utils import my_snapshot_download
20
-
21
-
22
- def is_float(string):
23
- try:
24
- float(string)
25
- return True
26
- except ValueError:
27
- return False
28
-
29
-
30
- def find_json_files(json_path):
31
- res = []
32
- for root, dirs, files in os.walk(json_path):
33
- for file in files:
34
- if file.endswith(".json"):
35
- res.append(os.path.join(root, file))
36
- return res
37
-
38
-
39
- def sanitise_metric(name: str) -> str:
40
- res = name
41
- res = res.replace("prompt_level_strict_acc", "Prompt-Level Accuracy")
42
- res = res.replace("acc", "Accuracy")
43
- res = res.replace("exact_match", "EM")
44
- res = res.replace("avg-selfcheckgpt", "AVG")
45
- res = res.replace("max-selfcheckgpt", "MAX")
46
- res = res.replace("rouge", "ROUGE-")
47
- res = res.replace("bertscore_precision", "BERT-P")
48
- res = res.replace("exact", "EM")
49
- res = res.replace("HasAns_EM", "HasAns")
50
- res = res.replace("NoAns_EM", "NoAns")
51
- res = res.replace("em", "EM")
52
- return res
53
-
54
-
55
- def sanitise_dataset(name: str) -> str:
56
- res = name
57
- res = res.replace("tqa8", "TriviaQA (8-shot)")
58
- res = res.replace("nq8", "NQ (8-shot)")
59
- res = res.replace("nq_open", "NQ (64-shot)")
60
- res = res.replace("triviaqa", "TriviaQA (64-shot)")
61
- res = res.replace("truthfulqa", "TruthfulQA")
62
- res = res.replace("ifeval", "IFEval")
63
- res = res.replace("selfcheckgpt", "SelfCheckGPT")
64
- res = res.replace("truefalse_cieacf", "True-False")
65
- res = res.replace("mc", "MC")
66
- res = res.replace("race", "RACE")
67
- res = res.replace("squad", "SQuAD")
68
- res = res.replace("memo-trap", "MemoTrap")
69
- res = res.replace("cnndm", "CNN/DM")
70
- res = res.replace("xsum", "XSum")
71
- res = res.replace("qa", "QA")
72
- res = res.replace("summarization", "Summarization")
73
- res = res.replace("dialogue", "Dialog")
74
- res = res.replace("halueval", "HaluEval")
75
- res = res.replace("_v2", "")
76
- res = res.replace("_", " ")
77
- return res
78
-
79
-
80
- cache_file = "data_map_cache.pkl"
81
-
82
-
83
- def load_data_map_from_cache(cache_file):
84
- if os.path.exists(cache_file):
85
- with open(cache_file, "rb") as f:
86
- return pickle.load(f)
87
- else:
88
- return None
89
-
90
-
91
- def save_data_map_to_cache(data_map, cache_file):
92
- with open(cache_file, "wb") as f:
93
- pickle.dump(data_map, f)
94
-
95
-
96
- # Try to load the data_map from the cache file
97
- data_map = load_data_map_from_cache(cache_file)
98
-
99
-
100
- if data_map is None:
101
- my_snapshot_download(
102
- repo_id=RESULTS_REPO, revision="main", local_dir=EVAL_RESULTS_PATH_BACKEND, repo_type="dataset", max_workers=60
103
- )
104
- my_snapshot_download(
105
- repo_id=QUEUE_REPO, revision="main", local_dir=EVAL_REQUESTS_PATH_BACKEND, repo_type="dataset", max_workers=60
106
- )
107
-
108
- result_path_lst = find_json_files(EVAL_RESULTS_PATH_BACKEND)
109
- request_path_lst = find_json_files(EVAL_REQUESTS_PATH_BACKEND)
110
-
111
- model_name_to_model_map = {}
112
-
113
- for path in request_path_lst:
114
- with open(path, "r") as f:
115
- data = json.load(f)
116
- model_name_to_model_map[data["model"]] = data
117
-
118
- model_dataset_metric_to_result_map = {}
119
-
120
- # data_map[model_name][(dataset_name, sanitised_metric_name)] = value
121
- data_map = {}
122
-
123
- for path in result_path_lst:
124
- with open(path, "r") as f:
125
- data = json.load(f)
126
- model_name = data["config"]["model_name"]
127
- for dataset_name, results_dict in data["results"].items():
128
- for metric_name, value in results_dict.items():
129
-
130
- if model_name_to_model_map[model_name]["likes"] > 128:
131
-
132
- to_add = True
133
-
134
- if "f1" in metric_name:
135
- to_add = False
136
-
137
- if "stderr" in metric_name:
138
- to_add = False
139
-
140
- if "memo-trap_v2" in dataset_name:
141
- to_add = False
142
-
143
- if "faithdial" in dataset_name:
144
- to_add = False
145
-
146
- if "truthfulqa_gen" in dataset_name:
147
- to_add = False
148
-
149
- if "bertscore" in metric_name:
150
- if "precision" not in metric_name:
151
- to_add = False
152
-
153
- if "halueval" in dataset_name:
154
- if "acc" not in metric_name:
155
- to_add = False
156
-
157
- if "ifeval" in dataset_name:
158
- if "prompt_level_strict_acc" not in metric_name:
159
- to_add = False
160
-
161
- if "squad" in dataset_name:
162
- # to_add = False
163
- if "best_exact" in metric_name:
164
- to_add = False
165
-
166
- if "fever" in dataset_name:
167
- to_add = False
168
-
169
- if ("xsum" in dataset_name or "cnn" in dataset_name) and "v2" not in dataset_name:
170
- to_add = False
171
-
172
- if isinstance(value, str):
173
- if is_float(value):
174
- value = float(value)
175
- else:
176
- to_add = False
177
-
178
- if to_add:
179
- if "rouge" in metric_name:
180
- value /= 100.0
181
-
182
- if "squad" in dataset_name:
183
- value /= 100.0
184
-
185
- sanitised_metric_name = metric_name
186
- if "," in sanitised_metric_name:
187
- sanitised_metric_name = sanitised_metric_name.split(",")[0]
188
- sanitised_metric_name = sanitise_metric(sanitised_metric_name)
189
- sanitised_dataset_name = sanitise_dataset(dataset_name)
190
-
191
- model_dataset_metric_to_result_map[
192
- (model_name, sanitised_dataset_name, sanitised_metric_name)
193
- ] = value
194
-
195
- if model_name not in data_map:
196
- data_map[model_name] = {}
197
- data_map[model_name][(sanitised_dataset_name, sanitised_metric_name)] = value
198
-
199
- print(
200
- "model_name",
201
- model_name,
202
- "dataset_name",
203
- sanitised_dataset_name,
204
- "metric_name",
205
- sanitised_metric_name,
206
- "value",
207
- value,
208
- )
209
-
210
- save_data_map_to_cache(data_map, cache_file)
211
-
212
- model_name_lst = [m for m in data_map.keys()]
213
-
214
- nb_max_metrics = max(len(data_map[model_name]) for model_name in model_name_lst)
215
-
216
- for model_name in model_name_lst:
217
- if len(data_map[model_name]) < nb_max_metrics - 5:
218
- del data_map[model_name]
219
-
220
- plot_type_lst = ["all", "summ", "qa", "instr", "detect", "rc"]
221
-
222
- for plot_type in plot_type_lst:
223
-
224
- data_map_v2 = {}
225
- for model_name in data_map.keys():
226
- for dataset_metric in data_map[model_name].keys():
227
- if dataset_metric not in data_map_v2:
228
- data_map_v2[dataset_metric] = {}
229
-
230
- if plot_type in {"all"}:
231
- to_add = True
232
- if "ROUGE" in dataset_metric[1] and "ROUGE-L" not in dataset_metric[1]:
233
- to_add = False
234
- if "SQuAD" in dataset_metric[0] and "EM" not in dataset_metric[1]:
235
- to_add = False
236
- if "SelfCheckGPT" in dataset_metric[0] and "MAX" not in dataset_metric[1]:
237
- to_add = False
238
- if "64-shot" in dataset_metric[0]:
239
- to_add = False
240
- if to_add is True:
241
- data_map_v2[dataset_metric][model_name] = data_map[model_name][dataset_metric]
242
- elif plot_type in {"summ"}:
243
- if "CNN" in dataset_metric[0] or "XSum" in dataset_metric[0]:
244
- data_map_v2[dataset_metric][model_name] = data_map[model_name][dataset_metric]
245
- elif plot_type in {"qa"}:
246
- if "TriviaQA" in dataset_metric[0] or "NQ" in dataset_metric[0] or "TruthfulQA" in dataset_metric[0]:
247
- data_map_v2[dataset_metric][model_name] = data_map[model_name][dataset_metric]
248
- elif plot_type in {"instr"}:
249
- if "MemoTrap" in dataset_metric[0] or "IFEval" in dataset_metric[0]:
250
- data_map_v2[dataset_metric][model_name] = data_map[model_name][dataset_metric]
251
- elif plot_type in {"detect"}:
252
- if "HaluEval" in dataset_metric[0] or "SelfCheck" in dataset_metric[0]:
253
- data_map_v2[dataset_metric][model_name] = data_map[model_name][dataset_metric]
254
- elif plot_type in {"rc"}:
255
- if "RACE" in dataset_metric[0] or "SQuAD" in dataset_metric[0]:
256
- data_map_v2[dataset_metric][model_name] = data_map[model_name][dataset_metric]
257
- else:
258
- assert False, f"Unknown plot type: {plot_type}"
259
-
260
- # df = pd.DataFrame.from_dict(data_map, orient='index') # Invert the y-axis (rows)
261
- df = pd.DataFrame.from_dict(data_map_v2, orient="index") # Invert the y-axis (rows)
262
- df.index = [", ".join(map(str, idx)) for idx in df.index]
263
-
264
- o_df = df.copy(deep=True)
265
-
266
- # breakpoint()
267
-
268
- print(df)
269
-
270
- # Check for NaN or infinite values and replace them
271
- df.replace([np.inf, -np.inf], np.nan, inplace=True) # Replace infinities with NaN
272
- df.fillna(0, inplace=True) # Replace NaN with 0 (or use another imputation strategy)
273
-
274
- from sklearn.preprocessing import MinMaxScaler
275
-
276
- # scaler = MinMaxScaler()
277
- # df = pd.DataFrame(scaler.fit_transform(df), index=df.index, columns=df.columns)
278
-
279
- # Calculate dimensions based on the DataFrame size
280
- cell_height = 1.0 # Height of each cell in inches
281
- cell_width = 1.0 # Width of each cell in inches
282
-
283
- n_rows = len(df.index) # Datasets and Metrics
284
- n_cols = len(df.columns) # Models
285
-
286
- # Calculate figure size dynamically
287
- fig_width = cell_width * n_cols + 0
288
- fig_height = cell_height * n_rows + 0
289
-
290
- col_cluster = True
291
- row_cluster = True
292
-
293
- sns.set_context("notebook", font_scale=1.3)
294
-
295
- dendrogram_ratio = (0.1, 0.1)
296
-
297
- if plot_type in {"detect"}:
298
- fig_width = cell_width * n_cols - 2
299
- fig_height = cell_height * n_rows + 5.2
300
- dendrogram_ratio = (0.1, 0.2)
301
-
302
- if plot_type in {"instr"}:
303
- fig_width = cell_width * n_cols - 2
304
- fig_height = cell_height * n_rows + 5.2
305
- dendrogram_ratio = (0.1, 0.4)
306
-
307
- if plot_type in {"qa"}:
308
- fig_width = cell_width * n_cols - 2
309
- fig_height = cell_height * n_rows + 4
310
- dendrogram_ratio = (0.1, 0.2)
311
-
312
- if plot_type in {"summ"}:
313
- fig_width = cell_width * n_cols - 2
314
- fig_height = cell_height * n_rows + 2.0
315
- dendrogram_ratio = (0.1, 0.1)
316
- row_cluster = False
317
-
318
- if plot_type in {"rc"}:
319
- fig_width = cell_width * n_cols - 2
320
- fig_height = cell_height * n_rows + 5.2
321
- dendrogram_ratio = (0.1, 0.4)
322
-
323
- print("figsize", (fig_width, fig_height))
324
-
325
- o_df.to_json(f"plots/clustermap_{plot_type}.json", orient="split")
326
-
327
- print(f"Generating the clustermaps for {plot_type}")
328
-
329
- for cmap in [None, "coolwarm", "viridis"]:
330
- fig = sns.clustermap(
331
- df,
332
- method="ward",
333
- metric="euclidean",
334
- cmap=cmap,
335
- figsize=(fig_width, fig_height), # figsize=(24, 16),
336
- annot=True,
337
- mask=o_df.isnull(),
338
- dendrogram_ratio=dendrogram_ratio,
339
- fmt=".2f",
340
- col_cluster=col_cluster,
341
- row_cluster=row_cluster,
342
- )
343
-
344
- # Adjust the size of the cells (less wide)
345
- plt.setp(fig.ax_heatmap.get_yticklabels(), rotation=0)
346
- plt.setp(fig.ax_heatmap.get_xticklabels(), rotation=90)
347
-
348
- cmap_suffix = "" if cmap is None else f"_{cmap}"
349
-
350
- # Save the clustermap to file
351
- fig.savefig(f"blog/figures/clustermap_{plot_type}{cmap_suffix}.pdf")
352
- fig.savefig(f"blog/figures/clustermap_{plot_type}{cmap_suffix}.png")
353
- fig.savefig(f"blog/figures/clustermap_{plot_type}{cmap_suffix}_t.png", transparent=True, facecolor="none")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
open-moe-llm-leaderboard-gh/cli/averitec-upload-cli.py DELETED
@@ -1,14 +0,0 @@
1
- #!/usr/bin/env python3
2
-
3
- from datasets import load_dataset
4
-
5
- path = "pminervini/averitec"
6
-
7
- ds = load_dataset(
8
- "json",
9
- data_files={
10
- "train": "/Users/pasquale/workspace/AVeriTeC/data/train.json",
11
- "dev": "/Users/pasquale/workspace/AVeriTeC/data/dev.json",
12
- },
13
- )
14
- ds.push_to_hub(path)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
open-moe-llm-leaderboard-gh/cli/beta-cli.py DELETED
@@ -1,77 +0,0 @@
1
- #!/usr/bin/env python
2
-
3
- from huggingface_hub import snapshot_download
4
- from src.leaderboard.read_evals import get_raw_eval_results
5
- from src.envs import API, EVAL_REQUESTS_PATH, EVAL_RESULTS_PATH, QUEUE_REPO, RESULTS_REPO
6
-
7
- from src.backend.run_eval_suite import run_evaluation
8
- from src.backend.manage_requests import check_completed_evals, get_eval_requests, set_eval_request
9
- from src.backend.sort_queue import sort_models_by_priority
10
- from src.backend.envs import Tasks, EVAL_REQUESTS_PATH_BACKEND, EVAL_RESULTS_PATH_BACKEND, DEVICE, LIMIT, Task
11
-
12
- from src.leaderboard.read_evals import get_raw_eval_results
13
-
14
- from src.backend.manage_requests import EvalRequest
15
- from src.leaderboard.read_evals import EvalResult
16
-
17
- snapshot_download(
18
- repo_id=QUEUE_REPO, local_dir=EVAL_REQUESTS_PATH, repo_type="dataset", tqdm_class=None, etag_timeout=30
19
- )
20
- snapshot_download(
21
- repo_id=RESULTS_REPO, local_dir=EVAL_RESULTS_PATH, repo_type="dataset", tqdm_class=None, etag_timeout=30
22
- )
23
-
24
- PENDING_STATUS = "PENDING"
25
- RUNNING_STATUS = "RUNNING"
26
- FINISHED_STATUS = "FINISHED"
27
- FAILED_STATUS = "FAILED"
28
-
29
- TASKS_HARNESS = [task.value for task in Tasks]
30
-
31
- current_finished_status = [FINISHED_STATUS]
32
-
33
-
34
- def request_to_result_name(request: EvalRequest) -> str:
35
- org_and_model = request.model.split("/", 1)
36
- if len(org_and_model) == 1:
37
- model = org_and_model[0]
38
- res = f"{model}_{request.precision}"
39
- else:
40
- org = org_and_model[0]
41
- model = org_and_model[1]
42
- res = f"{org}_{model}_{request.precision}"
43
- return res
44
-
45
-
46
- # Get all eval request that are FINISHED, if you want to run other evals, change this parameter
47
- eval_requests: list[EvalRequest] = get_eval_requests(
48
- job_status=current_finished_status, hf_repo=QUEUE_REPO, local_dir=EVAL_REQUESTS_PATH_BACKEND
49
- )
50
- # Sort the evals by priority (first submitted first run)
51
- eval_requests: list[EvalRequest] = sort_models_by_priority(api=API, models=eval_requests)
52
-
53
- eval_results: list[EvalResult] = get_raw_eval_results(EVAL_RESULTS_PATH, EVAL_REQUESTS_PATH)
54
-
55
- result_name_to_request = {request_to_result_name(r): r for r in eval_requests}
56
- result_name_to_result = {r.eval_name: r for r in eval_results}
57
-
58
- print("Requests", sorted(result_name_to_request.keys()))
59
- print("Results", sorted(result_name_to_result.keys()))
60
-
61
- for eval_request in eval_requests:
62
- result_name: str = request_to_result_name(eval_request)
63
-
64
- # Check the corresponding result
65
- eval_result: EvalResult = result_name_to_result[result_name]
66
-
67
- # Iterate over tasks and, if we do not have results for a task, run the relevant evaluations
68
- for task in TASKS_HARNESS:
69
- task_name = task.benchmark
70
-
71
- if task_name not in eval_result.results:
72
- print("RUN THIS ONE!", result_name, task_name)
73
-
74
- raw_data = get_raw_eval_results(EVAL_RESULTS_PATH, EVAL_REQUESTS_PATH)
75
- all_data_json = [v.to_dict() for v in raw_data if v.is_complete()]
76
-
77
- breakpoint()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
open-moe-llm-leaderboard-gh/cli/completed-cli.py DELETED
@@ -1,136 +0,0 @@
1
- #!/usr/bin/env python
2
-
3
- from huggingface_hub import snapshot_download
4
-
5
- from src.backend.manage_requests import get_eval_requests
6
- from src.backend.sort_queue import sort_models_by_priority
7
- from src.backend.envs import Tasks, EVAL_REQUESTS_PATH_BACKEND, EVAL_RESULTS_PATH_BACKEND
8
-
9
- from src.backend.manage_requests import EvalRequest
10
- from src.leaderboard.read_evals import EvalResult
11
-
12
- from src.envs import QUEUE_REPO, RESULTS_REPO, API
13
-
14
- import logging
15
- import pprint
16
-
17
- logging.getLogger("openai").setLevel(logging.WARNING)
18
-
19
- logging.basicConfig(level=logging.ERROR)
20
- pp = pprint.PrettyPrinter(width=80)
21
-
22
- PENDING_STATUS = "PENDING"
23
- RUNNING_STATUS = "RUNNING"
24
- FINISHED_STATUS = "FINISHED"
25
- FAILED_STATUS = "FAILED"
26
-
27
- TASKS_HARNESS = [task.value for task in Tasks]
28
-
29
- snapshot_download(
30
- repo_id=RESULTS_REPO, revision="main", local_dir=EVAL_RESULTS_PATH_BACKEND, repo_type="dataset", max_workers=60
31
- )
32
- snapshot_download(
33
- repo_id=QUEUE_REPO, revision="main", local_dir=EVAL_REQUESTS_PATH_BACKEND, repo_type="dataset", max_workers=60
34
- )
35
-
36
-
37
- def request_to_result_name(request: EvalRequest) -> str:
38
- org_and_model = request.model.split("/", 1)
39
- if len(org_and_model) == 1:
40
- model = org_and_model[0]
41
- res = f"{model}_{request.precision}"
42
- else:
43
- org = org_and_model[0]
44
- model = org_and_model[1]
45
- res = f"{org}_{model}_{request.precision}"
46
- return res
47
-
48
-
49
- def process_finished_requests() -> bool:
50
- current_finished_status = [FINISHED_STATUS]
51
-
52
- if False:
53
- import os
54
- import dateutil
55
-
56
- model_result_filepaths = []
57
- results_path = f"{EVAL_RESULTS_PATH_BACKEND}/EleutherAI/gpt-neo-1.3B"
58
- requests_path = f"{EVAL_REQUESTS_PATH_BACKEND}/EleutherAI/gpt-neo-1.3B_eval_request_False_False_False.json"
59
-
60
- for root, _, files in os.walk(results_path):
61
- # We should only have json files in model results
62
- if len(files) == 0 or any([not f.endswith(".json") for f in files]):
63
- continue
64
-
65
- # Sort the files by date
66
- try:
67
- files.sort(key=lambda x: x.removesuffix(".json").removeprefix("results_")[:-7])
68
- except dateutil.parser._parser.ParserError:
69
- files = [files[-1]]
70
-
71
- for file in files:
72
- model_result_filepaths.append(os.path.join(root, file))
73
-
74
- eval_results = {}
75
- for model_result_filepath in model_result_filepaths:
76
- # Creation of result
77
- eval_result = EvalResult.init_from_json_file(model_result_filepath)
78
- eval_result.update_with_request_file(requests_path)
79
-
80
- print("XXX", eval_result)
81
-
82
- # Store results of same eval together
83
- eval_name = eval_result.eval_name
84
- if eval_name in eval_results.keys():
85
- eval_results[eval_name].results.update({k: v for k, v in eval_result.results.items() if v is not None})
86
- else:
87
- eval_results[eval_name] = eval_result
88
-
89
- print(eval_results)
90
-
91
- return True
92
-
93
- # Get all eval request that are FINISHED, if you want to run other evals, change this parameter
94
- eval_requests: list[EvalRequest] = get_eval_requests(
95
- job_status=current_finished_status, hf_repo=QUEUE_REPO, local_dir=EVAL_REQUESTS_PATH_BACKEND
96
- )
97
- # Sort the evals by priority (first submitted first run)
98
- eval_requests: list[EvalRequest] = sort_models_by_priority(api=API, models=eval_requests)
99
-
100
- # XXX
101
- # eval_requests = [r for r in eval_requests if 'neo-1.3B' in r.model]
102
-
103
- import random
104
-
105
- random.shuffle(eval_requests)
106
-
107
- from src.leaderboard.read_evals import get_raw_eval_results
108
-
109
- eval_results: list[EvalResult] = get_raw_eval_results(EVAL_RESULTS_PATH_BACKEND, EVAL_REQUESTS_PATH_BACKEND)
110
-
111
- result_name_to_request = {request_to_result_name(r): r for r in eval_requests}
112
- result_name_to_result = {r.eval_name: r for r in eval_results}
113
-
114
- for eval_request in eval_requests:
115
- result_name: str = request_to_result_name(eval_request)
116
-
117
- # Check the corresponding result
118
- from typing import Optional
119
-
120
- eval_result: Optional[EvalResult] = (
121
- result_name_to_result[result_name] if result_name in result_name_to_result else None
122
- )
123
-
124
- # Iterate over tasks and, if we do not have results for a task, run the relevant evaluations
125
- for task in TASKS_HARNESS:
126
- task_name = task.benchmark
127
-
128
- if eval_result is None or task_name not in eval_result.results:
129
- eval_request: EvalRequest = result_name_to_request[result_name]
130
-
131
- # print(eval_result)
132
- print(result_name, "is incomplete -- missing task:", task_name, eval_result, eval_request.likes)
133
-
134
-
135
- if __name__ == "__main__":
136
- res = process_finished_requests()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
open-moe-llm-leaderboard-gh/cli/create_request_file.py DELETED
@@ -1,107 +0,0 @@
1
- import json
2
- import os
3
- import pprint
4
- import re
5
- from datetime import datetime, timezone
6
-
7
- import click
8
- from colorama import Fore
9
- from huggingface_hub import HfApi, snapshot_download
10
-
11
- EVAL_REQUESTS_PATH = "eval-queue"
12
- QUEUE_REPO = "sparse-generative-ai/requests"
13
-
14
- precisions = ("float16", "bfloat16", "8bit (LLM.int8)", "4bit (QLoRA / FP4)", "GPTQ")
15
- model_types = ("pretrained", "fine-tuned", "RL-tuned", "instruction-tuned")
16
- weight_types = ("Original", "Delta", "Adapter")
17
-
18
-
19
- def get_model_size(model_info, precision: str):
20
- size_pattern = size_pattern = re.compile(r"(\d\.)?\d+(b|m)")
21
- try:
22
- model_size = round(model_info.safetensors["total"] / 1e9, 3)
23
- except (AttributeError, TypeError):
24
- try:
25
- size_match = re.search(size_pattern, model_info.modelId.lower())
26
- model_size = size_match.group(0)
27
- model_size = round(float(model_size[:-1]) if model_size[-1] == "b" else float(model_size[:-1]) / 1e3, 3)
28
- except AttributeError:
29
- return 0 # Unknown model sizes are indicated as 0, see NUMERIC_INTERVALS in app.py
30
-
31
- size_factor = 8 if (precision == "GPTQ" or "gptq" in model_info.modelId.lower()) else 1
32
- model_size = size_factor * model_size
33
- return model_size
34
-
35
-
36
- def main():
37
- api = HfApi()
38
- current_time = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
39
- snapshot_download(repo_id=QUEUE_REPO, revision="main", local_dir=EVAL_REQUESTS_PATH, repo_type="dataset")
40
-
41
- model_name = click.prompt("Enter model name")
42
- revision = click.prompt("Enter revision", default="main")
43
- precision = click.prompt("Enter precision", default="float32", type=click.Choice(precisions))
44
- model_type = click.prompt("Enter model type", type=click.Choice(model_types))
45
- weight_type = click.prompt("Enter weight type", default="Original", type=click.Choice(weight_types))
46
- base_model = click.prompt("Enter base model", default="")
47
- status = click.prompt("Enter status", default="FINISHED")
48
-
49
- try:
50
- model_info = api.model_info(repo_id=model_name, revision=revision)
51
- except Exception as e:
52
- print(f"{Fore.RED}Could not find model info for {model_name} on the Hub\n{e}{Fore.RESET}")
53
- return 1
54
-
55
- model_size = get_model_size(model_info=model_info, precision=precision)
56
-
57
- try:
58
- license = model_info.cardData["license"]
59
- except Exception:
60
- license = "?"
61
-
62
- eval_entry = {
63
- "model": model_name,
64
- "base_model": base_model,
65
- "revision": revision,
66
- "private": False,
67
- "precision": precision,
68
- "weight_type": weight_type,
69
- "status": status,
70
- "submitted_time": current_time,
71
- "model_type": model_type,
72
- "likes": model_info.likes,
73
- "params": model_size,
74
- "license": license,
75
- }
76
-
77
- user_name = ""
78
- model_path = model_name
79
- if "/" in model_name:
80
- user_name = model_name.split("/")[0]
81
- model_path = model_name.split("/")[1]
82
-
83
- pprint.pprint(eval_entry)
84
-
85
- if click.confirm("Do you want to continue? This request file will be pushed to the hub"):
86
- click.echo("continuing...")
87
-
88
- out_dir = f"{EVAL_REQUESTS_PATH}/{user_name}"
89
- os.makedirs(out_dir, exist_ok=True)
90
- out_path = f"{out_dir}/{model_path}_eval_request_{False}_{precision}_{weight_type}.json"
91
-
92
- with open(out_path, "w") as f:
93
- f.write(json.dumps(eval_entry))
94
-
95
- api.upload_file(
96
- path_or_fileobj=out_path,
97
- path_in_repo=out_path.split(f"{EVAL_REQUESTS_PATH}/")[1],
98
- repo_id=QUEUE_REPO,
99
- repo_type="dataset",
100
- commit_message=f"Add {model_name} to eval queue",
101
- )
102
- else:
103
- click.echo("aborting...")
104
-
105
-
106
- if __name__ == "__main__":
107
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
open-moe-llm-leaderboard-gh/cli/eval-cli.py DELETED
@@ -1,96 +0,0 @@
1
- #!/usr/bin/env python
2
-
3
- from huggingface_hub import snapshot_download
4
-
5
- from src.backend.envs import EVAL_REQUESTS_PATH_BACKEND
6
- from src.backend.manage_requests import get_eval_requests
7
- from src.backend.manage_requests import EvalRequest
8
- from src.backend.run_eval_suite import run_evaluation
9
-
10
- from src.backend.tasks.xsum.task import XSum
11
- from src.backend.tasks.xsum.task_v2 import XSumv2
12
-
13
- from src.backend.tasks.cnndm.task import CNNDM
14
- from src.backend.tasks.cnndm.task_v2 import CNNDMv2
15
-
16
- from src.backend.tasks.selfcheckgpt.task import SelfCheckGPT
17
-
18
- from lm_eval.tasks import TaskManager
19
- from lm_eval import tasks, evaluator, utils
20
-
21
- from src.backend.envs import Tasks, EVAL_REQUESTS_PATH_BACKEND, EVAL_RESULTS_PATH_BACKEND, DEVICE, LIMIT, Task
22
- from src.envs import QUEUE_REPO
23
-
24
- from lm_eval.models.huggingface import HFLM
25
-
26
-
27
- def main():
28
- # snapshot_download(repo_id=QUEUE_REPO, revision="main", local_dir=EVAL_REQUESTS_PATH_BACKEND, repo_type="dataset", max_workers=60)
29
-
30
- PENDING_STATUS = "PENDING"
31
- RUNNING_STATUS = "RUNNING"
32
- FINISHED_STATUS = "FINISHED"
33
- FAILED_STATUS = "FAILED"
34
-
35
- status = [PENDING_STATUS, RUNNING_STATUS, FINISHED_STATUS, FAILED_STATUS]
36
-
37
- # Get all eval request that are FINISHED, if you want to run other evals, change this parameter
38
- eval_requests: list[EvalRequest] = get_eval_requests(
39
- job_status=status, hf_repo=QUEUE_REPO, local_dir=EVAL_REQUESTS_PATH_BACKEND, do_download=False
40
- )
41
- # eval_request = [r for r in eval_requests if 'bloom-560m' in r.model][0]
42
- eval_request = [r for r in eval_requests if "meta-llama/Llama-2-7b-hf" in r.model][0]
43
-
44
- # my_task = Task("memo-trap", "acc", "memo-trap", 0)
45
- # my_task = Task("selfcheckgpt", "avg-selfcheckgpt", "SGPT", 2)
46
- # my_task = Task("ifeval", "prompt_level_strict_acc", "IFEval", 0)
47
- # my_task = Task("truefalse_cieacf", "acc", "TrueFalse", 5)
48
- # my_task = Task("faithdial_hallu", "acc", "FaithDIAL", 2)
49
-
50
- # my_task = Task("nq_swap", "exact_match", "NQ-Swap", 2)
51
- # my_task = Task("memo-trap_v2", "acc", "XXX", 2)
52
- my_task = Task("xsum_v2", "rougeL", "XXX", 0)
53
- # my_task = Task("squadv2", "exact", "XXX", 0)
54
- # my_task = Task("scrolls_qasper", "f1", "XXX", 0)
55
-
56
- eval_logger = utils.eval_logger
57
- import logging
58
-
59
- eval_logger.setLevel(getattr(logging, "DEBUG"))
60
-
61
- TASKS_HARNESS = [my_task]
62
- # task_names = ['triviaqa']
63
- # TASKS_HARNESS = [task.value for task in Tasks]
64
-
65
- # include_task_folder("src/backend/tasks/")
66
- task_manager = TaskManager(include_path="./src/backend/tasks/")
67
- # task_manager.initialize_tasks(include_path="src/backend/tasks/")
68
-
69
- # breakpoint()
70
-
71
- print(task_manager.all_tasks)
72
-
73
- for task in TASKS_HARNESS:
74
- print(f"Selected Tasks: [{task}]")
75
- import torch
76
-
77
- # breakpoint()
78
- results = evaluator.simple_evaluate(
79
- model="hf",
80
- model_args=eval_request.get_model_args(),
81
- tasks=[task.benchmark],
82
- num_fewshot=task.num_fewshot,
83
- batch_size=1,
84
- device="mps",
85
- use_cache=None,
86
- limit=2,
87
- write_out=True,
88
- task_manager=task_manager,
89
- )
90
- print("AAA", results["results"])
91
-
92
- breakpoint()
93
-
94
-
95
- if __name__ == "__main__":
96
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
open-moe-llm-leaderboard-gh/cli/fever-upload-cli.py DELETED
@@ -1,70 +0,0 @@
1
- #!/usr/bin/env python3
2
-
3
- import glob
4
- import os
5
-
6
- import random
7
- from tqdm import tqdm
8
-
9
- from datasets import Dataset, DatasetDict, load_dataset
10
-
11
-
12
- def convert(list_of_dicts):
13
- res = {}
14
- for d in list_of_dicts:
15
- for k, v in d.items():
16
- res.setdefault(k, []).append(v)
17
- return res
18
-
19
-
20
- v10 = load_dataset("fever", "v1.0")
21
- name_lst = ["train", "labelled_dev"]
22
-
23
- old_to_new_label_map = {"SUPPORTS": "supported", "REFUTES": "refuted"}
24
-
25
- data_map = {}
26
-
27
- for name in name_lst:
28
- instance_lst = []
29
-
30
- for entry in tqdm(v10[name]):
31
- id_ = entry["id"]
32
- label = entry["label"]
33
- claim = entry["claim"]
34
-
35
- evidence_id = entry["evidence_id"]
36
- evidence_wiki_url = entry["evidence_wiki_url"]
37
-
38
- if evidence_id != -1:
39
- assert label in {"SUPPORTS", "REFUTES"}
40
-
41
- instance = {"id": id_, "label": old_to_new_label_map[label], "claim": claim}
42
- instance_lst.append(instance)
43
-
44
- key = "dev" if name in {"labelled_dev"} else name
45
-
46
- instance_lst = sorted([dict(t) for t in {tuple(d.items()) for d in instance_lst}], key=lambda d: d["claim"])
47
-
48
- label_to_instance_lst = {}
49
- for e in instance_lst:
50
- if e["label"] not in label_to_instance_lst:
51
- label_to_instance_lst[e["label"]] = []
52
- label_to_instance_lst[e["label"]].append(e)
53
-
54
- min_len = min(len(v) for k, v in label_to_instance_lst.items())
55
-
56
- new_instance_lst = []
57
- for k in sorted(label_to_instance_lst.keys()):
58
- new_instance_lst += label_to_instance_lst[k][:min_len]
59
-
60
- random.Random(42).shuffle(new_instance_lst)
61
- data_map[key] = new_instance_lst
62
-
63
- ds_path = "pminervini/hl-fever"
64
-
65
- task_to_ds_map = {k: Dataset.from_dict(convert(v)) for k, v in data_map.items()}
66
- ds_dict = DatasetDict(task_to_ds_map)
67
-
68
- ds_dict.push_to_hub(ds_path, "v1.0")
69
-
70
- # breakpoint()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
open-moe-llm-leaderboard-gh/cli/fix-requests-cli.py DELETED
@@ -1,54 +0,0 @@
1
- #!/usr/bin/env python
2
-
3
- import os
4
- import fnmatch
5
-
6
- import json
7
- from huggingface_hub import HfApi
8
-
9
-
10
- def find_json_files(directory):
11
- matches = []
12
- for root, dirnames, filenames in os.walk(directory):
13
- for filename in fnmatch.filter(filenames, "*.json"):
14
- matches.append(os.path.join(root, filename))
15
- return matches
16
-
17
-
18
- directory_path = "/Users/pasquale/workspace/eval/requests"
19
- json_files = find_json_files(directory_path)
20
-
21
- api = HfApi()
22
- model_lst = api.list_models()
23
-
24
- model_lst = [m for m in model_lst]
25
-
26
- id_to_model = {m.id: m for m in model_lst}
27
-
28
- for path in json_files:
29
- with open(path, "r") as fr:
30
- data = json.load(fr)
31
-
32
- model_id = data["model"]
33
- if model_id in id_to_model:
34
- model = id_to_model[model_id]
35
-
36
- to_overwrite = False
37
-
38
- is_finetuned = any(tag.startswith("base_model:") for tag in id_to_model[data["model"]].tags)
39
-
40
- if is_finetuned:
41
- data["model_type"] = "fine-tuned"
42
- to_overwrite = True
43
-
44
- is_instruction_tuned = ("nstruct" in model_id) or ("chat" in model_id)
45
- if is_instruction_tuned:
46
- data["model_type"] = "instruction-tuned"
47
- to_overwrite = True
48
-
49
- if to_overwrite is True:
50
- with open(path, "w") as fw:
51
- json.dump(data, fw)
52
-
53
- else:
54
- print(f"Model {model_id} not found")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
open-moe-llm-leaderboard-gh/cli/halueval-upload-cli.py DELETED
@@ -1,72 +0,0 @@
1
- #!/usr/bin/env python3
2
-
3
- import random
4
- import requests
5
-
6
- from datasets import load_dataset, Dataset, DatasetDict
7
-
8
-
9
- path = "pminervini/HaluEval"
10
-
11
- API_URL = f"https://datasets-server.huggingface.co/splits?dataset={path}"
12
- response = requests.get(API_URL)
13
- res_json = response.json()
14
-
15
- gold_splits = {"dialogue", "qa", "summarization", "general"}
16
-
17
- available_splits = {split["config"] for split in res_json["splits"]} if "splits" in res_json else set()
18
-
19
- name_to_ds = dict()
20
-
21
- for name in gold_splits:
22
- ds = load_dataset("json", data_files={"data": f"data/{name}_data.json"})
23
- name_to_ds[name] = ds
24
- # if name not in available_splits:
25
- ds.push_to_hub(path, config_name=name)
26
-
27
-
28
- def list_to_dict(lst: list) -> dict:
29
- res = dict()
30
- for entry in lst:
31
- for k, v in entry.items():
32
- if k not in res:
33
- res[k] = []
34
- res[k] += [v]
35
- return res
36
-
37
-
38
- for name in gold_splits - {"general"}:
39
- random.seed(42)
40
- ds = name_to_ds[name]
41
- new_entry_lst = []
42
-
43
- for entry in ds["data"]:
44
- is_hallucinated = random.random() > 0.5
45
- new_entry = None
46
- if name in {"qa"}:
47
- new_entry = {
48
- "knowledge": entry["knowledge"],
49
- "question": entry["question"],
50
- "answer": entry[f'{"hallucinated" if is_hallucinated else "right"}_answer'],
51
- "hallucination": "yes" if is_hallucinated else "no",
52
- }
53
- if name in {"dialogue"}:
54
- new_entry = {
55
- "knowledge": entry["knowledge"],
56
- "dialogue_history": entry["dialogue_history"],
57
- "response": entry[f'{"hallucinated" if is_hallucinated else "right"}_response'],
58
- "hallucination": "yes" if is_hallucinated else "no",
59
- }
60
- if name in {"summarization"}:
61
- new_entry = {
62
- "document": entry["document"],
63
- "summary": entry[f'{"hallucinated" if is_hallucinated else "right"}_summary'],
64
- "hallucination": "yes" if is_hallucinated else "no",
65
- }
66
- assert new_entry is not None
67
- new_entry_lst += [new_entry]
68
- new_ds_map = list_to_dict(new_entry_lst)
69
- new_ds = Dataset.from_dict(new_ds_map)
70
- new_dsd = DatasetDict({"data": new_ds})
71
-
72
- new_dsd.push_to_hub(path, config_name=f"{name}_samples")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
open-moe-llm-leaderboard-gh/cli/isp-upload-cli.py DELETED
@@ -1,20 +0,0 @@
1
- #!/usr/bin/env python3
2
-
3
- import glob
4
- import os
5
-
6
- from datasets import load_dataset
7
-
8
- folder_path = "isp-data-json/" # Replace with your folder path
9
-
10
- # Search for all .json files in the folder
11
- json_files = glob.glob(os.path.join(folder_path, "*.jsonl"))
12
-
13
- path = "pminervini/inverse-scaling"
14
-
15
- for json_path in json_files:
16
- base_name = os.path.basename(json_path)
17
- name = base_name.split("_")[0]
18
-
19
- ds = load_dataset("json", data_files={"data": json_path})
20
- ds.push_to_hub(path, config_name=name)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
open-moe-llm-leaderboard-gh/cli/nqswap-upload-cli.py DELETED
@@ -1,8 +0,0 @@
1
- #!/usr/bin/env python3
2
-
3
- from datasets import load_dataset
4
-
5
- path = "pminervini/NQ-Swap"
6
-
7
- ds = load_dataset("json", data_files={"original": "nqswap/original.jsonl", "substituted": "nqswap/substituted.jsonl"})
8
- ds.push_to_hub(path)
 
 
 
 
 
 
 
 
 
open-moe-llm-leaderboard-gh/cli/shroom-upload-cli.py DELETED
@@ -1,34 +0,0 @@
1
- #!/usr/bin/env python3
2
-
3
- import json
4
- from datasets import Dataset, DatasetDict
5
-
6
- file_path = "shroom-data/val.model-agnostic.json"
7
- ds_path = "pminervini/shroom"
8
-
9
- with open(file_path, "r") as file:
10
- data = json.load(file)
11
-
12
-
13
- def convert(list_of_dicts):
14
- dict_of_lists = {}
15
- for d in list_of_dicts:
16
- for key, value in d.items():
17
- dict_of_lists.setdefault(key, []).append(value)
18
- return dict_of_lists
19
-
20
-
21
- task_to_data_map = {}
22
-
23
- for entry in data:
24
- task_name = entry["task"]
25
- del entry["task"]
26
- if task_name not in task_to_data_map:
27
- task_to_data_map[task_name] = []
28
- task_to_data_map[task_name] += [entry]
29
-
30
- task_to_ds_map = {k: Dataset.from_dict(convert(data)) for k, data in task_to_data_map.items()}
31
-
32
- ds_dict = DatasetDict(task_to_ds_map)
33
-
34
- ds_dict.push_to_hub(ds_path)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
open-moe-llm-leaderboard-gh/cli/submit-cli.py DELETED
@@ -1,194 +0,0 @@
1
- #!/usr/bin/env python
2
-
3
- import json
4
- import os
5
- import time
6
-
7
- from datetime import datetime, timezone
8
-
9
- from src.envs import API, EVAL_REQUESTS_PATH, H4_TOKEN, QUEUE_REPO
10
- from src.submission.check_validity import already_submitted_models, get_model_size, is_model_on_hub
11
-
12
- from huggingface_hub import snapshot_download
13
- from src.backend.envs import EVAL_REQUESTS_PATH_BACKEND
14
- from src.backend.manage_requests import get_eval_requests
15
- from src.backend.manage_requests import EvalRequest
16
-
17
-
18
- def add_new_eval(
19
- model: str, base_model: str, revision: str, precision: str, private: bool, weight_type: str, model_type: str
20
- ):
21
- REQUESTED_MODELS, USERS_TO_SUBMISSION_DATES = already_submitted_models(EVAL_REQUESTS_PATH)
22
-
23
- user_name = ""
24
- model_path = model
25
- if "/" in model:
26
- tokens = model.split("/")
27
- user_name = tokens[0]
28
- model_path = tokens[1]
29
-
30
- precision = precision.split(" ")[0]
31
- current_time = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
32
-
33
- if model_type is None or model_type == "":
34
- return print("Please select a model type.")
35
-
36
- # Does the model actually exist?
37
- if revision == "":
38
- revision = "main"
39
-
40
- # Is the model on the hub?
41
- if weight_type in ["Delta", "Adapter"]:
42
- base_model_on_hub, error, _ = is_model_on_hub(
43
- model_name=base_model, revision=revision, token=H4_TOKEN, test_tokenizer=True
44
- )
45
- if not base_model_on_hub:
46
- print(f'Base model "{base_model}" {error}')
47
- return
48
-
49
- if not weight_type == "Adapter":
50
- model_on_hub, error, _ = is_model_on_hub(model_name=model, revision=revision, test_tokenizer=True)
51
- if not model_on_hub:
52
- print(f'Model "{model}" {error}')
53
- return
54
-
55
- # Is the model info correctly filled?
56
- try:
57
- model_info = API.model_info(repo_id=model, revision=revision)
58
- except Exception:
59
- print("Could not get your model information. Please fill it up properly.")
60
- return
61
-
62
- model_size = get_model_size(model_info=model_info, precision=precision)
63
-
64
- license = "none"
65
- try:
66
- license = model_info.cardData["license"]
67
- except Exception:
68
- print("Please select a license for your model")
69
- # return
70
-
71
- # modelcard_OK, error_msg = check_model_card(model)
72
- # if not modelcard_OK:
73
- # print(error_msg)
74
- # return
75
-
76
- # Seems good, creating the eval
77
- print("Adding new eval")
78
-
79
- eval_entry = {
80
- "model": model,
81
- "base_model": base_model,
82
- "revision": revision,
83
- "private": private,
84
- "precision": precision,
85
- "weight_type": weight_type,
86
- "status": "PENDING",
87
- "submitted_time": current_time,
88
- "model_type": model_type,
89
- "likes": model_info.likes,
90
- "params": model_size,
91
- "license": license,
92
- }
93
-
94
- # Check for duplicate submission
95
- if f"{model}_{revision}_{precision}" in REQUESTED_MODELS:
96
- print("This model has been already submitted.")
97
- return
98
-
99
- print("Creating eval file")
100
- OUT_DIR = f"{EVAL_REQUESTS_PATH}/{user_name}"
101
- os.makedirs(OUT_DIR, exist_ok=True)
102
- out_path = f"{OUT_DIR}/{model_path}_eval_request_{private}_{precision}_{weight_type}.json"
103
-
104
- with open(out_path, "w") as f:
105
- f.write(json.dumps(eval_entry))
106
-
107
- print("Uploading eval file")
108
- API.upload_file(
109
- path_or_fileobj=out_path,
110
- path_in_repo=out_path.split("eval-queue/")[1],
111
- repo_id=QUEUE_REPO,
112
- repo_type="dataset",
113
- commit_message=f"Add {model} to eval queue",
114
- )
115
-
116
- # Remove the local file
117
- os.remove(out_path)
118
-
119
- print(
120
- "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."
121
- )
122
- return
123
-
124
-
125
- def main():
126
- from huggingface_hub import HfApi
127
-
128
- api = HfApi()
129
- model_lst = api.list_models()
130
-
131
- model_lst = [m for m in model_lst]
132
-
133
- def custom_filter(m) -> bool:
134
- # res = m.pipeline_tag in {'text-generation'} and 'en' in m.tags and m.private is False
135
- # res = m.pipeline_tag in {'text-generation'} and 'en' in m.tags and m.private is False and 'mistralai/' in m.id
136
- res = "mistralai/" in m.id
137
- return res
138
-
139
- filtered_model_lst = sorted([m for m in model_lst if custom_filter(m)], key=lambda m: m.downloads, reverse=True)
140
-
141
- snapshot_download(
142
- repo_id=QUEUE_REPO, revision="main", local_dir=EVAL_REQUESTS_PATH_BACKEND, repo_type="dataset", max_workers=60
143
- )
144
-
145
- PENDING_STATUS = "PENDING"
146
- RUNNING_STATUS = "RUNNING"
147
- FINISHED_STATUS = "FINISHED"
148
- FAILED_STATUS = "FAILED"
149
-
150
- status = [PENDING_STATUS, RUNNING_STATUS, FINISHED_STATUS, FAILED_STATUS]
151
-
152
- # Get all eval requests
153
- eval_requests: list[EvalRequest] = get_eval_requests(
154
- job_status=status, hf_repo=QUEUE_REPO, local_dir=EVAL_REQUESTS_PATH_BACKEND
155
- )
156
-
157
- requested_model_names = {e.model for e in eval_requests}
158
-
159
- # breakpoint()
160
-
161
- for i in range(min(200, len(filtered_model_lst))):
162
- model = filtered_model_lst[i]
163
-
164
- print(f"Considering {model.id} ..")
165
-
166
- is_finetuned = any(tag.startswith("base_model:") for tag in model.tags)
167
-
168
- model_type = "pretrained"
169
- if is_finetuned:
170
- model_type = "fine-tuned"
171
-
172
- is_instruction_tuned = "nstruct" in model.id
173
- if is_instruction_tuned:
174
- model_type = "instruction-tuned"
175
-
176
- if model.id not in requested_model_names:
177
-
178
- if "mage" not in model.id:
179
- add_new_eval(
180
- model=model.id,
181
- base_model="",
182
- revision="main",
183
- precision="float32",
184
- private=False,
185
- weight_type="Original",
186
- model_type=model_type,
187
- )
188
- time.sleep(10)
189
- else:
190
- print(f"Model {model.id} already added, not adding it to the queue again.")
191
-
192
-
193
- if __name__ == "__main__":
194
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
open-moe-llm-leaderboard-gh/cli/sync-open-llm-cli.py DELETED
@@ -1,109 +0,0 @@
1
- import os
2
- import json
3
- import glob
4
-
5
- from tqdm import tqdm
6
- from huggingface_hub import HfApi, snapshot_download
7
- from src.backend.manage_requests import EvalRequest
8
- from src.backend.envs import EVAL_REQUESTS_PATH_BACKEND_SYNC
9
- from src.envs import QUEUE_REPO, API
10
- from src.envs import EVAL_REQUESTS_PATH_OPEN_LLM, QUEUE_REPO_OPEN_LLM
11
- from src.utils import my_snapshot_download
12
-
13
-
14
- def my_set_eval_request(api, json_filepath, hf_repo, local_dir):
15
- for i in range(10):
16
- try:
17
- set_eval_request(api=api, json_filepath=json_filepath, hf_repo=hf_repo, local_dir=local_dir)
18
- return
19
- except Exception:
20
- time.sleep(60)
21
- return
22
-
23
-
24
- def set_eval_request(api: HfApi, json_filepath: str, hf_repo: str, local_dir: str):
25
- """Updates a given eval request with its new status on the hub (running, completed, failed, ...)"""
26
-
27
- with open(json_filepath) as fp:
28
- data = json.load(fp)
29
-
30
- with open(json_filepath, "w") as f:
31
- f.write(json.dumps(data))
32
-
33
- api.upload_file(
34
- path_or_fileobj=json_filepath,
35
- path_in_repo=json_filepath.replace(local_dir, ""),
36
- repo_id=hf_repo,
37
- repo_type="dataset",
38
- )
39
-
40
-
41
- def get_request_file_for_model(data, requests_path):
42
- model_name = data["model"]
43
- precision = data["precision"]
44
- """Selects the correct request file for a given model. Only keeps runs tagged as FINISHED and RUNNING"""
45
- request_files = os.path.join(
46
- requests_path,
47
- f"{model_name}_eval_request_*.json",
48
- )
49
- request_files = glob.glob(request_files)
50
-
51
- # Select correct request file (precision)
52
- request_file = ""
53
- request_files = sorted(request_files, reverse=True)
54
-
55
- for tmp_request_file in request_files:
56
- with open(tmp_request_file, "r") as f:
57
- req_content = json.load(f)
58
- if req_content["precision"] == precision.split(".")[-1]:
59
- request_file = tmp_request_file
60
- return request_file
61
-
62
-
63
- def update_model_type(data, requests_path):
64
- open_llm_request_file = get_request_file_for_model(data, requests_path)
65
-
66
- try:
67
- with open(open_llm_request_file, "r") as f:
68
- open_llm_request = json.load(f)
69
- data["model_type"] = open_llm_request["model_type"]
70
- return True, data
71
- except:
72
- return False, data
73
-
74
-
75
- def read_and_write_json_files(directory, requests_path_open_llm):
76
- # Walk through the directory
77
- for subdir, dirs, files in tqdm(os.walk(directory), desc="updating model type according to open llm leaderboard"):
78
- for file in files:
79
- # Check if the file is a JSON file
80
- if file.endswith(".json"):
81
- file_path = os.path.join(subdir, file)
82
- # Open and read the JSON file
83
- with open(file_path, "r") as json_file:
84
- data = json.load(json_file)
85
- sucess, data = update_model_type(data, requests_path_open_llm)
86
- if sucess:
87
- with open(file_path, "w") as json_file:
88
- json.dump(data, json_file)
89
- my_set_eval_request(
90
- api=API, json_filepath=file_path, hf_repo=QUEUE_REPO, local_dir=EVAL_REQUESTS_PATH_BACKEND_SYNC
91
- )
92
-
93
-
94
- if __name__ == "__main__":
95
- my_snapshot_download(
96
- repo_id=QUEUE_REPO_OPEN_LLM,
97
- revision="main",
98
- local_dir=EVAL_REQUESTS_PATH_OPEN_LLM,
99
- repo_type="dataset",
100
- max_workers=60,
101
- )
102
- my_snapshot_download(
103
- repo_id=QUEUE_REPO,
104
- revision="main",
105
- local_dir=EVAL_REQUESTS_PATH_BACKEND_SYNC,
106
- repo_type="dataset",
107
- max_workers=60,
108
- )
109
- read_and_write_json_files(EVAL_REQUESTS_PATH_BACKEND_SYNC, EVAL_REQUESTS_PATH_OPEN_LLM)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
open-moe-llm-leaderboard-gh/cli/truefalse-upload-cli.py DELETED
@@ -1,15 +0,0 @@
1
- #!/usr/bin/env python3
2
-
3
- import glob
4
- import os
5
-
6
- from datasets import load_dataset
7
-
8
- path = "pminervini/true-false"
9
- folder_path = "true-false-data/" # Replace with your folder path
10
-
11
- # Search for all .json files in the folder
12
- csv_files = glob.glob(os.path.join(folder_path, "*.csv"))
13
-
14
- ds = load_dataset("csv", data_files={os.path.basename(path).split("_")[0]: path for path in csv_files})
15
- ds.push_to_hub(path)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
open-moe-llm-leaderboard-gh/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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
open-moe-llm-leaderboard-gh/requirements.txt DELETED
@@ -1,34 +0,0 @@
1
- torch
2
- colorama
3
- APScheduler
4
- black
5
- click
6
- datasets
7
- gradio
8
- gradio_client
9
- huggingface-hub
10
- matplotlib
11
- numpy
12
- pandas
13
- plotly
14
- python-dateutil
15
- requests
16
- semantic-version
17
- tqdm
18
- wandb
19
- transformers>=4.36.0
20
- tokenizers>=0.15.0
21
- lm_eval[ifeval] @ git+https://github.com/EleutherAI/[email protected]
22
- accelerate
23
- sentencepiece
24
- langdetect
25
- sacrebleu
26
- cchardet
27
- rouge_score
28
- bert-score
29
- evaluate
30
- spacy==3.7.4
31
- selfcheckgpt
32
- immutabledict
33
- gputil
34
- bitsandbytes
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
open-moe-llm-leaderboard-gh/snippets/xsum.yaml DELETED
@@ -1,49 +0,0 @@
1
- task: xsum
2
- dataset_path: EdinburghNLP/xsum
3
- dataset_name: xsum
4
- output_type: generate_until
5
- training_split: train
6
- validation_split: validation
7
- test_split: test
8
- doc_to_text: "Document: {{document}}\nSummary:"
9
- doc_to_target: "{{summary}}"
10
- # process_docs: !function utils.process_docs
11
- process_results: !function utils.process_results
12
- should_decontaminate: True
13
- doc_to_decontamination_query: document
14
- generation_kwargs:
15
- until:
16
- - "\n"
17
- - "."
18
- do_sample: false
19
- temperature: 0.0
20
- metric_list:
21
- - metric: rouge1_max
22
- aggregation: mean
23
- higher_is_better: true
24
- - metric: rouge1_acc
25
- aggregation: mean
26
- higher_is_better: true
27
- - metric: rouge1_diff
28
- aggregation: mean
29
- higher_is_better: true
30
- - metric: rouge2_max
31
- aggregation: mean
32
- higher_is_better: true
33
- - metric: rouge2_acc
34
- aggregation: mean
35
- higher_is_better: true
36
- - metric: rouge2_diff
37
- aggregation: mean
38
- higher_is_better: true
39
- - metric: rougeL_max
40
- aggregation: mean
41
- higher_is_better: true
42
- - metric: rougeL_acc
43
- aggregation: mean
44
- higher_is_better: true
45
- - metric: rougeL_diff
46
- aggregation: mean
47
- higher_is_better: true
48
- metadata:
49
- - version: 0.0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
open-moe-llm-leaderboard-gh/src/backend/envs.py DELETED
@@ -1,68 +0,0 @@
1
- import os
2
-
3
- import torch
4
-
5
- from dataclasses import dataclass
6
- from enum import Enum
7
-
8
- from src.envs import CACHE_PATH
9
-
10
-
11
- @dataclass
12
- class Task:
13
- benchmark: str
14
- metric: str
15
- col_name: str
16
- num_fewshot: int
17
-
18
-
19
- class Tasks(Enum):
20
- # task0 = Task("nq_open", "em", "NQ Open", 64) # 64, as in the ATLAS paper
21
- # task1 = Task("triviaqa", "em", "TriviaQA", 64) # 64, as in the ATLAS paper
22
-
23
- # task11 = Task("nq8", "em", "NQ Open 8", 8)
24
- # task12 = Task("tqa8", "em", "TriviaQA 8", 8)
25
-
26
- # TruthfulQA is intended as a zero-shot benchmark [5, 47]. https://owainevans.github.io/pdfs/truthfulQA_lin_evans.pdf
27
- # task2 = Task("truthfulqa_gen", "rougeL_acc", "TruthfulQA Gen", 0)
28
- # task3 = Task("truthfulqa_mc1", "acc", "TruthfulQA MC1", 0)
29
- # task4 = Task("truthfulqa_mc2", "acc", "TruthfulQA MC2", 0)
30
-
31
- # task5 = Task("halueval_qa", "acc", "HaluEval QA", 0)
32
- # task6 = Task("halueval_dialogue", "acc", "HaluEval Dialogue", 0)
33
- # task7 = Task("halueval_summarization", "acc", "HaluEval Summarization", 0)
34
-
35
- # task8 = Task("xsum", "rougeL", "XSum", 2)
36
- # task9 = Task("cnndm", "rougeL", "CNN/DM", 2)
37
-
38
- # task8_1 = Task("xsum_v2", "rougeL", "XSum", 0)
39
- # task9_1 = Task("cnndm_v2", "rougeL", "CNN/DM", 0)
40
-
41
- # task10 = Task("memo-trap", "acc", "memo-trap", 0)
42
- # task10_2 = Task("memo-trap_v2", "acc", "memo-trap", 0)
43
-
44
- # task13 = Task("ifeval", "prompt_level_strict_acc", "IFEval", 0)
45
-
46
- task14 = Task("selfcheckgpt", "max-selfcheckgpt", "SelfCheckGPT", 0)
47
-
48
- # task15 = Task("fever10", "acc", "FEVER", 16)
49
- # task15_1 = Task("fever11", "acc", "FEVER", 8)
50
-
51
- # task16 = Task("squadv2", "exact", "SQuADv2", 4)
52
-
53
- # task17 = Task("truefalse_cieacf", "acc", "TrueFalse", 8)
54
-
55
- # task18 = Task("faithdial_hallu", "acc", "FaithDial", 8)
56
- # task19 = Task("faithdial_hallu_v2", "acc", "FaithDial", 8)
57
-
58
- # task20 = Task("race", "acc", "RACE", 0)
59
- task21 = Task("mmlu", "acc", "MMLU", 5)
60
- task22 = Task("gsm8k_custom", "em", "GSM8K", 5)
61
- task23 = Task("gsm8k_cot", "em", "GSM8K", 8)
62
-
63
-
64
- EVAL_REQUESTS_PATH_BACKEND = os.path.join(CACHE_PATH, "eval-queue-bk")
65
- EVAL_REQUESTS_PATH_BACKEND_SYNC = os.path.join(CACHE_PATH, "eval-queue-bk-sync")
66
- EVAL_RESULTS_PATH_BACKEND = os.path.join(CACHE_PATH, "eval-results-bk")
67
-
68
- DEVICE = "cuda:0" if torch.cuda.is_available() else "cpu"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
open-moe-llm-leaderboard-gh/src/backend/hflm_with_measurement.py DELETED
@@ -1,592 +0,0 @@
1
- import copy
2
- import os
3
- from datetime import timedelta
4
- import sys
5
- from time import time
6
- from pathlib import Path
7
- from typing import List, Literal, Optional, Tuple, Union
8
-
9
- import torch
10
- import torch.nn.functional as F
11
- import transformers
12
- from accelerate import (
13
- Accelerator,
14
- DistributedType,
15
- InitProcessGroupKwargs,
16
- find_executable_batch_size,
17
- )
18
- from packaging import version
19
- from peft import PeftModel
20
- from peft import __version__ as PEFT_VERSION
21
- from tqdm import tqdm
22
- from transformers.models.auto.modeling_auto import (
23
- MODEL_FOR_CAUSAL_LM_MAPPING_NAMES,
24
- MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES,
25
- )
26
- from transformers import TextStreamer
27
-
28
- from lm_eval import utils
29
- from lm_eval.api.instance import Instance
30
- from lm_eval.api.model import TemplateLM
31
- from lm_eval.api.registry import register_model
32
- from lm_eval.models.utils import (
33
- Collator,
34
- clear_torch_cache,
35
- get_dtype,
36
- pad_and_concat,
37
- stop_sequences_criteria,
38
- )
39
- from lm_eval.models.huggingface import HFLM
40
- from src.utils import get_gpu_number, get_gpu_details, get_peak_bw, transfer_precision2bytes, get_peak_flops
41
- from src.submission.check_validity import get_model_size
42
- from src.envs import API
43
-
44
-
45
- class StopWatch(TextStreamer):
46
- def __init__(self, *args, **kwargs):
47
- super().__init__(*args, **kwargs)
48
- self.start_prefilling = None
49
- self.prefilling_time = None
50
- self.start_decoding = None
51
- self.decoding_time = None
52
- self.decoding_iterations = 0
53
-
54
- def put(self, value):
55
- if self.start_prefilling is None:
56
- self.start_prefilling = time()
57
- return
58
- elif self.prefilling_time is None:
59
- self.prefilling_time = time() - self.start_prefilling
60
- self.start_decoding = time()
61
- self.decoding_iterations += 1
62
- return
63
-
64
- def end(self):
65
- if self.decoding_time is None and self.start_decoding is not None:
66
- self.decoding_time = time() - self.start_decoding
67
- return
68
-
69
-
70
- class HFLMWithMeasurement(HFLM):
71
- def __init__(self, **kwargs):
72
- super().__init__(**kwargs)
73
- self.pretrained = kwargs.get("pretrained", None)
74
- self.revision = kwargs.get("revision", None)
75
- self.precision = kwargs.get("dtype", None)
76
-
77
- def _loglikelihood_tokens(
78
- self,
79
- requests: List[Tuple[Tuple[str, str], List[int], List[int]]],
80
- disable_tqdm: bool = False,
81
- override_bs: int = None,
82
- ) -> List[Tuple[float, bool]]:
83
- # TODO: implement some kind of efficient-request-middleware that lumps together requests with the same context
84
- res = []
85
-
86
- def _collate(req: Tuple[Tuple[str, str], List[int], List[int]]):
87
- """Defines the key for the sorted method"""
88
- # the negative sign on len(toks) sorts descending - this has a few advantages:
89
- # - time estimates will always be over not underestimates, which is more useful for planning
90
- # - to know the size of a batch when going through the list, you know the first one is always the batch
91
- # padded context length. this is useful to simplify the batching logic and more importantly to make
92
- # automatic adaptive batches much much easier to implement
93
- # - any OOMs will happen right away rather than near the end
94
-
95
- toks = req[1] + req[2]
96
- return -len(toks), tuple(toks)
97
-
98
- def _lookup_one_token_cont(req: Tuple[Tuple[str, str], List[int], List[int]]):
99
- """Defines the key to group and lookup one-token continuations"""
100
- # Use with group_by="contexts" (optional)"
101
- # allows for the creation of a lookup, so we can reuse logits in case of one-token continuations.
102
- # speeds up some multiple-choice tasks proportionally to the number of choices.
103
- # groups requests by context+continuation[:-1] and infer on one request/group.
104
- return req[-2] + req[-1][:-1]
105
-
106
- re_ord = Collator(
107
- requests,
108
- sort_fn=_collate,
109
- group_by="contexts"
110
- if self.AUTO_MODEL_CLASS == transformers.AutoModelForCausalLM
111
- and self.logits_cache
112
- else None,
113
- group_fn=_lookup_one_token_cont,
114
- )
115
-
116
- # automatic (variable) batch size detection for vectorization
117
- # pull longest context sample from request
118
- n_reordered_requests = len(re_ord)
119
- batch_size = (
120
- self.batch_size
121
- if self.batch_size != "auto"
122
- else override_bs
123
- if override_bs is not None
124
- else 0
125
- )
126
- batch_fn = (
127
- self._batch_scheduler
128
- if self.batch_size == "auto"
129
- and n_reordered_requests > 0
130
- and not override_bs
131
- else None
132
- )
133
-
134
- chunks = re_ord.get_batched(n=batch_size, batch_fn=batch_fn)
135
- pbar = tqdm(
136
- total=len(requests),
137
- disable=(disable_tqdm or (self.rank != 0)),
138
- desc="Running loglikelihood requests",
139
- )
140
- for chunk in chunks:
141
- inps = []
142
- cont_toks_list = []
143
- inplens = []
144
-
145
- conts = []
146
- encoder_attns = []
147
-
148
- padding_len_inp = None
149
- padding_len_cont = None
150
- # because vectorizing is annoying, we first convert each (context, continuation) pair to padded
151
- # tensors, then we pack them together into a batch, call the model, and then pick it all apart
152
- # again because vectorizing is annoying
153
-
154
- for _, context_enc, continuation_enc in chunk:
155
- # sanity check
156
- assert len(context_enc) > 0
157
- assert len(continuation_enc) > 0
158
- assert len(continuation_enc) <= self.max_length
159
-
160
- # how this all works (illustrated on a causal decoder-only setup):
161
- # CTX CONT
162
- # inp 0 1 2 3|4 5 6 7 8 9 <- last token is deleted by inp[:, :-1]
163
- # model \ \
164
- # logits 1 2 3|4 5 6 7 8 9 <- the ctx half gets tossed out by the
165
- # cont_toks 4 5 6 7 8 9 [:, -len(continuation_enc):, :self.vocab_size] slice
166
-
167
- # when too long to fit in context, truncate from the left
168
- if self.AUTO_MODEL_CLASS == transformers.AutoModelForCausalLM:
169
- inp = torch.tensor(
170
- (context_enc + continuation_enc)[-(self.max_length + 1) :][:-1],
171
- dtype=torch.long,
172
- device=self.device,
173
- )
174
- (inplen,) = inp.shape
175
- elif self.AUTO_MODEL_CLASS == transformers.AutoModelForSeq2SeqLM:
176
- inp = torch.tensor(
177
- (context_enc)[-self.max_length :],
178
- dtype=torch.long,
179
- device=self.device,
180
- )
181
- (inplen,) = inp.shape
182
-
183
- # build encoder attn masks
184
- encoder_attns.append(torch.ones_like(inp))
185
-
186
- cont = torch.tensor(
187
- (continuation_enc)[-self.max_length :],
188
- # TODO: left-shift these?
189
- # TODO: our code assumes we never end up truncating conts for either model type
190
- dtype=torch.long,
191
- device=self.device,
192
- )
193
- (contlen,) = cont.shape
194
-
195
- conts.append(cont)
196
-
197
- padding_len_cont = (
198
- max(padding_len_cont, contlen)
199
- if padding_len_cont is not None
200
- else contlen
201
- )
202
-
203
- padding_len_inp = (
204
- max(padding_len_inp, inplen)
205
- if padding_len_inp is not None
206
- else inplen
207
- )
208
-
209
- inps.append(inp) # [1, inp_length]
210
- cont_toks_list.append(continuation_enc)
211
- inplens.append(inplen)
212
-
213
- # create encoder attn mask and batched conts, if seq2seq
214
- call_kwargs = {}
215
- if self.AUTO_MODEL_CLASS == transformers.AutoModelForCausalLM:
216
- batched_inps = pad_and_concat(
217
- padding_len_inp, inps, padding_side="right"
218
- ) # [batch, padding_len_inp]
219
- elif self.AUTO_MODEL_CLASS == transformers.AutoModelForSeq2SeqLM:
220
- # TODO: left-pad encoder inps and mask?
221
- batched_inps = pad_and_concat(
222
- padding_len_inp, inps
223
- ) # [batch, padding_len_inp]
224
- batched_conts = pad_and_concat(
225
- padding_len_cont, conts
226
- ) # [batch, padding_len_cont]
227
- batched_encoder_mask = pad_and_concat(
228
- padding_len_inp, encoder_attns
229
- ) # [batch, padding_len_inp]
230
- call_kwargs = {
231
- "attn_mask": batched_encoder_mask,
232
- "labels": batched_conts,
233
- }
234
-
235
- start = time()
236
- intermediate_res = self._model_call(batched_inps, **call_kwargs)
237
- end = time()
238
- multi_logits = F.log_softmax(
239
- intermediate_res , dim=-1
240
- ) # [batch, padding_length (inp or cont), vocab]
241
- per_sample_time = (end - start) / len(multi_logits)
242
-
243
- for (request_str, ctx_tokens, _), logits, inplen, cont_toks in zip(
244
- chunk, multi_logits, inplens, cont_toks_list
245
- ):
246
- # Slice to original seq length
247
- contlen = len(cont_toks)
248
- # take only logits in the continuation
249
- # (discard context toks if decoder-only ; discard right-padding)
250
- # also discards + checks for "virtual tokens" in the causal LM's input window
251
- # from prompt/prefix tuning tokens, if applicable
252
- ctx_len = (
253
- inplen + (logits.shape[0] - padding_len_inp)
254
- if self.AUTO_MODEL_CLASS == transformers.AutoModelForCausalLM
255
- else None
256
- )
257
- logits = self._select_cont_toks(logits, contlen=contlen, inplen=ctx_len)
258
- logits = logits.unsqueeze(0) # [1, seq, vocab]
259
-
260
- # Check if per-token argmax is exactly equal to continuation
261
- greedy_tokens = logits.argmax(dim=-1)
262
-
263
- # check for one-token continuation cache hits.
264
- # noop in case group_by != "contexts" or no cache hit and returns the
265
- # original args. Otherwise, expands the logits batch dimension and yields each
266
- # batch along with matching continuation tokens and prompt strings.
267
- # logits -> [1, seq, vocab]
268
- for request_str, cont_toks, logits in re_ord.get_cache(
269
- req_str=request_str,
270
- cxt_toks=ctx_tokens,
271
- cont_toks=cont_toks,
272
- logits=logits,
273
- ):
274
- cont_toks = torch.tensor(
275
- cont_toks, dtype=torch.long, device=self.device
276
- ).unsqueeze(0) # [1, seq]
277
- max_equal = (greedy_tokens == cont_toks).all()
278
-
279
- # Obtain log-probs at the corresponding continuation token indices
280
- # last_token_slice = logits[:, -1, :].squeeze(0).tolist()
281
- logits = torch.gather(logits, 2, cont_toks.unsqueeze(-1)).squeeze(
282
- -1
283
- ) # [1, seq]
284
-
285
- # Answer: (log prob, is-exact-match)
286
- answer = (float(logits.sum()), bool(max_equal))
287
-
288
- res.append((answer, per_sample_time, 0, 0, 0, 0))
289
-
290
- self.cache_hook.add_partial("loglikelihood", request_str, answer)
291
- pbar.update(1)
292
-
293
- pbar.close()
294
-
295
- return re_ord.get_original(res)
296
-
297
- def _model_generate(self, context, max_tokens, stop, **generation_kwargs):
298
- # temperature = 0.0 if not set
299
- # if do_sample is false and temp==0.0:
300
- # remove temperature, as do_sample=False takes care of this
301
- # and we don't want a warning from HF
302
- generation_kwargs["temperature"] = generation_kwargs.get("temperature", 0.0)
303
- do_sample = generation_kwargs.get("do_sample", None)
304
-
305
- # is_gsm8k = generation_kwargs.get("is_gsm8k", False)
306
-
307
- # The temperature has to be a strictly positive float -- if it is 0.0, use greedy decoding strategies
308
- if generation_kwargs.get("temperature") == 0.0 and do_sample is None:
309
- generation_kwargs["do_sample"] = do_sample = False
310
-
311
- if do_sample is False and generation_kwargs.get("temperature") == 0.0:
312
- generation_kwargs.pop("temperature")
313
-
314
- # if is_gsm8k:
315
- # generation_kwargs.pop("is_gsm8k")
316
-
317
- context_length = context.shape[1]
318
-
319
- if self.model.__class__.__name__ == "MoE":
320
- model_config = self.model.model.config
321
- else:
322
- model_config = self.model.config
323
-
324
- if not self.precision:
325
- if model_config.quantization_config._load_in_4bit:
326
- self.precision = "4bit"
327
- elif model_config.quantization_config._load_in_8bit:
328
- self.precision = "8bit"
329
- else:
330
- raise ValueError("Unknown precision")
331
-
332
- # print(self.model)
333
- linear_count = 0
334
- element_wise_mul = 0
335
- for name, module in self.model.named_modules():
336
- if ('layers.0.' in name or 'decoder.0.' in name) and ('attn' not in name):
337
- if 'experts.0.' in name:
338
- if isinstance(module, torch.nn.Linear):
339
- # print(name, module)
340
- linear_count += 1
341
- elif 'experts' not in name:
342
- if "gate" not in name or "gate_proj" in name:
343
- if "gate_proj" in name:
344
- element_wise_mul = 1
345
- if isinstance(module, torch.nn.Linear):
346
- # print(name, module)
347
- linear_count += 1
348
- else:
349
- continue
350
- print(f"linear_count: {linear_count}")
351
-
352
- stopping_criteria = stop_sequences_criteria(
353
- self.tokenizer, stop, context.shape[1], context.shape[0]
354
- )
355
- stop_watch = StopWatch(self.tokenizer)
356
- start = time()
357
- res = self.model.generate(
358
- input_ids=context,
359
- max_new_tokens=max_tokens,
360
- stopping_criteria=stopping_criteria,
361
- pad_token_id=self.tokenizer.pad_token_id,
362
- use_cache=True,
363
- streamer=stop_watch,
364
- **generation_kwargs,
365
- )
366
- end = time()
367
-
368
- batch_size = context.shape[0]
369
- output_length = stop_watch.decoding_iterations
370
-
371
- precision_bytes = transfer_precision2bytes(self.precision)
372
-
373
- model_info = API.model_info(repo_id=self.pretrained, revision=self.revision)
374
- model_size_param = get_model_size(model_info=model_info, precision=self.precision)
375
-
376
- n_layers = model_config.num_hidden_layers if hasattr(model_config, "num_hidden_layers") else model_config.num_layers
377
- d_model = model_config.hidden_size if hasattr(model_config, "hidden_size") else model_config.d_model
378
-
379
- if hasattr(model_config, "num_experts_per_tok"):
380
- n_experts_per_tok = model_config.num_experts_per_tok
381
- elif hasattr(model_config, "num_selected_experts"):
382
- n_experts_per_tok = model_config.num_selected_experts
383
- else:
384
- n_experts_per_tok = 1
385
-
386
- if hasattr(model_config, "ffn_dim"):
387
- d_ff = model_config.ffn_dim
388
- elif hasattr(model_config, "intermediate_size"):
389
- d_ff = model_config.intermediate_size
390
- elif hasattr(model_config, "d_ff"):
391
- d_ff = model_config.d_ff
392
- else:
393
- if hasattr(model_config, "ff_ratio"):
394
- d_ff = d_model * model_config.ff_ratio
395
- else:
396
- raise ValueError("Unknown FFN dimension")
397
-
398
- if hasattr(model_config, "num_local_experts"):
399
- num_experts = model_config.num_local_experts
400
- elif hasattr(model_config, "num_experts"):
401
- num_experts = model_config.num_experts
402
- else:
403
- num_experts = 1
404
-
405
- ffn_params = n_layers * d_ff * linear_count * d_model
406
-
407
- shared_params = model_size_param * 1e9 - num_experts * ffn_params
408
-
409
- model_size = shared_params + n_experts_per_tok * ffn_params
410
-
411
- per_token_kv_size = 2 * n_layers * d_model * precision_bytes
412
-
413
- peak_bw_single = get_peak_bw(get_gpu_details())
414
- peak_bw = peak_bw_single * get_gpu_number()
415
-
416
- context_prefill_size = context_length
417
- kv_size = context_prefill_size * per_token_kv_size + (output_length - 1) * per_token_kv_size / 2
418
-
419
- kv_size = kv_size / 1e9
420
-
421
- n_vocab = model_config.vocab_size
422
-
423
- end_to_end_time = (end - start) / batch_size
424
- prefilling_time = stop_watch.prefilling_time / batch_size
425
- decoding_time = stop_watch.decoding_time / batch_size
426
- token_per_sec = output_length / decoding_time
427
- achieve_mem_bw = (model_size * precision_bytes / 1e9 + kv_size) * token_per_sec
428
-
429
- avg_context_length = context_length + (output_length - 1) / 2
430
- flops_per_token = 2 * model_size + ((linear_count + element_wise_mul) * n_layers * avg_context_length * d_model) + 4 * d_model + 2 * d_model * n_vocab
431
- peak_flops_single = get_peak_flops(get_gpu_details(), self.precision)
432
- peak_flops = peak_flops_single * get_gpu_number()
433
-
434
- ## TODO only support llama-type decoder only models and moe models of switch transformer and mixtrial
435
- mfu = token_per_sec * flops_per_token / peak_flops
436
- mbu = achieve_mem_bw / peak_bw
437
-
438
- print(f"mfu: {mfu}, mbu: {mbu}")
439
-
440
- return res, end_to_end_time, prefilling_time, token_per_sec, mfu, mbu
441
-
442
- def generate_until(
443
- self, requests: List[Instance], disable_tqdm: bool = False
444
- ) -> List[str]:
445
- res = []
446
-
447
- def _collate(req: Tuple[str, dict]):
448
- """Defines the key for the sorted method"""
449
- # the negative sign on len(toks) sorts descending - this has a few advantages:
450
- # - time estimates will always be over not underestimates, which is more useful for planning
451
- # - to know the size of a batch when going through the list, you know the first one is always the batch
452
- # padded context length. this is useful to simplify the batching logic and more importantly to make
453
- # automatic adaptive batches much much easier to implement
454
- # - any OOMs will happen right away rather than near the end
455
- toks = self.tok_encode(req[0])
456
- return -len(toks), req[0]
457
-
458
- pbar = tqdm(
459
- total=len(requests),
460
- disable=(disable_tqdm or (self.rank != 0)),
461
- desc="Running generate_until requests",
462
- )
463
- adaptive_batch_size = None
464
- if self.batch_size == "auto":
465
- # using rolling window with maximum context
466
- print("Passed argument batch_size = auto. Detecting largest batch size")
467
- batch_size = self._detect_batch_size()
468
- print(f"Determined Largest batch size: {batch_size}")
469
- adaptive_batch_size = batch_size
470
- # for each different set of kwargs, we execute all requests, by batch.
471
- batch_size = (
472
- self.batch_size
473
- if self.batch_size != "auto"
474
- else adaptive_batch_size
475
- if adaptive_batch_size is not None
476
- else 0
477
- )
478
- batch_fn = (
479
- self._batch_scheduler
480
- if self.batch_size == "auto" and not adaptive_batch_size
481
- else None
482
- )
483
-
484
- # we group requests by their generation_kwargs,
485
- # so that we don't try to execute e.g. greedy sampling and temp=0.8 sampling
486
- # in the same batch.
487
- # group_fn=lambda x: x[1] -> x=(context, gen_kwargs)
488
- re_ords = Collator(
489
- [reg.args for reg in requests],
490
- sort_fn=_collate,
491
- group_by="gen_kwargs",
492
- group_fn=lambda x: x[1],
493
- )
494
- chunks = re_ords.get_batched(n=batch_size, batch_fn=batch_fn)
495
- for chunk in chunks:
496
- contexts, all_gen_kwargs = zip(*chunk)
497
- # we assume all gen kwargs in the batch are the same
498
- # this is safe to assume because the `grouper` object ensures it.
499
- gen_kwargs = all_gen_kwargs[0]
500
- # unpack our keyword arguments.
501
- until = None
502
- if isinstance(gen_kwargs, dict):
503
- kwargs = copy.deepcopy(gen_kwargs) # edge case for repeats > 1
504
- if "until" in kwargs.keys():
505
- until = kwargs.pop("until")
506
- if isinstance(until, str):
507
- until = [kwargs]
508
- elif not isinstance(until, list):
509
- raise ValueError(
510
- f"Expected `kwargs['until']` to be of type Union[str,list] but got {until}"
511
- )
512
- else:
513
- raise ValueError(
514
- f"Expected `kwargs` to be of type `dict` but got {type(gen_kwargs)}"
515
- )
516
- # add EOS token to stop sequences
517
- eos = "<|eot_id|>"
518
- if not until:
519
- until = [eos]
520
- else:
521
- until.append(eos)
522
-
523
- # is_gsm8k = kwargs.get("is_gsm8k", False)
524
- # if is_gsm8k:
525
- # until = ["Question:", "Question", "</s>"]
526
- # eos_ids = [self.tokenizer.eos_token_id,
527
- # self.tokenizer.convert_tokens_to_ids("<|eot_id|>")]
528
-
529
-
530
- if "max_gen_toks" in kwargs.keys():
531
- max_gen_toks = kwargs.pop("max_gen_toks")
532
- else:
533
- max_gen_toks = self.max_gen_toks
534
-
535
- # set the max length in tokens of inputs ("context_enc")
536
- if self.AUTO_MODEL_CLASS == transformers.AutoModelForCausalLM:
537
- # max len for inputs = max length, minus room to generate the max new tokens
538
- max_ctx_len = self.max_length - max_gen_toks
539
- elif self.AUTO_MODEL_CLASS == transformers.AutoModelForSeq2SeqLM:
540
- # max len for inputs = encoder's whole max_length
541
- max_ctx_len = self.max_length
542
-
543
- # encode, pad, and truncate contexts for this batch
544
- context_enc, attn_masks = self.tok_batch_encode(
545
- contexts,
546
- left_truncate_len=max_ctx_len,
547
- truncation=self.truncation,
548
- )
549
-
550
- # print("context: ", self.tok_decode(context_enc[0]))
551
- context_enc = context_enc.to(self.device)
552
- attn_masks = attn_masks.to(self.device)
553
-
554
- if "max_tokens" not in kwargs:
555
- kwargs["max_tokens"] = max_gen_toks
556
-
557
- # perform batched generation
558
- cont, end_to_end_time, prefilling_time, token_per_sec, mfu, mbu = self._model_generate(
559
- context=context_enc,
560
- attention_mask=attn_masks,
561
- stop=until,
562
- **kwargs,
563
- )
564
-
565
- cont_toks_list = cont.tolist()
566
- for cont_toks, context in zip(cont_toks_list, contexts):
567
- # discard context + left-padding toks if using causal decoder-only LM
568
- if self.AUTO_MODEL_CLASS == transformers.AutoModelForCausalLM:
569
- # print("After Generation: ", self.tok_decode(cont_toks))
570
- cont_toks = cont_toks[context_enc.shape[1] :]
571
-
572
- s = self.tok_decode(cont_toks)
573
-
574
- # # use secondary stop seqs to cut off should-have-been-stopped content post-hoc
575
- # if not is_gsm8k:
576
- for term in until:
577
- if len(term) > 0:
578
- # ignore '' separator,
579
- # for seq2seq case where self.tok_decode(self.eot_token_id) = ''
580
- s = s.split(term)[0]
581
-
582
- # print(s)
583
- res.append((s, end_to_end_time, prefilling_time, token_per_sec, mfu, mbu))
584
-
585
- self.cache_hook.add_partial("generate_until", (context, gen_kwargs), s)
586
- pbar.update(1)
587
- # reorder this group of results back to original unsorted form
588
- res = re_ords.get_original(res)
589
-
590
- pbar.close()
591
-
592
- return res
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
open-moe-llm-leaderboard-gh/src/backend/huggingface_generate_until.py DELETED
@@ -1,60 +0,0 @@
1
- from typing import List, Literal, Optional, Tuple, Union
2
- import torch
3
- import transformers
4
-
5
- from lm_eval.api.registry import register_model
6
-
7
- from src.backend.hflm_with_measurement import HFLMWithMeasurement
8
-
9
-
10
- @register_model("hf-chat")
11
- class HFLMwithChatTemplate(HFLMWithMeasurement):
12
- def __init__(self, use_chat_template=True, **kwargs):
13
- super().__init__(**kwargs)
14
- self.use_chat_template = use_chat_template
15
-
16
- def tok_batch_encode(
17
- self,
18
- strings: List[str],
19
- padding_side: str = "left",
20
- left_truncate_len: int = None,
21
- truncation: bool = False,
22
- ) -> Tuple[torch.Tensor, torch.Tensor]:
23
-
24
- if self.use_chat_template:
25
- try:
26
- updated_strings = []
27
- for input_string in strings:
28
- messages = [
29
- {"role": "user", "content": f"{input_string}"},
30
- ]
31
- if "dbrx" in self.model.name_or_path:
32
- updated_string = self.tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
33
- else:
34
- updated_string = self.tokenizer.apply_chat_template(messages, tokenize=False)
35
- updated_strings.append(updated_string)
36
- strings = updated_strings[:]
37
- except:
38
- print(f"failed to update input string with chat template: {self._model}")
39
- # encode a batch of strings. converts to tensors and pads automatically, unlike tok_encode.
40
- old_padding_side = self.tokenizer.padding_side
41
- self.tokenizer.padding_side = padding_side
42
-
43
- if self.AUTO_MODEL_CLASS == transformers.AutoModelForCausalLM:
44
- add_special_tokens = False
45
- elif self.AUTO_MODEL_CLASS == transformers.AutoModelForSeq2SeqLM:
46
- add_special_tokens = True
47
-
48
- encoding = self.tokenizer(
49
- strings,
50
- truncation=truncation,
51
- padding="longest",
52
- return_tensors="pt",
53
- add_special_tokens=add_special_tokens,
54
- )
55
- if left_truncate_len:
56
- encoding["input_ids"] = encoding["input_ids"][:, -left_truncate_len:]
57
- encoding["attention_mask"] = encoding["attention_mask"][:, -left_truncate_len:]
58
- self.tokenizer.padding_side = old_padding_side
59
-
60
- return encoding["input_ids"], encoding["attention_mask"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
open-moe-llm-leaderboard-gh/src/backend/manage_requests.py DELETED
@@ -1,134 +0,0 @@
1
- import glob
2
- import json
3
- from dataclasses import dataclass
4
- from typing import Optional
5
-
6
- from huggingface_hub import HfApi, snapshot_download
7
-
8
- from src.utils import my_snapshot_download
9
-
10
-
11
- @dataclass
12
- class EvalRequest:
13
- model: str
14
- private: bool
15
- status: str
16
- json_filepath: str
17
- weight_type: str = "Original"
18
- model_type: str = "" # pretrained, finetuned, with RL
19
- inference_framework: str = "hf-chat"
20
- precision: str = "" # float16, bfloat16
21
- base_model: Optional[str] = None # for adapter models
22
- revision: str = "main" # commit
23
- submitted_time: Optional[str] = (
24
- "2022-05-18T11:40:22.519222" # random date just so that we can still order requests by date
25
- )
26
- model_type: Optional[str] = None
27
- likes: Optional[int] = 0
28
- params: Optional[int] = None
29
- license: Optional[str] = ""
30
- batch_size: Optional[int] = 1
31
- gpu_type: Optional[str] = "NVIDIA-A100-PCIe-80GB"
32
-
33
- def get_model_args(self) -> str:
34
- model_args = f"pretrained={self.model},revision={self.revision},parallelize=True" # ,max_length=4096"
35
- model_args += ",trust_remote_code=True,device_map=auto"
36
- if self.precision in ["float16", "float32", "bfloat16"]:
37
- model_args += f",dtype={self.precision}"
38
- # Quantized models need some added config, the install of bits and bytes, etc
39
- # elif self.precision == "8bit":
40
- # model_args += ",load_in_8bit=True"
41
- elif self.precision == "4bit":
42
- model_args += ",load_in_4bit=True"
43
- # elif self.precision == "GPTQ":
44
- # A GPTQ model does not need dtype to be specified,
45
- # it will be inferred from the config
46
- elif self.precision == "8bit":
47
- model_args += ",load_in_8bit=True"
48
- else:
49
- raise Exception(f"Unknown precision {self.precision}.")
50
- return model_args
51
-
52
-
53
- def set_eval_request(api: HfApi, eval_request: EvalRequest, set_to_status: str, hf_repo: str, local_dir: str):
54
- """Updates a given eval request with its new status on the hub (running, completed, failed, ...)"""
55
- json_filepath = eval_request.json_filepath
56
-
57
- with open(json_filepath) as fp:
58
- data = json.load(fp)
59
-
60
- data["status"] = set_to_status
61
-
62
- with open(json_filepath, "w") as f:
63
- f.write(json.dumps(data))
64
-
65
- api.upload_file(
66
- path_or_fileobj=json_filepath,
67
- path_in_repo=json_filepath.replace(local_dir, ""),
68
- repo_id=hf_repo,
69
- repo_type="dataset",
70
- )
71
-
72
-
73
- def get_eval_requests(job_status: list, local_dir: str, hf_repo: str, do_download: bool = True) -> list[EvalRequest]:
74
- """Get all pending evaluation requests and return a list in which private
75
- models appearing first, followed by public models sorted by the number of
76
- likes.
77
-
78
- Returns:
79
- `list[EvalRequest]`: a list of model info dicts.
80
- """
81
- if do_download:
82
- my_snapshot_download(
83
- repo_id=hf_repo, revision="main", local_dir=local_dir, repo_type="dataset", max_workers=60
84
- )
85
-
86
- json_files = glob.glob(f"{local_dir}/**/*.json", recursive=True)
87
-
88
- eval_requests = []
89
- for json_filepath in json_files:
90
- with open(json_filepath) as fp:
91
- data = json.load(fp)
92
- if data["status"] in job_status:
93
- # import pdb
94
- # breakpoint()
95
- data["json_filepath"] = json_filepath
96
-
97
- if "job_id" in data:
98
- del data["job_id"]
99
-
100
- eval_request = EvalRequest(**data)
101
- eval_requests.append(eval_request)
102
-
103
- return eval_requests
104
-
105
-
106
- def check_completed_evals(
107
- api: HfApi,
108
- hf_repo: str,
109
- local_dir: str,
110
- checked_status: str,
111
- completed_status: str,
112
- failed_status: str,
113
- hf_repo_results: str,
114
- local_dir_results: str,
115
- ):
116
- """Checks if the currently running evals are completed, if yes, update their status on the hub."""
117
- my_snapshot_download(
118
- repo_id=hf_repo_results, revision="main", local_dir=local_dir_results, repo_type="dataset", max_workers=60
119
- )
120
-
121
- running_evals = get_eval_requests([checked_status], hf_repo=hf_repo, local_dir=local_dir)
122
-
123
- for eval_request in running_evals:
124
- model = eval_request.model
125
- print("====================================")
126
- print(f"Checking {model}")
127
-
128
- output_path = model
129
- output_file = f"{local_dir_results}/{output_path}/results*.json"
130
- output_file_exists = len(glob.glob(output_file)) > 0
131
-
132
- if output_file_exists:
133
- print(f"EXISTS output file exists for {model} setting it to {completed_status}")
134
- set_eval_request(api, eval_request, completed_status, hf_repo, local_dir)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
open-moe-llm-leaderboard-gh/src/backend/moe_infinity.py DELETED
@@ -1,124 +0,0 @@
1
- import torch
2
- import os
3
- import shutil
4
- from transformers import AutoTokenizer
5
- from transformers import AutoModelForCausalLM
6
- from moe_infinity import MoE
7
- from typing import List, Tuple, Optional, Union
8
-
9
- from lm_eval.api.registry import register_model
10
-
11
- from src.backend.hflm_with_measurement import HFLMWithMeasurement
12
-
13
-
14
- @register_model("moe-infinity")
15
- class MoEHFLM(HFLMWithMeasurement):
16
- def __init__(
17
- self,
18
- pretrained: str = "mistralai/Mixtral-8x7B-Instruct-v0.1",
19
- moe_config: dict = None,
20
- offload_path=os.path.expanduser("~"),
21
- device_memory_ratio=0.75,
22
- use_chat_template=True,
23
- *args,
24
- **kwargs,
25
- ):
26
- # Initialize parent class without calling _create_model in the parent's __init__
27
- self.checkpoint = pretrained
28
- self.moe_config = moe_config if moe_config is not None else {}
29
- self.offload_path = offload_path
30
- self.device_memory_ratio = device_memory_ratio
31
- self.use_chat_template = use_chat_template
32
- if "device" in kwargs:
33
- kwargs.pop("device")
34
- kwargs["device_map"] = "cuda:0"
35
- super().__init__(
36
- *args, **kwargs, pretrained=pretrained
37
- ) # Assuming HFLM accepts a 'pretrained' arg and handles it
38
- # self._create_model()
39
- shutil.rmtree(os.path.join(self.offload_path, "moe-infinity-offloads"))
40
-
41
- def __del__(self):
42
- # Clean up offloaded models from self.offload_path
43
- shutil.rmtree(os.path.join(self.offload_path, "moe-infinity-offloads"))
44
-
45
- def _create_model(self, *args, **kwargs):
46
- """
47
- Initializes the MoE model from MoE-infinity with the provided configuration.
48
- """
49
- # Ensure default configurations are set if not provided
50
- default_moe_config = {
51
- "offload_path": os.path.join(self.offload_path, "moe-infinity-offloads"),
52
- "device_memory_ratio": self.device_memory_ratio, # Default value, adjust as necessary
53
- }
54
- # Update default config with any user-provided config
55
- final_moe_config = {**default_moe_config, **self.moe_config}
56
-
57
- # dirty fix, to be removed when MoE-infinity supports move input to correct device
58
- def MoEGenDecorator(func):
59
- def wrapper(*args, **kwargs):
60
- # Ensure all tensor in the input are in the same device as the model
61
- args = [arg.to("cuda:0") if isinstance(arg, torch.Tensor) else arg for arg in args]
62
- kwargs = {k: v.to("cuda:0") if isinstance(v, torch.Tensor) else v for k, v in kwargs.items()}
63
- return func(*args, **kwargs)
64
- return wrapper
65
-
66
- self._model = MoE(self.checkpoint, final_moe_config)
67
- self._model.generate = MoEGenDecorator(self._model.generate)
68
- # self._model = AutoModelForCausalLM.from_pretrained(
69
- # self.checkpoint, torch_dtype=torch.float16, device_map="auto"
70
- # )
71
-
72
- @property
73
- def max_length(self):
74
- if self._max_length: # if max length manually set, return it
75
- return self._max_length
76
- seqlen_config_attrs = ("n_positions", "max_position_embeddings", "n_ctx")
77
- for attr in seqlen_config_attrs:
78
- if hasattr(self.model.model.config, attr):
79
- return getattr(self.model.model.config, attr)
80
- if hasattr(self.tokenizer, "model_max_length"):
81
- if self.tokenizer.model_max_length == 1000000000000000019884624838656:
82
- return self._DEFAULT_MAX_LENGTH
83
- return self.tokenizer.model_max_length
84
- return self._DEFAULT_MAX_LENGTH
85
-
86
- def tok_batch_encode(
87
- self,
88
- strings: List[str],
89
- padding_side: str = "left",
90
- left_truncate_len: int = None,
91
- truncation: bool = False,
92
- ) -> Tuple[torch.Tensor, torch.Tensor]:
93
-
94
- if self.use_chat_template:
95
- try:
96
- updated_strings = []
97
- for input_string in strings:
98
- messages = [
99
- {"role": "user", "content": f"{input_string}"},
100
- ]
101
- updated_string = self.tokenizer.apply_chat_template(messages, tokenize=False)
102
- updated_strings.append(updated_string)
103
- strings = updated_strings[:]
104
- except:
105
- print(f"failed to update input string with chat template: {self._model}")
106
- # encode a batch of strings. converts to tensors and pads automatically, unlike tok_encode.
107
- old_padding_side = self.tokenizer.padding_side
108
- self.tokenizer.padding_side = padding_side
109
-
110
- add_special_tokens = False
111
-
112
- encoding = self.tokenizer(
113
- strings,
114
- truncation=truncation,
115
- padding="longest",
116
- return_tensors="pt",
117
- add_special_tokens=add_special_tokens,
118
- )
119
- if left_truncate_len:
120
- encoding["input_ids"] = encoding["input_ids"][:, -left_truncate_len:]
121
- encoding["attention_mask"] = encoding["attention_mask"][:, -left_truncate_len:]
122
- self.tokenizer.padding_side = old_padding_side
123
-
124
- return encoding["input_ids"], encoding["attention_mask"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
open-moe-llm-leaderboard-gh/src/backend/run_eval_suite.py DELETED
@@ -1,130 +0,0 @@
1
- from lm_eval import evaluator
2
- from lm_eval.tasks import TaskManager
3
- from lm_eval.api.metrics import mean
4
- from lm_eval.api.task import ConfigurableTask
5
-
6
- from src.backend.manage_requests import EvalRequest
7
-
8
-
9
- orig_process_results = ConfigurableTask.process_results
10
- orig_aggregation = ConfigurableTask.aggregation
11
- orig_higher_is_better = ConfigurableTask.higher_is_better
12
-
13
- def process_results_decorator(func):
14
- def wrapper(self, doc, results, *args, **kwargs):
15
- processed_results = [r[0] for r in results]
16
-
17
- end_to_end_time = sum([r[1] for r in results]) / len(results)
18
- prefilling_time = sum([r[2] for r in results]) / len(results)
19
- decoding_throughput = sum([r[3] for r in results]) / len(results)
20
- mfu = sum([r[4] for r in results]) / len(results)
21
- mbu = sum([r[5] for r in results]) / len(results)
22
- # print(f"end_to_end_time: {end_to_end_time}, prefilling_time: {prefilling_time}, decoding_throughput: {decoding_throughput}")
23
-
24
- result_dict = func(self, doc, processed_results, *args, **kwargs)
25
- result_dict["end_to_end_time"] = end_to_end_time
26
- result_dict["prefilling_time"] = prefilling_time
27
- result_dict["decoding_throughput"] = decoding_throughput
28
- result_dict["mfu"] = mfu * 100
29
- result_dict["mbu"] = mbu * 100
30
- return result_dict
31
- return wrapper
32
- ConfigurableTask.process_results = process_results_decorator(orig_process_results)
33
-
34
- def aggregation_decorator(func):
35
- def wrapper(self, *args, **kwargs):
36
- aggregation_list = func(self, *args, **kwargs)
37
- aggregation_list["end_to_end_time"] = mean
38
- aggregation_list["prefilling_time"] = mean
39
- aggregation_list["decoding_throughput"] = mean
40
- aggregation_list["mfu"] = mean
41
- aggregation_list["mbu"] = mean
42
- return aggregation_list
43
- return wrapper
44
- ConfigurableTask.aggregation = aggregation_decorator(orig_aggregation)
45
-
46
- def higher_is_better_decorator(func):
47
- def wrapper(self, *args, **kwargs):
48
- higher_is_better_dict = func(self, *args, **kwargs)
49
- higher_is_better_dict["end_to_end_time"] = False
50
- higher_is_better_dict["prefilling_time"] = False
51
- higher_is_better_dict["decoding_throughput"] = True
52
- higher_is_better_dict["mfu"] = True
53
- higher_is_better_dict["mbu"] = True
54
- return higher_is_better_dict
55
- return wrapper
56
- ConfigurableTask.higher_is_better = higher_is_better_decorator(orig_higher_is_better)
57
-
58
- # from src.backend.tasks.xsum.task import XSum
59
- # from src.backend.tasks.xsum.task_v2 import XSumv2
60
-
61
- # from src.backend.tasks.cnndm.task import CNNDM
62
- # from src.backend.tasks.cnndm.task_v2 import CNNDMv2
63
-
64
- from src.backend.tasks.selfcheckgpt.task import SelfCheckGPT
65
-
66
- from src.backend.huggingface_generate_until import HFLMwithChatTemplate
67
- from src.backend.moe_infinity import MoEHFLM
68
-
69
- def run_evaluation(
70
- eval_request: EvalRequest,
71
- task_names,
72
- num_fewshot,
73
- batch_size,
74
- device,
75
- use_cache=None,
76
- limit=None,
77
- max_nb_samples=100,
78
- ) -> dict:
79
- if limit:
80
- print("WARNING: --limit SHOULD ONLY BE USED FOR TESTING. REAL METRICS SHOULD NOT BE COMPUTED USING LIMIT.")
81
-
82
- # include_task_folder("src/backend/tasks/")
83
- # initialize_tasks('INFO')
84
-
85
- print(f"Allocating task manager for: {task_names}")
86
-
87
- task_manager = TaskManager(include_path="./src/backend/tasks/")
88
- # task_manager.initialize_tasks('INFO')
89
-
90
- print(f"Considered Tasks: {task_names}")
91
- # print(f"Allowed Tasks: {tasks.ALL_TASKS}")
92
-
93
- # task_names = utils.pattern_match(task_names, tasks.ALL_TASKS)
94
-
95
- print(f"Selected Tasks: {task_names}")
96
- print(f"Eval Request: {eval_request}")
97
- print(
98
- f"Num Fewshot: {num_fewshot}, Batch Size: {batch_size}, Device: {device}, Use Cache: {use_cache}, Limit: {limit}"
99
- )
100
- # hf-chat is implemented to use apply_chat_template
101
- results = evaluator.simple_evaluate(
102
- model=eval_request.inference_framework, # "hf-chat", "moe-infinity"
103
- model_args=eval_request.get_model_args(),
104
- tasks=task_names,
105
- num_fewshot=num_fewshot,
106
- batch_size=batch_size,
107
- max_batch_size=8,
108
- device=device,
109
- use_cache=use_cache,
110
- limit=limit,
111
- write_out=True,
112
- task_manager=task_manager,
113
- verbosity="WARNING",
114
- )
115
-
116
- results["config"]["model_dtype"] = eval_request.precision
117
- results["config"]["model_name"] = eval_request.model
118
- results["config"]["model_sha"] = eval_request.revision
119
- results["config"]["inference_framework"] = eval_request.inference_framework
120
-
121
- if max_nb_samples is not None:
122
- if "samples" in results:
123
- samples = results["samples"]
124
- for task_name in samples.keys():
125
- if len(samples[task_name]) > max_nb_samples:
126
- results["samples"][task_name] = results["samples"][task_name][:max_nb_samples]
127
-
128
- # print(evaluator.make_table(results))
129
-
130
- return results
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
open-moe-llm-leaderboard-gh/src/backend/sort_queue.py DELETED
@@ -1,28 +0,0 @@
1
- from dataclasses import dataclass
2
- from huggingface_hub import HfApi
3
- from src.backend.manage_requests import EvalRequest
4
-
5
-
6
- @dataclass
7
- class ModelMetadata:
8
- likes: int = 0
9
- size: int = 15
10
-
11
-
12
- def sort_models_by_priority(api: HfApi, models: list[EvalRequest]) -> list[EvalRequest]:
13
- private_models = [model for model in models if model.private]
14
- public_models = [model for model in models if not model.private]
15
-
16
- return sort_by_submit_date(private_models) + sort_by_submit_date(public_models)
17
-
18
-
19
- def sort_by_submit_date(eval_requests: list[EvalRequest]) -> list[EvalRequest]:
20
- return sorted(eval_requests, key=lambda x: x.submitted_time, reverse=False)
21
-
22
-
23
- def sort_by_size(eval_requests: list[EvalRequest]) -> list[EvalRequest]:
24
- return sorted(eval_requests, key=lambda x: x.params, reverse=False)
25
-
26
-
27
- def sort_by_likes(eval_requests: list[EvalRequest]) -> list[EvalRequest]:
28
- return sorted(eval_requests, key=lambda x: x.likes, reverse=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
open-moe-llm-leaderboard-gh/src/backend/tasks/__init__.py DELETED
@@ -1,7 +0,0 @@
1
- from src.backend.tasks.xsum.task import XSum
2
- from src.backend.tasks.xsum.task_v2 import XSumv2
3
-
4
- from src.backend.tasks.cnndm.task import CNNDM
5
- from src.backend.tasks.cnndm.task_v2 import CNNDMv2
6
-
7
- from src.backend.tasks.selfcheckgpt.task import SelfCheckGPT
 
 
 
 
 
 
 
 
open-moe-llm-leaderboard-gh/src/backend/tasks/cnndm/README.md DELETED
@@ -1,54 +0,0 @@
1
- # Task-name
2
-
3
- ### Paper
4
-
5
- Title: `Know What You Don’t Know: Unanswerable Questions for SQuAD`
6
- Abstract: https://arxiv.org/abs/1806.03822
7
-
8
- Stanford Question Answering Dataset (SQuAD) is a reading comprehension dataset,
9
- consisting of questions posed by crowdworkers on a set of Wikipedia articles,
10
- where the answer to every question is a segment of text, or span, from the
11
- corresponding reading passage, or the question might be unanswerable.
12
- SQuAD2.0 combines the 100,000 questions in SQuAD1.1 with over 50,000 unanswerable
13
- questions written adversarially by crowdworkers to look similar to answerable ones.
14
- To do well on SQuAD2.0, systems must not only answer questions when possible, but
15
- also determine when no answer is supported by the paragraph and abstain from answering.
16
-
17
- Homepage: https://rajpurkar.github.io/SQuAD-explorer/
18
-
19
-
20
- ### Citation
21
-
22
- ```
23
- @misc{rajpurkar2018know,
24
- title={Know What You Don't Know: Unanswerable Questions for SQuAD},
25
- author={Pranav Rajpurkar and Robin Jia and Percy Liang},
26
- year={2018},
27
- eprint={1806.03822},
28
- archivePrefix={arXiv},
29
- primaryClass={cs.CL}
30
- }
31
- ```
32
-
33
- ### Groups and Tasks
34
-
35
- #### Groups
36
-
37
- * Not part of a group yet
38
-
39
- #### Tasks
40
-
41
- * `squadv2`: `Default squadv2 task`
42
-
43
- ### Checklist
44
-
45
- For adding novel benchmarks/datasets to the library:
46
- * [ ] Is the task an existing benchmark in the literature?
47
- * [ ] Have you referenced the original paper that introduced the task?
48
- * [ ] If yes, does the original paper provide a reference implementation? If so, have you checked against the reference implementation and documented how to run such a test?
49
-
50
-
51
- If other tasks on this dataset are already supported:
52
- * [ ] Is the "Main" variant of this task clearly denoted?
53
- * [ ] Have you provided a short sentence in a README on what each new variant adds / evaluates?
54
- * [ ] Have you noted which, if any, published evaluation setups are matched by this variant?
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
open-moe-llm-leaderboard-gh/src/backend/tasks/cnndm/cnndm.yaml DELETED
@@ -1,2 +0,0 @@
1
- task: cnndm
2
- class: !function task.CNNDM
 
 
 
open-moe-llm-leaderboard-gh/src/backend/tasks/cnndm/cnndm_v2.yaml DELETED
@@ -1,2 +0,0 @@
1
- task: cnndm_v2
2
- class: !function task_v2.CNNDMv2
 
 
 
open-moe-llm-leaderboard-gh/src/backend/tasks/cnndm/task.py DELETED
@@ -1,218 +0,0 @@
1
- from lm_eval.api.task import ConfigurableTask
2
- from lm_eval.api.instance import Instance
3
-
4
- # from lm_eval.api.registry import register_task
5
- from lm_eval.api.metrics import mean
6
-
7
- import torch
8
- import sacrebleu
9
- from rouge_score import rouge_scorer, scoring
10
-
11
-
12
- def bleu(refs, preds):
13
- """
14
- Returns `t5` style BLEU scores. See the related implementation:
15
- https://github.com/google-research/text-to-text-transfer-transformer/blob/3d10afd51ba97ac29eb66ae701eca274488202f7/t5/evaluation/metrics.py#L41
16
-
17
- :param refs:
18
- A `list` of `list` of reference `str`s.
19
- :param preds:
20
- A `list` of predicted `str`s.
21
- """
22
- score = sacrebleu.corpus_bleu(
23
- preds,
24
- refs,
25
- smooth_method="exp",
26
- smooth_value=0.0,
27
- force=False,
28
- lowercase=False,
29
- tokenize="intl",
30
- use_effective_order=False,
31
- ).score
32
- return score
33
-
34
-
35
- def rouge(refs, preds):
36
- """
37
- Returns `t5` style ROUGE scores. See the related implementation:
38
- https://github.com/google-research/text-to-text-transfer-transformer/blob/3d10afd51ba97ac29eb66ae701eca274488202f7/t5/evaluation/metrics.py#L68
39
-
40
- :param refs:
41
- A `list` of reference `strs`.
42
- :param preds:
43
- A `list` of predicted `strs`.
44
- """
45
- rouge_types = ["rouge1", "rouge2", "rougeLsum"]
46
- scorer = rouge_scorer.RougeScorer(rouge_types)
47
- # Add newlines between sentences to correctly compute `rougeLsum`.
48
-
49
- def _prepare_summary(summary):
50
- summary = summary.replace(" . ", ".\n")
51
- return summary
52
-
53
- # Accumulate confidence intervals.
54
- aggregator = scoring.BootstrapAggregator()
55
- for ref, pred in zip(refs, preds):
56
- ref = _prepare_summary(ref)
57
- pred = _prepare_summary(pred)
58
- aggregator.add_scores(scorer.score(ref, pred))
59
- result = aggregator.aggregate()
60
- return {type: result[type].mid.fmeasure * 100 for type in rouge_types}
61
-
62
-
63
- # @register_task("cnndm")
64
- class CNNDM(ConfigurableTask):
65
- VERSION = 0
66
- DATASET_PATH = "cnn_dailymail"
67
- DATASET_NAME = "3.0.0"
68
-
69
- def __init__(self):
70
- super().__init__(config={"metadata": {"version": self.VERSION}})
71
- self.factkb_tokenizer = None
72
- self.factkb_model = None
73
- self.bert_score = None
74
-
75
- def maybe_init_factkb(self):
76
- if self.factkb_tokenizer is None or self.factkb_model is None:
77
- from transformers import AutoTokenizer, AutoModelForSequenceClassification
78
-
79
- self.factkb_tokenizer = AutoTokenizer.from_pretrained(
80
- "roberta-base", padding="max_length", truncation=True
81
- )
82
- self.factkb_model = AutoModelForSequenceClassification.from_pretrained(
83
- "bunsenfeng/FactKB", num_labels=2, device_map="auto"
84
- )
85
-
86
- def maybe_init_bertscore(self):
87
- if self.bert_score is None:
88
- from evaluate import load
89
-
90
- self.bert_score = load("bertscore")
91
-
92
- def has_training_docs(self):
93
- return True
94
-
95
- def has_validation_docs(self):
96
- return True
97
-
98
- def has_test_docs(self):
99
- return True
100
-
101
- def training_docs(self):
102
- return self.dataset["train"]
103
-
104
- def validation_docs(self):
105
- return self.dataset["validation"]
106
-
107
- def test_docs(self):
108
- return self.dataset["test"]
109
-
110
- def doc_to_text(self, doc):
111
- return f'Document: {doc["article"]}\nSummary:'
112
-
113
- @staticmethod
114
- def should_decontaminate():
115
- return True
116
-
117
- def doc_to_decontamination_query(self, doc):
118
- return doc["article"]
119
-
120
- def doc_to_target(self, doc):
121
- return doc["highlights"]
122
-
123
- def construct_requests(self, doc, ctx, **kwargs):
124
- """Uses RequestFactory to construct Requests and returns an iterable of
125
- Requests which will be sent to the LM.
126
-
127
- :param doc:
128
- The document as returned from training_docs, validation_docs, or test_docs.
129
- :param ctx: str
130
- The context string, generated by fewshot_context. This includes the natural
131
- language description, as well as the few shot examples, and the question
132
- part of the document for `doc`.
133
- """
134
-
135
- return [Instance(request_type="generate_until", doc=doc, arguments=(ctx, {"until": ["\n"]}), idx=0, **kwargs)]
136
-
137
- def process_results(self, doc, results):
138
- completion = results[0]
139
- # true_refs, false_refs = doc["correct_answers"], doc["incorrect_answers"]
140
- # all_refs = true_refs + false_refs
141
-
142
- document = doc["article"]
143
- gold_summary = doc["highlights"]
144
-
145
- true_refs = [doc["highlights"]]
146
- all_refs = true_refs
147
-
148
- # ROUGE-N
149
- rouge_scores = [rouge([ref], [completion]) for ref in all_refs]
150
- # ROUGE-1
151
- rouge1_scores = [score["rouge1"] for score in rouge_scores]
152
- # ROUGE-2
153
- rouge2_scores = [score["rouge2"] for score in rouge_scores]
154
- # ROUGE-L
155
- rougeL_scores = [score["rougeLsum"] for score in rouge_scores]
156
-
157
- self.maybe_init_factkb()
158
- input_factkb = [[completion, document]]
159
- factkb_tokens = self.factkb_tokenizer(
160
- input_factkb, return_tensors="pt", padding="max_length", truncation=True
161
- ).to(self.factkb_model.device)
162
- factkb_logits = self.factkb_model(**factkb_tokens).logits
163
- factkb_res = torch.softmax(factkb_logits, dim=1)
164
-
165
- self.maybe_init_bertscore()
166
- bert_score_res = self.bert_score.compute(
167
- predictions=[completion], references=[gold_summary], model_type="microsoft/deberta-xlarge-mnli", lang="en"
168
- )
169
-
170
- res = {
171
- "rouge1": rouge1_scores[0],
172
- "rouge2": rouge2_scores[0],
173
- "rougeL": rougeL_scores[0],
174
- "factKB": float(factkb_res[0][1]),
175
- "bertscore_precision": float(bert_score_res["precision"][0]),
176
- "bertscore_recall": float(bert_score_res["recall"][0]),
177
- "bertscore_f1": float(bert_score_res["f1"][0]),
178
- }
179
-
180
- return res
181
-
182
- def aggregation(self):
183
- """
184
- :returns: {str: [float] -> float}
185
- A dictionary where keys are the names of submetrics and values are
186
- functions that aggregate a list of metrics
187
- """
188
- return {
189
- k: mean
190
- for k in [
191
- "rouge1",
192
- "rouge2",
193
- "rougeL",
194
- "factKB",
195
- "bertscore_precision",
196
- "bertscore_recall",
197
- "bertscore_f1",
198
- ]
199
- }
200
-
201
- def higher_is_better(self):
202
- """
203
- :returns: {str: bool}
204
- A dictionary where keys are the names of submetrics and values are
205
- whether a higher value of the submetric is better
206
- """
207
- return {
208
- k: True
209
- for k in [
210
- "rouge1",
211
- "rouge2",
212
- "rougeL",
213
- "factKB",
214
- "bertscore_precision",
215
- "bertscore_recall",
216
- "bertscore_f1",
217
- ]
218
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
open-moe-llm-leaderboard-gh/src/backend/tasks/cnndm/task_v2.py DELETED
@@ -1,231 +0,0 @@
1
- from lm_eval.api.task import ConfigurableTask
2
- from lm_eval.api.instance import Instance
3
-
4
- # from lm_eval.api.registry import register_task
5
- from lm_eval.api.metrics import mean
6
-
7
- import torch
8
- import sacrebleu
9
- from rouge_score import rouge_scorer, scoring
10
-
11
-
12
- def bleu(refs, preds):
13
- """
14
- Returns `t5` style BLEU scores. See the related implementation:
15
- https://github.com/google-research/text-to-text-transfer-transformer/blob/3d10afd51ba97ac29eb66ae701eca274488202f7/t5/evaluation/metrics.py#L41
16
-
17
- :param refs:
18
- A `list` of `list` of reference `str`s.
19
- :param preds:
20
- A `list` of predicted `str`s.
21
- """
22
- score = sacrebleu.corpus_bleu(
23
- preds,
24
- refs,
25
- smooth_method="exp",
26
- smooth_value=0.0,
27
- force=False,
28
- lowercase=False,
29
- tokenize="intl",
30
- use_effective_order=False,
31
- ).score
32
- return score
33
-
34
-
35
- def rouge(refs, preds):
36
- """
37
- Returns `t5` style ROUGE scores. See the related implementation:
38
- https://github.com/google-research/text-to-text-transfer-transformer/blob/3d10afd51ba97ac29eb66ae701eca274488202f7/t5/evaluation/metrics.py#L68
39
-
40
- :param refs:
41
- A `list` of reference `strs`.
42
- :param preds:
43
- A `list` of predicted `strs`.
44
- """
45
- rouge_types = ["rouge1", "rouge2", "rougeLsum"]
46
- scorer = rouge_scorer.RougeScorer(rouge_types)
47
- # Add newlines between sentences to correctly compute `rougeLsum`.
48
-
49
- def _prepare_summary(summary):
50
- summary = summary.replace(" . ", ".\n")
51
- return summary
52
-
53
- # Accumulate confidence intervals.
54
- aggregator = scoring.BootstrapAggregator()
55
- for ref, pred in zip(refs, preds):
56
- ref = _prepare_summary(ref)
57
- pred = _prepare_summary(pred)
58
- aggregator.add_scores(scorer.score(ref, pred))
59
- result = aggregator.aggregate()
60
- return {type: result[type].mid.fmeasure * 100 for type in rouge_types}
61
-
62
-
63
- # @register_task("cnndm_v2")
64
- class CNNDMv2(ConfigurableTask):
65
- VERSION = 2
66
- DATASET_PATH = "cnn_dailymail"
67
- DATASET_NAME = "3.0.0"
68
-
69
- def __init__(self):
70
- super().__init__(
71
- config={
72
- "metadata": {"version": self.VERSION},
73
- "generation_kwargs": {"do_sample": False, "temperature": 0.0, "until": ["\n", "\n\n"]},
74
- }
75
- )
76
- self.factkb_tokenizer = None
77
- self.factkb_model = None
78
- self.bert_score = None
79
-
80
- def maybe_init_factkb(self):
81
- if self.factkb_tokenizer is None or self.factkb_model is None:
82
- from transformers import AutoTokenizer, AutoModelForSequenceClassification
83
-
84
- self.factkb_tokenizer = AutoTokenizer.from_pretrained(
85
- "roberta-base", padding="max_length", truncation=True
86
- )
87
- self.factkb_model = AutoModelForSequenceClassification.from_pretrained(
88
- "bunsenfeng/FactKB", num_labels=2, device_map="auto"
89
- )
90
-
91
- def maybe_init_bertscore(self):
92
- if self.bert_score is None:
93
- from evaluate import load
94
-
95
- self.bert_score = load("bertscore")
96
-
97
- def has_training_docs(self):
98
- return True
99
-
100
- def has_validation_docs(self):
101
- return True
102
-
103
- def has_test_docs(self):
104
- return True
105
-
106
- def training_docs(self):
107
- return self.dataset["train"]
108
-
109
- def validation_docs(self):
110
- return self.dataset["validation"]
111
-
112
- def test_docs(self):
113
- return self.dataset["test"]
114
-
115
- # def custom_prompt(self):
116
- # res = "Provide a summary of the provided article."
117
- # return res
118
-
119
- # def fewshot_delimiter(self):
120
- # return "\n\n"
121
-
122
- # From https://arxiv.org/abs/2305.14739
123
- def doc_to_text(self, doc):
124
- return f'Article: {doc["article"]}\nSummarize the article. Summary:'
125
-
126
- @staticmethod
127
- def should_decontaminate():
128
- return True
129
-
130
- def doc_to_decontamination_query(self, doc):
131
- return doc["article"]
132
-
133
- def doc_to_target(self, doc):
134
- return doc["highlights"]
135
-
136
- def construct_requests(self, doc, ctx, **kwargs):
137
- """Uses RequestFactory to construct Requests and returns an iterable of
138
- Requests which will be sent to the LM.
139
-
140
- :param doc:
141
- The document as returned from training_docs, validation_docs, or test_docs.
142
- :param ctx: str
143
- The context string, generated by fewshot_context. This includes the natural
144
- language description, as well as the few shot examples, and the question
145
- part of the document for `doc`.
146
- """
147
-
148
- return [Instance(request_type="generate_until", doc=doc, arguments=(ctx, {"until": ["\n"]}), idx=0, **kwargs)]
149
-
150
- def process_results(self, doc, results):
151
- completion = results[0]
152
- # true_refs, false_refs = doc["correct_answers"], doc["incorrect_answers"]
153
- # all_refs = true_refs + false_refs
154
-
155
- document = doc["article"]
156
- gold_summary = doc["highlights"]
157
-
158
- true_refs = [doc["highlights"]]
159
- all_refs = true_refs
160
-
161
- # ROUGE-N
162
- rouge_scores = [rouge([ref], [completion]) for ref in all_refs]
163
- # ROUGE-1
164
- rouge1_scores = [score["rouge1"] for score in rouge_scores]
165
- # ROUGE-2
166
- rouge2_scores = [score["rouge2"] for score in rouge_scores]
167
- # ROUGE-L
168
- rougeL_scores = [score["rougeLsum"] for score in rouge_scores]
169
-
170
- self.maybe_init_factkb()
171
- input_factkb = [[completion, document]]
172
- factkb_tokens = self.factkb_tokenizer(
173
- input_factkb, return_tensors="pt", padding="max_length", truncation=True
174
- ).to(self.factkb_model.device)
175
- factkb_logits = self.factkb_model(**factkb_tokens).logits
176
- factkb_res = torch.softmax(factkb_logits, dim=1)
177
-
178
- self.maybe_init_bertscore()
179
- bert_score_res = self.bert_score.compute(
180
- predictions=[completion], references=[gold_summary], model_type="microsoft/deberta-xlarge-mnli", lang="en"
181
- )
182
-
183
- res = {
184
- "rouge1": rouge1_scores[0],
185
- "rouge2": rouge2_scores[0],
186
- "rougeL": rougeL_scores[0],
187
- "factKB": float(factkb_res[0][1]),
188
- "bertscore_precision": float(bert_score_res["precision"][0]),
189
- "bertscore_recall": float(bert_score_res["recall"][0]),
190
- "bertscore_f1": float(bert_score_res["f1"][0]),
191
- }
192
-
193
- return res
194
-
195
- def aggregation(self):
196
- """
197
- :returns: {str: [float] -> float}
198
- A dictionary where keys are the names of submetrics and values are
199
- functions that aggregate a list of metrics
200
- """
201
- return {
202
- k: mean
203
- for k in [
204
- "rouge1",
205
- "rouge2",
206
- "rougeL",
207
- "factKB",
208
- "bertscore_precision",
209
- "bertscore_recall",
210
- "bertscore_f1",
211
- ]
212
- }
213
-
214
- def higher_is_better(self):
215
- """
216
- :returns: {str: bool}
217
- A dictionary where keys are the names of submetrics and values are
218
- whether a higher value of the submetric is better
219
- """
220
- return {
221
- k: True
222
- for k in [
223
- "rouge1",
224
- "rouge2",
225
- "rougeL",
226
- "factKB",
227
- "bertscore_precision",
228
- "bertscore_recall",
229
- "bertscore_f1",
230
- ]
231
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
open-moe-llm-leaderboard-gh/src/backend/tasks/faithdial/faithdial.yaml DELETED
@@ -1,14 +0,0 @@
1
- task: faithdial_hallu
2
- dataset_path: McGill-NLP/FaithDial
3
- training_split: train
4
- validation_split: validation
5
- test_split: test
6
- output_type: multiple_choice
7
- doc_to_text: !function utils.doc_to_text
8
- doc_to_target: !function utils.doc_to_target
9
- doc_to_choice: ["false", "true"]
10
- metric_list:
11
- - metric: acc
12
- higher_is_better: True
13
- metadata:
14
- version: 0.0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
open-moe-llm-leaderboard-gh/src/backend/tasks/faithdial/faithdial_v2.yaml DELETED
@@ -1,14 +0,0 @@
1
- task: faithdial_hallu_v2
2
- dataset_path: McGill-NLP/FaithDial
3
- training_split: train
4
- validation_split: validation
5
- test_split: test
6
- output_type: multiple_choice
7
- doc_to_text: !function utils.doc_to_text_v2
8
- doc_to_target: !function utils.doc_to_target
9
- doc_to_choice: ["false", "true"]
10
- metric_list:
11
- - metric: acc
12
- higher_is_better: True
13
- metadata:
14
- version: 0.0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
open-moe-llm-leaderboard-gh/src/backend/tasks/faithdial/utils.py DELETED
@@ -1,20 +0,0 @@
1
- from typing import List, Union
2
-
3
- ValueType = Union[str, List[str]]
4
-
5
-
6
- def doc_to_text(doc: dict[str, ValueType]) -> str:
7
- history_str = " ".join([f'[{"Human" if i % 2 == 0 else "Assistant"}] {m}' for i, m in enumerate(doc["history"])])
8
- doc_text = f'#Knowledge#: {doc["knowledge"]}\n#Dialogue History#: {history_str}\n#Response#: {doc["response"]}\n#Hallucinated#:'
9
- return doc_text
10
-
11
-
12
- def doc_to_text_v2(doc: dict[str, ValueType]) -> str:
13
- history_str = " ".join([f'[{"Human" if i % 2 == 0 else "Assistant"}] {m}' for i, m in enumerate(doc["history"])])
14
- doc_text = f'#Knowledge#: {doc["knowledge"]}\n#Dialogue History#: {history_str}\n#Response#: {doc["original_response"]}\n#Hallucinated#:'
15
- return doc_text
16
-
17
-
18
- def doc_to_target(doc: dict[str, ValueType]) -> str:
19
- res = "true" if "Hallucination" in doc["BEGIN"] else "false"
20
- return res
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
open-moe-llm-leaderboard-gh/src/backend/tasks/fever/fever10.yaml DELETED
@@ -1,16 +0,0 @@
1
- task: fever10
2
- dataset_path: fever
3
- dataset_name: v1.0
4
- output_type: multiple_choice
5
- training_split: train
6
- validation_split: labelled_dev
7
- test_split: null
8
- doc_to_text: "Claim: {{claim}}\nLabel:"
9
- doc_to_choice: ["SUPPORTS", "REFUTES", "NOT ENOUGH INFO"]
10
- doc_to_target: label
11
- metric_list:
12
- - metric: acc
13
- aggregation: mean
14
- higher_is_better: true
15
- metadata:
16
- version: 0.0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
open-moe-llm-leaderboard-gh/src/backend/tasks/fever/fever11.yaml DELETED
@@ -1,16 +0,0 @@
1
- task: fever11
2
- dataset_path: pminervini/hl-fever
3
- dataset_name: v1.0
4
- output_type: multiple_choice
5
- training_split: train
6
- validation_split: dev
7
- test_split: null
8
- doc_to_text: "Claim: {{claim}}\nLabel:"
9
- doc_to_choice: ["supported", "refuted"]
10
- doc_to_target: label
11
- metric_list:
12
- - metric: acc
13
- aggregation: mean
14
- higher_is_better: true
15
- metadata:
16
- version: 0.0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
open-moe-llm-leaderboard-gh/src/backend/tasks/gsm8k/gsm8k-custom.yaml DELETED
@@ -1,47 +0,0 @@
1
- group:
2
- - math_word_problems
3
- task: gsm8k_custom
4
- dataset_path: gsm8k
5
- dataset_name: main
6
- output_type: generate_until
7
- training_split: train
8
- fewshot_split: train
9
- test_split: test
10
- doc_to_text: "Question: {{question}}\nAnswer:"
11
- doc_to_target: "{{answer}}" #" {{answer.split('### ')[-1].rstrip()}}"
12
- metric_list:
13
- - metric: exact_match
14
- aggregation: mean
15
- higher_is_better: true
16
- ignore_case: true
17
- ignore_punctuation: false
18
- regexes_to_ignore:
19
- - ","
20
- - "\\$"
21
- - "(?s).*#### "
22
- - "\\.$"
23
- generation_kwargs:
24
- until:
25
- - "Question:"
26
- - "Question"
27
- - "</s>"
28
- - "<|im_end|>"
29
- do_sample: false
30
- temperature: 0.0
31
- # is_gsm8k: true
32
- repeats: 1
33
- num_fewshot: 5
34
- filter_list:
35
- - name: "strict-match"
36
- filter:
37
- - function: "regex"
38
- regex_pattern: "#### (\\-?[0-9\\.\\,]+)"
39
- - function: "take_first"
40
- - name: "flexible-extract"
41
- filter:
42
- - function: "regex"
43
- group_select: -1
44
- regex_pattern: "(-?[$0-9.,]{2,})|(-?[0-9]+)"
45
- - function: "take_first"
46
- metadata:
47
- version: 3.0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
open-moe-llm-leaderboard-gh/src/backend/tasks/halueval/halueval_dialogue.yaml DELETED
@@ -1,29 +0,0 @@
1
- task: halueval_dialogue
2
- dataset_path: pminervini/HaluEval
3
- dataset_name: dialogue_samples
4
- output_type: generate_until
5
- training_split: null
6
- validation_split: null
7
- test_split: data
8
- num_fewshot: 0
9
- doc_to_text: !function utils.doc_to_text_dialogue
10
- doc_to_target: !function utils.doc_to_target
11
- process_results: !function utils.process_results
12
- generation_kwargs:
13
- until:
14
- - "\n"
15
- - "."
16
- do_sample: false
17
- temperature: 0.0
18
- metric_list:
19
- - metric: em
20
- aggregation: mean
21
- higher_is_better: true
22
- - metric: correctness
23
- aggregation: mean
24
- higher_is_better: true
25
- - metric: acc
26
- aggregation: mean
27
- higher_is_better: true
28
- metadata:
29
- version: 0.0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
open-moe-llm-leaderboard-gh/src/backend/tasks/halueval/halueval_qa.yaml DELETED
@@ -1,29 +0,0 @@
1
- task: halueval_qa
2
- dataset_path: pminervini/HaluEval
3
- dataset_name: qa_samples
4
- output_type: generate_until
5
- training_split: null
6
- validation_split: null
7
- test_split: data
8
- num_fewshot: 0
9
- doc_to_text: !function utils.doc_to_text_qa
10
- doc_to_target: !function utils.doc_to_target
11
- process_results: !function utils.process_results
12
- generation_kwargs:
13
- until:
14
- - "\n"
15
- - "."
16
- do_sample: false
17
- temperature: 0.0
18
- metric_list:
19
- - metric: em
20
- aggregation: mean
21
- higher_is_better: true
22
- - metric: correctness
23
- aggregation: mean
24
- higher_is_better: true
25
- - metric: acc
26
- aggregation: mean
27
- higher_is_better: true
28
- metadata:
29
- version: 0.0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
open-moe-llm-leaderboard-gh/src/backend/tasks/halueval/halueval_summarization.yaml DELETED
@@ -1,29 +0,0 @@
1
- task: halueval_summarization
2
- dataset_path: pminervini/HaluEval
3
- dataset_name: summarization_samples
4
- output_type: generate_until
5
- training_split: null
6
- validation_split: null
7
- test_split: data
8
- num_fewshot: 0
9
- doc_to_text: !function utils.doc_to_text_summarization
10
- doc_to_target: !function utils.doc_to_target
11
- process_results: !function utils.process_results
12
- generation_kwargs:
13
- until:
14
- - "\n"
15
- - "."
16
- do_sample: false
17
- temperature: 0.0
18
- metric_list:
19
- - metric: em
20
- aggregation: mean
21
- higher_is_better: true
22
- - metric: correctness
23
- aggregation: mean
24
- higher_is_better: true
25
- - metric: acc
26
- aggregation: mean
27
- higher_is_better: true
28
- metadata:
29
- version: 0.0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
open-moe-llm-leaderboard-gh/src/backend/tasks/halueval/utils.py DELETED
@@ -1,154 +0,0 @@
1
- # Main reference: https://github.com/RUCAIBox/HaluEval/blob/main/evaluation/evaluate.py
2
-
3
- QA_INSTURCTIONS = """I want you act as an answer judge. Given a question and an answer, your objective is to determine if the provided answer contains non-factual or hallucinated information. You SHOULD give your judgement based on the following hallucination types and the world knowledge.
4
-
5
- You are trying to determine if the answer misunderstands the question context and intention.
6
- #Question#: What is a rare breed of dog that was derived as a variant of Rat Terrier, Shiloh Shepherd dog or American Hairless Terrier?
7
- #Answer#: American Hairless Terrier
8
- #Your Judgement#: No
9
-
10
- You are trying to determine if there is a factual contradiction between the answer and the world knowledge. Some information in the answer might be fabricated.
11
- #Question#: Are the New Orleans Outfall Canals the same length as the Augusta Canal?
12
- #Answer#: No, the New Orleans Outfall Canals and the Augusta Canal are not the same length. The Orleans Canal is approximately 3.6 miles (5.8 kilometers) long while the Augusta Canal is approximately 7 miles (11.3 kilometers) long.
13
- #Your Judgement#: Yes
14
- #Question#: What U.S Highway gives access to Zilpo Road, and is also known as Midland Trail?
15
- #Answer#: U.S Highway 70
16
- #Your Judgement#: Yes
17
-
18
- You are trying to determine if the answer is too general or too specific to answer the question at an appropriate level of specificity.
19
- #Question#: What genre do Superheaven and Oceansize belong to?
20
- #Answer#: Superheaven and Oceansize belong to the rock genre.
21
- #Your Judgement#: No
22
- #Question#: What profession do Kōbō Abe and Agatha Christie share?
23
- #Answer#: Playwright.
24
- #Your Judgement#: No
25
-
26
- You are trying to determine if the answer can be correctly inferred from the knowledge.
27
- #Question#: Which band has more members, Muse or The Raconteurs?
28
- #Answer#: Muse has more members than The Raconteurs.
29
- #Your Judgement#: Yes
30
- #Question#: Which is currently more valuable, Temagami-Lorrain Mine or Meadowbank Gold Mine?
31
- #Answer#: Meadowbank Gold Mine, since Meadowbank Gold Mine is still producing gold and the TemagamiLorrain Mine has been inactive for years.
32
- #Your Judgement#: No
33
-
34
- You should try your best to determine if the answer contains non-factual or hallucinated information according to the above hallucination types. The answer you give MUST be \"Yes\" or \"No\""."""
35
-
36
- DIALOGUE_INSTRUCTIONS = """I want you act as a response judge. Given a dialogue history and a response, your objective is to determine if the provided response contains non-factual or hallucinated information. You SHOULD give your judgement based on the following hallucination types and the world knowledge.
37
-
38
- You are trying to determine if the true entity in the response is replaced with a highly similar entity.
39
- #Dialogue History#: [Human]: Could you recommand movies similar to The Dark Knight? [Assistant]: The sequel to Batman Begins is The Dark Knight. [Human]: Okay. Who is the director of The Dark Knight and any other movies from him not related to Batman?
40
- #Response#: Christopher Nolan was the director. He also directed insomnia and inception.
41
- #Your Judgement#: No
42
- #Dialogue History#: [Human]: Could you recommand movies similar to The Dark Knight? [Assistant]: The sequel to Batman Begins is The Dark Knight. [Human]: Okay. Who is the director of The Dark Knight and any other movies from him not related to Batman?
43
- #Response#: Steven Spielberg was the director. He also directed insomnia and inception.
44
- #Your Judgement#: Yes
45
-
46
- You are trying to determine if the true entity in the response is replaced with a dissimilar entity.
47
- #Dialogue History#: [Human]: Could you recommand movies similar to The Dark Knight? [Assistant]: The sequel to Batman Begins is The Dark Knight. [Human]: Okay. Who is the director of The Dark Knight and any other movies from him not related to Batman?
48
- #Response#: Christopher Nolan was the director. He also directed insomnia and inception.
49
- #Your Judgement#: No
50
- #Dialogue History#: [Human]: Could you recommand movies similar to The Dark Knight? [Assistant]: The sequel to Batman Begins is The Dark Knight. [Human]: Okay. Who is the director of The Dark Knight and any other movies from him not related to Batman?
51
- #Response#: Batman Begins was the director. He also directed insomnia and inception.
52
- #Your Judgement#: Yes
53
-
54
- You are trying to determine if the true entity in the response is replaced with a dissimilar entity in a different entity type.
55
- #Dialogue History#: [Human]: Could you recommand movies similar to The Dark Knight? [Assistant]: The sequel to Batman Begins is The Dark Knight. [Human]: Okay. Who is the director of The Dark Knight and any other movies from him not related to Batman?
56
- #Response#: Christopher Nolan was the director. He also directed insomnia and inception.
57
- #Your Judgement#: No
58
- #Dialogue History#: [Human]: Could you recommand movies similar to The Dark Knight? [Assistant]: The sequel to Batman Begins is The Dark Knight. [Human]: Okay. Who is the director of The Dark Knight and any other movies from him not related to Batman?
59
- #Response#: United States of America was the director. He also directed insomnia and inception.
60
- #Your Judgement#: Yes
61
-
62
- You should try your best to determine if the response contains non-factual or hallucinated information according to the above hallucination types. The answer you give MUST be \"Yes\" or \"No\""."""
63
-
64
- SUMMARIZATION_INSTRUCTIONS = """I want you act as a summary judge. Given a document and a summary, your objective is to determine if the provided summary contains non-factual or hallucinated information. You SHOULD give your judgement based on the following hallucination types and the world knowledge.
65
-
66
- You are trying to determine if the summary is factual but some information cannot be directly inferred or entailed from the document.
67
- #Document#: The panther chameleon was found on Monday by a dog walker in the wooded area at Marl Park. It had to be put down after X-rays showed all of its legs were broken and it had a deformed spine. RSPCA Cymru said it was an "extremely sad example of an abandoned and neglected exotic pet". Inspector Selina Chan said: "It is a possibility that the owners took on this animal but were unable to provide the care he needs and decided to release him to the wild. "We are urging potential owners of exotic animals to thoroughly research what is required in the care of the particular species before taking one on. "Potential owners need to make sure they can give their animal the environment it needs and they have the facilities, time, financial means and long-term commitment to maintain a good standard of care, as required under the Animal Welfare Act 2006." She added it was illegal to release non-native species into the wild.
68
- #Summary#: A chameleon that was found in a Cardiff park has been put down after being abandoned and neglected by its owners.
69
- #Your Judgement#: Yes
70
-
71
- You are trying to determine if there exists some non-factual and incorrect information in the summary.
72
- #Document#: The city was brought to a standstill on 15 December last year when a gunman held 18 hostages for 17 hours. Family members of victims Tori Johnson and Katrina Dawson were in attendance. Images of the floral tributes that filled the city centre in the wake of the siege were projected on to the cafe and surrounding buildings in an emotional twilight ceremony. Prime Minister Malcolm Turnbull gave an address saying a "whole nation resolved to answer hatred with love". "Testament to the spirit of Australians is that with such unnecessary, thoughtless tragedy, an amazing birth of mateship, unity and love occurs. Proud to be Australian," he said. How the Sydney siege unfolded New South Wales Premier Mike Baird has also announced plans for a permanent memorial to be built into the pavement in Martin Place. Clear cubes containing flowers will be embedded into the concrete and will shine with specialised lighting. It is a project inspired by the massive floral tributes that were left in the days after the siege. "Something remarkable happened here. As a city we were drawn to Martin Place. We came in shock and in sorrow but every step we took was with purpose," he said on Tuesday.
73
- #Summary#: Crowds have gathered in Sydney's Martin Place to honour the victims of the Lindt cafe siege, one year on.
74
- #Your Judgement#: No
75
-
76
- You are trying to determine if there is a factual contradiction between the summary and the document.
77
- #Document#: Christopher Huxtable, 34, from Swansea, had been missing since the collapse in February. His body was found on Wednesday and workers who carried out the search formed a guard of honour as it was driven from the site in the early hours of the morning. Ken Cresswell, 57, and John Shaw, 61, both from Rotherham, remain missing. The body of a fourth man, Michael Collings, 53, from Brotton, Teesside, was previously recovered from the site. Swansea East MP Carolyn Harris, who has been involved with the family since the incident, said they still did not know all the facts about the collapse. She said: "I feel very sad. My heart and my prayers go out to the family who have waited desperately for Christopher's body to be found. They can finally have closure, and say goodbye to him and grieve his loss. "But let's not forget that there's two other families who are still waiting for their loved ones to be returned." The building was due for demolition when it partially collapsed in February.
78
- #Summary#: The body of a man whose body was found at the site of the Swansea Bay Power Station collapse has been removed from the site.
79
- #Your Judgement#: Yes
80
-
81
- You should try your best to determine if the summary contains non-factual or hallucinated information according to the above hallucination types. The answer you give MUST be \"Yes\" or \"No\""."""
82
-
83
-
84
- def doc_to_text_qa(doc: dict[str, str]) -> str:
85
- # prompt = instruction + "\n\n#Question#: " + question + "\n#Answer#: " + answer + "\n#Your Judgement#:"
86
- doc_text = (
87
- QA_INSTURCTIONS
88
- + "\n\n#Knowledge#: "
89
- + doc["knowledge"]
90
- + "\n#Question#: "
91
- + doc["question"]
92
- + "\n#Answer#: "
93
- + doc["answer"]
94
- + "\n#Your Judgement#:"
95
- )
96
- return doc_text
97
-
98
-
99
- def doc_to_text_dialogue(doc: dict[str, str]) -> str:
100
- # prompt = instruction + "\n\n#Dialogue History#: " + dialog + "\n#Response#: " + response + "\n#Your Judgement#:"
101
- doc_text = (
102
- DIALOGUE_INSTRUCTIONS
103
- + "\n\n#Knowledge#: "
104
- + doc["knowledge"]
105
- + "\n#Dialogue History#: "
106
- + doc["dialogue_history"]
107
- + "\n#Response#: "
108
- + doc["response"]
109
- + "\n#Your Judgement#:"
110
- )
111
- return doc_text
112
-
113
-
114
- def doc_to_text_summarization(doc: dict[str, str]) -> str:
115
- # prompt1 = instruction + "\n\n#Document#: " + document
116
- # prompt2 = "\n#Summary#: " + summary + "\n#Your Judgement#:"
117
- doc_text_1 = SUMMARIZATION_INSTRUCTIONS + "\n\n#Document#: " + doc["document"]
118
- doc_text_2 = "\n#Summary#: " + doc["summary"] + "\n#Your Judgement#:"
119
- doc_text = doc_text_1 + doc_text_2
120
- return doc_text
121
-
122
-
123
- def doc_to_target(doc: dict[str, str]) -> str:
124
- return doc["hallucination"]
125
-
126
-
127
- def compute_metrics(gold_answer: str, prediction: str) -> dict[str, float]:
128
- is_correct = True
129
-
130
- if ("Yes" in prediction and "No" in prediction) or ("Yes" not in prediction and "No" not in prediction):
131
- is_correct = False
132
- elif "Yes" in prediction:
133
- prediction = "yes"
134
- elif "No" in prediction:
135
- prediction = "no"
136
-
137
- is_exact = gold_answer == prediction
138
-
139
- res = {"correctness": 1.0 if is_correct else 0.0}
140
- if is_correct:
141
- res["em"] = 1.0 if is_exact else 0.0
142
-
143
- res["acc"] = 1.0 if (is_correct and is_exact) else 0.0
144
-
145
- return res
146
-
147
-
148
- def process_results(doc: dict[str, str], results: list[str]) -> dict[str, float]:
149
- # results is e.g., ['Yes']
150
- gold_list = doc_to_target(doc)
151
- # gold_list is e.g., 'yes'
152
- prediction = results[0].strip().split("\n")[0]
153
- scores = compute_metrics(gold_list, prediction)
154
- return scores
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
open-moe-llm-leaderboard-gh/src/backend/tasks/measurement_task_utils.py DELETED
@@ -1,69 +0,0 @@
1
- import functools
2
- from lm_eval.api.metrics import mean
3
-
4
-
5
- def process_results_decorator(func):
6
- # This decorator processes the results of a task before passing them to the original process_results function
7
- @functools.wraps(func)
8
- def wrapper(self, doc, results, *args, **kwargs):
9
- # We process the results here
10
- processed_results = [r[0] for r in results]
11
-
12
- end_to_end_time = sum([r[1] for r in results]) / len(results)
13
- prefilling_time = sum([r[2] for r in results]) / len(results)
14
- decoding_throughput = sum([r[3] for r in results]) / len(results)
15
- mfu = sum([r[4] for r in results]) / len(results)
16
- mbu = sum([r[5] for r in results]) / len(results)
17
-
18
- # print(f"end_to_end_time: {end_to_end_time}, prefilling_time: {prefilling_time}, decoding_throughput: {decoding_throughput}")
19
-
20
- # Now call the original process_results with the processed results
21
- result_dict = func(self, doc, processed_results, *args, **kwargs)
22
- result_dict["end_to_end_time"] = end_to_end_time
23
- result_dict["prefilling_time"] = prefilling_time
24
- result_dict["decoding_throughput"] = decoding_throughput
25
- result_dict["mfu"] = mfu
26
- result_dict["mbu"] = mbu
27
- return result_dict
28
- return wrapper
29
-
30
-
31
- def aggregation_decorator(func):
32
- @functools.wraps(func)
33
- def wrapper(self, *args, **kwargs):
34
- aggregation_list = func(self, *args, **kwargs)
35
- aggregation_list["end_to_end_time"] = mean
36
- aggregation_list["prefilling_time"] = mean
37
- aggregation_list["decoding_throughput"] = mean
38
- aggregation_list["mfu"] = mean
39
- aggregation_list["mbu"] = mean
40
- return aggregation_list
41
- return wrapper
42
-
43
-
44
- def higher_is_better_decorator(func):
45
- @functools.wraps(func)
46
- def wrapper(self, *args, **kwargs):
47
- higher_is_better_dict = func(self, *args, **kwargs)
48
- higher_is_better_dict["end_to_end_time"] = False
49
- higher_is_better_dict["prefilling_time"] = False
50
- higher_is_better_dict["decoding_throughput"] = True
51
- higher_is_better_dict["mfu"] = True
52
- higher_is_better_dict["mbu"] = True
53
- return higher_is_better_dict
54
- return wrapper
55
-
56
-
57
- def measure_system_metrics(cls):
58
- method_decorators = {
59
- 'process_results': [process_results_decorator],
60
- 'aggregation': [aggregation_decorator],
61
- 'higher_is_better': [higher_is_better_decorator],
62
- }
63
- for method_name, decorators in method_decorators.items():
64
- if callable(getattr(cls, method_name, None)):
65
- original_method = getattr(cls, method_name)
66
- for decorator in reversed(decorators):
67
- original_method = decorator(original_method)
68
- setattr(cls, method_name, original_method)
69
- return cls
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
open-moe-llm-leaderboard-gh/src/backend/tasks/memo-trap/memo-trap.yaml DELETED
@@ -1,19 +0,0 @@
1
- task: memo-trap
2
- dataset_path: pminervini/inverse-scaling
3
- dataset_name: memo-trap
4
- output_type: multiple_choice
5
- training_split: null
6
- validation_split: data
7
- test_split: null
8
- num_fewshot: 0
9
- doc_to_text: "{{prompt}}"
10
- doc_to_target: answer_index
11
- doc_to_choice: "{{classes}}"
12
- should_decontaminate: False
13
- doc_to_decontamination_query: prompt
14
- metric_list:
15
- - metric: acc
16
- aggregation: mean
17
- higher_is_better: true
18
- metadata:
19
- version: 0.0