base.py 4.69 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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
        :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
    def gen_greedy(self, requests):
        """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
107
108

    @abc.abstractmethod
    def doc_to_text(self, doc, include_target=True):
        pass
Leo Gao's avatar
Leo Gao committed
109
110
111
112

    @abc.abstractmethod
    def construct_requests(self, doc, nshot=0, prompt=False):
        pass
Leo Gao's avatar
Leo Gao committed
113
114
    
    @abc.abstractmethod
Leo Gao's avatar
Leo Gao committed
115
116
    def process_results(self, doc, results):
        """Take a single document and the LM results and evaluates, returning a dict with the following format:
Jason Phang's avatar
checkin  
Jason Phang committed
117
118

        {
Leo Gao's avatar
Leo Gao committed
119
120
            "submetric": str,
            "value": float,
Jason Phang's avatar
checkin  
Jason Phang committed
121
            "higher_is_better": bool,
Leo Gao's avatar
Leo Gao committed
122
            "aggregation": (list -> float),
Jason Phang's avatar
checkin  
Jason Phang committed
123
124
        }

Leo Gao's avatar
Leo Gao committed
125
126
        * `submetric` should be the name of the metric
        * `value` should be the value of the metric
Jason Phang's avatar
checkin  
Jason Phang committed
127
        * `higher_is_better` determines whether a higher metric is better
Leo Gao's avatar
Leo Gao committed
128
129
130
131
        * `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
132
        """
Leo Gao's avatar
Leo Gao committed
133
        pass
Jason Phang's avatar
gpt3  
Jason Phang committed
134

Jason Phang's avatar
Jason Phang committed
135
    def fewshot_description(self):
Jason Phang's avatar
checkin  
Jason Phang committed
136
137
        return ""

Jason Phang's avatar
Jason Phang committed
138
    def fewshot_context(self, doc, num_fewshot, provide_description):
Jason Phang's avatar
Jason Phang committed
139
        raw_description = self.fewshot_description()
Jason Phang's avatar
Jason Phang committed
140
        description = (raw_description + "\n===\n\n") if provide_description and raw_description else ""
Jason Phang's avatar
Jason Phang committed
141
142
143
144
        labeled_examples = "\n\n".join(
            map(self.doc_to_text, self.fewshot_examples(k=num_fewshot))
        ) + "\n\n"
        example = self.doc_to_text(doc, include_target=False).strip()
Leo Gao's avatar
Leo Gao committed
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
        return description + labeled_examples + example



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

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


Request = collections.namedtuple('Request', ('type', 'args', 'kwargs'))

class RequestFactory:
    def __getattr__(self, attr):
        def fn(*args, **kwargs):
            return Request(attr, args, kwargs)
        return fn


rf = RequestFactory()