gpt3.py 7.8 KB
Newer Older
Jason Phang's avatar
gpt3  
Jason Phang committed
1
import os
Jason Phang's avatar
Jason Phang committed
2
import numpy as np
Jason Phang's avatar
gpt3  
Jason Phang committed
3
import transformers
Jason Phang's avatar
lib  
Jason Phang committed
4
5
from lm_eval.base import LM
from lm_eval import utils
Leo Gao's avatar
Leo Gao committed
6
from tqdm import tqdm
Leo Gao's avatar
Leo Gao committed
7
import time
Leo Gao's avatar
Leo Gao committed
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23


def get_result(response, ctxlen):
    is_greedy = True
    logprobs = response["logprobs"]["token_logprobs"]
    continuation_logprobs = sum(logprobs[ctxlen:])

    for i in range(ctxlen, len(response["logprobs"]["tokens"])):
        token = response["logprobs"]["tokens"][i]
        top_tokens = response["logprobs"]["top_logprobs"][i]
        top_token = max(top_tokens.keys(), key=lambda x: top_tokens[x])
        if top_token != token:
            is_greedy = False
            break
    
    return continuation_logprobs, is_greedy
Jason Phang's avatar
gpt3  
Jason Phang committed
24
25


Leo Gao's avatar
Leo Gao committed
26
27
28
29
30
31
32
33
34
35
36
37
def oa_completion(**kwargs):
    import openai

    backoff_time = 3
    while True:
        try:
            return openai.Completion.create(**kwargs)
        except openai.error.OpenAIError:
            time.sleep(backoff_time)
            backoff_time *= 1.5


Jason Phang's avatar
gpt3  
Jason Phang committed
38
class GPT3LM(LM):
Jason Phang's avatar
Jason Phang committed
39
40

    MAX_LENGTH = 2048
Leo Gao's avatar
Leo Gao committed
41
    REQ_CHUNK_SIZE = 20
Leo Gao's avatar
Leo Gao committed
42
    MAX_GEN_TOKS = 256
Jason Phang's avatar
Jason Phang committed
43
44
45
46
47
48
49
50
51

    def __init__(self, engine, truncate=False):
        """

        :param engine: str
            OpenAI API engine (e.g. davinci)
        :param truncate: bool
            Truncate input if too long (if False and input is too long, throw error)
        """
Leo Gao's avatar
Leo Gao committed
52
        super().__init__()
Jason Phang's avatar
Jason Phang committed
53
        import openai
Jason Phang's avatar
gpt3  
Jason Phang committed
54
        self.engine = engine
55
        self.tokenizer = transformers.GPT2TokenizerFast.from_pretrained('gpt2')
Leo Gao's avatar
Leo Gao committed
56

Leo Gao's avatar
Leo Gao committed
57

Leo Gao's avatar
Leo Gao committed
58
59
        # to make the annoying "Using pad_token, but it is not set yet." error go away
        self.tokenizer.pad_token = "<|endoftext|>"
Leo Gao's avatar
Leo Gao committed
60
        assert self.tokenizer.encode('hello\n\nhello') == [31373, 198, 198, 31373]
Jason Phang's avatar
Jason Phang committed
61
        self.truncate = truncate
Jason Phang's avatar
Jason Phang committed
62
        self.end_of_text_token_id = self.tokenizer.convert_tokens_to_ids(["<|endoftext|>"])[0]
Jason Phang's avatar
Jason Phang committed
63

Jason Phang's avatar
gpt3  
Jason Phang committed
64
65
66
67
        # Read from environment variable OPENAI_API_SECRET_KEY
        openai.api_key = os.environ["OPENAI_API_SECRET_KEY"]

    @classmethod
68
    def create_from_arg_string(cls, arg_string, additional_config={}):
Jason Phang's avatar
gpt3  
Jason Phang committed
69
        args = utils.simple_parse_args_string(arg_string)
70
71
        args2 = {k: v for k, v in additional_config.items() if v is not None}
        return cls(**args, **args2)
Jason Phang's avatar
gpt3  
Jason Phang committed
72

Leo Gao's avatar
Leo Gao committed
73
    def loglikelihood(self, requests):
Leo Gao's avatar
Leo Gao committed
74
75
76
77
78
79
80
81
82
83
        new_reqs = []
        for context, continuation in requests:
            if context == "":
                # end of text as context
                context_enc = [50256]
            else:
                context_enc = self.tokenizer.encode(context)

            continuation_enc = self.tokenizer.encode(continuation)

Leo Gao's avatar
Leo Gao committed
84
            new_reqs.append(((context, continuation), context_enc, continuation_enc))
Leo Gao's avatar
Leo Gao committed
85
86
87

        return self._loglikelihood_tokens(new_reqs)

Leo Gao's avatar
Leo Gao committed
88
    def loglikelihood_rolling(self, requests):
Leo Gao's avatar
Leo Gao committed
89
        # TODO: switch implementation to use _loglikelihood_tokens rather than having it do its own thing
Jason Phang's avatar
Jason Phang committed
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106

        loglikelihoods = []
        for string, in tqdm(requests):
            encoded = self.tokenizer.encode_plus(string)["input_ids"]
            rolling_token_windows = utils.get_rolling_token_windows(
                token_list=encoded,
                prefix_token=self.end_of_text_token_id,
                max_seq_len=self.MAX_LENGTH,
                context_len=1,
            )
            string_loglikelihoods = []
            for input_tokens, pred_tokens in rolling_token_windows:
                block_output = self.get_token_logprobs(
                    input_tokens=input_tokens,
                    pred_tokens=pred_tokens,
                )
                string_loglikelihoods.append(block_output["logprobs"])
Leo Gao's avatar
Leo Gao committed
107
            string_loglikelihoods = np.concatenate(string_loglikelihoods).sum()
Jason Phang's avatar
Jason Phang committed
108
109
110
111
            loglikelihoods.append(string_loglikelihoods)

        return loglikelihoods

Leo Gao's avatar
Leo Gao committed
112
    def _loglikelihood_tokens(self, requests):
Leo Gao's avatar
Leo Gao committed
113
        import openai
Leo Gao's avatar
Leo Gao committed
114
115
        res = []

116
        def _collate(x):
Leo Gao's avatar
Leo Gao committed
117
118
119
            # this doesn't efficiently handle last-token differences yet, but those are kinda annoying because
            # it's not guaranteed that the 100 or so logprobs we get to see actually contain all the continuations
            # we care about and so we need some kind of backup for when it isn't
Leo Gao's avatar
Leo Gao committed
120
            toks = x[1] + x[2]
121
            return (-len(toks), tuple(toks))
122
123
        
        reord = utils.Reorderer(requests, _collate)
Jason Phang's avatar
Jason Phang committed
124

125
        for chunk in tqdm(list(utils.chunks(reord.get_reordered(), self.REQ_CHUNK_SIZE))):
Leo Gao's avatar
Leo Gao committed
126
127
            inps = []
            ctxlens = []
Leo Gao's avatar
Leo Gao committed
128
            for cache_key, context_enc, continuation_enc in chunk:
Leo Gao's avatar
Leo Gao committed
129
130
131
132
133
134
                inp = (context_enc + continuation_enc)[-self.MAX_LENGTH:]
                ctxlen = len(context_enc) - max(0, len(context_enc) + len(continuation_enc) - self.MAX_LENGTH)

                inps.append(inp)
                ctxlens.append(ctxlen)

Leo Gao's avatar
Leo Gao committed
135
            response = oa_completion(
Leo Gao's avatar
Leo Gao committed
136
137
138
139
140
141
142
                engine=self.engine,
                prompt=inps,
                echo=True,
                max_tokens=0, temperature=0.,
                logprobs=10,
            )

Leo Gao's avatar
Leo Gao committed
143
            for resp, ctxlen, (cache_key, context_enc, continuation_enc) in zip(response.choices, ctxlens, chunk):
Leo Gao's avatar
Leo Gao committed
144
145
146
147
148
                answer = get_result(resp, ctxlen)

                res.append(answer)

                # partial caching
Leo Gao's avatar
Leo Gao committed
149
150
                if cache_key is not None:
                    self.cache_hook.add_partial("loglikelihood", cache_key, answer)
Jason Phang's avatar
Jason Phang committed
151

152
        return reord.get_original(res)
Leo Gao's avatar
Leo Gao committed
153

Jason Phang's avatar
Jason Phang committed
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
    def get_token_logprobs(self, input_tokens, pred_tokens):
        pred_start = len(input_tokens) - len(pred_tokens) + 1
        # We're going to stitch together the input_tokens and pred_tokens
        # In the longest case, this gets us to length = max_seq_len+1 (which the API works with)
        assert input_tokens[pred_start:] == pred_tokens[:-1]
        token_ids = input_tokens + [pred_tokens[-1]]
        response = oa_completion(
            engine=self.engine,
            prompt=token_ids,
            max_tokens=0,
            temperature=0.0,
            logprobs=0,
            echo=True,
        )
        logprobs = np.array(response["choices"][0]["logprobs"]["token_logprobs"][pred_start:])
        positions = np.arange(pred_start-1, pred_start-1 + len(token_ids[pred_start:]))
        return {
            "logprobs": logprobs,
            "positions": positions,
        }

Leo Gao's avatar
Leo Gao committed
175
    def greedy_until(self, requests):
Leo Gao's avatar
Leo Gao committed
176
        if not requests: return []
Leo Gao's avatar
Leo Gao committed
177
178
179
        import openai
        res = []

180
181
182
183
184
185
        def _collate(x):
            toks = self.tokenizer.encode(x[0])
            return (len(toks), x[0])
        
        reord = utils.Reorderer(requests, _collate)

Leo Gao's avatar
Leo Gao committed
186
187
188
189
190
191
192
193
194
195
196
197
198
        def sameuntil_chunks(xs, size):
            ret = []
            lastuntil = xs[0][1]
            for x in xs:
                if len(ret) >= size or x[1] != lastuntil:
                    yield ret, lastuntil
                    ret = []
                    lastuntil = x[1]
                ret.append(x)
            
            if ret: yield ret, lastuntil

        # todo: more intelligent batching for heterogenous `until`
199
        for chunk, until in tqdm(list(sameuntil_chunks(reord.get_reordered(), self.REQ_CHUNK_SIZE))):
Leo Gao's avatar
Leo Gao committed
200
201
202
203
204
            inps = []
            for context, _ in chunk:
                context_enc = self.tokenizer.encode(context)
                inp = context_enc[-(self.MAX_LENGTH - self.MAX_GEN_TOKS):]
                inps.append(inp)
Leo Gao's avatar
Leo Gao committed
205

Leo Gao's avatar
Leo Gao committed
206
            response = oa_completion(
Leo Gao's avatar
Leo Gao committed
207
                engine=self.engine,
Leo Gao's avatar
Leo Gao committed
208
                prompt=inps,
Leo Gao's avatar
Leo Gao committed
209
210
211
                max_tokens=self.MAX_GEN_TOKS, 
                temperature=0.,
                logprobs=10,
Leo Gao's avatar
Leo Gao committed
212
                stop=until
Leo Gao's avatar
Leo Gao committed
213
            )
Leo Gao's avatar
Leo Gao committed
214

Leo Gao's avatar
Leo Gao committed
215
            for resp, (context, until) in zip(response.choices, chunk):
Leo Gao's avatar
Leo Gao committed
216
                s = resp['text']
Leo Gao's avatar
Leo Gao committed
217
218
219

                for term in until:
                    s = s.split(term)[0]
Leo Gao's avatar
Leo Gao committed
220

Leo Gao's avatar
Leo Gao committed
221
222
223
                # partial caching
                self.cache_hook.add_partial("greedy_until", (context, until), s)
                
Leo Gao's avatar
Leo Gao committed
224
                res.append(s)
Leo Gao's avatar
Leo Gao committed
225
        
Leo Gao's avatar
Leo Gao committed
226
        return reord.get_original(res)()