






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





    def     lowerCamelCase__				(							self     : int    ,		A     : int    ,		A     : int      ):


      '''simple docstring'''




      a					:      Tuple    =       jnp.ones((batch_size, length)      ) / length
      return scores





    def     lowerCamelCase__				(							self     : Tuple      ):


      '''simple docstring'''




      a					:      Optional[Any]    =       None
      a					:      Tuple    =       2_0

      a					:      str    =       self._get_uniform_logits(batch_size=2    ,		length=A      )

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

      # compute softmax
      a					:      Optional[int]    =       jax.nn.softmax(A    ,		axis=-1      )

      a					:      str    =       FlaxTemperatureLogitsWarper(temperature=0.5      )
      a					:      int    =       FlaxTemperatureLogitsWarper(temperature=1.3      )

      a					:      Dict    =       jax.nn.softmax(temp_dist_warper_sharper(A    ,		scores.copy()    ,		cur_len=A      )    ,		axis=-1      )
      a					:      Dict    =       jax.nn.softmax(temp_dist_warper_smoother(A    ,		scores.copy()    ,		cur_len=A      )    ,		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     lowerCamelCase__				(							self     : Any      ):


      '''simple docstring'''




      a					:      Any    =       None
      a					:      Dict    =       1_0
      a					:      str    =       2

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

      a					:      Union[str, Any]    =       FlaxTopKLogitsWarper(3      )

      a					:      Dict    =       top_k_warp(A    ,		A    ,		cur_len=A      )

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

      a					:      str    =       np.broadcast_to(np.arange(A      )[None, :]    ,		(batch_size, length)      ).copy()
      a					:      Union[str, Any]    =       top_k_warp_safety_check(A    ,		A    ,		cur_len=A      )

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





    def     lowerCamelCase__				(							self     : Union[str, Any]      ):


      '''simple docstring'''




      a					:      Tuple    =       None
      a					:      Any    =       1_0
      a					:      str    =       2

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

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

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

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

      # make ramp_logits more extreme
      a					:      Optional[Any]    =       ramp_logits[1] * 1_00.0

      # make sure at least 2 tokens are kept
      a					:      List[Any]    =       FlaxTopPLogitsWarper(0.9    ,		min_tokens_to_keep=2    ,		filter_value=0.0      )
      a					:      Any    =       top_p_warp(A    ,		A    ,		cur_len=A      )

      # 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     lowerCamelCase__				(							self     : List[Any]      ):


      '''simple docstring'''




      a					:      Union[str, Any]    =       2_0
      a					:      List[Any]    =       4
      a					:      Optional[int]    =       0

      a					:      Tuple    =       FlaxMinLengthLogitsProcessor(min_length=1_0    ,		eos_token_id=A      )

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





    def     lowerCamelCase__				(							self     : List[Any]      ):


      '''simple docstring'''




      a					:      Union[str, Any]    =       2_0
      a					:      Optional[int]    =       4
      a					:      List[Any]    =       0

      a					:      str    =       FlaxForcedBOSTokenLogitsProcessor(bos_token_id=A      )

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





    def     lowerCamelCase__				(							self     : Optional[Any]      ):


      '''simple docstring'''




      a					:      Any    =       2_0
      a					:      Union[str, Any]    =       4
      a					:      Union[str, Any]    =       0
      a					:      Union[str, Any]    =       5

      a					:      int    =       FlaxForcedEOSTokenLogitsProcessor(max_length=A    ,		eos_token_id=A      )

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





    def     lowerCamelCase__				(							self     : Any      ):


      '''simple docstring'''




      a					:      int    =       4
      a					:      Union[str, Any]    =       1_0
      a					:      Dict    =       1_5
      a					:      int    =       2
      a					:      List[str]    =       1
      a					:      str    =       1_5

      # dummy input_ids and scores
      a					:      Dict    =       ids_tensor((batch_size, sequence_length)    ,		A      )
      a					:      Optional[int]    =       input_ids.copy()

      a					:      str    =       self._get_uniform_logits(A    ,		A      )
      a					:      str    =       scores.copy()

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

      # instantiate all logits processors
      a					:      List[str]    =       FlaxMinLengthLogitsProcessor(min_length=1_0    ,		eos_token_id=A      )
      a					:      Optional[int]    =       FlaxForcedBOSTokenLogitsProcessor(bos_token_id=A      )
      a					:      str    =       FlaxForcedEOSTokenLogitsProcessor(max_length=A    ,		eos_token_id=A      )

      a					:      Dict    =       1_0

      # no processor list
      a					:      Any    =       temp_dist_warp(A    ,		A    ,		cur_len=A      )
      a					:      int    =       top_k_warp(A    ,		A    ,		cur_len=A      )
      a					:      Tuple    =       top_p_warp(A    ,		A    ,		cur_len=A      )
      a					:      Any    =       min_dist_proc(A    ,		A    ,		cur_len=A      )
      a					:      Dict    =       bos_dist_proc(A    ,		A    ,		cur_len=A      )
      a					:      Tuple    =       eos_dist_proc(A    ,		A    ,		cur_len=A      )

      # with processor list
      a					:      Union[str, Any]    =       FlaxLogitsProcessorList(
          [temp_dist_warp, top_k_warp, top_p_warp, min_dist_proc, bos_dist_proc, eos_dist_proc]      )
      a					:      str    =       processor(A    ,		A    ,		cur_len=A      )

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

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





    def     lowerCamelCase__				(							self     : str      ):


      '''simple docstring'''




      a					:      int    =       4
      a					:      List[Any]    =       1_0
      a					:      Any    =       1_5
      a					:      str    =       2
      a					:      Union[str, Any]    =       1
      a					:      Optional[int]    =       1_5

      # dummy input_ids and scores
      a					:      Union[str, Any]    =       ids_tensor((batch_size, sequence_length)    ,		A      )
      a					:      Dict    =       input_ids.copy()

      a					:      Dict    =       self._get_uniform_logits(A    ,		A      )
      a					:      Any    =       scores.copy()

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

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

      a					:      Optional[Any]    =       1_0

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

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

      a					:      Union[str, Any]    =       jax.jit(A      )
      a					:      Any    =       jax.jit(A      )

      a					:      Optional[Any]    =       jitted_run_no_processor_list(A    ,		A    ,		A      )
      a					:      Tuple    =       jitted_run_processor_list(A    ,		A    ,		A      )

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

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












"""simple docstring"""


from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available


_UpperCamelCase    :   Optional[int]   			=						{
    'configuration_rag': ['RagConfig'],
    'retrieval_rag': ['RagRetriever'],
    'tokenization_rag': ['RagTokenizer'],
}

try:
   if not is_torch_available():
      raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
   pass
else:
   _UpperCamelCase    :   Dict   			=						[
       'RagModel',
       'RagPreTrainedModel',
       'RagSequenceForGeneration',
       'RagTokenForGeneration',
   ]

try:
   if not is_tf_available():
      raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
   pass
else:
   _UpperCamelCase    :   Optional[int]   			=						[
       'TFRagModel',
       'TFRagPreTrainedModel',
       'TFRagSequenceForGeneration',
       'TFRagTokenForGeneration',
   ]


if TYPE_CHECKING:
   from .configuration_rag import RagConfig
   from .retrieval_rag import RagRetriever
   from .tokenization_rag import RagTokenizer

   try:
      if not is_torch_available():
         raise OptionalDependencyNotAvailable()
   except OptionalDependencyNotAvailable:
      pass
   else:
      from .modeling_rag import RagModel, RagPreTrainedModel, RagSequenceForGeneration, RagTokenForGeneration

   try:
      if not is_tf_available():
         raise OptionalDependencyNotAvailable()
   except OptionalDependencyNotAvailable:
      pass
   else:
      from .modeling_tf_rag import (
          TFRagModel,
          TFRagPreTrainedModel,
          TFRagSequenceForGeneration,
          TFRagTokenForGeneration,
      )

else:
   import sys

   _UpperCamelCase    :   int   			=						_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)




