"vscode:/vscode.git/clone" did not exist on "d913d52c9a25f64238ab3fb23b02e0ced2d9c625"
api_models.py 32.9 KB
Newer Older
Baber Abbasi's avatar
Baber Abbasi committed
1
2
3
4
5
import abc
import asyncio
import copy
import itertools
import json
Lintang Sutawika's avatar
Lintang Sutawika committed
6
import logging
Baber Abbasi's avatar
Baber Abbasi committed
7
8
from functools import cached_property
from typing import (
9
    TYPE_CHECKING,
Baber Abbasi's avatar
Baber Abbasi committed
10
11
12
13
14
15
16
    Any,
    Awaitable,
    Callable,
    Dict,
    Iterable,
    List,
    Literal,
Baber Abbasi's avatar
Baber Abbasi committed
17
    NamedTuple,
Baber Abbasi's avatar
Baber Abbasi committed
18
19
20
21
22
23
24
25
    Optional,
    Tuple,
    Union,
)


try:
    import requests
26
    from aiohttp import ClientSession, ClientTimeout, TCPConnector
Baber Abbasi's avatar
Baber Abbasi committed
27
28
29
30
31
32
33
    from tenacity import RetryError, retry, stop_after_attempt, wait_exponential
    from tqdm import tqdm
    from tqdm.asyncio import tqdm_asyncio
except ModuleNotFoundError:
    pass


34
import base64
Baber Abbasi's avatar
Baber Abbasi committed
35
from importlib.util import find_spec
36
from io import BytesIO
Baber Abbasi's avatar
Baber Abbasi committed
37
38
39
40
41
42
43

from lm_eval import utils
from lm_eval.api.instance import Instance
from lm_eval.api.model import TemplateLM
from lm_eval.models.utils import Collator, chunks, configure_pad_token


44
45
46
47
if TYPE_CHECKING:
    from PIL import Image


Lintang Sutawika's avatar
Lintang Sutawika committed
48
49
eval_logger = logging.getLogger(__name__)

Baber Abbasi's avatar
Baber Abbasi committed
50
LogLikelihoodInputs = Tuple[Tuple[str, str], List[int], List[int]]
Baber Abbasi's avatar
Baber Abbasi committed
51
52
53
54
55
56
57
58
59


# utility class to keep track of json encoded chats
class JsonChatStr(NamedTuple):
    prompt: str

    def encode(self, encoding):
        return self.prompt.encode(encoding)

Baber Abbasi's avatar
Baber Abbasi committed
60

61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
def create_image_prompt(
    imgs: list["Image.Image"], chat: dict, fmt: str = "PNG"
) -> dict:
    """

    Parameters
    ----------
    img : list[PIL.Image.Image]
        The list of images to encode to base64
    chat : dict
    fmt : str, optional
        Any format Pillow understands (e.g. "PNG", "JPEG").
        Defaults to "PNG".

    Returns
    -------
    dict
    """
    images = []
    for img in imgs:
        buf = BytesIO()
        img.save(buf, format=fmt)
        img_b64 = base64.b64encode(buf.getvalue()).decode("utf-8")
        img_dict = {
            "type": "image_url",
            "image_url": {"url": f"data:image/png;base64,{img_b64}", "detail": "auto"},
        }
        images.append(img_dict)

    # chat is in format of list[dict["role": "user"/"system", "content": str, "type": "text"],...]
    # with images, we need "content" to be a list of dicts with "type" and "text"/"image_url"
    # currently we do not support few-shots so only one user message
    # text content also has <image> placeholders, which apparently is not necessary for API class (confirm)

    if isinstance(chat[-1]["content"], list):
        chat[-1]["content"] = images + chat[-1]["content"]
    else:
        text_content = {"type": "text", "text": chat[-1]["content"]}
        chat[-1]["content"] = images + [text_content]
    chat[-1].pop("type")
    return chat


Baber Abbasi's avatar
Baber Abbasi committed
104
class TemplateAPI(TemplateLM):
105
106
    MULTIMODAL = True

Baber Abbasi's avatar
Baber Abbasi committed
107
108
109
110
111
112
    def __init__(
        self,
        model: str = None,
        pretrained: str = None,  # `model` takes precedence over `pretrained` when passed.
        base_url: str = None,
        tokenizer: Optional[str] = None,
113
        # Loglikelihood tasks require a tokenizer to calculate context lengths,
Baber Abbasi's avatar
Baber Abbasi committed
114
115
116
        # however the requests can be sent as a string if the API doesn't support token inputs.
        # use tokenized_requests=False
        tokenizer_backend: Optional[
117
            Literal["tiktoken", "huggingface", "remote", "None", "none"]
Baber Abbasi's avatar
Baber Abbasi committed
118
119
120
121
122
123
124
125
126
127
        ] = "huggingface",
        truncate: bool = False,
        # number of concurrent requests. More useful if not batching
        num_concurrent: int = 1,
        max_retries: int = 3,
        max_gen_toks: int = 256,
        batch_size: Union[str, int] = 1,
        seed: int = 1234,
        max_length: Optional[int] = 2048,
        add_bos_token: bool = False,
128
        custom_prefix_token_id: int = None,
Baber Abbasi's avatar
Baber Abbasi committed
129
        # send the requests as tokens or strings
130
131
132
133
        tokenized_requests: bool = True,
        trust_remote_code: bool = False,
        revision: Optional[str] = "main",
        use_fast_tokenizer: bool = True,
134
        verify_certificate: bool = True,
135
136
        ca_cert_path: Optional[str] = None,
        auth_token: Optional[str] = None,
137
        eos_string: str = None,
138
139
        # timeout in seconds
        timeout: int = 300,
140
        header: Optional[Dict[str, str]] = None,
141
        max_images: int = 1,
Baber Abbasi's avatar
Baber Abbasi committed
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
        **kwargs,
    ) -> None:
        super().__init__()
        missing_packages = [
            pkg
            for pkg in ["aiohttp", "tqdm", "tenacity", "requests"]
            if find_spec(pkg) is None
        ]
        if missing_packages:
            raise ModuleNotFoundError(
                f"Attempted to use an API model, but the required packages {missing_packages} are not installed. "
                'Please install these via `pip install lm-eval[api]` or `pip install -e ."[api]"`'
            )
        self.model = model or pretrained
        self.base_url = base_url
        self.tokenizer = tokenizer
158
        self._header = header
Baber Abbasi's avatar
Baber Abbasi committed
159
160
161
162
163
164
165
166
167
168
169
170
        if not isinstance(batch_size, int) and "auto" in batch_size:
            eval_logger.warning(
                "Automatic batch size is not supported for API models. Defaulting to batch size 1."
            )
        elif int(batch_size) > 1:
            eval_logger.warning(
                "Batch size > 1 detected. Ensure your API supports batched requests with varying total sequence lengths."
            )
        self._batch_size = int(batch_size) if batch_size != "auto" else 1
        self._truncate = truncate
        self._max_gen_toks = int(max_gen_toks)
        self._seed = int(seed)
Baber Abbasi's avatar
Baber Abbasi committed
171
172
173
        # max_length - 1 as we always have 1 token for generation
        eval_logger.info(f"Using max length {max_length} - 1")
        self.max_length = max_length - 1
Baber Abbasi's avatar
Baber Abbasi committed
174
175
        if int(num_concurrent) <= 1:
            eval_logger.info(
176
                "Concurrent requests are disabled. To enable concurrent requests, set `num_concurrent` > 1."
Baber Abbasi's avatar
Baber Abbasi committed
177
178
            )
        self._concurrent = int(num_concurrent)
179
180
181
        self.tokenizer_backend = (
            None if tokenizer_backend in ("None", "none") else tokenizer_backend
        )
Baber Abbasi's avatar
Baber Abbasi committed
182
183
184
185
        self.add_bos_token = add_bos_token
        self.custom_prefix_token_id = custom_prefix_token_id
        self.tokenized_requests = tokenized_requests
        self.max_retries = int(max_retries)
186
        self.verify_certificate = verify_certificate
187
188
        self.ca_cert_path = ca_cert_path
        self.auth_token = auth_token
189
        self._eos_string = eos_string
190
        self.timeout = int(timeout)
191
        self.max_images = int(max_images)
Baber Abbasi's avatar
Baber Abbasi committed
192
193
194
195
196
197

        eval_logger.info(f"Using tokenizer {self.tokenizer_backend}")
        if self.tokenizer_backend is None:
            self.tokenizer = None
            self.tokenized_requests = False
        else:
Baber Abbasi's avatar
Baber Abbasi committed
198
199
200
201
202
            if self.tokenizer is None:
                if self.tokenizer_backend == "huggingface":
                    import transformers

                    self.tokenizer = transformers.AutoTokenizer.from_pretrained(
203
204
205
206
                        self.tokenizer if self.tokenizer else self.model,
                        trust_remote_code=trust_remote_code,
                        revision=revision,
                        use_fast=use_fast_tokenizer,
Baber Abbasi's avatar
Baber Abbasi committed
207
208
209
210
211
212
213
214
215
                    )
                    # Not used as the API will handle padding but to mirror the behavior of the HFLM
                    self.tokenizer = configure_pad_token(self.tokenizer)
                elif self.tokenizer_backend == "tiktoken":
                    try:
                        import tiktoken

                        self.tokenizer = tiktoken.encoding_for_model(self.model)
                    except ModuleNotFoundError as e:
216
                        raise ModuleNotFoundError(
Baber Abbasi's avatar
Baber Abbasi committed
217
218
219
220
221
222
223
224
                            "Attempted to use 'openai' LM type, but the package `tiktoken` is not installed. "
                            "Please install it via `pip install lm-eval[api]` or `pip install -e .[api]`."
                        ) from e
                    if "openai" not in self.base_url:
                        eval_logger.warning(
                            f"Passed `base_url={self.base_url}` but using (OpenAI) Tiktoken tokenizer backend. "
                            "Pass `tokenizer_backend=huggingface` and provide the HF tokenizer name if your model does not use Tiktoken."
                        )
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
                elif self.tokenizer_backend == "remote":
                    from lm_eval.utils import RemoteTokenizer

                    if not self.base_url:
                        raise ValueError(
                            "base_url is required for remote tokenizer backend"
                        )
                    self.tokenizer = RemoteTokenizer(
                        self.base_url,
                        self.timeout,
                        self.verify_certificate,
                        self.ca_cert_path,
                        self.auth_token,
                    )
                    eval_logger.info(f"Using remote tokenizer from {self.base_url}")
Baber Abbasi's avatar
Baber Abbasi committed
240
            else:
Baber Abbasi's avatar
Baber Abbasi committed
241
242
                import transformers

Baber Abbasi's avatar
Baber Abbasi committed
243
                assert isinstance(tokenizer, str), "tokenizer must be a string"
Baber Abbasi's avatar
Baber Abbasi committed
244
                self.tokenizer = transformers.AutoTokenizer.from_pretrained(
Baber Abbasi's avatar
Baber Abbasi committed
245
                    tokenizer,
246
247
248
                    trust_remote_code=trust_remote_code,
                    revision=revision,
                    use_fast=use_fast_tokenizer,
Baber Abbasi's avatar
Baber Abbasi committed
249
250
251
252
253
254
255
256
257
                )

    @abc.abstractmethod
    def _create_payload(
        self,
        messages: Union[List[List[int]], List[dict], List[str], str],
        *,
        generate: bool = True,
        gen_kwargs: Optional[dict] = None,
258
        seed: int = 1234,
259
        eos: str = None,
Baber Abbasi's avatar
Baber Abbasi committed
260
261
262
263
264
265
266
267
268
269
270
271
272
        **kwargs,
    ) -> dict:
        """This method is responsible for creating the json payload that will be sent to the API."""
        raise NotImplementedError

    def create_message(
        self,
        messages: Union[List[List[int]], List[str], List[JsonChatStr]],
        generate=False,
    ) -> Union[List[List[int]], List[dict], List[str], str]:
        """Helper method to transform the prompt into the expected API input format. messages consist of batched requests"""
        if isinstance(messages[0], JsonChatStr):
            # for chat completions we need to decode the json string to list[dict,...]
Baber Abbasi's avatar
Baber Abbasi committed
273
274
275
            assert self._batch_size == 1, (
                "non-tokenized chat requests are only supported with batch_size=1"
            )
Baber Abbasi's avatar
Baber Abbasi committed
276
277
278
279
280
281
            # list[dict["role":..., "content":...],...]
            return json.loads(messages[0].prompt)

        if not self.tokenized_requests:
            # if messages are tokenized:
            if isinstance(messages[0][0], int):
282
                # assuming decoding is lossless. However, this is only for loglikelihood requests
Baber Abbasi's avatar
Baber Abbasi committed
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
                # as we need to compute the context length. For generations, we don't need to tokenize.
                messages = self.decode_batch(messages)
            if self._batch_size <= 1:
                # if batch is 1 return str
                return messages[0]
            else:
                # list[str,...]
                return messages

        # list[list[int], ...]
        return messages

    @staticmethod
    @abc.abstractmethod
    def parse_logprobs(
        outputs: Union[Any, List[Any]],
        tokens: List[List[int]] = None,
        ctxlen: List[int] = None,
        **kwargs,
    ) -> List[Tuple[float, bool]]:
        """Method used to parse the logprobs from the (batched) API response. This method should return a list of tuples"""
        raise NotImplementedError

    @staticmethod
    @abc.abstractmethod
    def parse_generations(outputs: Union[Any, List[Any]], **kwargs) -> List[str]:
        """Method used to parse the generations from the (batched) API response. This method should return a list of str"""
        raise NotImplementedError

    @cached_property
    def api_key(self) -> str:
        """Override this property to return the API key for the API request."""
        return ""

    @cached_property
    def header(self) -> dict:
        """Override this property to return the headers for the API request."""
320
        return self._header or {"Authorization": f"Bearer {self.api_key}"}
Baber Abbasi's avatar
Baber Abbasi committed
321
322
323
324
325
326
327
328
329
330

    @property
    def tokenizer_name(self) -> str:
        """Must be defined for LM subclasses which implement Chat Templating.
        Should return the name of the tokenizer or chat template used.
        Used only to properly fingerprint caches when requests are being cached with `--cache_requests`, otherwise not used.
        """
        return ""

    def apply_chat_template(
Baber Abbasi's avatar
Baber Abbasi committed
331
        self, chat_history: List[Dict[str, str]], add_generation_prompt: bool = True
332
    ) -> Union[str, JsonChatStr, List[Dict]]:
Baber Abbasi's avatar
Baber Abbasi committed
333
334
335
        """Applies a chat template to a list of chat history between user and model."""
        if self.tokenizer_backend == "huggingface" and self.tokenized_requests:
            return self.tokenizer.apply_chat_template(
Baber Abbasi's avatar
Baber Abbasi committed
336
337
338
339
                chat_history,
                tokenize=False,
                add_generation_prompt=add_generation_prompt,
                continue_final_message=not add_generation_prompt,
Baber Abbasi's avatar
Baber Abbasi committed
340
            )
341
342
        elif self.tokenizer_backend == "remote" and self.tokenized_requests:
            return chat_history
Baber Abbasi's avatar
Baber Abbasi committed
343
344
        else:
            # bit of a hack. We'll load back before sending to the API
345
346
347
348
349
350
            return JsonChatStr(
                json.dumps(
                    [{**item, "type": "text"} for item in chat_history],
                    ensure_ascii=False,
                )
            )
Baber Abbasi's avatar
Baber Abbasi committed
351
352
353
354
355
356
357
358
359
360

    @cached_property
    def eot_token_id(self) -> Optional[int]:
        if self.tokenizer is None:
            return None
        else:
            if self.tokenizer_backend == "huggingface":
                return self.tokenizer.eos_token_id
            elif self.tokenizer_backend == "tiktoken":
                return self.tokenizer.eot_token
361
362
            elif self.tokenizer_backend == "remote":
                return self.tokenizer.eos_token_id
Baber Abbasi's avatar
Baber Abbasi committed
363

364
365
366
367
368
369
370
371
372
    @cached_property
    def eos_string(self) -> Optional[str]:
        if self._eos_string:
            return self._eos_string
        elif self.tokenizer is not None:
            if self.tokenizer_backend == "huggingface":
                return self.tokenizer.eos_token
            elif self.tokenizer_backend == "tiktoken":
                return self.tokenizer.decode([self.tokenizer.eot_token])
373
374
            elif self.tokenizer_backend == "remote":
                return self.tokenizer.eos_token
375
376
377
378
379
380
        else:
            eval_logger.warning(
                "Cannot determine EOS string to pass to stop sequence. Manually set by passing `eos_string` to model_args."
            )
            return None

Baber Abbasi's avatar
Baber Abbasi committed
381
382
383
384
385
386
387
388
389
390
391
    @cached_property
    def prefix_token_id(self) -> Optional[int]:
        if self.tokenizer is None:
            return None
        else:
            if self.custom_prefix_token_id is not None:
                return self.custom_prefix_token_id
            if self.tokenizer_backend == "huggingface":
                if self.tokenizer.bos_token_id is not None:
                    return self.tokenizer.bos_token_id
                return self.tokenizer.eos_token_id
392
393
            elif self.tokenizer_backend == "remote":
                return self.tokenizer.bos_token_id or self.tokenizer.eos_token_id
Baber Abbasi's avatar
Baber Abbasi committed
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
            else:
                return self.tokenizer.eot_token

    def tok_encode(
        self,
        string: str,
        left_truncate_len: int = None,
        add_special_tokens: bool = False,
        truncation: bool = False,
        **kwargs,
    ) -> Union[List[List[int]], List[int], List[str]]:
        if self.tokenizer_backend is None:
            return [string]
        elif self.tokenizer_backend == "huggingface":
            # by default for CausalLM - false or self.add_bos_token is set
            if not add_special_tokens:
                add_special_tokens = False or self.add_bos_token
            encoding: Union[List[List[int]], List[int]] = self.tokenizer(
                string,
                add_special_tokens=add_special_tokens,
                truncation=truncation,
                return_attention_mask=False,
            ).input_ids

            # left-truncate the encoded context to be at most `left_truncate_len` tokens long
            if left_truncate_len:
                if not isinstance(string, str):
                    encoding = [enc[-left_truncate_len:] for enc in encoding]
                else:
                    encoding = encoding[-left_truncate_len:]

            return encoding
426
427
428
429
430
        elif self.tokenizer_backend == "remote":
            if isinstance(string, str):
                encoding = self.tokenizer.encode(string)
            else:
                encoding = [self.tokenizer.encode(s) for s in string]
Baber Abbasi's avatar
Baber Abbasi committed
431

432
433
434
435
436
437
438
            if left_truncate_len:
                if isinstance(string, str):
                    encoding = encoding[-left_truncate_len:]
                else:
                    encoding = [enc[-left_truncate_len:] for enc in encoding]

            return encoding
Baber Abbasi's avatar
Baber Abbasi committed
439
440
441
442
443
444
445
446
447
448
449
450
        else:
            try:
                encoding = self.tokenizer.encode(string)
            except Exception:
                encoding = self.tokenizer.encode_batch(string)
            return encoding

    def decode_batch(self, tokens: List[List[int]]) -> List[str]:
        if self.tokenizer_backend == "huggingface":
            return self.tokenizer.batch_decode(tokens)
        elif self.tokenizer_backend == "tiktoken":
            return self.tokenizer.decode_batch(tokens)
451
452
        elif self.tokenizer_backend == "remote":
            return self.tokenizer.batch_decode(tokens)
Baber Abbasi's avatar
Baber Abbasi committed
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470

    def model_call(
        self,
        messages: Union[List[List[int]], List[str], List[JsonChatStr]],
        *,
        generate: bool = True,
        gen_kwargs: Optional[Dict] = None,
        **kwargs,
    ) -> Optional[dict]:
        # !!! Copy: shared dict for each request, need new object !!!
        gen_kwargs = copy.deepcopy(gen_kwargs)
        try:
            response = requests.post(
                self.base_url,
                json=self._create_payload(
                    self.create_message(messages),
                    generate=generate,
                    gen_kwargs=gen_kwargs,
471
                    seed=self._seed,
472
                    eos=self.eos_string,
Baber Abbasi's avatar
Baber Abbasi committed
473
474
475
                    **kwargs,
                ),
                headers=self.header,
476
                verify=self.verify_certificate,
Baber Abbasi's avatar
Baber Abbasi committed
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
            )
            if not response.ok:
                eval_logger.warning(
                    f"API request failed with error message: {response.text}. Retrying..."
                )
            response.raise_for_status()
            return response.json()
        except RetryError:
            eval_logger.error(
                "API request failed after multiple retries. Please check the API status."
            )
            return None

    async def amodel_call(
        self,
        session: ClientSession,
493
        sem: asyncio.Semaphore,
Baber Abbasi's avatar
Baber Abbasi committed
494
495
496
497
498
499
500
501
502
503
504
505
506
507
        messages: Union[List[List[int]], List[str], List[JsonChatStr]],
        *,
        generate: bool = True,
        cache_keys: list = None,
        ctxlens: Optional[List[int]] = None,
        gen_kwargs: Optional[Dict] = None,
        **kwargs,
    ) -> Union[List[str], List[Tuple[float, bool]], None]:
        # !!! Copy: shared dict for each request, need new object !!!
        gen_kwargs = copy.deepcopy(gen_kwargs)
        payload = self._create_payload(
            self.create_message(messages),
            generate=generate,
            gen_kwargs=gen_kwargs,
508
            seed=self._seed,
Baber Abbasi's avatar
Baber Abbasi committed
509
510
511
            **kwargs,
        )
        cache_method = "generate_until" if generate else "loglikelihood"
512
        acquired = await sem.acquire()
Baber Abbasi's avatar
Baber Abbasi committed
513
514
515
516
517
518
519
520
521
        try:
            async with session.post(
                self.base_url,
                json=payload,
                headers=self.header,
            ) as response:
                if not response.ok:
                    error_text = await response.text()
                    eval_logger.warning(
522
523
                        f"API request failed! Status code: {response.status}, "
                        f"Response text: {error_text}. Retrying..."
Baber Abbasi's avatar
Baber Abbasi committed
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
                    )
                # raising exception will retry the request
                response.raise_for_status()
                outputs = await response.json()
            answers = (
                self.parse_generations(
                    outputs=outputs,
                )
                if generate
                else self.parse_logprobs(
                    outputs=outputs,
                    tokens=messages,
                    ctxlens=ctxlens,
                )
            )
            if cache_keys:
                for res, cache in zip(answers, cache_keys):
                    self.cache_hook.add_partial(cache_method, cache, res)
            return answers
        # If the retries also fail
544
545
546
547
548
549
        except BaseException as e:
            eval_logger.error(f"Exception:{repr(e)}, {outputs}, retrying.")
            raise e
        finally:
            if acquired:
                sem.release()
Baber Abbasi's avatar
Baber Abbasi committed
550

551
    def batch_loglikelihood_requests(
Baber Abbasi's avatar
Baber Abbasi committed
552
553
554
555
556
557
558
        self, chunks: Iterable[List[LogLikelihoodInputs]]
    ) -> Tuple[List[List[int]], List[int], List[Tuple[str, str]]]:
        inputs = []
        ctxlens = []
        cache_keys = []
        for chunk in chunks:
            for cache_key, context_enc, continuation_enc in chunk:
559
                # max_length - 1 as we always have 1 token for generation
560
561
562
563
564
                inp = (context_enc + continuation_enc)[-self.max_length :]
                if len(inp) < len(context_enc + continuation_enc):
                    eval_logger.warning(
                        f"Context length ({len(context_enc)}) + continuation length ({len(continuation_enc)}) > max_length ({self.max_length}). Left truncating context."
                    )
Baber Abbasi's avatar
Baber Abbasi committed
565
                ctxlen = len(context_enc) - max(
566
                    0, len(context_enc) + len(continuation_enc) - self.max_length
Baber Abbasi's avatar
Baber Abbasi committed
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
                )

                inputs.append(inp)
                ctxlens.append(ctxlen)
                cache_keys.append(cache_key)
        return inputs, ctxlens, cache_keys

    async def get_batched_requests(
        self,
        requests: list,
        cache_keys: list,
        *,
        generate: bool = True,
        ctxlens: List[int] = None,
        **kwargs,
    ) -> Union[List[List[str]], List[List[Tuple[float, bool]]]]:
        ctxlens = ctxlens if ctxlens else [None] * len(requests)
584
        conn = TCPConnector(limit=self._concurrent, ssl=self.verify_certificate)
585
        sem = asyncio.Semaphore(self._concurrent)
586
587
588
        async with ClientSession(
            connector=conn, timeout=ClientTimeout(total=self.timeout)
        ) as session:
Baber Abbasi's avatar
Baber Abbasi committed
589
590
591
592
            retry_: Callable[..., Awaitable[Any]] = retry(
                stop=stop_after_attempt(self.max_retries),
                wait=wait_exponential(multiplier=0.5, min=1, max=10),
                reraise=True,
593
594
595
                before_sleep=lambda retry_state: eval_logger.info(
                    f"Retry attempt {retry_state.attempt_number}"
                ),
Baber Abbasi's avatar
Baber Abbasi committed
596
597
598
599
600
601
            )(self.amodel_call)
            # Create tasks for each batch of request
            tasks = [
                asyncio.create_task(
                    retry_(
                        session=session,
602
                        sem=sem,
Baber Abbasi's avatar
Baber Abbasi committed
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
                        messages=message,
                        cache_keys=cache_key,
                        generate=generate,
                        ctxlens=ctxlen,
                        **kwargs,
                    )
                )
                for message, cache_key, ctxlen in zip(
                    chunks(requests, n=self._batch_size),
                    chunks(cache_keys, n=self._batch_size),
                    chunks(ctxlens, n=self._batch_size),
                )
            ]

            return await tqdm_asyncio.gather(*tasks, desc="Requesting API")

    def _loglikelihood_tokens(self, requests, **kwargs) -> List[Tuple[float, bool]]:
Baber Abbasi's avatar
Baber Abbasi committed
620
621
622
        assert self.tokenizer is not None, (
            "Tokenizer is required for loglikelihood tasks to compute context lengths."
        )
Baber Abbasi's avatar
Baber Abbasi committed
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
        res = []

        def _collate(req: LogLikelihoodInputs):
            """Defines the key for the sorted method"""
            # the negative sign on len(toks) sorts descending - this has a few advantages:
            # - time estimates will always be over not underestimates, which is more useful for planning
            # - to know the size of a batch when going through the list, you know the first one is always the batch
            #   padded context length. this is useful to simplify the batching logic and more importantly to make
            #   automatic adaptive batches much much easier to implement
            # - any OOMs will happen right away rather than near the end

            toks = req[1] + req[2]
            return -len(toks), tuple(toks)

        re_ord = Collator(
            requests,
            sort_fn=_collate,
            group_by=None,
        )
        # if concurrent then we'll batch in the async context
        chunked = re_ord.get_batched(n=self._batch_size if self._concurrent <= 1 else 0)
        if self._concurrent <= 1:
            pbar = tqdm(desc="Requesting API", total=len(requests))
            for chunk in chunked:
647
                inputs, ctxlens, cache_keys = self.batch_loglikelihood_requests([chunk])
Baber Abbasi's avatar
Baber Abbasi committed
648
649
650
651
652

                outputs = retry(
                    stop=stop_after_attempt(self.max_retries),
                    wait=wait_exponential(multiplier=0.5, min=1, max=10),
                    reraise=True,
653
                )(self.model_call)(messages=inputs, generate=False)
Baber Abbasi's avatar
Baber Abbasi committed
654
655
656
657
658
659
660
661
662
663
                if isinstance(outputs, dict):
                    outputs = [outputs]
                for answer_, cache_key in zip(
                    self.parse_logprobs(
                        outputs=outputs, tokens=inputs, ctxlens=ctxlens
                    ),
                    cache_keys,
                ):
                    if answer_ is not None:
                        res.append(answer_)
664
                        # cache requests that aren't from a loglikelihood_rolling request
Baber Abbasi's avatar
Baber Abbasi committed
665
666
667
668
669
670
                        if cache_key is not None:
                            self.cache_hook.add_partial(
                                "loglikelihood", cache_key, answer_
                            )
                        pbar.update(1)
        else:
671
            inputs, ctxlens, cache_keys = self.batch_loglikelihood_requests(chunked)
Baber Abbasi's avatar
Baber Abbasi committed
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
            res = itertools.chain.from_iterable(
                asyncio.run(
                    self.get_batched_requests(
                        inputs, cache_keys, generate=False, ctxlens=ctxlens
                    )
                )
            )

        return re_ord.get_original(res)

    def generate_until(
        self, requests: List[Instance], disable_tqdm: bool = False
    ) -> List[str]:
        res = []

        def _collate_gen(_requests):
            # sort by the length of the non-tokenized contexts
            return -len(_requests[0])

        # Let the API deal with tokenization
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
        if len(requests[0].args) > 2:
            assert self.tokenizer is None, (
                "tokenizer is not supported for multimodal requests yet!"
            )
            eval_logger.info(
                f"Using max_images {self.max_images}. Set in the model args."
            )
            requests, all_gen_kwargs, auxiliary_args = zip(
                *(req.args for req in requests)
            )
            requests = tuple(
                JsonChatStr(
                    json.dumps(
                        create_image_prompt(
                            y["visual"][: self.max_images], json.loads(x.prompt)
                        )
                    )
                )
                for x, y in zip(requests, auxiliary_args)
            )
        else:
            requests, all_gen_kwargs = zip(*(req.args for req in requests))
Baber Abbasi's avatar
Baber Abbasi committed
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
        if self.tokenized_requests:
            encodings_list = self.tok_encode(
                requests, add_special_tokens=self.add_bos_token
            )
        else:
            encodings_list = [None] * len(requests)
        requests = [
            (a, b, c) for a, b, c in zip(requests, all_gen_kwargs, encodings_list)
        ]

        re_ord = Collator(
            requests,
            sort_fn=_collate_gen,
            group_by="gen_kwargs",
        )
        chunked = re_ord.get_batched(
            n=self._batch_size if self._concurrent <= 1 else 0, batch_fn=None
        )
732
733
734
735
        if not self.tokenized_requests:
            eval_logger.info(
                "Tokenized requests are disabled. Context + generation length is not checked."
            )
Baber Abbasi's avatar
Baber Abbasi committed
736
737
738
739
        if self._concurrent <= 1:
            pbar = tqdm(desc="Requesting API", total=len(requests))
            for chunk in chunked:
                contexts, all_gen_kwargs, encodings_list = zip(*chunk)
740
741
742
743
744
745
746
747
748
749
750
751
752
753
                if self.tokenized_requests:
                    max_gen_toks = all_gen_kwargs[0].get(
                        "max_gen_toks", self._max_gen_toks
                    )
                    max_context_len = self.max_length - max_gen_toks

                    encodings_list = [x[-max_context_len:] for x in encodings_list]

                    if any(
                        len(x) + max_gen_toks > self.max_length for x in encodings_list
                    ):
                        eval_logger.warning(
                            f"Some contexts exceeded (max length: ({self.max_length}) - max_gen_toks: ({max_gen_toks}). They were left truncated."
                        )
754

Baber Abbasi's avatar
Baber Abbasi committed
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
                req = encodings_list if self.tokenized_requests else contexts
                outputs = retry(
                    stop=stop_after_attempt(self.max_retries),
                    wait=wait_exponential(multiplier=0.5, min=1, max=10),
                    reraise=True,
                )(self.model_call)(
                    messages=req,
                    generate=True,
                    gen_kwargs=copy.deepcopy(all_gen_kwargs[0]),
                )
                for generated_text, context in zip(
                    self.parse_generations(
                        outputs=outputs,
                        contexts=contexts,
                    ),
                    contexts,
                ):
                    if generated_text is not None:
                        res.append(generated_text)

                        # partial caching
                        if context is not None:
                            self.cache_hook.add_partial(
                                "generate_until",
                                (context, all_gen_kwargs[0]),
                                generated_text,
                            )
                            pbar.update(1)
        else:
            for chunk in chunked:
                contexts, all_gen_kwargs, encodings_list = zip(*chunk)
786
787
788
789
790
791
792
793
794
795
796
797
798
799
                if self.tokenized_requests:
                    max_gen_toks = all_gen_kwargs[0].get(
                        "max_gen_toks", self._max_gen_toks
                    )
                    max_context_len = self.max_length - max_gen_toks

                    encodings_list = [x[-max_context_len:] for x in encodings_list]

                    if any(
                        len(x) + max_gen_toks > self.max_length for x in encodings_list
                    ):
                        eval_logger.warning(
                            f"Some contexts exceeded (max length: ({self.max_length}) - max_gen_toks ({max_gen_toks}). They were left truncated."
                        )
800

Baber Abbasi's avatar
Baber Abbasi committed
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
                req = encodings_list if self.tokenized_requests else contexts
                results = itertools.chain.from_iterable(
                    asyncio.run(
                        self.get_batched_requests(
                            req,
                            cache_keys=[(ctx, all_gen_kwargs[0]) for ctx in contexts],
                            generate=True,
                            gen_kwargs=copy.deepcopy(all_gen_kwargs[0]),
                        )
                    )
                )
                res.extend(results)

        return re_ord.get_original(res)

    def loglikelihood_rolling(
        self, requests: List[Instance], disable_tqdm: bool = False
    ) -> List[float]:
        loglikelihoods = []

        for (string,) in tqdm([req.args for req in requests], disable=disable_tqdm):
            rolling_token_windows = list(
                map(
                    utils.make_disjoint_window,
                    utils.get_rolling_token_windows(
                        token_list=self.tok_encode(string),
                        prefix_token=self.prefix_token_id,
828
829
                        # max_seq_len - (1 for context)
                        max_seq_len=self.max_length - 1,
Baber Abbasi's avatar
Baber Abbasi committed
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
                        context_len=1,
                    ),
                )
            )

            # TODO: Right now, we pass single EOT token to the Encoder and the full context to the decoder, in seq2seq case
            rolling_token_windows = [(None,) + x for x in rolling_token_windows]

            string_nll = self._loglikelihood_tokens(
                rolling_token_windows,
                disable_tqdm=True,
            )

            # discard is_greedy
            string_nll = [x[0] for x in string_nll]

            string_nll = sum(string_nll)
            loglikelihoods.append(string_nll)
848
849
850

            # cache this loglikelihood_rolling request
            self.cache_hook.add_partial("loglikelihood_rolling", (string,), string_nll)
Baber Abbasi's avatar
Baber Abbasi committed
851
        return loglikelihoods