main.py 7.57 KB
Newer Older
lintangsutawika's avatar
lintangsutawika committed
1
import os
lintangsutawika's avatar
lintangsutawika committed
2
import re
Jason Phang's avatar
Jason Phang committed
3
import json
4
import fnmatch
lintangsutawika's avatar
lintangsutawika committed
5
import jsonlines
lintangsutawika's avatar
lintangsutawika committed
6
import argparse
FarzanehNakhaee's avatar
FarzanehNakhaee committed
7
import logging
8
from pathlib import Path
Leo Gao's avatar
Leo Gao committed
9

10
from lm_eval import evaluator, utils
11
from lm_eval.api.registry import ALL_TASKS
lintangsutawika's avatar
lintangsutawika committed
12
from lm_eval.logger import eval_logger, SPACING
lintangsutawika's avatar
lintangsutawika committed
13
from lm_eval.tasks import include_task_folder
lintangsutawika's avatar
format  
lintangsutawika committed
14

15
os.environ["TOKENIZERS_PARALLELISM"] = "false"
16

Fabrizio Milo's avatar
Fabrizio Milo committed
17

Ethan Smith's avatar
Ethan Smith committed
18
def parse_args() -> argparse.Namespace:
lintangsutawika's avatar
lintangsutawika committed
19
    parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter)
20
    parser.add_argument("--model", required=True, help="Name of model e.g. `hf`")
lintangsutawika's avatar
lintangsutawika committed
21
22
23
24
25
    parser.add_argument(
        "--tasks",
        default=None,
        help="Available Tasks:\n - {}".format("\n - ".join(sorted(ALL_TASKS))),
    )
26
27
28
29
30
    parser.add_argument(
        "--model_args",
        default="",
        help="String arguments for model, e.g. `pretrained=EleutherAI/pythia-160m,dtype=float32`",
    )
lintangsutawika's avatar
lintangsutawika committed
31
    parser.add_argument(
32
33
        "--num_fewshot",
        type=int,
34
        default=None,
35
36
        help="Number of examples in few-shot context",
    )
lintangsutawika's avatar
lintangsutawika committed
37
    parser.add_argument("--batch_size", type=str, default=1)
lintangsutawika's avatar
lintangsutawika committed
38
39
40
41
42
43
    parser.add_argument(
        "--max_batch_size",
        type=int,
        default=None,
        help="Maximal batch size to try with --batch_size auto",
    )
44
45
46
47
48
49
50
51
52
53
54
    parser.add_argument(
        "--device",
        type=str,
        default=None,
        help="Device to use (e.g. cuda, cuda:0, cpu)",
    )
    parser.add_argument(
        "--output_path",
        default=None,
        type=str,
        metavar="= [dir/file.jsonl] [DIR]",
55
        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.",
56
    )
lintangsutawika's avatar
lintangsutawika committed
57
58
59
60
61
62
63
    parser.add_argument(
        "--limit",
        type=float,
        default=None,
        help="Limit the number of examples per task. "
        "If <1, limit is a percentage of the total number of examples.",
    )
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
    parser.add_argument(
        "--use_cache",
        type=str,
        default=None,
        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",
        help="Whether to run the relevant part of the test suite for the tasks",
    )
    parser.add_argument(
        "--write_out",
        action="store_true",
        default=False,
        help="Prints the prompt for the first few documents",
    )
    parser.add_argument(
        "--log_samples",
        action="store_true",
        default=False,
        help="If True, write out all model outputs and documents for per-sample measurement and post-hoc analysis",
    )
88
89
90
91
92
93
    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.",
    )
94
95
96
97
98
99
    parser.add_argument(
        "--include_path",
        type=str,
        default=None,
        help="Additional path to include if there are external tasks to include.",
    )
100
101
102
    parser.add_argument(
        "--gen_kwargs",
        default="",
USVSN Sai Prashanth's avatar
USVSN Sai Prashanth committed
103
104
105
106
        help=(
            "String arguments for model generation on greedy_until tasks,"
            " e.g. `temperature=0,top_k=0,top_p=0`"
        )
107
    )
Jason Phang's avatar
Jason Phang committed
108
109
    return parser.parse_args()

Fabrizio Milo's avatar
Fabrizio Milo committed
110

Ethan Smith's avatar
Ethan Smith committed
111
def main() -> None:
Jason Phang's avatar
Jason Phang committed
112
    args = parse_args()
Fabrizio Milo's avatar
Fabrizio Milo committed
113

Leo Gao's avatar
Leo Gao committed
114
    if args.limit:
lintangsutawika's avatar
lintangsutawika committed
115
116
117
        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
118
        )
Leo Gao's avatar
Leo Gao committed
119

lintangsutawika's avatar
lintangsutawika committed
120
121
122
123
    if args.include_path is not None:
        eval_logger.info(f"Including path: {args.include_path}")
        include_task_folder(args.include_path)

124
    if args.tasks is None:
125
        task_names = ALL_TASKS
Jason Phang's avatar
Jason Phang committed
126
    else:
127
128
        if os.path.isdir(args.tasks):
            import glob
129
130

            task_names = []
131
132
            yaml_path = os.path.join(args.tasks, "*.yaml")
            for yaml_file in glob.glob(yaml_path):
lintangsutawika's avatar
lintangsutawika committed
133
                config = utils.load_yaml_config(yaml_file)
134
135
                task_names.append(config)
        else:
136
            tasks_list = args.tasks.split(",")
137
            task_names = utils.pattern_match(tasks_list, ALL_TASKS)
138
            task_missing = []
139
140
            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
141
                    config = utils.load_yaml_config(task)
142
                    task_names.append(config)
143
144
                else:
                    task_missing.append(task)
lintangsutawika's avatar
lintangsutawika committed
145

146
        if task_missing != []:
lintangsutawika's avatar
lintangsutawika committed
147
            missing = ", ".join(task_missing)
lintangsutawika's avatar
lintangsutawika committed
148
            eval_logger.error(
lintangsutawika's avatar
lintangsutawika committed
149
150
                f"Tasks were not found: {missing}\n"
                f"{SPACING}Try `lm-eval -h` for list of available tasks",
lintangsutawika's avatar
lintangsutawika committed
151
            )
lintangsutawika's avatar
lintangsutawika committed
152
153
            raise ValueError(f"Tasks {missing} were not found.")

154
155
    if args.output_path:
        path = Path(args.output_path)
Lintang Sutawika's avatar
Lintang Sutawika committed
156
        # check if file or 'dir/results.json' exists
baberabb's avatar
baberabb committed
157
        if path.is_file() or Path(args.output_path).joinpath("results.json").is_file():
158
159
160
            eval_logger.warning(
                f"File already exists at {path}. Results will be overwritten."
            )
lintangsutawika's avatar
lintangsutawika committed
161
            output_path_file = path.joinpath("results.json")
162
163
164
165
166
167
168
169
170
            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")
171
172
    elif args.log_samples and not args.output_path:
        assert args.output_path, "Specify --output_path"
173

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

176
177
178
179
180
181
    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,
182
        max_batch_size=args.max_batch_size,
183
        device=args.device,
haileyschoelkopf's avatar
haileyschoelkopf committed
184
        use_cache=args.use_cache,
185
186
187
        limit=args.limit,
        decontamination_ngrams_path=args.decontamination_ngrams_path,
        check_integrity=args.check_integrity,
188
        write_out=args.write_out,
189
        log_samples=args.log_samples,
190
        gen_kwargs=args.gen_kwargs
191
    )
192

193
    if results is not None:
194
195
        if args.log_samples:
            samples = results.pop("samples")
196
        dumped = json.dumps(results, indent=2, default=lambda o: str(o))
197
198
        if args.show_config:
            print(dumped)
199

200
201
        batch_sizes = ",".join(map(str, results["config"]["batch_sizes"]))

202
        if args.output_path:
203
            output_path_file.open("w").write(dumped)
204

205
206
207
            if args.log_samples:
                for task_name, config in results["configs"].items():
                    output_name = "{}_{}".format(
lintangsutawika's avatar
lintangsutawika committed
208
                        re.sub("/|=", "__", args.model_args), task_name
lintangsutawika's avatar
lintangsutawika committed
209
                    )
210
                    filename = path.joinpath(f"{output_name}.jsonl")
211
212
213

                    with jsonlines.open(filename, "w") as f:
                        f.write_all(samples[task_name])
lintangsutawika's avatar
lintangsutawika committed
214

215
        print(
216
            f"{args.model} ({args.model_args}), gen_kwargs: ({args.gen_kwargs}), limit: {args.limit}, num_fewshot: {args.num_fewshot}, "
217
            f"batch_size: {args.batch_size}{f' ({batch_sizes})' if batch_sizes else ''}"
218
219
        )
        print(evaluator.make_table(results))
lintangsutawika's avatar
lintangsutawika committed
220
221
        if "groups" in results:
            print(evaluator.make_table(results, "groups"))
Jason Phang's avatar
lib  
Jason Phang committed
222

223

Jason Phang's avatar
Jason Phang committed
224
if __name__ == "__main__":
Jason Phang's avatar
lib  
Jason Phang committed
225
    main()