coqa.py 5.67 KB
Newer Older
1
import os
2
import json
3
import transformers.data.metrics.squad_metrics as squad_metrics
4
from lm_eval.base import Task, rf, mean
sdtblck's avatar
sdtblck committed
5
from ..utils import sh
6
from itertools import zip_longest
7
from best_download import download_file
8

9

10
class CoQA(Task):
Leo Gao's avatar
Leo Gao committed
11
    VERSION = 1
thefazzer's avatar
thefazzer committed
12

sdtblck's avatar
sdtblck committed
13
    def download(self):
14
15
16
17
        coqa_train_filepath = 'data/coqa/coqa-train-v1.0.json'
        coqa_dev_filepath = 'data/coqa/coqa-dev-v1.0.json'

        sh ("""mkdir -p data/coqa""")
18

19
20
        download_file("http://downloads.cs.stanford.edu/nlp/data/coqa/coqa-train-v1.0.json", local_file=coqa_train_filepath, expected_checksum="b0fdb2bc1bd38dd3ca2ce5fa2ac3e02c6288ac914f241ac409a655ffb6619fa6")
        download_file("http://downloads.cs.stanford.edu/nlp/data/coqa/coqa-dev-v1.0.json", local_file=coqa_dev_filepath, expected_checksum="dfa367a9733ce53222918d0231d9b3bedc2b8ee831a2845f62dfc70701f2540a")
sdtblck's avatar
sdtblck committed
21

22
23
24
25
    def has_training_docs(self):
        return True

    def has_validation_docs(self):
Anish Thite's avatar
Anish Thite committed
26
        return True
Jason Phang's avatar
Jason Phang committed
27
28
29
30

    def has_test_docs(self):
        return False

31
    def training_docs(self):
32
        return json.load(open('data/coqa/coqa-train-v1.0.json'))['data']
33
34

    def validation_docs(self):
thefazzer's avatar
thefazzer committed
35
        return json.load(open('data/coqa/coqa-dev-v1.0.json'))['data']
36
37

    def test_docs(self):
Leo Gao's avatar
Leo Gao committed
38
        pass
39

Leo Gao's avatar
Leo Gao committed
40
    def doc_to_text(self, doc):
thefazzer's avatar
thefazzer committed
41
42
        # Given a passage p, the conversation history {q1, a1, . . . qi−1, ai−1} 
        # and a question qi, the task is to predict the answer ai
43
        doc_text = doc["story"] + '\n\n'
thefazzer's avatar
thefazzer committed
44
        for (q, a) in zip_longest(doc["questions"], doc["answers"][:-1]):   # omit target answer ai
45
            question = f"Q: {q['input_text']}" + '\n\n'
Leo Gao's avatar
Leo Gao committed
46
            answer = f"A: {a['input_text']}" + '\n\n' if a is not None else "A:"
47
48
            doc_text += question + answer
        return doc_text
thefazzer's avatar
thefazzer committed
49
        
50
51
    @classmethod
    def get_answers(cls, doc, turn_id):
thefazzer's avatar
thefazzer committed
52
        # Returns unique answers and valid alternatives (Some questions in CoQA have multiple valid answers).
53
54
55
56
        answers = []
        answer_forturn = doc["answers"][turn_id - 1]["input_text"]
        answers.append(answer_forturn)
        
thefazzer's avatar
thefazzer committed
57
58
59
60
61
        additional_answers = doc.get("additional_answers")
        if additional_answers:
            for key in additional_answers:
                additional_answer_for_turn = additional_answers[key][turn_id - 1]["input_text"]
                if additional_answer_for_turn.lower() not in map(str.lower, answers):
62
63
                    answers.append(additional_answer_for_turn)
        return answers
thefazzer's avatar
thefazzer committed
64
    
thefazzer's avatar
thefazzer committed
65
66
67
68
69
70
71
72
73
74
75
76
77
    @classmethod
    def get_answer_choice(self, raw_text):
        # Function maps answers to CoQA answer categories
        # ~ 1/5 of the CoQA answers are Yes/No 
        # ~ 2/3 of the CoQA answers are span-based
        # (answers overlap with the passage ignoring punctuation and case mismatch)
        if raw_text == "unknown":
            return '0'
        if squad_metrics.normalize_answer(raw_text) == "yes":
            return '1'
        if squad_metrics.normalize_answer(raw_text) == "no":
            return '2'
        return '3' # Not a yes/no question
Leo Gao's avatar
Leo Gao committed
78

79
80
    @staticmethod
    def compute_scores(gold_list, pred):
thefazzer's avatar
thefazzer committed
81
82
        # tests for exact match and on the normalised answer (compute_exact)
        # test for overlap (compute_f1)
83
84
85
86
87
        f1_sum = 0.0
        em_sum = 0.0
        if len(gold_list) > 1:
            for i in range(len(gold_list)):
                gold_answers = gold_list[0:i] + gold_list[i + 1:]
thefazzer's avatar
thefazzer committed
88
                # predictions compared against (n) golds and take maximum
89
90
91
92
93
94
95
96
                em_sum += max(squad_metrics.compute_exact(a, pred) for a in gold_answers)
                f1_sum += max(squad_metrics.compute_f1(a, pred) for a in gold_answers)
        else:
            em_sum += max(squad_metrics.compute_exact(a, pred) for a in gold_list)
            f1_sum += max(squad_metrics.compute_f1(a, pred) for a in gold_list)

        return {'em': em_sum / max(1, len(gold_list)), 'f1': f1_sum / max(1, len(gold_list))}

thefazzer's avatar
thefazzer committed
97
98
99
100
101
    def doc_to_target(self, doc, turnid=None):
        # Default to prediction of last turn.
        if turnid is None:
            turnid = len(doc["questions"])
        raw_text = doc['answers'][turnid - 1]["input_text"]
Leo Gao's avatar
Leo Gao committed
102
        return " " + raw_text
thefazzer's avatar
thefazzer committed
103

Leo Gao's avatar
Leo Gao committed
104
105
106
107
108
109
110
111
112
113
114
    def construct_requests(self, doc, ctx):
        """ Uses RequestFactory to construct Requests and returns an iterable of 
        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`. 
        """
115
        cont_request = rf.greedy_until(ctx, ['\nQ:'])
116
        return cont_request
thefazzer's avatar
thefazzer committed
117

Leo Gao's avatar
Leo Gao committed
118
119
120
121
122
123
124
125
126
127
    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.
        """
128
        turn_id = len(doc["questions"])
129
        gold_list = self.get_answers(doc, turn_id)
130
        pred = results[0].strip().split('\n')[0]
131

thefazzer's avatar
thefazzer committed
132
        scores = self.compute_scores(gold_list, pred)
133

thefazzer's avatar
thefazzer committed
134
        return {
thefazzer's avatar
thefazzer committed
135
136
            "f1": scores['f1'],
            "em": scores['em'],
thefazzer's avatar
thefazzer committed
137
        }
138
139

    def higher_is_better(self):
140
        return {
141
142
            "f1": True,
            "em": True,
143
        }
Leo Gao's avatar
Leo Gao committed
144

145
    def aggregation(self):
146
        return {
147
148
            "f1": mean,
            "em": mean,
Leo Gao's avatar
Leo Gao committed
149
        }