





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_    : Optional[int]								=	jnp.ones((batch_size, length)     ) / length
        return scores



     def   SCREAMING_SNAKE_CASE						(							self				:List[Any]     ):





        '''simple docstring'''




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

        A_    : Any								=	self._get_uniform_logits(batch_size=2	,					length=UpperCamelCase_     )

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

        # compute softmax
        A_    : Dict								=	jax.nn.softmax(UpperCamelCase_	,					axis=-1     )

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

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





        '''simple docstring'''




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

        # create ramp distribution
        A_    : Optional[Any]								=	np.broadcast_to(np.arange(UpperCamelCase_     )[None, :]	,					(batch_size, vocab_size)     ).copy()
        A_    : Optional[Any]								=	ramp_logits[1:, : vocab_size // 2] + vocab_size

        A_    : Optional[int]								=	FlaxTopKLogitsWarper(3     )

        A_    : Dict								=	top_k_warp(UpperCamelCase_	,					UpperCamelCase_	,					cur_len=UpperCamelCase_     )

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

        A_    : Dict								=	np.broadcast_to(np.arange(UpperCamelCase_     )[None, :]	,					(batch_size, length)     ).copy()
        A_    : Optional[int]								=	top_k_warp_safety_check(UpperCamelCase_	,					UpperCamelCase_	,					cur_len=UpperCamelCase_     )

        # 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[Any]     ):





        '''simple docstring'''




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

        # create distribution and take log (inverse to Softmax as taken in TopPLogitsWarper)
        A_    : List[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_    : Optional[Any]								=	np.exp(top_p_warp(UpperCamelCase_	,					UpperCamelCase_	,					cur_len=UpperCamelCase_     )     )

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

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

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

        # make sure at least 2 tokens are kept
        A_    : Dict								=	FlaxTopPLogitsWarper(0.9	,					min_tokens_to_keep=2	,					filter_value=0.0     )
        A_    : str								=	top_p_warp(UpperCamelCase_	,					UpperCamelCase_	,					cur_len=UpperCamelCase_     )

        # 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				:Optional[Any]     ):





        '''simple docstring'''




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

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

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



     def   SCREAMING_SNAKE_CASE						(							self				:List[Any]     ):





        '''simple docstring'''




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

        A_    : int								=	FlaxForcedBOSTokenLogitsProcessor(bos_token_id=UpperCamelCase_     )

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



     def   SCREAMING_SNAKE_CASE						(							self				:List[Any]     ):





        '''simple docstring'''




        A_    : Optional[Any]								=	20
        A_    : Dict								=	4
        A_    : Tuple								=	0
        A_    : Any								=	5

        A_    : Dict								=	FlaxForcedEOSTokenLogitsProcessor(max_length=UpperCamelCase_	,					eos_token_id=UpperCamelCase_     )

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



     def   SCREAMING_SNAKE_CASE						(							self				:str     ):





        '''simple docstring'''




        A_    : Union[str, Any]								=	4
        A_    : Tuple								=	10
        A_    : Union[str, Any]								=	15
        A_    : Union[str, Any]								=	2
        A_    : int								=	1
        A_    : Tuple								=	15

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

        A_    : Tuple								=	self._get_uniform_logits(UpperCamelCase_	,					UpperCamelCase_     )
        A_    : List[str]								=	scores.copy()

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

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

        A_    : List[str]								=	10

        # no processor list
        A_    : Dict								=	temp_dist_warp(UpperCamelCase_	,					UpperCamelCase_	,					cur_len=UpperCamelCase_     )
        A_    : Dict								=	top_k_warp(UpperCamelCase_	,					UpperCamelCase_	,					cur_len=UpperCamelCase_     )
        A_    : Optional[Any]								=	top_p_warp(UpperCamelCase_	,					UpperCamelCase_	,					cur_len=UpperCamelCase_     )
        A_    : Any								=	min_dist_proc(UpperCamelCase_	,					UpperCamelCase_	,					cur_len=UpperCamelCase_     )
        A_    : int								=	bos_dist_proc(UpperCamelCase_	,					UpperCamelCase_	,					cur_len=UpperCamelCase_     )
        A_    : List[Any]								=	eos_dist_proc(UpperCamelCase_	,					UpperCamelCase_	,					cur_len=UpperCamelCase_     )

        # with processor list
        A_    : Tuple								=	FlaxLogitsProcessorList(
            [temp_dist_warp, top_k_warp, top_p_warp, min_dist_proc, bos_dist_proc, eos_dist_proc]     )
        A_    : Optional[int]								=	processor(UpperCamelCase_	,					UpperCamelCase_	,					cur_len=UpperCamelCase_     )

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

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





     def   SCREAMING_SNAKE_CASE						(							self				:Dict     ):





        '''simple docstring'''




        A_    : Dict								=	4
        A_    : str								=	10
        A_    : str								=	15
        A_    : Union[str, Any]								=	2
        A_    : List[Any]								=	1
        A_    : List[Any]								=	15

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

        A_    : str								=	self._get_uniform_logits(UpperCamelCase_	,					UpperCamelCase_     )
        A_    : Any								=	scores.copy()

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

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

        A_    : Optional[Any]								=	10

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

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

        A_    : Any								=	jax.jit(UpperCamelCase_     )
        A_    : int								=	jax.jit(UpperCamelCase_     )

        A_    : str								=	jitted_run_no_processor_list(UpperCamelCase_	,					UpperCamelCase_	,					UpperCamelCase_     )
        A_    : int								=	jitted_run_processor_list(UpperCamelCase_	,					UpperCamelCase_	,					UpperCamelCase_     )

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

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




"""simple docstring"""





import gc
import unittest

from diffusers import FlaxDPMSolverMultistepScheduler, FlaxStableDiffusionPipeline
from diffusers.utils import is_flax_available, slow
from diffusers.utils.testing_utils import require_flax


if is_flax_available():
 import jax
 import jax.numpy as jnp
 from flax.jax_utils import replicate
 from flax.training.common_utils import shard



@slow
@require_flax
class 						snake_case_(				unittest.TestCase	):






     def    lowerCamelCase__   (		self     :    int ):
           # clean up the VRAM after each test
           super().tearDown()
           gc.collect()






     def    lowerCamelCase__   (		self     :    Optional[Any] ):
           lowerCAmelCase,					lowerCAmelCase    :		Optional[int]				=      FlaxStableDiffusionPipeline.from_pretrained(
               '''stabilityai/stable-diffusion-2'''    , revision='''bf16'''    , dtype=jnp.bfloataa    , )

           lowerCAmelCase    :		Optional[int]				=      '''A painting of a squirrel eating a burger'''
           lowerCAmelCase    :		List[str]				=      jax.device_count()
           lowerCAmelCase    :		Optional[int]				=      num_samples * [prompt]
           lowerCAmelCase    :		Any				=      sd_pipe.prepare_inputs(UpperCamelCase_ )

           lowerCAmelCase    :		Optional[int]				=      replicate(UpperCamelCase_ )
           lowerCAmelCase    :		Union[str, Any]				=      shard(UpperCamelCase_ )

           lowerCAmelCase    :		Optional[int]				=      jax.random.PRNGKey(0 )
           lowerCAmelCase    :		Optional[Any]				=      jax.random.split(UpperCamelCase_    , jax.device_count() )

           lowerCAmelCase    :		str				=      sd_pipe(UpperCamelCase_    , UpperCamelCase_    , UpperCamelCase_    , num_inference_steps=2_5    , jit=UpperCamelCase_ )[0]
           assert images.shape == (jax.device_count(), 1, 7_6_8, 7_6_8, 3)

           lowerCAmelCase    :		str				=      images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:] )
           lowerCAmelCase    :		List[str]				=      images[0, 2_5_3:2_5_6, 2_5_3:2_5_6, -1]

           lowerCAmelCase    :		Dict				=      jnp.asarray(jax.device_get(image_slice.flatten() ) )
           lowerCAmelCase    :		List[str]				=      jnp.array([0.4_238, 0.4_414, 0.4_395, 0.4_453, 0.4_629, 0.4_590, 0.4_531, 0.45_508, 0.4_512] )
           print(F'''output_slice: {output_slice}''' )
           assert jnp.abs(output_slice - expected_slice ).max() < 1E-2






     def    lowerCamelCase__   (		self     :    Union[str, Any] ):
           lowerCAmelCase    :		Union[str, Any]				=      '''stabilityai/stable-diffusion-2'''
           lowerCAmelCase,					lowerCAmelCase    :		Dict				=      FlaxDPMSolverMultistepScheduler.from_pretrained(UpperCamelCase_    , subfolder='''scheduler''' )
           lowerCAmelCase,					lowerCAmelCase    :		int				=      FlaxStableDiffusionPipeline.from_pretrained(
               UpperCamelCase_    , scheduler=UpperCamelCase_    , revision='''bf16'''    , dtype=jnp.bfloataa    , )
           lowerCAmelCase    :		List[Any]				=      scheduler_params

           lowerCAmelCase    :		List[Any]				=      '''A painting of a squirrel eating a burger'''
           lowerCAmelCase    :		Any				=      jax.device_count()
           lowerCAmelCase    :		int				=      num_samples * [prompt]
           lowerCAmelCase    :		int				=      sd_pipe.prepare_inputs(UpperCamelCase_ )

           lowerCAmelCase    :		Dict				=      replicate(UpperCamelCase_ )
           lowerCAmelCase    :		Tuple				=      shard(UpperCamelCase_ )

           lowerCAmelCase    :		int				=      jax.random.PRNGKey(0 )
           lowerCAmelCase    :		Optional[int]				=      jax.random.split(UpperCamelCase_    , jax.device_count() )

           lowerCAmelCase    :		Tuple				=      sd_pipe(UpperCamelCase_    , UpperCamelCase_    , UpperCamelCase_    , num_inference_steps=2_5    , jit=UpperCamelCase_ )[0]
           assert images.shape == (jax.device_count(), 1, 7_6_8, 7_6_8, 3)

           lowerCAmelCase    :		Any				=      images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:] )
           lowerCAmelCase    :		str				=      images[0, 2_5_3:2_5_6, 2_5_3:2_5_6, -1]

           lowerCAmelCase    :		Optional[int]				=      jnp.asarray(jax.device_get(image_slice.flatten() ) )
           lowerCAmelCase    :		Tuple				=      jnp.array([0.4_336, 0.42_969, 0.4_453, 0.4_199, 0.4_297, 0.4_531, 0.4_434, 0.4_434, 0.4_297] )
           print(F'''output_slice: {output_slice}''' )
           assert jnp.abs(output_slice - expected_slice ).max() < 1E-2


