




'''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(UpperCamelCase   )
   def __call__(						self   ,				UpperCamelCase   ,				UpperCamelCase   )					->     jnp.ndarray:
     raise NotImplementedError(
         f"{self.__class__} is an abstract class. Only classes inheriting this class can be called."   )





class  __lowercase    :







   @add_start_docstrings(UpperCamelCase   )
   def __call__(						self   ,				UpperCamelCase   ,				UpperCamelCase   )					->     jnp.ndarray:
     raise NotImplementedError(
         f"{self.__class__} is an abstract class. Only classes inheriting this class can be called."   )





class  __lowercase    (	__magic_name__			):







   @add_start_docstrings(UpperCamelCase   )
   def __call__(						self   ,				UpperCamelCase   ,				UpperCamelCase   ,				UpperCamelCase   ,				**UpperCamelCase   )					->     jnp.ndarray:
     for processor in self:
       __a								=       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."   )
         __a								=       processor(UpperCamelCase   ,				UpperCamelCase   ,				UpperCamelCase   ,				**UpperCamelCase   )
       else:
         __a								=       processor(UpperCamelCase   ,				UpperCamelCase   ,				UpperCamelCase   )
     return scores





class  __lowercase    (	__magic_name__			):







   def __init__(						self   ,				UpperCamelCase   )					->     Any:
     if not isinstance(UpperCamelCase   ,				UpperCamelCase   ) or not (temperature > 0):
       raise ValueError(f"`temperature` has to be a strictly positive float, but is {temperature}"   )

     __a								=       temperature







   def __call__(						self   ,				UpperCamelCase   ,				UpperCamelCase   ,				UpperCamelCase   )					->     jnp.ndarray:
     __a								=       scores / self.temperature
     return scores





class  __lowercase    (	__magic_name__			):







   def __init__(						self   ,				UpperCamelCase   ,				UpperCamelCase = -float('Inf'   )   ,				UpperCamelCase = 1   )					->     Any:
     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}"   )

     __a								=       top_p
     __a								=       filter_value
     __a								=       min_tokens_to_keep







   def __call__(						self   ,				UpperCamelCase   ,				UpperCamelCase   ,				UpperCamelCase   )					->     jnp.ndarray:
     __a						,							__a								=       lax.top_k(UpperCamelCase   ,				scores.shape[-1]   )

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

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

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

     __a								=       jnp.where(UpperCamelCase   ,				UpperCamelCase   ,				UpperCamelCase   )
     __a								=       jax.lax.sort_key_val(UpperCamelCase   ,				UpperCamelCase   )[-1]

     return next_scores





class  __lowercase    (	__magic_name__			):







   def __init__(						self   ,				UpperCamelCase   ,				UpperCamelCase = -float('Inf'   )   ,				UpperCamelCase = 1   )					->     str:
     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}"   )

     __a								=       max(UpperCamelCase   ,				UpperCamelCase   )
     __a								=       filter_value







   def __call__(						self   ,				UpperCamelCase   ,				UpperCamelCase   ,				UpperCamelCase   )					->     jnp.ndarray:
     __a						,							__a								=       scores.shape
     __a								=       jnp.full(batch_size * vocab_size   ,				self.filter_value   )

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

     __a								=       next_scores_flat.at[topk_indices_flat].set(UpperCamelCase   )
     __a								=       next_scores_flat.reshape(UpperCamelCase   ,				UpperCamelCase   )
     return next_scores





class  __lowercase    (	__magic_name__			):







   def __init__(						self   ,				UpperCamelCase   )					->     Dict:
     __a								=       bos_token_id







   def __call__(						self   ,				UpperCamelCase   ,				UpperCamelCase   ,				UpperCamelCase   )					->     jnp.ndarray:
     __a								=       jnp.full(scores.shape   ,				-float('inf'   )   )

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

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

     return scores





class  __lowercase    (	__magic_name__			):







   def __init__(						self   ,				UpperCamelCase   ,				UpperCamelCase   )					->     List[str]:
     __a								=       max_length
     __a								=       eos_token_id







   def __call__(						self   ,				UpperCamelCase   ,				UpperCamelCase   ,				UpperCamelCase   )					->     jnp.ndarray:
     __a								=       jnp.full(scores.shape   ,				-float('inf'   )   )

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

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

     return scores





class  __lowercase    (	__magic_name__			):







   def __init__(						self   ,				UpperCamelCase   ,				UpperCamelCase   )					->     List[Any]:
     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}"   )

     __a								=       min_length
     __a								=       eos_token_id







   def __call__(						self   ,				UpperCamelCase   ,				UpperCamelCase   ,				UpperCamelCase   )					->     jnp.ndarray:
     # create boolean flag to decide if min length penalty should be applied
     __a								=       1 - jnp.clip(cur_len - self.min_length   ,				0   ,				1   )

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

     return scores





class  __lowercase    (	__magic_name__			):







   def __init__(						self   ,				UpperCamelCase   ,				UpperCamelCase   )					->     Optional[int]:
     __a								=       list(UpperCamelCase   )
     __a								=       begin_index







   def __call__(						self   ,				UpperCamelCase   ,				UpperCamelCase   ,				UpperCamelCase   )					->     Dict:
     __a								=       1 - jnp.bool_(cur_len - self.begin_index   )

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

     return scores





class  __lowercase    (	__magic_name__			):







   def __init__(						self   ,				UpperCamelCase   )					->     Optional[Any]:
     __a								=       list(UpperCamelCase   )







   def __call__(						self   ,				UpperCamelCase   ,				UpperCamelCase   ,				UpperCamelCase   )					->     jnp.ndarray:
     __a								=       scores.at[..., self.suppress_tokens].set(-float('inf'   )   )

     return scores





class  __lowercase    (	__magic_name__			):







   def __init__(						self   ,				UpperCamelCase   )					->     Any:
     __a								=       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.
     __a								=       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:
         __a								=       force_token_array.at[index].set(UpperCamelCase   )
     __a								=       jnp.intaa(UpperCamelCase   )







   def __call__(						self   ,				UpperCamelCase   ,				UpperCamelCase   ,				UpperCamelCase   )					->     jnp.ndarray:
     def _force_token(UpperCamelCase   ):
       __a								=       scores.shape[0]
       __a								=       self.force_token_array[generation_idx]

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

     __a								=       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  __lowercase    (	__magic_name__			):







   def __init__(						self   ,				UpperCamelCase   ,				UpperCamelCase   ,				UpperCamelCase   )					->     str:
     __a								=       generate_config.eos_token_id
     __a								=       generate_config.no_timestamps_token_id
     __a								=       generate_config.no_timestamps_token_id + 1

     __a								=       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'   ):
       __a								=       generate_config.max_initial_timestamp_index
     else:
       __a								=       model_config.vocab_size
     if self.max_initial_timestamp_index is None:
       __a								=       model_config.vocab_size







   def __call__(						self   ,				UpperCamelCase   ,				UpperCamelCase   ,				UpperCamelCase   )					->     Optional[Any]:
     # suppress <|notimestamps|> which is handled by without_timestamps
     __a								=       scores.at[:, self.no_timestamps_token_id].set(-float('inf'   )   )

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

       __a								=       jnp.where((cur_len - self.begin_index) < 2   ,				UpperCamelCase   ,				UpperCamelCase   )
       __a								=       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   ,				)

     __a								=       jax.vmap(UpperCamelCase   )(UpperCamelCase   ,				UpperCamelCase   )

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

     __a								=       self.timestamp_begin + self.max_initial_timestamp_index

     __a								=       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
     __a								=       jax.nn.log_softmax(UpperCamelCase   ,				axis=-1   )

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

     __a								=       jax.vmap(UpperCamelCase   )(UpperCamelCase   ,				UpperCamelCase   )

     return scores









'''simple docstring'''


class  __lowercase    :  # Public class to implement a graph







   def __init__(						self   ,				UpperCamelCase   ,				UpperCamelCase   ,				UpperCamelCase   )					->     None:
     __a								=       row
     __a								=       col
     __a								=       graph







   def 		UpperCamelCase__      (						self   ,				UpperCamelCase   ,				UpperCamelCase   ,				UpperCamelCase   )					->     bool:
     return (
         0 <= i < self.ROW
         and 0 <= j < self.COL
         and not visited[i][j]
         and self.graph[i][j]
     )







   def 		UpperCamelCase__      (						self   ,				UpperCamelCase   ,				UpperCamelCase   ,				UpperCamelCase   )					->     None:
     # Checking all 8 elements surrounding nth element
     __a								=       [-1, -1, -1, 0, 0, 1, 1, 1]  # Coordinate order
     __a								=       [-1, 0, 1, -1, 1, -1, 0, 1]
     __a								=       True  # Make those cells visited
     for k in range(8   ):
       if self.is_safe(i + row_nbr[k]   ,				j + col_nbr[k]   ,				UpperCamelCase   ):
         self.diffs(i + row_nbr[k]   ,				j + col_nbr[k]   ,				UpperCamelCase   )







   def 		UpperCamelCase__      (						self   )					->     int:  # And finally, count all islands.
     __a								=       [[False for j in range(self.COL   )] for i in range(self.ROW   )]
     __a								=       0
     for i in range(self.ROW   ):
       for j in range(self.COL   ):
         if visited[i][j] is False and self.graph[i][j] == 1:
           self.diffs(UpperCamelCase   ,				UpperCamelCase   ,				UpperCamelCase   )
           count += 1
     return count



