__main__.py 9.87 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
from pathlib import Path
haileyschoelkopf's avatar
haileyschoelkopf committed
7
from typing import Union
Leo Gao's avatar
Leo Gao committed
8

9
10
import numpy as np

11
from lm_eval import evaluator, utils
12
from lm_eval.tasks import TaskManager
13
from lm_eval.utils import make_table
lintangsutawika's avatar
format  
lintangsutawika committed
14

15

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

24

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

Fabrizio Milo's avatar
Fabrizio Milo committed
146

haileyschoelkopf's avatar
haileyschoelkopf committed
147
148
149
150
151
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()

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

lintangsutawika's avatar
lintangsutawika committed
157
    # initialize_tasks(args.verbosity)
158
    task_manager = TaskManager(args.verbosity, include_path=args.include_path)
Fabrizio Milo's avatar
Fabrizio Milo committed
159

Leo Gao's avatar
Leo Gao committed
160
    if args.limit:
lintangsutawika's avatar
lintangsutawika committed
161
162
163
        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
164
        )
lintangsutawika's avatar
lintangsutawika committed
165

166
    if args.tasks is None:
lintangsutawika's avatar
lintangsutawika committed
167
        eval_logger.error("Need to specify task to evaluate.")
lintangsutawika's avatar
lintangsutawika committed
168
169
170
        import sys

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

lintangsutawika's avatar
lintangsutawika committed
179
            loaded_task_list = []
180
181
            yaml_path = os.path.join(args.tasks, "*.yaml")
            for yaml_file in glob.glob(yaml_path):
lintangsutawika's avatar
lintangsutawika committed
182
                config = utils.load_yaml_config(yaml_file)
lintangsutawika's avatar
lintangsutawika committed
183
                loaded_task_list.append(config)
184
        else:
lintangsutawika's avatar
lintangsutawika committed
185
            input_task_list = args.tasks.split(",")
186
            loaded_task_list = utils.pattern_match(input_task_list, task_manager.all_tasks())
lintangsutawika's avatar
lintangsutawika committed
187
188
189
            for task in [
                task for task in input_task_list if task not in loaded_task_list
            ]:
190
                if os.path.isfile(task):
lintangsutawika's avatar
lintangsutawika committed
191
                    config = utils.load_yaml_config(task)
lintangsutawika's avatar
lintangsutawika committed
192
                    loaded_task_list.append(config)
193
194
            task_missing = [
                task
lintangsutawika's avatar
lintangsutawika committed
195
196
                for task in input_task_list
                if task not in loaded_task_list 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: {loaded_task_list}")
lintangsutawika's avatar
lintangsutawika committed
230
231
    eval_logger.info("Loading selected tasks...")

232
    all_tasks = task_manager.load_task_or_group(loaded_task_list)
lintangsutawika's avatar
lintangsutawika committed
233

234
235
236
    for key, value in all_tasks.items():
        print(key, value)
    import sys; sys.exit()
237

238
239
240
    results = evaluator.simple_evaluate(
        model=args.model,
        model_args=args.model_args,
lintangsutawika's avatar
lintangsutawika committed
241
        tasks=all_tasks,
242
243
        num_fewshot=args.num_fewshot,
        batch_size=args.batch_size,
244
        max_batch_size=args.max_batch_size,
245
        device=args.device,
haileyschoelkopf's avatar
haileyschoelkopf committed
246
        use_cache=args.use_cache,
247
248
249
        limit=args.limit,
        decontamination_ngrams_path=args.decontamination_ngrams_path,
        check_integrity=args.check_integrity,
250
        write_out=args.write_out,
251
        log_samples=args.log_samples,
lintangsutawika's avatar
lintangsutawika committed
252
        gen_kwargs=args.gen_kwargs,
253
    )
254

255
    if results is not None:
256
257
        if args.log_samples:
            samples = results.pop("samples")
258
259
260
        dumped = json.dumps(
            results, indent=2, default=_handle_non_serializable, ensure_ascii=False
        )
261
262
        if args.show_config:
            print(dumped)
263

264
265
        batch_sizes = ",".join(map(str, results["config"]["batch_sizes"]))

266
        if args.output_path:
267
            output_path_file.open("w").write(dumped)
268

269
270
271
            if args.log_samples:
                for task_name, config in results["configs"].items():
                    output_name = "{}_{}".format(
lintangsutawika's avatar
lintangsutawika committed
272
                        re.sub("/|=", "__", args.model_args), task_name
lintangsutawika's avatar
lintangsutawika committed
273
                    )
274
                    filename = path.joinpath(f"{output_name}.jsonl")
275
                    samples_dumped = json.dumps(
276
277
278
279
                        samples[task_name],
                        indent=2,
                        default=_handle_non_serializable,
                        ensure_ascii=False,
280
                    )
281
                    filename.write_text(samples_dumped, encoding="utf-8")
lintangsutawika's avatar
lintangsutawika committed
282

283
        print(
284
            f"{args.model} ({args.model_args}), gen_kwargs: ({args.gen_kwargs}), limit: {args.limit}, num_fewshot: {args.num_fewshot}, "
285
            f"batch_size: {args.batch_size}{f' ({batch_sizes})' if batch_sizes else ''}"
286
        )
287
        print(make_table(results))
lintangsutawika's avatar
lintangsutawika committed
288
        if "groups" in results:
289
            print(make_table(results, "groups"))
Jason Phang's avatar
lib  
Jason Phang committed
290

291

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