klue.py 12.1 KB
Newer Older
Ubuntu's avatar
Ubuntu committed
1
"""
2
3
4
5
6
7
8
9
10
KLUE
https://arxiv.org/abs/2105.09680

 Korean Language Understanding Evaluation (KLUE) benchmark is a series of datasets
 to evaluate natural language understanding capability of Korean language models.
 KLUE consists of 8 diverse and representative tasks, which are accessible to anyone without any restrictions.
 With ethical considerations in mind, we deliberately design annotation guidelines
 to obtain unambiguous annotations for all datasets. Furthermore, we build an evaluation system
 and carefully choose evaluations metrics for every task, thus establishing fair comparison across Korean language models.
danny980521's avatar
danny980521 committed
11

12
 Homepage: https://klue-benchmark.com/
Ubuntu's avatar
Ubuntu committed
13
"""
14

ingyuseong's avatar
ingyuseong committed
15
16
import datasets
from math import exp
Ubuntu's avatar
Ubuntu committed
17
import numpy as np
18
19
from lm_eval.base import Task, MultipleChoiceTask, rf
from lm_eval.metrics import macro_f1_score, mean, matthews_corrcoef, f1_score, yesno
Ubuntu's avatar
Ubuntu committed
20
from lm_eval.utils import general_detokenize
ingyuseong's avatar
ingyuseong committed
21
from functools import partial
Ubuntu's avatar
Ubuntu committed
22
23
24
25
26
27
28
29
30
31
32
33
34

_CITATION = """
@misc{park2021klue,
      title={KLUE: Korean Language Understanding Evaluation},
      author={Sungjoon Park and Jihyung Moon and Sungdong Kim and Won Ik Cho and Jiyoon Han and Jangwon Park and Chisung Song and Junseong Kim and Yongsook Song and Taehwan Oh and Joohong Lee and Juhyun Oh and Sungwon Lyu and Younghoon Jeong and Inkwon Lee and Sangwoo Seo and Dongjun Lee and Hyunwoo Kim and Myeonghwa Lee and Seongbo Jang and Seungwon Do and Sunkyoung Kim and Kyungtae Lim and Jongwon Lee and Kyumin Park and Jamin Shin and Seonghyun Kim and Lucy Park and Alice Oh and Jungwoo Ha and Kyunghyun Cho},
      year={2021},
      eprint={2105.09680},
      archivePrefix={arXiv},
      primaryClass={cs.CL}
}
"""


ingyuseong's avatar
ingyuseong committed
35
def _squad_metric(predictions, references):
ingyuseong's avatar
ingyuseong committed
36
    squad_metric = datasets.load_metric("squad_v2")
37

ingyuseong's avatar
ingyuseong committed
38
    return squad_metric.compute(predictions=predictions, references=references)
ingyuseong's avatar
ingyuseong committed
39
40
41
42
43
44
45
46


def _squad_agg(key, items):
    predictions, references = zip(*items)

    return _squad_metric(predictions=predictions, references=references)[key]


Ubuntu's avatar
Ubuntu committed
47
48
49
50
class STS(Task):
    VERSION = 0
    DATASET_PATH = "klue"
    DATASET_NAME = "sts"
danny980521's avatar
danny980521 committed
51

Ubuntu's avatar
Ubuntu committed
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
    def has_training_docs(self):
        return True

    def has_validation_docs(self):
        return True

    def has_test_docs(self):
        return False

    def training_docs(self):
        if self._training_docs is None:
            self._training_docs = list(self.dataset["train"])
        return self._training_docs

    def validation_docs(self):
        return self.dataset["validation"]

    def doc_to_text(self, doc):
ingyuseong's avatar
ingyuseong committed
70
        return "질문: 문장 1과 문장 2는 서로 유사한 의미를 가지나요?\n문장 1: {}\n문장 2: {}\n정답:".format(
danny980521's avatar
danny980521 committed
71
            general_detokenize(doc["sentence1"]), general_detokenize(doc["sentence2"])
Ubuntu's avatar
Ubuntu committed
72
73
74
        )

    def doc_to_target(self, doc):
ingyuseong's avatar
ingyuseong committed
75
        return " {}".format({0: "아니오", 1: "예"}[doc["labels"]["binary-label"]])
Ubuntu's avatar
Ubuntu committed
76
77

    def construct_requests(self, doc, ctx):
ingyuseong's avatar
ingyuseong committed
78
        ll_negative, _ = rf.loglikelihood(ctx, " 아니오")
79
80
        ll_positive, _ = rf.loglikelihood(ctx, " 예")
        return ll_negative, ll_positive
Ubuntu's avatar
Ubuntu committed
81
82

    def process_results(self, doc, results):
83
        pred = np.argmax(results)
Ubuntu's avatar
Ubuntu committed
84
        gold = doc["labels"]["binary-label"]
danny980521's avatar
danny980521 committed
85
86
        return {"acc": pred == gold, "f1": (gold, pred)}

Ubuntu's avatar
Ubuntu committed
87
    def higher_is_better(self):
danny980521's avatar
danny980521 committed
88
        return {"acc": True, "f1": True}
Ubuntu's avatar
Ubuntu committed
89
90

    def aggregation(self):
danny980521's avatar
danny980521 committed
91
        return {"acc": mean, "f1": f1_score}
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109


class YNAT(MultipleChoiceTask):
    VERSION = 0
    DATASET_PATH = "klue"
    DATASET_NAME = "ynat"

    def has_training_docs(self):
        return True

    def has_validation_docs(self):
        return True

    def has_test_docs(self):
        return False

    def training_docs(self):
        if self._training_docs is None:
danny980521's avatar
danny980521 committed
110
            self._training_docs = list(map(self._process_doc, self.dataset["train"]))
111
112
113
        return self._training_docs

    def validation_docs(self):
ingyuseong's avatar
ingyuseong committed
114
        return map(self._process_doc, self.dataset["validation"])
115
116
117
118
119

    def _process_doc(self, doc):
        out_doc = {
            "title": doc["title"],
            "choices": ["과학", "경제", "사회", "생활", "세계", "스포츠", "정치"],
danny980521's avatar
danny980521 committed
120
            "gold": doc["label"],
121
122
123
124
        }
        return out_doc

    def doc_to_text(self, doc):
danny980521's avatar
danny980521 committed
125
        return "질문: 다음의 제목을 가지는 뉴스는 어느 분야의 뉴스인가요?\n제목: {}\n분야:".format(doc["title"])
126
127

    def doc_to_target(self, doc):
danny980521's avatar
danny980521 committed
128
129
130
131
132
        return " {}".format(
            {0: "과학", 1: "경제", 2: "사회", 3: "생활", 4: "세계", 5: "스포츠", 6: "정치"}[
                doc["gold"]
            ]
        )
133
134
135
136

    def process_results(self, doc, results):
        pred = np.argmax(results)
        gold = doc["gold"]
danny980521's avatar
danny980521 committed
137
        return {"f1": (gold, pred)}
138
139

    def higher_is_better(self):
danny980521's avatar
danny980521 committed
140
        return {"f1": True}
141
142

    def aggregation(self):
danny980521's avatar
danny980521 committed
143
        return {"f1": macro_f1_score}
ingyuseong's avatar
ingyuseong committed
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168


class NLI(Task):
    VERSION = 0
    DATASET_PATH = "klue"
    DATASET_NAME = "nli"

    def has_training_docs(self):
        return True

    def has_validation_docs(self):
        return True

    def has_test_docs(self):
        return False

    def training_docs(self):
        if self._training_docs is None:
            self._training_docs = list(self.dataset["train"])
        return self._training_docs

    def validation_docs(self):
        return self.dataset["validation"]

    def doc_to_text(self, doc):
ingyuseong's avatar
ingyuseong committed
169
        return "{}\n질문: {} 참, 거짓, 중립 중 무엇인가요?\n정답:".format(
ingyuseong's avatar
ingyuseong committed
170
171
172
173
174
175
            doc["premise"],
            doc["hypothesis"].strip()
            + ("" if doc["hypothesis"].strip().endswith(".") else "."),
        )

    def doc_to_target(self, doc):
ingyuseong's avatar
ingyuseong committed
176
177
178
179
180
        """
        참 = entailment
        거짓 = contradiction
        무관 = neutral
        """
ingyuseong's avatar
ingyuseong committed
181
        return " {}".format({0: "참", 1: "중립", 2: "거짓"}[doc["label"]])
ingyuseong's avatar
ingyuseong committed
182
183
184

    def construct_requests(self, doc, ctx):
        ll_true, _ = rf.loglikelihood(ctx, " 참")
ingyuseong's avatar
ingyuseong committed
185
        ll_neither, _ = rf.loglikelihood(ctx, " 중립")
ingyuseong's avatar
ingyuseong committed
186
187
188
189
190
191
192
193
194
195
196
197
        ll_false, _ = rf.loglikelihood(ctx, " 거짓")
        return ll_true, ll_neither, ll_false

    def process_results(self, doc, results):
        gold = doc["label"]
        pred = np.argmax(results)
        return {"acc": pred == gold}

    def higher_is_better(self):
        return {"acc": True}

    def aggregation(self):
ingyuseong's avatar
ingyuseong committed
198
        return {"acc": mean}
ingyuseong's avatar
ingyuseong committed
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221


class MRC(Task):
    VERSION = 0
    DATASET_PATH = "klue"
    DATASET_NAME = "mrc"

    def has_training_docs(self):
        return True

    def has_validation_docs(self):
        return True

    def has_test_docs(self):
        return False

    def training_docs(self):
        return self.dataset["train"]

    def validation_docs(self):
        return self.dataset["validation"]

    def doc_to_text(self, doc):
danny980521's avatar
danny980521 committed
222
223
224
225
226
227
228
229
230
231
232
233
        return (
            "제목: "
            + doc["title"]
            + "\n\n"
            + "본문: "
            + doc["context"]
            + "\n\n"
            + "질문: "
            + doc["question"]
            + "\n\n"
            + "답:"
        )
ingyuseong's avatar
ingyuseong committed
234
235

    def doc_to_target(self, doc):
236
237
238
        answer = doc["answers"]["text"][0]
        if doc["is_impossible"]:
            answer = "대답 불가"
ingyuseong's avatar
ingyuseong committed
239
240
241
        return " " + answer

    def construct_requests(self, doc, ctx):
danny980521's avatar
danny980521 committed
242
        """Uses RequestFactory to construct Requests and returns an iterable of
ingyuseong's avatar
ingyuseong committed
243
244
245
246
247
        Requests which will be sent to the LM.

        :param doc:
            The document as returned from training_docs, validation_docs, or test_docs.
        :param ctx: str
danny980521's avatar
danny980521 committed
248
            The context string, generated by fewshot_context. This includes the natural
ingyuseong's avatar
ingyuseong committed
249
            language description, as well as the few shot examples, and the question
danny980521's avatar
danny980521 committed
250
            part of the document for `doc`.
ingyuseong's avatar
ingyuseong committed
251
        """
danny980521's avatar
danny980521 committed
252
        continuation = rf.greedy_until(ctx, ["\n"])
ingyuseong's avatar
ingyuseong committed
253
254
        is_unanswerable = rf.loglikelihood(ctx, " " + "대답 불가")
        return continuation, is_unanswerable
danny980521's avatar
danny980521 committed
255

ingyuseong's avatar
ingyuseong committed
256
    def process_results(self, doc, results):
danny980521's avatar
danny980521 committed
257
258
        """Take a single document and the LM results and evaluates, returning a
        dict where keys are the names of submetrics and values are the values of
ingyuseong's avatar
ingyuseong committed
259
260
261
262
263
264
265
266
267
268
        the metric for that one document

        :param doc:
            The document as returned from training_docs, validation_docs, or test_docs.
        :param results:
            The results of the requests created in construct_requests.
        """
        continuation, (logprob_unanswerable, _) = results

        no_answer_probability = exp(logprob_unanswerable)
danny980521's avatar
danny980521 committed
269

ingyuseong's avatar
ingyuseong committed
270
        predictions = {
danny980521's avatar
danny980521 committed
271
272
273
            "id": doc["guid"],
            "prediction_text": continuation,
            "no_answer_probability": no_answer_probability,
ingyuseong's avatar
ingyuseong committed
274
275
276
        }

        references = {
danny980521's avatar
danny980521 committed
277
278
279
            "id": doc["guid"],
            "answers": doc["answers"],
            "unanswerable": doc["is_impossible"],
ingyuseong's avatar
ingyuseong committed
280
281
        }

282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
        return {
            "exact": (
                predictions,
                references,
            ),  # Exact match (the normalized answer exactly match the gold answer)
            "f1": (
                predictions,
                references,
            ),  # The F-score of predicted tokens versus the gold answer
            "HasAns_exact": (
                predictions,
                references,
            ),  # Exact match (the normalized answer exactly match the gold answer)
            "HasAns_f1": (
                predictions,
                references,
            ),  # The F-score of predicted tokens versus the gold answer
            "NoAns_exact": (
                predictions,
                references,
            ),  # Exact match (the normalized answer exactly match the gold answer)
            "NoAns_f1": (
                predictions,
                references,
            ),  # The F-score of predicted tokens versus the gold answer
            "best_exact": (
                predictions,
                references,
            ),  # Best exact match (with varying threshold)
            "best_f1": (predictions, references),  # Best F1 (with varying threshold)
ingyuseong's avatar
ingyuseong committed
312
313
314
315
316
        }

    def aggregation(self):
        """
        :returns: {str: [float] -> float}
danny980521's avatar
danny980521 committed
317
            A dictionary where keys are the names of submetrics and values are
ingyuseong's avatar
ingyuseong committed
318
319
            functions that aggregate a list of metrics
        """
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
        return {
            "exact": partial(
                _squad_agg, "exact"
            ),  # Exact match (the normalized answer exactly match the gold answer)
            "f1": partial(
                _squad_agg, "f1"
            ),  # The F-score of predicted tokens versus the gold answer
            "HasAns_exact": partial(
                _squad_agg, "HasAns_exact"
            ),  # Exact match (the normalized answer exactly match the gold answer)
            "HasAns_f1": partial(
                _squad_agg, "HasAns_f1"
            ),  # The F-score of predicted tokens versus the gold answer
            "NoAns_exact": partial(
                _squad_agg, "NoAns_exact"
            ),  # Exact match (the normalized answer exactly match the gold answer)
            "NoAns_f1": partial(
                _squad_agg, "NoAns_f1"
            ),  # The F-score of predicted tokens versus the gold answer
            "best_exact": partial(
                _squad_agg, "best_exact"
            ),  # Best exact match (with varying threshold)
            "best_f1": partial(
                _squad_agg, "best_f1"
            ),  # Best F1 (with varying threshold)
ingyuseong's avatar
ingyuseong committed
345
346
347
348
349
        }

    def higher_is_better(self):
        """
        :returns: {str: bool}
danny980521's avatar
danny980521 committed
350
            A dictionary where keys are the names of submetrics and values are
ingyuseong's avatar
ingyuseong committed
351
352
            whether a higher value of the submetric is better
        """
353
354
355
356
357
358
359
360
361
        return {
            "exact": True,  # Exact match (the normalized answer exactly match the gold answer)
            "f1": True,  # The F-score of predicted tokens versus the gold answer
            "HasAns_exact": True,  # Exact match (the normalized answer exactly match the gold answer)
            "HasAns_f1": True,  # The F-score of predicted tokens versus the gold answer
            "NoAns_exact": True,  # Exact match (the normalized answer exactly match the gold answer)
            "NoAns_f1": True,  # The F-score of predicted tokens versus the gold answer
            "best_exact": True,  # Best exact match (with varying threshold)
            "best_f1": True,  # Best F1 (with varying threshold)
ingyuseong's avatar
ingyuseong committed
362
        }