


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 :   Any							      =				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) ->     jnp.ndarray:




           """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) ->     jnp.ndarray:




           """simple docstring"""

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






class _lowerCamelCase(		_a     ):
       @add_start_docstrings(lowerCamelCase)
       def __call__(      self,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase,   **lowerCamelCase) ->     jnp.ndarray:




           """simple docstring"""

           for processor in self:
               _lowercase :							List[Any]   	=	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 :							int   	=	processor(lowerCamelCase,   lowerCamelCase,   lowerCamelCase,   **lowerCamelCase)
               else:
                   _lowercase :							int   	=	processor(lowerCamelCase,   lowerCamelCase,   lowerCamelCase)
           return scores






class _lowerCamelCase(		_a     ):
       def __init__(      self,   lowerCamelCase) ->     List[str]:




           """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[Any]   	=	temperature




       def __call__(      self,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase) ->     jnp.ndarray:




           """simple docstring"""

           _lowercase :							Union[str, Any]   	=	scores / self.temperature
           return scores






class _lowerCamelCase(		_a     ):
       def __init__(      self,   lowerCamelCase,   lowerCamelCase = -float('Inf'),   lowerCamelCase = 1) ->     Optional[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 :							str   	=	top_p
           _lowercase :							Dict   	=	filter_value
           _lowercase :							Union[str, Any]   	=	min_tokens_to_keep




       def __call__(      self,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase) ->     jnp.ndarray:




           """simple docstring"""

           _lowercase	,       _lowercase :							Dict   	=	lax.top_k(lowerCamelCase,   scores.shape[-1])

           _lowercase :							Tuple   	=	jnp.full_like(lowerCamelCase,   self.filter_value)
           _lowercase :							Any   	=	jax.nn.softmax(lowerCamelCase,   axis=-1).cumsum(axis=-1)
           _lowercase :							Dict   	=	cumulative_probs < self.top_p

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

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

           _lowercase :							List[str]   	=	jnp.where(lowerCamelCase,   lowerCamelCase,   lowerCamelCase)
           _lowercase :							Optional[int]   	=	jax.lax.sort_key_val(lowerCamelCase,   lowerCamelCase)[-1]

           return next_scores






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




           """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 :							Any   	=	max(lowerCamelCase,   lowerCamelCase)
           _lowercase :							str   	=	filter_value




       def __call__(      self,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase) ->     jnp.ndarray:




           """simple docstring"""

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

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

           _lowercase :							Union[str, Any]   	=	next_scores_flat.at[topk_indices_flat].set(lowerCamelCase)
           _lowercase :							List[str]   	=	next_scores_flat.reshape(lowerCamelCase,   lowerCamelCase)
           return next_scores






class _lowerCamelCase(		_a     ):
       def __init__(      self,   lowerCamelCase) ->     List[str]:




           """simple docstring"""

           _lowercase :							Any   	=	bos_token_id




       def __call__(      self,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase) ->     jnp.ndarray:




           """simple docstring"""

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

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

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

           return scores






class _lowerCamelCase(		_a     ):
       def __init__(      self,   lowerCamelCase,   lowerCamelCase) ->     int:




           """simple docstring"""

           _lowercase :							Any   	=	max_length
           _lowercase :							Union[str, Any]   	=	eos_token_id




       def __call__(      self,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase) ->     jnp.ndarray:




           """simple docstring"""

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

           _lowercase :							int   	=	1 - jnp.bool_(cur_len - self.max_length + 1)

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

           return scores






class _lowerCamelCase(		_a     ):
       def __init__(      self,   lowerCamelCase,   lowerCamelCase) ->     Union[str, 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 :							str   	=	min_length
           _lowercase :							Any   	=	eos_token_id




       def __call__(      self,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase) ->     jnp.ndarray:




           """simple docstring"""

           _lowercase :							List[str]   	=	1 - jnp.clip(cur_len - self.min_length,   0,   1)

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

           return scores






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




           """simple docstring"""

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




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




           """simple docstring"""

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

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

           return scores






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




           """simple docstring"""

           _lowercase :							Optional[int]   	=	list(lowerCamelCase)




       def __call__(      self,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase) ->     jnp.ndarray:




           """simple docstring"""

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

           return scores






class _lowerCamelCase(		_a     ):
       def __init__(      self,   lowerCamelCase) ->     str:




           """simple docstring"""

           _lowercase :							Union[str, Any]   	=	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 :							Optional[int]   	=	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 :							Tuple   	=	force_token_array.at[index].set(lowerCamelCase)
           _lowercase :							Tuple   	=	jnp.intaa(lowerCamelCase)




       def __call__(      self,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase) ->     jnp.ndarray:




           """simple docstring"""

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

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

           _lowercase :							Any   	=	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(		_a     ):
       def __init__(      self,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase) ->     Any:




           """simple docstring"""

           _lowercase :							Tuple   	=	generate_config.eos_token_id
           _lowercase :							str   	=	generate_config.no_timestamps_token_id
           _lowercase :							Dict   	=	generate_config.no_timestamps_token_id + 1

           _lowercase :							Tuple   	=	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 :							Optional[int]   	=	generate_config.max_initial_timestamp_index
           else:
               _lowercase :							Any   	=	model_config.vocab_size
           if self.max_initial_timestamp_index is None:
               _lowercase :							Dict   	=	model_config.vocab_size




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




           """simple docstring"""

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

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

               _lowercase :							Optional[int]   	=	jnp.where((cur_len - self.begin_index) < 2,   lowerCamelCase,   lowerCamelCase)
               _lowercase :							Tuple   	=	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 :							List[Any]   	=	jax.vmap(lowerCamelCase)(lowerCamelCase,   lowerCamelCase)

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

           _lowercase :							Union[str, Any]   	=	self.timestamp_begin + self.max_initial_timestamp_index

           _lowercase :							Union[str, 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 :							List[Any]   	=	jax.nn.log_softmax(lowerCamelCase,   axis=-1)

           def handle_cumulative_probs(lowerCamelCase,   lowerCamelCase):
               _lowercase :							List[Any]   	=	jax.nn.logsumexp(logprobs_k[self.timestamp_begin :],   axis=-1)
               _lowercase :							int   	=	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 :							Any   	=	jax.vmap(lowerCamelCase)(lowerCamelCase,   lowerCamelCase)

           return scores






from typing import Dict

from .base import GenericTensor, Pipeline






class _lowerCamelCase(		_a     ):
       def     UpperCamelCase  (      self,   lowerCamelCase=None,   lowerCamelCase=None,   lowerCamelCase=None,   **lowerCamelCase) ->     int:




           """simple docstring"""

           if tokenize_kwargs is None:
               _lowercase :							Any   	=	{}

           if truncation is not None:
               if "truncation" in tokenize_kwargs:
                   raise ValueError(
                       'truncation parameter defined twice (given as keyword argument as well as in tokenize_kwargs)')
               _lowercase :							List[Any]   	=	truncation

           _lowercase :							Optional[Any]   	=	tokenize_kwargs

           _lowercase :							Tuple   	=	{}
           if return_tensors is not None:
               _lowercase :							Union[str, Any]   	=	return_tensors

           return preprocess_params, {}, postprocess_params
       def     UpperCamelCase  (      self,   lowerCamelCase,   **lowerCamelCase) ->     Dict[str, GenericTensor]:




           """simple docstring"""

           _lowercase :							Optional[Any]   	=	self.framework
           _lowercase :							Dict   	=	self.tokenizer(lowerCamelCase,   return_tensors=lowerCamelCase,   **lowerCamelCase)
           return model_inputs
       def     UpperCamelCase  (      self,   lowerCamelCase) ->     Optional[Any]:




           """simple docstring"""

           _lowercase :							str   	=	self.model(**lowerCamelCase)
           return model_outputs
       def     UpperCamelCase  (      self,   lowerCamelCase,   lowerCamelCase=False) ->     Dict:




           """simple docstring"""

           if return_tensors:
               return model_outputs[0]
           if self.framework == "pt":
               return model_outputs[0].tolist()
           elif self.framework == "tf":
               return model_outputs[0].numpy().tolist()




       def __call__(      self,   *lowerCamelCase,   **lowerCamelCase) ->     Union[str, Any]:




           """simple docstring"""

           return super().__call__(*lowerCamelCase,   **lowerCamelCase)


