klue.py 12.2 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
import datasets
16
import evaluate
ingyuseong's avatar
ingyuseong committed
17
from math import exp
Ubuntu's avatar
Ubuntu committed
18
import numpy as np
19
20
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
21
from lm_eval.utils import general_detokenize
ingyuseong's avatar
ingyuseong committed
22
from functools import partial
Ubuntu's avatar
Ubuntu committed
23
24
25
26
27
28
29
30
31
32
33
34
35

_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}
}
"""


36
37
def _klue_mrc_metric(predictions, references):
    klue_mrc_metric = evaluate.load("ingyu/klue_mrc")
38

39
    return klue_mrc_metric.compute(predictions=predictions, references=references)
ingyuseong's avatar
ingyuseong committed
40
41


42
def _klue_mrc_agg(key, items):
ingyuseong's avatar
ingyuseong committed
43
44
    predictions, references = zip(*items)

45
    return _klue_mrc_metric(predictions=predictions, references=references)[key]
ingyuseong's avatar
ingyuseong committed
46
47


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

Ubuntu's avatar
Ubuntu committed
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
    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
71
        return "질문: 문장 1과 문장 2는 서로 유사한 의미를 가지나요?\n문장 1: {}\n문장 2: {}\n정답:".format(
danny980521's avatar
danny980521 committed
72
            general_detokenize(doc["sentence1"]), general_detokenize(doc["sentence2"])
Ubuntu's avatar
Ubuntu committed
73
74
75
        )

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

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

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

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

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


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
111
            self._training_docs = list(map(self._process_doc, self.dataset["train"]))
112
113
114
        return self._training_docs

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

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

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

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

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

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

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


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
170
        return "{}\n질문: {} 참, 거짓, 중립 중 무엇인가요?\n정답:".format(
ingyuseong's avatar
ingyuseong committed
171
172
173
174
175
176
            doc["premise"],
            doc["hypothesis"].strip()
            + ("" if doc["hypothesis"].strip().endswith(".") else "."),
        )

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

    def construct_requests(self, doc, ctx):
        ll_true, _ = rf.loglikelihood(ctx, " 참")
ingyuseong's avatar
ingyuseong committed
186
        ll_neither, _ = rf.loglikelihood(ctx, " 중립")
ingyuseong's avatar
ingyuseong committed
187
188
189
190
191
192
193
194
195
196
197
198
        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
199
        return {"acc": mean}
ingyuseong's avatar
ingyuseong committed
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222


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
223
224
225
226
227
228
229
230
231
232
233
234
        return (
            "제목: "
            + doc["title"]
            + "\n\n"
            + "본문: "
            + doc["context"]
            + "\n\n"
            + "질문: "
            + doc["question"]
            + "\n\n"
            + "답:"
        )
ingyuseong's avatar
ingyuseong committed
235
236

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

    def construct_requests(self, doc, ctx):
danny980521's avatar
danny980521 committed
243
        """Uses RequestFactory to construct Requests and returns an iterable of
ingyuseong's avatar
ingyuseong committed
244
245
246
247
248
        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
249
            The context string, generated by fewshot_context. This includes the natural
ingyuseong's avatar
ingyuseong committed
250
            language description, as well as the few shot examples, and the question
danny980521's avatar
danny980521 committed
251
            part of the document for `doc`.
ingyuseong's avatar
ingyuseong committed
252
        """
danny980521's avatar
danny980521 committed
253
        continuation = rf.greedy_until(ctx, ["\n"])
ingyuseong's avatar
ingyuseong committed
254
255
        is_unanswerable = rf.loglikelihood(ctx, " " + "대답 불가")
        return continuation, is_unanswerable
danny980521's avatar
danny980521 committed
256

ingyuseong's avatar
ingyuseong committed
257
    def process_results(self, doc, results):
danny980521's avatar
danny980521 committed
258
259
        """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
260
261
262
263
264
265
266
267
268
269
        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
270

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

        references = {
danny980521's avatar
danny980521 committed
278
279
280
            "id": doc["guid"],
            "answers": doc["answers"],
            "unanswerable": doc["is_impossible"],
ingyuseong's avatar
ingyuseong committed
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
312
        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
313
314
315
316
317
        }

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

    def higher_is_better(self):
        """
        :returns: {str: bool}
danny980521's avatar
danny980521 committed
351
            A dictionary where keys are the names of submetrics and values are
ingyuseong's avatar
ingyuseong committed
352
353
            whether a higher value of the submetric is better
        """
354
355
356
357
358
359
360
361
362
        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
363
        }