main.py 6.54 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
lintangsutawika's avatar
lintangsutawika committed
13
from lm_eval.tasks import include_task_folder
Jason Phang's avatar
lib  
Jason Phang committed
14

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

Fabrizio Milo's avatar
Fabrizio Milo committed
17

Jason Phang's avatar
Jason Phang committed
18
19
def parse_args():
    parser = argparse.ArgumentParser()
20
21
22
23
24
25
    parser.add_argument("--model", required=True, help="Name of model e.g. `hf`")
    parser.add_argument(
        "--model_args",
        default="",
        help="String arguments for model, e.g. `pretrained=EleutherAI/pythia-160m,dtype=float32`",
    )
lintangsutawika's avatar
lintangsutawika committed
26
27
28
    parser.add_argument(
        "--tasks", default=None, choices=utils.MultiChoice(sorted(ALL_TASKS))
    )
29
30
31
32
33
34
35
    parser.add_argument(
        "--num_fewshot",
        type=int,
        default=0,
        help="Number of examples in few-shot context",
    )
    parser.add_argument("--batch_size", type=int, default=1)  # TODO: only integers
lintangsutawika's avatar
lintangsutawika committed
36
37
38
39
40
41
    parser.add_argument(
        "--max_batch_size",
        type=int,
        default=None,
        help="Maximal batch size to try with --batch_size auto",
    )
42
43
44
45
46
47
48
49
50
51
52
    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]",
53
        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.",
54
    )
lintangsutawika's avatar
lintangsutawika committed
55
56
57
58
59
60
61
    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.",
    )
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
    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",
    )
86
87
88
89
90
91
    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.",
    )
Jason Phang's avatar
Jason Phang committed
92
93
    return parser.parse_args()

Fabrizio Milo's avatar
Fabrizio Milo committed
94

95
def main():
Jason Phang's avatar
Jason Phang committed
96
    args = parse_args()
Fabrizio Milo's avatar
Fabrizio Milo committed
97

Leo Gao's avatar
Leo Gao committed
98
    if args.limit:
lintangsutawika's avatar
lintangsutawika committed
99
100
101
        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
102
        )
Leo Gao's avatar
Leo Gao committed
103

lintangsutawika's avatar
lintangsutawika committed
104
105
106
107
    if args.include_path is not None:
        eval_logger.info(f"Including path: {args.include_path}")
        include_task_folder(args.include_path)

108
    if args.tasks is None:
109
        task_names = ALL_TASKS
Jason Phang's avatar
Jason Phang committed
110
    else:
111
112
        if os.path.isdir(args.tasks):
            import glob
113
114

            task_names = []
115
116
            yaml_path = os.path.join(args.tasks, "*.yaml")
            for yaml_file in glob.glob(yaml_path):
lintangsutawika's avatar
lintangsutawika committed
117
                config = utils.load_yaml_config(yaml_file)
118
119
                task_names.append(config)
        else:
120
            tasks_list = args.tasks.split(",")
121
            task_names = utils.pattern_match(tasks_list, ALL_TASKS)
122
123
            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
124
                    config = utils.load_yaml_config(task)
125
                    task_names.append(config)
lintangsutawika's avatar
lintangsutawika committed
126

127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
    if args.output_path:
        path = Path(args.output_path)
        # check if file or 'dir/results.jsonl' exists
        if path.is_file() or Path(args.output_path).joinpath("results.jsonl").is_file():
            eval_logger.warning(
                f"File already exists at {path}. Results will be overwritten."
            )
            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")
143
144
    elif args.log_samples and not args.output_path:
        assert args.output_path, "Specify --output_path"
145

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

148
149
150
151
152
153
    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,
154
        max_batch_size=args.max_batch_size,
155
        device=args.device,
haileyschoelkopf's avatar
haileyschoelkopf committed
156
        use_cache=args.use_cache,
157
158
159
        limit=args.limit,
        decontamination_ngrams_path=args.decontamination_ngrams_path,
        check_integrity=args.check_integrity,
160
        write_out=args.write_out,
161
        log_samples=args.log_samples,
162
    )
163

164
    if results is not None:
165
166
        if args.log_samples:
            samples = results.pop("samples")
167
        dumped = json.dumps(results, indent=2, default=lambda o: str(o))
168
169
        if args.show_config:
            print(dumped)
170

171
172
        batch_sizes = ",".join(map(str, results["config"]["batch_sizes"]))

173
        if args.output_path:
174
            output_path_file.open("w").write(dumped)
175

176
177
178
179
            if args.log_samples:
                for task_name, config in results["configs"].items():
                    output_name = "{}_{}".format(
                        re.sub("/", "__", args.model_args), task_name
lintangsutawika's avatar
lintangsutawika committed
180
                    )
181
                    filename = path.joinpath(f"{output_name}.jsonl")
182
183
184

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

186
        print(
187
188
            f"{args.model} ({args.model_args}), limit: {args.limit}, num_fewshot: {args.num_fewshot}, "
            f"batch_size: {args.batch_size}{f' ({batch_sizes})' if batch_sizes else ''}"
189
190
        )
        print(evaluator.make_table(results))
lintangsutawika's avatar
lintangsutawika committed
191
192
        if "aggregate" in results:
            print(evaluator.make_table(results, "aggregate"))
Jason Phang's avatar
lib  
Jason Phang committed
193

194

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