





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


__A     =    get_logger(__name__)


__A     =    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        _SCREAMING_SNAKE_CASE						:







 '''simple docstring'''

 @add_start_docstrings(UpperCAmelCase_)
 def __call__(self    :       Tuple	,			UpperCAmelCase_    :       jnp.ndarray	,			UpperCAmelCase_    :       jnp.ndarray)	->jnp.ndarray:



   '''simple docstring'''



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



class        _SCREAMING_SNAKE_CASE						:







 '''simple docstring'''

 @add_start_docstrings(UpperCAmelCase_)
 def __call__(self    :       str	,			UpperCAmelCase_    :       jnp.ndarray	,			UpperCAmelCase_    :       jnp.ndarray)	->jnp.ndarray:



   '''simple docstring'''



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



class        _SCREAMING_SNAKE_CASE						(     __SCREAMING_SNAKE_CASE   ):







 '''simple docstring'''

 @add_start_docstrings(UpperCAmelCase_)
 def __call__(self    :       Dict	,			UpperCAmelCase_    :       jnp.ndarray	,			UpperCAmelCase_    :       jnp.ndarray	,			UpperCAmelCase_    :       int	,			**UpperCAmelCase_    :       Dict)	->jnp.ndarray:



   '''simple docstring'''



   for processor in self:
     lowerCamelCase__:				Optional[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.""")
       lowerCamelCase__:				Tuple        =processor(UpperCAmelCase_	,			UpperCAmelCase_	,			UpperCAmelCase_	,			**UpperCAmelCase_)
     else:
       lowerCamelCase__:				Optional[Any]        =processor(UpperCAmelCase_	,			UpperCAmelCase_	,			UpperCAmelCase_)
   return scores



class        _SCREAMING_SNAKE_CASE						(     __SCREAMING_SNAKE_CASE   ):







 '''simple docstring'''

 def __init__(self    :       Dict	,			UpperCAmelCase_    :       float)	->str:



   '''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}""")

   lowerCamelCase__:				Optional[int]        =temperature







 def __call__(self    :       str	,			UpperCAmelCase_    :       jnp.ndarray	,			UpperCAmelCase_    :       jnp.ndarray	,			UpperCAmelCase_    :       int)	->jnp.ndarray:



   '''simple docstring'''



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



class        _SCREAMING_SNAKE_CASE						(     __SCREAMING_SNAKE_CASE   ):







 '''simple docstring'''

 def __init__(self    :       Optional[int]	,			UpperCAmelCase_    :       float	,			UpperCAmelCase_    :       float = -float("Inf")	,			UpperCAmelCase_    :       int = 1)	->List[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}""")

   lowerCamelCase__:				Any        =top_p
   lowerCamelCase__:				Optional[Any]        =filter_value
   lowerCamelCase__:				Optional[int]        =min_tokens_to_keep







 def __call__(self    :       List[str]	,			UpperCAmelCase_    :       jnp.ndarray	,			UpperCAmelCase_    :       jnp.ndarray	,			UpperCAmelCase_    :       int)	->jnp.ndarray:



   '''simple docstring'''



   lowerCamelCase__  , lowerCamelCase__:				int        =lax.top_k(UpperCAmelCase_	,			scores.shape[-1])

   lowerCamelCase__:				int        =jnp.full_like(UpperCAmelCase_	,			self.filter_value)
   lowerCamelCase__:				Optional[Any]        =jax.nn.softmax(UpperCAmelCase_	,			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[str]        =jnp.roll(UpperCAmelCase_	,			1)
   score_mask |= score_mask.at[:, 0].set(UpperCAmelCase_)

   # min tokens to keep
   lowerCamelCase__:				List[Any]        =score_mask.at[:, : self.min_tokens_to_keep].set(UpperCAmelCase_)

   lowerCamelCase__:				str        =jnp.where(UpperCAmelCase_	,			UpperCAmelCase_	,			UpperCAmelCase_)
   lowerCamelCase__:				str        =jax.lax.sort_key_val(UpperCAmelCase_	,			UpperCAmelCase_)[-1]

   return next_scores



class        _SCREAMING_SNAKE_CASE						(     __SCREAMING_SNAKE_CASE   ):







 '''simple docstring'''

 def __init__(self    :       List[str]	,			UpperCAmelCase_    :       int	,			UpperCAmelCase_    :       float = -float("Inf")	,			UpperCAmelCase_    :       int = 1)	->List[str]:



   '''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}""")

   lowerCamelCase__:				List[str]        =max(UpperCAmelCase_	,			UpperCAmelCase_)
   lowerCamelCase__:				Tuple        =filter_value







 def __call__(self    :       List[str]	,			UpperCAmelCase_    :       jnp.ndarray	,			UpperCAmelCase_    :       jnp.ndarray	,			UpperCAmelCase_    :       int)	->jnp.ndarray:



   '''simple docstring'''



   lowerCamelCase__  , lowerCamelCase__:				int        =scores.shape
   lowerCamelCase__:				Any        =jnp.full(batch_size * vocab_size	,			self.filter_value)

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

   lowerCamelCase__:				Tuple        =next_scores_flat.at[topk_indices_flat].set(UpperCAmelCase_)
   lowerCamelCase__:				Optional[Any]        =next_scores_flat.reshape(UpperCAmelCase_	,			UpperCAmelCase_)
   return next_scores



class        _SCREAMING_SNAKE_CASE						(     __SCREAMING_SNAKE_CASE   ):







 '''simple docstring'''

 def __init__(self    :       Optional[int]	,			UpperCAmelCase_    :       int)	->List[Any]:



   '''simple docstring'''



   lowerCamelCase__:				List[str]        =bos_token_id







 def __call__(self    :       List[Any]	,			UpperCAmelCase_    :       jnp.ndarray	,			UpperCAmelCase_    :       jnp.ndarray	,			UpperCAmelCase_    :       int)	->jnp.ndarray:



   '''simple docstring'''



   lowerCamelCase__:				Optional[Any]        =jnp.full(scores.shape	,			-float("inf"))

   lowerCamelCase__:				Any        =1 - jnp.bool_(cur_len - 1)

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

   return scores



class        _SCREAMING_SNAKE_CASE						(     __SCREAMING_SNAKE_CASE   ):







 '''simple docstring'''

 def __init__(self    :       List[Any]	,			UpperCAmelCase_    :       int	,			UpperCAmelCase_    :       int)	->Optional[int]:



   '''simple docstring'''



   lowerCamelCase__:				Optional[Any]        =max_length
   lowerCamelCase__:				Union[str, Any]        =eos_token_id







 def __call__(self    :       Any	,			UpperCAmelCase_    :       jnp.ndarray	,			UpperCAmelCase_    :       jnp.ndarray	,			UpperCAmelCase_    :       int)	->jnp.ndarray:



   '''simple docstring'''



   lowerCamelCase__:				List[str]        =jnp.full(scores.shape	,			-float("inf"))

   lowerCamelCase__:				Optional[Any]        =1 - jnp.bool_(cur_len - self.max_length + 1)

   lowerCamelCase__:				List[Any]        =jnp.where(UpperCAmelCase_	,			new_scores.at[:, self.eos_token_id].set(0)	,			UpperCAmelCase_)

   return scores



class        _SCREAMING_SNAKE_CASE						(     __SCREAMING_SNAKE_CASE   ):







 '''simple docstring'''

 def __init__(self    :       int	,			UpperCAmelCase_    :       int	,			UpperCAmelCase_    :       int)	->Union[str, Any]:



   '''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}""")

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







 def __call__(self    :       str	,			UpperCAmelCase_    :       jnp.ndarray	,			UpperCAmelCase_    :       jnp.ndarray	,			UpperCAmelCase_    :       int)	->jnp.ndarray:



   '''simple docstring'''



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

   lowerCamelCase__:				str        =jnp.where(UpperCAmelCase_	,			scores.at[:, self.eos_token_id].set(-float("inf"))	,			UpperCAmelCase_)

   return scores



class        _SCREAMING_SNAKE_CASE						(     __SCREAMING_SNAKE_CASE   ):







 '''simple docstring'''

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



   '''simple docstring'''



   lowerCamelCase__:				Union[str, Any]        =list(UpperCAmelCase_)
   lowerCamelCase__:				str        =begin_index







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



   '''simple docstring'''



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

   lowerCamelCase__:				Any        =jnp.where(UpperCAmelCase_	,			scores.at[:, self.begin_suppress_tokens].set(-float("inf"))	,			UpperCAmelCase_)

   return scores



class        _SCREAMING_SNAKE_CASE						(     __SCREAMING_SNAKE_CASE   ):







 '''simple docstring'''

 def __init__(self    :       Union[str, Any]	,			UpperCAmelCase_    :       list)	->List[str]:



   '''simple docstring'''



   lowerCamelCase__:				Union[str, Any]        =list(UpperCAmelCase_)







 def __call__(self    :       str	,			UpperCAmelCase_    :       jnp.ndarray	,			UpperCAmelCase_    :       jnp.ndarray	,			UpperCAmelCase_    :       int)	->jnp.ndarray:



   '''simple docstring'''



   lowerCamelCase__:				Any        =scores.at[..., self.suppress_tokens].set(-float("inf"))

   return scores



class        _SCREAMING_SNAKE_CASE						(     __SCREAMING_SNAKE_CASE   ):







 '''simple docstring'''

 def __init__(self    :       Union[str, Any]	,			UpperCAmelCase_    :       Union[str, Any])	->str:



   '''simple docstring'''



   lowerCamelCase__:				Optional[Any]        =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.
   lowerCamelCase__:				Tuple        =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__:				Dict        =force_token_array.at[index].set(UpperCAmelCase_)
   lowerCamelCase__:				Optional[int]        =jnp.intaa(UpperCAmelCase_)







 def __call__(self    :       List[str]	,			UpperCAmelCase_    :       jnp.ndarray	,			UpperCAmelCase_    :       jnp.ndarray	,			UpperCAmelCase_    :       int)	->jnp.ndarray:



   '''simple docstring'''



   def _force_token(UpperCAmelCase_    :       List[Any]):
     lowerCamelCase__:				str        =scores.shape[0]
     lowerCamelCase__:				Any        =self.force_token_array[generation_idx]

     lowerCamelCase__:				str        =jnp.ones_like(UpperCAmelCase_	,			dtype=scores.dtype) * -float("inf")
     lowerCamelCase__:				Any        =jnp.zeros((batch_size, 1)	,			dtype=scores.dtype)
     lowerCamelCase__:				Tuple        =lax.dynamic_update_slice(UpperCAmelCase_	,			UpperCAmelCase_	,			(0, current_token))
     return new_scores

   lowerCamelCase__:				Dict        =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        _SCREAMING_SNAKE_CASE						(     __SCREAMING_SNAKE_CASE   ):







 '''simple docstring'''

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



   '''simple docstring'''



   lowerCamelCase__:				List[Any]        =generate_config.eos_token_id
   lowerCamelCase__:				Optional[int]        =generate_config.no_timestamps_token_id
   lowerCamelCase__:				List[str]        =generate_config.no_timestamps_token_id + 1

   lowerCamelCase__:				str        =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"):
     lowerCamelCase__:				List[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__:				List[Any]        =model_config.vocab_size







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



   '''simple docstring'''



   lowerCamelCase__:				Any        =scores.at[:, self.no_timestamps_token_id].set(-float("inf"))

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

     lowerCamelCase__:				str        =jnp.where((cur_len - self.begin_index) < 2	,			UpperCAmelCase_	,			UpperCAmelCase_)
     lowerCamelCase__:				Tuple        =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_	,			)

   lowerCamelCase__:				Optional[int]        =jax.vmap(UpperCAmelCase_)(UpperCAmelCase_	,			UpperCAmelCase_)

   lowerCamelCase__:				List[Any]        =jnp.where(cur_len == self.begin_index	,			UpperCAmelCase_	,			UpperCAmelCase_)
   lowerCamelCase__:				Any        =jnp.where(
       self.max_initial_timestamp_index is not None	,			True and apply_max_initial_timestamp	,			UpperCAmelCase_	,			)

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

   lowerCamelCase__:				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
   lowerCamelCase__:				List[str]        =jax.nn.log_softmax(UpperCAmelCase_	,			axis=-1)

   def handle_cumulative_probs(UpperCAmelCase_    :       Tuple	,			UpperCAmelCase_    :       str):
     lowerCamelCase__:				Tuple        =jax.nn.logsumexp(logprobs_k[self.timestamp_begin :]	,			axis=-1)
     lowerCamelCase__:				Optional[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"))	,			UpperCAmelCase_	,			)

   lowerCamelCase__:				Dict        =jax.vmap(UpperCAmelCase_)(UpperCAmelCase_	,			UpperCAmelCase_)

   return scores








def 					lowerCAmelCase_			(	__a		)					->		str:







  """simple docstring"""





  if isinstance(__a     ,   __a		):
    raise TypeError("'float' object cannot be interpreted as an integer"		)
  if isinstance(__a     ,   __a		):
    raise TypeError("'str' object cannot be interpreted as an integer"		)

  if num == 0:
    return "0b0"

  lowerCamelCase__:				Optional[int]        =False

  if num < 0:
    lowerCamelCase__:				Optional[Any]        =True
    lowerCamelCase__:				List[Any]        =-num

  lowerCamelCase__:				list[int]        =[]
  while num > 0:
    binary.insert(0     ,   num % 2		)
    num >>= 1

  if negative:
    return "-0b" + "".join(str(__a		) for e in binary		)

  return "0b" + "".join(str(__a		) for e in binary		)


if __name__ == "__main__":
     import doctest

     doctest.testmod()

