superglue.py 10.7 KB
Newer Older
Leo Gao's avatar
Leo Gao committed
1
2
# REMINDER: this code needs to be rewritten for the new framework. Remove this comment when the code is fully converted.

Jason Phang's avatar
Jason Phang committed
3
4
import numpy as np
from tqdm import auto as tqdm_lib
5
from . common import HFTask, simple_accuracy_metric, yesno
thefazzer's avatar
thefazzer committed
6
from lm_eval.base import rf, mean, f1_score, acc_all
Jason Phang's avatar
Jason Phang committed
7

8
class BoolQ(HFTask):
Leo Gao's avatar
Leo Gao committed
9
10
    DATASET_PATH = "super_glue"
    DATASET_NAME = "boolq"
Jason Phang's avatar
Jason Phang committed
11
12
13
14
15
16
17
18
19
20
21

    def has_training_docs(self):
        return True

    def has_validation_docs(self):
        return True

    def has_test_docs(self):
        return True

    def fewshot_description(self):
22
        # TODO: figure out actual description
Jason Phang's avatar
Jason Phang committed
23
24
        return "Read the following passages and answer each question with a yes or a no."

Leo Gao's avatar
Update  
Leo Gao committed
25
26
27
28
29
    def doc_to_text(self, doc):
        return f"{doc['passage']}\nquestion: {doc['question']}\nanswer: "
    
    def doc_to_target(self, doc):
        return yesno(doc['label']) 
Jason Phang's avatar
Jason Phang committed
30

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

33
34
        ll_yes, _ = rf.loglikelihood(ctx, ' yes')
        ll_no , _ = rf.loglikelihood(ctx, ' no')
Leo Gao's avatar
Update  
Leo Gao committed
35
36
37
38
39
40
41
42
43

        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.

44
45
46
47
48
49
50
51
52
53
54
55
56
        return {
            "acc": acc
        }
    
    def higher_is_better(self):
        return {
            "acc": True
        }
    
    def aggregation(self):
        return {
            "acc": mean
        }
Jason Phang's avatar
Jason Phang committed
57

58
class CommitmentBank(HFTask):
Leo Gao's avatar
Leo Gao committed
59
60
    DATASET_PATH = "super_glue"
    DATASET_NAME = "cb"
Jason Phang's avatar
Jason Phang committed
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 True

thefazzer's avatar
thefazzer committed
71
72
73
    def fewshot_description(self):
        return "Given a premise and a hypothesis, classify whether the author of the premise is committed to the truth of the hypothesis. The three possible labels are true, false or neither."

74
    def doc_to_text(self, doc):
75
        return "{}\nquestion: {} true, false or neither?\nanswer:".format(
Jason Phang's avatar
Jason Phang committed
76
77
78
            doc["premise"],
            doc["hypothesis"],
        )
79

thefazzer's avatar
thefazzer committed
80
    def doc_to_target(self, doc):
81
82
83
84
        # True = entailment
        # False = contradiction
        # Neither = neutral
        return " {}".format({0: "true", 1: "neither", 2: "false"}[doc["label"]])
Jason Phang's avatar
Jason Phang committed
85

thefazzer's avatar
thefazzer committed
86
87
88
89
    def construct_requests(self, doc, ctx):
        ll_true, _ = rf.loglikelihood(ctx, ' true')
        ll_neither, _ = rf.loglikelihood(ctx, ' neither')
        ll_false, _ = rf.loglikelihood(ctx, ' false')
90

thefazzer's avatar
thefazzer committed
91
92
93
94
        return ll_true, ll_neither, ll_false

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

thefazzer's avatar
thefazzer committed
98
        return {
thefazzer's avatar
thefazzer committed
99
100
            "acc": acc,
            "f1": (pred, gold)
thefazzer's avatar
thefazzer committed
101
102
103
104
        }
    
    def higher_is_better(self):
        return {
105
106
            "acc": True,
            "f1": True
thefazzer's avatar
thefazzer committed
107
108
109
110
        }
    
    def aggregation(self):
        return {
thefazzer's avatar
thefazzer committed
111
112
            "acc": mean,
            "f1": f1_score
thefazzer's avatar
thefazzer committed
113
        }
Jason Phang's avatar
Jason Phang committed
114

115
class Copa(HFTask):
Leo Gao's avatar
Leo Gao committed
116
117
    DATASET_PATH = "super_glue"
    DATASET_NAME = "copa"
Jason Phang's avatar
Jason Phang committed
118
119
120
121
122
123
124
125
126
127

    def has_training_docs(self):
        return True

    def has_validation_docs(self):
        return True

    def has_test_docs(self):
        return True

thefazzer's avatar
thefazzer committed
128
    def fewshot_description(self):
thefazzer's avatar
thefazzer committed
129
        return "Given a premise and one alternative with a causal relation to the premise and another without, choose the more plausible alternative"
thefazzer's avatar
thefazzer committed
130

131
    def doc_to_text(self, doc):
Jason Phang's avatar
Jason Phang committed
132
        # Drop the period
Jason Phang's avatar
Jason Phang committed
133
134
135
136
        connector = {
            "cause": "because",
            "effect": "therefore",
        }[doc["question"]]
137
        return doc["premise"].strip()[:-1] + f" {connector} "
Jason Phang's avatar
Jason Phang committed
138

thefazzer's avatar
thefazzer committed
139
    def doc_to_target(self, doc):
140
141
142
        correct_choice = doc["choice1"] if doc["label"] == 0 else doc["choice2"]
        # Connect the sentences
        return self.convert_choice(correct_choice)
thefazzer's avatar
thefazzer committed
143
144

    def construct_requests(self, doc, ctx):
thefazzer's avatar
thefazzer committed
145
146
        choice1 = " " + self.convert_choice(doc["choice1"])
        choice2 = " " + self.convert_choice(doc["choice2"])
thefazzer's avatar
thefazzer committed
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
        
        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
171
172
173
174
175
176

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


177
class MultiRC(HFTask):
Leo Gao's avatar
Leo Gao committed
178
179
    DATASET_PATH = "super_glue"
    DATASET_NAME = "multirc"
Jason Phang's avatar
multirc  
Jason Phang committed
180
181
182
183
184
185
186
187
188
189
190
191
192

    def has_training_docs(self):
        return True

    def has_validation_docs(self):
        return True

    def has_test_docs(self):
        return True

    def fewshot_description(self):
        return "READING COMPREHENSION ANSWER KEY"

193
194
195
196
197
    def doc_to_text(self, doc):
        return f"{doc['paragraph']}\n\n{doc['question']}\n"

    def doc_to_target(self, doc):
        return self.format_answer(answer=doc["answer"], label=doc["label"])
Jason Phang's avatar
multirc  
Jason Phang committed
198
199
200
201
202
203

    @staticmethod
    def format_answer(answer, label):
        label_str = "True" if label else "False"
        return f"[{label_str}] {answer}"

thefazzer's avatar
thefazzer committed
204
205
206
207
208
209
210
211
212
213
214
215
216
    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):
        gold = doc["label"]
        pred = np.argmax(results)
        acc = 1. if pred == gold else 0.
217

Jason Phang's avatar
multirc  
Jason Phang committed
218
        return {
thefazzer's avatar
thefazzer committed
219
220
221
222
223
224
225
226
227
228
229
            "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
230
231
        }

232
class WordsInContext(HFTask):
Leo Gao's avatar
Leo Gao committed
233
234
    DATASET_PATH = "super_glue"
    DATASET_NAME = "wic"
Jason Phang's avatar
Jason Phang committed
235
236
237
238
239
240
241
242
243
244

    def has_training_docs(self):
        return True

    def has_validation_docs(self):
        return True

    def has_test_docs(self):
        return True

245
    def doc_to_text(self, doc):
246
        return "{}\n{}\nQuestion: Is the word '{}' used in the same way in the" \
Jason Phang's avatar
Jason Phang committed
247
248
249
250
251
               " two sentences above?\nanswer:".format(
                    doc["sentence1"],
                    doc["sentence2"],
                    doc["sentence1"][doc["start1"]:doc["end1"]],
                )
252
253
254

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

    def evaluate(self, docs, lm, provide_description, num_fewshot):
257
258
259
260
261
        # TODO: Implement evaluation code using new framework

        # ***IMPORTANT***: this evaluation function needs to be rewritten for the new framework. 
        # For more info, check out the interface in base.py and the example BoolQ implementation in superglue.py. 
        # Remove this comment when the evaluation code is implemented.
Jason Phang's avatar
Jason Phang committed
262
263
264
265
266
267
268
269
270
271
272
273
        golds = [doc["label"] for doc in docs]
        preds = []
        for doc in tqdm_lib.tqdm(docs):
            ctx = self.fewshot_context(
                doc=doc,
                provide_description=provide_description,
                num_fewshot=num_fewshot,
            )
            preds.append(lm.loglikelihood(ctx, ' yes') > lm.loglikelihood(ctx, ' no'))
        return simple_accuracy_metric(preds=preds, golds=golds)


274
class SGWinogradSchemaChallenge(HFTask):
Leo Gao's avatar
Leo Gao committed
275
276
    DATASET_PATH = "super_glue"
    DATASET_NAME = "wsc"
Jason Phang's avatar
Jason Phang committed
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303

    def has_training_docs(self):
        return True

    def has_validation_docs(self):
        return True

    def has_test_docs(self):
        return True

    def training_docs(self):
        if self.has_training_docs():
            if self._training_docs is None:
                # GPT-3 Paper's format only uses positive examples
                self._training_docs = [
                    doc for doc in
                    self._load_nlp_dataset()["train"]
                    if doc["label"]
                ]
            return self._training_docs

    def fewshot_description(self):
        return "Final Exam with Answer Key\n" \
           "Instructions: Please carefully read the following passages. " \
           "For each passage, you must identify which noun the pronoun marked in *bold*" \
           " refers to.\n====="

304
    def doc_to_text(self, doc):
Jason Phang's avatar
Jason Phang committed
305
306
307
308
309
310
311
312
313
314
315
316
317
318
        raw_passage = doc["text"]
        passage = (
            raw_passage[:doc["span2_index"]]
            + "*{}*".format(doc["span2_text"])
            + raw_passage[doc["span2_index"] + len(doc["span2_text"]):]
        )
        pronoun = doc["span2_text"]
        text = (
            f"Passage: {passage}\n"
            + f"Question: In the passage above, what does the pronoun \"*{pronoun}*\" refer to?\n"
            + "Answer:"
        )
        return text

319
320
321
    def doc_to_target(self, doc):
        return " {}".format(doc["span1_text"])

Jason Phang's avatar
Jason Phang committed
322
    def evaluate(self, docs, lm, provide_description, num_fewshot):
323
324
325
326
327
        # TODO: Implement evaluation code using new framework

        # ***IMPORTANT***: this evaluation function needs to be rewritten for the new framework. 
        # For more info, check out the interface in base.py and the example BoolQ implementation in superglue.py. 
        # Remove this comment when the evaluation code is implemented.
Jason Phang's avatar
Jason Phang committed
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
        golds = [doc["label"] for doc in docs]
        preds = []
        for doc in tqdm_lib.tqdm(docs):
            ctx = self.fewshot_context(
                doc=doc,
                provide_description=provide_description,
                num_fewshot=num_fewshot,
            )
            to_predict = " " + doc["span1_text"]
            num_tokens = len(lm.tokenizer.tokenize(to_predict))
            generated = lm.generate(
                context=ctx,
                max_gen_length=num_tokens,
            )
            preds.append(1 if generated == to_predict else 0)
        return simple_accuracy_metric(preds=preds, golds=golds)
Anish Thite's avatar
Anish Thite committed
344
345
346
347
348
349
350
351
352

class RTE(HFTask):
    DATASET_PATH = "super_glue"
    DATASET_NAME = "rte"

    def fewshot_description(self):
        #TODO: implement
        pass

353
354
355
356
357
358
    def doc_to_text(self, doc):
        return ''.join([doc['premise'], '\nquestion: ',doc['hypothesis'], ' True or False?\nanswer: '])

    def doc_to_target(self, doc):
        return 'True' if doc['label'] == 0 else 'False'

359
360
361
362
363
    # TODO: Implement evaluation code

    # ***IMPORTANT***: this evaluation function needs to be written for the new framework. 
    # For more info, check out the interface in base.py and the example BoolQ implementation in superglue.py. 
    # Remove this comment when the evaluation code is implemented.
Anish Thite's avatar
Anish Thite committed
364