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

10
11
import numpy as np

12
from lm_eval import evaluator, utils
13
from lm_eval.api.registry import ALL_TASKS
14
15
from lm_eval.tasks import include_path, initialize_tasks
from lm_eval.utils import make_table
lintangsutawika's avatar
format  
lintangsutawika committed
16

17

18
def _handle_non_serializable(o):
19
    if isinstance(o, np.int64) or isinstance(o, np.int32):
20
21
22
        return int(o)
    elif isinstance(o, set):
        return list(o)
23
24
    else:
        return str(o)
Fabrizio Milo's avatar
Fabrizio Milo committed
25

26

haileyschoelkopf's avatar
haileyschoelkopf committed
27
def parse_eval_args() -> argparse.Namespace:
lintangsutawika's avatar
lintangsutawika committed
28
    parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter)
Baber Abbasi's avatar
Baber Abbasi committed
29
    parser.add_argument("--model", "-m", default="hf", help="Name of model e.g. `hf`")
lintangsutawika's avatar
lintangsutawika committed
30
31
    parser.add_argument(
        "--tasks",
Baber Abbasi's avatar
Baber Abbasi committed
32
        "-t",
lintangsutawika's avatar
lintangsutawika committed
33
        default=None,
34
        metavar="task1,task2",
lintangsutawika's avatar
lintangsutawika committed
35
        help="To get full list of tasks, use the command lm-eval --tasks list",
lintangsutawika's avatar
lintangsutawika committed
36
    )
37
38
    parser.add_argument(
        "--model_args",
Baber Abbasi's avatar
Baber Abbasi committed
39
        "-a",
40
        default="",
41
        help="Comma separated string arguments for model, e.g. `pretrained=EleutherAI/pythia-160m,dtype=float32`",
42
    )
lintangsutawika's avatar
lintangsutawika committed
43
    parser.add_argument(
44
        "--num_fewshot",
Baber Abbasi's avatar
Baber Abbasi committed
45
        "-f",
46
        type=int,
47
        default=None,
48
        metavar="N",
49
50
        help="Number of examples in few-shot context",
    )
51
52
    parser.add_argument(
        "--batch_size",
Baber Abbasi's avatar
Baber Abbasi committed
53
        "-b",
54
55
56
57
58
        type=str,
        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
59
60
61
62
    parser.add_argument(
        "--max_batch_size",
        type=int,
        default=None,
63
64
        metavar="N",
        help="Maximal batch size to try with --batch_size auto.",
lintangsutawika's avatar
lintangsutawika committed
65
    )
66
67
68
69
    parser.add_argument(
        "--device",
        type=str,
        default=None,
70
        help="Device to use (e.g. cuda, cuda:0, cpu).",
71
72
73
    )
    parser.add_argument(
        "--output_path",
Baber Abbasi's avatar
Baber Abbasi committed
74
        "-o",
75
76
        default=None,
        type=str,
77
        metavar="DIR|DIR/file.json",
78
        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.",
79
    )
lintangsutawika's avatar
lintangsutawika committed
80
81
    parser.add_argument(
        "--limit",
Baber Abbasi's avatar
Baber Abbasi committed
82
        "-L",
lintangsutawika's avatar
lintangsutawika committed
83
84
        type=float,
        default=None,
85
        metavar="N|0<N<1",
lintangsutawika's avatar
lintangsutawika committed
86
87
88
        help="Limit the number of examples per task. "
        "If <1, limit is a percentage of the total number of examples.",
    )
89
90
    parser.add_argument(
        "--use_cache",
Baber Abbasi's avatar
Baber Abbasi committed
91
        "-c",
92
93
        type=str,
        default=None,
94
        metavar="DIR",
95
96
97
98
99
100
        help="A path to a sqlite db file for caching model responses. `None` if not caching.",
    )
    parser.add_argument("--decontamination_ngrams_path", default=None)  # TODO: not used
    parser.add_argument(
        "--check_integrity",
        action="store_true",
101
        help="Whether to run the relevant part of the test suite for the tasks.",
102
103
104
    )
    parser.add_argument(
        "--write_out",
Baber Abbasi's avatar
Baber Abbasi committed
105
        "-w",
106
107
        action="store_true",
        default=False,
108
        help="Prints the prompt for the first few documents.",
109
110
111
    )
    parser.add_argument(
        "--log_samples",
Baber Abbasi's avatar
Baber Abbasi committed
112
        "-s",
113
114
        action="store_true",
        default=False,
115
        help="If True, write out all model outputs and documents for per-sample measurement and post-hoc analysis. Use with --output_path.",
116
    )
117
118
119
120
121
122
    parser.add_argument(
        "--show_config",
        action="store_true",
        default=False,
        help="If True, shows the the full config of all tasks at the end of the evaluation.",
    )
123
124
125
126
    parser.add_argument(
        "--include_path",
        type=str,
        default=None,
127
        metavar="DIR",
128
129
        help="Additional path to include if there are external tasks to include.",
    )
130
131
    parser.add_argument(
        "--gen_kwargs",
132
        default=None,
USVSN Sai Prashanth's avatar
USVSN Sai Prashanth committed
133
134
        help=(
            "String arguments for model generation on greedy_until tasks,"
135
            " e.g. `temperature=0,top_k=0,top_p=0`."
lintangsutawika's avatar
lintangsutawika committed
136
137
138
        ),
    )
    parser.add_argument(
lintangsutawika's avatar
lintangsutawika committed
139
        "--verbosity",
Baber Abbasi's avatar
Baber Abbasi committed
140
141
        "-v",
        type=str.upper,
lintangsutawika's avatar
lintangsutawika committed
142
        default="INFO",
143
144
        metavar="CRITICAL|ERROR|WARNING|INFO|DEBUG",
        help="Controls the reported logging error level. Set to DEBUG when testing + adding new task configurations for comprehensive log output.",
145
    )
Jason Phang's avatar
Jason Phang committed
146
147
    return parser.parse_args()

Fabrizio Milo's avatar
Fabrizio Milo committed
148

haileyschoelkopf's avatar
haileyschoelkopf committed
149
150
151
152
153
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
        args = parse_eval_args()

154
    eval_logger = utils.eval_logger
lintangsutawika's avatar
lintangsutawika committed
155
    eval_logger.setLevel(getattr(logging, f"{args.verbosity}"))
156
    eval_logger.info(f"Verbosity set to {args.verbosity}")
haileyschoelkopf's avatar
haileyschoelkopf committed
157
    os.environ["TOKENIZERS_PARALLELISM"] = "false"
Fabrizio Milo's avatar
Fabrizio Milo committed
158

159
    initialize_tasks(args.verbosity)
Fabrizio Milo's avatar
Fabrizio Milo committed
160

Leo Gao's avatar
Leo Gao committed
161
    if args.limit:
lintangsutawika's avatar
lintangsutawika committed
162
163
164
        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
165
        )
lintangsutawika's avatar
lintangsutawika committed
166
167
    if args.include_path is not None:
        eval_logger.info(f"Including path: {args.include_path}")
168
        include_path(args.include_path)
lintangsutawika's avatar
lintangsutawika committed
169

170
    if args.tasks is None:
171
        task_names = ALL_TASKS
172
    elif args.tasks == "list":
lintangsutawika's avatar
lintangsutawika committed
173
        eval_logger.info(
174
            "Available Tasks:\n - {}".format("\n - ".join(sorted(ALL_TASKS)))
lintangsutawika's avatar
lintangsutawika committed
175
        )
176
        sys.exit()
Jason Phang's avatar
Jason Phang committed
177
    else:
178
179
        if os.path.isdir(args.tasks):
            import glob
180
181

            task_names = []
182
183
            yaml_path = os.path.join(args.tasks, "*.yaml")
            for yaml_file in glob.glob(yaml_path):
lintangsutawika's avatar
lintangsutawika committed
184
                config = utils.load_yaml_config(yaml_file)
185
186
                task_names.append(config)
        else:
187
            tasks_list = args.tasks.split(",")
188
            task_names = utils.pattern_match(tasks_list, ALL_TASKS)
189
190
            for task in [task for task in tasks_list if task not in task_names]:
                if os.path.isfile(task):
lintangsutawika's avatar
lintangsutawika committed
191
                    config = utils.load_yaml_config(task)
192
                    task_names.append(config)
193
194
195
196
            task_missing = [
                task
                for task in tasks_list
                if task not in task_names and "*" not in task
197
            ]  # we don't want errors if a wildcard ("*") task name was used
lintangsutawika's avatar
lintangsutawika committed
198

baberabb's avatar
baberabb committed
199
200
201
202
            if task_missing:
                missing = ", ".join(task_missing)
                eval_logger.error(
                    f"Tasks were not found: {missing}\n"
lintangsutawika's avatar
lintangsutawika committed
203
                    f"{utils.SPACING}Try `lm-eval --tasks list` for list of available tasks",
baberabb's avatar
baberabb committed
204
205
                )
                raise ValueError(
206
                    f"Tasks not found: {missing}. Try `lm-eval --tasks list` for list of available tasks, or '--verbosity DEBUG' to troubleshoot task registration issues."
baberabb's avatar
baberabb committed
207
                )
lintangsutawika's avatar
lintangsutawika committed
208

209
210
    if args.output_path:
        path = Path(args.output_path)
Lintang Sutawika's avatar
Lintang Sutawika committed
211
        # check if file or 'dir/results.json' exists
baberabb's avatar
baberabb committed
212
        if path.is_file() or Path(args.output_path).joinpath("results.json").is_file():
213
214
215
            eval_logger.warning(
                f"File already exists at {path}. Results will be overwritten."
            )
lintangsutawika's avatar
lintangsutawika committed
216
            output_path_file = path.joinpath("results.json")
217
218
219
220
221
222
223
224
225
            assert not path.is_file(), "File already exists"
        # if path json then get parent dir
        elif path.suffix in (".json", ".jsonl"):
            output_path_file = path
            path.parent.mkdir(parents=True, exist_ok=True)
            path = path.parent
        else:
            path.mkdir(parents=True, exist_ok=True)
            output_path_file = path.joinpath("results.json")
226
227
    elif args.log_samples and not args.output_path:
        assert args.output_path, "Specify --output_path"
228

lintangsutawika's avatar
lintangsutawika committed
229
    eval_logger.info(f"Selected Tasks: {task_names}")
230

231
232
233
234
235
236
    results = evaluator.simple_evaluate(
        model=args.model,
        model_args=args.model_args,
        tasks=task_names,
        num_fewshot=args.num_fewshot,
        batch_size=args.batch_size,
237
        max_batch_size=args.max_batch_size,
238
        device=args.device,
haileyschoelkopf's avatar
haileyschoelkopf committed
239
        use_cache=args.use_cache,
240
241
242
        limit=args.limit,
        decontamination_ngrams_path=args.decontamination_ngrams_path,
        check_integrity=args.check_integrity,
243
        write_out=args.write_out,
244
        log_samples=args.log_samples,
lintangsutawika's avatar
lintangsutawika committed
245
        gen_kwargs=args.gen_kwargs,
246
    )
247

248
    if results is not None:
249
250
        if args.log_samples:
            samples = results.pop("samples")
251
        dumped = json.dumps(results, indent=2, default=_handle_non_serializable)
252
253
        if args.show_config:
            print(dumped)
254

255
256
        batch_sizes = ",".join(map(str, results["config"]["batch_sizes"]))

257
        if args.output_path:
258
            output_path_file.open("w").write(dumped)
259

260
261
262
            if args.log_samples:
                for task_name, config in results["configs"].items():
                    output_name = "{}_{}".format(
lintangsutawika's avatar
lintangsutawika committed
263
                        re.sub("/|=", "__", args.model_args), task_name
lintangsutawika's avatar
lintangsutawika committed
264
                    )
265
                    filename = path.joinpath(f"{output_name}.jsonl")
266
267
268
269
                    samples_dumped = json.dumps(
                        samples[task_name], indent=2, default=_handle_non_serializable
                    )
                    filename.open("w").write(samples_dumped)
lintangsutawika's avatar
lintangsutawika committed
270

271
        print(
272
            f"{args.model} ({args.model_args}), gen_kwargs: ({args.gen_kwargs}), limit: {args.limit}, num_fewshot: {args.num_fewshot}, "
273
            f"batch_size: {args.batch_size}{f' ({batch_sizes})' if batch_sizes else ''}"
274
        )
275
        print(make_table(results))
lintangsutawika's avatar
lintangsutawika committed
276
        if "groups" in results:
277
            print(make_table(results, "groups"))
Jason Phang's avatar
lib  
Jason Phang committed
278

279

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