




import gc
import unittest

from parameterized import parameterized

from diffusers import FlaxUNetaDConditionModel
from diffusers.utils import is_flax_available
from diffusers.utils.testing_utils import load_hf_numpy, require_flax, slow


if is_flax_available():
   import jax
   import jax.numpy as jnp





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


 '''simple docstring'''







 def  lowerCAmelCase_    (				self    :						List[str]							,							_lowerCAmelCase    :						Dict							,							_lowerCAmelCase    :						Optional[int]		):
       return F"gaussian_noise_s={seed}_shape={'_'.join([str(_lowerCAmelCase		) for s in shape]		)}.npy"



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



 def  lowerCAmelCase_    (				self    :						int							,							_lowerCAmelCase    :						int=0							,							_lowerCAmelCase    :						Dict=(4, 4, 64, 64)							,							_lowerCAmelCase    :						List[str]=False		):
       SCREAMING_SNAKE_CASE_      		=     jnp.bfloataa if fpaa else jnp.floataa
       SCREAMING_SNAKE_CASE_      		=     jnp.array(load_hf_numpy(self.get_file_format(_lowerCAmelCase							,							_lowerCAmelCase		)		)							,							dtype=_lowerCAmelCase		)
       return image



 def  lowerCAmelCase_    (				self    :						List[str]							,							_lowerCAmelCase    :						List[Any]=False							,							_lowerCAmelCase    :						Optional[Any]="CompVis/stable-diffusion-v1-4"		):
       SCREAMING_SNAKE_CASE_      		=     jnp.bfloataa if fpaa else jnp.floataa
       SCREAMING_SNAKE_CASE_      		=     'bf16' if fpaa else None

       SCREAMING_SNAKE_CASE_		,					SCREAMING_SNAKE_CASE_      		=     FlaxUNetaDConditionModel.from_pretrained(
           _lowerCAmelCase							,							subfolder='unet'							,							dtype=_lowerCAmelCase							,							revision=_lowerCAmelCase		)
       return model, params



 def  lowerCAmelCase_    (				self    :						List[Any]							,							_lowerCAmelCase    :						Tuple=0							,							_lowerCAmelCase    :						List[str]=(4, 77, 768)							,							_lowerCAmelCase    :						List[str]=False		):
       SCREAMING_SNAKE_CASE_      		=     jnp.bfloataa if fpaa else jnp.floataa
       SCREAMING_SNAKE_CASE_      		=     jnp.array(load_hf_numpy(self.get_file_format(_lowerCAmelCase							,							_lowerCAmelCase		)		)							,							dtype=_lowerCAmelCase		)
       return hidden_states



 @parameterized.expand(
     [
         # fmt: off
         [83, 4, [-0.2323, -0.1304, 0.0813, -0.3093, -0.0919, -0.1571, -0.1125, -0.5806]],
         [17, 0.55, [-0.0831, -0.2443, 0.0901, -0.0919, 0.3396, 0.0103, -0.3743, 0.0701]],
         [8, 0.89, [-0.4863, 0.0859, 0.0875, -0.1658, 0.9199, -0.0114, 0.4839, 0.4639]],
         [3, 1_000, [-0.5649, 0.2402, -0.5518, 0.1248, 1.1328, -0.2443, -0.0325, -1.0078]],
         # fmt: on
     ]		)
 def  lowerCAmelCase_    (				self    :						List[str]							,							_lowerCAmelCase    :						Optional[Any]							,							_lowerCAmelCase    :						Any							,							_lowerCAmelCase    :						Optional[Any]		):
       SCREAMING_SNAKE_CASE_		,					SCREAMING_SNAKE_CASE_      		=     self.get_unet_model(model_id='CompVis/stable-diffusion-v1-4'							,							fpaa=_lowerCAmelCase		)
       SCREAMING_SNAKE_CASE_      		=     self.get_latents(_lowerCAmelCase							,							fpaa=_lowerCAmelCase		)
       SCREAMING_SNAKE_CASE_      		=     self.get_encoder_hidden_states(_lowerCAmelCase							,							fpaa=_lowerCAmelCase		)

       SCREAMING_SNAKE_CASE_      		=     model.apply(
           {'params': params}							,							_lowerCAmelCase							,							jnp.array(_lowerCAmelCase							,							dtype=jnp.intaa		)							,							encoder_hidden_states=_lowerCAmelCase							,							).sample

       assert sample.shape == latents.shape

       SCREAMING_SNAKE_CASE_      		=     jnp.asarray(jax.device_get((sample[-1, -2:, -2:, :2].flatten())		)							,							dtype=jnp.floataa		)
       SCREAMING_SNAKE_CASE_      		=     jnp.array(_lowerCAmelCase							,							dtype=jnp.floataa		)

       # Found torch (float16) and flax (bfloat16) outputs to be within this tolerance, in the same hardware
       assert jnp.allclose(_lowerCAmelCase							,							_lowerCAmelCase							,							atol=1E-2		)




 @parameterized.expand(
     [
         # fmt: off
         [83, 4, [0.1514, 0.0807, 0.1624, 0.1016, -0.1896, 0.0263, 0.0677, 0.2310]],
         [17, 0.55, [0.1164, -0.0216, 0.0170, 0.1589, -0.3120, 0.1005, -0.0581, -0.1458]],
         [8, 0.89, [-0.1758, -0.0169, 0.1004, -0.1411, 0.1312, 0.1103, -0.1996, 0.2139]],
         [3, 1_000, [0.1214, 0.0352, -0.0731, -0.1562, -0.0994, -0.0906, -0.2340, -0.0539]],
         # fmt: on
     ]		)
 def  lowerCAmelCase_    (				self    :						Optional[int]							,							_lowerCAmelCase    :						Union[str, Any]							,							_lowerCAmelCase    :						Dict							,							_lowerCAmelCase    :						Dict		):
       SCREAMING_SNAKE_CASE_		,					SCREAMING_SNAKE_CASE_      		=     self.get_unet_model(model_id='stabilityai/stable-diffusion-2'							,							fpaa=_lowerCAmelCase		)
       SCREAMING_SNAKE_CASE_      		=     self.get_latents(_lowerCAmelCase							,							shape=(4, 4, 96, 96)							,							fpaa=_lowerCAmelCase		)
       SCREAMING_SNAKE_CASE_      		=     self.get_encoder_hidden_states(_lowerCAmelCase							,							shape=(4, 77, 1_024)							,							fpaa=_lowerCAmelCase		)

       SCREAMING_SNAKE_CASE_      		=     model.apply(
           {'params': params}							,							_lowerCAmelCase							,							jnp.array(_lowerCAmelCase							,							dtype=jnp.intaa		)							,							encoder_hidden_states=_lowerCAmelCase							,							).sample

       assert sample.shape == latents.shape

       SCREAMING_SNAKE_CASE_      		=     jnp.asarray(jax.device_get((sample[-1, -2:, -2:, :2].flatten())		)							,							dtype=jnp.floataa		)
       SCREAMING_SNAKE_CASE_      		=     jnp.array(_lowerCAmelCase							,							dtype=jnp.floataa		)

       # Found torch (float16) and flax (bfloat16) outputs to be within this tolerance, on the same hardware
       assert jnp.allclose(_lowerCAmelCase							,							_lowerCAmelCase							,							atol=1E-2		)





from ...configuration_utils import PretrainedConfig
from ...utils import logging


lowerCamelCase__					:  str      							=				logging.get_logger(__name__)

lowerCamelCase__					:  Tuple      							=				{
    'funnel-transformer/small': 'https://huggingface.co/funnel-transformer/small/resolve/main/config.json',
    'funnel-transformer/small-base': 'https://huggingface.co/funnel-transformer/small-base/resolve/main/config.json',
    'funnel-transformer/medium': 'https://huggingface.co/funnel-transformer/medium/resolve/main/config.json',
    'funnel-transformer/medium-base': 'https://huggingface.co/funnel-transformer/medium-base/resolve/main/config.json',
    'funnel-transformer/intermediate': (
        'https://huggingface.co/funnel-transformer/intermediate/resolve/main/config.json'
    ),
    'funnel-transformer/intermediate-base': (
        'https://huggingface.co/funnel-transformer/intermediate-base/resolve/main/config.json'
    ),
    'funnel-transformer/large': 'https://huggingface.co/funnel-transformer/large/resolve/main/config.json',
    'funnel-transformer/large-base': 'https://huggingface.co/funnel-transformer/large-base/resolve/main/config.json',
    'funnel-transformer/xlarge': 'https://huggingface.co/funnel-transformer/xlarge/resolve/main/config.json',
    'funnel-transformer/xlarge-base': 'https://huggingface.co/funnel-transformer/xlarge-base/resolve/main/config.json',
}





class 			lowerCamelCase_				( _SCREAMING_SNAKE_CASE   ):


 '''simple docstring'''







 lowercase_							       =       "funnel"
 lowercase_							       =       {
     "hidden_size": "d_model",
     "num_attention_heads": "n_head",
 }



 def __init__(				self    :						int							,							_lowerCAmelCase    :						Optional[int]=30_522							,							_lowerCAmelCase    :						List[str]=[4, 4, 4]							,							_lowerCAmelCase    :						Tuple=None							,							_lowerCAmelCase    :						Optional[int]=2							,							_lowerCAmelCase    :						int=768							,							_lowerCAmelCase    :						Optional[Any]=12							,							_lowerCAmelCase    :						Optional[Any]=64							,							_lowerCAmelCase    :						Optional[Any]=3_072							,							_lowerCAmelCase    :						List[str]="gelu_new"							,							_lowerCAmelCase    :						Any=0.1							,							_lowerCAmelCase    :						int=0.1							,							_lowerCAmelCase    :						Tuple=0.0							,							_lowerCAmelCase    :						List[Any]=0.1							,							_lowerCAmelCase    :						Dict=None							,							_lowerCAmelCase    :						str=1E-9							,							_lowerCAmelCase    :						Any="mean"							,							_lowerCAmelCase    :						Union[str, Any]="relative_shift"							,							_lowerCAmelCase    :						Optional[Any]=True							,							_lowerCAmelCase    :						Dict=True							,							_lowerCAmelCase    :						Tuple=True							,							**_lowerCAmelCase    :						Optional[Any]							,							):
       SCREAMING_SNAKE_CASE_      		=     vocab_size
       SCREAMING_SNAKE_CASE_      		=     block_sizes
       SCREAMING_SNAKE_CASE_      		=     [1] * len(_lowerCAmelCase		) if block_repeats is None else block_repeats
       assert len(_lowerCAmelCase		) == len(
           self.block_repeats		), "`block_sizes` and `block_repeats` should have the same length."
       SCREAMING_SNAKE_CASE_      		=     num_decoder_layers
       SCREAMING_SNAKE_CASE_      		=     d_model
       SCREAMING_SNAKE_CASE_      		=     n_head
       SCREAMING_SNAKE_CASE_      		=     d_head
       SCREAMING_SNAKE_CASE_      		=     d_inner
       SCREAMING_SNAKE_CASE_      		=     hidden_act
       SCREAMING_SNAKE_CASE_      		=     hidden_dropout
       SCREAMING_SNAKE_CASE_      		=     attention_dropout
       SCREAMING_SNAKE_CASE_      		=     activation_dropout
       SCREAMING_SNAKE_CASE_      		=     initializer_range
       SCREAMING_SNAKE_CASE_      		=     initializer_std
       SCREAMING_SNAKE_CASE_      		=     layer_norm_eps
       assert pooling_type in [
           "mean",
           "max",
       ], F"Got {pooling_type} for `pooling_type` but only 'mean' and 'max' are supported."
       SCREAMING_SNAKE_CASE_      		=     pooling_type
       assert attention_type in [
           "relative_shift",
           "factorized",
       ], F"Got {attention_type} for `attention_type` but only 'relative_shift' and 'factorized' are supported."
       SCREAMING_SNAKE_CASE_      		=     attention_type
       SCREAMING_SNAKE_CASE_      		=     separate_cls
       SCREAMING_SNAKE_CASE_      		=     truncate_seq
       SCREAMING_SNAKE_CASE_      		=     pool_q_only

       super().__init__(**_lowerCAmelCase		)



 @property
 def  lowerCAmelCase_    (				self    :						Optional[int]		):
       return sum(self.block_sizes		)



 @num_hidden_layers.setter
 def  lowerCAmelCase_    (				self    :						int							,							_lowerCAmelCase    :						List[Any]		):
       raise NotImplementedError(
           'This model does not support the setting of `num_hidden_layers`. Please set `block_sizes`.'		)



 @property
 def  lowerCAmelCase_    (				self    :						List[Any]		):
       return len(self.block_sizes		)




 @num_blocks.setter
 def  lowerCAmelCase_    (				self    :						Dict							,							_lowerCAmelCase    :						Union[str, Any]		):
       raise NotImplementedError('This model does not support the setting of `num_blocks`. Please set `block_sizes`.'		)