registry.py 4.96 KB
Newer Older
lintangsutawika's avatar
lintangsutawika committed
1
<<<<<<< HEAD
2
import os
lintangsutawika's avatar
lintangsutawika committed
3
import logging
4
import evaluate
5
import collections
lintangsutawika's avatar
lintangsutawika committed
6
7
from functools import partial

8
from lm_eval.api.model import LM
lintangsutawika's avatar
lintangsutawika committed
9
=======
10
11
import logging

12
import evaluate
13

14
from lm_eval.api.model import LM
15

lintangsutawika's avatar
lintangsutawika committed
16
>>>>>>> 4d10ad56b1ffe569467eee2297e2317c99313118
lintangsutawika's avatar
lintangsutawika committed
17

18
eval_logger = logging.getLogger("lm-eval")
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

MODEL_REGISTRY = {}


def register_model(*names):
    # either pass a list or a single alias.
    # function receives them as a tuple of strings

    def decorate(cls):
        for name in names:
            assert issubclass(
                cls, LM
            ), f"Model '{name}' ({cls.__name__}) must extend LM class"

            assert (
                name not in MODEL_REGISTRY
            ), f"Model named '{name}' conflicts with existing model! Please register with a non-conflicting alias instead."

            MODEL_REGISTRY[name] = cls
        return cls

    return decorate


def get_model(model_name):
haileyschoelkopf's avatar
haileyschoelkopf committed
44
45
46
    try:
        return MODEL_REGISTRY[model_name]
    except KeyError:
47
48
49
        raise ValueError(
            f"Attempted to load model '{model_name}', but no model for this name found! Supported model names: {', '.join(MODEL_REGISTRY.keys())}"
        )
50
51
52
53


TASK_REGISTRY = {}
GROUP_REGISTRY = {}
54
ALL_TASKS = set()
55
56
57
58
59
60
61
62
63
64
func2task_index = {}


def register_task(name):
    def decorate(fn):
        assert (
            name not in TASK_REGISTRY
        ), f"task named '{name}' conflicts with existing registered task!"

        TASK_REGISTRY[name] = fn
65
        ALL_TASKS.add(name)
66
67
68
69
70
71
72
73
74
75
76
77
78
        func2task_index[fn.__name__] = name
        return fn

    return decorate


def register_group(name):
    def decorate(fn):
        func_name = func2task_index[fn.__name__]
        if name in GROUP_REGISTRY:
            GROUP_REGISTRY[name].append(func_name)
        else:
            GROUP_REGISTRY[name] = [func_name]
79
            ALL_TASKS.add(name)
80
81
82
83
84
        return fn

    return decorate


85
86
METRIC_REGISTRY = collections.defaultdict(dict)
AGGREGATION_REGISTRY = collections.defaultdict(dict)
87
88

DEFAULT_METRIC_REGISTRY = {
89
90
91
92
    "loglikelihood": [],
    "loglikelihood_rolling": [],
    "multiple_choice": [],
    "generate_until": [],
93
94
95
}


96
def register_metric(
lintangsutawika's avatar
lintangsutawika committed
97
    metric=None,
98
99
    higher_is_better=None,
    output_type=None,
100
    aggregation=None,
101
):
102
103
    # TODO: do we want to enforce a certain interface to registered metrics?
    def decorate(fn):
lintangsutawika's avatar
lintangsutawika committed
104
105
106
107
108
109
        if type(metric) == str:
            metric_list = [metric]
        elif type(metric) == list:
            metric_list = metric

        for _metric in metric_list:
110
111
112
113
            METRIC_REGISTRY[_metric]["function"] = fn

            if aggregation is not None:
                METRIC_REGISTRY[_metric]["aggregation"] = aggregation
lintangsutawika's avatar
lintangsutawika committed
114
115

            if higher_is_better is not None:
116
                METRIC_REGISTRY[_metric]["higher_is_better"] = higher_is_better
lintangsutawika's avatar
lintangsutawika committed
117
118
119
120
121
122
123
124
125
126

            if output_type is not None:
                if type(output_type) == str:
                    output_type_list = [output_type]
                elif type(output_type) == list:
                    output_type_list = output_type

                for _output_type in output_type_list:
                    DEFAULT_METRIC_REGISTRY[_output_type].append(_metric)

127
128
129
130
131
        return fn

    return decorate


lintangsutawika's avatar
lintangsutawika committed
132
<<<<<<< HEAD
133
def get_metric(name):
134

135
136
137
138
139
140
141
    if name in METRIC_REGISTRY:
        return METRIC_REGISTRY[name]
    else:
        eval_logger.error(f"Could not find registered metric '{name}' in lm-eval")


def get_evaluate(name, **kwargs):
lintangsutawika's avatar
lintangsutawika committed
142
=======
143
144
145
146
147
148
149
150
def get_metric(name, hf_evaluate_metric=False):
    if not hf_evaluate_metric:
        if name in METRIC_REGISTRY:
            return METRIC_REGISTRY[name]
        else:
            eval_logger.warning(
                f"Could not find registered metric '{name}' in lm-eval, searching in HF Evaluate library..."
            )
lintangsutawika's avatar
lintangsutawika committed
151
>>>>>>> 4d10ad56b1ffe569467eee2297e2317c99313118
Chris's avatar
Chris committed
152

153
    try:
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169

        class HFEvaluateAdaptor:
            def __init__(self, name, **kwargs):

                self.name = name
                metric_object = evaluate.load(name)
                self.hf_evaluate_fn = partial(metric_object.compute, **kwargs)

            def __call__(self, items):
                refs = list(zip(*items))[0]
                preds = list(zip(*items))[1]

                return self.hf_evaluate_fn(references=refs, predictions=preds)[
                    self.name
                ]

170
        return HFEvaluateAdaptor(name, **kwargs)
171
172
173
    except Exception:
        eval_logger.error(
            f"{name} not found in the evaluate library! Please check https://huggingface.co/evaluate-metric",
174
175
176
        )


177
178
179
180
181
182
183
184
185
186
187
188
189
def register_aggregation(name):
    def decorate(fn):
        assert (
            name not in AGGREGATION_REGISTRY
        ), f"aggregation named '{name}' conflicts with existing registered aggregation!"

        AGGREGATION_REGISTRY[name] = fn
        return fn

    return decorate


def get_aggregation(name):
haileyschoelkopf's avatar
haileyschoelkopf committed
190
    try:
191
        return AGGREGATION_REGISTRY[name]
haileyschoelkopf's avatar
haileyschoelkopf committed
192
    except KeyError:
193
        eval_logger.warning(
194
            "{} not a registered aggregation metric!".format(name),
195
        )