winogrande.py 4.36 KB
Newer Older
Charles Foster's avatar
Charles Foster committed
1
import numpy as np
2
3
4
5
6
7
8
9
10
from . common import HFTask
from lm_eval.base import rf, mean

"""
This evaluation of Winogrande uses partial evaluation as described by
Trinh & Le in Simple Method for Commonsense Reasoning (2018).
Reference: https://arxiv.org/abs/1806.02847
"""

Charles Foster's avatar
Charles Foster committed
11
12
13
14
15

class Winogrande(HFTask):
    DATASET_PATH = "winogrande"
    DATASET_NAME = "winogrande_xl"

16
17
    answer_to_num = {'1': 0, '2': 1}

Charles Foster's avatar
Charles Foster committed
18
19
20
21
22
23
24
    def has_training_docs(self):
        return True

    def has_validation_docs(self):
        return True

    def has_test_docs(self):
25
        return False
Charles Foster's avatar
Charles Foster committed
26

27
28
    def doc_to_text(self, doc):
        return self.partial_context(doc, doc["option" + doc["answer"]])
Charles Foster's avatar
Charles Foster committed
29

30
    @classmethod
31
32
    def partial_context(cls, doc, option):
        # Substitute the pronoun in the sentence with the specified option
33
34
        # and ignore everything after.
        pronoun_loc = doc["sentence"].index("_")
35
36
37
38
        return doc["sentence"][:pronoun_loc] + option

    def doc_to_target(self, doc):
        return " " + self.partial_target(doc)
39
40
41
42
43
44
45

    @classmethod
    def partial_target(cls, doc):
        # The target is everything after the document specified pronoun.
        pronoun_loc = doc["sentence"].index("_") + 1
        return doc["sentence"][pronoun_loc:].strip()

46
47
48
    def fewshot_description(self):
        # TODO: redo description
        return "Winograd schema sentence including a either a ___ blank with a missing word, making the pronoun ambiguous, or the same with the word filled in."
49

50
51
52
53
54
55
56
57
    def fewshot_context(self, doc, num_fewshot, provide_description):
        fewshot_ctx = super().fewshot_context(doc, num_fewshot, provide_description)
        return fewshot_ctx + "\n" + self._wrong_partial_context(doc)

    def _wrong_partial_context(self, doc):
        wrong_answer = f"{int(not self.answer_to_num[doc['answer']]) + 1}"
        wrong_option = doc["option" + wrong_answer]
        return self.partial_context(doc, wrong_option)
Charles Foster's avatar
Charles Foster committed
58

Leo Gao's avatar
Leo Gao committed
59
    def construct_requests(self, doc, ctx):
60
        """Uses RequestFactory to construct Requests and returns an iterable of
Leo Gao's avatar
Leo Gao committed
61
        Requests which will be sent to the LM.
62

Leo Gao's avatar
Leo Gao committed
63
64
65
        :param doc:
            The document as returned from training_docs, validation_docs, or test_docs.
        :param ctx: str
66
            The context string, generated by fewshot_context. This includes the natural
Leo Gao's avatar
Leo Gao committed
67
            language description, as well as the few shot examples, and the question
68
            part of the document for `doc`.
Leo Gao's avatar
Leo Gao committed
69
        """
70
        target = self.partial_target(doc)
71
72
73
74
75
76
77
78
79
80
81
82
83
        right_ctx, wrong_ctx = self.split_fewshot_context(ctx)
        ll_right_ctx, _ = rf.loglikelihood(right_ctx, target)
        ll_wrong_ctx, _ = rf.loglikelihood(wrong_ctx, target)
        return ll_right_ctx, ll_wrong_ctx

    @classmethod
    def split_fewshot_context(cls, ctx):
        ctx = ctx.split("\n\n")  # Each fewshot context is on its own new line.
        partial_ctxs = ctx.pop().split("\n")
        # NOTE: First context in `partial_ctxs` is always right because of `doc_to_text`.
        right_ctx = "\n\n".join([*ctx, partial_ctxs[0]]) if ctx else partial_ctxs[0]
        wrong_ctx = "\n\n".join([*ctx, partial_ctxs[1]]) if ctx else partial_ctxs[1]
        return right_ctx, wrong_ctx
84

Leo Gao's avatar
Leo Gao committed
85
    def process_results(self, doc, results):
86
87
        """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
Leo Gao's avatar
Leo Gao committed
88
89
90
91
92
93
94
        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.
        """
95
        return {
96
            "acc": np.argmax(results) == self.answer_to_num[doc["answer"]]
97
        }
Leo Gao's avatar
Leo Gao committed
98
99
100
101

    def aggregation(self):
        """
        :returns: {str: [float] -> float}
102
            A dictionary where keys are the names of submetrics and values are
Leo Gao's avatar
Leo Gao committed
103
104
            functions that aggregate a list of metrics
        """
105
106
107
        return {
            "acc": mean
        }
Leo Gao's avatar
Leo Gao committed
108
109
110
111

    def higher_is_better(self):
        """
        :returns: {str: bool}
112
            A dictionary where keys are the names of submetrics and values are
Leo Gao's avatar
Leo Gao committed
113
114
            whether a higher value of the submetric is better
        """
115
116
117
        return {
            "acc": True
        }