





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





     """simple docstring"""



     def     SCREAMING_SNAKE_CASE		(				self							:Any      ,   snake_case							:int      ,   snake_case							:int	):





        '''simple docstring'''




        A_       :					int        =      jnp.ones((batch_size, length)	) / length
        return scores



     def     SCREAMING_SNAKE_CASE		(				self							:Any	):





        '''simple docstring'''




        A_       :					str        =      None
        A_       :					Optional[Any]        =      20

        A_       :					str        =      self._get_uniform_logits(batch_size=2      ,   length=a_	)

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

        # compute softmax
        A_       :					List[Any]        =      jax.nn.softmax(a_      ,   axis=-1	)

        A_       :					Optional[Any]        =      FlaxTemperatureLogitsWarper(temperature=0.5	)
        A_       :					List[Any]        =      FlaxTemperatureLogitsWarper(temperature=1.3	)

        A_       :					str        =      jax.nn.softmax(temp_dist_warper_sharper(a_      ,   scores.copy()      ,   cur_len=a_	)      ,   axis=-1	)
        A_       :					str        =      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     SCREAMING_SNAKE_CASE		(				self							:Optional[Any]	):





        '''simple docstring'''




        A_       :					List[Any]        =      None
        A_       :					int        =      10
        A_       :					List[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_       :					List[str]        =      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_       :					Any        =      5
        A_       :					Optional[int]        =      FlaxTopKLogitsWarper(top_k=1      ,   filter_value=0.0      ,   min_tokens_to_keep=3	)

        A_       :					List[str]        =      np.broadcast_to(np.arange(a_	)[None, :]      ,   (batch_size, length)	).copy()
        A_       :					int        =      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     SCREAMING_SNAKE_CASE		(				self							:Optional[Any]	):





        '''simple docstring'''




        A_       :					Any        =      None
        A_       :					List[str]        =      10
        A_       :					int        =      2

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

        A_       :					Any        =      FlaxTopPLogitsWarper(0.8	)
        A_       :					List[Any]        =      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_       :					Tuple        =      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_       :					Union[str, Any]        =      np.broadcast_to(np.arange(a_	)[None, :]      ,   (batch_size, vocab_size)	).copy() - (
            vocab_size // 2
        )

        # make ramp_logits more extreme
        A_       :					Dict        =      ramp_logits[1] * 100.0

        # make sure at least 2 tokens are kept
        A_       :					List[str]        =      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     SCREAMING_SNAKE_CASE		(				self							:str	):





        '''simple docstring'''




        A_       :					Optional[Any]        =      20
        A_       :					str        =      4
        A_       :					int        =      0

        A_       :					Any        =      FlaxMinLengthLogitsProcessor(min_length=10      ,   eos_token_id=a_	)

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



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





        '''simple docstring'''




        A_       :					List[Any]        =      20
        A_       :					Tuple        =      4
        A_       :					Optional[int]        =      0

        A_       :					Optional[int]        =      FlaxForcedBOSTokenLogitsProcessor(bos_token_id=a_	)

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



     def     SCREAMING_SNAKE_CASE		(				self							:str	):





        '''simple docstring'''




        A_       :					Union[str, Any]        =      20
        A_       :					Tuple        =      4
        A_       :					List[Any]        =      0
        A_       :					Optional[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_       :					Tuple        =      ids_tensor((batch_size, 4)      ,   vocab_size=20	)
        A_       :					Tuple        =      4
        A_       :					List[str]        =      self._get_uniform_logits(a_      ,   a_	)
        A_       :					List[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[Any]        =      3
        A_       :					Optional[int]        =      self._get_uniform_logits(a_      ,   a_	)
        A_       :					Tuple        =      logits_processor(a_      ,   a_      ,   cur_len=a_	)
        self.assertFalse(jnp.isinf(a_	).any()	)



     def     SCREAMING_SNAKE_CASE		(				self							:List[str]	):





        '''simple docstring'''




        A_       :					Optional[int]        =      4
        A_       :					List[Any]        =      10
        A_       :					Any        =      15
        A_       :					Optional[int]        =      2
        A_       :					List[str]        =      1
        A_       :					Optional[Any]        =      15

        # dummy input_ids and scores
        A_       :					Union[str, Any]        =      ids_tensor((batch_size, sequence_length)      ,   a_	)
        A_       :					List[Any]        =      input_ids.copy()

        A_       :					List[str]        =      self._get_uniform_logits(a_      ,   a_	)
        A_       :					int        =      scores.copy()

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

        # instantiate all logits processors
        A_       :					Tuple        =      FlaxMinLengthLogitsProcessor(min_length=10      ,   eos_token_id=a_	)
        A_       :					List[str]        =      FlaxForcedBOSTokenLogitsProcessor(bos_token_id=a_	)
        A_       :					int        =      FlaxForcedEOSTokenLogitsProcessor(max_length=a_      ,   eos_token_id=a_	)

        A_       :					str        =      10

        # no processor list
        A_       :					Tuple        =      temp_dist_warp(a_      ,   a_      ,   cur_len=a_	)
        A_       :					Dict        =      top_k_warp(a_      ,   a_      ,   cur_len=a_	)
        A_       :					Optional[Any]        =      top_p_warp(a_      ,   a_      ,   cur_len=a_	)
        A_       :					Tuple        =      min_dist_proc(a_      ,   a_      ,   cur_len=a_	)
        A_       :					Dict        =      bos_dist_proc(a_      ,   a_      ,   cur_len=a_	)
        A_       :					Union[str, Any]        =      eos_dist_proc(a_      ,   a_      ,   cur_len=a_	)

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





        '''simple docstring'''




        A_       :					Optional[int]        =      4
        A_       :					Optional[Any]        =      10
        A_       :					str        =      15
        A_       :					Any        =      2
        A_       :					Dict        =      1
        A_       :					Optional[Any]        =      15

        # dummy input_ids and scores
        A_       :					Any        =      ids_tensor((batch_size, sequence_length)      ,   a_	)
        A_       :					Tuple        =      input_ids.copy()

        A_       :					Dict        =      self._get_uniform_logits(a_      ,   a_	)
        A_       :					Optional[int]        =      scores.copy()

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

        # instantiate all logits processors
        A_       :					int        =      FlaxMinLengthLogitsProcessor(min_length=10      ,   eos_token_id=a_	)
        A_       :					Optional[int]        =      FlaxForcedBOSTokenLogitsProcessor(bos_token_id=a_	)
        A_       :					Dict        =      FlaxForcedEOSTokenLogitsProcessor(max_length=a_      ,   eos_token_id=a_	)

        A_       :					Optional[int]        =      10

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

        # with processor list
        def run_processor_list(snake_case							:List[str]      ,   snake_case							:Dict      ,   snake_case							:Dict	):
           A_       :					str        =      FlaxLogitsProcessorList(
               [temp_dist_warp, top_k_warp, top_p_warp, min_dist_proc, bos_dist_proc, eos_dist_proc]	)
           A_       :					int        =      processor(a_      ,   a_      ,   cur_len=a_	)
           return scores

        A_       :					Any        =      jax.jit(a_	)
        A_       :					List[Any]        =      jax.jit(a_	)

        A_       :					Optional[Any]        =      jitted_run_no_processor_list(a_      ,   a_      ,   a_	)
        A_       :					List[Any]        =      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 __future__ import annotations






def      lowercase__ (					lowerCAmelCase__   :			int			)    ->			list[int]:



			'''simple docstring'''
			a__  :	Tuple		 =			[True] * limit
			a__  :	Tuple		 =			False
			a__  :	int		 =			False
			a__  :	Tuple		 =			True

			for i in range(3							,			int(limit**0.5 + 1			)							,			2			):
						a__  :	int		 =			i * 2
						while index < limit:
									a__  :	Union[str, Any]		 =			False
									a__  :	int		 =			index + i

			a__  :	str		 =			[2]

			for i in range(3							,			lowerCAmelCase__							,			2			):
						if is_prime[i]:
									primes.append(lowerCAmelCase__			)

			return primes






def      lowercase__ (					lowerCAmelCase__   :			int = 1_0_0_0_0_0_0			)    ->			int:



			'''simple docstring'''
			a__  :	List[Any]		 =			prime_sieve(lowerCAmelCase__			)
			a__  :	int		 =			0
			a__  :	str		 =			0

			for i in range(len(lowerCAmelCase__			)			):
						for j in range(i + length							,			len(lowerCAmelCase__			)			):
									a__  :	List[str]		 =			sum(primes[i:j]			)
									if sol >= ceiling:
												break

									if sol in primes:
												a__  :	Tuple		 =			j - i
												a__  :	Union[str, Any]		 =			sol

			return largest


if __name__ == "__main__":
		print(f"{solution() = }")