__init__.py 8.19 KB
Newer Older
1
import os
lintangsutawika's avatar
lintangsutawika committed
2
import yaml
lintangsutawika's avatar
lintangsutawika committed
3
from typing import List, Union
&'s avatar
& committed
4

5
from lm_eval import utils
6
from lm_eval import prompts
lintangsutawika's avatar
lintangsutawika committed
7
from lm_eval.logger import eval_logger
8
from lm_eval.api.task import TaskConfig, Task, ConfigurableTask
lintangsutawika's avatar
lintangsutawika committed
9
from lm_eval.api.registry import (
10
11
    register_task,
    register_group,
lintangsutawika's avatar
lintangsutawika committed
12
13
    TASK_REGISTRY,
    GROUP_REGISTRY,
haileyschoelkopf's avatar
haileyschoelkopf committed
14
    ALL_TASKS,
lintangsutawika's avatar
lintangsutawika committed
15
)
lintangsutawika's avatar
lintangsutawika committed
16

17

18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
def register_configurable_task(config):
    SubClass = type(
        config["task"] + "ConfigurableTask",
        (ConfigurableTask,),
        {"CONFIG": TaskConfig(**config)},
    )

    if "task" in config:
        task_name = "{}".format(config["task"])
        register_task(task_name)(SubClass)

    if "group" in config:
        if type(config["group"]) == str:
            group_name = [config["group"]]
        else:
            group_name = config["group"]

        for group in group_name:
            register_group(group)(SubClass)

    return 0


def check_prompt_config(config):
    all_configs = []
    if "use_prompt" in config:
        prompt_list = prompts.load_prompt_list(
            use_prompt=config["use_prompt"],
            dataset_name=config["dataset_path"],
            subset_name=config["dataset_name"],
        )
        for idx, prompt_variation in enumerate(prompt_list):
            all_configs.append(
                {
                    **config,
                    **{"use_prompt": prompt_variation},
                    **{
                        "task": "_".join(
                            [
                                get_task_name_from_config(config),
                                "promptsource",
                                str(idx).zfill(2),
                            ]
                        )
                    },
                    **{"output_type": "greedy_until"},
                }
            )
    else:
        all_configs.append(config)
    return all_configs


71
def get_task_name_from_config(task_config):
Lintang Sutawika's avatar
Lintang Sutawika committed
72
    if "dataset_name" in task_config:
Lintang Sutawika's avatar
Lintang Sutawika committed
73
74
75
        return "{dataset_path}_{dataset_name}".format(**task_config)
    else:
        return "{dataset_path}".format(**task_config)
76
77


78
79
80
81
82
def include_task_folder(task_dir):
    """
    Calling this function
    """
    for root, subdirs, file_list in os.walk(task_dir):
83
        if (subdirs == [] or subdirs == ["__pycache__"]) and (len(file_list) > 0):
84
85
86
87
88
            for f in file_list:
                if f.endswith(".yaml"):
                    yaml_path = os.path.join(root, f)
                    try:
                        config = utils.load_yaml_config(yaml_path)
89
90
91
                        all_configs = check_prompt_config(config)
                        for config in all_configs:
                            register_configurable_task(config)
92
93
94
95
96
97
98
99

                    except Exception as error:
                        eval_logger.warning(
                            "Failed to load config in\n"
                            f"                                 {yaml_path}\n"
                            "                                 Config will not be added to registry\n"
                            f"                                 Error: {error}"
                        )
100

101

lintangsutawika's avatar
lintangsutawika committed
102
103
104
105
106
107
def include_benchmarks(task_dir, benchmark_dir="benchmarks"):

    for root, subdirs, file_list in os.walk(os.path.join(task_dir, benchmark_dir)):
        if (subdirs == [] or subdirs == ["__pycache__"]) and (len(file_list) > 0):
            for f in file_list:
                if f.endswith(".yaml"):
lintangsutawika's avatar
changes  
lintangsutawika committed
108
109
110
111
112
113
114
115
                    try:
                        benchmark_path = os.path.join(root, f)

                        with open(benchmark_path, "rb") as file:
                            yaml_config = yaml.full_load(file)

                        assert "group" in yaml_config
                        group = yaml_config["group"]
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
                        all_task_list = yaml_config["task"]
                        config_list = [
                            task for task in all_task_list if type(task) != str
                        ]
                        task_list = [
                            task for task in all_task_list if type(task) == str
                        ]

                        for task_config in config_list:
                            var_configs = check_prompt_config(
                                {
                                    **task_config,
                                    **{"group": group},
                                }
                            )
                            for config in var_configs:
                                register_configurable_task(config)

lintangsutawika's avatar
changes  
lintangsutawika committed
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
                        task_names = utils.pattern_match(task_list, ALL_TASKS)
                        for task in task_names:
                            if task in TASK_REGISTRY:
                                if group in GROUP_REGISTRY:
                                    GROUP_REGISTRY[group].append(task)
                                else:
                                    GROUP_REGISTRY[group] = [task]
                                    ALL_TASKS.add(group)
                    except Exception as error:
                        eval_logger.warning(
                            "Failed to load benchmark in\n"
                            f"                                 {benchmark_path}\n"
                            "                                 Benchmark will not be added to registry\n"
                            f"                                 Error: {error}"
                        )
lintangsutawika's avatar
lintangsutawika committed
149
150


151
152
task_dir = os.path.dirname(os.path.abspath(__file__)) + "/"
include_task_folder(task_dir)
lintangsutawika's avatar
lintangsutawika committed
153
include_benchmarks(task_dir)
lintangsutawika's avatar
lintangsutawika committed
154

lintangsutawika's avatar
lintangsutawika committed
155

156
157
def get_task(task_name, config):
    try:
158
        return TASK_REGISTRY[task_name](config=config)
159
    except KeyError:
lintangsutawika's avatar
lintangsutawika committed
160
        eval_logger.info("Available tasks:")
161
        eval_logger.info(list(TASK_REGISTRY) + list(GROUP_REGISTRY))
lintangsutawika's avatar
lintangsutawika committed
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
        raise KeyError(f"Missing task {task_name}")


def get_task_name_from_object(task_object):
    for name, class_ in TASK_REGISTRY.items():
        if class_ is task_object:
            return name

    # TODO: scrap this
    # this gives a mechanism for non-registered tasks to have a custom name anyways when reporting
    return (
        task_object.EVAL_HARNESS_NAME
        if hasattr(task_object, "EVAL_HARNESS_NAME")
        else type(task_object).__name__
    )


# TODO: pass num_fewshot and other cmdline overrides in a better way
lintangsutawika's avatar
lintangsutawika committed
180
181
182
def get_task_dict(task_name_list: List[Union[str, dict, Task]], **kwargs):

    config = {**kwargs}
183
184
185
186
187
188
189
190
191

    task_name_from_registry_dict = {}
    task_name_from_config_dict = {}
    task_name_from_object_dict = {}

    for task_element in task_name_list:
        if isinstance(task_element, str):

            if task_element in GROUP_REGISTRY:
192
                group_name = task_element
193
194
195
196
                for task_name in GROUP_REGISTRY[task_element]:
                    if task_name not in task_name_from_registry_dict:
                        task_name_from_registry_dict = {
                            **task_name_from_registry_dict,
197
198
199
200
                            task_name: (
                                group_name,
                                get_task(task_name=task_name, config=config),
                            ),
lintangsutawika's avatar
lintangsutawika committed
201
                        }
202
            else:
203
                task_name = task_element
204
205
206
                if task_name not in task_name_from_registry_dict:
                    task_name_from_registry_dict = {
                        **task_name_from_registry_dict,
lintangsutawika's avatar
lintangsutawika committed
207
208
                        task_name: get_task(task_name=task_element, config=config),
                    }
209
210

        elif isinstance(task_element, dict):
211
            task_element.update(config)
212
213
214
            task_name_from_config_dict = {
                **task_name_from_config_dict,
                get_task_name_from_config(task_element): ConfigurableTask(
215
                    config=task_element
lintangsutawika's avatar
lintangsutawika committed
216
                ),
217
218
219
220
221
222
            }

        elif isinstance(task_element, Task):

            task_name_from_object_dict = {
                **task_name_from_object_dict,
lintangsutawika's avatar
lintangsutawika committed
223
                get_task_name_from_object(task_element): task_element,
224
            }
lintangsutawika's avatar
lintangsutawika committed
225
226
227
228

    assert set(task_name_from_registry_dict.keys()).isdisjoint(
        set(task_name_from_object_dict.keys())
    )
lintangsutawika's avatar
lintangsutawika committed
229
230
231
    return {
        **task_name_from_registry_dict,
        **task_name_from_config_dict,
232
        **task_name_from_object_dict,
lintangsutawika's avatar
lintangsutawika committed
233
    }