base.py 4.77 KB
Newer Older
Leo Gao's avatar
Leo Gao committed
1
2
import abc
import random
Leo Gao's avatar
Leo Gao committed
3
import collections
Leo Gao's avatar
Leo Gao committed
4

Jason Phang's avatar
gpt3  
Jason Phang committed
5

Leo Gao's avatar
Leo Gao committed
6
7
class LM(abc.ABC):
    @abc.abstractmethod
Leo Gao's avatar
Leo Gao committed
8
    def loglikelihood(self, requests):
Leo Gao's avatar
Leo Gao committed
9
        """Compute log-likelihood of generating a continuation from a context
Jason Phang's avatar
gpt3  
Jason Phang committed
10

Leo Gao's avatar
Leo Gao committed
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
        :param requests: list
            A list of pairs (context, continuation)
            context: str
                Context string
            continuation: str
                The continuation over which log likelihood will be calculated. If 
                there is a word boundary, the space should be in the continuation. 
                For example, context="hello" continuation=" world" is correct.
        :return: list
            A list of pairs (logprob, isgreedy)
            logprob: float
                The log probability of `contination`
            isgreedy:
                Whether `contination` would be generated by greedy sampling from `context`
        """
        pass

    @abc.abstractmethod
Leo Gao's avatar
Update  
Leo Gao committed
29
    def greedy_until(self, requests):
Leo Gao's avatar
Leo Gao committed
30
31
32
33
34
35
36
37
38
39
40
41
42
        """Generate greedily until a stopping sequence

        :param requests: list
            A list of pairs (context, until)
            context: str
                Context string
            until: str
                The string sequence to generate until. This string sequence may 
                span across msultiple tokens, or may be part of one token.
        :return: list
            A list of strings continuation
            continuation: str
                The generated continuation.
Jason Phang's avatar
gpt3  
Jason Phang committed
43
        """
Leo Gao's avatar
Leo Gao committed
44
45
        pass

Jason Phang's avatar
gpt3  
Jason Phang committed
46
47
48
49
50
51
52
53
54
55
56
    @classmethod
    def create_from_arg_string(cls, arg_string):
        """Constructor method, in case models need additional arguments
        e.g. OpenAI API engine, paths for loading, other params

        :param arg_string: str
            Left up to individual model class to handle

        """
        return cls()

Leo Gao's avatar
Leo Gao committed
57
58

class Dataset(abc.ABC):
Leo Gao's avatar
Leo Gao committed
59
60
61
    @abc.abstractmethod
    def __init__(self):
        self.download()
Leo Gao's avatar
Leo Gao committed
62
        self._traindocs = None
sdtblck's avatar
sdtblck committed
63
64
65
66
67

    def download(self):
        """Downloads the task dataset if necessary"""
        pass

68
69
    @abc.abstractmethod
    def has_training_docs(self):
Jason Phang's avatar
checkin  
Jason Phang committed
70
        """Whether the task has a training set"""
71
72
73
74
        pass
    
    @abc.abstractmethod
    def has_validation_docs(self):
Jason Phang's avatar
checkin  
Jason Phang committed
75
76
77
78
79
80
        """Whether the task has a validation set"""
        pass

    @abc.abstractmethod
    def has_test_docs(self):
        """Whether the task has a test set"""
81
82
        pass

Leo Gao's avatar
Leo Gao committed
83
84
    @abc.abstractmethod
    def training_docs(self):
Jason Phang's avatar
checkin  
Jason Phang committed
85
86
87
88
89
        """

        :return: Iterable[obj]
            A iterable of any object, that doc_to_text can handle
        """
Leo Gao's avatar
Leo Gao committed
90
91
92
93
94
95
96
97
98
99
100
        pass
    
    @abc.abstractmethod
    def validation_docs(self):
        pass
    
    @abc.abstractmethod
    def test_docs(self):
        pass
    
    def fewshot_examples(self, k):
Leo Gao's avatar
Leo Gao committed
101
102
103
104
        if self._traindocs is None:
            self._traindocs = list(self.training_docs())

        return random.sample(self._traindocs, k)
Leo Gao's avatar
Leo Gao committed
105
106

    @abc.abstractmethod
Leo Gao's avatar
Update  
Leo Gao committed
107
108
109
110
111
    def doc_to_text(self, doc):
        pass

    @abc.abstractmethod
    def doc_to_target(self, doc):
Leo Gao's avatar
Leo Gao committed
112
        pass
Leo Gao's avatar
Leo Gao committed
113
114
115
116

    @abc.abstractmethod
    def construct_requests(self, doc, nshot=0, prompt=False):
        pass
Leo Gao's avatar
Leo Gao committed
117
118
    
    @abc.abstractmethod
Leo Gao's avatar
Leo Gao committed
119
    def process_results(self, doc, results):
Leo Gao's avatar
Update  
Leo Gao committed
120
121
        """Take a single document and the LM results and evaluates, returning a 
        list of dicts, each with the following format:
Jason Phang's avatar
checkin  
Jason Phang committed
122
123

        {
Leo Gao's avatar
Leo Gao committed
124
125
            "submetric": str,
            "value": float,
Jason Phang's avatar
checkin  
Jason Phang committed
126
            "higher_is_better": bool,
Leo Gao's avatar
Update  
Leo Gao committed
127
            "aggregation": ([float] -> float),
Jason Phang's avatar
checkin  
Jason Phang committed
128
129
        }

Leo Gao's avatar
Leo Gao committed
130
131
        * `submetric` should be the name of the metric
        * `value` should be the value of the metric
Jason Phang's avatar
checkin  
Jason Phang committed
132
        * `higher_is_better` determines whether a higher metric is better
Leo Gao's avatar
Leo Gao committed
133
134
135
136
        * `aggregation` should be a function that takes a list of floats and 
            aggregates them into one float. This should be the same for all 
            submetrics of the same name; if it differs, an error should be 
            raised.
Jason Phang's avatar
checkin  
Jason Phang committed
137
        """
Leo Gao's avatar
Leo Gao committed
138
        pass
Jason Phang's avatar
gpt3  
Jason Phang committed
139

Jason Phang's avatar
Jason Phang committed
140
    def fewshot_description(self):
Jason Phang's avatar
checkin  
Jason Phang committed
141
142
        return ""

Jason Phang's avatar
Jason Phang committed
143
    def fewshot_context(self, doc, num_fewshot, provide_description):
Jason Phang's avatar
Jason Phang committed
144
        raw_description = self.fewshot_description()
Jason Phang's avatar
Jason Phang committed
145
        description = (raw_description + "\n===\n\n") if provide_description and raw_description else ""
Leo Gao's avatar
Update  
Leo Gao committed
146
        
Jason Phang's avatar
Jason Phang committed
147
        labeled_examples = "\n\n".join(
Leo Gao's avatar
Update  
Leo Gao committed
148
            [self.doc_to_text(doc) + self.doc_to_target(doc) for doc in self.fewshot_examples(k=num_fewshot)]
Jason Phang's avatar
Jason Phang committed
149
        ) + "\n\n"
Leo Gao's avatar
Update  
Leo Gao committed
150
151

        example = self.doc_to_text(doc).strip()
Leo Gao's avatar
Leo Gao committed
152
153
154
155
156
157
158
159
160
161
162
        return description + labeled_examples + example



def mean(arr):
    return sum(arr) / len(arr)

def median(arr):
    return arr[len(arr) // 2]


Leo Gao's avatar
Update  
Leo Gao committed
163
Request = collections.namedtuple('Request', ('type', 'args'))
Leo Gao's avatar
Leo Gao committed
164
165
166

class RequestFactory:
    def __getattr__(self, attr):
Leo Gao's avatar
Update  
Leo Gao committed
167
168
        def fn(*args):
            return Request(attr, args)
Leo Gao's avatar
Leo Gao committed
169
170
171
172
        return fn


rf = RequestFactory()