
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 __snake_case		(				unittest.TestCase					):
    def 				_SCREAMING_SNAKE_CASE	(  self		,snake_case		,snake_case				):



           '''simple docstring'''







           lowercase							:					List[str]	     =				jnp.ones((batch_size, length)				) / length
           return scores
    def 				_SCREAMING_SNAKE_CASE	(  self				):



           '''simple docstring'''







           lowercase							:					List[Any]	     =				None
           lowercase							:					Dict	     =				20

           lowercase							:					Dict	     =				self._get_uniform_logits(batch_size=2		,length=snake_case				)

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

           # compute softmax
           lowercase							:					List[str]	     =				jax.nn.softmax(snake_case		,axis=-1				)

           lowercase							:					Any	     =				FlaxTemperatureLogitsWarper(temperature=0.5				)
           lowercase							:					Optional[int]	     =				FlaxTemperatureLogitsWarper(temperature=1.3				)

           lowercase							:					Optional[int]	     =				jax.nn.softmax(temp_dist_warper_sharper(snake_case		,scores.copy()		,cur_len=snake_case				)		,axis=-1				)
           lowercase							:					Optional[int]	     =				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 				_SCREAMING_SNAKE_CASE	(  self				):



           '''simple docstring'''







           lowercase							:					Tuple	     =				None
           lowercase							:					List[Any]	     =				10
           lowercase							:					Any	     =				2

           # create ramp distribution
           lowercase							:					List[str]	     =				np.broadcast_to(np.arange(snake_case				)[None, :]		,(batch_size, vocab_size)				).copy()
           lowercase							:					Union[str, Any]	     =				ramp_logits[1:, : vocab_size // 2] + vocab_size

           lowercase							:					Optional[Any]	     =				FlaxTopKLogitsWarper(3				)

           lowercase							:					List[str]	     =				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
           lowercase							:					int	     =				5
           lowercase							:					Dict	     =				FlaxTopKLogitsWarper(top_k=1		,filter_value=0.0		,min_tokens_to_keep=3				)

           lowercase							:					str	     =				np.broadcast_to(np.arange(snake_case				)[None, :]		,(batch_size, length)				).copy()
           lowercase							:					int	     =				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 				_SCREAMING_SNAKE_CASE	(  self				):



           '''simple docstring'''







           lowercase							:					Any	     =				None
           lowercase							:					Dict	     =				10
           lowercase							:					Union[str, Any]	     =				2

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

           lowercase							:					Optional[int]	     =				FlaxTopPLogitsWarper(0.8				)
           lowercase							:					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
           lowercase							:					Any	     =				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
           lowercase							:					Dict	     =				np.broadcast_to(np.arange(snake_case				)[None, :]		,(batch_size, vocab_size)				).copy() - (
               vocab_size // 2
           )

           # make ramp_logits more extreme
           lowercase							:					Optional[int]	     =				ramp_logits[1] * 100.0

           # make sure at least 2 tokens are kept
           lowercase							:					List[Any]	     =				FlaxTopPLogitsWarper(0.9		,min_tokens_to_keep=2		,filter_value=0.0				)
           lowercase							:					Dict	     =				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 				_SCREAMING_SNAKE_CASE	(  self				):



           '''simple docstring'''







           lowercase							:					Union[str, Any]	     =				20
           lowercase							:					Any	     =				4
           lowercase							:					List[str]	     =				0

           lowercase							:					Any	     =				FlaxMinLengthLogitsProcessor(min_length=10		,eos_token_id=snake_case				)

           # check that min length is applied at length 5
           lowercase							:					Optional[Any]	     =				ids_tensor((batch_size, 20)		,vocab_size=20				)
           lowercase							:					Tuple	     =				5
           lowercase							:					Optional[Any]	     =				self._get_uniform_logits(snake_case		,snake_case				)
           lowercase							:					str	     =				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
           lowercase							:					Union[str, Any]	     =				self._get_uniform_logits(snake_case		,snake_case				)
           lowercase							:					List[Any]	     =				15
           lowercase							:					str	     =				min_dist_processor(snake_case		,snake_case		,cur_len=snake_case				)
           self.assertFalse(jnp.isinf(snake_case				).any()				)
    def 				_SCREAMING_SNAKE_CASE	(  self				):



           '''simple docstring'''







           lowercase							:					Union[str, Any]	     =				20
           lowercase							:					str	     =				4
           lowercase							:					Dict	     =				0

           lowercase							:					Any	     =				FlaxForcedBOSTokenLogitsProcessor(bos_token_id=snake_case				)

           # check that all scores are -inf except the bos_token_id score
           lowercase							:					Any	     =				ids_tensor((batch_size, 1)		,vocab_size=20				)
           lowercase							:					Dict	     =				1
           lowercase							:					Tuple	     =				self._get_uniform_logits(snake_case		,snake_case				)
           lowercase							:					Any	     =				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
           lowercase							:					int	     =				3
           lowercase							:					List[Any]	     =				self._get_uniform_logits(snake_case		,snake_case				)
           lowercase							:					List[Any]	     =				logits_processor(snake_case		,snake_case		,cur_len=snake_case				)
           self.assertFalse(jnp.isinf(snake_case				).any()				)
    def 				_SCREAMING_SNAKE_CASE	(  self				):



           '''simple docstring'''







           lowercase							:					str	     =				20
           lowercase							:					str	     =				4
           lowercase							:					Dict	     =				0
           lowercase							:					Any	     =				5

           lowercase							:					List[Any]	     =				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
           lowercase							:					Any	     =				ids_tensor((batch_size, 4)		,vocab_size=20				)
           lowercase							:					Any	     =				4
           lowercase							:					Tuple	     =				self._get_uniform_logits(snake_case		,snake_case				)
           lowercase							:					List[str]	     =				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
           lowercase							:					Dict	     =				3
           lowercase							:					int	     =				self._get_uniform_logits(snake_case		,snake_case				)
           lowercase							:					Dict	     =				logits_processor(snake_case		,snake_case		,cur_len=snake_case				)
           self.assertFalse(jnp.isinf(snake_case				).any()				)
    def 				_SCREAMING_SNAKE_CASE	(  self				):



           '''simple docstring'''







           lowercase							:					Any	     =				4
           lowercase							:					Union[str, Any]	     =				10
           lowercase							:					List[Any]	     =				15
           lowercase							:					Any	     =				2
           lowercase							:					Tuple	     =				1
           lowercase							:					Union[str, Any]	     =				15

           # dummy input_ids and scores
           lowercase							:					str	     =				ids_tensor((batch_size, sequence_length)		,snake_case				)
           lowercase							:					str	     =				input_ids.copy()

           lowercase							:					Any	     =				self._get_uniform_logits(snake_case		,snake_case				)
           lowercase							:					Any	     =				scores.copy()

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

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

           lowercase							:					Optional[Any]	     =				10

           # no processor list
           lowercase							:					List[str]	     =				temp_dist_warp(snake_case		,snake_case		,cur_len=snake_case				)
           lowercase							:					Optional[Any]	     =				top_k_warp(snake_case		,snake_case		,cur_len=snake_case				)
           lowercase							:					str	     =				top_p_warp(snake_case		,snake_case		,cur_len=snake_case				)
           lowercase							:					List[Any]	     =				min_dist_proc(snake_case		,snake_case		,cur_len=snake_case				)
           lowercase							:					List[Any]	     =				bos_dist_proc(snake_case		,snake_case		,cur_len=snake_case				)
           lowercase							:					Optional[Any]	     =				eos_dist_proc(snake_case		,snake_case		,cur_len=snake_case				)

           # with processor list
           lowercase							:					List[Any]	     =				FlaxLogitsProcessorList(
               [temp_dist_warp, top_k_warp, top_p_warp, min_dist_proc, bos_dist_proc, eos_dist_proc]				)
           lowercase							:					int	     =				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 				_SCREAMING_SNAKE_CASE	(  self				):



           '''simple docstring'''







           lowercase							:					Dict	     =				4
           lowercase							:					int	     =				10
           lowercase							:					List[Any]	     =				15
           lowercase							:					Tuple	     =				2
           lowercase							:					Optional[int]	     =				1
           lowercase							:					Any	     =				15

           # dummy input_ids and scores
           lowercase							:					int	     =				ids_tensor((batch_size, sequence_length)		,snake_case				)
           lowercase							:					Dict	     =				input_ids.copy()

           lowercase							:					int	     =				self._get_uniform_logits(snake_case		,snake_case				)
           lowercase							:					Optional[Any]	     =				scores.copy()

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

           # instantiate all logits processors
           lowercase							:					Tuple	     =				FlaxMinLengthLogitsProcessor(min_length=10		,eos_token_id=snake_case				)
           lowercase							:					List[Any]	     =				FlaxForcedBOSTokenLogitsProcessor(bos_token_id=snake_case				)
           lowercase							:					int	     =				FlaxForcedEOSTokenLogitsProcessor(max_length=snake_case		,eos_token_id=snake_case				)

           lowercase							:					Optional[Any]	     =				10

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

           # with processor list
           def run_processor_list(snake_case		,snake_case		,snake_case				):
                  lowercase							:					int	     =				FlaxLogitsProcessorList(
                      [temp_dist_warp, top_k_warp, top_p_warp, min_dist_proc, bos_dist_proc, eos_dist_proc]				)
                  lowercase							:					Union[str, Any]	     =				processor(snake_case		,snake_case		,cur_len=snake_case				)
                  return scores

           lowercase							:					List[Any]	     =				jax.jit(snake_case				)
           lowercase							:					Dict	     =				jax.jit(snake_case				)

           lowercase							:					Tuple	     =				jitted_run_no_processor_list(snake_case		,snake_case		,snake_case				)
           lowercase							:					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()				)


from __future__ import annotations

from itertools import permutations
from random import randint
from timeit import repeat







def 						_snake_case(  )			->   tuple[list[int], int]:
       lowercase							:					List[Any]	     =				[randint(-1_000 ,     1_000    ) for i in range(10    )]
       lowercase							:					Tuple	     =				randint(-5_000 ,     5_000    )
       return (arr, r)


lowercase  : List[Any]						   =							make_dataset()







def 						_snake_case(  SCREAMING_SNAKE_CASE__ ,     SCREAMING_SNAKE_CASE__    )			->   tuple[int, ...]:
       for triplet in permutations(SCREAMING_SNAKE_CASE__ ,     3    ):
              if sum(SCREAMING_SNAKE_CASE__    ) == target:
                     return tuple(sorted(SCREAMING_SNAKE_CASE__    )    )
       return (0, 0, 0)







def 						_snake_case(  SCREAMING_SNAKE_CASE__ ,     SCREAMING_SNAKE_CASE__    )			->   tuple[int, int, int]:
       arr.sort()
       lowercase							:					Optional[int]	     =				len(SCREAMING_SNAKE_CASE__    )
       for i in range(n - 1    ):
              lowercase     ,      lowercase							:					Optional[Any]	     =				i + 1, n - 1
              while left < right:
                     if arr[i] + arr[left] + arr[right] == target:
                            return (arr[i], arr[left], arr[right])
                     elif arr[i] + arr[left] + arr[right] < target:
                            left += 1
                     elif arr[i] + arr[left] + arr[right] > target:
                            right -= 1
       return (0, 0, 0)







def 						_snake_case(  )			->   tuple[float, float]:
       lowercase							:					Dict	     =				"""
from __main__ import dataset, triplet_sum1, triplet_sum2
"""
       lowercase							:					Tuple	     =				"""
triplet_sum1(*dataset)
"""
       lowercase							:					int	     =				"""
triplet_sum2(*dataset)
"""
       lowercase							:					str	     =				repeat(setup=SCREAMING_SNAKE_CASE__ ,     stmt=SCREAMING_SNAKE_CASE__ ,     repeat=5 ,     number=10_000    )
       lowercase							:					Dict	     =				repeat(setup=SCREAMING_SNAKE_CASE__ ,     stmt=SCREAMING_SNAKE_CASE__ ,     repeat=5 ,     number=10_000    )
       return (min(SCREAMING_SNAKE_CASE__    ), min(SCREAMING_SNAKE_CASE__    ))


if __name__ == "__main__":
  from doctest import testmod

  testmod()
  lowercase  : Union[str, Any]						   =							solution_times()
  print(F'''The time for naive implementation is {times[0]}.''')
  print(F'''The time for optimized implementation is {times[1]}.''')
