



'''simple docstring'''






import unittest

import numpy as np

from transformers import is_flax_available
from transformers.testing_utils import require_flax

from ..test_modeling_flax_common import ids_tensor


if is_flax_available():
						import jax
						import jax.numpy as jnp

						from transformers.generation import (
						    FlaxForcedBOSTokenLogitsProcessor,
						    FlaxForcedEOSTokenLogitsProcessor,
						    FlaxLogitsProcessorList,
						    FlaxMinLengthLogitsProcessor,
						    FlaxTemperatureLogitsWarper,
						    FlaxTopKLogitsWarper,
						    FlaxTopPLogitsWarper,
						)

@require_flax
class        SCREAMING_SNAKE_CASE(							unittest.TestCase    ):







	"""simple docstring"""






	def   A			(		self    :  Any	,    __snake_case    :  int	,    __snake_case    :  int	)    ->	Any:
								UpperCAmelCase				: Optional[Any]											=	jnp.ones((batch_size, length)	) / length
								return scores







	def   A			(		self    :  str	)    ->	List[Any]:
								UpperCAmelCase				: Dict											=	None
								UpperCAmelCase				: int											=	20

								UpperCAmelCase				: Dict											=	self._get_uniform_logits(batch_size=2	,    length=__snake_case	)

								# tweak scores to not be uniform anymore
								UpperCAmelCase				: Dict											=	scores.at[1, 5].set((1 / length) + 0.1	)  # peak, 1st batch
								UpperCAmelCase				: Optional[Any]											=	scores.at[1, 10].set((1 / length) - 0.4	)  # valley, 1st batch

								# compute softmax
								UpperCAmelCase				: Optional[Any]											=	jax.nn.softmax(__snake_case	,    axis=-1	)

								UpperCAmelCase				: str											=	FlaxTemperatureLogitsWarper(temperature=0.5	)
								UpperCAmelCase				: List[str]											=	FlaxTemperatureLogitsWarper(temperature=1.3	)

								UpperCAmelCase				: str											=	jax.nn.softmax(temp_dist_warper_sharper(__snake_case	,    scores.copy()	,    cur_len=__snake_case	)	,    axis=-1	)
								UpperCAmelCase				: Dict											=	jax.nn.softmax(temp_dist_warper_smoother(__snake_case	,    scores.copy()	,    cur_len=__snake_case	)	,    axis=-1	)

								# uniform distribution stays uniform
								self.assertTrue(jnp.allclose(probs[0, :]	,    warped_prob_sharp[0, :]	,    atol=1E-3	)	)
								self.assertTrue(jnp.allclose(probs[0, :]	,    warped_prob_smooth[0, :]	,    atol=1E-3	)	)

								# sharp peaks get higher, valleys get lower
								self.assertLess(probs[1, :].max()	,    warped_prob_sharp[1, :].max()	)
								self.assertGreater(probs[1, :].min()	,    warped_prob_sharp[1, :].min()	)

								# smooth peaks get lower, valleys get higher
								self.assertGreater(probs[1, :].max()	,    warped_prob_smooth[1, :].max()	)
								self.assertLess(probs[1, :].min()	,    warped_prob_smooth[1, :].min()	)







	def   A			(		self    :  Union[str, Any]	)    ->	Any:
								UpperCAmelCase				: Tuple											=	None
								UpperCAmelCase				: Union[str, Any]											=	10
								UpperCAmelCase				: Tuple											=	2

								# create ramp distribution
								UpperCAmelCase				: Any											=	np.broadcast_to(np.arange(__snake_case	)[None, :]	,    (batch_size, vocab_size)	).copy()
								UpperCAmelCase				: Optional[int]											=	ramp_logits[1:, : vocab_size // 2] + vocab_size

								UpperCAmelCase				: List[str]											=	FlaxTopKLogitsWarper(3	)

								UpperCAmelCase				: int											=	top_k_warp(__snake_case	,    __snake_case	,    cur_len=__snake_case	)

								# check that correct tokens are filtered
								self.assertListEqual(jnp.isinf(scores[0]	).tolist()	,    7 * [True] + 3 * [False]	)
								self.assertListEqual(jnp.isinf(scores[1]	).tolist()	,    2 * [True] + 3 * [False] + 5 * [True]	)

								# check special case
								UpperCAmelCase				: List[str]											=	5
								UpperCAmelCase				: Optional[Any]											=	FlaxTopKLogitsWarper(top_k=1	,    filter_value=0.0	,    min_tokens_to_keep=3	)

								UpperCAmelCase				: Dict											=	np.broadcast_to(np.arange(__snake_case	)[None, :]	,    (batch_size, length)	).copy()
								UpperCAmelCase				: List[Any]											=	top_k_warp_safety_check(__snake_case	,    __snake_case	,    cur_len=__snake_case	)

								# min_tokens overwrites k: 3 tokens are kept => 2 tokens are nullified
								self.assertListEqual((scores == 0.0).sum(axis=-1	).tolist()	,    [2, 2]	)







	def   A			(		self    :  str	)    ->	Union[str, Any]:
								UpperCAmelCase				: Optional[Any]											=	None
								UpperCAmelCase				: Optional[int]											=	10
								UpperCAmelCase				: Optional[Any]											=	2

								# create distribution and take log (inverse to Softmax as taken in TopPLogitsWarper)
								UpperCAmelCase				: Tuple											=	np.log(np.array([[0.3, 0.1, 0.1, 0.5], [0.15, 0.3, 0.3, 0.25]]	)	)

								UpperCAmelCase				: Optional[int]											=	FlaxTopPLogitsWarper(0.8	)
								UpperCAmelCase				: Dict											=	np.exp(top_p_warp(__snake_case	,    __snake_case	,    cur_len=__snake_case	)	)

								# dist should be filtered to keep min num values so that sum is >= top_p
								# exp (-inf) => 0
								UpperCAmelCase				: Dict											=	np.array([[0.3, 0.0, 0.0, 0.5], [0.0, 0.3, 0.3, 0.25]]	)
								self.assertTrue(np.allclose(__snake_case	,    __snake_case	,    atol=1E-3	)	)

								# check edge cases with negative and extreme logits
								UpperCAmelCase				: Union[str, Any]											=	np.broadcast_to(np.arange(__snake_case	)[None, :]	,    (batch_size, vocab_size)	).copy() - (
								    vocab_size // 2
								)

								# make ramp_logits more extreme
								UpperCAmelCase				: List[str]											=	ramp_logits[1] * 1_00.0

								# make sure at least 2 tokens are kept
								UpperCAmelCase				: Optional[int]											=	FlaxTopPLogitsWarper(0.9	,    min_tokens_to_keep=2	,    filter_value=0.0	)
								UpperCAmelCase				: Optional[int]											=	top_p_warp(__snake_case	,    __snake_case	,    cur_len=__snake_case	)

								# first batch should keep three tokens, second batch would keep only 1, but due to `min_tokens_to_keep=2` keeps 2.
								self.assertListEqual((filtered_dist != 0.0).sum(axis=-1	).tolist()	,    [3, 2]	)







	def   A			(		self    :  str	)    ->	str:
								UpperCAmelCase				: Dict											=	20
								UpperCAmelCase				: Union[str, Any]											=	4
								UpperCAmelCase				: Optional[Any]											=	0

								UpperCAmelCase				: Optional[Any]											=	FlaxMinLengthLogitsProcessor(min_length=10	,    eos_token_id=__snake_case	)

								# check that min length is applied at length 5
								UpperCAmelCase				: List[str]											=	ids_tensor((batch_size, 20)	,    vocab_size=20	)
								UpperCAmelCase				: int											=	5
								UpperCAmelCase				: List[Any]											=	self._get_uniform_logits(__snake_case	,    __snake_case	)
								UpperCAmelCase				: Optional[int]											=	min_dist_processor(__snake_case	,    __snake_case	,    cur_len=__snake_case	)
								self.assertListEqual(scores_before_min_length[:, eos_token_id].tolist()	,    4 * [-float('''inf'''	)]	)

								# check that min length is not applied anymore at length 15
								UpperCAmelCase				: Any											=	self._get_uniform_logits(__snake_case	,    __snake_case	)
								UpperCAmelCase				: Any											=	15
								UpperCAmelCase				: Optional[int]											=	min_dist_processor(__snake_case	,    __snake_case	,    cur_len=__snake_case	)
								self.assertFalse(jnp.isinf(__snake_case	).any()	)







	def   A			(		self    :  Optional[int]	)    ->	Dict:
								UpperCAmelCase				: Optional[int]											=	20
								UpperCAmelCase				: List[Any]											=	4
								UpperCAmelCase				: int											=	0

								UpperCAmelCase				: List[Any]											=	FlaxForcedBOSTokenLogitsProcessor(bos_token_id=__snake_case	)

								# check that all scores are -inf except the bos_token_id score
								UpperCAmelCase				: Dict											=	ids_tensor((batch_size, 1)	,    vocab_size=20	)
								UpperCAmelCase				: Union[str, Any]											=	1
								UpperCAmelCase				: Dict											=	self._get_uniform_logits(__snake_case	,    __snake_case	)
								UpperCAmelCase				: int											=	logits_processor(__snake_case	,    __snake_case	,    cur_len=__snake_case	)
								self.assertTrue(jnp.isneginf(scores[:, bos_token_id + 1 :]	).all()	)
								self.assertListEqual(scores[:, bos_token_id].tolist()	,    4 * [0]	)  # score for bos_token_id shold be zero

								# check that bos_token_id is not forced if current length is greater than 1
								UpperCAmelCase				: str											=	3
								UpperCAmelCase				: str											=	self._get_uniform_logits(__snake_case	,    __snake_case	)
								UpperCAmelCase				: Union[str, Any]											=	logits_processor(__snake_case	,    __snake_case	,    cur_len=__snake_case	)
								self.assertFalse(jnp.isinf(__snake_case	).any()	)







	def   A			(		self    :  List[str]	)    ->	List[Any]:
								UpperCAmelCase				: Dict											=	20
								UpperCAmelCase				: Optional[int]											=	4
								UpperCAmelCase				: List[Any]											=	0
								UpperCAmelCase				: Optional[Any]											=	5

								UpperCAmelCase				: Tuple											=	FlaxForcedEOSTokenLogitsProcessor(max_length=__snake_case	,    eos_token_id=__snake_case	)

								# check that all scores are -inf except the eos_token_id when max_length is reached
								UpperCAmelCase				: Optional[Any]											=	ids_tensor((batch_size, 4)	,    vocab_size=20	)
								UpperCAmelCase				: Optional[Any]											=	4
								UpperCAmelCase				: Tuple											=	self._get_uniform_logits(__snake_case	,    __snake_case	)
								UpperCAmelCase				: Dict											=	logits_processor(__snake_case	,    __snake_case	,    cur_len=__snake_case	)
								self.assertTrue(jnp.isneginf(scores[:, eos_token_id + 1 :]	).all()	)
								self.assertListEqual(scores[:, eos_token_id].tolist()	,    4 * [0]	)  # score for eos_token_id should be zero

								# check that eos_token_id is not forced if max_length is not reached
								UpperCAmelCase				: Optional[Any]											=	3
								UpperCAmelCase				: Any											=	self._get_uniform_logits(__snake_case	,    __snake_case	)
								UpperCAmelCase				: int											=	logits_processor(__snake_case	,    __snake_case	,    cur_len=__snake_case	)
								self.assertFalse(jnp.isinf(__snake_case	).any()	)







	def   A			(		self    :  Tuple	)    ->	int:
								UpperCAmelCase				: Any											=	4
								UpperCAmelCase				: List[str]											=	10
								UpperCAmelCase				: Tuple											=	15
								UpperCAmelCase				: Any											=	2
								UpperCAmelCase				: Any											=	1
								UpperCAmelCase				: int											=	15

								# dummy input_ids and scores
								UpperCAmelCase				: List[Any]											=	ids_tensor((batch_size, sequence_length)	,    __snake_case	)
								UpperCAmelCase				: Optional[int]											=	input_ids.copy()

								UpperCAmelCase				: Tuple											=	self._get_uniform_logits(__snake_case	,    __snake_case	)
								UpperCAmelCase				: List[Any]											=	scores.copy()

								# instantiate all dist processors
								UpperCAmelCase				: Tuple											=	FlaxTemperatureLogitsWarper(temperature=0.5	)
								UpperCAmelCase				: Optional[int]											=	FlaxTopKLogitsWarper(3	)
								UpperCAmelCase				: Dict											=	FlaxTopPLogitsWarper(0.8	)

								# instantiate all logits processors
								UpperCAmelCase				: Dict											=	FlaxMinLengthLogitsProcessor(min_length=10	,    eos_token_id=__snake_case	)
								UpperCAmelCase				: int											=	FlaxForcedBOSTokenLogitsProcessor(bos_token_id=__snake_case	)
								UpperCAmelCase				: int											=	FlaxForcedEOSTokenLogitsProcessor(max_length=__snake_case	,    eos_token_id=__snake_case	)

								UpperCAmelCase				: Dict											=	10

								# no processor list
								UpperCAmelCase				: Optional[Any]											=	temp_dist_warp(__snake_case	,    __snake_case	,    cur_len=__snake_case	)
								UpperCAmelCase				: Dict											=	top_k_warp(__snake_case	,    __snake_case	,    cur_len=__snake_case	)
								UpperCAmelCase				: Union[str, Any]											=	top_p_warp(__snake_case	,    __snake_case	,    cur_len=__snake_case	)
								UpperCAmelCase				: Dict											=	min_dist_proc(__snake_case	,    __snake_case	,    cur_len=__snake_case	)
								UpperCAmelCase				: str											=	bos_dist_proc(__snake_case	,    __snake_case	,    cur_len=__snake_case	)
								UpperCAmelCase				: Union[str, Any]											=	eos_dist_proc(__snake_case	,    __snake_case	,    cur_len=__snake_case	)

								# with processor list
								UpperCAmelCase				: Tuple											=	FlaxLogitsProcessorList(
								    [temp_dist_warp, top_k_warp, top_p_warp, min_dist_proc, bos_dist_proc, eos_dist_proc]	)
								UpperCAmelCase				: Any											=	processor(__snake_case	,    __snake_case	,    cur_len=__snake_case	)

								# scores should be equal
								self.assertTrue(jnp.allclose(__snake_case	,    __snake_case	,    atol=1E-3	)	)

								# input_ids should never be changed
								self.assertListEqual(input_ids.tolist()	,    input_ids_comp.tolist()	)







	def   A			(		self    :  Union[str, Any]	)    ->	Dict:
								UpperCAmelCase				: List[Any]											=	4
								UpperCAmelCase				: Optional[int]											=	10
								UpperCAmelCase				: Tuple											=	15
								UpperCAmelCase				: int											=	2
								UpperCAmelCase				: Any											=	1
								UpperCAmelCase				: str											=	15

								# dummy input_ids and scores
								UpperCAmelCase				: Tuple											=	ids_tensor((batch_size, sequence_length)	,    __snake_case	)
								UpperCAmelCase				: Tuple											=	input_ids.copy()

								UpperCAmelCase				: Optional[Any]											=	self._get_uniform_logits(__snake_case	,    __snake_case	)
								UpperCAmelCase				: Dict											=	scores.copy()

								# instantiate all dist processors
								UpperCAmelCase				: str											=	FlaxTemperatureLogitsWarper(temperature=0.5	)
								UpperCAmelCase				: List[Any]											=	FlaxTopKLogitsWarper(3	)
								UpperCAmelCase				: Any											=	FlaxTopPLogitsWarper(0.8	)

								# instantiate all logits processors
								UpperCAmelCase				: List[Any]											=	FlaxMinLengthLogitsProcessor(min_length=10	,    eos_token_id=__snake_case	)
								UpperCAmelCase				: Optional[int]											=	FlaxForcedBOSTokenLogitsProcessor(bos_token_id=__snake_case	)
								UpperCAmelCase				: Union[str, Any]											=	FlaxForcedEOSTokenLogitsProcessor(max_length=__snake_case	,    eos_token_id=__snake_case	)

								UpperCAmelCase				: Union[str, Any]											=	10

								# no processor list
								def run_no_processor_list(__snake_case    :  Optional[Any]	,    __snake_case    :  int	,    __snake_case    :  List[Any]	):
															UpperCAmelCase				: Dict											=	temp_dist_warp(__snake_case	,    __snake_case	,    cur_len=__snake_case	)
															UpperCAmelCase				: List[Any]											=	top_k_warp(__snake_case	,    __snake_case	,    cur_len=__snake_case	)
															UpperCAmelCase				: List[str]											=	top_p_warp(__snake_case	,    __snake_case	,    cur_len=__snake_case	)
															UpperCAmelCase				: List[str]											=	min_dist_proc(__snake_case	,    __snake_case	,    cur_len=__snake_case	)
															UpperCAmelCase				: Union[str, Any]											=	bos_dist_proc(__snake_case	,    __snake_case	,    cur_len=__snake_case	)
															UpperCAmelCase				: Optional[int]											=	eos_dist_proc(__snake_case	,    __snake_case	,    cur_len=__snake_case	)
															return scores

								# with processor list
								def run_processor_list(__snake_case    :  int	,    __snake_case    :  str	,    __snake_case    :  Dict	):
															UpperCAmelCase				: Optional[int]											=	FlaxLogitsProcessorList(
															    [temp_dist_warp, top_k_warp, top_p_warp, min_dist_proc, bos_dist_proc, eos_dist_proc]	)
															UpperCAmelCase				: int											=	processor(__snake_case	,    __snake_case	,    cur_len=__snake_case	)
															return scores

								UpperCAmelCase				: Tuple											=	jax.jit(__snake_case	)
								UpperCAmelCase				: Any											=	jax.jit(__snake_case	)

								UpperCAmelCase				: Optional[Any]											=	jitted_run_no_processor_list(__snake_case	,    __snake_case	,    __snake_case	)
								UpperCAmelCase				: Union[str, Any]											=	jitted_run_processor_list(__snake_case	,    __snake_case	,    __snake_case	)

								# scores should be equal
								self.assertTrue(jnp.allclose(__snake_case	,    __snake_case	,    atol=1E-3	)	)

								# input_ids should never be changed
								self.assertListEqual(input_ids.tolist()	,    input_ids_comp.tolist()	)










'''simple docstring'''






# Lint as: python3
import dataclasses
import re
from dataclasses import dataclass
from functools import total_ordering
from typing import Optional, Union


UpperCamelCase__:     List[str]										=    re.compile(r"^(?P<major>\d+)" r"\.(?P<minor>\d+)" r"\.(?P<patch>\d+)$")

@total_ordering
@dataclass
class        SCREAMING_SNAKE_CASE:







	"""simple docstring"""






	lowerCamelCase__    				= 42
	lowerCamelCase__    				= None
	lowerCamelCase__    				= None
	lowerCamelCase__    				= None
	lowerCamelCase__    				= None







	def   A			(		self    :  Optional[Any]	)    ->	Dict:
								UpperCAmelCase							,	UpperCAmelCase							,	UpperCAmelCase				: Any											=	_str_to_version_tuple(self.version_str	)







	def __repr__(		self    :  str	)    ->	Optional[Any]:
								return F"""{self.tuple[0]}.{self.tuple[1]}.{self.tuple[2]}"""







	@property
	def   A			(		self    :  Tuple	)    ->	Dict:
								return self.major, self.minor, self.patch







	def   A			(		self    :  str	,    __snake_case    :  Any	)    ->	Tuple:
								if isinstance(__snake_case	,    __snake_case	):
															return Version(__snake_case	)
								elif isinstance(__snake_case	,    __snake_case	):
															return other
								raise TypeError(F"""{other} (type {type(__snake_case	)}) cannot be compared to version."""	)







	def __eq__(		self    :  str	,    __snake_case    :  Union[str, Any]	)    ->	List[Any]:
								try:
															UpperCAmelCase				: Dict											=	self._validate_operand(__snake_case	)
								except (TypeError, ValueError):
															return False
								else:
															return self.tuple == other.tuple







	def __lt__(		self    :  Any	,    __snake_case    :  int	)    ->	Optional[int]:
								UpperCAmelCase				: int											=	self._validate_operand(__snake_case	)
								return self.tuple < other.tuple







	def __hash__(		self    :  List[str]	)    ->	str:
								return hash(_version_tuple_to_str(self.tuple	)	)







	@classmethod
	def   A			(		cls    :  Any	,    __snake_case    :  Tuple	)    ->	Union[str, Any]:
								UpperCAmelCase				: Optional[Any]											=	{f.name for f in dataclasses.fields(cls	)}
								return cls(**{k: v for k, v in dic.items() if k in field_names}	)







	def   A			(		self    :  Dict	)    ->	str:
								return self.version_str


def 				snake_case_  (      _lowerCAmelCase						:		Optional[Any]						)   ->     List[Any]:
							UpperCAmelCase				: Optional[Any]											=	_VERSION_REG.match(_lowerCAmelCase						)
							if not res:
														raise ValueError(f"""Invalid version '{version_str}'. Format should be x.y.z with {{x,y,z}} being digits."""						)
							return tuple(int(_lowerCAmelCase						) for v in [res.group('''major'''						), res.group('''minor'''						), res.group('''patch'''						)]						)




def 				snake_case_  (      _lowerCAmelCase						:		List[str]						)   ->     List[Any]:
							return ".".join(str(_lowerCAmelCase						) for v in version_tuple						)





