"""simple docstring"""







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        UpperCamelCase		:
   @add_start_docstrings(__UpperCamelCase			)
   def __call__(			self     ,__UpperCamelCase     ,__UpperCamelCase			)	->      jnp.ndarray:


        '''simple docstring'''


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







class        UpperCamelCase		:
   @add_start_docstrings(__UpperCamelCase			)
   def __call__(			self     ,__UpperCamelCase     ,__UpperCamelCase			)	->      jnp.ndarray:


        '''simple docstring'''


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







class        UpperCamelCase		(			lowercase_  ):
   @add_start_docstrings(__UpperCamelCase			)
   def __call__(			self     ,__UpperCamelCase     ,__UpperCamelCase     ,__UpperCamelCase     ,**__UpperCamelCase			)	->      jnp.ndarray:


        '''simple docstring'''


        for processor in self:
             lowercase_	:				List[Any]													=	inspect.signature(processor.__call__			).parameters
             if len(__UpperCamelCase			) > 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(__UpperCamelCase     ,__UpperCamelCase     ,__UpperCamelCase     ,**__UpperCamelCase			)
             else:
                  lowercase_	:				int													=	processor(__UpperCamelCase     ,__UpperCamelCase     ,__UpperCamelCase			)
        return scores







class        UpperCamelCase		(			lowercase_  ):
   def __init__(			self     ,__UpperCamelCase			)	->      Tuple:


        '''simple docstring'''


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

        lowercase_	:				str													=	temperature







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


        '''simple docstring'''


        lowercase_	:				Any													=	scores / self.temperature
        return scores







class        UpperCamelCase		(			lowercase_  ):
   def __init__(			self     ,__UpperCamelCase     ,__UpperCamelCase = -float('Inf'			)     ,__UpperCamelCase = 1			)	->      Any:


        '''simple docstring'''


        if not isinstance(__UpperCamelCase     ,__UpperCamelCase			) 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(__UpperCamelCase     ,__UpperCamelCase			) 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_	:				List[Any]													=	top_p
        lowercase_	:				str													=	filter_value
        lowercase_	:				int													=	min_tokens_to_keep







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


        '''simple docstring'''


        lowercase_							,  lowercase_	:				Union[str, Any]													=	lax.top_k(__UpperCamelCase     ,scores.shape[-1]			)

        lowercase_	:				Any													=	jnp.full_like(__UpperCamelCase     ,self.filter_value			)
        lowercase_	:				Union[str, Any]													=	jax.nn.softmax(__UpperCamelCase     ,axis=-1			).cumsum(axis=-1			)
        lowercase_	:				Tuple													=	cumulative_probs < self.top_p

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

        # min tokens to keep
        lowercase_	:				Union[str, Any]													=	score_mask.at[:, : self.min_tokens_to_keep].set(__UpperCamelCase			)

        lowercase_	:				Optional[int]													=	jnp.where(__UpperCamelCase     ,__UpperCamelCase     ,__UpperCamelCase			)
        lowercase_	:				str													=	jax.lax.sort_key_val(__UpperCamelCase     ,__UpperCamelCase			)[-1]

        return next_scores







class        UpperCamelCase		(			lowercase_  ):
   def __init__(			self     ,__UpperCamelCase     ,__UpperCamelCase = -float('Inf'			)     ,__UpperCamelCase = 1			)	->      Dict:


        '''simple docstring'''


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

        lowercase_	:				List[Any]													=	max(__UpperCamelCase     ,__UpperCamelCase			)
        lowercase_	:				List[Any]													=	filter_value







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


        '''simple docstring'''


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

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

        lowercase_	:				Tuple													=	next_scores_flat.at[topk_indices_flat].set(__UpperCamelCase			)
        lowercase_	:				List[str]													=	next_scores_flat.reshape(__UpperCamelCase     ,__UpperCamelCase			)
        return next_scores







class        UpperCamelCase		(			lowercase_  ):
   def __init__(			self     ,__UpperCamelCase			)	->      Tuple:


        '''simple docstring'''


        lowercase_	:				Any													=	bos_token_id







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


        '''simple docstring'''


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

        lowercase_	:				int													=	1 - jnp.bool_(cur_len - 1			)

        lowercase_	:				List[str]													=	jnp.where(__UpperCamelCase     ,new_scores.at[:, self.bos_token_id].set(0			)     ,__UpperCamelCase			)

        return scores







class        UpperCamelCase		(			lowercase_  ):
   def __init__(			self     ,__UpperCamelCase     ,__UpperCamelCase			)	->      List[Any]:


        '''simple docstring'''


        lowercase_	:				int													=	max_length
        lowercase_	:				int													=	eos_token_id







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


        '''simple docstring'''


        lowercase_	:				Tuple													=	jnp.full(scores.shape     ,-float('inf'			)			)

        lowercase_	:				Any													=	1 - jnp.bool_(cur_len - self.max_length + 1			)

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

        return scores







class        UpperCamelCase		(			lowercase_  ):
   def __init__(			self     ,__UpperCamelCase     ,__UpperCamelCase			)	->      Tuple:


        '''simple docstring'''


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

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

        lowercase_	:				Optional[int]													=	min_length
        lowercase_	:				Optional[int]													=	eos_token_id







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


        '''simple docstring'''


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

        lowercase_	:				int													=	jnp.where(__UpperCamelCase     ,scores.at[:, self.eos_token_id].set(-float('inf'			)			)     ,__UpperCamelCase			)

        return scores







class        UpperCamelCase		(			lowercase_  ):
   def __init__(			self     ,__UpperCamelCase     ,__UpperCamelCase			)	->      Union[str, Any]:


        '''simple docstring'''


        lowercase_	:				Tuple													=	list(__UpperCamelCase			)
        lowercase_	:				List[Any]													=	begin_index







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


        '''simple docstring'''


        lowercase_	:				str													=	1 - jnp.bool_(cur_len - self.begin_index			)

        lowercase_	:				List[str]													=	jnp.where(__UpperCamelCase     ,scores.at[:, self.begin_suppress_tokens].set(-float('inf'			)			)     ,__UpperCamelCase			)

        return scores







class        UpperCamelCase		(			lowercase_  ):
   def __init__(			self     ,__UpperCamelCase			)	->      int:


        '''simple docstring'''


        lowercase_	:				str													=	list(__UpperCamelCase			)







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


        '''simple docstring'''


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

        return scores







class        UpperCamelCase		(			lowercase_  ):
   def __init__(			self     ,__UpperCamelCase			)	->      List[str]:


        '''simple docstring'''


        lowercase_	:				List[str]													=	dict(__UpperCamelCase			)
        # 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_	:				str													=	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[Any]													=	force_token_array.at[index].set(__UpperCamelCase			)
        lowercase_	:				List[Any]													=	jnp.intaa(__UpperCamelCase			)







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


        '''simple docstring'''


        def _force_token(__UpperCamelCase			):
             lowercase_	:				Optional[Any]													=	scores.shape[0]
             lowercase_	:				List[str]													=	self.force_token_array[generation_idx]

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

        lowercase_	:				int													=	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(__UpperCamelCase			)     ,lambda: scores     ,)     ,)
        return scores







class        UpperCamelCase		(			lowercase_  ):
   def __init__(			self     ,__UpperCamelCase     ,__UpperCamelCase     ,__UpperCamelCase			)	->      Tuple:


        '''simple docstring'''


        lowercase_	:				Any													=	generate_config.eos_token_id
        lowercase_	:				Optional[Any]													=	generate_config.no_timestamps_token_id
        lowercase_	:				Optional[int]													=	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(__UpperCamelCase     ,'max_initial_timestamp_index'			):
             lowercase_	:				Optional[int]													=	generate_config.max_initial_timestamp_index
        else:
             lowercase_	:				List[str]													=	model_config.vocab_size
        if self.max_initial_timestamp_index is None:
             lowercase_	:				List[Any]													=	model_config.vocab_size







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


        '''simple docstring'''


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

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

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

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

        lowercase_	:				List[str]													=	jax.vmap(__UpperCamelCase			)(__UpperCamelCase     ,__UpperCamelCase			)

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

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

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

        # if sum of probability over timestamps is above any other token, sample timestamp
        lowercase_	:				List[str]													=	jax.nn.log_softmax(__UpperCamelCase     ,axis=-1			)

        def handle_cumulative_probs(__UpperCamelCase     ,__UpperCamelCase			):
             lowercase_	:				Optional[int]													=	jax.nn.logsumexp(logprobs_k[self.timestamp_begin :]     ,axis=-1			)
             lowercase_	:				Optional[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'			)			)     ,__UpperCamelCase     ,)

        lowercase_	:				List[str]													=	jax.vmap(__UpperCamelCase			)(__UpperCamelCase     ,__UpperCamelCase			)

        return scores


"""simple docstring"""







from argparse import ArgumentParser

from datasets.commands.convert import ConvertCommand
from datasets.commands.dummy_data import DummyDataCommand
from datasets.commands.env import EnvironmentCommand
from datasets.commands.run_beam import RunBeamCommand
from datasets.commands.test import TestCommand
from datasets.utils.logging import set_verbosity_info



def 			lowercase__(       __SCREAMING_SNAKE_CASE							:     Optional[int]      ):
     return {key.lstrip('-'      ): value for key, value in zip(unknown_args[::2]     ,			unknown_args[1::2]      )}



def 			lowercase__(       ):
     lowercase_	:				Any													=	ArgumentParser(
         'HuggingFace Datasets CLI tool'     ,			usage='datasets-cli <command> [<args>]'     ,			allow_abbrev=__SCREAMING_SNAKE_CASE      )
     lowercase_	:				Tuple													=	parser.add_subparsers(help='datasets-cli command helpers'      )
     set_verbosity_info()

     # Register commands
     ConvertCommand.register_subcommand(__SCREAMING_SNAKE_CASE      )
     EnvironmentCommand.register_subcommand(__SCREAMING_SNAKE_CASE      )
     TestCommand.register_subcommand(__SCREAMING_SNAKE_CASE      )
     RunBeamCommand.register_subcommand(__SCREAMING_SNAKE_CASE      )
     DummyDataCommand.register_subcommand(__SCREAMING_SNAKE_CASE      )

     # Parse args
     lowercase_							,  lowercase_	:				Dict													=	parser.parse_known_args()
     if not hasattr(__SCREAMING_SNAKE_CASE     ,			'func'      ):
          parser.print_help()
          exit(1      )
     lowercase_	:				int													=	parse_unknown_args(__SCREAMING_SNAKE_CASE      )

     # Run
     lowercase_	:				List[Any]													=	args.func(__SCREAMING_SNAKE_CASE     ,			**__SCREAMING_SNAKE_CASE      )
     service.run()


if __name__ == "__main__":
       main()

