


import inspect

import jax
import jax.lax as lax
import jax.numpy as jnp

from ..utils import add_start_docstrings
from ..utils.logging import get_logger


SCREAMING_SNAKE_CASE			: Dict				   =					get_logger(__name__)


SCREAMING_SNAKE_CASE			: Tuple				   =					r'\n    Args:\n        input_ids (`jnp.ndarray` of shape `(batch_size, sequence_length)`):\n            Indices of input sequence tokens in the vocabulary.\n\n            Indices can be obtained using [`PreTrainedTokenizer`]. See [`PreTrainedTokenizer.encode`] and\n            [`PreTrainedTokenizer.__call__`] for details.\n\n            [What are input IDs?](../glossary#input-ids)\n        scores (`jnp.ndarray` of shape `(batch_size, config.vocab_size)`):\n            Prediction scores of a language modeling head. These can be logits for each vocabulary when not using beam\n            search or log softmax for each vocabulary token when using beam search\n        kwargs (`Dict[str, Any]`, *optional*):\n            Additional logits processor specific kwargs.\n\n    Return:\n        `jnp.ndarray` of shape `(batch_size, config.vocab_size)`: The processed prediction scores.\n\n'






class _lowerCamelCase:
       @add_start_docstrings(__lowerCamelCase)
       def __call__(   self, lowerCamelCase, lowerCamelCase)			->  Dict:




           """simple docstring"""

           raise NotImplementedError(
               F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''')






class _lowerCamelCase:
       @add_start_docstrings(__lowerCamelCase)
       def __call__(   self, lowerCamelCase, lowerCamelCase)			->  Optional[Any]:




           """simple docstring"""

           raise NotImplementedError(
               F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''')






class _lowerCamelCase(		__snake_case  ):
       @add_start_docstrings(__lowerCamelCase)
       def __call__(   self, lowerCamelCase, lowerCamelCase, lowerCamelCase, **lowerCamelCase)			->  Dict:




           """simple docstring"""

           for processor in self:
               _lowercase			:				Dict 						=						inspect.signature(processor.__call__).parameters
               if len(__lowerCamelCase) > 3:
                   if not all(arg in kwargs for arg in list(function_args.keys())[2:]):
                       raise ValueError(
                           F'''Make sure that all the required parameters: {list(function_args.keys())} for '''
                           F'''{processor.__class__} are passed to the logits processor.''')
                   _lowercase			:				Optional[Any] 						=						processor(__lowerCamelCase, __lowerCamelCase, __lowerCamelCase, **__lowerCamelCase)
               else:
                   _lowercase			:				Tuple 						=						processor(__lowerCamelCase, __lowerCamelCase, __lowerCamelCase)
           return scores






class _lowerCamelCase(		__snake_case  ):
       def __init__(   self, lowerCamelCase)			->  Union[str, Any]:




           """simple docstring"""

           if not isinstance(__lowerCamelCase, __lowerCamelCase) or not (temperature > 0):
               raise ValueError(F'''`temperature` has to be a strictly positive float, but is {temperature}''')

           _lowercase			:				Optional[int] 						=						temperature




       def __call__(   self, lowerCamelCase, lowerCamelCase, lowerCamelCase)			->  List[Any]:




           """simple docstring"""

           _lowercase			:				Optional[int] 						=						scores / self.temperature
           return scores






class _lowerCamelCase(		__snake_case  ):
       def __init__(   self, lowerCamelCase, lowerCamelCase = -float('Inf'), lowerCamelCase = 1)			->  Any:




           """simple docstring"""

           if not isinstance(__lowerCamelCase, __lowerCamelCase) or (top_p < 0 or top_p > 1.0):
               raise ValueError(F'''`top_p` has to be a float > 0 and < 1, but is {top_p}''')
           if not isinstance(__lowerCamelCase, __lowerCamelCase) or (min_tokens_to_keep < 1):
               raise ValueError(F'''`min_tokens_to_keep` has to be a positive integer, but is {min_tokens_to_keep}''')

           _lowercase			:				Tuple 						=						top_p
           _lowercase			:				Optional[Any] 						=						filter_value
           _lowercase			:				List[str] 						=						min_tokens_to_keep




       def __call__(   self, lowerCamelCase, lowerCamelCase, lowerCamelCase)			->  List[Any]:




           """simple docstring"""

           _lowercase						,							_lowercase			:				str 						=						lax.top_k(__lowerCamelCase, scores.shape[-1])

           _lowercase			:				Optional[int] 						=						jnp.full_like(__lowerCamelCase, self.filter_value)
           _lowercase			:				List[str] 						=						jax.nn.softmax(__lowerCamelCase, axis=-1).cumsum(axis=-1)
           _lowercase			:				int 						=						cumulative_probs < self.top_p

           # include the token that is higher than top_p as well
           _lowercase			:				Any 						=						jnp.roll(__lowerCamelCase, 1)
           score_mask |= score_mask.at[:, 0].set(__lowerCamelCase)

           # min tokens to keep
           _lowercase			:				str 						=						score_mask.at[:, : self.min_tokens_to_keep].set(__lowerCamelCase)

           _lowercase			:				Optional[Any] 						=						jnp.where(__lowerCamelCase, __lowerCamelCase, __lowerCamelCase)
           _lowercase			:				Union[str, Any] 						=						jax.lax.sort_key_val(__lowerCamelCase, __lowerCamelCase)[-1]

           return next_scores






class _lowerCamelCase(		__snake_case  ):
       def __init__(   self, lowerCamelCase, lowerCamelCase = -float('Inf'), lowerCamelCase = 1)			->  Optional[int]:




           """simple docstring"""

           if not isinstance(__lowerCamelCase, __lowerCamelCase) or top_k <= 0:
               raise ValueError(F'''`top_k` has to be a strictly positive integer, but is {top_k}''')

           _lowercase			:				List[Any] 						=						max(__lowerCamelCase, __lowerCamelCase)
           _lowercase			:				Union[str, Any] 						=						filter_value




       def __call__(   self, lowerCamelCase, lowerCamelCase, lowerCamelCase)			->  Tuple:




           """simple docstring"""

           _lowercase						,							_lowercase			:				List[Any] 						=						scores.shape
           _lowercase			:				Dict 						=						jnp.full(batch_size * vocab_size, self.filter_value)

           _lowercase			:				Optional[Any] 						=						min(self.top_k, scores.shape[-1])  # Safety check
           _lowercase						,							_lowercase			:				List[Any] 						=						lax.top_k(__lowerCamelCase, __lowerCamelCase)
           _lowercase			:				List[str] 						=						jnp.broadcast_to((jnp.arange(__lowerCamelCase) * vocab_size)[:, None], (batch_size, topk)).flatten()
           _lowercase			:				Any 						=						topk_scores.flatten()
           _lowercase			:				str 						=						topk_indices.flatten() + shift

           _lowercase			:				Optional[int] 						=						next_scores_flat.at[topk_indices_flat].set(__lowerCamelCase)
           _lowercase			:				Optional[Any] 						=						next_scores_flat.reshape(__lowerCamelCase, __lowerCamelCase)
           return next_scores






class _lowerCamelCase(		__snake_case  ):
       def __init__(   self, lowerCamelCase)			->  Optional[Any]:




           """simple docstring"""

           _lowercase			:				Tuple 						=						bos_token_id




       def __call__(   self, lowerCamelCase, lowerCamelCase, lowerCamelCase)			->  Any:




           """simple docstring"""

           _lowercase			:				Union[str, Any] 						=						jnp.full(scores.shape, -float('inf'))

           _lowercase			:				List[Any] 						=						1 - jnp.bool_(cur_len - 1)

           _lowercase			:				str 						=						jnp.where(__lowerCamelCase, new_scores.at[:, self.bos_token_id].set(0), __lowerCamelCase)

           return scores






class _lowerCamelCase(		__snake_case  ):
       def __init__(   self, lowerCamelCase, lowerCamelCase)			->  Optional[int]:




           """simple docstring"""

           _lowercase			:				Dict 						=						max_length
           _lowercase			:				Any 						=						eos_token_id




       def __call__(   self, lowerCamelCase, lowerCamelCase, lowerCamelCase)			->  str:




           """simple docstring"""

           _lowercase			:				int 						=						jnp.full(scores.shape, -float('inf'))

           _lowercase			:				Union[str, Any] 						=						1 - jnp.bool_(cur_len - self.max_length + 1)

           _lowercase			:				str 						=						jnp.where(__lowerCamelCase, new_scores.at[:, self.eos_token_id].set(0), __lowerCamelCase)

           return scores






class _lowerCamelCase(		__snake_case  ):
       def __init__(   self, lowerCamelCase, lowerCamelCase)			->  List[Any]:




           """simple docstring"""

           if not isinstance(__lowerCamelCase, __lowerCamelCase) or min_length < 0:
               raise ValueError(F'''`min_length` has to be a positive integer, but is {min_length}''')

           if not isinstance(__lowerCamelCase, __lowerCamelCase) or eos_token_id < 0:
               raise ValueError(F'''`eos_token_id` has to be a positive integer, but is {eos_token_id}''')

           _lowercase			:				Union[str, Any] 						=						min_length
           _lowercase			:				Tuple 						=						eos_token_id




       def __call__(   self, lowerCamelCase, lowerCamelCase, lowerCamelCase)			->  int:




           """simple docstring"""

           _lowercase			:				Any 						=						1 - jnp.clip(cur_len - self.min_length, 0, 1)

           _lowercase			:				Dict 						=						jnp.where(__lowerCamelCase, scores.at[:, self.eos_token_id].set(-float('inf')), __lowerCamelCase)

           return scores






class _lowerCamelCase(		__snake_case  ):
       def __init__(   self, lowerCamelCase, lowerCamelCase)			->  Optional[Any]:




           """simple docstring"""

           _lowercase			:				Any 						=						list(__lowerCamelCase)
           _lowercase			:				Optional[int] 						=						begin_index




       def __call__(   self, lowerCamelCase, lowerCamelCase, lowerCamelCase)			->  str:




           """simple docstring"""

           _lowercase			:				Optional[int] 						=						1 - jnp.bool_(cur_len - self.begin_index)

           _lowercase			:				Any 						=						jnp.where(__lowerCamelCase, scores.at[:, self.begin_suppress_tokens].set(-float('inf')), __lowerCamelCase)

           return scores






class _lowerCamelCase(		__snake_case  ):
       def __init__(   self, lowerCamelCase)			->  List[Any]:




           """simple docstring"""

           _lowercase			:				Optional[int] 						=						list(__lowerCamelCase)




       def __call__(   self, lowerCamelCase, lowerCamelCase, lowerCamelCase)			->  Optional[Any]:




           """simple docstring"""

           _lowercase			:				Dict 						=						scores.at[..., self.suppress_tokens].set(-float('inf'))

           return scores






class _lowerCamelCase(		__snake_case  ):
       def __init__(   self, lowerCamelCase)			->  Dict:




           """simple docstring"""

           _lowercase			:				Optional[int] 						=						dict(__lowerCamelCase)
           # Converts the dictionary of format {index: token} containing the tokens to be forced to an array, where the
           # index of the array corresponds to the index of the token to be forced, for XLA compatibility.
           # Indexes without forced tokens will have a negative value.
           _lowercase			:				Dict 						=						jnp.ones((max(force_token_map.keys()) + 1), dtype=jnp.intaa) * -1
           for index, token in force_token_map.items():
               if token is not None:
                   _lowercase			:				Optional[int] 						=						force_token_array.at[index].set(__lowerCamelCase)
           _lowercase			:				List[str] 						=						jnp.intaa(__lowerCamelCase)




       def __call__(   self, lowerCamelCase, lowerCamelCase, lowerCamelCase)			->  Tuple:




           """simple docstring"""

           def _force_token(lowerCamelCase):
               _lowercase			:				Optional[int] 						=						scores.shape[0]
               _lowercase			:				str 						=						self.force_token_array[generation_idx]

               _lowercase			:				Optional[int] 						=						jnp.ones_like(__lowerCamelCase, dtype=scores.dtype) * -float('inf')
               _lowercase			:				str 						=						jnp.zeros((batch_size, 1), dtype=scores.dtype)
               _lowercase			:				Optional[Any] 						=						lax.dynamic_update_slice(__lowerCamelCase, __lowerCamelCase, (0, current_token))
               return new_scores

           _lowercase			:				Tuple 						=						lax.cond(
               cur_len >= self.force_token_array.shape[0], lambda: scores, lambda: lax.cond(
                   self.force_token_array[cur_len] >= 0, lambda: _force_token(__lowerCamelCase), lambda: scores, ), )
           return scores






class _lowerCamelCase(		__snake_case  ):
       def __init__(   self, lowerCamelCase, lowerCamelCase, lowerCamelCase)			->  Optional[Any]:




           """simple docstring"""

           _lowercase			:				Any 						=						generate_config.eos_token_id
           _lowercase			:				List[str] 						=						generate_config.no_timestamps_token_id
           _lowercase			:				List[Any] 						=						generate_config.no_timestamps_token_id + 1

           _lowercase			:				List[str] 						=						decoder_input_length + 1

           if generate_config.is_multilingual:
               # room for language token and task token
               self.begin_index += 2
           if hasattr(__lowerCamelCase, 'max_initial_timestamp_index'):
               _lowercase			:				List[str] 						=						generate_config.max_initial_timestamp_index
           else:
               _lowercase			:				Optional[int] 						=						model_config.vocab_size
           if self.max_initial_timestamp_index is None:
               _lowercase			:				Optional[Any] 						=						model_config.vocab_size




       def __call__(   self, lowerCamelCase, lowerCamelCase, lowerCamelCase)			->  str:




           """simple docstring"""

           _lowercase			:				Union[str, Any] 						=						scores.at[:, self.no_timestamps_token_id].set(-float('inf'))

           def handle_pairs(lowerCamelCase, lowerCamelCase):
               _lowercase			:				Optional[int] 						=						jnp.where((cur_len - self.begin_index) >= 1, __lowerCamelCase, __lowerCamelCase)
               _lowercase			:				Union[str, Any] 						=						jnp.where(
                   input_ids_k[cur_len - 1] >= self.timestamp_begin, True and last_was_timestamp, __lowerCamelCase, )

               _lowercase			:				List[Any] 						=						jnp.where((cur_len - self.begin_index) < 2, __lowerCamelCase, __lowerCamelCase)
               _lowercase			:				Union[str, Any] 						=						jnp.where(
                   input_ids_k[cur_len - 2] >= self.timestamp_begin, __lowerCamelCase, __lowerCamelCase, )

               return jnp.where(
                   __lowerCamelCase, jnp.where(
                       penultimate_was_timestamp > 0, scores_k.at[self.timestamp_begin :].set(-float('inf')), scores_k.at[: self.eos_token_id].set(-float('inf')), ), __lowerCamelCase, )

           _lowercase			:				Optional[Any] 						=						jax.vmap(__lowerCamelCase)(__lowerCamelCase, __lowerCamelCase)

           _lowercase			:				Optional[int] 						=						jnp.where(cur_len == self.begin_index, __lowerCamelCase, __lowerCamelCase)
           _lowercase			:				List[str] 						=						jnp.where(
               self.max_initial_timestamp_index is not None, True and apply_max_initial_timestamp, __lowerCamelCase, )

           _lowercase			:				List[str] 						=						self.timestamp_begin + self.max_initial_timestamp_index

           _lowercase			:				List[Any] 						=						jnp.where(
               __lowerCamelCase, scores.at[:, last_allowed + 1 :].set(-float('inf')), __lowerCamelCase, )

           # if sum of probability over timestamps is above any other token, sample timestamp
           _lowercase			:				Dict 						=						jax.nn.log_softmax(__lowerCamelCase, axis=-1)

           def handle_cumulative_probs(lowerCamelCase, lowerCamelCase):
               _lowercase			:				Any 						=						jax.nn.logsumexp(logprobs_k[self.timestamp_begin :], axis=-1)
               _lowercase			:				List[Any] 						=						jnp.max(logprobs_k[: self.timestamp_begin])
               return jnp.where(
                   timestamp_logprob > max_text_token_logprob, scores_k.at[: self.timestamp_begin].set(-float('inf')), __lowerCamelCase, )

           _lowercase			:				Tuple 						=						jax.vmap(__lowerCamelCase)(__lowerCamelCase, __lowerCamelCase)

           return scores





from dataclasses import dataclass, field
from typing import Tuple

from ..utils import cached_property, is_tf_available, logging, requires_backends
from .benchmark_args_utils import BenchmarkArguments


if is_tf_available():
    import tensorflow as tf


__A			:					Dict						=			logging.get_logger(__name__)





@dataclass
class 			_SCREAMING_SNAKE_CASE (   __snake_case		):







   '''simple docstring'''




   lowerCamelCase__				=      [
       "no_inference",
       "no_cuda",
       "no_tpu",
       "no_speed",
       "no_memory",
       "no_env_print",
       "no_multi_process",
   ]





   def __init__(       self					:			List[Any]     , **__lowerCamelCase					:			Any			):
       for deprecated_arg in self.deprecated_args:
           if deprecated_arg in kwargs:
               SCREAMING_SNAKE_CASE										=   deprecated_arg[3:]
               SCREAMING_SNAKE_CASE										=   not kwargs.pop(__lowerCamelCase			)
               logger.warning(
                   f"{deprecated_arg} is depreciated. Please use --no-{positive_arg} or"
                   f" {positive_arg}={kwargs[positive_arg]}"			)
       SCREAMING_SNAKE_CASE										=   kwargs.pop("tpu_name"     , self.tpu_name			)
       SCREAMING_SNAKE_CASE										=   kwargs.pop("device_idx"     , self.device_idx			)
       SCREAMING_SNAKE_CASE										=   kwargs.pop("eager_mode"     , self.eager_mode			)
       SCREAMING_SNAKE_CASE										=   kwargs.pop("use_xla"     , self.use_xla			)
       super().__init__(**__lowerCamelCase			)

   lowerCamelCase__				=      field(
       default=__snake_case					,       metadata={"help": "Name of TPU"}					,       )
   lowerCamelCase__				=      field(
       default=0					,       metadata={"help": "CPU / GPU device index. Defaults to 0."}					,       )
   lowerCamelCase__				=      field(default=__snake_case					,       metadata={"help": "Benchmark models in eager model."}		)
   lowerCamelCase__				=      field(
       default=__snake_case					,       metadata={
           "help": "Benchmark models using XLA JIT compilation. Note that `eager_model` has to be set to `False`."
       }					,       )





   @cached_property
   def      _snake_case		(       self					:			Optional[int]			):
       requires_backends(self     , ["tf"]			)
       SCREAMING_SNAKE_CASE										=   None
       if self.tpu:
           try:
               if self.tpu_name:
                   SCREAMING_SNAKE_CASE										=   tf.distribute.cluster_resolver.TPUClusterResolver(self.tpu_name			)
               else:
                   SCREAMING_SNAKE_CASE										=   tf.distribute.cluster_resolver.TPUClusterResolver()
           except ValueError:
               SCREAMING_SNAKE_CASE										=   None
       return tpu





   @cached_property
   def      _snake_case		(       self					:			Any			):
       requires_backends(self     , ["tf"]			)
       if self.is_tpu:
           tf.config.experimental_connect_to_cluster(self._setup_tpu			)
           tf.tpu.experimental.initialize_tpu_system(self._setup_tpu			)

           SCREAMING_SNAKE_CASE										=   tf.distribute.TPUStrategy(self._setup_tpu			)
       else:
           # currently no multi gpu is allowed
           if self.is_gpu:
               # TODO: Currently only single GPU is supported
               tf.config.set_visible_devices(self.gpu_list[self.device_idx]     , "GPU"			)
               SCREAMING_SNAKE_CASE										=   tf.distribute.OneDeviceStrategy(device=f"/gpu:{self.device_idx}"			)
           else:
               tf.config.set_visible_devices([]     , "GPU"			)  # disable GPU
               SCREAMING_SNAKE_CASE										=   tf.distribute.OneDeviceStrategy(device=f"/cpu:{self.device_idx}"			)

       return strategy





   @property
   def      _snake_case		(       self					:			Any			):
       requires_backends(self     , ["tf"]			)
       return self._setup_tpu is not None





   @property
   def      _snake_case		(       self					:			Optional[Any]			):
       requires_backends(self     , ["tf"]			)
       return self._setup_strategy





   @property
   def      _snake_case		(       self					:			List[str]			):
       requires_backends(self     , ["tf"]			)
       return tf.config.list_physical_devices("GPU"			)





   @property
   def      _snake_case		(       self					:			Any			):
       requires_backends(self     , ["tf"]			)
       if self.cuda:
           return len(self.gpu_list			)
       return 0





   @property
   def      _snake_case		(       self					:			Dict			):
       return self.n_gpu > 0