klue.py 12.1 KB
Newer Older
Ubuntu's avatar
Ubuntu committed
1
"""
2
3
4
5
6
7
8
9
10
11
12
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.
 
 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"
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(
Ubuntu's avatar
Ubuntu committed
72
73
74
75
76
            general_detokenize(doc["sentence1"]),
            general_detokenize(doc["sentence2"]) 
        )

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

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

    def process_results(self, doc, results):
85
        pred = np.argmax(results)
Ubuntu's avatar
Ubuntu committed
86
87
88
89
90
        gold = doc["labels"]["binary-label"]
        return {
            "acc": pred == gold,
            "f1": (gold, pred)
        }
91
    
Ubuntu's avatar
Ubuntu committed
92
93
94
95
96
97
98
99
100
101
102
    def higher_is_better(self):
        return {
            "acc": True,
            "f1": True
        }

    def aggregation(self):
        return {
            "acc": mean,
            "f1": f1_score
        }
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124


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

    def validation_docs(self):
ingyuseong's avatar
ingyuseong committed
125
        return map(self._process_doc, self.dataset["validation"])
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156

    def _process_doc(self, doc):
        out_doc = {
            "title": doc["title"],
            "choices": ["과학", "경제", "사회", "생활", "세계", "스포츠", "정치"],
            "gold": doc["label"]
        }
        return out_doc

    def doc_to_text(self, doc):
        return "{}".format(doc["title"])

    def doc_to_target(self, doc):
        return " ({})".format({0: "과학", 1: "경제", 2: "사회", 3: "생활", 4: "세계", 5: "스포츠", 6: "정치"}[doc["gold"]])

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

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

    def aggregation(self):
        return {
            "f1": macro_f1_score
        }
ingyuseong's avatar
ingyuseong committed
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181


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
182
        return "{}\n질문: {} 참, 거짓, 중립 중 무엇인가요?\n정답:".format(
ingyuseong's avatar
ingyuseong committed
183
184
185
186
187
188
            doc["premise"],
            doc["hypothesis"].strip()
            + ("" if doc["hypothesis"].strip().endswith(".") else "."),
        )

    def doc_to_target(self, doc):
ingyuseong's avatar
ingyuseong committed
189
190
191
192
193
        """
        참 = entailment
        거짓 = contradiction
        무관 = neutral
        """
ingyuseong's avatar
ingyuseong committed
194
        return " {}".format({0: "참", 1: "중립", 2: "거짓"}[doc["label"]])
ingyuseong's avatar
ingyuseong committed
195
196
197

    def construct_requests(self, doc, ctx):
        ll_true, _ = rf.loglikelihood(ctx, " 참")
ingyuseong's avatar
ingyuseong committed
198
        ll_neither, _ = rf.loglikelihood(ctx, " 중립")
ingyuseong's avatar
ingyuseong committed
199
200
201
202
203
204
205
206
207
208
209
210
        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
211
        return {"acc": mean}
ingyuseong's avatar
ingyuseong committed
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234


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):
235
        return "제목: " + doc["title"] + "\n\n" + "본문: " + doc["context"] + "\n\n" + "질문: " + doc["question"] + "\n\n" + "답:"
ingyuseong's avatar
ingyuseong committed
236
237

    def doc_to_target(self, doc):
238
239
240
        answer = doc["answers"]["text"][0]
        if doc["is_impossible"]:
            answer = "대답 불가"
ingyuseong's avatar
ingyuseong committed
241
242
243
244
245
246
247
248
249
250
251
252
253
        return " " + answer

    def construct_requests(self, doc, ctx):
        """ Uses RequestFactory to construct Requests and returns an iterable of 
        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
            The context string, generated by fewshot_context. This includes the natural 
            language description, as well as the few shot examples, and the question
            part of the document for `doc`. 
        """
254
        continuation = rf.greedy_until(ctx, {"until": ["\n"]})
ingyuseong's avatar
ingyuseong committed
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
        is_unanswerable = rf.loglikelihood(ctx, " " + "대답 불가")
        return continuation, is_unanswerable
    
    def process_results(self, doc, results):
        """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 
        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)
        
        predictions = {
273
274
275
            'id': doc['guid'],
            'prediction_text': continuation,
            'no_answer_probability': no_answer_probability,
ingyuseong's avatar
ingyuseong committed
276
277
278
        }

        references = {
279
280
281
            'id': doc['guid'],
            'answers': doc['answers'],
            'unanswerable': doc['is_impossible'],
ingyuseong's avatar
ingyuseong committed
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
313
        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
314
315
316
317
318
319
320
321
        }

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

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