




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"""
    Args:
        input_ids (`jnp.ndarray` of shape `(batch_size, sequence_length)`):
            Indices of input sequence tokens in the vocabulary.

            Indices can be obtained using [`PreTrainedTokenizer`]. See [`PreTrainedTokenizer.encode`] and
            [`PreTrainedTokenizer.__call__`] for details.

            [What are input IDs?](../glossary#input-ids)
        scores (`jnp.ndarray` of shape `(batch_size, config.vocab_size)`):
            Prediction scores of a language modeling head. These can be logits for each vocabulary when not using beam
            search or log softmax for each vocabulary token when using beam search
        kwargs (`Dict[str, Any]`, *optional*):
            Additional logits processor specific kwargs.

    Return:
        `jnp.ndarray` of shape `(batch_size, config.vocab_size)`: The processed prediction scores.

"""







class     __lowerCAmelCase :

			"""simple docstring"""







			@add_start_docstrings(lowerCamelCase__							)
			def __call__(      self			,						lowerCamelCase__			,						lowerCamelCase__							)    ->      Optional[int]:



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







class     __lowerCAmelCase :

			"""simple docstring"""







			@add_start_docstrings(lowerCamelCase__							)
			def __call__(      self			,						lowerCamelCase__			,						lowerCamelCase__							)    ->      Any:



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







class     __lowerCAmelCase (       snake_case__ ):

			"""simple docstring"""







			@add_start_docstrings(lowerCamelCase__							)
			def __call__(      self			,						lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__			,						**lowerCamelCase__							)    ->      Optional[Any]:



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







class     __lowerCAmelCase (       snake_case__ ):

			"""simple docstring"""







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



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

							__lowerCamelCase		       =    temperature






			def __call__(      self			,						lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__							)    ->      List[Any]:



							'''simple docstring'''
							__lowerCamelCase		       =    scores / self.temperature
							return scores







class     __lowerCAmelCase (       snake_case__ ):

			"""simple docstring"""







			def __init__(      self			,						lowerCamelCase__			,						lowerCamelCase__ = -float('Inf'							)			,						lowerCamelCase__ = 1							)    ->      Tuple:



							'''simple docstring'''
							if not isinstance(lowerCamelCase__			,						lowerCamelCase__							) 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(lowerCamelCase__			,						lowerCamelCase__							) 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		       =    top_p
							__lowerCamelCase		       =    filter_value
							__lowerCamelCase		       =    min_tokens_to_keep






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



							'''simple docstring'''
							__lowerCamelCase		       =    lax.top_k(lowerCamelCase__			,						scores.shape[-1]							)

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

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

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

							__lowerCamelCase		       =    jnp.where(lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__							)
							__lowerCamelCase		       =    jax.lax.sort_key_val(lowerCamelCase__			,						lowerCamelCase__							)[-1]

							return next_scores







class     __lowerCAmelCase (       snake_case__ ):

			"""simple docstring"""







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



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

							__lowerCamelCase		       =    max(lowerCamelCase__			,						lowerCamelCase__							)
							__lowerCamelCase		       =    filter_value






			def __call__(      self			,						lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__							)    ->      Any:



							'''simple docstring'''
							__lowerCamelCase		       =    scores.shape
							__lowerCamelCase		       =    jnp.full(batch_size * vocab_size			,						self.filter_value							)

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

							__lowerCamelCase		       =    next_scores_flat.at[topk_indices_flat].set(lowerCamelCase__							)
							__lowerCamelCase		       =    next_scores_flat.reshape(lowerCamelCase__			,						lowerCamelCase__							)
							return next_scores







class     __lowerCAmelCase (       snake_case__ ):

			"""simple docstring"""







			def __init__(      self			,						lowerCamelCase__							)    ->      Optional[int]:



							'''simple docstring'''
							__lowerCamelCase		       =    bos_token_id






			def __call__(      self			,						lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__							)    ->      str:



							'''simple docstring'''
							__lowerCamelCase		       =    jnp.full(scores.shape			,						-float('inf'							)							)

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

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

							return scores







class     __lowerCAmelCase (       snake_case__ ):

			"""simple docstring"""







			def __init__(      self			,						lowerCamelCase__			,						lowerCamelCase__							)    ->      Dict:



							'''simple docstring'''
							__lowerCamelCase		       =    max_length
							__lowerCamelCase		       =    eos_token_id






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



							'''simple docstring'''
							__lowerCamelCase		       =    jnp.full(scores.shape			,						-float('inf'							)							)

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

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

							return scores







class     __lowerCAmelCase (       snake_case__ ):

			"""simple docstring"""







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



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

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

							__lowerCamelCase		       =    min_length
							__lowerCamelCase		       =    eos_token_id






			def __call__(      self			,						lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__							)    ->      str:



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

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

							return scores







class     __lowerCAmelCase (       snake_case__ ):

			"""simple docstring"""







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



							'''simple docstring'''
							__lowerCamelCase		       =    list(lowerCamelCase__							)
							__lowerCamelCase		       =    begin_index






			def __call__(      self			,						lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__							)    ->      str:



							'''simple docstring'''
							__lowerCamelCase		       =    1 - jnp.bool_(cur_len - self.begin_index							)

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

							return scores







class     __lowerCAmelCase (       snake_case__ ):

			"""simple docstring"""







			def __init__(      self			,						lowerCamelCase__							)    ->      Optional[int]:



							'''simple docstring'''
							__lowerCamelCase		       =    list(lowerCamelCase__							)






			def __call__(      self			,						lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__							)    ->      Optional[Any]:



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

							return scores







class     __lowerCAmelCase (       snake_case__ ):

			"""simple docstring"""







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



							'''simple docstring'''
							__lowerCamelCase		       =    dict(lowerCamelCase__							)
							# 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		       =    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		       =    force_token_array.at[index].set(lowerCamelCase__							)
							__lowerCamelCase		       =    jnp.intaa(lowerCamelCase__							)






			def __call__(      self			,						lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__							)    ->      int:



							'''simple docstring'''
							def _force_token(lowerCamelCase__							):
											__lowerCamelCase		       =    scores.shape[0]
											__lowerCamelCase		       =    self.force_token_array[generation_idx]

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

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







class     __lowerCAmelCase (       snake_case__ ):

			"""simple docstring"""







			def __init__(      self			,						lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__							)    ->      List[str]:



							'''simple docstring'''
							__lowerCamelCase		       =    generate_config.eos_token_id
							__lowerCamelCase		       =    generate_config.no_timestamps_token_id
							__lowerCamelCase		       =    generate_config.no_timestamps_token_id + 1

							__lowerCamelCase		       =    decoder_input_length + 1

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






			def __call__(      self			,						lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__							)    ->      Optional[int]:



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

							def handle_pairs(lowerCamelCase__			,						lowerCamelCase__							):
											__lowerCamelCase		       =    jnp.where((cur_len - self.begin_index) >= 1			,						lowerCamelCase__			,						lowerCamelCase__							)
											__lowerCamelCase		       =    jnp.where(
											    input_ids_k[cur_len - 1] >= self.timestamp_begin			,						True and last_was_timestamp			,						lowerCamelCase__			,						)

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

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

							__lowerCamelCase		       =    jax.vmap(lowerCamelCase__							)(lowerCamelCase__			,						lowerCamelCase__							)

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

							__lowerCamelCase		       =    self.timestamp_begin + self.max_initial_timestamp_index

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

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

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

							__lowerCamelCase		       =    jax.vmap(lowerCamelCase__							)(lowerCamelCase__			,						lowerCamelCase__							)

							return scores



'''simple docstring'''




import math
from typing import List, Optional, Tuple, Union

import numpy as np
import torch

from ..configuration_utils import ConfigMixin, register_to_config
from .scheduling_utils import SchedulerMixin, SchedulerOutput

class 	lowerCamelCase_	(snake_case__							, snake_case__    ):
      '''simple docstring'''

      __UpperCamelCase:  Optional[Any]						=						1




      @register_to_config
      def __init__(       self						:				Optional[int]						,					A						:				int = 1000						,					A						:				Optional[Union[np.ndarray, List[float]]] = None       ):
             # set `betas`, `alphas`, `timesteps`
             self.set_timesteps(A       )

             # standard deviation of the initial noise distribution
             _UpperCAmelCase     :  int							      =    1.0

             # For now we only support F-PNDM, i.e. the runge-kutta method
             # For more information on the algorithm please take a look at the paper: https://arxiv.org/pdf/2202.09778.pdf
             # mainly at formula (9), (12), (13) and the Algorithm 2.
             _UpperCAmelCase     :  int							      =    4

             # running values
             _UpperCAmelCase     :  Dict							      =    []




      def      _A	(       self						:				Optional[int]						,					A						:				int						,					A						:				Union[str, torch.device] = None       ):
             _UpperCAmelCase     :  int							      =    num_inference_steps
             _UpperCAmelCase     :  Union[str, Any]							      =    torch.linspace(1						,					0						,					num_inference_steps + 1       )[:-1]
             _UpperCAmelCase     :  Any							      =    torch.cat([steps, torch.tensor([0.0]       )]       )

             if self.config.trained_betas is not None:
                    _UpperCAmelCase     :  str							      =    torch.tensor(self.config.trained_betas						,					dtype=torch.floataa       )
             else:
                    _UpperCAmelCase     :  Dict							      =    torch.sin(steps * math.pi / 2       ) ** 2

             _UpperCAmelCase     :  List[Any]							      =    (1.0 - self.betas**2) ** 0.5

             _UpperCAmelCase     :  List[str]							      =    (torch.atana(self.betas						,					self.alphas       ) / math.pi * 2)[:-1]
             _UpperCAmelCase     :  Dict							      =    timesteps.to(A       )

             _UpperCAmelCase     :  Dict							      =    []




      def      _A	(       self						:				Optional[int]						,					A						:				torch.FloatTensor						,					A						:				int						,					A						:				torch.FloatTensor						,					A						:				bool = True						,					):
             if self.num_inference_steps is None:
                    raise ValueError(
                        "Number of inference steps is 'None', you need to run 'set_timesteps' after creating the scheduler"       )

             _UpperCAmelCase     :  Tuple							      =    (self.timesteps == timestep).nonzero().item()
             _UpperCAmelCase     :  Optional[Any]							      =    timestep_index + 1

             _UpperCAmelCase     :  int							      =    sample * self.betas[timestep_index] + model_output * self.alphas[timestep_index]
             self.ets.append(A       )

             if len(self.ets       ) == 1:
                    _UpperCAmelCase     :  List[Any]							      =    self.ets[-1]
             elif len(self.ets       ) == 2:
                    _UpperCAmelCase     :  str							      =    (3 * self.ets[-1] - self.ets[-2]) / 2
             elif len(self.ets       ) == 3:
                    _UpperCAmelCase     :  Tuple							      =    (23 * self.ets[-1] - 16 * self.ets[-2] + 5 * self.ets[-3]) / 12
             else:
                    _UpperCAmelCase     :  Union[str, Any]							      =    (1 / 24) * (55 * self.ets[-1] - 59 * self.ets[-2] + 37 * self.ets[-3] - 9 * self.ets[-4])

             _UpperCAmelCase     :  Union[str, Any]							      =    self._get_prev_sample(A						,					A						,					A						,					A       )

             if not return_dict:
                    return (prev_sample,)

             return SchedulerOutput(prev_sample=A       )




      def      _A	(       self						:				Union[str, Any]						,					A						:				torch.FloatTensor						,					*A						:				Union[str, Any]						,					**A						:				Dict       ):
             return sample




      def      _A	(       self						:				Optional[Any]						,					A						:				Optional[int]						,					A						:				int						,					A						:				Optional[Any]						,					A						:				List[str]       ):
             _UpperCAmelCase     :  List[str]							      =    self.alphas[timestep_index]
             _UpperCAmelCase     :  List[Any]							      =    self.betas[timestep_index]

             _UpperCAmelCase     :  Optional[Any]							      =    self.alphas[prev_timestep_index]
             _UpperCAmelCase     :  Dict							      =    self.betas[prev_timestep_index]

             _UpperCAmelCase     :  Tuple							      =    (sample - sigma * ets) / max(A						,					1E-8       )
             _UpperCAmelCase     :  List[str]							      =    next_alpha * pred + ets * next_sigma

             return prev_sample





      def __len__(       self						:				Union[str, Any]       ):
             return self.config.num_train_timesteps

