
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


_lowerCamelCase       :				Optional[Any]       =			get_logger(__name__)


_lowerCamelCase       :				Optional[Any]       =			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			,  lowercase	:    int			,  lowercase	:    str	):


				'''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	:    int			,  lowercase	:    Optional[Any]			,  lowercase	:    Union[str, Any]	):


				'''simple docstring'''


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




class    SCREAMING_SNAKE_CASE__     (	__A					):





	'''simple docstring'''



	@add_start_docstrings(__UpperCAmelCase	)
	def __call__(  self	:    Optional[Any]			,  lowercase	:    Union[str, Any]			,  lowercase	:    Tuple			,  lowercase	:    Tuple			,  **lowercase	:    Dict	):


				'''simple docstring'''


				for processor in self:
							_snake_case		=			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.'''	)
										_snake_case		=			processor(__UpperCAmelCase			,  __UpperCAmelCase			,  __UpperCAmelCase			,  **__UpperCAmelCase	)
							else:
										_snake_case		=			processor(__UpperCAmelCase			,  __UpperCAmelCase			,  __UpperCAmelCase	)
				return scores




class    SCREAMING_SNAKE_CASE__     (	__A					):





	'''simple docstring'''



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


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

				_snake_case		=			temperature





	def __call__(  self	:    int			,  lowercase	:    Optional[Any]			,  lowercase	:    Any			,  lowercase	:    Union[str, Any]	):


				'''simple docstring'''


				_snake_case		=			scores / self.temperature
				return scores




class    SCREAMING_SNAKE_CASE__     (	__A					):





	'''simple docstring'''



	def __init__(  self	:    str			,  lowercase	:    Optional[int]			,  lowercase	:    Dict = -float('Inf'	)			,  lowercase	:    Optional[int] = 1	):


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

				_snake_case		=			top_p
				_snake_case		=			filter_value
				_snake_case		=			min_tokens_to_keep





	def __call__(  self	:    Any			,  lowercase	:    str			,  lowercase	:    Union[str, Any]			,  lowercase	:    int	):


				'''simple docstring'''


				_snake_case	,					_snake_case		=			lax.top_k(__UpperCAmelCase			,  scores.shape[-1]	)

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

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

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

				_snake_case		=			jnp.where(__UpperCAmelCase			,  __UpperCAmelCase			,  __UpperCAmelCase	)
				_snake_case		=			jax.lax.sort_key_val(__UpperCAmelCase			,  __UpperCAmelCase	)[-1]

				return next_scores




class    SCREAMING_SNAKE_CASE__     (	__A					):





	'''simple docstring'''



	def __init__(  self	:    Dict			,  lowercase	:    str			,  lowercase	:    str = -float('Inf'	)			,  lowercase	:    Tuple = 1	):


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

				_snake_case		=			max(__UpperCAmelCase			,  __UpperCAmelCase	)
				_snake_case		=			filter_value





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


				'''simple docstring'''


				_snake_case	,					_snake_case		=			scores.shape
				_snake_case		=			jnp.full(batch_size * vocab_size			,  self.filter_value	)

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

				_snake_case		=			next_scores_flat.at[topk_indices_flat].set(__UpperCAmelCase	)
				_snake_case		=			next_scores_flat.reshape(__UpperCAmelCase			,  __UpperCAmelCase	)
				return next_scores




class    SCREAMING_SNAKE_CASE__     (	__A					):





	'''simple docstring'''



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


				'''simple docstring'''


				_snake_case		=			bos_token_id





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


				'''simple docstring'''


				_snake_case		=			jnp.full(scores.shape			,  -float('inf'	)	)

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

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

				return scores




class    SCREAMING_SNAKE_CASE__     (	__A					):





	'''simple docstring'''



	def __init__(  self	:    Dict			,  lowercase	:    Optional[int]			,  lowercase	:    Union[str, Any]	):


				'''simple docstring'''


				_snake_case		=			max_length
				_snake_case		=			eos_token_id





	def __call__(  self	:    List[str]			,  lowercase	:    List[str]			,  lowercase	:    List[str]			,  lowercase	:    Tuple	):


				'''simple docstring'''


				_snake_case		=			jnp.full(scores.shape			,  -float('inf'	)	)

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

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

				return scores




class    SCREAMING_SNAKE_CASE__     (	__A					):





	'''simple docstring'''



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


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

				_snake_case		=			min_length
				_snake_case		=			eos_token_id





	def __call__(  self	:    str			,  lowercase	:    int			,  lowercase	:    List[str]			,  lowercase	:    int	):


				'''simple docstring'''


				_snake_case		=			1 - jnp.clip(cur_len - self.min_length			,  0			,  1	)

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

				return scores




class    SCREAMING_SNAKE_CASE__     (	__A					):





	'''simple docstring'''



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


				'''simple docstring'''


				_snake_case		=			list(__UpperCAmelCase	)
				_snake_case		=			begin_index





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


				'''simple docstring'''


				_snake_case		=			1 - jnp.bool_(cur_len - self.begin_index	)

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

				return scores




class    SCREAMING_SNAKE_CASE__     (	__A					):





	'''simple docstring'''



	def __init__(  self	:    List[str]			,  lowercase	:    Tuple	):


				'''simple docstring'''


				_snake_case		=			list(__UpperCAmelCase	)





	def __call__(  self	:    Tuple			,  lowercase	:    Any			,  lowercase	:    Optional[Any]			,  lowercase	:    Any	):


				'''simple docstring'''


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

				return scores




class    SCREAMING_SNAKE_CASE__     (	__A					):





	'''simple docstring'''



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


				'''simple docstring'''


				_snake_case		=			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.
				_snake_case		=			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:
										_snake_case		=			force_token_array.at[index].set(__UpperCAmelCase	)
				_snake_case		=			jnp.intaa(__UpperCAmelCase	)





	def __call__(  self	:    List[str]			,  lowercase	:    Dict			,  lowercase	:    Optional[Any]			,  lowercase	:    int	):


				'''simple docstring'''


				def _force_token(lowercase	:    str	):
							_snake_case		=			scores.shape[0]
							_snake_case		=			self.force_token_array[generation_idx]

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

				_snake_case		=			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__     (	__A					):





	'''simple docstring'''



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


				'''simple docstring'''


				_snake_case		=			generate_config.eos_token_id
				_snake_case		=			generate_config.no_timestamps_token_id
				_snake_case		=			generate_config.no_timestamps_token_id + 1

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





	def __call__(  self	:    Optional[int]			,  lowercase	:    Optional[int]			,  lowercase	:    Optional[int]			,  lowercase	:    Union[str, Any]	):


				'''simple docstring'''


				_snake_case		=			scores.at[:, self.no_timestamps_token_id].set(-float('inf'	)	)

				def handle_pairs(lowercase	:    List[str]			,  lowercase	:    List[str]	):
							_snake_case		=			jnp.where((cur_len - self.begin_index) >= 1			,  __UpperCAmelCase			,  __UpperCAmelCase	)
							_snake_case		=			jnp.where(
							    input_ids_k[cur_len - 1] >= self.timestamp_begin			,  True and last_was_timestamp			,  __UpperCAmelCase			,  )

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

				_snake_case		=			jax.vmap(__UpperCAmelCase	)(__UpperCAmelCase			,  __UpperCAmelCase	)

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

				_snake_case		=			self.timestamp_begin + self.max_initial_timestamp_index

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

				def handle_cumulative_probs(lowercase	:    Union[str, Any]			,  lowercase	:    Optional[int]	):
							_snake_case		=			jax.nn.logsumexp(logprobs_k[self.timestamp_begin :]			,  axis=-1	)
							_snake_case		=			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			,  )

				_snake_case		=			jax.vmap(__UpperCAmelCase	)(__UpperCAmelCase			,  __UpperCAmelCase	)

				return scores
"""simple docstring"""




import contextlib
import importlib
import io
import unittest

import transformers

# Try to import everything from transformers to ensure every object can be loaded.
from transformers import *  # noqa F406
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, require_flax, require_tf, require_torch
from transformers.utils import ContextManagers, find_labels, is_flax_available, is_tf_available, is_torch_available


if is_torch_available():
				from transformers import BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification

if is_tf_available():
				from transformers import TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification

if is_flax_available():
				from transformers import FlaxBertForPreTraining, FlaxBertForQuestionAnswering, FlaxBertForSequenceClassification


__lowerCamelCase							 =     DUMMY_UNKNOWN_IDENTIFIER
# An actual model hosted on huggingface.co

__lowerCamelCase							 =     "main"
# Default branch name
__lowerCamelCase							 =     "f2c752cfc5c0ab6f4bdec59acea69eefbee381c2"
# One particular commit (not the top of `main`)
__lowerCamelCase							 =     "aaaaaaa"
# This commit does not exist, so we should 404.

__lowerCamelCase							 =     "d9e9f15bc825e4b2c9249e9578f884bbcb5e3684"
# Sha-1 of config.json on the top of `main`, for checking purposes
__lowerCamelCase							 =     "4b243c475af8d0a7754e87d7d096c92e5199ec2fe168a2ee7998e3b8e9bcb1d3"






@contextlib.contextmanager
def      UpperCAmelCase    (		):






							"""simple docstring"""





							print('Welcome!' )
							yield
							print('Bye!' )






@contextlib.contextmanager
def      UpperCAmelCase    (		):






							"""simple docstring"""





							print('Bonjour!' )
							yield
							print('Au revoir!' )
class 			UpperCamelCase__(	unittest.TestCase       ):





						def  snake_case__		(				self   )    -> List[str]:
													# If the spec is missing, importlib would not be able to import the module dynamically.
													assert transformers.__spec__ is not None
													assert importlib.util.find_spec('transformers'   ) is not None






class 			UpperCamelCase__(	unittest.TestCase       ):





						@unittest.mock.patch('sys.stdout'						,new_callable=io.StringIO   )
						def  snake_case__		(				self						,__UpperCAmelCase   )    -> Dict:
													with ContextManagers([]   ):
																				print('Transformers are awesome!'   )
													# The print statement adds a new line at the end of the output
													self.assertEqual(mock_stdout.getvalue()						,'Transformers are awesome!\n'   )





						@unittest.mock.patch('sys.stdout'						,new_callable=io.StringIO   )
						def  snake_case__		(				self						,__UpperCAmelCase   )    -> List[str]:
													with ContextManagers([context_en()]   ):
																				print('Transformers are awesome!'   )
													# The output should be wrapped with an English welcome and goodbye
													self.assertEqual(mock_stdout.getvalue()						,'Welcome!\nTransformers are awesome!\nBye!\n'   )





						@unittest.mock.patch('sys.stdout'						,new_callable=io.StringIO   )
						def  snake_case__		(				self						,__UpperCAmelCase   )    -> Any:
													with ContextManagers([context_fr(), context_en()]   ):
																				print('Transformers are awesome!'   )
													# The output should be wrapped with an English and French welcome and goodbye
													self.assertEqual(mock_stdout.getvalue()						,'Bonjour!\nWelcome!\nTransformers are awesome!\nBye!\nAu revoir!\n'   )





						@require_torch
						def  snake_case__		(				self   )    -> Union[str, Any]:
													self.assertEqual(find_labels(__UpperCAmelCase   )						,['labels']   )
													self.assertEqual(find_labels(__UpperCAmelCase   )						,['labels', 'next_sentence_label']   )
													self.assertEqual(find_labels(__UpperCAmelCase   )						,['start_positions', 'end_positions']   )
													class 			UpperCamelCase__(	__A       ):
																			pass






													self.assertEqual(find_labels(__UpperCAmelCase   )						,['labels']   )





						@require_tf
						def  snake_case__		(				self   )    -> str:
													self.assertEqual(find_labels(__UpperCAmelCase   )						,['labels']   )
													self.assertEqual(find_labels(__UpperCAmelCase   )						,['labels', 'next_sentence_label']   )
													self.assertEqual(find_labels(__UpperCAmelCase   )						,['start_positions', 'end_positions']   )
													class 			UpperCamelCase__(	__A       ):
																			pass






													self.assertEqual(find_labels(__UpperCAmelCase   )						,['labels']   )





						@require_flax
						def  snake_case__		(				self   )    -> List[Any]:
													# Flax models don't have labels
													self.assertEqual(find_labels(__UpperCAmelCase   )						,[]   )
													self.assertEqual(find_labels(__UpperCAmelCase   )						,[]   )
													self.assertEqual(find_labels(__UpperCAmelCase   )						,[]   )
													class 			UpperCamelCase__(	__A       ):
																			pass






													self.assertEqual(find_labels(__UpperCAmelCase   )						,[]   )





