



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




      """simple docstring"""




      def 					SCREAMING_SNAKE_CASE__			(				self    :				int   ,      SCREAMING_SNAKE_CASE_    :				List[Any]   ,      SCREAMING_SNAKE_CASE_    :				int	):
        lowerCAmelCase_       :    Dict								=			jnp.ones((batch_size, length)	) / length
        return scores



      def 					SCREAMING_SNAKE_CASE__			(				self    :				Union[str, Any]	):
        lowerCAmelCase_       :    Optional[Any]								=			None
        lowerCAmelCase_       :    Optional[Any]								=			2_0

        lowerCAmelCase_       :    str								=			self._get_uniform_logits(batch_size=2   ,      length=_SCREAMING_SNAKE_CASE	)

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

        # compute softmax
        lowerCAmelCase_       :    Dict								=			jax.nn.softmax(_SCREAMING_SNAKE_CASE   ,      axis=-1	)

        lowerCAmelCase_       :    Dict								=			FlaxTemperatureLogitsWarper(temperature=0.5	)
        lowerCAmelCase_       :    Dict								=			FlaxTemperatureLogitsWarper(temperature=1.3	)

        lowerCAmelCase_       :    int								=			jax.nn.softmax(temp_dist_warper_sharper(_SCREAMING_SNAKE_CASE   ,      scores.copy()   ,      cur_len=_SCREAMING_SNAKE_CASE	)   ,      axis=-1	)
        lowerCAmelCase_       :    int								=			jax.nn.softmax(temp_dist_warper_smoother(_SCREAMING_SNAKE_CASE   ,      scores.copy()   ,      cur_len=_SCREAMING_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    :				Optional[int]	):
        lowerCAmelCase_       :    Dict								=			None
        lowerCAmelCase_       :    int								=			1_0
        lowerCAmelCase_       :    List[Any]								=			2

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

        lowerCAmelCase_       :    List[Any]								=			FlaxTopKLogitsWarper(3	)

        lowerCAmelCase_       :    Any								=			top_k_warp(_SCREAMING_SNAKE_CASE   ,      _SCREAMING_SNAKE_CASE   ,      cur_len=_SCREAMING_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
        lowerCAmelCase_       :    Any								=			5
        lowerCAmelCase_       :    List[str]								=			FlaxTopKLogitsWarper(top_k=1   ,      filter_value=0.0   ,      min_tokens_to_keep=3	)

        lowerCAmelCase_       :    int								=			np.broadcast_to(np.arange(_SCREAMING_SNAKE_CASE	)[None, :]   ,      (batch_size, length)	).copy()
        lowerCAmelCase_       :    Dict								=			top_k_warp_safety_check(_SCREAMING_SNAKE_CASE   ,      _SCREAMING_SNAKE_CASE   ,      cur_len=_SCREAMING_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    :				List[str]	):
        lowerCAmelCase_       :    List[str]								=			None
        lowerCAmelCase_       :    str								=			1_0
        lowerCAmelCase_       :    Optional[int]								=			2

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

        lowerCAmelCase_       :    str								=			FlaxTopPLogitsWarper(0.8	)
        lowerCAmelCase_       :    List[str]								=			np.exp(top_p_warp(_SCREAMING_SNAKE_CASE   ,      _SCREAMING_SNAKE_CASE   ,      cur_len=_SCREAMING_SNAKE_CASE	)	)

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

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

        # make ramp_logits more extreme
        lowerCAmelCase_       :    Tuple								=			ramp_logits[1] * 1_0_0.0

        # make sure at least 2 tokens are kept
        lowerCAmelCase_       :    Tuple								=			FlaxTopPLogitsWarper(0.9   ,      min_tokens_to_keep=2   ,      filter_value=0.0	)
        lowerCAmelCase_       :    Optional[Any]								=			top_p_warp(_SCREAMING_SNAKE_CASE   ,      _SCREAMING_SNAKE_CASE   ,      cur_len=_SCREAMING_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    :				Union[str, Any]	):
        lowerCAmelCase_       :    int								=			2_0
        lowerCAmelCase_       :    Optional[Any]								=			4
        lowerCAmelCase_       :    List[str]								=			0

        lowerCAmelCase_       :    Union[str, Any]								=			FlaxMinLengthLogitsProcessor(min_length=1_0   ,      eos_token_id=_SCREAMING_SNAKE_CASE	)

        # check that min length is applied at length 5
        lowerCAmelCase_       :    Dict								=			ids_tensor((batch_size, 2_0)   ,      vocab_size=2_0	)
        lowerCAmelCase_       :    str								=			5
        lowerCAmelCase_       :    List[str]								=			self._get_uniform_logits(_SCREAMING_SNAKE_CASE   ,      _SCREAMING_SNAKE_CASE	)
        lowerCAmelCase_       :    List[str]								=			min_dist_processor(_SCREAMING_SNAKE_CASE   ,      _SCREAMING_SNAKE_CASE   ,      cur_len=_SCREAMING_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
        lowerCAmelCase_       :    Dict								=			self._get_uniform_logits(_SCREAMING_SNAKE_CASE   ,      _SCREAMING_SNAKE_CASE	)
        lowerCAmelCase_       :    Union[str, Any]								=			1_5
        lowerCAmelCase_       :    Optional[int]								=			min_dist_processor(_SCREAMING_SNAKE_CASE   ,      _SCREAMING_SNAKE_CASE   ,      cur_len=_SCREAMING_SNAKE_CASE	)
        self.assertFalse(jnp.isinf(_SCREAMING_SNAKE_CASE	).any()	)



      def 					SCREAMING_SNAKE_CASE__			(				self    :				Tuple	):
        lowerCAmelCase_       :    List[str]								=			2_0
        lowerCAmelCase_       :    List[Any]								=			4
        lowerCAmelCase_       :    Optional[int]								=			0

        lowerCAmelCase_       :    List[str]								=			FlaxForcedBOSTokenLogitsProcessor(bos_token_id=_SCREAMING_SNAKE_CASE	)

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



      def 					SCREAMING_SNAKE_CASE__			(				self    :				List[Any]	):
        lowerCAmelCase_       :    Any								=			2_0
        lowerCAmelCase_       :    Tuple								=			4
        lowerCAmelCase_       :    Dict								=			0
        lowerCAmelCase_       :    Dict								=			5

        lowerCAmelCase_       :    List[Any]								=			FlaxForcedEOSTokenLogitsProcessor(max_length=_SCREAMING_SNAKE_CASE   ,      eos_token_id=_SCREAMING_SNAKE_CASE	)

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



      def 					SCREAMING_SNAKE_CASE__			(				self    :				str	):
        lowerCAmelCase_       :    str								=			4
        lowerCAmelCase_       :    List[str]								=			1_0
        lowerCAmelCase_       :    Any								=			1_5
        lowerCAmelCase_       :    Dict								=			2
        lowerCAmelCase_       :    int								=			1
        lowerCAmelCase_       :    Dict								=			1_5

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

        lowerCAmelCase_       :    Optional[int]								=			self._get_uniform_logits(_SCREAMING_SNAKE_CASE   ,      _SCREAMING_SNAKE_CASE	)
        lowerCAmelCase_       :    Optional[Any]								=			scores.copy()

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

        # instantiate all logits processors
        lowerCAmelCase_       :    Optional[int]								=			FlaxMinLengthLogitsProcessor(min_length=1_0   ,      eos_token_id=_SCREAMING_SNAKE_CASE	)
        lowerCAmelCase_       :    str								=			FlaxForcedBOSTokenLogitsProcessor(bos_token_id=_SCREAMING_SNAKE_CASE	)
        lowerCAmelCase_       :    Union[str, Any]								=			FlaxForcedEOSTokenLogitsProcessor(max_length=_SCREAMING_SNAKE_CASE   ,      eos_token_id=_SCREAMING_SNAKE_CASE	)

        lowerCAmelCase_       :    Dict								=			1_0

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

        # with processor list
        lowerCAmelCase_       :    List[str]								=			FlaxLogitsProcessorList(
            [temp_dist_warp, top_k_warp, top_p_warp, min_dist_proc, bos_dist_proc, eos_dist_proc]	)
        lowerCAmelCase_       :    Optional[int]								=			processor(_SCREAMING_SNAKE_CASE   ,      _SCREAMING_SNAKE_CASE   ,      cur_len=_SCREAMING_SNAKE_CASE	)

        # scores should be equal
        self.assertTrue(jnp.allclose(_SCREAMING_SNAKE_CASE   ,      _SCREAMING_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    :				int	):
        lowerCAmelCase_       :    Tuple								=			4
        lowerCAmelCase_       :    Optional[Any]								=			1_0
        lowerCAmelCase_       :    List[Any]								=			1_5
        lowerCAmelCase_       :    Any								=			2
        lowerCAmelCase_       :    List[str]								=			1
        lowerCAmelCase_       :    str								=			1_5

        # dummy input_ids and scores
        lowerCAmelCase_       :    Dict								=			ids_tensor((batch_size, sequence_length)   ,      _SCREAMING_SNAKE_CASE	)
        lowerCAmelCase_       :    Dict								=			input_ids.copy()

        lowerCAmelCase_       :    List[str]								=			self._get_uniform_logits(_SCREAMING_SNAKE_CASE   ,      _SCREAMING_SNAKE_CASE	)
        lowerCAmelCase_       :    Dict								=			scores.copy()

        # instantiate all dist processors
        lowerCAmelCase_       :    Tuple								=			FlaxTemperatureLogitsWarper(temperature=0.5	)
        lowerCAmelCase_       :    str								=			FlaxTopKLogitsWarper(3	)
        lowerCAmelCase_       :    int								=			FlaxTopPLogitsWarper(0.8	)

        # instantiate all logits processors
        lowerCAmelCase_       :    Tuple								=			FlaxMinLengthLogitsProcessor(min_length=1_0   ,      eos_token_id=_SCREAMING_SNAKE_CASE	)
        lowerCAmelCase_       :    int								=			FlaxForcedBOSTokenLogitsProcessor(bos_token_id=_SCREAMING_SNAKE_CASE	)
        lowerCAmelCase_       :    Union[str, Any]								=			FlaxForcedEOSTokenLogitsProcessor(max_length=_SCREAMING_SNAKE_CASE   ,      eos_token_id=_SCREAMING_SNAKE_CASE	)

        lowerCAmelCase_       :    Union[str, Any]								=			1_0

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

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

        lowerCAmelCase_       :    Dict								=			jax.jit(_SCREAMING_SNAKE_CASE	)
        lowerCAmelCase_       :    Optional[Any]								=			jax.jit(_SCREAMING_SNAKE_CASE	)

        lowerCAmelCase_       :    Tuple								=			jitted_run_no_processor_list(_SCREAMING_SNAKE_CASE   ,      _SCREAMING_SNAKE_CASE   ,      _SCREAMING_SNAKE_CASE	)
        lowerCAmelCase_       :    Optional[int]								=			jitted_run_processor_list(_SCREAMING_SNAKE_CASE   ,      _SCREAMING_SNAKE_CASE   ,      _SCREAMING_SNAKE_CASE	)

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

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










"""simple docstring"""







import baseaa

def     UpperCamelCase_   (   lowerCAmelCase__				:    str						)						->       bytes:

  """simple docstring"""




  return baseaa.aaaencode(string.encode('utf-8'						)						)

def     UpperCamelCase_   (   lowerCAmelCase__				:    bytes						)						->       str:

  """simple docstring"""




  return baseaa.aaadecode(lowerCAmelCase__						).decode('utf-8'						)


if __name__ == "__main__":
     import doctest

     doctest.testmod()





