__main__.py 20.6 KB
Newer Older
1
2
3
import argparse
import json
import logging
lintangsutawika's avatar
lintangsutawika committed
4
import os
5
import sys
6
from functools import partial
7
from pathlib import Path
haileyschoelkopf's avatar
haileyschoelkopf committed
8
from typing import Union
Leo Gao's avatar
Leo Gao committed
9

Baber Abbasi's avatar
Baber Abbasi committed
10
11
12
13
14
15
16
17
18
19
20
21

def try_parse_json(value: str) -> Union[str, dict, None]:
    if value is None:
        return None
    try:
        return json.loads(value)
    except json.JSONDecodeError:
        if "{" in value:
            raise argparse.ArgumentTypeError(
                f"Invalid JSON: {value}. Hint: Use double quotes for JSON strings."
            )
        return value
Fabrizio Milo's avatar
Fabrizio Milo committed
22

23

24
25
26
def _int_or_none_list_arg_type(
    min_len: int, max_len: int, defaults: str, value: str, split_char: str = ","
):
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
    def parse_value(item):
        item = item.strip().lower()
        if item == "none":
            return None
        try:
            return int(item)
        except ValueError:
            raise argparse.ArgumentTypeError(f"{item} is not an integer or None")

    items = [parse_value(v) for v in value.split(split_char)]
    num_items = len(items)

    if num_items == 1:
        # Makes downstream handling the same for single and multiple values
        items = items * max_len
42
    elif num_items < min_len or num_items > max_len:
43
44
45
        raise argparse.ArgumentTypeError(
            f"Argument requires {max_len} integers or None, separated by '{split_char}'"
        )
46
47
48
49
50
51
52
53
54
    elif num_items != max_len:
        logging.warning(
            f"Argument requires {max_len} integers or None, separated by '{split_char}'. "
            "Missing values will be filled with defaults."
        )
        default_items = [parse_value(v) for v in defaults.split(split_char)]
        items.extend(
            default_items[num_items:]
        )  # extend items list with missing defaults
55
56
57
58

    return items


59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
def check_argument_types(parser: argparse.ArgumentParser):
    """
    Check to make sure all CLI args are typed, raises error if not
    """
    for action in parser._actions:
        if action.dest != "help" and not action.const:
            if action.type is None:
                raise ValueError(
                    f"Argument '{action.dest}' doesn't have a type specified."
                )
            else:
                continue


def setup_parser() -> argparse.ArgumentParser:
lintangsutawika's avatar
lintangsutawika committed
74
    parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter)
75
    parser.add_argument(
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
        "--config",
        "-C",
        default=None,
        type=str,
        metavar="DIR/file.yaml",
        action=TrackExplicitAction,
        help="Path to config with all arguments for `lm-eval`",
    )
    parser.add_argument(
        "--model",
        "-m",
        type=str,
        default="hf",
        action=TrackExplicitAction,
        help="Name of model e.g. `hf`",
91
    )
lintangsutawika's avatar
lintangsutawika committed
92
93
    parser.add_argument(
        "--tasks",
Baber Abbasi's avatar
Baber Abbasi committed
94
        "-t",
lintangsutawika's avatar
lintangsutawika committed
95
        default=None,
96
        type=str,
97
        action=TrackExplicitAction,
98
        metavar="task1,task2",
99
        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",
lintangsutawika's avatar
lintangsutawika committed
100
    )
101
102
    parser.add_argument(
        "--model_args",
Baber Abbasi's avatar
Baber Abbasi committed
103
        "-a",
104
        default="",
105
        action=TrackExplicitAction,
Baber Abbasi's avatar
Baber Abbasi committed
106
107
        type=try_parse_json,
        help="""Comma separated string or JSON formatted arguments for model, e.g. `pretrained=EleutherAI/pythia-160m,dtype=float32` or '{"pretrained":"EleutherAI/pythia-160m","dtype":"float32"}'""",
108
    )
lintangsutawika's avatar
lintangsutawika committed
109
    parser.add_argument(
110
        "--num_fewshot",
Baber Abbasi's avatar
Baber Abbasi committed
111
        "-f",
112
        type=int,
113
        default=None,
114
        action=TrackExplicitAction,
115
        metavar="N",
116
117
        help="Number of examples in few-shot context",
    )
118
119
    parser.add_argument(
        "--batch_size",
Baber Abbasi's avatar
Baber Abbasi committed
120
        "-b",
121
        type=str,
122
        action=TrackExplicitAction,
123
124
125
126
        default=1,
        metavar="auto|auto:N|N",
        help="Acceptable values are 'auto', 'auto:N' or N, where N is an integer. Default 1.",
    )
lintangsutawika's avatar
lintangsutawika committed
127
128
129
130
    parser.add_argument(
        "--max_batch_size",
        type=int,
        default=None,
131
        action=TrackExplicitAction,
132
133
        metavar="N",
        help="Maximal batch size to try with --batch_size auto.",
lintangsutawika's avatar
lintangsutawika committed
134
    )
135
136
137
138
    parser.add_argument(
        "--device",
        type=str,
        default=None,
139
        action=TrackExplicitAction,
140
        help="Device to use (e.g. cuda, cuda:0, cpu).",
141
142
143
    )
    parser.add_argument(
        "--output_path",
Baber Abbasi's avatar
Baber Abbasi committed
144
        "-o",
145
146
        default=None,
        type=str,
147
        action=TrackExplicitAction,
148
        metavar="DIR|DIR/file.json",
Niccolò Ajroldi's avatar
Niccolò Ajroldi committed
149
        help="Path where result metrics will be saved. Can be either a directory or a .json file. 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.",
150
    )
lintangsutawika's avatar
lintangsutawika committed
151
152
    parser.add_argument(
        "--limit",
Baber Abbasi's avatar
Baber Abbasi committed
153
        "-L",
lintangsutawika's avatar
lintangsutawika committed
154
155
        type=float,
        default=None,
156
        action=TrackExplicitAction,
157
        metavar="N|0<N<1",
lintangsutawika's avatar
lintangsutawika committed
158
159
160
        help="Limit the number of examples per task. "
        "If <1, limit is a percentage of the total number of examples.",
    )
161
162
163
164
165
    parser.add_argument(
        "--samples",
        "-E",
        default=None,
        type=str,
166
        action=TrackExplicitAction,
167
168
169
        metavar="/path/to/json",
        help='JSON string or path to JSON file containing doc indices of selected examples to test. Format: {"task_name":[indices],...}',
    )
170
171
    parser.add_argument(
        "--use_cache",
Baber Abbasi's avatar
Baber Abbasi committed
172
        "-c",
173
        type=str,
174
        action=TrackExplicitAction,
175
        default=None,
176
        metavar="DIR",
177
178
        help="A path to a sqlite db file for caching model responses. `None` if not caching.",
    )
179
180
181
182
    parser.add_argument(
        "--cache_requests",
        type=str,
        default=None,
183
        action=TrackExplicitAction,
184
185
186
        choices=["true", "refresh", "delete"],
        help="Speed up evaluation by caching the building of dataset requests. `None` if not caching.",
    )
187
188
    parser.add_argument(
        "--check_integrity",
189
        action=TrackExplicitStoreTrue,
190
        help="Whether to run the relevant part of the test suite for the tasks.",
191
192
193
    )
    parser.add_argument(
        "--write_out",
Baber Abbasi's avatar
Baber Abbasi committed
194
        "-w",
195
        action=TrackExplicitStoreTrue,
196
        default=False,
197
        help="Prints the prompt for the first few documents.",
198
199
200
    )
    parser.add_argument(
        "--log_samples",
Baber Abbasi's avatar
Baber Abbasi committed
201
        "-s",
202
        action=TrackExplicitStoreTrue,
203
        default=False,
204
        help="If True, write out all model outputs and documents for per-sample measurement and post-hoc analysis. Use with --output_path.",
205
    )
KonradSzafer's avatar
KonradSzafer committed
206
207
208
209
    parser.add_argument(
        "--system_instruction",
        type=str,
        default=None,
210
        action=TrackExplicitAction,
KonradSzafer's avatar
KonradSzafer committed
211
212
213
214
        help="System instruction to be used in the prompt",
    )
    parser.add_argument(
        "--apply_chat_template",
215
216
        type=str,
        nargs="?",
217
        action=TrackExplicitAction,
218
        const=True,
KonradSzafer's avatar
KonradSzafer committed
219
        default=False,
220
221
222
223
224
225
        help=(
            "If True, apply chat template to the prompt. "
            "Providing `--apply_chat_template` without an argument will apply the default chat template to the prompt. "
            "To apply a specific template from the available list of templates, provide the template name as an argument. "
            "E.g. `--apply_chat_template template_name`"
        ),
KonradSzafer's avatar
KonradSzafer committed
226
227
228
    )
    parser.add_argument(
        "--fewshot_as_multiturn",
229
        action=TrackExplicitStoreTrue,
KonradSzafer's avatar
KonradSzafer committed
230
231
232
        default=False,
        help="If True, uses the fewshot as a multi-turn conversation",
    )
233
234
    parser.add_argument(
        "--show_config",
235
        action=TrackExplicitStoreTrue,
236
237
238
        default=False,
        help="If True, shows the the full config of all tasks at the end of the evaluation.",
    )
239
240
241
242
    parser.add_argument(
        "--include_path",
        type=str,
        default=None,
243
        action=TrackExplicitAction,
244
        metavar="DIR",
245
246
        help="Additional path to include if there are external tasks to include.",
    )
247
248
    parser.add_argument(
        "--gen_kwargs",
Baber Abbasi's avatar
Baber Abbasi committed
249
        type=try_parse_json,
250
        default=None,
251
        action=TrackExplicitAction,
USVSN Sai Prashanth's avatar
USVSN Sai Prashanth committed
252
        help=(
Baber Abbasi's avatar
Baber Abbasi committed
253
254
            "Either comma delimited string or JSON formatted arguments for model generation on greedy_until tasks,"
            """ e.g. '{"temperature":0.7,"until":["hello"]}' or temperature=0,top_p=0.1."""
lintangsutawika's avatar
lintangsutawika committed
255
256
257
        ),
    )
    parser.add_argument(
lintangsutawika's avatar
lintangsutawika committed
258
        "--verbosity",
Baber Abbasi's avatar
Baber Abbasi committed
259
260
        "-v",
        type=str.upper,
Lintang Sutawika's avatar
Lintang Sutawika committed
261
        default=None,
262
        action=TrackExplicitAction,
263
        metavar="CRITICAL|ERROR|WARNING|INFO|DEBUG",
Lintang Sutawika's avatar
Lintang Sutawika committed
264
        help="(Deprecated) Controls logging verbosity level. Use the `LOGLEVEL` environment variable instead. Set to DEBUG for detailed output when testing or adding new task configurations.",
265
    )
266
267
    parser.add_argument(
        "--wandb_args",
268
        type=str,
269
        default="",
270
        action=TrackExplicitAction,
271
272
        help="Comma separated string arguments passed to wandb.init, e.g. `project=lm-eval,job_type=eval",
    )
273
274
275
276
    parser.add_argument(
        "--wandb_config_args",
        type=str,
        default="",
277
        action=TrackExplicitAction,
278
279
        help="Comma separated string arguments passed to wandb.config.update. Use this to trace parameters that aren't already traced by default. eg. `lr=0.01,repeats=3",
    )
280
281
282
283
    parser.add_argument(
        "--hf_hub_log_args",
        type=str,
        default="",
284
        action=TrackExplicitAction,
285
286
        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`",
    )
Baber Abbasi's avatar
Baber Abbasi committed
287
288
289
    parser.add_argument(
        "--predict_only",
        "-x",
290
        action=TrackExplicitStoreTrue,
Baber Abbasi's avatar
Baber Abbasi committed
291
292
293
        default=False,
        help="Use with --log_samples. Only model outputs will be saved and metrics will not be evaluated.",
    )
294
    default_seed_string = "0,1234,1234,1234"
295
296
    parser.add_argument(
        "--seed",
297
        type=partial(_int_or_none_list_arg_type, 3, 4, default_seed_string),
298
        action=TrackExplicitAction,
299
        default=default_seed_string,  # for backward compatibility
300
        help=(
301
302
            "Set seed for python's random, numpy, torch, and fewshot sampling.\n"
            "Accepts a comma-separated list of 4 values for python's random, numpy, torch, and fewshot sampling seeds, "
Sadra Barikbin's avatar
Sadra Barikbin committed
303
            "respectively, or a single integer to set the same seed for all four.\n"
304
305
306
307
308
            f"The values are either an integer or 'None' to not set the seed. Default is `{default_seed_string}` "
            "(for backward compatibility).\n"
            "E.g. `--seed 0,None,8,52` sets `random.seed(0)`, `torch.manual_seed(8)`, and fewshot sampling seed to 52. "
            "Here numpy's seed is not set since the second value is `None`.\n"
            "E.g, `--seed 42` sets all four seeds to 42."
309
310
        ),
    )
311
312
    parser.add_argument(
        "--trust_remote_code",
313
        action=TrackExplicitStoreTrue,
314
315
        help="Sets trust_remote_code to True to execute code to create HF Datasets from the Hub",
    )
Hojin Lee's avatar
Hojin Lee committed
316
317
    parser.add_argument(
        "--confirm_run_unsafe_code",
318
        action=TrackExplicitStoreTrue,
Hojin Lee's avatar
Hojin Lee committed
319
320
        help="Confirm that you understand the risks of running unsafe code for tasks that require it",
    )
Baber Abbasi's avatar
Baber Abbasi committed
321
322
323
324
    parser.add_argument(
        "--metadata",
        type=json.loads,
        default=None,
325
        action=TrackExplicitAction,
Baber Abbasi's avatar
Baber Abbasi committed
326
327
        help="""JSON string metadata to pass to task configs, for example '{"max_seq_lengths":[4096,8192]}'. Will be merged with model_args. Can also be set in task config.""",
    )
328
329
330
331
332
    return parser


def parse_eval_args(parser: argparse.ArgumentParser) -> argparse.Namespace:
    check_argument_types(parser)
Jason Phang's avatar
Jason Phang committed
333
334
    return parser.parse_args()

Fabrizio Milo's avatar
Fabrizio Milo committed
335

haileyschoelkopf's avatar
haileyschoelkopf committed
336
337
338
def cli_evaluate(args: Union[argparse.Namespace, None] = None) -> None:
    if not args:
        # we allow for args to be passed externally, else we parse them ourselves
339
340
        parser = setup_parser()
        args = parse_eval_args(parser)
haileyschoelkopf's avatar
haileyschoelkopf committed
341

Baber's avatar
nit  
Baber committed
342
    cfg = EvaluationConfig.from_cli(args)
343

344
345
346
347
348
349
350
351
352
353
354
    # defer loading `lm_eval` submodules for faster CLI load
    from lm_eval import evaluator, utils
    from lm_eval.evaluator import request_caching_arg_to_dict
    from lm_eval.loggers import EvaluationTracker, WandbLogger
    from lm_eval.tasks import TaskManager
    from lm_eval.utils import (
        handle_non_serializable,
        make_table,
        simple_parse_args_string,
    )

355
    if args.wandb_args:
Baber's avatar
nit  
Baber committed
356
        wandb_logger = WandbLogger(cfg.wandb_args, cfg.wandb_config_args)
357

Baber's avatar
nit  
Baber committed
358
    utils.setup_logging(cfg.verbosity)
Lintang Sutawika's avatar
Lintang Sutawika committed
359
    eval_logger = logging.getLogger(__name__)
haileyschoelkopf's avatar
haileyschoelkopf committed
360
    os.environ["TOKENIZERS_PARALLELISM"] = "false"
Fabrizio Milo's avatar
Fabrizio Milo committed
361

362
    # update the evaluation tracker args with the output path and the HF token
Baber's avatar
nit  
Baber committed
363
364
    if cfg.output_path:
        cfg.hf_hub_log_args["output_path"] = cfg.output_path
365

366
    if os.environ.get("HF_TOKEN", None):
Baber's avatar
nit  
Baber committed
367
        cfg.hf_hub_log_args["token"] = os.environ.get("HF_TOKEN")
artemorloff's avatar
artemorloff committed
368

Baber's avatar
nit  
Baber committed
369
    evaluation_tracker_args = cfg.hf_hub_log_args
370
371
    evaluation_tracker = EvaluationTracker(**evaluation_tracker_args)

Baber's avatar
nit  
Baber committed
372
373
    if cfg.predict_only:
        cfg.log_samples = True
374

Baber's avatar
nit  
Baber committed
375
    if (cfg.log_samples or cfg.predict_only) and not cfg.output_path:
376
377
378
        raise ValueError(
            "Specify --output_path if providing --log_samples or --predict_only"
        )
Baber Abbasi's avatar
Baber Abbasi committed
379

Baber's avatar
nit  
Baber committed
380
    if cfg.fewshot_as_multiturn and cfg.apply_chat_template is False:
KonradSzafer's avatar
KonradSzafer committed
381
        raise ValueError(
382
            "When `fewshot_as_multiturn` is selected, `apply_chat_template` must be set (either to `True` or to the chosen template name)."
KonradSzafer's avatar
KonradSzafer committed
383
384
        )

Baber's avatar
nit  
Baber committed
385
386
    if cfg.include_path is not None:
        eval_logger.info(f"Including path: {cfg.include_path}")
387

Baber's avatar
nit  
Baber committed
388
389
    metadata = (cfg.model_args) | (cfg.metadata)
    cfg.metadata = metadata
Baber Abbasi's avatar
Baber Abbasi committed
390

artemorloff's avatar
artemorloff committed
391
    # task_manager = TaskManager(include_path=config["include_path"], metadata=metadata)
Baber's avatar
nit  
Baber committed
392
    task_manager = TaskManager(include_path=cfg.include_path, metadata=metadata)
Fabrizio Milo's avatar
Fabrizio Milo committed
393

Baber's avatar
nit  
Baber committed
394
    if "push_samples_to_hub" in evaluation_tracker_args and not cfg.log_samples:
395
396
397
398
        eval_logger.warning(
            "Pushing samples to the Hub requires --log_samples to be set. Samples will not be pushed to the Hub."
        )

Baber's avatar
nit  
Baber committed
399
    if cfg.limit:
lintangsutawika's avatar
lintangsutawika committed
400
401
402
        eval_logger.warning(
            " --limit SHOULD ONLY BE USED FOR TESTING."
            "REAL METRICS SHOULD NOT BE COMPUTED USING LIMIT."
Fabrizio Milo's avatar
Fabrizio Milo committed
403
        )
artemorloff's avatar
artemorloff committed
404

Baber's avatar
nit  
Baber committed
405
406
407
408
    if cfg.samples:
        assert cfg.limit is None, "If --samples is not None, then --limit must be None."
        if (samples := Path(cfg.samples)).is_file():
            cfg.samples = json.loads(samples.read_text())
409
        else:
Baber's avatar
nit  
Baber committed
410
            cfg.samples = json.loads(cfg.samples)
lintangsutawika's avatar
lintangsutawika committed
411

Baber's avatar
nit  
Baber committed
412
    if cfg.tasks is None:
413
414
        eval_logger.error("Need to specify task to evaluate.")
        sys.exit()
Baber's avatar
nit  
Baber committed
415
    elif cfg.tasks == "list":
416
417
        print(task_manager.list_all_tasks())
        sys.exit()
Baber's avatar
nit  
Baber committed
418
    elif cfg.tasks == "list_groups":
419
420
        print(task_manager.list_all_tasks(list_subtasks=False, list_tags=False))
        sys.exit()
Baber's avatar
nit  
Baber committed
421
    elif cfg.tasks == "list_tags":
422
423
        print(task_manager.list_all_tasks(list_groups=False, list_subtasks=False))
        sys.exit()
Baber's avatar
nit  
Baber committed
424
    elif cfg.tasks == "list_subtasks":
425
        print(task_manager.list_all_tasks(list_groups=False, list_tags=False))
Lintang Sutawika's avatar
Lintang Sutawika committed
426
        sys.exit()
Jason Phang's avatar
Jason Phang committed
427
    else:
Baber's avatar
nit  
Baber committed
428
        if os.path.isdir(cfg.tasks):
429
            import glob
430
431

            task_names = []
Baber's avatar
nit  
Baber committed
432
            yaml_path = os.path.join(cfg.tasks, "*.yaml")
433
            for yaml_file in glob.glob(yaml_path):
Baber's avatar
nit  
Baber committed
434
435
                cfg = utils.load_yaml_config(yaml_file)
                task_names.append(cfg)
436
        else:
Baber's avatar
nit  
Baber committed
437
            task_list = cfg.tasks.split(",")
438
439
            task_names = task_manager.match_tasks(task_list)
            for task in [task for task in task_list if task not in task_names]:
440
                if os.path.isfile(task):
Baber's avatar
nit  
Baber committed
441
442
                    cfg = utils.load_yaml_config(task)
                    task_names.append(cfg)
443
            task_missing = [
444
                task for task in task_list if task not in task_names and "*" not in task
445
            ]  # we don't want errors if a wildcard ("*") task name was used
lintangsutawika's avatar
lintangsutawika committed
446

baberabb's avatar
baberabb committed
447
448
449
450
            if task_missing:
                missing = ", ".join(task_missing)
                eval_logger.error(
                    f"Tasks were not found: {missing}\n"
lintangsutawika's avatar
lintangsutawika committed
451
                    f"{utils.SPACING}Try `lm-eval --tasks list` for list of available tasks",
baberabb's avatar
baberabb committed
452
453
                )
                raise ValueError(
454
                    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."
baberabb's avatar
baberabb committed
455
                )
Baber's avatar
nit  
Baber committed
456
        cfg.tasks = task_names
lintangsutawika's avatar
lintangsutawika committed
457

458
    # Respect user's value passed in via CLI, otherwise default to True and add to comma-separated model args
Baber's avatar
nit  
Baber committed
459
    if cfg.trust_remote_code:
460
461
        eval_logger.info(
            "Passed `--trust_remote_code`, setting environment variable `HF_DATASETS_TRUST_REMOTE_CODE=true`"
462
        )
463
464
465
466
467
468
469
        # HACK: import datasets and override its HF_DATASETS_TRUST_REMOTE_CODE value internally,
        # because it's already been determined based on the prior env var before launching our
        # script--`datasets` gets imported by lm_eval internally before these lines can update the env.
        import datasets

        datasets.config.HF_DATASETS_TRUST_REMOTE_CODE = True

Baber's avatar
nit  
Baber committed
470
        cfg.model_args["trust_remote_code"] = True
471
472
473
474
    (
        eval_logger.info(f"Selected Tasks: {task_names}")
        if eval_logger.getEffectiveLevel() >= logging.INFO
        else print(f"Selected Tasks: {task_names}")
Baber Abbasi's avatar
Baber Abbasi committed
475
    )
476

477
    request_caching_args = request_caching_arg_to_dict(
Baber's avatar
nit  
Baber committed
478
        cache_requests=cfg.cache_requests
479
    )
Baber's avatar
nit  
Baber committed
480
    cfg.request_caching_args = request_caching_args
artemorloff's avatar
artemorloff committed
481

482
    results = evaluator.simple_evaluate(
Baber's avatar
nit  
Baber committed
483
484
485
486
487
488
489
490
491
492
        model=cfg.model,
        model_args=cfg.model_args,
        tasks=cfg.tasks,
        num_fewshot=cfg.num_fewshot,
        batch_size=cfg.batch_size,
        max_batch_size=cfg.max_batch_size,
        device=cfg.device,
        use_cache=cfg.use_cache,
        cache_requests=cfg.request_caching_args.get("cache_requests", False),
        rewrite_requests_cache=cfg.request_caching_args.get(
493
494
            "rewrite_requests_cache", False
        ),
Baber's avatar
nit  
Baber committed
495
        delete_requests_cache=cfg.request_caching_args.get(
496
497
            "delete_requests_cache", False
        ),
Baber's avatar
nit  
Baber committed
498
499
500
501
502
        limit=cfg.limit,
        samples=cfg.samples,
        check_integrity=cfg.check_integrity,
        write_out=cfg.write_out,
        log_samples=cfg.log_samples,
KonradSzafer's avatar
KonradSzafer committed
503
        evaluation_tracker=evaluation_tracker,
Baber's avatar
nit  
Baber committed
504
505
506
507
        system_instruction=cfg.system_instruction,
        apply_chat_template=cfg.apply_chat_template,
        fewshot_as_multiturn=cfg.fewshot_as_multiturn,
        gen_kwargs=cfg.gen_kwargs,
508
        task_manager=task_manager,
Baber's avatar
nit  
Baber committed
509
510
511
512
513
514
515
516
        verbosity=cfg.verbosity,
        predict_only=cfg.predict_only,
        random_seed=cfg.seed[0] if cfg.seed else None,
        numpy_random_seed=cfg.seed[1] if cfg.seed else None,
        torch_random_seed=cfg.seed[2] if cfg.seed else None,
        fewshot_random_seed=cfg.seed[3] if cfg.seed else None,
        confirm_run_unsafe_code=cfg.confirm_run_unsafe_code,
        metadata=cfg.metadata,
517
    )
518

519
    if results is not None:
Baber's avatar
nit  
Baber committed
520
        if cfg.log_samples:
521
            samples = results.pop("samples")
522
        dumped = json.dumps(
523
            results, indent=2, default=handle_non_serializable, ensure_ascii=False
524
        )
Baber's avatar
nit  
Baber committed
525
        if cfg.show_config:
526
            print(dumped)
527

528
529
        batch_sizes = ",".join(map(str, results["config"]["batch_sizes"]))

530
        # Add W&B logging
Baber's avatar
nit  
Baber committed
531
        if cfg.wandb_args:
532
533
534
            try:
                wandb_logger.post_init(results)
                wandb_logger.log_eval_result()
Baber's avatar
nit  
Baber committed
535
                if cfg.log_samples:
536
537
538
539
                    wandb_logger.log_eval_samples(samples)
            except Exception as e:
                eval_logger.info(f"Logging to Weights and Biases failed due to {e}")

KonradSzafer's avatar
KonradSzafer committed
540
541
542
        evaluation_tracker.save_results_aggregated(
            results=results, samples=samples if args.log_samples else None
        )
543

Baber's avatar
nit  
Baber committed
544
        if cfg.log_samples:
545
            for task_name, _ in results["configs"].items():
546
547
548
                evaluation_tracker.save_results_samples(
                    task_name=task_name, samples=samples[task_name]
                )
lintangsutawika's avatar
lintangsutawika committed
549

550
551
552
553
554
555
        if (
            evaluation_tracker.push_results_to_hub
            or evaluation_tracker.push_samples_to_hub
        ):
            evaluation_tracker.recreate_metadata_card()

556
        print(
Baber's avatar
nit  
Baber committed
557
558
            f"{cfg.model} ({cfg.model_args}), gen_kwargs: ({cfg.gen_kwargs}), limit: {cfg.limit}, num_fewshot: {cfg.num_fewshot}, "
            f"batch_size: {cfg.batch_size}{f' ({batch_sizes})' if batch_sizes else ''}"
559
        )
560
        print(make_table(results))
lintangsutawika's avatar
lintangsutawika committed
561
        if "groups" in results:
562
            print(make_table(results, "groups"))
Jason Phang's avatar
lib  
Jason Phang committed
563

Baber's avatar
nit  
Baber committed
564
        if cfg.wandb_args:
565
566
567
            # Tear down wandb run once all the logging is done.
            wandb_logger.run.finish()

568

Jason Phang's avatar
Jason Phang committed
569
if __name__ == "__main__":
haileyschoelkopf's avatar
haileyschoelkopf committed
570
    cli_evaluate()