

"""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


__UpperCAmelCase =				get_logger(__name__)


__UpperCAmelCase =				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      __lowercase			:

  @add_start_docstrings(A    )
  def __call__(  self		:			Any					,A		:			jnp.ndarray					,A		:			jnp.ndarray    ):






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







class      __lowercase			:

  @add_start_docstrings(A    )
  def __call__(  self		:			Tuple					,A		:			jnp.ndarray					,A		:			jnp.ndarray    ):






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







class      __lowercase			(    __lowerCamelCase					):

  @add_start_docstrings(A    )
  def __call__(  self		:			Optional[int]					,A		:			jnp.ndarray					,A		:			jnp.ndarray					,A		:			int					,**A		:			Dict    ):






   '''simple docstring'''
   for processor in self:
    UpperCAmelCase__					:  List[str]					   =					inspect.signature(processor.__call__    ).parameters
    if len(A    ) > 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."    )
     UpperCAmelCase__					:  List[str]					   =					processor(A					,A					,A					,**A    )
    else:
     UpperCAmelCase__					:  str					   =					processor(A					,A					,A    )
   return scores







class      __lowercase			(    __lowerCamelCase					):

  def __init__(  self		:			Union[str, Any]					,A		:			float    ):






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

   UpperCAmelCase__					:  Tuple					   =					temperature




  def __call__(  self		:			Any					,A		:			jnp.ndarray					,A		:			jnp.ndarray					,A		:			int    ):






   '''simple docstring'''
   UpperCAmelCase__					:  Union[str, Any]					   =					scores / self.temperature
   return scores







class      __lowercase			(    __lowerCamelCase					):

  def __init__(  self		:			str					,A		:			float					,A		:			float = -float("""Inf"""    )					,A		:			int = 1    ):






   '''simple docstring'''
   if not isinstance(A					,A    ) 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(A					,A    ) 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}"    )

   UpperCAmelCase__					:  Union[str, Any]					   =					top_p
   UpperCAmelCase__					:  Optional[Any]					   =					filter_value
   UpperCAmelCase__					:  List[Any]					   =					min_tokens_to_keep




  def __call__(  self		:			Any					,A		:			jnp.ndarray					,A		:			jnp.ndarray					,A		:			int    ):






   '''simple docstring'''
   UpperCAmelCase__   ,      UpperCAmelCase__					:  List[str]					   =					lax.top_k(A					,scores.shape[-1]    )

   UpperCAmelCase__					:  List[Any]					   =					jnp.full_like(A					,self.filter_value    )
   UpperCAmelCase__					:  Dict					   =					jax.nn.softmax(A					,axis=-1    ).cumsum(axis=-1    )
   UpperCAmelCase__					:  Dict					   =					cumulative_probs < self.top_p

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

   # min tokens to keep
   UpperCAmelCase__					:  Dict					   =					score_mask.at[:, : self.min_tokens_to_keep].set(A    )

   UpperCAmelCase__					:  List[Any]					   =					jnp.where(A					,A					,A    )
   UpperCAmelCase__					:  Optional[int]					   =					jax.lax.sort_key_val(A					,A    )[-1]

   return next_scores







class      __lowercase			(    __lowerCamelCase					):

  def __init__(  self		:			List[Any]					,A		:			int					,A		:			float = -float("""Inf"""    )					,A		:			int = 1    ):






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

   UpperCAmelCase__					:  Optional[int]					   =					max(A					,A    )
   UpperCAmelCase__					:  List[Any]					   =					filter_value




  def __call__(  self		:			Optional[int]					,A		:			jnp.ndarray					,A		:			jnp.ndarray					,A		:			int    ):






   '''simple docstring'''
   UpperCAmelCase__   ,      UpperCAmelCase__					:  Dict					   =					scores.shape
   UpperCAmelCase__					:  List[str]					   =					jnp.full(batch_size * vocab_size					,self.filter_value    )

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

   UpperCAmelCase__					:  Optional[int]					   =					next_scores_flat.at[topk_indices_flat].set(A    )
   UpperCAmelCase__					:  str					   =					next_scores_flat.reshape(A					,A    )
   return next_scores







class      __lowercase			(    __lowerCamelCase					):

  def __init__(  self		:			List[str]					,A		:			int    ):






   '''simple docstring'''
   UpperCAmelCase__					:  Any					   =					bos_token_id




  def __call__(  self		:			str					,A		:			jnp.ndarray					,A		:			jnp.ndarray					,A		:			int    ):






   '''simple docstring'''
   UpperCAmelCase__					:  Any					   =					jnp.full(scores.shape					,-float("""inf"""    )    )

   UpperCAmelCase__					:  str					   =					1 - jnp.bool_(cur_len - 1    )

   UpperCAmelCase__					:  Optional[int]					   =					jnp.where(A					,new_scores.at[:, self.bos_token_id].set(0    )					,A    )

   return scores







class      __lowercase			(    __lowerCamelCase					):

  def __init__(  self		:			int					,A		:			int					,A		:			int    ):






   '''simple docstring'''
   UpperCAmelCase__					:  Union[str, Any]					   =					max_length
   UpperCAmelCase__					:  int					   =					eos_token_id




  def __call__(  self		:			Optional[Any]					,A		:			jnp.ndarray					,A		:			jnp.ndarray					,A		:			int    ):






   '''simple docstring'''
   UpperCAmelCase__					:  Optional[int]					   =					jnp.full(scores.shape					,-float("""inf"""    )    )

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

   UpperCAmelCase__					:  Any					   =					jnp.where(A					,new_scores.at[:, self.eos_token_id].set(0    )					,A    )

   return scores







class      __lowercase			(    __lowerCamelCase					):

  def __init__(  self		:			List[Any]					,A		:			int					,A		:			int    ):






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

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

   UpperCAmelCase__					:  Dict					   =					min_length
   UpperCAmelCase__					:  List[str]					   =					eos_token_id




  def __call__(  self		:			int					,A		:			jnp.ndarray					,A		:			jnp.ndarray					,A		:			int    ):






   '''simple docstring'''
   # create boolean flag to decide if min length penalty should be applied
   UpperCAmelCase__					:  Any					   =					1 - jnp.clip(cur_len - self.min_length					,0					,1    )

   UpperCAmelCase__					:  Any					   =					jnp.where(A					,scores.at[:, self.eos_token_id].set(-float("""inf"""    )    )					,A    )

   return scores







class      __lowercase			(    __lowerCamelCase					):

  def __init__(  self		:			List[str]					,A		:			Optional[Any]					,A		:			List[Any]    ):






   '''simple docstring'''
   UpperCAmelCase__					:  Optional[Any]					   =					list(A    )
   UpperCAmelCase__					:  Optional[Any]					   =					begin_index




  def __call__(  self		:			Optional[int]					,A		:			Any					,A		:			List[Any]					,A		:			int    ):






   '''simple docstring'''
   UpperCAmelCase__					:  List[Any]					   =					1 - jnp.bool_(cur_len - self.begin_index    )

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

   return scores







class      __lowercase			(    __lowerCamelCase					):

  def __init__(  self		:			int					,A		:			list    ):






   '''simple docstring'''
   UpperCAmelCase__					:  Dict					   =					list(A    )




  def __call__(  self		:			List[str]					,A		:			jnp.ndarray					,A		:			jnp.ndarray					,A		:			int    ):






   '''simple docstring'''
   UpperCAmelCase__					:  Dict					   =					scores.at[..., self.suppress_tokens].set(-float("""inf"""    )    )

   return scores







class      __lowercase			(    __lowerCamelCase					):

  def __init__(  self		:			Dict					,A		:			Optional[int]    ):






   '''simple docstring'''
   UpperCAmelCase__					:  Tuple					   =					dict(A    )
   # 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.
   UpperCAmelCase__					:  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:
     UpperCAmelCase__					:  Any					   =					force_token_array.at[index].set(A    )
   UpperCAmelCase__					:  Tuple					   =					jnp.intaa(A    )




  def __call__(  self		:			str					,A		:			jnp.ndarray					,A		:			jnp.ndarray					,A		:			int    ):






   '''simple docstring'''
   def _force_token(A		:			str    ):
    UpperCAmelCase__					:  Tuple					   =					scores.shape[0]
    UpperCAmelCase__					:  Dict					   =					self.force_token_array[generation_idx]

    UpperCAmelCase__					:  Dict					   =					jnp.ones_like(A					,dtype=scores.dtype    ) * -float("""inf"""    )
    UpperCAmelCase__					:  Union[str, Any]					   =					jnp.zeros((batch_size, 1)					,dtype=scores.dtype    )
    UpperCAmelCase__					:  Any					   =					lax.dynamic_update_slice(A					,A					,(0, current_token)    )
    return new_scores

   UpperCAmelCase__					:  Tuple					   =					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(A    )					,lambda: scores					,)					,)
   return scores







class      __lowercase			(    __lowerCamelCase					):

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






   '''simple docstring'''
   UpperCAmelCase__					:  Any					   =					generate_config.eos_token_id
   UpperCAmelCase__					:  Union[str, Any]					   =					generate_config.no_timestamps_token_id
   UpperCAmelCase__					:  Tuple					   =					generate_config.no_timestamps_token_id + 1

   UpperCAmelCase__					:  Any					   =					decoder_input_length + 1

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




  def __call__(  self		:			List[str]					,A		:			List[Any]					,A		:			Optional[Any]					,A		:			str    ):






   '''simple docstring'''
   # suppress <|notimestamps|> which is handled by without_timestamps
   UpperCAmelCase__					:  Optional[Any]					   =					scores.at[:, self.no_timestamps_token_id].set(-float("""inf"""    )    )

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

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

    return jnp.where(
        A					,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"""    )    )					,)					,A					,)

   UpperCAmelCase__					:  Tuple					   =					jax.vmap(A    )(A					,A    )

   UpperCAmelCase__					:  Dict					   =					jnp.where(cur_len == self.begin_index					,A					,A    )
   UpperCAmelCase__					:  Dict					   =					jnp.where(
       self.max_initial_timestamp_index is not None					,True and apply_max_initial_timestamp					,A					,)

   UpperCAmelCase__					:  Tuple					   =					self.timestamp_begin + self.max_initial_timestamp_index

   UpperCAmelCase__					:  Optional[Any]					   =					jnp.where(
       A					,scores.at[:, last_allowed + 1 :].set(-float("""inf"""    )    )					,A					,)

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

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

   UpperCAmelCase__					:  Optional[int]					   =					jax.vmap(A    )(A					,A    )

   return scores








"""simple docstring"""




from __future__ import annotations
def   lowerCAmelCase						(					__UpperCamelCase							,    __UpperCamelCase							,    __UpperCamelCase      ):
 '''simple docstring'''





 UpperCAmelCase__					:  Dict					   =					list(range(len(__UpperCamelCase      )      )      )
 UpperCAmelCase__					:  Union[str, Any]					   =					[v / w for v, w in zip(__UpperCamelCase							,    __UpperCamelCase      )]
 index.sort(key=lambda __UpperCamelCase      : ratio[i]							,    reverse=__UpperCamelCase      )

 UpperCAmelCase__					:  float					   =					0
 UpperCAmelCase__					:  list[float]					   =					[0] * len(__UpperCamelCase      )
 for i in index:
  if weight[i] <= capacity:
   UpperCAmelCase__					:  Optional[Any]					   =					1
   max_value += value[i]
   capacity -= weight[i]
  else:
   UpperCAmelCase__					:  Union[str, Any]					   =					capacity / weight[i]
   max_value += value[i] * capacity / weight[i]
   break

 return max_value, fractions


if __name__ == "__main__":
      import doctest

      doctest.testmod()





