|
| 1 | +from abc import ABC, abstractmethod |
| 2 | +from typing import Optional, Union |
| 3 | + |
| 4 | +import torch |
| 5 | +from transformers import BatchEncoding |
| 6 | + |
| 7 | +from lighteval.models.model_config import EnvConfig |
| 8 | +from lighteval.models.model_output import GenerateReturn, LoglikelihoodReturn, LoglikelihoodSingleTokenReturn |
| 9 | +from lighteval.tasks.requests import ( |
| 10 | + GreedyUntilRequest, |
| 11 | + GreedyUntilWithLogitsRequest, |
| 12 | + LoglikelihoodRequest, |
| 13 | + LoglikelihoodRollingRequest, |
| 14 | + LoglikelihoodSingleTokenRequest, |
| 15 | +) |
| 16 | + |
| 17 | + |
| 18 | +TokenSequence = Union[list[int], torch.LongTensor, torch.Tensor, BatchEncoding] |
| 19 | + |
| 20 | + |
| 21 | +class LightevalModel(ABC): |
| 22 | + DATASET_SPLITS = 4 |
| 23 | + |
| 24 | + """Abstract model class defining the API that every model to plug into lighteval must follow.""" |
| 25 | + |
| 26 | + @abstractmethod |
| 27 | + def __init__( |
| 28 | + self, |
| 29 | + config, |
| 30 | + env_config: EnvConfig, |
| 31 | + ): |
| 32 | + return NotImplemented |
| 33 | + |
| 34 | + def cleanup(self): |
| 35 | + """Clean up operations if needed, such as closing an endpoint.""" |
| 36 | + return |
| 37 | + |
| 38 | + @property |
| 39 | + @abstractmethod |
| 40 | + def tokenizer(self): |
| 41 | + raise NotImplementedError |
| 42 | + |
| 43 | + @property |
| 44 | + @abstractmethod |
| 45 | + def add_special_tokens(self): |
| 46 | + raise NotImplementedError |
| 47 | + |
| 48 | + @property |
| 49 | + @abstractmethod |
| 50 | + def max_length(self) -> int: |
| 51 | + """Return the maximum sequence length of the model.""" |
| 52 | + raise NotImplementedError |
| 53 | + |
| 54 | + @property |
| 55 | + def disable_tqdm(self) -> bool: |
| 56 | + raise NotImplementedError |
| 57 | + |
| 58 | + def greedy_until_with_logits( |
| 59 | + self, |
| 60 | + requests: list[GreedyUntilWithLogitsRequest], |
| 61 | + override_bs: Optional[int] = None, |
| 62 | + ) -> list[GenerateReturn]: |
| 63 | + """ |
| 64 | + Generates sequences greedily until a stopping condition is met, |
| 65 | + returning both the generated sequences and the logits. |
| 66 | +
|
| 67 | + Args: |
| 68 | + requests (list[tuple[str, dict]]): A list of input requests, |
| 69 | + where each request is a tuple containing a prompt string and a dictionary of additional parameters. |
| 70 | + disable_tqdm (bool, optional): Whether to disable the tqdm progress bar. Defaults to False. |
| 71 | + override_bs (Optional[int], optional): Overrides the batch size for generation. Defaults to None. |
| 72 | +
|
| 73 | + Returns: |
| 74 | + list[GenerateReturn]: A list of GenerateReturn objects, |
| 75 | + where each object contains the generated sequence and the corresponding logits. |
| 76 | + """ |
| 77 | + return self.greedy_until( |
| 78 | + requests=requests, |
| 79 | + override_bs=override_bs, |
| 80 | + returns_logits=True, |
| 81 | + ) |
| 82 | + |
| 83 | + @abstractmethod |
| 84 | + def greedy_until( |
| 85 | + self, |
| 86 | + requests: list[GreedyUntilRequest], |
| 87 | + returns_logits: bool = False, |
| 88 | + override_bs: Optional[int] = None, |
| 89 | + ) -> list[GenerateReturn]: |
| 90 | + """ |
| 91 | + Generates responses using a greedy decoding strategy until certain ending conditions are met. |
| 92 | +
|
| 93 | + Args: |
| 94 | + requests (list[Request]): list of requests containing the context and ending conditions. |
| 95 | + returns_logits (bool, optional): Whether to return the logits of the generated responses. Defaults to False. |
| 96 | + disable_tqdm (bool, optional): Whether to disable the progress bar. Defaults to False. |
| 97 | + override_bs (int, optional): Override the batch size for generation. Defaults to None. |
| 98 | +
|
| 99 | + Returns: |
| 100 | + list[GenerateReturn]: list of generated responses. |
| 101 | + """ |
| 102 | + return NotImplemented |
| 103 | + |
| 104 | + @abstractmethod |
| 105 | + def loglikelihood( |
| 106 | + self, requests: list[LoglikelihoodRequest], override_bs: Optional[int] = None |
| 107 | + ) -> list[LoglikelihoodReturn]: |
| 108 | + """Tokenize the context and continuation and compute the log likelihood of those |
| 109 | + tokenized sequences. |
| 110 | + """ |
| 111 | + return NotImplemented |
| 112 | + |
| 113 | + @abstractmethod |
| 114 | + def loglikelihood_rolling( |
| 115 | + self, requests: list[LoglikelihoodRollingRequest], override_bs=None |
| 116 | + ) -> list[LoglikelihoodReturn]: |
| 117 | + """This function is used to compute the log likelihood of the context for perplexity metrics.""" |
| 118 | + return NotImplemented |
| 119 | + |
| 120 | + @abstractmethod |
| 121 | + def loglikelihood_single_token( |
| 122 | + self, requests: list[LoglikelihoodSingleTokenRequest], override_bs: Optional[int] = None |
| 123 | + ) -> list[LoglikelihoodSingleTokenReturn]: |
| 124 | + """Tokenize the context and continuation and compute the log likelihood of those |
| 125 | + tokenized sequences. |
| 126 | + """ |
| 127 | + return NotImplemented |
| 128 | + |
| 129 | + # Tokenization utils |
| 130 | + def tok_encode(self, str_to_encode: str | list[str], add_special_tokens: Optional[bool] = None) -> TokenSequence: |
| 131 | + if add_special_tokens is None: |
| 132 | + add_special_tokens = self.add_special_tokens |
| 133 | + if isinstance(str_to_encode, str): |
| 134 | + return self.tokenizer.encode(str_to_encode, add_special_tokens=add_special_tokens) |
| 135 | + return self.tokenizer( |
| 136 | + str_to_encode, |
| 137 | + padding=True, |
| 138 | + add_special_tokens=add_special_tokens, |
| 139 | + return_tensors="pt", |
| 140 | + ) |
| 141 | + |
| 142 | + def tok_encode_pair(self, context, continuation): |
| 143 | + """Encodes a context, continuation pair by taking care of the spaces in between.""" |
| 144 | + n_spaces = len(context) - len(context.rstrip()) |
| 145 | + if n_spaces > 0: |
| 146 | + continuation = context[-n_spaces:] + continuation |
| 147 | + context = context[:-n_spaces] |
| 148 | + whole_enc = self.tok_encode(context + continuation) |
| 149 | + context_enc = self.tok_encode(context) |
| 150 | + context_enc_len = len(context_enc) |
| 151 | + continuation_enc = whole_enc[context_enc_len:] |
| 152 | + return context_enc, continuation_enc |
| 153 | + |
| 154 | + def tok_decode(self, tokens: torch.LongTensor) -> list[str]: |
| 155 | + return self.tokenizer.batch_decode(tokens, skip_special_tokens=True) |
0 commit comments