coqa.py 4.96 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.

3
4
import json
import random
5
6
import numpy as np
from lm_eval.base import Dataset, rf, mean
sdtblck's avatar
sdtblck committed
7
from ..utils import sh
8
from itertools import zip_longest
9
import transformers.data.metrics.squad_metrics as squad_metrics
10
11

class CoQA(Dataset):
sdtblck's avatar
sdtblck committed
12
    def download(self):
13
14
        pass
        # -N only overwrites if the remote file has changed
thefazzer's avatar
thefazzer committed
15
        sh ("""
sdtblck's avatar
sdtblck committed
16
            mkdir -p data/coqa 
17
18
            wget -N http://downloads.cs.stanford.edu/nlp/data/coqa/coqa-train-v1.0.json -O data/coqa/coqa-train-v1.0.json
            wget -N http://downloads.cs.stanford.edu/nlp/data/coqa/coqa-dev-v1.0.json -O data/coqa/coqa-dev-v1.0.json
sdtblck's avatar
sdtblck committed
19
20
            """)

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

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

    def has_test_docs(self):
        return False

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

    def validation_docs(self):
34
        return json.load(open('data/coqa/coqa-dev-v1.0.json'))['data']  
35
36

    def test_docs(self):
Leo Gao's avatar
Leo Gao committed
37
        pass
38
39
    
    def fewshot_description(self):
thefazzer's avatar
thefazzer committed
40
        return "Given a passage and a conversation so far, answer the next question in the conversation."
41
    
Leo Gao's avatar
Leo Gao committed
42
    def doc_to_text(self, doc):
43
        # Each "doc" is a story and conversation (Q and A pairs).
44
45
46
47
48
        doc_text = doc["story"] + '\n\n'
        for (q, a) in zip_longest(doc["questions"], doc["answers"][:-1]):   # omit target answer
            question = f"Q: {q['input_text']}" + '\n\n'
            answer = f"A: {a['input_text']}" + '\n\n' if a is not None else "A:\n\n"
            doc_text += question + answer
49
            print(doc_text)
50
51
52
53
        return doc_text

    @classmethod
    def get_answers(cls, doc, turn_id):
54
        # This function returns an answer and valid alternatives.
55
56
57
58
59
60
61
62
63
64
65
        answers = []
        answer_forturn = doc["answers"][turn_id - 1]["input_text"]
        answers.append(answer_forturn)
        
        additionals = doc.get("additional_answers")
        if additionals:
            for key in additionals:
                additional_answer_for_turn = additionals[key][turn_id - 1]["input_text"]
                if additional_answer_for_turn.upper() not in map(str.upper, answers):
                    answers.append(additional_answer_for_turn)
        return answers
thefazzer's avatar
thefazzer committed
66
    
67
    def doc_to_target(self, doc, turnid=None):
68
        # Default to predict last turn.
69
70
71
72
        if turnid is None:
            turnid = len(doc["questions"])
        all_answers = self.get_answers(doc, turnid)
        return all_answers[0]   # ignore alternative answers for now
Leo Gao's avatar
Leo Gao committed
73

74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
    @staticmethod
    def compute_scores(gold_list, pred):
        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:]
                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))}

Leo Gao's avatar
Leo Gao committed
89
90
91
92
93
94
95
96
97
98
99
    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`. 
        """
100
        requests = []
101
102
103
        for answers in self.get_answers(doc, len(doc["questions"])):
            for a in answers:
                requests.append(rf.loglikelihood(ctx, " " + a)) 
104
        return requests
Leo Gao's avatar
Leo Gao committed
105
106
107
108
109
110
111
112
113
114
115
    
    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.
        """
116
117
118

        turn_id = len(doc["questions"])
        gold_list = self.get_answers(doc, turn_id)
thefazzer's avatar
thefazzer committed
119
        pred = np.argmax(results)
120
121
122

        (em, f1) = self.compute_scores(gold_list, pred)

thefazzer's avatar
thefazzer committed
123
        return {
124
125
            "f1": f1,
            "em": em,
thefazzer's avatar
thefazzer committed
126
        }
127
128

    def higher_is_better(self):
129
        return {
130
131
            "f1": True,
            "em": True,
132
        }
Leo Gao's avatar
Leo Gao committed
133

134
    def aggregation(self):
135
        return {
136
137
            "f1": mean,
            "em": mean,
138
        }