


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


lowercase_	   =     get_logger(__name__)


lowercase_	   =     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_ :




      '''simple docstring'''


      @add_start_docstrings(lowercase_    )
      def __call__(    self:	Union[str, Any]						,				a:	jnp.ndarray						,				a:	jnp.ndarray    ):
       raise NotImplementedError(
           F'{self.__class__} is an abstract class. Only classes inheriting this class can be called.'    )



class 	A_ :




      '''simple docstring'''


      @add_start_docstrings(lowercase_    )
      def __call__(    self:	Optional[int]						,				a:	jnp.ndarray						,				a:	jnp.ndarray    ):
       raise NotImplementedError(
           F'{self.__class__} is an abstract class. Only classes inheriting this class can be called.'    )



class 	A_ (	__UpperCamelCase   ):




      '''simple docstring'''


      @add_start_docstrings(lowercase_    )
      def __call__(    self:	Union[str, Any]						,				a:	jnp.ndarray						,				a:	jnp.ndarray						,				a:	int						,				**a:	List[Any]    ):







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



class 	A_ (	__UpperCamelCase   ):




      '''simple docstring'''


      def __init__(    self:	Optional[int]						,				a:	float    ):







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

       __lowerCamelCase		:							List[Any]		 =						temperature




      def __call__(    self:	Tuple						,				a:	jnp.ndarray						,				a:	jnp.ndarray						,				a:	int    ):
       __lowerCamelCase		:							Dict		 =						scores / self.temperature
       return scores



class 	A_ (	__UpperCamelCase   ):




      '''simple docstring'''


      def __init__(    self:	Optional[Any]						,				a:	float						,				a:	float = -float('Inf'    )						,				a:	int = 1    ):







       if not isinstance(lowercase_						,				lowercase_    ) 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(lowercase_						,				lowercase_    ) 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}'    )

       __lowerCamelCase		:							Tuple		 =						top_p
       __lowerCamelCase		:							List[str]		 =						filter_value
       __lowerCamelCase		:							Union[str, Any]		 =						min_tokens_to_keep




      def __call__(    self:	Optional[Any]						,				a:	jnp.ndarray						,				a:	jnp.ndarray						,				a:	int    ):
       __lowerCamelCase ,					__lowerCamelCase		:							List[Any]		 =						lax.top_k(lowercase_						,				scores.shape[-1]    )

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

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

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

       __lowerCamelCase		:							Tuple		 =						jnp.where(lowercase_						,				lowercase_						,				lowercase_    )
       __lowerCamelCase		:							Optional[Any]		 =						jax.lax.sort_key_val(lowercase_						,				lowercase_    )[-1]

       return next_scores



class 	A_ (	__UpperCamelCase   ):




      '''simple docstring'''


      def __init__(    self:	Any						,				a:	int						,				a:	float = -float('Inf'    )						,				a:	int = 1    ):







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

       __lowerCamelCase		:							Tuple		 =						max(lowercase_						,				lowercase_    )
       __lowerCamelCase		:							int		 =						filter_value




      def __call__(    self:	str						,				a:	jnp.ndarray						,				a:	jnp.ndarray						,				a:	int    ):
       __lowerCamelCase ,					__lowerCamelCase		:							List[Any]		 =						scores.shape
       __lowerCamelCase		:							List[str]		 =						jnp.full(batch_size * vocab_size						,				self.filter_value    )

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

       __lowerCamelCase		:							Optional[Any]		 =						next_scores_flat.at[topk_indices_flat].set(lowercase_    )
       __lowerCamelCase		:							List[str]		 =						next_scores_flat.reshape(lowercase_						,				lowercase_    )
       return next_scores



class 	A_ (	__UpperCamelCase   ):




      '''simple docstring'''


      def __init__(    self:	Optional[Any]						,				a:	int    ):
       __lowerCamelCase		:							Any		 =						bos_token_id




      def __call__(    self:	int						,				a:	jnp.ndarray						,				a:	jnp.ndarray						,				a:	int    ):
       __lowerCamelCase		:							List[str]		 =						jnp.full(scores.shape						,				-float('inf'    )    )

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

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

       return scores



class 	A_ (	__UpperCamelCase   ):




      '''simple docstring'''


      def __init__(    self:	Optional[Any]						,				a:	int						,				a:	int    ):
       __lowerCamelCase		:							Optional[Any]		 =						max_length
       __lowerCamelCase		:							List[Any]		 =						eos_token_id




      def __call__(    self:	Tuple						,				a:	jnp.ndarray						,				a:	jnp.ndarray						,				a:	int    ):
       __lowerCamelCase		:							List[str]		 =						jnp.full(scores.shape						,				-float('inf'    )    )

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

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

       return scores



class 	A_ (	__UpperCamelCase   ):




      '''simple docstring'''


      def __init__(    self:	Union[str, Any]						,				a:	int						,				a:	int    ):







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

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

       __lowerCamelCase		:							List[str]		 =						min_length
       __lowerCamelCase		:							int		 =						eos_token_id




      def __call__(    self:	str						,				a:	jnp.ndarray						,				a:	jnp.ndarray						,				a:	int    ):
       __lowerCamelCase		:							List[Any]		 =						1 - jnp.clip(cur_len - self.min_length						,				0						,				1    )

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

       return scores



class 	A_ (	__UpperCamelCase   ):




      '''simple docstring'''


      def __init__(    self:	List[str]						,				a:	Optional[int]						,				a:	Optional[Any]    ):
       __lowerCamelCase		:							Any		 =						list(lowercase_    )
       __lowerCamelCase		:							List[Any]		 =						begin_index




      def __call__(    self:	Any						,				a:	Optional[Any]						,				a:	Optional[Any]						,				a:	int    ):
       __lowerCamelCase		:							Optional[Any]		 =						1 - jnp.bool_(cur_len - self.begin_index    )

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

       return scores



class 	A_ (	__UpperCamelCase   ):




      '''simple docstring'''


      def __init__(    self:	Optional[Any]						,				a:	list    ):
       __lowerCamelCase		:							List[Any]		 =						list(lowercase_    )




      def __call__(    self:	Union[str, Any]						,				a:	jnp.ndarray						,				a:	jnp.ndarray						,				a:	int    ):
       __lowerCamelCase		:							Dict		 =						scores.at[..., self.suppress_tokens].set(-float('inf'    )    )

       return scores



class 	A_ (	__UpperCamelCase   ):




      '''simple docstring'''


      def __init__(    self:	Any						,				a:	Union[str, Any]    ):
       __lowerCamelCase		:							List[Any]		 =						dict(lowercase_    )
       # 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.
       __lowerCamelCase		:							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:
         __lowerCamelCase		:							Optional[int]		 =						force_token_array.at[index].set(lowercase_    )
       __lowerCamelCase		:							List[str]		 =						jnp.intaa(lowercase_    )




      def __call__(    self:	Dict						,				a:	jnp.ndarray						,				a:	jnp.ndarray						,				a:	int    ):







       def _force_token(a:	int    ):
        __lowerCamelCase		:							Tuple		 =						scores.shape[0]
        __lowerCamelCase		:							List[str]		 =						self.force_token_array[generation_idx]

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

       __lowerCamelCase		:							Optional[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(lowercase_    )						,				lambda: scores						,				)						,				)
       return scores



class 	A_ (	__UpperCamelCase   ):




      '''simple docstring'''


      def __init__(    self:	Dict						,				a:	List[Any]						,				a:	List[Any]						,				a:	List[str]    ):
       __lowerCamelCase		:							Optional[Any]		 =						generate_config.eos_token_id
       __lowerCamelCase		:							Optional[Any]		 =						generate_config.no_timestamps_token_id
       __lowerCamelCase		:							Dict		 =						generate_config.no_timestamps_token_id + 1

       __lowerCamelCase		:							Union[str, Any]		 =						decoder_input_length + 1

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




      def __call__(    self:	Tuple						,				a:	Tuple						,				a:	Tuple						,				a:	Optional[Any]    ):
       __lowerCamelCase		:							str		 =						scores.at[:, self.no_timestamps_token_id].set(-float('inf'    )    )

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

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

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

       __lowerCamelCase		:							int		 =						jax.vmap(lowercase_    )(lowercase_						,				lowercase_    )

       __lowerCamelCase		:							Tuple		 =						jnp.where(cur_len == self.begin_index						,				lowercase_						,				lowercase_    )
       __lowerCamelCase		:							str		 =						jnp.where(
           self.max_initial_timestamp_index is not None						,				True and apply_max_initial_timestamp						,				lowercase_						,				)

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

       __lowerCamelCase		:							Optional[int]		 =						jnp.where(
           lowercase_						,				scores.at[:, last_allowed + 1 :].set(-float('inf'    )    )						,				lowercase_						,				)

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

       def handle_cumulative_probs(a:	List[Any]						,				a:	List[str]    ):
        __lowerCamelCase		:							List[Any]		 =						jax.nn.logsumexp(logprobs_k[self.timestamp_begin :]						,				axis=-1    )
        __lowerCamelCase		:							Union[str, 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'    )    )						,				lowercase_						,				)

       __lowerCamelCase		:							Any		 =						jax.vmap(lowercase_    )(lowercase_						,				lowercase_    )

       return scores





def 				UpperCamelCase__					(  SCREAMING_SNAKE_CASE__						):
 __lowerCamelCase		:							str		 =						0
 __lowerCamelCase		:							Tuple		 =						len(SCREAMING_SNAKE_CASE__						)

 for i in range(n - 1						):
  for j in range(i + 1      ,	SCREAMING_SNAKE_CASE__						):
   if arr[i] > arr[j]:
    num_inversions += 1

 return num_inversions
def 				UpperCamelCase__					(  SCREAMING_SNAKE_CASE__						):
 if len(SCREAMING_SNAKE_CASE__						) <= 1:
  return arr, 0
 __lowerCamelCase		:							Optional[int]		 =						len(SCREAMING_SNAKE_CASE__						) // 2
 __lowerCamelCase		:							Union[str, Any]		 =						arr[0:mid]
 __lowerCamelCase		:							List[Any]		 =						arr[mid:]

 __lowerCamelCase ,					__lowerCamelCase		:							Any		 =						count_inversions_recursive(SCREAMING_SNAKE_CASE__						)
 __lowerCamelCase ,					__lowerCamelCase		:							List[str]		 =						count_inversions_recursive(SCREAMING_SNAKE_CASE__						)
 __lowerCamelCase ,					__lowerCamelCase		:							Dict		 =						_count_cross_inversions(SCREAMING_SNAKE_CASE__      ,	SCREAMING_SNAKE_CASE__						)

 __lowerCamelCase		:							List[str]		 =						inversion_p + inversions_q + cross_inversions
 return c, num_inversions
def 				UpperCamelCase__					(  SCREAMING_SNAKE_CASE__      ,	SCREAMING_SNAKE_CASE__						):
 __lowerCamelCase		:							Optional[int]		 =						[]
 __lowerCamelCase		:							List[Any]		 =						0
 while i < len(SCREAMING_SNAKE_CASE__						) and j < len(SCREAMING_SNAKE_CASE__						):
  if p[i] > q[j]:
   # if P[1] > Q[j], then P[k] > Q[k] for all  i < k <= len(P)
   # These are all inversions. The claim emerges from the
   # property that P is sorted.
   num_inversion += len(SCREAMING_SNAKE_CASE__						) - i
   r.append(q[j]						)
   j += 1
  else:
   r.append(p[i]						)
   i += 1

 if i < len(SCREAMING_SNAKE_CASE__						):
  r.extend(p[i:]						)
 else:
  r.extend(q[j:]						)

 return r, num_inversion
def 				UpperCamelCase__					(  ):
 __lowerCamelCase		:							Optional[int]		 =						[10, 2, 1, 5, 5, 2, 11]

 # this arr has 8 inversions:
 # (10, 2), (10, 1), (10, 5), (10, 5), (10, 2), (2, 1), (5, 2), (5, 2)

 __lowerCamelCase		:							Optional[Any]		 =						count_inversions_bf(SCREAMING_SNAKE_CASE__						)
 __lowerCamelCase ,					__lowerCamelCase		:							Optional[Any]		 =						count_inversions_recursive(SCREAMING_SNAKE_CASE__						)

 assert num_inversions_bf == num_inversions_recursive == 8

 print('number of inversions = '      ,	SCREAMING_SNAKE_CASE__						)

 # testing an array with zero inversion (a sorted arr_1)

 arr_a.sort()
 __lowerCamelCase		:							Optional[Any]		 =						count_inversions_bf(SCREAMING_SNAKE_CASE__						)
 __lowerCamelCase ,					__lowerCamelCase		:							int		 =						count_inversions_recursive(SCREAMING_SNAKE_CASE__						)

 assert num_inversions_bf == num_inversions_recursive == 0
 print('number of inversions = '      ,	SCREAMING_SNAKE_CASE__						)

 # an empty list should also have zero inversions
 __lowerCamelCase		:							List[str]		 =						[]
 __lowerCamelCase		:							Dict		 =						count_inversions_bf(SCREAMING_SNAKE_CASE__						)
 __lowerCamelCase ,					__lowerCamelCase		:							Dict		 =						count_inversions_recursive(SCREAMING_SNAKE_CASE__						)

 assert num_inversions_bf == num_inversions_recursive == 0
 print('number of inversions = '      ,	SCREAMING_SNAKE_CASE__						)


if __name__ == "__main__":
       main()

