|
| 1 | +# MIT License |
| 2 | + |
| 3 | +# Copyright (c) 2024 The HuggingFace Team |
| 4 | + |
| 5 | +# Permission is hereby granted, free of charge, to any person obtaining a copy |
| 6 | +# of this software and associated documentation files (the "Software"), to deal |
| 7 | +# in the Software without restriction, including without limitation the rights |
| 8 | +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
| 9 | +# copies of the Software, and to permit persons to whom the Software is |
| 10 | +# furnished to do so, subject to the following conditions: |
| 11 | + |
| 12 | +# The above copyright notice and this permission notice shall be included in all |
| 13 | +# copies or substantial portions of the Software. |
| 14 | + |
| 15 | +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 16 | +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 17 | +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 18 | +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 19 | +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
| 20 | +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE |
| 21 | +# SOFTWARE. |
| 22 | + |
| 23 | +import hashlib |
| 24 | +import logging |
| 25 | +import os |
| 26 | +import time |
| 27 | + |
| 28 | +import diskcache |
| 29 | +import tenacity |
| 30 | +from deep_translator import GoogleTranslator |
| 31 | +from tqdm import tqdm |
| 32 | +from transformers import AutoTokenizer |
| 33 | + |
| 34 | +from lighteval.data import GenerativeTaskDataset |
| 35 | +from lighteval.models.abstract_model import LightevalModel, ModelInfo |
| 36 | +from lighteval.models.model_output import ( |
| 37 | + GenerativeResponse, |
| 38 | + LoglikelihoodResponse, |
| 39 | + LoglikelihoodSingleTokenResponse, |
| 40 | +) |
| 41 | +from lighteval.tasks.requests import ( |
| 42 | + GreedyUntilRequest, |
| 43 | + LoglikelihoodRequest, |
| 44 | + LoglikelihoodRollingRequest, |
| 45 | + LoglikelihoodSingleTokenRequest, |
| 46 | +) |
| 47 | + |
| 48 | + |
| 49 | +logger = logging.getLogger(__name__) |
| 50 | + |
| 51 | + |
| 52 | +class GoogleTranslateClient(LightevalModel): |
| 53 | + def __init__(self, config) -> None: |
| 54 | + self.model = config.model_name |
| 55 | + self.model_definition_file_path = config.model_definition_file_path |
| 56 | + |
| 57 | + self.model_info = ModelInfo( |
| 58 | + model_name=config.model, |
| 59 | + model_sha="", |
| 60 | + model_dtype=None, |
| 61 | + model_size="", |
| 62 | + ) |
| 63 | + |
| 64 | + self._tokenizer = AutoTokenizer.from_pretrained("gpt2") # Use a dummy tokenizer for compatibility |
| 65 | + |
| 66 | + # Deep-translator also supports other translators |
| 67 | + self.translator = GoogleTranslator() |
| 68 | + |
| 69 | + # Initialize disk cache |
| 70 | + cache_dir = os.path.join(os.getcwd(), ".translation_cache") |
| 71 | + self.cache = diskcache.Cache(cache_dir) |
| 72 | + |
| 73 | + self.max_retries = 3 |
| 74 | + self.retry_delay = 1 |
| 75 | + |
| 76 | + def _get_cache_key(self, context: str, src_lang: str, tgt_lang: str) -> str: |
| 77 | + """Generate a unique cache key for the translation request.""" |
| 78 | + # IMPORTANT: In case we want to support other translators, we can add the translator name to the key |
| 79 | + key_string = f"{context}|{src_lang}|{tgt_lang}" |
| 80 | + return hashlib.md5(key_string.encode()).hexdigest() |
| 81 | + |
| 82 | + @tenacity.retry( |
| 83 | + stop=tenacity.stop_after_attempt(3), |
| 84 | + wait=tenacity.wait_exponential(multiplier=1, min=4, max=10), |
| 85 | + retry=tenacity.retry_if_exception_type((Exception)), |
| 86 | + before_sleep=lambda retry_state: time.sleep(1), |
| 87 | + ) |
| 88 | + def _translate_with_cache(self, context: str, src_lang: str, tgt_lang: str) -> str: |
| 89 | + """Translate text using cache if available, otherwise call Google Translate with retry logic.""" |
| 90 | + cache_key = self._get_cache_key(context, src_lang, tgt_lang) |
| 91 | + |
| 92 | + # Try to get from cache |
| 93 | + if cache_key in self.cache: |
| 94 | + result = self.cache[cache_key] |
| 95 | + if result is not None and result != "": |
| 96 | + return result |
| 97 | + logger.warning("Translation in cache is empty. Removing from cache and retrying...") |
| 98 | + del self.cache[cache_key] |
| 99 | + |
| 100 | + try: |
| 101 | + # Updated translation call for deep-translator |
| 102 | + self.translator.source = src_lang |
| 103 | + self.translator.target = tgt_lang |
| 104 | + result = self.translator.translate(context) |
| 105 | + if result is None or result == "": |
| 106 | + result = "" |
| 107 | + |
| 108 | + self.cache[cache_key] = result |
| 109 | + return result |
| 110 | + except Exception as e: |
| 111 | + logger.warning(f"Translation error: {str(e)}. Retrying...") |
| 112 | + raise # Let tenacity handle the retry |
| 113 | + |
| 114 | + def greedy_until( |
| 115 | + self, |
| 116 | + requests: list[GreedyUntilRequest], |
| 117 | + ) -> list[GenerativeResponse]: |
| 118 | + """ |
| 119 | + Generates responses using a greedy decoding strategy until certain ending conditions are met. |
| 120 | + Results are cached to disk to avoid repeated translations. |
| 121 | +
|
| 122 | + Args: |
| 123 | + requests (list[Request]): list of requests containing the context and ending conditions. |
| 124 | + override_bs (int, optional): Override the batch size for generation. Defaults to None. |
| 125 | +
|
| 126 | + Returns: |
| 127 | + list[GenerativeResponse]: list of generated responses. |
| 128 | + """ |
| 129 | + for request in requests: |
| 130 | + request.tokenized_context = self.tok_encode(request.context) |
| 131 | + |
| 132 | + dataset = GenerativeTaskDataset(requests=requests, num_dataset_splits=self.DATASET_SPLITS) |
| 133 | + results = [] |
| 134 | + |
| 135 | + for _ in tqdm( |
| 136 | + dataset.splits_start_end_iterator(), |
| 137 | + total=dataset.num_dataset_splits, |
| 138 | + desc="Splits", |
| 139 | + position=0, |
| 140 | + disable=False, # self.disable_tqdm, |
| 141 | + ): |
| 142 | + for r in tqdm(dataset, desc="Batch", position=1, disable=False): |
| 143 | + # Extract source and target languages from task name |
| 144 | + # Format is like "community|sdst-text_level:de-fr|0" |
| 145 | + src_lang, tgt_lang = r.task_name.split("|")[1].split(":")[-1].split("-") |
| 146 | + |
| 147 | + context = r.context.replace(f"{src_lang.upper()}: ", "").replace(f"\n{tgt_lang.upper()}: ", "") |
| 148 | + result = self._translate_with_cache(context, src_lang, tgt_lang) |
| 149 | + if result is None: |
| 150 | + result = "" # Set to empty string to prevent errors in metric computation |
| 151 | + |
| 152 | + cur_response = GenerativeResponse( |
| 153 | + result=result, |
| 154 | + logits=None, |
| 155 | + generated_tokens=[], |
| 156 | + input_tokens=[], |
| 157 | + ) |
| 158 | + results.append(cur_response) |
| 159 | + |
| 160 | + return dataset.get_original_order(results) |
| 161 | + |
| 162 | + @property |
| 163 | + def tokenizer(self): |
| 164 | + return self._tokenizer |
| 165 | + |
| 166 | + def tok_encode(self, text: str): |
| 167 | + return text |
| 168 | + |
| 169 | + @property |
| 170 | + def add_special_tokens(self) -> bool: |
| 171 | + return False |
| 172 | + |
| 173 | + @property |
| 174 | + def max_length(self) -> int: |
| 175 | + """Return the maximum sequence length of the model.""" |
| 176 | + return 4096 |
| 177 | + |
| 178 | + def loglikelihood(self, requests: list[LoglikelihoodRequest]) -> list[LoglikelihoodResponse]: |
| 179 | + """Tokenize the context and continuation and compute the log likelihood of those |
| 180 | + tokenized sequences. |
| 181 | + """ |
| 182 | + raise NotImplementedError |
| 183 | + |
| 184 | + def loglikelihood_rolling( |
| 185 | + self, |
| 186 | + requests: list[LoglikelihoodRollingRequest], |
| 187 | + ) -> list[LoglikelihoodResponse]: |
| 188 | + """This function is used to compute the log likelihood of the context for perplexity metrics.""" |
| 189 | + raise NotImplementedError |
| 190 | + |
| 191 | + def loglikelihood_single_token( |
| 192 | + self, |
| 193 | + requests: list[LoglikelihoodSingleTokenRequest], |
| 194 | + ) -> list[LoglikelihoodSingleTokenResponse]: |
| 195 | + """Tokenize the context and continuation and compute the log likelihood of those |
| 196 | + tokenized sequences. |
| 197 | + """ |
| 198 | + raise NotImplementedError |
0 commit comments