coqa.py 4.33 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
10

class CoQA(Dataset):
sdtblck's avatar
sdtblck committed
11
    def download(self):
12
13
        pass
        # -N only overwrites if the remote file has changed
thefazzer's avatar
thefazzer committed
14
        sh ("""
sdtblck's avatar
sdtblck committed
15
            mkdir -p data/coqa 
16
17
            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
18
19
            """)

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

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

    def has_test_docs(self):
        return False

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

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

    def test_docs(self):
Leo Gao's avatar
Leo Gao committed
36
        pass
37
38
    
    def fewshot_description(self):
thefazzer's avatar
thefazzer committed
39
        return "Given a passage and a conversation so far, answer the next question in the conversation."
40
    
Leo Gao's avatar
Leo Gao committed
41
    def doc_to_text(self, doc):
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
        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
        return doc_text

    @classmethod
    def get_answers(cls, doc, turn_id):
        # get answers and valid alternatives
        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
63
    
64
65
66
67
68
69
    def doc_to_target(self, doc, turnid=None):
        # default to predict last turn
        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
70
71
72
73
74
75
76
77
78
79
80
81

    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`. 
        """
82
83
84
85
        requests = []
        for answer in self.get_answers(doc, len(doc["questions"])):
            requests.append(rf.loglikelihood(ctx, " " + answer)) 
        return requests
Leo Gao's avatar
Leo Gao committed
86
87
88
89
90
91
92
93
94
95
96
    
    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.
        """
97
        gold = self.get_answers(doc, len(doc["questions"]))
thefazzer's avatar
thefazzer committed
98
99
        pred = np.argmax(results)
        return {
100
            "acc": int(pred == gold)
thefazzer's avatar
thefazzer committed
101
        }
102
       
Leo Gao's avatar
Leo Gao committed
103
104
105
106
107
108
    def aggregation(self):
        """
        :returns: {str: [float] -> float}
            A dictionary where keys are the names of submetrics and values are 
            functions that aggregate a list of metrics
        """
109
110
111
        return {
            "acc": mean
        }
Leo Gao's avatar
Leo Gao committed
112
113
114
115
116
117
118

    def higher_is_better(self):
        """
        :returns: {str: bool}
            A dictionary where keys are the names of submetrics and values are 
            whether a higher value of the submetric is better
        """
119
120
121
        return {
            "acc": True
        }