mc_taco.py 5.31 KB
Newer Older
Jonathan Tow's avatar
Jonathan Tow committed
1
2
3
4
5
"""
“Going on a vacation” takes longer than “Going for a walk”:
A Study of Temporal Commonsense Understanding
https://arxiv.org/pdf/1909.03065.pdf

Fabrizio Milo's avatar
Fabrizio Milo committed
6
MC-TACO is a dataset of 13k question-answer pairs that require temporal commonsense
7
comprehension. The dataset contains five temporal properties, (1) duration (how long
Fabrizio Milo's avatar
Fabrizio Milo committed
8
an event takes), (2) temporal ordering (typical order of events), (3) typical time
9
10
11
(when an event occurs), (4) frequency (how often an event occurs), and (5) stationarity
(whether a state is maintained for a very long time or indefinitely).

Fabrizio Milo's avatar
Fabrizio Milo committed
12
WARNING: Running this task with a `--limit` arg will give misleading results! The
Jonathan Tow's avatar
Jonathan Tow committed
13
corresponding dataset is structured such that each multiple-choice-question gathered
Fabrizio Milo's avatar
Fabrizio Milo committed
14
by the authors is split into question-option pairs, where each such pair gets
Jonathan Tow's avatar
Jonathan Tow committed
15
16
siloed into an individual document for plausibility testing. Because the harness
shuffles these documents, setting `--limit` will likely "cut off" certain candidate
Fabrizio Milo's avatar
Fabrizio Milo committed
17
answers. This is a problem because the task's metrics require an exhaustive evaluation
18
of a question's options. See section 4 of the paper for details.
Jonathan Tow's avatar
Jonathan Tow committed
19

20
Homepage: https://leaderboard.allenai.org/mctaco/submissions/public
21
22
23
"""
import numpy as np
from collections import defaultdict
Jonathan Tow's avatar
Jonathan Tow committed
24
from lm_eval.base import rf, Task
25

26

27
_CITATION = """
Jonathan Tow's avatar
Jonathan Tow committed
28
29
30
31
32
33
34
35
36
@inproceedings{ZKNR19,
    author = {Ben Zhou, Daniel Khashabi, Qiang Ning and Dan Roth},
    title = {“Going on a vacation” takes longer than “Going for a walk”: A Study of Temporal Commonsense Understanding },
    booktitle = {EMNLP},
    year = {2019},
}
"""


Jonathan Tow's avatar
Jonathan Tow committed
37
class MCTACO(Task):
Jonathan Tow's avatar
Jonathan Tow committed
38
39
40
41
42
43
44
45
46
47
48
49
50
    VERSION = 0
    DATASET_PATH = "mc_taco"
    DATASET_NAME = None

    def has_training_docs(self):
        return False

    def has_validation_docs(self):
        return True

    def has_test_docs(self):
        return True

Jonathan Tow's avatar
Jonathan Tow committed
51
52
53
54
55
56
    def validation_docs(self):
        return self.dataset["validation"]

    def test_docs(self):
        return self.dataset["test"]

Jonathan Tow's avatar
Jonathan Tow committed
57
    def doc_to_text(self, doc):
Fabrizio Milo's avatar
Fabrizio Milo committed
58
59
        return (
            f"{doc['sentence']}\nQuestion: {doc['question']}\n"
Jonathan Tow's avatar
Jonathan Tow committed
60
            f"Answer: {doc['answer']}\nPlausible:"
Fabrizio Milo's avatar
Fabrizio Milo committed
61
        )
Jonathan Tow's avatar
Jonathan Tow committed
62

63
64
65
66
    def should_decontaminate(self):
        return True

    def doc_to_decontamination_query(self, doc):
Fabrizio Milo's avatar
Fabrizio Milo committed
67
        return doc["question"] + " " + doc["sentence"]
68

Jonathan Tow's avatar
Jonathan Tow committed
69
    def doc_to_target(self, doc):
Fabrizio Milo's avatar
Fabrizio Milo committed
70
        return " " + ["no", "yes"][doc["label"]]
Jonathan Tow's avatar
Jonathan Tow committed
71
72

    def construct_requests(self, doc, ctx):
Fabrizio Milo's avatar
Fabrizio Milo committed
73
        """Uses RequestFactory to construct Requests and returns an iterable of
Jonathan Tow's avatar
Jonathan Tow committed
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
        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`.
        """
        ll_no, _ = rf.loglikelihood(ctx, " no")
        ll_yes, _ = rf.loglikelihood(ctx, " yes")
        return ll_no, ll_yes

    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.
        """
        ll_no, ll_yes = results
Fabrizio Milo's avatar
Fabrizio Milo committed
98
        gold = doc["label"]
Jonathan Tow's avatar
Jonathan Tow committed
99
100
101
        pred = int(ll_yes > ll_no)
        question_id = self._question2id(doc)
        items = (gold, pred, question_id)
Fabrizio Milo's avatar
Fabrizio Milo committed
102
        return {"em": items, "f1": items}
Jonathan Tow's avatar
Jonathan Tow committed
103
104

    def _question2id(self, doc):
Fabrizio Milo's avatar
Fabrizio Milo committed
105
106
        """Returns an identifier for the question in the given document."""
        return " ".join([doc["sentence"], doc["question"]])
Jonathan Tow's avatar
Jonathan Tow committed
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133

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

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


def exact_match(items):
    """
    Counts a question as correct if the model accurately classifies the plausibility
    of an answer for all candidate answers. See section 4 "Evaluation Metrics" in the paper.
    """
    results = list(zip(*items))
    accuracies = defaultdict(list)
    for gold, pred, question in zip(results[0], results[1], results[2]):
        accuracies[question].append(pred == gold)
    return np.mean([int(all(accs)) for accs in accuracies.values()])


def f1(items):
Fabrizio Milo's avatar
Fabrizio Milo committed
134
    """See section 4 "Evaluation Metrics" in the paper about the F1 metric used."""
Jonathan Tow's avatar
Jonathan Tow committed
135
136
137
138
139
140
141
142
143
144
145
146
147
    results = list(zip(*items))
    # Group the positive ("yes" = 1) golds and predictions by question.
    gold_positives, pred_positives = defaultdict(list), defaultdict(list)
    for gold, pred, question in zip(results[0], results[1], results[2]):
        gold_positives[question].append(gold)
        pred_positives[question].append(pred)
    f1 = []
    for question in gold_positives.keys():
        gp, pp = sum(gold_positives[question]), sum(pred_positives[question])
        tp = sum(np.logical_and(gold_positives[question], pred_positives[question]))
        p = tp / pp if pp > 0.0 else 1.0
        r = tp / gp if gp > 0.0 else 1.0
        if p + r > 0.0:
Fabrizio Milo's avatar
Fabrizio Milo committed
148
            f1.append(2.0 * (p * r) / (p + r))
Jonathan Tow's avatar
Jonathan Tow committed
149
    return np.mean(f1)