






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      UpperCamelCase (				unittest.TestCase ):







		"""simple docstring"""



		def       A(  self		:       List[Any]						,_SCREAMING_SNAKE_CASE		:       int						,_SCREAMING_SNAKE_CASE		:       int		)    ->   int:


						'''simple docstring'''
						A	 =      jnp.ones((batch_size, length)		) / length
						return scores
		def       A(  self		:       Any		)    ->   List[str]:


						'''simple docstring'''
						A	 =      None
						A	 =      2_0

						A	 =      self._get_uniform_logits(batch_size=2						,length=UpperCamelCase__		)

						# tweak scores to not be uniform anymore
						A	 =      scores.at[1, 5].set((1 / length) + 0.1		)  # peak, 1st batch
						A	 =      scores.at[1, 1_0].set((1 / length) - 0.4		)  # valley, 1st batch

						# compute softmax
						A	 =      jax.nn.softmax(UpperCamelCase__						,axis=-1		)

						A	 =      FlaxTemperatureLogitsWarper(temperature=0.5		)
						A	 =      FlaxTemperatureLogitsWarper(temperature=1.3		)

						A	 =      jax.nn.softmax(temp_dist_warper_sharper(UpperCamelCase__						,scores.copy()						,cur_len=UpperCamelCase__		)						,axis=-1		)
						A	 =      jax.nn.softmax(temp_dist_warper_smoother(UpperCamelCase__						,scores.copy()						,cur_len=UpperCamelCase__		)						,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		:       List[str]		)    ->   List[str]:


						'''simple docstring'''
						A	 =      None
						A	 =      1_0
						A	 =      2

						# create ramp distribution
						A	 =      np.broadcast_to(np.arange(UpperCamelCase__		)[None, :]						,(batch_size, vocab_size)		).copy()
						A	 =      ramp_logits[1:, : vocab_size // 2] + vocab_size

						A	 =      FlaxTopKLogitsWarper(3		)

						A	 =      top_k_warp(UpperCamelCase__						,UpperCamelCase__						,cur_len=UpperCamelCase__		)

						# 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
						A	 =      5
						A	 =      FlaxTopKLogitsWarper(top_k=1						,filter_value=0.0						,min_tokens_to_keep=3		)

						A	 =      np.broadcast_to(np.arange(UpperCamelCase__		)[None, :]						,(batch_size, length)		).copy()
						A	 =      top_k_warp_safety_check(UpperCamelCase__						,UpperCamelCase__						,cur_len=UpperCamelCase__		)

						# 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		:       Any		)    ->   Tuple:


						'''simple docstring'''
						A	 =      None
						A	 =      1_0
						A	 =      2

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

						A	 =      FlaxTopPLogitsWarper(0.8		)
						A	 =      np.exp(top_p_warp(UpperCamelCase__						,UpperCamelCase__						,cur_len=UpperCamelCase__		)		)

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

						# check edge cases with negative and extreme logits
						A	 =      np.broadcast_to(np.arange(UpperCamelCase__		)[None, :]						,(batch_size, vocab_size)		).copy() - (
						    vocab_size // 2
						)

						# make ramp_logits more extreme
						A	 =      ramp_logits[1] * 1_0_0.0

						# make sure at least 2 tokens are kept
						A	 =      FlaxTopPLogitsWarper(0.9						,min_tokens_to_keep=2						,filter_value=0.0		)
						A	 =      top_p_warp(UpperCamelCase__						,UpperCamelCase__						,cur_len=UpperCamelCase__		)

						# 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		:       Optional[Any]		)    ->   Optional[int]:


						'''simple docstring'''
						A	 =      2_0
						A	 =      4
						A	 =      0

						A	 =      FlaxMinLengthLogitsProcessor(min_length=1_0						,eos_token_id=UpperCamelCase__		)

						# check that min length is applied at length 5
						A	 =      ids_tensor((batch_size, 2_0)						,vocab_size=2_0		)
						A	 =      5
						A	 =      self._get_uniform_logits(UpperCamelCase__						,UpperCamelCase__		)
						A	 =      min_dist_processor(UpperCamelCase__						,UpperCamelCase__						,cur_len=UpperCamelCase__		)
						self.assertListEqual(scores_before_min_length[:, eos_token_id].tolist()						,4 * [-float('inf'		)]		)

						# check that min length is not applied anymore at length 15
						A	 =      self._get_uniform_logits(UpperCamelCase__						,UpperCamelCase__		)
						A	 =      1_5
						A	 =      min_dist_processor(UpperCamelCase__						,UpperCamelCase__						,cur_len=UpperCamelCase__		)
						self.assertFalse(jnp.isinf(UpperCamelCase__		).any()		)
		def       A(  self		:       List[str]		)    ->   Tuple:


						'''simple docstring'''
						A	 =      2_0
						A	 =      4
						A	 =      0

						A	 =      FlaxForcedBOSTokenLogitsProcessor(bos_token_id=UpperCamelCase__		)

						# check that all scores are -inf except the bos_token_id score
						A	 =      ids_tensor((batch_size, 1)						,vocab_size=2_0		)
						A	 =      1
						A	 =      self._get_uniform_logits(UpperCamelCase__						,UpperCamelCase__		)
						A	 =      logits_processor(UpperCamelCase__						,UpperCamelCase__						,cur_len=UpperCamelCase__		)
						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
						A	 =      3
						A	 =      self._get_uniform_logits(UpperCamelCase__						,UpperCamelCase__		)
						A	 =      logits_processor(UpperCamelCase__						,UpperCamelCase__						,cur_len=UpperCamelCase__		)
						self.assertFalse(jnp.isinf(UpperCamelCase__		).any()		)
		def       A(  self		:       Optional[Any]		)    ->   Union[str, Any]:


						'''simple docstring'''
						A	 =      2_0
						A	 =      4
						A	 =      0
						A	 =      5

						A	 =      FlaxForcedEOSTokenLogitsProcessor(max_length=UpperCamelCase__						,eos_token_id=UpperCamelCase__		)

						# check that all scores are -inf except the eos_token_id when max_length is reached
						A	 =      ids_tensor((batch_size, 4)						,vocab_size=2_0		)
						A	 =      4
						A	 =      self._get_uniform_logits(UpperCamelCase__						,UpperCamelCase__		)
						A	 =      logits_processor(UpperCamelCase__						,UpperCamelCase__						,cur_len=UpperCamelCase__		)
						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
						A	 =      3
						A	 =      self._get_uniform_logits(UpperCamelCase__						,UpperCamelCase__		)
						A	 =      logits_processor(UpperCamelCase__						,UpperCamelCase__						,cur_len=UpperCamelCase__		)
						self.assertFalse(jnp.isinf(UpperCamelCase__		).any()		)
		def       A(  self		:       Tuple		)    ->   List[Any]:


						'''simple docstring'''
						A	 =      4
						A	 =      1_0
						A	 =      1_5
						A	 =      2
						A	 =      1
						A	 =      1_5

						# dummy input_ids and scores
						A	 =      ids_tensor((batch_size, sequence_length)						,UpperCamelCase__		)
						A	 =      input_ids.copy()

						A	 =      self._get_uniform_logits(UpperCamelCase__						,UpperCamelCase__		)
						A	 =      scores.copy()

						# instantiate all dist processors
						A	 =      FlaxTemperatureLogitsWarper(temperature=0.5		)
						A	 =      FlaxTopKLogitsWarper(3		)
						A	 =      FlaxTopPLogitsWarper(0.8		)

						# instantiate all logits processors
						A	 =      FlaxMinLengthLogitsProcessor(min_length=1_0						,eos_token_id=UpperCamelCase__		)
						A	 =      FlaxForcedBOSTokenLogitsProcessor(bos_token_id=UpperCamelCase__		)
						A	 =      FlaxForcedEOSTokenLogitsProcessor(max_length=UpperCamelCase__						,eos_token_id=UpperCamelCase__		)

						A	 =      1_0

						# no processor list
						A	 =      temp_dist_warp(UpperCamelCase__						,UpperCamelCase__						,cur_len=UpperCamelCase__		)
						A	 =      top_k_warp(UpperCamelCase__						,UpperCamelCase__						,cur_len=UpperCamelCase__		)
						A	 =      top_p_warp(UpperCamelCase__						,UpperCamelCase__						,cur_len=UpperCamelCase__		)
						A	 =      min_dist_proc(UpperCamelCase__						,UpperCamelCase__						,cur_len=UpperCamelCase__		)
						A	 =      bos_dist_proc(UpperCamelCase__						,UpperCamelCase__						,cur_len=UpperCamelCase__		)
						A	 =      eos_dist_proc(UpperCamelCase__						,UpperCamelCase__						,cur_len=UpperCamelCase__		)

						# with processor list
						A	 =      FlaxLogitsProcessorList(
						    [temp_dist_warp, top_k_warp, top_p_warp, min_dist_proc, bos_dist_proc, eos_dist_proc]		)
						A	 =      processor(UpperCamelCase__						,UpperCamelCase__						,cur_len=UpperCamelCase__		)

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

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







		def       A(  self		:       Optional[int]		)    ->   List[Any]:


						'''simple docstring'''
						A	 =      4
						A	 =      1_0
						A	 =      1_5
						A	 =      2
						A	 =      1
						A	 =      1_5

						# dummy input_ids and scores
						A	 =      ids_tensor((batch_size, sequence_length)						,UpperCamelCase__		)
						A	 =      input_ids.copy()

						A	 =      self._get_uniform_logits(UpperCamelCase__						,UpperCamelCase__		)
						A	 =      scores.copy()

						# instantiate all dist processors
						A	 =      FlaxTemperatureLogitsWarper(temperature=0.5		)
						A	 =      FlaxTopKLogitsWarper(3		)
						A	 =      FlaxTopPLogitsWarper(0.8		)

						# instantiate all logits processors
						A	 =      FlaxMinLengthLogitsProcessor(min_length=1_0						,eos_token_id=UpperCamelCase__		)
						A	 =      FlaxForcedBOSTokenLogitsProcessor(bos_token_id=UpperCamelCase__		)
						A	 =      FlaxForcedEOSTokenLogitsProcessor(max_length=UpperCamelCase__						,eos_token_id=UpperCamelCase__		)

						A	 =      1_0

						# no processor list
						def run_no_processor_list(_SCREAMING_SNAKE_CASE		:       str						,_SCREAMING_SNAKE_CASE		:       Optional[Any]						,_SCREAMING_SNAKE_CASE		:       Union[str, Any]		):
										A	 =      temp_dist_warp(UpperCamelCase__						,UpperCamelCase__						,cur_len=UpperCamelCase__		)
										A	 =      top_k_warp(UpperCamelCase__						,UpperCamelCase__						,cur_len=UpperCamelCase__		)
										A	 =      top_p_warp(UpperCamelCase__						,UpperCamelCase__						,cur_len=UpperCamelCase__		)
										A	 =      min_dist_proc(UpperCamelCase__						,UpperCamelCase__						,cur_len=UpperCamelCase__		)
										A	 =      bos_dist_proc(UpperCamelCase__						,UpperCamelCase__						,cur_len=UpperCamelCase__		)
										A	 =      eos_dist_proc(UpperCamelCase__						,UpperCamelCase__						,cur_len=UpperCamelCase__		)
										return scores

						# with processor list
						def run_processor_list(_SCREAMING_SNAKE_CASE		:       Dict						,_SCREAMING_SNAKE_CASE		:       Optional[Any]						,_SCREAMING_SNAKE_CASE		:       str		):
										A	 =      FlaxLogitsProcessorList(
										    [temp_dist_warp, top_k_warp, top_p_warp, min_dist_proc, bos_dist_proc, eos_dist_proc]		)
										A	 =      processor(UpperCamelCase__						,UpperCamelCase__						,cur_len=UpperCamelCase__		)
										return scores

						A	 =      jax.jit(UpperCamelCase__		)
						A	 =      jax.jit(UpperCamelCase__		)

						A	 =      jitted_run_no_processor_list(UpperCamelCase__						,UpperCamelCase__						,UpperCamelCase__		)
						A	 =      jitted_run_processor_list(UpperCamelCase__						,UpperCamelCase__						,UpperCamelCase__		)

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

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













from math import factorial
class      UpperCamelCase :







		"""simple docstring"""



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


						'''simple docstring'''
						A	 =      real
						if isinstance(_SCREAMING_SNAKE_CASE						,_SCREAMING_SNAKE_CASE		):
										A	 =      [1] * rank
						else:
										A	 =      rank
		def __repr__(  self		:       Any		)    ->   Optional[Any]:


						'''simple docstring'''
						return (
						    f'{self.real}+'
						    f'{"+".join(str(_SCREAMING_SNAKE_CASE		)+"E"+str(n+1		)for n,dual in enumerate(self.duals		)		)}'
						)
		def       A(  self		:       Optional[Any]		)    ->   Tuple:


						'''simple docstring'''
						A	 =      self.duals.copy()
						while cur[-1] == 0:
										cur.pop(-1		)
						return Dual(self.real						,_SCREAMING_SNAKE_CASE		)
		def __add__(  self		:       Optional[Any]						,_SCREAMING_SNAKE_CASE		:       int		)    ->   Any:


						'''simple docstring'''
						if not isinstance(_SCREAMING_SNAKE_CASE						,_SCREAMING_SNAKE_CASE		):
										return Dual(self.real + other						,self.duals		)
						A	 =      self.duals.copy()
						A	 =      other.duals.copy()
						if len(_SCREAMING_SNAKE_CASE		) > len(_SCREAMING_SNAKE_CASE		):
										o_dual.extend([1] * (len(_SCREAMING_SNAKE_CASE		) - len(_SCREAMING_SNAKE_CASE		))		)
						elif len(_SCREAMING_SNAKE_CASE		) < len(_SCREAMING_SNAKE_CASE		):
										s_dual.extend([1] * (len(_SCREAMING_SNAKE_CASE		) - len(_SCREAMING_SNAKE_CASE		))		)
						A	 =      []
						for i in range(len(_SCREAMING_SNAKE_CASE		)		):
										new_duals.append(s_dual[i] + o_dual[i]		)
						return Dual(self.real + other.real						,_SCREAMING_SNAKE_CASE		)

		snake_case    =   __add__
		def __sub__(  self		:       Tuple						,_SCREAMING_SNAKE_CASE		:       Dict		)    ->   Optional[Any]:


						'''simple docstring'''
						return self + other * -1
		def __mul__(  self		:       Any						,_SCREAMING_SNAKE_CASE		:       Union[str, Any]		)    ->   Union[str, Any]:


						'''simple docstring'''
						if not isinstance(_SCREAMING_SNAKE_CASE						,_SCREAMING_SNAKE_CASE		):
										A	 =      []
										for i in self.duals:
														new_duals.append(i * other		)
										return Dual(self.real * other						,_SCREAMING_SNAKE_CASE		)
						A	 =      [0] * (len(self.duals		) + len(other.duals		) + 1)
						for i, item in enumerate(self.duals		):
										for j, jtem in enumerate(other.duals		):
														new_duals[i + j + 1] += item * jtem
						for k in range(len(self.duals		)		):
										new_duals[k] += self.duals[k] * other.real
						for index in range(len(other.duals		)		):
										new_duals[index] += other.duals[index] * self.real
						return Dual(self.real * other.real						,_SCREAMING_SNAKE_CASE		)

		snake_case    =   __mul__
		def __truediv__(  self		:       Union[str, Any]						,_SCREAMING_SNAKE_CASE		:       int		)    ->   List[str]:


						'''simple docstring'''
						if not isinstance(_SCREAMING_SNAKE_CASE						,_SCREAMING_SNAKE_CASE		):
										A	 =      []
										for i in self.duals:
														new_duals.append(i / other		)
										return Dual(self.real / other						,_SCREAMING_SNAKE_CASE		)
						raise ValueError
		def __floordiv__(  self		:       Any						,_SCREAMING_SNAKE_CASE		:       Any		)    ->   Dict:


						'''simple docstring'''
						if not isinstance(_SCREAMING_SNAKE_CASE						,_SCREAMING_SNAKE_CASE		):
										A	 =      []
										for i in self.duals:
														new_duals.append(i // other		)
										return Dual(self.real // other						,_SCREAMING_SNAKE_CASE		)
						raise ValueError







		def __pow__(  self		:       int						,_SCREAMING_SNAKE_CASE		:       Union[str, Any]		)    ->   str:


						'''simple docstring'''
						if n < 0 or isinstance(_SCREAMING_SNAKE_CASE						,_SCREAMING_SNAKE_CASE		):
										raise ValueError('power must be a positive integer'		)
						if n == 0:
										return 1
						if n == 1:
										return self
						A	 =      self
						for _ in range(n - 1		):
										x *= self
						return x







def      snake_case		(							UpperCAmelCase	:       Optional[int],						UpperCAmelCase	:       List[Any],						UpperCAmelCase	:       int   ):
				if not callable(UpperCAmelCase   ):
								raise ValueError('differentiate() requires a function as input for func'   )
				if not isinstance(UpperCAmelCase,						(float, int)   ):
								raise ValueError('differentiate() requires a float as input for position'   )
				if not isinstance(UpperCAmelCase,						UpperCAmelCase   ):
								raise ValueError('differentiate() requires an int as input for order'   )
				A	 =      Dual(UpperCAmelCase,						1   )
				A	 =      func(UpperCAmelCase   )
				if order == 0:
								return result.real
				return result.duals[order - 1] * factorial(UpperCAmelCase   )


if __name__ == "__main__":
					import doctest

					doctest.testmod()







					def      snake_case		(							UpperCAmelCase	:       int   ):
									return y**2 * y**4



					print(differentiate(f, 9, 2))





