superglue.py 11.9 KB
Newer Older
Jason Phang's avatar
Jason Phang committed
1
2
3
4
5
"""
To-do:
    - WSC requires free-form generation
    - ReCoRD
"""
Jason Phang's avatar
Jason Phang committed
6
import numpy as np
7
8
import sklearn
import transformers.data.metrics.squad_metrics as squad_metrics
Jason Phang's avatar
Jason Phang committed
9
from . common import HFTask, yesno
&'s avatar
& committed
10
11
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
12
from ..utils import general_detokenize
Jason Phang's avatar
Jason Phang committed
13

Jason Phang's avatar
Jason Phang committed
14

15
class BoolQ(HFTask):
16
    VERSION = 1
Leo Gao's avatar
Leo Gao committed
17
18
    DATASET_PATH = "super_glue"
    DATASET_NAME = "boolq"
Jason Phang's avatar
Jason Phang committed
19
20
21
22
23
24
25
26

    def has_training_docs(self):
        return True

    def has_validation_docs(self):
        return True

    def has_test_docs(self):
27
        return False
Jason Phang's avatar
Jason Phang committed
28

Leo Gao's avatar
Update  
Leo Gao committed
29
    def doc_to_text(self, doc):
30
        return f"{doc['passage']}\nQuestion: {doc['question']}?\nAnswer:"
Leo Gao's avatar
Update  
Leo Gao committed
31
32
    
    def doc_to_target(self, doc):
33
        return " " + yesno(doc['label']) 
Jason Phang's avatar
Jason Phang committed
34

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

37
        ll_yes, _ = rf.loglikelihood(ctx, ' yes')
Jason Phang's avatar
Jason Phang committed
38
        ll_no, _ = rf.loglikelihood(ctx, ' no')
Leo Gao's avatar
Update  
Leo Gao committed
39
40
41
42
43
44
45
46
47

        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.

48
49
50
51
52
53
54
55
56
57
58
59
60
        return {
            "acc": acc
        }
    
    def higher_is_better(self):
        return {
            "acc": True
        }
    
    def aggregation(self):
        return {
            "acc": mean
        }
Jason Phang's avatar
Jason Phang committed
61

Jason Phang's avatar
Jason Phang committed
62

63
class CommitmentBank(HFTask):
thomasw21's avatar
thomasw21 committed
64
    VERSION = 1
Leo Gao's avatar
Leo Gao committed
65
66
    DATASET_PATH = "super_glue"
    DATASET_NAME = "cb"
Jason Phang's avatar
Jason Phang committed
67
68
69
70
71
72
73
74

    def has_training_docs(self):
        return True

    def has_validation_docs(self):
        return True

    def has_test_docs(self):
75
        return False
Jason Phang's avatar
Jason Phang committed
76

77
    def doc_to_text(self, doc):
Leo Gao's avatar
Leo Gao committed
78
        return "{}\nQuestion: {}. True, False or Neither?\nAnswer:".format(
Jason Phang's avatar
Jason Phang committed
79
80
81
            doc["premise"],
            doc["hypothesis"],
        )
82

thefazzer's avatar
thefazzer committed
83
    def doc_to_target(self, doc):
84
85
86
        # True = entailment
        # False = contradiction
        # Neither = neutral
thomasw21's avatar
Fix CB  
thomasw21 committed
87
        return " {}".format({0: "True", 1: "False", 2: "Neither"}[doc["label"]])
Jason Phang's avatar
Jason Phang committed
88

thefazzer's avatar
thefazzer committed
89
    def construct_requests(self, doc, ctx):
Leo Gao's avatar
Leo Gao committed
90
91
        ll_true, _ = rf.loglikelihood(ctx, ' True')
        ll_false, _ = rf.loglikelihood(ctx, ' False')
thomasw21's avatar
Fix CB  
thomasw21 committed
92
        ll_neither, _ = rf.loglikelihood(ctx, ' Neither')
93

thomasw21's avatar
Fix CB  
thomasw21 committed
94
        return ll_true, ll_false, ll_neither
thefazzer's avatar
thefazzer committed
95
96
97

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

thefazzer's avatar
thefazzer committed
101
        return {
thefazzer's avatar
thefazzer committed
102
103
            "acc": acc,
            "f1": (pred, gold)
thefazzer's avatar
thefazzer committed
104
105
106
107
        }
    
    def higher_is_better(self):
        return {
108
109
            "acc": True,
            "f1": True
thefazzer's avatar
thefazzer committed
110
        }
Jason Phang's avatar
Jason Phang committed
111
112
113
114
115
116
117
118
119
120
121

    @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
122
123
124
    
    def aggregation(self):
        return {
thefazzer's avatar
thefazzer committed
125
            "acc": mean,
Jason Phang's avatar
Jason Phang committed
126
            "f1": self.cb_multi_fi,
thefazzer's avatar
thefazzer committed
127
        }
Jason Phang's avatar
Jason Phang committed
128

Jason Phang's avatar
Jason Phang committed
129

130
class Copa(HFTask):
Leo Gao's avatar
Leo Gao committed
131
    VERSION = 0
Leo Gao's avatar
Leo Gao committed
132
133
    DATASET_PATH = "super_glue"
    DATASET_NAME = "copa"
Jason Phang's avatar
Jason Phang committed
134
135
136
137
138
139
140
141

    def has_training_docs(self):
        return True

    def has_validation_docs(self):
        return True

    def has_test_docs(self):
142
        return False
Jason Phang's avatar
Jason Phang committed
143

144
    def doc_to_text(self, doc):
Jason Phang's avatar
Jason Phang committed
145
        # Drop the period
Jason Phang's avatar
Jason Phang committed
146
147
148
149
        connector = {
            "cause": "because",
            "effect": "therefore",
        }[doc["question"]]
150
        return doc["premise"].strip()[:-1] + f" {connector}"
Jason Phang's avatar
Jason Phang committed
151

thefazzer's avatar
thefazzer committed
152
    def doc_to_target(self, doc):
153
154
        correct_choice = doc["choice1"] if doc["label"] == 0 else doc["choice2"]
        # Connect the sentences
155
        return " " + self.convert_choice(correct_choice)
thefazzer's avatar
thefazzer committed
156
157

    def construct_requests(self, doc, ctx):
thefazzer's avatar
thefazzer committed
158
159
        choice1 = " " + self.convert_choice(doc["choice1"])
        choice2 = " " + self.convert_choice(doc["choice2"])
thefazzer's avatar
thefazzer committed
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
        
        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
184
185
186
187
188
189

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


190
class MultiRC(HFTask):
191
    VERSION = 1
Leo Gao's avatar
Leo Gao committed
192
193
    DATASET_PATH = "super_glue"
    DATASET_NAME = "multirc"
Jason Phang's avatar
multirc  
Jason Phang committed
194
195
196
197
198
199
200
201

    def has_training_docs(self):
        return True

    def has_validation_docs(self):
        return True

    def has_test_docs(self):
202
        return False
Jason Phang's avatar
multirc  
Jason Phang committed
203

204
    def doc_to_text(self, doc):
Leo Gao's avatar
Leo Gao committed
205
        return f"{doc['paragraph']}\nQuestion: {doc['question']}\nAnswer:"
206
207

    def doc_to_target(self, doc):
Leo Gao's avatar
Leo Gao committed
208
        return " " + self.format_answer(answer=doc["answer"], label=doc["label"])
Jason Phang's avatar
multirc  
Jason Phang committed
209
210
211

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

thefazzer's avatar
thefazzer committed
215
216
217
218
219
220
221
222
223
224
    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
225
226
        ll_true_choice, ll_false_choice = results
        pred = ll_true_choice > ll_false_choice
Jason Phang's avatar
multirc  
Jason Phang committed
227
        return {
thefazzer's avatar
thefazzer committed
228
229
230
231
232
233
234
235
236
237
238
            "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
239
240
        }

Jason Phang's avatar
Jason Phang committed
241
242

class ReCoRD(HFTask):
Leo Gao's avatar
Leo Gao committed
243
    VERSION = 0
Jason Phang's avatar
Jason Phang committed
244
245
246
247
248
249
250
251
252
253
    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
254
        return False
Jason Phang's avatar
Jason Phang committed
255
256
257
258

    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.
259
260
261
        if self._training_docs is None:
            self._training_docs = []
            for doc in self.data["train"]:
Jason Phang's avatar
Jason Phang committed
262
                self._training_docs.append(self._process_doc(doc))
263
264
265
        return self._training_docs

    def validation_docs(self):
Jason Phang's avatar
Jason Phang committed
266
267
268
269
270
271
272
273
274
275
276
277
        # 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
278
279
280
281
282
283
284
285
286
287
288
289
290

    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
291
292
        # 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
293
294
295
296

    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
297
            for entity in doc["entities"]
Jason Phang's avatar
Jason Phang committed
298
299
300
301
302
303
304
305
        ]
        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
306
        max_idx = np.argmax(np.array([result[0] for result in results]))
Leo Gao's avatar
Leo Gao committed
307

Jason Phang's avatar
Jason Phang committed
308
        prediction = doc["entities"][max_idx]
Jason Phang's avatar
Jason Phang committed
309
        gold_label_set = doc["answers"]
Jason Phang's avatar
Jason Phang committed
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
        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,
        }


331
class WordsInContext(HFTask):
Leo Gao's avatar
Leo Gao committed
332
    VERSION = 0
Leo Gao's avatar
Leo Gao committed
333
334
    DATASET_PATH = "super_glue"
    DATASET_NAME = "wic"
Jason Phang's avatar
Jason Phang committed
335
336
337
338
339
340
341
342

    def has_training_docs(self):
        return True

    def has_validation_docs(self):
        return True

    def has_test_docs(self):
343
        return False
Jason Phang's avatar
Jason Phang committed
344

345
    def doc_to_text(self, doc):
Leo Gao's avatar
Leo Gao committed
346
347
        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
348
349
350
351
                    doc["sentence1"],
                    doc["sentence2"],
                    doc["sentence1"][doc["start1"]:doc["end1"]],
                )
352
353
354

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

Jason Phang's avatar
Jason Phang committed
356
357
358
359
360
    def construct_requests(self, doc, ctx):
        ll_yes, _ = rf.loglikelihood(ctx, ' yes')
        ll_no, _ = rf.loglikelihood(ctx, ' no')

        return ll_yes, ll_no
361

Jason Phang's avatar
Jason Phang committed
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
    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
381
382


383
class SGWinogradSchemaChallenge(HFTask):
Leo Gao's avatar
Leo Gao committed
384
    VERSION = 0
Jason Phang's avatar
wsc  
Jason Phang committed
385
386
    # 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
387
388
    DATASET_PATH = "super_glue"
    DATASET_NAME = "wsc"
Jason Phang's avatar
Jason Phang committed
389
390
391
392
393
394
395
396

    def has_training_docs(self):
        return True

    def has_validation_docs(self):
        return True

    def has_test_docs(self):
397
        return False
Jason Phang's avatar
Jason Phang committed
398
399
400
401

    def training_docs(self):
        if self.has_training_docs():
            if self._training_docs is None:
Jason Phang's avatar
Jason Phang committed
402
                # GPT-3 Paper's format only uses positive examples for fewshot "training"
Jason Phang's avatar
Jason Phang committed
403
404
                self._training_docs = [
                    doc for doc in
Jason Phang's avatar
Jason Phang committed
405
                    self.data["train"]
Jason Phang's avatar
Jason Phang committed
406
407
408
409
                    if doc["label"]
                ]
            return self._training_docs

410
    def doc_to_text(self, doc):
Jason Phang's avatar
Jason Phang committed
411
        raw_passage = doc["text"]
Jonathan Tow's avatar
Jonathan Tow committed
412
413
414
        # 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
415
        passage = general_detokenize(pre + " *{}*".format(doc['span2_text']) + post)
Jason Phang's avatar
wsc  
Jason Phang committed
416
        noun = doc["span1_text"]
Jason Phang's avatar
Jason Phang committed
417
418
419
        pronoun = doc["span2_text"]
        text = (
            f"Passage: {passage}\n"
Jason Phang's avatar
wsc  
Jason Phang committed
420
            + f"Question: In the passage above, does the pronoun \"*{pronoun}*\" refer to \"*{noun}*\"?\n"
Jason Phang's avatar
Jason Phang committed
421
422
423
424
            + "Answer:"
        )
        return text

425
    def doc_to_target(self, doc):
Leo Gao's avatar
Leo Gao committed
426
        return " " + yesno(doc['label'])
427

Leo Gao's avatar
Leo Gao committed
428
    def construct_requests(self, doc, ctx):
Jason Phang's avatar
wsc  
Jason Phang committed
429
430
431
432
433

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

        return ll_yes, ll_no
434

Jason Phang's avatar
Jason Phang committed
435
    def process_results(self, doc, results):
Jason Phang's avatar
wsc  
Jason Phang committed
436
437
438
439
440
441
442
443
        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
444

Leo Gao's avatar
Leo Gao committed
445
    def higher_is_better(self):
Jason Phang's avatar
Jason Phang committed
446
447
448
449
450
451
452
453
        return {
            "acc": True
        }

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