
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__							=				get_logger(__name__)


SCREAMING_SNAKE_CASE__							=				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 	A__   :





							@add_start_docstrings(snake_case_				)
							def __call__( self  :   int     , _UpperCAmelCase  :   Tuple     , _UpperCAmelCase  :   Dict				)						->		Dict:



											"""simple docstring"""


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






class 	A__   :





							@add_start_docstrings(snake_case_				)
							def __call__( self  :   Union[str, Any]     , _UpperCAmelCase  :   List[Any]     , _UpperCAmelCase  :   List[Any]				)						->		Tuple:



											"""simple docstring"""


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






class 	A__   (						UpperCAmelCase__				):





							@add_start_docstrings(snake_case_				)
							def __call__( self  :   Any     , _UpperCAmelCase  :   Optional[int]     , _UpperCAmelCase  :   Optional[int]     , _UpperCAmelCase  :   List[str]     , **_UpperCAmelCase  :   Union[str, Any]				)						->		int:



											"""simple docstring"""


											for processor in self:
															__lowercase								=					inspect.signature(processor.__call__				).parameters
															if len(snake_case_				) > 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								=					processor(snake_case_     , snake_case_     , snake_case_     , **snake_case_				)
															else:
																			__lowercase								=					processor(snake_case_     , snake_case_     , snake_case_				)
											return scores






class 	A__   (						UpperCAmelCase__				):





							def __init__( self  :   Optional[Any]     , _UpperCAmelCase  :   List[Any]				)						->		List[str]:



											"""simple docstring"""


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

											__lowercase								=					temperature





							def __call__( self  :   Any     , _UpperCAmelCase  :   Dict     , _UpperCAmelCase  :   Union[str, Any]     , _UpperCAmelCase  :   Dict				)						->		str:



											"""simple docstring"""


											__lowercase								=					scores / self.temperature
											return scores






class 	A__   (						UpperCAmelCase__				):





							def __init__( self  :   int     , _UpperCAmelCase  :   Optional[int]     , _UpperCAmelCase  :   List[str] = -float('Inf'				)     , _UpperCAmelCase  :   Dict = 1				)						->		int:



											"""simple docstring"""


											if not isinstance(snake_case_     , snake_case_				) 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(snake_case_     , snake_case_				) 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								=					top_p
											__lowercase								=					filter_value
											__lowercase								=					min_tokens_to_keep





							def __call__( self  :   Any     , _UpperCAmelCase  :   Dict     , _UpperCAmelCase  :   int     , _UpperCAmelCase  :   Union[str, Any]				)						->		Optional[Any]:



											"""simple docstring"""


											__lowercase								=					lax.top_k(snake_case_     , scores.shape[-1]				)

											__lowercase								=					jnp.full_like(snake_case_     , self.filter_value				)
											__lowercase								=					jax.nn.softmax(snake_case_     , axis=-1				).cumsum(axis=-1				)
											__lowercase								=					cumulative_probs < self.top_p

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

											# min tokens to keep
											__lowercase								=					score_mask.at[:, : self.min_tokens_to_keep].set(snake_case_				)

											__lowercase								=					jnp.where(snake_case_     , snake_case_     , snake_case_				)
											__lowercase								=					jax.lax.sort_key_val(snake_case_     , snake_case_				)[-1]

											return next_scores






class 	A__   (						UpperCAmelCase__				):





							def __init__( self  :   Union[str, Any]     , _UpperCAmelCase  :   Optional[int]     , _UpperCAmelCase  :   Any = -float('Inf'				)     , _UpperCAmelCase  :   Optional[Any] = 1				)						->		Any:



											"""simple docstring"""


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

											__lowercase								=					max(snake_case_     , snake_case_				)
											__lowercase								=					filter_value





							def __call__( self  :   List[str]     , _UpperCAmelCase  :   Any     , _UpperCAmelCase  :   Tuple     , _UpperCAmelCase  :   Any				)						->		int:



											"""simple docstring"""


											__lowercase								=					scores.shape
											__lowercase								=					jnp.full(batch_size * vocab_size     , self.filter_value				)

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

											__lowercase								=					next_scores_flat.at[topk_indices_flat].set(snake_case_				)
											__lowercase								=					next_scores_flat.reshape(snake_case_     , snake_case_				)
											return next_scores






class 	A__   (						UpperCAmelCase__				):





							def __init__( self  :   Tuple     , _UpperCAmelCase  :   Tuple				)						->		Optional[Any]:



											"""simple docstring"""


											__lowercase								=					bos_token_id





							def __call__( self  :   Tuple     , _UpperCAmelCase  :   List[str]     , _UpperCAmelCase  :   Tuple     , _UpperCAmelCase  :   Optional[int]				)						->		int:



											"""simple docstring"""


											__lowercase								=					jnp.full(scores.shape     , -float('inf'				)				)

											__lowercase								=					1 - jnp.bool_(cur_len - 1				)

											__lowercase								=					jnp.where(snake_case_     , new_scores.at[:, self.bos_token_id].set(0				)     , snake_case_				)

											return scores






class 	A__   (						UpperCAmelCase__				):





							def __init__( self  :   int     , _UpperCAmelCase  :   List[Any]     , _UpperCAmelCase  :   str				)						->		str:



											"""simple docstring"""


											__lowercase								=					max_length
											__lowercase								=					eos_token_id





							def __call__( self  :   List[str]     , _UpperCAmelCase  :   List[Any]     , _UpperCAmelCase  :   List[Any]     , _UpperCAmelCase  :   Tuple				)						->		List[str]:



											"""simple docstring"""


											__lowercase								=					jnp.full(scores.shape     , -float('inf'				)				)

											__lowercase								=					1 - jnp.bool_(cur_len - self.max_length + 1				)

											__lowercase								=					jnp.where(snake_case_     , new_scores.at[:, self.eos_token_id].set(0				)     , snake_case_				)

											return scores






class 	A__   (						UpperCAmelCase__				):





							def __init__( self  :   Tuple     , _UpperCAmelCase  :   Any     , _UpperCAmelCase  :   Tuple				)						->		Optional[int]:



											"""simple docstring"""


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

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

											__lowercase								=					min_length
											__lowercase								=					eos_token_id





							def __call__( self  :   int     , _UpperCAmelCase  :   Tuple     , _UpperCAmelCase  :   List[Any]     , _UpperCAmelCase  :   Union[str, Any]				)						->		Any:



											"""simple docstring"""


											__lowercase								=					1 - jnp.clip(cur_len - self.min_length     , 0     , 1				)

											__lowercase								=					jnp.where(snake_case_     , scores.at[:, self.eos_token_id].set(-float('inf'				)				)     , snake_case_				)

											return scores






class 	A__   (						UpperCAmelCase__				):





							def __init__( self  :   List[str]     , _UpperCAmelCase  :   List[Any]     , _UpperCAmelCase  :   Any				)						->		Tuple:



											"""simple docstring"""


											__lowercase								=					list(snake_case_				)
											__lowercase								=					begin_index





							def __call__( self  :   Any     , _UpperCAmelCase  :   Any     , _UpperCAmelCase  :   int     , _UpperCAmelCase  :   Dict				)						->		Tuple:



											"""simple docstring"""


											__lowercase								=					1 - jnp.bool_(cur_len - self.begin_index				)

											__lowercase								=					jnp.where(snake_case_     , scores.at[:, self.begin_suppress_tokens].set(-float('inf'				)				)     , snake_case_				)

											return scores






class 	A__   (						UpperCAmelCase__				):





							def __init__( self  :   List[str]     , _UpperCAmelCase  :   Tuple				)						->		Optional[int]:



											"""simple docstring"""


											__lowercase								=					list(snake_case_				)





							def __call__( self  :   Optional[Any]     , _UpperCAmelCase  :   List[Any]     , _UpperCAmelCase  :   Optional[Any]     , _UpperCAmelCase  :   List[str]				)						->		List[str]:



											"""simple docstring"""


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

											return scores






class 	A__   (						UpperCAmelCase__				):





							def __init__( self  :   Any     , _UpperCAmelCase  :   List[Any]				)						->		Dict:



											"""simple docstring"""


											__lowercase								=					dict(snake_case_				)
											# 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								=					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								=					force_token_array.at[index].set(snake_case_				)
											__lowercase								=					jnp.intaa(snake_case_				)





							def __call__( self  :   List[str]     , _UpperCAmelCase  :   Dict     , _UpperCAmelCase  :   Any     , _UpperCAmelCase  :   Any				)						->		Optional[int]:



											"""simple docstring"""


											def _force_token(_UpperCAmelCase  :   Any				):
															__lowercase								=					scores.shape[0]
															__lowercase								=					self.force_token_array[generation_idx]

															__lowercase								=					jnp.ones_like(snake_case_     , dtype=scores.dtype				) * -float('inf'				)
															__lowercase								=					jnp.zeros((batch_size, 1)     , dtype=scores.dtype				)
															__lowercase								=					lax.dynamic_update_slice(snake_case_     , snake_case_     , (0, current_token)				)
															return new_scores

											__lowercase								=					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(snake_case_				)     , lambda: scores     , )     , )
											return scores






class 	A__   (						UpperCAmelCase__				):





							def __init__( self  :   Dict     , _UpperCAmelCase  :   Any     , _UpperCAmelCase  :   List[Any]     , _UpperCAmelCase  :   Any				)						->		int:



											"""simple docstring"""


											__lowercase								=					generate_config.eos_token_id
											__lowercase								=					generate_config.no_timestamps_token_id
											__lowercase								=					generate_config.no_timestamps_token_id + 1

											__lowercase								=					decoder_input_length + 1

											if generate_config.is_multilingual:
															# room for language token and task token
															self.begin_index += 2
											if hasattr(snake_case_     , 'max_initial_timestamp_index'				):
															__lowercase								=					generate_config.max_initial_timestamp_index
											else:
															__lowercase								=					model_config.vocab_size
											if self.max_initial_timestamp_index is None:
															__lowercase								=					model_config.vocab_size





							def __call__( self  :   List[Any]     , _UpperCAmelCase  :   Any     , _UpperCAmelCase  :   Tuple     , _UpperCAmelCase  :   List[str]				)						->		Optional[int]:



											"""simple docstring"""


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

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

															__lowercase								=					jnp.where((cur_len - self.begin_index) < 2     , snake_case_     , snake_case_				)
															__lowercase								=					jnp.where(
															    input_ids_k[cur_len - 2] >= self.timestamp_begin     , snake_case_     , snake_case_     , )

															return jnp.where(
															    snake_case_     , 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'				)				)     , )     , snake_case_     , )

											__lowercase								=					jax.vmap(snake_case_				)(snake_case_     , snake_case_				)

											__lowercase								=					jnp.where(cur_len == self.begin_index     , snake_case_     , snake_case_				)
											__lowercase								=					jnp.where(
											    self.max_initial_timestamp_index is not None     , True and apply_max_initial_timestamp     , snake_case_     , )

											__lowercase								=					self.timestamp_begin + self.max_initial_timestamp_index

											__lowercase								=					jnp.where(
											    snake_case_     , scores.at[:, last_allowed + 1 :].set(-float('inf'				)				)     , snake_case_     , )

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

											def handle_cumulative_probs(_UpperCAmelCase  :   Any     , _UpperCAmelCase  :   List[Any]				):
															__lowercase								=					jax.nn.logsumexp(logprobs_k[self.timestamp_begin :]     , axis=-1				)
															__lowercase								=					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'				)				)     , snake_case_     , )

											__lowercase								=					jax.vmap(snake_case_				)(snake_case_     , snake_case_				)

											return scores












"""simple docstring"""




from typing import Dict

import numpy as np

from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging
from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline, PipelineException


if is_tf_available():
   import tensorflow as tf

   from ..tf_utils import stable_softmax


if is_torch_available():
   import torch


lowerCamelCase_     :						str						=					logging.get_logger(__name__)

@add_end_docstrings(
    UpperCAmelCase__			,   r"""
        top_k (`int`, defaults to 5):
            The number of predictions to return.
        targets (`str` or `List[str]`, *optional*):
            When passed, the model will limit the scores to the passed targets instead of looking up in the whole
            vocab. If the provided targets are not in the model vocab, they will be tokenized and the first resulting
            token will be used (with a warning, and that might be slower).

    """			,   )
class  _UpperCAmelCase  (   UpperCAmelCase__		):



      '''simple docstring'''

      def 					lowerCamelCase_			(     self					,      snake_case_  ):

        """simple docstring"""

        if self.framework == "tf":
          A_  :       str										=  tf.where(input_ids == self.tokenizer.mask_token_id  ).numpy()
        elif self.framework == "pt":
          A_  :       List[str]										=  torch.nonzero(input_ids == self.tokenizer.mask_token_id					,      as_tuple=snake_case_  )
        else:
          raise ValueError('Unsupported framework'  )
        return masked_index

      def 					lowerCamelCase_			(     self					,      snake_case_  ):

        """simple docstring"""

        A_  :       List[str]										=  self.get_masked_index(snake_case_  )
        A_  :       str										=  np.prod(masked_index.shape  )
        if numel < 1:
          raise PipelineException(
              'fill-mask'					,      self.model.base_model_prefix					,      F"""No mask_token ({self.tokenizer.mask_token}) found on the input"""					,      )

      def 					lowerCamelCase_			(     self					,      snake_case_  ):

        """simple docstring"""

        if isinstance(snake_case_					,      snake_case_  ):
          for model_input in model_inputs:
            self._ensure_exactly_one_mask_token(model_input['input_ids'][0]  )
        else:
          for input_ids in model_inputs["input_ids"]:
            self._ensure_exactly_one_mask_token(snake_case_  )

      def 					lowerCamelCase_			(     self					,      snake_case_					,      snake_case_=None					,      **snake_case_  ):

        """simple docstring"""

        if return_tensors is None:
          A_  :       Any										=  self.framework
        A_  :       Dict										=  self.tokenizer(snake_case_					,      return_tensors=snake_case_  )
        self.ensure_exactly_one_mask_token(snake_case_  )
        return model_inputs

      def 					lowerCamelCase_			(     self					,      snake_case_  ):

        """simple docstring"""

        A_  :       Dict										=  self.model(**snake_case_  )
        A_  :       Optional[int]										=  model_inputs['input_ids']
        return model_outputs

      def 					lowerCamelCase_			(     self					,      snake_case_					,      snake_case_=5					,      snake_case_=None  ):

        """simple docstring"""

        if target_ids is not None and target_ids.shape[0] < top_k:
          A_  :       str										=  target_ids.shape[0]
        A_  :       Optional[Any]										=  model_outputs['input_ids'][0]
        A_  :       List[Any]										=  model_outputs['logits']

        if self.framework == "tf":
          A_  :       List[str]										=  tf.where(input_ids == self.tokenizer.mask_token_id  ).numpy()[:, 0]

          A_  :       Union[str, Any]										=  outputs.numpy()

          A_  :       Optional[int]										=  outputs[0, masked_index, :]
          A_  :       Optional[Any]										=  stable_softmax(snake_case_					,      axis=-1  )
          if target_ids is not None:
            A_  :       Union[str, Any]										=  tf.gather_nd(tf.squeeze(snake_case_					,      0  )					,      target_ids.reshape(-1					,      1  )  )
            A_  :       Optional[int]										=  tf.expand_dims(snake_case_					,      0  )

          A_  :       Any										=  tf.math.top_k(snake_case_					,      k=snake_case_  )
          A_						,       A_  :       str										=  topk.values.numpy(), topk.indices.numpy()
        else:
          A_  :       int										=  torch.nonzero(input_ids == self.tokenizer.mask_token_id					,      as_tuple=snake_case_  ).squeeze(-1  )
          # Fill mask pipeline supports only one ${mask_token} per sample

          A_  :       Tuple										=  outputs[0, masked_index, :]
          A_  :       List[str]										=  logits.softmax(dim=-1  )
          if target_ids is not None:
            A_  :       str										=  probs[..., target_ids]

          A_						,       A_  :       List[str]										=  probs.topk(snake_case_  )

        A_  :       List[Any]										=  []
        A_  :       int										=  values.shape[0] == 1
        for i, (_values, _predictions) in enumerate(zip(values.tolist()					,      predictions.tolist()  )  ):
          A_  :       str										=  []
          for v, p in zip(_values					,      _predictions  ):
            # Copy is important since we're going to modify this array in place
            A_  :       Union[str, Any]										=  input_ids.numpy().copy()
            if target_ids is not None:
              A_  :       str										=  target_ids[p].tolist()

            A_  :       Union[str, Any]										=  p
            # Filter padding out:
            A_  :       Any										=  tokens[np.where(tokens != self.tokenizer.pad_token_id  )]
            # Originally we skip special tokens to give readable output.
            # For multi masks though, the other [MASK] would be removed otherwise
            # making the output look odd, so we add them back
            A_  :       Any										=  self.tokenizer.decode(snake_case_					,      skip_special_tokens=snake_case_  )
            A_  :       Any										=  {'score': v, 'token': p, 'token_str': self.tokenizer.decode([p]  ), 'sequence': sequence}
            row.append(snake_case_  )
          result.append(snake_case_  )
        if single_mask:
          return result[0]
        return result

      def 					lowerCamelCase_			(     self					,      snake_case_					,      snake_case_=None  ):

        """simple docstring"""

        if isinstance(snake_case_					,      snake_case_  ):
          A_  :       List[str]										=  [targets]
        try:
          A_  :       Optional[int]										=  self.tokenizer.get_vocab()
        except Exception:
          A_  :       int										=  {}
        A_  :       Tuple										=  []
        for target in targets:
          A_  :       int										=  vocab.get(snake_case_					,      snake_case_  )
          if id_ is None:
            A_  :       Tuple										=  self.tokenizer(
                snake_case_					,      add_special_tokens=snake_case_					,      return_attention_mask=snake_case_					,      return_token_type_ids=snake_case_					,      max_length=1					,      truncation=snake_case_					,      )['input_ids']
            if len(snake_case_  ) == 0:
              logger.warning(
                  F"""The specified target token `{target}` does not exist in the model vocabulary. """
                  'We cannot replace it with anything meaningful, ignoring it'  )
              continue
            A_  :       str										=  input_ids[0]
            # XXX: If users encounter this pass
            # it becomes pretty slow, so let's make sure
            # The warning enables them to fix the input to
            # get faster performance.
            logger.warning(
                F"""The specified target token `{target}` does not exist in the model vocabulary. """
                F"""Replacing with `{self.tokenizer.convert_ids_to_tokens(id_  )}`."""  )
          target_ids.append(id_  )
        A_  :       Tuple										=  list(set(snake_case_  )  )
        if len(snake_case_  ) == 0:
          raise ValueError('At least one target must be provided when passed.'  )
        A_  :       Optional[Any]										=  np.array(snake_case_  )
        return target_ids

      def 					lowerCamelCase_			(     self					,      snake_case_=None					,      snake_case_=None  ):

        """simple docstring"""

        A_  :       List[str]										=  {}

        if targets is not None:
          A_  :       Any										=  self.get_target_ids(snake_case_					,      snake_case_  )
          A_  :       Optional[Any]										=  target_ids

        if top_k is not None:
          A_  :       int										=  top_k

        if self.tokenizer.mask_token_id is None:
          raise PipelineException(
              'fill-mask'					,      self.model.base_model_prefix					,      'The tokenizer does not define a `mask_token`.'  )
        return {}, {}, postprocess_params

      def __call__(     self					,      snake_case_					,      *snake_case_					,      **snake_case_  ):

        """simple docstring"""

        A_  :       List[str]										=  super().__call__(snake_case_					,      **snake_case_  )
        if isinstance(snake_case_					,      snake_case_  ) and len(snake_case_  ) == 1:
          return outputs[0]
        return outputs