anthropic_llms.py 6.42 KB
Newer Older
haileyschoelkopf's avatar
haileyschoelkopf committed
1
2
from lm_eval.api.model import LM
from lm_eval.api.registry import register_model
Jason Phang's avatar
Jason Phang committed
3
4
from tqdm import tqdm
import time
baberabb's avatar
baberabb committed
5
from lm_eval.logger import eval_logger
baberabb's avatar
baberabb committed
6
from typing import List, Any, Tuple
Jason Phang's avatar
Jason Phang committed
7
8


lintangsutawika's avatar
lintangsutawika committed
9
def anthropic_completion(
10
    client,  #: anthropic.Anthropic,
baberabb's avatar
baberabb committed
11
12
13
14
15
    model: str,
    prompt: str,
    max_tokens_to_sample: int,
    temperature: float,
    stop: List[str],
baberabb's avatar
baberabb committed
16
    **kwargs: Any,
baberabb's avatar
baberabb committed
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
) -> str:
    """Wrapper function around the Anthropic completion API client with exponential back-off
    in case of RateLimitError.

    params:
        client: anthropic.Anthropic
            Anthropic API client
        model: str
            Anthropic model e.g. 'claude-instant-v1', 'claude-2'
        prompt: str
            Prompt to feed to the model
        max_tokens_to_sample: int
            Maximum number of tokens to sample from the model
        temperature: float
            Sampling temperature
        stop: List[str]
            List of stop sequences
        kwargs: Any
            Additional model_args to pass to the API client
Jason Phang's avatar
Jason Phang committed
36
    """
37
38
39
40
41
42
43
44
45

    try:
        import anthropic
    except ModuleNotFoundError:
        raise Exception(
            "attempted to use 'anthropic' LM type, but package `anthropic` is not installed. \
please install anthropic via `pip install lm-eval[anthropic]` or `pip install -e .[anthropic]`",
        )

baberabb's avatar
baberabb committed
46
    backoff_time: float = 3
Jason Phang's avatar
Jason Phang committed
47
48
    while True:
        try:
baberabb's avatar
baberabb committed
49
            response = client.completions.create(
Jason Phang's avatar
Jason Phang committed
50
51
52
53
54
55
56
                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
57
                **kwargs,
Jason Phang's avatar
Jason Phang committed
58
            )
baberabb's avatar
baberabb committed
59
60
61
62
63
            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
64
65
66
67
            time.sleep(backoff_time)
            backoff_time *= 1.5


haileyschoelkopf's avatar
haileyschoelkopf committed
68
@register_model("anthropic")
lintangsutawika's avatar
lintangsutawika committed
69
class AnthropicLM(LM):
baberabb's avatar
baberabb committed
70
    REQ_CHUNK_SIZE = 20  # TODO: not used
Jason Phang's avatar
Jason Phang committed
71

baberabb's avatar
baberabb committed
72
73
    def __init__(
        self,
74
        batch_size: int = 1,
baberabb's avatar
baberabb committed
75
76
        model: str = "claude-2.0",
        max_tokens_to_sample: int = 256,
77
78
        temperature: float = 0,  # defaults to 1
        **kwargs,  # top_p, top_k, etc.
Ethan Smith's avatar
Ethan Smith committed
79
    ) -> None:
baberabb's avatar
baberabb committed
80
        """Anthropic API wrapper.
Jason Phang's avatar
Jason Phang committed
81
82

        :param model: str
baberabb's avatar
baberabb committed
83
            Anthropic model e.g. 'claude-instant-v1', 'claude-2'
baberabb's avatar
baberabb committed
84
85
86
87
88
89
        :param max_tokens_to_sample: int
            Maximum number of tokens to sample from the model
        :param temperature: float
            Sampling temperature
        :param kwargs: Any
            Additional model_args to pass to the API client
Jason Phang's avatar
Jason Phang committed
90
91
        """
        super().__init__()
lintangsutawika's avatar
lintangsutawika committed
92

93
94
95
96
97
98
99
100
        try:
            import anthropic
        except ModuleNotFoundError:
            raise Exception(
                "attempted to use 'anthropic' LM type, but package `anthropic` is not installed. \
please install anthropic via `pip install lm-eval[anthropic]` or `pip install -e .[anthropic]`",
            )

Jason Phang's avatar
Jason Phang committed
101
        self.model = model
baberabb's avatar
baberabb committed
102
        # defaults to os.environ.get("ANTHROPIC_API_KEY")
baberabb's avatar
baberabb committed
103
        self.client = anthropic.Anthropic()
baberabb's avatar
baberabb committed
104
105
106
        self.temperature = temperature
        self.max_tokens_to_sample = max_tokens_to_sample
        self.tokenizer = self.client.get_tokenizer()
baberabb's avatar
baberabb committed
107
        self.kwargs = kwargs
Jason Phang's avatar
Jason Phang committed
108
109
110

    @property
    def eot_token_id(self):
baberabb's avatar
baberabb committed
111
        # Not sure but anthropic.HUMAN_PROMPT ?
Jason Phang's avatar
Jason Phang committed
112
113
114
        raise NotImplementedError("No idea about anthropic tokenization.")

    @property
baberabb's avatar
baberabb committed
115
    def max_length(self) -> int:
Jason Phang's avatar
Jason Phang committed
116
117
118
        return 2048

    @property
baberabb's avatar
baberabb committed
119
    def max_gen_toks(self) -> int:
baberabb's avatar
baberabb committed
120
        return self.max_tokens_to_sample
Jason Phang's avatar
Jason Phang committed
121
122
123
124

    @property
    def batch_size(self):
        # Isn't used because we override _loglikelihood_tokens
baberabb's avatar
baberabb committed
125
        raise NotImplementedError("No support for logits.")
Jason Phang's avatar
Jason Phang committed
126
127
128
129

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

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

baberabb's avatar
baberabb committed
135
136
    def tok_decode(self, tokens: List[int]) -> str:
        return self.tokenizer.decode(tokens)
Jason Phang's avatar
Jason Phang committed
137

Ethan Smith's avatar
Ethan Smith committed
138
    def _loglikelihood_tokens(self, requests, disable_tqdm: bool = False):
Jason Phang's avatar
Jason Phang committed
139
140
        raise NotImplementedError("No support for logits.")

baberabb's avatar
baberabb committed
141
    def greedy_until(self, requests) -> List[str]:
Jason Phang's avatar
Jason Phang committed
142
143
144
        if not requests:
            return []

baberabb's avatar
baberabb committed
145
        _requests: List[Tuple[str, dict]] = [req.args for req in requests]
haileyschoelkopf's avatar
haileyschoelkopf committed
146

Jason Phang's avatar
Jason Phang committed
147
        res = []
baberabb's avatar
baberabb committed
148
        for request in tqdm(_requests):
baberabb's avatar
baberabb committed
149
150
151
            try:
                inp = request[0]
                request_args = request[1]
152
153
154
155
                # generation_kwargs
                until = request_args.get("until")
                max_gen_toks = request_args.get("max_gen_toks", self.max_length)
                temperature = request_args.get("temperature", self.temperature)
baberabb's avatar
baberabb committed
156
157
158
159
                response = anthropic_completion(
                    client=self.client,
                    model=self.model,
                    prompt=inp,
160
161
                    max_tokens_to_sample=max_gen_toks,
                    temperature=temperature,  # TODO: implement non-greedy sampling for Anthropic
baberabb's avatar
baberabb committed
162
                    stop=until,  # type: ignore
baberabb's avatar
baberabb committed
163
164
165
166
167
                    **self.kwargs,
                )
                res.append(response)

                self.cache_hook.add_partial("greedy_until", request, response)
baberabb's avatar
baberabb committed
168
            except anthropic.APIConnectionError as e:  # type: ignore # noqa: F821
baberabb's avatar
baberabb committed
169
170
                eval_logger.critical(f"Server unreachable: {e.__cause__}")
                break
baberabb's avatar
baberabb committed
171
            except anthropic.APIStatusError as e:  # type: ignore # noqa: F821
baberabb's avatar
baberabb committed
172
173
                eval_logger.critical(f"API error {e.status_code}: {e.message}")
                break
haileyschoelkopf's avatar
haileyschoelkopf committed
174

Jason Phang's avatar
Jason Phang committed
175
176
177
178
179
180
181
182
183
        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
184
185
186
187
188
189

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

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