__init__.py 10.1 KB
Newer Older
1
import os
2
import abc
lintangsutawika's avatar
lintangsutawika committed
3
import yaml
4
import collections
lintangsutawika's avatar
lintangsutawika committed
5

lintangsutawika's avatar
lintangsutawika committed
6
from functools import partial
7
from typing import List, Union, Dict
&'s avatar
& committed
8

9
from lm_eval import utils
10
from lm_eval import prompts
11
from lm_eval.api.task import TaskConfig, Task, ConfigurableTask
lintangsutawika's avatar
lintangsutawika committed
12

lintangsutawika's avatar
lintangsutawika committed
13
import logging
lintangsutawika's avatar
lintangsutawika committed
14

15
16
17
18
19
20
21
22
23
24
25
26
# # import python tasks
# import squadv2.task
# import scrolls.task
# python_tasks = {
#     "squadv2": squadv2.task.SQuAD2,
#     "scrolls_quality": scrolls.task.QuALITY,
#     "scrolls_narrativeqa": scrolls.task.NarrativeQA,
#     "scrolls_contractnli": scrolls.task.ContractNLI,
#     "scrolls_govreport": scrolls.task.GovReport,
#     "scrolls_summscreenfd": scrolls.task.SummScreenFD,
#     "scrolls_qmsum": scrolls.task.QMSum,
# }
lintangsutawika's avatar
lintangsutawika committed
27

28
eval_logger = utils.eval_logger
29

30
31
GROUP_KEYS = ["group", "task", "weight_by_size"]
PYTHON_TASK_KEYS = ["task", "class"]
lintangsutawika's avatar
lintangsutawika committed
32

33
class TaskManager(abc.ABC):
34

35
    def __init__(
lintangsutawika's avatar
lintangsutawika committed
36
        self,
37
38
39
        verbosity="INFO",
        include_path=None
        ) -> None:
40

lintangsutawika's avatar
lintangsutawika committed
41
42
        self.verbosity = verbosity
        self.include_path = include_path
lintangsutawika's avatar
lintangsutawika committed
43
        self.logger = eval_logger.setLevel(getattr(logging, f"{verbosity}"))
lintangsutawika's avatar
lintangsutawika committed
44
45

        self.ALL_TASKS = self.initialize_tasks(
46
47
48
            include_path=include_path
            )

lintangsutawika's avatar
lintangsutawika committed
49
    def initialize_tasks(self, include_path=None):
lintangsutawika's avatar
lintangsutawika committed
50

lintangsutawika's avatar
lintangsutawika committed
51
52
53
54
55
56
57
58
        all_paths = [os.path.dirname(os.path.abspath(__file__)) + "/"]
        if include_path is not None:
            if isinstance(include_path, str):
                include_path = [include_path]
            all_paths.extend(include_path)

        ALL_TASKS = {}
        for task_dir in all_paths:
lintangsutawika's avatar
lintangsutawika committed
59
            tasks = self._get_task_and_group(task_dir)
lintangsutawika's avatar
lintangsutawika committed
60
61
62
63
            ALL_TASKS = {**tasks, **ALL_TASKS}

        return ALL_TASKS

64
    def all_tasks(self):
lintangsutawika's avatar
lintangsutawika committed
65
        return sorted(list(self.ALL_TASKS.keys()))
66

lintangsutawika's avatar
lintangsutawika committed
67
68
69
70
71
72
    def _name_is_registered(self, name):
        if name in self.ALL_TASKS:
            return True
        return False

    def _name_is_task(self, name):
73
74
75
76
77
78
        if self._name_is_registered(name) and ("task" in self.ALL_TASKS[name]["type"]):
            return True
        return False

    def _name_is_python_task(self, name):
        if self._name_is_registered(name) and (self.ALL_TASKS[name]["type"] == "python_task"):
lintangsutawika's avatar
lintangsutawika committed
79
80
81
82
            return True
        return False

    def _config_is_task(self, config):
83
        if set(config.keys()) <= set(GROUP_KEYS):
lintangsutawika's avatar
lintangsutawika committed
84
85
86
            return False
        return True

87
88
89
90
91
    def _config_is_python_task(self, config):
        if set(config.keys()) == set(PYTHON_TASK_KEYS):
            return True
        return False

lintangsutawika's avatar
lintangsutawika committed
92
93
94
95
    def _get_yaml_path(self, name):
        assert name in self.ALL_TASKS
        return self.ALL_TASKS[name]["yaml_path"]

lintangsutawika's avatar
lintangsutawika committed
96
97
    def _get_config(self, name):
        assert name in self.ALL_TASKS
lintangsutawika's avatar
lintangsutawika committed
98
        yaml_path = self._get_yaml_path(name)
lintangsutawika's avatar
lintangsutawika committed
99
100
101
102
103
104
        return utils.load_yaml_config(yaml_path)

    def _get_tasklist(self, name):
        assert self._name_is_task(name) == False
        return self.ALL_TASKS[name]["task"]

105
106
107
108
109
110
    def _load_individual_task_or_group(
            self,
            name_or_config: Union[str, dict] = None,
            parent_name: str = None,
            update_config: dict = None
        ) -> ConfigurableTask:
lintangsutawika's avatar
lintangsutawika committed
111

112
113
114
115
116
        def load_task(config, task, group=None, is_python_class=False):
            if is_python_class:
                task_object = config["class"]()
            else:
                task_object = ConfigurableTask(config=config)
lintangsutawika's avatar
lintangsutawika committed
117
118
119
120
            if group is not None:
                task_object = (group, task_object)
            return {task: task_object}

lintangsutawika's avatar
lintangsutawika committed
121
        if isinstance(name_or_config, str):
122
            if update_config is not None:
123
                # Process name_or_config as a dict instead
124
125
                name_or_config = {"task": name_or_config, **update_config}
            elif self._name_is_task(name_or_config):
lintangsutawika's avatar
lintangsutawika committed
126
                task_config = self._get_config(name_or_config)
127
128
129
130
                is_python_class=False
                if self._name_is_python_task(name_or_config):
                    is_python_class=True
                return load_task(task_config, task=name_or_config, group=parent_name, is_python_class=is_python_class)
131
            else:
lintangsutawika's avatar
lintangsutawika committed
132
133
                group_name = name_or_config
                subtask_list = self._get_tasklist(name_or_config)
134
                if subtask_list == -1:
lintangsutawika's avatar
lintangsutawika committed
135
136
                    subtask_list = self._get_config(name_or_config)["task"]

137
138
139
140
141
142
143
144
        if isinstance(name_or_config, dict):

            if update_config is not None:
                name_or_config={
                    **name_or_config,
                    **update_config,
                }

lintangsutawika's avatar
lintangsutawika committed
145
            if self._config_is_task(name_or_config):
146
                name = name_or_config["task"]
147
                # If the name is registered as a group
148
149
                if self._name_is_task(name) is False:
                    group_name = name
150
                    update_config = {k:v for k,v in name_or_config.items() if k != "task"}
151
152
153
                    subtask_list = self._get_tasklist(name)
                    if subtask_list == -1:
                        subtask_list = self._get_config(name)["task"]
154
                else:
155
156
157
158
159
160
161
162
163
                    if self._name_is_registered(name):
                        base_task_config = self._get_config(name)
                        task_config={
                                **base_task_config,
                                **name_or_config,
                            }
                    else:
                        task_config = name_or_config
                    return load_task(task_config, task=name, group=parent_name)
164
            else:
lintangsutawika's avatar
lintangsutawika committed
165
166
167
                group_name = name_or_config["group"]
                subtask_list = name_or_config["task"]

lintangsutawika's avatar
lintangsutawika committed
168
        if (self._name_is_registered(group_name) is False) or (self._get_yaml_path(group_name) == -1):
lintangsutawika's avatar
lintangsutawika committed
169
170
171
172
            all_subtasks = {group_name: (parent_name, None)}
        else:
            all_subtasks = {}

173
        fn = partial(self._load_individual_task_or_group, parent_name=group_name, update_config=update_config)
lintangsutawika's avatar
lintangsutawika committed
174
        all_subtasks = {**all_subtasks, **dict(collections.ChainMap(*map(fn, subtask_list)))}
lintangsutawika's avatar
lintangsutawika committed
175
176
        return all_subtasks

177
178
179
180
181
182

    def load_task_or_group(self, task_list: Union[str, list] = None) -> dict:

        if isinstance(task_list, str):
            task_list = [task_list]

lintangsutawika's avatar
lintangsutawika committed
183
184
185
186
187
188
        all_loaded_tasks = dict(
            collections.ChainMap(
                *map(
                    self._load_individual_task_or_group,
                    task_list
                )
189
            )
lintangsutawika's avatar
lintangsutawika committed
190
        )
191
        return all_loaded_tasks
192

lintangsutawika's avatar
lintangsutawika committed
193
194
195
196
197
198
199
    def _get_task_and_group(self, task_dir: str):
        tasks_and_groups = collections.defaultdict()
        for root, _, file_list in os.walk(task_dir):
            for f in file_list:
                if f.endswith(".yaml"):
                    yaml_path = os.path.join(root, f)
                    config = utils.simple_load_yaml_config(yaml_path)
200
201
202
203
204
205
206
207
208
209
210
                    if set(config.keys()) == set(PYTHON_TASK_KEYS):
                        # This is a python class config
                        tasks_and_groups[config["task"]] = {
                            "type": "python_task",
                            "yaml_path": yaml_path,
                        }
                    elif set(config.keys()) <= set(GROUP_KEYS):
                        print("###")
                        print(config["group"])
                        print(config)
                        print("###")
lintangsutawika's avatar
lintangsutawika committed
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
                        # This is a group config
                        tasks_and_groups[config["group"]] = {
                            "type": "group",
                            "task": -1, # This signals that
                                        # we don't need to know
                                        # the task list for indexing
                                        # as it can be loaded
                                        # when called.
                            "yaml_path": yaml_path,
                        }
                    else:
                        # This is a task config
                        task = config["task"]
                        tasks_and_groups[task] = {
                            "type": "task",
                            "yaml_path": yaml_path,
                            }

                        if "group" in config:
                            groups = config["group"]
                            if isinstance(config["group"], str):
                                groups = [groups]

                            for group in groups:
                                if group not in tasks_and_groups:
                                    tasks_and_groups[group] = {
                                        "type": "group",
                                        "task": [task],
                                        "yaml_path": -1,
                                    }
                                else:
                                    tasks_and_groups[group]["task"].append(task)

        return tasks_and_groups
245

lintangsutawika's avatar
format  
lintangsutawika committed
246

lintangsutawika's avatar
lintangsutawika committed
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
# def check_prompt_config(
#     config: Dict[str, str], yaml_path: str = None
# ) -> List[Dict[str, str]]:
#     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"] if "dataset_name" in config else None,
#             yaml_path=yaml_path,
#         )
#         for idx, prompt_variation in enumerate(prompt_list):
#             all_configs.append(
#                 {
#                     **config,
#                     **{"use_prompt": prompt_variation},
#                     **{
#                         "task": "_".join(
#                             [
#                                 config["task"]
#                                 if "task" in config
#                                 else get_task_name_from_config(config),
#                                 prompt_variation.split("/")[-1]
#                                 if ".yaml" in prompt_variation
#                                 else prompt_variation,
#                             ]
#                         )
#                     },
#                     **{"output_type": "generate_until"},
#                 }
#             )
#     else:
#         all_configs.append(config)
#     return all_configs