superglue.py 12.9 KB
Newer Older
Jason Phang's avatar
Jason Phang committed
1
"""
2
3
4
5
6
7
8
9
10
SuperGLUE: A Stickier Benchmark for General-Purpose Language Understanding Systems
https://w4ngatang.github.io/static/papers/superglue.pdf

SuperGLUE is a benchmark styled after GLUE with a new set of more difficult language
understanding tasks.

Homepage: https://super.gluebenchmark.com/

TODO: WSC requires free-form generation.
Jason Phang's avatar
Jason Phang committed
11
"""
Jason Phang's avatar
Jason Phang committed
12
import numpy as np
13
14
import sklearn
import transformers.data.metrics.squad_metrics as squad_metrics
Jason Phang's avatar
Jason Phang committed
15
from . common import HFTask, yesno
&'s avatar
& committed
16
17
from lm_eval.base import rf
from ..metrics import mean, acc_all, metric_max_over_ground_truths
Leo Gao's avatar
Fix  
Leo Gao committed
18
from ..utils import general_detokenize
Jason Phang's avatar
Jason Phang committed
19

Jason Phang's avatar
Jason Phang committed
20

21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
_CITATION = """
@inproceedings{NEURIPS2019_4496bf24,
    author = {Wang, Alex and Pruksachatkun, Yada and Nangia, Nikita and Singh, Amanpreet and Michael, Julian and Hill, Felix and Levy, Omer and Bowman, Samuel},
    booktitle = {Advances in Neural Information Processing Systems},
    editor = {H. Wallach and H. Larochelle and A. Beygelzimer and F. d\textquotesingle Alch\'{e}-Buc and E. Fox and R. Garnett},
    pages = {},
    publisher = {Curran Associates, Inc.},
    title = {SuperGLUE: A Stickier Benchmark for General-Purpose Language Understanding Systems},
    url = {https://proceedings.neurips.cc/paper/2019/file/4496bf24afe7fab6f046bf4923da8de6-Paper.pdf},
    volume = {32},
    year = {2019}
}
"""


36
class BoolQ(HFTask):
37
    VERSION = 1
Leo Gao's avatar
Leo Gao committed
38
39
    DATASET_PATH = "super_glue"
    DATASET_NAME = "boolq"
Jason Phang's avatar
Jason Phang committed
40
41
42
43
44
45
46
47

    def has_training_docs(self):
        return True

    def has_validation_docs(self):
        return True

    def has_test_docs(self):
48
        return False
Jason Phang's avatar
Jason Phang committed
49

Leo Gao's avatar
Update  
Leo Gao committed
50
    def doc_to_text(self, doc):
51
        return f"{doc['passage']}\nQuestion: {doc['question']}?\nAnswer:"
Leo Gao's avatar
Update  
Leo Gao committed
52
53
    
    def doc_to_target(self, doc):
54
        return " " + yesno(doc['label']) 
Jason Phang's avatar
Jason Phang committed
55

56
    def construct_requests(self, doc, ctx):
Leo Gao's avatar
Update  
Leo Gao committed
57

58
        ll_yes, _ = rf.loglikelihood(ctx, ' yes')
Jason Phang's avatar
Jason Phang committed
59
        ll_no, _ = rf.loglikelihood(ctx, ' no')
Leo Gao's avatar
Update  
Leo Gao committed
60
61
62
63
64
65
66
67
68

        return ll_yes, ll_no

    def process_results(self, doc, results):
        ll_yes, ll_no = results
        gold = doc["label"]

        acc = 1. if (ll_yes > ll_no) == gold else 0.

69
70
71
72
73
74
75
76
77
78
79
80
81
        return {
            "acc": acc
        }
    
    def higher_is_better(self):
        return {
            "acc": True
        }
    
    def aggregation(self):
        return {
            "acc": mean
        }
Jason Phang's avatar
Jason Phang committed
82

Jason Phang's avatar
Jason Phang committed
83

84
class CommitmentBank(HFTask):
thomasw21's avatar
thomasw21 committed
85
    VERSION = 1
Leo Gao's avatar
Leo Gao committed
86
87
    DATASET_PATH = "super_glue"
    DATASET_NAME = "cb"
Jason Phang's avatar
Jason Phang committed
88
89
90
91
92
93
94
95

    def has_training_docs(self):
        return True

    def has_validation_docs(self):
        return True

    def has_test_docs(self):
96
        return False
Jason Phang's avatar
Jason Phang committed
97

98
    def doc_to_text(self, doc):
Leo Gao's avatar
Leo Gao committed
99
        return "{}\nQuestion: {}. True, False or Neither?\nAnswer:".format(
Jason Phang's avatar
Jason Phang committed
100
101
102
            doc["premise"],
            doc["hypothesis"],
        )
103

thefazzer's avatar
thefazzer committed
104
    def doc_to_target(self, doc):
105
106
107
        # True = entailment
        # False = contradiction
        # Neither = neutral
thomasw21's avatar
Fix CB  
thomasw21 committed
108
        return " {}".format({0: "True", 1: "False", 2: "Neither"}[doc["label"]])
Jason Phang's avatar
Jason Phang committed
109

thefazzer's avatar
thefazzer committed
110
    def construct_requests(self, doc, ctx):
Leo Gao's avatar
Leo Gao committed
111
112
        ll_true, _ = rf.loglikelihood(ctx, ' True')
        ll_false, _ = rf.loglikelihood(ctx, ' False')
thomasw21's avatar
Fix CB  
thomasw21 committed
113
        ll_neither, _ = rf.loglikelihood(ctx, ' Neither')
114

thomasw21's avatar
Fix CB  
thomasw21 committed
115
        return ll_true, ll_false, ll_neither
thefazzer's avatar
thefazzer committed
116
117
118

    def process_results(self, doc, results):
        gold = doc["label"]
thefazzer's avatar
thefazzer committed
119
120
        pred = np.argmax(results)
        acc = 1. if pred == gold else 0.
Jason Phang's avatar
Jason Phang committed
121

thefazzer's avatar
thefazzer committed
122
        return {
thefazzer's avatar
thefazzer committed
123
124
            "acc": acc,
            "f1": (pred, gold)
thefazzer's avatar
thefazzer committed
125
126
127
128
        }
    
    def higher_is_better(self):
        return {
129
130
            "acc": True,
            "f1": True
thefazzer's avatar
thefazzer committed
131
        }
Jason Phang's avatar
Jason Phang committed
132
133
134
135
136
137
138
139
140
141
142

    @classmethod
    def cb_multi_fi(cls, items):
        preds, golds = zip(*items)
        preds = np.array(preds)
        golds = np.array(golds)
        f11 = sklearn.metrics.f1_score(y_true=golds == 0, y_pred=preds == 0)
        f12 = sklearn.metrics.f1_score(y_true=golds == 1, y_pred=preds == 1)
        f13 = sklearn.metrics.f1_score(y_true=golds == 2, y_pred=preds == 2)
        avg_f1 = mean([f11, f12, f13])
        return avg_f1
thefazzer's avatar
thefazzer committed
143
144
145
    
    def aggregation(self):
        return {
thefazzer's avatar
thefazzer committed
146
            "acc": mean,
Jason Phang's avatar
Jason Phang committed
147
            "f1": self.cb_multi_fi,
thefazzer's avatar
thefazzer committed
148
        }
Jason Phang's avatar
Jason Phang committed
149

Jason Phang's avatar
Jason Phang committed
150

151
class Copa(HFTask):
Leo Gao's avatar
Leo Gao committed
152
    VERSION = 0
Leo Gao's avatar
Leo Gao committed
153
154
    DATASET_PATH = "super_glue"
    DATASET_NAME = "copa"
Jason Phang's avatar
Jason Phang committed
155
156
157
158
159
160
161
162

    def has_training_docs(self):
        return True

    def has_validation_docs(self):
        return True

    def has_test_docs(self):
163
        return False
Jason Phang's avatar
Jason Phang committed
164

165
    def doc_to_text(self, doc):
Jason Phang's avatar
Jason Phang committed
166
        # Drop the period
Jason Phang's avatar
Jason Phang committed
167
168
169
170
        connector = {
            "cause": "because",
            "effect": "therefore",
        }[doc["question"]]
171
        return doc["premise"].strip()[:-1] + f" {connector}"
Jason Phang's avatar
Jason Phang committed
172

thefazzer's avatar
thefazzer committed
173
    def doc_to_target(self, doc):
174
175
        correct_choice = doc["choice1"] if doc["label"] == 0 else doc["choice2"]
        # Connect the sentences
176
        return " " + self.convert_choice(correct_choice)
thefazzer's avatar
thefazzer committed
177
178

    def construct_requests(self, doc, ctx):
thefazzer's avatar
thefazzer committed
179
180
        choice1 = " " + self.convert_choice(doc["choice1"])
        choice2 = " " + self.convert_choice(doc["choice2"])
thefazzer's avatar
thefazzer committed
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
        
        ll_choice1, _ = rf.loglikelihood(ctx, choice1)
        ll_choice2, _ = rf.loglikelihood(ctx, choice2)

        return ll_choice1, ll_choice2

    def process_results(self, doc, results):
        gold = doc["label"]
        pred = np.argmax(results)
        acc = 1. if pred == gold else 0.

        return {
            "acc": acc
        }
    
    def higher_is_better(self):
        return {
            "acc": True
        }
    
    def aggregation(self):
        return {
            "acc": mean
        }
Jason Phang's avatar
Jason Phang committed
205
206
207
208
209
210

    @staticmethod
    def convert_choice(choice):
        return choice[0].lower() + choice[1:]


211
class MultiRC(HFTask):
212
    VERSION = 1
Leo Gao's avatar
Leo Gao committed
213
214
    DATASET_PATH = "super_glue"
    DATASET_NAME = "multirc"
Jason Phang's avatar
multirc  
Jason Phang committed
215
216
217
218
219
220
221
222

    def has_training_docs(self):
        return True

    def has_validation_docs(self):
        return True

    def has_test_docs(self):
223
        return False
Jason Phang's avatar
multirc  
Jason Phang committed
224

225
    def doc_to_text(self, doc):
Leo Gao's avatar
Leo Gao committed
226
        return f"{doc['paragraph']}\nQuestion: {doc['question']}\nAnswer:"
227
228

    def doc_to_target(self, doc):
Leo Gao's avatar
Leo Gao committed
229
        return " " + self.format_answer(answer=doc["answer"], label=doc["label"])
Jason Phang's avatar
multirc  
Jason Phang committed
230
231
232

    @staticmethod
    def format_answer(answer, label):
Leo Gao's avatar
Fix  
Leo Gao committed
233
        label_str = "yes" if label else "no"
thomasw21's avatar
thomasw21 committed
234
        return f"{answer}\nIs the answer correct? {label_str}"
Jason Phang's avatar
multirc  
Jason Phang committed
235

thefazzer's avatar
thefazzer committed
236
237
238
239
240
241
242
243
244
245
    def construct_requests(self, doc, ctx):
        true_choice = self.format_answer(answer=doc["answer"], label=True)
        false_choice = self.format_answer(answer=doc["answer"], label=False)
        
        ll_true_choice, _ = rf.loglikelihood(ctx, f' {true_choice}')
        ll_false_choice, _ = rf.loglikelihood(ctx, f' {false_choice}')

        return ll_true_choice, ll_false_choice

    def process_results(self, doc, results):
thomasw21's avatar
thomasw21 committed
246
247
        ll_true_choice, ll_false_choice = results
        pred = ll_true_choice > ll_false_choice
Jason Phang's avatar
multirc  
Jason Phang committed
248
        return {
thefazzer's avatar
thefazzer committed
249
250
251
252
253
254
255
256
257
258
259
            "acc": (pred, doc)
        }
    
    def higher_is_better(self):
        return {
            "acc": True
        }
    
    def aggregation(self):
        return {
            "acc": acc_all
Jason Phang's avatar
multirc  
Jason Phang committed
260
261
        }

Jason Phang's avatar
Jason Phang committed
262
263

class ReCoRD(HFTask):
Leo Gao's avatar
Leo Gao committed
264
    VERSION = 0
Jason Phang's avatar
Jason Phang committed
265
266
267
268
269
270
271
272
273
274
    DATASET_PATH = "super_glue"
    DATASET_NAME = "record"

    def has_training_docs(self):
        return True

    def has_validation_docs(self):
        return True

    def has_test_docs(self):
Leo Gao's avatar
Leo Gao committed
275
        return False
Jason Phang's avatar
Jason Phang committed
276
277
278
279

    def training_docs(self):
        # In ReCoRD, each doc manifests multiple "examples" in the context of few shot example packing.
        # Each doc consists of multiple answer candidates, each of which is scored yes/no.
280
281
282
        if self._training_docs is None:
            self._training_docs = []
            for doc in self.data["train"]:
Jason Phang's avatar
Jason Phang committed
283
                self._training_docs.append(self._process_doc(doc))
284
285
286
        return self._training_docs

    def validation_docs(self):
Jason Phang's avatar
Jason Phang committed
287
288
289
290
291
292
293
294
295
296
297
298
        # See: training_docs
        for doc in self.data["validation"]:
            yield self._process_doc(doc)

    @classmethod
    def _process_doc(cls, doc):
        return {
            "passage": doc["passage"],
            "query": doc["query"],
            "entities": sorted(list(set(doc["entities"]))),
            "answers": sorted(list(set(doc["answers"]))),
        }
Jason Phang's avatar
Jason Phang committed
299
300
301
302
303
304
305
306
307
308
309
310
311

    def doc_to_text(self, doc):
        initial_text, *highlights = doc["passage"].strip().split("\n@highlight\n")
        text = initial_text + "\n\n"
        for highlight in highlights:
            text += f"  - {highlight}.\n"
        return text

    @classmethod
    def format_answer(cls, query, entity):
        return f'  - {query}'.replace("@placeholder", entity)

    def doc_to_target(self, doc):
Jason Phang's avatar
Jason Phang committed
312
313
        # We only output the first correct entity in a doc
        return self.format_answer(query=doc["query"], entity=doc["answers"][0])
Jason Phang's avatar
Jason Phang committed
314
315
316
317

    def construct_requests(self, doc, ctx):
        requests = [
            rf.loglikelihood(ctx, self.format_answer(query=doc["query"], entity=entity))
Jason Phang's avatar
Jason Phang committed
318
            for entity in doc["entities"]
Jason Phang's avatar
Jason Phang committed
319
320
321
322
323
324
325
326
        ]
        return requests

    def process_results(self, doc, results):
        # ReCoRD's evaluation is actually deceptively simple:
        # - Pick the maximum likelihood prediction entity
        # - Evaluate the accuracy and token F1 PER EXAMPLE
        # - Average over all examples
Jason Phang's avatar
Jason Phang committed
327
        max_idx = np.argmax(np.array([result[0] for result in results]))
Leo Gao's avatar
Leo Gao committed
328

Jason Phang's avatar
Jason Phang committed
329
        prediction = doc["entities"][max_idx]
Jason Phang's avatar
Jason Phang committed
330
        gold_label_set = doc["answers"]
Jason Phang's avatar
Jason Phang committed
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
        f1 = metric_max_over_ground_truths(squad_metrics.compute_f1, prediction, gold_label_set)
        em = metric_max_over_ground_truths(squad_metrics.compute_exact, prediction, gold_label_set)

        return {
            "f1": f1,
            "em": em,
        }

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

    def aggregation(self):
        return {
            "f1": mean,
            "em": mean,
        }


352
class WordsInContext(HFTask):
Leo Gao's avatar
Leo Gao committed
353
    VERSION = 0
Leo Gao's avatar
Leo Gao committed
354
355
    DATASET_PATH = "super_glue"
    DATASET_NAME = "wic"
Jason Phang's avatar
Jason Phang committed
356
357
358
359
360
361
362
363

    def has_training_docs(self):
        return True

    def has_validation_docs(self):
        return True

    def has_test_docs(self):
364
        return False
Jason Phang's avatar
Jason Phang committed
365

366
    def doc_to_text(self, doc):
Leo Gao's avatar
Leo Gao committed
367
368
        return "Sentence 1: {}\nSentence 2: {}\nQuestion: Is the word '{}' used in the same way in the" \
               " two sentences above?\nAnswer:".format(
Jason Phang's avatar
Jason Phang committed
369
370
371
372
                    doc["sentence1"],
                    doc["sentence2"],
                    doc["sentence1"][doc["start1"]:doc["end1"]],
                )
373
374
375

    def doc_to_target(self, doc):
        return " {}".format({0: "no", 1: "yes"}[doc["label"]])
Jason Phang's avatar
Jason Phang committed
376

Jason Phang's avatar
Jason Phang committed
377
378
379
380
381
    def construct_requests(self, doc, ctx):
        ll_yes, _ = rf.loglikelihood(ctx, ' yes')
        ll_no, _ = rf.loglikelihood(ctx, ' no')

        return ll_yes, ll_no
382

Jason Phang's avatar
Jason Phang committed
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
    def process_results(self, doc, results):
        ll_yes, ll_no = results
        gold = doc["label"]

        acc = 1. if (ll_yes > ll_no) == gold else 0.

        return {
            "acc": acc
        }

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

    def aggregation(self):
        return {
            "acc": mean
        }
Jason Phang's avatar
Jason Phang committed
402
403


404
class SGWinogradSchemaChallenge(HFTask):
Leo Gao's avatar
Leo Gao committed
405
    VERSION = 0
Jason Phang's avatar
wsc  
Jason Phang committed
406
407
    # Note: This implementation differs from Fig G.32 because this is the SuperGLUE,
    #       binary version of the task.
Leo Gao's avatar
Leo Gao committed
408
409
    DATASET_PATH = "super_glue"
    DATASET_NAME = "wsc"
Jason Phang's avatar
Jason Phang committed
410
411
412
413
414
415
416
417

    def has_training_docs(self):
        return True

    def has_validation_docs(self):
        return True

    def has_test_docs(self):
418
        return False
Jason Phang's avatar
Jason Phang committed
419
420
421
422

    def training_docs(self):
        if self.has_training_docs():
            if self._training_docs is None:
Jason Phang's avatar
Jason Phang committed
423
                # GPT-3 Paper's format only uses positive examples for fewshot "training"
Jason Phang's avatar
Jason Phang committed
424
425
                self._training_docs = [
                    doc for doc in
Jason Phang's avatar
Jason Phang committed
426
                    self.data["train"]
Jason Phang's avatar
Jason Phang committed
427
428
429
430
                    if doc["label"]
                ]
            return self._training_docs

431
    def doc_to_text(self, doc):
Jason Phang's avatar
Jason Phang committed
432
        raw_passage = doc["text"]
Jonathan Tow's avatar
Jonathan Tow committed
433
434
435
        # NOTE: HuggingFace span indices are word-based not character-based.
        pre = " ".join(raw_passage.split()[:doc["span2_index"]])
        post = raw_passage[len(pre) + len(doc["span2_text"]) + 1:]
Leo Gao's avatar
Leo Gao committed
436
        passage = general_detokenize(pre + " *{}*".format(doc['span2_text']) + post)
Jason Phang's avatar
wsc  
Jason Phang committed
437
        noun = doc["span1_text"]
Jason Phang's avatar
Jason Phang committed
438
439
440
        pronoun = doc["span2_text"]
        text = (
            f"Passage: {passage}\n"
Jason Phang's avatar
wsc  
Jason Phang committed
441
            + f"Question: In the passage above, does the pronoun \"*{pronoun}*\" refer to \"*{noun}*\"?\n"
Jason Phang's avatar
Jason Phang committed
442
443
444
445
            + "Answer:"
        )
        return text

446
    def doc_to_target(self, doc):
Leo Gao's avatar
Leo Gao committed
447
        return " " + yesno(doc['label'])
448

Leo Gao's avatar
Leo Gao committed
449
    def construct_requests(self, doc, ctx):
Jason Phang's avatar
wsc  
Jason Phang committed
450
451
452
453
454

        ll_yes, _ = rf.loglikelihood(ctx, ' yes')
        ll_no, _ = rf.loglikelihood(ctx, ' no')

        return ll_yes, ll_no
455

Jason Phang's avatar
Jason Phang committed
456
    def process_results(self, doc, results):
Jason Phang's avatar
wsc  
Jason Phang committed
457
458
459
460
461
462
463
464
        ll_yes, ll_no = results
        gold = doc["label"]

        acc = 1. if (ll_yes > ll_no) == gold else 0.

        return {
            "acc": acc
        }
Anish Thite's avatar
Anish Thite committed
465

Leo Gao's avatar
Leo Gao committed
466
    def higher_is_better(self):
Jason Phang's avatar
Jason Phang committed
467
468
469
470
471
472
473
474
        return {
            "acc": True
        }

    def aggregation(self):
        return {
            "acc": mean
        }