__main__.py 9.32 KB
Newer Older
lintangsutawika's avatar
lintangsutawika committed
1
import os
lintangsutawika's avatar
lintangsutawika committed
2
import re
3
import sys
Jason Phang's avatar
Jason Phang committed
4
import json
FarzanehNakhaee's avatar
FarzanehNakhaee committed
5
import logging
6
import argparse
7
import numpy as np
lintangsutawika's avatar
format  
lintangsutawika committed
8

9
from pathlib import Path
haileyschoelkopf's avatar
haileyschoelkopf committed
10
from typing import Union
Leo Gao's avatar
Leo Gao committed
11

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

16

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

25

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

Fabrizio Milo's avatar
Fabrizio Milo committed
137

haileyschoelkopf's avatar
haileyschoelkopf committed
138
139
140
141
142
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()

143
    eval_logger = utils.eval_logger
lintangsutawika's avatar
lintangsutawika committed
144
    eval_logger.setLevel(getattr(logging, f"{args.verbosity}"))
145
    eval_logger.info(f"Verbosity set to {args.verbosity}")
haileyschoelkopf's avatar
haileyschoelkopf committed
146
    os.environ["TOKENIZERS_PARALLELISM"] = "false"
Fabrizio Milo's avatar
Fabrizio Milo committed
147

148
    initialize_tasks(args.verbosity)
Fabrizio Milo's avatar
Fabrizio Milo committed
149

Leo Gao's avatar
Leo Gao committed
150
    if args.limit:
lintangsutawika's avatar
lintangsutawika committed
151
152
153
        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
154
        )
lintangsutawika's avatar
lintangsutawika committed
155
156
    if args.include_path is not None:
        eval_logger.info(f"Including path: {args.include_path}")
157
        include_path(args.include_path)
lintangsutawika's avatar
lintangsutawika committed
158

159
    if args.tasks is None:
160
        task_names = ALL_TASKS
161
    elif args.tasks == "list":
lintangsutawika's avatar
lintangsutawika committed
162
163
164
        eval_logger.info(
            "Available Tasks:\n - {}".format(f"\n - ".join(sorted(ALL_TASKS)))
        )
165
        sys.exit()
Jason Phang's avatar
Jason Phang committed
166
    else:
167
168
        if os.path.isdir(args.tasks):
            import glob
169
170

            task_names = []
171
172
            yaml_path = os.path.join(args.tasks, "*.yaml")
            for yaml_file in glob.glob(yaml_path):
lintangsutawika's avatar
lintangsutawika committed
173
                config = utils.load_yaml_config(yaml_file)
174
175
                task_names.append(config)
        else:
176
            tasks_list = args.tasks.split(",")
177
            task_names = utils.pattern_match(tasks_list, ALL_TASKS)
178
179
            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
180
                    config = utils.load_yaml_config(task)
181
                    task_names.append(config)
182
183
184
185
            task_missing = [
                task
                for task in tasks_list
                if task not in task_names and "*" not in task
186
            ]  # we don't want errors if a wildcard ("*") task name was used
lintangsutawika's avatar
lintangsutawika committed
187

baberabb's avatar
baberabb committed
188
189
190
191
            if task_missing:
                missing = ", ".join(task_missing)
                eval_logger.error(
                    f"Tasks were not found: {missing}\n"
lintangsutawika's avatar
lintangsutawika committed
192
                    f"{utils.SPACING}Try `lm-eval --tasks list` for list of available tasks",
baberabb's avatar
baberabb committed
193
194
                )
                raise ValueError(
195
                    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
196
                )
lintangsutawika's avatar
lintangsutawika committed
197

198
199
    if args.output_path:
        path = Path(args.output_path)
Lintang Sutawika's avatar
Lintang Sutawika committed
200
        # check if file or 'dir/results.json' exists
baberabb's avatar
baberabb committed
201
        if path.is_file() or Path(args.output_path).joinpath("results.json").is_file():
202
203
204
            eval_logger.warning(
                f"File already exists at {path}. Results will be overwritten."
            )
lintangsutawika's avatar
lintangsutawika committed
205
            output_path_file = path.joinpath("results.json")
206
207
208
209
210
211
212
213
214
            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")
215
216
    elif args.log_samples and not args.output_path:
        assert args.output_path, "Specify --output_path"
217

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

220
221
222
223
224
225
    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,
226
        max_batch_size=args.max_batch_size,
227
        device=args.device,
haileyschoelkopf's avatar
haileyschoelkopf committed
228
        use_cache=args.use_cache,
229
230
231
        limit=args.limit,
        decontamination_ngrams_path=args.decontamination_ngrams_path,
        check_integrity=args.check_integrity,
232
        write_out=args.write_out,
233
        log_samples=args.log_samples,
lintangsutawika's avatar
lintangsutawika committed
234
        gen_kwargs=args.gen_kwargs,
235
    )
236

237
    if results is not None:
238
239
        if args.log_samples:
            samples = results.pop("samples")
240
        dumped = json.dumps(results, indent=2, default=_handle_non_serializable)
241
242
        if args.show_config:
            print(dumped)
243

244
245
        batch_sizes = ",".join(map(str, results["config"]["batch_sizes"]))

246
        if args.output_path:
247
            output_path_file.open("w").write(dumped)
248

249
250
251
            if args.log_samples:
                for task_name, config in results["configs"].items():
                    output_name = "{}_{}".format(
lintangsutawika's avatar
lintangsutawika committed
252
                        re.sub("/|=", "__", args.model_args), task_name
lintangsutawika's avatar
lintangsutawika committed
253
                    )
254
                    filename = path.joinpath(f"{output_name}.jsonl")
255
256
257
258
                    samples_dumped = json.dumps(
                        samples[task_name], indent=2, default=_handle_non_serializable
                    )
                    filename.open("w").write(samples_dumped)
lintangsutawika's avatar
lintangsutawika committed
259

260
        print(
261
            f"{args.model} ({args.model_args}), gen_kwargs: ({args.gen_kwargs}), limit: {args.limit}, num_fewshot: {args.num_fewshot}, "
262
            f"batch_size: {args.batch_size}{f' ({batch_sizes})' if batch_sizes else ''}"
263
264
        )
        print(evaluator.make_table(results))
lintangsutawika's avatar
lintangsutawika committed
265
266
        if "groups" in results:
            print(evaluator.make_table(results, "groups"))
Jason Phang's avatar
lib  
Jason Phang committed
267

268

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