"lm_eval/tasks/cmmlu/cmmlu_default_arts.yaml" did not exist on "ed53d51c5c9c5f88abe4d55e379b76f501118b43"
anthropic_llms.py 4.45 KB
Newer Older
Jason Phang's avatar
Jason Phang committed
1
import os
haileyschoelkopf's avatar
haileyschoelkopf committed
2
3
from lm_eval.api.model import LM
from lm_eval.api.registry import register_model
Jason Phang's avatar
Jason Phang committed
4
5
from tqdm import tqdm
import time
baberabb's avatar
baberabb committed
6
7
8
import anthropic
from lm_eval.logger import eval_logger
from typing import List, Literal
Jason Phang's avatar
Jason Phang committed
9
10


lintangsutawika's avatar
lintangsutawika committed
11
def anthropic_completion(
baberabb's avatar
baberabb committed
12
13
14
15
16
17
    client: anthropic.Anthropic,
    model: str,
    prompt: str,
    max_tokens_to_sample: int,
    temperature: float,
    stop: List[str],
lintangsutawika's avatar
lintangsutawika committed
18
):
Jason Phang's avatar
Jason Phang committed
19
20
21
22
23
24
25
    """Query Anthropic API for completion.

    Retry with back-off until they respond
    """
    backoff_time = 3
    while True:
        try:
baberabb's avatar
baberabb committed
26
            response = client.completions.create(
Jason Phang's avatar
Jason Phang committed
27
28
29
30
31
32
33
34
                prompt=f"{anthropic.HUMAN_PROMPT} {prompt}{anthropic.AI_PROMPT}",
                model=model,
                # NOTE: Claude really likes to do CoT, and overly aggressive stop sequences
                #       (e.g. gsm8k's ":") may truncate a lot of the input.
                stop_sequences=[anthropic.HUMAN_PROMPT] + stop,
                max_tokens_to_sample=max_tokens_to_sample,
                temperature=temperature,
            )
baberabb's avatar
baberabb committed
35
36
37
38
39
            return response.completion
        except anthropic.RateLimitError as e:
            eval_logger.warning(
                f"RateLimitError occurred: {e.__cause__}\n Retrying in {backoff_time} seconds"
            )
Jason Phang's avatar
Jason Phang committed
40
41
            time.sleep(backoff_time)
            backoff_time *= 1.5
baberabb's avatar
baberabb committed
42
43
44
45
46
47
        except anthropic.APIConnectionError as e:
            eval_logger.critical(f"Server unreachable: {e.__cause__}")
            break
        except anthropic.APIStatusError as e:
            eval_logger.critical(f"API error {e.status_code}: {e.message}")
            break
Jason Phang's avatar
Jason Phang committed
48
49


haileyschoelkopf's avatar
haileyschoelkopf committed
50
@register_model("anthropic")
lintangsutawika's avatar
lintangsutawika committed
51
class AnthropicLM(LM):
baberabb's avatar
baberabb committed
52
    REQ_CHUNK_SIZE = 20  # TODO: not used
Jason Phang's avatar
Jason Phang committed
53

baberabb's avatar
baberabb committed
54
55
56
57
58
59
60
61
    def __init__(
        self,
        batch_size=None,
        model: str = "claude-2.0",
        max_tokens_to_sample: int = 256,
        temperature: float = 0.0,
    ):  # TODO: remove batch_size
        """Anthropic API wrapper.
Jason Phang's avatar
Jason Phang committed
62
63

        :param model: str
baberabb's avatar
baberabb committed
64
            Anthropic model e.g. 'claude-instant-v1', 'claude-2'
Jason Phang's avatar
Jason Phang committed
65
66
        """
        super().__init__()
lintangsutawika's avatar
lintangsutawika committed
67

Jason Phang's avatar
Jason Phang committed
68
        self.model = model
baberabb's avatar
baberabb committed
69
70
71
72
        self.client = anthropic.Anthropic()
        self.temperature = temperature
        self.max_tokens_to_sample = max_tokens_to_sample
        self.tokenizer = self.client.get_tokenizer()
Jason Phang's avatar
Jason Phang committed
73
74
75

    @property
    def eot_token_id(self):
baberabb's avatar
baberabb committed
76
        # Not sure but anthropic.AI_PROMPT -> [203, 203, 50803, 30]
Jason Phang's avatar
Jason Phang committed
77
78
79
80
81
82
83
84
        raise NotImplementedError("No idea about anthropic tokenization.")

    @property
    def max_length(self):
        return 2048

    @property
    def max_gen_toks(self):
baberabb's avatar
baberabb committed
85
        return self.max_tokens_to_sample
Jason Phang's avatar
Jason Phang committed
86
87
88
89

    @property
    def batch_size(self):
        # Isn't used because we override _loglikelihood_tokens
baberabb's avatar
baberabb committed
90
        raise NotImplementedError("No support for logits.")
Jason Phang's avatar
Jason Phang committed
91
92
93
94

    @property
    def device(self):
        # Isn't used because we override _loglikelihood_tokens
baberabb's avatar
baberabb committed
95
        raise NotImplementedError("No support for logits.")
Jason Phang's avatar
Jason Phang committed
96

baberabb's avatar
baberabb committed
97
98
    def tok_encode(self, string: str) -> List[int]:
        return self.tokenizer.encode(string).ids
Jason Phang's avatar
Jason Phang committed
99

baberabb's avatar
baberabb committed
100
101
    def tok_decode(self, tokens: List[int]) -> str:
        return self.tokenizer.decode(tokens)
Jason Phang's avatar
Jason Phang committed
102
103
104
105
106
107
108
109

    def _loglikelihood_tokens(self, requests, disable_tqdm=False):
        raise NotImplementedError("No support for logits.")

    def greedy_until(self, requests):
        if not requests:
            return []

haileyschoelkopf's avatar
haileyschoelkopf committed
110
111
        requests = [req.args for req in requests]

Jason Phang's avatar
Jason Phang committed
112
113
114
115
116
117
118
119
120
        res = []
        for request in tqdm(requests):
            inp = request[0]
            request_args = request[1]
            until = request_args["until"]
            response = anthropic_completion(
                client=self.client,
                model=self.model,
                prompt=inp,
baberabb's avatar
baberabb committed
121
122
                max_tokens_to_sample=self.max_tokens_to_sample,
                temperature=self.temperature,  # TODO: implement non-greedy sampling for Anthropic
Jason Phang's avatar
Jason Phang committed
123
124
125
                stop=until,
            )
            res.append(response)
haileyschoelkopf's avatar
haileyschoelkopf committed
126
127
128

            self.cache_hook.add_partial("greedy_until", request, response)

Jason Phang's avatar
Jason Phang committed
129
130
131
132
133
134
135
136
137
        return res

    def _model_call(self, inps):
        # Isn't used because we override _loglikelihood_tokens
        raise NotImplementedError()

    def _model_generate(self, context, max_length, eos_token_id):
        # Isn't used because we override greedy_until
        raise NotImplementedError()
baberabb's avatar
baberabb committed
138
139
140
141
142
143

    def loglikelihood(self, requests):
        raise NotImplementedError("No support for logits.")

    def loglikelihood_rolling(self, requests):
        raise NotImplementedError("No support for logits.")