hc99 commited on
Commit
9ce23df
·
verified ·
1 Parent(s): e4b9a7b

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. testbed/EleutherAI__lm-evaluation-harness/lm_eval/__init__.py +1 -0
  2. testbed/EleutherAI__lm-evaluation-harness/lm_eval/__main__.py +461 -0
  3. testbed/EleutherAI__lm-evaluation-harness/lm_eval/evaluator.py +657 -0
  4. testbed/EleutherAI__lm-evaluation-harness/lm_eval/evaluator_utils.py +544 -0
  5. testbed/EleutherAI__lm-evaluation-harness/lm_eval/loggers/__init__.py +2 -0
  6. testbed/EleutherAI__lm-evaluation-harness/lm_eval/loggers/evaluation_tracker.py +521 -0
  7. testbed/EleutherAI__lm-evaluation-harness/lm_eval/loggers/utils.py +143 -0
  8. testbed/EleutherAI__lm-evaluation-harness/lm_eval/loggers/wandb_logger.py +352 -0
  9. testbed/EleutherAI__lm-evaluation-harness/lm_eval/tasks/README.md +122 -0
  10. testbed/EleutherAI__lm-evaluation-harness/lm_eval/tasks/__init__.py +652 -0
  11. testbed/EleutherAI__lm-evaluation-harness/lm_eval/tasks/tinyBenchmarks/tinyGSM8k.yaml +44 -0
  12. testbed/EleutherAI__lm-evaluation-harness/lm_eval/tasks/tmlu/README.md +59 -0
  13. testbed/EleutherAI__lm-evaluation-harness/lm_eval/tasks/tmlu/default/_generate_configs.py +198 -0
  14. testbed/EleutherAI__lm-evaluation-harness/lm_eval/tasks/tmlu/default/_tmlu.yaml +37 -0
  15. testbed/EleutherAI__lm-evaluation-harness/lm_eval/tasks/tmlu/default/tmlu_AST_biology.yaml +15 -0
  16. testbed/EleutherAI__lm-evaluation-harness/lm_eval/tasks/tmlu/default/tmlu_AST_chinese.yaml +15 -0
  17. testbed/EleutherAI__lm-evaluation-harness/lm_eval/tasks/tmlu/default/tmlu_AST_civics.yaml +15 -0
  18. testbed/EleutherAI__lm-evaluation-harness/lm_eval/tasks/tmlu/default/tmlu_AST_geography.yaml +15 -0
  19. testbed/EleutherAI__lm-evaluation-harness/lm_eval/tasks/tmlu/default/tmlu_AST_history.yaml +15 -0
  20. testbed/EleutherAI__lm-evaluation-harness/lm_eval/tasks/tmlu/default/tmlu_CAP_biology.yaml +15 -0
  21. testbed/EleutherAI__lm-evaluation-harness/lm_eval/tasks/tmlu/default/tmlu_CAP_chemistry.yaml +15 -0
  22. testbed/EleutherAI__lm-evaluation-harness/lm_eval/tasks/tmlu/default/tmlu_CAP_chinese.yaml +15 -0
  23. testbed/EleutherAI__lm-evaluation-harness/lm_eval/tasks/tmlu/default/tmlu_CAP_civics.yaml +15 -0
  24. testbed/EleutherAI__lm-evaluation-harness/lm_eval/tasks/tmlu/default/tmlu_CAP_earth_science.yaml +15 -0
  25. testbed/EleutherAI__lm-evaluation-harness/lm_eval/tasks/tmlu/default/tmlu_CAP_geography.yaml +15 -0
  26. testbed/EleutherAI__lm-evaluation-harness/lm_eval/tasks/tmlu/default/tmlu_CAP_history.yaml +15 -0
  27. testbed/EleutherAI__lm-evaluation-harness/lm_eval/tasks/tmlu/default/tmlu_GSAT_biology.yaml +16 -0
  28. testbed/EleutherAI__lm-evaluation-harness/lm_eval/tasks/tmlu/default/tmlu_GSAT_chemistry.yaml +16 -0
  29. testbed/EleutherAI__lm-evaluation-harness/lm_eval/tasks/tmlu/default/tmlu_GSAT_chinese.yaml +15 -0
  30. testbed/EleutherAI__lm-evaluation-harness/lm_eval/tasks/tmlu/default/tmlu_GSAT_civics.yaml +15 -0
  31. testbed/EleutherAI__lm-evaluation-harness/lm_eval/tasks/tmlu/default/tmlu_GSAT_earth_science.yaml +16 -0
  32. testbed/EleutherAI__lm-evaluation-harness/lm_eval/tasks/tmlu/default/tmlu_GSAT_geography.yaml +15 -0
  33. testbed/EleutherAI__lm-evaluation-harness/lm_eval/tasks/tmlu/default/tmlu_GSAT_history.yaml +15 -0
  34. testbed/EleutherAI__lm-evaluation-harness/lm_eval/tasks/tmlu/default/tmlu_accountant.yaml +15 -0
  35. testbed/EleutherAI__lm-evaluation-harness/lm_eval/tasks/tmlu/default/tmlu_clinical_psychologist.yaml +15 -0
  36. testbed/EleutherAI__lm-evaluation-harness/lm_eval/tasks/tmlu/default/tmlu_clinical_traditional_chinese_medicine.yaml +15 -0
  37. testbed/EleutherAI__lm-evaluation-harness/lm_eval/tasks/tmlu/default/tmlu_driving_rule.yaml +15 -0
  38. testbed/EleutherAI__lm-evaluation-harness/lm_eval/tasks/tmlu/default/tmlu_lawyer_qualification.yaml +15 -0
  39. testbed/EleutherAI__lm-evaluation-harness/lm_eval/tasks/tmlu/default/tmlu_nutritionist.yaml +15 -0
  40. testbed/EleutherAI__lm-evaluation-harness/lm_eval/tasks/tmlu/default/tmlu_taiwan_tourist_resources.yaml +15 -0
  41. testbed/EleutherAI__lm-evaluation-harness/lm_eval/tasks/tmlu/default/tmlu_teacher_qualification.yaml +15 -0
  42. testbed/EleutherAI__lm-evaluation-harness/lm_eval/tasks/tmlu/default/tmlu_tour_guide.yaml +15 -0
  43. testbed/EleutherAI__lm-evaluation-harness/lm_eval/tasks/tmlu/default/tmlu_tour_leader.yaml +15 -0
  44. testbed/EleutherAI__lm-evaluation-harness/lm_eval/tasks/tmlu/default/utils.py +23 -0
  45. testbed/EleutherAI__lm-evaluation-harness/lm_eval/tasks/tmlu/subject.tsv +38 -0
  46. testbed/EleutherAI__lm-evaluation-harness/lm_eval/tasks/tmmluplus/README.md +47 -0
  47. testbed/EleutherAI__lm-evaluation-harness/lm_eval/tasks/tmmluplus/default/_generate_configs.py +211 -0
  48. testbed/EleutherAI__lm-evaluation-harness/lm_eval/tasks/tmmluplus/default/_tmmluplus.yaml +13 -0
  49. testbed/EleutherAI__lm-evaluation-harness/lm_eval/tasks/tmmluplus/default/_tmmluplus_STEM.yaml +10 -0
  50. testbed/EleutherAI__lm-evaluation-harness/lm_eval/tasks/tmmluplus/default/_tmmluplus_humanities.yaml +10 -0
testbed/EleutherAI__lm-evaluation-harness/lm_eval/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .evaluator import evaluate, simple_evaluate
testbed/EleutherAI__lm-evaluation-harness/lm_eval/__main__.py ADDED
@@ -0,0 +1,461 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import json
3
+ import logging
4
+ import os
5
+ import sys
6
+ from functools import partial
7
+ from typing import Union
8
+
9
+ from lm_eval import evaluator, utils
10
+ from lm_eval.evaluator import request_caching_arg_to_dict
11
+ from lm_eval.loggers import EvaluationTracker, WandbLogger
12
+ from lm_eval.tasks import TaskManager
13
+ from lm_eval.utils import handle_non_serializable, make_table, simple_parse_args_string
14
+
15
+
16
+ def _int_or_none_list_arg_type(
17
+ min_len: int, max_len: int, defaults: str, value: str, split_char: str = ","
18
+ ):
19
+ def parse_value(item):
20
+ item = item.strip().lower()
21
+ if item == "none":
22
+ return None
23
+ try:
24
+ return int(item)
25
+ except ValueError:
26
+ raise argparse.ArgumentTypeError(f"{item} is not an integer or None")
27
+
28
+ items = [parse_value(v) for v in value.split(split_char)]
29
+ num_items = len(items)
30
+
31
+ if num_items == 1:
32
+ # Makes downstream handling the same for single and multiple values
33
+ items = items * max_len
34
+ elif num_items < min_len or num_items > max_len:
35
+ raise argparse.ArgumentTypeError(
36
+ f"Argument requires {max_len} integers or None, separated by '{split_char}'"
37
+ )
38
+ elif num_items != max_len:
39
+ logging.warning(
40
+ f"Argument requires {max_len} integers or None, separated by '{split_char}'. "
41
+ "Missing values will be filled with defaults."
42
+ )
43
+ default_items = [parse_value(v) for v in defaults.split(split_char)]
44
+ items.extend(
45
+ default_items[num_items:]
46
+ ) # extend items list with missing defaults
47
+
48
+ return items
49
+
50
+
51
+ def check_argument_types(parser: argparse.ArgumentParser):
52
+ """
53
+ Check to make sure all CLI args are typed, raises error if not
54
+ """
55
+ for action in parser._actions:
56
+ if action.dest != "help" and not action.const:
57
+ if action.type is None:
58
+ raise ValueError(
59
+ f"Argument '{action.dest}' doesn't have a type specified."
60
+ )
61
+ else:
62
+ continue
63
+
64
+
65
+ def setup_parser() -> argparse.ArgumentParser:
66
+ parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter)
67
+ parser.add_argument(
68
+ "--model", "-m", type=str, default="hf", help="Name of model e.g. `hf`"
69
+ )
70
+ parser.add_argument(
71
+ "--tasks",
72
+ "-t",
73
+ default=None,
74
+ type=str,
75
+ metavar="task1,task2",
76
+ help="Comma-separated list of task names or task groupings to evaluate on.\nTo get full list of tasks, use one of the commands `lm-eval --tasks {{list_groups,list_subtasks,list_tags,list}}` to list out all available names for task groupings; only (sub)tasks; tags; or all of the above",
77
+ )
78
+ parser.add_argument(
79
+ "--model_args",
80
+ "-a",
81
+ default="",
82
+ type=str,
83
+ help="Comma separated string arguments for model, e.g. `pretrained=EleutherAI/pythia-160m,dtype=float32`",
84
+ )
85
+ parser.add_argument(
86
+ "--num_fewshot",
87
+ "-f",
88
+ type=int,
89
+ default=None,
90
+ metavar="N",
91
+ help="Number of examples in few-shot context",
92
+ )
93
+ parser.add_argument(
94
+ "--batch_size",
95
+ "-b",
96
+ type=str,
97
+ default=1,
98
+ metavar="auto|auto:N|N",
99
+ help="Acceptable values are 'auto', 'auto:N' or N, where N is an integer. Default 1.",
100
+ )
101
+ parser.add_argument(
102
+ "--max_batch_size",
103
+ type=int,
104
+ default=None,
105
+ metavar="N",
106
+ help="Maximal batch size to try with --batch_size auto.",
107
+ )
108
+ parser.add_argument(
109
+ "--device",
110
+ type=str,
111
+ default=None,
112
+ help="Device to use (e.g. cuda, cuda:0, cpu).",
113
+ )
114
+ parser.add_argument(
115
+ "--output_path",
116
+ "-o",
117
+ default=None,
118
+ type=str,
119
+ metavar="DIR|DIR/file.json",
120
+ help="The path to the output file where the result metrics will be saved. If the path is a directory and log_samples is true, the results will be saved in the directory. Else the parent directory will be used.",
121
+ )
122
+ parser.add_argument(
123
+ "--limit",
124
+ "-L",
125
+ type=float,
126
+ default=None,
127
+ metavar="N|0<N<1",
128
+ help="Limit the number of examples per task. "
129
+ "If <1, limit is a percentage of the total number of examples.",
130
+ )
131
+ parser.add_argument(
132
+ "--use_cache",
133
+ "-c",
134
+ type=str,
135
+ default=None,
136
+ metavar="DIR",
137
+ help="A path to a sqlite db file for caching model responses. `None` if not caching.",
138
+ )
139
+ parser.add_argument(
140
+ "--cache_requests",
141
+ type=str,
142
+ default=None,
143
+ choices=["true", "refresh", "delete"],
144
+ help="Speed up evaluation by caching the building of dataset requests. `None` if not caching.",
145
+ )
146
+ parser.add_argument(
147
+ "--check_integrity",
148
+ action="store_true",
149
+ help="Whether to run the relevant part of the test suite for the tasks.",
150
+ )
151
+ parser.add_argument(
152
+ "--write_out",
153
+ "-w",
154
+ action="store_true",
155
+ default=False,
156
+ help="Prints the prompt for the first few documents.",
157
+ )
158
+ parser.add_argument(
159
+ "--log_samples",
160
+ "-s",
161
+ action="store_true",
162
+ default=False,
163
+ help="If True, write out all model outputs and documents for per-sample measurement and post-hoc analysis. Use with --output_path.",
164
+ )
165
+ parser.add_argument(
166
+ "--system_instruction",
167
+ type=str,
168
+ default=None,
169
+ help="System instruction to be used in the prompt",
170
+ )
171
+ parser.add_argument(
172
+ "--apply_chat_template",
173
+ type=str,
174
+ nargs="?",
175
+ const=True,
176
+ default=False,
177
+ help=(
178
+ "If True, apply chat template to the prompt. "
179
+ "Providing `--apply_chat_template` without an argument will apply the default chat template to the prompt. "
180
+ "To apply a specific template from the available list of templates, provide the template name as an argument. "
181
+ "E.g. `--apply_chat_template template_name`"
182
+ ),
183
+ )
184
+ parser.add_argument(
185
+ "--fewshot_as_multiturn",
186
+ action="store_true",
187
+ default=False,
188
+ help="If True, uses the fewshot as a multi-turn conversation",
189
+ )
190
+ parser.add_argument(
191
+ "--show_config",
192
+ action="store_true",
193
+ default=False,
194
+ help="If True, shows the the full config of all tasks at the end of the evaluation.",
195
+ )
196
+ parser.add_argument(
197
+ "--include_path",
198
+ type=str,
199
+ default=None,
200
+ metavar="DIR",
201
+ help="Additional path to include if there are external tasks to include.",
202
+ )
203
+ parser.add_argument(
204
+ "--gen_kwargs",
205
+ type=str,
206
+ default=None,
207
+ help=(
208
+ "String arguments for model generation on greedy_until tasks,"
209
+ " e.g. `temperature=0,top_k=0,top_p=0`."
210
+ ),
211
+ )
212
+ parser.add_argument(
213
+ "--verbosity",
214
+ "-v",
215
+ type=str.upper,
216
+ default="INFO",
217
+ metavar="CRITICAL|ERROR|WARNING|INFO|DEBUG",
218
+ help="Controls the reported logging error level. Set to DEBUG when testing + adding new task configurations for comprehensive log output.",
219
+ )
220
+ parser.add_argument(
221
+ "--wandb_args",
222
+ type=str,
223
+ default="",
224
+ help="Comma separated string arguments passed to wandb.init, e.g. `project=lm-eval,job_type=eval",
225
+ )
226
+ parser.add_argument(
227
+ "--hf_hub_log_args",
228
+ type=str,
229
+ default="",
230
+ help="Comma separated string arguments passed to Hugging Face Hub's log function, e.g. `hub_results_org=EleutherAI,hub_repo_name=lm-eval-results`",
231
+ )
232
+ parser.add_argument(
233
+ "--predict_only",
234
+ "-x",
235
+ action="store_true",
236
+ default=False,
237
+ help="Use with --log_samples. Only model outputs will be saved and metrics will not be evaluated.",
238
+ )
239
+ default_seed_string = "0,1234,1234,1234"
240
+ parser.add_argument(
241
+ "--seed",
242
+ type=partial(_int_or_none_list_arg_type, 3, 4, default_seed_string),
243
+ default=default_seed_string, # for backward compatibility
244
+ help=(
245
+ "Set seed for python's random, numpy, torch, and fewshot sampling.\n"
246
+ "Accepts a comma-separated list of 4 values for python's random, numpy, torch, and fewshot sampling seeds, "
247
+ "respectively, or a single integer to set the same seed for all four.\n"
248
+ f"The values are either an integer or 'None' to not set the seed. Default is `{default_seed_string}` "
249
+ "(for backward compatibility).\n"
250
+ "E.g. `--seed 0,None,8,52` sets `random.seed(0)`, `torch.manual_seed(8)`, and fewshot sampling seed to 52. "
251
+ "Here numpy's seed is not set since the second value is `None`.\n"
252
+ "E.g, `--seed 42` sets all four seeds to 42."
253
+ ),
254
+ )
255
+ parser.add_argument(
256
+ "--trust_remote_code",
257
+ action="store_true",
258
+ help="Sets trust_remote_code to True to execute code to create HF Datasets from the Hub",
259
+ )
260
+ return parser
261
+
262
+
263
+ def parse_eval_args(parser: argparse.ArgumentParser) -> argparse.Namespace:
264
+ check_argument_types(parser)
265
+ return parser.parse_args()
266
+
267
+
268
+ def cli_evaluate(args: Union[argparse.Namespace, None] = None) -> None:
269
+ if not args:
270
+ # we allow for args to be passed externally, else we parse them ourselves
271
+ parser = setup_parser()
272
+ args = parse_eval_args(parser)
273
+
274
+ if args.wandb_args:
275
+ wandb_logger = WandbLogger(**simple_parse_args_string(args.wandb_args))
276
+
277
+ eval_logger = utils.eval_logger
278
+ eval_logger.setLevel(getattr(logging, f"{args.verbosity}"))
279
+ eval_logger.info(f"Verbosity set to {args.verbosity}")
280
+ os.environ["TOKENIZERS_PARALLELISM"] = "false"
281
+
282
+ # update the evaluation tracker args with the output path and the HF token
283
+ if args.output_path:
284
+ args.hf_hub_log_args += f",output_path={args.output_path}"
285
+ if os.environ.get("HF_TOKEN", None):
286
+ args.hf_hub_log_args += f",token={os.environ.get('HF_TOKEN')}"
287
+ evaluation_tracker_args = simple_parse_args_string(args.hf_hub_log_args)
288
+ evaluation_tracker = EvaluationTracker(**evaluation_tracker_args)
289
+
290
+ if args.predict_only:
291
+ args.log_samples = True
292
+ if (args.log_samples or args.predict_only) and not args.output_path:
293
+ raise ValueError(
294
+ "Specify --output_path if providing --log_samples or --predict_only"
295
+ )
296
+
297
+ if args.fewshot_as_multiturn and args.apply_chat_template is False:
298
+ raise ValueError(
299
+ "When `fewshot_as_multiturn` is selected, `apply_chat_template` must be set (either to `True` or to the chosen template name)."
300
+ )
301
+
302
+ if args.include_path is not None:
303
+ eval_logger.info(f"Including path: {args.include_path}")
304
+ task_manager = TaskManager(args.verbosity, include_path=args.include_path)
305
+
306
+ if "push_samples_to_hub" in evaluation_tracker_args and not args.log_samples:
307
+ eval_logger.warning(
308
+ "Pushing samples to the Hub requires --log_samples to be set. Samples will not be pushed to the Hub."
309
+ )
310
+
311
+ if args.limit:
312
+ eval_logger.warning(
313
+ " --limit SHOULD ONLY BE USED FOR TESTING."
314
+ "REAL METRICS SHOULD NOT BE COMPUTED USING LIMIT."
315
+ )
316
+
317
+ if args.tasks is None:
318
+ eval_logger.error("Need to specify task to evaluate.")
319
+ sys.exit()
320
+ elif args.tasks == "list":
321
+ print(task_manager.list_all_tasks())
322
+ sys.exit()
323
+ elif args.tasks == "list_groups":
324
+ print(task_manager.list_all_tasks(list_subtasks=False, list_tags=False))
325
+ sys.exit()
326
+ elif args.tasks == "list_tags":
327
+ print(task_manager.list_all_tasks(list_groups=False, list_subtasks=False))
328
+ sys.exit()
329
+ elif args.tasks == "list_subtasks":
330
+ print(task_manager.list_all_tasks(list_groups=False, list_tags=False))
331
+ sys.exit()
332
+ else:
333
+ if os.path.isdir(args.tasks):
334
+ import glob
335
+
336
+ task_names = []
337
+ yaml_path = os.path.join(args.tasks, "*.yaml")
338
+ for yaml_file in glob.glob(yaml_path):
339
+ config = utils.load_yaml_config(yaml_file)
340
+ task_names.append(config)
341
+ else:
342
+ task_list = args.tasks.split(",")
343
+ task_names = task_manager.match_tasks(task_list)
344
+ for task in [task for task in task_list if task not in task_names]:
345
+ if os.path.isfile(task):
346
+ config = utils.load_yaml_config(task)
347
+ task_names.append(config)
348
+ task_missing = [
349
+ task for task in task_list if task not in task_names and "*" not in task
350
+ ] # we don't want errors if a wildcard ("*") task name was used
351
+
352
+ if task_missing:
353
+ missing = ", ".join(task_missing)
354
+ eval_logger.error(
355
+ f"Tasks were not found: {missing}\n"
356
+ f"{utils.SPACING}Try `lm-eval --tasks list` for list of available tasks",
357
+ )
358
+ raise ValueError(
359
+ f"Tasks not found: {missing}. Try `lm-eval --tasks {{list_groups,list_subtasks,list_tags,list}}` to list out all available names for task groupings; only (sub)tasks; tags; or all of the above, or pass '--verbosity DEBUG' to troubleshoot task registration issues."
360
+ )
361
+
362
+ # Respect user's value passed in via CLI, otherwise default to True and add to comma-separated model args
363
+ if args.trust_remote_code:
364
+ eval_logger.info(
365
+ "Passed `--trust_remote_code`, setting environment variable `HF_DATASETS_TRUST_REMOTE_CODE=true`"
366
+ )
367
+ # HACK: import datasets and override its HF_DATASETS_TRUST_REMOTE_CODE value internally,
368
+ # because it's already been determined based on the prior env var before launching our
369
+ # script--`datasets` gets imported by lm_eval internally before these lines can update the env.
370
+ import datasets
371
+
372
+ datasets.config.HF_DATASETS_TRUST_REMOTE_CODE = True
373
+
374
+ args.model_args = args.model_args + ",trust_remote_code=True"
375
+
376
+ eval_logger.info(f"Selected Tasks: {task_names}")
377
+
378
+ request_caching_args = request_caching_arg_to_dict(
379
+ cache_requests=args.cache_requests
380
+ )
381
+
382
+ results = evaluator.simple_evaluate(
383
+ model=args.model,
384
+ model_args=args.model_args,
385
+ tasks=task_names,
386
+ num_fewshot=args.num_fewshot,
387
+ batch_size=args.batch_size,
388
+ max_batch_size=args.max_batch_size,
389
+ device=args.device,
390
+ use_cache=args.use_cache,
391
+ limit=args.limit,
392
+ check_integrity=args.check_integrity,
393
+ write_out=args.write_out,
394
+ log_samples=args.log_samples,
395
+ evaluation_tracker=evaluation_tracker,
396
+ system_instruction=args.system_instruction,
397
+ apply_chat_template=args.apply_chat_template,
398
+ fewshot_as_multiturn=args.fewshot_as_multiturn,
399
+ gen_kwargs=args.gen_kwargs,
400
+ task_manager=task_manager,
401
+ verbosity=args.verbosity,
402
+ predict_only=args.predict_only,
403
+ random_seed=args.seed[0],
404
+ numpy_random_seed=args.seed[1],
405
+ torch_random_seed=args.seed[2],
406
+ fewshot_random_seed=args.seed[3],
407
+ **request_caching_args,
408
+ )
409
+
410
+ if results is not None:
411
+ if args.log_samples:
412
+ samples = results.pop("samples")
413
+ dumped = json.dumps(
414
+ results, indent=2, default=handle_non_serializable, ensure_ascii=False
415
+ )
416
+ if args.show_config:
417
+ print(dumped)
418
+
419
+ batch_sizes = ",".join(map(str, results["config"]["batch_sizes"]))
420
+
421
+ # Add W&B logging
422
+ if args.wandb_args:
423
+ try:
424
+ wandb_logger.post_init(results)
425
+ wandb_logger.log_eval_result()
426
+ if args.log_samples:
427
+ wandb_logger.log_eval_samples(samples)
428
+ except Exception as e:
429
+ eval_logger.info(f"Logging to Weights and Biases failed due to {e}")
430
+
431
+ evaluation_tracker.save_results_aggregated(
432
+ results=results, samples=samples if args.log_samples else None
433
+ )
434
+
435
+ if args.log_samples:
436
+ for task_name, config in results["configs"].items():
437
+ evaluation_tracker.save_results_samples(
438
+ task_name=task_name, samples=samples[task_name]
439
+ )
440
+
441
+ if (
442
+ evaluation_tracker.push_results_to_hub
443
+ or evaluation_tracker.push_samples_to_hub
444
+ ):
445
+ evaluation_tracker.recreate_metadata_card()
446
+
447
+ print(
448
+ f"{args.model} ({args.model_args}), gen_kwargs: ({args.gen_kwargs}), limit: {args.limit}, num_fewshot: {args.num_fewshot}, "
449
+ f"batch_size: {args.batch_size}{f' ({batch_sizes})' if batch_sizes else ''}"
450
+ )
451
+ print(make_table(results))
452
+ if "groups" in results:
453
+ print(make_table(results, "groups"))
454
+
455
+ if args.wandb_args:
456
+ # Tear down wandb run once all the logging is done.
457
+ wandb_logger.run.finish()
458
+
459
+
460
+ if __name__ == "__main__":
461
+ cli_evaluate()
testbed/EleutherAI__lm-evaluation-harness/lm_eval/evaluator.py ADDED
@@ -0,0 +1,657 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import itertools
2
+ import json
3
+ import logging
4
+ import random
5
+ import time
6
+ from collections import defaultdict
7
+ from typing import TYPE_CHECKING, List, Optional, Union
8
+
9
+ import numpy as np
10
+ import torch
11
+
12
+ import lm_eval.api.metrics
13
+ import lm_eval.api.registry
14
+ import lm_eval.api.task
15
+ import lm_eval.models
16
+ from lm_eval.caching.cache import delete_cache
17
+ from lm_eval.evaluator_utils import (
18
+ consolidate_group_results,
19
+ consolidate_results,
20
+ get_sample_size,
21
+ get_subtask_list,
22
+ get_task_list,
23
+ prepare_print_tasks,
24
+ print_writeout,
25
+ run_task_tests,
26
+ )
27
+ from lm_eval.loggers import EvaluationTracker
28
+ from lm_eval.loggers.utils import add_env_info, add_tokenizer_info, get_git_commit_hash
29
+ from lm_eval.tasks import (
30
+ TaskManager,
31
+ get_task_dict,
32
+ )
33
+ from lm_eval.utils import (
34
+ eval_logger,
35
+ handle_non_serializable,
36
+ hash_string,
37
+ positional_deprecated,
38
+ simple_parse_args_string,
39
+ )
40
+
41
+
42
+ if TYPE_CHECKING:
43
+ from lm_eval.api.model import LM
44
+ from lm_eval.api.task import Task
45
+
46
+
47
+ @positional_deprecated
48
+ def simple_evaluate(
49
+ model,
50
+ model_args: Optional[Union[str, dict]] = None,
51
+ tasks: Optional[List[Union[str, dict, object]]] = None,
52
+ num_fewshot: Optional[int] = None,
53
+ batch_size: Optional[Union[int, str]] = None,
54
+ max_batch_size: Optional[int] = None,
55
+ device: Optional[str] = None,
56
+ use_cache: Optional[str] = None,
57
+ cache_requests: bool = False,
58
+ rewrite_requests_cache: bool = False,
59
+ delete_requests_cache: bool = False,
60
+ limit: Optional[Union[int, float]] = None,
61
+ bootstrap_iters: int = 100000,
62
+ check_integrity: bool = False,
63
+ write_out: bool = False,
64
+ log_samples: bool = True,
65
+ evaluation_tracker: Optional[EvaluationTracker] = None,
66
+ system_instruction: Optional[str] = None,
67
+ apply_chat_template: Union[bool, str] = False,
68
+ fewshot_as_multiturn: bool = False,
69
+ gen_kwargs: Optional[str] = None,
70
+ task_manager: Optional[TaskManager] = None,
71
+ verbosity: str = "INFO",
72
+ predict_only: bool = False,
73
+ random_seed: int = 0,
74
+ numpy_random_seed: int = 1234,
75
+ torch_random_seed: int = 1234,
76
+ fewshot_random_seed: int = 1234,
77
+ ):
78
+ """Instantiate and evaluate a model on a list of tasks.
79
+
80
+ :param model: Union[str, LM]
81
+ Name of model or LM object, see lm_eval.models.get_model
82
+ :param model_args: Optional[str, dict]
83
+ String or dict arguments for each model class, see LM.create_from_arg_string and LM.create_from_arg_object.
84
+ Ignored if `model` argument is a LM object.
85
+ :param tasks: list[Union[str, dict, Task]]
86
+ List of task names or Task objects. Task objects will be taken to have name task.EVAL_HARNESS_NAME if defined and type(task).__name__ otherwise.
87
+ :param num_fewshot: int
88
+ Number of examples in few-shot context
89
+ :param batch_size: int or str, optional
90
+ Batch size for model
91
+ :param max_batch_size: int, optional
92
+ Maximal batch size to try with automatic batch size detection
93
+ :param device: str, optional
94
+ PyTorch device (e.g. "cpu" or "cuda:0") for running models
95
+ :param use_cache: str, optional
96
+ A path to a sqlite db file for caching model responses. `None` if not caching.
97
+ :param cache_requests: bool, optional
98
+ Speed up evaluation by caching the building of dataset requests. `None` if not caching.
99
+ :param rewrite_requests_cache: bool, optional
100
+ Rewrites all of the request cache if set to `True`. `None` if not desired.
101
+ :param delete_requests_cache: bool, optional
102
+ Deletes all of the request cache if set to `True`. `None` if not desired.
103
+ :param limit: int or float, optional
104
+ Limit the number of examples per task (only use this for testing), If <1, limit is a percentage of the total number of examples.
105
+ :param bootstrap_iters:
106
+ Number of iterations for bootstrap statistics, used when calculating stderrs. set to 0 for no stderr calculations to be performed.
107
+ :param check_integrity: bool
108
+ Whether to run the relevant part of the test suite for the tasks
109
+ :param write_out: bool
110
+ If True, write out an example document and model input for checking task integrity
111
+ :param log_samples: bool
112
+ If True, write out all model outputs and documents for per-sample measurement and post-hoc analysis
113
+ :param system_instruction: str
114
+ System instruction to be applied to the prompt
115
+ :param apply_chat_template: Union[bool, str]
116
+ Specifies whether to apply a chat template to the prompt.
117
+ - If set to True, the default chat template is applied.
118
+ - If set to a string, applies the specified chat template by name.
119
+ Defaults to False (no chat template applied).
120
+ :param fewshot_as_multiturn: bool
121
+ Whether to provide the fewshot examples as a multiturn conversation or a single user turn.
122
+ :param gen_kwargs: str
123
+ String arguments for model generation
124
+ Ignored for all tasks with loglikelihood output_type
125
+ :param predict_only: bool
126
+ If true only model outputs will be generated and returned. Metrics will not be evaluated
127
+ :param random_seed: int
128
+ Random seed for python's random module. If set to None, the seed will not be set.
129
+ :param numpy_random_seed: int
130
+ Random seed for numpy. If set to None, the seed will not be set.
131
+ :param torch_random_seed: int
132
+ Random seed for torch. If set to None, the seed will not be set.
133
+ :param fewshot_random_seed: int
134
+ Random seed for fewshot sampler random generator. If set to None, the seed of generator will be set to None.
135
+
136
+ :return
137
+ Dictionary of results
138
+ """
139
+ eval_logger.setLevel(getattr(logging, f"{verbosity}"))
140
+ start_date = time.time()
141
+
142
+ if delete_requests_cache:
143
+ eval_logger.info("Deleting requests cache...")
144
+ delete_cache()
145
+
146
+ seed_message = []
147
+ if random_seed is not None:
148
+ # See https://github.com/EleutherAI/lm-evaluation-harness/pull/1412
149
+ seed_message.append(f"Setting random seed to {random_seed}")
150
+ random.seed(random_seed)
151
+
152
+ if numpy_random_seed is not None:
153
+ seed_message.append(f"Setting numpy seed to {numpy_random_seed}")
154
+ np.random.seed(numpy_random_seed)
155
+
156
+ if torch_random_seed is not None:
157
+ seed_message.append(f"Setting torch manual seed to {torch_random_seed}")
158
+ torch.manual_seed(torch_random_seed)
159
+
160
+ if seed_message:
161
+ eval_logger.info(" | ".join(seed_message))
162
+
163
+ if tasks is None:
164
+ tasks = []
165
+ if len(tasks) == 0:
166
+ raise ValueError(
167
+ "No tasks specified, or no tasks found. Please verify the task names."
168
+ )
169
+
170
+ if gen_kwargs is not None:
171
+ gen_kwargs = simple_parse_args_string(gen_kwargs)
172
+ eval_logger.warning(
173
+ "generation_kwargs specified through cli, these settings will update set parameters in yaml tasks. "
174
+ "Ensure 'do_sample=True' for non-greedy decoding!"
175
+ )
176
+ if gen_kwargs == "":
177
+ gen_kwargs = None
178
+
179
+ if isinstance(model, str):
180
+ if model_args is None:
181
+ eval_logger.warning("model_args not specified. Using defaults.")
182
+ model_args = ""
183
+
184
+ if isinstance(model_args, dict):
185
+ eval_logger.info(
186
+ f"Initializing {model} model, with arguments: {model_args}"
187
+ )
188
+ lm = lm_eval.api.registry.get_model(model).create_from_arg_obj(
189
+ model_args,
190
+ {
191
+ "batch_size": batch_size,
192
+ "max_batch_size": max_batch_size,
193
+ "device": device,
194
+ },
195
+ )
196
+
197
+ else:
198
+ eval_logger.info(
199
+ f"Initializing {model} model, with arguments: {simple_parse_args_string(model_args)}"
200
+ )
201
+ lm = lm_eval.api.registry.get_model(model).create_from_arg_string(
202
+ model_args,
203
+ {
204
+ "batch_size": batch_size,
205
+ "max_batch_size": max_batch_size,
206
+ "device": device,
207
+ },
208
+ )
209
+ else:
210
+ if not isinstance(model, lm_eval.api.model.LM):
211
+ raise TypeError(
212
+ f"The value of `model` passed to simple_evaluate() was of type {type(model)}, but is required to be a subclass of lm_eval.api.model.LM . This may be because you are passing an initialized Hugging Face PreTrainedModel without having wrapped it in `lm_eval.models.huggingface.HFLM(pretrained=my_model)` first."
213
+ )
214
+ eval_logger.info("Using pre-initialized model")
215
+ lm = model
216
+
217
+ if use_cache is not None:
218
+ eval_logger.info(f"Using cache at {use_cache + '_rank' + str(lm.rank) + '.db'}")
219
+ lm = lm_eval.api.model.CachingLM(
220
+ lm,
221
+ use_cache
222
+ # each rank receives a different cache db.
223
+ # necessary to avoid multiple writes to cache at once
224
+ + "_rank"
225
+ + str(lm.rank)
226
+ + ".db",
227
+ )
228
+
229
+ if task_manager is None:
230
+ task_manager = TaskManager(verbosity)
231
+
232
+ task_dict = get_task_dict(tasks, task_manager)
233
+
234
+ # helper function to recursively apply config overrides to leaf subtasks, skipping their constituent groups.
235
+ # (setting of num_fewshot ; bypassing metric calculation ; setting fewshot seed)
236
+ def _adjust_config(task_dict):
237
+ adjusted_task_dict = {}
238
+ for task_name, task_obj in task_dict.items():
239
+ if isinstance(task_obj, dict):
240
+ adjusted_task_dict = {
241
+ **adjusted_task_dict,
242
+ **{task_name: _adjust_config(task_obj)},
243
+ }
244
+
245
+ else:
246
+ if task_obj.get_config("output_type") == "generate_until":
247
+ if gen_kwargs is not None:
248
+ task_obj.set_config(
249
+ key="generation_kwargs", value=gen_kwargs, update=True
250
+ )
251
+
252
+ if predict_only:
253
+ eval_logger.info(
254
+ f"Processing {task_name} in output-only mode. Metrics will not be calculated!"
255
+ )
256
+ # we have to change the class properties post-hoc. This is pretty hacky.
257
+ task_obj.override_metric(metric_name="bypass")
258
+
259
+ # override tasks' fewshot values to the provided num_fewshot arg value
260
+ # except if tasks have it set to 0 manually in their configs--then we should never overwrite that
261
+ if num_fewshot is not None:
262
+ if (default_num_fewshot := task_obj.get_config("num_fewshot")) == 0:
263
+ eval_logger.info(
264
+ f"num_fewshot has been set to 0 for {task_name} in its config. Manual configuration will be ignored."
265
+ )
266
+ else:
267
+ eval_logger.warning(
268
+ f"Overwriting default num_fewshot of {task_name} from {default_num_fewshot} to {num_fewshot}"
269
+ )
270
+ task_obj.set_config(key="num_fewshot", value=num_fewshot)
271
+ else:
272
+ # if num_fewshot not provided, and the task does not define a default one, default to 0
273
+ if (
274
+ default_num_fewshot := task_obj.get_config("num_fewshot")
275
+ ) is None:
276
+ task_obj.set_config(key="num_fewshot", value=0)
277
+ # fewshot_random_seed set for tasks, even with a default num_fewshot (e.g. in the YAML file)
278
+ task_obj.set_fewshot_seed(seed=fewshot_random_seed)
279
+ eval_logger.info(
280
+ f"Setting fewshot random generator seed to {fewshot_random_seed}"
281
+ )
282
+
283
+ adjusted_task_dict[task_name] = task_obj
284
+
285
+ return adjusted_task_dict
286
+
287
+ task_dict = _adjust_config(task_dict)
288
+
289
+ if check_integrity:
290
+ run_task_tests(task_list=tasks)
291
+
292
+ if evaluation_tracker is not None:
293
+ evaluation_tracker.general_config_tracker.log_experiment_args(
294
+ model_source=model,
295
+ model_args=model_args,
296
+ system_instruction=system_instruction,
297
+ chat_template=lm.chat_template(apply_chat_template),
298
+ fewshot_as_multiturn=fewshot_as_multiturn,
299
+ )
300
+
301
+ results = evaluate(
302
+ lm=lm,
303
+ task_dict=task_dict,
304
+ limit=limit,
305
+ cache_requests=cache_requests,
306
+ rewrite_requests_cache=rewrite_requests_cache,
307
+ bootstrap_iters=bootstrap_iters,
308
+ write_out=write_out,
309
+ log_samples=True if predict_only else log_samples,
310
+ system_instruction=system_instruction,
311
+ apply_chat_template=apply_chat_template,
312
+ fewshot_as_multiturn=fewshot_as_multiturn,
313
+ verbosity=verbosity,
314
+ )
315
+
316
+ if lm.rank == 0:
317
+ if isinstance(model, str):
318
+ model_name = model
319
+ elif hasattr(model, "config") and hasattr(model.config, "_name_or_path"):
320
+ model_name = model.config._name_or_path
321
+ else:
322
+ model_name = type(model).__name__
323
+
324
+ # add info about the model and few shot config
325
+ results["config"] = {
326
+ "model": model_name,
327
+ "model_args": model_args,
328
+ }
329
+ # add more detailed model info if available
330
+ if isinstance(lm, lm_eval.models.huggingface.HFLM):
331
+ results["config"].update(lm.get_model_info())
332
+ # add info about execution
333
+ results["config"].update(
334
+ {
335
+ "batch_size": batch_size,
336
+ "batch_sizes": (
337
+ list(lm.batch_sizes.values()) if hasattr(lm, "batch_sizes") else []
338
+ ),
339
+ "device": device,
340
+ "use_cache": use_cache,
341
+ "limit": limit,
342
+ "bootstrap_iters": bootstrap_iters,
343
+ "gen_kwargs": gen_kwargs,
344
+ "random_seed": random_seed,
345
+ "numpy_seed": numpy_random_seed,
346
+ "torch_seed": torch_random_seed,
347
+ "fewshot_seed": fewshot_random_seed,
348
+ }
349
+ )
350
+ results["git_hash"] = get_git_commit_hash()
351
+ results["date"] = start_date
352
+ add_env_info(results) # additional environment info to results
353
+ add_tokenizer_info(results, lm) # additional info about tokenizer
354
+ return results
355
+ else:
356
+ return None
357
+
358
+
359
+ @positional_deprecated
360
+ def evaluate(
361
+ lm: "LM",
362
+ task_dict,
363
+ limit: Optional[int] = None,
364
+ cache_requests: bool = False,
365
+ rewrite_requests_cache: bool = False,
366
+ bootstrap_iters: Optional[int] = 100000,
367
+ write_out: bool = False,
368
+ log_samples: bool = True,
369
+ system_instruction: Optional[str] = None,
370
+ apply_chat_template: Union[bool, str] = False,
371
+ fewshot_as_multiturn: bool = False,
372
+ verbosity: str = "INFO",
373
+ ):
374
+ """Instantiate and evaluate a model on a list of tasks.
375
+
376
+ :param lm: obj
377
+ Language Model
378
+ :param task_dict: dict[str, Task]
379
+ Dictionary of tasks. Tasks will be taken to have name type(task).config.task .
380
+ :param limit: int, optional
381
+ Limit the number of examples per task (only use this for testing)
382
+ :param bootstrap_iters:
383
+ Number of iterations for bootstrap statistics, used when calculating stderr. Set to 0 for skipping all stderr calculations.
384
+ :param write_out: bool
385
+ If True, write out an example document and model input for checking task integrity
386
+ :param log_samples: bool
387
+ If True, write out all model outputs and documents for per-sample measurement and post-hoc analysis
388
+ :param system_instruction: str
389
+ System instruction to be applied to the prompt
390
+ :param apply_chat_template: Union[bool, str]
391
+ Specifies whether to apply a chat template to the prompt.
392
+ - If set to True, the default chat template is applied.
393
+ - If set to a string, applies the specified chat template by name.
394
+ Defaults to False (no chat template applied).
395
+ :param fewshot_as_multiturn: bool
396
+ Whether to provide the fewshot examples as a multiturn conversation or a single user turn.
397
+ :return
398
+ Dictionary of results
399
+ """
400
+
401
+ eval_logger.setLevel(getattr(logging, f"{verbosity}"))
402
+
403
+ # tracks all Instances/requests a model must generate output on.
404
+ requests = defaultdict(list)
405
+ # stores the amount to pad out reqs per req. type so that
406
+ # number of fwd passes per distributed rank is equal
407
+ padding_requests = defaultdict(int)
408
+
409
+ # get lists of group hierarchy and each type of request
410
+ eval_tasks = get_task_list(task_dict)
411
+ if not log_samples:
412
+ if not all(
413
+ "bypass" not in getattr(task_output.task, "_metric_fn_list", {}).keys()
414
+ for task_output in eval_tasks
415
+ ):
416
+ raise ValueError("log_samples must be True for 'bypass' metric-only tasks")
417
+ for task_output in eval_tasks:
418
+ task: Task = task_output.task
419
+ limit = get_sample_size(task, limit)
420
+ task.build_all_requests(
421
+ limit=limit,
422
+ rank=lm.rank,
423
+ world_size=lm.world_size,
424
+ cache_requests=cache_requests,
425
+ rewrite_requests_cache=rewrite_requests_cache,
426
+ system_instruction=system_instruction,
427
+ apply_chat_template=bool(apply_chat_template),
428
+ fewshot_as_multiturn=fewshot_as_multiturn,
429
+ chat_template=getattr(lm, "apply_chat_template")
430
+ if apply_chat_template
431
+ else None,
432
+ tokenizer_name=getattr(lm, "tokenizer_name", "")
433
+ if apply_chat_template
434
+ else "",
435
+ )
436
+ eval_logger.debug(
437
+ f"Task: {task_output.task_name}; number of requests on this rank: {len(task.instances)}"
438
+ )
439
+ if write_out:
440
+ print_writeout(task)
441
+ # aggregate Instances by LM method requested to get output.
442
+ for instance in task.instances:
443
+ reqtype = instance.request_type
444
+ requests[reqtype].append(instance)
445
+
446
+ if lm.world_size > 1:
447
+ instances_rnk = torch.tensor(len(task._instances), device=lm.device)
448
+ gathered_item = (
449
+ lm.accelerator.gather(instances_rnk).cpu().detach().numpy().tolist()
450
+ )
451
+ # "multiple_choice" task types dispatch (several) "loglikelihood" request types
452
+ reqtype = (
453
+ "loglikelihood"
454
+ if task.OUTPUT_TYPE == "multiple_choice"
455
+ else task.OUTPUT_TYPE
456
+ )
457
+ # compute number of pseudo-batches to pad with (FSDP/DDP require even batches among ranks)
458
+ numpad = max(gathered_item) - gathered_item[lm.rank]
459
+ # todo: may not account for padding in cases like SquadV2 which has multiple req types
460
+ padding_requests[reqtype] += numpad
461
+
462
+ ### Run LM on inputs, get all outputs ###
463
+ # execute each type of request
464
+ for reqtype, reqs in requests.items():
465
+ eval_logger.info(f"Running {reqtype} requests")
466
+ # create `K` copies of each request `req` based off `K = req.repeats`
467
+ cloned_reqs = []
468
+ for req in reqs:
469
+ cloned_reqs.extend([req] * req.repeats)
470
+
471
+ if (lm.world_size > 1) and (padding_requests[reqtype] > 0):
472
+ for _ in range(padding_requests[reqtype]):
473
+ cloned_reqs.extend([req] * req.repeats)
474
+
475
+ # run requests through model
476
+ resps = getattr(lm, reqtype)(cloned_reqs)
477
+
478
+ # put responses from model into a list of length K for each request.
479
+ for x, req in zip(resps, cloned_reqs):
480
+ req.resps.append(x)
481
+
482
+ if lm.world_size > 1:
483
+ lm.accelerator.wait_for_everyone()
484
+
485
+ RANK = lm.rank
486
+ WORLD_SIZE = lm.world_size
487
+ ### Postprocess outputs ###
488
+ # TODO: del model here, maybe (idea: allow user to specify device of e.g. reward model separately)
489
+ for task_output in eval_tasks:
490
+ task = task_output.task
491
+ task.apply_filters()
492
+
493
+ ### Collect values of metrics on all datapoints ###
494
+ # # unpack results and sort back in order and return control to Task
495
+ # TODO: make it possible to use a different metric per filter
496
+ # Pre-process task.instances to group by doc_id
497
+ instances_by_doc_id = defaultdict(list)
498
+ for instance in task.instances:
499
+ instances_by_doc_id[instance.doc_id].append(instance)
500
+ # Sort instances within each group
501
+ for instances in instances_by_doc_id.values():
502
+ instances.sort(key=lambda x: x.idx)
503
+ # iterate over different filters used
504
+ for filter_key in task.instances[0].filtered_resps.keys():
505
+ doc_iterator = task.doc_iterator(
506
+ rank=RANK, limit=limit, world_size=WORLD_SIZE
507
+ )
508
+ for doc_id, doc in doc_iterator:
509
+ requests = instances_by_doc_id[doc_id]
510
+ metrics = task.process_results(
511
+ doc, [req.filtered_resps[filter_key] for req in requests]
512
+ )
513
+ if log_samples:
514
+ target = task.doc_to_target(doc)
515
+ example = {
516
+ "doc_id": doc_id,
517
+ "doc": doc,
518
+ "target": target,
519
+ "arguments": [req.args for req in requests],
520
+ "resps": [req.resps for req in requests],
521
+ "filtered_resps": [
522
+ req.filtered_resps[filter_key] for req in requests
523
+ ],
524
+ "doc_hash": hash_string(
525
+ json.dumps(
526
+ requests[0].doc,
527
+ indent=2,
528
+ default=handle_non_serializable,
529
+ ensure_ascii=False,
530
+ )
531
+ ),
532
+ "prompt_hash": hash_string(requests[0].arguments[0]),
533
+ "target_hash": hash_string(str(target)),
534
+ }
535
+ example.update(metrics)
536
+ task_output.logged_samples.append(example)
537
+ for metric, value in metrics.items():
538
+ task_output.sample_metrics[(metric, filter_key)].append(value)
539
+
540
+ if WORLD_SIZE > 1:
541
+ # if multigpu, then gather data across all ranks to rank 0
542
+ # first gather logged samples across all ranks
543
+ for task_output in eval_tasks:
544
+ if log_samples:
545
+ # for task_name, task_samples in list(samples.items()):
546
+ full_samples = [None] * WORLD_SIZE if RANK == 0 else None
547
+ torch.distributed.gather_object(
548
+ obj=task_output.logged_samples,
549
+ object_gather_list=full_samples,
550
+ dst=0,
551
+ )
552
+
553
+ if RANK == 0:
554
+ task_output.logged_samples = list(
555
+ itertools.chain.from_iterable(full_samples)
556
+ )
557
+
558
+ # then collect metrics across all ranks
559
+ for metrics in task_output.sample_metrics:
560
+ metric_list = [None] * WORLD_SIZE if RANK == 0 else None
561
+ torch.distributed.gather_object(
562
+ obj=task_output.sample_metrics[metrics],
563
+ object_gather_list=metric_list,
564
+ dst=0,
565
+ )
566
+ if RANK == 0:
567
+ task_output.sample_metrics[metrics] = list(
568
+ itertools.chain.from_iterable(metric_list)
569
+ )
570
+
571
+ if RANK == 0:
572
+ ### Aggregate results over all datapoints ###
573
+ # aggregate results ; run bootstrap CIs
574
+ for task_output in eval_tasks:
575
+ task_output.calculate_aggregate_metric(bootstrap_iters=bootstrap_iters)
576
+ (
577
+ results,
578
+ samples,
579
+ configs,
580
+ versions,
581
+ num_fewshot,
582
+ higher_is_better,
583
+ ) = consolidate_results(eval_tasks)
584
+
585
+ ### Calculate group metrics ###
586
+ if bool(results):
587
+ results, versions, show_group_table, *_ = consolidate_group_results(
588
+ results, versions, task_dict
589
+ )
590
+
591
+ results_agg, group_agg = prepare_print_tasks(task_dict, results)
592
+ subtask_list = get_subtask_list(task_dict)
593
+
594
+ # collect all higher_is_better values for metrics
595
+ # in the group's subtasks.
596
+ # TODO: clean this up ; unify with the below metric_list loop?
597
+ _higher_is_better = {}
598
+ for group, task_list in subtask_list.items():
599
+ if (
600
+ len(task_list) != 0
601
+ ): # subtask list will list "task_name": [] for solo tasks
602
+ for task in task_list:
603
+ for m, h in higher_is_better[task].items():
604
+ if m not in _higher_is_better.keys():
605
+ _higher_is_better[m] = h
606
+
607
+ if (
608
+ m in _higher_is_better
609
+ and _higher_is_better[m] is not None
610
+ and _higher_is_better[m] != h
611
+ ):
612
+ eval_logger.warning(
613
+ f"Higher_is_better values for metric {m} in group {group} are not consistent. Defaulting to None."
614
+ )
615
+ _higher_is_better[m] = None
616
+ higher_is_better[group] = _higher_is_better
617
+
618
+ results_dict = {
619
+ "results": dict(results_agg.items()),
620
+ **(
621
+ {"groups": dict(group_agg.items())}
622
+ if (bool(group_agg) & show_group_table)
623
+ else {}
624
+ ),
625
+ "group_subtasks": dict(reversed(subtask_list.items())),
626
+ "configs": dict(sorted(configs.items())),
627
+ "versions": dict(sorted(versions.items())),
628
+ "n-shot": dict(sorted(num_fewshot.items())),
629
+ "higher_is_better": dict(sorted(higher_is_better.items())),
630
+ "n-samples": {
631
+ task_output.task_name: {
632
+ "original": len(task_output.task.eval_docs),
633
+ "effective": min(
634
+ limit if limit else len(task_output.task.eval_docs),
635
+ len(task_output.task.eval_docs),
636
+ ),
637
+ }
638
+ for task_output in eval_tasks
639
+ },
640
+ }
641
+ if log_samples:
642
+ results_dict["samples"] = dict(samples)
643
+
644
+ return results_dict
645
+
646
+ else:
647
+ return None
648
+
649
+
650
+ def request_caching_arg_to_dict(cache_requests: str) -> dict:
651
+ request_caching_args = {
652
+ "cache_requests": cache_requests in {"true", "refresh"},
653
+ "rewrite_requests_cache": cache_requests == "refresh",
654
+ "delete_requests_cache": cache_requests == "delete",
655
+ }
656
+
657
+ return request_caching_args
testbed/EleutherAI__lm-evaluation-harness/lm_eval/evaluator_utils.py ADDED
@@ -0,0 +1,544 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import collections
2
+ import math
3
+ import pathlib
4
+ import sys
5
+ from typing import List, Optional, Tuple, Union
6
+
7
+ from lm_eval.api.group import ConfigurableGroup
8
+ from lm_eval.api.metrics import (
9
+ aggregate_subtask_metrics,
10
+ pooled_sample_stderr,
11
+ stderr_for_metric,
12
+ )
13
+ from lm_eval.api.task import Task
14
+ from lm_eval.utils import eval_logger, positional_deprecated
15
+
16
+
17
+ class TaskOutput:
18
+ """
19
+ Wrapper class for Task outputs.It contains various attributes and methods to manage and calculate metrics for the task.
20
+
21
+ Attributes:
22
+ task (object): The task object.
23
+ task_name (str): The name of the task.
24
+ task_config (dict): The configuration of the task.
25
+ version (str): The version of the task.
26
+ group_name (str): The name of the task group.
27
+ n_shot (int): The number of shots for the task.
28
+ task_alias (str): The alias of the task.
29
+ group_alias (str): The alias of the task group.
30
+ is_group (bool): Indicates if the task is a group.
31
+ logged_samples (list): The list of logged samples.
32
+ sample_len (int): The length of the samples.
33
+ sample_metrics (defaultdict): The dictionary of samples' metrics.
34
+ agg_metrics (defaultdict): The dictionary of aggregate metrics.
35
+
36
+ Methods:
37
+ from_taskdict(cls, task_name: str, task):
38
+ Creates a TaskOutput instance from a task dictionary.
39
+
40
+ calculate_aggregate_metric(bootstrap_iters=100000) -> None:
41
+ Calculates the aggregate metrics for the task.
42
+ """
43
+
44
+ def __init__(
45
+ self,
46
+ task=None,
47
+ task_name=None,
48
+ task_config=None,
49
+ version=None,
50
+ group_name=None,
51
+ n_shot=None,
52
+ task_alias=None,
53
+ group_alias=None,
54
+ is_group=None,
55
+ ):
56
+ self.task = task
57
+ self.task_config = task_config
58
+ self.task_name = task_name
59
+ self.group_name = group_name
60
+ self.version = version
61
+ self.n_shot = n_shot
62
+ self.task_alias = task_alias
63
+ self.group_alias = group_alias
64
+ self.is_group = is_group
65
+ self.logged_samples = []
66
+ self.sample_len = None
67
+ self.sample_metrics = collections.defaultdict(list)
68
+ self.agg_metrics = collections.defaultdict(list)
69
+
70
+ @classmethod
71
+ def from_taskdict(cls, task_name: str, task):
72
+ if isinstance(task, tuple):
73
+ group_name, task = task
74
+ else:
75
+ group_name = None
76
+ if not task:
77
+ # these gets filtered out in get_task_list
78
+ # once they are added to group hierarchy
79
+ is_group = True
80
+ return cls(
81
+ task=task, task_name=task_name, is_group=is_group, group_name=group_name
82
+ )
83
+ version = task.VERSION
84
+ task_config = dict(task.dump_config())
85
+ if (n_shot := task_config.get("num_fewshot")) == 0:
86
+ n_shot = task_config.get("metadata", {}).get("num_fewshot", 0)
87
+ task_alias = task_config.get("alias")
88
+ group_alias = task_config.get("group_alias")
89
+ return cls(
90
+ task=task,
91
+ task_name=task_name,
92
+ task_config=task_config,
93
+ group_name=group_name,
94
+ version=version,
95
+ n_shot=n_shot,
96
+ task_alias=task_alias,
97
+ group_alias=group_alias,
98
+ )
99
+
100
+ def calculate_aggregate_metric(self, bootstrap_iters=100000) -> None:
101
+ for (metric, filter_key), items in self.sample_metrics.items():
102
+ agg_fn = self.task.aggregation()[metric]
103
+ metric_key = f"{metric},{filter_key}"
104
+ self.agg_metrics[metric_key] = agg_fn(items)
105
+ self.sample_len = len(items) # TODO: same sample size for each metric?
106
+ if isinstance(bootstrap_iters, int):
107
+ stderr_fn = stderr_for_metric(
108
+ metric=agg_fn,
109
+ bootstrap_iters=min(bootstrap_iters, 100)
110
+ if metric in ["bleu", "chrf", "ter"]
111
+ else bootstrap_iters,
112
+ )
113
+ self.agg_metrics[f"{metric}_stderr,{filter_key}"] = (
114
+ stderr_fn(items) if (stderr_fn and len(items) > 1) else "N/A"
115
+ )
116
+ else:
117
+ raise ValueError(
118
+ f"Received bootstrap_iters '{bootstrap_iters}' but expected an integer. Set to 0 to turn off stderr calculations."
119
+ )
120
+
121
+ def __repr__(self):
122
+ return (
123
+ f"TaskOutput(task_name={self.task_name}, "
124
+ f"group_name={self.group_name}, "
125
+ f"version={self.version}, "
126
+ f"n_shot={self.n_shot}, "
127
+ f"task_alias={self.task_alias}, "
128
+ f"group_alias={self.group_alias})"
129
+ )
130
+
131
+
132
+ def get_task_list(task_dict: dict) -> List[TaskOutput]:
133
+ outputs = []
134
+ for task_name, task_obj in task_dict.items():
135
+ if isinstance(task_obj, dict):
136
+ _outputs = get_task_list(task_obj)
137
+ outputs.extend(_outputs)
138
+ else:
139
+ task_output = TaskOutput.from_taskdict(task_name, task_obj)
140
+ outputs.append(task_output)
141
+
142
+ return outputs
143
+
144
+
145
+ def get_subtask_list(task_dict, task_root=None, depth=0):
146
+ subtask_list = {}
147
+ for group_obj, task_obj in task_dict.items():
148
+ if isinstance(group_obj, ConfigurableGroup):
149
+ # group_name = group_obj.group_name
150
+ group_name = group_obj.group_name
151
+ else:
152
+ group_name = group_obj
153
+ if isinstance(task_obj, dict):
154
+ _subtask_list = get_subtask_list(
155
+ task_obj, task_root=group_name, depth=depth + 1
156
+ )
157
+ if task_root:
158
+ subtask_list.setdefault((task_root, depth), []).extend(
159
+ [
160
+ _task
161
+ for (_task, _depth) in _subtask_list.keys()
162
+ if (_depth - 1) == depth
163
+ ]
164
+ )
165
+
166
+ subtask_list = {**subtask_list, **_subtask_list}
167
+ else:
168
+ if isinstance(task_obj, ConfigurableGroup):
169
+ # group_or_task_name = task_obj.group_name
170
+ group_or_task_name = task_obj.group_name
171
+ elif isinstance(task_obj, Task):
172
+ # group_or_task_name = task_obj.task_name
173
+ group_or_task_name = task_obj.task_name
174
+
175
+ if task_root is None:
176
+ subtask_list.setdefault((group_or_task_name, depth), [])
177
+ else:
178
+ subtask_list.setdefault((task_root, depth), []).append(
179
+ group_or_task_name
180
+ )
181
+
182
+ if depth == 0:
183
+ _subtask_list = {}
184
+ for group_key, task_list in subtask_list.items():
185
+ group_name, depth = group_key
186
+ _subtask_list[group_name] = task_list
187
+ subtask_list = _subtask_list
188
+
189
+ return subtask_list
190
+
191
+
192
+ def print_writeout(task) -> None:
193
+ for inst in task.instances:
194
+ # print the prompt for the first few documents
195
+ if inst.doc_id < 1:
196
+ eval_logger.info(
197
+ f"Task: {task}; document {inst.doc_id}; context prompt (starting on next line):\
198
+ \n{inst.args[0]}\n(end of prompt on previous line)\ntarget string or answer choice index (starting on next line):\n{task.doc_to_target(inst.doc)}\n(end of target on previous line)"
199
+ )
200
+ eval_logger.info(f"Request: {str(inst)}")
201
+
202
+
203
+ def get_sample_size(task, limit: Optional[int]) -> Union[int, None]:
204
+ if limit is not None:
205
+ limit = (
206
+ int(math.ceil(len(task.eval_docs) * limit)) if limit < 1.0 else int(limit)
207
+ )
208
+ return limit
209
+
210
+
211
+ def prepare_print_tasks(
212
+ task_dict: dict,
213
+ results: dict,
214
+ task_depth=0,
215
+ group_depth=0,
216
+ ) -> Tuple[dict, dict]:
217
+ """
218
+ @param task_dict: Dictionary representing the group hierarchy of tasks. Each key is a group name and its
219
+ value is a list of task names.
220
+ @param results: Dictionary containing the results of each task. Each key is a
221
+ group name and its value is a dictionary of task results.
222
+ @param task_depth: The indentation level for printing the task
223
+ hierarchy. Default is 0.
224
+ @param group_depth: The indentation level for printing the group
225
+ hierarchy. Default is 0.
226
+ @return: A tuple of two dictionaries: results_agg and groups_agg. results_agg contains
227
+ aggregated results for each task, and groups_agg contains aggregated results for each group.
228
+
229
+ Prepares the task hierarchy and aggregates the results for each task and group recursively for printing.
230
+ """
231
+
232
+ def _sort_task_dict(task_dict):
233
+ """
234
+ Helper utility. Sorts the task dict at the current level of the hierarchy based on alphabetized task name.
235
+ Required so that we end up sorting within each sub-header correctly.
236
+ """
237
+
238
+ return dict(
239
+ sorted(
240
+ task_dict.items(),
241
+ key=lambda item: item[0].group_name
242
+ if isinstance(item[0], ConfigurableGroup)
243
+ else item[0],
244
+ )
245
+ )
246
+
247
+ task_agg = collections.defaultdict(dict)
248
+ group_agg = collections.defaultdict(dict)
249
+ task_dict = _sort_task_dict(task_dict)
250
+ for task_or_group_name, task_or_group_obj in task_dict.items():
251
+ tab_string = " " * task_depth + "- " if task_depth > 0 else ""
252
+ if isinstance(task_or_group_name, ConfigurableGroup):
253
+ # string_name = task_or_group_name.group_name
254
+ name = task_or_group_name.group_name
255
+ from_configurable_group = True
256
+ task_or_group_obj = _sort_task_dict(task_or_group_obj)
257
+ elif isinstance(task_or_group_name, str):
258
+ name = task_or_group_name
259
+ if isinstance(task_or_group_obj, Task):
260
+ # string_name = task_or_group_obj.task_name
261
+ name = task_or_group_obj.task_name
262
+ from_configurable_group = False
263
+
264
+ task_agg[name] = results[name].copy()
265
+ if from_configurable_group:
266
+ if task_or_group_name.group_alias is not None:
267
+ alias = task_or_group_name.group_alias
268
+ else:
269
+ alias = task_or_group_name.group
270
+ else:
271
+ if "alias" in task_agg[name]:
272
+ alias = task_agg[name]["alias"]
273
+ else:
274
+ alias = name
275
+
276
+ task_agg[name]["alias"] = tab_string + alias
277
+ if "samples" in task_agg[name]:
278
+ task_agg[name].pop("samples")
279
+
280
+ if from_configurable_group and (" " not in results[name]):
281
+ group_tab_string = " " * group_depth + "- " if group_depth > 0 else ""
282
+ group_agg[name] = results[name].copy()
283
+ group_agg[name]["alias"] = group_tab_string + alias
284
+ if "samples" in group_agg[name]:
285
+ group_agg[name].pop("samples")
286
+
287
+ if isinstance(task_or_group_obj, dict):
288
+ task_depth += 1
289
+ group_depth += 1
290
+ _task_agg, _group_agg = prepare_print_tasks(
291
+ task_or_group_obj, results, task_depth, group_depth
292
+ )
293
+ task_agg = {
294
+ **task_agg,
295
+ **_task_agg,
296
+ }
297
+ group_agg = {**group_agg, **_group_agg}
298
+ task_depth -= 1
299
+ group_depth -= 1
300
+ return task_agg, group_agg
301
+
302
+
303
+ def consolidate_results(
304
+ eval_tasks: List[TaskOutput],
305
+ ) -> Tuple[dict, dict, dict, dict, dict, dict]:
306
+ """
307
+ @param eval_tasks: list(TaskOutput).
308
+ @return: A tuple containing the consolidated results, samples, configs, versions, and num_fewshot.
309
+
310
+ Consolidates the results of multiple evaluation tasks into a single structure.
311
+
312
+ The method iterates over each evaluation instance and extracts relevant information to create the consolidated
313
+ results structure. The consolidated results structure has the following properties:
314
+
315
+ - results: A defaultdict with task names as keys and dictionaries as values. Each dictionary contains
316
+ metric/filter pairs as keys and corresponding metric values as values. The "alias" key is used to store task
317
+ aliases specified in the task configuration.
318
+ - samples: A defaultdict with task names as keys and lists of log samples as values.
319
+ - configs: A defaultdict with task names as keys and task configurations as values.
320
+ - versions: A defaultdict with task names as keys and task versions as values.
321
+ - num_fewshot: A defaultdict with task names as keys and number of few-shot samples as values.
322
+ - higher_is_better: A defaultdict with task names as keys and indicators of whether higher values are better
323
+ for each metric as values.
324
+
325
+ The method then returns the consolidated results, samples, configs, versions, and num_fewshot as a tuple.
326
+ """
327
+ # stores the final result for each task, for each metric/filter pair.
328
+ results = collections.defaultdict(dict)
329
+ # logs info about each document evaluated.
330
+ samples = collections.defaultdict(list)
331
+ # store num-fewshot value per task
332
+ num_fewshot = collections.defaultdict(int)
333
+ # Tracks the YAML configs of all chosen task
334
+ configs = collections.defaultdict(dict)
335
+ # Tracks each task's version.
336
+ versions = collections.defaultdict(dict)
337
+ # Track `higher_is_better` for each metric
338
+ higher_is_better = collections.defaultdict(dict)
339
+
340
+ for task_output in eval_tasks:
341
+ if "task_alias" in (task_config := task_output.task_config):
342
+ results[task_output.task_name]["alias"] = task_config["task_alias"]
343
+ else:
344
+ results[task_output.task_name]["alias"] = task_output.task_name
345
+ if group_alias := task_output.group_alias:
346
+ if group_alias not in results and (group_name := task_output.group_name):
347
+ results[group_name]["alias"] = group_alias
348
+ num_fewshot[task_output.task_name] = task_output.n_shot
349
+ configs[task_output.task_name] = task_output.task_config
350
+ versions[task_output.task_name] = task_output.version
351
+ samples[task_output.task_name] = task_output.logged_samples
352
+ higher_is_better[task_output.task_name] = task_output.task.higher_is_better()
353
+ for (metric, filter_key), items in task_output.sample_metrics.items():
354
+ metric_key = f"{metric},{filter_key}"
355
+ results[task_output.task_name][metric_key] = task_output.agg_metrics[
356
+ metric_key
357
+ ]
358
+ results[task_output.task_name]["samples"] = task_output.sample_len
359
+ results[task_output.task_name][f"{metric}_stderr,{filter_key}"] = (
360
+ task_output.agg_metrics[f"{metric}_stderr,{filter_key}"]
361
+ )
362
+ return results, samples, configs, versions, num_fewshot, higher_is_better
363
+
364
+
365
+ def consolidate_group_results(
366
+ results,
367
+ versions,
368
+ task_dict,
369
+ task_root=None,
370
+ show_group_table=False,
371
+ task_aggregation_list=None,
372
+ ) -> Tuple[dict, dict, bool, Union[None,]]:
373
+ """
374
+ (Recursively) calculates groups' aggregated metrics and updates the results and versions dictionaries with this info.
375
+
376
+ @return: a tuple [results, versions, show_group_table, task_aggregation_list] with formats described below:
377
+
378
+ - results: A defaultdict with task names (and, after this function is called, group names of
379
+ groups that perform aggregation) as keys, and dictionaries with "alias" and metric,filter_name pairs as keys.
380
+ - versions: A defaultdict with task names (and, after this function is called, group names of
381
+ groups that perform aggregation) as keys, and float values representing the task or group's version if a version is specified. (defaulting to None).
382
+ - show_group_table: a boolean which is true if there exists a group that requires printing of its aggregated scores in a group table.
383
+ - task_aggregation_list: a defaultdict listing the subtasks to average over to produce a given group's end metric.
384
+
385
+ The method then returns the updated results, versions, show_group_table, and task_aggregation_list as a tuple.
386
+ In the top-level invocation of this function, task_aggregation_list is ignored.
387
+ """
388
+ if task_root is None:
389
+ task_root = {}
390
+
391
+ if task_aggregation_list is None:
392
+ task_aggregation_list = {}
393
+
394
+ for group_or_task, group_or_task_info in task_dict.items():
395
+ # Convert to string
396
+ if isinstance(group_or_task, ConfigurableGroup):
397
+ group_config = group_or_task.config
398
+ group_or_task = group_or_task.group_name
399
+ else:
400
+ group_config = None
401
+
402
+ if isinstance(group_or_task_info, Task):
403
+ if task_root:
404
+ task_aggregation_list.setdefault(task_root, []).append(
405
+ group_or_task_info.task_name
406
+ )
407
+ else:
408
+ (
409
+ results,
410
+ versions,
411
+ show_group_table,
412
+ _task_aggregation_list,
413
+ ) = consolidate_group_results(
414
+ results,
415
+ versions,
416
+ group_or_task_info,
417
+ group_or_task,
418
+ show_group_table,
419
+ task_aggregation_list,
420
+ )
421
+ if task_root:
422
+ task_aggregation_list.setdefault(task_root, []).extend(
423
+ task_aggregation_list.get(group_or_task, [])
424
+ )
425
+
426
+ if (group_config is None) or (
427
+ group_config["aggregate_metric_list"] is None
428
+ ):
429
+ results[group_or_task][" "] = " "
430
+ continue
431
+
432
+ if "aggregate_metric_list" in group_config:
433
+ agg_metric_list = group_config["aggregate_metric_list"]
434
+
435
+ show_group_table = show_group_table | bool(
436
+ group_config["aggregate_metric_list"]
437
+ )
438
+
439
+ task_list = _task_aggregation_list[group_or_task]
440
+
441
+ metric_list = list(
442
+ {
443
+ key
444
+ for task in task_list
445
+ for key in results[task].keys()
446
+ if "_stderr" not in key and key not in ["task", "alias", "samples"]
447
+ }
448
+ )
449
+ for metric in metric_list:
450
+ stderr = "_stderr,".join(metric.split(","))
451
+
452
+ # gather metrics, sizes, and stderrs from subtasks
453
+ metrics = [
454
+ results[task][metric]
455
+ for task in task_list
456
+ if metric in results[task]
457
+ ] # TODO: copy?
458
+ stderrs = [
459
+ results[task][stderr]
460
+ for task in task_list
461
+ if stderr in results[task]
462
+ ]
463
+ sizes = [
464
+ results[task]["samples"]
465
+ for task in task_list
466
+ if metric in results[task]
467
+ ]
468
+
469
+ for metric_config in agg_metric_list:
470
+ for filter_name in metric_config["filter_list"]:
471
+ if metric != ",".join([metric_config["metric"], filter_name]):
472
+ continue
473
+
474
+ # compute group's pooled metric and stderr
475
+ if metric_config["aggregation"] == "mean":
476
+ aggregate_fn = aggregate_subtask_metrics
477
+ elif callable(metric_config["aggregation"]):
478
+ aggregate_fn = metric_config["aggregation"]
479
+ else:
480
+ raise ValueError(
481
+ f"Currently, only 'mean' is supported for automatically aggregating scores across groups' subtasks. Got '{metric_config['aggregation']}' for group '{group_or_task}'"
482
+ )
483
+
484
+ results[group_or_task][metric] = aggregate_fn(
485
+ metrics,
486
+ sizes,
487
+ metric_config["weight_by_size"],
488
+ )
489
+ # TODO: calculate groups' metrics using arbitrary agg fns
490
+ if "N/A" in stderrs:
491
+ results[group_or_task][stderr] = "N/A"
492
+ else:
493
+ # NOTE: this assumes we are using the mean to aggregate. There are warnings about this elsewhere
494
+ results[group_or_task][stderr] = pooled_sample_stderr(
495
+ stderrs, sizes
496
+ )
497
+
498
+ results[group_or_task]["samples"] = sum(sizes)
499
+ group_metadata = group_config.get("metadata", None)
500
+ if group_metadata is not None:
501
+ versions[group_or_task] = group_metadata.get("version", None)
502
+ # print(results)
503
+ return results, versions, show_group_table, task_aggregation_list
504
+
505
+
506
+ @positional_deprecated
507
+ def find_test_root(start_path: pathlib.Path) -> pathlib.Path:
508
+ """
509
+ Search upward in the directory tree to a maximum of three layers
510
+ to find and return the package root (containing the 'tests' folder)
511
+ """
512
+ cur_path = start_path.resolve()
513
+ max_layers = 3
514
+ for _ in range(max_layers):
515
+ if (cur_path / "tests" / "test_version_stable.py").exists():
516
+ return cur_path
517
+ else:
518
+ cur_path = cur_path.parent.resolve()
519
+ raise FileNotFoundError(
520
+ f"Unable to find package root within {max_layers} upwards" + f"of {start_path}"
521
+ )
522
+
523
+
524
+ @positional_deprecated
525
+ def run_task_tests(task_list: List[str]):
526
+ """
527
+ Find the package root and run the tests for the given tasks
528
+ """
529
+ import pytest
530
+
531
+ package_root = find_test_root(start_path=pathlib.Path(__file__))
532
+ task_string = " or ".join(task_list)
533
+ args = [
534
+ f"{package_root}/tests/test_version_stable.py",
535
+ f"--rootdir={package_root}",
536
+ "-k",
537
+ f"{task_string}",
538
+ ]
539
+ sys.path.append(str(package_root))
540
+ pytest_return_val = pytest.main(args)
541
+ if pytest_return_val:
542
+ raise ValueError(
543
+ f"Not all tests for the specified tasks ({task_list}) ran successfully! Error code: {pytest_return_val}"
544
+ )
testbed/EleutherAI__lm-evaluation-harness/lm_eval/loggers/__init__.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ from .evaluation_tracker import EvaluationTracker
2
+ from .wandb_logger import WandbLogger
testbed/EleutherAI__lm-evaluation-harness/lm_eval/loggers/evaluation_tracker.py ADDED
@@ -0,0 +1,521 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ import re
4
+ import time
5
+ from collections import defaultdict
6
+ from dataclasses import asdict, dataclass
7
+ from datetime import datetime
8
+ from pathlib import Path
9
+
10
+ from datasets import load_dataset
11
+ from datasets.utils.metadata import MetadataConfigs
12
+ from huggingface_hub import (
13
+ DatasetCard,
14
+ DatasetCardData,
15
+ HfApi,
16
+ hf_hub_url,
17
+ )
18
+ from huggingface_hub.utils import build_hf_headers, get_session, hf_raise_for_status
19
+
20
+ from lm_eval.utils import (
21
+ eval_logger,
22
+ get_file_datetime,
23
+ get_file_task_name,
24
+ get_results_filenames,
25
+ get_sample_results_filenames,
26
+ handle_non_serializable,
27
+ hash_string,
28
+ sanitize_list,
29
+ sanitize_model_name,
30
+ sanitize_task_name,
31
+ )
32
+
33
+
34
+ @dataclass(init=False)
35
+ class GeneralConfigTracker:
36
+ """
37
+ Tracker for the evaluation parameters.
38
+
39
+ Attributes:
40
+ model_source (str): Source of the model (e.g. Hugging Face, GGUF, etc.)
41
+ model_name (str): Name of the model.
42
+ model_name_sanitized (str): Sanitized model name for directory creation.
43
+ start_time (float): Start time of the experiment. Logged at class init.
44
+ end_time (float): Start time of the experiment. Logged when calling [`GeneralConfigTracker.log_end_time`]
45
+ total_evaluation_time_seconds (str): Inferred total evaluation time in seconds (from the start and end times).
46
+ """
47
+
48
+ model_source: str = None
49
+ model_name: str = None
50
+ model_name_sanitized: str = None
51
+ system_instruction: str = None
52
+ system_instruction_sha: str = None
53
+ fewshot_as_multiturn: bool = None
54
+ chat_template: str = None
55
+ chat_template_sha: str = None
56
+ start_time: float = None
57
+ end_time: float = None
58
+ total_evaluation_time_seconds: str = None
59
+
60
+ def __init__(self) -> None:
61
+ """Starts the evaluation timer."""
62
+ self.start_time = time.perf_counter()
63
+
64
+ @staticmethod
65
+ def _get_model_name(model_args: str) -> str:
66
+ """Extracts the model name from the model arguments."""
67
+
68
+ def extract_model_name(model_args: str, key: str) -> str:
69
+ """Extracts the model name from the model arguments using a key."""
70
+ args_after_key = model_args.split(key)[1]
71
+ return args_after_key.split(",")[0]
72
+
73
+ # order does matter, e.g. peft and delta are provided together with pretrained
74
+ prefixes = ["peft=", "delta=", "pretrained=", "model=", "path=", "engine="]
75
+ for prefix in prefixes:
76
+ if prefix in model_args:
77
+ return extract_model_name(model_args, prefix)
78
+ return ""
79
+
80
+ def log_experiment_args(
81
+ self,
82
+ model_source: str,
83
+ model_args: str,
84
+ system_instruction: str,
85
+ chat_template: str,
86
+ fewshot_as_multiturn: bool,
87
+ ) -> None:
88
+ """Logs model parameters and job ID."""
89
+ self.model_source = model_source
90
+ self.model_name = GeneralConfigTracker._get_model_name(model_args)
91
+ self.model_name_sanitized = sanitize_model_name(self.model_name)
92
+ self.system_instruction = system_instruction
93
+ self.system_instruction_sha = (
94
+ hash_string(system_instruction) if system_instruction else None
95
+ )
96
+ self.chat_template = chat_template
97
+ self.chat_template_sha = hash_string(chat_template) if chat_template else None
98
+ self.fewshot_as_multiturn = fewshot_as_multiturn
99
+
100
+ def log_end_time(self) -> None:
101
+ """Logs the end time of the evaluation and calculates the total evaluation time."""
102
+ self.end_time = time.perf_counter()
103
+ self.total_evaluation_time_seconds = str(self.end_time - self.start_time)
104
+
105
+
106
+ class EvaluationTracker:
107
+ """
108
+ Keeps track and saves relevant information of the evaluation process.
109
+ Compiles the data from trackers and writes it to files, which can be published to the Hugging Face hub if requested.
110
+ """
111
+
112
+ def __init__(
113
+ self,
114
+ output_path: str = None,
115
+ hub_results_org: str = "",
116
+ hub_repo_name: str = "",
117
+ details_repo_name: str = "",
118
+ results_repo_name: str = "",
119
+ push_results_to_hub: bool = False,
120
+ push_samples_to_hub: bool = False,
121
+ public_repo: bool = False,
122
+ token: str = "",
123
+ leaderboard_url: str = "",
124
+ point_of_contact: str = "",
125
+ gated: bool = False,
126
+ ) -> None:
127
+ """
128
+ Creates all the necessary loggers for evaluation tracking.
129
+
130
+ Args:
131
+ output_path (str): Path to save the results. If not provided, the results won't be saved.
132
+ hub_results_org (str): The Hugging Face organization to push the results to. If not provided, the results will be pushed to the owner of the Hugging Face token.
133
+ hub_repo_name (str): The name of the Hugging Face repository to push the results to. If not provided, the results will be pushed to `lm-eval-results`.
134
+ details_repo_name (str): The name of the Hugging Face repository to push the details to. If not provided, the results will be pushed to `lm-eval-results`.
135
+ result_repo_name (str): The name of the Hugging Face repository to push the results to. If not provided, the results will not be pushed and will be found in the details_hub_repo.
136
+ push_results_to_hub (bool): Whether to push the results to the Hugging Face hub.
137
+ push_samples_to_hub (bool): Whether to push the samples to the Hugging Face hub.
138
+ public_repo (bool): Whether to push the results to a public or private repository.
139
+ token (str): Token to use when pushing to the Hugging Face hub. This token should have write access to `hub_results_org`.
140
+ leaderboard_url (str): URL to the leaderboard on the Hugging Face hub on the dataset card.
141
+ point_of_contact (str): Contact information on the Hugging Face hub dataset card.
142
+ gated (bool): Whether to gate the repository.
143
+ """
144
+ self.general_config_tracker = GeneralConfigTracker()
145
+
146
+ self.output_path = output_path
147
+ self.push_results_to_hub = push_results_to_hub
148
+ self.push_samples_to_hub = push_samples_to_hub
149
+ self.public_repo = public_repo
150
+ self.leaderboard_url = leaderboard_url
151
+ self.point_of_contact = point_of_contact
152
+ self.api = HfApi(token=token) if token else None
153
+ self.gated_repo = gated
154
+
155
+ if not self.api and (push_results_to_hub or push_samples_to_hub):
156
+ raise ValueError(
157
+ "Hugging Face token is not defined, but 'push_results_to_hub' or 'push_samples_to_hub' is set to True. "
158
+ "Please provide a valid Hugging Face token by setting the HF_TOKEN environment variable."
159
+ )
160
+
161
+ if (
162
+ self.api
163
+ and hub_results_org == ""
164
+ and (push_results_to_hub or push_samples_to_hub)
165
+ ):
166
+ hub_results_org = self.api.whoami()["name"]
167
+ eval_logger.warning(
168
+ f"hub_results_org was not specified. Results will be pushed to '{hub_results_org}'."
169
+ )
170
+
171
+ if hub_repo_name == "":
172
+ details_repo_name = (
173
+ details_repo_name if details_repo_name != "" else "lm-eval-results"
174
+ )
175
+ results_repo_name = (
176
+ results_repo_name if results_repo_name != "" else details_repo_name
177
+ )
178
+ else:
179
+ details_repo_name = hub_repo_name
180
+ results_repo_name = hub_repo_name
181
+ eval_logger.warning(
182
+ "hub_repo_name was specified. Both details and results will be pushed to the same repository. Using hub_repo_name is no longer recommended, details_repo_name and results_repo_name should be used instead."
183
+ )
184
+
185
+ self.details_repo = f"{hub_results_org}/{details_repo_name}"
186
+ self.details_repo_private = f"{hub_results_org}/{details_repo_name}-private"
187
+ self.results_repo = f"{hub_results_org}/{results_repo_name}"
188
+ self.results_repo_private = f"{hub_results_org}/{results_repo_name}-private"
189
+
190
+ def save_results_aggregated(
191
+ self,
192
+ results: dict,
193
+ samples: dict,
194
+ ) -> None:
195
+ """
196
+ Saves the aggregated results and samples to the output path and pushes them to the Hugging Face hub if requested.
197
+
198
+ Args:
199
+ results (dict): The aggregated results to save.
200
+ samples (dict): The samples results to save.
201
+ """
202
+ self.general_config_tracker.log_end_time()
203
+
204
+ if self.output_path:
205
+ try:
206
+ eval_logger.info("Saving results aggregated")
207
+
208
+ # calculate cumulative hash for each task - only if samples are provided
209
+ task_hashes = {}
210
+ if samples:
211
+ for task_name, task_samples in samples.items():
212
+ sample_hashes = [
213
+ s["doc_hash"] + s["prompt_hash"] + s["target_hash"]
214
+ for s in task_samples
215
+ ]
216
+ task_hashes[task_name] = hash_string("".join(sample_hashes))
217
+
218
+ # update initial results dict
219
+ results.update({"task_hashes": task_hashes})
220
+ results.update(asdict(self.general_config_tracker))
221
+ dumped = json.dumps(
222
+ results,
223
+ indent=2,
224
+ default=handle_non_serializable,
225
+ ensure_ascii=False,
226
+ )
227
+
228
+ path = Path(self.output_path if self.output_path else Path.cwd())
229
+ path = path.joinpath(self.general_config_tracker.model_name_sanitized)
230
+ path.mkdir(parents=True, exist_ok=True)
231
+
232
+ self.date_id = datetime.now().isoformat().replace(":", "-")
233
+ file_results_aggregated = path.joinpath(f"results_{self.date_id}.json")
234
+ file_results_aggregated.open("w", encoding="utf-8").write(dumped)
235
+
236
+ if self.api and self.push_results_to_hub:
237
+ repo_id = (
238
+ self.results_repo
239
+ if self.public_repo
240
+ else self.results_repo_private
241
+ )
242
+ self.api.create_repo(
243
+ repo_id=repo_id,
244
+ repo_type="dataset",
245
+ private=not self.public_repo,
246
+ exist_ok=True,
247
+ )
248
+ self.api.upload_file(
249
+ repo_id=repo_id,
250
+ path_or_fileobj=str(
251
+ path.joinpath(f"results_{self.date_id}.json")
252
+ ),
253
+ path_in_repo=os.path.join(
254
+ self.general_config_tracker.model_name,
255
+ f"results_{self.date_id}.json",
256
+ ),
257
+ repo_type="dataset",
258
+ commit_message=f"Adding aggregated results for {self.general_config_tracker.model_name}",
259
+ )
260
+ eval_logger.info(
261
+ "Successfully pushed aggregated results to the Hugging Face Hub. "
262
+ f"You can find them at: {repo_id}"
263
+ )
264
+
265
+ except Exception as e:
266
+ eval_logger.warning("Could not save results aggregated")
267
+ eval_logger.info(repr(e))
268
+ else:
269
+ eval_logger.info(
270
+ "Output path not provided, skipping saving results aggregated"
271
+ )
272
+
273
+ def save_results_samples(
274
+ self,
275
+ task_name: str,
276
+ samples: dict,
277
+ ) -> None:
278
+ """
279
+ Saves the samples results to the output path and pushes them to the Hugging Face hub if requested.
280
+
281
+ Args:
282
+ task_name (str): The task name to save the samples for.
283
+ samples (dict): The samples results to save.
284
+ """
285
+ if self.output_path:
286
+ try:
287
+ eval_logger.info(f"Saving per-sample results for: {task_name}")
288
+
289
+ path = Path(self.output_path if self.output_path else Path.cwd())
290
+ path = path.joinpath(self.general_config_tracker.model_name_sanitized)
291
+ path.mkdir(parents=True, exist_ok=True)
292
+
293
+ file_results_samples = path.joinpath(
294
+ f"samples_{task_name}_{self.date_id}.jsonl"
295
+ )
296
+
297
+ for sample in samples:
298
+ # we first need to sanitize arguments and resps
299
+ # otherwise we won't be able to load the dataset
300
+ # using the datasets library
301
+ arguments = {}
302
+ for i, arg in enumerate(sample["arguments"]):
303
+ arguments[f"gen_args_{i}"] = {}
304
+ for j, tmp in enumerate(arg):
305
+ arguments[f"gen_args_{i}"][f"arg_{j}"] = tmp
306
+
307
+ sample["resps"] = sanitize_list(sample["resps"])
308
+ sample["filtered_resps"] = sanitize_list(sample["filtered_resps"])
309
+ sample["arguments"] = arguments
310
+ sample["target"] = str(sample["target"])
311
+
312
+ sample_dump = (
313
+ json.dumps(
314
+ sample,
315
+ default=handle_non_serializable,
316
+ ensure_ascii=False,
317
+ )
318
+ + "\n"
319
+ )
320
+
321
+ with open(file_results_samples, "a", encoding="utf-8") as f:
322
+ f.write(sample_dump)
323
+
324
+ if self.api and self.push_samples_to_hub:
325
+ repo_id = (
326
+ self.details_repo
327
+ if self.public_repo
328
+ else self.details_repo_private
329
+ )
330
+ self.api.create_repo(
331
+ repo_id=repo_id,
332
+ repo_type="dataset",
333
+ private=not self.public_repo,
334
+ exist_ok=True,
335
+ )
336
+ try:
337
+ if self.gated_repo:
338
+ headers = build_hf_headers()
339
+ r = get_session().put(
340
+ url=f"https://huggingface.co/api/datasets/{repo_id}/settings",
341
+ headers=headers,
342
+ json={"gated": "auto"},
343
+ )
344
+ hf_raise_for_status(r)
345
+ except Exception as e:
346
+ eval_logger.warning("Could not gate the repository")
347
+ eval_logger.info(repr(e))
348
+ self.api.upload_folder(
349
+ repo_id=repo_id,
350
+ folder_path=str(path),
351
+ path_in_repo=self.general_config_tracker.model_name_sanitized,
352
+ repo_type="dataset",
353
+ commit_message=f"Adding samples results for {task_name} to {self.general_config_tracker.model_name}",
354
+ )
355
+ eval_logger.info(
356
+ f"Successfully pushed sample results for task: {task_name} to the Hugging Face Hub. "
357
+ f"You can find them at: {repo_id}"
358
+ )
359
+
360
+ except Exception as e:
361
+ eval_logger.warning("Could not save sample results")
362
+ eval_logger.info(repr(e))
363
+ else:
364
+ eval_logger.info("Output path not provided, skipping saving sample results")
365
+
366
+ def recreate_metadata_card(self) -> None:
367
+ """
368
+ Creates a metadata card for the evaluation results dataset and pushes it to the Hugging Face hub.
369
+ """
370
+
371
+ eval_logger.info("Recreating metadata card")
372
+ repo_id = self.details_repo if self.public_repo else self.details_repo_private
373
+
374
+ files_in_repo = self.api.list_repo_files(repo_id=repo_id, repo_type="dataset")
375
+ results_files = get_results_filenames(files_in_repo)
376
+ sample_files = get_sample_results_filenames(files_in_repo)
377
+
378
+ # Build a dictionary to store the latest evaluation datetime for:
379
+ # - Each tested model and its aggregated results
380
+ # - Each task and sample results, if existing
381
+ # i.e. {
382
+ # "org__model_name__gsm8k": "2021-09-01T12:00:00",
383
+ # "org__model_name__ifeval": "2021-09-01T12:00:00",
384
+ # "org__model_name__results": "2021-09-01T12:00:00"
385
+ # }
386
+ latest_task_results_datetime = defaultdict(lambda: datetime.min.isoformat())
387
+
388
+ for file_path in sample_files:
389
+ file_path = Path(file_path)
390
+ filename = file_path.name
391
+ model_name = file_path.parent
392
+ task_name = get_file_task_name(filename)
393
+ results_datetime = get_file_datetime(filename)
394
+ task_name_sanitized = sanitize_task_name(task_name)
395
+ # Results and sample results for the same model and task will have the same datetime
396
+ samples_key = f"{model_name}__{task_name_sanitized}"
397
+ results_key = f"{model_name}__results"
398
+ latest_datetime = max(
399
+ latest_task_results_datetime[samples_key],
400
+ results_datetime,
401
+ )
402
+ latest_task_results_datetime[samples_key] = latest_datetime
403
+ latest_task_results_datetime[results_key] = max(
404
+ latest_task_results_datetime[results_key],
405
+ latest_datetime,
406
+ )
407
+
408
+ # Create metadata card
409
+ card_metadata = MetadataConfigs()
410
+
411
+ # Add the latest aggregated results to the metadata card for easy access
412
+ for file_path in results_files:
413
+ file_path = Path(file_path)
414
+ results_filename = file_path.name
415
+ model_name = file_path.parent
416
+ eval_date = get_file_datetime(results_filename)
417
+ eval_date_sanitized = re.sub(r"[^\w\.]", "_", eval_date)
418
+ results_filename = Path("**") / Path(results_filename).name
419
+ config_name = f"{model_name}__results"
420
+ sanitized_last_eval_date_results = re.sub(
421
+ r"[^\w\.]", "_", latest_task_results_datetime[config_name]
422
+ )
423
+
424
+ if eval_date_sanitized == sanitized_last_eval_date_results:
425
+ # Ensure that all results files are listed in the metadata card
426
+ current_results = card_metadata.get(config_name, {"data_files": []})
427
+ current_results["data_files"].append(
428
+ {"split": eval_date_sanitized, "path": [str(results_filename)]}
429
+ )
430
+ card_metadata[config_name] = current_results
431
+ # If the results file is the newest, update the "latest" field in the metadata card
432
+ card_metadata[config_name]["data_files"].append(
433
+ {"split": "latest", "path": [str(results_filename)]}
434
+ )
435
+
436
+ # Add the tasks details configs
437
+ for file_path in sample_files:
438
+ file_path = Path(file_path)
439
+ filename = file_path.name
440
+ model_name = file_path.parent
441
+ task_name = get_file_task_name(filename)
442
+ eval_date = get_file_datetime(filename)
443
+ task_name_sanitized = sanitize_task_name(task_name)
444
+ eval_date_sanitized = re.sub(r"[^\w\.]", "_", eval_date)
445
+ results_filename = Path("**") / Path(filename).name
446
+ config_name = f"{model_name}__{task_name_sanitized}"
447
+ sanitized_last_eval_date_results = re.sub(
448
+ r"[^\w\.]", "_", latest_task_results_datetime[config_name]
449
+ )
450
+ if eval_date_sanitized == sanitized_last_eval_date_results:
451
+ # Ensure that all sample results files are listed in the metadata card
452
+ current_details_for_task = card_metadata.get(
453
+ config_name, {"data_files": []}
454
+ )
455
+ current_details_for_task["data_files"].append(
456
+ {"split": eval_date_sanitized, "path": [str(results_filename)]}
457
+ )
458
+ card_metadata[config_name] = current_details_for_task
459
+ # If the samples results file is the newest, update the "latest" field in the metadata card
460
+ card_metadata[config_name]["data_files"].append(
461
+ {"split": "latest", "path": [str(results_filename)]}
462
+ )
463
+
464
+ # Get latest results and extract info to update metadata card examples
465
+ latest_datetime = max(latest_task_results_datetime.values())
466
+ latest_model_name = max(
467
+ latest_task_results_datetime, key=lambda k: latest_task_results_datetime[k]
468
+ )
469
+ last_results_file = [
470
+ f for f in results_files if latest_datetime.replace(":", "-") in f
471
+ ][0]
472
+ last_results_file_path = hf_hub_url(
473
+ repo_id=repo_id, filename=last_results_file, repo_type="dataset"
474
+ )
475
+ latest_results_file = load_dataset(
476
+ "json", data_files=last_results_file_path, split="train"
477
+ )
478
+ results_dict = latest_results_file["results"][0]
479
+ new_dictionary = {"all": results_dict}
480
+ new_dictionary.update(results_dict)
481
+ results_string = json.dumps(new_dictionary, indent=4)
482
+
483
+ dataset_summary = (
484
+ "Dataset automatically created during the evaluation run of model "
485
+ )
486
+ if self.general_config_tracker.model_source == "hf":
487
+ dataset_summary += f"[{self.general_config_tracker.model_name}](https://huggingface.co/{self.general_config_tracker.model_name})\n"
488
+ else:
489
+ dataset_summary += f"{self.general_config_tracker.model_name}\n"
490
+ dataset_summary += (
491
+ f"The dataset is composed of {len(card_metadata)-1} configuration(s), each one corresponding to one of the evaluated task.\n\n"
492
+ f"The dataset has been created from {len(results_files)} run(s). Each run can be found as a specific split in each "
493
+ 'configuration, the split being named using the timestamp of the run.The "train" split is always pointing to the latest results.\n\n'
494
+ 'An additional configuration "results" store all the aggregated results of the run.\n\n'
495
+ "To load the details from a run, you can for instance do the following:\n"
496
+ )
497
+ if self.general_config_tracker.model_source == "hf":
498
+ dataset_summary += (
499
+ "```python\nfrom datasets import load_dataset\n"
500
+ f'data = load_dataset(\n\t"{repo_id}",\n\tname="{latest_model_name}",\n\tsplit="latest"\n)\n```\n\n'
501
+ )
502
+ dataset_summary += (
503
+ "## Latest results\n\n"
504
+ f'These are the [latest results from run {latest_datetime}]({last_results_file_path.replace("/resolve/", "/blob/")}) '
505
+ "(note that there might be results for other tasks in the repos if successive evals didn't cover the same tasks. "
506
+ 'You find each in the results and the "latest" split for each eval):\n\n'
507
+ f"```python\n{results_string}\n```"
508
+ )
509
+ card_data = DatasetCardData(
510
+ dataset_summary=dataset_summary,
511
+ repo_url=f"https://huggingface.co/{self.general_config_tracker.model_name}",
512
+ pretty_name=f"Evaluation run of {self.general_config_tracker.model_name}",
513
+ leaderboard_url=self.leaderboard_url,
514
+ point_of_contact=self.point_of_contact,
515
+ )
516
+ card_metadata.to_dataset_card_data(card_data)
517
+ card = DatasetCard.from_template(
518
+ card_data,
519
+ pretty_name=card_data.pretty_name,
520
+ )
521
+ card.push_to_hub(repo_id, repo_type="dataset")
testbed/EleutherAI__lm-evaluation-harness/lm_eval/loggers/utils.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import os
3
+ import re
4
+ import subprocess
5
+ from pathlib import Path
6
+ from typing import Any, Dict, Optional, Tuple, Union
7
+
8
+ import numpy as np
9
+ from torch.utils.collect_env import get_pretty_env_info
10
+ from transformers import __version__ as trans_version
11
+
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+
16
+ def remove_none_pattern(input_string: str) -> Tuple[str, bool]:
17
+ """Remove the ',none' substring from the input_string if it exists at the end.
18
+
19
+ Args:
20
+ input_string (str): The input string from which to remove the ',none' substring.
21
+
22
+ Returns:
23
+ Tuple[str, bool]: A tuple containing the modified input_string with the ',none' substring removed
24
+ and a boolean indicating whether the modification was made (True) or not (False).
25
+ """
26
+ # Define the pattern to match ',none' at the end of the string
27
+ pattern = re.compile(r",none$")
28
+
29
+ # Use sub() to replace ',none' with an empty string
30
+ result = re.sub(pattern, "", input_string)
31
+
32
+ # check if the input_string changed
33
+ removed = result != input_string
34
+
35
+ return result, removed
36
+
37
+
38
+ def _handle_non_serializable(o: Any) -> Union[int, str, list]:
39
+ """Handle non-serializable objects by converting them to serializable types.
40
+
41
+ Args:
42
+ o (Any): The object to be handled.
43
+
44
+ Returns:
45
+ Union[int, str, list]: The converted object. If the object is of type np.int64 or np.int32,
46
+ it will be converted to int. If the object is of type set, it will be converted
47
+ to a list. Otherwise, it will be converted to str.
48
+ """
49
+ if isinstance(o, np.int64) or isinstance(o, np.int32):
50
+ return int(o)
51
+ elif isinstance(o, set):
52
+ return list(o)
53
+ else:
54
+ return str(o)
55
+
56
+
57
+ def get_commit_from_path(repo_path: Union[Path, str]) -> Optional[str]:
58
+ try:
59
+ git_folder = Path(repo_path, ".git")
60
+ if git_folder.is_file():
61
+ git_folder = Path(
62
+ git_folder.parent,
63
+ git_folder.read_text(encoding="utf-8").split("\n")[0].split(" ")[-1],
64
+ )
65
+ if Path(git_folder, "HEAD").exists():
66
+ head_name = (
67
+ Path(git_folder, "HEAD")
68
+ .read_text(encoding="utf-8")
69
+ .split("\n")[0]
70
+ .split(" ")[-1]
71
+ )
72
+ head_ref = Path(git_folder, head_name)
73
+ git_hash = head_ref.read_text(encoding="utf-8").replace("\n", "")
74
+ else:
75
+ git_hash = None
76
+ except Exception as err:
77
+ logger.debug(
78
+ f"Failed to retrieve a Git commit hash from path: {str(repo_path)}. Error: {err}"
79
+ )
80
+ return None
81
+ return git_hash
82
+
83
+
84
+ def get_git_commit_hash():
85
+ """
86
+ Gets the git commit hash of your current repo (if it exists).
87
+ Source: https://github.com/EleutherAI/gpt-neox/blob/b608043be541602170bfcfb8ec9bf85e8a0799e0/megatron/neox_arguments/neox_args.py#L42
88
+ """
89
+ try:
90
+ git_hash = subprocess.check_output(["git", "describe", "--always"]).strip()
91
+ git_hash = git_hash.decode()
92
+ except (subprocess.CalledProcessError, FileNotFoundError):
93
+ # FileNotFoundError occurs when git not installed on system
94
+ git_hash = get_commit_from_path(os.getcwd()) # git hash of repo if exists
95
+ return git_hash
96
+
97
+
98
+ def add_env_info(storage: Dict[str, Any]):
99
+ try:
100
+ pretty_env_info = get_pretty_env_info()
101
+ except Exception as err:
102
+ pretty_env_info = str(err)
103
+ transformers_version = trans_version
104
+ upper_dir_commit = get_commit_from_path(
105
+ Path(os.getcwd(), "..")
106
+ ) # git hash of upper repo if exists
107
+ added_info = {
108
+ "pretty_env_info": pretty_env_info,
109
+ "transformers_version": transformers_version,
110
+ "upper_git_hash": upper_dir_commit, # in case this repo is submodule
111
+ }
112
+ storage.update(added_info)
113
+
114
+
115
+ def add_tokenizer_info(storage: Dict[str, Any], lm):
116
+ if getattr(lm, "tokenizer", False):
117
+ try:
118
+ tokenizer_info = {
119
+ "tokenizer_pad_token": [
120
+ lm.tokenizer.pad_token,
121
+ str(lm.tokenizer.pad_token_id),
122
+ ],
123
+ "tokenizer_eos_token": [
124
+ lm.tokenizer.eos_token,
125
+ str(lm.tokenizer.eos_token_id),
126
+ ],
127
+ "tokenizer_bos_token": [
128
+ lm.tokenizer.bos_token,
129
+ str(lm.tokenizer.bos_token_id),
130
+ ],
131
+ "eot_token_id": getattr(lm, "eot_token_id", None),
132
+ "max_length": getattr(lm, "max_length", None),
133
+ }
134
+ storage.update(tokenizer_info)
135
+ except Exception as err:
136
+ logger.debug(
137
+ f"Logging detailed tokenizer info failed with {err}, skipping..."
138
+ )
139
+ # seems gguf and textsynth do not have tokenizer
140
+ else:
141
+ logger.debug(
142
+ "LM does not have a 'tokenizer' attribute, not logging tokenizer metadata to results."
143
+ )
testbed/EleutherAI__lm-evaluation-harness/lm_eval/loggers/wandb_logger.py ADDED
@@ -0,0 +1,352 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+ import json
3
+ import logging
4
+ from typing import Any, Dict, List, Literal, Tuple
5
+
6
+ import numpy as np
7
+ import pandas as pd
8
+ from packaging.version import Version
9
+
10
+ from lm_eval.loggers.utils import _handle_non_serializable, remove_none_pattern
11
+
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+
16
+ def get_wandb_printer() -> Literal["Printer"]:
17
+ """Returns a wandb printer instance for pretty stdout."""
18
+ from wandb.sdk.lib.printer import get_printer
19
+ from wandb.sdk.wandb_settings import Settings
20
+
21
+ printer = get_printer(Settings()._jupyter)
22
+ return printer
23
+
24
+
25
+ class WandbLogger:
26
+ def __init__(self, **kwargs) -> None:
27
+ """Attaches to wandb logger if already initialized. Otherwise, passes kwargs to wandb.init()
28
+
29
+ Args:
30
+ kwargs Optional[Any]: Arguments for configuration.
31
+
32
+ Parse and log the results returned from evaluator.simple_evaluate() with:
33
+ wandb_logger.post_init(results)
34
+ wandb_logger.log_eval_result()
35
+ wandb_logger.log_eval_samples(results["samples"])
36
+ """
37
+ try:
38
+ import wandb
39
+
40
+ assert Version(wandb.__version__) >= Version("0.13.6")
41
+ if Version(wandb.__version__) < Version("0.13.6"):
42
+ wandb.require("report-editing:v0")
43
+ except Exception as e:
44
+ logger.warning(
45
+ "To use the wandb reporting functionality please install wandb>=0.13.6.\n"
46
+ "To install the latest version of wandb run `pip install wandb --upgrade`\n"
47
+ f"{e}"
48
+ )
49
+
50
+ self.wandb_args: Dict[str, Any] = kwargs
51
+
52
+ # initialize a W&B run
53
+ if wandb.run is None:
54
+ self.run = wandb.init(**self.wandb_args)
55
+ else:
56
+ self.run = wandb.run
57
+
58
+ self.printer = get_wandb_printer()
59
+
60
+ def post_init(self, results: Dict[str, Any]) -> None:
61
+ self.results: Dict[str, Any] = copy.deepcopy(results)
62
+ self.task_names: List[str] = list(results.get("results", {}).keys())
63
+ self.group_names: List[str] = list(results.get("groups", {}).keys())
64
+
65
+ def _get_config(self) -> Dict[str, Any]:
66
+ """Get configuration parameters."""
67
+ self.task_configs = self.results.get("configs", {})
68
+ cli_configs = self.results.get("config", {})
69
+ configs = {
70
+ "task_configs": self.task_configs,
71
+ "cli_configs": cli_configs,
72
+ }
73
+
74
+ return configs
75
+
76
+ def _sanitize_results_dict(self) -> Tuple[Dict[str, str], Dict[str, Any]]:
77
+ """Sanitize the results dictionary."""
78
+ _results = copy.deepcopy(self.results.get("results", dict()))
79
+
80
+ # Remove None from the metric string name
81
+ tmp_results = copy.deepcopy(_results)
82
+ for task_name in self.task_names:
83
+ task_result = tmp_results.get(task_name, dict())
84
+ for metric_name, metric_value in task_result.items():
85
+ _metric_name, removed = remove_none_pattern(metric_name)
86
+ if removed:
87
+ _results[task_name][_metric_name] = metric_value
88
+ _results[task_name].pop(metric_name)
89
+
90
+ # remove string valued keys from the results dict
91
+ wandb_summary = {}
92
+ for task in self.task_names:
93
+ task_result = _results.get(task, dict())
94
+ for metric_name, metric_value in task_result.items():
95
+ if isinstance(metric_value, str):
96
+ wandb_summary[f"{task}/{metric_name}"] = metric_value
97
+
98
+ for summary_metric, summary_value in wandb_summary.items():
99
+ _task, _summary_metric = summary_metric.split("/")
100
+ _results[_task].pop(_summary_metric)
101
+
102
+ tmp_results = copy.deepcopy(_results)
103
+ for task_name, task_results in tmp_results.items():
104
+ for metric_name, metric_value in task_results.items():
105
+ _results[f"{task_name}/{metric_name}"] = metric_value
106
+ _results[task_name].pop(metric_name)
107
+ for task in self.task_names:
108
+ _results.pop(task)
109
+
110
+ return wandb_summary, _results
111
+
112
+ def _log_results_as_table(self) -> None:
113
+ """Generate and log evaluation results as a table to W&B."""
114
+ columns = [
115
+ "Version",
116
+ "Filter",
117
+ "num_fewshot",
118
+ "Metric",
119
+ "Value",
120
+ "Stderr",
121
+ ]
122
+
123
+ def make_table(columns: List[str], key: str = "results"):
124
+ import wandb
125
+
126
+ table = wandb.Table(columns=columns)
127
+ results = copy.deepcopy(self.results)
128
+
129
+ for k, dic in results.get(key).items():
130
+ if k in self.group_names and not key == "groups":
131
+ continue
132
+ version = results.get("versions").get(k)
133
+ if version == "N/A":
134
+ version = None
135
+ n = results.get("n-shot").get(k)
136
+
137
+ for (mf), v in dic.items():
138
+ m, _, f = mf.partition(",")
139
+ if m.endswith("_stderr"):
140
+ continue
141
+ if m == "alias":
142
+ continue
143
+
144
+ if m + "_stderr" + "," + f in dic:
145
+ se = dic[m + "_stderr" + "," + f]
146
+ if se != "N/A":
147
+ se = "%.4f" % se
148
+ table.add_data(*[k, version, f, n, m, str(v), str(se)])
149
+ else:
150
+ table.add_data(*[k, version, f, n, m, str(v), ""])
151
+
152
+ return table
153
+
154
+ # log the complete eval result to W&B Table
155
+ table = make_table(["Tasks"] + columns, "results")
156
+ self.run.log({"evaluation/eval_results": table})
157
+
158
+ if "groups" in self.results.keys():
159
+ table = make_table(["Groups"] + columns, "groups")
160
+ self.run.log({"evaluation/group_eval_results": table})
161
+
162
+ def _log_results_as_artifact(self) -> None:
163
+ """Log results as JSON artifact to W&B."""
164
+ import wandb
165
+
166
+ dumped = json.dumps(
167
+ self.results, indent=2, default=_handle_non_serializable, ensure_ascii=False
168
+ )
169
+ artifact = wandb.Artifact("results", type="eval_results")
170
+ with artifact.new_file("results.json", mode="w", encoding="utf-8") as f:
171
+ f.write(dumped)
172
+ self.run.log_artifact(artifact)
173
+
174
+ def log_eval_result(self) -> None:
175
+ """Log evaluation results to W&B."""
176
+ # Log configs to wandb
177
+ configs = self._get_config()
178
+ self.run.config.update(configs)
179
+
180
+ wandb_summary, self.wandb_results = self._sanitize_results_dict()
181
+ # update wandb.run.summary with items that were removed
182
+ self.run.summary.update(wandb_summary)
183
+ # Log the evaluation metrics to wandb
184
+ self.run.log(self.wandb_results)
185
+ # Log the evaluation metrics as W&B Table
186
+ self._log_results_as_table()
187
+ # Log the results dict as json to W&B Artifacts
188
+ self._log_results_as_artifact()
189
+
190
+ def _generate_dataset(
191
+ self, data: List[Dict[str, Any]], config: Dict[str, Any]
192
+ ) -> pd.DataFrame:
193
+ """Generate a dataset from evaluation data.
194
+
195
+ Args:
196
+ data (List[Dict[str, Any]]): The data to generate a dataset for.
197
+ config (Dict[str, Any]): The configuration of the task.
198
+
199
+ Returns:
200
+ pd.DataFrame: A dataframe that is ready to be uploaded to W&B.
201
+ """
202
+ ids = [x["doc_id"] for x in data]
203
+ labels = [x["target"] for x in data]
204
+ instance = [""] * len(ids)
205
+ resps = [""] * len(ids)
206
+ filtered_resps = [""] * len(ids)
207
+ model_outputs = {}
208
+
209
+ metrics_list = config["metric_list"]
210
+ metrics = {}
211
+ for metric in metrics_list:
212
+ metric = metric.get("metric")
213
+ if metric in ["word_perplexity", "byte_perplexity", "bits_per_byte"]:
214
+ metrics[f"{metric}_loglikelihood"] = [x[metric][0] for x in data]
215
+ if metric in ["byte_perplexity", "bits_per_byte"]:
216
+ metrics[f"{metric}_bytes"] = [x[metric][1] for x in data]
217
+ else:
218
+ metrics[f"{metric}_words"] = [x[metric][1] for x in data]
219
+ else:
220
+ metrics[metric] = [x[metric] for x in data]
221
+
222
+ if config["output_type"] == "loglikelihood":
223
+ instance = [x["arguments"][0][0] for x in data]
224
+ labels = [x["arguments"][0][1] for x in data]
225
+ resps = [
226
+ f'log probability of continuation is {x["resps"][0][0][0]} '
227
+ + "\n\n"
228
+ + "continuation will {} generated with greedy sampling".format(
229
+ "not be" if not x["resps"][0][0][1] else "be"
230
+ )
231
+ for x in data
232
+ ]
233
+ filtered_resps = [
234
+ f'log probability of continuation is {x["filtered_resps"][0][0]} '
235
+ + "\n\n"
236
+ + "continuation will {} generated with greedy sampling".format(
237
+ "not be" if not x["filtered_resps"][0][1] else "be"
238
+ )
239
+ for x in data
240
+ ]
241
+ elif config["output_type"] == "multiple_choice":
242
+ instance = [x["arguments"][0][0] for x in data]
243
+ choices = [
244
+ "\n".join([f"{idx}. {y[1]}" for idx, y in enumerate(x["arguments"])])
245
+ for x in data
246
+ ]
247
+ resps = [np.argmax([n[0][0] for n in x["resps"]]) for x in data]
248
+ filtered_resps = [
249
+ np.argmax([n[0] for n in x["filtered_resps"]]) for x in data
250
+ ]
251
+ elif config["output_type"] == "loglikelihood_rolling":
252
+ instance = [x["arguments"][0][0] for x in data]
253
+ resps = [x["resps"][0][0] for x in data]
254
+ filtered_resps = [x["filtered_resps"][0] for x in data]
255
+ elif config["output_type"] == "generate_until":
256
+ instance = [x["arguments"][0][0] for x in data]
257
+ resps = [x["resps"][0][0] for x in data]
258
+ filtered_resps = [x["filtered_resps"][0] for x in data]
259
+
260
+ model_outputs["raw_predictions"] = resps
261
+ model_outputs["filtered_predictions"] = filtered_resps
262
+
263
+ df_data = {
264
+ "id": ids,
265
+ "data": instance,
266
+ }
267
+ if config["output_type"] == "multiple_choice":
268
+ df_data["choices"] = choices
269
+
270
+ tmp_data = {
271
+ "input_len": [len(x) for x in instance],
272
+ "labels": labels,
273
+ "output_type": config["output_type"],
274
+ }
275
+ df_data.update(tmp_data)
276
+ df_data.update(model_outputs)
277
+ df_data.update(metrics)
278
+
279
+ return pd.DataFrame(df_data)
280
+
281
+ def _log_samples_as_artifact(
282
+ self, data: List[Dict[str, Any]], task_name: str
283
+ ) -> None:
284
+ import wandb
285
+
286
+ # log the samples as an artifact
287
+ dumped = json.dumps(
288
+ data,
289
+ indent=2,
290
+ default=_handle_non_serializable,
291
+ ensure_ascii=False,
292
+ )
293
+ artifact = wandb.Artifact(f"{task_name}", type="samples_by_task")
294
+ with artifact.new_file(
295
+ f"{task_name}_eval_samples.json", mode="w", encoding="utf-8"
296
+ ) as f:
297
+ f.write(dumped)
298
+ self.run.log_artifact(artifact)
299
+ # artifact.wait()
300
+
301
+ def log_eval_samples(self, samples: Dict[str, List[Dict[str, Any]]]) -> None:
302
+ """Log evaluation samples to W&B.
303
+
304
+ Args:
305
+ samples (Dict[str, List[Dict[str, Any]]]): Evaluation samples for each task.
306
+ """
307
+ task_names: List[str] = [
308
+ x for x in self.task_names if x not in self.group_names
309
+ ]
310
+
311
+ ungrouped_tasks = []
312
+ tasks_by_groups = {}
313
+
314
+ for task_name in task_names:
315
+ group_names = self.task_configs[task_name].get("group", None)
316
+ if group_names:
317
+ if isinstance(group_names, str):
318
+ group_names = [group_names]
319
+
320
+ for group_name in group_names:
321
+ if not tasks_by_groups.get(group_name):
322
+ tasks_by_groups[group_name] = [task_name]
323
+ else:
324
+ tasks_by_groups[group_name].append(task_name)
325
+ else:
326
+ ungrouped_tasks.append(task_name)
327
+
328
+ for task_name in ungrouped_tasks:
329
+ eval_preds = samples[task_name]
330
+
331
+ # log the samples as a W&B Table
332
+ df = self._generate_dataset(eval_preds, self.task_configs.get(task_name))
333
+ self.run.log({f"{task_name}_eval_results": df})
334
+
335
+ # log the samples as a json file as W&B Artifact
336
+ self._log_samples_as_artifact(eval_preds, task_name)
337
+
338
+ for group, grouped_tasks in tasks_by_groups.items():
339
+ grouped_df = pd.DataFrame()
340
+ for task_name in grouped_tasks:
341
+ eval_preds = samples[task_name]
342
+ df = self._generate_dataset(
343
+ eval_preds, self.task_configs.get(task_name)
344
+ )
345
+ df["group"] = group
346
+ df["task"] = task_name
347
+ grouped_df = pd.concat([grouped_df, df], ignore_index=True)
348
+
349
+ # log the samples as a json file as W&B Artifact
350
+ self._log_samples_as_artifact(eval_preds, task_name)
351
+
352
+ self.run.log({f"{group}_eval_results": grouped_df})
testbed/EleutherAI__lm-evaluation-harness/lm_eval/tasks/README.md ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ # Tasks
3
+
4
+ A list of supported tasks and task groupings can be viewed with `lm-eval --tasks list`.
5
+
6
+ For more information, including a full list of task names and their precise meanings or sources, follow the links provided to the individual README.md files for each subfolder.
7
+
8
+ | Task Family | Description | Language(s) |
9
+ |-------------|-------------|-------------|
10
+ | [aclue](aclue/README.md) | Tasks focusing on ancient Chinese language understanding and cultural aspects. | Ancient Chinese |
11
+ | [aexams](aexams/README.md) | Tasks in Arabic related to various academic exams covering a range of subjects. | Arabic |
12
+ | [agieval](agieval/README.md) | Tasks involving historical data or questions related to history and historical texts. | English, Chinese |
13
+ | [anli](anli/README.md) | Adversarial natural language inference tasks designed to test model robustness. | English |
14
+ | [arabic_leaderboard_complete](arabic_leaderboard_complete/README.md) | A full version of the tasks in the Open Arabic LLM Leaderboard, focusing on the evaluation of models that reflect the characteristics of Arabic language understanding and comprehension, culture, and heritage. Note that some of these tasks are machine-translated. | Arabic (Some MT) |
15
+ | [arabic_leaderboard_light](arabic_leaderboard_light/README.md) | A light version of the tasks in the Open Arabic LLM Leaderboard (i.e., 10% samples of the test set in the original benchmarks), focusing on the evaluation of models that reflect the characteristics of Arabic language understanding and comprehension, culture, and heritage. Note that some of these tasks are machine-translated. | Arabic (Some MT) |
16
+ | [arabicmmlu](arabicmmlu/README.md) | Localized Arabic version of MMLU with multiple-choice questions from 40 subjects. | Arabic |
17
+ | [arc](arc/README.md) | Tasks involving complex reasoning over a diverse set of questions. | English |
18
+ | [arithmetic](arithmetic/README.md) | Tasks involving numerical computations and arithmetic reasoning. | English |
19
+ | [asdiv](asdiv/README.md) | Tasks involving arithmetic and mathematical reasoning challenges. | English |
20
+ | [babi](babi/README.md) | Tasks designed as question and answering challenges based on simulated stories. | English |
21
+ | [basqueglue](basqueglue/README.md) | Tasks designed to evaluate language understanding in Basque language. | Basque |
22
+ | [bbh](bbh/README.md) | Tasks focused on deep semantic understanding through hypothesization and reasoning. | English, German |
23
+ | [belebele](belebele/README.md) | Language understanding tasks in a variety of languages and scripts. | Multiple (122 languages) |
24
+ | benchmarks | General benchmarking tasks that test a wide range of language understanding capabilities. | |
25
+ | [bertaqa](bertaqa/README.md) | Local Basque cultural trivia QA tests in English and Basque languages. | English, Basque, Basque (MT) |
26
+ | [bigbench](bigbench/README.md) | Broad tasks from the BIG-bench benchmark designed to push the boundaries of large models. | Multiple |
27
+ | [blimp](blimp/README.md) | Tasks testing grammatical phenomena to evaluate language model's linguistic capabilities. | English |
28
+ | [ceval](ceval/README.md) | Tasks that evaluate language understanding and reasoning in an educational context. | Chinese |
29
+ | [cmmlu](cmmlu/README.md) | Multi-subject multiple choice question tasks for comprehensive academic assessment. | Chinese |
30
+ | code_x_glue | Tasks that involve understanding and generating code across multiple programming languages. | Go, Java, JS, PHP, Python, Ruby |
31
+ | [commonsense_qa](commonsense_qa/README.md) | CommonsenseQA, a multiple-choice QA dataset for measuring commonsense knowledge. | English |
32
+ | [copal_id](copal_id/README.md) | Indonesian causal commonsense reasoning dataset that captures local nuances. | Indonesian |
33
+ | [coqa](coqa/README.md) | Conversational question answering tasks to test dialog understanding. | English |
34
+ | [crows_pairs](crows_pairs/README.md) | Tasks designed to test model biases in various sociodemographic groups. | English, French |
35
+ | csatqa | Tasks related to SAT and other standardized testing questions for academic assessment. | Korean |
36
+ | [drop](drop/README.md) | Tasks requiring numerical reasoning, reading comprehension, and question answering. | English |
37
+ | [eq_bench](eq_bench/README.md) | Tasks focused on equality and ethics in question answering and decision-making. | English |
38
+ | [eus_exams](eus_exams/README.md) | Tasks based on various professional and academic exams in the Basque language. | Basque |
39
+ | [eus_proficiency](eus_proficiency/README.md) | Tasks designed to test proficiency in the Basque language across various topics. | Basque |
40
+ | [eus_reading](eus_reading/README.md) | Reading comprehension tasks specifically designed for the Basque language. | Basque |
41
+ | [eus_trivia](eus_trivia/README.md) | Trivia and knowledge testing tasks in the Basque language. | Basque |
42
+ | [fda](fda/README.md) | Tasks for extracting key-value pairs from FDA documents to test information extraction. | English |
43
+ | [fld](fld/README.md) | Tasks involving free-form and directed dialogue understanding. | English |
44
+ | [french_bench](french_bench/README.md) | Set of tasks designed to assess language model performance in French. | French|
45
+ | [glue](glue/README.md) | General Language Understanding Evaluation benchmark to test broad language abilities. | English |
46
+ | [gpqa](gpqa/README.md) | Tasks designed for general public question answering and knowledge verification. | English |
47
+ | [gsm8k](gsm8k/README.md) | A benchmark of grade school math problems aimed at evaluating reasoning capabilities. | English |
48
+ | [haerae](haerae/README.md) | Tasks focused on assessing detailed factual and historical knowledge. | Korean |
49
+ | [headqa](headqa/README.md) | A high-level education-based question answering dataset to test specialized knowledge. | Spanish, English |
50
+ | [hellaswag](hellaswag/README.md) | Tasks to predict the ending of stories or scenarios, testing comprehension and creativity. | English |
51
+ | [hendrycks_ethics](hendrycks_ethics/README.md) | Tasks designed to evaluate the ethical reasoning capabilities of models. | English |
52
+ | [hendrycks_math](hendrycks_math/README.md) | Mathematical problem-solving tasks to test numerical reasoning and problem-solving. | English |
53
+ | [ifeval](ifeval/README.md) | Interactive fiction evaluation tasks for narrative understanding and reasoning. | English |
54
+ | [inverse_scaling](inverse_scaling/README.md) | Multiple-choice tasks from the Inverse Scaling Prize, designed to find settings where larger language models perform worse. | English |
55
+ | [kmmlu](kmmlu/README.md) | Knowledge-based multi-subject multiple choice questions for academic evaluation. | Korean |
56
+ | [kobest](kobest/README.md) | A collection of tasks designed to evaluate understanding in Korean language. | Korean |
57
+ | [kormedmcqa](kormedmcqa/README.md) | Medical question answering tasks in Korean to test specialized domain knowledge. | Korean |
58
+ | [lambada](lambada/README.md) | Tasks designed to predict the endings of text passages, testing language prediction skills. | English |
59
+ | [lambada_cloze](lambada_cloze/README.md) | Cloze-style LAMBADA dataset. | English |
60
+ | [lambada_multilingual](lambada_multilingual/README.md) | Multilingual LAMBADA dataset. This is a legacy version of the multilingual dataset, and users should instead use `lambada_multilingual_stablelm`. | German, English, Spanish, French, Italian |
61
+ | [lambada_multilingual_stablelm](lambada_multilingual_stablelm/README.md) | Multilingual LAMBADA dataset. Users should prefer evaluating on this version of the multilingual dataset instead of on `lambada_multilingual`. | German, English, Spanish, French, Italian, Dutch, Portuguese |
62
+ | [leaderboard](leaderboard/README.md) | Task group used by Hugging Face's [Open LLM Leaderboard v2](https://huggingface.co/spaces/open-llm-leaderboard/open_llm_leaderboard). Those tasks are static and will not change through time | English |
63
+ | [lingoly](lingoly/README.md) | Challenging logical reasoning benchmark in low-resource languages with controls for memorization | English, Multilingual |
64
+ | [logiqa](logiqa/README.md) | Logical reasoning tasks requiring advanced inference and deduction. | English, Chinese |
65
+ | [logiqa2](logiqa2/README.md) | Large-scale logical reasoning dataset adapted from the Chinese Civil Service Examination. | English, Chinese |
66
+ | [mathqa](mathqa/README.md) | Question answering tasks involving mathematical reasoning and problem-solving. | English |
67
+ | [mc_taco](mc_taco/README.md) | Question-answer pairs that require temporal commonsense comprehension. | English |
68
+ | [med_concepts_qa](med_concepts_qa/README.md) | Benchmark for evaluating LLMs on their abilities to interpret medical codes and distinguish between medical concept. | English |
69
+ | medmcqa | Medical multiple choice questions assessing detailed medical knowledge. | English |
70
+ | medqa | Multiple choice question answering based on the United States Medical License Exams. | |
71
+ | [mgsm](mgsm/README.md) | Benchmark of multilingual grade-school math problems. | Spanish, French, German, Russian, Chinese, Japanese, Thai, Swahili, Bengali, Telugu |
72
+ | [minerva_math](minerva_math/README.md) | Mathematics-focused tasks requiring numerical reasoning and problem-solving skills. | English |
73
+ | mmlu | Massive Multitask Language Understanding benchmark for broad domain language evaluation. Several variants are supported. | English |
74
+ | [mmlusr](mmlusr/README.md) | Variation of MMLU designed to be more rigorous. | English |
75
+ | model_written_evals | Evaluation tasks auto-generated for evaluating a collection of AI Safety concerns. | |
76
+ | [mutual](mutual/README.md) | A retrieval-based dataset for multi-turn dialogue reasoning. | English |
77
+ | [nq_open](nq_open/README.md) | Open domain question answering tasks based on the Natural Questions dataset. | English |
78
+ | [okapi/arc_multilingual](okapi/arc_multilingual/README.md) | Tasks that involve reading comprehension and information retrieval challenges. | Multiple (31 languages) **Machine Translated.** |
79
+ | [okapi/hellaswag_multilingual](okapi/hellaswag_multilingual/README.md) | Tasks that involve reading comprehension and information retrieval challenges. | Multiple (30 languages) **Machine Translated.** |
80
+ | okapi/mmlu_multilingual | Tasks that involve reading comprehension and information retrieval challenges. | Multiple (34 languages) **Machine Translated.** |
81
+ | [okapi/truthfulqa_multilingual](okapi/truthfulqa_multilingual/README.md) | Tasks that involve reading comprehension and information retrieval challenges. | Multiple (31 languages) **Machine Translated.** |
82
+ | [openbookqa](openbookqa/README.md) | Open-book question answering tasks that require external knowledge and reasoning. | English |
83
+ | [paloma](paloma/README.md) | Paloma is a comprehensive benchmark designed to evaluate open language models across a wide range of domains, ranging from niche artist communities to mental health forums on Reddit. | English |
84
+ | [paws-x](paws-x/README.md) | Paraphrase Adversaries from Word Scrambling, focusing on cross-lingual capabilities. | English, French, Spanish, German, Chinese, Japanese, Korean |
85
+ | [pile](pile/README.md) | Open source language modelling data set that consists of 22 smaller, high-quality datasets. | English |
86
+ | [pile_10k](pile_10k/README.md) | The first 10K elements of The Pile, useful for debugging models trained on it. | English |
87
+ | [piqa](piqa/README.md) | Physical Interaction Question Answering tasks to test physical commonsense reasoning. | English |
88
+ | [polemo2](polemo2/README.md) | Sentiment analysis and emotion detection tasks based on Polish language data. | Polish |
89
+ | [prost](prost/README.md) | Tasks requiring understanding of professional standards and ethics in various domains. | English |
90
+ | [pubmedqa](pubmedqa/README.md) | Question answering tasks based on PubMed research articles for biomedical understanding. | English |
91
+ | [qa4mre](qa4mre/README.md) | Question Answering for Machine Reading Evaluation, assessing comprehension and reasoning. | English |
92
+ | [qasper](qasper/README.md) | Question Answering dataset based on academic papers, testing in-depth scientific knowledge. | English |
93
+ | [race](race/README.md) | Reading comprehension assessment tasks based on English exams in China. | English |
94
+ | realtoxicityprompts | Tasks to evaluate language models for generating text with potential toxicity. | |
95
+ | [sciq](sciq/README.md) | Science Question Answering tasks to assess understanding of scientific concepts. | English |
96
+ | [scrolls](scrolls/README.md) | Tasks that involve long-form reading comprehension across various domains. | English |
97
+ | [siqa](siqa/README.md) | Social Interaction Question Answering to evaluate common sense and social reasoning. | English |
98
+ | [squad_completion](squad_completion/README.md) | A variant of the SQuAD question answering task designed for zero-shot evaluation of small LMs. | English |
99
+ | [squadv2](squadv2/README.md) | Stanford Question Answering Dataset version 2, a reading comprehension benchmark. | English |
100
+ | [storycloze](storycloze/README.md) | Tasks to predict story endings, focusing on narrative logic and coherence. | English |
101
+ | [super_glue](super_glue/README.md) | A suite of challenging tasks designed to test a range of language understanding skills. | English |
102
+ | [swag](swag/README.md) | Situations With Adversarial Generations, predicting the next event in videos. | English |
103
+ | [swde](swde/README.md) | Information extraction tasks from semi-structured web pages. | English |
104
+ | [tinyBenchmarks](tinyBenchmarks/README.md) | Evaluation of large language models with fewer examples using tiny versions of popular benchmarks. | English |
105
+ | [tmmluplus](tmmluplus/README.md) | An extended set of tasks under the TMMLU framework for broader academic assessments. | Traditional Chinese |
106
+ | [toxigen](toxigen/README.md) | Tasks designed to evaluate language models on their propensity to generate toxic content. | English |
107
+ | [translation](translation/README.md) | Tasks focused on evaluating the language translation capabilities of models. | Arabic, English, Spanish, Basque, Hindi, Indonesian, Burmese, Russian, Swahili, Telugu, Chinese |
108
+ | [triviaqa](triviaqa/README.md) | A large-scale dataset for trivia question answering to test general knowledge. | English |
109
+ | [truthfulqa](truthfulqa/README.md) | A QA task aimed at evaluating the truthfulness and factual accuracy of model responses. | English |
110
+ | [unitxt](unitxt/README.md) | A number of tasks implemented using the unitxt library for flexible, shareable, and reusable data preparation and evaluation for generative AI. | English |
111
+ | [unscramble](unscramble/README.md) | Tasks involving the rearrangement of scrambled sentences to test syntactic understanding. | English |
112
+ | [webqs](webqs/README.md) | Web-based question answering tasks designed to evaluate internet search and retrieval. | English |
113
+ | [wikitext](wikitext/README.md) | Tasks based on text from Wikipedia articles to assess language modeling and generation. | English |
114
+ | [winogrande](winogrande/README.md) | A large-scale dataset for coreference resolution, inspired by the Winograd Schema Challenge. | English |
115
+ | [wmdp](wmdp/README.md) | A benchmark with the objective of minimizing performance, based on potentially-sensitive multiple-choice knowledge questions. | English |
116
+ | [wmt2016](wmt2016/README.md) | Tasks from the WMT 2016 shared task, focusing on translation between multiple languages. | English, Czech, German, Finnish, Russian, Romanian, Turkish |
117
+ | [wsc273](wsc273/README.md) | The Winograd Schema Challenge, a test of commonsense reasoning and coreference resolution. | English |
118
+ | [xcopa](xcopa/README.md) | Cross-lingual Choice of Plausible Alternatives, testing reasoning in multiple languages. | Estonian, Haitian, Indonesian, Italian, Quechua, Swahili, Tamil, Thai, Turkish, Vietnamese, Chinese |
119
+ | [xnli](xnli/README.md) | Cross-Lingual Natural Language Inference to test understanding across different languages. | Arabic, Bulgarian, German, Greek, English, Spanish, French, Hindi, Russian, Swahili, Thai, Turkish, Urdu, Vietnamese, Chinese |
120
+ | [xnli_eu](xnli_eu/README.md) | Cross-lingual Natural Language Inference tasks in Basque. | Basque |
121
+ | [xstorycloze](xstorycloze/README.md) | Cross-lingual narrative understanding tasks to predict story endings in multiple languages. | Russian, Simplified Chinese, Spanish, Arabic, Hindi, Indonesian, Telugu, Swahili, Basque, Burmese |
122
+ | [xwinograd](xwinograd/README.md) | Cross-lingual Winograd schema tasks for coreference resolution in multiple languages. | English, French, Japanese, Portuguese, Russian, Chinese |
testbed/EleutherAI__lm-evaluation-harness/lm_eval/tasks/__init__.py ADDED
@@ -0,0 +1,652 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import collections
2
+ import inspect
3
+ import logging
4
+ import os
5
+ from functools import partial
6
+ from typing import Dict, List, Mapping, Optional, Union
7
+
8
+ from lm_eval import utils
9
+ from lm_eval.api.group import ConfigurableGroup, GroupConfig
10
+ from lm_eval.api.task import ConfigurableTask, Task
11
+ from lm_eval.evaluator_utils import get_subtask_list
12
+
13
+
14
+ GROUP_ONLY_KEYS = list(GroupConfig().to_dict().keys())
15
+
16
+
17
+ class TaskManager:
18
+ """TaskManager indexes all tasks from the default `lm_eval/tasks/`
19
+ and an optional directory if provided.
20
+
21
+ """
22
+
23
+ def __init__(
24
+ self,
25
+ verbosity="INFO",
26
+ include_path: Optional[Union[str, List]] = None,
27
+ include_defaults: bool = True,
28
+ ) -> None:
29
+ self.verbosity = verbosity
30
+ self.include_path = include_path
31
+ self.logger = utils.eval_logger
32
+ self.logger.setLevel(getattr(logging, f"{verbosity}"))
33
+
34
+ self._task_index = self.initialize_tasks(
35
+ include_path=include_path, include_defaults=include_defaults
36
+ )
37
+ self._all_tasks = sorted(list(self._task_index.keys()))
38
+
39
+ self._all_groups = sorted(
40
+ [x for x in self._all_tasks if self._task_index[x]["type"] == "group"]
41
+ )
42
+ self._all_subtasks = sorted(
43
+ [x for x in self._all_tasks if self._task_index[x]["type"] == "task"]
44
+ )
45
+ self._all_tags = sorted(
46
+ [x for x in self._all_tasks if self._task_index[x]["type"] == "tag"]
47
+ )
48
+
49
+ self.task_group_map = collections.defaultdict(list)
50
+
51
+ def initialize_tasks(
52
+ self,
53
+ include_path: Optional[Union[str, List]] = None,
54
+ include_defaults: bool = True,
55
+ ):
56
+ """Creates a dictionary of tasks index.
57
+
58
+ :param include_path: Union[str, List] = None
59
+ An additional path to be searched for tasks recursively.
60
+ Can provide more than one such path as a list.
61
+ :param include_defaults: bool = True
62
+ If set to false, default tasks (those in lm_eval/tasks/) are not indexed.
63
+ :return
64
+ Dictionary of task names as key and task metadata
65
+ """
66
+ if include_defaults:
67
+ all_paths = [os.path.dirname(os.path.abspath(__file__)) + "/"]
68
+ else:
69
+ all_paths = []
70
+ if include_path is not None:
71
+ if isinstance(include_path, str):
72
+ include_path = [include_path]
73
+ all_paths.extend(include_path)
74
+
75
+ task_index = {}
76
+ for task_dir in all_paths:
77
+ tasks = self._get_task_and_group(task_dir)
78
+ task_index = {**tasks, **task_index}
79
+
80
+ return task_index
81
+
82
+ @property
83
+ def all_tasks(self):
84
+ return self._all_tasks
85
+
86
+ @property
87
+ def all_groups(self):
88
+ return self._all_groups
89
+
90
+ @property
91
+ def all_subtasks(self):
92
+ return self._all_subtasks
93
+
94
+ @property
95
+ def all_tags(self):
96
+ return self._all_tags
97
+
98
+ @property
99
+ def task_index(self):
100
+ return self._task_index
101
+
102
+ def list_all_tasks(
103
+ self, list_groups=True, list_tags=True, list_subtasks=True
104
+ ) -> str:
105
+ from pytablewriter import MarkdownTableWriter
106
+
107
+ def sanitize_path(path):
108
+ # don't print full path if we are within the lm_eval/tasks dir !
109
+ # if we aren't though, provide the full path.
110
+ if "lm_eval/tasks/" in path:
111
+ return "lm_eval/tasks/" + path.split("lm_eval/tasks/")[-1]
112
+ else:
113
+ return path
114
+
115
+ group_table = MarkdownTableWriter()
116
+ group_table.headers = ["Group", "Config Location"]
117
+ gt_values = []
118
+ for g in self.all_groups:
119
+ path = self.task_index[g]["yaml_path"]
120
+ if path == -1:
121
+ path = "---"
122
+ else:
123
+ path = sanitize_path(path)
124
+ gt_values.append([g, path])
125
+ group_table.value_matrix = gt_values
126
+
127
+ tag_table = MarkdownTableWriter()
128
+ tag_table.headers = ["Tag"]
129
+ tag_table.value_matrix = [[t] for t in self.all_tags]
130
+
131
+ subtask_table = MarkdownTableWriter()
132
+ subtask_table.headers = ["Task", "Config Location", "Output Type"]
133
+ st_values = []
134
+ for t in self.all_subtasks:
135
+ path = self.task_index[t]["yaml_path"]
136
+
137
+ output_type = ""
138
+
139
+ # read the yaml file to determine the output type
140
+ if path != -1:
141
+ config = utils.load_yaml_config(path, mode="simple")
142
+ if "output_type" in config:
143
+ output_type = config["output_type"]
144
+ elif (
145
+ "include" in config
146
+ ): # if no output type, check if there is an include with an output type
147
+ include_path = path.split("/")[:-1] + config["include"]
148
+ include_config = utils.load_yaml_config(include_path, mode="simple")
149
+ if "output_type" in include_config:
150
+ output_type = include_config["output_type"]
151
+
152
+ if path == -1:
153
+ path = "---"
154
+ else:
155
+ path = sanitize_path(path)
156
+ st_values.append([t, path, output_type])
157
+ subtask_table.value_matrix = st_values
158
+
159
+ result = "\n"
160
+ if list_groups:
161
+ result += group_table.dumps() + "\n\n"
162
+ if list_tags:
163
+ result += tag_table.dumps() + "\n\n"
164
+ if list_subtasks:
165
+ result += subtask_table.dumps() + "\n\n"
166
+ return result
167
+
168
+ def match_tasks(self, task_list):
169
+ return utils.pattern_match(task_list, self.all_tasks)
170
+
171
+ def _name_is_registered(self, name) -> bool:
172
+ if name in self.all_tasks:
173
+ return True
174
+ return False
175
+
176
+ def _name_is_task(self, name) -> bool:
177
+ if self._name_is_registered(name) and (self.task_index[name]["type"] == "task"):
178
+ return True
179
+ return False
180
+
181
+ def _name_is_tag(self, name) -> bool:
182
+ if self._name_is_registered(name) and (self.task_index[name]["type"] == "tag"):
183
+ return True
184
+ return False
185
+
186
+ def _name_is_group(self, name) -> bool:
187
+ if self._name_is_registered(name) and (
188
+ self.task_index[name]["type"] == "group"
189
+ ):
190
+ return True
191
+ return False
192
+
193
+ def _name_is_python_task(self, name):
194
+ if self._name_is_registered(name) and (
195
+ self.task_index[name]["type"] == "python_task"
196
+ ):
197
+ return True
198
+ return False
199
+
200
+ def _config_is_task(self, config) -> bool:
201
+ if ("task" in config) and isinstance(config["task"], str):
202
+ return True
203
+ return False
204
+
205
+ def _config_is_group(self, config) -> bool:
206
+ if ("task" in config) and isinstance(config["task"], list):
207
+ return True
208
+ return False
209
+
210
+ def _config_is_python_task(self, config) -> bool:
211
+ if "class" in config:
212
+ return True
213
+ return False
214
+
215
+ def _get_yaml_path(self, name):
216
+ if name not in self.task_index:
217
+ raise ValueError
218
+ return self.task_index[name]["yaml_path"]
219
+
220
+ def _get_config(self, name):
221
+ if name not in self.task_index:
222
+ raise ValueError
223
+ yaml_path = self._get_yaml_path(name)
224
+ if yaml_path == -1:
225
+ return {}
226
+ else:
227
+ return utils.load_yaml_config(yaml_path, mode="full")
228
+
229
+ def _get_tasklist(self, name):
230
+ if self._name_is_task(name):
231
+ raise ValueError
232
+ return self.task_index[name]["task"]
233
+
234
+ def _process_alias(self, config, group=None):
235
+ # If the group is not the same as the original
236
+ # group which the group alias was intended for,
237
+ # Set the group_alias to None instead.
238
+ if ("group_alias" in config) and ("group" in config) and group is not None:
239
+ if config["group"] != group:
240
+ config["group_alias"] = None
241
+ return config
242
+
243
+ def _class_has_config_in_constructor(self, cls):
244
+ constructor = getattr(cls, "__init__", None)
245
+ return (
246
+ "config" in inspect.signature(constructor).parameters
247
+ if constructor
248
+ else False
249
+ )
250
+
251
+ def _load_individual_task_or_group(
252
+ self,
253
+ name_or_config: Optional[Union[str, dict]] = None,
254
+ parent_name: Optional[str] = None,
255
+ update_config: Optional[dict] = None,
256
+ ) -> Mapping:
257
+ def _load_task(config, task):
258
+ if "include" in config:
259
+ config = {
260
+ **utils.load_yaml_config(
261
+ yaml_path=None,
262
+ yaml_config={"include": config.pop("include")},
263
+ mode="full",
264
+ ),
265
+ **config,
266
+ }
267
+ if self._config_is_python_task(config):
268
+ if self._class_has_config_in_constructor(config["class"]):
269
+ task_object = config["class"](config=config)
270
+ else:
271
+ task_object = config["class"]()
272
+ if isinstance(task_object, ConfigurableTask):
273
+ # very scuffed: set task name here. TODO: fixme?
274
+ task_object.config.task = config["task"]
275
+ else:
276
+ task_object = ConfigurableTask(config=config)
277
+
278
+ return {task: task_object}
279
+
280
+ def _get_group_and_subtask_from_config(config):
281
+ group_name = ConfigurableGroup(config=config)
282
+ subtask_list = []
283
+ for task in group_name.config["task"]:
284
+ if isinstance(task, str) and self._name_is_tag(task):
285
+ subtask_list.extend(self._get_tasklist(task))
286
+ else:
287
+ subtask_list.append(task)
288
+ return group_name, subtask_list
289
+
290
+ def _process_group_config(config, update_config=None):
291
+ if update_config is not None:
292
+ config = {**config, **update_config}
293
+ _update_config = {
294
+ k: v for k, v in config.items() if k not in GROUP_ONLY_KEYS
295
+ }
296
+ if not bool(_update_config):
297
+ _update_config = None
298
+
299
+ group_config = {k: v for k, v in config.items() if k in GROUP_ONLY_KEYS}
300
+ return group_config, _update_config
301
+
302
+ if isinstance(name_or_config, str):
303
+ if update_config is not None:
304
+ # Process name_or_config as a dict instead
305
+ name_or_config = {"task": name_or_config, **update_config}
306
+ elif self._name_is_task(name_or_config) or self._name_is_python_task(
307
+ name_or_config
308
+ ):
309
+ task_config = self._get_config(name_or_config)
310
+ return _load_task(task_config, task=name_or_config)
311
+ else:
312
+ subtask_list = self._get_tasklist(name_or_config)
313
+ if subtask_list == -1:
314
+ group_config = self._get_config(name_or_config)
315
+ group_config, update_config = _process_group_config(group_config)
316
+ group_name, subtask_list = _get_group_and_subtask_from_config(
317
+ group_config
318
+ )
319
+ else:
320
+ if self._name_is_tag(name_or_config):
321
+ fn = partial(
322
+ self._load_individual_task_or_group,
323
+ update_config=name_or_config
324
+ if isinstance(name_or_config, dict)
325
+ else None,
326
+ )
327
+ return dict(
328
+ collections.ChainMap(*map(fn, reversed(subtask_list)))
329
+ )
330
+ else:
331
+ group_name = ConfigurableGroup(
332
+ config={"group": name_or_config, "task": subtask_list}
333
+ )
334
+
335
+ if isinstance(name_or_config, dict):
336
+ if self._config_is_task(name_or_config):
337
+ name = name_or_config.pop("task")
338
+ if update_config is not None:
339
+ name_or_config = {**name_or_config, **update_config}
340
+ # If the name is registered as a group
341
+ if self._name_is_group(name):
342
+ group_config = self._get_config(name)
343
+
344
+ group_config, update_config = _process_group_config(
345
+ group_config, name_or_config
346
+ )
347
+ group_name, subtask_list = _get_group_and_subtask_from_config(
348
+ group_config
349
+ )
350
+ elif self._name_is_tag(name):
351
+ subtask_list = self._get_tasklist(name)
352
+ fn = partial(
353
+ self._load_individual_task_or_group,
354
+ update_config=name_or_config,
355
+ )
356
+ return dict(collections.ChainMap(*map(fn, reversed(subtask_list))))
357
+ else:
358
+ if self._name_is_registered(name):
359
+ base_task_config = self._get_config(name)
360
+
361
+ # Check if this is a duplicate.
362
+ if parent_name is not None:
363
+ num_duplicate = len(
364
+ list(
365
+ filter(
366
+ lambda x: x.startswith(name),
367
+ self.task_group_map[parent_name],
368
+ )
369
+ )
370
+ )
371
+ if num_duplicate > 0:
372
+ name = f"{name}-{num_duplicate}"
373
+ self.task_group_map[parent_name].append(name)
374
+
375
+ task_config = {
376
+ **base_task_config,
377
+ **name_or_config,
378
+ }
379
+ else:
380
+ task_config = name_or_config
381
+ return _load_task(task_config, task=name)
382
+ else:
383
+ group_config, update_config = _process_group_config(name_or_config)
384
+ group_name, subtask_list = _get_group_and_subtask_from_config(
385
+ group_config
386
+ )
387
+
388
+ fn = partial(
389
+ self._load_individual_task_or_group,
390
+ parent_name=group_name,
391
+ update_config=update_config,
392
+ )
393
+ return {
394
+ group_name: dict(collections.ChainMap(*map(fn, reversed(subtask_list))))
395
+ }
396
+
397
+ def load_task_or_group(self, task_list: Optional[Union[str, list]] = None) -> dict:
398
+ """Loads a dictionary of task objects from a list
399
+
400
+ :param task_list: Union[str, list] = None
401
+ Single string or list of string of task names to be loaded
402
+
403
+ :return
404
+ Dictionary of task objects
405
+ """
406
+ if isinstance(task_list, str):
407
+ task_list = [task_list]
408
+
409
+ all_loaded_tasks = dict(
410
+ collections.ChainMap(*map(self._load_individual_task_or_group, task_list))
411
+ )
412
+ return all_loaded_tasks
413
+
414
+ def load_config(self, config: Dict):
415
+ return self._load_individual_task_or_group(config)
416
+
417
+ def _get_task_and_group(self, task_dir: str):
418
+ """Creates a dictionary of tasks index with the following metadata,
419
+ - `type`, that can be either `task`, `python_task`, `group` or `tags`.
420
+ `task` refer to regular task configs, `python_task` are special
421
+ yaml files that only consists of `task` and `class` parameters.
422
+ `group` are group configs. `tags` are labels that can be assigned
423
+ to tasks to assist in sorting and calling tasks of certain themes.
424
+ - `yaml_path`, path to the yaml file. If the entry is a `group` that
425
+ was configured through a task config, the yaml_path will be -1
426
+ and all subtasks will be listed in `task` (see below)
427
+ - `task`, reserved for entries with `type` as `group`. This will list
428
+ all subtasks. When a group config is created (as opposed to task
429
+ config having `group` parameter set), this will be set to -1 to
430
+ avoid recursive indexing. The whole list of subtasks will be loaded
431
+ at evaluation.
432
+
433
+ :param task_dir: str
434
+ A directory to check for tasks
435
+
436
+ :return
437
+ Dictionary of task names as key and task metadata
438
+ """
439
+ # TODO: remove group in next release
440
+ print_info = True
441
+ ignore_dirs = [
442
+ "__pycache__",
443
+ ".ipynb_checkpoints",
444
+ ]
445
+ tasks_and_groups = collections.defaultdict()
446
+ for root, dirs, file_list in os.walk(task_dir):
447
+ dirs[:] = [d for d in dirs if d not in ignore_dirs]
448
+ for f in file_list:
449
+ if f.endswith(".yaml"):
450
+ yaml_path = os.path.join(root, f)
451
+ config = utils.load_yaml_config(yaml_path, mode="simple")
452
+ if self._config_is_python_task(config):
453
+ # This is a python class config
454
+ tasks_and_groups[config["task"]] = {
455
+ "type": "python_task",
456
+ "yaml_path": yaml_path,
457
+ }
458
+ elif self._config_is_group(config):
459
+ # This is a group config
460
+ tasks_and_groups[config["group"]] = {
461
+ "type": "group",
462
+ "task": -1, # This signals that
463
+ # we don't need to know
464
+ # the task list for indexing
465
+ # as it can be loaded
466
+ # when called.
467
+ "yaml_path": yaml_path,
468
+ }
469
+
470
+ # # Registered the level 1 tasks from a group config
471
+ # for config in config["task"]:
472
+ # if isinstance(config, dict) and self._config_is_task(config):
473
+ # task = config["task"]
474
+ # tasks_and_groups[task] = {
475
+ # "type": "task",
476
+ # "yaml_path": yaml_path,
477
+ # }
478
+
479
+ elif self._config_is_task(config):
480
+ # This is a task config
481
+ task = config["task"]
482
+ tasks_and_groups[task] = {
483
+ "type": "task",
484
+ "yaml_path": yaml_path,
485
+ }
486
+
487
+ # TODO: remove group in next release
488
+ for attr in ["tag", "group"]:
489
+ if attr in config:
490
+ if attr == "group" and print_info:
491
+ self.logger.info(
492
+ "`group` and `group_alias` keys in TaskConfigs are deprecated and will be removed in v0.4.5 of lm_eval. "
493
+ "The new `tag` field will be used to allow for a shortcut to a group of tasks one does not wish to aggregate metrics across. "
494
+ "`group`s which aggregate across subtasks must be only defined in a separate group config file, "
495
+ "which will be the official way to create groups that support cross-task aggregation as in `mmlu`. "
496
+ "Please see the v0.4.4 patch notes and our documentation: https://github.com/EleutherAI/lm-evaluation-harness/blob/main/docs/new_task_guide.md#advanced-group-configs "
497
+ "for more information."
498
+ )
499
+ print_info = False
500
+ # attr = "tag"
501
+
502
+ attr_list = config[attr]
503
+ if isinstance(attr_list, str):
504
+ attr_list = [attr_list]
505
+
506
+ for tag in attr_list:
507
+ if tag not in tasks_and_groups:
508
+ tasks_and_groups[tag] = {
509
+ "type": "tag",
510
+ "task": [task],
511
+ "yaml_path": -1,
512
+ }
513
+ elif tasks_and_groups[tag]["type"] != "tag":
514
+ self.logger.info(
515
+ f"The tag {tag} is already registered as a group, this tag will not be registered. "
516
+ "This may affect tasks you want to call."
517
+ )
518
+ break
519
+ else:
520
+ tasks_and_groups[tag]["task"].append(task)
521
+ else:
522
+ self.logger.debug(f"File {f} in {root} could not be loaded")
523
+
524
+ return tasks_and_groups
525
+
526
+
527
+ def get_task_name_from_config(task_config: Dict[str, str]) -> str:
528
+ if "task" in task_config:
529
+ return task_config["task"]
530
+ if "dataset_name" in task_config:
531
+ return "{dataset_path}_{dataset_name}".format(**task_config)
532
+ else:
533
+ return "{dataset_path}".format(**task_config)
534
+
535
+
536
+ def get_task_name_from_object(task_object):
537
+ if hasattr(task_object, "config"):
538
+ return task_object._config["task"]
539
+
540
+ # TODO: scrap this
541
+ # this gives a mechanism for non-registered tasks to have a custom name anyways when reporting
542
+ return (
543
+ task_object.EVAL_HARNESS_NAME
544
+ if hasattr(task_object, "EVAL_HARNESS_NAME")
545
+ else type(task_object).__name__
546
+ )
547
+
548
+
549
+ def _check_duplicates(task_dict: dict) -> List[str]:
550
+ """helper function solely used in validating get_task_dict output.
551
+ Takes the output of lm_eval.evaluator_utils.get_subtask_list and
552
+ returns a list of all leaf subtasks contained within, and errors if any such leaf subtasks are
553
+ "oversubscribed" to several disjoint groups.
554
+ """
555
+ subtask_names = []
556
+ for key, value in task_dict.items():
557
+ subtask_names.extend(value)
558
+
559
+ duplicate_tasks = {
560
+ task_name for task_name in subtask_names if subtask_names.count(task_name) > 1
561
+ }
562
+
563
+ # locate the potentially problematic groups that seem to 'compete' for constituent subtasks
564
+ competing_groups = [
565
+ group
566
+ for group in task_dict.keys()
567
+ if len(set(task_dict[group]).intersection(duplicate_tasks)) > 0
568
+ ]
569
+
570
+ if len(duplicate_tasks) > 0:
571
+ raise ValueError(
572
+ f"Found 1 or more tasks while trying to call get_task_dict() that were members of more than 1 called group: {list(duplicate_tasks)}. Offending groups: {competing_groups}. Please call groups which overlap their constituent tasks in separate evaluation runs."
573
+ )
574
+
575
+
576
+ def get_task_dict(
577
+ task_name_list: Union[str, List[Union[str, Dict, Task]]],
578
+ task_manager: Optional[TaskManager] = None,
579
+ ):
580
+ """Creates a dictionary of task objects from either a name of task, config, or prepared Task object.
581
+
582
+ :param task_name_list: List[Union[str, Dict, Task]]
583
+ Name of model or LM object, see lm_eval.models.get_model
584
+ :param task_manager: TaskManager = None
585
+ A TaskManager object that stores indexed tasks. If not set,
586
+ task_manager will load one. This should be set by the user
587
+ if there are additional paths that want to be included
588
+ via `include_path`
589
+
590
+ :return
591
+ Dictionary of task objects
592
+ """
593
+
594
+ task_name_from_string_dict = {}
595
+ task_name_from_config_dict = {}
596
+ task_name_from_object_dict = {}
597
+
598
+ if isinstance(task_name_list, str):
599
+ task_name_list = [task_name_list]
600
+ elif isinstance(task_name_list, list):
601
+ if not all([isinstance(task, (str, dict, Task)) for task in task_name_list]):
602
+ raise TypeError(
603
+ "Expected all list items to be of types 'str', 'dict', or 'Task', but at least one entry did not match."
604
+ )
605
+ else:
606
+ raise TypeError(
607
+ f"Expected a 'str' or 'list' but received {type(task_name_list)}."
608
+ )
609
+
610
+ string_task_name_list = [task for task in task_name_list if isinstance(task, str)]
611
+ others_task_name_list = [
612
+ task for task in task_name_list if not isinstance(task, str)
613
+ ]
614
+ if len(string_task_name_list) > 0:
615
+ if task_manager is None:
616
+ task_manager = TaskManager()
617
+
618
+ task_name_from_string_dict = task_manager.load_task_or_group(
619
+ string_task_name_list
620
+ )
621
+
622
+ for task_element in others_task_name_list:
623
+ if isinstance(task_element, dict):
624
+ task_name_from_config_dict = {
625
+ **task_name_from_config_dict,
626
+ **task_manager.load_config(config=task_element),
627
+ }
628
+
629
+ elif isinstance(task_element, Task):
630
+ task_name_from_object_dict = {
631
+ **task_name_from_object_dict,
632
+ get_task_name_from_object(task_element): task_element,
633
+ }
634
+
635
+ if not set(task_name_from_string_dict.keys()).isdisjoint(
636
+ set(task_name_from_object_dict.keys())
637
+ ):
638
+ raise ValueError
639
+
640
+ final_task_dict = {
641
+ **task_name_from_string_dict,
642
+ **task_name_from_config_dict,
643
+ **task_name_from_object_dict,
644
+ }
645
+
646
+ # behavior can get odd if one tries to invoke several groups that "compete" for the same task.
647
+ # (notably, because one could request several num_fewshot values at once in GroupConfig overrides for the subtask
648
+ # and we'd be unsure which to use and report.)
649
+ # we explicitly check and error in this case.
650
+ _check_duplicates(get_subtask_list(final_task_dict))
651
+
652
+ return final_task_dict
testbed/EleutherAI__lm-evaluation-harness/lm_eval/tasks/tinyBenchmarks/tinyGSM8k.yaml ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ task: tinyGSM8k
2
+ dataset_path: tinyBenchmarks/tinyGSM8k
3
+ dataset_name: main
4
+ output_type: generate_until
5
+ training_split: train
6
+ fewshot_split: train
7
+ test_split: test
8
+ num_fewshot: 5
9
+ doc_to_text: "Question: {{question}}\nAnswer:"
10
+ doc_to_target: "{{answer}}" #" {{answer.split('### ')[-1].rstrip()}}"
11
+ metric_list:
12
+ - metric: exact_match
13
+ aggregation: !function agg_functions.agg_gpirt_gsm8k
14
+ higher_is_better: true
15
+ ignore_case: true
16
+ ignore_punctuation: false
17
+ regexes_to_ignore:
18
+ - ","
19
+ - "\\$"
20
+ - "(?s).*#### "
21
+ - "\\.$"
22
+ generation_kwargs:
23
+ until:
24
+ - "Question:"
25
+ - "</s>"
26
+ - "<|im_end|>"
27
+ do_sample: false
28
+ temperature: 0.0
29
+ repeats: 1
30
+ num_fewshot: 5
31
+ filter_list:
32
+ - name: "strict-match"
33
+ filter:
34
+ - function: "regex"
35
+ regex_pattern: "#### (\\-?[0-9\\.\\,]+)"
36
+ - function: "take_first"
37
+ - name: "flexible-extract"
38
+ filter:
39
+ - function: "regex"
40
+ group_select: -1
41
+ regex_pattern: "(-?[$0-9.,]{2,})|(-?[0-9]+)"
42
+ - function: "take_first"
43
+ metadata:
44
+ version: 0.0
testbed/EleutherAI__lm-evaluation-harness/lm_eval/tasks/tmlu/README.md ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # TMLU
2
+
3
+ ### Paper
4
+
5
+ Title: `Measuring Taiwanese Mandarin Language Understanding`
6
+
7
+ Abstract: `The evaluation of large language models (LLMs) has drawn substantial attention in the field recently. This work focuses on evaluating LLMs in a Chinese context, specifically, for Traditional Chinese which has been largely underrepresented in existing benchmarks. We present TMLU, a holistic evaluation suit tailored for assessing the advanced knowledge and reasoning capability in LLMs, under the context of Taiwanese Mandarin. TMLU consists of an array of 37 subjects across social science, STEM, humanities, Taiwan-specific content, and others, ranging from middle school to professional levels. In addition, we curate chain-of-thought-like few-shot explanations for each subject to facilitate the evaluation of complex reasoning skills. To establish a comprehensive baseline, we conduct extensive experiments and analysis on 24 advanced LLMs. The results suggest that Chinese open-weight models demonstrate inferior performance comparing to multilingual proprietary ones, and open-weight models tailored for Taiwanese Mandarin lag behind the Simplified-Chinese counterparts. The findings indicate great headrooms for improvement, and emphasize the goal of TMLU to foster the development of localized Taiwanese-Mandarin LLMs. We release the benchmark and evaluation scripts for the community to promote future research.`
8
+
9
+
10
+ Homepage: [TMLU Huggingface Dataset](https://huggingface.co/datasets/miulab/tmlu)
11
+
12
+
13
+ ### Citation
14
+
15
+ ```
16
+ @article{DBLP:journals/corr/abs-2403-20180,
17
+ author = {Po{-}Heng Chen and
18
+ Sijia Cheng and
19
+ Wei{-}Lin Chen and
20
+ Yen{-}Ting Lin and
21
+ Yun{-}Nung Chen},
22
+ title = {Measuring Taiwanese Mandarin Language Understanding},
23
+ journal = {CoRR},
24
+ volume = {abs/2403.20180},
25
+ year = {2024},
26
+ url = {https://doi.org/10.48550/arXiv.2403.20180},
27
+ doi = {10.48550/ARXIV.2403.20180},
28
+ eprinttype = {arXiv},
29
+ eprint = {2403.20180},
30
+ timestamp = {Wed, 10 Apr 2024 17:37:45 +0200},
31
+ biburl = {https://dblp.org/rec/journals/corr/abs-2403-20180.bib},
32
+ bibsource = {dblp computer science bibliography, https://dblp.org}
33
+ }
34
+ ```
35
+
36
+ ### Groups and Tasks
37
+
38
+ #### Groups
39
+
40
+ * `tmlu`: `The dataset comprises 2,981 multiple-choice questions from 37 subjects. `
41
+
42
+ #### Tasks
43
+
44
+ The following tasks evaluate subjects in the TMLU dataset using loglikelihood-based multiple-choice scoring:
45
+
46
+ * `tmlu_{subject_english}`
47
+
48
+ ### Checklist
49
+
50
+ For adding novel benchmarks/datasets to the library:
51
+ * [x] Is the task an existing benchmark in the literature?
52
+ * [x] Have you referenced the original paper that introduced the task?
53
+ * [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?
54
+
55
+
56
+ If other tasks on this dataset are already supported:
57
+ * [x] Is the "Main" variant of this task clearly denoted?
58
+ * [x] Have you provided a short sentence in a README on what each new variant adds / evaluates?
59
+ * [x] Have you noted which, if any, published evaluation setups are matched by this variant?
testbed/EleutherAI__lm-evaluation-harness/lm_eval/tasks/tmlu/default/_generate_configs.py ADDED
@@ -0,0 +1,198 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Take in a YAML, and output all "other" splits with this YAML
3
+ """
4
+
5
+ import argparse
6
+ import os
7
+
8
+ import pandas as pd
9
+ import yaml
10
+ from tqdm import tqdm
11
+
12
+
13
+ categories = {
14
+ "STEM": [
15
+ "biology",
16
+ "chemistry",
17
+ "mathematics" "physics",
18
+ "earth science",
19
+ ],
20
+ "humanities": ["Chinese", "history", "Tour", "law"],
21
+ "social_sciences": [
22
+ "civics",
23
+ "geography",
24
+ "accounting",
25
+ "psychologist",
26
+ ],
27
+ "Taiwan Specific": [
28
+ "Taiwan Specific",
29
+ ],
30
+ "other": ["Medicine", "Nutritionist"], # (business, health, misc.)
31
+ }
32
+
33
+ task_list = [
34
+ "AST civics",
35
+ "AST geography",
36
+ "CAP civics",
37
+ "CAP geography",
38
+ "GSAT civics",
39
+ "GSAT geography",
40
+ "MOEX Accountant",
41
+ "MOEX Clinical psychologist",
42
+ "AST biology",
43
+ "AST chemistry",
44
+ "AST mathematics",
45
+ "AST physics",
46
+ "CAP biology",
47
+ "CAP chemistry",
48
+ "CAP earth science",
49
+ "CAP mathematics",
50
+ "CAP physics",
51
+ "GSAT biology",
52
+ "GSAT chemistry",
53
+ "GSAT earth science",
54
+ "GSAT mathematics",
55
+ "GSAT physics",
56
+ "AST Chinese",
57
+ "AST history",
58
+ "CAP Chinese",
59
+ "CAP history",
60
+ "GSAT Chinese",
61
+ "GSAT history",
62
+ "MOEX Tour guide",
63
+ "MOEX Tour leader",
64
+ "MOEX Lawyer qualification",
65
+ "HB Driving Rule",
66
+ "MOEX Teacher qualification",
67
+ "MOEX Taiwan tourist resources",
68
+ "MOEX Basic Traditional Chinese Medicine",
69
+ "MOEX Clinical Traditional Chinese Medicine",
70
+ "MOEX Nutritionist",
71
+ ]
72
+ subject2name = {}
73
+ subject2num_choice = {}
74
+ # subject2category = {}
75
+ SUBJECTS = {}
76
+
77
+
78
+ def parse_args():
79
+ parser = argparse.ArgumentParser()
80
+ parser.add_argument("--base_yaml_path", default="_default_template_yaml")
81
+ parser.add_argument("--save_prefix_path", default="tmlu")
82
+ parser.add_argument("--cot_prompt_path", default=None)
83
+ parser.add_argument("--task_prefix", default="")
84
+ parser.add_argument("--group_prefix", default="")
85
+ parser.add_argument("--subject_file", default="../subject.tsv")
86
+ return parser.parse_args()
87
+
88
+
89
+ if __name__ == "__main__":
90
+ args = parse_args()
91
+ from pathlib import Path
92
+
93
+ # Initialization
94
+ SUBJECT_FILE = Path(__file__).parent / Path(args.subject_file)
95
+
96
+ df = pd.read_csv(SUBJECT_FILE, delimiter="\t")
97
+
98
+ for _, row in df.iterrows():
99
+ for _c in categories:
100
+ if row["subject"] in SUBJECTS:
101
+ raise ValueError(f"Duplicate tasks. {row['subject']} already exists.")
102
+ if row["category"] in categories[_c]: # append new item into SUBJECTS
103
+ SUBJECTS[row["subject"]] = _c
104
+ subject2name[row["subject"]] = row["name"]
105
+ subject2num_choice[row["subject"]] = row["# Choices"]
106
+ break
107
+ # End of SUBJECTS initialization
108
+
109
+ # get filename of base_yaml so we can `"include": ` it in our "other" YAMLs.
110
+ base_yaml_name = os.path.split(args.base_yaml_path)[-1]
111
+ with open(args.base_yaml_path) as f:
112
+ base_yaml = yaml.full_load(f)
113
+
114
+ if args.cot_prompt_path is not None:
115
+ import json
116
+
117
+ with open(args.cot_prompt_path) as f:
118
+ cot_file = json.load(f)
119
+
120
+ ALL_CATEGORIES = []
121
+ for subject, category in tqdm(SUBJECTS.items()):
122
+ if category not in ALL_CATEGORIES:
123
+ ALL_CATEGORIES.append(category)
124
+
125
+ if args.cot_prompt_path is not None:
126
+ description = cot_file[subject]
127
+ else:
128
+ name_of_subject = subject2name[subject].replace("_", " ")
129
+ description = f"以下為{name_of_subject}的單選題,請提供正確答案的選項。\n\n"
130
+ # description = f"The following are multiple choice questions (with answers) about {' '.join(subject.split('_'))}.\n\n"
131
+
132
+ num_choies = subject2num_choice[subject]
133
+ # basic_doc_to_text = "{{question.strip()}}\nA. {{choices[0]}}\nB. {{choices[1]}}\nC. {{choices[2]}}\nD. {{choices[3]}}"
134
+ basic_doc_to_choice = ["A", "B", "C", "D"]
135
+ if num_choies == 5:
136
+ # basic_doc_to_text += "\nE. {{choices[4]}}"
137
+ basic_doc_to_choice.append("E")
138
+ if num_choies == 6:
139
+ # basic_doc_to_text += "\nE. {{choices[4]}}\nF. {{choices[5]}}"
140
+ basic_doc_to_choice += ["E", "F"]
141
+ # basic_doc_to_text += "\nAnswer:"
142
+ # basic_doc_to_text = "{{question.strip()}}\nA. {{choices[0]}}\nB. {{choices[1]}}\nC. {{choices[2]}}\nD. {{choices[3]}}{% if choices[4] %}\nE. {{choices[4]}}{% endif %}{% if choices[5] %}\nF. {{choices[5]}}{% endif %}\nAnswer:"
143
+ basic_doc_to_text = "{{question.strip()}}\nA. {{choices[0]}}\nB. {{choices[1]}}\nC. {{choices[2]}}\nD. {{choices[3]}}{% if choices is defined and choices|length > 4 %}\nE. {{choices[4]}}{% endif %}{% if choices is defined and choices|length > 5 %}\nF. {{choices[5]}}{% endif %}\nAnswer:"
144
+
145
+ yaml_dict = {
146
+ "include": base_yaml_name,
147
+ "group": f"tmlu_{args.task_prefix}_{category}"
148
+ if args.task_prefix != ""
149
+ else f"tmlu_{category}",
150
+ "group_alias": category.replace("_", " "),
151
+ "task": f"tmlu_{args.task_prefix}_{subject}"
152
+ if args.task_prefix != ""
153
+ else f"tmlu_{subject}",
154
+ "task_alias": subject.replace("_", " "),
155
+ "dataset_name": subject,
156
+ "description": description,
157
+ # doc_to_text: "{{question.strip()}}\nA. {{choices[0]}}\nB. {{choices[1]}}\nC. {{choices[2]}}\nD. {{choices[3]}}\nAnswer:"
158
+ "doc_to_text": basic_doc_to_text,
159
+ # doc_to_choice: ["A", "B", "C", "D"]
160
+ "doc_to_choice": basic_doc_to_choice,
161
+ }
162
+
163
+ file_save_path = args.save_prefix_path + f"_{subject}.yaml"
164
+ # eval_logger.info(f"Saving yaml for subset {subject} to {file_save_path}")
165
+ with open(file_save_path, "w") as yaml_file:
166
+ yaml.dump(
167
+ yaml_dict,
168
+ yaml_file,
169
+ # width=float("inf"),
170
+ allow_unicode=True,
171
+ default_style='"',
172
+ )
173
+
174
+ if args.task_prefix != "":
175
+ mmlu_subcategories = [
176
+ f"tmlu_{args.task_prefix}_{category}" for category in ALL_CATEGORIES
177
+ ]
178
+ else:
179
+ mmlu_subcategories = [f"tmlu_{category}" for category in ALL_CATEGORIES]
180
+
181
+ if args.group_prefix != "":
182
+ file_save_path = args.group_prefix + ".yaml"
183
+ else:
184
+ file_save_path = args.save_prefix_path + ".yaml"
185
+
186
+ # eval_logger.info(f"Saving benchmark config to {file_save_path}")
187
+ with open(file_save_path, "w") as yaml_file:
188
+ yaml.dump(
189
+ {
190
+ "group": f"tmlu_{args.task_prefix}"
191
+ if args.task_prefix != ""
192
+ else "tmlu",
193
+ "task": mmlu_subcategories,
194
+ },
195
+ yaml_file,
196
+ indent=4,
197
+ default_flow_style=False,
198
+ )
testbed/EleutherAI__lm-evaluation-harness/lm_eval/tasks/tmlu/default/_tmlu.yaml ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ group: tmlu
2
+ group_alias: TMLU
3
+ task:
4
+ - group: tmlu_social_sciences
5
+ group_alias: Social Sciences
6
+ task:
7
+ - tmlu_social_sciences_tasks
8
+ aggregate_metric_list:
9
+ - metric: acc
10
+ - group: tmlu_stem
11
+ group_alias: STEM
12
+ task:
13
+ - tmlu_stem_tasks
14
+ aggregate_metric_list:
15
+ - metric: acc
16
+ - group: tmlu_humanities
17
+ group_alias: Humanities
18
+ task:
19
+ - tmlu_humanities_tasks
20
+ aggregate_metric_list:
21
+ - metric: acc
22
+ - group: tmlu_taiwan_specific
23
+ group_alias: Taiwan Specific
24
+ task:
25
+ - tmlu_taiwan_specific_tasks
26
+ aggregate_metric_list:
27
+ - metric: acc
28
+ - group: tmlu_other
29
+ group_alias: Other
30
+ task:
31
+ - tmlu_other_tasks
32
+ aggregate_metric_list:
33
+ - metric: acc
34
+ aggregate_metric_list:
35
+ - metric: acc
36
+ metadata:
37
+ version: 1
testbed/EleutherAI__lm-evaluation-harness/lm_eval/tasks/tmlu/default/tmlu_AST_biology.yaml ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "dataset_name": "AST_biology"
2
+ "description": "以下為分科測驗生物的單選題,請提供正確答案的選項。\n\n"
3
+ "doc_to_choice":
4
+ - "A"
5
+ - "B"
6
+ - "C"
7
+ - "D"
8
+ "doc_to_text": "{{question.strip()}}\nA. {{choices[0]}}\nB. {{choices[1]}}\nC. {{choices[2]}}\n\
9
+ D. {{choices[3]}}{% if choices is defined and choices|length > 4 %}\nE. {{choices[4]}}{%\
10
+ \ endif %}{% if choices is defined and choices|length > 5 %}\nF. {{choices[5]}}{%\
11
+ \ endif %}\nAnswer:"
12
+ "tag": "tmlu_stem_tasks"
13
+ "include": "_default_template_yaml"
14
+ "task": "tmlu_AST_biology"
15
+ "task_alias": "AST biology"
testbed/EleutherAI__lm-evaluation-harness/lm_eval/tasks/tmlu/default/tmlu_AST_chinese.yaml ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "dataset_name": "AST_chinese"
2
+ "description": "以下為分科測驗國文的單選題,請提供正確答案的選項。\n\n"
3
+ "doc_to_choice":
4
+ - "A"
5
+ - "B"
6
+ - "C"
7
+ - "D"
8
+ "doc_to_text": "{{question.strip()}}\nA. {{choices[0]}}\nB. {{choices[1]}}\nC. {{choices[2]}}\n\
9
+ D. {{choices[3]}}{% if choices is defined and choices|length > 4 %}\nE. {{choices[4]}}{%\
10
+ \ endif %}{% if choices is defined and choices|length > 5 %}\nF. {{choices[5]}}{%\
11
+ \ endif %}\nAnswer:"
12
+ "tag": "tmlu_humanities_tasks"
13
+ "include": "_default_template_yaml"
14
+ "task": "tmlu_AST_chinese"
15
+ "task_alias": "AST chinese"
testbed/EleutherAI__lm-evaluation-harness/lm_eval/tasks/tmlu/default/tmlu_AST_civics.yaml ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "dataset_name": "AST_civics"
2
+ "description": "以下為分科測驗公民的單選題,請提供正確答案的選項。\n\n"
3
+ "doc_to_choice":
4
+ - "A"
5
+ - "B"
6
+ - "C"
7
+ - "D"
8
+ "doc_to_text": "{{question.strip()}}\nA. {{choices[0]}}\nB. {{choices[1]}}\nC. {{choices[2]}}\n\
9
+ D. {{choices[3]}}{% if choices is defined and choices|length > 4 %}\nE. {{choices[4]}}{%\
10
+ \ endif %}{% if choices is defined and choices|length > 5 %}\nF. {{choices[5]}}{%\
11
+ \ endif %}\nAnswer:"
12
+ "tag": "tmlu_social_sciences_tasks"
13
+ "include": "_default_template_yaml"
14
+ "task": "tmlu_AST_civics"
15
+ "task_alias": "AST civics"
testbed/EleutherAI__lm-evaluation-harness/lm_eval/tasks/tmlu/default/tmlu_AST_geography.yaml ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "dataset_name": "AST_geography"
2
+ "description": "以下為分科測驗地理的單選題,請提供正確答案的選項。\n\n"
3
+ "doc_to_choice":
4
+ - "A"
5
+ - "B"
6
+ - "C"
7
+ - "D"
8
+ "doc_to_text": "{{question.strip()}}\nA. {{choices[0]}}\nB. {{choices[1]}}\nC. {{choices[2]}}\n\
9
+ D. {{choices[3]}}{% if choices is defined and choices|length > 4 %}\nE. {{choices[4]}}{%\
10
+ \ endif %}{% if choices is defined and choices|length > 5 %}\nF. {{choices[5]}}{%\
11
+ \ endif %}\nAnswer:"
12
+ "tag": "tmlu_social_sciences_tasks"
13
+ "include": "_default_template_yaml"
14
+ "task": "tmlu_AST_geography"
15
+ "task_alias": "AST geography"
testbed/EleutherAI__lm-evaluation-harness/lm_eval/tasks/tmlu/default/tmlu_AST_history.yaml ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "dataset_name": "AST_history"
2
+ "description": "以下為分科測驗歷史的單選題,請提供正確答案的選項。\n\n"
3
+ "doc_to_choice":
4
+ - "A"
5
+ - "B"
6
+ - "C"
7
+ - "D"
8
+ "doc_to_text": "{{question.strip()}}\nA. {{choices[0]}}\nB. {{choices[1]}}\nC. {{choices[2]}}\n\
9
+ D. {{choices[3]}}{% if choices is defined and choices|length > 4 %}\nE. {{choices[4]}}{%\
10
+ \ endif %}{% if choices is defined and choices|length > 5 %}\nF. {{choices[5]}}{%\
11
+ \ endif %}\nAnswer:"
12
+ "tag": "tmlu_humanities_tasks"
13
+ "include": "_default_template_yaml"
14
+ "task": "tmlu_AST_history"
15
+ "task_alias": "AST history"
testbed/EleutherAI__lm-evaluation-harness/lm_eval/tasks/tmlu/default/tmlu_CAP_biology.yaml ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "dataset_name": "CAP_biology"
2
+ "description": "以下為會考生物的單選題,請提供正確答案的選項。\n\n"
3
+ "doc_to_choice":
4
+ - "A"
5
+ - "B"
6
+ - "C"
7
+ - "D"
8
+ "doc_to_text": "{{question.strip()}}\nA. {{choices[0]}}\nB. {{choices[1]}}\nC. {{choices[2]}}\n\
9
+ D. {{choices[3]}}{% if choices is defined and choices|length > 4 %}\nE. {{choices[4]}}{%\
10
+ \ endif %}{% if choices is defined and choices|length > 5 %}\nF. {{choices[5]}}{%\
11
+ \ endif %}\nAnswer:"
12
+ "tag": "tmlu_stem_tasks"
13
+ "include": "_default_template_yaml"
14
+ "task": "tmlu_CAP_biology"
15
+ "task_alias": "CAP biology"
testbed/EleutherAI__lm-evaluation-harness/lm_eval/tasks/tmlu/default/tmlu_CAP_chemistry.yaml ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "dataset_name": "CAP_chemistry"
2
+ "description": "以下為會考化學的單選題,請提供正確答案的選項。\n\n"
3
+ "doc_to_choice":
4
+ - "A"
5
+ - "B"
6
+ - "C"
7
+ - "D"
8
+ "doc_to_text": "{{question.strip()}}\nA. {{choices[0]}}\nB. {{choices[1]}}\nC. {{choices[2]}}\n\
9
+ D. {{choices[3]}}{% if choices is defined and choices|length > 4 %}\nE. {{choices[4]}}{%\
10
+ \ endif %}{% if choices is defined and choices|length > 5 %}\nF. {{choices[5]}}{%\
11
+ \ endif %}\nAnswer:"
12
+ "tag": "tmlu_stem_tasks"
13
+ "include": "_default_template_yaml"
14
+ "task": "tmlu_CAP_chemistry"
15
+ "task_alias": "CAP chemistry"
testbed/EleutherAI__lm-evaluation-harness/lm_eval/tasks/tmlu/default/tmlu_CAP_chinese.yaml ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "dataset_name": "CAP_chinese"
2
+ "description": "以下為會考國文的單選題,請提供正確答案的選項。\n\n"
3
+ "doc_to_choice":
4
+ - "A"
5
+ - "B"
6
+ - "C"
7
+ - "D"
8
+ "doc_to_text": "{{question.strip()}}\nA. {{choices[0]}}\nB. {{choices[1]}}\nC. {{choices[2]}}\n\
9
+ D. {{choices[3]}}{% if choices is defined and choices|length > 4 %}\nE. {{choices[4]}}{%\
10
+ \ endif %}{% if choices is defined and choices|length > 5 %}\nF. {{choices[5]}}{%\
11
+ \ endif %}\nAnswer:"
12
+ "tag": "tmlu_humanities_tasks"
13
+ "include": "_default_template_yaml"
14
+ "task": "tmlu_CAP_chinese"
15
+ "task_alias": "CAP chinese"
testbed/EleutherAI__lm-evaluation-harness/lm_eval/tasks/tmlu/default/tmlu_CAP_civics.yaml ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "dataset_name": "CAP_civics"
2
+ "description": "以下為會考公民的單選題,請提供正確答案的選項。\n\n"
3
+ "doc_to_choice":
4
+ - "A"
5
+ - "B"
6
+ - "C"
7
+ - "D"
8
+ "doc_to_text": "{{question.strip()}}\nA. {{choices[0]}}\nB. {{choices[1]}}\nC. {{choices[2]}}\n\
9
+ D. {{choices[3]}}{% if choices is defined and choices|length > 4 %}\nE. {{choices[4]}}{%\
10
+ \ endif %}{% if choices is defined and choices|length > 5 %}\nF. {{choices[5]}}{%\
11
+ \ endif %}\nAnswer:"
12
+ "tag": "tmlu_social_sciences_tasks"
13
+ "include": "_default_template_yaml"
14
+ "task": "tmlu_CAP_civics"
15
+ "task_alias": "CAP civics"
testbed/EleutherAI__lm-evaluation-harness/lm_eval/tasks/tmlu/default/tmlu_CAP_earth_science.yaml ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "dataset_name": "CAP_earth_science"
2
+ "description": "以下為會考地球科學的單選題,請提供正確答案的選項。\n\n"
3
+ "doc_to_choice":
4
+ - "A"
5
+ - "B"
6
+ - "C"
7
+ - "D"
8
+ "doc_to_text": "{{question.strip()}}\nA. {{choices[0]}}\nB. {{choices[1]}}\nC. {{choices[2]}}\n\
9
+ D. {{choices[3]}}{% if choices is defined and choices|length > 4 %}\nE. {{choices[4]}}{%\
10
+ \ endif %}{% if choices is defined and choices|length > 5 %}\nF. {{choices[5]}}{%\
11
+ \ endif %}\nAnswer:"
12
+ "tag": "tmlu_stem_tasks"
13
+ "include": "_default_template_yaml"
14
+ "task": "tmlu_CAP_earth_science"
15
+ "task_alias": "CAP earth science"
testbed/EleutherAI__lm-evaluation-harness/lm_eval/tasks/tmlu/default/tmlu_CAP_geography.yaml ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "dataset_name": "CAP_geography"
2
+ "description": "以下為會考地理的單選題,請提供正確答案的選項。\n\n"
3
+ "doc_to_choice":
4
+ - "A"
5
+ - "B"
6
+ - "C"
7
+ - "D"
8
+ "doc_to_text": "{{question.strip()}}\nA. {{choices[0]}}\nB. {{choices[1]}}\nC. {{choices[2]}}\n\
9
+ D. {{choices[3]}}{% if choices is defined and choices|length > 4 %}\nE. {{choices[4]}}{%\
10
+ \ endif %}{% if choices is defined and choices|length > 5 %}\nF. {{choices[5]}}{%\
11
+ \ endif %}\nAnswer:"
12
+ "tag": "tmlu_social_sciences_tasks"
13
+ "include": "_default_template_yaml"
14
+ "task": "tmlu_CAP_geography"
15
+ "task_alias": "CAP geography"
testbed/EleutherAI__lm-evaluation-harness/lm_eval/tasks/tmlu/default/tmlu_CAP_history.yaml ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "dataset_name": "CAP_history"
2
+ "description": "以下為會考歷史的單選題,請提供正確答案的選項。\n\n"
3
+ "doc_to_choice":
4
+ - "A"
5
+ - "B"
6
+ - "C"
7
+ - "D"
8
+ "doc_to_text": "{{question.strip()}}\nA. {{choices[0]}}\nB. {{choices[1]}}\nC. {{choices[2]}}\n\
9
+ D. {{choices[3]}}{% if choices is defined and choices|length > 4 %}\nE. {{choices[4]}}{%\
10
+ \ endif %}{% if choices is defined and choices|length > 5 %}\nF. {{choices[5]}}{%\
11
+ \ endif %}\nAnswer:"
12
+ "tag": "tmlu_humanities_tasks"
13
+ "include": "_default_template_yaml"
14
+ "task": "tmlu_CAP_history"
15
+ "task_alias": "CAP history"
testbed/EleutherAI__lm-evaluation-harness/lm_eval/tasks/tmlu/default/tmlu_GSAT_biology.yaml ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "dataset_name": "GSAT_biology"
2
+ "description": "以下為學測生物的單選題,請提供正確答案的選項。\n\n"
3
+ "doc_to_choice":
4
+ - "A"
5
+ - "B"
6
+ - "C"
7
+ - "D"
8
+ - "E"
9
+ "doc_to_text": "{{question.strip()}}\nA. {{choices[0]}}\nB. {{choices[1]}}\nC. {{choices[2]}}\n\
10
+ D. {{choices[3]}}{% if choices is defined and choices|length > 4 %}\nE. {{choices[4]}}{%\
11
+ \ endif %}{% if choices is defined and choices|length > 5 %}\nF. {{choices[5]}}{%\
12
+ \ endif %}\nAnswer:"
13
+ "tag": "tmlu_stem_tasks"
14
+ "include": "_default_template_yaml"
15
+ "task": "tmlu_GSAT_biology"
16
+ "task_alias": "GSAT biology"
testbed/EleutherAI__lm-evaluation-harness/lm_eval/tasks/tmlu/default/tmlu_GSAT_chemistry.yaml ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "dataset_name": "GSAT_chemistry"
2
+ "description": "以下為學測化學的單選題,請提供正確答案的選項。\n\n"
3
+ "doc_to_choice":
4
+ - "A"
5
+ - "B"
6
+ - "C"
7
+ - "D"
8
+ - "E"
9
+ "doc_to_text": "{{question.strip()}}\nA. {{choices[0]}}\nB. {{choices[1]}}\nC. {{choices[2]}}\n\
10
+ D. {{choices[3]}}{% if choices is defined and choices|length > 4 %}\nE. {{choices[4]}}{%\
11
+ \ endif %}{% if choices is defined and choices|length > 5 %}\nF. {{choices[5]}}{%\
12
+ \ endif %}\nAnswer:"
13
+ "tag": "tmlu_stem_tasks"
14
+ "include": "_default_template_yaml"
15
+ "task": "tmlu_GSAT_chemistry"
16
+ "task_alias": "GSAT chemistry"
testbed/EleutherAI__lm-evaluation-harness/lm_eval/tasks/tmlu/default/tmlu_GSAT_chinese.yaml ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "dataset_name": "GSAT_chinese"
2
+ "description": "以下為學測國文的單選題,請提供正確答案的選項。\n\n"
3
+ "doc_to_choice":
4
+ - "A"
5
+ - "B"
6
+ - "C"
7
+ - "D"
8
+ "doc_to_text": "{{question.strip()}}\nA. {{choices[0]}}\nB. {{choices[1]}}\nC. {{choices[2]}}\n\
9
+ D. {{choices[3]}}{% if choices is defined and choices|length > 4 %}\nE. {{choices[4]}}{%\
10
+ \ endif %}{% if choices is defined and choices|length > 5 %}\nF. {{choices[5]}}{%\
11
+ \ endif %}\nAnswer:"
12
+ "tag": "tmlu_humanities_tasks"
13
+ "include": "_default_template_yaml"
14
+ "task": "tmlu_GSAT_chinese"
15
+ "task_alias": "GSAT chinese"
testbed/EleutherAI__lm-evaluation-harness/lm_eval/tasks/tmlu/default/tmlu_GSAT_civics.yaml ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "dataset_name": "GSAT_civics"
2
+ "description": "以下為學測公民的單選題,請提供正確答案的選項。\n\n"
3
+ "doc_to_choice":
4
+ - "A"
5
+ - "B"
6
+ - "C"
7
+ - "D"
8
+ "doc_to_text": "{{question.strip()}}\nA. {{choices[0]}}\nB. {{choices[1]}}\nC. {{choices[2]}}\n\
9
+ D. {{choices[3]}}{% if choices is defined and choices|length > 4 %}\nE. {{choices[4]}}{%\
10
+ \ endif %}{% if choices is defined and choices|length > 5 %}\nF. {{choices[5]}}{%\
11
+ \ endif %}\nAnswer:"
12
+ "tag": "tmlu_social_sciences_tasks"
13
+ "include": "_default_template_yaml"
14
+ "task": "tmlu_GSAT_civics"
15
+ "task_alias": "GSAT civics"
testbed/EleutherAI__lm-evaluation-harness/lm_eval/tasks/tmlu/default/tmlu_GSAT_earth_science.yaml ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "dataset_name": "GSAT_earth_science"
2
+ "description": "以下為學測地球科學的單選題,請提供正確答案的選項。\n\n"
3
+ "doc_to_choice":
4
+ - "A"
5
+ - "B"
6
+ - "C"
7
+ - "D"
8
+ - "E"
9
+ "doc_to_text": "{{question.strip()}}\nA. {{choices[0]}}\nB. {{choices[1]}}\nC. {{choices[2]}}\n\
10
+ D. {{choices[3]}}{% if choices is defined and choices|length > 4 %}\nE. {{choices[4]}}{%\
11
+ \ endif %}{% if choices is defined and choices|length > 5 %}\nF. {{choices[5]}}{%\
12
+ \ endif %}\nAnswer:"
13
+ "tag": "tmlu_stem_tasks"
14
+ "include": "_default_template_yaml"
15
+ "task": "tmlu_GSAT_earth_science"
16
+ "task_alias": "GSAT earth science"
testbed/EleutherAI__lm-evaluation-harness/lm_eval/tasks/tmlu/default/tmlu_GSAT_geography.yaml ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "dataset_name": "GSAT_geography"
2
+ "description": "以下為學測地理的單選題,請提供正確答案的選項。\n\n"
3
+ "doc_to_choice":
4
+ - "A"
5
+ - "B"
6
+ - "C"
7
+ - "D"
8
+ "doc_to_text": "{{question.strip()}}\nA. {{choices[0]}}\nB. {{choices[1]}}\nC. {{choices[2]}}\n\
9
+ D. {{choices[3]}}{% if choices is defined and choices|length > 4 %}\nE. {{choices[4]}}{%\
10
+ \ endif %}{% if choices is defined and choices|length > 5 %}\nF. {{choices[5]}}{%\
11
+ \ endif %}\nAnswer:"
12
+ "tag": "tmlu_social_sciences_tasks"
13
+ "include": "_default_template_yaml"
14
+ "task": "tmlu_GSAT_geography"
15
+ "task_alias": "GSAT geography"
testbed/EleutherAI__lm-evaluation-harness/lm_eval/tasks/tmlu/default/tmlu_GSAT_history.yaml ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "dataset_name": "GSAT_history"
2
+ "description": "以下為學測歷史的單選題,請提供正確答案的選項。\n\n"
3
+ "doc_to_choice":
4
+ - "A"
5
+ - "B"
6
+ - "C"
7
+ - "D"
8
+ "doc_to_text": "{{question.strip()}}\nA. {{choices[0]}}\nB. {{choices[1]}}\nC. {{choices[2]}}\n\
9
+ D. {{choices[3]}}{% if choices is defined and choices|length > 4 %}\nE. {{choices[4]}}{%\
10
+ \ endif %}{% if choices is defined and choices|length > 5 %}\nF. {{choices[5]}}{%\
11
+ \ endif %}\nAnswer:"
12
+ "tag": "tmlu_humanities_tasks"
13
+ "include": "_default_template_yaml"
14
+ "task": "tmlu_GSAT_history"
15
+ "task_alias": "GSAT history"
testbed/EleutherAI__lm-evaluation-harness/lm_eval/tasks/tmlu/default/tmlu_accountant.yaml ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "dataset_name": "accountant"
2
+ "description": "以下為會計師的單選題,請提供正確答案的選項。\n\n"
3
+ "doc_to_choice":
4
+ - "A"
5
+ - "B"
6
+ - "C"
7
+ - "D"
8
+ "doc_to_text": "{{question.strip()}}\nA. {{choices[0]}}\nB. {{choices[1]}}\nC. {{choices[2]}}\n\
9
+ D. {{choices[3]}}{% if choices is defined and choices|length > 4 %}\nE. {{choices[4]}}{%\
10
+ \ endif %}{% if choices is defined and choices|length > 5 %}\nF. {{choices[5]}}{%\
11
+ \ endif %}\nAnswer:"
12
+ "tag": "tmlu_social_sciences_tasks"
13
+ "include": "_default_template_yaml"
14
+ "task": "tmlu_accountant"
15
+ "task_alias": "accountant"
testbed/EleutherAI__lm-evaluation-harness/lm_eval/tasks/tmlu/default/tmlu_clinical_psychologist.yaml ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "dataset_name": "clinical_psychologist"
2
+ "description": "以下為臨床心理師的單選題,請提供正確答案的選項。\n\n"
3
+ "doc_to_choice":
4
+ - "A"
5
+ - "B"
6
+ - "C"
7
+ - "D"
8
+ "doc_to_text": "{{question.strip()}}\nA. {{choices[0]}}\nB. {{choices[1]}}\nC. {{choices[2]}}\n\
9
+ D. {{choices[3]}}{% if choices is defined and choices|length > 4 %}\nE. {{choices[4]}}{%\
10
+ \ endif %}{% if choices is defined and choices|length > 5 %}\nF. {{choices[5]}}{%\
11
+ \ endif %}\nAnswer:"
12
+ "tag": "tmlu_social_sciences_tasks"
13
+ "include": "_default_template_yaml"
14
+ "task": "tmlu_clinical_psychologist"
15
+ "task_alias": "clinical psychologist"
testbed/EleutherAI__lm-evaluation-harness/lm_eval/tasks/tmlu/default/tmlu_clinical_traditional_chinese_medicine.yaml ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "dataset_name": "clinical_traditional_chinese_medicine"
2
+ "description": "以下為中醫針灸的單選題,請提供正確答案的選項。\n\n"
3
+ "doc_to_choice":
4
+ - "A"
5
+ - "B"
6
+ - "C"
7
+ - "D"
8
+ "doc_to_text": "{{question.strip()}}\nA. {{choices[0]}}\nB. {{choices[1]}}\nC. {{choices[2]}}\n\
9
+ D. {{choices[3]}}{% if choices is defined and choices|length > 4 %}\nE. {{choices[4]}}{%\
10
+ \ endif %}{% if choices is defined and choices|length > 5 %}\nF. {{choices[5]}}{%\
11
+ \ endif %}\nAnswer:"
12
+ "tag": "tmlu_other_tasks"
13
+ "include": "_default_template_yaml"
14
+ "task": "tmlu_clinical_traditional_chinese_medicine"
15
+ "task_alias": "clinical traditional chinese medicine"
testbed/EleutherAI__lm-evaluation-harness/lm_eval/tasks/tmlu/default/tmlu_driving_rule.yaml ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "dataset_name": "driving_rule"
2
+ "description": "以下為台灣駕駛規則的單選題,請提供正確答案的選項。\n\n"
3
+ "doc_to_choice":
4
+ - "A"
5
+ - "B"
6
+ - "C"
7
+ - "D"
8
+ "doc_to_text": "{{question.strip()}}\nA. {{choices[0]}}\nB. {{choices[1]}}\nC. {{choices[2]}}\n\
9
+ D. {{choices[3]}}{% if choices is defined and choices|length > 4 %}\nE. {{choices[4]}}{%\
10
+ \ endif %}{% if choices is defined and choices|length > 5 %}\nF. {{choices[5]}}{%\
11
+ \ endif %}\nAnswer:"
12
+ "tag": "tmlu_taiwan_specific"
13
+ "include": "_default_template_yaml"
14
+ "task": "tmlu_driving_rule"
15
+ "task_alias": "driving rule"
testbed/EleutherAI__lm-evaluation-harness/lm_eval/tasks/tmlu/default/tmlu_lawyer_qualification.yaml ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "dataset_name": "lawyer_qualification"
2
+ "description": "以下為律師資格的單選題,請提供正確答案的選項。\n\n"
3
+ "doc_to_choice":
4
+ - "A"
5
+ - "B"
6
+ - "C"
7
+ - "D"
8
+ "doc_to_text": "{{question.strip()}}\nA. {{choices[0]}}\nB. {{choices[1]}}\nC. {{choices[2]}}\n\
9
+ D. {{choices[3]}}{% if choices is defined and choices|length > 4 %}\nE. {{choices[4]}}{%\
10
+ \ endif %}{% if choices is defined and choices|length > 5 %}\nF. {{choices[5]}}{%\
11
+ \ endif %}\nAnswer:"
12
+ "tag": "tmlu_humanities_tasks"
13
+ "include": "_default_template_yaml"
14
+ "task": "tmlu_lawyer_qualification"
15
+ "task_alias": "lawyer qualification"
testbed/EleutherAI__lm-evaluation-harness/lm_eval/tasks/tmlu/default/tmlu_nutritionist.yaml ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "dataset_name": "nutritionist"
2
+ "description": "以下為營養師的單選題,請提供正確答案的選項。\n\n"
3
+ "doc_to_choice":
4
+ - "A"
5
+ - "B"
6
+ - "C"
7
+ - "D"
8
+ "doc_to_text": "{{question.strip()}}\nA. {{choices[0]}}\nB. {{choices[1]}}\nC. {{choices[2]}}\n\
9
+ D. {{choices[3]}}{% if choices is defined and choices|length > 4 %}\nE. {{choices[4]}}{%\
10
+ \ endif %}{% if choices is defined and choices|length > 5 %}\nF. {{choices[5]}}{%\
11
+ \ endif %}\nAnswer:"
12
+ "tag": "tmlu_other_tasks"
13
+ "include": "_default_template_yaml"
14
+ "task": "tmlu_nutritionist"
15
+ "task_alias": "nutritionist"
testbed/EleutherAI__lm-evaluation-harness/lm_eval/tasks/tmlu/default/tmlu_taiwan_tourist_resources.yaml ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "dataset_name": "taiwan_tourist_resources"
2
+ "description": "以下為台灣觀光資源的單選題,請提供正確答案的選項。\n\n"
3
+ "doc_to_choice":
4
+ - "A"
5
+ - "B"
6
+ - "C"
7
+ - "D"
8
+ "doc_to_text": "{{question.strip()}}\nA. {{choices[0]}}\nB. {{choices[1]}}\nC. {{choices[2]}}\n\
9
+ D. {{choices[3]}}{% if choices is defined and choices|length > 4 %}\nE. {{choices[4]}}{%\
10
+ \ endif %}{% if choices is defined and choices|length > 5 %}\nF. {{choices[5]}}{%\
11
+ \ endif %}\nAnswer:"
12
+ "tag": "tmlu_taiwan_specific"
13
+ "include": "_default_template_yaml"
14
+ "task": "tmlu_taiwan_tourist_resources"
15
+ "task_alias": "taiwan tourist resources"
testbed/EleutherAI__lm-evaluation-harness/lm_eval/tasks/tmlu/default/tmlu_teacher_qualification.yaml ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "dataset_name": "teacher_qualification"
2
+ "description": "以下為教師資格的單選題,請提供正確答案的選項。\n\n"
3
+ "doc_to_choice":
4
+ - "A"
5
+ - "B"
6
+ - "C"
7
+ - "D"
8
+ "doc_to_text": "{{question.strip()}}\nA. {{choices[0]}}\nB. {{choices[1]}}\nC. {{choices[2]}}\n\
9
+ D. {{choices[3]}}{% if choices is defined and choices|length > 4 %}\nE. {{choices[4]}}{%\
10
+ \ endif %}{% if choices is defined and choices|length > 5 %}\nF. {{choices[5]}}{%\
11
+ \ endif %}\nAnswer:"
12
+ "tag": "tmlu_taiwan_specific"
13
+ "include": "_default_template_yaml"
14
+ "task": "tmlu_teacher_qualification"
15
+ "task_alias": "teacher qualification"
testbed/EleutherAI__lm-evaluation-harness/lm_eval/tasks/tmlu/default/tmlu_tour_guide.yaml ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "dataset_name": "tour_guide"
2
+ "description": "以下為導遊的單選題,請提供正確答案的選項。\n\n"
3
+ "doc_to_choice":
4
+ - "A"
5
+ - "B"
6
+ - "C"
7
+ - "D"
8
+ "doc_to_text": "{{question.strip()}}\nA. {{choices[0]}}\nB. {{choices[1]}}\nC. {{choices[2]}}\n\
9
+ D. {{choices[3]}}{% if choices is defined and choices|length > 4 %}\nE. {{choices[4]}}{%\
10
+ \ endif %}{% if choices is defined and choices|length > 5 %}\nF. {{choices[5]}}{%\
11
+ \ endif %}\nAnswer:"
12
+ "tag": "tmlu_humanities_tasks"
13
+ "include": "_default_template_yaml"
14
+ "task": "tmlu_tour_guide"
15
+ "task_alias": "tour guide"
testbed/EleutherAI__lm-evaluation-harness/lm_eval/tasks/tmlu/default/tmlu_tour_leader.yaml ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "dataset_name": "tour_leader"
2
+ "description": "以下為領隊的單選題,請提供正確答案的選項。\n\n"
3
+ "doc_to_choice":
4
+ - "A"
5
+ - "B"
6
+ - "C"
7
+ - "D"
8
+ "doc_to_text": "{{question.strip()}}\nA. {{choices[0]}}\nB. {{choices[1]}}\nC. {{choices[2]}}\n\
9
+ D. {{choices[3]}}{% if choices is defined and choices|length > 4 %}\nE. {{choices[4]}}{%\
10
+ \ endif %}{% if choices is defined and choices|length > 5 %}\nF. {{choices[5]}}{%\
11
+ \ endif %}\nAnswer:"
12
+ "tag": "tmlu_humanities_tasks"
13
+ "include": "_default_template_yaml"
14
+ "task": "tmlu_tour_leader"
15
+ "task_alias": "tour leader"
testbed/EleutherAI__lm-evaluation-harness/lm_eval/tasks/tmlu/default/utils.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import datasets
2
+
3
+
4
+ def process_docs(dataset: datasets.Dataset) -> datasets.Dataset:
5
+ def _helper(doc):
6
+ # modifies the contents of a single
7
+ # document in our dataset.
8
+ answer_list = ["A", "B", "C", "D"]
9
+ choices = [doc["A"], doc["B"], doc["C"], doc["D"]]
10
+ if doc.get("E", None):
11
+ answer_list.append("E")
12
+ choices.append(doc["E"])
13
+ if doc.get("F", None):
14
+ answer_list.append("F")
15
+ choices.append(doc["F"])
16
+ out_doc = {
17
+ "questions": doc["question"],
18
+ "choices": choices,
19
+ "goal": answer_list.index(doc["answer"]),
20
+ }
21
+ return out_doc
22
+
23
+ return dataset.map(_helper) # returns back a datasets.Dataset object
testbed/EleutherAI__lm-evaluation-harness/lm_eval/tasks/tmlu/subject.tsv ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ category subject name # Questions # Choices
2
+ civics AST_civics 分科測驗公民 57 4
3
+ geography AST_geography 分科測驗地理 58 4
4
+ civics CAP_civics 會考公民 73 4
5
+ geography CAP_geography 會考地理 45 4
6
+ civics GSAT_civics 學測公民 73 4
7
+ geography GSAT_geography 學測地理 49 4
8
+ accounting accountant 會計師 117 4
9
+ psychologist clinical_psychologist 臨床心理師 117 4
10
+ biology AST_biology 分科測驗生物 40 4
11
+ chemistry AST_chemistry 分科測驗化學 34 5
12
+ mathematics AST_mathematics 分科測驗數學 25 5
13
+ physics AST_physics 分科測驗物理 43 5
14
+ biology CAP_biology 會考生物 27 4
15
+ chemistry CAP_chemistry 會考化學 27 4
16
+ earth science CAP_earth_science 會考地球科學 15 4
17
+ mathematics CAP_mathematics 會考數學 115 4
18
+ physics CAP_physics 會考物理 15 4
19
+ biology GSAT_biology 學測生物 21 5
20
+ chemistry GSAT_chemistry 學測化學 29 5
21
+ earth science GSAT_earth_science 學測地球科學 24 5
22
+ mathematics GSAT_mathematics 學測數學 29 5
23
+ physics GSAT_physics 學測物理 24 5
24
+ Chinese AST_chinese 分科測驗國文 131 4
25
+ history AST_history 分科測驗歷史 56 4
26
+ Chinese CAP_chinese 會考國文 61 4
27
+ history CAP_history 會考歷史 56 4
28
+ Chinese GSAT_chinese 學測國文 97 4
29
+ history GSAT_history 學測歷史 85 4
30
+ Tour tour_guide 導遊 99 4
31
+ Tour tour_leader 領隊 145 4
32
+ law lawyer_qualification 律師資格 279 4
33
+ Taiwan Specific driving_rule 台灣駕駛規則 432 4
34
+ Taiwan Specific teacher_qualification 教師資格 75 4
35
+ Taiwan Specific taiwan_tourist_resources 台灣觀光資源 50 4
36
+ Medicine basic_traditional_chinese_medicine 中醫基礎醫學 159 4
37
+ Medicine clinical_traditional_chinese_medicine 中醫針灸 79 4
38
+ Nutritionist nutritionist 營養師 120 4
testbed/EleutherAI__lm-evaluation-harness/lm_eval/tasks/tmmluplus/README.md ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # TMMLU+
2
+
3
+ ### Paper
4
+
5
+ Title: `An Improved Traditional Chinese Evaluation Suite for Foundation Model`
6
+
7
+ Abstract: `We present TMMLU+, a comprehensive dataset designed for the Traditional Chinese massive multitask language understanding dataset. TMMLU+ is a multiple-choice question-answering dataset with 66 subjects from elementary to professional level. Compared to its predecessor, TMMLU, TMMLU+ is six times larger and boasts a more balanced subject distribution. We included benchmark results in TMMLU+ from closed-source models and 24 open-weight Chinese large language models of parameters ranging from 1.8B to 72B. Our findings reveal that Traditional Chinese models still trail behind their Simplified Chinese counterparts. Additionally, current large language models have yet to outperform human performance in average scores. We publicly release our dataset and the corresponding benchmark source code.`
8
+
9
+
10
+ Homepage: [https://huggingface.co/datasets/ikala/tmmluplus](https://huggingface.co/datasets/ikala/tmmluplus)
11
+
12
+
13
+ ### Citation
14
+
15
+ ```
16
+ @article{ikala2024improved,
17
+ title={An Improved Traditional Chinese Evaluation Suite for Foundation Model},
18
+ author={Tam, Zhi-Rui and Pai, Ya-Ting and Lee, Yen-Wei and Cheng, Sega and Shuai, Hong-Han},
19
+ journal={arXiv preprint arXiv:2403.01858},
20
+ year={2024}
21
+ }
22
+ ```
23
+
24
+ ### Groups and Tasks
25
+
26
+ #### Groups
27
+
28
+ * `tmmluplus`: `The dataset comprises 22,690 multiple-choice questions from 66 subjects ranging from primary to professional level. `
29
+
30
+ #### Tasks
31
+
32
+ The following tasks evaluate subjects in the TMMLU+ dataset using loglikelihood-based multiple-choice scoring:
33
+
34
+ * `tmmluplus_{subject_english}`
35
+
36
+ ### Checklist
37
+
38
+ For adding novel benchmarks/datasets to the library:
39
+ * [x] Is the task an existing benchmark in the literature?
40
+ * [x] Have you referenced the original paper that introduced the task?
41
+ * [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?
42
+
43
+
44
+ If other tasks on this dataset are already supported:
45
+ * [x] Is the "Main" variant of this task clearly denoted?
46
+ * [x] Have you provided a short sentence in a README on what each new variant adds / evaluates?
47
+ * [x] Have you noted which, if any, published evaluation setups are matched by this variant?
testbed/EleutherAI__lm-evaluation-harness/lm_eval/tasks/tmmluplus/default/_generate_configs.py ADDED
@@ -0,0 +1,211 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Take in a YAML, and output all "other" splits with this YAML
3
+ """
4
+
5
+ import argparse
6
+ import os
7
+
8
+ import pandas as pd
9
+ import yaml
10
+ from tqdm import tqdm
11
+
12
+
13
+ # Copy from https://github.com/iKala/ievals/blob/main/ievals/settings.py
14
+ # from TMMLU+ official example
15
+ categories = {
16
+ "STEM": [
17
+ "physics",
18
+ "chemistry",
19
+ "biology",
20
+ "computer science",
21
+ "math",
22
+ "engineering",
23
+ ],
24
+ "humanities": ["history", "philosophy", "law"],
25
+ "social_sciences": [
26
+ "politics",
27
+ "culture",
28
+ "economics",
29
+ "geography",
30
+ "psychology",
31
+ "education",
32
+ ],
33
+ "other": ["other", "business", "health"], # (business, health, misc.)
34
+ }
35
+
36
+ task_list = [
37
+ "engineering_math",
38
+ "dentistry",
39
+ "traditional_chinese_medicine_clinical_medicine",
40
+ "clinical_psychology",
41
+ "technical",
42
+ "culinary_skills",
43
+ "mechanical",
44
+ "logic_reasoning",
45
+ "real_estate",
46
+ "general_principles_of_law",
47
+ "finance_banking",
48
+ "anti_money_laundering",
49
+ "ttqav2",
50
+ "marketing_management",
51
+ "business_management",
52
+ "organic_chemistry",
53
+ "advance_chemistry",
54
+ "physics",
55
+ "secondary_physics",
56
+ "human_behavior",
57
+ "national_protection",
58
+ "jce_humanities",
59
+ "politic_science",
60
+ "agriculture",
61
+ "official_document_management",
62
+ "financial_analysis",
63
+ "pharmacy",
64
+ "educational_psychology",
65
+ "statistics_and_machine_learning",
66
+ "management_accounting",
67
+ "introduction_to_law",
68
+ "computer_science",
69
+ "veterinary_pathology",
70
+ "accounting",
71
+ "fire_science",
72
+ "optometry",
73
+ "insurance_studies",
74
+ "pharmacology",
75
+ "taxation",
76
+ "education_(profession_level)",
77
+ "economics",
78
+ "veterinary_pharmacology",
79
+ "nautical_science",
80
+ "occupational_therapy_for_psychological_disorders",
81
+ "trust_practice",
82
+ "geography_of_taiwan",
83
+ "physical_education",
84
+ "auditing",
85
+ "administrative_law",
86
+ "basic_medical_science",
87
+ "macroeconomics",
88
+ "trade",
89
+ "chinese_language_and_literature",
90
+ "tve_design",
91
+ "junior_science_exam",
92
+ "junior_math_exam",
93
+ "junior_chinese_exam",
94
+ "junior_social_studies",
95
+ "tve_mathematics",
96
+ "tve_chinese_language",
97
+ "tve_natural_sciences",
98
+ "junior_chemistry",
99
+ "music",
100
+ "education",
101
+ "three_principles_of_people",
102
+ "taiwanese_hokkien",
103
+ ]
104
+ subject2name = {}
105
+ # subject2category = {}
106
+ SUBJECTS = {}
107
+
108
+
109
+ def parse_args():
110
+ parser = argparse.ArgumentParser()
111
+ parser.add_argument("--base_yaml_path", required=True)
112
+ parser.add_argument("--save_prefix_path", default="tmmluplus")
113
+ parser.add_argument("--cot_prompt_path", default=None)
114
+ parser.add_argument("--task_prefix", default="")
115
+ parser.add_argument("--group_prefix", default="")
116
+ parser.add_argument("--subject_file", default="subject.tsv")
117
+ return parser.parse_args()
118
+
119
+
120
+ if __name__ == "__main__":
121
+ args = parse_args()
122
+ from pathlib import Path
123
+
124
+ # Initialization
125
+ SUBJECT_FILE = Path(__file__).parent / Path(args.subject_file)
126
+
127
+ df = pd.read_csv(SUBJECT_FILE, delimiter="\t")
128
+
129
+ for _, row in df.iterrows():
130
+ for _c in categories:
131
+ if row["subject"] in SUBJECTS:
132
+ raise ValueError("Duplicate tasks.")
133
+ if row["category"] in categories[_c]: # append new item into SUBJECTS
134
+ SUBJECTS[row["subject"]] = _c
135
+ subject2name[row["subject"]] = row["name"]
136
+ break
137
+ # End of SUBJECTS initialization
138
+
139
+ # get filename of base_yaml so we can `"include": ` it in our "other" YAMLs.
140
+ base_yaml_name = os.path.split(args.base_yaml_path)[-1]
141
+ with open(args.base_yaml_path) as f:
142
+ base_yaml = yaml.full_load(f)
143
+
144
+ if args.cot_prompt_path is not None:
145
+ import json
146
+
147
+ with open(args.cot_prompt_path) as f:
148
+ cot_file = json.load(f)
149
+
150
+ ALL_CATEGORIES = []
151
+ for subject, category in tqdm(SUBJECTS.items()):
152
+ if category not in ALL_CATEGORIES:
153
+ ALL_CATEGORIES.append(category)
154
+
155
+ if args.cot_prompt_path is not None:
156
+ description = cot_file[subject]
157
+ else:
158
+ name_of_subject = subject2name[subject].replace("_", " ")
159
+ description = f"以下為{name_of_subject}的單選題,請提供正確答案的選項。\n\n"
160
+ # description = f"The following are multiple choice questions (with answers) about {' '.join(subject.split('_'))}.\n\n"
161
+
162
+ yaml_dict = {
163
+ "include": base_yaml_name,
164
+ "group": f"tmmluplus_{args.task_prefix}_{category}"
165
+ if args.task_prefix != ""
166
+ else f"tmmluplus_{category}",
167
+ "group_alias": category.replace("_", " "),
168
+ "task": f"tmmluplus_{args.task_prefix}_{subject}"
169
+ if args.task_prefix != ""
170
+ else f"tmmluplus_{subject}",
171
+ "task_alias": subject.replace("_", " "),
172
+ "dataset_name": subject,
173
+ "description": description,
174
+ }
175
+
176
+ file_save_path = args.save_prefix_path + f"_{subject}.yaml"
177
+ # eval_logger.info(f"Saving yaml for subset {subject} to {file_save_path}")
178
+ with open(file_save_path, "w") as yaml_file:
179
+ yaml.dump(
180
+ yaml_dict,
181
+ yaml_file,
182
+ # width=float("inf"),
183
+ allow_unicode=True,
184
+ default_style='"',
185
+ )
186
+
187
+ if args.task_prefix != "":
188
+ mmlu_subcategories = [
189
+ f"tmmluplus_{args.task_prefix}_{category}" for category in ALL_CATEGORIES
190
+ ]
191
+ else:
192
+ mmlu_subcategories = [f"tmmluplus_{category}" for category in ALL_CATEGORIES]
193
+
194
+ if args.group_prefix != "":
195
+ file_save_path = args.group_prefix + ".yaml"
196
+ else:
197
+ file_save_path = args.save_prefix_path + ".yaml"
198
+
199
+ # eval_logger.info(f"Saving benchmark config to {file_save_path}")
200
+ with open(file_save_path, "w") as yaml_file:
201
+ yaml.dump(
202
+ {
203
+ "group": f"tmmluplus_{args.task_prefix}"
204
+ if args.task_prefix != ""
205
+ else "tmmluplus",
206
+ "task": mmlu_subcategories,
207
+ },
208
+ yaml_file,
209
+ indent=4,
210
+ default_flow_style=False,
211
+ )
testbed/EleutherAI__lm-evaluation-harness/lm_eval/tasks/tmmluplus/default/_tmmluplus.yaml ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ group: tmmluplus
2
+ task:
3
+ - tmmluplus_other
4
+ - tmmluplus_social_sciences
5
+ - tmmluplus_humanities
6
+ - tmmluplus_STEM
7
+ aggregate_metric_list:
8
+ - metric: acc
9
+ weight_by_size: True
10
+ - metric: acc_norm
11
+ weight_by_size: True
12
+ metadata:
13
+ version: 2.0
testbed/EleutherAI__lm-evaluation-harness/lm_eval/tasks/tmmluplus/default/_tmmluplus_STEM.yaml ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ group: tmmluplus_STEM
2
+ task:
3
+ - tmmluplus_STEM_tasks
4
+ aggregate_metric_list:
5
+ - metric: acc
6
+ weight_by_size: True
7
+ - metric: acc_norm
8
+ weight_by_size: True
9
+ metadata:
10
+ version: 2.0
testbed/EleutherAI__lm-evaluation-harness/lm_eval/tasks/tmmluplus/default/_tmmluplus_humanities.yaml ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ group: tmmluplus_humanities
2
+ task:
3
+ - tmmluplus_humanities_tasks
4
+ aggregate_metric_list:
5
+ - metric: acc
6
+ weight_by_size: True
7
+ - metric: acc_norm
8
+ weight_by_size: True
9
+ metadata:
10
+ version: 2.0