



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  ):



   '''simple docstring'''






   def      UpperCamelCase_  (					self							:			List[str]				,		lowerCAmelCase							:			List[Any]				,		lowerCAmelCase							:			List[Any])				->				Tuple:

    """simple docstring"""







    _snake_case    :  Optional[int]					=					jnp.ones((batch_size, length)) / length
    return scores

   def      UpperCamelCase_  (					self							:			Any)				->				Dict:

    """simple docstring"""







    _snake_case    :  Union[str, Any]					=					None
    _snake_case    :  List[Any]					=					20

    _snake_case    :  str					=					self._get_uniform_logits(batch_size=2				,		length=__lowerCAmelCase)

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

    # compute softmax
    _snake_case    :  Any					=					jax.nn.softmax(__lowerCAmelCase				,		axis=-1)

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

    _snake_case    :  Optional[Any]					=					jax.nn.softmax(temp_dist_warper_sharper(__lowerCAmelCase				,		scores.copy()				,		cur_len=__lowerCAmelCase)				,		axis=-1)
    _snake_case    :  Optional[int]					=					jax.nn.softmax(temp_dist_warper_smoother(__lowerCAmelCase				,		scores.copy()				,		cur_len=__lowerCAmelCase)				,		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      UpperCamelCase_  (					self							:			int)				->				List[Any]:

    """simple docstring"""







    _snake_case    :  Dict					=					None
    _snake_case    :  Optional[Any]					=					10
    _snake_case    :  Tuple					=					2

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

    _snake_case    :  Dict					=					FlaxTopKLogitsWarper(3)

    _snake_case    :  str					=					top_k_warp(__lowerCAmelCase				,		__lowerCAmelCase				,		cur_len=__lowerCAmelCase)

    # 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
    _snake_case    :  Optional[int]					=					5
    _snake_case    :  Tuple					=					FlaxTopKLogitsWarper(top_k=1				,		filter_value=0.0				,		min_tokens_to_keep=3)

    _snake_case    :  Any					=					np.broadcast_to(np.arange(__lowerCAmelCase)[None, :]				,		(batch_size, length)).copy()
    _snake_case    :  Tuple					=					top_k_warp_safety_check(__lowerCAmelCase				,		__lowerCAmelCase				,		cur_len=__lowerCAmelCase)

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

   def      UpperCamelCase_  (					self							:			str)				->				Optional[int]:

    """simple docstring"""







    _snake_case    :  Union[str, Any]					=					None
    _snake_case    :  Optional[int]					=					10
    _snake_case    :  Tuple					=					2

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

    _snake_case    :  Union[str, Any]					=					FlaxTopPLogitsWarper(0.8)
    _snake_case    :  Union[str, Any]					=					np.exp(top_p_warp(__lowerCAmelCase				,		__lowerCAmelCase				,		cur_len=__lowerCAmelCase))

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

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

    # make ramp_logits more extreme
    _snake_case    :  str					=					ramp_logits[1] * 100.0

    # make sure at least 2 tokens are kept
    _snake_case    :  Dict					=					FlaxTopPLogitsWarper(0.9				,		min_tokens_to_keep=2				,		filter_value=0.0)
    _snake_case    :  Tuple					=					top_p_warp(__lowerCAmelCase				,		__lowerCAmelCase				,		cur_len=__lowerCAmelCase)

    # 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      UpperCamelCase_  (					self							:			Union[str, Any])				->				Union[str, Any]:

    """simple docstring"""







    _snake_case    :  Optional[int]					=					20
    _snake_case    :  Union[str, Any]					=					4
    _snake_case    :  Optional[int]					=					0

    _snake_case    :  Dict					=					FlaxMinLengthLogitsProcessor(min_length=10				,		eos_token_id=__lowerCAmelCase)

    # check that min length is applied at length 5
    _snake_case    :  Tuple					=					ids_tensor((batch_size, 20)				,		vocab_size=20)
    _snake_case    :  Any					=					5
    _snake_case    :  Any					=					self._get_uniform_logits(__lowerCAmelCase				,		__lowerCAmelCase)
    _snake_case    :  Dict					=					min_dist_processor(__lowerCAmelCase				,		__lowerCAmelCase				,		cur_len=__lowerCAmelCase)
    self.assertListEqual(scores_before_min_length[:, eos_token_id].tolist()				,		4 * [-float("""inf""")])

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

   def      UpperCamelCase_  (					self							:			Optional[Any])				->				Dict:

    """simple docstring"""







    _snake_case    :  int					=					20
    _snake_case    :  Optional[Any]					=					4
    _snake_case    :  List[str]					=					0

    _snake_case    :  Dict					=					FlaxForcedBOSTokenLogitsProcessor(bos_token_id=__lowerCAmelCase)

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

   def      UpperCamelCase_  (					self							:			Union[str, Any])				->				List[str]:

    """simple docstring"""







    _snake_case    :  Optional[int]					=					20
    _snake_case    :  Dict					=					4
    _snake_case    :  List[str]					=					0
    _snake_case    :  int					=					5

    _snake_case    :  int					=					FlaxForcedEOSTokenLogitsProcessor(max_length=__lowerCAmelCase				,		eos_token_id=__lowerCAmelCase)

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

   def      UpperCamelCase_  (					self							:			Dict)				->				Dict:

    """simple docstring"""







    _snake_case    :  Optional[int]					=					4
    _snake_case    :  Tuple					=					10
    _snake_case    :  int					=					15
    _snake_case    :  Optional[int]					=					2
    _snake_case    :  int					=					1
    _snake_case    :  List[str]					=					15

    # dummy input_ids and scores
    _snake_case    :  Tuple					=					ids_tensor((batch_size, sequence_length)				,		__lowerCAmelCase)
    _snake_case    :  Union[str, Any]					=					input_ids.copy()

    _snake_case    :  Any					=					self._get_uniform_logits(__lowerCAmelCase				,		__lowerCAmelCase)
    _snake_case    :  Dict					=					scores.copy()

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

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

    _snake_case    :  Optional[int]					=					10

    # no processor list
    _snake_case    :  Optional[int]					=					temp_dist_warp(__lowerCAmelCase				,		__lowerCAmelCase				,		cur_len=__lowerCAmelCase)
    _snake_case    :  Union[str, Any]					=					top_k_warp(__lowerCAmelCase				,		__lowerCAmelCase				,		cur_len=__lowerCAmelCase)
    _snake_case    :  int					=					top_p_warp(__lowerCAmelCase				,		__lowerCAmelCase				,		cur_len=__lowerCAmelCase)
    _snake_case    :  Any					=					min_dist_proc(__lowerCAmelCase				,		__lowerCAmelCase				,		cur_len=__lowerCAmelCase)
    _snake_case    :  int					=					bos_dist_proc(__lowerCAmelCase				,		__lowerCAmelCase				,		cur_len=__lowerCAmelCase)
    _snake_case    :  List[Any]					=					eos_dist_proc(__lowerCAmelCase				,		__lowerCAmelCase				,		cur_len=__lowerCAmelCase)

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

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

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


   def      UpperCamelCase_  (					self							:			Any)				->				Union[str, Any]:

    """simple docstring"""







    _snake_case    :  Optional[int]					=					4
    _snake_case    :  Dict					=					10
    _snake_case    :  List[Any]					=					15
    _snake_case    :  Union[str, Any]					=					2
    _snake_case    :  str					=					1
    _snake_case    :  Any					=					15

    # dummy input_ids and scores
    _snake_case    :  Optional[Any]					=					ids_tensor((batch_size, sequence_length)				,		__lowerCAmelCase)
    _snake_case    :  Dict					=					input_ids.copy()

    _snake_case    :  List[str]					=					self._get_uniform_logits(__lowerCAmelCase				,		__lowerCAmelCase)
    _snake_case    :  int					=					scores.copy()

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

    # instantiate all logits processors
    _snake_case    :  str					=					FlaxMinLengthLogitsProcessor(min_length=10				,		eos_token_id=__lowerCAmelCase)
    _snake_case    :  List[str]					=					FlaxForcedBOSTokenLogitsProcessor(bos_token_id=__lowerCAmelCase)
    _snake_case    :  str					=					FlaxForcedEOSTokenLogitsProcessor(max_length=__lowerCAmelCase				,		eos_token_id=__lowerCAmelCase)

    _snake_case    :  List[Any]					=					10

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

    # with processor list
    def run_processor_list(lowerCAmelCase							:			Tuple				,		lowerCAmelCase							:			Optional[int]				,		lowerCAmelCase							:			Union[str, Any]):
     _snake_case    :  str					=					FlaxLogitsProcessorList(
         [temp_dist_warp, top_k_warp, top_p_warp, min_dist_proc, bos_dist_proc, eos_dist_proc])
     _snake_case    :  List[str]					=					processor(__lowerCAmelCase				,		__lowerCAmelCase				,		cur_len=__lowerCAmelCase)
     return scores

    _snake_case    :  Union[str, Any]					=					jax.jit(__lowerCAmelCase)
    _snake_case    :  Dict					=					jax.jit(__lowerCAmelCase)

    _snake_case    :  Optional[Any]					=					jitted_run_no_processor_list(__lowerCAmelCase				,		__lowerCAmelCase				,		__lowerCAmelCase)
    _snake_case    :  List[Any]					=					jitted_run_processor_list(__lowerCAmelCase				,		__lowerCAmelCase				,		__lowerCAmelCase)

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

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





import json
import os
import unittest

from transformers.models.ctrl.tokenization_ctrl import VOCAB_FILES_NAMES, CTRLTokenizer

from ...test_tokenization_common import TokenizerTesterMixin







class 		snake_case						(	SCREAMING_SNAKE_CASE_					,unittest.TestCase  ):



   '''simple docstring'''






   snake_case_					: Optional[Any]          =		CTRLTokenizer
   snake_case_					: Optional[Any]          =		False
   snake_case_					: List[Any]          =		False

   def      UpperCamelCase_  (					self							:			int)				->				Dict:

    """simple docstring"""







    super().setUp()

    # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt
    _snake_case    :  Dict					=					["""adapt""", """re@@""", """a@@""", """apt""", """c@@""", """t""", """<unk>"""]
    _snake_case    :  Optional[int]					=					dict(zip(lowerCAmelCase				,		range(len(lowerCAmelCase))))
    _snake_case    :  int					=					["""#version: 0.2""", """a p""", """ap t</w>""", """r e""", """a d""", """ad apt</w>""", """"""]
    _snake_case    :  List[Any]					=					{"""unk_token""": """<unk>"""}

    _snake_case    :  Dict					=					os.path.join(self.tmpdirname				,		VOCAB_FILES_NAMES["""vocab_file"""])
    _snake_case    :  Any					=					os.path.join(self.tmpdirname				,		VOCAB_FILES_NAMES["""merges_file"""])
    with open(self.vocab_file				,		"""w"""				,		encoding="""utf-8""") as fp:
     fp.write(json.dumps(lowerCAmelCase) + """\n""")
    with open(self.merges_file				,		"""w"""				,		encoding="""utf-8""") as fp:
     fp.write("""\n""".join(lowerCAmelCase))

   def      UpperCamelCase_  (					self							:			Dict				,		**lowerCAmelCase							:			int)				->				Optional[Any]:

    """simple docstring"""







    kwargs.update(self.special_tokens_map)
    return CTRLTokenizer.from_pretrained(self.tmpdirname				,		**lowerCAmelCase)

   def      UpperCamelCase_  (					self							:			Any				,		lowerCAmelCase							:			Optional[int])				->				Optional[int]:

    """simple docstring"""







    _snake_case    :  Tuple					=					"""adapt react readapt apt"""
    _snake_case    :  Tuple					=					"""adapt react readapt apt"""
    return input_text, output_text


   def      UpperCamelCase_  (					self							:			Union[str, Any])				->				str:

    """simple docstring"""







    _snake_case    :  str					=					CTRLTokenizer(self.vocab_file				,		self.merges_file				,		**self.special_tokens_map)
    _snake_case    :  Dict					=					"""adapt react readapt apt"""
    _snake_case    :  int					=					"""adapt re@@ a@@ c@@ t re@@ adapt apt""".split()
    _snake_case    :  Tuple					=					tokenizer.tokenize(lowerCAmelCase)
    self.assertListEqual(lowerCAmelCase				,		lowerCAmelCase)

    _snake_case    :  str					=					tokens + [tokenizer.unk_token]

    _snake_case    :  Union[str, Any]					=					[0, 1, 2, 4, 5, 1, 0, 3, 6]
    self.assertListEqual(tokenizer.convert_tokens_to_ids(lowerCAmelCase)				,		lowerCAmelCase)
