pingnie commited on
Commit
14e4843
1 Parent(s): e91d742

delete binary files

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitignore +1 -0
  2. Makefile +13 -0
  3. README.md +9 -6
  4. app.py +366 -0
  5. backend-cli.py +309 -0
  6. blog/Hallucination-Leaderboard-Summary.csv +20 -0
  7. cli/analysis-cli.py +336 -0
  8. cli/averitec-upload-cli.py +12 -0
  9. cli/beta-cli.py +71 -0
  10. cli/completed-cli.py +124 -0
  11. cli/create_request_file.py +107 -0
  12. cli/eval-cli.py +86 -0
  13. cli/fever-upload-cli.py +73 -0
  14. cli/fix-requests-cli.py +54 -0
  15. cli/halueval-upload-cli.py +72 -0
  16. cli/isp-upload-cli.py +20 -0
  17. cli/nqswap-upload-cli.py +12 -0
  18. cli/shroom-upload-cli.py +34 -0
  19. cli/submit-cli.py +171 -0
  20. cli/sync-open-llm-cli.py +91 -0
  21. cli/truefalse-upload-cli.py +15 -0
  22. pyproject.toml +13 -0
  23. requirements.txt +32 -0
  24. src/backend/envs.py +67 -0
  25. src/backend/huggingface_generate_until.py +57 -0
  26. src/backend/manage_requests.py +113 -0
  27. src/backend/moe_infinity.py +99 -0
  28. src/backend/run_eval_suite.py +62 -0
  29. src/backend/sort_queue.py +28 -0
  30. src/backend/tasks/__init__.py +7 -0
  31. src/backend/tasks/cnndm/README.md +54 -0
  32. src/backend/tasks/cnndm/cnndm.yaml +2 -0
  33. src/backend/tasks/cnndm/cnndm_v2.yaml +2 -0
  34. src/backend/tasks/cnndm/task.py +194 -0
  35. src/backend/tasks/cnndm/task_v2.py +203 -0
  36. src/backend/tasks/faithdial/faithdial.yaml +14 -0
  37. src/backend/tasks/faithdial/faithdial_v2.yaml +14 -0
  38. src/backend/tasks/faithdial/utils.py +19 -0
  39. src/backend/tasks/fever/fever10.yaml +16 -0
  40. src/backend/tasks/fever/fever11.yaml +16 -0
  41. src/backend/tasks/halueval/halueval_dialogue.yaml +29 -0
  42. src/backend/tasks/halueval/halueval_qa.yaml +29 -0
  43. src/backend/tasks/halueval/halueval_summarization.yaml +29 -0
  44. src/backend/tasks/halueval/utils.py +136 -0
  45. src/backend/tasks/memo-trap/memo-trap.yaml +19 -0
  46. src/backend/tasks/memo-trap/memo-trap_v2.yaml +20 -0
  47. src/backend/tasks/nq8/README.md +0 -0
  48. src/backend/tasks/nq8/nq8.yaml +32 -0
  49. src/backend/tasks/nq_swap/nq_swap.yaml +31 -0
  50. src/backend/tasks/selfcheckgpt/README.md +94 -0
.gitignore CHANGED
@@ -1 +1,2 @@
1
  *ipynb
 
 
1
  *ipynb
2
+ *_pycache_*
Makefile ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .PHONY: style format
2
+
3
+
4
+ style:
5
+ python -m black --line-length 119 .
6
+ python -m isort .
7
+ ruff check --fix .
8
+
9
+
10
+ quality:
11
+ python -m black --check --line-length 119 .
12
+ python -m isort --check-only .
13
+ ruff check .
README.md CHANGED
@@ -1,13 +1,16 @@
1
  ---
2
- title: MOE LLM GPU Poor Leaderboard
3
- emoji: 👁
4
- colorFrom: indigo
5
- colorTo: red
6
  sdk: gradio
7
- sdk_version: 4.21.0
8
  app_file: app.py
9
- pinned: false
10
  license: apache-2.0
 
 
 
11
  ---
12
 
13
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
  ---
2
+ title: MOE-LLM-GPU-POOR_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
app.py ADDED
@@ -0,0 +1,366 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ import os
4
+ import datetime
5
+ import socket
6
+
7
+ import gradio as gr
8
+ import pandas as pd
9
+
10
+ from apscheduler.schedulers.background import BackgroundScheduler
11
+
12
+ from huggingface_hub import snapshot_download
13
+
14
+ from src.display.about import (
15
+ CITATION_BUTTON_LABEL,
16
+ CITATION_BUTTON_TEXT,
17
+ EVALUATION_QUEUE_TEXT,
18
+ INTRODUCTION_TEXT,
19
+ LLM_BENCHMARKS_TEXT,
20
+ LLM_BENCHMARKS_DETAILS,
21
+ FAQ_TEXT,
22
+ TITLE
23
+ )
24
+
25
+ from src.display.css_html_js import custom_css
26
+
27
+ from src.display.utils import (
28
+ BENCHMARK_COLS,
29
+ COLS,
30
+ EVAL_COLS,
31
+ EVAL_TYPES,
32
+ NUMERIC_INTERVALS,
33
+ TYPES,
34
+ AutoEvalColumn,
35
+ ModelType,
36
+ fields,
37
+ WeightType,
38
+ Precision
39
+ )
40
+
41
+ from src.envs import API, EVAL_REQUESTS_PATH, EVAL_RESULTS_PATH, H4_TOKEN, IS_PUBLIC, QUEUE_REPO, REPO_ID, RESULTS_REPO
42
+ from src.populate import get_evaluation_queue_df, get_leaderboard_df
43
+ from src.submission.submit import add_new_eval
44
+ from src.utils import get_dataset_summary_table
45
+
46
+
47
+ def ui_snapshot_download(repo_id, local_dir, repo_type, tqdm_class, etag_timeout):
48
+ try:
49
+ print(local_dir)
50
+ snapshot_download(repo_id=repo_id, local_dir=local_dir, repo_type=repo_type, tqdm_class=tqdm_class, etag_timeout=etag_timeout)
51
+ except Exception as e:
52
+ restart_space()
53
+
54
+
55
+ def restart_space():
56
+ API.restart_space(repo_id=REPO_ID, token=H4_TOKEN)
57
+
58
+
59
+ def init_space():
60
+ dataset_df = get_dataset_summary_table(file_path='blog/Hallucination-Leaderboard-Summary.csv')
61
+
62
+ if socket.gethostname() not in {'neuromancer'}:
63
+ # sync model_type with open-llm-leaderboard
64
+ ui_snapshot_download(repo_id=QUEUE_REPO, local_dir=EVAL_REQUESTS_PATH, repo_type="dataset", tqdm_class=None, etag_timeout=30)
65
+ ui_snapshot_download(repo_id=RESULTS_REPO, local_dir=EVAL_RESULTS_PATH, repo_type="dataset", tqdm_class=None, etag_timeout=30)
66
+ raw_data, original_df = get_leaderboard_df(EVAL_RESULTS_PATH, EVAL_REQUESTS_PATH, "", COLS, BENCHMARK_COLS)
67
+
68
+ finished_eval_queue_df, running_eval_queue_df, pending_eval_queue_df = get_evaluation_queue_df(EVAL_REQUESTS_PATH, EVAL_COLS)
69
+ return dataset_df, original_df, finished_eval_queue_df, running_eval_queue_df, pending_eval_queue_df
70
+
71
+
72
+ dataset_df, original_df, finished_eval_queue_df, running_eval_queue_df, pending_eval_queue_df = init_space()
73
+ leaderboard_df = original_df.copy()
74
+
75
+
76
+ # Searching and filtering
77
+ def update_table(hidden_df: pd.DataFrame,
78
+ columns: list,
79
+ type_query: list,
80
+ precision_query: list,
81
+ size_query: list,
82
+ query: str):
83
+ filtered_df = filter_models(hidden_df, type_query, size_query, precision_query)
84
+ filtered_df = filter_queries(query, filtered_df)
85
+ df = select_columns(filtered_df, columns)
86
+ return df
87
+
88
+
89
+ def search_table(df: pd.DataFrame, query: str) -> pd.DataFrame:
90
+ return df[(df[AutoEvalColumn.dummy.name].str.contains(query, case=False))]
91
+
92
+
93
+ def select_columns(df: pd.DataFrame, columns: list) -> pd.DataFrame:
94
+ # always_here_cols = [AutoEvalColumn.model_type_symbol.name, AutoEvalColumn.model.name]
95
+
96
+ always_here_cols = [c.name for c in fields(AutoEvalColumn) if c.never_hidden]
97
+ dummy_col = [AutoEvalColumn.dummy.name]
98
+
99
+ # We use COLS to maintain sorting
100
+ filtered_df = df[
101
+ # always_here_cols + [c for c in COLS if c in df.columns and c in columns] + [AutoEvalColumn.dummy.name]
102
+ always_here_cols + [c for c in COLS if c in df.columns and c in columns] + dummy_col
103
+ ]
104
+ return filtered_df
105
+
106
+
107
+ def filter_queries(query: str, filtered_df: pd.DataFrame):
108
+ final_df = []
109
+ if query != "":
110
+ queries = [q.strip() for q in query.split(";")]
111
+ for _q in queries:
112
+ _q = _q.strip()
113
+ if _q != "":
114
+ temp_filtered_df = search_table(filtered_df, _q)
115
+ if len(temp_filtered_df) > 0:
116
+ final_df.append(temp_filtered_df)
117
+ if len(final_df) > 0:
118
+ filtered_df = pd.concat(final_df)
119
+ subset = [AutoEvalColumn.model.name, AutoEvalColumn.precision.name, AutoEvalColumn.revision.name]
120
+ filtered_df = filtered_df.drop_duplicates(subset=subset)
121
+ return filtered_df
122
+
123
+
124
+ def filter_models(df: pd.DataFrame,
125
+ type_query: list,
126
+ size_query: list,
127
+ precision_query: list) -> pd.DataFrame:
128
+ # Show all models
129
+ filtered_df = df
130
+
131
+ type_emoji = [t[0] for t in type_query]
132
+ filtered_df = filtered_df.loc[df[AutoEvalColumn.model_type_symbol.name].isin(type_emoji)]
133
+ filtered_df = filtered_df.loc[df[AutoEvalColumn.precision.name].isin(precision_query + ["None"])]
134
+
135
+ numeric_interval = pd.IntervalIndex(sorted([NUMERIC_INTERVALS[s] for s in size_query]))
136
+ params_column = pd.to_numeric(df[AutoEvalColumn.params.name], errors="coerce")
137
+ mask = params_column.apply(lambda x: any(numeric_interval.contains(x)))
138
+ filtered_df = filtered_df.loc[mask]
139
+
140
+ return filtered_df
141
+
142
+
143
+ # triggered only once at startup => read query parameter if it exists
144
+ def load_query(request: gr.Request):
145
+ query = request.query_params.get("query") or ""
146
+ return query
147
+
148
+
149
+ demo = gr.Blocks(css=custom_css)
150
+ with demo:
151
+ gr.HTML(TITLE)
152
+ gr.Markdown(INTRODUCTION_TEXT, elem_classes="markdown-text")
153
+
154
+ with gr.Tabs(elem_classes="tab-buttons") as tabs:
155
+ with gr.TabItem("Hallucinations Benchmark",
156
+ elem_id="llm-benchmark-tab-table",
157
+ id=0):
158
+ with gr.Row():
159
+ with gr.Column():
160
+ with gr.Row():
161
+ search_bar = gr.Textbox(placeholder=" 🔍 Model search (separate multiple queries with `;`)",
162
+ show_label=False,
163
+ elem_id="search-bar")
164
+ with gr.Row():
165
+ shown_columns = gr.CheckboxGroup(
166
+ choices=[
167
+ c.name
168
+ for c in fields(AutoEvalColumn)
169
+ if not c.hidden and not c.never_hidden and not c.dummy
170
+ ],
171
+ value=[
172
+ c.name
173
+ for c in fields(AutoEvalColumn)
174
+ if c.displayed_by_default and not c.hidden and not c.never_hidden
175
+ ],
176
+ label="Select columns to show",
177
+ elem_id="column-select",
178
+ interactive=True)
179
+
180
+ with gr.Column(min_width=320):
181
+ filter_columns_type = gr.CheckboxGroup(
182
+ label="Model types",
183
+ choices=[t.to_str() for t in ModelType],
184
+ value=[t.to_str() for t in ModelType],
185
+ interactive=True,
186
+ elem_id="filter-columns-type")
187
+
188
+ filter_columns_precision = gr.CheckboxGroup(
189
+ label="Precision",
190
+ choices=[i.value.name for i in Precision],
191
+ value=[i.value.name for i in Precision],
192
+ interactive=True,
193
+ elem_id="filter-columns-precision")
194
+
195
+ filter_columns_size = gr.CheckboxGroup(
196
+ label="Model sizes (in billions of parameters)",
197
+ choices=list(NUMERIC_INTERVALS.keys()),
198
+ value=list(NUMERIC_INTERVALS.keys()),
199
+ interactive=True,
200
+ elem_id="filter-columns-size")
201
+
202
+ # breakpoint()
203
+
204
+ leaderboard_table = gr.components.Dataframe(
205
+ value=leaderboard_df[
206
+ [c.name for c in fields(AutoEvalColumn) if c.never_hidden] + shown_columns.value + [AutoEvalColumn.dummy.name]
207
+ ] if leaderboard_df.empty is False else leaderboard_df,
208
+ headers=[c.name for c in fields(AutoEvalColumn) if c.never_hidden] + shown_columns.value,
209
+ datatype=TYPES,
210
+ elem_id="leaderboard-table",
211
+ interactive=False,
212
+ visible=True) # column_widths=["2%", "20%"]
213
+
214
+ # Dummy leaderboard for handling the case when the user uses backspace key
215
+ hidden_leaderboard_table_for_search = gr.components.Dataframe(
216
+ value=original_df[COLS] if original_df.empty is False else original_df,
217
+ headers=COLS,
218
+ datatype=TYPES,
219
+ visible=False)
220
+
221
+ search_bar.submit(
222
+ update_table,
223
+ [
224
+ hidden_leaderboard_table_for_search,
225
+ shown_columns,
226
+ filter_columns_type,
227
+ filter_columns_precision,
228
+ filter_columns_size,
229
+ search_bar,
230
+ ],
231
+ leaderboard_table)
232
+
233
+ # Check query parameter once at startup and update search bar
234
+ demo.load(load_query, inputs=[], outputs=[search_bar])
235
+
236
+ for selector in [shown_columns, filter_columns_type, filter_columns_precision, filter_columns_size]:
237
+ selector.change(
238
+ update_table,
239
+ [
240
+ hidden_leaderboard_table_for_search,
241
+ shown_columns,
242
+ filter_columns_type,
243
+ filter_columns_precision,
244
+ filter_columns_size,
245
+ search_bar,
246
+ ],
247
+ leaderboard_table,
248
+ queue=True)
249
+
250
+ with gr.TabItem("About", elem_id="llm-benchmark-tab-table", id=2):
251
+ gr.Markdown(LLM_BENCHMARKS_TEXT, elem_classes="markdown-text")
252
+
253
+ dataset_table = gr.components.Dataframe(
254
+ value=dataset_df,
255
+ headers=list(dataset_df.columns),
256
+ datatype=['str', 'markdown', 'str', 'str', 'str'],
257
+ elem_id="dataset-table",
258
+ interactive=False,
259
+ visible=True,
260
+ column_widths=["15%", "20%"])
261
+
262
+ gr.Markdown(LLM_BENCHMARKS_DETAILS, elem_classes="markdown-text")
263
+ gr.Markdown(FAQ_TEXT, elem_classes="markdown-text")
264
+
265
+ with gr.TabItem("Submit a model ", elem_id="llm-benchmark-tab-table", id=3):
266
+ with gr.Column():
267
+ with gr.Row():
268
+ gr.Markdown(EVALUATION_QUEUE_TEXT, elem_classes="markdown-text")
269
+
270
+ with gr.Column():
271
+ with gr.Accordion(f"✅ Finished Evaluations ({len(finished_eval_queue_df)})", open=False):
272
+ with gr.Row():
273
+ finished_eval_table = gr.components.Dataframe(
274
+ value=finished_eval_queue_df,
275
+ headers=EVAL_COLS,
276
+ datatype=EVAL_TYPES,
277
+ row_count=5)
278
+
279
+ with gr.Accordion(f"🔄 Running Evaluation Queue ({len(running_eval_queue_df)})", open=False):
280
+ with gr.Row():
281
+ running_eval_table = gr.components.Dataframe(
282
+ value=running_eval_queue_df,
283
+ headers=EVAL_COLS,
284
+ datatype=EVAL_TYPES,
285
+ row_count=5)
286
+
287
+ with gr.Accordion(f"⏳ Scheduled Evaluation Queue ({len(pending_eval_queue_df)})", open=False):
288
+ with gr.Row():
289
+ pending_eval_table = gr.components.Dataframe(
290
+ value=pending_eval_queue_df,
291
+ headers=EVAL_COLS,
292
+ datatype=EVAL_TYPES,
293
+ row_count=5)
294
+
295
+ with gr.Row():
296
+ gr.Markdown("# Submit your model here", elem_classes="markdown-text")
297
+
298
+ with gr.Row():
299
+ with gr.Column():
300
+ model_name_textbox = gr.Textbox(label="Model name")
301
+ revision_name_textbox = gr.Textbox(label="Revision commit", placeholder="main")
302
+ private = gr.Checkbox(False, label="Private", visible=not IS_PUBLIC)
303
+ model_type = gr.Dropdown(
304
+ choices=[t.to_str(" : ") for t in ModelType if t != ModelType.Unknown],
305
+ label="Model type",
306
+ multiselect=False,
307
+ value=None,
308
+ interactive=True)
309
+
310
+ with gr.Column():
311
+ precision = gr.Dropdown(
312
+ choices=[i.value.name for i in Precision if i != Precision.Unknown],
313
+ label="Precision",
314
+ multiselect=False,
315
+ value="float32",
316
+ interactive=True)
317
+
318
+ weight_type = gr.Dropdown(
319
+ choices=[i.value.name for i in WeightType],
320
+ label="Weights type",
321
+ multiselect=False,
322
+ value="Original",
323
+ interactive=True)
324
+
325
+ base_model_name_textbox = gr.Textbox(label="Base model (for delta or adapter weights)")
326
+
327
+ submit_button = gr.Button("Submit Eval")
328
+ submission_result = gr.Markdown()
329
+ submit_button.click(
330
+ add_new_eval,
331
+ [
332
+ model_name_textbox,
333
+ base_model_name_textbox,
334
+ revision_name_textbox,
335
+ precision,
336
+ private,
337
+ weight_type,
338
+ model_type,
339
+ ],
340
+ submission_result)
341
+
342
+ with gr.Row():
343
+ with gr.Accordion("Citing this leaderboard", open=False):
344
+ citation_button = gr.Textbox(
345
+ value=CITATION_BUTTON_TEXT,
346
+ label=CITATION_BUTTON_LABEL,
347
+ lines=20,
348
+ elem_id="citation-button",
349
+ show_copy_button=True)
350
+
351
+ scheduler = BackgroundScheduler()
352
+
353
+ scheduler.add_job(restart_space, "interval", seconds=6 * 60 * 60)
354
+
355
+
356
+ def launch_backend():
357
+ import subprocess
358
+ from src.backend.envs import DEVICE
359
+ if DEVICE not in {'cpu'}:
360
+ _ = subprocess.run(["python", "backend-cli.py"])
361
+
362
+
363
+ # scheduler.add_job(launch_backend, "interval", seconds=120)
364
+
365
+ scheduler.start()
366
+ demo.queue(default_concurrency_limit=40).launch()
backend-cli.py ADDED
@@ -0,0 +1,309 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ import os
4
+ import json
5
+
6
+ import socket
7
+ import random
8
+ from datetime import datetime
9
+
10
+ from src.backend.run_eval_suite import run_evaluation
11
+ from src.backend.manage_requests import check_completed_evals, get_eval_requests, set_eval_request
12
+ from src.backend.sort_queue import sort_models_by_priority
13
+ from src.backend.envs import Tasks, EVAL_REQUESTS_PATH_BACKEND, EVAL_RESULTS_PATH_BACKEND, DEVICE, LIMIT, Task
14
+
15
+ from src.backend.manage_requests import EvalRequest
16
+ from src.leaderboard.read_evals import EvalResult
17
+
18
+ from src.envs import QUEUE_REPO, RESULTS_REPO, API
19
+ from src.utils import my_snapshot_download
20
+
21
+ from src.leaderboard.read_evals import get_raw_eval_results
22
+
23
+ from typing import Optional
24
+
25
+ import time
26
+
27
+ import logging
28
+ import pprint
29
+
30
+
31
+ def my_set_eval_request(api, eval_request, set_to_status, hf_repo, local_dir):
32
+ for i in range(10):
33
+ try:
34
+ set_eval_request(api=api, eval_request=eval_request, set_to_status=set_to_status, hf_repo=hf_repo, local_dir=local_dir)
35
+ return
36
+ except Exception:
37
+ time.sleep(60)
38
+ return
39
+
40
+
41
+ logging.getLogger("openai").setLevel(logging.WARNING)
42
+
43
+ logging.basicConfig(level=logging.ERROR)
44
+ pp = pprint.PrettyPrinter(width=80)
45
+
46
+ PENDING_STATUS = "PENDING"
47
+ RUNNING_STATUS = "RUNNING"
48
+ FINISHED_STATUS = "FINISHED"
49
+ FAILED_STATUS = "FAILED"
50
+
51
+ TASKS_HARNESS = [task.value for task in Tasks]
52
+
53
+
54
+ my_snapshot_download(repo_id=RESULTS_REPO, revision="main", local_dir=EVAL_RESULTS_PATH_BACKEND, repo_type="dataset", max_workers=60)
55
+ my_snapshot_download(repo_id=QUEUE_REPO, revision="main", local_dir=EVAL_REQUESTS_PATH_BACKEND, repo_type="dataset", max_workers=60)
56
+
57
+
58
+ def sanity_checks():
59
+ print(f'Device: {DEVICE}')
60
+
61
+ # pull the eval dataset from the hub and parse any eval requests
62
+ # check completed evals and set them to finished
63
+ my_snapshot_download(repo_id=QUEUE_REPO, revision="main", local_dir=EVAL_REQUESTS_PATH_BACKEND, repo_type="dataset", max_workers=60)
64
+ check_completed_evals(api=API, checked_status=RUNNING_STATUS, completed_status=FINISHED_STATUS,
65
+ failed_status=FAILED_STATUS, hf_repo=QUEUE_REPO, local_dir=EVAL_REQUESTS_PATH_BACKEND,
66
+ hf_repo_results=RESULTS_REPO, local_dir_results=EVAL_RESULTS_PATH_BACKEND)
67
+ return
68
+
69
+
70
+ def request_to_result_name(request: EvalRequest) -> str:
71
+ # Request: EvalRequest(model='meta-llama/Llama-2-13b-hf', private=False, status='FINISHED',
72
+ # json_filepath='./eval-queue-bk/meta-llama/Llama-2-13b-hf_eval_request_False_False_False.json',
73
+ # weight_type='Original', model_type='pretrained', precision='float32', base_model='', revision='main',
74
+ # submitted_time='2023-09-09T10:52:17Z', likes=389, params=13.016, license='?')
75
+ #
76
+ # EvalResult(eval_name='meta-llama_Llama-2-13b-hf_float32', full_model='meta-llama/Llama-2-13b-hf',
77
+ # org='meta-llama', model='Llama-2-13b-hf', revision='main',
78
+ # results={'nq_open': 33.739612188365655, 'triviaqa': 74.12505572893447},
79
+ # precision=<Precision.float32: ModelDetails(name='float32', symbol='')>,
80
+ # model_type=<ModelType.PT: ModelDetails(name='pretrained', symbol='🟢')>,
81
+ # weight_type=<WeightType.Original: ModelDetails(name='Original', symbol='')>,
82
+ # architecture='LlamaForCausalLM', license='?', likes=389, num_params=13.016, date='2023-09-09T10:52:17Z', still_on_hub=True)
83
+ #
84
+ org_and_model = request.model.split("/", 1)
85
+ if len(org_and_model) == 1:
86
+ model = org_and_model[0]
87
+ res = f"{model}_{request.precision}"
88
+ else:
89
+ org = org_and_model[0]
90
+ model = org_and_model[1]
91
+ res = f"{org}_{model}_{request.precision}"
92
+ return res
93
+
94
+
95
+ def process_evaluation(task: Task, eval_request: EvalRequest) -> dict:
96
+ batch_size = 2
97
+ try:
98
+ results = run_evaluation(eval_request=eval_request, task_names=[task.benchmark], num_fewshot=task.num_fewshot,
99
+ batch_size=batch_size, device=DEVICE, use_cache=None, limit=LIMIT)
100
+ except RuntimeError as e:
101
+ if "No executable batch size found" in str(e):
102
+ batch_size = 1
103
+ results = run_evaluation(eval_request=eval_request, task_names=[task.benchmark], num_fewshot=task.num_fewshot,
104
+ batch_size=batch_size, device=DEVICE, use_cache=None, limit=LIMIT)
105
+ else:
106
+ raise
107
+
108
+ print('RESULTS', results)
109
+
110
+ dumped = json.dumps(results, indent=2, default=lambda o: '<not serializable>')
111
+ print(dumped)
112
+
113
+ output_path = os.path.join(EVAL_RESULTS_PATH_BACKEND, *eval_request.model.split("/"), f"results_{datetime.now()}.json")
114
+ os.makedirs(os.path.dirname(output_path), exist_ok=True)
115
+ with open(output_path, "w") as f:
116
+ f.write(dumped)
117
+
118
+ my_snapshot_download(repo_id=RESULTS_REPO, revision="main", local_dir=EVAL_RESULTS_PATH_BACKEND, repo_type="dataset", max_workers=60)
119
+ API.upload_file(path_or_fileobj=output_path, path_in_repo=f"{eval_request.model}/results_{datetime.now()}.json",
120
+ repo_id=RESULTS_REPO, repo_type="dataset")
121
+ return results
122
+
123
+
124
+ def process_finished_requests(thr: int, hard_task_lst: Optional[list[str]] = None) -> bool:
125
+ sanity_checks()
126
+
127
+ current_finished_status = [FINISHED_STATUS, FAILED_STATUS]
128
+
129
+ # Get all eval request that are FINISHED, if you want to run other evals, change this parameter
130
+ eval_requests: list[EvalRequest] = get_eval_requests(job_status=current_finished_status, hf_repo=QUEUE_REPO, local_dir=EVAL_REQUESTS_PATH_BACKEND)
131
+ # Sort the evals by priority (first submitted, first run)
132
+ eval_requests: list[EvalRequest] = sort_models_by_priority(api=API, models=eval_requests)
133
+
134
+ random.shuffle(eval_requests)
135
+
136
+ eval_results: list[EvalResult] = get_raw_eval_results(EVAL_RESULTS_PATH_BACKEND, EVAL_REQUESTS_PATH_BACKEND)
137
+
138
+ result_name_to_request = {request_to_result_name(r): r for r in eval_requests}
139
+ result_name_to_result = {r.eval_name: r for r in eval_results}
140
+
141
+ for eval_request in eval_requests:
142
+ if eval_request.likes >= thr:
143
+ result_name: str = request_to_result_name(eval_request)
144
+
145
+ # Check the corresponding result
146
+ eval_result: Optional[EvalResult] = result_name_to_result[result_name] if result_name in result_name_to_result else None
147
+
148
+ # breakpoint()
149
+
150
+ task_lst = TASKS_HARNESS.copy()
151
+ random.shuffle(task_lst)
152
+
153
+ # Iterate over tasks and, if we do not have results for a task, run the relevant evaluations
154
+ for task in task_lst:
155
+ task_name = task.benchmark
156
+
157
+ do_run_task = False
158
+ if hard_task_lst is None or any(ss in task_name for ss in hard_task_lst):
159
+ do_run_task = True
160
+
161
+ if (eval_result is None or task_name not in eval_result.results) and do_run_task:
162
+ eval_request: EvalRequest = result_name_to_request[result_name]
163
+
164
+ my_snapshot_download(repo_id=QUEUE_REPO, revision="main", local_dir=EVAL_REQUESTS_PATH_BACKEND, repo_type="dataset", max_workers=60)
165
+ my_set_eval_request(api=API, eval_request=eval_request, set_to_status=RUNNING_STATUS, hf_repo=QUEUE_REPO, local_dir=EVAL_REQUESTS_PATH_BACKEND)
166
+
167
+ results = process_evaluation(task, eval_request)
168
+
169
+ my_snapshot_download(repo_id=QUEUE_REPO, revision="main", local_dir=EVAL_REQUESTS_PATH_BACKEND, repo_type="dataset", max_workers=60)
170
+ my_set_eval_request(api=API, eval_request=eval_request, set_to_status=FINISHED_STATUS, hf_repo=QUEUE_REPO, local_dir=EVAL_REQUESTS_PATH_BACKEND)
171
+
172
+ return True
173
+
174
+ return False
175
+
176
+
177
+ def maybe_refresh_results(thr: int, hard_task_lst: Optional[list[str]] = None) -> bool:
178
+ sanity_checks()
179
+
180
+ current_finished_status = [PENDING_STATUS, FINISHED_STATUS, FAILED_STATUS]
181
+
182
+ # Get all eval request that are FINISHED, if you want to run other evals, change this parameter
183
+ eval_requests: list[EvalRequest] = get_eval_requests(job_status=current_finished_status, hf_repo=QUEUE_REPO, local_dir=EVAL_REQUESTS_PATH_BACKEND)
184
+ # Sort the evals by priority (first submitted, first run)
185
+ eval_requests: list[EvalRequest] = sort_models_by_priority(api=API, models=eval_requests)
186
+
187
+ random.shuffle(eval_requests)
188
+
189
+ eval_results: list[EvalResult] = get_raw_eval_results(EVAL_RESULTS_PATH_BACKEND, EVAL_REQUESTS_PATH_BACKEND)
190
+
191
+ result_name_to_request = {request_to_result_name(r): r for r in eval_requests}
192
+ result_name_to_result = {r.eval_name: r for r in eval_results}
193
+
194
+ for eval_request in eval_requests:
195
+ if eval_request.likes >= thr:
196
+ result_name: str = request_to_result_name(eval_request)
197
+
198
+ # Check the corresponding result
199
+ eval_result: Optional[EvalResult] = result_name_to_result[result_name] if result_name in result_name_to_result else None
200
+
201
+ task_lst = TASKS_HARNESS.copy()
202
+ random.shuffle(task_lst)
203
+
204
+ # Iterate over tasks and, if we do not have results for a task, run the relevant evaluations
205
+ for task in task_lst:
206
+ task_name = task.benchmark
207
+
208
+ do_run_task = False
209
+ if hard_task_lst is None or any(ss in task_name for ss in hard_task_lst):
210
+ do_run_task = True
211
+
212
+ task_lst = ['nq', 'trivia', 'tqa', 'self']
213
+ if (eval_result is None or do_run_task or task_name not in eval_result.results or
214
+ any(ss in task_name for ss in task_lst)):
215
+ eval_request: EvalRequest = result_name_to_request[result_name]
216
+
217
+ my_snapshot_download(repo_id=QUEUE_REPO, revision="main", local_dir=EVAL_REQUESTS_PATH_BACKEND, repo_type="dataset", max_workers=60)
218
+ my_set_eval_request(api=API, eval_request=eval_request, set_to_status=RUNNING_STATUS, hf_repo=QUEUE_REPO, local_dir=EVAL_REQUESTS_PATH_BACKEND)
219
+
220
+ results = process_evaluation(task, eval_request)
221
+
222
+ my_snapshot_download(repo_id=QUEUE_REPO, revision="main", local_dir=EVAL_REQUESTS_PATH_BACKEND, repo_type="dataset", max_workers=60)
223
+ my_set_eval_request(api=API, eval_request=eval_request, set_to_status=FINISHED_STATUS, hf_repo=QUEUE_REPO, local_dir=EVAL_REQUESTS_PATH_BACKEND)
224
+
225
+ return True
226
+
227
+ return False
228
+
229
+
230
+ def process_pending_requests() -> bool:
231
+ sanity_checks()
232
+
233
+ current_pending_status = [PENDING_STATUS]
234
+
235
+ # Get all eval request that are PENDING, if you want to run other evals, change this parameter
236
+ eval_requests = get_eval_requests(job_status=current_pending_status, hf_repo=QUEUE_REPO, local_dir=EVAL_REQUESTS_PATH_BACKEND)
237
+ # Sort the evals by priority (first submitted, first run)
238
+ eval_requests = sort_models_by_priority(api=API, models=eval_requests)
239
+
240
+ random.shuffle(eval_requests)
241
+
242
+ print(f"Found {len(eval_requests)} {','.join(current_pending_status)} eval requests")
243
+
244
+ if len(eval_requests) == 0:
245
+ return False
246
+
247
+ eval_request = eval_requests[0]
248
+ pp.pprint(eval_request)
249
+
250
+ my_snapshot_download(repo_id=QUEUE_REPO, revision="main", local_dir=EVAL_REQUESTS_PATH_BACKEND, repo_type="dataset", max_workers=60)
251
+ my_set_eval_request(api=API, eval_request=eval_request, set_to_status=RUNNING_STATUS, hf_repo=QUEUE_REPO, local_dir=EVAL_REQUESTS_PATH_BACKEND)
252
+
253
+ task_lst = TASKS_HARNESS.copy()
254
+ random.shuffle(task_lst)
255
+
256
+ for task in task_lst:
257
+ results = process_evaluation(task, eval_request)
258
+
259
+ my_snapshot_download(repo_id=QUEUE_REPO, revision="main", local_dir=EVAL_REQUESTS_PATH_BACKEND, repo_type="dataset", max_workers=60)
260
+ my_set_eval_request(api=API, eval_request=eval_request, set_to_status=FINISHED_STATUS, hf_repo=QUEUE_REPO, local_dir=EVAL_REQUESTS_PATH_BACKEND)
261
+
262
+ return True
263
+
264
+
265
+ if __name__ == "__main__":
266
+ local_debug = True
267
+ #debug specific task by ping
268
+ if local_debug:
269
+ debug_model_names = ['mistralai/Mixtral-8x7B-Instruct-v0.1']
270
+ debug_model_names = ["TheBloke/Mixtral-8x7B-v0.1-GPTQ"]
271
+ # debug_task_name = 'ifeval'
272
+ debug_task_name = 'selfcheckgpt'
273
+ task_lst = TASKS_HARNESS.copy()
274
+ for task in task_lst:
275
+ for debug_model_name in debug_model_names:
276
+ task_name = task.benchmark
277
+ if task_name != debug_task_name:
278
+ continue
279
+ eval_request = EvalRequest(model=debug_model_name, private=False, status='', json_filepath='', precision='float16')
280
+ results = process_evaluation(task, eval_request)
281
+
282
+ wait = True
283
+ hard_task_lst = None
284
+ if socket.gethostname() in {'hamburg', 'neuromancer'} or os.path.isdir("/home/pminervi"):
285
+ wait = False
286
+ hard_task_lst = ['nq', 'trivia', 'tqa']
287
+
288
+ if wait:
289
+ time.sleep(60 * random.randint(5, 10))
290
+
291
+ res = False
292
+
293
+ if random.randint(0, 10) == 0:
294
+ res = process_pending_requests()
295
+ time.sleep(60)
296
+
297
+ if res is False:
298
+ if random.randint(0, 5) == 0:
299
+ res = maybe_refresh_results(100, hard_task_lst=hard_task_lst)
300
+ else:
301
+ res = process_finished_requests(100, hard_task_lst=hard_task_lst)
302
+
303
+ time.sleep(60)
304
+
305
+ if res is False:
306
+ if random.randint(0, 5) == 0:
307
+ res = maybe_refresh_results(0, hard_task_lst=hard_task_lst)
308
+ else:
309
+ res = process_finished_requests(0, hard_task_lst=hard_task_lst)
blog/Hallucination-Leaderboard-Summary.csv ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Category,Benchmark,Dataset Link,Data Split,Data Size,Language
2
+ Closed-book Open-domain QA ,NQ Open (64-shot),https://huggingface.co/datasets/nq_open/viewer/nq_open/validation,validation,3.61k,En
3
+ Closed-book Open-domain QA ,NQ Open (8-shot),https://huggingface.co/datasets/nq_open/viewer/nq_open/validation,validation,3.61k,En
4
+ Closed-book Open-domain QA ,TriviaQA (64-shot),https://huggingface.co/datasets/trivia_qa/viewer/rc.nocontext/test,test,17.2k,En
5
+ Closed-book Open-domain QA ,TriviaQA 8 (8-shot),https://huggingface.co/datasets/trivia_qa/viewer/rc.nocontext/test,test,17.2k,En
6
+ Closed-book Open-domain QA ,TruthfulQA MC1 (0-shot),https://huggingface.co/datasets/truthful_qa/viewer/multiple_choice,mc1_targets column,0.8k,En
7
+ Closed-book Open-domain QA ,TruthfulQA MC2 (0-shot),https://huggingface.co/datasets/truthful_qa/viewer/multiple_choice,mc2_targets column,0.8k,En
8
+ Fact-Checking,FEVER (16-shot),https://huggingface.co/datasets/fever/viewer/v1.0/labelled_dev,labeld_dev,37.6k,En
9
+ Hallucination Detection,FaithDial (8-shot),https://huggingface.co/datasets/McGill-NLP/FaithDial,test,3.54k,En
10
+ Hallucination Detection,HaluEval QA (0-shot),https://huggingface.co/datasets/pminervini/HaluEval/viewer/qa_samples,qa_samples,10k,En
11
+ Hallucination Detection,HaluEval Summ (0-shot),https://huggingface.co/datasets/pminervini/HaluEval/viewer/summarization_samples,summarization_samples,10k,En
12
+ Hallucination Detection,HaluEval Dial (0-shot),https://huggingface.co/datasets/pminervini/HaluEval/viewer/dialogue_samples,dialogue_samples,10k,En
13
+ Hallucination Detection,TrueFalse (8-shot),https://huggingface.co/datasets/pminervini/true-false/viewer/default/cieacf,cieacf,6.09k,En
14
+ Instruction Following,MemoTrap (0-shot),https://huggingface.co/datasets/pminervini/inverse-scaling/viewer/memo-trap,memo-trap,0.9k,En
15
+ Instruction Following,IFEval (0-shot),https://huggingface.co/datasets/wis-k/instruction-following-eval,train,0.5k,En
16
+ Reading Comprehension,SQuADv2 (4-shot),https://huggingface.co/datasets/squad_v2/viewer/squad_v2/validation,validation,11.9k,En
17
+ Reading Comprehension,RACE (0-shot),https://huggingface.co/datasets/EleutherAI/race,test,1.05k,En
18
+ Self-Consistency,SelfCheckGPT (0-shot),https://huggingface.co/datasets/potsawee/wiki_bio_gpt3_hallucination,validation,0.2k,En
19
+ Summarisation,XSum (2-shot),https://huggingface.co/datasets/EdinburghNLP/xsum/viewer/default/test,test,11.3k,En
20
+ Summarisation,CNN/DM (2-shot),https://huggingface.co/datasets/cnn_dailymail/viewer/3.0.0/test,test,11.5k,En
cli/analysis-cli.py ADDED
@@ -0,0 +1,336 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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(repo_id=RESULTS_REPO, revision="main", local_dir=EVAL_RESULTS_PATH_BACKEND, repo_type="dataset", max_workers=60)
102
+ my_snapshot_download(repo_id=QUEUE_REPO, revision="main", local_dir=EVAL_REQUESTS_PATH_BACKEND, repo_type="dataset", max_workers=60)
103
+
104
+ result_path_lst = find_json_files(EVAL_RESULTS_PATH_BACKEND)
105
+ request_path_lst = find_json_files(EVAL_REQUESTS_PATH_BACKEND)
106
+
107
+ model_name_to_model_map = {}
108
+
109
+ for path in request_path_lst:
110
+ with open(path, 'r') as f:
111
+ data = json.load(f)
112
+ model_name_to_model_map[data["model"]] = data
113
+
114
+ model_dataset_metric_to_result_map = {}
115
+
116
+ # data_map[model_name][(dataset_name, sanitised_metric_name)] = value
117
+ data_map = {}
118
+
119
+ for path in result_path_lst:
120
+ with open(path, 'r') as f:
121
+ data = json.load(f)
122
+ model_name = data["config"]["model_name"]
123
+ for dataset_name, results_dict in data["results"].items():
124
+ for metric_name, value in results_dict.items():
125
+
126
+ if model_name_to_model_map[model_name]["likes"] > 128:
127
+
128
+ to_add = True
129
+
130
+ if 'f1' in metric_name:
131
+ to_add = False
132
+
133
+ if 'stderr' in metric_name:
134
+ to_add = False
135
+
136
+ if 'memo-trap_v2' in dataset_name:
137
+ to_add = False
138
+
139
+ if 'faithdial' in dataset_name:
140
+ to_add = False
141
+
142
+ if 'truthfulqa_gen' in dataset_name:
143
+ to_add = False
144
+
145
+ if 'bertscore' in metric_name:
146
+ if 'precision' not in metric_name:
147
+ to_add = False
148
+
149
+ if 'halueval' in dataset_name:
150
+ if 'acc' not in metric_name:
151
+ to_add = False
152
+
153
+ if 'ifeval' in dataset_name:
154
+ if 'prompt_level_strict_acc' not in metric_name:
155
+ to_add = False
156
+
157
+ if 'squad' in dataset_name:
158
+ # to_add = False
159
+ if 'best_exact' in metric_name:
160
+ to_add = False
161
+
162
+ if 'fever' in dataset_name:
163
+ to_add = False
164
+
165
+ if ('xsum' in dataset_name or 'cnn' in dataset_name) and 'v2' not in dataset_name:
166
+ to_add = False
167
+
168
+ if isinstance(value, str):
169
+ if is_float(value):
170
+ value = float(value)
171
+ else:
172
+ to_add = False
173
+
174
+ if to_add:
175
+ if 'rouge' in metric_name:
176
+ value /= 100.0
177
+
178
+ if 'squad' in dataset_name:
179
+ value /= 100.0
180
+
181
+ sanitised_metric_name = metric_name
182
+ if "," in sanitised_metric_name:
183
+ sanitised_metric_name = sanitised_metric_name.split(',')[0]
184
+ sanitised_metric_name = sanitise_metric(sanitised_metric_name)
185
+ sanitised_dataset_name = sanitise_dataset(dataset_name)
186
+
187
+ model_dataset_metric_to_result_map[(model_name, sanitised_dataset_name, sanitised_metric_name)] = value
188
+
189
+ if model_name not in data_map:
190
+ data_map[model_name] = {}
191
+ data_map[model_name][(sanitised_dataset_name, sanitised_metric_name)] = value
192
+
193
+ print('model_name', model_name, 'dataset_name', sanitised_dataset_name, 'metric_name', sanitised_metric_name, 'value', value)
194
+
195
+ save_data_map_to_cache(data_map, cache_file)
196
+
197
+ model_name_lst = [m for m in data_map.keys()]
198
+
199
+ nb_max_metrics = max(len(data_map[model_name]) for model_name in model_name_lst)
200
+
201
+ for model_name in model_name_lst:
202
+ if len(data_map[model_name]) < nb_max_metrics - 5:
203
+ del data_map[model_name]
204
+
205
+ plot_type_lst = ['all', 'summ', 'qa', 'instr', 'detect', 'rc']
206
+
207
+ for plot_type in plot_type_lst:
208
+
209
+ data_map_v2 = {}
210
+ for model_name in data_map.keys():
211
+ for dataset_metric in data_map[model_name].keys():
212
+ if dataset_metric not in data_map_v2:
213
+ data_map_v2[dataset_metric] = {}
214
+
215
+ if plot_type in {'all'}:
216
+ to_add = True
217
+ if 'ROUGE' in dataset_metric[1] and 'ROUGE-L' not in dataset_metric[1]:
218
+ to_add = False
219
+ if 'SQuAD' in dataset_metric[0] and 'EM' not in dataset_metric[1]:
220
+ to_add = False
221
+ if 'SelfCheckGPT' in dataset_metric[0] and 'MAX' not in dataset_metric[1]:
222
+ to_add = False
223
+ if '64-shot' in dataset_metric[0]:
224
+ to_add = False
225
+ if to_add is True:
226
+ data_map_v2[dataset_metric][model_name] = data_map[model_name][dataset_metric]
227
+ elif plot_type in {'summ'}:
228
+ if 'CNN' in dataset_metric[0] or 'XSum' in dataset_metric[0]:
229
+ data_map_v2[dataset_metric][model_name] = data_map[model_name][dataset_metric]
230
+ elif plot_type in {'qa'}:
231
+ if 'TriviaQA' in dataset_metric[0] or 'NQ' in dataset_metric[0] or 'TruthfulQA' in dataset_metric[0]:
232
+ data_map_v2[dataset_metric][model_name] = data_map[model_name][dataset_metric]
233
+ elif plot_type in {'instr'}:
234
+ if 'MemoTrap' in dataset_metric[0] or 'IFEval' in dataset_metric[0]:
235
+ data_map_v2[dataset_metric][model_name] = data_map[model_name][dataset_metric]
236
+ elif plot_type in {'detect'}:
237
+ if 'HaluEval' in dataset_metric[0] or 'SelfCheck' in dataset_metric[0]:
238
+ data_map_v2[dataset_metric][model_name] = data_map[model_name][dataset_metric]
239
+ elif plot_type in {'rc'}:
240
+ if 'RACE' in dataset_metric[0] or 'SQuAD' in dataset_metric[0]:
241
+ data_map_v2[dataset_metric][model_name] = data_map[model_name][dataset_metric]
242
+ else:
243
+ assert False, f"Unknown plot type: {plot_type}"
244
+
245
+ # df = pd.DataFrame.from_dict(data_map, orient='index') # Invert the y-axis (rows)
246
+ df = pd.DataFrame.from_dict(data_map_v2, orient='index') # Invert the y-axis (rows)
247
+ df.index = [', '.join(map(str, idx)) for idx in df.index]
248
+
249
+ o_df = df.copy(deep=True)
250
+
251
+ # breakpoint()
252
+
253
+ print(df)
254
+
255
+ # Check for NaN or infinite values and replace them
256
+ df.replace([np.inf, -np.inf], np.nan, inplace=True) # Replace infinities with NaN
257
+ df.fillna(0, inplace=True) # Replace NaN with 0 (or use another imputation strategy)
258
+
259
+ from sklearn.preprocessing import MinMaxScaler
260
+
261
+ # scaler = MinMaxScaler()
262
+ # df = pd.DataFrame(scaler.fit_transform(df), index=df.index, columns=df.columns)
263
+
264
+ # Calculate dimensions based on the DataFrame size
265
+ cell_height = 1.0 # Height of each cell in inches
266
+ cell_width = 1.0 # Width of each cell in inches
267
+
268
+ n_rows = len(df.index) # Datasets and Metrics
269
+ n_cols = len(df.columns) # Models
270
+
271
+ # Calculate figure size dynamically
272
+ fig_width = cell_width * n_cols + 0
273
+ fig_height = cell_height * n_rows + 0
274
+
275
+ col_cluster = True
276
+ row_cluster = True
277
+
278
+ sns.set_context("notebook", font_scale=1.3)
279
+
280
+ dendrogram_ratio = (.1, .1)
281
+
282
+ if plot_type in {'detect'}:
283
+ fig_width = cell_width * n_cols - 2
284
+ fig_height = cell_height * n_rows + 5.2
285
+ dendrogram_ratio = (.1, .2)
286
+
287
+ if plot_type in {'instr'}:
288
+ fig_width = cell_width * n_cols - 2
289
+ fig_height = cell_height * n_rows + 5.2
290
+ dendrogram_ratio = (.1, .4)
291
+
292
+ if plot_type in {'qa'}:
293
+ fig_width = cell_width * n_cols - 2
294
+ fig_height = cell_height * n_rows + 4
295
+ dendrogram_ratio = (.1, .2)
296
+
297
+ if plot_type in {'summ'}:
298
+ fig_width = cell_width * n_cols - 2
299
+ fig_height = cell_height * n_rows + 2.0
300
+ dendrogram_ratio = (.1, .1)
301
+ row_cluster = False
302
+
303
+ if plot_type in {'rc'}:
304
+ fig_width = cell_width * n_cols - 2
305
+ fig_height = cell_height * n_rows + 5.2
306
+ dendrogram_ratio = (.1, .4)
307
+
308
+ print('figsize', (fig_width, fig_height))
309
+
310
+ o_df.to_json(f'plots/clustermap_{plot_type}.json', orient='split')
311
+
312
+ print(f'Generating the clustermaps for {plot_type}')
313
+
314
+ for cmap in [None, 'coolwarm', 'viridis']:
315
+ fig = sns.clustermap(df,
316
+ method='ward',
317
+ metric='euclidean',
318
+ cmap=cmap,
319
+ figsize=(fig_width, fig_height), # figsize=(24, 16),
320
+ annot=True,
321
+ mask=o_df.isnull(),
322
+ dendrogram_ratio=dendrogram_ratio,
323
+ fmt='.2f',
324
+ col_cluster=col_cluster,
325
+ row_cluster=row_cluster)
326
+
327
+ # Adjust the size of the cells (less wide)
328
+ plt.setp(fig.ax_heatmap.get_yticklabels(), rotation=0)
329
+ plt.setp(fig.ax_heatmap.get_xticklabels(), rotation=90)
330
+
331
+ cmap_suffix = '' if cmap is None else f'_{cmap}'
332
+
333
+ # Save the clustermap to file
334
+ fig.savefig(f'blog/figures/clustermap_{plot_type}{cmap_suffix}.pdf')
335
+ fig.savefig(f'blog/figures/clustermap_{plot_type}{cmap_suffix}.png')
336
+ fig.savefig(f'blog/figures/clustermap_{plot_type}{cmap_suffix}_t.png', transparent=True, facecolor="none")
cli/averitec-upload-cli.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+
3
+ from datasets import load_dataset
4
+
5
+ path = 'pminervini/averitec'
6
+
7
+ ds = load_dataset("json",
8
+ data_files={
9
+ 'train': '/Users/pasquale/workspace/AVeriTeC/data/train.json',
10
+ 'dev': '/Users/pasquale/workspace/AVeriTeC/data/dev.json'
11
+ })
12
+ ds.push_to_hub(path)
cli/beta-cli.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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(repo_id=QUEUE_REPO, local_dir=EVAL_REQUESTS_PATH, repo_type="dataset", tqdm_class=None, etag_timeout=30)
18
+ snapshot_download(repo_id=RESULTS_REPO, local_dir=EVAL_RESULTS_PATH, repo_type="dataset", tqdm_class=None, etag_timeout=30)
19
+
20
+ PENDING_STATUS = "PENDING"
21
+ RUNNING_STATUS = "RUNNING"
22
+ FINISHED_STATUS = "FINISHED"
23
+ FAILED_STATUS = "FAILED"
24
+
25
+ TASKS_HARNESS = [task.value for task in Tasks]
26
+
27
+ current_finished_status = [FINISHED_STATUS]
28
+
29
+
30
+ def request_to_result_name(request: EvalRequest) -> str:
31
+ org_and_model = request.model.split("/", 1)
32
+ if len(org_and_model) == 1:
33
+ model = org_and_model[0]
34
+ res = f"{model}_{request.precision}"
35
+ else:
36
+ org = org_and_model[0]
37
+ model = org_and_model[1]
38
+ res = f"{org}_{model}_{request.precision}"
39
+ return res
40
+
41
+
42
+ # Get all eval request that are FINISHED, if you want to run other evals, change this parameter
43
+ eval_requests: list[EvalRequest] = get_eval_requests(job_status=current_finished_status, hf_repo=QUEUE_REPO, local_dir=EVAL_REQUESTS_PATH_BACKEND)
44
+ # Sort the evals by priority (first submitted first run)
45
+ eval_requests: list[EvalRequest] = sort_models_by_priority(api=API, models=eval_requests)
46
+
47
+ eval_results: list[EvalResult] = get_raw_eval_results(EVAL_RESULTS_PATH, EVAL_REQUESTS_PATH)
48
+
49
+ result_name_to_request = {request_to_result_name(r): r for r in eval_requests}
50
+ result_name_to_result = {r.eval_name: r for r in eval_results}
51
+
52
+ print('Requests', sorted(result_name_to_request.keys()))
53
+ print('Results', sorted(result_name_to_result.keys()))
54
+
55
+ for eval_request in eval_requests:
56
+ result_name: str = request_to_result_name(eval_request)
57
+
58
+ # Check the corresponding result
59
+ eval_result: EvalResult = result_name_to_result[result_name]
60
+
61
+ # Iterate over tasks and, if we do not have results for a task, run the relevant evaluations
62
+ for task in TASKS_HARNESS:
63
+ task_name = task.benchmark
64
+
65
+ if task_name not in eval_result.results:
66
+ print('RUN THIS ONE!', result_name, task_name)
67
+
68
+ raw_data = get_raw_eval_results(EVAL_RESULTS_PATH, EVAL_REQUESTS_PATH)
69
+ all_data_json = [v.to_dict() for v in raw_data if v.is_complete()]
70
+
71
+ breakpoint()
cli/completed-cli.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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(repo_id=RESULTS_REPO, revision="main", local_dir=EVAL_RESULTS_PATH_BACKEND, repo_type="dataset", max_workers=60)
30
+ snapshot_download(repo_id=QUEUE_REPO, revision="main", local_dir=EVAL_REQUESTS_PATH_BACKEND, repo_type="dataset", max_workers=60)
31
+
32
+
33
+ def request_to_result_name(request: EvalRequest) -> str:
34
+ org_and_model = request.model.split("/", 1)
35
+ if len(org_and_model) == 1:
36
+ model = org_and_model[0]
37
+ res = f"{model}_{request.precision}"
38
+ else:
39
+ org = org_and_model[0]
40
+ model = org_and_model[1]
41
+ res = f"{org}_{model}_{request.precision}"
42
+ return res
43
+
44
+
45
+ def process_finished_requests() -> bool:
46
+ current_finished_status = [FINISHED_STATUS]
47
+
48
+ if False:
49
+ import os
50
+ import dateutil
51
+ model_result_filepaths = []
52
+ results_path = f'{EVAL_RESULTS_PATH_BACKEND}/EleutherAI/gpt-neo-1.3B'
53
+ requests_path = f'{EVAL_REQUESTS_PATH_BACKEND}/EleutherAI/gpt-neo-1.3B_eval_request_False_False_False.json'
54
+
55
+ for root, _, files in os.walk(results_path):
56
+ # We should only have json files in model results
57
+ if len(files) == 0 or any([not f.endswith(".json") for f in files]):
58
+ continue
59
+
60
+ # Sort the files by date
61
+ try:
62
+ files.sort(key=lambda x: x.removesuffix(".json").removeprefix("results_")[:-7])
63
+ except dateutil.parser._parser.ParserError:
64
+ files = [files[-1]]
65
+
66
+ for file in files:
67
+ model_result_filepaths.append(os.path.join(root, file))
68
+
69
+ eval_results = {}
70
+ for model_result_filepath in model_result_filepaths:
71
+ # Creation of result
72
+ eval_result = EvalResult.init_from_json_file(model_result_filepath)
73
+ eval_result.update_with_request_file(requests_path)
74
+
75
+ print('XXX', eval_result)
76
+
77
+ # Store results of same eval together
78
+ eval_name = eval_result.eval_name
79
+ if eval_name in eval_results.keys():
80
+ eval_results[eval_name].results.update({k: v for k, v in eval_result.results.items() if v is not None})
81
+ else:
82
+ eval_results[eval_name] = eval_result
83
+
84
+ print(eval_results)
85
+
86
+ return True
87
+
88
+ # Get all eval request that are FINISHED, if you want to run other evals, change this parameter
89
+ eval_requests: list[EvalRequest] = get_eval_requests(job_status=current_finished_status, hf_repo=QUEUE_REPO, local_dir=EVAL_REQUESTS_PATH_BACKEND)
90
+ # Sort the evals by priority (first submitted first run)
91
+ eval_requests: list[EvalRequest] = sort_models_by_priority(api=API, models=eval_requests)
92
+
93
+ # XXX
94
+ # eval_requests = [r for r in eval_requests if 'neo-1.3B' in r.model]
95
+
96
+ import random
97
+ random.shuffle(eval_requests)
98
+
99
+ from src.leaderboard.read_evals import get_raw_eval_results
100
+ eval_results: list[EvalResult] = get_raw_eval_results(EVAL_RESULTS_PATH_BACKEND, EVAL_REQUESTS_PATH_BACKEND)
101
+
102
+ result_name_to_request = {request_to_result_name(r): r for r in eval_requests}
103
+ result_name_to_result = {r.eval_name: r for r in eval_results}
104
+
105
+ for eval_request in eval_requests:
106
+ result_name: str = request_to_result_name(eval_request)
107
+
108
+ # Check the corresponding result
109
+ from typing import Optional
110
+ eval_result: Optional[EvalResult] = result_name_to_result[result_name] if result_name in result_name_to_result else None
111
+
112
+ # Iterate over tasks and, if we do not have results for a task, run the relevant evaluations
113
+ for task in TASKS_HARNESS:
114
+ task_name = task.benchmark
115
+
116
+ if eval_result is None or task_name not in eval_result.results:
117
+ eval_request: EvalRequest = result_name_to_request[result_name]
118
+
119
+ # print(eval_result)
120
+ print(result_name, 'is incomplete -- missing task:', task_name, eval_result, eval_request.likes)
121
+
122
+
123
+ if __name__ == "__main__":
124
+ res = process_finished_requests()
cli/create_request_file.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 = "hallucinations-leaderboard/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()
cli/eval-cli.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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(job_status=status,
39
+ hf_repo=QUEUE_REPO,
40
+ local_dir=EVAL_REQUESTS_PATH_BACKEND,
41
+ do_download=False)
42
+ # eval_request = [r for r in eval_requests if 'bloom-560m' in r.model][0]
43
+ eval_request = [r for r in eval_requests if 'meta-llama/Llama-2-7b-hf' in r.model][0]
44
+
45
+ # my_task = Task("memo-trap", "acc", "memo-trap", 0)
46
+ # my_task = Task("selfcheckgpt", "avg-selfcheckgpt", "SGPT", 2)
47
+ # my_task = Task("ifeval", "prompt_level_strict_acc", "IFEval", 0)
48
+ # my_task = Task("truefalse_cieacf", "acc", "TrueFalse", 5)
49
+ # my_task = Task("faithdial_hallu", "acc", "FaithDIAL", 2)
50
+
51
+ # my_task = Task("nq_swap", "exact_match", "NQ-Swap", 2)
52
+ # my_task = Task("memo-trap_v2", "acc", "XXX", 2)
53
+ my_task = Task("xsum_v2", "rougeL", "XXX", 0)
54
+ # my_task = Task("squadv2", "exact", "XXX", 0)
55
+ # my_task = Task("scrolls_qasper", "f1", "XXX", 0)
56
+
57
+ eval_logger = utils.eval_logger
58
+ import logging
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(model="hf", model_args=eval_request.get_model_args(), tasks=[task.benchmark], num_fewshot=task.num_fewshot,
79
+ batch_size=1, device="mps", use_cache=None, limit=2, write_out=True, task_manager=task_manager)
80
+ print('AAA', results["results"])
81
+
82
+ breakpoint()
83
+
84
+
85
+ if __name__ == "__main__":
86
+ main()
cli/fever-upload-cli.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 = {
24
+ 'SUPPORTS': 'supported',
25
+ 'REFUTES': 'refuted'
26
+ }
27
+
28
+ data_map = {}
29
+
30
+ for name in name_lst:
31
+ instance_lst = []
32
+
33
+ for entry in tqdm(v10[name]):
34
+ id_ = entry['id']
35
+ label = entry['label']
36
+ claim = entry['claim']
37
+
38
+ evidence_id = entry['evidence_id']
39
+ evidence_wiki_url = entry['evidence_wiki_url']
40
+
41
+ if evidence_id != -1:
42
+ assert label in {'SUPPORTS', 'REFUTES'}
43
+
44
+ instance = {'id': id_, 'label': old_to_new_label_map[label], 'claim': claim}
45
+ instance_lst.append(instance)
46
+
47
+ key = 'dev' if name in {'labelled_dev'} else name
48
+
49
+ instance_lst = sorted([dict(t) for t in {tuple(d.items()) for d in instance_lst}], key=lambda d: d['claim'])
50
+
51
+ label_to_instance_lst = {}
52
+ for e in instance_lst:
53
+ if e['label'] not in label_to_instance_lst:
54
+ label_to_instance_lst[e['label']] = []
55
+ label_to_instance_lst[e['label']].append(e)
56
+
57
+ min_len = min(len(v) for k, v in label_to_instance_lst.items())
58
+
59
+ new_instance_lst = []
60
+ for k in sorted(label_to_instance_lst.keys()):
61
+ new_instance_lst += label_to_instance_lst[k][:min_len]
62
+
63
+ random.Random(42).shuffle(new_instance_lst)
64
+ data_map[key] = new_instance_lst
65
+
66
+ ds_path = 'pminervini/hl-fever'
67
+
68
+ task_to_ds_map = {k: Dataset.from_dict(convert(v)) for k, v in data_map.items()}
69
+ ds_dict = DatasetDict(task_to_ds_map)
70
+
71
+ ds_dict.push_to_hub(ds_path, "v1.0")
72
+
73
+ # breakpoint()
cli/fix-requests-cli.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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')
cli/halueval-upload-cli.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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')
cli/isp-upload-cli.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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)
cli/nqswap-upload-cli.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+
3
+ from datasets import load_dataset
4
+
5
+ path = 'pminervini/NQ-Swap'
6
+
7
+ ds = load_dataset("json",
8
+ data_files={
9
+ 'original': 'nqswap/original.jsonl',
10
+ 'substituted': 'nqswap/substituted.jsonl'
11
+ })
12
+ ds.push_to_hub(path)
cli/shroom-upload-cli.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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)
cli/submit-cli.py ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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(model: str, base_model: str, revision: str, precision: str, private: bool, weight_type: str, model_type: str):
19
+ REQUESTED_MODELS, USERS_TO_SUBMISSION_DATES = already_submitted_models(EVAL_REQUESTS_PATH)
20
+
21
+ user_name = ""
22
+ model_path = model
23
+ if "/" in model:
24
+ tokens = model.split("/")
25
+ user_name = tokens[0]
26
+ model_path = tokens[1]
27
+
28
+ precision = precision.split(" ")[0]
29
+ current_time = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
30
+
31
+ if model_type is None or model_type == "":
32
+ return print("Please select a model type.")
33
+
34
+ # Does the model actually exist?
35
+ if revision == "":
36
+ revision = "main"
37
+
38
+ # Is the model on the hub?
39
+ if weight_type in ["Delta", "Adapter"]:
40
+ base_model_on_hub, error, _ = is_model_on_hub(model_name=base_model, revision=revision, token=H4_TOKEN, test_tokenizer=True)
41
+ if not base_model_on_hub:
42
+ print(f'Base model "{base_model}" {error}')
43
+ return
44
+
45
+ if not weight_type == "Adapter":
46
+ model_on_hub, error, _ = is_model_on_hub(model_name=model, revision=revision, test_tokenizer=True)
47
+ if not model_on_hub:
48
+ print(f'Model "{model}" {error}')
49
+ return
50
+
51
+ # Is the model info correctly filled?
52
+ try:
53
+ model_info = API.model_info(repo_id=model, revision=revision)
54
+ except Exception:
55
+ print("Could not get your model information. Please fill it up properly.")
56
+ return
57
+
58
+ model_size = get_model_size(model_info=model_info, precision=precision)
59
+
60
+ license = 'none'
61
+ try:
62
+ license = model_info.cardData["license"]
63
+ except Exception:
64
+ print("Please select a license for your model")
65
+ # return
66
+
67
+ # modelcard_OK, error_msg = check_model_card(model)
68
+ # if not modelcard_OK:
69
+ # print(error_msg)
70
+ # return
71
+
72
+ # Seems good, creating the eval
73
+ print("Adding new eval")
74
+
75
+ eval_entry = {
76
+ "model": model,
77
+ "base_model": base_model,
78
+ "revision": revision,
79
+ "private": private,
80
+ "precision": precision,
81
+ "weight_type": weight_type,
82
+ "status": "PENDING",
83
+ "submitted_time": current_time,
84
+ "model_type": model_type,
85
+ "likes": model_info.likes,
86
+ "params": model_size,
87
+ "license": license,
88
+ }
89
+
90
+ # Check for duplicate submission
91
+ if f"{model}_{revision}_{precision}" in REQUESTED_MODELS:
92
+ print("This model has been already submitted.")
93
+ return
94
+
95
+ print("Creating eval file")
96
+ OUT_DIR = f"{EVAL_REQUESTS_PATH}/{user_name}"
97
+ os.makedirs(OUT_DIR, exist_ok=True)
98
+ out_path = f"{OUT_DIR}/{model_path}_eval_request_{private}_{precision}_{weight_type}.json"
99
+
100
+ with open(out_path, "w") as f:
101
+ f.write(json.dumps(eval_entry))
102
+
103
+ print("Uploading eval file")
104
+ API.upload_file(path_or_fileobj=out_path, path_in_repo=out_path.split("eval-queue/")[1],
105
+ repo_id=QUEUE_REPO, repo_type="dataset", commit_message=f"Add {model} to eval queue")
106
+
107
+ # Remove the local file
108
+ os.remove(out_path)
109
+
110
+ print("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.")
111
+ return
112
+
113
+
114
+ def main():
115
+ from huggingface_hub import HfApi
116
+
117
+ api = HfApi()
118
+ model_lst = api.list_models()
119
+
120
+ model_lst = [m for m in model_lst]
121
+
122
+ def custom_filter(m) -> bool:
123
+ # res = m.pipeline_tag in {'text-generation'} and 'en' in m.tags and m.private is False
124
+ # res = m.pipeline_tag in {'text-generation'} and 'en' in m.tags and m.private is False and 'mistralai/' in m.id
125
+ res = 'mistralai/' in m.id
126
+ return res
127
+
128
+ filtered_model_lst = sorted([m for m in model_lst if custom_filter(m)], key=lambda m: m.downloads, reverse=True)
129
+
130
+ snapshot_download(repo_id=QUEUE_REPO, revision="main", local_dir=EVAL_REQUESTS_PATH_BACKEND, repo_type="dataset", max_workers=60)
131
+
132
+ PENDING_STATUS = "PENDING"
133
+ RUNNING_STATUS = "RUNNING"
134
+ FINISHED_STATUS = "FINISHED"
135
+ FAILED_STATUS = "FAILED"
136
+
137
+ status = [PENDING_STATUS, RUNNING_STATUS, FINISHED_STATUS, FAILED_STATUS]
138
+
139
+ # Get all eval requests
140
+ eval_requests: list[EvalRequest] = get_eval_requests(job_status=status, hf_repo=QUEUE_REPO, local_dir=EVAL_REQUESTS_PATH_BACKEND)
141
+
142
+ requested_model_names = {e.model for e in eval_requests}
143
+
144
+ # breakpoint()
145
+
146
+ for i in range(min(200, len(filtered_model_lst))):
147
+ model = filtered_model_lst[i]
148
+
149
+ print(f'Considering {model.id} ..')
150
+
151
+ is_finetuned = any(tag.startswith('base_model:') for tag in model.tags)
152
+
153
+ model_type = 'pretrained'
154
+ if is_finetuned:
155
+ model_type = "fine-tuned"
156
+
157
+ is_instruction_tuned = 'nstruct' in model.id
158
+ if is_instruction_tuned:
159
+ model_type = "instruction-tuned"
160
+
161
+ if model.id not in requested_model_names:
162
+
163
+ if 'mage' not in model.id:
164
+ add_new_eval(model=model.id, base_model='', revision='main', precision='float32', private=False, weight_type='Original', model_type=model_type)
165
+ time.sleep(10)
166
+ else:
167
+ print(f'Model {model.id} already added, not adding it to the queue again.')
168
+
169
+
170
+ if __name__ == "__main__":
171
+ main()
cli/sync-open-llm-cli.py ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ def my_set_eval_request(api, json_filepath, hf_repo, local_dir):
14
+ for i in range(10):
15
+ try:
16
+ set_eval_request(api=api, json_filepath=json_filepath, hf_repo=hf_repo, local_dir=local_dir)
17
+ return
18
+ except Exception:
19
+ time.sleep(60)
20
+ return
21
+
22
+
23
+ def set_eval_request(api: HfApi, json_filepath: str, hf_repo: str, local_dir: str):
24
+ """Updates a given eval request with its new status on the hub (running, completed, failed, ...)"""
25
+
26
+ with open(json_filepath) as fp:
27
+ data = json.load(fp)
28
+
29
+ with open(json_filepath, "w") as f:
30
+ f.write(json.dumps(data))
31
+
32
+ api.upload_file(path_or_fileobj=json_filepath, path_in_repo=json_filepath.replace(local_dir, ""),
33
+ repo_id=hf_repo, repo_type="dataset")
34
+
35
+
36
+ def get_request_file_for_model(data, requests_path):
37
+ model_name = data["model"]
38
+ precision = data["precision"]
39
+ """Selects the correct request file for a given model. Only keeps runs tagged as FINISHED and RUNNING"""
40
+ request_files = os.path.join(
41
+ requests_path,
42
+ f"{model_name}_eval_request_*.json",
43
+ )
44
+ request_files = glob.glob(request_files)
45
+
46
+ # Select correct request file (precision)
47
+ request_file = ""
48
+ request_files = sorted(request_files, reverse=True)
49
+
50
+ for tmp_request_file in request_files:
51
+ with open(tmp_request_file, "r") as f:
52
+ req_content = json.load(f)
53
+ if req_content["precision"] == precision.split(".")[-1]:
54
+ request_file = tmp_request_file
55
+ return request_file
56
+
57
+ def update_model_type(data, requests_path):
58
+ open_llm_request_file = get_request_file_for_model(data, requests_path)
59
+
60
+ try:
61
+ with open(open_llm_request_file, "r") as f:
62
+ open_llm_request = json.load(f)
63
+ data["model_type"] = open_llm_request["model_type"]
64
+ return True, data
65
+ except:
66
+ return False, data
67
+
68
+
69
+ def read_and_write_json_files(directory, requests_path_open_llm):
70
+ # Walk through the directory
71
+ for subdir, dirs, files in tqdm(os.walk(directory), desc="updating model type according to open llm leaderboard"):
72
+ for file in files:
73
+ # Check if the file is a JSON file
74
+ if file.endswith('.json'):
75
+ file_path = os.path.join(subdir, file)
76
+ # Open and read the JSON file
77
+ with open(file_path, 'r') as json_file:
78
+ data = json.load(json_file)
79
+ sucess, data = update_model_type(data, requests_path_open_llm)
80
+ if sucess:
81
+ with open(file_path, 'w') as json_file:
82
+ json.dump(data, json_file)
83
+ my_set_eval_request(api=API, json_filepath=file_path, hf_repo=QUEUE_REPO, local_dir=EVAL_REQUESTS_PATH_BACKEND_SYNC)
84
+
85
+
86
+
87
+
88
+ if __name__ == "__main__":
89
+ my_snapshot_download(repo_id=QUEUE_REPO_OPEN_LLM, revision="main", local_dir=EVAL_REQUESTS_PATH_OPEN_LLM, repo_type="dataset", max_workers=60)
90
+ my_snapshot_download(repo_id=QUEUE_REPO, revision="main", local_dir=EVAL_REQUESTS_PATH_BACKEND_SYNC, repo_type="dataset", max_workers=60)
91
+ read_and_write_json_files(EVAL_REQUESTS_PATH_BACKEND_SYNC, EVAL_REQUESTS_PATH_OPEN_LLM)
cli/truefalse-upload-cli.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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)
pyproject.toml ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [tool.ruff]
2
+ # Enable pycodestyle (`E`) and Pyflakes (`F`) codes by default.
3
+ select = ["E", "F"]
4
+ ignore = ["E501"] # line too long (black is taking care of this)
5
+ line-length = 119
6
+ fixable = ["A", "B", "C", "D", "E", "F", "G", "I", "N", "Q", "S", "T", "W", "ANN", "ARG", "BLE", "COM", "DJ", "DTZ", "EM", "ERA", "EXE", "FBT", "ICN", "INP", "ISC", "NPY", "PD", "PGH", "PIE", "PL", "PT", "PTH", "PYI", "RET", "RSE", "RUF", "SIM", "SLF", "TCH", "TID", "TRY", "UP", "YTT"]
7
+
8
+ [tool.isort]
9
+ profile = "black"
10
+ line_length = 119
11
+
12
+ [tool.black]
13
+ line-length = 119
requirements.txt ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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/lm-evaluation-harness.git
22
+ accelerate
23
+ sentencepiece
24
+ langdetect
25
+ sacrebleu
26
+ cchardet
27
+ rouge_score
28
+ bert-score
29
+ evaluate
30
+ spacy
31
+ selfcheckgpt
32
+ immutabledict
src/backend/envs.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
60
+
61
+ EVAL_REQUESTS_PATH_BACKEND = os.path.join(CACHE_PATH, "eval-queue-bk")
62
+ EVAL_REQUESTS_PATH_BACKEND_SYNC = os.path.join(CACHE_PATH, "eval-queue-bk-sync")
63
+ EVAL_RESULTS_PATH_BACKEND = os.path.join(CACHE_PATH, "eval-results-bk")
64
+
65
+ DEVICE = "cuda" if torch.cuda.is_available() else 'cpu'
66
+
67
+ LIMIT = None # Testing; needs to be None
src/backend/huggingface_generate_until.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List, Literal, Optional, Tuple, Union
2
+ import torch
3
+ import transformers
4
+
5
+ from lm_eval.models.huggingface import HFLM
6
+ from lm_eval.api.registry import register_model
7
+
8
+ @register_model('hf-chat')
9
+ class HFLMwithChatTemplate(HFLM):
10
+ def __init__(self, use_chat_template=True, **kwargs):
11
+ super().__init__(**kwargs)
12
+ self.use_chat_template = use_chat_template
13
+
14
+ def tok_batch_encode(
15
+ self,
16
+ strings: List[str],
17
+ padding_side: str = "left",
18
+ left_truncate_len: int = None,
19
+ truncation: bool = False,
20
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
21
+
22
+ if self.use_chat_template:
23
+ try:
24
+ updated_strings = []
25
+ for input_string in strings:
26
+ messages = [
27
+ {"role": "user", "content": f"{input_string}"},
28
+ ]
29
+ updated_string = self.tokenizer.apply_chat_template(messages, tokenize=False)
30
+ updated_strings.append(updated_string)
31
+ strings = updated_strings[:]
32
+ except:
33
+ print(f"failed to update input string with chat template: {self._model}")
34
+ # encode a batch of strings. converts to tensors and pads automatically, unlike tok_encode.
35
+ old_padding_side = self.tokenizer.padding_side
36
+ self.tokenizer.padding_side = padding_side
37
+
38
+ if self.AUTO_MODEL_CLASS == transformers.AutoModelForCausalLM:
39
+ add_special_tokens = False
40
+ elif self.AUTO_MODEL_CLASS == transformers.AutoModelForSeq2SeqLM:
41
+ add_special_tokens = True
42
+
43
+ encoding = self.tokenizer(
44
+ strings,
45
+ truncation=truncation,
46
+ padding="longest",
47
+ return_tensors="pt",
48
+ add_special_tokens=add_special_tokens,
49
+ )
50
+ if left_truncate_len:
51
+ encoding["input_ids"] = encoding["input_ids"][:, -left_truncate_len:]
52
+ encoding["attention_mask"] = encoding["attention_mask"][
53
+ :, -left_truncate_len:
54
+ ]
55
+ self.tokenizer.padding_side = old_padding_side
56
+
57
+ return encoding["input_ids"], encoding["attention_mask"]
src/backend/manage_requests.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ precision: str = "" # float16, bfloat16
20
+ base_model: Optional[str] = None # for adapter models
21
+ revision: str = "main" # commit
22
+ submitted_time: Optional[str] = "2022-05-18T11:40:22.519222" # random date just so that we can still order requests by date
23
+ model_type: Optional[str] = None
24
+ likes: Optional[int] = 0
25
+ params: Optional[int] = None
26
+ license: Optional[str] = ""
27
+ def get_model_args(self) -> str:
28
+ model_args = f"pretrained={self.model},revision={self.revision},parallelize=True" # ,max_length=4096"
29
+
30
+ if self.precision in ["float16", "float32", "bfloat16"]:
31
+ model_args += f",dtype={self.precision}"
32
+ # Quantized models need some added config, the install of bits and bytes, etc
33
+ #elif self.precision == "8bit":
34
+ # model_args += ",load_in_8bit=True"
35
+ #elif self.precision == "4bit":
36
+ # model_args += ",load_in_4bit=True"
37
+ #elif self.precision == "GPTQ":
38
+ # A GPTQ model does not need dtype to be specified,
39
+ # it will be inferred from the config
40
+ pass
41
+ else:
42
+ raise Exception(f"Unknown precision {self.precision}.")
43
+ return model_args
44
+
45
+
46
+ def set_eval_request(api: HfApi, eval_request: EvalRequest, set_to_status: str, hf_repo: str, local_dir: str):
47
+ """Updates a given eval request with its new status on the hub (running, completed, failed, ...)"""
48
+ json_filepath = eval_request.json_filepath
49
+
50
+ with open(json_filepath) as fp:
51
+ data = json.load(fp)
52
+
53
+ data["status"] = set_to_status
54
+
55
+ with open(json_filepath, "w") as f:
56
+ f.write(json.dumps(data))
57
+
58
+ api.upload_file(path_or_fileobj=json_filepath, path_in_repo=json_filepath.replace(local_dir, ""),
59
+ repo_id=hf_repo, repo_type="dataset")
60
+
61
+
62
+ def get_eval_requests(job_status: list, local_dir: str, hf_repo: str, do_download: bool = True) -> list[EvalRequest]:
63
+ """Get all pending evaluation requests and return a list in which private
64
+ models appearing first, followed by public models sorted by the number of
65
+ likes.
66
+
67
+ Returns:
68
+ `list[EvalRequest]`: a list of model info dicts.
69
+ """
70
+ if do_download:
71
+ my_snapshot_download(repo_id=hf_repo, revision="main", local_dir=local_dir, repo_type="dataset", max_workers=60)
72
+
73
+ json_files = glob.glob(f"{local_dir}/**/*.json", recursive=True)
74
+
75
+ eval_requests = []
76
+ for json_filepath in json_files:
77
+ with open(json_filepath) as fp:
78
+ data = json.load(fp)
79
+ if data["status"] in job_status:
80
+ # import pdb
81
+ # breakpoint()
82
+ data["json_filepath"] = json_filepath
83
+
84
+ if 'job_id' in data:
85
+ del data['job_id']
86
+
87
+ eval_request = EvalRequest(**data)
88
+ eval_requests.append(eval_request)
89
+
90
+ return eval_requests
91
+
92
+
93
+ def check_completed_evals(api: HfApi, hf_repo: str, local_dir: str, checked_status: str, completed_status: str,
94
+ failed_status: str, hf_repo_results: str, local_dir_results: str):
95
+ """Checks if the currently running evals are completed, if yes, update their status on the hub."""
96
+ my_snapshot_download(repo_id=hf_repo_results, revision="main", local_dir=local_dir_results, repo_type="dataset", max_workers=60)
97
+
98
+ running_evals = get_eval_requests([checked_status], hf_repo=hf_repo, local_dir=local_dir)
99
+
100
+ for eval_request in running_evals:
101
+ model = eval_request.model
102
+ print("====================================")
103
+ print(f"Checking {model}")
104
+
105
+ output_path = model
106
+ output_file = f"{local_dir_results}/{output_path}/results*.json"
107
+ output_file_exists = len(glob.glob(output_file)) > 0
108
+
109
+ if output_file_exists:
110
+ print(f"EXISTS output file exists for {model} setting it to {completed_status}")
111
+ set_eval_request(api, eval_request, completed_status, hf_repo, local_dir)
112
+
113
+
src/backend/moe_infinity.py ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import os
3
+ from transformers import AutoTokenizer
4
+ import transformers
5
+ from moe_infinity import MoE
6
+ from typing import List, Tuple, Optional, Union
7
+
8
+ from lm_eval.models.huggingface import HFLM
9
+ from lm_eval.api.registry import register_model
10
+
11
+ @register_model('moe-infinity')
12
+ class MoEHFLM(HFLM):
13
+ def __init__(
14
+ self,
15
+ pretrained: str = "mistralai/Mixtral-8x7B-Instruct-v0.1",
16
+ moe_config: dict = None,
17
+ offload_path = os.path.expanduser('~'),
18
+ device_memory_ratio = 0.75,
19
+ use_chat_template=True,
20
+ *args,
21
+ **kwargs
22
+ ):
23
+ # Initialize parent class without calling _create_model in the parent's __init__
24
+ self.checkpoint = pretrained
25
+ self.moe_config = moe_config if moe_config is not None else {}
26
+ self.offload_path = offload_path
27
+ self.device_memory_ratio = device_memory_ratio
28
+ self.use_chat_template = use_chat_template
29
+ super().__init__(*args, **kwargs, pretrained=pretrained) # Assuming HFLM accepts a 'pretrained' arg and handles it
30
+ # self._create_model()
31
+
32
+ def _create_model(self, *args, **kwargs):
33
+ """
34
+ Initializes the MoE model from MoE-infinity with the provided configuration.
35
+ """
36
+ # Ensure default configurations are set if not provided
37
+ default_moe_config = {
38
+ "offload_path": os.path.join(self.offload_path, "moe-infinity-offloads"),
39
+ "device_memory_ratio": self.device_memory_ratio, # Default value, adjust as necessary
40
+ }
41
+ # Update default config with any user-provided config
42
+ final_moe_config = {**default_moe_config, **self.moe_config}
43
+ self._model = MoE(self.checkpoint, final_moe_config)
44
+
45
+ @property
46
+ def max_length(self):
47
+ if self._max_length: # if max length manually set, return it
48
+ return self._max_length
49
+ seqlen_config_attrs = ("n_positions", "max_position_embeddings", "n_ctx")
50
+ for attr in seqlen_config_attrs:
51
+ if hasattr(self.model.model.config, attr):
52
+ return getattr(self.model.model.config, attr)
53
+ if hasattr(self.tokenizer, "model_max_length"):
54
+ if self.tokenizer.model_max_length == 1000000000000000019884624838656:
55
+ return self._DEFAULT_MAX_LENGTH
56
+ return self.tokenizer.model_max_length
57
+ return self._DEFAULT_MAX_LENGTH
58
+
59
+ def tok_batch_encode(
60
+ self,
61
+ strings: List[str],
62
+ padding_side: str = "left",
63
+ left_truncate_len: int = None,
64
+ truncation: bool = False,
65
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
66
+
67
+ if self.use_chat_template:
68
+ try:
69
+ updated_strings = []
70
+ for input_string in strings:
71
+ messages = [
72
+ {"role": "user", "content": f"{input_string}"},
73
+ ]
74
+ updated_string = self.tokenizer.apply_chat_template(messages, tokenize=False)
75
+ updated_strings.append(updated_string)
76
+ strings = updated_strings[:]
77
+ except:
78
+ print(f"failed to update input string with chat template: {self._model}")
79
+ # encode a batch of strings. converts to tensors and pads automatically, unlike tok_encode.
80
+ old_padding_side = self.tokenizer.padding_side
81
+ self.tokenizer.padding_side = padding_side
82
+
83
+ add_special_tokens = False
84
+
85
+ encoding = self.tokenizer(
86
+ strings,
87
+ truncation=truncation,
88
+ padding="longest",
89
+ return_tensors="pt",
90
+ add_special_tokens=add_special_tokens,
91
+ )
92
+ if left_truncate_len:
93
+ encoding["input_ids"] = encoding["input_ids"][:, -left_truncate_len:]
94
+ encoding["attention_mask"] = encoding["attention_mask"][
95
+ :, -left_truncate_len:
96
+ ]
97
+ self.tokenizer.padding_side = old_padding_side
98
+
99
+ return encoding["input_ids"], encoding["attention_mask"]
src/backend/run_eval_suite.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from lm_eval import evaluator
2
+ from lm_eval.tasks import TaskManager
3
+
4
+ from src.backend.manage_requests import EvalRequest
5
+
6
+ from src.backend.tasks.xsum.task import XSum
7
+ from src.backend.tasks.xsum.task_v2 import XSumv2
8
+
9
+ from src.backend.tasks.cnndm.task import CNNDM
10
+ from src.backend.tasks.cnndm.task_v2 import CNNDMv2
11
+
12
+ from src.backend.tasks.selfcheckgpt.task import SelfCheckGPT
13
+
14
+ from src.backend.huggingface_generate_until import HFLMwithChatTemplate
15
+ from src.backend.moe_infinity import MoEHFLM
16
+
17
+ def run_evaluation(eval_request: EvalRequest, task_names, num_fewshot, batch_size, device, use_cache=None, limit=None, max_nb_samples=100) -> dict:
18
+ if limit:
19
+ print("WARNING: --limit SHOULD ONLY BE USED FOR TESTING. REAL METRICS SHOULD NOT BE COMPUTED USING LIMIT.")
20
+
21
+ # include_task_folder("src/backend/tasks/")
22
+ # initialize_tasks('INFO')
23
+
24
+ print(f"Allocating task manager for: {task_names}")
25
+
26
+ task_manager = TaskManager(include_path="./src/backend/tasks/")
27
+ # task_manager.initialize_tasks('INFO')
28
+
29
+ print(f"Considered Tasks: {task_names}")
30
+ # print(f"Allowed Tasks: {tasks.ALL_TASKS}")
31
+
32
+ # task_names = utils.pattern_match(task_names, tasks.ALL_TASKS)
33
+
34
+ print(f"Selected Tasks: {task_names}")
35
+ print(f"Eval Request: {eval_request.get_model_args()}")
36
+ # hf-chat is implemented to use apply_chat_template
37
+ results = evaluator.simple_evaluate(model="moe-infinity", # "hf-causal-experimental", # "hf-causal", hf-chat
38
+ model_args=eval_request.get_model_args(),
39
+ tasks=task_names,
40
+ num_fewshot=num_fewshot,
41
+ batch_size=batch_size,
42
+ max_batch_size=8,
43
+ device=device,
44
+ use_cache=use_cache,
45
+ limit=limit,
46
+ write_out=True,
47
+ task_manager=task_manager)
48
+
49
+ results["config"]["model_dtype"] = eval_request.precision
50
+ results["config"]["model_name"] = eval_request.model
51
+ results["config"]["model_sha"] = eval_request.revision
52
+
53
+ if max_nb_samples is not None:
54
+ if 'samples' in results:
55
+ samples = results['samples']
56
+ for task_name in samples.keys():
57
+ if len(samples[task_name]) > max_nb_samples:
58
+ results['samples'][task_name] = results['samples'][task_name][:max_nb_samples]
59
+
60
+ # print(evaluator.make_table(results))
61
+
62
+ return results
src/backend/sort_queue.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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)
src/backend/tasks/__init__.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
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
src/backend/tasks/cnndm/README.md ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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?
src/backend/tasks/cnndm/cnndm.yaml ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ task: cnndm
2
+ class: !function task.CNNDM
src/backend/tasks/cnndm/cnndm_v2.yaml ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ task: cnndm_v2
2
+ class: !function task_v2.CNNDMv2
src/backend/tasks/cnndm/task.py ADDED
@@ -0,0 +1,194 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from lm_eval.api.task import ConfigurableTask
2
+ from lm_eval.api.instance import Instance
3
+ # from lm_eval.api.registry import register_task
4
+ from lm_eval.api.metrics import mean
5
+
6
+ import torch
7
+ import sacrebleu
8
+ from rouge_score import rouge_scorer, scoring
9
+
10
+
11
+ def bleu(refs, preds):
12
+ """
13
+ Returns `t5` style BLEU scores. See the related implementation:
14
+ https://github.com/google-research/text-to-text-transfer-transformer/blob/3d10afd51ba97ac29eb66ae701eca274488202f7/t5/evaluation/metrics.py#L41
15
+
16
+ :param refs:
17
+ A `list` of `list` of reference `str`s.
18
+ :param preds:
19
+ A `list` of predicted `str`s.
20
+ """
21
+ score = sacrebleu.corpus_bleu(
22
+ preds,
23
+ refs,
24
+ smooth_method="exp",
25
+ smooth_value=0.0,
26
+ force=False,
27
+ lowercase=False,
28
+ tokenize="intl",
29
+ use_effective_order=False,
30
+ ).score
31
+ return score
32
+
33
+
34
+ def rouge(refs, preds):
35
+ """
36
+ Returns `t5` style ROUGE scores. See the related implementation:
37
+ https://github.com/google-research/text-to-text-transfer-transformer/blob/3d10afd51ba97ac29eb66ae701eca274488202f7/t5/evaluation/metrics.py#L68
38
+
39
+ :param refs:
40
+ A `list` of reference `strs`.
41
+ :param preds:
42
+ A `list` of predicted `strs`.
43
+ """
44
+ rouge_types = ["rouge1", "rouge2", "rougeLsum"]
45
+ scorer = rouge_scorer.RougeScorer(rouge_types)
46
+ # Add newlines between sentences to correctly compute `rougeLsum`.
47
+
48
+ def _prepare_summary(summary):
49
+ summary = summary.replace(" . ", ".\n")
50
+ return summary
51
+
52
+ # Accumulate confidence intervals.
53
+ aggregator = scoring.BootstrapAggregator()
54
+ for ref, pred in zip(refs, preds):
55
+ ref = _prepare_summary(ref)
56
+ pred = _prepare_summary(pred)
57
+ aggregator.add_scores(scorer.score(ref, pred))
58
+ result = aggregator.aggregate()
59
+ return {type: result[type].mid.fmeasure * 100 for type in rouge_types}
60
+
61
+
62
+ # @register_task("cnndm")
63
+ class CNNDM(ConfigurableTask):
64
+ VERSION = 0
65
+ DATASET_PATH = "cnn_dailymail"
66
+ DATASET_NAME = "3.0.0"
67
+
68
+ def __init__(self):
69
+ super().__init__(config={'metadata': {'version': self.VERSION}})
70
+ self.factkb_tokenizer = None
71
+ self.factkb_model = None
72
+ self.bert_score = None
73
+
74
+ def maybe_init_factkb(self):
75
+ if self.factkb_tokenizer is None or self.factkb_model is None:
76
+ from transformers import AutoTokenizer, AutoModelForSequenceClassification
77
+ self.factkb_tokenizer = AutoTokenizer.from_pretrained("roberta-base", padding="max_length", truncation=True)
78
+ self.factkb_model = AutoModelForSequenceClassification.from_pretrained("bunsenfeng/FactKB", num_labels=2, device_map="auto")
79
+
80
+ def maybe_init_bertscore(self):
81
+ if self.bert_score is None:
82
+ from evaluate import load
83
+ self.bert_score = load("bertscore")
84
+
85
+ def has_training_docs(self):
86
+ return True
87
+
88
+ def has_validation_docs(self):
89
+ return True
90
+
91
+ def has_test_docs(self):
92
+ return True
93
+
94
+ def training_docs(self):
95
+ return self.dataset["train"]
96
+
97
+ def validation_docs(self):
98
+ return self.dataset["validation"]
99
+
100
+ def test_docs(self):
101
+ return self.dataset["test"]
102
+
103
+ def doc_to_text(self, doc):
104
+ return f'Document: {doc["article"]}\nSummary:'
105
+
106
+ @staticmethod
107
+ def should_decontaminate():
108
+ return True
109
+
110
+ def doc_to_decontamination_query(self, doc):
111
+ return doc["article"]
112
+
113
+ def doc_to_target(self, doc):
114
+ return doc["highlights"]
115
+
116
+ def construct_requests(self, doc, ctx, **kwargs):
117
+ """Uses RequestFactory to construct Requests and returns an iterable of
118
+ Requests which will be sent to the LM.
119
+
120
+ :param doc:
121
+ The document as returned from training_docs, validation_docs, or test_docs.
122
+ :param ctx: str
123
+ The context string, generated by fewshot_context. This includes the natural
124
+ language description, as well as the few shot examples, and the question
125
+ part of the document for `doc`.
126
+ """
127
+
128
+ return [
129
+ Instance(
130
+ request_type="generate_until",
131
+ doc=doc,
132
+ arguments=(ctx, {"until": ["\n"]}),
133
+ idx=0,
134
+ **kwargs
135
+ )
136
+ ]
137
+
138
+ def process_results(self, doc, results):
139
+ completion = results[0]
140
+ # true_refs, false_refs = doc["correct_answers"], doc["incorrect_answers"]
141
+ # all_refs = true_refs + false_refs
142
+
143
+ document = doc["article"]
144
+ gold_summary = doc["highlights"]
145
+
146
+ true_refs = [doc["highlights"]]
147
+ all_refs = true_refs
148
+
149
+ # ROUGE-N
150
+ rouge_scores = [rouge([ref], [completion]) for ref in all_refs]
151
+ # ROUGE-1
152
+ rouge1_scores = [score["rouge1"] for score in rouge_scores]
153
+ # ROUGE-2
154
+ rouge2_scores = [score["rouge2"] for score in rouge_scores]
155
+ # ROUGE-L
156
+ rougeL_scores = [score["rougeLsum"] for score in rouge_scores]
157
+
158
+ self.maybe_init_factkb()
159
+ input_factkb = [[completion, document]]
160
+ factkb_tokens = self.factkb_tokenizer(input_factkb, return_tensors="pt", padding="max_length", truncation=True).to(self.factkb_model.device)
161
+ factkb_logits = self.factkb_model(**factkb_tokens).logits
162
+ factkb_res = torch.softmax(factkb_logits, dim=1)
163
+
164
+ self.maybe_init_bertscore()
165
+ bert_score_res = self.bert_score.compute(predictions=[completion], references=[gold_summary], model_type="microsoft/deberta-xlarge-mnli", lang="en")
166
+
167
+ res = {
168
+ "rouge1": rouge1_scores[0],
169
+ "rouge2": rouge2_scores[0],
170
+ "rougeL": rougeL_scores[0],
171
+ "factKB": float(factkb_res[0][1]),
172
+ "bertscore_precision": float(bert_score_res["precision"][0]),
173
+ "bertscore_recall": float(bert_score_res["recall"][0]),
174
+ "bertscore_f1": float(bert_score_res["f1"][0])
175
+ }
176
+
177
+ return res
178
+
179
+ def aggregation(self):
180
+ """
181
+ :returns: {str: [float] -> float}
182
+ A dictionary where keys are the names of submetrics and values are
183
+ functions that aggregate a list of metrics
184
+ """
185
+ return {k: mean for k in ["rouge1", "rouge2", "rougeL", "factKB", "bertscore_precision", "bertscore_recall", "bertscore_f1"]}
186
+
187
+ def higher_is_better(self):
188
+ """
189
+ :returns: {str: bool}
190
+ A dictionary where keys are the names of submetrics and values are
191
+ whether a higher value of the submetric is better
192
+ """
193
+ return {k: True for k in ["rouge1", "rouge2", "rougeL", "factKB", "bertscore_precision", "bertscore_recall", "bertscore_f1"]}
194
+
src/backend/tasks/cnndm/task_v2.py ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from lm_eval.api.task import ConfigurableTask
2
+ from lm_eval.api.instance import Instance
3
+ # from lm_eval.api.registry import register_task
4
+ from lm_eval.api.metrics import mean
5
+
6
+ import torch
7
+ import sacrebleu
8
+ from rouge_score import rouge_scorer, scoring
9
+
10
+
11
+ def bleu(refs, preds):
12
+ """
13
+ Returns `t5` style BLEU scores. See the related implementation:
14
+ https://github.com/google-research/text-to-text-transfer-transformer/blob/3d10afd51ba97ac29eb66ae701eca274488202f7/t5/evaluation/metrics.py#L41
15
+
16
+ :param refs:
17
+ A `list` of `list` of reference `str`s.
18
+ :param preds:
19
+ A `list` of predicted `str`s.
20
+ """
21
+ score = sacrebleu.corpus_bleu(
22
+ preds,
23
+ refs,
24
+ smooth_method="exp",
25
+ smooth_value=0.0,
26
+ force=False,
27
+ lowercase=False,
28
+ tokenize="intl",
29
+ use_effective_order=False,
30
+ ).score
31
+ return score
32
+
33
+
34
+ def rouge(refs, preds):
35
+ """
36
+ Returns `t5` style ROUGE scores. See the related implementation:
37
+ https://github.com/google-research/text-to-text-transfer-transformer/blob/3d10afd51ba97ac29eb66ae701eca274488202f7/t5/evaluation/metrics.py#L68
38
+
39
+ :param refs:
40
+ A `list` of reference `strs`.
41
+ :param preds:
42
+ A `list` of predicted `strs`.
43
+ """
44
+ rouge_types = ["rouge1", "rouge2", "rougeLsum"]
45
+ scorer = rouge_scorer.RougeScorer(rouge_types)
46
+ # Add newlines between sentences to correctly compute `rougeLsum`.
47
+
48
+ def _prepare_summary(summary):
49
+ summary = summary.replace(" . ", ".\n")
50
+ return summary
51
+
52
+ # Accumulate confidence intervals.
53
+ aggregator = scoring.BootstrapAggregator()
54
+ for ref, pred in zip(refs, preds):
55
+ ref = _prepare_summary(ref)
56
+ pred = _prepare_summary(pred)
57
+ aggregator.add_scores(scorer.score(ref, pred))
58
+ result = aggregator.aggregate()
59
+ return {type: result[type].mid.fmeasure * 100 for type in rouge_types}
60
+
61
+
62
+ # @register_task("cnndm_v2")
63
+ class CNNDMv2(ConfigurableTask):
64
+ VERSION = 2
65
+ DATASET_PATH = "cnn_dailymail"
66
+ DATASET_NAME = "3.0.0"
67
+
68
+ def __init__(self):
69
+ super().__init__(config={'metadata': {'version': self.VERSION},
70
+ 'generation_kwargs': {'do_sample': False, 'temperature': 0.0, 'until': ['\n', '\n\n']}})
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
+ self.factkb_tokenizer = AutoTokenizer.from_pretrained("roberta-base", padding="max_length", truncation=True)
79
+ self.factkb_model = AutoModelForSequenceClassification.from_pretrained("bunsenfeng/FactKB", num_labels=2, device_map="auto")
80
+
81
+ def maybe_init_bertscore(self):
82
+ if self.bert_score is None:
83
+ from evaluate import load
84
+ self.bert_score = load("bertscore")
85
+
86
+ def has_training_docs(self):
87
+ return True
88
+
89
+ def has_validation_docs(self):
90
+ return True
91
+
92
+ def has_test_docs(self):
93
+ return True
94
+
95
+ def training_docs(self):
96
+ return self.dataset["train"]
97
+
98
+ def validation_docs(self):
99
+ return self.dataset["validation"]
100
+
101
+ def test_docs(self):
102
+ return self.dataset["test"]
103
+
104
+ # def custom_prompt(self):
105
+ # res = "Provide a summary of the provided article."
106
+ # return res
107
+
108
+ # def fewshot_delimiter(self):
109
+ # return "\n\n"
110
+
111
+ # From https://arxiv.org/abs/2305.14739
112
+ def doc_to_text(self, doc):
113
+ return f'Article: {doc["article"]}\nSummarize the article. Summary:'
114
+
115
+ @staticmethod
116
+ def should_decontaminate():
117
+ return True
118
+
119
+ def doc_to_decontamination_query(self, doc):
120
+ return doc["article"]
121
+
122
+ def doc_to_target(self, doc):
123
+ return doc["highlights"]
124
+
125
+ def construct_requests(self, doc, ctx, **kwargs):
126
+ """Uses RequestFactory to construct Requests and returns an iterable of
127
+ Requests which will be sent to the LM.
128
+
129
+ :param doc:
130
+ The document as returned from training_docs, validation_docs, or test_docs.
131
+ :param ctx: str
132
+ The context string, generated by fewshot_context. This includes the natural
133
+ language description, as well as the few shot examples, and the question
134
+ part of the document for `doc`.
135
+ """
136
+
137
+ return [
138
+ Instance(
139
+ request_type="generate_until",
140
+ doc=doc,
141
+ arguments=(ctx, {"until": ["\n"]}),
142
+ idx=0,
143
+ **kwargs
144
+ )
145
+ ]
146
+
147
+ def process_results(self, doc, results):
148
+ completion = results[0]
149
+ # true_refs, false_refs = doc["correct_answers"], doc["incorrect_answers"]
150
+ # all_refs = true_refs + false_refs
151
+
152
+ document = doc["article"]
153
+ gold_summary = doc["highlights"]
154
+
155
+ true_refs = [doc["highlights"]]
156
+ all_refs = true_refs
157
+
158
+ # ROUGE-N
159
+ rouge_scores = [rouge([ref], [completion]) for ref in all_refs]
160
+ # ROUGE-1
161
+ rouge1_scores = [score["rouge1"] for score in rouge_scores]
162
+ # ROUGE-2
163
+ rouge2_scores = [score["rouge2"] for score in rouge_scores]
164
+ # ROUGE-L
165
+ rougeL_scores = [score["rougeLsum"] for score in rouge_scores]
166
+
167
+ self.maybe_init_factkb()
168
+ input_factkb = [[completion, document]]
169
+ factkb_tokens = self.factkb_tokenizer(input_factkb, return_tensors="pt", padding="max_length", truncation=True).to(self.factkb_model.device)
170
+ factkb_logits = self.factkb_model(**factkb_tokens).logits
171
+ factkb_res = torch.softmax(factkb_logits, dim=1)
172
+
173
+ self.maybe_init_bertscore()
174
+ bert_score_res = self.bert_score.compute(predictions=[completion], references=[gold_summary], model_type="microsoft/deberta-xlarge-mnli", lang="en")
175
+
176
+ res = {
177
+ "rouge1": rouge1_scores[0],
178
+ "rouge2": rouge2_scores[0],
179
+ "rougeL": rougeL_scores[0],
180
+ "factKB": float(factkb_res[0][1]),
181
+ "bertscore_precision": float(bert_score_res["precision"][0]),
182
+ "bertscore_recall": float(bert_score_res["recall"][0]),
183
+ "bertscore_f1": float(bert_score_res["f1"][0])
184
+ }
185
+
186
+ return res
187
+
188
+ def aggregation(self):
189
+ """
190
+ :returns: {str: [float] -> float}
191
+ A dictionary where keys are the names of submetrics and values are
192
+ functions that aggregate a list of metrics
193
+ """
194
+ return {k: mean for k in ["rouge1", "rouge2", "rougeL", "factKB", "bertscore_precision", "bertscore_recall", "bertscore_f1"]}
195
+
196
+ def higher_is_better(self):
197
+ """
198
+ :returns: {str: bool}
199
+ A dictionary where keys are the names of submetrics and values are
200
+ whether a higher value of the submetric is better
201
+ """
202
+ return {k: True for k in ["rouge1", "rouge2", "rougeL", "factKB", "bertscore_precision", "bertscore_recall", "bertscore_f1"]}
203
+
src/backend/tasks/faithdial/faithdial.yaml ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
src/backend/tasks/faithdial/faithdial_v2.yaml ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
src/backend/tasks/faithdial/utils.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List, Union
2
+ ValueType = Union[str, List[str]]
3
+
4
+
5
+ def doc_to_text(doc: dict[str, ValueType]) -> str:
6
+ history_str = " ".join([f'[{"Human" if i % 2 == 0 else "Assistant"}] {m}' for i, m in enumerate(doc['history'])])
7
+ doc_text = f'#Knowledge#: {doc["knowledge"]}\n#Dialogue History#: {history_str}\n#Response#: {doc["response"]}\n#Hallucinated#:'
8
+ return doc_text
9
+
10
+
11
+ def doc_to_text_v2(doc: dict[str, ValueType]) -> str:
12
+ history_str = " ".join([f'[{"Human" if i % 2 == 0 else "Assistant"}] {m}' for i, m in enumerate(doc['history'])])
13
+ doc_text = f'#Knowledge#: {doc["knowledge"]}\n#Dialogue History#: {history_str}\n#Response#: {doc["original_response"]}\n#Hallucinated#:'
14
+ return doc_text
15
+
16
+
17
+ def doc_to_target(doc: dict[str, ValueType]) -> str:
18
+ res = "true" if "Hallucination" in doc["BEGIN"] else "false"
19
+ return res
src/backend/tasks/fever/fever10.yaml ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
src/backend/tasks/fever/fever11.yaml ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
src/backend/tasks/halueval/halueval_dialogue.yaml ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
src/backend/tasks/halueval/halueval_qa.yaml ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
src/backend/tasks/halueval/halueval_summarization.yaml ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
src/backend/tasks/halueval/utils.py ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 = QA_INSTURCTIONS + "\n\n#Knowledge#: " + doc["knowledge"] + "\n#Question#: " + doc["question"] + "\n#Answer#: " + doc["answer"] + "\n#Your Judgement#:"
87
+ return doc_text
88
+
89
+
90
+ def doc_to_text_dialogue(doc: dict[str, str]) -> str:
91
+ # prompt = instruction + "\n\n#Dialogue History#: " + dialog + "\n#Response#: " + response + "\n#Your Judgement#:"
92
+ doc_text = DIALOGUE_INSTRUCTIONS + "\n\n#Knowledge#: " + doc["knowledge"] + "\n#Dialogue History#: " + doc["dialogue_history"] + "\n#Response#: " + doc["response"] + "\n#Your Judgement#:"
93
+ return doc_text
94
+
95
+
96
+ def doc_to_text_summarization(doc: dict[str, str]) -> str:
97
+ # prompt1 = instruction + "\n\n#Document#: " + document
98
+ # prompt2 = "\n#Summary#: " + summary + "\n#Your Judgement#:"
99
+ doc_text_1 = SUMMARIZATION_INSTRUCTIONS + "\n\n#Document#: " + doc["document"]
100
+ doc_text_2 = "\n#Summary#: " + doc["summary"] + "\n#Your Judgement#:"
101
+ doc_text = doc_text_1 + doc_text_2
102
+ return doc_text
103
+
104
+
105
+ def doc_to_target(doc: dict[str, str]) -> str:
106
+ return doc['hallucination']
107
+
108
+
109
+ def compute_metrics(gold_answer: str, prediction: str) -> dict[str, float]:
110
+ is_correct = True
111
+
112
+ if ("Yes" in prediction and "No" in prediction) or ("Yes" not in prediction and "No" not in prediction):
113
+ is_correct = False
114
+ elif "Yes" in prediction:
115
+ prediction = "yes"
116
+ elif "No" in prediction:
117
+ prediction = "no"
118
+
119
+ is_exact = gold_answer == prediction
120
+
121
+ res = {"correctness": 1.0 if is_correct else 0.0}
122
+ if is_correct:
123
+ res["em"] = 1.0 if is_exact else 0.0
124
+
125
+ res["acc"] = 1.0 if (is_correct and is_exact) else 0.0
126
+
127
+ return res
128
+
129
+
130
+ def process_results(doc: dict[str, str], results: list[str]) -> dict[str, float]:
131
+ # results is e.g., ['Yes']
132
+ gold_list = doc_to_target(doc)
133
+ # gold_list is e.g., 'yes'
134
+ prediction = results[0].strip().split("\n")[0]
135
+ scores = compute_metrics(gold_list, prediction)
136
+ return scores
src/backend/tasks/memo-trap/memo-trap.yaml ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
src/backend/tasks/memo-trap/memo-trap_v2.yaml ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ task: memo-trap_v2
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
+ target_delimiter: ""
13
+ should_decontaminate: False
14
+ doc_to_decontamination_query: prompt
15
+ metric_list:
16
+ - metric: acc
17
+ aggregation: mean
18
+ higher_is_better: true
19
+ metadata:
20
+ version: 0.0
src/backend/tasks/nq8/README.md ADDED
File without changes
src/backend/tasks/nq8/nq8.yaml ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ task: nq8
2
+ dataset_path: nq_open
3
+ output_type: generate_until
4
+ training_split: train
5
+ validation_split: validation
6
+ description: "Answer these questions:\n\n"
7
+ doc_to_text: "Q: {{question}}?\nA:"
8
+ doc_to_target: "{{answer}}" # TODO: should be multi-target
9
+ fewshot_delimiter: "\n"
10
+ generation_kwargs:
11
+ until:
12
+ - "\n"
13
+ - "."
14
+ - ","
15
+ do_sample: false
16
+ temperature: 0.0
17
+ filter_list:
18
+ - name: remove_whitespace
19
+ filter:
20
+ - function: remove_whitespace
21
+ - function: take_first
22
+ target_delimiter: " "
23
+ metric_list:
24
+ - metric: exact_match
25
+ aggregation: mean
26
+ higher_is_better: true
27
+ ignore_case: true
28
+ ignore_punctuation: true
29
+ regexes_to_ignore:
30
+ - "\\b(?:The |the |An |A |The |a |an )"
31
+ metadata:
32
+ version: 0.0
src/backend/tasks/nq_swap/nq_swap.yaml ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ task: nq_swap
2
+ dataset_path: pminervini/NQ-Swap
3
+ output_type: generate_until
4
+ validation_split: substituted
5
+ description: "Answer the following question based on the provided context:\n\n"
6
+ doc_to_text: "Context: {{context}}\nQuestion: {{question}}?\nAnswer:"
7
+ doc_to_target: "{{answer}}" # TODO: should be multi-target
8
+ fewshot_delimiter: "\n\n"
9
+ generation_kwargs:
10
+ until:
11
+ - "\n"
12
+ - "."
13
+ - ","
14
+ do_sample: false
15
+ temperature: 0.0
16
+ filter_list:
17
+ - name: remove_whitespace
18
+ filter:
19
+ - function: remove_whitespace
20
+ - function: take_first
21
+ target_delimiter: " "
22
+ metric_list:
23
+ - metric: exact_match
24
+ aggregation: mean
25
+ higher_is_better: true
26
+ ignore_case: true
27
+ ignore_punctuation: true
28
+ regexes_to_ignore:
29
+ - "\\b(?:The |the |An |A |The |a |an )"
30
+ metadata:
31
+ version: 0.0
src/backend/tasks/selfcheckgpt/README.md ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Task-name
2
+
3
+ ### Paper
4
+
5
+ Title: `SelfCheckGPT: Zero-Resource Black-Box Hallucination Detection for Generative Large Language Models`
6
+
7
+ Abstract: `Generative Large Language Models (LLMs) such as GPT-3 are capable of generating highly fluent responses to a wide variety of user prompts. However, LLMs are known to hallucinate facts and make non-factual statements which can undermine trust in their output. Existing fact-checking approaches either require access to the output probability distribution (which may not be available for systems such as ChatGPT) or external databases that are interfaced via separate, often complex, modules. In this work, we propose "SelfCheckGPT", a simple sampling-based approach that can be used to fact-check the responses of black-box models in a zero-resource fashion, i.e. without an external database. SelfCheckGPT leverages the simple idea that if an LLM has knowledge of a given concept, sampled responses are likely to be similar and contain consistent facts. However, for hallucinated facts, stochastically sampled responses are likely to diverge and contradict one another. We investigate this approach by using GPT-3 to generate passages about individuals from the WikiBio dataset, and manually annotate the factuality of the generated passages. We demonstrate that SelfCheckGPT can: i) detect non-factual and factual sentences; and ii) rank passages in terms of factuality. We compare our approach to several baselines and show that our approach has considerably higher AUC-PR scores in sentence-level hallucination detection and higher correlation scores in passage-level factuality assessment compared to grey-box methods.`
8
+
9
+ `task.py` in this folder uses the original
10
+
11
+ Homepage: [selfcheckgpt](https://github.com/potsawee/selfcheckgpt)
12
+
13
+
14
+ ### Citation
15
+
16
+ ```
17
+ @article{manakul2023selfcheckgpt,
18
+ title={Selfcheckgpt: Zero-resource black-box hallucination detection for generative large language models},
19
+ author={Manakul, Potsawee and Liusie, Adian and Gales, Mark JF},
20
+ journal={arXiv preprint arXiv:2303.08896},
21
+ year={2023}
22
+ }
23
+ ```
24
+
25
+ #### Tasks
26
+
27
+ * `selfcheckgpt`: This task uses generative models to generate wikipedia passage based on given starting topics/words. Then generated passages are messured by [selfcheckgpt](https://github.com/potsawee/selfcheckgpt). The default metric is `SelfCheckNgram`, which does not need GPU. Other metrics are `SelfCheckBERTScore`, `SelfCheckMQAG` and `SelfCheckNLI`, which are model-based scores. You can change the metric by changing the enviornment variables.
28
+
29
+ The results `"avg-selfcheckgpt` and `max-selfcheckgpt` is the average and max sentences' `selfcheckgpt` score for the generated passage(with temperature=0.0). The score is lower and it is less likely to be hallucination.
30
+ ```
31
+ export SELFCHECKGPTTYPE=SelfCheckBERTScore #SelfCheckMQAG, SelfCheckNLI
32
+ ```
33
+
34
+ Since model-based metric are slow when they are running in cpu, you can change the running device to gpu by:
35
+ ```
36
+ export SELFCHECKGPTDEVICE=cuda
37
+ ```
38
+ #### Dependencies for sucessful running
39
+ ```
40
+ pip install spacy
41
+ pip install selfcheckgpt
42
+ python -m spacy download en
43
+ ```
44
+ ### Checklist
45
+
46
+ For adding novel benchmarks/datasets to the library:
47
+ * [ ] Is the task an existing benchmark in the literature?
48
+ * [x] Have you referenced the original paper that introduced the task?
49
+ * [x] 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?
50
+
51
+
52
+ If other tasks on this dataset are already supported:
53
+ * [x] Is the "Main" variant of this task clearly denoted?
54
+ * [x] Have you provided a short sentence in a README on what each new variant adds / evaluates?
55
+ * [ ] Have you noted which, if any, published evaluation setups are matched by this variant?
56
+
57
+
58
+
59
+
60
+
61
+
62
+
63
+
64
+ # SelfCheckGPT: Zero-Resource Black-Box Hallucination Detection for Generative Large Language Models
65
+
66
+ In order to run selfcheckgpt evaluation, these dependencies should be installed.
67
+ ```
68
+ pip install spacy
69
+ pip install selfcheckgpt
70
+ python -m spacy download en
71
+ ```
72
+
73
+ selfcheckgpt support different evaluation methods including: `SelfCheckNgram`, `SelfCheckBERTScore`, `SelfCheckMQAG` and `SelfCheckNLI`.
74
+ The default evaluation method in llm-eval-harness is `SelfCheckNgram`. You can change the evaluation method by changing the environment variable
75
+ ```
76
+ export SELFCHECKGPTTYPE=SelfCheckNgram
77
+ ```
78
+ For `SelfCheckBERTScore`, `SelfCheckMQAG` and `SelfCheckNLI` evaluation method which will also run some huggingface models, You can change the running device of the selfcheckgpt to GPU by setting enviroment device:
79
+ ```
80
+ export SELFCHECKGPTDEVICE=cuda
81
+ ```
82
+
83
+ ## Citation
84
+
85
+ ```
86
+ @misc{manakul2023selfcheckgpt,
87
+ title={SelfCheckGPT: Zero-Resource Black-Box Hallucination Detection for Generative Large Language Models},
88
+ author={Potsawee Manakul and Adian Liusie and Mark J. F. Gales},
89
+ year={2023},
90
+ eprint={2303.08896},
91
+ archivePrefix={arXiv},
92
+ primaryClass={cs.CL}
93
+ }
94
+ ```